Large Language Models
Generative AI

Large Language Models

A complete technical guide to Large Language Models (LLMs): the Transformer architecture, Self-Attention ($Q, K, V$), Pre-training, Supervised Fine-Tuning (SFT), and RLHF alignment.

In 2017, a team of researchers at Google published a landmark research paper titled 'Attention Is All You Need'. At the time, they were looking for better ways to translate text between languages. In the process, they introduced the architecture that would reshape modern AI: the Transformer. Before Transformers, computers processed text word by word in sequence, much like reading through a narrow slit. By the time an algorithm reached the end of a long sentence, it often struggled to retain information from the beginning. These older recurrent models were difficult to run in parallel across modern GPUs. The Transformer changed that approach. It processes entire sentences and paragraphs all at once, using a mathematical technique called Self-Attention to calculate how every word relates to every other word in the text simultaneously. When researchers scaled this architecture to hundreds of billions of parameters and trained it on massive text collections, they created Large Language Models (LLMs). These models demonstrate impressive capabilities: writing prose, drafting code, analyzing legal contracts, and reasoning through multi-step problems.

Definition

A Large Language Model (LLM) is an autoregressive deep neural network based on the Transformer architecture, containing tens to hundreds of billions of parameters, pre-trained on large-scale text to model token probabilities and generate coherent, context-aware natural language.

Why It Matters

Historically, instructing computers required learning formal programming languages like Python, C++, or SQL. Large Language Models change this relationship by allowing people to use natural human language as an interface. An LLM can interpret requests expressed in everyday English and turn them into database queries, API calls, application code, or written summaries. Understanding how LLMs operate has become a valuable skill for software developers and technology professionals.

How It Works

Let us examine how modern frontier LLMs are built and how they generate text: 1. The Core Mechanism: Self-Attention ($Q, K, V$): Each token in a prompt is mapped to three learned vectors: • Query ($Q$): What information am I seeking? • Key ($K$): What information do I hold? • Value ($V$): What content do I pass along? The model computes dot products between every Query and all Keys, scales the scores by $\sqrt{d_k}$, applies Softmax to normalize them into weights, and calculates a weighted sum of the Values: $$\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V$$ • Multi-Head Attention: The model runs this calculation across many parallel heads (such as 32 or 64 heads), allowing different heads to track different linguistic relationships, such as grammar, pronoun references, or sentence structure. 2. Next-Token Prediction: At their core, language models operate by predicting the next token in a sequence. Given preceding tokens $t_1, t_2, \dots, t_n$, the model calculates a probability distribution across its entire vocabulary (often 50,000 to 100,000 tokens) for the next token: $$P(t_{n+1} | t_1, t_2, \dots, t_n)$$ It picks a token, appends it to the prompt, and repeats this process one token at a time. 3. The Three-Stage Training Pipeline: • Stage 1: Pre-training (Self-Supervised Learning): - Input: Trillions of tokens from books, articles, code repositories, and web content. - Outcome: A Base Model with broad factual knowledge and language patterns, though not yet tuned to converse politely. • Stage 2: Supervised Fine-Tuning (SFT / Instruction Tuning): - The model is trained on curated examples of helpful question-and-answer dialogues. - Outcome: The model learns the conversational assistant format, directly answering prompts rather than merely extending text. • Stage 3: Alignment (RLHF / DPO): - Reinforcement Learning from Human Feedback: Human evaluators rate model responses. - A reward mechanism guides the model toward helpful, honest, and safe answers, teaching it to refuse hazardous or malicious requests. 4. Generation Parameters: • Temperature: Adjusts response diversity. A temperature of 0.0 makes outputs deterministic by always selecting the highest-probability token. Higher values (like 0.7 to 1.0) flatten the distribution, encouraging more varied and creative phrasing. • Top-p (Nucleus Sampling): Limits candidate tokens to the smallest pool whose cumulative probability equals $p$ (for example, $p=0.9$ considers only the top 90% most probable tokens, filtering out unlikely choices).

