{"id":1050,"date":"2026-07-07T09:59:04","date_gmt":"2026-07-07T09:59:04","guid":{"rendered":"https:\/\/learnerbox.net\/blog\/?p=1050"},"modified":"2026-07-07T10:04:17","modified_gmt":"2026-07-07T10:04:17","slug":"how-large-language-models-work-part-5-inference-sampling-emergent-behaviour-and-open-frontiers","status":"publish","type":"post","link":"https:\/\/learnerbox.net\/blog\/ai-theory\/how-large-language-models-work-part-5-inference-sampling-emergent-behaviour-and-open-frontiers\/","title":{"rendered":"How Large Language Models Work \u2014 Part 5: Inference, Sampling, Emergent Behaviour, and Open Frontiers"},"content":{"rendered":"\n<h6 class=\"wp-block-heading\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">This is the final part of a five-part series on the internal mechanics of large language models. Parts 1\u20134 covered tokenization, embeddings, attention, the transformer block, and the training and alignment pipeline. Part 5 addresses inference: how a trained model generates text, the mathematics of sampling, context window management, emergent capabilities, and the open research frontiers shaping the next generation of LLMs.<\/mark><\/h6>\n\n\n\n<h4 class=\"wp-block-heading\">From Trained Weights to Generated Text<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">A trained, aligned LLM is a fixed mathematical function: given a sequence of input tokens, it produces a probability distribution over the next token. Inference is the process of repeatedly applying this function to generate text, while the engineering decisions made at inference time have a surprisingly large impact on the quality, diversity, safety, and cost of model outputs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">At each generation step <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>t<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">t<\/annotation><\/semantics><\/math>, the model computes:<math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\" display=\"block\"><semantics><mrow><mi>P<\/mi><mo stretchy=\"false\">(<\/mo><msub><mi>t<\/mi><mrow><mi>n<\/mi><mo>+<\/mo><mn>1<\/mn><\/mrow><\/msub><mo>\u2223<\/mo><msub><mi>t<\/mi><mn>1<\/mn><\/msub><mo separator=\"true\">,<\/mo><msub><mi>t<\/mi><mn>2<\/mn><\/msub><mo separator=\"true\">,<\/mo><mo>\u2026<\/mo><mo separator=\"true\">,<\/mo><msub><mi>t<\/mi><mi>n<\/mi><\/msub><mo separator=\"true\">;<\/mo><mtext>\u2009<\/mtext><mi>\u03b8<\/mi><mo stretchy=\"false\">)<\/mo><mo>=<\/mo><mtext>softmax<\/mtext><mo stretchy=\"false\">(<\/mo><msub><mi>W<\/mi><mi>U<\/mi><\/msub><mo>\u22c5<\/mo><msubsup><mi mathvariant=\"bold\">h<\/mi><mi>n<\/mi><mrow><mo stretchy=\"false\">(<\/mo><mi>N<\/mi><mo stretchy=\"false\">)<\/mo><\/mrow><\/msubsup><mo stretchy=\"false\">)<\/mo><\/mrow><annotation encoding=\"application\/x-tex\">P(t_{n+1} \\mid t_1, t_2, \\ldots, t_n;\\, \\theta) = \\text{softmax}(W_U \\cdot \\mathbf{h}_n^{(N)})<\/annotation><\/semantics><\/math><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">where <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><msubsup><mi mathvariant=\"bold\">h<\/mi><mi>n<\/mi><mrow><mo stretchy=\"false\">(<\/mo><mi>N<\/mi><mo stretchy=\"false\">)<\/mo><\/mrow><\/msubsup><mo>\u2208<\/mo><msup><mi mathvariant=\"double-struck\">R<\/mi><mi>d<\/mi><\/msup><\/mrow><annotation encoding=\"application\/x-tex\">\\mathbf{h}_n^{(N)} \\in \\mathbb{R}^d<\/annotation><\/semantics><\/math> is the final-layer hidden state at position <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>n<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">n<\/annotation><\/semantics><\/math>n, <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><msub><mi>W<\/mi><mi>U<\/mi><\/msub><mo>\u2208<\/mo><msup><mi mathvariant=\"double-struck\">R<\/mi><mrow><mi mathvariant=\"normal\">\u2223<\/mi><mi>V<\/mi><mi mathvariant=\"normal\">\u2223<\/mi><mo>\u00d7<\/mo><mi>d<\/mi><\/mrow><\/msup><\/mrow><annotation encoding=\"application\/x-tex\">W_U \\in \\mathbb{R}^{|V| \\times d}<\/annotation><\/semantics><\/math> is the unembedding matrix (often tied to the transpose of the input embedding matrix <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><msub><mi>W<\/mi><mi>E<\/mi><\/msub><\/mrow><annotation encoding=\"application\/x-tex\">W_E<\/annotation><\/semantics><\/math>WE\u200b), and the resulting vector of logits over <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi mathvariant=\"normal\">\u2223<\/mi><mi>V<\/mi><mi mathvariant=\"normal\">\u2223<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">|V|<\/annotation><\/semantics><\/math> vocabulary entries is passed through softmax to produce a probability distribution. A token is then drawn from this distribution (called the sampling step) appended to the context, and the process repeats.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">The Mathematics of Sampling<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">How a token is selected from the output distribution is not trivial. Naive greedy decoding that always selects the highest-probability token tends to produce repetitive, degenerate outputs. Real systems use one or more of the following strategies.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Temperature scaling.<\/strong> Before applying softmax, the logits are divided by a temperature parameter <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>T<\/mi><mo>&gt;<\/mo><mn>0<\/mn><\/mrow><annotation encoding=\"application\/x-tex\">T &gt; 0<\/annotation><\/semantics><\/math>T>0:<math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\" display=\"block\"><semantics><mrow><msub><mi>P<\/mi><mi>T<\/mi><\/msub><mo stretchy=\"false\">(<\/mo><msub><mi>t<\/mi><mrow><mi>n<\/mi><mo>+<\/mo><mn>1<\/mn><\/mrow><\/msub><mo>=<\/mo><mi>k<\/mi><mo stretchy=\"false\">)<\/mo><mo>=<\/mo><mfrac><mrow><mi>exp<\/mi><mo>\u2061<\/mo><mo stretchy=\"false\">(<\/mo><msub><mi>z<\/mi><mi>k<\/mi><\/msub><mi mathvariant=\"normal\">\/<\/mi><mi>T<\/mi><mo stretchy=\"false\">)<\/mo><\/mrow><mrow><munder><mo>\u2211<\/mo><mi>j<\/mi><\/munder><mi>exp<\/mi><mo>\u2061<\/mo><mo stretchy=\"false\">(<\/mo><msub><mi>z<\/mi><mi>j<\/mi><\/msub><mi mathvariant=\"normal\">\/<\/mi><mi>T<\/mi><mo stretchy=\"false\">)<\/mo><\/mrow><\/mfrac><\/mrow><annotation encoding=\"application\/x-tex\">P_T(t_{n+1} = k) = \\frac{\\exp(z_k \/ T)}{\\sum_j \\exp(z_j \/ T)}<\/annotation><\/semantics><\/math><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">As <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>T<\/mi><mo>\u2192<\/mo><mn>0<\/mn><\/mrow><annotation encoding=\"application\/x-tex\">T \\to 0<\/annotation><\/semantics><\/math>, the distribution concentrates on the single highest-logit token, equivalent to greedy decoding. As <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>T<\/mi><mo>\u2192<\/mo><mi mathvariant=\"normal\">\u221e<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">T \\to \\infty<\/annotation><\/semantics><\/math>, the distribution approaches uniformity with maximum entropy, maximum randomness. Values of <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>T<\/mi><mo>\u2208<\/mo><mo stretchy=\"false\">[<\/mo><mn>0.6<\/mn><mo separator=\"true\">,<\/mo><mn>1.0<\/mn><mo stretchy=\"false\">]<\/mo><\/mrow><annotation encoding=\"application\/x-tex\">T \\in [0.6, 1.0]<\/annotation><\/semantics><\/math> are typical for creative generation; <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>T<\/mi><mo>\u2208<\/mo><mo stretchy=\"false\">[<\/mo><mn>0.0<\/mn><mo separator=\"true\">,<\/mo><mn>0.3<\/mn><mo stretchy=\"false\">]<\/mo><\/mrow><annotation encoding=\"application\/x-tex\">T \\in [0.0, 0.3]<\/annotation><\/semantics><\/math> for precise factual or code generation tasks. Temperature does not change which token is most probable; instead, it changes how peaked or flat the distribution is.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Top-k sampling.<\/strong> The distribution is truncated to only the <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>k<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">k<\/annotation><\/semantics><\/math> highest-probability tokens, which are then renormalised and sampled from. A typical value is <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>k<\/mi><mo>=<\/mo><mn>40<\/mn><\/mrow><annotation encoding=\"application\/x-tex\">k = 40<\/annotation><\/semantics><\/math>. Top-<math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>k<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">k<\/annotation><\/semantics><\/math> prevents the model from sampling tokens with negligible probability, but it is sensitive to the shape of the distribution. In a uniform distribution, <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>k<\/mi><mo>=<\/mo><mn>40<\/mn><\/mrow><annotation encoding=\"application\/x-tex\">k = 40<\/annotation><\/semantics><\/math> keeps 40 of many reasonable options; in a very peaked distribution, <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>k<\/mi><mo>=<\/mo><mn>40<\/mn><\/mrow><annotation encoding=\"application\/x-tex\">k = 40<\/annotation><\/semantics><\/math> may retain tokens with near-zero probability.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">**Nucleus (top-<math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>p<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">p<\/annotation><\/semantics><\/math>) sampling.** Rather than fixing the number of tokens, nucleus sampling fixes the cumulative probability mass: the smallest set of tokens <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><msub><mi mathvariant=\"script\">V<\/mi><mi>p<\/mi><\/msub><\/mrow><annotation encoding=\"application\/x-tex\">\\mathcal{V}_p<\/annotation><\/semantics><\/math>\u200b such that <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><msub><mo>\u2211<\/mo><mrow><mi>k<\/mi><mo>\u2208<\/mo><msub><mi mathvariant=\"script\">V<\/mi><mi>p<\/mi><\/msub><\/mrow><\/msub><mi>P<\/mi><mo stretchy=\"false\">(<\/mo><msub><mi>t<\/mi><mi>k<\/mi><\/msub><mo stretchy=\"false\">)<\/mo><mo>\u2265<\/mo><mi>p<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">\\sum_{k \\in \\mathcal{V}_p} P(t_k) \\geq p<\/annotation><\/semantics><\/math> is retained and renormalised. A typical value is <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>p<\/mi><mo>=<\/mo><mn>0.9<\/mn><\/mrow><annotation encoding=\"application\/x-tex\">p = 0.9<\/annotation><\/semantics><\/math> or <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>p<\/mi><mo>=<\/mo><mn>0.95<\/mn><\/mrow><annotation encoding=\"application\/x-tex\">p = 0.95<\/annotation><\/semantics><\/math>. Nucleus sampling adapts naturally to the distribution&#8217;s shape. A peaked distribution retains few tokens, a flat one retains many &#8211; this is now the dominant strategy in production systems.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Min-p sampling.<\/strong> A newer variant, increasingly adopted in open-source inference stacks, sets a dynamic minimum probability threshold relative to the top token: any token with <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>P<\/mi><mo stretchy=\"false\">(<\/mo><msub><mi>t<\/mi><mi>k<\/mi><\/msub><mo stretchy=\"false\">)<\/mo><mo>&lt;<\/mo><msub><mi>p<\/mi><mi>min<\/mi><mo>\u2061<\/mo><\/msub><mo>\u00d7<\/mo><mi>P<\/mi><mo stretchy=\"false\">(<\/mo><msub><mi>t<\/mi><mi>max<\/mi><mo>\u2061<\/mo><\/msub><mo stretchy=\"false\">)<\/mo><\/mrow><annotation encoding=\"application\/x-tex\">P(t_k) &lt; p_{\\min} \\times P(t_{\\max})<\/annotation><\/semantics><\/math> is discarded. This keeps tokens that are meaningfully competitive with the best option while discarding genuinely improbable ones, and empirically reduces repetition more effectively than top-<math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>p<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">p<\/annotation><\/semantics><\/math>p at matched quality.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In practice, production inference systems combine multiple strategies: temperature scaling applied first to reshape the distribution, followed by top-<math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>p<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">p<\/annotation><\/semantics><\/math> or min-<math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>p<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">p<\/annotation><\/semantics><\/math> truncation, followed by top-<math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>k<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">k<\/annotation><\/semantics><\/math> as a hard ceiling. The specific combination and hyperparameters are treated as tunable properties of a deployment configuration, not fixed properties of the model itself.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Context Windows and Memory Management<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Every inference call operates within a <strong>context window<\/strong>, which is the maximum sequence length the model can process in a single forward pass. For GPT-4, the context window is 128K tokens; for Gemini 1.5 Pro, it extended to 1 million tokens; Llama 3.1 supports 128K. Context window length is not a free parameter, rather, it is constrained by the quadratic <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>O<\/mi><mo stretchy=\"false\">(<\/mo><msup><mi>n<\/mi><mn>2<\/mn><\/msup><mo stretchy=\"false\">)<\/mo><\/mrow><annotation encoding=\"application\/x-tex\">O(n^2)<\/annotation><\/semantics><\/math> attention cost and, critically, by KV cache memory.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">As established in <a href=\"https:\/\/learnerbox.net\/blog\/ai-theory\/how-large-language-models-work-part-2-the-attention-mechanism\/#comments\">Part 2<\/a>, the KV cache stores the key and value tensors for every previous token at every layer, avoiding redundant recomputation during autoregressive generation. The memory footprint is:<math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\" display=\"block\"><semantics><mrow><mtext>KV&nbsp;cache&nbsp;memory<\/mtext><mo>=<\/mo><mn>2<\/mn><mo>\u00d7<\/mo><mi>n<\/mi><mo>\u00d7<\/mo><msub><mi>N<\/mi><mtext>layers<\/mtext><\/msub><mo>\u00d7<\/mo><msub><mi>n<\/mi><mtext>heads<\/mtext><\/msub><mo>\u00d7<\/mo><msub><mi>d<\/mi><mi>k<\/mi><\/msub><mo>\u00d7<\/mo><mtext>bytes&nbsp;per&nbsp;element<\/mtext><\/mrow><annotation encoding=\"application\/x-tex\">\\text{KV cache memory} = 2 \\times n \\times N_{\\text{layers}} \\times n_{\\text{heads}} \\times d_k \\times \\text{bytes per element}<\/annotation><\/semantics><\/math><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For a model with 96 layers, 96 heads, <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><msub><mi>d<\/mi><mi>k<\/mi><\/msub><mo>=<\/mo><mn>128<\/mn><\/mrow><annotation encoding=\"application\/x-tex\">d_k = 128<\/annotation><\/semantics><\/math>, processing a 128K-token context in FP16: <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mn>2<\/mn><mo>\u00d7<\/mo><mn>128000<\/mn><mo>\u00d7<\/mo><mn>96<\/mn><mo>\u00d7<\/mo><mn>96<\/mn><mo>\u00d7<\/mo><mn>128<\/mn><mo>\u00d7<\/mo><mn>2<\/mn><mo>\u2248<\/mo><mn>601<\/mn><\/mrow><annotation encoding=\"application\/x-tex\">2 \\times 128000 \\times 96 \\times 96 \\times 128 \\times 2 \\approx 601<\/annotation><\/semantics><\/math> GB. This exceeds the VRAM of any single current GPU by a factor of roughly 10, which is why long-context inference requires either model parallelism across multiple devices, quantisation of KV cache entries to lower precision (INT8 or INT4), or approximate attention methods that reduce what must be stored.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Several efficient attention variants address this scaling problem. <a href=\"https:\/\/arxiv.org\/abs\/2205.14135\" rel=\"noopener\">Flash Attention (Dao et al., 2022)<\/a> reorders the attention computation to avoid materialising the full <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>n<\/mi><mo>\u00d7<\/mo><mi>n<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">n \\times n<\/annotation><\/semantics><\/math> attention matrix in high-bandwidth memory, reducing memory complexity from <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>O<\/mi><mo stretchy=\"false\">(<\/mo><msup><mi>n<\/mi><mn>2<\/mn><\/msup><mo stretchy=\"false\">)<\/mo><\/mrow><annotation encoding=\"application\/x-tex\">O(n^2)<\/annotation><\/semantics><\/math> to <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>O<\/mi><mo stretchy=\"false\">(<\/mo><mi>n<\/mi><mo stretchy=\"false\">)<\/mo><\/mrow><annotation encoding=\"application\/x-tex\">O(n)<\/annotation><\/semantics><\/math> while maintaining identical numerical output. Grouped-query attention (GQA), used in Llama 2 and 3, shares key and value heads across multiple query heads, reducing KV cache size by a factor of <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>g<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">g<\/annotation><\/semantics><\/math> (the group size) without significant quality degradation. Sliding window attention, used in Mistral, restricts each token to attend only within a fixed window of recent tokens, allowing arbitrarily long sequences at the cost of cross-window recall.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Emergent Capabilities and Phase Transitions<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">One of the most scientifically consequential, and practically important, observations in LLM scaling is the phenomenon of <strong>emergent capabilities<\/strong>: abilities that are essentially absent in smaller models and appear abruptly as scale crosses some threshold, without being explicitly trained for.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Wei et al. (2022) documented dozens of such capabilities: few-shot chain-of-thought reasoning, multi-step arithmetic, word unscrambling, and logical deduction all exhibit sharp phase transitions: near-zero performance at sub-threshold scales, near-human performance above it. The sharpness of these transitions distinguishes emergence from smooth capability growth and has profound implications for predicting what a model trained at a given scale will be able to do.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The mechanism underlying emergence is debated. One influential account (<a href=\"https:\/\/papers.neurips.cc\/paper_files\/paper\/2022\/file\/dfc310e81992d2e4cedc09ac47eff13e-Paper-Conference.pdf\" rel=\"noopener\">the &#8220;grokking&#8221; hypothesis, from Power et al. at Anthropic<\/a>) suggests that models first memorise training examples, then undergo a phase transition in which they discover a compressed algorithmic solution that generalises to held-out data. Another account, from Anthropic&#8217;s interpretability research, suggests that emergent capabilities correspond to the model assembling multi-step circuits, consisting of sequences of attention heads and FFN layers that compose to implement a non-trivial algorithm, and that these circuits can only form once the model has sufficient depth and width to represent all required intermediate computations simultaneously.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">From an engineering standpoint, emergence creates a prediction problem. The GPT-3 scaling curve gave no warning that a GPT-4-scale model would exhibit chain-of-thought reasoning, code execution, or structured tool use. This motivates careful capability elicitation and evaluation at each new model generation \u2014(<a href=\"https:\/\/research.ibm.com\/blog\/what-is-red-teaming-gen-AI\" rel=\"noopener\">the practice of <strong>red-teaming<\/strong><\/a>) as a safety and capability discovery discipline.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Chain-of-Thought and Reasoning Models<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The most practically significant emergent capability is multi-step reasoning \u2014 and the discovery that it can be dramatically improved by prompting or training the model to externalise its intermediate steps.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong><em>Chain-of-thought prompting<\/em><\/strong> (Wei et al., 2022) established that providing examples of step-by-step reasoning in the prompt elicits dramatically better performance on multi-step arithmetic, commonsense reasoning, and symbolic manipulation tasks without any additional training. The effect is robust and scales with model size: smaller models gain little from chain-of-thought, but models above approximately 100B parameters show large, consistent improvements.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong><em>Reasoning models<\/em><\/strong> \u2014 exemplified by OpenAI&#8217;s o1 and o3, and Anthropic&#8217;s Claude&#8217;s extended thinking mode \u2014 take this further by training models to produce extended internal reasoning traces before generating a final answer. The training procedure uses reinforcement learning on verifiable outcomes: the model is rewarded for producing correct final answers to problems where correctness can be checked algorithmically (mathematics, code execution, formal logic), and the RL signal drives the model to develop longer, more structured reasoning traces that are instrumentally useful for producing correct outputs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The result is a qualitatively different inference regime. A standard GPT-style model generates tokens in a single forward pass per token, with effective reasoning depth bounded by model depth. A reasoning model generates a long internal monologue, often thousands of tokens of scratchpad, before committing to an answer, effectively trading inference-time compute for reasoning quality. This represents a fundamental shift in the compute profile of AI: capability is no longer a fixed function of model size, but can be increased at inference time by allocating more tokens to reasoning.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Open Frontiers: Mechanistic Interpretability, Multimodality, and Agents<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Three research frontiers are most likely to define the next phase of LLM development.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Mechanistic interpretability<\/strong> is the program of reverse-engineering what computations specific model components implement. The goal is to go beyond behavioural evaluation \u2014 what the model does \u2014 to structural understanding \u2014 what algorithm it uses to do it. Anthropic&#8217;s superposition hypothesis (Elhage et al., 2022) established that neural networks represent more features than they have dimensions by encoding features as directions in a high-dimensional space and tolerating controlled interference between them. The subsequent Sparse Autoencoder (SAE) program \u2014 also led at Anthropic \u2014 has made it possible to decompose model activations into sparse, interpretable features: human-understandable concepts that each activate for a specific, semantically coherent set of inputs. SAE-based interpretability tools are now being applied to frontier models at production scale, with the goal of identifying circuits responsible for deception, sycophancy, and unsafe behaviours before deployment.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Multimodality<\/strong> extends the transformer architecture beyond text. Vision-language models (GPT-4V, Gemini, Claude 3) process images by encoding them through a vision encoder \u2014 typically a Vision Transformer (ViT) \u2014 into a sequence of patch embeddings that are projected into the LLM&#8217;s token embedding space and concatenated with text tokens before the first transformer layer. Audio-language models (GPT-4o&#8217;s audio mode) follow an analogous pattern with a spectrogram encoder. The frontier is native multimodality \u2014 a single model trained end-to-end on text, image, audio, and video tokens simultaneously, rather than modality-specific encoders bolted onto a text backbone.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Agentic systems<\/strong> extend the inference loop beyond token generation to include tool use, memory retrieval, and sequential decision-making. An agent wraps an LLM in a loop: the model generates text that includes structured tool calls (web search, code execution, database queries); the tool results are appended to the context; the model continues generating, possibly issuing further tool calls, until it produces a final response. Multi-agent systems extend this further: multiple LLM instances, each with different system prompts and tool access, communicate with each other through structured message passing. The engineering challenges are significant \u2014 context management, tool reliability, error recovery, and safety alignment in agentic settings are all active areas of research \u2014 but the capability ceiling of agentic LLMs is substantially higher than single-turn generation.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">A Map of the Whole<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Across this five-part series, we have traced the complete path from raw string to generated output:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Tokenization<\/strong> \u2014 BPE or SentencePiece converts text into integer token IDs from a vocabulary of 32K\u2013256K entries.<\/li>\n\n\n\n<li><strong>Embedding<\/strong> \u2014 each token ID is projected into a <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>d<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">d<\/annotation><\/semantics><\/math>d-dimensional vector; positional information is added via learned embeddings, sinusoidal encoding, or RoPE.<\/li>\n\n\n\n<li><strong>Attention<\/strong> \u2014 <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>N<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">N<\/annotation><\/semantics><\/math>N transformer blocks each apply multi-head self-attention: Q, K, V projections; scaled dot products; causal masking; softmax; value aggregation.<\/li>\n\n\n\n<li><strong>Feed-forward network<\/strong> \u2014 each block applies a position-wise two-layer MLP with SwiGLU activation, implementing key-value memory over learned factual associations.<\/li>\n\n\n\n<li><strong>Training<\/strong> \u2014 next-token prediction loss over trillions of tokens; AdamW with cosine decay; Chinchilla-optimal compute allocation; distributed parallelism at scale.<\/li>\n\n\n\n<li><strong>Alignment<\/strong> \u2014 SFT on human demonstrations, reward model training on preference rankings, RLHF with PPO or DPO to concentrate capability toward preferred outputs.<\/li>\n\n\n\n<li><strong>Inference<\/strong> \u2014 temperature scaling, nucleus or min-<math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>p<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">p<\/annotation><\/semantics><\/math>p sampling, KV cache management, and extended chain-of-thought reasoning to generate high-quality outputs efficiently.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">The transformer is a simple, composable architectural primitive. What it does, when trained at sufficient scale on sufficient data, and aligned to human preferences, is not simple at all.<\/p>\n\n\n\n<h6 class=\"wp-block-heading\"><em><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">This concludes the five-part series on how large language models work. If you have found this series useful, the natural next steps are the mechanistic interpretability literature (Anthropic&#8217;s Transformer Circuits thread), the Chinchilla and scaling laws papers, and Neel Nanda&#8217;s open-source interpretability tooling at TransformerLens.<\/mark><\/em><\/h6>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This is the final part of a five-part series on the internal mechanics of large language models. Parts 1\u20134 covered tokenization, embeddings, attention, the transformer block, and the training and alignment pipeline. Part 5 addresses inference: how a trained model generates text, the mathematics of sampling, context window management, emergent capabilities, and the open research frontiers shaping the next generation of LLMs. From Trained Weights to Generated Text A trained, aligned LLM is a fixed mathematical function: given a sequence of input tokens, it produces a probability distribution over the next token. Inference is the process of repeatedly applying this function to generate text, while the engineering decisions made at inference time have a surprisingly large impact on the quality, diversity, safety, and cost of model outputs. At each generation step tt, the model computes:P(tn+1\u2223t1,t2,\u2026,tn;\u2009\u03b8)=softmax(WU\u22c5hn(N))P(t_{n+1} \\mid t_1, t_2, \\ldots, t_n;\\, \\theta) = \\text{softmax}(W_U \\cdot \\mathbf{h}_n^{(N)}) where hn(N)\u2208Rd\\mathbf{h}_n^{(N)} \\in \\mathbb{R}^d is the final-layer hidden state at position nnn, WU\u2208R\u2223V\u2223\u00d7dW_U \\in \\mathbb{R}^{|V| \\times d} is the unembedding matrix (often tied to the transpose of the input embedding matrix WEW_EWE\u200b), and the resulting vector of logits over \u2223V\u2223|V| vocabulary entries is passed through softmax to produce a probability distribution. A token is then drawn from this distribution (called the sampling step) appended to the context, and the process repeats. The Mathematics of Sampling How a token is selected from the output distribution is not trivial. Naive greedy decoding that always selects the highest-probability token tends to produce repetitive, degenerate outputs. Real systems use one or more of the following strategies. Temperature scaling. Before applying softmax, the logits are divided by a temperature parameter T&gt;0T &gt; 0T>0:PT(tn+1=k)=exp\u2061(zk\/T)\u2211jexp\u2061(zj\/T)P_T(t_{n+1} = k) = \\frac{\\exp(z_k \/ T)}{\\sum_j \\exp(z_j \/ T)} As T\u21920T \\to 0, the distribution concentrates on the single highest-logit token, equivalent to greedy decoding. As T\u2192\u221eT \\to \\infty, the distribution approaches uniformity with maximum entropy, maximum randomness. Values of T\u2208[0.6,1.0]T \\in [0.6, 1.0] are typical for creative generation; T\u2208[0.0,0.3]T \\in [0.0, 0.3] for precise factual or code generation tasks. Temperature does not change which token is most probable; instead, it changes how peaked or flat the distribution is. Top-k sampling. The distribution is truncated to only the kk highest-probability tokens, which are then renormalised and sampled from. A typical value is k=40k = 40. Top-kk prevents the model from sampling tokens with negligible probability, but it is sensitive to the shape of the distribution. In a uniform distribution, k=40k = 40 keeps 40 of many reasonable options; in a very peaked distribution, k=40k = 40 may retain tokens with near-zero probability. **Nucleus (top-pp) sampling.** Rather than fixing the number of tokens, nucleus sampling fixes the cumulative probability mass: the smallest set of tokens Vp\\mathcal{V}_p\u200b such that \u2211k\u2208VpP(tk)\u2265p\\sum_{k \\in \\mathcal{V}_p} P(t_k) \\geq p is retained and renormalised. A typical value is p=0.9p = 0.9 or p=0.95p = 0.95. Nucleus sampling adapts naturally to the distribution&#8217;s shape. A peaked distribution retains few tokens, a flat one retains many &#8211; this is now the dominant strategy in production systems. Min-p sampling. A newer variant, increasingly adopted in open-source inference stacks, sets a dynamic minimum probability threshold relative to the top token: any token with P(tk)&lt;pmin\u2061\u00d7P(tmax\u2061)P(t_k) &lt; p_{\\min} \\times P(t_{\\max}) is discarded. This keeps tokens that are meaningfully competitive with the best option while discarding genuinely improbable ones, and empirically reduces repetition more effectively than top-ppp at matched quality. In practice, production inference systems combine multiple strategies: temperature scaling applied first to reshape the distribution, followed by top-pp or min-pp truncation, followed by top-kk as a hard ceiling. The specific combination and hyperparameters are treated as tunable properties of a deployment configuration, not fixed properties of the model itself. Context Windows and Memory Management Every inference call operates within a context window, which is the maximum sequence length the model can process in a single forward pass. For GPT-4, the context window is 128K tokens; for Gemini 1.5 Pro, it extended to 1 million tokens; Llama 3.1 supports 128K. Context window length is not a free parameter, rather, it is constrained by the quadratic O(n2)O(n^2) attention cost and, critically, by KV cache memory. As established in Part 2, the KV cache stores the key and value tensors for every previous token at every layer, avoiding redundant recomputation during autoregressive generation. The memory footprint is:KV&nbsp;cache&nbsp;memory=2\u00d7n\u00d7Nlayers\u00d7nheads\u00d7dk\u00d7bytes&nbsp;per&nbsp;element\\text{KV cache memory} = 2 \\times n \\times N_{\\text{layers}} \\times n_{\\text{heads}} \\times d_k \\times \\text{bytes per element} For a model with 96 layers, 96 heads, dk=128d_k = 128, processing a 128K-token context in FP16: 2\u00d7128000\u00d796\u00d796\u00d7128\u00d72\u22486012 \\times 128000 \\times 96 \\times 96 \\times 128 \\times 2 \\approx 601 GB. This exceeds the VRAM of any single current GPU by a factor of roughly 10, which is why long-context inference requires either model parallelism across multiple devices, quantisation of KV cache entries to lower precision (INT8 or INT4), or approximate attention methods that reduce what must be stored. Several efficient attention variants address this scaling problem. Flash Attention (Dao et al., 2022) reorders the attention computation to avoid materialising the full n\u00d7nn \\times n attention matrix in high-bandwidth memory, reducing memory complexity from O(n2)O(n^2) to O(n)O(n) while maintaining identical numerical output. Grouped-query attention (GQA), used in Llama 2 and 3, shares key and value heads across multiple query heads, reducing KV cache size by a factor of gg (the group size) without significant quality degradation. Sliding window attention, used in Mistral, restricts each token to attend only within a fixed window of recent tokens, allowing arbitrarily long sequences at the cost of cross-window recall. Emergent Capabilities and Phase Transitions One of the most scientifically consequential, and practically important, observations in LLM scaling is the phenomenon of emergent capabilities: abilities that are essentially absent in smaller models and appear abruptly as scale crosses some threshold, without being explicitly trained for. Wei et al. (2022) documented dozens of such capabilities: few-shot chain-of-thought reasoning, multi-step arithmetic, word unscrambling, and logical deduction all exhibit sharp phase transitions: near-zero performance at sub-threshold scales, near-human performance above it. The sharpness of these transitions distinguishes emergence from smooth capability growth and has profound implications for predicting what a model trained at a given scale will be able to do. The mechanism underlying emergence is debated. One influential account (the &#8220;grokking&#8221; hypothesis, from Power et al. at Anthropic) suggests that models first memorise training examples, then undergo a phase transition in which they discover a compressed algorithmic solution that generalises to held-out data. Another account, from Anthropic&#8217;s interpretability research, suggests that emergent capabilities correspond to the model assembling multi-step circuits, consisting of sequences of attention heads and FFN layers that compose to implement a non-trivial algorithm, and that these circuits can only form once the model has sufficient depth and width to represent all required intermediate computations simultaneously. From an engineering standpoint, emergence creates a prediction problem. The GPT-3 scaling curve gave no warning that a GPT-4-scale model would exhibit chain-of-thought reasoning, code execution, or structured tool use. This motivates careful capability elicitation and evaluation at each new model generation \u2014(the practice of red-teaming) as a safety and capability discovery discipline. Chain-of-Thought and Reasoning Models The most practically significant emergent capability is multi-step reasoning \u2014 and the discovery that it can be dramatically improved by prompting or training the model to externalise its intermediate steps. Chain-of-thought prompting (Wei et al., 2022) established that providing examples of step-by-step reasoning in the prompt elicits dramatically better performance on multi-step arithmetic, commonsense reasoning, and symbolic manipulation tasks without any additional training. The effect is robust and scales with model size: smaller models gain little from chain-of-thought, but models above approximately 100B parameters show large, consistent improvements. Reasoning models \u2014 exemplified by OpenAI&#8217;s o1 and o3, and Anthropic&#8217;s Claude&#8217;s extended thinking mode \u2014 take this further by training models to produce extended internal reasoning traces before generating a final answer. The training procedure uses reinforcement learning on verifiable outcomes: the model is rewarded for producing correct final answers to problems where correctness can be checked algorithmically (mathematics, code execution, formal logic), and the RL signal drives the model to develop longer, more structured reasoning traces that are instrumentally useful for producing correct outputs. The result is a qualitatively different inference regime. A standard GPT-style model generates tokens in a single forward pass per token, with effective reasoning depth bounded by model depth. A reasoning model generates a long internal monologue, often thousands of tokens of scratchpad, before committing to an answer, effectively trading inference-time compute for reasoning quality. This represents a fundamental shift in the compute profile of AI: capability is no longer a fixed function of model size, but can be increased at inference time by allocating more tokens to reasoning. Open Frontiers: Mechanistic Interpretability, Multimodality, and Agents Three research frontiers are most likely to define the next phase of LLM development. Mechanistic interpretability is the program of reverse-engineering what computations specific model components implement. The goal is to go beyond behavioural evaluation \u2014 what the model does \u2014 to structural understanding \u2014 what algorithm it uses to do it. Anthropic&#8217;s superposition hypothesis (Elhage et al., 2022) established that neural networks represent more features than they have dimensions by encoding features as directions in a high-dimensional space and tolerating controlled interference between them. The subsequent Sparse Autoencoder (SAE) program \u2014 also led at Anthropic \u2014 has made it possible to decompose model activations into sparse, interpretable features: human-understandable concepts that each activate for a specific, semantically coherent set of inputs. SAE-based interpretability tools are now being applied to frontier models at production scale, with the goal of identifying circuits responsible for deception, sycophancy, and unsafe behaviours before deployment. Multimodality extends the transformer architecture beyond text. Vision-language models (GPT-4V, Gemini, Claude 3) process images by encoding them through a vision encoder \u2014 typically a Vision Transformer (ViT) \u2014 into a sequence of patch embeddings that are projected into the LLM&#8217;s token embedding space and concatenated with text tokens before the first transformer layer. Audio-language models (GPT-4o&#8217;s audio mode) follow an analogous pattern with a spectrogram encoder. The frontier is native multimodality \u2014 a single model trained end-to-end on text, image, audio, and video tokens simultaneously, rather than modality-specific encoders bolted onto a text backbone. Agentic systems extend the inference loop beyond token generation to include tool use, memory retrieval, and sequential decision-making. An agent wraps an LLM in a loop: the model generates text that includes structured tool calls (web search, code execution, database queries); the tool results are appended to the context; the model continues generating, possibly issuing further tool calls, until it produces a final response. Multi-agent systems extend this further: multiple LLM instances, each with different system prompts and tool access, communicate with each other through structured message passing. The engineering challenges are significant \u2014 context management, tool reliability, error recovery, and safety alignment in agentic settings are all active areas of research \u2014 but the capability ceiling of agentic LLMs is substantially higher than single-turn generation. A Map of the Whole Across this five-part series, we have traced the complete path from raw string to generated output: The transformer is a simple, composable architectural primitive. What it does, when trained at sufficient scale on sufficient data, and aligned to human preferences, is not simple at all. This concludes the five-part series on how large language models work. If you have found this series useful, the natural next steps are the mechanistic interpretability literature (Anthropic&#8217;s Transformer Circuits thread), the Chinchilla and scaling laws papers, and Neel Nanda&#8217;s open-source interpretability tooling at TransformerLens.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[38],"tags":[],"class_list":["post-1050","post","type-post","status-publish","format-standard","hentry","category-ai-theory"],"_links":{"self":[{"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/posts\/1050","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/comments?post=1050"}],"version-history":[{"count":1,"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/posts\/1050\/revisions"}],"predecessor-version":[{"id":1051,"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/posts\/1050\/revisions\/1051"}],"wp:attachment":[{"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/media?parent=1050"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/categories?post=1050"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/tags?post=1050"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}