Large language models — the transformer-based models trained on web-scale text that now underlie most language applications, and what it takes to build, run, evaluate and use them. The treatment centres on behaviour at scale: classical language methods and the general transformer mechanism are assumed, and multi-step autonomous systems built on these models are a separate subject.
Foundations & Concepts
An LLM is a language model big enough, and trained on enough text, that one system can read and write about almost any subject instead of being built for a single task. Its starting point is a Pretrained Language Model: a network that has spent the bulk of its training doing nothing but predicting what comes next in ordinary text, with no application in mind. Because that one humble skill turns out to carry translation, summarising, question answering and programming alike, the result is usually described as a Foundation Model — a broad base that many different products are built on top of, the way one engine design ends up in several very different vehicles.
Almost every current model of this kind is a Decoder-Only Language Model, and the name describes the behaviour well. There is no separate stage that reads your input and a second one that composes an answer; there is a single stack that continues whatever text it is handed. Your question and the model's reply are one continuous stream, which is why the same model can hold a conversation, finish a half-written document, or complete a function you have only named.
The unit all of this is counted in is the Token — not quite a word, closer to a frequent fragment of one, so that a common word costs a single token while an unusual name may cost four or five. Tokens are the field's currency: the length of an input, the size of a training set, the price of a request and the speed of generation are all quoted in them. Speed in particular is reported as Tokens-per-Second, the rate at which a running model emits text — the number that decides whether a reply feels instant or whether you sit and watch it type.
Because the text a model learns from is gathered once and then frozen, every model carries a Knowledge Cutoff: a point in time after which it has read nothing at all. Ask about last week's news and a model with an older cutoff will not merely be unsure, it will have no idea the event exists. Knowing where that line falls is the first habit of using a model well, and it is the main reason fresh information is usually supplied inside the prompt rather than expected from memory.
Supplying it works because of In-Context Learning, the surprising property that a model can pick up a pattern from the text placed in front of it at the moment of use, with no change to its weights at all. Show it two examples of the format you want and the third comes back in that format. The standing instructions of a deployed product arrive the same way, through a System Prompt: a block of text placed before the conversation that fixes the model's role, tone and limits, and that the end user never sees.
The newest variation on the idea is the Reasoning Model, trained to spend tokens thinking before it answers — working a problem through in intermediate steps rather than committing to the first plausible sentence. The trade is explicit: more tokens and more waiting, in exchange for much better results on problems where one wrong early step spoils everything after it.
Architecture
Architecture is the shape of the machine that turns tokens into tokens, and three questions decide it: how the overall stack is laid out, how attention is actually computed, and how the model keeps track of order and length. Each answer is a trade between what the model can do and what it costs to run, and the choices below are where almost all of a model's practical character comes from.
Transformer Variants
The transformer comes in three layouts, and what separates them is which part of the text each half is allowed to see. An Encoder-Decoder Transformer keeps two stacks: one reads the whole input at once, the other writes the output while consulting it. That suits a task with a definite source and a definite target, such as translating a sentence. An Encoder-Only Transformer keeps just the reading half and produces a representation rather than text, which is what you want when the goal is to classify or compare rather than to write. A Decoder-Only Transformer keeps just the writing half and treats its input as the opening of what it has to continue. This is the layout large language models settled on, because a single stack then handles both halves of every job.
Making a single dense stack larger means every parameter does work for every token, and the bill grows with the model. Mixture of Experts (MoE) breaks that link: the layer holds many parallel sub-networks, the experts, and each token is sent to only a couple of them. The traffic control is Sparse Routing, a small learned gate deciding which experts see which token, so the model can carry an enormous number of parameters while the cost of any one token stays modest. The Switch Transformer is the design that made this practical, by routing each token to exactly one expert and trading a little capacity per token for a far simpler and more stable system.
Not every alternative keeps attention at all. Mamba (SSM) replaces it with a state space model that walks through the sequence carrying a compact running state, the way a reader remembers the gist of a page instead of re-reading every word on it. Its cost grows in step with length rather than with length squared, which makes very long inputs cheap, and that is why it remains the most closely watched challenger to the transformer layout.
Attention Mechanisms
Attention is the transformer's engine and also its bill: every token compares itself against every other, so naive cost rises with the square of the length. Generation makes it worse, because each new token would re-read the entire text written so far. The fix every serving system relies on is the KV Cache, which stores the keys and values already computed for earlier tokens so they are never computed twice. It turns generation into one cheap step per token, at the price of memory that grows with every token held.
That memory is what the next two designs attack. Multi-Query Attention (MQA) has all the attention heads in a layer share a single set of keys and values instead of each keeping its own, which shrinks the cache dramatically but costs a little quality. Grouped-Query Attention (GQA) is the compromise that won: heads are divided into a few groups, each group sharing one set, recovering most of the quality for most of the saving. It is now the default in mainstream open models.
A second line of work leaves the mathematics untouched and rewrites how it meets the hardware. FlashAttention computes attention in tiles that stay in fast on-chip memory and never writes the huge intermediate score matrix out at all; the result is numerically the same and the run is several times quicker. FlashAttention-2 refines the same idea with a better division of work across the chip. Sparse Attention takes the other road and changes the problem itself: each token attends only to a chosen subset of the others, such as its neighbours plus a few global anchors, so cost grows far more slowly with length and the pairs left uncompared are accepted as a loss worth taking.
Context & Position
Two practical limits follow from attention: how much text a model can hold at once, and how it knows the order of what it holds. The first is the Context Window, the maximum number of tokens an input and its reply may occupy together. It is the hard ceiling on everything you can show a model in one go, from a long document to a whole conversation's history, and when the ceiling is reached the oldest material has to be dropped or condensed.
Order has to be injected deliberately, because attention on its own sees an unordered bag of tokens. Rotary Position Embedding (RoPE) does it by rotating each token's query and key vectors through an angle proportional to its position, so that any comparison between two tokens automatically depends on the distance between them. ALiBi is simpler: it subtracts from each attention score a penalty that grows with distance, building in a gentle preference for the recent past. Both encode position in a form that keeps working, at least partly, beyond the lengths seen during training.
Partly is rarely enough, so a family of techniques stretches the reach of a model that is already trained. YARN rescales the rotations so the same weights handle much longer inputs after a short additional training run. Sliding Window Attention restricts each token to a fixed window of recent neighbours, letting information travel further in hops from layer to layer while the cost per token stays flat. Work of this kind is collected under Long-Context Extension: growing a trained model's horizon instead of paying to pretrain a long-context model from scratch. It is worth remembering that a large window is not the same as using it well; a model may accept a hundred thousand tokens and still attend poorly to what sits in the middle of them.
Pretraining & Datasets
Everything a model knows before anyone fine-tunes or prompts it comes from one long, expensive run over a very large pile of text. This section covers that run: the mechanics of the process, the actual collections of text that go into it, and the laws that let you predict what you will get out before you commit the money.
Pretraining Process
Pretraining is the phase in which the model learns language itself, by reading enormous amounts of text and repeatedly predicting the next token. No labels are needed, because the text is its own answer key, and that is exactly why the method scales: the supply of training material is the supply of writing. The size of the run is quoted in Training Tokens, the total count of tokens the model sees, now routinely in the trillions.
What constrains the run is the Compute Budget: the total arithmetic you are willing to pay for, which must be divided between making the model bigger and feeding it more tokens. Every pretraining plan is a choice about that split, and the choice cannot be revisited cheaply once the run has started.
Within the budget, what matters next is composition. The Data Mixture is the recipe of proportions — how much web text, how much code, how much reference material, how much of each language — and it shapes the finished model's strengths more directly than almost any architectural choice. Raw collections also repeat themselves heavily, so Data Deduplication (LLM) removes near-identical documents and passages before training; this both saves compute and reduces the model's tendency to memorise and recite. A further refinement is Curriculum Pretraining, which orders the material rather than shuffling it — broad and easy text first, dense or specialised text later — on the intuition that a learner benefits from a sequence, not just a volume.
Training Datasets
The pile itself is assembled from a fairly small number of public collections, and knowing them tells you a great deal about what any open model has read. The foundation of most of them is Common Crawl, a long-running open snapshot of a very large portion of the web; almost every other web dataset is a filtered descendant of it. Alongside it sit two trusted, carefully written sources that appear in nearly every mixture despite their modest size: Wikipedia Dumps, the full exported text of the encyclopedia, and BookCorpus, a collection of full-length books whose long, coherent narratives teach a model to hold a thread across thousands of tokens.
The interesting work is in the filtering, and each major dataset is essentially a published opinion about how to do it. C4 cleaned a single crawl snapshot with a set of simple, strict rules and became the standard web corpus for an entire generation of models. OpenWebText took a different signal, keeping only pages that readers had bothered to link to and recommend, as a proxy for text worth reading. The Pile went the other way and deliberately mixed many distinct curated sources, including code, academic papers and dialogue, to give a model breadth rather than just volume.
Later collections pushed filtering much harder and showed that quality can substitute for quantity. RefinedWeb argued the case most sharply, demonstrating that aggressively filtered and deduplicated web text alone can train a strong model with no curated sources propping it up. FineWeb continued in that direction at a far larger scale, publishing both the data and the filtering decisions behind it so that others could judge them. RedPajama set out to solve a different problem: reproducing the recipe behind a well-known model's training set openly, so that anyone could retrain on something comparable rather than taking a published mixture on trust.
Scaling & Emergent Behaviour
Pretraining would be pure gambling if its results were unpredictable, and the central finding of the field is that they are not. Scaling Laws are the observed, remarkably smooth relationships between compute, model size, data volume and the loss a model reaches: plot them and you get straight lines on a log scale, which means you can measure small runs and forecast a large one. That forecast is what makes a nine-figure training run a business decision rather than a bet.
The laws also answer the budget question directly. Compute-Optimal Training is the split of a fixed budget between parameters and tokens that reaches the lowest loss, and the answer was long assumed to favour ever bigger models on relatively little data. Chinchilla Scaling overturned that: for a given budget, models had been built far too large and fed far too little, and a smaller model trained on many more tokens wins. The correction reset the industry's defaults, and it has an extra payoff, because a smaller model is cheaper every single time it is served.
Not everything about scale is smooth, however. Emergent Abilities are capabilities that are absent at one scale and present at the next, appearing as a step rather than a slope — following a chain of instructions, or doing arithmetic reliably. Whether these are genuine phase changes or artefacts of how we grade all-or-nothing tasks is still argued, but they are the reason each new generation of models has to be probed afresh rather than assumed to be a slightly better version of the last.
Fine-tuning & Alignment
A freshly pretrained model knows language but has no manners and no job. Turning it into something useful takes a second, much smaller phase of training, and this section covers it in three layers: the strategies for adapting a model at all, the cheap methods that make adaptation practical on ordinary hardware, and the preference-based techniques that teach a model not just what to say but which answer is better.
Fine-tuning Strategies
Fine-tuning is the general practice of continuing to train a pretrained model on a smaller chosen set of examples so that it leans toward the behaviour you want. It is thousands of times cheaper than pretraining because it is not teaching language, only shifting an existing competence, and it is how one base model becomes a hundred specialised products.
The standard form is Supervised Fine-Tuning (SFT): you provide pairs of input and the desired output, and the model is trained to produce the output it was shown. Quality of examples matters far more than quantity here, since the model will faithfully copy whatever habits the examples contain. The most consequential use of it is Instruction Tuning, which is supervised fine-tuning on a wide variety of tasks all phrased as instructions with their answers. This is the step that converts a raw text continuation engine into something that responds to a request rather than extending it, and it is why a chat model feels so different to use than the base model underneath it.
When the gap is subject matter rather than style, the goal is Domain Adaptation (LLM): making a general model fluent in the vocabulary, conventions and reasoning of one field, such as law, medicine or a single company's internal systems. The heavier tool for that job is Continued Pretraining (LLM), which resumes plain next-token prediction on a large body of in-domain text with no labels at all. It is the right choice when the model is missing knowledge rather than missing instructions, and it is usually followed by an instruction-tuning pass to restore the conversational behaviour it blurs.
Parameter-Efficient Methods
Updating every weight of a large model needs the memory to hold the weights, their gradients and their optimiser state at once, which puts full fine-tuning out of reach for most people and produces a complete model copy for every task. The parameter-efficient family avoids both problems by freezing the original model and training something small beside it.
The method that made this mainstream is LoRA, which keeps the base weights frozen and learns a pair of small low-rank matrices alongside each one; their product is the adjustment, so a few million trained numbers can stand in for billions, and the result is a small file you can ship, swap or stack. QLoRA pushes the same trick further by holding the frozen base in 4-bit form while those small matrices train in higher precision, which is what brought the fine-tuning of very large models onto a single consumer card.
Other designs add small trainable pieces rather than side matrices. Adapter Layers insert compact trainable blocks between the existing layers, leaving everything around them untouched; the inserted blocks carry the new behaviour and can be removed to recover the original model exactly. IA3 is leaner still, learning only a handful of vectors that rescale the model's internal activations, which makes it remarkably cheap in both memory and stored size.
A third group leaves the network entirely alone and learns the input instead. Prefix Tuning learns a set of trainable vectors that act as a prepended context at every layer, steering the model from the inside without altering a weight. Prompt Tuning simplifies this to the input embeddings alone: a few soft tokens, learned rather than written, that do the work a hand-crafted prompt would do but much more precisely. P-Tuning sits between the two, generating those soft prompt vectors with a small network so that they train stably even on smaller models, where plain prompt tuning tends to struggle.
Alignment & Preference Optimization
Supervised examples can teach a model what a good answer looks like, but not what makes one good answer better than another, and for qualities like helpfulness, honesty and restraint that comparison is the only practical signal. Preference Tuning is the family of methods that learn from exactly that: pairs of responses to the same prompt, with a human judgement of which is preferable. Judging two answers is far easier and more consistent than writing the ideal one, which is what makes the data collectable at scale.
The classical pipeline turns those judgements into a trainable objective in two steps. Reward Modelling trains a separate model to predict which response a human would choose, producing a score for any answer and so standing in for a human reviewer. RLHF then optimises the language model against that score with reinforcement learning, while a penalty holds it near its starting point so it improves its answers instead of drifting into whatever text the reward model happens to like. This is the process that produced the first genuinely well-behaved assistants, and also the process whose complexity and instability motivated everything after it.
Direct Preference Optimization (DPO) removes the middle step entirely: a derivation shows the same preferences can be optimised with a simple loss applied directly to the chosen and rejected pairs, with no reward model and no reinforcement learning loop. It is far easier to run and reproduce, and it is now the common default. KTO relaxes the data requirement rather than the algorithm, learning from single responses labelled merely good or bad instead of matched pairs — which fits the feedback real products actually collect, where users rate one answer and never see its alternative.
A different answer to the cost of human labelling is Constitutional AI, where the judgements come from the model itself, guided by a short written set of principles. The model critiques and revises its own responses against that constitution, and the resulting preferences drive training. The human effort moves from labelling thousands of comparisons to writing and arguing about the rules, which has the useful side effect of making the intended behaviour explicit and reviewable rather than buried in a dataset.
Compute Requirements
Large models are as much an infrastructure problem as a research one, and the hardware bill comes in two very different shapes. Compute for Training is a single enormous outlay: a cluster running for weeks, paid once, with the result a set of weights you own. Compute for Inference is small per request and never stops, since every answer the model gives is paid for again. Over the life of a popular model, the second total quietly exceeds the first, which is why so much engineering effort goes into making a finished model cheaper to run rather than better to begin with.
Both are counted in FLOPs, the number of floating-point operations a job requires. It is the one unit that lets you compare a training run against a serving fleet, or a plan against a budget, independently of which hardware you happen to rent. The hardware itself is a class of AI Accelerators: chips built to perform vast numbers of matrix multiplications in parallel, with the memory bandwidth to keep them fed, which is the only reason models of this size are trainable at all.
In practice the binding constraint is usually not arithmetic but GPU Memory. A device has to hold the weights, the activations, the cached attention state and — during training — the gradients and optimiser state together, and that total runs several times the model's own size. When it does not fit, nothing runs at all, however much compute is available, so most of the techniques below exist to break one oversized job across many devices.
The umbrella term for that is Sharded Training: splitting a model and its training state across a cluster so that no single device needs the whole thing, at the cost of constant communication between them. Tensor Parallelism makes the cut inside each layer, dividing individual weight matrices across devices that then compute one layer together; it is fast but demands very high-bandwidth links, so it is normally kept within a single machine. Pipeline Parallelism cuts along the depth instead, giving each device a consecutive block of layers and passing activations down the line like stations on an assembly line; it is tolerant of slower links but leaves devices idle unless the work is fed through in small batches to keep every station busy.
A third approach attacks the memory overhead rather than the model. ZeRO Optimisation notices that in ordinary data-parallel training every worker keeps an identical copy of the optimiser states, gradients and parameters, and partitions each of them across the workers instead, gathering the pieces only when they are needed. The redundancy disappears, the memory per device falls by something close to the number of workers, and models that would never have fit become trainable on hardware that already exists.
Inference Optimization
A trained model is finished, but it is not yet cheap. Every reply it produces has to be paid for again: memory to hold the weights, arithmetic to push the request through them, and seconds that a waiting reader notices. This section is about the engineering that sits between a research result and a service people can afford to run. None of it tries to make the model cleverer; all of it tries to make the same model smaller, lighter and faster to serve. The work falls into three moves, each attacking a different part of the bill — shrinking the numbers the weights are stored as, removing or transferring parts of the network itself, and reorganising the stream of requests so that expensive hardware is never left idle.
Quantization Methods
Weights come out of training as high-precision floating-point numbers, which is far more detail than a finished model actually needs. Quantization exploits that slack: it stores each weight in fewer bits, keeping a scale factor so the small integers can be mapped back onto the original range when the arithmetic happens. Memory is the prize. A model whose weights occupy sixteen bits each may not fit on one accelerator; the same model at a quarter of that size might, and a model that fits on a single device avoids all the communication overhead of being split across several.
The steps are conventional. 8-bit Quantization halves the footprint and is close to free, with quality differences usually too small to notice in ordinary use. 4-bit Quantization halves it again, and this is the point where careful method starts to matter: the rounding error is now large enough that a careless implementation degrades the model visibly, while a good one stays remarkably close to the original. Four bits is what puts a large model on a single consumer graphics card, which is why so much effort has gone into doing it well.
There are two moments at which it can be done. Quantization-Aware Training (LLM) builds the rounding into training itself, letting the model see the coarse numbers it will eventually be stored in and adapt its weights to tolerate them; this gives the best quality at a given bit width, but it requires a training run, which few teams can afford for a large model. Everyone else compresses afterwards, working from the finished weights and a small sample of text. GPTQ proceeds layer by layer, choosing how to round each weight so that the layer’s output on that sample stays as close as possible to what the full-precision layer produced, and compensating for each rounding decision in the weights it has not yet fixed. AWQ starts from the observation that weights are not equally important: a small fraction of channels carry outsized activations, and protecting those while compressing the rest harder preserves quality more cheaply than treating every weight alike. GGUF is not a method but the container the results travel in — a single file holding compressed weights together with the metadata a runtime needs to load them, which is how compressed models move between machines and run on ordinary laptops.
Compression & Distillation
Compressing the numbers leaves the network’s shape untouched. The alternative is to make the network itself smaller. Model Pruning (LLM) deletes the parts that contribute least — individual weights, whole attention heads, sometimes entire layers — on the evidence that a large trained network is substantially redundant. Knowledge Distillation (LLM) reaches the same end by another route: rather than cutting a big model down, it trains a small one to imitate the big one, learning from the full distribution over next tokens rather than from text alone. The small model inherits behaviour it could never have discovered from raw data at its size, and what is compressed is the teacher’s judgement rather than its storage.
Both ideas only pay off if the runtime can exploit them. Sparse Inference is the machinery that actually skips the removed weights instead of dutifully multiplying by stored zeros; without kernels and hardware that support it, a pruned model occupies the same memory and takes the same time as before, and the saving stays theoretical. Mixed-Precision Inference is the pragmatic middle: instead of one precision everywhere, the bulk matrix multiplications run low while the few numerically delicate places — accumulations, normalisation statistics, the final output layer — are kept high. Most of the speed is captured, and the handful of operations where rounding would compound are left alone.
Decoding & Serving
Serving has an awkward shape. Tokens are produced one at a time, and each one needs the whole model read out of memory to compute a single step, so a lone request leaves most of an accelerator’s arithmetic unused and is limited by memory bandwidth instead. The remedy is to serve many requests together, but requests arrive at different moments and finish after different numbers of tokens. Continuous Batching handles that by treating the batch as a rolling population rather than a fixed group: the moment one sequence finishes, a waiting request takes its place, instead of every request idling until the slowest member of its batch is done. Throughput rises sharply and queueing time falls, with no change whatever to the model.
The other scarce resource is the memory each live conversation needs for the attention state it has accumulated. Reserving the worst case for every request wastes most of it, and growing those buffers naively fragments memory until a device with plenty of room in total has no usable block left. Paged Attention borrows the operating system’s answer and keeps that state in fixed-size pages with a lookup table, so a conversation grows page by page, pages can be shared between requests that begin from the same text, and fragmentation largely disappears. Many more conversations fit at once, which is exactly what the batching above needs in order to help.
Three techniques attack the per-step cost directly. Speculative Decoding uses a small, fast model to guess the next several tokens, then has the large model check all of them in a single pass; every guess it agrees with is a token obtained for a fraction of the usual cost, and the first disagreement simply resets the guessing, so the output is identical to what the large model would have produced alone. Flash Decoding addresses the long-input case, where a single new token must attend over an enormous history: it splits that computation across many cores and combines the partial results, keeping the hardware busy during the one step that would otherwise be hopelessly serial. Prompt Caching removes repeated work of another kind — when many requests begin with the same long preamble or document, its computed state is kept and reused rather than recomputed for each one.
These pieces are rarely assembled by hand. vLLM is the best known of the serving engines that package them together, and it is a fair summary of the whole section: paged memory, rolling batches, cached prefixes and compressed weights, combined so that the same trained model answers many more people per second on the same hardware.
Evaluation
Judging a language model is harder than judging most software, because there is usually no single correct output to compare against. The field’s answer is a collection of benchmarks, each narrowing the question to something that can be scored, plus the tooling to run them the same way twice. No one of them says whether a model is good; together they sketch a profile, and reading that profile — knowing what each test rewards and how each can be gamed — is the skill this section is about.
The broadest tests ask what a model knows. MMLU is the standard breadth exam: thousands of multiple-choice questions spread across dozens of school and professional subjects, from history to medicine, reported as the single accuracy figure that has become the headline number of model announcements. BIG-Bench approaches breadth from the opposite direction, collecting hundreds of small, deliberately strange tasks contributed by many researchers, a good number of them chosen precisely because the models of the day failed them. It works less as a scoreboard than as a probe for where capability stops.
Running such tests fairly is a problem in itself. A score depends on the prompt wording, the number of examples shown and how an answer is extracted from free-form text, so two laboratories reporting the same benchmark can differ by several points without either being dishonest. Two projects exist to pin this down. Helm is a holistic framework that evaluates models across many scenarios and many measures at once — accuracy alongside calibration, robustness, bias and cost — and publishes the results as one comparable grid, on the argument that a lone accuracy number hides more than it reveals. LM Evaluation Harness is the practical counterpart: a widely used implementation of a large library of benchmarks with fixed prompts and fixed scoring rules, which is what makes one group’s reported figure checkable by another.
Knowing things is not the same as being honest about them. TruthfulQA targets that gap, with questions built around widely repeated misconceptions, where the most statistically natural continuation of the text is a popular falsehood. A larger model that has read more of the internet can score worse than a smaller one, which is what makes the test worth having.
Reasoning gets its own benchmarks, because there the answer can be checked exactly. GSM8K is a set of grade-school word problems requiring a few arithmetic steps in the right order — easy for a person, revealing for a model, since one slip in the middle ruins the final number and no amount of fluent wording can hide it. MATH (Benchmark) raises the ceiling to competition problems, where the route to the answer may take many steps and a genuine idea, and where scores separate models that manipulate symbols from models that merely imitate their appearance. ARC sits in a different place again: grade-school science questions, split into an easy portion and a challenge portion, with the challenge half assembled from questions that straightforward word-matching and retrieval methods got wrong, so that scoring well demands a little inference rather than recall.
Code is the cleanest case of all, because a computer can grade it. HumanEval hands the model a function signature and a description of what it should do, then runs hidden tests against whatever it writes, so correctness is executed rather than judged. Because a model can be sampled repeatedly, the natural measure is Pass@k: the chance that at least one of k attempts passes the tests. It matches how such tools are really used, with a developer glancing over several suggestions and keeping one, and the gap between one attempt and ten tells you how reliably the ability is there rather than occasionally lucky.
None of the above covers what most people actually do with a model, which is to hold a conversation. Open-ended replies have no single right answer, so measurement becomes comparison. MT-Bench poses multi-turn questions across several categories and has a strong model grade the responses, which tests whether a system stays coherent when a follow-up quietly changes the task. AlpacaEval is the same idea stripped down: a fixed set of instructions, a model judge choosing between the candidate’s answer and a reference answer, reported as a win rate. Automatic judging is cheap and repeatable, and its known weakness is a taste for long, confident, well-formatted prose, which is corrected for but never entirely removed.
The final arbiter is people. Chatbot Arena shows anonymous answers from two models to the same question and asks visitors which they prefer, accumulating the votes into a rating of the kind used for chess. It cannot be revised for in advance, it reflects the messy things real users ask, and it is the hardest of these numbers to game — but it records preference rather than correctness, and a model can be liked for the wrong reasons. That is the lesson of the whole section: each of these benchmarks answers one narrow question honestly, and treating any single one of them as the score of a model is the mistake they were all built to prevent.
Popular Models
Behind the techniques sits a surprisingly short list of named model families, and the most useful way to sort them is not by size or score but by how they reach you: as a service you call over the network, as weights you download and run yourself, or as a deliberate effort to serve the languages the first two groups neglect. That division is commercial and practical rather than technical, and it decides what you are allowed to do — inspect, adapt, compress, run offline — far more than any benchmark result does.
Closed-Weight Models
These models are reachable only as a hosted service. You send text and receive text; the weights stay with the provider, who controls the version you talk to and sees the traffic you send. In exchange you get the strongest systems available with no hardware of your own and no operational work.
The GPT Series established the pattern: a lineage of successive generations, each substantially larger and trained on more text than the last, whose steady improvement was the public evidence that capability grows with scale. GPT-4 was the generation that moved these systems from impressive to professionally useful, with markedly better reasoning, much longer inputs and the ability to accept images alongside text; its size and training data were never published, marking the point at which leading laboratories stopped describing their systems in technical detail. ChatGPT matters for a different reason altogether: it was the product that wrapped a model of this family in a plain chat window and let anyone try it, turning a research curiosity into something hundreds of millions of people had an opinion about within months, and setting the conversational interface that every competitor now copies.
Two other families define the current field. Claude, from Anthropic, is built with unusual emphasis on safety, on honest refusals and on working comfortably over very long documents, which has made it a common choice for careful analytical work. Gemini, from Google, was designed from the start to handle more than text — images, audio and video arrive as naturally as words — and it is distributed less as a destination than as a capability woven into products people already use. The three families compete on much the same ground, and the practical difference for a builder is usually price, context length, latency and tone rather than any single ability.
Open-Weight Models
The other half of the field publishes its weights for download. Nothing about the model is secret, you can run it on your own hardware with your own data, adapt it, compress it and keep it working unchanged for years. The cost is that you own the serving, and the strongest open model usually trails the strongest closed one — by a gap that has been narrowing steadily.
LLaMA, from Meta, is the release that changed this picture. Weights of genuinely competitive quality became freely available, and within weeks an entire ecosystem of adaptation, compression and local serving grew around them; most of the open tooling in this chapter exists because that family gave it something worth running. Mistral built its reputation on efficiency instead of size, with compact models that matched much larger ones and were small enough to serve cheaply. Mixtral extends that line with a sparse design: the network contains many expert sub-blocks but routes each token through only a couple of them, so it carries the knowledge capacity of a large model while costing roughly what a small one costs to run.
The frontier of open weights is now plural and international. Qwen, from Alibaba, ships an unusually wide range of sizes and specialisations and is particularly strong across Chinese and English. DeepSeek became known for extracting frontier-level reasoning out of a training budget far below what the field assumed was necessary, and for publishing enough detail to be checked. Gemma is the open sibling of Google’s closed family, small and permissively licensed, aimed squarely at running on a laptop or a single card. Phi, from Microsoft, makes a pointed argument about data rather than scale: trained on heavily filtered, textbook-like material, these very small models reason far better than their size suggests. Falcon, from the Technology Innovation Institute in Abu Dhabi, was among the first high-quality families released under a genuinely permissive licence, and demonstrated that a carefully filtered web corpus could stand in for proprietary data.
Multilingual Models
Most of the models above were trained on corpora dominated by English, and their fluency drops away sharply in languages with little text online. A third group treats that as the problem to solve rather than a side effect to apologise for.
BLOOM came out of a large open scientific collaboration and was trained deliberately across dozens of natural languages and a handful of programming ones, with language communities themselves helping choose and clean the data — a different theory of how a model should be built, as well as a different model. mT5 takes a multilingual approach to the text-in, text-out framing, where every task is expressed as text to be rewritten; trained over a hundred-odd languages, it remains a dependable base to adapt for translation-like work. XGLM was built to answer a narrower question: whether learning a task from a few examples in the prompt works outside English. It balances its training data towards lower-resource languages, and its results map out where that ability holds and where it quietly fails — a reminder that capability in this field is distributed as unevenly as text is.
Building with LLMs
Everything up to here concerns making models. This section is about using one you did not make. You cannot change its weights, you cannot teach it your company’s documents by willpower, and you cannot inspect why it said what it said. What you control is the text you send in, the information you place in front of it, and the shape of the system you build around it — and that turns out to be enough to build most of what people actually ship.
Prompt Engineering
Prompt Engineering is the practice of designing that input deliberately rather than typing a request and hoping. It helps to remember what the model is doing: continuing text. A prompt is therefore less a command than the opening of a pattern you would like completed, and the craft lies in making the desired completion the obvious one — stating the task plainly, supplying the material it needs, and showing the shape of a good answer.
The moment a prompt is used more than once it becomes a piece of software, and it deserves the same discipline. Prompt Templating separates the fixed wording from the parts that change, so that a reviewed, version-controlled skeleton is filled with each request’s data instead of being retyped and quietly mutated; this is the difference between a clever prompt and a maintainable one. Role-Based Prompting sets who the model is speaking as and to whom — a cautious reviewer addressing an expert, a teacher addressing a beginner — which narrows an enormous range of possible styles and assumed knowledge to the one you wanted.
The simplest lever is how many examples you provide. Zero-Shot Prompting describes the task and asks for the answer, relying entirely on what the model already knows; it is clean, cheap, and often all you need. Few-Shot Prompting includes a handful of worked examples instead, which communicates format, tone and the handling of awkward cases far more reliably than any amount of instruction, because the model can see what you mean rather than being told. The price is input length, and the examples must be representative: a few badly chosen ones teach the wrong rule precisely as efficiently as good ones teach the right one.
For problems with steps, the prompt can shape the process instead of the format. Chain-of-Thought Prompting asks the model to work through its reasoning before committing to an answer, which gives it room to do the intermediate work in writing rather than guessing a conclusion in one leap; on multi-step problems the improvement is large. Self-Consistency Prompting builds on it by sampling several independent lines of reasoning and keeping the answer most of them reach, on the sound assumption that mistakes diverge while correct reasoning converges. Tree-of-Thought Prompting goes further still, deliberately branching into alternative partial solutions, evaluating them and abandoning the weak ones, which suits puzzles where a wrong early commitment cannot be recovered from. Self-Refinement Prompting adds a second pass of a different kind: the model criticises its own first draft against the requirements and rewrites it, often catching omissions it was blind to while producing them.
Beyond the single call, prompts become architecture. Prompt Chaining splits a job into a sequence of narrow calls, each doing one thing with the previous result as its input — extract, then classify, then write — which is easier to test, cheaper to debug and far more reliable than one heroic instruction that tries to do everything at once. Structured Output is what makes such chains mechanical: by constraining the reply to a declared set of named fields, the next stage can parse the result instead of interpreting prose, and the whole pipeline stops depending on the model’s choice of wording.
Finally, prompts can be improved by method rather than by intuition. Meta-Prompting turns the model on its own instructions, having it draft, critique or rewrite the prompt for a task — often producing a more explicit version than a person would bother to write. Automatic Prompt Optimization closes the loop and searches: candidate variants are generated, scored against examples, and the winners kept and mutated again. Both rest entirely on Prompt Evaluation — a held-out set of real cases and an agreed way to score them, so that a change can be shown to help instead of merely feeling better on the one example you happened to try. Without it, prompt work is superstition, and most prompt disputes are really disputes about the absence of a test set.
RAG
Retrieval-Augmented Generation (RAG) answers the one thing prompting alone cannot fix: the model knows nothing about your documents, your products or anything that happened after its training ended. Rather than training it on that material — slow, expensive and awkward to update — you fetch the few relevant passages at the moment a question is asked, place them in the prompt, and ask the model to answer from them. Knowledge becomes data you can edit, remove and re-index at will, the answer can point at its source, and the model is reduced from an oracle to a very capable reader. It is the single most common pattern in serious applications, and the rest of this section is how it is actually assembled.
RAG Components
Four parts do the work. The Knowledge Base is the body of trusted material the system is allowed to answer from, and its quality sets a ceiling nothing downstream can raise: stale or contradictory sources produce stale or contradictory answers, delivered with equal confidence. The Retriever turns a question into a search over that material and returns a shortlist of candidates; it must be fast, because it runs before the user sees anything, so it favours catching the right passage somewhere in its list over ranking it first. A Reranker (RAG) then reads that shortlist properly, scoring each candidate against the question with a slower and more careful model, and reorders it — a cheap addition that often improves answers more than any change to the generator. Context Window Retrieval is the budgeting decision that follows: how many of the surviving passages, and how much of the text surrounding each hit, actually travel into the prompt. Space is finite, neighbouring sentences often supply the meaning a lone passage lacks, and padding the prompt with marginal material measurably degrades the result rather than hedging against it. The Generator (RAG) finally writes the answer from the question and the selected passages, and its real job is restraint: use what is given, and say plainly when the answer is not there.
RAG Pipeline
Half of that work happens long before any question arrives. Document Chunking cuts long documents into passages small enough to be retrieved precisely and large enough to make sense on their own; cut too finely and every passage loses its context, too coarsely and each one drags in paragraphs of irrelevance. Chunk boundaries that respect the document’s own structure — sections, headings, list items — outperform fixed-length cuts almost always. Document Indexing then builds the searchable structure over those passages, which is what makes finding a handful of them among millions take milliseconds.
The rest happens per question. The Retrieval Step (RAG) searches the index and brings back candidates. Context Synthesis assembles the keepers into coherent prompt material — ordering them sensibly, dropping near-duplicates, trimming to the budget and labelling where each came from — a stage that is easy to treat as plumbing and that quietly decides how good the answer can be. Citation and Attribution carries source identity all the way through to the output, so a reader can follow a claim back to the passage it came from. That is more than a courtesy: it is the only practical way for a user to tell a grounded statement from an invented one, and it converts a fluent assertion into a checkable one.
Vector Databases & Embeddings
Searching by keyword fails the moment a question is worded differently from the document that answers it, which is most of the time. An Embedding Model solves this by mapping a piece of text to a list of numbers positioned so that closeness in that space means closeness in meaning; a question and the passage that answers it land near each other even with no words in common. A Vector Database is built to store millions of such vectors and return the nearest ones to a query quickly, which is a different problem from the one ordinary databases solve. Comparing a query against every stored vector is far too slow at that scale, so these systems rely on Approximate Nearest Neighbour Search, which organises the vectors so that only a small, promising fraction is ever examined — accepting a small chance of missing a true nearest neighbour in exchange for orders of magnitude of speed.
What this buys is Semantic Search: retrieval by meaning, tolerant of paraphrase, synonyms and clumsy phrasing. Its blind spot is exactness. Part numbers, surnames, error codes and rare jargon are precisely the tokens that meaning-based matching blurs, so production systems use Hybrid Search, running keyword and semantic retrieval together and merging the rankings, which is more robust than either alone and usually the sensible default.
The implementations differ mostly in how much operational burden they take off you. Faiss is a library of similarity-search algorithms you embed in your own program, giving fine control and no service to run. Milvus is an open-source database built to do the same job distributed across machines at large scale. Pinecone is a managed service, where indexing, scaling and uptime are someone else’s concern and the cost is a monthly bill and a dependency. Weaviate is open source with hybrid search and typed objects built in, which suits data that has structure as well as text. Chroma is deliberately small and local, the one most prototypes start with because it runs inside the application with no setup at all. The choice is an operational one; the retrieval quality comes from the chunking, the embeddings and the reranking, not from the brand of store.
RAG Patterns
Naive RAG is the straight line through all of the above: embed the question, fetch the top passages, answer from them. It works more often than its name suggests, and it fails in predictable ways — when the question is phrased unlike the documents, when the answer is spread across several of them, when the question needed no retrieval at all, or when nothing relevant exists and the model answers anyway.
Each fix addresses one of those failures. Query Rewriting is the first and cheapest: before searching, rephrase the question in the language of the corpus, expand it into several sub-questions, or resolve the pronouns that a follow-up turn left dangling. Advanced RAG is the umbrella name for that generation of refinements around the basic flow — better queries going in, reranking and filtering coming out. Modular RAG reframes the pipeline itself, treating each stage as an interchangeable component that can be swapped, repeated or skipped, so one architecture serves use cases with quite different needs instead of being rebuilt for each. GraphRAG adds structure to the knowledge rather than the plumbing: entities and the relations between them are extracted into a graph, so a question that depends on several connected facts can be answered by traversing those links, which flat passage retrieval can only stumble upon. Agentic RAG hands the control flow to the model, letting it decide whether to search at all, what to search for, whether the result is sufficient, and whether to try again differently. It is slower and costs more per answer, and it is the only one of these patterns that copes with questions whose answer cannot be planned in a single hop.
Applications
The patterns above recur in a small number of recognisable products. A Chat Assistant is the plainest: a conversational front end over a model, often with retrieval behind it, answering whatever is asked. A Conversational Agent is the more demanding relative, holding goals and state across a dialogue and taking actions in other systems rather than only producing text, which makes it useful and makes its mistakes consequential. Code Generation was the first application to reach real economic scale, helped by a feedback loop the others lack: the result compiles or it does not, and the developer reviewing it is a competent judge.
Document Question Answering is retrieval in its most recognisable commercial form — ask a question of a contract, a manual or a policy archive and get an answer with citations — and it is where attribution stops being a nicety, because the users are people who must be able to verify what they are told. Long-form Summarisation compresses material too long to read, and its real difficulty is not fluency but faithfulness and judgement about what matters; a summary that reads beautifully and drops the one clause that reverses the meaning is worse than none. Tutoring Systems (LLM) exploit something models are genuinely good at: explaining the same idea in several ways, at the learner’s pace, without impatience — while needing exactly the safeguards this chapter keeps returning to, since a confident wrong explanation is far more damaging to a beginner than to an expert. Across all six the division of labour is the same: the model supplies fluency, breadth and patience, and the system around it supplies the facts, the memory and the checks.
Challenges
The capability of these models and their trustworthiness are two different measurements, and the gap between them is where this section lives. What follows are not bugs awaiting a patch but consequences of how the models are built — statistical systems trained on enormous amounts of human text to continue it plausibly. Each one is managed rather than solved, and knowing which of them your application is exposed to is part of building it responsibly.
Hallucination is the most visible. A model will state something untrue in the same fluent, confident register it uses for everything else, inventing a citation, a figure or an entire function that does not exist. The cause is structural: it was trained to produce a likely continuation, not to track whether it knows something, so a convincing-sounding answer and a correct one are not distinguished anywhere in the process. There is no internal signal that fires when it is making things up, which is why the fixes are external — grounding answers in retrieved sources, demanding citations, and treating any unverified claim as a draft.
Factuality is the positive property being chased, and stating it as a goal exposes how hard it is to measure. Facts are not evenly difficult: some are stable and widely recorded, some change weekly, some are disputed, and some depend on a context the question never supplied. Improving factuality in practice means narrowing what the model is asked to assert from memory and teaching it to decline — a model that reliably says it does not know is more useful than one that is right slightly more often and silent never.
Bias and Fairness follows from the training material. A model absorbs the regularities of the text it was shown, including which groups are described in which terms and which perspectives are abundant or missing, then reproduces those patterns in its output — in who it assumes a surname belongs to, which dialects it treats as errors, whose questions it answers well. The harms are unevenly distributed, which is what makes this a fairness question and not merely an accuracy one, and filtering is no clean remedy: removing text to reduce one kind of bias also narrows whose language is represented at all.
Data Privacy cuts in two directions. The training corpus, scraped at internet scale, contains personal information its subjects never offered for the purpose, and a model can reproduce passages it effectively memorised, so private text can resurface in an unrelated answer. Separately, every prompt sent to a hosted model is data leaving your organisation — customer records, draft contracts, source code — which is why so many deployments choose weights they can run themselves even at a cost in quality.
Model Interpretability is the difficulty underneath the others. The behaviour arises from billions of numbers with no human-readable account of why any particular answer was produced, so a wrong answer cannot be traced to a faulty rule and corrected. You can only observe inputs and outputs, probe with more examples, and constrain the system from outside — which is uncomfortable wherever a decision must be audited, explained or defended.
Alignment is the name for the whole problem seen from above: making a system’s behaviour match what people actually intend, including the intentions nobody wrote down. It is hard because the target cannot be fully specified — be helpful, be honest, be harmless pull against each other in real requests, and any proxy objective can be satisfied in letter while being missed in spirit. The other five challenges are, in a sense, the places where this one surfaces, and progress on them has come less from a single breakthrough than from accumulating careful practice around systems whose insides remain opaque.
Security & Safety
Most of what goes into building with a language model quietly assumes that the text reaching the model is well meant. This is the part of the subject where that assumption is dropped. A language model receives instructions and data through the same channel — to it, both are simply text — so it has no dependable way to tell a developer's directions from a stranger's. That single structural weakness explains the majority of the attacks below, and it is why securing a model feels less like patching software and more like handling untrusted input that can argue back.
Adversarial Prompts is the umbrella idea: input shaped deliberately to make a model act against the intent of whoever deployed it. Its most familiar form is Prompt Injection, where the attacker's text smuggles in directions of its own — ignore what you were told earlier, do this instead — and the model, having no way to rank one instruction above another, tends to follow the newest and most confidently phrased one. Indirect Prompt Injection is the same trick delivered at a distance. Instead of typing at the model, the attacker plants the instructions in material the model will later read on a user's behalf: a web page, a shared document, a calendar invitation, an email footer. The user asks an innocent question, the application pulls in the poisoned source, and the hidden instruction runs although nobody typed it. This indirect path is the harder one to defend, because the attack surface grows with every new source the application is allowed to touch.
Jailbreaks aim at a different target — not the surrounding application's logic but the model's own trained-in refusals. Role-play framings, fictional wrappers, invented emergencies, obfuscated spelling and slow escalation across several turns all work the same way: they make a request the model would decline look like something it is happy to do. Prompt Leaking is the quieter cousin, coaxing the model into reciting the confidential instructions and examples it was configured with. Those often encode business rules, internal policy or private data, and a leak is frequently the reconnaissance step that lets a later jailbreak be aimed precisely.
Toxic Output needs no attacker at all. Abusive, demeaning or dangerous text can surface from an entirely ordinary request, because the model learned from human writing that contains plenty of it. That makes toxicity an output-side concern: something to be measured and filtered where text leaves the system, not merely guarded at the point where text comes in.
A second family of attacks ignores the model's behaviour and goes after what it absorbed while training. A Data Extraction Attack tries to make the model reproduce fragments of its training data word for word — credentials, personal records, copyrighted passages — which is possible because rare strings seen during training can be memorised rather than generalised. Membership Inference is subtler and asks only a yes-or-no question: was this particular record part of the training data? That sounds modest until the membership itself is the secret, as with a patient register or a breached dataset. Model Inversion works in the opposite direction, reconstructing the attributes of training examples from the model's responses, so that something resembling the original input can be recovered without ever seeing it. Together these three make an uncomfortable point: a trained model is not a clean abstraction over its data but a lossy, partially readable copy of it.
Text Watermarking faces outward instead of defending inward. By nudging the model's choice among equally plausible next words, it embeds a statistical signature that a holder of the detection key can recognise later, while a human reader notices nothing. It answers provenance — did this machine write this passage? — rather than preventing misuse, and it is fragile under heavy paraphrasing. Read as a whole, this subject argues for defence in layers: treat every incoming text as untrusted, constrain what the model is permitted to do rather than only what it is asked to do, watch outputs as attentively as inputs, and assume that anything the model memorised can eventually be probed for.