Skip to content

TokenGate: End-to-End Trainable Token Pruning for Long-Context Prefill

optionalcorefrontierpaperrubric 11/122026 · arXiv · ~40 min

Liana Patel, Rishabh Ranjan, Ion Stoica, Matei Zaharia, Carlos Guestrin

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

Status

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 KK, and pruned tokens skip all upper layers and never get KV-cache entries there. To train the non-differentiable top-KK, 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.

Three phases. Layers up to LL run a normal forward over all NN tokens. The gate then scores tokens and selects a set SS. Layers above LL process only SS.

Gate module. For each prunable token j∈Pj \in \mathcal{P}, an MLP reads the normalised residual at layer LL and emits b~j\tilde b_j, which is RMS-normalised across the sequence into bjb_j. Non-prunable tokens N\mathcal{N} (the question, answer tokens in training, generated tokens) get bj=0b_j = 0 and are always kept:

S=top-⁡Kj∈P bj  ∪  N.S = \operatorname{top-}K_{j \in \mathcal{P}}\, b_j \;\cup\; \mathcal{N}.

The MLP is initialised to output zero.

Token-gated attention. In layers above LL each kept key gets a gate value gjℓh=softmax⁡j∈S(softplus⁡(γℓh) bj)g_j^{\ell h} = \operatorname{softmax}_{j \in S}\big(\operatorname{softplus}(\gamma^{\ell h})\, b_j\big) with a learnable gain per layer and head. Because the softmax normaliser is shared by all keys, multiplying attention weights by gjg_j is the same as adding a bias to the logits:

αijℓh=softmax⁡j∈S, j≤i(τiℓh(qi⊤kjdhead+softplus⁡(γℓh) bj)),τiℓh=softplus⁡(σℓh)log⁡milog⁡max⁡(2,pi).\alpha^{\ell h}_{ij} = \operatorname{softmax}_{j \in S,\, j \le i}\Big(\tau^{\ell h}_i \big(\tfrac{q_i^\top k_j}{\sqrt{d_{\text{head}}}} + \operatorname{softplus}(\gamma^{\ell h})\, b_j\big)\Big), \qquad \tau^{\ell h}_i = \operatorname{softplus}(\sigma^{\ell h}) \frac{\log m_i}{\log \max(2, p_i)}.

The temperature τ\tau corrects for each query seeing mim_i kept keys instead of its original pip_i. 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 t1,…,t4t_1,\dots,t_4 and one question token qq. After layer LL, suppose the normalised scores are b=(1.2, −0.3, 0.8, −1.7)b = (1.2,\ -0.3,\ 0.8,\ -1.7), and the question gets bq=0b_q = 0.

  • Selection. With K=2K = 2, the gate keeps t1t_1 and t3t_3. So S={t1,t3,q}S = \{t_1, t_3, q\}.
  • Saved memory. Every layer above LL now stores 3 key/value entries instead of 5; t2t_2 and t4t_4 are never computed there.
  • Soft gain. Take softplus⁡(γ)=1\operatorname{softplus}(\gamma) = 1 for one head and ignore the temperature. The gate values are the softmax of (1.2,0.8,0)(1.2, 0.8, 0) over SS: about 0.510.51, 0.340.34 and 0.150.15. Equivalently, the attention logits of t1t_1 and t3t_3 get +1.2+1.2 and +0.8+0.8, so for equal qi⊤kjq_i^\top k_j a query attends to t1t_1 about e1.2≈3.3e^{1.2} \approx 3.3 times as much as to qq.
  • Gradient. If attending more to t1t_1 lowers the loss, the gradient through this bias raises b1b_1; 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:

L=12(LKfull+LKprune),Kfull=∣P∣,Kprune∼LogUniform⁡(1,∣P∣/2).\mathcal{L} = \tfrac12\big(\mathcal{L}_{K_{\text{full}}} + \mathcal{L}_{K_{\text{prune}}}\big), \qquad K_{\text{full}} = |\mathcal{P}|,\quad K_{\text{prune}} \sim \operatorname{LogUniform}\big(1, |\mathcal{P}|/2\big).

The full term anchors accuracy and gives every token a gradient. The random budget means one trained model works across many pruning ratios.

TokenGate prefill with a learned token gate A grid with input tokens as columns and layers as rows. In layers 0 and 1, up to the gate layer L, every token is processed: two question tokens and ten document tokens. At the gate, a small MLP scores each document token; the top K document tokens and the question tokens are kept, and only these columns continue through layers 2 to 27. Pruned tokens stop at layer L and create no key-value cache entries above it. Panels on the right explain token-gated attention in the upper layers (the score is added to each kept key as a per-head bias, with a temperature that corrects for fewer keys, run in a patched FlashAttention-2 kernel), the gate (an MLP score, RMS-normalised, keeping the top K plus the never-pruned question), and training (the average of a full-context loss and a loss at a random log-uniform budget). Layers above L: kept tokens only layer 27 layer 3 layer 2 layer 1 = L layer 0 ⋮ × × × × × × Q Q d d d d d d d d d d Q = question (never pruned), d = document × = pruned at L: skips upper layers, no KV Qwen3-1.7B: gate at layer 1 of 28 Gate at layer L MLP score per token, RMS-norm keep top-K document tokens plus question tokens Token-gated attention logit + gain · score, per key temperature: fewer keys seen patched FlashAttention-2 Training loss ½ (full-K loss + random-K loss) random K ~ LogUniform(1, |P|/2)
Original sketch. All tokens pass through the layers up to L; the gate scores prunable tokens, keeps the top K plus the question, and only those continue upward, carrying their score as an attention bias.
  • 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.
  • 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-LL 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.

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.

  1. 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).
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.

Done with this page?

Status