Learn · Module 01
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.
The question
Predict how a person feels from 45 minutes of sensors
In words
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.
In math
The teaching rule (hidden from the model):
In numbers · live
| Air temp (°C) | Humidity (%) | Heart rate (bpm) | |
|---|---|---|---|
| t−45 | |||
| t−30 | |||
| t−15 | |||
| t |
The rule says
Warm
s = 3.54
Edit any reading or pick a preset. Every matrix below is recomputed from this table, instantly.
Standardize
Put every signal on the same scale
In words
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.
In math
= (24.04, 50.70, 79.27) · = (2.88, 11.91, 12.57)
In numbers · live
Air temp at t: (27.8 − 24.04) ÷ 2.88 = 1.31hover or tap any cell of X
In code
x = (x_raw - mu) / sigmaLinear projection · position · LayerNorm
Turn each reading into a vector the model can work with
In words
A linear layer turns each 3-number row into a 4-number row, the model's working width . That is one matrix multiplication. Every output number is a dot product between one row of (one time step) and one column of (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 . 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.
In math
In numbers · live
Entry row 4, column 1 — hover or tap any cell of the result
Largest term: 1.31 × 0.25 (temp) carries 61% of the total magnitude of the terms.
Row t — tap a row to switch
| row | 0.59 | −0.71 | 0.14 | −0.52 | μ = −0.128, σ = 0.518 |
| (x − μ)/σ | 1.38 | −1.12 | 0.51 | −0.77 | mean 0, variance 1 |
| × + | 1.38 | −1.12 | 0.51 | −0.77 | = (1.00, 1.00, 1.00, 1.00), = (0.00, 0.00, 0.00, 0.00) |
In code
z = ln0(embed(x) + pos) # embed = nn.Linear(3, 4)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.
In T3C (the full model)
Pretraining: 12 steps × 17 ASHRAE features projected to 256, so . For the 6 local features the adapter replaces it: two linear layers, 6 → 128 → 256, trained on local data.
Queries · keys · values
Every step asks a question and offers an answer
In words
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 . 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 ⑥.
In math
In numbers · live
Entry row 4, column 1 — hover or tap any cell of the result
Largest term: 1.38 × −0.22 (d₁) carries 46% of the total magnitude of the terms.
and come from the same by the same recipe, with their own weights.
In code
q, k, v = (z @ W_qkv + b_qkv).chunk(3, dim=-1)
q = q.view(T, heads, d_k) # split columns into headsIn T3C (the full model)
8 heads × 32 dims = 256 columns. Each head has its own query, key and value matrices.
Scaled dot products
How much should each step listen to every other step?
In words
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, : 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 . Without it, the softmax in the next step would saturate and its gradients would vanish.
This is the step that makes Transformers expensive: scores per head. 16 here, 144 in T3C, about a million per head per layer in a 1,024-token GPT-2 context.
In math
In numbers · live
Entry row 4, column 1 — hover or tap any cell of the result
Largest term: −0.45 × −0.22 (c₂) carries 88% of the total magnitude of the terms.
In code
scores = q @ k.transpose(-2, -1) / math.sqrt(d_k)Softmax, row by row
Turn scores into attention weights that sum to one
In words
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 from overflowing. The same fact explains why the key bias never learns: it adds the same constant to every score in a row, so its gradient is exactly zero (check it in step ⑪).
In math
In numbers · live
Row t worked out — tap a row to switch
| j | t−45 | t−30 | t−15 | t | |
|---|---|---|---|---|---|
| score s | 0.08 | 0.27 | 0.37 | 0.40 | max m = 0.40 |
| s − m | −0.32 | −0.13 | −0.03 | 0.00 | |
| e^(s − m) | 0.725 | 0.879 | 0.967 | 1.000 | Σ = 3.570 |
| ÷ Σ | 0.203 | 0.246 | 0.271 | 0.280 | sums to 1.000 |
In code
weights = scores.softmax(dim=-1)Weighted sum · concatenate · project
Each step becomes a weighted average of what it attended to
In words
The attention weights are a recipe. Row t of is the weighted average of all four value rows, using row t of 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, , mixes them back into the model's width.
In math
In numbers · live
Entry row 4, column 1 — hover or tap any cell of the result
Largest term: 0.28 × −0.42 (t) carries 32% of the total magnitude of the terms.
Entry row 4, column 1 — hover or tap any cell of the result
Largest term: 0.41 × 0.45 (H₂c₂) carries 49% of the total magnitude of the terms.
In code
out = (weights @ v).transpose(0, 1).reshape(T, d_model)
out = out @ W_o + b_oIn T3C (the full model)
8 heads of 12×32 are concatenated to 12×256, then . The whole attention block has 263,168 parameters per layer.
Residual connection · LayerNorm
Add the input back, then normalize
In words
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 . That sum is also a highway for gradients: during training, the derivative of always contains the identity, so the signal reaches the early layers even when 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.
In math
In numbers · live
Row t — tap a row to switch
| row | 1.76 | −1.20 | 0.52 | −0.65 | μ = 0.107, σ = 1.139 |
| (x − μ)/σ | 1.45 | −1.15 | 0.36 | −0.66 | mean 0, variance 1 |
| × + | 1.45 | −1.15 | 0.36 | −0.66 | = (1.00, 1.00, 1.00, 1.00), = (0.00, 0.00, 0.00, 0.00) |
In code
z = norm1(z + self_attn(z))Feed-forward network · ReLU · Add & Norm
Think about each step on its own
In words
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, , 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.
In math
In numbers · live
Entry row 4, column 1 — hover or tap any cell of the result
Largest term: 1.45 × −0.44 (d₁) carries 44% of the total magnitude of the terms.
Entry row 4, column 1 — hover or tap any cell of the result
Largest term: 0.51 × −0.28 (h₈) carries 44% of the total magnitude of the terms.
In code
z = norm2(z + linear2(relu(linear1(z))))In T3C (the full model)
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.
Last-token pooling · linear · softmax
Read the last row and decide
In words
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.
In math
In numbers · live
Entry row 1, column 3 — hover or tap any cell of the result
Largest term: 1.30 × −0.37 (d₁) carries 42% of the total magnitude of the terms.
softmax(ℓ)
| ℓ | 0.35 | −0.87 | −0.82 |
| e^(ℓ − max) | 1.000 | 0.297 | 0.312 |
| ÷ 1.608 | 0.622 | 0.184 | 0.194 |
Model: Cool
✗ rule says Warm
In code
logits = head(z[:, -1]) # head = nn.Linear(4, 3)
probs = logits.softmax(-1)Class-weighted cross-entropy
Score how wrong the prediction is
In words
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 , 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.
In math
In numbers · live
Your input: the rule says Warm, the model gives it p = 0.194, so the loss is −log(0.194) = 1.641.
| Class | Training count N_c | Weight w_c |
|---|---|---|
| Cool | 143 | 1.110 |
| Neutral | 138 | 1.150 |
| Warm | 195 | 0.814 |
N = 476, K = 3. Example: Cool, 476 / (3 × 143) = 1.110.
In code
loss = F.cross_entropy(logits, y, weight=class_weights) # softmax + weighted −log pThe chain rule, as matrix products
Ask all 227 numbers which way to move
In words
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 .
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, . 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.
In math
The same two rules for every linear layer :
plus ReLU (pass the gradient where the input was positive) and softmax:
In numbers · live
Entry row 1, column 3 — hover or tap any cell of the result
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.
Gradient size for every parameter — for this one example. Tap to inspect.
In code
loss.backward() # fills p.grad for every parameter pAdam optimizer
Take a step downhill, with a different stride for every number
In words
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, (momentum: noisy batches partly cancel), and of the squared gradient, (how large this number's gradients usually are). The step is , 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 corrects that. One consequence you can see below: on the very first step and , 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.
In math
T3C used .
In numbers · live
In code
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step() # opt = torch.optim.Adam(model.parameters(), lr=1e-2)
opt.zero_grad()The loop
Repeat 440 times, and the prediction becomes good
In words
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.
In math
In numbers · live
Loss
Accuracy
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.
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.
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.
In code
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)Same math, bigger matrices
From this page to T3C and to GPT
In words
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 page | T3C · M.S. defense | GPT-2 small | |
|---|---|---|---|
| Tokens per sequence | 4 readings | 12 five-minute steps | up to 1,024 word pieces |
| Input per token | 3 signals | 17 ASHRAE features (6 local, via adapter) | 1 of 50,257 tokens, by embedding lookup |
| Width d_model | 4 | 256 | 768 |
| Heads × d_k | 2 × 2 | 8 × 32 | 12 × 64 |
| Feed-forward | 4 → 8 → 4, ReLU | 256 → 512 → 256, ReLU | 768 → 3,072 → 768, GELU |
| Layers | 1 | 6 | 12 |
| LayerNorm | after each block (post-norm) | post-norm | before each block (pre-norm) |
| Attention mask | none (encoder) | none (encoder) | causal (decoder) |
| Output | 3 classes, from the last row | 3 classes, from the last row | next-token probabilities, at every row |
| Parameters | 227 | ≈ 3.17 million | ≈ 124 million |
| Trained on | 476 rule-labelled examples | 44,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 . Written as algebra, the lookup is again a matrix product: a one-hot row vector times picks out exactly one row. GPT-2's is 50,257 × 768.
Entry row 1, column 1 — hover or tap any cell of the result
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 . Its exponential is 0, and each row renormalizes over the past only. Below: head 1 of the live model, with and without the mask.
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.
From the defense · transfer learning
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%).
Everything above, in PyTorch
The same model in PyTorch
In words
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)References
- Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., & Polosukhin, I. (2017). Attention is all you need. NeurIPS 30. ↗
- Ba, J. L., Kiros, J. R., & Hinton, G. E. (2016). Layer normalization. arXiv:1607.06450. ↗
- He, K., Zhang, X., Ren, S., & Sun, J. (2016). Deep residual learning for image recognition. CVPR. ↗
- Kingma, D. P., & Ba, J. (2015). Adam: A method for stochastic optimization. ICLR. ↗
- Glorot, X., & Bengio, Y. (2010). Understanding the difficulty of training deep feedforward neural networks. AISTATS. ↗
- Houlsby, N., et al. (2019). Parameter-efficient transfer learning for NLP. ICML. ↗
- Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., & Sutskever, I. (2019). Language models are unsupervised multitask learners. OpenAI. ↗
- Chahardoli, S. (2026). Transfer learning with a Transformer adapter for personalized thermal comfort prediction using wearable heart rate and environmental sensors. M.S. defense, Computer Science, Louisiana State University. ↗
See also
- Transformer Explainer, Polo Club of Data Science, Georgia Tech ↗GPT-2 running live in the browser, with a strong visual flow.
- LLM Visualization, Brendan Bycroft ↗A 3D walk through nano-GPT; the style of the model on my home page.
This page adds what those leave implicit: the numbers inside every matrix product, the softmax arithmetic, the gradients and the optimizer update.