44 / 90

Day 44: Autoregressive Causal Masking and Strict Invariance

Enforce the autoregressive constraint in generative language models. Construct lower-triangular causal masks, prove that softmax maps -inf to exact zero probability, and empirically verify that future token perturbations have zero impact on past representations.

Models & Training 480 active minutes (8 hours focused study)
01 120 min

Autoregressive Constraint and Lower-Triangular Causal Masking

Agent-Assisted Engineering Check

Prerequisites

Day 43 attention mechanisms and scaling derivations.

Learning Objective

Define the autoregressive constraint for decoder language models, construct the lower-triangular causal mask matrix M, and derive masked scores S_masked = S + M.

Instructions

Required work: explain why a causal decoder must satisfy P(x_1, ..., x_T) = prod_{t=1}^T P(x_t | x_{ t, allowing the model to cheat during training by trivial copying. Define the additive causal mask M in R^{T x T} such that M_{i,j} = 0 for j <= i and M_{i,j} = -inf for j > i. For sequence length T=3, explicitly write out M. Using the Day 43 scaled scores S = [[2.0, 0.0, 2.0], [0.0, 3.0, 2.0], [1.0, 1.5, 2.0]], compute the masked score matrix S_masked = S + M.

Practice & Prediction Log

1. Write out the 3x3 causal mask matrix M.
2. Write out the masked score matrix S_masked = S + M.
3. What happens if an implementation accidentally puts 0 above the diagonal and -inf below?

Independent Mastery Criterion

Exact formulation of lower-triangular mask M and derivation of the 3x3 S_masked matrix.

Authoritative Source Resources & Provenance

linking arXiv.org perpetual non-exclusive license / Open Access

Attention Is All You Need

Author: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | Original Source Link ↗

Relevant Section / Range: Section 3.2.3: Masked Multi-Head Attention in the decoder preventing leftward information flow

Verified Version & Date: NeurIPS 2017 / arXiv:1706.03762v7 (Verified: 2026-10-30)

Selection Rationale:

The foundational primary literature establishing scaled dot-product attention, multi-head projection mechanisms, and autoregressive causal masking.

Source Prerequisites:

Linear algebra, matrix multiplication, softmax probability distributions

Safe Fallback (Offline Resilience):

Complete original algebraic derivations, matrix examples, variance proofs, and tensor diagrams are self-contained in the curriculum text without external document dependency.

Compared Candidate Sources & Selection Analysis (3)

Pioneered additive attention in RNNs, but Vaswani scaled dot-product attention replaced additive alignment in modern LLM architectures due to parallel matrix multiplication speed.

Introduces relative positional biases into attention; deferred to subsequent positional embedding modules after absolute scaled attention is thoroughly mastered.

Karpathy nanoGPT (causal self-attention module) ↗ compared_selected_co_primary [MIT]

Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.

linking MIT

The Annotated Transformer

Author: v2022: Austin Huang, Suraj Subramanian, Jonathan Sum, Khalid Almubarak, Stella Biderman; original: Sasha Rush (Harvard NLP) | Original Source Link ↗

Relevant Section / Range: subsequent_mask implementation using torch.triu and triangular boolean masking

Verified Version & Date: Updated 2022 edition (Verified: 2026-10-30)

Selection Rationale:

Widely used pedagogical commentary that pairs every paragraph of the original Vaswani paper with an executable, testable code cell.

Source Prerequisites:

Intermediate Python, PyTorch broadcasting and tensor slicing semantics

Safe Fallback (Offline Resilience):

The curriculum provides standalone hand-worked numerical tables, explicit causal mask verification scripts, and offline analytical proofs.

Compared Candidate Sources & Selection Analysis (3)
Jay Alammar: The Illustrated Transformer ↗ compared_alternative [CC BY-NC 4.0]

Spectacular visual diagrams and intuitive color-coding, but lacks executable tensor code and formal numerical shape validation.

Stanford CS224N: Natural Language Processing with Deep Learning (Lecture 10) ↗ compared_alternative [Stanford University Copyright]

Rigorous academic slides and video lectures, but access to assignment grading is restricted to Stanford enrolled students.

Vaswani et al.: Attention Is All You Need ↗ compared_selected_co_primary [arXiv Open Access]

The original primary paper; Annotated Transformer annotates it directly.

02 120 min

Softmax with Causal Masking: Exact Step-by-Step Matrix Derivation

Independent Mastery Check

Prerequisites

Complete Day 44 Activity 1.

Learning Objective

Compute row-wise softmax over masked scores with max-shift stability, derive causal attention weights A_causal, and calculate the masked output representations.

Instructions

Required work: calculate row-wise softmax on S_masked = [[2.0, -inf, -inf], [0.0, 3.0, -inf], [1.0, 1.5, 2.0]]. For row 0: max over finite entries is 2.0. exp([2.0-2.0, -inf, -inf]) = [1.0, 0.0, 0.0]. Normalization yields A_causal[0, :] = [1.0, 0.0, 0.0]. For row 1: max is 3.0. exp([-3.0, 0.0, -inf]) = [exp(-3), 1.0, 0.0] ~= [0.049787, 1.0, 0.0]. Sum = 1.049787. A_causal[1, :] = [0.047426, 0.952574, 0.0]. For row 2: all entries unmasked, yielding [0.186324, 0.307196, 0.506480]. Compute causal output Out_causal = A_causal V using Day 43 V = [[1,0], [0,2], [1,1]].

Practice & Prediction Log

1. Compute A_causal row 0, row 1, and row 2 to 6 decimal places.
2. Compute Out_causal = A_causal V for all three rows.
3. Compare Out_causal[0] with the unmasked Out[0] from Day 43 and explain why they differ.

Independent Mastery Criterion

Exact calculation of A_causal rows and Out_causal vectors matching reference values to 4+ decimal places.

Authoritative Source Resources & Provenance

linking MIT

The Annotated Transformer

Author: v2022: Austin Huang, Suraj Subramanian, Jonathan Sum, Khalid Almubarak, Stella Biderman; original: Sasha Rush (Harvard NLP) | Original Source Link ↗

Relevant Section / Range: Attention masking implementation: masked_fill with -1e9 before softmax

Verified Version & Date: Updated 2022 edition (Verified: 2026-10-30)

Selection Rationale:

Widely used pedagogical commentary that pairs every paragraph of the original Vaswani paper with an executable, testable code cell.

Source Prerequisites:

Intermediate Python, PyTorch broadcasting and tensor slicing semantics

Safe Fallback (Offline Resilience):

The curriculum provides standalone hand-worked numerical tables, explicit causal mask verification scripts, and offline analytical proofs.

Compared Candidate Sources & Selection Analysis (3)
Jay Alammar: The Illustrated Transformer ↗ compared_alternative [CC BY-NC 4.0]

Spectacular visual diagrams and intuitive color-coding, but lacks executable tensor code and formal numerical shape validation.

Stanford CS224N: Natural Language Processing with Deep Learning (Lecture 10) ↗ compared_alternative [Stanford University Copyright]

Rigorous academic slides and video lectures, but access to assignment grading is restricted to Stanford enrolled students.

Vaswani et al.: Attention Is All You Need ↗ compared_selected_co_primary [arXiv Open Access]

The original primary paper; Annotated Transformer annotates it directly.

linking MIT

nanoGPT: Simplest, Fastest Repository for Training and Finetuning Medium GPTs

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: model.py: att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float("-inf"))

Verified Version & Date: GitHub master commit (Verified: 2026-10-30)

Selection Rationale:

Detailed modern reference implementation of clean, idiomatic batched causal self-attention in fewer than 60 lines of code.

Source Prerequisites:

Python, NumPy/PyTorch tensor fundamentals, and feed-forward network basics

Safe Fallback (Offline Resilience):

Self-contained step-by-step tensor derivations, numeric matrix traces, and pure Python/NumPy implementations are directly provided in curriculum exercises.

Compared Candidate Sources & Selection Analysis (3)
Hugging Face transformers (GPT2Attention) ↗ compared_rejected_for_foundations [Apache-2.0]

Includes extensive production abstraction layers, configuration polymorphism, and cache tracking that obscure direct mathematical tensor operations for beginner learners.

Harvard NLP: The Annotated Transformer ↗ compared_selected_co_primary [MIT]

Selected jointly: provides line-by-line literary commentary mapping equations directly to PyTorch tensors.

Expanded video walkthrough; software is MIT-licensed while video audio/subtitles remain linking-only without transcript import.

03 120 min

Causal Invariance Perturbation Experiment and Proof

Agent-Assisted Engineering Check

Prerequisites

Complete Day 44 Activity 2.

Learning Objective

Empirically verify and algebraically prove that perturbing future tokens leaves earlier attention distributions and representations strictly unchanged.

Instructions

Required work: perform a strict perturbation test on the sequence. Replace token 2 (the future token) with extreme random values: q_2' = [99.0, -42.0, 13.0, 7.0], k_2' = [-50.0, 12.0, 34.0, -8.0], v_2' = [100.0, -200.0]. Recompute S_masked, A_causal, and Out_causal. Prove that diff(A_causal[0], A_causal_pert[0]) = 0.0, diff(A_causal[1], A_causal_pert[1]) = 0.0, diff(Out[0], Out_pert[0]) = 0.0, and diff(Out[1], Out_pert[1]) = 0.0. Contrast this invariance with an unmasked attention layer where all preceding rows are corrupted.

Practice & Prediction Log

1. Prove algebraically why row i of A_causal cannot depend on any k_j or v_j for j > i.
2. Report the numerical differences for rows 0, 1, and 2 under the perturbation of token 2.
3. How does this causal invariance guarantee the correctness of autoregressive KV-cache inference?

Independent Mastery Criterion

Rigorous algebraic proof of future-independence and empirical demonstration of 0.0 diff on historical positions.

Authoritative Source Resources & Provenance

linking arXiv.org perpetual non-exclusive license / Open Access

Attention Is All You Need

Author: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | Original Source Link ↗

Relevant Section / Range: Section 3.2.3: Autoregressive self-attention property ensuring causal factorization

Verified Version & Date: NeurIPS 2017 / arXiv:1706.03762v7 (Verified: 2026-10-30)

Selection Rationale:

The foundational primary literature establishing scaled dot-product attention, multi-head projection mechanisms, and autoregressive causal masking.

Source Prerequisites:

Linear algebra, matrix multiplication, softmax probability distributions

Safe Fallback (Offline Resilience):

Complete original algebraic derivations, matrix examples, variance proofs, and tensor diagrams are self-contained in the curriculum text without external document dependency.

Compared Candidate Sources & Selection Analysis (3)

Pioneered additive attention in RNNs, but Vaswani scaled dot-product attention replaced additive alignment in modern LLM architectures due to parallel matrix multiplication speed.

Introduces relative positional biases into attention; deferred to subsequent positional embedding modules after absolute scaled attention is thoroughly mastered.

Karpathy nanoGPT (causal self-attention module) ↗ compared_selected_co_primary [MIT]

Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.

linking MIT

nanoGPT: Simplest, Fastest Repository for Training and Finetuning Medium GPTs

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: model.py: CausalSelfAttention buffer verification ensuring past tokens remain strictly invariant

Verified Version & Date: GitHub master commit (Verified: 2026-10-30)

Selection Rationale:

Detailed modern reference implementation of clean, idiomatic batched causal self-attention in fewer than 60 lines of code.

Source Prerequisites:

Python, NumPy/PyTorch tensor fundamentals, and feed-forward network basics

Safe Fallback (Offline Resilience):

Self-contained step-by-step tensor derivations, numeric matrix traces, and pure Python/NumPy implementations are directly provided in curriculum exercises.

Compared Candidate Sources & Selection Analysis (3)
Hugging Face transformers (GPT2Attention) ↗ compared_rejected_for_foundations [Apache-2.0]

Includes extensive production abstraction layers, configuration polymorphism, and cache tracking that obscure direct mathematical tensor operations for beginner learners.

Harvard NLP: The Annotated Transformer ↗ compared_selected_co_primary [MIT]

Selected jointly: provides line-by-line literary commentary mapping equations directly to PyTorch tensors.

Expanded video walkthrough; software is MIT-licensed while video audio/subtitles remain linking-only without transcript import.

04 120 min

Independent Mastery Check: Causal Leaks, Mask Bugs, and Invariance Assertions

Independent Mastery Check

Prerequisites

Activities 44-01 through 44-03.

Learning Objective

Demonstrate unassisted mastery in identifying causal leak bugs, tracing masked attention for a 2-token sequence, and asserting invariant representations under declared AI-free conditions.

Instructions

Required work: work independently without AI assistance or external calculators. For T=2 with scaled scores S = [[3.0, 1.0], [2.0, 4.0]] and V = [[1.0, 2.0], [3.0, 0.0]]: 1. Construct the 2x2 causal mask M and write S_masked. 2. Calculate the exact 2x2 causal attention matrix A_causal. 3. Calculate Out_causal. 4. If token 1 is replaced with arbitrary new vectors, prove what happens to Out_causal[0]. 5. Complete the objective knowledge check quiz.

Practice & Prediction Log

1. Write S_masked for the 2x2 setup.
2. Compute A_causal to 6 decimal places.
3. Compute Out_causal = A_causal V.
4. State the exact difference in Out_causal[0] if token 1 is perturbed.
5. Complete the 3-question quiz.

Objective Knowledge Check: Causal Masking and Invariance

Answer the following diagnostic questions to verify your understanding. Select your declared assistance condition before submitting.

Declared Assistance Condition

Note: AI-free work is an honest declared condition, not claimed surveillance.

1.

What is the primary operational role of the lower-triangular causal mask in autoregressive generation?

2.

When constructing an additive causal mask for scaled scores, what value must be assigned to upper-triangular entries (j > i)?

3.

If token 2 in a 3-token sequence (t in {0, 1, 2}) is perturbed with arbitrary values, how do the attention weights and output representation at position 0 change under strict causal masking?

Attempt History & Evidence

    Independent Mastery Criterion

    Accurate derivation of 2x2 causal attention and output, rigorous invariance assertion, and 100% quiz score.

    Authoritative Source Resources & Provenance

    linking MIT

    The Annotated Transformer

    Author: v2022: Austin Huang, Suraj Subramanian, Jonathan Sum, Khalid Almubarak, Stella Biderman; original: Sasha Rush (Harvard NLP) | Original Source Link ↗

    Relevant Section / Range: subsequent_mask unit tests and triangular boundary checks

    Verified Version & Date: Updated 2022 edition (Verified: 2026-10-30)

    Selection Rationale:

    Widely used pedagogical commentary that pairs every paragraph of the original Vaswani paper with an executable, testable code cell.

    Source Prerequisites:

    Intermediate Python, PyTorch broadcasting and tensor slicing semantics

    Safe Fallback (Offline Resilience):

    The curriculum provides standalone hand-worked numerical tables, explicit causal mask verification scripts, and offline analytical proofs.

    Compared Candidate Sources & Selection Analysis (3)
    Jay Alammar: The Illustrated Transformer ↗ compared_alternative [CC BY-NC 4.0]

    Spectacular visual diagrams and intuitive color-coding, but lacks executable tensor code and formal numerical shape validation.

    Stanford CS224N: Natural Language Processing with Deep Learning (Lecture 10) ↗ compared_alternative [Stanford University Copyright]

    Rigorous academic slides and video lectures, but access to assignment grading is restricted to Stanford enrolled students.

    Vaswani et al.: Attention Is All You Need ↗ compared_selected_co_primary [arXiv Open Access]

    The original primary paper; Annotated Transformer annotates it directly.

    linking MIT

    nanoGPT: Simplest, Fastest Repository for Training and Finetuning Medium GPTs

    Author: Andrej Karpathy | Original Source Link ↗

    Relevant Section / Range: model.py: causal mask shape registration and forward assertion

    Verified Version & Date: GitHub master commit (Verified: 2026-10-30)

    Selection Rationale:

    Detailed modern reference implementation of clean, idiomatic batched causal self-attention in fewer than 60 lines of code.

    Source Prerequisites:

    Python, NumPy/PyTorch tensor fundamentals, and feed-forward network basics

    Safe Fallback (Offline Resilience):

    Self-contained step-by-step tensor derivations, numeric matrix traces, and pure Python/NumPy implementations are directly provided in curriculum exercises.

    Compared Candidate Sources & Selection Analysis (3)
    Hugging Face transformers (GPT2Attention) ↗ compared_rejected_for_foundations [Apache-2.0]

    Includes extensive production abstraction layers, configuration polymorphism, and cache tracking that obscure direct mathematical tensor operations for beginner learners.

    Harvard NLP: The Annotated Transformer ↗ compared_selected_co_primary [MIT]

    Selected jointly: provides line-by-line literary commentary mapping equations directly to PyTorch tensors.

    Expanded video walkthrough; software is MIT-licensed while video audio/subtitles remain linking-only without transcript import.