9. Matrices

A matrix is a grid of numbers, and it is also a function: it takes a vector and returns a vector, moving every point of space in a way that keeps straight lines straight. This chapter covers both views, the products that compose such functions, and what those products cost on a real machine. Attention stores its keys and values as matrices, and one decoding step multiplies the key matrix by the query (section 9.3, section 17.4). Diagonal matrices (section 9.5) give the weighted lengths behind the paper's ellipsoid bound (section 10.6), and rotations (section 9.6) are how RoPE encodes positions (section 16.7). Chapter 8 is assumed: vectors, dot products, lengths.

9.1 Matrices as linear maps

An \(m \times n\) matrix \(A\) is a table of \(m\) rows and \(n\) columns; \(A_{ij}\) is the entry in row \(i\), column \(j\). In C, double A[m][n], stored row after row (row-major). It acts on a vector \(x \in \mathbb{R}^n\) and gives \(y = Ax \in \mathbb{R}^m\):

\[ y_i = \sum_{j=1}^{n} A_{ij} x_j , \qquad i = 1, \dots, m. \]

Read it two ways. By rows: \(y_i\) is the dot product of row \(i\) of \(A\) with \(x\). By columns: \(y = x_1 a_1 + \dots + x_n a_n\), a linear combination of the columns \(a_j\) of \(A\) with the coordinates of \(x\) as weights. The second view says what the matrix does: column \(j\) is where the \(j\)-th unit vector \(e_j = (0, \dots, 1, \dots, 0)\) lands, and every other vector lands at the same combination of those images.

The map \(x \mapsto Ax\) is linear: \(A(x + y) = Ax + Ay\) and \(A(cx) = c\,Ax\). Conversely, every linear map from \(\mathbb{R}^n\) to \(\mathbb{R}^m\) is a matrix: record where it sends each \(e_j\), as columns [axler]. Linear maps keep the origin fixed, send lines to lines and parallelograms to parallelograms. They can stretch, shear, rotate, reflect and flatten, but not bend.

1 2 1 square S × square
Figure 9.1. The shear \(S = \begin{pmatrix} 1 & 1 \\ 0 & 1 \end{pmatrix}\) keeps \(e_1 = (1, 0)\) (its first column) and sends \(e_2 = (0, 1)\) to \((1, 1)\) (its second). The unit square becomes the parallelogram on those two columns.

A key matrix is the plainest example. Stack the \(N\) cached keys as rows: \(K\) is \(N \times d\) with row \(i\) equal to \(k_i^\top\). Then \(Kq\) is the vector of all \(N\) dot products \(q^\top k_i\), and the logits are \(s = Kq / \sqrt{d}\). The value matrix \(V\) (\(N \times d_v\), rows \(v_i^\top\)) gives the output as \(o = V^\top \alpha\), by the column view: a combination of the values with the weights \(\alpha_i\).

9.2 Matrix multiplication

Apply \(B\), then \(A\): \(x \mapsto A(Bx)\). That is again linear, so it is a matrix, the product \(AB\). Its column \(j\) is \(A\) applied to column \(j\) of \(B\), and its entry \((i, j)\) is a dot product:

\[ (AB)_{ij} = \sum_{k} A_{ik} B_{kj} = (\text{row } i \text{ of } A) \cdot (\text{column } j \text{ of } B). \]

\(A\) must have as many columns as \(B\) has rows: \((m \times n)(n \times p) = m \times p\). The product is associative, \((AB)C = A(BC)\), since both mean “apply \(C\), then \(B\), then \(A\)”. It is not commutative: shearing then rotating is not rotating then shearing.

An example. With the shear \(S\) of figure 9.1 and the quarter turn \(R = \begin{pmatrix} 0 & -1 \\ 1 & 0 \end{pmatrix}\),

\[ RS = \begin{pmatrix} 0 & -1 \\ 1 & 1 \end{pmatrix}, \qquad SR = \begin{pmatrix} 1 & -1 \\ 1 & 0 \end{pmatrix}, \]

