teaching_llm_applications

MSc Course: Large Language Models — Internals and Applications

An 18-week masters-level course on the internals of large language models and their real-world applications. The course combines rigorous theory with hands-on Python practicals, culminating in a group project.


Course Overview

This course takes students from first principles through to deploying LLM-powered applications. The first half focuses on internals (tokenisation, embeddings, attention, transformers, pre-training, fine-tuning). The second half focuses on applications (RAG, agents, tool use, evaluation, safety, healthcare AI, multimodal models). Week 13 provides a dedicated deep dive into Reinforcement Learning from Human Feedback (RLHF), covering the full mathematical derivation, PPO, DPO, reward hacking, Constitutional AI, and process reward models. Week 14 covers mechanistic interpretability (superposition, sparse autoencoders, circuits, the logit lens, grokking, knowledge editing). Week 15 is a dedicated deep dive into evaluation (evals): the full evaluation stack from automatic metrics through human evaluation, LLM-as-judge, benchmark design, red-teaming, safety evals, and evaluation for deployed LLM applications. Week 16 provides a deep dive into Direct Preference Optimisation (DPO): the full mathematical derivation from the RLHF objective, the gradient interpretation, practical implementation, failure modes (likelihood displacement, over-optimisation, distribution shift), and a survey of variants including IPO, KTO, SimPO, and ORPO. Week 17 covers efficiency in attention and alternative architectures: the quadratic cost of full attention, sparse attention patterns (sliding window, BigBird), FlashAttention (tiling and online softmax), linear attention approximations (Performer, RWKV), state space models (S4, Mamba), grouped-query attention, and hybrid Mamba/transformer architectures. Week 18 is a short, practical primer on reinforcement learning — just enough RL intuition (policies, rewards, REINFORCE, baselines) to understand why PPO, DPO, and GRPO are shaped the way they are.

Each week has:


Directory Structure

teaching_llm_applications/
├── README.md                        ← this file
├── requirements.txt                 ← Python dependencies
├── materials/
│   ├── week01_intro_and_history.md
│   ├── week02_tokenisation.md
│   ├── week03_embeddings.md
│   ├── week04_attention.md
│   ├── week05_transformer_architecture.md
│   ├── week06_pretraining_and_scaling.md
│   ├── week07_finetuning_and_rlhf.md
│   ├── week08_prompting_and_context_engineering.md
│   ├── week09_rag_and_retrieval.md
│   ├── week10_agents_and_tool_use.md
│   ├── week11_evaluation_safety_ethics.md
│   ├── week12_applications_and_project.md
│   ├── week13_rlhf_deep_dive.md
│   ├── week14_mechanistic_interpretability.md
│   ├── week15_evals.md
│   ├── week16_dpo.md
│   ├── week17_efficiency_attention.md
│   └── week18_intro_to_rl.md
└── practicals/
    ├── week01_practical.py
    ├── week02_practical.py
    ├── week03_practical.py
    ├── week04_practical.py
    ├── week05_practical.py
    ├── week06_practical.py
    ├── week07_practical.py
    ├── week08_practical.py
    ├── week09_practical.py
    ├── week10_practical.py
    ├── week11_practical.py
    ├── week12_practical.py
    ├── week13_practical.py
    ├── week14_practical.py
    ├── week15_practical.py
    ├── week16_practical.py
    ├── week17_practical.py
    └── week18_practical.py

Week-by-Week Plan

Week Topic Lecture Notes Practical
1 Introduction and History of LLMs materials/week01_intro_and_history.md practicals/week01_practical.py
2 Tokenisation materials/week02_tokenisation.md practicals/week02_practical.py
3 Embeddings and Representations materials/week03_embeddings.md practicals/week03_practical.py
4 The Attention Mechanism materials/week04_attention.md practicals/week04_practical.py
5 Transformer Architecture materials/week05_transformer_architecture.md practicals/week05_practical.py
6 Pre-training and Scaling Laws materials/week06_pretraining_and_scaling.md practicals/week06_practical.py
7 Fine-tuning and RLHF (overview) materials/week07_finetuning_and_rlhf.md practicals/week07_practical.py
8 Prompting and Context Engineering materials/week08_prompting_and_context_engineering.md practicals/week08_practical.py
9 Retrieval-Augmented Generation (RAG) materials/week09_rag_and_retrieval.md practicals/week09_practical.py
10 Agents and Tool Use materials/week10_agents_and_tool_use.md practicals/week10_practical.py
11 Evaluation, Safety, and Ethics materials/week11_evaluation_safety_ethics.md practicals/week11_practical.py
12 Applications and Final Project materials/week12_applications_and_project.md practicals/week12_practical.py
13 RLHF: Deep Dive materials/week13_rlhf_deep_dive.md practicals/week13_practical.py
14 Mechanistic Interpretability materials/week14_mechanistic_interpretability.md practicals/week14_practical.py
15 Evals: Evaluating LLMs materials/week15_evals.md practicals/week15_practical.py
16 Direct Preference Optimisation (DPO) materials/week16_dpo.md practicals/week16_practical.py
17 Efficiency: Attention Variants & Architectures materials/week17_efficiency_attention.md practicals/week17_practical.py
18 Introduction to Reinforcement Learning materials/week18_intro_to_rl.md practicals/week18_practical.py

