Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathDeep Learning for Production: Transformers, Fine-Tuning and Serving
  1. 1
    Dropout, Early Stopping and Batch Norm: Judge Each One by the Validation Curve
  2. 2
    Transfer Learning on Images: A Frozen ResNet-18, a Small Head and an Honest Baseline
  3. 3
    Attention Explained Without the Maths: Query, Key, Value and the Word "it"
  4. 4
    Transformer Building Blocks in PyTorch: Follow the Shapes Through Attention and a Block
  5. 5
    Pretrained Models from Hugging Face: A Sentiment Pipeline and Sentence Embeddings on a CPU
  6. 6
    Loading a Language Model and Running Inference: Download, Load, Tokenize, Generate
  7. 7
    Model Size and Memory: Parameters x Bytes, Quantization, and Where to Run a Model
  8. 8
    Training on a GPU: Mixed Precision, Gradient Accumulation and Checkpoints That Really Resume
  9. 9
    When NOT to Fine-Tune: A Decision Tree of Prompt, RAG, Tools, Then Fine-Tuning
  10. 10
    Full Fine-Tuning vs LoRA vs QLoRA: What Each One Changes and What It Costs
  11. 11
    LoRA Fine-Tune of a Tiny Model: Teach SmolLM2-135M Your House Style on a CPU
  12. 12
    Knowledge Distillation: Teach a Model 100 Times Smaller From a Teacher's Soft Labels
  13. 13
    Serving Open Models: Continuous Batching, vLLM and Cold Starts
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. Deep Learning

Learning path: Deep Learning for Production: Transformers, Fine-Tuning and Serving · Step 3 of 13

Attention Explained Without the Maths: Query, Key, Value and the Word "it"

Attention without matrices: query, key and value as what a word looks for, offers and passes on, a 10-line NumPy toy where "it" gives 0.62 of its attention to "animal", and why many heads and all-at-once reading made attention win.

Chaand Sheikh

·27 November 2026Deep Learning

What you will learn

  • Explain what attention does with a real sentence: which word does "it" point to?
  • Describe query, key and value as what I look for, what I offer and what I pass on
  • Read attention weights from a tiny NumPy script as shares that add up to one
  • Explain why many heads and looking at all words at once made attention win

Before you start

  • Embeddings: Words as Vectors, Cosine Similarity and nn.Embedding

Here's a sentence: The animal didn't cross the street because it was too tired.

Now look at the small word it. You know straight away that it means the animal. A model has to work that out. Does it mean the animal, or the street?

Picture a noisy party. You can hear everyone in the room, but you turn your ear to the people saying something that matters to you. That's what the model has to do with it: listen harder to some words than to others. That's attention, the idea at the heart of every modern language model. We'll get through it with three simple ideas and not a single matrix.

Words as numbers

A computer can't read words, so every word becomes a list of numbers, and words with a similar meaning get similar numbers. If that's new, start with Embeddings: Words as Vectors.

To see everything with our own eyes, we'll use a toy example: four numbers per word, made by hand, not learned by a model. Each number is a made-up feature:

Wordliving thingobject or placeactionglue word
animal3.00.00.00.0
street0.02.00.00.0
cross0.00.02.00.0
because0.00.00.01.5
it1.01.00.00.0

Query, key, value

At the party, every guest plays three roles at once:

  • Query: what I'm looking for. The word it asks a question: which word here is a living thing?
  • Key: what I offer. Each word shows a small label. animal says "I'm a living thing". street says "I'm a place".
  • Value: what I pass on. If a word gets chosen, it hands over its meaning.

The query is matched against every key. The better the match, the more of that word's value you take in. That's the whole mechanism.

The toy script

Here's the whole thing in NumPy. Eight words, a key for each word, and one query for it:

import numpy as np

# Toy example: hand-made 4-number vectors, not from a trained model.
# Each number is a made-up feature: [living thing, object or place, action, glue word]
words = ["The", "animal", "didn't", "cross", "the", "street", "because", "it"]
keys = np.array([
    [0.0, 0.0, 0.0, 1.0],   # The
    [3.0, 0.0, 0.0, 0.0],   # animal
    [0.0, 0.0, 1.0, 0.5],   # didn't
    [0.0, 0.0, 2.0, 0.0],   # cross
    [0.0, 0.0, 0.0, 1.0],   # the
    [0.0, 2.0, 0.0, 0.0],   # street
    [0.0, 0.0, 0.0, 1.5],   # because
    [1.0, 1.0, 0.0, 0.0],   # it
])

