24 / 90

Day 24: Tensors, Broadcasting, Reshape, and Memory Ledgers

Generalize vectors and matrices to rank-n tensors with named axes (batch, time, channel); verify broadcasting rules and failure cases, reshape and view-versus-copy behavior, and memory ledgers for real model tensors. Every activity records prediction, observation, review, and recovery inside the 480-minute ledger.

Mathematics & Algorithmic Foundations 480 active minutes (8 hours focused study)
01 120 min

Tensors: axes, ranks, and model weight blocks

Assistance allowed only after prediction and observed evidence are recorded.

Prerequisites

Complete Day 23; use the listed recovery link if matrix shapes are shaky.

Learning Objective

Describe a tensor as an n-dimensional array whose rank is its number of axes; name the batch, time, and channel axes of model tensors; and trace an embedding lookup from a table E of shape (V x d) to an output of shape (B, T, d).

Instructions

A scalar is rank 0, a vector rank 1, a matrix rank 2, and a batch of sequences of embeddings is a rank-3 tensor of shape (B, T, d): batch axis, time axis, channel axis. An embedding lookup gathers rows: ids of shape (B, T) into table E of shape (V, d) produce output (B, T, d). Weight matrices are rank-2 tensors; a hidden state carrying batch and time is rank 3.

Practice & Prediction Log

A small model has vocabulary V = 50000 and embedding width d = 512. Predict: (a) the number of scalar weights in table E; (b) the output shape when ids of shape (B=2, T=3) are looked up; (c) how many float32 values that output holds and its byte size.

Independent Mastery Criterion

Your ledger derives (B, T, d) from (V, d) and (B, T) without prompting, you compute both element counts exactly, and you can name the physical meaning of each axis (which item, which position, which feature).

Authoritative Source Resources & Provenance

linking BSD 3-Clause License

NumPy Reference: The N-dimensional array (ndarray)

Author: NumPy Developers | Original Source Link ↗

Relevant Section / Range: ndarray.ndim / ndarray.shape and axis ordering

Verified Version & Date: NumPy 2.x documentation (Verified: 2026-10-30)

Selection Rationale:

Primary semantics for ndarray shape, strides, reshape orders, and view-versus-copy behavior used in tensor memory accounting.

Source Prerequisites:

Basic Python

Safe Fallback (Offline Resilience):

Shape, stride, and memory-ledger exercises are fully explained with local runnable examples.

Compared Candidate Sources & Selection Analysis (2)
PyTorch Documentation: torch.Tensor ↗ compared_alternative [Modified BSD]

Equivalent tensor semantics in the framework used later in the curriculum; NumPy reference selected to keep Days 22-24 dependency-free.

NumPy User Guide: Broadcasting ↗ compared_selected_for_days_22_24 [BSD 3-Clause License]

Selected as co-primary for Day 24: the broadcasting rules page pairs with the ndarray attribute reference.

linking 3Blue1Brown copyright (all rights reserved); site FAQ permits only short clips under stated conditions No video, audio, transcript or frame redistribution permitted

Essence of Linear Algebra

Author: Grant Sanderson (3Blue1Brown) | Original Source Link ↗

Relevant Section / Range: Chapter 3 review: a matrix is a rank-2 tensor

Verified Version & Date: 2016-2023 (Verified: 2026-10-30)

Selection Rationale:

Unequaled geometric and visual intuition for vectors, linear transformations, matrix multiplication, and inverses before tensor operations.

Source Prerequisites:

High-school coordinate geometry

Safe Fallback (Offline Resilience):

Geometric explanations, worked formulas, and coordinate exercises are fully provided as original lesson text.

Compared Candidate Sources & Selection Analysis (2)
MIT OCW 18.06 Linear Algebra (Prof. Gilbert Strang) ↗ compared_alternative [CC BY-NC-SA 4.0]

Established textbook/lecture approach, strong mathematical rigor alongside 3Blue1Brown visual intuition.

Linear Algebra Done Right (Sheldon Axler) ↗ compared_rejected_for_curriculum [CC BY-NC (4th edition, Open Access)]

Theoretical determinant-free proof structure is mathematically elegant but less aligned with computational tensor engineering.

02 120 min

Broadcasting rules and failure diagnosis

Independent practice: record predictions before checking results; assistance only after evidence is logged.

Prerequisites

Complete the previous activity; use the listed recovery link if blocked.

Learning Objective

Apply the broadcasting rule - align trailing axes; each pair of dimensions must be equal or one must be 1 - to predict outputs and diagnose failures before running code.

Instructions

Broadcasting applies to tensors of any rank: compare shapes right-to-left. Missing axes count as size 1 and a size-1 axis is stretched without copying memory. Bias addition in an MLP, (B, T, d_ff) + (d_ff,), broadcasts the bias over batch and time. A pair like (2, 3) and (4,) fails because 3 != 4 on the last axis.

