Module contents
Lesson 26 of 28Advanced 110 min

Pruning and sparsity

Study pruning by magnitude and second-order saliency, the lottery ticket hypothesis, structured and 2:4 sparsity, Wanda and SparseGPT. Measure quality and latency on an RTX 3060 and examine layer removal and recovery.

After this lesson you can

  • Derive OBD and OBS saliencies from a second-order Taylor expansion.
  • Reproduce a small lottery ticket experiment with rewinding.
  • Implement Wanda and a SparseGPT-inspired method for unstructured and 2:4 sparsity and measure perplexity.
  • Measure performance of sparse patterns and explain when their formats pay off.
  • Remove a layer or channels from a small LLM and evaluate recovery.

Before you start

Zeros do not mean speed

A network may tolerate setting some parameters to zero, but dense multiplication normally still reads and multiplies those zeros. Magnitude pruning removes small weights according to a budget: it can impose the same fraction on each layer or use a global threshold. The latter allows different densities but may concentrate too much damage in a sensitive layer. Pruning can be performed at once or gradually, and quality recovered with subsequent training.

A mask MM produces W^=M⊙W\hat W=M\odot W. Sparsity is the fraction of zeros, while density is the fraction of retained values. Claiming a deployment gain requires quality as well as a format that does not store every zero and a kernel that exploits it. If indices and irregular accesses cost more than saved operations, sparse format can be slower.

Magnitude pruning assumes a small weight has little effect, but reparameterization can change magnitudes without changing the function. For example, in two consecutive linear layers an intermediate output can be multiplied by a positive constant and consuming weights divided by that constant. A global threshold over weights changes even though the product of both layers remains the same. Normalization, activations and residual connections constrain which reparameterizations are valid in a particular architecture; the observation explains why one global scale is not always a good criterion.

A gradual schedule increases sparsity over several phases and lets surviving parameters adapt. One-pass pruning is cheaper when there is no retraining budget, but its result must be compared with the recovery allowed to each alternative. After each training update, the mask must be reapplied if removed weights are to remain zero; otherwise the optimizer can reactivate them.

Which weight should be removed?

Second-order saliency approximates the increase in loss from setting a weight to zero. Near a stationary point ww,

L(w+δ)−L(w)≈12δ⊤Hδ.L(w+\delta)-L(w)\approx\tfrac12\delta\T H\delta.

The local approximation requires an approximately zero gradient; otherwise the linear term ∇L(w)⊤δ\nabla L(w)\T\delta is missing. OBD approximates HH by its diagonal and assigns weight qq saliency 12Hqqwq2\tfrac12 H_{qq}w_q^2. OBS allows other weights to compensate and uses the full inverse. Both values describe a local loss model, not a quality guarantee after pruning many coordinates.

InteractiveThree pruning criteria

Original weights (0.5, 0.7); Hessian [[4, 2ρ], [2ρ, 1]]. Quadratic loss is evaluated from the minimum.

Resulting weight: (0.000, 0.700). OBS adjusts the remaining coordinate; the other two criteria leave it fixed.

Contours are centered on the minimum; the blue point is the result. The bar uses a fixed scale from 0 to 1.5.

0.7
Removed weight1
Saliencies0.500 / 0.700
Loss increase0.5000
Change correlation and compare the chosen weight and compensation in an explicit quadratic loss.
Proof

The constraint is eq⊤δ=−wqe_q\T\delta=-w_q. The stationary condition of 12δ⊤Hδ−λ(eq⊤δ+wq)\tfrac12\delta\T H\delta-\lambda(e_q\T\delta+w_q) gives Hδ=λeqH\delta=\lambda e_q. Enforcing the constraint gives λ=−wq/[H−1]qq\lambda=-w_q/[H^{-1}]_{qq}. Substitution into the function yields the saliency. Positive definiteness ensures a unique minimum. If changes to other coordinates are forbidden, cost is 12Hqqwq2\tfrac12H_{qq}w_q^2, OBD’s diagonal approximation.

∎

