|
| 1 | +import { IgnitionEnvTFJS } from '@ignitionai/backend-tfjs'; |
| 2 | +import { GridWorldEnv } from '@ignitionai/environments'; |
| 3 | + |
| 4 | +/** |
| 5 | + * Declared before any training or evaluation in this module's runners. |
| 6 | + * Do not change these after a measured run has started. |
| 7 | + */ |
| 8 | +export const TRAIN_SEEDS = [11, 22, 33] as const; |
| 9 | +export const TRAIN_EPISODES = 180; |
| 10 | +export const TRAIN_MAX_STEPS = 80; |
| 11 | +export const EVAL_EPISODES = 25; |
| 12 | +export const EVAL_MAX_STEPS = 80; |
| 13 | +export const GRID_SIZE = 5; |
| 14 | +export const QTABLE_OVERRIDES = { |
| 15 | + stateBins: 5, |
| 16 | + lr: 0.3, |
| 17 | + gamma: 0.99, |
| 18 | + epsilon: 1, |
| 19 | + epsilonDecay: 0.99, |
| 20 | + minEpsilon: 0.05, |
| 21 | +} as const; |
| 22 | + |
| 23 | +export interface SeedReturns { |
| 24 | + seed: number; |
| 25 | + trainedMean: number; |
| 26 | + randomMean: number; |
| 27 | + trainedEpisodes: number[]; |
| 28 | + randomEpisodes: number[]; |
| 29 | +} |
| 30 | + |
| 31 | +export async function withSeed<T>(seed: number, fn: () => Promise<T> | T): Promise<T> { |
| 32 | + const previous = Math.random; |
| 33 | + let state = seed >>> 0; |
| 34 | + Math.random = () => { |
| 35 | + state = (Math.imul(state, 1664525) + 1013904223) >>> 0; |
| 36 | + return state / 4294967296; |
| 37 | + }; |
| 38 | + try { |
| 39 | + return await fn(); |
| 40 | + } finally { |
| 41 | + Math.random = previous; |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +function sleep(ms: number): Promise<void> { |
| 46 | + return new Promise((resolve) => setTimeout(resolve, ms)); |
| 47 | +} |
| 48 | + |
| 49 | +async function runEpisode( |
| 50 | + env: IgnitionEnvTFJS, |
| 51 | + greedy: boolean, |
| 52 | + maxSteps: number, |
| 53 | +): Promise<number> { |
| 54 | + env.reset(); |
| 55 | + let total = 0; |
| 56 | + for (let step = 0; step < maxSteps; step++) { |
| 57 | + const result = greedy ? await env.inferStep() : await env.step(); |
| 58 | + total += result.reward; |
| 59 | + if (result.terminated || result.truncated) break; |
| 60 | + } |
| 61 | + return total; |
| 62 | +} |
| 63 | + |
| 64 | +async function randomPolicyReturns(episodes: number, maxSteps: number): Promise<number[]> { |
| 65 | + const world = new GridWorldEnv(GRID_SIZE); |
| 66 | + const returns: number[] = []; |
| 67 | + for (let ep = 0; ep < episodes; ep++) { |
| 68 | + world.reset(); |
| 69 | + let total = 0; |
| 70 | + for (let step = 0; step < maxSteps; step++) { |
| 71 | + world.step(Math.floor(Math.random() * world.actions.length)); |
| 72 | + total += world.reward(); |
| 73 | + if (world.done()) break; |
| 74 | + } |
| 75 | + returns.push(total); |
| 76 | + } |
| 77 | + return returns; |
| 78 | +} |
| 79 | + |
| 80 | +async function trainThenEvaluate(seed: number): Promise<SeedReturns> { |
| 81 | + const world = new GridWorldEnv(GRID_SIZE); |
| 82 | + const env = new IgnitionEnvTFJS(world); |
| 83 | + env.train('qtable', { ...QTABLE_OVERRIDES }); |
| 84 | + env.stop(); |
| 85 | + |
| 86 | + const trainedEpisodes: number[] = []; |
| 87 | + for (let ep = 0; ep < TRAIN_EPISODES; ep++) { |
| 88 | + trainedEpisodes.push(await runEpisode(env, false, TRAIN_MAX_STEPS)); |
| 89 | + } |
| 90 | + |
| 91 | + const evalTrained: number[] = []; |
| 92 | + for (let ep = 0; ep < EVAL_EPISODES; ep++) { |
| 93 | + evalTrained.push(await runEpisode(env, true, EVAL_MAX_STEPS)); |
| 94 | + } |
| 95 | + |
| 96 | + const randomEpisodes = await randomPolicyReturns(EVAL_EPISODES, EVAL_MAX_STEPS); |
| 97 | + env.stop(); |
| 98 | + env.agent?.dispose?.(); |
| 99 | + |
| 100 | + const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / xs.length; |
| 101 | + return { |
| 102 | + seed, |
| 103 | + trainedMean: mean(evalTrained), |
| 104 | + randomMean: mean(randomEpisodes), |
| 105 | + trainedEpisodes: evalTrained, |
| 106 | + randomEpisodes, |
| 107 | + }; |
| 108 | +} |
| 109 | + |
| 110 | +export async function measureQTableVsRandom(): Promise<{ |
| 111 | + seeds: typeof TRAIN_SEEDS; |
| 112 | + budget: { |
| 113 | + trainEpisodes: number; |
| 114 | + trainMaxSteps: number; |
| 115 | + evalEpisodes: number; |
| 116 | + evalMaxSteps: number; |
| 117 | + gridSize: number; |
| 118 | + }; |
| 119 | + perSeed: SeedReturns[]; |
| 120 | + trainedMean: number; |
| 121 | + randomMean: number; |
| 122 | +}> { |
| 123 | + const perSeed: SeedReturns[] = []; |
| 124 | + for (const seed of TRAIN_SEEDS) { |
| 125 | + perSeed.push(await withSeed(seed, () => trainThenEvaluate(seed))); |
| 126 | + } |
| 127 | + const trainedMean = perSeed.reduce((a, r) => a + r.trainedMean, 0) / perSeed.length; |
| 128 | + const randomMean = perSeed.reduce((a, r) => a + r.randomMean, 0) / perSeed.length; |
| 129 | + return { |
| 130 | + seeds: TRAIN_SEEDS, |
| 131 | + budget: { |
| 132 | + trainEpisodes: TRAIN_EPISODES, |
| 133 | + trainMaxSteps: TRAIN_MAX_STEPS, |
| 134 | + evalEpisodes: EVAL_EPISODES, |
| 135 | + evalMaxSteps: EVAL_MAX_STEPS, |
| 136 | + gridSize: GRID_SIZE, |
| 137 | + }, |
| 138 | + perSeed, |
| 139 | + trainedMean, |
| 140 | + randomMean, |
| 141 | + }; |
| 142 | +} |
| 143 | + |
| 144 | +export async function assertNoStepsAfterStop(): Promise<{ |
| 145 | + stepCountAtStop: number; |
| 146 | + stepCountAfterSettle: number; |
| 147 | + stepCountAfterWait: number; |
| 148 | +}> { |
| 149 | + const env = new IgnitionEnvTFJS(new GridWorldEnv(GRID_SIZE)); |
| 150 | + env.setSpeed(1); |
| 151 | + env.train('qtable', { ...QTABLE_OVERRIDES }); |
| 152 | + |
| 153 | + const deadline = Date.now() + 2000; |
| 154 | + while (env.stepCount < 2 && Date.now() < deadline) { |
| 155 | + await sleep(10); |
| 156 | + } |
| 157 | + if (env.stepCount < 2) { |
| 158 | + throw new Error(`automatic loop did not step before stop(); lastError=${String(env.lastError)}`); |
| 159 | + } |
| 160 | + |
| 161 | + env.stop(); |
| 162 | + const stepCountAtStop = env.stepCount; |
| 163 | + await sleep(20); |
| 164 | + const stepCountAfterSettle = env.stepCount; |
| 165 | + await sleep(200); |
| 166 | + const stepCountAfterWait = env.stepCount; |
| 167 | + env.agent?.dispose?.(); |
| 168 | + return { stepCountAtStop, stepCountAfterSettle, stepCountAfterWait }; |
| 169 | +} |
0 commit comments