import { SparseResidualModel, planarSpeeds, unpackState } from './model.js'; import { REST_SPEED, RULE_DESCRIPTIONS, Scoreboard, evaluateRules } from './battery.js'; import { OBJECT_RADIUS, PUSHER_RADIUS, PlanarPushEnv, changedMask } from './planar.js'; const WORLD_BOUND = 0.28; const BASE_STEP_MS = 60; const MOTION_THRESHOLD = 0.02; const HF_BASE = 'https://huggingface.co/datasets/ParamThakkar123/sparse_world_models/resolve/main'; const TASKS = { sandbox: { title: 'Sandbox: you drive, the model predicts', copy: 'Live planar physics, running in this tab. Each frame the model outputs a gate ' + 'per object and a delta; the dashed outline is where it thinks each object will be. ' + 'Switch to mouse or keys and push objects yourself. The ground truth is created by you, ' + 'so nothing here is a recording.', hint: 'Mouse: pusher follows cursor. Keys: arrows or WASD. Auto: scripted push to goal.', }, replay: { title: 'Four engines: MuJoCo, Box2D, Chipmunk2D, ours', copy: 'MuJoCo, Box2D and Chipmunk cannot run in a browser, so these are recorded episodes ' + 'from the paper datasets, but the model is predicting on each frame live, and the ' + 'labels are the real ones. The shortcut existence condition holds on all four ' + 'engines: P(change | already moving) exceeds P(change | at rest) by 36 to 84x.', hint: 'Watch already_moving climb on billiards, where objects roll for a long time after contact.', }, transfer: { title: 'Count transfer: one checkpoint, any number of objects', copy: 'The same weights, trained on three object scenes, driving scenes with up to twelve. ' + 'The contact featurisation is fixed width, so nothing has to be retrained. Watch the ' + 'objects the gate leaves off: they are copied forward exactly, which is the one ' + 'architectural claim that survived proper baselines.', hint: 'Turn the count up. The trivial rules degrade too, but they degrade more slowly.', }, planning: { title: 'Planning: the model as a forward simulator', copy: 'Sampling based MPC (CEM), replanning every step, using the model to imagine each ' + 'candidate action sequence. The planner is sound: with the true simulator in place of ' + 'the model it succeeds every time. Anything it fails to do here is model quality.', hint: 'In the paper this reaches 0.25 success against a dense monolith at 0.00, and a ' + 'published probabilistic ensemble (PETS) beats it at 0.35.', }, }; const state = { models: null, model: null, modelName: null, episodes: null, task: 'sandbox', running: true, drive: 'auto', radius: 0.07, numObjects: 3, env: null, replayName: null, replayIndex: 0, scoreboard: new Scoreboard(), frames: 0, pointer: null, lastPrediction: null, lastTruth: null, seenFrames: 0, planSuccess: 0, planAttempts: 0, speed: 1, showTrails: false, showProbs: true, showGrid: true, showVel: false, sortBy: 'f1', trails: [], keys: {}, inspector: null, }; const canvas = document.getElementById('scene'); const context = canvas.getContext('2d'); const statusEl = document.getElementById('status'); const scoresBody = document.querySelector('#scores tbody'); const framesEl = document.getElementById('frames'); const taskCopy = document.getElementById('task-copy'); const hintEl = document.getElementById('hint'); function toCanvas(x, y) { const scale = canvas.width / (2 * WORLD_BOUND); return [(x + WORLD_BOUND) * scale, (WORLD_BOUND - y) * scale]; } function styleValue(name) { return getComputedStyle(document.body).getPropertyValue(name).trim(); } function worldFromPointer(event) { const rect = canvas.getBoundingClientRect(); const x = ((event.clientX - rect.left) / rect.width) * 2 * WORLD_BOUND - WORLD_BOUND; const y = WORLD_BOUND - ((event.clientY - rect.top) / rect.height) * 2 * WORLD_BOUND; return [x, y]; } function drawGrid(scale) { if (!state.showGrid) return; context.strokeStyle = 'color-mix(in srgb, var(--line) 55%, transparent)'; context.lineWidth = 1; context.setLineDash([2, 6]); for (let g = -0.2; g <= 0.2; g += 0.1) { const [x0, y0] = toCanvas(g, -0.26); const [x1, y1] = toCanvas(g, 0.26); context.beginPath(); context.moveTo(x0, y0); context.lineTo(x1, y1); context.stroke(); const [hx0, hy0] = toCanvas(-0.26, g); const [hx1, hy1] = toCanvas(0.26, g); context.beginPath(); context.moveTo(hx0, hy0); context.lineTo(hx1, hy1); context.stroke(); } context.setLineDash([]); } function drawScene({ poses, pusher, goal, gates, probs, predicted, truth, velocities }) { const scale = canvas.width / (2 * WORLD_BOUND); const dpr = window.devicePixelRatio || 1; context.setTransform(dpr, 0, 0, dpr, 0, 0); context.clearRect(0, 0, canvas.width / dpr, canvas.height / dpr); const [tableX, tableY] = toCanvas(-0.26, 0.26); context.fillStyle = styleValue('--bg'); context.fillRect(0, 0, canvas.width, canvas.height); drawGrid(scale); context.strokeStyle = styleValue('--line'); context.lineWidth = 2; context.strokeRect(tableX / dpr, tableY / dpr, 0.52 * scale / dpr, 0.52 * scale / dpr); if (goal) { const [gx, gy] = toCanvas(goal[0], goal[1]); context.beginPath(); context.arc(gx / dpr, gy / dpr, 0.03 * scale / dpr, 0, Math.PI * 2); context.strokeStyle = styleValue('--goal'); context.setLineDash([4, 4]); context.lineWidth = 2; context.stroke(); context.setLineDash([]); } if (state.showTrails && state.trails.length) { state.trails.forEach((trail, idx) => { if (trail.length < 2) return; context.strokeStyle = styleValue('--ghost'); context.lineWidth = 1.5; context.globalAlpha = 0.35; context.beginPath(); trail.forEach((p, i) => { const [cx, cy] = toCanvas(p[0], p[1]); if (i === 0) context.moveTo(cx / dpr, cy / dpr); else context.lineTo(cx / dpr, cy / dpr); }); context.stroke(); context.globalAlpha = 1; }); } if (predicted) { context.strokeStyle = styleValue('--ghost'); context.setLineDash([5, 4]); context.lineWidth = 2; predicted.forEach((pose) => drawBox(pose, scale, null, dpr)); context.setLineDash([]); } poses.forEach((pose, index) => { const gateOn = gates && gates[index]; const changed = truth && truth[index]; context.lineWidth = 3; context.fillStyle = gateOn ? `color-mix(in srgb, ${styleValue('--gate')} 55%, transparent)` : styleValue('--surface'); context.strokeStyle = changed ? styleValue('--truth') : styleValue('--line'); drawBox(pose, scale, true, dpr); if (state.showProbs && probs) { const [px, py] = toCanvas(pose[0], pose[1]); context.fillStyle = styleValue('--ink-soft'); context.font = '11px ui-monospace, monospace'; context.textAlign = 'center'; context.fillText(probs[index].toFixed(2), px / dpr, py / dpr - 0.035 * scale / dpr); } if (state.showVel && velocities) { const v = velocities[index]; if (v) { const [px, py] = toCanvas(pose[0], pose[1]); const vx = v[3] || 0; const vy = v[4] || 0; const mag = Math.hypot(vx, vy); if (mag > 1e-4) { context.strokeStyle = styleValue('--gate'); context.lineWidth = 1.5; context.beginPath(); context.moveTo(px / dpr, py / dpr); context.lineTo((px + vx * 2 * scale) / dpr, (py - vy * 2 * scale) / dpr); context.stroke(); } } } if (state.inspector && state.inspector.index === index) { const [px, py] = toCanvas(pose[0], pose[1]); context.strokeStyle = styleValue('--accent'); context.lineWidth = 2; context.setLineDash([3, 3]); context.beginPath(); context.arc(px / dpr, py / dpr, OBJECT_RADIUS * scale / dpr + 4, 0, Math.PI * 2); context.stroke(); context.setLineDash([]); } }); const [px, py] = toCanvas(pusher[0], pusher[1]); context.beginPath(); context.arc(px / dpr, py / dpr, PUSHER_RADIUS * scale / dpr, 0, Math.PI * 2); context.fillStyle = styleValue('--ink'); context.fill(); if (state.drive === 'keys') { context.fillStyle = styleValue('--accent'); context.font = '10px ui-sans-serif, sans-serif'; context.textAlign = 'center'; context.fillText('KEYS', px / dpr, py / dpr - 18); } } function drawBox(pose, scale, filled, dpr) { const [x, y] = toCanvas(pose[0], pose[1]); const half = OBJECT_RADIUS * scale / dpr; context.save(); context.translate(x / dpr, y / dpr); context.rotate(-pose[2]); context.beginPath(); context.rect(-half, -half, 2 * half, 2 * half); if (filled) context.fill(); context.stroke(); context.restore(); } function passesMotionFilter(before, after) { return before.some((pose, i) => Math.hypot(after[i][0] - pose[0], after[i][1] - pose[1]) > MOTION_THRESHOLD); } function scoreFrame(stateVector, action, numObjects, truthMask) { const speeds = planarSpeeds(stateVector, numObjects); const atRest = speeds.map((speed) => speed <= REST_SPEED); const { rules } = evaluateRules(stateVector, action, numObjects, state.radius, state.model.constants); for (const [name, prediction] of Object.entries(rules)) { state.scoreboard.update(name, prediction, truthMask, atRest); } const { gates } = state.lastPrediction; state.scoreboard.update('model', gates, truthMask, atRest); state.frames += 1; } function renderScores() { let rows = state.scoreboard.rows(); if (state.sortBy === 'onset') rows = [...rows].sort((a, b) => b.onsetF1 - a.onsetF1 || b.f1 - a.f1); scoresBody.innerHTML = ''; for (const row of rows) { const tr = document.createElement('tr'); if (row.isModel) tr.className = 'model'; else if (row.parameters === 0) tr.className = 'zero-param'; const label = row.isModel ? 'the trained model' : row.name; tr.innerHTML = `
${info.copy}
`; hintEl.textContent = info.hint; document.getElementById('count-row').hidden = task !== 'transfer'; document.getElementById('episode-row').hidden = task !== 'replay'; document.getElementById('drive-row').hidden = task === 'replay' || task === 'planning'; document.getElementById('keys-hint').hidden = state.drive !== 'keys'; state.planSuccess = 0; state.planAttempts = 0; selectModel(task === 'replay' ? 'tabletop' : 'planar'); newScene(); resetScores(); pushUrlState(); } function pushUrlState() { const url = new URL(window.location); url.searchParams.set('task', state.task); url.searchParams.set('count', String(state.numObjects)); url.searchParams.set('radius', String(state.radius)); url.searchParams.set('speed', String(state.speed)); url.searchParams.set('drive', state.drive); history.replaceState(null, '', url); } function applyUrlState() { const p = new URLSearchParams(window.location.search); if (p.get('task') && TASKS[p.get('task')]) state.task = p.get('task'); if (p.get('count')) state.numObjects = Math.max(2, Math.min(12, Number(p.get('count')) || 3)); if (p.get('radius')) state.radius = Math.max(0.02, Math.min(0.22, Number(p.get('radius')) || 0.07)); if (p.get('speed')) state.speed = Math.max(0.25, Math.min(3, Number(p.get('speed')) || 1)); if (p.get('drive') && ['auto', 'mouse', 'keys'].includes(p.get('drive'))) state.drive = p.get('drive'); } async function fetchWithProgress(url, label) { const res = await fetch(url); if (!res.ok) throw new Error(`${label} not found at ${url}`); return res.json(); } async function loadBundleWithFallback() { const params = new URLSearchParams(window.location.search); const override = params.get('modelUrl'); const candidates = []; if (override) candidates.push(override); candidates.push('assets/model.json'); candidates.push(`${HF_BASE}/docs/assets/model.json`); let lastError = null; for (const url of candidates) { try { const bundle = await SparseResidualModel.loadBundle(url); return bundle; } catch (e) { lastError = e; } } throw lastError || new Error('could not load model bundle'); } function resizeCanvas() { const dpr = window.devicePixelRatio || 1; const rect = canvas.getBoundingClientRect(); const size = Math.round(rect.width * dpr); if (canvas.width !== size) { canvas.width = size; canvas.height = size; } } async function main() { resizeCanvas(); window.addEventListener('resize', resizeCanvas); applyUrlState(); const progress = document.getElementById('progress'); const progressBar = document.getElementById('progress-bar'); if (progress) progress.hidden = false; if (progressBar) progressBar.style.width = '30%'; try { const bundle = await loadBundleWithFallback(); state.models = bundle.models; state.modelDefault = bundle.default; if (progressBar) progressBar.style.width = '60%'; let episodes = null; try { episodes = await fetchWithProgress('assets/episodes.json', 'episodes'); } catch { episodes = await fetchWithProgress(`${HF_BASE}/docs/assets/episodes.json`, 'episodes'); } state.episodes = episodes; if (progressBar) progressBar.style.width = '100%'; setTimeout(() => { if (progress) progress.hidden = true; }, 400); } catch (error) { statusEl.textContent = 'Could not load the model. This page uses ES modules and fetch, so it needs to be served over http. Open it from GitHub Pages, or run `python -m http.server` in docs/.'; if (progress) progress.hidden = true; return; } selectModel('planar'); const saved = JSON.parse(localStorage.getItem('demoPrefs') || '{}'); if (saved.showTrails) state.showTrails = saved.showTrails; if (saved.showGrid === false) state.showGrid = false; if (saved.showVel) state.showVel = saved.showVel; if (saved.showProbs === false) state.showProbs = false; document.getElementById('param-count').textContent = state.model.weights.num_parameters.toLocaleString(); const episodeSelect = document.getElementById('episode'); for (const [name, episode] of Object.entries(state.episodes)) { const option = document.createElement('option'); option.value = name; option.textContent = `${name}: ${episode.engine} (${episode.num_objects} objects)`; episodeSelect.appendChild(option); } state.replayName = Object.keys(state.episodes)[0]; episodeSelect.value = state.replayName; episodeSelect.addEventListener('change', () => { state.replayName = episodeSelect.value; state.replayIndex = 0; selectModel('tabletop'); renderDomainNotice(); resetScores(); }); document.querySelectorAll('.tasks button').forEach((button) => { button.addEventListener('click', () => selectTask(button.dataset.task)); }); const play = document.getElementById('play'); play.addEventListener('click', () => { state.running = !state.running; syncPlayButton(); }); document.getElementById('reset').addEventListener('click', () => { newScene(); resetScores(); }); const doStep = () => { const was = state.running; state.running = true; if (state.task === 'replay') stepReplay(); else stepLive(); renderScores(); updateStatus(); updateInspector(); state.running = was; syncPlayButton(); }; document.getElementById('step').addEventListener('click', doStep); document.getElementById('btn-step').addEventListener('click', doStep); document.getElementById('share').addEventListener('click', async () => { pushUrlState(); const url = window.location.href; try { await navigator.clipboard.writeText(url); statusEl.textContent = 'Link copied to clipboard.'; setTimeout(updateStatus, 1500); } catch { statusEl.textContent = url; } }); const radius = document.getElementById('radius'); const radiusOut = document.getElementById('radius-out'); radius.value = state.radius; radiusOut.textContent = `${state.radius.toFixed(3)} m`; radius.addEventListener('input', () => { state.radius = Number(radius.value); radiusOut.textContent = `${state.radius.toFixed(3)} m`; resetScores(); pushUrlState(); }); const count = document.getElementById('count'); const countOut = document.getElementById('count-out'); count.value = state.numObjects; countOut.textContent = count.value; count.addEventListener('input', () => { state.numObjects = Number(count.value); countOut.textContent = count.value; newScene(); resetScores(); }); const speed = document.getElementById('speed'); const speedOut = document.getElementById('speed-out'); speed.value = state.speed; speedOut.textContent = `${state.speed}x`; speed.addEventListener('input', () => { state.speed = Number(speed.value); speedOut.textContent = `${state.speed}x`; pushUrlState(); }); const checkTrails = document.getElementById('check-trails'); const btnTrails = document.getElementById('btn-trails'); checkTrails.checked = state.showTrails; if (btnTrails) btnTrails.setAttribute('aria-pressed', String(state.showTrails)); const toggleTrails = () => { state.showTrails = !state.showTrails; checkTrails.checked = state.showTrails; if (btnTrails) btnTrails.setAttribute('aria-pressed', String(state.showTrails)); if (!state.showTrails) state.trails = []; persistPrefs(); }; checkTrails.addEventListener('change', toggleTrails); if (btnTrails) btnTrails.addEventListener('click', toggleTrails); const checkVel = document.getElementById('check-vel'); checkVel.checked = state.showVel; checkVel.addEventListener('change', () => { state.showVel = checkVel.checked; persistPrefs(); }); const checkGrid = document.getElementById('check-grid'); checkGrid.checked = state.showGrid; checkGrid.addEventListener('change', () => { state.showGrid = checkGrid.checked; persistPrefs(); }); const btnProbs = document.getElementById('btn-probs'); const syncProbs = () => { if (btnProbs) btnProbs.setAttribute('aria-pressed', String(state.showProbs)); }; syncProbs(); if (btnProbs) btnProbs.addEventListener('click', () => { state.showProbs = !state.showProbs; syncProbs(); persistPrefs(); }); document.getElementById('btn-screenshot').addEventListener('click', () => { const a = document.createElement('a'); a.download = `demo-${state.task}-${Date.now()}.png`; a.href = canvas.toDataURL('image/png'); a.click(); }); document.getElementById('sort-f1').addEventListener('click', () => { state.sortBy = 'f1'; renderScores(); }); document.getElementById('sort-onset').addEventListener('click', () => { state.sortBy = 'onset'; renderScores(); }); document.getElementById('copy-scores').addEventListener('click', async () => { const rows = state.scoreboard.rows(); const csv = ['rule,params,f1,onsetF1'].concat(rows.map(r => `${r.name},${r.isModel ? state.model.weights.num_parameters : r.parameters},${r.f1.toFixed(3)},${r.support ? r.onsetF1.toFixed(3) : ''}`)).join('\n'); try { await navigator.clipboard.writeText(csv); statusEl.textContent = 'Scores copied as CSV.'; setTimeout(updateStatus, 1500); } catch { statusEl.textContent = csv.slice(0, 80); } }); document.querySelectorAll('input[name="drive"]').forEach((input) => { if (input.value === state.drive) input.checked = true; input.addEventListener('change', () => { state.drive = input.value; document.getElementById('keys-hint').hidden = state.drive !== 'keys'; pushUrlState(); }); }); document.getElementById('keys-hint').hidden = state.drive !== 'keys'; function persistPrefs() { localStorage.setItem('demoPrefs', JSON.stringify({ showTrails: state.showTrails, showVel: state.showVel, showGrid: state.showGrid, showProbs: state.showProbs })); } canvas.addEventListener('pointermove', (event) => { state.pointer = worldFromPointer(event); const env = state.env; const poses = env ? env.observation().poses : (state.episodes && state.episodes[state.replayName] ? unpackState(state.episodes[state.replayName].state[state.replayIndex] || state.episodes[state.replayName].state[0], state.episodes[state.replayName].num_objects).poses : null); const pusher = env ? env.pusher : (state.episodes && state.episodes[state.replayName] ? unpackState(state.episodes[state.replayName].state[state.replayIndex] || state.episodes[state.replayName].state[0], state.episodes[state.replayName].num_objects).pusher : null); if (!poses || !pusher) return; let best = null; let bestDist = Infinity; poses.forEach((pose, i) => { const d = Math.hypot(state.pointer[0] - pose[0], state.pointer[1] - pose[1]); if (d < bestDist && d < 0.06) { bestDist = d; best = i; } }); if (best !== null) { const speedVal = state.env ? Math.hypot(state.env.objectVel[best][0], state.env.objectVel[best][1]) : 0; const distToPusher = Math.hypot(poses[best][0] - pusher[0], poses[best][1] - pusher[1]); state.inspector = { index: best, distance: distToPusher, speed: speedVal }; } else state.inspector = null; }); canvas.addEventListener('pointerleave', () => { state.pointer = null; state.inspector = null; const el = document.getElementById('inspector'); if (el) el.hidden = true; }); canvas.addEventListener('pointerdown', (e) => { if (state.drive === 'mouse') state.pointer = worldFromPointer(e); }); window.addEventListener('keydown', (e) => { state.keys[e.key] = true; if (e.code === 'Space') { e.preventDefault(); state.running = !state.running; syncPlayButton(); } else if (e.key.toLowerCase() === 'r') { newScene(); resetScores(); } else if (e.key === '.') { const was = state.running; state.running = true; if (state.task === 'replay') stepReplay(); else stepLive(); renderScores(); updateStatus(); state.running = was; syncPlayButton(); } else if (e.key.toLowerCase() === 't') { state.showTrails = !state.showTrails; document.getElementById('check-trails').checked = state.showTrails; const b = document.getElementById('btn-trails'); if (b) b.setAttribute('aria-pressed', String(state.showTrails)); if (!state.showTrails) state.trails = []; } else if (e.key.toLowerCase() === 'p') { state.showProbs = !state.showProbs; const b = document.getElementById('btn-probs'); if (b) b.setAttribute('aria-pressed', String(state.showProbs)); } else if (e.key.toLowerCase() === 'g') { state.showGrid = !state.showGrid; document.getElementById('check-grid').checked = state.showGrid; } else if (['1','2','3','4'].includes(e.key)) { const tasks = ['sandbox','replay','transfer','planning']; selectTask(tasks[Number(e.key)-1]); } }); window.addEventListener('keyup', (e) => { state.keys[e.key] = false; }); document.getElementById('theme-toggle').addEventListener('click', () => { const cur = document.documentElement.getAttribute('data-theme'); const next = cur === 'light' ? 'dark' : cur === 'dark' ? 'light' : (matchMedia('(prefers-color-scheme: dark)').matches ? 'light' : 'dark'); if (next === 'light') document.documentElement.setAttribute('data-theme', 'light'); else if (next === 'dark') document.documentElement.setAttribute('data-theme', 'dark'); else document.documentElement.removeAttribute('data-theme'); }); selectTask(state.task); syncPlayButton(); requestAnimationFrame(frame); } main();