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
47 changes: 47 additions & 0 deletions examples/skill-train-infer-split.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { describe, expect, it } from 'vitest';
import {
TRAIN_INFER_SPLIT_BUDGET,
runTrainInferSplit,
type TrainInferSplitReport,
} from './skill-train-infer-split';

/**
* Declared BEFORE any protocol run. This budget is a compute cap, not a
* success criterion. No seed may claim CartPole convergence from these steps.
*/
const DECLARED_BUDGET = TRAIN_INFER_SPLIT_BUDGET;

describe('skill ignition-train-infer-split example', () => {
it('prints the declared budget and seeds before measuring', () => {
// eslint-disable-next-line no-console
console.log(JSON.stringify({ declaredBudget: DECLARED_BUDGET }, null, 2));
expect(DECLARED_BUDGET.seeds.length).toBeGreaterThanOrEqual(3);
expect(DECLARED_BUDGET.inferSteps).toBeGreaterThan(0);
expect(DECLARED_BUDGET.maxCpuMs).toBeLessThanOrEqual(60_000);
});

it(
'keeps weights frozen across inferStep, reloads greedy actions, and disposes tensors',
async () => {
const started = Date.now();
const reports: TrainInferSplitReport[] = [];

for (const seed of DECLARED_BUDGET.seeds) {
const report = await runTrainInferSplit(seed);
reports.push(report);
// eslint-disable-next-line no-console
console.log(JSON.stringify(report));
expect(report.weightsUnchangedAfterInfer).toBe(true);
expect(report.greedyActionsMatchAfterReload).toBe(true);
expect(report.tensorsAfterDispose).toBeLessThan(report.tensorsBeforeDispose);
expect(report.greedyBefore).toEqual(report.greedyAfter);
}

const elapsedMs = Date.now() - started;
// eslint-disable-next-line no-console
console.log(JSON.stringify({ elapsedMs, seedCount: reports.length }));
expect(elapsedMs).toBeLessThan(DECLARED_BUDGET.maxCpuMs);
},
TRAIN_INFER_SPLIT_BUDGET.maxCpuMs,
);
});
154 changes: 154 additions & 0 deletions examples/skill-train-infer-split.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import type { ModelStorageProvider } from '@ignitionai/storage';
import { IgnitionEnvTFJS, DQNAgent } from '@ignitionai/backend-tfjs';
import { CartPoleEnv } from '@ignitionai/environments';
import * as tf from '../packages/backend-tfjs/node_modules/@tensorflow/tfjs';

type LayersModel = tf.LayersModel;
type ModelArtifacts = tf.io.ModelArtifacts;

/**
* Declared before any training or inference run.
* Seeds and step counts are a compute budget, not a claim that CartPole solves.
*/
export const TRAIN_INFER_SPLIT_BUDGET = {
seeds: [11, 23, 47] as const,
trainSteps: 8,
inferSteps: 16,
hiddenLayers: [8] as const,
batchSize: 4,
memorySize: 32,
greedyObservations: [
[0, 0, 0, 0],
[0.1, 0, 0.02, 0],
[-0.1, 0, -0.02, 0],
[0.2, 0.1, 0.05, 0.01],
[-0.2, -0.1, -0.05, -0.01],
],
maxCpuMs: 60_000,
} as const;

export interface TrainInferSplitReport {
seed: number;
trainSteps: number;
inferSteps: number;
weightsUnchangedAfterInfer: boolean;
greedyActionsMatchAfterReload: boolean;
greedyBefore: number[];
greedyAfter: number[];
tensorsBeforeDispose: number;
tensorsAfterDispose: number;
}

export function createInMemoryModelStore(): ModelStorageProvider {
const artifacts = new Map<string, ModelArtifacts>();
return {
async save(modelId, model) {
await model.save(
tf.io.withSaveHandler(async (saved) => {
artifacts.set(modelId, saved);
return { modelArtifactsInfo: tf.io.getModelArtifactsInfoForJSON(saved) };
}),
);
return `memory://${modelId}`;
},
async load(modelId) {
const saved = artifacts.get(modelId);
if (!saved) {
throw new Error(`No saved model: ${modelId}`);
}
return tf.loadLayersModel(tf.io.fromMemory(saved));
},
async list() {
return [...artifacts.keys()].map((modelId) => ({ modelId, uri: `memory://${modelId}` }));
},
async delete(modelId) {
artifacts.delete(modelId);
},
async exists(modelId) {
return artifacts.has(modelId);
},
};
}

