How a Tiny Transformer Solves a Riddle

Machine Learning
LLM
Three knocks, two clues, and one password. Try the riddle with a single layer, an MLP, and a tiny transformer.
Author

Josh Pearlson

Published

Nov 28, 2026

The Fox knocks twice. The Raven knocks three times. The Fox’s password is ember. The Raven’s is frost.

Someone knocks three times. The password is ___.

The knock count tells you who’s at the door. That tells you which password to use. Can a tiny language model put those clues together?

Change Someone knocks from three times to twice and watch the prediction. Under What the model reads, each numbered line is one token, a unit of text the model reads. The list runs in input order, from the first clue to the knock at the door.

What’s the password?

Enable JavaScript to use the demo.

From the riddle to numbers

All three models answer the same question. Given the lines so far, what token comes next? I gave them four possible answers: ember, frost, moss, and a period. The period lets the model finish the answer after it produces a password.

For the first two models, I turn each numbered position into a row of switches. There’s a switch for every token that could appear there. If line 2 says “Raven knocks three times,” that switch is on at position 2 and every other switch there is off. In numbers, on is 1 and off is 0. This is called one-hot encoding. It lets the model distinguish the same clue in two different positions.

One layer adds scores

The first model has one layer of learned numbers, the basic structure of a single-layer perceptron, or SLP. It gives each possible next token its own score. For moss, it starts with a learned constant called a bias. Then each input switch contributes its learned weight if it’s on, or zero if it’s off.

Here’s the moss score from the actual demo with the starting passwords and three knocks. The five active switches contribute one number each.

Source of the score Contribution to moss
Bias −0.01321
1. Fox knocks twice +0.07511
2. Raven knocks three times +0.00736
3. Fox’s password is ember +0.04376
4. Raven’s password is frost +0.22418
5. Someone knocks three times +0.05210
Sum 0.38930

Line 4 literally says frost, yet it adds the most to the moss score. The model learned a separate set of weights and a bias for each possible answer.

Input switches
Single learned layer
Weighted sums + biases
4 scores
Softmax
4 probabilities

Turn scores into probabilities

A score can be any number, including a negative one. To get probabilities, we need nonnegative numbers that add up to 1. Softmax does this in two steps. It raises the constant ee (about 2.718) to the power of each score. Those results are all positive. Then it divides each result by the sum of all four.

The other answers get their own scores from the same five lines. The exponentials of the four scores add up to about 3.9165.

Token Score escoree^{\text{score}} Probability
ember −0.07104 0.9314 23.8%
frost −0.07577 0.9270 23.7%
moss 0.38930 1.4759 37.7%
Period −0.54106 0.5821 14.9%

Softmax gives moss about 1.4759/3.9165≈37.7%1.4759/3.9165\approx 37.7\%. It’s the highest bar in the single-layer demo for exactly this prompt. The percentages add up to 100% before rounding.

Where one layer gets stuck

With the starting passwords, changing three knocks to two should push the prediction from frost toward ember. Give the Fox frost and the Raven ember, and that same change should push it the other way. For the single layer, only the last line’s row of switches changes. The switch for three knocks turns off and the one for two knocks turns on. The resulting score adjustment is the same whichever passwords appeared earlier.

Try the single layer with the starting riddle. It picks moss for three knocks. Change the count to two and it still picks moss, even though neither visitor has that password.

How the weights learn

Give the model an answer to check

A training example consists of some input lines and one correct next token, called the target. Under the opening knock rules, if the Fox’s password is moss and someone knocks twice, the target is moss. I also make a second example by adding moss to the end of those lines. Now the target is the period (to end the example).

I start with mostly random weights. The model uses them to score the answers and softmax turns those scores into probabilities. To see how well it did, I take the probability it assigned to the correct answer, pp, and calculate:

loss=−ln(p) \text{loss}=-\ln(p)

