The neural notebook
← All chapters

IV-22 / Part V · Self-Attention

Queries, Keys and Values as Projections

Compute three distinct projections of the same token rows, inspect every product, and connect feature-last storage to column-vector mathematics.

Review the ideas this chapter uses

A sequence supplies several small vectors, one for each position. We want a position to compare itself with other positions and, eventually, combine information from them. The comparison and the information being combined need not use the same coordinates. Our first step is to calculate three different representations of each input, using three weight matrices.

Learning objective: Compute Q, K and V from the same token representations with distinct weights.

Review IV-16 — Token IDs and Embedding Lookup Tables for how token IDs select embedding rows, and II.9 — Matrix × vector for matrix–vector multiplication. An embedding is a numerical representation of an item. This lesson begins with supplied numerical rows; it does not tokenize text, update an embedding table, or train the projection weights.

Start with a calculation you can edit

Compute it yourself

Compute separate query, key and value projections

These controls recompute the actual example. Trace navigation shows saved calculation steps; editing starts a new trace from the displayed inputs.

Complete results from this trace’s starting inputs

Starting inputs for these results
B
1
T
3
Dk
2
Dv
2
x000
1
x001
0
x010
0
x011
1
x020
1
x021
1
x100
1
x101
1
x110
-1
x111
0
x120
0
x121
2
wq00
1
wq01
0
wq10
0
wq11
1
wk00
1
wk01
0
wk10
0
wk11
1
wv00
1
wv01
0
wv10
0
wv11
1
B1
T3
Dk2
Dv2

B 1. T 3. Dk 2. Dv 2. Validate all scalar inputs and select active dimensions. All stored slots are validated. Active tensors use only the selected batches, time prefix and leading output columns; neither input-feature row is removed.. B 1. T 3. D 2. Dk 2. Dv 2

Validate all scalar inputs and select active dimensions

D=2; X[B,T,D]; WQ,WK[D,Dk]; WV[D,Dv]

All stored slots are validated. Active tensors use only the selected batches, time prefix and leading output columns; neither input-feature row is removed.

Inputs

B
1
T
3
Dk
2
Dv
2
x000
1
x001
0
x010
0
x011
1
x020
1
x021
1
x100
1
x101
1
x110
-1
x111
0
x120
0
x121
2
wq00
1
wq01
0
wq10
0
wq11
1
wk00
1
wk01
0
wk10
0
wk11
1
wv00
1
wv01
0
wv10
0
wv11
1

Outputs

B
1
T
3
D
2
Dk
2
Dv
2

Token rows → separate projections

These are hand-set weights, not a trained model. D=2 always counts input features. Dk=2 counts query/key features; Dv=2 counts value features. All indices start at zero. Inactive stored slots remain validated but do not appear in active tensors.

The example button restores B=1, T=3, Dk=Dv=2 and X=[[1,0],[0,1],[1,1]], then sets three different matrices. Inspect the separate Q, K and V results below. Reset example above restores every lesson default.

Showing batch 0, all 3 active token rows. These selectors change the view only. Trace navigation above selects a saved operation independently; highlighted rows mark that operation when it is in this view.

X batch 0

B=1 × T=3 × D=2 · float64. Rows: Token; columns: Input feature D.

X batch 0; stored values without display rounding
TokenInput feature D 0Input feature D 1
010
101
211

WQ shared weights

D=2 × Dk=2 · float64. Rows: Input feature D; columns: Query feature Dk.

WQ shared weights; stored values without display rounding
Input feature DQuery feature Dk 0Query feature Dk 1
010
101

WK shared weights

D=2 × Dk=2 · float64. Rows: Input feature D; columns: Key feature Dk.

WK shared weights; stored values without display rounding
Input feature DKey feature Dk 0Key feature Dk 1
010
101

WV shared weights

D=2 × Dv=2 · float64. Rows: Input feature D; columns: Value feature Dv.

WV shared weights; stored values without display rounding
Input feature DValue feature Dv 0Value feature Dv 1
010
101

Q batch 0

B=1 × T=3 × Dk=2 · float64. Rows: Token; columns: Query feature Dk.

Q batch 0; stored values without display rounding
TokenQuery feature Dk 0Query feature Dk 1
010
101
211

K batch 0

B=1 × T=3 × Dk=2 · float64. Rows: Token; columns: Key feature Dk.

K batch 0; stored values without display rounding
TokenKey feature Dk 0Key feature Dk 1
010
101
211

V batch 0

B=1 × T=3 × Dv=2 · float64. Rows: Token; columns: Value feature Dv.

V batch 0; stored values without display rounding
TokenValue feature Dv 0Value feature Dv 1
010
101
211

Every projection coordinate in batch 0

For row-feature inputs, output feature f is x0·W[0,f]+x1·W[1,f]. A column-vector version uses the transposed weights: q_column=WQᵀ·x_column.

