Fundamentals of NLPGreen AI, Topic 1 · Universidade da Coruña · updated
Contents

Start

Cátedra Inditex–UDC de Algoritmos Verdes

Microcredencial Algoritmos verdes para la IA: diseño e implementación

Fundamentals of NLP

Natural language processing · Topic 1 · Instructor: Olga Zamaraeva

CITIC, Universidade da CoruñaFunding

How this topic works

One page: explanations, interactive panels, code

  • This page is the whole topic. Open it on your laptop or phone, now or later:

olzama.github.io/teaching/GreenAI

  • Interactive screens are animations you can step through, change and replay.
  • Try it screens have Python that runs in your browser. Nothing to install.
  • The longer notebooks run in Google Colab.

olga.zamaraeva@udc.es · UDC Teams · CITIC, 2nd floor

NLP and what it costs

Natural Language Processing & Computational Linguistics

  • NLP: building systems that do things with language
  • CL: using computation to study language
NLPCL translation, dialogue,summarization syntax, semantics,typology languagemodels

One engine now runs many tasks

Before: separate models, one per task

Translate
Summarize
Classify
Chat

Now: one model, prompted

Language model
→
Translate
Summarize
Classify
Chat

This is where “NLP” and “AI” blur.

Radford et al., “Language Models are Unsupervised Multitask Learners,” 2019; Brown et al., “Language Models are Few-Shot Learners,” NeurIPS 2020

Where the costs come from

A language model uses electricity, hardware and water for its whole life

TrainingComputing the model's parameters from text. Many processors for days or weeks. Paid once per model.
InferenceRunning the trained model on each request. Small per request, paid every time, for as long as the model is in use.
StorageThe model's parameters and the data, kept on disks and in memory, powered all the time.
Cooling and waterProcessors turn electricity into heat. Data centers remove it, often by evaporating water.
  • Building the hardware has a cost too, before any of this runs.

Training once, inference every time

Train
(once)
→
Deployed
model
⇉
request
request
request
request
… millions of requests
  • Over a model's life, the cost of all its requests can add up to more than the cost of training it.
  • Generating text costs more than classifying it: the model runs once for every word it writes.
  • One request runs on more than the processor that computes it: the host machine, idle spare machines, and the data center around them.

How do we measure it?

Computation, power and energy

An example: one hour on the GPU you will use in Colab

  • FLOPs (floating-point operations): how much computation. They count the work, whatever the hardware.
  • Power, in watts (W): how fast a device uses electricity, at a given moment.
  • Energy, in watt-hours (Wh) or kilowatt-hours (kWh): power × time. This is what you pay for.

An NVIDIA T4 GPU

70 W maximum power × 1 h for one hour = 70 W·h = 70 Wh 70 Wh × 1kWh1000Wh 1 kWh = 1000 Wh = 0.07 kWh

A real run draws less than the maximum, so 0.07 kWh is an upper bound for the GPU alone.

From energy to carbon and water

The same hour on the T4, with example values

  • PUE (Power Usage Effectiveness): the data center's total energy ÷ the computers' energy. 1.0 would mean no overhead.
  • Carbon intensity: grams of CO₂eq per kWh of electricity. It depends on where and when: the grid's mix of coal, gas, wind, sun.
  • CO₂eq: all greenhouse gases, converted to the amount of CO₂ with the same effect.
  • WUE (Water Usage Effectiveness): liters of water per kWh used by the computers.
  • Operational carbon comes from running the hardware; embodied carbon, from building it.
0.07 kWh GPU energy × 1.1 PUE ≈ 0.077 kWh the whole data center 0.077 kWh × 200 g CO₂eq1kWh carbon intensity of the grid ≈ 15 g CO₂eq 0.07 kWh water: the GPU energy (before PUE) × WUE × 1.15 L1kWh ≈ 0.08 L of water

Example values. Real ones depend on the data center and the grid.

Notebook 1 measures with CodeCarbon: it tracks the power of the processor, GPU and memory while your code runs, and multiplies the energy by your region's carbon intensity.

A real measurement: one prompt

The median Gemini text prompt, May 2025, as measured by Google

What is countedWh
AI accelerators, while computing0.14
host processor and memory0.06
idle machines, kept ready0.02
data center overhead (PUE 1.09)0.02
total0.24
  • What you count changes the number.
  • Carbon: all the energy × the grid's carbon intensity, plus a share of building the hardware. Water: the computers' energy × WUE.
  • Measured by the company that runs the model, for its own system. Not independently checked.
0.14 accelerators + 0.06 host + 0.02 idle + 0.02 overhead = 0.24 Wh only the accelerators, as a share of the total share = 0.140.24 ≈ 0.58: a little over half carbon: all the energy (0.24 Wh = 0.00024 kWh) × the grid's carbon intensity 0.00024 kWh × 94 g CO₂eq1kWh ≈ 0.023 g + 0.010 g building the hardware ≈ 0.03 g CO₂eq water: the computers' energy, without the overhead (0.24 − 0.02 = 0.22 Wh) × WUE 0.00022 kWh × 1.15 L1kWh ≈ 0.25 mL of water the paper reports 0.26 mL: it starts from unrounded values

Source: Elsworth et al., “Measuring the environmental impact of delivering AI at Google Scale,” 2025 (arXiv:2508.15734)

What this course covers

The goal: to talk about modern LLMs, and what they cost