The matrix may be singular or ill-conditioned and, in large networks, constructing the full loss Hessian is prohibitive. Practical methods use layerwise approximations and damping. Correlation explains why magnitude and saliency can disagree: a small weight in a sensitive direction can cost more than a larger one, and compensation can reduce cost if other directions are correlated.

In the interactive example, the Hessian diagonal is 4 and 1. Weight 0.5 is smaller in magnitude than 0.7, but removing it without compensation costs 12⋅4⋅0.52=0.5\tfrac12\cdot4\cdot0.5^2=0.5, whereas removing the second costs 12⋅1⋅0.72=0.245\tfrac12\cdot1\cdot0.7^2=0.245. The diagonal criterion chooses the second. OBS allows the other coordinate to move and its cost also depends on correlation. The diagram depicts an exactly quadratic loss, so there is no Taylor error; in a real network the approximation can fail far from the expansion point.

Individual saliencies cannot simply be added to predict damage from removing many entries: each new constraint changes the compensation problem for the rest. If HH is not positive definite, the unique-minimum interpretation no longer applies. Layerwise reconstruction often uses a matrix proportional to XX⊤XX^\top, which is positive semidefinite, and adds a diagonal to stabilize factorization. The damping value is part of the method and should be reported.

The lottery ticket

The lottery ticket hypothesis proposes that an initialized network contains subnetworks which, trained in isolation from their initial weights, can reach quality comparable to the dense network under studied conditions. Frankle and Carbin find masks through training and pruning, not a rule that knows the ticket before training.

Rewinding returns retained weights to an early training step instead of the final one. A useful comparison holds mask, architecture, steps, optimizer and data fixed, and contrasts rewinding with a fresh initialization and the dense model. One seed or small problem does not prove the result holds in LLMs or at another sparsity. The next cell presents a synthetic experiment with a magnitude-learned mask and explicit rewind point.

The cell saves state after 20 steps of the dense trajectory, trains until step 600, selects half the weights by magnitude and applies that mask to the saved state. It then trains the subnetwork with the fixed mask for 600 additional steps; the dense reference trained 600 from the start. The control uses the same mask and a fresh random initialization; biases remain active. In one run test accuracies were 0.975 for dense, 0.980 for rewind and 0.970 for restart. With 200 test examples, each correct answer changes the figure by 0.005; these differences establish neither a statistical advantage nor a general law.

More careful evaluation needs several seeds, control masks, a sparsity curve and a comparable training protocol. Also distinguish a mask selected after observing dense training from a method able to find it without that cost. Reusing a mask can be useful, but does not retrospectively remove the compute spent finding it.

Formats that can accelerate

Structured pruning removes whole groups such as channels, heads or layers and can reduce dimensions of dense operations. An irregular mask instead requires indices and sparse access. CSR stores nonzero values, column indices and row pointers; its memory depends on index types and matrix shape. With 64-bit indices and FP32 values, storing a value and its column costs 12 bytes before pointers, versus 4 bytes per dense entry.

InteractivePatterns and CSR measurements

RTX 3060, FP32, 2048 × 2048 matrix, batch 16; times from one run.

011×

Illustrative pattern: 2:4 always retains two of four. Curve: dense / CSR time by density, with dashed line at 1×. Dense: 0.128 ms; CSR: 1.084 ms.

CSR values and indices are counted. This installation’s 2:4 test reported cuSPARSELt unavailable; no speed is attributed to that format here.

1
Observed density0.500
Dense / CSR0.12 ×
CSR / dense memory1.50 ×
Explore illustrative patterns and a real CSR versus dense measurement; times are not attributed to the other patterns.

The figure records an RTX 3060 run with FP32, a 2048 × 2048 matrix and batch 16, random masks and the same values in dense and CSR. Speeds vary with shared load, sizes and software. Visual examples of blocks, channels and 2:4 are not the timed patterns. In that installation PyTorch’s 2:4 conversion reported cuSPARSELt not supported on your machine, so no invented 2:4 speed is presented.

