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
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
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.
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.
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.
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.
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
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}")Base Model (Raw) vs Aligned Model (Instruct / RLHF)
| Aspect | Base Model (Raw) | Aligned Model (Instruct / RLHF) |
|---|---|---|
| Training Objective | Self-supervised text completion on broad internet corpuses | Supervised instruction tuning combined with preference optimization |
| Behavior on Prompts | Continues sentences without necessarily answering the question directly | Follows instructions and converses as an attentive assistant |
| Safety & Guardrails | No built-in guardrails: reflects arbitrary text from training data | Includes safeguards: refuses unsafe, harmful, or illegal instructions |
| Best Use Cases | Starting point for specialized domain fine-tuning and academic experiments | Enterprise customer service, business writing, code assistants, and chat |
KV-Cache Memory Consumption in Autoregressive Inference
Post-Training Alignment: RLHF vs DPO (Direct Preference Optimization)
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
- If a prompt contains 500 tokens and the model generates 200 output tokens, how many forward passes does the Transformer execute?
- Explain how Retrieval-Augmented Generation (RAG) mathematically mitigates hallucinations in Large Language Models.