Three topics, one running project: the Green NLP Benchmark Lab

  • To understand large language models, we need to understand language models in general, and how NLP got to them
Topic 1
Language models
→
Topic 2
Quantized language models
→
Topic 3
Retrieval-augmented generation
  • Topic 2: the same model, with fewer bits for each of its numbers
  • Topic 3: not a kind of model, but a way of using one: give it only the relevant pieces of the documents
  • Every topic: the same tasks, measured the same way. One row per run in your own leaderboard.

Two tasks: question answering and translation

Question answering

  • Answer questions about a small set of documents
  • Easy to evaluate: an answer is right or wrong, so the score is the share of right answers
  • The main task for measurement, in all three topics

Machine translation

  • Harder to evaluate: a sentence has many good translations
  • Our example, Galician to English. Galician is a low-resource language: there is much less text for it than for Spanish or English.

Unha tía miña, que todo o solucionaba con ditos e refráns, dicía algo así como “un é escravo do que di e dono do que cala”

from the novel Speechwriter by Paulo Naseiro

The plan

From n-grams to transformers

Each step fixes a problem of the step before.

StepWhat it addsWhat is still missing
1 N-grams (statistical, 1990s)predict the next word by countinga word pair it never counted gets probability 0, even if a similar pair was counted
2 Embeddings (neural, 2013)a learned vector per word: similar words get similar vectorsvectors for words, not for sentences
3 Encoder–decoder (2014)read a sentence into one vector, write the translation from itone vector for a whole sentence: early words fade
4 Attention (2015)the decoder looks back at every source wordthe source is still read one word after another
5 Self-attention (2017)every word looks at every word of its own sentence, all at onceone round of looking
6 Transformers (2017 onward)many blocks of self-attention, stacked: modern LLMscost grows with size and length

Before statistics, NLP systems were written by hand, as rules. Each step since has replaced hand-written knowledge with more data and more computation.

Step 1 · N-grams

N-grams

What is a language model?

  • It predicts the next word.
  • It gives a probability to every word in the vocabulary. The probabilities add up to 1.
  • An n-gram model is the simplest kind: it counts word sequences in a corpus, then divides.
Next-word probabilities, from Jurafsky and MartinCredit: Jurafsky & Martin, Speech and Language Processing

After “my”: one probability per word

Counted from three sentences, on the next screen. The vocabulary has 7 words.

N-grams

Count, then divide

the corpus my aunt stayed quiet my aunt spoke wisely my uncle stayed quiet P(wi | wi−1) = Count(wi−1 wi)Count(wi−1) P(aunt | my) = 23 ≈ 0.67 P(uncle | my) = 13 ≈ 0.33 P(spoke | aunt) = 12 = 0.5 P(spoke | uncle) = no “uncle spoke” 01 = 0
  • This is a bigram model: the next word depends on the one word before it.
  • Counting, then dividing: that is the whole model.
  • A pair it never counted gets probability 0. Aunt and uncle appear in the same places, but the model keeps separate counts for each word: what it learns about aunt does not help with uncle.
  • A Galician model has far fewer sentences to count from than a Spanish or English one, so more of its pairs are never counted.
QuestionIs a bigger n better?
Interactive

Count, generate, score

Open the full page
Try it · about 15 minutes for the three screens

Build the bigram model

The Python here runs in your browser. The first Run loads Python, which takes a few seconds.

Some lines have gaps marked ___. Replace each gap with code. Run shows what your code prints. Run the tests also checks it: each test checks one thing, including unusual inputs, and says what to fix. Under each exercise you can read the tests, the hints and the solution. Do the exercises in order: later ones use your earlier code.

Exercise 1 · Count bigrams, then divide

Complete build_bigram_counts and bigram_prob. counts[w1][w2] is how many times the pair w1 w2 occurs. unigram_counts[w1] is how many pairs start with w1. bigram_prob returns P(w2 | w1) = count(w1 w2) / count(w1). The cell should print 0.67 and 0.33.

Hints
  • The inner loop looks at position i and the word right after it, words[i + 1].
  • The pair count is indexed by the first word, then the second word.
  • The probability divides the pair count by the count of the first word.

Exercise 2 · Change the data, change the model

Add at least two sentences to EXTENDED_CORPUS so that, in the new model, P(uncle | my) is larger than P(aunt | my).

Hints
  • The original corpus has “my aunt” twice and “my uncle” once.
  • Each new sentence is a Python string, for example "my uncle spoke kindly".
Try it

Generate text with the model

Exercise 3 · Generate text greedily

Given a start word, the model repeatedly picks the next word with the highest count. Complete the loop in generate: pick that word, and add it to the sentence.

Hints
  • candidates maps each possible next word to its count, for example {'aunt': 2, 'uncle': 1}.
  • max(candidates, key=...) returns the key with the largest value of key(word).
Think about it. Change the last line to generate("her", counts, unigram_counts) and run it. Why does the model stop at once? There is far less Galician text online than Spanish or English text. What would you predict about an n-gram model trained on Galician?
Try it

Use the model to fix word order

A word-for-word translator turns Galician “unha tía miña” into “a aunt my”: the right words in the wrong order. A bigram model can score each possible order by how fluent it sounds, and keep the best one.

Exercise 4 · Score word orders with a smoothed bigram model

Two gaps. In sentence_log_prob, compute the add-one smoothed probability of each pair and add its logarithm to log_prob. In the search loop, keep the best-scoring order seen so far.

