Skip to content
Merged
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
404 changes: 404 additions & 0 deletions packages/backend-tfjs/scripts/dqn-target-chasing.mjs

Large diffs are not rendered by default.

81 changes: 81 additions & 0 deletions packages/backend-tfjs/scripts/eval-dqn-checkpoint.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/**
* New-process eval of the frozen DQN / Double DQN policies.
* For each algo and seed: load trained/ from disk, compare the greedy action and the
* Q-values at the replay state with the values recorded by the training process,
* replay the greedy episode from 0.2, and run the greedy eval episodes.
* Writes <algo>/seed-<n>/eval-new-process.json. Exit code 2 if any greedy action differs.
*
* Usage: node scripts/eval-dqn-checkpoint.mjs [--variant noisy] [--algo dqn] [--seed 11]
*/
import { readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseArgs } from 'node:util';
import * as tf from '@tensorflow/tfjs';
import { DQNAgent } from '../dist/index.js';
import { fileSystemModelProvider } from './fs-provider.mjs';
import { ALGOS, buildAgentConfig, evaluateGreedy, greedyEpisodeFrom, variantOf } from './dqn-target-chasing.mjs';

const here = dirname(fileURLToPath(import.meta.url));
const repoRoot = join(here, '../../..');
const { values } = parseArgs({
options: { variant: { type: 'string' }, algo: { type: 'string' }, seed: { type: 'string' } },
});
const variant = variantOf(values.variant);
const outRoot = join(repoRoot, variant.outDir);
const experiment = JSON.parse(readFileSync(join(repoRoot, variant.experimentPath), 'utf8'));
const algos = values.algo ? [values.algo] : ALGOS;
const seeds = values.seed ? [Number(values.seed)] : experiment.seeds;

await tf.setBackend(experiment.agent.backend);
await tf.ready();

let allMatch = true;
for (const algo of algos) {
for (const seed of seeds) {
const seedDir = join(outRoot, algo, `seed-${seed}`);
const expected = JSON.parse(readFileSync(join(seedDir, 'trained-greedy.json'), 'utf8'));
const agent = new DQNAgent({
...buildAgentConfig(experiment, algo, seed),
storageProvider: fileSystemModelProvider(seedDir),
});
try {
await agent.load('trained');
const action = await agent.getAction(expected.state, true);
const q = tf.tidy(() => agent.getModel().predict(tf.tensor2d([expected.state])).arraySync()[0]);
const maxAbsQDiff = Math.max(...q.map((v, i) => Math.abs(v - expected.q[i])));
const replay = await greedyEpisodeFrom(agent, experiment, expected.state[0]);
const greedy = await evaluateGreedy(agent, experiment, seed);
const identicalReplay =
replay.actions.length === expected.actions.length &&
replay.actions.every((a, i) => a === expected.actions[i]);
const match = action === expected.action && identicalReplay;
allMatch &&= match;
const result = {
process: 'eval-dqn-checkpoint',
algo,
seed,
loaded: 'trained',
tfjsBackend: tf.getBackend(),
state: expected.state,
expectedAction: expected.action,
loadedAction: action,
identicalGreedyAction: action === expected.action,
expectedQ: expected.q,
loadedQ: q,
maxAbsQDiff,
replay,
identicalReplay,
...greedy,
};
writeFileSync(join(seedDir, 'eval-new-process.json'), JSON.stringify(result, null, 2));
console.log(
JSON.stringify({ algo, seed, identicalGreedyAction: result.identicalGreedyAction, identicalReplay, maxAbsQDiff,
greedyEvalMean: greedy.greedyEvalMean, greedySuccessRate: greedy.greedySuccessRate }),
);
} finally {
agent.dispose();
}
}
}
if (!allMatch) process.exit(2);
150 changes: 150 additions & 0 deletions packages/backend-tfjs/scripts/manifest-dqn-vs-double.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/**
* Builds public/<variant dir>/experiment.json (declared config + measured runtime per run)
* and public/<variant dir>/manifest.json (every artifact with bytes and sha256, plus the
* per-run summaries), so a page can report exactly which artifact is missing or altered.
* Fails (exit 1) if any expected artifact is absent. Run after train and eval.
*
* Usage: node scripts/manifest-dqn-vs-double.mjs [--variant noisy]
*/
import { createHash } from 'node:crypto';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseArgs } from 'node:util';
import { ALGOS, variantOf } from './dqn-target-chasing.mjs';

const here = dirname(fileURLToPath(import.meta.url));
const repoRoot = join(here, '../../..');
const { values } = parseArgs({ options: { variant: { type: 'string' } } });
const variant = variantOf(values.variant);
const outRoot = join(repoRoot, variant.outDir);
const declaredPath = variant.experimentPath;
const declared = JSON.parse(readFileSync(join(repoRoot, declaredPath), 'utf8'));

