LLM Engineering Cheatsheet

Quick reference for the most common LLM engineering facts, formulas, and decisions.


Tokenization

RuleFact
Average English words → tokens~0.75 words/token (1 token ≈ 4 chars)
1 page of text~500-800 tokens
1000 words~1300-1400 tokens
CodeDenser — 1 token ≈ 2-3 chars

Tiktoken quick check:

import tiktoken
enc = tiktoken.encoding_for_model("gpt-4o")
len(enc.encode("your text here"))

Context Windows (2024-2025)

ModelContextNotes
GPT-4o128KDefault output max 16K
Claude 3.5 Sonnet200KOutput max 8K
Gemini 1.5 Pro1MVery long context
Llama 3.1 70B128KOpen weights
Mistral Large128KEuropean provider
Qwen2.5 72B128KStrong multilingual

Pricing Reference (approximate, verify current pricing)

ModelInput ($/1M tok)Output ($/1M tok)
GPT-4o$2.50$10.00
GPT-4o-mini$0.15$0.60
Claude 3.5 Sonnet$3.00$15.00
Claude 3.5 Haiku$0.80$4.00
Gemini 1.5 Flash$0.075$0.30
Gemini 1.5 Pro$1.25$5.00

Cost formula:

cost = (input_tokens / 1_000_000 × input_price) + (output_tokens / 1_000_000 × output_price)

Memory Requirements

ModelFP16Q8Q4
7B14 GB7 GB3.5 GB
13B26 GB13 GB6.5 GB
34B68 GB34 GB17 GB
70B140 GB70 GB35 GB
405B810 GB405 GB200 GB

Formula: params × bytes_per_param + KV_cache + activations

KV cache per token: 2 × num_layers × num_kv_heads × head_dim × bytes_per_element


Inference Parameters Quick Reference

ParameterDefaultRangeUse For
temperature1.00-2Creativity. 0 = deterministic
top_p1.00-1Nucleus sampling. 0.9 = good default
top_k-1-∞Limit vocab at each step
max_tokensvaries1-maxCap output length
stop-stringsStop sequences
frequency_penalty0-2 to 2Reduce repetition

By use case:

Use CaseTemperaturetop_p
Code generation0.01.0
Factual Q&A0.11.0
Customer support0.30.9
Creative writing0.90.95
Brainstorming1.20.95

Architecture Key Numbers

ComponentWhat It Does
Embedding dim (d_model)Width of token representation
Num layersDepth of transformer
Num headsParallel attention streams
FFN expansionTypically 4× d_model
Vocab size32K-256K for most models
KV heads (GQA)Fewer than Q heads → less memory

Llama-3.1-70B specs: 80 layers, 8192 d_model, 64 Q heads, 8 KV heads (GQA), 32K vocab


Quantization Quick Reference

FormatSize vs FP16Quality LossUse For
FP16NoneTraining, highest quality
BF16NoneTraining on modern hardware
Q8_00.5×NegligibleLocal, high quality
Q5_K_M~0.31×SlightLocal, good balance
Q4_K_M~0.25×MinorLocal, most common
Q3_K_M~0.19×NoticeableRAM-limited
Q2_K~0.13×SignificantEmergency only

Model Selection Quick Decision Tree

Need structured JSON output?
  → gpt-4o-mini with json_mode OR fine-tuned smaller model

Need to run locally / no cloud?
  → Ollama + Qwen2.5-7B (or 14B if you have 16GB RAM)

Need to process 100K+ token documents?
  → Gemini 1.5 Pro (1M context)

Need best coding quality?
  → claude-3-5-sonnet OR gpt-4o OR deepseek-coder

Need cheapest possible for batch tasks?
  → gpt-4o-mini OR gemini-1.5-flash OR groq-llama3

Need best reasoning?
  → o1 OR claude-3-5-sonnet OR gemini-1.5-pro

Need open weights for fine-tuning?
  → Llama-3.1-8B (small) OR Qwen2.5-14B (medium) OR Llama-3.1-70B (large)

vLLM Key Flags

vllm serve meta-llama/Llama-3.1-8B-Instruct \
  --port 8000 \
  --tensor-parallel-size 2 \       # Number of GPUs
  --max-model-len 32768 \          # Context window
  --gpu-memory-utilization 0.90 \  # 90% of VRAM for KV cache
  --enable-prefix-caching \        # Cache repeated prefixes
  --max-num-seqs 256               # Max concurrent sequences

RAG Quick Reference

Chunk size guidance:

  • Short factual docs: 256-512 tokens
  • Long-form text: 512-1024 tokens
  • Code: function-level (variable size)
  • Overlap: 10-20% of chunk size

top_k retrieval → rerank → top_n to model:

  • Retrieve top 20-50 → rerank → send top 3-8 to model

Embedding models:

  • text-embedding-3-small: 1536 dim, $0.02/1M tokens
  • text-embedding-3-large: 3072 dim, $0.13/1M tokens

Serving Performance Targets

MetricTarget
TTFT (interactive)< 500ms
TTFT (background)< 5s
TPS (streaming)> 20 tokens/sec
P99 latency< 3× P50
Error rate< 0.1%
GPU utilization> 80%

Cost Estimation Formula

def estimate_monthly_cost(
    daily_requests: int,
    avg_input_tokens: int,
    avg_output_tokens: int,
    input_price_per_m: float,
    output_price_per_m: float
) -> float:
    monthly_requests = daily_requests * 30
    input_cost = (monthly_requests * avg_input_tokens / 1_000_000) * input_price_per_m
    output_cost = (monthly_requests * avg_output_tokens / 1_000_000) * output_price_per_m
    return input_cost + output_cost

# Example: 10k req/day, 500 input, 200 output, gpt-4o-mini
cost = estimate_monthly_cost(10_000, 500, 200, 0.15, 0.60)
print(f"${cost:.2f}/month")  # ~$22.50/month

Security Checklist (Quick)

□ Input length limit enforced
□ Prompt injection hardening in system prompt
□ Tool whitelist (agents only call approved tools)
□ Approval gates for irreversible agent actions
□ Output schema validation
□ PII scrubbed from logs
□ Rate limiting per user
□ Content moderation on public endpoints
□ API keys in secrets manager (not hard-coded)
□ No secrets in system prompts

Fine-Tuning Decision

Can solve with prompting? → Use prompting
Can solve with few-shot? → Use few-shot
Need up-to-date knowledge? → Use RAG
Need consistent style/format at scale? → Fine-tune
Have < 100 examples? → Don't fine-tune yet
Need to teach facts? → Use RAG, not fine-tuning

Key Open Source Models (2024-2025)

ModelSizeStrengths
Llama 3.1 8B/70B/405B8B-405BGeneral, well-rounded, large community
Qwen 2.5 7B/14B/72B7B-72BStrong coding, multilingual
Mistral 7B / Mixtral 8x7B7B / 47B activeFast, efficient, MoE
DeepSeek-R17B-671BReasoning, coding
Gemma 2 2B/9B/27B2B-27BGoogle, efficient
Phi-3.5 Mini3.8BSmall, surprisingly capable