What You'll Learn
- 1Compute the KV cache footprint of a serving fleet and size GPU memory around it
- 2Derive decode tokens per second from model weight size and HBM bandwidth
- 3Estimate cost per million output tokens for a chosen instance type and batch size
- 4Decide between prompt engineering, retrieval, and fine-tuning from a stated task requirement
Why This Matters
LLMs power chatbots, code generation, summarization, and agentic workflows. Designing an LLM system means managing massive model serving, optimizing inference latency, implementing guardrails, and balancing quality with cost - while handling prompts, context windows, and streaming responses.
Two numbers frame the whole design. A 70B model in FP16 holds 140 GB of weights, and every single output token streams all of them once, so on one A100 with 2.0 TB/s of HBM bandwidth the floor is 70 ms per token before any batching. Meanwhile the KV cache for a 32-way batch at a 4,096 token window is another 40 GiB. Serving is therefore a memory capacity and bandwidth problem first, and a floating point problem second.
System Architecture Overview
Prompt Engineering Patterns
Prompt templates structure LLM interactions with a system prompt, few-shot examples, and user input. The ReAct pattern alternates between reasoning (Thought), tool use (Action/Action Input), and observation before producing a final answer. Chain-of-thought prompting elicits step-by-step reasoning by providing an incomplete chain (e.g., "Step 1:") that the model continues. Temperature controls randomness - lower values (0.2-0.3) for deterministic tasks, higher (0.7+) for creative ones.
LLM Serving with vLLM
Production LLM serving uses vLLM with PagedAttention for efficient KV cache management. A typical configuration uses tensor parallelism across multiple GPUs (e.g., 4x), limits context length (e.g., 8192 tokens), and enables prefix caching for repeated prompts. The service generates text with sampling parameters including top-p (0.95), frequency/presence penalties, and supports both synchronous batch generation and asynchronous streaming.
Fine-Tuning with LoRA
LoRA (Low-Rank Adaptation) fine-tunes LLMs by freezing the base model and training only low-rank decomposition matrices inserted into attention layers (q/k/v/o projections) and MLP layers (gate/up/down). With rank 16, only ~0.5% of parameters are trainable (e.g., 42M out of 8B). Training uses 4-bit quantization (QLoRA), cosine learning rate scheduling, gradient accumulation, and paged AdamW optimizer for memory efficiency.
Scaling Laws
Chinchilla-style scaling laws show that model size (N) and training data (D) should scale proportionally, with approximately 20 tokens per parameter being compute-optimal:
A 1B parameter model therefore needs about 20B tokens, a 7B model about 140B tokens, and a 70B model about 1.4T tokens. The loss itself follows a two-term power law fitted on Chinchilla:
Larger models are more sample-efficient but need proportionally more data to avoid underfitting. The practical consequence is that a model trained far below the curve is overtrained: you paid for parameters you cannot exercise, and a 7B model on 20B tokens will lose to a 3B model on 60B tokens at the same compute budget.
LoRA Parameter Budget
Low-rank adaptation freezes the base weights and trains two matrices per adapted projection. For a projection of input width and output width at rank :
At and that is 262,144 parameters per projection, versus 16,777,216 for the full matrix. Summed over the 40 attention and MLP projections of a 7B transformer, QLoRA trains roughly 10 million parameters, about 0.14 percent of the model, which is why a single 24 GB card can fine-tune it.
Serving Capacity: KV Cache and Decode Speed
Decode is memory-bandwidth bound, not compute bound. Every output token streams the full weight matrix once, so with weight bytes , per-GPU bandwidth , and GPUs in a tensor-parallel group:
Llama-2-70B in FP16 has GB. One A100 delivers 2.0 TB/s, so ms per token, or 14 tokens per second. Across 4 GPUs the same formula gives 17.5 ms, or 57 tokens per second per sequence. That ceiling is physics, not software: kernel work and quantization only move you toward it.
The KV cache decides how many sequences can share that bandwidth. For layers, KV heads, head dimension , sequence length , batch , and bytes per element:
With , (grouped-query attention), , , , and , the cache is 40 GiB. Add 140 GB of weights and a 70B deployment is bandwidth-starved long before it is compute-starved, which is exactly why prefix caching and PagedAttention exist.
Cost follows from the same measurement. If the service sustains output tokens per second at price per GPU-hour:
An A100 at USD 3.50 per hour pushing 2,500 output tokens per second costs USD 0.39 per million tokens, so a 500 token answer costs USD 0.0002 in raw compute before retries, caching, and idle capacity.
| Instance | Model | Precision | Batch | Decode tokens/s | USD per 1M tokens |
|---|---|---|---|---|---|
| 1x A100 80GB | Llama-2-13B | FP16 | 32 | 2,500 | 0.39 |
| 4x A100 80GB | Llama-2-70B | FP16 | 16 | 1,800 | 2.16 |
| 1x L4 | Llama-2-7B | INT8 | 32 | 3,200 | 0.07 |
Common Mistakes
Sizing a deployment from parameter count alone
Fix: Budget weights plus KV cache: 140 GB of weights and 40 GiB of cache at a 4K window with batch 32 both come out of the same cards.
Measuring latency with time to first token only
Fix: Track inter-token delay separately, since decode is bandwidth bound and a 70 ms per token floor survives a fast prefill.
Re-embedding or re-prompting instead of changing model size
Fix: Route simple intents to a 7B model and escalate only the hard 10 to 20 percent of traffic to a 70B model.
Best Practices
- Run a model router so easy prompts land on the small model and only hard prompts pay for the large one
- Enable prefix caching for system prompts, since a 2,000 token shared prefix re-read costs 2,000 prefill tokens per request
- Cap max context length at the 95th percentile of real prompts rather than the model's advertised window
Key Takeaways
- Decode time per token is W / (BW x N): 140 GB of weights on one A100 is 70 ms, on four GPUs 17.5 ms
- KV cache is 2 x L x H_kv x d x s x B x b, which is 40 GiB for a 70B model at 4K context with batch 32
- Compute-optimal training is D = 20 x N, so a 7B model wants 140B tokens and a 70B model wants 1.4T
- Cost per million tokens is p / (3600 x R): an A100 at USD 3.50 per hour at 2,500 tok/s costs USD 0.39
Frequently Asked Questions
Why is decode latency dominated by memory bandwidth rather than FLOPs?
Prefill is compute bound because it processes the whole prompt in parallel, but decode emits one token at a time and each step must read every weight once. Reading 140 GB at 2.0 TB/s takes 70 ms, whereas the arithmetic for a single token is only about 140 GFLOP, which an A100 finishes in well under a millisecond. Hardware therefore sits idle waiting on HBM, which is why quantization, grouped-query attention, and tensor parallelism all target bytes moved rather than operations.
Should I prompt, retrieve, or fine-tune?
Prompt when the behavior fits in a few examples and the model already knows the domain. Retrieve when the answer depends on facts that change, since re-embedding 100,000 documents costs far less than retraining a 7B model and can run every night. Fine-tune when you need a consistent style, a fixed output schema, or a 10x latency reduction that only a smaller specialist model can give you.
What does speculative decoding actually save?
A small draft model proposes k tokens per step and the large model verifies them in one forward pass, so unchanged tokens are accepted for free. When the draft is 70 percent accurate over k = 5, roughly 4 of every 5 tokens skip a full decode step, cutting per-token time toward t / 4 in the limit. The output distribution is mathematically identical to sampling from the large model, so the speedup costs nothing in quality.
Interview Questions
Q1: Explain the difference between SFT, RLHF, and DPO.
SFT trains on (prompt, ideal response) pairs to teach format and behavior. RLHF trains a reward model on human preferences and then optimizes the policy with PPO. DPO skips the reward model and optimizes the policy directly on preference pairs with a Bradley-Terry loss, which is simpler and more stable to run.
Q2: How does PagedAttention work in vLLM?
It treats KV cache like virtual memory: key and value tensors live in fixed 16-token blocks that need not be contiguous, so internal fragmentation drops from roughly 60 percent of a contiguous allocator to near zero and blocks can be shared between a system prompt and its descendants.
Q3: How do you reduce LLM inference latency?
Quantize weights with AWQ or GPTQ to cut the bytes decode has to read, enable Flash Attention and prefix caching, add speculative decoding with a small draft model, run continuous batching so the GPU never idles, and distill the hard fraction of traffic into a smaller model.