Gradient Decent / audio
Can you listen to a model think?
The browser's audio engine as a calculator. The same tiny Shakespeare model as the
css page, where the weights are a five-second sound file, each matrix multiply is a reverb
(a ConvolverNode) and the activation is a distortion curve (a WaveShaperNode). One
offline render of 1.7 seconds of audio is one character.
Yes. The whole forward pass fits in one audio render per character, with no script touching the numbers between the layers, and the logits come out as the last 37 samples of the sound. It matches a plain JavaScript run of the same weights to about 0.0002 and picks the same top character every time. It takes 10 to 45 ms a character in headless Chrome, a few hundred times slower than a plain loop. You can play back both the weights and any character's render. Whether that counts as listening to it think is up to you. The signals look like noise on the scope, and nobody has heard the playback yet (see the last gotcha).
Run it
The render for the latest character, as a scope
The first three traces are channels of the one buffer the audio engine rendered. The bottom one is the last 37 samples of the output channel, which is the answer. Playback is turned down to 15% after levelling the peaks, because raw model signals are harsh. The weights file is also a plain download: weights.wav (167 KB, mono, 8 kHz, 32-bit float).
Race it in your browser
Runs 40 random 8-character contexts through both engines: the audio graph fed from weights.wav,
and a plain JavaScript loop over the same weights from the CSS page's model.json. It also checks
that the decoded sound file holds exactly the floats in model.json. Same as
window.selfTest().
How one character gets made
Eight steps and one render. JavaScript does three of the steps and none of the arithmetic.
-
JS
Tokenise and copy the embeddings in.
Take the last 8 characters. For each one, copy its 9 samples out of the first 333 samples of the decoded sound file into a 72-sample buffer. A copy, no sums. That buffer is the input: 9 ms of audio.
-
Audio
Layer 1 is a reverb.
A
ConvolverNodewhose impulse response is the 192 × 72 weight matrix: 13,824 samples, one 72-sample slot per neuron, each slot written back to front. Convolving slides the input across it. At the last sample of slot i the input lines up exactly with neuron i's weights, so that one sample is the dot product. The 71 samples around it are half-overlaps: real numbers, but junk. -
Audio
The bias is a second track.
An
AudioBufferSourceNodeplays 192 clicks, one per slot, each as loud as that neuron's bias, timed to land on the useful sample. Connecting two nodes to the same input adds them. -
Audio
ReLU is a distortion curve.
A
WaveShaperNodewith the three-point curve[0, 0, 1]. It maps −1…1 through the curve with straight lines between points, and the middle point sits exactly at zero, so negative samples become silence and positive ones pass. It clamps anything outside −1…1, soGainNodes turn the signal down by 32 first. No neuron in this model can exceed 19.2. -
Audio
A click track picks out the neurons.
A
GainNodewith its gain at 0, and a track that is 1 on every 72nd sample and 0 elsewhere connected to the gain itself. The junk is muted. What's left is 192 spikes, 72 samples apart. -
Audio
Layer 2 is another reverb, laid out to match the spacing.
Its impulse response has the same 72-sample slots. Slot 191 − i starts with neuron i's 37 outgoing weights. Because the spikes are 72 apart and 37 is less than 72, at sample 13,823 + o every spike lines up with its own weight for output o and with nothing else. Layer 2's biases are 37 more samples mixed in at that spot, and a last gain undoes the scaling.
-
JS
Read back.
Start the render, wait, and read samples 13,823 to 13,859 of the result. Those are the 37 logits, already in the right units.
-
JS
Sample.
Softmax with temperature and pick one character. Then go back to step 1 with it on the end.
The graph
input ─▶ Convolver (layer 1) ─▶ Gain ×8 ─┐
bias 1 track ────────────▶ Gain ×0.5 ──┴▶ WaveShaper [0, 0, 1] ─▶ gate
click track ─▶ gate.gain
gate ─▶ Convolver (layer 2) ─▶ Gain ×32 ─┐
bias 2 track ───────────────────────────┴▶ Gain ×16 ─▶ the rendered buffer
const c1 = new ConvolverNode(ctx, { disableNormalization: true, buffer: layer1 })
const relu = new WaveShaperNode(ctx, { curve: new Float32Array([0, 0, 1]), oversample: 'none' })
const gate = new GainNode(ctx, { gain: 0 })
clicks.connect(gate.gain) // an audio signal as the volume knob
The gains are all powers of two, so they cost no precision. The file stores every weight divided by 16 to stay inside −1…1 like any sound file. ×8 and ×0.5 bring layer 1 and its bias to "divided by 32" for the WaveShaper, ×32 and ×16 bring the output back.
JS the bookkeeping
- Decode the sound file once and cut it into five pieces
- Build the 13-node graph for each character (an offline context can only render once)
- Copy 8 embedding rows into the input buffer
- Read 37 samples back
- Softmax, temperature and sampling
- The scope and the playback buttons
Audio all of the maths
- Both matrix multiplies (
ConvolverNode) - Both biases (
AudioBufferSourceNode, summed at a node input) - ReLU (
WaveShaperNode) - Picking 192 samples out of 13,860 (
GainNodewith an audio-rate gain) - Carrying the hidden layer from one multiply to the next
- Every scale factor (
GainNode)
What it says
- One render per character, nothing in between. The catch with a convolver as a matrix multiply is that its answers come out 72 samples apart with junk between them. Muting the junk with a click track, and spacing layer 2's weights the same 72 samples apart, lets layer 1 feed layer 2 directly. The second layer then costs no extra time on the clock: all 37 logits land one after another at the end.
-
A sound file is an exact weight format. A 32-bit float WAV decoded by
decodeAudioDatacomes back bit for bit, all 41,842 samples, as long as the decoding context runs at the file's sample rate. At 4 bytes a weight it's also about five times smaller than the CSS version's 21 bytes. (This file is 167 KB because the layouts for the bias track and layer 2 are mostly silence.) - Precision is float32 with an FFT in the middle. Chrome's convolver works in the frequency domain, so the dot products aren't summed in order. The logits still match a plain loop to about 0.0002 on values as large as 400 (random contexts give some very negative logits), and the plain float32 loop is itself about 0.00006 away from the same sums done in float64. The ReLU and the gains add nothing measurable.
-
It's slow, and the slow part is setup. Between 10 and 45 ms a character in headless Chrome
153, against 50 to 300 µs for a plain loop on the same machine (the race measures yours). The audio engine
does two 13,824-tap convolutions over 13,860 samples to compute what is really 192 dot products of 72
numbers and 37 of 192. And an
OfflineAudioContextcan't be reused, so both convolvers are built again for every character. - The model's time axis is real. At 8 kHz, neuron 0 answers 9 ms in, neuron 191 answers at 1.73 seconds, and the 37 logits take the last 4.6 ms. On the scope, layer 1 looks like steady noise and the answer is a short burst at the very end.
Gotchas found on the way
-
ConvolverNoderescales its impulse response by default so reverbs come out at a sensible loudness.normalizehas to be set to false before the buffer is assigned, or every weight is silently rescaled. -
WaveShaperNodeclamps its input to −1…1. Without turning the signal down first, the largest logit error was about 300 and only 26 of 40 top characters matched. - The curve needs a point exactly at zero, which means an odd number of points. A 1,024-point ReLU curve has its kink between two points and is off by up to 0.07 in the logits. Three points are exact; a 65,537-point curve gave the same numbers and took several times as long. A two-point curve is just a straight line.
-
oversamplehas to stay at'none'. At'4x'the node filters the signal, which smears each sample into its neighbours and puts the answers in the wrong place: errors in the hundreds. - Without the click-track gate the junk between the useful samples leaks into layer 2: 1 of 40 top characters matched. The other way to keep it out also works in one render: give each of the 37 outputs its own 13,896-sample stretch of impulse response, so the junk never lines up with a weight. That was just as accurate (10 of 10) but makes one character 64 seconds of audio and about a second to render, so the gate stayed.
-
decodeAudioDataresamples to the context's rate. Decoded by a 48 kHz context, this 8 kHz file comes back as 251,052 interpolated samples, not 41,842 weights. The page decodes it with an 8 kHzOfflineAudioContext. -
Playing sound needs a click first, and the playback path (a normal
AudioContext) resamples the 8 kHz buffers to the sound card's rate, so what you hear is not sample-exact. The maths never goes through that path. - Only tried in headless Chrome 153, which has no speakers. The playback code runs without errors there, but nobody has heard it yet.