LLM Fundamentals

Course path (9 chapters)
  1. LLM
  2. RAG
  3. Agent Core
  4. Retrieval Engineering
  5. LangChain & LangGraph
  6. MCP & A2A
  7. OpenClaw & Hermes
  8. Multi-agent & KG
  9. Multimodal
Chapter 1

LLM Fundamentals

NLP → Transformer → training pipeline → applications → model selection

Scroll reference — matches course-present*.html slide deck

Course hub · LLM / RAG / Multimodal are separate documents with aligned content.

Chapter 1

Why did LLMs emerge?

From NLP to LLM: why traditional AI was not enough

Two questions to start (problem-driven)

Why did Siri feel dumb?

Short replies, lost context, brittle rules.

Why did ChatGPT feel smart?

Long context, fluent reasoning, general tasks.

Root cause of classical NLP: cannot model long-range context.

NLP in one sentence: everything is prediction

Statistical NLP learns rules from large corpora. A Language Model predicts the next word (token) probabilistically given all previous words.

ChatGPT looks like it "understands" and "answers" — but under the hood it is still next-token prediction, one token at a time.

Every NLP task = a prediction problem

TaskWhat the model predictsExample
Language modelingP(next token | context)"I love" → "Paris"
ClassificationP(label | text)Sentiment: positive / negative
TranslationP(target word | source + target so far)En → Zh, one token at a time
QA / ChatP(answer token | question + history)"Capital of France?" → "Paris"
ASR (speech-to-text)P(text token | audio frames)Audio waveform → transcript
TTS (text-to-speech)P(audio frame | text + past audio)Text → waveform

Prediction loop (train and inference)

NLP = predict next unit, repeatedly Input context Model f_theta P(next token) Pick token Append to context Training: compare prediction vs ground truth, backprop. Inference: loop until EOS.

Four failures of traditional AI

ApproachWhy it failed
Rule systemsInfinite language variation; rules break
Traditional MLHand-crafted features; semantics not end-to-end
RNN / LSTMSequential, slow; distant tokens fade (vanishing gradient)
CNN on textLocal window; needs many layers for global view

Long-range dependency: Germany example

I grew up in Germany ... (50 words) ... I speak fluent ______ RNN: sequential chain T1 - T2 - T3 - ... - T50 - [blank] "Germany" signal fades along the chain May predict wrong language Transformer: Attention [blank] connects directly to "Germany" one hop, full weight Correct: German / Deutsch

Language Model: mathematical definition

$$\mathcal{P}(s_1 \ldots s_n) = \prod_{j=1}^{n} \mathcal{P}(s_j \mid s_1, \ldots, s_{j-1})$$

Chain rule: modeling language = modeling next-token probability, repeatedly.

GPT approximates $\mathcal{P}(s_{t+1} \mid s_{1:t})$ with a Transformer.

Numeric example (toy vocabulary {I, love, Paris})

$$\mathcal{P}(\text{I love Paris}) = \mathcal{P}(\text{I}) \cdot \mathcal{P}(\text{love}\mid\text{I}) \cdot \mathcal{P}(\text{Paris}\mid\text{I love})$$

If $\mathcal{P}(\text{I})=0.02$, $\mathcal{P}(\text{love}\mid\text{I})=0.12$, $\mathcal{P}(\text{Paris}\mid\text{I love})=0.09$:

Joint probability = $0.02 \times 0.12 \times 0.09 = \mathbf{0.000216}$

Tokenization & Embedding

Tokenization: text → subword tokens → integer IDs

"What is the capital of France?"

→ [What, is, the, capital, of, France, ?]

→ [1234, 42, 5, 891, 18, 4021, 31]

$$\mathbf{x}_t = \mathbf{E}[id_t] + \mathbf{PE}_t$$

Each ID maps to a vector in $\mathbb{R}^d$ (768, 4096, ...). Similar meaning → nearby vectors.

Word embedding similarity

Semantically related words have similar vectors. Classic example:

$$\text{vec}(\text{king}) - \text{vec}(\text{man}) + \text{vec}(\text{woman}) \approx \text{vec}(\text{queen})$$

