How Large Language Models Work: From Text Input to Token-by-Token Generation

    Learn how autoregressive large language models turn text into tokens, process context through attention, and generate output one token at a time. This article explains prefill, decoding, KV caching, and quantization, along with the performance metrics and validation practices developers need to balance speed, memory use, and output quality.

    1. Start with the Right Mental Model

    The core operation of a typical autoregressive large language model (LLM) is straightforward: given a sequence of tokens, calculate a probability distribution for the next token, select one according to a generation strategy, append it to the sequence, and repeat.

    A token is the basic processing unit defined by a tokenizer. It does not necessarily correspond to a single character, an English word, or a punctuation mark.

    For an input sequence:

    [
    x_1,x_2,\ldots,x_n
    ]

    the model first calculates:

    [
    P(x_{n+1}\mid x_1,x_2,\ldots,x_n)
    ]

    After selecting the next token, it calculates:

    [
    P(x{n+2}\mid x_1,x_2,\ldots,x{n+1})
    ]

    This process continues until the model produces an end token, reaches an output length limit, or meets another stopping condition.

    However, “predicting the next token” describes the model’s computational objective—not a process of mechanically joining adjacent words. Large-scale training encodes language patterns, knowledge associations, and some reasoning patterns in the model’s parameters. Each prediction uses the available context, not just the most recent token.

    It is also important to distinguish inference from reasoning. In engineering, inference means running computations with trained model parameters. In a task context, reasoning refers to logical analysis. The two are related, but they are not interchangeable.

    2. How Text Becomes Model Input

    Tokenization: Converting Text into Integer IDs

    Neural networks cannot perform matrix operations directly on raw strings. A tokenizer first maps text to a sequence of token IDs.

    One common approach is byte pair encoding (BPE). It starts with basic units, such as characters or bytes, and progressively merges frequently occurring adjacent units based on training-corpus statistics to build a vocabulary. Models do not all use the same tokenization algorithm, and there is no universal vocabulary size.

    The same text may be split differently by different tokenizers. Common text fragments may correspond to a single token, while uncommon words, technical terms, or text containing mixed encodings may require several tokens.

    Three misconceptions are worth avoiding:

    • Character count is not the same as token count.
    • A token does not necessarily represent a complete, independently displayable piece of text.
    • Token IDs are not interchangeable across models.

    In practice, model input often includes role markers, message boundaries, and other special tokens. These can also consume context capacity. Estimating input size therefore requires more than counting the user-visible text.

    Embeddings: Mapping IDs to Vectors

    A token ID is simply an index into a vocabulary. Its numeric value does not provide a meaningful semantic distance: two tokens with adjacent IDs are not necessarily similar in meaning.

    The model uses an embedding matrix to map each ID to a fixed-dimensional vector:

    [
    e_i=E[x_i]
    ]

    Here, (E) is the learned embedding matrix, and (e_i) is the vector representation of the (i)-th token.

    These vectors are learned numerical representations, not manually written dictionary definitions. Subsequent network layers transform them so that they incorporate context. The same token typically starts with the same embedding in different sentences, but its representation after network processing can differ.

    Positional Information: Representing Order

    Token embeddings alone are not enough. Rearranging the same words can change their meaning completely.

    Models therefore incorporate positional information through methods such as positional embeddings, rotary positional encodings, or other techniques. Their shared purpose is to let the model use token positions and the relationships between those positions.

    Supporting a longer input does not guarantee consistent quality at every input length. Long-context performance also depends on training data, positional handling, and the task itself.

    3. How Attention Uses Context

    The Roles of Queries, Keys, and Values

    In a typical attention layer, linear transformations convert token representations into three sets of vectors:

    • Queries (Q): Used to calculate how relevant other positions are to the current position.
    • Keys (K): Used in relevance matching.
    • Values (V): Carry the information to be aggregated.

    Scaled dot-product attention is commonly expressed as:

    [
    \operatorname{Attention}(Q,K,V)
    =
    \operatorname{softmax}
    \left(
    \frac{QK^\mathsf{T}}{\sqrt{d_k}}+M
    \right)V
    ]

    Here, (d_k) is the key-vector dimension, and (M) is the attention mask.

    For autoregressive generation, the mask prevents a position from accessing future positions. The model can use the current position and preceding context, but it cannot look ahead at an answer that has not yet been generated.

    Intuitively, each position computes a relevance-weighted combination of information from the positions it can access. Attention weights, however, are not a complete account of the model’s reasoning or a reliable causal explanation.

    Multi-Head Attention and Multiple Layers

    Multi-head attention computes information relationships in parallel across different representation subspaces. This provides several paths for combining information, but it does not mean that one head always handles grammar while another always handles facts.

    Alongside attention, the network typically includes feed-forward computations, normalization, and residual connections:

    • Attention exchanges information across positions.
    • Feed-forward networks apply nonlinear transformations to each position’s representation.
    • Residual connections and normalization help maintain stability during training and computation.

    After multiple layers, the representation at the final position incorporates information from the accessible context.

    4. From Hidden States to the Next Token

    The model maps the hidden state at the last valid position to the vocabulary dimension, producing an unnormalized score for each candidate token. These scores are called logits.

    Normalizing the scores produces a next-token probability distribution. A generation strategy then determines which token to select:

    • Greedy selection: Choose the highest-scoring candidate.
    • Probability sampling: Draw a candidate from the probability distribution.
    • Temperature adjustment: Change how concentrated the distribution is.
    • Candidate truncation: Restrict sampling to a subset of high-probability candidates.

    These strategies primarily affect output predictability and diversity. They do not give the model additional knowledge, and lowering temperature does not guarantee factual accuracy.

    The selected token is added to the context, and the next computation begins. The tokenizer eventually decodes the generated token sequence into text. Because tokens can represent incomplete character fragments, the chunks a user sees in a streamed response do not necessarily correspond one-to-one with internally generated tokens.

    5. Why the First Token and Later Tokens Have Different Latencies

    A generation request usually has two core stages: prefill and decoding.

    Prefill: Processing the Input Context

    During prefill, the model processes the full prompt, calculates hidden states across its layers, and builds the cache needed for subsequent generation.

    Although causal masking still applies, all prompt positions are already known. Computations for many positions can therefore run in parallel within the same pass. GPUs can use large matrix operations to process this work efficiently.

    Prefill typically also produces the prediction scores used to select the first output token. That token often comes directly from the computation at the prompt’s final position; it does not necessarily require a separate full decoding pass.

    Longer inputs generally take more time to prefill. With standard full attention, the number of attention interactions grows quadratically with sequence length. Overall latency also depends on model size, operator implementations, and hardware utilization, so input length alone cannot provide a fixed latency estimate.

    Decoding: Processing Newly Generated Tokens

    After the first token is selected, generation proceeds incrementally. With caching enabled, each step primarily processes the newly added token and reads the keys and values associated with the previous context.

    In the basic autoregressive path for a single sequence, each subsequent token depends on the preceding token’s selection. The model therefore cannot compute all unknown output positions in parallel as it can process known prompt positions during prefill.

    A decoding step usually involves less computation than prefill, but it repeatedly reads model weights and the historical cache. In common small-batch scenarios, memory bandwidth is often an important bottleneck. With other batch sizes or model configurations, compute capacity, communication overhead, or other factors may become limiting.

    A slow first token followed by faster subsequent tokens is therefore common, but not universal. Request queues, batch scheduling, context length, and system load all affect the speed users experience.

    6. Why the KV Cache Matters—and Why It Is Expensive

    Which Repeated Computations Does Caching Avoid?

    Recomputing the entire historical sequence for every new token would repeatedly process a large amount of unchanged content.

    In common causal attention models, earlier positions cannot attend to newly appended tokens. Their existing keys and values can therefore be reused. A KV cache stores the historical K and V vectors at each layer so that a new position’s query can attend directly to them.

    Caching does not eliminate the cost of reading historical information, nor does it make generation a single parallel operation. Its main benefit is avoiding repeated computation of historical keys, values, and the associated network processing.

    How Cache Size Grows with Context

    For a conventional, uncompressed cache layout, memory usage can be estimated as:

    [
    \text{Cache size in bytes}
    \approx
    2\times L\times B\times S\times H_{kv}\times D\times b
    ]

    where:

    • (L): Number of network layers.
    • (B): Number of sequences in the batch.
    • (S): Cached sequence length.
    • (H_{kv}): Number of key/value heads.
    • (D): Dimension of each head.
    • (b): Bytes per cached element.

    The factor of 2 accounts for both K and V. Actual implementations may also require memory alignment, metadata, quantization scales, and temporary buffers.

    The key implication is that GPU memory requirements can grow substantially with concurrency, input length, and output length even when model weights remain unchanged.

    Reducing Cache Costs Through Architecture and Management

    Common approaches include:

    • Sharing fewer key/value heads across multiple query heads.
    • Using compact representations or cache compression supported by the architecture.
    • Limiting the visible history to control cache growth.
    • Managing cache memory in blocks to reduce fragmentation and improve dynamic allocation.
    • Reusing an existing cache when prefixes match exactly and the relevant conditions are compatible.

    These approaches solve different problems. Block-based management primarily improves memory utilization; it does not necessarily reduce the theoretical cache capacity required per token. Limiting history may change the information available to the model. Structural compression generally requires model support and cannot be applied arbitrarily to any model.

    Prefix reuse also requires strict checks of the model version, token sequence, positional handling, and relevant configuration. User data isolation must be maintained to prevent incorrect reuse or privacy problems.

    7. Quantization: When Lower Precision Reduces Costs

    Quantization uses low-bit numerical representations to approximate values otherwise stored or computed at higher precision. It can be applied to model weights, activations, or the KV cache.

    The most direct benefit is a smaller data footprint. Potential additional benefits include reduced memory traffic, support for more concurrent requests, and faster execution on suitable hardware.

    Lower bit width, however, does not automatically mean faster inference. Results depend on:

    1. Whether the hardware efficiently supports the relevant data types.
    2. Whether the inference implementation has mature low-bit operators.
    3. The overhead of quantization, dequantization, and scale handling.
    4. Whether the current bottleneck is compute, bandwidth, scheduling, or communication.
    5. The model’s sensitivity to quantization error.

    Weight quantization and cache quantization should be evaluated separately. Weight quantization mainly reduces parameter memory, while cache quantization more directly addresses the costs of long contexts and high concurrency.

    A model merely running successfully is not enough to establish that quantization is acceptable. Evaluation should also cover task accuracy, long-text stability, structured-output validity, and latency distributions. Resource savings must not push quality below the application’s requirements.

    8. Putting the Inference Pipeline Together

    The following pseudocode illustrates the process. It does not represent any specific product interface:

    1. input_tokens = tokenize(conversation_text)
    2. cache = empty
    3. logits, cache = prefill(input_tokens, cache)
    4. loop:
    5. new_token = select_using_strategy(logits)
    6. if new_token is an end token:
    7. exit loop
    8. append_to_output_buffer(new_token)
    9. stream_decodable_text(output_buffer)
    10. if generation_length_limit_reached:
    11. exit loop
    12. logits, cache = decode_one_step(new_token, cache)

    Two details in this workflow are easy to overlook.

    First, token selection and neural network computation are separate stages. Changing the sampling strategy does not change the model’s underlying parameters.

    Second, longer outputs usually mean more accumulated computation, a larger cache, and more historical information for later steps to access. Output length is therefore an important contributor to serving cost.

    9. How Developers Should Evaluate Performance and Quality

    Separate Time to First Token from Ongoing Generation Speed

    Time to first token primarily reflects request queuing, input preparation, prefill, and initial output overhead. Ongoing generation speed more directly reflects decoding efficiency.

    If the first token takes too long to appear, investigate input length, service load, and prefill scheduling. If output begins quickly but subsequent generation is slow, examine cache reads, batching, and device bandwidth.

    End-to-end latency also includes network transmission, text processing, and client-side rendering. Not all of it should be attributed to model computation.

    Do Not Confuse Throughput with Per-Request Speed

    Batching allows multiple requests to share hardware resources and can improve overall system throughput. It does not guarantee that each request becomes faster. Waiting to form batches, mixing short and long requests, and resource contention can all affect tail latency.

    Performance evaluation should cover at least:

    • Time to first token.
    • Inter-token latency.
    • Total completion time.
    • Throughput.
    • Peak GPU memory usage.
    • Failure rate under high load.

    Streamline Context for the Task Rather Than Truncating Blindly

    Long prompts can increase prefill costs and cache usage. They can also introduce irrelevant information that interferes with the task. A better approach is to retain clear instructions, necessary constraints, and relevant material while removing repetition.

    For very long documents, retrieval, segmented processing, or summarization may be appropriate, depending on the task. These methods can omit information, so a summary should not be treated as a lossless replacement for the original text.

    Use Validation to Address the Limits of Generation

    A model generates text based on conditional probabilities; its output is not inherently fact-checked. Fluent responses can still contain errors, outdated information, or violations of required constraints.

    Production systems should apply external validation in proportion to risk. This may include checking structures and fields, verifying supporting references, enforcing rules, and arranging human review for high-risk results.

    Generation capability and correctness assurance should be designed as complementary parts of the system.

    10. Conclusion: Connecting Generation to Computation

    An LLM’s processing pipeline begins by splitting text into tokens and mapping them to vector representations with positional information. Multiple attention and feed-forward layers transform those representations into a next-token probability distribution. A selection strategy then chooses tokens to build the output incrementally.

    Prefill and decoding use the same model parameters but have different computational patterns. Prefill processes known input in parallel, while decoding advances step by step along the generated sequence. KV caching reduces repeated computation by reusing historical keys and values, but its memory cost grows with context length and concurrency. Quantization and cache optimizations can reduce these pressures, provided hardware compatibility and output quality are also validated.

    Understanding these mechanisms makes optimization more precise than simply choosing faster hardware. Developers can identify the actual bottleneck and make informed trade-offs among input design, cache management, batching, numerical precision, and quality validation.