Understanding LLM Inference: A Deep Dive into the Computation Pipeline

    This article breaks down the complete computation pipeline of large language model (LLM) inference from an engineering perspective. It walks through each stage—tokenization, embedding, Transformer computation, output probability mapping, and sampling—analyzing where computational load concentrates, which stages are memory-bound versus compute-bound, and why KV Cache matters for long-context generation, with a summary table of bottlenecks at every stage.

    From a Sentence to LLM Inference: A Complete Breakdown from a Computation Perspective

    When we feed a natural-language sentence into a large language model, a long chain of numerical computation unfolds behind the scenes. For developers, truly understanding how an LLM works means going beyond buzzwords like “Transformer” and “attention mechanism.” What matters more is understanding how data flows through each computation stage, where the compute load concentrates, and where resource bottlenecks appear.

    This article follows a single complete inference pass—“input one sentence, get an answer”—and dissects every key stage of the LLM computation pipeline step by step.

    1. Overview of the Computation Pipeline

    A complete LLM inference pass can be divided into five main stages:

    1. Text preprocessing and tokenization — converting natural language into a sequence of token IDs
    2. Vector embedding — mapping token IDs to dense vectors
    3. Transformer computation layers — repeated iterations of attention and fully connected networks
    4. Output normalization and probability mapping — converting hidden states into a probability distribution over the vocabulary
    5. Sampling and decoding — selecting the next token from the probability distribution, then looping to generate more

    These five stages follow the same basic logic regardless of model size. Below, we use one example sentence to walk through each stage.

    Example input: “Can you introduce the history of artificial intelligence?”

    2. Tokenizer: From Text to Token IDs

    2.1 What the Tokenizer Does

    The tokenizer is the first stage of the computation pipeline, with three core responsibilities:

    • Text cleaning: handling encoding formats, special symbols, whitespace, capitalization, etc.
    • Text segmentation: splitting continuous text into subword units according to rules learned during training
    • ID mapping: mapping each subword unit to an integer ID in the vocabulary

    The computational cost of this stage is low, but it is one of the more error-prone stages in the pipeline—because tokenization quality directly affects the input quality of everything that follows.

    2.2 Core Logic of the BPE Algorithm

    Modern LLMs commonly use Byte Pair Encoding (BPE) or its variants (such as WordPiece and Unigram). Taking BPE as an example, the core logic is as follows:

    BPE essentially maintains a set of merge rules, learned statistically from large-scale corpora during pretraining. The rules look like this:

    1. "a" + "t" → "at"
    2. "at" + "tion" → "ation"

    At inference time, the tokenizer takes the text and merges from the lowest-level characters upward, following the priority of the merge rules, until no further merges are possible—producing the final token sequence.

    2.3 Computation Characteristics

    The computation here is lightweight; the main cost is string matching and hash lookups. The factor with the biggest performance impact is vocabulary size: a larger vocabulary raises per-lookup cost, but finer tokenization granularity reduces the number of tokens that the embedding stage must process.

    In practice, tokenization is rarely the inference bottleneck, but it is part of time to first token (TTFT), so it still offers some optimization headroom in latency-sensitive scenarios.

    3. Embedding: From Discrete IDs to Dense Vectors

    3.1 The Nature of a Lookup Operation

    After tokenization, the input text becomes a sequence of token IDs, for example:

    1. [1024, 3361, 889, 552, ...]

    The next key step is converting these discrete integer IDs into dense numerical vectors, done via an embedding lookup table.

    Assuming a vocabulary size of 102,400 and an embedding dimension of 2048, the embedding matrix has dimensions:

    1. 102400 × 2048

    This matrix occupies roughly 400 MB in FP16 precision and 800 MB in FP32. For large models, the embedding parameters alone account for a non-trivial share of storage.

    3.2 The Semantic Meaning of High-Dimensional Vectors

    Each token is represented as a 2048-dimensional vector in embedding space. These vectors are not randomly initialized; they are progressively adjusted through backpropagation during pretraining.

    After sufficient training, semantically similar words end up closer together in vector space. For example, the vector distance between “cat” and “dog” is much smaller than that between “cat” and “car.” This distributed representation capability is the foundation of the model’s ability to understand linguistic semantics.

    3.3 Computation Characteristics and Bottlenecks

    The embedding stage is a classic memory-bound operation:

    • Extremely low compute—essentially a table lookup
    • Large memory access volume—the embedding matrix must be loaded
    • Under high-concurrency workloads, memory bandwidth can become the bottleneck

    Some efficient inference frameworks fuse the embedding layer into subsequent computations or use more compact storage formats to reduce memory overhead.

    4. Transformer Layers: The True Compute Core

    4.1 Overview of the Computation Units

    The vector sequence from the embedding layer enters the Transformer layers. A standard Transformer layer contains these core components:

    • Multi-Head Self-Attention
    • Feed-Forward Network (FFN)
    • Layer Normalization
    • Residual Connections

    Modern LLMs typically stack dozens of such layers. With each layer, the semantic representation of every token vector becomes more abstract and refined.

    4.2 How Self-Attention Computes

    For every token in the input sequence, self-attention computation can be summarized in three steps:

    Step 1: Linear projection. Each token vector is multiplied by three weight matrices to produce Query, Key, and Value vectors.

    1. Q = X × W_Q
    2. K = X × W_K
    3. V = X × W_V

    Step 2: Attention score computation. Each token’s Query is dot-producted with the Keys of all tokens, divided by a scaling factor, and normalized via Softmax to produce attention weights. The compute cost of this step grows quadratically with sequence length—this is the root cause of skyrocketing computational complexity when LLMs process long texts.

    Step 3: Weighted summation. The attention weights are applied to the Value vectors and summed to produce each token’s new representation.

    4.3 Feed-Forward Network Computation

    After the attention layer, each token vector passes independently through a two-layer fully connected network. The FFN typically expands the dimension from 2048 to 8192 (or higher), then compresses it back to 2048. Although the computation here is enormous, each token is processed independently, so parallelism is very high—the work can be almost entirely absorbed by GPU matrix units.

    4.4 Normalization and Residual Connections

    After each sublayer, a residual connection and layer normalization are applied:

    1. Output = LayerNorm(Input + SubLayer(Input))

    Residual connections address gradient propagation in deep networks; layer normalization stabilizes the numerical range during training. At inference time, these operations are relatively cheap but indispensable.

    4.5 Compute Load and Resource Bottlenecks

    Transformer-layer computation is a classic compute-bound operation:

    • It involves large-scale matrix multiplications
    • All model weight parameters must be loaded
    • Compute scales with model parameter count and token count

    For a 70B-parameter model, loading all weights once in FP16 requires about 140 GB of GPU memory. In actual inference, reading weight parameters accounts for the majority of memory-bandwidth consumption.

    5. Output Layer and Sampling: From Vectors Back to Text

    5.1 Output Probability Distribution

    After all Transformer layers, the model holds the hidden-state vector of the last token. This vector passes through an output projection layer that maps it to vocabulary-sized dimensions:

    1. Logits = HiddenState × OutputMatrix

    The resulting logits vector is normalized with Softmax, producing a probability distribution over every token in the vocabulary.

    5.2 Sampling Strategies

    Common strategies for choosing the next token from the distribution include:

    • Greedy search: directly pick the highest-probability token—stable output but low diversity
    • Temperature sampling: adjusts the “sharpness” of the distribution—lower temperature means more deterministic output, higher temperature means more diverse output
    • Top-K / Top-P sampling: sample from the top-K highest-probability tokens, or from the smallest set of tokens whose cumulative probability reaches P

    The choice of sampling strategy has a major impact on output quality. Greedy sampling is common in deterministic tasks like code generation, while temperature-based sampling performs better in scenarios like creative writing.

    5.3 Autoregressive Generation and KV Cache

    After a token is generated, it is appended to the input sequence and fed back into the model for the next round. If the entire sequence were recomputed every round, the compute cost would be unacceptable. Inference frameworks therefore introduce the KV Cache mechanism:

    • Key and Value vectors of historical tokens are cached in GPU memory
    • Each round only computes the new token’s Q, K, V and updates the relevant attention scores
    • Redundant computation is dramatically reduced, greatly improving generation efficiency

    KV Cache size scales with sequence length, number of layers, and number of attention heads—it is the main source of GPU memory growth in long-text generation scenarios.

    6. Key Takeaways from the Overall Computation Perspective

    Looking at the full pipeline, several characteristics of LLM inference deserve developer attention:

    First, inference generates tokens serially, one at a time. Each output token depends on the semantics of all preceding tokens and inherently cannot be fully parallelized. This means inference latency correlates directly with output length, not just input length.

    Second, bottlenecks differ significantly across stages. Tokenization and embedding are memory-bound; Transformer layers are compute-bound; self-attention becomes a complexity bottleneck at long sequence lengths.

    Third, KV Cache is the core GPU memory consumer in long-context scenarios. The longer the sequence, the larger the KV Cache. In production deployments, developers must manage memory through batch-size control, quantization, and sensible sequence-length limits.

    Fourth, inference efficiency is influenced by many factors. Weight storage format (FP32, FP16, INT8/INT4), batch size, and attention implementation (native attention, Flash Attention, and equivalent optimizations) all directly affect inference speed and resource usage.

    7. Conclusion

    From receiving a piece of text to producing an answer, an LLM goes through four core stages: tokenization, vectorization, multi-layer Transformer computation, and probabilistic sampling. Each stage has its own computation profile and resource demands. Understanding this pipeline helps developers be more targeted in model deployment, inference optimization, and resource planning.

    Here is a summary of the key points worth remembering:

    Computation Stage Core Operations Primary Bottleneck
    Tokenizer Text segmentation and ID mapping Memory access
    Embedding Table lookup for word vectors Memory bandwidth
    Transformer layers Matrix multiplication and attention Compute and GPU memory
    KV Cache update Caching historical states GPU memory capacity
    Output sampling Probability mapping and sampling Low compute

    Master the patterns in this table, and you will not lose your way when tuning LLM inference performance.