Module 0 · optional · Lesson 0.2

Indices, sums and maxima

Trace one output entry through a reduction. By the end, you should distinguish a fixed output index from a changing summation index, count the terms, and translate a sum into a loop.

Prerequisite: read matrix subscripts; 0.1 is available if needed.

0.2.1 Fix an output, then vary the reduction index

Attention mixes value rows using attention weights. A matrix entry has two coordinates: the first subscript selects a row, the second a column. In the following expression, i selects an output token row, j selects an output feature, and k visits the six source token rows:

O_ij = sum over k=1 through 6 of A_ik V_kj

O is the output, A the attention-weight matrix, and V the value matrix. The free indices i and j identify which answer is requested; the bound index k is consumed by the sum and does not become an extra output axis. Choosing i=1 and j=1 fixes one scalar output. The lower and upper limits include both endpoints.

0.2.2 Worked example: six products, one answer

For arithmetic practice, use the invented row A₁ = [1,2,3,4,5,6] and the first column of V = [1,2,1,0,2,1]. These A entries are unnormalized coefficients, not attention probabilities. This isolates the reduction; real softmax attention rows sum to one.

O_1,1 = 1 + 4 + 3 + 0 + 10 + 6 = 24

All six products belong to the same answer. Changing j selects a different value column while retaining the selected A row. Changing i selects a different A row. The bound index could be renamed r everywhere inside the same sum without changing the result.

total = 0
for k in 1..6 inclusive:
    total += A[i, k] * V[k, j]
O[i, j] = total

Common mistake: keeping k in the answer shape or summing over j. Read the bound variable printed below the sigma; only that index is reduced here.

0.2.3 A maximum is another reduction

z = [4,8,2,6]; m is the maximum entry, 8

The maximum produces one scalar m from four candidates. It returns the largest value, 8; it does not return the index 2. The operation that returns a maximizing index is argmax. Here z is the score vector and k is a local search index; it has no surviving output coordinate.

0.2.4 Inspect a different output

Make a prediction before opening hints. Try the task again without help after checking the reasoning.

0.2.5 Transfer without the term display

Read R_ab = sum over r=1 through 3 of P_ar U_rb. Which indices are free? Write a loop for one requested output and name its three products. Separately explain c = max over r of h_r without confusing the value with its location.

Check the reference explanation

a and b are free; r is bound. For fixed a,b, initialize a scalar accumulator to zero, then add P[a,1]U[1,b], P[a,2]U[2,b] and P[a,3]U[3,b]. Store that scalar in R[a,b]. The maximum c is the greatest entry of vector h, not its index. If you created three separate outputs, you omitted the reduction.

Return to weighted values in attention.

Return to the attention equation