1 of 61

MACHINE LEARNING · UNIVERSITY OF VIRGINIA

Transformers

Part 1

ML @ UVA · FALL 2026

Lecture by Anmol Thapa

MLATUVA.ORG

2 of 61

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

3 of 61

Motivation

3

SECTION 01

Why sequence models needed a rethink

01

4 of 61

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.

5 of 61

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.

6 of 61

Word Embeddings

6

SECTION 02

Turning text into vectors

02

7 of 61

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.

8 of 61

Tokenization

8

  • Before any vectors, text is split into tokens
  • Tokens are sub-word units, so a word can be one token or several
  • A fixed vocabulary can still handle rare or invented words by combining pieces
  • Common words usually stay whole

EXAMPLE

Transformer

Transform

##er

“##” marks a piece that continues the one before it

9 of 61

Live Tokenizer

9

Common words

one token each

Emoji and some characters

split into several pieces

Long digit strings

grouped into chunks

10 of 61

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.

11 of 61

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

12 of 61

Similar Vectors Point Similarly

12

Same direction means a high dot product. That is the number attention scores with.

13 of 61

Directions in Vector Space Carry Meaning

13

  • Think of each vector as a point in a very high dimensional space
  • Training pushes related words close together
  • It also lines up directions
  • A direction can stand for an idea, like plurality, on its own

Real embeddings have thousands of dimensions and many directions of meaning.

14 of 61

Embedding Visualizer

14

  • The Embedding Projector flattens high dimensional word vectors down to 2D or 3D so you can look at them
  • Each dot is a word, and words used in similar ways land near each other
  • Search for a word and look at its nearest neighbours

each cluster is a group of related words

15 of 61

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

16 of 61

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]

17 of 61

Attention

17

SECTION 03

Letting words look at each other

03

18 of 61

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

  • The encoder reads the whole input and squeezes it into one fixed-size vector
  • The decoder writes the output one word at a time, with only that vector to go on
  • This was the standard setup for translation, usually built out of RNNs or LSTMs

19 of 61

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.

20 of 61

Transformers Keep One Vector Per Token

20

  • An RNN squeezes the whole input into one fixed vector before the decoder sees anything
  • A Transformer keeps one vector per token, so nothing is thrown away up front
  • No recurrence either, so every token is handled at once

21 of 61

Let the Decoder Look At Neighbors

21

  • In 2014, researchers added attention to encoder-decoder models
  • Instead of one summary vector, the decoder can look at every input word
  • For each output word it leans on the input words that matter most for that word
  • Neural translation got good enough to beat the older statistical systems

rojo

The

red

car

thicker line means more attention

22 of 61

Tokens “Talk” To Each Other

22

  • A darker arc means that word matters more for the meaning
  • Grey vector is what goes in, orange is what comes out

23 of 61

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

24 of 61

The Attention Pattern

24

  • A row is one word rebuilding itself out of the sentence
  • A column is where that information is pulled from
  • Darker means more weight

Attention is directional: “model” draws 0.40 from “machine”, but “machine” draws only 0.20 back.

25 of 61

Summary So Far

25

01

Motivation

  • RNNs read one token at a time, so they are slow and they forget
  • Transformers take every token at once

02

Word Embeddings

  • A tokenizer splits the text, then an embedding matrix hands each token a vector
  • Directions in that space carry meaning

03

Attention

  • One fixed vector per word cannot mean two things at once
  • Attention rebuilds each word as a weighted blend of its neighbours

26 of 61

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.

27 of 61

Self-Attention

27

SECTION 04

Where the weights come from

04

28 of 61

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.

29 of 61

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

30 of 61

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.

31 of 61

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.

32 of 61

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.

33 of 61

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.

34 of 61

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.

35 of 61

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.

​

36 of 61

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.

37 of 61

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.

38 of 61

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

39 of 61

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.

40 of 61

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.

41 of 61

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.

42 of 61

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.

43 of 61

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.

44 of 61

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.

45 of 61

Step 1 of 4: Score Every Key

45

Then “learning”.

The same score again. “model” wants these two words about equally.

46 of 61

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.

47 of 61

Step 2 of 4: Scale

47

One adjustment before the scores can become weights: divide them all by √dₖ.

48 of 61

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.

49 of 61

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.

50 of 61

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.

51 of 61

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.

52 of 61

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.

53 of 61

Worked Example

53

“A” is a determiner. Its query matches its own key best, so most of its weight stays at home.

  • A function word has little to gain from its neighbours

54 of 61

Worked Example

54

“machine” leans hardest on “learning”, the word it forms a phrase with.

  • The pair “machine learning” shows up as mutual attention

55 of 61

Worked Example

55

And “learning” leans back on “machine”, at 0.38. The attention runs both ways here.

  • Rows 2 and 3 point at each other
  • The grid is not symmetric though: 0.39 one way, 0.38 the other
  • Each row is computed independently

56 of 61

The Full Attention Pattern

56

Four queries, four rows. This grid is the whole attention step for this sentence.

  • Each row is one word being updated
  • Each column is where the information comes from

“model” draws 0.40 from “machine”, but “machine” draws only 0.20 from “model”. Attention is directional.

57 of 61

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.

58 of 61

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.

59 of 61

What Is Actually Learned

59

The most common misreading of this whole section is worth heading off directly.

LEARNED

 

NOT LEARNED

  • The attention pattern itself
    • Computed fresh on every inference run
    • Different for every sentence, and different for the same word in two sentences
    • These are activations, not weights

60 of 61

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

  • “he” on its own carries almost no meaning: it is a pointer with nothing attached
  • Its query asks for a singular person mentioned earlier in the sentence
  • Both “Cornelius” and “Marcus” advertise keys that could match
  • Whichever wins, the value it hands over is what “he” comes to mean
  • No rule for pronouns was written down. These queries and keys came out of training.

61 of 61

Summary: Self-Attention

61

01

Three Projections

  • Every token becomes a query, a key and a value, each from its own learned matrix
  • The query asks, the key answers, the value is what updates happen.

02

Four Steps

  • Score with a dot product, scale by √dₖ, softmax into weights, blend the values
  • All of it is one expression:

03

Learned vs Computed

  • The three matrices are fixed the moment training ends
  • The pattern is computed fresh for every sentence it ever sees