Unit 7 of 7 · about 6 hours · derive, implement

Assembling and verifying a decoder

Correct components do not automatically make a correct model. Assembly checks catch final-norm, configuration, weight-sharing and information-flow defects before training hides them.

You'll be able to

  • Assemble a configurable decoder from owned tensor components, ending in raw logits.
  • Derive component parameter counts and dominant forward matrix-multiplication terms, distinguishing tied and untied heads.
  • Verify causal prefix equivalence and match an independent reference under transferred weights.
  • Contrast the decoder's causal next-token use with BERT's bidirectional masked-token use.

Covers

Embedding-output weight tying and final logitsDecoder composition and configuration ownershipParameter counts and dominant operation termsSlow attention oracle and causal intervention testsEncoder-only BERT contrast
1

Read

In this order, only the parts listed

0 of 4 done

  1. Decoder assembly, configuration and tyingModern LLM Notebook - decoder construction path

    Implementing MiniGPT from scratch: Implementation of MiniGPT and Logits and predictions; Reading the nanoGPT source code: The main thread of GPT.forward and Weight Tying: sharing weights between input and output

    Read architecture and shape flow only. Skip training, generation demos and the full GPT-2 parameter survey; substitute your modern blocks for the teaching version.

  2. Full tensor model and tied parameter countLLMs from Scratch companion - attention and GPT construction

    Section 4.6, Coding the GPT model, through the weight-tying and memory-count discussion

    Skip the larger GPT-2 configuration exercise and section 4.7 generation. Keep the final normalization and raw-logit contract.

  3. Full model and resource accountingStanford CS336 Assignment 1 - model contract

    Section 3.1, Transformer LM, printed pp. 13 to 14; section 3.5, The Full Transformer LM, including (transformer_lm), Resource accounting and (transformer_accounting), printed pp. 26 to 28

    Do transformer_accounting parts (a) to (c). Leave the model-size sweep and long-context sweep in parts (d) and (e) for the model-arithmetic section.

  4. Optional encoder-only contrastModern LLM Notebook - decoder construction path

    Decoder-Only Architecture: the Encoder-Only, Encoder-Decoder and next-token-training comparison

    Use only for the optional BERT contrast. Do not start an encoder implementation or model survey.

2

Focus on

  • One configuration owns , , layer count , query and KV head counts, FFN width , RoPE , context policy and tying. Validate divisibility before creating weights; different layers share a design, not all their parameters.
  • A tied head uses the same Parameter as input lookup and computes . Equal initial values in separate Parameters are not tying; gradients from lookup and classification must accumulate into one weight.
  • For bias-free MHA with two RMSNorms and SwiGLU per block, untied parameters are . Tying subtracts ; standard RoPE adds no learned parameters.
  • List dense forward terms: per layer for MHA projections, for and , and for SwiGLU matrices; the vocabulary head adds . Use the slow per-head oracle and suffix interventions to check causality, not a loss curve.
Common mistakes · 3
  • Adding softmax inside the model's training forward path. Return raw logits; the loss owns normalization.
  • Matching a CS336 snapshot with a tied output head. Its supplied embedding and lm_head weights are independent; test untied mode there and tying separately.
  • Checking causality only in the attention matrix. Cross-token normalization or a composition error can still alter prefix logits.
3

Try it yourself

Closed-book, before checking anything

Build a two-layer decoder with , , and , using bias-free MHA, RoPE, two RMSNorms per block and one final RMSNorm. Derive 7,760 untied or 7,248 tied parameters, reconcile with unique registered weights, and verify unchanged prefix logits after replacing every suffix token.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Does tying the head remove the vocabulary projection's compute?Answer

    No. It removes a separate weight matrix, but still costs about dense FLOPs.

  2. 2.What should changing tokens after zero-based position do to logits through ?Answer

    Nothing within numerical tolerance, with identical prefix positions and deterministic evaluation. Those logits may depend on tokens at positions at most , not the suffix.

  3. 3.If sequence length doubles at fixed batch and width, which dominant terms quadruple?Answer

    Dense and attention-times- work, and the stored score/probability matrices, scale quadratically. Projection and FFN terms scale linearly with length.

  4. 4.Why cannot an ordinary BERT forward pass serve as this causal decoder oracle?Answer

    BERT uses bidirectional attention for masked-token prediction, so its representations can use right context. The decoder must preserve the causal prefix boundary.

5

Practice

  • CS336 Assignment 1: transformer_lm

    Problem (transformer_lm), section 3.5; implement run_transformer_lm and pass test_transformer_lm and test_transformer_lm_truncated_input

    Use the untied MHA contract for snapshots. Add prefix-alone versus full-sequence comparisons, adversarial suffix changes, tied-weight identity and gradient accumulation checks, and a full-model comparison using the slow attention oracle. Keep dropout off.

  • CS336 Assignment 1: transformer_accounting, parts (a) to (c)

    Problem (transformer_accounting), printed pp. 27 to 28: parameter and FP32 weight memory count, forward matrix multiplies and dominant FLOPs

    This written problem has no public accounting test. Check its algebra against your tiny model's unique parameter count, using tests/test_model.py's model tests for implementation correctness; do not allocate the XL model.

You're done when

Both full-model public tests pass, the tiny parameter count matches the derivation, and your model matches the slow reference and preserves prefix logits under suffix replacement in tied and untied modes.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 3 more in the section
  • Modern LLM Notebook - decoder construction pathWalking Labs · primary

    Work through English notebooks 03-embedding, 04-position-encoding, 05-transformer-block, 06-mini-gpt and the selected normalization, RoPE, GQA and SwiGLU comparisons in 08-gpt2-to-modern-models. Re-derive shapes and rerun with changed dimensions.

  • LLMs from Scratch companion - attention and GPT constructionSebastian Raschka · required

    Use the ch03 attention notebooks and ch04 model code. Rebuild the model without a high-level Transformer module and compare one forward and backward path with an independent small reference.

  • Stanford CS336 Assignment 1 - model contractStanford University · required

    Use the named linear, embedding, rmsnorm, positionwise_feedforward, rope, softmax, scaled_dot_product_attention, multihead_self_attention, transformer_block, transformer_lm and transformer_accounting specifications and public tests. Keep implementation independent and respect the course AI and honor-code boundary.

Also in this section

  • PyTorch scaled dot product attention referencePyTorch · support

    Use the functional contract only after the explicit attention oracle passes. Transfer identical weights and masks, compare outputs and gradients, and explain dtype, causal and dropout behavior from the documented semantics.

  • Deep-ML candidate - three transformer closing drillsDeep-ML · optional

    After the platform quality sample passes, attempt at most problems 490, 53 and 904 as changed-prompt drills for attention shapes and multi-head composition. Preserve independent tests; a judge result does not replace the section checkpoint.

  • nanoGPT - residual projection initializationAndrej Karpathy · support

    Read model.py: MLP, Block, GPT.__init__'s special scaled initialization of c_proj.weight, and GPT._init_weights. Contrast the depth-dependent residual initialization with CS336's component initialization; do not adopt the training or generation code.