Personalize this lesson
Adapt explanations and teaching visuals to your background and preferred voice.
Your key-rotation assistant says that K10234, a 42-day-old service-account key, is eligible for rotation under policy P-7. Tomorrow morning security leadership updates the policy: keys now rotate at 60 days instead of 30 days. The exact same key must now receive an ineligible verdict. Does that change require retraining a 70-billion-parameter large language model (LLM), or does it require changing the evidence supplied in the request?
The preceding application lesson separated an interactive form, a server decision boundary, and a persistent trace. Here we step behind that server boundary into the engine room: how weights are forged, how raw text morphs into structured tools, how models get evaluated and squeezed into memory, and how running systems distinguish parametric memory from live runtime context.
The age threshold itself belongs in deterministic code. An LLM can parse messy policy documents, explain the decision to engineers, or synthesize incident reports, but it shouldn't be the final unchecked authority executing privileged cryptographic rotations. The examples below make no external provider calls and execute no real key revocations.
A model-building loop alters parameters through pre-training, post-training alignment, and post-training compression. A production serving loop runs a frozen checkpoint alongside live context retrieval, authenticated gateways, schema validators, and observability pipelines. A deployed assistant isn't just the checkpoint. It's that checkpoint combined with retrieved evidence, serving infrastructure, safety rails, and evaluation feedback.

