ThriftAttention: Selective Mixed Precision for Long-Context FP4 Attention
Abstract: Efficient attention algorithms are critical to mitigate the quadratic cost of attention in long-context workloads. Prior work utilises block-scaled quantisation techniques on Blackwell GPUs to move attention computation to 4-bit precision to accelerate inference. However, these techniques result in significant quality degradation in long-context settings. We show that the output impact of quantisation error is highly non-uniform and increases with the importance of each query-key interaction, concentrating functionally relevant error in a small number of attention blocks that contain the most important tokens. We propose ThriftAttention, a low-bit attention variant that delivers near-FP16 long-context quality at FP4 inference efficiency. This approach proceeds in two stages. First, a heuristic rapidly selects a small number of important query-key block pairs for FP16 precision. Second, the selected blocks are computed in FP16 and the remaining blocks in FP4, with both paths merged via online softmax into a single output. We demonstrate across long-context benchmarks and model families that by computing only 5% of query-key blocks in FP16, ThriftAttention recovers on average 89.1% of the FP4-to-FP16 performance gap. We show ThriftAttention's advantage grows with sequence length, mitigating the systematic FP4 quality degradation observed at longer contexts. The code is available at https://github.com/joesharratt1229/ThriftAttention.
Paper Prompts
Sign up for free to create and run prompts on this paper using GPT-5.
Top Community Prompts
Explain it Like I'm 14
What this paper is about
This paper introduces ThriftAttention, a way to make LLMs read very long inputs faster and cheaper without losing much accuracy. It does this by mixing two levels of number detail:
- FP4 (very small, fast numbers) for most of the work
- FP16 (bigger, more accurate numbers) only for the most important parts
Think of it like watching a long video where most scenes are in standard quality to save data, but the key moments are switched to HD so you don’t miss important details.
What questions were they trying to answer?
- Can we run attention—the part of a Transformer that decides “which earlier words matter”—mostly in tiny 4-bit numbers (FP4) to go faster, but keep the same quality as using 16-bit numbers (FP16)?
- Is the accuracy loss from using FP4 spread evenly everywhere, or is it concentrated in a few especially important places?
- If it’s concentrated, can we automatically find those important places and compute just those in FP16 to recover most of the accuracy?
How did they do it? (Explained simply)
First, a few plain-language definitions:
- Attention: When the model reads a long text, attention helps each new word look back and decide which earlier words are most relevant.
- Precision (FP4 vs FP16): This is how detailed a number is. FP4 uses very few bits (faster and smaller but noisier). FP16 uses more bits (slower and bigger but more accurate).
- Blocks: Instead of looking at every single pair of words one by one, the model groups them into small chunks (“blocks”) to process them efficiently.
What ThriftAttention does:
- Quick importance check: For each pair of blocks (a group of “queries” looking at a group of “keys”), it computes a fast, cheap score using simple averages. This is like skimming a book chapter’s headings to guess which sections matter most.
- Select a few important blocks: It picks the top-scoring 5–25% of block pairs as “important.”
- Mixed precision:
- Important blocks are computed with FP16 (more accurate).
- All other blocks are computed with FP4 (faster and smaller).
- Smart combining: The results from both paths are merged carefully so the final attention output behaves like a normal attention layer.
Key idea: The authors show that most of the error from using FP4 happens in a small number of places where attention scores are highest. By upgrading just those parts to FP16, you get most of the lost quality back, while keeping almost all of the speed and memory benefits of FP4.
Analogy: Storing a huge photo album in low resolution saves space, but you keep a few key photos in high resolution. You remember the most important moments clearly, while the album is still light and fast to flip through.
What did they find and why it matters
Here are the main results in simple terms:
- Most errors are not spread evenly: The harmful FP4 rounding errors show up mainly in a small number of highly important attention blocks.
- Small FP16 budget, big quality win: By computing only about 5% of blocks in FP16 and the rest in FP4, ThriftAttention recovers about 89% of the accuracy gap between full FP4 and full FP16. With 10% or 25% FP16, the recovery is around 92%.
- Faster at long contexts: On very long inputs (like 131,000 tokens), it keeps speed close to pure FP4 and can cut end-to-end generation time up to about 2× compared to using full FP16 attention.
- Scales better as inputs get longer: The benefit grows with longer sequences—exactly where pure FP4 tends to struggle more.
- Better than skipping work: Methods that skip many attention blocks entirely (sparsity) can miss crucial information. At similar compute cost, ThriftAttention outperforms those methods because it keeps everything, even if most is low-precision.
Why it matters:
- Running LLMs on long documents is expensive and slow mainly because attention cost grows very fast with length. ThriftAttention keeps the model fast and memory-efficient without throwing away important details, making long-context tasks more practical.
What this could mean going forward
- Cheaper, faster long-context AI: Apps like reading and summarizing books, analyzing long reports or codebases, and handling long chats can run faster with almost the same quality.
- Better use of new hardware: New GPUs (like NVIDIA Blackwell) have special units that are great at FP4. ThriftAttention taps into that speed while guarding accuracy where it matters.
- Practical deployment: It doesn’t require retraining models—just a smarter way to run them—so it’s easier to adopt.
- Room to grow: The current version targets certain GPUs and slightly increases memory for caches. Future work could expand to more hardware and explore training with similar mixed-precision ideas.
In short, ThriftAttention is a “best of both worlds” approach: it keeps nearly the quality of high-precision attention while running at the speed and memory savings of low-precision, especially shining on very long inputs.
Knowledge Gaps
Unresolved gaps, limitations, and open questions
Below is a concise, actionable list of what remains missing, uncertain, or unexplored in the paper.
- Algorithmic selection heuristic: The block-importance score uses only the dot product of block means (Ŝ_ij = q̄_i·k̄_j), ignoring the value term ∥v_j − o∥ that appears in the first‑order sensitivity analysis; it is unclear whether alternative proxies (e.g., approximating p_j∥v_j−o∥, using higher moments, max pooling instead of mean, attention logits from low‑cost pilots, or learned predictors) would yield better selection at the same budget.
- Granularity of selection: Only block‑level selection is studied; it is unknown how token‑level, row‑sparse, or head‑specific selection (different k per head/layer) would impact quality/efficiency trade‑offs and kernel complexity.
- Sensitivity to block size: Block size is fixed at B_q = B_k = 64 in all experiments; the effect of varying block sizes on selection accuracy, quantization error, memory traffic, and kernel throughput is unreported.
- Budget adaptivity: A fixed fractional top‑k budget is used; no mechanism is provided to adapt k dynamically per layer/head/query based on measured entropy/peakedness or a target error/latency constraint.
- Selection computation overhead: The cost of computing block means and TopK per query block at decode time (when T_k grows every step) is not isolated; amortization strategies, caching of statistics, and their net effect on end‑to‑end latency are not quantified.
- Numerical coupling of paths: Online softmax merges FP16 and FP4 paths, but there is no formal analysis of bias/variance or stability when probability blocks are quantized (two‑level) on one path and not the other; error in the normalization constant and its propagation across tiles is not bounded.
- Robustness of the “error concentration” claim: Evidence is shown for a subset of heads/layers (and at seq=4096); a broader quantification across models, layers, heads, and lengths (including long contexts) and under distribution shifts is missing.
- Worst‑case behavior: The method is motivated by peaked attention; behavior on flat/entropic attention patterns (e.g., certain reasoning or coding tokens) and adversarial cases that defeat the heuristic is not studied.
- Interplay with value vectors: The selection ignores V statistics; cases where ∥v_j−o∥ dominates error contributions (Eq. (4)) could cause mis‑ranking; proxies using V features or low‑rank V summaries are unexplored.
- Head/layer heterogeneity: The same selection rule and budget are applied uniformly; whether some layers/heads merit larger FP16 budgets (e.g., sink heads, positional heads) is not evaluated.
- Interaction with KV‑cache quantization: Compatibility and synergies with KV compression methods (e.g., KIVI, KVQuant, QServe) are not explored; combined effects on memory, latency, and accuracy remain open.
- Memory footprint trade‑off: Storing both FP16 and FP4 KV caches increases memory by 28%; alternative designs (e.g., storing only FP4 and decompressing/promoting on demand, partial FP16 shadow caches, or recomputation) and their performance trade‑offs are unexamined.
- Hardware portability: The approach is implemented on consumer Blackwell; performance, scheduling, and asynchrony on data‑center Blackwell (SM100), prior architectures (Ampere/Hopper), and non‑NVIDIA hardware are unreported.
- Kernel-level edge cases: Irregular top‑k patterns may cause warp divergence, non‑coalesced HBM accesses, or shared‑memory thrashing; worst‑case occupancy and latency tails are not characterized.
- Throughput vs power: Energy efficiency and power draw under mixed precision are not measured; whether the FP16 helper path meaningfully increases energy per token is unknown.
- Scalability to larger models: Evaluations are limited to 3B–8B models; behavior for 30B–70B+ models, MoE architectures, and different attention schemes (MQA/GQA) is unknown.
- Modal and task generality: Only text LLMs are evaluated; applicability to bi‑directional encoders, cross‑attention (e.g., multimodal, retrieval), diffusion/vision transformers, and speech models is untested.
- Extremely long contexts: Results stop at 131k; behavior at 256k–1M context (where KV traffic and softmax scaling dominate) and potential kernel or numerical bottlenecks are not studied.
- Batching and throughput: Speed evaluations focus on batch size 1; the effects of batch size >1 (multi‑sequence decoding), padding/packing, and server-side scheduling on throughput and latency are not reported.
- Distributed/TP settings: Interaction with tensor/pipeline parallelism and sharded KV caches is not addressed; communicating per‑query top‑k selections across devices may impose nontrivial synchronization overheads.
- Quantization format dependence: The method assumes NVFP4 microscaling (E2M1 + FP8 scales); portability to INT4, alternative FP4 formats, group sizes, or learned rotations (e.g., QuaRot/SpinQuant) is not evaluated.
- Calibration and scales: The impact of per‑group scale choices (group size d/16), per‑head scaling, and scale update policies on error propagation and selection quality is not ablated.
- Probability quantization: Two‑level quantization of probability tiles is borrowed from SageAttention3; its specific contribution to total error in the mixed‑precision setting is not isolated or compared with alternative probability representations.
- Ablation depth: Beyond random/diagonal selectors, broader baselines (e.g., norm‑based, max pooling, learned gating, attention‑entropy thresholds, pilot FP8 passes) and sensitivity to hyperparameters are missing.
- Theoretical guarantees: There is no formal bound connecting the mean‑based selector to the first‑order error expression or to attention mass coverage; conditions under which the selector is provably near‑optimal are not provided.
- Dynamic error control: No mechanism ensures a target NLL or accuracy degradation bound; adaptive control loops to increase/decrease FP16 budget based on observed tile statistics are unexplored.
- Prefill vs decode asymmetry: The method’s benefits are stronger in decode; how to tailor selection for prefill (e.g., sharing selection across tokens, block reuse) and quantify the overhead/benefit split is not analyzed.
- Data/benchmark coverage: Statistical variability (seeds, confidence intervals), per‑task breakdowns, and robustness across more long‑context benchmarks/datasets are not reported; some comparisons use subsets of HELMET.
- Combination with sparsity: Only a matched‑compute comparison is given; hybrid strategies (skip near‑zero blocks, keep medium in FP4, top in FP16) and their compute–quality–latency trade‑offs are left open.
- Safety and reliability: Effects on factuality, hallucination rates, and safety benchmarks are not assessed; whether mixed precision can exacerbate rare but severe errors is unknown.
- Implementation details: Whether block‑means are computed in FP16 or FP4 (and their memory/read implications) is ambiguous; the exact cache layout and on‑chip buffering policies for promoted vs non‑promoted blocks need clarification.
Practical Applications
Practical Applications of ThriftAttention
Below are actionable real-world applications that leverage ThriftAttention’s selective mixed-precision FP4/FP16 attention for long-context LLM inference. Each item notes sectors, potential tools/products/workflows, and key assumptions/dependencies.
Immediate Applications
- Long-context enterprise chatbots and copilots (document Q&A, meeting/transcript summarization)
- Sectors: Enterprise software, customer support, media
- Tools/Workflows: Integrate ThriftAttention kernel into vLLM/TensorRT-LLM/PyTorch custom op; enable 64k–131k context “premium” modes with 5–10% FP16 budget; automated monitoring of NLL gap and fallback to full FP16 on critical prompts
- Assumptions/Dependencies: NVIDIA Blackwell GPUs with FP4 Tensor Cores; acceptance of small residual quality gap; increased KV-cache footprint (+~28%)
- Retrieval-augmented generation (RAG) with larger windows and lower latency
- Sectors: Search, knowledge management, enterprise IT
- Tools/Workflows: Longer context concatenation (e.g., 100+ passages) with dynamic k/Tk per query; pipeline-level SLA that scales FP16 budget with predicted answer difficulty
- Assumptions/Dependencies: RAG stack supports long contexts; heuristic top‑k stable across domains; bandwidth improvements translate to end-to-end gains
- Legal and compliance review at scale (e-discovery, policy/procedure audits)
- Sectors: Legal, governance/risk/compliance (GRC)
- Tools/Workflows: Batch prefill over 10k–100k token documents; decode acceleration for summarization and redaction; “near-FP16 quality at FP4 cost” deployment tier
- Assumptions/Dependencies: Documented validation on representative corpora; auditability of mixed-precision settings; Blackwell availability in review clusters
- Financial analysis of long filings and transcripts (10-K/10-Q, earnings calls)
- Sectors: Finance
- Tools/Workflows: Ingest full filings + supplementary exhibits in a single context; interactive analyst Q&A with reduced latency; scheduled night runs at FP4-heavy settings, interactive runs with higher FP16 budget
- Assumptions/Dependencies: Strict accuracy targets might require 10–25% FP16 budgets; risk management approval for mixed-precision inference
- Healthcare documentation and longitudinal patient summaries
- Sectors: Healthcare
- Tools/Workflows: Summarize multi-visit EHR histories; generate discharge notes with long-context recall; per-task budget tuning and strict evaluation on HELMET-like testbeds
- Assumptions/Dependencies: Privacy/security compliance; rigorous clinical validation; fallback paths for safety-critical decisions
- Code assistants with repository-scale context (repo-level understanding)
- Sectors: Software engineering
- Tools/Workflows: IDE plugins using 64k–131k token context; selective FP16 promotion for “hot” blocks in code regions; CI inference acceleration for static analysis or refactoring
- Assumptions/Dependencies: Long-context models trained on code; project-specific tuning of block sizes and top‑k
- Scientific literature copilots (systematic reviews, multi-paper synthesis)
- Sectors: Academia, pharmaceuticals
- Tools/Workflows: Load multiple full papers into context; near-FP16 quality with FP4 speed for literature triage; tracking per-length recovery to set FP16 budgets
- Assumptions/Dependencies: Domain robustness across jargon-heavy texts; Blackwell-backed research clusters
- Contact-center and CRM assistants with long customer histories
- Sectors: Customer support, CRM
- Tools/Workflows: Retrieve and process entire ticket histories; dynamic promotion of recent/critical interactions to FP16
- Assumptions/Dependencies: Reliable top‑k heuristic on conversational logs; monitor for topic-shift sensitivity
- Cost- and energy-optimized LLM serving
- Sectors: Cloud/hosting, energy management
- Tools/Workflows: Offer “long-context efficient” SKU; autoscale FP16 block budget by queue depth and latency targets; capacity planning based on 1.2–2× speedups and KV bandwidth savings
- Assumptions/Dependencies: Net energy reduction despite KV-cache memory increase; orchestration support for per-request precision control
- Government/policy document analysis (FOIA, regulations, standards)
- Sectors: Public sector, policy analysis
- Tools/Workflows: Batch processing of long regulations; mixed-precision guardrails (limit FP4 share on sections requiring verbatim compliance extraction)
- Assumptions/Dependencies: Procurement of Blackwell hardware; policy accuracy validation and traceability
Long-Term Applications
- Training-time selective precision for attention (forward+backward)
- Sectors: AI infrastructure
- Tools/Workflows: Extend mixed-precision routing to training to stabilize FP4 training (synergy with NVFP4 training); per-head/top‑k schedules
- Assumptions/Dependencies: Further research on stability and convergence; framework/compiler support
- Mixed-precision + sparsity co-design
- Sectors: AI infrastructure
- Tools/Workflows: Combine block-skipping for near-zero blocks with FP4/FP16 routing; learned predictors to allocate FP16 to high-sensitivity blocks
- Assumptions/Dependencies: New kernels and schedulers; careful tail-risk control to avoid irrecoverable omissions
- Hardware co-design for native selective precision primitives
- Sectors: Semiconductors, cloud providers
- Tools/Workflows: ISA support for dynamic per-tile precision; hybrid-format KV caches with low overhead; better asynchrony on data-center Blackwell/next-gen GPUs
- Assumptions/Dependencies: Vendor support; standardization of sub-byte microscaling
- Cross-modality extensions (vision, audio, video, diffusion transformers)
- Sectors: Media, autonomous systems
- Tools/Workflows: Apply selective precision to ViTs for high-res images/video; diffusion transformer attention blocks with FP4 base + FP16 critical tiles
- Assumptions/Dependencies: Empirical validation on modality-specific attention patterns; latency/quality trade studies
- Long-horizon robotics planners and multi-agent memory
- Sectors: Robotics, autonomous systems
- Tools/Workflows: LLM-based task planners with long instruction/history contexts; selective FP16 on recent or task-relevant segments
- Assumptions/Dependencies: Availability of compatible accelerators on edge/robot hardware; robust real-time performance
- Edge/on-device long-context assistants
- Sectors: Consumer devices, automotive
- Tools/Workflows: Future NPUs/GPUs supporting FP4 microscaling and selective precision; personal memory copilots with efficient long contexts
- Assumptions/Dependencies: Hardware roadmap maturity; thermal/power constraints; memory format standardization
- Learned or adaptive block-selection policies
- Sectors: AI infrastructure, MLOps
- Tools/Workflows: Train lightweight policies to predict FP16-worthy blocks beyond the mean-dot-product heuristic; online adaptation to user/task
- Assumptions/Dependencies: Training data and labels for sensitivity; inference overhead must remain negligible
- KV-cache memory optimization under mixed precision
- Sectors: AI infrastructure
- Tools/Workflows: Store KV mostly in FP4; on-demand promotion/companding for selected blocks; memory tiering across GPU/CPU
- Assumptions/Dependencies: New cache managers; careful control of promotion latency and fragmentation
- Standards and evaluation frameworks for long-context quantized inference
- Sectors: Policy, standards bodies
- Tools/Workflows: Benchmarks like HELMET/LongBench integrated into procurement SLAs; certification for “near-FP16” long-context quality under quantization
- Assumptions/Dependencies: Community consensus on metrics and acceptance thresholds
- Domain-specific packaged solutions
- Sectors: Healthcare, finance, legal, education
- Tools/Workflows: Turnkey “long-context accelerator” bundles (kernels + configs) tuned per sector; pre-validated precision budgets and guardrails
- Assumptions/Dependencies: Sector-specific validation and regulatory approvals
- Sustainable AI operations
- Sectors: Energy, cloud operations
- Tools/Workflows: Use mixed precision to reduce GPU-hours per task at long contexts; integrate with carbon accounting dashboards
- Assumptions/Dependencies: Accurate measurement of end-to-end energy impact including memory overhead; operator buy-in
Notes on feasibility across applications:
- Best gains at long contexts (≥32k), especially in decoding; prefill speedups are smaller but consistent.
- The method currently targets consumer Blackwell; porting to data-center Blackwell can unlock larger throughput gains.
- Some tasks may require >5% FP16 budgets (e.g., precision-critical extraction), trading off a bit of latency for quality.
- Dual-precision KV caches increase memory footprint; capacity planning and cache policy adjustments may be required.
Glossary
- attention sinks: Tokens or positions that attract a large share of attention mass across many queries. "These are typically near-diagonal blocks and non-initial attention sinks"
- block-scaled quantisation: Quantization that applies scaling factors per block to reduce precision while controlling error. "Prior work utilises block-scaled quantisation techniques on Blackwell GPUs"
- block-sparsity: Structuring computation to skip entire blocks of query-key interactions deemed unimportant. "combines block-sparsity prediction with quantised attention"
- causal mask: A mask enforcing autoregressive causality so each token only attends to past tokens. "we apply the standard causal mask"
- CTA (Cooperative Thread Array): A CUDA thread block executing as a group on the GPU. "Warps/CTAs whose KV range contains no top- blocks bypass the FP16 path entirely"
- decode (phase): The token-by-token generation phase of inference after prefill. "ThriftAttention's decode kernels achieve a -- speed-up compared to FlashAttention-2"
- double-buffered: Using two buffers to overlap computation and data movement for throughput. "with double-buffered FP4 KV tiles to hide the latency of memory loads behind MMA instructions"
- E2M1 (format): A 4-bit floating-point format with 2 exponent bits and 1 mantissa bit. "each element of is stored in E2M1 format"
- E4M3 (format): An 8-bit floating-point format with 4 exponent bits and 3 mantissa bits. "each per-group scale in is stored in E4M3 format"
- FlashAttention-2: An I/O-aware, tiled attention kernel with improved parallelism and work partitioning. "FlashAttention-2 is the fastest attention variant supported on RTX 6000 Blackwell."
- FP4: 4-bit floating-point precision used to accelerate inference at the cost of quantization error. "uniform FP4 attention"
- FP4 Tensor Cores: NVIDIA hardware units that accelerate low-precision matrix operations in FP4. "introduces native FP4 Tensor Cores"
- FP8: 8-bit floating-point precision often used for scaling factors or mixed-precision operations. "an FP8 microscale tensor"
- HBM (High Bandwidth Memory): High-throughput memory used by GPUs for fast data access. "avoiding both the HBM loads of FP16 , , tiles"
- INT8: 8-bit integer precision used for quantized arithmetic to improve efficiency. "accelerates attention via INT8/FP8 quantisation"
- KV cache compression: Techniques to compress key-value caches to reduce memory and bandwidth costs. "Other works target KV cache compression"
- KV-cache: Stored keys and values from previous tokens to enable efficient autoregressive attention. "KV-cache memory traffic"
- linear attention: Attention variants with sub-quadratic complexity via kernel tricks or factorization. "Other approaches including linear attention work less effectively where the attention distribution is peaked."
- microscale tensor: A tensor of per-group scaling factors used with sub-byte formats to recover dynamic range. "an FP8 microscale tensor"
- microscaling: Applying fine-grained (e.g., per-group) scale factors with low-bit formats to preserve accuracy. "two-level microscaling"
- MMA instructions: Matrix Multiply-Accumulate GPU instructions for high-throughput linear algebra. "behind MMA instructions"
- negative log-likelihood (NLL): A metric measuring how well the model predicts data; lower is better. "Pareto frontier of negative log-likelihood (NLL) recovery vs inference efficiency"
- NVFP4: NVIDIA’s FP4 numerical format and tooling for sub-byte computation. "We use the NVFP4 microscaling format"
- online softmax: A numerically stable, streaming softmax computation that fuses with accumulation. "both paths merged via online softmax into a single output"
- outlier smoothing: Preprocessing to reduce the impact of large-magnitude activations before quantization. "with outlier smoothing"
- PagedAttention: A memory-management technique for attention that virtualizes KV storage with paging. "Efficient Memory Management for LLM Serving with {PagedAttention}"
- Pareto frontier: The trade-off curve showing optimal balances between competing objectives (e.g., speed vs. quality). "Pareto frontier of negative log-likelihood (NLL) recovery vs inference efficiency"
- prefill (phase): The initial bulk attention computation over a long prompt before token-by-token decoding. "For prefill, ThriftAttention achieves up to a kernel speedup"
- register pressure: The demand for limited GPU registers that can constrain occupancy and performance. "To reduce register pressure from supporting two precision paths in a single fused kernel"
- shared memory: On-chip memory shared within a CUDA block for fast data reuse. "The same shared memory region is aliased for , tiles across both precision paths"
- softmax Jacobian: The matrix of partial derivatives of softmax outputs with respect to inputs. "From the softmax Jacobian"
- sparsity ratios: The proportion of elements or blocks pruned or skipped in sparse computation. "Such aggressive sparsity ratios can become a major source of performance degradation"
- tiling: Partitioning computations into tiles to reduce memory I/O and improve locality. "introduced tiling to reduce GPU memory I/O"
- top‑k (block selection): Selecting the k highest-scoring blocks or items based on an importance metric. "we select the top- key blocks"
- two-scale quantisation: A quantization scheme using two levels of scaling to better preserve precision. "two-scale quantisation from SageAttention3"
- warps: Groups of threads (typically 32) that execute in lockstep on NVIDIA GPUs. "Warps/CTAs whose KV range contains no top- blocks bypass the FP16 path entirely"
Collections
Sign up for free to add this paper to one or more collections.