The 3-Tier Transformer LLM Training & Inference Stack

1. Web-Scale Pre-Training
Parallel compute clusters train on trillions of tokens via next-token prediction
2. Base Foundation Model
Captures grammar, factual associations, and general reasoning patterns
3. Supervised Fine-Tuning (SFT)
High-quality demonstration conversations teach instruction-following behavior
4. RLHF Alignment Tuning
Reward signals and preference optimization encourage helpful and safe responses
5. Production Autoregressive Inference
Token-by-token generation with KV caching and sampling temperature controls

Key Points

  • LLMs are built on the Transformer architecture using Self-Attention ($Q, K, V$).
  • Self-attention allows the model to process tokens in parallel, connecting context across the prompt.
  • Generation works autoregressively by predicting the single most appropriate next token repeatedly.
  • The training pipeline moves from Pre-training (world knowledge) to Fine-tuning (instruction following) to Alignment (safety and helpfulness).
  • Temperature and Top-p parameters govern the balance between predictable answers and creative phrasing.

Steps

  1. Select Foundation Model Size

    Pick a model class suitable for your latency and hardware budget: compact 7B to 8B models (can run locally on laptops), 70B models (strong enterprise workhorses), or large proprietary APIs for complex reasoning tasks.

  2. Optimize Context Window & KV Caching

    Use Key-Value (KV) caching to store computed attention representations so the model does not recalculate earlier tokens at each new step.

  3. Implement Retrieval-Augmented Generation (RAG)

    Rather than relying solely on training memory for proprietary information, connect the model to a vector store that injects relevant documents directly into the prompt.

  4. Calibrate Inference Hyperparameters

    For structured extraction and code, set Temperature to 0.0 for consistency. For conversational writing or creative brainstorming, set Temperature to 0.7 or higher.

  5. Enforce Structured Output Schemas

    Use constrained decoding and schema validators (like Pydantic or TypeScript interfaces) to ensure the model returns clean, parseable JSON.

Formula

Scaled Dot-Product Attention:
\text{Attention}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \text{softmax}\left( \frac{\mathbf{Q}\mathbf{K}^T}{\sqrt{d_k}} \right) \mathbf{V}

Multi-Head Attention:
\text{MultiHead}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \text{Concat}(\text{head}_1, \dots, \text{head}_h)\mathbf{W}^O
\text{where } \text{head}_i = \text{Attention}(\mathbf{Q}\mathbf{W}_i^Q, \mathbf{K}\mathbf{W}_i^K, \mathbf{V}\mathbf{W}_i^V)

Rotary Position Embedding (RoPE):
\mathbf{R}_{\Theta, m}^d = \text{diag}\left( \mathbf{R}_{\theta_1, m}, \mathbf{R}_{\theta_2, m}, \dots, \mathbf{R}_{\theta_{d/2}, m} \right)
\mathbf{R}_{\theta_i, m} = \begin{pmatrix} \cos(m\theta_i) & -\sin(m\theta_i) \\ \sin(m\theta_i) & \cos(m\theta_i) \end{pmatrix}, \quad \theta_i = 10000^{-2(i-1)/d}

Examples

The Library Metaphor for LLMs

Pre-training is like reading through an enormous public library: the model absorbs wide-ranging information but has not learned how to converse as an assistant. Supervised fine-tuning is like training that reader to work as a helpful librarian who answers questions directly. Alignment is the training that ensures the librarian provides safe, appropriate, and verified advice.

Temperature in Action

Prompt: 'The astronaut stepped onto the surface of the...' At Temperature = 0.0: The model reliably outputs 'Moon'. At Temperature = 0.8: It might generate 'red planet' or 'distant asteroid', introducing creative variations.

Real-World Examples

Medical Examination Benchmarks

Frontier language models have been tested on standard medical licensing exam questions. When evaluated on clinical reasoning benchmarks, top models achieve passing scores well above 80%, demonstrating strong multi-step reasoning across clinical terminology and patient scenarios.