Hints
  • Add-one smoothing adds 1 to every pair count, and adds the vocabulary size to the denominator.
  • Logs turn the product of probabilities into a sum: log_prob += math.log(prob).
  • Update the best order only when the new score is higher than best_score.
Think about it. The best order is “a my aunt”: better than “a aunt my”, still wrong. The model only knows which words tend to sit next to each other. It does not know that “a” belongs with a noun.

Exercise 5 · Count the orderings

There are two ways to get the number of orderings of the 8 words in BIGGER_WORDS, and they must give the same number:

  1. Count them. The loop goes through every ordering, one at a time. Fill in the list to order, and add 1 to count for each ordering.
  2. Compute them. Set expected with the formula for the number of orderings of n different words.

The last lines print both numbers, one under the other, and say whether they match.

Hints
  • n different words have n! orderings: n × (n − 1) × … × 1.
  • math was imported in Exercise 4.
Think about it. 3 words have 6 orderings and 8 words have 40,320. How many does a 20-word sentence have? Could a system try them all?
Interactive · if there is time

Shakespeare, one word at a time

Open the full page
Activity · about 20 minutes, individual

N-grams at scale

Notebook 01b, in Colab (CPU only, no GPU needed)

  • The same counting, on 2 million words each of Galician and Spanish Wikipedia
  • How many bigrams of new text has the model never seen, as the training text grows?
  • What does a longer n do? And a Galician trigram model writes text

Step 2 · Embeddings

Embeddings

Comparing vectors: cosine similarity

How similar are the directions of two vectors? The formula, derived on the board.

1 1 2 2 3 3 4 4 aunt (4, 2) uncle (3, 3) ‖aunt‖ = 4 √(4² 2 + 2²) = √(16 + 4) = √20 ≈ 4.47 ‖uncle‖ = √(3² + 3²) = √(9 + 9) = √18 ≈ 4.24 1 â = aunt / ‖aunt‖ â = (4 / 4.47, 2 / 4.47) ≈ (0.89, 0.45) û = uncle / ‖uncle‖ û = (3 / 4.24, 3 / 4.24) ≈ (0.71, 0.71) α β cos α = ( cos α sin α , sin α ) = ( cos β , sin β ) â · û = cos α · cos β + sin α · sin β = cos(β − α) θ = cos θ cos θ = â · û = aunt · uncle‖aunt‖‖uncle‖ = 4·3+ 2·34.47· 4.24 = 12+ 618.95 = 1818.95 ≈ 0.95
Interactive

Shakespeare, counted by play

Embeddings

From words to vectors: embeddings

Why vectors of counts are not enough: they are long, mostly 0, and similar words do not line up

our corpus my aunt stayed quiet my aunt spoke wisely my uncle stayed quiet how often each word stands right before or after it my aunt uncle stayed spoke quiet wisely aunt 2 0 0 1 1 0 0 uncle 1 0 0 1 0 0 0 7 words, 7 columns. Already here, most entries are 0. Galician Wikipedia, 2 million words: 127,848 different words, so 127,848 columns tía … 127,848 boxes 23 of them are not 0; the other 127,825 are 0. A vector that is mostly 0 is called sparse. súa stands right before tía 11 times; seu before tío 33 times. Both mean “her” or “his”: súa goes with feminine words, seu with masculine ones, so they are two different columns. cos(tía, tío) ≈ 0.05 cos(tía, casa “house”) ≈ 0.33 With so few counts, in columns that do not line up, aunt and uncle look unrelated. An embedding of a word: a vector of a few hundred numbers, learned from text, none of them 0 (dense). tía … a few hundred boxes The learning aims at one thing: words used in similar ways get similar vectors, so tía and tío should get a high cosine.
Embeddings

How embeddings are actually learned

Skip-gram (Mikolov et al., 2013): predict the neighbors

A tiny corpus

cats chase micedogs chase ballscats eat fishdogs eat meat

Window = 1

cats chase mice predict both neighbors

16 training pairs: input → word to predict

cats → chasecats → eat
chase → catseat → cats
chase → miceeat → fish
mice → chasefish → eat
dogs → chasedogs → eat
chase → dogseat → dogs
chase → ballseat → meat
balls → chasemeat → eat
Embeddings

Skip-gram: two pictures of the same model

The classic picture (Mikolov et al., 2013)

INPUTPROJECTIONOUTPUT w(t) w(t−2)w(t−1)w(t+1)w(t+2) Redrawn after Mikolov et al., “Efficient Estimation of Word Representations in Vector Space,” 2013 (arXiv:1301.3781), Figure 1

The same model, with numbers

The skip-gram network with its two tables of numbersIllustration: district-data-labs (Medium)
Embeddings

Step by step, 1: from a word to its vector

Our corpus, with the tables at the start of training

word cats dogs chase eat mice balls fish meat one-hot vectors, one row per word 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 × p, random at the start −0.41 −0.26 0.30 0.08 −0.41 −0.07 −0.02 −0.34 0.23 −0.39 −0.11 0.02 −0.07 0.09 0.24 0.46 h1 = 1 · (−0.41) + 0 · 0.30 + … = −0.41 = −0.41 h h2 = 1 · (−0.26) + 0 · 0.08 + … = −0.26 −0.26
Embeddings

Step by step, 2: from the vector to probabilities

The model's guess for the neighbor of cats, before any training