Five lifecycle stages, one key decision
When a developer queries the assistant, they see a single sentence: "Eligible under P-7: stale key is 42 days old (minimum 30 days)." That output represents the convergence of five distinct engineering stages, divided between offline parameter creation and online request handling:
| Stage | Input artifact | Output artifact | Do model weights change? |
|---|---|---|---|
| 1. Pre-training | Trillions of filtered web and code tokens | Base foundation checkpoint | Yes |
| 2. Post-training | Instructions, dialogues, preference pairs, reward unit tests | Instruction-following and reasoning checkpoint | Yes |
| 3. Evaluation | Standardized benchmarks, LLM judge rubrics, golden test suites | Promotion gate decision (Ship or Block) | No |
| 4. Compression | High-precision FP16 or BF16 weights | Quantized INT8 or INT4 checkpoint (AWQ, GPTQ) | Yes (quantized parameters) |
| 5. Deployment | Quantized checkpoint, KV-cache blocks, runtime prompts | Low-latency response stream via PagedAttention | No |
| Runtime context retrieval | Active policy repository and key registry records | Augmented prompt evidence | No |
| Gateway access control | Bearer tokens and required scopes | Authorized upstream provider route | No |
Different organizations adopt different recipes. Some teams train foundation models from scratch on massive clusters; others fine-tune open checkpoints with Low-Rank Adaptation (LoRA); many consume hosted APIs directly and focus on retrieval and gateway routing. Regardless of where your team joins the pipeline, separating changing the weights from changing the context gives you your first reliable debugging intuition.
The real key's private facts never need to touch training data. Model builders teach general reasoning and interface compliance; your application provides K10234's live facts at request time.
Stage 1: pre-training builds the base predictor
Pre-training transforms raw computing power into general linguistic and conceptual representations. The model reads sequences of tokens and learns to predict the next token across billions of documents. Parameters, or weights, are the learned floating-point numbers adjusted via backpropagation. A saved snapshot of these weights is a base checkpoint.
Before touching a single GPU cluster, builders curate their training data. Raw web scrapes from Common Crawl contain massive volumes of spam, machine-translated gibberish, search engine optimization noise, and toxic content. Filtering pipelines like CCNet and C4 apply strict heuristic and statistical screens to clean this corpus:[1][2]
- Language identification: FastText classifiers discard text outside target training languages.
- Quality filtering: Small n-gram language models trained on curated reference text (such as Wikipedia or peer-reviewed literature) score document perplexity. Scrapes with abnormal perplexity, excessive boilerplate, or skewed punctuation ratios get purged.
- Deduplication: Document-level and line-level MinHash Locality-Sensitive Hashing (LSH) strips duplicate pages, preventing the network from memorizing repeated web spam.
Next, raw character strings are converted into discrete vocabulary integers via Byte-Pair Encoding (BPE). Character-level models produce sequences that are too long for attention windows, while whole-word vocabularies explode and stumble on out-of-vocabulary terms. BPE solves this by starting with single bytes and iteratively merging the most frequent adjacent byte or subword pairs across the corpus until reaching a target vocabulary size, typically between 32,000 and 128,000 tokens.[3]
You can observe this merge dynamic with a minimal frequency counter:
1from collections import Counter
2
3# Frequencies of token tuples in a toy security corpus
4corpus_words = {
5 ("k", "e", "y"): 4,
6 ("s", "t", "a", "l", "e"): 3,
7 ("r", "o", "t", "a", "t", "i", "o", "n"): 2,
8}
9
10adjacent_pairs: Counter[tuple[str, str]] = Counter()
11for word_tokens, frequency in corpus_words.items():
12 for first, second in zip(word_tokens, word_tokens[1:]):
13 adjacent_pairs[(first, second)] += frequency
14
15most_frequent_pair, pair_count = adjacent_pairs.most_common(1)[0]
16print(f"Top adjacent pair: {most_frequent_pair} ({pair_count} observations)")
17print("BPE merges this pair into a single new subword token.")1Top adjacent pair: ('t', 'a') (5 observations)
2BPE merges this pair into a single new subword token.The pair ('k', 'e') occurs four times, making it the primary merge candidate. After the tokenizer adds 'ke' to its vocabulary, occurrences of k followed by e become a single token.
Once tokenized, the network updates its weights using cross-entropy loss: for observed target token with predicted probability , the step loss is . When the network assigns probability to the correct continuation, it incurs negligible penalty; assigning probability triggers a severe loss spike:
1from math import log
2
3def token_cross_entropy(probability_of_correct_token: float) -> float:
4 return -log(probability_of_correct_token)
5
6confident = token_cross_entropy(0.80)
7uncertain = token_cross_entropy(0.20)
8
9print(f"p=0.80 -> loss={confident:.3f}")
10print(f"p=0.20 -> loss={uncertain:.3f}")
11print("Lower loss rewards higher probability on the true observed continuation.")1p=0.80 -> loss=0.223
2p=0.20 -> loss=1.609
3Lower loss rewards higher probability on the true observed continuation.At frontier scale, selecting model dimensions and data volume requires principled compute budgeting. Kaplan et al. initially proposed power-law relationships governing parameters, data, and compute.[4] Hoffmann et al. challenged those allocations with the Chinchilla scaling experiments: for dense transformers under a compute budget, parameters and tokens should scale in roughly equal proportion ().[5]
Their analysis revealed that earlier models like Gopher (280B parameters on 300B tokens) were severely undertrained. Under the same total training FLOP budget, a 70B parameter model trained on 1.4T tokens substantially outperformed the 280B giant. For dense transformers, training floating-point operations follow the approximation , where is parameter count and is training token count:
1def estimate_dense_training_flops(parameter_count: float, token_count: float) -> float:
2 """Hoffmann et al. standard approximation: FLOPs ≈ 6ND."""
3 return 6 * parameter_count * token_count
4
5chinchilla_flops = estimate_dense_training_flops(70e9, 1.4e12)
6print(f"Chinchilla 70B x 1.4T tokens: {chinchilla_flops:.2e} FLOPs")
7assert abs(chinchilla_flops - 5.88e23) / 5.88e23 < 1e-121Chinchilla 70B x 1.4T tokens: 5.88e+23 FLOPsCompute optimality during pre-training isn't identical to economic optimality in production serving. The formula assumes you throw away the weights after training. In reality, a deployed checkpoint runs billions of inference queries over months.
Because inference cost scales directly with parameter count , running an 8B model is vastly cheaper than running a 70B model. The authors of Llama 3 deliberately trained their 8B model on 15 trillion tokens (over 10 times the Chinchilla-optimal token count), paying higher upfront pre-training FLOPs to produce an ultra-capable lightweight model that saves millions in serving hardware.[6]
A base model excels at text completion, yet it makes a clumsy software assistant. When prompted with stale key rotation request K10234:, a raw base model often appends another hypothetical ticket or rambles into internet prose rather than returning a structured decision. Teaching it how to behave requires post-training.
Stage 2: post-training aligns interface and behavior
Post-training adapts a raw probabilistic continuation engine into an aligned, instruction-following collaborator. This phase enforces clear communication protocols, safety boundaries, and structured data outputs.

