Gradient Decent / stories
Can blend modes write a story?
A 2D canvas, the browser's drawing surface, used as a calculator. It runs tiny-tiny-stories, a one-million-weight story model whose weights are only ever +1, 0 or −1, so each weight is one pixel: red, black or green. Every matrix multiply is colours being blended together. No WebGPU, no WebGL, no WASM, just a goofy way to do the maths with a tool that was built for pictures.
Yes, at 20 to 30 tokens a second, and it gets the maths right: over a 60-token run it picks the same token as a plain numpy version of the model every time. The stories wobble because the model has a million weights, not because of the canvas. A plain JavaScript loop is still much faster; the race below measures by how much on your machine.
Run it
Give it the start of a children's story.
The activation function (SiLU), stored as a gradient. Red is positive, green is negative.
Every layer's weights multiplied by its current input, live.
Rotary positions, turned by CSS rotate. One clock per frequency, at token position
0.
query pairs before, after, key pairs after. Under each clock: tokens per full turn.
The tiles aren't a visualisation added afterwards. Each one is the working canvas for that multiply, copied to the page. The clocks are the same: every coloured dot is the element whose position gets read back as the rotated numbers. They show the last layer's pairs.
Race it in your browser
Feeds the same run of tokens through both engines: the canvas with CSS turning the positions, and a plain JavaScript loop over the same weights read back out of the pictures. They should pick the same next token at every position.
How one token gets made
36 matrix multiplies per token, every one of them on the canvas. The rotation that tells attention where each token sits is done by CSS transforms. JavaScript does the bookkeeping around them.
-
JS
Tokenise.
The text is cut into pieces from a 192-piece vocabulary, choosing the split with the best total score (a SentencePiece unigram tokenizer).
-
JS
Embed and normalise.
Look up the token's row of numbers, then scale it so its average size is 1 (RMSNorm). This is the input vector for the layer.
-
Canvas
Multiply.
The input becomes a 2-pixel-tall strip of colours. It's stretched over the weight picture with the
multiplyblend mode, so every pixel becomes one weight times one input. -
Canvas
Sum.
The product is drawn at half its width, again and again, with smoothing on. Each halving averages neighbouring pixels, so when a row is one pixel wide that pixel is the row's average, which is the sum divided by the width.
-
JS
Read back.
One
getImageDataon a 1-pixel-wide column returns every output of the multiply at once. Red plus green from the top half, minus the same from the bottom half, times a scale. -
CSS
Rotate for position.
Three of those multiplies give a query, a key and a value. The query and key are cut into pairs of numbers, and each pair is turned by an angle that grows with the token's position, at 16 different speeds (rotary position embeddings). Each pair is a zero-size element placed with
translateinside an element withrotateset to that angle. WheregetBoundingClientRect()says it ended up is the rotated pair. -
JS
Attention.
The rotated key and the value are cached. The query is compared with every cached key, the scores go through a softmax, and the values are mixed in those proportions. This is how it remembers earlier tokens.
-
Canvas
The gradient.
The feed-forward part needs SiLU, a smooth curve. It's stored as a canvas linear gradient with 1,025 colour stops, rendered once. Applying it is reading the colour at the right position, like an eyedropper.
-
JS
Repeat, then sample.
5 layers of seven multiplies each, then one more against the vocabulary picture to score every possible next token. Pick one, show it, and go back to step 1.
What one multiply looks like
strip.putImageData(input, 0, 0) // the vector, as a 2-pixel-tall strip work.globalCompositeOperation = 'copy' work.drawImage(weights, 0, 0) // the matrix, as a picture work.globalCompositeOperation = 'multiply' work.drawImage(strip, 0, 0, w, 2, 0, 0, w, h) // every weight times its input, in one draw for (half of halvings) half.drawImage(prev, 0, 0, pw, h, 0, 0, pw / 2, h) // sum by squashing answer = last.getImageData(0, 0, 1, h) // one pixel per output
That's the real sequence from lib/blend.js, trimmed. Negative numbers can't be colours, so positives go in the red channel and negatives in green, and
the strip is drawn twice (once swapped) so all four sign combinations get multiplied.
JS the bookkeeping
- The tokenizer
- Norms
- Attention scores and softmax over the cache
- Adding results back into the running vector
- Sampling
Canvas every matrix multiply
- Query, key, value and attention output
- Gate, up and down in the feed-forward part
- The output head over the whole vocabulary
- The SiLU curve, as a gradient
- The live tiles on this page are those products
CSS the rotary positions
-
Turning every query and key pair by its position angle, with
rotateandtranslate - The dots on the clocks are those pairs
The weights themselves
One pixel is one weight: red is +1, green is −1, black is 0. The head is full precision, so its picture has shades. Every picture in a row is drawn at the same scale. Click one to see it up close.
What it says
- Ternary weights are the easy case. A weight is exactly red, green or black, so the pictures are ordinary 8-bit PNGs with no rounding at all, and the whole model is 743 KB.
- Blend modes are exact enough. In a float16 canvas the logits come out within 0.022 of the reference on values up to 14.5.
- The gradient is a good enough lookup table. Reading SiLU off a 4,096-pixel gradient is accurate to about 0.004.
-
CSS transforms can do the rotary positions. Against
Math.cosandMath.sinon 64,000 random pairs, the worst answer was off by 0.0007% of the longest pair on its clock with the page scrolled to the top, and 0.003% scrolled to the bottom. It changes none of the top tokens. The logits still move by up to 0.04, but a nudge of one part in ten million moves them just as far, because every canvas multiply rounds to float16. -
The rotation costs about 7 ms a token, or 18% more work on the main thread: five rounds of
about 145 style writes, one layout and 145 position reads, plus painting the dots.
window.rotaryTest()andwindow.rotaryCost()measure both here. - It isn't fast. A plain JavaScript loop over the same weights is about 17 times faster per token in headless Chrome on a CPU. The race above gives the number for your machine. The canvas is here because you can watch it.
Gotchas found on the way
-
Squashing a picture to one pixel in a single
drawImagegives garbage, because the browser only samples a few pixels. Halving step by step is what makes it a sum. - An ordinary 8-bit canvas is about 5% off on one multiply. It needs
colorType: 'float16'. - Positions read back from the page are 32-bit floats measured from the corner of the window. The clocks are about 20 pixels across and sit a thousand or more pixels from that corner, so a few digits of every answer are spent on where the clock is. With a clock in the corner itself the rotation is good to the last digit of a float (about 1 part in 10 million).
-
Placing the points with
leftandtopwould snap them to 1/64 of a pixel.translatekeeps the whole float, and scaling each clock by a power of two means nothing is lost turning numbers into pixels. - Widths have to be powers of two for the halving, so the 336-wide matrices are padded to 512 with black.
- Tested in Chrome only.