Library

Volume 2 · GenAI Foundations & LLM Architecture

Notebook
Sign in

Section 3

Tokenization, Context Windows & Inference Optimization

612 words · about 3 min

3.1 Tokenization Deep Dive

Tokenization converts text into numerical tokens the model can process. Different tokenizers produce different token counts for identical text — this directly affects both cost and effective context capacity.

Tokenizer Models Vocab Size Avg Tokens/Word
tiktoken (cl100k_base) GPT-4, GPT-4o 100K ~1.3
tiktoken (o200k_base) GPT-4o-mini, o1 200K ~1.2
SentencePiece (BPE) Llama, Mistral 32K-128K ~1.4
Claude tokenizer Claude 3+ ~100K ~1.3

BPE (Byte-Pair Encoding) example:

"Healthcare"    → ["Health", "care"]         (2 tokens)
"Adjudication"  → ["Adj", "ud", "ication"]   (3 tokens)
"ICD-10-CM"     → ["ICD", "-", "10", "-CM"]  (4 tokens)

Rule of thumb: 1 token ≈ 4 characters ≈ 0.75 words (English). Non-English languages (especially non-Latin scripts like Japanese, Hindi) use significantly more tokens per word — sometimes 2-3x — which materially affects both cost and effective context budget for multilingual deployments.

3.2 Context Window Management

flowchart LR
    subgraph TotalWindow["Total Available Context Window (e.g., 128,000 Tokens)"]
        direction TB
        SP["System Prompt\n(~500 - 2,000 Tokens)"]
        RC["Retrieved Context / RAG\n(~3,000 - 8,000 Tokens)"]
        Hist["User Query & Conversation History\n(~1,000 - 4,000 Tokens)"]
        Out["Reserved Generation Headroom\n(~2,000 - 4,000 Tokens)"]
    end

Context Budget Planning (Claims Processing Agent Example):

  • System Instructions: ~500 tokens (lean guardrails & schema rules)
  • Domain Metadata: ~2,000 tokens (tenant policies, user context)
  • Retrieved RAG Chunks: ~4,000 tokens (top-k semantic chunks)
  • Multi-turn Chat History: ~1,000 tokens (summarized sliding window)
  • Output Reservation: ~2,000 tokens (reserved buffer for generation)
  • Total Utilization: ~9,500 tokens (safely within a 128K window, avoiding attention degradation)

Context Preservation Strategies:

  1. Sliding Window: Retain only the trailing $N$ conversation turns; purge older turns.
  2. Recursive Summarization: Compress historical turns into an updated background summary block.
  3. Re-Ranking & Chunk Pruning: Use cross-encoder re-rankers (e.g., Cohere Rerank) to ingest only top-$K$ chunks rather than flooding context.
  4. Sectional Budget Quotas: Enforce strict upper token limits per component to prevent retrieval spikes from starving the generation budget.

3.3 Inference Optimization Techniques

Technique Mechanism Latency / Memory Impact
KV-Cache Caches prior Key/Value attention tensors; avoids recomputing $K, V$ on every new generated token 2–5× faster generation for long prompts
FlashAttention Hardware-aware IO-tiling; executes attention directly in GPU SRAM without materializing $O(N^2)$ matrix 2–4× speedup, dramatically lowers VRAM usage
Continuous Batching Dynamically introduces new inference requests at token boundaries rather than waiting for entire batches to finish 2–4× overall serving throughput
Speculative Decoding Small draft model proposes $K$ tokens; large target model validates all $K$ tokens in a single parallel forward pass 2–3× wall-clock latency reduction
Quantization (AWQ / GPTQ) Compresses model weights from FP16 down to INT4 / INT8 2–4× VRAM reduction, higher throughput
PagedAttention (vLLM) Manages KV-cache memory via virtual memory paging; eliminates contiguous allocation fragmentation 2–4× concurrent concurrency capacity

Section 3 — Interview Q&A

Q: Walk through how you’d budget the context window for a production RAG agent handling multi-turn conversations.

A: I allocate strict section budgets:

  • System Prompt: ~500 tokens kept highly concise.
  • Retrieved RAG Context: The largest variable component (~2K–4K tokens), strictly capped and re-ranked using cross-encoders to ensure only top-relevance chunks enter.
  • Conversation History: Sliding-window for the last 5 turns, paired with a compressed summary of older turns.
  • Reserved Output Generation: 2K+ tokens reserved to guarantee the model never aborts mid-stream due to max-token limits.

Q: What is KV-cache and why does it matter for serving cost?

A: During autoregressive generation, each new token requires attention over all previous tokens. Caching those Key and Value tensors avoids quadratic recomputation. However, KV-cache grows linearly with sequence length and concurrency. For a 70B model with a 128K window, the KV-cache can consume over 40 GB of VRAM per active stream. Managing this via PagedAttention (vLLM) is essential to maximize concurrent throughput without provisioning extra GPUs.