Embeddings encode semantic relationships (gender, geography, tense) as geometric directions in vector space.

Chapter 2

Why Transformer changed the world

Before formulas: understand why Attention beats RNN and CNN

RNN vs CNN vs Attention

Transformers also power computer vision and audio (ASR/TTS) — see Ch9.

ArchitecturePatternProblem
RNNT1 → T2 → T3 → ... → T50Serial, no parallel; forgets distant tokens
CNNLocal sliding windowsCannot see global context in one layer
AttentionT1 ↔ T2 ↔ ... ↔ T50Direct links; parallel; global in one layer
RNN: Token1 to Token50 = 49 hops Attention: Token1 to Token50 = 1 hop T1 T2 T3 ... T50 T1 T50 direct connection

Attention intuition: "Who matters most?"

The animal did not cross the street because it was tired. it animal street weight 0.84 to "animal"

Scaled dot-product attention

$$\text{Attention}(Q,K,V)=\text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V$$

Self-attention: when $Q,K,V$ all come from input $X$:

$$\text{Self-Attention}(X)=\text{softmax}\!\left(\frac{XX^\top}{\sqrt{d_k}}\right)X$$

In practice, learnable projections $W_Q, W_K, W_V$ are applied first:

$$\text{Self-Attention}(X,W)=\text{softmax}\!\left(\frac{XW_Q(XW_K)^\top}{\sqrt{d_k}}\right)XW_V$$

Hand calculation (3 tokens: cat, sat, mat)

Scores for "sat": cat=0.85, sat=1.41, mat=0.28

Softmax weights: [0.26, 0.58, 0.16]

Output = $0.26 V_{cat} + 0.58 V_{sat} + 0.16 V_{mat}$

Multi-head attention

$$\text{MultiHead}(X)=\text{Concat}(\text{head}_1,\ldots,\text{head}_h)\,W_O$$

Each head uses its own $(W_Q^{(i)}, W_K^{(i)}, W_V^{(i)})$. Heads can focus on syntax, coreference, or semantics in parallel, then merge via $W_O$.

Key takeaway: Transformer = encoder-decoder + self-attention + residual connections + layer normalization. Non-recurrent; context via attention, not hidden state chains.
Chapter 2 · Architecture

Transformer: Encoder-Decoder Architecture

Vaswani et al. 2017 — Attention Is All You Need

Three model families

ModelStackAttention typeExamples
Encoder-DecoderBothEncoder: full · Decoder: masked + cross-attnTranslation, Whisper ASR
Decoder-only (GPT)Decoder onlyCausal masked self-attentionChatGPT, Claude, Llama
Encoder-only (BERT)Encoder onlyBidirectional self-attentionSearch, classification, embeddings

Encoder-Decoder architecture diagram

ENCODER DECODER Input tokens Embedding + Positional Encoding Encoder Layer x N Multi-Head Self-Attention Add and Norm + FFN + Add and Norm Encoder output (K, V) Output tokens so far (BOS...) Output Embedding + Pos Encoding Decoder Layer x N 1. Masked Self-Attention (causal) 2. Cross-Attention (Q dec, K/V enc) 3. FFN + Add and Norm each step Linear + Softmax P(next token) - append and repeat cross-attn K,V

Encoder layer internals

Input X
Multi-Head Self-Attention(X,X,X)
Add and LayerNorm (residual)
Feed-Forward: FFN(x)=max(0,xW1+b1)W2+b2
Add and LayerNorm
Output to next encoder layer

Decoder layer internals (3 sub-layers)

Masked Self-Attention (cannot see future tokens)
Cross-Attention: Q from decoder, K/V from encoder output
Position-wise FFN

Positional encoding (sin/cos)

$$PE_{(pos,2i)}=\sin\!\left(\frac{pos}{10000^{2i/d}}\right), \quad PE_{(pos,2i+1)}=\cos\!\left(\frac{pos}{10000^{2i/d}}\right)$$

Attention has no built-in order; positional encoding injects token position. Modern models often use RoPE (rotary) instead, which extends better to long context.

