SD·196A
AI Depth I: Python, ML Fundamentals, LLM Application Architecture, RAG, Evaluation
The first half of the AI track at L5/L6, with experiments: ladders; Python at L3 — the GIL measured (four threads no faster than one for CPU-bound code, processes twice as fast on two cores, a thousand I/O waits in 0.21 s with asyncio), the data model, and packaging; ML fundamentals at L4 — data leakage that turns random labels into 80% "accuracy", generalisation, metrics and the baselines that keep you honest; LLM application architecture as layers and patterns (prompting, structured output, tools, workflows versus agents, routing, caching, guardrails) with the decisions that matter; RAG measured rather than assumed — recall@3 and MRR for word-level BM25, character n-grams and hybrid fusion on a labelled query set, where hybrid did not win; and evaluation as statistics — bootstrap intervals and a paired McNemar test showing why 120 cases couldn't confirm a 7.5-point improvement that 480 could.
Start here: what L5/L6 depth in AI engineering looks like
An AI engineer at L2 can call a model API, build a RAG prototype and fine-tune with a tutorial. At L3 they understand why it works: Python's execution model, how models learn and overfit, how retrieval and context assembly shape answers, why evaluation is statistics. At L4 they can find why answers got worse after a "harmless" change. At L5/L6 they design AI systems whose quality, cost and safety are measured and controlled, and run them in production.
One example from the foundations: Python's GIL
Most AI code is Python, and Python (CPython, with its default build) runs only one thread of Python code at a time: the Global Interpreter Lock. The lab measured what that means:
| Work | 1 copy | 2 copies in 2 threads | 2 copies in 2 processes |
|---|---|---|---|
| pure-Python loop | 0.72 s | 1.47 s (no speed-up) | 0.76 s (2× throughput) |
| NumPy matrix multiplications | 0.34 s | 0.34 s (2× throughput) | — |
| 100 waits of 0.1 s (I/O) | — | 0.11 s with 100 threads | 0.10 s with asyncio |
Threads didn't help pure-Python computation at all; separate processes did. NumPy work ran in parallel in threads because NumPy releases the GIL inside its C code. Waiting (network, disk) overlapped fine with threads or asyncio. This is why data loaders use processes, inference servers push work into native code, and an L3 engineer reaches for the right tool (or Python's newer free-threaded build) instead of "adding threads".
How deep to go in AI engineering foundations
Volume 17 defines six mastery levels; for this chapter's topics they look like this:
| Level | You can… |
|---|---|
| L1 | explain Python's runtime basics, ML fundamentals, LLM app patterns and RAG |
| L2 | build a RAG or LLM feature with evaluation, in clean, tested Python |
| L3 | explain the GIL and async, leakage and generalisation, retrieval and context design, eval statistics |
| L4 | diagnose performance, leakage, retrieval and evaluation problems |
| L5 | design LLM application architectures with measured quality, cost and latency |
| L6 | run AI applications in production with continuous evaluation and governance |
The ladders
| Level | Python | ML fundamentals | LLM application architecture | RAG | Evaluation |
|---|---|---|---|---|---|
| L1 | Knows syntax, the standard library | Knows supervised/unsupervised, train/test split | Knows prompts, context windows, tokens | Knows retrieve-then-generate | Knows you should test AI outputs |
| L2 | Writes idiomatic Python: comprehensions, dataclasses, typing, virtual envs, pytest | Trains and evaluates scikit-learn models with pipelines and cross-validation | Builds a feature with an SDK: prompts, structured output, tool calls | Builds a pipeline: chunk, embed, store, retrieve, prompt | Writes example-based tests and a small eval set |
| L3 | Explains the object model, the GIL, the import system, memory management, async | Explains bias/variance, regularisation, gradient descent, loss functions, why metrics differ | Explains decoding, attention costs, why models hallucinate, tool-calling mechanics, caching | Explains embeddings and similarity, ANN indexes, chunking effects, rerankers, hybrid search | Explains metric choice, sampling error, LLM-as-judge biases, contamination |
| L4 | Profiles and fixes performance and memory issues; packaging conflicts | Diagnoses leakage, overfitting, distribution shift, label problems | Diagnoses failures by tracing: prompt, context, tool, model | Diagnoses retrieval vs generation failures; measures recall | Diagnoses misleading evals; reads error analyses |
| L5 | Designs packages and services; chooses concurrency model | Chooses problem framing, model class, metrics, baselines | Chooses patterns: single call, workflow, agent; model routing; guardrails | Chooses retrieval strategy, index, chunking, freshness, access control | Designs eval strategy: offline sets, online metrics, statistics, release gates |
| L6 | Runs Python services in production | Monitors models in production; retraining | Runs AI features: cost, latency, safety, upgrades | Runs RAG over changing corpora with permissions | Runs continuous evaluation and incident review |
Python at L3
The GIL, measured
CPython's global interpreter lock lets only one thread execute Python bytecode at a time. Threads still help when they wait (I/O releases the GIL), and native code (NumPy, PyTorch) releases it during heavy work, but pure-Python CPU-bound code doesn't run in parallel on threads:
# Python concurrency at L3: threads don't speed up CPU-bound pure-Python code under the GIL; processes do; asyncio wins for I/O waits
def cpu(n=10_000_000):
s = 0
for i in range(n): s += i * i
return s
timed("CPU-bound x4, sequential", lambda: [cpu() for _ in range(4)])
timed("CPU-bound x4, 4 threads", lambda: list(ThreadPoolExecutor(4).map(lambda _: cpu(), range(4))))
timed("CPU-bound x4, 2 processes (2 cores)", lambda: list(ProcessPoolExecutor(2).map(cpu, [10_000_000] * 4)))
async def io_wait(): await asyncio.sleep(0.2)
async def many(): await asyncio.gather(*(io_wait() for _ in range(1000)))
timed("1000 × 200 ms I/O waits, asyncio", lambda: asyncio.run(many()))
3.13.17 GIL enabled: True
CPU-bound x4, sequential 2.36 s
CPU-bound x4, 4 threads 2.41 s
CPU-bound x4, 2 processes (2 cores) 1.22 s
1000 × 200 ms I/O waits, asyncio 0.21 s
Python 3.13 introduced an experimental free-threaded build (PEP 703, python3.13t) without the GIL, and 3.14 made it officially supported (no longer experimental), though not the default; C extensions must declare compatibility. L5 rule for AI services: the model or vector math runs in native code (releasing the GIL), request handling is I/O-bound (asyncio: FastAPI, httpx), and CPU-heavy pure-Python steps (parsing, chunking large documents) go to process pools or separate workers.
Other L3 essentials
- Data model: everything is an object; names are references; mutable default arguments are evaluated once (
def f(x=[])shares one list across calls);__eq__/__hash__consistency (as with Java'sequals/hashCode, 194A). - Memory: reference counting plus a cycle collector; large lists of small objects are expensive (a Python
intis 28 bytes); NumPy arrays and generators keep memory flat for big data. - Async: one event loop thread; a blocking call (synchronous HTTP client,
time.sleep, heavy CPU) insideasync defstalls every request on that loop (the same failure as in Node and tokio, 194C). - Packaging and environments: reproducible environments with lockfiles (
uv, Poetry, pip-tools); CUDA-specific wheels for PyTorch; pin versions in production images. "Works on my machine" in ML is usually an unpinned library or CUDA mismatch. - Typing: hints aren't enforced at runtime; validate at boundaries with pydantic (as with zod in TypeScript, 195A), and run a type checker (mypy, pyright) in CI.
ML fundamentals at L4: leakage
The most damaging ML bug is evaluation that looks great and means nothing. Data leakage is information from the evaluation data influencing training. A demonstration with pure noise: 200 subscribers, 5,000 random features, random churn labels. There is nothing to learn; honest accuracy must be about 50%.
# Data leakage, the classic L4 bug: selecting features on ALL data before cross-validation finds "signal" in pure noise
X = rng.normal(size=(200, 5000)) # 200 subscribers, 5,000 random features
y = rng.integers(0, 2, size=200) # random churn labels: there is NOTHING to learn
leaky_X = SelectKBest(f_classif, k=20).fit_transform(X, y) # selection saw every label
leaky = cross_val_score(LogisticRegression(max_iter=1000), leaky_X, y, cv=5).mean()
honest = cross_val_score(make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000)), X, y, cv=5).mean()
feature selection before CV (leaky): accuracy 80%
feature selection inside CV (honest): accuracy 51% (chance = 50%)
Selecting the 20 features most correlated with the labels using all the labels picks features that happen, by chance, to align with the test folds' labels too. Putting selection inside the pipeline (fit on each training fold only) gives the honest answer. Other common leaks: scaling or imputing with statistics from all data; target information in features ("refund_issued" predicting churn); time leakage (random splits on time-series data let the model see the future; split by time); duplicates or near-duplicates across train and test (the same customer in both); and, for LLM evaluation, contamination (test questions present in the model's training data or in few-shot examples).
The rest of the L3/L4 core (Volume 14, chapters 143–158): generalisation and the bias–variance trade-off; regularisation; loss functions and what they optimise; metrics chosen for the decision (precision/recall and their thresholds for imbalanced problems, calibration when probabilities drive actions, ranking metrics for recommendation); baselines (a constant predictor, a simple rule, logistic regression) that any complex model must beat; and distribution shift in production (the world changes after training).
LLM application architecture
An LLM feature is a stack of decisions. From simplest to most autonomous:
- Single call with a well-designed prompt: classification, extraction, summarisation, rewriting.
- Structured output with schema validation (194F): the output feeds code.
- Retrieval-augmented: the model answers from your data, provided in context.
- Workflows: fixed sequences or graphs of LLM calls and code (route → retrieve → draft → check → format), each step testable; parallelisation and voting where useful.
- Agents: the model decides which tools to call and when to stop, in a loop. Most flexible; hardest to make reliable, predict cost for, and secure.
L5 decisions across the stack:
| Decision | Options | Driven by |
|---|---|---|
| Pattern | Single call → workflow → agent | Task open-endedness; evals showing simpler fails |
| Model | Large frontier model vs smaller/faster; one vs routed | Quality on your evals, latency, cost, data constraints |
| Context | Prompt engineering, few-shot, retrieval, long context, fine-tuning | Whether the gap is knowledge (retrieval), behaviour/format (prompting, fine-tuning), or capability (bigger model) |
| Output contract | Free text, JSON schema, function calls | Who consumes the output |
| Tools | Read-only vs side-effecting; confirmation | Risk of the action (194F) |
| Caching | Prompt-prefix caching, response caching, semantic caching | Repetition in traffic; freshness needs |
| Guardrails | Input/output classifiers, policy checks, PII redaction, allow-lists | Risk and regulation |
| Hosting | Provider API, cloud-hosted, self-hosted open weights | Cost at volume, data residency, control (196B) |
The fine-tuning rule of thumb: retrieval for knowledge, fine-tuning for behaviour. Fine-tuning teaches style, format and task-specific skills reliably; it's a poor way to inject facts that change (they go stale and the model may still confabulate).
RAG, measured
A retrieval-augmented system can fail in two places: retrieval (the right passage isn't in the context) or generation (it is, but the model ignores, misreads or contradicts it). Measure them separately. Retrieval is measurable without any model: a set of queries with the passage that answers each, and metrics like recall@k (is the right passage in the top k?) and MRR (mean reciprocal rank of the first relevant result).
A TiffinBox help-centre corpus of 15 articles and 15 realistic queries (including paraphrases and typos), comparing word-level BM25, character n-gram TF-IDF (robust to typos and partial words), and reciprocal rank fusion (RRF) of the two:
def rank_bm25(q): return list(np.argsort(-bm25.get_scores(tok(q))))
def rank_chars(q): return list(np.argsort(-(D @ chars.transform([q]).T).toarray().ravel()))
def rank_rrf(q, k=60): # reciprocal rank fusion of the two rankings
s = np.zeros(len(ids))
for r in (rank_bm25(q), rank_chars(q)):
for pos, i in enumerate(r): s[i] += 1 / (k + pos + 1)
return list(np.argsort(-s))
BM25 (words) recall@3 60% MRR 0.59 misses: ['what happens to money when I skip', 'how long does a refund take', 'I am allergic to peanuts', 'tax invoice download', 'where is my delivery guy', 'cancle my subscripton']
char n-gram TF-IDF recall@3 93% MRR 0.88 misses: ['where is my delivery guy']
hybrid (RRF) recall@3 80% MRR 0.68 misses: ['I am allergic to peanuts', 'tax invoice download', 'where is my delivery guy']
What the numbers teach:
- Lexical retrieval misses vocabulary mismatch and typos ("cancle my subscripton", "allergic" vs "allergies", "delivery guy" vs "rider"). Dense embeddings handle paraphrase much better ("delivery guy" ≈ "rider"), which is why production systems use them (the sandbox can't download an embedding model, so character n-grams stand in for robustness to spelling).
- Hybrid didn't win here: fusing a weak ranker with a strong one dragged the strong one down on this corpus. Hybrid search usually helps in practice (dense and lexical fail on different queries: exact codes, names and rare terms favour BM25), but "usually" is not "here": measure on your queries.
- 15 queries is far too few to choose a production design (next section); this is a demonstration of method.
The RAG design space at L5: chunking (by document structure, with overlap; sizes chosen by measurement; heading-aware, as built in Volume 14), metadata and filters (product, language, date, permissions: retrieve only what the user may see, enforced at query time), embeddings model choice (domain, languages: Hindi and Telugu queries for TiffinBox), ANN index (HNSW, IVF; recall vs latency vs memory), reranking (a cross-encoder rescoring the top 50: often the biggest single quality gain), query rewriting, freshness (re-index on change via events), citations shown to users, and the "I don't know" path when retrieval confidence is low.
L6: corpora change daily; permissions change; documents are deleted and must disappear from indexes (data-protection obligations); embedding model upgrades require re-embedding everything; retrieval quality regresses silently unless evaluated continuously.
Evaluation as statistics
An eval set is a sample; its accuracy is an estimate with error. Comparing two prompts on the same cases, with paired outcomes (A right/B wrong, and so on):
def make(n, a_right, fixed, broken):
"""Paired outcomes: A is right on a_right cases; B fixes `fixed` of A's failures and breaks `broken` of its successes."""
a = np.zeros(n, bool); a[:a_right] = True
b = a.copy(); b[a_right:a_right + fixed] = True; b[:broken] = False
return a, b
def ci(x, reps=10_000): # bootstrap 95% interval for accuracy
return np.percentile(rng.choice(x, size=(reps, len(x))).mean(axis=1), [2.5, 97.5])
# exact McNemar test: only discordant cases carry information
p = binomtest(only_b, only_b + only_a, 0.5).pvalue
--- 120 eval cases
prompt A: 70.0% correct, 95% CI [61.7%, 78.3%]
prompt B: 77.5% correct, 95% CI [70.0%, 85.0%]
discordant: B-only right 14, A-only right 5 → McNemar exact p = 0.064
--- 480 eval cases
prompt A: 70.0% correct, 95% CI [65.8%, 74.0%]
prompt B: 77.5% correct, 95% CI [73.8%, 81.0%]
discordant: B-only right 56, A-only right 20 → McNemar exact p = 4.4e-05
With 120 cases, a 7.5-point improvement isn't distinguishable from noise (intervals overlap heavily; the paired test gives p ≈ 0.06). With four times as many cases at the same rates, it's clear. Lessons for L5 eval design:
- Size eval sets for the differences you care about: ±8 points of uncertainty at n = 120 means you can't detect 3-point regressions. Hundreds to thousands of cases for release gates; stratify by category so each important slice has enough.
- Use paired comparisons on the same cases (more powerful than comparing two independent accuracies), and run each case several times if outputs are sampled (non-determinism adds variance).
- LLM-as-judge scales grading of open-ended answers, but judges have biases (position, verbosity, self-preference): calibrate them against human labels on a subset, use pairwise comparisons with swapped order, and give rubrics, not vibes.
- Error analysis beats aggregate scores: read failures, cluster them, fix the biggest cluster (Volume 14, ch. 177).
- Offline and online: offline evals gate releases; online metrics (task success, user corrections, escalations, thumbs, A/B tests) confirm value; both are needed because offline sets drift from real traffic.
- Contamination and overfitting to the eval: keep a held-out set you don't tune against; refresh with recent production cases.
Lab: Python concurrency for AI workloads
Setup. CPython 3.13.17 (standard build, GIL enabled) on the lab machine (2 CPUs), NumPy with BLAS threading pinned to 1 thread per call (OMP_NUM_THREADS=1, OPENBLAS_NUM_THREADS=1) so parallelism comes only from what the experiment creates. Each NumPy measurement follows a warm-up call.
Results
| Workload | Configuration | Time | Throughput vs one copy |
|---|---|---|---|
| pure-Python loop (20 M multiply-adds) | 1 copy | 0.72 s | 1× |
| 2 copies, 2 threads | 1.47 s | 1× | |
| 2 copies, 2 processes | 0.76 s | 1.9× | |
| 30 NumPy 700 × 700 matrix multiplications | 1 copy | 0.34 s | 1× |
| 2 copies, 2 threads | 0.34 s | 2× | |
| 100 blocking waits of 0.1 s | 100 threads | 0.11 s | — |
asyncio.gather of 100 sleeps |
0.10 s | — |
What it means for AI systems
- CPU-bound Python code doesn't scale with threads. Tokenisation in pure Python, custom feature engineering loops and per-item post-processing need processes (
multiprocessing, PyTorchDataLoaderworkers), vectorisation, or native extensions (Rust tokenisers, NumPy). - Native libraries release the GIL. NumPy, PyTorch kernels and most inference runtimes do their heavy work in C/C++/CUDA, so a Python server can keep a GPU busy from a few threads; the Python glue becomes the bottleneck only when it does per-token or per-item work in Python.
- I/O-bound AI work fits async. An application calling a hosted model, a vector database and tools spends its time waiting;
asyncio(or threads) overlaps hundreds of such waits per process, which is why FastAPI-style async servers are the norm for LLM apps. - Python 3.13+ also ships an optional free-threaded build (PEP 703) without the GIL; it wasn't installed here, and library support is still maturing, so check before relying on it.
Try it yourself
- Rerun with
OMP_NUM_THREADSunset and explain how NumPy's own threads interact with yours. - Replace the pure-Python loop with a vectorised NumPy expression and measure the speed-up.
- Tokenise 100,000 sentences with a pure-Python tokeniser in threads, in processes, and with Hugging Face
tokenizers(Rust), and compare. - If a free-threaded CPython build (
python3.13t) is available to you, rerun the threads row.
Revision sheet: AI depth I
Key ideas
- Python at L3: object model, GIL and its release in native code, threads vs processes vs asyncio, memory and copying in NumPy/pandas, packaging and environments, typing.
- ML fundamentals at L4: generalisation, overfitting, validation design, leakage (target, temporal, preprocessing, duplicates), calibration, imbalanced metrics.
- LLM application architecture: prompts as code, context assembly, structured outputs, tools, caching, routing, guardrails, observability.
- RAG, measured: chunking, hybrid retrieval, reranking, permissions; retrieval and generation evaluated separately.
- Evaluation as statistics: golden sets, paired comparisons, confidence intervals, contamination, judge calibration.
Numbers to remember
- Lab: pure-Python ×2 in threads 1.47 s vs processes 0.76 s (vs 0.72 s for one).
- Lab: NumPy ×2 in threads: 2× throughput (GIL released).
- Lab: 100 × 0.1 s waits overlap to ~0.1 s with threads or asyncio.
Pitfalls
- Threading CPU-bound Python and expecting speed-ups.
- Preprocessing (scaling, feature selection) fitted on all data before splitting.
- Changing prompts or models without rerunning evals.
- Treating a small eval improvement as real without intervals.
- RAG without permission filtering.
Glossary
- GIL: CPython's Global Interpreter Lock.
- Free-threaded Python: a CPython build without the GIL (PEP 703).
- Leakage: information from evaluation data or the future reaching training.
- Context assembly: choosing and ordering what goes into a model call.
- Paired comparison: comparing systems on the same items.