2:4 sparsity keeps at most two values from each group of four along the dimension required by the kernel. Regularity enables specialized formats and hardware, but a correct mask alone does not activate fast multiplication. The PyTorch documentation details GPU, shape and format constraints. If each retained FP16 value carries two metadata bits, four original entries ideally cost 2(16+2)=362(16+2)=36 bits versus 64 dense: 56.25%; actual packing may have other constraints.

There are six ways to choose two positions among four. A theoretical code per group would need at least ⌈log⁡26⌉=3\lceil\log_2 6\rceil=3 bits to distinguish them; counting two bits per retained value uses four bits per group and is a simple storage assumption. The effective format may add alignment and metadata, and some kernels impose particular matrix sizes and data types. The pattern must hold along the multiplication’s reduction dimension, not merely any visual grouping of four elements.

In the CSR measurement, density near 0.5 used around 1.50 times dense matrix memory because column indices were 64-bit. At density near 0.05, CSR used around 0.15 times dense memory and was faster in that particular run. Two points cannot establish a universal threshold: performance depends on row count, batch, nonzero distribution, format and library. The curve plots five measured points and does not assign those times to 2:4 or removed channels.

Wanda and layer reconstruction

Wanda ranks, per output row, each weight’s magnitude multiplied by its input channel norm, ∣Wij∣∥Xj∥2|W_{ij}|\|X_j\|_2. A small weight associated with large activations can be more important than a larger one that rarely receives signal. The norm depends on calibration data and domain, and the rule does not itself consider all correlations between channels.

InteractiveWeight times activation

16 outputs × 16 selected q_proj channels. Blue: retained. Loss is from the partial product over 32 tokens.

Activation norm per channel:

Magnitude

Wanda

Activations and weights come from one SmolLM2-135M prompt and are not a general model evaluation.

8
Magnitude MSE0.008949
Wanda MSE0.006004
Compare magnitude and Wanda masks on a real partial projection and measure product error on the calibration prompt.

The data are the 16 selected channels and first 16 outputs of layer 0’s q_proj projection in SmolLM2-135M, revision 93efa2f097d58c2a74874c7e644dbc9b0cee75a2, with the previous lesson’s 32 prompt tokens. Channels were selected by activation maximum, so the example is not an unbiased sample. MSE applies only to that partial product and the same tokens used to calculate norms.

SparseGPT and Wanda use activation information without requiring full subsequent training. SparseGPT approximates layer reconstruction and uses second-order information and block updates related to GPTQ. The teaching version below fixes a mask per block and row using a saliency from triangular factorization, then compensates remaining columns; it does not claim to reproduce every detail or result in the paper.

In 2:4 format, selection is restricted to two retained values within each group. This may increase error versus freely selecting the best weights across the whole row. Compensation changes retained values and can reduce reconstruction error, but does not guarantee lower task loss for every calibration. Compare variants with the same sparsity, precision, inputs and evaluation protocol.

To see why the norm appears in Wanda, consider removing only WijW_{ij}. The perturbation of that output across the example column is −WijXj-W_{ij}X_j and its squared norm is Wij2∥Xj∥22W_{ij}^2\|X_j\|_2^2. Ranking by the square root of that cost equals ranking by ∣Wij∣∥Xj∥2|W_{ij}|\|X_j\|_2. Removing several weights introduces cross terms between correlated channels; a sum of individual costs ignores these interactions. Second-order reconstruction attempts to capture them with a Gram matrix, at greater storage and computation cost.

The calibration norm can vary with language, context length or task type. A channel rarely active in ordinary text may matter for code or multimodal input. The figure therefore uses the same prompt to select and evaluate only as a local demonstration, while the labs retain a separate split. That separation reduces leakage but does not make a small sample representative of all domains.

A layer may appear redundant

InteractiveIndividual layer ablation

SmolLM2-135M: cosine per layer on calibration.

Test PPL when removing one layer; logarithmic vertical scale.

029max 284810baseline 29.8

The test does not remove multiple layers at once or prove a layer is dispensable on other data or tasks.

12
Cosine before / after0.9729
Baseline PPL29.82
PPL without this layer31.20
Select a layer: cosine is measured on calibration data and perplexity after removing only that layer on test data.