Lecture Notes

Part 1 — Internals

Part 2 — Applications

Part 3 — Advanced Topics


Guest Lectures

Practitioner and research perspectives complement the core weekly material. See materials/guest_lectures.md for full details on each speaker, talk overviews, suggested background reading, and guidance on how to prepare questions.

Speaker Topic Relevant weeks
Cole Robertson Speech, language, and LLMs in industry — real-time spoken dialogue, ASR + LLM pipelines, startup deployment 1, 8, 12
Glasgow Startup (TBC) LLMs for real-world applications — prototyping, fine-tuning vs RAG vs prompting, evaluation in the wild 7, 8, 9, 11, 12

Practicals

All practicals are self-contained Python scripts with inline comments. Run with:

python practicals/weekNN_practical.py
Practical What you build
Week 1 Query GPT-2, inspect next-token probabilities, visualise top-k predictions, compare temperatures, compute perplexity
Week 2 Compare tokenisers (tiktoken, BERT, GPT-2 HF), train BPE from scratch, visualise token boundaries, estimate API cost
Week 3 Sentence embeddings, cosine similarity matrix, semantic search, PCA / t-SNE / UMAP visualisation, sinusoidal positional encoding
Week 4 Scaled dot-product attention (NumPy), causal masked attention, multi-head attention (PyTorch), extract real BERT attention weights
Week 5 Complete decoder-only Transformer from scratch, train on Shakespeare, plot loss curves, generate text at multiple temperatures
Week 6 Scaling law experiment: train models of 5 different sizes, plot loss vs parameters and vs FLOPs, Chinchilla analysis
Week 7 LoRA from scratch, fine-tune a toy LM, Bradley-Terry reward model, DPO loss demonstration
Week 8 Zero-shot vs few-shot vs CoT comparison, self-consistency decoding, structured extraction, prompt injection demo
Week 9 Full RAG pipeline (chunk → embed → FAISS index → retrieve → generate), BM25 hybrid retrieval, faithfulness evaluation
Week 10 ReAct agent from scratch, tool calling loop, two-agent orchestrator-specialist system, success rate evaluation
Week 11 ROUGE / BERTScore / LLM-as-judge evaluation, hallucination rate measurement, gender bias probing, jailbreak attempts
Week 12 End-to-end LLM application (RAG + agent + Streamlit UI), systematic evaluation on 20 queries
Week 13 Full RLHF pipeline from scratch: synthetic preference dataset, Bradley-Terry reward model, PPO actor-critic update loop, DPO training, reward hacking detection; RM score / KL divergence / win rate plots
Week 14 Mechanistic interpretability: logit lens across GPT-2 layers; activation patching heatmap (IOI heads); linear probe for verb detection per layer; sparse autoencoder trained on MLP activations with feature inspection; grokking on modular arithmetic
Week 15 Evals: BLEU/ROUGE/BERTScore/MAUVE comparison; LLM-as-judge pipeline with position-bias mitigation (swap A/B); position bias measurement; sycophancy probing; mini red-team across three jailbreak categories; factual QA eval with McNemar significance testing
Week 16 DPO from scratch: implement DPO, IPO, and SimPO losses; train a toy LM on synthetic preferences; monitor chosen/rejected rewards, margin, accuracy, and KL; demonstrate likelihood displacement; two-iteration online DPO; comparison plots across all three methods
Week 17 Efficiency: time/memory scaling of naive vs tiled (FlashAttention-style) vs sliding-window attention; S4-style SSM from scratch — verify recurrent == convolutional form via FFT; Mamba selective SSM with input-dependent Δ; KV-cache memory comparison (MHA vs GQA vs SSM) across sequence lengths up to 262k tokens; output quality analysis of sliding window at varying window sizes
Week 18 REINFORCE basics: a minimal policy-gradient agent on a toy bandit, trained with and without a baseline, showing the variance reduction directly in a plot