Q, then K, then V; actual operands, products and sums in batch 0
Coordinatex0w0x0 × w0x1w1x1 × w1Sum
Q,0,0,01110001
Q,0,0,11000100
Q,0,1,00101000
Q,0,1,10001111
Q,0,2,01111001
Q,0,2,11001111
K,0,0,01110001
K,0,0,11000100
K,0,1,00101000
K,0,1,10001111
K,0,2,01111001
K,0,2,11001111
V,0,0,01110001
V,0,0,11000100
V,0,1,00101000
V,0,1,10001111
V,0,2,01111001
V,0,2,11001111
Inspect tensor shapes and full precision

All computed outputs

B
1
T
3
Dk
2
Dv
2
q000
1
q001
0
q010
0
q011
1
q020
1
q021
1
k000
1
k001
0
k010
0
k011
1
k020
1
k021
1
v000
1
v001
0
v010
0
v011
1
v020
1
v021
1
setup_B
1
setup_T
3
setup_D
2
setup_Dk
2
setup_Dv
2
project_Q_0_0_0_product0
1
project_Q_0_0_0_product1
0
project_Q_0_0_0_value
1
project_Q_0_0_1_product0
0
project_Q_0_0_1_product1
0
project_Q_0_0_1_value
0
project_Q_0_1_0_product0
0
project_Q_0_1_0_product1
0
project_Q_0_1_0_value
0
project_Q_0_1_1_product0
0
project_Q_0_1_1_product1
1
project_Q_0_1_1_value
1
project_Q_0_2_0_product0
1
project_Q_0_2_0_product1
0
project_Q_0_2_0_value
1
project_Q_0_2_1_product0
0
project_Q_0_2_1_product1
1
project_Q_0_2_1_value
1
project_K_0_0_0_product0
1
project_K_0_0_0_product1
0
project_K_0_0_0_value
1
project_K_0_0_1_product0
0
project_K_0_0_1_product1
0
project_K_0_0_1_value
0
project_K_0_1_0_product0
0
project_K_0_1_0_product1
0
project_K_0_1_0_value
0
project_K_0_1_1_product0
0
project_K_0_1_1_product1
1
project_K_0_1_1_value
1
project_K_0_2_0_product0
1
project_K_0_2_0_product1
0
project_K_0_2_0_value
1
project_K_0_2_1_product0
0
project_K_0_2_1_product1
1
project_K_0_2_1_value
1
project_V_0_0_0_product0
1
project_V_0_0_0_product1
0
project_V_0_0_0_value
1
project_V_0_0_1_product0
0
project_V_0_0_1_product1
0
project_V_0_0_1_value
0
project_V_0_1_0_product0
0
project_V_0_1_0_product1
0
project_V_0_1_0_value
0
project_V_0_1_1_product0
0
project_V_0_1_1_product1
1
project_V_0_1_1_value
1
project_V_0_2_0_product0
1
project_V_0_2_0_product1
0
project_V_0_2_0_value
1
project_V_0_2_1_product0
0
project_V_0_2_1_product1
1
project_V_0_2_1_value
1

Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.

X

B=1 × T=3 × D=2 · float64 · display precision 8 · Active input token rows, selected without padding or broadcasting.

Storage indexValue
01
10
20
31
41
51

WQ

D=2 × Dk=2 · float64 · display precision 8 · Both input rows; leading Dk query columns of the editable WQ.

Storage indexValue
01
10
20
31

WK

D=2 × Dk=2 · float64 · display precision 8 · Both input rows; leading Dk key columns of the editable WK.

Storage indexValue
01
10
20
31

WV

D=2 × Dv=2 · float64 · display precision 8 · Both input rows; leading Dv value columns of the editable WV.

Storage indexValue
01
10
20
31

Q

B=1 × T=3 × Dk=2 · float64 · display precision 8 · Q=XWQ, with each coordinate traced as two products and one sum.

Storage indexValue
01
10
20
31
41
51

K

B=1 × T=3 × Dk=2 · float64 · display precision 8 · K=XWK, with each coordinate traced as two products and one sum.

Storage indexValue
01
10
20
31
41
51

V

B=1 × T=3 × Dv=2 · float64 · display precision 8 · V=XWV, available for later value mixing; not mixed in IV-22–24.

Storage indexValue
01
10
20
31
41
51

Start with identity weights: Q=K=V=X when both output widths are two. Load the nonsymmetric example to obtain Q=[[1,2],[0,1],[1,3]], K=[[0,1],[1,0],[1,1]], V=[[1,−1],[2,0],[3,−1]]. Follow both products in each output coordinate, not just the final matrix.

Try B=2 and switch the batch inspector. Then try T=1, Dk=1 or Dv=1: inactive stored coordinates remain validated, while active shapes and calculations shrink. All weights are editable, but no optimization step occurs. IV-23 uses Q and K to compute scores; V is reserved for later value mixing.

