diff --git a/packages/demo-car-circuit/README.md b/packages/demo-car-circuit/README.md index 94b7cab..0ef8b6e 100644 --- a/packages/demo-car-circuit/README.md +++ b/packages/demo-car-circuit/README.md @@ -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-/train-episodes.jsonl` (one line per training episode), `seed-/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. diff --git a/packages/demo-car-circuit/art/rl3/rl3-desktop1280-en.png b/packages/demo-car-circuit/art/rl3/rl3-desktop1280-en.png new file mode 100644 index 0000000..f3932f5 Binary files /dev/null and b/packages/demo-car-circuit/art/rl3/rl3-desktop1280-en.png differ diff --git a/packages/demo-car-circuit/art/rl3/rl3-desktop1280-fr.png b/packages/demo-car-circuit/art/rl3/rl3-desktop1280-fr.png new file mode 100644 index 0000000..8b7fdbf Binary files /dev/null and b/packages/demo-car-circuit/art/rl3/rl3-desktop1280-fr.png differ diff --git a/packages/demo-car-circuit/art/rl3/rl3-mobile390-en.png b/packages/demo-car-circuit/art/rl3/rl3-mobile390-en.png new file mode 100644 index 0000000..0123501 Binary files /dev/null and b/packages/demo-car-circuit/art/rl3/rl3-mobile390-en.png differ diff --git a/packages/demo-car-circuit/art/rl3/rl3-mobile390-fr.png b/packages/demo-car-circuit/art/rl3/rl3-mobile390-fr.png new file mode 100644 index 0000000..de6ff2d Binary files /dev/null and b/packages/demo-car-circuit/art/rl3/rl3-mobile390-fr.png differ diff --git a/packages/demo-car-circuit/package.json b/packages/demo-car-circuit/package.json index 0185ce4..4fea47b 100644 --- a/packages/demo-car-circuit/package.json +++ b/packages/demo-car-circuit/package.json @@ -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:*", @@ -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" } } diff --git a/packages/demo-car-circuit/rl3-generalisation-experiment.json b/packages/demo-car-circuit/rl3-generalisation-experiment.json new file mode 100644 index 0000000..4288c88 --- /dev/null +++ b/packages/demo-car-circuit/rl3-generalisation-experiment.json @@ -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)" + } +} diff --git a/packages/demo-car-circuit/scripts/capture-rl3-demo.mjs b/packages/demo-car-circuit/scripts/capture-rl3-demo.mjs new file mode 100644 index 0000000..3dbaa54 --- /dev/null +++ b/packages/demo-car-circuit/scripts/capture-rl3-demo.mjs @@ -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 + * Optional RL3_ERROR_CASES='[{"name":"missing","manifest":"/rl3-test/missing/manifest.json"}]' + * Writes PNG captures and checks.json into (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)); diff --git a/packages/demo-car-circuit/scripts/rl3-bench.mts b/packages/demo-car-circuit/scripts/rl3-bench.mts new file mode 100644 index 0000000..d99e1ba --- /dev/null +++ b/packages/demo-car-circuit/scripts/rl3-bench.mts @@ -0,0 +1,288 @@ +/** + * RL 3 — generalisation bench: same frozen policy, training circuit vs unseen circuit. + * + * Reads the declared budget in packages/demo-car-circuit/rl3-generalisation-experiment.json + * (committed before any training run) and writes everything under + * packages/demo-car-circuit/src/public/rl3-generalisation/ (served by the page). + * + * pnpm --filter demo-car-circuit rl3:train [--seed 11] # DQN on the training circuit only + * pnpm --filter demo-car-circuit rl3:eval [--seed 11] # new process: frozen weights, circuit-evaluation-v1 + * pnpm --filter demo-car-circuit rl3:manifest # summary.json, experiment.json, manifest.json (sha256) + * + * Probe (not an artifact): rl3:train --seed 1 --steps 5000 --out /tmp/rl3-probe + * + * gitSha is `git rev-parse HEAD` at train time (same rule as RL 1 and RL 2). + */ +import { createHash } from 'node:crypto'; +import { execSync } from 'node:child_process'; +import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { dirname, join, relative } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseArgs } from 'node:util'; +import * as tf from '@tensorflow/tfjs'; +import { DQNAgent } from '@ignitionai/backend-tfjs'; +import { fileSystemModelProvider } from '../../backend-tfjs/scripts/fs-provider.mjs'; +import { CircuitEnv } from '../src/circuit-env'; +import { CIRCUIT_PROTOCOL, evaluateCircuit, type CircuitEvaluationReport } from '../src/evaluation'; +import { buildAgentConfig, runTraining, type Rl3Experiment } from '../src/generalisation/training'; +import { + parseEvalLog, RL3_CIRCUITS, RL3_POLICIES, summarizePolicy, summaryFile, + type EvalEpisodeRow, type Rl3Circuit, type Rl3Policy, +} from '../src/generalisation/results'; + +const here = dirname(fileURLToPath(import.meta.url)); +const pkgRoot = join(here, '..'); +const repoRoot = join(pkgRoot, '../..'); +const DECLARED = 'packages/demo-car-circuit/rl3-generalisation-experiment.json'; +const OUT_DIR = 'packages/demo-car-circuit/src/public/rl3-generalisation'; + +const { values, positionals } = parseArgs({ + allowPositionals: true, + options: { seed: { type: 'string' }, steps: { type: 'string' }, out: { type: 'string' } }, +}); +const command = positionals[0]; +// `pnpm run x -- --seed 11` would turn the options into positionals: refuse instead of running every seed. +if (positionals.length > 1) throw new Error(`unexpected arguments: ${positionals.slice(1).join(' ')} (pass options without --)`); +const experiment = JSON.parse(readFileSync(join(repoRoot, DECLARED), 'utf8')) as Rl3Experiment; +const outRoot = values.out ?? join(repoRoot, OUT_DIR); +const steps = values.steps ? Number(values.steps) : undefined; +if (steps !== undefined && !values.out) throw new Error('--steps overrides the declared budget: pass --out to a scratch directory'); +const seeds = values.seed ? [Number(values.seed)] : experiment.seeds; +if (!values.out) { + for (const seed of seeds) if (!experiment.seeds.includes(seed)) throw new Error(`seed ${seed} is not declared`); +} +if (experiment.protocolId !== CIRCUIT_PROTOCOL.id) { + throw new Error(`experiment declares ${experiment.protocolId}, code is ${CIRCUIT_PROTOCOL.id}`); +} + +await tf.setBackend(experiment.agent.backend); +await tf.ready(); + +const git = (cmd: string) => execSync(cmd, { cwd: repoRoot, encoding: 'utf8' }).trim(); +const runtime = () => ({ + gitSha: git('git rev-parse HEAD'), + gitDirtyAtRunTime: git('git status --porcelain') !== '', + nodeVersion: process.version, + platform: `${process.platform}-${process.arch}`, + tfjsVersion: tf.version.tfjs, + tfjsBackend: tf.getBackend(), +}); +const seedDir = (seed: number) => join(outRoot, `seed-${seed}`); +const writeJson = (path: string, value: unknown) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`); + +/** sha256 over every weight tensor of a model, in layer order. */ +function weightsHash(model: tf.LayersModel): string { + const hash = createHash('sha256'); + for (const w of model.getWeights()) hash.update(Buffer.from((w.dataSync() as Float32Array).buffer)); + return hash.digest('hex'); +} + +// ── train ──────────────────────────────────────────────────────────────────── +async function train(seed: number) { + const dir = seedDir(seed); + mkdirSync(dir, { recursive: true }); + const logPath = join(dir, 'train-episodes.jsonl'); + rmSync(logPath, { force: true }); + const agent = new DQNAgent({ ...buildAgentConfig(experiment, seed), storageProvider: fileSystemModelProvider(dir) }); + const startedAt = new Date().toISOString(); + const t0 = process.hrtime.bigint(); + try { + await agent.saveModel('untrained', { seed, stage: 'untrained' }); + const untrainedHash = weightsHash(agent.getModel()); + let last = Date.now(); + const result = await runTraining({ + experiment, seed, agent, envSteps: steps, + onEpisode: (row) => { + appendFileSync(logPath, `${JSON.stringify(row)}\n`); + if (Date.now() - last > 30_000) { + last = Date.now(); + console.error(JSON.stringify({ seed, envSteps: row.envStepsEnd, episode: row.episode, endReason: row.endReason, laps: row.laps })); + } + }, + }); + const durationMs = Number(process.hrtime.bigint() - t0) / 1e6; + await agent.saveModel('trained', { seed, stage: 'trained', envSteps: result.envSteps }); + const trainedHash = weightsHash(agent.getModel()); + const eps = result.episodes; + const tail = eps.slice(-100); + const run = { + seed, + algorithm: experiment.algorithm, + agentConfig: buildAgentConfig(experiment, seed), + envSteps: result.envSteps, + declaredEnvSteps: experiment.budget.envStepsPerRun, + episodes: eps.length, + partialEpisodeAtBudget: result.partialEpisodeAtBudget, + trainingEndReasons: { + success: eps.filter((e) => e.endReason === 'success').length, + offTrack: eps.filter((e) => e.endReason === 'off-track').length, + timeLimit: eps.filter((e) => e.endReason === 'time-limit').length, + }, + last100: { + episodes: tail.length, + success: tail.filter((e) => e.endReason === 'success').length, + meanLaps: tail.reduce((s, e) => s + e.laps, 0) / Math.max(1, tail.length), + }, + weightsSha256: { untrained: untrainedHash, trained: trainedHash }, + startedAt, + finishedAt: new Date().toISOString(), + durationMs, + msPerEnvStep: durationMs / result.envSteps, + ...runtime(), + }; + writeJson(join(dir, 'run.json'), run); + console.log(JSON.stringify({ seed, durationMs: Math.round(durationMs), msPerEnvStep: run.msPerEnvStep, episodes: run.episodes, endReasons: run.trainingEndReasons, last100: run.last100 })); + } finally { + agent.dispose(); + } +} + +// ── eval (new process, frozen weights) ─────────────────────────────────────── +function greedyPolicy(model: tf.LayersModel) { + // Only getAction: evaluateCircuit cannot reach remember() or train() through it. + return { + async getAction(observation: number[]): Promise { + return tf.tidy(() => (model.predict(tf.tensor2d([observation])) as tf.Tensor).argMax(1).dataSync()[0]); + }, + }; +} + +/** Re-drives one episode outside the protocol to record x/y, and checks it matches the protocol episode. */ +async function replay(policy: ReturnType, circuit: Rl3Circuit, start: number) { + const t = CIRCUIT_PROTOCOL.circuits[circuit]; + const world = new CircuitEnv(t.straightLength, t.radius, t.halfWidth, { + startWaypoint: start, maxSteps: CIRCUIT_PROTOCOL.maxSteps, targetLaps: CIRCUIT_PROTOCOL.targetLaps, + }); + // points[k] = car position after k steps (points[0] = start), one point per step. + const points: [number, number][] = [[round(world.carX), round(world.carY)]]; + const lapEndSteps: number[] = []; + while (!world.done()) { + const laps = world.laps; + world.step(await policy.getAction(world.observe())); + points.push([round(world.carX), round(world.carY)]); + if (world.laps > laps) lapEndSteps.push(world.stepCount); + } + world.reset(); + return { episode: world.lastEpisode!, points, lapEndSteps }; +} +const round = (v: number) => Math.round(v * 1000) / 1000; + +async function evaluate(seed: number) { + const dir = seedDir(seed); + const rows: EvalEpisodeRow[] = []; + const reports: Record = {}; + const trajectories: Record = {}; + const frozen: Record = {}; + const run = JSON.parse(readFileSync(join(dir, 'run.json'), 'utf8')); + const t0 = process.hrtime.bigint(); + for (const policyName of RL3_POLICIES) { + const model = await fileSystemModelProvider(dir).load(policyName) as tf.LayersModel; + try { + const before = weightsHash(model); + const policy = greedyPolicy(model); + for (const circuit of RL3_CIRCUITS) { + const report = await evaluateCircuit(policy, { policyId: `rl3-dqn-seed-${seed}-${policyName}-w${before.slice(0, 12)}`, circuit }); + reports[`${policyName}-${circuit}`] = report; + for (const e of report.episodes) { + rows.push({ + protocolId: report.protocolId, policyId: report.policyId, seed, policy: policyName, circuit, start: e.startWaypoint, + endReason: e.endReason, laps: e.completedLaps, transitions: e.transitions, + lapTimesSeconds: e.lapTimesSeconds, simulationSeconds: e.simulationSeconds, + }); + const r = await replay(policy, circuit, e.startWaypoint); + const same = r.episode.endReason === e.endReason && r.episode.transitions === e.transitions && r.episode.completedLaps === e.completedLaps; + if (!same) throw new Error(`replay differs from protocol episode: seed ${seed} ${policyName} ${circuit} start ${e.startWaypoint}`); + trajectories[`${policyName}/${circuit}/${e.startWaypoint}`] = { + policyId: report.policyId, transitions: e.transitions, completedLaps: e.completedLaps, endReason: e.endReason, + lapEndSteps: r.lapEndSteps, everySteps: 1, points: r.points, + }; + } + } + const after = weightsHash(model); + frozen[policyName] = { before, after, unchanged: before === after, matchesTrainProcess: before === run.weightsSha256[policyName] }; + if (before !== after) throw new Error(`weights changed during evaluation (seed ${seed}, ${policyName})`); + if (before !== run.weightsSha256[policyName]) throw new Error(`loaded weights differ from the training process (seed ${seed}, ${policyName})`); + } finally { + model.dispose(); + } + } + writeFileSync(join(dir, 'eval-episodes.jsonl'), rows.map((r) => JSON.stringify(r)).join('\n') + '\n'); + writeJson(join(dir, 'eval-reports.json'), reports); + writeJson(join(dir, 'trajectories.json'), trajectories); + writeJson(join(dir, 'eval-run.json'), { + process: 'rl3-bench eval (new process, weights loaded from disk)', + seed, protocolId: CIRCUIT_PROTOCOL.id, frozenWeights: frozen, + durationMs: Number(process.hrtime.bigint() - t0) / 1e6, + finishedAt: new Date().toISOString(), ...runtime(), + }); + console.log(JSON.stringify({ seed, rows: rows.map((r) => `${r.policy}/${r.circuit}/${r.start}:${r.endReason}:${r.laps}`) })); +} + +// ── manifest ───────────────────────────────────────────────────────────────── +const RUN_FILES = [ + 'train-episodes.jsonl', 'run.json', 'eval-episodes.jsonl', 'eval-reports.json', 'eval-run.json', 'trajectories.json', + 'untrained/model.json', 'untrained/weights.bin', 'trained/model.json', 'trained/weights.bin', +]; +const GIT_SHA_RULE = `gitSha is git rev-parse HEAD at train time; after the artifacts are committed it is an ancestor of the commit that last modified ${OUT_DIR}/manifest.json`; + +function manifest() { + const missing: string[] = []; + for (const seed of experiment.seeds) for (const f of RUN_FILES) if (!existsSync(join(seedDir(seed), f))) missing.push(`seed-${seed}/${f}`); + if (missing.length) { + console.error(JSON.stringify({ error: 'missing artifacts', missing }, null, 2)); + process.exit(1); + } + const runs = experiment.seeds.map((seed) => JSON.parse(readFileSync(join(seedDir(seed), 'run.json'), 'utf8'))); + const evalRuns = experiment.seeds.map((seed) => JSON.parse(readFileSync(join(seedDir(seed), 'eval-run.json'), 'utf8'))); + const budgets = new Set(runs.map((r) => r.envSteps)); + if (budgets.size !== 1 || !budgets.has(experiment.budget.envStepsPerRun)) throw new Error('runs do not all use the declared budget'); + const rows = experiment.seeds.flatMap((seed) => parseEvalLog(readFileSync(join(seedDir(seed), 'eval-episodes.jsonl'), 'utf8'))); + const options = { seeds: experiment.seeds, protocolId: CIRCUIT_PROTOCOL.id, starts: CIRCUIT_PROTOCOL.startWaypoints, targetLaps: CIRCUIT_PROTOCOL.targetLaps }; + const results = RL3_POLICIES.map((policy: Rl3Policy) => summarizePolicy(rows, { ...options, policy })); + writeJson(join(outRoot, 'summary.json'), { protocolId: CIRCUIT_PROTOCOL.id, source: 'seed-/eval-episodes.jsonl', ...summaryFile(results) }); + writeJson(join(outRoot, 'experiment.json'), { + ...experiment, + declaredPath: DECLARED, + protocol: CIRCUIT_PROTOCOL, + runtime: { + gitSha: runs[0].gitSha, + gitShaRule: GIT_SHA_RULE, + allRunsSameGitSha: new Set(runs.map((r) => r.gitSha)).size === 1, + nodeVersion: runs[0].nodeVersion, + platform: runs[0].platform, + tfjsVersion: runs[0].tfjsVersion, + tfjsBackend: runs[0].tfjsBackend, + trainingDurationMs: runs.reduce((s, r) => s + r.durationMs, 0), + evaluationDurationMs: evalRuns.reduce((s, r) => s + r.durationMs, 0), + }, + runs: runs.map((r, i) => ({ + seed: r.seed, envSteps: r.envSteps, episodes: r.episodes, trainingEndReasons: r.trainingEndReasons, + partialEpisodeAtBudget: r.partialEpisodeAtBudget, startedAt: r.startedAt, finishedAt: r.finishedAt, + durationMs: r.durationMs, msPerEnvStep: r.msPerEnvStep, gitSha: r.gitSha, gitDirtyAtRunTime: r.gitDirtyAtRunTime, + evalGitSha: evalRuns[i].gitSha, frozenWeights: evalRuns[i].frozenWeights, + })), + }); + const artifact = (rel: string) => { + const buf = readFileSync(join(outRoot, rel)); + return { path: rel, bytes: buf.byteLength, sha256: createHash('sha256').update(buf).digest('hex') }; + }; + writeJson(join(outRoot, 'manifest.json'), { + gitSha: runs[0].gitSha, + gitShaRule: GIT_SHA_RULE, + protocolId: CIRCUIT_PROTOCOL.id, + algorithm: experiment.algorithm, + seeds: experiment.seeds, + budget: experiment.budget, + experiment: artifact('experiment.json'), + summary: artifact('summary.json'), + runs: Object.fromEntries(experiment.seeds.map((seed) => [ + String(seed), Object.fromEntries(RUN_FILES.map((f) => [f, artifact(`seed-${seed}/${f}`)])), + ])), + }); + console.log(JSON.stringify({ gitSha: runs[0].gitSha, artifacts: experiment.seeds.length * RUN_FILES.length + 2, out: relative(repoRoot, outRoot) })); +} + +if (command === 'train') for (const seed of seeds) await train(seed); +else if (command === 'eval') for (const seed of seeds) await evaluate(seed); +else if (command === 'manifest') manifest(); +else throw new Error('usage: rl3-bench.mts train|eval|manifest [--seed n] [--steps n --out dir]'); diff --git a/packages/demo-car-circuit/src/generalisation-main.tsx b/packages/demo-car-circuit/src/generalisation-main.tsx new file mode 100644 index 0000000..bf90d71 --- /dev/null +++ b/packages/demo-car-circuit/src/generalisation-main.tsx @@ -0,0 +1,9 @@ +import { StrictMode } from 'react'; +import { createRoot } from 'react-dom/client'; +import Rl3App from './generalisation/Rl3App'; + +createRoot(document.getElementById('root')!).render( + + + , +); diff --git a/packages/demo-car-circuit/src/generalisation.html b/packages/demo-car-circuit/src/generalisation.html new file mode 100644 index 0000000..9ee9e65 --- /dev/null +++ b/packages/demo-car-circuit/src/generalisation.html @@ -0,0 +1,17 @@ + + + + + + + IgnitionAI — RL 3 + + + +
+ + + diff --git a/packages/demo-car-circuit/src/generalisation/Rl3App.tsx b/packages/demo-car-circuit/src/generalisation/Rl3App.tsx new file mode 100644 index 0000000..15925f9 --- /dev/null +++ b/packages/demo-car-circuit/src/generalisation/Rl3App.tsx @@ -0,0 +1,893 @@ +import { useEffect, useMemo, useRef, useState, useSyncExternalStore, type CSSProperties, type ReactNode } from 'react'; +import { OvalTrack } from '../track'; +import { CIRCUIT_PROTOCOL } from '../evaluation'; +import { getLanguage, setLanguage, subscribe, t, type Language } from './i18n'; +import { + loadRl3, manifestOverride, rl3ManifestUrl, + type Rl3Data, type Rl3LoadResult, type Rl3Problem, type Trajectory, +} from './data'; +import { RL3_CIRCUITS, type CircuitCounts, type EvalEpisodeRow, type PolicyResult, type Rl3Circuit, type Rl3EndReason } from './results'; + +// Condition hues at equal relative luminance (0.389 / 0.391), same weight everywhere. +export const HUE: Record = { training: '#5eadf5', test: '#e8954a' }; +const TEXT = '#e2e8f0'; +const MUTED = '#94a3b8'; +const BORDER = '#334155'; +const EDGE = '#64748b'; +const ACTIVE = '#4f46e5'; +const NARROW = 720; +const STEPS_PER_FRAME = 4; +/** Tutorial URL; the link is shown only once the tutorial is published. */ +export const RL3_TUTORIAL_URL: string | null = null; + +// ── hooks ──────────────────────────────────────────────────────────────────── + +function useLanguage(): Language { + return useSyncExternalStore(subscribe, getLanguage, getLanguage); +} + +function subscribeResize(listener: () => void) { + window.addEventListener('resize', listener); + return () => window.removeEventListener('resize', listener); +} + +function useWidth(): number { + return useSyncExternalStore(subscribeResize, () => window.innerWidth, () => 1280); +} + +function prefersReducedMotion(): boolean { + return typeof window !== 'undefined' && typeof window.matchMedia === 'function' && + window.matchMedia('(prefers-reduced-motion: reduce)').matches; +} + +// ── formatting ─────────────────────────────────────────────────────────────── + +export function formatDecimal(value: number, lang: Language, digits = 2): string { + const text = value.toFixed(digits); + return lang === 'fr' ? text.replace('.', ',') : text; +} + +export function formatInt(value: number, lang: Language): string { + // fr-FR groups with a narrow no-break space. + return value.toLocaleString(lang === 'fr' ? 'fr-FR' : 'en-US'); +} + +/** Signed integer with a true minus sign: "+2", "−3", "0". */ +export function formatSignedInt(value: number): string { + if (value > 0) return `+${value}`; + if (value < 0) return `−${Math.abs(value)}`; + return '0'; +} + +export function formatSignedDecimal(value: number, lang: Language, digits = 2): string { + const rounded = Number(value.toFixed(digits)); + const body = formatDecimal(Math.abs(rounded), lang, digits); + if (rounded > 0) return `+${body}`; + if (rounded < 0) return `−${body}`; + return body; +} + +const endText = (end: Rl3EndReason) => + end === 'success' ? t('rl3.end.success') : end === 'off-track' ? t('rl3.end.offTrack') : t('rl3.end.timeLimit', { maxSteps: formatInt(CIRCUIT_PROTOCOL.maxSteps, getLanguage()) }); + +const endSymbol = (end: Rl3EndReason) => (end === 'success' ? '●' : end === 'off-track' ? '×' : '□'); + +// ── page ───────────────────────────────────────────────────────────────────── + +type State = { status: 'loading' } | { status: 'done'; result: Rl3LoadResult }; + +export default function Rl3App({ initial }: { initial?: Rl3LoadResult }) { + const lang = useLanguage(); + const width = useWidth(); + const narrow = width < NARROW; + const [state, setState] = useState(initial ? { status: 'done', result: initial } : { status: 'loading' }); + + useEffect(() => { + if (initial) return; + let cancelled = false; + const url = manifestOverride(window.location.search, window.location.href) ?? rl3ManifestUrl(); + loadRl3(url) + .then((result) => { if (!cancelled) setState({ status: 'done', result }); }) + .catch((cause) => { + if (!cancelled) setState({ status: 'done', result: { kind: 'format', problems: [{ url, format: String(cause) }] } }); + }); + return () => { cancelled = true; }; + }, [initial]); + + const result = state.status === 'done' ? state.result : null; + const data = result?.kind === 'loaded' ? result.data : null; + + return ( +
+
+
+