# What "it" is looking for: something living, a little bit of something physical
query_it = np.array([2.0, 1.0, 0.0, 0.0])

scores = keys @ query_it / np.sqrt(4)            # how well each key matches the query
weights = np.exp(scores) / np.exp(scores).sum()  # softmax: weights add up to 1

print("Toy example: attention weights for the word 'it'")
for word, w in zip(words, weights):
    print(f"{word:>8}  {w:.2f}  {'#' * round(w * 40)}")
print(f"{'total':>8}  {weights.sum():.2f}")

Two steps do the work. First, the query is multiplied with each key, number by number, and added up. That's a score: a high score means a good match. (Dividing by the square root of 4 just keeps the scores from getting too big.) Then softmax turns the scores into weights.

Toy example: attention weights for the word 'it'
     The  0.03  #
  animal  0.62  #########################
  didn't  0.03  #
   cross  0.03  #
     the  0.03  #
  street  0.08  ###
 because  0.03  #
      it  0.14  ######
   total  1.00

animal gets 0.62. street gets only 0.08. it itself gets 0.14, and the small words get 0.03 each. Remember the numbers were chosen by hand, so this shows how attention works, not what a real model learned.

The weights add up to 1.00. So you can read each weight as a share of attention: a bigger weight means "listen more to this word".

Where does "it" listen?

Where the word it listens The 0.03 animal 0.62 didn't 0.03 cross 0.03 the 0.03 street 0.08 because 0.03 it 0.14
Every arc starts at it, and its thickness is the weight from the toy run. The thickest goes to animal (0.62).

The thickest arrow goes to animal, the word that best matches what it was looking for. The rest are thin. So the model reads it as the animal, and no human wrote a rule for that. It only needed numbers, a match score and a share of attention.

In a real model, the query, key and value aren't typed in by hand. They're made from each word's numbers by small layers that are learned in training, and every word runs this, not only it. You'll see those layers in code in Transformer Building Blocks in PyTorch.

Many heads

A model doesn't run attention once. It runs it many times side by side, and each copy is called a head. To give you the feel (these are examples, not measured):

  • one head might link a verb to who did the action,
  • another might link a pronoun like it to what it points to,
  • a third might notice which words sit together in a phrase.

At the party, it's like several people each listening for something different and then sharing notes. Together they build a much richer picture of the sentence.

Why attention won

Older models read one word at a time and carried a summary forward. By the end of a long sentence, the first words were just a faint memory.

Attention looks at all the words at once. Any word can link straight to any other word, near or far. Long-range links become easy, and all the words can be handled in parallel, which makes training much faster.

Common mistakes

  • Thinking attention needs a rule about grammar. It doesn't: matching scores do the work, and training shapes the numbers.
  • Reading the weights as probabilities of meaning. They're shares of attention for one word, and they always add up to 1.
  • Taking the toy numbers as a real model's. They were made by hand so the result is easy to see.
  • Mixing up key and value. The key decides how much you listen; the value is what you take.

Quick recap

IdeaIn one line
AttentionEach word gathers information from the words that matter most to it
QueryWhat I'm looking for
KeyWhat I offer
ValueWhat I pass on
SoftmaxTurns match scores into weights that add up to 1
HeadsSeveral attentions side by side, each looking for a different kind of link

Try it yourself

Change the numbers in query_it and see who it listens to. Give street a living-thing number and watch the weights shift. Or write your own eight-word sentence with its own toy vectors.

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
← Previous
Transfer Learning on Images: A Frozen ResNet-18, a Small Head and an Honest Baseline
Next →
Transformer Building Blocks in PyTorch: Follow the Shapes Through Attention and a Block
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Related articles
Why Neural Networks: Pixels, One Neuron and Layers

Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.

The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax

Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.

Loss and Backpropagation: How Wrong, and Who Is to Blame

The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.

The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers

How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.

On this page
  • Words as numbers
  • Query, key, value
  • The toy script
  • Where does "it" listen?
  • Many heads
  • Why attention won
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.