function asDqn(agent: unknown): DQNAgent {
if (!(agent instanceof DQNAgent)) {
throw new Error('Expected a DQNAgent created by IgnitionEnvTFJS.train("dqn")');
}
return agent;
}

function weightSnapshot(model: LayersModel): number[][] {
return model.getWeights().map((tensor) => Array.from(tensor.dataSync()));
}

function dqnOverrides(seed: number, storageProvider: ModelStorageProvider) {
return {
backend: 'cpu' as const,
hiddenLayers: [...TRAIN_INFER_SPLIT_BUDGET.hiddenLayers],
batchSize: TRAIN_INFER_SPLIT_BUDGET.batchSize,
memorySize: TRAIN_INFER_SPLIT_BUDGET.memorySize,
seed,
storageProvider,
};
}

/**
* Headless train → artefact → new-instance greedy inference, for one seed.
* Does not score episode returns and does not claim convergence.
*/
export async function runTrainInferSplit(seed: number): Promise<TrainInferSplitReport> {
await tf.setBackend('cpu');
const storageProvider = createInMemoryModelStore();
const trainWorld = new CartPoleEnv();
const trainer = new IgnitionEnvTFJS(trainWorld);
trainer.train('dqn', dqnOverrides(seed, storageProvider));
trainer.stop();

for (let i = 0; i < TRAIN_INFER_SPLIT_BUDGET.trainSteps; i++) {
await trainer.step();
}

const trained = asDqn(trainer.agent);
const weightsBeforeInfer = weightSnapshot(trained.getModel());
for (let i = 0; i < TRAIN_INFER_SPLIT_BUDGET.inferSteps; i++) {
await trainer.inferStep();
}
const weightsAfterInfer = weightSnapshot(trained.getModel());
const greedyBefore = await Promise.all(
TRAIN_INFER_SPLIT_BUDGET.greedyObservations.map((observation) =>
trained.getAction([...observation], true),
),
);

await trainer.save('skill-train-infer-split');
const tensorsBeforeDispose = tf.memory().numTensors;
trainer.stop();
trained.dispose();
const tensorsAfterDispose = tf.memory().numTensors;

const inferWorld = new CartPoleEnv();
const inference = new IgnitionEnvTFJS(inferWorld);
inference.train('dqn', dqnOverrides(seed, storageProvider));
inference.stop();
await inference.load('skill-train-infer-split');
const reloaded = asDqn(inference.agent);
const greedyAfter = await Promise.all(
TRAIN_INFER_SPLIT_BUDGET.greedyObservations.map((observation) =>
reloaded.getAction([...observation], true),
),
);
inference.stop();
reloaded.dispose();

return {
seed,
trainSteps: TRAIN_INFER_SPLIT_BUDGET.trainSteps,
inferSteps: TRAIN_INFER_SPLIT_BUDGET.inferSteps,
weightsUnchangedAfterInfer: JSON.stringify(weightsBeforeInfer) === JSON.stringify(weightsAfterInfer),
greedyActionsMatchAfterReload: JSON.stringify(greedyBefore) === JSON.stringify(greedyAfter),
greedyBefore,
greedyAfter,
tensorsBeforeDispose,
tensorsAfterDispose,
};
}
78 changes: 78 additions & 0 deletions skills/ignition-train-infer-split/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
---
name: ignition-train-infer-split
description: Use when splitting IgnitionRL training from frozen-policy inference — train() then infer()/inferStep()/getAction(obs, greedy), save/load into a new runner or process, keep the React Three Fiber render loop off the training loop, or dispose tensors after a headless artefact. Not for ONNX export or remote providers.
---

# Split training and inference

Train until you have weights worth freezing. Then run a **greedy** policy on a
separate loop, runner, or process. Do not keep calling `step()` (training) while
you believe you are serving a frozen policy.