{t('rl3.heading')}

+ {data && ( +

+ {t('rl3.subtitle', { sha: data.manifest.gitSha.slice(0, 12), protocolId: data.manifest.protocolId, seeds: data.manifest.seeds.join(', ') })} +

+ )} +
+ +
+ + {state.status === 'loading' &&

{t('rl3.loading')}

} + {result && result.kind !== 'loaded' && } + {data && } +
+ ); +} + +function problemText(p: Rl3Problem): string { + if (p.format) return t('rl3.error.format', { url: p.url }); + return p.status === undefined ? t('rl3.error.missing', { url: p.url }) : t('rl3.error.missingStatus', { url: p.url, status: p.status }); +} + +function ProblemList({ problems }: { problems: Rl3Problem[] }) { + return ( +
    + {problems.map((p) =>
  • {problemText(p)}
  • )} +
+ ); +} + +function GlobalError({ result }: { result: Exclude }) { + const testId = { missing: 'rl3-error', format: 'rl3-format-error', protocol: 'rl3-protocol-error', policy: 'rl3-policy-error' }[result.kind]; + return ( +
+ {(result.kind === 'missing' || result.kind === 'format') && } + {result.kind === 'protocol' &&

{t('rl3.error.protocol', { protocolId: CIRCUIT_PROTOCOL.id })} ({result.protocolId})

} + {result.kind === 'policy' &&

{t('rl3.error.policy', { seed: result.seed })}

} +

{t('rl3.error.noSimulation')}

+
+ ); +} + +function Loaded({ data, narrow, width, lang }: { data: Rl3Data; narrow: boolean; width: number; lang: Language }) { + const seeds = data.manifest.seeds; + const [seed, setSeed] = useState(seeds[0]); + const [start, setStart] = useState(CIRCUIT_PROTOCOL.startWaypoints[0]); + const select = (s: number, st: number) => { setSeed(s); setStart(st); }; + return ( + <> + + + + + + + ); +} + +// ── A. protocol ────────────────────────────────────────────────────────────── + +function ProtocolBlock({ data, lang }: { data: Rl3Data; lang: Language }) { + const p = data.experiment.protocol; + const c = p.circuits; + return ( +
+

