Skip to content
libdensePublic

About

A small language model entirely contained within a URL. WebAssembly SIMD engine.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

dense-lm

A language model in a link. It fits on the URL bar in your browser.

dist/shakespeare.url is a single data: URL, 252,312 characters long. Paste it into a browser's address bar and it becomes a page that writes text and continues whatever you type. There is no server, no download and no library: the URL holds the page, a WebAssembly inference engine, and the weights of a 448,608-parameter model.

Train it on your own text and you get your own link. Check out data/spongebob/build/spongebob-patty.url as an example

dense-lm running in Chrome

Open a link

  1. Copy the whole contents of dist/shakespeare.url. On Linux with X11:

    xclip -selection clipboard < dist/shakespeare.url
    

    Or

    xclip -selection clipboard < data/spongebob/build/spongebob-patty.url
    
  2. Paste into the address bar and press Enter.

Then:

  • It starts writing on its own.
  • Type anything and pause for a moment. It continues from your text.
  • Tab asks for more. Esc stops.

Browsers block a web page from opening a data: link, so paste it or save it as a bookmark. A link can also be saved as a local HTML file, which opens without the paste:

python3 -c "import urllib.parse,sys; u=open(sys.argv[1]).read().strip(); open(sys.argv[2],'w').write(urllib.parse.unquote(u.split(',',1)[1]))" dist/shakespeare.url shakespeare.html

Train on your own text

Four steps: describe the corpus, learn a tokenizer, train, build.

1. Describe the corpus

A corpus spec is a TOML file that lists your folders. examples/corpus/spec.toml is a complete, commented example over notes, code and chat sources in examples/corpus/, and examples/corpus/spec-memo.toml is the same with memo lines on. Copy one and point the sources at your own folders:

name = "mine"
chunk_chars = 4096
val_fraction = 0.05
maps = ["newlines", "bom", "typographic"]
memo_every = 400
memo_chars = 160

[[source]]
name = "stories"
path = "/home/you/stories"
include = ["*.txt"]
python3 tools/prepare.py mine.toml --out corpora/mine

It writes train.txt, val.txt, vocab.json and report.json to corpora/mine and prints what it read. Nothing is changed or dropped silently:

  • A character outside the allowed set stops the build, with its code point, its count and the file, line and column where it first appears.
  • Every replacement comes from a map the spec names (newlines, bom, typographic, tabs4) and is counted in the report.
  • A binary file, a file that is not UTF-8, a source that matches no files, or an unknown spec key stops the build.
  • Duplicate files and hidden files are skipped and listed.

Spec settings:

Key Default Meaning
name required Corpus name, stored in the model
chunk_chars 4096 Documents are cut into chunks of at most this size for the split
val_fraction 0.05 Share of the text held out for validation
separator "\n\n" Written between documents and around held-out chunks
charset "ascii" Printable ASCII, newline and tab
extra_chars "" More allowed characters, e.g. "\u00e9"
maps ["newlines", "bom"] Replacements applied before the character check
on_unknown "error" "drop" removes disallowed characters and counts them
dedupe true Skip files identical to one already read
vocab "charset" "charset": every allowed character gets a token. "corpus": only characters that occur
memo_every 0 Restate each document's first lines on a memo line after every this many characters; 0 is off
memo_chars 160 How much of the document's start a memo line holds; memo_every must be at least twice this

Per source: name, path (a folder or one file, relative to the spec), include and exclude (glob patterns), repeat (write its training chunks this many times to weight it), hidden (read hidden files), skip_binary (skip binary files instead of stopping).

Memo lines keep a document's setup in view. The first non-blank lines of each document (title, setting, whatever the story depends on), up to memo_chars, are written again on a marked line every memo_every characters. The model is never trained to write memo lines, only to read them, and the page inserts them by the same rule while it writes, invisibly. Without them a small model forgets a name or a detail once it scrolls out of its window.

