Matrices as Small Programs
A matrix is executable structure: its shape declares an interface, its entries route influence, and multiplication composes programs in a specific order.
- Authorship
- InterviewsVector
- Published / updated
- 2026-08-14 / 2026-08-14
- Review status
- Artifact tests passing · primary sources recorded
Original InterviewsVector material. Code examples are covered by repository tests and primary references are recorded. No named human reviewer is claimed.
The decision in one pass
Read an m×n matrix A as a program that accepts an n-coordinate vector and emits an m-coordinate vector. Each output row computes one weighted sum; each input column shows where one input can influence the outputs. Matrix multiplication composes these programs in reverse symbolic order: BA applies A first, then B. Shapes prove only numeric composability, so production code also needs named input and output semantics, finite-value checks, and tests for order, orientation, projection loss, and aliasing.
Why this matters
Most tensor systems are long compositions of linear maps with nonlinear or stateful operations between them. A transpose error, swapped composition order, or same-shaped semantic mismatch can run successfully while routing the wrong information. Reading matrices as typed programs makes those failures visible before they become opaque model behavior.
You will be able to
- Interpret matrix rows, columns, and shape as a linear program interface.
- Derive composition order and distinguish matrix multiplication from elementwise multiplication.
- Recognize projection, scaling, rotation, and mixing from their effect on inputs.
- Build a named-axis linear-map pipeline that compiles to one equivalent matrix.
- Stress shape-valid programs for semantic axis, ordering, finite-value, and immutability failures.
Prerequisite contract
- — Algebra and coordinate vectors
- Vectors as Representations →
Your Vector Loop for this lab
- 01
Model
Treat each matrix as a typed function from named input axes to named output axes.
- 02
Derive
Expand row computations and derive why BA means A first and B second.
- 03
Build
Compose rotation, scaling, and projection in a traced, compilable pipeline.
- 04
Stress
Swap order, transpose orientation, spoof same-shaped axes, and inject invalid numbers.
- 05
Operate
Validate tensor boundaries, compare fused and unfused paths, and observe numerical drift.
- 06
Defend
Explain a tensor program from shapes, semantics, influence paths, and failure evidence.
Model a matrix as a typed function
A ∈ ℝᵐˣⁿ, x ∈ ℝⁿ, y = Ax ∈ ℝᵐ
The n columns match input coordinates; the m rows define output coordinates. This is a shape contract, not yet a semantic one.
Row i is a small program for output yᵢ: multiply each input by the corresponding row weight, then add. Column j exposes every path by which input xⱼ can affect the outputs. Zeros remove direct influence; repeated or correlated rows can make outputs redundant; fewer rows than columns can discard distinctions.
| View | Read it as | Question to ask |
|---|---|---|
| shape m×n | function ℝⁿ → ℝᵐ | which axes enter and leave? |
| row i | weighted program for output i | which inputs control this output? |
| column j | influence routes from input j | where can this feature propagate? |
| rank | number of independent output directions | which distinctions collapse? |
| named axes | semantic type signature | does shape-compatible also mean meaning-compatible? |
Derive composition before optimizing it
z = B(Ax) = (BA)x
The matrix nearest x runs first. If A maps n inputs to m intermediates, B must accept those m intermediates. The product BA maps the original n inputs directly to B's outputs.
AB ≠ BA in general
Rotation then anisotropic scaling usually differs from scaling then rotation. Reordering matrices is a program change, not an algebraic cleanup.
| Map | Representative structure | Effect |
|---|---|---|
| uniform scale | sI | changes every direction by the same factor |
| coordinate scale | diagonal matrix | changes axes by different factors |
| rotation/reflection | orthogonal matrix | changes basis while preserving Euclidean geometry |
| projection | fewer independent output directions | removes components and can create collisions |
| mixing | dense off-diagonal weights | lets each output combine several inputs |
A transpose reverses rows and columns; it is not a visual formatting operation. In a learned layer, transposing can change whether examples, tokens, channels, or features are being mixed. Write axis names beside shapes during derivation, then make the executable boundary enforce them.
Build and compile a linear-map pipeline
The reference artifact represents every stage with immutable weights plus unique input and output axis names. A pipeline accepts adjacent stages only when the complete semantic axis tuple matches. It records intermediate values for diagnosis and compiles the stages into one matrix, allowing a test to prove that the optimized and inspectable executions agree.
1if __name__ == "__main__":2 run = EXAMPLE_PIPELINE.run((3.0, 1.0))3 compiled = EXAMPLE_PIPELINE.compile()4 print(f"pipeline={EXAMPLE_PIPELINE.name}")5 print(f"compiled_shape={compiled.shape[0]}x{compiled.shape[1]}")6 print("stage_outputs=" + ";".join(7 f"{trace.stage}:{trace.values}" for trace in run.stages8 ))9 print(f"compiled_matches={compiled.apply(run.input_values) == run.output}")Expected output
pipeline=rotate-scale-project
compiled_shape=1x2
stage_outputs=rotate:(-1.0, 3.0);scale:(-2.0, 1.5);project:(1.0,)
compiled_matches=TrueVerify: Run python3 -m unittest discover courses/ai-engineering/reference-impl/matrix_program.
- 01Declare axesName dimensions by meaning rather than relying on position: raw features, hidden channels, heads, tokens, or decision outputs.
- 02Run with stage tracesKeep an inspectable path that reveals which transformation first produced a bad value or erased a distinction.
- 03Compile and compareCompose compatible linear stages for efficiency, then test the compiled map against the staged path over representative and adversarial inputs.
Locate linear maps inside tensor systems
Learned weight matrices project input features into hidden spaces, mix channels, produce attention queries, keys, and values, and map hidden states back to outputs. The same rules apply, but tensors add batch, sequence, head, and channel axes. A reshape or transpose changes which collection a matrix operates over, so annotate the contraction axes rather than saying only that two tensors are multiplied.
| Operation | Linear-program reading | Boundary risk |
|---|---|---|
| feature projection | mix input channels into hidden channels | wrong feature order remains shape-valid |
| Q/K/V projection | create different views of each token state | weights or head axes are swapped |
| attention mixing | combine value rows using data-dependent weights | mask or sequence axis is wrong |
| output projection | mix head channels back into model width | concatenation order disagrees with weights |
| fused linear kernels | execute composed maps with fewer memory trips | optimized path diverges numerically or semantically |
Stress the program, not only its output example
- 01Swap non-commuting stagesUse anisotropic scale and rotation so a reorder visibly changes the result. Identity-like examples can let the bug escape.
- 02Connect equal shapes with different meaningsVerify that named axes fail closed even when raw dimensions match exactly.
- 03Transpose one boundaryCheck whether examples, tokens, or channels are now mixed. Assert the entire expected shape and axis signature after each operation.
- 04Inject ragged and non-finite weightsReject partial rows, booleans, NaN, and infinity at capture time so they cannot contaminate later stages.
- 05Mutate the caller's buffersConfirm that compiled behavior cannot be rewritten through a list retained by configuration code.
Operate optimized maps without losing the contract
- Emit resolved tensor shapes, axis conventions, dtype, and weight revision into diagnostic metadata without logging sensitive values by default.
- Test fused, quantized, exported, and accelerator-specific paths against a trusted implementation with dtype-aware tolerances.
- Monitor saturation, non-finite rates, norm changes, and output drift by model version and slice.
- Keep a staged diagnostic path or sampled intermediate hooks even when production compiles operations into one kernel.
- Benchmark arithmetic and memory movement separately; algebraic fusion can reduce traffic while changing rounding behavior.
| Change | Required comparison | Likely rollback |
|---|---|---|
| weight export | framework versus exported outputs | artifact revision |
| kernel fusion | staged versus fused path | runtime or compiler flag |
| dtype reduction | slice and margin-conditioned drift | precision policy |
| axis-layout optimization | semantic signature plus output parity | layout adapter |
Operate at three altitudes
Production lens
- — Attach semantic axis contracts to module and serialization boundaries, not only comments in training code.
- — Compare staged and optimized execution over adversarial shapes, values, dtypes, and protected slices.
- — Reject ragged, mismatched, boolean, and non-finite inputs before arithmetic begins.
- — Version weight layout and axis order with exported artifacts and runtime kernels.
Staff lens
- — Standardize tensor axis vocabulary across modeling, serving, compiler, and observability teams.
- — Preserve debuggability when authorizing fusion: an optimized graph still needs attributable boundaries and rollback controls.
- — Require semantic tests at interoperability boundaries where two frameworks may agree on shape but differ on layout or broadcasting.
Interview defense
A team fuses three linear layers into one matrix. What would you verify before enabling the optimized path?
I would first prove the layers are truly linear across the boundary—no activation, normalization, state, masking, or input-dependent operation between them. I would derive the composition in execution order, validate input and output axis semantics, then compare the fused matrix against the staged path on basis vectors, random bounded inputs, extreme finite values, and production slices with dtype-aware tolerances. I would separately test exported layouts and keep the fusion behind a rollback control with drift and non-finite telemetry.
Expect the interviewer to press on
- — Why is BA the composition for A first, B second?
- — How would bias terms change the fusion?
- — Which transformations cannot be fused into one fixed matrix?
- — Why can broadcasting hide an axis bug?
Misconceptions to remove
“Matrix multiplication is elementwise multiplication with extra syntax.”
It contracts an inner axis: every output combines products across that axis. Elementwise multiplication preserves aligned positions instead.
“If AB and BA are both defined, they represent the same program.”
Matrix multiplication is generally non-commutative. Changing order changes which transform acts first and usually changes the result.
“Compatible shapes guarantee a valid pipeline.”
Shapes establish numeric composability. Axis meaning, ordering, units, representation version, and dtype still need explicit contracts.
Check your model
1. For A with shape 3×4 and B with shape 2×3, what is the shape of BA and which map runs first on a 4-vector?
BA has shape 2×4. A runs first, mapping four inputs to three intermediates; B then maps those three values to two outputs.
2. Why does naming axes catch failures that integer shape checks miss?
Two axes can have the same length but different meaning or order. Named input/output signatures reject a latitude/longitude vector where price/quantity is expected even though both are length two.
3. What property makes an orthogonal matrix geometry-preserving?
Its transpose is its inverse, so AᵀA = I. Consequently it preserves dot products, norms, angles, and Euclidean distances.
Prove the mechanism
Add a shear stage and show with two inputs that rotate-then-shear differs from shear-then-rotate. Compile both pipelines and explain the differing influence paths from columns to outputs.
Add a production constraint
Extend the artifact to affine maps with bias by using homogeneous coordinates or an explicit bias field, then prove staged-versus-compiled equivalence and reject a bias-axis mismatch.
Artifact: Tested linear-map pipeline
courses/ai-engineering/reference-impl/matrix_program/linear_map_pipeline.py
Download reference implementationPrimary references and next links
References
- 1. PEP 465 — A dedicated infix operator for matrix multiplication
Python Enhancement Proposals. Accepted standards-track proposal distinguishing matrix multiplication from elementwise multiplication in Python.
- 2. Python Array API matmul specification
Consortium for Python Data API Standards. Official cross-library specification for matrix-product shape, dimension, and type behavior.
- 3. Attention Is All You Need
Vaswani et al.. Primary transformer paper grounding learned projections and composed linear maps in a production-relevant architecture.
Continue through the graph
- Vectors as Representations →
Review the coordinate and representation contract consumed by a matrix.
- Similarity Is a Retrieval Policy →
Connect matrix-produced representations to downstream geometric scoring.
- Academy roadmap →
See how linear maps support later neural and transformer systems.
Glossary: matrix · linear map · matrix multiplication · composition · projection · transpose · rank · tensor axis