The figure uses the previous model and revision in FP32: 256 training tokens for cosine between each block’s input and output, and 254 test tokens scored in two independent windows of 128 for perplexity. Each point removes one layer without subsequent recovery. Results do not show that several layers can be removed simultaneously: their effects may interact. In this example baseline PPL was 29.82; removing layer 12 gave 31.20 and removing layer 29 gave 235.98. Cosine measures residual-stream similarity, not causal damage across all tasks. Research on deep layers requires checking model and evaluation, as in Gromov et al..

Head or channel pruning reduces latency only if the operation actually changes or a compatible kernel is used. Zeroing a head’s output without changing dimensions may retain the same cost. After removing structure, a recovery phase can improve quality; compare its cost and keep evaluation data separate.

A transformer residual layer computes x+f(x)x+f(x), so input and output can have high cosine even when f(x)f(x) affects small directions that later prove decisive. Cosine also depends on the residual stream norm and can hide a change concentrated in a few channels. The figure therefore combines a descriptive measure with an intervention: it nulls a whole layer and measures loss again. Even that intervention remains limited to one isolated layer and the evaluated text; it is not a guarantee for long-context generation.

When removing MLP channels, input and output projections sharing those channels must be reduced compatibly. In attention, pruning a head requires considering projections and key and value head layout. In models with grouped heads, removing a query head does not necessarily remove a KV head. After changing dimensions, check both output and chosen kernel time and retain an unpruned baseline under the same protocol.

NumPy lab

The first part compares magnitude, Wanda and a block compensation variant in both unstructured and 2:4 forms on a synthetic layer. Norms and Hessian use training data and error is measured on test data from the same generating distribution. The second trains an MLP for synthetic classification, fixes a magnitude mask, rewinds to step 20 and compares with a fresh initialization. It uses one seed and does not reproduce a large-scale evaluation.

[ ]Masks, compensation and rewindingBrowser
import numpy as np
rng=np.random.default_rng(26)

def wanda_mask(W,act_norms,sparsity=.5,n_m=None):
    scores=np.abs(W)*act_norms[None,:]
    keep=np.ones_like(W,dtype=bool)
    if n_m is None:
        remove=round(W.shape[1]*sparsity)
        order=np.argsort(scores,axis=1,kind='stable')
        np.put_along_axis(keep,order[:,:remove],False,axis=1)
    else:
        n,m=n_m
        if W.shape[1]%m or not 0<=n<=m: raise ValueError('grupo N:M incompatible')
        for start in range(0,W.shape[1],m):
            idx=np.argsort(scores[:,start:start+m],axis=1,kind='stable')[:,:m-n]+start
            np.put_along_axis(keep,idx,False,axis=1)
    return keep

