Pocket Storyteller
A tiny language model that writes children's stories. Its whole brain is one 4.6 MB file, and it runs inside a browser tab in plain JavaScript. No server, no GPU, no libraries.
In the picture the word "and" is tapped. The panel shows that the model's favourite there was "fox" (32%) and that this time it went with its second choice (18%). The words outlined in blue are the ones it was looking at.
Three ways to try it
- Live: open the demo Space. The model runs in your own browser tab.
- Offline: download
pocket-storyteller.htmland double-click it. The page, the engine and the model are all inside that one file. - Your own site or app: copy the three files in
web/to any web host.
What the page does
- Type a first line and press Tell a story. It writes one word-piece at a time.
- Tap any word. The panel shows the 8 pieces the model liked most at that spot, and outlines in blue the earlier words it was looking at when it chose.
- Tap a different bar. The story rewinds to that spot, uses your pick, and carries on from there. It works on "The end." too, so you can make a finished story keep going.
- Imagination makes it safer or wilder. Speed goes from slow up to flat out.
The numbers
Everything here was measured on 4 and 5 December 2026, on the 4-core cloud machine that trained it.
| Size of the model file | 4,589,020 bytes (4.6 MB) |
| Parameters | 5.57 million: 6 layers, 256 wide, 8 attention heads, remembers the last 256 word-pieces |
| Vocabulary | 4,096 word-pieces (a small tokenizer trained for this model) |
| Training data | all of TinyStoriesV2: 2.7 million stories, 557 million word-pieces |
| Training | from scratch, 57,954 steps in 9 hours on a 4-core CPU, no GPU. It read 475 million word-pieces in that time. Passages are picked at random, so some stories came up more than once and some never did |
| Loss on stories it never saw | 1.384 before packing, 1.387 after packing, measured on 1.02 million word-pieces. Lower is better. 1.39 means that at each step it is about as unsure as picking between 4.0 equally likely pieces. After the first 3 hours it was 4.8 |
| First guess for the next piece | right 66.0% of the time (62.4% after the first 3 hours) |
| Who is who | when a story has two or more named characters and the next word is one of their names, it prefers the right one 92.5% of the time (90.2% after the first 3 hours; picking one of those names at random would give 49%) |
| Speed | 100 to 160 word-pieces a second in Node, 60 to 105 on the page at "flat out" in headless Chromium, same machine |
The loss is counted per word-piece of this model's own tokenizer, so it cannot be compared directly with models that split text differently.
How it got here
| Steps so far | Loss before packing | Loss after packing | Right character | First guess right | |
|---|---|---|---|---|---|
| First 3 hours, on the first 512,000 stories | 8,537 | 1.571 | 1.572 | 90.2% | 62.4% |
| 3 more hours (round 1), on all the stories | 32,429 | 1.436 | 1.438 | 92.0% | 65.0% |
| 3 more hours (round 2), the model that ships | 57,954 | 1.384 | 1.387 | 92.5% | 66.0% |
Each round starts with a high learning rate and cools down, so the loss gets worse for the first minutes of a round and ends lower than before.
Round 2 gained much less than round 1: 0.05 against 0.13. Another round like these would probably add less again.
The model that ships is the average of the last 16 saves of round 2, which were 250 steps apart. Averaging the numbers of several nearby saves often gives a slightly better model than any one of them, and here it did: on the same 1.02 million word-pieces the last save alone scores 1.396 and the average 1.384. How many saves to average was chosen on a different 512,000 word-pieces (1.3897 for the last save, 1.3775 for the average), so the big sample played no part in the choice. code/avg_snaps.py does this.
The extra rounds did 2.8 and 3.0 times as many steps as the first 3 hours. The machine's processor can multiply 16-bit numbers much faster than 32-bit ones (Intel AMX), so train.py --fast does the big multiplications that way and compiles the model. A check on one batch shows that this teaches the same thing: the direction of learning agrees with the plain 32-bit way to 0.9999 (where 1 is identical, and two different batches agree to about 0.05). The loss on unseen stories is always measured the plain way.
How it fits in under 5 MB
The trained model is 22 MB of 32-bit numbers. code/export.py stores each number with fewer bits: 8 bits for the word-piece table and 6 bits for everything else. code/quant_eval.py measures what each choice costs. On the final model:
| Bits per number | Size of the numbers | Loss | Change |
|---|---|---|---|
| 32, as trained | 22.37 MB | 1.3702 | |
| 8 | 5.66 MB | 1.3707 | +0.0004 |
| 7 | 4.97 MB | 1.3721 | +0.0018 |
| 8 for the word-piece table, 6 for the rest | 4.53 MB | 1.3733 | +0.0031 |
| 6 | 4.27 MB | 1.3768 | +0.0066 |
| 8 and 5 | 3.97 MB | 1.3830 | +0.0127 |
| 5 | 3.57 MB | 1.3989 | +0.0287 |
| 8 and 4 | 3.40 MB | 1.4260 | +0.0558 |
| 4 | 2.88 MB | 1.4918 | +0.1215 |
This table uses a smaller sample (196,000 word-pieces) than the table above, which is why its starting loss is a little different. The change column was worked out before rounding, so its last digit can differ by one from what the loss column suggests. On the large sample the row in bold costs 0.003 (1.3844 to 1.3873).
The first column is the size of the numbers alone. The file adds about 0.06 MB for the word-piece list. The row in bold is the one that ships. Three thousandths is far too small to see in the stories.
Squeezing costs more now than it did on the first 3-hour model. The row in bold went from +0.0020 to +0.0031, and the rows with 5 bits or fewer cost about twice what they did (4 bits: +0.054 then, +0.12 now).
Checks that were run
code/tests/bigval.pymeasures the loss of the checkpoint and of the packed file on 1.02 million word-pieces of unseen stories. These are the loss numbers above.code/tests/check_export.pyreads the packed file back in Python and compares its loss with the original checkpoint.code/tests/check_engine.jschecks that the JavaScript engine splits text into the same pieces as Python and gets the same scores as PyTorch (largest difference 0.00002), and that rewinding and steering give the same answers as doing it from scratch.code/tests/window_test.jscompares two ways of handling stories longer than the model's memory. Sliding (overwrite the oldest piece) was as good as re-reading (loss 1.285 against 1.286 on text beyond the memory size, on the final model) and has no pauses, so the page uses sliding.code/tests/name_probe.pyis the "who is who" test in the tables. It finds 13,654 spots in 6,000 unseen stories where the next word is the name of one of two or more characters already in the story, and checks which of those names the model prefers. It ran on the packed files.code/tests/sampling_eval.jswrites stories with fixed random numbers and counts words that never appear in 120 MB of the real stories, repeated phrases, and stories that reach an ending. On 160 stories at the default setting the first 3-hour model and the final one score about the same: 4 and 5 made-up words out of about 23,000, 1.8% and 2.0% of 4-word runs repeated, 121 and 119 stories finished. So the extra training shows up in the loss and in the "who is who" test, not in these counts.- The page was clicked through automatically in headless Chromium at laptop, tablet and phone sizes, in light and dark mode, with the first model. With the final model the one-file page and the page in
web/were opened again: they load, write a story, show the 8 bars and steer. model.safetensorsholds exactly the same numbers ascode/ckpt.pt, and the Python example below was run as written.
What it can't do
- It only knows the little world of TinyStories: simple English words, animals, toys, moms, parks. Ask about anything else and you get a children's story anyway. It is a toy for learning how small language models work, not an assistant.
- It still repeats itself at times and plots wander. In the "who is who" test it prefers the wrong name about 1 time in 13. About 1 word in 5,000 is glued together from pieces and is not in the real stories (5 of 23,731 words in the 160 test stories), the same as before the extra training.
- Not tested: Safari and Firefox, real phones, and training on a GPU. Only Chromium and a CPU were available.
Use it in your own page
<script src="storyteller.js"></script>
<script type="module">
const st = await Storyteller.load("storyteller.bin");
st.reset(st.encode("Once upon a time"));
let step;
while (!(step = st.next({ temperature: 0.8, topK: 40 })).done) {
document.body.append(step.text);
// step.prob = how sure it was, step.top = its 8 favourites, step.attn = what it looked at
}
</script>
storyteller.js is about 290 lines with comments. st.push(id) writes a piece of your choosing, and st.rewind(n) goes back in time.
In the terminal, with Node: node code/tell.js "Once upon a time, there was a little fox named Pip".
Use the full-precision weights in Python
model.safetensors is the model before packing, as 32-bit numbers. You need torch and safetensors. Run this from the top folder of the repository:
import json, sys, torch
from safetensors.torch import load_file
sys.path.insert(0, "code")
from model import Config, Storyteller
from tokenizer import Tokenizer
cfg = json.load(open("config.json"))
model = Storyteller(Config(**cfg["model"]))
model.load_state_dict(load_file("model.safetensors"))
model.eval()
tok = Tokenizer.load(cfg["tokenizer"])
start = [0] + tok.encode("Once upon a time, there was a little fox named Pip") # 0 marks the start of a story
story = model.generate(torch.tensor([start]), 200) # up to 200 more word-pieces
print(tok.decode(story[0].tolist()))
Train it more
Is it worth it? Round 1 improved the loss by 0.13 and round 2 by 0.05, so a third round of 3 hours would probably add less than that. A bigger step would need a different recipe, for example a larger model that is trained to survive being stored in 4 bits. That has not been tried.
Everything is in code/. You need Python with torch and numpy.
cd code
mkdir -p data
curl -L -o data/train.txt https://huggingface.co/datasets/roneneldan/TinyStories/resolve/main/TinyStoriesV2-GPT4-train.txt
curl -L -o data/valid.txt https://huggingface.co/datasets/roneneldan/TinyStories/resolve/main/TinyStoriesV2-GPT4-valid.txt
python prepare.py data/valid.txt data/tok4096.json data/val.bin
python prepare.py data/train.txt data/tok4096.json data/train.bin
The training file is 2.2 GB. prepare.py reads it a piece at a time and took 2 minutes on the 4-core machine.
Keep training the included checkpoint:
python train.py --resume --minutes 180 --lr 5e-4 --fast --keep 16
python avg_snaps.py ckpt.pt snaps ckpt_avg.pt
The first line trains for 3 more hours and keeps the last 16 saves in snaps/. The second tries averaging them, and writes ckpt_avg.pt if that beats the last save. Round 2 started at a learning rate of 7e-4. A third round should start a little lower, which is why the line says 5e-4. A third round has not been run.
Leave out --fast if your processor is not a recent Intel one (look for amx_bf16 in /proc/cpuinfo). It still works, at under half the speed. On a GPU --fast should also help, but that has not been tested.
Or let rounds run one after another without watching them. rounds.conf lists them (name, minutes, learning rate). The two rounds that made this model are in that file as notes, with a third one ready to switch on. Then:
bash more.sh
python avg_snaps.py rounds/round3.pt snaps rounds/round3_avg.pt
more.sh keeps each result in rounds/ and the last 16 saves in snaps/. If the machine restarts, run it again and it carries on where it stopped.
Or start over, for example on a GPU (not tested):
python train.py --steps 30000 --batch 64 --lr 1.5e-3
Then pack it, measure it, check it and rebuild the demo files:
bash finalize.sh # uses ckpt.pt
bash finalize.sh ckpt_avg.pt # or any other checkpoint
dist/pocket-storyteller.html and dist/web/ are the fresh copies of the two things at the top of this repository. python to_safetensors.py ckpt.pt model.safetensors config.json writes the other two.
To change the tokenizer you would run python tokenizer.py data/train.txt 4096 data/tok4096.json first, but then the included checkpoint no longer fits and you have to train from scratch.
What's in this repository
pocket-storyteller.html |
the whole demo in one file |
web/ |
the same demo as three files: index.html, storyteller.js (engine), storyteller.bin (the 4.6 MB model) |
model.safetensors, config.json |
the model before packing, in full precision, and its shape |
code/tokenizer.py |
splits text into word-pieces |
code/prepare.py |
turns the stories into numbers for training |
code/model.py |
the model: a small Llama-style transformer |
code/train.py |
training loop, CPU or GPU |
code/more.sh, code/rounds.conf |
run extra rounds of training one after another |
code/avg_snaps.py |
averages the last saves of a round |
code/export.py |
packs a checkpoint into storyteller.bin |
code/to_safetensors.py |
writes model.safetensors and config.json |
code/quant_eval.py |
measures the cost of using fewer bits |
code/build.py |
builds the one-file page and the web/ folder |
code/web/ |
page and engine source |
code/tests/ |
the checks described above |
code/tell.js |
tells a story in the terminal |
code/finalize.sh |
pack, measure, check and rebuild in one go |
code/ckpt.pt |
the final model as a PyTorch checkpoint, with the optimizer's state, ready for --resume. It is a pickle file. model.safetensors has the same weights in a safer format |
code/train_log.jsonl |
loss and a sample story along the way, for every round |
License and credits
The code and the weights in this repository are under the MIT license.
Trained from scratch on TinyStories by Ronen Eldan and Yuanzhi Li (paper), which is under the CDLA-Sharing-1.0 license. The stories used here (the TinyStoriesV2-GPT4 files) were written by GPT-4.
- Downloads last month
- -