Learning Objectives

The objectives are organised by theme, expressed using measurable action verbs at masters level, and grounded in Bloom’s revised taxonomy. They map directly to the weekly topics and assessments.

1. Foundations and History (Weeks 1–2)

By the end of Week 2, students will be able to:

2. Representations and Embeddings (Week 3)

By the end of Week 3, students will be able to:

3. The Attention Mechanism (Week 4)

By the end of Week 4, students will be able to:

4. Transformer Architecture (Week 5)

By the end of Week 5, students will be able to:

5. Pre-training and Scaling Laws (Week 6)

By the end of Week 6, students will be able to:

6. Fine-tuning and Alignment (Week 7)

By the end of Week 7, students will be able to:

7. Prompting and Context Engineering (Week 8)

By the end of Week 8, students will be able to:

8. Retrieval-Augmented Generation (Week 9)

By the end of Week 9, students will be able to:

9. Agents and Tool Use (Week 10)

By the end of Week 10, students will be able to:

10. Evaluation, Safety, and Ethics (Week 11)

By the end of Week 11, students will be able to:

11. Applications and Deployment (Week 12)

By the end of Week 12, students will be able to:

12. RLHF: Deep Dive (Week 13)

By the end of Week 13, students will be able to:

13. Direct Preference Optimisation (Week 16)

By the end of Week 16, students will be able to:

14. Introduction to Reinforcement Learning (Week 18)

By the end of Week 18, students will be able to:


Mapping to Bloom’s Revised Taxonomy

The objectives above span all six cognitive levels:

Level Verbs used Examples from this course
Remember Define, identify, list, name Define token, perplexity, LoRA rank, KV cache, Bradley-Terry model
Understand Explain, describe, distinguish, summarise Explain causal masking, Chinchilla scaling, reward hacking, KL penalty
Apply Implement, apply, calculate, build Implement attention, LoRA, RAG pipeline, PPO loop, DPO loss
Analyse Analyse, compare, interpret, diagnose Interpret attention weights, diagnose reward hacking, compare PPO vs DPO
Evaluate Evaluate, assess, justify, critique Assess alignment strategies, critique deployment proposals, score with LLM-as-judge
Create Design, construct, assemble, produce Design multi-agent system, build evaluated LLM application, implement full RLHF pipeline

Assessment

Component Weight Details
Weekly practicals (submitted as scripts/notebooks) 30% 18 short submissions, one per week
Mid-term written assignment (Week 6) 20% 1500-word essay on scaling laws or fine-tuning
Final group project 50% Working LLM application + 10-page report + live demo

Prerequisites

No prior NLP experience required.


Setup

python -m venv .venv
source .venv/bin/activate       # Windows: .venv\Scripts\activate
pip install -r requirements.txt

Create a .env file with your API keys:

OPENAI_API_KEY=<your-openai-key>
ANTHROPIC_API_KEY=<your-anthropic-key>
HF_TOKEN=<your-huggingface-token>

Run any practical:

python practicals/week01_practical.py

External Resources

Key Papers

