CATS gated-MLP sparsity¶
At a glance
Training-free threshold sparsity of the gated-MLP activations (CATS, see CatsConfig).
| Registered name | Family | Saves | Lossless | Trainable | Configuration |
|---|---|---|---|---|---|
cats |
activation-sparsity | compute or latency | no | no | CatsConfig |
Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: no · trtllm: no · vllm: no
CATS (Lee et al., 2024) sparsifies the activation of every gated MLP down(act(gate(x)) * up(x)). With
g = act(gate(x)), the MLP computes down((g * 1[|g| > t]) * up(x)), so the rows of the up map and the columns of
the down map that belong to dropped channels are never needed. The gate map stays dense. Each layer's threshold t
is the sparsity quantile of |g| on calibration tokens, computed on the base model's activations, so the
thresholds of different layers do not depend on each other. The paper follows the thresholding with a short
fine-tuning, and economize implements the training-free variant. The result is lossy.
The technique patches the MLP forward and leaves the weights untouched, so detach() restores the base model. The
default backend auto runs Triton kernels that read only the kept rows of the up map and the kept columns of the
down map in batch-1 decoding (see Kernels). It needs CUDA, Triton and bfloat16 or float16 weights, and
raises ConfigError when it attaches otherwise, naming every map the kernels cannot serve and why, before any
calibration batch is read. There is no dense fallback, since dense maps with masked channels would give the outputs of
CATS without its saving. A call of more than 16 rows runs the kernels on blocks of at most 16 rows. prefill chooses
which calls are sparsified,
as for TEAL. By default, prefill and the exact passes of speculative decoding stay dense and only decoding and
draft steps are sparsified.
Setup¶
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
import economize
device = "cuda" if torch.cuda.is_available() else "cpu"
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map=device)
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B")
ids = tokenizer("Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. "
"How many clips did Natalia sell altogether?", return_tensors="pt").input_ids.to(device)
Training data is a flat file of uint32 token ids, the format of nanoGPT-style pretraining shards, and calibration
data is a [N, S] tensor of token ids. Both are made here from GSM8K:
import numpy as np
from datasets import load_dataset
texts = [f"{row['question']}\n{row['answer']}" for row in load_dataset("openai/gsm8k", "main", split="train")]
tokens = np.concatenate([tokenizer(t + tokenizer.eos_token).input_ids for t in texts]).astype(np.uint32)
tokens[: len(tokens) * 9 // 10].tofile("train.bin")
tokens[len(tokens) * 9 // 10 :].tofile("val.bin")
calibration = torch.from_numpy(tokens[: 128 * 2048].astype(np.int64)).view(128, 2048)
A perplexity forward is a multi-token call outside decoding, which the default prefill="dense" leaves dense. The
examples below use prefill="second_half", which sparsifies the second half of every sequence:
from economize.train import fixed_windows
windows = fixed_windows("val.bin", 64, 1024).cuda()
@torch.no_grad()
def perplexity(model, windows):
return torch.stack([model(w[None], labels=w[None]).loss for w in windows]).float().mean().exp().item()
dense_ppl = perplexity(base, windows)
Quick start¶
The paper's 50% level drops half of the FFN channels of every token:
from economize.techniques.mlp_sparsity import CatsConfig
model = economize.apply(base, CatsConfig(sparsity=0.5, prefill="second_half"), calibration=calibration)
print(model.techniques["cats"].summary) # target, sparsified layers, installed
print(model.techniques["cats"].threshold_map()[1])
print(dense_ppl, perplexity(model, windows))
threshold_map() maps every sparsified layer (1-indexed) to its threshold. layers restricts the technique to some
layers, and max_samples bounds the activation magnitudes that each layer keeps for the quantile.
Generation with the default prefill sparsifies only the decoding steps:
model.detach()
model = economize.apply(base, CatsConfig(sparsity=0.5), calibration=calibration)
out = model.generate(ids, max_new_tokens=32, do_sample=False)
print(tokenizer.decode(out[0, ids.shape[1]:]))
detach() removes the patches and returns the unchanged base model:
base = model.detach()
print(perplexity(base, windows))
Kernels¶
The default auto backend times the launch parameters of both kernels once per map shape and device and caches
them for the process. Every sparsified call runs the kernels, a call of more than 16 rows in blocks of 16, and a
call under autograd backpropagates through them. Rows of different tokens keep nearly the union of their channels,
so large blocks save little; the default prefill="dense" therefore runs the exact passes (prefill, verification)
on the unchanged MLP, which sparsifies nothing and claims no saving. While the backend is attached it stores the down
weights transposed, and detach() restores them. triton runs the same kernels with heuristic launch parameters.
model = economize.apply(base, CatsConfig(sparsity=0.5), calibration=calibration) # backend="auto"
out = model.generate(ids, max_new_tokens=128)
On an H100 NVL at one row and half of the channels kept, the tuned row kernel runs the up map of a Llama-3-8B-shaped MLP (14336 by 4096) at 1.72x the speed of the dense cuBLAS matrix-vector product and the column-skipping down map at 1.71x. The gate map stays dense, so the MLP saves about a third of its weight reads. A full decode step of OLMo-3-7B under a CUDA graph at position 256 takes 10.9 ms dense and 10.7 ms with CATS at 50% (1.02x), and multiplying the masked activations with the dense weights would take 11.6 ms.
Saving and loading¶
The thresholds are a buffer of the technique, so a checkpoint loads without calibration data:
model = economize.apply(base, CatsConfig(sparsity=0.5, prefill="second_half"), calibration=calibration)
model.save_pretrained("qwen-cats")
model.detach()
model = economize.load(base, "qwen-cats")
print(perplexity(model, windows))
Combining with other techniques¶
CATS calibrates its thresholds on the model that the weight transforms produced. Its sparse Triton kernel reads
dense floating-point weights, so it combines with transforms that leave the remaining maps dense, such as removing
whole layers (depth_prune), and refuses packed low-bit weights (quant) and 2:4 sparse weights (prune). It also
excludes the other activation-sparsity techniques (teal, dejavu) and rotate. Here four layers are removed with
ShortGPT first:
from economize.techniques.prune import DepthPruneConfig
print(economize.compatible("cats", "depth_prune"), economize.compatible("cats", "quant"))
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, DepthPruneConfig(method="shortgpt", num_blocks=4),
CatsConfig(sparsity=0.5, prefill="second_half"), calibration=calibration)
print(perplexity(model, windows))
vLLM and SGLang do not run CATS.
Configuration¶
CatsConfig
dataclass
¶
CatsConfig(sparsity: float = 0.5, prefill: str | PhasePolicy = 'dense', backend: str = 'auto', layers: tuple[int, ...] = (), mlp: str = 'mlp', gate: str = 'gate_proj', up: str = 'up_proj', down: str = 'down_proj', act: str = 'act_fn', max_samples: int = 1 << 20, offload: bool = False)
CATS: threshold the gate activations of every gated MLP (Lee et al., "CATS: Contextually-Aware Thresholding for Sparsity in Large Language Models", COLM 2024).
Each layer's threshold t is the sparsity quantile of |act(gate(x))| on calibration text; the MLP
then computes down(g * 1[|g| > t] * up(x)) with g = act(gate(x)), so the up rows and the down columns
of the dropped channels are never needed. The gate map stays dense.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sparsity
|
float
|
Target fraction of dropped channels per layer (the paper's 50% and 70%). |
0.5
|
max_samples
|
int
|
Activation magnitudes kept per layer for the threshold quantile. |
1 << 20
|
offload
|
bool
|
Keep calibration activations on the CPU between layers. |
False
|
prefill
|
str | PhasePolicy
|
See :class: |
'dense'
|
backend
|
str
|
See :class: |
'auto'
|
layers
|
tuple[int, ...]
|
See :class: |
()
|
mlp
|
str
|
See :class: |
'mlp'
|
gate
|
str
|
See :class: |
'gate_proj'
|
up
|
str
|
See :class: |
'up_proj'
|
down
|
str
|
See :class: |
'down_proj'
|
act
|
str
|
See :class: |
'act_fn'
|
References¶
- Lee, D., Lee, J.-Y., Zhang, G., Tiwari, M., & Mirhoseini, A. (2024). CATS: Contextually-aware thresholding for sparsity in large language models. In Conference on Language Modeling. https://doi.org/10.48550/arXiv.2404.08763