and for \(x = (2, 3)\), \(R(Sx) = R(5, 3) = (-3, 5) = (RS)x\). Cost: an \(m \times n\) matrix times a vector is \(mn\) multiply-adds; \((m \times n)(n \times p)\) is \(mnp\).

The program laws.c in this chapter's sources checks every identity of the chapter (associativity, \((AB)x = A(Bx)\), the transpose rules of section 9.4, the diagonal rules of section 9.5, the 2×2 inverse) on 20 000 random 5×5 matrices; the largest discrepancy is \(3.6 \times 10^{-15}\).

Matrix–matrix products are how attention handles many queries at once: with the queries as rows of \(Q\) (\(n \times d\)), \(QK^\top\) is the \(n \times N\) table of all logits. In prefill all \(n\) prompt tokens are queries; in decode there is one, and the product shrinks to a matrix–vector product (section 17.2).

9.3 Its cost and blocking

Multiplying two \(n \times n\) matrices takes \(n^2\) dot products of length \(n\): \(n^3\) multiply-adds, \(2n^3\) flops. The data is only \(3n^2\) numbers, so each number is used about \(n\) times. That reuse is the whole game: if every use came from DRAM the multiply units would sit idle; if the reused numbers stay in cache, the work can run at the speed of the arithmetic [hp].

The loop order decides which. In the textbook ijk order the inner loop walks down a column of \(B\), touching one double per 64-byte cache line and a new line every step. Swapping to ikj makes the inner loop run along a row of \(B\) and of \(C\): sequential, every byte of every line used, and vectorizable. Tiling (blocking) goes further: split the matrices into \(T \times T\) tiles small enough that a tile of \(A\), one of \(B\) and one of \(C\) fit in cache together, and finish all the work on those tiles before moving on [drepper]. With \(T = 64\) doubles the three tiles take 96 KB: more than the 32 KB L1 of this machine's core, well inside its 256 KB L2.

C A B = ×
Figure 9.2. Tiling. The red tile of \(C\) is the sum over \(k\) of (tile \(k\) of the blue row of \(A\)) times (tile \(k\) of the green column of \(B\)). The dark pair is the one being multiplied: three tiles in cache, \(T^3\) multiply-adds done on them.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define T 64                         /* tile: three 64 x 64 tiles of doubles = 96 KB */
#define MIN(a, b) ((a) < (b) ? (a) : (b))

static int n;
static double *A, *B, *C, *R;        /* n x n, row-major: A[i][k] is A[i*n + k] */

static void ijk(void)                /* textbook order: B is walked down a column */
{
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) {
            double s = 0;
            for (int k = 0; k < n; k++) s += A[i*n + k] * B[k*n + j];
            C[i*n + j] = s;
        }
}

static void ikj(void)                /* same sums, inner loop along rows of B and C */
{
    memset(C, 0, sizeof *C * n * n);
    for (int i = 0; i < n; i++)
        for (int k = 0; k < n; k++)
            for (int j = 0; j < n; j++) C[i*n + j] += A[i*n + k] * B[k*n + j];
}

static void tiled(void)              /* ikj on T x T tiles that stay in cache */
{
    memset(C, 0, sizeof *C * n * n);
    for (int ii = 0; ii < n; ii += T)
        for (int kk = 0; kk < n; kk += T)
            for (int jj = 0; jj < n; jj += T)
                for (int i = ii; i < MIN(ii + T, n); i++)
                    for (int k = kk; k < MIN(kk + T, n); k++)
                        for (int j = jj; j < MIN(jj + T, n); j++)
                            C[i*n + j] += A[i*n + k] * B[k*n + j];
}

static void run(const char *name, void (*f)(void))
{
    clock_t t0 = clock();
    f();
    double s = (double)(clock() - t0) / CLOCKS_PER_SEC, err = 0;
    for (int i = 0; i < n * n; i++) err = fmax(err, fabs(C[i] - R[i]));
    printf("n = %d  %-5s %6.3f s  %5.2f GFLOP/s  max diff %.0e\n",
           n, name, s, 2.0 * n * n * n / s / 1e9, err);
}