Check your understanding

Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.

1. What are Q, K and V in this lab?
2. For the current controls, which shapes are correct?
3. Use the current operands: what is Q[0,0,0] = (1 × 1) + (0 × 0)?
4. Change only WV while holding X, WQ, WK and all dimensions fixed. Which projected tensor can change?
5. Transfer to row x=[1,0] and nonsymmetric WQ=[[1,2],[0,1]]. What is the query row xWQ?

Reset supplies one sequence with three input rows: (1,0)(1,0), (0,1)(0,1) and (1,1)(1,1). The three weight matrices initially equal the two-dimensional identity. Inspect the Q, K and V tensors and the products in the trace. Then change one query weight while leaving the other matrices alone. Only Q should change in this lesson’s derived tensors.

The identity is a gentle starting point because every output equals its input. It also hides orientation mistakes. After understanding reset, enter the nonsymmetric matrices worked below. Read a coordinate’s two products before reading its final sum. Editing numbers changes the actual projection calculation; selecting a trace step explains that calculation rather than supplying a different learned model.

Three names for three roles

A query, abbreviated Q, will describe a position on the asking side of a comparison. A key, K, will describe a position on the candidate side. A value, V, will carry the coordinates combined after the comparison weights have been calculated. These names describe computational roles. A query is not an English question, and a key is not a symbolic label looked up by exact equality.

Each representation is a linear projection: multiply input coordinates by weights and add. Here “projection” means a linear mapping to another feature representation; it need not be a perpendicular geometric projection, preserve lengths, or reduce the number of coordinates. There is no bias or activation in this particular operation.

All three maps receive the same input row. They may produce different numbers because their weights differ. Reset makes their numbers coincide only because their weights happen to coincide. The names alone do not cause semantic specialization. In a trained model, optimization can change these weights; here you explicitly set them.

Name every axis before multiplying

A tensor is an array with named axes. B counts separate sequences in a batch, T counts positions within each sequence, and D counts input features. This lab fixes D=2. Dk counts query/key features; Dv counts value features. Indices start at zero: b selects a batch, t a position, d an input feature, and f an output feature.

TensorShapeAxis meanings
X[B,T,2]batch, position, input feature
WQ and WK[2,Dk]input feature, query/key feature
WV[2,Dv]input feature, value feature
Q and K[B,T,Dk]batch, position, query/key feature
V[B,T,Dv]batch, position, value feature

Q and K require the same width so their corresponding features can later be multiplied in a dot product. V can have another width because its later job is different. B is integer 1 or 2, T is integer 1 through 3, and both output widths are integer 1 or 2. A second batch adds another independent sequence; it does not let the first sequence compare with that sequence.

Derive one coordinate from its two contributions

For a fixed batch b, position t and query feature f, the rule is

Q[b,t,f]=X[b,t,0]WQ[0,f]+X[b,t,1]WQ[1,f].Q[b,t,f]=X[b,t,0]W_Q[0,f]+X[b,t,1]W_Q[1,f].

Brackets select array coordinates. The subscript Q labels the query matrix, rather than multiplying W by Q. Compute the first product, compute the second product, then add them. K and V use the same rule with their respective weight matrices. Since D=2, every output has exactly two input-feature contributions, even when its output width is one.

For a whole sequence we abbreviate these repeated coordinate calculations as Q=XWQQ=XW_Q, K=XWKK=XW_K, V=XWVV=XW_V, understood separately within each batch. Each input row has shape [1,2][1,2], so multiplying by [2,Dk][2,Dk] gives a [1,Dk][1,Dk] query row. The matching inner dimensions explain why the multiplication is legal.

This is the row-feature convention. Earlier column-vector mathematics writes qcol=Wcolxcolq_{\rm col}=W_{\rm col}x_{\rm col}. The same transformation here is

xrow=xcolT,Wrow=WcolT,qrow=xrowWrow.x_{\rm row}=x_{\rm col}^{\mathsf T},\qquad W_{\rm row}=W_{\rm col}^{\mathsf T},\qquad q_{\rm row}=x_{\rm row}W_{\rm row}.

The superscript T\mathsf T means transpose, exchanging rows and columns; it is different from the plain letter T counting positions. Transposing the column equation gives (Wcolxcol)T=xcolTWcolT(W_{\rm col}x_{\rm col})^{\mathsf T}=x_{\rm col}^{\mathsf T}W_{\rm col}^{\mathsf T}, which reverses multiplication order. Keeping the old weights unchanged while moving them to the other side generally changes the map.

Work through the identity reset

The identity matrix has ones on its diagonal and zeros elsewhere. For each of Q, K and V, all six output calculations in batch zero are

