Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c4a78d1134 | ||
|
|
cacae615e6 | ||
|
|
a9005aba8e | ||
|
|
788b9fdd1a | ||
|
|
abcf7c0acc | ||
|
|
26c967c6e3 | ||
|
|
7760531310 | ||
|
|
ce65f38fc0 | ||
|
|
1c45dc4572 | ||
|
|
4a80d747db | ||
|
|
8df2329a70 | ||
|
|
487d8a76d1 | ||
|
|
d05fe6de95 | ||
|
|
a563a03d61 | ||
|
|
de08c72769 | ||
|
|
7f811c01a8 | ||
|
|
2d6dc64efd | ||
|
|
07ebe34570 | ||
|
|
c1ac451e39 | ||
|
|
d5ed9fb7e4 | ||
|
|
b4a41d3f2c | ||
|
|
d7339fcf25 |
@@ -43,9 +43,9 @@ Namespaces are one honking great idea -- let's do more of those!
|
||||
|
||||
## Skills
|
||||
|
||||
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs). When you make changes to the codebase, check if any skills need to be updated to stay accurate.
|
||||
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs).
|
||||
|
||||
You are responsible for maintaining the skills folder. When a workflow fails and you fix it – whether with help from the user or through trial and error – you must update the skills to make implicit knowledge explicit. You are also responsible for keeping the skills up to date whenever you or anyone else modifies the code.
|
||||
If a repository skill could benefit from an update, suggest the specific change, explain why it would help, and ask the user for approval before making it. Wait for approval before creating, modifying, renaming, or deleting skills, including their supporting files and symlinks. If the user has already explicitly requested or approved the skill change, proceed without asking again. Requests to change code, fix workflows, update documentation, or open a PR do not implicitly authorize skill changes. You may read and follow skills without changing them.
|
||||
|
||||
## Testing
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
|
||||
5. Multi-node deployment with Slurm and Kubernetes support.
|
||||
6. Multimodal support for VLMs such as Qwen3-VL.
|
||||
7. Hackable, modular, and extensible by design.
|
||||
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/advanced/glm-5.2/).
|
||||
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/advanced/glm-5.3/).
|
||||
|
||||
|
||||
## Models support
|
||||
@@ -204,7 +204,7 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
|
||||
|
||||
1. [**Qwen3-30B-A3B**](examples/advanced/qwen3-30b-a3b/): Train `Qwen3-30B-A3B` on math, SWE, and agentic tool use.
|
||||
2. [**GLM-4.5-Air**](examples/advanced/glm-4.5-air/): Train `GLM-4.5-Air` on search, SWE, and terminal tasks.
|
||||
3. [**GLM-5**](examples/advanced/glm-5.2/): Large-scale `GLM-5`/`GLM-5.2` training with P/D disaggregation, the `llm-d` router, and FP8.
|
||||
3. [**GLM-5**](examples/advanced/glm-5.3/): Large-scale `GLM-5`/`GLM-5.3` training with P/D disaggregation, the `llm-d` router, and FP8.
|
||||
|
||||
## Docs
|
||||
|
||||
|
||||
@@ -135,5 +135,5 @@ FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
quantization = "fp8"
|
||||
quantization = "fp8_per_block"
|
||||
enable_return_routed_experts = true
|
||||
|
||||
Vendored
+1
-1
Submodule deps/verifiers updated: 5a69fb4d25...ceecc4d422
+1
-1
@@ -188,7 +188,7 @@ For large MoE serving, splitting prefill and decode onto separate vLLM groups ca
|
||||
| Agentic (SWE, Lean) | 3:1 | Long growing contexts → prefill-heavy |
|
||||
| Non-agentic (math, chat) | 1:2 | Short prompts, long generations → decode-heavy |
|
||||
|
||||
Example config: [`examples/advanced/glm-5.2/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-5.2/swe.toml) — full RL run on `GLM-5` with P/D disaggregation behind a `vllm-router`, FP8 inference, and NCCL weight broadcast, paired with an inference config from [`examples/advanced/glm-5.2/infer/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2/infer).
|
||||
Example config: [`examples/advanced/glm-5.3/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-5.3/swe.toml) — full RL run on `GLM-5` with P/D disaggregation behind a `vllm-router`, FP8 inference, and NCCL weight broadcast, paired with an inference config from [`examples/advanced/glm-5.3/infer/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3/infer).
|
||||
|
||||
Monitor live queue depths to detect imbalance:
|
||||
|
||||
|
||||
+2
-2
@@ -209,9 +209,9 @@ The knobs under `[trainer.loss]` are:
|
||||
|
||||
| Knob | Default | What it does |
|
||||
|---|---|---|
|
||||
| `eps` | 0.1 | Maximum absolute probability change before a token is masked. |
|
||||
| `eps` | 0.3 | Maximum absolute probability change before a token is masked. |
|
||||
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 to drop the policy-gradient term, leaving only the KL regularizer. |
|
||||
| `kl_tau` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
|
||||
| `kl_tau` | 0.0 | Temperature on the KL regularizer. Set to 0 to disable. |
|
||||
|
||||
Omit `[trainer.loss]` to use these defaults. Set `type = "ipo"` when you specify the section. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
|
||||
|
||||
|
||||
@@ -225,11 +225,11 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
|
||||
**Advanced** (32–2048 GPUs, SLURM):
|
||||
|
||||
- [**Qwen3-30B-A3B**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/qwen3-30b-a3b) — `Qwen3-30B-A3B` on math, SWE, and tool use.
|
||||
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal.
|
||||
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal; includes a variant that trains the 100B+ MoE on only two nodes.
|
||||
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
|
||||
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
|
||||
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/intellect-3.1) — reproduces our INTELLECT-3.1 training run.
|
||||
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation and FP8.
|
||||
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3) — large-scale `GLM-5`/`GLM-5.3` inference with P/D disaggregation and FP8.
|
||||
|
||||
### Worked Example: Compose, Override, Dry-Run
|
||||
|
||||
|
||||
+1
-1
@@ -89,7 +89,7 @@ Monitors receive the run's metrics and episodes through one abstraction. The fil
|
||||
|
||||
The file monitor writes the run's metrics and trace stream under `output_dir / run.name / monitors/file/` and feeds the local [dashboard](training.md#dashboard). Env servers stream every rollout to the eval process as it happens: the trace's header when it is minted, then one delta per committed turn (the new messages and the model call behind them), per phase change (boot, setup, agent, finalize, scoring), and a preview of each model request's uncommitted messages, so a tool result shows the moment the model is asked about it rather than with the reply. The file monitor appends those deltas to `monitors/file/traces/live/<trace_id>.jsonl` and deletes the file when the episode lands in the finished trace stream, so that directory is exactly the live set and finished traces stay where they always were. The dashboard's traces tab shows live rollouts in the episode table itself: a pulsing dot in the `#` cell marks the row, a phase badge says where the rollout is (boot, setup, running, finalize, scoring), the `dispatched → arrived` column shows the dispatch time with the elapsed time in brackets, and the turn, token and branch counts grow as deltas land. The status filter toggles live and completed rows, and a live row opens in the trace viewer, which follows the rollout turn by turn (the transcript stays pinned to the newest turn until you scroll up; folded entries stay folded; the pending messages of the request in flight render dimmed with an `awaiting model` chip). The table and an open live trace poll once a second and transfer nothing while the rollout is unchanged. The progress line in `eval.log` counts the live rollouts by phase (`2 inflight episodes ... - boot 1 · running 1`). Read a live trace from a shell with `uv run python -m prime_rl.monitors.file.traces <run_dir> [<trace_id>]`. The same stream exists for RL runs, covering train and online-eval rollouts alike.
|
||||
|
||||
The dashboard's metrics tab reads the trace stream directly. It shows one env at a time; the filter menu picks the env and whether errored episodes join the distributions. A block bar has one cell per expected episode: landed episodes (errored ones in red; click one to open it), live rollouts as pulsing outlines (click one to follow it), and the rest empty, with the percentage beside it. The expected count is what the eval runner wrote to `monitors/file/plan.json` when it counted the epoch's tasks. Below the bar, a summary row gives the headline numbers: avg@k and pass@k, the error and truncation rates (yellow past 10%, red past 50%), mean turns and branches in one tile, mean episode time and tokens, and the total cost when the run has costs; hover a tile for its distribution. The env's own rewards and metrics follow, a beeswarm pane each, resizable like the training charts. The usage section is one pane splitting each episode's tokens into input and output, and the timing section is the same pane over the phases of a rollout (boot, setup, model, harness, finalize, scoring, and `other` for wall time no phase accounts for): an icicle bar shows the mean split, one strip per episode below shows the split per rollout, and a legend sits above. Hovering a phase highlights it across the pane; the strips show 40 episodes by default and all of them on `show all`. A metric every episode shares appears as a chip instead of a pane, and a metric with only a few distinct values, such as a binary reward, as a counted dot plot with the count and share of each value. Every dot is an episode (or a task): hover it for its value and click it to open the trace; hover the pane's background for the summary (min, p10, median, p90, max), with a faint boxplot behind the dots. Errored episodes stay out of the distributions until the filter includes them, where they read red.
|
||||
The dashboard's overview tab reads the trace stream directly. It shows one env at a time; the filter menu picks the env and whether errored episodes join the distributions. A block bar has one cell per expected episode: landed episodes (errored ones in red; click one to open it), live rollouts as pulsing outlines (click one to follow it), and the rest empty, with the percentage beside it. The expected count is what the eval runner wrote to `monitors/file/plan.json` when it counted the epoch's tasks. Below the bar, a summary row gives the headline numbers: avg@k and pass@k, the error and truncation rates (yellow past 10%, red past 50%), mean turns and branches in one tile, mean episode time and tokens, and the total cost when the run has costs; hover a tile for its distribution. The env's own rewards and metrics follow, a beeswarm pane each, resizable like the training charts. The usage section is one pane splitting each episode's tokens into input and output, and the timing section is the same pane over the phases of a rollout (boot, setup, model, harness, finalize, scoring, and `other` for wall time no phase accounts for): an icicle bar shows the mean split, one strip per episode below shows the split per rollout, and a legend sits above. Hovering a phase highlights it across the pane; the strips show 40 episodes by default and all of them on `show all`. A metric every episode shares appears as a chip instead of a pane, and a metric with only a few distinct values, such as a binary reward, as a counted dot plot with the count and share of each value. Every dot is an episode (or a task): hover it for its value and click it to open the trace; hover the pane's background for the summary (min, p10, median, p90, max), with a faint boxplot behind the dots. Errored episodes stay out of the distributions until the filter includes them, where they read red. The metrics tab charts every key of the run's `metrics.jsonl`: the epoch's `eval/<env>/…` summaries and the time-keyed `inference/` and `concurrency/` rows the runner samples while the epoch is in flight.
|
||||
|
||||
### Prime
|
||||
|
||||
|
||||
+4
-2
@@ -190,8 +190,10 @@ Both backends support the 2 most important things:
|
||||
- P/D disaggregation - handling the prefill and decode stages separately
|
||||
|
||||
### Routing policies
|
||||
The 2 policies you might want to configure are:
|
||||
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - it hashes the `X-Session-ID` request header (sent per rollout by the verifiers clients) to pick a replica.
|
||||
The policies you might want to configure are:
|
||||
- `sticky_least_loaded` - the default policy. A new `X-Session-ID` is assigned to the least-loaded replica, then every later turn in that rollout remains on the same replica for KV cache reuse. The orchestrator releases sessions when rollouts complete, fail, or are cancelled, including traces discarded during retries. Failed release requests are logged without disabling future cleanup.
|
||||
|
||||
- `consistent_hash` - hashes the `X-Session-ID` request header (sent per rollout by the verifiers clients) to pick a replica, preserving KV cache reuse without considering current load.
|
||||
|
||||
- `round_robin` - this policy will round-robin the requests between the available replicas. This is useful if you want to balance the load between the replicas. This might give you better results if you don't have enough rollouts to make `consistent_hash` hashing saturated.
|
||||
|
||||
|
||||
+2
-1
@@ -233,7 +233,8 @@ gpus_per_node = 8
|
||||
Full multi-node configs ship under [`examples/advanced/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced):
|
||||
|
||||
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/configs/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
|
||||
- [`glm-5.2/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale and P/D-disaggregated inference across the GLM-5 family.
|
||||
- [`glm-5.3/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3) — large-scale and P/D-disaggregated inference across the GLM-5 family.
|
||||
- [`glm-4.5-air/swe-2-node.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-4.5-air/swe-2-node.toml) — train a 100B+ MoE on only two nodes: a single-node sign-SGD trainer (full optimizer offload) paired with one inference replica at batch size 64. An overlay on the shared `swe-budget.toml` base — launch with `uv run rl @ swe-budget.toml @ swe-2-node.toml`.
|
||||
|
||||
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
|
||||
|
||||
|
||||
+1
-1
@@ -355,7 +355,7 @@ tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
|
||||
|
||||
### Dashboard
|
||||
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from the file monitor's `metrics.jsonl`), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. The trace viewer separates the transcript, the wall-clock timeline of physical prefix branches, a wall-clock terminal replay of model and tool activity, and a top-to-bottom semantic graph of labeled model-call relationships. Replay uses recorded model-call and message timestamps; because providers do not persist per-token timestamps, it reveals response text evenly across the measured call span and labels that cadence as inferred. Agent and context labels in the semantic graph show the latest and peak prompt lengths first, with cumulative token processing available below on hover and click. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with six views per run: an overview (the W&B overview sections, read from the file monitor's `metrics.jsonl`), metrics (every key in that file, one pane each, with a regex filter), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. The trace viewer separates the transcript, the wall-clock timeline of physical prefix branches, a wall-clock terminal replay of model and tool activity, and a top-to-bottom semantic graph of labeled model-call relationships. Replay uses recorded model-call and message timestamps; because providers do not persist per-token timestamps, it reveals response text evenly across the measured call span and labels that cadence as inferred. Agent and context labels in the semantic graph show the latest and peak prompt lengths first, with cumulative token processing available below on hover and click. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
|
||||
|
||||
A coding agent on the same machine can drive the open dashboard: `POST /api/view` with an on-disk address (`{"run", "tab", "step", "kind", "subset", "episode", "highlight": [...]}`) navigates every connected tab there and paints quote-anchored highlights in the trace viewer. Reports cite traces with `[^id]` markers whose JSON definitions carry the same address plus a verbatim quote; the dashboard re-checks each quote against the trace files and marks the citation verified or broken, so answers stay grounded in what is actually on disk. The `dashboard` skill documents the full contract.
|
||||
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ Larger runs on frontier models, one folder per model, each with a launch README
|
||||
|
||||
- [`qwen3-30b-a3b/`](advanced/qwen3-30b-a3b/README.md) — `Qwen3-30B-A3B` RL on math (`i3_math`), SWE (`r2e-gym`), and agentic tool use (general-agent on Modal). 2 train + 2 infer nodes; the SWE config runs at 131k context with `ep = 8` + `cp = 2`.
|
||||
- [`glm-4.5-air/`](advanced/glm-4.5-air/README.md) — `GLM-4.5-Air` (100B MoE) RL across search, SWE, and terminal domains at 131k context, with agents in sandboxes. 2 train + 4 infer nodes (SWE: 1 + 3).
|
||||
- [`glm-5.2/`](advanced/glm-5.2/README.md) — the GLM-5 family at scale: 16 trainer nodes, P/D-disaggregated FP8 inference, and an llm-d router + Mooncake KV-offload variant. Also ships standalone `infer/` pre-flights.
|
||||
- [`glm-5.3/`](advanced/glm-5.3/README.md) — the GLM-5 family at scale: 16 trainer nodes, P/D-disaggregated FP8 inference, and an llm-d router + Mooncake KV-offload variant. Also ships standalone `infer/` pre-flights.
|
||||
- `intellect-3.1/` — reproduce the `INTELLECT-3.1` run: 4 train + 12 infer nodes on SWE.
|
||||
|
||||
All advanced configs submit through SLURM (the `rl` entrypoint writes the sbatch job when the config has a `[slurm]` table) and are monitored with `uv run dashboard`. See the per-model README for the full walkthrough.
|
||||
|
||||
@@ -1,22 +1,25 @@
|
||||
# GLM-4.5-Air
|
||||
|
||||
RL on [`zai-org/GLM-4.5-Air`](https://huggingface.co/zai-org/GLM-4.5-Air) — a 100B MoE — at 131k context, across three agentic domains: web search, SWE, and terminal. Rollouts run in sandboxes ([Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — see [Requirements](#requirements) for using your own), driven either by the `rlm` agent harness (with its `search` skill, or ipython-only) or a plain `bash` harness. All three configs share the same recipe: GRPO with a linear length penalty on input tokens (and turns, for SWE/terminal), the custom MoE trainer implementation with `cp = 4` (ulysses) context parallelism, router replay, NCCL weight broadcast, checkpoints every 50 steps (`keep_last = 1`), and evals every 20 steps (including step 0).
|
||||
RL on [`zai-org/GLM-4.5-Air`](https://huggingface.co/zai-org/GLM-4.5-Air) — a 100B MoE — at 131k context, across three agentic domains: web search, SWE, and terminal. Rollouts run in sandboxes ([Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — see [Requirements](#requirements) for using your own), driven either by the `rlm` agent harness (with its `search` skill, or ipython-only) or a plain `bash` harness. All three configs share the same recipe: GRPO with a linear length penalty on input tokens (and turns, for SWE/terminal), the custom MoE trainer implementation with `cp = 4` (ulysses) context parallelism, router replay, NCCL weight broadcast, checkpoints every 50 steps (`keep_last = 1`), and evals every 20 steps (including step 0). The SWE configs also ship budget variants: `swe-4-node.toml` (1 train + 3 infer) and `swe-2-node.toml` — train a 100B+ MoE on only two nodes. Both are thin overlays on a shared `swe-budget.toml` base: the base holds the recipe, the overlay the topology, batch size, and per-run identity.
|
||||
|
||||
| Config | Trains on | Evals on | Topology |
|
||||
|---|---|---|---|
|
||||
| [`search.toml`](search.toml) | `openseeker` + `redsearcher` (search QA, `rlm` harness + `search` skill) | `browsecomp` (500 examples) | 2 train + 4 infer nodes |
|
||||
| [`swe.toml`](swe.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 3 infer nodes |
|
||||
| [`swe.toml`](swe.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 2 train + 4 infer nodes |
|
||||
| [`swe-budget.toml`](swe-budget.toml) + [`swe-4-node.toml`](swe-4-node.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 3 infer nodes |
|
||||
| [`swe-budget.toml`](swe-budget.toml) + [`swe-2-node.toml`](swe-2-node.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 1 infer node |
|
||||
| [`terminal.toml`](terminal.toml) | `tmax` (per-task Docker image, `rlm` ipython harness) | `swebench-verified` + `terminal-bench-2` (avg@4) | 2 train + 4 infer nodes |
|
||||
|
||||
Inference serves the bf16 checkpoint as-is (no quantization), with `tensor_parallel_size = 8`. `search.toml` and `terminal.toml` train with Muon on 2 nodes; `swe.toml` fits the trainer on a single node with full optimizer offload and the stateless sign-SGD optimizer. Search answers are scored by a reference judge (`Qwen/Qwen3-235B-A22B-Instruct-2507`).
|
||||
Inference serves the bf16 checkpoint as-is (no quantization), with `tensor_parallel_size = 8` (plus expert parallelism on `swe.toml`). `search.toml`, `swe.toml`, and `terminal.toml` train with Muon on 2 trainer nodes. The budget variants instead fit the trainer on a single node with full optimizer offload and the stateless sign-SGD optimizer; `swe-2-node.toml` cuts the batch size to 64 (4 groups of 16) to match the throughput of its single inference replica. They don't parse standalone: compose them left-to-right over `swe-budget.toml` (`uv run rl @ swe-budget.toml @ swe-2-node.toml`). Search answers are scored by a reference judge (`Qwen/Qwen3-235B-A22B-Instruct-2507`).
|
||||
|
||||
## Requirements
|
||||
|
||||
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
|
||||
- **Sandboxes.** Rollout and eval agents run in sandboxes. These configs are wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — if you use those, log the `prime` CLI in (it ships with prime-rl's dependencies), and each config's `slurm.pre_run_command` will clean up the run's orphaned sandboxes by label before launching:
|
||||
- **Sandboxes.** Rollout and eval agents run in sandboxes. These configs are wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. Install the `prime` CLI separately and log in. Each config's `slurm.pre_run_command` then cleans up the run's orphaned sandboxes by label before launch:
|
||||
|
||||
```bash
|
||||
uv run prime login # or: uv run prime config set-api-key <your-key>
|
||||
uv tool install prime
|
||||
prime login # or: prime config set-api-key <your-key>
|
||||
```
|
||||
|
||||
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend) and drop the `slurm.pre_run_command` cleanup line.
|
||||
@@ -54,7 +57,7 @@ uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
|
||||
--run.name glm45air-swe
|
||||
```
|
||||
|
||||
Swap `swe.toml` for `search.toml` or `terminal.toml` to run the other domains. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
|
||||
Swap `swe.toml` for `search.toml` or `terminal.toml` to run the other domains. For SWE on a smaller budget, compose a budget variant over its base: `uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-2-node.toml` trains the 100B+ MoE on only two nodes. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
|
||||
|
||||
## Monitor with the dashboard
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# Budget variant of swe.toml: train a 100B+ MoE on only two nodes (1 train + 1 infer replica) with
|
||||
# the single-node sign-SGD trainer. Overlay for swe-budget.toml — this file only carries the
|
||||
# deltas, so compose the two (left-to-right merge, see docs/configuration.md "TOML Composition"):
|
||||
#
|
||||
# uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-2-node.toml
|
||||
#
|
||||
# The batch size is 64 (4 groups of 16), matching the rollout throughput of the single inference
|
||||
# replica. The SLURM job name, sandbox cleanup label, and W&B run name are per-variant so the
|
||||
# budget variants can run side by side.
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-swe-2-node"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe-2-node" -y || true'
|
||||
|
||||
[deployment]
|
||||
num_infer_replicas = 1
|
||||
|
||||
[monitors.wandb]
|
||||
name = "glm45air-scaleswe-2-node"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 64
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "scaleswe"
|
||||
env.taskset.id = "scaleswe"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["glm45air-swe-2-node"]
|
||||
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["glm45air-swe-2-node"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
@@ -0,0 +1,42 @@
|
||||
# Budget variant of swe.toml: the same recipe on four nodes (1 train + 3 infer replicas, the
|
||||
# topology swe.toml used before the Muon switch) with the single-node sign-SGD trainer. Overlay for
|
||||
# swe-budget.toml — this file only carries the deltas, so compose the two (left-to-right merge, see
|
||||
# docs/configuration.md "TOML Composition"):
|
||||
#
|
||||
# uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-4-node.toml
|
||||
#
|
||||
# Batch size 256 (16 groups of 16) matches the rollout throughput of the three inference replicas.
|
||||
# The SLURM job name, sandbox cleanup label, and W&B run name are per-variant so the budget
|
||||
# variants can run side by side.
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-swe-4-node"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe-4-node" -y || true'
|
||||
|
||||
[deployment]
|
||||
num_infer_replicas = 3
|
||||
|
||||
[monitors.wandb]
|
||||
name = "glm45air-scaleswe-4-node"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "scaleswe"
|
||||
env.taskset.id = "scaleswe"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["glm45air-swe-4-node"]
|
||||
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["glm45air-swe-4-node"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
@@ -0,0 +1,114 @@
|
||||
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, bash harness on a prime sandbox
|
||||
# runtime; eval on SWE-Bench Verified. Shared base of the budget variants of swe.toml
|
||||
# (`swe-4-node.toml`, `swe-2-node.toml`): the pre-Muon recipe with the single-node sign-SGD
|
||||
# trainer, composed as `uv run rl @ swe-budget.toml @ <variant>.toml`. Router replay is enabled
|
||||
# (trainer.enable_router_replay replays the routed-expert decisions returned by inference via
|
||||
# enable_return_routed_experts) — GLM-4.5-Air is a glm4_moe model, which supports routed_experts.
|
||||
#
|
||||
# GRPO uses the linear length penalty with the input-token and turns coefficients set to 0.1. Each
|
||||
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
|
||||
# subtraction.
|
||||
#
|
||||
# Inference serves the bf16 checkpoint as-is (no quantization). The trainer fits on one node via
|
||||
# cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus the
|
||||
# memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
|
||||
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), and
|
||||
# skip-gather / skip-optimizer checkpointing. Concurrency is fully default: the controller derives
|
||||
# its start from the measured KV budget and adapts from there.
|
||||
#
|
||||
# The variant overlays on top of this base set the inference replica count and batch size, the
|
||||
# per-variant SLURM job name / sandbox cleanup label / W&B run name, and the train/eval sources
|
||||
# with their matching runtime labels.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
|
||||
# slow/contended shared-FS caches and FS lock deadlocks.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
partition = "all"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
|
||||
[monitors.wandb]
|
||||
project = "swe-ablations"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
|
||||
[resume]
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
optim_cpu_offload = false
|
||||
full_offload = true
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "sign_sgd"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.algo.length_penalty]
|
||||
type = "linear"
|
||||
num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.1
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
enable_return_routed_experts = true
|
||||
@@ -1,11 +1,11 @@
|
||||
# GLM-5 family at scale
|
||||
|
||||
Large-scale RL and serving for the GLM-5 family — `zai-org/GLM-5`, `GLM-5.1`, and `GLM-5.2-FP8` — at 131k context: 16 trainer nodes on the custom MoE implementation (expert parallelism; the llm-d variant adds context parallelism) and P/D-disaggregated FP8 inference. The `-llmd` variants front the inference plane with the [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy): its `active-request-scorer` load-balances in flight — instead of reacting to delayed metrics like the default `vllm-router` — which, combined with prefix-cache affinity for grouped rollouts, keeps prefill and decode ranks evenly loaded under RL's bursty request pattern. They also offload KV to a Mooncake distributed CPU pool (1TB per node by default).
|
||||
Large-scale RL and serving for the GLM-5 family — including `zai-org/GLM-5.3-BF16` for training and its `GLM-5.3` block-FP8 serving release — at 131k context: 16 trainer nodes on the custom MoE implementation (expert parallelism; the llm-d variant adds context parallelism) and P/D-disaggregated FP8 inference. The `-llmd` variants front the inference plane with the [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy): its `active-request-scorer` load-balances in flight — instead of reacting to delayed metrics like the default `vllm-router` — which, combined with prefix-cache affinity for grouped rollouts, keeps prefill and decode ranks evenly loaded under RL's bursty request pattern. They also offload KV to a Mooncake distributed CPU pool (1TB per node by default).
|
||||
|
||||
| Config | What it runs | Topology |
|
||||
|---|---|---|
|
||||
| [`swe.toml`](swe.toml) | GLM-5 RL plane: 16 train nodes, eval on `swebench-verified` every 20 steps, default vLLM router over 2 P/D replicas (4 prefill + 4 decode nodes each). Declares **no train source** — compose yours on top with an `[[orchestrator.train.source]]` overlay. | 16 train + 16 infer nodes |
|
||||
| [`swe-llmd.toml`](swe-llmd.toml) | Full-stack GLM-5.1 RL: trains on `r2e-gym` (`rlm` harness), FP8-quantized trainer (`deepgemm_fp8` MoE compute), llm-d router + Mooncake KV offload. | 16 train + 16 infer nodes |
|
||||
| [`swe-llmd.toml`](swe-llmd.toml) | Full-stack GLM-5.3 RL: trains on `r2e-gym` (`rlm` harness), FP8-quantized trainer (`deepgemm_fp8` MoE compute), llm-d router + Mooncake KV offload. | 16 train + 16 infer nodes |
|
||||
| [`infer/pd.toml`](infer/pd.toml) | Inference-only pre-flight: P/D-disaggregated `GLM-5-FP8`. | 6 infer nodes |
|
||||
| [`infer/pd-llmd.toml`](infer/pd-llmd.toml) | Inference-only pre-flight: `GLM-5.2-FP8` with llm-d + Mooncake. | 16 infer nodes |
|
||||
|
||||
@@ -13,10 +13,11 @@ Large-scale RL and serving for the GLM-5 family — `zai-org/GLM-5`, `GLM-5.1`,
|
||||
|
||||
- A Slurm cluster with 8-GPU nodes, a shared filesystem, and at least **32 nodes** (16 trainer + 16 inference) for the RL configs. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path. If you have fewer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` (llm-d variant) accordingly.
|
||||
- InfiniBand/RDMA NICs for the Mooncake KV pool (llm-d variants).
|
||||
- **Sandboxes.** Rollout and eval agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, log the `prime` CLI in — it ships with prime-rl's dependencies:
|
||||
- **Sandboxes.** Rollout and eval agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, install the `prime` CLI separately and log in:
|
||||
|
||||
```bash
|
||||
uv run prime login # or: uv run prime config set-api-key <your-key>
|
||||
uv tool install prime
|
||||
prime login # or: prime config set-api-key <your-key>
|
||||
```
|
||||
|
||||
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend).
|
||||
@@ -57,18 +58,18 @@ uv sync --all-extras --all-packages
|
||||
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
|
||||
|
||||
```bash
|
||||
# GLM-5.1 RL with llm-d + Mooncake (recommended)
|
||||
uv run rl @ examples/advanced/glm-5.2/swe-llmd.toml
|
||||
# GLM-5.3 RL with llm-d + Mooncake (recommended)
|
||||
uv run rl @ examples/advanced/glm-5.3/swe-llmd.toml
|
||||
|
||||
# GLM-5 base plane — compose your train source onto it
|
||||
uv run rl @ examples/advanced/glm-5.2/swe.toml @ my-train-source.toml
|
||||
uv run rl @ examples/advanced/glm-5.3/swe.toml @ my-train-source.toml
|
||||
```
|
||||
|
||||
The inference configs are standalone pre-flights: they serve the FP8 checkpoint through the same entrypoint the trainer uses (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster` included — never call `vllm serve` directly), and are a fast way to check that this cluster can serve the model at all before committing it to a run:
|
||||
|
||||
```bash
|
||||
uv run inference @ examples/advanced/glm-5.2/infer/pd.toml
|
||||
uv run inference @ examples/advanced/glm-5.2/infer/pd-llmd.toml
|
||||
uv run inference @ examples/advanced/glm-5.3/infer/pd.toml
|
||||
uv run inference @ examples/advanced/glm-5.3/infer/pd-llmd.toml
|
||||
```
|
||||
|
||||
## Monitor with the dashboard
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
# Step 3 / goal target. Topology mirrors the proven original glm5.1_llmd_inference
|
||||
# (job 348 succeeded): 8 prefill nodes (4 replicas x 2) + 8 decode nodes (1 replica).
|
||||
#
|
||||
# Launch: uv run inference @ examples/advanced/glm-5.2/infer/pd-llmd.toml
|
||||
# Launch: uv run inference @ examples/advanced/glm-5.3/infer/pd-llmd.toml
|
||||
|
||||
output_dir = "/shared/outputs/glm5.2-16node-llmd"
|
||||
|
||||
@@ -17,7 +17,6 @@ name = "base"
|
||||
type = "nccl"
|
||||
port = 29502
|
||||
timeout = 12000
|
||||
quantize_in_weight_transfer = true
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
@@ -69,7 +68,10 @@ non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
|
||||
"queue-scorer" = 3.0
|
||||
|
||||
[inference.vllm]
|
||||
model = "zai-org/GLM-5.1-FP8"
|
||||
# The trainer uses GLM-5.3-BF16; serve the official block-FP8 release.
|
||||
model = "zai-org/GLM-5.3"
|
||||
dtype = "bfloat16"
|
||||
quantization = "fp8_per_block"
|
||||
max_model_len = 131072
|
||||
tool_call_parser = "glm47"
|
||||
reasoning_parser = "glm45"
|
||||
@@ -86,7 +88,7 @@ partition = "all" # FILL IN: set to your cluster's partition
|
||||
dist_timeout_seconds = 1800
|
||||
|
||||
[trainer.model]
|
||||
name = "zai-org/GLM-5.1"
|
||||
name = "zai-org/GLM-5.3-BF16"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2" # ignored with GLM5
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
@@ -122,7 +124,7 @@ initial_inflight = 256
|
||||
max_inflight = 512
|
||||
|
||||
[orchestrator.model]
|
||||
name = "zai-org/GLM-5.1-FP8"
|
||||
name = "zai-org/GLM-5.3"
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-5.1"
|
||||
@@ -1,5 +1,8 @@
|
||||
seq_len = 131072
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-5.3-BF16"
|
||||
|
||||
[log]
|
||||
level = "debug"
|
||||
|
||||
@@ -10,7 +13,6 @@ project = "glm5-pd-disag"
|
||||
type = "nccl"
|
||||
port = 29502
|
||||
timeout = 12000
|
||||
quantize_in_weight_transfer = true
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
@@ -24,7 +26,9 @@ prefill_nodes_per_replica = 4
|
||||
decode_nodes_per_replica = 4
|
||||
|
||||
[inference.vllm]
|
||||
model = "zai-org/GLM-5-FP8"
|
||||
# Serve the shared BF16 checkpoint above with online per-block FP8 quantization.
|
||||
dtype = "bfloat16"
|
||||
quantization = "fp8_per_block"
|
||||
tool_call_parser = "glm47"
|
||||
gpu_memory_utilization = 0.80
|
||||
enable_expert_parallel = true
|
||||
@@ -39,7 +43,6 @@ interval = 100
|
||||
dist_timeout_seconds = 7200
|
||||
|
||||
[trainer.model]
|
||||
name = "zai-org/GLM-5"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2" # dsa is skipping flash attn anyway
|
||||
fused_lm_head_token_chunk_size = 2048
|
||||
@@ -70,8 +73,8 @@ max_off_policy_steps = 16
|
||||
initial_inflight = 4096
|
||||
max_inflight = 8192
|
||||
|
||||
[orchestrator.model]
|
||||
name = "zai-org/GLM-5-FP8"
|
||||
[orchestrator.renderer]
|
||||
name = "glm-5.1"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
@@ -13,10 +13,11 @@ RL on the 30B-A3B MoE across three domains: math, SWE, and agentic tool use. The
|
||||
## Requirements
|
||||
|
||||
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
|
||||
- **Sandboxes** (`swe.toml` only) — the SWE agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, log the `prime` CLI in (it ships with prime-rl's dependencies):
|
||||
- **Sandboxes** (`swe.toml` only) — the SWE agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, install the `prime` CLI separately and log in:
|
||||
|
||||
```bash
|
||||
uv run prime login # or: uv run prime config set-api-key <your-key>
|
||||
uv tool install prime
|
||||
prime login # or: prime config set-api-key <your-key>
|
||||
```
|
||||
|
||||
To run on your own infrastructure instead, swap `env.agent.runtime` on the source for a runtime your environments support (e.g. a local Docker backend).
|
||||
|
||||
@@ -38,6 +38,8 @@ All2AllBackend = Literal[
|
||||
"flashinfer_nvlink_two_sided",
|
||||
]
|
||||
|
||||
QuantizationType = Literal["fp8_per_block"]
|
||||
|
||||
|
||||
class VllmConfig(BaseConfig):
|
||||
"""Arguments forwarded to the vLLM server, under vLLM's own argument names
|
||||
@@ -105,7 +107,7 @@ class VllmConfig(BaseConfig):
|
||||
enable_prefix_caching: bool | None = None
|
||||
"""Enable prefix caching."""
|
||||
|
||||
quantization: str | None = None
|
||||
quantization: QuantizationType | None = None
|
||||
"""Online inference quantization method. If None, vLLM infers it from the checkpoint."""
|
||||
|
||||
enable_lora: bool = False
|
||||
@@ -303,8 +305,8 @@ class VllmRouterConfig(BaseConfig):
|
||||
|
||||
type: Literal["vllm-router"] = "vllm-router"
|
||||
|
||||
policy: str = "consistent_hash"
|
||||
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
|
||||
policy: str = "sticky_least_loaded"
|
||||
"""Routing policy. Defaults to session-affine least-loaded routing; alternatives include ``consistent_hash`` and ``round_robin``."""
|
||||
|
||||
|
||||
class LlmdRouterConfig(BaseConfig):
|
||||
|
||||
@@ -459,9 +459,6 @@ class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
port: int = 29501
|
||||
"""Port for the NCCL broadcast rendezvous."""
|
||||
|
||||
quantize_in_weight_transfer: bool = False
|
||||
"""Use kernel-format FP8 quantized NCCL transfer for weight updates."""
|
||||
|
||||
|
||||
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
|
||||
@@ -145,9 +145,6 @@ class SharedNCCLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
|
||||
port: int = 29501
|
||||
"""Port for NCCL weight broadcast."""
|
||||
|
||||
quantize_in_weight_transfer: bool = False
|
||||
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
|
||||
|
||||
|
||||
class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
@@ -368,22 +365,6 @@ class RLConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_quantize_in_weight_transfer(self):
|
||||
if not isinstance(self.weight_broadcast, SharedNCCLWeightBroadcastConfig):
|
||||
return self
|
||||
|
||||
if not self.weight_broadcast.quantize_in_weight_transfer:
|
||||
return self
|
||||
|
||||
if self.inference is None:
|
||||
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires an inference config.")
|
||||
|
||||
if self.trainer.model.impl != "custom":
|
||||
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires trainer.model.impl = 'custom'.")
|
||||
|
||||
return self
|
||||
|
||||
### Auto-setup shared configs (before sub-config construction)
|
||||
|
||||
@model_validator(mode="before")
|
||||
@@ -487,9 +468,7 @@ class RLConfig(BaseConfig):
|
||||
inference_world_size=inference_world_size,
|
||||
)
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
transport_config = dict(
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
transport_config = {}
|
||||
trainer_config_type = TrainerNCCLWeightBroadcastConfig
|
||||
orchestrator_config_type = OrchestratorNCCLWeightBroadcastConfig
|
||||
else:
|
||||
@@ -538,18 +517,9 @@ class RLConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_eplb_requires_quantized_weight_transfer(self):
|
||||
if self.inference is None or not self.inference.vllm.enable_eplb:
|
||||
return self
|
||||
|
||||
# TODO(matej): check if weight reloading works itself before supporting EPLB without quantized transfer.
|
||||
trainer_weight_broadcast = self.trainer.weight_broadcast
|
||||
if trainer_weight_broadcast.type != "nccl" or not trainer_weight_broadcast.quantize_in_weight_transfer:
|
||||
raise ValueError(
|
||||
"inference.vllm.enable_eplb requires weight_broadcast.type = 'nccl' and "
|
||||
"weight_broadcast.quantize_in_weight_transfer = true."
|
||||
)
|
||||
|
||||
def validate_eplb(self):
|
||||
if self.inference is not None and self.inference.vllm.enable_eplb:
|
||||
raise ValueError("inference.vllm.enable_eplb is not supported with RL weight updates.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -568,13 +568,13 @@ class CheckpointConfig(BaseConfig):
|
||||
|
||||
class IPOLossConfig(BaseConfig):
|
||||
type: Literal["ipo"] = "ipo"
|
||||
eps: float = Field(0.1, ge=0)
|
||||
eps: float = Field(0.3, ge=0)
|
||||
"""Maximum absolute probability change before a token is masked."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
kl_tau: float = Field(1e-3, ge=0)
|
||||
kl_tau: float = Field(0.0, ge=0)
|
||||
"""Temperature for the KL term."""
|
||||
|
||||
|
||||
@@ -645,9 +645,6 @@ class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
port: int = 29501
|
||||
"""Port for the NCCL broadcast rendezvous."""
|
||||
|
||||
quantize_in_weight_transfer: bool = False
|
||||
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
|
||||
|
||||
|
||||
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
|
||||
+4
-4
@@ -16,8 +16,8 @@ dependencies = [
|
||||
"transformers==5.6.2",
|
||||
"wandb>=0.26.1",
|
||||
"wandb-workspaces>=0.4.3",
|
||||
"prime>=0.6.19",
|
||||
"prime-runs[train]>=0.1.1",
|
||||
"prime-sandboxes>=0.3.0",
|
||||
"prime-runs[train]>=0.1.3",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
@@ -269,8 +269,8 @@ torchao = [
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "99e5f7e" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "0251105" }
|
||||
vllm-router = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
|
||||
@@ -9,10 +9,11 @@ description: Find, start, use, and stop the local run dashboard for metrics, con
|
||||
|
||||
What is not obvious from the UI:
|
||||
|
||||
- Overview and Metrics read the same `monitors/file/metrics.jsonl`. **Overview** is the curated view (the sections of the W&B overview: train, eval, stability, inference, performance). **Metrics** is every key in the file, one pane per key, sectioned by parent path (`Flat`) or as a tree of sections along the key path (`Nested`), with a regex filter; time-keyed rows (`inference/`, `concurrency/`, `dispatcher/`) chart against wall time.
|
||||
- Config and Logs default to `latest (attempt <n>)`; select an attempt to inspect an earlier launch. The Config view shows a copyable launch command.
|
||||
- Trace viewer views: **Transcript**, **Timeline** (wall-clock Gantt of prefix branches), **Replay** (the branch as a terminal session; response text is paced evenly across the recorded model-call span and labelled inferred; default 8×; **Skip inference** collapses model calls but keeps tool delays; **T** toggles thinking, never advertise Ctrl+T) and **Semantic** (`semantic_parents` as a causal graph of model calls; width reflects peak agent concurrency; unplaceable fragments show as unlinked). Traces without semantic parents disable Semantic.
|
||||
- Live rollouts appear in the traces table with a pulsing dot and a phase badge, and open in the viewer, which follows them (pinned to the newest turn until you scroll up; the request in flight's uncommitted messages render dimmed as `awaiting model`). They come from `monitors/file/traces/live/*.jsonl`, polled once a second.
|
||||
- For an eval run the metrics tab shows one env at a time (filter → env, `include errors`): a block progress bar (one cell per expected episode, from `monitors/file/plan.json`), summary tiles (avg@k, pass@k, error and truncation rate coloured >10% yellow / >50% red, turns / branches, episode time, tokens, cost), env metrics as dot plots or beeswarms (hover a dot for its episode, click to open it; hover the background for the quantiles), and usage / timing composition panes (icicle of the mean split over per-episode strips; `other` is wall time no phase accounts for; hover a part to dim the rest; 40 strips by default, `show all` for every one).
|
||||
- For an eval run the overview tab shows one env at a time (filter → env, `include errors`): a block progress bar (one cell per expected episode, from `monitors/file/plan.json`), summary tiles (avg@k, pass@k, error and truncation rate coloured >10% yellow / >50% red, turns / branches, episode time, tokens, cost), env metrics as dot plots or beeswarms (hover a dot for its episode, click to open it; hover the background for the quantiles), and usage / timing composition panes (icicle of the mean split over per-episode strips; `other` is wall time no phase accounts for; hover a part to dim the rest; 40 strips by default, `show all` for every one).
|
||||
- `view on platform` in the top bar links to the run on the Prime platform when `--monitors.prime` was on (`monitors/prime/run.json`); an eval's evaluation opens at epoch start, so the link is live from the first episode.
|
||||
- An eval reads `completed` once its stream is sealed by a clean exit; a crashed or interrupted one reads `stopped` after its files go quiet.
|
||||
|
||||
|
||||
@@ -74,7 +74,9 @@ uv run sft @ examples/basic/reverse-text/sft.toml --dry-run
|
||||
|
||||
## `inference` — vLLM server
|
||||
|
||||
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly. It starts a `vllm-router` on `server.port` (default 8000, the client-facing URL) fronting the engine on `backend_port` (default 8100); admin endpoints must target the engine port directly.
|
||||
Router session cleanup runs on successful, failed, and cancelled episodes, including discarded retry traces. Cleanup failures are logged per session and do not disable subsequent releases.
|
||||
|
||||
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly. It starts a `vllm-router` on `server.port` (default 8000, the client-facing URL) fronting the engine on `backend_port` (default 8100); admin endpoints must target the engine port directly. The default `sticky_least_loaded` policy keeps each rollout on one replica while assigning new sessions to the least-loaded replica; RL and SFT online eval automatically release completed sessions.
|
||||
|
||||
```bash
|
||||
uv run inference --vllm.model Qwen/Qwen3-0.6B
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# Dashboard
|
||||
|
||||
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
|
||||
directories (metrics, resolved configs, rollout traces, cited reports,
|
||||
component logs) at
|
||||
directories (a curated overview, every logged metric, resolved configs,
|
||||
rollout traces, cited reports, component logs) at
|
||||
http://localhost:7788. The trace viewer includes transcript, synchronized
|
||||
agent timeline, and terminal replay views; timeline activities open the
|
||||
corresponding transcript call. Needs the `dashboard` extra. Every instance also serves
|
||||
|
||||
@@ -37,6 +37,7 @@ from prime_rl.utils.process import set_proc_title
|
||||
try:
|
||||
import uvicorn
|
||||
from fastapi import FastAPI, HTTPException, Query
|
||||
from fastapi.middleware.gzip import GZipMiddleware
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
except ModuleNotFoundError as error: # the dashboard ships as an extra
|
||||
@@ -47,6 +48,7 @@ MASTER_LOGS = {"trainer.log", "orchestrator.log", "inference.log", "eval.log"}
|
||||
MAX_LOG_CHUNK = 2_000_000
|
||||
|
||||
app = FastAPI()
|
||||
app.add_middleware(GZipMiddleware, minimum_size=1000, compresslevel=1)
|
||||
output_dirs: list[Path] = [default_output_dir()]
|
||||
|
||||
# run id -> run dir, rebuilt on every /api/runs poll; ids are the run name,
|
||||
@@ -550,7 +552,7 @@ def read_report(run: str, file: str) -> dict:
|
||||
# ------------------------------------------------------------------------- metrics
|
||||
|
||||
|
||||
MAX_METRICS_CHUNK = 4 * 1024 * 1024
|
||||
MAX_METRICS_CHUNK = 16 * 1024 * 1024
|
||||
"""Per-response cap on /metrics: huge runs stream in chunks the client loops over,
|
||||
so the first charts paint long before a 100MB metrics.jsonl finishes loading."""
|
||||
|
||||
@@ -566,7 +568,9 @@ def read_metrics(run: str, offset: int = 0) -> dict:
|
||||
rows = []
|
||||
with path.open("rb") as f:
|
||||
f.seek(offset)
|
||||
data = f.read(MAX_METRICS_CHUNK)
|
||||
# Keep the first response small for quick initial chart rendering.
|
||||
chunk_size = 4 * 1024 * 1024 if offset == 0 else MAX_METRICS_CHUNK
|
||||
data = f.read(chunk_size)
|
||||
if data and b"\n" not in data: # a single line larger than the chunk
|
||||
data += f.readline()
|
||||
consumed = data.rfind(b"\n") + 1 # leave a partially-written last line for the next poll
|
||||
|
||||
@@ -26,13 +26,13 @@ const state = {
|
||||
runs: [],
|
||||
run: null,
|
||||
meta: null,
|
||||
tab: "metrics",
|
||||
tab: "overview",
|
||||
live: true,
|
||||
metrics: {
|
||||
loaded: false, offset: 0, byKey: new Map(),
|
||||
charts: [], renderedKeys: -1, timeKeys: new Set(), timeZero: null, maxStep: null,
|
||||
collapsedSections: new Set(prefs.collapsedSections ?? []),
|
||||
mode: prefs.metricsMode ?? "overview", search: prefs.metricsSearch ?? "",
|
||||
searches: { overview: prefs.overviewSearch ?? "", metrics: prefs.metricsSearch ?? "" },
|
||||
smooth: prefs.smooth ?? 1, paneMin: prefs.paneMin ?? 260, paneH: prefs.paneH ?? 150, includeErrors: prefs.includeErrors ?? false,
|
||||
allLayout: prefs.allLayout ?? "flat",
|
||||
paneOrder: prefs.paneOrder ?? {},
|
||||
@@ -177,16 +177,15 @@ async function toggleCompare(name, on) {
|
||||
renderMetricsBody();
|
||||
}
|
||||
|
||||
/* eval runs have one env and no steps: the step bar, kind/subset toggles, chart
|
||||
mode, and smoothing make no sense there */
|
||||
/* eval runs have one env and no steps: the step bar, kind/subset toggles and
|
||||
smoothing make no sense there, and the overview is the episode pane */
|
||||
function applyRunTypeControls() {
|
||||
const isEval = state.meta?.type === "eval";
|
||||
$("#metrics-mode").hidden = isEval;
|
||||
$("#metrics-filter-wrap").hidden = !isEval;
|
||||
$("#metrics-search").hidden = isEval;
|
||||
$("#metrics-collapse").hidden = isEval;
|
||||
$("#metrics-expand").hidden = isEval;
|
||||
$("#smooth-range").closest(".ctl").hidden = isEval;
|
||||
$("#overview-filter-wrap").hidden = !isEval;
|
||||
$("#overview-search").hidden = isEval;
|
||||
$("#overview-collapse").hidden = isEval;
|
||||
$("#overview-expand").hidden = isEval;
|
||||
$("#overview-smooth").closest(".ctl").hidden = isEval;
|
||||
$("#step-bar").hidden = isEval;
|
||||
// an eval run has no steps to switch between, so it is stream-only
|
||||
$("#trace-mode").hidden = isEval;
|
||||
@@ -332,7 +331,7 @@ function renderOverview() {
|
||||
["status", `<span class="badge st-${status}">${status}</span>`],
|
||||
["type", `<span class="val">${esc((meta.type ?? "n/a").toUpperCase())}</span>`],
|
||||
meta.type === "eval"
|
||||
? ["episodes", `<span class="val">${step != null ? step.toLocaleString() : "n/a"}</span>`]
|
||||
? ["episodes", `<span class="val">${state.metrics.evalCount.toLocaleString()}</span>`]
|
||||
: ["step", `<span class="val">${stepText}</span>`],
|
||||
["model", `<span class="val" title="${esc(meta.model ?? "")}">${esc(meta.model ?? "n/a")}</span>`],
|
||||
...(meta.type === "eval"
|
||||
@@ -372,9 +371,12 @@ async function activateTab(tab, force = false) {
|
||||
setActive("#tabs", "tab", tab);
|
||||
document.querySelectorAll("main > section").forEach((s) => (s.hidden = s.id !== `tab-${tab}`));
|
||||
updateHash();
|
||||
if (tab === "metrics") {
|
||||
if (isChartTab(tab)) {
|
||||
if (!state.metrics.loaded) await initMetrics();
|
||||
else if (state.live) await fetchMetrics();
|
||||
else {
|
||||
renderMetricsBody();
|
||||
if (state.live) await fetchMetrics();
|
||||
}
|
||||
}
|
||||
if (tab === "config" && !state.config.loaded) await initConfig();
|
||||
if (tab === "logs" && !state.logs.loaded) await initLogs();
|
||||
@@ -390,6 +392,36 @@ async function activateTab(tab, force = false) {
|
||||
|
||||
/* ---------------------------------------------------------------- metrics */
|
||||
|
||||
/* the overview and metrics tabs read one metric store and share one chart
|
||||
registry: the open tab owns the charts, so switching re-renders into its body.
|
||||
The overview is the curated view (for an eval run, the episode pane); metrics
|
||||
is every key in the file, sectioned by family */
|
||||
const CHART_VIEWS = {
|
||||
overview: { body: "#overview-body", status: "#overview-status", search: "#overview-search", mode: "overview" },
|
||||
metrics: { body: "#metrics-body", status: "#metrics-status", search: "#metrics-search", mode: "all" },
|
||||
};
|
||||
|
||||
function isChartTab(tab = state.tab) {
|
||||
return tab in CHART_VIEWS;
|
||||
}
|
||||
|
||||
function chartBodies() {
|
||||
return Object.values(CHART_VIEWS).map((view) => $(view.body));
|
||||
}
|
||||
|
||||
function chartView() {
|
||||
return CHART_VIEWS[state.tab] ?? CHART_VIEWS.overview;
|
||||
}
|
||||
|
||||
function metricsMode() {
|
||||
return chartView().mode;
|
||||
}
|
||||
|
||||
/* the eval overview is built from the episode series, not the metric rows */
|
||||
function rowsChartHere() {
|
||||
return isChartTab() && !(state.tab === "overview" && state.meta?.type === "eval");
|
||||
}
|
||||
|
||||
const COMMON_METRICS = ["effective/num_turns/mean", "effective/num_total_tokens/mean", "effective/num_branches/mean"];
|
||||
const COMMON_REGEXES = ["effective/[^/]+/is_truncated/mean", "all/[^/]+/has_error/mean"];
|
||||
const STABILITY_METRICS = ["optim/grad_norm", "entropy/all/mean", "mismatch_kl/all/mean", "kl_ent_ratio/mean"];
|
||||
@@ -406,8 +438,9 @@ const INFERENCE_PANELS = [
|
||||
["inference/agg/num_requests_running/mean", "inference/agg/num_requests_running/min", "inference/agg/num_requests_running/max"],
|
||||
["inference/agg/num_requests_waiting/mean", "inference/agg/num_requests_waiting/min", "inference/agg/num_requests_waiting/max"],
|
||||
["inference/agg/prefix_cache_hit_rate/pooled", "inference/agg/prefix_cache_hit_rate/min"],
|
||||
["inference/agg/generation_tokens_total:rate/sum", "inference/agg/generation_tokens_total:rate/min"],
|
||||
["inference/agg/prompt_tokens_total:rate/sum", "inference/agg/prompt_tokens_total:rate/max"],
|
||||
["inference/agg/generation_tokens_total:rate/sum"],
|
||||
["inference/agg/prompt_tokens_total:rate/sum"],
|
||||
["dispatcher/inflight/train", "dispatcher/inflight/eval", "concurrency/max_inflight"],
|
||||
];
|
||||
|
||||
const TRAINER_KEY_RE = /^(perf|optim|loss|entropy|system|mismatch_kl|kl_ent_ratio|is_masked|masked_|unmasked_|max_vio|routing_|ref_kl|val)[/_]?/;
|
||||
@@ -461,46 +494,52 @@ function ingestInto(store, rows, meta) {
|
||||
first charts paint immediately and a progress readout ticks up while the rest
|
||||
loads, with the main thread yielding between chunks */
|
||||
async function fetchMetrics() {
|
||||
if (state.meta?.type === "eval") return fetchEvalSeries();
|
||||
const m = state.metrics;
|
||||
if (m.fetching) return 0;
|
||||
m.fetching = true;
|
||||
let total = 0;
|
||||
let showedProgress = false;
|
||||
try {
|
||||
for (let first = true; ; first = false) {
|
||||
const requestedOffset = m.offset;
|
||||
const [data, compared] = await Promise.all([
|
||||
api(`/api/runs/${encodeURIComponent(state.run)}/metrics?offset=${m.offset}`),
|
||||
first ? fetchCompares() : false,
|
||||
]);
|
||||
if (state.metrics !== m) return total; // the run changed mid-load
|
||||
m.offset = data.offset;
|
||||
total += data.rows.length;
|
||||
let touched = null;
|
||||
if (data.rows.length) {
|
||||
touched = ingestInto(m, data.rows, state.meta);
|
||||
renderOverview();
|
||||
}
|
||||
if (data.rows.length || compared) {
|
||||
if (m.byKey.size !== m.renderedKeys) renderMetricsBody();
|
||||
else updateCharts(compared ? null : touched); // compares may touch any panel
|
||||
}
|
||||
// A writer can leave one incomplete JSONL record at EOF. Wait for the
|
||||
// next poll instead of repeatedly requesting the same partial record.
|
||||
if (data.offset >= (data.size ?? data.offset) || data.offset === requestedOffset) break;
|
||||
showedProgress = true;
|
||||
$("#metrics-status").textContent = `loading metrics · ${Math.round((data.offset / data.size) * 100)}%`;
|
||||
}
|
||||
if (showedProgress && m.mode === "overview") $("#metrics-status").textContent = "";
|
||||
if (state.meta?.type === "eval") await fetchEvalSeries();
|
||||
if (state.metrics !== m) return 0;
|
||||
return await fetchMetricRows(m);
|
||||
} finally {
|
||||
m.fetching = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchMetricRows(m) {
|
||||
let total = 0;
|
||||
let showedProgress = false;
|
||||
for (let first = true; ; first = false) {
|
||||
const requestedOffset = m.offset;
|
||||
const [data, compared] = await Promise.all([
|
||||
api(`/api/runs/${encodeURIComponent(state.run)}/metrics?offset=${m.offset}`),
|
||||
first ? fetchCompares() : false,
|
||||
]);
|
||||
if (state.metrics !== m) return total; // the run changed mid-load
|
||||
m.offset = data.offset;
|
||||
total += data.rows.length;
|
||||
let touched = null;
|
||||
if (data.rows.length) {
|
||||
touched = ingestInto(m, data.rows, state.meta);
|
||||
renderOverview();
|
||||
}
|
||||
if ((data.rows.length || compared) && rowsChartHere()) {
|
||||
if (m.byKey.size !== m.renderedKeys) renderMetricsBody();
|
||||
else updateCharts(compared ? null : touched); // compares may touch any panel
|
||||
}
|
||||
// A writer can leave one incomplete JSONL record at EOF. Wait for the
|
||||
// next poll instead of repeatedly requesting the same partial record.
|
||||
if (data.offset >= (data.size ?? data.offset) || data.offset === requestedOffset) break;
|
||||
if (!rowsChartHere()) continue;
|
||||
showedProgress = true;
|
||||
$(chartView().status).textContent = `loading metrics · ${Math.round((data.offset / data.size) * 100)}%`;
|
||||
}
|
||||
if (showedProgress && metricsMode() === "overview") $(chartView().status).textContent = "";
|
||||
return total;
|
||||
}
|
||||
|
||||
/* eval runs have no metrics.jsonl and no step axis — their metrics view is a
|
||||
grid of stat cards showing the running average over the episodes so far */
|
||||
/* an eval run's overview reads the episode series: the running distributions
|
||||
over the episodes so far */
|
||||
async function fetchEvalSeries() {
|
||||
const m = state.metrics;
|
||||
const liveChanged = await loadLive({ render: state.tab === "traces" });
|
||||
@@ -514,7 +553,7 @@ async function fetchEvalSeries() {
|
||||
data = { unchanged: true };
|
||||
}
|
||||
if (data.unchanged) {
|
||||
if (liveChanged && m.loaded && state.tab === "metrics") renderMetricsBody();
|
||||
if (liveChanged && m.loaded && state.tab === "overview") renderMetricsBody();
|
||||
return 0;
|
||||
}
|
||||
m.evalEtag = data.etag;
|
||||
@@ -527,11 +566,10 @@ async function fetchEvalSeries() {
|
||||
m.evalSeries[key] = existing;
|
||||
}
|
||||
m.evalCount = data.count;
|
||||
m.maxStep = data.count; // the overview's episode count
|
||||
const costs = (m.evalSeries.cost || []).filter((v) => v != null); // merged, not just the increment
|
||||
m.evalCost = costs.length ? costs.reduce((a, b) => a + b, 0) : null;
|
||||
renderOverview();
|
||||
if (m.loaded) renderMetricsBody();
|
||||
if (m.loaded && state.tab === "overview") renderMetricsBody();
|
||||
return data.count;
|
||||
}
|
||||
|
||||
@@ -556,8 +594,8 @@ function evalEnv() {
|
||||
function renderEvalEnvs() {
|
||||
const envs = evalEnvs();
|
||||
const current = evalEnv();
|
||||
$("#metrics-env-row").hidden = !envs.length;
|
||||
$("#metrics-env").innerHTML = envs.map((env) => `<option value="${esc(env)}" ${env === current ? "selected" : ""}>${esc(env)}</option>`).join("");
|
||||
$("#overview-env-row").hidden = !envs.length;
|
||||
$("#overview-env").innerHTML = envs.map((env) => `<option value="${esc(env)}" ${env === current ? "selected" : ""}>${esc(env)}</option>`).join("");
|
||||
syncDressedSelects();
|
||||
}
|
||||
|
||||
@@ -615,7 +653,7 @@ function evalProgressHtml(env, idx, live) {
|
||||
`<span class="ep-cell"></span>`.repeat(Math.max(0, EP_CELL_CAP - doneCells - liveCells));
|
||||
}
|
||||
// the toolbar line reads like the traces tab's
|
||||
$("#metrics-status").textContent = [...(live.length ? [`${live.length} live`] : []), `${fmtCompact(done)} completed episode${done === 1 ? "" : "s"}`].join(" · ");
|
||||
$("#overview-status").textContent = [...(live.length ? [`${live.length} live`] : []), `${fmtCompact(done)} completed episode${done === 1 ? "" : "s"}`].join(" · ");
|
||||
return (
|
||||
`<div class="eval-progress"><div class="ep-head"><span class="name">${esc(env)}</span></div>` +
|
||||
`<div class="ep-row"><div class="ep-blocks">${cells || `<span class="ep-cell"></span>`}</div>` +
|
||||
@@ -820,7 +858,7 @@ function swarmSvg(entry, W, H) {
|
||||
|
||||
/* swarms are drawn to their host's pixel size, so they redraw with the panes */
|
||||
function drawSwarms() {
|
||||
for (const card of document.querySelectorAll("#metrics-body .swarm-card")) {
|
||||
for (const card of document.querySelectorAll("#overview-body .swarm-card")) {
|
||||
const entry = swarmRegistry.get(card.dataset.key);
|
||||
const host = card.querySelector(".swarm-host");
|
||||
if (!entry || !host?.clientWidth) continue;
|
||||
@@ -1016,8 +1054,8 @@ function tokensPaneHtml(idx) {
|
||||
const TM_MAX_STRIPS = 40;
|
||||
|
||||
function drawTiming() {
|
||||
drawComposition(document.querySelector("#metrics-body .timing-pane"), timingModel, { kind: "timing", fmt: fmtDuration, time: true, color: phaseColor });
|
||||
drawComposition(document.querySelector("#metrics-body .tokens-pane"), tokensModel, { kind: "tokens", fmt: (v) => fmtCompact(Math.round(v)), time: false, color: (n) => TOKEN_COLORS[n] || "#3a3a3a" });
|
||||
drawComposition(document.querySelector("#overview-body .timing-pane"), timingModel, { kind: "timing", fmt: fmtDuration, time: true, color: phaseColor });
|
||||
drawComposition(document.querySelector("#overview-body .tokens-pane"), tokensModel, { kind: "tokens", fmt: (v) => fmtCompact(Math.round(v)), time: false, color: (n) => TOKEN_COLORS[n] || "#3a3a3a" });
|
||||
}
|
||||
|
||||
/* an icicle of the mean composition above one strip per episode; every segment
|
||||
@@ -1173,12 +1211,12 @@ function summaryTilesHtml(idx, all, scoreEntries) {
|
||||
function renderEvalPane(body) {
|
||||
const m = state.metrics;
|
||||
const series = m.evalSeries || {};
|
||||
const filter = makeFilter(m.search.trim());
|
||||
const filter = makeFilter(m.searches.overview.trim());
|
||||
renderEvalEnvs();
|
||||
const env = evalEnv();
|
||||
$("#metrics-status").textContent = "";
|
||||
$("#metrics-errors").checked = !!m.includeErrors;
|
||||
$("#metrics-filter-btn").classList.toggle("active", !!m.includeErrors);
|
||||
$("#overview-status").textContent = "";
|
||||
$("#overview-errors").checked = !!m.includeErrors;
|
||||
$("#overview-filter-btn").classList.toggle("active", !!m.includeErrors);
|
||||
swarmRegistry.clear();
|
||||
if (!env) {
|
||||
body.innerHTML = emptyState("no episodes yet", "metrics appear as episodes land");
|
||||
@@ -1250,19 +1288,19 @@ function renderEvalPane(body) {
|
||||
drawTiming();
|
||||
}
|
||||
|
||||
$("#metrics-errors").addEventListener("change", (e) => {
|
||||
$("#overview-errors").addEventListener("change", (e) => {
|
||||
state.metrics.includeErrors = e.target.checked;
|
||||
savePrefs();
|
||||
renderMetricsBody();
|
||||
});
|
||||
|
||||
$("#metrics-body").addEventListener("mousemove", (e) => {
|
||||
$("#overview-body").addEventListener("mousemove", (e) => {
|
||||
const tip = $("#swarm-tip");
|
||||
const timed = e.target.closest("[data-tip]");
|
||||
const pane = e.target.closest(".comp-pane");
|
||||
const rowEl = e.target.closest("[data-row]");
|
||||
const part = rowEl ? null : e.target.closest("[data-part]");
|
||||
document.querySelectorAll("#metrics-body .comp-pane").forEach((p) => {
|
||||
document.querySelectorAll("#overview-body .comp-pane").forEach((p) => {
|
||||
if (p === pane && rowEl) highlightRow(p, rowEl.dataset.row);
|
||||
else highlightPart(p, p === pane && part ? part.dataset.part : null);
|
||||
});
|
||||
@@ -1278,22 +1316,22 @@ $("#metrics-body").addEventListener("mousemove", (e) => {
|
||||
tip.innerHTML = swarmTipHtml(entry, dot ? entry.points[+dot.dataset.i] : null);
|
||||
}
|
||||
tip.hidden = false;
|
||||
const host = $("#tab-metrics").getBoundingClientRect();
|
||||
const host = $("#tab-overview").getBoundingClientRect();
|
||||
const left = Math.min(e.clientX - host.left + 12, host.width - tip.offsetWidth - 8);
|
||||
tip.style.left = `${Math.max(4, left)}px`;
|
||||
tip.style.top = `${e.clientY - host.top + 14}px`;
|
||||
});
|
||||
$("#metrics-body").addEventListener("mouseleave", () => {
|
||||
$("#overview-body").addEventListener("mouseleave", () => {
|
||||
$("#swarm-tip").hidden = true;
|
||||
document.querySelectorAll("#metrics-body .comp-pane").forEach((p) => highlightPart(p, null));
|
||||
document.querySelectorAll("#overview-body .comp-pane").forEach((p) => highlightPart(p, null));
|
||||
});
|
||||
|
||||
$("#metrics-env").addEventListener("change", (e) => {
|
||||
$("#overview-env").addEventListener("change", (e) => {
|
||||
state.metrics.evalEnv = e.target.value;
|
||||
renderMetricsBody();
|
||||
});
|
||||
|
||||
$("#metrics-body").addEventListener("click", (e) => {
|
||||
$("#overview-body").addEventListener("click", (e) => {
|
||||
const strip = e.target.closest(".tm-strip-seg[data-line], .tm-row-hit[data-line]");
|
||||
if (strip) {
|
||||
openEpisode(+strip.dataset.line);
|
||||
@@ -1804,7 +1842,7 @@ function panelTitle(panel, series, sectionName) {
|
||||
}
|
||||
if (sectionName && title.startsWith(`${sectionName}/`)) title = title.slice(sectionName.length + 1);
|
||||
// overview: a lone mean is implied - all mode keeps the stat next to its /min//p10 siblings
|
||||
if (state.metrics.mode === "overview" && title.endsWith("/mean")) title = title.slice(0, -"/mean".length);
|
||||
if (metricsMode() === "overview" && title.endsWith("/mean")) title = title.slice(0, -"/mean".length);
|
||||
return title;
|
||||
}
|
||||
|
||||
@@ -1850,7 +1888,7 @@ function renderPanelCard(grid, panel, lazy = false) {
|
||||
}
|
||||
|
||||
function paneOrderKey(sectionName) {
|
||||
return `${state.metrics.mode}:${sectionName ?? ""}`;
|
||||
return `${metricsMode()}:${sectionName ?? ""}`;
|
||||
}
|
||||
|
||||
function persistPaneOrder(grid) {
|
||||
@@ -1910,33 +1948,39 @@ function addSection(body, name, count, display = name) {
|
||||
/* all-mode: fully recursive sections along family path segments (train → agg →
|
||||
all → agent → …). Every logged key gets its own pane — stats are never
|
||||
overlaid, so min/p10/median/... show as raw separate plots. */
|
||||
function renderKeyTree(parent, name, families, depth) {
|
||||
/* one section per path prefix: the keys right under it are its panes, the deeper
|
||||
ones nest as sections of their own */
|
||||
function renderKeyTree(parent, name, keys, depth) {
|
||||
const display = depth === 1 ? name : name.split("/").pop();
|
||||
const { div, grid } = addSection(parent, name, families.length, display);
|
||||
const { div, grid } = addSection(parent, name, keys.length, display);
|
||||
const children = new Map();
|
||||
const leaves = [];
|
||||
for (const f of families) {
|
||||
const segments = f.family.split("/");
|
||||
if (segments.length <= depth + 1) leaves.push(f);
|
||||
for (const key of keys) {
|
||||
const segments = key.split("/");
|
||||
// a bare key (no path) is a pane of its own top-level section
|
||||
if (segments.length <= depth + 1) renderPanelCard(grid, { metric: key }, true);
|
||||
else {
|
||||
const segment = segments[depth];
|
||||
if (!children.has(segment)) children.set(segment, []);
|
||||
children.get(segment).push(f);
|
||||
children.get(segment).push(key);
|
||||
}
|
||||
}
|
||||
for (const f of leaves) for (const key of f.keys) renderPanelCard(grid, { metric: key }, true);
|
||||
if (grid.children.length) applyPaneOrder(grid);
|
||||
else grid.remove();
|
||||
for (const [segment, childFamilies] of children) renderKeyTree(div, `${name}/${segment}`, childFamilies, depth + 1);
|
||||
for (const [segment, childKeys] of children) renderKeyTree(div, `${name}/${segment}`, childKeys, depth + 1);
|
||||
}
|
||||
|
||||
function renderMetricsBody() {
|
||||
const m = state.metrics;
|
||||
for (const entry of m.charts) entry.u?.destroy();
|
||||
m.charts = [];
|
||||
if (!isChartTab()) {
|
||||
m.renderedKeys = -1; // nothing on screen: the next chart tab renders afresh
|
||||
return;
|
||||
}
|
||||
m.renderedKeys = m.byKey.size;
|
||||
const body = $("#metrics-body");
|
||||
body.innerHTML = "";
|
||||
const view = chartView();
|
||||
const body = $(view.body);
|
||||
for (const other of chartBodies()) other.innerHTML = ""; // the other tab's panes lost their charts above
|
||||
lazyObserver?.disconnect();
|
||||
lazyObserver = new IntersectionObserver(
|
||||
(entries) => {
|
||||
@@ -1948,15 +1992,15 @@ function renderMetricsBody() {
|
||||
},
|
||||
{ root: body, rootMargin: "400px" }
|
||||
);
|
||||
if (state.meta?.type === "eval") return renderEvalPane(body);
|
||||
activeFilter = makeFilter(state.metrics.search.trim());
|
||||
if (state.tab === "overview" && state.meta?.type === "eval") return renderEvalPane(body);
|
||||
activeFilter = makeFilter(m.searches[state.tab].trim());
|
||||
if (!state.meta?.has_metrics && !m.byKey.size) {
|
||||
body.innerHTML = emptyState("no metrics yet");
|
||||
$("#metrics-status").textContent = "";
|
||||
$(view.status).textContent = "";
|
||||
return;
|
||||
}
|
||||
if (m.mode === "overview") {
|
||||
$("#metrics-status").textContent = "";
|
||||
if (view.mode === "overview") {
|
||||
$(view.status).textContent = "";
|
||||
for (const section of buildSections(state.meta)) {
|
||||
const { div, grid } = addSection(body, section.name);
|
||||
for (const panel of section.panels) {
|
||||
@@ -1973,38 +2017,36 @@ function renderMetricsBody() {
|
||||
body.innerHTML = emptyState("no keys match", "no overview panels match the filter");
|
||||
return;
|
||||
}
|
||||
// all: one card per metric family - flat lists a section per family with a
|
||||
// pane per stat, nested groups families recursively along path segments
|
||||
const familyKeys = new Map();
|
||||
let shown = 0;
|
||||
for (const key of [...m.byKey.keys()].sort()) {
|
||||
if (activeFilter && !activeFilter.test(key)) continue;
|
||||
shown++;
|
||||
const family = familyOf(key);
|
||||
if (!familyKeys.has(family)) familyKeys.set(family, []);
|
||||
familyKeys.get(family).push(key);
|
||||
}
|
||||
$("#metrics-status").textContent = activeFilter ? `${shown} / ${m.byKey.size} keys` : "";
|
||||
if (!familyKeys.size) {
|
||||
// all: one pane per key - flat lists a section per parent path, nested walks
|
||||
// the path segments as a tree of sections
|
||||
const keys = [...m.byKey.keys()].filter((key) => !activeFilter || activeFilter.test(key)).sort();
|
||||
$(view.status).textContent = activeFilter ? `${keys.length} / ${m.byKey.size} keys` : "";
|
||||
if (!keys.length) {
|
||||
body.innerHTML = emptyState("no keys match", `0 of ${m.byKey.size} keys match the filter`);
|
||||
return;
|
||||
}
|
||||
const bySegment = (keys, at) => {
|
||||
const groups = new Map();
|
||||
for (const key of keys) {
|
||||
const segments = key.split("/");
|
||||
const group = at(segments);
|
||||
if (!groups.has(group)) groups.set(group, []);
|
||||
groups.get(group).push(key);
|
||||
}
|
||||
return groups;
|
||||
};
|
||||
if (m.allLayout === "flat") {
|
||||
for (const [family, keys] of familyKeys) {
|
||||
const { div, grid } = addSection(body, family, keys.length);
|
||||
for (const key of keys) renderPanelCard(grid, { metric: key }, true);
|
||||
// a bare key with no path is its own section
|
||||
const sections = [...bySegment(keys, (segments) => segments.slice(0, -1).join("/") || segments[0])].sort(([a], [b]) => a.localeCompare(b));
|
||||
for (const [parent, group] of sections) {
|
||||
const { div, grid } = addSection(body, parent, group.length);
|
||||
for (const key of group) renderPanelCard(grid, { metric: key }, true);
|
||||
if (!grid.children.length) div.remove();
|
||||
else applyPaneOrder(grid);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const groups = new Map();
|
||||
for (const [family, keys] of familyKeys) {
|
||||
const group = family.split("/")[0];
|
||||
if (!groups.has(group)) groups.set(group, []);
|
||||
groups.get(group).push({ family, keys });
|
||||
}
|
||||
for (const [group, families] of groups) renderKeyTree(body, group, families, 1);
|
||||
for (const [group, groupKeys] of bySegment(keys, (segments) => segments[0])) renderKeyTree(body, group, groupKeys, 1);
|
||||
}
|
||||
|
||||
async function initMetrics() {
|
||||
@@ -6253,15 +6295,6 @@ function syncTraceFilterControls() {
|
||||
|
||||
document.querySelectorAll("#tabs button").forEach((b) => b.addEventListener("click", () => activateTab(b.dataset.tab)));
|
||||
|
||||
document.querySelectorAll("#metrics-mode button").forEach((b) =>
|
||||
b.addEventListener("click", () => {
|
||||
state.metrics.mode = b.dataset.mode;
|
||||
setActive("#metrics-mode", "mode", b.dataset.mode);
|
||||
$("#all-layout").hidden = b.dataset.mode !== "all";
|
||||
renderMetricsBody();
|
||||
savePrefs();
|
||||
})
|
||||
);
|
||||
$("#config-format").addEventListener("click", (e) => {
|
||||
const btn = e.target.closest("button[data-fmt]");
|
||||
if (!btn || btn.disabled || btn.dataset.fmt === state.config.fmt) return;
|
||||
@@ -6281,49 +6314,57 @@ $("#config-search").addEventListener(
|
||||
savePrefs();
|
||||
})
|
||||
);
|
||||
document.querySelectorAll("#all-layout button").forEach((b) =>
|
||||
document.querySelectorAll("#metrics-layout button").forEach((b) =>
|
||||
b.addEventListener("click", () => {
|
||||
state.metrics.allLayout = b.dataset.layout;
|
||||
setActive("#all-layout", "layout", b.dataset.layout);
|
||||
setActive("#metrics-layout", "layout", b.dataset.layout);
|
||||
renderMetricsBody();
|
||||
savePrefs();
|
||||
})
|
||||
);
|
||||
$("#metrics-search").addEventListener(
|
||||
"input",
|
||||
debounce(() => {
|
||||
state.metrics.search = $("#metrics-search").value;
|
||||
renderMetricsBody();
|
||||
for (const [tab, view] of Object.entries(CHART_VIEWS)) {
|
||||
$(view.search).addEventListener(
|
||||
"input",
|
||||
debounce(() => {
|
||||
state.metrics.searches[tab] = $(view.search).value;
|
||||
renderMetricsBody();
|
||||
savePrefs();
|
||||
}, 250)
|
||||
);
|
||||
$(`#${tab}-collapse`).addEventListener("click", () =>
|
||||
document.querySelectorAll(`${view.body} details.section`).forEach((s) => (s.open = false))
|
||||
);
|
||||
$(`#${tab}-expand`).addEventListener("click", () =>
|
||||
document.querySelectorAll(`${view.body} details.section`).forEach((s) => (s.open = true))
|
||||
);
|
||||
$(`#${tab}-smooth`).addEventListener("input", (e) => {
|
||||
state.metrics.smooth = +e.target.value;
|
||||
syncSmoothControls();
|
||||
updateCharts();
|
||||
savePrefs();
|
||||
}, 250)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// remember collapsed sections across re-renders; charts created while hidden
|
||||
// have zero width, so resize on expand ("toggle" doesn't bubble → capture)
|
||||
$("#metrics-body").addEventListener(
|
||||
"toggle",
|
||||
(e) => {
|
||||
const section = e.target;
|
||||
if (!section.matches?.("details.section")) return;
|
||||
if (section.open) resizeCharts();
|
||||
// a search force-opens sections - don't let that overwrite the saved state
|
||||
if (activeFilter) return;
|
||||
if (section.open) state.metrics.collapsedSections.delete(section.dataset.name);
|
||||
else state.metrics.collapsedSections.add(section.dataset.name);
|
||||
savePrefs();
|
||||
},
|
||||
true
|
||||
);
|
||||
|
||||
$("#metrics-collapse").addEventListener("click", () =>
|
||||
document.querySelectorAll("#metrics-body details.section").forEach((s) => (s.open = false))
|
||||
);
|
||||
$("#metrics-expand").addEventListener("click", () =>
|
||||
document.querySelectorAll("#metrics-body details.section").forEach((s) => (s.open = true))
|
||||
);
|
||||
for (const body of chartBodies())
|
||||
body.addEventListener(
|
||||
"toggle",
|
||||
(e) => {
|
||||
const section = e.target;
|
||||
if (!section.matches?.("details.section")) return;
|
||||
if (section.open) resizeCharts();
|
||||
// a search force-opens sections - don't let that overwrite the saved state
|
||||
if (activeFilter) return;
|
||||
if (section.open) state.metrics.collapsedSections.delete(section.dataset.name);
|
||||
else state.metrics.collapsedSections.add(section.dataset.name);
|
||||
savePrefs();
|
||||
},
|
||||
true
|
||||
);
|
||||
|
||||
// drag a pane header to reorder within its section (order persisted by title)
|
||||
$("#metrics-body").addEventListener("dragover", (e) => {
|
||||
for (const body of chartBodies()) body.addEventListener("dragover", (e) => {
|
||||
if (!dragCard) return;
|
||||
const grid = e.target.closest(".chart-grid");
|
||||
if (!grid || grid !== dragCard.parentElement) return;
|
||||
@@ -6336,7 +6377,7 @@ $("#metrics-body").addEventListener("dragover", (e) => {
|
||||
});
|
||||
|
||||
/* wandb-style resize handles: resizing one pane resizes all of them */
|
||||
$("#metrics-body").addEventListener("pointerdown", (e) => {
|
||||
for (const body of chartBodies()) body.addEventListener("pointerdown", (e) => {
|
||||
const grip = e.target.closest("[data-rz]");
|
||||
if (!grip) return;
|
||||
e.preventDefault();
|
||||
@@ -6982,7 +7023,7 @@ $("#tm-meta").addEventListener("click", (e) => {
|
||||
});
|
||||
|
||||
function resizeCharts() {
|
||||
$("#metrics-body").style.setProperty("--pane-h", `${chartHeight()}px`);
|
||||
for (const body of chartBodies()) body.style.setProperty("--pane-h", `${chartHeight()}px`);
|
||||
drawSwarms();
|
||||
drawTiming();
|
||||
for (const entry of state.metrics.charts) {
|
||||
@@ -7011,8 +7052,8 @@ function savePrefs() {
|
||||
paneH: state.metrics.paneH,
|
||||
includeErrors: state.metrics.includeErrors,
|
||||
paneOrder: state.metrics.paneOrder,
|
||||
metricsMode: state.metrics.mode,
|
||||
metricsSearch: state.metrics.search,
|
||||
overviewSearch: state.metrics.searches.overview,
|
||||
metricsSearch: state.metrics.searches.metrics,
|
||||
collapsedSections: [...state.metrics.collapsedSections],
|
||||
traceErrorsOnly: state.traces.errorsOnly,
|
||||
traceStatus: state.traces.status,
|
||||
@@ -7033,16 +7074,17 @@ function savePrefs() {
|
||||
}
|
||||
|
||||
function applyPaneSize() {
|
||||
$("#metrics-body").style.setProperty("--pane-min", `${state.metrics.paneMin}px`);
|
||||
for (const body of chartBodies()) body.style.setProperty("--pane-min", `${state.metrics.paneMin}px`);
|
||||
resizeCharts();
|
||||
}
|
||||
|
||||
$("#smooth-range").addEventListener("input", (e) => {
|
||||
state.metrics.smooth = +e.target.value;
|
||||
$("#smooth-val").textContent = state.metrics.smooth > 1 ? String(state.metrics.smooth) : "off";
|
||||
updateCharts();
|
||||
savePrefs();
|
||||
});
|
||||
/* one smoothing window, shown on both chart tabs */
|
||||
function syncSmoothControls() {
|
||||
for (const tab of Object.keys(CHART_VIEWS)) {
|
||||
$(`#${tab}-smooth`).value = state.metrics.smooth;
|
||||
$(`#${tab}-smooth-val`).textContent = state.metrics.smooth > 1 ? String(state.metrics.smooth) : "off";
|
||||
}
|
||||
}
|
||||
|
||||
let ticking = false;
|
||||
async function pollDashboard() {
|
||||
@@ -7060,7 +7102,7 @@ async function pollDashboard() {
|
||||
}
|
||||
renderOverview(); // keeps the duration field ticking
|
||||
syncDressedSelects();
|
||||
if (state.tab === "metrics" && state.metrics.loaded) await fetchMetrics();
|
||||
if (isChartTab() && state.metrics.loaded) await fetchMetrics();
|
||||
else if (state.tab === "logs" && state.logs.loaded) await pollLogs();
|
||||
else if (state.tab === "traces" && state.traces.loaded) await refreshTraces();
|
||||
else if (state.tab === "report" && state.report.loaded) await refreshReport();
|
||||
@@ -7088,9 +7130,8 @@ document.addEventListener("visibilitychange", () => {
|
||||
});
|
||||
|
||||
(async function init() {
|
||||
$("#smooth-range").value = state.metrics.smooth;
|
||||
$("#smooth-val").textContent = state.metrics.smooth > 1 ? String(state.metrics.smooth) : "off";
|
||||
$("#metrics-search").value = state.metrics.search;
|
||||
syncSmoothControls();
|
||||
for (const [tab, view] of Object.entries(CHART_VIEWS)) $(view.search).value = state.metrics.searches[tab];
|
||||
state.logs.level = LOG_LEVELS.some(([level]) => level === prefs.logLevel) ? prefs.logLevel : "DEBUG";
|
||||
renderLogLevel();
|
||||
$("#log-search").value = prefs.logSearch ?? "";
|
||||
@@ -7098,16 +7139,14 @@ document.addEventListener("visibilitychange", () => {
|
||||
const signal = prefs.tokenSignal ?? "";
|
||||
$("#token-signal").value = $(`#token-signal option[value="${CSS.escape(signal)}"]`) ? signal : "";
|
||||
$("#follow-toggle").checked = state.follow;
|
||||
for (const sel of ["#run-select", "#trace-env", "#metrics-env", "#trace-sort", "#tm-env", "#tm-sort", "#config-attempt-select", "#attempt-select", "#token-signal", "#report-select"])
|
||||
for (const sel of ["#run-select", "#trace-env", "#overview-env", "#trace-sort", "#tm-env", "#tm-sort", "#config-attempt-select", "#attempt-select", "#token-signal", "#report-select"])
|
||||
dressSelect($(sel));
|
||||
syncTraceFilterControls();
|
||||
setActive("#metrics-mode", "mode", state.metrics.mode);
|
||||
setActive("#all-layout", "layout", state.metrics.allLayout);
|
||||
$("#all-layout").hidden = state.metrics.mode !== "all";
|
||||
setActive("#metrics-layout", "layout", state.metrics.allLayout);
|
||||
setActive("#log-view", "view", state.logs.view);
|
||||
applyPaneSize();
|
||||
const params = new URLSearchParams(location.hash.slice(1));
|
||||
state.tab = params.get("tab") || "metrics";
|
||||
state.tab = params.get("tab") || "overview";
|
||||
state.report.wanted = params.get("report");
|
||||
hadHashRun = !!params.get("run");
|
||||
setActive("#tabs", "tab", state.tab);
|
||||
@@ -7116,6 +7155,6 @@ document.addEventListener("visibilitychange", () => {
|
||||
const wanted = params.get("run");
|
||||
const run = state.runs.find((r) => r.name === wanted)?.name ?? state.runs[0]?.name;
|
||||
if (run) await selectRun(run);
|
||||
else $("#metrics-body").innerHTML = emptyState("no runs found", `nothing to show in ${state.outputDir ?? "the output directory"}`);
|
||||
else $("#overview-body").innerHTML = emptyState("no runs found", `nothing to show in ${state.outputDir ?? "the output directory"}`);
|
||||
connectViewEvents();
|
||||
})();
|
||||
|
||||
@@ -21,7 +21,8 @@
|
||||
</div>
|
||||
<nav id="tabs">
|
||||
<button data-tab="config">Config</button>
|
||||
<button data-tab="metrics" class="active">Metrics</button>
|
||||
<button data-tab="overview" class="active">Overview</button>
|
||||
<button data-tab="metrics">Metrics</button>
|
||||
<button data-tab="traces">Traces</button>
|
||||
<button data-tab="report">Report</button>
|
||||
<button data-tab="logs">Logs</button>
|
||||
@@ -38,30 +39,39 @@
|
||||
<div id="run-overview"></div>
|
||||
|
||||
<main>
|
||||
<section id="tab-metrics">
|
||||
<section id="tab-overview">
|
||||
<div class="controls">
|
||||
<div id="metrics-filter-wrap" class="dd-wrap" hidden>
|
||||
<button id="metrics-filter-btn" class="btn dd-btn" title="filter">
|
||||
<div id="overview-filter-wrap" class="dd-wrap" hidden>
|
||||
<button id="overview-filter-btn" class="btn dd-btn" title="filter">
|
||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
|
||||
filter
|
||||
</button>
|
||||
<div class="dd-menu dd-filters" id="metrics-filter-menu" hidden>
|
||||
<div class="dd-menu dd-filters" id="overview-filter-menu" hidden>
|
||||
<div class="dd-sec">filter</div>
|
||||
<label class="dd-row" id="metrics-env-row"><span class="t-label">env</span>
|
||||
<select id="metrics-env"></select>
|
||||
<label class="dd-row" id="overview-env-row"><span class="t-label">env</span>
|
||||
<select id="overview-env"></select>
|
||||
</label>
|
||||
<label class="toggle dd-row"><input type="checkbox" id="metrics-errors"><span class="dot"></span>include errors</label>
|
||||
<label class="toggle dd-row"><input type="checkbox" id="overview-errors"><span class="dot"></span>include errors</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="seg" id="metrics-mode">
|
||||
<button data-mode="overview" class="active">Overview</button>
|
||||
<button data-mode="all">All</button>
|
||||
</div>
|
||||
<input id="overview-search" class="search" type="search" placeholder="regex filter, e.g. reward or ^inference/">
|
||||
<label class="ctl">smooth <input id="overview-smooth" type="range" min="1" max="50" value="1"><span id="overview-smooth-val">off</span></label>
|
||||
<span id="overview-status" class="muted"></span>
|
||||
<div class="spacer"></div>
|
||||
<button id="overview-collapse" class="btn">collapse</button>
|
||||
<button id="overview-expand" class="btn">expand</button>
|
||||
</div>
|
||||
<div id="overview-body"></div>
|
||||
<div id="swarm-tip" hidden></div>
|
||||
</section>
|
||||
|
||||
<section id="tab-metrics" hidden>
|
||||
<div class="controls">
|
||||
<input id="metrics-search" class="search" type="search" placeholder="regex filter, e.g. ^entropy/ or reward">
|
||||
<label class="ctl">smooth <input id="smooth-range" type="range" min="1" max="50" value="1"><span id="smooth-val">off</span></label>
|
||||
<label class="ctl">smooth <input id="metrics-smooth" type="range" min="1" max="50" value="1"><span id="metrics-smooth-val">off</span></label>
|
||||
<span id="metrics-status" class="muted"></span>
|
||||
<div class="spacer"></div>
|
||||
<div class="seg" id="all-layout" hidden>
|
||||
<div class="seg" id="metrics-layout">
|
||||
<button data-layout="flat">Flat</button>
|
||||
<button data-layout="nested">Nested</button>
|
||||
</div>
|
||||
@@ -69,7 +79,6 @@
|
||||
<button id="metrics-expand" class="btn">expand</button>
|
||||
</div>
|
||||
<div id="metrics-body"></div>
|
||||
<div id="swarm-tip" hidden></div>
|
||||
</section>
|
||||
|
||||
<section id="tab-config" hidden>
|
||||
|
||||
@@ -306,12 +306,14 @@ main > section { flex: 1; min-height: 0; display: flex; flex-direction: column;
|
||||
|
||||
/* --------------------------------------------------------------- metrics */
|
||||
/* stable gutter: no layout shift when collapsing sections hides the scrollbar */
|
||||
#metrics-body { flex: 1; overflow-y: auto; scrollbar-gutter: stable; min-height: 0; padding-right: 10px; }
|
||||
#overview-body, #metrics-body { flex: 1; overflow-y: auto; scrollbar-gutter: stable; min-height: 0; padding-right: 10px; }
|
||||
.chart-card.dragging { opacity: 0.45; }
|
||||
/* one 12px rhythm everywhere: section-to-section, header-to-panes, pane-to-pane */
|
||||
details.section { margin-bottom: 12px; }
|
||||
/* nested sections (all-mode key tree) indent one step */
|
||||
details.section details.section { margin-left: 14px; }
|
||||
/* a section's own panes keep the rhythm before the sections nested under them */
|
||||
details.section > .chart-grid:not(:last-child) { margin-bottom: 12px; }
|
||||
details.section:not([open]) > summary { margin-bottom: 0; }
|
||||
/* section headers are full-width bars so the clickable region is obvious */
|
||||
details.section > summary {
|
||||
@@ -360,7 +362,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
|
||||
.ep-cell.live { border-color: var(--accent); background: rgba(182, 255, 60, 0.18); animation: live-pulse 1.6s ease-in-out infinite; cursor: pointer; }
|
||||
|
||||
/* distributions: a beeswarm per metric, a faint boxplot behind it, stats on hover */
|
||||
#tab-metrics { position: relative; }
|
||||
#tab-overview { position: relative; }
|
||||
.swarm-card .chart-head { cursor: default; }
|
||||
.swarm-host { height: var(--pane-h, 150px); margin-top: 6px; }
|
||||
.swarm { display: block; }
|
||||
@@ -528,7 +530,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
|
||||
|
||||
|
||||
/* metrics regex filter (overview + all) */
|
||||
#metrics-search, #config-search, #log-search { flex: 1; max-width: 460px; }
|
||||
#overview-search, #metrics-search, #config-search, #log-search { flex: 1; max-width: 460px; }
|
||||
|
||||
/* wandb-style resize handles on every chart card: right edge = width, bottom
|
||||
edge = height, corner = both. Resizing one pane resizes all of them. */
|
||||
|
||||
@@ -531,7 +531,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
|
||||
use_zmq_transport=config.rollout_transport is not None and config.rollout_transport.type == "zmq",
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
|
||||
env_names={"train": train_env_names, "eval": eval_env_names},
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
**modelexpress_vars,
|
||||
)
|
||||
else:
|
||||
@@ -571,7 +572,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
orchestrator_env_vars=orchestrator_env_vars,
|
||||
inference_env_vars=inference_env_vars,
|
||||
env_names={"train": train_env_names, "eval": eval_env_names},
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
**modelexpress_vars,
|
||||
)
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ from prime_rl.orchestrator import live
|
||||
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
|
||||
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient
|
||||
from prime_rl.orchestrator.concurrency import ConcurrencyController
|
||||
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
|
||||
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMode
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.eval_sink import EvalSink
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
@@ -79,7 +79,6 @@ class EvalRunner:
|
||||
# The launcher-set $PRL_RUN_ID is the run identity; standalone runs mint a local one.
|
||||
self.run_id = os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex
|
||||
self.run_name = os.environ.get("PRL_RUN_NAME")
|
||||
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
|
||||
|
||||
get_logger().info(f"Initializing inference pool (base_url={config.client.base_url}, model={config.model})")
|
||||
self.clients = InferenceClient(config.client, model_name=config.model)
|
||||
@@ -153,13 +152,7 @@ class EvalRunner:
|
||||
self.periodic_logger = PeriodicLogger(
|
||||
name="Eval",
|
||||
collect=self.collect_pipeline_view,
|
||||
metric_keys=[
|
||||
*list(self.dispatcher.gauges().keys()),
|
||||
*list(self.concurrency.gauges().keys()),
|
||||
*DispatcherMetrics.drain_keys(train_envs=set(), eval_envs={env.name for env in self.eval_envs}),
|
||||
],
|
||||
interval=config.log.interval,
|
||||
wandb_enabled=wandb_enabled,
|
||||
)
|
||||
|
||||
async def start(self) -> None:
|
||||
|
||||
@@ -391,7 +391,6 @@ class DynamoAdminPlane(AdminPlane):
|
||||
port: int,
|
||||
timeout: int,
|
||||
inference_world_size: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
) -> None:
|
||||
async with self._mutation_lock:
|
||||
self._require_uninitialized_nccl()
|
||||
@@ -411,7 +410,6 @@ class DynamoAdminPlane(AdminPlane):
|
||||
0,
|
||||
1,
|
||||
timeout,
|
||||
quantize_in_weight_transfer,
|
||||
"default",
|
||||
],
|
||||
)
|
||||
|
||||
@@ -138,11 +138,10 @@ async def init_broadcaster(request: Request):
|
||||
timeout = data.get("timeout")
|
||||
rank_offset = data.get("rank_offset")
|
||||
inference_world_size = data.get("inference_world_size")
|
||||
quantize_in_weight_transfer = data.get("quantize_in_weight_transfer", False)
|
||||
session_id = data.get("session_id", "default")
|
||||
await engine_client(request).collective_rpc(
|
||||
"init_broadcaster",
|
||||
args=(host, port, rank_offset, inference_world_size, timeout, quantize_in_weight_transfer, session_id),
|
||||
args=(host, port, rank_offset, inference_world_size, timeout, session_id),
|
||||
)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@@ -7,11 +7,7 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
|
||||
from vllm.distributed.utils import StatelessProcessGroup
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from prime_rl.inference.vllm.worker.weight_transfer import (
|
||||
load_weights_checkpoint_layerwise,
|
||||
load_weights_kernel,
|
||||
update_mla_absorbed_weights,
|
||||
)
|
||||
from prime_rl.inference.vllm.worker.weight_transfer import load_weights_checkpoint_layerwise
|
||||
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
|
||||
|
||||
# This is to get type hints for the Worker class but not actually extend it at runtime as this is required by vLLM worker extension
|
||||
@@ -99,7 +95,6 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
rank_offset: int,
|
||||
inference_world_size: int,
|
||||
timeout: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
session_id: str = "default",
|
||||
) -> None:
|
||||
"""Initialize the NCCL broadcast receiver.
|
||||
@@ -109,7 +104,6 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
inference_world_size: Total number of inference GPUs across all servers.
|
||||
"""
|
||||
del session_id
|
||||
self.quantize_in_weight_transfer = quantize_in_weight_transfer
|
||||
# Use the worker's device index directly as the local rank.
|
||||
# The previous dp_group-based computation broke in vLLM v1 multiprocess
|
||||
# DP mode where each worker is a separate process with a singleton
|
||||
@@ -145,11 +139,6 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
assert isinstance(model, Module)
|
||||
|
||||
state_iter = self.nccl_broadcast_receiver.receive_state_dict()
|
||||
if self.quantize_in_weight_transfer:
|
||||
load_weights_kernel(model, state_iter)
|
||||
update_mla_absorbed_weights(model)
|
||||
return
|
||||
|
||||
load_weights_checkpoint_layerwise(
|
||||
model,
|
||||
state_iter,
|
||||
|
||||
@@ -98,10 +98,9 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
rank_offset: int,
|
||||
inference_world_size: int,
|
||||
timeout: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
session_id: str = "default",
|
||||
) -> None:
|
||||
del inference_world_size, quantize_in_weight_transfer
|
||||
del inference_world_size
|
||||
global_rank = rank_offset + self.device.index
|
||||
server_url = f"{host}:{port}"
|
||||
set_ucx_env_defaults(self.device.index)
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
from typing import Generator, Iterable
|
||||
from typing import Iterable
|
||||
|
||||
import torch
|
||||
from torch.nn import Module
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.reload import finalize_layerwise_reload, initialize_layerwise_reload
|
||||
from vllm.model_executor.model_loader.weight_utils import remap_moe_expert_weights
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_weight_transfer")
|
||||
|
||||
@@ -24,116 +23,6 @@ def load_weights_checkpoint_layerwise(
|
||||
finalize_layerwise_reload(model, model_config)
|
||||
|
||||
|
||||
def _invert_logical_to_physical_map(logical_to_physical_map: torch.Tensor, num_physical_experts: int) -> torch.Tensor:
|
||||
"""Build a physical expert -> logical expert map from vLLM EPLB state."""
|
||||
physical_to_logical = torch.full(
|
||||
(num_physical_experts,),
|
||||
-1,
|
||||
dtype=torch.long,
|
||||
device=logical_to_physical_map.device,
|
||||
)
|
||||
logical_indices = torch.arange(
|
||||
logical_to_physical_map.shape[0],
|
||||
dtype=torch.long,
|
||||
device=logical_to_physical_map.device,
|
||||
)[:, None].expand_as(logical_to_physical_map)
|
||||
physical_indices = logical_to_physical_map.to(torch.long)
|
||||
invalid = (physical_indices < -1) | (physical_indices >= num_physical_experts)
|
||||
if invalid.any():
|
||||
invalid_indices = physical_indices[invalid].unique().tolist()
|
||||
raise ValueError(f"EPLB maps to invalid physical experts: {invalid_indices}")
|
||||
|
||||
valid = physical_indices >= 0
|
||||
physical_to_logical[physical_indices[valid]] = logical_indices[valid]
|
||||
return physical_to_logical
|
||||
|
||||
|
||||
def _build_expert_source_indices(routed_experts, router) -> torch.Tensor | None:
|
||||
if routed_experts._expert_map is None:
|
||||
return None
|
||||
|
||||
physical_indices = torch.where(routed_experts._expert_map >= 0)[0]
|
||||
local_indices = routed_experts._expert_map[physical_indices]
|
||||
physical_indices = physical_indices[local_indices.argsort()]
|
||||
|
||||
eplb_layer_state = getattr(router, "eplb_state", None)
|
||||
logical_to_physical_map = getattr(eplb_layer_state, "logical_to_physical_map", None)
|
||||
if logical_to_physical_map is None:
|
||||
return physical_indices
|
||||
|
||||
physical_to_logical = _invert_logical_to_physical_map(logical_to_physical_map, routed_experts.global_num_experts)
|
||||
logical_indices = physical_to_logical[physical_indices.to(physical_to_logical.device)]
|
||||
if (logical_indices < 0).any():
|
||||
missing = physical_indices[(logical_indices < 0).to(physical_indices.device)].tolist()
|
||||
raise ValueError(f"EPLB has no logical mapping for local physical experts: {missing}")
|
||||
|
||||
return logical_indices.to(physical_indices.device)
|
||||
|
||||
|
||||
def build_expert_map(model: Module) -> dict[str, torch.Tensor]:
|
||||
"""Map MoE module names to source expert indices local to this worker.
|
||||
|
||||
vLLM 0.24 turned ``FusedMoE`` into a factory returning a ``MoERunner`` and
|
||||
split the state that used to live on the ``FusedMoE`` module: the expert map
|
||||
(``_expert_map`` / ``global_num_experts``) now lives on
|
||||
``MoERunner.routed_experts`` (a ``RoutedExperts``), and the EPLB state on
|
||||
``MoERunner.router``. Keying by the ``MoERunner`` name prefix-matches the
|
||||
nested ``routed_experts.*`` weight params after ``load_weights_kernel``
|
||||
remaps incoming flat names via ``remap_moe_expert_weights``.
|
||||
"""
|
||||
from vllm.model_executor.layers.fused_moe import MoERunner
|
||||
|
||||
source_indices_by_module: dict[str, torch.Tensor] = {}
|
||||
for module_name, module in model.named_modules():
|
||||
if not isinstance(module, MoERunner):
|
||||
continue
|
||||
source_indices = _build_expert_source_indices(module.routed_experts, module.router)
|
||||
if source_indices is None:
|
||||
continue
|
||||
source_indices_by_module[module_name] = source_indices
|
||||
return source_indices_by_module
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def load_weights_kernel(model: Module, state_iter: Generator[tuple[str, torch.Tensor], None, None]) -> None:
|
||||
"""Load vLLM kernel-format tensors using in-place copy_ updates."""
|
||||
params = dict(model.named_parameters())
|
||||
expert_source_indices = build_expert_map(model)
|
||||
|
||||
loaded = 0
|
||||
skipped: list[str] = []
|
||||
shape_mismatches: list[str] = []
|
||||
|
||||
# The trainer emits pre-0.24 flat kernel names (``...experts.w13_weight``); since
|
||||
# vLLM 0.24 the expert params are nested (``...experts.routed_experts.w13_weight``).
|
||||
# ``remap_moe_expert_weights`` is upstream's compat shim for exactly this transition.
|
||||
for name, tensor in remap_moe_expert_weights(state_iter, params):
|
||||
if name not in params:
|
||||
skipped.append(name)
|
||||
continue
|
||||
|
||||
param = params[name]
|
||||
if param.shape != tensor.shape:
|
||||
for module_name, source_indices in expert_source_indices.items():
|
||||
if not name.startswith(f"{module_name}."):
|
||||
continue
|
||||
tensor = tensor[source_indices.to(tensor.device)]
|
||||
break
|
||||
|
||||
if param.shape != tensor.shape:
|
||||
shape_mismatches.append(f"{name}: param={list(param.shape)} != received={list(tensor.shape)}")
|
||||
continue
|
||||
|
||||
param.copy_(tensor)
|
||||
loaded += 1
|
||||
|
||||
if shape_mismatches:
|
||||
raise ValueError(f"Kernel weight transfer had {len(shape_mismatches)} shape mismatches: {shape_mismatches}")
|
||||
if skipped:
|
||||
raise ValueError(f"Kernel weight transfer skipped {len(skipped)} weights not found in model: {skipped}")
|
||||
logger.debug(f"Kernel weight transfer copied {loaded} weights in-place")
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def update_mla_absorbed_weights(model: Module) -> None:
|
||||
"""Recompute MLA absorbed KV weights after in-place kv_b_proj updates."""
|
||||
|
||||
@@ -7,7 +7,7 @@ from typing import TYPE_CHECKING, Any
|
||||
|
||||
import orjson
|
||||
import prime_runs as pr
|
||||
from prime_cli.core.config import Config as PrimeConfig
|
||||
from prime_sandboxes import Config as PrimeConfig
|
||||
|
||||
from prime_rl.configs.monitors import PrimeEvalMonitorConfig, PrimeTrainMonitorConfig
|
||||
from prime_rl.monitors.base import Kind, Monitor, Subset
|
||||
|
||||
@@ -73,9 +73,9 @@ INFERENCE_PANELS = [
|
||||
"inference/agg/num_requests_waiting/max",
|
||||
],
|
||||
["inference/agg/prefix_cache_hit_rate/pooled", "inference/agg/prefix_cache_hit_rate/min"],
|
||||
["inference/agg/generation_tokens_total:rate/sum", "inference/agg/generation_tokens_total:rate/min"],
|
||||
["inference/agg/prompt_tokens_total:rate/sum", "inference/agg/prompt_tokens_total:rate/max"],
|
||||
["dispatcher/inflight/train", "dispatcher/inflight/eval"],
|
||||
["inference/agg/generation_tokens_total:rate/sum"],
|
||||
["inference/agg/prompt_tokens_total:rate/sum"],
|
||||
["dispatcher/inflight/train", "dispatcher/inflight/eval", "concurrency/max_inflight"],
|
||||
]
|
||||
|
||||
# SFT flavor: no rollout-based train sections — the training signal is the loss curve.
|
||||
|
||||
@@ -24,7 +24,7 @@ def resolve_api_key(api_key_var: str) -> str:
|
||||
CLI config (``prime login``), like the verifiers client does. ``"EMPTY"`` when unset."""
|
||||
api_key = os.environ.get(api_key_var)
|
||||
if not api_key and api_key_var == "PRIME_API_KEY":
|
||||
from prime_cli.core.config import Config as PrimeConfig
|
||||
from prime_sandboxes import Config as PrimeConfig
|
||||
|
||||
api_key = PrimeConfig().api_key
|
||||
return api_key or "EMPTY"
|
||||
@@ -39,7 +39,7 @@ def resolve_headers(client_config: ClientConfig) -> dict[str, str]:
|
||||
}
|
||||
headers = {**client_config.headers, **env_headers}
|
||||
if client_config.base_url.startswith(PRIME_INFERENCE_URL) and "X-Prime-Team-ID" not in headers:
|
||||
from prime_cli.core.config import Config as PrimeConfig
|
||||
from prime_sandboxes import Config as PrimeConfig
|
||||
|
||||
if team_id := os.environ.get("PRIME_TEAM_ID") or PrimeConfig().team_id:
|
||||
headers["X-Prime-Team-ID"] = team_id
|
||||
@@ -91,6 +91,13 @@ class InferenceClient:
|
||||
)
|
||||
self.eval_client = setup_client(client_config, client_type=eval_client_type)
|
||||
self._scorer = PrefillScorer()
|
||||
# Managed routed deployments set admin_base_url so engine admin traffic
|
||||
# bypasses the client-facing router. External and frozen clients do not.
|
||||
self._session_client = (
|
||||
setup_admin_clients(client_config.model_copy(update={"admin_base_url": None}))[0]
|
||||
if client_config.admin_base_url is not None
|
||||
else None
|
||||
)
|
||||
self.model_name = model_name
|
||||
|
||||
async def score(self, token_ids: list[int]) -> list[float]:
|
||||
@@ -100,6 +107,26 @@ class InferenceClient:
|
||||
|
||||
async def aclose(self) -> None:
|
||||
await self._scorer.aclose()
|
||||
if self._session_client is not None:
|
||||
await self._session_client.aclose()
|
||||
|
||||
async def finish_sessions(self, session_ids: list[str]) -> None:
|
||||
"""Release completed sessions when the client-facing router supports it."""
|
||||
if self._session_client is None or not session_ids:
|
||||
return
|
||||
|
||||
async def finish_session(session_id: str) -> None:
|
||||
try:
|
||||
await _admin_post(
|
||||
self._session_client,
|
||||
"/finish_session",
|
||||
timeout_s=5.0,
|
||||
params={"session_id": session_id},
|
||||
)
|
||||
except Exception as error:
|
||||
get_logger().debug(f"Failed to release inference session {session_id}: {error!r}")
|
||||
|
||||
await asyncio.gather(*(finish_session(session_id) for session_id in session_ids))
|
||||
|
||||
|
||||
class AdminPlane:
|
||||
@@ -142,7 +169,6 @@ class AdminPlane:
|
||||
port: int,
|
||||
timeout: int,
|
||||
inference_world_size: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
) -> None:
|
||||
gpus_per_server = inference_world_size // len(self.clients)
|
||||
get_logger().info(
|
||||
@@ -160,7 +186,6 @@ class AdminPlane:
|
||||
"rank_offset": rank_offset,
|
||||
"inference_world_size": inference_world_size,
|
||||
"timeout": timeout,
|
||||
"quantize_in_weight_transfer": quantize_in_weight_transfer,
|
||||
},
|
||||
)
|
||||
response.raise_for_status()
|
||||
@@ -486,7 +511,6 @@ async def init_nixl_broadcast(
|
||||
"rank_offset": rank_offset,
|
||||
"inference_world_size": inference_world_size,
|
||||
"timeout": timeout,
|
||||
"quantize_in_weight_transfer": False,
|
||||
"session_id": session_id,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -5,8 +5,9 @@ treats it as a black box. There is no cost model: the controller measures KV
|
||||
pressure off the engines and reacts at the pipeline's own pace (AIMD):
|
||||
|
||||
- **Grow** the cap multiplicatively per pipeline turnover (each completion
|
||||
advances the turnover by ``1/inflight``) while the engines are clear, KV
|
||||
usage is below ``KV_USAGE_GROW``, and the cap binds admission.
|
||||
advances the turnover by ``1/inflight``) while the engines are clear and
|
||||
the cap binds admission. The multiplier tapers linearly with GPU-KV usage
|
||||
until the soft-cap boundary.
|
||||
- **Trim** above ``KV_USAGE_SOFT_CAP``: lower the cap to what the engines
|
||||
hold at ``KV_USAGE_TARGET`` and let completions drain the pool (soft). If
|
||||
usage still climbs past ``KV_USAGE_HARD_CAP`` — units maturing in place
|
||||
@@ -38,14 +39,12 @@ from prime_rl.configs.orchestrator import ConcurrencyConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import format_num
|
||||
|
||||
TURNOVER_GROWTH = 1.25
|
||||
"""Cap growth per pipeline turnover while the engines are clear and the cap binds."""
|
||||
TURNOVER_GROWTH_MAX = 1.2
|
||||
"""Cap growth per pipeline turnover at zero GPU-KV utilization."""
|
||||
|
||||
BINDING_FRACTION = 0.9
|
||||
"""The cap counts as binding when inflight reaches this fraction of it."""
|
||||
|
||||
KV_USAGE_GROW = 0.6
|
||||
"""Grow only while every decode engine's KV usage is below this."""
|
||||
|
||||
KV_USAGE_SOFT_CAP = 0.8
|
||||
"""Above this usage, soft-trim: lower the cap and let completions drain the
|
||||
@@ -129,6 +128,7 @@ class ConcurrencyController:
|
||||
|
||||
self.turnover = 0.0
|
||||
self.signal: Signal = "clear"
|
||||
self.growth_multiplier = 1.0
|
||||
# Growth gate from the last poll, consumed by per-completion growth
|
||||
self.can_grow = False
|
||||
self.can_grow_until = 0.0
|
||||
@@ -183,7 +183,7 @@ class ConcurrencyController:
|
||||
and time.monotonic() < self.can_grow_until
|
||||
and inflight >= BINDING_FRACTION * self.max_inflight
|
||||
):
|
||||
self.cap = self.clamp(self.cap * TURNOVER_GROWTH**fraction)
|
||||
self.cap = self.clamp(self.cap * self.growth_multiplier**fraction)
|
||||
self.apply_limit(int(self.cap), reason=None)
|
||||
|
||||
def observe(self, samples: list[EngineLoadSample]) -> None:
|
||||
@@ -223,8 +223,10 @@ class ConcurrencyController:
|
||||
else:
|
||||
self.queue_overload_polls = 0
|
||||
queue_overload = self.queue_overload_polls >= QUEUE_PERSISTENCE_POLLS
|
||||
if queue_overload or max_usage > KV_USAGE_GROW:
|
||||
worst = max(worst, "hard" if queue_overload else "soft", key=SEVERITY.__getitem__)
|
||||
if queue_overload:
|
||||
worst = max(worst, "hard", key=SEVERITY.__getitem__)
|
||||
elif max_usage > KV_USAGE_SOFT_CAP:
|
||||
worst = max(worst, "soft", key=SEVERITY.__getitem__)
|
||||
self.signal = worst
|
||||
|
||||
inflight = self.get_inflight() if self.get_inflight is not None else 0
|
||||
@@ -247,6 +249,7 @@ class ConcurrencyController:
|
||||
self.escalated = False
|
||||
self.trim_cooldown = max(0, self.trim_cooldown - 1)
|
||||
self.can_grow = worst == "clear" and total_queued == 0 and not self.draining
|
||||
self.growth_multiplier = 1.0 + (TURNOVER_GROWTH_MAX - 1.0) * max(0.0, 1.0 - max_usage / KV_USAGE_SOFT_CAP)
|
||||
self.can_grow_until = time.monotonic() + GROWTH_GATE_TTL_S
|
||||
|
||||
# First capacity observation without a user-set start: derive the
|
||||
@@ -331,4 +334,5 @@ class ConcurrencyController:
|
||||
"concurrency/turnover": self.turnover,
|
||||
"concurrency/capacity": float(self.capacity or 0),
|
||||
"concurrency/signal": float(SEVERITY[self.signal]),
|
||||
"concurrency/growth_multiplier": self.growth_multiplier,
|
||||
}
|
||||
|
||||
@@ -92,8 +92,8 @@ class DispatcherMetrics:
|
||||
|
||||
def drained(self, *, train_envs: set[str], eval_envs: set[str]) -> dict[str, float]:
|
||||
"""Return per-tick counters and clear them. Emits the full pre-
|
||||
registered key set every tick (zero when no activity) so the wandb
|
||||
time axis stays dense and ``define_metric`` lines up."""
|
||||
registered key set every tick (zero when no activity) so the
|
||||
time-keyed series stay dense on every monitor."""
|
||||
out: dict[str, float] = {}
|
||||
for kind in ("train", "eval"):
|
||||
envs = train_envs if kind == "train" else eval_envs
|
||||
@@ -112,21 +112,6 @@ class DispatcherMetrics:
|
||||
self.errored_by_kind_env.clear()
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def drain_keys(*, train_envs: set[str], eval_envs: set[str]) -> list[str]:
|
||||
"""Full set of keys ``drained`` may emit; used by the periodic
|
||||
logger for ``wandb.define_metric``."""
|
||||
keys = [
|
||||
"dispatcher/cancelled/train",
|
||||
"dispatcher/cancelled/eval",
|
||||
"dispatcher/errored/train",
|
||||
"dispatcher/errored/eval",
|
||||
]
|
||||
for env in train_envs | eval_envs:
|
||||
keys.append(f"dispatcher/cancelled/{env}")
|
||||
keys.append(f"dispatcher/errored/{env}")
|
||||
return keys
|
||||
|
||||
|
||||
def _validate_episode_task(episode: vf.WireEpisode, task: vf.Task) -> None:
|
||||
expected = (task.key, task.hash)
|
||||
@@ -593,7 +578,10 @@ class Dispatcher:
|
||||
started_at=time.monotonic(),
|
||||
)
|
||||
|
||||
session_ids: set[str] = set()
|
||||
|
||||
def on_delta(delta: dict) -> None:
|
||||
session_ids.add(delta["trace"])
|
||||
first = not meta.live
|
||||
live.apply(meta, delta)
|
||||
self.queue_live({"delta": delta, "dispatch": live.dispatch_info(meta)})
|
||||
@@ -602,15 +590,26 @@ class Dispatcher:
|
||||
if first and meta.live:
|
||||
self.live_events.append(live.dispatched_event(meta))
|
||||
|
||||
task = asyncio.create_task(
|
||||
env.run(
|
||||
client=client,
|
||||
model_name=model_name,
|
||||
cache_salt=cache_salt,
|
||||
task_data=group.task.data.model_dump(mode="json"),
|
||||
on_delta=on_delta,
|
||||
)
|
||||
)
|
||||
async def run_episode() -> vf.WireEpisode:
|
||||
try:
|
||||
episode = await env.run(
|
||||
client=client,
|
||||
model_name=model_name,
|
||||
cache_salt=cache_salt,
|
||||
task_data=group.task.data.model_dump(mode="json"),
|
||||
on_delta=on_delta,
|
||||
)
|
||||
session_ids.update(trace.id for trace in episode.traces)
|
||||
return episode
|
||||
finally:
|
||||
cleanup = asyncio.create_task(clients.finish_sessions(sorted(session_ids)))
|
||||
try:
|
||||
await asyncio.shield(cleanup)
|
||||
except asyncio.CancelledError:
|
||||
await cleanup
|
||||
raise
|
||||
|
||||
task = asyncio.create_task(run_episode())
|
||||
self.inflight[task] = meta
|
||||
self.live_events.append(live.pending_event(meta))
|
||||
return True
|
||||
|
||||
@@ -11,7 +11,7 @@ and drives the pipeline. Components are single-purpose:
|
||||
- ``TrainEpisodes`` / ``EvalEpisodes`` preserve episode boundaries and build per-step metrics.
|
||||
- ``WeightWatcher`` advances ``Policy`` and notifies observers.
|
||||
- ``PeriodicLogger`` polls the components on a shared interval for the
|
||||
``_timestamp``-axis pipeline log.
|
||||
pipeline log, a time-keyed row through the monitors.
|
||||
|
||||
Components don't reference the orchestrator. The orchestrator wires them
|
||||
in ``setup()`` and drives them from ``main_loop()``.
|
||||
@@ -41,7 +41,7 @@ from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
|
||||
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
|
||||
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient, setup_admin_plane
|
||||
from prime_rl.orchestrator.concurrency import ConcurrencyController
|
||||
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
|
||||
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMode
|
||||
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
|
||||
from prime_rl.orchestrator.eval_sink import EvalSink
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
@@ -336,7 +336,6 @@ class Orchestrator:
|
||||
)
|
||||
|
||||
log_interval = config.log.interval
|
||||
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
|
||||
|
||||
self.concurrency = ConcurrencyController(config.concurrency, fallback_cost=config.seq_len)
|
||||
self.dispatcher = Dispatcher(
|
||||
@@ -398,24 +397,7 @@ class Orchestrator:
|
||||
self.periodic_logger = PeriodicLogger(
|
||||
name="Pipeline",
|
||||
collect=self.collect_pipeline_view,
|
||||
metric_keys=[
|
||||
*list(self.dispatcher.gauges().keys()),
|
||||
*list(self.concurrency.gauges().keys()),
|
||||
*DispatcherMetrics.drain_keys(
|
||||
train_envs={e.name for e in self.train_envs},
|
||||
eval_envs={e.name for e in self.eval_envs} if self.eval_envs is not None else set(),
|
||||
),
|
||||
*list(self.watcher.gauges().keys()),
|
||||
"event_loop_lag/min",
|
||||
"event_loop_lag/mean",
|
||||
"event_loop_lag/median",
|
||||
"event_loop_lag/p90",
|
||||
"event_loop_lag/p99",
|
||||
"event_loop_lag/max",
|
||||
"event_loop_lag/n",
|
||||
],
|
||||
interval=log_interval,
|
||||
wandb_enabled=wandb_enabled,
|
||||
)
|
||||
|
||||
get_logger().info(f"Syncing inference to the trainer's startup broadcast (v{sync_version})")
|
||||
@@ -457,10 +439,12 @@ class Orchestrator:
|
||||
elapsed = format_time(time.perf_counter() - start_time)
|
||||
if clean_exit:
|
||||
get_logger().success(f"Orchestrator step loop done in {elapsed}")
|
||||
# The collector logs to the W&B run, so it must stop before
|
||||
# finalize marks the run finished
|
||||
# The background loggers write through the monitors, so they must
|
||||
# stop before finalize marks the run finished
|
||||
if self.inference_metrics is not None:
|
||||
await self.inference_metrics.stop()
|
||||
if self.periodic_logger is not None:
|
||||
await self.periodic_logger.stop()
|
||||
# Finalize only on a clean exit — a crashed run must not be marked
|
||||
# completed; the platform run's atexit hook marks it failed instead.
|
||||
await monitors.finalize()
|
||||
@@ -830,7 +814,7 @@ class Orchestrator:
|
||||
|
||||
def collect_pipeline_view(self) -> tuple[str, dict[str, float]]:
|
||||
"""Pipeline view for the orchestrator's ``PeriodicLogger``. Returns
|
||||
``(console_body, wandb_payload)``. Per-env ``(env=N, …)``
|
||||
``(console_body, payload)``. Per-env ``(env=N, …)``
|
||||
breakdowns inline only when there's more than one train / eval env;
|
||||
the eval halves drop entirely when nothing is accumulating."""
|
||||
disp_gauges = self.dispatcher.gauges()
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
"""PeriodicLogger: orchestrator's pipeline view, fires every ``interval``
|
||||
seconds. ``collect()`` returns ``(console_body, wandb_payload)`` in one
|
||||
call so drain-on-read counters fire exactly once per tick. Wandb writes
|
||||
land on the ``_timestamp`` axis."""
|
||||
seconds. ``collect()`` returns ``(console_body, payload)`` in one call so
|
||||
drain-on-read counters fire exactly once per tick. The payload goes to every
|
||||
registered monitor as a time-keyed row (``step=None``)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from typing import Callable
|
||||
|
||||
import wandb
|
||||
|
||||
from prime_rl import monitors
|
||||
from prime_rl.utils.async_utils import safe_cancel
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -21,21 +19,14 @@ class PeriodicLogger:
|
||||
*,
|
||||
name: str,
|
||||
collect: Callable[[], tuple[str, dict[str, float]]],
|
||||
metric_keys: list[str],
|
||||
interval: float,
|
||||
wandb_enabled: bool,
|
||||
) -> None:
|
||||
self.name = name
|
||||
self.collect = collect
|
||||
self.interval = interval
|
||||
self.wandb_enabled = wandb_enabled
|
||||
self.task: asyncio.Task | None = None
|
||||
self.stopped = asyncio.Event()
|
||||
|
||||
if self.wandb_enabled:
|
||||
for key in metric_keys:
|
||||
wandb.define_metric(key, step_metric="_timestamp")
|
||||
|
||||
async def start(self) -> None:
|
||||
self.task = asyncio.create_task(self.run(), name=f"{self.name}_periodic_logger")
|
||||
|
||||
@@ -46,16 +37,17 @@ class PeriodicLogger:
|
||||
await asyncio.wait_for(self.stopped.wait(), timeout=self.interval)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
self.emit()
|
||||
await self.emit()
|
||||
except asyncio.CancelledError:
|
||||
return
|
||||
|
||||
def emit(self) -> None:
|
||||
async def emit(self) -> None:
|
||||
body, payload = self.collect()
|
||||
get_logger().info(body)
|
||||
if self.wandb_enabled and payload:
|
||||
payload["_timestamp"] = time.time()
|
||||
wandb.log(payload)
|
||||
if payload:
|
||||
# Time-keyed row: the pipeline view is sampled on wall time, not
|
||||
# the training step. Each monitor stamps its own time axis.
|
||||
await monitors.log(payload, step=None)
|
||||
|
||||
async def stop(self) -> None:
|
||||
self.stopped.set()
|
||||
|
||||
@@ -143,23 +143,6 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
|
||||
"""
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_vllm_kernel(
|
||||
cls,
|
||||
state_dict: dict[str, Tensor],
|
||||
layer_idx: int,
|
||||
quantize_fp8: bool = False,
|
||||
) -> dict[str, Tensor]:
|
||||
"""
|
||||
Convert a single layer's state dict from PrimeRL format to vLLM kernel format.
|
||||
|
||||
Args:
|
||||
state_dict: Layer weights in PrimeRL format.
|
||||
layer_idx: Layer index to convert.
|
||||
quantize_fp8: Whether to emit FP8 (e4m3) kernel weights with per-block scales.
|
||||
"""
|
||||
raise NotImplementedError(f"convert_layer_to_vllm_kernel is not implemented for {cls.__name__}")
|
||||
|
||||
def init_buffers_post_meta(self) -> None:
|
||||
"""
|
||||
Initialize buffers that are not in the state dict after loading with meta device.
|
||||
|
||||
@@ -713,8 +713,9 @@ class DeepseekV4Attention(nn.Module):
|
||||
cos, sin = packed.position_embeddings[self.rope_layer_type] # (1, t, qk_rope_head_dim // 2) each
|
||||
|
||||
q_residual = self.q_a_norm(self.q_a_proj(hidden_states)) # (b, t, r)
|
||||
q = self.q_b_proj(q_residual).view(*hidden_shape).transpose(1, 2) # (b, h, t, d)
|
||||
q = apply_rotary_pos_emb_interleaved(self.q_b_norm(q), cos, sin)
|
||||
# Normalizing before the transpose keeps the input contiguous for the quack kernel.
|
||||
q = self.q_b_norm(self.q_b_proj(q_residual).view(*hidden_shape)).transpose(1, 2) # (b, h, t, d)
|
||||
q = apply_rotary_pos_emb_interleaved(q, cos, sin)
|
||||
|
||||
kv = self.kv_norm(self.kv_proj(hidden_states)) # (b, t, d)
|
||||
kv = kv.view(*kv.shape[:2], 1, self.head_dim) # (b, t, 1, d)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Naive DeepSeek V4 attention reference.
|
||||
"""Naive DeepSeek V4 attention and mHC references.
|
||||
|
||||
Nothing in the production path calls these. They exist for the tests, where a dense, obviously
|
||||
correct implementation is the standard the fused kernel is measured against, and where it is the
|
||||
@@ -170,3 +170,25 @@ def use_eager_attention(module: nn.Module) -> None:
|
||||
for submodule in module.modules():
|
||||
if isinstance(submodule, DeepseekV4Attention):
|
||||
submodule.forward = types.MethodType(eager_attention_forward, submodule)
|
||||
|
||||
|
||||
def eager_sinkhorn(logits: Tensor, num_iterations: int, eps: float) -> Tensor:
|
||||
"""Project `logits` onto the doubly-stochastic manifold by alternating row and column sums."""
|
||||
comb = torch.softmax(logits, dim=-1) + eps
|
||||
comb = comb / (comb.sum(dim=-2, keepdim=True) + eps)
|
||||
for _ in range(num_iterations - 1):
|
||||
comb = comb / (comb.sum(dim=-1, keepdim=True) + eps)
|
||||
comb = comb / (comb.sum(dim=-2, keepdim=True) + eps)
|
||||
return comb
|
||||
|
||||
|
||||
def eager_update_states(post: Tensor, comb: Tensor, sublayer_out: Tensor, mhc_states: Tensor) -> Tensor:
|
||||
"""Broadcast the sublayer output over the streams via `post` and remix them via `comb`.
|
||||
|
||||
`comb` is consumed summing over the *source* stream axis, i.e. transposed; the fused kernel
|
||||
applies that transpose internally, so both take `comb` untransposed.
|
||||
"""
|
||||
dtype = mhc_states.dtype
|
||||
return post.to(dtype).unsqueeze(-1) * sublayer_out.unsqueeze(-2) + torch.matmul(
|
||||
comb.to(dtype).transpose(-1, -2), mhc_states
|
||||
)
|
||||
|
||||
@@ -3,23 +3,31 @@ import torch.nn.functional as F
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4 import dsv4_mhc
|
||||
from prime_rl.trainer.models.layers import norms
|
||||
|
||||
|
||||
class DeepseekV4UnweightedRMSNorm(nn.Module):
|
||||
"""RMS normalization without a learnable gain, computed in fp32."""
|
||||
|
||||
def __init__(self, eps: float = 1e-6):
|
||||
def __init__(self, eps: float = 1e-6, out_dtype: torch.dtype | None = None):
|
||||
super().__init__()
|
||||
self.eps = eps
|
||||
self.out_dtype = out_dtype
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return x * torch.rsqrt(x.float().square().mean(-1, keepdim=True) + self.eps).to(x.dtype)
|
||||
out_dtype = self.out_dtype if self.out_dtype is not None else x.dtype
|
||||
quack_rms = norms.get_quack_rmsnorm()
|
||||
if quack_rms is not None:
|
||||
return quack_rms(x, eps=self.eps, out_dtype=out_dtype)
|
||||
x = x.float()
|
||||
return (x * torch.rsqrt(x.square().mean(-1, keepdim=True) + self.eps)).to(out_dtype)
|
||||
|
||||
|
||||
class DeepseekV4HyperConnection(nn.Module):
|
||||
"""Manifold-constrained hyper-connection (mHC) around one sublayer.
|
||||
|
||||
The residual is `hc_mult` parallel streams shaped `(B, S, hc_mult, hidden_size)`.
|
||||
The residual, `mhc_states`, is `hc_mult` parallel streams shaped `(B, S, hc_mult, hidden_size)`.
|
||||
A single projection of the normalized, flattened streams produces three gates:
|
||||
|
||||
- `pre`: weights that collapse the streams into the single sequence fed to the
|
||||
@@ -39,16 +47,16 @@ class DeepseekV4HyperConnection(nn.Module):
|
||||
self.hc_mult = config.hc_mult
|
||||
self.hc_sinkhorn_iters = config.hc_sinkhorn_iters
|
||||
self.hc_eps = config.hc_eps
|
||||
self.input_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps)
|
||||
self.input_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps, out_dtype=torch.float32)
|
||||
mix = (2 + self.hc_mult) * self.hc_mult
|
||||
self.fn = nn.Parameter(torch.empty(mix, self.hc_mult * config.hidden_size))
|
||||
self.base = nn.Parameter(torch.empty(mix))
|
||||
# One scale per gate: `pre`, `post`, `comb`.
|
||||
self.scale = nn.Parameter(torch.empty(3))
|
||||
|
||||
def forward(self, hidden_streams: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
def forward(self, mhc_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
hc = self.hc_mult
|
||||
flat = self.input_norm(hidden_streams.flatten(start_dim=2).float())
|
||||
flat = self.input_norm(mhc_states.flatten(start_dim=2))
|
||||
pre_w, post_w, comb_w = F.linear(flat, self.fn.float()).split([hc, hc, hc * hc], dim=-1)
|
||||
pre_b, post_b, comb_b = self.base.split([hc, hc, hc * hc])
|
||||
pre_scale, post_scale, comb_scale = self.scale.unbind(0)
|
||||
@@ -56,15 +64,18 @@ class DeepseekV4HyperConnection(nn.Module):
|
||||
pre = torch.sigmoid(pre_w * pre_scale + pre_b) + self.hc_eps
|
||||
post = 2 * torch.sigmoid(post_w * post_scale + post_b)
|
||||
comb_logits = comb_w.view(*comb_w.shape[:-1], hc, hc) * comb_scale + comb_b.view(hc, hc)
|
||||
comb = torch.softmax(comb_logits, dim=-1) + self.hc_eps
|
||||
comb = comb / (comb.sum(dim=-2, keepdim=True) + self.hc_eps)
|
||||
for _ in range(self.hc_sinkhorn_iters - 1):
|
||||
comb = comb / (comb.sum(dim=-1, keepdim=True) + self.hc_eps)
|
||||
comb = comb / (comb.sum(dim=-2, keepdim=True) + self.hc_eps)
|
||||
comb = dsv4_mhc.fused_sinkhorn(comb_logits, self.hc_sinkhorn_iters, self.hc_eps)
|
||||
|
||||
collapsed = (pre.unsqueeze(-1) * hidden_streams).sum(dim=2).to(hidden_streams.dtype)
|
||||
collapsed = (pre.unsqueeze(-1) * mhc_states).sum(dim=2).to(mhc_states.dtype)
|
||||
return post, comb, collapsed
|
||||
|
||||
def update_states(
|
||||
self, post: torch.Tensor, comb: torch.Tensor, sublayer_out: torch.Tensor, mhc_states: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
"""Broadcast the sublayer output over the streams via `post` and remix them via `comb`."""
|
||||
dtype = mhc_states.dtype
|
||||
return dsv4_mhc.fused_post_bda(comb.to(dtype), mhc_states, post.to(dtype), sublayer_out)
|
||||
|
||||
def init_weights(self, init_std: float) -> None:
|
||||
nn.init.normal_(self.fn, mean=0.0, std=init_std)
|
||||
nn.init.zeros_(self.base)
|
||||
@@ -77,17 +88,17 @@ class DeepseekV4HyperHead(nn.Module):
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
super().__init__()
|
||||
self.hc_mult = config.hc_mult
|
||||
self.input_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps)
|
||||
self.input_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps, out_dtype=torch.float32)
|
||||
self.eps = config.hc_eps
|
||||
self.hc_fn = nn.Parameter(torch.empty(self.hc_mult, self.hc_mult * config.hidden_size))
|
||||
self.hc_base = nn.Parameter(torch.empty(self.hc_mult))
|
||||
self.hc_scale = nn.Parameter(torch.empty(1))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
flat = self.input_norm(x.flatten(2).float())
|
||||
def forward(self, mhc_states: torch.Tensor) -> torch.Tensor:
|
||||
flat = self.input_norm(mhc_states.flatten(2))
|
||||
mixes = F.linear(flat, self.hc_fn.float())
|
||||
pre = torch.sigmoid(mixes * self.hc_scale.float() + self.hc_base.float()) + self.eps
|
||||
return (pre.unsqueeze(-1) * x).sum(dim=2).to(x.dtype)
|
||||
return (pre.unsqueeze(-1) * mhc_states).sum(dim=2).to(mhc_states.dtype)
|
||||
|
||||
def init_weights(self, init_std: float) -> None:
|
||||
nn.init.normal_(self.hc_fn, mean=0.0, std=init_std)
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
|
||||
This is where the pieces built in `attention.py`, `moe.py`, `hyperconnections.py` and
|
||||
`rotary.py` come together. The one structural surprise is the residual: it is not a single
|
||||
stream but `hc_mult` parallel ones, carried as `(batch, seq, hc_mult, hidden)` from the
|
||||
embedding all the way to `hc_head`, which collapses them back before the final norm.
|
||||
stream but `hc_mult` parallel ones, carried as `mhc_states` of shape
|
||||
`(batch, seq, hc_mult, hidden)` from the embedding all the way to `hc_head`, which collapses
|
||||
them back before the final norm.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,7 +20,10 @@ from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, P
|
||||
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
|
||||
from prime_rl.trainer.models.deepseek_v4.converting_deepseek_v4 import conversion_chain
|
||||
from prime_rl.trainer.models.deepseek_v4.dequantize import dequantize_state_dict_
|
||||
from prime_rl.trainer.models.deepseek_v4.hyperconnections import DeepseekV4HyperConnection, DeepseekV4HyperHead
|
||||
from prime_rl.trainer.models.deepseek_v4.hyperconnections import (
|
||||
DeepseekV4HyperConnection,
|
||||
DeepseekV4HyperHead,
|
||||
)
|
||||
from prime_rl.trainer.models.deepseek_v4.moe import DeepseekV4MoE
|
||||
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
@@ -52,27 +56,21 @@ class DeepseekV4DecoderLayer(GradientCheckpointingLayer):
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
mhc_states: torch.Tensor,
|
||||
input_ids: torch.Tensor | None = None,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
*,
|
||||
packed: PackedContext,
|
||||
) -> torch.Tensor:
|
||||
dtype = hidden_states.dtype
|
||||
|
||||
post, comb, collapsed = self.attn_hc(hidden_states)
|
||||
post, comb, collapsed = self.attn_hc(mhc_states)
|
||||
attn_output, _ = self.self_attn(self.input_layernorm(collapsed), packed=packed)
|
||||
hidden_states = post.to(dtype).unsqueeze(-1) * attn_output.unsqueeze(-2) + torch.matmul(
|
||||
comb.to(dtype).transpose(-1, -2), hidden_states
|
||||
)
|
||||
mhc_states = self.attn_hc.update_states(post, comb, attn_output, mhc_states)
|
||||
|
||||
post, comb, collapsed = self.ffn_hc(hidden_states)
|
||||
post, comb, collapsed = self.ffn_hc(mhc_states)
|
||||
mlp_output = self.mlp(
|
||||
self.post_attention_layernorm(collapsed), input_ids=input_ids, routed_experts=routed_experts
|
||||
)
|
||||
return post.to(dtype).unsqueeze(-1) * mlp_output.unsqueeze(-2) + torch.matmul(
|
||||
comb.to(dtype).transpose(-1, -2), hidden_states
|
||||
)
|
||||
return self.ffn_hc.update_states(post, comb, mlp_output, mhc_states)
|
||||
|
||||
|
||||
# Mirrors HF's `_keep_in_fp32_modules_strict`, with `e_score_correction_bias` renamed to
|
||||
@@ -265,17 +263,17 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
|
||||
if position_ids is not None:
|
||||
packed.check_position_ids(position_ids)
|
||||
|
||||
hidden_states = inputs_embeds.unsqueeze(2).expand(-1, -1, self.config.hc_mult, -1).contiguous()
|
||||
mhc_states = inputs_embeds.unsqueeze(2).expand(-1, -1, self.config.hc_mult, -1).contiguous()
|
||||
for layer_idx, decoder_layer in enumerate(self.layers):
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
mhc_states = decoder_layer(
|
||||
mhc_states,
|
||||
input_ids=input_ids,
|
||||
routed_experts=routed_experts_layer,
|
||||
packed=packed,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(self.hc_head(hidden_states))
|
||||
hidden_states = self.norm(self.hc_head(mhc_states))
|
||||
return MoeModelOutputWithPast(last_hidden_state=hidden_states)
|
||||
|
||||
|
||||
|
||||
@@ -37,28 +37,3 @@ def quantize_to_fp8_blockwise(weight: Tensor, block_size: int = 128) -> tuple[Te
|
||||
|
||||
quantized = blocks_fp8.permute(0, 2, 1, 3).reshape(padded_rows, padded_cols)[:rows, :cols].contiguous()
|
||||
return quantized, scales.float().contiguous()
|
||||
|
||||
|
||||
def quantize_to_vllm_kernel_format(weight: Tensor, block_size: int = 128) -> tuple[Tensor, Tensor]:
|
||||
"""Quantize a weight into the FP8 layout used by vLLM kernels.
|
||||
|
||||
Hopper kernels consume the regular blockwise scale grid. On SM100, vLLM's
|
||||
DeepGEMM kernels instead use UE8M0 scales in an architecture-specific packed
|
||||
layout. Reuse vLLM's own post-processing so tensors sent over the kernel
|
||||
weight-transfer path have the same representation as the loaded parameters.
|
||||
"""
|
||||
quantized, scales = quantize_to_fp8_blockwise(weight, block_size)
|
||||
|
||||
if not weight.is_cuda or torch.cuda.get_device_capability(weight.device) != (10, 0):
|
||||
return quantized, scales
|
||||
|
||||
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
|
||||
deepgemm_post_process_fp8_weight_block,
|
||||
)
|
||||
|
||||
return deepgemm_post_process_fp8_weight_block(
|
||||
wq=quantized,
|
||||
ws=scales,
|
||||
quant_block_shape=(block_size, block_size),
|
||||
use_e8m0=True,
|
||||
)
|
||||
|
||||
@@ -6,11 +6,7 @@ parameters retain their names in both formats.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import ConvOp
|
||||
from prime_rl.trainer.models.fp8 import quantize_to_vllm_kernel_format
|
||||
from prime_rl.trainer.models.glm4_moe.converting_glm4_moe import glm_moe_layer_ops
|
||||
|
||||
|
||||
@@ -19,123 +15,3 @@ def conversion_chain(config) -> list[ConvOp]:
|
||||
for layer_idx in range(config.num_hidden_layers):
|
||||
ops.extend(glm_moe_layer_ops(layer_idx))
|
||||
return ops
|
||||
|
||||
|
||||
def convert_tt_layer_to_vllm_kernel(
|
||||
state_dict: dict[str, Tensor],
|
||||
layer_idx: int,
|
||||
quantize_fp8: bool = False,
|
||||
) -> dict[str, Tensor]:
|
||||
"""Convert a single GLM layer from PrimeRL format to vLLM kernel format."""
|
||||
out: dict[str, Tensor] = {}
|
||||
prefix = f"model.layers.{layer_idx}"
|
||||
|
||||
def add(name: str, tensor: Tensor) -> None:
|
||||
out[name] = tensor
|
||||
|
||||
def add_maybe_fp8(name: str, tensor: Tensor) -> None:
|
||||
if quantize_fp8 and tensor.ndim == 2:
|
||||
fp8_weight, scale = quantize_to_vllm_kernel_format(tensor)
|
||||
out[name] = fp8_weight
|
||||
scale_name = name.removesuffix(".weight") + ".weight_scale_inv"
|
||||
out[scale_name] = scale
|
||||
return
|
||||
out[name] = tensor
|
||||
|
||||
for name in [f"{prefix}.input_layernorm.weight", f"{prefix}.post_attention_layernorm.weight"]:
|
||||
if name in state_dict:
|
||||
add(name, state_dict[name])
|
||||
|
||||
q_a_key = f"{prefix}.self_attn.q_a_proj.weight"
|
||||
kv_a_key = f"{prefix}.self_attn.kv_a_proj_with_mqa.weight"
|
||||
if q_a_key in state_dict and kv_a_key in state_dict:
|
||||
add_maybe_fp8(
|
||||
f"{prefix}.self_attn.fused_qkv_a_proj.weight", torch.cat([state_dict[q_a_key], state_dict[kv_a_key]], dim=0)
|
||||
)
|
||||
|
||||
for suffix in ["q_a_layernorm.weight", "kv_a_layernorm.weight"]:
|
||||
key = f"{prefix}.self_attn.{suffix}"
|
||||
if key in state_dict:
|
||||
add(key, state_dict[key])
|
||||
|
||||
for suffix in ["q_b_proj.weight", "kv_b_proj.weight", "o_proj.weight"]:
|
||||
key = f"{prefix}.self_attn.{suffix}"
|
||||
if key in state_dict:
|
||||
add_maybe_fp8(key, state_dict[key])
|
||||
|
||||
indexer_wq_b_key = f"{prefix}.self_attn.indexer.wq_b.weight"
|
||||
if indexer_wq_b_key in state_dict:
|
||||
add_maybe_fp8(indexer_wq_b_key, state_dict[indexer_wq_b_key])
|
||||
|
||||
indexer_wk_key = f"{prefix}.self_attn.indexer.wk.weight"
|
||||
indexer_weights_proj_key = f"{prefix}.self_attn.indexer.weights_proj.weight"
|
||||
if indexer_wk_key in state_dict and indexer_weights_proj_key in state_dict:
|
||||
add(
|
||||
f"{prefix}.self_attn.indexer.wk_weights_proj.weight",
|
||||
torch.cat([state_dict[indexer_wk_key], state_dict[indexer_weights_proj_key]], dim=0),
|
||||
)
|
||||
for suffix in ["indexer.k_norm.weight", "indexer.k_norm.bias"]:
|
||||
key = f"{prefix}.self_attn.{suffix}"
|
||||
if key in state_dict:
|
||||
add(key, state_dict[key])
|
||||
|
||||
gate_key = f"{prefix}.mlp.gate_proj.weight"
|
||||
up_key = f"{prefix}.mlp.up_proj.weight"
|
||||
down_key = f"{prefix}.mlp.down_proj.weight"
|
||||
if gate_key in state_dict and up_key in state_dict:
|
||||
add_maybe_fp8(f"{prefix}.mlp.gate_up_proj.weight", torch.cat([state_dict[gate_key], state_dict[up_key]], dim=0))
|
||||
if down_key in state_dict:
|
||||
add_maybe_fp8(f"{prefix}.mlp.down_proj.weight", state_dict[down_key])
|
||||
|
||||
router_key = f"{prefix}.mlp.router.gate.weight"
|
||||
if router_key in state_dict:
|
||||
add(f"{prefix}.mlp.gate.weight", state_dict[router_key])
|
||||
selection_bias_key = f"{prefix}.mlp.router.selection_bias"
|
||||
if selection_bias_key in state_dict:
|
||||
add(f"{prefix}.mlp.gate.e_score_correction_bias", state_dict[selection_bias_key])
|
||||
|
||||
w1_key = f"{prefix}.mlp.experts.gate_proj"
|
||||
w2_key = f"{prefix}.mlp.experts.down_proj"
|
||||
w3_key = f"{prefix}.mlp.experts.up_proj"
|
||||
if w1_key in state_dict and w2_key in state_dict and w3_key in state_dict:
|
||||
w1 = state_dict[w1_key]
|
||||
w2 = state_dict[w2_key]
|
||||
w3 = state_dict[w3_key]
|
||||
w13 = torch.cat([w1, w3], dim=1)
|
||||
|
||||
if quantize_fp8:
|
||||
w13_fp8: list[Tensor] = []
|
||||
w13_scales: list[Tensor] = []
|
||||
w2_fp8: list[Tensor] = []
|
||||
w2_scales: list[Tensor] = []
|
||||
for expert_idx in range(w1.shape[0]):
|
||||
expert_w13_fp8, expert_w13_scales = quantize_to_vllm_kernel_format(w13[expert_idx])
|
||||
expert_w2_fp8, expert_w2_scales = quantize_to_vllm_kernel_format(w2[expert_idx])
|
||||
w13_fp8.append(expert_w13_fp8)
|
||||
w13_scales.append(expert_w13_scales)
|
||||
w2_fp8.append(expert_w2_fp8)
|
||||
w2_scales.append(expert_w2_scales)
|
||||
|
||||
out[f"{prefix}.mlp.experts.w13_weight"] = torch.stack(w13_fp8)
|
||||
out[f"{prefix}.mlp.experts.w13_weight_scale_inv"] = torch.stack(w13_scales)
|
||||
out[f"{prefix}.mlp.experts.w2_weight"] = torch.stack(w2_fp8)
|
||||
out[f"{prefix}.mlp.experts.w2_weight_scale_inv"] = torch.stack(w2_scales)
|
||||
else:
|
||||
out[f"{prefix}.mlp.experts.w13_weight"] = w13
|
||||
out[f"{prefix}.mlp.experts.w2_weight"] = w2
|
||||
|
||||
sw1_key = f"{prefix}.mlp.shared_expert.gate_proj.weight"
|
||||
sw2_key = f"{prefix}.mlp.shared_expert.down_proj.weight"
|
||||
sw3_key = f"{prefix}.mlp.shared_expert.up_proj.weight"
|
||||
if sw1_key in state_dict and sw2_key in state_dict and sw3_key in state_dict:
|
||||
sw1 = state_dict[sw1_key]
|
||||
sw2 = state_dict[sw2_key]
|
||||
sw3 = state_dict[sw3_key]
|
||||
if sw1.ndim == 3:
|
||||
sw1 = sw1.squeeze(0)
|
||||
sw2 = sw2.squeeze(0)
|
||||
sw3 = sw3.squeeze(0)
|
||||
add_maybe_fp8(f"{prefix}.mlp.shared_experts.gate_up_proj.weight", torch.cat([sw1, sw3], dim=0))
|
||||
add_maybe_fp8(f"{prefix}.mlp.shared_experts.down_proj.weight", sw2)
|
||||
|
||||
return out
|
||||
|
||||
@@ -14,10 +14,7 @@ from transformers.utils.deprecation import deprecate_kwarg
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.glm_moe_dsa.configuration_glm_moe_dsa import GlmMoeDsaConfig, _index_cache_skip_topk
|
||||
from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import (
|
||||
conversion_chain,
|
||||
convert_tt_layer_to_vllm_kernel,
|
||||
)
|
||||
from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import conversion_chain
|
||||
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import GlmMoeDsaAttention, SparseMlaAttentionArgs
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
@@ -153,12 +150,6 @@ class GlmMoeDsaPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
def conversion_chain(cls, config):
|
||||
return conversion_chain(config)
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_vllm_kernel(
|
||||
cls, state_dict: dict[str, Tensor], layer_idx: int, quantize_fp8: bool = False
|
||||
) -> dict[str, Tensor]:
|
||||
return convert_tt_layer_to_vllm_kernel(state_dict, layer_idx, quantize_fp8=quantize_fp8)
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
|
||||
|
||||
@@ -0,0 +1,646 @@
|
||||
# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions
|
||||
# are met:
|
||||
# * Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
# * Redistributions in binary form must reproduce the above copyright
|
||||
# notice, this list of conditions and the following disclaimer in the
|
||||
# documentation and/or other materials provided with the distribution.
|
||||
# * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
# contributors may be used to endorse or promote products derived
|
||||
# from this software without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
#
|
||||
# Triton kernels vendored from NVIDIA/Megatron-LM under the BSD-3-clause license
|
||||
# reproduced above, megatron/core/fusions/fused_mhc_kernels.py at commit bb5dfd08f,
|
||||
# trimmed to the Sinkhorn-Knopp and h_post_bda fusions and rewrapped as the
|
||||
# `prime_rl::dsv4_mhc_*` custom ops.
|
||||
|
||||
import math
|
||||
|
||||
import torch
|
||||
import triton
|
||||
import triton.language as tl
|
||||
|
||||
LOG2E = math.log2(math.e)
|
||||
TLOG2E = tl.constexpr(LOG2E)
|
||||
|
||||
|
||||
@triton.autotune(configs=[triton.Config({}, num_warps=nw) for nw in (1, 2, 4, 8)], key=["HC", "NUM_ITERS"])
|
||||
@triton.jit
|
||||
def _triton_sinkhorn_fwd_kernel(inp_ptr, out_ptr, M_init_ptr, N_batch, eps, HC: tl.constexpr, NUM_ITERS: tl.constexpr):
|
||||
"""Grid: (N_batch,). Each program handles one [HC, HC] matrix."""
|
||||
pid = tl.program_id(0)
|
||||
if pid >= N_batch:
|
||||
return
|
||||
|
||||
base = pid * HC * HC
|
||||
offs_r = tl.arange(0, HC)
|
||||
offs_c = tl.arange(0, HC)
|
||||
mat_ptrs = base + offs_r[:, None] * HC + offs_c[None, :]
|
||||
|
||||
logits = tl.load(inp_ptr + mat_ptrs).to(tl.float32)
|
||||
row_max = tl.max(logits, axis=1)
|
||||
# Subtract row_max before exp to keep the exponent numerically stable.
|
||||
M = tl.exp2((logits - row_max[:, None]) * TLOG2E)
|
||||
tl.store(M_init_ptr + mat_ptrs, M.to(M_init_ptr.dtype.element_ty))
|
||||
|
||||
row_sum = tl.sum(M, axis=1)
|
||||
M = M / row_sum[:, None] + eps
|
||||
col_sum = tl.sum(M, axis=0)
|
||||
M = M / (col_sum[None, :] + eps)
|
||||
for _ in range(NUM_ITERS - 1):
|
||||
row_sum = tl.sum(M, axis=1)
|
||||
M = M / (row_sum[:, None] + eps)
|
||||
col_sum = tl.sum(M, axis=0)
|
||||
M = M / (col_sum[None, :] + eps)
|
||||
|
||||
tl.store(out_ptr + mat_ptrs, M.to(out_ptr.dtype.element_ty))
|
||||
|
||||
|
||||
@triton.autotune(configs=[triton.Config({}, num_warps=nw) for nw in (1, 2, 4, 8)], key=["HC", "NUM_ITERS"])
|
||||
@triton.jit
|
||||
def _triton_sinkhorn_bwd_kernel(
|
||||
grad_out_ptr,
|
||||
M_init_ptr,
|
||||
grad_inp_ptr,
|
||||
ws_M_ptr,
|
||||
ws_rs_ptr,
|
||||
ws_cs_ptr,
|
||||
N_batch,
|
||||
eps,
|
||||
HC: tl.constexpr,
|
||||
NUM_ITERS: tl.constexpr,
|
||||
):
|
||||
"""Grid: (N_batch,). Each program handles one [HC, HC] backward."""
|
||||
pid = tl.program_id(0)
|
||||
if pid >= N_batch:
|
||||
return
|
||||
|
||||
base = pid * HC * HC
|
||||
M_ws_base = pid * 2 * NUM_ITERS * HC * HC
|
||||
v_ws_base = pid * NUM_ITERS
|
||||
offs_r = tl.arange(0, HC)
|
||||
offs_c = tl.arange(0, HC)
|
||||
mat_ptrs = base + offs_r[:, None] * HC + offs_c[None, :]
|
||||
|
||||
M = tl.load(M_init_ptr + mat_ptrs).to(tl.float32)
|
||||
for t in range(NUM_ITERS):
|
||||
ws_off = M_ws_base + (2 * t) * HC * HC
|
||||
tl.store(ws_M_ptr + ws_off + offs_r[:, None] * HC + offs_c[None, :], M)
|
||||
|
||||
row_sum = tl.sum(M, axis=1)
|
||||
tl.store(ws_rs_ptr + (v_ws_base + t) * HC + offs_r, row_sum)
|
||||
if t == 0:
|
||||
M = M / row_sum[:, None] + eps
|
||||
else:
|
||||
M = M / (row_sum[:, None] + eps)
|
||||
|
||||
ws_off = M_ws_base + (2 * t + 1) * HC * HC
|
||||
tl.store(ws_M_ptr + ws_off + offs_r[:, None] * HC + offs_c[None, :], M)
|
||||
|
||||
col_sum = tl.sum(M, axis=0)
|
||||
tl.store(ws_cs_ptr + (v_ws_base + t) * HC + offs_c, col_sum)
|
||||
M = M / (col_sum[None, :] + eps)
|
||||
|
||||
# M is the final forward output. It is the right value for the first VJP
|
||||
# through the last column-normalization step.
|
||||
grad = tl.load(grad_out_ptr + mat_ptrs).to(tl.float32)
|
||||
for t_rev in range(NUM_ITERS):
|
||||
t = NUM_ITERS - 1 - t_rev
|
||||
|
||||
col_s = tl.load(ws_cs_ptr + (v_ws_base + t) * HC + offs_c).to(tl.float32)
|
||||
grad = grad / (col_s[None, :] + eps)
|
||||
col_corr = tl.sum(grad * M, axis=0)
|
||||
grad = grad - col_corr[None, :]
|
||||
M = tl.load(ws_M_ptr + M_ws_base + (2 * t + 1) * HC * HC + offs_r[:, None] * HC + offs_c[None, :]).to(
|
||||
tl.float32
|
||||
)
|
||||
|
||||
row_s = tl.load(ws_rs_ptr + (v_ws_base + t) * HC + offs_r).to(tl.float32)
|
||||
if t == 0:
|
||||
grad = grad / row_s[:, None]
|
||||
row_corr = tl.sum(grad * (M - eps), axis=1)
|
||||
else:
|
||||
grad = grad / (row_s[:, None] + eps)
|
||||
row_corr = tl.sum(grad * M, axis=1)
|
||||
grad = grad - row_corr[:, None]
|
||||
M = tl.load(ws_M_ptr + M_ws_base + (2 * t) * HC * HC + offs_r[:, None] * HC + offs_c[None, :]).to(tl.float32)
|
||||
|
||||
M_init = tl.load(M_init_ptr + mat_ptrs).to(tl.float32)
|
||||
grad = grad * M_init
|
||||
tl.store(grad_inp_ptr + mat_ptrs, grad.to(grad_inp_ptr.dtype.element_ty))
|
||||
|
||||
|
||||
def _triton_sinkhorn_fwd(
|
||||
input_logits: torch.Tensor, num_iterations: int, eps: float
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
original_shape = input_logits.shape
|
||||
hc = original_shape[-1]
|
||||
N_batch = input_logits.numel() // (hc * hc)
|
||||
dev = input_logits.device
|
||||
out = torch.empty(N_batch, hc, hc, dtype=input_logits.dtype, device=dev)
|
||||
M_init = torch.empty(N_batch, hc, hc, dtype=input_logits.dtype, device=dev)
|
||||
inp = input_logits.contiguous().view(N_batch, hc, hc)
|
||||
_triton_sinkhorn_fwd_kernel[(N_batch,)](inp, out, M_init, N_batch, eps, hc, num_iterations)
|
||||
return out.view(original_shape), M_init.view(original_shape)
|
||||
|
||||
|
||||
def _triton_sinkhorn_bwd(
|
||||
grad_output: torch.Tensor, M_init: torch.Tensor, num_iterations: int, eps: float
|
||||
) -> torch.Tensor:
|
||||
original_shape = grad_output.shape
|
||||
hc = original_shape[-1]
|
||||
N_batch = grad_output.numel() // (hc * hc)
|
||||
dev = grad_output.device
|
||||
grad_input = torch.empty(N_batch, hc, hc, dtype=grad_output.dtype, device=dev)
|
||||
go = grad_output.contiguous().view(N_batch, hc, hc)
|
||||
mi = M_init.contiguous().view(N_batch, hc, hc)
|
||||
ws_M = torch.empty(N_batch * 2 * num_iterations * hc * hc, dtype=torch.float32, device=dev)
|
||||
ws_rs = torch.empty(N_batch * num_iterations * hc, dtype=torch.float32, device=dev)
|
||||
ws_cs = torch.empty(N_batch * num_iterations * hc, dtype=torch.float32, device=dev)
|
||||
_triton_sinkhorn_bwd_kernel[(N_batch,)](go, mi, grad_input, ws_M, ws_rs, ws_cs, N_batch, eps, hc, num_iterations)
|
||||
return grad_input.view(original_shape)
|
||||
|
||||
|
||||
@triton.autotune(
|
||||
configs=[
|
||||
triton.Config({"BLOCK_C": bc, "BLOCK_S": bs}, num_warps=nw)
|
||||
for bc in (64, 128, 256, 512)
|
||||
for bs in (1, 2, 4, 8)
|
||||
for nw in (2, 4, 8)
|
||||
],
|
||||
key=["C", "N"],
|
||||
)
|
||||
@triton.jit
|
||||
def _triton_hpb_fwd_kernel(
|
||||
hr_ptr,
|
||||
orig_ptr,
|
||||
hp_ptr,
|
||||
x_ptr,
|
||||
bias_ptr,
|
||||
out_ptr,
|
||||
sb,
|
||||
C: tl.constexpr,
|
||||
N: tl.constexpr,
|
||||
stride_hr_s,
|
||||
stride_hr_i,
|
||||
stride_hr_j,
|
||||
stride_orig_s,
|
||||
stride_orig_n,
|
||||
stride_orig_c,
|
||||
stride_out_s,
|
||||
stride_out_n,
|
||||
stride_out_c,
|
||||
HAS_BIAS: tl.constexpr,
|
||||
BLOCK_C: tl.constexpr,
|
||||
BLOCK_S: tl.constexpr,
|
||||
):
|
||||
"""out = hr.T @ orig + hp * (x + bias)."""
|
||||
pid_s = tl.program_id(0)
|
||||
pid_c = tl.program_id(1)
|
||||
offs_s = pid_s * BLOCK_S + tl.arange(0, BLOCK_S)
|
||||
offs_c = pid_c * BLOCK_C + tl.arange(0, BLOCK_C)
|
||||
mask_s = offs_s < sb
|
||||
mask_c = offs_c < C
|
||||
mask_2d = mask_s[:, None] & mask_c[None, :]
|
||||
|
||||
x_tile = tl.load(x_ptr + offs_s[:, None] * C + offs_c[None, :], mask=mask_2d, other=0.0).to(tl.float32)
|
||||
if HAS_BIAS:
|
||||
bias_tile = tl.load(bias_ptr + offs_c, mask=mask_c, other=0.0).to(tl.float32)
|
||||
x_tile += bias_tile[None, :]
|
||||
|
||||
for i in tl.static_range(N):
|
||||
hp_i = tl.load(hp_ptr + offs_s * N + i, mask=mask_s, other=0.0).to(tl.float32)
|
||||
out_i = hp_i[:, None] * x_tile
|
||||
|
||||
for j in tl.static_range(N):
|
||||
hr_ji = tl.load(
|
||||
hr_ptr + offs_s * stride_hr_s + j * stride_hr_i + i * stride_hr_j,
|
||||
mask=mask_s,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
orig_j = tl.load(
|
||||
orig_ptr + offs_s[:, None] * stride_orig_s + j * stride_orig_n + offs_c[None, :],
|
||||
mask=mask_2d,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
out_i += hr_ji[:, None] * orig_j
|
||||
|
||||
tl.store(
|
||||
out_ptr + offs_s[:, None] * stride_out_s + i * stride_out_n + offs_c[None, :],
|
||||
out_i.to(out_ptr.dtype.element_ty),
|
||||
mask=mask_2d,
|
||||
)
|
||||
|
||||
|
||||
def _triton_h_post_bda_fwd(
|
||||
h_res: torch.Tensor, original_residual: torch.Tensor, h_post: torch.Tensor, x: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
s, b, n, C = original_residual.shape
|
||||
sb = s * b
|
||||
dev = h_res.device
|
||||
out = torch.empty(sb, n, C, dtype=h_res.dtype, device=dev)
|
||||
hr_flat = h_res.contiguous().view(sb, n, n)
|
||||
orig_flat = original_residual.contiguous().view(sb, n, C)
|
||||
hp_flat = h_post.contiguous().view(sb, n)
|
||||
x_flat = x.contiguous().view(sb, C)
|
||||
|
||||
grid = lambda META: (triton.cdiv(sb, META["BLOCK_S"]), triton.cdiv(C, META["BLOCK_C"]))
|
||||
_triton_hpb_fwd_kernel[grid](
|
||||
hr_flat,
|
||||
orig_flat,
|
||||
hp_flat,
|
||||
x_flat,
|
||||
x_flat,
|
||||
out,
|
||||
sb,
|
||||
C,
|
||||
n,
|
||||
hr_flat.stride(0),
|
||||
hr_flat.stride(1),
|
||||
hr_flat.stride(2),
|
||||
orig_flat.stride(0),
|
||||
orig_flat.stride(1),
|
||||
orig_flat.stride(2),
|
||||
out.stride(0),
|
||||
out.stride(1),
|
||||
out.stride(2),
|
||||
HAS_BIAS=False,
|
||||
)
|
||||
return out.view(s, b, n, C)
|
||||
|
||||
|
||||
@triton.autotune(
|
||||
configs=[
|
||||
triton.Config({"BLOCK_C": bc, "BLOCK_S": bs}, num_warps=nw)
|
||||
for bc in (64, 128, 256, 512)
|
||||
for bs in (1, 2, 4, 8)
|
||||
for nw in (2, 4, 8)
|
||||
],
|
||||
key=["C", "N"],
|
||||
)
|
||||
@triton.jit
|
||||
def _triton_hpb_bwd_g_x_orig_kernel(
|
||||
go_ptr,
|
||||
hr_ptr,
|
||||
hp_ptr,
|
||||
g_orig_ptr,
|
||||
g_x_ptr,
|
||||
sb,
|
||||
C: tl.constexpr,
|
||||
N: tl.constexpr,
|
||||
stride_go_s,
|
||||
stride_go_n,
|
||||
stride_go_c,
|
||||
stride_hr_s,
|
||||
stride_hr_i,
|
||||
stride_hr_j,
|
||||
stride_orig_s,
|
||||
stride_orig_n,
|
||||
stride_orig_c,
|
||||
BLOCK_C: tl.constexpr,
|
||||
BLOCK_S: tl.constexpr,
|
||||
):
|
||||
"""g_x = hp @ go, g_orig = hr @ go."""
|
||||
pid_s = tl.program_id(0)
|
||||
pid_c = tl.program_id(1)
|
||||
offs_s = pid_s * BLOCK_S + tl.arange(0, BLOCK_S)
|
||||
offs_c = pid_c * BLOCK_C + tl.arange(0, BLOCK_C)
|
||||
mask_s = offs_s < sb
|
||||
mask_c = offs_c < C
|
||||
mask_2d = mask_s[:, None] & mask_c[None, :]
|
||||
|
||||
g_x_acc = tl.zeros((BLOCK_S, BLOCK_C), dtype=tl.float32)
|
||||
for j in tl.static_range(N):
|
||||
go_j = tl.load(
|
||||
go_ptr + offs_s[:, None] * stride_go_s + j * stride_go_n + offs_c[None, :],
|
||||
mask=mask_2d,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
hp_j = tl.load(hp_ptr + offs_s * N + j, mask=mask_s, other=0.0).to(tl.float32)
|
||||
g_x_acc += hp_j[:, None] * go_j
|
||||
tl.store(
|
||||
g_x_ptr + offs_s[:, None] * C + offs_c[None, :],
|
||||
g_x_acc.to(g_x_ptr.dtype.element_ty),
|
||||
mask=mask_2d,
|
||||
)
|
||||
|
||||
for i in tl.static_range(N):
|
||||
g_orig_i = tl.zeros((BLOCK_S, BLOCK_C), dtype=tl.float32)
|
||||
for j in tl.static_range(N):
|
||||
go_j = tl.load(
|
||||
go_ptr + offs_s[:, None] * stride_go_s + j * stride_go_n + offs_c[None, :],
|
||||
mask=mask_2d,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
hr_ij = tl.load(
|
||||
hr_ptr + offs_s * stride_hr_s + i * stride_hr_i + j * stride_hr_j,
|
||||
mask=mask_s,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
g_orig_i += hr_ij[:, None] * go_j
|
||||
tl.store(
|
||||
g_orig_ptr + offs_s[:, None] * stride_orig_s + i * stride_orig_n + offs_c[None, :],
|
||||
g_orig_i.to(g_orig_ptr.dtype.element_ty),
|
||||
mask=mask_2d,
|
||||
)
|
||||
|
||||
|
||||
@triton.autotune(
|
||||
configs=[
|
||||
triton.Config({"BLOCK_C": bc, "BLOCK_S": bs}, num_warps=nw)
|
||||
for bc in (64, 128, 256, 512)
|
||||
for bs in (1, 2, 4, 8)
|
||||
for nw in (2, 4, 8)
|
||||
],
|
||||
key=["C", "N"],
|
||||
)
|
||||
@triton.jit
|
||||
def _triton_hpb_bwd_g_hp_hr_kernel(
|
||||
go_ptr,
|
||||
orig_ptr,
|
||||
x_ptr,
|
||||
bias_ptr,
|
||||
g_hr_ptr,
|
||||
g_hp_ptr,
|
||||
sb,
|
||||
C: tl.constexpr,
|
||||
N: tl.constexpr,
|
||||
stride_go_s,
|
||||
stride_go_n,
|
||||
stride_go_c,
|
||||
stride_orig_s,
|
||||
stride_orig_n,
|
||||
stride_orig_c,
|
||||
stride_hr_s,
|
||||
stride_hr_i,
|
||||
stride_hr_j,
|
||||
HAS_BIAS: tl.constexpr,
|
||||
BLOCK_C: tl.constexpr,
|
||||
BLOCK_S: tl.constexpr,
|
||||
):
|
||||
"""g_hp = sum_c go*(x+bias), g_hr = orig @ go.T."""
|
||||
pid_s = tl.program_id(0)
|
||||
offs_s = pid_s * BLOCK_S + tl.arange(0, BLOCK_S)
|
||||
mask_s = offs_s < sb
|
||||
|
||||
g_hp_acc = tl.zeros((BLOCK_S, N), dtype=tl.float32)
|
||||
g_hr_acc = tl.zeros((BLOCK_S, N * N), dtype=tl.float32)
|
||||
|
||||
for c_start in range(0, C, BLOCK_C):
|
||||
offs_c = c_start + tl.arange(0, BLOCK_C)
|
||||
mask_c = offs_c < C
|
||||
mask_2d = mask_s[:, None] & mask_c[None, :]
|
||||
|
||||
x_tile = tl.load(x_ptr + offs_s[:, None] * C + offs_c[None, :], mask=mask_2d, other=0.0).to(tl.float32)
|
||||
if HAS_BIAS:
|
||||
bias_tile = tl.load(bias_ptr + offs_c, mask=mask_c, other=0.0).to(tl.float32)
|
||||
x_tile += bias_tile[None, :]
|
||||
|
||||
for i in tl.static_range(N):
|
||||
go_i = tl.load(
|
||||
go_ptr + offs_s[:, None] * stride_go_s + i * stride_go_n + offs_c[None, :],
|
||||
mask=mask_2d,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
dot_hp = tl.sum(go_i * x_tile, axis=1)
|
||||
g_hp_acc += tl.where(
|
||||
tl.arange(0, N)[None, :] == i,
|
||||
dot_hp[:, None],
|
||||
tl.zeros((BLOCK_S, N), dtype=tl.float32),
|
||||
)
|
||||
for j in tl.static_range(N):
|
||||
orig_j = tl.load(
|
||||
orig_ptr + offs_s[:, None] * stride_orig_s + j * stride_orig_n + offs_c[None, :],
|
||||
mask=mask_2d,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
dot_hr = tl.sum(go_i * orig_j, axis=1)
|
||||
g_hr_acc += tl.where(
|
||||
tl.arange(0, N * N)[None, :] == j * N + i,
|
||||
dot_hr[:, None],
|
||||
tl.zeros((BLOCK_S, N * N), dtype=tl.float32),
|
||||
)
|
||||
|
||||
offs_n = tl.arange(0, N)
|
||||
tl.store(
|
||||
g_hp_ptr + offs_s[:, None] * N + offs_n[None, :],
|
||||
g_hp_acc.to(g_hp_ptr.dtype.element_ty),
|
||||
mask=mask_s[:, None],
|
||||
)
|
||||
|
||||
# N is expected to stay small for mHC, so this simple extraction is acceptable.
|
||||
nn_offs = tl.arange(0, N * N)
|
||||
for i in tl.static_range(N):
|
||||
for j in tl.static_range(N):
|
||||
col_mask = (nn_offs == (i * N + j)).to(tl.float32)
|
||||
val = tl.sum(g_hr_acc * col_mask[None, :], axis=1)
|
||||
tl.store(
|
||||
g_hr_ptr + offs_s * stride_hr_s + i * stride_hr_i + j * stride_hr_j,
|
||||
val.to(g_hr_ptr.dtype.element_ty),
|
||||
mask=mask_s,
|
||||
)
|
||||
|
||||
|
||||
def _triton_h_post_bda_bwd(
|
||||
grad_output: torch.Tensor,
|
||||
h_res: torch.Tensor,
|
||||
original_residual: torch.Tensor,
|
||||
h_post: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
s, b, n, C = original_residual.shape
|
||||
sb = s * b
|
||||
dev = h_res.device
|
||||
|
||||
g_hr = torch.empty(sb, n, n, dtype=h_res.dtype, device=dev)
|
||||
g_res = torch.empty(sb, n, C, dtype=original_residual.dtype, device=dev)
|
||||
g_hp = torch.empty(sb, n, dtype=h_post.dtype, device=dev)
|
||||
g_x = torch.empty(sb, C, dtype=x.dtype, device=dev)
|
||||
|
||||
go_flat = grad_output.contiguous().view(sb, n, C)
|
||||
hr_flat = h_res.contiguous().view(sb, n, n)
|
||||
orig_flat = original_residual.contiguous().view(sb, n, C)
|
||||
hp_flat = h_post.contiguous().view(sb, n)
|
||||
x_flat = x.contiguous().view(sb, C)
|
||||
|
||||
grid_a = lambda META: (triton.cdiv(sb, META["BLOCK_S"]), triton.cdiv(C, META["BLOCK_C"]))
|
||||
_triton_hpb_bwd_g_x_orig_kernel[grid_a](
|
||||
go_flat,
|
||||
hr_flat,
|
||||
hp_flat,
|
||||
g_res,
|
||||
g_x,
|
||||
sb,
|
||||
C,
|
||||
n,
|
||||
go_flat.stride(0),
|
||||
go_flat.stride(1),
|
||||
go_flat.stride(2),
|
||||
hr_flat.stride(0),
|
||||
hr_flat.stride(1),
|
||||
hr_flat.stride(2),
|
||||
g_res.stride(0),
|
||||
g_res.stride(1),
|
||||
g_res.stride(2),
|
||||
)
|
||||
|
||||
grid_b = lambda META: (triton.cdiv(sb, META["BLOCK_S"]),)
|
||||
_triton_hpb_bwd_g_hp_hr_kernel[grid_b](
|
||||
go_flat,
|
||||
orig_flat,
|
||||
x_flat,
|
||||
x_flat,
|
||||
g_hr,
|
||||
g_hp,
|
||||
sb,
|
||||
C,
|
||||
n,
|
||||
go_flat.stride(0),
|
||||
go_flat.stride(1),
|
||||
go_flat.stride(2),
|
||||
orig_flat.stride(0),
|
||||
orig_flat.stride(1),
|
||||
orig_flat.stride(2),
|
||||
g_hr.stride(0),
|
||||
g_hr.stride(1),
|
||||
g_hr.stride(2),
|
||||
HAS_BIAS=False,
|
||||
)
|
||||
|
||||
return (
|
||||
g_hr.view(s, b, n, n),
|
||||
g_res.view(s, b, n, C),
|
||||
g_hp.view(s, b, n),
|
||||
g_x.view(s, b, C),
|
||||
)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl::dsv4_mhc_sinkhorn", mutates_args=())
|
||||
def _mhc_sinkhorn(logits: torch.Tensor, num_iterations: int, eps: float) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return _triton_sinkhorn_fwd(logits, num_iterations, eps)
|
||||
|
||||
|
||||
@_mhc_sinkhorn.register_fake
|
||||
def _mhc_sinkhorn_fake(logits: torch.Tensor, num_iterations: int, eps: float) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return torch.empty_like(logits), torch.empty_like(logits)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl::dsv4_mhc_sinkhorn_backward", mutates_args=())
|
||||
def _mhc_sinkhorn_backward(
|
||||
grad_output: torch.Tensor, m_init: torch.Tensor, num_iterations: int, eps: float
|
||||
) -> torch.Tensor:
|
||||
return _triton_sinkhorn_bwd(grad_output, m_init, num_iterations, eps)
|
||||
|
||||
|
||||
@_mhc_sinkhorn_backward.register_fake
|
||||
def _mhc_sinkhorn_backward_fake(
|
||||
grad_output: torch.Tensor, m_init: torch.Tensor, num_iterations: int, eps: float
|
||||
) -> torch.Tensor:
|
||||
return torch.empty_like(grad_output)
|
||||
|
||||
|
||||
def _mhc_sinkhorn_setup_context(ctx, inputs, output) -> None:
|
||||
_, num_iterations, eps = inputs
|
||||
ctx.save_for_backward(output[1])
|
||||
ctx.num_iterations = num_iterations
|
||||
ctx.eps = eps
|
||||
|
||||
|
||||
def _mhc_sinkhorn_autograd_backward(ctx, grad_output: torch.Tensor, grad_m_init: torch.Tensor):
|
||||
(m_init,) = ctx.saved_tensors
|
||||
grad_logits = _mhc_sinkhorn_backward(grad_output, m_init, ctx.num_iterations, ctx.eps)
|
||||
return grad_logits, None, None
|
||||
|
||||
|
||||
_mhc_sinkhorn.register_autograd(_mhc_sinkhorn_autograd_backward, setup_context=_mhc_sinkhorn_setup_context)
|
||||
|
||||
|
||||
def fused_sinkhorn(logits: torch.Tensor, num_iterations: int, eps: float) -> torch.Tensor:
|
||||
"""Project logits onto the doubly stochastic manifold, one Triton program per matrix."""
|
||||
out, _ = _mhc_sinkhorn(logits, num_iterations, eps)
|
||||
return out
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl::dsv4_mhc_post_bda", mutates_args=())
|
||||
def _mhc_post_bda(
|
||||
h_res: torch.Tensor, original_residual: torch.Tensor, h_post: torch.Tensor, x: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
return _triton_h_post_bda_fwd(h_res, original_residual, h_post, x)
|
||||
|
||||
|
||||
@_mhc_post_bda.register_fake
|
||||
def _mhc_post_bda_fake(
|
||||
h_res: torch.Tensor, original_residual: torch.Tensor, h_post: torch.Tensor, x: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
return torch.empty_like(original_residual, dtype=h_res.dtype)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl::dsv4_mhc_post_bda_backward", mutates_args=())
|
||||
def _mhc_post_bda_backward(
|
||||
grad_output: torch.Tensor,
|
||||
h_res: torch.Tensor,
|
||||
original_residual: torch.Tensor,
|
||||
h_post: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
return _triton_h_post_bda_bwd(grad_output, h_res, original_residual, h_post, x)
|
||||
|
||||
|
||||
@_mhc_post_bda_backward.register_fake
|
||||
def _mhc_post_bda_backward_fake(
|
||||
grad_output: torch.Tensor,
|
||||
h_res: torch.Tensor,
|
||||
original_residual: torch.Tensor,
|
||||
h_post: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
return (
|
||||
torch.empty_like(h_res),
|
||||
torch.empty_like(original_residual),
|
||||
torch.empty_like(h_post),
|
||||
torch.empty_like(x),
|
||||
)
|
||||
|
||||
|
||||
def _mhc_post_bda_setup_context(ctx, inputs, output) -> None:
|
||||
h_res, original_residual, h_post, x = inputs
|
||||
ctx.save_for_backward(h_res, original_residual, h_post, x)
|
||||
|
||||
|
||||
def _mhc_post_bda_autograd_backward(ctx, grad_output: torch.Tensor):
|
||||
h_res, original_residual, h_post, x = ctx.saved_tensors
|
||||
needs = ctx.needs_input_grad
|
||||
g_hr, g_res, g_hp, g_x = _mhc_post_bda_backward(grad_output, h_res, original_residual, h_post, x)
|
||||
return (
|
||||
g_hr if needs[0] else None,
|
||||
g_res if needs[1] else None,
|
||||
g_hp if needs[2] else None,
|
||||
g_x if needs[3] else None,
|
||||
)
|
||||
|
||||
|
||||
_mhc_post_bda.register_autograd(_mhc_post_bda_autograd_backward, setup_context=_mhc_post_bda_setup_context)
|
||||
|
||||
|
||||
def fused_post_bda(
|
||||
h_res: torch.Tensor, original_residual: torch.Tensor, h_post: torch.Tensor, x: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
"""Fused stream write-back `h_res.T @ original_residual + h_post * x`.
|
||||
|
||||
The kernel applies the transpose internally, so `h_res` is passed untransposed.
|
||||
"""
|
||||
return _mhc_post_bda(h_res, original_residual, h_post, x)
|
||||
@@ -22,9 +22,9 @@ def _per_token_group_quant_fp8(
|
||||
group_size,
|
||||
y_num_columns,
|
||||
y_row_stride,
|
||||
eps,
|
||||
fp8_min,
|
||||
fp8_max,
|
||||
eps: tl.constexpr,
|
||||
fp8_min: tl.constexpr,
|
||||
fp8_max: tl.constexpr,
|
||||
use_ue8m0: tl.constexpr,
|
||||
BLOCK: tl.constexpr,
|
||||
):
|
||||
|
||||
@@ -17,7 +17,7 @@ from prime_rl.trainer.models.kernels.fp8_utils import (
|
||||
def _compute_grad_weight(
|
||||
x: torch.Tensor,
|
||||
grad_output: torch.Tensor,
|
||||
weight_shape: torch.Size,
|
||||
weight: torch.Tensor,
|
||||
padded_total_m: int,
|
||||
block_to_group: torch.Tensor,
|
||||
ks_tensor: torch.Tensor,
|
||||
@@ -78,7 +78,7 @@ def _compute_grad_weight(
|
||||
)
|
||||
grouped_weight_grad = deep_gemm.k_grouped_fp8_gemm_nt_contiguous
|
||||
|
||||
grad_weight = torch.zeros(weight_shape, device=x.device, dtype=torch.float32)
|
||||
grad_weight = torch.zeros(weight.shape, device=x.device, dtype=torch.float32)
|
||||
grouped_weight_grad(
|
||||
x_fp8,
|
||||
dy_fp8,
|
||||
@@ -87,7 +87,7 @@ def _compute_grad_weight(
|
||||
ks_tensor,
|
||||
grad_weight,
|
||||
)
|
||||
return grad_weight.to(torch.bfloat16)
|
||||
return grad_weight.to(weight.dtype)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl::grouped_fp8_gemm", mutates_args=())
|
||||
@@ -165,14 +165,14 @@ def _grouped_fp8_gemm_backward(
|
||||
block_starts_tensor,
|
||||
) = build_grouped_layout(offs, total_m=x.size(0))
|
||||
grad_output = grad_output.contiguous()
|
||||
grad_x = torch.empty_like(x)
|
||||
grad_weight = torch.empty_like(weight)
|
||||
grad_x = x.new_empty(x.shape)
|
||||
grad_weight = weight.new_empty(weight.shape)
|
||||
|
||||
if needs_grad_weight:
|
||||
grad_weight = _compute_grad_weight(
|
||||
x,
|
||||
grad_output,
|
||||
weight.shape,
|
||||
weight,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
ks_tensor,
|
||||
@@ -230,7 +230,7 @@ def _grouped_fp8_gemm_backward_fake(
|
||||
needs_grad_x: bool,
|
||||
needs_grad_weight: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return torch.empty_like(x), torch.empty_like(weight)
|
||||
return x.new_empty(x.shape), weight.new_empty(weight.shape)
|
||||
|
||||
|
||||
def _grouped_fp8_gemm_setup_context(ctx, inputs, output) -> None:
|
||||
|
||||
@@ -48,8 +48,8 @@ def _fp8_blockwise_mm_backward(
|
||||
x_2d = x.reshape(-1, x.shape[-1]).contiguous()
|
||||
grad_output_2d = grad_output.reshape(-1, grad_output.shape[-1]).contiguous()
|
||||
use_ue8m0 = ue8m0_for_device(grad_output.device)
|
||||
grad_x = torch.empty_like(x)
|
||||
grad_weight = torch.empty_like(weight)
|
||||
grad_x = x.new_empty(x.shape)
|
||||
grad_weight = weight.new_empty(weight.shape)
|
||||
|
||||
if needs_grad_x:
|
||||
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, use_ue8m0, block_size)
|
||||
@@ -68,7 +68,7 @@ def _fp8_blockwise_mm_backward(
|
||||
x_2d = torch.nn.functional.pad(x_2d, (0, 0, 0, pad_rows))
|
||||
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d, use_ue8m0, block_size)
|
||||
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d, use_ue8m0, block_size)
|
||||
grad_weight_fp32 = torch.zeros_like(weight, dtype=torch.float32)
|
||||
grad_weight_fp32 = torch.zeros(weight.shape, device=weight.device, dtype=torch.float32)
|
||||
deep_gemm.fp8_gemm_nt(
|
||||
grad_output_t_fp8,
|
||||
x_t_fp8,
|
||||
@@ -90,7 +90,7 @@ def _fp8_blockwise_mm_backward_fake(
|
||||
needs_grad_x: bool,
|
||||
needs_grad_weight: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return torch.empty_like(x), torch.empty_like(weight)
|
||||
return x.new_empty(x.shape), weight.new_empty(weight.shape)
|
||||
|
||||
|
||||
def _fp8_blockwise_mm_setup_context(ctx, inputs, output) -> None:
|
||||
|
||||
@@ -8,7 +8,7 @@ from transformers.integrations import use_kernel_forward_from_hub
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _get_quack_rmsnorm():
|
||||
def get_quack_rmsnorm():
|
||||
"""Lazy-load quack rmsnorm. Returns None if unavailable or GPU is pre-Hopper."""
|
||||
if not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] < 9:
|
||||
return None
|
||||
@@ -34,7 +34,7 @@ class RMSNorm(nn.Module):
|
||||
self.variance_epsilon = config.eps
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
quack_fn = _get_quack_rmsnorm() if hidden_states.is_cuda else None
|
||||
quack_fn = get_quack_rmsnorm() if hidden_states.is_cuda else None
|
||||
if quack_fn is not None:
|
||||
return quack_fn(hidden_states, self.weight, eps=self.variance_epsilon)
|
||||
input_dtype = hidden_states.dtype
|
||||
|
||||
@@ -272,7 +272,7 @@ def _ring_attention_forward_fake(
|
||||
window_size_right: int,
|
||||
attention_backend: str,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return torch.empty_like(q), q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
|
||||
return q.new_empty(q.shape), q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_ring::attention_backward", mutates_args=())
|
||||
@@ -313,9 +313,9 @@ def ring_attention_backward(
|
||||
if heads_k_stride != num_kv_heads
|
||||
else None
|
||||
)
|
||||
dq = torch.empty_like(q)
|
||||
dk = torch.empty_like(k)
|
||||
dv = torch.empty_like(v)
|
||||
dq = q.new_empty(q.shape)
|
||||
dk = k.new_empty(k.shape)
|
||||
dv = v.new_empty(v.shape)
|
||||
|
||||
communication = AllGatherComm(group)
|
||||
communication.all_gather(next_gathered_kv[0], k[:, :heads_k_stride].contiguous())
|
||||
@@ -364,8 +364,8 @@ def ring_attention_backward(
|
||||
else:
|
||||
reduced_dk = local_kv_grad[0]
|
||||
reduced_dv = local_kv_grad[1]
|
||||
dist.reduce_scatter_tensor(reduced_dk, gathered_kv_grad[0], group=group)
|
||||
dist.reduce_scatter_tensor(reduced_dv, gathered_kv_grad[1], group=group)
|
||||
dist.reduce_scatter_single(reduced_dk, gathered_kv_grad[0], group=group)
|
||||
dist.reduce_scatter_single(reduced_dv, gathered_kv_grad[1], group=group)
|
||||
if local_kv_grad is not None:
|
||||
kv_head_stop = kv_head_start + heads_k_stride
|
||||
dk[:, kv_head_start:kv_head_stop] = reduced_dk
|
||||
@@ -395,7 +395,7 @@ def _ring_attention_backward_fake(
|
||||
window_size_right: int,
|
||||
attention_backend: str,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
return torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
|
||||
return q.new_empty(q.shape), k.new_empty(k.shape), v.new_empty(v.shape)
|
||||
|
||||
|
||||
def _ring_attention_setup_context(ctx, inputs, output) -> None:
|
||||
|
||||
@@ -114,16 +114,6 @@ def preprocess_layer_checkpoint(
|
||||
return revert_weight_conversion(model, layer_state_dict)
|
||||
|
||||
|
||||
def preprocess_layer_quantized(
|
||||
model: nn.Module,
|
||||
layer_state_dict: dict[str, Tensor],
|
||||
layer_idx: int,
|
||||
) -> dict[str, Tensor]:
|
||||
if layer_idx < 0:
|
||||
return layer_state_dict
|
||||
return model.convert_layer_to_vllm_kernel(layer_state_dict, layer_idx, quantize_fp8=True)
|
||||
|
||||
|
||||
class NCCLBroadcaster:
|
||||
def __init__(
|
||||
self,
|
||||
@@ -133,12 +123,10 @@ class NCCLBroadcaster:
|
||||
world_size: int,
|
||||
device: int | str | torch.device,
|
||||
timeout: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
):
|
||||
self.logger = get_logger()
|
||||
self.world = get_world()
|
||||
self.dtype = torch.bfloat16
|
||||
self.quantize_in_weight_transfer = quantize_in_weight_transfer
|
||||
|
||||
if self.world.is_master:
|
||||
disable_nccl_p2p_if_unavailable()
|
||||
@@ -163,16 +151,10 @@ class NCCLBroadcaster:
|
||||
broadcast_integer(num_state_dict_to_send, self.communicator)
|
||||
|
||||
self.logger.debug(f"Broadcasting {num_state_dict_to_send} layer state dicts")
|
||||
preprocess_fn: Callable[[nn.Module, dict[str, Tensor], int], dict[str, Tensor]]
|
||||
if self.quantize_in_weight_transfer:
|
||||
preprocess_fn = preprocess_layer_quantized
|
||||
else:
|
||||
preprocess_fn = preprocess_layer_checkpoint
|
||||
|
||||
keep_in_fp32 = getattr(model, "keep_in_fp32_for_weight_transfer", None)
|
||||
for layer_id, layer_state_dict in filter_state_dict_by_layers(state_dict, num_layers, layer_prefix):
|
||||
layer_state_dict = resolve_dtensors(layer_state_dict, keep_in_fp32, self.dtype)
|
||||
layer_state_dict = preprocess_fn(model, layer_state_dict, layer_id)
|
||||
layer_state_dict = preprocess_layer_checkpoint(model, layer_state_dict, layer_id)
|
||||
if self.world.is_master:
|
||||
broadcast_state_dict(layer_state_dict, self.communicator)
|
||||
|
||||
@@ -194,14 +176,13 @@ class NCCLWeightSender(WeightSender):
|
||||
config.inference_world_size + 1,
|
||||
device,
|
||||
config.timeout,
|
||||
quantize_in_weight_transfer=config.quantize_in_weight_transfer,
|
||||
)
|
||||
|
||||
@torch.no_grad()
|
||||
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
|
||||
# The master enters only after the receiver acknowledged the handshake,
|
||||
# but all ranks must be held back until then: the broadcast preparation
|
||||
# (DTensor resolution, quantization) enqueues collectives on non-master
|
||||
# (DTensor resolution, checkpoint conversion) enqueues collectives on non-master
|
||||
# ranks, and if those start before the receiver has paused inference,
|
||||
# the collectives sit unmatched until NCCL's watchdog kills the process.
|
||||
if self.world.world_size > 1:
|
||||
@@ -221,7 +202,6 @@ class NCCLWeightReceiver(WeightReceiver):
|
||||
port=self.config.port,
|
||||
timeout=self.config.timeout,
|
||||
inference_world_size=self.config.inference_world_size,
|
||||
quantize_in_weight_transfer=self.config.quantize_in_weight_transfer,
|
||||
)
|
||||
|
||||
async def receive(self, step: int) -> None:
|
||||
|
||||
@@ -60,8 +60,8 @@ def check_dashboard_smoke(output_dir: Path, run_name: str) -> None:
|
||||
page.on("pageerror", lambda e: errors.append(f"page: {e}"))
|
||||
base = f"http://127.0.0.1:{port}"
|
||||
|
||||
# metrics: the run resolves and the overview renders charts with data
|
||||
page.goto(f"{base}/#run={run_name}&tab=metrics")
|
||||
# overview: the run resolves and the curated view renders with data
|
||||
page.goto(f"{base}/#run={run_name}&tab=overview")
|
||||
page.wait_for_timeout(PAGE_SETTLE_MS)
|
||||
status = page.locator("#run-overview .badge").first.inner_text()
|
||||
assert status, "overview card did not render a status"
|
||||
@@ -82,6 +82,14 @@ def check_dashboard_smoke(output_dir: Path, run_name: str) -> None:
|
||||
with_data = page.evaluate("""() => [...document.querySelectorAll('.chart-card .u-wrap')].length""")
|
||||
assert with_data >= 5, f"expected >=5 mounted charts, got {with_data}"
|
||||
|
||||
# metrics: every key in metrics.jsonl, one pane each, for every run type
|
||||
page.click("#tabs [data-tab=metrics]")
|
||||
page.wait_for_timeout(PAGE_SETTLE_MS)
|
||||
panes = page.locator("#metrics-body .chart-card").count()
|
||||
assert panes >= 5, f"expected >=5 metric panes, got {panes}"
|
||||
mounted = page.evaluate("""() => document.querySelectorAll('#metrics-body .chart-card .u-wrap').length""")
|
||||
assert mounted >= 1, f"expected mounted metric panes, got {mounted}"
|
||||
|
||||
# config: the default view renders (launch TOML on new runs), and the
|
||||
# resolved concatenated document renders as a tree
|
||||
page.click("#tabs [data-tab=config]")
|
||||
|
||||
@@ -213,7 +213,7 @@ def test_dynamo_nccl_lifecycle_initializes_and_updates_weights(tmp_path):
|
||||
asyncio.run(admin.initialize_nccl(host="trainer", port=29501, timeout=10, inference_world_size=1))
|
||||
asyncio.run(admin.update_weights(tmp_path / "step_1", transport="nccl", step=1))
|
||||
|
||||
assert collective_rpc.await_args_list[0].kwargs["args"] == ["trainer", 29501, 0, 1, 10, False, "default"]
|
||||
assert collective_rpc.await_args_list[0].kwargs["args"] == ["trainer", 29501, 0, 1, 10, "default"]
|
||||
assert collective_rpc.await_args_list[1].kwargs["args"] == [(tmp_path / "step_1").as_posix()]
|
||||
assert [call.args[1] for call in post.await_args_list] == ["/pause", "/resume"]
|
||||
assert admin._nccl_initialization_state == "ready"
|
||||
|
||||
@@ -81,7 +81,6 @@ def test_admin_plane_initializes_nccl():
|
||||
"rank_offset": 0,
|
||||
"inference_world_size": 1,
|
||||
"timeout": 1200,
|
||||
"quantize_in_weight_transfer": False,
|
||||
},
|
||||
)
|
||||
asyncio.run(admin_plane.aclose())
|
||||
|
||||
@@ -40,16 +40,33 @@ def get_config_files() -> list[Path]:
|
||||
return config_files + example_files + k8s_files
|
||||
|
||||
|
||||
def can_parse(config_cls: type, args: list[str]) -> bool:
|
||||
"""Whether `cli` parses the given `@` config file args into `config_cls`."""
|
||||
try:
|
||||
cli(config_cls, args=args)
|
||||
return True
|
||||
except (ValidationError, ConfigFileError, SystemExit):
|
||||
return False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("config_file", get_config_files(), ids=lambda x: x.as_posix())
|
||||
def test_load_configs(config_file: Path):
|
||||
"""Tests that all config files can be loaded by at least one config class."""
|
||||
could_parse = []
|
||||
for config_cls in CONFIG_CLASSES:
|
||||
try:
|
||||
cli(config_cls, args=["@", config_file.as_posix()])
|
||||
could_parse.append(True)
|
||||
except (ValidationError, ConfigFileError, SystemExit):
|
||||
could_parse.append(False)
|
||||
"""Tests that all config files can be loaded by at least one config class.
|
||||
|
||||
A file that no class parses standalone is an overlay — a checked-in config that only carries
|
||||
the deltas over a shared base (e.g. the glm-4.5-air budget variants over
|
||||
`swe-budget.toml`). Retry those composed with each sibling TOML as the base: the
|
||||
documented `@ base.toml @ overlay.toml` left-to-right merge (docs/configuration.md,
|
||||
"TOML Composition").
|
||||
"""
|
||||
could_parse = [can_parse(config_cls, ["@", config_file.as_posix()]) for config_cls in CONFIG_CLASSES]
|
||||
if not any(could_parse):
|
||||
sibling_bases = sorted(p for p in config_file.parent.glob("*.toml") if p != config_file)
|
||||
could_parse = [
|
||||
can_parse(config_cls, ["@", base.as_posix(), "@", config_file.as_posix()])
|
||||
for base in sibling_bases
|
||||
for config_cls in CONFIG_CLASSES
|
||||
]
|
||||
assert any(could_parse), f"No config class could be parsed from {config_file}"
|
||||
|
||||
|
||||
|
||||
@@ -105,7 +105,7 @@ def _torch_rms_norm(monkeypatch):
|
||||
The kernel is a project-wide choice that predates this model and drifts from a fp32
|
||||
reference by up to ~1e-2 in bf16, which would swamp what the V4-specific math contributes.
|
||||
"""
|
||||
monkeypatch.setattr(norms, "_get_quack_rmsnorm", lambda: None)
|
||||
monkeypatch.setattr(norms, "get_quack_rmsnorm", lambda: None)
|
||||
|
||||
|
||||
def _tid2eid(vocab_size: int, num_experts: int, top_k: int) -> torch.Tensor:
|
||||
|
||||
@@ -12,8 +12,9 @@ from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, eager_referenc
|
||||
from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention
|
||||
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext
|
||||
from prime_rl.trainer.models.deepseek_v4.eager_reference import dense_mask_from_indices, eager_attention_with_sinks
|
||||
from prime_rl.trainer.models.deepseek_v4.hyperconnections import DeepseekV4HyperConnection
|
||||
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding, apply_rotary_pos_emb_interleaved
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT, dsv4_mhc
|
||||
from prime_rl.utils.cp import CPContext
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
|
||||
@@ -1257,3 +1258,64 @@ def test_context_parallel_shards_reproduce_the_whole_row(layer_idx, cp_world_siz
|
||||
|
||||
_assert_relative(hidden_full.grad, reference_input_grad, PACKED_GRAD_RTOL, "hidden states gradient")
|
||||
_compare_accumulated_grads(module, reference_grads)
|
||||
|
||||
|
||||
MHC_SHAPES = [(1, 256), (1, 203), (3, 67)]
|
||||
MHC_SHAPE_IDS = ["aligned", "misaligned", "batched"]
|
||||
|
||||
SINKHORN_RTOL = 1e-5
|
||||
SINKHORN_GRAD_RTOL = 1e-5
|
||||
POST_BDA_RTOL = 1e-2
|
||||
POST_BDA_GRAD_RTOL = 1e-2
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("batch", "seq_len"), MHC_SHAPES, ids=MHC_SHAPE_IDS)
|
||||
def test_fused_sinkhorn_matches_the_eager_reference(batch, seq_len):
|
||||
hc = V4FLASH_MODEL["hc_mult"]
|
||||
iters, eps = V4FLASH_MODEL["hc_sinkhorn_iters"], V4FLASH_MODEL["hc_eps"]
|
||||
with torch.device("cuda"):
|
||||
logits = torch.randn(batch, seq_len, hc, hc)
|
||||
weight = torch.randn(batch, seq_len, hc, hc)
|
||||
|
||||
fused_logits, reference_logits = _leaves(logits, logits)
|
||||
|
||||
fused_comb = dsv4_mhc.fused_sinkhorn(fused_logits, iters, eps)
|
||||
(fused_comb * weight).sum().backward()
|
||||
|
||||
reference_comb = eager_reference.eager_sinkhorn(reference_logits, iters, eps)
|
||||
(reference_comb * weight).sum().backward()
|
||||
|
||||
_assert_relative(fused_comb, reference_comb, SINKHORN_RTOL, "comb")
|
||||
_assert_relative(fused_logits.grad, reference_logits.grad, SINKHORN_GRAD_RTOL, "logits gradient")
|
||||
|
||||
|
||||
def test_fused_post_bda_matches_the_eager_reference():
|
||||
batch, seq_len = 2, 129
|
||||
hc, dim = V4FLASH_MODEL["hc_mult"], V4FLASH_MODEL["hidden_size"]
|
||||
with torch.device("cuda"):
|
||||
module = DeepseekV4HyperConnection(V4FLASH_CONFIG)
|
||||
streams = torch.randn(batch, seq_len, hc, dim, dtype=torch.bfloat16)
|
||||
sublayer_out = torch.randn(batch, seq_len, dim, dtype=torch.bfloat16)
|
||||
post = 2 * torch.sigmoid(torch.randn(batch, seq_len, hc))
|
||||
comb = torch.softmax(torch.randn(batch, seq_len, hc, hc), dim=-1)
|
||||
weight = torch.randn(batch, seq_len, hc, dim, dtype=torch.bfloat16)
|
||||
|
||||
fused_post, fused_comb, fused_x, fused_streams = _leaves(post, comb, sublayer_out, streams)
|
||||
reference_post, reference_comb, reference_x, reference_streams = _leaves(post, comb, sublayer_out, streams)
|
||||
|
||||
fused_out = module.update_states(fused_post, fused_comb, fused_x, fused_streams)
|
||||
(fused_out * weight).sum().backward()
|
||||
|
||||
reference_out = eager_reference.eager_update_states(reference_post, reference_comb, reference_x, reference_streams)
|
||||
(reference_out * weight).sum().backward()
|
||||
|
||||
_assert_relative(fused_out, reference_out, POST_BDA_RTOL, "write-back output")
|
||||
grads = (
|
||||
("post gradient", fused_post, reference_post),
|
||||
("comb gradient", fused_comb, reference_comb),
|
||||
("sublayer output gradient", fused_x, reference_x),
|
||||
("streams gradient", fused_streams, reference_streams),
|
||||
)
|
||||
for label, fused_leaf, reference_leaf in grads:
|
||||
assert reference_leaf.grad is not None, f"{label}: the reference backward left the leaf without a gradient"
|
||||
_assert_relative(fused_leaf.grad, reference_leaf.grad, POST_BDA_GRAD_RTOL, label)
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import convert_tt_layer_to_vllm_kernel
|
||||
|
||||
|
||||
def _build_prime_layer_state(layer_idx: int = 0) -> dict[str, torch.Tensor]:
|
||||
prefix = f"model.layers.{layer_idx}"
|
||||
return {
|
||||
f"{prefix}.self_attn.q_a_proj.weight": torch.randn(4, 6),
|
||||
f"{prefix}.self_attn.kv_a_proj_with_mqa.weight": torch.randn(3, 6),
|
||||
f"{prefix}.self_attn.q_b_proj.weight": torch.randn(5, 6),
|
||||
f"{prefix}.self_attn.kv_b_proj.weight": torch.randn(7, 6),
|
||||
f"{prefix}.self_attn.o_proj.weight": torch.randn(6, 5),
|
||||
f"{prefix}.self_attn.indexer.wq_b.weight": torch.randn(4, 6),
|
||||
f"{prefix}.self_attn.indexer.wk.weight": torch.randn(4, 6),
|
||||
f"{prefix}.self_attn.indexer.k_norm.weight": torch.randn(6),
|
||||
f"{prefix}.self_attn.indexer.k_norm.bias": torch.randn(6),
|
||||
f"{prefix}.self_attn.indexer.weights_proj.weight": torch.randn(2, 6),
|
||||
f"{prefix}.mlp.gate_proj.weight": torch.randn(8, 6),
|
||||
f"{prefix}.mlp.up_proj.weight": torch.randn(8, 6),
|
||||
f"{prefix}.mlp.down_proj.weight": torch.randn(6, 8),
|
||||
f"{prefix}.mlp.router.gate.weight": torch.randn(4, 6),
|
||||
f"{prefix}.mlp.router.selection_bias": torch.randn(4),
|
||||
f"{prefix}.mlp.experts.gate_proj": torch.randn(2, 3, 6),
|
||||
f"{prefix}.mlp.experts.up_proj": torch.randn(2, 3, 6),
|
||||
f"{prefix}.mlp.experts.down_proj": torch.randn(2, 6, 3),
|
||||
f"{prefix}.mlp.shared_expert.gate_proj.weight": torch.randn(3, 6),
|
||||
f"{prefix}.mlp.shared_expert.up_proj.weight": torch.randn(3, 6),
|
||||
f"{prefix}.mlp.shared_expert.down_proj.weight": torch.randn(6, 3),
|
||||
}
|
||||
|
||||
|
||||
def test_convert_tt_layer_to_vllm_kernel_no_fp8():
|
||||
state = _build_prime_layer_state()
|
||||
out = convert_tt_layer_to_vllm_kernel(state, layer_idx=0, quantize_fp8=False)
|
||||
|
||||
assert "model.layers.0.self_attn.fused_qkv_a_proj.weight" in out
|
||||
assert out["model.layers.0.self_attn.fused_qkv_a_proj.weight"].shape == (7, 6)
|
||||
assert "model.layers.0.self_attn.indexer.wk_weights_proj.weight" in out
|
||||
assert out["model.layers.0.self_attn.indexer.wk_weights_proj.weight"].shape == (6, 6)
|
||||
assert "model.layers.0.self_attn.indexer.wk.weight" not in out
|
||||
assert "model.layers.0.self_attn.indexer.weights_proj.weight" not in out
|
||||
|
||||
assert "model.layers.0.mlp.gate_up_proj.weight" in out
|
||||
assert out["model.layers.0.mlp.gate_up_proj.weight"].shape == (16, 6)
|
||||
|
||||
assert "model.layers.0.mlp.experts.w13_weight" in out
|
||||
assert out["model.layers.0.mlp.experts.w13_weight"].shape == (2, 6, 6)
|
||||
assert "model.layers.0.mlp.experts.w2_weight" in out
|
||||
assert out["model.layers.0.mlp.experts.w2_weight"].shape == (2, 6, 3)
|
||||
|
||||
assert "model.layers.0.mlp.gate.weight" in out
|
||||
assert "model.layers.0.mlp.gate.e_score_correction_bias" in out
|
||||
|
||||
|
||||
def test_convert_tt_layer_to_vllm_kernel_with_fp8():
|
||||
state = _build_prime_layer_state()
|
||||
out = convert_tt_layer_to_vllm_kernel(state, layer_idx=0, quantize_fp8=True)
|
||||
|
||||
assert out["model.layers.0.self_attn.fused_qkv_a_proj.weight"].dtype == torch.float8_e4m3fn
|
||||
assert out["model.layers.0.self_attn.fused_qkv_a_proj.weight_scale_inv"].dtype == torch.float32
|
||||
assert out["model.layers.0.self_attn.indexer.wk_weights_proj.weight"].dtype == torch.float32
|
||||
assert "model.layers.0.self_attn.indexer.wk.weight_scale_inv" not in out
|
||||
|
||||
assert out["model.layers.0.mlp.experts.w13_weight"].dtype == torch.float8_e4m3fn
|
||||
assert out["model.layers.0.mlp.experts.w13_weight_scale_inv"].dtype == torch.float32
|
||||
assert out["model.layers.0.mlp.experts.w2_weight"].dtype == torch.float8_e4m3fn
|
||||
assert out["model.layers.0.mlp.experts.w2_weight_scale_inv"].dtype == torch.float32
|
||||
@@ -17,27 +17,27 @@ exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for
|
||||
exclude-newer-span = "P7D"
|
||||
|
||||
[options.exclude-newer-package]
|
||||
vllm = false
|
||||
verifiers = false
|
||||
harbor = "2026-08-11T00:00:00Z"
|
||||
prime-traces = false
|
||||
prime-pydantic-config = false
|
||||
vllm-router = false
|
||||
dion = false
|
||||
prime-runs = false
|
||||
flash-attn-3 = false
|
||||
prime-tunnel = false
|
||||
fastokens = false
|
||||
deep-gemm = false
|
||||
prime-evals = false
|
||||
torchao = false
|
||||
tokenspeed-mla = false
|
||||
nixl-cu13 = false
|
||||
deep-ep = false
|
||||
prime-sandboxes = false
|
||||
renderers = false
|
||||
prime-kernels = false
|
||||
deep-gemm = false
|
||||
dion = false
|
||||
fastokens = false
|
||||
flash-attn-3 = false
|
||||
harbor = "2026-08-11T00:00:00Z"
|
||||
nixl-cu13 = false
|
||||
prime = false
|
||||
prime-evals = false
|
||||
prime-kernels = false
|
||||
prime-pydantic-config = false
|
||||
prime-runs = false
|
||||
prime-sandboxes = false
|
||||
prime-traces = false
|
||||
prime-tunnel = false
|
||||
renderers = false
|
||||
tokenspeed-mla = false
|
||||
torchao = false
|
||||
verifiers = false
|
||||
vllm = false
|
||||
vllm-router = false
|
||||
|
||||
[manifest]
|
||||
members = [
|
||||
@@ -2069,12 +2069,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/a0/61/5c78b91c3143ed5c14207f463aecfc8f9dbb5092fb2869baf37c273b2705/gitdb-4.0.12-py3-none-any.whl", hash = "sha256:67073e15955400952c6565cc3e707c554a4eea2e428946f7a4c162fab9bd9bcf", size = 62794, upload-time = "2025-01-02T07:20:43.624Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gitignore-parser"
|
||||
version = "0.1.13"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/e5/51/e391a1a4238f18d0abb47be479b07af265ad4519022cf51b7da47ef82487/gitignore_parser-0.1.13.tar.gz", hash = "sha256:c7e10c8190accb8ae57fb3711889e73a9c0dbc04d4222b91ace8a4bf64d2f746", size = 5603, upload-time = "2025-08-25T06:33:22.704Z" }
|
||||
|
||||
[[package]]
|
||||
name = "gitpython"
|
||||
version = "3.1.50"
|
||||
@@ -3142,18 +3136,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e9/61/f75cd1fa54d8434276126034aed54dd120747de9a8fa013cdd79545ccbeb/latex2sympy2_extended-1.11.0-py3-none-any.whl", hash = "sha256:aebb77d52ce269e25028e4bea89ddb14d242ba36bcf7b636496fb5fd9728d234", size = 209050, upload-time = "2026-01-10T01:43:19.458Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "linkify-it-py"
|
||||
version = "2.1.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "uc-micro-py" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/2e/c9/06ea13676ef354f0af6169587ae292d3e2406e212876a413bf9eece4eb23/linkify_it_py-2.1.0.tar.gz", hash = "sha256:43360231720999c10e9328dc3691160e27a718e280673d444c38d7d3aaa3b98b", size = 29158, upload-time = "2026-03-01T07:48:47.683Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b4/de/88b3be5c31b22333b3ca2f6ff1de4e863d8fe45aaea7485f591970ec1d3e/linkify_it_py-2.1.0-py3-none-any.whl", hash = "sha256:0d252c1594ecba2ecedc444053db5d3a9b7ec1b0dd929c8f1d74dce89f86c05e", size = 19878, upload-time = "2026-03-01T07:48:46.098Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "litellm"
|
||||
version = "1.95.0"
|
||||
@@ -3349,11 +3331,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b3/81/4da04ced5a082363ecfa159c010d200ecbd959ae410c10c0264a38cac0f5/markdown_it_py-4.2.0-py3-none-any.whl", hash = "sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a", size = 91687, upload-time = "2026-05-07T12:08:27.182Z" },
|
||||
]
|
||||
|
||||
[package.optional-dependencies]
|
||||
linkify = [
|
||||
{ name = "linkify-it-py" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "markupsafe"
|
||||
version = "3.0.3"
|
||||
@@ -3502,18 +3479,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/f5/4c/c78d78c3d52b0ac594ad7cc8ef5972adfe070e3597a8a4c6ce0cd39196ea/mcp_types-2.0.0-py3-none-any.whl", hash = "sha256:6b2de797ca2797f568b79529e1b25948e34de511bcc0bd82fef1039a6d1b8eb0", size = 69649, upload-time = "2026-07-28T13:45:30.713Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mdit-py-plugins"
|
||||
version = "0.6.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "markdown-it-py" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/59/fc/f8d0863f8862f25602c0404d75568e89fb6b4109804645e5cdfb1be5cf56/mdit_py_plugins-0.6.1.tar.gz", hash = "sha256:a2bca0f039f39dbd35fb74ae1b5f998608c437463371f0ff7f49a19a17a114d0", size = 56114, upload-time = "2026-05-13T09:03:38.91Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/a5/69/6da5581c6a7fede7dc261bf4e67d6adca4196f176b43288b55b3db395b6e/mdit_py_plugins-0.6.1-py3-none-any.whl", hash = "sha256:214c82fb2ac524472ab6a5bcab1de80f73b50443e187f401bfd77efbc7c6481d", size = 66663, upload-time = "2026-05-13T09:03:37.76Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mdurl"
|
||||
version = "0.1.2"
|
||||
@@ -4886,47 +4851,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e6/88/bdb244e40284ded3632a9f88c23bc80230bd7b2ae4a8b7f2cc91adead7a8/preshed-3.0.13-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2e77bed56aded7cbe5d28d6bd2178bc5b13eda0e0e464dab205fb578fa915000", size = 1919236, upload-time = "2026-03-23T08:56:42.616Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prime"
|
||||
version = "0.6.19"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "build" },
|
||||
{ name = "cryptography" },
|
||||
{ name = "gitignore-parser" },
|
||||
{ name = "httpx" },
|
||||
{ name = "prime-evals" },
|
||||
{ name = "prime-sandboxes" },
|
||||
{ name = "prime-tunnel" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "pyyaml" },
|
||||
{ name = "rich" },
|
||||
{ name = "textual" },
|
||||
{ name = "textual-plot" },
|
||||
{ name = "toml" },
|
||||
{ name = "tomli" },
|
||||
{ name = "typer" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/54/01/d355265be49ec5bd5ce602791e572e266c315ba9087c1a9e77911781a99d/prime-0.6.19.tar.gz", hash = "sha256:cbf33d5050e3795373842b9b89be0ee2b11a9ae9bbdcda080272eb0d982276c2", size = 711104, upload-time = "2026-07-17T17:41:09.283Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/5e/ad/67705b41b441513cc09de0a6134b8584d436efba8bc8b4ddeb4a3bbca768/prime-0.6.19-py3-none-any.whl", hash = "sha256:c2a4ee9252cd1a54fa6bcec2958a09ad4374077c68d461071d1ca699a9f4dda2", size = 473362, upload-time = "2026-07-17T17:41:07.35Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prime-evals"
|
||||
version = "0.2.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "httpx" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "tenacity" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/1b/e6/8c84619b09ecfb9484ba9b14bf57de3e9417a08e0b3695bd054b181efca8/prime_evals-0.2.3.tar.gz", hash = "sha256:4b22f9057a8765c85f2e91c795d78e48015ae6d30439f24aea9e8396b2c3f016", size = 14417, upload-time = "2026-06-05T00:39:56.145Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e9/f8/41c4a4bc7a03ece28b1c4f39d45a5c362ebaa0895a161db83c591f10e6b6/prime_evals-0.2.3-py3-none-any.whl", hash = "sha256:e5217f36d360baedf2c10dd49abe7be504932bf8249a35c9f7abad12d0c0299a", size = 13575, upload-time = "2026-06-05T00:39:54.901Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prime-kernels"
|
||||
version = "0.1.0+cu130torch2.13.0"
|
||||
@@ -5006,10 +4930,10 @@ dependencies = [
|
||||
{ name = "openai" },
|
||||
{ name = "orjson" },
|
||||
{ name = "pandas" },
|
||||
{ name = "prime" },
|
||||
{ name = "prime-pydantic-config" },
|
||||
{ name = "prime-rl-configs" },
|
||||
{ name = "prime-runs", extra = ["train"] },
|
||||
{ name = "prime-sandboxes" },
|
||||
{ name = "prometheus-client" },
|
||||
{ name = "psutil" },
|
||||
{ name = "pyarrow" },
|
||||
@@ -5058,8 +4982,8 @@ all = [
|
||||
{ name = "torchvision", marker = "sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.28.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.28.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm-router", version = "0.2.0", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm-router", version = "0.2.0", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm-router", version = "0.2.1", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm-router", version = "0.2.1", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
]
|
||||
dashboard = [
|
||||
{ name = "fastapi" },
|
||||
@@ -5072,8 +4996,8 @@ disagg = [
|
||||
{ name = "deep-gemm", version = "2.5.0+891d57b", source = { url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "nixl", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nixl-cu13", marker = "sys_platform == 'linux'" },
|
||||
{ name = "vllm-router", version = "0.2.0", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm-router", version = "0.2.0", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm-router", version = "0.2.1", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm-router", version = "0.2.1", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
]
|
||||
dynamo = [
|
||||
{ name = "ai-dynamo", marker = "sys_platform == 'linux'" },
|
||||
@@ -5165,7 +5089,6 @@ requires-dist = [
|
||||
{ name = "orjson", specifier = ">=3.10" },
|
||||
{ name = "orjson", specifier = ">=3.11.0" },
|
||||
{ name = "pandas", specifier = ">=2.0" },
|
||||
{ name = "prime", specifier = ">=0.6.19" },
|
||||
{ name = "prime-kernels", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'kernels'", url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl" },
|
||||
{ name = "prime-kernels", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'kernels'" },
|
||||
{ name = "prime-kernels", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'kernels'", url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl" },
|
||||
@@ -5177,7 +5100,8 @@ requires-dist = [
|
||||
{ name = "prime-rl", extras = ["gpu"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl", extras = ["quack"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl-configs", editable = "packages/prime-rl-configs" },
|
||||
{ name = "prime-runs", extras = ["train"], specifier = ">=0.1.1" },
|
||||
{ name = "prime-runs", extras = ["train"], specifier = ">=0.1.3" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.3.0" },
|
||||
{ name = "prometheus-client", specifier = ">=0.20.0" },
|
||||
{ name = "psutil", specifier = ">=7.0.0" },
|
||||
{ name = "pyarrow", specifier = ">=21.0.0" },
|
||||
@@ -5206,9 +5130,9 @@ requires-dist = [
|
||||
{ name = "vllm", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_aarch64.whl" },
|
||||
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", specifier = ">=0.28.0" },
|
||||
{ name = "vllm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl" },
|
||||
{ name = "vllm-router", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl" },
|
||||
{ name = "vllm-router", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl" },
|
||||
{ name = "vllm-router", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'disagg'" },
|
||||
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl" },
|
||||
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl" },
|
||||
{ name = "wandb", specifier = ">=0.26.1" },
|
||||
{ name = "wandb-workspaces", specifier = ">=0.4.3" },
|
||||
]
|
||||
@@ -5251,15 +5175,15 @@ requires-dist = [
|
||||
|
||||
[[package]]
|
||||
name = "prime-runs"
|
||||
version = "0.1.2"
|
||||
version = "0.1.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "httpx" },
|
||||
{ name = "prime-traces" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/db/ee/0e9cf800aa6b3db148b01d26e0d6957074027f52323b348ad35594e41d1c/prime_runs-0.1.2.tar.gz", hash = "sha256:2cd4775aa3176f95abf3def78ba257b6b0579ba2606d24307c88495e5b1bb6f1", size = 62099, upload-time = "2026-09-09T00:28:45.621Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/3f/ba/3d38aeafc0ef885eef7b99bbe26fe350b4248af8d3fa89d4ca8a249f0f04/prime_runs-0.1.3.tar.gz", hash = "sha256:181ab1c720ed9113abbf3719ba6863c9ee23c55309101c0b7f4021ff9dafbe20", size = 65541, upload-time = "2026-09-17T15:31:42.319Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/37/59/e48470b0b47d3fc261e31e13d1ed47177f0a71044234ae46b40b00063f1c/prime_runs-0.1.2-py3-none-any.whl", hash = "sha256:95ca0775317cf2733aa38a0a26b263174b992d5be63009a4cfeeff212924759b", size = 43333, upload-time = "2026-09-09T00:28:44.22Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6e/93/5fff685470a6cb12fc93192432951a081de70e271aef1cebc506fba4ccc5/prime_runs-0.1.3-py3-none-any.whl", hash = "sha256:86c3d5183ed5848854a194233b4a9451deabea56a9063771244c5c54c00d69df", size = 45087, upload-time = "2026-09-17T15:31:40.913Z" },
|
||||
]
|
||||
|
||||
[package.optional-dependencies]
|
||||
@@ -5269,7 +5193,7 @@ train = [
|
||||
|
||||
[[package]]
|
||||
name = "prime-sandboxes"
|
||||
version = "0.2.39"
|
||||
version = "0.3.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "aiofiles" },
|
||||
@@ -5281,36 +5205,36 @@ dependencies = [
|
||||
{ name = "pyqwest" },
|
||||
{ name = "tenacity" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/59/8c/0bf89180addb74f75e41fbf6fa06c5401ea802b69ec0b565330562270be2/prime_sandboxes-0.2.39.tar.gz", hash = "sha256:7ff6c23aa2c96985a9129d977d532c0ae2fb6afb6d394dac746393ce0c53b597", size = 103161, upload-time = "2026-08-19T23:09:27.921Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/b6/46/2d118d8bbb901b729f3bc0678725eb28088d757a872db04cffa1492d0208/prime_sandboxes-0.3.0.tar.gz", hash = "sha256:c99075ed82a9bbfe5a453cee84b9f09565a7f6b07fd5ace072401cce59a1fe08", size = 132759, upload-time = "2026-09-18T01:32:31.263Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/db/a5/8a2a1aefecfc58ca926d6b21e8302a127884bf2a45952ed390b5f702eeda/prime_sandboxes-0.2.39-py3-none-any.whl", hash = "sha256:3ea355158473c1697f9ef6ec2a07f3189e9a2555c80d1c88e1f7e22979772e0a", size = 58161, upload-time = "2026-08-19T23:09:26.69Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5f/04/c77c7f260babf93978f912b85511e76f63a3cfa5bb11a8c34108177d5825/prime_sandboxes-0.3.0-py3-none-any.whl", hash = "sha256:19078ff508fa72de8f565422918faf367e2831ed8a2f26a5a6a98110e4062941", size = 71441, upload-time = "2026-09-18T01:32:30.062Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prime-traces"
|
||||
version = "0.0.3"
|
||||
version = "0.0.4"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "httpx" },
|
||||
{ name = "pydantic" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/8c/77/13fa99c0fb71909f2f35d048d9724efb9ae432484e47f12386b1542815e8/prime_traces-0.0.3.tar.gz", hash = "sha256:4071833db77a606ccbb718e5c73f2dfaf63982fe801aa096daed0bc605da554f", size = 50874, upload-time = "2026-08-27T19:46:44.672Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/5f/5d/d3646fb34d4f3cf4caf2064eb3830c4da5c18a3ecd3292ce9e85eb04398f/prime_traces-0.0.4.tar.gz", hash = "sha256:713b59984292304bd4e99a55998b7d69373f22b5205a7e097ef0d0d8e531561c", size = 50935, upload-time = "2026-09-04T16:51:10.488Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ce/9a/5a917de29a3a839c0ba36d445e3af562f744d9716b509571be643a01476c/prime_traces-0.0.3-py3-none-any.whl", hash = "sha256:0838f60651f1ed38371e383bd88b954e461d20ac424874e694bc83358934f5f3", size = 38345, upload-time = "2026-08-27T19:46:43.396Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b6/55/de30cc732631522f5f12cb590b63b80cb1c6ca004ad81762d94ee7dda256/prime_traces-0.0.4-py3-none-any.whl", hash = "sha256:68f2b527d266f9c3d02f6c86a1713309a58a61b81e1be6be43948e1dd2456d8f", size = 38409, upload-time = "2026-09-04T16:51:09.201Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prime-tunnel"
|
||||
version = "0.1.10"
|
||||
version = "0.1.11"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "httpx" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "tenacity" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/bf/26/7324b5b9ec117c21fc9320214bf04ecbe9144ee87ef48c7d6d6c3e3d3f7f/prime_tunnel-0.1.10.tar.gz", hash = "sha256:8bf575af659bcc107a98b0b5ec1ba3e958ea72ead535ced03c443134a1ad07ea", size = 15305, upload-time = "2026-06-17T00:01:02.392Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/de/c7/55c21d8e1abfb66d3a0dc0e25b89abb506b0a49605fb4b0040590af82136/prime_tunnel-0.1.11.tar.gz", hash = "sha256:cd93e78824ef824b45e636f5f506898bc7f9a6c913fd5095ab1df2233a49b949", size = 15889, upload-time = "2026-09-04T17:09:25.258Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/a9/b9/d767b4f6c7ce72b54aaba834b97f97c3c494f1865a37f8b5b9acfb1b2a68/prime_tunnel-0.1.10-py3-none-any.whl", hash = "sha256:6a1cb49a14cfc9622db5cae90665ebe7e7e8cd5d84e963e8c3572bce85288400", size = 16319, upload-time = "2026-06-17T00:01:01.095Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d0/7f/6ea38563db9414ed208758de6e8dc557b20e245787e42568f89531fc6717/prime_tunnel-0.1.11-py3-none-any.whl", hash = "sha256:19c5e02e389e5e61fff1507f07c46db9b05ad01424ff3b6a0cbe66187c957f61", size = 16676, upload-time = "2026-09-04T17:09:24.157Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7042,50 +6966,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/26/b4/9a9ba65154aff853c75b3d7324319d168ad9c69c6097f4aa3c16da7d9ef3/textarena-0.7.4-py3-none-any.whl", hash = "sha256:684784e78278e518066f67557ee93b47c238d16cbbd15d3abdaa3147562d3024", size = 1073570, upload-time = "2025-10-16T14:41:53.965Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "textual"
|
||||
version = "8.2.7"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "markdown-it-py", extra = ["linkify"] },
|
||||
{ name = "mdit-py-plugins" },
|
||||
{ name = "platformdirs" },
|
||||
{ name = "pygments" },
|
||||
{ name = "rich" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/9b/7a/c519db0aba5024f86e71e9631810bfdd6866ed2c8695bd7fa34b90e7ef59/textual-8.2.7.tar.gz", hash = "sha256:658f568ff81e30ed43890c3e07520390e5cf1b4763822006e060656b0a88f105", size = 1859249, upload-time = "2026-05-19T10:52:49.531Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/a8/f5/c1e18bc0707300a0e90204343abbf7d7acd6fb7ebe03a6d4893b99a234b8/textual-8.2.7-py3-none-any.whl", hash = "sha256:4caaa13a90bc4cf9c6c862c067ccd34fe84e9c161710a2a907a8026313b6bd73", size = 731129, upload-time = "2026-05-19T10:52:51.773Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "textual-hires-canvas"
|
||||
version = "0.14.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "numpy" },
|
||||
{ name = "textual" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/20/f0/13f2a30ab7950cc3d5d5a2c893fbe3d40b4d129fd2cd30313260181578c4/textual_hires_canvas-0.14.0.tar.gz", hash = "sha256:0fa512492ddd2cd6c2a970a6beea58f5350f4cf25f40ad14ffd9fa86c6458769", size = 1251440, upload-time = "2026-01-10T22:16:56.708Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/85/ea/e7e6d0f749395d61ca2ab8cda2f3c4e6613800b6b0d0b21f9d1d180c4d42/textual_hires_canvas-0.14.0-py3-none-any.whl", hash = "sha256:8cd67d656387220684449e837dd5809b6c00c5dfee8e4b494414b5837cb5a804", size = 19825, upload-time = "2026-01-10T22:16:54.69Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "textual-plot"
|
||||
version = "0.10.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "numpy" },
|
||||
{ name = "textual" },
|
||||
{ name = "textual-hires-canvas" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/a0/c2/13f9f747e83cd0b740d1bf310e89a006316cfb5acb4e5a4136c12f96340b/textual_plot-0.10.1.tar.gz", hash = "sha256:503db96d849134293228419324eb15efbadf1f1927a2e0a229b54e7a7e5d5292", size = 2451096, upload-time = "2026-02-01T13:27:43.658Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/2a/36/75eba496995e6f9a001cd601972eab753203167dfcccfbf1816e3959d28d/textual_plot-0.10.1-py3-none-any.whl", hash = "sha256:74ff3a8b2d84bd71b3a9abbac95139ff952f190e6bac60c7091911c63a1863ba", size = 50409, upload-time = "2026-02-01T13:27:41.013Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thinc"
|
||||
version = "8.3.13"
|
||||
@@ -7677,15 +7557,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/93/4f/c43a0a8f0c66fd40a1d6cc47332a5a1d1043e9b331f7070ea701b91a7598/tyro-1.0.13-py3-none-any.whl", hash = "sha256:a0bdb8462c551dd84fc00a76916ce4d37e879c84eefaf34e2165312407cc6c09", size = 185221, upload-time = "2026-04-14T18:21:54.328Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uc-micro-py"
|
||||
version = "2.0.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/78/67/9a363818028526e2d4579334460df777115bdec1bb77c08f9db88f6389f2/uc_micro_py-2.0.0.tar.gz", hash = "sha256:c53691e495c8db60e16ffc4861a35469b0ba0821fe409a8a7a0a71864d33a811", size = 6611, upload-time = "2026-03-01T06:31:27.526Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/61/73/d21edf5b204d1467e06500080a50f79d49ef2b997c79123a536d4a17d97c/uc_micro_py-2.0.0-py3-none-any.whl", hash = "sha256:3603a3859af53e5a39bc7677713c78ea6589ff188d70f4fee165db88e22b242c", size = 6383, upload-time = "2026-03-01T06:31:26.257Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unidiff"
|
||||
version = "0.7.5"
|
||||
@@ -7837,8 +7708,8 @@ requires-dist = [
|
||||
{ name = "openai", specifier = ">=2.54.0,<3.0.0" },
|
||||
{ name = "openenv", marker = "extra == 'openenv'", specifier = ">=0.4.1" },
|
||||
{ name = "prime-pydantic-config", extras = ["toml"], specifier = ">=0.4.3" },
|
||||
{ name = "prime-runs", specifier = ">=0.1.2" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.2.39" },
|
||||
{ name = "prime-runs", specifier = ">=0.1.3" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.3.0" },
|
||||
{ name = "prime-tunnel", specifier = ">=0.1.8" },
|
||||
{ name = "pydantic", specifier = ">=2.12.3" },
|
||||
{ name = "pyzmq", specifier = ">=27.1.0" },
|
||||
@@ -8298,8 +8169,8 @@ provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttens
|
||||
|
||||
[[package]]
|
||||
name = "vllm-router"
|
||||
version = "0.2.0"
|
||||
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl" }
|
||||
version = "0.2.1"
|
||||
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'aarch64' and sys_platform == 'linux'",
|
||||
]
|
||||
@@ -8312,7 +8183,7 @@ dependencies = [
|
||||
{ name = "uvicorn" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:07b4b18155231c926334a497db504767930fb81758049cbd9113c1e9f9c2ba69" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:0420aba42df1c970a78e1c4d4062eb00498e397f2dd506bade39eb915bf807b6" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
@@ -8331,8 +8202,8 @@ provides-extras = ["dev"]
|
||||
|
||||
[[package]]
|
||||
name = "vllm-router"
|
||||
version = "0.2.0"
|
||||
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
version = "0.2.1"
|
||||
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'x86_64' and sys_platform == 'linux'",
|
||||
]
|
||||
@@ -8345,7 +8216,7 @@ dependencies = [
|
||||
{ name = "uvicorn" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:bac193bedf10f9a0265fe4fdaae0f0418574cd1f15c45f27da1b4a2bae8c10b8" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:046591cac21424997600d30b500bbaa3c450601e8b2b4fad6db9d142d1c36a0e" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
|
||||
Reference in New Issue
Block a user