Skip to content

Deja Vu contextual sparsity

At a glance

Contextual FFN-channel sparsity with a trained predictor per layer (Deja Vu, see DejaVuConfig).

Registered name Family Saves Lossless Trainable Configuration
dejavu activation-sparsity compute or latency no predictors DejaVuConfig

Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: no · trtllm: no · vllm: no

Deja Vu (Liu et al., 2023) computes only a subset of the FFN channels of every token. A small predictor per layer, Linear(d, rank) followed by Linear(rank, ffn) as in the reference code, reads the token's hidden state and scores every channel. The 1 - sparsity fraction with the highest scores is computed in the gate, up and down maps, and the rest is skipped. The paper labels a channel of the ReLU MLPs of OPT as active when its activation is positive. Gated MLPs have no exact zeros, so economize labels the top 1 - sparsity fraction of |act(gate(x)) * up(x)|, the channels with the largest contribution to the down map's input. This adaptation to gated MLPs is economize's own. The predictors are trained on the binary cross-entropy against these labels. The paper's attention-head sparsity is not implemented. The result is lossy.

The predictors are fitted at attach time, layer by layer, on the base model's activations for the calibration tokens (fit_steps Adam steps per layer), and the objective dejavu trains them further. The weights are untouched, so detach() restores the base model. The default backend auto runs the Triton kernels of CATS, which read only the kept rows of the gate and up maps and the kept columns of the down map in batch-1 decoding, with launch parameters timed per map shape. 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 the predictors are fitted. There is no dense fallback, since dense maps with masked channels would give Deja Vu's outputs without its saving. prefill chooses which calls are sparsified, as for TEAL, and by default only decoding and draft steps are.

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

from economize.techniques.mlp_sparsity import DejaVuConfig

model = economize.apply(base, DejaVuConfig(sparsity=0.5, prefill="second_half"), calibration=calibration)

print(model.techniques["dejavu"].summary)     # target, sparsified layers, fitted, installed
print(dense_ppl, perplexity(model, windows))

The predictors add rank * (d + ffn) parameters per layer. predictor_dtype sets their storage dtype, and rank trades their cost against the quality of the selection.

Training

The attach-time fit reads a bounded sample of calibration tokens per layer (max_tokens). The objective dejavu trains all predictors together on any token stream that economize.train.fit reads, with the technique attached. Only the predictors are trainable, and the objective reports the recall of the predicted channels against the labels:

from economize.train import fit

fit(model, "train.bin", "dejavu", steps=2000, batch_size=8, seq_len=1024, output_dir="runs/dejavu")
print(perplexity(model, windows))

Lookahead prediction

The paper's lookahead predictor reads the layer's input before attention, so the prediction can overlap the attention block. predictor_input="lookahead" reads the output of the layer's first norm (lookahead_norm):

model.detach()
model = economize.apply(base, DejaVuConfig(sparsity=0.5, prefill="second_half", predictor_input="lookahead"),
                        calibration=calibration)
print(perplexity(model, windows))

Kernels

The kernels and their dispatch are those of CATS: every sparsified call runs the tuned kernels, calls of more than 16 rows in blocks of 16, and the exact passes stay on the unchanged MLP by default.

model = economize.apply(base, DejaVuConfig(sparsity=0.5), calibration=calibration)   # backend="auto"
out = model.generate(ids, max_new_tokens=128)

The kernels skip half of the weight reads of all three maps, but every decode step also runs the low-rank predictor of every layer and selects the top channels. With the default rank of 1000 this costs more than the kernels save: a decode step of OLMo-3-7B under a CUDA graph at position 256 takes 10.9 ms dense and 15.1 ms with Deja Vu at 50% (0.72x), against 16.6 ms for the masked dense reference. A smaller rank lowers the cost of the predictors and their recall of the active channels.

Saving and loading

The predictors and the flag fitted are part of the technique's state, so a loaded checkpoint skips the attach-time fit and needs no calibration data:

model.save_pretrained("qwen-dejavu")
base = model.detach()

model = economize.load(base, "qwen-dejavu")
print(model.techniques["dejavu"].summary["fitted"], perplexity(model, windows))

Combining with other techniques

Deja Vu fits its predictors 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, cats) and rotate. vLLM and SGLang do not run it:

from economize.techniques.prune import DepthPruneConfig

print(economize.compatible("dejavu", "depth_prune"), economize.compatible("dejavu", "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),
                        DejaVuConfig(sparsity=0.5, prefill="second_half"), calibration=calibration)
print(perplexity(model, windows))

Configuration

DejaVuConfig dataclass

DejaVuConfig(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', rank: int = 1000, predictor_input: str = 'mlp', lookahead_norm: str = 'input_layernorm', predictor_dtype: str = 'float32', fit_steps: int = 200, fit_lr: float = 0.001, fit_batch: int = 1024, max_tokens: int = 65536, seed: int = 0, offload: bool = False)

Deja Vu: a trained low-rank predictor per layer chooses the FFN channels to compute (Liu et al., "Deja Vu: Contextual Sparsity for Efficient LLMs at Inference Time", ICML 2023).

The predictor of a layer maps the hidden state to one logit per FFN channel (Linear(d, rank) then Linear(rank, ffn), the reference's two-layer predictor without a nonlinearity); the 1 - sparsity fraction of channels with the largest logits is computed and the rest is skipped in the gate, up and down maps. The predictors are fitted at attach time (fit_steps) and trained further by the objective dejavu.

Parameters:

Name Type Description Default
rank int

Inner width of each predictor (the reference uses 1000).

1000
predictor_input str

"mlp" (the MLP's own input) or "lookahead" (the output of the layer's first norm, lookahead_norm, available before attention runs, so the prediction can overlap it).

'mlp'
lookahead_norm str

Attribute of the decoder layer holding the norm read by "lookahead".

'input_layernorm'
predictor_dtype str

Storage dtype of the predictors.

'float32'
fit_steps int

Adam steps per layer of the attach-time fit (0: no fit; the predictors stay at their random initialization until trained).

200
fit_lr float

Learning rate of the attach-time fit.

0.001
fit_batch int

Tokens per step of the attach-time fit.

1024
max_tokens int

Calibration tokens kept per layer for the fit.

65536
seed int

Seed of the predictor initialization and of the token subsample.

0
offload bool

Keep calibration activations on the CPU between layers.

False
sparsity float

See :class:MlpSparsityConfig.

0.5
prefill str | PhasePolicy

See :class:MlpSparsityConfig.

'dense'
backend str

See :class:MlpSparsityConfig.

'auto'
layers tuple[int, ...]

See :class:MlpSparsityConfig.

()
mlp str

See :class:MlpSparsityConfig.

'mlp'
gate str

See :class:MlpSparsityConfig.

'gate_proj'
up str

See :class:MlpSparsityConfig.

'up_proj'
down str

See :class:MlpSparsityConfig.

'down_proj'
act str

See :class:MlpSparsityConfig.

'act_fn'

References

  • Liu, Z., Wang, J., Dao, T., Zhou, T., Yuan, B., Song, Z., Shrivastava, A., Zhang, C., Tian, Y., Ré, C., & Chen, B. (2023). Deja Vu: Contextual sparsity for efficient LLMs at inference time. In International Conference on Machine Learning. https://doi.org/10.48550/arXiv.2310.17157