cats dogs chase eat mice balls fish meat h = (−0.41, −0.26) the vector of cats, from the previous screen p′ p′: the model's second table, one column per word (drawn here as rows); random at the start, like p −0.22 0.39 0.15 0.09 0.20 −0.03 −0.21 0.27 −0.50 −0.47 0.47 0.21 −0.20 −0.13 −0.19 −0.41 score(chase) = (−0.41) · 0.20 + (−0.26) · (−0.03) = −0.082 + 0.008 = −0.074 score −0.074 −0.011 −0.085 0.016 0.327 −0.247 0.116 0.184 e−0.074​ = 0.929 escore​ 0.929 0.989 0.919 1.016 1.387 0.781 1.123 1.202 sum = 0.989 + 0.919 + … + 1.202 = 8.346 sum 8.346 P(chase | cats) = 0.9298.346 = 0.111 P(word | cats) 0.111 0.118 0.110 0.122 0.166 0.094 0.135 0.144 1.000
Interactive

Skip-gram, step by step

Embeddings

Similar company, similar vectors

The company each word keeps

catschase, eat
dogschase, eat
micechase
ballschase
fisheat
meateat

The table after training

cats0.630.37
dogs0.860.48
mice3.89−3.15
balls3.93−2.94
fish−0.345.00
meat−0.164.91

“You shall know a word by the company it keeps.” J. R. Firth (1957)

Interactive

Which words are similar?

Embeddings

What we keep: the embedding table

task: predict neighboring words
↓
the model needs adjustable numbers for each word
↓
training adjusts those numbers, pair after pair
↓
words with similar neighbors get similar adjustments
↓
a space where similar words are close together
  • After training, discard the prediction part and keep the table. Its rows are the word embeddings.
  • Embeddings = the parameters the model uses to solve its prediction task
  • Rare word → few pairs → few nudges → poorly placed vector
  • Less Galician text online → weaker embeddings for many Galician words
Activity · about 25 minutes, individual

Embeddings playground

Notebook 01c, in Colab (CPU only, no GPU needed)

  • Part A: train skip-gram on 2 million words of Galician, with 2 to 300 dimensions: time, energy, quality
  • Part B: train on less text: which words suffer first?
  • Part C: does a multilingual model match Galician words with their Spanish and English translations?

Step 3 · Encoder–decoder translation

Encoder–decoder

Machine translation: a very short history

Rules
1950s
→
Statistics
1990s
→
Neural +
attention, 2015
→
LLMs
2020s
  • One of AI's oldest goals: first public demo in 1954 (Georgetown–IBM)
  • Each shift trades hand-written knowledge for more data and more compute

Source: Hutchins, “Machine Translation: A Concise History,” 2007

Encoder–decoder

Neural translation: an encoder and a decoder

possible inputs a b c d e f g … the input is a sequence of these input 1: c input 2: a input 3: e Encoder reads the inputs one by one, updates a vector after each a vector the input, as numbers (often called the summary) Decoder keeps its own vector, the state: it starts as the encoder's vector possible outputs A B C D … ‹end› each step: a probability for each, one is written output 1: D output 2: B output 3: ‹end› each output is mixed into the state; then the next step, until ‹end› (= finished) Both parts are trained together, on pairs: an input and its gold output (the right output, made by a person). training passes the gradient of the loss back through the decoder and the encoder: backpropagation (next screens) task possible inputs possible outputs translation Galician words English words, ‹end› summarization words words, ‹end› speech recognition short slices of a recording written words, ‹end› image captioning small patches of an image words, ‹end›

The first neural translation models: Sutskever, Vinyals & Le, NeurIPS 2014 (arXiv:1409.3215)

Encoder–decoder

Loss and gradient

the loss: how bad the model is on the training data for a pair, L = −log p, with p the probability the model gives the gold output: p = 1 gives L = 0, smaller p a larger L w, the value of one parameter (all the others stay as they are) → loss L w now an illustration: a real loss depends on millions of parameters run: +0.5 rise: −0.98 slope = rise ÷ run = −0.98 ÷ 0.5 = −1.96 this slope is the derivative of the loss for this parameter, dL/dw: how much L changes per small change of w; negative: increasing w lowers L gradient descent: new = old − learning rate × derivative; the learning rate is a number chosen by hand that sets the step size, here 0.4 first step: w = −1.60 − 0.4 × (−1.96) = −1.60 + 0.78 = −0.82; the minus sends every step downhill the steps shrink as the slope flattens a model has many parameters: one derivative, one slope, for each; all of them together are the gradient, and every parameter steps at once (computed for all of them together: the chain rule and backpropagation, the next screens)
Encoder–decoder

Training, development and test data

traditionally, one collection of data is divided at random into three parts: training data, 80% development, 10% test, 10% real use: data that comes later (not in the collection) training steps → 0 1 2 3 loss L 1 0.5 0.2 0.1 p an illustration, not measured data training data: the model learns from these (gradient descent) development data: never learned from, only measured stop here: the lowest development loss (early stopping) after it, the model fits its training data better and new data worse (overfitting) test data: measured once, here test data: never learned from and never used for any decision; measured once, at the chosen step. It estimates how the model does on new data from the same collection (drawn whole only to show that it follows development) the gap: unknown until the model is in use real use real use: the data the model meets later may be wildly different, other topics, other kinds of text, other speakers; its loss can be far higher than the test loss, and nobody knows it in advance: the test data come from the same collection back to training: most parameters sit far from the loss; their gradients come from the chain rule (next)
Encoder–decoder

The chain rule

