Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions packages/demo-car-circuit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,24 @@ Browser CPU V3 verification: a newly trained Double DQN seed 11 checkpoint (`dri
The training interface guides users through Train → Test → Save → Race with one primary action at each step. Technical configuration and individual evaluation results stay in expandable details. The 3D view is explicitly labelled as a session snapshot, not continuous racing. Saving carries the exact checkpoint into the garage; switching to player mode preserves that opponent.

Interactive races now use **ghost mode** (`circuit-race-v2-ghost-v1`): cars cannot push or slow each other; rail collisions, off-road penalties and rescue still apply. This includes AI races and player opponents. Existing checkpoints can race in this mode, while their recorded training/evaluation scores remain explicitly labelled as contact-mode results. The default training/evaluation simulation keeps its original contact rules so those protocols are not silently changed.


## RL 3: same frozen policy, training circuit vs unseen circuit

`generalisation.html` (on the website: `/demos/car-circuit/generalisation.html`, FR/EN) compares one frozen DQN policy per seed on the two circuits of `circuit-evaluation-v1` (`src/evaluation.ts`, unchanged): training circuit 10/4/2, unseen test circuit 6/6/2, starts 0/16/32, 1,500 steps, 3 laps.

The budget, network, hyperparameters and seeds (11, 29, 47) are declared in `rl3-generalisation-experiment.json`, committed before the runs. Training uses the training circuit only; the evaluated policy is the network at the end of the budget, with no checkpoint selection. Evaluation runs in a new process on the saved weights; their sha256 is checked before and after, and against the training process.

Raw logs live in `src/public/rl3-generalisation/` (not under `evidence/`): `seed-<n>/train-episodes.jsonl` (one line per training episode), `seed-<n>/eval-episodes.jsonl` (one line per evaluation episode: seed, policy, circuit, start, endReason, laps, transitions), the raw `evaluateCircuit` reports, per-step car positions (`trajectories.json`), both checkpoints, `summary.json`, and `manifest.json` with the sha256 of every file. The page recomputes every number from the JSONL logs and shows no comparison if a log is missing or the protocol or policy differs.

Reproduce from the repository root (about 35 minutes with three seeds in parallel on 8 CPU cores, tfjs CPU backend):

```
pnpm install --frozen-lockfile
pnpm --filter demo-car-circuit rl3:train --seed 11 # likewise 29 and 47
pnpm --filter demo-car-circuit rl3:eval
pnpm --filter demo-car-circuit rl3:manifest
pnpm exec vitest run packages/demo-car-circuit/test/rl3-generalisation.test.ts
```

Native and browser CPU backends may produce different trained weights; the published numbers are those of the committed logs.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 changes: 7 additions & 2 deletions packages/demo-car-circuit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@
"dev": "vite",
"build": "vite build",
"test": "vitest run",
"e2e:human-race": "node e2e/human-race.mjs"
"e2e:human-race": "node e2e/human-race.mjs",
"rl3:train": "tsx --tsconfig ../../scripts/tsconfig.racing.json scripts/rl3-bench.mts train",
"rl3:eval": "tsx --tsconfig ../../scripts/tsconfig.racing.json scripts/rl3-bench.mts eval",
"rl3:manifest": "tsx --tsconfig ../../scripts/tsconfig.racing.json scripts/rl3-bench.mts manifest",
"typecheck:rl3": "tsc -p tsconfig.rl3.json"
},
"dependencies": {
"@ignitionai/backend-tfjs": "workspace:*",
Expand All @@ -29,6 +33,7 @@
"typescript": "~5.7.2",
"vite": "^6.3.1",
"playwright": "^1.56.1",
"vitest": "^3.1.1"
"vitest": "^3.1.1",
"tsx": "^4.19.3"
}
}
62 changes: 62 additions & 0 deletions packages/demo-car-circuit/rl3-generalisation-experiment.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{
"experiment": "rl3-generalisation",
"declaredBeforeExecution": true,
"declaredAt": "2026-11-30T09:04:15Z",
"note": "Budget, network, hyperparameters and seeds are frozen before the training command that produces src/public/rl3-generalisation/. All three seeds use exactly the same values; only the seed changes. Results must come from the raw JSONL logs; numbers are not edited after the run.",
"gitBase": "cb9e04c",
"protocolId": "circuit-evaluation-v1",
"protocolRule": "circuit-evaluation-v1 (src/evaluation.ts) is used unchanged: training circuit 10/4/2, test circuit 6/6/2, starts 0/16/32, 1500 steps, 3 laps, greedy actions only. The test circuit is never built during training.",
"seeds": [
11,
29,
47
],
"algorithm": "dqn",
"algorithmChoice": "DQN (DQNAgent, doubleQ false), the baseline of RL 2: seeded weights, seeded exploration and replay sampling, discrete actions (CircuitEnv has 3), and the frozen-weights checks of RL 2 (save, reload in a new process, compare). The RL 1 PPO set-up was written for the 1-D task and has no per-seed replay determinism check in this package.",
"training": {
"circuit": "training",
"startWaypoints": "uniform",
"startSeedRule": "new start waypoint at every training episode, uniform over 0..63, drawn from mulberry32(seed * 7919 + 13)",
"maxStepsPerEpisode": 1500,
"targetLaps": 3
},
"budget": {
"envStepsPerRun": 100000,
"unit": "environment steps through IgnitionEnv.step() (one train() call per step once the replay holds a batch). An episode still running when the budget ends is not logged as an episode; its length is in run.json partialEpisodeAtBudget.",
"choice": "Measured before declaring, on scratch seeds outside the declared ones (seed 1 and seed 2, outputs discarded): about 6 ms per env step on this machine (tfjs cpu backend, node v22). A 60000-step probe on seed 1 completed its first 3-lap training episode near step 16700 and 59 of its last 100 training episodes; only training-circuit episodes were looked at, the probe was never evaluated on the test circuit. 100000 steps is about 10 minutes per seed, 3 seeds run in parallel.",
"checkpointSelection": "none: the evaluated policy is the network after exactly envStepsPerRun steps"
},
"agent": {
"class": "DQNAgent (packages/backend-tfjs/src/agents/dqn.ts)",
"inputSize": 5,
"actionSize": 3,
"hiddenLayers": [
64,
64
],
"lr": 0.0005,
"gamma": 0.99,
"epsilon": 1.0,
"epsilonDecay": 0.99992,
"minEpsilon": 0.05,
"batchSize": 32,
"memorySize": 50000,
"targetUpdateFrequency": 1000,
"backend": "cpu",
"doubleQ": false
},
"agentNotes": {
"epsilonSchedule": "epsilon multiplied by epsilonDecay after each train() call: 0.05 is reached after about 37400 train calls (37 % of the budget)",
"targetUpdateUnit": "train() calls (hard copy of the online weights)",
"optimizer": "adam, mean squared error, 1 epoch per train() call, shuffle off (seeded)"
},
"evaluation": {
"policies": [
"trained",
"untrained"
],
"untrainedReference": "the same seeded network before any training step, evaluated with the same protocol, as a reference only",
"process": "new process: weights reloaded from trained/ and untrained/, sha256 of the weights compared before and after evaluation and with the training process",
"trajectories": "x, y of the car at every step, recorded by a second deterministic drive of the same frozen policy and checked against the protocol episode (endReason, transitions, laps)"
}
}
105 changes: 105 additions & 0 deletions packages/demo-car-circuit/scripts/capture-rl3-demo.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/**
* Playwright captures and DOM checks of the RL 3 page (training circuit vs unseen circuit).
^ * Usage: [CHROMIUM_PATH=/path/to/chrome] RL3_URL=http://127.0.0.1:4175/generalisation.html node scripts/capture-rl3-demo.mjs <outDir>
* Optional RL3_ERROR_CASES='[{"name":"missing","manifest":"/rl3-test/missing/manifest.json"}]'
* Writes PNG captures and checks.json into <outDir> (default .scratch/rl3-captures).
*/
import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';

const here = dirname(fileURLToPath(import.meta.url));
const output = process.argv[2] || join(here, '../../../.scratch/rl3-captures');
mkdirSync(output, { recursive: true });
const url = process.env.RL3_URL || 'http://127.0.0.1:4175/generalisation.html';
const errorCases = JSON.parse(process.env.RL3_ERROR_CASES || '[]');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROMIUM_PATH ? { executablePath: process.env.CHROMIUM_PATH } : {}) });
const report = { url, views: [], errorCases: [], pageErrors: [], consoleErrors: [] };

async function measure(page) {
return page.evaluate(() => {
const css = (el, prop) => (el ? getComputedStyle(el)[prop] : null);
const rect = (sel) => {
const el = document.querySelector(sel);
if (!el) return null;
const r = el.getBoundingClientRect();
return { x: Math.round(r.x), y: Math.round(r.y), width: Math.round(r.width), height: Math.round(r.height) };
};
const buttons = [...document.querySelectorAll('button')].map((b) => b.getBoundingClientRect().height);
const trajectories = [...document.querySelectorAll('[data-testid^="rl3-traj-"]')].map((p) => ({
id: p.getAttribute('data-testid'), stroke: p.getAttribute('stroke'), opacity: p.getAttribute('stroke-opacity'),
dash: p.getAttribute('stroke-dasharray'), width: p.getAttribute('stroke-width'),
}));
return {
innerWidth: window.innerWidth,
scrollWidth: document.documentElement.scrollWidth,
bg: css(document.querySelector('[data-testid="rl3-page"]'), 'backgroundColor'),
h1: css(document.querySelector('h1'), 'fontSize'),
minButtonHeight: buttons.length ? Math.min(...buttons) : null,
svg: { training: rect('[data-testid="rl3-svg-training"]'), test: rect('[data-testid="rl3-svg-test"]') },
viewBoxes: [...document.querySelectorAll('svg[data-testid^="rl3-svg-"]')].map((s) => s.getAttribute('viewBox')),
trajectories,
ends: [...document.querySelectorAll('[data-testid^="rl3-end-"]')].map((e) => e.getAttribute('data-end')),
cells: document.querySelectorAll('[data-testid^="rl3-cell-"]').length,
hasTable: !!document.querySelector('[data-testid="rl3-table"] table'),
cards: document.querySelectorAll('[data-testid^="rl3-card-"]').length,
status: ['training', 'test'].map((c) => document.querySelector(`[data-testid="rl3-status-${c}"]`)?.innerText ?? null),
reading: document.querySelector('[data-testid="rl3-reading"]')?.innerText ?? null,
alerts: [...document.querySelectorAll('[role="alert"]')].map((a) => a.getAttribute('data-testid')),
rawKeysVisible: /\brl3\.[a-z]/.test(document.body.innerText),
forbidden: /généralise|generali[sz]es/i.test(document.body.innerText),
};
});
}

async function open(name, width, lang, target) {
const page = await browser.newPage({ viewport: { width, height: 900 } });
page.on('pageerror', (e) => report.pageErrors.push(`${name}: ${e.message}`));
page.on('console', (m) => { if (m.type() === 'error') report.consoleErrors.push(`${name}: ${m.text()}`); });
await page.addInitScript((l) => localStorage.setItem('lang', l), lang);
await page.goto(target, { waitUntil: 'networkidle' });
await page.waitForSelector('[data-testid="rl3-matrix"], [role="alert"]', { timeout: 60000 });
await page.waitForTimeout(500);
return page;
}

for (const [width, tag] of [[1280, 'desktop1280'], [390, 'mobile390']]) {
for (const lang of ['fr', 'en']) {
const name = `${tag}-${lang}`;
const page = await open(name, width, lang, url);
const before = await measure(page);
await page.screenshot({ path: join(output, `rl3-${name}.png`), fullPage: true });
// Lockstep play: both cars advance on the same step index until the longer episode ends.
let afterPlay = null;
const play = page.locator('[data-testid="rl3-play"]');
if (await play.count() && await play.isEnabled()) {
await play.click();
await page.waitForTimeout(400);
const mid = await measure(page);
await page.screenshot({ path: join(output, `rl3-${name}-playing.png`), fullPage: false });
await page.waitForFunction(() => !document.querySelector('[data-testid^="rl3-car-"]'), null, { timeout: 30000 });
afterPlay = { mid: mid.status, end: (await measure(page)).status };
}
report.views.push({ name, ...before, afterPlay });
await page.close();
}
}

for (const c of errorCases) {
const page = await open(c.name, 1280, 'fr', `${url}?manifest=${encodeURIComponent(c.manifest)}`);
await page.screenshot({ path: join(output, `rl3-error-${c.name}.png`), fullPage: true });
const m = await measure(page);
report.errorCases.push({ name: c.name, alerts: m.alerts, cells: m.cells, hasSvg: !!m.svg.training, alertText: await page.locator('[role="alert"]').allInnerTexts() });
await page.close();
}

await browser.close();
writeFileSync(join(output, 'checks.json'), JSON.stringify(report, null, 2));
console.log(JSON.stringify({
output,
views: report.views.map((v) => ({ name: v.name, scrollWidth: v.scrollWidth, innerWidth: v.innerWidth, minButtonHeight: v.minButtonHeight, svg: v.svg, viewBoxes: v.viewBoxes, cells: v.cells, hasTable: v.hasTable, cards: v.cards, rawKeysVisible: v.rawKeysVisible, forbidden: v.forbidden, afterPlay: v.afterPlay })),
errorCases: report.errorCases.map((c) => ({ name: c.name, alerts: c.alerts, cells: c.cells, hasSvg: c.hasSvg })),
pageErrors: report.pageErrors,
consoleErrors: report.consoleErrors,
}, null, 2));
Loading
Loading