The natural logarithm, ln\ln, answers the reverse of the exponential we used in softmax. It asks what power of ee gives pp. For one correct answer per example, this formula is the cross-entropy loss. Lower is better. At 25% for the right answer, the loss is about 1.39. At 75%, it falls to about 0.29. Training uses the average loss over the examples it sees.

Take one step downhill

Imagine a simpler version with just ember and frost. The score for ember stays at 0. The score for frost is the one number we can change, ww. Suppose frost is correct. Starting at w=0w=0, the scores tie, so frost gets 50% and the loss is −ln(0.5)≈0.69-\ln(0.5)\approx 0.69.

How should we move ww? Try nudging it from 0 to 0.1. The loss goes from about 0.693 to 0.644, a drop of 0.049 over 0.1 units. That’s a slope of about −0.49-0.49 over that interval. The exact slope at 0 is −0.5-0.5. The gradient is the collection of these slopes, one for each adjustable number in the model.

Gradient descent subtracts the slope multiplied by a learning rate, which sets the size of the update. A negative slope means the loss falls to the right, so subtracting it increases the weight. With a learning rate of 2 in this example:

new weight=0−2(−0.5)=1 \text{new weight}=0-2(-0.5)=1

At w=1w=1, softmax gives frost e1/(1+e1)≈73%e^1/(1+e^1)\approx 73\%, so the loss falls to about 0.31.

One gradient descent step Loss falls as the frost score increases. A step from weight zero to weight one drops the loss from 0.69 to 0.31. Loss 2 1 0 −2 0 1 4 Weight w Weight 0 Loss 0.69 Weight 1 Loss 0.31
One weight changes. The curve shows the loss we’d get at each possible value.

A smaller learning rate would take a shorter step. On a curve with a low point, a step that’s too large can jump past it. In a network with many weights, we calculate the slopes by working backward from the loss through the model’s layers. This calculation is called backpropagation. We update the weights, run the model again, and repeat.

A hidden layer combines clues

A multilayer perceptron, or MLP, inserts a hidden layer between the input switches and the output scores. Each unit in the hidden layer first makes a weighted sum and adds a bias, just like a unit in the single-layer model. Then it passes the result through an activation function, a rule that changes the sum before handing it to the next layer.

Input switches
Hidden layer
Weighted sums + biases
ReLU
64 hidden values
Output layer
Weighted sums + biases
4 scores
Softmax
4 probabilities

What ReLU does

I used ReLU, short for rectified linear unit. It returns zero for an input below zero and passes positive inputs through. Written as a formula, ReLU(x)=max(0,x)\operatorname{ReLU}(x)=\max(0,x), the bigger of 0 and xx.

The change at zero matters. A stack of weighted sums and biases alone can be combined into one weighted sum and bias. ReLU gives a hidden unit a way to respond to a combination of clues.

For example, imagine a unit that adds 1 for each of these clues in its expected position:

  • The Raven knocks three times.
  • The Raven’s password is frost.
  • Someone knocks three times.

Give that unit a bias of −2-2. With all three clues present, the sum is 3−2=13-2=1, and ReLU passes 1 through. With only two clues, the sum is 2−2=02-2=0. With fewer clues, it’s negative. In both cases the unit outputs zero. The next layer can use that unit’s output as evidence for frost.

The ReLU activation function ReLU outputs zero below zero and passes positive inputs through. Two matching clues give input zero and output zero. Three matching clues give input one and output one. Output 2 1 −2 0 1 2 Input to ReLU 2 clues (0 → 0) 3 clues (1 → 1)
The inputs at both marked points include the bias of −2.

Those weights illustrate a possible unit. In the demo, the model learns weights for 64 hidden units, and its output layer uses their values to score the four answers.

Try the MLP. It starts with ember for the Fox and moss for the Raven, a pair it saw in training. It gets moss right after three knocks. Change the Raven’s password to frost. That pair was held out, and the MLP still guesses moss.

Try a confident mistake. Two knocks mean the Fox is at the door, so the answer is moss. The MLP puts 91.0% on frost, a password neither visitor has. The percentage is the model’s confidence in its guess.

