Macalinao StudioLearnAll enriched lessons ↗
College path · 7 sectionsSwitch to high school ↗

College / LONGER LESSON 19

Encoder-decoder: read a source, write a target

Track source and target lengths through self-attention, cross-attention and training.

Preparation: Matrices and causal attention.

Plan 20–35 minutes with the activities; this is a study estimate, not a timed requirement. Both paths have complete narration. Your notes and progress are kept separately for each level.

Section 01 / 07

Separate the two streams

College path. Track source and target lengths through self-attention, cross-attention and training.

Preparation: Matrices and causal attention. Work through one section at a time. Predict the experiment result before changing its controls, then explain what the example leaves out.

The encoder produces source representations. The decoder produces target states while consulting those representations. Source length and generated length have different roles throughout the computation. Encoder output has source length S. Decoder states have target length T. Cross-attention permits T by S scores, while decoder self-attention uses T by T.

Worked step 1. Source has five tokens; target prefix has three.

Worked step 2. Encoder states have five rows.

Worked step 3. Decoder states have three rows.

Try it yourself. Which length determines cross-attention output rows?

Pause the recording and write your reasoning before continuing. The worked solution follows.

Reveal worked solution

Worked solution. Target query length: three in this example. Source length determines available keys and values.

Section 02 / 07

Read source context

Encoder self-attention can contextualize each valid source position using other source positions. A padding mask is distinct from causal masking and must match the actual sequence lengths. Apply source key-padding masks in encoder self-attention and decoder cross-attention. Query padding also affects which outputs and losses are meaningful. Framework mask conventions differ.

Worked step 1. Batch a five-token and a three-token source to width five.

Worked step 2. The shorter source has two padded slots.

Worked step 3. Only its first three keys are valid.

Try it yourself. Does padding increase the amount of source evidence?

Pause the recording and write your reasoning before continuing. The worked solution follows.

Reveal worked solution

Worked solution. No. It is a storage and batching convention. Mask it and exclude irrelevant output positions from evaluation.

Section 03 / 07

Generate from a legal prefix

During training, shifted target tokens feed a causally masked decoder. During generation, previous generated tokens form the prefix. These contexts can diverge after an error. Teacher forcing allows parallel training positions while preserving the causal dependency graph. Incremental decoding can cache prior keys and values; it does not require exposing future targets.

Worked step 1. Target is A, B, end.

Worked step 2. Decoder input is start, A, B.

Worked step 3. Targets align one step ahead.

Try it yourself. Why not feed A, B, end and predict the same positions?

Pause the recording and write your reasoning before continuing. The worked solution follows.

Reveal worked solution

Worked solution. That would leak the intended answers unless the objective explicitly removes them. Shift inputs and labels for ordinary next-token training.

Section 04 / 07

Look back through cross-attention

Each target query weights source values. Cross-attention need not use a triangular mask over the source because the source is already available. Source padding still must be excluded. For queries T by d and keys S by d, scaled scores are T by S. Multiplication by source values S by dv produces T by dv.

(T×S) · (S×dᵥ) → T×dᵥ

Worked step 1. Let T=3, S=5, d=4 and dv=6.

Worked step 2. Scores are 3 by 5.

Worked step 3. The context output is 3 by 6.

Try it yourself. Must the value width equal the key count?

Pause the recording and write your reasoning before continuing. The worked solution follows.

Reveal worked solution

Worked solution. No. Value width is a feature dimension. Key count is the number of source positions.

Section 05 / 07

Distinguish routing from explanation

A high attention weight shows where a particular computation routes information. It does not, by itself, establish a faithful human explanation of the final answer. Residual paths, multiple heads, transformations and later layers complicate causal attribution. Test interventions and output changes rather than equating one attention map with complete explanation.

Worked step 1. Change one source value while holding a toy score matrix fixed.

Worked step 2. Measure the output difference.

Worked step 3. Then change a score separately.

Try it yourself. Are these two interventions equivalent?

Pause the recording and write your reasoning before continuing. The worked solution follows.

Reveal worked solution

Worked solution. No. One changes the message; the other changes routing. A full model can couple both effects.

Section 06 / 07

Evaluate the complete task

Measure whether outputs preserve the source’s meaning and satisfy the task. A fluent translation or summary can still omit a condition, reverse a relation or invent a detail. Use task-appropriate metrics alongside targeted human error analysis. Record decoding configuration and test source perturbations, long inputs and domain shifts; a single overlap metric is incomplete.

Worked step 1. Take a three-fact source and a two-sentence summary.

Worked step 2. Check all three facts and any added claims.

Worked step 3. Record omissions separately from inventions.

Try it yourself. Does grammatical output prove source faithfulness?

Pause the recording and write your reasoning before continuing. The worked solution follows.

Reveal worked solution

Worked solution. No. Fluency and fidelity are different properties and should be evaluated separately.

Section 07 / 07

Mastery and transfer

Bring the pieces together. First answer the checkpoint without the worked solutions. Then explain the mechanism in your own words, using one numerical example from this lesson.

Decoder cross-attention queries normally come from… Option 1: Source padding slots. Option 2: Target decoder states. Option 3: Future target labels.

Pause here and choose an answer before continuing. The checkpoint explanation follows.

Reveal worked solution

The correct choice is option 2: Target decoder states. Target states query the encoded source; future labels remain unavailable.

Transfer task. Change one assumption in the worked example. State your prediction, calculate or test it in Workbench, then explain whether the result supports your prediction.

Reveal worked solution

Self-check rubric. Name the changed assumption, keep the other inputs fixed, show at least one intermediate calculation, and distinguish what the toy example guarantees from what would require a trained model or a real measurement.

MODERN MODEL CASE STUDY

DeepSeek V4.1 Flash: where this idea goes next

Follow how the decoder obtains global keys and values from encoder states. Follow the worked examples, then evaluate the reported gains and their limits.

Open the college case study →

Added October 21, 2026. This optional extension has its own complete local narration.

Sources and scope

Original worked examples and teaching text, grounded in these primary references. Numerical fixtures explain mechanisms; model quality and hardware performance require separate measurements. Both levels share key examples, with different explanations and checkpoints.

Reset this college path?

This removes only this path’s notes, progress and experiments from this browser.