{t('rl3.protocol.title')}

+

+ {t('rl3.protocol.line', { maxSteps: formatInt(p.maxSteps, lang), laps: p.targetLaps, starts: p.startWaypoints.join(', ') })} +

+

{t('rl3.protocol.samePolicy')}

+

+ {t('rl3.protocol.circuits', { + trainingStraight: c.training.straightLength, trainingRadius: c.training.radius, trainingHalf: c.training.halfWidth, + testStraight: c.test.straightLength, testRadius: c.test.radius, testHalf: c.test.halfWidth, + })} +

+

+ {t('rl3.protocol.training', { + algorithm: data.experiment.algorithm.toUpperCase(), + layers: `[${data.experiment.agent.hiddenLayers.join(', ')}]`, + steps: formatInt(data.experiment.budget.envStepsPerRun, lang), + })} +

+
+ ); +} + +// ── B. side-by-side top view ───────────────────────────────────────────────── + +const tracks: Record = { + training: new OvalTrack(CIRCUIT_PROTOCOL.circuits.training.straightLength, CIRCUIT_PROTOCOL.circuits.training.radius, CIRCUIT_PROTOCOL.circuits.training.halfWidth), + test: new OvalTrack(CIRCUIT_PROTOCOL.circuits.test.straightLength, CIRCUIT_PROTOCOL.circuits.test.radius, CIRCUIT_PROTOCOL.circuits.test.halfWidth), +}; + +/** Right-hand unit normal at waypoint i (signedDistance > 0 side in track.ts). */ +function normalAt(track: OvalTrack, i: number): [number, number] { + const w = track.waypoints; + const a = w[i]; + const b = w[(i + 1) % w.length]; + const angle = Math.atan2(b.y - a.y, b.x - a.x); + return [Math.sin(angle), -Math.cos(angle)]; +} + +function edges(track: OvalTrack) { + const left: [number, number][] = []; + const right: [number, number][] = []; + track.waypoints.forEach((p, i) => { + const [nx, ny] = normalAt(track, i); + right.push([p.x + nx * track.halfWidth, p.y + ny * track.halfWidth]); + left.push([p.x - nx * track.halfWidth, p.y - ny * track.halfWidth]); + }); + return { left, right }; +} + +// SVG y points down; the world y points up. +const sv = ([x, y]: [number, number]) => `${x.toFixed(3)},${(-y).toFixed(3)}`; +const pathOf = (pts: [number, number][], close = false) => `M${pts.map(sv).join('L')}${close ? 'Z' : ''}`; + +function splitLaps(traj: Trajectory, upTo: number): [number, number][][] { + const bounds = [0, ...traj.lapEndSteps, traj.points.length - 1]; + const parts: [number, number][][] = []; + for (let i = 0; i < bounds.length - 1; i++) { + const from = bounds[i]; + const to = Math.min(bounds[i + 1], upTo); + if (to > from) parts.push(traj.points.slice(from, to + 1)); + } + return parts; +} + +export const lapStyle = (lap: number): { opacity: number; dash?: string } => + // Lap 1 solid, lap 2 faded, lap 3 dashed (index 0 = lap 1). + lap === 1 ? { opacity: 0.55 } : lap === 2 ? { opacity: 1, dash: '6 3' } : { opacity: 1 }; + +// The three laps follow almost the same path: each one is drawn only inside its own +// vertical bands (3 phases), so that none of them hides another. +const VIEW_X = -12; +const VIEW_Y = -10; +const VIEW_W = 24; +const VIEW_H = 20; +export const LAP_PHASES = 3; + +/** Band width in screen pixels: 8 px from 720 px of viewport, 6 px below. */ +export const lapBandPx = (viewportWidth: number) => (viewportWidth >= NARROW ? 8 : 6); + +/** + * Vertical bands of the viewBox for each lap (index 0 = lap 1), in viewBox units. + * Band i spans the screen pixels [i·bandPx − offsetPx, (i+1)·bandPx − offsetPx] from the left + * edge of the SVG (cut to the viewBox), and belongs to lap (i mod 3) + 1. + */ +export function lapBands(renderedPx: number, bandPx: number, offsetPx = 0): { x: number; width: number; index: number }[][] { + const unitsPerPx = VIEW_W / Math.max(1, renderedPx); + const bands: { x: number; width: number; index: number }[][] = Array.from({ length: LAP_PHASES }, () => []); + for (let i = 0; (i * bandPx - offsetPx) * unitsPerPx < VIEW_W - 1e-9; i++) { + const from = Math.max(VIEW_X, VIEW_X + (i * bandPx - offsetPx) * unitsPerPx); + const to = Math.min(VIEW_X + VIEW_W, VIEW_X + ((i + 1) * bandPx - offsetPx) * unitsPerPx); + if (to - from > 1e-9) bands[i % LAP_PHASES].push({ x: from, width: to - from, index: i }); + } + return bands; +} + +/** Share of ink kept by each lap style: the 6 3 dashes keep 6 px out of 9. */ +export const LAP_INK = [1, 1, 6 / 9]; + +/** + * Length of each lap drawn inside its own bands, weighted by the ink of its style + * (index 0 = lap 1), for a band origin shifted by offsetPx. + */ +export function lapVisibleLengths(laps: [number, number][][], renderedPx: number, bandPx: number, offsetPx: number): number[] { + const pxPerUnit = Math.max(1, renderedPx) / VIEW_W; + return laps.slice(0, LAP_PHASES).map((pts, lap) => { + let length = 0; + for (let i = 1; i < pts.length; i++) { + const [x0, y0] = pts[i - 1]; + const [x1, y1] = pts[i]; + const pieces = 4; + const piece = Math.hypot(x1 - x0, y1 - y0) / pieces; + for (let j = 0; j < pieces; j++) { + const x = x0 + ((j + 0.5) / pieces) * (x1 - x0); + const band = Math.floor(((x - VIEW_X) * pxPerUnit + offsetPx) / bandPx); + if (((band % LAP_PHASES) + LAP_PHASES) % LAP_PHASES === lap) length += piece; + } + } + return length * LAP_INK[lap]; + }); +} + +/** + * Band origin (0 … 3·bandPx − 1 screen pixels) that gives the laps the most even visible + * share: the laps follow almost the same path, so which phase falls on the long straights + * and on the vertical ends of the curves matters, and the dashed lap keeps less ink. + */ +export function balancedBandOffset(laps: [number, number][][], renderedPx: number, bandPx: number): number { + const present = Math.min(laps.length, LAP_PHASES); + if (present < 2) return 0; + let best = 0; + let bestScore = -Infinity; + for (let offset = 0; offset < LAP_PHASES * bandPx; offset++) { + const lengths = lapVisibleLengths(laps, renderedPx, bandPx, offset).slice(0, present); + const total = lengths.reduce((a, b) => a + b, 0); + const score = total > 0 ? Math.min(...lengths) / total : 0; + if (score > bestScore + 1e-12) { best = offset; bestScore = score; } + } + return best; +} + +/** Rendered width of the SVG in CSS pixels (estimate until the first layout). */ +function useRenderedWidth(ref: { current: SVGSVGElement | null }, estimate: number): number { + const [measured, setMeasured] = useState(null); + useEffect(() => { + const el = ref.current; + if (!el) return; + const read = () => { const w = el.getBoundingClientRect().width; if (w > 0) setMeasured(w); }; + read(); + if (typeof ResizeObserver === 'undefined') { + window.addEventListener('resize', read); + return () => window.removeEventListener('resize', read); + } + const observer = new ResizeObserver(read); + observer.observe(el); + return () => observer.disconnect(); + }, [ref]); + return measured ?? estimate; +} + +function TrackSvg({ circuit, traj, step, start, px, seed, bandPx }: { circuit: Rl3Circuit; traj: Trajectory | null; step: number; start: number; px: number; seed: number; bandPx: number }) { + const track = tracks[circuit]; + const { left, right } = useMemo(() => edges(track), [track]); + const svgRef = useRef(null); + const renderedPx = useRenderedWidth(svgRef, px); + // Computed on the whole episode, so the bands do not move while the cars are playing. + const offsetPx = useMemo(() => (traj ? balancedBandOffset(splitLaps(traj, Infinity), renderedPx, bandPx) : 0), [traj, renderedPx, bandPx]); + const bands = useMemo(() => lapBands(renderedPx, bandPx, offsetPx), [renderedPx, bandPx, offsetPx]); + const unit = 24 / px; // world units per screen pixel (viewBox is 24 wide) + const hue = HUE[circuit]; + const shown = traj ? Math.min(step, traj.points.length - 1) : 0; + const finished = traj ? shown >= traj.points.length - 1 : false; + const end = traj?.points[shown]; + const mark = 5 * unit; + const centre = track.waypoints.map((p) => [p.x, p.y] as [number, number]); + const top = track.waypoints[8]; + return ( + + + {bands.map((laps, lap) => ( + + {laps.map((b) => )} + + ))} + + + + + + {/* Direction of travel (clockwise seen from above): along +x on the top straight. */} + + {CIRCUIT_PROTOCOL.startWaypoints.map((wp) => { + const p = track.waypoints[wp]; + const [nx, ny] = normalAt(track, wp); + const a: [number, number] = [p.x + nx * track.halfWidth, p.y + ny * track.halfWidth]; + const b: [number, number] = [p.x - nx * track.halfWidth, p.y - ny * track.halfWidth]; + const outer = Math.hypot(...a) > Math.hypot(...b) ? 1 : -1; + const label: [number, number] = [p.x + outer * nx * (track.halfWidth + 0.8), p.y + outer * ny * (track.halfWidth + 0.8)]; + const selected = wp === start; + return ( + + + + {wp} + + + ); + })} + {traj && splitLaps(traj, shown).map((pts, lap) => { + const s = lapStyle(lap); + return ( + + ); + })} + {traj && end && finished && ( + + {traj.endReason === 'success' && } + {traj.endReason === 'off-track' && ( + + )} + {traj.endReason === 'time-limit' && ( + + )} + + )} + {traj && end && !finished && ( + + )} + + ); +} + +function StatusLine({ circuit, traj, row, step, playing, lang, showPolicy }: { circuit: Rl3Circuit; traj: Trajectory; row: EvalEpisodeRow; step: number; playing: boolean; lang: Language; showPolicy: boolean }) { + const shown = Math.min(step, row.transitions); + const lapsSoFar = traj.lapEndSteps.filter((s) => s <= shown).length; + const finished = shown >= row.transitions; + const times = row.lapTimesSeconds.map((s) => formatDecimal(s, lang, 2)).join(' · '); + return ( +
+
+ {t('rl3.state.step', { step: formatInt(shown, lang), total: formatInt(row.transitions, lang) })} + {' · '} + {t('rl3.state.laps', { laps: lapsSoFar })} +
+
+ {finished ? `${endSymbol(row.endReason)} ${endText(row.endReason)}` : '…'} + {finished && playing ? ` · ${t('rl3.state.doneAt', { step: formatInt(row.transitions, lang) })}` : ''} +
+
{t('rl3.state.simTime', { seconds: formatDecimal(row.simulationSeconds, lang, 2) })}
+ {row.lapTimesSeconds.length > 0 &&
{t('rl3.state.lapTimes', { times })}
} + {showPolicy &&
{t('rl3.state.policy', { policyId: row.policyId })}
} +
+ ); +} + +function SideBySide({ data, seed, start, select, narrow, width, lang }: { + data: Rl3Data; seed: number; start: number; select: (seed: number, start: number) => void; narrow: boolean; width: number; lang: Language; +}) { + const [step, setStep] = useState(Infinity); + const [playing, setPlaying] = useState(false); + const reduced = prefersReducedMotion(); + const frame = useRef(null); + const seedResult = data.trained.seeds.find((s) => s.seed === seed)!; + const rows = { + training: seedResult.episodes.training.find((r) => r.start === start)!, + test: seedResult.episodes.test.find((r) => r.start === start)!, + }; + const longest = Math.max(rows.training.transitions, rows.test.transitions); + + useEffect(() => { + setPlaying(false); + setStep(Infinity); + }, [seed, start]); + + useEffect(() => { + if (!playing) return; + const tick = () => { + setStep((s) => { + const next = s + STEPS_PER_FRAME; + if (next >= longest) { + setPlaying(false); + return longest; + } + return next; + }); + frame.current = requestAnimationFrame(tick); + }; + frame.current = requestAnimationFrame(tick); + return () => { if (frame.current !== null) cancelAnimationFrame(frame.current); }; + }, [playing, longest]); + + const panelPx = narrow ? Math.max(120, (width - 40 - 8) / 2) : Math.min(612, (width - 40 - 16) / 2); + const traces = data.trajectories; + + return ( +
+
+ {data.manifest.seeds.map((s) => ( + + ))} +
+
+ {CIRCUIT_PROTOCOL.startWaypoints.map((st) => ( + + ))} +
+ {traces.ok ? ( + <> +
+ + +
+ {reduced &&

{t('rl3.reducedMotion')}

} +
+ {RL3_CIRCUITS.map((circuit) => ( +
+

+ {t(`rl3.circuit.${circuit}`)} +

+ + +
+ ))} +
+ +

+ {narrow ? ( + <> + {t('rl3.samePolicyNoteNarrow')}{' '} + {rows.training.policyId} + + ) : t('rl3.samePolicyNote')} +

+ + ) : 'missing' in traces ? ( +
+

{t('rl3.error.trace')}

+ +
+ ) : ( +
+

+ {t('rl3.error.replayMismatch', { field: traces.mismatch.field, replay: traces.mismatch.replay, report: traces.mismatch.report })} +

+

+ {t('rl3.control.seed', { seed: traces.mismatch.seed })} · {t(`rl3.circuit.${traces.mismatch.circuit}`)} · {t('rl3.control.start', { start: traces.mismatch.start })} +

+
+ )} +
+ ); +} + +/** 16 px stroke sample in the style of a lap (neutral hue), drawn in front of its label. */ +function LapSample({ lap }: { lap: number }) { + const s = lapStyle(lap); + return ( + + ); +} + +function LapLegend() { + return ( +

+ {Array.from({ length: LAP_PHASES }, (_, lap) => ( + {t('rl3.lapItem', { lap: lap + 1 })} + ))} +

+ ); +} + +function Swatch({ circuit }: { circuit: Rl3Circuit }) { + return