Decoder Transformer Mechanics

The transformer should be a set of owned tensor operations rather than a diagram or framework class. This section connects shapes, causal information flow, modern block choices and parameter arithmetic.

Section 2 of 5 · 7 units · about 32 hours

0/7

By the end you can Build a tiny decoder from blank tensor operations, derive every intermediate shape and parameter count, and pass causal intervention, mask, RoPE-offset, grouped-head, residual, normalization, tying and differential forward or backward tests.

Units

Build it

Mini project · about 10 to 14 hours

Tiny decoder with an independent oracle

Build a configurable decoder-only model from tensor operations in the same repository, and prove it correct without trusting a training curve: public snapshot tests for each component, a slow per-head reference for attention, and intervention tests for causality.

  1. 1Implement linear, embedding, RMSNorm, SwiGLU, RoPE, softmax and scaled dot-product attention from tensor operations, and pass the matching CS336 tests in tests/test_model.py and tests/test_nn_utils.py.
  2. 2Add grouped KV heads to your attention with an explicit map, query head reads KV head , so that MHA and MQA are the two ends of one code path.
  3. 3Write a slow reference that loops over heads with sliced weights, and compare outputs and gradients in float64 with your batched path for MHA, GQA and MQA.
  4. 4Assemble the decoder from one config object with optional embedding tying, and pass test_transformer_block, test_transformer_lm and test_transformer_lm_truncated_input.
  5. 5Derive the parameter count of your config by hand and assert that it equals the count of unique registered parameters, tied and untied.
  6. 6Write property tests showing RoPE preserves norms with scores depending only on relative position including offset equivalence, a future-token change leaves earlier outputs unchanged, and batch rows stay independent.
What you hand in
  • The model package: components, config, grouped attention and the tied or untied head.
  • Your test suite: the head-loop oracle, float64 gradient comparisons, suffix-intervention tests and the parameter-count assertion.
  • A one-page shape and parameter sheet for your config, derived by hand.
How to check it
How it's graded

Component correctness

Pass: All CS336 model tests and the softmax test pass.

Great: Your own tests add fully masked rows, padding plus causal masks and non-contiguous inputs.

Independent oracle

Pass: The batched attention matches the head loop on outputs.

Great: Outputs and all projection gradients match in float64 for MHA, GQA and MQA within a stated tolerance.

Causality

Pass: Changing a suffix leaves prefix logits unchanged.

Great: Your tests also show that the change does reach the logits at and after the edited position, and they cover batch independence.

Grouped heads and RoPE

Pass: Your batched attention matches the head-loop reference for MHA, GQA and MQA, and the RoPE, causality and batch-independence tests pass.

Great: You explain why an interleaved KV expansion differs from the PyTorch grouping convention, and your weights load correctly under yours.

Accounting

Pass: The hand-derived parameter count equals the registered count.

Great: The sheet also gives the dominant forward FLOP terms and predicts how each scales when the sequence length doubles.

Resources

  • Modern LLM Notebook - decoder construction pathWalking Labs

    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

    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

    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.

  • PyTorch scaled dot product attention referencePyTorch

    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.

  • nanoGPT - residual projection initializationAndrej Karpathy

    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.

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

    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.