Module contents
Lesson 25 of 28Advanced 115 min

Quantization III: few bits, rotations, QAT and kernels

Compare low-bit formats, use Hadamard rotations, train with simulated quantization, quantize a KV cache and optimizer states, and measure a teaching W4A16 Triton kernel on the local GPU.

After this lesson you can

  • Construct NF4, FP4 E2M1 and MXFP4 and compare errors on approximately normal weights.
  • Explain and apply randomized Hadamard rotations to reduce incoherence before quantization.
  • Train using simulated quantization, straight-through estimation and learnable scales.
  • Quantize KV cache with keys per channel and values per token and assess memory and quality effects.
  • Implement a W4A16 matmul in Triton with register dequantization and measure its performance across batch sizes.

Before you start

Four bits are not a single format

Reducing BF16 to four bits cuts nominal weight storage by a factor of four. Metadata, unquantized layers and the KV cache also occupy memory. A compact format speeds execution only if the kernel can use it without spending more time on conversions than it saves reading memory.

Low-bit formats distribute their codes differently. Uniform INT4 assigns equally spaced levels; NF4 uses a table derived from normal quantiles; FP4 E2M1 assigns sign, exponent and mantissa. The figure compares a real sample of 64 weights from the first row of q_proj in SmolLM2-135M, revision 93efa2f097d58c2a74874c7e644dbc9b0cee75a2. The sample does not guarantee normality or represent the full model.

InteractiveThree grids for one block

Histogram and levels of 64 real weights from one row with a shared scale.

SymmetricNF4FP4−1.5 × maximum+1.5 × maximum

Symmetric INT4 and E2M1 have two zero codes or an unused code; their 15 distinct values are drawn. NF4 has 16 values.

1.00
MSE Symmetric INT40.002151
MSE NF40.001292
MSE FP4 E2M10.001574
Adjust the shared scale and compare levels and squared error on the same 64 weights.

NF4 is a table of 16 values, not an exponent field. QLoRA constructs it from normal quantiles, an exact zero and normalization. The specific table used here is the one published by bitsandbytes. The normal assumption motivates the grid but does not guarantee it wins for every block or that minimizing weight MSE minimizes task loss. The figure uses the same maximum scale to compare grids; it does not optimize a different scale for each.

In E2M1 the 16 codes include two signed zeros. Its distinct finite values are 00, ±0.5\pm0.5, ±1\pm1, ±1.5\pm1.5, ±2\pm2, ±3\pm3, ±4\pm4 and ±6\pm6 before applying a scale. This E2M1 convention should not be confused with other tables called FP4. MXFP4 combines E2M1 with an E8M0 scale shared by 32 elements. NVFP4 uses E4M3 scales per 16 elements and an FP32 scale per tensor in its one-dimensional recipe; there are variants for weights in two-dimensional blocks. These are different formats and recipes with different hardware requirements.

An NF4 group of 64 weights with an FP32 scale ideally costs 4+32/64=4.54+32/64=4.5 bits per weight. If an 8-bit quantized scale is stored per group and another FP32 scale per 256 scales, ideal cost is 4+8/64+32/(64⋅256)≈4.1274+8/64+32/(64\cdot256)\approx4.127 bits. This illustrates double quantization of scales; alignment and additional metadata can increase actual size. The k-quants formats in llama.cpp group values and metadata in their own designs: the format suffix alone does not turn each weight into a uniform integer of the same bit width.

Block shape changes the comparison. A very large absolute maximum stretches any grid scaled by it, so many small weights share few levels. Reducing the scale makes levels denser near zero, but values outside the interval are clipped. Total error combines both effects. Comparing formats requires fixing block size, scale selection, rounding criterion and evaluation set; choosing an optimal scale for each format answers a different question from applying the same maximum scale to all.

In the figure, FP4 levels are normalized by dividing by six and multiplying by block scale. That normalization helps visual comparison, but does not itself define an MXFP4 or NVFP4 file. Their scales have specific representation, granularity and rules, and must also be stored. The lab shows a simple way to choose a power-of-two scale for MXFP4; it does not handle all the standard’s special cases.

Rotate before quantizing

