Skip to content

armgit / laya

Public Imported from GitHub
0

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.

feat(rust): add options, model config and artifact resolution with opt-in download

kevin-gatimua3abad584e43
diff --git a/laya-rust/MODELS.md b/laya-rust/MODELS.md
new file mode 100644
index 00000000..e864beff
--- /dev/null
+++ b/laya-rust/MODELS.md
@@ -0,0 +1,469 @@
+# Laya Models: Obtaining the ONNX Artifacts
+
+The Laya Rust SDK ([README](https://github.com/NandhaKishorM/laya/blob/main/laya-rust/README.md)), a Rust port of the Laya Python SDK, runs
+**ONNX** models through ONNX Runtime, not PyTorch weights, so no Python process is needed at runtime. This
+guide explains how to get those ONNX artifacts: either convert them yourself
+from the published PyTorch checkpoints (works today), or let the SDK download
+them once they are published.
+
+**Quick path:** create a venv, `pip install -e .` plus the exporter's
+dependencies, run `python laya-rust/tools/export_onnx.py --model all`, and set `LAYA_ONNX_ROOT` to the
+resulting `onnx/` folder. [Section 1](#1-export-the-onnx-model-step-by-step)
+walks through each step.
+
+The ONNX export is not on Hugging Face yet, so exporting it yourself is the
+only way to get the artifacts today. Downloading
+([section 6](#6-downloading-future-once-published)) will work without code
+changes once they are published.
+
+---
+
+## 1. Export the ONNX model (step by step)
+
+You need Python 3.9+ and about 2.5 GB free per checkpoint (6.7 GB for all
+three, counting the Hugging Face download cache; see step 3). Run everything
+from the **repository root** unless a step says otherwise.
+
+### Step 1: Create a virtual environment and install
+
+The dynamo-based ONNX exporter requires `torch >= 2.9`.
+Tested versions (from the repo's `.venv`):
+
+| Package | Tested version |
+|---|---|
+| `torch` | 2.14.0 |
+| `onnx` | 1.23.0 |
+| `onnxscript` | 0.7.2 |
+| `onnxruntime` | 1.30.0 |
+| `transformers` | 5.17.0 |
+| `safetensors` | 0.8.0 |
+| `huggingface_hub` | 1.32.0 |
+| `numpy` | 2.5.3 |
+
+The `laya` Python package itself must be importable, so the commands below
+also install the repository with `pip install -e .`.
+
+```powershell
+# PowerShell
+python -m venv .venv
+.venv\Scripts\Activate.ps1
+pip install "torch>=2.9" onnx onnxscript onnxruntime transformers safetensors huggingface_hub numpy
+pip install -e .
+```
+
+```bash
+# Bash / WSL
+python -m venv .venv && source .venv/bin/activate
+pip install "torch>=2.9" onnx onnxscript onnxruntime transformers safetensors huggingface_hub numpy
+pip install -e .
+```
+
+### Step 2 (optional): Hugging Face authentication
+
+The `convaiinnovations/laya` checkpoints are public and need no token. For
+gated or private repos, supply a token:
+
+```powershell
+$env:HF_TOKEN = "hf_..." # PowerShell — persists for the session
+```
+
+```bash
+export HF_TOKEN="hf_..." # Bash
+```
+
+Or pass `--token hf_...` directly to the script.
+
+### Step 3 (optional): Disk space and HF\_HOME
+
+The exporter calls `huggingface_hub.snapshot_download` to fetch the PyTorch
+weights. If the default HuggingFace cache (`%LOCALAPPDATA%\HuggingFace` on
+Windows, `~/.cache/huggingface` elsewhere) is on a volume without enough
+space, redirect it with `HF_HOME`.
+
+| Checkpoint | PyTorch weights (HF cache) | ONNX output | Total |
+|---|---|---|---|
+| `multilingual` | ~644 MB | ~1.2 GB | ~1.9 GB |
+| `english` | ~842 MB | ~1.6 GB | ~2.5 GB |
+| `typed-decisions` | ~842 MB | ~1.6 GB | ~2.5 GB |
+| all three | ~2.3 GB | ~4.4 GB | ~6.7 GB |
+
+```powershell
+$env:HF_HOME = "C:\hf_cache" # PowerShell
+```
+
+```bash
+export HF_HOME=/d/hf_cache # Bash
+```
+
+### Step 4: Export
+
+The script downloads the PyTorch checkpoint from `convaiinnovations/laya`
+(public, no token needed) and writes `onnx/<checkpoint>/` under the repository
+root. The multilingual checkpoint takes about 9 minutes on CPU.
+
+```powershell
+# Export the multilingual checkpoint to onnx/multilingual/ (~9 min on CPU)
+python laya-rust/tools/export_onnx.py --model multilingual
+
+# Export and verify ONNX parity against PyTorch (~9 min + ~5 min verify)
+python laya-rust/tools/export_onnx.py --model multilingual --verify
+
+# Export typed-decisions with parity check (~30 min total)
+python laya-rust/tools/export_onnx.py --model typed-decisions --verify
+
+# Export all three checkpoints
+python laya-rust/tools/export_onnx.py --model all
+
+# Export to a custom directory (no --force needed; leaves onnx/ untouched)
+python laya-rust/tools/export_onnx.py --model multilingual --out C:\tmp\laya-test --verify
+
+# Re-export, overwriting an existing artifact
+python laya-rust/tools/export_onnx.py --model multilingual --force
+
+# Export a local checkpoint directory (must contain rl_agent_config.json)
+python laya-rust/tools/export_onnx.py C:\path\to\checkpoint --out onnx\my-model
+```
+
+The script refuses to overwrite `<out>/<name>/model.onnx` if it already exists.
+Pass `--force` to overwrite. The check happens before any download, so a
+refusal wastes no time or bandwidth.
+
+The `--verify` flag runs a self-check against the `fixtures.npz` reference
+outputs and a 36-combination shape sweep (`6 seq_lens × 2 batch_sizes × 3
+marker_counts`). Skip it if you just need the files quickly; run it before
+publishing.
+
+### Step 5: Point the SDK at the export
+
+The quickest way — no code changes.
+
+**Single checkpoint (legacy, multilingual only):**
+
+```powershell
+# PowerShell
+$env:LAYA_ONNX_DIR = "C:\models\laya\multilingual"
+```
+
+```bash
+# Bash
+export LAYA_ONNX_DIR=/c/models/laya/multilingual
+```
+
+**All three checkpoints at once:**
+
+If you export all three under a common parent directory (e.g. `onnx/multilingual`,
+`onnx/english`, `onnx/typed-decisions`), point `LAYA_ONNX_ROOT` at the parent:
+
+```powershell
+# PowerShell
+$env:LAYA_ONNX_ROOT = "C:\models\laya"
+```
+
+```bash
+# Bash
+export LAYA_ONNX_ROOT=/c/models/laya
+```
+
+The SDK appends the checkpoint subdirectory name automatically
+(`multilingual`, `english`, or `typed-decisions`).
+
+Use absolute paths. Relative paths depend on the working directory, which
+is not reliable across test runners and hosts.
+
+Or pass the checkpoint folder in code with `LayaOptions::model_directory` /
+`LayaEngine::from_directory(...)` (see [section 7](#7-using-the-artifact-in-code-and-tests)).
+
+### Step 6: Check it works
+
+Run the quickstart sample against the export. From `laya-rust/`, the default
+export location is `../onnx/<checkpoint>`:
+
+```bash
+cargo run --release -p laya-sample -- --model-dir ../onnx/multilingual
+cargo run --release -p laya-sample -- --checkpoint english --model-dir ../onnx/english
+cargo run --release -p laya-sample -- --checkpoint typed-decisions --model-dir ../onnx/typed-decisions
+```
+
+---
+
+## 2. The three checkpoints
+
+All three are published under the bundle repo `convaiinnovations/laya`; the
+exporter downloads from there by default.
+
+| Name | Bundle subfolder | Encoder | Params | max\_len | head\_max\_len | model.onnx | model.onnx.data |
+|---|---|---|---|---|---|---|---|
+| `english` | (root) | `answerdotai/ModernBERT-large` | 421 M | 512 | 192 | 3.2 MB | 1.57 GB |
+| `multilingual` | `multilingual` | `jhu-clsp/mmBERT-base` | 322 M | 1024 | 256 | 2.5 MB | 1.20 GB |
+| `typed-decisions` | `typed-decisions` | `answerdotai/ModernBERT-large` | 421 M | 1024 | 256 | 2.6 MB | 1.57 GB |
+
+Each checkpoint also has a standalone repo (`convaiinnovations/laya-multilingual`,
+etc.) that mirrors the same weights.
+
+---
+
+## 3. SDK support status
+
+**All three checkpoints are fully supported by the Rust SDK.**
+
+`HfTokenizer` resolves special-token ids from `tokenizer_config.json` +
+`tokenizer.json` at load time, so it works for both the mmBERT-style tokens
+(`<pad>=0`, `<bos>=2`, `<eos>=1`, `<unk>=3`, `<mask>=4`) and the ModernBERT
+ByteLevel-BPE tokens (`[PAD]=50283`, `[CLS]=50281`, `[SEP]=50282`,
+`[UNK]=50280`, `[MASK]=50284`). Select a checkpoint with `LayaOptions::checkpoint`
+or point `LayaOptions::model_directory` / `LAYA_ONNX_DIR` at the artifact
+directory directly.
+
+```rust,no_run
+use laya::{LayaCheckpoint, LayaEngine, LayaOptions};
+
+// explicit checkpoint selection
+let engine = LayaEngine::create(LayaOptions {
+ checkpoint: LayaCheckpoint::English,
+ ..Default::default()
+})?;
+
+// or point directly at the directory
+let engine = LayaEngine::from_directory("/models/laya/english")?;
+```
+
+---
+
+## 4. Output layout
+
+The Rust SDK auto-detects two different export layouts for a checkpoint directory. Whichever one
+is present, only that directory needs to be pointed at — `ModelArtifacts::layout()` reports which
+one it found.
+
+### Fused layout (`export_onnx.py`, this section's exporter)
+
+Each model is written to `<out>/<name>/`:
+
+```
+<out>/<name>/
+ model.onnx # ONNX graph (~2.5–3.2 MB, opset 18)
+ model.onnx.data # External weight sidecar (~1.2–1.6 GB)
+ rl_agent_config.json # Sequence lengths and temperature calibration
+ tokenizer/
+ tokenizer.json # HuggingFace tokenizer (post_processor kept intact)
+ tokenizer_config.json # optional but recommended; fetched by download
+ fixtures.npz # PyTorch reference outputs (used by --verify; not needed by SDK)
+```
+
+Inputs: `input_ids`, `attention_mask`, `marker_pos`, `marker_mask`, `qtype` (shape `[B]`).
+Outputs: `logits`, `act_logits`.
+
+**`model.onnx` and `model.onnx.data` must stay in the same directory.** ONNX
+Runtime resolves the external-data file relative to the graph file, which is
+also why the API takes a *directory* rather than a file. Moving `model.onnx`
+alone produces a baffling "missing initializer" error.
+
+**Tokenizer post\_processor:** `tokenizer.json` retains its `TemplateProcessing`
+post\_processor. The Rust SDK needs no stripped copy: the `tokenizers` crate
+encodes without special tokens directly.
+
+### Split layout (laya-ts's exporter)
+
+This is the layout produced by laya-ts's own ONNX exporter — a graph split into a text encoder and
+a small prediction head instead of one fused graph:
+
+```
+<out>/<name>/
+ encoder.onnx # text -> hidden states: inputs input_ids, attention_mask;
+ # output last_hidden_state
+ encoder.onnx.data # encoder weights (~1.2-1.6 GB)
+ head.onnx # hidden states + marker metadata -> logits: inputs hidden_states,
+ # marker_pos, marker_mask, qtype (shape [B, 1]), attention_mask;
+ # outputs logits, act_logits
+ head.onnx.data # head weights (~60-110 MB)
+ rl_agent_config.json # same schema as the fused layout
+ tokenizer.json # HuggingFace tokenizer, at the directory root (no tokenizer/ nesting)
+```
+
+Each `.data` file must stay next to its graph, for the same reason as `model.onnx.data`.
+
+There is no sibling `tokenizer_config.json` in this layout. The SDK instead takes CLS and SEP
+from `tokenizer.json`'s own `post_processor` template (`[CLS] $A [SEP]`, or `<bos> $A <eos>` for
+multilingual), and resolves `pad`/`mask`/`unk` from `added_tokens` by matching the usual content
+spellings (`[PAD]`/`[MASK]`/`[UNK]` or `<pad>`/`<mask>`/`<unk>`); see
+`src/tokenization/hf_tokenizer.rs`. A spelling guess alone is not safe for CLS/SEP: the
+multilingual vocabulary also contains `<s>`/`</s>`, which are not its CLS/SEP. `qtype`'s declared rank (`[B]` vs. `[B, 1]`) is read from each
+graph's own input metadata rather than assumed from the layout, so the same binding code drives
+both `head.onnx` here and `model.onnx` in the fused layout.
+
+The two `ort` sessions (encoder, head) are run in sequence inside one `LayaEngine::run` call: the
+encoder's `last_hidden_state` output is fed into the head's `hidden_states` input, with no
+intermediate copy back into caller-visible state.
+
+If a directory somehow has both a complete fused export and a complete split export, the fused
+layout wins.
+
+---
+
+## 5. Where the engine looks
+
+`ModelArtifacts::resolve` (called for you by `LayaEngine::create`) looks for the directory in this
+order:
+
+1. `LayaOptions::model_directory`
+2. the `LAYA_ONNX_DIR` environment variable — maps to the **multilingual** checkpoint only (legacy)
+3. `LAYA_ONNX_ROOT/<checkpoint-subdir>` — the recommended multi-checkpoint path (`multilingual`,
+ `english`, or `typed-decisions`)
+4. the local cache, `<cache_directory>/<checkpoint-subdir>`. `cache_directory` defaults to
+ `%LOCALAPPDATA%\laya\onnx` on Windows and `~/.cache/laya/onnx` elsewhere.
+5. a download into that cache, only if `LayaOptions::allow_download = true`
+
+Once a directory is chosen, the SDK detects which of the two layouts from
+[section 4](#4-output-layout) it holds: `model.onnx` present means fused; otherwise both
+`encoder.onnx` and `head.onnx` must be present for the split layout. If a directory has neither —
+or half of a split export (only one of `encoder.onnx` / `head.onnx`) — resolution fails with a
+`LayaError::MissingFile` naming what was expected for both layouts, rather than a generic "model
+not found". Downloading (step 5 above, and [section 6](#6-downloading-future-once-published))
+handles either layout: it sends a `HEAD` request for `model.onnx` and fetches the fused files if it
+exists, otherwise the split files if both `encoder.onnx` and `head.onnx` exist.
+
+If none of these has the artifact, resolution fails with `LayaError::ArtifactsNotFound`, whose
+message lists every location it tried and what to do next.
+
+---
+
+## 6. Downloading (future, once published)
+
+**The ONNX artifacts have not been uploaded to HuggingFace yet.** The
+`convaiinnovations/laya` repository ships PyTorch weights
+(`model.safetensors`), which the SDK cannot load. Until the ONNX files are
+uploaded, `allow_download: true` fails immediately with a 404 and an explanatory
+message.
+
+Downloading is **opt-in**. Nothing touches the network unless you ask for it.
+Once the files are published (see section 8), enabling the download requires only:
+
+```rust,no_run
+use laya::{ArtifactDownloadProgress, LayaEngine, LayaOptions};
+use std::sync::Arc;
+
+let engine = LayaEngine::create(LayaOptions {
+ allow_download: true, // fetch from Hugging Face into the cache, once
+ // hugging_face_token: None is the default (falls back to HF_TOKEN); Some(String::new()) disables auth
+ download_progress: Some(Arc::new(|p: ArtifactDownloadProgress| {
+ eprintln!("{}: {}/{:?}", p.file_name, p.bytes_received, p.total_bytes);
+ })),
+ ..Default::default()
+})?;
+```
+
+The SDK downloads the files of whichever layout the repository publishes (five for fused; for
+split, the two graphs, their `.data` sidecars when present, `rl_agent_config.json` and
+`tokenizer.json`) into the per-user cache, and skips the download on subsequent runs if the
+directory is already complete:
+
+- Windows: `%LOCALAPPDATA%\laya\onnx\multilingual`
+- Linux / macOS: `~/.cache/laya/onnx/multilingual`
+
+Override the cache root with `LayaOptions::cache_directory`.
+
+Without the `download` cargo feature (`--no-default-features`), setting `allow_download = true`
+returns a clear `LayaError::Download` explaining that the crate was built without it, rather than
+silently failing to compile a network call.
+
+---
+
+## 7. Using the artifact in code and tests
+
+### Create the engine in code
+
+```rust,no_run
+use laya::{LayaCheckpoint, LayaEngine, LayaOptions};
+
+// From a known directory (all checkpoints work)
+let engine = LayaEngine::from_directory("/models/laya/multilingual")?;
+
+// English checkpoint via LayaOptions::checkpoint
+let engine = LayaEngine::create(LayaOptions {
+ checkpoint: LayaCheckpoint::English,
+ model_directory: Some("/models/laya/english".into()),
+ intra_op_threads: Some(4), // pin in containers with a CPU limit
+ ..Default::default()
+})?;
+```
+
+### Run the tests
+
+Run from `laya-rust/`. The tests find the repository-root `onnx/<checkpoint>`
+folders by walking up from the crate, or use `LAYA_ONNX_ROOT` / `LAYA_ONNX_DIR`.
+Checkpoints whose artifacts are missing are skipped with a `skip:` line;
+model-backed tests should run in `--release`:
+
+```bash
+LAYA_ONNX_ROOT=/c/models/laya cargo test --release --workspace
+```
+
+---
+
+## 8. Publishing to HuggingFace (maintainers only)
+
+**Requires write access to `convaiinnovations/laya`.**
+
+The SDK downloader fetches five files per checkpoint from `convaiinnovations/laya`.
+A maintainer must upload the following paths for each checkpoint:
+
+| Checkpoint | HF path in repo |
+|---|---|
+| `multilingual` | `multilingual/<files>` |
+| `english` | `<files>` (bundle root — no subfolder) |
+| `typed-decisions` | `typed-decisions/<files>` |
+
+The five files per checkpoint are:
+`model.onnx`, `model.onnx.data`, `rl_agent_config.json`,
+`tokenizer/tokenizer.json`, `tokenizer/tokenizer_config.json`.
+
+`onnx/` is gitignored (the weights exceed GitHub's 100 MB hard limit), so
+upload must go through the HuggingFace Hub CLI or Python API directly.
+
+Run from the repo root after completing `--verify`:
+
+```bash
+# huggingface-cli (pip install huggingface_hub)
+huggingface-cli upload convaiinnovations/laya onnx/multilingual multilingual \
+ --repo-type model --token hf_...
+huggingface-cli upload convaiinnovations/laya onnx/english . \
+ --repo-type model --token hf_...
+huggingface-cli upload convaiinnovations/laya onnx/typed-decisions typed-decisions \
+ --repo-type model --token hf_...
+```
+
+Once these files are live, `allow_download: true` with the matching checkpoint
+works without any code changes.
+
+---
+
+## 9. Troubleshooting
+
+**404 on download (`allow_download`)**
+The ONNX artifacts have not been published yet (see section 8). Export locally with
+`laya-rust/tools/export_onnx.py` and point the SDK at the result via `LAYA_ONNX_DIR` or
+`LayaOptions::model_directory`.
+
+**Low disk space during export**
+Set `HF_HOME` to a volume with enough free space before running the exporter
+(see the disk-space table in [section 1, step 3](#step-3-optional-disk-space-and-hf_home)). `--out` controls where the ONNX output lands.
+
+**`model.onnx.data` not found / "missing initializer" in ONNX Runtime**
+The sidecar must sit beside `model.onnx`. Copy both files together; the SDK
+error message already reminds you of this: *"both model.onnx and model.onnx.data
+must reside in the same directory."*
+
+**"already exists, pass --force"**
+`<out>/<name>/model.onnx` is present from a previous run. Use `--force` to
+overwrite in place, or use `--out` to write to a separate directory.
+
+**Wrong-checkpoint error (tokenizer/config mismatch)**
+`tokenizer.json` and `tokenizer_config.json` are from different checkpoints
+(e.g., the tokenizer from `english` with the config from `multilingual`). The
+error message names the missing token. Keep the two files together as exported.
+
+**Windows console encoding during export**
+The dynamo exporter logs Unicode emoji (✅, etc.) that crash a non-UTF-8 Windows
+console. The script reconfigures `stdout`/`stderr` to UTF-8 with replacement
+automatically. Any unrecognised emoji appears as `?`; the export continues
+normally.
diff --git a/laya-rust/src/laya_config.rs b/laya-rust/src/laya_config.rs
new file mode 100644
index 00000000..5bd456b8
--- /dev/null
+++ b/laya-rust/src/laya_config.rs
@@ -0,0 +1,116 @@
+//! The contents of a checkpoint's `rl_agent_config.json`. Ports the config shape `laya/agent.py`'s
+//! `Agent.system_one` reads via `cfg.get(...)`.
+//!
+//! Defaults match Python's `cfg.get(...)` fallbacks in `Agent.system_one`, not the shipped
+//! multilingual values, so a config missing a key behaves the same in both runtimes.
+
+use crate::calibration::Calibration;
+use crate::error::Result;
+use serde_json::Value;
+use std::collections::HashMap;
+use std::path::Path;
+
+/// The parsed and clamped contents of `rl_agent_config.json`.
+#[derive(Debug, Clone)]
+pub struct LayaConfig {
+ /// The encoder the checkpoint was trained on, for information only.
+ pub encoder: Option<String>,
+ /// Maximum total sequence length.
+ pub max_len: usize,
+ /// Token budget for the question head: instructions plus all option fragments.
+ pub head_max_len: usize,
+ /// Per-question-type temperature, clamped to the usable range. Always 3 entries.
+ pub temperature: Vec<f64>,
+ /// Per `(type, option-count)` bucket temperature, clamped. Keys as
+ /// [`Calibration::temp_bucket`] builds them.
+ pub temperature_by_options: HashMap<String, f64>,
+ /// What the checkpoint shipped, before clamping.
+ pub temperature_raw: Vec<f64>,
+ /// What the checkpoint shipped, before clamping.
+ pub temperature_by_options_raw: HashMap<String, f64>,
+ /// Descriptions of every temperature that had to be clamped, empty when none were. A
+ /// non-empty list means confidence from those buckets is uncalibrated and worth surfacing to
+ /// the caller (this crate does not log; the caller decides how to report it).
+ pub clamped_temperatures: Vec<String>,
+}
+
+impl LayaConfig {
+ /// Read a config from a `rl_agent_config.json` file.
+ pub fn load(path: impl AsRef<Path>) -> Result<Self> {
+ Self::parse(&std::fs::read_to_string(path)?)
+ }
+
+ /// Parse a config from JSON text.
+ pub fn parse(json: &str) -> Result<Self> {
+ let root: Value = serde_json::from_str(json)?;
+
+ let mut temperature_raw: Vec<f64> = root
+ .get("temperature")
+ .and_then(Value::as_array)
+ .map(|arr| arr.iter().map(|v| v.as_f64().unwrap_or(f64::NAN)).collect())
+ .unwrap_or_default();
+ // Python indexes self.temperature[qtype] for qtype 0..2, so a short list would be an
+ // IndexError there; pad to 3 with the neutral value rather than failing later per-question.
+ while temperature_raw.len() < 3 {
+ temperature_raw.push(1.0);
+ }
+
+ let temperature_by_options_raw: HashMap<String, f64> = root
+ .get("temperature_by_options")
+ .and_then(Value::as_object)
+ .map(|obj| {
+ obj.iter()
+ .map(|(k, v)| (k.clone(), v.as_f64().unwrap_or(f64::NAN)))
+ .collect()
+ })
+ .unwrap_or_default();
+
+ let encoder = root
+ .get("encoder")
+ .and_then(Value::as_str)
+ .map(str::to_string);
+ let max_len = root
+ .get("max_len")
+ .and_then(Value::as_u64)
+ .map(|v| v as usize)
+ .unwrap_or(512);
+ let head_max_len = root
+ .get("head_max_len")
+ .and_then(Value::as_u64)
+ .map(|v| v as usize)
+ .unwrap_or(192);
+
+ let temperature: Vec<f64> = temperature_raw
+ .iter()
+ .copied()
+ .map(Calibration::clamp_temperature)
+ .collect();
+ let temperature_by_options: HashMap<String, f64> = temperature_by_options_raw
+ .iter()
+ .map(|(k, &v)| (k.clone(), Calibration::clamp_temperature(v)))
+ .collect();
+
+ let mut clamped_temperatures = Vec::new();
+ for (bucket, &raw) in &temperature_by_options_raw {
+ if Calibration::clamp_temperature(raw) != raw {
+ clamped_temperatures.push(format!("{bucket}={raw}"));
+ }
+ }
+ for (i, &raw) in temperature_raw.iter().enumerate() {
+ if Calibration::clamp_temperature(raw) != raw {
+ clamped_temperatures.push(format!("temperature[{i}]={raw}"));
+ }
+ }
+
+ Ok(LayaConfig {
+ encoder,
+ max_len,
+ head_max_len,
+ temperature,
+ temperature_by_options,
+ temperature_raw,
+ temperature_by_options_raw,
+ clamped_temperatures,
+ })
+ }
+}
diff --git a/laya-rust/src/laya_options.rs b/laya-rust/src/laya_options.rs
new file mode 100644
index 00000000..8a0be27e
--- /dev/null
+++ b/laya-rust/src/laya_options.rs
@@ -0,0 +1,179 @@
+//! Checkpoint selection and engine configuration. Ports the options `laya.load` / `laya.Agent`
+//! accept in `laya/agent.py`.
+
+use std::path::PathBuf;
+use std::sync::Arc;
+
+/// Selects which Laya checkpoint to load. Each maps to a different encoder and context length.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
+pub enum LayaCheckpoint {
+ /// mmBERT-base (322M), 1024-token context, 100+ languages. The safest default for
+ /// mixed-language traffic; covers English too, so there is no router to configure.
+ #[default]
+ Multilingual,
+ /// ModernBERT-large (421M), 512-token context, English-optimised. Higher accuracy on
+ /// English-only workloads; accuracy collapses on non-Latin scripts.
+ English,
+ /// ModernBERT-large (421M), 1024-token context, fine-tuned on four typed-decisions
+ /// workflows. Use only for the specific workflows it was trained on.
+ TypedDecisions,
+}
+
+impl LayaCheckpoint {
+ /// The local artifact subdirectory name. Used inside the cache root and inside an `onnx/`
+ /// tree (e.g. `onnx/multilingual/`).
+ pub fn subdir(self) -> &'static str {
+ match self {
+ LayaCheckpoint::Multilingual => "multilingual",
+ LayaCheckpoint::English => "english",
+ LayaCheckpoint::TypedDecisions => "typed-decisions",
+ }
+ }
+
+ /// The subfolder path used in HuggingFace download URLs. For English the checkpoint lives at
+ /// the bundle root (empty string), which differs from the local directory name `"english"`.
+ pub fn hf_download_subfolder(self) -> &'static str {
+ match self {
+ LayaCheckpoint::Multilingual => "multilingual",
+ LayaCheckpoint::English => "",
+ LayaCheckpoint::TypedDecisions => "typed-decisions",
+ }
+ }
+}
+
+/// ONNX execution provider. `Cpu` is always available; the GPU providers need the matching cargo
+/// feature, and requesting one without it returns a clear error.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum LayaExecutionProvider {
+ /// CPU execution (default).
+ #[default]
+ Cpu,
+ /// NVIDIA CUDA. Requires the crate's `cuda` feature.
+ Cuda,
+ /// Windows DirectML. Requires the crate's `directml` feature.
+ DirectMl,
+}
+
+/// Progress report for a single file being downloaded from HuggingFace Hub.
+#[derive(Debug, Clone)]
+pub struct ArtifactDownloadProgress {
+ /// The file name being fetched, e.g. `model.onnx.data`.
+ pub file_name: String,
+ /// Bytes written to disk so far.
+ pub bytes_received: u64,
+ /// Total file size in bytes, or `None` when the server omits `Content-Length`.
+ pub total_bytes: Option<u64>,
+}
+
+/// Controls how the Laya engine locates or downloads its ONNX artifact and how it configures
+/// ONNX Runtime.
+///
+/// `Clone`: `laya_router.rs` keeps one `LayaOptions` template shared across every checkpoint it
+/// may load and clones it per load, overriding only `checkpoint`. Every field here is itself
+/// cheaply cloneable (`Arc` for the progress callback, owned `String`/`PathBuf` elsewhere).
+#[derive(Clone)]
+pub struct LayaOptions {
+ /// The directory that contains `model.onnx`. When set, skips all other resolution steps.
+ pub model_directory: Option<PathBuf>,
+ /// Which checkpoint to load. The subdirectory, HuggingFace subfolder, and cache path all
+ /// derive from this value unless overridden by `hugging_face_subfolder` or `model_directory`.
+ pub checkpoint: LayaCheckpoint,
+ /// Which hardware back-end to use.
+ pub execution_provider: LayaExecutionProvider,
+ /// Number of threads used within a single ONNX operator. `None` lets ONNX Runtime choose.
+ pub intra_op_threads: Option<u32>,
+ /// Number of threads used to run independent ONNX operators in parallel. `None` lets ONNX
+ /// Runtime choose.
+ pub inter_op_threads: Option<u32>,
+ /// Whether the engine may fetch the artifact from HuggingFace Hub when it is not found
+ /// locally. Downloading is always opt-in.
+ pub allow_download: bool,
+ /// HuggingFace repository that hosts the artifact.
+ pub hugging_face_repo: String,
+ /// Subfolder override for non-standard bundle layouts. `None` derives it from `checkpoint`;
+ /// public so `LayaOptions { .., ..Default::default() }` compiles outside the crate.
+ pub hugging_face_subfolder: Option<String>,
+ /// HuggingFace access token used in the `Authorization: Bearer` header. When `None`, falls
+ /// back to the `HF_TOKEN` environment variable. Set to `Some(String::new())` to suppress all
+ /// auth (public repos only).
+ pub hugging_face_token: Option<String>,
+ /// Root directory under which the downloaded artifact is stored. `None` resolves to
+ /// `%LOCALAPPDATA%\laya\onnx` on Windows and `~/.cache/laya/onnx` elsewhere.
+ pub cache_directory: Option<PathBuf>,
+ /// Optional sink for per-file download progress.
+ pub download_progress: Option<Arc<dyn Fn(ArtifactDownloadProgress) + Send + Sync>>,
+}
+
+impl std::fmt::Debug for LayaOptions {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("LayaOptions")
+ .field("model_directory", &self.model_directory)
+ .field("checkpoint", &self.checkpoint)
+ .field("execution_provider", &self.execution_provider)
+ .field("intra_op_threads", &self.intra_op_threads)
+ .field("inter_op_threads", &self.inter_op_threads)
+ .field("allow_download", &self.allow_download)
+ .field("hugging_face_repo", &self.hugging_face_repo)
+ .field("hugging_face_subfolder", &self.hugging_face_subfolder)
+ .field(
+ "hugging_face_token",
+ &self.hugging_face_token.as_ref().map(|_| "<redacted>"),
+ )
+ .field("cache_directory", &self.cache_directory)
+ .field("download_progress", &self.download_progress.is_some())
+ .finish()
+ }
+}
+
+impl Default for LayaOptions {
+ fn default() -> Self {
+ Self {
+ model_directory: None,
+ checkpoint: LayaCheckpoint::default(),
+ execution_provider: LayaExecutionProvider::default(),
+ intra_op_threads: None,
+ inter_op_threads: None,
+ allow_download: false,
+ hugging_face_repo: "convaiinnovations/laya".to_string(),
+ hugging_face_subfolder: None,
+ hugging_face_token: None,
+ cache_directory: None,
+ download_progress: None,
+ }
+ }
+}
+
+impl LayaOptions {
+ /// The default options: multilingual checkpoint, CPU, no download.
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Subfolder within the repository and local cache. Derived from `checkpoint` unless set
+ /// explicitly with [`Self::set_hugging_face_subfolder`].
+ ///
+ /// Note that the HuggingFace bundle subfolder for the English checkpoint is the bundle root
+ /// (empty string), not `"english"`. When this is left at its default, download URLs are
+ /// computed correctly; if you override it for English you must use the empty string for the
+ /// download path, while `"english"` remains the conventional local directory name.
+ pub fn hugging_face_subfolder(&self) -> String {
+ self.hugging_face_subfolder
+ .clone()
+ .unwrap_or_else(|| self.checkpoint.subdir().to_string())
+ }
+
+ /// Override the HuggingFace subfolder. Prefer setting `checkpoint` instead unless loading a
+ /// custom export that does not follow the standard bundle layout.
+ pub fn set_hugging_face_subfolder(&mut self, value: impl Into<String>) {
+ self.hugging_face_subfolder = Some(value.into());
+ }
+
+ /// The subfolder path to use in HuggingFace download URLs specifically. Differs from
+ /// [`Self::hugging_face_subfolder`] only when the subfolder was never overridden and the
+ /// checkpoint is English (see [`LayaCheckpoint::hf_download_subfolder`]).
+ pub fn hugging_face_download_subfolder(&self) -> String {
+ self.hugging_face_subfolder
+ .clone()
+ .unwrap_or_else(|| self.checkpoint.hf_download_subfolder().to_string())
+ }
+}
diff --git a/laya-rust/src/model_artifacts.rs b/laya-rust/src/model_artifacts.rs
new file mode 100644
index 00000000..bda65120
--- /dev/null
+++ b/laya-rust/src/model_artifacts.rs
@@ -0,0 +1,874 @@
+//! Resolved, validated paths to the files a Laya engine needs at startup.
+//!
+//! [`ModelArtifacts::resolve`] implements the full five-step resolution order (explicit directory -> `LAYA_ONNX_DIR` -> `LAYA_ONNX_ROOT`
+//! -> cache -> opt-in download), and [`ModelArtifacts::from_directory`] validates a directory the
+//! caller already knows about.
+//!
+//! Checkpoint validation (comparing the loaded `rl_agent_config.json`'s `encoder` field against the
+//! checkpoint the caller asked for) is **not** done here: this module only records `Checkpoint`,
+//! and `LayaEngine::create`'s validation step does the actual check once the config is loaded.
+//! That check belongs in `laya_engine.rs`.
+
+use crate::error::{LayaError, Result};
+use crate::laya_options::{LayaCheckpoint, LayaOptions};
+use std::path::{Component, Path, PathBuf};
+
+#[cfg(feature = "download")]
+use crate::laya_options::ArtifactDownloadProgress;
+#[cfg(feature = "download")]
+use std::io::{Read, Write};
+#[cfg(feature = "download")]
+use std::sync::Arc;
+
+/// Which of the two supported ONNX export layouts an artifact directory uses.
+///
+/// - `Fused`: a single graph, `model.onnx` + `model.onnx.data`, exposing `input_ids`,
+/// `attention_mask`, `marker_pos`, `marker_mask`, `qtype` -> `logits`, `act_logits` directly.
+/// - `Split`: two graphs, `encoder.onnx` + `head.onnx` — the layout laya-ts's exporter
+/// (`scripts/export_onnx.py`) produces. `encoder.onnx` maps `(input_ids, attention_mask)` to
+/// `last_hidden_state`; `head.onnx` maps `(hidden_states, marker_pos, marker_mask, qtype,
+/// attention_mask)` to `(logits, act_logits)`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ModelLayout {
+ /// `model.onnx` + `model.onnx.data`.
+ Fused,
+ /// `encoder.onnx` + `head.onnx`.
+ Split,
+}
+
+/// The resolved graph file path(s) for whichever [`ModelLayout`] an artifact directory uses.
+#[derive(Debug, Clone)]
+pub enum ModelPaths {
+ /// The fused layout's single graph file.
+ Fused {
+ /// Absolute path to `model.onnx`.
+ model_path: PathBuf,
+ },
+ /// The split layout's two graph files.
+ Split {
+ /// Absolute path to `encoder.onnx`.
+ encoder_path: PathBuf,
+ /// Absolute path to `head.onnx`.
+ head_path: PathBuf,
+ },
+}
+
+impl ModelPaths {
+ /// Which layout these paths belong to.
+ pub fn layout(&self) -> ModelLayout {
+ match self {
+ ModelPaths::Fused { .. } => ModelLayout::Fused,
+ ModelPaths::Split { .. } => ModelLayout::Split,
+ }
+ }
+}
+
+/// Resolved, validated paths to every file the Laya engine needs at startup.
+#[derive(Debug, Clone)]
+pub struct ModelArtifacts {
+ /// The directory that contains the graph file(s).
+ pub directory: PathBuf,
+ /// The resolved graph file path(s); see [`ModelPaths::layout`] for which layout was found.
+ pub model: ModelPaths,
+ /// Absolute path to `rl_agent_config.json`.
+ pub config_path: PathBuf,
+ /// Absolute path to `tokenizer.json`. Looked up in `<directory>/tokenizer/` first, then
+ /// directly in `<directory>` — the fused layout ships the former, the split layout the
+ /// latter (see the module docs).
+ pub tokenizer_path: PathBuf,
+ /// Absolute path to `tokenizer_config.json`, when present, using the same `<directory>/
+ /// tokenizer/` then `<directory>` lookup order as [`Self::tokenizer_path`]. The split layout
+ /// never has this file by design; when absent, [`crate::tokenization::HfTokenizer`] falls
+ /// back to resolving special tokens from `tokenizer.json`'s own `added_tokens`.
+ pub tokenizer_config_path: Option<PathBuf>,
+ /// The checkpoint this artifact directory corresponds to, or `None` when loaded from an
+ /// explicit path (`LayaOptions::model_directory` or `LAYA_ONNX_DIR`), in which case no encoder
+ /// validation is performed by later phases.
+ pub checkpoint: Option<LayaCheckpoint>,
+}
+
+impl ModelArtifacts {
+ /// Which ONNX export layout this artifact directory uses.
+ pub fn layout(&self) -> ModelLayout {
+ self.model.layout()
+ }
+
+ /// Whether `dir` contains a complete artifact for either supported layout: the graph file(s)
+ /// for one layout (fused: `model.onnx` + `model.onnx.data`; split: `encoder.onnx` +
+ /// `head.onnx`), plus `rl_agent_config.json` and a `tokenizer.json` resolvable via the
+ /// `<dir>/tokenizer/` then `<dir>` lookup order. When `model.onnx` is present the fused
+ /// layout is what gets checked, even if a split pair also happens to sit alongside it —
+ /// matching [`Self::from_directory`]'s "fused wins" detection order. A `.part` file left over
+ /// from an interrupted download does not count: the check looks for the final file name only.
+ pub fn is_complete(dir: impl AsRef<Path>) -> bool {
+ let dir = dir.as_ref();
+ if !dir.is_dir() {
+ return false;
+ }
+ let layout_complete = if dir.join("model.onnx").is_file() {
+ dir.join("model.onnx.data").is_file()
+ } else {
+ dir.join("encoder.onnx").is_file() && dir.join("head.onnx").is_file()
+ };
+ layout_complete
+ && dir.join("rl_agent_config.json").is_file()
+ && find_tokenizer_json(dir).is_some()
+ }
+
+ /// Validates `dir` and resolves it to an absolute path, checking each required file
+ /// individually so a missing one is named rather than surfacing as a generic "not found".
+ ///
+ /// Layout detection: if `model.onnx` exists, the fused layout is used (and `model.onnx.data`
+ /// is then required next to it). Otherwise, if both `encoder.onnx` and `head.onnx` exist, the
+ /// split layout is used. Otherwise this returns [`LayaError::MissingFile`] describing both
+ /// layouts. A directory with only one of `encoder.onnx` / `head.onnx` (a half-written split
+ /// export) also fails, naming the specific file that is missing.
+ ///
+ /// `checkpoint` is recorded as-is; no encoder-family validation against it happens here (see
+ /// the module docs).
+ pub fn from_directory(
+ dir: impl AsRef<Path>,
+ checkpoint: Option<LayaCheckpoint>,
+ ) -> Result<Self> {
+ let requested = dir.as_ref().to_path_buf();
+ let resolved = absolute_path(&requested);
+
+ // Reported before the per-file checks, and naming the requested path beside the resolved
+ // one, because the two diverge in ways that are invisible otherwise: a POSIX shell eats
+ // unquoted backslashes, and Windows then reads what is left of "D:\a\b" as the
+ // drive-relative "D:ab", resolving it against the current directory. Naming only the
+ // resolved path would turn that into a baffling "missing model.onnx" in a directory the
+ // user never typed.
+ if !resolved.is_dir() {
+ return Err(LayaError::DirectoryNotFound {
+ requested: if requested == resolved {
+ None
+ } else {
+ Some(requested)
+ },
+ resolved,
+ });
+ }
+
+ let model = resolve_model_paths(&resolved)?;
+
+ let config_path = resolved.join("rl_agent_config.json");
+ require_file(&config_path, None)?;
+
+ let tokenizer_path =
+ find_tokenizer_json(&resolved).ok_or_else(|| LayaError::MissingFile {
+ path: resolved.join("tokenizer").join("tokenizer.json"),
+ hint: Some(
+ "Looked for tokenizer.json in <directory>/tokenizer/ and then directly in \
+ <directory>; neither had it."
+ .to_string(),
+ ),
+ })?;
+ let tokenizer_config_path = find_tokenizer_config_json(&resolved);
+
+ Ok(ModelArtifacts {
+ directory: resolved,
+ model,
+ config_path,
+ tokenizer_path,
+ tokenizer_config_path,
+ checkpoint,
+ })
+ }
+
+ /// Resolves and validates the artifact directory, downloading it when
+ /// `options.allow_download` is `true` and it is not already present.
+ ///
+ /// Resolution order:
+ ///
+ /// 1. `options.model_directory`, if set — validated and used directly. No further steps.
+ /// 2. The `LAYA_ONNX_DIR` environment variable, if set — backward-compat; always treated as
+ /// pointing directly at the artifact directory, independent of the checkpoint. No further
+ /// steps.
+ /// 3. `LAYA_ONNX_ROOT/<checkpoint-subdir>`, if the env var is set and that directory contains
+ /// a complete artifact. Otherwise falls through to the remaining steps rather than failing
+ /// immediately, so a partially-downloaded cache still works.
+ /// 4. `<cache root>/<checkpoint-subdir>`, if it already contains a complete artifact.
+ /// 5. A download into the cache directory, if `options.allow_download` is `true`.
+ /// 6. [`LayaError::ArtifactsNotFound`], listing every location tried, if none of the above
+ /// worked.
+ ///
+ /// Returns [`LayaError::DirectoryNotFound`] or [`LayaError::MissingFile`] when an explicit
+ /// path (steps 1 or 2) does not check out, and [`LayaError::Download`] if a download is
+ /// requested but the crate was built with `--no-default-features` (the `download` feature is
+ /// on by default).
+ pub fn resolve(options: &LayaOptions) -> Result<Self> {
+ // 1. Explicit directory. No checkpoint inference: the caller knows what they loaded.
+ if let Some(dir) = &options.model_directory
+ && !dir.as_os_str().is_empty()
+ {
+ return Self::from_directory(dir, None);
+ }
+
+ // 2. LAYA_ONNX_DIR: backward-compat env var that points directly at the artifact dir.
+ // Treated as an explicit path for the same reason: it may point at any checkpoint.
+ if let Ok(env_dir) = std::env::var("LAYA_ONNX_DIR")
+ && !env_dir.trim().is_empty()
+ {
+ return Self::from_directory(&env_dir, None);
+ }
+
+ let subfolder = options.checkpoint.subdir();
+
+ // 3. LAYA_ONNX_ROOT: new env var for a tree that holds every checkpoint in named
+ // subdirectories (english/, multilingual/, typed-decisions/).
+ let onnx_root = std::env::var("LAYA_ONNX_ROOT")
+ .ok()
+ .filter(|s| !s.trim().is_empty());
+ if let Some(root) = &onnx_root {
+ let root_dir = Path::new(root).join(subfolder);
+ if Self::is_complete(&root_dir) {
+ return Self::from_directory(&root_dir, Some(options.checkpoint));
+ }
+ // Not complete under LAYA_ONNX_ROOT — fall through to cache and download rather than
+ // failing immediately.
+ }
+
+ // 4. Cache hit.
+ let cache_root = resolve_cache_root(options);
+ let artifact_dir = cache_root.join(subfolder);
+ if Self::is_complete(&artifact_dir) {
+ return Self::from_directory(&artifact_dir, Some(options.checkpoint));
+ }
+
+ // 5. Download, if allowed.
+ if options.allow_download {
+ #[cfg(feature = "download")]
+ {
+ download_artifact(options, &artifact_dir)?;
+ return Self::from_directory(&artifact_dir, Some(options.checkpoint));
+ }
+ #[cfg(not(feature = "download"))]
+ {
+ return Err(LayaError::Download(
+ "LayaOptions::allow_download is true, but this crate was built without the \
+ `download` cargo feature (it is on by default; it was likely disabled with \
+ --no-default-features). Rebuild with the `download` feature enabled, or \
+ fetch the artifact manually and point LayaOptions::model_directory, \
+ LAYA_ONNX_DIR, or LAYA_ONNX_ROOT at it."
+ .to_string(),
+ ));
+ }
+ }
+
+ // 6. Nothing worked — report every location tried.
+ Err(LayaError::ArtifactsNotFound {
+ tried: build_tried_list(&onnx_root, subfolder, &artifact_dir),
+ })
+ }
+}
+
+/// Detects which layout `dir` uses and resolves + validates its graph file path(s).
+///
+/// `model.onnx` present wins outright (fused), even if a split pair also happens to sit alongside
+/// it. Otherwise both `encoder.onnx` and `head.onnx` must be present (split). A directory with
+/// only one of the split pair is treated as a validation error naming the missing file, not as
+/// "neither layout" — the caller very likely meant to export the split layout and just failed
+/// partway through.
+fn resolve_model_paths(dir: &Path) -> Result<ModelPaths> {
+ let fused_path = dir.join("model.onnx");
+ if fused_path.is_file() {
+ let data_path = dir.join("model.onnx.data");
+ require_file(
+ &data_path,
+ Some(
+ "The external weights file must sit next to model.onnx — ONNX Runtime resolves \
+ it relative to the graph file, and loading the graph on its own produces a \
+ baffling 'missing initializer' error.",
+ ),
+ )?;
+ return Ok(ModelPaths::Fused {
+ model_path: fused_path,
+ });
+ }
+
+ let encoder_path = dir.join("encoder.onnx");
+ let head_path = dir.join("head.onnx");
+ let has_encoder = encoder_path.is_file();
+ let has_head = head_path.is_file();
+
+ if has_encoder || has_head {
+ // A half-written split export: name the specific missing file rather than the generic
+ // "neither layout found" message below.
+ require_file(&encoder_path, None)?;
+ require_file(&head_path, None)?;
+ return Ok(ModelPaths::Split {
+ encoder_path,
+ head_path,
+ });
+ }
+
+ Err(LayaError::MissingFile {
+ path: fused_path,
+ hint: Some(
+ "Expected either the fused layout (model.onnx + model.onnx.data) or the split \
+ layout (encoder.onnx + head.onnx, the layout laya-ts's exporter produces) in this \
+ directory; found neither."
+ .to_string(),
+ ),
+ })
+}
+
+/// Looks up `tokenizer.json` using the fused-then-split lookup order: `<dir>/tokenizer/` first
+/// (the fused layout's location), then directly in `<dir>` (where the split layout's exporter
+/// puts it).
+fn find_tokenizer_json(dir: &Path) -> Option<PathBuf> {
+ let nested = dir.join("tokenizer").join("tokenizer.json");
+ if nested.is_file() {
+ return Some(nested);
+ }
+ let root = dir.join("tokenizer.json");
+ if root.is_file() {
+ return Some(root);
+ }
+ None
+}
+
+/// Looks up `tokenizer_config.json` using the same lookup order as [`find_tokenizer_json`]. The
+/// split layout never ships this file; callers must treat its absence as expected, not an error.
+fn find_tokenizer_config_json(dir: &Path) -> Option<PathBuf> {
+ let nested = dir.join("tokenizer").join("tokenizer_config.json");
+ if nested.is_file() {
+ return Some(nested);
+ }
+ let root = dir.join("tokenizer_config.json");
+ if root.is_file() {
+ return Some(root);
+ }
+ None
+}
+
+fn require_file(path: &Path, hint: Option<&str>) -> Result<()> {
+ if path.is_file() {
+ Ok(())
+ } else {
+ Err(LayaError::MissingFile {
+ path: path.to_path_buf(),
+ hint: hint.map(str::to_string),
+ })
+ }
+}
+
+/// An absolute path: joins onto the current directory if relative, then lexically collapses `.`
+/// and `..` components. Deliberately does not resolve symlinks and does not require the path to
+/// exist (unlike `std::fs::canonicalize`, which fails outright on a path that isn't there yet —
+/// exactly the case this function's caller needs to report clearly).
+fn absolute_path(path: &Path) -> PathBuf {
+ let joined = if path.is_absolute() {
+ path.to_path_buf()
+ } else {
+ std::env::current_dir().unwrap_or_default().join(path)
+ };
+
+ let mut result = PathBuf::new();
+ for component in joined.components() {
+ match component {
+ Component::CurDir => {}
+ Component::ParentDir => {
+ result.pop();
+ }
+ other => result.push(other.as_os_str()),
+ }
+ }
+ result
+}
+
+/// The cache root: `options.cache_directory` if set, otherwise `%LOCALAPPDATA%\laya\onnx` on
+/// Windows or `~/.cache/laya/onnx` elsewhere.
+fn resolve_cache_root(options: &LayaOptions) -> PathBuf {
+ if let Some(dir) = &options.cache_directory
+ && !dir.as_os_str().is_empty()
+ {
+ return dir.clone();
+ }
+ default_cache_root()
+}
+
+#[cfg(target_os = "windows")]
+fn default_cache_root() -> PathBuf {
+ if let Ok(local_app_data) = std::env::var("LOCALAPPDATA")
+ && !local_app_data.trim().is_empty()
+ {
+ return PathBuf::from(local_app_data).join("laya").join("onnx");
+ }
+ // %LOCALAPPDATA% is unset on some minimal/service accounts; fall back to a `.cache`
+ // directory under the user profile.
+ let home = std::env::var("USERPROFILE").unwrap_or_default();
+ PathBuf::from(home).join(".cache").join("laya").join("onnx")
+}
+
+#[cfg(not(target_os = "windows"))]
+fn default_cache_root() -> PathBuf {
+ let home = std::env::var("HOME").unwrap_or_default();
+ PathBuf::from(home).join(".cache").join("laya").join("onnx")
+}
+
+/// Builds the "Tried:" list for [`LayaError::ArtifactsNotFound`]. By the time this runs,
+/// `LayaOptions::model_directory` and `LAYA_ONNX_DIR` are known to be unset (otherwise
+/// [`ModelArtifacts::resolve`] would already have returned via one of those two steps), so those
+/// two lines hardcode "(not set)" for the same reason.
+fn build_tried_list(
+ onnx_root: &Option<String>,
+ subfolder: &str,
+ artifact_dir: &Path,
+) -> Vec<String> {
+ let onnx_root_line = match onnx_root {
+ Some(root) => format!(
+ " - LAYA_ONNX_ROOT env var {}",
+ Path::new(root).join(subfolder).display()
+ ),
+ None => " - LAYA_ONNX_ROOT env var (not set)".to_string(),
+ };
+ vec![
+ " - LayaOptions::model_directory (not set)".to_string(),
+ " - LAYA_ONNX_DIR env var (not set)".to_string(),
+ onnx_root_line,
+ format!(
+ " - Cache directory {}",
+ artifact_dir.display()
+ ),
+ String::new(),
+ "To fix this, do one of:".to_string(),
+ " a) Download the artifact and point LayaOptions::model_directory or LAYA_ONNX_DIR at \
+ its directory, or set LAYA_ONNX_ROOT to the parent of all checkpoints."
+ .to_string(),
+ " b) Set LayaOptions::allow_download = true to download automatically.".to_string(),
+ "Note: both model.onnx and model.onnx.data must reside in the same directory — ORT \
+ resolves the external weights file relative to the graph file."
+ .to_string(),
+ ]
+}
+
+// ── download ───────────────────────────────────────────────────────────────
+
+// Files to fetch for the fused layout, as (remote sub-path relative to the HF subfolder, local
+// path segments relative to the destination directory).
+#[cfg(feature = "download")]
+const FUSED_ARTIFACT_FILES: &[(&str, &[&str])] = &[
+ ("model.onnx", &["model.onnx"]),
+ ("model.onnx.data", &["model.onnx.data"]),
+ ("rl_agent_config.json", &["rl_agent_config.json"]),
+ ("tokenizer/tokenizer.json", &["tokenizer", "tokenizer.json"]),
+ (
+ "tokenizer/tokenizer_config.json",
+ &["tokenizer", "tokenizer_config.json"],
+ ),
+];
+
+// Files to fetch for the split layout (laya-ts's exporter output): no `tokenizer/` subdirectory,
+// no `tokenizer_config.json`.
+#[cfg(feature = "download")]
+const SPLIT_ARTIFACT_FILES: &[(&str, &[&str])] = &[
+ ("encoder.onnx", &["encoder.onnx"]),
+ ("encoder.onnx.data", &["encoder.onnx.data"]),
+ ("head.onnx", &["head.onnx"]),
+ ("head.onnx.data", &["head.onnx.data"]),
+ ("rl_agent_config.json", &["rl_agent_config.json"]),
+ ("tokenizer.json", &["tokenizer.json"]),
+];
+
+// External-data sidecars are only written when a graph's weights exceed the protobuf limit, so a
+// split export may ship without them; these are skipped when absent instead of failing.
+#[cfg(feature = "download")]
+const OPTIONAL_SPLIT_FILES: &[&str] = &["encoder.onnx.data", "head.onnx.data"];
+
+#[cfg(feature = "download")]
+fn local_path(dest_dir: &Path, segments: &[&str]) -> PathBuf {
+ segments
+ .iter()
+ .fold(dest_dir.to_path_buf(), |path, segment| path.join(segment))
+}
+
+/// Probes the remote repository to find out which layout it publishes, mirroring the local
+/// detection order in [`resolve_model_paths`]: `model.onnx` wins if present, otherwise
+/// `encoder.onnx` + `head.onnx`. Uses a `HEAD` request per candidate file so no bytes are
+/// downloaded before the layout is known.
+#[cfg(feature = "download")]
+fn probe_remote_layout(
+ agent: &ureq::Agent,
+ base_url: &str,
+ token: Option<&str>,
+) -> Result<ModelLayout> {
+ if remote_file_exists(agent, &format!("{base_url}model.onnx"), token) {
+ return Ok(ModelLayout::Fused);
+ }
+ let has_encoder = remote_file_exists(agent, &format!("{base_url}encoder.onnx"), token);
+ let has_head = remote_file_exists(agent, &format!("{base_url}head.onnx"), token);
+ if has_encoder && has_head {
+ return Ok(ModelLayout::Split);
+ }
+ Err(LayaError::Download(format!(
+ "Hugging Face has neither the fused layout (model.onnx) nor the split layout \
+ (encoder.onnx + head.onnx) at {base_url}.\n\n\
+ The Laya repository publishes PyTorch weights (model.safetensors), which this SDK \
+ cannot load: it needs an ONNX export. Unless that export has been uploaded to the \
+ repository, allow_download cannot succeed.\n\n\
+ Export the model once with the Python package (or laya-ts's exporter), then point the \
+ SDK at the output directory via LAYA_ONNX_DIR or LayaOptions::model_directory."
+ )))
+}
+
+/// `true` if a `HEAD` request against `url` succeeds. Any failure (404, network error, TLS error,
+/// ...) is treated the same way — as "not present" — since the caller only needs a yes/no signal
+/// to pick a file list, not a diagnostic; a real download attempt further down produces the
+/// detailed 404/401/403 errors.
+#[cfg(feature = "download")]
+fn remote_file_exists(agent: &ureq::Agent, url: &str, token: Option<&str>) -> bool {
+ let mut request = agent.head(url);
+ if let Some(t) = token {
+ request = request.header("Authorization", format!("Bearer {t}"));
+ }
+ request.call().is_ok()
+}
+
+/// Downloads every file in `files` into `dest_dir`, creating parent directories as needed (the
+/// fused layout nests two files under `tokenizer/`; the split layout does not nest anything). One
+/// `ureq::Agent` is built and reused for all files rather than a fresh client per file.
+#[cfg(feature = "download")]
+fn download_file_list(
+ options: &LayaOptions,
+ dest_dir: &Path,
+ agent: &ureq::Agent,
+ base_url: &str,
+ token: Option<&str>,
+ files: &[(&str, &[&str])],
+) -> Result<()> {
+ for (remote, local) in files {
+ let url = format!("{base_url}{remote}");
+ if OPTIONAL_SPLIT_FILES.contains(remote) && !remote_file_exists(agent, &url, token) {
+ continue;
+ }
+ let dest_path = local_path(dest_dir, local);
+ if let Some(parent) = dest_path.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ let mut part_os = dest_path.clone().into_os_string();
+ part_os.push(".part");
+ let part_path = PathBuf::from(part_os);
+ let display_name = local.last().copied().unwrap_or(*remote);
+
+ fetch_to_file(
+ agent,
+ &url,
+ display_name,
+ &dest_path,
+ &part_path,
+ token,
+ options.download_progress.as_ref(),
+ )?;
+ }
+ Ok(())
+}
+
+/// Detects which layout the remote repository publishes, then downloads that layout's artifact
+/// files into `dest_dir`.
+#[cfg(feature = "download")]
+fn download_artifact(options: &LayaOptions, dest_dir: &Path) -> Result<()> {
+ std::fs::create_dir_all(dest_dir)?;
+
+ let token = options
+ .hugging_face_token
+ .clone()
+ .or_else(|| std::env::var("HF_TOKEN").ok())
+ .filter(|t| !t.is_empty());
+
+ let agent = ureq::Agent::new_with_defaults();
+
+ // The English checkpoint lives at the bundle root; all others use a named subfolder.
+ // hugging_face_download_subfolder() returns "" for English, so the URL has no extra segment.
+ let hf_sub = options.hugging_face_download_subfolder();
+ let base_url = if hf_sub.is_empty() {
+ format!(
+ "https://huggingface.co/{}/resolve/main/",
+ options.hugging_face_repo
+ )
+ } else {
+ format!(
+ "https://huggingface.co/{}/resolve/main/{}/",
+ options.hugging_face_repo, hf_sub
+ )
+ };
+
+ let layout = probe_remote_layout(&agent, &base_url, token.as_deref())?;
+ let files = match layout {
+ ModelLayout::Fused => FUSED_ARTIFACT_FILES,
+ ModelLayout::Split => SPLIT_ARTIFACT_FILES,
+ };
+ download_file_list(
+ options,
+ dest_dir,
+ &agent,
+ &base_url,
+ token.as_deref(),
+ files,
+ )
+}
+
+/// The download seam: fetches one URL to `part_path`, then atomically promotes it to
+/// `dest_path`. Kept as a standalone function (rather than inlined into
+/// [`download_artifact`]) so tests can point it at a local `TcpListener` instead of a real
+/// HuggingFace URL and exercise the 404 / 401 / success paths without any network access.
+#[cfg(feature = "download")]
+fn fetch_to_file(
+ agent: &ureq::Agent,
+ url: &str,
+ display_name: &str,
+ dest_path: &Path,
+ part_path: &Path,
+ token: Option<&str>,
+ progress: Option<&Arc<dyn Fn(ArtifactDownloadProgress) + Send + Sync>>,
+) -> Result<()> {
+ let mut request = agent.get(url);
+ if let Some(t) = token {
+ request = request.header("Authorization", format!("Bearer {t}"));
+ }
+
+ // A bare status-code error here would surface as "404 (Not Found)" with no hint as to which
+ // file was missing or what to do about it. The two failures worth naming:
+ // 404 — the repository does not publish the ONNX export at all (it ships safetensors, which
+ // this SDK cannot load), or the subfolder is wrong.
+ // 401/403 — a gated or private repository that needs a token.
+ let mut response = match request.call() {
+ Ok(response) => response,
+ Err(ureq::Error::StatusCode(404)) => {
+ return Err(LayaError::Download(format!(
+ "Hugging Face has no '{display_name}' at {url} (404).\n\n\
+ The Laya repository publishes PyTorch weights (model.safetensors), which this \
+ SDK cannot load: it needs an ONNX export (model.onnx + model.onnx.data). Unless \
+ that export has been uploaded to the repository, allow_download cannot \
+ succeed.\n\n\
+ Export the model once with the Python package, then point the SDK at the output \
+ directory via LAYA_ONNX_DIR or LayaOptions::model_directory."
+ )));
+ }
+ Err(ureq::Error::StatusCode(code)) if code == 401 || code == 403 => {
+ return Err(LayaError::Download(format!(
+ "Hugging Face refused access to {url} ({code}).\n\
+ The repository is gated or private. Set LayaOptions::hugging_face_token, or the \
+ HF_TOKEN environment variable, to a token that can read it."
+ )));
+ }
+ Err(e) => {
+ return Err(LayaError::Download(format!(
+ "downloading '{display_name}' from {url}: {e}"
+ )));
+ }
+ };
+
+ let total = response.body().content_length();
+
+ let mut file = std::fs::File::create(part_path)?;
+ {
+ let mut reader = response.body_mut().as_reader();
+ let mut buffer = [0u8; 81_920];
+ let mut received: u64 = 0;
+ loop {
+ let read = reader.read(&mut buffer)?;
+ if read == 0 {
+ break;
+ }
+ file.write_all(&buffer[..read])?;
+ received += read as u64;
+ if let Some(callback) = progress {
+ callback(ArtifactDownloadProgress {
+ file_name: display_name.to_string(),
+ bytes_received: received,
+ total_bytes: total,
+ });
+ }
+ }
+ }
+ drop(file);
+
+ // Atomic promotion: a .part file that survived means a previous run was interrupted, not
+ // that the destination is valid. Windows can't rename onto an existing file, so remove it
+ // first.
+ if dest_path.is_file() {
+ std::fs::remove_file(dest_path)?;
+ }
+ std::fs::rename(part_path, dest_path)?;
+ Ok(())
+}
+
+#[cfg(all(test, feature = "download"))]
+mod download_tests {
+ use super::*;
+ use std::net::TcpListener;
+ use std::sync::Mutex;
+
+ /// Starts a one-shot HTTP server on an ephemeral port, replies with `response` to the single
+ /// connection it accepts, and returns the base URL (`http://127.0.0.1:PORT`). The accept loop
+ /// runs on a background thread and this function does not join it — the test process exits
+ /// (or the listener is dropped) when the test ends, which is enough to clean it up.
+ fn spawn_once_server(response: Vec<u8>) -> String {
+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port");
+ let addr = listener.local_addr().expect("local_addr");
+ std::thread::spawn(move || {
+ if let Ok((mut stream, _)) = listener.accept() {
+ let mut buf = [0u8; 4096];
+ // Read (and discard) whatever the client sent; we don't need to parse it, just
+ // drain enough that the client isn't blocked writing its request.
+ let _ = stream.read(&mut buf);
+ let _ = std::io::Write::write_all(&mut stream, &response);
+ let _ = std::io::Write::flush(&mut stream);
+ }
+ });
+ format!("http://{addr}")
+ }
+
+ fn http_response(status_line: &str, body: &[u8]) -> Vec<u8> {
+ let mut head = format!(
+ "{status_line}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
+ body.len()
+ )
+ .into_bytes();
+ head.extend_from_slice(body);
+ head
+ }
+
+ #[test]
+ fn fetch_to_file_success_streams_body_and_reports_progress() {
+ let body = b"hello world, this is the fake artifact body";
+ let base = spawn_once_server(http_response("HTTP/1.1 200 OK", body));
+ let url = format!("{base}/model.onnx");
+
+ let dir = tempfile::tempdir().expect("tempdir");
+ let dest = dir.path().join("model.onnx");
+ let part = dir.path().join("model.onnx.part");
+
+ let agent = ureq::Agent::new_with_defaults();
+ let received_totals: Arc<Mutex<Vec<u64>>> = Arc::new(Mutex::new(Vec::new()));
+ let sink = received_totals.clone();
+ let callback: Arc<dyn Fn(ArtifactDownloadProgress) + Send + Sync> =
+ Arc::new(move |p: ArtifactDownloadProgress| {
+ sink.lock().unwrap().push(p.bytes_received);
+ assert_eq!(p.total_bytes, Some(body.len() as u64));
+ });
+
+ fetch_to_file(
+ &agent,
+ &url,
+ "model.onnx",
+ &dest,
+ &part,
+ None,
+ Some(&callback),
+ )
+ .expect("download should succeed");
+
+ assert_eq!(std::fs::read(&dest).unwrap(), body);
+ assert!(
+ !part.exists(),
+ ".part file must be renamed away, not left behind"
+ );
+ assert!(
+ !received_totals.lock().unwrap().is_empty(),
+ "progress callback should have fired at least once"
+ );
+ }
+
+ #[test]
+ fn fetch_to_file_404_gives_descriptive_error() {
+ let base = spawn_once_server(http_response("HTTP/1.1 404 Not Found", b""));
+ let url = format!("{base}/model.onnx");
+
+ let dir = tempfile::tempdir().expect("tempdir");
+ let dest = dir.path().join("model.onnx");
+ let part = dir.path().join("model.onnx.part");
+
+ let agent = ureq::Agent::new_with_defaults();
+ let err = fetch_to_file(&agent, &url, "model.onnx", &dest, &part, None, None)
+ .expect_err("404 must be an error");
+ let message = err.to_string();
+ assert!(message.contains("404"), "message was: {message}");
+ assert!(
+ message.contains("safetensors") || message.contains("ONNX export"),
+ "message should explain the safetensors-vs-ONNX gap: {message}"
+ );
+ assert!(!dest.exists());
+ assert!(!part.exists());
+ }
+
+ #[test]
+ fn fetch_to_file_401_gives_descriptive_error() {
+ let base = spawn_once_server(http_response("HTTP/1.1 401 Unauthorized", b""));
+ let url = format!("{base}/model.onnx");
+
+ let dir = tempfile::tempdir().expect("tempdir");
+ let dest = dir.path().join("model.onnx");
+ let part = dir.path().join("model.onnx.part");
+
+ let agent = ureq::Agent::new_with_defaults();
+ let err = fetch_to_file(&agent, &url, "model.onnx", &dest, &part, None, None)
+ .expect_err("401 must be an error");
+ let message = err.to_string();
+ assert!(message.contains("401"), "message was: {message}");
+ assert!(
+ message.contains("HF_TOKEN") || message.contains("hugging_face_token"),
+ "message should point at the token settings: {message}"
+ );
+ }
+
+ #[test]
+ fn fetch_to_file_403_gives_descriptive_error() {
+ let base = spawn_once_server(http_response("HTTP/1.1 403 Forbidden", b""));
+ let url = format!("{base}/model.onnx");
+
+ let dir = tempfile::tempdir().expect("tempdir");
+ let dest = dir.path().join("model.onnx");
+ let part = dir.path().join("model.onnx.part");
+
+ let agent = ureq::Agent::new_with_defaults();
+ let err = fetch_to_file(&agent, &url, "model.onnx", &dest, &part, None, None)
+ .expect_err("403 must be an error");
+ assert!(err.to_string().contains("403"));
+ }
+
+ #[test]
+ fn fetch_to_file_sends_bearer_token_when_provided() {
+ // The server echoes back whether it saw an Authorization header, as the response body,
+ // so the test can assert on it without a full HTTP request parser.
+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port");
+ let addr = listener.local_addr().expect("local_addr");
+ std::thread::spawn(move || {
+ if let Ok((mut stream, _)) = listener.accept() {
+ let mut buf = [0u8; 8192];
+ let n = stream.read(&mut buf).unwrap_or(0);
+ let request_text = String::from_utf8_lossy(&buf[..n]).to_ascii_lowercase();
+ let saw_bearer = request_text.contains("authorization: bearer secret-token");
+ let body = if saw_bearer {
+ b"ok".as_slice()
+ } else {
+ b"missing".as_slice()
+ };
+ let response = http_response("HTTP/1.1 200 OK", body);
+ let _ = std::io::Write::write_all(&mut stream, &response);
+ let _ = std::io::Write::flush(&mut stream);
+ }
+ });
+ let url = format!("http://{addr}/model.onnx");
+
+ let dir = tempfile::tempdir().expect("tempdir");
+ let dest = dir.path().join("model.onnx");
+ let part = dir.path().join("model.onnx.part");
+ let agent = ureq::Agent::new_with_defaults();
+
+ fetch_to_file(
+ &agent,
+ &url,
+ "model.onnx",
+ &dest,
+ &part,
+ Some("secret-token"),
+ None,
+ )
+ .expect("download should succeed");
+
+ assert_eq!(std::fs::read(&dest).unwrap(), b"ok");
+ }
+}
diff --git a/laya-rust/tests/model_artifacts_tests.rs b/laya-rust/tests/model_artifacts_tests.rs
new file mode 100644
index 00000000..e04259bd
--- /dev/null
+++ b/laya-rust/tests/model_artifacts_tests.rs
@@ -0,0 +1,620 @@
+//! Integration tests for [`laya::ModelArtifacts`], covering the resolution order, error
+//! reporting, and cache/download behaviour implemented in `src/model_artifacts.rs`.
+//!
+//! Every test that reads or writes `LAYA_ONNX_DIR` / `LAYA_ONNX_ROOT` / `HF_TOKEN` holds
+//! [`ENV_LOCK`] for its whole body: `cargo test` runs tests on multiple threads by default, and
+//! these are process-wide environment variables, so two such tests running concurrently would
+//! stomp on each other's state. Tests that never touch an env var don't need the lock.
+//!
+//! Network-touching behaviour (404 / 401 / 403 handling, the `.part`-then-rename write) is covered
+//! by unit tests inside `src/model_artifacts.rs` against a local `TcpListener`, not here — those
+//! tests need access to the private `fetch_to_file` seam, which isn't visible from an integration
+//! test crate.
+//!
+//! Tests build `LayaOptions` with [`plain_options`] plus direct field assignment rather than
+//! `LayaOptions { ..., ..Default::default() }`: `LayaOptions` has a private field
+//! (`hugging_face_subfolder`, deliberately not `pub` because its default is computed from
+//! `checkpoint`), and Rust's `..base` struct-update syntax requires every field of the struct type
+//! to be visible at the call site — even ones the update doesn't mention — so it does not compile
+//! from outside the defining crate. Plain field assignment on an already-constructed value has no
+//! such restriction, since each assignment only needs that one field to be `pub`.
+
+use laya::{LayaCheckpoint, LayaError, LayaOptions, ModelArtifacts, ModelLayout, ModelPaths};
+use std::path::Path;
+use std::sync::Mutex;
+
+/// Serializes every test in this file that reads or writes `LAYA_ONNX_DIR`, `LAYA_ONNX_ROOT`, or
+/// `HF_TOKEN`.
+static ENV_LOCK: Mutex<()> = Mutex::new(());
+
+/// Restores (or removes) one environment variable when dropped, so a test can freely mutate
+/// process-wide state without leaking it into whichever test happens to run next.
+struct EnvVarGuard {
+ key: &'static str,
+ previous: Option<String>,
+}
+
+impl EnvVarGuard {
+ fn set(key: &'static str, value: &str) -> Self {
+ let previous = std::env::var(key).ok();
+ // SAFETY: callers hold `ENV_LOCK` for the guard's whole lifetime, so no other thread in
+ // this test binary observes or mutates the environment concurrently.
+ unsafe { std::env::set_var(key, value) };
+ Self { key, previous }
+ }
+
+ fn unset(key: &'static str) -> Self {
+ let previous = std::env::var(key).ok();
+ unsafe { std::env::remove_var(key) };
+ Self { key, previous }
+ }
+}
+
+impl Drop for EnvVarGuard {
+ fn drop(&mut self) {
+ match &self.previous {
+ Some(value) => unsafe { std::env::set_var(self.key, value) },
+ None => unsafe { std::env::remove_var(self.key) },
+ }
+ }
+}
+
+fn lock_env() -> std::sync::MutexGuard<'static, ()> {
+ ENV_LOCK
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+}
+
+/// Clears `LAYA_ONNX_DIR` and `LAYA_ONNX_ROOT` for the duration of the returned guards, so a test
+/// starts from a clean slate regardless of what the outer environment happens to have set (a
+/// developer running the suite locally with either variable exported would otherwise see
+/// unrelated failures).
+fn clear_onnx_env_vars() -> (EnvVarGuard, EnvVarGuard) {
+ (
+ EnvVarGuard::unset("LAYA_ONNX_DIR"),
+ EnvVarGuard::unset("LAYA_ONNX_ROOT"),
+ )
+}
+
+/// A fresh, all-defaults `LayaOptions`. See the module docs for why this — plus direct field
+/// assignment — is used instead of `LayaOptions { .., ..Default::default() }`.
+fn plain_options() -> LayaOptions {
+ LayaOptions::new()
+}
+
+fn write_complete_artifact(dir: &Path) {
+ std::fs::create_dir_all(dir.join("tokenizer")).expect("create tokenizer dir");
+ std::fs::write(dir.join("model.onnx"), b"graph").expect("write model.onnx");
+ std::fs::write(dir.join("model.onnx.data"), b"weights").expect("write model.onnx.data");
+ std::fs::write(dir.join("rl_agent_config.json"), b"{}").expect("write config");
+ std::fs::write(dir.join("tokenizer").join("tokenizer.json"), b"{}")
+ .expect("write tokenizer.json");
+}
+
+// ── is_complete ───────────────────────────────────────────────────────────────
+
+#[test]
+fn is_complete_true_for_a_fully_populated_directory() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(dir.path());
+ assert!(ModelArtifacts::is_complete(dir.path()));
+}
+
+#[test]
+fn is_complete_false_for_a_directory_that_does_not_exist() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ assert!(!ModelArtifacts::is_complete(dir.path().join("nope")));
+}
+
+#[test]
+fn is_complete_false_when_model_onnx_is_missing() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(dir.path());
+ std::fs::remove_file(dir.path().join("model.onnx")).unwrap();
+ assert!(!ModelArtifacts::is_complete(dir.path()));
+}
+
+#[test]
+fn is_complete_false_when_model_onnx_data_is_missing() {
+ // The most common real-world case: the 1.29 GB sidecar was left behind when copying.
+ let dir = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(dir.path());
+ std::fs::remove_file(dir.path().join("model.onnx.data")).unwrap();
+ assert!(!ModelArtifacts::is_complete(dir.path()));
+}
+
+#[test]
+fn is_complete_false_when_config_is_missing() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(dir.path());
+ std::fs::remove_file(dir.path().join("rl_agent_config.json")).unwrap();
+ assert!(!ModelArtifacts::is_complete(dir.path()));
+}
+
+#[test]
+fn is_complete_false_when_tokenizer_json_is_missing() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(dir.path());
+ std::fs::remove_file(dir.path().join("tokenizer").join("tokenizer.json")).unwrap();
+ assert!(!ModelArtifacts::is_complete(dir.path()));
+}
+
+#[test]
+fn is_complete_ignores_a_leftover_part_file() {
+ // An interrupted download leaves `model.onnx.data.part`, never `model.onnx.data` itself.
+ // `is_complete` must not be fooled by the `.part` file's presence.
+ let dir = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(dir.path());
+ std::fs::remove_file(dir.path().join("model.onnx.data")).unwrap();
+ std::fs::write(dir.path().join("model.onnx.data.part"), b"partial").unwrap();
+ assert!(!ModelArtifacts::is_complete(dir.path()));
+}
+
+// ── layout detection ──────────────────────────────────────────────────────────
+
+fn write_split_pair(dir: &Path) {
+ std::fs::create_dir_all(dir).expect("create dir");
+ std::fs::write(dir.join("encoder.onnx"), b"encoder-graph").expect("write encoder.onnx");
+ std::fs::write(dir.join("head.onnx"), b"head-graph").expect("write head.onnx");
+ std::fs::write(dir.join("rl_agent_config.json"), b"{}").expect("write config");
+ std::fs::write(dir.join("tokenizer.json"), b"{}").expect("write tokenizer.json");
+}
+
+#[test]
+fn is_complete_true_for_a_fused_only_directory() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(dir.path());
+ assert!(ModelArtifacts::is_complete(dir.path()));
+}
+
+#[test]
+fn is_complete_true_for_a_split_only_directory() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ write_split_pair(dir.path());
+ assert!(ModelArtifacts::is_complete(dir.path()));
+}
+
+#[test]
+fn is_complete_true_when_both_layouts_present_fused_wins() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(dir.path());
+ // A stray split pair alongside a complete fused layout must not affect completeness.
+ std::fs::write(dir.path().join("encoder.onnx"), b"encoder-graph").unwrap();
+ std::fs::write(dir.path().join("head.onnx"), b"head-graph").unwrap();
+ assert!(ModelArtifacts::is_complete(dir.path()));
+
+ let artifacts = ModelArtifacts::from_directory(dir.path(), None).expect("must resolve");
+ assert_eq!(artifacts.layout(), ModelLayout::Fused);
+}
+
+#[test]
+fn is_complete_false_for_neither_layout() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ std::fs::write(dir.path().join("rl_agent_config.json"), b"{}").unwrap();
+ std::fs::write(dir.path().join("tokenizer.json"), b"{}").unwrap();
+ assert!(!ModelArtifacts::is_complete(dir.path()));
+}
+
+#[test]
+fn is_complete_false_for_half_a_split_pair() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ write_split_pair(dir.path());
+ std::fs::remove_file(dir.path().join("head.onnx")).unwrap();
+ assert!(!ModelArtifacts::is_complete(dir.path()));
+}
+
+#[test]
+fn from_directory_resolves_the_split_layout() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ write_split_pair(dir.path());
+
+ let artifacts = ModelArtifacts::from_directory(dir.path(), None).expect("must resolve");
+ assert_eq!(artifacts.layout(), ModelLayout::Split);
+ match &artifacts.model {
+ ModelPaths::Split {
+ encoder_path,
+ head_path,
+ } => {
+ assert_eq!(encoder_path, &dir.path().join("encoder.onnx"));
+ assert_eq!(head_path, &dir.path().join("head.onnx"));
+ }
+ other => panic!("expected ModelPaths::Split, got {other:?}"),
+ }
+ // The split layout never ships tokenizer_config.json.
+ assert_eq!(artifacts.tokenizer_config_path, None);
+}
+
+#[test]
+fn from_directory_prefers_fused_when_both_layouts_are_present() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(dir.path());
+ std::fs::write(dir.path().join("encoder.onnx"), b"encoder-graph").unwrap();
+ std::fs::write(dir.path().join("head.onnx"), b"head-graph").unwrap();
+
+ let artifacts = ModelArtifacts::from_directory(dir.path(), None).expect("must resolve");
+ assert_eq!(artifacts.layout(), ModelLayout::Fused);
+}
+
+#[test]
+fn from_directory_reports_neither_layout_found() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ std::fs::write(dir.path().join("rl_agent_config.json"), b"{}").unwrap();
+ std::fs::write(dir.path().join("tokenizer.json"), b"{}").unwrap();
+
+ let err = ModelArtifacts::from_directory(dir.path(), None).expect_err("must fail");
+ match err {
+ LayaError::MissingFile { path, hint } => {
+ assert_eq!(path, dir.path().join("model.onnx"));
+ let hint = hint.expect("should explain both layouts");
+ assert!(hint.contains("encoder.onnx") && hint.contains("head.onnx"));
+ }
+ other => panic!("expected MissingFile, got {other:?}"),
+ }
+}
+
+#[test]
+fn from_directory_reports_a_half_written_split_export_by_the_missing_file() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ write_split_pair(dir.path());
+ std::fs::remove_file(dir.path().join("head.onnx")).unwrap();
+
+ let err = ModelArtifacts::from_directory(dir.path(), None).expect_err("must fail");
+ match err {
+ LayaError::MissingFile { path, .. } => {
+ assert_eq!(path, dir.path().join("head.onnx"));
+ }
+ other => panic!("expected MissingFile naming head.onnx, got {other:?}"),
+ }
+}
+
+// ── tokenizer lookup order ────────────────────────────────────────────────────
+
+#[test]
+fn from_directory_finds_tokenizer_in_the_nested_tokenizer_directory_first() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(dir.path());
+ // A root-level tokenizer.json should be ignored in favor of the nested one.
+ std::fs::write(dir.path().join("tokenizer.json"), b"root-copy").unwrap();
+
+ let artifacts = ModelArtifacts::from_directory(dir.path(), None).expect("must resolve");
+ assert_eq!(
+ artifacts.tokenizer_path,
+ dir.path().join("tokenizer").join("tokenizer.json")
+ );
+}
+
+#[test]
+fn from_directory_falls_back_to_the_root_tokenizer_when_no_nested_one_exists() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ write_split_pair(dir.path());
+
+ let artifacts = ModelArtifacts::from_directory(dir.path(), None).expect("must resolve");
+ assert_eq!(artifacts.tokenizer_path, dir.path().join("tokenizer.json"));
+}
+
+// ── from_directory ────────────────────────────────────────────────────────────
+
+#[test]
+fn from_directory_succeeds_and_resolves_paths_for_a_complete_directory() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(dir.path());
+
+ let artifacts = ModelArtifacts::from_directory(dir.path(), Some(LayaCheckpoint::Multilingual))
+ .expect("resolve should succeed");
+
+ assert_eq!(artifacts.layout(), ModelLayout::Fused);
+ match &artifacts.model {
+ ModelPaths::Fused { model_path } => {
+ assert_eq!(model_path, &dir.path().join("model.onnx"));
+ }
+ other => panic!("expected ModelPaths::Fused, got {other:?}"),
+ }
+ assert_eq!(
+ artifacts.config_path,
+ dir.path().join("rl_agent_config.json")
+ );
+ assert_eq!(
+ artifacts.tokenizer_path,
+ dir.path().join("tokenizer").join("tokenizer.json")
+ );
+ assert_eq!(artifacts.checkpoint, Some(LayaCheckpoint::Multilingual));
+}
+
+#[test]
+fn from_directory_reports_missing_file_by_name() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(dir.path());
+ std::fs::remove_file(dir.path().join("rl_agent_config.json")).unwrap();
+
+ let err = ModelArtifacts::from_directory(dir.path(), None).expect_err("must fail");
+ match err {
+ LayaError::MissingFile { path, .. } => {
+ assert_eq!(path, dir.path().join("rl_agent_config.json"));
+ }
+ other => panic!("expected MissingFile, got {other:?}"),
+ }
+}
+
+#[test]
+fn from_directory_reports_directory_not_found() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let missing = dir.path().join("does-not-exist");
+
+ let err = ModelArtifacts::from_directory(&missing, None).expect_err("must fail");
+ assert!(matches!(err, LayaError::DirectoryNotFound { .. }));
+}
+
+// ── resolve: precedence ───────────────────────────────────────────────────────
+
+#[test]
+fn resolve_prefers_model_directory_over_everything_else() {
+ let _env = lock_env();
+ let (_dir_guard, _root_guard) = clear_onnx_env_vars();
+
+ let option_dir = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(option_dir.path());
+
+ let env_dir = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(env_dir.path());
+ let _env_dir_set = EnvVarGuard::set("LAYA_ONNX_DIR", env_dir.path().to_str().unwrap());
+
+ let cache_root = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(&cache_root.path().join("multilingual"));
+
+ let mut options = plain_options();
+ options.model_directory = Some(option_dir.path().to_path_buf());
+ options.cache_directory = Some(cache_root.path().to_path_buf());
+
+ let artifacts = ModelArtifacts::resolve(&options).expect("resolve should succeed");
+ assert_eq!(artifacts.directory, option_dir.path());
+ // Explicit directories carry no inferred checkpoint.
+ assert_eq!(artifacts.checkpoint, None);
+}
+
+#[test]
+fn resolve_prefers_env_dir_over_onnx_root_and_cache() {
+ let _env = lock_env();
+ let (_dir_guard, _root_guard) = clear_onnx_env_vars();
+
+ let env_dir = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(env_dir.path());
+ let _env_dir_set = EnvVarGuard::set("LAYA_ONNX_DIR", env_dir.path().to_str().unwrap());
+
+ let onnx_root = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(&onnx_root.path().join("multilingual"));
+ let _root_set = EnvVarGuard::set("LAYA_ONNX_ROOT", onnx_root.path().to_str().unwrap());
+
+ let cache_root = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(&cache_root.path().join("multilingual"));
+
+ let mut options = plain_options();
+ options.cache_directory = Some(cache_root.path().to_path_buf());
+
+ let artifacts = ModelArtifacts::resolve(&options).expect("resolve should succeed");
+ assert_eq!(artifacts.directory, env_dir.path());
+ assert_eq!(artifacts.checkpoint, None);
+}
+
+#[test]
+fn resolve_prefers_onnx_root_over_cache() {
+ let _env = lock_env();
+ let (_dir_guard, _root_guard) = clear_onnx_env_vars();
+
+ let onnx_root = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(&onnx_root.path().join("multilingual"));
+ let _root_set = EnvVarGuard::set("LAYA_ONNX_ROOT", onnx_root.path().to_str().unwrap());
+
+ let cache_root = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(&cache_root.path().join("multilingual"));
+
+ let mut options = plain_options();
+ options.cache_directory = Some(cache_root.path().to_path_buf());
+
+ let artifacts = ModelArtifacts::resolve(&options).expect("resolve should succeed");
+ assert_eq!(artifacts.directory, onnx_root.path().join("multilingual"));
+ assert_eq!(artifacts.checkpoint, Some(LayaCheckpoint::Multilingual));
+}
+
+#[test]
+fn resolve_falls_through_a_stale_onnx_root_to_the_cache() {
+ // LAYA_ONNX_ROOT is set but this checkpoint's subdirectory under it is incomplete: resolution
+ // must fall through to the cache rather than failing immediately.
+ let _env = lock_env();
+ let (_dir_guard, _root_guard) = clear_onnx_env_vars();
+
+ let onnx_root = tempfile::tempdir().expect("tempdir");
+ std::fs::create_dir_all(onnx_root.path().join("multilingual")).unwrap();
+ // Incomplete: no model.onnx.data.
+ std::fs::write(
+ onnx_root.path().join("multilingual").join("model.onnx"),
+ b"x",
+ )
+ .unwrap();
+ let _root_set = EnvVarGuard::set("LAYA_ONNX_ROOT", onnx_root.path().to_str().unwrap());
+
+ let cache_root = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(&cache_root.path().join("multilingual"));
+
+ let mut options = plain_options();
+ options.cache_directory = Some(cache_root.path().to_path_buf());
+
+ let artifacts = ModelArtifacts::resolve(&options).expect("resolve should succeed");
+ assert_eq!(artifacts.directory, cache_root.path().join("multilingual"));
+}
+
+#[test]
+fn resolve_uses_the_cache_directory_when_nothing_else_is_set() {
+ let _env = lock_env();
+ let (_dir_guard, _root_guard) = clear_onnx_env_vars();
+
+ let cache_root = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(&cache_root.path().join("english"));
+
+ let mut options = plain_options();
+ options.cache_directory = Some(cache_root.path().to_path_buf());
+ options.checkpoint = LayaCheckpoint::English;
+
+ let artifacts = ModelArtifacts::resolve(&options).expect("resolve should succeed");
+ assert_eq!(artifacts.directory, cache_root.path().join("english"));
+ assert_eq!(artifacts.checkpoint, Some(LayaCheckpoint::English));
+}
+
+#[test]
+fn resolve_respects_checkpoint_subdirectory_naming() {
+ let _env = lock_env();
+ let (_dir_guard, _root_guard) = clear_onnx_env_vars();
+
+ let cache_root = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(&cache_root.path().join("typed-decisions"));
+
+ let mut options = plain_options();
+ options.cache_directory = Some(cache_root.path().to_path_buf());
+ options.checkpoint = LayaCheckpoint::TypedDecisions;
+
+ let artifacts = ModelArtifacts::resolve(&options).expect("resolve should succeed");
+ assert_eq!(
+ artifacts.directory,
+ cache_root.path().join("typed-decisions")
+ );
+}
+
+// ── resolve: not found ────────────────────────────────────────────────────────
+
+#[test]
+fn resolve_reports_every_location_tried_when_nothing_is_found() {
+ let _env = lock_env();
+ let (_dir_guard, _root_guard) = clear_onnx_env_vars();
+
+ let cache_root = tempfile::tempdir().expect("tempdir");
+ // Deliberately left empty: no complete artifact anywhere.
+
+ let mut options = plain_options();
+ options.cache_directory = Some(cache_root.path().to_path_buf());
+ options.allow_download = false;
+
+ let err = ModelArtifacts::resolve(&options).expect_err("must fail: nothing is present");
+ let message = err.to_string();
+
+ assert!(matches!(err, LayaError::ArtifactsNotFound { .. }));
+ assert!(message.contains("not found"), "message was: {message}");
+ let expected_cache_dir = cache_root.path().join("multilingual");
+ assert!(
+ message.contains(expected_cache_dir.to_str().unwrap()),
+ "message should name the cache directory it tried: {message}"
+ );
+ assert!(
+ message.contains("LayaOptions::model_directory"),
+ "message should list the ModelDirectory step: {message}"
+ );
+ assert!(
+ message.contains("LAYA_ONNX_DIR"),
+ "message should list the LAYA_ONNX_DIR step: {message}"
+ );
+ assert!(
+ message.contains("LAYA_ONNX_ROOT"),
+ "message should list the LAYA_ONNX_ROOT step: {message}"
+ );
+}
+
+#[test]
+fn resolve_not_found_message_names_the_onnx_root_path_when_the_env_var_is_set() {
+ let _env = lock_env();
+ let (_dir_guard, _root_guard) = clear_onnx_env_vars();
+
+ let onnx_root = tempfile::tempdir().expect("tempdir");
+ // Root is set but has nothing under it for this checkpoint.
+ let _root_set = EnvVarGuard::set("LAYA_ONNX_ROOT", onnx_root.path().to_str().unwrap());
+
+ let cache_root = tempfile::tempdir().expect("tempdir");
+
+ let mut options = plain_options();
+ options.cache_directory = Some(cache_root.path().to_path_buf());
+
+ let err = ModelArtifacts::resolve(&options).expect_err("must fail");
+ let message = err.to_string();
+ let expected_root_dir = onnx_root.path().join("multilingual");
+ assert!(
+ message.contains(expected_root_dir.to_str().unwrap()),
+ "message should name the LAYA_ONNX_ROOT path it tried: {message}"
+ );
+}
+
+#[test]
+fn resolve_with_allow_download_false_never_touches_the_network() {
+ let _env = lock_env();
+ let (_dir_guard, _root_guard) = clear_onnx_env_vars();
+
+ let cache_root = tempfile::tempdir().expect("tempdir");
+
+ let mut options = plain_options();
+ options.cache_directory = Some(cache_root.path().to_path_buf());
+ options.allow_download = false;
+ // A repo name that does not exist; if resolve() attempted a network call despite
+ // allow_download being false, this would surface as a very different (slow, DNS-error)
+ // failure rather than the immediate ArtifactsNotFound below.
+ options.hugging_face_repo = "this-repo-does-not-exist/laya-nope".to_string();
+
+ let started = std::time::Instant::now();
+ let err = ModelArtifacts::resolve(&options).expect_err("must fail without downloading");
+ assert!(matches!(err, LayaError::ArtifactsNotFound { .. }));
+ // Resolution is pure filesystem/env work when allow_download is false; it should complete
+ // near-instantly. A generous bound avoids flakiness on a loaded CI box while still catching
+ // an accidental network attempt (which would take seconds, not milliseconds).
+ assert!(
+ started.elapsed() < std::time::Duration::from_secs(2),
+ "resolve() with allow_download=false took {:?}; it may have attempted a network call",
+ started.elapsed()
+ );
+}
+
+// ── resolve: explicit-path validation errors propagate ────────────────────────
+
+#[test]
+fn resolve_propagates_missing_file_error_from_an_explicit_model_directory() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ write_complete_artifact(dir.path());
+ std::fs::remove_file(dir.path().join("model.onnx")).unwrap();
+
+ let mut options = plain_options();
+ options.model_directory = Some(dir.path().to_path_buf());
+
+ let err = ModelArtifacts::resolve(&options).expect_err("must fail");
+ assert!(matches!(err, LayaError::MissingFile { .. }));
+}
+
+#[test]
+fn resolve_propagates_directory_not_found_from_laya_onnx_dir() {
+ let _env = lock_env();
+ let (_dir_guard, _root_guard) = clear_onnx_env_vars();
+
+ let missing = tempfile::tempdir()
+ .expect("tempdir")
+ .path()
+ .join("does-not-exist");
+ let _env_dir_set = EnvVarGuard::set("LAYA_ONNX_DIR", missing.to_str().unwrap());
+
+ let options = plain_options();
+ let err = ModelArtifacts::resolve(&options).expect_err("must fail");
+ assert!(matches!(err, LayaError::DirectoryNotFound { .. }));
+}
+
+// ── download feature gate ──────────────────────────────────────────────────────
+
+#[test]
+#[cfg(not(feature = "download"))]
+fn resolve_with_allow_download_true_and_no_download_feature_gives_a_clear_error() {
+ let _env = lock_env();
+ let (_dir_guard, _root_guard) = clear_onnx_env_vars();
+
+ let cache_root = tempfile::tempdir().expect("tempdir");
+ let mut options = plain_options();
+ options.cache_directory = Some(cache_root.path().to_path_buf());
+ options.allow_download = true;
+
+ let err = ModelArtifacts::resolve(&options).expect_err("must fail: no download feature");
+ let message = err.to_string();
+ assert!(
+ message.contains("download") && message.contains("feature"),
+ "message should explain the missing `download` feature: {message}"
+ );
+}
diff --git a/laya-rust/tools/export_onnx.py b/laya-rust/tools/export_onnx.py
new file mode 100644
index 00000000..41cc0971
--- /dev/null
+++ b/laya-rust/tools/export_onnx.py
@@ -0,0 +1,882 @@
+"""Export a Laya checkpoint to ONNX with external weights.
+
+Produces the same artifact layout as the pre-built exports in onnx/:
+
+ <out>/<name>/
+ model.onnx # graph structure (~2-3 MB)
+ model.onnx.data # weight sidecar (all initializers, ~1.3 GB)
+ rl_agent_config.json
+ tokenizer/
+ tokenizer.json
+ tokenizer_config.json
+ fixtures.npz # PyTorch reference outputs for ONNX parity checks
+
+The tokenizer post_processor (TemplateProcessing) is deliberately kept in
+tokenizer.json. Some SDK ports strip it at load time and cache the result as
+tokenizer.nopost.json -- that file, if present, is created by the SDK, not by this script.
+
+Usage:
+ # Export the multilingual checkpoint to onnx/multilingual/
+ python laya-rust/tools/export_onnx.py --model multilingual
+
+ # Re-export, overwriting an existing artifact
+ python laya-rust/tools/export_onnx.py --model multilingual --force
+
+ # Export all three checkpoints and verify each against PyTorch
+ python laya-rust/tools/export_onnx.py --model all --verify
+
+ # Export to a custom directory and verify
+ python laya-rust/tools/export_onnx.py --model multilingual --out /tmp/laya-test --verify
+
+ # Export a local checkpoint directory (must contain rl_agent_config.json)
+ python laya-rust/tools/export_onnx.py /path/to/checkpoint --out onnx/my-model --verify
+
+ # Use a private HuggingFace token
+ python laya-rust/tools/export_onnx.py --model typed-decisions --token hf_...
+
+ # Redirect HuggingFace cache to a drive with more free space (typed-decisions is 842 MB)
+ HF_HOME=/d/hf_cache python laya-rust/tools/export_onnx.py --model typed-decisions
+"""
+
+import argparse
+import io
+import json
+import os
+import shutil
+import sys
+import tempfile
+import time
+
+TOOLS = os.path.dirname(os.path.abspath(__file__))
+REPO = os.path.dirname(os.path.dirname(TOOLS))
+sys.path.insert(0, REPO)
+
+from laya.agent import _fix_tokenizer_config # noqa: E402
+from laya.common import ( # noqa: E402
+ QTYPES,
+ build_model,
+ build_sequence,
+ collate_items,
+)
+from laya.router import BUNDLE_REPO, DEFAULT_MODELS, STANDALONE_MODELS # noqa: E402
+
+
+# ─── model catalogue ────────────────────────────────────────────────────────
+
+# Canonical short names for the three shipped checkpoints.
+_NAMES = ["english", "multilingual", "typed-decisions"]
+
+
+def _resolve_spec(name_or_path: str, token: str):
+ """Return (model_dir, subfolder, label) for a name or a local path."""
+ if os.path.exists(name_or_path):
+ # Local directory: treat as a self-contained checkpoint.
+ return name_or_path, None, os.path.basename(name_or_path.rstrip("/\\"))
+
+ if name_or_path not in _NAMES:
+ raise SystemExit(
+ "unknown model %r; use one of %s or a local path" % (name_or_path, _NAMES)
+ )
+
+ repo, subfolder = DEFAULT_MODELS[name_or_path]
+
+ import huggingface_hub
+
+ prefix = (subfolder + "/") if subfolder else ""
+ kw = {
+ "token": token or os.environ.get("HF_TOKEN"),
+ "allow_patterns": [
+ prefix + n for n in (
+ "rl_agent_config.json",
+ "model.safetensors",
+ "tokenizer/*",
+ "encoder/*",
+ )
+ ],
+ }
+ print(" downloading %s/%s from HuggingFace Hub..." % (repo, subfolder or "(root)"))
+ model_dir = huggingface_hub.snapshot_download(repo, **kw)
+ return model_dir, subfolder, name_or_path
+
+
+# ─── fixture cases ──────────────────────────────────────────────────────────
+
+# Two synthetic test cases, chosen to cover noul (2 markers) and a mixed
+# multi-question batch (max 5 markers). These are identical across all
+# checkpoints: the state and question texts are the same; only the tokenised
+# lengths differ.
+
+_NOUL_STATE = (
+ "Subject: Double charged on invoice 88213\n\n"
+ "Hi, I was billed twice this month for the Pro plan and the second "
+ "charge has not been refunded. This is the third time I have written in."
+)
+_NOUL_QUESTIONS = {
+ "churn_risk": {
+ "t": "noul",
+ "ins": "The customer threatens to cancel the account.",
+ "crit": None,
+ }
+}
+
+_TRIAGE_STATE = _NOUL_STATE
+_TRIAGE_QUESTIONS = {
+ "department": {
+ "t": "choice",
+ "ins": "Which department should handle this?",
+ "crit": {
+ "billing": "invoices, payments, double charges, refunds",
+ "technical": "bugs, outages, integration errors",
+ "account": "logins, seats, plan changes",
+ "escalation": "manager required, repeat issue, SLA breach",
+ "retention": "cancellation threats, churn risk",
+ },
+ },
+ "urgency": {
+ "t": "score",
+ "ins": "How urgent is this request?",
+ "crit": ["not urgent", "this week", "today", "drop everything"],
+ },
+ "churn_risk": {
+ "t": "noul",
+ "ins": "The customer threatens to cancel the account.",
+ "crit": None,
+ },
+ "needs_human": {
+ "t": "noul",
+ "ins": "This requires a human agent rather than an automated reply.",
+ "crit": {"false": "a template reply resolves it", "true": "a person must intervene"},
+ },
+}
+
+
+def _build_fixture_group(tok, questions, state, max_len, head_max_len, pad_id):
+ """Collate one fixture group and return the numpy arrays."""
+ import numpy as np
+
+ items = []
+ for qid, q in questions.items():
+ seq, markers = build_sequence(tok, state, q, max_len, head_max_len)
+ items.append({
+ "ids": seq,
+ "markers": markers,
+ "qtype": QTYPES[q["t"]],
+ })
+ batch = collate_items([items], pad_id)
+ return {
+ "input_ids": batch["input_ids"].numpy().astype(np.int64),
+ "attention_mask": batch["attention_mask"].numpy().astype(np.int64),
+ "marker_pos": batch["marker_pos"].numpy().astype(np.int64),
+ "marker_mask": batch["marker_mask"].numpy(), # bool
+ "qtype": batch["qtype"].numpy().astype(np.int64),
+ }
+
+
+def _time_forward(model, inputs_pt, n=5):
+ """Return n wall-clock timings (seconds) for a forward pass, discarding the first."""
+ import torch
+ times = []
+ with torch.no_grad():
+ for _ in range(n + 1):
+ t0 = time.perf_counter()
+ model(*inputs_pt)
+ times.append(time.perf_counter() - t0)
+ return times[1:] # skip first (warm-up)
+
+
+def generate_fixtures(model, tok, cfg, out_dir):
+ """Save PyTorch reference outputs as fixtures.npz."""
+ import numpy as np
+ import torch
+
+ max_len = cfg.get("max_len", 512)
+ head_max_len = cfg.get("head_max_len", 192)
+ pad_id = tok.pad_token_id
+
+ groups = {
+ "single_noul": _build_fixture_group(
+ tok, _NOUL_QUESTIONS, _NOUL_STATE, max_len, head_max_len, pad_id
+ ),
+ "triage_4q": _build_fixture_group(
+ tok, _TRIAGE_QUESTIONS, _TRIAGE_STATE, max_len, head_max_len, pad_id
+ ),
+ }
+
+ arrays = {}
+ model.eval()
+ with torch.no_grad():
+ for g, tensors in groups.items():
+ inp_pt = [
+ torch.from_numpy(tensors["input_ids"]),
+ torch.from_numpy(tensors["attention_mask"]),
+ torch.from_numpy(tensors["marker_pos"]),
+ torch.from_numpy(tensors["marker_mask"]),
+ torch.from_numpy(tensors["qtype"]),
+ ]
+ logits, act_logits = model(*inp_pt)
+ arrays["%s/input_ids" % g] = tensors["input_ids"]
+ arrays["%s/attention_mask" % g] = tensors["attention_mask"]
+ arrays["%s/marker_pos" % g] = tensors["marker_pos"]
+ arrays["%s/marker_mask" % g] = tensors["marker_mask"]
+ arrays["%s/qtype" % g] = tensors["qtype"]
+ arrays["%s/ref_logits" % g] = logits.float().cpu().numpy()
+ arrays["%s/ref_act" % g] = act_logits.float().cpu().numpy()
+ timings = _time_forward(model, inp_pt)
+ arrays["%s/torch_ms" % g] = np.array(
+ [t * 1000.0 for t in timings], dtype=np.float64
+ )
+
+ path = os.path.join(out_dir, "fixtures.npz")
+ np.savez(path, **arrays)
+
+ for g in groups:
+ shape_ids = arrays["%s/input_ids" % g].shape
+ shape_mp = arrays["%s/marker_pos" % g].shape
+ print(
+ " fixture %-14s input_ids=%s marker_pos=%s" % (g, shape_ids, shape_mp)
+ )
+ print(" wrote %s" % path)
+
+
+# ─── ONNX export ────────────────────────────────────────────────────────────
+
+def _dummy_inputs():
+ """Dummy inputs for the ONNX export trace.
+
+ batch=2 (not 1): using batch=1 causes the dynamo exporter to specialise
+ (fix) the batch axis as a static 1 even when batch is listed in
+ dynamic_shapes. batch=2 forces a symbolic batch node into the graph.
+ seq=32, markers=2 are near-minimum values; the Dim constraints extend them
+ to the full legal range.
+ """
+ import torch
+
+ B, S, M = 2, 32, 2
+ return (
+ torch.zeros(B, S, dtype=torch.long),
+ torch.ones(B, S, dtype=torch.long),
+ torch.zeros(B, M, dtype=torch.long),
+ torch.ones(B, M, dtype=torch.bool),
+ torch.zeros(B, dtype=torch.long),
+ )
+
+
+def export_onnx(model, out_dir: str, opset: int = 18):
+ """Export model to model.onnx + model.onnx.data in out_dir.
+
+ Uses torch.onnx.export with dynamo=True (the new torch.export-based path,
+ default from PyTorch 2.9+). The dynamo exporter inserts Shape/Concat nodes
+ to compute tensor shapes symbolically at runtime, giving fully dynamic axes
+ for batch, seq, and markers -- matching the pre-built artifacts exactly.
+
+ The legacy TorchScript tracer (dynamo=False) bakes concrete shapes from the
+ dummy inputs, so e.g. the ModernBERT sliding-window attention would always
+ expect the traced sequence length.
+ """
+ import torch
+ from torch.export.dynamic_shapes import Dim
+
+ model.eval()
+ dummy = _dummy_inputs()
+
+ # Declare all three free dimensions: batch, seq, markers.
+ batch = Dim("batch", min=1, max=1024)
+ seq = Dim("seq", min=1, max=8192)
+ markers = Dim("markers", min=2, max=512) # min=2: TopK(k=2) constraint
+
+ dynamic_shapes = (
+ {0: batch, 1: seq}, # input_ids
+ {0: batch, 1: seq}, # attention_mask
+ {0: batch, 1: markers}, # marker_pos
+ {0: batch, 1: markers}, # marker_mask
+ {0: batch}, # qtype
+ )
+
+ # The dynamo exporter prints unicode emoji (✅, etc.) which crashes on
+ # Windows consoles with a non-UTF-8 code page. Reconfigure stdout/stderr to
+ # UTF-8 with replacement for the duration of the export.
+ for _stream in (sys.stdout, sys.stderr):
+ try:
+ _stream.reconfigure(encoding="utf-8", errors="replace")
+ except (AttributeError, io.UnsupportedOperation):
+ pass
+
+ with torch.no_grad():
+ prog = torch.onnx.export(
+ model,
+ dummy,
+ f=None,
+ input_names=["input_ids", "attention_mask", "marker_pos", "marker_mask", "qtype"],
+ output_names=["logits", "act_logits"],
+ dynamic_shapes=dynamic_shapes,
+ opset_version=opset,
+ dynamo=True,
+ external_data=False, # we handle external data ourselves below
+ optimize=True,
+ report=False,
+ )
+
+ if prog is None:
+ raise RuntimeError("torch.onnx.export returned None -- export failed")
+
+ import onnx
+
+ # Save to a temp file first, then re-save with our specific external-data layout.
+ # For large models (≥ ~1.6 GB weights), prog.save may create an external-data
+ # sidecar alongside the temp file even when external_data=False. Clean up both.
+ tmp_path = os.path.join(out_dir, "_model_tmp.onnx")
+ tmp_data_path = tmp_path + ".data"
+ try:
+ prog.save(tmp_path, external_data=False)
+ proto = onnx.load(tmp_path)
+ finally:
+ for _p in (tmp_path, tmp_data_path):
+ if os.path.exists(_p):
+ os.remove(_p)
+
+ # onnx.save_model opens the external-data sidecar in append mode, so if a
+ # previous export left a stale file it would be silently inflated. Always
+ # remove both output files before writing.
+ final_path = os.path.join(out_dir, "model.onnx")
+ data_path = os.path.join(out_dir, "model.onnx.data")
+ for p in (final_path, data_path):
+ if os.path.exists(p):
+ os.remove(p)
+
+ # Persist with large initializers (weight matrices etc.) in one sidecar named
+ # exactly "model.onnx.data". Tensors ≤ 1 KB stay inline so ONNX Runtime can
+ # perform shape inference without having to parse external-data files (which it
+ # cannot do for shape-inference purposes).
+ onnx.save_model(
+ proto,
+ final_path,
+ save_as_external_data=True,
+ all_tensors_to_one_file=True,
+ location="model.onnx.data", # must be exactly this name
+ size_threshold=1024, # keep tensors ≤ 1 KB inline
+ convert_attribute=False,
+ )
+
+ size_graph = os.path.getsize(final_path)
+ size_data = os.path.getsize(os.path.join(out_dir, "model.onnx.data"))
+ print(
+ " model.onnx %.1f MB model.onnx.data %.1f MB"
+ % (size_graph / 1e6, size_data / 1e6)
+ )
+
+
+# ─── tokenizer copy ─────────────────────────────────────────────────────────
+
+def copy_tokenizer(model_dir: str, out_dir: str):
+ """Copy tokenizer/ from model_dir to out_dir/tokenizer/."""
+ src_tok = os.path.join(model_dir, "tokenizer")
+ dst_tok = os.path.join(out_dir, "tokenizer")
+
+ if not os.path.isdir(src_tok):
+ raise FileNotFoundError("tokenizer directory not found: %s" % src_tok)
+
+ os.makedirs(dst_tok, exist_ok=True)
+ n = 0
+ for fname in os.listdir(src_tok):
+ # Copy the canonical tokenizer files; skip any pre-existing nopost cache
+ # (a strip-and-cache SDK regenerates them at load time from tokenizer.json).
+ if fname.endswith(".nopost.json") or fname.endswith(".nopost.json.meta"):
+ continue
+ shutil.copy2(os.path.join(src_tok, fname), os.path.join(dst_tok, fname))
+ n += 1
+ print(" tokenizer/ (%d files)" % n)
+
+ # Apply the same tokenizer_config fix that Agent.__init__ does, so the directory
+ # works with AutoTokenizer.from_pretrained() without any environment correction.
+ _fix_tokenizer_config(out_dir)
+
+
+# ─── ONNX parity verification ────────────────────────────────────────────────
+
+def _run_onnx(sess, feeds_np):
+ """Run one ONNX inference and return (logits, act_logits) as numpy arrays."""
+ input_meta = {i.name: i.type for i in sess.get_inputs()}
+ _NP = {
+ "tensor(int64)": __import__("numpy").int64,
+ "tensor(int32)": __import__("numpy").int32,
+ "tensor(bool)": __import__("numpy").bool_,
+ "tensor(float)": __import__("numpy").float32,
+ }
+ feeds = {n: feeds_np[n].astype(_NP[input_meta[n]]) for n in input_meta}
+ return sess.run(["logits", "act_logits"], feeds)
+
+
+def verify(out_dir: str, cfg: dict, seq_lens=None, batch_sizes=None, marker_counts=None):
+ """Verify the exported ONNX matches PyTorch across a range of tensor shapes.
+
+ Feeds synthetic zero-valued tensors so no text or tokenizer is needed.
+ Reports max absolute difference on logits and act_logits for every shape.
+ """
+ import numpy as np
+ import onnxruntime as ort
+ import torch
+
+ from laya.common import build_model as _build_model
+
+ if seq_lens is None:
+ seq_lens = [16, 32, 64, 128, 256, cfg.get("max_len", 512)]
+ if batch_sizes is None:
+ batch_sizes = [1, 3]
+ if marker_counts is None:
+ marker_counts = [2, 5, 9]
+
+ # Load the exported model weights for PyTorch re-evaluation.
+ # Re-use the fixtures.npz rather than re-downloading to avoid an extra
+ # snapshot_download; the fixtures were written from the same weights.
+ fixtures_path = os.path.join(out_dir, "fixtures.npz")
+ if not os.path.exists(fixtures_path):
+ raise SystemExit("fixtures.npz not found in %s; run without --verify first" % out_dir)
+
+ sess = ort.InferenceSession(
+ os.path.join(out_dir, "model.onnx"),
+ sess_options=ort.SessionOptions(),
+ providers=["CPUExecutionProvider"],
+ )
+
+ # --- self-check against fixtures ----------------------------------------
+ z = np.load(fixtures_path)
+ groups = sorted({k.split("/")[0] for k in z.files})
+ print(" self-check against fixtures.npz:")
+ for g in groups:
+ need = ["input_ids", "attention_mask", "marker_pos", "marker_mask", "qtype"]
+ if not all("%s/%s" % (g, n) in z.files for n in need):
+ continue
+ feeds = {n: z["%s/%s" % (g, n)] for n in need}
+ logits, act = _run_onnx(sess, feeds)
+ d_logits = float(np.abs(logits - z["%s/ref_logits" % g]).max())
+ d_act = float(np.abs(act - z["%s/ref_act" % g]).max())
+ ok = "OK" if d_logits <= 1e-3 and d_act <= 1e-2 else "FAIL"
+ print(
+ " %-14s logits %.3e act_logits %.3e %s" % (g, d_logits, d_act, ok)
+ )
+ if ok == "FAIL":
+ raise SystemExit(
+ "ONNX parity check failed for %r (logits %.3e > 1e-3 or "
+ "act_logits %.3e > 1e-2)" % (g, d_logits, d_act)
+ )
+
+ # --- shape sweep --------------------------------------------------------
+ print(
+ " shape sweep: %d seq_lens × %d batch_sizes × %d marker_counts = %d combos"
+ % (len(seq_lens), len(batch_sizes), len(marker_counts),
+ len(seq_lens) * len(batch_sizes) * len(marker_counts))
+ )
+
+ # We need PyTorch weights for the shape sweep comparison. Load from the
+ # original checkpoint directory if it is still cached locally.
+ # If not available, skip PyTorch comparison and only check that the ONNX
+ # session runs without error and produces the expected output shapes.
+ pt_model = _load_pt_model_if_cached(cfg, out_dir)
+
+ max_d_logits = max_d_act = 0.0
+ n_ok = n_skip = 0
+ max_len = cfg.get("max_len", 512)
+
+ for seq in seq_lens:
+ if seq > max_len:
+ continue
+ for B in batch_sizes:
+ for M in marker_counts:
+ feeds = _make_synthetic_feeds(B, seq, M)
+ logits_onnx, act_onnx = _run_onnx(sess, feeds)
+
+ # Shape assertions.
+ assert logits_onnx.shape == (B, M), \
+ "logits shape %s != (%d, %d)" % (logits_onnx.shape, B, M)
+ assert act_onnx.shape[0] == B, \
+ "act_logits batch %d != %d" % (act_onnx.shape[0], B)
+
+ if pt_model is not None:
+ inp = [
+ torch.from_numpy(feeds["input_ids"]),
+ torch.from_numpy(feeds["attention_mask"]),
+ torch.from_numpy(feeds["marker_pos"]),
+ torch.from_numpy(feeds["marker_mask"]),
+ torch.from_numpy(feeds["qtype"]),
+ ]
+ with torch.no_grad():
+ logits_pt, act_pt = pt_model(*inp)
+ logits_pt = logits_pt.float().numpy()
+ act_pt = act_pt.float().numpy()
+
+ d_l = float(abs(logits_onnx - logits_pt).max())
+ d_a = float(abs(act_onnx - act_pt).max())
+ max_d_logits = max(max_d_logits, d_l)
+ max_d_act = max(max_d_act, d_a)
+ n_ok += 1
+ else:
+ n_skip += 1
+
+ if pt_model is not None:
+ print(
+ " shape sweep done: %d combos, max diff logits %.3e act_logits %.3e"
+ % (n_ok, max_d_logits, max_d_act)
+ )
+ else:
+ print(
+ " shape sweep done: %d combos (PyTorch not available, "
+ "shape/session checks only)" % (n_ok + n_skip)
+ )
+
+
+def _make_synthetic_feeds(B, seq, M):
+ """Synthetic zero inputs of the given shape for the shape sweep."""
+ import numpy as np
+
+ return {
+ "input_ids": np.zeros((B, seq), dtype=np.int64),
+ "attention_mask": np.ones((B, seq), dtype=np.int64),
+ "marker_pos": np.zeros((B, M), dtype=np.int64),
+ "marker_mask": np.ones((B, M), dtype=np.bool_),
+ "qtype": np.zeros(B, dtype=np.int64),
+ }
+
+
+def _load_pt_model_if_cached(cfg, out_dir):
+ """Return a loaded PyTorch model if weights are available locally, else None."""
+ from safetensors.torch import load_file
+ import torch
+
+ # The export was done from a snapshot_download() cache; try to locate the
+ # safetensors file there. If it is gone (evicted or never downloaded because
+ # the user supplied a local path that has since been removed), skip PT compare.
+ cache_candidates = []
+ # Check if there is a safetensors file alongside the onnx output (for local-path exports).
+ out_parent = os.path.dirname(out_dir)
+ for candidate in [
+ os.path.join(out_parent, "model.safetensors"),
+ os.path.join(out_dir, "model.safetensors"), # shouldn't normally exist here
+ ]:
+ if os.path.exists(candidate):
+ cache_candidates.append(candidate)
+
+ # Also check the HF cache for a known pattern.
+ try:
+ import huggingface_hub
+ cache_info = huggingface_hub.scan_cache_dir()
+ for repo in cache_info.repos:
+ for rev in repo.revisions:
+ for f in rev.files:
+ if f.file_name == "model.safetensors" and os.path.exists(f.file_path):
+ cache_candidates.append(str(f.file_path))
+ except Exception:
+ pass
+
+ # Find a safetensors that is compatible with this cfg's architecture.
+ for sf_path in cache_candidates:
+ try:
+ model = build_model(cfg)
+ weights = load_file(sf_path)
+ model.load_state_dict(weights, strict=True)
+ try:
+ model.encoder.config.reference_compile = False
+ except Exception:
+ pass
+ model.eval()
+ return model
+ except Exception:
+ continue
+
+ return None
+
+
+# ─── ONNX graph signature check ─────────────────────────────────────────────
+
+def check_graph_signature(out_dir: str, reference_onnx: str):
+ """Compare input/output names, dtypes, and dynamic-axis names to a reference graph."""
+ import onnx
+
+ def sig(path):
+ m = onnx.load(path, load_external_data=False)
+ return {
+ "opset": m.opset_import[0].version,
+ "inputs": {
+ inp.name: {
+ "dtype": inp.type.tensor_type.elem_type,
+ "dims": [
+ d.dim_param if d.dim_param else d.dim_value
+ for d in inp.type.tensor_type.shape.dim
+ ],
+ }
+ for inp in m.graph.input
+ },
+ "outputs": {
+ out.name: {
+ "dtype": out.type.tensor_type.elem_type,
+ "dims": [
+ d.dim_param if d.dim_param else d.dim_value
+ for d in out.type.tensor_type.shape.dim
+ ],
+ }
+ for out in m.graph.output
+ },
+ }
+
+ new_sig = sig(os.path.join(out_dir, "model.onnx"))
+ ref_sig = sig(reference_onnx)
+
+ ok = True
+ # Opset
+ if new_sig["opset"] != ref_sig["opset"]:
+ print(" WARN opset %d != reference %d" % (new_sig["opset"], ref_sig["opset"]))
+ ok = False
+ # Inputs
+ for name, ref_inp in ref_sig["inputs"].items():
+ if name not in new_sig["inputs"]:
+ print(" WARN input %r missing" % name)
+ ok = False
+ continue
+ new_inp = new_sig["inputs"][name]
+ if new_inp["dtype"] != ref_inp["dtype"]:
+ print(" WARN input %r dtype %d != %d" % (name, new_inp["dtype"], ref_inp["dtype"]))
+ ok = False
+ if new_inp["dims"] != ref_inp["dims"]:
+ print(" WARN input %r dims %s != %s" % (name, new_inp["dims"], ref_inp["dims"]))
+ ok = False
+ # Outputs
+ for name, ref_out in ref_sig["outputs"].items():
+ if name not in new_sig["outputs"]:
+ print(" WARN output %r missing" % name)
+ ok = False
+ continue
+ new_out = new_sig["outputs"][name]
+ if new_out["dtype"] != ref_out["dtype"]:
+ print(" WARN output %r dtype %d != %d" % (name, new_out["dtype"], ref_out["dtype"]))
+ ok = False
+ if new_out["dims"] != ref_out["dims"]:
+ print(" WARN output %r dims %s != %s" % (name, new_out["dims"], ref_out["dims"]))
+ ok = False
+ if ok:
+ print(" graph signature matches reference (%s)" % os.path.basename(os.path.dirname(reference_onnx)))
+ return ok
+
+
+# ─── main per-model export ───────────────────────────────────────────────────
+
+def export_one(name_or_path: str, out_root: str, token: str, opset: int, do_verify: bool,
+ force: bool = False):
+ """Download (if needed), export, and verify one checkpoint.
+
+ Raises RuntimeError if <out_root>/<name>/model.onnx already exists and
+ force is False. Pass force=True (--force on the CLI) to overwrite.
+ The check happens before any download so nothing is wasted on a refusal.
+ """
+ from safetensors.torch import load_file
+ from transformers import AutoTokenizer
+ import torch
+
+ print("\n=== %s ===" % name_or_path)
+ t0 = time.perf_counter()
+
+ # 1. Compute out_dir early so we can detect an existing export BEFORE
+ # downloading or building the model (a slow, expensive step).
+ if os.path.exists(name_or_path):
+ label_hint = os.path.basename(name_or_path.rstrip("/\\"))
+ else:
+ label_hint = name_or_path # e.g., "multilingual"
+ out_dir = os.path.join(out_root, label_hint)
+ final_onnx = os.path.join(out_dir, "model.onnx")
+ if os.path.exists(final_onnx) and not force:
+ raise RuntimeError(
+ "%s already exists. Pass --force to overwrite." % final_onnx
+ )
+
+ # 2. Resolve model directory (may trigger a HuggingFace download).
+ model_dir, subfolder, label = _resolve_spec(name_or_path, token)
+ if subfolder:
+ model_dir = os.path.join(model_dir, subfolder)
+
+ _fix_tokenizer_config(model_dir)
+
+ cfg_path = os.path.join(model_dir, "rl_agent_config.json")
+ if not os.path.exists(cfg_path):
+ raise FileNotFoundError("rl_agent_config.json not found in %s" % model_dir)
+ with open(cfg_path, encoding="utf-8") as f:
+ cfg = json.load(f)
+
+ # 3. Prepare output directory.
+ os.makedirs(out_dir, exist_ok=True)
+
+ # 4. Build model and load weights.
+ print(" building model from config...")
+ enc_dir = os.path.join(model_dir, "encoder")
+ model = build_model(cfg, encoder_dir=enc_dir if os.path.exists(enc_dir) else None)
+ weights_path = os.path.join(model_dir, "model.safetensors")
+ if not os.path.exists(weights_path):
+ raise FileNotFoundError("model.safetensors not found in %s" % model_dir)
+ weights = load_file(weights_path)
+ model.load_state_dict(weights, strict=True)
+ try:
+ model.encoder.config.reference_compile = False
+ except Exception:
+ pass
+ # Switch the encoder to eager attention for ONNX export. The SDPA path
+ # (default for ModernBERT) calls torch.nn.functional.scaled_dot_product_attention
+ # and the sliding-window attention utility in masking_utils.py, both of which
+ # bake sequence-length shapes into the traced graph. The eager path uses plain
+ # matmul and produces fully dynamic ONNX nodes. The weights are identical in
+ # both paths; we are only changing the forward dispatch.
+ try:
+ model.encoder.config._attn_implementation = "eager"
+ except Exception:
+ pass
+ model.eval()
+ print(" model loaded (%.1f M parameters)" % (sum(p.numel() for p in model.parameters()) / 1e6))
+
+ # 5. Load tokenizer.
+ tok_dir = os.path.join(model_dir, "tokenizer")
+ tok = AutoTokenizer.from_pretrained(tok_dir)
+
+ # 6. Copy config and tokenizer.
+ shutil.copy2(cfg_path, os.path.join(out_dir, "rl_agent_config.json"))
+ print(" rl_agent_config.json copied")
+ copy_tokenizer(model_dir, out_dir)
+
+ # 7. Generate PyTorch reference fixtures before export (they are independent).
+ print(" generating fixtures...")
+ with torch.no_grad():
+ generate_fixtures(model, tok, cfg, out_dir)
+
+ # 8. Export to ONNX.
+ print(" exporting to ONNX (opset=%d)..." % opset)
+ export_onnx(model, out_dir, opset=opset)
+
+ # 9. Verify if requested.
+ if do_verify:
+ print(" verifying...")
+ verify(out_dir, cfg)
+
+ elapsed = time.perf_counter() - t0
+ print(" done in %.1f s -> %s" % (elapsed, out_dir))
+ return out_dir
+
+
+# ─── graph signature check against reference ────────────────────────────────
+
+def _check_against_reference(out_dir: str, label: str):
+ """If a pre-built reference exists in onnx/, compare signatures."""
+ import onnx
+
+ ref_candidates = {
+ "english": os.path.join(REPO, "onnx", "english", "model.onnx"),
+ "multilingual": os.path.join(REPO, "onnx", "multilingual", "model.onnx"),
+ }
+ ref_path = ref_candidates.get(label)
+ if ref_path and os.path.exists(ref_path):
+ try:
+ check_graph_signature(out_dir, ref_path)
+ except Exception as e:
+ print(" signature check error: %s" % e)
+
+
+# ─── CLI ────────────────────────────────────────────────────────────────────
+
+def main():
+ ap = argparse.ArgumentParser(
+ description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+ ap.add_argument(
+ "local_path",
+ nargs="?",
+ help="Local checkpoint directory (alternative to --model).",
+ )
+ ap.add_argument(
+ "--model",
+ choices=_NAMES + ["all"],
+ default=None,
+ help="Which checkpoint to export: english, multilingual, typed-decisions, or all.",
+ )
+ ap.add_argument(
+ "--out",
+ default=os.path.join(REPO, "onnx"),
+ help="Output root directory (default: %(default)s). "
+ "Each model is written to <out>/<model-name>/.",
+ )
+ ap.add_argument(
+ "--token",
+ default=None,
+ metavar="HF_TOKEN",
+ help="HuggingFace API token (default: HF_TOKEN env var).",
+ )
+ ap.add_argument(
+ "--opset",
+ type=int,
+ default=18,
+ help="ONNX opset version (default: %(default)s).",
+ )
+ ap.add_argument(
+ "--verify",
+ action="store_true",
+ help="After export, reload in ONNX Runtime and compare to PyTorch "
+ "across a range of tensor shapes.",
+ )
+ ap.add_argument(
+ "--force",
+ action="store_true",
+ help="Overwrite an existing export. By default the script refuses to "
+ "overwrite <out>/<model>/model.onnx if it already exists.",
+ )
+ args = ap.parse_args()
+
+ if args.local_path and args.model:
+ ap.error("Specify either a local path or --model, not both.")
+ if not args.local_path and not args.model:
+ ap.error("Specify --model {english,multilingual,typed-decisions,all} or a local path.")
+
+ out_root = os.path.abspath(args.out)
+ os.makedirs(out_root, exist_ok=True)
+
+ targets = (
+ [args.local_path]
+ if args.local_path
+ else (_NAMES if args.model == "all" else [args.model])
+ )
+
+ multi_model = len(targets) > 1
+ out_dirs = []
+ failures = []
+ for target in targets:
+ try:
+ od = export_one(
+ target,
+ out_root=out_root,
+ token=args.token,
+ opset=args.opset,
+ do_verify=args.verify,
+ force=args.force,
+ )
+ out_dirs.append((target, od))
+ # Signature check against the pre-built reference (if any).
+ label = os.path.basename(od)
+ _check_against_reference(od, label)
+ except KeyboardInterrupt:
+ raise
+ except (Exception, SystemExit) as e:
+ if multi_model:
+ msg = str(e).strip()
+ print("\n[%s] skipped: %s" % (target, msg or type(e).__name__))
+ failures.append((target, msg))
+ else:
+ raise
+
+ print("\nexport complete:")
+ for target, od in out_dirs:
+ files = [f for f in os.listdir(od) if not os.path.isdir(os.path.join(od, f))]
+ print(" %-20s -> %s (%d files)" % (target, od, len(files)))
+ if failures:
+ print("\nskipped (%d):" % len(failures))
+ for target, msg in failures:
+ print(" %-20s %s" % (target, msg))
+ return 1
+
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())