Generative AI

A statistical model that learned the joint distribution of data and can sample from it. Everything else — chat, code, images, agents — is engineering around that one primitive.

Contents
  1. What it is, and what it is not
  2. Anatomy of a generative AI system
  3. The transformer in one page
  4. How a model is trained
  5. Decoding: turning probabilities into text
  6. Beyond text: images, audio, video
  7. Grounding with retrieval (RAG)
  8. Prompting patterns that survive production
  9. Evaluation: what to measure
  10. Cost and latency
  11. Failure modes and mitigations
  12. Production checklist
  13. Sources

1. What it is, and what it is not

A generative model learns P(x) — the probability distribution of the training data — and then draws new samples from it. For language models the distribution is factorised one token at a time:

P(x1…xn) = ∏t=1..n P(xt | x1…xt-1)

That single equation explains most behaviour you will observe: fluent output, no source of truth, sensitivity to how the prefix is phrased, and the fact that a wrong answer is generated with exactly the same machinery as a right one.

It isIt is not
A compressor of statistical regularities in its training dataA database of facts with citations
Deterministic given a seed, temperature and promptReproducible across model versions
Excellent at transformation, summarisation, drafting, classificationReliable at exact arithmetic, current events, or counting
A component inside a system that supplies context and checksA replacement for retrieval, rules, or a business process
Mental model. Treat the model as a very well-read intern with no memory of yesterday, no access to your systems, and full confidence. The engineering job is to give it context, constrain its output, and verify what it returns.

2. Anatomy of a generative AI system

Inputuser + session Retrievalsearch + rerank Prompt assemblysystem, tools, context Modeldecode tokens Validationschema, rules, checks OutputUI or action
The model is one box in five. Most quality gains in production come from the other four.

Each stage owns a different failure mode: retrieval owns relevance, prompt assembly owns instruction drift, the model owns fluency and reasoning, validation owns correctness of contract, and output owns user trust.

3. The transformer in one page

Text is split into tokens (sub-word units). Each token becomes an embedding vector; the sequence passes through N identical blocks of self-attention plus a feed-forward network; a final linear layer scores every vocabulary item for the next position.

Self-attention

Attention(Q, K, V) = softmax( Q·KT / √dk ) · V

Each token builds a query, compares it against the keys of all previous tokens, normalises the scores with softmax, and mixes the corresponding values. The 1/√dk factor keeps the dot products from saturating the softmax as dimensionality grows.

ConceptWhat it buys youWhere you feel it
Context windowHow much text the attention can look atLong documents, chat history, agent transcripts
Causal maskToken t only sees tokens before itWhy generation is left-to-right and streaming works
KV cacheReuse of previous keys/valuesLatency and memory per concurrent request
Positional encodingOrder informationDegradation on very long or shuffled inputs
Attention is not memory. Everything the model "knows" about your session lives in the tokens you resend. Truncate the transcript and the knowledge disappears with it.

4. How a model is trained

StageObjectiveDataEffect
Pre-trainingNext-token prediction on trillions of tokensWeb, books, codeKnowledge, syntax, reasoning traces
Supervised fine-tuning (SFT)Imitate curated instruction→answer pairsTens of thousands of examplesFollows instructions, adopts format
Preference tuning (RLHF / DPO)Prefer chosen over rejected answersPairwise human or model judgementsHelpfulness, tone, refusal behaviour
DistillationSmall model mimics large model outputsTeacher generationsCheaper, faster, slightly less capable
LoRA / adaptersFine-tune low-rank deltasDomain corpusStyle and vocabulary without full retraining
Fine-tuning vs retrieval. Use retrieval when the problem is missing knowledge. Use fine-tuning when the problem is format, vocabulary or task shape. Fine-tuning facts into a model is expensive and drifts; retrieval stays auditable.

5. Decoding: turning probabilities into text

At each step the model produces a score for every token in the vocabulary. A softmax turns scores into probabilities and a decoding rule picks one.

pi = exp(zi/T) / ∑j exp(zj/T)
ParameterWhat it doesPractical setting
temperatureFlattens (high) or sharpens (low) the distribution0–0.3 for extraction and code; 0.7–1.0 for ideation
top_pKeeps the smallest set of tokens whose mass reaches p0.9–0.95; do not tune together with temperature
top_kKeeps only the k highest-probability tokensRarely needed when top_p is set
max_tokensHard stop on generation lengthAlways set it; truncation must be handled
stop sequencesEnd generation on a markerCheap way to bound structured output
Determinism. Temperature 0 makes sampling greedy, not reproducible: floating-point non-associativity, batching and provider-side version changes still move the output. Design for it — validate the contract, not the exact string.