(0,0):1(1)+0(0)=1+0=1,(0,1):1(0)+0(1)=0+0=0,(1,0):0(1)+1(0)=0+0=0,(1,1):0(0)+1(1)=0+1=1,(2,0):1(1)+1(0)=1+0=1,(2,1):1(0)+1(1)=0+1=1.\begin{aligned} (0,0):&\quad 1(1)+0(0)=1+0=1,\\ (0,1):&\quad 1(0)+0(1)=0+0=0,\\ (1,0):&\quad 0(1)+1(0)=0+0=0,\\ (1,1):&\quad 0(0)+1(1)=0+1=1,\\ (2,0):&\quad 1(1)+1(0)=1+0=1,\\ (2,1):&\quad 1(0)+1(1)=0+1=1. \end{aligned}

The pair before each calculation means (position, output feature). Thus all three projected matrices equal [[1,0],[0,1],[1,1]][[1,0],[0,1],[1,1]]. No normalization has taken place. A negative input would remain negative under these identity maps, and an output row need not sum to one.

Use weights that expose orientation

Keep reset X, B=1, T=3 and both output widths two. Enter

WQ=[1201],WK=[0110],WV=[1−120].W_Q=\begin{bmatrix}1&2\\0&1\end{bmatrix},\qquad W_K=\begin{bmatrix}0&1\\1&0\end{bmatrix},\qquad W_V=\begin{bmatrix}1&-1\\2&0\end{bmatrix}.

Each table cell below shows both products and their sum. Rows follow position order; columns are output features.

Input rowQ feature 0Q feature 1K feature 0K feature 1V feature 0V feature 1
(1,0)1·1+0·0=11·2+0·1=21·0+0·1=01·1+0·0=11·1+0·2=11·(-1)+0·0=-1
(0,1)0·1+1·0=00·2+1·1=10·0+1·1=10·1+1·0=00·1+1·2=20·(-1)+1·0=0
(1,1)1·1+1·0=11·2+1·1=31·0+1·1=11·1+1·0=11·1+1·2=31·(-1)+1·0=-1

Therefore

Q=[120113],K=[011011],V=[1−1203−1].Q=\begin{bmatrix}1&2\\0&1\\1&3\end{bmatrix},\quad K=\begin{bmatrix}0&1\\1&0\\1&1\end{bmatrix},\quad V=\begin{bmatrix}1&-1\\2&0\\3&-1\end{bmatrix}.

For example, Q’s first row is (1,2)(1,2). Multiplying the same numerical WQ by the input column (1,0)T(1,0)^{\mathsf T} would instead give (1,0)T(1,0)^{\mathsf T}. That counterexample explains why “the matrices are square” is not a reason to ignore orientation.

Smaller widths and honest boundaries

Dk=1 retains the first column of WQ and WK, including both input-feature rows. It does not keep just the first input coordinate. In the nonsymmetric example, the surviving Q coordinates are 1,0,11,0,1 and the K coordinates are 0,1,10,1,1. Dv=1 similarly keeps WV’s first column and gives value coordinates 1,2,31,2,3. Reducing T selects the active position prefix; increasing B activates the separately supplied second batch.

All twelve input slots and twelve weight slots remain validated, including inactive slots. Each must be a finite number in [−4,4][-4,4]: an ordinary numerical value, excluding infinity and undefined numerical results. Missing or extra fields, invalid dimensions and nonnumeric entries are rejected rather than silently repaired. The complete base state has these twenty-four numbers plus B, T, Dk and Dv. There is no editable D field. Numeric tensors use binary64, also called double precision or float64: a finite-precision format that approximates real numbers. The tables expose stored values; formatting is not an extra projection operation.

Changing WV can change V but cannot change Q or K in this calculation. Changing an input row can change all three projections of that row. A zero input row produces three zero rows because there is no bias. Distinct inputs can also map to the same output when a projection discards a direction. These are linear-algebra facts, not evidence that the demonstration has learned which words mean the same thing.

Read the actual Python and its helper

Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""IV22: queries, keys and values from explicit row-feature projections.

