AI Wiki中文/EN

Matrix multiplication

矩阵乘法

Calculate a batch of prices and weights to understand row-by-column products, shape constraints, operation order, and model dimensions.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

One table calculates both price and weight

Suppose there are three products and two orders. Each row of AA is an order and each column a product. A second table, BB, lists unit prices and unit weights in the same product order. These are invented values:

A=[210031],B=[412352],AB=[1051111].A=\begin{bmatrix}2&1&0\\0&3&1\end{bmatrix},\qquad B=\begin{bmatrix}4&1\\2&3\\5&2\end{bmatrix},\qquad AB=\begin{bmatrix}10&5\\11&11\end{bmatrix}.

The first order costs 2×4+1×2+0×5=102\times4+1\times2+0\times5=10 and weighs 2×1+1×3+0×2=52\times1+1\times3+0\times2=5. 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 AA has mm rows and kk columns, and BB has kk rows and nn columns, every output entry matches kk pairs of coefficients:

C=AB∈Rm×n,Cij=∑r=1kAirBrj.C=AB\in\mathbb R^{m\times n},\qquad C_{ij}=\sum_{r=1}^{k}A_{ir}B_{rj}.

Equivalently, column jj of the result is a linear combination of the columns of AA, weighted by column jj of BB. 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 SS double the horizontal coordinate and HH add the vertical coordinate to the horizontal coordinate:

S=[2001],H=[1101],SH=[2201],HS=[2101].S=\begin{bmatrix}2&0\\0&1\end{bmatrix},\quad H=\begin{bmatrix}1&1\\0&1\end{bmatrix},\quad SH=\begin{bmatrix}2&2\\0&1\end{bmatrix},\quad HS=\begin{bmatrix}2&1\\0&1\end{bmatrix}.

For a column vector xx, SHxSHx applies HH first, then SS. Changing the order can change the coordinates. Multiplication is associative and distributive, and transposing a product reverses the order: (AB)⊤=B⊤A⊤(AB)^\top=B^\top A^\top. 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 X∈Rb×dX\in\mathbb R^{b\times d} and use W∈Rd×hW\in\mathbb R^{d\times h} to produce XW∈Rb×hXW\in\mathbb R^{b\times h}. 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 mnmn entries, each combining kk terms, for O(mkn)O(mkn) time and O(mn)O(mn) 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 100×2100\times2, 2×1002\times100, and 100×2100\times2, 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

  1. How should BB change if orders need only a price, not a weight? Answer: retain its first column, giving a 3×13\times1 input and a 2×12\times1 output.
  2. If AA is 2×32\times3 and BB is 3×43\times4, what about ABAB and BABA? Answer: ABAB is 2×42\times4; BABA is undefined because its inner dimensions are 4 and 2.
  3. Compare SHxSHx and HSxHSx for x=(1,1)⊤x=(1,1)^\top. Answer: (4,1)⊤(4,1)^\top and (3,1)⊤(3,1)^\top, respectively.
  4. How many naive scalar multiplications do the two parenthesizations of the three-matrix example require? Answer: 40,000 for (AB)C(AB)C and 800 for A(BC)A(BC), excluding additions and scheduling overhead.

Reading attention through multiplication

Attention uses QK⊤QK^\top to compare positions, then multiplies an attention-weight matrix by VV 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?

Choose one answer

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

  1. Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
    Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020
  2. 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

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.