Automated Enterprise Customer Support

Major global retail and financial services companies deploy LLM-driven virtual assistants. These systems handle millions of customer conversations across dozens of languages, answering account questions, processing returns, and resolving routine requests in minutes.

Technical Examples

Autoregressive Next-Token Generation Loop in Pythonpython
import torch
import torch.nn.functional as F

def sample_next_token(logits: torch.Tensor, temperature: float = 0.7, top_p: float = 0.9) -> int:
    """Demonstrates how LLMs convert raw logits into the next predicted token."""
    # 1. Scale logits by temperature (T -> 0: greedy, T -> inf: uniform)
    scaled_logits = logits / max(temperature, 1e-5)
    
    # 2. Convert to probabilities via Softmax
    probs = F.softmax(scaled_logits, dim=-1)
    
    # 3. Top-p (Nucleus) Filtering
    sorted_probs, sorted_indices = torch.sort(probs, descending=True)
    cumulative_probs = torch.cumsum(sorted_probs, dim=-1)
    
    # Remove tokens with cumulative probability above the threshold
    sorted_indices_to_remove = cumulative_probs > top_p
    # Shift indices right to keep first token above threshold
    sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
    sorted_indices_to_remove[..., 0] = 0
    
    # Scatter back to original indices and set removed probabilities to 0
    indices_to_remove = sorted_indices_to_remove.scatter(0, sorted_indices, sorted_indices_to_remove)
    probs[indices_to_remove] = 0.0
    probs = probs / probs.sum() # Renormalize
    
    # 4. Multinomial random draw from remaining valid tokens
    next_token_id = torch.multinomial(probs, num_samples=1).item()
    return next_token_id

# Simulating a vocabulary of 5 tokens
mock_logits = torch.tensor([2.5, 4.1, 1.2, 0.1, 3.8])
chosen_token = sample_next_token(mock_logits, temperature=0.7, top_p=0.9)
print(f"Sampled Next Token ID: {chosen_token}")
This script illustrates the token sampling process used in language models: scaling raw model outputs by temperature, converting to probabilities with Softmax, applying Top-p nucleus filtering, and drawing the next predicted token.

Base Model (Raw) vs Aligned Model (Instruct / RLHF)

AspectBase Model (Raw)Aligned Model (Instruct / RLHF)
Training ObjectiveSelf-supervised text completion on broad internet corpusesSupervised instruction tuning combined with preference optimization
Behavior on PromptsContinues sentences without necessarily answering the question directlyFollows instructions and converses as an attentive assistant
Safety & GuardrailsNo built-in guardrails: reflects arbitrary text from training dataIncludes safeguards: refuses unsafe, harmful, or illegal instructions
Best Use CasesStarting point for specialized domain fine-tuning and academic experimentsEnterprise customer service, business writing, code assistants, and chat

KV-Cache Memory Consumption in Autoregressive Inference

In standard autoregressive generation, generating token $t+1$ requires computing attention between token $t$ and all prior tokens $1, \dots, t-1$. Since token embeddings $1, \dots, t-1$ are already computed, recomputing Key ($\mathbf{K}$) and Value ($\mathbf{V}$) projections across all layers on every new step leads to unnecessary slowdowns. The KV-Cache resolves this by storing previously computed $\mathbf{K}$ and $\mathbf{V}$ tensors in GPU memory. The required storage depends on context length, batch size, and layer count: $$\text{KV Cache Size (Bytes)} = 2 \times 2 \times n_{layers} \times d_{model} \times n_{ctx} \times b$$ Where: • The first $2$ accounts for both Keys and Values. • The second $2$ accounts for 16-bit precision (FP16 or BF16 = 2 bytes per element). • $n_{layers}$ is the number of transformer blocks. • $d_{model}$ is the hidden dimension ($n_{heads} \times d_k$). • $n_{ctx}$ is the current context token length. • $b$ is the inference batch size. For a 70B parameter model with 80 layers and hidden dimension 8192, running at batch size 1 with a 4096 token context in FP16 precision: $$\text{Memory} = 4 \times 80 \times 8192 \times 4096 \times 1 \approx 10.74 \text{ GB}$$ At batch size 16, this cache alone can exceed 170 GB of memory, requiring significant GPU capacity simply to hold context. This memory demand led to innovations such as Grouped-Query Attention (GQA) and PagedAttention to reduce memory footprints and eliminate fragmentation.

