This first lecture sets the scene. We ask: what is a language model, why has it become so powerful, and how did we get here?
Just a quick, gentle correction on the vector math before you present it: the famous analogy formula is actually $\vec{w}{king} - \vec{w}{man} + \vec{w}{woman} \approx \vec{w}{queen}$, but you have the exact right idea!
| Time (Mins) | Topic | Key Concepts |
|---|---|---|
| 00 - 15 | The Limits of Symbolic AI | GOFAI, syntax vs. semantics, the scaling problem. |
| 15 - 30 | The Deep Learning Revolution | Connectionism, massive text associations, learning without explicit rules. |
| 30 - 60 | Embeddings & Vector Spaces | 3Blue1Brown visual concepts, high-dimensional arrays. |
| 60 - 80 | Semantic Mathematics | Vector arithmetic, how meaning is encoded in distance. |
| 80 - 120 | Python Practical Session | Hands-on with word vectors using Gensim. |
Context is Everything: Explain the foundational linguistic theory by J.R. Firth: “You shall know a word by the company it keeps.” Deep learning models look at a word and learn its meaning based on the words that frequently surround it.
Bag of words model: how that fails to capture context.
Concept 🧩 🚀 Context is everything! Bag of words model cannot capture context
Enter LLMs
transformers model long-range dependencies in text
Reading: Attention is all you need
Formula: $\vec{w}{king} - \vec{w}{man} + \vec{w}{woman} \approx \vec{w}{queen}$
For the practical, we will use gensim, a robust Python library for topic modeling and document similarity, to download a pre-trained set of GloVe (Global Vectors for Word Representation) embeddings.
Prerequisites: Have your students install the library by running
pip install gensimin their terminal or Jupyter Notebook.
import gensim.downloader as api
print("Downloading/Loading the word vector model... (This may take a minute or two)")
# We use a relatively small 50-dimensional model for speed in a classroom setting
model = api.load("glove-wiki-gigaword-50")
print("Model loaded successfully!\n")
# --- EXPERIMENT 1: Finding Similar Words ---
print("--- Experiment 1: Nearest Neighbors ---")
word = "computer"
print(f"Words most similar to '{word}':")
for similar_word, similarity_score in model.most_similar(word, topn=5):
# Formatting the score to 2 decimal places using standard Python formatting
print(f"- {similar_word} (Score: {similarity_score:.2f})")
print("\n")
# --- EXPERIMENT 2: Semantic Mathematics ---
# King - Man + Woman = ?
print("--- Experiment 2: Vector Arithmetic ---")
print("Equation: King - Man + Woman = ?")
# In Gensim, positive=[additions], negative=[subtractions]
result = model.most_similar(positive=['king', 'woman'], negative=['man'], topn=1)
print(f"Result: {result[0][0]} (Confidence: {result[0][1]:.2f})\n")
# --- EXPERIMENT 3: The Odd One Out ---
print("--- Experiment 3: Finding the Outlier ---")
word_list = ["breakfast", "cereal", "dinner", "lunch", "car"]
print(f"List: {word_list}")
outlier = model.doesnt_match(word_list)
print(f"The model thinks the odd one out is: '{outlier}'")
doctor - human + dog = vet). Warn them that it doesn’t always work perfectly, which opens up a great discussion on the biases and limitations of training data!
🎥 Stanford CME 295 course on tokenization and transformer intro
subword level tokenization

if too many tokens then sequence length increases (computational cost increases)
if too little, then hard to interpret embeddings
OOV (out of word vocabulary) could be possible for words
a word may not occur in training but appears in test (this may have to be marked as a special symbol)


how to represent tokens?
🤔 ❓ will one-hot encoding work?
🤔 all words will be equidistant from each other! Aardvark is equidistant from starship and anemone
this will not capture concepts
🔑🔐 we need a representation that will capture meaning and context
🔑🔐context captures meaning

🔑🔐tokens that have similar meanings should have similar values
🎥 Video (short) explaining how Aardvark and anemone get represented

Link and segue between unsupervised learning and PCAs (see diagram on last page) and polished diagram here and diagram here
🎥 Unsupervised learning is the first step towards LLMs: video by 3blue1brown
Interactive ipython notebook 📒 to understand embeddings and here
use a neural network to predict next token
if prediction not good, then update weights
🔑🔐 update embeddings also!

predict using softmax function
when do you stop?
hard to say: sometimes you have a budget and sometimes you look at how good you are at a downstream task (say chatbot or sentiment classification)

meaning of a sentence is encoded in hidden state
predict last word using every hidden state that came before
long range dependencies hard to model
enter transformers
Concept 🔑🔐 very long range context could be modelled using direct links
Concept 🔑🔐 this is the basic idea behing attention

in order to compute representation of teddy bear we will look at all words (direct links)
this is called self attention

Q, K, V
What other tokens is the query (teddy bear) similar to?
how similar query is to a key (and then take the corresponding value)
Attention computation
Attention can be computed using a simple formula
softmax of query and 🔑 key
multiply with value (V)
Concept 🧩 🚀💡🔑🔐 if less importance then small weight (V)
Concept 🧩 🚀💡🔑🔐 if more important then bigger weight (V)