Practice & Prediction Log

Predict each result or its failure: (a) [[1,2,3],[4,5,6]] + [10,20,30]; (b) [[1],[2]] + [[10,20,30]]; (c) shape (2,3) + shape (4,); (d) hidden (32,128,768) + bias (768,).

Independent Mastery Criterion

You predict all four outcomes (three shapes and one failure) unaided, reproduce both numeric results exactly, and explain why (2,3) + (4,) must fail under the trailing-axis rule.

Authoritative Source Resources & Provenance

linking BSD 3-Clause License

NumPy User Guide: Broadcasting

Author: NumPy Developers | Original Source Link ↗

Relevant Section / Range: General broadcasting rules and incompatible-shape errors

Verified Version & Date: NumPy 2.x documentation (Verified: 2026-10-30)

Selection Rationale:

Normative definition of broadcasting rules, shape mismatch errors, and implicit axis expansion shared by NumPy, PyTorch, and other tensor frameworks.

Source Prerequisites:

Basic Python and array indexing

Safe Fallback (Offline Resilience):

Broadcasting rules, failure cases, and memory-layout caveats are fully explained with local runnable examples.

Compared Candidate Sources & Selection Analysis (2)
PyTorch Documentation: Broadcasting semantics ↗ compared_alternative [Modified BSD]

Equivalent rules for PyTorch tensors; NumPy chosen because Day 24 exercises run without a PyTorch dependency, while the rule wording is identical.

NumPy Reference: The N-dimensional array (ndarray) ↗ compared_selected_for_days_22_24 [BSD 3-Clause License]

Selected as co-primary for Day 24: normative shape/strides/reshape semantics complementing the broadcasting rules page.

linking BSD 3-Clause License

NumPy Reference: The N-dimensional array (ndarray)

Author: NumPy Developers | Original Source Link ↗

Relevant Section / Range: Implicit dimension expansion for element-wise ops

Verified Version & Date: NumPy 2.x documentation (Verified: 2026-10-30)

Selection Rationale:

Primary semantics for ndarray shape, strides, reshape orders, and view-versus-copy behavior used in tensor memory accounting.

Source Prerequisites:

Basic Python

Safe Fallback (Offline Resilience):

Shape, stride, and memory-ledger exercises are fully explained with local runnable examples.

Compared Candidate Sources & Selection Analysis (2)
PyTorch Documentation: torch.Tensor ↗ compared_alternative [Modified BSD]

Equivalent tensor semantics in the framework used later in the curriculum; NumPy reference selected to keep Days 22-24 dependency-free.

NumPy User Guide: Broadcasting ↗ compared_selected_for_days_22_24 [BSD 3-Clause License]

Selected as co-primary for Day 24: the broadcasting rules page pairs with the ndarray attribute reference.

03 120 min

Reshape, views vs copies, and memory ledgers

Assistance allowed only after prediction and observed evidence are recorded.

Prerequisites

Complete the previous activity; use the listed recovery link if blocked.

Learning Objective

Predict reshape results knowing element count is invariant and order is row-major; distinguish views from copies (a transpose is a non-contiguous view, so reshape after transpose may copy); and keep a memory ledger of elements x itemsize for real model tensors.

Instructions

reshape re-reads the same flat buffer in C (row-major) order, so the element count must be preserved. Many reshapes and every plain transpose return views - new axis metadata on the same memory. A non-contiguous tensor (for example after .T) may force reshape to copy. Byte size = element count * itemsize; float32 has itemsize 4.

Practice & Prediction Log

Let a = [[1,2,3],[4,5,6]] of shape (2,3). Predict: (a) a reshaped to (3,2); (b) a flattened to (6,); (c) whether a.T.reshape(6) can share a's memory; (d) the byte size of a float32 hidden state of shape (32, 128, 768).

Independent Mastery Criterion

You predict all four results, state the element-count invariant for reshape, and can explain the view-versus-copy caveat with the transpose example plus the 12 MiB ledger entry.

Authoritative Source Resources & Provenance

linking BSD 3-Clause License

NumPy Reference: The N-dimensional array (ndarray)

Author: NumPy Developers | Original Source Link ↗

Relevant Section / Range: ndarray.reshape, ndarray.T, strides, and non-contiguous copies

Verified Version & Date: NumPy 2.x documentation (Verified: 2026-10-30)

Selection Rationale:

Primary semantics for ndarray shape, strides, reshape orders, and view-versus-copy behavior used in tensor memory accounting.

Source Prerequisites:

Basic Python

Safe Fallback (Offline Resilience):

Shape, stride, and memory-ledger exercises are fully explained with local runnable examples.

Compared Candidate Sources & Selection Analysis (2)
PyTorch Documentation: torch.Tensor ↗ compared_alternative [Modified BSD]

