Gradient Decent / chat
Can a 2D canvas hold a conversation?
A 2D canvas, the browser's drawing surface, used as a calculator to hold a conversation. It runs TinyChat-1776K, a 1.8-million-weight chat model. The weights are pictures, every multiply is a blend mode, every sum is an image being squashed, the activation function is a gradient, and page layout picks each next token. No WebGPU, no WebGL, no WASM, just a goofy way to do the maths with tools that were built for pictures.
Yes, and it gets the maths right: on a 136-token test conversation it picks the same next token as the original model in Hugging Face transformers at every position. The odd answers are the model's fault, not the canvas's. It was trained on conversations at a three-year-old's level and knows nothing about the world. A plain JavaScript loop is still much faster; the race below measures by how much on your machine.
Run it
Ask it about cats, cake or its favourite colour. Don't ask it for facts. It keeps the whole conversation in mind for about 250 tokens.
The next token, picked by page layout. Each box is as wide as that token is likely, and the needle lands on the one that gets said.
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
22 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, and the page's layout engine picks the token. JavaScript does the bookkeeping around them.
-
JS
Tokenise.
Your message is wrapped as
<A>your text <end>followed by<B>, the model's turn, and cut into pieces with byte-pair encoding from a 2,048-piece vocabulary. -
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 6 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.
3 layers of seven multiplies each, then one more against the vocabulary picture to score every possible next token. The 40 highest scores go on to the next step.
-
Layout
Pick by layout.
Each of the 40 becomes a box in one flex row with
flex-growset toexp(score − best score). Flexbox shares the row out in those proportions, so each box's width is its probability: a softmax with no division in the script. Flexordersorts them, biggest first. The box under the dashed line at 80% is the last one kept (top-p 0.8). A needle goes to a random spot across the kept boxes, anddocument.elementFromPointsays which box it's on. That token is shown, and it's back to step 2.
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
- Choosing the 40 candidates and rolling the needle's random number
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
All 22 of them. One pixel is one weight: red is positive, green is negative, brighter is bigger. Every picture in a row is drawn at the same scale. Click one to see it up close.
What it says
- Blend modes are exact enough. In a float16 canvas a multiply lands within about 0.2% of the true answer, and the logits end up within 0.17 of the real model's on values around 20. In an ordinary 8-bit canvas the same multiply is about 5% off, which is too much.
- Full-precision weights fit in 8-bit pictures. Each pixel holds 8 bits of size, the channel holds the sign, and every row has its own scale. Against the original weights that moves the logits by about 0.06 and changes none of the top tokens.
-
Layout can do the sampling. Flexbox does the softmax, flex
orderdoes the sort and a hit test does the pick. Given the same random number, it chose the same token as the plain JavaScript sampler in 1,600 of 1,600 tries (400 needle positions on each of four sets of scores), and in 19,995 of 20,000 with finer steps. The five misses were each one box along, with the needle within 1/64 of a pixel of the edge between them, which is as fine as layout measures.samplingTest()in the console reruns it. -
The pick costs about 4 ms a token against about 1 ms for the JavaScript sampler it
replaced, on a token that takes about 70 ms. The 40 boxes are reused, not rebuilt. Box widths, read back
through a
ResizeObserver, are within 0.00007 of the true probabilities on a 497-pixel row. -
CSS transforms can do the rotary positions. Against
Math.cosandMath.sinon 60,000 random pairs, the worst answer was off by 0.0006% of the longest pair on its clock with the page scrolled to the top, and 0.0025% scrolled to the bottom. It changes none of the top tokens. The logits still move by up to 0.08, 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 5 ms a token, or 7% more work on the main thread: three rounds of
about 125 style writes, one layout and 125 position reads, plus painting the dots.
window.rotaryTest()andwindow.rotaryCost()measure both here. - It runs at about 14 tokens a second in headless Chrome on a CPU with no GPU, with the tiles and clocks drawing. With the rotation in plain JavaScript it was about 15.
- It isn't fast. A plain JavaScript loop over the same weights is about 19 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. - 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. - Colours can't be negative, so every number is split into a positive and a negative channel and the multiply is done for all four sign combinations.
- This model's vocabulary has glued-together pieces (a full stop, an end marker and the next speaker's tag as one token) that its own tokenizer never produces. They're blocked at sampling.
-
elementFromPointworks in whole pixels and returns the last box touching that pixel, so on a row of 40 boxes it named the wrong one about 4% of the time. The fix is to slide the row a fraction of a pixel just for the hit test, so the needle's exact position lines up with the pixel's edge, then slide it back before anything is painted. - A hit test only sees what's on screen. If the row is scrolled out of view or under a dialog, the pick falls back to comparing the needle with the box edges layout produced.
- Tested in Chrome only. It needs a float16 2D canvas.