File size: 19,134 Bytes
ebf8f81 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | <meta charset="utf-8">
<title>Pocket Storyteller</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Baloo+2:wght@600;800&family=Literata:opsz,wght@7..72,400;7..72,600&family=Inter:wght@400;600&display=swap" rel="stylesheet">
<style>
/* VOICE occasion, hushed: a bedtime picture book that writes itself
IDEA an open storybook page beside a peek inside the storyteller's head
PICTURE the story page itself, words inked in as they are chosen, each tinted by how sure the model was
COLOUR white page, cornflower field #3555e8, ink #18183a, sunshine #ffcf33 for "sure", coral #ff6b5e for "guess"
TYPE Baloo 2 display + Literata story text + Inter for the machinery
LAYOUT laptop: blue band with title and prompt, then page (wide) | head panel; phone: title, page, head panel */
:root{color-scheme:light dark;--bg:light-dark(#ffffff,#0f1230);--ink:light-dark(#18183a,#eef0ff);--soft:light-dark(#5b5f86,#a8addb);--field:light-dark(#3555e8,#24349c);--mark:light-dark(#3555e8,#8ea2ff);--paper:light-dark(#fffdf7,#171b42);--edge:light-dark(#e3e5f3,#2c3270);--sure:#ffcf33;--guess:#ff6b5e;--chip:light-dark(#eef1ff,#222866)}
:root[data-theme=light]{color-scheme:light}:root[data-theme=dark]{color-scheme:dark}
*{box-sizing:border-box;min-width:0}
[hidden]{display:none!important}
body{background:var(--bg);color:var(--ink);font:16px/1.55 Inter,system-ui,sans-serif;overflow-x:clip;margin:0}
.wrap{max-width:1240px;margin:0 auto}
.band{padding-left:max(5vw,16px,env(safe-area-inset-left,0px));padding-right:max(5vw,16px,env(safe-area-inset-right,0px))}
.top{background:var(--field);color:#fff;margin-top:calc(-1*env(safe-area-inset-top,0px));padding-top:calc(env(safe-area-inset-top,0px) + 28px);padding-bottom:28px}
.top .wrap{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.4fr);gap:28px;align-items:end}
h1{font:800 clamp(34px,5vw,52px)/1.05 "Baloo 2",system-ui,sans-serif;letter-spacing:-.02em;margin:0}
.lede{margin:6px 0 0;color:#dfe5ff;max-width:34em}
form{display:flex;flex-wrap:wrap;gap:10px}
#prompt{flex:1 1 260px;font:16px Literata,Georgia,serif;padding:12px 14px;border-radius:12px;border:2px solid #fff;background:#fff;color:#18183a}
.top button{font:600 16px Inter,system-ui,sans-serif;border-radius:12px;min-height:46px;padding:0 18px;cursor:pointer;border:2px solid #fff}
.top button:disabled{opacity:.5;cursor:default}
.go{background:var(--sure);color:#18183a;border-color:var(--sure)!important}
.go:not(:disabled):hover{filter:brightness(1.06)}
.go:not(:disabled):active{transform:translateY(1px)}
.ghost{background:transparent;color:#fff}
.ghost:not(:disabled):hover{background:#ffffff22}
button:focus-visible,#prompt:focus-visible,input:focus-visible{outline:3px solid var(--sure);outline-offset:2px}
.starts{display:flex;flex-wrap:wrap;gap:8px;margin-top:10px}
.top .starts button{min-height:34px;padding:0 12px;font:400 14px Inter,system-ui,sans-serif;background:#ffffff1f;color:#fff;border:1px solid #ffffff55;border-radius:99px}
.top .starts button:hover{background:#ffffff38}
main .wrap{display:grid;grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);gap:28px;padding-block:28px 24px;align-items:start}
.page{background:var(--paper);border:1px solid var(--edge);border-radius:18px;padding:clamp(20px,3vw,40px);min-height:460px;position:relative;align-self:stretch}
#story{font:clamp(18px,1.6vw,21px)/1.75 Literata,Georgia,serif;white-space:pre-wrap;overflow-wrap:anywhere;margin:0}
#story span{border-radius:4px}
#story .p{font-weight:600}
#story .t{background:color-mix(in srgb,var(--c) var(--a),transparent);cursor:pointer}
#story .t:hover{box-shadow:0 2px 0 var(--mark)}
#story .forced{text-decoration:underline dotted var(--mark) 2px;text-underline-offset:4px}
#story .look{outline:2px solid var(--mark);background:color-mix(in srgb,var(--mark) var(--w),transparent)}
#story .sel,.end.sel{outline:2px solid var(--ink)}
.caret{display:inline-block;width:.5em;height:1.1em;background:var(--mark);vertical-align:-.15em;margin-left:2px;animation:blink 1s steps(1) infinite}
@keyframes blink{50%{opacity:0}}
.end{font:600 16px "Baloo 2",system-ui,sans-serif;color:var(--soft);margin-top:18px;width:fit-content;padding:0 6px;border-radius:6px;cursor:pointer}
.empty{color:var(--soft);font:18px/1.6 Literata,Georgia,serif;margin:0}
.meta{display:flex;flex-wrap:wrap;gap:6px 18px;margin-top:22px;font-size:14px;color:var(--soft)}
.meta b{color:var(--ink);font-variant-numeric:tabular-nums}
aside{display:flex;flex-direction:column;gap:18px}
.panel{border:1px solid var(--edge);border-radius:18px;padding:20px}
h2{font:800 24px/1.1 "Baloo 2",system-ui,sans-serif;margin:0 0 4px;letter-spacing:-.01em}
.sub{font-size:14px;color:var(--soft);margin:0 0 12px;min-height:4.6em}
.bars{display:grid;gap:2px}
.bar{display:grid;grid-template-columns:7.5em minmax(0,1fr) 3.6em;align-items:center;gap:8px;width:100%;min-height:30px;padding:0 6px;margin:0 -6px;box-sizing:content-box;border:0;border-radius:8px;background:none;color:inherit;font:14px Inter,system-ui,sans-serif;text-align:left;cursor:pointer}
.bar:disabled{cursor:default}
.bar:not(:disabled):hover{background:var(--chip)}
.bar .w{font:15px Literata,Georgia,serif;white-space:pre;overflow:hidden;text-overflow:ellipsis}
.bar .track{height:14px;background:var(--chip);border-radius:7px;overflow:hidden}
.bar:not(:disabled):hover .track{background:var(--edge)}
.bar .fill{display:block;height:100%;background:var(--mark);border-radius:7px}
.bar.pick .fill{background:var(--sure)}
.bar.pick .w{font-weight:600}
.bar .p{text-align:right;font-variant-numeric:tabular-nums;color:var(--soft)}
.legend{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--soft);margin-top:14px}
.legend i{flex:1;height:10px;border-radius:5px;background:linear-gradient(90deg,color-mix(in srgb,var(--guess) 32%,transparent),color-mix(in srgb,var(--guess) 12%,transparent) 50%,color-mix(in srgb,var(--sure) 2%,transparent));border:1px solid var(--edge)}
label{display:block;font-size:14px;font-weight:600;margin-top:12px}
label small{font-weight:400;color:var(--soft)}
input[type=range]{width:100%;accent-color:var(--mark);height:30px}
.note{font-size:13px;color:var(--soft);margin:10px 0 0}
#loading{position:absolute;inset:0;display:grid;place-items:center;text-align:center;background:var(--paper);border-radius:18px;padding:20px}
#loading b{font:800 22px "Baloo 2",system-ui,sans-serif}
#loading .track{width:min(320px,80%);height:10px;background:var(--chip);border-radius:5px;margin:12px auto 0;overflow:hidden}
#loading .fill{height:100%;width:0;background:var(--mark)}
footer{padding-bottom:40px}
footer p{margin:0;padding-top:16px;border-top:1px solid var(--edge);font-size:14px;color:var(--soft);max-width:none}
@media(pointer:coarse){.bar{min-height:40px}}
@media(max-width:600px){.top .starts button:nth-child(n+4){display:none}.sub{min-height:0}}
@media(max-width:860px){.top .wrap,main .wrap{grid-template-columns:minmax(0,1fr)}.page{min-height:340px}}
@media(prefers-reduced-motion:reduce){.caret{animation:none}}
</style>
<header class="top band"><div class="wrap">
<div>
<h1>Pocket Storyteller</h1>
<p class="lede">A <span id="sz">tiny</span> language model that runs entirely in this tab. Give it a first line and it writes the rest of a bedtime story, one word-piece at a time.</p>
</div>
<div>
<form id="f">
<input id="prompt" value="Once upon a time, there was a little fox named Pip" aria-label="First line of the story" autocomplete="off" maxlength="400">
<button class="go" id="go" disabled>Tell a story</button>
<button class="ghost" type="button" id="stop" disabled>Stop</button>
</form>
<div class="starts" id="starts"></div>
</div>
</div></header>
<main class="band"><div class="wrap">
<section class="page">
<div id="story"><p class="empty">Your story will appear here.</p></div>
<div class="meta" id="meta"></div>
<div id="loading"><div><b>Unpacking the storyteller</b><div class="track"><div class="fill" id="lf"></div></div><p class="note" id="lt">Starting</p></div></div>
</section>
<aside>
<div class="panel">
<h2>Inside its head</h2>
<p class="sub" id="hsub">At every step the model scores all 4,096 word-pieces it knows. These are its favourites for the next one. The yellow bar is the one it picked.</p>
<div class="bars" id="bars"></div>
<div class="legend"><span>a guess</span><i></i><span>very sure</span></div>
<p class="note">Words in the story are shaded by how unsure it was. Tap any word to see what it was choosing between, and which earlier words it was looking at (outlined in blue). Then tap a different bar to steer the story your way.</p>
</div>
<div class="panel">
<h2>Dials</h2>
<label for="temp">Imagination <small id="tv">0.80</small></label>
<input type="range" id="temp" min="0.1" max="1.5" step="0.05" value="0.8">
<label for="speed">Speed <small id="sv">reading pace</small></label>
<input type="range" id="speed" min="0" max="3" step="1" value="1">
<p class="note">Low imagination keeps it safe and repetitive. High makes it wilder and sillier.</p>
</div>
</aside>
</div></main>
<footer class="band"><div class="wrap"><p id="about">A small language model trained from scratch on the TinyStories dataset by Ronen Eldan and Yuanzhi Li. It only knows the little world of those stories. Every word is worked out on your device, and nothing you type leaves this page.</p></div></footer>
<script src="storyteller.js"></script>
<script>
{
const $ = (id) => document.getElementById(id);
const esc = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
const MODEL_URLS = ["storyteller.wasm", "storyteller.b64.txt"];
const STARTS = ["Once upon a time, there was a little fox named Pip", "Lily found a tiny door in the garden", "The big red ball rolled down the hill", "Tom wanted to fly like a bird", "One day, a dragon came to the village"];
const SPEEDS = [["slow", 6], ["reading pace", 18], ["fast", 60], ["flat out", 0]];
const MAX = 600;
const story = $("story"), bars = $("bars"), hsub = $("hsub"), HINT = hsub.textContent;
const caret = document.createElement("span"); caret.className = "caret";
const endEl = document.createElement("div"); endEl.className = "end"; endEl.textContent = "The end.";
let st = null, runId = 0, running = false, promptIds = [], steps = [], endStep = null, cur = null, made = 0, t0 = 0;
$("starts").innerHTML = STARTS.map((s, i) => `<button type="button" data-i="${i}">${esc(s.split(" ").slice(0, 5).join(" "))}...</button>`).join("");
$("starts").onclick = (e) => { const b = e.target.closest("button"); if (!b) return; $("prompt").value = STARTS[+b.dataset.i]; tell(); };
$("temp").oninput = () => { $("tv").textContent = (+$("temp").value).toFixed(2); };
$("speed").oninput = () => { $("sv").textContent = SPEEDS[+$("speed").value][0]; };
const pct = (p) => (p >= 0.0995 ? Math.round(100 * p) + "%" : p >= 0.001 ? (100 * p).toFixed(1) + "%" : "<0.1%");
// text just before step i, to tell "a new word" from "more of the same word"
const before = (i) => (i > 0 ? steps[i - 1].text : promptIds.length ? st.vocab[promptIds[promptIds.length - 1]] : "");
function label(r, prev) {
if (r.id === 0) return "(the end)";
if (r.text === "\n") return "(new line)";
if (r.text[0] === " ") return r.text.slice(1) || "(space)";
return /[A-Za-z]$/.test(prev) && /^[A-Za-z]/.test(r.text) ? "..." + r.text : r.text;
}
const rowsOf = (s) => (s.top.some((r) => r.id === s.id) ? s.top : [...s.top, { id: s.id, text: s.text, p: s.prob }]);
function drawBars(s, i, live) {
const rows = rowsOf(s), max = Math.max(rows[0].p, 1e-9), prev = before(i);
bars.innerHTML = rows.map((r) => `<button type="button" class="bar${r.id === s.id ? " pick" : ""}" data-id="${r.id}"${live ? " disabled" : ""}><span class="w">${esc(label(r, prev))}</span><span class="track"><span class="fill" style="width:${(100 * r.p / max).toFixed(1)}%"></span></span><span class="p">${pct(r.p)}</span></button>`).join("");
}
function clearMarks() {
story.querySelectorAll(".look,.sel").forEach((x) => { x.classList.remove("look", "sel"); x.style.removeProperty("--w"); });
endEl.classList.remove("sel");
}
function addStep(s) {
const el = document.createElement("span");
el.className = s.forced ? "t forced" : "t";
el.textContent = s.text;
el.style.setProperty("--c", `color-mix(in srgb,var(--sure) ${Math.round(s.prob * 100)}%,var(--guess))`);
el.style.setProperty("--a", Math.round(2 + 30 * (1 - s.prob) ** 2) + "%");
story.insertBefore(el, caret.parentNode === story ? caret : null);
steps.push(s);
}
function meta() {
const secs = (performance.now() - t0) / 1000;
$("meta").innerHTML = `<span>Model file <b>${(st.bytes / 1e6).toFixed(1)} MB</b></span><span><b>${(st.params / 1e6).toFixed(1)} million</b> parameters</span><span><b>${steps.length}</b> word-pieces written</span>${made > 3 ? `<span><b>${Math.round(made / secs)}</b> per second</span>` : ""}`;
}
function tell() {
if (!st) return;
runId++; running = false;
promptIds = st.encode($("prompt").value.trim());
if (!promptIds.length) { $("prompt").value = STARTS[0]; promptIds = st.encode(STARTS[0]); }
steps = []; endStep = null;
story.textContent = "";
for (const id of promptIds) { const el = document.createElement("span"); el.className = "p"; el.textContent = st.vocab[id]; story.appendChild(el); }
st.reset(promptIds);
run();
}
// "flat out" must not wait for the screen: this runs a function as soon as the browser is free
const chan = new MessageChannel(); let queued = null;
chan.port1.onmessage = () => { const f = queued; queued = null; if (f) f(); };
const soon = (f) => { queued = f; chan.port2.postMessage(0); };
function run() {
const my = ++runId; let last = 0, latest = null;
running = true; cur = null; made = 0; t0 = performance.now();
clearMarks(); endEl.remove(); story.appendChild(caret);
hsub.textContent = HINT; $("stop").disabled = false;
const paint = () => { if (my === runId && latest) { drawBars(latest, steps.length - 1, true); meta(); } latest = null; };
const tick = () => {
if (my !== runId) return;
const now = performance.now(), rate = SPEEDS[+$("speed").value][1], gap = rate ? 1000 / rate : 0;
if (!last || now - last > 400) last = now - gap;
let owed = rate ? Math.floor((now - last) / gap) : 99, s = null;
while (owed-- > 0) {
s = st.next({ temperature: +$("temp").value, topK: 40 });
if (s.done) { endStep = s; finish(true); return; }
addStep(s); made++; last += gap;
if (steps.length >= MAX) { finish(false); return; }
if (performance.now() - now > 10) break; // let the page breathe
}
if (s) { if (!latest) requestAnimationFrame(paint); latest = s; }
if (rate) setTimeout(tick, Math.max(4, last + gap - performance.now())); else { last = performance.now(); soon(tick); }
};
tick();
}
function finish(isEnd) {
runId++; running = false;
caret.remove(); if (isEnd) story.appendChild(endEl);
$("stop").disabled = true; meta();
if (isEnd || steps.length) inspect(isEnd ? steps.length : steps.length - 1);
}
// show what the model was thinking when it chose step i (i === steps.length means "the end")
function inspect(i) {
const isEnd = i === steps.length, s = isEnd ? endStep : steps[i];
if (!s) return;
clearMarks(); cur = { i, s };
const cells = story.querySelectorAll(".p,.t"), n = promptIds.length + i, L = s.attn.length;
(isEnd ? endEl : cells[n]).classList.add("sel");
drawBars(s, i, false);
hsub.textContent = isEnd
? (s.forced ? `Here you ended the story (it only gave that ${pct(s.prob)}).` : `Here it decided the story was over (${pct(s.prob)} sure).`) + " Tap another bar to make it carry on."
: s.forced
? `Here you made it write "${label(s, before(i))}" (it only gave that ${pct(s.prob)}). Tap another bar to rewrite the story from this word.`
: `Here it chose "${label(s, before(i))}" (${pct(s.prob)} sure). Tap another bar to rewrite the story from this word.`;
const seen = [];
for (let t = 0; t < L; t++) { const v = n - L + t; if (v >= 0) seen.push([cells[v], s.attn[t]]); }
seen.sort((a, b) => b[1] - a[1]);
const m = seen.length ? seen[0][1] : 0;
for (const [el, w] of seen.slice(0, 6)) if (w > 0.01 && w > 0.2 * m) { el.classList.add("look"); el.style.setProperty("--w", Math.round(10 + 40 * w / m) + "%"); }
}
story.onclick = (e) => {
if (running) return;
if (e.target === endEl && endStep) return inspect(steps.length);
const el = e.target.closest(".t");
if (el) inspect(Array.prototype.indexOf.call(story.querySelectorAll(".t"), el));
};
// steer: swap the chosen word for another candidate and let the story continue from there
bars.onclick = (e) => {
const b = e.target.closest("button[data-id]");
if (!b || running || !cur) return;
const id = +b.dataset.id, { i, s } = cur, cand = rowsOf(s).find((r) => r.id === id);
if (!cand || id === s.id) return;
const spans = story.querySelectorAll(".t");
for (let j = spans.length - 1; j >= i; j--) spans[j].remove();
steps.length = Math.min(steps.length, i); endStep = null; endEl.remove();
if (!st.rewind(1 + promptIds.length + i)) st.reset(promptIds.concat(steps.map((x) => x.id)));
if (id === 0) { endStep = { ...s, id: 0, text: "", prob: cand.p, forced: true }; finish(true); return; }
st.push(id);
addStep({ id, text: st.vocab[id], prob: cand.p, top: s.top, attn: s.attn, forced: true });
run();
};
$("f").onsubmit = (e) => { e.preventDefault(); tell(); };
$("stop").onclick = () => { if (running) finish(false); };
async function boot() {
const inline = $("model-b64");
if (inline) { $("lt").textContent = "Unpacking"; await new Promise((r) => setTimeout(r, 30)); return Storyteller.fromBase64(inline.textContent); }
let err;
for (const url of MODEL_URLS) {
try {
return await Storyteller.load(url, (got, total) => {
$("lf").style.width = total ? (100 * got / total).toFixed(0) + "%" : Math.min(95, got / 5e4).toFixed(0) + "%";
$("lt").textContent = `${(got / 1e6).toFixed(1)} MB${total ? " of " + (total / 1e6).toFixed(1) + " MB" : ""}`;
});
} catch (e) { err = e; }
}
throw err;
}
boot().then((m) => {
st = m;
const mb = (st.bytes / 1e6).toFixed(1) + " MB", inf = st.info || {};
$("sz").textContent = mb;
$("about").textContent = `About this model: ${(st.params / 1e6).toFixed(1)} million parameters in ${st.cfg.layers} layers, packed into one ${mb} file. It was trained from scratch${inf.train_minutes ? ` in ${Math.round(inf.train_minutes / 6) / 10} hours on an ordinary 4-core CPU` : ""} on the TinyStories dataset by Ronen Eldan and Yuanzhi Li, so it only knows the little world of those stories. Every word is worked out on your device, and nothing you type leaves this page.`;
$("loading").hidden = true; $("go").disabled = false;
tell();
}).catch((err) => { $("lt").textContent = "Could not load the model. " + (err && err.message ? err.message : ""); });
}
</script>
|