Module contents
Lesson 6 of 28Advanced 120 min

Triton kernels II: matmul, fused normalization and logit-free cross-entropy

We write kernels that save memory and time in LLM training: tiled matmul with Tensor Cores, grouped L2 cache order and fused epilogues; fused RMSNorm forward and backward; and linear-head cross-entropy without materializing logits that can exceed model size at 128k vocabularies. The kernels are registered as PyTorch operators and integrated into the course GPT.

After this lesson you can

  • Implement tiled Triton matmul with an FP32 accumulator and autotuning and compare it with cuBLAS.
  • Measure how grouped program order affects L2 hit rate and performance.
  • Derive and implement fused RMSNorm backward with two-stage dW reduction.
  • Implement cross-entropy fused with the linear head and verify loss and gradients.
  • Register kernels as operators compatible with autograd and torch.compile and test with gradcheck and opcheck.

Before you start

Three matrices you do not want to move unnecessarily

A matrix product reuses inputs if each program keeps an output tile while traversing the inner dimension. A normalization can combine statistics, scaling, and derivatives in a few passes. A language model head presents another problem: a tokens-by-vocabulary logits matrix can occupy more memory than a small model’s states. Savings depend on shape and implementation; they are not automatic just because a kernel is called “fused.”

In Triton tiled matmul, A∈RM×KA\in\R^{M\times K} and B∈RK×NB\in\R^{K\times N} produce C∈RM×NC\in\R^{M\times N}. Each program chooses a BM×BNB_M\times B_N tile of CC, traverses KK in BKB_K blocks, and accumulates partial products in FP32 before converting output. Masks protect nondivisible edges. This is tile reuse expressed with Triton’s program model and memory operations. tl.dot can use Tensor Cores for compatible types and shapes; check the code and device rather than assuming it.

InteractiveA tile and its roofs
05101520Compute20Memory2.016Minimum2.016TFLOP/s

One K iteration loads one FP16 tile from A and one from B. The model omits writes to C and reuse across programs. The A and B sizes describe one hypothetical shared-memory stage. The compiler can use multiple stages or a different layout. The accumulator size is a logical quantity. The previous lesson's measured copy rate of 62.74 GB/s is rounded to 63. The initial peak of 20 TFLOP/s is an editable assumption.

BLOCK_M
BLOCK_N
BLOCK_K
20
63
Intensity per iteration32.00 FLOP/byte
A and B: one shared-memory stage8.00 KiB
Logical FP32 accumulator16.0 KiB
Model limit2.02 TFLOP/s
Change the three dimensions. Intensity counts one FP16 load of each tile per iteration and two FLOPs per multiply-add. Roofs are editable assumptions, not a kernel profile.

One full iteration performs approximately 2BMBNBK2B_MB_NB_K FLOPs and reads 2(BMBK+BKBN)2(B_MB_K+B_KB_N) bytes of FP16 inputs, assuming no other accesses and each tile read once. The ratio is BMBN/(BM+BN)B_MB_N/(B_M+B_N) FLOP/byte: BKB_K cancels in this model. It excludes writing CC, scaling, edges, and traffic between programs. The logical accumulator holds BMBNB_MB_N FP32 values; its distribution into actual registers depends on compiler and architecture.

Cancellation of BKB_K does not mean its choice is irrelevant. A larger inner block changes iteration count, temporary data, and opportunities to overlap loads with compute. A larger output tile reuses each input element more but also keeps more accumulators live and can reduce occupancy or cause spills to memory. Incomplete edges run masked lanes that do not contribute to output. Ideal intensity is therefore an initial diagnosis; actual time must be measured on the shapes the model will use.

Each program calculates row, column, and inner-dimension indices. Read masks replace elements outside the matrix with zero; the write mask avoids touching positions outside CC. Strides are in elements, so a transposed view can use the same kernel with different addressing. Correctness on contiguous square matrices does not prove those strides or edges work. A performance comparison with torch.matmul must use the same types, shape, and epilogue; if one version has a separate epilogue, time that operation too.

Order and epilogue

Grouped program ordering numbers several row tiles for the same column before advancing. This can favor reuse of a BB tile still in cache; row order favors a different access sequence. Numbering does not force programs to execute in exactly that order, and replacement and concurrency in real L2 are not simple LRU.

InteractiveTile order and reuse
C0,0
C0,1
C0,2
C0,3
C1,0
C1,1
C1,2
C1,3
C2,0
C2,1
C2,2
C2,3
C3,0
C3,1
C3,2
C3,3
  • Row order
  • Grouped order

The LRU model has 16 sequential programs. Each accesses one A tile and one B tile. It abstracts away real execution order, different tile sizes, cache replacement details and concurrency in physical L2.

2
4
Programs completed: 0
Row-order hits0
Grouped-order hits0
Grouped-order cacheEmpty
Compare orders in an explicit LRU cache of unit tiles. Play through the 16 programs and change GROUP_M and capacity. The figure does not represent real GPU counters.

Epilogue fusion adds bias, activation, or conversion at the end of accumulation before writing CC. It avoids materializing an intermediate output, but can increase register use or limit type combinations. Apply the epilogue once, after summing all KK blocks: adding bias in each iteration multiplies it by the number of blocks. Autotuning must include relevant dimensions in its key, as in Triton I.

Grouping programs proposes a logical order, not a barrier or scheduler promise. Observing its effect on a device requires at least two types of measurement: time under comparable conditions and an L2 hit or traffic counter from a compatible profiling tool. The timing ratio alone does not prove cache caused the change. If the counter is unavailable or profiling permissions are disabled, report that absence; the LRU figure remains useful for reasoning but does not become a hardware reading.

The autotuner runs several configurations before choosing one. The first call includes that cost and does not represent steady-state time. If a configuration is valid for one shape but not another, an incomplete key can reuse a poor choice; for variants with different epilogues or strides, consider whether those properties change the best configuration. The choice is specific to compiler, device, and load. A shape well served by cuBLAS may not justify maintaining a custom kernel even if mathematically correct.

RMSNorm and its backward pass

For a row x∈RD\vb{x}\in\R^D with scale g\vb{g} and ε>0\eps>0, RMSNorm defines r=(D−1∑jxj2+ε)−1/2r=(D^{-1}\sum_j x_j^2+\eps)^{-1/2} and yj=gjxjry_j=g_jx_jr. The fused normalization backward combines row reduction with the derivative. If uj=(∂L/∂yj)gju_j=(\partial L/\partial y_j)g_j, then