a value computed in steps: if the start changes, how much does the end change? walker x bicycle u car y × 4 × 2 4 times as fast 2 times as fast the car is 4 × 2 = 8 times as fast as the walker: if the walker speeds up by 1 km/h, the bicycle speeds up by 4 and the car by 8 · along a chain, the rates multiply in general, y is computed from u, and u from x (above: the car's speed from the bicycle's, the bicycle's from the walker's): change of y per change of x = (change of y per change of u) × (change of u per change of x) in symbols, the chain rule: dydx = dydu · dudx · here: 8 = 2 · 4 · for a longer chain, multiply the rate of every step each of these is a derivative: a slope, the change of a step's output ÷ the change of its input (rise ÷ run, as on the loss screen) a model is a long chain of steps, from each of its vectors to the loss; the chain rule gives, for every vector, how the loss changes with it: its gradient, computed from the loss back (next screen)
Encoder–decoder

Backpropagation

input vectors (weights) x1​ 0.80 0.30 x2​ 0.40 0.70 x3​ 0.60 0.50 Encoder 0.50 0.46 summary = state ⅛ x₁ + ¼ x₂ + ½ x₃ Decoder output vectors (weights) score p A 0.70 0.20 0.44 0.24 B 0.30 0.40 0.33 0.22 C 0.60 0.60 0.58 0.28 D 0.20 0.90 0.52 0.26 forward pass 1. Forward pass: give the network an input. It processes it through the encoder and the decoder and produces a prediction: a probability p for each possible output. (Here the encoder mixes the input vectors into the summary; each score is the dot product of the state and an output vector; softmax gives p, as in skip-gram.) D: the correct answer L −log p(D) = 1.34 2. Calculate the loss: compare the prediction with the correct answer, D, and calculate how wrong it was: L = −log p(D) = 1.34. backward pass +0.12 +0.11 +0.11 +0.10 +0.14 +0.13 −0.37 −0.34 × ⅛ +0.03 −0.05 × ¼ +0.06 −0.09 × ½ +0.13 −0.18 3. Backward pass (backpropagation): work backward through the network, calculating how changing each weight would affect the loss. The number under each weight (its gradient) shows it. Red: increasing that weight would increase the loss. Green: increasing it would decrease the loss. It is calculated with the chain rule: first for the output vectors, next to the loss; then for the input vectors, through the summary (× ½, ¼, ⅛). 0.78 0.32 0.37 0.75 0.54 0.59 0.64 0.14 0.25 0.35 0.53 0.54 0.38 1.07 0.46 0.52 0.37 0.22 0.29 0.20 0.52 0.26 0.74 0.32 = 1.15 4. Gradient descent then updates the weights accordingly: each weight's new value = old value − learning rate (0.5) × its gradient (the new numbers in the vectors). With the new weights, a second forward pass gives p(D) = 0.32 instead of 0.26, and L = 1.15 instead of 1.34. The next screen trains a small translation model this way: after each training pair, its weight vectors make exactly these moves. Cost: one update takes about 3 times the computation of one use of the model, plus memory for the forward pass's values.
Interactive

Neural translation, step by step

Open the full page
Encoder–decoder

Why a real model still writes “an aunt of mine”

Helsinki-NLP/opus-mt-gl-en, a real Galician–English model, translates our sentence as “An aunt of mine, who …” its probability for each opening, given the Galician sentence (log scale) An aunt of mine 0.33 My aunt 0.015 I had an aunt 7.5 × 10-6 One of my aunts 5.5 × 10-10 word by word: the first words decide An aunt of mine An 0.53 aunt 0.95 of 0.65 mine 1.00 I had an aunt I 0.006 had 0.03 an 0.04 aunt 0.90 likely reasons 1. it learned translations, not English in general: “unha X miña” is usually rendered “a X of mine” 2. rare is not absent: “a … of mine” is a common pattern, so it comes out fluently 3. rebuilding is a big step: “I had …” needs a new subject and verb, chosen one word at a time

Step 4 · Attention

Attention

Attention was born in machine translation

  • The bottleneck: the whole sentence squeezed into one vector
  • Bahdanau, Cho & Bengio (2015): for every word it writes, the decoder looks back at every source word and computes how much to use each one: the attention weights (scores, then softmax, as for p)
  • Computed anew for every word written, through learned tables that backpropagation trains (diagram, right; next screen: query, key and value)
  • Which source word goes with which word written (alignment) comes out of the attention weights, with no hand-written rule
  • Invented for translation, years before modern LLMs
L' accord sur la zone ← being written The agreement on the European Economic 0.25 Area 0.71 was signed in August 1992 . ‹end› one row of the grid: writing zone, the decoder looks back at every English word · line width = attention weight
The agreement on the European Economic Area was signed in August 1992 . ‹end› L' accord sur la zone économique européenne a été signé en août 1992 . ‹end› the order flips: European Economic Area → zone économique européenne 2 English words, 3 French words: was signed → a été signé row: French word being written · column: English input word · stronger orange = higher attention weight their trained model, English → French decoder's state query table query source vectors key table keys values = the source vectors, as they are scores softmax attention weights not stored: computed anew for every word written mix: weights × values next word thick green: learned tables, trained by backpropagation backward pass: from the loss back to the tables (and to the vectors the state and the keys are made from)

Attention weights: Bahdanau, Cho & Bengio, ICLR 2015 (arXiv:1409.0473), Figure 3(a), read from the paper and redrawn

Attention

