From 05fa432c3ae52f5ac13aef17e344cf48982b2d62 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 16 Nov 2026 12:32:44 +0000 Subject: [PATCH] docs(skills): add ignition-evaluate frozen-policy protocol Add the Agent Skill, CartPole evaluate() helper, and tests for reproducible greedy eval, frozen weights, hand-checked stats, and a random baseline. No package API changes. Co-authored-by: Salim --- examples/skill-evaluate.test.ts | 110 ++++++++ examples/skill-evaluate.ts | 245 ++++++++++++++++++ skills/ignition-evaluate/SKILL.md | 108 ++++++++ skills/ignition-evaluate/frontmatter.test.ts | 26 ++ .../references/report-template.md | 24 ++ 5 files changed, 513 insertions(+) create mode 100644 examples/skill-evaluate.test.ts create mode 100644 examples/skill-evaluate.ts create mode 100644 skills/ignition-evaluate/SKILL.md create mode 100644 skills/ignition-evaluate/frontmatter.test.ts create mode 100644 skills/ignition-evaluate/references/report-template.md diff --git a/examples/skill-evaluate.test.ts b/examples/skill-evaluate.test.ts new file mode 100644 index 0000000..00b2e7f --- /dev/null +++ b/examples/skill-evaluate.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it } from 'vitest'; +import { DQNAgent, setBackend } from '@ignitionai/backend-tfjs'; +import { + EVAL_BUDGET, + EVAL_SEEDS, + EPISODES_PER_SEED, + POLICY_AGENT_SEED, + TRAIN_SEEDS, + evaluate, + evaluateWithRandomBaseline, + formatEvaluationReport, + mean, + sampleStd, + seededCartPoleFactory, + snapshotDqnWeights, + summarizeReturns, +} from './skill-evaluate'; + +function makeFrozenDqn(): DQNAgent { + return new DQNAgent({ + inputSize: 4, + actionSize: 2, + hiddenLayers: [8], + backend: 'cpu', + seed: POLICY_AGENT_SEED, + epsilon: 1, + }); +} + +describe('evaluation statistics (hand-calculated)', () => { + it('matches mean, sample std, and 95% CI for [1, 2, 3]', () => { + const values = [1, 2, 3]; + expect(mean(values)).toBe(2); + expect(sampleStd(values)).toBe(1); + const stats = summarizeReturns(values); + const stderr = 1 / Math.sqrt(3); + expect(stats.n).toBe(3); + expect(stats.mean).toBe(2); + expect(stats.sampleStd).toBe(1); + expect(stats.stderr).toBeCloseTo(stderr, 12); + expect(stats.ci95Low).toBeCloseTo(2 - 1.96 * stderr, 12); + expect(stats.ci95High).toBeCloseTo(2 + 1.96 * stderr, 12); + }); +}); + +describe('evaluate() on CartPole', () => { + it('declares disjoint train/eval seeds and a compute budget before running', () => { + expect(TRAIN_SEEDS).toEqual([11, 29, 47]); + expect(EVAL_SEEDS).toEqual([101, 202, 303]); + for (const seed of EVAL_SEEDS) { + expect(TRAIN_SEEDS).not.toContain(seed); + } + expect(EVAL_BUDGET.evalSeeds).toEqual(EVAL_SEEDS); + expect(EVAL_BUDGET.episodesPerSeed).toBe(EPISODES_PER_SEED); + expect(EVAL_BUDGET.maxEnvStepsPolicy).toBe(3 * 3 * 500); + }); + + it('repeats the same returns for the same eval seeds', async () => { + await setBackend('cpu'); + const a = makeFrozenDqn(); + const b = makeFrozenDqn(); + try { + const first = await evaluate(a, seededCartPoleFactory, EVAL_SEEDS, EPISODES_PER_SEED); + const second = await evaluate(b, seededCartPoleFactory, EVAL_SEEDS, EPISODES_PER_SEED); + expect(first.returns).toEqual(second.returns); + expect(first.stats).toEqual(second.stats); + } finally { + a.dispose(); + b.dispose(); + } + }); + + it('leaves DQN weights and getState() unchanged after greedy evaluation', async () => { + await setBackend('cpu'); + const agent = makeFrozenDqn(); + try { + const weightsBefore = snapshotDqnWeights(agent); + const stateBefore = agent.getState(); + await evaluate(agent, seededCartPoleFactory, EVAL_SEEDS, EPISODES_PER_SEED); + expect(snapshotDqnWeights(agent)).toEqual(weightsBefore); + expect(agent.getState()).toEqual(stateBefore); + } finally { + agent.dispose(); + } + }); + + it('includes a random-policy comparison in the report', async () => { + await setBackend('cpu'); + const agent = makeFrozenDqn(); + try { + const report = await evaluateWithRandomBaseline( + agent, + seededCartPoleFactory, + EVAL_SEEDS, + EPISODES_PER_SEED, + ); + expect(report.randomBaseline).toBeDefined(); + expect(report.randomBaseline?.n).toBe(EVAL_SEEDS.length * EPISODES_PER_SEED); + expect(typeof report.meanMinusRandom).toBe('number'); + // Raw measurement for the PR (no convergence claimed). + console.log(formatEvaluationReport(report)); + const text = formatEvaluationReport(report); + expect(text).toContain('Random baseline mean'); + expect(text).toContain('95% CI'); + expect(text).toContain('No convergence is claimed'); + } finally { + agent.dispose(); + } + }); +}); diff --git a/examples/skill-evaluate.ts b/examples/skill-evaluate.ts new file mode 100644 index 0000000..a98e99d --- /dev/null +++ b/examples/skill-evaluate.ts @@ -0,0 +1,245 @@ +import type { AgentInterface, TrainingEnv } from '@ignitionai/core'; +import { CartPoleEnv } from '@ignitionai/environments'; +import type { DQNAgent } from '@ignitionai/backend-tfjs'; + +/** + * Declared before any evaluation run (batch #102). + * Train seeds are listed only to keep them disjoint from eval seeds. + * This example does not train to a target return and does not claim convergence. + */ +export const TRAIN_SEEDS = [11, 29, 47] as const; +export const EVAL_SEEDS = [101, 202, 303] as const; +export const EPISODES_PER_SEED = 3; +export const MAX_STEPS_PER_EPISODE = 500; +export const RANDOM_BASELINE_SEED = 9001; +export const POLICY_AGENT_SEED = 11; + +export const EVAL_BUDGET = { + policy: 'frozen-greedy-dqn', + trainSeedsHeldOutFromEval: TRAIN_SEEDS, + evalSeeds: EVAL_SEEDS, + episodesPerSeed: EPISODES_PER_SEED, + maxStepsPerEpisode: MAX_STEPS_PER_EPISODE, + maxEnvStepsPolicy: + EVAL_SEEDS.length * EPISODES_PER_SEED * MAX_STEPS_PER_EPISODE, + maxEnvStepsRandomBaseline: + EVAL_SEEDS.length * EPISODES_PER_SEED * MAX_STEPS_PER_EPISODE, + notes: + 'Greedy getAction only. No remember/train during evaluate(). Random baseline uses the same env seeds.', +} as const; + +export type EnvFactory = (seed: number) => TrainingEnv; + +export interface ReturnStats { + n: number; + mean: number; + sampleStd: number; + stderr: number; + ci95Low: number; + ci95High: number; +} + +export interface EvaluationReport { + policy: string; + seeds: number[]; + episodesPerSeed: number; + returns: number[]; + stats: ReturnStats; + budget: typeof EVAL_BUDGET; + randomBaseline?: ReturnStats; + meanMinusRandom?: number; +} + +const Z95 = 1.96; + +export function createRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (Math.imul(state, 1664525) + 1013904223) >>> 0; + return state / 4294967296; + }; +} + +export function episodeSeed(evalSeed: number, episodeIndex: number): number { + const mixed = (Math.imul(evalSeed, 1009) + Math.imul(episodeIndex + 1, 9176) + 13) >>> 0; + return mixed === 0 ? 1 : mixed; +} + +/** CartPoleEnv has no seed API; map a seed onto the public `state` field. */ +export function applySeededCartPoleState(env: CartPoleEnv, seed: number): void { + const rng = createRng(seed); + env.state = { + x: (rng() - 0.5) * 0.1, + xDot: (rng() - 0.5) * 0.1, + theta: (rng() - 0.5) * 0.1, + thetaDot: (rng() - 0.5) * 0.1, + stepCount: 0, + }; +} + +export function seededCartPoleFactory(seed: number): CartPoleEnv { + const env = new CartPoleEnv(); + applySeededCartPoleState(env, seed); + return env; +} + +export function mean(values: readonly number[]): number { + if (values.length === 0) { + throw new Error('mean() requires at least one value'); + } + let sum = 0; + for (const value of values) sum += value; + return sum / values.length; +} + +export function sampleStd(values: readonly number[]): number { + if (values.length < 2) { + throw new Error('sampleStd() requires at least two values'); + } + const m = mean(values); + let sumSq = 0; + for (const value of values) { + const d = value - m; + sumSq += d * d; + } + return Math.sqrt(sumSq / (values.length - 1)); +} + +export function summarizeReturns(returns: readonly number[]): ReturnStats { + const n = returns.length; + const m = mean(returns); + const s = sampleStd(returns); + const stderr = s / Math.sqrt(n); + return { + n, + mean: m, + sampleStd: s, + stderr, + ci95Low: m - Z95 * stderr, + ci95High: m + Z95 * stderr, + }; +} + +export function snapshotDqnWeights(agent: DQNAgent): number[] { + const out: number[] = []; + for (const tensor of agent.getModel().getWeights()) { + out.push(...Array.from(tensor.dataSync())); + } + return out; +} + +function discreteAction(action: number | number[]): number { + return typeof action === 'number' ? action : action[0]; +} + +async function runGreedyEpisode( + agent: AgentInterface, + env: TrainingEnv, +): Promise { + let episodeReturn = 0; + let steps = 0; + while (!env.done() && steps < MAX_STEPS_PER_EPISODE) { + const action = discreteAction(await agent.getAction(env.observe(), true)); + env.step(action); + episodeReturn += env.reward(); + steps += 1; + } + return episodeReturn; +} + +function runRandomEpisode(env: TrainingEnv, rng: () => number, actionCount: number): number { + let episodeReturn = 0; + let steps = 0; + while (!env.done() && steps < MAX_STEPS_PER_EPISODE) { + env.step(Math.floor(rng() * actionCount)); + episodeReturn += env.reward(); + steps += 1; + } + return episodeReturn; +} + +function actionCountOf(env: TrainingEnv): number { + return typeof env.actions === 'number' ? env.actions : env.actions.length; +} + +export async function evaluate( + agent: AgentInterface, + envFactory: EnvFactory, + seeds: readonly number[], + episodes: number, +): Promise { + if (seeds.length < 1) throw new Error('evaluate() requires at least one eval seed'); + if (episodes < 1) throw new Error('evaluate() requires at least one episode per seed'); + + const returns: number[] = []; + for (const seed of seeds) { + for (let episode = 0; episode < episodes; episode += 1) { + const env = envFactory(episodeSeed(seed, episode)); + returns.push(await runGreedyEpisode(agent, env)); + } + } + + return { + policy: 'greedy-frozen', + seeds: [...seeds], + episodesPerSeed: episodes, + returns, + stats: summarizeReturns(returns), + budget: EVAL_BUDGET, + }; +} + +export async function evaluateRandomBaseline( + envFactory: EnvFactory, + seeds: readonly number[], + episodes: number, + rngSeed: number = RANDOM_BASELINE_SEED, +): Promise { + const rng = createRng(rngSeed); + const returns: number[] = []; + for (const seed of seeds) { + for (let episode = 0; episode < episodes; episode += 1) { + const env = envFactory(episodeSeed(seed, episode)); + returns.push(runRandomEpisode(env, rng, actionCountOf(env))); + } + } + return summarizeReturns(returns); +} + +export async function evaluateWithRandomBaseline( + agent: AgentInterface, + envFactory: EnvFactory, + seeds: readonly number[], + episodes: number, +): Promise { + const report = await evaluate(agent, envFactory, seeds, episodes); + const randomBaseline = await evaluateRandomBaseline(envFactory, seeds, episodes); + return { + ...report, + randomBaseline, + meanMinusRandom: report.stats.mean - randomBaseline.mean, + }; +} + +export function formatEvaluationReport(report: EvaluationReport): string { + const lines = [ + '# Policy evaluation report', + '', + `- Policy: ${report.policy} (greedy getAction; no learning during eval)`, + `- Train seeds (not used for eval): ${TRAIN_SEEDS.join(', ')}`, + `- Eval seeds: ${report.seeds.join(', ')}`, + `- Episodes per seed: ${report.episodesPerSeed}`, + `- Episode returns: ${report.returns.join(', ')}`, + `- Mean return: ${report.stats.mean.toFixed(4)} ± ${report.stats.sampleStd.toFixed(4)} (sample std, n=${report.stats.n})`, + `- 95% CI: [${report.stats.ci95Low.toFixed(4)}, ${report.stats.ci95High.toFixed(4)}]`, + `- Budget: max ${report.budget.maxEnvStepsPolicy} env steps for the policy, same cap for the random baseline`, + ]; + if (report.randomBaseline && report.meanMinusRandom !== undefined) { + lines.push( + `- Random baseline mean: ${report.randomBaseline.mean.toFixed(4)} ± ${report.randomBaseline.sampleStd.toFixed(4)}`, + `- Policy mean minus random mean: ${report.meanMinusRandom.toFixed(4)}`, + ); + } + lines.push('', 'No convergence is claimed. Numbers are the measured returns for this budget and these seeds.'); + return lines.join('\n'); +} diff --git a/skills/ignition-evaluate/SKILL.md b/skills/ignition-evaluate/SKILL.md new file mode 100644 index 0000000..46bfdfa --- /dev/null +++ b/skills/ignition-evaluate/SKILL.md @@ -0,0 +1,108 @@ +--- +name: ignition-evaluate +description: Evaluate a frozen IgnitionRL policy with held-out seeds, multiple episodes, mean ± sample std or a 95% CI, a random baseline, and a declared compute budget. Use before reporting returns, comparing agents, or claiming that a policy improved. +--- + +# Evaluate a frozen policy + +Measure a **fixed** policy. Do not report a single seed, a single episode, or a number without a spread. Do not claim convergence unless you measured it against a declared budget. + +This skill uses only the public API on `dev` at SHA `343a76952f9dcd6594674c3526ee03ee45b4d93e`. + +## When to use + +- After training, before export, or when comparing two checkpoints. +- When a user asks “how good is this agent?” or wants a leaderboard-style number. +- When you need a random-policy baseline on the same evaluation seeds. + +## Hard rules + +1. **Greedy, no learning.** Call `agent.getAction(observation, true)`. On `IgnitionEnv`, `inferStep()` is the greedy path: it does not `remember` or `train`. Never evaluate with `step()` / `train()` — those write the replay buffer and update weights (DQN also decays epsilon inside `train()`). +2. **Hold out eval seeds.** List training seeds and evaluation seeds **before** the run. They must be disjoint. Use at least three evaluation seeds. +3. **Several episodes.** For each eval seed, run `N` episodes. Report the vector of episode returns, then mean ± sample standard deviation (Bessel, `n-1`) or a 95% CI (`mean ± 1.96 * s / sqrt(n)`). +4. **Random baseline.** Run a seeded uniform-random policy on the **same** env seeds and episode count. Report `policy mean − random mean`. Do not treat a positive gap as solved. +5. **Budget first.** Write max env steps (and wall clock if you use one) before the first `getAction`. Paste raw returns, including failures. If the budget ends first, say so. +6. **No silent CartPole seeding.** `CartPoleEnv` has no seed argument; `reset()` uses `Math.random()`. For reproducibility, write the public `state` field from a seeded RNG (see the example), or wrap the env. Do not “fix” `packages/environments` in this skill’s PR. + +## Workflow + +### 1. Declare protocol (before any step) + +```ts +const TRAIN_SEEDS = [11, 29, 47] as const; // never used at eval time +const EVAL_SEEDS = [101, 202, 303] as const; // held-out, ≥ 3 +const EPISODES_PER_SEED = 3; +const MAX_STEPS_PER_EPISODE = 500; // CartPole done() cap +``` + +Copy this block into the report before you run anything. + +### 2. Freeze the policy + +Create or load the agent, then evaluate **only** with `greedy === true`. + +```ts +import { DQNAgent } from '@ignitionai/backend-tfjs'; +import { CartPoleEnv } from '@ignitionai/environments'; + +const agent = new DQNAgent({ + inputSize: 4, + actionSize: 2, + hiddenLayers: [8], + backend: 'cpu', + seed: 11, +}); + +const action = await agent.getAction(env.observe(), true); // greedy +``` + +To prove the policy stayed frozen, snapshot `DQNAgent.getModel().getWeights()` and `getState()` (`epsilon`, `trainStepCounter`, `bestReward`) before and after. They must match. + +`IgnitionEnv.inferStep()` is equivalent for a single transition: `performStep(true)` skips `remember` / `train`. Do **not** rely on it for seeded CartPole episodes: a terminal `inferStep` calls `env.reset()`, which is unseeded. + +### 3. Run `evaluate(agent, envFactory, seeds, episodes)` + +There is **no** public `evaluate()` on `@ignitionai/*`. Use the helper in `examples/skill-evaluate.ts` (or copy it). Proposed addition to core: same signature, documented in the PR, not implemented here. + +```ts +import { + evaluateWithRandomBaseline, + formatEvaluationReport, + seededCartPoleFactory, + EVAL_SEEDS, + EPISODES_PER_SEED, +} from '../../examples/skill-evaluate'; + +const report = await evaluateWithRandomBaseline( + agent, + seededCartPoleFactory, + EVAL_SEEDS, + EPISODES_PER_SEED, +); +console.log(formatEvaluationReport(report)); +``` + +`envFactory(seed)` must return a **new** env whose initial state is a deterministic function of `seed`. The helper derives per-episode seeds so `reset()` is never required for reproducibility. + +### 4. Fill the report template + +See [references/report-template.md](references/report-template.md). Required fields: train seeds, eval seeds, episodes per seed, budget, raw returns, mean ± sample std, 95% CI, random baseline, and an explicit “no convergence claimed” line unless you have a separate measured criterion. + +## CartPole specifics (this API) + +- Actions: `['push_left', 'push_right']`. +- Observation: `[x, xDot, theta, thetaDot]`. +- `reward()` is `0` when `done()`, else `1`. Sum rewards **after** each `step`. +- `done()` is true when `|theta| > 12°`, `|x| > 2.4`, or `stepCount >= 500`. There is no `truncated()`; the 500-step cap is treated as terminal by `IgnitionEnv`. + +## What not to do + +- Do not average only the last episode, or only the best seed. +- Do not evaluate with epsilon-greedy (`getAction(obs)` / `getAction(obs, false)`). +- Do not change package code to add seeding; report the gap. +- Do not paste internal hostnames, tokens, or machine paths into the skill or the PR. + +## Executable example + +- Helper: `examples/skill-evaluate.ts` +- Tests: `examples/skill-evaluate.test.ts` (real CartPole + DQN, no mocks) diff --git a/skills/ignition-evaluate/frontmatter.test.ts b/skills/ignition-evaluate/frontmatter.test.ts new file mode 100644 index 0000000..622db27 --- /dev/null +++ b/skills/ignition-evaluate/frontmatter.test.ts @@ -0,0 +1,26 @@ +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; + +const skillDir = dirname(fileURLToPath(import.meta.url)); +const folderName = 'ignition-evaluate'; +const skillPath = join(skillDir, 'SKILL.md'); + +describe('ignition-evaluate SKILL.md frontmatter', () => { + it('has name equal to the folder, description ≤ 1024 chars, body ≤ 500 lines', () => { + const source = readFileSync(skillPath, 'utf8'); + expect(source.startsWith('---\n')).toBe(true); + const end = source.indexOf('\n---\n', 4); + expect(end).toBeGreaterThan(0); + const frontmatter = source.slice(4, end); + const body = source.slice(end + 5); + const name = frontmatter.match(/^name:\s*(.+)$/m)?.[1]?.trim(); + const description = frontmatter.match(/^description:\s*(.+)$/m)?.[1]?.trim(); + expect(name).toBe(folderName); + expect(description).toBeTruthy(); + expect(description!.length).toBeGreaterThan(0); + expect(description!.length).toBeLessThanOrEqual(1024); + expect(body.split('\n').length).toBeLessThanOrEqual(500); + }); +}); diff --git a/skills/ignition-evaluate/references/report-template.md b/skills/ignition-evaluate/references/report-template.md new file mode 100644 index 0000000..ef98feb --- /dev/null +++ b/skills/ignition-evaluate/references/report-template.md @@ -0,0 +1,24 @@ +# Evaluation report template + +Fill this **after** declaring seeds and budget, and **after** the run. Paste raw numbers. Do not edit returns to look better. + +```text +# Policy evaluation report + +- Framework API: IgnitionRL @ignitionai/* on git SHA 343a76952f9dcd6594674c3526ee03ee45b4d93e +- Policy: frozen greedy (getAction(obs, true) / inferStep). Algorithm + checkpoint id: +- Train seeds (not evaluated): +- Eval seeds (≥ 3, disjoint from train): +- Episodes per eval seed: +- Max steps per episode / max env steps (budget): +- Wall-clock cap (if any) and whether it fired: +- Episode returns (all of them): +- Mean ± sample std (n=…): +- 95% CI: +- Random baseline mean ± sample std (same env seeds): +- Policy mean − random mean: +- Weight snapshot unchanged (yes/no): +- Convergence criterion (if any) and whether it was met: +``` + +If you did not define a numeric success threshold **before** the run, write: `No convergence is claimed.`