## When to use

- A policy must stop learning (browser demo, second process, later session).
- R3F `useFrame` is dropping frames because training ran inside the render loop.
- You need identical greedy actions after `save` / `load` on a new `IgnitionEnvTFJS`.
- You need tensor cleanup via `agent.dispose()` measured with `tf.memory()`.

## Hard split

| Mode | Public entry | Learns? | Action selection |
|---|---|---|---|
| Train | `train()` then automatic ticks, or manual `step()` | Yes (`remember` + `agent.train`) | `getAction(obs, false)` (ε-greedy for DQN) |
| Infer | `infer()` automatic ticks, or manual `inferStep()` | No | `getAction(obs, true)` |
| Direct | `agent.getAction(obs, greedy)` | No, unless you also `remember`/`train` | Caller chooses `greedy` |

`inferStep()` is the one-step freeze: it requests a greedy action and **skips**
`remember` / `agent.train` (`packages/core/src/ignition-env.ts:77-101`).
`infer()` starts the same greedy path on the `setTimeout` loop (`:111-114`).

`IgnitionEnv` has **no** `dispose()`. Stop the loop, then dispose the agent:

```ts
runner.stop();
runner.agent?.dispose?.();
```

## Headless train → artefact → new instance

1. `new IgnitionEnvTFJS(world)` then `train('dqn', { backend: 'cpu', storageProvider, seed })`.
2. Call `stop()` immediately if you will drive steps yourself (`train()` starts the timer).
3. Budgeted `step()` calls. Do not claim return improvement unless you measure it.
4. `save(modelId)` — requires `storageProvider` on the DQN config.
5. New `IgnitionEnvTFJS`, `train(...)` to build a same-shaped agent, `stop()`, `load(modelId)`.
6. Compare `getAction(obs, true)` on a **fixed** observation set.
7. `dispose()` and compare `tf.memory().numTensors`.

Overrides apply only at agent creation. Resuming the same algorithm with
overrides throws (`ignition-env.ts:44-47`).

Executable protocol: `examples/skill-train-infer-split.ts` (seeds `11, 23, 47`).

## R3F: two loops, one env

Keep `train()` / `infer()` **outside** `useFrame`. The Canvas only **reads** env
fields. Shared mutable state on the `TrainingEnv` is the bridge; JavaScript is
single-threaded so the timers never overlap. Cleanup with `stop()` on unmount.
Details: `references/r3f-loop-split.md`.

## Signatures (dev `343a769`)

See `references/api.md` for `file:line` citations.

## Common mistakes

| Mistake | What actually happens |
|---|---|
| Leave `train()` running while “demoing” | Weights keep changing; ε-greedy still explores |
| `getAction(obs)` without `true` | DQN may explore (`dqn.ts:76-78`) |
| `load()` on an empty runner | Throws: agent must exist (`ignition-env.ts:201-204`) |
| Expect `load()` to restore ε | DQN `load` replaces weights only (`dqn.ts:251-253`) |
| `runner.dispose()` | Does not exist; use `stop()` + `agent.dispose?.()` |
| Mutate physics in `useFrame` | Render loop becomes the env; training sees a different world |
| ONNX / Hugging Face in this skill | Out of scope (other skills) |

## Out of scope

`@ignitionai/viz`, ONNX (`OnnxAgent`), remote checkpoints, changing package code.
61 changes: 61 additions & 0 deletions skills/ignition-train-infer-split/references/api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Public signatures used by ignition-train-infer-split

Base SHA `343a76952f9dcd6594674c3526ee03ee45b4d93e`. Nothing from unmerged PRs
#90, #77/#78, #39, or #42.

## Runner (`packages/core/src/ignition-env.ts`)