∂L∂xj=ruj−r3xjD∑iuixi,∂L∂gj=∑filas∂L∂yjxjr.\frac{\partial L}{\partial x_j}=r u_j-\frac{r^3x_j}{D}\sum_i u_i x_i, \qquad \frac{\partial L}{\partial g_j}=\sum_{\text{filas}}\frac{\partial L}{\partial y_j}x_jr.

Indeed, ∂r/∂xj=−r3xj/D\partial r/\partial x_j=-r^3x_j/D. The first expression adds the direct term and the effect of xjx_j on the shared denominator. The second accumulates contributions from all rows. An implementation can write partial contributions per row and reduce them in a second phase without atomics; its buffer and reduction order also cost memory and compute. Without ε>0\eps>0, a zero row would need special handling.

One concrete path saves rr in forward. In backward each row program reads x,g,dy,rx,g,dy,r, reduces ∑iuixi\sum_i u_i x_i, and writes dxdx and a partial vector dy⊙x rdy\odot x\,r. A second kernel traverses rows and sums partials by channel to produce dgdg. No two programs write the same dgdg element, so atomics are unnecessary. FP32 reduction and final BF16 conversion yield a result close to, but not necessarily bit-identical to, a reference reducing in another order. The rows-by-channels partial buffer is a real cost of this strategy.

A head without a logits matrix

For hidden row x\vb{x} and vocabulary weight WW, cross-entropy is ℓ=log⁡∑vezv−zy\ell=\log\sum_v e^{z_v}-z_y, with zv=x⊤wvz_v=\vb{x}\T\vb{w}_v. A linear head fused with cross-entropy traverses vocabulary blocks and retains only a maximum and normalized sum per row. If (m,s)(m,s) summarizes previous blocks and (mb,sb)(m_b,s_b) the new one, then

m′=max⁡(m,mb),s′=sem−m′+sbemb−m′.m'=\max(m,m_b),\qquad s'=s e^{m-m'}+s_b e^{m_b-m'}.

