Kayavak / Recaps / Applied AI Systems
Recaps · Volume 14B
Applied AI Systems
The revision sheet of every chapter, on one page: the key ideas, the numbers worth knowing, the pitfalls and the words. Use it before an interview, after a chapter, or to find which chapter to reread. Each title opens its chapter; below each sheet are its exercises, companion and TiffinBox stage, and the misconceptions the companion corrects.
159
Key ideas
- An embedding maps content to a vector so that similar meanings are close; similarity is usually cosine (or dot product on normalised vectors).
- Modern text embeddings are trained contrastively: pull matching pairs (question/answer, title/body) together, push in-batch negatives apart.
- Bi-encoders embed query and document separately (fast, indexable); cross-encoders read them together (accurate, slow; used to rerank).
- Many models need prefixes or instructions ("query:" vs "passage:"); using the wrong one quietly lowers quality.
- Dimensions trade quality for memory and speed; Matryoshka models allow truncation; int8 and binary quantisation cut storage further.
- Embeddings are weak on exact identifiers, rare terms, negation and numbers; keep keyword search alongside.
- Changing the embedding model means re-embedding everything; vectors from different models aren't comparable.
- Choose a model by measuring it on your own golden set, not by leaderboard rank alone.
Numbers to remember
- Lab: BM25 R@5 0.768 vs LSA 256-d 0.660 on term queries; hybrid 0.778 on definition queries.
- Lab: int8 kept recall at ¼ memory; 1-bit kept 93% at 1/32.
- Random unit vectors at 1,536 dimensions: mean |cos| ≈ 0.02.
- float32 storage = vectors × dimensions × 4 bytes (1 M × 1,024-d ≈ 4 GB).
Pitfalls
- Mixing vectors from two models or model versions in one index.
- Forgetting query/document prefixes, or normalising inconsistently.
- Using a fixed similarity threshold copied from another model.
- Dropping keyword search and losing exact matches on IDs and error codes.
- Embedding text in a language or domain the model wasn't trained on without testing.
Glossary
- Embedding: a vector representation of content.
- Cosine similarity: dot product of length-normalised vectors.
- Contrastive learning: training by pulling positives together and pushing negatives apart.
- Bi-encoder / cross-encoder: separate vs joint encoding of query and document.
- Matryoshka embedding: a vector whose leading dimensions are useful on their own.
- LSA: latent semantic analysis; SVD of a term–document matrix.
160
Key ideas
- Exact search costs vectors × dimensions per query; ANN trades recall for speed; measure recall@k against exact results.
- HNSW: layered proximity graph; M (links per node; build time, memory, recall), efConstruction (build quality), efSearch (query-time recall/latency dial). Fast and accurate; memory-hungry.
- IVF: k-means partitions; nlist and nprobe trade recall for speed; works best when data clusters well.
- PQ / scalar / binary quantisation: compress vectors; rerank candidates with full vectors to recover recall.
- DiskANN-style indexes keep the graph and compressed vectors in memory and full vectors on SSD.
- Filtering: post-filtering starves selective filters; use partitioning, filter-aware traversal, or exact search on small subsets.
- Operations: upserts and deletes (tombstones, compaction), re-indexing on model change, replication, backups, per-tenant isolation.
- Options: pgvector, Elasticsearch/OpenSearch, Qdrant, Weaviate, Milvus, Pinecone, Vespa, LanceDB, FAISS as a library.
Numbers to remember
- Lab: exact 21 ms/query on 200k × 256; HNSW M=16 ef=64 recall 0.999 at 0.25 ms.
- Lab: PQ 1/32 size, recall 0.43; with exact rerank of top 100, 0.87.
- Lab: post-filtering a 1% tenant filter: recall 0.006; per-tenant index: 1.0.
- Memory: N × d × 4 bytes for float32 vectors, plus graph links (≈ M × 2 × 4 bytes per vector at layer 0).
Pitfalls
- Reporting latency without recall (or recall without latency).
- Tuning on random vectors and deploying on real embeddings (or the reverse).
- Post-filtering selective metadata filters.
- Forgetting that HNSW needs the full vectors in RAM.
- Not budgeting re-indexing time when changing embedding models.
Glossary
- ANN: approximate nearest-neighbour search.
- HNSW: hierarchical navigable small-world graph index.
- IVF: inverted-file index over k-means partitions.
- PQ: product quantisation; vectors split into sub-vectors, each replaced by a codebook index.
- Filter starvation: too few results left after post-filtering.
161
Key ideas
- RAG = retrieve relevant passages at question time + generate an answer constrained to them, with citations. RAG for knowledge, fine-tuning for behaviour.
- Parsing quality (tables, PDFs, OCR, layout) limits everything downstream.
- Chunking: structure-aware (headings, sentences), a few hundred tokens, with titles/metadata attached; measure evidence recall vs context size.
- Retrieval: BM25 + dense, fused (RRF), then a cross-encoder reranker; query rewriting, HyDE, multi-query and metadata filters as needed.
- Context construction: most relevant first, labelled sources, dedupe, budget tokens, instructions to cite and to admit missing information, and to treat sources as data.
- Permissions are enforced at retrieval time from chunk metadata, never by asking the model.
- Advanced: parent-document retrieval, contextual chunk headers, GraphRAG, agentic multi-hop retrieval.
- Failure modes: missed retrieval, wrong chunk boundaries, stale index, conflicting sources, unfaithful generation, prompt injection in documents.
Numbers to remember
- Lab: heading-aware chunks: top-5 chapter recall 0.744 with 863 words of context; 800-word chunks: 0.718 with 3,879.
- Lab: unfiltered retrieval would have leaked restricted text for 4 of 6 questions.
- Typical: 3–10 chunks of 200–500 tokens; rerank 20–100 candidates.
Pitfalls
- Judging RAG by a few demo questions instead of a golden set.
- Chunks without titles or source metadata (no citations, no filtering).
- Post-filtering permissions or, worse, relying on the prompt to hide restricted text.
- Stuffing as much as fits into the context window.
- Forgetting to re-index when documents change or are deleted.
Glossary
- Grounding: constraining an answer to supplied sources.
- Chunk: a passage stored and retrieved as a unit.
- RRF: reciprocal rank fusion; sum of 1/(k + rank) across retrievers.
- Reranker: a model that rescores query–passage pairs.
- HyDE: retrieving with a hypothetical answer generated from the question.
- Faithfulness: whether an answer is supported by the retrieved sources.
162
Key ideas
- Evaluate retrieval, generation and end-to-end separately, plus refusal behaviour.
- Golden set: real queries where possible, reference answers, relevant-source labels, unanswerable cases, coverage of important slices; version it.
- Retrieval metrics: recall@k, precision@k, hit rate, MRR, nDCG (graded relevance).
- Generation metrics: faithfulness/groundedness, answer relevance, correctness vs reference, citation accuracy.
- LLM-as-judge: scalable but biased (position, verbosity, self-preference); use rubrics, pairwise comparisons with swapped order, and calibrate against human labels.
- Deterministic checks first: citations exist and point to retrieved chunks, format, forbidden content, refusals.
- Compare systems with paired differences and confidence intervals; inspect per-question wins and losses.
- Online: thumbs up/down, follow-up rate, escalations, citation clicks; feed failures back into the golden set.
Numbers to remember
- Lab: hybrid − BM25 R@5 = +0.026 [+0.005, +0.047], paired.
- Lab: 30-question sets ranged 0.63–0.90; 300-question sets 0.73–0.81.
- Lab: copied-sentence queries 0.985 vs real-style 0.771.
- Lab: retrieval score as refusal signal AUC 0.615.
Pitfalls
- Too few questions, no confidence intervals.
- Synthetic questions that copy document wording.
- Trusting an LLM judge without checking it against humans.
- Only measuring end-to-end, so failures can't be located.
- Never testing unanswerable or permission-restricted questions.
Glossary
- Golden set: versioned evaluation questions with labels.
- MRR: mean of 1/rank of the first relevant result.
- nDCG: discounted cumulative gain normalised by the ideal ranking.
- Faithfulness: support of each claim by the provided context.
- Paired bootstrap: resampling questions to get an interval on a difference between systems.
163
Key ideas
- Fine-tune for behaviour (format, style, task skill, tool use, domain language); use retrieval for knowledge.
- Data quality beats quantity: hundreds to a few thousand clean, diverse, production-formatted examples often suffice for behaviour; dedupe; hold out a test set; remove personal data.
- Use the model's chat template exactly; mask the loss to assistant tokens.
- Hyperparameters: low learning rates for full fine-tuning (~1e-5 for large models), higher for LoRA (~1e-4); 1–3 epochs; watch held-out loss.
- PEFT: LoRA (rank, alpha, target modules), QLoRA (4-bit base), adapters per tenant/task.
- Forgetting: evaluate general skills before and after; mitigate with LoRA, replay, fewer steps.
- Evaluate with task metrics on held-out data, regression suites, and safety checks; a lower training loss is not a better model.
- Alternatives: prompt engineering, few-shot examples, distillation from a larger model, preference optimisation (chapter 164).
Numbers to remember
- Lab: malformed answers 89% → 0% after 400 SFT steps.
- Lab: held-out F1 ≈ 0.01 throughout; trained-question F1 0.914 after 1,500 steps (memorisation).
- Lab: general loss 4.227 → 5.229 (full) vs 4.858 (LoRA) after 400 steps.
Pitfalls
- Fine-tuning to inject facts that change.
- Training/serving template mismatch.
- Selecting checkpoints by training loss.
- No general-skill regression test.
- Training on data with personal information, secrets or unclear rights.
Glossary
- SFT: supervised fine-tuning on input–output demonstrations.
- Loss masking: excluding prompt tokens from the training loss.
- Chat template: the exact token format of roles and turns a model expects.
- PEFT: parameter-efficient fine-tuning (LoRA, adapters, prefix tuning).
- Replay: mixing original-distribution data into fine-tuning to limit forgetting.
164
Key ideas
- Alignment shapes a pre-trained model into a helpful, honest, harmless assistant; post-training typically = SFT → preference optimisation → safety work.
- Preference data: prompts with chosen/rejected answers from humans or AI judges; quality, diversity and confound control matter most.
- Reward model: Bradley–Terry loss −log σ(r(chosen) − r(rejected)).
- RLHF (PPO): maximise reward minus a KL penalty to the reference model; needs policy, reference, reward and value models.
- DPO: closed-form objective on pairs relative to a frozen reference; β sets drift; variants (IPO, KTO, ORPO, SimPO) change regularisation, data needs or length handling.
- Best-of-n / rejection sampling with a reward model; RL from verifiable rewards for maths and code; Constitutional AI / RLAIF for AI-generated feedback against written principles.
- Failure modes: reward hacking, length bias, sycophancy, over-refusal, mode collapse, forgetting.
- Evaluate preferences won, plus length, capability benchmarks, safety and refusal rates.
Numbers to remember
- Lab (confounded): SFT already "preferred" chosen 92% because rejected were longer; DPO collapsed answers to ~1 word.
- Lab (length-matched): preference accuracy 0.63 → 0.84; doubled-word answers 9% → 1–3%; answers 9.6 → 4–6 words.
- Lab: SFT on chosen only: 0.63 → 0.65; the rejected side carries the signal.
Pitfalls
- Preference pairs where a superficial feature (length, format, politeness) predicts the label.
- Optimising too long or with too small β.
- Judging alignment only by the training objective or reward-model score.
- Using one judge model for both training and evaluation.
- Ignoring over-refusal while measuring harmlessness.
Glossary
- Policy / reference: the model being trained / the frozen starting copy.
- KL penalty: a cost on divergence from the reference distribution.
- Bradley–Terry model: P(A preferred to B) = σ(r_A − r_B).
- Reward hacking: exploiting flaws in the reward signal.
- RLVR: reinforcement learning from verifiable rewards (tests, checkers).
165
Key ideas
- Quantisation stores numbers in fewer bits: smaller models, less memory traffic, often faster inference and cheaper hardware.
- Formats: fp32, fp16, bf16 (fp32's range, less precision), fp8 (E4M3/E5M2), int8, int4, and lower-bit codebook formats.
- Symmetric (scale) vs asymmetric (scale + zero point); granularity: per tensor, per channel, per group (32–128).
- LLMs are hard because of outliers, especially in activations; fixes: finer groups, mixed precision, SmoothQuant, AWQ, rotations (QuaRot, SpinQuant).
- Weight-only (W4A16, W8A16) speeds memory-bound decoding; weight-and-activation (W8A8, FP8) speeds compute-bound prefill.
- PTQ methods: round-to-nearest, GPTQ (second-order error compensation), AWQ (activation-aware scaling); QAT trains with quantisation in the loop.
- GGUF / llama.cpp K-quants and I-quants for CPUs and Macs; KV-cache quantisation saves memory for long contexts.
- Evaluate on your tasks: perplexity hides losses in maths, code, long context and less common languages.
Numbers to remember
- Weights memory = parameters × bits / 8 (7B: 14 GB fp16, 7 GB int8, ~3.5–4 GB int4).
- Lab: int8 Δ +0.0002–0.0005; int4 per tensor +0.159; per channel +0.030; groups of 32 +0.015; int2 +1.26.
- Lab: an outlier input channel made int4 per-channel 20× worse; groups of 32 only 3×.
Pitfalls
- Using per-tensor scales at 4 bits.
- Judging a quantised model by perplexity alone.
- Expecting speed-ups without kernels for the format on your hardware.
- Forgetting the KV cache and activations in memory budgets.
- Comparing quantised models built with different calibration data without saying so.
Glossary
- Scale / zero point: the parameters mapping integers back to real values.
- Group-wise quantisation: one scale per block of weights.
- PTQ / QAT: post-training quantisation / quantisation-aware training.
- W4A16: 4-bit weights, 16-bit activations.
- Outlier channel: a feature dimension with much larger magnitudes than others.
166
Key ideas
- Prefill (parallel over the prompt, compute-bound) and decode (one token per step, memory-bandwidth-bound).
- Metrics: TTFT, TPOT / ITL, end-to-end latency, throughput (tokens/s, requests/s), goodput under SLOs.
- KV cache: 2 × layers × KV heads × head dim × bytes per token; reduced by GQA/MQA, KV quantisation, sliding windows.
- Continuous batching + PagedAttention (block-allocated KV cache) keep GPUs busy without wasting memory.
- Prefix / prompt caching reuses KV for shared prefixes (system prompts, documents); chunked prefill and prefill–decode disaggregation balance the phases.
- Speculative decoding: a cheap draft proposes tokens, the big model verifies several in one pass; output distribution unchanged.
- Parallelism: tensor (within layers), pipeline (across layers), expert (MoE), data (replicas).
- Engines: vLLM, SGLang, TensorRT-LLM, TGI, llama.cpp, Ollama; benchmark with realistic prompt/output length distributions.
Numbers to remember
- Lab: KV cache 3.4× faster for 96 tokens, identical output.
- Lab: prefill 0.058 ms/token vs decode ≈ 2 ms/step.
- Lab: batch 64 → 14.6× throughput, 4.4× per-user step time.
- Simulation: continuous batching 0.96 slot utilisation vs 0.57 static.
- 70B-class GQA model: ≈ 320 KB of KV cache per token in fp16.
Pitfalls
- Benchmarking with fixed short prompts and outputs.
- Reporting throughput without latency percentiles (or the reverse).
- Forgetting KV-cache memory when sizing batch and context.
- Not reusing shared prefixes.
- Ignoring the cold-start time of loading weights.
Glossary
- TTFT / TPOT: time to first token / time per output token.
- KV cache: stored attention keys and values.
- PagedAttention: paged allocation of KV-cache blocks.
- Continuous batching: scheduling at the level of individual decode steps.
- Speculative decoding: draft-and-verify generation.
- GQA: grouped-query attention; several query heads share one KV head.
167
Key ideas
- Structured output turns model text into data your code can trust: JSON matching a JSON Schema, generated from typed definitions (Pydantic, Zod).
- Three levels: prompt (no guarantee), validate + repair/retry (guarantee on success), constrained decoding (guaranteed syntax).
- Constrained decoding masks invalid tokens using a grammar compiled against the tokenizer; must handle partial-token and byte-level issues.
- Validation still needed for semantics: ranges, cross-field rules, references, business logic.
- Schema design: clear names and descriptions, enums over free text, explicit nulls/"unknown", flat over deeply nested, order fields so reasoning precedes conclusions if needed.
- Streaming structured output needs incremental parsers.
- Monitor validity rate, repair rate, retry latency, refusals and field-level accuracy.
Numbers to remember
- Lab: tiny GPT valid JSON 0% unconstrained (even with 5 retries) → 100% constrained.
- Retries: with per-attempt success p, k attempts succeed with 1 − (1 − p)^k.
Pitfalls
- Treating "valid JSON" as "correct answer".
- Grammars that can reach dead states, or that cut answers off at length limits silently.
- Overly complex schemas that degrade answer quality.
- Not giving the model a way to say "unknown".
- Silent coercion (e.g. "7" → 7) hiding real errors.
Glossary
- JSON Schema: a vocabulary for describing JSON structure and constraints.
- Constrained (guided) decoding: masking tokens to satisfy a grammar.
- Logit mask: setting disallowed tokens' scores to −∞.
- Repair: fixing malformed output, by code or by re-prompting with errors.
- Typed output: parsing model output directly into a language type.
168
Key ideas
- The model emits structured call requests; the application validates, authorises, executes and returns results; the loop repeats until a final answer.
- Tool definitions: clear name, description of when to use it, strict JSON Schema (enums, ranges,
additionalProperties: false), examples where useful; few, well-separated tools beat many overlapping ones.
- Authorisation uses the authenticated user's identity and your data, never model-supplied identity; least privilege per tool and per user.
- Policy gates: human approval for irreversible, high-value or external actions; dry-run modes.
- Execution: timeouts, cancellation, sandboxes for code, rate limits, budgets per conversation.
- Idempotency keys for side-effecting tools; retries only with the same key.
- Errors: short, specific, actionable; results: shaped and truncated to what the model needs.
- Parallel tool calls, tool search/discovery for large catalogues, and protocols (MCP, chapter 172) for reuse.
Numbers to remember
- Lab: undefended harness issued 2 wrong refunds out of 10 calls and crashed on 4; defended: 0 wrong refunds, 0 crashes.
- Lab: timeout + retry without idempotency → 2 refunds; with → 1.
Pitfalls
- Passing model arguments straight to functions.
- Trusting identity, role or permissions stated in the conversation.
- Retrying side-effecting calls without idempotency.
- Returning huge raw results (whole tables, HTML) into the context.
- Tools with vague, overlapping descriptions.
Glossary
- Tool / function calling: model-generated structured requests to run code.
- Allow-list: the set of tools and arguments the harness permits.
- Human-in-the-loop approval: a person confirms a proposed action before it runs.
- Idempotency key: an identifier that makes repeated requests have one effect.
- Sandbox: an isolated environment for executing untrusted code.
169
Key ideas
- Spectrum: workflow (code-defined steps) → LLM workflow (model inside fixed steps) → agent (model chooses steps). Use the least autonomy that works.
- Agent loop: observe → decide (reason) → act (tool) → observe, until a stop condition; ReAct interleaves reasoning and acting.
- Planning: plan-and-execute, re-planning on failure, task decomposition; reflection/critique loops when feedback is checkable.
- State: messages, scratchpads, files, external state; keep observations concise.
- Environments: sandboxes, browsers, code execution, with least privilege.
- Autonomy levels and human approval for consequential actions.
- Patterns: prompt chaining, routing, parallelisation, orchestrator–workers, evaluator–optimiser; multi-agent only when it pays for its coordination cost.
- Failure modes: compounding errors, loops, tool misuse, context overload, goal drift, unsafe actions, cost blow-ups.
Numbers to remember
- p^n: 0.95²⁰ = 0.36; 0.99⁵⁰ = 0.61.
- Simulation: 90% failure detection + 1 retry → 0.86 success on 20 steps (from 0.36).
- Simulation: no loop guard → mean 549 steps; guards → max 25.
Pitfalls
- Building an agent where a workflow would do.
- Silent tool failures the agent can't see.
- No budgets on steps, tokens, money and time.
- Multi-agent designs that multiply calls without improving results.
- Granting broad credentials to a sandbox "for convenience".
Glossary
- Agent: a system in which a model directs its own sequence of actions.
- ReAct: reason + act prompting pattern.
- Orchestrator–workers: a lead model delegating sub-tasks to others.
- Evaluator–optimiser: generate, critique, revise loop.
- Autonomy level: how much an agent may do without human approval.
170
Key ideas
- Models are stateless; memory is context engineering: selecting, compressing and ordering what each call sees.
- Kinds: in-context working memory, session state, conversation history, summaries, long-term user/task memory (semantic facts, episodic events, procedural know-how), and external knowledge (RAG).
- Techniques: sliding windows, rolling summaries, retrieval over history, extracted fact stores with update/merge rules, scratchpads and files, sub-agent context isolation.
- Write-time work (extraction, dedupe, consolidation) makes read-time retrieval cheap and clean.
- Conflicts: timestamps, source pointers, "latest wins" or explicit confirmation; forgetting and expiry policies.
- Privacy: per-user/tenant isolation, consent for sensitive data, user-visible and deletable memories, retention limits, no cross-user retrieval.
- Evaluate memory: recall of needed facts, staleness, contradiction rate, extraction precision, token cost.
Numbers to remember
- Lab: truncation to the last 120 words kept 0% of early facts.
- Lab: history search returned outdated versions alongside 100% of updated facts.
- Lab: paraphrased questions: history search 33%, fact store 100% (perfect extraction assumed).
Pitfalls
- Stuffing the whole history until the window overflows.
- Retrieval memory without timestamps or update handling.
- Storing model-inferred "facts" as truth without provenance.
- Shared indexes across users without hard isolation.
- No way for users to see or delete memories.
Glossary
- Context engineering: deciding what goes into each model call.
- Working memory: information in the current context window.
- Episodic / semantic memory: records of events / distilled facts.
- Consolidation: merging and summarising memories over time.
- Provenance: a link from a stored memory to its source.
171
Key ideas
- Orchestration runs multi-step AI work as an explicit state machine/graph: sequence, branch, loop, parallel fan-out/fan-in, wait.
- Checkpointing persists step outputs and state so runs resume after crashes, deploys and long waits without repeating paid model calls.
- Idempotent side effects (keys, upserts, outbox) close the gap between acting and recording.
- Retries with back-off and jitter, per-step timeouts, overall deadlines, cancellation.
- Compensation (sagas) undoes earlier effects when a later step fails permanently.
- Human-in-the-loop: approval nodes, interrupts, edits to state, then resume.
- Durable execution platforms (Temporal, Restate, DBOS, Step Functions) vs agent frameworks (LangGraph, CrewAI, OpenAI Agents SDK, Google ADK, Microsoft Agent Framework): choose by durability needs, team skills, and determinism constraints.
- Version workflows; code changes must not corrupt in-flight runs.
Numbers to remember
- Lab: 200 runs with crashes: no checkpoints → 106 double charges, 377 model calls; checkpoints → 41 double charges, 250 calls; + idempotency → 0 duplicates.
Pitfalls
- Treating a checkpoint as exactly-once.
- Non-deterministic code inside replayed workflow logic (time, random, direct I/O).
- Keeping a process (and a GPU) alive while waiting for humans.
- Unbounded retries on non-retryable errors.
- Changing workflow code without versioning in-flight runs.
Glossary
- Durable execution: execution whose progress survives process failure.
- Checkpoint: persisted state after a step.
- Replay: re-running workflow code against recorded history to rebuild state.
- Saga / compensation: a sequence of steps with undo actions.
- Interrupt: pausing a graph for external input.
172
Key ideas
- MCP standardises how AI applications (hosts/clients) connect to capabilities (servers): N + M instead of N × M integrations.
- Server primitives: tools (model-controlled), resources (application-controlled data by URI), prompts (user-controlled templates); client features include sampling, roots and elicitation.
- JSON-RPC 2.0 messages; transports: stdio (local subprocess) and Streamable HTTP (remote); capability negotiation at initialisation (newer revisions move towards stateless requests).
- Remote servers use OAuth 2.1-based authorisation; never pass tokens through prompts; avoid token passthrough to downstream APIs.
- Threats: tool poisoning (instructions in metadata), rug pulls (definitions changing after approval), prompt injection via tool outputs, over-broad permissions, confused deputies, malicious or typosquatted servers.
- Controls: trusted sources and version pinning, definition pinning and diffing, least privilege, user approval for consequential actions, gateways and registries for organisations, audit logs.
- Related protocols: agent-to-agent (A2A), OpenAPI-described tools, provider-native tool formats.
Numbers to remember
- Lab: server start + initialise ≈ 775 ms; per-call median 1.91 ms over stdio.
- Lab: argument validation from type hints rejected bad input before tool code ran.
Pitfalls
- Auto-approving tools from servers you haven't reviewed.
- Leaking internal exception messages into tool results.
- Launching a new server process per call.
- Treating tool outputs as trusted instructions.
- Giving one server credentials that span many systems.
Glossary
- Host / client / server: the AI application / its protocol connector / the capability provider.
- Tool poisoning: malicious instructions embedded in tool metadata.
- Rug pull: a server changing definitions after approval.
- Streamable HTTP: MCP's HTTP transport with optional streaming responses.
- Sampling: a server asking the client's model to generate text.
173
Key ideas
- Every modality becomes a sequence of vectors: image patches (ViT), audio frames (spectrogram encoders, neural codecs), video frames (sampled, compressed).
- Contrastive alignment (CLIP, SigLIP) learns shared image–text spaces for search and zero-shot classification.
- Vision-language models connect a vision encoder to an LLM with a projector or cross-attention; trained on captions, interleaved documents and instructions.
- Practical vision: OCR and document understanding, charts, screenshots, UI agents; resolution and tiling choices drive accuracy and cost.
- Audio: speech recognition (Whisper-style), speech synthesis, speech-to-speech with low latency; diarisation, timestamps, accents and noise.
- Video: frame sampling, temporal grounding, long-context cost.
- Evaluation per task (OCR accuracy, WER, grounding), bias across accents and skin tones, privacy (faces, voices, documents), and injection via text in images and audio.
Numbers to remember
- Patches = (side / patch)²: 224/14 → 256; 336/14 → 576; 448/14 → 1,024.
- 30 s speech → 1,500 encoder frames (Whisper-style).
- Lab: tiny CLIP 97–99% by nearest caption; ~93% at half resolution.
Pitfalls
- Downscaling documents until text is unreadable.
- Paying for maximum resolution when a thumbnail would do.
- Trusting text extracted from images as instructions.
- Evaluating speech only on clean, single-accent audio.
- Storing faces, voices or ID documents without consent and retention rules.
Glossary
- Patch embedding: projecting an image patch to a vector.
- CLIP / SigLIP: contrastive image–text models.
- VLM: vision-language model.
- WER: word error rate for speech recognition.
- Tiling: splitting a large image into crops processed separately.
174
Key ideas
- Families: diffusion / flow matching (dominant for images, video, audio), autoregressive token models, GANs, VAEs.
- Diffusion: forward process adds noise; a network learns to predict noise (or velocity/clean signal); sampling reverses it. Samplers (DDIM, DPM-Solver) and distillation (consistency, few-step models) cut steps.
- Latent diffusion: an autoencoder compresses images; denoising runs in latent space; a text encoder supplies conditioning via cross-attention; backbones are U-Nets or Diffusion Transformers.
- Classifier-free guidance: (1 + w)·ε(cond) − w·ε(uncond); fidelity vs diversity.
- Control: image-to-image, inpainting, ControlNet-style structural conditioning, adapters (LoRA), reference images.
- Video adds temporal consistency; audio uses codecs/spectrograms; music and speech have rights and consent concerns.
- Evaluation: FID/CLIP-score-style metrics plus human preference; prompt adherence vs diversity; memorisation tests.
- Provenance (C2PA content credentials, watermarking), safety filters, likeness and copyright policies.
Numbers to remember
- Lab: DDIM 50 steps ≈ 200 steps; 1 step → blurry averages.
- Lab: guidance w = 3: requested digit 76% → 100%; within-digit spread 4.29 → 3.09.
- Lab: NN distance to training ≈ 2.8 vs 2.41 between real digits (no copying).
Pitfalls
- Too much guidance (over-saturated, repetitive outputs).
- Judging a model by cherry-picked samples.
- No memorisation or likeness checks.
- Shipping without provenance metadata or abuse safeguards.
- Ignoring the rights status of training data and reference inputs.
Glossary
- Forward / reverse process: adding noise / removing it.
- DDIM: a deterministic, few-step diffusion sampler.
- CFG: classifier-free guidance.
- Latent space: the compressed representation an autoencoder produces.
- C2PA: a standard for content credentials recording media provenance.
175
Key ideas
- Evals are the specification of an AI feature: write them first, run them on every change.
- Types: benchmarks (general capability, contamination-prone), golden datasets for your task, regression suites, human evaluation, pairwise/A-B, rubric scoring, LLM-as-judge, agent/trajectory evaluation, online metrics.
- Scoring: exact/programmatic checks first; likelihood-based multiple choice; rubrics with anchored scales; pairwise preferences with order swapping.
- LLM-as-judge biases: position, verbosity, self-preference, leniency; mitigate with rubrics, swaps, reference answers, calibration against humans, and different judge/model families.
- Statistics: confidence intervals, paired tests (bootstrap, McNemar), enough items for the effect size; report variance across seeds and prompts.
- Contamination: hold out early, deduplicate, report clean subsets, prefer fresh/private sets.
- Agent evals: task success in sandboxed environments, trajectory quality, cost, safety violations.
- Online: user feedback, task completion, escalation, A/B tests with guardrail metrics.
Numbers to remember
- Lab: fine-tuned model 46.3% overall vs 2.1% on unseen items (chance 25%).
- Lab: prompt template moved accuracy 46.3% → 30.6%.
- Lab: paired comparison 1 vs 29 disagreements → p < 0.0001.
Pitfalls
- Evaluating on data that leaked into training, prompts or retrieval.
- One prompt template, one seed, no intervals.
- Trusting an LLM judge without human calibration.
- Reporting only aggregate scores; never reading failures.
- Optimising a metric until it stops measuring the goal.
Glossary
- Contamination: overlap between evaluation and training data.
- McNemar's test: a paired test using only items where two systems disagree.
- Rubric: explicit criteria and score levels for judging outputs.
- Pairwise evaluation: choosing the better of two outputs.
- Trajectory evaluation: judging an agent's sequence of actions, not just its final answer.
176
Key ideas
- Threat model: everything in the context is potential instructions; any tool is a potential weapon; any output channel is a potential leak.
- Prompt injection (direct and indirect) can't be fully prevented by prompting or filtering; design so that a successful injection can do little harm.
- Exfiltration channels: rendered images and links, tool calls with URLs, emails, file writes. Control with allow-lists, CSP, and egress restrictions.
- Lethal trifecta: private data + untrusted content + external communication; break one leg per session or require approval.
- Excessive agency: least-privilege tools, scoped credentials, approvals, rate and spend limits, sandboxes.
- Other risks: data/model poisoning, model extraction, secrets in prompts or training data, cross-tenant leakage via caches/memory/RAG, insecure output handling (XSS, SQLi, command injection from model output).
- Controls in layers: input isolation and labelling, detection classifiers, capability gating, output encoding and sanitisation, monitoring, red-teaming, incident response.
- References: OWASP Top 10 for LLM Applications, MITRE ATLAS, NIST AI RMF.
Numbers to remember
- Lab: keyword detector caught 3/6 injections and flagged 2/6 benign texts.
- Lab: exact-host allow-list removed 3/3 exfiltration URLs, including a look-alike.
Pitfalls
- Relying on "ignore instructions in documents" in the system prompt.
- Substring checks on URLs.
- Agents with broad, long-lived credentials.
- Rendering model output as HTML without encoding.
- Shared caches or memory across tenants.
Glossary
- Direct / indirect prompt injection: via the user's input / via processed content.
- Exfiltration: moving data out to an attacker-controlled destination.
- Lethal trifecta: private data, untrusted content, external communication in one agent.
- Excessive agency: more autonomy or permission than the task needs.
- Red-teaming: adversarial testing to find failures before attackers do.
177
Key ideas
- Trace every AI request: retrieval, prompt assembly, model calls, tool calls, guardrails, post-processing, with parent–child spans.
- OpenTelemetry GenAI conventions: model, operation, token usage, finish reasons, request parameters; content capture opt-in.
- Metrics: latency (TTFT, TPOT, end-to-end), tokens, cost, error and refusal rates, cache hit rates, tool-call success, retrieval scores.
- Quality signals: online evals on sampled traces, user feedback, escalations; link traces to eval results.
- Privacy: redact at source or in the collector, minimise content capture, restrict access, set retention; telemetry is user data.
- Sampling: head vs tail; keep errors, slow and flagged traces; compute metrics before sampling.
- Tools: OpenTelemetry collectors and backends; LLM-specific platforms (Langfuse, Arize Phoenix, LangSmith, MLflow Tracing, vendor APM).
- Alerts on cost spikes, latency SLOs, context-limit proximity, refusal/error rates and drift in quality scores.
Numbers to remember
- Lab: generation 136 ms p50 vs retrieval 0.2 ms; duration correlated 0.94 with output tokens.
- Lab: 120/120 prompts exceeded the generator's 100-token window (silent truncation).
- Lab: 16 attributes leaked personal data before redaction, 0 after.
- Lab: tail sampling kept 54/120 traces.
Pitfalls
- Logging full prompts and outputs with no redaction or retention policy.
- Sampling before computing metrics.
- No alert on prompts near the context limit.
- Token and cost data not attributed to users, tenants or features.
- Traces that stop at the model call and miss tools and retrieval.
Glossary
- Span / trace: a timed operation / a tree of spans for one request.
- Semantic conventions: standard attribute names in OpenTelemetry.
- Tail sampling: deciding which traces to keep after they finish.
- Collector: a service that receives, processes and exports telemetry.
- Cost attribution: assigning token spend to users, tenants or features.
178
Key ideas
- Lifecycle: data → training → tracking → registry → evaluation gates → staged rollout (shadow, canary, A/B) → monitoring → retraining/rollback.
- Reproducibility: version code, data (snapshots/hashes), configuration, environment and seeds; record lineage.
- Registry aliases (
champion, challenger) decouple serving from versions; promotion and rollback are alias moves.
- Gates: fixed golden sets, paired comparisons, non-inferiority margins, slice checks, safety and cost checks.
- Monitoring: input drift (PSI, KS), prediction drift, outcome metrics with delayed labels, data-quality checks, latency/cost.
- Training–serving skew: same feature code in both paths; feature stores with point-in-time correctness.
- LLMOps: version prompts, retrieval configs, tools, adapters and eval sets; run evals in CI; monitor quality with sampled online evals.
- Security: safe serialisation formats, signed artefacts, provenance for third-party models.
Numbers to remember
- Lab: gate v1→v2 diff 0.000, lower bound −0.020 (canary); v1→v3 −0.100 (reject).
- Lab: PSI baseline noise with 100 rows: median 0.21, p95 0.35; unit change 12.4.
- Lab: promotion/rollback by alias in ~10 ms.
Pitfalls
- Deploying by copying model files with no lineage.
- Gates on tiny or changing evaluation sets.
- Deciding canaries on a handful of requests.
- Using textbook drift thresholds without a baseline.
- Loading untrusted pickled models.
Glossary
- Model registry: a versioned catalogue of models with metadata and aliases.
- Champion / challenger: current production model / candidate replacement.
- Canary release: sending a small share of traffic to a new version first.
- PSI: population stability index, Σ (p − q) ln(p / q) over bins.
- Training–serving skew: differences between training-time and serving-time data processing.
179
Key ideas
- Serving options: hosted APIs, managed endpoints, self-hosted engines (vLLM, SGLang, TGI, TensorRT-LLM, llama.cpp/Ollama).
- Streaming (SSE or WebSockets) for perceived latency; handle disconnects and cancel work.
- Batching: continuous batching in the engine; the web tier shouldn't block on generation.
- Gateways: authentication, rate limits and token budgets per user/tenant, routing across models/providers, retries and fallbacks, caching, logging, cost attribution.
- Capacity: concurrency × (prompt + output tokens) vs engine throughput; queue limits and load shedding (429 with Retry-After).
- Autoscaling on queue depth, KV-cache utilisation or tokens/s, not CPU; cold starts dominated by weight loading.
- Reliability: health and readiness checks, timeouts at every hop, idempotent retries, multi-region and multi-provider fallbacks.
- Cost: right-size models, route simple requests to small models, cache, quantise, use batch APIs for offline work.
Numbers to remember
- Lab: TTFT 9 ms vs full answer 184 ms at one user (streaming).
- Lab: 16 users: per-request 261 tok/s, TTFT p50 1,266 ms; batched 1,287 tok/s, TTFT 251 ms.
Pitfalls
- Running generation inside the async event loop or an unbounded thread pool.
- No admission control: overload becomes multi-minute latency.
- Autoscaling on CPU for GPU-bound work.
- Retrying non-idempotent operations across providers.
- Not cancelling generation when clients disconnect.
Glossary
- SSE: Server-Sent Events, one-way HTTP streaming.
- Gateway: a proxy enforcing policy and routing for model calls.
- Load shedding: rejecting excess work quickly to protect latency.
- Fallback: an alternative model or provider used on failure.
- Cold start: delay to start a replica, mainly loading weights.
180
Key ideas
- Reference architecture: client → gateway (auth, quotas, routing, caching) → orchestrator (workflow/agent, state) → retrieval, tools, models → guardrails → response; cross-cutting observability, evaluation, versioning, security.
- Life of a request: authenticate, budget check, input guardrails, retrieve with permissions, assemble context, call model(s), validate/structure output, output guardrails, stream, log/trace, collect feedback.
- Cost levers: model routing/cascades, prompt caching, response caching (exact and semantic), shorter outputs, batch APIs for offline work, quantised self-hosting at scale.
- Reliability: timeouts, retries with idempotency, fallbacks across models/providers, graceful degradation (e.g. "search results only" mode).
- Build vs buy: managed APIs and platforms for speed; self-host for control, data residency or unit cost at scale.
- Team practices: evals in CI, prompt/version control, incident runbooks, red-team cadence, cost reviews.
- Production readiness: quality bar met on golden sets, security review, privacy review, SLOs, dashboards and alerts, rollback plan, user feedback loop.
Numbers to remember
- Lab: semantic cache threshold 0.8 → 98.0% hits, 0 wrong; 0.6 → 249 wrong answers out of 2,000.
- Lab: Sunday/Saturday questions similarity 0.71.
- Illustrative costs: $2,700 → $544/month with prompt caching, routing and response caching.
Pitfalls
- Semantic caches without labelled-traffic thresholds or tenant scoping.
- Routing to cheaper models without per-route evals.
- No fallback when the model provider has an outage.
- Architecture with no place to enforce permissions or budgets.
- Treating the prototype's prompt as the product: no versioning, no evals, no monitoring.
Glossary
- Model routing / cascade: choosing a model per request / trying cheap models first and escalating.
- Semantic cache: reusing answers for similar requests.
- Prompt caching: provider-side reuse of processed prompt prefixes.
- Graceful degradation: reduced but safe functionality during failures.
- Guardrails: checks on inputs and outputs enforcing policy.