Transformers, one matrix at a time.

GPT, Claude and the comfort model from my M.S. defense are built from the same few operations: matrix products, softmax, LayerNorm, and an optimizer that nudges numbers. This page runs a real Transformer in your browser, small enough that every number fits on screen, and shows how those operations turn four sensor readings into a prediction.

Nothing faked

Every matrix is computed live from the input you choose.

Hover any number

See the row, the column and the dot product that produced it.

Train it yourself

Watch backprop and Adam move all 227 weights.

Color keypositive valuenegative valuerow operandcolumn operandresult entry
0

Predict how a person feels from 45 minutes of sensors

The task is the one from my M.S. defense, shrunk. Three signals are read every 15 minutes: air temperature, relative humidity and smartwatch heart rate. From the last four readings the model has to say whether the person feels Cool, Neutral or Warm.

Each row is one time step. In Transformer language a row is a token: GPT reads a row per word, this model reads a row per reading. The last row, t, is the moment the person answers the survey.

So that you can check the model against a known answer, the 596 examples are labelled by a transparent teaching rule rather than real surveys. The model never sees the rule. It sees 476 labelled examples (another 120 are held out for validation, the same 476/120 split as the field data in the thesis) and has to discover it.

Xraw∈RT×F,T=4,  F=3X^{\text{raw}} \in \mathbb{R}^{T \times F},\quad T = 4,\; F = 3

The teaching rule (hidden from the model):

