Skip to content
Visual explainer 4h to learn 5 steps

Embeddings, attention and transformer blocks explained

Explain tokenisation, embeddings, attention and a transformer block, and choose between pretrained use, fine-tuning and inference-only use.

By Invicly Tech, , in AI and Machine Learning with Python. About 11 minutes to read.

Topic 22 of 34

In short

Transformers turn text into token IDs, map each ID to an embedding vector, and then let every token look at every other token through attention. Stacking attention and small feed-forward layers into blocks gives the models behind modern language tools. Knowing these parts helps you decide whether to use a pretrained model as is, fine-tune it, or only run inference.

Explained simply

A transformer is the neural network design behind modern language models, translation tools and many image models. It reads a whole sequence at once and lets every piece look at every other piece to decide what matters. That ability is called attention.

Computers cannot read words, so text is first split into tokens. A token is often a whole common word or a piece of a rarer one. Each token gets an ID number, and each ID is mapped to a list of numbers called an embedding, which the model learns during training.

Inside the model, attention lets the word it in a sentence borrow meaning from the noun it refers to. A transformer stacks many blocks, each with attention and a small feed-forward network, so the representation of every token gets richer layer by layer.

You rarely train one from scratch. You either use a pretrained model as it is, fine-tune it on your own labelled examples, or just run it for predictions. Each choice has very different costs in data, memory and time.

Press Play on a diagram to walk through it one step at a time.

FlowFrom text to predictions
  1. Step 1
    Tokenise

    Text becomes subword token IDs

  2. Step 2
    Embed

    Each ID becomes a vector, plus position information

  3. Step 3
    Transformer blocks

    Attention and feed-forward layers, repeated N times

  4. Step 4
    Output head

    Scores for the next token or a class label

LayersInside one transformer block
  1. 1
    Add and normalise

    Residual connection plus layer normalisation

  2. 2
    Feed-forward network

    Two linear layers applied to each token

  3. 3
    Add and normalise

    Residual keeps the original signal flowing

  4. 4
    Multi-head self-attention

    Each token mixes information from others

CompareTransformer families
Encoder-only
  • Sees tokens in both directions
  • Example: BERT
  • Good for classification and embeddings
Decoder-only
  • Causal mask, left to right
  • Example: GPT-2 and later GPT models
  • Good for text generation
Encoder-decoder
  • Encoder reads, decoder writes
  • Example: T5
  • Good for translation and summarising

In depth

Tokenisation in practice

Modern models use subword tokenisers such as byte-pair encoding (BPE) or WordPiece. Frequent words become single tokens, while rare words split into pieces, so the vocabulary stays a manageable size, often 30,000 to over 100,000 tokens, and no word is ever truly unknown.

Tokenisation affects cost and limits. Context windows and prices are counted in tokens, not words. For English prose a rough rule is about three quarters of a word per token, but code, numbers and many other languages use more tokens per word. Each model ships with its own tokeniser and special tokens, such as markers for the start of text or padding. Always load the tokeniser that matches the model, for example with AutoTokenizer.from_pretrained using the same model name.

  • Count tokens with the model's own tokeniser, not by words
  • Special tokens mark start, end, padding or separators
  • Padding plus an attention mask lets sequences of different lengths share a batch

Embeddings and position

An embedding layer, nn.Embedding(vocab_size, d_model) in PyTorch, is a lookup table: row i holds the vector for token ID i. These vectors start random and are learned, so tokens used in similar ways end up with similar vectors. Typical widths range from a few hundred to several thousand numbers.

Attention treats its inputs as a set, so on its own it cannot tell dog bites man from man bites dog. Transformers add position information. The original design added fixed sine and cosine patterns; many models learn a position embedding, and many recent language models use rotary position embeddings, which rotate query and key vectors by an angle that depends on position. The details differ, but the goal is the same: make word order visible.

Scaled dot-product attention step by step

Each token's vector is multiplied by three learned matrices to give a query, a key and a value. The query says what this token is looking for, the key says what each token offers, and the value is the information passed along. Scores are the dot products of one token's query with every key, divided by the square root of the key size d_k so they do not grow too large. Softmax turns each row of scores into weights that sum to 1, and the output for that token is the weighted sum of the values.

Multi-head attention runs several of these in parallel on smaller slices, so different heads can track different relationships, such as grammar or coreference. For next-token prediction, a causal mask sets scores for future positions to minus infinity before softmax.

FlowComputing attention for one token
  1. 1
    Project

    Make query, key and value vectors

  2. 2
    Score

    Dot product of the query with every key

  3. 3
    Scale and mask

    Divide by sqrt(d_k); hide future tokens if causal

  4. 4
    Softmax

    Scores become weights that sum to 1

  5. 5
    Mix values

    Weighted sum of value vectors

Blocks, stacks and model families

A transformer block combines multi-head attention with a feed-forward network that processes each token separately, with residual connections around both and layer normalisation. The original 2017 paper normalised after each sub-layer; most modern models normalise before it, which trains more stably in deep stacks.

Three families matter. Encoder-only models such as BERT see the whole sequence in both directions and suit classification and embeddings. Decoder-only models such as the GPT family use a causal mask and generate text one token at a time. Encoder-decoder models such as T5 read an input with an encoder and write an output with a decoder, which suits translation and summarisation. PyTorch provides nn.TransformerEncoderLayer and nn.Transformer as building blocks.

Pretrained use, fine-tuning or inference only