GPT = Decoder-only (ChatGPT path)

GPT (Decoder-only) Input: prompt tokens + generated tokens Token Embedding + RoPE Decoder Block x L (same stack repeated) Causal Masked Multi-Head Self-Attention Add and Norm + SwiGLU FFN + Add and Norm No encoder. No cross-attention. LM Head (Linear to vocab) Softmax - sample next token - append Autoregressive loop until EOS

No encoder stack. Your prompt is left context; model generates rightward with causal mask.

How data flows in Transformers

Encoder path

  1. Input tokens (source sentence or prompt)
  2. Tokenize → embed → add positional encoding
  3. Pass through N encoder layers
  4. Output: deep representation used as K, V for decoder

Decoder path

  1. Start with <BOS>, grow output token by token
  2. Masked self-attention: only see past generated tokens
  3. Cross-attention: Q from decoder, K/V from encoder
  4. Linear + softmax → P(next word); if not <EOS>, append and repeat
Output is always P(next token). This is why ChatGPT responds like a typewriter — one token at a time until <EOS>.

Pre-training vs Fine-tuning

Pre-trainingFine-tuning
DataBillions of web tokens (unlabeled)Thousands-millions labeled examples
ObjectivePredict next tokenTask-specific (QA, chat, tools)
Cost$ millions, 1000+ GPUs$ hundreds - thousands
ResultBase model (continues text)Assistant / domain model
Chapter 2 · Inference

How an LLM answers your question

Step-by-step decode for: "What is the capital of France?"

Seven-step inference loop

  1. Tokenize → embed + positional encoding
  2. Forward through L Transformer layers
  3. LM Head → logits (vocab size |V|)
  4. Softmax → $\mathcal{P}(\text{next token} \mid \text{context})$
  5. Pick token (greedy / top-p) → "Paris"
  6. Append → repeat until <EOS>
Autoregressive: one token at a time, like a typewriter.

Numeric decode (toy logits)

TokenParisLondonthe<EOS>
logit3.21.10.3-1.0
softmax77.9%9.5%4.3%1.2%
$$\mathcal{P}_i=\frac{e^{z_i/T}}{\sum_j e^{z_j/T}} \quad (T = \text{temperature})$$

Next: Temperature, top-p, decoding strategies

Chapter 2 · Sampling

Inference parameters: temperature, top-p, top-k

Same model, different settings → very different output behavior

After the model outputs logits, you choose how to pick the next token. API parameters control randomness vs determinism.

Core parameters

ParameterWhat it doesTypical rangeUse when
temperature (T)Scales logits before softmax. Low = peaked; high = random0 – 20 for facts/code; 0.7-1.0 chat; >1 creative
top-p (nucleus)Sample from smallest set with cumulative prob ≥ p0.1 – 1.0~0.9 default; lower = safer
top-kKeep only k highest-probability tokens1 – 100k=1 is greedy; often 40-50
max_tokensCap generated length256 – 128KCost control, UI limits
stop sequencesHalt when string appearscustomJSON blocks, end markers
frequency / presence penaltyReduce repetition0 – 2Long generations
seedFix RNG when supportedintegerReproducible tests

Temperature effect (Paris example logits)

TokenT=0.1T=1.0T=2.0
Paris99.2%77.9%52.1%
London0.5%9.5%18.3%
the0.2%4.3%12.8%

Presets by task

Tasktemperaturetop_p
Code / JSON0 – 0.21.0
RAG factual QA0 – 0.30.9
General chat0.70.9
Creative writing1.0 – 1.20.95
Chapter 3

Why "intelligence" suddenly emerges

Emergent abilities & Scaling Laws

< 1B params

Advanced autocomplete. Weak reasoning.

10B - 100B+ params

Suddenly: CoT reasoning, coding, planning, translation.

Emergence: capabilities absent in small models; nonlinear jump at scale.

Scaling Laws

$$L(N,D) \approx \left(\frac{N_c}{N}\right)^{\alpha_N} + \left(\frac{D_c}{D}\right)^{\alpha_D}$$

