13.3 Weight Sparsification
You zero half the entries of a weight matrix, save it, and discover that the file is no smaller. The same dense matrix multiplication also takes roughly the same time. The missing step is representation: a dense tensor still stores every zero and its kernel still performs the dense computation.
Sparsification has two separate jobs. First, choose what can be removed while preserving the behavior you need. Second, encode and execute the remaining computation efficiently. A pruning score addresses the first; a sparse format or physically smaller dense matrix addresses the second. Neither alone proves end-to-end acceleration.
1. A Pattern Is a Contract with the Kernel
| Pattern | Example across eight input columns | Execution implication |
|---|---|---|
| Unstructured | [0, 0, 0, 4, 5, 6, 0, 8] | Four retained values overall, but irregular positions need a suitable sparse representation and kernel. |
| 2:4 semi-structured | [1, 0, 3, 0] [0, 6, 0, 8] | Each contiguous quartet has two retained positions, matching a particular constrained layout. |
| Structured | Remove a complete input channel and the corresponding column | Subsequent matrices must agree on the new dimensions; smaller dense kernels may be used. |
The first row is 50% sparse but is not 2:4: its groups retain one and three entries. Unstructured means the locations are unrestricted, not that the algorithm chooses them randomly. A dense kernel does not inspect each value and dynamically skip zero multiplies; a sparse kernel needs metadata and a layout it understands.
As of 2026-11-18, PyTorch 2.15 documents dtype, shape and CUDA requirements for its semi-structured representation [4]. The four-value pattern is necessary for that representation, but it does not guarantee that any tensor shape, transpose, device or operator is supported. Record the actual runtime and inspect the executed kernel.
Half the Values Is More Than Half the Storage
In a representation with two FP16 values and four index bits per quartet, the original four values take 8 bytes. The retained values take 4 bytes and the metadata another 0.5 byte. Writing and for the respective weight-storage sizes,
For one billion original FP16 weights, that is 1.125 GB rather than 2 GB, before alignment or other tensors. The savings are 43.75%, not 50%. This encoding example matches the documented two index bits per retained value [4]; metadata varies by format.
Even a sparse matrix kernel that runs twice as fast need not double application throughput. If that kernel accounted for 60% of baseline latency and everything else stayed unchanged, the normalized latency would be , or about speedup. This is an illustrative upper-bound calculation under the stated assumptions, not a hardware measurement.
2. SparseGPT: Compensate for Removed Weights
SparseGPT reports one-shot pruning of OPT-175B and BLOOM-176B to substantial unstructured sparsity with small perplexity changes in its experiments [1]. These results concern the evaluated models and tasks; neither the sparsity level nor the lack of retraining guarantees preservation of every capability.
For and calibration columns , the local objective is
Here is the Frobenius norm, counts retained nonzero entries and is their budget. An N:M layout adds constraints inside each group. As in GPTQ, is the Hessian of a row’s local reconstruction loss, not the full language-model loss.
SparseGPT uses this input-correlation information to adjust still-unfixed weights as it prunes. The adjustment can recover some local output error, but second-moment estimation, damping and matrix factorization consume compression-time memory and compute. Held-out domain evaluation must decide whether the resulting artifact is usable.
3. Wanda: A Cheaper Importance Proxy
Wanda scores a weight using both its magnitude and the calibration activation norm [2]:
where contains the observed values of input feature across calibration tokens. Scores are compared within an output row. Wanda removes low-scoring entries without SparseGPT-style compensation updates. This saves a calibration operation; it does not identify literal “reasoning pathways.”
Consider weights and one input . Magnitude pruning removes the first two weights; Wanda’s scores are and it removes the middle two. The original output is 3.5. The two pruned outputs are 2.3 and 3.0. In this example, weighting by activations reduces output error. On a different input distribution, that conclusion can change.
Calibration tokens should represent intended traffic, with padding excluded from the statistics. Keep private release examples and related documents out of calibration; record sample IDs, tokenizer version, filters and the exact mask-generation settings.
4. Construct and Check a 2:4 Mask
Deliberately simplified mask implementation. CPU FP32 with
W[out_features, in_features]andX[valid_tokens, in_features]. It computes one layer’s scores and a deterministic mask. It omits model-wide calibration, output compensation, sparse packing, GPU kernel conversion, quality evaluation and performance measurement. Existing zeros can leave fewer than two nonzeros in a quartet; the mask retains exactly two positions.
import torch
@torch.no_grad()
def wanda_2_4_mask(W: torch.Tensor, X: torch.Tensor):
"""CPU FP32 teaching example; X contains valid calibration tokens only."""
if W.device.type != "cpu" or X.device.type != "cpu":
raise ValueError("this teaching example is CPU-only")
if W.dtype != torch.float32 or X.dtype != torch.float32:
raise ValueError("use FP32 weights and activations")
if W.ndim != 2 or X.ndim != 2 or X.shape[1] != W.shape[1]:
raise ValueError("expected W[out,in], X[tokens,in]")
if X.shape[0] == 0 or W.shape[0] == 0 or W.shape[1] == 0 or W.shape[1] % 4:
raise ValueError("need nonempty tensors and input width divisible by four")
if not torch.isfinite(W).all() or not torch.isfinite(X).all():
raise ValueError("nonfinite calibration data")
scores = W.abs() * X.norm(p=2, dim=0)[None, :]
blocks = scores.reshape(W.shape[0], -1, 4)
# Stable ordering defines what happens when scores tie.
pruned = blocks.argsort(dim=-1, stable=True)[..., :2]
keep = torch.ones_like(blocks, dtype=torch.bool)
keep.scatter_(dim=-1, index=pruned, value=False)
keep = keep.reshape_as(W)
return W * keep, keep
torch.manual_seed(7)
W = torch.randn(128, 256)
X = torch.randn(1024, 256) # 1,024 valid calibration tokens
W_pruned, keep = wanda_2_4_mask(W, X)
assert torch.all(keep.reshape(128, -1, 4).sum(-1) == 2)
assert torch.all((W_pruned.reshape(128, -1, 4) != 0).sum(-1) <= 2)
# Zeros do not change the allocation of a dense tensor.
assert W_pruned.numel() * W_pruned.element_size() == W.numel() * W.element_size()
# Authored one-row counterexample: compare the same input, not a model score.
w = torch.tensor([[0.01, 0.2, 0.3, 2.0]])
x = torch.tensor([[100.0, 1.0, 1.0, 1.0]])
w_wanda, _ = wanda_2_4_mask(w, x)
w_magnitude = w.clone()
w_magnitude[:, :2] = 0
original = x @ w.T
print(original.item(), (x @ w_magnitude.T).item(), (x @ w_wanda.T).item())
# Approximately 3.5, 2.3, 3.0. These figures concern this input only.
The dense storage assertion is intentional. To obtain compression or acceleration, export a supported sparse representation and verify its metadata and kernel path. Do not time this Python mask constructor as if it were a serving kernel.
5. SliceGPT: Reduce Dense Dimensions
SliceGPT uses computational invariance to change the representation basis, then uses calibration-driven principal directions to choose dimensions to retain [3]. Full orthogonal changes of basis can preserve the model’s computation when all connected operations are transformed consistently. Removing dimensions is the lossy step. Low activation variance does not prove that a direction contains only noise or is irrelevant to a rare task.
The resulting matrices are smaller and dense, which can make them easier to execute on ordinary dense kernels. Tile alignment, conversion support, changes to intermediate dimensions and the workload still determine runtime. Compare the exported model against the original under matched quality, context and concurrency conditions.
6. Compare the Authored Pruning Example
The visualizer uses an authored matrix and activation values. Compare the removed entries under magnitude, activation-weighted and 2:4-constrained choices. It illustrates how a scoring rule changes a mask; it does not measure a trained model’s accuracy or demonstrate a GPU speedup.
Activation norms (||X||)
Weight matrix (W)
Selection rules are computed on an authored matrix. Ties are resolved by index to prune exactly half. Zeroing entries alone does not accelerate a dense kernel.
Wanda scores multiply |W| by the input-channel norm. This is a sensitivity proxy, not a quality guarantee.
7. Choose a Deployment, Not Just a Sparsity Percentage
| Method | What selects or adjusts weights? | What must be true for a runtime gain? |
|---|---|---|
| Magnitude | Weight magnitude selects entries to remove. | The exported pattern and kernel must make the remaining work cheaper. |
| SparseGPT | Local reconstruction and compensation under a sparsity constraint. | Supported sparse layout, compatible operator shapes and measured workload benefit. |
| Wanda | Weight magnitude times activation norm; no compensation update. | The same layout/kernel checks; a lower calibration cost does not imply faster serving. |
| SliceGPT | Consistent basis changes and dimension removal. | Smaller dense operations must remain efficient and preserve required quality. |
Preserve the base checkpoint, pruning/calibration manifest, masks or transformed dimensions, tokenizer/template, runtime versions and hashes as one artifact bundle. Compare base/domain capability, safety, format/tool behavior, peak memory, latency and throughput against predeclared gates. Keep the original artifact available for rollback. If these methods cannot meet the product’s quality and resource budget together, the next section considers distillation into a separately trained smaller model.
Quizzes
Quiz 1: A matrix has 50% zeros. Why can its stored size and runtime remain unchanged?
Dense storage still allocates every entry and dense matrix multiplication still executes the dense operation. A supported compressed format/kernel or physically smaller structure is needed. General sparse kernels can accelerate suitable workloads; 2:4 is one constrained route, not the only possible sparse method.
Quiz 2: Does Wanda’s lower error on the one-row example prove it preserves reasoning better?
No. It shows how an activation-weighted score changes local error on one authored input. Calibration distribution, correlations ignored by the proxy and downstream tasks can change the outcome. Test independent representative slices.
Quiz 3: Why does
Its two quartets retain one and three values. A global count cannot enforce the local pattern. Check every group in the actual layout expected by the target kernel.[0,0,0,4,5,6,0,8] violate 2:4 despite 50% sparsity?
Quiz 4: Which part of SliceGPT introduces approximation?
The consistent full change of basis can preserve the computation. Discarding dimensions loses information; low observed variance is not proof of irrelevance to all tasks. Validate the reduced exported model.
Quiz 5: Why are the example’s storage savings 43.75% and its latency speedup only about 1.43×?
Two FP16 values plus four index bits take 4.5 bytes instead of 8, leaving 56.25% of weight storage. If a twice-as-fast kernel covers only 60% of original latency, total latency becomes and speedup is . Additional overhead can reduce the gain further.
References
- Frantar, E., & Alistarh, D. (2023). SparseGPT: Massive Language Models Can Be Accurately Pruned in One-Shot. arXiv:2301.00774.
- Sun, M., Liu, Z., Bair, A., & Kolter, J. Z. (2023). A Simple and Effective Pruning Approach for Large Language Models. arXiv:2306.11695.
- Ashkboos, S., Croci, M. L., Nascimento, M. G., Hoefler, T., & Hensman, J. (2024). SliceGPT: Compress Large Language Models by Deleting Rows and Columns. arXiv:2401.15024.
- PyTorch. Semi-structured sparsity. PyTorch 2.15 documentation.