Post-Training Alignment: RLHF vs DPO (Direct Preference Optimization)

Base models trained on broad internet text need alignment to ensure they provide helpful, honest, and safe answers: 1. Reinforcement Learning from Human Feedback (RLHF): • Step 1: Supervised Fine-Tuning (SFT) on curated question-and-answer pairs. • Step 2: Training a Reward Model on pairs of responses where human reviewers marked one completion as preferable to another. • Step 3: Optimizing the model policy using algorithms like PPO (Proximal Policy Optimization) to maximize the reward score while penalizing large deviations from the original fine-tuned model. • RLHF is effective but requires keeping multiple models active in memory simultaneously (the generator, critic, reward model, and reference model). 2. Direct Preference Optimization (DPO): • DPO demonstrates that the constrained optimization problem can be solved mathematically without needing a separate reward model or complex reinforcement learning sampling. • The model policy is optimized directly on pairs of preferred and dispreferred responses using a clear loss formula: $$\mathcal{L}_{DPO}(\theta; \pi_{ref}) = -\mathbb{E}_{(x, y_w, y_l)}\left[ \log \sigma\left( \beta \log \frac{\pi_\theta(y_w|x)}{\pi_{ref}(y_w|x)} - \beta \log \frac{\pi_\theta(y_l|x)}{\pi_{ref}(y_l|x)} \right) \right]$$ • DPO increases the likelihood of preferred completions while lowering the probability of dispreferred ones. It provides a more stable, computationally efficient alternative to traditional RLHF pipelines.

Advantages

  • Broad linguistic capability: understands nuance, idioms, and multi-step instructions.
  • Performs in-context learning, following new tasks through examples without model retraining.
  • Acts as a flexible bridge between human requests and software APIs or code.
  • Significantly increases writing, research, and coding productivity.

Limitations

  • Can hallucinate plausible-sounding but incorrect information.
  • Limited by context window sizes, which bound the amount of active text in memory.
  • Requires substantial computing resources for high-throughput production deployment.
  • Can be susceptible to prompt injection attempts that seek to bypass safety guidelines.

Interview Questions

Derive and explain the Scaled Dot-Product Attention formula $\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V$. Why do we scale by $\sqrt{d_k}$?

Queries ($Q$) and Keys ($K$) of dimension $d_k$ are combined using the dot product $QK^T$ to measure how strongly tokens relate. We scale by $\frac{1}{\sqrt{d_k}}$ because as the dimension $d_k$ grows large, the dot products can grow quite large in magnitude, which pushes the Softmax function into areas with very small gradients. Dividing by $\sqrt{d_k}$ stabilizes the variance of the products near 1.0, keeping gradient flow healthy. Softmax turns these scores into normalized attention weights that sum to 1.0, which then weight the Value vectors ($V$).

What is In-Context Learning and how does it differ from Fine-Tuning?

Fine-Tuning updates the internal mathematical weights of the neural network using backpropagation on a domain dataset. In-Context Learning leaves the model weights completely unchanged and frozen. Instead, the model relies on its self-attention mechanism to identify patterns, instructions, and demonstration examples provided directly inside the current prompt window.

Practice Questions

  1. If a prompt contains 500 tokens and the model generates 200 output tokens, how many forward passes does the Transformer execute?
  2. Explain how Retrieval-Augmented Generation (RAG) mathematically mitigates hallucinations in Large Language Models.