6. Beyond text: images, audio, video

ModalityCore mechanismControls that matter
ImagesDiffusion: learn to reverse a noising process, then sample from noisePrompt, negative prompt, steps, guidance scale, seed, aspect ratio
SpeechNeural codecs plus autoregressive or flow modelsVoice, speaking rate, prosody, language
VideoTemporal diffusion or latent sequence modelsDuration, motion strength, keyframe conditioning
EmbeddingsEncoder mapping text to a vector spaceDimension, normalisation, distance metric

Diffusion is worth one formula because it explains the main knob, guidance: the model learns εθ(xt, t), the noise present at step t, and sampling walks backwards. Classifier-free guidance extrapolates between the unconditional and conditional predictions, trading diversity for prompt adherence.

7. Grounding with retrieval (RAG)

Retrieval-augmented generation replaces the model's memory with a search step whose results are pasted into the prompt. It converts an unsolvable problem (make the model know your data) into a solvable one (make search return the right chunk).

query ──▶ rewrite ──▶ embed ──▶ vector + keyword search ──▶ rerank ──▶ top-k chunks
                                                                          │
                          answer ◀── model with citations ◀── prompt ◀────┘
StageTypical failureFix
ChunkingChunks split mid-argumentOverlap, heading-aware splits, keep tables intact
EmbeddingDomain vocabulary not representedDomain-tuned or hybrid lexical + dense search
RerankingTop-k full of near-duplicatesCross-encoder rerank plus diversity (MMR)
CitationModel paraphrases beyond the sourceRequire span-level quotes; verify they exist
FreshnessIndex older than the source of truthIncremental indexing with timestamps
Retrieval cannot fix a bad question. Query rewriting, synonym expansion and filters usually move relevance more than swapping the embedding model.

8. Prompting patterns that survive production

PatternUse whenSketch
Role + contractAny task with a fixed output shape"You extract fields. Reply only with JSON matching this schema."
Few-shotFormat or judgement is hard to describe2–5 representative input/output pairs, including a hard negative
Chain of thoughtMulti-step arithmetic or logic"Work through the steps, then give the final answer on its own line."
DecompositionTask mixes independent sub-problemsOne call per sub-task, deterministic assembly
Self-checkOutput is verifiableSecond pass: "verify each claim against the sources; list failures."
Tool useData or actions live outside the modelTyped functions with validation on the way in and out
Prompt hygiene. Version prompts in the repository, pin the model version, and treat every prompt change as a code change with an evaluation run attached. A prompt nobody can diff is a configuration bug waiting to happen.

9. Evaluation: what to measure

LayerMetricNotes
Task accuracyExact match, F1, pass@kOnly valid with a stable, versioned gold set
GroundingFaithfulness, citation precisionCheck that quoted spans exist in the source
RetrievalRecall@k, MRR, nDCGMeasure separately from generation
SafetyRefusal rate on adversarial set, leakage rateNeeds a red-team corpus that grows over time
Operationsp95 latency, cost per request, error rateProduct metrics, not model metrics
PreferenceWin rate against a baselineLLM-as-judge is fast but biased; calibrate on human labels
Judge bias. An LLM judge prefers longer answers, its own family of models, and the first option it sees. Randomise order, pin the judge version, and keep a human-labelled slice as ground truth.

10. Cost and latency

cost ≈ (input tokens × pin + output tokens × pout) × requests
LeverEffectRisk
Smaller model for easy callsLarge cost cutRouting errors on edge cases
Prompt cachingCheap repeated prefixesCache invalidation when context changes
Shorter contextDirectly proportional savingsDropping evidence the answer needed
StreamingBetter perceived latencyHarder to validate before display
BatchingHigher throughputUnacceptable for interactive paths
Retrieval instead of long contextFewer tokens per callRecall risk, extra component

11. Failure modes and mitigations

FailureSymptomMitigation
HallucinationConfident, plausible, unsupportedRetrieval, mandatory citations, span verification, refusal path
Prompt injectionRetrieved text or a document overrides instructionsSeparate untrusted content, allow-lists, never let retrieved text call tools
Data leakageOther tenants' data in the answerFiltering at retrieval, per-tenant indexes, output scanning
BiasSystematic skew across groupsStratified eval sets, human review, documented limitations
DriftQuality falls after a provider updatePin versions, regression suite on every upgrade
Over-trustUsers stop checkingConfidence cues, source links, visible limitations

12. Production checklist

13. Sources