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.
Python calibrationclassificationdecision-modelhuggingfacejevmodernbertmultilingualnlppythonpytorchroutingtyped-decisionszero-shot
feat(dotnet): add options, model config and artifact resolution with opt-in download
kevin-gatimu2081276c2671
diff --git a/laya-dotnet/MODELS.md b/laya-dotnet/MODELS.mdnew file mode 100644index 00000000..16e55c0d--- /dev/null+++ b/laya-dotnet/MODELS.md@@ -0,0 +1,501 @@+# Laya Models: Obtaining the ONNX Artifacts++The Laya .NET SDK ([README](https://github.com/NandhaKishorM/laya/blob/main/laya-dotnet/README.md)), a .NET 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-dotnet/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-dotnet/tools/export_onnx.py --model multilingual++# Export and verify ONNX parity against PyTorch (~9 min + ~5 min verify)+python laya-dotnet/tools/export_onnx.py --model multilingual --verify++# Export typed-decisions with parity check (~30 min total)+python laya-dotnet/tools/export_onnx.py --model typed-decisions --verify++# Export all three checkpoints+python laya-dotnet/tools/export_onnx.py --model all++# Export to a custom directory (no --force needed; leaves onnx/ untouched)+python laya-dotnet/tools/export_onnx.py --model multilingual --out C:\tmp\laya-test --verify++# Re-export, overwriting an existing artifact+python laya-dotnet/tools/export_onnx.py --model multilingual --force++# Export a local checkpoint directory (must contain rl_agent_config.json)+python laya-dotnet/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.ModelDirectory` /+`LayaEngine.FromDirectory(...)` (see [section 7](#7-using-the-artifact-in-code-and-tests)).++### Step 6: Check it works++Run the quickstart sample against the export, from the repository root:++```bash+# Multilingual (default)+dotnet run --project laya-dotnet/samples/Laya.Sample -- --model-dir onnx/multilingual++# English checkpoint+dotnet run --project laya-dotnet/samples/Laya.Sample -- --checkpoint english --model-dir onnx/english++# Typed-decisions checkpoint+dotnet run --project laya-dotnet/samples/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 .NET 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.ModelDirectory` / `LAYA_ONNX_DIR` at the artifact+directory directly.++```csharp+// explicit checkpoint selection+using var engine = LayaEngine.Create(new LayaOptions+{+ Checkpoint = LayaCheckpoint.English,+ AllowDownload = true,+});++// or point directly at the directory+using var engine = LayaEngine.FromDirectory(@"C:\models\laya\english");+```++---++## 4. Output layout++`export_onnx.py` (this SDK's exporter) writes the **fused** layout below 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+ fixtures.npz # PyTorch reference outputs (used by --verify; not needed by SDK)+```++**`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 SDK strips it at load time via+`HfTokenizer.EnsureStrippedTokenizer` and caches the result as+`tokenizer.nopost.json` alongside the original. That cache file is written by+the SDK, not by the exporter.++### Split layout (laya-ts exporter)++The `laya-ts` exporter produces a second, **split** layout instead of one fused graph — the+encoder and the RL head as two separate ONNX files, each with its own external-data sidecar:++```+<out>/<name>/+ encoder.onnx # Encoder graph: (input_ids, attention_mask) -> last_hidden_state+ encoder.onnx.data # Encoder weights (~1.2-1.6 GB)+ head.onnx # RL head graph: (hidden_states, marker_pos, marker_mask,+ # qtype [B, 1], attention_mask) -> logits, act_logits+ head.onnx.data # Head weights (~60-110 MB)+ rl_agent_config.json # Same shape/config file as the fused layout+ tokenizer.json # Sits directly in the directory, not under tokenizer/+```++Each `.data` file must stay next to its graph, for the same reason as `model.onnx.data`.++Note the split layout's `tokenizer.json` has no sibling `tokenizer_config.json` and no+`tokenizer/` subfolder. When `tokenizer_config.json` is absent, `HfTokenizer` 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 and UNK from `added_tokens`' conventional spellings+(`[PAD]`/`[MASK]`/`[UNK]` or `<pad>`/`<mask>`/`<unk>`). A spelling guess alone is not safe for+CLS/SEP: the multilingual vocabulary also contains `<s>`/`</s>`, which are not its CLS/SEP.++The .NET SDK auto-detects which layout a directory holds (see [section 5](#5-where-the-engine-looks));+callers do not choose a layout explicitly. If a directory somehow has both `model.onnx` and+`encoder.onnx`+`head.onnx`, the fused layout wins, since that is what this SDK's own exporter has+always produced.++In both layouts, `rl_agent_config.json` is where `MaxLen` (`max_len`) and `HeadMaxLen`+(`head_max_len`) come from — `LayaConfig.Load` reads the same file regardless of which ONNX+layout sits beside it, so a split export needs the same config file the fused one does.++---++## 5. Where the engine looks++The engine looks for the directory in this order:++1. `LayaOptions.ModelDirectory`+2. the `LAYA_ONNX_DIR` environment variable — maps to the **multilingual** checkpoint only (legacy)+3. `LAYA_ONNX_ROOT/<checkpoint-name>` — the recommended multi-checkpoint path; the SDK appends the+ subfolder name (`multilingual`, `english`, or `typed-decisions`)+4. the local cache, `<CacheDirectory>/<checkpoint-name>`. `CacheDirectory` defaults to+ `%LOCALAPPDATA%\laya\onnx` on Windows and `~/.cache/laya/onnx` elsewhere.+5. a download into that cache, only if `LayaOptions.AllowDownload = true`++If none of these has the artifact, resolution fails with a message that lists every location it+tried.++Once a directory is chosen, `ModelArtifacts.Resolve` decides fused vs. split by checking which+files are actually present, not by any option or environment variable:++- `model.onnx` + `model.onnx.data` → fused (`LayaArtifactLayout.Fused`)+- `encoder.onnx` + `head.onnx` → split (`LayaArtifactLayout.Split`)+- both present → fused wins+- neither present, or only one half of a layout (e.g. `encoder.onnx` with no `head.onnx`) →+ `FileNotFoundException` listing all four filenames, so a partial/interrupted export fails with+ the same message as an empty directory rather than a confusing null-session error later.++The tokenizer path is resolved the same way in both layouts: `tokenizer/tokenizer.json` (fused)+is tried before the root-level `tokenizer.json` (split); if a directory happens to have both, the+nested one wins.++---++## 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, `AllowDownload = 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:++```csharp+using var engine = LayaEngine.Create(new LayaOptions+{+ AllowDownload = true, // fetch from Hugging Face into the cache, once+ HuggingFaceToken = null, // null falls back to HF_TOKEN; "" disables auth+ DownloadProgress = new Progress<ArtifactDownloadProgress>(p =>+ Console.Error.WriteLine($"{p.FileName}: {p.BytesReceived}/{p.TotalBytes}")),+});+```++The SDK downloads five files 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.CacheDirectory`.++---++## 7. Using the artifact in code and tests++### Create the engine in code++```csharp+// From a known directory (all checkpoints work)+using var engine = LayaEngine.FromDirectory(@"C:\models\laya\multilingual");++// English checkpoint via LayaOptions.Checkpoint+using var engine = LayaEngine.Create(new LayaOptions+{+ Checkpoint = LayaCheckpoint.English,+ ModelDirectory = @"C:\models\laya\english",+ IntraOpThreads = 4, // pin in containers with a CPU limit+});++// Multilingual with thread config, no ModelDirectory (LAYA_ONNX_DIR / LAYA_ONNX_ROOT / cache)+using var engine = LayaEngine.Create(new LayaOptions+{+ IntraOpThreads = 4,+});+```++### Run the tests++The test suite is parameterized over all three checkpoints. Set `LAYA_ONNX_ROOT`+to the parent of the three checkpoint directories:++```powershell+# PowerShell — all three checkpoints+$env:LAYA_ONNX_ROOT = "C:\models\laya"+dotnet test --solution laya-dotnet/Laya.slnx+```++```bash+# Bash — all three checkpoints+LAYA_ONNX_ROOT=/c/models/laya dotnet test --solution laya-dotnet/Laya.slnx+```++The legacy `LAYA_ONNX_DIR` still works and maps to the multilingual checkpoint+only; the other two are found via walk-up or skipped gracefully.++Checkpoints whose artifacts are missing are skipped, not failed. The 646 tests that need no+ONNX artifact at all (Tier 1, plus the layout-detection and tokenizer-fallback fixtures) always+run; a much larger number of theory rows additionally run once `onnx/<checkpoint>` (fused) and/or+`onnx-split/<checkpoint>` (split) are present, since most of Tier 2 is parameterized per checkpoint,+per shape, and now per layout. That theory-row count is not a fixed constant — it grows every time+a checkpoint's golden-answer coverage or shape sweep grows, and again once split-layout artifacts+exist for a checkpoint — so treat any specific figure quoted here as a snapshot, not a target.+As of 0.1.0 the full count (all three checkpoints, both layouts, everything present) is 1368.+Re-derive it yourself with `dotnet test --solution laya-dotnet/Laya.slnx -c Release` (all+artifacts present) or with `-class-` exclusions for the model-backed classes (see+[README.md § Tests](https://github.com/NandhaKishorM/laya/blob/main/laya-dotnet/README.md#tests)) if you need the true count without loading any weights.++---++## 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, `AllowDownload = true` with the matching checkpoint+works without any code changes.++The downloader handles either layout. It first sends a `HEAD` request for `model.onnx`; if that+exists it fetches the fused files above. Otherwise, if `encoder.onnx` and `head.onnx` both exist,+it fetches the split files (`encoder.onnx`, `head.onnx`, their `.data` sidecars when present,+`rl_agent_config.json` and `tokenizer.json`; see [section 4](#4-output-layout)). So whichever+layout gets uploaded to Hugging Face, `AllowDownload = true` works without code changes.++---++## 9. Troubleshooting++**404 on download (`AllowDownload`)**+The ONNX artifacts have not been published yet (see section 8). Export locally with+`laya-dotnet/tools/export_onnx.py` and point the SDK at the result via `LAYA_ONNX_DIR` or+`LayaOptions.ModelDirectory`.++**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.++**"neither model.onnx nor encoder.onnx/head.onnx found" (or the message names only three of the+four filenames it tried)**+The directory has neither a complete fused export nor a complete split export — most often a+split export that only partly copied (`encoder.onnx` present, `head.onnx` missing, or vice+versa). `ModelArtifacts.Resolve` treats a half-split directory the same as an empty one rather+than guessing; copy the missing file, or re-run whichever exporter produced the directory.++**Split-layout tokenizer error naming a token role (e.g. "cls_token") instead of a filename**+The split layout has no `tokenizer_config.json`, so `HfTokenizer` reads CLS/SEP from the+`post_processor` template and the other roles from `added_tokens`' spelling instead (see+[section 4](#4-output-layout)). This error means the vocabulary uses a spelling the fallback does+not recognise; either add a `tokenizer_config.json` beside `tokenizer.json` (the fused layout's+approach), or update the fallback if this is a spelling worth supporting generally.++**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-dotnet/src/Laya/LayaConfig.cs b/laya-dotnet/src/Laya/LayaConfig.csnew file mode 100644index 00000000..d00fd497--- /dev/null+++ b/laya-dotnet/src/Laya/LayaConfig.cs@@ -0,0 +1,109 @@+using System.Text.Json;++namespace Laya;++/// <summary>+/// The contents of a checkpoint's <c>rl_agent_config.json</c>.+/// </summary>+/// <remarks>+/// Defaults match Python's <c>cfg.get(...)</c> fallbacks in <c>Agent.system_one</c>, not the+/// shipped multilingual values, so a config missing a key behaves the same in both runtimes.+/// </remarks>+public sealed class LayaConfig+{+ private LayaConfig(string? encoder, int maxLen, int headMaxLen,+ IReadOnlyList<double> temperatureRaw,+ IReadOnlyDictionary<string, double> temperatureByOptionsRaw)+ {+ Encoder = encoder;+ MaxLen = maxLen;+ HeadMaxLen = headMaxLen;+ TemperatureRaw = temperatureRaw;+ TemperatureByOptionsRaw = temperatureByOptionsRaw;++ Temperature = temperatureRaw.Select(Calibration.ClampTemperature).ToList();+ TemperatureByOptions = temperatureByOptionsRaw+ .ToDictionary(kv => kv.Key, kv => Calibration.ClampTemperature(kv.Value), StringComparer.Ordinal);++ var rejected = new List<string>();+ foreach (var kv in temperatureByOptionsRaw)+ if (Calibration.ClampTemperature(kv.Value) != kv.Value)+ rejected.Add($"{kv.Key}={kv.Value:G4}");+ for (var i = 0; i < temperatureRaw.Count; i++)+ if (Calibration.ClampTemperature(temperatureRaw[i]) != temperatureRaw[i])+ rejected.Add($"temperature[{i}]={temperatureRaw[i]:G4}");+ ClampedTemperatures = rejected;++ // Mirrors Python's RuntimeWarning. One warning per clamped value so a log scan finds+ // them without needing the property; use System.Diagnostics.Trace so the caller can+ // suppress them by removing trace listeners rather than needing a new dependency.+ foreach (var desc in rejected)+ System.Diagnostics.Trace.TraceWarning(+ "Laya: temperature {0} is outside [{1}, {2}] and was clamped — " ++ "confidence from that bucket is uncalibrated",+ desc, Calibration.TempMin, Calibration.TempMax);+ }++ /// <summary>The encoder the checkpoint was trained on, for information only.</summary>+ public string? Encoder { get; }++ /// <summary>Maximum total sequence length.</summary>+ public int MaxLen { get; }++ /// <summary>Token budget for the question head: instructions plus all option fragments.</summary>+ public int HeadMaxLen { get; }++ /// <summary>Per-question-type temperature, clamped to the usable range. Always 3 entries.</summary>+ public IReadOnlyList<double> Temperature { get; }++ /// <summary>Per <c>(type, option-count)</c> bucket temperature, clamped. Keys as <see cref="Calibration.TempBucket"/> builds them.</summary>+ public IReadOnlyDictionary<string, double> TemperatureByOptions { get; }++ /// <summary>What the checkpoint shipped, before clamping.</summary>+ public IReadOnlyList<double> TemperatureRaw { get; }++ /// <summary>What the checkpoint shipped, before clamping.</summary>+ public IReadOnlyDictionary<string, double> TemperatureByOptionsRaw { get; }++ /// <summary>+ /// 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.+ /// Each entry also triggers a <c>System.Diagnostics.Trace.TraceWarning</c> at load+ /// time, mirroring Python's <c>RuntimeWarning</c> for the same condition.+ /// </summary>+ public IReadOnlyList<string> ClampedTemperatures { get; }++ /// <summary>Read a config from a <c>rl_agent_config.json</c> file.</summary>+ public static LayaConfig Load(string path) => Parse(File.ReadAllText(path));++ /// <summary>Parse a config from JSON text.</summary>+ public static LayaConfig Parse(string json)+ {+ using var doc = JsonDocument.Parse(json);+ var root = doc.RootElement;++ var temperature = new List<double>();+ if (root.TryGetProperty("temperature", out var temp) && temp.ValueKind == JsonValueKind.Array)+ foreach (var t in temp.EnumerateArray())+ temperature.Add(t.ValueKind == JsonValueKind.Number ? t.GetDouble() : double.NaN);+ // 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.Count < 3) temperature.Add(1.0);++ var byOptions = new Dictionary<string, double>(StringComparer.Ordinal);+ if (root.TryGetProperty("temperature_by_options", out var tbo) && tbo.ValueKind == JsonValueKind.Object)+ foreach (var p in tbo.EnumerateObject())+ byOptions[p.Name] = p.Value.ValueKind == JsonValueKind.Number ? p.Value.GetDouble() : double.NaN;++ return new LayaConfig(+ root.TryGetProperty("encoder", out var enc) && enc.ValueKind == JsonValueKind.String+ ? enc.GetString()+ : null,+ root.TryGetProperty("max_len", out var ml) && ml.ValueKind == JsonValueKind.Number ? ml.GetInt32() : 512,+ root.TryGetProperty("head_max_len", out var hml) && hml.ValueKind == JsonValueKind.Number+ ? hml.GetInt32()+ : 192,+ temperature,+ byOptions);+ }+}diff --git a/laya-dotnet/src/Laya/LayaOptions.cs b/laya-dotnet/src/Laya/LayaOptions.csnew file mode 100644index 00000000..393bcb39--- /dev/null+++ b/laya-dotnet/src/Laya/LayaOptions.cs@@ -0,0 +1,176 @@+namespace Laya;++/// <summary>+/// Selects which Laya checkpoint to load. Each maps to a different encoder and context length;+/// see the SDK README for the tradeoffs.+/// </summary>+public enum LayaCheckpoint+{+ /// <summary>+ /// mmBERT-base (322 M), 1 024-token context, 100+ languages. The safest default for+ /// mixed-language traffic; covers English too, so there is no router to configure.+ /// </summary>+ Multilingual,++ /// <summary>+ /// ModernBERT-large (421 M), 512-token context, English-optimised. Higher accuracy on+ /// English-only workloads; accuracy collapses on non-Latin scripts (route those through+ /// the multilingual checkpoint).+ /// </summary>+ English,++ /// <summary>+ /// ModernBERT-large (421 M), 1 024-token context, fine-tuned on four typed-decisions+ /// workflows. Use only for the specific workflows it was trained on.+ /// </summary>+ TypedDecisions,+}++/// <summary>+/// ONNX execution provider. Only <see cref="Cpu"/> is wired in v1; the others are reserved so+/// callers can opt in and receive a clear error if the matching ORT package is absent.+/// </summary>+public enum LayaExecutionProvider+{+ /// <summary>CPU execution (default).</summary>+ Cpu,++ /// <summary>NVIDIA CUDA. Requires the <c>Microsoft.ML.OnnxRuntime.Gpu</c> package.</summary>+ Cuda,++ /// <summary>Windows DirectML. Requires the <c>Microsoft.ML.OnnxRuntime.DirectML</c> package.</summary>+ DirectMl,+}++/// <summary>Progress report for a single file being downloaded from HuggingFace Hub.</summary>+/// <param name="FileName">The file name being fetched, e.g. <c>model.onnx.data</c>.</param>+/// <param name="BytesReceived">Bytes written to disk so far.</param>+/// <param name="TotalBytes">+/// Total file size in bytes, or <see langword="null"/> when the server omits+/// <c>Content-Length</c>.+/// </param>+public readonly record struct ArtifactDownloadProgress(+ string FileName,+ long BytesReceived,+ long? TotalBytes);++/// <summary>+/// Controls how the Laya engine locates or downloads its ONNX artifact and how it+/// configures ONNX Runtime.+/// </summary>+public sealed class LayaOptions+{+ private string? _huggingFaceSubfolder;++ /// <summary>+ /// The directory that contains <c>model.onnx</c>. When set, skips all other+ /// resolution steps. Default <see langword="null"/> (auto-resolve).+ /// </summary>+ public string? ModelDirectory { get; set; }++ /// <summary>+ /// Which checkpoint to load. Default <see cref="LayaCheckpoint.Multilingual"/>.+ /// The subdirectory, HuggingFace subfolder, and cache path all derive from this value+ /// unless overridden by <see cref="HuggingFaceSubfolder"/> or <see cref="ModelDirectory"/>.+ /// </summary>+ public LayaCheckpoint Checkpoint { get; set; } = LayaCheckpoint.Multilingual;++ /// <summary>+ /// Which hardware back-end to use. Default <see cref="LayaExecutionProvider.Cpu"/>.+ /// </summary>+ public LayaExecutionProvider ExecutionProvider { get; set; } = LayaExecutionProvider.Cpu;++ /// <summary>+ /// Number of threads used within a single ONNX operator.+ /// <see langword="null"/> lets ONNX Runtime choose (usually one per logical CPU).+ /// </summary>+ public int? IntraOpThreads { get; set; }++ /// <summary>+ /// Number of threads used to run independent ONNX operators in parallel.+ /// <see langword="null"/> lets ONNX Runtime choose.+ /// </summary>+ public int? InterOpThreads { get; set; }++ /// <summary>+ /// Whether the engine may fetch the artifact from HuggingFace Hub when it is not+ /// found locally. Default <see langword="false"/>; downloading must always be opt-in.+ /// </summary>+ public bool AllowDownload { get; set; } = false;++ /// <summary>+ /// HuggingFace repository that hosts the artifact.+ /// Default <c>"convaiinnovations/laya"</c>.+ /// </summary>+ public string HuggingFaceRepo { get; set; } = "convaiinnovations/laya";++ /// <summary>+ /// Subfolder within the repository and local cache. Derived from <see cref="Checkpoint"/>+ /// by default. Set explicitly only when loading a custom export that does not follow the+ /// standard bundle layout — prefer setting <see cref="Checkpoint"/> instead.+ /// </summary>+ /// <remarks>+ /// Note that the HuggingFace bundle subfolder for the English checkpoint is the bundle+ /// root (empty string), not "english". When this property is left at its default,+ /// download URLs are computed correctly. If you set it explicitly for English you must+ /// use the empty string for the download path; for local artifact directories "english"+ /// is the conventional name.+ /// </remarks>+ public string HuggingFaceSubfolder+ {+ get => _huggingFaceSubfolder ?? CheckpointSubfolder(Checkpoint);+ set => _huggingFaceSubfolder = value;+ }++ /// <summary>+ /// HuggingFace access token used in the <c>Authorization: Bearer</c> header.+ /// When <see langword="null"/>, falls back to the <c>HF_TOKEN</c> environment variable.+ /// Set to an empty string to suppress all auth (public repos only).+ /// </summary>+ public string? HuggingFaceToken { get; set; }++ /// <summary>+ /// Root directory under which the downloaded artifact is stored. Default+ /// <see langword="null"/>, which resolves to+ /// <c>%LOCALAPPDATA%\laya\onnx</c> on Windows and <c>~/.cache/laya/onnx</c>+ /// elsewhere.+ /// </summary>+ public string? CacheDirectory { get; set; }++ /// <summary>+ /// Optional sink for per-file download progress. Each notification carries the+ /// file name, bytes received so far, and total size when known.+ /// </summary>+ public IProgress<ArtifactDownloadProgress>? DownloadProgress { get; set; }++ // ── internal helpers ──────────────────────────────────────────────────────++ /// <summary>+ /// The local artifact subdirectory name for <paramref name="c"/>.+ /// Used as the subdirectory inside the cache root and inside an <c>onnx/</c> tree.+ /// </summary>+ internal static string CheckpointSubfolder(LayaCheckpoint c) => c switch+ {+ LayaCheckpoint.Multilingual => "multilingual",+ LayaCheckpoint.English => "english",+ LayaCheckpoint.TypedDecisions => "typed-decisions",+ _ => throw new ArgumentOutOfRangeException(nameof(c), c, null),+ };++ /// <summary>+ /// The subfolder path to use in HuggingFace download URLs. For English the checkpoint+ /// lives at the bundle root (empty string), which differs from the local directory name+ /// "english". When <see cref="HuggingFaceSubfolder"/> was set explicitly that value is+ /// used as-is.+ /// </summary>+ internal string HuggingFaceDownloadSubfolder =>+ _huggingFaceSubfolder ?? HfDownloadSubfolder(Checkpoint);++ private static string HfDownloadSubfolder(LayaCheckpoint c) => c switch+ {+ LayaCheckpoint.Multilingual => "multilingual",+ LayaCheckpoint.English => "", // lives at the bundle root+ LayaCheckpoint.TypedDecisions => "typed-decisions",+ _ => throw new ArgumentOutOfRangeException(nameof(c), c, null),+ };+}diff --git a/laya-dotnet/src/Laya/ModelArtifacts.cs b/laya-dotnet/src/Laya/ModelArtifacts.csnew file mode 100644index 00000000..d6c0cc3d--- /dev/null+++ b/laya-dotnet/src/Laya/ModelArtifacts.cs@@ -0,0 +1,478 @@+using System.Net.Http.Headers;++namespace Laya;++/// <summary>+/// Which of the two ONNX artifact shapes an artifact directory contains.+/// </summary>+public enum LayaArtifactLayout+{+ /// <summary><c>model.onnx</c> + <c>model.onnx.data</c>, a single graph for the whole forward pass.</summary>+ Fused,++ /// <summary>+ /// <c>encoder.onnx</c> + <c>head.onnx</c> (each optionally with a <c>.data</c> sidecar), the+ /// layout produced by laya-ts's exporter (<c>laya-ts/scripts/export_onnx.py</c>).+ /// </summary>+ Split,+}++/// <summary>+/// Resolved, validated paths to every file the Laya engine needs at startup.+/// Obtain via <see cref="Resolve"/> or <see cref="ResolveAsync"/>.+/// </summary>+public sealed class ModelArtifacts+{+ /// <summary>The directory that contains the artifact.</summary>+ public string Directory { get; }++ /// <summary>Which layout was found in <see cref="Directory"/>.</summary>+ public LayaArtifactLayout Layout { get; }++ /// <summary>Absolute path to <c>model.onnx</c>, or <see langword="null"/> for <see cref="LayaArtifactLayout.Split"/>.</summary>+ public string? ModelPath { get; }++ /// <summary>Absolute path to <c>encoder.onnx</c>, or <see langword="null"/> for <see cref="LayaArtifactLayout.Fused"/>.</summary>+ public string? EncoderPath { get; }++ /// <summary>Absolute path to <c>head.onnx</c>, or <see langword="null"/> for <see cref="LayaArtifactLayout.Fused"/>.</summary>+ public string? HeadPath { get; }++ /// <summary>Absolute path to <c>rl_agent_config.json</c>.</summary>+ public string ConfigPath { get; }++ /// <summary>+ /// Absolute path to <c>tokenizer.json</c> — under <c>tokenizer/</c> for the fused layout,+ /// or (usually) directly in <see cref="Directory"/> for the split layout. See+ /// <see cref="ResolveTokenizerPath"/> for the exact lookup order.+ /// </summary>+ public string TokenizerPath { get; }++ /// <summary>+ /// The checkpoint this artifact directory corresponds to, or <see langword="null"/>+ /// when loaded from an explicit path (via <see cref="LayaOptions.ModelDirectory"/> or+ /// the <c>LAYA_ONNX_DIR</c> environment variable), in which case no encoder validation+ /// is performed.+ /// </summary>+ public LayaCheckpoint? Checkpoint { get; }++ private ModelArtifacts(string directory, LayaArtifactLayout layout, string? modelPath,+ string? encoderPath, string? headPath, string configPath,+ string tokenizerPath, LayaCheckpoint? checkpoint)+ {+ Directory = directory;+ Layout = layout;+ ModelPath = modelPath;+ EncoderPath = encoderPath;+ HeadPath = headPath;+ ConfigPath = configPath;+ TokenizerPath = tokenizerPath;+ Checkpoint = checkpoint;+ }++ /// <summary>+ /// Resolves and validates the artifact directory synchronously.+ /// Equivalent to calling <see cref="ResolveAsync"/> and blocking on the result.+ /// </summary>+ /// <exception cref="DirectoryNotFoundException">+ /// When no artifact is found and <see cref="LayaOptions.AllowDownload"/> is+ /// <see langword="false"/>.+ /// </exception>+ /// <exception cref="FileNotFoundException">+ /// When the resolved directory is missing a required file.+ /// </exception>+ public static ModelArtifacts Resolve(LayaOptions options)+ => ResolveAsync(options).GetAwaiter().GetResult();++ /// <summary>+ /// Resolves and validates the artifact directory. Downloads the artifact when+ /// <see cref="LayaOptions.AllowDownload"/> is <see langword="true"/> and it is not+ /// already present.+ /// </summary>+ /// <remarks>+ /// Resolution order:+ /// <list type="number">+ /// <item><see cref="LayaOptions.ModelDirectory"/> if set.</item>+ /// <item>The <c>LAYA_ONNX_DIR</c> environment variable if set (backward compat;+ /// always treated as pointing directly at the artifact directory).</item>+ /// <item>The <c>LAYA_ONNX_ROOT</c> environment variable combined with the+ /// checkpoint subdirectory name, e.g. <c>$LAYA_ONNX_ROOT/multilingual</c>.</item>+ /// <item>The cache directory (<c><CacheDirectory>/<subfolder></c>) if it+ /// already contains a complete artifact.</item>+ /// <item>Download into the cache if <see cref="LayaOptions.AllowDownload"/> is+ /// <see langword="true"/>; otherwise throw.</item>+ /// </list>+ /// Every step accepts either the fused or the split layout; see+ /// <see cref="LayaArtifactLayout"/>. The fused layout wins when a directory somehow has+ /// both, since it is the one this SDK has always produced.+ /// </remarks>+ /// <exception cref="DirectoryNotFoundException">+ /// When no artifact is found and <see cref="LayaOptions.AllowDownload"/> is+ /// <see langword="false"/>.+ /// </exception>+ /// <exception cref="FileNotFoundException">+ /// When the resolved directory is missing a required file.+ /// </exception>+ public static async Task<ModelArtifacts> ResolveAsync(+ LayaOptions options, CancellationToken ct = default)+ {+ ArgumentNullException.ThrowIfNull(options);++ // 1. Explicit directory. No checkpoint inference: the caller knows what they loaded.+ if (!string.IsNullOrEmpty(options.ModelDirectory))+ return ValidateDirectory(options.ModelDirectory, checkpoint: null);++ // 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.+ var envDir = Environment.GetEnvironmentVariable("LAYA_ONNX_DIR");+ if (!string.IsNullOrEmpty(envDir))+ return ValidateDirectory(envDir, checkpoint: null);++ var subfolder = LayaOptions.CheckpointSubfolder(options.Checkpoint);++ // 3. LAYA_ONNX_ROOT: new env var for a tree that holds every checkpoint in named+ // subdirectories (english/, multilingual/, typed-decisions/).+ var onnxRoot = Environment.GetEnvironmentVariable("LAYA_ONNX_ROOT");+ if (!string.IsNullOrEmpty(onnxRoot))+ {+ var rootDir = Path.Combine(onnxRoot, subfolder);+ if (IsComplete(rootDir))+ return ValidateDirectory(rootDir, options.Checkpoint);+ // Not complete under LAYA_ONNX_ROOT — fall through to cache and download rather+ // than failing immediately, so a partially-downloaded cache still works.+ }++ // 4. Cache hit.+ var cacheRoot = ResolveCacheRoot(options);+ var artifactDir = Path.Combine(cacheRoot, subfolder);+ if (IsComplete(artifactDir))+ return ValidateDirectory(artifactDir, options.Checkpoint);++ // 5. Download or report the locations that were tried.+ if (!options.AllowDownload)+ {+ throw new DirectoryNotFoundException(+ $"Laya model artifact (~1.3 GB) not found. Tried:\n" ++ $" • LayaOptions.ModelDirectory (not set)\n" ++ $" • LAYA_ONNX_DIR env var (not set)\n" ++ $" • LAYA_ONNX_ROOT env var {(string.IsNullOrEmpty(onnxRoot) ? "(not set)" : Path.Combine(onnxRoot, subfolder))}\n" ++ $" • Cache directory {artifactDir}\n\n" ++ "To fix this, do one of:\n" ++ " a) Download the artifact and set LAYA_ONNX_DIR or LayaOptions.ModelDirectory " ++ "to its directory, or set LAYA_ONNX_ROOT to the parent of all checkpoints.\n" ++ " b) Set LayaOptions.AllowDownload = true to download automatically.\n" ++ "Expected one of two layouts:\n" ++ " Fused : model.onnx + model.onnx.data (both must sit in the same directory —\n" ++ " ORT resolves the external weights file relative to the graph file).\n" ++ " Split : encoder.onnx + head.onnx (the laya-ts exporter's layout).");+ }++ await DownloadArtifactAsync(options, artifactDir, ct).ConfigureAwait(false);+ return ValidateDirectory(artifactDir, options.Checkpoint);+ }++ // ── helpers ────────────────────────────────────────────────────────────────++ private static string ResolveCacheRoot(LayaOptions options)+ {+ if (!string.IsNullOrEmpty(options.CacheDirectory))+ return options.CacheDirectory;++ // %LOCALAPPDATA% on Windows; ~/.cache elsewhere (DoNotVerify avoids creation).+ var appData = Environment.GetFolderPath(+ Environment.SpecialFolder.LocalApplicationData,+ Environment.SpecialFolderOption.DoNotVerify);++ if (string.IsNullOrEmpty(appData))+ {+ var home = Environment.GetFolderPath(+ Environment.SpecialFolder.UserProfile,+ Environment.SpecialFolderOption.DoNotVerify);+ appData = Path.Combine(home, ".cache");+ }++ return Path.Combine(appData, "laya", "onnx");+ }++ private static bool IsComplete(string dir)+ => System.IO.Directory.Exists(dir)+ && File.Exists(Path.Combine(dir, "rl_agent_config.json"))+ && ResolveTokenizerPath(dir) is not null+ && (IsFusedComplete(dir) || IsSplitComplete(dir));++ private static bool IsFusedComplete(string dir)+ => File.Exists(Path.Combine(dir, "model.onnx"))+ && File.Exists(Path.Combine(dir, "model.onnx.data"));++ private static bool IsSplitComplete(string dir)+ => File.Exists(Path.Combine(dir, "encoder.onnx"))+ && File.Exists(Path.Combine(dir, "head.onnx"));++ /// <summary>+ /// Looks for <c>tokenizer.json</c> first under <c><dir>/tokenizer/</c> (the fused+ /// layout's location), then directly in <paramref name="dir"/> (where the split layout's+ /// exporter puts it, alongside <c>rl_agent_config.json</c>). Returns <see langword="null"/>+ /// if found in neither place.+ /// </summary>+ private static string? ResolveTokenizerPath(string dir)+ {+ var nested = Path.Combine(dir, "tokenizer", "tokenizer.json");+ if (File.Exists(nested)) return nested;++ var root = Path.Combine(dir, "tokenizer.json");+ return File.Exists(root) ? root : null;+ }++ private static ModelArtifacts ValidateDirectory(string dir, LayaCheckpoint? checkpoint)+ {+ var requested = dir;+ dir = Path.GetFullPath(dir);++ // Reported before the per-file checks, and quoting 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 turns that into a+ // baffling "missing model.onnx" in a directory the user never typed.+ if (!System.IO.Directory.Exists(dir))+ {+ var note = requested == dir+ ? string.Empty+ : $"\nRequested : {requested}";+ throw new DirectoryNotFoundException(+ $"Laya artifact directory does not exist.{note}\nResolved : {dir}\n\n" ++ "If the resolved path does not look like what you typed, quote it: an unquoted " ++ "Windows path loses its backslashes in a POSIX shell. Forward slashes also work.");+ }++ // Layout detection: fused wins when both are present, since it is the layout this SDK+ // has always produced and the one most artifact directories will contain.+ var modelPath = Path.Combine(dir, "model.onnx");+ var encoderPath = Path.Combine(dir, "encoder.onnx");+ var headPath = Path.Combine(dir, "head.onnx");++ if (File.Exists(modelPath))+ {+ RequireFile(dir, "model.onnx.data",+ "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.");+ RequireFile(dir, "rl_agent_config.json");+ var tokenizerPath = ResolveTokenizerPath(dir) ?? throw MissingTokenizer(dir);++ return new ModelArtifacts(dir, LayaArtifactLayout.Fused,+ modelPath: modelPath, encoderPath: null, headPath: null,+ configPath: Path.Combine(dir, "rl_agent_config.json"),+ tokenizerPath: tokenizerPath, checkpoint: checkpoint);+ }++ if (File.Exists(encoderPath) && File.Exists(headPath))+ {+ RequireFile(dir, "rl_agent_config.json");+ var tokenizerPath = ResolveTokenizerPath(dir) ?? throw MissingTokenizer(dir);++ return new ModelArtifacts(dir, LayaArtifactLayout.Split,+ modelPath: null, encoderPath: encoderPath, headPath: headPath,+ configPath: Path.Combine(dir, "rl_agent_config.json"),+ tokenizerPath: tokenizerPath, checkpoint: checkpoint);+ }++ // Neither layout is present: half a split export (only one of encoder.onnx/head.onnx)+ // falls through to here too, since neither "if" above matched.+ throw new FileNotFoundException(+ $"No ONNX artifact found in '{dir}'. Expected one of:\n" ++ " Fused : model.onnx (+ model.onnx.data) next to rl_agent_config.json and\n" ++ " tokenizer/tokenizer.json.\n" ++ " Split : encoder.onnx + head.onnx (the laya-ts exporter's layout) next to\n" ++ " rl_agent_config.json and tokenizer.json.\n",+ modelPath);+ }++ private static FileNotFoundException MissingTokenizer(string dir)+ {+ var expected = Path.Combine(dir, "tokenizer", "tokenizer.json");+ return new FileNotFoundException(+ $"Missing artifact file: {expected}\n" ++ $"Looked for it at '{expected}' and at '{Path.Combine(dir, "tokenizer.json")}'.",+ expected);+ }++ private static void RequireFile(string dir, string relative, string? extraHint = null)+ {+ var full = Path.Combine(dir, relative);+ if (!File.Exists(full))+ {+ var msg = $"Missing artifact file: {full}";+ if (extraHint is not null) msg += "\n" + extraHint;+ throw new FileNotFoundException(msg, full);+ }+ }++ // ── download ───────────────────────────────────────────────────────────────++ // Files to fetch for the fused layout, as (remote sub-path relative to subfolder, local relative path).+ private static readonly (string Remote, string Local)[] FusedArtifactFiles =+ [+ ("model.onnx", "model.onnx"),+ ("model.onnx.data", "model.onnx.data"),+ ("rl_agent_config.json", "rl_agent_config.json"),+ ("tokenizer/tokenizer.json", Path.Combine("tokenizer", "tokenizer.json")),+ ("tokenizer/tokenizer_config.json", Path.Combine("tokenizer", "tokenizer_config.json")),+ ];++ // Files to fetch for the split layout. No tokenizer_config.json: the exporter does not+ // produce one (see HfTokenizer's added_tokens fallback).+ private static readonly (string Remote, string Local)[] SplitArtifactFiles =+ [+ ("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 on 404 instead of failing.+ private static readonly HashSet<string> OptionalSplitFiles =+ ["encoder.onnx.data", "head.onnx.data"];++ private static async Task DownloadArtifactAsync(+ LayaOptions options, string destDir, CancellationToken ct)+ {+ System.IO.Directory.CreateDirectory(destDir);++ var token = options.HuggingFaceToken+ ?? Environment.GetEnvironmentVariable("HF_TOKEN");++ // One client for every file; disposed here, not per file.+ using var client = new HttpClient();+ if (!string.IsNullOrEmpty(token))+ client.DefaultRequestHeaders.Authorization =+ new AuthenticationHeaderValue("Bearer", token);++ // The English checkpoint lives at the bundle root; all others use a named subfolder.+ // HuggingFaceDownloadSubfolder returns "" for English, so the URL has no extra segment.+ var hfSub = options.HuggingFaceDownloadSubfolder;+ var baseUrl = $"https://huggingface.co/{options.HuggingFaceRepo}/resolve/main/"+ + (string.IsNullOrEmpty(hfSub) ? "" : hfSub + "/");++ // Try the fused file list first (the layout this SDK has always produced); fall back to+ // the split list only if the repository has no model.onnx. A HEAD request on model.onnx+ // decides which list to fetch, without downloading anything from the losing layout.+ var (layout, files) = await ProbeLayoutAsync(client, baseUrl, ct).ConfigureAwait(false);+ System.Diagnostics.Trace.TraceInformation(+ "Laya: found '{0}' layout artifacts at {1}", layout, baseUrl);++ if (layout == LayaArtifactLayout.Fused)+ System.IO.Directory.CreateDirectory(Path.Combine(destDir, "tokenizer"));++ foreach (var (remote, local) in files)+ {+ var url = $"{baseUrl}{remote}";+ var dest = Path.Combine(destDir, local);+ var part = dest + ".part";++ if (layout == LayaArtifactLayout.Split && OptionalSplitFiles.Contains(remote)+ && !await ExistsAsync(client, url, ct).ConfigureAwait(false))+ continue;++ await DownloadFileAsync(client, url, remote, dest, part, options.DownloadProgress, ct)+ .ConfigureAwait(false);+ }+ }++ /// <summary>+ /// Decides, with a single HEAD request per candidate, whether the repository publishes the+ /// fused or the split layout, and returns the matching file list. Fused is tried first.+ /// </summary>+ private static async Task<(LayaArtifactLayout Layout, (string Remote, string Local)[] Files)> ProbeLayoutAsync(+ HttpClient client, string baseUrl, CancellationToken ct)+ {+ if (await ExistsAsync(client, baseUrl + "model.onnx", ct).ConfigureAwait(false))+ return (LayaArtifactLayout.Fused, FusedArtifactFiles);++ if (await ExistsAsync(client, baseUrl + "encoder.onnx", ct).ConfigureAwait(false))+ return (LayaArtifactLayout.Split, SplitArtifactFiles);++ throw new DirectoryNotFoundException(+ $"Hugging Face has neither 'model.onnx' nor 'encoder.onnx' at {baseUrl} (404).\n\n" ++ "The Laya repository publishes PyTorch weights (model.safetensors), which this SDK " ++ "cannot load: it needs either a fused ONNX export (model.onnx + model.onnx.data) or " ++ "a split export (encoder.onnx + head.onnx). Unless one of those has been uploaded to " ++ "the repository, --download/AllowDownload 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.ModelDirectory.");+ }++ private static async Task<bool> ExistsAsync(HttpClient client, string url, CancellationToken ct)+ {+ using var request = new HttpRequestMessage(HttpMethod.Head, url);+ using var response = await client.SendAsync(request, ct).ConfigureAwait(false);+ // Anything other than 404 is treated as "exists" — a 401/403 means the repo is gated but+ // the file is really there, and DownloadFileAsync gives the token-specific error for that.+ return response.StatusCode is not System.Net.HttpStatusCode.NotFound;+ }++ private static async Task DownloadFileAsync(+ HttpClient client,+ string url,+ string displayName,+ string destPath,+ string partPath,+ IProgress<ArtifactDownloadProgress>? progress,+ CancellationToken ct)+ {+ using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct)+ .ConfigureAwait(false);++ // A bare EnsureSuccessStatusCode here surfaces 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.+ if (response.StatusCode is System.Net.HttpStatusCode.NotFound)+ {+ throw new DirectoryNotFoundException(+ $"Hugging Face has no '{displayName}' at {url} (404).\n\n" ++ "The Laya repository publishes PyTorch weights (model.safetensors), which this SDK " ++ "cannot load: it needs an ONNX export (either model.onnx + model.onnx.data, or " ++ "encoder.onnx + head.onnx). Unless that export has been uploaded to the repository, " ++ "--download/AllowDownload 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.ModelDirectory.");+ }++ if (response.StatusCode is System.Net.HttpStatusCode.Unauthorized+ or System.Net.HttpStatusCode.Forbidden)+ {+ throw new DirectoryNotFoundException(+ $"Hugging Face refused access to {url} ({(int)response.StatusCode}).\n" ++ "The repository is gated or private. Set LayaOptions.HuggingFaceToken, or the " ++ "HF_TOKEN environment variable, to a token that can read it.");+ }++ response.EnsureSuccessStatusCode();++ var total = response.Content.Headers.ContentLength;++ using var src = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);+ using (var dst = new FileStream(partPath, FileMode.Create, FileAccess.Write,+ FileShare.None, 81_920, useAsync: true))+ {+ var buffer = new byte[81_920];+ long received = 0;+ int read;+ while ((read = await src.ReadAsync(buffer, ct).ConfigureAwait(false)) > 0)+ {+ await dst.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false);+ received += read;+ progress?.Report(new ArtifactDownloadProgress(displayName, received, total));+ }+ }++ // Atomic promotion: a .part file that survived means a previous run was interrupted,+ // not that the destination is valid.+ if (File.Exists(destPath)) File.Delete(destPath);+ File.Move(partPath, destPath);+ }+}diff --git a/laya-dotnet/tests/Laya.Tests/ModelArtifactsTests.cs b/laya-dotnet/tests/Laya.Tests/ModelArtifactsTests.csnew file mode 100644index 00000000..f9da2882--- /dev/null+++ b/laya-dotnet/tests/Laya.Tests/ModelArtifactsTests.cs@@ -0,0 +1,196 @@+namespace Laya.Tests;++/// <summary>+/// Tier 1: layout detection and tokenizer-path lookup, using empty placeholder files in a temp+/// directory rather than real weights. These pin the branching in+/// <see cref="ModelArtifacts"/> that decides fused vs. split (and reports both layouts when+/// neither is found) without needing anything downloaded.+/// </summary>+public sealed class ModelArtifactsTests : IDisposable+{+ private readonly string _dir;++ public ModelArtifactsTests()+ {+ _dir = Path.Combine(Path.GetTempPath(), "laya-artifact-tests-" + Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(_dir);+ }++ public void Dispose()+ {+ try { Directory.Delete(_dir, recursive: true); }+ catch (IOException) { /* best effort */ }+ }++ private void Touch(params string[] relativeSegments)+ {+ var path = Path.Combine(_dir, Path.Combine(relativeSegments));+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);+ File.WriteAllBytes(path, []);+ }++ private ModelArtifacts Resolve() =>+ ModelArtifacts.Resolve(new LayaOptions { ModelDirectory = _dir });++ [Fact]+ public void FusedOnly_IsDetectedAsFused()+ {+ Touch("model.onnx");+ Touch("model.onnx.data");+ Touch("rl_agent_config.json");+ Touch("tokenizer", "tokenizer.json");++ var artifacts = Resolve();++ Assert.Equal(LayaArtifactLayout.Fused, artifacts.Layout);+ Assert.NotNull(artifacts.ModelPath);+ Assert.Null(artifacts.EncoderPath);+ Assert.Null(artifacts.HeadPath);+ }++ [Fact]+ public void SplitOnly_IsDetectedAsSplit()+ {+ Touch("encoder.onnx");+ Touch("head.onnx");+ Touch("rl_agent_config.json");+ Touch("tokenizer.json");++ var artifacts = Resolve();++ Assert.Equal(LayaArtifactLayout.Split, artifacts.Layout);+ Assert.Null(artifacts.ModelPath);+ Assert.NotNull(artifacts.EncoderPath);+ Assert.NotNull(artifacts.HeadPath);+ }++ [Fact]+ public void BothLayoutsPresent_FusedWins()+ {+ // A directory that somehow has both (e.g. a developer exported one on top of the other)+ // must not become ambiguous: the fused layout is what this SDK has always produced, so+ // it is the one that wins.+ Touch("model.onnx");+ Touch("model.onnx.data");+ Touch("encoder.onnx");+ Touch("head.onnx");+ Touch("rl_agent_config.json");+ Touch("tokenizer", "tokenizer.json");++ var artifacts = Resolve();++ Assert.Equal(LayaArtifactLayout.Fused, artifacts.Layout);+ }++ [Fact]+ public void NeitherLayoutPresent_ThrowsListingBothLayouts()+ {+ Touch("rl_agent_config.json");++ var ex = Assert.Throws<FileNotFoundException>(Resolve);++ Assert.Contains("model.onnx", ex.Message);+ Assert.Contains("encoder.onnx", ex.Message);+ Assert.Contains("head.onnx", ex.Message);+ }++ [Fact]+ public void HalfSplit_EncoderWithoutHead_ThrowsListingBothLayouts()+ {+ // Only encoder.onnx: an interrupted or partial split export must fall through to the+ // same "neither layout matched" error as a genuinely empty directory, not silently pick+ // the split branch with a null head session.+ Touch("encoder.onnx");+ Touch("rl_agent_config.json");+ Touch("tokenizer.json");++ var ex = Assert.Throws<FileNotFoundException>(Resolve);++ Assert.Contains("model.onnx", ex.Message);+ Assert.Contains("encoder.onnx", ex.Message);+ Assert.Contains("head.onnx", ex.Message);+ }++ [Fact]+ public void HalfSplit_HeadWithoutEncoder_ThrowsListingBothLayouts()+ {+ Touch("head.onnx");+ Touch("rl_agent_config.json");+ Touch("tokenizer.json");++ var ex = Assert.Throws<FileNotFoundException>(Resolve);++ Assert.Contains("model.onnx", ex.Message);+ Assert.Contains("encoder.onnx", ex.Message);+ Assert.Contains("head.onnx", ex.Message);+ }++ [Fact]+ public void TokenizerLookup_PrefersNestedTokenizerDirectoryOverRoot()+ {+ // Both locations exist (a directory that has both a fused-style tokenizer/ subfolder and+ // a root-level tokenizer.json, however that came about): the nested one must win, since+ // that is where the fused layout's downloader and every fused artifact puts it.+ Touch("model.onnx");+ Touch("model.onnx.data");+ Touch("rl_agent_config.json");+ Touch("tokenizer", "tokenizer.json");+ Touch("tokenizer.json");++ var artifacts = Resolve();++ Assert.Equal(Path.Combine(_dir, "tokenizer", "tokenizer.json"), artifacts.TokenizerPath);+ }++ [Fact]+ public void TokenizerLookup_FallsBackToRootWhenNoNestedDirectory()+ {+ // The split layout's tokenizer.json sits directly in the artifact directory, with no+ // tokenizer/ subfolder at all.+ Touch("encoder.onnx");+ Touch("head.onnx");+ Touch("rl_agent_config.json");+ Touch("tokenizer.json");++ var artifacts = Resolve();++ Assert.Equal(Path.Combine(_dir, "tokenizer.json"), artifacts.TokenizerPath);+ }++ [Fact]+ public void MissingTokenizer_ThrowsNamingBothLocationsTried()+ {+ Touch("model.onnx");+ Touch("model.onnx.data");+ Touch("rl_agent_config.json");++ var ex = Assert.Throws<FileNotFoundException>(Resolve);++ Assert.Contains(Path.Combine(_dir, "tokenizer", "tokenizer.json"), ex.Message);+ Assert.Contains(Path.Combine(_dir, "tokenizer.json"), ex.Message);+ }++ [Fact]+ public void MissingModelDotOnnxData_ThrowsNamingTheSidecar()+ {+ // model.onnx alone (no .data sidecar) must fail with a message pointing at the sidecar+ // specifically, not the generic "neither layout" message — a half-fused export is a much+ // more common mistake (a copy that missed the large external-data file) than a half-split+ // one, and deserves its own hint.+ Touch("model.onnx");+ Touch("rl_agent_config.json");+ Touch("tokenizer", "tokenizer.json");++ var ex = Assert.Throws<FileNotFoundException>(Resolve);++ Assert.Contains("model.onnx.data", ex.Message);+ }++ [Fact]+ public void MissingDirectory_ThrowsDirectoryNotFound()+ {+ var missing = Path.Combine(_dir, "does-not-exist");+ Assert.Throws<DirectoryNotFoundException>(+ () => ModelArtifacts.Resolve(new LayaOptions { ModelDirectory = missing }));+ }+}diff --git a/laya-dotnet/tools/export_onnx.py b/laya-dotnet/tools/export_onnx.pynew file mode 100644index 00000000..0ea2d2d1--- /dev/null+++ b/laya-dotnet/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. The .NET SDK strips it at load time and caches the result as+tokenizer.nopost.json -- that file is created by the SDK, not by this script.++Usage:+ # Export the multilingual checkpoint to onnx/multilingual/+ python laya-dotnet/tools/export_onnx.py --model multilingual++ # Re-export, overwriting an existing artifact+ python laya-dotnet/tools/export_onnx.py --model multilingual --force++ # Export all three checkpoints and verify each against PyTorch+ python laya-dotnet/tools/export_onnx.py --model all --verify++ # Export to a custom directory and verify+ python laya-dotnet/tools/export_onnx.py --model multilingual --out /tmp/laya-test --verify++ # Export a local checkpoint directory (must contain rl_agent_config.json)+ python laya-dotnet/tools/export_onnx.py /path/to/checkpoint --out onnx/my-model --verify++ # Use a private HuggingFace token+ python laya-dotnet/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-dotnet/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+ # (the .NET 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())