static void bench(int size)
{
    n = size;
    A = malloc(sizeof *A * n * n); B = malloc(sizeof *B * n * n);
    C = malloc(sizeof *C * n * n); R = malloc(sizeof *R * n * n);
    srand(1);
    for (int i = 0; i < n * n; i++) {
        A[i] = rand() / (double)RAND_MAX;
        B[i] = rand() / (double)RAND_MAX;
    }
    ijk();
    memcpy(R, C, sizeof *C * n * n);  /* reference result */
    run("ijk", ijk);
    run("ikj", ikj);
    run("tiled", tiled);
    free(A); free(B); free(C); free(R);
}

int main(void)
{
    bench(1000);
    bench(1024);
    return 0;
}
n = 1000  ijk    1.469 s   1.36 GFLOP/s  max diff 0e+00
n = 1000  ikj    0.508 s   3.94 GFLOP/s  max diff 0e+00
n = 1000  tiled  0.242 s   8.26 GFLOP/s  max diff 0e+00
n = 1024  ijk    1.820 s   1.18 GFLOP/s  max diff 0e+00
n = 1024  ikj    0.367 s   5.85 GFLOP/s  max diff 0e+00
n = 1024  tiled  0.391 s   5.50 GFLOP/s  max diff 0e+00

Printed on FreeBSD 15.1 on amd64 (Core i5-9400), clang 19. It depends on the machine: elsewhere the timings, the random numbers or the last digits differ.

How it maps to the math. All three functions compute \(C_{ij} = \sum_k A_{ik} B_{kj}\); they differ only in the order in which the \(n^3\) terms are visited. Matrices are flat arrays with \(A_{ik}\) at A[i*n + k] (row-major), so consecutive \(k\) in a row of \(A\) are adjacent in memory and consecutive \(k\) in a column of \(B\) are \(n\) doubles apart. ijk fixes \((i, j)\) and runs the sum over \(k\): the dot product of row \(i\) of \(A\) with column \(j\) of \(B\), the formula read literally, with the column read at stride \(n\). ikj moves \(k\) out: for fixed \((i, k)\) it adds \(A_{ik}\) times row \(k\) of \(B\) to row \(i\) of \(C\). That is the column view of section 9.1 applied to rows: row \(i\) of \(C\) is a linear combination of the rows of \(B\) with weights \(A_{i1}, \dots, A_{in}\). Every inner access is now at stride 1, and \(C\) must start at zero because it is accumulated. tiled runs the same ikj loop, restricted to \(T \times T\) blocks: the outer three loops pick a tile of \(C\) (rows ii, columns jj) and a step kk along the sum, and the inner three do the \(T^3\) multiply-adds of that tile product while the three tiles stay in cache. The MIN handles \(n\) not a multiple of \(T\). run times one call and compares with the ijk result; \(2n^3\) flops over the time gives GFLOP/s.

This ran on fbsd-srv, an Intel Core i5-9400 (Coffee Lake, 32 KB L1 data cache and 256 KB L2 per core, 9 MB shared L3), compiled as every program in this book (cc -std=c99 -O2, clang 19, so SSE2 vectors only). The machine was shared, and times varied between runs: over ten runs, at \(n = 1000\), ijk took 1.1 to 1.5 s, ikj 0.28 to 0.56 s, tiled 0.22 to 0.24 s. The order of the three never changed. The three variants add the same products in the same order (\(k\) ascending for each \(C_{ij}\)), so the results agree to the last bit: max diff 0e+00.

\(n = 1024\) is the trap. A row is 8192 bytes, so walking down a column steps by a power of two, and every element of a column, and every row of a tile, maps to the same few sets of the 8-way L1 cache: only 8 of them fit at once, and the rest evict each other (conflict misses [drepper]). ijk at \(n = 1024\) took 1.8 to 5.6 s over ten runs, and tiling stopped helping. Padding each row to 1032 doubles (exercise 5) restores the \(n = 1000\) speeds. The variation probably comes from the larger caches, which are indexed by physical address, so how badly the lines collide there depends on which pages the allocator got.

