The prefill phase is the first stage of transformer inference where the model processes the entire input prompt simultaneously. This parallel computation generates the initial key-value (KV) cache for all prompt tokens, which is a prerequisite for the subsequent autoregressive decoding phase. It is a computationally heavy, memory-bandwidth-intensive operation, as it performs a full forward pass through the model's layers to establish the context for generation.
Glossary
Prefill Phase

What is the Prefill Phase?
The initial, compute-intensive stage of transformer inference where the model processes the entire input prompt in parallel to compute the initial KV cache.
This phase is distinct from the decode phase, where tokens are generated one-by-one using the cached KV states. Optimizations like continuous batching and PagedAttention manage the prefill's high memory demand. Its cost scales with prompt length, making it a primary target for inference latency reduction and GPU utilization improvements in serving systems like vLLM.
Key Characteristics of the Prefill Phase
The prefill phase is the foundational, single-pass computation that initializes the KV cache. Its properties define the initial latency, memory footprint, and computational profile of an inference request.
Compute-Intensive Parallelism
Unlike the sequential decode phase, the prefill phase processes the entire input prompt in a single, parallel forward pass. This allows the model to leverage the full parallelism of modern accelerators (GPUs/TPUs) but results in high FLOP (Floating Point Operation) consumption proportional to prompt length. The computational complexity is typically O(n²d) for attention, where n is the prompt length and d is the model dimension, making long prompts expensive.
KV Cache Initialization
The primary output of the prefill phase is the initial state of the KV cache. For each transformer layer and attention head, the model computes and stores:
- Key (K) tensors: Representations used for matching in attention.
- Value (V) tensors: Representations used to produce the output. This cached state is then read-only during the subsequent decode phase, enabling efficient autoregressive generation without recomputation.
Memory Allocation & Pressure
The prefill phase determines the fixed memory allocation for the KV cache for the entire request lifetime. The cache size scales linearly with:
- Batch Size: Number of concurrent requests.
- Context Length: Total prompt tokens.
- Model Configuration: Layers, heads, and hidden dimensions. For a 70B parameter model, the KV cache for a single 4K-token context can require ~10-15 GB of GPU memory. This makes prefill a critical moment for memory planning and potential out-of-memory (OOM) errors.
Dominant First Token Latency
The time to generate the first output token (Time to First Token - TTFT) is almost entirely dictated by the prefill phase. This latency is sensitive to:
- Prompt Length: Longer prompts increase prefill time linearly or quadratically.
- Hardware Compute: FLOP/s of the accelerator.
- Memory Bandwidth: Speed of loading weights and writing the initial cache. Optimizations like FlashAttention directly target prefill latency by reducing memory I/O during this phase.
Static Computational Graph
Because the prompt length is known upfront, the computation graph for the prefill phase is static and predictable. This allows for aggressive compiler-level optimizations that are not possible during dynamic decoding, such as:
- Optimal Kernel Selection: Using specialized fused kernels for known sequence lengths.
- Operator Fusion: Combining linear, activation, and layer norm operations.
- Memory Planning: Pre-allocating buffers for intermediate activations.
Contrast with Decode Phase
The prefill and decode phases represent two distinct computational regimes:
| Characteristic | Prefill Phase | Decode Phase |
|---|---|---|
| Processing | Parallel over all prompt tokens. | Sequential, one new token at a time. |
| Compute Bound | Often compute-bound (high FLOP utilization). | Often memory-bound (limited by KV cache reads). |
| Primary Output | Initial KV Cache. | Next token prediction. |
| Latency Profile | Defines TTFT. | Defines inter-token latency and throughput. |
Understanding this dichotomy is essential for holistic inference optimization.
Prefill Phase vs. Decode Phase: A Comparison
A detailed comparison of the two primary computational stages in autoregressive transformer inference, focusing on their operational characteristics and optimization targets.
| Feature / Metric | Prefill Phase | Decode Phase |
|---|---|---|
Primary Function | Processes the entire input prompt in parallel to compute the initial KV cache. | Generates output tokens sequentially using the cached KV states. |
Computational Pattern | Compute-bound; dominated by large matrix multiplications (matmuls) across the full prompt. | Memory-bound; dominated by reading the KV cache for attention and small matmuls for the new token. |
Parallelism | Massive token-level parallelism across the entire prompt length. | Limited parallelism; primarily batch-level across concurrent requests. |
Attention Complexity | O(n²) in sequence length for standard attention; optimized by FlashAttention. | O(n) per step, where n is the growing sequence length in the cache. |
KV Cache I/O | Writes the initial KV cache for all prompt tokens. High write bandwidth. | Reads the entire cached history for each new token. High read bandwidth and latency-sensitive. |
Dominant Bottleneck | FLOPs and GPU compute throughput. | Memory bandwidth (HBM) for KV cache access. |
Typical Optimization Target | Reduce FLOPs via kernel fusion (e.g., FlashAttention), efficient attention patterns. | Reduce memory I/O via KV cache compression (quantization), efficient caching (PagedAttention), and scheduling. |
Relationship to Batch Size | Prefill cost scales linearly with batch size, as each prompt is unique. | Decode cost scales sub-linearly with batch size in continuous batching due to shared kernel execution. |
Impact of Context Length | Cost increases quadratically (or linearly with optimizations) with prompt length. | Latency per token increases linearly with total cached sequence length. |
Key Performance Metrics | Time-to-first-token (TTFT), prompt processing throughput (tokens/sec). | Inter-token latency, token generation throughput (tokens/sec), total time-to-last-token. |
Optimization Techniques for the Prefill Phase
The prefill phase is a critical, compute-intensive bottleneck in transformer inference. These techniques focus on accelerating the initial parallel processing of the prompt to reduce overall latency.
FlashAttention & Kernel Fusion
FlashAttention is an IO-aware exact attention algorithm that dramatically speeds up the prefill phase. It avoids materializing the large, intermediate attention matrix to high-bandwidth memory (HBM) by recomputing parts of the attention operation on-chip. This reduces HBM reads/writes, which are the primary bottleneck. Related kernel fusion techniques combine multiple operations (e.g., softmax, masking, scaling) into a single, optimized GPU kernel to minimize launch overhead and memory traffic.
- Primary Benefit: Reduces memory bandwidth pressure, the key limiter in prefill.
- Impact: Can provide 2-4x speedup for long-context prefill compared to standard attention implementations.
Continuous Batching & Dynamic Scheduling
While continuous batching is often associated with the decode phase, it is equally critical for prefill efficiency. An optimized scheduler dynamically groups incoming requests with similar context lengths into a single batch for prefill execution.
- Key Strategy: Grouping sequences of similar length minimizes the padding overhead, which wastes FLOPs and memory bandwidth.
- Dynamic Scheduling: Advanced systems (e.g., vLLM, TGI) use cache-aware scheduling to prefill requests in an order that optimizes subsequent decode-phase memory locality and KV cache utilization.
Multi-Query & Grouped-Query Attention
Multi-Query Attention (MQA) and Grouped-Query Attention (GQA) are architectural modifications that directly reduce the memory and compute cost of the KV cache generated during prefill.
- MQA: All query heads share a single key head and a single value head. This drastically shrinks the size of the KV tensors that must be computed and stored.
- GQA: A tunable middle ground where groups of query heads share a single key/value head.
- Prefill Impact: These variants reduce the total FLOPs and memory volume during the parallel attention computation of the prompt, leading to faster prefill times and a smaller cache to manage.
Operator Parallelism (Tensor/Sequence)
For very large models or extremely long contexts, the prefill computation must be distributed across multiple devices. Two primary parallelism strategies are used:
- Tensor Parallelism: Splits individual model layers (including attention heads and feed-forward weights) across GPUs. During prefill, the massive matrix multiplications are distributed, reducing compute time per device. This requires careful synchronization and high inter-GPU bandwidth.
- Sequence Parallelism: Splits the input sequence dimension across devices. Each GPU processes a chunk of the prompt tokens, and results are combined via communication (e.g., all-reduce) for the attention operation. This is effective for contexts longer than the model's per-GPU memory limit.
Mixed Precision Computation
Using lower numerical precision for compute and storage during prefill provides significant speed and memory benefits.
- Compute in BF16/FP16: Performing the heavy matrix multiplications of the prefill phase in 16-bit floating-point (BF16 or FP16) doubles the computational throughput on modern GPUs (e.g., NVIDIA Tensor Cores) compared to FP32.
- KV Cache in FP8/INT8: The newly computed KV cache can be immediately quantized and stored in 8-bit format (e.g., FP8). This reduces the memory footprint written to during prefill and the bandwidth required for subsequent decode-phase reads.
- Requirement: Models must be stable at lower precision, often achieved through quantization-aware training or sophisticated post-training quantization methods.
Prefill-Decode Overlap & Asynchronous Execution
In a production serving system, the goal is to hide prefill latency and maximize overall throughput. This involves overlapping prefill with other operations.
- Prefill/Decode Overlap: While one request is in its decode phase (reading from its KV cache), the system can schedule the prefill computation for a new request on the same GPU, utilizing idle compute cycles.
- Asynchronous CUDA Graphs: Capturing the entire prefill computational graph as a single, replayable CUDA Graph eliminates Python and kernel launch overhead, leading to more predictable and lower latency.
- Non-Blocking HBM Transfers: Overlapping the transfer of the computed KV cache to its final memory location with the beginning of decode computations for other requests.
Frequently Asked Questions
The prefill phase is the initial, compute-intensive stage of transformer inference. These questions address its mechanics, optimization, and role in the broader inference pipeline.
The prefill phase is the initial, parallel processing stage in transformer-based language model inference where the entire input prompt is ingested and processed in one forward pass to compute the initial KV cache for all prompt tokens before autoregressive decoding begins.
During this phase, the model's self-attention mechanism computes the key (K) and value (V) tensors for every token in the prompt context. These tensors are stored in the KV cache, a memory buffer that allows the subsequent decode phase to generate tokens autoregressively without recomputing attention over the entire growing sequence for each new token. The prefill phase is highly parallelizable but computationally expensive, as it performs a full matrix multiplication across the entire prompt length, making its latency sensitive to context window size.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
The prefill phase is the foundational compute step for transformer inference. These related concepts detail the techniques, systems, and bottlenecks that define and optimize this critical stage.
Decode Phase
The autoregressive token generation stage that follows the prefill phase. During decoding, the model uses the pre-computed KV cache to efficiently attend to the entire context, predicting one token at a time with minimal new computation. This phase is typically memory-bandwidth bound, as performance is limited by reading the cached keys and values.
KV Cache
The memory buffer that stores computed key and value tensors for all previous tokens. The prefill phase's primary job is to populate this cache for the initial prompt. During the decode phase, the model reads from this cache instead of recomputing attention from scratch, which is the key to efficient autoregressive generation.
- Purpose: Eliminates redundant computation.
- Memory Cost: Scales linearly with batch size and sequence length.
Continuous Batching
A dynamic scheduling technique that maximizes GPU utilization across both prefill and decode phases. Unlike static batching, it allows:
- New requests to join an ongoing batch (prefill).
- Completed sequences to exit, freeing resources.
- It treats the KV cache as a shared resource, managed by systems like PagedAttention, to handle variable sequence lengths efficiently within a single batch.
Context Window
The maximum sequence length a model can process, a limit directly tied to prefill. The prefill phase must compute the KV cache for all tokens in the prompt, making its cost quadratic with respect to context length for standard attention. Techniques like Sliding Window Attention or StreamingLLM modify this relationship to enable longer contexts by bounding or managing the cache size.
Compute-Bound vs. Memory-Bound
The two primary performance regimes in inference:
- Prefill Phase: Typically compute-bound. Performance is limited by the GPU's FLOPs as it performs dense matrix multiplications for attention across the full prompt.
- Decode Phase: Typically memory-bound. Performance is limited by the bandwidth to read the KV cache for each new token generation. Optimizations target the bottleneck of each phase separately.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us