An incoherence rotation distributes energy across coordinates before applying a block grid. If QQ is orthogonal, Q⊤Q=IQ^\top Q=I, and a layer computes y=Wxy=Wx, then y=(WQ⊤)(Qx)y=(WQ^\top)(Qx) in exact arithmetic. Norms are preserved, but coordinate maxima and rounding error can change.

InteractiveSpread an outlier

Magnitude by coordinate: original vector and rotated vector.

Before

After

Energy is preserved; error is computed in each basis with one scale per vector. The real row comes from SmolLM2-135M’s q projection and does not represent all layers.

8.0
Maximum before / after8.24 / 1.88
INT4 MSE before / after0.04438 / 0.00693
Real-row incoherence before / after3.17 / 3.04
Change an outlier in a toy vector and compare quantization and incoherence of a real row before and after Hadamard.

The normalized Walsh-Hadamard matrix is constructed recursively and can be applied with additions and subtractions in O(dlog⁡d)O(d\log d) for power-of-two dd. Multiplying by chosen signs before the transform changes orientation without changing the norm. The figure uses a deterministic sign pattern; displayed incoherence is d∥w∥∞/∥w∥2\sqrt d\|w\|_\infty/\|w\|_2 for one weight row. A reduction in one example is not a guarantee for every vector. QuIP# uses incoherence transforms and codebooks; QuaRot and SpinQuant explore rotations for LLM quantization, the latter with learned rotations.

Proof

The first identity follows from Q⊤Q=IQ^\top Q=I. The Euclidean norm of QxQx equals that of xx, so both normalizations have the same denominator and equality follows by linearity. An arbitrary diagonal gain does not generally commute with QQ; it must be handled or absorbed compatibly. Nonlinearities and residual branches also constrain moving a rotation across a whole block.

∎

The preceding equality holds before quantization. Quantizing both factors introduces error and the full function must be measured. If rotation is calculated at each step and not fused or efficiently implemented, its cost can exceed the gain. The lab compares a toy vector and layer; it does not attribute an unmeasured time saving to the real model.

A signal with only one nonzero component illustrates the mechanism: after a normalized Hadamard, its magnitude is spread across dd coordinates of magnitude ∣a∣/d|a|/\sqrt d. The norm remains ∣a∣|a|, but the maximum falls. For a general vector, sums can interfere constructively or destructively; randomized signs are therefore used and probabilistic dispersion guarantees studied. A particular sign pattern can produce a better or worse result on one sample. Group quantization also depends on how coordinates are divided after rotation.

To check an integration, first calculate the original and rotated products without rounding, with the same dimensions and order of factors. Then quantize both operands and compare outputs, not just activation maxima. If a representation feeding several branches is rotated, all must receive a consistent transformation. An operation that does not commute with QQ may require explicitly applying the rotation or redesigning its insertion point.

Training with rounding in the loop

Quantization-aware training retains higher-precision latent parameters but uses quantized and dequantized values in the forward pass. For scale s>0s>0, w^=s clip⁡(round⁡(w/s),qmin⁡,qmax⁡)\hat w=s\,\operatorname{clip}(\operatorname{round}(w/s),q_{\min},q_{\max}). The true derivative of rounding is zero almost everywhere: the straight-through estimator substitutes that derivative to carry a training signal. It is a gradient approximation, not the exact derivative of the step function.

InteractiveA surrogate derivative

Target 1.5, initial weight 4.2, grid from −3 to 3 times the scale. Lines show latent weight and its quantized value over 40 steps.

040

Blue: latent weight. Orange: quantized. Dashed line: target. The scale’s surrogate derivative follows LSQ with normalization for this single weight.

0
Latent weight4.200
Quantized weight3.000
Scale1.000
Loss1.1250
Compare clipped and identity STE and enable scale learning in a toy scalar loss.

A clipped STE passes the weight gradient inside the representable region and zeros it outside; an identity STE can move a saturated weight even when its quantized value has not yet changed. LSQ learns step size using a surrogate derivative and scales its gradient by element count and range. For u=w/su=w/s, within range the approximate contribution to ∂w^/∂s\partial\hat w/\partial s is round⁡(u)−u\operatorname{round}(u)-u; outside it is the grid endpoint. The example scales that gradient for one weight, not a reproduction of a large-scale training recipe.