Defaults use identity weights. For the nonsymmetric worked example set
WQ=[[1,2],[0,1]], WK=[[0,1],[1,0]], WV=[[1,-1],[2,0]]. Each helper trace
records both scalar products and their sum; no semantic learning is claimed.
"""
from types import MappingProxyType
from attention_reference import PROJECTION_DEFAULTS, attention_trace, guarded, project, run, validated_state

DEFAULT_IV22 = MappingProxyType(dict(PROJECTION_DEFAULTS))


@guarded
def derive_iv22(state):
    """Return active Q/K/V arrays, their named tensors and every scalar product."""
    s = validated_state(state, attention=False)
    trace = attention_trace()
    projection = project(s, trace)
    summary = dict(B=s["B"], T=s["T"], Dk=s["Dk"], Dv=s["Dv"])
    summary.update(projection["aliases"])
    return trace.result(summary, projection["tensors"])


if __name__ == "__main__":
    run(derive_iv22, DEFAULT_IV22)
Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""Shared IV22–24 source: strict states, explicit scalar loops, NumPy storage.

X uses row features: Q[b,t,f] = X[b,t,0]*WQ[0,f] + X[b,t,1]*WQ[1,f].
This is the transpose convention of a single column-vector map. No matmul,
BLAS reduction, broadcasting, learned parameters or value mixing is hidden here.
Keep this helper beside the lesson programs. Authored, never executed under hold.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np


class NumericalFault(ValueError):
    def __init__(self, code, reason):
        super().__init__(reason)
        self.code = code


def finite(value, label):
    # Accept actual numeric scalars, never booleans or numeric strings.
    if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = float(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


PROJECTION_DEFAULTS = MappingProxyType(dict(
    B=1, T=3, Dk=2, Dv=2,
    x000=1, x001=0, x010=0, x011=1, x020=1, x021=1,
    x100=1, x101=1, x110=-1, x111=0, x120=0, x121=2,
    wq00=1, wq01=0, wq10=0, wq11=1,
    wk00=1, wk01=0, wk10=0, wk11=1,
    wv00=1, wv01=0, wv10=0, wv11=1,
))
ATTENTION_DEFAULTS = MappingProxyType(dict(
    **PROJECTION_DEFAULTS, mode=1, valid0=1, valid1=1, valid2=1, shift=0,
))


def validated_state(state, attention=False):
    defaults = ATTENTION_DEFAULTS if attention else PROJECTION_DEFAULTS
    if type(state) not in (dict, MappingProxyType):
        raise NumericalFault("INVALID_INPUT", "Use a plain object containing exactly the named scalar fields.")
    if set(state) != set(defaults):
        raise NumericalFault("INVALID_INPUT", "Provide every named scalar field and no extra fields, including inactive slots.")
    integer_bounds = dict(B=(1, 2), T=(1, 3), Dk=(1, 2), Dv=(1, 2),
                          mode=(0, 3), valid0=(0, 1), valid1=(0, 1), valid2=(0, 1))
    result = {}
    # Defaults determine record order, regardless of the incoming object's order.
    for key in defaults:
        value = finite(state[key], key)
        low, high = integer_bounds.get(key, (-10000, 10000) if key == "shift" else (-4, 4))
        if value < low or value > high:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
        if key in integer_bounds and not value.is_integer():
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
        result[key] = int(value) if key in integer_bounds else value
    return result


def guarded(derive):
    @wraps(derive)
    def call(state):
        try:
            return derive(state)
        except NumericalFault as error:
            return {"status": "unavailable", "code": error.code, "reason": str(error)}
        except (OverflowError, FloatingPointError) as error:
            return {"status": "unavailable", "code": "NONFINITE", "reason": str(error)}
    return call


def numbers(values):
    return {key: finite(value, key) for key, value in values.items()}


class AttentionTrace:
    def __init__(self):
        self.outputs = {}
        self.steps = []

    def add(self, identifier, label, equation, explanation, inputs, values):
        inputs, values = numbers(inputs), numbers(values)
        self.outputs.update({f"{identifier}_{key}": value for key, value in values.items()})
        self.steps.append({"id": identifier, "label": label, "equation": equation,
                           "explanation": explanation, "inputs": inputs, "outputs": values})

    def result(self, summary, tensors):
        return {"status": "defined", "outputs": numbers({**summary, **self.outputs}),
                "steps": self.steps, "tensors": tensors}


def attention_trace():
    return AttentionTrace()


def tensor(identifier, shape, axes, values, provenance):
    array = np.asarray(values, dtype=np.float64)
    if array.size != math.prod(shape) or len(shape) != len(axes) or len(set(axes)) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage must match the named dimensions.")
    # Flatten into detached Python scalars; no record retains a view of an array.
    flat = [finite(value, identifier) for value in array.reshape(-1)]
    return {"id": identifier, "shape": list(shape), "axes": list(axes), "dtype": "float64",
            "values": flat, "provenance": provenance, "precision": 8}


def project(s, trace):
    """Build real arrays, then trace Q, K, V in that order, each b,t,f."""
    B, T, Dk, Dv = s["B"], s["T"], s["Dk"], s["Dv"]
    # D stays 2; smaller Dk/Dv select leading weight COLUMNS, never input rows.
    X = np.empty((B, T, 2), dtype=np.float64)
    WQ = np.empty((2, Dk), dtype=np.float64)
    WK = np.empty((2, Dk), dtype=np.float64)
    WV = np.empty((2, Dv), dtype=np.float64)
    for b in range(B):
        for t in range(T):
            for d in range(2):
                X[b, t, d] = s[f"x{b}{t}{d}"]
    for weights, prefix, width in ((WQ, "wq", Dk), (WK, "wk", Dk), (WV, "wv", Dv)):
        for d in range(2):
            for f in range(width):
                weights[d, f] = s[f"{prefix}{d}{f}"]
    Q = np.empty((B, T, Dk), dtype=np.float64)
    K = np.empty((B, T, Dk), dtype=np.float64)
    V = np.empty((B, T, Dv), dtype=np.float64)
    trace.add("setup", "Validate all scalar inputs and select active dimensions", "D=2; X[B,T,D]; WQ,WK[D,Dk]; WV[D,Dv]",
              "All stored slots are validated. Active tensors use only the selected batches, time prefix and leading output columns; neither input-feature row is removed.",
              s, dict(B=B, T=T, D=2, Dk=Dk, Dv=Dv))
    aliases = {}
    for name, weights, output, width in (("Q", WQ, Q, Dk), ("K", WK, K, Dk), ("V", WV, V, Dv)):
        for b in range(B):
            for t in range(T):
                for f in range(width):
                    x0, x1 = float(X[b, t, 0]), float(X[b, t, 1])
                    w0, w1 = float(weights[0, f]), float(weights[1, f])
                    product0 = finite(x0 * w0, "projection product0")
                    product1 = finite(x1 * w1, "projection product1")
                    value = finite(product0 + product1, "projection value")
                    output[b, t, f] = value
                    aliases[f"{name.lower()}{b}{t}{f}"] = value
                    trace.add(f"project_{name}_{b}_{t}_{f}", f"{name}[{b},{t},{f}]: two input-feature contributions",
                              "product0=x0*w0; product1=x1*w1; value=product0+product1",
                              "One token row times one weight column. Both products are computed separately, then added; no bias, activation or training is hidden.",
                              dict(b=b, t=t, f=f, x0=x0, x1=x1, w0=w0, w1=w1),
                              dict(product0=product0, product1=product1, value=value))
    tensors = [
        tensor("X", [B, T, 2], ["B", "T", "D"], X, "Active input token rows, selected without padding or broadcasting."),
        tensor("WQ", [2, Dk], ["D", "Dk"], WQ, "Both input rows; leading Dk query columns of the editable WQ."),
        tensor("WK", [2, Dk], ["D", "Dk"], WK, "Both input rows; leading Dk key columns of the editable WK."),
        tensor("WV", [2, Dv], ["D", "Dv"], WV, "Both input rows; leading Dv value columns of the editable WV."),
        tensor("Q", [B, T, Dk], ["B", "T", "Dk"], Q, "Q=XWQ, with each coordinate traced as two products and one sum."),
        tensor("K", [B, T, Dk], ["B", "T", "Dk"], K, "K=XWK, with each coordinate traced as two products and one sum."),
        tensor("V", [B, T, Dv], ["B", "T", "Dv"], V, "V=XWV, available for later value mixing; not mixed in IV-22–24."),
    ]
    return dict(X=X, WQ=WQ, WK=WK, WV=WV, Q=Q, K=K, V=V, aliases=aliases, tensors=tensors)


def score(s, projection, trace):
    """Compute one feature product at a time; scaling is not normalization."""
    B, T, Dk = s["B"], s["T"], s["Dk"]
    Q, K = projection["Q"], projection["K"]
    raw = np.empty((B, T, T), dtype=np.float64)
    scores = np.empty((B, T, T), dtype=np.float64)
    divisor = finite(math.sqrt(Dk), "score divisor")
    aliases = {}
    for b in range(B):
        for i in range(T):
            for j in range(T):
                q0, k0 = float(Q[b, i, 0]), float(K[b, j, 0])
                inputs = dict(b=b, i=i, j=j, Dk=Dk, divisor=divisor, q0=q0, k0=k0)
                product0 = finite(q0 * k0, "score product0")
                values = dict(product0=product0)
                dot = product0
                if Dk == 2:
                    q1, k1 = float(Q[b, i, 1]), float(K[b, j, 1])
                    inputs.update(q1=q1, k1=k1)
                    product1 = finite(q1 * k1, "score product1")
                    values["product1"] = product1
                    dot = finite(product0 + product1, "raw score")
                scaled = finite(dot / divisor, "scaled score")
                raw[b, i, j], scores[b, i, j] = dot, scaled
                values.update(raw=dot, score=scaled)
                aliases[f"raw{b}{i}{j}"] = dot
                aliases[f"score{b}{i}{j}"] = scaled
                trace.add(f"score_{b}_{i}_{j}", f"Batch {b}: query {i} against key {j}",
                          "product0=q0*k0; raw=product0; score=raw/sqrt(Dk)" if Dk == 1 else
                          "product0=q0*k0; product1=q1*k1; raw=product0+product1; score=raw/sqrt(Dk)",
                          "Compare matching query/key features in the same batch. The divisor uses key-feature width Dk, not time length T or value width Dv. A signed score is not a probability.",
                          inputs, values)
    tensors = [tensor("raw", [B, T, T], ["B", "Query", "Key"], raw, "QK transpose: explicit feature products followed by their sum, within each batch."),
               tensor("scores", [B, T, T], ["B", "Query", "Key"], scores, "Raw query-key agreement divided by sqrt(Dk); not softmax probabilities.")]
    return dict(raw=raw, scores=scores, aliases=aliases, tensors=tensors)


def stable_softmax(logits, allowed):
    """Scalar counterpart of platform stableSoftmax; reject an empty support."""
    if len(logits) != len(allowed) or not 1 <= len(logits) <= 64:
        raise NumericalFault("SHAPE_MISMATCH", "A boolean allowed mask must match 1–64 logits.")
    logits = [finite(value, f"logit {j}") for j, value in enumerate(logits)]
    if any(type(value) is not bool for value in allowed):
        raise NumericalFault("INVALID_INPUT", "Every mask entry must be boolean.")
    candidates = [value for j, value in enumerate(logits) if allowed[j]]
    if not candidates:
        raise NumericalFault("FULLY_MASKED_ROW", "This query has no allowed keys; no probability distribution exists.")
    maximum = max(candidates)
    # Match Math.max zero ties without erasing an all-negative-zero maximum.
    if maximum == 0.0 and any(value == 0.0 and math.copysign(1.0, value) > 0.0 for value in candidates):
        maximum = 0.0
    terms = []
    denominator = 0.0
    for j in range(len(logits)):
        # An allowed exp can underflow to 0; the boolean mask still says allowed.
        term = math.exp(finite(logits[j] - maximum, "shifted logit")) if allowed[j] else 0.0
        terms.append(finite(term, "softmax term"))
        denominator = finite(denominator + term, "softmax denominator")
    probabilities = []
    for term in terms:
        probabilities.append(finite(term / denominator, "softmax probability"))
    return dict(max=maximum, terms=terms, denominator=denominator, probabilities=probabilities)


def normalize(s, scored, trace):
    """Retain every query; mask keys, then normalize along each row's key axis."""
    B, T = s["B"], s["T"]
    # Keep real finite logits for forbidden keys too; never invent -infinity.
    allowed = np.empty((B, T, T), dtype=np.bool_)
    logits = np.empty((B, T, T), dtype=np.float64)
    probabilities = np.empty((B, T, T), dtype=np.float64)
    aliases = {}
    causal = s["mode"] in (1, 3)
    padding = s["mode"] in (2, 3)
    for b in range(B):
        for i in range(T):
            row_logits, row_allowed = [], []
            inputs = dict(b=b, i=i, mode=s["mode"], shift=s["shift"])
            for j in range(T):
                value = float(scored["scores"][b, i, j])
                inputs[f"score{j}"] = value
                permit = (not causal or j <= i) and (not padding or s[f"valid{j}"] == 1)
                allowed[b, i, j] = permit
                logit = finite(value + s["shift"], "shifted score")
                logits[b, i, j] = logit
                row_logits.append(logit)
                row_allowed.append(permit)
            for j in range(T):
                inputs[f"allowed{j}"] = 1 if row_allowed[j] else 0
            if not any(row_allowed):
                raise NumericalFault("FULLY_MASKED_ROW", f"Batch {b}, query {i} has no allowed keys; no probability distribution exists.")
            row = stable_softmax(row_logits, row_allowed)
            values = dict(max=row["max"], denominator=row["denominator"])
            # These are the actual shifted operands passed to exp; forbidden keys
            # have no shifted operand and therefore no fabricated shifted field.
            for j in range(T):
                if row_allowed[j]:
                    values[f"shifted{j}"] = finite(row_logits[j] - row["max"], "shifted logit")
            for j in range(T):
                values[f"term{j}"] = row["terms"][j]
            for j in range(T):
                probability = row["probabilities"][j]
                values[f"p{j}"] = probability
                probabilities[b, i, j] = probability
                aliases[f"p{b}{i}{j}"] = probability
            trace.add(f"row_{b}_{i}", f"Batch {b}: masked key-axis softmax for query {i}",
                      "logit_j=score_j+shift; max=max(allowed logits); term_j=allowed_j?exp(logit_j-max):0; denominator=sum_j term_j; p_j=term_j/denominator",
                      "Keys alone are masked; every query remains. Terms sum in increasing key order. Forbidden keys have exact zero probability; allowed terms can also underflow to zero in binary64. The common shift preserves real softmax but can change rounded results.",
                      inputs, values)
    allowed_record = tensor("allowed", [B, T, T], ["B", "Query", "Key"], allowed.astype(np.float64),
                            "True means this key may contribute to this query; key validity is shared across batches.")
    # Validate 0/1 storage through tensor first, then expose actual JSON booleans.
    allowed_record["values"] = [bool(value) for value in allowed_record["values"]]
    allowed_record["dtype"] = "bool"
    tensors = [allowed_record,
               tensor("logits", [B, T, T], ["B", "Query", "Key"], logits, "Finite score+common shift for every active key, including forbidden keys; no mask sentinel."),
               tensor("probabilities", [B, T, T], ["B", "Query", "Key"], probabilities,
                      "Allowed-key stable softmax along the key axis only. Forbidden keys have exactly zero; allowed exponential underflow is separately possible.")]
    return dict(allowed=allowed, logits=logits, probabilities=probabilities, aliases=aliases, tensors=tensors)