None of these is fast. With AVX2 and FMA a core of this chip can do 16 double-precision flops per cycle, about 60 GFLOP/s; tuned libraries add register blocking, packing of tiles into contiguous buffers and explicit vector code to get most of that. The point here is the factor between the first and last line, which comes from memory alone.

Decode is a matrix–vector product

When generating one token, attention for a head computes \(Kq\): an \(N \times d\) matrix times one vector. That is \(2Nd\) flops on \(Nd\) numbers, each used once. Nothing is reused, so tiling cannot help: the time is the time to stream \(K\) from memory. In float, 2 flops per 4 bytes, 0.5 flop per byte. That ratio, the arithmetic intensity, against the machine's flops per byte of bandwidth, decides whether a kernel is compute-bound or memory-bound [roofline].

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define D 128                               /* head dimension d */

/* s = K q: one decode step's logits (before the 1/sqrt(d)) for N cached keys */
static void kq(const float *K, const float *q, float *s, long n)
{
    for (long i = 0; i < n; i++) {
        float acc[8] = { 0 };               /* 8 independent sums: no add waits for the last */
        for (int j = 0; j < D; j += 8)
            for (int u = 0; u < 8; u++) acc[u] += K[i*D + j + u] * q[j + u];
        s[i] = ((acc[0] + acc[1]) + (acc[2] + acc[3]))
             + ((acc[4] + acc[5]) + (acc[6] + acc[7]));
    }
}

static void bench(long n, int reps)
{
    float *K = malloc(sizeof *K * n * D), *s = malloc(sizeof *s * n), q[D];
    for (long i = 0; i < n * D; i++) K[i] = rand() / (float)RAND_MAX - 0.5f;
    for (int j = 0; j < D; j++) q[j] = rand() / (float)RAND_MAX - 0.5f;
    kq(K, q, s, n);                         /* warm up: page in, fill caches */
    clock_t t0 = clock();
    for (int r = 0; r < reps; r++) { q[r % D] += 1e-3f; kq(K, q, s, n); }
    double t = (double)(clock() - t0) / CLOCKS_PER_SEC / reps;
    printf("N = %7ld (K is %6.1f MB): %8.1f us per K q  %5.2f GFLOP/s  %5.1f GB/s read"
           "  (s[0] %.3f)\n",
           n, n * D * 4 / 1e6, t * 1e6, 2.0 * n * D / t / 1e9, n * D * 4.0 / t / 1e9, s[0]);
    free(K); free(s);
}

int main(void)
{
    bench(1024, 20000);                     /* 0.5 MB: stays in L2/L3 cache */
    bench(262144, 50);                      /* 128 MB: streamed from DRAM each time */
    return 0;
}
N =    1024 (K is    0.5 MB):     37.5 us per K q   6.99 GFLOP/s   14.0 GB/s read  (s[0] -0.775)
N =  262144 (K is  134.2 MB):  11250.0 us per K q   5.97 GFLOP/s   11.9 GB/s read  (s[0] -0.474)

Printed on FreeBSD 15.1 on amd64 (Core i5-9400), clang 19. It depends on the machine: elsewhere the timings, the random numbers or the last digits differ.

How it maps to the math. K holds the \(N\) keys as rows, \(k_i\) at K[i*D], as a KV cache stores them; kq computes \(s_i = q^\top k_i\) for each \(i\), the matrix–vector product by rows. Each dot product is split into 8 partial sums, \(\sum_j = \sum_{u=0}^{7} \sum_{j \equiv u}\), so eight additions are independent and the loop is limited by throughput, not by the latency of one chain of adds (section 8.3); the order of the partial sums is fixed in the source, so the compiler may vectorize it without changing the result. bench times the product at two sizes: \(N = 1024\), where \(K\) (0.5 MB) stays in cache across repetitions, and \(N = 262\,144\), where \(K\) (134 MB) is far larger than the 9 MB L3 and must come from DRAM every time. Changing one coordinate of \(q\) per repetition keeps the compiler from treating the repetitions as one. The rates are \(2Nd\) flops and \(4Nd\) bytes over the time.

