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.
From NLP to LLM: why traditional AI was not enough
Short replies, lost context, brittle rules.
Long context, fluent reasoning, general tasks.
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.
| Task | What the model predicts | Example |
|---|---|---|
| Language modeling | P(next token | context) | "I love" → "Paris" |
| Classification | P(label | text) | Sentiment: positive / negative |
| Translation | P(target word | source + target so far) | En → Zh, one token at a time |
| QA / Chat | P(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 |
| Approach | Why it failed |
|---|---|
| Rule systems | Infinite language variation; rules break |
| Traditional ML | Hand-crafted features; semantics not end-to-end |
| RNN / LSTM | Sequential, slow; distant tokens fade (vanishing gradient) |
| CNN on text | Local window; needs many layers for global view |
Chain rule: modeling language = modeling next-token probability, repeatedly.
GPT approximates $\mathcal{P}(s_{t+1} \mid s_{1:t})$ with a Transformer.
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: text → subword tokens → integer IDs
"What is the capital of France?"
→ [What, is, the, capital, of, France, ?]
→ [1234, 42, 5, 891, 18, 4021, 31]
Each ID maps to a vector in $\mathbb{R}^d$ (768, 4096, ...). Similar meaning → nearby vectors.
Semantically related words have similar vectors. Classic example:
Embeddings encode semantic relationships (gender, geography, tense) as geometric directions in vector space.
Before formulas: understand why Attention beats RNN and CNN
Transformers also power computer vision and audio (ASR/TTS) — see Ch9.
| Architecture | Pattern | Problem |
|---|---|---|
| RNN | T1 → T2 → T3 → ... → T50 | Serial, no parallel; forgets distant tokens |
| CNN | Local sliding windows | Cannot see global context in one layer |
| Attention | T1 ↔ T2 ↔ ... ↔ T50 | Direct links; parallel; global in one layer |
Self-attention: when $Q,K,V$ all come from input $X$:
In practice, learnable projections $W_Q, W_K, W_V$ are applied first:
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}$
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$.
Vaswani et al. 2017 — Attention Is All You Need
| Model | Stack | Attention type | Examples |
|---|---|---|---|
| Encoder-Decoder | Both | Encoder: full · Decoder: masked + cross-attn | Translation, Whisper ASR |
| Decoder-only (GPT) | Decoder only | Causal masked self-attention | ChatGPT, Claude, Llama |
| Encoder-only (BERT) | Encoder only | Bidirectional self-attention | Search, classification, embeddings |
Attention has no built-in order; positional encoding injects token position. Modern models often use RoPE (rotary) instead, which extends better to long context.
No encoder stack. Your prompt is left context; model generates rightward with causal mask.
| Pre-training | Fine-tuning | |
|---|---|---|
| Data | Billions of web tokens (unlabeled) | Thousands-millions labeled examples |
| Objective | Predict next token | Task-specific (QA, chat, tools) |
| Cost | $ millions, 1000+ GPUs | $ hundreds - thousands |
| Result | Base model (continues text) | Assistant / domain model |
Step-by-step decode for: "What is the capital of France?"
| Token | Paris | London | the | <EOS> |
|---|---|---|---|---|
| logit | 3.2 | 1.1 | 0.3 | -1.0 |
| softmax | 77.9% | 9.5% | 4.3% | 1.2% |
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.
| Parameter | What it does | Typical range | Use when |
|---|---|---|---|
| temperature (T) | Scales logits before softmax. Low = peaked; high = random | 0 – 2 | 0 for facts/code; 0.7-1.0 chat; >1 creative |
| top-p (nucleus) | Sample from smallest set with cumulative prob ≥ p | 0.1 – 1.0 | ~0.9 default; lower = safer |
| top-k | Keep only k highest-probability tokens | 1 – 100 | k=1 is greedy; often 40-50 |
| max_tokens | Cap generated length | 256 – 128K | Cost control, UI limits |
| stop sequences | Halt when string appears | custom | JSON blocks, end markers |
| frequency / presence penalty | Reduce repetition | 0 – 2 | Long generations |
| seed | Fix RNG when supported | integer | Reproducible tests |
| Token | T=0.1 | T=1.0 | T=2.0 |
|---|---|---|---|
| Paris | 99.2% | 77.9% | 52.1% |
| London | 0.5% | 9.5% | 18.3% |
| the | 0.2% | 4.3% | 12.8% |
| Task | temperature | top_p |
|---|---|---|
| Code / JSON | 0 – 0.2 | 1.0 |
| RAG factual QA | 0 – 0.3 | 0.9 |
| General chat | 0.7 | 0.9 |
| Creative writing | 1.0 – 1.2 | 0.95 |
Emergent abilities & Scaling Laws
Advanced autocomplete. Weak reasoning.
Suddenly: CoT reasoning, coding, planning, translation.
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.
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).
| Technique | What it means | Example |
|---|---|---|
| Scaling | More params + data + compute → better capacity | GPT-1 117M → GPT-3 175B |
| Distributed training | Parallel strategies to train huge models | Data / tensor / pipeline parallel |
| Ability eliciting | Prompt design, few-shot, CoT to unlock skills | "Think step by step" |
| Alignment tuning | Match human values (HHH) | RLHF, DPO |
| Tool manipulation | Compensate for stale knowledge / no action | RAG, API calls, code exec |
| Family | Origin | Notes |
|---|---|---|
| LLaMA (Meta) | Feb 2023; LLaMA 3.2 (Sep 2024): 1B, 3B, 11B, 90B | Most popular open base; strong benchmarks |
| Alpaca (Stanford) | First open instruct model on LLaMA-7B | 52k instruction examples; cheap SFT demo |
| ChatGLM (Zhipu + Tsinghua) | Open bilingual model; multimodal image understanding | Academic + commercial use (with registration) |
| DeepSeek-V3 | Dec 2024; 671B MoE (37B active); MIT license | Strong code/math; very low API cost |
| Qwen 2.5 (Alibaba) | Open weights, strong CN/EN | Common in China ecosystem |
What happens at each stage, how it is done, and how we evaluate
| Model | Year | Params | Key change |
|---|---|---|---|
| GPT-1 | 2018 | 117M | First generative pre-trained Transformer |
| GPT-2 | 2019 | 1.5B | Stronger generation |
| GPT-3 | 2020 | 175B | Few-shot reasoning emerges |
| ChatGPT | 2022 | ~175B | SFT + RLHF = conversational assistant |
| GPT-4 | 2023 | — | Multimodal in/out; 25K+ word replies; safer & more factual vs 3.5 |
| GPT-4o | May 2024 | — | Text + audio + image; 128K context; knowledge Oct 2023 |
| Stage | Output | User-visible behavior |
|---|---|---|
| Pretrain | Base LLM | Continues text; ignores instructions |
| SFT | Instruction model | Follows questions, chat format |
| RLHF | Aligned model | More helpful, safer, better style |
| Agent FT | Agent model | Calls tools, multi-step tasks |
Every position: predict next token from all previous tokens. Wrong prediction updates all weights via backprop.
| Source | Role | Share |
|---|---|---|
| Web crawl | Scale, diversity | 60-80% |
| Books | Long-form coherence | 5-10% |
| Wikipedia | Factual knowledge | 3-5% |
| Code | Programming | 5-15% |
| Metric | Meaning | Target |
|---|---|---|
| Perplexity (PPL) | Model surprise on validation text | Lower is better |
| Val loss | Negative log-likelihood curve | Smooth decrease |
| LAMBADA / HellaSwag | Zero-shot benchmarks | Higher accuracy |
Teach the model to follow instructions
Q: "What is 2+2?"
May continue: "...and why math matters..."
Q: "What is 2+2?"
Answer: "2+2 equals 4."
<|user|> What is the capital of France? <|assistant|> The capital of France is Paris.
| Method | Trains | GPU need | Use when |
|---|---|---|---|
| Full FT | All params | Very high | Max quality, big budget |
| LoRA | Low-rank adapters (~0.1% params) | Low | Alpaca, most open FT |
| QLoRA | LoRA on 4-bit base | 1x 24GB GPU | Consumer hardware |
| Benchmark | Tests |
|---|---|
| MMLU | 57-subject multiple choice knowledge |
| MT-Bench / AlpacaEval | Multi-turn quality (GPT-4 as judge) |
| Human side-by-side | Win rate A vs B |
| Format compliance | JSON / length / structure adherence |
Ouyang et al. 2022
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.
| Type | How |
|---|---|
| Human eval | Side-by-side win rate vs SFT baseline |
| Reward model score | Average RM on test prompts |
| Safety red-teaming | Adversarial prompts, refusal rate |
| TruthfulQA | Hallucination / factuality |
| Chatbot Arena Elo | Crowdsourced preference ranking |
| Stage | How (concrete) | Evaluation |
|---|---|---|
| Tool Learning | Curate (prompt, tool_call JSON) pairs; function schema in prompt | Tool call accuracy, BFCL benchmark |
| Agent FT | ReAct trajectories: Thought, Action, Observation | Task success rate, SWE-bench |
| Long-context | RoPE scaling, continue train on long docs | Needle-in-haystack, RULER |
| Memory Align | When to save/recall user facts | Multi-session recall accuracy |
| Stage | Automatic | Human | Production |
|---|---|---|---|
| Pretrain | PPL, val loss | Sample continuations | Train curves, GPU util |
| SFT | MMLU, CE loss | MT-Bench, side-by-side | Instruction follow rate |
| RLHF | RM score, TruthfulQA | Win rate, red team | Thumbs up/down |
| Agent | Task success, tool accuracy | End-to-end completion | Badcase replay |
The brain still needs arms, legs, and memory
Each chat is a fresh start. Need Memory system.
Only emits tokens. Need Tools (API, code, DB).
"Do market analysis" fails in one shot. Need Planning.
Blind to real world. Need Environment feedback.
Behavior training, not just prompts
Path: ③ Agent → ④ Retrieval → ⑤ LangChain/LangGraph → ⑥ MCP/A2A → ⑦ OpenClaw → ⑧ Multi-agent.
Context Engineering
AI Coding Agent needs in one window:
Context window (128k tokens)
Vector DB + user profile DB
Implementation: ⑤ SqliteSaver + Store · ⑧ Multi-agent (course path, not this appendix number).
Real-world domains beyond chat
| Domain | How LLM is used | Examples / models |
|---|---|---|
| Customer support | Answer inquiries, troubleshoot, conversational FAQ | Chatbot + RAG on product docs |
| Content generation | Articles, blogs, social posts, product copy | GPT-4o, Claude; human edit required |
| Recommendations | Analyze preferences, personalized suggestions | Embedding + LLM ranking |
| Healthcare | Info extraction, advice, mental health chat, report simplification | Med-PaLM, PubMedQA (not a doctor!) |
| Virtual assistants | Task execution, personalized responses | Siri successor pattern: LLM + tools |
| Education | Explain concepts, answer student questions, tutoring | SFT on pedagogical data |
| Finance | Sentiment, NER, numerical claim detection, reasoning | BloombergGPT, FinGPT |
| Law | Research assistant, draft review | GPT-4 scored top 10% on bar exam |
| Civil engineering (course context) | Report drafting, code/regulation Q&A, schedule analysis | LLM + RAG on project docs + BIM data |
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).
Frontier models compared — specs from official docs; benchmarks vary by task
| Model | Vendor | Architecture | Context | Modal | Open? | Strengths |
|---|---|---|---|---|---|---|
| GPT-4o | OpenAI | Closed | 128K | Text + image + audio | API only | Multimodal, ecosystem, tool use, reliability |
| GPT-4 | OpenAI | Closed | 128K | Text + image | API only | Longer answers, safer, more factual vs 3.5 |
| DeepSeek-V3 | DeepSeek | 671B MoE (37B active) | 128K | Text | MIT open weights | Code, math, cost (~10x cheaper than GPT-4o API) |
| DeepSeek-R1 | DeepSeek | RL-trained reasoning | 128K | Text | Open | Chain-of-thought math/reasoning; slower, verbose |
| Claude 3.5 Sonnet | Anthropic | Closed | 200K | Text + image | API only | Long documents, coding, safety-focused |
| Llama 3.2 | Meta | 1B-90B dense | 128K | Text (+ vision 11B/90B) | Open | Self-host, fine-tune, on-device |
| ChatGLM | Zhipu / Tsinghua | 6B+ | 8K-128K | Text + image | Open (academic) | Chinese-English bilingual |
| Qwen 2.5 | Alibaba | 0.5B-72B | 128K | Text (+ vision variants) | Open | CN/EN, coding, local deploy |
| Scenario | Recommended | Why |
|---|---|---|
| Multimodal app (voice + image) | GPT-4o | Native audio/image; mature API |
| High-volume text API, cost-sensitive | DeepSeek-V3 | Strong benchmarks, open weights, low price |
| Hard math / logic proofs | DeepSeek-R1 or o-series | RL reasoning training; shows CoT |
| Self-host / fine-tune on private data | Llama 3.2 / Qwen / DeepSeek | Open weights, no vendor lock-in |
| 100-page document analysis | Claude 3.5 (200K) | Larger advertised context |
| Chinese bilingual assistant | ChatGLM / Qwen | Strong CN/EN bilingual |
| Agent with tools + memory | Any frontier + your stack | Model is brain; RAG/tools matter more than small benchmark gaps |
| Benchmark | Tests | GPT-4o ~ | DeepSeek-V3 ~ | DeepSeek-R1 ~ |
|---|---|---|---|---|
| MMLU | General knowledge | ~88% | ~88% | ~90% |
| HumanEval | Code generation | ~90% | ~82-90% | Strong |
| MATH | Math reasoning | Good | ~90% | ~97% (specialized) |
Benchmarks shift with each model version. Use as rough guide; always eval on your task.
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.
| Boundary | What happens | Mitigation |
|---|---|---|
| Knowledge cutoff | GPT-4o trained through Oct 2023; unaware of 2024+ events | RAG, web search tool, newer model |
| Hallucination | Confident but false facts, fake citations, wrong numbers | RAG + cite sources, human review, lower temperature |
| Context vs effective context | Advertised 128K-200K, but accuracy drops long before limit (2025 research: MECW often << advertised) | Chunk + retrieve; do not dump entire repo blindly |
| No real-world action | Can only emit text unless given tools | Agent + APIs + code execution |
| Math / logic edge cases | Fail on multi-step arithmetic, constraint puzzles without CoT | Calculator tool, R1/o-series, verify with code |
| Privacy / security | Cloud API may log prompts; model may leak training patterns | Self-host open model, PII filtering, enterprise API |
| Consistency | Same question, different runs → different answers (sampling) | temperature=0, structured output, caching |
| Closed (GPT-4o, Claude) | Open (DeepSeek, Llama, Qwen) | |
|---|---|---|
| Transparency | Black box weights | Inspect / fine-tune weights |
| Cost at scale | Higher API fees | Self-host can be cheaper |
| Multimodal | GPT-4o native audio/image | Most open models text-first |
| Compliance | Vendor handles infra | You own data residency |
| Peak capability | Often leads on general tasks | DeepSeek-R1 competitive on reasoning |
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.
LLM is the brain. Agent is the whole person.