InterviewsVector
Arc 2
Build labFoundation90 min estimateOriginal publication

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

Your Vector Loop for this lab

  1. 01

    Model

    Treat each matrix as a typed function from named input axes to named output axes.

  2. 02

    Derive

    Expand row computations and derive why BA means A first and B second.

  3. 03

    Build

    Compose rotation, scaling, and projection in a traced, compilable pipeline.

  4. 04

    Stress

    Swap order, transpose orientation, spoof same-shaped axes, and inject invalid numbers.

  5. 05

    Operate

    Validate tensor boundaries, compare fused and unfused paths, and observe numerical drift.

  6. 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.

ViewRead it asQuestion to ask
shape m×nfunction ℝⁿ → ℝᵐwhich axes enter and leave?
row iweighted program for output iwhich inputs control this output?
column jinfluence routes from input jwhere can this feature propagate?
ranknumber of independent output directionswhich distinctions collapse?
named axessemantic type signaturedoes 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.

MapRepresentative structureEffect
uniform scalesIchanges every direction by the same factor
coordinate scalediagonal matrixchanges axes by different factors
rotation/reflectionorthogonal matrixchanges basis while preserving Euclidean geometry
projectionfewer independent output directionsremoves components and can create collisions
mixingdense off-diagonal weightslets 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.

linear_map_pipeline.py
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.stages
8 ))
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=True

Verify: Run python3 -m unittest discover courses/ai-engineering/reference-impl/matrix_program.

  1. 01Declare axesName dimensions by meaning rather than relying on position: raw features, hidden channels, heads, tokens, or decision outputs.
  2. 02Run with stage tracesKeep an inspectable path that reveals which transformation first produced a bad value or erased a distinction.
  3. 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.

OperationLinear-program readingBoundary risk
feature projectionmix input channels into hidden channelswrong feature order remains shape-valid
Q/K/V projectioncreate different views of each token stateweights or head axes are swapped
attention mixingcombine value rows using data-dependent weightsmask or sequence axis is wrong
output projectionmix head channels back into model widthconcatenation order disagrees with weights
fused linear kernelsexecute composed maps with fewer memory tripsoptimized path diverges numerically or semantically

Stress the program, not only its output example

  1. 01Swap non-commuting stagesUse anisotropic scale and rotation so a reorder visibly changes the result. Identity-like examples can let the bug escape.
  2. 02Connect equal shapes with different meaningsVerify that named axes fail closed even when raw dimensions match exactly.
  3. 03Transpose one boundaryCheck whether examples, tokens, or channels are now mixed. Assert the entire expected shape and axis signature after each operation.
  4. 04Inject ragged and non-finite weightsReject partial rows, booleans, NaN, and infinity at capture time so they cannot contaminate later stages.
  5. 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.
ChangeRequired comparisonLikely rollback
weight exportframework versus exported outputsartifact revision
kernel fusionstaged versus fused pathruntime or compiler flag
dtype reductionslice and margin-conditioned driftprecision policy
axis-layout optimizationsemantic signature plus output paritylayout 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 implementation

Primary references and next links

References

  1. 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. 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. 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

Glossary: matrix · linear map · matrix multiplication · composition · projection · transpose · rank · tensor axis