The positive scale simultaneously controls resolution and range. Reducing it brings levels closer around zero but saturates earlier; increasing it expands the interval at the cost of a coarser step. LSQ’s contribution inside the interval subtracts the normalized value from its rounded code; in saturation output changes proportionally to the grid endpoint as scale changes. The approximate scale gradient is aggregated across elements sharing it and normalized to prevent its magnitude growing uncontrollably with tensor size.

The figure deliberately starts with an out-of-range weight. With fixed scale and clipped STE, that weight receives no gradient and is trapped; with identity STE it can return toward the interval. If scale is learned, quantized output can change even when the latent weight does not move. No scalar trajectory determines which estimator is better for a full network: activations, initialization, optimizer and other weights interact.

Calibration, learning rate and saturation affect the result. LLM-QAT uses data generated by the model itself to adapt quantizers when original data is unavailable: that does not mean training with no input data. Ternary quantization from training is another option: BitNet b1.58 studies ternary weights {−1,0,1}\{-1,0,1\} and takes its name from log⁡23≈1.585\log_2 3\approx1.585 bits of information per symbol. Practical storage may need more for packing and scales; the number also does not imply activations and other states are ternary.

The cache grows too

KV cache quantization reduces memory per token and may allow more simultaneous sequences if freed memory is the limiting resource. Effective reduction includes scales, fragmentation, the unquantized recent window and other tensors. KIVI studies keys per channel across tokens and values per token across channels, with a higher-precision recent region before forming groups. The choice reflects observed distributions and effects of errors on attention; it is not a universal theorem for every head or prompt.

InteractiveKV quantization axes

Quantized keys: 32 tokens × first 32 dimensions

Quantized values: 32 tokens × first 32 dimensions

Blue: positive; orange: negative. Computation uses all 64 dimensions and the last query after RoPE; maps show 32. Affine scale per full group, without residual window.

2
Attention output MSE0.0000366
Attention TV distance0.10802
Try bits and axes on real keys and values; compare attention distribution and output with the reference.

The data come from layer 0, query head 0 and KV head 0 of SmolLM2-135M, revision pinned above, for the prompt “A quantized neural network maps numbers to a finite grid. The grid is chosen using representative calibration data. A model predicts the next token from the previous context.” Thirty-two tokens, keys and query after RoPE, and values were saved in FP32. The figure computes attention of the last query across all 64 dimensions; its maps show the first 32. It quantizes complete groups with affine minimum and maximum and does not reproduce KIVI’s residual window or kernels. Output MSE and total variation distance of probabilities measure this single attention operation, not general generation quality.

FP8 cache offers another tradeoff between range, precision and hardware compatibility. For long context, check attention and generation on long sequences and measure throughput, latency and memory in the specific engine. Saving half the cache bytes does not necessarily double concurrency: the model, temporary memory and per-request budget also matter.

A scale’s axis determines which values share its range. In a token-by-channel matrix, quantizing keys per channel groups one dimension across time, while quantizing values per token groups dimensions of each position. For query qq, keys first affect logits qK⊤/dqK^\top/\sqrt d and, through softmax, which tokens receive attention; values affect the subsequent weighted sum. Thus the same input MSE can yield different errors. The figure shows both distance between attention distributions and output MSE, which answer different questions.

During decoding, one token’s keys and values are added at a time. A group requiring several tokens is not yet complete when the latest arrives; temporarily keeping a region at higher precision lets the group form without continually requantizing history. Its size and metadata must be included in memory accounting. A test on 32 tokens and one head helps understand axes, but does not validate a policy for a whole model or behavior with millions of tokens.

Multiply without unpacking all weights

Weight dequantization kernels can read two 4-bit codes per byte, extract each nibble and apply a scale per group while computing the product with FP16 activations. Marlin combines packing and computational organization for W4A16 inference. A teaching implementation without its optimizations does not inherit its results.

For an ideal weight-read-bound calculation, FP16 needs 16 bits per weight and W4 with one FP16 scale per 128 weights needs 4+16/128=4.1254+16/128=4.125 bits. The ratio 16/4.125≈3.8816/4.125\approx3.88 is a ceiling for that part of traffic, not total speedup: activations, output, scale accesses, unpacking and computation still cost time. As batch size grows, weights are reused and compute may dominate. The local lab measures this interaction on the available machine; do not extrapolate time from one batch or shared GPU to production.