_JSON_INT = int


def run(derive, defaults):
    """No argument: defaults. A JSON object fully replaces them; '-' reads stdin."""
    class ParseFault(ValueError):
        """Only locally owned JSON profile/conversion faults."""

    def _members(pairs):
        value = {}
        for key, member in pairs:
            if key in value:
                raise ParseFault("Duplicate JSON object members are not allowed.")
            value[key] = member
        return value

    def _constant(token):
        raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")

    def _integer(token):
        if token == "-0":
            return -0.0
        try:
            return _JSON_INT(token)
        except ValueError as fault:
            if type(fault) is not ValueError:
                raise
            raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from fault

    parser = argparse.ArgumentParser(description=derive.__doc__)
    parser.add_argument("state", nargs="?")
    args = parser.parse_args()
    if args.state is not None:
        source = sys.stdin.read() if args.state == "-" else args.state
        try:
            state = json.loads(source, object_pairs_hook=_members,
                               parse_constant=_constant, parse_int=_integer)
        except (json.JSONDecodeError, ParseFault) as error:
            result = {"status": "unavailable", "code": "INVALID_INPUT", "reason": str(error)}
        else:
            result = derive(state)
    else:
        result = derive(dict(defaults))
    print(json.dumps(result, allow_nan=False, separators=(",", ":")))