Query, key and value

  • Query q, computed from the decoder's state: what the decoder looks for, before the word it is about to write
  • Key k: what each source word offers to be found by
  • Score = q · k, the dot product; softmax turns the scores into attention weights that add up to 1
  • Value v: what each source word contributes; the mix is the sum of the values, each times its attention weight
  • On the attention page (next screen), the keys and the values are the same vectors: the encoder's, after each word
query q the decoder, about towrite the next English word key k1 unha value v1 key k2 tía value v2 key k3 miña value v3 score of each key: q · k;softmax: attention weightsthat add up to 1 each source word →values × attention weights the mix: w1v1 + w2v2 + w3v3 → the decoder's state thicker line: larger attention weight (made up for the picture)

Like a search in a library. You come with a question: the query. Every book has a label on its spine: its key. You compare your question with each label, and the better the match, the more of that book you read: the attention weight. What you take away is a blend of the books' contents, the values, mostly from the best matches. The decoder does this before every word it writes, each time with a new question.

Interactive

Attention, computed by hand

Open the full page
Interactive

The query's numbers, and two trained models

Open the full page
Attention

A large attention weight does not mean an important word

Unha tía miña, que todo o solucionaba con ditos e refráns, dicía algo así como “un é escravo do que di e dono do que cala”.

  • The small model with attention from the previous screen (section 4) has written “an aunt of mine, who solved everything”. Next: “with”.
  • Largest attention weight before “with”: the full stop, not con (“with”)
  • Test: replace the mix the model reads (table, right). It still writes “with”: the full stop does not matter here.
  • Why: in all 5,000 training sentences, “everything” is followed by “with”. The English already written decides the next word.
  • An attention weight shows where the model looked, not what it needed.

The attention weights before “with”: the four largest of 31, one per Galician word or mark

. (the full stop)0.54
solucionaba (solved)0.12
con (with)0.10
algo (something)0.08

The test: what the model reads → probability of “with”

its own mix0.999
nothing (all zeros)0.997
only the full stop0.998
only con0.998
Interactive

From a row of attention weights to a real model's grids

Step 5 · Self-attention

Self-attention

Self-attention: every word looks at every word of its own sentence

  • Vaswani et al. (2017): the same mechanism within one sentence: every word looks at every word, itself included, all at once
  • “it” → “the animal”, with no hand-written rule
  • No decoder here: every word's vector gives its own query, key and value, each through its own learned table (attention page, section 6, “one head”)
Self-attention from it to the animalLayer 5; colored squares: its 8 heads (orange: the one drawn); right: “it”, left: where it looks, darker = more; “tire·d”: one word, two tokens. Illustration: jalammar.github.io/illustrated-transformer · Source: Vaswani et al., NeurIPS 2017 (arXiv:1706.03762)
Self-attention

Several heads at once: multi-head attention

  • Several heads side by side, each with its own grid of attention weights and its own mix; one learned table combines the mixes into one new vector per word (the real model: 8 heads)
a vector per word
⇉
head 1
head 2
head 3
head 4
⇉
combined: one new vector per word
Interactive

Self-attention heads

Open the full page
Self-attention

Why attention cost grows with the length of the input

Unha tía miña que Unha tía miña que 4 × 4 = 16 Unha tía miña que todo o solucionaba con Unha tía miña que todo o solucionaba con 8 × 8 = 64 n words: n × n = n² 2n words: (2n)² = 4n²
  • One square = one score (query · key). Double the words → four times the scores: the growth is quadratic
  • “unha tía miña” was three words; a whole document is thousands

Step 6 · Transformers

Transformers

A transformer

Encoder: reads the whole inputone layer, repeated 6 timesunha+ positiontía+ positionmiña+ position‹end›+ positionself-attention: every token looks at every tokenfeed-forwardfeed-forwardfeed-forwardfeed-forwardencoder vectorsDecoder: writes, one token at a timeone layer, repeated 6 times‹start›+ positionA+ positionAunt+ positionself-attention: only what is writtencross-attention: looks at the encoder vectorsfeed-forwardfeed-forwardfeed-forwarda probability for every tokenofofwritten:the next input
  • Orange: information moves between tokens. Green: each token on its own
Transformers

Independence assumptions

A line means “depends on”. An independence assumption removes lines: the computation gets simpler, at a price

In probability×ABCP(A, B | C) = P(A | C) · P(B | C)given C, A and B do not dependon each othergain: each computed on its ownprice: any link between them is lostBigram (Step 1)×unhatíamiñaP(miña | unha, tía) ≈ P(miña | tía)given the word before, the nextdoes not depend on earlier wordsgain: we can count word pairsprice: earlier words are ignoredRecurrent layer (Step 3)outputsunhatíamiñaoutput₂ = f(output₁, tía)no such assumption: each outputdepends on the one beforegain: earlier tokens reach later onesprice: the steps must run in orderTransformer layeroutputs××unhatíamiñaoutput₂ = f(unha, tía, miña)given the input, the outputs donot depend on each othergain: all the tokens at onceprice: n² scores; order must be addedthe same shape as in probability; tokens still influence each other, through the input
  • The decisive step of 2017: applying this to the tokens of a layer. Parallel training, and with it the scale of modern models, follows from it
Transformers

Sequential and parallel computation

The problem both layers solve: the output for a token must hold information from the other tokens