Loss decreases predictably with parameters N, data tokens D, and compute C.

Continue: What is an LLM → training and apps first; model selection at the end.

Ch3 · LLM Landscape

What is an LLM?

Transformer models with 10B+ parameters trained on massive text

Definition: LLMs = Transformer language models with hundreds of billions+ parameters, trained on massive text (GPT-3, LLaMA, DeepSeek).

They understand language and solve complex tasks via text generation (next-token prediction at scale).

Five key techniques

TechniqueWhat it meansExample
ScalingMore params + data + compute → better capacityGPT-1 117M → GPT-3 175B
Distributed trainingParallel strategies to train huge modelsData / tensor / pipeline parallel
Ability elicitingPrompt design, few-shot, CoT to unlock skills"Think step by step"
Alignment tuningMatch human values (HHH)RLHF, DPO
Tool manipulationCompensate for stale knowledge / no actionRAG, API calls, code exec

Open-source LLM family

FamilyOriginNotes
LLaMA (Meta)Feb 2023; LLaMA 3.2 (Sep 2024): 1B, 3B, 11B, 90BMost popular open base; strong benchmarks
Alpaca (Stanford)First open instruct model on LLaMA-7B52k instruction examples; cheap SFT demo
ChatGLM (Zhipu + Tsinghua)Open bilingual model; multimodal image understandingAcademic + commercial use (with registration)
DeepSeek-V3Dec 2024; 671B MoE (37B active); MIT licenseStrong code/math; very low API cost
Qwen 2.5 (Alibaba)Open weights, strong CN/ENCommon in China ecosystem
Chapter 4

Modern LLM Training Pipeline

What happens at each stage, how it is done, and how we evaluate

Seven-stage pipeline overview

1 Pretrain 2 SFT 3 RLHF 4 Tools 5 Agent 6 Longctx 7 Memory Product Foundation: steps 1-3 | Agent era: steps 4-7

GPT family timeline

ModelYearParamsKey change
GPT-12018117MFirst generative pre-trained Transformer
GPT-220191.5BStronger generation
GPT-32020175BFew-shot reasoning emerges
ChatGPT2022~175BSFT + RLHF = conversational assistant
GPT-42023Multimodal in/out; 25K+ word replies; safer & more factual vs 3.5
GPT-4oMay 2024Text + audio + image; 128K context; knowledge Oct 2023

What each stage produces

StageOutputUser-visible behavior
PretrainBase LLMContinues text; ignores instructions
SFTInstruction modelFollows questions, chat format
RLHFAligned modelMore helpful, safer, better style
Agent FTAgent modelCalls tools, multi-step tasks

Continue to Pretrain, SFT, RLHF, Eval for full detail.

Ch4 Stage 1

Pretraining: how it actually works

Objective

$$\mathcal{L}_{\text{PT}} = -\frac{1}{N}\sum_{t=1}^{N} \log \mathcal{P}_\theta(x_t \mid x_{1:t-1})$$

Every position: predict next token from all previous tokens. Wrong prediction updates all weights via backprop.

End-to-end workflow

1. Collect raw text (Common Crawl, books, Wikipedia, code)
2. Clean: dedup, filter toxic/PII, language ID, quality score
3. Tokenize entire corpus (BPE / SentencePiece)
4. Train on GPU cluster (data + tensor + pipeline parallel)
5. Save checkpoint (base model)
6. Evaluate on validation set

Data mix (typical)

SourceRoleShare
Web crawlScale, diversity60-80%
BooksLong-form coherence5-10%
WikipediaFactual knowledge3-5%
CodeProgramming5-15%

Distributed training (how 175B is possible)

Evaluation after pretraining

MetricMeaningTarget
Perplexity (PPL)Model surprise on validation textLower is better
Val lossNegative log-likelihood curveSmooth decrease
LAMBADA / HellaSwagZero-shot benchmarksHigher accuracy
After pretrain the model cannot chat — it only continues text. Example: Q: "2+2=" may continue with essay about math, not "4".
Ch4 Stage 2

SFT / Instruction Tuning

Teach the model to follow instructions

After pretrain