Paper Link
Vaswani et al. (2017) — Attention is All You Need https://arxiv.org/abs/1706.03762
Brown et al. (2020) — GPT-3 https://arxiv.org/abs/2005.14165
Kaplan et al. (2020) — Scaling Laws https://arxiv.org/abs/2001.08361
Hoffmann et al. (2022) — Chinchilla https://arxiv.org/abs/2203.15556
Wei et al. (2022) — Emergent Abilities https://arxiv.org/abs/2206.07682
Wei et al. (2022) — Chain-of-Thought https://arxiv.org/abs/2201.11903
Hu et al. (2022) — LoRA https://arxiv.org/abs/2106.09685
Christiano et al. (2017) — Deep RL from Human Preferences https://arxiv.org/abs/1706.03741
Ouyang et al. (2022) — InstructGPT / RLHF https://arxiv.org/abs/2203.02155
Schulman et al. (2017) — Proximal Policy Optimisation https://arxiv.org/abs/1707.06347
Bai et al. (2022) — Constitutional AI https://arxiv.org/abs/2212.08073
Rafailov et al. (2023) — DPO https://arxiv.org/abs/2305.18290
Lightman et al. (2023) — Let’s Verify Step by Step (PRMs) https://arxiv.org/abs/2305.20050
Skalse et al. (2022) — Defining and Characterizing Reward Hacking https://arxiv.org/abs/2209.13085
Lewis et al. (2020) — RAG https://arxiv.org/abs/2005.11401
Yao et al. (2022) — ReAct https://arxiv.org/abs/2210.03629
Dettmers et al. (2023) — QLoRA https://arxiv.org/abs/2305.14314
DeepSeek-R1 (2025) — Incentivising Reasoning via RL (GRPO) https://arxiv.org/abs/2501.12948
Azar et al. (2023) — IPO https://arxiv.org/abs/2310.12036
Ethayarajh et al. (2024) — KTO https://arxiv.org/abs/2402.01306
Meng et al. (2024) — SimPO https://arxiv.org/abs/2405.14734
Hong et al. (2024) — ORPO https://arxiv.org/abs/2403.07691
Rafailov et al. (2024) — Scaling Laws for DPO Overoptimisation https://arxiv.org/abs/2406.02900
Dao et al. (2022) — FlashAttention https://arxiv.org/abs/2205.14135
Dao (2023) — FlashAttention-2 https://arxiv.org/abs/2307.08691
Beltagy et al. (2020) — Longformer https://arxiv.org/abs/2004.05150
Zaheer et al. (2020) — BigBird https://arxiv.org/abs/2007.14062
Choromanski et al. (2021) — Performers https://arxiv.org/abs/2009.14794
Peng et al. (2023) — RWKV https://arxiv.org/abs/2305.13048
Gu et al. (2022) — S4 https://arxiv.org/abs/2111.00396
Gu and Dao (2023) — Mamba https://arxiv.org/abs/2312.00752
Ainslie et al. (2023) — GQA https://arxiv.org/abs/2305.13245
Team AI21 (2024) — Jamba https://arxiv.org/abs/2403.19887
Williams (1992) — REINFORCE https://link.springer.com/article/10.1007/BF00992696

Additional material

Acknowledgements and courses for inspiration

  1. Stanford CS324: Understanding and Developing Large Language Models — this is probably the best single Stanford reference for your purpose because it explicitly combines modeling, theory, ethics, and systems, and it is designed to give hands-on experience with massive language models. (Stanford CRFM)

  2. Stanford CS224N: Natural Language Processing with Deep Learning — a very strong backbone course. The current offering explicitly covers deep learning for NLP and LLMs, and its assessment structure is especially useful for inspiration: one assignment each on word vectors, neural-network foundations, self-attention and Transformers, and LLM benchmarking/evaluation. (Stanford University)

  3. Stanford CS25: Transformers United V6 — this is less of a core methods course and more of a transformer seminar, but it is valuable if you want to see how Stanford frames cutting-edge transformer topics and guest talks from major researchers. It is especially useful for a reading-seminar or guest-lecture component. (Stanford University)

  4. UC Berkeley CS 194/294-267: Understanding Large Language Models: Foundations and Safety — very useful if you want to balance internals with interpretability, scaling laws, robustness, alignment, privacy, watermarking, agency, reasoning, and evaluation. It is a strong model for a course that treats LLMs as both a technical and safety-relevant system. (rdi.berkeley.edu)

  5. UC Berkeley INFO 290: Applied Generative AI and Large Language Models — this is a good reference for the applied side of the syllabus: transformer architectures, prompt engineering, API integration, RAG, open-source models, fine-tuning, graph enhancements, and agentic technologies. (UC Berkeley School of Information)

  6. MIT OCW 6.7960 Deep Learning, Lecture 8: Architectures: Transformers — a clean, compact lecture resource for explaining the core internals: tokens, attention, and positional codes, with a nice framing that connects transformers to other architectures. (MIT OpenCourseWare)

  7. MIT OCW 15.773, Lecture 10: Adapting LLMs with Parameter-Efficient Fine-Tuning — useful for the post-pretraining part of the course, especially instruction tuning and adapting base models. (MIT OpenCourseWare)

A sensible design pattern would be to use CS224N for the course spine, CS324 for the “LLM systems + theory” lens, MIT’s transformer lecture for the internals exposition, and Berkeley’s courses for safety, interpretability, and application modules. (Stanford University)

Contact

Soumya Banerjee