REAL PYTORCH · CPU TRAINING AND AUTOGRAD
Normalize RMS with stable accumulation and autograd
RMS normalization rescales by the root mean square and differs from centering-based layer normalization.
Run this Lab in Pythilo
Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.
No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.
PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.
Pythilo on the App Store →Read lesson: Normalize RMS with stable accumulation and autograd →
Your task
Compute x / sqrt(mean(x**2,last_axis,keepdim=True)+eps) times a learned last-axis weight. Do not subtract the mean. Accumulate in float32 for float16/bfloat16/float32 input and float64 for float64 input, cast the normalized values back to x.dtype, then multiply weight. Require a nonempty last axis, weight shape [D] and finite eps>0. Return a new differentiable tensor without changing inputs.
Starter
import torch
def rms_normalize(x, weight, eps=1e-6):
return NoneInspect the worked answer
import math
import torch
def rms_normalize(x, weight, eps=1e-6):
if x.ndim < 1 or x.shape[-1] == 0 or weight.shape != x.shape[-1:]:
raise ValueError('one learned weight per last-axis feature required')
if not math.isfinite(eps) or eps <= 0:
raise ValueError('positive finite epsilon required')
working = x if x.dtype == torch.float64 else x.float()
mean_square = working.square().mean(dim=-1, keepdim=True)
normalized = working * torch.rsqrt(mean_square + eps)
return normalized.to(x.dtype) * weight