Q: "What is 2+2?"
May continue: "...and why math matters..."

After SFT

Q: "What is 2+2?"
Answer: "2+2 equals 4."

Data format

<|user|> What is the capital of France?
<|assistant|> The capital of France is Paris.

Training procedure

$$\mathcal{L}_{\text{SFT}} = -\sum_{t \in \text{answer only}} \log \mathcal{P}_\theta(y_t \mid x, y_{1:t-1})$$
  1. Load pretrained weights (not random init)
  2. Format as chat template
  3. Mask loss on prompt — only train on assistant reply tokens
  4. Train 1-3 epochs on 10k-1M examples, LR ~1e-5

Fine-tuning methods

MethodTrainsGPU needUse when
Full FTAll paramsVery highMax quality, big budget
LoRALow-rank adapters (~0.1% params)LowAlpaca, most open FT
QLoRALoRA on 4-bit base1x 24GB GPUConsumer hardware

Evaluation after SFT

BenchmarkTests
MMLU57-subject multiple choice knowledge
MT-Bench / AlpacaEvalMulti-turn quality (GPT-4 as judge)
Human side-by-sideWin rate A vs B
Format complianceJSON / length / structure adherence
Ch4 Stage 3

RLHF and DPO

Ouyang et al. 2022

Why SFT alone fails

RLHF three-step flowchart

RLHF Pipeline Step 1: SFT Human writes ideal answers. Train imitation. Output = pi_SFT Step 2: Train Reward Model Same prompt, generate 4-9 responses. Humans rank best to worst. Train RM r(x,y) to predict ranking (Bradley-Terry loss). Step 3: PPO fine-tune LLM Generate y, score with RM, PPO update LLM to maximize reward. KL penalty keeps LLM close to pi_SFT (prevent reward hacking).
$$\max_\theta \; \mathbb{E}[r_\phi(x,y)] - \beta\, D_{\text{KL}}(\pi_\theta \,\|\, \pi_{\text{SFT}})$$

PPO: Proximal Policy Optimization — limits policy change per step.

DPO: trains directly on preference pairs (y_w preferred over y_l) without separate reward model.

Evaluation after RLHF

TypeHow
Human evalSide-by-side win rate vs SFT baseline
Reward model scoreAverage RM on test prompts
Safety red-teamingAdversarial prompts, refusal rate
TruthfulQAHallucination / factuality
Chatbot Arena EloCrowdsourced preference ranking
Ch4 Stages 4-7 + Eval

Agent-era training and full evaluation

Stages 4-7

StageHow (concrete)Evaluation
Tool LearningCurate (prompt, tool_call JSON) pairs; function schema in promptTool call accuracy, BFCL benchmark
Agent FTReAct trajectories: Thought, Action, ObservationTask success rate, SWE-bench
Long-contextRoPE scaling, continue train on long docsNeedle-in-haystack, RULER
Memory AlignWhen to save/recall user factsMulti-session recall accuracy

Master evaluation matrix

StageAutomaticHumanProduction
PretrainPPL, val lossSample continuationsTrain curves, GPU util
SFTMMLU, CE lossMT-Bench, side-by-sideInstruction follow rate
RLHFRM score, TruthfulQAWin rate, red teamThumbs up/down
AgentTask success, tool accuracyEnd-to-end completionBadcase replay

ChatGPT 3-step summary

Pretrain Internet text Next-token loss Eval: PPL Base model SFT Human QA pairs Supervised loss Eval: MMLU Instruction model RLHF Human preferences RM + PPO / DPO Eval: win rate ChatGPT
PM rule: Define eval before training. Pretrain = capability ceiling. SFT = instruction. RLHF = preference. Agent = action in the real world.
Appendix · LLM ≠ Agent

Why LLM cannot be an Agent alone

The brain still needs arms, legs, and memory

1. No long-term memory

Each chat is a fresh start. Need Memory system.

2. Cannot act

Only emits tokens. Need Tools (API, code, DB).

3. No planning

"Do market analysis" fails in one shot. Need Planning.

4. No environment

Blind to real world. Need Environment feedback.

