TEAL activation sparsity¶
At a glance
Training-free magnitude activation sparsity (TEAL, see TealConfig).
| Registered name | Family | Saves | Lossless | Trainable | Configuration |
|---|---|---|---|---|---|
teal |
activation-sparsity | compute or latency | no | no | TealConfig |
Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: no · trtllm: no · vllm: real
TEAL (Liu et al., 2025) zeroes the entries with |x| < t of the input x of every linear map in the decoder layers,
with no training. The thresholds t come from the magnitude distribution of the base model's inputs on calibration
tokens. sparsity is the parameter-weighted mean fraction of zeroed inputs, which is the fraction of weight columns
a sparse matrix-vector kernel skips. allocation="greedy" runs TEAL's block-wise greedy search, which repeatedly
raises the sparsity of the map whose raise adds least to the layer's output error until the layer reaches the
target. "uniform" gives every map the target level. The result is lossy.
The backend replaces the forward of every sparsified map and stores its weight transposed behind the usual [out, in]
parameter, and detach() restores both. The default backend auto runs TEAL's sparse matrix-vector kernel in Triton,
which reads only the weight columns of nonzero inputs, on a CUDA GPU (see Kernels). It needs CUDA, Triton
and bfloat16 or float16 weights, and raises ConfigError when it attaches otherwise, naming every map the kernel cannot
serve and why, before any calibration batch is read. There is no dense fallback, since a dense matmul with zeroed inputs
would give TEAL's outputs without its saving. backend="triton" runs the same kernel with heuristic launch parameters,
and backend="triton_autotune" times them per map shape. prefill chooses which calls are sparsified. 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. TEAL
measures perplexity with 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¶
from economize.techniques.sparsity import TealConfig
config = TealConfig(sparsity=0.4, prefill="second_half")
model = economize.apply(base, config, calibration=calibration)
summary = model.techniques["teal"].summary
print(summary["maps"], summary["model_sparsity"]) # sparsified maps, calibrated sparsity
print(dense_ppl, perplexity(model, windows))
print(model.simulations())
measure_sparsity counts the zeros that the sparsified maps actually multiply while a function runs. It counts
every token of every call, so the measured value depends on prefill and on the length of the prompt:
from economize.techniques.sparsity import measure_sparsity
measured = measure_sparsity(model.adapter, config, lambda: model.generate(ids, max_new_tokens=32))
print(measured["model"])
detach() removes every hook and returns the unchanged base model:
base = model.detach()
print(perplexity(base, windows))
Kernels¶
The default auto backend stores every sparsified weight transposed and times the kernel's launch parameters once
per map shape and device (a few seconds per shape, cached for the process), as triton_autotune does; triton uses
heuristic launch parameters. Every sparsified call runs the kernel, a call of more than 16 rows in blocks of 16, and
a call under autograd backpropagates through the sparsified map. With independent rows the union of their nonzero
inputs covers most columns, so the kernel rarely beats the dense matmul on several rows. TEAL's default policy keeps
prefill and the exact passes on the unchanged maps for this reason, which sparsifies nothing and claims no saving.
model = economize.apply(base, TealConfig(sparsity=0.4), calibration=calibration) # backend="auto"
out = model.generate(ids, max_new_tokens=128)
On an H100 NVL at one row and 50% sparsity, the tuned kernel runs the maps of a Llama-3-8B-shaped model at 1.30-1.71x the speed of the dense cuBLAS matrix-vector product (1.21-1.50x at 40%), and the maps of OLMo-3-7B at 1.38-1.52x. A full decode step of OLMo-3-7B under a CUDA graph at position 256 takes 10.9 ms dense, 9.8 ms with TEAL at 40% and 9.5 ms at 50% (1.11x and 1.14x). The masked dense reference takes 13.1 ms there. On maps that are only 896 wide, as in Qwen2.5-0.5B, the kernel is slower than the dense product (0.69x for the query map), so TEAL saves time only on models of a few billion parameters and more.
Saving and loading¶
The calibrated levels and thresholds are buffers of the technique, so a checkpoint loads without calibration data:
model = economize.apply(base, TealConfig(sparsity=0.4, prefill="second_half"), calibration=calibration)
model.save_pretrained("qwen-teal")
model.detach()
model = economize.load(base, "qwen-teal")
print(perplexity(model, windows))
Combining with other techniques¶
TEAL sparsifies the inputs of the maps and calibrates its thresholds after the weight transforms have run. 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). Packed low-bit weights (quant) and 2:4 sparse weights
(prune) are refused, and economize.incompatibility("teal", "quant") gives the reason. It also excludes the other
activation-sparsity techniques (cats, dejavu) and rotate, which would change the inputs that the thresholds were
calibrated on.
Here four layers are removed with ShortGPT before TEAL is calibrated:
from economize.techniques.prune import DepthPruneConfig
print(economize.compatible("teal", "depth_prune"), economize.compatible("teal", "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),
TealConfig(sparsity=0.4, prefill="second_half"), calibration=calibration)
print(perplexity(model, windows))
Configuration¶
TealConfig
dataclass
¶
TealConfig(sparsity: float = 0.4, allocation: str = 'greedy', greedy_step: float = 0.05, greedy_fraction: float = 0.25, greedy_batches: int = 0, prefill: str | PhasePolicy = 'dense', backend: str = 'auto', targets: tuple[str, ...] = ('*',), exclude: tuple[str, ...] = (), layers: tuple[int, ...] = (), max_samples: int = 1 << 20, offload: bool = False)
Magnitude activation sparsity on the inputs of the linear maps of every decoder layer (TEAL).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sparsity
|
float
|
Target layer-level sparsity: the parameter-weighted mean fraction of zeroed inputs, i.e. the fraction of weight reads a sparse kernel skips (the paper reports 25%, 40% and 50%). |
0.4
|
allocation
|
str
|
|
'greedy'
|
greedy_step
|
float
|
Base step of the greedy search: a map with |
0.05
|
greedy_fraction
|
float
|
Trailing fraction of sequence positions on which the greedy search measures the layer
error (the reference's |
0.25
|
greedy_batches
|
int
|
Number of calibration batches the greedy search evaluates (0: all). Every accepted move costs one layer forward per candidate map, so long calibration sets are expensive here. |
0
|
prefill
|
str | PhasePolicy
|
Which tokens each kind of call sparsifies: a :class: |
'dense'
|
backend
|
str
|
Registered kernel backend; each runs TEAL's sparse Triton GEMV on every sparsified call and raises
a :class: |
'auto'
|
targets
|
tuple[str, ...]
|
Globs over linear-module names inside a layer. |
('*',)
|
exclude
|
tuple[str, ...]
|
Globs removed from |
()
|
layers
|
tuple[int, ...]
|
1-indexed layers to sparsify; empty means all. |
()
|
max_samples
|
int
|
Magnitudes kept per map for the threshold quantiles. |
1 << 20
|
offload
|
bool
|
Keep calibration activations on the CPU between layers. |
False
|
References¶
- Liu, J., Ponnusamy, P., Cai, T., Guo, H., Kim, Y., & Athiwaratkun, B. (2025). Training-free activation sparsity in large language models. In International Conference on Learning Representations. https://doi.org/10.48550/arXiv.2408.14690