2. Learn a tokenizer

python3 tools/bpe.py train --corpus corpora/mine --vocab 1024

It writes corpora/mine/tokenizer.json and prints characters per token. Tokens are subwords: a word with its leading space can be one token, so the model's window covers about 2.5 to 4 times as much text as with characters, and a name is copied as one token instead of letter by letter. Merges never cross a newline or a memo mark. Templated corpora may stop short of the requested size when no pair repeats; that is reported, not an error.

Without this step the model uses characters, as v0.0.2 did.

3. Train

python3 tools/train.py --corpus corpora/mine --tokenizer corpora/mine/tokenizer.json --preset default --out models/mine --steps 6000 --lr 1e-3

--device auto (the default) uses a CUDA GPU when PyTorch sees one. The best checkpoint by validation bits per character is exported to models/mine as model.json, weights.bin and latent.pt. Bits per character compare directly between character and subword models.

Presets (sizes at 3.3 stored bits per weight, with the tokenizer size shown):

Preset Width Heads Stored layers x loops Depth Context Tokenizer Parameters Link payload
tiny 64 4 1 x 6 6 256 tokens 512 82K ~33 KB
default 128 4 2 x 4 8 256 tokens 1,024 524K ~211 KB
large 288 8 2 x 4 8 512 tokens 1,024 2.29M ~921 KB

Recurrent blocks are about 3% smaller than attention blocks of the same width. large uses batch 16; lower --batch if your GPU runs out of memory.

Architecture options (each also settable without a preset):

Option Default Meaning
--mixer attention Per stored layer: a attention, r recurrent. attention, recurrent and hybrid (alternating, recurrent first) are shorthands; ra and rr also work
--layers, --loops preset Stored blocks, and how many times the stack runs. Depth costs compute, not bytes
--global-heads heads / 4 with a preset Attention heads with no distance penalty, which can reach the whole window
--rank preset Rank of the recurrent decay gate
--ctx preset Training window in tokens, and the size of each attention ring
--init Fine-tune from an exported model. Its stored shape is kept; --loops, --ctx and --global-heads may change

How much text: the default preset wants at least a few megabytes of text to learn patterns instead of memorizing lines, large ten times that. The trainer prints a note when the corpus is much smaller than the model.

4. Build and check

python3 tools/build.py --model models/mine --out dist/mine
python3 tools/verify.py --model models/mine --wasm dist/mine.wasm --corpus corpora/mine
python3 tools/session.py --model models/mine --wasm dist/mine.wasm --prompt "TITLE: " --tokens 300

dist/mine.url is your link. tools/session.py writes exactly what the page would write for the same seed, which makes it the tool for scoring samples in bulk.

A link is a copy of the model, and a small model can repeat lines of its training text word for word. Do not publish a link trained on anything you would not publish as text.

What the page does while it writes

  • Subword healing. The last word you typed is not fed as tokens; the first tokens the model writes must spell it. "Once upon a ti" is completed as the model would have tokenized "time", not as a lone "ti" it never saw.
  • Memo lines. When the model was trained with memo lines, the page inserts them by the same rule, invisibly.
  • Line starts. Right after a newline, only tokens that start a line somewhere in the training text can be sampled. In a script that means speaker names and stage directions, not stray fragments.
  • No memo marks. The memo mark itself is never sampled.

tools/session.py implements the same steps in Python, and the checks confirm the two write the same text.

The shipped links

shakespeare shakespeare-tiny
File dist/shakespeare.url dist/shakespeare-tiny.url
URL length 252,312 chars 62,306 chars
Parameters 448,608 102,464
Shape characters, 4 attention layers, width 96 characters, 2 attention layers, width 64
Module, deflated 185,709 bytes 43,204 bytes
Stored bits per weight 3.30 3.30
Validation, 128-char blocks 2.25 bits/char 2.53 bits/char
Validation, streaming 2.22 bits/char 2.51 bits/char
Speed, one thread, in Node 22 about 7,400 chars/s about 23,600 chars/s
Memory while running 2.6 MB 0.7 MB