In the code, the first value of each pair occupies the low nibble and the second the high one. Eight is added to the signed integer to obtain codes from zero to fifteen; the kernel reverses that offset before multiplying by the scale. The test compares against a matrix reconstructed from the same bytes and scales, detecting packing errors independently of quantization error against original weights. FP32 accumulation and FP16 output do not require a bitwise match with another matmul implementation: operation and rounding order may vary.

Timing comparisons must synchronize the GPU, warm up both paths, repeat measurements and state dimensions and precision. Measure format preparation separately from repeated execution: packing once and reusing many times represents a different situation from quantizing on every call. The prototype teaches the data path but does not include Marlin’s specialized design or aim to compete with an optimized library.

8-bit optimizer states apply the same idea to training. Adam keeps means and second moments per parameter; quantizing them by block reduces storage, but they must be reconstructed for updates and blocks with very different ranges handled. 8-bit Optimizers studies block quantization and stability mechanisms. Gradients, master parameters and activations still occupy memory, so total savings do not equal savings in those two states.

NumPy lab

Four grids are compared on simulated normal weights, a signed Hadamard and a small network trained with simulated quantization and learnable scales. Training and test sets differ, though they come from the same synthetic distribution. The MXFP4 implementation uses blocks of 32, E2M1 and a power-of-two scale rounded upward; it omits special scale cases and is not intended as a full standard serializer. The toy cache illustrates axes and does not replace the figure’s real sample.

The last calculation packs four two-bit codes per byte and stores FP32 minima and scales. It checks that unpacking reproduces dequantized values, measures one attention error and counts bytes in those arrays. Capacity under a 64 KiB budget is an ideal division for this fixed cache shape: it does not measure concurrent requests or include model, recent cache, fragmentation or engine buffers.

[ ]Formats, rotation, QAT and cacheBrowser
import numpy as np
from scipy.special import ndtri

# Cuantiles asimétricos de NF4 con un cero exacto, como la tabla de QLoRA.
offset=.9677083
positive=ndtri(np.linspace(.5,offset,9))[1:]
negative=ndtri(np.linspace(.5,offset,8))[1:]
nf4=np.r_[-negative[::-1],0.,positive]
nf4/=np.max(np.abs(nf4))
fp4=np.array([-6,-4,-3,-2,-1.5,-1,-.5,0,.5,1,1.5,2,3,4,6.])/6
int4=np.arange(-7,8)/7
def nearest(x,levels):
    return levels[np.argmin(np.abs(x[...,None]-levels),axis=-1)]
def quant_blocks(x,levels,block=64):
    b=x.reshape(-1,block)
    scale=np.maximum(np.max(np.abs(b),axis=1,keepdims=True),1e-12)
    return (nearest(b/scale,levels)*scale).reshape(x.shape)
def mxfp4(x):
    b=x.reshape(-1,32)
    scale=2.**np.ceil(np.log2(np.maximum(np.max(np.abs(b),axis=1,keepdims=True)/6,1e-12)))
    return (nearest(b/scale,fp4*6)*scale).reshape(x.shape)
rng=np.random.default_rng(25)
w=rng.normal(size=(128,64))
for name,quant in [('INT4',lambda x:quant_blocks(x,int4)),('NF4',lambda x:quant_blocks(x,nf4)),('FP4',lambda x:quant_blocks(x,fp4)),('MXFP4',mxfp4)]:
    print(name,'MSE',round(np.mean((w-quant(w))**2),6))

def hadamard(x):
    n=x.shape[-1]
    if n<1 or n&(n-1): raise ValueError('longitud potencia de dos')
    y=x.copy().astype(float);h=1
    while h<n:
        blocks=y.reshape(*y.shape[:-1],-1,2*h)
        a=blocks[...,:h].copy();b=blocks[...,h:].copy()
        blocks[...,:h]=a+b;blocks[...,h:]=a-b;h*=2
    return y/np.sqrt(n)