export const RUN_FILES = [
'episodes.jsonl',
'q-vs-return.jsonl',
'summary.json',
'run.json',
'untrained-greedy.json',
'trained-greedy.json',
'eval-new-process.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 equals the first parent of git log -1 --format=%H -- ${variant.outDir}/manifest.json`;

const readJson = (rel) => JSON.parse(readFileSync(join(outRoot, rel), 'utf8'));
const missing = [];
const runs = [];
const summaries = [];
for (const algo of ALGOS) {
for (const seed of declared.seeds) {
const base = `${algo}/seed-${seed}`;
for (const f of RUN_FILES) if (!existsSync(join(outRoot, base, f))) missing.push(`${base}/${f}`);
if (missing.length) continue;
const run = readJson(`${base}/run.json`);
const summary = readJson(`${base}/summary.json`);
const evalNew = readJson(`${base}/eval-new-process.json`);
runs.push(run);
summaries.push({
algo,
seed,
envSteps: summary.envSteps,
episodes: summary.episodes,
lastMeanReturn: summary.lastMeanReturn,
lastSuccessRate: summary.lastSuccessRate,
greedyEvalMean: summary.greedyEvalMean,
greedySuccessRate: summary.greedySuccessRate,
finalMeanQMax: summary.finalQVsReturn.meanQMax,
finalMeanDiscountedReturn: summary.finalQVsReturn.meanDiscountedReturn,
finalMeanGap: summary.finalQVsReturn.meanGap,
meanGapOverRun: summary.meanGapOverRun,
meanGapSecondHalf: summary.meanGapSecondHalf,
...(summary.rewardNoise
? {
lastMeanNoisyReturn: summary.lastMeanNoisyReturn,
finalMeanDiscountedNoisyReturn: summary.finalQVsReturn.meanDiscountedNoisyReturn,
rewardNoiseSampleMean: summary.rewardNoise.sampleMean,
rewardNoiseSampleStd: summary.rewardNoise.sampleStd,
}
: {}),
newProcessIdenticalGreedyAction: evalNew.identicalGreedyAction,
newProcessIdenticalReplay: evalNew.identicalReplay,
durationMs: run.durationMs,
});
}
}
if (missing.length) {
console.error(JSON.stringify({ error: 'missing artifacts', missing }, null, 2));
process.exit(1);
}

const shas = new Set(runs.map((r) => r.gitSha));
const envSteps = new Set(runs.map((r) => r.envSteps));
if (envSteps.size !== 1) throw new Error(`runs do not share one budget: ${[...envSteps]}`);
const experiment = {
...declared,
declaredPath,
runtime: {
gitSha: runs[0].gitSha,
gitShaRule: GIT_SHA_RULE,
allRunsSameGitSha: shas.size === 1,
nodeVersion: runs[0].nodeVersion,
platform: runs[0].platform,
tfjsVersion: runs[0].tfjsVersion,
tfjsBackend: runs[0].tfjsBackend,
startedAt: runs.map((r) => r.startedAt).sort()[0],
finishedAt: runs.map((r) => r.finishedAt).sort().at(-1),
totalDurationMs: runs.reduce((s, r) => s + r.durationMs, 0),
},
runs: runs.map((r) => ({
algo: r.algo,
seed: r.seed,
envSteps: r.envSteps,
trainSteps: r.trainSteps,
episodes: r.episodes,
startedAt: r.startedAt,
finishedAt: r.finishedAt,
durationMs: r.durationMs,
msPerEnvStep: r.msPerEnvStep,
gitSha: r.gitSha,
nodeVersion: r.nodeVersion,
tfjsVersion: r.tfjsVersion,
tfjsBackend: r.tfjsBackend,
})),
};
writeFileSync(join(outRoot, 'experiment.json'), `${JSON.stringify(experiment, null, 2)}\n`);

const sha256 = (rel) => createHash('sha256').update(readFileSync(join(outRoot, rel))).digest('hex');
const bytes = (rel) => readFileSync(join(outRoot, rel)).byteLength;
const artifact = (rel) => ({ path: rel, bytes: bytes(rel), sha256: sha256(rel) });
const manifest = {
gitSha: experiment.runtime.gitSha,
gitShaRule: GIT_SHA_RULE,
experiment: artifact('experiment.json'),
algorithms: ALGOS,
order: 'dqn first, then double-dqn',
seeds: declared.seeds,
budget: { envStepsPerRun: declared.budget.envStepsPerRun },
gamma: declared.agent.gamma,
...(declared.rewardNoise ? { rewardNoise: declared.rewardNoise } : {}),
summaries,
runs: Object.fromEntries(
ALGOS.map((algo) => [
algo,
Object.fromEntries(
declared.seeds.map((seed) => [
String(seed),
Object.fromEntries(RUN_FILES.map((f) => [f, artifact(`${algo}/seed-${seed}/${f}`)])),
]),
),
]),
),
};
writeFileSync(join(outRoot, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
console.log(JSON.stringify({ gitSha: manifest.gitSha, artifacts: ALGOS.length * declared.seeds.length * RUN_FILES.length + 1 }));
122 changes: 122 additions & 0 deletions packages/backend-tfjs/scripts/train-dqn-target-chasing.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/**
* Local DQN vs Double DQN training on the declared Target Chasing (nav1d-discrete) budget.
* Reads packages/demo-target-chasing/dqn-vs-double-experiment.json (frozen before the runs).
* Writes raw JSONL + summaries + frozen policies under public/dqn-vs-double/<algo>/seed-<n>/.
* Does not invent metrics.
*
* Usage:
* node scripts/train-dqn-target-chasing.mjs # all algos x all seeds
* node scripts/train-dqn-target-chasing.mjs --algo dqn --seed 11
* node scripts/train-dqn-target-chasing.mjs --steps 2000 --out /tmp/x # speed probe, not an artifact
* node scripts/train-dqn-target-chasing.mjs --variant noisy # reward-noise variant
* (reads dqn-vs-double-noisy-experiment.json, writes public/dqn-vs-double-noisy/)
*
* Then: node scripts/eval-dqn-checkpoint.mjs && node scripts/manifest-dqn-vs-double.mjs
* (same --variant on all three scripts)
*
* gitSha is `git rev-parse HEAD` at train time (same rule as RL 1): after the
* artifacts commit it is the first parent of the commit that last modified
* public/<variant dir>/manifest.json.
*/
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { execSync } from 'node:child_process';
import { parseArgs } from 'node:util';
import * as tf from '@tensorflow/tfjs';
import { DQNAgent } from '../dist/index.js';
import { fileSystemModelProvider } from './fs-provider.mjs';
import { ALGOS, buildAgentConfig, runTraining, variantOf } from './dqn-target-chasing.mjs';

const here = dirname(fileURLToPath(import.meta.url));
const repoRoot = join(here, '../../..');

const { values } = parseArgs({
options: {
variant: { type: 'string' },
algo: { type: 'string' },
seed: { type: 'string' },
steps: { type: 'string' },
out: { type: 'string' },
},
});

const variant = variantOf(values.variant);
const experimentPath = join(repoRoot, variant.experimentPath);
const defaultOut = join(repoRoot, variant.outDir);
const experiment = JSON.parse(readFileSync(experimentPath, 'utf8'));
const outRoot = values.out ?? defaultOut;
const envSteps = values.steps ? Number(values.steps) : undefined;
if (envSteps !== undefined && !values.out) {
throw new Error('--steps overrides the declared budget: pass --out to a scratch directory');
}
const algos = values.algo ? [values.algo] : ALGOS;
const seeds = values.seed ? [Number(values.seed)] : experiment.seeds;
for (const seed of seeds) {
if (!experiment.seeds.includes(seed)) throw new Error(`seed ${seed} is not declared`);
}

await tf.setBackend(experiment.agent.backend);
await tf.ready();

const gitSha = execSync('git rev-parse HEAD', { cwd: repoRoot, encoding: 'utf8' }).trim();
const gitDirty = execSync('git status --porcelain', { cwd: repoRoot, encoding: 'utf8' }).trim() !== '';
const runtime = {
gitSha,
gitDirtyAtTrainTime: gitDirty,
nodeVersion: process.version,
platform: `${process.platform}-${process.arch}`,
tfjsVersion: tf.version.tfjs,
tfjsCoreVersion: tf.version['tfjs-core'],
tfjsBackend: tf.getBackend(),
};

for (const algo of algos) {
for (const seed of seeds) {
const seedDir = join(outRoot, algo, `seed-${seed}`);
mkdirSync(seedDir, { recursive: true });
const startedAt = new Date().toISOString();
const t0 = process.hrtime.bigint();
const { summary } = await runTraining({
AgentClass: DQNAgent,
experiment,
algo,
seed,
outDir: seedDir,
provider: fileSystemModelProvider(seedDir),
envSteps,
log: (row) => console.error(JSON.stringify(row)),
});
const durationMs = Number(process.hrtime.bigint() - t0) / 1e6;
const run = {
algo,
seed,
agentConfig: buildAgentConfig(experiment, algo, seed),
envSteps: summary.envSteps,
trainSteps: summary.trainSteps,
episodes: summary.episodes,
startedAt,
finishedAt: new Date().toISOString(),
durationMs,
msPerEnvStep: durationMs / summary.envSteps,
...runtime,
};
writeFileSync(join(seedDir, 'run.json'), JSON.stringify(run, null, 2));
console.log(
JSON.stringify({
algo,
seed,
durationMs: Math.round(durationMs),
msPerEnvStep: run.msPerEnvStep,
envSteps: summary.envSteps,
episodes: summary.episodes,
lastMeanReturn: summary.lastMeanReturn,
lastSuccessRate: summary.lastSuccessRate,
greedyEvalMean: summary.greedyEvalMean,
greedySuccessRate: summary.greedySuccessRate,
finalMeanGap: summary.finalQVsReturn.meanGap,
meanGapSecondHalf: summary.meanGapSecondHalf,
}),
);
}
}
Loading
Loading