Module contents
Stage 7 of 9Advanced 120 min

Weight-only quantization and its kernel

Implement grouped INT8 and INT4 quantization, activation-based GPTQ-style calibration and a Triton matrix-vector product that dequantizes on the fly; measure quality and speed.

After this lesson you can

  • Implement grouped INT8 and INT4 quantization with two values packed per byte.
  • Implement layerwise GPTQ calibration using an inverse Hessian.
  • Write a Triton matrix-vector kernel with register dequantization.
  • Measure perplexity, task accuracy and tokens per second for each variant.

Before you start

Fewer bytes, different computation

In small-batch decoding, much work can consist of reading weights to multiply by a vector. Weight-only quantization stores a compact representation and dequantizes during computation. Fewer bytes can help when reads limit the step and the kernel exploits the format; proportional speedup is not guaranteed. Unpacking, scales, KV cache, launches and computation also cost time. In prefill, a multi-token batch reuses weights more and the bottleneck can differ.

For a symmetric weight group ww, one possible scale is s=max⁡∣w∣/7s=\max|w|/7 and the int4 code is z=clip⁡(round⁡(w/s),−8,7)z=\operatorname{clip}(\operatorname{round}(w/s),-8,7). Reconstruct w^=sz\hat w=sz. An all-zero group must avoid division by zero. The lab calculates scales per row and column group; other formats use affine zero points, scales of other precision or different groupings.

Two four-bit codes fit in one byte. To store signed codes in the example, add eight; the first occupies the low nibble and the second the high one. On reading, separate nibbles and subtract eight. Packer and kernel order must match. If column count does not complete a group, add and declare padding; those bytes occupy memory even though they do not participate in the product.

With groups of 128 and a 16-bit scale and zero point per group, ideal cost is 4+(16+16)/128=4.254+(16+16)/128=4.25 bits per weight. The lab uses symmetric quantization and stores only an FP16 scale: its ideal count is 4.125 bits per weight before padding and metadata. Do not compare both figures as if the formats were identical. An individual weight can have small error and still yield different output if its multiplying activation is important.

InteractiveA frontier you can measure

The initial points quantize just one SmolLM2 projection and are a short sample. You can edit perplexity and throughput:

BF16
INT8
INT4 rounded
INT4 GPTQ
  • Non-dominated
  • Dominated

Pareto frontier: BF16, INT4 rounded, INT4 GPTQ. A variant is dominated if another has equal or lower perplexity and equal or higher speed, with at least one strict improvement. Compare only measurements using the same model, evaluation set and workload.

128
Bits per INT4 weight4.250
Variants entered4
On the frontier3
Initial points come from the single-projection test below. Enter other measurements with the same model and protocol; the control calculates ideal cost of an affine format.

A variant is dominated if another has equal or lower perplexity and equal or higher throughput, with at least one strict improvement. That frontier depends on entered measurements. Also check task accuracy, actual memory, latency and configuration: similar perplexity does not guarantee retaining retrieval or reasoning capability. Do not turn a one-layer measurement into a conclusion about the full model.

Calibrate with activations

Direct rounding approximately minimizes individual weight error, not necessarily layer-output error. For activations XX and weight matrix WW, the reconstruction objective can be written ∥X(W−W^)⊤∥F2\|X(W-\hat W)^\top\|_F^2. Its curvature matrix is proportional to X⊤XX^\top X. GPTQ uses approximate second-order information to compensate quantization errors; AWQ studies another activation-aware strategy.

For one row and fixed error e=w^i−wie=\hat w_i-w_i in column ii, minimize δ⊤Hδ\delta^\top H\delta subject to δi=e\delta_i=e. With positive-definite HH, a Lagrange multiplier gives δ=eH−1ei/(H−1)ii\delta=e H^{-1}e_i/(H^{-1})_{ii}. Thus correction of other columns depends on the corresponding inverse column. A practical implementation uses factorizations and ordered updates rather than reinverting at every step. Diagonal damping helps when activations do not cover every direction; it does not by itself make calibration data representative.