signs=rng.choice([-1.,1.],size=64)
v=np.zeros(64);v[3]=12.;v+=rng.normal(size=64)*.2
rot=hadamard(v*signs)
assert np.allclose(hadamard(rot)*signs,v)
print('Hadamard norma',round(np.linalg.norm(v),5),round(np.linalg.norm(rot),5),'máximos',round(np.max(np.abs(v)),4),round(np.max(np.abs(rot)),4))
print('MSE vector original y rotado:',round(np.mean((v-quant_blocks(v,int4))**2),6),round(np.mean((rot-quant_blocks(rot,int4))**2),6))

W=rng.normal(size=(16,64))*.2
inputs=rng.normal(size=(128,64));inputs[:,3]*=8
rot_W=hadamard(W*signs);rot_inputs=hadamard(inputs*signs)
assert np.allclose([email protected],rot_inputs@rot_W.T)
before=quant_blocks(inputs,int4)@quant_blocks(W,int4).T
after=quant_blocks(rot_inputs,int4)@quant_blocks(rot_W,int4).T
[email protected]
print('W4A4 MSE antes/después de rotar:',round(np.mean((before-reference)**2),6),round(np.mean((after-reference)**2),6))

# QAT de un MLP con activaciones y pesos W4A4; escalas actualizadas mediante LSQ.
X=rng.normal(size=(384,8)); teacher=rng.normal(size=(8,1)); Y=np.tanh(X@teacher)
train,xt=X[:320],X[320:]; targets,yt=Y[:320],Y[320:]
W1=rng.normal(size=(8,16))*.2;W2=rng.normal(size=(16,1))*.2
s1,s2,sa=.10,.10,.10
def fake(z,s):return np.clip(np.round(z/s),-7,7)*s
def scale_derivative(z,s):
    u=z/s; return np.where(u < -7,-7,np.where(u>7,7,np.round(u)-u))
def prediction(x):return fake(np.maximum(x@fake(W1,s1),0),sa)@fake(W2,s2)
def loss(x,y):return float(np.mean((prediction(x)-y)**2))
initial=(loss(train,targets),loss(xt,yt))
for step in range(400):
    w1=fake(W1,s1);w2=fake(W2,s2);h=train@w1;a=np.maximum(h,0);aq=fake(a,sa)
    dy=2*(aq@w2-targets)/len(train)
    gw2=aq.T@dy;[email protected]
    ga=gaq*(np.abs(a/sa)<=7);gh=ga*(h>0);gw1=train.T@gh
    ds1=np.sum(gw1*scale_derivative(W1,s1))/np.sqrt(W1.size*7)
    ds2=np.sum(gw2*scale_derivative(W2,s2))/np.sqrt(W2.size*7)
    dsa=np.sum(gaq*scale_derivative(a,sa))/np.sqrt(a.size*7)
    W1-=.03*gw1*(np.abs(W1/s1)<=7);W2-=.03*gw2*(np.abs(W2/s2)<=7)
    s1=max(.002,s1-.003*ds1);s2=max(.002,s2-.003*ds2);sa=max(.002,sa-.003*dsa)
print('QAT MSE inicial train/test',np.round(initial,5),'final',round(loss(train,targets),5),round(loss(xt,yt),5),'escalas',np.round([s1,s2,sa],4))

# Caché de ejemplo: claves con dos canales amplificados; valores por token.
K=rng.normal(size=(32,16));K[:,[2,11]]*=8
V=rng.normal(size=(32,16));q=rng.normal(size=16)
def affine(x,bits,axis):
    lo=x.min(axis=axis,keepdims=True);hi=x.max(axis=axis,keepdims=True)
    scale=np.maximum((hi-lo)/(2**bits-1),1e-12)
    return np.clip(np.round((x-lo)/scale),0,2**bits-1)*scale+lo
def attention(k,v):
    score=k@q/np.sqrt(len(q));p=np.exp(score-score.max());p/=p.sum()
    return p@v
reference=attention(K,V)
for axis,name in [(0,'por canal'),(1,'por token')]:
    print('KV 2 bits',name,'error atención',round(float(np.mean((attention(affine(K,2,axis),affine(V,2,axis))-reference)**2)),6))
print('KV ejes distintos: claves por canal, valores por token',round(float(np.mean((attention(affine(K,2,0),affine(V,2,1))-reference)**2)),6))