Q, K and V are learnt
also see transfomers
encoder (left) and decoder (right) architecture

encoder will find meaningful embeddings (self-attention will apply)
self attention
then cross attention to predict next token
arrows from encoder
🤔❓ what does arrow from encoder to decoder represent? Q, K or V ?
it represents the query
Concept 🧩 🚀 _given the query _what are the words from the input that matter?
Concept 🧩 🚀 the 🎹 keys and values come from the encoder
Concept 🧩 🚀 masked atention is another kind of attention: what other tokens (that have already been looked at) can be useful in predicting the next token: do not look at tokens that have not been translated (masked)
Concept 🧩 🚀 self attention figure out what my embedding needs to be (by looking at everyone else)
no sense of order
so positional encodings
quick overview




⚠️ NOTE what does head mean?
when you compute attention, you make queries interact with keys and get corresponding values. But nothing prevents you doing that several times.
Concept 🧩 🚀💡 each time you do that, is a head
when you have several heads, you are allowing your model to learn different associations/meanings/embeddings



Concept 🧩 🚀💡🔑🔐 The dot product measures how much two vectors agree with each other, or how well they align


weighted sum of values
Attention map

since you have direct links (everything is connected), you lose position information
contrast to RNNs which had sequential connections
position specific embeddings
learnt?
can learn position embeddings till max (say 512). At inference time, if you get something beyond this, then you have a problem
versus hardcoded position embeddings (not learnt)


words that are close together should have similar embeddings
dot product of two vectors



why do I care about dot product? Because if I want to know how similar two embeddings are, I need dot product
if m = n then this quantity is maximal (vctors/embeddings are most similar)
high frequency
can be extended to any sequence length
added before attention (which is why we are doing all of this)
add bias in attention layer to reflect the fact that some tokens are more similar than others

in T5 this is learnt
ROPE Embeddings (Rotary Position Embeddings)
rotate Q and K by some angle that is a function of its position

multiply by rotation matrix
relative distance is captured in the rotation matrix


input and output add together and normalize
aid convergence and stability
Concept 🧩 🚀💡🔑🔐 some activations may have extreme values: model may struggle to learn weights. Bring activations in same range





what about softmax? there are some tricks
sliding window attention





A language model assigns a probability to a sequence of tokens (words, subwords, characters):
P(w_1, w_2, ..., w_n)
Equivalently, using the chain rule:
P(w_1, ..., w_n) = P(w_1) * P(w_2 | w_1) * P(w_3 | w_1, w_2) * ...
This is the autoregressive view: each token is predicted given all previous tokens.
| n-gram models: estimate P(w_t | w_{t-n+1}, …, w_{t-1}) using counts. |
| Year | Model | Organisation | Parameters |
|---|---|---|---|
| 2018 | GPT-1 | OpenAI | 117M |
| 2018 | BERT | 340M | |
| 2019 | GPT-2 | OpenAI | 1.5B |
| 2020 | GPT-3 | OpenAI | 175B |
| 2022 | ChatGPT / InstructGPT | OpenAI | ~175B |
| 2023 | LLaMA-2 | Meta | 7B–70B |
| 2024 | Llama-3, Mistral, Gemini, Claude | Meta/Mistral/Google/Anthropic | 7B–1T+ |
The core recipe: pre-train on massive text corpora (self-supervised), then fine-tune or prompt for downstream tasks.
Words that appear in similar contexts tend to have similar meanings. (Harris, 1954; Firth, 1957)
Training on next-token prediction forces the model to learn:
At sufficient scale, LLMs develop emergent abilities not present in smaller models:
Wei et al. (2022) document many such emergent abilities as a function of model size.
One of the most surprising properties: LLMs can perform new tasks just from examples in the prompt, without updating weights. This is called in-context learning (ICL).
Design decisions
Loss function
Optimizer
Initialization scale
Learning rate schedule
Regularization
Batch size
Assignment: BPE encoding and create model while doing Resource accounting
DGX B200
Operator fusion, flash attention
Minimize data movement principle
Shard memory: split data or split models, layers, sequences, etc.
| Domain | Example Application |
|---|---|
| Text generation | Creative writing, summarisation |
| Code | GitHub Copilot, code review |
| Q&A / search | RAG-based assistants |
| Healthcare | Clinical note summarisation, diagnostic support |
| Science | Hypothesis generation, literature review |
| Education | Tutoring, automated feedback |
| Agents | Web browsing, task automation |
(We cover this in depth in Weeks 4–5; here is a high-level sketch.)
Input tokens
│
▼
[Token Embedding + Positional Encoding]
│
▼
[Transformer Block × N]
┌──────────────────────────────────┐
│ Multi-Head Self-Attention │
│ + Add & Norm │
│ Feed-Forward Network │
│ + Add & Norm │
└──────────────────────────────────┘
│
▼
[Linear + Softmax → Probability over vocabulary]
See practicals/week01_practical.py: