Large Language Models
How LLMs work and are built — next-token prediction, pretraining at scale and scaling laws, tokens and context windows, sampling (temperature, top-p), instruction tuning, RLHF and preference optimisation, prompting, tool use and agents, reasoning models, hallucinations, inference optimisation, and evaluation.
A large language model (LLM) is a decoder-only transformer with billions of parameters, trained on trillions of tokens of text (and often code, images and audio) to predict the next token. That simple objective, at enormous scale, produces models that can write, summarise, translate, code, reason through problems and use tools.
Next-token prediction
Given a sequence of tokens, the model outputs a probability distribution over its vocabulary (often 100k–250k tokens) for the next token:
Input: "The capital of France is"
Output: " Paris" 0.92 · " a" 0.02 · " the" 0.01 · " located" 0.01 · …Generation is a loop: sample a token, append it, run the model again. Each step attends to all previous tokens (via the KV cache).
tokens = tokenize(prompt)
for _ in range(max_new_tokens):
logits = model(tokens)[-1] # scores for the next token
next_tok = sample(logits, temperature=0.7, top_p=0.9)
if next_tok == EOS: break
tokens.append(next_tok)To predict the next word well across all of the internet's text, a model must implicitly learn grammar, facts, styles, the structure of code, and patterns of reasoning.
Tokens and context
- Text is split into sub-word tokens — about ¾ of an English word on average; other languages and code often take more tokens per word (Sequence models). Pricing and limits are counted in tokens.
- The context window is the maximum number of tokens the model can attend to at once — prompt plus output — from 8k to over 1M in recent models. Everything the model "knows" about your task must fit there (or be retrieved into it — RAG).
- LLMs are stateless between calls: chat apps resend the conversation history each turn.
Sampling
| Setting | Effect |
|---|---|
| Temperature | Divides logits before softmax: < 1 sharpens (more deterministic), > 1 flattens (more varied); 0 ≈ always the top token (greedy) |
| Top-k | Sample only from the k most likely tokens |
| Top-p (nucleus) | Sample from the smallest set of tokens whose probabilities sum to p |
| Stop sequences, max tokens | Control where output ends |
Use low temperature for extraction, classification and code; higher for brainstorming and creative writing.
How LLMs are built
- Pretraining: self-supervised next-token prediction on a huge, filtered corpus (web, books, code, papers). By far the most compute — thousands of GPUs for weeks or months. The result is a base model: a powerful text continuer, not yet a helpful assistant.
- Supervised fine-tuning (SFT / instruction tuning): train on curated examples of instructions and high-quality responses, teaching the assistant format and behaviour.
- Preference tuning: improve outputs using comparisons. RLHF trains a reward model on human preference rankings, then optimises the LLM with reinforcement learning (PPO) to maximise reward while staying close to the SFT model. DPO and related methods optimise directly on preference pairs without a separate reward model. RLAIF / constitutional approaches use AI feedback guided by written principles.
- Reinforcement learning on verifiable tasks: reward correct answers in maths and code (checked automatically), which teaches models to produce long chains of reasoning — the basis of reasoning models that "think" before answering.
- Safety training, evaluation and red-teaming throughout.
Scaling laws
Loss falls predictably as a power law in parameters, training tokens and compute. The Chinchilla result showed models were under-trained for their size: compute-optimal training uses roughly 20 tokens per parameter — and many modern models train far beyond that, because smaller models trained longer are cheaper to serve. Capabilities such as multi-step arithmetic and in-context learning become reliable only at sufficient scale.
Prompting
The prompt is the program. Good practices:
- Be clear and specific: the task, audience, format, length, constraints, and what to do when unsure.
- Provide context (documents, data) and examples of the desired output (few-shot prompting).
- Use a system prompt for role, rules and tone; delimit inputs clearly (XML tags or headings).
- Ask for step-by-step reasoning on complex problems (chain-of-thought), or use a reasoning model.
- Request structured output (JSON matching a schema) when a program consumes the result — many APIs can enforce schemas.
- Iterate with an evaluation set, not just one example.
import anthropic
client = anthropic.Anthropic()
msg = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=1024,
system="You are a support assistant for Acme. Answer only from the provided policy. "
"If the policy doesn't cover the question, say so.",
messages=[{"role": "user",
"content": f"<policy>{policy_text}</policy>\n\nCustomer: Can I return opened headphones?"}],
)
print(msg.content[0].text)Tool use and agents
LLMs can be given tools — functions described by a name, description and JSON schema. The model decides when to call one and with what arguments; your code executes it and returns the result for the model to continue.
An agent runs this loop repeatedly — plan, act with tools (search, code execution, file edits, browsers, APIs), observe, and continue — until the task is done. Coding agents, research agents and computer-use agents are built this way. Standards like the Model Context Protocol (MCP) let applications expose tools and data to models uniformly. Agent design concerns: clear tool descriptions, limits on actions, human confirmation for irreversible steps, and defence against prompt injection (malicious instructions hidden in web pages or documents the agent reads).
Adapting a model to your use case
| Approach | When |
|---|---|
| Prompting (+ few-shot examples) | Always start here |
| RAG — retrieve relevant documents into the prompt | Private, large or changing knowledge; citations (Embeddings and RAG) |
| Tools / function calling | Live data, actions, calculations |
| Fine-tuning (often parameter-efficient: LoRA, QLoRA) | Consistent style or format, narrow tasks, smaller/cheaper models matching a bigger one's quality on a task |
| Distillation | Train a small model on a large model's outputs to cut cost and latency |
Fine-tuning teaches behaviour and format better than it teaches facts; for knowledge, prefer RAG.
Limitations
- Hallucination: models generate plausible text, which is sometimes false — invented citations, APIs or facts — especially for niche topics or when asked about things not in context. Mitigate with grounding (RAG), citations, tool use, letting the model say "I don't know", and verification.
- Knowledge cutoff: no knowledge of events after training unless given tools or context.
- Reasoning errors: arithmetic slips, brittle logic on unfamiliar problems (reasoning models and tools reduce this).
- Bias, toxicity and safety risks inherited from training data; prompt injection and data leakage in applications.
- Cost and latency grow with model size and tokens.
Inference and serving
Generating tokens is memory-bandwidth bound: every token requires reading all the weights. Key optimisations:
| Technique | Benefit |
|---|---|
| KV cache | Avoids recomputing attention over the prefix |
| Quantisation (8-bit, 4-bit weights) | Smaller memory, faster; small quality loss |
| Continuous batching, PagedAttention (vLLM) | Higher throughput by batching requests at the token level and managing cache memory in pages |
| Speculative decoding | A small draft model proposes several tokens; the big model verifies them in one pass |
| Prompt caching | Reuse computation for repeated prefixes (long system prompts, documents) |
| Mixture of experts (MoE) | Only a few expert sub-networks run per token — large capacity at lower compute |
Metrics: time to first token, tokens per second, cost per million tokens.
Evaluating LLM applications
- Build a test set of realistic inputs with expected outputs or grading criteria.
- Use exact checks where possible (JSON validity, unit tests for code, correct answers), LLM-as-judge with clear rubrics for open-ended output, and human review for calibration.
- Measure groundedness/faithfulness for RAG, safety, latency and cost.
- Re-run evaluations on every prompt or model change — LLM apps regress silently.
- LLMs are decoder-only transformers trained to predict the next token; generation samples tokens one at a time.
- Context windows bound what the model can see; temperature and top-p control randomness.
- Pipeline: pretraining (base model) → instruction tuning → preference tuning (RLHF, DPO) → RL on verifiable tasks for reasoning.
- Scaling laws relate loss to parameters, data and compute.
- Prompt clearly with context, examples and structure; use tools for live data and actions; agents loop over tool calls.
- Prefer prompting and RAG before fine-tuning; mitigate hallucination with grounding and verification.
- Serving relies on KV caches, quantisation, batching, speculative decoding and caching; evaluate with test sets on every change.
QWhat is hallucination in LLMs and how can you reduce it?medium
Hallucination is when a model produces fluent but false or unsupported content, because it generates statistically plausible continuations rather than looking facts up. Reduce it by grounding answers in retrieved sources (RAG) and requiring citations, giving tools for facts and calculations, instructing the model to say when information isn't available, using lower temperature for factual tasks, constraining outputs with schemas, and verifying outputs with checks, a second model or humans for high-stakes uses.
QWhen would you fine-tune an LLM instead of using RAG?medium
Fine-tune when you need to change behaviour — a consistent format or tone, a specialised task like classification or extraction, or to get a smaller, cheaper model to perform like a larger one on a narrow task. Use RAG when the model needs knowledge that is private, large, frequently updated or must be cited, because retrieval keeps information current and traceable without retraining. They combine well: a fine-tuned model that is good at using retrieved context.