Two attention blocks follow the clues

The MLP uses a fixed position for each of its input switches. The transformer gives each possible token an embedding, a list of 16 learned numbers. The model can adjust those numbers during training, just like its other weights.

Attention lets one position pull information from other positions. An attention head scores how well the positions match and blends what they have to share. In the first block, the head turns each embedding into three vectors, or lists of numbers, using a separate set of learned weights for each:

  • A query describes what the current position is looking for.
  • A key describes what each candidate position can match.
  • A value carries the information a position can pass along if it gets attention.
Every line produces a query, a key, and a value. Here I’m following line 5’s query and the keys and values of the two knock clues.

Work through one attention calculation

Suppose line 5 has the query [2,1][2,1], and we compare only the Raven’s and Fox’s knock clues. I’m using two numbers per vector to keep the arithmetic short. The demo uses 16 and compares all the lines in view.

  1. Compare the query with each key. Multiply corresponding numbers and add the products. If the Raven’s key is [1,0][1,0], its match score is 2×1+1×0=22\times1+1\times0=2. If the Fox’s key is [0,1][0,1], its score is 2×0+1×1=12\times0+1\times1=1.
  2. Scale the scores and apply softmax. Divide by the square root of the number of coordinates, 2\sqrt{2} here. That keeps typical score sizes comparable as the vectors get wider. The scaled scores are about 1.41 and 0.71. Their exponentials are about 4.11 and 2.03. Dividing by their sum gives the Raven about 0.67 of the attention and the Fox about 0.33.
  3. Blend the values. Suppose the Raven’s value is [3,0][3,0] and the Fox’s is [0,3][0,3]. Give each vector its share of the blend. The first coordinate is 0.67×3+0.33×0=2.010.67\times3+0.33\times0=2.01. The second is 0.67×0+0.33×3=0.990.67\times0+0.33\times3=0.99. The attention output is approximately [2.01,0.99][2.01,0.99].

The block adds the blend to line 5’s existing vector, then centers and rescales the coordinates and applies a learned scale and bias before the MLP. The demo does the same calculation with learned vectors and divides the match scores by 16=4\sqrt{16}=4. Vaswani et al., Attention Is All You Need, §§3.1–3.2

The block does this at every position, with a simple rule: a position can see its own line and earlier lines. That rule is causal attention. Next, an MLP transforms each position’s updated vector separately. The second block repeats both operations using the vectors from the first block. The model uses the final position’s vector to score the four next tokens and then applies softmax. Vaswani et al., Attention Is All You Need, §§3.2–3.4

Token vectors
Transformer block × 2
Causal attention
MLP
Next-token probabilities

Try the transformer with the starting passwords and three knocks.

For each training riddle, I marked the visitor’s knock rule for block 1 and their password clue for block 2. The usual loss rewards predicting the right next token. I added a penalty when those marked lines received little attention. In the browser, the model computes attention from the current riddle using its saved weights.

  1. Block 1 Line 5Someone knocks three times Line 2Raven knocks three times
  2. Block 2 Line 5Updated by block 1 Line 4Raven’s password is frost
Each arrow points to the clue with the largest weight in that block’s blend. The answer bars reflect the full computation, including the values being blended and the layers that follow. To see how much a clue changes the answer, you could change that clue and run the model again.

The green underlines mark key words in the last line and the highest-weight clue in each block. Switch to two knocks to see the clue underlines move to the Fox.

Generate one token at a time

Open the transformer panel and click Generate one token. Each click chooses the most probable of the four possible tokens, including the period. With these clues, frost has the highest probability, so the model adds it as line 6. It reads the six lines together to predict the next token. The second click produces a period. This demo stops at a period or after two tokens. A longer text generator can keep predicting and appending tokens until it reaches its own stopping point.

How I trained and tested the demo