Soul diagram: Agent = LLM + execution system

User LLM Reasoning Brain Memory vector DB / history Planning task decomposition Tools Browser / Python / API Database Weather
$$\text{Agent} = \text{LLM} + \text{Memory} + \text{Planning} + \text{Tools} + \text{Environment}$$
Appendix · Agent preview

How agents are trained

Behavior training, not just prompts

  1. Tool Calling — learn when/how to call APIs
    User: NYC weather? → {"tool":"weather_api","city":"New York"}
  2. Planning — research → collect → analyze → report
  3. Reflection — "Did I answer wrong? Should I retry?"
  4. ReAct — Thought → Action → Observation loop

ReAct loop

Thought: User wants NYC weather. I need the weather tool.
Action: {"tool":"weather_api","city":"New York"}
Observation: {"temp":22,"unit":"C","condition":"sunny"}
Thought: I have data. Answer in natural language.
Action: Reply: "New York is 22C and sunny today."
ChatGPT chat = one generation pass · Agent = many Thought-Action-Obs cycles

Path: ③ Agent④ Retrieval⑤ LangChain/LangGraph⑥ MCP/A2A⑦ OpenClaw⑧ Multi-agent.

Appendix · Long context

Long context & memory

Context Engineering

AI Coding Agent needs in one window:

Short-term memory

Context window (128k tokens)

Long-term memory

Vector DB + user profile DB

Implementation: ⑤ SqliteSaver + Store · ⑧ Multi-agent (course path, not this appendix number).

Context Engineering — design what enters the prompt, in what order, with what priority.
Appendix · Applications

Applications of LLMs

Real-world domains beyond chat

DomainHow LLM is usedExamples / models
Customer supportAnswer inquiries, troubleshoot, conversational FAQChatbot + RAG on product docs
Content generationArticles, blogs, social posts, product copyGPT-4o, Claude; human edit required
RecommendationsAnalyze preferences, personalized suggestionsEmbedding + LLM ranking
HealthcareInfo extraction, advice, mental health chat, report simplificationMed-PaLM, PubMedQA (not a doctor!)
Virtual assistantsTask execution, personalized responsesSiri successor pattern: LLM + tools
EducationExplain concepts, answer student questions, tutoringSFT on pedagogical data
FinanceSentiment, NER, numerical claim detection, reasoningBloombergGPT, FinGPT
LawResearch assistant, draft reviewGPT-4 scored top 10% on bar exam
Civil engineering (course context)Report drafting, code/regulation Q&A, schedule analysisLLM + RAG on project docs + BIM data
Pattern: Raw LLM alone is rarely enough. Production = LLM + RAG (domain docs) + tools (calculator, DB) + human oversight (healthcare, law, finance).
Appendix · Model selection

Model selection and deployment

After you understand training, agents, and applications — now pick the right model and settings

Why last? Comparison only makes sense once you know pretrain/SFT/RLHF, RAG, agents, and use cases.

Selection = which model + which inference params + which tools (RAG, API).

  1. Match model to task (multimodal? Chinese? self-host?)
  2. Set temperature / top-p for the task (see Ch2 sampling)
  3. Know hard boundaries (cutoff, hallucination, context)
  4. A/B test on real queries before production

Frontier model comparison · Capability boundaries

Ch11 · Model Comparison

OpenAI vs DeepSeek vs others (2025-2026)

Frontier models compared — specs from official docs; benchmarks vary by task

Frontier model comparison

ModelVendorArchitectureContextModalOpen?Strengths
GPT-4oOpenAIClosed128KText + image + audioAPI onlyMultimodal, ecosystem, tool use, reliability
GPT-4OpenAIClosed128KText + imageAPI onlyLonger answers, safer, more factual vs 3.5
DeepSeek-V3DeepSeek671B MoE (37B active)128KTextMIT open weightsCode, math, cost (~10x cheaper than GPT-4o API)
DeepSeek-R1DeepSeekRL-trained reasoning128KTextOpenChain-of-thought math/reasoning; slower, verbose
Claude 3.5 SonnetAnthropicClosed200KText + imageAPI onlyLong documents, coding, safety-focused
Llama 3.2Meta1B-90B dense128KText (+ vision 11B/90B)OpenSelf-host, fine-tune, on-device
ChatGLMZhipu / Tsinghua6B+8K-128KText + imageOpen (academic)Chinese-English bilingual
Qwen 2.5Alibaba0.5B-72B128KText (+ vision variants)OpenCN/EN, coding, local deploy

