MACHINE LEARNING · UNIVERSITY OF VIRGINIA
Transformers
Part 1
ML @ UVA · FALL 2026
Lecture by Anmol Thapa
MLATUVA.ORG
Two Lectures, Two Workshops
2
LECTURE 1
today
01
Motivation
02
Word embeddings
03
Attention
04
Self-attention
LECTURE 2
next week
05
Multi-head attention
06
Transformer architecture
07
Common models
Motivation
3
SECTION 01
Why sequence models needed a rethink
01
Recap: RNNs and LSTMs
4
An RNN reads one token at a time, carrying a hidden state forward from step to step.
hidden state
input
h1
x1
h2
x2
h3
x3
h4
x4
ŷ
the problem | plain RNN | LSTM, 1997 |
Forgetting early tokens | | FIXED. Gates choose what to keep, update or forget. |
Training speed | Step 5 waits for step 4, so nothing runs in parallel. | NOT FIXED. Still one step at a time. |
The translation handoff | The whole input is squeezed into one fixed-size vector. | NOT FIXED. Still one vector, and this is the one attention fixes. |
Transformers drop the recurrence altogether, which clears all three at once.
Enter the Transformer
5
Introduced by Google researchers in 2017, with translation as the first goal.
1
Parallel training
No step waits for the one before it, so training can use huge amounts of data on modern GPUs.
2
All tokens at once
A Transformer processes every token together. An RNN has to walk through them in order.
3
Built for translation
The original paper targeted machine translation. The design then spread to nearly every language task.
Word Embeddings
6
SECTION 02
Turning text into vectors
02
Transformers Do Not Read Text
7
Raw text
what you type
Tokenizer
splits text into pieces
Token IDs
one integer per piece
Embedding layer
looks up a vector per ID
Vectors
lists of numbers
Tokenizers and embedders are two separate stages. The tokenizer outputs token IDs, and those IDs are what the embedding layer takes in.
Tokenization
8
EXAMPLE
Transformer
Transform
##er
“##” marks a piece that continues the one before it
Live Tokenizer
9
Common words
one token each
Emoji and some characters
split into several pieces
Long digit strings
grouped into chunks
The Embedding Matrix
10
A token ID is just a column number. The lookup is pulling out that column.
Columns start random and are learned, so related tokens end up with related vectors.
Background Context: Weighted Sums
11
The weights are learned, and they can be positive or negative.
W
the learned weights, one row per output
y
the data coming out
x
the data going in, one number per input
n
how many inputs there are
Similar Vectors Point Similarly
12
Same direction means a high dot product. That is the number attention scores with.
Directions in Vector Space Carry Meaning
13
Real embeddings have thousands of dimensions and many directions of meaning.
Embedding Visualizer
14
each cluster is a group of related words
Problem: One Word, Many Meanings
15
A static embedding hands “model” the same vector in all three sentences.
The vectors are identical every time across context
Solution: Context-Aware Vectors
16
Attention lets a word’s meaning depend on the context
“model” on its own
[-0.05, 0.67,
-0.39, 0.44]
+ context
“model” in “A machine learning model”
[-0.09, -0.19, 0.35, 0.30]
“model” in “A fashion model”
[0.71, -0.22, 0.58, -0.33]
Attention
17
SECTION 03
Letting words look at each other
03
An Earlier Idea: Encoder and Decoder
18
The red car
Encoder
one vector
Decoder
El coche rojo
the same size however long the input was
Where One Vector Falls Short
19
Word order changes between languages, so output words do not line up with input words one to one.
The
red
car
El
coche
rojo
The
black
cat
ate
the
mouse
Le
chat
noir
a mangé
la
souris
Adjectives come before the noun in English and after it in Spanish and French. A decoder holding only one summary vector has to guess which input word each output word came from.
Transformers Keep One Vector Per Token
20
Let the Decoder Look At Neighbors
21
rojo
The
red
car
thicker line means more attention
Tokens “Talk” To Each Other
22
How Vectors Get Context
23
vⱼ
the vector of word j
aᵢⱼ
how much word i draws from word j
zᵢ
the new vector for word i
n
how many words in the sentence
The Attention Pattern
24
Attention is directional: “model” draws 0.40 from “machine”, but “machine” draws only 0.20 back.
Summary So Far
25
01
Motivation
02
Word Embeddings
03
Attention
Next: Where Do The Scores Come From?
26
So far, the weights have been given. Self-attention is how a model works them out.
1
What is each word looking for?
2
How does it score every other word?
3
How do the scores become a new vector?
Self-attention answers all three by using the dot product and the softmax.
Self-Attention
27
SECTION 04
Where the weights come from
04
Background Context: Softmax
28
Softmax turns any list of scores into weights that add to 1, and keeps their order intact.
Exponentiate so every entry is positive, then divide by the total so they add to 1.
Token Position Matters
29
Attention compares every token with every other and knows nothing about order.
sentence 1
the
cat
ate
the
mouse
sentence 2
the
mouse
ate
the
cat
Same bag of tokens, opposite meaning. Without position information a Transformer cannot tell these apart.
The embedding that reaches attention is the token's own vector plus information about where it sits.
token embedding
+
position information
what attention sees
Three Jobs for Every Token
30
Attention is a lookup on the semantic meaning of a token, devised by three parts:
query
What am I looking for?
“model” is a noun whose sense is unclear, so it looks for words that pin it down.
key
What do I advertise?
“machine” advertises that it is a modifier sitting right before a noun.
value
What do I hand over?
If chosen, “machine” passes on the content that shifts “model” toward computing.
A word matches its query against everyone's keys, then collects the values of whichever words matched best.
Three Jobs for Every Token
31
Start with what a token needs from the rest of the sentence.
A query is a question: what this word still has to find out.
“model” cannot tell on its own which kind of model it is, so its query goes looking.
Three Jobs for Every Token
32
Every other word gets a chance to answer, so the query meets all four keys.
A key is what a word advertises. Each of those comparisons is a dot product.
Three Jobs for Every Token
33
Matching is only half of it. Whoever answered now has to hand something over.
A value is what a word contributes, which is not the same as what it means.
Query, Key and Value
34
Before any scoring, every token is projected three times, once for each job.
The matrices are fixed once training ends. The vectors they produce change with every sentence.
In a real model the number of dimensions in q and k is much smaller than the embedding.
Why Three Projections?
35
Three matrices is a lot of machinery. Why not dot the embeddings and be done?
As plain words, “model” and “machine” have almost nothing in common. Yet “machine” is one of the most useful word in the sentence for settling what “model” means.
Why Three Projections?
36
Project them first, and the same two words give a completely different answer.
The matrices let the model learn what counts as relevant, which is not what counts as similar.
Why Three Projections?
37
Unlike similarity, this answer depends on which of the two is doing the asking.
2.8 one way, 0.70 the other. One vector per word could never do that: a dot product is symmetric, while attention is directional.
Self-Attention In 4 Steps
38
1
Score
Dot every query
against every key
2
Scale
3
Softmax
Turn scores into
weights that add to 1
4
Blend
Weighted sum of
the value vectors
Step 1 of 4: Score
39
Start with the question: the query belonging to “model”.
Two of its four entries are zero. Hold on to that, it decides everything below.
Step 1 of 4: Score
40
Now the key for “machine”, the word we are scoring it against.
A dot product pairs the two vectors up entry by entry. That is what the crosses mean.
Step 1 of 4: Score
41
Multiply each pair.
Where the query held a zero the product is zero, whatever the key was offering there.
Step 1 of 4: Score
42
Add the four products and the score falls out.
2.8, which is just 1.5 + 1.3. One number for how well “machine” answers what “model” asked.
Step 1 of 4: Score Every Key
43
Same query, different key. Run it against “A”.
0.5 and −0.5 cancel. “A” offers nothing on the two entries the query asked about.
Step 1 of 4: Score Every Key
44
“machine” next, the one we just did the long way.
Both entries positive, so the two terms add instead of cancelling.
Step 1 of 4: Score Every Key
45
Then “learning”.
The same score again. “model” wants these two words about equally.
Step 1 of 4: Score Every Key
46
And “model” against its own key.
−0.7 and 0.7 cancel. A word's own key is not automatically what its own query wants.
Step 2 of 4: Scale
47
One adjustment before the scores can become weights: divide them all by √dₖ.
Step 2 of 4: Scale
48
Why bother scaling?
If unscaled, softmax can collapse onto the single highest score and the gradients nearly vanish with it.
Step 3 of 4: Softmax
49
The scaled scores still are not weights.
They can be negative, and nothing makes them add up to anything in particular.
Attention needs the opposite: all positive, and summing to exactly 1.
Step 3 of 4: Softmax
50
Raise e to the power of each one.
e to any power is positive, so every entry is now above zero, and the bigger scores stay bigger.
Step 3 of 4: Softmax
51
Then divide each by the total of all four.
1.00 + 4.06 + 4.06 + 1.00 = 10.11, so each entry over 10.11 gives weights that sum to 1.
These four are the “model” row of the attention pattern from the Attention section.
Step 4 of 4: Blend the Values
52
The weights say how much of each word to take. Now take it, from the value vectors.
Worked Example
53
“A” is a determiner. Its query matches its own key best, so most of its weight stays at home.
Worked Example
54
“machine” leans hardest on “learning”, the word it forms a phrase with.
Worked Example
55
And “learning” leans back on “machine”, at 0.38. The attention runs both ways here.
The Full Attention Pattern
56
Four queries, four rows. This grid is the whole attention step for this sentence.
“model” draws 0.40 from “machine”, but “machine” draws only 0.20 from “model”. Attention is directional.
Query, Key, Value
57
Stack all the queries into one matrix and all the keys into another.
This is why Transformers parallelise. One matrix multiply replaces the loop over every pair of words.
The Attention Formula
58
Every piece of that is something you just computed by hand.
stage | what it is | shape |
X | input embeddings, with position | |
Q, K, V | the three projections | |
Q Kᵀ | raw scores, every pair | n × n |
softmax(·/√dₖ) | the attention pattern | n × n |
· V | the new vectors | |
Where n is the number of tokens.
What Is Actually Learned
59
The most common misreading of this whole section is worth heading off directly.
LEARNED
NOT LEARNED
Example: Resolving a Pronoun
60
A sentence where the answer is obvious to you and not at all obvious to a bag of vectors.
Cornelius
taught
Marcus
ML
,
and
he
was
proud
strongest link
a plausible competitor
Summary: Self-Attention
61
01
Three Projections
02
Four Steps
03
Learned vs Computed