The code implements a teaching version by columns with Cholesky of the inverse and recalculates scales at each group start. In one synthetic CPU test with correlated activations, squared reconstruction error was 0.1821 for direct rounding and 0.1040 for this correction. That sample only checks example behavior: it does not prove GPTQ always improves a task metric or reproduce all engineering of an optimized library.

Calibration and evaluation must use separate data. Choosing scales or corrections using the same texts used for evaluation favors that set. Even with separation, few samples may not represent the production distribution. Report token count, windows, dataset and precision; when comparing variants, retain everything except quantization method and parameters.

An RTX 3060 test with SmolLM2-135M BF16 replaced only first-layer q_proj. It calibrated with 256 WikiText-2 training tokens and evaluated 512 test tokens in windows of 128, plus 16 SST-2 validation examples. Throughput is a short observation of eight tokens on a shared GPU, not a stable benchmark:

Variant of that projectionPerplexitySST-2 correctTokens/sCalibration reconstruction error
BF1629.2863711/165.3020
Reconstructed INT829.3281011/165.1310.0000085
INT4 rounding29.2827811/164.1400.0027699
Teaching INT4 GPTQ29.2860411/164.3050.0001224

The correction reduced that layer’s calibration-data error, but here did not improve perplexity over rounding or speed generation versus BF16. The task sample is small. Other layers remained BF16 and the code reconstructed the matrix for prefill; these numbers do not establish quality or speed of a fully quantized model.

Dequantize inside the product

The int4 matrix-vector product in Triton loads packed bytes, extracts each nibble, reconstructs signed code and applies group scale. The kernel accumulates in FP32 and does not materialize the entire dequantized matrix in global memory. The lab compares with a PyTorch reference that does reconstruct the matrix, using the same FP16 scale and explicit tolerances. FP16 accumulation can lose precision in long sums.

One local run tested shapes 192×576, 576×576, 1536×576, 576×1536 and 49152×576, corresponding to SmolLM2-135M projections and output head. Maximum absolute error against the reconstructed matrix was 3.06e-5. The kernel uses three autotuning configurations and a reduction in 128-column chunks. This agreement checks test products, not full transformer generation or end-to-end speedup.

Local labs

The first block needs PyTorch CUDA and Triton. It checks packing and products for the five shapes above. If less than 1 GiB is free it skips those matrices and reports this; the check applies only to this experiment. A shared GPU can vary between runs.

[ ]Packing and int4 GEMVLocal GPU
import os
# El ejecutor puede asignar un nombre de celda con acentos; ptxas en Windows
# no acepta esos caracteres en información de líneas. El kernel es el mismo.
os.environ.setdefault('TRITON_DISABLE_LINE_INFO', '1')
import math, torch, triton, triton.language as tl

def quantize(w,bits=4,group=128):
    rows,cols=w.shape;padded=triton.cdiv(cols,group)*group;z=torch.nn.functional.pad(w.float(),(0,padded-cols));groups=z.reshape(rows,-1,group)
    limit=7 if bits==4 else 127;scales=groups.abs().amax(-1).clamp_min(1e-8)/limit;codes=(groups/scales[...,None]).round().clamp(-limit-1,limit).to(torch.int8)
    return codes.reshape(rows,padded),scales.to(torch.float16),cols
def pack_int4(q):
    assert q.dtype==torch.int8 and q.shape[-1]%2==0 and bool(((q>=-8)&(q<=7)).all())
    x=(q.to(torch.int16)+8).to(torch.uint8);return x[...,0::2]|(x[...,1::2]<<4)
def unpack_int4(p):
    low=(p&15).to(torch.int16)-8;high=((p>>4)&15).to(torch.int16)-8
    return torch.stack((low,high),dim=-1).reshape(*p.shape[:-1],p.shape[-1]*2).to(torch.int8)