GPT-4o details

When to choose which?

ScenarioRecommendedWhy
Multimodal app (voice + image)GPT-4oNative audio/image; mature API
High-volume text API, cost-sensitiveDeepSeek-V3Strong benchmarks, open weights, low price
Hard math / logic proofsDeepSeek-R1 or o-seriesRL reasoning training; shows CoT
Self-host / fine-tune on private dataLlama 3.2 / Qwen / DeepSeekOpen weights, no vendor lock-in
100-page document analysisClaude 3.5 (200K)Larger advertised context
Chinese bilingual assistantChatGLM / QwenStrong CN/EN bilingual
Agent with tools + memoryAny frontier + your stackModel is brain; RAG/tools matter more than small benchmark gaps

Benchmark snapshot (indicative, not absolute)

BenchmarkTestsGPT-4o ~DeepSeek-V3 ~DeepSeek-R1 ~
MMLUGeneral knowledge~88%~88%~90%
HumanEvalCode generation~90%~82-90%Strong
MATHMath reasoningGood~90%~97% (specialized)

Benchmarks shift with each model version. Use as rough guide; always eval on your task.

Ch11 · Boundaries

Model capability boundaries

What LLMs cannot do reliably — even frontier models

Core truth: LLMs predict plausible tokens. They do not have guaranteed access to truth, real-time world state, or persistent memory unless you add tools.

Seven hard boundaries

BoundaryWhat happensMitigation
Knowledge cutoffGPT-4o trained through Oct 2023; unaware of 2024+ eventsRAG, web search tool, newer model
HallucinationConfident but false facts, fake citations, wrong numbersRAG + cite sources, human review, lower temperature
Context vs effective contextAdvertised 128K-200K, but accuracy drops long before limit (2025 research: MECW often << advertised)Chunk + retrieve; do not dump entire repo blindly
No real-world actionCan only emit text unless given toolsAgent + APIs + code execution
Math / logic edge casesFail on multi-step arithmetic, constraint puzzles without CoTCalculator tool, R1/o-series, verify with code
Privacy / securityCloud API may log prompts; model may leak training patternsSelf-host open model, PII filtering, enterprise API
ConsistencySame question, different runs → different answers (sampling)temperature=0, structured output, caching

Closed vs open model tradeoffs

Closed (GPT-4o, Claude)Open (DeepSeek, Llama, Qwen)
TransparencyBlack box weightsInspect / fine-tune weights
Cost at scaleHigher API feesSelf-host can be cheaper
MultimodalGPT-4o native audio/imageMost open models text-first
ComplianceVendor handles infraYou own data residency
Peak capabilityOften leads on general tasksDeepSeek-R1 competitive on reasoning

PM decision framework

  1. Define task + eval set before picking a model
  2. Check: need multimodal? real-time data? self-host?
  3. Run A/B on 50-100 real user queries
  4. Add RAG/tools where boundaries hit (cutoff, hallucination, action)
  5. Monitor production: thumbs down, badcase replay, cost per task
Summary

The full picture

Traditional AI: input → output

LLM: input → reason → generate

Agent: goal → plan → act → feedback → iterate

NLP core: everything is next-token (next-unit) prediction.

RAG: offline index build + online retrieve-then-predict.

Multimodal: same prediction idea for vision (ViT, SAM, Diffusion) and audio (Whisper ASR, TTS).

Models: pick by task (GPT-4o multimodal, DeepSeek cost/reasoning, Llama self-host) — know the boundaries.

$$\text{Agent} = \text{LLM} + \text{Memory} + \text{Planning} + \text{Tools} + \text{Environment}$$

LLM is the brain. Agent is the whole person.