s=0.5 (Tt−24)+0.05 (HR‾−75)+0.02 (RHt−50)+0.4 (Tt−Tt−45)\begin{aligned} s = {} & 0.5\,(T_t - 24) + 0.05\,(\overline{HR} - 75) \\ & + 0.02\,(RH_t - 50) + 0.4\,(T_t - T_{t-45}) \end{aligned}
y={Cools<−0.75Warms>0.75Neutralotherwisey = \begin{cases}\text{Cool} & s < -0.75\\ \text{Warm} & s > 0.75\\ \text{Neutral} & \text{otherwise}\end{cases}
Air temp (°C)Humidity (%)Heart rate (bpm)
t−45
t−30
t−15
t

Warm

s = 3.54

Edit any reading or pick a preset. Every matrix below is recomputed from this table, instantly.

  1. X4×3
  2. →Z⁽⁰⁾4×4
  3. →Q4×4
  4. →S₁4×4
  5. →A₁4×4
  6. →MHSA4×4
  7. →Z̃4×4
  8. →ReLU(F)4×8
  9. →Z⁽¹⁾4×4
  10. →zₜ1×4
  11. →p1×3

Blue = positive, red = negative, darker = larger. Change the input or press Train and the whole chain recolors.

①

Put every signal on the same scale

Temperature sits near 24, humidity near 51 and heart rate near 79. If they went in raw, the biggest numbers would dominate every dot product that follows. So each column is shifted by its training-set mean and divided by its standard deviation: afterwards 0 means “typical” and ±1 means “one standard deviation away”.

The mean and standard deviation come from the 476 training examples only, never from the validation set.

xt,f=xt,fraw−μfσfx_{t,f} = \frac{x^{\text{raw}}_{t,f} - \mu_f}{\sigma_f}

μ\mu = (24.04, 50.70, 79.27)  ·  σ\sigma = (2.88, 11.91, 12.57)

XrawX^{\text{raw}}4 × 3
tempRHHRt−45t−30t−15t24.652.076.025.653.079.026.754.082.027.855.084.0
→
XX4 × 3
tempRHHRt−45t−30t−15t

Air temp at t: (27.8 − 24.04) ÷ 2.88 = 1.31hover or tap any cell of X

x = (x_raw - mu) / sigma
# (4, 3) → (4, 3); mu, sigma: (3,) from the training set
②

Turn each reading into a vector the model can work with

A linear layer turns each 3-number row into a 4-number row, the model's working width dmodeld_{\text{model}}. That is one matrix multiplication. Every output number is a dot product between one row of XX (one time step) and one column of WeW_e(one learned “feature detector”).

Attention, coming next, treats its rows as a set: shuffle the rows and its outputs shuffle the same way. To know which reading came first, the model adds a learned vector to each row, one per position. That is PP. It starts at zero (it still is: press Train and watch it fill in).

Finally each row is re-centered and re-scaled by LayerNorm, so no row can drift to huge values.

E=X We+beE = \htmlClass{tx-row}{X}\,\htmlClass{tx-col}{W_e} + b_e
(4×3) (3×4)→4×4(4{\times}3)\,(3{\times}4) \to 4{\times}4
U=E+P,Z(0)=LN(U)U = E + P, \qquad Z^{(0)} = \mathrm{LN}(U)
LN(u)=γ⊙u−μσ2+ϵ+β\mathrm{LN}(u) = \gamma \odot \frac{u - \mu}{\sqrt{\sigma^2 + \epsilon}} + \beta
XX4 × 3
tempRHHRt−45t−30t−15t0.200.11−0.260.540.19−0.020.920.280.221.310.360.38
·
WeW_e3 × 4
d₁d₂d₃d₄tempRHHR0.25−0.53−0.05−0.490.30−0.02−0.02−0.39−0.270.06−0.35−0.48
+
beb_e1 × 4
d₁d₂d₃d₄0.25−0.030.340.44
=
EE4 × 4
d₁d₂d₃d₄t−45t−30t−15t
row 4 of XX · column 1 of WeW_e =1.31×0.25+0.36×0.30+0.38×−0.27
=0.332+0.110+−0.103=0.339+ bias0.25=0.586

Largest term: 1.31 × 0.25 (temp) carries 61% of the total magnitude of the terms.

EE4 × 4
d₁d₂d₃d₄t−45t−30t−15t0.40−0.150.420.420.45−0.320.320.110.51−0.510.21−0.230.59−0.710.14−0.52
+
PP4 × 4
d₁d₂d₃d₄t−45t−30t−15t0.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.00
=
UU4 × 4
d₁d₂d₃d₄t−45t−30t−15t0.40−0.150.420.420.45−0.320.320.110.51−0.510.21−0.230.59−0.710.14−0.52
UU4 × 4
d₁d₂d₃d₄t−45t−30t−15t
→
Z(0)Z^{(0)}4 × 4
d₁d₂d₃d₄t−45t−30t−15t
row0.59−0.710.14−0.52μ = −0.128, σ = 0.518
(x − μ)/σ1.38−1.120.51−0.77mean 0, variance 1
× γ0\gamma_0 + β0\beta_01.38−1.120.51−0.77γ0\gamma_0 = (1.00, 1.00, 1.00, 1.00), β0\beta_0 = (0.00, 0.00, 0.00, 0.00)
z = ln0(embed(x) + pos) # embed = nn.Linear(3, 4)
# (4, 3) @ (3, 4) → (4, 4); 48 multiply-adds

PyTorch stores embed.weight as 4×3 and computes x @ W.T + b. The math above writes the same numbers as a 3×4 matrix.

Pretraining: 12 steps × 17 ASHRAE features projected to 256, so We∈R17×256W_e \in \mathbb{R}^{17\times256}. For the 6 local features the adapter replaces it: two linear layers, 6 → 128 → 256, trained on local data.

③

Every step asks a question and offers an answer

Three learned matrices project each row into three new vectors. The query says what this step is looking for, the key says what it contains, and the value is what it hands over if another step decides to listen to it.

With 2 heads, the 4 columns are split into two blocks of dk=2d_k = 2. Each head runs the next three steps in its own small space, so one head can track temperature trends while the other tracks heart rate. They are recombined in step ⑥.

Qh=Z WhQ+bhQKh=Z WhK+bhKVh=Z WhV+bhV\begin{aligned} Q_h &= Z\,W^Q_h + b^Q_h \\ K_h &= Z\,W^K_h + b^K_h \\ V_h &= Z\,W^V_h + b^V_h \end{aligned}
WhQ∈Rdmodel×dk=R4×2W^Q_h \in \mathbb{R}^{d_{\text{model}} \times d_k} = \mathbb{R}^{4\times 2}
Z(0)Z^{(0)}4 × 4
d₁d₂d₃d₄t−45t−30t−15t0.52−1.730.590.621.07−1.570.61−0.111.31−1.290.55−0.571.38−1.120.51−0.77
·
W1QW^Q_14 × 2
c₁c₂d₁d₂d₃d₄−0.220.230.030.410.46−0.23−0.100.26
+
b1Qb^Q_11 × 2
c₁c₂0.000.00
=
Q1Q_14 × 2
c₁c₂t−45t−30t−15t
row 4 of Z(0)Z^{(0)} · column 1 of W1QW^Q_1 =1.38×−0.22+−1.12×0.03+0.51×0.46+−0.77×−0.10
=−0.298+−0.036+0.235+0.075=−0.025+ bias0.00=−0.025

Largest term: 1.38 × −0.22 (d₁) carries 46% of the total magnitude of the terms.

W1KW^K_14 × 2
c₁c₂d₁d₂d₃d₄0.27−0.610.440.130.100.100.040.41
→
K1K_14 × 2
c₁c₂t−45t−30t−15t−0.54−0.22−0.35−0.83−0.18−1.14−0.10−1.25
W1VW^V_14 × 2
c₁c₂d₁d₂d₃d₄0.000.090.20−0.16−0.040.590.220.55
→
V1V_14 × 2
c₁c₂t−45t−30t−15t−0.241.01−0.370.64−0.410.33−0.420.17

K1K_1 and V1V_1 come from the same Z(0)Z^{(0)} by the same recipe, with their own weights.

q, k, v = (z @ W_qkv + b_qkv).chunk(3, dim=-1) q = q.view(T, heads, d_k) # split columns into heads
# (4, 4) @ (4, 12) → 3 × (4, 4) → (4, 2, 2)

8 heads × 32 dims = 256 columns. Each head has its own 12×3212\times32 query, key and value matrices.

④

How much should each step listen to every other step?

The dot product of a query with a key is large when they point the same way. Doing it for all 16 pairs of steps at once is one matrix product, QK⊤QK^\top: row i holds step i's scores for every step j.

Dot products grow with the width of the vectors, so they are divided by dk\sqrt{d_k}. Without it, the softmax in the next step would saturate and its gradients would vanish.

This is the step that makes Transformers expensive: T2T^2 scores per head. 16 here, 144 in T3C, about a million per head per layer in a 1,024-token GPT-2 context.

Sh=Qh Kh⊤dk∈RT×TS_h = \frac{\htmlClass{tx-row}{Q_h}\,\htmlClass{tx-col}{K_h^\top}}{\sqrt{d_k}} \in \mathbb{R}^{T\times T}
(Sh)ij=qi⋅kj2(S_h)_{ij} = \frac{q_i \cdot k_j}{\sqrt{2}}
Q1Q_14 × 2
c₁c₂t−45t−30t−15t0.05−0.560.01−0.56−0.01−0.50−0.02−0.45
·
K1⊤K_1^\top2 × 4
t−45t−30t−15tc₁c₂−0.54−0.35−0.18−0.10−0.22−0.83−1.14−1.25
×12\times \tfrac{1}{\sqrt{2}}=
S1S_14 × 4
t−45t−30t−15tt−45t−30t−15t
row 4 of Q1Q_1 · column 1 of K1⊤K_1^\top =−0.02×−0.54+−0.45×−0.22
=0.013+0.100=0.113×12\tfrac{1}{\sqrt{2}}=0.080=0.080

Largest term: −0.45 × −0.22 (c₂) carries 88% of the total magnitude of the terms.

scores = q @ k.transpose(-2, -1) / math.sqrt(d_k)
# (2, 4, 2) @ (2, 2, 4) → (2, 4, 4): one 4×4 score matrix per head
⑤

Turn scores into attention weights that sum to one

Scores can be any real number. Softmax turns each row into a probability distribution: exponentiate (so everything is positive and large scores dominate), then divide by the row sum (so the row sums to 1).

Subtracting the row maximum first changes nothing mathematically, because it cancels in the ratio, but it keeps exe^x from overflowing. The same fact explains why the key bias bKb^K never learns: it adds the same constant to every score in a row, so its gradient is exactly zero (check it in step ⑪).

Aij=eSij∑keSik=eSij−mi∑keSik−miA_{ij} = \frac{e^{S_{ij}}}{\sum_{k} e^{S_{ik}}} = \frac{e^{S_{ij} - m_i}}{\sum_k e^{S_{ik} - m_i}}
mi=max⁡kSikm_i = \max_k S_{ik}
∑jAij=1,Aij>0\textstyle\sum_j A_{ij} = 1,\quad A_{ij} > 0
S1S_14 × 4
t−45t−30t−15tt−45t−30t−15t
→
A1A_14 × 4
t−45t−30t−15tt−45t−30t−15t
Bold = where each row attends most. Darker = larger weight.
query (row)key (column)t−45t−30t−15tt−4520%t−3025%t−1527%t28%
Head 1, row t: line width = attention weight. Hover a query on the left to switch rows.
jt−45t−30t−15t
score s0.080.270.370.40max m = 0.40
s − m−0.32−0.13−0.030.00
e^(s − m)0.7250.8790.9671.000Σ = 3.570
÷ Σ0.2030.2460.2710.280sums to 1.000
weights = scores.softmax(dim=-1)
# (2, 4, 4) → (2, 4, 4); every row sums to 1
⑥

Each step becomes a weighted average of what it attended to

The attention weights are a recipe. Row t of AhVhA_hV_h is the weighted average of all four value rows, using row t of AhA_h as the weights. This is how the survey moment collects information from 45 minutes earlier.

The two heads' 4×2 outputs are placed side by side (4×4) and one more matrix, WOW^O, mixes them back into the model's width.

Hh=Ah Vh∈R4×2H_h = \htmlClass{tx-row}{A_h}\,\htmlClass{tx-col}{V_h} \in \mathbb{R}^{4\times 2}
MHSA(Z)=[ H1 ∥ H2 ] WO+bO\mathrm{MHSA}(Z) = [\,H_1 \,\Vert\, H_2\,]\,W^O + b^O
A1A_14 × 4
t−45t−30t−15tt−45t−30t−15t0.190.240.280.290.190.240.280.290.200.250.270.280.200.250.270.28
·
V1V_14 × 2
c₁c₂t−45t−30t−15t−0.241.01−0.370.64−0.410.33−0.420.17
=
H1H_14 × 2
c₁c₂t−45t−30t−15t
row 4 of A1A_1 · column 1 of V1V_1 =0.20×−0.24+0.25×−0.37+0.27×−0.41+0.28×−0.42
=−0.049+−0.091+−0.111+−0.117=−0.369=−0.369

Largest term: 0.28 × −0.42 (t) carries 32% of the total magnitude of the terms.

[H1∥H2][H_1 \Vert H_2]4 × 4
H₁c₁H₁c₂H₂c₁H₂c₂t−45t−30t−15t−0.370.490.230.42−0.370.490.230.42−0.370.490.230.41−0.370.500.230.41
·
WOW^O4 × 4
d₁d₂d₃d₄H₁c₁H₁c₂H₂c₁H₂c₂−0.430.040.37−0.160.04−0.21−0.040.050.08−0.110.26−0.330.450.140.250.27
+
bOb^O1 × 4
d₁d₂d₃d₄0.000.000.000.00
=
MHSA\mathrm{MHSA}4 × 4
d₁d₂d₃d₄t−45t−30t−15t
row 4 of [H1∥H2][H_1 \Vert H_2] · column 1 of WOW^O =−0.37×−0.43+0.50×0.04+0.23×0.08+0.41×0.45
=0.160+0.020+0.018+0.186=0.384+ bias0.00=0.384

Largest term: 0.41 × 0.45 (H₂c₂) carries 49% of the total magnitude of the terms.

out = (weights @ v).transpose(0, 1).reshape(T, d_model) out = out @ W_o + b_o
# (2, 4, 4) @ (2, 4, 2) → (2, 4, 2) → (4, 4) → (4, 4)

8 heads of 12×32 are concatenated to 12×256, then WO∈R256×256W^O \in \mathbb{R}^{256\times256}. The whole attention block has 263,168 parameters per layer.

⑦

Add the input back, then normalize

The attention output is not used on its own. It is added to the input it was computed from, so the block only has to learn a correction to Z(0)Z^{(0)}. That sum is also a highway for gradients: during training, the derivative of Z+f(Z)Z + f(Z) always contains the identity, so the signal reaches the early layers even when ff is small. This is what makes stacks of 6 (T3C), 12 (GPT-2) or 100+ layers trainable.

T3C is a post-norm Transformer: LayerNorm comes after the addition, as in the original 2017 paper.

Z~=LN(Z(0)+MHSA(Z(0)))\tilde Z = \mathrm{LN}\big(Z^{(0)} + \mathrm{MHSA}(Z^{(0)})\big)
∂∂Z(Z+f(Z))=I+∂f∂Z\frac{\partial}{\partial Z}\big(Z + f(Z)\big) = I + \frac{\partial f}{\partial Z}
Z(0)Z^{(0)}4 × 4
d₁d₂d₃d₄t−45t−30t−15t0.52−1.730.590.621.07−1.570.61−0.111.31−1.290.55−0.571.38−1.120.51−0.77
+
MHSA\mathrm{MHSA}4 × 4
d₁d₂d₃d₄t−45t−30t−15t0.39−0.080.010.120.39−0.080.010.120.39−0.080.010.120.38−0.080.010.12
=
RR4 × 4
d₁d₂d₃d₄t−45t−30t−15t0.91−1.810.600.741.46−1.650.620.021.69−1.370.56−0.451.76−1.200.52−0.65
RR4 × 4
d₁d₂d₃d₄t−45t−30t−15t
→
Z~\tilde Z4 × 4
d₁d₂d₃d₄t−45t−30t−15t
row1.76−1.200.52−0.65μ = 0.107, σ = 1.139
(x − μ)/σ1.45−1.150.36−0.66mean 0, variance 1
× γ1\gamma_1 + β1\beta_11.45−1.150.36−0.66γ1\gamma_1 = (1.00, 1.00, 1.00, 1.00), β1\beta_1 = (0.00, 0.00, 0.00, 0.00)
z = norm1(z + self_attn(z))
# (4, 4) + (4, 4) → (4, 4)
⑧

Think about each step on its own

Attention moved information between steps. The feed-forward network now processes each step by itself, with the same weights for every row: widen from 4 to 8, apply ReLU, narrow back to 4.

ReLU replaces every negative number with 0. Without this kink the two matrix products would collapse into one, W1W2W_1W_2, and the block could only compute linear functions. Right now ReLU zeroes 18 of 32 numbers (struck through below).

Then the same residual addition and LayerNorm as in step ⑦. Attention + feed-forward together form one encoder layer.

FFN(Z~)=ReLU(Z~W1+b1) W2+b2\mathrm{FFN}(\tilde Z) = \mathrm{ReLU}(\tilde Z W_1 + b_1)\,W_2 + b_2
ReLU(x)=max⁡(0,x)\mathrm{ReLU}(x) = \max(0, x)
Z(1)=LN(Z~+FFN(Z~))Z^{(1)} = \mathrm{LN}\big(\tilde Z + \mathrm{FFN}(\tilde Z)\big)
Z~\tilde Z4 × 4
d₁d₂d₃d₄t−45t−30t−15t0.72−1.720.440.571.18−1.550.45−0.081.39−1.300.40−0.491.45−1.150.36−0.66
·
W1W_14 × 8
h₁h₂h₃h₄h₅h₆h₇h₈d₁d₂d₃d₄−0.44−0.09−0.350.190.270.120.490.490.480.080.390.450.31−0.180.130.44−0.110.10−0.360.130.05−0.240.38−0.450.35−0.41−0.080.39−0.470.17−0.40−0.21
+
b1b_11 × 8
h₁h₂h₃h₄h₅h₆h₇h₈0.490.02−0.32−0.49−0.340.150.130.33
=
FF4 × 8
h₁h₂h₃h₄h₅h₆h₇h₈t−45t−30t−15t
row 4 of Z~\tilde Z · column 1 of W1W_1 =1.45×−0.44+−1.15×0.48+0.36×−0.11+−0.66×0.35
=−0.638+−0.553+−0.039+−0.230=−1.460+ bias0.49=−0.966

Largest term: 1.45 × −0.44 (d₁) carries 44% of the total magnitude of the terms.

FF4 × 8
h₁h₂h₃h₄h₅h₆h₇h₈t−45t−30t−15t−0.50−0.37−1.44−0.86−0.930.540.21−0.41−0.85−0.13−1.48−0.94−0.440.450.710.03−0.950.03−1.41−0.95−0.120.380.990.35−0.970.11−1.35−0.950.020.341.090.51
→ ReLU \xrightarrow{\ \mathrm{ReLU}\ }
ReLU(F)\mathrm{ReLU}(F)4 × 8
h₁h₂h₃h₄h₅h₆h₇h₈t−45t−30t−15t0.000.000.000.000.000.540.210.000.000.000.000.000.000.450.710.030.000.030.000.000.000.380.990.350.000.110.000.000.020.341.090.51
ReLU(F)\mathrm{ReLU}(F)4 × 8
h₁h₂h₃h₄h₅h₆h₇h₈t−45t−30t−15t0.000.000.000.000.000.540.210.000.000.000.000.000.000.450.710.030.000.030.000.000.000.380.990.350.000.110.000.000.020.341.090.51
·
W2W_28 × 4
d₁d₂d₃d₄h₁h₂h₃h₄h₅h₆h₇h₈0.130.22−0.26−0.22−0.260.080.120.050.16−0.130.32−0.290.33−0.22−0.080.00−0.040.04−0.160.12−0.35−0.030.20−0.12−0.04−0.090.35−0.30−0.28−0.22−0.260.26
+
b2b_21 × 4
d₁d₂d₃d₄0.190.24−0.08−0.31
=
FFN\mathrm{FFN}4 × 4
d₁d₂d₃d₄t−45t−30t−15t
row 4 of ReLU(F)\mathrm{ReLU}(F) · column 1 of W2W_2 =0.00×0.13+0.11×−0.26+0.00×0.16+0.00×0.33+0.02×−0.04+0.34×−0.35+1.09×−0.04+0.51×−0.28
=0.000+−0.029+0.000+0.000+−0.001+−0.116+−0.039+−0.142=−0.327+ bias0.19=−0.136

Largest term: 0.51 × −0.28 (h₈) carries 44% of the total magnitude of the terms.

Z~\tilde Z4 × 4
d₁d₂d₃d₄t−45t−30t−15t0.72−1.720.440.571.18−1.550.45−0.081.39−1.300.40−0.491.45−1.150.36−0.66
+
FFN\mathrm{FFN}4 × 4
d₁d₂d₃d₄t−45t−30t−15t0.000.210.10−0.430.000.150.25−0.56−0.080.060.24−0.55−0.140.030.24−0.53
→ LN \xrightarrow{\ \mathrm{LN}\ }
Z(1)Z^{(1)}4 × 4
d₁d₂d₃d₄t−45t−30t−15t0.84−1.680.650.191.19−1.320.72−0.591.28−1.070.67−0.881.30−0.940.64−1.00
z = norm2(z + linear2(relu(linear1(z))))
# (4, 4) → (4, 8) → (4, 8) → (4, 4)

256 → 512 → 256 (262,912 parameters). With attention and two LayerNorms, one encoder layer has 527,104 parameters, and T3C stacks 6 of them. This page runs 1.

⑨

Read the last row and decide

Only the last row, the survey moment, goes to the classifier. It is enough, because through attention that row has already collected what it needs from the three earlier readings.

One more matrix maps its 4 numbers to 3 logits, one score per class, and a softmax (the same function as step ⑤) turns them into probabilities.

These weights are still random, so the prediction is close to a coin toss. and watch these probabilities, and every matrix above, change.
zt=Zt,:(1)∈R1×4z_t = Z^{(1)}_{t,:} \in \mathbb{R}^{1\times4}
ℓ=zt Wc+bc∈R1×3\ell = \htmlClass{tx-row}{z_t}\,\htmlClass{tx-col}{W_c} + b_c \in \mathbb{R}^{1\times3}
p=softmax(ℓ),y^=arg⁡max⁡cpcp = \mathrm{softmax}(\ell),\qquad \hat y = \arg\max_c p_c
ztz_t1 × 4
d₁d₂d₃d₄t1.30−0.940.64−1.00
·
WcW_c4 × 3
CoolNeutralWarmd₁d₂d₃d₄−0.16−0.24−0.37−0.37−0.09−0.27−0.480.05−0.04−0.120.460.39
+
bcb_c1 × 3
CoolNeutralWarm0.40−0.21−0.18
=
ℓ\ell1 × 3
CoolNeutralWarmt
row 1 of ztz_t · column 3 of WcW_c =1.30×−0.37+−0.94×−0.27+0.64×−0.04+−1.00×0.39
=−0.477+0.253+−0.023+−0.396=−0.644+ bias−0.18=−0.820

Largest term: 1.30 × −0.37 (d₁) carries 42% of the total magnitude of the terms.

ℓ0.35−0.87−0.82
e^(ℓ − max)1.0000.2970.312
÷ 1.6080.6220.1840.194

Model: Cool

✗ rule says Warm

Cool
62.2%
Neutral
18.4%
Warm(rule)
19.4%
logits = head(z[:, -1]) # head = nn.Linear(4, 3) probs = logits.softmax(-1)
# (4, 4) → last row (4,) → (3,)
⑩

Score how wrong the prediction is

To learn, the model needs one number that says how bad its prediction was. Cross-entropy is minus the log of the probability it gave to the true class: 0 when it was certain and right, and very large when it was confident and wrong. The log punishes confident mistakes far more than hesitant ones.

Over a batch, each example is weighted by its class weight wc=N/(K Nc)w_c = N/(K\,N_c), so a mistake on a rare class costs more. In the thesis this kept the model from ignoring the rare “Uncomfortably Cool” class in ASHRAE (weight 1.28); here the weights are computed from the 476 training labels.

Lw=−∑iwyi log⁡pθ(yi∣Xi)∑iwyi\mathcal{L}_w = -\frac{\sum_i w_{y_i}\,\log p_\theta(y_i \mid X_i)}{\sum_i w_{y_i}}
wc=NK Ncw_c = \frac{N}{K\,N_c}
one example: L=−log⁡py\text{one example: } \mathcal{L} = -\log p_y

Your input: the rule says Warm, the model gives it p = 0.194, so the loss is −log(0.194) = 1.641.

ClassTraining count N_cWeight w_c
Cool1431.110
Neutral1381.150
Warm1950.814

N = 476, K = 3. Example: Cool, 476 / (3 × 143) = 1.110.

your examplep = 0p_y = 150−log p_y
loss = F.cross_entropy(logits, y, weight=class_weights) # softmax + weighted −log p
# (64, 3) logits, (64,) labels → scalar
⑪

Ask all 227 numbers which way to move

Training needs, for every one of the 227 numbers in the model, the answer to one question: if I nudged you up a little, would the loss go up or down, and how fast? That is the gradient ∂L/∂θ\partial\mathcal{L}/\partial\theta.

Backpropagation gets all of them in one backward sweep, applying the chain rule from the loss toward the input. It starts with a beautiful simplification: for softmax followed by cross-entropy, the gradient with respect to the logits is just prediction minus truth, p−yp - y. Every step after that is again a matrix product.

This page's backward pass is written by hand. Before publishing it was checked against finite differences: all 227 gradients agree to within 10⁻⁷ relative error.

∂L∂ℓ=p−y\frac{\partial \mathcal{L}}{\partial \ell} = p - y
∂L∂Wc=zt⊤ (p−y)\frac{\partial \mathcal{L}}{\partial W_c} = \htmlClass{tx-row}{z_t^{\top}}\,\htmlClass{tx-col}{(p - y)}
∂L∂zt=(p−y) Wc⊤\frac{\partial \mathcal{L}}{\partial z_t} = (p-y)\,W_c^{\top}

The same two rules for every linear layer Y=XWY = XW:

∂L∂W=X⊤∂L∂Y,∂L∂X=∂L∂Y W⊤\frac{\partial \mathcal{L}}{\partial W} = X^{\top}\frac{\partial \mathcal{L}}{\partial Y},\qquad \frac{\partial \mathcal{L}}{\partial X} = \frac{\partial \mathcal{L}}{\partial Y}\,W^{\top}

plus ReLU (pass the gradient where the input was positive) and softmax:

∂L∂Sij=Aij(∂L∂Aij−∑kAik∂L∂Aik)\frac{\partial \mathcal{L}}{\partial S_{ij}} = A_{ij}\Big(\frac{\partial \mathcal{L}}{\partial A_{ij}} - \sum_k A_{ik}\frac{\partial \mathcal{L}}{\partial A_{ik}}\Big)
pp1 × 3
CoolNeutralWarm0.6220.1840.194
−
yy1 × 3
CoolNeutralWarm001
=
∂L/∂ℓ\partial\mathcal{L}/\partial\ell1 × 3
CoolNeutralWarm0.6220.184−0.806
zt⊤z_t^{\top}4 × 1
·d₁d₂d₃d₄1.30−0.940.64−1.00
·
(p−y)(p - y)1 × 3
CoolNeutralWarm·0.620.18−0.81
=
∂L/∂Wc\partial\mathcal{L}/\partial W_c4 × 3
CoolNeutralWarmd₁d₂d₃d₄
row 1 of zt⊤z_t^{\top} · column 3 of (p−y)(p - y) =1.30×−0.81
=−1.050=−1.050=−1.050

Largest term: 1.30 × −0.81 (·) carries 100% of the total magnitude of the terms. An outer product: a 4×1 column times a 1×3 row gives the full 4×3 gradient of W_c.

∂L/∂WQ\partial\mathcal{L}/\partial W^Q4 × 4
0.002−0.0040.0000.000−0.0010.0030.0000.0000.001−0.0010.0000.000−0.0010.0020.0000.000
Blue entries would raise the loss if increased, so training pushes them down; red entries are pushed up.
loss.backward() # fills p.grad for every parameter p
# 227 gradients, one per parameter, same shapes as the parameters
⑫

Take a step downhill, with a different stride for every number

The gradient says which way is downhill. Adam decides how far to step, separately for each number. It keeps a running average of the gradient, mm (momentum: noisy batches partly cancel), and of the squared gradient, vv (how large this number's gradients usually are). The step is m/vm/\sqrt{v}, so a number with consistently large gradients does not overshoot and a number with tiny gradients still moves.

Both averages start at zero, which would bias the first steps toward zero; dividing by 1−βt1-\beta^t corrects that. One consequence you can see below: on the very first step m^=g\hat m = g and v^=g2\hat v = g^2, so every weight with a nonzero gradient moves by almost exactly the learning rate, η = 0.01, against its gradient, however small that gradient was.

Before the update, the global gradient norm is clipped to 1.0, as in the T3C recipe.

mt=β1mt−1+(1−β1) gtvt=β2vt−1+(1−β2) gt2\begin{aligned} m_t &= \beta_1 m_{t-1} + (1-\beta_1)\,g_t \\ v_t &= \beta_2 v_{t-1} + (1-\beta_2)\,g_t^2 \end{aligned}
m^t=mt1−β1t,v^t=vt1−β2t\hat m_t = \frac{m_t}{1-\beta_1^t},\qquad \hat v_t = \frac{v_t}{1-\beta_2^t}
θt=θt−1−η m^tv^t+ϵ\theta_t = \theta_{t-1} - \eta\,\frac{\hat m_t}{\sqrt{\hat v_t} + \epsilon}

β1=0.9, β2=0.999, ϵ=10−8, η0=0.01\beta_1 = 0.9,\ \beta_2 = 0.999,\ \epsilon = 10^{-8},\ \eta_0 = 0.01
T3C used η0=10−4\eta_0 = 10^{-4}.

One minibatch of 64 examples → gradients → clip → Adam. Shown here for WcW_c (4×3); all 227 numbers are updated the same way.
θ0=Wc\theta_0 = W_c4 × 3
CoolNeutralWarmd₁d₂d₃d₄−0.16−0.24−0.37−0.37−0.09−0.27−0.480.05−0.04−0.120.460.39
No step taken yet. Press “Take one Adam step” to see g, m̂, √v̂ and the update for this matrix.
nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step() # opt = torch.optim.Adam(model.parameters(), lr=1e-2) opt.zero_grad()
⑬

Repeat 440 times, and the prediction becomes good

That is the whole algorithm: forward pass, loss, backward pass, Adam step. Training is just this loop. Each epoch shuffles the 476 training examples into 8 minibatches of up to 64. After every epoch the model is scored on the 120 examples it never trains on, and if that validation loss stops improving for 3 epochs the learning rate is halved. 55 epochs × 8 = 440 Adam steps.

Nothing else is going on. Matrix products, a few softmaxes and LayerNorms forward; their transposes backward; Adam nudges the numbers. Press Train and watch the curves below, the prediction in step ⑨ and every matrix on this page change together.

for 55 epochs, for each batch B:\text{for } 55 \text{ epochs, for each batch } \mathcal{B}:
g=∇θ Lw(θ;B)g←g⋅min⁡ ⁣(1,1/∥g∥)θ←Adam(θ,g)\begin{aligned} g &= \nabla_\theta\, \mathcal{L}_w(\theta; \mathcal{B}) \\ g &\leftarrow g \cdot \min\!\big(1, 1/\lVert g\rVert\big) \\ \theta &\leftarrow \mathrm{Adam}(\theta, g) \end{aligned}
Macro-F1=1K∑c=1K2PcRcPc+Rc\text{Macro-F1} = \frac{1}{K}\sum_{c=1}^{K} \frac{2P_cR_c}{P_c + R_c}
seed 3 · step 0/440
0.000.350.701.051.40088176264352440Adam stepPress Train to start
Train (batch, smoothed)Validation
0%25%50%75%100%01122334455EpochPress Train to start
TrainValidation
Confusion (validation)\text{Confusion (validation)}3 × 3
pred Coolpred Neutralpred Warmtrue Cooltrue Neutraltrue Warm20023160114208
Rows: true class. Columns: predicted class. The diagonal is correct.
23.3%
Validation accuracy
0.168
Macro-F1
0.01
Learning rate now
0 / 55
Epochs done
0.331
F1 · Cool
0.000
F1 · Neutral
0.174
F1 · Warm

What the model has learned

Two views of the same 227 numbers. Press New seed to see them as noise, then Train and watch the colors line up with the rule and the three classes separate.

1820222426283060708090100110air temperature now (°C)average heart rate (bpm)
model says Cool model says Neutral model says Warmthe rule's boundaries◉ your input

Each of the 600 cells is one forward pass of the live model on your input, with its latest temperature and average heart rate moved to that cell (humidity and the warming trend kept). Darker = more confident. The model agrees with the rule on 7% of the map.

PC 1PC 2
● Cool■ Neutral▲ Warm(true labels)

Each mark is one of the 120 validation examples, placed by its last-row vector zₜ (4 numbers, projected to 2 with PCA). Training pulls the classes apart until a single linear layer, W_c, can separate them.

for epoch in range(55): for xb, yb in loader: # batch_size=64, shuffle=True loss = F.cross_entropy(model(xb), yb, weight=w) opt.zero_grad(); loss.backward() nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step() sched.step(val_loss(model)) # ReduceLROnPlateau(factor=0.5, patience=3)
⑭

From this page to T3C and to GPT

Nothing on this page is a simplification of the algorithm, only of the sizes. T3C, the model from my defense, runs exactly these steps with wider matrices and six stacked layers. GPT-2 runs them with three changes: tokens instead of sensor readings, a causal mask, and a vocabulary-sized output.

This pageT3C · M.S. defenseGPT-2 small
Tokens per sequence4 readings12 five-minute stepsup to 1,024 word pieces
Input per token3 signals17 ASHRAE features (6 local, via adapter)1 of 50,257 tokens, by embedding lookup
Width d_model4256768
Heads × d_k2 × 28 × 3212 × 64
Feed-forward4 → 8 → 4, ReLU256 → 512 → 256, ReLU768 → 3,072 → 768, GELU
Layers1612
LayerNormafter each block (post-norm)post-normbefore each block (pre-norm)
Attention masknone (encoder)none (encoder)causal (decoder)
Output3 classes, from the last row3 classes, from the last rownext-token probabilities, at every row
Parameters227≈ 3.17 million≈ 124 million
Trained on476 rule-labelled examples44,124 ASHRAE records, then 596 local≈ 40 GB of web text

1 · A word is a row of a matrix

GPT does not read numbers from sensors; it reads token ids. Each id selects one row of a learned embedding matrix WEW_E. Written as algebra, the lookup is again a matrix product: a one-hot row vector times WEW_E picks out exactly one row. GPT-2's WEW_E is 50,257 × 768.

eword=1word⊤WE∈R1×de_{\text{word}} = \mathbf{1}_{\text{word}}^{\top} W_E \in \mathbb{R}^{1\times d}
1warm⊤\mathbf{1}_{\text{warm}}^{\top}1 × 6
theroomfeelswarmcool.id0.000.000.001.000.000.00
·
WEW_E6 × 4
d₁d₂d₃d₄theroomfeelswarmcool.0.12−0.400.310.050.850.10−0.220.47−0.300.660.18−0.510.92−0.150.740.30−0.88−0.200.690.280.020.05−0.90−0.12
=
ee1 × 4
d₁d₂d₃d₄id
row 1 of 1warm⊤\mathbf{1}_{\text{warm}}^{\top} · column 1 of WEW_E =0.00×0.12+0.00×0.85+0.00×−0.30+1.00×0.92+0.00×−0.88+0.00×0.02
=0.000+0.000+0.000+0.920+0.000+0.000=0.920=0.920

Largest term: 1.00 × 0.92 (warm) carries 100% of the total magnitude of the terms. Every term is zero except the one where the one-hot vector is 1: the product copies that row of W_E. (Toy values.)

2 · A language model may not look ahead

T3C reads the whole hour at once, so every step may attend to every other step. A model that generates text must predict word i + 1 without seeing it, so before the softmax every score above the diagonal is set to −∞-\infty. Its exponential is 0, and each row renormalizes over the past only. Below: head 1 of the live model, with and without the mask.

A=softmax ⁣(QK⊤dk+M)A = \mathrm{softmax}\!\Big(\frac{QK^{\top}}{\sqrt{d_k}} + M\Big)
Mij={0j≤i−∞j>iM_{ij} = \begin{cases}0 & j \le i\\ -\infty & j > i\end{cases}
S1+MS_1 + M4 × 4
t−45t−30t−15tt−45t−30t−15t0.07−∞−∞−∞0.080.33−∞−∞0.080.300.40−∞0.080.270.370.40
→
A1A_14 × 4
t−45t−30t−15tt−45t−30t−15t1.000.000.000.000.440.560.000.000.280.340.380.000.200.250.270.28

3 · The output is a distribution you can sample

GPT's last layer has 50,257 logits instead of 3, one per token, and the next word is sampled from the softmax. Dividing the logits by a temperature τ before the softmax controls how adventurous that sample is: τ < 1 sharpens the distribution toward the top choice, τ > 1 flattens it. Try it on the live model's three logits.

pc(τ)=eℓc/τ∑keℓk/τp_c(\tau) = \frac{e^{\ell_c/\tau}}{\sum_k e^{\ell_k/\tau}}
Cool
62.2%
Neutral
18.4%
Warm
19.4%

Reuse the stack, retrain the edges

In my M.S. work, T3C was first trained on 44,124 ASHRAE survey records with 17 features per step. The field data had only 596 labelled observations and 6 features, including heart rate, which ASHRAE never measured. So the 17 → 256 input projection was replaced by an adapter, 6 → 128 → 256; the positional embedding and encoder layers 1–5 were frozen; and only the adapter, layer 6 and the classifier were trained: about 17.6% of 3.2 million parameters.

Mean over three seeds on local validation data, the Transformer adapter reached 73.33% accuracy (macro-F1 0.667) against 67.78% (0.580) for a BiLSTM adapter, although the two backbones had tied on the ASHRAE hold-out (71.06% and 71.07%).

Every frozen layer in that model is the same matrix algebra as steps ②–⑧ above, with 256-wide matrices. The adapter is two more of the linear layers from step ②. Open the defense deck ↗
⑮

The same model in PyTorch

This is the model and training loop that this page runs, written with PyTorch's built-in Transformer layer. Each line is tagged with the step it corresponds to. The page itself does not use PyTorch: it is a from-scratch TypeScript implementation of the same forward pass, backward pass and Adam update, so that every intermediate matrix can be shown.

import torch, torch.nn as nn, torch.nn.functional as F

class TinyT3C(nn.Module):
    """The model on this page: T3C with T=4, F=3, d=4, 2 heads, 1 layer."""
    def __init__(self, n_feat=3, T=4, d=4, heads=2, d_ff=8, n_cls=3):
        super().__init__()
        self.embed = nn.Linear(n_feat, d)               # ② X W_e + b_e
        self.pos   = nn.Parameter(torch.zeros(T, d))    # ② P, learned
        self.ln0   = nn.LayerNorm(d)                    # ② LayerNorm
        layer = nn.TransformerEncoderLayer(             # ③–⑧
            d, heads, d_ff, dropout=0.0, activation="relu",
            batch_first=True, norm_first=False)         # post-norm, as T3C
        self.encoder = nn.TransformerEncoder(layer, num_layers=1,
                                             enable_nested_tensor=False)
        self.head = nn.Linear(d, n_cls)                 # ⑨ W_c, b_c

    def forward(self, x):                               # x: (B, 4, 3), standardized
        z = self.ln0(self.embed(x) + self.pos)
        z = self.encoder(z)
        return self.head(z[:, -1])                      # last-token pooling → logits

model = TinyT3C()
opt   = torch.optim.Adam(model.parameters(), lr=1e-2)   # ⑫
sched = torch.optim.lr_scheduler.ReduceLROnPlateau(opt, factor=0.5, patience=3)

for epoch in range(55):                                 # ⑬
    model.train()
    for xb, yb in train_loader:                         # batch_size=64, shuffle=True
        loss = F.cross_entropy(model(xb), yb, weight=class_weights)   # ⑩
        opt.zero_grad()
        loss.backward()                                 # ⑪
        nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step()                                      # ⑫
    model.eval()
    with torch.no_grad():                               # all 120 validation examples
        val_loss = F.cross_entropy(model(X_val), y_val, weight=class_weights)
    sched.step(val_loss)
epoch 0/55 · untrained