Compiled for SSE2 the arithmetic is the bottleneck at both sizes. Compiled with -march=native (AVX2 and FMA) the same source prints:

N =    1024 (K is    0.5 MB):      9.4 us per K q  27.96 GFLOP/s   55.9 GB/s read  (s[0] -0.775)
N =  262144 (K is  134.2 MB):   6250.0 us per K q  10.74 GFLOP/s   21.5 GB/s read  (s[0] -0.474)

Printed on FreeBSD 15.1 on amd64 (Core i5-9400), clang 19. It depends on the machine: elsewhere the timings, the random numbers or the last digits differ.

Now the cache-resident \(K\) runs at about 28 GFLOP/s, and the 134 MB one at under 11: the cores could go faster, the memory cannot. That is section 17.4 in one line, and it is why RefineKV's goal is to read fewer keys and values, not to do fewer flops.

9.4 Transpose and inverse

The transpose \(A^\top\) swaps rows and columns: \((A^\top)_{ij} = A_{ji}\). A vector is a column (an \(n \times 1\) matrix), so \(a^\top\) is a row and \(a^\top b\) is a \(1 \times 1\) matrix, the dot product. Two rules:

\[ (AB)^\top = B^\top A^\top , \qquad (Ax) \cdot y = x \cdot (A^\top y). \]

The second moves a matrix from one side of a dot product to the other, transposed. Section 9.6 uses it.

The identity \(I\) has 1 on the diagonal and 0 elsewhere; \(Ix = x\). A square matrix \(A\) is invertible if some \(A^{-1}\) has \(A^{-1}A = AA^{-1} = I\): the map can be undone. It can when no nonzero \(x\) has \(Ax = 0\), i.e. when the map flattens nothing. For 2×2,

\[ \begin{pmatrix} a & b \\ c & d \end{pmatrix}^{-1} = \frac{1}{ad - bc} \begin{pmatrix} d & -b \\ -c & a \end{pmatrix}, \qquad ad - bc \ne 0 . \]

Solving versus inverting. To find \(x\) with \(Ax = b\), do not compute \(A^{-1}\) and multiply. Gaussian elimination solves the system directly, for about a third of the work of forming the inverse, and with smaller rounding error [strang-la], [higham]. Same rule as in code: do not compute a reciprocal table when you only need one division.

Elimination subtracts multiples of row \(c\) from the rows below it to zero column \(c\) under the diagonal, for \(c = 1, \dots, n\), applying the same operations to \(b\); this leaves a triangular system, solved from the last unknown up (back substitution). For \(\begin{pmatrix} 2 & 1 & 1 \\ 4 & -6 & 0 \\ -2 & 7 & 2 \end{pmatrix} x = (5, -2, 9)\) it gives \(x = (1, 1, 2)\) (solve.c in the sources). Choosing as divisor the largest entry in the column (partial pivoting) keeps the multipliers at most 1 in size and the rounding errors small.

This book needs no more of it; the paper never inverts or solves.

9.5 Diagonal matrices

A diagonal matrix \(W = \operatorname{diag}(w_1, \dots, w_d)\) has the \(w_j\) on its diagonal and zeros elsewhere. It scales each coordinate by its own factor:

\[ Wx = (w_1 x_1, \dots, w_d x_d). \]

In code it is a vector, not a matrix: \(d\) multiplies, not \(d^2\). \(WA\) scales row \(i\) of \(A\) by \(w_i\); \(AW\) scales column \(j\) by \(w_j\). If every \(w_j \ne 0\), \(W^{-1} = \operatorname{diag}(1/w_1, \dots, 1/w_d)\). Per-channel scales in quantized models, and the per-channel radii of the paper's key clusters, are diagonal matrices.

