TokenGate: End-to-End Trainable Token Pruning for Long-Context Prefill
Read first: FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning · LoRA: Low-Rank Adaptation of Large Language Models · Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity
TL;DR. Long-context prefill pushes every token through every layer, whether or not it matters. TokenGate adds a small gate module early in a pretrained model (layer 1 of Qwen3-1.7B). It scores each input token, keeps the top , and pruned tokens skip all upper layers and never get KV-cache entries there. To train the non-differentiable top-, kept tokens’ scores re-weight attention in every upper layer (token-gated attention), as a mixture-of-experts router is trained. Fine-tuned with LoRA, it gives 1.4–11.3× faster time-to-first-token (TTFT) and 1.5–3.4× lower peak prefill memory with no accuracy loss, and up to 6.4× faster TTFT than the best training-free pruning method.
Why it matters now. Agents, deep research and RAG readers spend much of their budget prefilling documents that arrive only at request time, so the KV cache cannot be precomputed. Training-free pruners use attention scores as heuristics and lose accuracy at high pruning rates. Architectural changes often need pretraining from scratch. TokenGate sits between the two: a drop-in component trained at about the cost of ordinary LoRA fine-tuning.
Key idea
Section titled “Key idea”Three phases. Layers up to run a normal forward over all tokens. The gate then scores tokens and selects a set . Layers above process only .
Gate module. For each prunable token , an MLP reads the normalised residual at layer and emits , which is RMS-normalised across the sequence into . Non-prunable tokens (the question, answer tokens in training, generated tokens) get and are always kept:
The MLP is initialised to output zero.
Token-gated attention. In layers above each kept key gets a gate value with a learnable gain per layer and head. Because the softmax normaliser is shared by all keys, multiplying attention weights by is the same as adding a bias to the logits:
The temperature corrects for each query seeing kept keys instead of its original . The bias gives the scoring network a gradient through the loss: a kept token whose extra attention lowers the loss gets a higher score. A patched FlashAttention-2 adds the per-key bias at 1.0–1.1× the cost of a plain call.
An illustrative four-token example. These numbers are made up to show the mechanics; they are not the paper’s settings. A document has four prunable tokens and one question token . After layer , suppose the normalised scores are , and the question gets .
- Selection. With , the gate keeps and . So .
- Saved memory. Every layer above now stores 3 key/value entries instead of 5; and are never computed there.
- Soft gain. Take for one head and ignore the temperature. The gate values are the softmax of over : about , and . Equivalently, the attention logits of and get and , so for equal a query attends to about times as much as to .
- Gradient. If attending more to lowers the loss, the gradient through this bias raises ; that is how the scorer learns which tokens to keep.
Training. With LoRA on the backbone, each step averages a full-context loss and a pruned loss at a random budget:
The full term anchors accuracy and gives every token a gradient. The random budget means one trained model works across many pruning ratios.
Key results
Section titled “Key results”- Main results (Fig. 3, Qwen3-1.7B, gate at layer 1). Five tasks: RepoBench-P, 2WikiMultihopQA, MultiNews, BioDEX and 16k needle-in-a-haystack (NIAH). At no accuracy loss TTFT falls 1.4–11.3× and peak prefill memory 1.5–3.4×. Against the next-best baseline TTFT is 1.2–6.4× lower and memory up to 2.1× lower. Baselines (FastKV, SlimInfer, GemFilter, DASH, FlexPrefill, MInference) run on the same LoRA-tuned model.
- 2WikiMultihopQA (Fig. 1d). At 95% of full-context accuracy, prefill is 3.0× faster with 2.7× less memory.
- Hybrid attention (Qwen3.5-2B, NIAH 32k). A gate at layer 3 matches full accuracy at 3.8× lower TTFT, 2.1× lower than the best FastKV run. Gates in the lower Gated DeltaNet layers reach up to 7.8× within 6% of full accuracy. FastKV can only prune at attention layers.
- Longer contexts (Table 3). Trained on 16k NIAH, TTFT gains are 11.3×, 12.8×, 13.0× and 13.0× at 16k, 32k, 64k and 128k. Memory reduction stays at 3.42–3.43× because the full forward below the gate sets the peak.
- Training cost (Table 2). Each step is 1.3× slower, but runs converge sooner on four of five tasks, so total time averages 0.8× plain LoRA fine-tuning.
- What the gate keeps (Fig. 2). Patterns differ by task: answer keywords for QA, phrase-final stop-words for summarisation.
Limitations & open questions
Section titled “Limitations & open questions”- Per-task gates. Every result fine-tunes on the task’s own training set. Whether one gate works across tasks, as a general assistant needs, is untested.
- Unequal training. Training-free baselines get no pruning-specific training. The comparison is fair as a deployment choice but not as a comparison of selection rules alone.
- Scale and setting. Only 1.7B and 2B models, batch-1 TTFT on A100s, and main-task contexts mostly under 40k tokens.
- Decoding. By default the layers at or below the gate keep the full KV cache, and Gated DeltaNet states cannot be pruned per token, so decode savings are smaller than prefill savings.
- Query awareness. With causal attention a document token’s layer- state has only seen earlier tokens. Whether pruning is query-aware therefore depends on placing the question first, a detail practitioners should check.
- Text inconsistencies. The setup names “Qwen3-2B” for the hybrid model elsewhere called Qwen3.5-2B. The hybrid result cites Fig. 5 but appears in Fig. 4. The memory gain over baselines is 2× in the abstract and 2.1× in §5.1. Training uses 4 A100s in §5 but one A100 in Table 2.
Connections
Section titled “Connections”- Routing and sparsity: Switch Transformers (sparse parameters through a trained router), native sparse attention (sparse attention patterns, all tokens kept), Gated DeltaNet (the hybrid backbone).
- Kernels and serving: FlashAttention-2 (the patched kernel), vLLM / PagedAttention (KV-cache memory), speculative decoding (a decode-side speedup).
- Adaptation: LoRA, trained jointly with the gate.
- Long-context behaviour: context rot, lost in the middle, RULER, NoLiMa. These benchmarks probe whether dropping tokens keeps the ones that matter.
- IR analogue: a reranker cascade trims passages before the reader; TokenGate learns a token-level filter inside the reader. For agents that spend most of their budget reading context, see recursive language models.
Questions to think through
These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.
- Derive / compute
Qwen3-1.7B has 28 layers and TokenGate sits at layer 1, so layers 0 and 1 see all N tokens and the 26 layers above see only K. For N = 16,384 and K = 1,024, estimate the fraction of attention compute (quadratic in tokens) and of projection and MLP compute (linear in tokens) that remains, ignoring that layer 1's MLP is also pruned. What is the TTFT ceiling as K goes to zero, and how does it compare with the 13.0× measured at 64k and 128k? Why does peak memory stay at about 3.4× for all lengths?
What a strong answer covers
- Attention: (2·N² + 26·K²) / (28·N²) = (2 + 26/256) / 28 ≈ 0.075, about 7.5% left, or roughly 13× less.
- Linear parts: (2N + 26K) / (28N) = (2 + 26/16) / 28 ≈ 0.13, about 13% left, or roughly 7.7× less; at 16k the linear terms keep the overall saving below the attention saving.
- As K goes to zero only the two full layers remain, so the ceiling is about 28/2 = 14× (a little higher because layer 1's MLP is pruned). The measured 13.0× at 64k and 128k is close to this ceiling, since at long N attention dominates and the full layers set the cost.
- Peak memory is set by the full-length forward through the layers below the gate, which scales with N just like the baseline, so the ratio stays flat (3.42–3.43× in Table 3).
- Mechanism
Top-K selection has no useful gradient, yet TokenGate trains its scoring network with an ordinary next-token loss. Explain how token-gated attention provides the gradient, why multiplying attention weights by a softmax gate equals adding a per-key bias to the logits, and what the zero-initialised MLP and the temperature term each do.
What a strong answer covers
- Each kept token's attention weight is multiplied by its gate value g_j in every layer above the gate, so the loss depends smoothly on the scores of kept tokens, as an MoE router is trained through the outputs of the experts it selected.
- g_j is a softmax over kept tokens of a head-wise gain times b_j; its normaliser is the same for every key, so it cancels in the attention softmax and leaves exp(logit + gain·b_j): an additive per-key, per-head bias.
- A per-key bias needs only one extra vector load per key block in a patched FlashAttention-2, costing 1.0–1.1× a plain call; in decoding it is folded into a fixed additive mask.
- The MLP starts at zero, so all b_j are 0 and the gated model starts as plain attention over the kept tokens; at full K it equals the fine-tuned base model.
- Pruning shrinks the number of keys a query sees from its position p_i to its rank m_i, which sharpens the softmax; the learnable temperature scaled by log m_i over log p_i recalibrates it.
- What if…
Summarise the paper's ablations: the loss that mixes a full-context term with a pruned term at a log-uniform budget, removing temperature or head-wise scaling, gate placement at layer 0, 1 or 2, and the random-K experiments of Fig. 5. What does each show, and which two mechanisms do the authors conclude explain the gains?
What a strong answer covers
- Dropping the full-context loss hurts accuracy most, including at full context; it anchors task accuracy and gives every token a gradient, while the log-uniform budget teaches the gate a wide range of pruning ratios.
- Removing temperature scaling or head-wise scaling also lowers accuracy and gives a worse accuracy–TTFT trade-off.
- A gate at layer 0 is Pareto-suboptimal to layers 1 and 2, suggesting layer-0 residuals carry too little signal; FastKV at layer 1 also does poorly because early attention scores are weak signals.
- With the same random-K selector, the TokenGate-trained backbone beats the fine-tuned base, showing co-adaptation; the learned selector beats both random-K and FastKV selection at every budget.
- Conclusion: a learned scoring network plus a backbone that co-adapts to pruning.
- Critique
The paper reports TokenGate at no accuracy loss on five tasks with Qwen3-1.7B and a hybrid Qwen3.5-2B. List the conditions behind these results and the reasons to be cautious before deploying it on a general-purpose assistant.
What a strong answer covers
- Each model is fine-tuned per dataset (LoRA r = 16 plus the gate), so the gate is task-specific; one gate across many tasks is not shown.
- Baselines are training-free methods run on the same fine-tuned model, so TokenGate gets extra training for pruning that they lack; this is fair for a deployment comparison but not a like-for-like algorithm comparison.
- Models are small (1.7B and 2B), TTFT is measured at batch 1 on A100s, and contexts are mostly under 40k in the main tasks, with only NIAH tested to 128k.
- Decoding still keeps the full KV cache for layers at or below the gate by default, and Gated DeltaNet states cannot be pruned per token, so decode-time savings are smaller than prefill savings.
- Text inconsistencies: Qwen3-2B vs Qwen3.5-2B in the setup, Fig. 5 cited for the hybrid result shown in Fig. 4, 2× vs 2.1× memory gain over the next-best baseline, and one A100 vs four A100s for training.
- Design
You run a RAG system whose reader receives 20 retrieved passages (about 30k tokens) per query. Design a study to test TokenGate as a learned, in-model passage filter. Cover prompt layout, what the gate can and cannot see at layer 1, how to compare it with a cross-encoder reranker that trims passages first, and which metrics to report.
What a strong answer covers
- Under causal attention a document token's layer-1 state has only seen earlier tokens, so put the question before the passages (the paper's x = [x_R, x_D] layout) if pruning should depend on the query; mark the question as non-prunable.
- Compare four arms at matched kept-token budgets: full context, reranker top-k passages, TokenGate alone, and reranker followed by TokenGate.
- Report answer accuracy and citation or support accuracy plus TTFT, peak memory and total cost including the reranker; sweep K to trace Pareto curves.
- Vary gold-passage position and the number of distractors to test whether the gate is robust to position effects such as lost-in-the-middle.
- Check transfer: train the gate on one QA set and test on another, since the paper trains per task.
- Connect
Compare TokenGate with Switch Transformer routing and with FlashAttention-2. What is being made sparse in each case, how is the hard routing decision trained, and why can TokenGate reuse FlashAttention-2 almost unchanged?
What a strong answer covers
- Switch Transformer routes each token to one expert, so parameters are sparse; TokenGate decides which tokens continue, so processed tokens are sparse.
- Both scale the selected path by the router or gate value, which gives the gradient that hard top-K or top-1 selection lacks.
- FlashAttention-2 makes exact attention fast without changing the result; TokenGate changes which keys exist above the gate and adds a per-key bias.
- Because the gate enters as an additive per-key bias and the temperature is applied by scaling queries, a FlashAttention-2 kernel needs only one extra vector per key block.