The transition from pre-training to post-training introduces three fundamental data contracts:
Data contract 1: raw text to turn messages
Base pre-training treats all text as an uninterrupted stream of tokens. Post-training reorganizes data into conversational turns with explicit role identities: system, user, and assistant.
Chat templates format these records using special boundary tokens (such as <|im_start|>user\n...<|im_end|>\n<|im_start|>assistant\n). During Supervised Fine-Tuning (SFT), the loss is masked: gradients backpropagate exclusively through the assistant's output tokens, ignoring the user prompt tokens. The model learns how an assistant responds, not how a user writes prompts.
Here's an SFT demonstration teaching the assistant to emit a structured JSON verdict:
1import json
2
3sft_record = {
4 "messages": [
5 {
6 "role": "system",
7 "content": "You are a key security assistant. Output JSON containing eligible, policy_id, and evidence.",
8 },
9 {
10 "role": "user",
11 "content": "Check key K10234 (age 42 days, owner confirmed) against policy P-7: Keys at least 30 days old require rotation.",
12 },
13 {
14 "role": "assistant",
15 "content": json.dumps({
16 "eligible": True,
17 "policy_id": "P-7",
18 "evidence": "Keys at least 30 days old require rotation.",
19 }, sort_keys=True),
20 },
21 ]
22}
23
24print("Role structure:", [m["role"] for m in sft_record["messages"]])
25print("Target assistant payload:", sft_record["messages"][2]["content"])1Role structure: ['system', 'user', 'assistant']
2Target assistant payload: {"eligible": true, "evidence": "Keys at least 30 days old require rotation.", "policy_id": "P-7"}SFT demonstrations teach interface compliance, but datasets require rigorous schema auditing. Missing fields in training targets teach the model to omit required contractual data:
1required_fields = {"eligible", "policy_id", "evidence"}
2
3training_targets = [
4 {"eligible": True, "policy_id": "P-7", "evidence": "at least 30 days old"},
5 {"eligible": True, "evidence": "age matches rule"},
6]
7
8for idx, target in enumerate(training_targets, start=1):
9 missing = sorted(required_fields - target.keys())
10 verdict = "VALID" if not missing else f"REJECT (missing {missing})"
11 print(f"Target {idx}: {verdict}")1Target 1: VALID
2Target 2: REJECT (missing ['policy_id'])Data contract 2: turn messages to preference pairs
SFT makes the desired format likely, but it struggles when two candidates both produce valid JSON while differing in truthfulness or safety. For example, one candidate correctly states the key is eligible, while a second candidate states the key is eligible and fabricates an unperformed rotation event.
InstructGPT popularized Reinforcement Learning from Human Feedback (RLHF), training a separate reward model on ranked response pairs, then optimizing the generative model using Proximal Policy Optimization (PPO).[7]
Direct Preference Optimization (DPO) simplified this process. Rafailov et al. proved that an analytical substitution yields an exact closed-form solution to the Bradley-Terry preference objective without training a separate reward model or executing an unstable RL training loop.[8] Llama 3 combined SFT and DPO passes to align conversational tone and instruction tracking.[6]
A preference training pair compares two completions for the exact same prompt:
1preference_pair = {
2 "prompt": "Evaluate K10234 (age 42, owner confirmed) under P-7 (threshold 30 days). No rotation ran.",
3 "chosen": "Eligible. P-7 requires rotation at 30 days. No rotation job has been triggered.",
4 "rejected": "Eligible under P-7. A rotation worker has successfully rotated K10234.",
5 "rationale": "Chosen adheres to reality; rejected hallucinates an unauthorized mutation.",
6}
7
8print("Chosen response: ", preference_pair["chosen"])
9print("Rejected response:", preference_pair["rejected"])1Chosen response: Eligible. P-7 requires rotation at 30 days. No rotation job has been triggered.
2Rejected response: Eligible under P-7. A rotation worker has successfully rotated K10234.Data contract 3: verifiable rewards and test-time reasoning compute
Human preference labeling stumbles when verifying complex code, multi-step mathematical proofs, or strict policy rule engines. Human annotators make mistakes, and human evaluation doesn't scale to millions of synthetic rollouts.
Reinforcement Learning with Verifiable Rewards (RLVR) replaces human raters with deterministic software checkers. DeepSeek-R1 demonstrated that running large-scale RL with rule-based verification directly on base or lightly fine-tuned models incentivizes emergent chain-of-thought exploration, backtracking, and self-correction.[9]
Test-time reasoning compute also lets models trade inference tokens for higher answer accuracy. Instead of expanding parameters, the model expends compute generating intermediate scratchpad traces, verifying intermediate steps, or sampling parallel candidates scored by a verifier.[10]
The deterministic verifier below scores candidates against authoritative fixtures:
1def verify_candidate_decision(output: dict[str, object], key_age: int) -> int:
2 expected_eligible = key_age >= 30
3 passes_all_checks = (
4 output.get("eligible") is expected_eligible
5 and output.get("policy_id") == "P-7"
6 and output.get("rotation_started") is False
7 )
8 return int(passes_all_checks)
9
10candidate_honest = {"eligible": True, "policy_id": "P-7", "rotation_started": False}
11candidate_invented = {"eligible": True, "policy_id": "P-7", "rotation_started": True}
12
13print("Honest candidate reward: ", verify_candidate_decision(candidate_honest, key_age=42))
14print("Invented mutation reward: ", verify_candidate_decision(candidate_invented, key_age=42))1Honest candidate reward: 1
2Invented mutation reward: 0The verifier assigns 0 to any response claiming an unexecuted side effect, penalizing deceptive completions.
Stage 3: evaluation tests capabilities and boundaries
Deploying an LLM without comprehensive evaluation is like deploying financial software without tests. You need rigorous offline evaluation gates that grade capability, safety, and operational reliability before promotion.
Standardized benchmarks and contamination audits
Frontier models are graded on standard public benchmarks:
- Knowledge: Massive Multitask Language Understanding (MMLU) evaluates factual breadth across 57 academic subjects from elementary math to professional law.[11]
- Reasoning: GSM8K tests multi-step grade-school mathematical reasoning.[12]
These benchmarks suffer from a vulnerability: data contamination. When web crawl spiders ingest open GitHub repositories, research papers, or forum discussions, benchmark questions and answer keys slip into pre-training corpora. A model scoring 92% on MMLU might simply be reciting memorized test strings rather than reasoning through novel problems.
Engineers combat contamination through rigorous decontamination audits:[13]
- N-gram filtering: Checking 8-gram and 13-gram overlap between benchmark splits and training documents.
- Synthetic perturbation: Scrambling names, numbers, and prompt structure to test whether accuracy collapses when syntax shifts.
- Dynamic benchmarks: Adopting live evaluation suites like LiveBench that update questions monthly from contemporary news, code commits, and recent competitions.[14]
LLM-as-a-judge and its systematic biases
Human evaluation remains the gold standard for conversational quality, but it's slow, expensive, and non-reproducible across pull requests. Teams frequently employ powerful frontier models as automated judges (such as MT-Bench and Chatbot Arena setups).[15]
LLM judges display three documented biases that engineers must detect and calibrate:
- Positional bias: Judges consistently favor candidate A over candidate B simply because candidate A appears first in the prompt. Swapping candidate order and requiring pairwise consensus mitigates this drift.
- Verbosity bias: Judges frequently rate wordy, verbose explanations as higher quality than concise, accurate answers.
- Self-enhancement bias: Models tend to assign higher scores to responses generated by their own model family.
Golden test suites and deterministic release gating
For domain assistants like our key rotator, open benchmarks aren't enough. You need private, version-pinned golden datasets that test explicit business constraints. The evaluator below grades candidate responses against golden fixtures:
1test_cases = [
2 # (key_id, age, confirmed, decision, policy, rotation_started, should_pass)
3 ("K10234", 42, True, "eligible", "P-7", False, True),
4 ("K10235", 15, True, "not_eligible", "P-7", False, True),
5 ("K10236", 50, True, "eligible", "P-7", True, False), # Invented rotation
6 ("K10237", 10, True, "eligible", "P-7", False, False), # Wrong verdict
7 ("K10238", 45, True, "eligible", "P-9", False, False), # Wrong policy ID
8]
9
10passes = 0
11for key_id, age, confirmed, decision, policy, started, should_pass in test_cases:
12 expected_decision = "eligible" if confirmed and age >= 30 else "not_eligible"
13 candidate_pass = (
14 decision == expected_decision
15 and policy == "P-7"
16 and started is False
17 )
18 agreed = (candidate_pass == should_pass)
19 passes += int(agreed)
20 print(f"Key {key_id}: evaluated_pass={candidate_pass} matches_expected={agreed}")
21
22print(f"Harness audit score: {passes}/{len(test_cases)}")1Key K10234: evaluated_pass=True matches_expected=True
2Key K10235: evaluated_pass=True matches_expected=True
3Key K10236: evaluated_pass=False matches_expected=True
4Key K10237: evaluated_pass=False matches_expected=True
5Key K10238: evaluated_pass=False matches_expected=True
6Harness audit score: 5/5Before any candidate reaches production traffic, it must pass a deterministic release gate checking functional accuracy, safety violations, and latency budgets:
1candidate_report = {
2 "policy_cases_passed": 20,
3 "policy_cases_total": 20,
4 "unauthorized_side_effect_claims": 0,
5 "p95_ttft_ms": 780,
6}
7
8def evaluate_release_gate(metrics: dict[str, int]) -> tuple[str, list[str]]:
9 blockers = []
10 if metrics["policy_cases_passed"] != metrics["policy_cases_total"]:
11 blockers.append("Policy correctness regression")
12 if metrics["unauthorized_side_effect_claims"] > 0:
13 blockers.append("Unauthorized side-effect claim detected")
14 if metrics["p95_ttft_ms"] > 1000:
15 blockers.append("P95 TTFT budget breached")
16
17 verdict = "BLOCK" if blockers else "PROMOTE"
18 return verdict, blockers
19
20verdict, blockers = evaluate_release_gate(candidate_report)
21print(f"Release gate verdict: {verdict}")
22print("Blockers identified: ", blockers if blockers else "None (all checks pass)")1Release gate verdict: PROMOTE
2Blockers identified: None (all checks pass)Stage 4: compression shrinks weights for serving
A trained 70-billion-parameter checkpoint stored in standard 16-bit brain floating point (bfloat16 or float16) consumes 2 bytes per parameter. Storing weights alone requires:
Fitting that model requires two 80 GB GPUs (such as NVIDIA A100 or H100) before allocating a single megabyte for runtime buffers or the key-value (KV) cache. On top of memory capacity, autoregressive text generation is memory-bandwidth bound: for every generated token, the GPU must transfer all active parameter weights from High Bandwidth Memory (HBM) into on-chip cache registers. Shrinking the parameter footprint directly boosts generation throughput.
Model compression tackles this bottleneck through Post-Training Quantization (PTQ), converting 16-bit floating-point weights into 8-bit (INT8) or 4-bit (INT4) integers without requiring expensive full-model retraining.
The calculation below estimates weight footprints across precisions:
1def calculate_weight_gib(param_count_billions: float, bytes_per_param: float) -> float:
2 return (param_count_billions * 1e9 * bytes_per_param) / (1024 ** 3)
3
4bf16_gib = calculate_weight_gib(70, 2.0)
5int8_gib = calculate_weight_gib(70, 1.0)
6int4_gib = calculate_weight_gib(70, 0.5)
7
8print(f"70B in BF16 (16-bit): {bf16_gib:.1f} GiB")
9print(f"70B in INT8 (8-bit): {int8_gib:.1f} GiB")
10print(f"70B in INT4 (4-bit): {int4_gib:.1f} GiB")170B in BF16 (16-bit): 130.4 GiB
270B in INT8 (8-bit): 65.2 GiB
370B in INT4 (4-bit): 32.6 GiBINT4 quantization shrinks the 70B model down to 32.6 GiB, enabling it to fit comfortably inside a single 48 GB workstation GPU or split across inexpensive consumer cards.
Symmetric uniform quantization maps a continuous floating-point tensor into an integer grid using a scale factor :
1weights = [-0.84, -0.22, 0.05, 0.41, 0.96]
2
3max_abs = max(abs(w) for w in weights)
4scale = max_abs / 127.0
5
6quantized_int8 = [max(-128, min(127, round(w / scale))) for w in weights]
7reconstructed = [q * scale for q in quantized_int8]
8max_reconstruction_error = max(abs(w - r) for w, r in zip(weights, reconstructed))
9
10print("Original FP16 weights: ", weights)
11print("Quantized INT8 grid: ", quantized_int8)
12print("Reconstructed values: ", [round(r, 4) for r in reconstructed])
13print(f"Max reconstruction error: {max_reconstruction_error:.4f}")1Original FP16 weights: [-0.84, -0.22, 0.05, 0.41, 0.96]
2Quantized INT8 grid: [-111, -29, 7, 54, 127]
3Reconstructed values: [-0.8391, -0.2192, 0.0529, 0.4082, 0.96]
4Max reconstruction error: 0.0029The outlier challenge: AWQ and GPTQ
Naive uniform quantization stumbles when pushed to 4 bits. In transformer architectures, roughly of hidden-layer activation channels exhibit extreme numerical spikes (outliers). Truncating these spikes introduces severe quantization noise that destroys model coherence.
Two modern PTQ methods overcome this hurdle:
- AWQ (Activation-aware Weight Quantization): Lin et al. observed that weights aren't equally critical; weights corresponding to large activation magnitudes protect model performance.[16] Rather than quantizing all weights identically, AWQ profiles activations on a small calibration set and scales up the salient weight channels before quantization, minimizing output feature distortion.
- GPTQ: Frantar et al. framed quantization as a layer-wise constrained optimization problem using second-order Taylor expansion.[17] GPTQ uses the inverse Hessian matrix to update the remaining unquantized weights in each row as each weight gets rounded, compensating for rounding errors in real time.
With weights safely compressed, the model is prepared for runtime deployment.
Stage 5: deployment optimizes latency and memory
Serving an LLM in production requires satisfying four competing engineering constraints:
- Time to First Token (TTFT): The delay between user request arrival and generation of the first token (governed by prompt processing throughput).
- Inter-Token Latency (ITL): The generation delay between subsequent output tokens (governed by memory bandwidth).
- Throughput: Total output tokens generated per second across all concurrent streams.
- VRAM footprint: Memory allocated across weights, runtime activations, and the KV cache.
Three serving innovations power modern inference engines like vLLM and SGLang:
PagedAttention manages KV-cache memory
During autoregressive generation, the attention mechanism caches key and value projection tensors for all previous tokens in the context sequence (the KV cache) to avoid recomputing them at every step. As context lengths stretch to 32,000 or 128,000 tokens, the KV cache outgrows the model weights.
Traditional inference engines allocated contiguous virtual memory blocks sized to the maximum possible sequence length. Because sequence lengths are unpredictable, up to 60% to 80% of GPU memory was squandered on unused contiguous buffers (internal fragmentation) or scattered between allocations (external fragmentation).
PagedAttention resolves this waste by borrowing virtual memory paging from operating systems.[18] It partitions the KV cache into fixed-size physical memory blocks (typically holding 16 or 32 tokens). A page table maps logical token positions to non-contiguous physical blocks on GPU VRAM, virtually eliminating memory fragmentation and allowing systems to support 2x to 4x higher batch concurrency on identical hardware.
Continuous batching prevents pipeline stalls
Traditional machine learning inference uses static batching: requests group together and execute simultaneously. In autoregressive LLM serving, static batching is wasteful. If Request 1 generates 15 tokens while Request 2 generates 600 tokens, Request 1's GPU slot sits idle for 585 iterations, burning compute on padding tokens.
Orca introduced continuous batching (or iteration-level scheduling).[19] Rather than scheduling at the batch level, the engine schedules at the token-generation step. As soon as Request 1 emits an end-of-sequence token, its KV blocks are freed and a newly arrived Request 3 joins the batch on the very next iteration.
Speculative decoding beats the memory bandwidth wall
Generating one token at a time leaves GPU compute cores underutilized because loading 70 billion parameters from HBM takes significantly longer than performing the arithmetic.
Speculative decoding pairs a small, lightning-fast draft model (such as an 8B model) with a massive target model (such as a 70B model).[20] The draft model quickly proposes candidate tokens sequentially. The large target model then evaluates all tokens in a single parallel forward pass. If the target model accepts 4 of the 5 tokens, the system generates 4 tokens in the time of a single forward pass, providing a 2x to 3x speedup with zero degradation in mathematical output distribution.
The runtime gateway: authentication, authorization, and rate limits
At the network edge, an API gateway protects upstream inference pools. The gateway enforces caller identity, verifies scoped permissions, and handles provider limits. Parameterized SQL queries prevent injection attacks:
1import sqlite3
2
3NOW = 100
4db = sqlite3.connect(":memory:")
5db.execute("CREATE TABLE client_keys (token TEXT PRIMARY KEY, scope TEXT, expires_at INTEGER)")
6db.executemany(
7 "INSERT INTO client_keys VALUES (?, ?, ?)",
8 [
9 ("client-prod", "rotation:read", 130),
10 ("client-staging", "staging:rotation", 130),
11 ("client-expired", "rotation:read", 90),
12 ],
13)
14
15provider_pools = {
16 "rotation:read": ["prod-primary", "prod-backup"],
17 "staging:rotation": ["staging-primary"],
18}
19provider_status = {
20 "prod-primary": ("credential", 429),
21 "prod-backup": ("credential", 200),
22 "staging-primary": ("credential", 200),
23}
24circuits: dict[str, str] = {}
25
26def authenticate(token: str, required_scope: str) -> str | None:
27 # Parameterized query keeps untrusted bearer tokens out of SQL syntax
28 row = db.execute("SELECT scope, expires_at FROM client_keys WHERE token = ?", (token,)).fetchone()
29 if row is None:
30 return None
31 scope, expires_at = row
32 return scope if scope == required_scope and expires_at > NOW else None
33
34def route(token: str, required_scope: str) -> str:
35 scope = authenticate(token, required_scope)
36 if scope is None:
37 return "unauthorized"
38
39 for credential_id in provider_pools[scope]:
40 if circuits.get(credential_id) == "open":
41 continue
42 limit_scope, status = provider_status[credential_id]
43 if status == 429 and limit_scope != "credential":
44 return "provider_rate_limited"
45 if status == 429:
46 circuits[credential_id] = "open"
47 continue
48 if 200 <= status < 300:
49 return f"ok:{credential_id}"
50 return f"provider_error:{status}"
51 return "provider_pool_exhausted"
52
53crafted_token = "missing' OR 1=1 --"
54print("Crafted SQL token: ", route(crafted_token, "rotation:read"))
55print("Expired token: ", route("client-expired", "rotation:read"))
56print("Wrong scope token: ", route("client-staging", "rotation:read"))
57print("Production routing: ", route("client-prod", "rotation:read"))
58print("Primary circuit: ", circuits.get("prod-primary"))
59db.close()1Crafted SQL token: unauthorized
2Expired token: unauthorized
3Wrong scope token: unauthorized
4Production routing: ok:prod-backup
5Primary circuit: openThe gateway trips a circuit breaker on the primary credential and fails over to an authorized backup credential without exposing secrets or crossing environment boundaries.
The diagnostic failure router: attributing production bugs
When an assistant misbehaves in production, jumping immediately to "we must retrain the model" burns budget and introduces regressions. A structured engineer reads the observability trace and maps the symptom back to its originating lifecycle stage.

