Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
perf(examples): speed up Laya router training
svonavab77cb3e729bb
diff --git a/examples/train-a-router/QUICKSTART.md b/examples/train-a-router/QUICKSTART.mdindex d5d9bdc06..9a90764bc 100644--- a/examples/train-a-router/QUICKSTART.md+++ b/examples/train-a-router/QUICKSTART.md@@ -9,7 +9,7 @@```bash# From your repository clone, install dependencies and download the pinned data and decision-model weights.cd examples/train-a-router-uv sync --frozen --group training --group outcomes+uv sync --frozen --group outcomesuv run --frozen python router.py fetch --output data --group core --group weightsuv run --frozen python router.py replay --data data --output published-resultsuv run --frozen python router.py prepare --data data --run my-router@@ -24,13 +24,15 @@ For the **CPU embedding exercise**, install only `--group outcomes`, fetch onlyuv run --frozen python router.py reuse-native --data data --run my-router```-**2–3. Try and adapt Laya on GPU.** Start with unchanged weights, then let development data choose the LoRA training duration. On H100, comparing eight training passes took about **51 minutes**; the selected three-pass refit and checkpoint export took another **26 minutes**. Allow **77 minutes total**, plus setup and scoring time.+**2–3. Try and adapt Laya on GPU.** Start with unchanged weights, then let development data choose the LoRA training duration. The fast recipe uses less padding and FlashAttention for training, with the same full-precision validation and export. The complete fit took **28.6 minutes on H100**, versus **77.4 minutes** for the supplied reference recipe; setup and input scoring add time. `--recipe reference` retains the original recipe. [GPU setup and comparison](gpu/README.md) explains the locked environment and measured results.```bash# Score unchanged Laya, train LoRA, and save input-only predictions for both versions.-uv run --frozen --group training python router.py base --data data --run my-router --device cuda-uv run --frozen --group training python router.py fit-native --data data --run my-router-uv run --frozen --group training python router.py score --data data --run my-router --method native --device cuda+uv sync --project gpu --frozen+uv run --project gpu --frozen python gpu/smoke.py --output gpu-smoke.json+uv run --project gpu --frozen python router.py base --data data --run my-router --device cuda+uv run --project gpu --frozen python router.py fit-native --data data --run my-router --recipe fast+uv run --project gpu --frozen python router.py score --data data --run my-router --method native --device cuda```**4–5. Fit embedding routers on CPU.** The large Qwen encoder stays fixed. Neighbors average outcomes of similar questions; two small classifiers learn whether Luna and Sol will answer correctly.diff --git a/examples/train-a-router/README.md b/examples/train-a-router/README.mdindex e4161ad69..97ddbeff7 100644--- a/examples/train-a-router/README.md+++ b/examples/train-a-router/README.md@@ -27,7 +27,7 @@ We use **Big-Bench Extra Hard (BBEH)**: reasoning problems involving logic, coun| Calibration | 385 | Choose routing policies at different spending levels || Final test | 975 | Measure the frozen policies once |-Repeated questions and identified source/context families stay together. Training uses training labels; model settings use development labels. After those choices, each learned router is fitted afresh on training + development. Calibration chooses the routing tradeoffs; final-test answers are collected only after all models and policies are frozen.+Repeated questions and identified source/context families stay together. Training uses training labels; model settings use development labels. After those choices, each learned router is fitted afresh on training + development. Calibration chooses the routing tradeoffs. In the original study, final-test answers were collected only after all models and policies were frozen.The main measurements are:@@ -53,18 +53,18 @@ Some questions are answered correctly only by Luna. A good router can thereforeAll router rows use a rule fixed before final collection: select the highest calibration accuracy under an **80% calibration answer-cost cap** relative to always-Sol. It is an illustrative spending level, not a required quality threshold or a guarantee of 20% test savings. The table reports final-test answer costs; add **$0.81 per 10,000 requests** for the Cloud encoder on embedding routes. For embedding + learned cost, that changes $58.16 to **$58.97**, or **16.7% savings** versus always-Sol at $70.77. Native and application hosting are separate. Every method, both cost variants and all preselected spending levels remain in the full report.-The steps compare different ways to learn the decision; they do not promise that every added model improves every tradeoff. LoRA improves on unchanged Laya. Neighbors provide a simple embedding baseline. Learning request costs improves the embedding classifier at the illustrated spending levels. The inexpensive text controls remain competitive and belong in the comparison.+The table and default replay use the supplied reference checkpoints. Step 3 also compares a faster training recipe against them. The steps compare different ways to learn the decision; they do not promise that every added model improves every tradeoff. LoRA improves on unchanged Laya. Neighbors provide a simple embedding baseline. Learning request costs improves the embedding classifier at the illustrated spending levels. The inexpensive text controls remain competitive and belong in the comparison.### Set up-For the **complete training sequence**, use a Linux machine with an NVIDIA GPU. The supplied LoRA recipe was validated on one **H100 80 GB**; its longest batches used approximately 51 GB of reserved GPU memory. Other GPU sizes and Apple Silicon LoRA training have not been validated. A Linux or macOS laptop can replay the results, train the embedding classifiers and run Laya inference; full-population Laya scoring is much faster on a GPU.+For the **complete training sequence**, use a Linux machine with an NVIDIA GPU. The fast LoRA recipe was validated on one **H100 80 GB**; PyTorch reserved up to **75.8 GiB of GPU memory** during the measured validation stages. Other GPU sizes and Apple Silicon LoRA training have not been validated. A Linux or macOS laptop can replay the results, train the embedding classifiers and run Laya inference; full-population Laya scoring is much faster on a GPU.Install Python 3.12 and [uv](https://docs.astral.sh/uv/getting-started/installation/). From a clone of this repository:```bash-# Enter the self-contained example and install the locked training and CPU dependencies.+# Enter the self-contained example and install the locked CPU dependencies.cd examples/train-a-router-uv sync --frozen --group training --group outcomes+uv sync --frozen --group outcomes``````bash@@ -98,30 +98,42 @@ This path uses the recorded Laya and LoRA comparisons; it does not train or copy**Laya is a decision model:** a roughly 0.4-billion-parameter ModernBERT encoder with a small decision head. For each request, we ask two questions: will Luna answer correctly, and will Sol answer correctly? Those scores, together with estimated answer costs, determine whether paying for Sol looks worthwhile. The request is the only input; the router never sees the reference answer.```bash-# Score the held-out question inputs with unchanged Laya; use --device cpu if needed.-uv run --frozen --group training python router.py base --data data --run my-router --device cuda+# Install the locked CUDA environment and check a real GPU forward/backward step.+uv sync --project gpu --frozen+uv run --project gpu --frozen python gpu/smoke.py --output gpu-smoke.json```-This establishes how much a general decision model knows before seeing this workload. The supplied calibration explorer already includes this baseline, so you can inspect its tradeoffs while your own scoring runs.+The [GPU setup guide](gpu/README.md) lists the supported system and public binary packages. `--project gpu` selects the GPU environment; keep working in `examples/train-a-router`.++```bash+# Score the held-out question inputs with unchanged Laya on the GPU.+uv run --project gpu --frozen python router.py base --data data --run my-router --device cuda+```++This establishes how much a general decision model knows before seeing this workload. The supplied calibration explorer already includes this baseline, so you can inspect its tradeoffs while your own scoring runs. For CPU inference on Linux or macOS, use the main environment with `--group training` in place of `--project gpu`, and `--device cpu`.## 3. Adapt Laya with LoRA [78.3% accuracy; 19.7% answer-cost savings]**LoRA learns small updates inside an existing model.** We keep Laya’s original encoder weights fixed, learn rank-16 attention updates, and train its existing decision head. The labels are two bits per question: whether Luna’s answer was correct and whether Sol’s was correct. They come from real model answers checked against the benchmark references.-The complete `fit-native` command took **77 minutes on H100**: about **51 minutes** to compare eight training passes using development data, then **26 minutes** for the selected three-pass refit and checkpoint export. Setup and scoring add time. The saved checkpoint and reports let you inspect the result before your own training finishes.+The fast recipe reduces padding and uses FlashAttention during training. It keeps the same model, labels, effective batch size and development-selection rule. Validation and exported-model inference use the original full-precision computation.++The complete fast fit took **28.6 minutes on H100**, compared with **77.4 minutes** for the reference recipe: **2.7× faster**. This includes all eight training passes and development checks (**18.2 minutes**), then the selected three-pass refit and checkpoint exports (**10.4 minutes**). Dependency setup and held-out input scoring add time. The reference recipe remains available with `--recipe reference`.```bash# Train on training data, select duration on development, then refit from the original model on both.-uv run --frozen --group training python router.py fit-native --data data --run my-router+uv run --project gpu --frozen python router.py fit-native --data data --run my-router --recipe fast``````bash# Apply both unchanged and adapted Laya to calibration/test inputs, without reading their answer labels.-uv run --frozen --group training python router.py score --data data --run my-router --method native --device cuda+uv run --project gpu --frozen python router.py score --data data --run my-router --method native --device cuda```The recipe considers the unchanged model and eight training passes. **Three passes gave the best development loss** in the supplied run; later passes worsened it. We then restarted from the original model and trained for those three passes on training + development. This check is why the example does not simply train for as long as possible. Small differences across hardware can change the selected pass; your run records its own selection.+At the same 80% calibration spending cap, the faster run reached **77.8% accuracy at $55.94 / 10k answers**, compared with **78.3% at $56.80** for the supplied reference. Adding the learned costs in step 6 gave the faster model **78.9% accuracy at $55.84**: **21.1% answer-cost savings with a 1.9-point loss** versus always-Sol, before native hosting. [The complete training comparison](gpu/README.md#measured-speed-and-routing-quality) includes all spending levels, uncertainty and a download that needs no GPU.+## 4. Estimate success from similar questions [76.3% accuracy; 22.8% savings incl. encoder]An **embedding** represents a question as a list of numbers that captures similarities in its content. We use **Qwen3-Embedding-4B**, fixed throughout the experiment. The neighbor router finds similar training questions and averages their two correctness labels. It selected **32 neighbors** on development data.diff --git a/examples/train-a-router/fast-release.json b/examples/train-a-router/fast-release.jsonnew file mode 100644index 000000000..887f18b24--- /dev/null+++ b/examples/train-a-router/fast-release.json@@ -0,0 +1,7 @@+{+ "dataset": "superlinked/train-a-router-bbeh",+ "format": "train-a-router-release-v1",+ "manifest_sha256": "8a0ea7abe853c6f63881f697ec81c527ab67f2a182566aa2aa68e4dc81935ec3",+ "manifest_url": "https://huggingface.co/datasets/superlinked/train-a-router-bbeh/resolve/dba077bf0560602066add92b0c5afd90a6f77156/fast-training/2026-10-24/run-002/manifest.json",+ "revision": "dba077bf0560602066add92b0c5afd90a6f77156"+}diff --git a/examples/train-a-router/gpu/README.md b/examples/train-a-router/gpu/README.mdnew file mode 100644index 000000000..3fce0cc0d--- /dev/null+++ b/examples/train-a-router/gpu/README.md@@ -0,0 +1,192 @@+# CUDA environment for Laya training++This separate project installs the faster native recipe without changing the+example's CPU environment. Use Linux x86_64, Python 3.12 and an NVIDIA H100 with+80 GB memory. Other GPU memory sizes have not been validated for the full+8,192-token recipe. The wheels require glibc 2.28 or newer and a CUDA 12.8-capable+driver; NVIDIA lists Linux driver 570.26 for+[CUDA 12.8 GA](https://docs.nvidia.com/cuda/archive/12.8.0/cuda-toolkit-release-notes/index.html).++From `examples/train-a-router`, using uv 0.5.31 or newer:++```bash+# Install public binary wheels into gpu/.venv; no compiler or API key is needed.+uv sync --project gpu --frozen --python 3.12++# Check imports and a real synthetic CUDA forward/backward/optimizer step.+uv run --project gpu --frozen python gpu/smoke.py --output runs/gpu-smoke.json+```++Keep the working directory at `examples/train-a-router` when following the main+guide. [`--project gpu`](https://docs.astral.sh/uv/reference/cli/#uv-run--project)+selects this environment without changing the working directory, so+`uv run --project gpu --frozen python router.py ...` uses the same run and data+paths as the CPU commands. The smoke uses random synthetic tensors: it downloads+no model, reads no answer data and makes no API calls. It verifies installed+versions, package isolation, finite gradients and one completed optimizer step.+It does not measure routing quality or full-model memory use.++On 2026-10-24, a fresh Linux H100 environment installed this lock from the public+indexes and passed the smoke with uv 0.5.31 and Python 3.12.12. A separate check+using the pinned Laya checkpoint also completed a synthetic update on the+longest example input (6,702 combined tokens), followed by FP32 SDPA validation;+its peak allocated memory was 44.99 GiB. These are installation and memory+checks, separate from the full training comparison.++The GPU project is for native training and scoring. Keep collection, Cloud+embedding and live API commands in the main environment with their documented+dependency groups. On a preconfigured VM, clear inherited `UV_NO_SYNC`,+`UV_PROJECT_ENVIRONMENT`, `UV_NO_BUILD` and `VIRTUAL_ENV` settings before installing, so uv+creates this project's environment.++## Measured speed and routing quality++The complete fast fit took **28.6 minutes**, versus **77.4 minutes** for the+original H100 run: **2.7× faster, or 63.1% less time**. Both selected three+epochs on development data and then trained afresh on training + development.+They visited the same 46,852 decision items and retained all nine development+checkpoints, including the unchanged model.++| Matching fit stage | Reference | Fast |+|---|---:|---:|+| Development selection, through epoch 8 | 51.2 min | 18.2 min |+| Fresh refit and checkpoint exports | 26.2 min | 10.4 min |+| Complete fit | 77.4 min | 28.6 min |++These are measured single runs on H100, not repeated timing trials. The fast+worker took 35.5 minutes through result copying, including a 49-second clean+dependency installation, diagnostic checks and 4.1 minutes of held-out input+scoring. VM/image startup and final archival/teardown are outside that worker+clock. The complete fit includes 11.8 minutes of full-precision validation and+export checks; these checks were retained when training became faster.++The following comparisons use all **975 published final questions**. Each+recipe chose its policy on calibration at the same four answer-cost caps;+actual test spending can differ. Both cost-estimation variants are retained.+The accuracy and dollar differences are **fast minus reference**; brackets give+95% paired intervals that keep related question families together.++| Cost estimate | Calibration cap | Accuracy: reference → fast | Answer $ / 10k: reference → fast | Accuracy difference, points [95% interval] | Dollar difference [95% interval] |+|---|---:|---:|---:|---:|---:|+| Original | 20% | 55.9% → 56.3% | $12.64 → $13.43 | +0.41 [−0.10, +0.92] | +$0.79 [+$0.09, +$1.56] |+| Original | 40% | 63.8% → 63.7% | $28.00 → $26.39 | −0.10 [−0.96, +0.79] | −$1.60 [−$2.93, −$0.29] |+| Original | 60% | 71.0% → 71.5% | $42.44 → $42.60 | +0.51 [−0.73, +1.85] | +$0.16 [−$1.74, +$2.14] |+| Original | 80% | 78.3% → 77.8% | $56.80 → $55.94 | −0.41 [−1.43, +0.61] | −$0.86 [−$1.79, +$0.05] |+| Learned | 20% | 57.1% → 57.0% | $13.92 → $13.39 | −0.10 [−0.89, +0.71] | −$0.53 [−$1.01, −$0.04] |+| Learned | 40% | 66.8% → 66.5% | $27.53 → $26.62 | −0.31 [−1.64, +1.03] | −$0.90 [−$2.09, +$0.31] |+| Learned | 60% | 74.1% → 74.6% | $41.67 → $41.08 | +0.51 [−0.94, +1.95] | −$0.59 [−$2.48, +$1.20] |+| Learned | 80% | 79.0% → 78.9% | $57.63 → $55.84 | −0.10 [−1.07, +0.97] | −$1.79 [−$3.01, −$0.58] |++For context, always-Sol achieved **80.8% at $70.77 / 10k**. The last fast policy+therefore saves **21.1% of answer cost with a 1.9-point accuracy loss**. Native+hosting and one-time training are separate. The full report includes every+calibration-frontier policy and the unchanged embedding and text controls.+These results support the faster training option; the intervals do not prove+that the recipes are equivalent. They describe question uncertainty for these+two trained models, not variation across training seeds. This comparison uses+already public answers and is a reproduction, not a new blind test.++The unchanged base export and its calibration/test probabilities match the+reference exactly. The adapted checkpoint's maximum margin difference after+merging and reloading was below 0.000272, within the original checks. Mixed-precision+loss scaling skipped 8 of 2,936 attempted updates; all 2,928 actual updates and+skip positions are recorded, with the original scheduler behavior preserved.++Training/validation intervals recorded up to **33.4 GiB allocated and 75.8 GiB+reserved**. The separate longest-input check recorded **45.0 GiB allocated**.+These counters reset between stages and do not capture every initialization+allocation. They establish a working H100 recipe, not a smaller GPU minimum.++### Download the comparison without training++`fast-release.json` pins the supplement independently of the original dataset.+Its core download contains the report, exact source snapshot, training receipts+and all eight comparisons. The optional weights group adds the adapted model.++```bash+# Download and verify the fast-training comparison on CPU; no API keys or model calls.+uv run --frozen python router.py fetch \+ --release fast-release.json --output fast-results --group core+```++Open `fast-results/comparison/explorer/index.html`. Select `fast_lora` or+`fast_lora · predicted cost` alongside the reference LoRA variants. The bundled+`fast-results/README.md` also gives commands to recompute the numerical+comparison from the frozen policies and original public answers.++## Locked binaries++| Dependency | Version | Public source |+|---|---|---|+| PyTorch | `2.9.1+cu128` | [PyTorch CUDA 12.8 index](https://download.pytorch.org/whl/cu128/) |+| FlashAttention 2 | `2.8.3.post1+cu.12.8.torch.2.9` | [Astral CUDA 12.8 index](https://wheels.astral.sh/simple/cu128/) |+| Transformers | `4.57.6` | PyPI |+| Laya | `0.3.29` | PyPI |+| PEFT | `0.18.1` | PyPI |+| einops | `0.8.2` | PyPI |++Astral documents its binary extension index in the+[uv PyTorch guide](https://docs.astral.sh/uv/guides/integration/pytorch/#installing-gpu-enabled-pytorch-extensions).+The lock contains all transitive versions and wheel hashes. The selected+[CPython 3.12 FlashAttention wheel](https://wheels.astral.sh/artifacts/f688c8526ab0633dde21c1b3153959a728f7d6b275353c48d3f346862691b06a/flash_attn-2.8.3.post1+cu.12.8.torch.2.9-cp312-cp312-manylinux_2_24_x86_64.whl)+has SHA-256 `f688c8526ab0633dde21c1b3153959a728f7d6b275353c48d3f346862691b06a`.+The locked Torch wheel has SHA-256+`7cb4018f4ce68b61fd3ef87dc1c4ca520731c7b5b200e360ad47b612d7844063`.+The project forbids source builds for Torch and FlashAttention with uv's+`no-build-package` setting. Avoid a blanket `--no-build` on uv 0.5.31: it also+rejects this project's intentionally unbuilt virtual package.++## Evaluated dependency scope++As of 2026-10-24, upstream [FlashAttention 2.8.3.post2](https://github.com/Dao-AILab/flash-attention/releases/tag/v2.8.3.post2)+contains newer fixes but has no matching published Torch 2.9 wheel in the checked+upstream release or Astral index. This recipe uses the pinned public binary above+within the following scope:++- The [checkpoint-loading advisory](https://github.com/advisories/GHSA-7g5w-pq96-8c5w)+ affects FlashAttention's model and distributed checkpoint helpers.+ [Transformers' ModernBERT integration](https://github.com/huggingface/transformers/blob/v4.57.6/src/transformers/models/modernbert/modeling_modernbert.py)+ imports its attention and rotary kernels instead. The smoke checks that those+ checkpoint helpers were not imported; Laya loads the pinned safetensors+ checkpoint through its existing loader.+- The [archive-extraction advisory](https://github.com/advisories/GHSA-w9r7-4gwr-j959)+ concerns `hopper/setup.py`. Installing the locked FA2 wheel, with its source+ build disabled, does not execute that helper.+- The [FA2 backward index fix](https://github.com/Dao-AILab/flash-attention/pull/2260)+ concerns large allocation offsets. The+ [pinned Laya encoder](https://huggingface.co/convaiinnovations/laya/blob/aa8c91ca088ec597df95a0d1c76b3063cb2ae5e8/encoder/config.json)+ has 16 heads of width 64. At microbatch 4 and sequence limit 8,192, the+ `batch × rounded_sequence × heads × head_width` bound is 33,554,432, below+ the signed 32-bit limit. This assessment does not cover arbitrary larger+ models or batches.++The fast recipe uses FA2 for mixed-precision training. Development selection,+export and scoring explicitly use the original FP32 SDPA path; disabling+autocast alone would not make FA2 evaluation equivalent to FP32 SDPA.++## Compare your trained model with the supplied results++After the walkthrough's `fit-native --recipe fast` and native `score` commands,+run this comparison on CPU. It reuses the supplied cost predictors and keeps the+original routers alongside your new LoRA model. Both cost-estimation variants+retain their complete curves.++```bash+# Choose comparison policies on calibration data and freeze them before checking test answers.+uv run --frozen python training_comparison.py calibrate \+ --data data --native-run my-router/native --output training-comparison+```++```bash+# Evaluate those frozen choices against the same published test answers.+uv run --frozen python training_comparison.py evaluate \+ --data data --output training-comparison+```++Open `training-comparison/explorer/index.html` for the overlaid curves.+`comparison-report.json` also pairs the two training recipes at calibration+answer-cost caps of 20%, 40%, 60% and 80% of always-Sol. Each pair reports the+accuracy and dollar differences with uncertainty intervals. The actual test+spending can differ between recipes at the same calibration cap. These are+reproductions on already public answers, not new blind tests; there is no+required quality-loss threshold.diff --git a/examples/train-a-router/gpu/pyproject.toml b/examples/train-a-router/gpu/pyproject.tomlnew file mode 100644index 000000000..e8ad45b0f--- /dev/null+++ b/examples/train-a-router/gpu/pyproject.toml@@ -0,0 +1,35 @@+[project]+name = "train-a-router-gpu"+version = "0.1.0"+description = "Pinned Linux CUDA environment for the faster Laya LoRA recipe"+requires-python = ">=3.12,<3.13"+dependencies = [+ "numpy==2.4.6",+ "scipy==1.17.0",+ "scikit-learn==1.6.1",+ "torch==2.9.1+cu128",+ "transformers==4.57.6",+ "laya==0.3.29",+ "peft==0.18.1",+ "einops==0.8.2",+ "flash-attn==2.8.3.post1+cu.12.8.torch.2.9",+]++[tool.uv]+package = false+no-build-package = ["torch", "flash-attn"]+environments = ["sys_platform == 'linux' and platform_machine == 'x86_64'"]++[[tool.uv.index]]+name = "pytorch-cu128"+url = "https://download.pytorch.org/whl/cu128"+explicit = true++[[tool.uv.index]]+name = "astral-cu128"+url = "https://wheels.astral.sh/simple/cu128/"+explicit = true++[tool.uv.sources]+torch = { index = "pytorch-cu128" }+flash-attn = { index = "astral-cu128" }diff --git a/examples/train-a-router/gpu/smoke.py b/examples/train-a-router/gpu/smoke.pynew file mode 100644index 000000000..a224b543f--- /dev/null+++ b/examples/train-a-router/gpu/smoke.py@@ -0,0 +1,136 @@+"""Check the locked CUDA environment with a synthetic ModernBERT LoRA step."""++from __future__ import annotations++import argparse+import hashlib+import importlib.metadata+import json+import platform+import sys+import time+import tomllib+from pathlib import Path+++def sha(path):+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()+++def environment():+ root = Path(__file__).resolve().parent+ if sys.platform != "linux" or platform.machine() != "x86_64" or sys.version_info[:2] != (3, 12):+ raise RuntimeError("Use Linux x86_64 and Python 3.12 with the gpu/ project")+ if sys.prefix == sys.base_prefix:+ raise RuntimeError("Run this check with uv run --project gpu --frozen")+ dependencies = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))["project"]["dependencies"]+ expected = dict(item.split("==", 1) for item in dependencies)+ versions = {name: importlib.metadata.version(name) for name in expected}+ if versions != expected:+ raise RuntimeError(f"Installed versions differ from gpu/pyproject.toml: {versions}")+ locations = {name: str(Path(importlib.metadata.distribution(name).locate_file("")).resolve()) for name in expected}+ if any(not Path(path).is_relative_to(Path(sys.prefix).resolve()) for path in locations.values()):+ raise RuntimeError("Training dependencies must be installed in this project's virtual environment")+ return {+ "python": platform.python_version(),+ "platform": platform.platform(),+ "virtual_environment": sys.prefix,+ "versions": versions,+ "package_locations": locations,+ "files_sha256": {name: sha(root / name) for name in ("pyproject.toml", "uv.lock", "smoke.py")},+ }+++def check():+ receipt = environment()+ # These optional imports deliberately exercise the complete training import chain.+ import flash_attn+ import laya.train+ import torch+ from peft import LoraConfig, get_peft_model+ from transformers import ModernBertConfig, ModernBertModel++ if not torch.cuda.is_available() or torch.version.cuda != "12.8":+ raise RuntimeError("A working NVIDIA driver and the locked CUDA 12.8 Torch build are required")+ if not torch.compiled_with_cxx11_abi():+ raise RuntimeError("The pinned FlashAttention wheel requires Torch's C++11 ABI")+ if torch.cuda.get_device_capability()[0] < 8:+ raise RuntimeError("FlashAttention 2 requires an Ampere or newer NVIDIA GPU")++ torch.manual_seed(89)+ config = ModernBertConfig(+ vocab_size=128, hidden_size=128, intermediate_size=256,+ num_hidden_layers=2, num_attention_heads=2, max_position_embeddings=8192,+ local_attention=128, pad_token_id=0, bos_token_id=1, eos_token_id=2,+ reference_compile=False, attention_dropout=0.0,+ )+ config._attn_implementation = "flash_attention_2"+ model = get_peft_model(+ ModernBertModel(config).to("cuda"),+ LoraConfig(r=4, lora_alpha=8, target_modules=["Wqkv"], lora_dropout=0.0, bias="none"),+ ).train()+ head = torch.nn.Linear(128, 2, device="cuda")+ parameters = [p for p in model.parameters() if p.requires_grad] + list(head.parameters())+ optimizer = torch.optim.AdamW(parameters, lr=1e-3)+ scaler = torch.amp.GradScaler("cuda", init_scale=128)+ before = head.weight.detach().clone()+ ids = torch.randint(3, 128, (2, 256), device="cuda")+ mask = torch.ones_like(ids)+ mask[1, 192:] = 0+ ids[mask == 0] = 0+ target = torch.tensor([0, 1], device="cuda")+ torch.cuda.synchronize()+ torch.cuda.reset_peak_memory_stats()+ started = time.perf_counter()+ with torch.autocast("cuda", dtype=torch.float16):+ states = model(input_ids=ids, attention_mask=mask).last_hidden_state+ pooled = (states * mask[..., None]).sum(1) / mask.sum(1, keepdim=True)+ logits = head(pooled)+ loss = torch.nn.functional.cross_entropy(logits.float(), target)+ scaler.scale(loss).backward()+ scaler.unscale_(optimizer)+ if not torch.isfinite(loss) or not torch.isfinite(logits).all():+ raise RuntimeError("The synthetic forward pass produced a nonfinite value")+ if any(p.grad is not None and not torch.isfinite(p.grad).all() for p in parameters):+ raise RuntimeError("The synthetic backward pass produced a nonfinite gradient")+ scaler.step(optimizer)+ scaler.update()+ torch.cuda.synchronize()+ elapsed = time.perf_counter() - started+ steps = {int(state["step"]) for state in optimizer.state.values()}+ if steps != {1} or torch.equal(before, head.weight) or any(not torch.isfinite(p).all() for p in parameters):+ raise RuntimeError("The synthetic optimizer did not complete one finite parameter update")+ unused = [name for name in sys.modules if name == "flash_attn.utils.distributed" or name.startswith("flash_attn.models")]+ if unused:+ raise RuntimeError(f"Unexpected FlashAttention checkpoint helper import: {unused}")+ receipt.update({+ "format": "router-gpu-install-smoke-v1", "status": "passed",+ "gpu": torch.cuda.get_device_name(),+ "gpu_memory_bytes": torch.cuda.get_device_properties(0).total_memory,+ "compute_capability": list(torch.cuda.get_device_capability()),+ "cuda_runtime": torch.version.cuda, "cxx11_abi": torch.compiled_with_cxx11_abi(),+ "imported_sources_sha256": {"flash_attn": sha(flash_attn.__file__), "laya.train": sha(laya.train.__file__)},+ "attention": config._attn_implementation, "parameter_dtype": str(head.weight.dtype),+ "autocast": "float16", "actual_optimizer_steps": 1, "loss": float(loss.detach()),+ "sequence_lengths": [256, 192], "step_seconds": elapsed,+ "peak_allocated_bytes": torch.cuda.max_memory_allocated(),+ "scope": "Synthetic import/forward/backward/update check; no checkpoint, API, benchmark data or quality evaluation",+ "unused_checkpoint_helpers_imported": unused,+ })+ return receipt+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--output", type=Path, required=True)+ args = parser.parse_args()+ if args.output.exists():+ parser.error("Output already exists; choose a new receipt path")+ result = check()+ args.output.parent.mkdir(parents=True, exist_ok=True)+ args.output.write_text(json.dumps(result, indent=2, allow_nan=False) + "\n", encoding="utf-8")+ print(json.dumps({"status": result["status"], "output": str(args.output), "actual_optimizer_steps": 1}))+++if __name__ == "__main__":+ main()diff --git a/examples/train-a-router/gpu/uv.lock b/examples/train-a-router/gpu/uv.locknew file mode 100644index 000000000..048f1fd94--- /dev/null+++ b/examples/train-a-router/gpu/uv.lock@@ -0,0 +1,658 @@+version = 1+requires-python = "==3.12.*"+resolution-markers = [+ "platform_machine == 'x86_64' and sys_platform == 'linux'",+]+supported-markers = [+ "platform_machine == 'x86_64' and sys_platform == 'linux'",+]++[[package]]+name = "accelerate"+version = "1.15.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "huggingface-hub", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "numpy", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "packaging", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "psutil", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "pyyaml", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "safetensors", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "torch", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/f5/b5/1d3ed029ac71d3f2961346829a268da923698e9fd63f218f78841f216bfd/accelerate-1.15.0.tar.gz", hash = "sha256:5654f8c5eaa0d4fa68b33e287a97765da6849bf6d51dcac874e73fbbddfb6134", size = 422615 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/8a/4c/34f0450479d01195027260da68d8a3880683f1640c3ca5adf64acb3185f1/accelerate-1.15.0-py3-none-any.whl", hash = "sha256:97eacca0b73e45cb867dbf8c5d5d4dc32219544300e0c8992c7334dc2ef33cec", size = 394295 },+]++[[package]]+name = "certifi"+version = "2026.10.19"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464 },+]++[[package]]+name = "charset-normalizer"+version = "3.5.2"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/33/1c/f41d4e74c28ab327ff3acd36053f7ea506c55872d7a90b0fa71aa3ab0c89/charset_normalizer-3.5.2.tar.gz", hash = "sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef", size = 172659 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/a8/9e/09efac30b937722f46d3110ba30b875b24b2e3a266ed746cc4e376a94d80/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:38a873987f3be698494da8b2e3085e29da02da7b633dce73e79c699a113d7bf0", size = 237707 },+ { url = "https://files.pythonhosted.org/packages/9e/18/70d76670b13686237863a379928d60bd10e021f17d243ab3d7014c4a5f4e/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:355ad8011081dec5412240c087a9a0c9d4d5039f3ed11a3f13e18c2b29b56c51", size = 273050 },+ { url = "https://files.pythonhosted.org/packages/54/e2/77a8b09d5adc013ed07b95b01b8b8fa5441c4e810e83ee7e4aae2fa4d91a/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ee21e28f0430bd6dc9086c6e525d5e818a44a5ad19720c8a0ef766792f3eb5e5", size = 270345 },+ { url = "https://files.pythonhosted.org/packages/7f/c5/38806a25ab5e65fc178f39affeda20858efafede2fce1ffc2556cfc9fe73/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3d31298449090ab8d47b7b1b2a555ff73cac7ed438a08b7ac160980c7ebed649", size = 257601 },+ { url = "https://files.pythonhosted.org/packages/ae/8d/213565184708fdb263ae55e2c04ee1ff748129dd65d48ed0e3502da9c85a/charset_normalizer-3.5.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5cde776b7cc66e4f6c99612cea4aa7269aa65863f7a15841b2c264f103822f4e", size = 252222 },+ { url = "https://files.pythonhosted.org/packages/7d/dc/65a801b66ab4c197e22c433ab25e7ac24324ac6f45a2269aca42cce309bf/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:f7d486c83842422badd511868fd8a9a20e9407ace71564b6af47ce7e60a336c1", size = 241206 },+ { url = "https://files.pythonhosted.org/packages/a7/95/ca9b5eabde673002c6f1e7ada1b223916fe18f6d661da7aabd4d643718f1/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:11a4d68a6ecda3292cb1e50239e111543ba5d709bb62a6b4ea1afcfa729d8875", size = 273190 },+ { url = "https://files.pythonhosted.org/packages/2d/8b/803b4d2a3f6e1740f63f1e87b04d14b42f3d4fdfe6ed7d4db2d34102b14f/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:d6734d2ef8a50fbf8445c139477da401f50d62a0606bf00e20ec6d87773fefb1", size = 253527 },+ { url = "https://files.pythonhosted.org/packages/a9/55/93c0e5dbd085ae0471346026abbe7e0db9ea2d6fea74e51f0b5a46f233a7/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:a815775b6c38d4e0ff7bcffbeba67feded90202bb6a226b8dd35f1c855217413", size = 271285 },+ { url = "https://files.pythonhosted.org/packages/95/69/0dbd0e0b9b16cfa816cdfcb3e2e3854a1f680dc07fb1245ea125e7448060/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:23851fb4e1b85ed3f6c2a27b777cdfe2e19fb5b38429a8faf38c7542b7665869", size = 260010 },+ { url = "https://files.pythonhosted.org/packages/7e/84/371eac6b30bdbcbf2d632a1a01809103459216fcaae61b8b8d922c1bfb8a/charset_normalizer-3.5.2-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7", size = 253276 },+ { url = "https://files.pythonhosted.org/packages/61/71/458c3f42164a07d0c5210798e9e704b39e540a6793b05aba67f3a35243a9/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93", size = 231121 },+ { url = "https://files.pythonhosted.org/packages/09/54/ab9e89367076f6331bb6c65c4bf14a5361fa5191cb6561bf534f18504e1b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade", size = 260350 },+ { url = "https://files.pythonhosted.org/packages/7c/c1/061431ecc688d9d76602502cb57cc01e691e682c18f1beb45f9673b5bbd2/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0", size = 255430 },+ { url = "https://files.pythonhosted.org/packages/8d/1f/20c8949f0676f7ab811abdeb7f4d7f1cbc6e61ff20bef08b44edeb092bc8/charset_normalizer-3.5.2-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26", size = 250612 },+ { url = "https://files.pythonhosted.org/packages/bd/39/559be29a0c0f086e0bba6922babd38916cc5e0b58ced4de13ee01ea05508/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621", size = 232738 },+ { url = "https://files.pythonhosted.org/packages/ff/6c/387b0e4f756a282831c1d9fc6aeb6c51ca4507ca202767c8de15ce9b12e2/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4", size = 260703 },+ { url = "https://files.pythonhosted.org/packages/96/92/1fdf015f09ef449f50d3ac4b67c90887c9c318b727daa95cc4f866e6521d/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e", size = 247622 },+ { url = "https://files.pythonhosted.org/packages/dc/3c/8e7b8a5671ad5d433669fb2a76f1a0164df2d9b1718b0206bc2a16d840cc/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c", size = 257500 },+ { url = "https://files.pythonhosted.org/packages/b4/f0/45b579df5cabc1d5d53ea1cc35e8437d3ca768c0acccc7041517cb6fbb32/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0", size = 255100 },+ { url = "https://files.pythonhosted.org/packages/fc/ad/d07d7862a62ffa6d79d68074d14823243dd235a77c45262acbf6adeb28bf/charset_normalizer-3.5.2-py3-none-any.whl", hash = "sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685", size = 68872 },+]++[[package]]+name = "cloudpickle"+version = "3.1.2"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/27/fb/576f067976d320f5f0114a8d9fa1215425441bb35627b1993e5afd8111e5/cloudpickle-3.1.2.tar.gz", hash = "sha256:7fda9eb655c9c230dab534f1983763de5835249750e85fbcef43aaa30a9a2414", size = 22330 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/88/39/799be3f2f0f38cc727ee3b4f1445fe6d5e4133064ec2e4115069418a5bb6/cloudpickle-3.1.2-py3-none-any.whl", hash = "sha256:9acb47f6afd73f60dc1df93bb801b472f05ff42fa6c84167d25cb206be1fbf4a", size = 22228 },+]++[[package]]+name = "einops"+version = "0.8.2"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/2c/77/850bef8d72ffb9219f0b1aac23fbc1bf7d038ee6ea666f331fa273031aa2/einops-0.8.2.tar.gz", hash = "sha256:609da665570e5e265e27283aab09e7f279ade90c4f01bcfca111f3d3e13f2827", size = 56261 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/2a/09/f8d8f8f31e4483c10a906437b4ce31bdf3d6d417b73fe33f1a8b59e34228/einops-0.8.2-py3-none-any.whl", hash = "sha256:54058201ac7087911181bfec4af6091bb59380360f069276601256a76af08193", size = 65638 },+]++[[package]]+name = "filelock"+version = "4.2.4"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/d8/28/3893324bcadf8f89b1616637468d766af3f625008c0735bf704fdfa86617/filelock-4.2.4.tar.gz", hash = "sha256:c6d8663535e1650ee430507b4ffbac7b464dd64b7647ea0112a9f406499d163d", size = 652444 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/e0/1b/5e74289a1878e666bb4b65fe5805a04cafcac2aa5f519ef1ead67ef91c56/filelock-4.2.4-py3-none-any.whl", hash = "sha256:301241438c57936ef93f4243a94f2559022268bfcf9b375a9a72eb0f8db8358e", size = 162475 },+]++[[package]]+name = "flash-attn"+version = "2.8.3.post1+cu.12.8.torch.2.9"+source = { registry = "https://wheels.astral.sh/simple/cu128/" }+dependencies = [+ { name = "einops", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "torch", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]+wheels = [+ { url = "https://wheels.astral.sh/artifacts/f688c8526ab0633dde21c1b3153959a728f7d6b275353c48d3f346862691b06a/flash_attn-2.8.3.post1+cu.12.8.torch.2.9-cp312-cp312-manylinux_2_24_x86_64.whl", hash = "sha256:f688c8526ab0633dde21c1b3153959a728f7d6b275353c48d3f346862691b06a", size = 253650586 },+]++[[package]]+name = "fsspec"+version = "2026.9.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/77/cd/9be253869fc42e764de7f3dedd6969af7d44ff9c3375214a3442a6f3fc08/fsspec-2026.9.0.tar.gz", hash = "sha256:0f08147951c8cb31d844c3547d631053b127863b60be04cf06e121333ee0e2fe", size = 333545 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/6c/c0/a98505f18594f1bce828bb159cec0fcf9860562f1a2c85913409fc8f3d9e/fsspec-2026.9.0-py3-none-any.whl", hash = "sha256:8dd6e646e99ea382bd85f97a45e6b526a442d79423a7dc673f1e2756d05fcb5f", size = 221738 },+]++[[package]]+name = "hf-xet"+version = "1.7.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/9e/27/06d899ea7bd721d272f84aac98bdb238de98af4cc767a69056d967d68c71/hf_xet-1.7.0.tar.gz", hash = "sha256:d406ec79053c0871817f700c2ac8c36ba0d87f9c34b7458b0f0063bb218b0466", size = 985689 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/a3/4c/2bf3b66c215d409655f28de1622393dde04c9461280d48c7924bb3b2decd/hf_xet-1.7.0-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2814a6e999d13464c4d679b788cc5d784eb5a4edfc638a31f10e9a11ab531ef8", size = 4212180 },+ { url = "https://files.pythonhosted.org/packages/6c/dc/03a21b89f118664a0926ff25b0f8e44a519bf22724a6a8fc7a9abbc188b6/hf_xet-1.7.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:0a9e802f33bf50c851abe45fc5380e61f959e2d369647d6742b79ad9d6c27cab", size = 4418814 },+]++[[package]]+name = "huggingface-hub"+version = "0.36.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "filelock", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "fsspec", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "hf-xet", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "packaging", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "pyyaml", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "requests", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "tqdm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "typing-extensions", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/98/63/4910c5fa9128fdadf6a9c5ac138e8b1b6cee4ca44bf7915bbfbce4e355ee/huggingface_hub-0.36.0.tar.gz", hash = "sha256:47b3f0e2539c39bf5cde015d63b72ec49baff67b6931c3d97f3f84532e2b8d25", size = 463358 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/cb/bd/1a875e0d592d447cbc02805fd3fe0f497714d6a2583f59d14fa9ebad96eb/huggingface_hub-0.36.0-py3-none-any.whl", hash = "sha256:7bcc9ad17d5b3f07b57c78e79d527102d08313caa278a641993acddcb894548d", size = 566094 },+]++[[package]]+name = "idna"+version = "3.20"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583 },+]++[[package]]+name = "jinja2"+version = "3.1.6"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "markupsafe", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899 },+]++[[package]]+name = "joblib"+version = "1.6.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "cloudpickle", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/d5/1d/537ab090f302b838943a1b56497dd53059b9a9b46a074936470173a2e207/joblib-1.6.0.tar.gz", hash = "sha256:2ccc96785b12046c08fd6d55839c12857831b54a3c1673ffadd2f04bfc4eda03", size = 327903 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/18/53/84099323c2ec4be98d935f63c033ac4151ee83836ca1050ede3b3aadf155/joblib-1.6.0-py3-none-any.whl", hash = "sha256:3dbbf9f6e4b592a2357b854608e980fe6390d131d7a82f011a377ef2ebef7aba", size = 306115 },+]++[[package]]+name = "laya"+version = "0.3.29"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "huggingface-hub", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "numpy", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "safetensors", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "torch", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "transformers", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/17/2e/9dcc0e424ea8f9e6c0cbcc91d6dbf4a0e30aba33021517eebf2a5dda286d/laya-0.3.29.tar.gz", hash = "sha256:7a3c64163be195c8ba6ca65c9cf6abb439de3d70d890900f80f3d0e923e6d0b4", size = 1082279 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/42/56/c82db3e34fe507ab6cda40ee5b8357ad5e30c1196e887ea7351896c96cde/laya-0.3.29-py3-none-any.whl", hash = "sha256:41a51775eae4bd624688f13425d71ce66aa0f6b9a49a922a775a92dc4a85c885", size = 377251 },+]++[[package]]+name = "markupsafe"+version = "3.0.4"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/38/9b/e422a865e1d5d57d0e509b4e0bf1c1a70a7f6382c29a5aa428df994c8bc8/markupsafe-3.0.4.tar.gz", hash = "sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6", size = 153777 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/60/ce/fa07dbe8a5675558fa36dea033e19995bc783de2dec5f540ccb9030b06aa/markupsafe-3.0.4-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:1e1451fab512d1bcc3dc26988ec1edb0b82c2db909132872cd9356070a6b63df", size = 28525 },+ { url = "https://files.pythonhosted.org/packages/85/40/be87c01f3868ec217f8a2015089d71c22c8c5a75324822e5ed1cdd87210d/markupsafe-3.0.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:bd3ce56ae2cbae3ba82b683bc425cd7e48d2ed8b10f3e818186b6f5646d9271c", size = 24733 },+ { url = "https://files.pythonhosted.org/packages/4f/a7/aeedb5140afa41fc74c225e9184ab96723a6e873b6ee1c9fede7283456d8/markupsafe-3.0.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8e124f974786f831d6043728e38296969d3579db8896fe004682f5758e613581", size = 22985 },+ { url = "https://files.pythonhosted.org/packages/c3/fc/e91352bb08c6a59da3ef0909d457bf95a5f5908fbf151b30a06d9dbcfbb4/markupsafe-3.0.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c02e8f18bdedba082cef725942ac823b9b60656db07f7e265cb31618dfd00d77", size = 22001 },+ { url = "https://files.pythonhosted.org/packages/ed/59/b853d6628ecb4d658e1d637224846d5e9bb4adf4f8df97f3be9f29dce2ec/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:d5f93ebbeb8032d47e349328ec8662d973d9b05a70b3c35df1f91fe419b84749", size = 22640 },+ { url = "https://files.pythonhosted.org/packages/09/b2/1506df394f0f075797c418d0301498f49e43be194e3ffcb49e6fe6ccf022/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:64511c54db4e4987aef4c41923235927428729e8174c5dba488429be70a998ed", size = 24074 },+ { url = "https://files.pythonhosted.org/packages/c7/81/5ed69cda630ac69ef60d06c09ba5a7f84ff66a2e28cf986fd5614ab3c6e6/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:e1a622f13970d81f95d0c72f9dc090dce9085fccfa4c9f2174377ee32bd15786", size = 21563 },+ { url = "https://files.pythonhosted.org/packages/0c/fe/fb1e79be0fea60aa32602ebefc9c35a82bb42b4df157285ab7dfec12341a/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c9a7f43c0b202b334cc9184af09bb8f21d3a209e038efaf106936fb69e6b026e", size = 23048 },+]++[[package]]+name = "mpmath"+version = "1.3.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198 },+]++[[package]]+name = "networkx"+version = "3.7"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/dc/76/3af777226b63a5e64a6b36b1ec5855c14e2b94a37096d4760e595fc43511/networkx-3.7.tar.gz", hash = "sha256:fd77a511bd90f39f3d016351345b52cf5319b813bdca01de3f755d3cca62e96a", size = 1866482 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/7e/cd/fe58041e9011f307c490e3e17dd48cc516448f7c698a3f2d9d9d65d7e6a8/networkx-3.7-py3-none-any.whl", hash = "sha256:e3fd2c13a7814cee3746340d8d7f8598a67f16a58bf47fb7f8793fab6efca1b0", size = 2142205 },+]++[[package]]+name = "numpy"+version = "2.4.6"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/d0/ad/fed0499ce6a338d2a03ebae59cd15093910c8875328855781952abf6c2fe/numpy-2.4.6.tar.gz", hash = "sha256:f3a3570c4a2a16746ac2c31a7c7c7b0c186b95ce902e33db6f28094ed7387dda", size = 20735807 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/99/60/14115e6364fa676c5397c2ad3004e527e9aa487abf5d0706ec81bbd08529/numpy-2.4.6-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:90f9849678c75fe7afa2d348ac842c168b0a4d3d61919687216dfc547976d853", size = 16645538 },+ { url = "https://files.pythonhosted.org/packages/ef/fc/85b7c4eff9b4966ade25c2273cf7e7012e92366c032058653934b37de044/numpy-2.4.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e5805d5a22fd19c8ccff10a9561f9df94436b0545619ea579db2d3c35294bce2", size = 18368541 },+]++[[package]]+name = "nvidia-cublas-cu12"+version = "12.8.4.1"+source = { registry = "https://pypi.org/simple" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/dc/61/e24b560ab2e2eaeb3c839129175fb330dfcfc29e5203196e5541a4c44682/nvidia_cublas_cu12-12.8.4.1-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:8ac4e771d5a348c551b2a426eda6193c19aa630236b418086020df5ba9667142", size = 594346921 },+]++[[package]]+name = "nvidia-cuda-cupti-cu12"+version = "12.8.90"+source = { registry = "https://pypi.org/simple" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/f8/02/2adcaa145158bf1a8295d83591d22e4103dbfd821bcaf6f3f53151ca4ffa/nvidia_cuda_cupti_cu12-12.8.90-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ea0cb07ebda26bb9b29ba82cda34849e73c166c18162d3913575b0c9db9a6182", size = 10248621 },+]++[[package]]+name = "nvidia-cuda-nvrtc-cu12"+version = "12.8.93"+source = { registry = "https://pypi.org/simple" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/05/6b/32f747947df2da6994e999492ab306a903659555dddc0fbdeb9d71f75e52/nvidia_cuda_nvrtc_cu12-12.8.93-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:a7756528852ef889772a84c6cd89d41dfa74667e24cca16bb31f8f061e3e9994", size = 88040029 },+]++[[package]]+name = "nvidia-cuda-runtime-cu12"+version = "12.8.90"+source = { registry = "https://pypi.org/simple" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/0d/9b/a997b638fcd068ad6e4d53b8551a7d30fe8b404d6f1804abf1df69838932/nvidia_cuda_runtime_cu12-12.8.90-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:adade8dcbd0edf427b7204d480d6066d33902cab2a4707dcfc48a2d0fd44ab90", size = 954765 },+]++[[package]]+name = "nvidia-cudnn-cu12"+version = "9.10.2.21"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "nvidia-cublas-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]+wheels = [+ { url = "https://files.pythonhosted.org/packages/ba/51/e123d997aa098c61d029f76663dedbfb9bc8dcf8c60cbd6adbe42f76d049/nvidia_cudnn_cu12-9.10.2.21-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:949452be657fa16687d0930933f032835951ef0892b37d2d53824d1a84dc97a8", size = 706758467 },+]++[[package]]+name = "nvidia-cufft-cu12"+version = "11.3.3.83"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "nvidia-nvjitlink-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]+wheels = [+ { url = "https://files.pythonhosted.org/packages/1f/13/ee4e00f30e676b66ae65b4f08cb5bcbb8392c03f54f2d5413ea99a5d1c80/nvidia_cufft_cu12-11.3.3.83-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4d2dd21ec0b88cf61b62e6b43564355e5222e4a3fb394cac0db101f2dd0d4f74", size = 193118695 },+]++[[package]]+name = "nvidia-cufile-cu12"+version = "1.13.1.3"+source = { registry = "https://pypi.org/simple" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/bb/fe/1bcba1dfbfb8d01be8d93f07bfc502c93fa23afa6fd5ab3fc7c1df71038a/nvidia_cufile_cu12-1.13.1.3-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1d069003be650e131b21c932ec3d8969c1715379251f8d23a1860554b1cb24fc", size = 1197834 },+]++[[package]]+name = "nvidia-curand-cu12"+version = "10.3.9.90"+source = { registry = "https://pypi.org/simple" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/fb/aa/6584b56dc84ebe9cf93226a5cde4d99080c8e90ab40f0c27bda7a0f29aa1/nvidia_curand_cu12-10.3.9.90-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:b32331d4f4df5d6eefa0554c565b626c7216f87a06a4f56fab27c3b68a830ec9", size = 63619976 },+]++[[package]]+name = "nvidia-cusolver-cu12"+version = "11.7.3.90"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "nvidia-cublas-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "nvidia-cusparse-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "nvidia-nvjitlink-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]+wheels = [+ { url = "https://files.pythonhosted.org/packages/85/48/9a13d2975803e8cf2777d5ed57b87a0b6ca2cc795f9a4f59796a910bfb80/nvidia_cusolver_cu12-11.7.3.90-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:4376c11ad263152bd50ea295c05370360776f8c3427b30991df774f9fb26c450", size = 267506905 },+]++[[package]]+name = "nvidia-cusparse-cu12"+version = "12.5.8.93"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "nvidia-nvjitlink-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]+wheels = [+ { url = "https://files.pythonhosted.org/packages/c2/f5/e1854cb2f2bcd4280c44736c93550cc300ff4b8c95ebe370d0aa7d2b473d/nvidia_cusparse_cu12-12.5.8.93-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1ec05d76bbbd8b61b06a80e1eaf8cf4959c3d4ce8e711b65ebd0443bb0ebb13b", size = 288216466 },+]++[[package]]+name = "nvidia-cusparselt-cu12"+version = "0.7.1"+source = { registry = "https://pypi.org/simple" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/56/79/12978b96bd44274fe38b5dde5cfb660b1d114f70a65ef962bcbbed99b549/nvidia_cusparselt_cu12-0.7.1-py3-none-manylinux2014_x86_64.whl", hash = "sha256:f1bb701d6b930d5a7cea44c19ceb973311500847f81b634d802b7b539dc55623", size = 287193691 },+]++[[package]]+name = "nvidia-nccl-cu12"+version = "2.27.5"+source = { registry = "https://pypi.org/simple" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/6e/89/f7a07dc961b60645dbbf42e80f2bc85ade7feb9a491b11a1e973aa00071f/nvidia_nccl_cu12-2.27.5-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ad730cf15cb5d25fe849c6e6ca9eb5b76db16a80f13f425ac68d8e2e55624457", size = 322348229 },+]++[[package]]+name = "nvidia-nvjitlink-cu12"+version = "12.8.93"+source = { registry = "https://pypi.org/simple" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/f6/74/86a07f1d0f42998ca31312f998bd3b9a7eff7f52378f4f270c8679c77fb9/nvidia_nvjitlink_cu12-12.8.93-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:81ff63371a7ebd6e6451970684f916be2eab07321b73c9d244dc2b4da7f73b88", size = 39254836 },+]++[[package]]+name = "nvidia-nvshmem-cu12"+version = "3.3.20"+source = { registry = "https://pypi.org/simple" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/3b/6c/99acb2f9eb85c29fc6f3a7ac4dccfd992e22666dd08a642b303311326a97/nvidia_nvshmem_cu12-3.3.20-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d00f26d3f9b2e3c3065be895e3059d6479ea5c638a3f38c9fec49b1b9dd7c1e5", size = 124657145 },+]++[[package]]+name = "nvidia-nvtx-cu12"+version = "12.8.90"+source = { registry = "https://pypi.org/simple" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/a2/eb/86626c1bbc2edb86323022371c39aa48df6fd8b0a1647bc274577f72e90b/nvidia_nvtx_cu12-12.8.90-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5b17e2001cc0d751a5bc2c6ec6d26ad95913324a4adb86788c944f8ce9ba441f", size = 89954 },+]++[[package]]+name = "packaging"+version = "26.3"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956 },+]++[[package]]+name = "peft"+version = "0.18.1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "accelerate", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "huggingface-hub", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "numpy", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "packaging", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "psutil", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "pyyaml", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "safetensors", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "torch", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "tqdm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "transformers", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/d8/48/147b3ea999560b40a34fd78724c7777aa9d18409c2250bdcaf9c4f2db7fc/peft-0.18.1.tar.gz", hash = "sha256:2dd0d6bfce936d1850e48aaddbd250941c5c02fc8ef3237cd8fd5aac35e0bae2", size = 635030 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/b3/14/b4e3f574acf349ae6f61f9c000a77f97a3b315b4bb6ad03791e79ae4a568/peft-0.18.1-py3-none-any.whl", hash = "sha256:0bf06847a3551e3019fc58c440cffc9a6b73e6e2962c95b52e224f77bbdb50f1", size = 556960 },+]++[[package]]+name = "psutil"+version = "7.2.2"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/aa/c6/d1ddf4abb55e93cebc4f2ed8b5d6dbad109ecb8d63748dd2b20ab5e57ebe/psutil-7.2.2.tar.gz", hash = "sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372", size = 493740 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/b5/70/5d8df3b09e25bce090399cf48e452d25c935ab72dad19406c77f4e828045/psutil-7.2.2-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9", size = 155560 },+ { url = "https://files.pythonhosted.org/packages/04/78/0acd37ca84ce3ddffaa92ef0f571e073faa6d8ff1f0559ab1272188ea2be/psutil-7.2.2-cp36-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc", size = 148266 },+]++[[package]]+name = "pyyaml"+version = "6.0.3"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/65/30/d7353c338e12baef4ecc1b09e877c1970bd3382789c159b4f89d6a70dc09/pyyaml-6.0.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c", size = 844011 },+ { url = "https://files.pythonhosted.org/packages/8b/9d/b3589d3877982d4f2329302ef98a8026e7f4443c765c46cfecc8858c6b4b/pyyaml-6.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc", size = 807870 },+ { url = "https://files.pythonhosted.org/packages/be/8e/98435a21d1d4b46590d5459a22d88128103f8da4c2d4cb8f14f2a96504e1/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea", size = 790181 },+]++[[package]]+name = "regex"+version = "2026.9.29"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/fc/f2/af1da9d3ceed77bfcdce40427d49ba0be94e4fe84245e3bfef68c10e75b6/regex-2026.9.29.tar.gz", hash = "sha256:8b5fcc4771732191b2b7d1dd68d8f0353f47f8d90b6150f6dce58bf1112442cb", size = 419199 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/f6/78/25436bcfd4d2260b4b4090094d55d7ab53ec8a1ab4865a0b8bcb33c7d5c0/regex-2026.9.29-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9e1d3a4cb7993b708f0ada8d0c84590efd853f169e7147d2202c9da503180242", size = 878344 },+ { url = "https://files.pythonhosted.org/packages/97/e6/a09ec3a23ae41d6179880e67f0aace9284b2d95f2d7b326eff203f8eec5e/regex-2026.9.29-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:dabee8f4935e731fb46b2a3091bdda0d3d94b3bbfb907d2b4f12eefce4009619", size = 919181 },+ { url = "https://files.pythonhosted.org/packages/26/83/d2fbd2e4e3afb1167daa825187d196f313cbaa1a4768f311fb041bb0e3d2/regex-2026.9.29-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:39ab5894d971f9ac68baa6eca5c50387db579cfcacf36ae8df3feceb1815e6d0", size = 807783 },+ { url = "https://files.pythonhosted.org/packages/46/0b/eb429a7016610d44fc89a597163f8c9127505f0d7dc724dc9effbb6a3ac0/regex-2026.9.29-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c1a9a6651197fbed6f0212591418b9def774fc3f8324f78d1bf0e6a63e5f8aa1", size = 783465 },+ { url = "https://files.pythonhosted.org/packages/2a/e8/161b94d39164520e21a7befe0245569bf7fda4c7cf1fc4e2df2b5def49da/regex-2026.9.29-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:3c5c2ef13797466aa64170cbb66ad98a32351dd4127694cea7199f80f213750d", size = 869293 },+ { url = "https://files.pythonhosted.org/packages/8f/07/3b02ed829aa2decdc1955d222bd1e2f99d1c8bb4873bbb9a66b2f0a36bff/regex-2026.9.29-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:59b49507f47479e299a9e1bc41b5cb83a7afda0540625f1dbae886615978acbf", size = 770239 },+ { url = "https://files.pythonhosted.org/packages/42/5b/ba61f6fe062eb8562e742367d177bb75370434138ef6c9d2a27114f8d613/regex-2026.9.29-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:0dd8af32e9f7b56b7f95cc1fd79b23054c3bdc172392ae560acc24d57b7ffe71", size = 861973 },+ { url = "https://files.pythonhosted.org/packages/cc/27/767259b20e8a842948990f5e99138d6c077248fd42f8b5468b1d9ca4b814/regex-2026.9.29-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:db5e82ba15c142425b8406690032df89e39cca4a2e8afbbb9a3d84edc2373ac3", size = 796470 },+]++[[package]]+name = "requests"+version = "2.34.2"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "certifi", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "charset-normalizer", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "idna", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "urllib3", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075 },+]++[[package]]+name = "safetensors"+version = "0.8.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/45/06/f955dbbb1859e3bd23c8ac6141af5106e7ad5fedec4a3a6e3d60f94b7001/safetensors-0.8.0.tar.gz", hash = "sha256:fabaf3e0f18a6618d9b36560682562157f77c2b71fcffc7b432be2baed9d753d", size = 325846 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/91/4f/3175c9d75634e0e0dda0082794193521035edd7c70a6f212bf33ca06ddf4/safetensors-0.8.0-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4124502b78f03534117c848f87a39b8f31e577b15eff423bf8bfb95f2a8c30d0", size = 511823 },+ { url = "https://files.pythonhosted.org/packages/20/87/846c289e7aa2299eff406335717cf43ce8777194ece8aad75772e0411615/safetensors-0.8.0-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7bc0a787ba8a35be368ee3574edfa2b1ad389eebd0a72e482ae275490e3f6c98", size = 633461 },+ { url = "https://files.pythonhosted.org/packages/76/22/8d64d9df2c45d5ded401df889d0ad90882804ca172d79ec4f0df8f727fe0/safetensors-0.8.0-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:040070828e36dc8e122178bbbd5830ff9e97920affb84cbe0f46442497bed358", size = 545148 },+ { url = "https://files.pythonhosted.org/packages/28/50/f203ff3a3ddfe19308efc83c5a3a29ed02bf786732ec35e68bf9162f3365/safetensors-0.8.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd6f3f93c9a0a7cc2788ee63fb763353d4bd2e89b0751bc78fcf7dda00bea774", size = 516040 },+ { url = "https://files.pythonhosted.org/packages/46/fb/cdaed17ceb2948784fd9c36b6fd3e951b608547cea81a48e8ee6f8cfdfcb/safetensors-0.8.0-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:fcdd41ec4628fee5799f807c73c353629130fbd942aa23d83c623dd6c9d52d78", size = 513832 },+ { url = "https://files.pythonhosted.org/packages/72/e3/68cd3fa5b48488e84add63e04cb12f3bc28ae4638c06d4508c6e88823d0e/safetensors-0.8.0-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:4a95ae2b05d7726d751da4ebf626a2ca782b706e101bd894c95bc2450b1cffcc", size = 786679 },+ { url = "https://files.pythonhosted.org/packages/27/43/41c1621732edd934d868a00d1b891584c892a7b62a9aab82ea5a0a5623ee/safetensors-0.8.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:8e080062fcde23be189565e1c3305d16751a218ecf9412c8601e64204eb6f846", size = 722361 },+]++[[package]]+name = "scikit-learn"+version = "1.6.1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "joblib", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "numpy", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "scipy", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "threadpoolctl", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/9e/a5/4ae3b3a0755f7b35a280ac90b28817d1f380318973cff14075ab41ef50d9/scikit_learn-1.6.1.tar.gz", hash = "sha256:b4fc2525eca2c69a59260f583c56a7557c6ccdf8deafdba6e060f94c1c59738e", size = 7068312 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/29/7a/8bce8968883e9465de20be15542f4c7e221952441727c4dad24d534c6d99/scikit_learn-1.6.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2e69fab4ebfc9c9b580a7a80111b43d214ab06250f8a7ef590a4edf72464dd86", size = 13147700 },+]++[[package]]+name = "scipy"+version = "1.17.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "numpy", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/56/3e/9cca699f3486ce6bc12ff46dc2031f1ec8eb9ccc9a320fdaf925f1417426/scipy-1.17.0.tar.gz", hash = "sha256:2591060c8e648d8b96439e111ac41fd8342fdeff1876be2e19dea3fe8930454e", size = 30396830 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/d1/fe/66d73b76d378ba8cc2fe605920c0c75092e3a65ae746e1e767d9d020a75a/scipy-1.17.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9eeb9b5f5997f75507814ed9d298ab23f62cf79f5a3ef90031b1ee2506abdb5b", size = 35009148 },+ { url = "https://files.pythonhosted.org/packages/81/61/0470810c8a093cdacd4ba7504b8a218fd49ca070d79eca23a615f5d9a0b0/scipy-1.17.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0cf46c8013fec9d3694dc572f0b54100c28405d55d3e2cb15e2895b25057996e", size = 37405953 },+]++[[package]]+name = "setuptools"+version = "84.2.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/70/b3/c19426f783614d625699a4b247faf628ea9ab1db228674491767b417f9e1/setuptools-84.2.1.tar.gz", hash = "sha256:3ff8b3b5492a0aa66960f4419365a86b84e013070d4313e4d4a6894f5d64d6bc", size = 1230289 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/ef/55/6dc6d6bb953bdfc52519a0059592c52b6e3b8ad51cf8256dffceb55b0610/setuptools-84.2.1-py3-none-any.whl", hash = "sha256:ca140b45d5325a9478f880e351484f62fef15f336462e449ca0c03c873d589c2", size = 876263 },+]++[[package]]+name = "sympy"+version = "1.14.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "mpmath", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353 },+]++[[package]]+name = "threadpoolctl"+version = "3.7.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/00/dc/6c58154c1c65f758ea979e7139cb76993a9cfc662d14e9be3c4a667cfb77/threadpoolctl-3.7.0.tar.gz", hash = "sha256:61348cfb77d53b9242e0017029244b559b810c142ced65b4e21eeca1843959a7", size = 31961 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/43/3f/f88a53f60a472b46f4023f56d204dd7de33d34c5d2acbfa0d70a674e639e/threadpoolctl-3.7.0-py3-none-any.whl", hash = "sha256:cd8b60b5641b45c67bbf73c64c843235fc2d8a480c87389f52f5dbee893b86be", size = 26362 },+]++[[package]]+name = "tokenizers"+version = "0.22.2"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "huggingface-hub", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/73/6f/f80cfef4a312e1fb34baf7d85c72d4411afde10978d4657f8cdd811d3ccc/tokenizers-0.22.2.tar.gz", hash = "sha256:473b83b915e547aa366d1eee11806deaf419e17be16310ac0a14077f1e28f917", size = 372115 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/78/59/09d0d9ba94dcd5f4f1368d4858d24546b4bdc0231c2354aa31d6199f0399/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:25b85325d0815e86e0bac263506dd114578953b7b53d7de09a6485e4a160a7dd", size = 3168835 },+ { url = "https://files.pythonhosted.org/packages/e0/fa/89f4cb9e08df770b57adb96f8cbb7e22695a4cb6c2bd5f0c4f0ebcf33b66/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1c774b1276f71e1ef716e5486f21e76333464f47bece56bbd554485982a9e03e", size = 3724818 },+ { url = "https://files.pythonhosted.org/packages/64/04/ca2363f0bfbe3b3d36e95bf67e56a4c88c8e3362b658e616d1ac185d47f2/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:df6c4265b289083bf710dff49bc51ef252f9d5be33a45ee2bed151114a56207b", size = 3379195 },+ { url = "https://files.pythonhosted.org/packages/2e/76/932be4b50ef6ccedf9d3c6639b056a967a86258c6d9200643f01269211ca/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:369cc9fc8cc10cb24143873a0d95438bb8ee257bb80c71989e3ee290e8d72c67", size = 3274982 },+ { url = "https://files.pythonhosted.org/packages/6c/fb/66e2da4704d6aadebf8cb39f1d6d1957df667ab24cff2326b77cda0dcb85/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:37ae80a28c1d3265bb1f22464c856bd23c02a05bb211e56d0c5301a435be6c1a", size = 9560069 },+ { url = "https://files.pythonhosted.org/packages/05/a1/d62dfe7376beaaf1394917e0f8e93ee5f67fea8fcf4107501db35996586b/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:38337540fbbddff8e999d59970f3c6f35a82de10053206a7562f1ea02d046fa5", size = 10033429 },+]++[[package]]+name = "torch"+version = "2.9.1+cu128"+source = { registry = "https://download.pytorch.org/whl/cu128" }+dependencies = [+ { name = "filelock", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "fsspec", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "jinja2", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "networkx", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "nvidia-cublas-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "nvidia-cuda-cupti-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "nvidia-cuda-nvrtc-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "nvidia-cuda-runtime-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "nvidia-cudnn-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "nvidia-cufft-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "nvidia-cufile-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "nvidia-curand-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "nvidia-cusolver-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "nvidia-cusparse-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "nvidia-cusparselt-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "nvidia-nccl-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "nvidia-nvjitlink-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "nvidia-nvshmem-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "nvidia-nvtx-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "setuptools", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "sympy", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "triton", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "typing-extensions", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]+wheels = [+ { url = "https://download-r2.pytorch.org/whl/cu128/torch-2.9.1%2Bcu128-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:7cb4018f4ce68b61fd3ef87dc1c4ca520731c7b5b200e360ad47b612d7844063" },+]++[[package]]+name = "tqdm"+version = "4.70.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/0d/ea/b2a5bd54b28a324dae8211928b2d730b6547500342c7e6c6dea08bd0a485/tqdm-4.70.1.tar.gz", hash = "sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4", size = 171846 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/a7/03/921a3d3c75785aca9ebfbfcabfbc3a1be12e2ab5265deb026d55a5a3f83e/tqdm-4.70.1-py3-none-any.whl", hash = "sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73", size = 80199 },+]++[[package]]+name = "train-a-router-gpu"+version = "0.1.0"+source = { virtual = "." }+dependencies = [+ { name = "einops", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "flash-attn", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "laya", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "numpy", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "peft", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "scikit-learn", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "scipy", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "torch", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "transformers", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]++[package.metadata]+requires-dist = [+ { name = "einops", specifier = "==0.8.2" },+ { name = "flash-attn", specifier = "==2.8.3.post1+cu.12.8.torch.2.9", index = "https://wheels.astral.sh/simple/cu128/" },+ { name = "laya", specifier = "==0.3.29" },+ { name = "numpy", specifier = "==2.4.6" },+ { name = "peft", specifier = "==0.18.1" },+ { name = "scikit-learn", specifier = "==1.6.1" },+ { name = "scipy", specifier = "==1.17.0" },+ { name = "torch", specifier = "==2.9.1+cu128", index = "https://download.pytorch.org/whl/cu128" },+ { name = "transformers", specifier = "==4.57.6" },+]++[[package]]+name = "transformers"+version = "4.57.6"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "filelock", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "huggingface-hub", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "numpy", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "packaging", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "pyyaml", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "regex", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "requests", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "safetensors", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "tokenizers", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+ { name = "tqdm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/c4/35/67252acc1b929dc88b6602e8c4a982e64f31e733b804c14bc24b47da35e6/transformers-4.57.6.tar.gz", hash = "sha256:55e44126ece9dc0a291521b7e5492b572e6ef2766338a610b9ab5afbb70689d3", size = 10134912 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/03/b8/e484ef633af3887baeeb4b6ad12743363af7cce68ae51e938e00aaa0529d/transformers-4.57.6-py3-none-any.whl", hash = "sha256:4c9e9de11333ddfe5114bc872c9f370509198acf0b87a832a0ab9458e2bd0550", size = 11993498 },+]++[[package]]+name = "triton"+version = "3.5.1"+source = { registry = "https://pypi.org/simple" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/f2/50/9a8358d3ef58162c0a415d173cfb45b67de60176e1024f71fbc4d24c0b6d/triton-3.5.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d2c6b915a03888ab931a9fd3e55ba36785e1fe70cbea0b40c6ef93b20fc85232", size = 170470207 },+]++[[package]]+name = "typing-extensions"+version = "4.16.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571 },+]++[[package]]+name = "urllib3"+version = "2.8.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717 },+]diff --git a/examples/train-a-router/native/fast_protocol.py b/examples/train-a-router/native/fast_protocol.pynew file mode 100644index 000000000..1610a74b7--- /dev/null+++ b/examples/train-a-router/native/fast_protocol.py@@ -0,0 +1,109 @@+"""Versioned runtime contract for accelerated training with reference FP32 scoring."""++from __future__ import annotations++import hashlib+import importlib.metadata+import inspect+from pathlib import Path++RECIPE_ID = "laya-fa2-grouped-v1"+REFERENCE_FILES = {+ "bbeh_native.py": "c379f86f55bfccbfcd6c0e613d54adf9f8f155cc1c654a0e30e45998181b9e28",+ "recipe.py": "c500d1278ae7fe5c726f9accd277ff94c8b09b86c78cfbd19c1db1b035ba21e1",+}+VERSIONS = {+ "laya": "0.3.29",+ "peft": "0.18.1",+ "torch": "2.9.1+cu128",+ "transformers": "4.57.6",+ "flash-attn": "2.8.3.post1+cu.12.8.torch.2.9",+ "einops": "0.8.2",+}+LAYA_SOURCES = {+ "laya/train.py": "71c83361dea7f9e4ae0f54d3f5d46e477860ebef875066aac9c9368e3d9fed34",+ "laya/common.py": "f9a67471e635754e3233fa25842ee2a51601755e53f21b2681938021236530e7",+}+EFFECTIVE = {+ "training_attention": "flash_attention_2",+ "training_autocast": "float16",+ "gradient_checkpointing": False,+ "micro_batch": 4,+ "grad_accum": 4,+ "effective_batch_decision_items": 16,+ "grouping": "Stable length sort within each original effective batch; unequal partial tail keeps original order",+ "option_permutations": "Original continuous seeded RNG, drawn in original epoch order before grouping",+ "validation_attention": "sdpa",+ "validation_autocast": False,+ "validation_dtype": "float32",+ "export_attention": "sdpa",+ "selection": "All epochs0..8; minimum development summed binary NLL; earlier epoch breaks exact ties",+ "refit": "Fresh pinned base and seed; train+development for selected epoch count",+ "scheduler": "Original cosine schedule and attempted-window advancement, including GradScaler skips",+ "trajectory": "Grouping changes dropout and floating-point accumulation; this is a distinct recipe",+}+++def sha(path):+ with Path(path).open("rb") as stream:+ return hashlib.file_digest(stream, "sha256").hexdigest()+++def checked_reference(directory=None):+ directory = Path(directory) if directory else Path(__file__).parent+ actual = {name: sha(directory / name) for name in REFERENCE_FILES}+ if actual != REFERENCE_FILES:+ raise ValueError("Fast recipe requires the exact frozen reference source")+ return actual+++def checked_versions():+ actual = {name: importlib.metadata.version(name) for name in VERSIONS}+ if actual != VERSIONS:+ raise ValueError(f"Fast recipe requires the pinned GPU environment: {actual}")+ return actual+++def manifest(plan_sha256, runtime):+ root = Path(__file__).parent+ gpu = root.parent / "gpu"+ return {+ "format": "laya-fast-runtime-recipe-v1",+ "recipe_id": RECIPE_ID,+ "reference_plan_sha256": plan_sha256,+ "reference_sources_sha256": checked_reference(root),+ "implementation_sources_sha256": {+ name: sha(root / name) for name in ("fast_protocol.py", "fast_runtime.py", "fast_train.py")+ },+ "effective_runtime": EFFECTIVE,+ "runtime": runtime,+ "gpu_project_sha256": {name: sha(gpu / name) for name in ("pyproject.toml", "uv.lock")},+ "unchanged": "Inputs, labels, context, loss, LoRA/head dimensions, optimizer hyperparameters and selection rule",+ "final_outcomes_accessed": False,+ }+++def runtime_inventory():+ import laya.common+ import laya.train+ import torch+ import transformers.models.modernbert.modeling_modernbert as modernbert++ versions = checked_versions()+ sources = {"laya/train.py": sha(inspect.getfile(laya.train)),+ "laya/common.py": sha(inspect.getfile(laya.common))}+ if sources != LAYA_SOURCES:+ raise ValueError("Installed Laya source differs from the versioned fast implementation contract")+ if not torch.cuda.is_available():+ raise ValueError("The fast recipe requires CUDA")+ if torch.backends.cuda.matmul.allow_tf32:+ raise ValueError("TF32 matmul must remain disabled, matching the reference precision")+ return {+ "versions": versions,+ "cuda_runtime": torch.version.cuda,+ "gpu": torch.cuda.get_device_name(0),+ "gpu_memory_bytes": torch.cuda.get_device_properties(0).total_memory,+ "cpu_threads": torch.get_num_threads(),+ "tf32_matmul_allowed": torch.backends.cuda.matmul.allow_tf32,+ "installed_source_sha256": dict(sources, **{"transformers/modernbert.py": sha(inspect.getfile(modernbert))}),+ }diff --git a/examples/train-a-router/native/fast_runtime.py b/examples/train-a-router/native/fast_runtime.pynew file mode 100644index 000000000..00785f466--- /dev/null+++ b/examples/train-a-router/native/fast_runtime.py@@ -0,0 +1,221 @@+"""Grouped FA2 training; synchronization keeps all reference scoring on FP32 SDPA."""++from __future__ import annotations++import copy+import gc+import hashlib+import json+import math+import random+import time+from dataclasses import asdict+++def grouped_windows(encoded, micro_batch=4, grad_accum=4):+ size = micro_batch * grad_accum+ for start in range(0, len(encoded), size):+ window = list(encoded[start:start + size])+ if len(window) % micro_batch == 0:+ window.sort(key=lambda item: len(item["ids"]))+ yield window+++def encoded_epoch(lt, tokenizer, items, config, epoch, order_rng, max_len, head_max_len, trace=None):+ ordered = list(range(len(items)))+ random.Random(config.seed + epoch).shuffle(ordered)+ encoded, assignment = [], []+ for index in ordered:+ item = items[index]+ options = lt.draw_option_order(item, order_rng, config.shuffle_options)+ assignment.append([index, options])+ encoded.append(lt.encode_item(tokenizer, item, max_len, head_max_len, options, False))+ if trace is not None:+ trace["original_item_option_assignment_sha256"] = hashlib.sha256(+ json.dumps(assignment, separators=(",", ":")).encode()+ ).hexdigest()+ return encoded+++def require_sdpa_fp32(model):+ import torch++ if model.encoder.config._attn_implementation != "sdpa":+ raise ValueError("Selection/export/scoring must use the SDPA model")+ if any(p.dtype != torch.float32 for p in model.parameters() if p.is_floating_point()):+ raise ValueError("Selection/export/scoring parameters must be FP32")+ if torch.is_autocast_enabled("cuda"):+ raise ValueError("Reference scoring cannot run inside CUDA autocast")+++def synchronized_state(source, destination):+ import torch++ state = source.state_dict()+ destination.load_state_dict(state, strict=True)+ target = destination.state_dict()+ if set(state) != set(target) or any(not torch.equal(value, target[key]) for key, value in state.items()):+ raise ValueError("FA2 to SDPA synchronization changed checkpoint values")+++def training_copy(model, device):+ import torch+ from peft import get_peft_model+ from transformers import AutoModel+ from transformers.modeling_utils import no_init_weights++ require_sdpa_fp32(model)+ if set(model.encoder.peft_config) != {"default"}:+ raise ValueError("Expected the single frozen default LoRA adapter")+ configuration = copy.deepcopy(model.encoder.config)+ configuration.reference_compile = False+ lora = copy.deepcopy(model.encoder.peft_config["default"])+ trained = copy.deepcopy(model)+ del trained.encoder+ with no_init_weights():+ encoder = AutoModel.from_config(configuration, attn_implementation="flash_attention_2")+ encoder = get_peft_model(encoder, lora)+ encoder.load_state_dict(model.encoder.state_dict(), strict=True)+ trained.encoder = encoder.to(device)+ synchronized_state(model, trained)+ if trained.encoder.config._attn_implementation != "flash_attention_2":+ raise ValueError("FA2 construction did not select the requested backend")+ if hasattr(trained.encoder, "gradient_checkpointing_disable"):+ trained.encoder.gradient_checkpointing_disable()+ trained.head_checkpointing = False+ trained.to(device).train()+ if any(p.dtype != torch.float32 for p in trained.parameters() if p.is_floating_point()):+ raise ValueError("Training parameters changed dtype")+ return trained+++def parameter_fingerprint(model):+ digest = hashlib.sha256()+ for name, parameter in model.named_parameters():+ if parameter.requires_grad:+ digest.update(name.encode())+ digest.update(parameter.detach().cpu().numpy().tobytes())+ return digest.hexdigest()+++def train_model(lt, model, tokenizer, items, config, device, max_len, head_max_len,+ on_epoch_end=None, parallel=False, *, phase, record):+ import torch++ config.validate()+ if (not items or parallel or config.freeze_encoder or config.loss != "soft-ce"+ or config.micro_batch != 4 or config.grad_accum != 4 or config.amp not in (None, True)):+ raise ValueError("Unsupported configuration for the versioned fast recipe")+ require_sdpa_fp32(model)+ started = time.perf_counter()+ trained = training_copy(model, device)+ torch.cuda.synchronize()+ copied_seconds = time.perf_counter() - started+ initial = parameter_fingerprint(trained)++ class CountedAdamW(torch.optim.AdamW):+ actual_steps = 0++ def step(self, closure=None):+ result = super().step(closure)+ self.actual_steps += 1+ return result++ groups = [+ {"params": [p for n, p in trained.named_parameters() if n.startswith("encoder.") and p.requires_grad],+ "lr": config.encoder_lr},+ {"params": [p for n, p in trained.named_parameters() if not n.startswith("encoder.") and p.requires_grad],+ "lr": config.head_lr},+ ]+ optimizer = CountedAdamW(groups, weight_decay=config.weight_decay)+ steps_per_epoch = math.ceil(len(items) / config.micro_batch)+ updates = max(1, math.ceil(steps_per_epoch / config.grad_accum) * config.epochs)+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=updates, eta_min=config.min_lr)+ scaler = torch.amp.GradScaler("cuda")+ torch.manual_seed(config.seed)+ rng = {"cpu_sha256": hashlib.sha256(torch.get_rng_state().numpy().tobytes()).hexdigest(),+ "cuda_sha256": [hashlib.sha256(x.cpu().numpy().tobytes()).hexdigest()+ for x in torch.cuda.get_rng_state_all()]}+ order_rng = random.Random(config.seed)+ parameters = [p for group in groups for p in group["params"]]+ history, epochs = [], []+ effective = dict(asdict(config), gradient_checkpointing=False)+ record({"event": "phase_start", "phase": phase, "effective_config": effective,+ "initial_trainable_sha256": initial, "model_copy_seconds": copied_seconds,+ "initial_rng": rng,+ "scheduler_attempted_windows": updates, "items_per_epoch": len(items)})+ try:+ for epoch in range(config.epochs):+ trained.train()+ torch.cuda.reset_peak_memory_stats()+ torch.cuda.synchronize()+ epoch_started = time.perf_counter()+ assignment = {}+ encoded = encoded_epoch(lt, tokenizer, items, config, epoch, order_rng, max_len, head_max_len, assignment)+ total, micro_steps, actual_tokens, padded_tokens = 0.0, 0, 0, 0+ windows, before_steps = [], optimizer.actual_steps+ optimizer.zero_grad(set_to_none=True)+ for window_index, window in enumerate(grouped_windows(encoded, config.micro_batch, config.grad_accum)):+ chunks = [window[start:start + config.micro_batch]+ for start in range(0, len(window), config.micro_batch)]+ for chunk in chunks:+ batch = lt.collate_items([chunk], tokenizer.pad_token_id)+ lengths = [len(item["ids"]) for item in chunk]+ actual_tokens += sum(lengths)+ padded_tokens += len(lengths) * max(lengths)+ logits = lt._forward(trained, batch, device, True, False)+ loss = lt.soft_ce_loss(logits, batch["target"].to(device), batch["marker_mask"].to(device))+ scaler.scale(loss / len(chunks)).backward()+ total += loss.item()+ micro_steps += 1+ scaler.unscale_(optimizer)+ norm = float(torch.nn.utils.clip_grad_norm_(parameters, config.grad_clip))+ scale_before, steps_before = scaler.get_scale(), optimizer.actual_steps+ scaler.step(optimizer)+ scaler.update()+ scheduler.step()+ optimizer.zero_grad(set_to_none=True)+ windows.append({"window": window_index, "gradient_norm": norm if math.isfinite(norm) else None,+ "scale_before": scale_before, "scale_after": scaler.get_scale(),+ "optimizer_step": optimizer.actual_steps != steps_before})+ torch.cuda.synchronize()+ train_seconds = time.perf_counter() - epoch_started+ loss = total / micro_steps+ if not math.isfinite(loss) or any(not torch.isfinite(p).all() for p in parameters):+ raise ValueError("Nonfinite loss or final trainable parameter")+ history.append(loss)+ sync_started = time.perf_counter()+ synchronized_state(trained, model)+ torch.cuda.synchronize()+ sync_seconds = time.perf_counter() - sync_started+ measured = {+ "event": "epoch", "phase": phase, "epoch": epoch + 1, "loss": loss,+ "training_seconds": train_seconds, "synchronization_seconds": sync_seconds,+ "decision_items": len(encoded), "micro_batches": micro_steps,+ "attempted_optimizer_windows": len(windows),+ "actual_optimizer_steps": optimizer.actual_steps - before_steps,+ "skipped_optimizer_windows": [w["window"] for w in windows if not w["optimizer_step"]],+ "actual_tokens": actual_tokens, "padded_tokens": padded_tokens,+ "peak_allocated_bytes": torch.cuda.max_memory_allocated(),+ "peak_reserved_bytes": torch.cuda.max_memory_reserved(), "windows": windows,+ **assignment,+ }+ callback_started = time.perf_counter()+ if on_epoch_end is not None:+ on_epoch_end(epoch, loss)+ measured["callback_seconds_including_reference_validation_and_persistence"] = (+ time.perf_counter() - callback_started+ )+ epochs.append(measured)+ record(measured)+ del encoded, batch, logits, loss+ model.eval()+ record({"event": "phase_complete", "phase": phase, "elapsed_seconds": time.perf_counter() - started,+ "epochs": len(epochs), "actual_optimizer_steps": optimizer.actual_steps,+ "attempted_optimizer_windows": sum(e["attempted_optimizer_windows"] for e in epochs)})+ return history+ finally:+ del trained, optimizer, scheduler, scaler, parameters, groups+ gc.collect()+ torch.cuda.synchronize()+ torch.cuda.empty_cache()diff --git a/examples/train-a-router/native/fast_train.py b/examples/train-a-router/native/fast_train.pynew file mode 100644index 000000000..bd3fc28cf--- /dev/null+++ b/examples/train-a-router/native/fast_train.py@@ -0,0 +1,213 @@+"""Train the explicit fast recipe; retain reference FP32 SDPA validation and exports."""++from __future__ import annotations++import argparse+import contextlib+import json+import os+import shutil+import time+from pathlib import Path++import bbeh_native as reference+import fast_protocol as protocol+import fast_runtime as runtime+++def replace_json(path, value):+ path = Path(path)+ temporary = path.with_suffix(path.suffix + ".tmp")+ temporary.write_text(json.dumps(value, sort_keys=True, indent=2, ensure_ascii=False, allow_nan=False) + "\n",+ encoding="utf-8")+ temporary.replace(path)+++class Recorder:+ def __init__(self, root):+ self.root = Path(root)+ self.root.mkdir(exist_ok=False)+ self.events = []+ self.started = time.perf_counter()+ self.phase = "initialization"++ def record(self, event):+ event = dict(event, elapsed_seconds_since_wrapper_start=time.perf_counter() - self.started)+ self.events.append(event)+ with (self.root / "events.jsonl").open("a", encoding="utf-8") as stream:+ stream.write(json.dumps(event, sort_keys=True, allow_nan=False) + "\n")+ if event.get("event") in {"epoch", "phase_start", "phase_complete"}:+ print(json.dumps({k: event[k] for k in ("event", "phase", "epoch", "loss", "training_seconds",+ "actual_optimizer_steps", "attempted_optimizer_windows") if k in event}), flush=True)++ def snapshot(self):+ epochs = [e for e in self.events if e["event"] == "epoch"]+ validations = [e for e in self.events if e["event"] == "reference_validation"]+ return {+ "format": "laya-fast-runtime-events-v1",+ "recipe_id": protocol.RECIPE_ID,+ "events": self.events,+ "training_seconds": sum(e["training_seconds"] for e in epochs),+ "synchronization_seconds": sum(e["synchronization_seconds"] for e in epochs),+ "model_copy_seconds": sum(e["model_copy_seconds"] for e in self.events if e["event"] == "phase_start"),+ "training_phase_wall_seconds_including_cleanup": {+ e["phase"]: e["elapsed_seconds"] for e in self.events if e["event"] == "training_phase_return"+ },+ "reference_fp32_validation_seconds": sum(e["elapsed_seconds"] for e in validations),+ "reference_fp32_validation_calls": len(validations),+ "actual_optimizer_steps": sum(e["actual_optimizer_steps"] for e in epochs),+ "attempted_optimizer_windows": sum(e["attempted_optimizer_windows"] for e in epochs),+ "peak_allocated_bytes": max((e["peak_allocated_bytes"] for e in epochs + validations), default=0),+ "peak_reserved_bytes": max((e["peak_reserved_bytes"] for e in epochs + validations), default=0),+ "elapsed_seconds": time.perf_counter() - self.started,+ "calibration_or_final_outcomes_accessed": False,+ }+++def fast_execution(recorder):+ import laya.train as lt+ import torch++ original_train, original_records, original_select = lt.train_model, lt.calibration_records, reference.select_epoch+ calls = 0++ def train_model(*args, **kwargs):+ nonlocal calls+ recorder.phase = "selection" if calls == 0 else "refit"+ phase = recorder.phase+ calls += 1+ started = time.perf_counter()+ result = runtime.train_model(lt, *args, **kwargs, phase=phase, record=recorder.record)+ recorder.record({"event": "training_phase_return", "phase": phase,+ "elapsed_seconds": time.perf_counter() - started})+ recorder.phase = "selection_complete" if phase == "selection" else "lora_export"+ return result++ def calibration_records(model, *args, **kwargs):+ runtime.require_sdpa_fp32(model)+ torch.cuda.synchronize()+ torch.cuda.reset_peak_memory_stats()+ started = time.perf_counter()+ result = original_records(model, *args, **kwargs)+ torch.cuda.synchronize()+ recorder.record({"event": "reference_validation", "phase": recorder.phase,+ "elapsed_seconds": time.perf_counter() - started, "decision_items": len(result),+ "attention": "sdpa", "dtype": "float32", "autocast": False,+ "peak_allocated_bytes": torch.cuda.max_memory_allocated(),+ "peak_reserved_bytes": torch.cuda.max_memory_reserved()})+ return result++ def select_epoch(history):+ selected = original_select(history)+ recorder.record({"event": "development_selection", "selected_epoch": selected,+ "candidate_epochs": [r["epoch"] for r in history]})+ recorder.phase = "base_export"+ return selected++ lt.train_model, lt.calibration_records, reference.select_epoch = train_model, calibration_records, select_epoch+ try:+ yield+ finally:+ lt.train_model, lt.calibration_records, reference.select_epoch = original_train, original_records, original_select+++def prepare(run):+ run = Path(run)+ protocol.checked_reference()+ plan, _ = reference.core.checked_plan(run)+ os.environ.update(TORCH_COMPILE_DISABLE="1", TORCHDYNAMO_DISABLE="1")+ inventory = protocol.runtime_inventory()+ recipe = protocol.manifest(reference.core.sha(run / "plan.json"), inventory)+ reference.core.write(run / "fast-recipe.json", recipe)+ recorder = Recorder(run / "fast-runtime")+ return run, plan, recipe, recorder+++def train(run, training_grades, development_grades, initial_checkpoint, *, commit=lambda: None):+ run, plan, recipe, recorder = prepare(run)+ out = run / "native"+ if out.exists():+ raise ValueError("Use a new run directory; native outputs already exist")++ def persist():+ recipe_path = out / "fast-recipe.json"+ if not recipe_path.exists():+ shutil.copyfile(run / "fast-recipe.json", recipe_path)+ binding = {"runtime_recipe_id": protocol.RECIPE_ID, "fast_recipe_sha256": protocol.sha(recipe_path),+ "reference_plan_sha256": recipe["reference_plan_sha256"],+ "fast_implementation_sources_sha256": recipe["implementation_sources_sha256"]}+ start_path = out / "training-start.json"+ if start_path.exists():+ start = reference.core.read(start_path)+ if "runtime_recipe_id" not in start:+ shutil.copyfile(start_path, out / "training-start.reference.json")+ start["reference_native_config"] = start.pop("config")+ start["config"] = dict(plan["native"], **protocol.EFFECTIVE)+ start.update(binding)+ replace_json(start_path, start)+ for name in ("selection-config.json", "refit-config.json"):+ path = out / name+ if path.exists():+ config = reference.core.read(path)+ if config["gradient_checkpointing"]:+ backup = path.with_name(path.stem + ".reference.json")+ if not backup.exists():+ shutil.copyfile(path, backup)+ config["gradient_checkpointing"] = False+ replace_json(path, config)+ runtime_path = out / "fast-runtime.json"+ replace_json(runtime_path, recorder.snapshot())+ trained_path = out / "trained.json"+ if trained_path.exists():+ trained = reference.core.read(trained_path)+ trained.update(binding, format="bbeh-paired-native-fast-v1", fast_runtime_sha256=protocol.sha(runtime_path),+ reference_training_start_sha256=protocol.sha(out / "training-start.reference.json"),+ training_start_sha256=protocol.sha(start_path),+ runtime_recipe_scope="New implementation; historical plan is the source/population reference")+ replace_json(trained_path, trained)+ elif (out / "base-export.json").exists() and recorder.phase == "base_export":+ recorder.record({"event": "base_export_complete"})+ recorder.phase = "lora_export"+ commit()++ try:+ with fast_execution(recorder):+ reference.train(run, training_grades, development_grades, initial_checkpoint, commit=persist)+ persist()+ except BaseException as error:+ recorder.record({"event": "failure", "error_type": type(error).__name__, "error": str(error)})+ if out.exists():+ persist()+ raise+ return reference.core.read(out / "trained.json")+++def memory_probe(run, initial_checkpoint, lengths_path, output):+ run = Path(run)+ protocol.checked_reference()+ inventory = protocol.runtime_inventory()+ recorder = Recorder(Path(output).parent / "fast-memory-runtime")+ with fast_execution(recorder):+ receipt = reference.memory_probe(run, initial_checkpoint, lengths_path, output)+ receipt.update(format="laya-fast-memory-probe-v1", runtime_recipe_id=protocol.RECIPE_ID,+ gradient_checkpointing=False, training_attention="flash_attention_2",+ validation_attention="sdpa", validation_dtype="float32", runtime=inventory,+ runtime_measurements=recorder.snapshot())+ replace_json(output, receipt)+ return receipt+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--run", type=Path, required=True)+ parser.add_argument("--training-grades", type=Path, required=True)+ parser.add_argument("--development-grades", type=Path, required=True)+ parser.add_argument("--initial-checkpoint", type=Path, required=True)+ args = parser.parse_args()+ result = train(args.run, args.training_grades, args.development_grades, args.initial_checkpoint)+ print(json.dumps({key: result[key] for key in ("format", "runtime_recipe_id", "selected_epoch", "elapsed_seconds")}))+++if __name__ == "__main__":+ main()diff --git a/examples/train-a-router/router.py b/examples/train-a-router/router.pyindex 599e9540e..e9076332d 100644--- a/examples/train-a-router/router.py+++ b/examples/train-a-router/router.py@@ -16,6 +16,7 @@ def parser():c = commands.add_parser("fetch", help="Download and verify the pinned public data; add weights for Laya")c.add_argument("--output", type=Path, required=True)c.add_argument("--group", choices=("core", "weights", "recordings"), action="append")+ c.add_argument("--release", type=Path, help="Alternate pinned result package; defaults to the main dataset")for name, help_text in (("prepare", "Create a fresh reproduction run from the supplied dataset"),("base", "Apply unchanged Laya before training; CPU or CUDA"),@@ -30,6 +31,9 @@ def parser():c = commands.add_parser(name, help=help_text)c.add_argument("--data", type=Path, required=True)c.add_argument("--run", type=Path, required=True)+ if name == "fit-native":+ c.add_argument("--recipe", choices=("reference", "fast"), default="reference",+ help="reference reproduces the published training; fast uses the GPU environment")if name in {"base", "score"}:c.add_argument("--device", choices=("cpu", "cuda"), default="cpu" if name == "base" else "cuda")if name in {"fit-embedding", "score"}:@@ -71,13 +75,13 @@ def parser():def execute(a):if a.command == "fetch":- return workflow.fetch(a.output, a.group or ["core"])+ return workflow.fetch(a.output, a.group or ["core"], release_path=a.release)if a.command == "prepare":return workflow.prepare(a.data, a.run)if a.command == "base":return workflow.base(a.data, a.run, a.device)if a.command == "fit-native":- return workflow.fit_native(a.data, a.run)+ return workflow.fit_native(a.data, a.run, recipe=a.recipe)if a.command == "fit-embedding":return workflow.fit_embedding(a.data, a.run, a.features)if a.command == "score":diff --git a/examples/train-a-router/test_fast_native.py b/examples/train-a-router/test_fast_native.pynew file mode 100644index 000000000..ea6a76543--- /dev/null+++ b/examples/train-a-router/test_fast_native.py@@ -0,0 +1,150 @@+"""Small runtime-contract checks without model downloads, CUDA or real outcomes."""++import contextlib+import copy+import importlib+import random+import sys+import tempfile+import types+import unittest+from pathlib import Path+from unittest.mock import patch++NATIVE = Path(__file__).parent / "native"+sys.path.insert(0, str(NATIVE))+protocol = importlib.import_module("fast_protocol")+runtime = importlib.import_module("fast_runtime")+fast = importlib.import_module("fast_train")+sys.path.pop(0)+++class BatchTests(unittest.TestCase):+ def test_membership_and_partial_tail_weighting(self):+ for count in (1, 2, 4, 5, 13, 16, 18, 28, 31, 32, 67):+ items = [{"id": i, "ids": [0] * (19 - i % 17)} for i in range(count)]+ original = copy.deepcopy(items)+ windows = list(runtime.grouped_windows(items))+ self.assertEqual(items, original)+ for index, window in enumerate(windows):+ expected = original[index * 16:(index + 1) * 16]+ self.assertEqual(sorted(x["id"] for x in window), [x["id"] for x in expected])+ if len(expected) % 4:+ self.assertEqual(window, expected)+ else:+ self.assertEqual([len(x["ids"]) for x in window], sorted(len(x["ids"]) for x in expected))++ def test_option_rng_remains_assigned_to_original_examples_across_epochs(self):+ config = types.SimpleNamespace(seed=89, shuffle_options=("choice",))+ items = [{"id": i, "length": 2 + (i * 7) % 23} for i in range(35)]++ def draw(item, rng, kinds):+ options = ["incorrect", "correct"]+ rng.shuffle(options)+ return options++ def encode(tokenizer, item, maximum, head, options, parallel):+ return {"id": item["id"], "ids": [0] * item["length"], "options": options}++ lt = types.SimpleNamespace(encode_item=encode, draw_option_order=draw)+ expected_rng, actual_rng = random.Random(89), random.Random(89)+ for epoch in range(3):+ order = list(items)+ random.Random(89 + epoch).shuffle(order)+ expected = {x["id"]: draw(x, expected_rng, config.shuffle_options) for x in order}+ encoded = runtime.encoded_epoch(lt, None, items, config, epoch, actual_rng, 8192, 256)+ grouped = [x for w in runtime.grouped_windows(encoded) for x in w]+ self.assertEqual({x["id"]: x["options"] for x in grouped}, expected)+ self.assertEqual(actual_rng.getstate(), expected_rng.getstate())+++class ProvenanceTests(unittest.TestCase):+ def test_reference_source_change_fails_closed(self):+ self.assertEqual(protocol.checked_reference(), protocol.REFERENCE_FILES)+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ for name in protocol.REFERENCE_FILES:+ (root / name).write_bytes((NATIVE / name).read_bytes())+ with (root / "bbeh_native.py").open("a", encoding="utf-8") as stream:+ stream.write("\n# modified\n")+ with self.assertRaisesRegex(ValueError, "exact frozen"):+ protocol.checked_reference(root)++ def test_gpu_dependency_drift_fails_closed(self):+ with patch.object(protocol.importlib.metadata, "version", side_effect=lambda name: protocol.VERSIONS[name]):+ self.assertEqual(protocol.checked_versions(), protocol.VERSIONS)+ with patch.object(protocol.importlib.metadata, "version", return_value="different"), \+ self.assertRaisesRegex(ValueError, "pinned GPU"):+ protocol.checked_versions()++ def test_wrapper_binds_actual_runtime_and_preserves_reference_plan(self):+ with tempfile.TemporaryDirectory() as temporary:+ run = Path(temporary)+ core = fast.reference.core+ core.write(run / "plan.json", {"source": "unchanged"})+ original_plan = (run / "plan.json").read_bytes()+ plan = {"native": {"gradient_checkpointing": True}}+ recipe = protocol.manifest(core.sha(run / "plan.json"), {"synthetic": True})+ core.write(run / "fast-recipe.json", recipe)+ recorder = fast.Recorder(run / "fast-runtime")++ def original_train(root, training, development, checkpoint, *, commit):+ self.assertEqual((training, development), ("train.json", "development.json"))+ out = root / "native"+ out.mkdir()+ core.write(out / "training-start.json", {"config": plan["native"]})+ core.write(out / "selection-config.json", {"gradient_checkpointing": True})+ commit()+ self.assertFalse(core.read(out / "training-start.json")["config"]["gradient_checkpointing"])+ self.assertFalse(core.read(out / "selection-config.json")["gradient_checkpointing"])+ core.write(out / "trained.json", {"plan_sha256": core.sha(run / "plan.json"),+ "training_start_sha256": core.sha(out / "training-start.json")})+ commit()++ with patch.object(fast, "prepare", return_value=(run, plan, recipe, recorder)), \+ patch.object(fast, "fast_execution", return_value=contextlib.nullcontext()), \+ patch.object(fast.reference, "train", side_effect=original_train):+ trained = fast.train(run, "train.json", "development.json", "checkpoint")+ out = run / "native"+ self.assertEqual(trained["format"], "bbeh-paired-native-fast-v1")+ self.assertEqual(trained["fast_recipe_sha256"], core.sha(out / "fast-recipe.json"))+ self.assertEqual(trained["fast_runtime_sha256"], core.sha(out / "fast-runtime.json"))+ self.assertEqual(trained["training_start_sha256"], core.sha(out / "training-start.json"))+ self.assertEqual(trained["reference_training_start_sha256"], core.sha(out / "training-start.reference.json"))+ self.assertTrue(core.read(out / "training-start.reference.json")["config"]["gradient_checkpointing"])+ self.assertEqual((run / "plan.json").read_bytes(), original_plan)+++class HookTests(unittest.TestCase):+ def test_scoring_guard_and_hooks_restored_after_exception(self):+ lt = types.ModuleType("laya.train")+ original_train = lambda *a, **k: "original"+ original_records = lambda *a, **k: [1, 2]+ lt.train_model, lt.calibration_records = original_train, original_records+ laya = types.ModuleType("laya")+ laya.train = lt+ cuda = types.SimpleNamespace(synchronize=lambda: None, reset_peak_memory_stats=lambda: None,+ max_memory_allocated=lambda: 17, max_memory_reserved=lambda: 23)+ torch = types.ModuleType("torch")+ torch.cuda = cuda+ original_select = fast.reference.select_epoch+ with tempfile.TemporaryDirectory() as temporary, \+ patch.dict(sys.modules, {"laya": laya, "laya.train": lt, "torch": torch}), \+ patch.object(runtime, "require_sdpa_fp32") as checked, \+ patch.object(runtime, "train_model", return_value=[0.5]) as trained:+ recorder = fast.Recorder(Path(temporary) / "events")+ with self.assertRaisesRegex(RuntimeError, "deliberate"), fast.fast_execution(recorder):+ self.assertEqual(lt.train_model("model"), [0.5])+ self.assertEqual(trained.call_args.kwargs["phase"], "selection")+ self.assertEqual(lt.calibration_records("model"), [1, 2])+ checked.assert_called_once_with("model")+ self.assertEqual(recorder.events[-1]["attention"], "sdpa")+ self.assertFalse(recorder.events[-1]["autocast"])+ raise RuntimeError("deliberate")+ self.assertIs(lt.train_model, original_train)+ self.assertIs(lt.calibration_records, original_records)+ self.assertIs(fast.reference.select_epoch, original_select)+++if __name__ == "__main__":+ unittest.main()diff --git a/examples/train-a-router/test_training_comparison.py b/examples/train-a-router/test_training_comparison.pynew file mode 100644index 000000000..81f5e5a88--- /dev/null+++ b/examples/train-a-router/test_training_comparison.py@@ -0,0 +1,279 @@+"""Synthetic comparison checks: no models, providers or published answer data."""++import copy+import shutil+import tempfile+import unittest+from pathlib import Path+from unittest.mock import patch++import numpy as np++import training_comparison as comparison+import workflow+from embedding import recipes as core+from embedding.cost_iteration import refit+from evaluation import frontier+from test_workflow import make_run, replace_json+++def candidate(identifier, accuracy, cost, final_accuracy=0):+ return {+ "candidate_id": identifier, "policy": {"mode": "always_cheap"},+ "calibration": {"answer_accuracy_percent": accuracy, "answer_cost_usd_per10000": cost},+ "final": {"answer_accuracy_percent": final_accuracy},+ }+++def fixture(root):+ """Construct a small real source/score/calibration chain using synthetic rows."""+ run, plan, rows, grades, _ = make_run(root)+ data = root / "data"+ reference = data / "reference"+ reference.mkdir(parents=True)+ shutil.move(run, reference / "embedding")+ for role, path in grades.items():+ destination = data / f"grades/grades-{role}.json"+ destination.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(path, destination)+ template = core.read(grades["train"])+ for role in ("calibration", "final"):+ values = []+ for i, row in enumerate(rows[role]):+ values.append({**template["rows"][i], "id": row["id"],+ "cheap_cost_usd": "0.001", "strong_cost_usd": "0.010"})+ core.write(data / f"grades/grades-{role}.json", {**template, "role": role, "rows": values})+ core.write(data / "manifest.json", {"fixture": "synthetic-only"})+ core.write(data / "fees.json", {+ "source_plan_sha256": plan["source_plan_sha256"], "model": core.MODEL,+ "hf_revision": core.REVISION, "instruction": core.INSTRUCTION,+ "cost_basis": "validated_singleton_projection",+ "rows": [{"id": row["id"], "projected_singleton_usd": "0.00001"}+ for role_rows in rows.values() for row in role_rows],+ })+ native = root / "native-run"+ native_plan = {"populations": {role: [r["id"] for r in value] for role, value in rows.items()}}+ core.write(reference / "native/plan.json", native_plan)+ core.write(native / "plan.json", native_plan)+ source = root / "synthetic-source"+ implementations = {}+ for name in ("fast_protocol.py", "fast_runtime.py", "fast_train.py"):+ path = source / "native" / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(f"# Synthetic {name}\n", encoding="utf-8")+ implementations[name] = core.sha(path)+ recipe = {+ "format": "laya-fast-runtime-recipe-v1", "recipe_id": "laya-fa2-grouped-v1",+ "reference_plan_sha256": core.sha(native / "plan.json"),+ "implementation_sources_sha256": implementations, "final_outcomes_accessed": False,+ }+ core.write(native / "native/fast-recipe.json", recipe)+ core.write(native / "native/fast-runtime.json", {"fixture": "no-model-runtime"})+ trained = {+ "plan_sha256": core.sha(native / "plan.json"),+ "training_ids": native_plan["populations"]["train"] + native_plan["populations"]["development"],+ "selection_train_ids": native_plan["populations"]["train"],+ "selection_development_ids": native_plan["populations"]["development"],+ "training_grades_sha256": core.sha(data / "grades/grades-train.json"),+ "development_grades_sha256": core.sha(data / "grades/grades-development.json"),+ "fast_recipe_sha256": core.sha(native / "native/fast-recipe.json"),+ "fast_runtime_sha256": core.sha(native / "native/fast-runtime.json"),+ "fast_implementation_sources_sha256": implementations,+ "elapsed_seconds": 12, "selected_epoch": 3,+ }+ core.write(native / "native/trained.json", trained)+ core.write(reference / "native/native/trained.json", {"elapsed_seconds": 40, "selected_epoch": 2})+ paths = {}+ for role in ("calibration", "final"):+ embedding = core.read(reference / f"embedding/scores-{role}.json")+ method = {**embedding["methods"]["embedding"], "router_kind": "native"}+ old = {**embedding, "model_sha256": core.sha(reference / "native/native/trained.json"),+ "methods": {"base": method, "lora": copy.deepcopy(method)}}+ core.write(reference / f"native/native/scores-{role}.json", old)+ core.write(native / f"native/scores-{role}.json", {+ **old, "model_sha256": core.sha(native / "native/trained.json"),+ })+ cost = {+ "format": "bbeh-shared-input-cost-scores-v1", "role": role,+ "ids": embedding["ids"], "source_plan_sha256": plan["source_plan_sha256"],+ "pair_sha256": plan["pair_sha256"], "cost_model_sha256": "7" * 64,+ "promotion_sha256": refit.PROMOTION_SHA, "outcomes_accessed": False,+ "expected_usd": [[0.001, 0.010], [0.002, 0.020]],+ }+ core.write(reference / f"cost/costs-{role}.json", cost)+ paths[role] = []+ for prefix, original in (("", reference / f"embedding/scores-{role}.json"),+ ("native-", reference / f"native/native/scores-{role}.json")):+ output = reference / f"cost/{prefix}scores-{role}.json"+ refit.augment_files(original, reference / f"cost/costs-{role}.json", output,+ reference / f"cost/{prefix}combined-model.json")+ paths[role].append(output)+ calibration = frontier.calibrate(reference / "embedding", data / "grades/grades-calibration.json",+ paths["calibration"], data / "fees.json",+ reference / "calibration-frontiers.json")+ frontier.freeze(reference / "embedding", reference / "calibration-frontiers.json", paths["final"],+ data / "fees.json", reference / "frozen-frontiers.json")+ choices = {}+ for method in comparison.METHODS.values():+ choices[method] = {}+ for cap in comparison.CAPS:+ selected = comparison.choose(calibration["methods"][method]["frontier"], 100 * cap)+ choices[method][str(cap)] = None if selected is None else {+ key: selected[key] for key in ("candidate_id", "policy", "calibration")+ }+ core.write(data / "metadata/presentation-policies.json", {+ "calibration_sha256": core.sha(reference / "calibration-frontiers.json"),+ "frozen_sha256": core.sha(reference / "frozen-frontiers.json"),+ "illustrative_caps_fraction_of_always_strong_answer_cost": list(comparison.CAPS),+ "choices": choices,+ })+ return data, native, root / "comparison", source+++class CalibrationChoiceTests(unittest.TestCase):+ def test_only_calibration_metrics_choose_policy_with_deterministic_ties(self):+ points = [candidate(9, 80, 40, 100), candidate(8, 80, 30, 0),+ candidate(2, 80, 30, 1), candidate(1, 99, 41, 100)]+ self.assertEqual(comparison.choose(points, 40)["candidate_id"], 2)+ for point in points:+ point["final"]["answer_accuracy_percent"] = 100 - point["final"]["answer_accuracy_percent"]+ self.assertEqual(comparison.choose(points[::-1], 40)["candidate_id"], 2)++ def test_infeasible_budget_returns_no_policy_and_boundary_is_inclusive(self):+ points = [candidate(1, 70, 20)]+ self.assertIsNone(comparison.choose(points, 19.99))+ self.assertIsNone(comparison.choose([], 100))+ self.assertIs(comparison.choose(points, 20), points[0])+++class PairedDifferenceTests(unittest.TestCase):+ def test_identical_routes_have_exact_zero_deltas_and_intervals(self):+ rows = [{"task": "a", "family": str(i // 2)} for i in range(8)]+ y = np.array([[0, 1], [1, 0]] * 4)+ cost = np.array([[1, 3], [2, 4]] * 4)+ route = np.array([False, True] * 4)+ result = comparison.paired_differences(rows, y, cost, route, route.copy())+ for metric in result.values():+ self.assertEqual(metric["estimate"], 0)+ self.assertEqual(metric["ci95"], {"lower": 0, "upper": 0, "defined_draws": 2000, "total_draws": 2000})++ def test_delta_units_sign_and_family_resampling(self):+ rows = [{"task": "a", "family": str(i // 10)} for i in range(20)]+ y = np.array([[1, 0]] * 10 + [[0, 1]] * 10)+ cost = np.tile([1, 4], (20, 1))+ result = comparison.paired_differences(rows, y, cost, np.ones(20, bool), np.zeros(20, bool))+ self.assertEqual(result["accuracy_pp"]["estimate"], 0)+ self.assertEqual(result["accuracy_pp"]["ci95"]["lower"], -100)+ self.assertEqual(result["accuracy_pp"]["ci95"]["upper"], 100)+ self.assertEqual(result["answer_usd_per_10000"]["estimate"], -30000)+ self.assertEqual(result["answer_savings_pp"]["estimate"], 75)+ self.assertEqual(result["strong_share_pp"]["estimate"], -100)++ def test_observed_task_weights_are_fixed_and_zero_strong_cost_is_rejected(self):+ rows = [{"task": "a", "family": "a"}] * 3 + [{"task": "b", "family": "b"}]+ y = np.array([[1, 0]] * 3 + [[0, 1]])+ cost = np.tile([1, 4], (4, 1))+ result = comparison.paired_differences(rows, y, cost, np.ones(4, bool), np.zeros(4, bool))+ self.assertEqual(result["accuracy_pp"]["estimate"], 50)+ self.assertEqual(result["accuracy_pp"]["ci95"]["lower"], 50)+ self.assertEqual(result["accuracy_pp"]["ci95"]["upper"], 50)+ with self.assertRaisesRegex(ValueError, "always-Sol cost"):+ comparison.paired_differences(rows, y, np.zeros((4, 2)), np.ones(4, bool), np.zeros(4, bool))+++class ComparisonProvenanceTests(unittest.TestCase):+ def test_calibration_freezes_renamed_methods_without_reading_final_grades(self):+ with tempfile.TemporaryDirectory() as temporary:+ data, native, output, source = fixture(Path(temporary))+ read, reads = core.read, []++ def guarded(path):+ reads.append(str(path))+ self.assertNotEqual(Path(path).name, "grades-final.json")+ return read(path)++ with patch.object(workflow, "ROOT", source), patch.object(workflow, "checked_data", return_value=data), \+ patch.object(core, "read", side_effect=guarded):+ comparison.calibrate(data, native, output)+ frozen = read(output / "comparison-freeze.json")+ self.assertFalse(frozen["new_blind_evaluation"])+ self.assertFalse(frozen["final_outcomes_read_by_comparison"])+ self.assertEqual(len(frozen["choices"]), 8)+ prior = read(data / "reference/calibration-frontiers.json")+ current = read(output / "calibration-frontiers.json")+ for method, value in prior["methods"].items():+ self.assertEqual(current["methods"][method], value)+ self.assertEqual(set(current["methods"]) - set(prior["methods"]), set(comparison.METHODS))+ binding = read(output / "combined-model.json")+ self.assertEqual(binding["methods"], ["fast_lora"])+ self.assertEqual(binding["quality_model_sha256"], core.sha(native / "native/trained.json"))+ self.assertEqual(read(output / "cost-calibration.json")["model_sha256"], core.sha(output / "combined-model.json"))+ published_choices = read(data / "metadata/presentation-policies.json")["choices"]+ for choice in frozen["choices"]:+ self.assertEqual(choice["reference"], published_choices[choice["reference_method"]][str(choice["cap_fraction"])])+ self.assertTrue(any(path.endswith("scores-final.json") for path in reads))++ def test_changed_grade_source_runtime_or_score_model_is_rejected(self):+ for changed in ("grade", "source", "runtime", "score"):+ with self.subTest(changed=changed), tempfile.TemporaryDirectory() as temporary:+ data, native, _, source = fixture(Path(temporary))+ if changed == "grade":+ path = data / "grades/grades-train.json"+ value = core.read(path)+ value["rows"][0]["cheap_correct"] = 1 - value["rows"][0]["cheap_correct"]+ replace_json(path, value)+ elif changed == "source":+ (source / "native/fast_runtime.py").write_text("# Changed implementation\n", encoding="utf-8")+ elif changed == "runtime":+ replace_json(native / "native/fast-runtime.json", {"changed": True})+ else:+ path = native / "native/scores-final.json"+ value = core.read(path)+ value["model_sha256"] = "0" * 64+ replace_json(path, value)+ with patch.object(workflow, "ROOT", source), self.assertRaises(ValueError):+ comparison.checked_native(data, native)++ def test_existing_directory_is_preserved_and_source_drift_blocks_final_replay(self):+ with tempfile.TemporaryDirectory() as temporary:+ data, native, output, source = fixture(Path(temporary))+ with patch.object(workflow, "ROOT", source), patch.object(workflow, "checked_data", return_value=data):+ comparison.calibrate(data, native, output)+ before = {p.name: p.read_bytes() for p in output.iterdir() if p.is_file()}+ with self.assertRaisesRegex(ValueError, "new comparison directory"):+ comparison.calibrate(data, native, output)+ self.assertEqual(before, {p.name: p.read_bytes() for p in output.iterdir() if p.is_file()})+ path = output / "comparison-freeze.json"+ declaration = core.read(path)+ declaration["comparison_source_sha256"] = "0" * 64+ replace_json(path, declaration)+ with patch.object(frontier, "evaluate") as evaluated, self.assertRaisesRegex(ValueError, "Frozen comparison"):+ comparison.evaluate(data, output)+ evaluated.assert_not_called()++ def test_synthetic_replay_keeps_choices_and_zero_paired_difference_for_identical_model(self):+ with tempfile.TemporaryDirectory() as temporary:+ data, native, output, source = fixture(Path(temporary))+ with patch.object(workflow, "ROOT", source), patch.object(workflow, "checked_data", return_value=data), \+ patch.object(workflow, "invoke"):+ comparison.calibrate(data, native, output)+ saved = (output / "comparison-freeze.json").read_bytes()+ comparison.evaluate(data, output)+ self.assertEqual(saved, (output / "comparison-freeze.json").read_bytes())+ result = core.read(output / "comparison-report.json")+ self.assertEqual(result["n"], 2)+ self.assertFalse(result["new_blind_evaluation"])+ for row in result["comparisons"]:+ if not row.get("infeasible"):+ for value in row["candidate_minus_reference"].values():+ self.assertEqual(value["estimate"], 0)+ self.assertEqual(value["ci95"]["lower"], 0)+ self.assertEqual(value["ci95"]["upper"], 0)+ report = (output / "comparison-report.json").read_bytes()+ with self.assertRaises(FileExistsError):+ comparison.evaluate(data, output)+ self.assertEqual(report, (output / "comparison-report.json").read_bytes())+++if __name__ == "__main__":+ unittest.main()diff --git a/examples/train-a-router/training_comparison.py b/examples/train-a-router/training_comparison.pynew file mode 100644index 000000000..52123b666--- /dev/null+++ b/examples/train-a-router/training_comparison.py@@ -0,0 +1,239 @@+"""Compare a fast LoRA refit with the published recipe using the same cost models."""++from __future__ import annotations++import argparse+from pathlib import Path++import numpy as np++import workflow+from embedding import recipes as core+from embedding.cost_iteration import refit+from evaluation import frontier+from evaluation import utility_router as utility+from reader_runtime import ensure_utf8++METHODS = {"fast_lora": "lora", "fast_lora__textcost": "lora__textcost"}+CAPS = (0.2, 0.4, 0.6, 0.8)+++def choose(candidates, cap):+ """Choose from a calibration frontier, never from final measurements."""+ eligible = [p for p in candidates if p["calibration"]["answer_cost_usd_per10000"] <= cap]+ return min(eligible, key=lambda p: (+ -p["calibration"]["answer_accuracy_percent"],+ p["calibration"]["answer_cost_usd_per10000"], p["candidate_id"],+ )) if eligible else None+++def checked_native(data, native_run):+ reference = data / "reference/native"+ plan = core.read(reference / "plan.json")+ core.require(core.sha(native_run / "plan.json") == core.sha(reference / "plan.json"),+ "Fast run must use the published populations and scientific input plan")+ trained = core.read(native_run / "native/trained.json")+ recipe_path = native_run / "native/fast-recipe.json"+ recipe = core.read(recipe_path)+ implementations = {name: core.sha(workflow.ROOT / "native" / name)+ for name in ("fast_protocol.py", "fast_runtime.py", "fast_train.py")}+ core.require(+ trained["plan_sha256"] == core.sha(reference / "plan.json")+ and trained["training_ids"] == plan["populations"]["train"] + plan["populations"]["development"]+ and trained["selection_train_ids"] == plan["populations"]["train"]+ and trained["selection_development_ids"] == plan["populations"]["development"]+ and trained["training_grades_sha256"] == core.sha(data / "grades/grades-train.json")+ and trained["development_grades_sha256"] == core.sha(data / "grades/grades-development.json")+ and trained["fast_recipe_sha256"] == core.sha(recipe_path)+ and trained["fast_runtime_sha256"] == core.sha(native_run / "native/fast-runtime.json")+ and recipe["reference_plan_sha256"] == trained["plan_sha256"]+ and recipe["format"] == "laya-fast-runtime-recipe-v1"+ and recipe["recipe_id"] == "laya-fa2-grouped-v1"+ and recipe["implementation_sources_sha256"] == implementations+ and trained["fast_implementation_sources_sha256"] == implementations+ and recipe["final_outcomes_accessed"] is False,+ "Fast training provenance changed",+ )+ for role in ("calibration", "final"):+ score = core.read(native_run / f"native/scores-{role}.json")+ core.require(score["model_sha256"] == core.sha(native_run / "native/trained.json")+ and set(score["methods"]) == {"base", "lora"}, "Native scores belong to another model")+ return trained+++def calibrate(data, native_run, output, comparison_plan=None):+ """Freeze the comparison and its illustrated policies without final answer labels."""+ data, native_run, output = workflow.checked_data(data), Path(native_run).resolve(), Path(output).resolve()+ core.require(not output.exists(), "Use a new comparison directory")+ if comparison_plan is not None:+ declaration = core.read(comparison_plan)+ core.require(declaration["format"] == "laya-fast-post-publication-comparison-v1"+ and declaration["reference"]["manifest_sha256"] == core.sha(data / "manifest.json")+ and tuple(declaration["comparison"]["illustrations"][+ "fractions_of_always_strong_calibration_answer_cost"]) == CAPS,+ "Comparison plan uses another study or budget choices")+ trained = checked_native(data, native_run)+ reference = data / "reference"+ presentation = core.read(data / "metadata/presentation-policies.json")+ core.require(presentation["calibration_sha256"] == core.sha(reference / "calibration-frontiers.json")+ and presentation["frozen_sha256"] == core.sha(reference / "frozen-frontiers.json")+ and tuple(presentation["illustrative_caps_fraction_of_always_strong_answer_cost"]) == CAPS,+ "Published comparison choices changed")+ output.mkdir(parents=True)+ paths, base_drift = {}, {}+ for role in ("calibration", "final"):+ incoming = native_run / f"native/scores-{role}.json"+ score = core.read(incoming)+ old = core.read(reference / f"native/native/scores-{role}.json")+ core.require(score["ids"] == old["ids"], "Native score order changed")+ base_drift[role] = float(np.max(np.abs(+ np.asarray(score["methods"]["base"]["probabilities"])+ - np.asarray(old["methods"]["base"]["probabilities"]))))+ selected = {**score, "methods": {"fast_lora": score["methods"]["lora"]},+ "parent_scores_sha256": core.sha(incoming)}+ path = output / f"native-{role}.json"+ core.write(path, selected)+ augmented = output / f"cost-{role}.json"+ refit.augment_files(path, reference / f"cost/costs-{role}.json", augmented,+ output / "combined-model.json")+ paths[role] = [reference / f"cost/scores-{role}.json",+ reference / f"cost/native-scores-{role}.json", augmented]+ calibration_path, frozen_path = output / "calibration-frontiers.json", output / "frozen-frontiers.json"+ calibration = frontier.calibrate(reference / "embedding", data / "grades/grades-calibration.json",+ paths["calibration"], data / "fees.json", calibration_path)+ frontier.freeze(reference / "embedding", calibration_path, paths["final"], data / "fees.json", frozen_path)+ prior = core.read(reference / "calibration-frontiers.json")+ for method, value in prior["methods"].items():+ core.require(workflow.same_values(calibration["methods"][method], value), "Reference calibration changed")+ strong = next(p["calibration"]["answer_cost_usd_per10000"]+ for p in calibration["methods"]["lora"]["candidates"]+ if p["policy"]["mode"] == "always_strong")+ choices = []+ for method, original in METHODS.items():+ for fraction in CAPS:+ selected = choose(calibration["methods"][method]["frontier"], strong * fraction)+ choices.append({"method": method, "reference_method": original, "cap_fraction": fraction,+ "candidate": selected,+ "reference": presentation["choices"][original][str(fraction)]})+ core.write(output / "comparison-freeze.json", {+ "format": "laya-training-comparison-v1", "new_blind_evaluation": False,+ "final_outcomes_read_by_comparison": False, "choices": choices,+ "calibration_sha256": core.sha(calibration_path), "frozen_sha256": core.sha(frozen_path),+ "comparison_source_sha256": core.sha(__file__),+ "comparison_plan_sha256": core.sha(comparison_plan) if comparison_plan is not None else None,+ "reference_presentation_sha256": core.sha(data / "metadata/presentation-policies.json"),+ "dataset_manifest_sha256": core.sha(data / "manifest.json"),+ "fast_trained_sha256": core.sha(native_run / "native/trained.json"),+ "fast_recipe_sha256": trained["fast_recipe_sha256"],+ "reference_trained_sha256": core.sha(reference / "native/native/trained.json"),+ "base_max_probability_difference": base_drift,+ "timing": {"fast_fit_seconds": trained["elapsed_seconds"],+ "reference_fit_seconds": core.read(reference / "native/native/trained.json")["elapsed_seconds"],+ "fast_selected_epoch": trained["selected_epoch"],+ "reference_selected_epoch": core.read(reference / "native/native/trained.json")["selected_epoch"],+ "scope": "Full fit calls; dependency setup and input-only scoring are separate. Historical reference."},+ })+ return {"comparison": str(output), "frozen": True, "final_outcomes_read": False}+++def paired_differences(rows, y, costs, reference_routes, candidate_routes):+ """Resample both routes jointly, keeping families together and fixed task weights."""+ index = np.arange(len(y))+ reference_routes, candidate_routes = reference_routes.astype(int), candidate_routes.astype(int)+ values = np.column_stack((+ y[index, reference_routes], y[index, candidate_routes],+ costs[index, reference_routes], costs[index, candidate_routes],+ reference_routes, candidate_routes, costs[:, 1],+ ))++ def differences(means):+ return {+ "accuracy_pp": 100 * (means[..., 1] - means[..., 0]),+ "answer_usd_per_10000": 10000 * (means[..., 3] - means[..., 2]),+ "answer_savings_pp": 100 * (means[..., 2] - means[..., 3]) / means[..., 6],+ "strong_share_pp": 100 * (means[..., 5] - means[..., 4]),+ }++ core.require(np.all(costs[:, 1] >= 0) and costs[:, 1].mean() > 0, "Undefined always-Sol cost")+ point = differences(values.mean(axis=0))+ with np.errstate(divide="ignore", invalid="ignore"):+ draws = differences(frontier.Bootstrap(rows, 2000).means(values))+ return {name: {"estimate": float(value), "ci95": frontier.interval(draws[name])}+ for name, value in point.items()}+++def evaluate(data, output):+ """Replay frozen policies against already published answers; never select on them."""+ data, output = workflow.checked_data(data), Path(output).resolve()+ frozen_path = output / "frozen-frontiers.json"+ declaration = core.read(output / "comparison-freeze.json")+ core.require(declaration["format"] == "laya-training-comparison-v1"+ and declaration["comparison_source_sha256"] == core.sha(__file__)+ and declaration["dataset_manifest_sha256"] == core.sha(data / "manifest.json")+ and declaration["reference_presentation_sha256"]+ == core.sha(data / "metadata/presentation-policies.json")+ and declaration["frozen_sha256"] == core.sha(frozen_path)+ and declaration["calibration_sha256"] == core.sha(output / "calibration-frontiers.json")+ and declaration["new_blind_evaluation"] is False, "Frozen comparison changed")+ reference = data / "reference"+ final = frontier.evaluate(reference / "embedding", frozen_path, data / "grades/grades-final.json",+ output / "final-report.json")+ frozen = core.read(frozen_path)+ plan = core.checked_plan(reference / "embedding")+ rows = core.role_rows(reference / "embedding", plan, "final")+ y, costs, _ = core.grades(plan, rows, data / "grades/grades-final.json", "final")+ comparisons = []+ for choice in declaration["choices"]:+ if choice["candidate"] is None:+ comparisons.append({**choice, "infeasible": True})+ continue+ policies, measured = [], {}+ for kind, method in (("reference", choice["reference_method"]), ("candidate", choice["method"])):+ selected = choice[kind]+ method_data = frozen["methods"][method]+ saved = next(p for p in method_data["candidates"] if p["candidate_id"] == selected["candidate_id"])+ core.require(saved["policy"] == selected["policy"], "Illustrated policy changed")+ scores = method_data["scores"]+ policies.append(utility.replay(saved["policy"], scores["probabilities"], scores["expected_usd"]))+ measured[kind] = next(p for p in final["methods"][method]["points"]+ if p["candidate_id"] == selected["candidate_id"])+ comparisons.append({"method": choice["method"], "cap_fraction": choice["cap_fraction"],+ **measured, "candidate_minus_reference": paired_differences(rows, y, costs, *policies)})+ summary = {"format": "laya-training-comparison-report-v1", "new_blind_evaluation": False,+ "comparison_freeze_sha256": core.sha(output / "comparison-freeze.json"),+ "comparison_plan_sha256": declaration["comparison_plan_sha256"],+ "reference_presentation_sha256": declaration["reference_presentation_sha256"],+ "final_report_sha256": core.sha(output / "final-report.json"), "n": len(rows),+ "timing": declaration["timing"], "comparisons": comparisons,+ "interval_scope": "Pointwise paired family intervals conditional on tasks; not training-seed uncertainty.",+ "selection": "All illustrated budget choices were frozen on calibration before final replay.",+ "cost_scope": "Native answer-cost savings; hosting and one-time training are separate."}+ core.write(output / "comparison-report.json", summary)+ workflow.invoke("evaluation/report.py", "--calibration", output / "calibration-frontiers.json",+ "--frozen", frozen_path, "--final-report", output / "final-report.json",+ "--output", output / "explorer", "--reproduction")+ workflow.invoke("evaluation/source_sensitivity.py", "--run", reference / "embedding", "--frozen", frozen_path,+ "--grades", data / "grades/grades-final.json", "--primary", output / "final-report.json",+ "--specification", workflow.ROOT / "source-format-sensitivity.json",+ "--output", output / "source-format-sensitivity.json")+ return {"report": str(output / "comparison-report.json"), "open": str(output / "explorer/index.html")}+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("phase", choices=("calibrate", "evaluate"))+ parser.add_argument("--data", type=Path, required=True)+ parser.add_argument("--output", type=Path, required=True)+ parser.add_argument("--native-run", type=Path, help="The native directory inside your prepared run")+ parser.add_argument("--plan", type=Path, help="Optional predeclared validation plan to bind into the comparison")+ args = parser.parse_args()+ if args.phase == "calibrate":+ core.require(args.native_run is not None, "Calibration needs --native-run")+ calibrate(args.data, args.native_run, args.output, args.plan)+ else:+ evaluate(args.data, args.output)+++if __name__ == "__main__":+ ensure_utf8()+ main()diff --git a/examples/train-a-router/workflow.py b/examples/train-a-router/workflow.pyindex 61a977daa..2c90aabd5 100644--- a/examples/train-a-router/workflow.py+++ b/examples/train-a-router/workflow.py@@ -81,14 +81,18 @@ def fit_embedding(data, run, features=None):return {"selected": model["selected"], "timing": model["timing"], "run": str(run)}-def fit_native(data, run):+def fit_native(data, run, *, recipe="reference"):+ core.require(recipe in {"reference", "fast"}, "Choose the reference or fast training recipe")data, run = checked_run(data, run)- invoke("native/bbeh_native.py", "--phase", "train", "--run", run / "native",+ script = "native/fast_train.py" if recipe == "fast" else "native/bbeh_native.py"+ arguments = [] if recipe == "fast" else ["--phase", "train"]+ invoke(script, *arguments, "--run", run / "native","--training-grades", data / "grades/grades-train.json","--development-grades", data / "grades/grades-development.json","--initial-checkpoint", data / "reference/native/native/base")trained = core.read(run / "native/native/trained.json")- return {"selected_epoch": trained["selected_epoch"], "elapsed_seconds": trained["elapsed_seconds"]}+ return {"recipe": recipe, "selected_epoch": trained["selected_epoch"],+ "elapsed_seconds": trained["elapsed_seconds"]}def base(data, run, device):