Equivalent tensor semantics in the framework used later in the curriculum; NumPy reference selected to keep Days 22-24 dependency-free.

NumPy User Guide: Broadcasting ↗ compared_selected_for_days_22_24 [BSD 3-Clause License]

Selected as co-primary for Day 24: the broadcasting rules page pairs with the ndarray attribute reference.

linking BSD 3-Clause License

NumPy User Guide: Broadcasting

Author: NumPy Developers | Original Source Link ↗

Relevant Section / Range: Broadcasting never materializes the expanded axes

Verified Version & Date: NumPy 2.x documentation (Verified: 2026-10-30)

Selection Rationale:

Normative definition of broadcasting rules, shape mismatch errors, and implicit axis expansion shared by NumPy, PyTorch, and other tensor frameworks.

Source Prerequisites:

Basic Python and array indexing

Safe Fallback (Offline Resilience):

Broadcasting rules, failure cases, and memory-layout caveats are fully explained with local runnable examples.

Compared Candidate Sources & Selection Analysis (2)
PyTorch Documentation: Broadcasting semantics ↗ compared_alternative [Modified BSD]

Equivalent rules for PyTorch tensors; NumPy chosen because Day 24 exercises run without a PyTorch dependency, while the rule wording is identical.

NumPy Reference: The N-dimensional array (ndarray) ↗ compared_selected_for_days_22_24 [BSD 3-Clause License]

Selected as co-primary for Day 24: normative shape/strides/reshape semantics complementing the broadcasting rules page.

04 120 min

Independent mastery: tensor shape and broadcasting audit

Independent Mastery Check (no AI assistance).

Prerequisites

Complete the previous activity; use the listed recovery link if blocked.

Learning Objective

Without assistance, audit a layer-norm-style computation end to end: predict reduction shapes with keepdims, broadcast subtraction, broadcast failures, and a memory ledger entry; write a recovery note for any miss.

Instructions

Closed book: predict first, compute second, compare. Write each tensor's shape beside its value. If a result surprises you, record which rule was misapplied and note the recovery link.

Practice & Prediction Log

Tasks: (a) for x = [[1,2,3],[4,5,6]] of shape (2,3), compute the mean over the last axis with keepdims and its shape; (b) x - mean broadcast result; (c) which of (2,3)+(3,), (2,3)+(4,), (2,1)+(1,3) fails and why; (d) bytes of a float32 logits tensor of shape (2, 3, 50000).

Independent Mastery Criterion

All four answers verified unaided with shapes written beside values; you state the broadcast failure rule and one sentence on why keepdims exists for reductions.

Authoritative Source Resources & Provenance

linking BSD 3-Clause License

NumPy Reference: The N-dimensional array (ndarray)

Author: NumPy Developers | Original Source Link ↗

Relevant Section / Range: Full ndarray attribute reference for self-check

Verified Version & Date: NumPy 2.x documentation (Verified: 2026-10-30)

Selection Rationale:

Primary semantics for ndarray shape, strides, reshape orders, and view-versus-copy behavior used in tensor memory accounting.

Source Prerequisites:

Basic Python

Safe Fallback (Offline Resilience):

Shape, stride, and memory-ledger exercises are fully explained with local runnable examples.

Compared Candidate Sources & Selection Analysis (2)
PyTorch Documentation: torch.Tensor ↗ compared_alternative [Modified BSD]

Equivalent tensor semantics in the framework used later in the curriculum; NumPy reference selected to keep Days 22-24 dependency-free.

NumPy User Guide: Broadcasting ↗ compared_selected_for_days_22_24 [BSD 3-Clause License]

Selected as co-primary for Day 24: the broadcasting rules page pairs with the ndarray attribute reference.

linking BSD 3-Clause License

NumPy User Guide: Broadcasting

Author: NumPy Developers | Original Source Link ↗

Relevant Section / Range: Broadcasting rules reference for self-check

Verified Version & Date: NumPy 2.x documentation (Verified: 2026-10-30)

Selection Rationale:

Normative definition of broadcasting rules, shape mismatch errors, and implicit axis expansion shared by NumPy, PyTorch, and other tensor frameworks.

Source Prerequisites:

Basic Python and array indexing

Safe Fallback (Offline Resilience):

Broadcasting rules, failure cases, and memory-layout caveats are fully explained with local runnable examples.

Compared Candidate Sources & Selection Analysis (2)
PyTorch Documentation: Broadcasting semantics ↗ compared_alternative [Modified BSD]

Equivalent rules for PyTorch tensors; NumPy chosen because Day 24 exercises run without a PyTorch dependency, while the rule wording is identical.

NumPy Reference: The N-dimensional array (ndarray) ↗ compared_selected_for_days_22_24 [BSD 3-Clause License]

Selected as co-primary for Day 24: normative shape/strides/reshape semantics complementing the broadcasting rules page.