Skip to content

ONNX policy export

Train in Python, export the policy to ONNX, and load it with ONNXAgent in Node.js or a browser. The exported model does not include game rules, game-specific observation construction, action masks, or action dispatch.

Train and export a Blackjack policy

The Python bridge guide shows how to run the single-agent Blackjack bridge and ai/python/examples/train_sb3.py. It produces blackjack_ppo.zip. Install ONNX tooling in the same virtual environment:

python -m pip install onnx onnxruntime
from hypertoken import export_sb3_to_onnx, verify_onnx

path = export_sb3_to_onnx(
    "blackjack_ppo.zip",
    "models/blackjack_policy.onnx",
    observation_shape=(7,),
    metadata={
        "env": "blackjack",
        "actions": ["hit", "stand", "double", "split", "insurance"],
        "observation_features": [
            "handValue", "dealerUpcard", "isSoft", "canDouble", "canSplit",
            "canInsurance", "deckRatio",
        ],
    },
)
assert verify_onnx(path)

export_sb3_to_onnx() takes a saved SB3 model path, an output path, the observation shape, optional action_type (discrete or continuous), opset_version, and metadata. PPO and A2C support the simple policy heads used here. For DQN the discrete scores are derived from Q-values and preserve greedy ranking; sampling them does not reproduce SB3's exploration policy. SAC exports its deterministic actor output for action_type="continuous". A continuous consumer must apply any environment-specific clipping or rescaling. For an arbitrary PyTorch model, call export_pytorch_to_onnx(model, output_path, observation_shape, ...) with a model that accepts batched observations and returns a single output tensor. verify_onnx(path, test_input=...) can also run a sample batch through Python ONNX Runtime.

Use a policy in TypeScript

ai/interface/ONNXAgent.ts loads ONNX Runtime only on load(). Install onnxruntime-node for Node.js or onnxruntime-web for a browser bundle, or expose the browser build as window.ort. Neither runtime is required to use other HyperToken interfaces. Browser models and metadata must be accessible over HTTP(S); serve model assets and configure CORS if they are on a different origin.

The following assumes the script is at the repository root, the model above has been exported, and onnxruntime-node is installed:

import { ONNXAgent } from "./ai/interface/ONNXAgent.js";
import { BlackjackAEC } from "./examples/blackjack/BlackjackAEC.js";

const policy = new ONNXAgent();
await policy.load("models/blackjack_policy.onnx");

const env = new BlackjackAEC({ numAgents: 1 });
try {
  await env.reset(42);
  for (const agent of env.agentIteration()) {
    const probabilities = await policy.predict(env.observe(agent));
    const mask = env.actionMask(agent);
    const legal = Array.from(mask.keys()).filter(i => mask[i]);
    const best = legal.reduce((a, b) => probabilities[b] > probabilities[a] ? b : a);
    await env.step(best);
  }
  console.log(env.rewards());
} finally {
  env.close();
  policy.dispose();
}

predict() accepts a flat numeric observation and returns the first output tensor's data. selectAction() uses "argmax" by default, or "sample" for normalized probability vectors. It does not mask actions; use your environment's current legality rules as shown above.

For an Engine-managed agent, supply an observationExtractor and an actionMap mapping output indexes to your existing registered action types. think(engine, agent) returns a decision for the engine agent to dispatch. If a game needs payloads or legality checks, adapt the policy decision before dispatch instead of assuming the model's labels are registered engine actions.

Metadata and troubleshooting

The exporter writes a same-basename .json sidecar containing optional labels and _export_info (algorithm, observation shape, action type, and opset). load() tries that sidecar automatically, or accepts an explicit path. For Engine-managed actions, explicit mapping entries take precedence over metadata mappings.

  • Input shape mismatch: Use the same observation length, feature order, and normalization as training. The 7-feature Blackjack AEC and 19-feature TypeScript Gym observations are not interchangeable.
  • Output mismatch: Compare a fixed unmasked sample in Python and TypeScript first, then apply the same legal-action mask and tie-breaking.
  • Slow inference: Measure after warm-up and keep one inference session loaded instead of reloading per turn.

See ONNX Runtime JavaScript and Stable-Baselines3 for runtime-specific setup.