Both are the v0.0.2 character models, trained on TinyShakespeare (1.1 MB, 65 distinct characters) with the last 10% of the file held out, rebuilt with this version's engine. Speed was measured on a shared 2-core cloud VM, so treat it as a floor. The page around the payload grew from 1,647 to 4,700 characters for the tokenizer, memo lines and masks.

How it fits

Every choice below removes bytes from the URL.

Weights are 4-bit, and the browser is the entropy coder. Each weight matrix is scale * q with q an integer from -7 to 7, trained that way from the start (quantization-aware training with a straight-through estimator). Two weights are packed per byte. The values are bell-shaped, not uniform, so deflate's Huffman coding takes them from 4 bits down to about 3.3. The decoder is DecompressionStream, which the browser already ships.

Nothing is stored except weight matrices. The output head is the embedding matrix, used twice. Norms have no learned gain. There are no biases and no positional table. Fixed tables (attention slopes, the recurrent decay spread) are computed from the shape, not trained.

Depth without bytes. The stored blocks run loops times. The default preset stores 2 blocks and runs them 4 times, for 8 layers of depth at the price of 2.

Two kinds of block.

  • Attention: ALiBi causal attention over a ring of ctx positions. Each head subtracts slope * distance from its scores. The last global_heads heads have slope 0, so they can reach the whole window instead of fading with distance.
  • Recurrent: a selective diagonal recurrence. Each channel keeps one number, updated as s = a * s + (1 - a) * silu(u), where the decay a depends on the input through a low-rank gate on top of a fixed spread of halflives from 1 to 4,096 tokens. A 4-tap causal convolution in front handles local patterns. The state is a fixed size with no window, so a recurrent block's memory never scrolls out. Training runs the recurrence as a parallel prefix scan with a hand-written backward pass; the engine runs it one token at a time.

Mixing the two (--mixer hybrid) gives exact recall over the recent window from attention and an unbounded running summary from the recurrence.

The engine is one WebAssembly module with no imports. src/dense_llm.wat is written by hand: an f32x4 SIMD dot product, matrix-vector products, RMSNorm, softmax, sigmoid, a masked sampler, and its own exp. tools/build.py keeps only the block types a model uses and writes out the layer stack, one call per layer of depth. It assembles to about 1,600 bytes (930 after deflate) for an attention model and about 2,100 for a hybrid. The weights, the tokenizer merges and the line-start table are its data segment.

Output is identical on every runtime. The engine uses only operations WebAssembly defines exactly, and computes exp itself instead of importing Math.exp. A given seed and prompt produce the same characters everywhere.

Why 15 levels

Three character models of about the same deflated size, 3,000 training steps each, on TinyShakespeare:

Weight values Parameters Deflated Bits per weight Validation loss
15 levels (-7..7) 102,464 43,056 bytes 3.30 1.757 nats/char
7 levels (-3..3) 158,800 49,144 bytes 2.44 1.771 nats/char
3 levels (-1..1) 235,600 52,655 bytes 1.76 1.819 nats/char

Fewer levels buy more parameters per byte, but not enough to pay for themselves at this scale. This was measured on small models only; --levels can test it again at the large size.

Verification

tools/verify.py checks a built module against the PyTorch model it came from:

  1. probabilities at every position of one context block
  2. validation bits per character over all blocks, engine against PyTorch
  3. streaming: the engine runs the whole validation text without a reset, so attention rings wrap and recurrent state carries on. The first 4 windows are compared with PyTorch over the same stretch with attention limited to a band of ctx, which is what a wrapped ring computes. Then the streaming loss.
  4. a fixed-seed sample and its SHA-256