def sparsegpt_like(W,H,pattern='unstructured',block=8,damp=.01):
    work=W.copy();d=W.shape[1]
    H=H+np.eye(d)*damp*np.mean(np.diag(H))
    U=np.linalg.cholesky(np.linalg.solve(H,np.eye(d))).T
    out=np.empty_like(work)
    for start in range(0,d,block):
        end=min(start+block,d);local=work[:,start:end].copy();errors=np.zeros_like(local)
        saliency=local**2/(np.diag(U)[None,start:end]**2)
        keep=np.ones_like(local,dtype=bool)
        if pattern=='unstructured':
            idx=np.argsort(saliency,axis=1,kind='stable')[:,:local.shape[1]//2]
            np.put_along_axis(keep,idx,False,axis=1)
        else:
            assert block%4==0 and local.shape[1]%4==0
            for j in range(0,local.shape[1],4):
                idx=np.argsort(saliency[:,j:j+4],axis=1,kind='stable')[:,:2]+j
                np.put_along_axis(keep,idx,False,axis=1)
        for j in range(end-start):
            q=local[:,j]*keep[:,j];out[:,start+j]=q
            errors[:,j]=(local[:,j]-q)/U[start+j,start+j]
            local[:,j:]-=errors[:,j,None]*U[start+j,start+j:end][None,:]
        work[:,end:]-=errors@U[start:end,end:]
    return out

d=32;W=rng.normal(size=(16,d));X=rng.normal(size=(d,256));X[:3]*=6
train,test=X[:,:192],X[:,192:];H=2*train@train.T/train.shape[1];norm=np.linalg.norm(train,axis=1)
def error(A):return float(np.mean(((W-A)@test)**2))
for pattern,nm in [('libre',None),('2:4',(2,4))]:
    magnitude=W*wanda_mask(W,np.ones(d),n_m=nm)
    wanda=W*wanda_mask(W,norm,n_m=nm)
    obs=sparsegpt_like(W,H,pattern='unstructured' if nm is None else '2:4')
    print(pattern,'MSE magnitud/Wanda/OBS por bloques',*[round(error(a),5) for a in (magnitude,wanda,obs)])
    if nm:assert np.all(np.count_nonzero(wanda.reshape(16,-1,4),axis=-1)==2)

# Un experimento de billete de lotería, no una afirmación general.
data=rng.normal(size=(1000,2));labels=(data[:,0]*data[:,1]>0).astype(float)[:,None]
train_x,test_x=data[:800],data[800:];train_y,test_y=labels[:800],labels[800:]
def initial(random):return [random.normal(size=(2,24))*.25,np.zeros((1,24)),random.normal(size=(24,1))*.25,np.zeros((1,1))]
def train(params,steps,mask=None,rewind=None):
    params=[x.copy() for x in params];saved=None
    for t in range(steps):
        a=np.tanh(train_x@params[0]+params[1]);logits=a@params[2]+params[3];p=1/(1+np.exp(-logits));g=(p-train_y)/len(train_x)
        grad=[train_x.T@((g@params[2].T)*(1-a*a)),np.sum((g@params[2].T)*(1-a*a),axis=0,keepdims=True),a.T@g,g.sum(axis=0,keepdims=True)]
        for i in range(4):
            params[i]-=.3*grad[i]
            if mask is not None:params[i]*=mask[i]
        if rewind is not None and t+1==rewind:saved=[x.copy() for x in params]
    return params,saved
def accuracy(params):
    pred=(np.tanh(test_x@params[0]+params[1])@params[2]+params[3]>0)
    return float(np.mean(pred==test_y))
init=initial(rng);dense,rewind=train(init,600,rewind=20)
weights=np.r_[np.abs(dense[0]).ravel(),np.abs(dense[2]).ravel()];cut=np.sort(weights)[len(weights)//2-1]
mask=[np.abs(dense[0])>cut,np.ones_like(dense[1],bool),np.abs(dense[2])>cut,np.ones_like(dense[3],bool)]
assert mask[0].sum()+mask[2].sum()==len(weights)//2
ticket,_=train([x*m for x,m in zip(rewind,mask)],600,mask)
fresh=initial(rng);random_reset,_=train([x*m for x,m in zip(fresh,mask)],600,mask)
print('billete: exactitud test denso/rebobinado/reinicio aleatorio',round(accuracy(dense),4),round(accuracy(ticket),4),round(accuracy(random_reset),4))

Local lab

Hooks capture inputs from the base model to estimate its projection reconstruction matrices. BLOCKS=1 tests the first block’s seven projections; None extends to all blocks and requires more time and memory. Masks are calculated on 256 training tokens. Baseline, Wanda and a second-order variant in unstructured and 2:4 forms are evaluated on the same 508 test tokens in windows of 128. Matrices remain in dense format with zeros, so this experiment measures quality, not sparse acceleration.

[ ]Wanda and compensation in a small modelLocal GPU
import math,torch
import torch.nn.functional as F
from datasets import load_dataset
from transformers import AutoModelForCausalLM,AutoTokenizer
MODEL='HuggingFaceTB/SmolLM2-135M';REV='93efa2f097d58c2a74874c7e644dbc9b0cee75a2';DATA_REV='b08601e04326c79dfdd32d625aee71d232d685c3'
BLOCKS=1  # None incluye todos los bloques
device='cuda' if torch.cuda.is_available() else 'cpu'
tok=AutoTokenizer.from_pretrained(MODEL,revision=REV)
ids={}
for split in ('train','test'):
    rows=load_dataset('Salesforce/wikitext','wikitext-2-raw-v1',split=split,revision=DATA_REV)
    ids[split]=tok('\n\n'.join(t for t in rows['text'] if t.strip())[:12000],return_tensors='pt').input_ids
model=AutoModelForCausalLM.from_pretrained(MODEL,revision=REV,dtype=torch.float32).to(device).eval()
limit=model.config.num_hidden_layers if BLOCKS is None else BLOCKS
modules=[(name,m) for name,m in model.model.layers.named_modules() if isinstance(m,torch.nn.Linear) and int(name.split('.')[0])<limit]
original={name:m.weight.detach().cpu().clone() for name,m in modules};stats={};hooks=[]
for name,m in modules:
    def capture(mod,args,name=name):
        x=args[0].detach().reshape(-1,args[0].shape[-1]).float()
        stats[name]=(x.T@x/len(x)).cpu()
    hooks.append(m.register_forward_pre_hook(capture))
with torch.no_grad():model(ids['train'][:,:256].to(device),use_cache=False)
for hook in hooks:hook.remove()
@torch.no_grad()
def mask_wanda(W,H,pattern):
    scores=W.abs()*H.diagonal().clamp_min(0).sqrt()[None,:]
    if pattern=='2:4':
        assert W.shape[1]%4==0
        grouped=scores.reshape(W.shape[0],-1,4)
        indices=grouped.topk(2,dim=-1,largest=False).indices
        mask=torch.ones_like(grouped,dtype=torch.bool).scatter_(-1,indices,False)
        return mask.reshape_as(W)
    count=W.shape[1]//2
    indices=scores.topk(count,dim=1,largest=False).indices
    return torch.ones_like(W,dtype=torch.bool).scatter_(1,indices,False)
@torch.no_grad()
def sparsegpt(W,H,pattern,block=128,damp=.01):
    W=W.clone();n=W.shape[1];H=H.clone()
    H.diagonal().add_(damp*H.diagonal().mean().clamp_min(1e-8))
    U=torch.linalg.cholesky(torch.cholesky_inverse(torch.linalg.cholesky(H)),upper=True)
    result=torch.empty_like(W)
    for start in range(0,n,block):
        end=min(start+block,n);local=W[:,start:end].clone();errors=torch.zeros_like(local)
        score=local.square()/U.diagonal()[None,start:end].square()
        keep=torch.ones_like(local,dtype=torch.bool)
        if pattern=='2:4':
            groups=score.reshape(score.shape[0],-1,4)
            idx=groups.topk(2,dim=-1,largest=False).indices
            keep=keep.reshape(score.shape[0],-1,4).scatter_(-1,idx,False).reshape_as(local)
        else:
            idx=score.topk(score.shape[1]//2,dim=1,largest=False).indices
            keep.scatter_(1,idx,False)
        for j in range(end-start):
            q=local[:,j]*keep[:,j];result[:,start+j]=q
            errors[:,j]=(local[:,j]-q)/U[start+j,start+j]
            local[:,j:]-=errors[:,j,None]*U[start+j,start+j:end][None,:]
        W[:,end:]-=errors@U[start:end,end:]
    return result
@torch.no_grad()
def evaluate():
    test=ids['test'][0,:512];total=0.;count=0
    for start in range(0,len(test),128):
        x=test[start:start+128][None,:].to(device)
        logits=model(x,use_cache=False).logits[:,:-1]
        total+=F.cross_entropy(logits.reshape(-1,logits.shape[-1]),x[:,1:].reshape(-1),reduction='sum').item();count+=x.shape[1]-1
    return math.exp(total/count),count
print('base',evaluate(),'módulos',len(modules),flush=True)
for method in ('wanda','sparsegpt'):
    for pattern in ('unstructured','2:4'):
        with torch.no_grad():
            for name,m in modules:
                W=original[name].to(device);H=stats[name].to(device)
                Wp=W*mask_wanda(W,H,pattern) if method=='wanda' else sparsegpt(W,H,pattern)
                if pattern=='2:4': assert torch.all((Wp!=0).reshape(Wp.shape[0],-1,4).sum(-1)<=2)
                m.weight.copy_(Wp)
        print(method,pattern,'PPL y tokens',evaluate(),flush=True)
with torch.no_grad():
    for name,m in modules:m.weight.copy_(original[name].to(device))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In an FP32 RTX 3060 run with the first block’s seven projections, baseline PPL was 28.30; Wanda gave 29.65 unstructured and 33.59 in 2:4, and the second-order variant 29.58 unstructured and 34.00 in 2:4. These are results from 508 scored tokens and 256 calibration tokens, without recovery or accelerated sparse format. They do not rank methods in general.

In another run with all 30 blocks and 210 internal projections, the same baseline gave 28.30; Wanda gave 58.28 unstructured and 147.79 in 2:4, and the second-order variant 78.10 unstructured and 219.70 in 2:4. Calibration was captured with the original model, without recalculating inputs after pruning earlier layers; the results do not represent a production SparseGPT implementation. A few windows and one configuration do not establish which method generally wins or how much subsequent training could recover.

Measure CSR and test 2:4

The following cell needs CUDA, PyTorch and Triton. It generates the same shapes and densities as the graph, checks the product and measures both paths; CSR creation cost is excluded from timing. It also attempts to convert a 2:4 matrix to semi-structured format and, if the installation does not support it, displays the error without assigning a speed. Measurements vary with load and should be repeated in a controlled environment.

[ ]CSR and 2:4 support testLocal GPU
import torch,triton
torch.manual_seed(26);N=K=2048;M=16
assert torch.cuda.is_available(), 'Este ejemplo mide en CUDA'
A=torch.randn(N,K,device='cuda',dtype=torch.float32)
X=torch.randn(K,M,device='cuda',dtype=torch.float32)
for density in (1.,.5,.25,.1,.05):
    mask=torch.rand(N,K,device='cuda')<density
    dense=(A*mask).contiguous();csr=dense.to_sparse_csr()
    actual=dense@X;test=torch.sparse.mm(csr,X)
    assert torch.allclose(actual,test,rtol=.002,atol=.002)
    td=triton.testing.do_bench(lambda:dense@X,warmup=100,rep=300)
    ts=triton.testing.do_bench(lambda:torch.sparse.mm(csr,X),warmup=100,rep=300)
    bytes_csr=sum(t.numel()*t.element_size() for t in (csr.values(),csr.crow_indices(),csr.col_indices()))
    print('densidad',round(float(mask.float().mean()),4),'denso ms',round(td,4),'CSR ms',round(ts,4),
          'bytes CSR',bytes_csr,'bytes denso',dense.numel()*dense.element_size())

W=torch.randn(2048,2048,device='cuda',dtype=torch.float16)
groups=W.reshape(2048,-1,4)
indices=groups.abs().topk(2,dim=-1).indices
mask=torch.zeros_like(groups,dtype=torch.bool).scatter_(-1,indices,True)
W2=(groups*mask).reshape_as(W).contiguous()
try:
    sparse=torch.sparse.to_sparse_semi_structured(W2)
    x=torch.randn(16,2048,device='cuda',dtype=torch.float16)
    yd=x@W2.T;ys=torch.nn.functional.linear(x,sparse)
    assert torch.allclose(yd,ys,rtol=.02,atol=.1)
    td=triton.testing.do_bench(lambda:x@W2.T,warmup=100,rep=300)
    ts=triton.testing.do_bench(lambda:torch.nn.functional.linear(x,sparse),warmup=100,rep=300)
    print('2:4 denso / disperso ms:',round(td,4),round(ts,4))
except (RuntimeError,NotImplementedError) as error:
    print('2:4 no disponible en esta instalación:',error)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Recovery after removing a layer

This test removes layer 12 and tunes only the final normalization gain for 16 steps, alternating two training windows. Everything else stays frozen. Evaluation uses the same four test windows and 508 scored tokens before and after. This is not a general recovery method or layer selection valid for other domains.

[ ]Tune gain after ablationLocal GPU
import math,torch
import torch.nn.functional as F
from datasets import load_dataset
from transformers import AutoTokenizer,AutoModelForCausalLM
model_id='HuggingFaceTB/SmolLM2-135M';rev='93efa2f097d58c2a74874c7e644dbc9b0cee75a2';data_rev='b08601e04326c79dfdd32d625aee71d232d685c3'
device='cuda' if torch.cuda.is_available() else 'cpu'
tok=AutoTokenizer.from_pretrained(model_id,revision=rev)
ids={}
for split in ('train','test'):
    rows=load_dataset('Salesforce/wikitext','wikitext-2-raw-v1',split=split,revision=data_rev)
    ids[split]=tok('\n\n'.join(t for t in rows['text'] if t.strip())[:12000],return_tensors='pt').input_ids
model=AutoModelForCausalLM.from_pretrained(model_id,revision=rev,dtype=torch.float32).to(device).eval()
@torch.no_grad()
def evaluate():
    total=0.;count=0;test=ids['test'][0,:512]
    for start in range(0,len(test),128):
        x=test[start:start+128][None,:].to(device);logits=model(x,use_cache=False).logits[:,:-1]
        total+=F.cross_entropy(logits.reshape(-1,logits.shape[-1]),x[:,1:].reshape(-1),reduction='sum').item();count+=x.shape[1]-1
    return math.exp(total/count)
print('PPL original',evaluate(),flush=True)
layer=model.model.layers[12];old_forward=layer.forward;layer.forward=lambda hidden_states,**kwargs:hidden_states
print('PPL sin capa 12',evaluate(),flush=True)
for parameter in model.parameters():parameter.requires_grad_(False)
model.model.norm.weight.requires_grad_(True)
optimizer=torch.optim.AdamW([model.model.norm.weight],lr=.01,weight_decay=0)
losses=[]
for step in range(16):
    start=(step%2)*128;x=ids['train'][:,start:start+128].to(device)
    optimizer.zero_grad(set_to_none=True);logits=model(x,use_cache=False).logits[:,:-1]
    loss=F.cross_entropy(logits.reshape(-1,logits.shape[-1]),x[:,1:].reshape(-1));loss.backward();optimizer.step();losses.append(loss.item())
print('pérdida de entrenamiento primer/último paso',round(losses[0],4),round(losses[-1],4),flush=True)
print('PPL tras ajustar únicamente ganancia final',evaluate(),flush=True)
layer.forward=old_forward
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In one run PPL was 28.30 for the original model, 30.25 after layer removal and 29.84 after tuning final gain. The improvement observed in this sample does not restore the baseline or demonstrate recovery on general tasks. The first and last printed losses correspond to different training windows and do not by themselves form a comparable curve. This 508-token evaluation differs from the figure, which uses 254; layer 12 was selected after looking at that test sweep and windows overlap, so it is not an independent evaluation of layer selection.

Exercises

Numeric
An FP16 2:4 matrix retains two values out of four and uses two metadata bits per retained value. What ideal fraction of dense matrix bits does it occupy?
Numeric
Ignoring row pointers, an FP32 value plus its index occupies 12 bytes in CSR and a dense FP32 entry occupies 4. What is the maximum density for CSR to use fewer bytes? Give the boundary value.
Numeric
In a hypothetical timing model, dense multiplication takes 1 ms and CSR takes 0.5 + 3d ms, where d is density. What is the boundary sparsity above which CSR is faster?
Proof
Prove: Derive OBD and OBS at a stationary point.
0
Hessian H is positive definite and weight q is set to zero.

Step 1 of 2. If only q changes, what is the quadratic increase?

Quiz
Which statement about a zero mask is correct?
Code
Implement wanda_mask(W, act_norms, sparsity, n_m=None): prune per row using |W| × input norm; with n_m=(n,m) retain n values per contiguous group of m. Return a Boolean mask.
import numpy as np
def wanda_mask(W, act_norms, sparsity, n_m=None):
  pass
Shift+Enter to run
Key idea
Pruning combines a quality decision with representation and execution choices: sparsity saves time only when the system can exploit it.