Two identities matter for chapter 10. Take \(w_j > 0\). First, a scale factor can be moved across a dot product:

\[ q^\top r = \sum_{j} q_j r_j = \sum_j (q_j w_j)\,\frac{r_j}{w_j} = (Wq)^\top (W^{-1} r). \]

Second, the weighted length \(\big(\sum_j r_j^2 / w_j^2\big)^{1/2}\) is the ordinary length of \(W^{-1} r\): measure each coordinate in units of its own \(w_j\). The set where it is at most \(\rho\),

\[ \Big\{ r : \sum_{j=1}^{d} \frac{r_j^2}{w_j^2} \le \rho^2 \Big\} = \{ r : \|W^{-1} r\| \le \rho \} , \]

is an ellipsoid with semi-axes \(\rho w_j\) along the coordinate axes: the ball of radius \(\rho\) stretched by \(W\). RefineKV's diagonal-ellipsoid bound puts a cluster's centered keys \(r_i = k_i - \bar k_C\) in such a set and splits \(q^\top r_i\) exactly as above ([refinekv], Appendix A.7.2).

W |r| ≤ 1 Σ rⱼ²/wⱼ² ≤ 1
Figure 9.3. \(W = \operatorname{diag}(2, 0.75)\) stretches the unit disk into an ellipse with semi-axes 2 and 0.75 along the axes. Each point moves to its scaled copy; the dots are one point and its image.

Both identities are exact algebra; diag.c in the sources checks them on 100 000 random cases (largest discrepancy \(1.8 \times 10^{-15}\), rounding).

9.6 Orthogonal matrices and rotations

A square matrix \(Q\) is orthogonal when \(Q^\top Q = I\): its columns are unit vectors, perpendicular to each other. Then \(Q^{-1} = Q^\top\), and, by the transpose rule of section 9.4,

\[ (Qx) \cdot (Qy) = x \cdot (Q^\top Q y) = x \cdot y , \qquad \|Qx\| = \|x\| . \]

Orthogonal maps preserve dot products, so lengths and angles: they are the rigid motions that fix the origin, rotations and reflections. In the plane, rotation by \(\theta\) is