tools/run_url.mjs opens a link the way the page does, in Node, and prints the same sample's SHA-256. tools/open_url.py opens a link in headless Chrome, exercises typing, Tab and Esc, and with --model compares the page's text against tools/session.py for several prompts and seeds.

Check shakespeare shakespeare-tiny hybrid, subwords, memos (CI) recurrent, subwords, memos (CI)
Largest probability difference, one block 1.5e-06 1.6e-06 3e-08 2e-08
Largest probability difference, streaming, 3 ring wraps 2.7e-06 1.6e-06 3e-08 2e-08
Same sample SHA-256 in wasmtime and Node yes yes yes yes
Page and session write the same text, 5 prompts yes yes yes yes

The CI models are trained for 60 steps only; they check the machinery, not quality. The recurrent scan's gradients are checked against a step-by-step loop in tests/test_model.py.

Not tested: Firefox, Safari, pasting by hand into a real address bar (the Chrome test navigates to the URL directly), and training on a GPU.

Run the checks

pip install torch --index-url https://download.pytorch.org/whl/cpu
pip install -r requirements.txt
sh tools/check.sh

tools/check.sh is what CI runs: the unit tests; three tiny models (characters with attention; subwords with memo lines, a hybrid stack, shared layers and a head with no distance penalty; subwords with recurrent blocks only), each trained for a few steps, built and verified, with sample digests compared between wasmtime and Node and the page compared with the session when Chrome is installed; and a byte-for-byte rebuild of both shipped links. wasmtime and zopfli are pinned in requirements.txt because another version of either changes the bytes of a link.

To rebuild the Shakespeare models from scratch, fetch the corpus first (it is not in this repository):

mkdir -p data
curl -L -o data/input.txt https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt
python3 tools/train.py --corpus data/input.txt --out models/shakespeare --levels 7 --layers 4 --d 96 --steps 5000
python3 tools/train.py --corpus data/input.txt --out models/shakespeare-tiny --levels 7 --layers 2 --d 64 --steps 3000

Without --preset, the trainer uses the v0.0.2 shape: characters, attention, no shared layers, a 128-token window.

Tree

src/dense_llm.wat         inference engine, WebAssembly text
src/page.html             page and loader around the payload
tools/prepare.py          corpus builder: spec -> train.txt, val.txt, vocab.json, memo lines
tools/bpe.py              subword tokenizer: learn merges, encode, decode
tools/arch.py             shapes, presets and fixed tables shared by every tool
tools/train.py            quantization-aware trainer and exporter
tools/build.py            model -> .wasm -> .url
tools/session.py          the page's generation logic in Python, for scoring samples
tools/verify.py           engine vs PyTorch: block, streaming, sample digest
tools/run_url.mjs         runs a link in Node and prints the sample digest
tools/open_url.py         opens a link in headless Chrome; page vs session
tools/check.sh            every CI check
tests/                    corpus builder, tokenizer and model tests
examples/corpus/          example specs with notes, code and chat sources
examples/shakespeare/     spec for TinyShakespeare as a prepared corpus
models/                   shipped models: config, int8 weights, float checkpoint
dist/                     shipped links, modules and size reports

Prepared corpora (corpora/) and raw text (data/) are ignored by git, so private training text does not end up in a commit by accident.

Limits

  • It writes in the style of its training text. The shipped links have read 1 MB of Shakespeare and nothing else, and do not answer questions.
  • Attention sees the last ctx tokens of each layer's input; recurrent blocks carry a fixed-size summary of everything before.
  • A character outside the vocabulary that you type into the page is read as the fallback character (a space by default).
  • About a quarter of the URL is base64 overhead.
  • The engine needs WebAssembly SIMD, which current Chrome, Firefox and Safari support.
  • The new presets and block types are verified for correctness here, not yet trained to measure quality.

License

Apache License 2.0. See LICENSE and NOTICE.

About

A small language model entirely contained within a URL. WebAssembly SIMD engine.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages