LLM Pretraining, Alignment, Evaluation, and Serving
Medium · Machine Learning · Machine Learning Engineer · Onsite
Prompt
Walk through the end-to-end engineering life cycle of a transformer-based large language model, from training a base checkpoint on raw text to serving low-latency traffic in production:
- Pretraining and adaptation: How is a decoder-only transformer pretrained at scale, and how do teams adapt pretrained weights via downstream finetuning?
- Alignment and factuality: How does supervised instruction tuning differ from preference-optimization stages such as RLHF, and which techniques reduce model hallucinations?
- Offline grading and live observability: How do you combine intrinsic metrics (such as perplexity), automated task benchmarks, and human or judge-based studies prior to launch, and what do you monitor once real users interact with the model?
- Serving efficiency: Which inference-time optimizations—such as KV-cache management and weight or activation quantization—keep latency and GPU memory within production budgets?
Scope & Expectations
- Explain the core training objectives, data curation requirements, and memory/compute scaling across pretraining, supervised finetuning, and preference alignment.
- Connect the root causes of hallucination to concrete mitigations spanning retrieval grounding, deterministic tool invocation, and calibrated abstention.
- Combine multi-tier offline evaluation with statistically grounded production monitoring across latency, output quality, and safety.
- Contrast compute-bound prompt prefill with memory-bandwidth-bound token decoding when selecting serving optimizations.
Step-by-step walkthrough
Map the end-to-end LLM life cycle
A clear, senior-level answer walks through the full life cycle of a large language model in order and anchors each stage with one concrete formula or back-of-the-envelope number:
raw text + code ──► [1. Pretraining] ──► base model ──► [2. SFT (instruction tuning)] │ ┌── feedback loop (hard failures -> new eval + training data) ◄─┼── [3. RLHF / DPO] │ ▼ [5. Production monitoring + serving (KV cache, quant)] ◄── [4. Offline evaluation]Define token up front: a word or common subword piece (averaging roughly 3–4 English characters) from a fixed vocabulary of ~32,000–128,000 entries that serves as the model's basic unit of reading and writing. - Pretraining teaches grammar, reasoning patterns, and world knowledge by predicting the next token across trillions of tokens. - Supervised finetuning (SFT) teaches the base model to act like an assistant by imitating curated
(prompt, ideal response)pairs. - Preference tuning (RLHF or DPO) aligns tone, helpfulness, and safety using human "Response A beats Response B" comparisons. - Offline evaluation, inference optimization, and production monitoring verify accuracy, serve tokens within memory-bandwidth limits, and catch real-world drift.Pretraining: causal next-token prediction, memory, and compute
Architecture. Modern LLMs use a decoder-only transformer: input tokens become dense vectors (embeddings) and pass through
Lstacked blocks—each combining causal self-attention and a feed-forward network with residual connections and normalization—ending in a linear layer that outputs one raw score (logit) per vocabulary token. A causal mask blocks positiontfrom looking at future positions> t, so a single sequence ofTtokens trainsTnext-token predictions simultaneously in one forward pass.Data pipeline. Web crawls, code, books, and papers are tokenized with a subword algorithm like Byte-Pair Encoding (BPE) (iteratively merging frequent character pairs into single tokens). Data quality dominates model quality: teams run exact and near-duplicate removal (such as MinHash), quality classifiers, personally identifiable information (PII) scrubbing, domain mixing weights, and benchmark decontamination so test questions do not leak into pretraining.
Loss function. At every position
t, the model minimizes cross-entropy loss—the negative natural log of the probability assigned to the true next token,-ln p(x_t | x_<t). If a 4-token toy model assigns equal probability0.25to all 4 tokens, its loss is-ln(0.25) = ln(4) = 1.386nats:import numpy as np def next_token_loss(logits: np.ndarray, targets: np.ndarray) -> float: """Compute mean cross-entropy loss across T positions for vocabulary size V.""" # Subtract row-wise max before exp() (the log-sum-exp trick) to prevent float overflow. shifted = logits - logits.max(axis=1, keepdims=True) log_probs = shifted - np.log(np.exp(shifted).sum(axis=1, keepdims=True)) # Pick the log-probability of the true next token at each position 0..T-1. true_token_log_probs = log_probs[np.arange(len(targets)), targets] return float(-true_token_log_probs.mean()) print(round(next_token_loss(np.zeros((3, 4)), np.array([0, 1, 2])), 3)) # 1.386Memory & compute sizing. Pretraining uses AdamW with learning-rate warmup + cosine decay, gradient clipping, and
bf16mixed precision across GPUs via data, tensor, and pipeline parallelism plus sharded optimizer state (ZeRO or FSDP). Why shard? Mixed-precision AdamW stores ~16 bytes per parameter:2 B(bf16weights) +2 B(bf16gradients) +4 B(fp32master weights) +8 B(twofp32Adam momentum/variance states). For a7B-parameter model,7 × 10^9 × 16 B = 112 GBbefore activations—exceeding a single 80 GB GPU! Compute costs roughly6 × N × DFLOPs (~2NDforward +~4NDbackward) forNparameters onDtokens: training7Bparameters on2 trilliontokens takes6 × 7×10^9 × 2×10^12 = 8.4 × 10^22FLOPs. While the Chinchilla study found ~20tokens per parameter (140Btokens for7B) is compute-optimal for training alone, models like Llama 2 7B train on2Ttokens because a smaller, over-trained model is far cheaper to serve millions of times in production.Finetuning: prompt masking and parameter-efficient LoRA
Finetuning starts from pretrained weights and adapts behavior or domain fluency: - Continued pretraining trains on unlabeled domain corpora (medical notes, fleet telematics logs, proprietary code) using the same next-token loss across every token. - Supervised finetuning (SFT) trains on
(prompt, response)pairs, masking prompt tokens out of the loss so gradients come solely from response tokens—teaching the model how to answer questions rather than how to mimic user prompts.Full finetuning updates 100% of weights (requiring the full ~16 bytes/parameter of training state and storing a separate multi-gigabyte checkpoint per task). LoRA (Low-Rank Adaptation) freezes each pretrained weight matrix
W(d × k) and trains only a thin bottleneck updateΔW = B · A, whereBisd × randAisr × kwith small rankr(such as8or16). Check the parameter savings on a single4096 × 4096projection atr = 8:Full weight matrix W: 4096 × 4096 = 16,777,216 trainable parameters LoRA adapters (B and A): (4096 × 8) + (8 × 4096) = 65,536 trainable parameters (0.39%)Only
BandAneed gradients and Adam states, and one frozen base model in GPU memory can hot-swap dozens of tiny LoRA adapters! QLoRA compresses the frozen base weights further to 4 bits (finetuning a 65B model on one 48 GB GPU in the original QLoRA paper). Use a small learning rate and mix in 5–10% general instruction data to avoid catastrophic forgetting (overwriting broad reasoning skills while adapting to a narrow task). Above all: finetune for style, schema, and skill; use Retrieval-Augmented Generation (RAG) for volatile facts.Compare instruction tuning (SFT) and RLHF / DPO
Instruction tuning (SFT) trains the model to imitate human-written demonstrations. It quickly establishes assistant formatting and instruction following, but it has two blind spots: writing gold-standard human answers is slow and expensive, and pure imitation gives zero negative signal—every token not written looks equally wrong, and the model copies demonstrators' subtle mistakes.
RLHF (Reinforcement Learning from Human Feedback) learns from pairwise comparisons, because humans judge which of two drafts is better far more reliably than they write an ideal answer from scratch: 1. Sample multiple completions per prompt from the SFT model and have raters pick winner
wover loserl. 2. Train a scalar reward modelr(x, y)using the Bradley–Terry preference model, which turns the score gapr_w - r_linto win probability via the logistic sigmoidσ(z) = 1 / (1 + exp(-z))and minimizes-ln σ(r_w - r_l). Ifr_w = 2.0andr_l = 1.0, win probability isσ(1.0) = 0.731and loss is-ln(0.731) = 0.313:import math def bradley_terry_loss(reward_winner: float, reward_loser: float): """Return (P(winner > loser), negative log-likelihood loss) for one preference pair.""" gap = reward_winner - reward_loser prob_win = 1.0 / (1.0 + math.exp(-gap)) loss = -math.log(prob_win) return prob_win, loss prob, loss = bradley_terry_loss(2.0, 1.0) print(round(prob, 3), round(loss, 3)) # 0.731 0.313- Optimize the LLM policy
πwith PPO (Proximal Policy Optimization) to maximizer(x, y) - β · KL(π || π_SFT). Here KL divergence measures how far the new policy drifts from the SFT model; without thatβleash, the policy exploits blind spots in the reward model (reward hacking, such as outputting excessively long, sycophantic bullet lists that trick the reward model into high scores).
DPO (Direct Preference Optimization) algebraically rewrites that RL objective so you train directly on
(prompt, winner, loser)triples using the policy's own log-probability ratios—no separate reward model and no online PPO instability, at the cost of not exploring fresh model rollouts unless run iteratively.Dimension Instruction tuning (SFT) RLHF / DPO preference tuning -------------- ----------------------------------- --------------------------------------------- Training data (prompt, single gold demonstration) (prompt, preferred answer w, rejected answer l) Learning signal Maximize likelihood of gold tokens Push w up and l down relative to SFT policy Best at Output format, following structure Helpfulness, nuance, safety refusals, tone Compute & ops Simple, stable supervised loss RLHF: 4 models in RAM + RL tuning; DPO: simple Failure modes Mimics annotator errors; hedges less Reward hacking, verbosity bias, lower entropyIn practice SFT and RLHF/DPO are sequential stages, not competitors: SFT builds a capable assistant first, and preference tuning sharpens it (in the public InstructGPT study, raters preferred a 1.3B SFT+RLHF model over the 175B raw GPT-3 base model).
- Optimize the LLM policy
Reduce hallucinations with grounding, tools, and calibrated abstention
A hallucination is fluent, confident text that contradicts real-world facts or the provided context. Why do LLMs hallucinate? Next-token pretraining rewards plausible-sounding continuations rather than verified truth, rare long-tail facts are compressed lossily in weights, and standard
1 / 0grading actively punishes honesty! Check the expected-score arithmetic when a model is only30%sure of an answer: - Standard grading (+1right,0wrong,0"I don't know"): Guessing scores0.30(+1) + 0.70(0) = +0.30vs0for abstaining—guessing always wins! - Penalty-aware grading (+1right,-1wrong,0"I don't know"): Guessing scores0.30(+1) + 0.70(-1) = -0.40 < 0, so abstaining wins whenever confidence is below50%(2p - 1 < 0).Combine six complementary defenses across data, serving, and UI: 1. RAG (Retrieval-Augmented Generation) with citations: Fetch authoritative passages at query time, instruct the model to answer strictly from those passages with inline citations (or reply "not found in the provided sources"), and verify groundedness with an NLI (Natural Language Inference) classifier checking whether each sentence is entailed by its cited chunk. 2. Deterministic tool calls: Route arithmetic, live metrics, and database lookups to Python, SQL, or search APIs instead of memory recall. 3. Abstention-aware SFT & preference tuning: Include unanswerable questions answered with "I don't have enough information" in SFT, and penalize confident falsehoods more heavily than abstentions in RLHF/DPO. 4. Low-temperature decoding & self-consistency: Use low temperature (
0–0.2) on factual tasks to suppress random tail tokens (note: temperature0stops coin-flip errors, not missing knowledge), or samplekanswers and treat disagreement across samples as an uncertainty trigger to abstain or retrieve more context. 5. Post-generation verification: Run a lightweight verifier pass against structured schemas or business rules before displaying the output.Evaluate offline and monitor continuously in production
No single metric captures LLM quality, so stack three offline evaluation tiers:
- Perplexity (
PPL) isexp(mean negative log-likelihood per token), measuring the effective branching factor of the model's uncertainty. If 4 target tokens receive probabilities[0.5, 0.25, 0.1, 0.8], their losses-ln(p)are[0.693, 1.386, 2.303, 0.223], averaging1.151, soPPL = exp(1.151) = 3.16(as uncertain as rolling a 3.16-sided die per token). Perplexity smoothly tracks pretraining progress, but you can never compare token perplexity across different tokenizers (a finer tokenizer splits words into more pieces, changing the denominator; compare bits-per-byte instead). - Automatic task benchmarks grade verifiable outputs: exact match / accuracy on Q&A, F1 on extraction, and
pass@kon code generation (the probability that at least 1 ofksampled programs passes unit tests, estimated unbiasedly fromnsamples withcpassing via1 - C(n - c, k) / C(n, k)):
import math from math import comb def perplexity(token_probs) -> float: """Compute perplexity = exp(mean(-ln p)) over predicted token probabilities.""" mean_nll = sum(-math.log(p) for p in token_probs) / len(token_probs) return math.exp(mean_nll) def pass_at_k(n: int, c: int, k: int) -> float: """Unbiased estimator of pass@k given n generated samples with c passing tests.""" if n - c < k: return 1.0 return 1.0 - comb(n - c, k) / comb(n, k) print(round(perplexity([0.5, 0.25, 0.1, 0.8]), 2)) # 3.16 print(round(pass_at_k(10, 3, 1), 3), round(pass_at_k(10, 3, 5), 3)) # 0.3 0.917Always attach confidence intervals (
72%accuracy on1,000items has95% CI ≈ ±1.96 × sqrt(0.72 × 0.28 / 1000) = ±2.8points), use paired McNemar tests when comparing two models on the same prompts, and check n-gram overlap for benchmark contamination. 3. Human & calibrated LLM-as-judge evaluation grades open-ended quality via blind, randomized pairwise comparisons, reporting win rate alongside inter-rater agreement (such as Cohen's kappa, which measures rater agreement above chance). When scaling with an LLM judge, swap(A, B)vs(B, A)order to cancel position bias, calibrate against a human-graded subset, and evaluate both red-team attack refusal and false-positive over-refusal on benign prompts.Production monitoring watches four live layers because prompts, retrieval indexes, and user behavior drift silently: - Operational: TTFT (time to first token), TPOT (time per output token), p50/p95/p99 end-to-end latency, GPU memory/utilization, timeout rate, and cost per query. - Quality & RAG health: Thumbs-up/down, user retries/edits, human-escalation rate, retrieval hit rate, and daily human/LLM-judge grading on a random traffic sample. Set alert thresholds statistically: at
92%acceptable on200graded chats/day, the 95% noise band is±1.96 × sqrt(0.92 × 0.08 / 200) = ±3.8points, so90%is normal noise while87%triggers investigation. - Safety & input drift: Guardrail block rates, PII leakage detectors, and embedding cluster drift on incoming user queries. Version prompts, indexes, and weights together, gating every release through golden regressions → canary → A/B test.- Perplexity (
Speed up serving with KV caching, quantization, and continuous batching
LLM inference splits into two very different hardware regimes: - Prefill processes all prompt tokens in parallel using dense matrix-matrix multiplies (compute-bound). - Decode generates output one token at a time; at small batch sizes, every single new token must stream all model weights from GPU HBM memory into compute cores (memory-bandwidth-bound). For a
7Bmodel infp16(7×10^9 × 2 B = 14 GB) on a GPU with2 TB/sbandwidth, reading weights alone takes at least14 GB / 2000 GB/s = 7 ms/token—capping single-stream speed near~140 tokens/s.Without KV cache: token t recomputes Keys & Values for tokens 1..t --> O(T^2) total work With KV cache: save past Keys & Values in GPU RAM; compute token t only --> O(T) total work- KV caching & GQA: Caching every layer's past Key and Value vectors avoids recomputing the prompt prefix at every decode step, trading compute for GPU RAM:
bytes/token = 2 (K and V) × layers × kv_heads × head_dim × bytes_per_elem. For a standard7Bmodel (32layers,32KV heads,head_dim = 128,fp16 = 2 B), one token takes2 × 32 × 32 × 128 × 2 = 524,288 B = 0.5 MiB—so a4096-token context takes2.0 GiB, and a batch of16sequences consumes32 GiB(more than twice the14 GBweights!). Shrink KV memory via Grouped-Query Attention (GQA) (sharing8KV heads across32query heads cuts KV size4×to0.5 GiB), PagedAttention (allocating KV blocks in fixed pages like OS virtual memory in vLLM to eliminate fragmentation), shared system-prompt prefix caching, andfp8/int8KV quantization:
def kv_cache_gib( layers: int, kv_heads: int, head_dim: int, seq_len: int, batch_size: int, bytes_per_val: int = 2, ) -> float: """Return total KV-cache memory in GiB (2^30 bytes).""" total_bytes = 2 * layers * kv_heads * head_dim * seq_len * batch_size * bytes_per_val return total_bytes / (1024 ** 3) print(kv_cache_gib(32, 32, 128, 4096, 1)) # 2.0 GiB (standard multi-head attention) print(kv_cache_gib(32, 8, 128, 4096, 1)) # 0.5 GiB (4x smaller with 8-head GQA)- Quantization: Compressing weights from
fp16(14 GB) toint8(7 GB) or 4-bit weight-only formats like AWQ/GPTQ (~3.5 GB, or4.125 bits/weightwith onefp16scale per 128 weights) roughly doubles/quadruples bandwidth-limited decode speed and frees RAM for larger batches;FP8/W8A8quantizes activations too so prefill speeds up on Tensor Cores. Always re-run slice evaluations after quantizing, because hard math/code or low-resource language slices degrade before average scores move. - Continuous batching, FlashAttention, & speculative decoding: Continuous batching inserts newly arrived requests and evicts finished ones at every token step (so short answers never wait behind a 2,000-token essay), FlashAttention computes exact attention in SRAM tiles without materializing huge
T × Tmatrices in HBM, and speculative decoding uses a tiny draft model to propose several tokens verified in parallel by one target-model pass with zero loss in output quality.
- KV caching & GQA: Caching every layer's past Key and Value vectors avoids recomputing the prompt prefix at every decode step, trading compute for GPU RAM:
Intuition & how it works
Think of building and deploying an LLM like training a specialist physician and running a busy clinic: pretraining is reading millions of textbooks and articles to absorb general language and facts; supervised finetuning (SFT) is practicing clinical case write-ups by imitating mentor examples; RLHF / DPO is receiving attending-physician critiques comparing two drafts ("Draft A is clearer and safer than Draft B"); evaluation and monitoring are board exams paired with daily chart audits; and inference optimization is organizing the clinic's memory and triage flow so patients do not wait an hour in the lobby.
A naive setup—training one giant transformer on raw web scrapes, shipping it right after pretraining in fp32 one request at a time, and checking only perplexity—fails at every stage. Raw base models ramble or continue a user's question with more questions instead of answering, reward guessing when unsure (producing fluent hallucinations—confident claims unsupported by facts), and run out of GPU memory or crawl at a few tokens per second because generating each token re-reads gigabytes of weights and past context.
Trace one concrete thread of numbers from training through serving on a 7B-parameter model:
1. Training & alignment: Assigning probability 0.25 to the true next token incurs cross-entropy loss -ln(0.25) = 1.386 nats; across 4 tokens with probabilities [0.5, 0.25, 0.1, 0.8], mean loss is 1.151, giving perplexity exp(1.151) = 3.16. Full mixed-precision AdamW needs ~16 bytes/parameter (112 GB), whereas rank-8 LoRA updates just 65,536 weights (0.39%) on a 4096 × 4096 matrix, and a Bradley–Terry reward gap of 1.0 gives preference probability 1 / (1 + e^-1) = 0.731.
2. Serving bottleneck: In fp16, 7B weights occupy 14 GB; streaming 14 GB across 2 TB/s GPU memory bandwidth takes at least 7 ms/token (~140 tokens/s ceiling at batch 1). Saving past attention Keys and Values in a KV cache avoids quadratic recomputation at a cost of 0.5 MiB/token (2.0 GiB for 4096 tokens, shrunk 4× to 0.5 GiB with 8-head Grouped-Query Attention), while 4-bit quantization cuts weight traffic to ~3.5 GB.
Key points
- Pretraining builds general capability via causal next-token prediction: A decoder-only transformer with a causal mask (preventing token
tfrom peeking at future tokens> t) minimizes-ln p(x_t | x_<t)over deduplicated, PII-scrubbed, decontaminated text; compute scales as~6 × N × DFLOPs (8.4 × 10^22FLOPs for7Bweights on2Ttokens), and sharding (ZeRO / FSDP) splits the~16 bytes/parameterAdamW state across GPUs. - Finetuning shapes format and skills efficiently: SFT masks prompt tokens out of the loss so gradients only teach answering; LoRA freezes
Wand learns low-rankB · Aadapters (0.39%of parameters at4096 × 4096,r = 8), while QLoRA holds the frozen base in 4 bits. Use finetuning for style and structure, and RAG (Retrieval-Augmented Generation) for changing facts. - SFT and RLHF / DPO are sequential stages, not rivals: SFT imitates single demonstrations; RLHF fits a Bradley–Terry reward model (
P(w > l) = σ(r_w - r_l)) on human comparisons and runs PPO with a KL-divergence leash to prevent reward hacking (gaming the reward model with verbose fluff), whereas DPO optimizes those same pairwise preferences directly without a separate reward model. - Cut hallucinations by changing context, tools, and incentives: Ground answers in retrieved passages with citations verified by NLI (entailment checking), offload exact lookups/math to tools, and penalize wrong guesses so abstaining beats guessing below
50%confidence (+1right /-1wrong /0abstain gives-0.40expected score at30%confidence). - Stack evaluation tiers and statistically sized production monitors: Pair perplexity (same-tokenizer regression tracking), task metrics like
pass@kwith confidence intervals (±2.8points at72%on1,000items) and paired McNemar tests, and blind human / position-debiased LLM-as-judge pairwise win rates; in production, monitor latency (TTFT and TPOT), sampled groundedness/quality (±3.8-point 95% band on200daily samples at92%), safety, and embedding topic drift. - Optimize prefill (compute-bound) and decode (bandwidth-bound) differently: Combine KV caching + GQA + PagedAttention + prefix caching, 8-bit/4-bit quantization, continuous batching (token-step dynamic scheduling), FlashAttention, and speculative decoding.
Common mistakes
- Claiming RLHF teaches the model large amounts of new factual knowledge: Factual knowledge is learned overwhelmingly during pretraining (or supplied at query time via RAG); SFT and RLHF steer instruction following, safety refusals, and response style.
- Computing SFT loss over prompt tokens by accident: Unmasked prompt tokens waste capacity teaching the assistant to predict user questions, hurting short-response instruction following.
- Comparing token-level perplexity across two models with different tokenizers: A larger vocabulary compresses the same paragraph into fewer, harder-to-predict tokens, raising per-token perplexity even when the model is strictly stronger; normalize to bits per byte (
total_nats / (ln(2) × utf8_bytes)) instead. - Saying
temperature = 0solves hallucinations: Greedy decoding removes random sampling coin-flips, but whenever the model's top belief is wrong,temperature = 0emits that falsehood with 100% determinism. - Sizing GPU memory from model weights alone: Sixteen concurrent
4096-token requests on a non-GQA7Bmodel consume32 GiBoffp16KV cache—more than double the14 GBweights! - Quantizing to
int4and checking only the overall average score: Aggregate accuracy can dip just0.4points while structured JSON generation, multi-step math, or non-English slices drop5+points. - Monitoring only HTTP 500s and p99 latency in production: Broken retrieval chunks or a bad prompt template return fast HTTP 200 responses full of wrong answers unless daily sampled quality and user-feedback signals are tracked.
Follow-up questions
- When should you use RAG versus finetuning to specialize an LLM for an enterprise domain? Choose RAG whenever facts update frequently, require per-user access control, or need verifiable source citations—updating knowledge is just re-indexing documents rather than retraining weights. Choose finetuning (SFT / LoRA) when you need consistent behavioral changes, such as strict JSON/DSL schemas, domain shorthand fluency, or concise house tone. In production systems, combining both works best: finetune a compact adapter to cite retrieved passages faithfully and say "not in sources" when evidence is missing, while keeping live facts in the retrieval index.
- Your new model scored +4 points higher on offline benchmarks, yet live user thumbs-up dropped in the A/B test. How do you debug the gap? First check distribution mismatch (compare production query lengths, languages, and topic clusters against your static benchmark) and operational confounders (did slower TTFT—time to first token—annoy users even though text quality rose?). Next inspect behavioral shifts invisible to multiple-choice benchmarks: over-refusals on benign edge cases, verbose multi-paragraph walls of text from RLHF reward hacking, or broken markdown/UI formatting. Pull 50 side-by-side prompt transcripts where user feedback diverged and run a blind human review to turn the newfound failure pattern into a permanent offline regression slice.
- How does speculative decoding speed up generation without losing any accuracy from the large model? A fast, tiny draft model
qproposesγcandidate tokens sequentially, and the large target modelpscores allγtokens in one parallel forward pass (amortizing the single weight read across multiple tokens). Accepting each draft tokenxwith probabilitymin(1, p(x) / q(x))—and on the first rejection sampling a corrected token from normalizedmax(0, p - q)—mathematically guarantees the exact same output distribution as sampling frompalone! With per-token acceptance rateα = 0.8andγ = 4draft tokens, one target forward pass produces(1 - 0.8^5) / (1 - 0.8) = 3.36tokens on average, giving roughly a2–3×real-world speedup at small batch sizes.
Follow-up questions
- When should you use RAG versus finetuning to specialize an LLM for an enterprise domain?
- Your new model scored +4 points higher on offline benchmarks, yet live user thumbs-up dropped in the A/B test. How do you debug the gap?
- How does speculative decoding speed up generation without losing any accuracy from the large model?
Similar questions
- Base-Only Compensation Expectations
- Lightweight Markdown HTML Converter
- Convert Quoted Link Markup to HTML Without Regex
- Low-Latency Tree Ensemble Inference
- Select Score Cutoff for Target Precision
- Payment Fraud Detection Under Class Imbalance and Drift