- `get agent()` — `:33-35`
- `train(algorithm?: AlgorithmType, overrides?: Record<string, unknown>): void` — `:41`
- `step(): Promise<StepResult>` — `:73` (learning transition)
- `inferStep(): Promise<StepResult>` — `:77` (greedy, no remember/train)
- `infer(): void` — `:111` (starts greedy `setTimeout` loop)
- `start(): void` — `:116` (training loop)
- `stop(): void` — `:147` (cancels future ticks; in-flight transition may finish)
- `reset(): void` — `:154`
- `setSpeed(multiplier: number): void` — `:164`
- `save(modelId: string, metadata?: Record<string, unknown>): Promise<string | void>` — `:184`
- `load(modelId: string): Promise<void>` — `:201`
- `lastError: Error | null` — `:14`
- `stepIntervalMs` / `stepsPerTick` — `:18-21`

There is no `IgnitionEnv.dispose()`. Switching algorithms eventually calls
`previous.dispose?.()` on the replaced agent (`:65`).

## Contracts (`packages/core/src/types.ts`)

- `AgentInterface.getAction(observation: number[], greedy?: boolean)` — `:54`
- `AgentInterface.remember` / `train` — `:55-56`
- `AgentInterface.dispose?(): void` — `:62`
- `AgentInterface.save?` / `load?` — `:69-72`
- `AgentInterface.getState?` / `setState?` — `:75-78`
- `StepResult` — `:43-49`
- `TrainingEnv` — `:95-112`
- `InferenceEnv` (`observe` + `step` only) — `:117-122`
- `AlgorithmType` — `:126`

## Validation (`packages/core/src/env-validation.ts`)

- `validateTrainingEnv` — `:9` (constructor of `IgnitionEnv`)
- `validateInferenceEnv` — `:42` (production-shaped env; runner still wants `TrainingEnv`)

## TF.js backend

- `IgnitionEnvTFJS` constructor — `packages/backend-tfjs/src/ignition-env-tfjs.ts:27`
- Factories `dqn` / `ppo` / `qtable` / `double-dqn` — `:8-13`
- `DQNAgent.getAction(state, greedy?)` — `packages/backend-tfjs/src/agents/dqn.ts:76`
- `DQNAgent.getModel(): tf.LayersModel` — `:96`
- `DQNAgent.save` / `load` (need `storageProvider`) — `:247-253`
- `DQNAgent.dispose()` — `:255`
- `DQNConfig.storageProvider?` — `packages/backend-tfjs/src/types.ts:24`
- `DQNConfig.seed?` / `backend?` — `:11-12`

## Storage + env

- `ModelStorageProvider.save/load` — `packages/storage/src/types.ts:14-23`
- `CartPoleEnv` — `packages/environments/src/cartpole.ts:23`

## Facade

- `IgnitionEnvTFJS`, `DQNAgent` re-exported from `packages/ignitionai/src/index.ts:22-27`
- `CartPoleEnv` — `:81-85`
39 changes: 39 additions & 0 deletions skills/ignition-train-infer-split/references/r3f-loop-split.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Training loop vs render loop (React Three Fiber)

Source of the pattern: `packages/web/content/en/r3f.mdx` on SHA `343a769`.
This skill does not import `@ignitionai/viz` (unmerged PRs #77/#78).

## Two independent timers on one thread

**Render (R3F)** — `requestAnimationFrame` / `useFrame`. Reads env fields
(`playerX`, …) and writes mesh transforms. Must not call `env.step()`,
`runner.step()`, or `runner.train()`.

**Train or infer (IgnitionEnv)** — `setTimeout` gated by `stepIntervalMs`
(default 50 ms) and `stepsPerTick`. Started by `train()` / `start()` /
`infer()`. Yields between ticks so the browser can paint.

They share the `TrainingEnv` instance. Single-threaded JS: the two callbacks
never run at the same time.

`setSpeed(1)` keeps one step per 50 ms (smoother frames). `setSpeed(50)` batches
many learning steps per yield (faster training, heavier frames).

## Lifecycle

```ts
useEffect(() => {
const runner = new IgnitionEnvTFJS(envRef.current);
runner.train('dqn');
return () => {
runner.stop();
runner.agent?.dispose?.();
};
}, []);
```

Keep the env in `useRef` so React re-renders do not construct a new world.

After training, switch the **same** runner with `infer()`, or `stop()` +
`save` and load into another instance / process. Serving a frozen policy from
inside `useFrame` via `getAction(obs, true)` is valid if you never `remember`.
Loading
Loading