Here is the operational triage playbook:
- Symptom: Stale threshold decision
- Example: The assistant evaluates
K10234against the obsolete 30-day threshold instead of the 60-day threshold. - Root cause: Retrieval index holds stale embeddings or outdated document chunks.
- Remedy: Refresh document indexing in the vector store; zero model weights change.
- Example: The assistant evaluates
- Symptom: Malformed JSON or broken tool-call grammar
- Example: The response emits unescaped quotes or omits
policy_id. - Root cause: Stage 2 SFT instruction tuning dataset lacks diverse structural demonstrations, or serving lacks grammar-constrained decoding.
- Remedy: Audit SFT prompt templates and enforce JSON schema masks during decoding.
- Example: The response emits unescaped quotes or omits
- Symptom: Hallucinated side-effect claim
- Example: Output claims "Key K10234 was rotated and deleted," but no API rotation call occurred.
- Root cause: Stage 2 or Stage 3 alignment data rewarded plausible-sounding completions without verifying backend execution state.
- Remedy: Add negative preference pairs penalizing fabricated actions, and enforce verifiable reward checks against execution fixtures.
- Symptom: Repetitive loops or numeric precision degradation
- Example: The assistant repeats phrases or scrambles numeric dates after quantization.
- Root cause: Stage 4 compression clipping activation outliers during INT4 quantization.
- Remedy: Switch from uniform PTQ to AWQ, protect salient activation channels, or shrink quantization group size from 128 to 64.
- Symptom: TTFT latency spike or out-of-memory crash under load
- Example: P95 latency jumps from 600 ms to 8 seconds during peak traffic hours.
- Root cause: Stage 5 deployment serving suffers from static batching stalls or KV-cache fragmentation.
- Remedy: Increase PagedAttention block pool capacity, tune continuous batching parameters, or deploy speculative decoding.
The script below classifies failures from execution traces:
1def route_failure_trace(trace_log: dict[str, str]) -> str:
2 symptom = trace_log["symptom"].lower()
3 if "stale policy" in symptom:
4 return "Context Retrieval Store: update document index (0 weight updates)"
5 if "missing field" in symptom or "malformed json" in symptom:
6 return "Stage 2 SFT: audit demonstration schemas and chat templates"
7 if "invented rotation" in symptom or "hallucinated action" in symptom:
8 return "Stage 3 Alignment: add negative DPO pairs and verifiable reward fixtures"
9 if "repetitive loop" in symptom or "numeric degradation" in symptom:
10 return "Stage 4 Compression: protect AWQ outlier channels and reduce group size"
11 if "slow first token" in symptom or "kv oom" in symptom:
12 return "Stage 5 Deployment: tune PagedAttention blocks and continuous batching"
13 return "Triage manually with full trace telemetry"
14
15traces = [
16 {"symptom": "K10234 used stale policy threshold 30 days"},
17 {"symptom": "Response missing field policy_id in JSON payload"},
18 {"symptom": "Response claimed invented rotation execution without tool trigger"},
19 {"symptom": "Generated text exhibited repetitive loop after 4-bit conversion"},
20 {"symptom": "Slow first token latency spike during traffic surge"},
21]
22
23for t in traces:
24 owner = route_failure_trace(t)
25 print(f"[{t['symptom'][:32]}...] -> {owner}")1[K10234 used stale policy thresho...] -> Context Retrieval Store: update document index (0 weight updates)
2[Response missing field policy_id...] -> Stage 2 SFT: audit demonstration schemas and chat templates
3[Response claimed invented rotati...] -> Stage 3 Alignment: add negative DPO pairs and verifiable reward fixtures
4[Generated text exhibited repetit...] -> Stage 4 Compression: protect AWQ outlier channels and reduce group size
5[Slow first token latency spike d...] -> Stage 5 Deployment: tune PagedAttention blocks and continuous batchingTracing bugs to their actual origin prevents wasteful retraining cycles. When policy changes tomorrow, your checkpoint stays completely untouched while your retrieval index updates in seconds:
1incident_trace = {
2 "key_id": "K10234",
3 "checkpoint": "security-assistant-70b-v2-awq",
4 "retrieved_policy_version": "P-7-v1",
5 "active_policy_version": "P-7-v2",
6 "failure": "stale policy threshold",
7}
8
9def resolve_incident(trace: dict[str, str]) -> tuple[str, str]:
10 target_checkpoint = trace["checkpoint"]
11 if trace["retrieved_policy_version"] != trace["active_policy_version"]:
12 action = f"Hot-reload vector store to version {trace['active_policy_version']}"
13 else:
14 action = "Audit model alignment and prompt template"
15 return target_checkpoint, action
16
17checkpoint, remediation = resolve_incident(incident_trace)
18print("Model checkpoint status: UNCHANGED ->", checkpoint)
19print("Remediation deployed: ", remediation)1Model checkpoint status: UNCHANGED -> security-assistant-70b-v2-awq
2Remediation deployed: Hot-reload vector store to version P-7-v2Review questions
Test your operational reasoning against these five boundary scenarios:
1. Does changing the policy from 30 days to 60 days require retraining?
No. Training embeds language syntax, schema habits, and reasoning protocols into parameters. The policy threshold is dynamic domain knowledge. Storing that threshold in a vector database or operational config and injecting it into the prompt at runtime lets the frozen checkpoint adapt instantly.
2. Can a rule-based verifier catch a text contradiction if structured fields pass?
Only if the verifier evaluates both channels. If a candidate returns {"rotation_started": false} in JSON while appending "Rotation completed successfully!" in user text, a verifier that checks only JSON keys will reward the deception. Robust verifiers cross-check text claims against system execution logs or assemble user-facing status messages strictly from verified structured fields outside the model.
3. How does AWQ protect 4-bit models from perplexity collapse?
In transformer layers, roughly of activation channels have extreme magnitudes. Uniform quantization maps the entire integer grid across those extreme outliers, crushing the precision of the remaining of weights. AWQ analyzes activation magnitudes, identifies salient weight channels, and applies protective scaling before rounding to preserve representation fidelity.
4. Why does PagedAttention reduce VRAM requirements under concurrent traffic?
Standard inference pre-allocates contiguous memory buffers sized for maximum possible context lengths, wasting to of GPU memory on unused padding and fragmentation. PagedAttention divides the KV cache into fixed-size virtual memory blocks allocated on demand, allowing models to serve several times more concurrent requests on the same GPU.
5. Why do modern teams overtrain small models past Chinchilla optimality?
Chinchilla optimality minimizes pre-training FLOPs for a given parameter count. However, inference costs recur for every generated token over the lifetime of the model. By overtraining an 8B model on 15 trillion tokens (over 10 times Chinchilla optimal), builders trade higher one-time training compute for dramatically lower serving hardware costs across billions of production queries.