\[ R(\theta) = \begin{pmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{pmatrix}, \qquad R(\alpha) R(\beta) = R(\alpha + \beta), \qquad R(\theta)^\top = R(-\theta). \]

The columns are where \(e_1\) and \(e_2\) go: \((\cos\theta, \sin\theta)\) and \((-\sin\theta, \cos\theta)\), both on the unit circle and perpendicular. The product rule is the angle-addition formulas of trigonometry in matrix form.

x R(θ) x θ
Figure 9.4. \(R(\theta)\) turns every vector by \(\theta\) (here 0.7 radians) and keeps its length: \(x\) and \(R(\theta)x\) are on the same circle.

A preview of RoPE. Rotary position embedding [rope] splits the query and key into pairs of coordinates and rotates each pair by an angle proportional to the token's position: \(q\) at position \(m\) becomes \(R(m\theta)q\), \(k\) at position \(n\) becomes \(R(n\theta)k\). Their dot product is

\[ (R(m\theta)q)^\top (R(n\theta)k) = q^\top R(m\theta)^\top R(n\theta) k = q^\top R((n - m)\theta)\, k , \]

which depends on the positions only through their difference \(n - m\). The logit sees how far apart two tokens are, not where they are. Section 16.7 does it properly, with a different \(\theta\) per pair.

Numerically (rot.c in the sources), with \(\theta = 0.1\), \(q = (1, 0.5)\), \(k = (0.3, -1.2)\), the position pairs \((5, 2)\), \((13, 10)\) and \((103, 100)\) all give the logit \(-0.685553225730490\), the last one off by one unit in the 15th decimal: the sines and cosines of 10.3 and 10.0 carry different rounding errors from those of 0.5 and 0.2. One more consequence matters for chapter 10: rotating every query and key by the same \(Q\) leaves all logits, and so \(\delta_C\), unchanged. A bound that uses per-coordinate minima and maxima does change, because it depends on the axes. That is why the paper's two bounds are called axis-aligned and diagonal (section 10.6).

Exercises

  1. With \(A = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}\) and \(P = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}\), compute \(AP\) and \(PA\). What does \(P\) do on each side?
    Answer

    \(AP = \begin{pmatrix} 2 & 1 \\ 4 & 3 \end{pmatrix}\): the columns of \(A\) swapped. \(PA = \begin{pmatrix} 3 & 4 \\ 1 & 2 \end{pmatrix}\): the rows swapped. A permutation matrix on the right permutes columns, on the left rows.

  2. A head has \(d = 128\) and \(N = 100\,000\) cached keys in fp16. How many bytes does \(Kq\) read, how many flops does it do, and how long does it take at 20 GB/s and at 30 GFLOP/s?
    Answer

    \(Nd \cdot 2 = 25.6\) MB and \(2Nd = 25.6\) MFLOP. Reading takes 1.28 ms, computing 0.85 ms: memory is the limit, and in a real model the same data is read for every layer and KV head.

  3. Invert \(B = \begin{pmatrix} 2 & 1 \\ 1 & 1 \end{pmatrix}\) with the 2×2 formula and check \(BB^{-1} = I\).
    Answer

    \(ad - bc = 1\), so \(B^{-1} = \begin{pmatrix} 1 & -1 \\ -1 & 2 \end{pmatrix}\), and the product is \(I\) (ex.c prints it).

  4. Show \((AB)^\top = B^\top A^\top\) from the entry formula.
    Answer

    \(((AB)^\top)_{ij} = (AB)_{ji} = \sum_k A_{jk} B_{ki} = \sum_k (B^\top)_{ik} (A^\top)_{kj} = (B^\top A^\top)_{ij}\).

  5. Change matmul.c so that rows are 1032 doubles apart when \(n = 1024\) (allocate \(n \times 1032\), index A[i*ld + k]). What happens?
    Answer

    The program pad.c does it. One run printed:

    n = 1000  ijk    1.352 s   1.48 GFLOP/s  max diff 0e+00
    n = 1000  ikj    0.375 s   5.33 GFLOP/s  max diff 0e+00
    n = 1000  tiled  0.219 s   9.14 GFLOP/s  max diff 0e+00
    n = 1024  ijk    1.195 s   1.80 GFLOP/s  max diff 0e+00
    n = 1024  ikj    0.391 s   5.50 GFLOP/s  max diff 0e+00
    n = 1024  tiled  0.234 s   9.16 GFLOP/s  max diff 0e+00

    Printed on FreeBSD 15.1 on amd64 (Core i5-9400), clang 19. It depends on the machine: elsewhere the timings, the random numbers or the last digits differ.

    \(n = 1024\) now runs like \(n = 1000\). The column stride is no longer a power of two, so a column's elements spread over all the cache sets.

  6. Show that \(R(\pi/2)^4 = I\). Is \(\operatorname{diag}(2, 1/2)\) orthogonal?
    Answer

    \(R(\pi/2)^4 = R(2\pi) = I\): four quarter turns. \(\operatorname{diag}(2, 1/2)\) is not orthogonal: it sends \(e_1\) to a vector of length 2. It preserves area (\(ad - bc = 1\)) but not lengths.

  7. RefineKV stores, per cluster, the coordinate-wise minimum and maximum of the keys. If all keys and queries were rotated by the same orthogonal \(Q\), which of these change: the logits, \(\delta_C\), the per-coordinate minima and maxima?
    Answer

    Logits do not: \((Qq)^\top(Qk_i) = q^\top k_i\). The mean key rotates with the keys, so \(\delta_C\) does not change either. The minima and maxima do: they are taken along the coordinate axes, which \(Q\) does not move. So the box bound of section 10.6 can be tighter or looser after a rotation, though the true \(\delta_C\) is the same.

References