def pack2(x,axis):
    lo=x.min(axis=axis,keepdims=True).astype(np.float32)
    scale=np.maximum((x.max(axis=axis,keepdims=True)-lo)/3,1e-12).astype(np.float32)
    code=np.clip(np.round((x-lo)/scale),0,3).astype(np.uint8).ravel()
    assert len(code)%4==0
    packed=code[0::4] | (code[1::4]<<2) | (code[2::4]<<4) | (code[3::4]<<6)
    return packed,lo,scale
kp,klo,ks=pack2(K,0);vp,vlo,vs=pack2(V,1)
def unpack2(packed,lo,scale,shape):
    shifts=np.array([0,2,4,6],dtype=np.uint8)
    codes=((packed[:,None]>>shifts)&3).reshape(shape)
    return codes*scale+lo
ku=unpack2(kp,klo,ks,K.shape);vu=unpack2(vp,vlo,vs,V.shape)
assert np.allclose(ku,affine(K,2,0),atol=1e-6)
assert np.allclose(vu,affine(V,2,1),atol=1e-6)
print('MSE atención con caché empaquetada:',round(float(np.mean((attention(ku,vu)-reference)**2)),6))
fp16_bytes=(K.size+V.size)*2
packed_bytes=sum(a.nbytes for a in (kp,klo,ks,vp,vlo,vs))
budget=64*1024
print('bytes caché FP16 / 2 bits con escalas y mínimos:',fp16_bytes,packed_bytes)
print('capacidad ideal con 64 KiB reservados solo a estas cachés:',budget//fp16_bytes,budget//packed_bytes)

Local lab: W4A16 in Triton

This requires a CUDA GPU and installations of PyTorch and Triton able to compile kernels for it. Two codes are packed per byte, with an FP16 scale per group of 128 and symmetric codes from −7-7 to 77. The kernel reads and unpacks each block during multiplication. Input dimensions must be divisible by 128; it is checked against the already dequantized FP16 matrix for batches of 1, 4, 16 and 64. The code measures with warmup and repetitions, but times under shared load vary. It then replaces only down_proj in the first SmolLM2-135M block with the kernel and compares logits with the same quantized matrix dequantized in FP16.

[ ]Packed W4A16 in TritonLocal GPU
import torch, triton, triton.language as tl

@triton.jit
def w4a16(A, P, S, C, M:tl.constexpr, N:tl.constexpr, K:tl.constexpr,
          BM:tl.constexpr, BN:tl.constexpr, BK:tl.constexpr, G:tl.constexpr):
    row = tl.program_id(0)*BM + tl.arange(0,BM)
    col = tl.program_id(1)*BN + tl.arange(0,BN)
    kk = tl.arange(0,BK)
    acc = tl.full((BM,BN),0,tl.float32)
    for start in range(0,tl.cdiv(K,BK)):
        k=start*BK+kk
        a=tl.load(A+row[:,None]*K+k[None,:],mask=(row[:,None]<M)&(k[None,:]<K),other=0)
        byte=tl.load(P+col[None,:]*(K//2)+(k[:,None]//2),mask=(col[None,:]<N)&(k[:,None]<K),other=0).to(tl.int32)
        code=(byte >> ((k[:,None]%2)*4)) & 15
        scale=tl.load(S+col[None,:]*(K//G)+(k[:,None]//G),mask=(col[None,:]<N)&(k[:,None]<K),other=0)
        b=((code-8).to(tl.float32)*scale.to(tl.float32)).to(tl.float16)
        acc += tl.dot(a,b)
    tl.store(C+row[:,None]*N+col[None,:],acc,mask=(row[:,None]<M)&(col[None,:]<N))

def pack(W,group=128):
    n,k=W.shape
    assert k%group==0 and k%2==0
    blocks=W.float().reshape(n,k//group,group)
    scales=(blocks.abs().amax(-1)/7).clamp_min(torch.finfo(torch.float16).tiny).half()
    codes=(blocks/scales.float().unsqueeze(-1)).round().clamp(-7,7).to(torch.int16).reshape(n,k)+8
    packed=(codes[:,0::2] | (codes[:,1::2]<<4)).to(torch.uint8).contiguous()
    return packed,scales.contiguous()

def unpack(P,S,group=128):
    n,k2=P.shape
    code=torch.empty((n,k2*2),dtype=torch.int16,device=P.device)
    code[:,0::2]=(P&15).to(torch.int16);code[:,1::2]=(P>>4).to(torch.int16)
    return ((code.reshape(n,-1,group)-8)*S[:,:,None]).reshape(n,-1).half()

def matmul(A,P,S,group=128):
    m,k=A.shape;n=P.shape[0];C=torch.empty((m,n),device=A.device,dtype=torch.float16)
    w4a16[(triton.cdiv(m,16),triton.cdiv(n,32))](A,P,S,C,m,n,k,16,32,32,group)
    return C

torch.manual_seed(25)
zero=torch.zeros((1,128),device='cuda',dtype=torch.float16)
zp,zs=pack(zero)
assert torch.all(zs>0) and torch.equal(unpack(zp,zs),zero)
N=K=1024
W=torch.randn((N,K),device='cuda',dtype=torch.float16)*.1
P,S=pack(W); Wq=unpack(P,S)
for M in (1,4,16,64):
    A=torch.randn((M,K),device='cuda',dtype=torch.float16)
    actual=matmul(A,P,S); [email protected]
    err=(actual-reference).abs().max().item()
    assert torch.allclose(actual,reference,rtol=.01,atol=.01)
    t1=triton.testing.do_bench(lambda:matmul(A,P,S),warmup=100,rep=300)
    t2=triton.testing.do_bench(lambda:[email protected],warmup=100,rep=300)
    print('lote',M,'error máximo',err,'triton ms',round(t1,4),'torch FP16 ms',round(t2,4),'razón',round(t2/t1,3),flush=True)

from transformers import AutoModelForCausalLM,AutoTokenizer
model_id='HuggingFaceTB/SmolLM2-135M'; revision='93efa2f097d58c2a74874c7e644dbc9b0cee75a2'
tokenizer=AutoTokenizer.from_pretrained(model_id,revision=revision)
model=AutoModelForCausalLM.from_pretrained(model_id,revision=revision,dtype=torch.float16).cuda().eval()
module=model.model.layers[0].mlp.down_proj
packed,scale=pack(module.weight.detach())
with torch.no_grad():module.weight.copy_(unpack(packed,scale))
ids=tokenizer('A compact model tests a quantized layer.',return_tensors='pt').input_ids.cuda()
with torch.no_grad():base=model(ids,use_cache=False).logits
class W4Linear(torch.nn.Module):
    def __init__(self,packed,scale):
        super().__init__();self.register_buffer('packed',packed);self.register_buffer('scale',scale)
    def forward(self,x):
        shape=x.shape; y=matmul(x.reshape(-1,shape[-1]).contiguous(),self.packed,self.scale)
        return y.reshape(*shape[:-1],self.packed.shape[0])
model.model.layers[0].mlp.down_proj=W4Linear(packed,scale)
with torch.no_grad():test=model(ids,use_cache=False).logits
print('modelo: máxima diferencia de logits',float((test-base).abs().max()),'mismo argmáximo final',bool(test[0,-1].argmax()==base[0,-1].argmax()),flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

An RTX 3060 run found a maximum product difference of 0.0078125 in tested batches. For a short prompt, maximum model logit difference was 0.2109375 and the final argmax matched. This is a limited check of this implementation and precision, not bitwise equality or proof of general quality. Times varied and do not establish a speedup. bitsandbytes was not installed in that environment, so no NF4 measurement from that library is provided.

Comparison with GGUF

The following cell compares quality of two related artifacts on exactly the same first 128 WikiText-2 test tokens: SmolLM2-135M FP32 and the QuantFactory Q4_K_M conversion, with pinned revisions. It requires llama-cpp-python and downloads the GGUF if missing. It checks token ID equality before evaluation, uses an independent window and scores 127 tokens. GGUF indicates Llama architecture and quantization version, but its metadata does not specify the exact source checkpoint revision. The file quantizes the full model under its own rules; this is not the same operation as replacing one projection in the previous kernel. The cell compares perplexity, not CPU and GPU times.

[ ]GGUF and FP32 on the same tokensLocal GPU
import math,torch,numpy as np
import torch.nn.functional as F
from huggingface_hub import hf_hub_download
from datasets import load_dataset
from transformers import AutoTokenizer,AutoModelForCausalLM
from llama_cpp import Llama

repo='QuantFactory/SmolLM2-135M-GGUF';revision='d948db3614be18259a175aafd7689a70f1cb4e2f';filename='SmolLM2-135M.Q4_K_M.gguf'
model_id='HuggingFaceTB/SmolLM2-135M';rev='93efa2f097d58c2a74874c7e644dbc9b0cee75a2';data_rev='b08601e04326c79dfdd32d625aee71d232d685c3'
path=hf_hub_download(repo,filename,revision=revision)
llama=Llama(model_path=path,n_ctx=256,n_batch=128,logits_all=True,verbose=False,n_gpu_layers=0)
for key in ('general.name','general.architecture','general.quantization_version','general.file_type','general.source.url','general.source.repo_url'):
    print(key,llama.metadata.get(key),flush=True)
rows=load_dataset('Salesforce/wikitext','wikitext-2-raw-v1',split='test',revision=data_rev)
text='\n\n'.join(t for t in rows['text'] if t.strip())[:12000]
tokenizer=AutoTokenizer.from_pretrained(model_id,revision=rev)
hf_ids=tokenizer.encode(text,add_special_tokens=False)[:128]
llama_ids=llama.tokenize(text.encode('utf8'),add_bos=False)[:128]
print('mismos primeros 128 tokens:',hf_ids==llama_ids,'cantidad',len(hf_ids),flush=True)
assert hf_ids==llama_ids
llama.eval(llama_ids)
scores=llama.scores[:len(llama_ids)-1,:]
target=np.asarray(llama_ids[1:]);maximum=scores.max(axis=1)
loss=np.mean(maximum+np.log(np.exp(scores-maximum[:,None]).sum(axis=1))-scores[np.arange(len(target)),target])
print('GGUF Q4_K_M CPU PPL:',math.exp(float(loss)),'tokens puntuados',len(target),flush=True)
llama.close()
device='cuda' if torch.cuda.is_available() else 'cpu'
model=AutoModelForCausalLM.from_pretrained(model_id,revision=rev,dtype=torch.float32).to(device).eval()
x=torch.tensor([hf_ids],device=device)
with torch.no_grad():logits=model(x,use_cache=False).logits[:,:-1]
hf_loss=F.cross_entropy(logits.reshape(-1,logits.shape[-1]),x[:,1:].reshape(-1)).item()
print('HF FP32',device,'PPL:',math.exp(hf_loss),'tokens puntuados',len(target),flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In one run of that protocol, PPL for GGUF Q4_K_M on CPU was 22.36 and for the HF FP32 model on GPU was 19.53. The sequence of 128 IDs matched. This sample is too small for general quality evaluation; moreover, it was not verified that the GGUF conversion began from the exact same revision of the reference model.

Exercises

Numeric
NF4 uses 64 weights per 8-bit scale and one FP32 scale per 256 scales. How many ideal bits per weight does it need?
Numeric
If only weight reads count, what is the ideal ratio between FP16 and W4 with FP16 scale per group of 128?
Proof
Prove: Prove layer invariance and its relationship to RMSNorm without gain.
0
Q is orthogonal and W acts on x.

Step 1 of 2. What happens when W becomes WQᵀ and x becomes Qx?

Quiz
What configuration does KIVI study and why keep a recent region at higher precision?
Code
Implement pack_int4 and unpack_int4 for integers from −8 to 7, two per byte: the first in the low nibble. The number of values is even.
import numpy as np
def pack_int4(values):
  pass
def unpack_int4(packed):
  pass
Shift+Enter to run
Code
Implement nf4_quantize(blocks, levels): each row is a block, scaled by its absolute maximum, and each value is approximated by the nearest level. Return dequantized values; a zero block must remain zero.
import numpy as np
def nf4_quantize(blocks, levels):
  pass
Shift+Enter to run
Key idea
Effective precision depends on the grid, scales and distribution; practical gain also depends on how the format is executed and what is measured.