def gptq(w,X,group=128):
    m,k=w.shape;padded=math.ceil(k/group)*group;H=(X.T@X)/X.shape[0];H.diagonal().add_(H.diagonal().mean()*0.01+1e-6)
    chol=torch.linalg.cholesky(H);inv=torch.cholesky_inverse(chol);U=torch.linalg.cholesky(inv,upper=True);work=w.clone();codes=torch.zeros((m,padded),device=w.device,dtype=torch.int8);scales=torch.empty((m,padded//group),device=w.device,dtype=torch.float16)
    for start in range(0,k,group):
        end=min(start+group,k);scale=(work[:,start:end].abs().amax(-1).clamp_min(1e-8)/7).to(torch.float16);scales[:,start//group]=scale
        for col in range(start,end):
            q=(work[:,col]/scale.float()).round().clamp(-8,7);codes[:,col]=q.to(torch.int8);quant=q*scale.float();error=(work[:,col]-quant)/U[col,col]
            work[:,col:]-=error[:,None]*U[col,col:][None,:]
    return codes,scales

@triton.autotune(configs=[triton.Config({'BM':1},num_warps=4),triton.Config({'BM':4},num_warps=4),triton.Config({'BM':8},num_warps=8)],key=['M','K'])
@triton.jit
def int4_gemv(P,S,X,Y,M:tl.constexpr,K:tl.constexpr,PK:tl.constexpr,G:tl.constexpr,BM:tl.constexpr,BK:tl.constexpr=128):
    row=tl.program_id(0)*BM+tl.arange(0,BM);k=tl.arange(0,BK);acc=tl.full((BM,),0.,tl.float32)
    for start in range(tl.cdiv(K,BK)):
        col=start*BK+k;byte=tl.load(P+row[:,None]*(PK//2)+col[None,:]//2,mask=(row<M)[:,None]&(col<K)[None,:],other=0).to(tl.int32)
        q=tl.where((col%2)[None,:]==0,byte&15,(byte>>4)&15)-8
        scale=tl.load(S+row[:,None]*(PK//G)+(col//G)[None,:],mask=(row<M)[:,None]&(col<K)[None,:],other=0).to(tl.float32)
        x=tl.load(X+col,mask=col<K,other=0).to(tl.float32);acc+=tl.sum(q.to(tl.float32)*scale*x[None,:],1)
    tl.store(Y+row,acc,mask=row<M)

def gemv(packed,scales,x,cols,group=128):
    rows=packed.shape[0];out=torch.empty(rows,device=x.device,dtype=torch.float32);pk=packed.shape[1]*2
    int4_gemv[lambda meta:(triton.cdiv(rows,meta['BM']),)](packed,scales,x,out,M=rows,K=cols,PK=pk,G=group)
    return out

def demo():
    torch.manual_seed(97);assert torch.cuda.is_available();torch.set_num_threads(1)
    free,_=torch.cuda.mem_get_info()
    if free<1*2**30:print('Kernel: no ejecutado; se recomienda 1 GiB libre para las matrices de prueba');return
    for m,k in [(192,576),(576,576),(1536,576),(576,1536),(49152,576)]:
        w=torch.randn(m,k,device='cuda');q,s,_=quantize(w);packed=pack_int4(q);assert torch.equal(unpack_int4(packed),q)
        x=torch.randn(k,device='cuda');dequant=(q.reshape(m,-1,128).float()*s.float()[...,None]).reshape(m,-1)[:,:k]
        got=gemv(packed,s,x,k);ref=dequant@x;torch.cuda.synchronize();err=float((got-ref).abs().max())
        print('forma',m,k,'error máx',err,'int4 bytes',packed.numel(),'escalas bytes',s.numel()*s.element_size(),flush=True)
        assert torch.allclose(got,ref,atol=.01,rtol=.002)
if __name__=='__main__':demo()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The second block is prepared to calibrate the first-layer query projection using 256 WikiText-2 train tokens and evaluate WikiText-2 test windows and 16 SST-2 validation examples. It quantizes one projection, not the full model. INT8 is reconstructed in BF16; INT4 uses the kernel in decode and a reconstructed matrix for prefill. PyTorch, Transformers, Datasets and cached files are required; the block requires 1.5 GiB free for this short test. If memory is insufficient it skips evaluation and produces no figures.

[ ]Calibration and quality of one projectionLocal GPU
import torch
if not torch.cuda.is_available() or torch.cuda.mem_get_info()[0] < 1.5*2**30:
    print('Calidad no ejecutada: se requiere CUDA y al menos 1.5 GiB libres para este ensayo')
else:
    import json, math, os, tempfile, time, numpy as np, torch
    import torch.nn as nn, torch.nn.functional as F
    from datasets import load_dataset
    from transformers import AutoModelForCausalLM,AutoTokenizer
    torch.set_num_threads(1);torch.manual_seed(71);assert torch.cuda.is_available();dev='cuda'
    free_bytes,total_bytes=torch.cuda.mem_get_info();print('GPU libre GiB',round(free_bytes/2**30,2),'total GiB',round(total_bytes/2**30,2),flush=True)
    if free_bytes<1.5*2**30:raise RuntimeError('Se requieren al menos 1.5 GiB libres para esta prueba corta; reintenta cuando haya memoria disponible')
    name='HuggingFaceTB/SmolLM2-135M';revision='93efa2f097d58c2a74874c7e644dbc9b0cee75a2'
    tok=AutoTokenizer.from_pretrained(name,revision=revision,local_files_only=True)
    model=AutoModelForCausalLM.from_pretrained(name,revision=revision,local_files_only=True,dtype=torch.bfloat16).eval().cuda()
    train=load_dataset('Salesforce/wikitext','wikitext-2-raw-v1',split='train');test=load_dataset('Salesforce/wikitext','wikitext-2-raw-v1',split='test');sst=load_dataset('stanfordnlp/sst2',split='validation')
    def text_tokens(dataset,n):
        text='\n'.join(x['text'] for x in dataset if x['text'].strip());return tok(text,return_tensors='pt').input_ids[:,:n].to(dev)
    cal=text_tokens(train,256);evaluation=text_tokens(test,512);assert cal.shape[1]==256 and evaluation.shape[1]==512
    original=model.model.layers[0].self_attn.q_proj;w=original.weight.detach().float().clone();observed=[]
    def capture(module,args):observed.append(args[0].detach().reshape(-1,args[0].shape[-1]).float())
    handle=original.register_forward_pre_hook(capture)
    with torch.inference_mode():
        for i in range(0,256,64):model(input_ids=cal[:,i:i+64],use_cache=False)
    handle.remove();X=torch.cat(observed);assert X.shape==(256,w.shape[1])
    
    def reconstruct(q,s,k):return (q.reshape(q.shape[0],-1,128).float()*s.float()[...,None]).reshape(q.shape[0],-1)[:,:k]
    class QuantLinear(nn.Module):
        def __init__(self,q,s,k,bits):
            super().__init__();self.k=k;self.bits=bits;self.register_buffer('dense',reconstruct(q,s,k).to(torch.bfloat16));self.register_buffer('scales',s)
            if bits==4:self.register_buffer('packed',pack_int4(q))
        def forward(self,x):
            if self.bits==4 and x.numel()==self.k:
                return gemv(self.packed,self.scales,x.reshape(-1).contiguous(),self.k).to(x.dtype).reshape(*x.shape[:-1],-1)
            return F.linear(x,self.dense)
    
    def perplexity():
        total=0.;count=0
        with torch.inference_mode():
            for i in range(0,evaluation.shape[1],128):
                ids=evaluation[:,i:i+128];logits=model(input_ids=ids,use_cache=False).logits[:,:-1].float();targets=ids[:,1:]
                total+=float(F.cross_entropy(logits.reshape(-1,logits.shape[-1]),targets.reshape(-1),reduction='sum'));count+=targets.numel()
        return math.exp(total/count),count
    pos=tok.encode(' positive',add_special_tokens=False);neg=tok.encode(' negative',add_special_tokens=False);assert len(pos)==len(neg)==1
    def accuracy():
        good=0;n=16
        with torch.inference_mode():
            for row in sst.select(range(n)):
                ids=tok('Review: '+row['sentence']+'\nSentiment:',return_tensors='pt',truncation=True,max_length=160).input_ids.to(dev)
                logits=model(input_ids=ids,use_cache=False).logits[0,-1].float();pred=int(logits[pos[0]]>logits[neg[0]]);good+=int(pred==row['label'])
        return good,n
    def throughput():
        ids=evaluation[:,:32]
        with torch.inference_mode():
            cache=model(input_ids=ids,use_cache=True).past_key_values;token=torch.tensor([[42]],device=dev)
            for _ in range(2):model(input_ids=token,past_key_values=cache,use_cache=True);cache.crop(-1)
            torch.cuda.synchronize();start=time.perf_counter()
            for _ in range(8):model(input_ids=token,past_key_values=cache,use_cache=True);cache.crop(-1)
            torch.cuda.synchronize();return 8/(time.perf_counter()-start)
    
    @torch.inference_mode()
    def main():
        print('GPU',torch.cuda.get_device_name(),'modelo',name,'calibración train 256 tokens, evaluación test 512 tokens, SST-2 validación 16',flush=True)
        q4,s4,k=quantize(w,bits=4);q8,s8,_=quantize(w,bits=8);qg,sg=gptq(w,X)
        variants=[('bf16',None),('int8 reconstruido',QuantLinear(q8,s8,k,8)),('int4 redondeo',QuantLinear(q4,s4,k,4)),('int4 GPTQ capa 0',QuantLinear(qg,sg,k,4))]
        rows=[]
        for label,replacement in variants:
            model.model.layers[0].self_attn.q_proj=original if replacement is None else replacement
            ppl,count=perplexity();good,n=accuracy();rate=throughput();rec=0. if replacement is None else float(((replacement.dense.float()-w)@X.T).square().mean())
            row={'variant':label,'ppl':ppl,'tokens':count,'correct':good,'task_n':n,'tokens_per_s':rate,'calibration_mse':rec};rows.append(row)
            print(label,'ppl',round(ppl,5),'tarea',good,'/',n,'decode tokens/s',round(rate,3),'MSE calibración',round(rec,7),flush=True)
        model.model.layers[0].self_attn.q_proj=original
        out=os.environ.get('P10_L07_OUT') or os.path.join(tempfile.mkdtemp(prefix='p10-l07-'),'evidence.json')
        with open(out,'w',encoding='utf8') as f:json.dump({'gpu':torch.cuda.get_device_name(),'model':name,'rows':rows},f)
        print('resultados guardados en',out)
    if __name__=='__main__':main()
    
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The next test extends comparison to all transformer linear projections and the output head. It retains the input embedding table in BF16 and quantizes a copy of the head, which originally shares those weights. It captures BF16 model activations before quantizing each projection; activations from already quantized layers are not propagated during calibration. Reconstructed matrices serve prefill and the packed kernel serves single-token decode. Both formats remain in memory during evaluation, so this demonstration’s consumption is not that of an optimized INT4 server.

Calibration uses 256 WikiText-2 train tokens, perplexity uses 512 test tokens in windows of 128, and the task uses 16 SST-2 validation examples. These are small checks, not exhaustive evaluation. The experiment can take substantial time; P10_L07_CHECKPOINT_DIR saves per projection and resumes only when model, shape, PyTorch version and activation fingerprint match. P10_L07_FULL_OUT changes the result file. With P10_L07_SKIP_TIMING=1 timing can be skipped temporarily and resumed later from checkpoints. Run the kernel cell first to define quantizer and product.

For speed comparison, the code runs six rounds with all six possible orders of three variants, shuffled with a fixed seed. Between measurements it moves the inactive variant to CPU outside the timer; weight-loading time is excluded from the rate. Each measurement prepares the same 32-token prefix, warms two steps and times eight with CUDA synchronization. It reports samples, median and range, and paired ratios against BF16. These intervals describe observed variation over six rounds, not confidence intervals or server measurements; if the GPU is shared, record that condition and avoid extrapolation.

In one extended comparison, perplexities over 508 predictions were 29.2864 for BF16, 58.5306 for rounded INT4 and 49.5603 for INT4 GPTQ. On the same 16 SST-2 examples they got 11, 15 and 12 correct, respectively. GPTQ improved perplexity over rounding in this sample, while task result did not follow that order; 16 examples cannot establish which generalizes better. Calibration activations came from the BF16 path, not sequential propagation through the already quantized model.

In six rounds with the RTX 3060 shared with other work, median decode rates were 2.654 tokens/s BF16, 2.378 rounding and 2.396 GPTQ. Observed ranges were 2.594 to 2.862, 2.100 to 2.586 and 2.298 to 2.502, respectively. Median paired ratios against BF16 were 0.888 for rounding and 0.886 for GPTQ; their ranges were 0.777 to 0.978 and 0.848 to 0.964. There was no speedup in these six rounds. Contention, BF16 output and the teaching kernel prevent attributing the ratio to a universal property of INT4.

[ ]Quantizing all transformer layersLocal GPU
import os
os.environ.setdefault('TRITON_DISABLE_LINE_INFO','1')
import hashlib, itertools, json, math, random, statistics, tempfile, time, torch
import torch.nn as nn, torch.nn.functional as F
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer

torch.manual_seed(71); torch.set_num_threads(1)
assert torch.cuda.is_available()
name='HuggingFaceTB/SmolLM2-135M'; revision='93efa2f097d58c2a74874c7e644dbc9b0cee75a2'
tok=AutoTokenizer.from_pretrained(name,revision=revision,local_files_only=True)
model=AutoModelForCausalLM.from_pretrained(name,revision=revision,local_files_only=True,dtype=torch.bfloat16).eval().cuda()
train=load_dataset('Salesforce/wikitext','wikitext-2-raw-v1',split='train')
test=load_dataset('Salesforce/wikitext','wikitext-2-raw-v1',split='test')
sst=load_dataset('stanfordnlp/sst2',split='validation')
def text_tokens(data,n):
    rows=[]; chars=0
    for item in data:
        if item['text'].strip():
            rows.append(item['text']);chars+=len(item['text'])+1
            if chars>=16384:break
    return tok('\n'.join(rows),return_tensors='pt',truncation=True,max_length=n).input_ids.cuda()
cal=text_tokens(train,256); evaluation=text_tokens(test,512)
assert cal.shape[1]==256 and evaluation.shape[1]==512
data_hashes={
    'cal_tokens':hashlib.sha256(cal.cpu().numpy().tobytes()).hexdigest(),
    'test_tokens':hashlib.sha256(evaluation.cpu().numpy().tobytes()).hexdigest(),
    'sst16':hashlib.sha256(json.dumps([sst[i] for i in range(16)],ensure_ascii=False,sort_keys=True).encode('utf-8')).hexdigest()
}
print('huellas de datos',data_hashes,flush=True)
modules=[('model.layers.'+path,mod) for path,mod in model.model.layers.named_modules() if isinstance(mod,nn.Linear)]
modules.append(('lm_head',model.lm_head))
assert len(modules)==7*model.config.num_hidden_layers+1 and all(mod.bias is None for _,mod in modules)
print('GPU',torch.cuda.get_device_name(),'proyecciones',len(modules),flush=True)
captures={name:[] for name,_ in modules}
def hook(name):
    def save(module,args): captures[name].append(args[0].detach().reshape(-1,args[0].shape[-1]).float().cpu())
    return save
handles=[mod.register_forward_pre_hook(hook(name)) for name,mod in modules]
with torch.inference_mode():
    for i in range(0,256,64): model(input_ids=cal[:,i:i+64],use_cache=False)
for h in handles: h.remove()
captures={name:torch.cat(xs) for name,xs in captures.items()}
assert all(x.shape[0]==256 for x in captures.values())

def reconstruct(q,s,k):
    return (q.reshape(q.shape[0],-1,128).float()*s.float()[...,None]).reshape(q.shape[0],-1)[:,:k]
class QuantLinear(nn.Module):
    def __init__(self,q,s,k):
        super().__init__();self.k=k
        self.register_buffer('dense',reconstruct(q,s,k).to(torch.bfloat16))
        self.register_buffer('scales',s);self.register_buffer('packed',pack_int4(q))
    def forward(self,x):
        if x.numel()==self.k:
            return gemv(self.packed,self.scales,x.reshape(-1).contiguous(),self.k).to(x.dtype).reshape(*x.shape[:-1],-1)
        return F.linear(x,self.dense)
def set_projection(name,module):
    parent,_,leaf=name.rpartition('.')
    setattr(model.get_submodule(parent) if parent else model,leaf,module)
def evaluate():
    total=0.;count=0
    with torch.inference_mode():
        for i in range(0,512,128):
            ids=evaluation[:,i:i+128]; logits=model(input_ids=ids,use_cache=False).logits[:,:-1].float(); targets=ids[:,1:]
            total+=float(F.cross_entropy(logits.reshape(-1,logits.shape[-1]),targets.reshape(-1),reduction='sum'));count+=targets.numel()
        pos=tok.encode(' positive',add_special_tokens=False);neg=tok.encode(' negative',add_special_tokens=False)
        assert len(pos)==len(neg)==1
        good=0
        for row in sst.select(range(16)):
            ids=tok('Review: '+row['sentence']+'\nSentiment:',return_tensors='pt',truncation=True,max_length=160).input_ids.cuda()
            logits=model(input_ids=ids,use_cache=False).logits[0,-1].float()
            good+=int(int(logits[pos[0]]>logits[neg[0]])==row['label'])
    return {'ppl':math.exp(total/count),'tokens':count,'correct':good,'task_n':16}

def decode_rate():
    cache=model(input_ids=evaluation[:,:32],use_cache=True).past_key_values
    token=torch.tensor([[42]],device='cuda')
    for _ in range(2): model(input_ids=token,past_key_values=cache,use_cache=True);cache.crop(-1)
    torch.cuda.synchronize();start=time.perf_counter()
    for _ in range(8): model(input_ids=token,past_key_values=cache,use_cache=True);cache.crop(-1)
    torch.cuda.synchronize()
    return 8/(time.perf_counter()-start)

results={}; built={}; timings=None
do_timing=os.environ.get('P10_L07_SKIP_TIMING')!='1'
checkpoint_dir=os.environ.get('P10_L07_CHECKPOINT_DIR')
protocol='gptq-v1-group128-bf16'
if checkpoint_dir: os.makedirs(checkpoint_dir,exist_ok=True)
with torch.inference_mode():
    results['bf16']=evaluate();print('bf16',results['bf16'],flush=True)
    for mode in ['redondeo','gptq']:
        replacements=[]
        for i,(path,original) in enumerate(modules):
            w=original.weight.detach()
            xhash=hashlib.sha256(captures[path].numpy().tobytes()).hexdigest()
            checkpoint=os.path.join(checkpoint_dir,f'{mode}-{i:03d}.pt') if checkpoint_dir else None
            if checkpoint and os.path.exists(checkpoint):
                saved=torch.load(checkpoint,map_location='cpu',weights_only=True)
                assert saved['path']==path and saved['revision']==revision and saved['shape']==list(w.shape) and saved['xhash']==xhash and saved['torch']==str(torch.__version__) and saved['protocol']==protocol
                q,s,k=saved['q'].cuda(),saved['s'].cuda(),saved['k']
            else:
                w=w.float();X=captures[path].cuda()
                if mode=='redondeo': q,s,k=quantize(w,bits=4)
                else: q,s=gptq(w,X);k=w.shape[1]
                if checkpoint:
                    tmp=checkpoint+'.tmp'
                    torch.save({'path':path,'revision':revision,'shape':list(w.shape),'xhash':xhash,'torch':str(torch.__version__),'protocol':protocol,'q':q.cpu(),'s':s.cpu(),'k':k},tmp)
                    os.replace(tmp,checkpoint)
            replacement=QuantLinear(q,s,k);set_projection(path,replacement)
            if do_timing: replacements.append((path,replacement))
            if i%20==0: print(mode,i,'/',len(modules),path,flush=True)
        results[mode]=evaluate();print(mode,results[mode],flush=True)
        print('pico CUDA asignado bytes',torch.cuda.max_memory_allocated(),flush=True)
        for path,original in modules:set_projection(path,original)
        if do_timing: built[mode]=[(path,replacement.cpu()) for path,replacement in replacements]
        torch.cuda.empty_cache()
    if do_timing:
        names=['bf16','redondeo','gptq']
        orders=list(itertools.permutations(names));random.Random(71).shuffle(orders)
        samples={name:[] for name in names};paired=[];active='bf16'
        for order in orders:
            row={}
            for mode in order:
                if active!='bf16':
                    for path,original in modules:set_projection(path,original)
                    for _,module in built[active]:module.cpu()
                if mode!='bf16':
                    for path,module in built[mode]:set_projection(path,module.cuda())
                active=mode
                row[mode]=decode_rate();samples[mode].append(row[mode])
            paired.append(row);print('orden',order,'tokens/s',row,flush=True)
        timings={name:{'samples':values,'median':statistics.median(values),'min':min(values),'max':max(values)} for name,values in samples.items()}
        for mode in ('redondeo','gptq'):
            ratios=[row[mode]/row['bf16'] for row in paired]
            timings[mode]['paired_ratio']={'samples':ratios,'median':statistics.median(ratios),'min':min(ratios),'max':max(ratios)}
        print('resumen tiempos pareados',timings,flush=True)
out=os.environ.get('P10_L07_FULL_OUT') or os.path.join(tempfile.mkdtemp(prefix='p10-l07-full-'),'evidence.json')
with open(out,'w',encoding='utf-8') as f:
    json.dump({'model':name,'revision':revision,'gpu':torch.cuda.get_device_name(),'calibration':'256 WikiText-2 train','data_hashes':data_hashes,'projections':len(modules),'results':results,'timings':timings},f,indent=2)
print('resultados guardados en',out,flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Numeric
How many bits per weight does INT4 ideally use with groups of 128 and one FP16 scale and zero point per group?
Code
Implement pack_int4(q) and unpack_int4(p). q is an even-length NumPy int8 array with values from −8 to 7. Add 8 to form codes 0 to 15; store the first code in the low nibble and the second in the high nibble. unpack returns int8 and recovers q exactly. Reject odd length or out-of-range values.
import numpy as np
def pack_int4(q):
  ...
def unpack_int4(p):
  ...
Shift+Enter to run
Proof
Prove: Derive the least-squares correction when column i error is fixed.
The proof will appear here as you work.

Step 1 of 2. What condition does the Lagrange multiplier impose on 2Hδ+λeᵢ?

Quiz
Why can reducing weight bytes help small-batch decode more than prefill?
Key idea
Fewer bits are insufficient: preserve an exact format, verify the kernel and measure quality and speed on the same workload. GPTQ uses activations to decide where to compensate error.