A recurrent layerinput of the layeroutput: the information it holdsunhatíamiñalayerunhastep 1 of 3unhatíastep 2 of 3unhatíamiñastep 3 of 3orange: the previous output carries the earlier tokens' informationit is the only route: the steps must run in orderA transformer layerinput of the layeroutput: the information it holdsunhatíamiñaattentionunhatíamiñaunhatíamiñaunhatíamiñastep 1 of 1miña's output: a mix of 3 values, weighted by miña's query · each keyqueries, keys and values come from the input rows, not from any outputthe same for every token: 3 × 3 = 9 scores (query · key)no score needs another score: all 9 can be computed at the same time
  • Recurrent: the output for one token is an input for the next, as in the encoder of Step 3: this is how earlier tokens reach later ones
  • Transformer: no waiting, but the scores grow with the square of the length (Step 5), the recurrent steps only with the length. The scores are independent: a GPU computes them side by side; the time grows once they exceed what it can run at once
Transformers

Token independence and matrix multiplication

token vectorsquery tableunha102tía011miña21010221003111×+00×+22×=512×+01×+20×=210×+03×+21×=201×+10×+12×=202×+11×+10×=100×+13×+11×=421×+10×+02×=222×+11×+00×=520×+13×+01×=311×+00×+22×=512×+01×+20×=210×+03×+21×=201×+10×+12×=202×+11×+10×=100×+13×+11×=421×+10×+02×=222×+11×+00×=520×+13×+01×=3××tokens wait for each other3 time stepstokens independent1 time stepone token: its row × the table gives its output rowas in a recurrent layer: if each row had to wait for the row above, the tokens would run in ordertransformer: no row needs another row: all the tokens run at the same moment
  • One row per token: the × is the same cut as on the slide on independence assumptions. With no row waiting, the whole matrix multiplication can run at once on a GPU's many cores, its arithmetic units (the T4 of your notebooks: 2,560)
Transformers

The shape follows the job

the jobinputthe modeloutputTurn one textinto anotherunha tía miñaencoderdecoderA Aunt of mineopus-mt-gl-enone stack reads all the input, the other writes the outputUnderstanda textsearch, classify,compare (BERTScore)The?flew overthe lake.it sees the words on both sidesencoderdecodernothing to writehelicopter0.34plane0.25bird0.03BERT: its probabilities for the ?Write textcontinue, answer,translate on requestThe dog barked at thethe input is the start of the textencoderno separate inputdecoderdog, and the dogbarked back.GPT-2 continues the textGuessing the ?: BERT sees “flew over the lake” and guesses helicopter, 0.34GPT-2 sees only “The”: its best guess has a probability of 0.014
  • Each model keeps only the half its job needs. The encoder sees both sides but cannot write; the decoder writes, and may look only back
  • BERT and GPT train on raw text: the hidden word and the next word are already in the text: nobody has to prepare a gold output

Real outputs: bert-base-uncased, GPT-2, opus-mt-gl-en

Transformers

What a decoder may look at

Encoder (BERT): every token looks at every token

myauntsolvedeveryproblemmyauntsolvedeveryproblem

Decoder (GPT): only at itself and the tokens before it

myauntsolvedeveryproblemmy××××aunt×××solved××every×problem
  • Rows look, columns are looked at, as in the grids you read. ×: the weight is forced to 0
  • The decoder's job is to write the next word: if it could see that word, there would be nothing to learn
Transformers

From two stacks to one

tokensembedding+ positiona vectorper tokenunhatíamiñaasisterofencoderits own tablesdecoderits own tablescross-attentionone stack of layers: self-attention (triangle), feed-forwardself-attention: the English tokenslook back at the Galician onesminenext tokenreading the input, done by the same layerswriting the outputStays: embeddings, positions, vectors, layers, attentionGoes: a separate stack with its own tables, cross-attentionThe difference from an encoder: each token looks only back,and unha cannot use tía or miña; one set of tables does both
  • The only thing removed is the separate encoder stack; its work moves into the single stack
  • Translation has an input and an output, but both are text: they can be one sequence, and the same layers can build the vectors of both
Transformers

Training on raw text

inputMyaunt< 0.001auntsolved< 0.001solvedevery0.003everyproblem0.44problemwith0.09witha0.10astory0.001story.0.11goldprobabilityfrom GPT-2Training raises every one of these bars, all at oncethe triangle keeps the gold token out of sightEach bar: P(gold token | all the tokens before it), from GPT-2P(problem | My aunt solved every) = 0.44
  • The task of Step 1, the next word, now with all the text before it. Every position of every text gives a gold output, with nobody writing one
  • Why this teaches so much: predicting well takes grammar, meaning and facts, and translation too, because text contains it: PaLM's training data held over 30 million translation pairs

Numbers: GPT-2 (124 million parameters), trained only on this task. Source: Briakou et al., “Searching for Needles in a Haystack,” ACL 2023 (arXiv:2305.10266)

Transformers

How a decoder-only model translates

Galician:unhatíamiña↵English:asisterofmineGalician:unhatíamiña↵English:.08.17.11.48a.31.12.48sister.19.17.59of.07.23.52mine

One sequence: the input, then what the model writes

Galician: unha tía miña
English:
a sister of mine
  • The real grid of Qwen2.5-1.5B, the model of your notebook: layer 19, head 10. Each row writes the next token: row “:” writes “a”
  • Orange block: the rows writing the English, looking at the Galician. They put 0.88 of their weight there; the median head, 0.12. This block does the job of section 6's grid
  • It looks at t·ía and writes “sister”: the weights show where it looks, not whether it is right