In the widget, the Fox always knocks twice and the Raven always knocks three times. The dataset includes that assignment and its reverse, so the model has to use the knock-rule clues to know who’s at the door. With nine password pairs and two possible knock counts at the door, those two assignments make 36 starting riddles.

I kept three complete password pairs out of training under both assignments and both knock counts. One is the starting pair of ember for the Fox and frost for the Raven. That left 24 training riddles and 12 held-out riddles. Each visitor still used each individual password somewhere in training.

Each training riddle contributes two examples, one for the password and one for the period. At each update I used all 48 examples. The code makes 600 updates per model using AdamW, an update rule that adapts the size of each weight’s step using its recent gradients. The base learning rate is 0.015. The models train offline, and the demo uses their saved weights to make predictions in your browser. Loshchilov and Hutter, Decoupled Weight Decay Regularization

The transformer has one attention head per block. I add the clue penalty to the next-token loss with a weight of 0.25. The penalty applies to the training examples where the next token is a password. In one run with the same split and starting weights and that penalty turned off, the transformer solved 8 of 12 held-out riddles.

I counted how often the top predicted password was correct. The held-out column measures how well these trained models combine familiar clues in new password pairings under the same riddle rules.

Model Training riddles Held-out riddles
Single layer 18 / 24 0 / 12
MLP 24 / 24 5 / 12
Transformer with clue feedback 24 / 24 12 / 12

What happens during training

I reran the demo’s training with the same seed and settings. At each step, the top chart averages next-token cross-entropy over 48 predictions (one password and one ending period for each of the 24 training riddles). I leave the transformer’s extra attention penalty out of the plotted loss so the curves measure the same thing.

The bottom chart checks the password on the four held-out riddles that use the starting password pair. I use those four riddles to track progress during training and call them the validation set. All 12 held-out riddles stay out of the weight updates. I fixed the settings and the 600-update stopping point before logging these results. The table above counts all 12 held-out riddles.

Training cross-entropy falls for all three models. At the end of 600 updates, validation accuracy is zero out of four for the single layer, two for the MLP, and four for the transformer.

The top panel tracks loss on the 24 training riddles, including both password and period predictions. The bottom panel counts correct passwords on four validation riddles at each 20-update checkpoint.

Cross-entropy can keep falling after the correct answer ranks first. That can push the displayed probability close to 100%. The MLP’s training loss ends near zero, yet it gets just two of the four validation passwords right at the end of the run. The transformer gets all four right at the first checkpoint after training starts, 20 updates in.

How much does the split matter?

The 12-of-12 result above comes from one set of held-out password pairs and one starting seed. I repeated the transformer experiment for three splits that rotate which complete pairs are held out. Each split still has 24 training riddles and 12 held-out riddles. One reserves the pairs where both visitors have the same password. The other two each reserve a different set of mismatched pairs, including the demo’s split.

Within each split, I trained from five starting seeds with the clue feedback turned on and again with it turned off. Each pair of runs starts from the same weights and trains for the same 600 updates. The dots show the number of correct held-out passwords in each run.

Held-out transformer results by password-pair split. In every row all five green circles with feedback are at 12 correct. Blue diamonds with feedback off span 11 to 12 for the same-password split and 8 to 12 across the two other splits.

Each dot is one run. Repeated scores are stacked within a row so all five starting seeds are visible for each feedback setting.

With clue feedback, the transformer got all 12 right in all 15 runs. With feedback turned off, it got between 8 and 12 right. In the same-password split, either visitor gives the same answer, so a correct password leaves open whether the model identified the visitor.

On the two splits with different passwords for the visitors, all 10 runs with feedback got 12 right. The 10 runs with feedback off ranged from 8 to 12. This checks how consistently the model handles new password pairings with the same clue vocabulary, line order, and riddle template.

Training code · Browser inference · Experiment code · Recorded results

To reproduce the plots and recorded results, save train.py and experiments.py together. Run this command in their directory.

uv run --python 3.13 --with torch==2.15.0 --with numpy \
  --with matplotlib==3.10.8 python experiments.py