The identity follows by factoring em′e^{m'} from the exponential sum. At the end, LSE⁡=m+log⁡s\operatorname{LSE}=m+\log s. The target logit can be computed directly from its row of WW. Backward reconstructs each logits block, computes pv=ezv−LSE⁡p_v=e^{z_v-\operatorname{LSE}}, and uses ∂ℓ/∂zv=pv−1[v=y]\partial\ell/\partial z_v=p_v-\ind[v=y]. Contributions to dXdX are accumulated and rows reduced for dWdW. The full matrix need not be retained, although weights, their gradients, and other buffers still occupy memory.

The initial maximum is −∞-\infty and the initial sum zero. In the first nonempty block, the factor rescaling the previous sum is zero and the new sum positive. Check that the label is within the vocabulary and the sequence of blocks covers every index, including the final partial block. For mean loss over MM rows, each logit’s derivative also carries a 1/M1/M factor; with ignored positions or per-token weights, the denominator must match the exact loss definition. This lesson’s example uses valid labels and uniform weights to make that convention visible.

Avoiding logits does not automatically eliminate every large object. Vocabulary weights and their gradient remain V×DV\times D, and backward recomputes products to avoid retaining M×VM\times V probabilities. In some regimes compute is traded for memory capacity; in others logits are small and a general kernel is already fast enough. A plot of isolated logits memory is not training peak, which also includes activations, optimizer states, and temporary allocations.

InteractiveThe logits wall
05101520253035Full31.31Tiled0.2501GiB

The example models two logit matrices or two tiles of size tokens × block, plus one FP32 LSE per token. It counts only those tensors and leaves actual peak kernel memory unmeasured. An implementation may store fewer matrices.

8
4096
Vocabulary
Bytes per logit
1024
Full logits15.7 GiB
Logits and gradient31.3 GiB
Tile and gradient plus LSE256 MiB
Ratio in this model125.2×
Change batch, length, vocabulary, tile size, and bytes per element. The model counts full logits and gradient versus two tiles plus LSE; it is not a measured kernel peak.

With 8×40968\times4096 tokens and vocabulary 128256, an FP32 logits matrix occupies 16810770432 bytes, or 15.65625 GiB. Its equally sized gradient would double that count if both coexist; implementations may release or reuse memory. Cut Cross-Entropy studies a head without full materialization and additional techniques: this lab’s exact procedure does not assume its gradient filtering or reproduce its benchmark.

NumPy lab: compare loss, gradients, and memory

First compute the dense reference. Inputs and weights are created before measurement; tracemalloc measures allocations tracked during each function in the current runtime, not all process or GPU memory. The block version retains the V×DV\times D weight gradient needed for updating but avoids storing full M×VM\times V logits.

[ ]Dense and blockwise headsBrowser
import numpy as np, tracemalloc
def dense(x,w,y):
    [email protected]
    maximum=logits.max(axis=1)
    lse=maximum+np.log(np.exp(logits-maximum[:,None]).sum(axis=1))
    loss=np.mean(lse-logits[np.arange(len(y)),y])
    p=np.exp(logits-lse[:,None]);p[np.arange(len(y)),y]-=1;p/=len(y)
    return loss,p@w,p.T@x

def tiled(x,w,y,block=128):
    rows=len(y);m=np.full(rows,-np.inf);s=np.zeros(rows);truth=np.empty(rows)
    for start in range(0,len(w),block):
        z=x@w[start:start+block].T
        new=np.maximum(m,z.max(axis=1))
        s=s*np.exp(m-new)+np.exp(z-new[:,None]).sum(axis=1);m=new
        chosen=(y>=start)&(y<start+z.shape[1])
        truth[chosen]=z[np.arange(rows)[chosen],y[chosen]-start]
    lse=m+np.log(s);loss=np.mean(lse-truth)
    dx=np.zeros_like(x);dw=np.zeros_like(w)
    for start in range(0,len(w),block):
        end=min(start+block,len(w));z=x@w[start:end].T
        p=np.exp(z-lse[:,None]);chosen=(y>=start)&(y<end)
        p[np.arange(rows)[chosen],y[chosen]-start]-=1;p/=rows
        dx+=p@w[start:end];dw[start:end]=p.T@x
    return loss,dx,dw

def measure(fn):
    tracemalloc.start();out=fn();_,peak=tracemalloc.get_traced_memory();tracemalloc.stop()
    return out,peak
rng=np.random.default_rng(6)
x=rng.normal(size=(32,32));w=rng.normal(size=(2048,32));y=rng.integers(len(w),size=len(x))
dense_result,dense_peak=measure(lambda:dense(x,w,y))
tile_result,tile_peak=measure(lambda:tiled(x,w,y,128))
print('pérdidas:',dense_result[0],tile_result[0])
print('error máximo dx:',np.max(np.abs(dense_result[1]-tile_result[1])))
print('error máximo dw:',np.max(np.abs(dense_result[2]-tile_result[2])))
print('picos rastreados, bytes:',dense_peak,tile_peak)
assert np.allclose(dense_result[0],tile_result[0],rtol=1e-12)
assert np.allclose(dense_result[1],tile_result[1],atol=1e-12)
assert np.allclose(dense_result[2],tile_result[2],atol=1e-12)

A local CPython run of this example tracked 2107403 bytes for the dense version and 667568 for blocks. Values depend on version and runtime; do not extrapolate those amounts to device memory. Both functions produce exactly the full gradients for this objective, apart from rounding.

Operator integration

Custom operator registration declares an input, output, and mutation contract for PyTorch. A fake implementation propagates shapes and types without running the device; registered backward must respect the contract. torch.library.opcheck verifies operator properties but does not alone prove the mathematical formula correct. gradcheck, comparison with a reference, and edge-case tests provide different checks. A custom autograd function can serve as a bridge, but does not itself guarantee torch.compile captures the whole graph.

In a finite-difference gradient test, each double-precision input is perturbed and the numerical derivative compared with the operator’s. That test exposes incorrect signs or factors, but does not replace a BF16 comparison at representative shapes and tolerances. opcheck checks registration and metadata propagation among other properties; an incorrectly defined operation could pass if its formula and contract are consistent with each other. Finally, a compiled call must verify both output and backward and state whether the whole graph was captured or had breaks.

Liger Kernel collects training kernels and Cut Cross-Entropy studies a head without logits materialization plus additional optimizations. They are references for comparing design and maintenance, not evidence that this teaching code reaches their figures. A fair local comparison uses the same model, inputs, type, precision, and seed; it includes warm-up and separates compilation from execution time. If a library cannot be installed in the environment, record its absence rather than attributing a result to it.

Local lab: kernels and a GPT step

The next four cells require compatible CUDA, PyTorch, and Triton. The documented run uses Ubuntu in WSL, Torch 2.11.0+cu128, Triton 3.6.0, and a 12 GiB RTX 3060. TRITON_DISABLE_LINE_INFO prevents a virtual path with non-ASCII characters from reaching ptxas in this environment; it disables debugging line information. Tests check values and gradients before timings. Block tuning compiles and warms kernels; do not confuse that initial cost with steady-state time.

Matmul with epilogue and autotuning

The kernel grid supports strides, edges, and row or grouped order. The accumulator is FP32 and the bias/ReLU epilogue is optional. Autotuning explores three tiles per shape and the comparison uses FP16 and BF16. Comparison with torch.matmul measures only the product without an epilogue on both paths.

[ ]Tiled matmul, autotuning and comparisonLocal GPU
"""Matmul por teselas con dos órdenes, autotuning y epílogo sesgo/ReLU."""
import os
os.environ['TRITON_DISABLE_LINE_INFO']='1'
import torch, triton
import triton.language as tl
import triton.testing

@triton.jit
def mm_kernel(A,B,Bias,C,M,N,K,ASM:tl.constexpr,ASK:tl.constexpr,BSK:tl.constexpr,BSN:tl.constexpr,
              BM:tl.constexpr,BN:tl.constexpr,BK:tl.constexpr,GROUP:tl.constexpr,FUSE:tl.constexpr):
    pid=tl.program_id(0); pm=tl.cdiv(M,BM);pn=tl.cdiv(N,BN)
    if GROUP == 1:
        im=pid//pn;jn=pid%pn
    else:
        per=GROUP*pn; group=pid//per; first=group*GROUP
        gm=tl.minimum(pm-first,GROUP); within=pid%per
        im=first+within%gm;jn=within//gm
    m=im*BM+tl.arange(0,BM); n=jn*BN+tl.arange(0,BN); kk=tl.arange(0,BK)
    acc=tl.zeros((BM,BN),dtype=tl.float32)
    for start in range(0,tl.cdiv(K,BK)):
        k=start*BK+kk
        a=tl.load(A+m[:,None]*ASM+k[None,:]*ASK,(m[:,None]<M)&(k[None,:]<K),other=0)
        b=tl.load(B+k[:,None]*BSK+n[None,:]*BSN,(k[:,None]<K)&(n[None,:]<N),other=0)
        acc=tl.dot(a,b,acc)
    if FUSE:
        bias=tl.load(Bias+n,n<N,other=0).to(tl.float32)
        acc=tl.maximum(acc+bias[None,:],0)
    tl.store(C+m[:,None]*N+n[None,:],acc,(m[:,None]<M)&(n[None,:]<N))

@triton.autotune(configs=[triton.Config({'BM':32,'BN':64,'BK':32},num_warps=4),
                         triton.Config({'BM':64,'BN':32,'BK':32},num_warps=4),
                         triton.Config({'BM':32,'BN':32,'BK':32},num_warps=4)],key=['M','N','K'])
@triton.jit
def tuned_mm(A,B,Bias,C,M,N,K,ASM:tl.constexpr,ASK:tl.constexpr,BSK:tl.constexpr,BSN:tl.constexpr,
             BM:tl.constexpr,BN:tl.constexpr,BK:tl.constexpr,GROUP:tl.constexpr,FUSE:tl.constexpr):
    mm_kernel(A,B,Bias,C,M,N,K,ASM,ASK,BSK,BSN,BM,BN,BK,GROUP,FUSE)

def matmul(a,b,group=4,fuse=False,tune=False):
    m,k=a.shape; kk,n=b.shape; assert k==kk
    bias=torch.randn(n,device=a.device,dtype=a.dtype) if fuse else torch.zeros(n,device=a.device,dtype=a.dtype)
    c=torch.empty((m,n),device=a.device,dtype=a.dtype)
    if tune:
        grid=lambda meta:(triton.cdiv(m,meta['BM'])*triton.cdiv(n,meta['BN']),)
        tuned_mm[grid](a,b,bias,c,m,n,k,*a.stride(),*b.stride(),GROUP=group,FUSE=fuse)
    else:
        grid=(triton.cdiv(m,32)*triton.cdiv(n,64),)
        mm_kernel[grid](a,b,bias,c,m,n,k,*a.stride(),*b.stride(),32,64,32,group,fuse,num_warps=4)
    return c,bias

if __name__=='__main__':
    torch.manual_seed(42)
    for dtype in (torch.float16,torch.bfloat16):
        a=torch.randn(257,129,device='cuda',dtype=dtype).T
        b=torch.randn(187,257,device='cuda',dtype=dtype).T
        for group in (1,4):
            c,bias=matmul(a,b,group,True)
            ref=torch.relu(a.float()@b.float()+bias.float()).to(dtype)
            torch.testing.assert_close(c,ref,rtol=.03,atol=.05)
        c,_=matmul(a,b,4,False,True)
        torch.testing.assert_close(c,(a.float()@b.float()).to(dtype),rtol=.03,atol=.05)
        print(dtype,'formas irregulares y strides comprobados; autotune',tuned_mm.best_config,flush=True)
    for dtype in (torch.float16,torch.bfloat16):
        for size in (256,512,1024):
            a=torch.randn(size,size,device='cuda',dtype=dtype);b=torch.randn_like(a)
            outputs={}
            for group in (1,4):
                c=torch.empty_like(a);bias=torch.zeros(size,device='cuda',dtype=dtype)
                def call():
                    mm_kernel[(triton.cdiv(size,32)*triton.cdiv(size,64),)](a,b,bias,c,size,size,size,
                        *a.stride(),*b.stride(),32,64,32,group,False,num_warps=4)
                call();torch.testing.assert_close(c,a@b,rtol=.03,atol=.05)
                ms=triton.testing.do_bench(call,warmup=20,rep=50,return_mode='median')
                outputs[group]=ms
            refms=triton.testing.do_bench(lambda:a@b,warmup=20,rep=50,return_mode='median')
            print(dtype,'n',size,'fila/agrupado/cublas ms',outputs[1],outputs[4],refms,flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In a shared RTX 3060 campaign with 1024-square FP16 matrices, median row order was 0.1157 ms, grouped order 0.1193 ms, and torch.matmul 0.1137 ms. This is one sample with other processes active, not a guaranteed rate. Grouped order did not win here; L2 was not measured for that shape and the difference is not attributed to cache.

A separate 2048 × 2048 FP16 multiplication was also profiled on the same RTX 3060 using Nsight Compute 2025.1.1 and lts__t_sector_hit_rate.pct. The row-order kernel, GROUP=1, obtained 52.60% L2 sector hits; grouped order, GROUP=4, obtained 81.58%, a 28.98 percentage-point difference. Each measurement used three profiler passes and checked the result against torch.matmul. The metric is an aggregate L2 sector ratio for the kernel under profiler replay conditions, not a measure of global-memory bytes read or a speed guarantee. The two measurements use a different shape from the previous paragraph’s 1024 timings; these figures cannot explain those timing differences. See NVIDIA’s metric definitions.

To repeat it, save the previous cell as matmul.py and the next program as perfil_l2.py in the same directory. The test uses the same seed, tile configuration, and types; it requires ncu and permission to access GPU counters. In WSL that permission also depends on the Windows host. Run the two commands separately; the profiler may replay the kernel and change cache conditions.

import sys
import torch, triton
from matmul import mm_kernel
group=int(sys.argv[1])
assert group in (1,4)
torch.manual_seed(61);n=2048
a=torch.randn(n,n,device='cuda',dtype=torch.float16);b=torch.randn_like(a)
bias=torch.zeros(n,device='cuda',dtype=a.dtype);c=torch.empty_like(a)
mm_kernel[(triton.cdiv(n,32)*triton.cdiv(n,64),)](
    a,b,bias,c,n,n,n,*a.stride(),*b.stride(),32,64,32,group,False,num_warps=4)
torch.cuda.synchronize()
torch.testing.assert_close(c,a@b,rtol=.03,atol=.05)
print('GPU',torch.cuda.get_device_name(),'GROUP_M',group,'comparación correcta')
ncu --kernel-name regex:mm_kernel --launch-count 1 --metrics lts__t_sector_hit_rate.pct python perfil_l2.py 1
ncu --kernel-name regex:mm_kernel --launch-count 1 --metrics lts__t_sector_hit_rate.pct python perfil_l2.py 4

RMSNorm with two reductions and registration

Forward saves the inverse root. Backward writes dx and a partial per row; a second kernel reduces the scale gradient without atomics. The operator registers a fake result and an autograd rule. The FP64 path is used for gradcheck; the BF16 check compares against FP32 autograd.

[ ]Triton RMSNorm and PyTorch operatorLocal GPU
"""RMSNorm Triton y registro de operadores; pruebas reales y gradcheck."""
import os
os.environ['TRITON_DISABLE_LINE_INFO']='1'
import torch, triton
import triton.language as tl

@triton.jit
def rms_fwd(X,G,Y,R,M:tl.constexpr,D:tl.constexpr,EPS:tl.constexpr,B:tl.constexpr,DOUBLE:tl.constexpr):
    row=tl.program_id(0); j=tl.arange(0,B); mask=j<D
    if DOUBLE:
        x=tl.load(X+row*D+j,mask,other=0).to(tl.float64)
        g=tl.load(G+j,mask,other=0).to(tl.float64)
    else:
        x=tl.load(X+row*D+j,mask,other=0).to(tl.float32)
        g=tl.load(G+j,mask,other=0).to(tl.float32)
    r=tl.rsqrt(tl.sum(x*x,0)/D+EPS)
    tl.store(R+row,r);tl.store(Y+row*D+j,x*r*g,mask)

@triton.jit
def rms_back(DY,X,G,R,DX,P,M:tl.constexpr,D:tl.constexpr,B:tl.constexpr,DOUBLE:tl.constexpr):
    row=tl.program_id(0);j=tl.arange(0,B);mask=j<D
    if DOUBLE:
        x=tl.load(X+row*D+j,mask,other=0).to(tl.float64)
        g=tl.load(G+j,mask,other=0).to(tl.float64)
        dy=tl.load(DY+row*D+j,mask,other=0).to(tl.float64)
        r=tl.load(R+row).to(tl.float64)
    else:
        x=tl.load(X+row*D+j,mask,other=0).to(tl.float32)
        g=tl.load(G+j,mask,other=0).to(tl.float32)
        dy=tl.load(DY+row*D+j,mask,other=0).to(tl.float32)
        r=tl.load(R+row).to(tl.float32)
    u=dy*g; dot=tl.sum(u*x,0)
    tl.store(DX+row*D+j,r*u-x*r*r*r*dot/D,mask)
    tl.store(P+row*D+j,dy*x*r,mask)

@triton.jit
def reduce_g(P,DG,M:tl.constexpr,D:tl.constexpr,BR:tl.constexpr,BC:tl.constexpr):
    cols=tl.program_id(0)*BC+tl.arange(0,BC); rr=tl.arange(0,BR)
    if P.dtype.element_ty==tl.float64:
        accum=tl.full((BC,),0.,tl.float64)
    else:
        accum=tl.full((BC,),0.,tl.float32)
    for start in range(0,M,BR):
        rows=start+rr
        vals=tl.load(P+rows[:,None]*D+cols[None,:],(rows[:,None]<M)&(cols[None,:]<D),other=0)
        accum+=tl.sum(vals,axis=0)
    tl.store(DG+cols,accum,cols<D)

@torch.library.custom_op('oryon06::rms_back',mutates_args=())
def backward_op(dy:torch.Tensor,x:torch.Tensor,g:torch.Tensor,r:torch.Tensor)->tuple[torch.Tensor,torch.Tensor]:
    m,d=x.shape
    dx=torch.empty_like(x); partial=torch.empty((m,d),device=x.device,dtype=r.dtype); dg=torch.empty_like(g)
    rms_back[(m,)](dy.contiguous(),x,g,r,dx,partial,m,d,triton.next_power_of_2(d),x.dtype==torch.float64)
    reduce_g[(triton.cdiv(d,32),)](partial,dg,m,d,32,32)
    return dx,dg

@backward_op.register_fake
def _(dy,x,g,r): return torch.empty_like(x),torch.empty_like(g)

@torch.library.custom_op('oryon06::rms',mutates_args=())
def rms_op(x:torch.Tensor,g:torch.Tensor,eps:float)->tuple[torch.Tensor,torch.Tensor]:
    if x.ndim != 2 or not x.is_contiguous() or not g.is_contiguous(): raise ValueError('x 2D y g contiguos')
    m,d=x.shape
    y=torch.empty_like(x); r=torch.empty((m,),device=x.device,dtype=torch.float64 if x.dtype==torch.float64 else torch.float32)
    rms_fwd[(m,)](x,g,y,r,m,d,eps,triton.next_power_of_2(d),x.dtype==torch.float64)
    return y,r

@rms_op.register_fake
def _(x,g,eps):
    return torch.empty_like(x),torch.empty((x.shape[0],),device=x.device,dtype=torch.float64 if x.dtype==torch.float64 else torch.float32)

def setup(ctx,inputs,output):
    x,g,eps=inputs; y,r=output
    ctx.save_for_backward(x,g,r);ctx.mark_non_differentiable(r)

def backward(ctx,dy,dr):
    x,g,r=ctx.saved_tensors
    dx,dg=backward_op(dy,x,g,r)
    return dx,dg,None

rms_op.register_autograd(backward,setup_context=setup)

if __name__=='__main__':
    torch.manual_seed(12)
    for dtype in (torch.float32,torch.bfloat16):
        x=torch.randn(7,37,device='cuda',dtype=dtype,requires_grad=True)
        g=torch.randn(37,device='cuda',dtype=dtype,requires_grad=True)
        dy=torch.randn_like(x); y,r=rms_op(x,g,1e-5); (y*dy).sum().backward()
        dx=x.grad.detach().clone();dg=g.grad.detach().clone()
        x2=x.detach().float().requires_grad_();g2=g.detach().float().requires_grad_()
        ref=x2*torch.rsqrt(x2.square().mean(-1,keepdim=True)+1e-5)*g2
        (ref*dy.float()).sum().backward()
        tol=.03 if dtype==torch.bfloat16 else 1e-5
        print(dtype,'max errors y/dx/dg',float((y.float()-ref).abs().max().detach()),float((dx.float()-x2.grad).abs().max()),float((dg.float()-g2.grad).abs().max()),flush=True)
        torch.testing.assert_close(y.float(),ref,rtol=tol,atol=tol)
        torch.testing.assert_close(dx.float(),x2.grad,rtol=tol,atol=tol)
        torch.testing.assert_close(dg.float(),g2.grad,rtol=tol,atol=tol)
    x=torch.randn(2,4,device='cuda',dtype=torch.float64,requires_grad=True)
    g=torch.randn(4,device='cuda',dtype=torch.float64,requires_grad=True)
    print('gradcheck:',torch.autograd.gradcheck(lambda a,b:rms_op(a,b,1e-5)[0],(x,g),eps=1e-6,atol=1e-5,rtol=1e-4),flush=True)
    z=torch.randn(3,8,device='cuda',requires_grad=True);w=torch.randn(8,device='cuda',requires_grad=True)
    print('opcheck:',torch.library.opcheck(rms_op,(z,w,1e-5)),flush=True)
    compiled=torch.compile(lambda a,b:rms_op(a,b,1e-5)[0],fullgraph=True)
    torch.testing.assert_close(compiled(z,w),rms_op(z,w,1e-5)[0])
    compiled(z,w).sum().backward()
    print('torch.compile forward/backward correct',flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Linear head and loss without full logits

The next operator computes the online maximum and sum per row and reconstructs blocks for dx and dw. Row reduction for dw is blockwise with one owner per term. The example uses valid labels, contiguous matrices, and mean loss; it does not implement ignored labels or weighted losses.

[ ]Fused cross-entropy and its gradientsLocal GPU
"""Cabeza lineal + entropía cruzada sin almacenar logits (prototipo)."""
import os
os.environ['TRITON_DISABLE_LINE_INFO']='1'
import torch, triton
import triton.language as tl

@triton.jit
def acc_type(x,DOUBLE:tl.constexpr):
    if DOUBLE: y=x.to(tl.float64)
    else: y=x.to(tl.float32)
    return y

@triton.jit
def ce_forward(X,W,T,LOSS,LSE,M:tl.constexpr,D:tl.constexpr,V:tl.constexpr,BD:tl.constexpr,BV:tl.constexpr,DOUBLE:tl.constexpr):
    row=tl.program_id(0);d=tl.arange(0,BD);mask=d<D
    x=acc_type(tl.load(X+row*D+d,mask,other=0),DOUBLE)
    label=tl.load(T+row)
    correct=acc_type(tl.load(W+label*D+d,mask,other=0),DOUBLE)
    target=tl.sum(x*correct,0)
    if DOUBLE:
        maximum=tl.full((),-float('inf'),tl.float64);total=tl.full((),0,tl.float64)
    else:
        maximum=tl.full((),-float('inf'),tl.float32);total=tl.full((),0,tl.float32)
    for start in range(0,V,BV):
        v=start+tl.arange(0,BV)
        w=acc_type(tl.load(W+v[:,None]*D+d[None,:],(v[:,None]<V)&mask[None,:],other=0),DOUBLE)
        z=tl.sum(w*x[None,:],1);z=tl.where(v<V,z,-float('inf'))
        mx=tl.maximum(maximum,tl.max(z,0))
        total=total*tl.exp(maximum-mx)+tl.sum(tl.exp(z-mx),0);maximum=mx
    lse=maximum+tl.log(total)
    tl.store(LSE+row,lse);tl.store(LOSS+row,lse-target)

@triton.jit
def ce_dx(X,W,T,LSE,DL,DX,M:tl.constexpr,D:tl.constexpr,V:tl.constexpr,BD:tl.constexpr,BV:tl.constexpr,DOUBLE:tl.constexpr):
    row=tl.program_id(0);d=tl.arange(0,BD);mask=d<D
    x=acc_type(tl.load(X+row*D+d,mask,other=0),DOUBLE)
    label=tl.load(T+row);lse=tl.load(LSE+row);dl=tl.load(DL+row)
    if DOUBLE: accum=tl.zeros((BD,),tl.float64)
    else: accum=tl.zeros((BD,),tl.float32)
    for start in range(0,V,BV):
        v=start+tl.arange(0,BV)
        w=acc_type(tl.load(W+v[:,None]*D+d[None,:],(v[:,None]<V)&mask[None,:],other=0),DOUBLE)
        z=tl.sum(w*x[None,:],1);p=tl.where(v<V,tl.exp(z-lse)-tl.cast(v==label,tl.float32),0)
        accum+=tl.sum(p[:,None]*w,axis=0)*dl
    tl.store(DX+row*D+d,accum,mask)

@triton.jit
def ce_dw(X,W,T,LSE,DL,DW,M:tl.constexpr,D:tl.constexpr,V:tl.constexpr,BD:tl.constexpr,BR:tl.constexpr,DOUBLE:tl.constexpr):
    v=tl.program_id(0);d=tl.arange(0,BD);rr=tl.arange(0,BR)
    w=acc_type(tl.load(W+v*D+d,d<D,other=0),DOUBLE)
    if DOUBLE: grad=tl.zeros((BD,),tl.float64)
    else: grad=tl.zeros((BD,),tl.float32)
    for start in range(0,M,BR):
        row=start+rr
        x=acc_type(tl.load(X+row[:,None]*D+d[None,:],(row[:,None]<M)&(d[None,:]<D),other=0),DOUBLE)
        labels=tl.load(T+row,row<M,other=0);lse=tl.load(LSE+row,row<M,other=0)
        dl=tl.load(DL+row,row<M,other=0)
        z=tl.sum(x*w[None,:],axis=1)
        p=tl.where(row<M,(tl.exp(z-lse)-tl.cast(labels==v,tl.float32))*dl,0)
        grad+=tl.sum(p[:,None]*x,axis=0)
    tl.store(DW+v*D+d,grad,d<D)

@torch.library.custom_op('oryon06::ce_back',mutates_args=())
def ce_back_op(dl:torch.Tensor,x:torch.Tensor,w:torch.Tensor,t:torch.Tensor,lse:torch.Tensor)->tuple[torch.Tensor,torch.Tensor]:
    m,d=x.shape;v=w.shape[0];dx=torch.empty_like(x);dw=torch.empty_like(w)
    ce_dx[(m,)](x,w,t,lse,dl.contiguous(),dx,m,d,v,triton.next_power_of_2(d),64,x.dtype==torch.float64)
    ce_dw[(v,)](x,w,t,lse,dl.contiguous(),dw,m,d,v,triton.next_power_of_2(d),32,x.dtype==torch.float64)
    return dx,dw

@ce_back_op.register_fake
def _(dl,x,w,t,lse): return torch.empty_like(x),torch.empty_like(w)

@torch.library.custom_op('oryon06::ce',mutates_args=())
def ce_op(x:torch.Tensor,w:torch.Tensor,t:torch.Tensor)->tuple[torch.Tensor,torch.Tensor]:
    if x.ndim!=2 or w.ndim!=2 or not x.is_contiguous() or not w.is_contiguous(): raise ValueError('matrices contiguas')
    m,d=x.shape;v=w.shape[0]
    loss=torch.empty(m,device=x.device,dtype=torch.float64 if x.dtype==torch.float64 else torch.float32);lse=torch.empty_like(loss)
    ce_forward[(m,)](x,w,t,loss,lse,m,d,v,triton.next_power_of_2(d),64,x.dtype==torch.float64)
    return loss,lse

@ce_op.register_fake
def _(x,w,t):
    shape=(x.shape[0],)
    dtype=torch.float64 if x.dtype==torch.float64 else torch.float32
    return (torch.empty(shape,device=x.device,dtype=dtype),torch.empty(shape,device=x.device,dtype=dtype))

def setup(ctx,inputs,output):
    x,w,t=inputs;loss,lse=output
    ctx.save_for_backward(x,w,t,lse);ctx.mark_non_differentiable(lse)

def backward(ctx,dl,dlse):
    x,w,t,lse=ctx.saved_tensors
    dx,dw=ce_back_op(dl,x,w,t,lse)
    return dx,dw,None

ce_op.register_autograd(backward,setup_context=setup)

if __name__=='__main__':
    torch.manual_seed(4)
    for dtype in (torch.float32,torch.bfloat16):
        x=torch.randn(13,33,device='cuda',dtype=dtype,requires_grad=True)
        w=torch.randn(259,33,device='cuda',dtype=dtype,requires_grad=True)
        t=torch.randint(259,(13,),device='cuda')
        loss=ce_op(x,w,t)[0].mean();loss.backward();dx=x.grad.clone();dw=w.grad.clone()
        a=x.detach().float().requires_grad_();b=w.detach().float().requires_grad_()
        ref=torch.nn.functional.cross_entropy([email protected],t);ref.backward()
        tol=.04 if dtype==torch.bfloat16 else 2e-4
        print(dtype,'loss',float(loss.detach()),'ref',float(ref.detach()),'max dx/dw',float((dx.float()-a.grad).abs().max()),float((dw.float()-b.grad).abs().max()),flush=True)
        torch.testing.assert_close(loss,ref,rtol=tol,atol=tol)
        torch.testing.assert_close(dx.float(),a.grad,rtol=tol,atol=tol)
        torch.testing.assert_close(dw.float(),b.grad,rtol=tol,atol=tol)
    xd=torch.randn(2,4,device='cuda',dtype=torch.float64,requires_grad=True);wd=torch.randn(5,4,device='cuda',dtype=torch.float64,requires_grad=True);td=torch.tensor([0,4],device='cuda')
    print('gradcheck',torch.autograd.gradcheck(lambda a,b:ce_op(a,b,td)[0],(xd,wd),eps=1e-6,atol=1e-5,rtol=1e-4),flush=True)
    x=torch.randn(3,8,device='cuda',requires_grad=True);w=torch.randn(17,8,device='cuda',requires_grad=True);t=torch.tensor([0,3,16],device='cuda')
    print('opcheck',torch.library.opcheck(ce_op,(x,w,t)),flush=True)
    compiled=torch.compile(lambda a,b,c:ce_op(a,b,c)[0].mean(),fullgraph=True)
    torch.testing.assert_close(compiled(x,w,t),ce_op(x,w,t)[0].mean())
    compiled(x,w,t).backward(); print('torch.compile forward/backward passed',flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Integration into the course GPT

This cell includes the m18 GPT class contract to be self-contained. It replaces LayerNorm with RMSNorm in both arms: it compares the same architecture and initial parameters, not an attempt to reproduce a checkpoint trained with LayerNorm. The head uses tied embedding weights. Data are synthetic, with batch 2, context 128, width 128, two blocks, and vocabulary 4096; this is an integration test, not a trained model quality evaluation.

[ ]Dense and fused training stepLocal GPU
"""GPT del curso con RMSNorm y cabeza densa o Triton, pendiente de ejecutar."""
import os,time
os.environ['TRITON_DISABLE_LINE_INFO']='1'
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F

source = r'''
import io, json, math
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F

class Attention(nn.Module):
    def __init__(self, width, heads, dropout):
        super().__init__()
        assert width % heads == 0
        self.heads = heads; self.dropout_p = dropout
        self.q = nn.Linear(width, width); self.k = nn.Linear(width, width)
        self.v = nn.Linear(width, width); self.o = nn.Linear(width, width)
        self.residual_dropout = nn.Dropout(dropout)
    def forward(self, x, diagnostics=False):
        b, t, d = x.shape; dh = d // self.heads
        def split(linear): return linear(x).view(b, t, self.heads, dh).transpose(1, 2)
        q, k, v = split(self.q), split(self.k), split(self.v)
        out = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=self.dropout_p if self.training else 0.)
        entropy = None
        if diagnostics:
            scores = (q @ k.transpose(-2, -1)) / math.sqrt(dh)
            mask = torch.ones((t,t), dtype=torch.bool, device=x.device).tril()
            probs = scores.masked_fill(~mask, float('-inf')).softmax(-1)
            entropy = -(probs * probs.clamp_min(1e-30).log()).sum(-1).mean().detach()
        out = out.transpose(1,2).contiguous().view(b,t,d)
        return self.residual_dropout(self.o(out)), entropy

class MLP(nn.Module):
    def __init__(self, width, dropout):
        super().__init__()
        self.fc = nn.Linear(width, 4*width); self.proj = nn.Linear(4*width, width)
        self.dropout = nn.Dropout(dropout)
    def forward(self, x):
        return self.dropout(self.proj(F.gelu(self.fc(x), approximate='tanh')))

class Block(nn.Module):
    def __init__(self, width, heads, dropout):
        super().__init__()
        self.n1 = nn.LayerNorm(width, eps=1e-5); self.n2 = nn.LayerNorm(width, eps=1e-5)
        self.attn = Attention(width, heads, dropout); self.mlp = MLP(width, dropout)
    def forward(self, x, diagnostics=False):
        a, entropy = self.attn(self.n1(x), diagnostics)
        x = x + a
        return x + self.mlp(self.n2(x)), entropy

class TorchGPT(nn.Module):
    def __init__(self, vocab, context, width, layers, heads, dropout=0.):
        super().__init__()
        if width % heads: raise ValueError('width debe ser divisible por heads')
        self.config = dict(vocab=vocab, context=context, width=width, layers=layers, heads=heads, dropout=dropout)
        self.token = nn.Embedding(vocab, width); self.position = nn.Embedding(context, width)
        self.embedding_dropout = nn.Dropout(dropout)
        self.blocks = nn.ModuleList([Block(width, heads, dropout) for _ in range(layers)])
        self.final = nn.LayerNorm(width, eps=1e-5)
        self.apply(self._init)
        for block in self.blocks:
            nn.init.normal_(block.attn.o.weight, mean=0, std=.02/math.sqrt(2*layers))
            nn.init.normal_(block.mlp.proj.weight, mean=0, std=.02/math.sqrt(2*layers))
    @staticmethod
    def _init(module):
        if isinstance(module, (nn.Linear, nn.Embedding)):
            nn.init.normal_(module.weight, mean=0, std=.02)
            if isinstance(module, nn.Linear) and module.bias is not None: nn.init.zeros_(module.bias)
    def forward(self, ids, targets=None, diagnostics=False):
        b, t = ids.shape
        if t < 1 or t > self.config['context']: raise ValueError('contexto fuera de rango')
        pos = torch.arange(t, device=ids.device)
        x = self.embedding_dropout(self.token(ids) + self.position(pos)[None,:,:])
        entropies = []
        for block in self.blocks:
            x, entropy = block(x, diagnostics)
            if diagnostics: entropies.append(entropy)
        logits = F.linear(self.final(x), self.token.weight)
        loss = None if targets is None else F.cross_entropy(logits.reshape(-1, logits.shape[-1]), targets.reshape(-1))
        return logits, loss, entropies
    @torch.no_grad()
    def generate(self, ids, count, generator):
        self.eval()
        for _ in range(count):
            logits, _, _ = self(ids[:, -self.config['context']:])
            probs = logits[:, -1].softmax(-1)
            token = torch.multinomial(probs, 1, generator=generator)
            ids = torch.cat((ids, token), dim=1)
        return ids

def load_numpy_checkpoint(path, dtype=torch.float64):
    with np.load(path, allow_pickle=False) as z:
        cfg = json.loads(str(z['config'])); chars = z['characters'].tolist()
        model = TorchGPT(**cfg, dropout=0.).to(dtype=dtype)
        if len(chars) != cfg['vocab'] or len(set(chars)) != len(chars): raise ValueError('vocabulario inválido')
        expected = {'config', 'characters', 'token', 'position', 'final.g', 'final.b'}
        for i in range(cfg['layers']):
            for n in ('n1', 'n2'):
                expected.update({f'block.{i}.{n}.g', f'block.{i}.{n}.b'})
            for n in ('q', 'k', 'v', 'o', 'fc', 'proj'):
                expected.update({f'block.{i}.{n}.w', f'block.{i}.{n}.b'})
        if set(z.files) != expected: raise ValueError('nombres de tensores incompatibles')
        with torch.no_grad():
            def copy(parameter, name, transpose=False):
                a = z[name]
                if transpose: a = a.T
                if tuple(a.shape) != tuple(parameter.shape) or not np.isfinite(a).all(): raise ValueError('tensor inválido: '+name)
                parameter.copy_(torch.as_tensor(a.copy(), dtype=dtype))
            copy(model.token.weight, 'token'); copy(model.position.weight, 'position')
            copy(model.final.weight, 'final.g'); copy(model.final.bias, 'final.b')
            for i, block in enumerate(model.blocks):
                pre = f'block.{i}.'
                for name in ('n1','n2'):
                    layer = getattr(block, name)
                    copy(layer.weight, pre+name+'.g'); copy(layer.bias, pre+name+'.b')
                for name in ('q','k','v','o'):
                    layer = getattr(block.attn, name)
                    copy(layer.weight, pre+name+'.w', True); copy(layer.bias, pre+name+'.b')
                for name in ('fc','proj'):
                    layer = getattr(block.mlp, name)
                    copy(layer.weight, pre+name+'.w', True); copy(layer.bias, pre+name+'.b')
    return model, chars

def configure_optimizers(model, weight_decay, lr=.0003):
    decay, no_decay = [], []
    for name, parameter in model.named_parameters():
        if not parameter.requires_grad: continue
        if parameter.ndim >= 2 and name not in ('token.weight','position.weight'): decay.append(parameter)
        else: no_decay.append(parameter)
    return torch.optim.AdamW([{'params': decay, 'weight_decay': weight_decay},
                              {'params': no_decay, 'weight_decay': 0.}], lr=lr, betas=(.9,.95))

def save_checkpoint(path, model, characters):
    if len(characters) != model.config['vocab']: raise ValueError('vocabulario inconsistente')
    torch.save({'config': model.config, 'characters': list(characters), 'state_dict': model.state_dict()}, path)

def load_checkpoint(path, map_location='cpu'):
    state = torch.load(path, map_location=map_location, weights_only=True)
    model = TorchGPT(**state['config']).to(device=map_location, dtype=state['state_dict']['token.weight'].dtype)
    model.load_state_dict(state['state_dict'], strict=True)
    if len(state['characters']) != model.config['vocab']: raise ValueError('vocabulario inconsistente')
    return model, state['characters']
'''
scope={};exec(compile(source,'gpt_pytorch.py','exec'),scope)

class RMS(nn.Module):
    def __init__(self,d,fused):
        super().__init__();self.weight=nn.Parameter(torch.ones(d));self.fused=fused
    def forward(self,x):
        shape=x.shape;flat=x.reshape(-1,shape[-1]).contiguous()
        if self.fused: y=rms_op(flat,self.weight,1e-5)[0]
        else: y=flat*torch.rsqrt(flat.square().mean(-1,keepdim=True)+1e-5)*self.weight
        return y.reshape(shape)

def make(fused):
    net=scope['TorchGPT'](vocab=4096,context=128,width=128,layers=2,heads=4,dropout=0).cuda()
    for block in net.blocks:
        block.n1=RMS(128,fused).cuda();block.n2=RMS(128,fused).cuda()
    net.final=RMS(128,fused).cuda()
    return net

def loss(net,ids,targets,fused):
    b,t=ids.shape
    x=net.embedding_dropout(net.token(ids)+net.position(torch.arange(t,device=ids.device))[None,:,:])
    for block in net.blocks:x=block(x)[0]
    x=net.final(x).reshape(-1,net.config['width']).contiguous(); y=targets.reshape(-1).contiguous()
    if fused:return ce_op(x,net.token.weight,y)[0].mean()
    return F.cross_entropy(F.linear(x,net.token.weight),y)

def run(fused,state,ids,targets):
    net=make(fused);net.load_state_dict(state);opt=torch.optim.AdamW(net.parameters(),lr=1e-4)
    timings=[];peaks=[];values=[]
    for step in range(4):
        opt.zero_grad(set_to_none=True);torch.cuda.synchronize();torch.cuda.reset_peak_memory_stats()
        start=time.perf_counter();value=loss(net,ids,targets,fused);value.backward();opt.step();torch.cuda.synchronize()
        if step:
            timings.append(time.perf_counter()-start);peaks.append(torch.cuda.max_memory_allocated());values.append(value.item())
    print('fused',fused,'losses',values,'tokens/s',ids.numel()/(sum(timings)/len(timings)),
          'peak allocated bytes',max(peaks),flush=True)
    return values

if __name__=='__main__':
    torch.manual_seed(61);baseline=make(False);state={k:v.detach().clone() for k,v in baseline.state_dict().items()};del baseline
    ids=torch.randint(4096,(2,128),device='cuda');targets=torch.randint(4096,(2,128),device='cuda')
    print('device',torch.cuda.get_device_name(),'torch',torch.__version__,'FP32',flush=True)
    reference=run(False,state,ids,targets);fused=run(True,state,ids,targets)
    for a,b in zip(reference,fused):
        assert abs(a-b)<0.02,(a,b)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

One shared run gave equal losses over the three measured steps. Allocated peak was 50791424 bytes in the dense arm and 40576512 bytes with fused operators; observed rates were approximately 18422 and 7064 tokens/s. This educational kernel saved memory in that case and was slower; the result does not generalize to other shapes. Measured peak includes the process’s live allocations and tied weights, not just logits.

Exercises

Numeric
How many bytes does an FP32 logits matrix occupy for batch 8, length 4096 and vocabulary 128256?
Numeric
Calculate FLOP/byte for one FP16 iteration of a tile with BLOCK_M = BLOCK_N = 128 and BLOCK_K = 32, counting two FLOPs per multiply-add and only reads of A and B.
Proof
Prove: RMSNorm backward contains a direct term and another coupling the entire row.
0
Let r = (mean of x² + ε)^(-1/2), y_j = g_j x_j r and u_j = g_j dL/dy_j.

Step 1 of 3. What is dr/dx_j?

Quiz
When is avoiding full logits most likely to help memory capacity?
Code
Implement rmsnorm_fwd and rmsnorm_bwd kernels for a contiguous row. The first writes output and inverse root; the second writes dx and one partial contribution to dg per row. Tests sum those contributions in a second phase and compare with BF16 autograd.
import os
os.environ['TRITON_DISABLE_LINE_INFO']='1'
import triton
import triton.language as tl
@triton.jit
def rmsnorm_fwd(X,G,Y,R,D:tl.constexpr,E:tl.constexpr,B:tl.constexpr):
  pass
@triton.jit
def rmsnorm_bwd(DY,X,G,R,DX,P,D:tl.constexpr,B:tl.constexpr):
  pass
Shift+Enter to run
Key idea
Fusion saves traffic or materialization when it preserves results and derivatives; each advantage depends on shapes, accumulation, operator registration, and real measurement.