Inference only means running the model as it is, through prompts or by taking its embeddings as features for a simple classifier. It needs memory for the weights, roughly two bytes per parameter in 16-bit precision, plus working memory that grows with sequence length. A model of about 100 million parameters runs comfortably on a laptop CPU.

Full fine-tuning updates every weight. With Adam you also store gradients and two optimiser values per parameter, so memory can be several times the inference figure, and you need labelled data and an evaluation set. Parameter-efficient methods such as LoRA, covered in the next module, train a small number of extra weights instead. Start with the cheapest option and move up only when your evaluation shows it falls short.

  • Inference: weights plus activations
  • Full fine-tune: weights, gradients, optimiser state, activations
  • Embeddings plus logistic regression is a strong cheap baseline

Learn it in 5 short steps

About 50m each. Track them with a timer in your plan.

  1. 1
    Tokenise text into IDs~50m
  2. 2
    Map tokens to embeddings~50m
  3. 3
    Compute scaled dot-product attention~50m
  4. 4
    Stack transformer blocks~50m
  5. 5
    Compare pretrained use and fine-tuning~50m

Key points

  • Tokenisers split text into subwords, so a rare word can become several tokens.
  • Attention weights come from softmax(Q times K transposed, divided by the square root of d_k), then multiply V.
  • Positional information is added because attention on its own ignores word order.
  • Decoder-only models use a causal mask so each token sees only earlier tokens.
  • Inference needs memory for the weights; fine-tuning also needs gradients and optimiser state.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
import torch
import torch.nn.functional as F

torch.manual_seed(0)
seq, d = 4, 8
Q, K, V = torch.randn(seq, d), torch.randn(seq, d), torch.randn(seq, d)
scores = Q @ K.T / d ** 0.5          # (4, 4)
weights = F.softmax(scores, dim=-1)  # each row sums to 1
out = weights @ V                    # (4, 8)
print(weights.sum(dim=-1))

Scaled dot-product attention by hand; F.scaled_dot_product_attention does the same, faster.

Seeing how text becomes tokens

Prerequisites: pip install transformers. Step 1: load the GPT-2 tokeniser, a small free download. Step 2: encode a short sentence and a rare word. Step 3: look at the IDs and the token strings. Expected evidence: common words map to one token each, while a rare word splits into several pieces, and a leading space often belongs to the token. This explains why token counts differ from word counts and why the same model must always use its own tokeniser.

python
from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("gpt2")
for text in ["The cat sat on the mat.", "Photosynthesis"]:
    ids = tok(text)["input_ids"]
    print(len(ids), ids)
    print(tok.convert_ids_to_tokens(ids))

A causal attention mask in PyTorch

Step 1: create random queries, keys and values for 5 tokens. Step 2: call torch.nn.functional.scaled_dot_product_attention with is_causal=True. Step 3: compute the weights by hand with an upper-triangular mask to confirm the pattern. Expected evidence: the first row puts all its weight on token 0, and every row has zeros to the right of the diagonal, so no token attends to the future.

python
import torch, torch.nn.functional as F

torch.manual_seed(0)
q = k = v = torch.randn(1, 5, 8)
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
scores = q @ k.transpose(-2, -1) / 8 ** 0.5
mask = torch.triu(torch.ones(5, 5, dtype=torch.bool), diagonal=1)
weights = scores.masked_fill(mask, float("-inf")).softmax(-1)
print(weights[0].round(decimals=2))
print(torch.allclose(out, weights @ v, atol=1e-6))

Quick reference

  • Attention(Q, K, V) = softmax(Q K^T / sqrt(d_k)) V
  • Count length in tokens with the model's own tokeniser; English averages about 0.75 words per token
  • nn.Embedding(vocab_size, d_model) is a learned lookup table
  • Causal mask: each token sees only itself and earlier tokens
  • Encoder-only for classification, decoder-only for generation, encoder-decoder for translation
  • 16-bit weights take about 2 bytes per parameter; fine-tuning needs several times more memory
  • Try embeddings plus a simple classifier before fine-tuning

Common mistakes

  • Using a different tokeniser from the one the model was trained with.
  • Assuming a word equals a token when estimating length and cost.
  • Planning a full fine-tune without checking memory for gradients and optimiser state.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why do transformers add positional information to embeddings?

Question 2

2In attention, what do the softmax weights in one row add up to?

Question 3

3Which model family is the natural fit for generating text one token at a time?

Question 4

4Why does full fine-tuning need much more memory than inference?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create an embedding table for a vocabulary of 1,000 tokens with 16 dimensions and look up the vectors for token IDs [5, 42, 7].

  2. Exercise 2medium

    Implement attention(q, k, v, causal=False) by hand and check it against F.scaled_dot_product_attention for both causal settings.

  3. Exercise 3hard

    Build a tiny text classifier: nn.Embedding, one nn.TransformerEncoderLayer with batch_first=True, mean pooling over tokens, and a linear head to 2 classes. Run a dummy batch of 4 sequences of length 12.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What does GPT stand for?
Generative pre-trained transformer: a decoder-only transformer trained on large amounts of text to predict the next token.
Is a token the same as a word?
Not usually. A token can be a whole word, part of a word, a space plus a word, or a punctuation mark. Token counts are usually higher than word counts.
Do I need to understand the maths to use transformers?
You can use pretrained models without it, but knowing tokens, embeddings and attention helps you estimate cost, choose models and debug odd behaviour.

Go deeper

ShareXLinkedInWhatsApp