Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 3: Transformers and Language Models

Week 03 / Lesson 3

Building a transformer block and generating tokens

Connect attention to a complete decoder block and trace next-token prediction.

Section 3.1 1 of 7

Overview

Focus

Connect attention to a complete decoder block and trace next-token prediction.

Your route through the lesson

  • 3.2 Residual connections, normalization, and feed-forward layers
  • 3.3 Shifted targets and cross-entropy
  • 3.4 Autoregressive generation and basic sampling
  • 3.5 Put it into practice
  • 3.6 Guided comparison
  • 3.7 A fluent but false generated claim

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 3.2 2 of 7

Residual connections, normalization, and feed-forward layers

Focus

Connect masked attention, residual additions, normalization, and a feed-forward layer.

A decoder block does more than attention. A common arrangement normalizes hidden states, computes causal attention, adds its result back through a residual connection, then applies another normalized feed-forward transformation and another residual addition. A residual connection adds a branch output to its input and therefore requires compatible shapes.

Layer normalization rescales a token's hidden coordinates using statistics calculated for that representation and learned scale and bias. A feed-forward subnetwork applies learned affine transformations with an activation independently at each position. Attention mixes information across allowed positions; the feed-forward component transforms features within each position.

For hidden shape (B,T,d), both branches return (B,T,d), allowing additions. A feed-forward hidden width may be larger, such as 4d, then project back to d. Normalization, attention, and output projection have learned parameters. This block remains causal only if every cross-position mixing operation respects the mask; residual additions do not fix a leaking attention branch.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A residual branch is added to a tensor shaped (2,5,8). What output shape should that branch return?
2. Which decoder component mixes information across token positions?
3. Can a residual addition repair an attention branch that reads future tokens?

Section 3.3 3 of 7

Shifted targets and cross-entropy

Focus

Construct shifted targets and calculate a next-token cross-entropy.

A causal language model predicts the next token using preceding tokens. For sequence [A,B,C,D], training input is [A,B,C] and targets are [B,C,D]. At each position the output contains one score for every vocabulary entry. The target tells which vocabulary entry actually followed the available context.

Cross-entropy for the correct token with predicted probability p is −ln(p), where ln is the natural logarithm. A probability of 1 gives loss zero; smaller assigned probability gives larger loss. For correct-token probabilities [0.5,0.25,0.5], individual losses are about 0.693,1.386,0.693 and their mean is about 0.924.

PyTorch's cross_entropy expects raw scores and integer target identifiers; it performs a stable combined normalization and logarithmic loss. Reshape the batch/sequence positions into one example axis while retaining vocabulary as the class axis. Lower held-out next-token loss measures this prediction objective, not factual correctness, useful tool behavior, or instruction following.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. For token sequence [A,B,C,D], what are targets paired with input [A,B,C]?
2. What is cross-entropy for a correct-token probability of one?
3. A model has lower held-out next-token loss. What has directly improved?

Section 3.4 4 of 7

Autoregressive generation and basic sampling

Focus

Trace repeated generation and distinguish greedy selection from sampling.

During generation, the model receives a prefix, produces scores for its next token, selects one token, appends it, and repeats. Unlike training, the later continuation is not available as input before it has been generated. A context limit may require a defined truncation policy or termination.

Greedy selection chooses the largest probability. Sampling draws from the distribution, so repeated outputs can differ. For probabilities [0.6,0.3,0.1], greedy always chooses the first entry under the stated ordering, while sampling can choose any entry with nonzero probability. Temperature divides scores before normalization. For scores [2,0], temperature two gives [1,0], making probabilities about [0.731,0.269] instead of [0.881,0.119] at temperature one. The flatter distribution gives the alternative more chance without adding factual evidence.

Set a maximum number of generated tokens and a stop condition. An end marker is useful only if the model and tokenizer define it. A tiny randomly initialized decoder can execute all generation steps and still produce nonsense. A runnable loop is evidence about implementation, while useful language requires training and evaluation.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A generator has probabilities [0.6,0.3,0.1]. What does greedy selection choose?
2. What input is appended after a token is selected during autoregressive generation?
3. A random tiny decoder generates text without crashing. What is established?

Section 3.5 5 of 7

Put it into practice

Focus

Assemble and test a tiny causal decoder before training it.

Download week03.py and run python week03.py --lesson 3. The TinyDecoder class combines token and position embeddings, a masked attention branch, a positionwise feed-forward branch, normalization, and a vocabulary output projection. A Python class groups stored components with a forward method that defines how inputs produce outputs.

Read the declared dimensions before running. Token identifiers are integers shaped (batch,sequence); hidden states add a width axis; output scores end with vocabulary size. The script checks those shapes, shifted targets, finite next-token loss, and a future-token perturbation invariant. It then runs a short generation loop from the untrained model.

Keep the script in the exercise folder. Week 4 imports this same class to train rather than invent a new architecture. Passing these structural checks is the starting point: the random samples are labeled untrained and are not presented as useful language.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A decoder takes tokens shaped (2,4) with vocabulary size ten. What should its output scores be shaped?
2. Why keep the decoder class for Week 4 training?
3. The untrained decoder returns fluent-looking characters by chance. What is an appropriate label?

Section 3.6 6 of 7

Guided comparison

Focus

Follow one prefix through scores, a chosen token, and the next forward pass.

Suppose a vocabulary is [A,B,C] and the prefix is [A]. The decoder returns a score vector for the prefix position; after normalization it represents [0.2,0.5,0.3]. Greedy generation picks B and the next input becomes [A,B]. On the next pass, take the scores at the final prefix position, not the first one, to predict what follows B.

Training a sequence [A,B,C] instead uses input [A,B] and targets [B,C], evaluating both next-token positions together while masking future access. This is efficient because each position has its own causal context. It does not permit the first position to see B merely because B exists elsewhere in the batch tensor.

In the lab, compare the three-token loss calculation with an independent hand value and inspect generated length. A loop that always reads the first output position would keep predicting from the initial context rather than the growing prefix. Tests on length and final-position selection catch different errors.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Prefix [A] produces probabilities A=0.2,B=0.5,C=0.3. After greedy selection, what is the next prefix?
2. After input prefix [A,B], which output position predicts the next token?
3. Training input is [A,B] with targets [B,C]. May the first input position read B?

Section 3.7 7 of 7

A fluent but false generated claim

Focus

Separate fluent continuation from a supported factual claim.

A language model can assign high probability to familiar-sounding continuations that are false. Suppose a generated troubleshooting answer invents a command flag that matches the style of real flags but does not exist. Good next-token loss on unrelated text does not validate that command.

Define a task-specific check: look up the actual command documentation, compare the exact option name, and, in a safe environment, test the stated behavior on a harmless fixture. If a source is absent, the assistant should identify that uncertainty rather than treat fluent syntax as evidence.

This distinction will motivate source-grounded generation later. The model's learned parameters supply a continuation distribution; retrieved evidence and executable checks can provide separate support. Even a cited passage must actually support the claim, and a successful syntax parse proves less than a correct operation. Evaluate each claimed property with the corresponding evidence.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A model invents a plausible command flag. What best checks whether the flag exists?
2. A generated command parses as valid text. What has not yet been established?
3. A model’s output lacks supporting evidence for a factual claim. What should an application do?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Training a miniature language model →