The chapter source calls the shared projection machinery; the helper exposes validation and the explicit coordinate products. Match product0, product1 and value to the two multiplication terms and their sum above. The projection trace names Q, then K, then V, with batch, position and feature indices identifying each output. Arrays hold actual active shapes; inactive coordinates are not invented outputs.

The helper also supports the next lessons’ scores and normalization. Those later functions do not make them part of IV-22’s projection-only result. The displayed code is imported from the actual files, with comments, rather than rewritten as a disconnected teaching snippet.

Five exercises matched to the lab

  1. What are Q, K and V in this lab? They are three linear projections of the same input rows using separate weight matrices. Q uses WQ, K uses WK, and V uses WV. They are not probabilities or outputs learned by moving controls. They equal X at the two-feature identity reset because of those particular weights, rather than because their roles require equality.
  2. For the current controls, which shapes are correct? Q has shape [B,T,Dk] and V has shape [B,T,Dv]; substitute the current four dimension controls. Reset gives [1,3,2] for both. For B=2, T=1, Dk=1 and Dv=2, the shapes would instead be [2,1,1] and [2,1,2]. A query tensor is not the later [B,T,T] comparison tensor. Taking one output column still keeps both input-feature rows in its weight matrix.
  3. Use the current operands: what is Q[0,0,0]? Compute x000*wq00 + x001*wq10, forming both products before adding. These fields are batch zero, token zero’s two input features and output column zero of WQ. At reset, 1(1)+0(0)=1+0=11(1)+0(0)=1+0=1. The current answer is q000, also value in trace project_Q_0_0_0; its product0 and product1 supply the corrective arithmetic after any edit. Do not substitute WQ’s first row for its first column.
  4. Change only WV while holding X, WQ, WK and all dimensions fixed. Which projected tensor can change? Only V. Neither Q nor K has WV as an operand. “Can change” does not mean every weight edit must alter V: changing a weight multiplied by zero can leave the output unchanged. Changing WV cannot make Q or K change through an undeclared connection.
  5. Transfer to row x=[1,0] and WQ=[[1,2],[0,1]]. What is xWQ? The query row is [1,2][1,2]: feature zero is 1(1)+0(0)=11(1)+0(0)=1, and feature one is 1(2)+0(1)=21(2)+0(1)=2. The answer [1,0][1,0] would result from using the unchanged numerical matrix on the input column instead. The equivalent column-vector map uses transposed weights, qcol=WQTxcolq_{\rm col}=W_Q^{\mathsf T}x_{\rm col}. Load the nonsymmetric example to inspect that distinction.

Recap and bridge

Three matrices map the same token rows into three computational roles. Each output adds two explicit products. Shapes distinguish positions from features, and row-feature weights are the transpose of the equivalent column-vector weights. Identity matrices are useful for a first example but insufficient for checking orientation.

Next, IV-23 — Dot-Product Attention Scores and Scaling compares each query with each key, then scales those comparisons by the query/key feature width.