The modern block: RMSNorm, SwiGLU, QK-norm and the anatomy of Llama
Study RMSNorm, gated feed-forward networks, QK normalization, logit soft-capping, and transformer block arrangements with parameter-matched examples and measured ablations.
After this lesson you can
- Derive and implement RMSNorm and its backward pass.
- Implement SwiGLU and compare gated and ordinary feed-forward parameter budgets.
- Analyze attention entropy, QK normalization, and logit soft-capping.
- Compare sequential and parallel residual branches and identify model configurations.
- Interpret controlled ablations of a small modern transformer block.
Before you start
- 18Transformer blockPosition-wise feed-forward networkRotary position embeddingPre-LN versus Post-LNAttention gradient saturationTransformer training recipeGPT architecture
- 15Layer normalizationScale invariance from normalizationGaussian error linear unitReLU variantsLoss spikesOutput logit divergence
One block, several independent decisions
An autoregressive model maintains a fixed-width residual stream, but operations that write to it are not fixed by the word “transformer”. Residual structure, normalization placement, the position-wise network’s function, and the positional mechanism can change independently. We distinguish what changes in the function, what changes in cost, and which claims need an experiment.
In particular, the first LLaMA uses RMSNorm before each sublayer, SwiGLU in the position-wise network, and RoPE in attention. Its architecture is described in section 2.2 of Touvron et al.. This does not imply that every model called Llama shares all its details, or that QK-norm or soft-capping belong to that architecture.
Centering or preserving direction
For vector , define and . RMS normalization (RMSNorm) with learned scale is
Layer normalization first subtracts and divides by component deviation, with its own ; it may also add a bias. The figure uses and . The transparent plane contains zero-mean vectors: LayerNorm lies on it, whereas RMSNorm preserves input direction. Circles indicate a sphere of radius , the zero-epsilon limit; with positive epsilon outputs lie slightly inside. A common shift changes direction and thus the RMS output.
With , , and , RMSNorm satisfies ; for the sign changes. With equality is no longer exact, especially near zero. LayerNorm is invariant to shift even with , because centering removes it. If mean is zero and both operations use the same , scale, and zero bias, they coincide. None of these equalities allows learned parameters to be ignored when loading weights.
Backward also reveals the difference. For scalar loss and , write . Since , the chain rule gives
With , the dot product of the first expression with is zero: the radial derivative vanishes. For it is not exactly zero. RMSNorm avoids mean reduction and centering subtraction, but actual time depends on implementation, shape, and hardware: fewer operations alone do not guarantee a measured speedup. The original work proposes this simplification and evaluates particular tasks, not a universal speed guarantee (Zhang and Sennrich).
There are two useful ways to interpret that derivative. The first term transmits divided by input scale; the second removes part of the component of parallel to . With zero epsilon, an infinitesimal positive radial perturbation does not change normalized direction, hence its dot product with is zero. A perpendicular perturbation can change direction and produce a gradient. Positive epsilon leaves a small radial sensitivity: the stabilizer avoids division by zero but also changes the function near the origin.
Indeed, multiplying the gradient expression by and using gives . The identity vanishes exactly when epsilon is removed, provided is nonzero. At the origin with positive epsilon output is zero and the input derivative is : there is no division by zero, but a very small epsilon can amplify that derivative. Numerical checking must use the same epsilon in forward and backward.
Learned scaling is applied after normalization and can alter direction, although normalization without it preserves input direction. The figure uses unit scale to isolate the geometric effect. In a sequence, one root is calculated per position and the same learned scale is reused; its gradient sums contributions from all positions and batch elements. The displayed vector backward is per position, so that sum is an additional reduction in a training implementation.
A gate changes computation and budget
A gated feed-forward network projects the same input twice and multiplies branches component-wise. Without biases, with matrices of shapes and :
GLU uses , GeGLU uses GELU, and SwiGLU uses . One intermediate output coordinate depends on two projections: one controls the other. The SiLU gate is not restricted to , so it can reverse or amplify the linear branch. Shazeer compares variants under an adjusted parameter budget.
An ordinary bias-free MLP with width has weights. A gated variant has three matrices and weights. To match those terms, take and then round according to implementation constraints. Rounding slightly changes the budget; a fair comparison must record actual parameter count and use the same tokens, data, optimizer, and seeds. Biases add terms of order and .
The chain rule shows what each branch receives. For coordinate and incoming derivative , obtain and . Since , both derivatives depend on the other branch. If , that coordinate’s derivative with respect to vanishes; this does not mean the whole gate matrix stops learning, because other coordinates and examples may contribute.
Matching budgets only matches the dominant FFN matrices. Also count attention, embeddings, normalizations, possible biases, and width-rounding granularity. For , continuous is approximately 10922.67; rounding up to a multiple of 256 gives 11008. An FFN SwiGLU with that width has slightly more weights than the ideal target. Comparing models with different step or token counts introduces another difference that cannot be attributed to the gate.
The figure shows actual synthetic-regression losses, with the same split and 384 weights in each bias-free network: ReLU and GELU use width 24, SwiGLU 16. All use SGD, the same rate, and one initialization seed. This run compares one task and budget; it does not establish which activation is best in a transformer. The next cell reproduces curve data and checks.
import numpy as np
rng = np.random.default_rng(42)
X = rng.normal(size=(64,8))
teacher = rng.normal(0,0.4,(8,8))
Y = np.tanh(X @ teacher)
Xtrain, Xval = X[:48], X[48:]
Ytrain, Yval = Y[:48], Y[48:]
def train_mlp(kind):
rng = np.random.default_rng(11)
hidden = 16 if kind == 'swiglu' else 24
W = rng.normal(0,0.2,(8,hidden))
O = rng.normal(0,0.2,(hidden,8))
U = rng.normal(0,0.2,(8,hidden)) if kind == 'swiglu' else None
history=[]
def forward(x):
a=x@W
if kind == 'relu': h=np.maximum(a,0)
elif kind == 'gelu': h=0.5*a*(1+np.tanh(np.sqrt(2/np.pi)*(a+0.044715*a**3)))
else: h=(a/(1+np.exp(-a)))*(x@U)
return h@O
for step in range(161):
if step%10 == 0: history.append(float(np.mean((forward(Xval)-Yval)**2)))
if step == 160: break
a=Xtrain@W
if kind == 'relu':
h=np.maximum(a,0); derivative=(a>0).astype(float)
elif kind == 'gelu':
t=np.tanh(np.sqrt(2/np.pi)*(a+0.044715*a**3))
h=0.5*a*(1+t)
derivative=0.5*(1+t)+0.5*a*(1-t*t)*np.sqrt(2/np.pi)*(1+3*0.044715*a*a)
else:
sigmoid=1/(1+np.exp(-a)); linear=Xtrain@U
gate=a*sigmoid; h=gate*linear
derivative=(sigmoid+a*sigmoid*(1-sigmoid))*linear
error=(h@O-Ytrain)*2/Ytrain.size
dO=h.T@error; [email protected]
dW=Xtrain.T@(dh*derivative)
dU=Xtrain.T@(dh*gate) if U is not None else None
W-=0.1*dW; O-=0.1*dO
if U is not None: U-=0.1*dU
return history, W.size+O.size+(0 if U is None else U.size)
curves={kind:train_mlp(kind) for kind in ('relu','gelu','swiglu')}
assert all(n==384 for _,n in curves.values())
assert all(np.isfinite(values).all() for values,_ in curves.values())
for kind,(values,n) in curves.items():
print(kind,'parámetros:',n,'pérdida inicial/final:',values[0],values[-1])Entropy, norms, and logit bounds
Attention computes logits and probabilities over allowed positions. Attention entropy is . If nonidentical logits are multiplied by a growing inverse temperature, the distribution concentrates on maxima; with a unique maximum, tends to zero. This is a row property, not proof that every low-entropy attention is pathological. Zhai et al. analyze the phenomenon during training and its conditions.
With tied maxima, limiting mass is shared and entropy tends to , not necessarily zero. The maximum is computed only over allowed positions; a fully masked row needs a separate convention because it does not define an ordinary softmax distribution. Reduced entropy is thus a signal to investigate context and gradients, not an automatic failure label.
Proof
With , . The derivative of is , while the derivative of that mean is . The first terms cancel, leaving . The claim assumes fixed base scores: during training directions can also change.
∎Query and key normalization limits the influence of their norms before the product. In Henry et al., vectors are normalized by their norm and a learned scale replaces . By Cauchy-Schwarz, the unit-vector product lies between and ; a learned scale can still grow. Variants use RMSNorm or LayerNorm, and their order relative to RoPE must match the checkpoint. Normalization with different coordinate scales generally does not commute with rotation.
The bound applies to the specific Euclidean-norm version: with fixed scale , logits lie between and . If is learned, that bound changes during training. Replacing Euclidean norm with RMSNorm and learned component gains introduces another transformation and does not permit the same bound without bounding those gains. If a query or key is zero, normalization needs an epsilon convention; there is no unit direction to recover from a zero vector.
RoPE is orthogonal in each component pair and preserves Euclidean norm. Thus scalar L2 normalization of a nonzero vector commutes with rotation in exact arithmetic. A diagonal scale with different gains within a pair need not commute: rotating then scaling mixes coordinates in a different order from scaling then rotating. This matters when transferring weights between implementations, even if both are informally described as “QK-norm plus RoPE”.
Logit soft-capping transforms each finite logit to for before softmax: the result lies between and . The causal mask must still exclude positions, for example by adding after that transformation: applying tanh to would put the position at and no longer exclude it. Gemma 2 describes soft-capping in its architecture. This modifies logits, unlike z-loss on the output partition; they are distinct interventions and not equivalent.
Branch ordering
In a sequential pre-norm block, and . A parallel block computes both branches from the same input and sums . The second branch no longer sees attention output within that block, so this is not merely an algebraic rearrangement of the sequential form. It can save synchronization in a specific implementation; cost and quality must be measured. PaLM describes a parallel variant (Chowdhery et al.). Designs with additional normalizations or substitutions such as DyT also exist and should not be confused with RMSNorm (Zhu et al.).
The dependency also appears in backward. In the sequential form, the gradient reaching attention includes the path through the FFN because it consumes . In the parallel form, both branches receive gradient from the sum and propagate it separately to . One cannot exchange the forms and expect identical logits with identical weights. Whether branches share normalization is another variant that belongs in configuration and loader.
The original LLaMA block combines pre-RMSNorm, causal attention with RoPE, and SwiGLU FFN in sequential branches. KV head count, embedding tying, and biases depend on configuration and version. Removing biases reduces linear-order parameters relative to quadratic matrix terms, but does not by itself prove expressive equivalence or better stability.
GPT-2 already uses pre-LayerNorm: its block code normalizes before attention and MLP and adds each result to the residual. Llama 2 code shows the same sequential order with RMSNorm and SwiGLU. Changing GPT-2 to Llama does not turn post-norm into pre-norm; the order already matches in those examples.
Do not treat that list as a template for every family. Gemma 2 describes approximate GeGLU, RoPE, and RMSNorm both at input and output of each sublayer; it applies soft-capping with in attention and at final output. The Llama 2 report describes pre-RMSNorm, SwiGLU, and RoPE; its table distinguishes variants using GQA from those that do not. These are specific model decisions, not interchangeable synonyms.
Checking from scratch
This cell checks RMSNorm backward with double-precision central differences. It uses zero-based Python indices; the formula above applies to one vector and independently to each position.
import numpy as np
def rms(x, g, eps=1e-5):
r = np.sqrt(np.mean(x*x) + eps)
return g*x/r
def rms_backward(x, g, upstream, eps=1e-5):
r = np.sqrt(np.mean(x*x) + eps)
v = upstream*g
dx = v/r - x*np.dot(x, v)/(x.size*r**3)
dg = upstream*x/r
return dx, dg
x = np.array([0.4, -1.3, 2.0], dtype=float)
g = np.array([0.8, 1.2, 0.5])
upstream = np.array([0.2, -0.7, 1.1])
dx, dg = rms_backward(x, g, upstream)
h = 1e-6
eye = np.eye(x.size)
numeric = np.array([(np.dot(upstream, rms(x+h*e, g)) - np.dot(upstream, rms(x-h*e, g)))/(2*h) for e in eye])
numeric_g = np.array([(np.dot(upstream, rms(x, g+h*e)) - np.dot(upstream, rms(x, g-h*e)))/(2*h) for e in eye])
print('error máximo dx:', np.max(np.abs(dx-numeric)))
print('error máximo dg:', np.max(np.abs(dg-numeric_g)))
assert np.allclose(dx, numeric, atol=1e-8)
assert np.allclose(dg, numeric_g, atol=1e-8)The next cell checks the gate and its derivatives for scalars, not a training curve. For and , these derivatives propagate through the matrices.
import numpy as np
def gate(a, b):
return a/(1+np.exp(-a))*b
a, b = 0.7, -1.2
s = 1/(1+np.exp(-a))
da = b*(s+a*s*(1-s))
db = a*s
h = 1e-6
assert np.allclose(da, (gate(a+h,b)-gate(a-h,b))/(2*h))
assert np.allclose(db, (gate(a,b+h)-gate(a,b-h))/(2*h))
print('derivadas:', da, db)
print('anchura redondeada para d=4096:', int(np.ceil((8*4096/3)/256)*256))Now propagate through all three matrices of a SwiGLU. The test checks derivatives with respect to input and each matrix by central differences. Matrices are small enough to run in the browser; this is not the complete GPT.
import numpy as np
def swiglu(x, wg, wu, wo):
a, b = wg @ x, wu @ x
sig = 1/(1+np.exp(-a))
return wo @ (a*sig*b)
def swiglu_backward(x, wg, wu, wo, u):
a, b = wg @ x, wu @ x
sig = 1/(1+np.exp(-a))
gate = a*sig
hidden = gate*b
dh = wo.T @ u
da = dh*b*(sig+a*sig*(1-sig))
db = dh*gate
dx = wg.T @ da + wu.T @ db
return dx, np.outer(da,x), np.outer(db,x), np.outer(u,hidden)
rng = np.random.default_rng(5)
args = [rng.normal(size=(3,)), rng.normal(size=(4,3)),
rng.normal(size=(4,3)), rng.normal(size=(3,4))]
u = rng.normal(size=(3,))
analytic = swiglu_backward(*args, u)
h = 1e-6
errors = []
for k, original in enumerate(args):
numerical = np.empty_like(original)
for ix in np.ndindex(original.shape):
plus = [z.copy() for z in args]
minus = [z.copy() for z in args]
plus[k][ix] += h
minus[k][ix] -= h
numerical[ix] = (u @ swiglu(*plus) - u @ swiglu(*minus))/(2*h)
errors.append(np.max(np.abs(analytic[k]-numerical)))
print('errores máximos x, Wg, Wu, Wo:', errors)
assert max(errors) < 1e-8In the browser you can integrate the same operations into a tiny GPT with the lesson 11 tensor contract. Synthetic weights are seeded, learned positions and biases are removed, and RMSNorm, RoPE, and SwiGLU with tied output are used. The test compares forward and backward at two coordinates per tensor; it does not load the trained checkpoint. Integration is then repeated with the actual file locally.
import numpy as np
rng=np.random.default_rng(13)
cfg={'vocab':11,'context':6,'width':8,'layers':2,'heads':2}
d,h,L=cfg['width'],cfg['heads'],cfg['layers']; dh=d//h; ff=24
p={'token':rng.normal(0,.02,(cfg['vocab'],d)),'final.g':np.ones(d)}
for layer in range(L):
pre=f'block.{layer}.'
p[pre+'n1.g']=np.ones(d); p[pre+'n2.g']=np.ones(d)
for name in ('q','k','v','o'): p[pre+name+'.w']=rng.normal(0,.02,(d,d))
gated=[(rng.normal(0,.02,(d,ff)),rng.normal(0,.02,(d,ff)),rng.normal(0,.02,(ff,d))) for _ in range(L)]
def rms_model(x,g,eps=1e-5):
return x/np.sqrt(np.mean(x*x,axis=-1,keepdims=True)+eps)*g
def rotate(x):
n=x.shape[0]
theta=np.arange(n)[:,None,None] / (10000**(np.arange(0,dh,2)[None,None,:]/dh))
even,odd=x[...,0::2],x[...,1::2]
out=np.empty_like(x)
out[...,0::2]=even*np.cos(theta)-odd*np.sin(theta)
out[...,1::2]=even*np.sin(theta)+odd*np.cos(theta)
return out
def modern_forward(ids, qk_norm=False):
n=len(ids)
if not 1<=n<=cfg['context']: raise ValueError('longitud fuera del contexto')
x=p['token'][ids].copy()
for layer in range(L):
pre=f'block.{layer}.'
a=rms_model(x,p[pre+'n1.g'])
q,k,v=[(a @ p[pre+name+'.w']).reshape(n,h,dh) for name in ('q','k','v')]
if qk_norm:
q=rms_model(q,1.0); k=rms_model(k,1.0)
q,k=rotate(q),rotate(k)
score=np.einsum('thd,shd->hts',q,k)/np.sqrt(dh)
score=np.where(np.arange(n)[None,None,:]<=np.arange(n)[None,:,None],score,-np.inf)
prob=np.exp(score-score.max(axis=-1,keepdims=True)); prob/=prob.sum(axis=-1,keepdims=True)
joined=np.einsum('hts,shd->thd',prob,v).reshape(n,d)
u=x+joined @ p[pre+'o.w']
b=rms_model(u,p[pre+'n2.g'])
wg,wu,wo=gated[layer]
gate=b @ wg
x=u+(gate/(1+np.exp(-gate)) * (b @ wu)) @ wo
return rms_model(x,p['final.g']) @ p['token'].T
ids=np.arange(4)%cfg['vocab']
out=modern_forward(ids)
params={'token':p['token'].copy(),'final.g':p['final.g'].copy()}
for layer in range(L):
pre=f'block.{layer}.'
for name in ('n1.g','n2.g','q.w','k.w','v.w','o.w'):
params[pre+name]=p[pre+name].copy()
for name,w in zip(('gate.w','up.w','down.w'),gated[layer]):
params[pre+name]=w.copy()
def rms_fwd(x,g):
r=np.sqrt(np.mean(x*x,axis=-1,keepdims=True)+1e-5)
return x/r*g,(x,r,g)
def rms_back(dy,cache):
x,r,g=cache
v=dy*g
return v/r-x*np.mean(v*x,axis=-1,keepdims=True)/(r**3), np.sum(dy*x/r,axis=0)
def rope(x,inverse=False):
theta=np.arange(x.shape[0])[:,None,None]/(10000**(np.arange(0,dh,2)[None,None,:]/dh))
if inverse: theta=-theta
a,b=x[...,0::2],x[...,1::2]
out=np.empty_like(x)
out[...,0::2]=a*np.cos(theta)-b*np.sin(theta)
out[...,1::2]=a*np.sin(theta)+b*np.cos(theta)
return out
def modern_loss_and_grads(ids,targets):
n=len(ids)
x=params['token'][ids].copy()
cache=[]
for layer in range(L):
pre=f'block.{layer}.'
a,c1=rms_fwd(x,params[pre+'n1.g'])
q,k,v=[(a @ params[pre+name+'.w']).reshape(n,h,dh) for name in ('q','k','v')]
qr,kr=rope(q),rope(k)
score=np.einsum('thd,shd->hts',qr,kr)/np.sqrt(dh)
score=np.where(np.arange(n)[None,None,:]<=np.arange(n)[None,:,None],score,-np.inf)
prob=np.exp(score-score.max(axis=-1,keepdims=True)); prob/=prob.sum(axis=-1,keepdims=True)
joined=np.einsum('hts,shd->thd',prob,v).reshape(n,d)
residual=x+joined @ params[pre+'o.w']
b,c2=rms_fwd(residual,params[pre+'n2.g'])
gate=b @ params[pre+'gate.w']; up=b @ params[pre+'up.w']
sig=1/(1+np.exp(-gate)); hidden=gate*sig*up
x=residual+hidden @ params[pre+'down.w']
cache.append((a,c1,qr,kr,v,prob,joined,b,c2,gate,up,sig,hidden))
last,cf=rms_fwd(x,params['final.g'])
logits=last @ params['token'].T
shifted=logits-logits.max(axis=-1,keepdims=True)
ex=np.exp(shifted); probs=ex/ex.sum(axis=-1,keepdims=True)
loss=np.mean(np.log(ex.sum(axis=-1))-shifted[np.arange(n),targets])
dz=probs.copy(); dz[np.arange(n),targets]-=1; dz/=n
grads={key:np.zeros_like(value) for key,value in params.items()}
grads['token']+=dz.T @ last
dx,grads['final.g']=rms_back(dz @ params['token'],cf)
for layer in range(L-1,-1,-1):
pre=f'block.{layer}.'
a,c1,qr,kr,v,prob,joined,b,c2,gate,up,sig,hidden=cache[layer]
grads[pre+'down.w']=hidden.T @ dx
dhidden=dx @ params[pre+'down.w'].T
dgate=dhidden*up*(sig+gate*sig*(1-sig))
dup=dhidden*(gate*sig)
grads[pre+'gate.w']=b.T @ dgate
grads[pre+'up.w']=b.T @ dup
db=dgate @ params[pre+'gate.w'].T + dup @ params[pre+'up.w'].T
dn2,grads[pre+'n2.g']=rms_back(db,c2)
dr=dx+dn2
grads[pre+'o.w']=joined.T @ dr
dj=(dr @ params[pre+'o.w'].T).reshape(n,h,dh)
dp=np.einsum('thd,shd->hts',dj,v)
dv=np.einsum('hts,thd->shd',prob,dj)
ds=prob*(dp-np.sum(dp*prob,axis=-1,keepdims=True))
dqr=np.einsum('hts,shd->thd',ds,kr)/np.sqrt(dh)
dkr=np.einsum('hts,thd->shd',ds,qr)/np.sqrt(dh)
dq,dk=rope(dqr,True),rope(dkr,True)
dn1=np.zeros_like(a)
for name,part in (('q',dq),('k',dk),('v',dv)):
flat=part.reshape(n,d)
grads[pre+name+'.w']=a.T @ flat
dn1+=flat @ params[pre+name+'.w'].T
residual_grad,grads[pre+'n1.g']=rms_back(dn1,c1)
dx=dr+residual_grad
np.add.at(grads['token'],ids,dx)
return float(loss),grads
targets=np.roll(ids,-1)
loss,grads=modern_loss_and_grads(ids,targets)
z=out-out.max(axis=-1,keepdims=True)
expected=np.mean(np.log(np.exp(z).sum(axis=-1))-z[np.arange(len(ids)),targets])
assert np.allclose(loss,expected)
errors={}
for name,tensor in params.items():
for ix in [(0,)*tensor.ndim, tuple(s-1 for s in tensor.shape)]:
old=tensor[ix]; step=1e-5
tensor[ix]=old+step; plus=modern_loss_and_grads(ids,targets)[0]
tensor[ix]=old-step; minus=modern_loss_and_grads(ids,targets)[0]
tensor[ix]=old
errors[(name,ix)]=abs((plus-minus)/(2*step)-grads[name][ix])
print('Pérdida inicial:',loss,'coordenadas verificadas:',len(errors),'error absoluto máximo:',max(errors.values()))
assert max(errors.values())<1e-5
The next local cell uses gpt-numpy.npz exported in lesson 11. Place it in the lab directory or set ORYON_GPT_NUMPY to its path. It retains the file’s tables and Q, K, V, and O matrices, uses its normalization scales, and replaces the rest with a demonstration block using RMSNorm, RoPE, and SwiGLU. The new MLP is seeded and biases are omitted. It therefore does not preserve the checkpoint’s function or quality; this control checks shapes, causality, and finiteness before training.
import json, os
from pathlib import Path
import numpy as np
path=Path(os.environ.get('ORYON_GPT_NUMPY','gpt-numpy.npz'))
if not path.is_file():
raise FileNotFoundError(f'Descarga gpt-numpy.npz de m18-l11 e indica su ruta: {path}')
with np.load(path,allow_pickle=False) as archive:
cfg=json.loads(str(archive['config']))
p={key:archive[key].copy() for key in archive.files if key not in ('config','characters')}
d,h,L=cfg['width'],cfg['heads'],cfg['layers']
dh=d//h
assert d%h==0 and dh%2==0, 'RoPE de pares requiere dimensión por cabeza par'
ff=int(np.ceil((8*d/3)/32)*32)
rng=np.random.default_rng(13)
gated=[(rng.normal(0,.02,(d,ff)),rng.normal(0,.02,(d,ff)),rng.normal(0,.02,(ff,d))) for _ in range(L)]
def rms_model(x,g,eps=1e-5):
return x/np.sqrt(np.mean(x*x,axis=-1,keepdims=True)+eps)*g
def rotate(x):
n=x.shape[0]
theta=np.arange(n)[:,None,None] / (10000**(np.arange(0,dh,2)[None,None,:]/dh))
even,odd=x[...,0::2],x[...,1::2]
out=np.empty_like(x)
out[...,0::2]=even*np.cos(theta)-odd*np.sin(theta)
out[...,1::2]=even*np.sin(theta)+odd*np.cos(theta)
return out
def modern_forward(ids, qk_norm=False):
n=len(ids)
if not 1<=n<=cfg['context']: raise ValueError('longitud fuera del contexto')
x=p['token'][ids].copy()
for layer in range(L):
pre=f'block.{layer}.'
a=rms_model(x,p[pre+'n1.g'])
q,k,v=[(a @ p[pre+name+'.w']).reshape(n,h,dh) for name in ('q','k','v')]
if qk_norm:
q=rms_model(q,1.0); k=rms_model(k,1.0)
q,k=rotate(q),rotate(k)
score=np.einsum('thd,shd->hts',q,k)/np.sqrt(dh)
score=np.where(np.arange(n)[None,None,:]<=np.arange(n)[None,:,None],score,-np.inf)
prob=np.exp(score-score.max(axis=-1,keepdims=True)); prob/=prob.sum(axis=-1,keepdims=True)
joined=np.einsum('hts,shd->thd',prob,v).reshape(n,d)
u=x+joined @ p[pre+'o.w']
b=rms_model(u,p[pre+'n2.g'])
wg,wu,wo=gated[layer]
gate=b @ wg
x=u+(gate/(1+np.exp(-gate)) * (b @ wu)) @ wo
return rms_model(x,p['final.g']) @ p['token'].T
ids=np.arange(min(5,cfg['context']))%cfg['vocab']
out=modern_forward(ids)
changed=ids.copy(); changed[-1]=(changed[-1]+1)%cfg['vocab']
assert np.isfinite(out).all() and np.allclose(out[:-1],modern_forward(changed)[:-1])
out_qk=modern_forward(ids,qk_norm=True)
assert np.isfinite(out_qk).all() and np.allclose(out_qk[:-1],modern_forward(changed,qk_norm=True)[:-1])
print('configuración:',cfg,'ancho SwiGLU:',ff,'forma de logits:',out.shape)
print('causalidad y finitud comprobadas; pesos de puerta nuevos sin entrenar')npm run lab and open the connection link.The preceding forward shows shape, but training requires propagation through both residual branches and summation of tied-embedding contributions. The cell implements backward for the modern block without QK-norm: it differentiates RoPE using inverse rotation, applies RMSNorm and SwiGLU backward, and checks each tensor with central differences. It starts from the file’s attention matrices and newly initialized gates; it does not claim the model is trained.
params={'token':p['token'].copy(),'final.g':p['final.g'].copy()}
for layer in range(L):
pre=f'block.{layer}.'
for name in ('n1.g','n2.g','q.w','k.w','v.w','o.w'):
params[pre+name]=p[pre+name].copy()
for name,w in zip(('gate.w','up.w','down.w'),gated[layer]):
params[pre+name]=w.copy()
def rms_fwd(x,g):
r=np.sqrt(np.mean(x*x,axis=-1,keepdims=True)+1e-5)
return x/r*g,(x,r,g)
def rms_back(dy,cache):
x,r,g=cache
v=dy*g
return v/r-x*np.mean(v*x,axis=-1,keepdims=True)/(r**3), np.sum(dy*x/r,axis=0)
def rope(x,inverse=False):
theta=np.arange(x.shape[0])[:,None,None]/(10000**(np.arange(0,dh,2)[None,None,:]/dh))
if inverse: theta=-theta
a,b=x[...,0::2],x[...,1::2]
out=np.empty_like(x)
out[...,0::2]=a*np.cos(theta)-b*np.sin(theta)
out[...,1::2]=a*np.sin(theta)+b*np.cos(theta)
return out
def modern_loss_and_grads(ids,targets):
n=len(ids)
x=params['token'][ids].copy()
cache=[]
for layer in range(L):
pre=f'block.{layer}.'
a,c1=rms_fwd(x,params[pre+'n1.g'])
q,k,v=[(a @ params[pre+name+'.w']).reshape(n,h,dh) for name in ('q','k','v')]
qr,kr=rope(q),rope(k)
score=np.einsum('thd,shd->hts',qr,kr)/np.sqrt(dh)
score=np.where(np.arange(n)[None,None,:]<=np.arange(n)[None,:,None],score,-np.inf)
prob=np.exp(score-score.max(axis=-1,keepdims=True)); prob/=prob.sum(axis=-1,keepdims=True)
joined=np.einsum('hts,shd->thd',prob,v).reshape(n,d)
residual=x+joined @ params[pre+'o.w']
b,c2=rms_fwd(residual,params[pre+'n2.g'])
gate=b @ params[pre+'gate.w']; up=b @ params[pre+'up.w']
sig=1/(1+np.exp(-gate)); hidden=gate*sig*up
x=residual+hidden @ params[pre+'down.w']
cache.append((a,c1,qr,kr,v,prob,joined,b,c2,gate,up,sig,hidden))
last,cf=rms_fwd(x,params['final.g'])
logits=last @ params['token'].T
shifted=logits-logits.max(axis=-1,keepdims=True)
ex=np.exp(shifted); probs=ex/ex.sum(axis=-1,keepdims=True)
loss=np.mean(np.log(ex.sum(axis=-1))-shifted[np.arange(n),targets])
dz=probs.copy(); dz[np.arange(n),targets]-=1; dz/=n
grads={key:np.zeros_like(value) for key,value in params.items()}
grads['token']+=dz.T @ last
dx,grads['final.g']=rms_back(dz @ params['token'],cf)
for layer in range(L-1,-1,-1):
pre=f'block.{layer}.'
a,c1,qr,kr,v,prob,joined,b,c2,gate,up,sig,hidden=cache[layer]
grads[pre+'down.w']=hidden.T @ dx
dhidden=dx @ params[pre+'down.w'].T
dgate=dhidden*up*(sig+gate*sig*(1-sig))
dup=dhidden*(gate*sig)
grads[pre+'gate.w']=b.T @ dgate
grads[pre+'up.w']=b.T @ dup
db=dgate @ params[pre+'gate.w'].T + dup @ params[pre+'up.w'].T
dn2,grads[pre+'n2.g']=rms_back(db,c2)
dr=dx+dn2
grads[pre+'o.w']=joined.T @ dr
dj=(dr @ params[pre+'o.w'].T).reshape(n,h,dh)
dp=np.einsum('thd,shd->hts',dj,v)
dv=np.einsum('hts,thd->shd',prob,dj)
ds=prob*(dp-np.sum(dp*prob,axis=-1,keepdims=True))
dqr=np.einsum('hts,shd->thd',ds,kr)/np.sqrt(dh)
dkr=np.einsum('hts,thd->shd',ds,qr)/np.sqrt(dh)
dq,dk=rope(dqr,True),rope(dkr,True)
dn1=np.zeros_like(a)
for name,part in (('q',dq),('k',dk),('v',dv)):
flat=part.reshape(n,d)
grads[pre+name+'.w']=a.T @ flat
dn1+=flat @ params[pre+name+'.w'].T
residual_grad,grads[pre+'n1.g']=rms_back(dn1,c1)
dx=dr+residual_grad
np.add.at(grads['token'],ids,dx)
return float(loss),grads
targets=np.roll(ids,-1)
loss,grads=modern_loss_and_grads(ids,targets)
z=out-out.max(axis=-1,keepdims=True)
expected=np.mean(np.log(np.exp(z).sum(axis=-1))-z[np.arange(len(ids)),targets])
assert np.allclose(loss,expected)
errors={}
for name,tensor in params.items():
for ix in [(0,)*tensor.ndim, tuple(s-1 for s in tensor.shape)]:
old=tensor[ix]; step=1e-5
tensor[ix]=old+step; plus=modern_loss_and_grads(ids,targets)[0]
tensor[ix]=old-step; minus=modern_loss_and_grads(ids,targets)[0]
tensor[ix]=old
errors[(name,ix)]=abs((plus-minus)/(2*step)-grads[name][ix])
print('Pérdida inicial:',loss,'coordenadas verificadas:',len(errors),'error absoluto máximo:',max(errors.values()))
assert max(errors.values())<1e-5npm run lab and open the connection link.Mini Llama and a controlled ablation
With the real small checkpoint from lesson 12, this implementation reuses embeddings and attention matrices, but removes biases, replaces learned positions with RoPE and normalizations with RMSNorm, and initializes a new SwiGLU FFN. It therefore does not preserve checkpoint function or quality. The comparison enables or disables L2 normalization of Q and K while keeping architecture, parameter count, data, steps, and batches equal for each seed and rate. Three rates and three seeds do not guarantee showing greater tolerance on this small corpus; results are obtained by running, not anticipated.
Save the “PyTorch GPT and loaders” cell from lesson 12 as gpt_pytorch.py, generate gpt-pytorch-small.pt, and save lesson 11’s text as corpus.txt, for example with Path('corpus.txt').write_text(corpus, encoding='utf-8'). Environment variables allow paths to be chosen. Validation uses a fixed held-out window distinct from training batches. Loss, maximum absolute valid logit, and mean attention entropy are shown at the end. The run saves mini-llama.pt for the no-QK-norm variant, seed 11 and rate 0.001; it contains configuration, vocabulary, and weights, not optimizer states. It also saves attention-trace.json with trajectories for seed 11 and rate 0.01. This is a short test, not a large-model result.
import os, math, json
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F
assert torch.cuda.is_available(), 'el laboratorio requiere CUDA'
scope = {}
exec(Path(os.environ.get('ORYON_GPT_TORCH_CODE','gpt_pytorch.py')).read_text(encoding='utf-8'),scope)
path = Path(os.environ.get('ORYON_GPT_TORCH','gpt-pytorch-small.pt'))
corpus = Path(os.environ.get('ORYON_CORPUS','corpus.txt')).read_text(encoding='utf-8')
base, chars = scope['load_checkpoint'](path, map_location='cpu')
stoi = {c:i for i,c in enumerate(chars)}
assert all(c in stoi for c in corpus) and len(corpus)>4000
ids = torch.tensor([stoi[c] for c in corpus],dtype=torch.long)
split = int(len(ids)*0.8); train, valid = ids[:split],ids[split:]
class RMS(nn.Module):
def __init__(self, weight):
super().__init__(); self.weight = nn.Parameter(weight.detach().float().clone())
def forward(self,x):
return x*torch.rsqrt(x.float().square().mean(-1,keepdim=True)+1e-5)*self.weight
def rotate(z):
d = z.shape[-1]
assert d % 2 == 0
freq = torch.exp(-math.log(10000)*torch.arange(0,d,2,device=z.device,dtype=z.dtype)/d)
angles = torch.arange(z.shape[-2],device=z.device,dtype=z.dtype)[:,None]*freq
c,s = angles.cos(),angles.sin()
even,odd = z[...,0::2],z[...,1::2]
return torch.stack((even*c-odd*s,even*s+odd*c),dim=-1).flatten(-2)
class ModernAttention(nn.Module):
def __init__(self, original, width, heads, qknorm):
super().__init__(); self.heads=heads; self.qknorm=qknorm; self.use_rope=True; self.cap=None
for name in ('q','k','v','o'):
layer = nn.Linear(width,width,bias=False)
layer.weight.data.copy_(getattr(original,name).weight.detach().float())
setattr(self,name,layer)
def forward(self,x):
b,t,d=x.shape; dh=d//self.heads
def proj(layer): return layer(x).view(b,t,self.heads,dh).transpose(1,2)
q,k,v=proj(self.q),proj(self.k),proj(self.v)
if self.use_rope: q,k=rotate(q),rotate(k)
if self.qknorm:
q=F.normalize(q,dim=-1); k=F.normalize(k,dim=-1)
[email protected](-2,-1)*math.sqrt(dh)
else:
[email protected](-2,-1)/math.sqrt(dh)
if self.cap is not None: scores=self.cap*torch.tanh(scores/self.cap)
mask=torch.ones((t,t),device=x.device,dtype=torch.bool).tril()
scores=scores.masked_fill(~mask,float('-inf'))
probs=scores.softmax(-1)
self.max_logit=scores.masked_select(mask).abs().max().detach()
self.entropy=-(probs*probs.clamp_min(1e-30).log()).sum(-1).mean().detach()
out=(probs@v).transpose(1,2).contiguous().view(b,t,d)
return self.o(out)
class ModernBlock(nn.Module):
def __init__(self, old, width, heads, qknorm):
super().__init__(); self.n1=RMS(old.n1.weight); self.n2=RMS(old.n2.weight)
self.attn=ModernAttention(old.attn,width,heads,qknorm)
hidden=math.ceil((8*width/3)/8)*8
self.gate=nn.Linear(width,hidden,bias=False); self.up=nn.Linear(width,hidden,bias=False)
self.down=nn.Linear(hidden,width,bias=False)
for layer in (self.gate,self.up,self.down): nn.init.normal_(layer.weight,std=0.02)
def forward(self,x):
x=x+self.attn(self.n1(x)); z=self.n2(x)
return x+self.down(F.silu(self.gate(z))*self.up(z))
class MiniLlama(nn.Module):
def __init__(self, old, qknorm):
super().__init__(); c=old.config
self.token=nn.Embedding(c['vocab'],c['width'])
self.token.weight.data.copy_(old.token.weight.detach().float())
self.blocks=nn.ModuleList([ModernBlock(b,c['width'],c['heads'],qknorm) for b in old.blocks])
self.final=RMS(old.final.weight)
self.register_buffer('position_table',None)
def logits(self,x):
h=self.token(x)
if self.position_table is not None: h=h+self.position_table[:x.shape[1]][None,:,:]
for block in self.blocks: h=block(h)
return F.linear(self.final(h),self.token.weight)
def forward(self,x,y):
logits=self.logits(x)
return F.cross_entropy(logits.reshape(-1,logits.shape[-1]),y.reshape(-1))
length=base.config['context']; batch_size=4
steps=int(os.environ.get('ORYON_STEPS','12')); assert steps>0 and len(valid)>length+1
vx=valid[:length].unsqueeze(0).cuda(); vy=valid[1:length+1].unsqueeze(0).cuda()
print('GPU:',torch.cuda.get_device_name(),'pasos por ejecución:',steps)
print('semilla, lr, QK, parámetros, pasos, pérdida inicial/final, validación, máximos, entropías')
traces={}
for seed in (11,22,33):
for lr in (0.0001,0.001,0.01):
for normalized in (False,True):
torch.manual_seed(seed)
net=MiniLlama(base,normalized).cuda()
if seed == 11 and lr == 0.0001:
changed=vx.clone(); changed[0,-1]=(changed[0,-1]+1)%len(chars)
with torch.no_grad():
before=net.logits(vx); after=net.logits(changed)
assert torch.allclose(before[:,:-1],after[:,:-1],atol=1e-6,rtol=1e-6)
print('causalidad comprobada, QK-norm:',normalized)
optimizer=torch.optim.AdamW(net.parameters(),lr=lr)
gen=torch.Generator().manual_seed(seed)
losses=[]
for _ in range(steps):
starts=torch.randint(len(train)-length,(batch_size,),generator=gen).tolist()
xx=torch.stack([train[i:i+length] for i in starts]).cuda()
yy=torch.stack([train[i+1:i+length+1] for i in starts]).cuda()
optimizer.zero_grad(set_to_none=True)
loss=net(xx,yy); losses.append(float(loss.detach()))
if seed==11 and lr==0.01:
key='con' if normalized else 'sin'
traces.setdefault(key,[]).append({'loss':losses[-1],
'maxima':[float(b.attn.max_logit) for b in net.blocks],
'entropias':[float(b.attn.entropy) for b in net.blocks]})
if not torch.isfinite(loss): break
loss.backward(); optimizer.step()
with torch.no_grad():
validation=float(net(vx,vy))
maxima=[float(b.attn.max_logit) for b in net.blocks]
entropies=[float(b.attn.entropy) for b in net.blocks]
print(seed,lr,int(normalized),sum(p.numel() for p in net.parameters()),len(losses),
round(losses[0],4),round(losses[-1],4),round(validation,4),
[round(x,3) for x in maxima],[round(x,3) for x in entropies])
if seed==11 and lr==0.001 and not normalized:
torch.save({'config':base.config,'characters':chars,'qknorm':False,
'state_dict':net.state_dict()},'mini-llama.pt')
state=torch.load('mini-llama.pt',map_location='cpu',weights_only=True)
restored=MiniLlama(base,state['qknorm']).cuda()
restored.load_state_dict(state['state_dict'],strict=True)
with torch.no_grad():
assert torch.allclose(net.logits(vx),restored.logits(vx),atol=1e-6,rtol=1e-6)
print('mini-llama.pt guardado y recargado')
del restored
del net,optimizer
Path('attention-trace.json').write_text(json.dumps(traces,indent=2),encoding='utf-8')
print('attention-trace.json guardado')npm run lab and open the connection link.Maximum and entropy are computed on the validation window after the last step. Masked positions are excluded and entropy is averaged over rows, heads, and batch. A decrease can be useful or signal saturation; compare with losses, layers, and seeds. This lab isolates QK-norm; it does not separately prove the effect of RMSNorm, RoPE, SwiGLU, or bias removal.
The figure summarizes one run of that lab on RTX 3060 with PyTorch 2.11.0+cu128, lesson 11’s 12000-character fragment, and 12 steps per seed. The lesson 12 small checkpoint used has SHA-256 aecf637725ca7470f3bcbea3651be4c7e14d76a974aa84f5b206ddb4ba6004a6; your file may differ. It shows only rate 0.01 and a fixed validation window. With L2 normalization and fixed scale , Cauchy-Schwarz bounds each logit by that scale, here 4; without normalization the bound does not apply. Norm control does not by itself demonstrate better loss or greater learning-rate tolerance in general.
This trace records attention values in training batches for seed 11 at rate 0.01 before each update. It comes from the same twelve-step run and identified checkpoint above; each mode uses the same batches. The previous figure instead measures a fixed validation window after fitting. Moving values do not by themselves prove failure or quality improvement; batches also change.
In a 100-step repeat on the same RTX 3060 at rate 0.01, first-block absolute maxima on the validation window were 58.671, 61.838, and 93.697 without QK-norm for seeds 11, 22, and 33; with QK-norm they were 3.822, 3.826, and 3.909, within bound 4. Validation losses did not favor the same mode for all three seeds. Repeat the sweep with ORYON_STEPS=100. The result shows magnitude control in this case, not universal tolerance or a substitute for longer stability evaluation.
The next cell continues in the same environment and tests one change at a time against the modern block without QK-norm: bias-free LayerNorm, fixed absolute positions from the checkpoint instead of RoPE, ungated GELU, projection biases, or attention soft-capping with . It compares variants at rate 0.01 and identical batches, and records validation entropy and maximum logit. ReLU and GELU were already compared in the preceding regression. GELU width exactly matches this model’s SwiGLU FFN weights, but its matrices are reinitialized. Absolute positions are frozen to avoid adding trainable parameters. The bias case adds parameters and the code counts them; it is therefore not strictly capacity-matched. These limits matter when interpreting loss differences.
class PlainBlock(nn.Module):
def __init__(self, modern):
super().__init__()
self.n1,self.n2,self.attn=modern.n1,modern.n2,modern.attn
width=modern.down.out_features; hidden=modern.gate.out_features*3//2
self.fc=nn.Linear(width,hidden,bias=False); self.proj=nn.Linear(hidden,width,bias=False)
nn.init.normal_(self.fc.weight,std=0.02); nn.init.normal_(self.proj.weight,std=0.02)
def forward(self,x):
x=x+self.attn(self.n1(x))
return x+self.proj(F.gelu(self.fc(self.n2(x)),approximate='tanh'))
def with_bias(layer):
new=nn.Linear(layer.in_features,layer.out_features,bias=True,device=layer.weight.device)
with torch.no_grad(): new.weight.copy_(layer.weight); new.bias.zero_()
return new
def apply_change(model, kind):
if kind=='layernorm':
def ln(old):
layer=nn.LayerNorm(old.weight.numel(),eps=1e-5,bias=False,device=old.weight.device)
with torch.no_grad(): layer.weight.copy_(old.weight)
return layer
for block in model.blocks: block.n1=ln(block.n1); block.n2=ln(block.n2)
model.final=ln(model.final)
elif kind=='posicion':
model.position_table=base.position.weight.detach().float().to('cuda')
for block in model.blocks: block.attn.use_rope=False
elif kind=='gelu':
model.blocks=nn.ModuleList([PlainBlock(block).cuda() for block in model.blocks])
elif kind=='sesgos':
for block in model.blocks:
for name in ('q','k','v','o'): setattr(block.attn,name,with_bias(getattr(block.attn,name)))
for name in ('gate','up','down'): setattr(block,name,with_bias(getattr(block,name)))
elif kind=='softcap':
for block in model.blocks: block.attn.cap=4.0
elif kind!='moderno': raise ValueError(kind)
print('semilla, variante, parámetros, pasos, pérdida inicial/final, validación, máximos, entropías')
for seed in (11,22,33):
for kind in ('moderno','layernorm','posicion','gelu','sesgos','softcap'):
torch.manual_seed(seed)
net=MiniLlama(base,False).cuda(); apply_change(net,kind)
if seed==11 and kind=='softcap':
changed=vx.clone(); changed[0,-1]=(changed[0,-1]+1)%len(chars)
with torch.no_grad(): before=net.logits(vx); after=net.logits(changed)
assert torch.allclose(before[:,:-1],after[:,:-1],atol=1e-6,rtol=1e-6)
print('causalidad con soft-capping comprobada')
optimizer=torch.optim.AdamW(net.parameters(),lr=0.01)
gen=torch.Generator().manual_seed(seed); losses=[]
for _ in range(steps):
starts=torch.randint(len(train)-length,(batch_size,),generator=gen).tolist()
xx=torch.stack([train[i:i+length] for i in starts]).cuda()
yy=torch.stack([train[i+1:i+length+1] for i in starts]).cuda()
optimizer.zero_grad(set_to_none=True)
loss=net(xx,yy); losses.append(float(loss.detach()))
if not torch.isfinite(loss): break
loss.backward(); optimizer.step()
with torch.no_grad():
validation=float(net(vx,vy))
maxima=[round(float(b.attn.max_logit),3) for b in net.blocks]
entropies=[round(float(b.attn.entropy),3) for b in net.blocks]
print(seed,kind,sum(p.numel() for p in net.parameters()),len(losses),
round(losses[0],4),round(losses[-1],4),round(validation,4),maxima,entropies)
del net,optimizernpm run lab and open the connection link.Exercises
Step 1 of 4. What happens to r(ax) if a is positive?
import numpy as np
def rms_backward(x, g, u, eps):
pass