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.

Loading the weight pictures

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.

Canvas, per token–
JavaScript, per token–
Canvas is slower by–
Same top token / largest logit gap–

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.

  1. 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.

  2. 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.

  3. Canvas
    Multiply.

    The input becomes a 2-pixel-tall strip of colours. It's stretched over the weight picture with the multiply blend mode, so every pixel becomes one weight times one input.

  4. 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.

  5. JS
    Read back.

    One getImageData on 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.

  6. 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 translate inside an element with rotate set to that angle. Where getBoundingClientRect() says it ended up is the rotated pair.

  7. 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.

  8. 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.

  9. 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.

  10. Layout
    Pick by layout.

    Each of the 40 becomes a box in one flex row with flex-grow set to exp(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. Flex order sorts 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, and document.elementFromPoint says 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 rotate and translate
  • 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

Gotchas found on the way