Guide / AI engineering Fundamentals
14. LLM fundamentals
An applied AI engineer doesn’t train foundation models but must explain how they behave, because cost, latency and failure modes follow from it.
14.1 How an LLM works (intuition level)#
- Tokens: text is split into sub-word tokens (~4 characters or ~0.75 English words per token; Indic languages often use more tokens per word, which raises cost). Pricing, context limits and latency are all per token.
- Embeddings layer: each token becomes a vector; position information is added (RoPE in most modern models).
- Transformer blocks: self-attention lets every token look at every other token to decide what’s relevant; feed-forward layers transform the result. Attention cost grows with sequence length squared (optimizations like FlashAttention make it practical).
- Next-token prediction: the model outputs a probability distribution over the vocabulary; the decoder picks one token, appends it, repeats. Everything (chat, code, tool calls) is this loop.
- Training stages: pre-training on huge text (knowledge, language) → supervised fine-tuning on instructions → preference tuning (RLHF, DPO, RL with verifiable rewards) for helpfulness, safety and reasoning.
- Mixture of Experts (MoE): only a subset of parameters activates per token → large capacity at lower inference cost.
14.2 Inference mechanics (asked in senior AI rounds)#
- Prefill processes the whole prompt in parallel (compute-bound) → determines time to first token (TTFT). Decode generates one token at a time (memory-bandwidth-bound) → determines tokens per second / inter-token latency.
- KV cache: stores attention keys/values of previous tokens so each new token doesn’t recompute them. Memory grows with context length × batch size — the main limit on concurrent long-context requests.
- Prompt (prefix) caching: providers reuse the KV cache for a repeated prompt prefix (system prompt, documents) → big cost and TTFT savings. Put stable content first, variable content last.
- Latency model: total ≈ TTFT + output_tokens × time_per_token. Output tokens are the expensive part: cutting output length is the fastest latency win.
- Batching: servers batch many requests (continuous batching) for throughput; per-request latency rises a little.
14.3 Sampling parameters#
- Temperature: 0 = near-deterministic (extraction, classification, tool calls); 0.7–1 = creative. Even temperature 0 is not fully deterministic on most APIs.
- Top-p (nucleus) / top-k: limit choices to the most probable tokens.
- Max tokens, stop sequences: cap cost and runaway output.
- Logprobs: token probabilities, usable as a rough confidence signal for classification.
14.4 Model capabilities and limits#
- Context window: how much fits (often 128K–1M+ tokens today), but quality degrades in the middle of very long contexts (“lost in the middle”) and cost scales linearly. Long context does not remove the need for retrieval.
- Hallucination: fluent but false output, worst for specific facts, numbers, citations and rare entities. Mitigate with grounding (RAG), citations, constrained output, verification steps, and letting the model say “I don’t know”.
- Knowledge cutoff: the model doesn’t know recent facts unless you supply them.
- Reasoning models: spend extra “thinking” tokens before answering; better at math, code, planning; slower and costlier. Use for hard steps, not simple classification.
- Multimodal: text + images (+ audio/video for some); document understanding can replace classic OCR pipelines for many cases.
14.5 Choosing a model#
| Factor | Questions |
|---|---|
| Quality | Does it pass your eval set (not public leaderboards)? |
| Latency | TTFT and tokens/s at your prompt sizes |
| Cost | Input vs output price, caching discounts, batch API discounts |
| Context and modality | Fits your documents? Needs vision/audio? |
| Tool use and structured output | Reliable function calling and JSON? |
| Deployment | API vs self-hosted open-weight (Llama, Qwen, Mistral, Gemma, DeepSeek) for data residency, cost at huge volume, or fine-tuning |
| Compliance | Data retention, region, certifications |
Model routing / cascades: send easy requests to a small, cheap model and hard ones to a frontier model (classify difficulty first, or escalate when the small model is low-confidence). Typical result: most traffic on the cheap model with little quality loss.
14.6 Embeddings (preview of section 16)#
An embedding model maps text (or images) to a fixed-length vector (e.g. 384–3072 dimensions) where similar meaning → nearby vectors. Similarity is measured by cosine similarity or dot product (equivalent for normalized vectors). Embeddings power semantic search, clustering, deduplication, classification and recommendations.