Matrix multiplication
矩阵乘法
Calculate a batch of prices and weights to understand row-by-column products, shape constraints, operation order, and model dimensions.
matrix-multiplicationOne table calculates both price and weight
Suppose there are three products and two orders. Each row of is an order and each column a product. A second table, , lists unit prices and unit weights in the same product order. These are invented values:
The first order costs and weighs . The result retains the order and measurement axes while summing over the product axis. This matching and aggregation is what “multiply a row by a column and sum” accomplishes.
Output columns may have different units, but adding price to weight is meaningless. Product order must match. Compatible dimensions do not guarantee compatible meanings, a distinction that also matters for token, feature, and batch axes in models.
Why must the inner dimensions match?
If has rows and columns, and has rows and columns, every output entry matches pairs of coefficients:
Equivalently, column of the result is a linear combination of the columns of , weighted by column of . The entrywise view helps with hand calculations; the column-combination view helps explain which outputs a model can represent. MML, Section 2.2
Matrix multiplication generally does not commute. Let double the horizontal coordinate and add the vertical coordinate to the horizontal coordinate:
For a column vector , applies first, then . Changing the order can change the coordinates. Multiplication is associative and distributive, and transposing a product reverses the order: . These are exact mathematical identities; finite-precision implementations can produce rounding differences when the evaluation order changes. Deep Learning, Section 2.2
Neural networks often arrange examples as and use to produce . A row-per-example convention and a single-column-vector convention are both usable. Moving between them requires the correct transposes, not merely matching variable names.
What do the three loops compute?
This complete program accepts only nonempty rectangular tables. Zero-dimensional matrices are outside its input convention. Ragged lists are rejected instead of being treated as valid matrices.
def shape(a):
if not a or not a[0] or any(len(row) != len(a[0]) for row in a):
raise ValueError("expected a nonempty rectangular matrix")
return len(a), len(a[0])
def matmul(a, b):
m, k = shape(a)
k2, n = shape(b)
if k != k2:
raise ValueError("inner dimensions differ")
return [[sum(a[i][r] * b[r][j] for r in range(k))
for j in range(n)] for i in range(m)]
a = [[2, 1, 0], [0, 3, 1]]
b = [[4, 1], [2, 3], [5, 2]]
assert matmul(a, b) == [[10, 5], [11, 11]]
s, h = [[2, 0], [0, 1]], [[1, 1], [0, 1]]
assert matmul(s, h) != matmul(h, s)
assert matmul(a, [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) == a
The naive dense algorithm computes entries, each combining terms, for time and additional output space. This is the complexity of this algorithm, not a lower bound for every matrix algorithm. Practical libraries use blocking, vector instructions, and hardware parallelism to improve throughput without changing the entrywise definition.
Correct shapes do not guarantee a correct calculation
Elementwise multiplication multiplies corresponding entries without summing over the shared axis. Both operations are legitimate but solve different problems. Test matrix multiplication with examples that distinguish them; diagonal or all-zero inputs alone are insufficient.
Parenthesization affects the work and intermediate storage in a long product. For matrices of shapes , , and , multiplying the last two first requires much less work than multiplying the first two first. Mathematical equivalence does not imply equal memory cost or runtime.
Sparse matrices can skip many zero entries, while low-rank structure can express a large matrix as a product of smaller ones. Whether those techniques help depends on the nonzero pattern, dimensions, and accuracy requirements. Knowing only that a matrix is large is not enough to select an algorithm.
Write shapes beside the symbols
- How should change if orders need only a price, not a weight? Answer: retain its first column, giving a input and a output.
- If is and is , what about and ? Answer: is ; is undefined because its inner dimensions are 4 and 2.
- Compare and for . Answer: and , respectively.
- How many naive scalar multiplications do the two parenthesizations of the three-matrix example require? Answer: 40,000 for and 800 for , excluding additions and scheduling overhead.
Reading attention through multiplication
Attention uses to compare positions, then multiplies an attention-weight matrix by to combine information. As in the order example, identify the matched and summed axes. Matrix decompositions, sparse computation, and tensor contractions ask how structure can make these combinations cheaper while controlling memory and numerical error.
Make a prediction, then check
A has shape 7×3 and B has shape 3×2. What is the shape of AB?
Learning objectives
- Derive matrix-product entries and label every axis by meaning.
- Compare product order, parenthesization, and computational work.
Prerequisites & connections
Explore related knowledge →References
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020 - Deep Learning — Chapter 2: Linear Algebra
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.
- Recomputed AB=[[10,5],[11,11]], SH/HS, and the 40,000/800 multiplication counts.
- Checked shared axes, row/column conventions, naive O(mkn) complexity, and floating-point associativity limitations.
- Compared the main arguments, numerical examples, exercises, and answers across languages; structural checks additionally compare display equations, source lists, and code.
- Reviewed the answer-label rendering fix: only Markdown emphasis markers changed to strong tags; normalized text and all code are identical.
Source locations checked:
Related topics