This head was found by searching all 336 heads on this one prompt.

Transformers

Training in parallel, writing in sequence

TrainingGalician: unha tía miña English:anauntofminethe text is known, the gold output included: all the positions in 1 stepWritingGalician: unha tía miña English:asisterofminethe next token does not exist until this one is chosen: 4 steps, in order
  • The parallel computation is what makes training fast. Using the model is another matter: every token written is one more pass through all the layers
Transformers

The KV cache

One row for each token written; one column for each earlier token whose key and value it needs

Without a cacheunhatíamiñaasisterofasisterofmine18 keys and values computedWith the KV cacheunhatíamiñaasisterofasisterofmine6 keys and values computedcomputed at this stepread from the cache
  • To write a token, its query needs the key and value of every earlier token. They do not change: the model keeps them: less computation, at the price of memory that grows with every token
Activity · about 20 minutes, individual

Attention playground

Notebook 01d, in Colab (CPU only, no GPU needed)

  • Part A: for each of the 48 heads of the real model's encoder (its self-attention), measure how much it looks at the previous, the same or the next token, on a sentence you choose
  • Part B: count the attention scores, then time the whole encoder as the text gets longer. Does the time grow like n²?

From transformers to modern LLMs

Modern LLMs

Modern LLMs are still transformers: what changed?

Parameters, drawn to size (area)

BERT-base110 millionQwen2.5-1.5B, your notebook1.5 billionGPT-3175 billion
  • The architecture stays: open models such as Qwen2.5 and Mixtral are decoder-only transformers (closed models do not publish theirs)
  • Scale: the squares on the left
  • Training stages: more training after writing the next word
  • Refinements: for example, using only part of the model for each token
Modern LLMs

From writing the next word to following instructions

stageone training examplewhat it teaches1. Pretrainingtext: My aunt solved everygold output, the next token: problemto continue any text(as on the slide on raw text)2. Instructiontuninginstruction: Name three colors.gold output, written by a person: Red, blue, green.to answer an instructioninstead of continuing it3. Preferencetrainingtwo answers from the model, and a person chooses:✓ Red, blue, green.✗ Colors are nice.to give the answerspeople preferThe same instruction, real outputs: Name three colors.after stage 1 only (GPT-2):“The first is the color of the first letter of the alphabet. The second is the color of the…”after all three (Qwen2.5-1.5B-Instruct):“Sure! Here are three common colors: 1. Red 2. Blue 3. Green”
  • The same transformer all along: only the training data changes. In Ouyang et al., people preferred a 1.3-billion-parameter model with these stages to the 175-billion-parameter GPT-3 without them

The examples of stages 2 and 3 are illustrations. The two models also differ in size and date: the outputs show the kind of change, not its exact cause. Source: Ouyang et al., NeurIPS 2022 (arXiv:2203.02155)

Modern LLMs

Cost levers in modern models

leverwhat modern models doeffect on the computation
the parametersMixture of experts: several feed-forward blocks per layer, each token uses only some. In Mixtral (from the company Mistral AI), 2 of the 8 blocks of a layer: about 13 of its 47 billion parameters for each tokendown: only part of the parameters works on each token
the inputLong context: whole documents read at onceup: attention grows with the square of the length
the outputReasoning models: hundreds to thousands of tokens written before the answer (DeepSeek-R1)up: more steps, a bigger cache
  • Topics 2 and 3 cut costs on these models: fewer bits for each number, less text to read

Sources: Jiang et al., “Mixtral of Experts,” 2024 (arXiv:2401.04088); DeepSeek-AI, “DeepSeek-R1,” 2025 (arXiv:2501.12948)

Your turn

Activity · 40–60 minutes, individual, if time allows

Notebook 01e: Translation and its evaluation

  • Part 1: a passage with our sentence, through rule-based, statistical, neural and LLM translation, each one measured
  • Part 2: BLEU, BERTScore and an LLM-as-judge grade the translations, and we measure what grading itself costs

Notebook 01e, in Colab, with a GPU

  • In Colab: Runtime → Change runtime type → T4 GPU
  • Download mt_leaderboard.csv and mt_eval_leaderboard.csv at the end

What comes next

What comes next

Next topics: the same tasks, two changes

Topic 2
baseline, then quantized
→
Topic 3
retrieval (RAG)
  • Topic 2: answering questions about documents, first as a baseline, then the same model with fewer bits for each number. Less memory, often less energy. Does the quality hold?
  • Topic 3: retrieve the relevant passages of the documents first, and give the model only those. Less text to process for every question.
  • Both are measured against the baseline, with the same method.

Thank you for your attention

Cátedra Inditex–UDC de Algoritmos Verdes
catedrainditexalgoritmosverdes.com

Refresher

Refresher

Quick refresher: multiplying matrices

  • To multiply A (m × n) by B (n × p): the inner dimensions must match; the result is m × p
  • Each entry of the result is a dot product: multiply matching entries, add them up
1 2 0 3 1 4 2 × 3 2 0 1 3 0 2 3 × 2 = 2 × 2 c11 = 1 × 2 + 2 × 1 + 0 × 0 = 4 4 6 7 11 the same for every row of A and column of B a one-hot vector 0 0 1 0 × 0.1 0.9 0.3 0.2 0.7 0.5 0.4 0.8 every row is multiplied by 0, except row 3 = 0.7 0.5
Contents
0:00