Compare commits

...
Author SHA1 Message Date
minh hoangandGitHub 96fa737c35 fix(docker): keep the editable verifiers when installing the prime CLI (#3705)
## Summary

Published prime-rl images since #3635 (2026-09-22) ship the PyPI
`verifiers==0.2.0` wheel instead of the submodule editable, and the
orchestrator and env-server entrypoints fail at import as a result. This
installs the prime CLI with its verifiers requirement overridden so the
editable stays, and asserts that at build time.

## What's wrong

`Dockerfile.cuda` installs the prime CLI after the lockfile sync (`uv
pip install 'prime>=0.7'`). Every prime release since 0.6.30 (prime#879,
2026-08-31) pins `verifiers==0.2.0`, so that install uninstalls the
editable verifiers (0.3.x, pretend version `0.3.2.dev137`) and replaces
it with the 0.2.0 wheel. Observed on a pristine `v0.9.1.dev128` pod on
telus:

```
$ uv run --no-sync orchestrator --help
  File ".../prime_rl/configs/orchestrator.py", line 160, in EnvConfig
    env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
AttributeError: module 'verifiers.v1' has no attribute 'SingleAgentEnvConfig'

$ uv run --no-sync env-server --help
  File ".../prime_rl/entrypoints/env_server.py", line 9, in <module>
    from verifiers.v1.runtimes import set_base_sandbox_labels
ImportError: cannot import name 'set_base_sandbox_labels' from 'verifiers.v1.runtimes'
```

`uv pip check` on the image reports 107 incompatibilities, all `...
requires verifiers>=0.3.1, but 0.2.0 is installed`.

Runs that install a Hub env at pod start survive by accident: `prime env
install` pulls an env that requires `verifiers>=0.3.1`, which drags
verifiers 0.3.x from PyPI back in before the orchestrator imports it.
Runs on baked envs get no such repair. The nightly FFT configs are all
baked envs, and nightly FFT has failed every day since 9/24.

An older CLI is not an option: the last release without the pin (0.6.29)
needs a prime-sandboxes API that 0.3.0 removed, and prime-rl itself
requires `prime-sandboxes>=0.3.0`.

## Fix

- Install the CLI with `--overrides` on a one-line file containing
`verifiers`, so its `verifiers==0.2.0` requirement is ignored and the
editable is left alone. Everything else the CLI needs (prime-traces,
prime-sandboxes, openai, …) still installs as before.
- Assert in the same `RUN` that `verifiers` imports from
`/app/deps/verifiers`, so a regression fails the build rather than the
orchestrator.
- **This is a workaround, marked `FIXME(prime#940)` in the Dockerfile.**
The real fix is the prime CLI dropping verifiers as a dependency,
PrimeIntellect-ai/prime#940. Once that ships, remove the overrides file
and the `--overrides` flag here and in `scripts/docker-entrypoint.sh` on
#3686, which replays this step with the same override for the runtime
source overlay. Keep the import assertion.

## Verified

- The override was exercised on telus pods against the
`v0.9.1.dev127-4-gba81f7c5b-feat-runtime-source-overlay` image (whose
entrypoint runs the identical command after re-syncing the editables):
verifiers stays at `0.3.2.dev137` from `deps/verifiers`, `prime
--version` and `uv run --no-sync prime env install
primeintellect/wordle` work, `orchestrator --help` and `env-server
--help` start, `uv pip check` drops from 107 incompatibilities to 7 (six
pre-existing lockfile inconsistencies plus the intentional `prime
requires verifiers==0.2.0`). A full hosted run (reverse-text, 20 steps)
completed on that venv.
- This Dockerfile change itself: image build dispatched from this
branch, result below.

Build from this branch: dispatched, result pending.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes Docker venv composition for a dependency that prime-rl
entrypoints rely on; mitigated by a build-time import-path assertion,
but image builds and baked-env runs depend on the override staying
correct.
> 
> **Overview**
> Published CUDA images broke **orchestrator** and **env-server**
because installing `prime>=0.7` after `uv sync` pulled PyPI
`verifiers==0.2.0` over the repo’s editable under `deps/verifiers`
(0.3.x APIs).
> 
> The **prime CLI install step** in `Dockerfile.cuda` now writes a
one-line `uv pip install --overrides` file (`verifiers`) so the CLI’s
pinned verifiers requirement is ignored while other CLI deps still
install. A **build-time assert** checks `verifiers` resolves under
`/app/deps/verifiers`. Comments mark this as a temporary
**FIXME(prime#940)** until the CLI drops verifiers; the entrypoint
overlay in `scripts/docker-entrypoint.sh` is called out as needing the
same cleanup later.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
22c9bfd1c9907da4662665f225ca10c3cdf6a930. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-27 16:53:54 -07:00
35aa06fbfa feat(eval): allow any config override on resume (#3690)
## Summary

`uv run eval --resume` used to compare the resolved config against the
interrupted attempt's `eval.json`. It refused any change outside a short
allowlist, which left out the solver `model`, everything under
`source.*.env` (including where each judge is served) and
`tasks_per_minute`. So a paused eval couldn't move to a new endpoint
serving the same weights under another name, such as a self-hosted
router becoming a hosted API. The only way out was `--clean`.

This PR removes that validation (`RESUMABLE`, `config_diff`,
`check_config`, `previous_config`), so any field can be overridden on
resume. It's up to whoever resumes to keep the measurement consistent.
The resolved config is still written beside each attempt's episodes
(`stamp_config`), so every attempt records what it ran with.
`docs/eval.md` still says a resume that changes the model, sampling or
env stops with the differing paths. That's no longer true and needs a
follow-up.

## Test plan

- Removed the tests for the deleted functions. `pytest tests/unit/eval`
passes (7 tests).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Resume can now mix previously landed episodes with a different model,
sampling, or env configuration, which can invalidate eval comparability
if operators override carelessly.
> 
> **Overview**
> **`uv run eval --resume` no longer compares the new resolved config to
the interrupted attempt's stamped `eval.json`.** The allowlist-based
guard (`RESUMABLE`, `config_diff`, `check_config`, `previous_config`) is
removed, so fields like model, sampling, env/judge endpoints, and source
layout can all change when resuming instead of forcing `--clean`.
> 
> Resume still loads landed episodes from the trace stream and stamps
the current config per attempt via `stamp_config`; only the validation
step in `Eval.run` is dropped. Module docs now state that **any config
may be overridden** and consistency is the operator's responsibility.
> 
> Unit tests for config checking and `previous_config` lookup were
removed; remaining resume tests (`plan`, `take_landed`, trigger
integration) are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
06482534d862782e1a844ea9f8d5c3f5c37310ac. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 14:43:05 -07:00
718635b2ca feat: treat timed-out rollouts as their own outcome (#3702)
## Summary

Companion to PrimeIntellect-ai/verifiers#2693, which stops a rollout
whose stage deadline expires as `<stage>_timeout` with
`Trace.is_timeout` set (scored, not errored).

- Training keeps main's semantics: the dispatcher records a `Timeout`
error on a timed-out train trace, so it stays out of the batch and
counts under `has_error`. Eval keeps the timeout as a scored outcome.
- Metrics: `is_timeout` joins the trace rates
(`<scope>/{all,effective}/<agent>/is_timeout/mean`) next to
`is_truncated`; `EpisodeMetrics.is_timeout` over the full cohort feeds
the console summary lines (`... | Truncation 0.0% | Timeout 100.0%`) for
train, online eval and standalone eval.
- W&B overview and dashboard metric sections plot
`all/<agent>/is_timeout/mean`.
- Trace index rows carry `timeout` (the episode's `is_timeout` or any
trace's); the dashboard series expose it.
- Dashboard: yellow (`--timeout`) marks for timed-out episodes on the
overview tile (`timeout rate`), episode cells, swarm points,
timing/token strips, episode table rows (with a `timed out (<stop>)`
title), trace tabs and the timeline state; the trace meta panel shows
`is_timeout`.
- Dispatcher: a timed-out eval trace with zero turns stays a timeout
instead of being promoted to an `EmptyTrajectory` error; it is scored
and counted under `is_timeout`.
- Bumps `deps/verifiers` to verifiers `main` with #2693 merged.

## Breaking

- In evals, a rollout that hits its `timeout.rollout` (or
setup/finalize/scoring) budget no longer counts under `has_error`: it
lands `ok` with `stop_condition = "<stage>_timeout"`, is scored, and
enters the `effective` subset like a truncated rollout does. Training is
unchanged: a timed-out rollout is still an error (now typed `Timeout`,
with `is_timeout` set alongside).

## Verification

Ran off this branch with the verifiers companion on `PYTHONPATH`:

```
uv run eval gsm8k -n 4 -r 1 -c 4 -m alibaba/qwen3.5-flash --env.agent.harness.id null --env.agent.runtime.type subprocess --env.agent.timeout.rollout 2
```

Before the dispatcher change: `Error 100.0% | Truncation 0.0% | Timeout
0.0%`, every trace re-labelled `EmptyTrajectory`. After: `Error 0.0% |
Truncation 0.0% | Timeout 100.0%`, metrics `is_timeout/mean = 1.0`,
`stop_condition/agent_timeout = 1.0`, index rows `ok=true,
stop_condition=agent_timeout, timeout=true`. A control run with the
default budget lands `agent_completed`, `timeout=false`, `Timeout 0.0%`.

Dashboard driven headlessly with playwright against both runs: `timeout
rate` tile `100%` in `rgb(255, 209, 102)`, every episode cell/row class
`timeout`, rows titled `timed out (agent_timeout)`, trace meta
`is_timeout true` / `ok true`; the control run shows `0%` and no marks;
no page errors.

`tests/unit/orchestrator`, `tests/unit/eval` and
`tests/unit/test_dashboard_timeline.py` pass.


## Screenshots

Eval with `--env.agent.timeout.rollout 2`: the overview tile and episode
cells read yellow, the traces table marks each row's edge yellow, and
the trace viewer lists the timed-out episodes with `is_timeout true` /
`ok true`.


![overview](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/assets/is-timeout/timeout-2s-overview.png)

![traces](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/assets/is-timeout/timeout-2s-traces-table.png)
![trace
viewer](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/assets/is-timeout/timeout-2s-traces.png)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Eval cohort semantics change (timeouts move off `has_error` onto
`is_timeout`), and the dispatcher path that promotes empty trajectories
to errors now explicitly exempts timed-out eval traces—worth validating
against downstream dashboards and monitors that assumed timeouts were
errors.
> 
> **Overview**
> Rollouts that hit a stage deadline (`<stage>_timeout`) are now a
**distinct outcome** from errors and truncation, with **`is_timeout`**
tracked alongside **`is_truncated`** in orchestrator metrics, console
summaries, W&B/dashboard metric panels, and docs.
> 
> **Training vs eval:** On **train**, the dispatcher still drops
timed-out traces from the batch by attaching a **`Timeout`** error and
marking the trace **`ok=false`** (same exclusion as before, now typed).
On **eval**, timeouts stay **`ok`** and scored; zero-turn timeout traces
are no longer relabeled as **`EmptyTrajectory`** errors.
> 
> **Observability:** Trace index rows and eval series expose
**`timeout`**; the dashboard uses yellow styling for timeout rate,
episode cells, swarm dots, tables, timeline state, and trace meta
**`is_timeout`**. Eval success logs and standalone eval runner output
add a **Timeout** percentage next to truncation/error.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
83c0ce4c920aa0fb55eea97c251db18ec763053f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-27 13:12:08 -07:00
f557d7593f feat: shared env block for train and eval sources (#3695)
## Summary

- **Group `env` block**: `[orchestrator.train]`, `[orchestrator.eval]`,
the `[eval]` block of `sft`, and the top level of `uv run eval` each
take an `env` block. Every source of the group inherits it through
`vf.merge_env_defaults`, and a source's own `env` values win.
- **Only shared knobs**: the block is typed as `vf.SharedEnvConfig`. It
takes `retries`, `timeout`, `max_concurrent_agents`, `interception`,
`taskset.task`, and `taskset.system_prompt`. Env ids, taskset ids, and
agent roles stay on each source and are rejected in the group block. So
one group can mix single-agent and multi-agent envs.
- **Eval shorthands**: `<taskset-id>` and `--env.<field>` keep their
single-source meaning. Next to a TOML that defines `[[source]]` blocks,
`--env.<field>` now sets the shared block instead of erroring, e.g. `uv
run eval @ sources.toml --env.retries.max-retries 3`.
- Pin `deps/verifiers` to the merged
[verifiers#2690](https://github.com/PrimeIntellect-ai/verifiers/pull/2690),
which adds `SharedEnvConfig` and `merge_env_defaults`. Raise the
`verifiers` minimum to `0.3.2.dev143`, its first release, in both
`pyproject.toml` files, so the slim `prime-rl-configs` install gets it.
- Update `docs/eval.md` and `docs/configuration.md`.

## Verification

- Composed `configs/basic/reverse-text/rl.toml` with an overlay that has
two train and two eval sources. Each group's `env` block sets
`retries.max_retries`, `retries.include`, `timeout.episode`,
`max_concurrent_agents`, and `taskset.system_prompt`. One source per
group overrides `retries.include` and `timeout.episode`. The other
source got every group value. The overriding source kept its two values
and inherited the rest. The same held after re-validating the resolved
`OrchestratorConfig` dump.
- Repeated the check with the same blocks in a `uv run eval` TOML, plus
a `proposer-solver` source. The multi-agent source inherited the shared
values and kept its `proposer` settings. The resolved `eval.json`
re-validates to the same dump.
- `--env.retries.max-retries 5 --env.retries.include A B` next to that
TOML reached every source, except that the overriding source kept its
own `include`.
- A group block with `id`, `agent.*`, `taskset.id`, or a misspelled
field fails with one error at `env.*`.
- `uv run eval gsm8k --env.agent.harness.id bash --env.taskset.split
test` still configures the single source.
- `pytest tests/unit/eval tests/unit/test_configs.py`: 202 passed.
- Built the `prime-rl-configs` wheel and installed it in a clean venv,
as the slim-install job does. It resolved `verifiers 0.3.2.dev143`, and
the configs imported with no heavy deps.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how train/eval env configs are merged at parse time, so
misconfigured shared blocks or invalid shared-only fields could affect
every source in a group; scope is config/CLI rather than training logic
itself.
> 
> **Overview**
> Adds a **group-level `[env]` block** on orchestrator train/eval source
groups (and standalone eval) so shared knobs—retries, timeouts,
concurrency caps, interception, shared taskset fields—apply to every
source, with per-source `env` still winning on conflict. Config
validation layers defaults through `merge_group_env` and verifiers’
`SharedEnvConfig` / `merge_env_defaults`.
> 
> **Eval CLI behavior** changes for multi-source TOMLs: `--env.*` now
targets the shared block instead of being rejected (single-source
`<taskset-id>` shorthands are unchanged and still cannot mix with
`[[source]]` TOMLs). Docs and unit tests cover the new TOML shape and
shorthand routing.
> 
> Pins **verifiers** to `>=0.3.2.dev143` in the root and
`prime-rl-configs` packages (lockfile updated).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8aef01e0cdd6baaf1275e06f33bf0091c548913a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 13:02:01 -07:00
f87fd0eb33 fix(examples): set group_size=8 in GRPO recipes (#3693)
## Summary

- Set `orchestrator.group_size = 8` in the INTELLECT-3.1 and Qwen3
math/SWE standalone RL examples.
- Prevent GRPO's default group size of 1 from giving every rollout a
zero group-relative advantage.
- Keep existing explicit group sizes, including GLM base configs used by
overlays.

## Verification

- Parsed each changed TOML through `RLConfig.model_validate`; all three
resolve to group size 8 for every train source.
- `git diff --check` passed.

Co-authored-by: Konstantin Dunas <git@hallerite.com>
2026-09-27 00:27:04 -07:00
Mika SenghaasandGitHub 12001f3167 fix: update eval dependency pins (#3694)
## Summary

- Pin verifiers to `6a82e5d`, which includes the [Bash/Null certifi
fix](https://github.com/PrimeIntellect-ai/verifiers/pull/2614) and the
[nano-rlm certifi
pin](https://github.com/PrimeIntellect-ai/verifiers/pull/2688).
- Pin prime-envs to `647ff7a`, which includes the [GPQA judge
fix](https://github.com/PrimeIntellect-ai/prime-envs/pull/845), [DeepSWE
missing-test
scoring](https://github.com/PrimeIntellect-ai/prime-envs/pull/847), and
[Apex Compose host
images](https://github.com/PrimeIntellect-ai/prime-envs/pull/842).
- Refresh `uv.lock`. Exclude `tau2-bench` from the shared workspace
because its new Tau2 dependency requires LiteLLM below 1.82.7, while
Harbor requires 1.92.0 or newer.

## Breaking

- `uv sync --all-packages` no longer installs `tau2-bench`. Install and
run it in a separate environment until its Tau2 and Harbor LiteLLM
requirements can share one lock.

## Verification

- `uv lock --check` and `uv sync --all-packages --all-extras --locked
--dry-run --quiet` passed.
- The five-source Intellect 4 GLM-5.3 eval composition resolved with the
intended model, max reasoning effort, harnesses, group sizes, and
rollout timeouts.
- `uv run --no-sync eval @ configs/debug/eval/multi-env.toml --dry-run`
passed.
- `uv run --no-sync rl @ configs/basic/wordle/rl.toml --dry-run` passed.
- A one-task `pi-terminal-bench-2` financial-document rollout on
`internal/glm-5.3-fast` completed with reward 1.0, 55 turns, and 0.0%
error.
- `git diff --check` passed.

Apex remains excluded from prime-rl's shared workspace because it pins a
separate verifiers git revision. Its new Compose host images still need
an Intellect 4 rollout check before Apex rejoins that suite.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking for anyone relying on `uv sync --all-packages` to install
`tau2-bench`; they must use a separate environment until LiteLLM
constraints align.
> 
> **Overview**
> **`tau2-bench` is removed from the shared `uv` workspace** so `uv sync
--all-packages` can keep Harbor’s **`litellm>=1.92.0`** without fighting
Tau tasksets’ **`litellm<1.82.7`**. The workspace **`exclude`** list now
includes `deps/prime-envs/environments/tool_use/tau2_bench`, and the
comment documents that split (alongside the existing Apex / tau2_synth /
tau3 exclusions).
> 
> **`uv.lock` is refreshed** accordingly: `tau2-bench` and the git
**`tau2`** package drop out of the lock, along with their former
transitive stack (e.g. gymnasium, matplotlib, langfuse, redis). Several
editable prime-envs packages show **patch version bumps** in the lock
(Lean/math envs, `gpqa`, `lean-common`, etc.) as part of the same
dependency refresh.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5f1504314e8e97d8e8bae5ebc49381cc30822106. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-26 22:43:55 -07:00
1cf683267d chore: drop CLAUDE.md in favor of native AGENTS.md (#3691)
## Summary

- Delete `CLAUDE.md`. It only imported `@AGENTS.md`, and Claude Code
reads `AGENTS.md` natively since v2.1.277
([docs](https://code.claude.com/docs/en/memory.md#agents-md)).
- Update the skills line in `AGENTS.md` to name both the
`.claude/skills` (Claude Code) and `.agents/skills` (Codex) symlinks.
Neither tool reads the other's skills folder, so both symlinks stay.

## Breaking

- Claude Code sessions older than v2.1.277 read only `CLAUDE.md`, so
they no longer load the repo instructions. On Bedrock or with telemetry
disabled, the minimum is v2.1.281. Migration: update Claude Code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation-only agent config changes with no runtime or application
code impact; the only caveat is older Claude Code versions losing loaded
instructions.
> 
> **Overview**
> Removes **`CLAUDE.md`**, which only re-exported **`AGENTS.md`** via
`@AGENTS.md`, so agent instructions live in a single file now that
Claude Code reads **`AGENTS.md`** natively.
> 
> The **Skills** section in **`AGENTS.md`** now documents both symlink
targets: **`.claude/skills/`** for Claude Code and **`.agents/skills/`**
for Codex, since each tool only loads its own folder.
> 
> **Breaking:** Claude Code builds before native **`AGENTS.md`** support
(v2.1.277+, v2.1.281+ on Bedrock/telemetry-off) no longer pick up repo
instructions unless upgraded.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
205ca092421609d40c938a16c78a75051c67ec2e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 18:59:04 -07:00
Xuan-Phi NguyenandGitHub b944873248 fix(trainer): measure MoE violation per EP group and microstep (#3684)
## Summary

`max_vio` is intended to capture the largest expert routing violation
for each training microbatch across an entire EP group. The metric uses
expert token counts, not the number of tokens allocated to an EP rank.
For each microbatch, we take the maximum across MoE layers and EP
groups; `max_vio/mean` and `max_vio/max` then summarize those microbatch
maxima within the logged optimizer step.

### Why the old numbers depended on topology

The router records selections for every expert on each rank before
dispatch, but the original `get_load_balance_stats` computed violation
from that rank's **local** counts. With CP, each rank sees only a
sequence shard. At fixed EP, changing CP or DP changes the local token
population and the number of rank readings. SFT averaged layer
violations locally, took a world maximum, and averaged it over gradient
accumulation; RL's `/mean`, `/median`, `/std`, and `/max` summarized all
local layer/rank/microbatch readings. Those reductions did not describe
one EP group's routed traffic, so equal EP degrees could report
substantially different values.

### What changed

- Sum per-expert token counts and routing-confidence sums within the EP
group **before** computing per-layer violation and confidence. Reset
both buffers after reading them. Remove the unused `reset_stats` and
`try_to_avoid_padding_experts` switches while keeping their previous
default behavior.
- In RL and SFT, read routing statistics after **each microbatch**
through the shared `get_global_moe_stats` helper. Take the maximum
violation across layers, then across the `dp_cp` mesh. This preserves a
short-lived imbalance instead of pooling counts across microbatches.
- Aggregate those per-microbatch global maxima into `max_vio/mean` and
`max_vio/max` for each optimizer step. RL also retains the other
distribution statistics supplied by `Tensors.compute_stats`; SFT now
publishes `/max` alongside `/mean`.
- Clear SFT validation routing buffers before the next training step.

### Validation: same EP, more trainer replicas

These RL runs used Qwen3-30B-A3B-Thinking-2507, EP=4, CP=1, sequence
length 32,768, group size 8, and learning rate 1e-6. The experiment
configs were temporary; the tracked `math.toml` is restored and
`math2.toml` is not included in this PR.

| Run | Topology | `orchestrator.batch_size` | Average `max_vio/mean` |
Average `max_vio/max` |
| --- | --- | ---: | ---: | ---: |
|
[math1-v1](https://wandb.ai/primeintellect/qwen30b-math/runs/a2da2577b6c54320bc1d997022b0ebe7)
| 8 GPUs total: 4 train + 4 inference; one EP group, `dp_replicate=1` |
16 | 6.7774 | 7.7035 |
|
[math2-v1](https://wandb.ai/primeintellect/qwen30b-math/runs/d69f377a0cb5425b99b455e6c8101118)
| 16 GPUs total: 8 train + 8 inference; two EP groups, `dp_replicate=2`
| 32 | 6.8707 | 7.7897 |

Values are arithmetic averages of the logged metrics over the **shared
steps 1–99**, read from W&B. The two-group run is 1.38% higher on
`/mean` and 1.12% higher on `/max`. Its rollouts are different, so this
is a comparability check, not a paired-input equality test. This
comparison does not exercise CP. The shared-helper refactor followed
these runs and preserves their reduction arithmetic.

Relative to the original `examples/advanced/qwen3-30b-a3b/math.toml`,
the experiments used:

- **Math1:** single-node deployment with 4 train and 4 inference GPUs
instead of 2 train and 2 inference nodes; EP 4 instead of 8;
`orchestrator.batch_size` 16 instead of 512; inference TP 4 instead of
8.
- **Math2:** 1 train and 1 inference node instead of 2 each; EP 4
instead of 8; `dp_replicate=2`; `orchestrator.batch_size=32` instead of
512; inference TP 4 and DP 2 instead of TP 8. Its Slurm job name was
`math2-qwen30b` instead of `math-qwen30b`.
- **Both:** added `max_steps=400`, `orchestrator.group_size=8`, Slurm
partition `all`, and a run-specific `VLLM_CACHE_ROOT`; changed
`orchestrator.concurrency.initial_inflight` from 1024 to 64 and added
`max_inflight=128`. Other settings followed the original config.

### Remaining topology effects

At fixed EP, equal violation readings are not guaranteed. For
fixed-length packed SFT, the per-microbatch token population in one EP
group is `micro_batch_size × (EP / CP) × seq_len`. Increasing CP makes
that population smaller, and the relative count imbalance noisier,
unless `micro_batch_size` scales with CP. Increasing trainer nodes at
fixed EP creates more EP groups (`trainer_world_size / EP`); taking the
maximum over more groups tends to raise both logged `/mean` and `/max`
slightly through an order-statistics effect. With fixed CP and global
SFT batch size, adding DP ranks also reduces gradient accumulation steps
and the number of microbatch samples in each logged step.

For a stricter fixed-EP comparison, keep tokens per microbatch per EP
group constant (`micro_batch_size` proportional to CP) and scale the
global batch size with trainer world size. For example, double batch
size when trainer world size doubles, whether the added ranks come from
DP or CP. RL can still vary with actual sequence lengths and rollout
contents.

Checks: `uv run --no-sync pytest tests/unit/train/models/test_moe.py -q`
(15 passed), `ruff check`, `ruff format --check`, and `git diff --check`
passed for the PR changes.
2026-09-26 10:11:07 -07:00
c28afbbae2 fix: keep workstation blackwell on fa2 in auto-attn (#3681)
## Summary

- Gate `attn='auto'` → FA4 on SM10x/SM11x (`major in (10, 11)`) instead
of `major >= 10`. FA4's own interface uses the same families for its
native tcgen05/TMEM Blackwell path.
- B200/GB200 (SM100) and B300/GB300 (SM103) keep FA4, so the goal of
#3655 stays intact. Hopper keeps FA3.
- Workstation Blackwell (SM12x, e.g. RTX PRO 6000) resolves to FA2
again. #3655 sent it to FA4 as a side effect.
- Update the `attn` comment in `docs/scaling.md`.

| GPU | CC | `attn: auto` |
|---|---|---|
| H100/H200 | SM90 | FA3 |
| B200/GB200 | SM100 | FA4 |
| B300/GB300 | SM103 | FA4 |
| RTX PRO 6000 | SM120 | FA2 (main: FA4) |

## Verification

5 steps of `configs/ci/integration/reverse-text/start.toml` on 2x RTX
PRO 6000 (SM120), same venv (vllm 0.29):

**Before (main `b963ceda3`)**: `Auto-resolved attn='auto' to
'flash_attention_4' (SM120)`
```
Step 1 | Mismatch KL 0.2967 | Grad. Norm nan
Step 2 | Loss nan | Entropy nan | Mismatch KL nan | Grad. Norm nan   (run then stalls: NaN weights reach inference)
```

**After (this branch)**: `Auto-resolved attn='auto' to
'flash_attention_2' (SM120)`
```
Step 1 | Mismatch KL 0.0008 | Grad. Norm 0.8843 | Reward 0.19
Step 3 | Mismatch KL 0.0012 | Grad. Norm 0.8779 | Reward 0.15
Step 5 | Mismatch KL 0.0013 | Grad. Norm 1.6303 | Reward 0.46
Training finished!
```

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Small, targeted change to GPU-architecture gating at model setup;
lowers risk on SM12x by avoiding an incompatible FA4 path rather than
altering auth or data handling.
> 
> **Overview**
> **`attn='auto'` no longer picks Flash Attention 4 on every SM10+
GPU.** Resolution now uses FA4 only when the compute capability major is
**10 or 11** (datacenter Blackwell, e.g. B200/B300), keeps **FA3 on
Hopper (SM90)**, and uses **FA2 for everything else**—including
workstation Blackwell (**SM12x**, e.g. RTX PRO 6000), which lack the
tcgen05/TMEM path FA4 expects.
> 
> The **`resolve_auto_attn`** docstring and the **`attn`** comment in
**`docs/scaling.md`** are updated to match this split so docs and
runtime behavior stay aligned.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ab27534ec84dba23a2043dc65235e6b7ea57b41c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 15:58:24 -07:00
b963ceda3c perf(deepseek_v4): dynamic sparse attention slot count, no recompiles, per-query tile skipping (#3644)
The DSv4 sparse attention kernels compiled one kernel per gather width,
and HCA's width tracks the longest
document in the packed row, so every new width stalled training while
TileLang compiled. The kernels now
compile once per process and skip slot tiles no query can reach.

- `topk` was a compile key, so each new gather width recompiled; kernels
now take `Indices` as a free view
  `(B, S, G, n_tiles, tile)` with only `n_tiles = K / tile` dynamic.
- The tile size stays fixed so in-tile offsets stay provable; a fully
dynamic `topk` slowed the backward 24-29%.
- Each query loops only over tiles up to its last valid slot; the
skipped tiles are fully masked, so this is exact.

End to end, DeepSeek V4 Flash SFT on 8 B300 nodes (full model, 256k,
cp8/ep8, bf16, 20 steps, fresh compile
caches per arm). Real data packs 4-9 documents per row; fake data is one
document per row.

| data | arm | median step, 6-20 | total, steps 2-20 | MFU |
|---|---|---|---|---|
| real (scaleswe) | main | 19.20 s | 440.1 s | 46.7% |
| real (scaleswe) | this PR | 17.81 s (-7.2%) | 346.8 s (-21%) | 53.6% |
| fake | main | 16.87 s | | 57.5% |
| fake | this PR | 16.76 s (-0.7%) | | 57.8% |

On real data, main recompiles mid-run and spends 27-30 s on 8 of 19
steps; this PR compiles 28 TileLang
kernels in step 1 versus 356 for main, and losses match to 1e-4.

![Before/after timeline of a recompile
step](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/78da67f7cc8f89dec8032ea322ce488d5181b8c8/benchmarks/fp8_grouped_gemm/dsv4_attn_dynamism_stall.png)

Rank 0, step 5 of a traced 8-step run on a 6-layer one-node proxy with
real data
([config](https://github.com/PrimeIntellect-ai/prime-rl/blob/b339e8eafed9f39d832a5da0d2eae9a5a91b0b7a/benchmarks/fp8_grouped_gemm/sft_1n_scaleswe.toml)),
aligned at the step start.
On main the GPU idles 5.6 s and 4.2 s inside the sparse attention
forward and backward while TileLang compiles
new widths (cache file times: 4-7 compiles in 6 of the 7 steps after
step 1, versus none for this PR).
The untraced full-model numbers above are the timing claim.

Before:
[main@33e02a7](https://github.com/PrimeIntellect-ai/prime-rl/commit/33e02a7a183002aca0864c5afc1c2f5a50e48e37).
After: [real-data
config](https://github.com/PrimeIntellect-ai/prime-rl/blob/b339e8eafed9f39d832a5da0d2eae9a5a91b0b7a/benchmarks/fp8_grouped_gemm/sft_scaleswe.toml),
[fake-data
config](https://github.com/PrimeIntellect-ai/prime-rl/blob/b339e8eafed9f39d832a5da0d2eae9a5a91b0b7a/benchmarks/fp8_grouped_gemm/sft.toml).
Both real-data arms carry #3544's tool-call fix (`c7ba105d5`), which the
dataset needs.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 11:10:03 -07:00
samsjaandGitHub 3cc565eecb feat(eval): add a BetterStack heartbeat to eval runs (#3664)
## Summary

The trainer, sft, and orchestrator already beat a Better Stack
heartbeat; evals (and the sft online-eval, which shares the
`EvalRunner`) were invisible to it. This gives the eval its own
`heartbeat` config: one ping per landed episode.

There is deliberately no startup ping: the first landed episode is the
first beat. The gap between run start and the first episode (pool boot,
env servers, the first episode's full duration) would otherwise sit
inside the ping stream as an abnormally long silence that flips a
healthy run stale. Until the first beat, the heartbeat has simply never
been pinged.

When episodes stop landing, the pings stop and Better Stack flips the
heartbeat stale after its grace period. Size that period + grace above
the longest legitimate gap between episodes. The `Heartbeat` never runs
more than one ping in flight (a `beat()` while one is pending is
dropped), so continuous landings cost at most ~one request per
round-trip.

The orchestrator keeps its existing per-batch heartbeat; nothing there
changes.

## Usage

```toml
[heartbeat]
url = "https://uptime.betterstack.com/api/v1/heartbeat/<token>"
```

Set it on the `eval` config (also available to the sft online-eval via
its `[eval]` block).

## Validation

- `ruff check` + `ruff format` clean.
- `uv run pytest tests/unit/test_configs.py
tests/unit/eval/test_cli.py`: identical to the unmodified tree (67
pre-existing failures in this env from missing verifiers hub plugins;
126 pass).
- Live 30-minute run against a real Better Stack heartbeat URL using the
exact `Heartbeat` class: 60 pings at a 30s cadence, all HTTP 200 (RTT
126-344ms); silence after stop, as the dashboard's staleness window
expects.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Optional observability hook with no change to eval logic, auth, or
data paths when `heartbeat` is unset.
> 
> **Overview**
> Eval and SFT online-eval (shared `EvalRunner`) can now opt into Better
Stack uptime monitoring via an optional **`heartbeat`** block on
**`ServedEvalConfig`**, matching trainer/orchestrator/SFT.
> 
> When configured, **`EvalRunner`** creates a **`Heartbeat`** at setup
and pings **once per successfully landed episode**—not on dispatch
failures or cancellations, and **not at startup**. The first beat is the
first landing so long boot/first-episode gaps do not look like stale
silence in Better Stack; if episodes stop (dead inference, hang, or
clean exit), pings stop and the monitor goes stale after grace.
> 
> Configure with `[heartbeat] url = "..."` on the eval config (or SFT
`[eval]`); size Better Stack period + grace above the longest gap
between landed episodes.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
75add6ed9027ef8b2f2aab2a63c945db38633655. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-25 10:59:31 -07:00
samsjaandGitHub f52f6a69df add sft example glm5 (#3666)
<!-- CURSOR_SUMMARY -->
> [!NOTE]
> **Low Risk**
> Documentation and example TOML only; no changes to training, auth, or
runtime code paths.
> 
> **Overview**
> Adds **supervised fine-tuning (SFT)** to the GLM-5.3 advanced example
alongside the existing RL/inference guides.
> 
> New TOML overlays under `sft/h200/` target **8-GPU H200 nodes** (8
training nodes, `cp`/`ep` = 8, 131k `seq_len`): **`base.toml`** wires
`zai-org/GLM-5.3-BF16`, custom MoE training settings, `sign_sgd`, and
Slurm; **`math-10k.toml`** points at
`PrimeIntellect/INTELLECT-3-SFT-10K` (math split); **`fake.toml`** swaps
in fake data for dry runs.
> 
> The README **SFT** section documents composing configs with `uv run
sft @ ...` and notes the existing dashboard can monitor SFT runs.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
81d7877b4e06ec9f3865006f6b309ac0b0e95aff. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

## Layout

The SFT overlays live under `examples/advanced/glm-5.3/sft/h200/` — an
`h200/` subfolder marks them as tuned for 8-GPU H200 nodes, and the
files drop the `sft-` prefix since the parent folder already says SFT:

- `sft/h200/base.toml` — base SFT config: `zai-org/GLM-5.3-BF16` on 8
training nodes with the same large-scale knobs as RL (custom impl,
`cp`/`ep` = 8, 131k context, AC offloading, `sign_sgd`, SLURM job
`glm53-sft`).
- `sft/h200/math-10k.toml` — data overlay:
`PrimeIntellect/INTELLECT-3-SFT-10K` (math split).
- `sft/h200/fake.toml` — fake-data overlay with `force_balanced_routing`
for dry runs.

Launch:

```bash
uv run sft @ examples/advanced/glm-5.3/sft/h200/base.toml @ examples/advanced/glm-5.3/sft/h200/math-10k.toml
```

The README SFT section documents the command, the fake-data variant, and
the dashboard. Both compositions validate with `sft --dry-run`.
2026-09-25 10:58:54 -07:00
Mika SenghaasandGitHub 9cc215df69 chore: bump prime-envs to latest main (#3672)
## Summary
- Bump the `deps/prime-envs` submodule from `1213b7336` to `b677502a2`
(latest `main`). Pulls in:
-
[prime-envs#818](https://github.com/PrimeIntellect-ai/prime-envs/pull/818):
separate original OfficeQA from repaired PI-OfficeQA (new
`pi-officeqa-pro-v2` env).
-
[prime-envs#832](https://github.com/PrimeIntellect-ai/prime-envs/pull/832)
(+ [#835](https://github.com/PrimeIntellect-ai/prime-envs/pull/835),
[#836](https://github.com/PrimeIntellect-ai/prime-envs/pull/836)):
switch `swebench_pro` to SWE-bench Pro V2, constraining image repository
choices.
-
[prime-envs#824](https://github.com/PrimeIntellect-ai/prime-envs/pull/824):
SWE-Atlas Harbor environments (new `swe-atlas-qna`, `swe-atlas-rf`,
`swe-atlas-tw` envs).
-
[prime-envs#811](https://github.com/PrimeIntellect-ai/prime-envs/pull/811):
PI-DeepSWE while preserving original DeepSWE (new `pi-deepswe` env).
-
[prime-envs#801](https://github.com/PrimeIntellect-ai/prime-envs/pull/801):
APEX-Agents 1.1 with its reference harness and Harbor grading (new
`apex-agents` env).
-
[prime-envs#810](https://github.com/PrimeIntellect-ai/prime-envs/pull/810):
`pi-terminal-bench-2` with repaired QEMU task images.
-
[prime-envs#829](https://github.com/PrimeIntellect-ai/prime-envs/pull/829):
agentic Lean tasksets on a shared `lean-common` base (new cambench,
combibench, discover-and-prove, formalmath, kimina, matholympiadbench,
minif2f, numina, proofnet, proverbench, putnambench tasksets; removes
`deepseek-prover` and `goedel-pset`).
-
[prime-envs#838](https://github.com/PrimeIntellect-ai/prime-envs/pull/838):
raise Verifiers dev requirements to 0.3.2.dev137, matching our vendored
`deps/verifiers` pin.
- Relock `uv.lock`: new workspace members are auto-discovered via
`deps/prime-envs/environments/*/*`; `lean-common` joins as an editable
path source.
- Exclude `apex-agents` from the workspace: it pins `verifiers` as a git
rev (`328c0b1`), which conflicts with the editable workspace member —
same lock-conflict pattern as `tau2_synth` and `tau3_bench`.

## Validation
- `uv lock` and `uv lock --check` pass (581 packages resolved).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Large dependency-graph churn and benchmark harness upgrades (e.g.
SWE-bench Pro V2) can affect eval/training env selection, though changes
are confined to workspace packaging and the lockfile.
> 
> **Overview**
> Updates the monorepo lockfile and workspace rules after advancing
**`deps/prime-envs`**, so newly added Harbor/SWE/Lean/search env
packages resolve alongside the editable **`verifiers`** pin.
> 
> **`pyproject.toml`** documents why **`apex-agents`** is excluded from
the uv workspace (it pins **`verifiers`** to a git rev, same conflict
pattern as **`tau2_synth`** / **`tau3_bench`**) and adds that path to
**`tool.uv.workspace.exclude`**.
> 
> **`uv.lock`** registers many new auto-discovered workspace
members—including **`lean-common`**, agentic Lean tasksets (e.g.
**`cambench`**, **`proofnet`**, **`putnambench`**), PI variants
(**`pi-deepswe`**, **`pi-officeqa-pro-v2`**, **`pi-terminal-bench-2`**),
and **`swe-atlas-*`**—while dropping **`deepseek-prover`** and
**`goedel-pset`**. Several existing packages bump versions and tighten
**`verifiers`** requirements to **`>=0.3.2.dev137`** (notably
**`deep-swe`**, **`swebench-pro`**, and the migrated Lean envs).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5d592eccccbb09ad765d6663e12a91399a49e29b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-25 10:21:37 -07:00
NeoandGitHub 13c82f0551 Mario/increase moe mfu split size tensorize (#3665)
<html>
<head>

</head>
<body>

<p class="p1">This PR changes the split representation to use CPU
tensors.</p>

<h3><span class="s1"><b>Performance</b></span></h3>

<p class="p4">Benchmarked on Qwen3-30B-A3B with 8× H200, EP 8, balanced
routing, bf16, and no activation checkpointing.</p>



Version | Step time (3–30) | Tok/s/GPU | MFU (head_dim 128)
-- | -- | -- | --
main (job 1426) | 7.59s | ~8,635 | ~32.8%
CPU-tensor splits, this PR (job 1434) | 6.95s | ~9,430 | ~35.9%
torchtitan (job 1422) | 6.58s | ~9,960 | 37.8%




<p class="p1">Compared with <code>main</code>, this PR reduces step time
from <span class="s1"><b>7.59s to 6.95s</b></span> (~8.4% reduction),
increases throughput from <span class="s1"><b>~8,635 to ~9,430
tok/s/GPU</b></span> (~9.2% improvement), and raises MFU from <span
class="s1"><b>~32.8% to ~35.9%</b></span>.</p>

</body>
</html>

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Logic for split sizes is unchanged; this only alters tensor
layout/device timing for a performance path in distributed MoE routing.
> 
> **Overview**
> Improves **MoE expert-parallel token dispatch** in
`TorchTokenDispatcher` by building `input_splits` and `output_splits`
together and moving them to **CPU once** before the all-to-all.
> 
> Instead of two separate GPU reductions, the change **stacks** the
per-rank token counts from local and grouped expert histograms, sums
them, and calls `.cpu()` up front so `all_to_all_single` can read split
sizes (via `.tolist()`) **without an extra device sync** on the hot
path. Dispatch/combine still use the same split semantics; only where
the tensors live and when they are transferred changes.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e61d0bfdda7fe7ec7170b20eb60096d3552daa7a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-25 04:18:29 +02:00
7d25aaa0d2 docs: drop the standalone RL trainer entrypoint from the docs (#3634)
## Problem

`uv run trainer` calls `prime_rl.trainer.rl.train` directly, outside
torchrun, so the `env://` rendezvous has no
`RANK`/`WORLD_SIZE`/`MASTER_ADDR`/`MASTER_PORT` and the process dies
before any training starts:

```
ValueError: Error initializing torch.distributed using env:// rendezvous:
environment variable RANK expected, but not set
```

Every documented use of that entrypoint was therefore broken. Scott hit
it during onboarding on the README's own validation steps (#3633).

## Fix

Rather than defaulting the rendezvous env for a single-process group
(#3633), drop the standalone trainer from the docs — per the thread, it
isn't a path we want people on:

- **`README.md`** — removed "Validate your environment setup" step 4
(`uv run trainer @ configs/debug/fake/rl.toml`) and renumbered the
following steps. The remaining step 5 (`uv run rl @
configs/basic/reverse-text/rl.toml`) already exercises the trainer
end-to-end.
- **`docs/training.md`** — dropped the `uv run trainer` row from the
entrypoints table, and reworded the `uv run orchestrator` row that
pointed at a "separately-launched trainer".
- **`docs/scaling.md`** — the trainer-alone benchmark now launches under
torchrun, the way the `rl` launcher and
[`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py)
(what the CI benchmark matrix runs) already do.

Docs only — no code or config changes, and the `trainer` entrypoint
itself is untouched.

## Follow-up, not in this PR

`k8s/README.md`, `k8s/prime-rl/values.yaml` (the `trainer.command`
example), and the k8s section of `examples/basic/reverse-text/README.md`
still drive the trainer pod with `uv run trainer`, and hit the same
failure — the chart sets no rendezvous env on the trainer StatefulSet.
Fixing that means changing how the chart launches the trainer, not just
the prose, so it wants its own PR from someone who can run the
deployment.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation-only edits with no runtime or config changes.
> 
> **Overview**
> Documentation no longer recommends **`uv run trainer`**, which fails
on startup without torchrun/`RANK` because it invokes the RL trainer
outside distributed launch.
> 
> The README **environment validation** checklist drops the standalone
RL trainer step and **renumbers** the inference and full **`uv run rl`**
checks. **`docs/training.md`** removes the trainer row from the
entrypoints table and updates the **`uv run orchestrator`** note so it
no longer assumes a separately launched trainer. **`docs/scaling.md`**
changes the “RL trainer alone” benchmark to **`torchrun …
src/prime_rl/trainer/rl/train.py`**, matching how the **`rl`** launcher
and CI benchmarks run it.
> 
> The **`trainer`** CLI entrypoint is unchanged; this is prose-only.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
cb2aa3805b8e77dbb9e334961349c42a1c7462db. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 16:05:26 -07:00
samsjaandGitHub 5a0c80e54a docs(readme): drop stale FA3 source-build step; flash_attn_3 comes from prebuilt wheels (#3648)
## Why

Section 3.1 of the README ("Optional: Install Flash Attention 3")
claimed FA3 "has no wheels prebuilt" and instructed a manual source
build from the `hopper` subdirectory. This is stale — **prime-rl already
installs FA3 as a prebuilt wheel from the lockfile**:

- `pyproject.toml` resolves `flash_attn_3 = { index =
"pytorch-cu130-test" }` → `https://download.pytorch.org/whl/test/cu130`
- `uv.lock` pins `flash-attn-3 == 3.0.0` from that index (real compiled
wheels: `flash_attn_3-3.0.0-cp39-abi3-manylinux_2_28_x86_64.whl`, ~402
MB, plus an aarch64 build)
- `uv sync --all-extras` (step 4 of the same install section) pulls it
in via the `flash-attn-3` extra — same as `Dockerfile.cuda` (`--extra
flash-attn-3`)
- This has been the case since at least May (the source was
`pytorch-cu128-test` before `70117046a` moved it to `cu130-test`)

Since step 4 already installs FA3, the section documents a step that
must not be followed: building from git would fight the lock (its "uv
sync will uninstall the package" warning was describing a self-inflicted
problem).

## What

- Remove section 3.1 entirely. Nothing is lost: `flash_attn_3` arrives
prebuilt with `uv sync --all-extras`, and the `flash_attention_3`
backend / `attn="auto"` picks it up on Hopper GPUs.

Docs-only change, no code touched.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> README-only edit with no runtime or dependency behavior changes.
> 
> **Overview**
> Removes **README Manual Setup subsection 3.1**, which told Hopper
users to build Flash Attention 3 from the Dao-AILab git source and
warned that **`uv sync` / `uv run` would uninstall** that manual
install.
> 
> That guidance is outdated for this repo: **`flash_attn_3` is already
pulled in via the lockfile and `uv sync --all-extras`** (optional extra
from the PyTorch test index), so the extra source-build step conflicted
with the pinned wheel and described a problem users only hit if they
bypassed the lock.
> 
> Docs-only; install flow in step 4 is unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
921c72d02f42ab0a58fe4b10cd8fb227f1a3543f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-24 16:05:09 -07:00
e48c943c48 fix(orchestrator): save final checkpoint before finalizing the run (#3642)
## Problem

`Orchestrator.start()` writes the orchestrator's own final checkpoint in
its `finally` block **after** `monitors.finalize()`. Finalize is what
tells the launcher the run is done: on the fft k8s path, the platform
marks the run COMPLETED and uninstalls the release. So the
orchestrator's final checkpoint races teardown.

## Fix

Save the final checkpoint first, then finalize. Clean and forced exits
both still save; only the order relative to `monitors.finalize()`
changes.

## Scope

This PR first also made the orchestrator wait for the trainer's final
checkpoint. Per review, waiting for both components is the launcher's
job, as the SLURM template already does with `.trainer.done` /
`.orchestrator.done`, so that part was dropped. The k8s launcher side is
platform#5817 + fft#92 (Linear ENG-6341): the platform marks a run
COMPLETED and tears it down only once both the trainer and the
orchestrator have finished.

With those in place, teardown already waits past the orchestrator's
finalize, so this change is **defense-in-depth** there. It still matters
for any launcher that tears down on finalize alone, and it makes the
orchestrator's own "I'm done" signal truthful.

## Testing

- `uv run pytest tests/unit -m "not gpu"` (as in `cpu_tests.yaml`,
x86_64, `--all-extras`): 616 passed, 1 skipped. CI CPU tests pass on
this head.
- Not exercised on k8s with an image built from this branch; the telus
runs for ENG-6341 used the stock prime-rl image. The GPU integration
tests (which run the orchestrator end to end from this branch) are the
coverage for the reordering.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 15:56:03 -06:00
e521297df6 perf(deepseek_v4): fused in-place interleaved RoPE for DeepSeek-V4, matching vLLM (#3645)
Eager interleaved RoPE was a large share of each DeepSeek-V4 attention
layer: every site widened the
tables with `repeat_interleave`, rotated a copy of the 64 rope channels,
and rebuilt the whole
512-channel head with `torch.cat`. All five RoPE sites (q, kv,
compressed kv, indexer q, and the
inverse rotation of the attention output) now run one out-of-place
Triton kernel, adapted from
Megatron-LM and bit for bit with vLLM's `rotary_embedding`, making the
end-to-end SFT step 13-14%
faster on B300.

- RoPE tables were built every forward in bf16. They are now one static
fp32 `[cos | sin]` cache in
  vLLM's layout, indexed by position inside the kernel.
- q was normed and rounded to bf16, then rotated and rounded again.
`dsv4_q_norm_rope` does both in
fp32 with one rounding: exact matches with vLLM rise from ~69% of rope
channels to 99.9997%.
- `dsv4_rope` is a functional custom op whose backward is the inverse
rotation. An in-place version
needs an `autograd.Function` wrapper, because `register_autograd`
rejects mutating ops.
- Passing fp32 tables through `PackedContext` failed multi-node: FSDP's
`cast_forward_inputs` cast
them to bf16. Hence the cache lives on one rotary module that every
attention layer shares.

DeepSeek V4 Flash SFT on 8 B300 nodes, full model, bf16, 256k tokens,
cp8/ep8, selective AC. Median step
over steps 6-20 of 20, which skips the sparse-attention recompiles both
real-data arms hit (removed by
#3644). tok/s/GPU is the 32,768 packed positions each GPU processes per
step, padding included, over that
median. Losses match `main` to 1.5e-3 on identical samples:

| Per step, 8 B300 nodes | Fake: main | Fake: this PR | Real: main |
Real: this PR |

|----------------------------------|------------|---------------|------------|---------------|
| Median step time | 16.896 s | 14.641 s | 19.203 s | 16.474 s |
| tok/s/GPU | 1939 | 2238 | 1706 | 1989 |
| MFU | 57.4% | 66.2% | 46.7% | 53.2% |
| Peak reserved GPU memory, rank 0 | 244.0 GiB | 246.6 GiB | 246.7 GiB |
247.0 GiB |

Fake data is one 256k document per row; real data is the scaleswe SFT
set, 4-9 documents per row.

![Before/after main-stream kernels in one DeepSeek-V4 layer's attention
block](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/1210bc4eaea568a0247d04d79ca425a21051ee6c/benchmarks/ds-v4-rope-profile-v2.png)

**Figure:** Kernels on rank 0's main GPU stream during layer 2's
forward, in the last of five
`torch.profiler` steps of a 1-node, 6-layer run (256k tokens, cp8/ep8,
bf16). Both arms start at the
layer's first kernel, and the dashed line marks the end of its attention
block at the MoE router. The two
~7 ms `torch.cat` blocks per layer, which rebuild the heads around q's
RoPE and around the inverse
rotation of the attention output, are gone, shortening the block from
94.1 ms to 72.3 ms. The bottom panel
sums each kernel category over the whole step: `torch.cat` -180 ms and
the RoPE path's elementwise ops and
copies -145 ms, against +7 ms for the fused kernels, for -307 ms of
main-stream kernel time. The profiled
run explains the mechanism; the unprofiled full-model runs in the table
are the timing claim.

Before: [`main`
33e02a7](https://github.com/PrimeIntellect-ai/prime-rl/commit/33e02a7a183002aca0864c5afc1c2f5a50e48e37).
After:
[`04f7b8a`](https://github.com/PrimeIntellect-ai/prime-rl/commit/04f7b8a94e7d6482843eb871e938ded9f71427fb),
the in-place version this PR began as, with the
[fake](https://github.com/PrimeIntellect-ai/prime-rl/blob/2c671d77ed8fe639a568976c832e4ed00995542f/benchmarks/fp8_grouped_gemm/sft.toml),

[real](https://github.com/PrimeIntellect-ai/prime-rl/blob/2c671d77ed8fe639a568976c832e4ed00995542f/benchmarks/fp8_grouped_gemm/sft_scaleswe.toml)
and
[profiling](https://github.com/PrimeIntellect-ai/prime-rl/blob/2c671d77ed8fe639a568976c832e4ed00995542f/benchmarks/fp8_grouped_gemm/sft_1n_256k.toml)
configs. Real-data runs add #3544's tool-call fix

([`c7ba105`](https://github.com/PrimeIntellect-ai/prime-rl/commit/c7ba105d58b1d825c3f411bcaf6bd6c85db57ddd))
to both arms.
The out-of-place rewrite was checked only in per-kernel benchmarks,
where it is net ~90 µs faster per
layer forward than in-place, and has not been re-run end to end.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 17:26:14 -04:00
Konstantin DunasandGitHub 1556db6ca7 chore: bump verifiers to latest main (#3663)
Advance the `deps/verifiers` submodule from `9e7ec2746` to `69cc0f948`,
the latest verifiers `main`, on top of prime-rl `origin/main`.

This picks up interrupted completion stream retries and the follow-up
refactor to tenacity. Dependency metadata is unchanged, so no lockfile
update is needed.

Validation: `uv lock --check --offline` passed. All four upstream
stream-retry regression cases passed with `uv run --no-sync pytest
--noconftest
deps/verifiers/tests/v1/test_e2e.py::test_chat_harness_preserves_streamed_reasoning
-q`. Shared integration fixtures were disabled because the local
environment lacks `prime_runs`. `git diff --check` passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Submodule pointer-only change with no prime-rl code or lockfile edits;
upstream behavior is limited to streaming/retry handling in verifiers
and was exercised by targeted tests.
> 
> **Overview**
> Updates the **`deps/verifiers`** git submodule from `9e7ec2746` to
**`69cc0f948`** (current verifiers `main`). There are **no changes to
prime-rl source or lockfiles**—only the pinned submodule commit moves.
> 
> The new verifiers revision adds **retries for interrupted completion
streams** and a follow-up refactor to use **tenacity** for that retry
logic. prime-rl still consumes verifiers the same way (CI initializes
the submodule; v1 config types extend `verifiers.v1`).
> 
> Validation noted in the PR: `uv lock --check --offline`, targeted
stream-retry e2e tests under `deps/verifiers/tests/v1/test_e2e.py`, and
`git diff --check`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c23df2e4bfaa88decca20bdb1a26d4fe5f9bd23c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-24 11:10:10 -07:00
Mika SenghaasandGitHub f984dee559 fix: pre-download data before trainer ranks (#3659)
## Summary

- pre-download Hub data in the SFT launcher, beside model predownload,
before trainer ranks start
- call data predownload only for SFT data, and skip generated fake data
in the launcher
- store the snapshot in the configured Hub cache and pass its local path
to the trainer
- log skipped local paths and download duration like model predownload
- add optional `data.revision` and honor it when loading data directly

## Verification

- before: research-prod debug job 1400 failed before its first step when
concurrent ranks received HTTP 429 from the Debug data tree API
- after: called the predownload utility with the pinned Debug data and
confirmed it resolved to the local snapshot
- ran Ruff lint and formatting checks on the changed Python files

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes SFT startup and mutates in-memory data config before
subprocesses start; low security impact but affects all real-data SFT
runs’ I/O behavior.
> 
> **Overview**
> **Pre-downloads Hugging Face SFT datasets in the launcher** (alongside
model pre-download) so a single process hits the Hub before
`torchrun`/SLURM ranks start, avoiding concurrent dataset API traffic
that caused HTTP 429 failures.
> 
> Adds `pre_download_data`, which no-ops for non-SFT/`fake` configs and
existing local paths, uses `snapshot_download` with optional
`HF_HUB_CACHE`, **rewrites `data.name` to the cached snapshot path**,
and logs timing like model pre-download. The launcher calls it for train
and validation data when not in `dry_run`.
> 
> Adds optional **`data.revision`** on `SFTDataConfig` and threads it
through `load_dataset` when data is loaded directly (revision is ignored
for local paths).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6aa6aa6e37a3e777bfd61ec835f02ee7f1a360cd. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-24 11:01:21 -07:00
Mika SenghaasandGitHub c1c1fe7e14 chore: update verifiers for buffered streams (#3656)
## Summary

- Advance the `deps/verifiers` submodule from `9cf0df2` to `9e7ec27`,
the last VF main commit before Matej's retry fix.
- Include buffered SSE keepalives and retry replay from
[verifiers#2650](https://github.com/PrimeIntellect-ai/verifiers/pull/2650),
the empty-tools fix from
[verifiers#2669](https://github.com/PrimeIntellect-ai/verifiers/pull/2669),
and Prime job-output recovery from
[verifiers#2670](https://github.com/PrimeIntellect-ai/verifiers/pull/2670).
- Include the nano-rlm default revision bump from
[verifiers#2672](https://github.com/PrimeIntellect-ai/verifiers/pull/2672).
- Keep Matej's stream-consumption retry PR
[verifiers#2654](https://github.com/PrimeIntellect-ai/verifiers/pull/2654)
out of this pin. VF main merged it during this load test.

## Breaking

- VF streams now send keepalives while they buffer a model turn. They
send the completed response after the turn commits. Consumers that need
live provider token deltas must connect to the provider directly.

## Verification

- `uv sync --all-extras --all-packages --locked` completed. Both eval
configs passed `uv run --no-sync eval @ ... --dry-run`.
- Served `poolside/Laguna-S-2.1-FP8` on eight H200 nodes. Each node ran
one ETP=8 replica behind the default vLLM router with a four-hour
request timeout.
- Ran AIME26/null and Terminal-Bench 2 `fix-git`/Bash together on VF
`1e0b660`, the direct parent of the pinned `9e7ec27`. The intervening VF
diff changes only the optional nano-rlm harness default. Neither tested
harness uses nano-rlm.
- Each eval had 2,000 rollouts, fixed 2,000 inflight concurrency, and a
900-second rollout cap. Bash used 20 maximum turns. No eval-side rate
limiter was set.

The table excludes sandbox-creation HTTP 429 rollouts. It counts the
configured 900-second cap as **no error**.

| Eval | No error | Other infrastructure errors | Stream errors |
| --- | ---: | ---: | ---: |
| AIME26/null | 1,770/1,772 | 2 | 0 |
| TB2 fix-git/Bash | 1,857/1,859 | 2 | 0 |
| Combined | 3,627/3,631 | 4 | 0 |

- AIME had 779 cap exits. Its other failures were one sandbox missing
`dockerImage` and one terminated sandbox. Its 996 model calls had no
recorded call error. Of its fully completed calls, 339 exceeded 600
seconds; the longest lasted 894 seconds.
- Fix-git had 37 cap exits. Its other failures were one sandbox missing
`dockerImage` and one sandbox setup `apt-get` I/O error. Its 27,874
model calls had no recorded call error. Six fully completed calls
exceeded 600 seconds.
- Found zero terminal stream-disconnect signatures in trace errors,
model-call errors, or eval and environment logs. Both eval commands
exited successfully.
2026-09-24 10:37:00 -07:00
samsjaandGitHub bdaafc35ab chore(deps): bump dion to 6f9242d (uneven FSDP shards) (#3658)
## Summary

Bumps the dion pin from `99e5f7e` to `6f9242d`, picking up samsja/dion#4
(merged into `sami/fix-ep`):

- **Uneven and empty FSDP shards in Muon**: local shards are padded to a
uniform peer-transfer size for the all-to-all and trimmed back
before/after orthogonalization, so the update is exactly the unpadded
Muon update. Previously the optimizer asserted the sharded dim is
divisible by the optimizer world size — full Muon failed on the first
step for matrices with e.g. 4 or 24 rows on a 64-rank FSDP group.
- **Partitioned-matrix fix**: per-row learning rates are now sliced with
chunk offsets matching DTensor's `Shard` (`torch.chunk`) layout;
`torch.tensor_split` disagrees with it at world size ≥ 3 and could
silently misassign or crash when a partition boundary fell inside an
uneven shard.
- Padding now uses `torch.nn.functional.pad` (no-op fast path when
shards are already uniform).

## Compatibility

- `Muon`'s constructor signature is unchanged; the call site in
`src/prime_rl/trainer/optim/__init__.py` is unaffected.
- The pinned tree is byte-identical to the dion branch validated with:
exact (`rtol=0, atol=0`) parity vs unsharded Muon across
uneven/empty/3D/partitioned shapes at world sizes 2 (NCCL) and 3 (gloo),
plus 170 pure-CPU padding round-trip cases.

## Changes

```
pyproject.toml | 2 +-
uv.lock        | 4 ++--
```

Note: `uv lock` in a fresh clone needs the `deps/` submodules
initialized **with tags** (`git submodule update --init`, then ensure
tags are fetched) — `verifiers` and `renderers` derive versions from git
tags via hatch-vcs, and a tagless shallow checkout resolves them as
`0.0.1.dev1`, which fails workspace resolution.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Pins a new git revision of the distributed Muon optimizer used on
Linux GPU training; behavior changes in FSDP edge cases but no in-repo
code edits.
> 
> **Overview**
> Updates the **dion** git pin from `99e5f7e` to `6f9242d` in
`pyproject.toml` and `uv.lock` only—no prime-rl source changes. Training
still wires **Muon** through `src/prime_rl/trainer/optim/__init__.py`
under the `gpu` extra.
> 
> The new revision pulls in upstream fixes for **FSDP-sharded Muon**:
uneven or empty local shards are padded for all-to-all peer transfer and
trimmed so updates match unsharded Muon (avoiding first-step failures
when matrix rows aren’t divisible by optimizer world size), and per-row
learning rates are sliced with **DTensor**-consistent chunk offsets
instead of `tensor_split` (which could misassign rates at world size ≥
3).
> 
> **Risk:** dependency-only bump, but it changes distributed optimizer
numerics/behavior on large FSDP runs where the old pin could assert or
silently wrong-rate parameters.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9ca26a11e000fb7ca8a374537af6a3858c1b1aed. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 22:40:17 -07:00
samsjaandGitHub 48aa99fbb5 feat(trainer): expose the torch.compile mode (reduce-overhead) in the compile config (#3657)
## Summary
`CompileConfig` only exposed `fullgraph`, so there was no way to opt
into `torch.compile`'s lower-overhead modes. This adds a `mode` field
that mirrors the `torch.compile` `mode` kwarg, and forwards it to each
layer's `.compile()` call in `apply_compile`.

- Accepts `reduce-overhead` (records CUDA graphs to cut kernel launch
overhead), `max-autotune`, `max-autotune-no-cudagraphs` (tune Triton
kernels, longer compile) and `lite`.
- `mode = None` (default) keeps the current behavior — layers compile
with PyTorch's default mode.
- CUDA-graph modes re-record on new input shapes, so runs with highly
variable shapes pay recompile churn.

## Usage

```toml
[trainer.model.compile]
mode = "reduce-overhead"
```

or on the CLI: `--trainer.model.compile.mode reduce-overhead`.
2026-09-23 22:39:07 -07:00
samsjaandGitHub 94dff2ca54 fix(trainer): b300 fallback to FA4 (#3655)
## Problem

Two GPU-capability gates in `src/prime_rl/trainer/model.py` matched
`(10, 0)` exactly, but B300/GB300 are **SM103** (compute capability
10.3, per https://developer.nvidia.com/cuda-gpus):

1. **`resolve_auto_attn`**: `attn: auto` on B300/GB300 resolved to
`flash_attention_2` instead of FA4, silently losing the Blackwell-native
attention kernels on every default-config B300 run.
2. **`apply_quantization` (MXFP8 gate)**: MXFP8 quantization raised
`requires SM100 (Blackwell)` on B300 even though Blackwell Ultra
supports it.

## Fix

Use `major >= 10` in both places, matching the existing Blackwell checks
in `fp8_utils.py` and `fp8_grouped_gemm.py`.

## Behavior after this PR

| GPU | CC | `attn: auto` | MXFP8 |
|---|---|---|---|
| H100/H200 | SM90 | FA3 (unchanged) | n/a |
| B200/GB200 | SM100 | FA4 (unchanged) | allowed (unchanged) |
| B300/GB300 | SM103 | **FA4 (was FA2)** | **allowed (was rejected)** |
| Other SM100+ parts | SM110+ | FA4 | allowed |

Note the previous code kept workstation Blackwell (SM120/121, e.g. RTX
PRO 6000) on FA2; with the simple `major >= 10` check those now
auto-resolve to FA4 too. If FA4 kernels aren't available on such a host,
set `attn` explicitly.

## Notes

- Verified SM103 device capability via NVIDIA's CUDA GPUs page; FA4 runs
on B300 with the pinned `flash-attn-4` rev (`0251105`), which is past
the SM103 JIT-compile-churn fixes reported in
Dao-AILab/flash-attention#2635/#2699.
- B300 runs can confirm the old behavior by grepping trainer logs for
`Auto-resolved attn='auto' to 'flash_attention_2' (SM103)`.
- No behavior change on Hopper or B200 hosts.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes GPU-specific attention backend auto-selection and MXFP8
eligibility at trainer setup; mis-gating could pick unsupported kernels
on some SM10x parts.
> 
> **Overview**
> **Fixes B300/GB300 (SM103) being treated as non-Blackwell** because
capability gates in `model.py` matched compute capability `(10, 0)`
exactly.
> 
> For **`attn: auto`**, `resolve_auto_attn` now picks **flash attention
4** when the device **major** compute capability is **≥ 10**, instead of
only SM100. SM103 runs get FA4 rather than silently falling back to FA2.
> 
> For **MXFP8** in `apply_quantization`, the same **`capability[0] <
10`** rule replaces the exact SM100 tuple check, and the error text now
refers to **Blackwell (SM100+)**.
> 
> Docstrings for auto attention resolution are updated to describe
**SM100+** (including SM103) rather than datacenter-only SM100 vs
workstation SM120 wording tied to the old `(10, 0)` branch.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fbd7387af8a54df4cb3829b29dcfbbc24c1a7d27. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 21:00:12 -07:00
Mika SenghaasandGitHub 4723b0ee5a fix: increase default router timeout to four hours (#3654) 2026-09-24 04:48:24 +02:00
Mika SenghaasandGitHub b695a0aeda fix(inference): align DeepSeek V4 request tool placement (#3646)
## Summary

- attach request-level tools to the first existing DeepSeek V4 system
message
- preserve vLLM's existing synthetic-system behavior when a request has
no system message
- cover both paths and ensure the caller's messages are not mutated

vLLM 0.29's Python DeepSeek V4 tokenizer prepends a synthetic tool-only
system message even when the request already has a system prompt. That
differs from DeepSeek's reference encoder, vLLM's Rust renderer, and
prime-rl's training renderer, producing a different token prefix at
inference time.

This is a temporary compatibility patch for
[vllm-project/vllm#51856](https://github.com/vllm-project/vllm/pull/51856)
(upstream commit `2909ad8f`). That fix is expected to ship in vLLM 0.31,
at which point this monkey patch can be removed.

## Tests

- `pytest tests/unit/inference/test_deepseek_v4_tokenizer_patch.py -q` —
2 passed
- `ruff check src/prime_rl/inference/patches.py
tests/unit/inference/test_deepseek_v4_tokenizer_patch.py`

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Inference-only tokenizer shim with idempotent guards; behavior is
covered by reference-encoding unit tests and should be removable after a
vLLM upgrade.
> 
> **Overview**
> Adds a temporary vLLM monkey patch so **DeepSeek V4 inference prompts
match the reference encoder and training renderer** when requests
include tools plus an existing system message.
> 
> On vLLM 0.29, the Python tokenizer **prepends a synthetic system block
for request-level tools**, putting `## Tools` before the caller’s system
text. The patch wraps `get_deepseek_v4_tokenizer` and
**`apply_chat_template`**: if the conversation already has a system
role, it shallow-copies the conversation, **attaches `tools` to the
first system message**, clears top-level `tools` so vLLM does not insert
the extra system message, and leaves **no-system** requests on stock
behavior. It is registered in **`apply_shared_vllm_patches`** and is
meant to be removed once the vLLM pin includes upstream **#51856**
(~0.31).
> 
> Unit tests assert rendered prompts match **`encode_messages`**, that
only one `## Tools` section appears, and that **input `messages` are not
mutated**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1acca7c9d1c503d0d497f05638d50e687ec714c8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 15:14:15 -07:00
753cfb5a42 fix: mark dashboard episodes failed by ok, not by carried errors (#3649)
## Summary
- The dashboard marks an episode as failed only when `ok` is false.
Retry history no longer turns a successful episode red: the episode
table row, the rollout list item, the error-rate tile on the eval
overview, and the server's `errors_only` filter all read `ok` alone.
- Episode errors and trace errors render in different places, each
tagged with its scope. A failed episode's own errors sit above the agent
and branch selectors, since they belong to the whole episode. A failed
trace's errors sit at the top of that trace's transcript, only on its
tab, and the tab is red. A failure recorded on both the episode and its
trace shows once, as the trace's.
- Errors an ok episode or ok trace carries render as a collapsed
`recovered from N episode|trace errors in earlier attempts` list in the
same two places, each entry with its traceback. The table row and
rollout list item get a dotted left edge with the recovery count in
their tooltip.

## Why
Verifiers retries a whole episode when a retryable error such as
`SandboxError` ends an attempt, and on success it prepends the earlier
attempts' errors to the final record: `final.errors[:0] = history`, with
the comment "success is the `ok` stamp, never errors-emptiness". The
agent-level retry does the same on the trace. An episode that hit the
sandbox creation limiter once and then completed cleanly therefore lands
with `ok = true`, a full trace, and the limiter error in `errors`. The
dashboard treated `num_errors > 0` as failure, so such episodes showed a
red row, an error banner over a clean transcript, and inflated the error
rate, which is what a user saw after a run with `retries.include =
["SandboxError", ...]`. Episode errors also rendered inside the open
trace, so a multi-agent episode showed a red banner over a green agent's
transcript.

## Verification
A synthetic eval run was built from a real 4-episode gsm8k stream and
served by an isolated dashboard on this branch, driven headlessly with
Playwright:

| Line | Shape | Before | After |
|---|---|---|---|
| 1 | episode failed; trace `solver` failed with `SandboxError`, trace
`judge` ok | red row, `error` badge, both banners inside the solver
transcript, episode banner inside the judge transcript | red row; the
`episode error` banner above the tabs on both; the `trace error` banner
only in the solver transcript; `solver` tab red |
| 2 | episode ok after a retry; episode and trace carry `SandboxError`
as history | red row, `error` badge, red banner over the clean
transcript | plain `done` row with a dotted edge and a "recovered from 1
error" tooltip, no banner, collapsed "recovered from 1 trace error in
earlier attempts" list holding the SandboxError and its traceback |
| 3, 4 | plain ok | `done` | `done` |
| error-rate tile | 2 failures counted | 50% | 25% |
| `errors_only=true` | | lines 1 and 2 | line 1 |

No console errors in either state.

## Screenshots
Episode table: line 1 failed (red edge), line 2 recovered (dotted edge),
lines 3 and 4 plain.

![episode
table](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/720f7ed72f1a3a5b09f7aaad34d94487b8688867/dashboard-retry-errors/table.png)

Line 2, recovered after a retry: no banner, the SandboxError in the
collapsed recovered list (expanded here), `ok = true`.

![recovered
episode](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/720f7ed72f1a3a5b09f7aaad34d94487b8688867/dashboard-retry-errors/recovered.png)

Line 1, `solver` tab: the episode error above the selectors, the failed
trace's error at the top of its transcript, the tab red.

![failed episode, solver
tab](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/720f7ed72f1a3a5b09f7aaad34d94487b8688867/dashboard-retry-errors/failed_solver.png)

Line 1, `judge` tab: the episode error stays above the selectors; the
judge's transcript carries no banner because that trace completed.

![failed episode, judge
tab](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/720f7ed72f1a3a5b09f7aaad34d94487b8688867/dashboard-retry-errors/failed_judge.png)

Screenshots live on the `assets/dashboard-retry-errors` branch.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dashboard display and filtering only; no changes to training, eval
recording, or auth paths.
> 
> **Overview**
> Aligns the eval dashboard with Verifiers’ retry semantics: **success
is `ok`, not empty errors**. Episodes that recovered after retryable
failures no longer look failed or inflate error metrics.
> 
> **Failure detection** now keys off `ok` only—the episode table,
rollout list, swarm **error-rate** tile, and server **`errors_only`**
filter no longer treat `num_errors` on successful episodes as failures.
Recovered episodes get a **dotted “retried”** row style and tooltips
instead of red error styling.
> 
> **Error UI** splits episode vs trace scope: episode-level failures
render in a new **`#tm-episode-errors`** strip above agent/branch tabs;
trace failures stay at the top of that trace’s transcript, with failed
agent tabs highlighted. **`scopedErrors`** dedupes episode/trace
duplicates (trace wins) and separates **failed** errors from
**recovered** history on ok records, shown as collapsible “recovered
from N … errors” sections. **`resetTranscript`** clears the episode
error strip whenever the transcript is replaced.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c4f6e242745c085c4bac60388dfb8c775e7b65f4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 14:29:47 -07:00
Biswa PandaandGitHub 33e02a7a18 fix(trainer): preserve Nemotron Mamba parameter dtype (#3557)
## Summary

- Initialize Nemotron Mamba `A_log` and `D` parameters with the active
default dtype so FSDP units do not mix float32 and bfloat16 storage.
- Keep the existing float32 state-space computation by casting at use
time.
- Add a focused bfloat16 parameter-dtype regression test.

## Validation

- `ruff check src/prime_rl/trainer/models/nemotron_h/mamba.py
tests/unit/train/models/test_nemotron_h.py`
- Focused in-cluster GPU probe: `A_log=torch.bfloat16`,
`D=torch.bfloat16`
- One-step Nemotron 3.5 Super VLM + MATH + Dynamo run: optimizer
completed and policy v1 was applied over NCCL.
- Three-step Kubernetes run: all optimizer steps completed; policies v0
through v3 applied to Dynamo; Job succeeded.
- Trainer mismatch KL by step: `0.0274`, `0.0344`, `0.0309`.

W&B: https://wandb.ai/test232/nemotron35-vlm-rl/runs/jq06zl0l
2026-09-23 13:35:34 -07:00
94f359e8d6 feat: scope verifiers limiters by run id and bump verifiers to main (#3641)
## Summary
- Bump the verifiers submodule to main (`9cf0df22b`), which includes
PrimeIntellect-ai/verifiers#2657: creation limiters wait on backlog
instead of raising past 300s, and their bucket is scoped by
`$VF_RUN_ID`. `uv.lock` is regenerated; verifiers dropped its `lean`
extra.
- The env-server entrypoint sets `VF_RUN_ID` from `PRL_RUN_ID`, minting
a uuid only when neither is set. Its pool workers inherit it.
- The multi-node SFT SLURM script exports `PRL_RUN_ID` and
`PRL_RUN_NAME` unconditionally, as the RL script does. Only the W&B
shared-mode variables stay behind the wandb condition, now named
`wandb_shared` in the template.

## Why
With the bump, a run whose sandbox creation outpaces `creates_per_min`
throttles instead of failing every rollout past the 300s backlog.
Scoping the bucket by run id keeps one run's backlog from delaying
another.

The env server is the one prime-rl process that creates sandboxes, and
every launcher hands it `PRL_RUN_ID`: the `rl`, `sft`, and `eval`
entrypoints export it before spawning, and the SLURM scripts export it
at the top of the sbatch script, which `srun` propagates to the `uv run
env-server` tasks. Deriving `VF_RUN_ID` there covers every launch path
with one line. The SFT script previously exported the run id only for a
shared W&B run, so its online-eval env servers would otherwise each have
minted their own scope.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes run-id propagation for SLURM-launched env servers and sandbox
creation throttling behavior; mis-set env vars could affect multi-run
cluster behavior but not auth or data integrity.
> 
> **Overview**
> Aligns prime-rl with verifiers’ run-scoped sandbox **creation
limiters** (keyed on `$VF_RUN_ID`) so throttling and backlog are per run
instead of shared across jobs.
> 
> The **env-server** entrypoint now sets `VF_RUN_ID` from `PRL_RUN_ID`,
or mints a UUID when launched standalone, so pool workers inherit the
same scope on every launch path.
> 
> **Multi-node SFT** previously exported `PRL_RUN_ID` only when shared
Weights & Biases logging was enabled, which left online-eval env servers
without a consistent run id. The SLURM template now always exports
`PRL_RUN_ID` and `PRL_RUN_NAME` (matching RL), while W&B shared-mode env
vars are gated on a new `wandb_shared` flag passed from `sft.py`.
> 
> **Lockfile** metadata drops the removed `lean` extra from the bumped
verifiers dependency.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
364f0b58699ad556746116a1bf6208e37b5afc6b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 13:34:19 -07:00
Matej SirovatkaandGitHub cf400e7db9 perf: reduce DSV4 indexer stalls and overlap CP gathers (#3643)
Packed sequence lengths were causing repeated FP8-indexer autotuning
during training. Other DP groups then arrived late at the layer-4 FSDP
prefetch, making a normal ~1–3 ms parameter gather appear to take 1.78
s. Together with narrower checkpoint state, avoiding a query-layout
copy, and overlapping CP communication, the matched BF16 benchmark
improves from **22.741 s / 40.23% MFU** after #3638 to **18.999 s /
47.79% MFU**.

- Bucket the indexer's autotune key by compressed-key length, also
keying on head count and dimension. Exact key lengths still control
addressing and masks. An all-rank trace showed the last rank arriving
1.718 s late and completing the gather in 1.34 ms; it had been
benchmarking the first CSA indexer.
- Register the FP8 indexer as an opaque operation and make its final
int32 selection a mandatory checkpoint save. This preserves the top-k
replay requirement while retaining compact IDs and skipping indexer
scoring on replay.
- Apply query RoPE directly in the sparse kernel's `(batch, tokens,
heads, dim)` layout, removing the transpose/contiguous round trip in
attention and the indexer.
- Launch the main KV CP gather with PyTorch's asynchronous functional
collective before query/compressor computation, and wait just before
consuming KV. Its registered backward performs the corresponding sum
reduce-scatter. Compilation stays enabled; communication uses NCCL's
existing stream.

### SAC configuration

Exact configuration for the measured run:

```toml
[model.ac]
mode = "selective"
freq = 1
targets = [
  "prime_rl::dsv4_sparse_attn",
  "prime_rl_collectives::all_to_all_single_equal",
  "aten::sort.stable",
]
```

`prime_rl::fp8_indexer` is saved automatically by the mandatory policy
in both full and selective checkpointing. The qualified stable-sort
overload matters: `aten::sort` does not match `aten::sort.stable`.

### Measurements

| Variant | Mean step time | Logged tokens/s | Logged MFU |
| --- | ---: | ---: | ---: |
| PR #3638 only (job 653) | 22.741 s | 86,890 | 40.23% |
| Indexer tuning buckets, full AC (665) | 20.718 s | 95,043 | 44.01% |
| Buckets + sparse-attention/EP-count SAC (675) | 20.042 s | 97,636 |
45.21% |
| All changes + SAC above (691) | **18.999 s** | **103,210** |
**47.79%** |

This is a **1.197× step-time speedup** over #3638 alone and **1.055×**
over the prior SAC run. Peak rank-0 reserved memory is **232.5 GiB /
267.7 GiB**. All five losses are finite. These are short benchmark
results, not a long-run convergence measurement. Measurements use the
pinned job-492 environment; this branch is rebased onto current main,
whose touched modeling files were identical to that baseline.

### Validation

- CPU checkpoint-policy tests: 4 passed on the PR branch, including
mandatory indexer retention under custom SAC targets. Ruff lint and
formatting checks passed for all changed files.
- Existing FP8-indexer GPU correctness cases: 2 passed. Changing key
lengths 1060 → 1064 → 1073 reused one autotune entry (2.015 s initial
tuning, then 0.919 ms and 0.634 ms).
- Existing sparse/eager attention parity cases: 9 passed, covering CSA,
HCA, sliding attention, packed documents, and empty compression.
- Existing CP packing checks: 6 passed across CP2/CP4 and all three
attention types; rerun successfully after inlining the gather and wait
calls directly in attention forward.
- Two-rank async-collective probe: outputs and input/weight gradients
passed with full/selective checkpointing, eager execution and
`torch.compile(fullgraph=True)`.
- Compiled two-rank BF16 attention checks: all three attention types
passed under full/selective checkpointing against the blocking
implementation; maximum relative L2 difference across outputs and
gradients was 0.026%. The sliding cases ran in a separate process after
the combined test harness reached its compiled-variant limit.
- Query-layout microcheck: bitwise-equal outputs and input gradients in
BF16/FP32, including the production query shape.



<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes touch CP collectives, compile/custom-op boundaries, and SAC
correctness for non-replayable top-k; numerics are covered by existing
kernel and CP tests but production timing depends on NCCL stream overlap
behavior.
> 
> **Overview**
> This PR targets **DeepSeek V4 training step time** by cutting FP8
indexer autotune churn, overlapping context-parallel communication, and
tightening activation-checkpoint behavior around sparse indexing.
> 
> The **FP8 Lightning indexer** is registered as `prime_rl::fp8_indexer`
and added to the **mandatory** selective-activation-checkpoint save list
so replay keeps the final int32 top-k without re-running scoring. Triton
autotune now keys on **`next_power_of_2(S_k)`** plus head count and
dimension so packed batches with slightly different compressed-key
lengths reuse one tuned config.
> 
> In **attention**, queries stay in **`(batch, tokens, heads, dim)`**
through RoPE and into `dsv4_sparse_attn`, dropping the
transpose/contiguous path. Under CP, **KV all-gather** starts
asynchronously via `_c10d_functional.all_gather_into_tensor` before
query and compressor work, with **`wait_tensor`** immediately before KV
is consumed.
> 
> Tests assert mandatory checkpoint retention for the new op and extend
CP parity mocks for the async gather path.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6449f9212c3430c812b9623a1b5bd274e350b780. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 16:07:21 -04:00
samsjaandGitHub 8da21f16b8 feat(eval): make task dispatch rate configurable (#3602)
<!-- CURSOR_SUMMARY -->
> [!NOTE]
> **Low Risk**
> Optional config with default unchanged; reuses existing orchestrator
dispatch rate limiting with no auth or data-path changes.
> 
> **Overview**
> Eval runs can now cap how fast episodes are dispatched via a new
**`tasks_per_minute`** setting on **`ServedEvalConfig`** (shared by
standalone eval and SFT online eval). **`None`** keeps the previous
behavior with no rate limit; a positive value throttles dispatch through
the existing **`Dispatcher`** **`AsyncLimiter`**, intended to pace
sandbox provisioning during autoscaling.
> 
> The eval **`runner`** passes **`config.tasks_per_minute`** into the
dispatcher instead of hard-coding **`None`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
31f8041b908234dc4c45f128540af8e4daa6435b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 09:30:15 -07:00
ae37b35a34 fix(trainer): match vLLM's per-token FP8 activation quantization bit for bit (#3623)
RL compares trainer and inference logprobs token by token, so any
disagreement between the two FP8
quantizers is model-independent noise. The trainer's per-token
activation cast is now bit-identical to
vLLM's production CUDA op, `torch.ops._C.per_token_group_fp8_quant`.

- Three kernels in `fp8_utils.py` floor `amax` at `1e-10` and use
`tl.math.div_rn` for scale and quotient.
Triton's `/` lowers to multiply-by-reciprocal, one fp32 ULP off the
correctly rounded value.
- The weight kernel is untouched: vLLM's weight path is itself a
reciprocal-multiply and already matched.
- A new GPU test pins the equality against the CUDA op; the trainer
still imports vLLM nowhere.

Share of 128-wide groups whose scale is bitwise equal to vLLM's, and
share of elements whose fp8 byte
is, on four 4096x4096 bf16 activation tensors on an H200:

| tensor | scales: before | after | bytes: before | after |
|---|---|---|---|---|
| randn x0.02 | 42.8329% | 100.0000% | 98.1890% | 100.0000% |
| randn x1.0 | 41.0797% | 100.0000% | 99.8822% | 100.0000% |
| randn x30.0 | 43.6028% | 100.0000% | 99.8869% | 100.0000% |
| randn heavytail 16ch x50 | 42.7979% | 100.0000% | 99.8999% | 100.0000%
|

Every pre-fix mismatch was exactly one e4m3 step, so weights stay at
100% and dequantization error is
unchanged. Agreement with vLLM's Triton fallback drops to about 42% on
scales, which is forced since
vLLM's two backends are not bit-identical to each other and only the
CUDA op runs in production. Costs
3.1% of quant-kernel time at 4096x4096 and 8.7% at [8192, 7168].
Verified on sm90 with
`use_ue8m0=False`; sm100 takes a different vLLM kernel.

## Effect on training gradients

The old floor applied to the scale, not to `amax`, so any 128-wide group
with `amax < 0.0448` was
quantized against an inflated scale: its values were squeezed into a
corner of the e4m3 range
instead of spanning it, and everything below `1e-7` rounded to zero.
Forward activations sit above
that threshold; gradients do not, and both the input-gradient (dgrad)
and weight-gradient (wgrad)
paths cast `grad_output` through these kernels. The error is one-sided
toward zero, so it shrinks
gradients rather than adding noise.

Measured end to end: a 131k-context SWE RL run with an FP8 trainer on
pre-fix code logged
`optim/grad_norm` averaging 0.0079 over 100 steps, against 0.0465 and
0.0528 for otherwise
identical runs with a bf16 trainer. A rerun of that config on the fixed
kernels is at 0.0421 over
its first 17 steps, where the pre-fix run read 0.0094 and the bf16
reference 0.0468 over the same
window. Mismatch KL is blind to all of this, since it depends on the
forward alone: lr = 0 probes
read 0.0089 before the fix and 0.0091 after.

### Why the floor's location matters

Per 128-element group:

```
# before
amax  = max(|x|)
scale = max(amax / 448, 1e-4)      # floor on the SCALE
y     = x / scale

# after
amax  = max(max(|x|), 1e-10)       # floor on the AMAX
scale = div_rn(amax, 448)
y     = clamp(div_rn(x, scale), -448, 448)
```

A floor exists only to keep an all-zero group from dividing by zero. The
correct scale, `amax / 448`,
maps the group's largest element to exactly 448 and spans the full e4m3
range. Pinning the scale at
`1e-4` makes it too large whenever `amax < 0.0448`, and a scale that is
too large makes `y = x / scale`
too small, so the group occupies a corner of the range.

Take a gradient group with `amax = 1e-5`:

- correct scale is `1e-5 / 448 = 2.2e-8`, giving `y_max = 448`, the full
range
- old scale is `1e-4`, giving `y_max = 0.1`, a sliver of it
- e4m3's smallest subnormal is `2^-9 = 0.00195`, so any `|y|` below
about `0.001` rounds to zero
- that is every `|x|` below `1e-7`, which is 1% of this group's maximum
- at `amax = 1e-6` the same `1e-7` cutoff erases everything below 10% of
the maximum

Two properties make this worse than rounding noise. It is one-sided,
always toward zero, so it biases
the gradient short rather than jittering it. And it is non-uniform:
groups above `0.0448` are exact
while groups far below it are gutted, so the surviving gradient also
points in a different direction.
AdamW's per-parameter normalization absorbs much of the magnitude loss,
which is why a run carrying
this bug trains through it while looking healthy.

## Launch-config retune

This PR also reconfigures the kernel launch specs for perf (for H200).

Measuring the cost of correct rounding exposed a separate problem: these
kernels were already launched
at block sizes that spill registers. The per-channel cast used a `[128,
128]` fp32 tile, and
`div.rn.f32` needs more live temporaries than `div.full.f32`, which is
why correct rounding looked
expensive there. Retuning `BLOCK_M`, `BLOCK_N` and `num_warps` in five
host wrappers, with no kernel
body change, recovers more than correct rounding costs.

Measured on an H200 at this model's dimensions (hidden 4096, MoE
intermediate 2048, 8 local experts
with ragged routing), 102 configs against a noise-control arm:

| kernel | wins | regressions | noise | best delta |
|---|---|---|---|---|
| `grouped_per_channel` k-major | 24 | 0 | 2 | -54.1% |
| `grouped_per_channel` row-major | 21 | 0 | 5 | -35.3% |
| `per_token` transposed | 6 | 0 | 6 | -44.8% |
| `grouped_per_token` | 7 | 0 | 19 | -12.0% |
| `per_token` | 3 | 0 | 9 | -12.4% |

Ragged expert groups gain more than equal ones: at K=4096 with 4096
tokens per rank, the k-major
per-channel cast is -28.5% on an equal split and -54.1% under realistic
routing. A launch config cannot
change the arithmetic, so bit identity against the CUDA op is
unaffected.

## Verification

```
uv run --no-sync python -m pytest tests/unit/train/models/test_fp8_utils.py -q
```

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 11:14:43 -04:00
Matej SirovatkaandGitHub 77788ba020 fix: retain two reduce-scatter input buffers for FP32 MoE routers (#3638)
FP32 MoE routing uses a separate FSDP unit. Its post-backward hook can
request a reduce-scatter input buffer while the expert reduction is
still in flight; FSDP's default limit of one inserts a compute-stream
wait before attention backward can run.

Set `set_reduce_scatter_max_input_buffers(2)` on that router unit
immediately after sharding. FSDP resolves the shared buffer limit to the
maximum across its units, allowing the router to pack gradients while
the expert reduction completes. This adds two lines on top of main, with
no new configuration or numerical dtype changes. The tradeoff is
additional memory for in-flight reduction inputs.

### Measured timings

Same saved packed tokens and checkpoint, GLM-5.3 EP8/CP8 on 32 B300
GPUs, FP32 routing, full activation checkpointing, and activation
offloading enabled in both runs. Two warmup passes followed by one
profiled forward/backward; no optimizer update.

| Metric | One buffer | Two buffers |
| --- | ---: | ---: |
| Warm forward + backward, median across 32 ranks | 14.699 s | 12.649 s
|
| Profiled forward + backward, median across 32 ranks | 14.808 s |
12.717 s |
| Expert reduce-scatter overlap with main-stream compute, rank 0 | 11.1%
| 93.7% |
| Maximum reserved GPU memory across ranks/passes | 204.49 GiB | 205.29
GiB |

Warm forward/backward is **13.9% shorter**, equivalent to **16.2% higher
throughput**, at **0.80 GiB** more peak reserved memory in this run.

### Timeline of the stall

Actual CUDA kernel intervals for layer 77, rank 0. Each panel is aligned
independently to that layer's expert reduce-scatter launch. Blue is
other main-stream compute, green is attention backward, and orange is
expert gradient reduce-scatter.

![Measured one-buffer versus two-buffer reduce-scatter
overlap](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/1bebf826b530cb7c52d18d8cf92d562174a7efbe/reduce-scatter-overlap.png)

With one buffer, the router's post-backward hook queues a compute-stream
wait while the **4.5 GiB expert reduction** is in flight. This creates a
**40.7 ms main-stream compute gap**. The router's own reduction is only
**6 MiB / 0.66 ms**. Attention backward starts **48.87 ms** after the
expert reduction launch; with two buffers it starts at **8.15 ms**
instead. The layer's expert-reduction overlap rises from **7.3% to
96.3%**. These layer-specific percentages differ from the aggregate
values in the table.

These are single-run comparisons, not repeated statistical benchmarks.
The measured experiment set the cap at the root; this PR applies the
same effective shared cap through the router unit. Ruff and `git diff
--check` pass; this exact main-based patch has not had a new distributed
run.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Two-line FSDP scheduling tweak in MoE setup only; no numerical or API
changes, with modest extra peak memory for reduction buffers.
> 
> **Overview**
> When **FP32 MoE routers** are sharded as their own FSDP unit
(alongside expert-parallel expert shards), backward can stall: the
router’s post-backward reduce-scatter needs an input buffer while the
much larger expert gradient reduction is still using FSDP’s default
single buffer, forcing a **compute-stream wait** before attention
backward can proceed.
> 
> Right after `fully_shard` on `block_mlp.router`, the PR calls
**`set_reduce_scatter_max_input_buffers(2)`** so the router can queue
its small reduction without blocking on the in-flight expert
reduce-scatter. FSDP’s shared limit becomes the max across units—same
effective behavior as raising the cap at the root, but scoped to the
router shard path. **Tradeoff:** slightly more memory for in-flight
reduction inputs; no new config or dtype changes.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
51a9e3daef8a53a254d7e7ff35d1ee3c8afce18c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 17:02:46 +02:00
Scott CabrinhaandGitHub ab85b3b369 fix(docker): install the Prime CLI into the image venv for hosted-run env bootstrap (#3635)
## Problem

Since #3585 removed the `prime` CLI as a prime-rl dependency ("Stop
installing the `prime` CLI with prime-rl. Run `uv tool install prime`
when the CLI is needed"), the published GHCR images ship no `prime`
executable. That breaks Hosted Training runs on these images at
bootstrap:

The platform's env-server and orchestrator pods prepend an
**authenticated** Hub env install to their pod command,

```
uv run --no-sync prime env install '<owner/name>' && ... && uv run --no-sync env-server @ config
```

because verifiers' own `ensure_installed` resolver fetches the Hub
**unauthenticated** and 404s on private environments — the pre-install
into the pod's venv is what makes v1 Hub tasksets resolvable at boot
(envs baked into the image never hit this path).

With the executable absent from `/app/.venv/bin`, every pod dies at
spawn and the run wedges at `CREATING`. Observed on
`ghcr.io/primeintellect-ai/prime-rl:v0.9.1.dev100` dispatching a run
with a Hub taskset:

```
error: Failed to spawn: `prime`
```

(the orchestrator's entire log is two lines: the no-checkpoints warning,
then that spawn failure).

## Fix

Install the CLI into the image venv at build time — **not** as a project
dependency, so #3585's "CLI as a separate tool" boundary stands for
library code; the image just ships the executable and its runtime deps
so the platform bootstrap can run.

- One `RUN` after the main `uv sync`, using the same uv cache mount as
the rest of the file.
- `prime>=0.7` — pure-Python CLI, few MB; most deps
(httpx/pydantic/etc.) are already in the venv.
- The runtime stage copies `/app` wholesale, and `PATH` already puts
`/app/.venv/bin` first, so `uv run --no-sync prime env install ...` and
direct `prime` calls both resolve.

## Alternatives considered

- Reverting #3585's dependency removal: rejected — keeps the boundary;
the image need, not the library, is what broke.
- Platform-side init container with a dedicated prime-cli image (cleaner
long-term: keeps the CLI out of the framework image entirely) — worth
tracking on the platform side; this PR is the minimal unblock for hosted
Hub-env runs today.

## Verification

- `VIRTUAL_ENV=<venv> uv pip install 'prime>=0.7'` smoke-tested locally
(CLI 0.7.0 boots).
- Placement reviewed against the builder stage: runs after the locked
sync chain, before the optional NIXL block; nothing downstream
overwrites the venv.
2026-09-22 19:06:08 -06:00
Mika SenghaasandGitHub de5cdb8bae fix: read serialized dashboard token counts (#3632)
## Summary

- pin Verifiers `main` at the merge of [Verifiers
#2652](https://github.com/PrimeIntellect-ai/verifiers/pull/2652),
including the computed fields from [Verifiers
#2651](https://github.com/PrimeIntellect-ai/verifiers/pull/2651)
- read serialized token counts directly from completed episode and live
trace records
- remove dashboard-specific token reconstruction and prompt-token
summation

The previous implementation summed every full prompt in a multi-turn
trace.
This counted the shared conversation once per request and inflated long
rollouts.

## Verification

Before this change, a two-turn trace with prompt usages of 100 and 150
tokens
reported 250 input tokens. After this change, the serialized record and
both
dashboard paths report 130 input tokens and 50 output tokens.

- tested the dashboard flow end to end
- `ruff check` and `py_compile` passed for both changed modules
2026-09-22 15:50:19 -07:00
samsjaandGitHub b636a8b7ec chore: bump prime-envs to latest main (#3630)
## Summary
- Bump the `deps/prime-envs` submodule from `1f1e050ab` to `1213b7336`
(latest `main`).
  - Pulls in:
-
[prime-envs#791](https://github.com/PrimeIntellect-ai/prime-envs/pull/791):
strip v0 remnants.
-
[prime-envs#795](https://github.com/PrimeIntellect-ai/prime-envs/pull/795):
restore solver network access for training environments.
-
[prime-envs#797](https://github.com/PrimeIntellect-ai/prime-envs/pull/797):
500-trace SWE cheating recall benchmark (new `trace-cheating-recall-500`
judge env).
-
[prime-envs#796](https://github.com/PrimeIntellect-ai/prime-envs/pull/796):
run MCP Atlas and Enterprise Ops Gym services in VMs.
-
[prime-envs#798](https://github.com/PrimeIntellect-ai/prime-envs/pull/798):
fair-use solver prompts for SWE and terminal training tasksets.
-
[prime-envs#805](https://github.com/PrimeIntellect-ai/prime-envs/pull/805):
keep env CI evals off the platform.
-
[prime-envs#770](https://github.com/PrimeIntellect-ai/prime-envs/pull/770):
OfficeQA Pro V2 (new `officeqa-pro-v2` env).
-
[prime-envs#808](https://github.com/PrimeIntellect-ai/prime-envs/pull/808):
complete TMax platform hosting and source references.
-
[prime-envs#814](https://github.com/PrimeIntellect-ai/prime-envs/pull/814):
ask before changing repository skills.
-
[prime-envs#815](https://github.com/PrimeIntellect-ai/prime-envs/pull/815):
support renamed Verifiers eval CLI in CI.
-
[prime-envs#822](https://github.com/PrimeIntellect-ai/prime-envs/pull/822):
remove obsolete Prime VM configuration.
- Relock `uv.lock`: new workspace members `officeqa-pro-v2` and
`trace-cheating-recall-500` (auto-discovered via
`deps/prime-envs/environments/*/*`); env package version bumps.

## Validation

- `uv sync --all-extras --all-packages --locked` passes.
- `uv run pytest tests/unit -m "not gpu"`: 616 passed, 1 skipped.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Training and evaluation behavior can shift (solver prompts, network
access, VM-hosted tool services, new benchmarks) because many SWE,
terminal, and tool-use env packages change together.
> 
> **Overview**
> Updates the **`deps/prime-envs`** submodule to the latest **`main`**
and refreshes **`uv.lock`** so the workspace picks up new and bumped
editable environment packages.
> 
> The lockfile adds two auto-discovered members—**`officeqa-pro-v2`**
(search) and **`trace-cheating-recall-500`** (judge)—and bumps patch
versions across many existing env packages (SWE stacks like
**`openswe`**, **`multiswe`**, **`swesmith-env`**; terminal **`tmax`** /
**`terminal-lego`**; tool-use **`mcp-atlas`** /
**`enterprise-ops-gym`**; plus assorted math, lean, long-context, and
reasoning envs).
> 
> Upstream **`prime-envs`** changes bundled with this bump include
stripping v0 remnants, restoring solver network access for training
envs, fair-use solver prompts for SWE/terminal tasksets, MCP Atlas and
Enterprise Ops Gym running services in VMs, TMax hosting completion,
CI/eval CLI fixes, and related housekeeping—not new logic in this repo
beyond the dependency pin and lock refresh.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
75422004f320992e134a1d188368f15637bf8193. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-22 13:19:08 -07:00
Mika SenghaasandGitHub 9aa8563eae fix(inference): extend startup readiness timeout (#3626)
## Summary
- increase the default inference readiness timeout from 30 minutes to 60
minutes
- keep the direct `check_health` default aligned with `ClientConfig`

Large models can exceed 30 minutes on a cold node while vLLM compiles
architecture-specific kernels and captures CUDA graphs. The previous
default can tear down an otherwise healthy launch just before readiness.

## Test plan
- `PYTHONPATH="$PWD/src:$PWD/packages/prime-rl-configs/src" pytest -q
tests/unit/orchestrator/test_clients.py` (10 passed)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Only increases startup wait defaults; no changes to auth, weight
updates, or runtime inference behavior once ready.
> 
> **Overview**
> Raises the default **inference pool startup wait** from 30 to **60
minutes** so cold starts (e.g. vLLM kernel compile and CUDA graph
capture on large models) are less likely to fail right before `/health`
succeeds.
> 
> The change updates `ClientConfig.wait_for_ready_timeout` in shared
config and the default `timeout` on `check_health`, keeping orchestrator
health polling aligned with the config default used by
`AdminPlane.wait_for_ready`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f9fdfe25be6d643d43e830121bf22b6a9bd036c1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-22 11:58:23 -07:00
Mika SenghaasandGitHub a44dc3572c feat(inference): configurable vLLM router request timeout (#3620)
## Summary

- Add `VllmRouterConfig.request_timeout_secs` (**default 1800 — the
router's own built-in default**, `ge=1`): the maximum lifetime of a
routed request, including streamed completions.
- Wire it through both router launch paths — the Python entrypoint
(`--request-timeout-secs`) and the `_launch_router.sh.j2` template. When
unset, the router behaves exactly as before.
- Long agentic rollouts set it explicitly, e.g. `request_timeout_secs =
3600` for one-hour SWE eval requests.

## Note on "no timeout"

The Rust router applies the value as its HTTP client's **total request
timeout unconditionally** (`server.rs`,
`.timeout(Duration::from_secs(...))`): plain `u64`, no disable sentinel,
and `0` would be an *immediate* timeout. So "no timeout" is not
expressible — a finite configurable value with the upstream default is
the right shape.

## Validation

- `VllmRouterConfig` default (`1800`) / set (`3600`) / `ge=1` rejection
all verified; both launch paths interpolate the same field (the template
already receives the `router` config object).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Operational tuning of router HTTP client timeouts only; no auth or
data-path changes, though misconfigured values could still cut off or
hang long requests.
> 
> **Overview**
> Adds **`request_timeout_secs`** on **`VllmRouterConfig`** (default
**1800s**, minimum 1) so the maximum lifetime of a routed
request—including streamed completions—can be set from inference config
instead of relying on implicit router defaults.
> 
> Both managed router launch paths now pass
**`--request-timeout-secs`**: the local **`start_router`** entrypoint
and the SLURM **`_launch_router.sh.j2`** template read
**`router.request_timeout_secs`**. Long agentic or eval rollouts can
raise the value (e.g. via config override) without patching launch
scripts.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
adf7321a3604f2fc784ab961688a281ab6002165. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-21 16:22:12 -07:00
Mika SenghaasandGitHub 32f4f40f9e feat(orchestrator): unified taskset shuffle for train and eval sources (#3622)
## Summary

- `EnvConfig.shuffle` (`bool`, default `False`): shuffle the source's
finite taskset **once at startup** with a fixed seed
(`TASKSET_SHUFFLE_SEED = 42`).
- Defined in one place — `EnvConfig`, the shared base — so both
`TrainSourceConfig` and `EvalSourceConfig` inherit it: one knob covers
RL train envs, RL/SFT online evals, and standalone evals. Train
curricula and eval example selection both consume the shuffled order.
- Infinite tasksets reject `shuffle` at startup with a clear error.
- The eval resume allowlist now overrides `source.*.shuffle` (fixed seed
⇒ deterministic across resume).

```toml
[[train.source]]           # or [[eval.source]]
shuffle = true
```

Mirrors the existing SFT-data convention (`shuffle: bool` + fixed seed).

## Validation

- `pytest tests/unit/orchestrator/ tests/unit/eval/
tests/unit/test_configs.py` — 288 passed, 1 skipped.
- Smoke: `TrainSourceConfig(..., shuffle=True)` and
`EvalSourceConfig(..., shuffle=True)` both parse; default is `False`;
resume allowlist updated.
- **Manual eval-selection run (real `Env.start()` path, gsm8k,
`num_examples = 50` of 1319 test tasks; only the env-server network
handshake stubbed — no GPU on the validating node):**
- `shuffle = false`, run 1 → `[0, 1, 2, ..., 49]` (natural source order)
- `shuffle = true`, run 1 → `[588, 1214, 57, 906, 1252, 618, 599, 289,
...]`
- `shuffle = true`, run 2 → identical to run 1 (same 50 tasks, same
order) ✔ reproduces
  - `shuffle = false`, run 2 → identical to run 1 ✔ off is stable
- off vs on selections differ (set overlap 2/50, as expected for a
random 50-of-1319 subset) ✔

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Behavior is opt-in with a fixed seed and only affects task ordering at
startup; infinite tasksets are explicitly rejected.
> 
> **Overview**
> Adds a **`shuffle`** flag on shared **`EnvConfig`** (default
**`false`**) so train and eval sources can reorder a **finite** taskset
once at env startup instead of always taking tasks in source order.
> 
> When **`shuffle=true`**, the orchestrator materializes the taskset and
shuffles it with a fixed seed (**`TASKSET_SHUFFLE_SEED = 42`**), so the
same permutation holds for the whole run and eval example selection
stays reproducible. **Infinite** tasksets fail fast with a clear error.
> 
> Eval **resume** may override **`source.*.shuffle`** alongside other
rollout knobs. New unit tests cover default order, changed selection,
reproducibility, full-taskset selection, and the infinite-taskset
rejection.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8358483c1144ed331f575a5e857fabe390de50c8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-21 16:20:06 -07:00
Mika SenghaasandGitHub ef07764841 feat(sft): per-row reasoning_effort renderer override (#3621)
## Summary

- A `reasoning_effort` column in the dataset overrides the `[renderer]`
config's `reasoning_effort` field **per row**, so one SFT run can mix
reasoning efforts with the configured renderer serving as the default
for rows that do not set one (or set null).
- Requires a typed renderer config that has the field: `renderer.name =
"auto"` and field-less renderers raise a clear `ValueError`. Renderer
configs are frozen, so resolved configs are cached and rows resolving to
the same config share one renderer instance.
- Doc paragraph in `docs/training.md`; dataloader and sft-dataset tests
updated.

```toml
[renderer]
name = "glm-5.3"          # typed renderer; reasoning_effort = "max" is the row default
# dataset rows may carry reasoning_effort = "low" | "high" | "max" per row
```

## Validation

- `pytest tests/unit/train/sft/` — 47/47 pass.
- E2E with the real GLM-5.3 renderer: rendered prompts carry the per-row
effort preamble (`Reasoning Effort: Low` vs `Max`), invalid efforts
rejected by the config `Literal`, `None` rows fall back to the
configured renderer, and the resolver caches one renderer per distinct
config.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are confined to SFT tokenization/renderer selection with
explicit validation for auto or unsupported renderers; misconfiguration
fails at load time rather than silently wrong training.
> 
> **Overview**
> SFT can now **mix reasoning efforts in one run** via an optional
dataset **`reasoning_effort`** column that overrides the typed
`[renderer]` config per row; null/missing values keep the TOML default.
> 
> **`RendererResolver`** (in `data.py`) builds and **caches** renderers
from `renderer_config` + row overrides instead of a single shared
renderer. **`SFTDataset`** takes a per-example renderer callable;
**`setup_dataset`** / **`train.py`** pass **`renderer_config`** and the
VLM **processor** rather than constructing one renderer up front (train
and validation use the same path).
> 
> Docs in **`training.md`** describe the column, typed-renderer
requirement, and supported model families. Unit tests were updated to
pass `lambda _: renderer` into **`SFTDataset`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3408b9918dccf06d86ab732faa94a18f6233ca31. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-21 16:20:00 -07:00
7745c669d1 feat(monitors): attach eval runs to a platform-created evaluation (#3619)
## Summary

`PrimeEvalMonitor` attaches to an existing platform evaluation when
`$PRIME_RUNS_EVAL_ID` is set, instead of always registering a new one.
This mirrors how `PrimeTrainMonitor` already attaches to `$RUN_ID`.

Why: A hosted evaluation is created by the platform before its sandbox
starts: the platform owns billing, secrets, timeouts, cancellation and
the final "did every episode reach the platform" check, and it hands the
sandbox the evaluation's id, which the monitor reads from
`$PRIME_RUNS_EVAL_ID`. Today `uv run eval --monitors.prime` inside that
sandbox would call `pr.init(kind="eval", ...)` without an id, register a
second evaluation and leave the platform's one open forever.


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes platform eval registration lifecycle for hosted runs;
misconfiguration (multiple sources or multiple epochs) fails fast with
explicit errors.
> 
> **Overview**
> **Hosted eval sandboxes** can now stream to an evaluation the platform
already created instead of registering a duplicate that leaves the
platform run orphaned.
> 
> When **`PRIME_RUNS_EVAL_ID`** is set, `PrimeEvalMonitor` calls
`pr.init` with that **`id`** (same attach pattern as training’s
**`$RUN_ID`**). Init requires **exactly one** eval source, and
**`open`** rejects a second epoch so one injected id maps to one epoch.
Logs note attachment when **`run.attached`** is true.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b4af11c50eb8201cbaf1b9a903b245a1bb8ed76e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 15:23:56 -07:00
87c5456806 chore(deps): bump vLLM to 0.29.0 (#3617)
Bumps vLLM from 0.28.0 to 0.29.0 and reconciles prime-rl's runtime
monkeypatches with 0.29's reorganized entrypoint layout. Three patches
are now obsolete and removed, each backed by a merged upstream PR.

- Rebound the API server layer onto `vllm.entrypoints.launchers.*`: on
0.29 the old `openai.api_server` path is a deprecation shim, so without
this the custom routes and the `PrimeRlServingTokens` swap would
silently not install.
- Dropped `monkey_patch_fp32_lm_head`: vLLM does the fp32 lm_head
projection natively via `head_dtype`
([#48390](https://github.com/vllm-project/vllm/pull/48390), LoRA path
[#48525](https://github.com/vllm-project/vllm/pull/48525)), so
`enable_fp32_lm_head` now injects `hf_overrides = {"head_dtype":
"float32"}`.
- Dropped the `PrimeRlServingTokens.serve_tokens` `kv_transfer_params`
bridge: upstream threads the params into the engine itself as of
[#42644](https://github.com/vllm-project/vllm/pull/42644), which landed
after the 0.28.0 cut.
- Dropped `monkey_patch_qwen3_coder_param_newline_trim`: upstream
restored the single-newline trim in
[#48846](https://github.com/vllm-project/vllm/pull/48846), making the
patch a byte-for-byte no-op.
- #48390 and #48846 already shipped in 0.28.0, so 0.29's role is to make
`fp32_lm_head` *fatal* via the new positional `skip_gather`; only #42644
is genuinely unlocked by the bump.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 15:36:25 -04:00
12b4d4b050 chore: whitelist the Environments Hub index for uv installs (#3612)
## Summary

- Add an explicit `[[tool.uv.index]]` named `prime-hub` for
`https://hub.primeintellect.ai/primeintellect/simple/` with
`exclude-newer = false`. Hub wheels carry no upload time, so the repo's
7-day `exclude-newer` cooldown filtered all of them out.
- `uv pip install gsm8k --index prime-hub` and `uv add gsm8k --index
prime-hub` now resolve inside prime-rl. The index is `explicit`, so `uv
sync` never consults it and `uv lock --check` passes unchanged.

Only the named index inherits the setting: passing the same URL via
`--extra-index-url` still hits the cooldown (uv matches index config by
name). Other Hub owners need their own entry or `--no-config`.

Verified in a fresh checkout: `uv lock --check`, slim `uv sync`, then
install through `--extra-index-url` (rejected), `--index prime-hub`
(0.1.4 installed), and the per-environment install index (rejected).

Companion: PrimeIntellect-ai/prime#934 (`prime eval run` installs Hub
environments into a prime-rl sandbox; it uses `--no-config` so any owner
works).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dependency-index configuration only; narrows the exclude-newer bypass
to an explicit, opt-in first-party index without changing default sync
behavior.
> 
> **Overview**
> Adds a named **`prime-hub`** uv index pointing at the Environments Hub
with **`exclude-newer = false`**, so Hub wheels (which lack upload
timestamps) are no longer blocked by the repo-wide **7-day**
`exclude-newer` policy.
> 
> The index is **`explicit`**, so default **`uv sync`** / lock checks
stay unchanged; Hub packages resolve only when you opt in (e.g. **`uv
add gsm8k --index prime-hub`**). Passing the same URL via
**`--extra-index-url`** still applies the global cooldown because uv
matches index settings by configured name, not raw URL.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1ac034977bbf2a54ef2977314fc87a9d2f6b1b5f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 10:51:06 -07:00
JannikStandGitHub 64a0decfaa improvement(docker): bake the dashboard extra into the cuda image (#3613)
### What & why

The prime-rl-fft chart runs a standalone read-only dashboard pod per
release (prime-rl-fft #75) that serves prime-rl's run dashboard (`uv run
dashboard`, port 7788) off the run's shared PVC. The chart image does
not include the `dashboard` extra (fastapi/uvicorn), so the pod
previously installed it at start with `uv sync --inexact` — which hangs
on some clusters, leaves the Deployment permanently unready, and times
out the whole release's helm `--wait` readiness gate after 90m, killing
every trainer/inference/orchestrator pod regardless of their own health.
The dashboard was disabled by default as a stopgap (prime-rl-fft #86).

This bakes the `dashboard` extra directly into the cuda image so the
dashboard pod serves straight from the image with no runtime install.

### Changes
- `Dockerfile.cuda`: add `--extra dashboard` to both `uv sync` calls
(third-party deps layer + first-party source layer).

### Notes
- `fastapi` + `uvicorn` are a few MB next to the ~20 GB GPU venv;
negligible size impact.
- Both syncs use `--locked` and `uv.lock` already resolves the
`dashboard` extra — no lockfile changes.
- Follow-ups (fft chart repo, separate PRs): drop the pod-start `uv sync
--inexact` command and re-enable the dashboard by default; expose it to
the platform backend over the tailnet.

### Testing
- No runtime code touched; image CI builds the image from this branch.
- `uv lock --check` equivalent verified: lock already contains the
dashboard extra deps with markers.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Build-only Dockerfile change that adds two small locked deps to the
venv; no application or runtime behavior changes in this repo.
> 
> **Overview**
> **Bakes the `dashboard` optional extra (FastAPI + Uvicorn) into the
CUDA Docker image** so Helm FFT chart dashboard pods can run `uv run
dashboard` from the image without a startup `uv sync`.
> 
> Both dependency install steps in `Dockerfile.cuda` now pass `--extra
dashboard` alongside the existing GPU/flash-attn extras, with a short
comment tying this to the chart dashboard pod. Lockfile is unchanged;
syncs stay `--locked`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
78fecdd68099796469bc2cecce1ad10142d9a76c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-21 09:27:47 -07:00
samsjaandGitHub a1822f7a0a feat: default enable_ep_weight_filter to true (#3608)
## What

- Adds a typed `inference.vllm.enable_ep_weight_filter` field defaulting
to `true`, so every vLLM server prime-rl launches now passes
`--enable-ep-weight-filter` (previously this flag only appeared as an
explicit pass-through in the GLM-5.3 advanced examples).
- Drops the now-redundant explicit `enable_ep_weight_filter = true` from
the GLM-5.3 examples (`examples/advanced/glm-5.3/swe.toml`,
`examples/advanced/glm-5.3/infer/pd-llmd.toml`).
- Asserts the default lands on the server namespace.

## Why

Under expert parallelism, vLLM's weight filter skips non-local
per-expert tensors **before** reading them from disk: each rank reads
only its own expert shard instead of the full checkpoint (experts are
~85-90% of MoE weight bytes). This cuts load I/O and startup time,
especially on shared storage.

The default is safe elsewhere — vLLM only activates the filter when the
model is MoE, `enable_expert_parallel` is on, and EPLB is off. It is a
silent no-op for dense models, fused-expert checkpoints (GPT-OSS style),
and EPLB runs. The repo pins `vllm>=0.28.0`, which has the flag.

Set `inference.vllm.enable_ep_weight_filter = false` to restore the old
behavior.

Note: #3604 relocates these GLM-5.3 examples to `configs/advanced/` and
its copies still carry the explicit line — drop it when rebasing on this
PR.

## Test plan

- `uv run pytest tests/unit/test_parsers.py tests/unit/test_configs.py`
- Verified `to_namespace()` emits `enable_ep_weight_filter=True` for a
real GLM-5.3 config, and that `--vllm.enable-ep-weight-filter false`
overrides it.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Behavior change is gated in vLLM to MoE + expert parallelism without
EPLB; dense models and other modes are no-ops, with an explicit config
escape hatch.
> 
> **Overview**
> **Expert-parallel MoE loads now opt into vLLM’s EP weight filter by
default**, via a typed `inference.vllm.enable_ep_weight_filter` field
(default `true`) that flows through `to_namespace()` to
`--enable-ep-weight-filter`. That lets each rank read only its local
expert shard at checkpoint load instead of full expert tensors, reducing
I/O and startup time when EP is on and EPLB is off.
> 
> The GLM-5.3 advanced TOML recipes **drop redundant**
`enable_ep_weight_filter = true` lines and rely on the default. A unit
test **asserts** the resolved server namespace includes
`enable_ep_weight_filter=True`. Set
`inference.vllm.enable_ep_weight_filter = false` to disable.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f26215dee423de2a19ec763106fd979183556cef. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 22:57:30 -07:00
samsjaandGitHub 8c2847721a chore(examples): glm-5.3 swe.toml base + swe-llmd.toml append, serve BF16 with vllm-side FP8 (#3607)
## What

Reworks the GLM-5.3 RL examples as a **base + append** pair instead of
two standalone configs, and moves both variants onto the shared
`GLM-5.3-BF16` checkpoint with vLLM-side online FP8 quantization:

- **`swe.toml`** — the base config, carrying all the params that used to
live only in `swe-llmd.toml` (r2e-gym train source under the `rlm`
harness, `deepgemm_fp8` trainer, `cp = 4` / `ep = 8`, 16 train + 16
disaggregated-P/D infer nodes) behind the default **`vllm-router`**.
Inference serves the same **`zai-org/GLM-5.3-BF16`** checkpoint the
trainer broadcasts; vLLM quantizes it to per-block FP8 online
(`quantization = "fp8_per_block"`) — no separate FP8 release checkpoint.
- **`swe-llmd.toml`** — now a small **append overlay**: llm-d router
(EPP scorer tuning), Mooncake KV offload, and run-identity swaps (run
name / W&B project / SLURM job / sandbox runtime label). Launch:

  ```bash
uv run rl @ examples/advanced/glm-5.3/swe.toml # vllm-router
uv run rl @ examples/advanced/glm-5.3/swe.toml @
examples/advanced/glm-5.3/swe-llmd.toml # llm-d + Mooncake
  ```

- **`README.md`** — documents the base/append split, the composed launch
command, and which FILL INs live where.

## Why

- Two nearly-identical 100+ line configs drifted apart; a base + `@`
overlay keeps the llm-d variant a true delta (router + KV offload) and
makes the router the only difference between runs.
- Serving `GLM-5.3-BF16` with online per-block FP8 matches the trainer's
broadcast target and removes the dependency on the official block-FP8
serving release for both variants.

## Validation

Both launch paths resolve and validate end-to-end with `rl --dry-run`
(resolved per-process configs + sbatch generation): the base launches
`vllm-router --policy sticky_least_loaded`; the composed run swaps in
the llm-d router (EPP + Envoy) and enables Mooncake KV offload. Overlay
list-replacement semantics verified — the composed run keeps exactly one
train source, with the runtime label swapped to `glm5-llmd`.

Infer pre-flight configs (`infer/pd.toml`, `infer/pd-llmd.toml`) are
untouched.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are limited to example TOMLs and documentation; no runtime or
library code paths are modified.
> 
> **Overview**
> Reorganizes the GLM-5.3 RL examples so **`swe.toml` is the full base
stack** (r2e-gym / `rlm`, FP8 trainer, P/D inference behind
**`vllm-router`**, serving **`GLM-5.3-BF16`** with online block FP8) and
**`swe-llmd.toml` is a thin overlay** for llm-d router scorer tuning,
Mooncake KV offload, and sandbox runtime labels.
> 
> Most settings that previously lived only in `swe-llmd.toml` move into
`swe.toml`; the llm-d file drops trainer/orchestrator/deployment
duplication. The README is updated to describe **base vs append**
launches (`rl @ swe.toml` vs `rl @ swe.toml @ swe-llmd.toml`), moves
“FILL IN” and Mooncake tuning notes to the right file, and states that
**neither RL file ships `[ckpt]`** by default (overlay to add
checkpoints). The old **`swe.toml` train-source-less / SWE-bench-eval
plane is replaced** by this composable layout—not removed entirely.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c9d87a57a24248945b3035d1cb87dee2f8f66a1a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 19:48:22 -07:00
samsjaandGitHub 9dbe8b5fa0 fix: select GLM-5.3 renderer in examples (#3606)
## Summary
- configure both GLM-5.3 example runs to use the matching `glm-5.3`
renderer

Requires the GLM-5.3 renderer pinned by #3605.
2026-09-18 16:03:56 -07:00
samsjaandGitHub 819993faac chore: bump renderers for GLM-5.3 (#3605)
## Summary
- pin `deps/renderers` to the GLM-5.3 renderer implementation

Depends on PrimeIntellect-ai/renderers#156.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> <sup>[Cursor Bugbot](https://cursor.com/bugbot) is generating a
summary for commit 8c41fdb84cd8bbfa5f2b2fc97887da57fbf3ba40. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 15:40:49 -07:00
Mika SenghaasandGitHub d57c59f16a fix: do not abort on consecutive empty train batches (#3595)
## Summary

- Remove the run-level aborts on consecutive empty train batches:
- The orchestrator raised after 10 consecutive no-sample train batches.
`MAX_CONSECUTIVE_EMPTY_BATCHES` and its counter are gone; an empty batch
now logs a warning and is skipped.
- The train sink raised after 10 batch-equivalents of finalized groups
that shipped no payload. The tally now only throttles the warning
(`_warn_zero_output`); there is no abort.
- Keep both warnings, so a run with no training signal stays visible in
the logs. A dead curriculum, an all-equal reward sweep, or an
infrastructure outage now stalls the run instead of killing it.
- Update the one `docs/algorithms.md` sentence that described the abort.
## Verification

- `uv run pytest tests/unit/orchestrator -q`: 82 passed, 1 skipped. The
8 failures are pre-existing `torch`/`vllm` import errors in a no-extras
env and fail the same way on `main`.
- `ruff check` / `ruff format --check` pass on both changed files.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Behavior change is limited to error handling: runs no longer fail fast
on sustained empty training signal, which may hide config issues but
avoids killing jobs on benign stalls.
> 
> **Overview**
> **Removes run-killing guards** when training produces no shippable
data, so misconfigured curricula or transient all-zero-advantage groups
**stall with warnings** instead of crashing the orchestrator.
> 
> In **`orchestrator.py`**, the **10 consecutive empty-batch abort** is
gone: empty `TrainBatch` samples log *"skipping empty train batch"* and
return without advancing the step. **`train_sink.py`** keeps counting
zero-output finalized units but **`_warn_zero_output`** only emits
throttled warnings—no **`RuntimeError`** after 10 batch-equivalents.
> 
> **`docs/algorithms.md`** now says group-relative `group_size = 1`
empty batches are **skipped at runtime**, not aborted.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3160f47b861a2c9c6cb33fef4961336f9b6560e9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 11:22:15 -07:00
Matej SirovatkaandGitHub c4a78d1134 fix: specialize FP8 indexer quantization constants (#3594)
Compiled GLM-5.3 training fails on its first forward pass because `eps`,
`fp8_min`, and `fp8_max` reach the FP8 indexer quantization kernel as
runtime FP64 scalars. Their arithmetic promotes the quantization result
to FP64, and Triton rejects the resulting conversion with `Unsupported
conversion from f64 to f8E4M3FN with rounding mode rtne`.

Mark these three fixed scalar arguments as `tl.constexpr` so Triton
specializes them at compile time.

Validation: reproduced the failure on an 8-node H200 BF16 trainer with
`torch.compile`, activation checkpointing/offloading, full CPU offload,
and SignSGD. With this patch, the first forward/backward pass and
optimizer update completed, and the trainer began broadcasting policy
v1. The 20-step verification run is still in progress. `git diff
--check` passes.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Single-line Triton signature change with no API or logic changes; only
affects compile-time specialization of fixed FP8 bounds.
> 
> **Overview**
> Fixes **compiled training crashes** on the first forward pass when the
FP8 indexer quantizes activations under `torch.compile`.
> 
> The Triton kernel `_per_token_group_quant_fp8` now treats **`eps`,
`fp8_min`, and `fp8_max` as `tl.constexpr`** instead of runtime
arguments. Previously those scalars promoted quant math to FP64, and
Triton failed converting the result to FP8 (`f64` → `f8E4M3FN`).
Specializing them at compile time keeps the quant path in types Triton
can lower correctly; callers still pass the same module-level `FP8_EPS`
/ `FP8_MIN` / `FP8_MAX` constants.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
02f155d8ffb8776346c320be42a6be1f1f5299e9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 13:12:13 +02:00
cacae615e6 chore(examples): rename GLM example folder to glm-5.3 (#3593)
The advanced GLM presets now train GLM-5.3, but the directory was still
named glm-5.2. Rename it and update every inbound link and the
"GLM-5/GLM-5.2" prose in the READMEs and docs.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation and example path updates only; no training, inference,
or runtime code changes.
> 
> **Overview**
> Renames the advanced GLM example from **`glm-5.2`** to **`glm-5.3`**
and updates every inbound link and launch snippet so docs match the
presets that target GLM-5.3.
> 
> **README**, **docs** (`advanced.md`, `configuration.md`,
`scaling.md`), and **examples/README** now point at
`examples/advanced/glm-5.3/` and describe **`GLM-5`/`GLM-5.3`** instead
of 5.2. The **glm-5.3** walkthrough updates `uv run rl` / `uv run
inference` paths; **`infer/pd-llmd.toml`** only fixes its launch comment
to the new path (config content such as `GLM-5.2-FP8` model IDs is
unchanged).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fb2d99039d8719ff2bcdf2ac1e2c7baaa6f49946. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Johannes Hagemann <johannes@Johanness-MacBook-Pro.local>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-18 00:22:35 -07:00
samsjaandGitHub a9005aba8e fix(examples): express GLM-5.2 SWE shared model as a [model] table (#3591)
## Summary
PR #3588 centralized the model id for
`examples/advanced/glm-5.2/swe.toml` as a top-level
string (`model = "zai-org/GLM-5.3-BF16"`), but `RLConfig.model` is a
`SharedModelConfig`
table, so no config class could parse the file and CPU tests on `main`
failed
(`test_load_configs[examples/advanced/glm-5.2/swe.toml]`).

- Express the shared model as a `[model]` table with `name =
"zai-org/GLM-5.3-BF16"`, which
propagates to `trainer.model.name`, `orchestrator.model.name`, and
`inference.vllm.model`
  (same intent as #3588).
- Update the `[inference.vllm]` comment: it now serves the shared BF16
checkpoint with online
  per-block FP8 quantization, not a separate block-FP8 release.

Fixes the CPU Tests failure on `main` introduced by #3588.
2026-09-17 23:55:47 -07:00
samsjaandGitHub 788b9fdd1a Update swe.toml (#3588)
<!-- CURSOR_SUMMARY -->
> [!NOTE]
> **Low Risk**
> Example config-only change with no application code; verify the stack
resolves the correct vLLM checkpoint now that `[inference.vllm]` no
longer sets a separate `zai-org/GLM-5.3` id.
> 
> **Overview**
> **Centralizes the Hugging Face model id** for the GLM-5.2 SWE advanced
example by adding a top-level `model = "zai-org/GLM-5.3-BF16"` and
dropping duplicate `name` / `model` entries under `[trainer.model]`,
`[inference.vllm]`, and `[orchestrator.model]`.
> 
> Inference still uses the same vLLM settings (BF16 dtype,
`fp8_per_block` quantization, GLM tool parser); only the redundant
per-section model strings are removed so one field drives training and
orchestration.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
4520df470f2417d4333f48fb80f40a2ed820574e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
2026-09-17 22:38:22 -07:00
93 changed files with 1968 additions and 1303 deletions
+1 -1
View File
@@ -43,7 +43,7 @@ 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).
Skills live in `skills/` and are symlinked to `.claude/skills/` (Claude Code) and `.agents/skills/` (Codex). They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs).
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.
-1
View File
@@ -1 +0,0 @@
@AGENTS.md
+19 -2
View File
@@ -94,9 +94,10 @@ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
# Third-party deps only — source edits don't bust this layer. First-party
# editables install in the source-layer sync below. No build-context bind
# mount here: .git would bust the cache every commit.
# `--extra dashboard` (fastapi/uvicorn) is baked in so the fft chart's dashboard pod needs no runtime uv sync (see PR body).
COPY --from=manifests /manifests /app
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
--no-install-workspace \
--no-install-package prime-rl-configs \
--no-install-package verifiers \
@@ -132,10 +133,26 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
# Needed for private environments hub auth.
#
# FIXME(prime#940): workaround, remove once the prime CLI drops verifiers as
# a dependency (https://github.com/PrimeIntellect-ai/prime/pull/940). The CLI
# pins verifiers==0.2.0, which replaced the editable verifiers synced above
# with the PyPI wheel and left prime-rl's own entrypoints unable to import;
# the --overrides file ignores that one requirement. When removing it, drop
# the overrides file and the --overrides flag, keep the import assertion, and
# make the same change in scripts/docker-entrypoint.sh, which replays this
# step for the runtime source overlay.
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
printf 'verifiers\n' > /tmp/prime-cli-overrides.txt \
&& VIRTUAL_ENV=/app/.venv uv pip install --overrides /tmp/prime-cli-overrides.txt 'prime>=0.7' \
&& rm /tmp/prime-cli-overrides.txt \
&& /app/.venv/bin/python -c 'import pathlib, verifiers; assert pathlib.Path(verifiers.__file__).is_relative_to("/app/deps/verifiers"), verifiers.__file__'
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
# (#2883); rebuilding against our UCX is the documented fix. Only needed for
+4 -19
View File
@@ -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
@@ -113,15 +113,6 @@ uv sync --all-extras
> *NOTE*: Environments are opt-in uv workspace members — `uv sync --all-extras` does not install them. To train on them, install all with `uv sync --all-extras --all-packages`, or a subset with `uv sync --package prime-rl --package <env>`.
3.1. Optional: Install Flash Attention 3 (on Hopper GPUs only, for flash_attention_3 attention backend)
> *NOTE*: This step will take a while, as it builds the Flash Attention 3 extension from source, as it has no wheels prebuilt.
> *NOTE*: After this step, you can't run `uv sync --all-extras` or `uv run` as it will uninstall the package, you can avoid it by running `uv sync --inexact` or `uv run --no-sync`
```bash
uv pip install "flash-attn-3 @ git+https://github.com/Dao-AILab/flash-attention.git@main#subdirectory=hopper" --no-build-isolation
```
</details>
<details>
@@ -148,19 +139,13 @@ uv run python -c "import flash_attn"
uv run sft @ configs/debug/fake/sft.toml
```
4. Check that you can run the RL trainer (*this requires 1 GPU*)
```bash
uv run trainer @ configs/debug/fake/rl.toml
```
5. Check that you can run the inference server (*this requires 1 GPU*)
4. Check that you can run the inference server (*this requires 1 GPU*)
```bash
uv run inference --vllm.model Qwen/Qwen3-0.6B
```
6. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
5. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
```bash
uv run rl @ configs/basic/reverse-text/rl.toml
@@ -204,7 +189,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
+1 -1
+1 -1
+1 -1
View File
@@ -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:
+1 -1
View File
@@ -112,7 +112,7 @@ patterns = ["WARNING"]
def drop_warnings(rollout, *, patterns: list[str]) -> list[list[bool]]: ...
```
Component compatibility is validated at config time: frozen-model sampling can only feed the `ce` loss component — the `rl` and `ref_kl` components need the live policy's own sampling logprobs for importance ratios — `opd` pointed at `"policy"` is rejected as degenerate (zero KL), `sft` without a frozen source is rejected (CE on the policy's own tokens is not a distillation target). A group-relative algorithm with `group_size = 1` produces all-zero advantages; the resulting empty batch is caught at runtime (the orchestrator warns and aborts after repeated zero-trainable batches), not at config time.
Component compatibility is validated at config time: frozen-model sampling can only feed the `ce` loss component — the `rl` and `ref_kl` components need the live policy's own sampling logprobs for importance ratios — `opd` pointed at `"policy"` is rejected as degenerate (zero KL), `sft` without a frozen source is rejected (CE on the policy's own tokens is not a distillation target). A group-relative algorithm with `group_size = 1` produces all-zero advantages; the resulting empty batch is caught at runtime (the orchestrator warns and skips it), not at config time.
### Per-Env Algorithms
+10 -1
View File
@@ -171,6 +171,15 @@ env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
Each source group — `[orchestrator.train]`, `[orchestrator.eval]`, the `[eval]` block of `sft` and the top level of `eval` — takes an `env` block that each of its sources inherits. A source's own `env` values win. The block holds only the knobs that every env and taskset has: `retries`, `timeout`, `max_concurrent_agents`, `interception`, and `taskset.task` and `taskset.system_prompt`. Ids and agents stay on each source:
```toml
[orchestrator.eval.env]
retries.max_retries = 3
retries.include = ["ProviderError", "SandboxError"]
timeout.episode = 7200
```
`ratio` is a training-source field: it defaults to `1` (equal weight per env), and values are relative weights normalized to probabilities across envs. Eval sources of a training run carry `interval` instead, the step interval at which they fire (inherited from the group-level `interval` when unset); a standalone eval has neither.
Everything environment lives under the `env` block (verifiers' `[env]` shape): `env.taskset` configures the v1 taskset, and each agent is a field on the env — `env.agent.harness` selects how the single-agent env's tasks are run, and per-run caps are per-agent (`env.agent.max_turns`, `env.agent.timeout`, `env.agent.max_output_tokens`). A multi-agent env declares its own seats (`env.<role>.*`).
@@ -229,7 +238,7 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
- [**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
+9 -2
View File
@@ -32,7 +32,7 @@ uv run inference --vllm.model Qwen/Qwen3-4B
uv run eval gsm8k -n 32 -r 4 -m Qwen/Qwen3-4B --client.base_url http://localhost:8000/v1
```
Single-source shorthands: `<taskset-id>` names the run's only source, `--env.<field> <value>` sets a field of that source's env block (`--env.agent.harness.id bash`, `--env.taskset.tasks '["fix-git"]'`), `-n`/`-r` set `num_examples`/`group_size`, `-m` the model, and `-c N` pins the concurrency band (`concurrency.min_inflight = max_inflight = N`). The shorthands cannot be combined with a TOML that defines `[[source]]` blocks. `uv run eval -h` lists them.
Single-source shorthands: `<taskset-id>` names the run's only source, `--env.<field> <value>` sets a field of that source's env block (`--env.agent.harness.id bash`, `--env.taskset.tasks '["fix-git"]'`), `-n`/`-r` set `num_examples`/`group_size`, `-m` the model, and `-c N` pins the concurrency band (`concurrency.min_inflight = max_inflight = N`). `<taskset-id>` cannot be combined with a TOML that defines `[[source]]` blocks; next to one, `--env.<field>` sets the shared [env block](#configuration) instead. `uv run eval -h` lists them.
Against a local vLLM deployment, set `min_inflight < max_inflight` in `[concurrency]` to dynamically adjust the number of concurrent episodes for maximum throughput. An external API exposes no vLLM `/metrics` to adapt to, so pin the concurrency there (`-c N`, i.e. `min_inflight = max_inflight`).
@@ -55,6 +55,10 @@ max_inflight = 256
[sampling]
max_completion_tokens = 2048
[env] # every source inherits these
timeout.episode = 7200
retries.max_retries = 3
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "bash"
@@ -65,7 +69,9 @@ env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
Per-source `num_examples`, `group_size` and `sampling` override the top-level defaults. Every source's env server is spawned by the eval process unless the source sets `serve.address`, in which case the server is externally managed. A spawned server binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/eval/<name>.address`, which the eval process reads, so concurrent runs on one host never collide on a port.
Per-source `num_examples`, `group_size` and `sampling` override the top-level defaults. The top-level `[env]` block holds the env knobs that every source inherits (see [Environments](configuration.md#environments)); a source's own `env` values win.
Every source's env server is spawned by the eval process unless the source sets `serve.address`, in which case the server is externally managed. A spawned server binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/eval/<name>.address`, which the eval process reads, so concurrent runs on one host never collide on a port.
## Resume
@@ -109,6 +115,7 @@ Eval metrics mirror the training rollout hierarchy under the `eval/<env>` scope:
|---|---|
| `eval/<env>/all/<agent>/reward/mean` | mean reward over the epoch |
| `eval/<env>/all/<agent>/is_truncated/mean` | share of rollouts cut by the length limit |
| `eval/<env>/all/<agent>/is_timeout/mean` | share of rollouts stopped by a stage deadline (`<stage>_timeout`) |
| `eval/<env>/all/<agent>/has_error/mean` | share of rollouts that raised |
| `eval/<env>/all/seq_len/mean` | mean episode length in tokens |
+1 -1
View File
@@ -287,7 +287,7 @@ On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (o
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. vLLM 0.28 uses the V2 model runner for standard deployments. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. vLLM 0.29 uses the V2 model runner for standard deployments. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
```toml
[trainer]
+4 -4
View File
@@ -117,7 +117,7 @@ CP shards a single sequence across multiple GPUs along the token dimension — f
```toml
[trainer.model]
impl = "custom"
attn = "auto" # auto = FA3 on Hopper, FA4 on Blackwell; or flash_attention_2/3/4
attn = "auto" # auto = FA3 on Hopper, FA4 on datacenter Blackwell, FA2 otherwise; or flash_attention_2/3/4
cp = 2 # CP degree
cp_style = "ulysses" # "ring"
```
@@ -233,7 +233,7 @@ 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.
@@ -274,8 +274,8 @@ To benchmark a parallelism config before committing a multi-day run, run a short
# SFT trainer alone
uv run sft @ sft.toml --data.type fake --max-steps 4
# RL trainer alone (no inference involved)
uv run trainer @ train.toml --data.fake --max-steps 4
# RL trainer alone (no inference involved) -- launch it under torchrun, like the `rl` launcher does
uv run torchrun --nproc-per-node=8 src/prime_rl/trainer/rl/train.py @ train.toml --data.fake --max-steps 4
```
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes `monitors/file/metrics.jsonl` under the run's output directory by default (`monitors.file`); aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
+5 -3
View File
@@ -35,8 +35,7 @@ This page covers everything you need to launch, observe, checkpoint, and recover
| `uv run rl` | Wraps the trainer, orchestrator, and inference server in one launch from a merged TOML. | The default for any RL run. Runs locally for single-node experiments; submits to SLURM for single- or multi-node when `[slurm]` is set (see [Scaling § SLURM](scaling.md#slurm)). |
| `uv run sft` | Supervised fine-tuning on a HF dataset. | Launches torchrun internally; never call torchrun directly. |
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
| `uv run trainer` | Standalone trainer process group. | Use only when launching the trainer separately from the orchestrator (e.g. multi-node RL without the `rl` wrapper). |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer, inference, and one `env-server` per source. |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched inference server and one `env-server` per source. |
| `uv run eval` | Multi-env evals against a live inference server. | One epoch per source, pinned (or adaptive) concurrency, cursor checkpoints + `--resume`, dashboard + optional platform upload; see [Eval](eval.md). |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source; each binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/<split>/<name>.address` for the orchestrator); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
@@ -119,6 +118,7 @@ Pulled from the console logs and mirrored to W&B.
- `reward/{all,env}/mean` — main signal. Should trend upward over hundreds of steps.
- `seq_len/{all,env}/mean` and `is_truncated/{all,env}/mean` — rollout length and truncation rate.
- `is_timeout/{all,env}/mean` — share of rollouts stopped by a stage deadline (`setup`/`agent`/`finalize`/`scoring` `_timeout`). Training counts a timed-out rollout as an error, so it stays out of the batch; eval scores it.
- `num_turns/{all,env}/mean` — for multi-turn envs.
- `empty_rollouts/{all,env}`, `errored_rollouts/{all,env}` — non-zero is fine in small numbers; sustained > 5% is a smell.
- `eval/{env}/{avg@k,pass@k}` — eval scores when `[orchestrator.eval]` is set.
@@ -162,6 +162,8 @@ name = "qwen3"
enable_thinking = false
```
A `reasoning_effort` column in the dataset sets the renderer's `reasoning_effort` field per row, on top of the `[renderer]` config. The column requires a typed renderer that has that field (for example `gpt-oss`, `qwen3.8`, `deepseek-v4`); rows with a null value use the configured renderer unchanged. This lets one run mix reasoning efforts, with the `[renderer]` value as the default for rows that do not set one.
If a model needs another template control, add it to that model's renderer config in `renderers` (for example a new field on the relevant `*RendererConfig`) and consume it in the renderer implementation.
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `<think>` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS, and VLM families such as Qwen3-VL/Qwen3.5.
@@ -250,7 +252,7 @@ Pulled from the console log and mirrored to W&B.
- `optim/grad_norm` — spikes precede divergence.
- `optim/lr` — LR schedule.
- For MoE: `max_vio/mean` (load-balancing violation), `routing_confidence/mean` — both are logged when non-zero.
- For MoE: `max_vio/mean`, `max_vio/max` — mean and max over the step's microsteps of the largest load-balancing violation across layers and EP groups, computed from expert token counts summed across each EP group. `routing_confidence/mean` — mean routing confidence.
**Performance:**
+1 -1
View File
@@ -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.
-93
View File
@@ -1,93 +0,0 @@
seq_len = 131072
[log]
level = "debug"
[monitors.wandb]
project = "glm5-pd-disag"
[weight_broadcast]
type = "nccl"
port = 29502
timeout = 12000
[deployment]
type = "multi_node"
num_train_nodes = 16
gpus_per_node = 8
num_infer_replicas = 2
[inference.deployment]
type = "disaggregated"
prefill_nodes_per_replica = 4
decode_nodes_per_replica = 4
[inference.vllm]
# Train from the official BF16 checkpoint above; serve the corresponding
# block-FP8 release, which vLLM loads natively.
model = "zai-org/GLM-5.3"
dtype = "bfloat16"
quantization = "fp8_per_block"
tool_call_parser = "glm47"
gpu_memory_utilization = 0.80
enable_expert_parallel = true
enable_eplb = false
[slurm]
job_name = "glm5-pd-disag"
[ckpt]
interval = 100
[trainer]
dist_timeout_seconds = 7200
[trainer.model]
name = "zai-org/GLM-5.3-BF16"
impl = "custom"
attn = "flash_attention_2" # dsa is skipping flash attn anyway
fused_lm_head_token_chunk_size = 2048
ep = 8
[trainer.model.ac]
freq = 1
[trainer.model.compile]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "adamw"
lr = 1e-6
weight_decay = 0.1
[orchestrator]
batch_size = 4096
group_size = 16
max_off_policy_steps = 16
[orchestrator.concurrency]
initial_inflight = 4096
max_inflight = 8192
[orchestrator.model]
name = "zai-org/GLM-5.3"
[orchestrator.renderer]
name = "glm-5.1"
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm5-pd-disag", "swe-bench-verified"]
[inference]
# we need <0.85 bc glm5 layers are too large for 0.85
use_deep_gemm = true
@@ -1,18 +1,18 @@
# GLM-5 family at scale
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).
Large-scale RL and serving for the GLM-5 family — `zai-org/GLM-5.3-BF16` for training and serving alike, quantized to per-block FP8 online on the vLLM side — at 131k context: 16 trainer nodes on the custom MoE implementation (expert + context parallelism) and P/D-disaggregated FP8 inference. The [`swe-llmd.toml`](swe-llmd.toml) append fronts the same 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. It also offloads 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.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 |
| [`swe.toml`](swe.toml) | Base GLM-5.3 RL: trains on `r2e-gym` (`rlm` harness), FP8-quantized trainer (`deepgemm_fp8` MoE compute), serves `GLM-5.3-BF16` with online per-block FP8 quantization behind the default `vllm-router`. | 16 train + 16 infer nodes |
| [`swe-llmd.toml`](swe-llmd.toml) | Append for `swe.toml`: swaps in the llm-d router (EPP scorer tuning) + Mooncake KV offload — launch as `rl @ swe.toml @ swe-llmd.toml`. | same |
| [`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 |
## Requirements
- 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).
- 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` accordingly.
- InfiniBand/RDMA NICs for the Mooncake KV pool (llm-d append).
- **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
@@ -25,9 +25,9 @@ prime login # or: prime config set-api-key <your-key>
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
- `HF_TOKEN` — the GLM-5 family checkpoints are gated models.
- `WANDB_API_KEY` — both RL configs log to W&B (`[monitors.wandb]`).
- `WANDB_API_KEY` — both RL variants log to W&B (`[monitors.wandb]`).
### Install llm-d (llmd variants only)
### Install llm-d (llm-d append only)
The llm-d router ships as vendored binaries (`epp`, `envoy`, `pd-sidecar`). Build them once into `third_party/llmd/bin`:
@@ -48,28 +48,27 @@ uv sync --all-extras --all-packages
## Tweak before launching
- `swe-llmd.toml` marks two `# FILL IN` values: `output_dir` (point it at your shared filesystem) and `[slurm] partition`. `swe.toml` needs `--slurm.partition <your-partition>` or `--output-dir` overrides on the command line.
- `[inference.kv_cache_offload] device_name` — the RDMA NIC list for Mooncake. Auto-detection is unreliable; set it by hand from `nvidia-smi topo -m` on your nodes.
- `[inference.kv_cache_offload.cpu] num_bytes` — 1TB per node by default; lower it if your nodes have less RAM.
- `swe-llmd.toml` ships without `[ckpt]` — add a checkpoint overlay if you want resume support.
- `swe.toml` marks two `# FILL IN` values: `output_dir` (point it at your shared filesystem) and `[slurm] partition`.
- `swe-llmd.toml` `[inference.kv_cache_offload] device_name` — the RDMA NIC list for Mooncake. Auto-detection is unreliable; set it by hand from `nvidia-smi topo -m` on your nodes.
- `swe-llmd.toml` `[inference.kv_cache_offload.cpu] num_bytes` — 1TB per node by default; lower it if your nodes have less RAM.
## Start the run
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.3 RL with llm-d + Mooncake (recommended)
uv run rl @ examples/advanced/glm-5.2/swe-llmd.toml
# GLM-5.3 RL behind the default vllm-router
uv run rl @ examples/advanced/glm-5.3/swe.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
# with the llm-d router + Mooncake KV offload appended
uv run rl @ examples/advanced/glm-5.3/swe.toml @ examples/advanced/glm-5.3/swe-llmd.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
@@ -98,6 +97,21 @@ Pass several output directories to track parallel experiments side by side (`uv
## Checkpoint and resume
`swe.toml` checkpoints every 100 steps (`[ckpt] interval = 100`). To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, a stable `--run.name`, and a `--max-steps` at least the target final step. Trainer checkpoints are DCP-sharded; export HF-format weights with `tools/convert_dcp_to_bf16.py`. See [Training](../../../docs/training.md) for the full resume and export reference.
Both RL configs ship without `[ckpt]` — add a `[ckpt]` overlay (e.g. `interval = 100`) for periodic checkpoints. To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, a stable `--run.name`, and a `--max-steps` at least the target final step. Trainer checkpoints are DCP-sharded; export HF-format weights with `tools/convert_dcp_to_bf16.py`. See [Training](../../../docs/training.md) for the full resume and export reference.
See [Scaling](../../../docs/scaling.md) for SLURM details and [Inference](../../../docs/inference.md) for the disaggregated-inference and router reference.
## SFT
The SFT configs live under [`sft/h200/`](sft/h200) — they are tuned for 8-GPU H200 nodes. Compose the base config with a data overlay:
```bash
uv run sft @ examples/advanced/glm-5.3/sft/h200/base.toml @ examples/advanced/glm-5.3/sft/h200/math-10k.toml
```
This will start a SFT run with the following configuration:
- The model is `zai-org/GLM-5.3-BF16`
- The data is `PrimeIntellect/INTELLECT-3-SFT-10K` (math split)
For a fake-data dry run, append [`fake.toml`](sft/h200/fake.toml) instead. You can use the same dashboard to monitor the SFT run.
@@ -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"
@@ -60,5 +60,4 @@ reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
@@ -0,0 +1,40 @@
clean = true
[env_vars]
HF_HOME = "/home/huggingface"
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
[model]
name = "zai-org/GLM-5.3-BF16"
impl = "custom"
attn = "flash_attention_2"
cp = 8
ep = 8
optim_cpu_offload = true
[model.ac]
freq = 1
[model.ac_offloading]
max_inflight_activations = 5
[optim]
type = "sign_sgd"
lr = 5e-5
weight_decay = 0.01
[scheduler]
type = "linear"
warmup_steps = 50
decay_steps = 0
[renderer]
name = "glm-5.3"
[deployment]
type = "multi_node"
num_train_nodes = 8
[slurm]
job_name = "glm53-sft"
partition = "all"
@@ -0,0 +1,8 @@
[model.debug]
force_balanced_routing = true
[data]
type = "fake"
batch_size = 8
micro_batch_size = 1
seq_len = 131072
@@ -0,0 +1,7 @@
[data]
type = "sft"
name = "PrimeIntellect/INTELLECT-3-SFT-10K"
splits = ["math"]
batch_size = 8
micro_batch_size = 1
seq_len = 131072
+47
View File
@@ -0,0 +1,47 @@
# llm-d append for swe.toml: fronts the P/D-disaggregated inference plane with
# the llm-d router (Endpoint Picker + Envoy) and offloads KV to a Mooncake
# distributed CPU pool. Everything else is inherited from the base config:
#
# uv run rl @ examples/advanced/glm-5.3/swe.toml @ examples/advanced/glm-5.3/swe-llmd.toml
[run]
name = "glm5-llmd"
[monitors.wandb]
project = "glm5-llmd"
[slurm]
job_name = "glm5-llmd"
# Overlays replace arrays of tables wholesale, so the train source is spelled
# out again just to swap the sandbox runtime label.
[[orchestrator.train.source]]
name = "r2e"
env.taskset.id = "r2e-gym"
env.agent.harness.id = "rlm"
env.agent.runtime.labels = ["glm5-llmd"]
[inference.router]
type = "llm-d"
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
[inference.router.scorers] # need some prefix-cache routing, however due to shared mooncake pool do low prio
"prefix-cache-scorer" = 3.0
[inference.router.prefill_scorer_overrides] # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
"queue-scorer" = 4.0
"active-request-scorer" = 5.0
[inference.router.decode_scorer_overrides] # decode doesn't really create queue, it fills in KV cache fast, give 4.0
"active-request-scorer" = 5.0
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
[inference.kv_cache_offload]
type = "mooncake"
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
[inference.kv_cache_offload.cpu]
num_bytes = 1_000_000_000_000 # 1TB per node - 16TB total CPU pool
@@ -1,16 +1,23 @@
# Base GLM-5.3 RL config: P/D-disaggregated FP8 inference behind the default
# vllm-router. Serves the same GLM-5.3-BF16 checkpoint the trainer broadcasts,
# quantized to per-block FP8 online on the vLLM side. Append swe-llmd.toml to
# front the same plane with the llm-d router + Mooncake KV offload:
#
# uv run rl @ examples/advanced/glm-5.3/swe.toml @ examples/advanced/glm-5.3/swe-llmd.toml
max_steps = 10000000
seq_len = 131072
output_dir = "/shared/outputs" # FILL IN: point at your shared filesystem
clean = true
[run]
name = "glm5-llmd"
name = "glm5"
[log]
level = "debug"
[monitors.wandb]
project = "glm5-llmd"
project = "glm5"
name = "base"
[weight_broadcast]
@@ -51,25 +58,12 @@ num_decode_replicas = 1
"max_num_seqs" = 96
[inference.router]
type = "llm-d"
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
[inference.router.scorers] # need some prefix-cache routing, however due to shared mooncake pool do low prio
"prefix-cache-scorer" = 3.0
[inference.router.prefill_scorer_overrides] # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
"queue-scorer" = 4.0
"active-request-scorer" = 5.0
[inference.router.decode_scorer_overrides] # decode doesn't really create queue, it fills in KV cache fast, give 4.0
"active-request-scorer" = 5.0
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
type = "vllm-router"
[inference.vllm]
# The trainer uses GLM-5.3-BF16; serve the official block-FP8 release.
model = "zai-org/GLM-5.3"
# Serve the same GLM-5.3-BF16 checkpoint the trainer broadcasts; vLLM quantizes
# it to per-block FP8 online.
model = "zai-org/GLM-5.3-BF16"
dtype = "bfloat16"
quantization = "fp8_per_block"
max_model_len = 131072
@@ -78,10 +72,9 @@ reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
[slurm]
job_name = "glm5-llmd"
job_name = "glm5"
partition = "all" # FILL IN: set to your cluster's partition
[trainer]
@@ -124,10 +117,10 @@ initial_inflight = 256
max_inflight = 512
[orchestrator.model]
name = "zai-org/GLM-5.3"
name = "zai-org/GLM-5.3-BF16"
[orchestrator.renderer]
name = "glm-5.1"
name = "glm-5.3"
clear_thinking = false
[orchestrator.train.sampling]
@@ -140,17 +133,9 @@ clear_thinking = false
name = "r2e"
env.taskset.id = "r2e-gym"
env.agent.harness.id = "rlm"
env.agent.runtime.labels = ["glm5-llmd"]
env.agent.runtime.labels = ["glm5"]
[inference]
# <0.80 because glm5 layers are too large for 0.85
use_deep_gemm = true
enable_fp32_lm_head = true
[inference.kv_cache_offload]
type = "mooncake"
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
[inference.kv_cache_offload.cpu]
num_bytes = 1_000_000_000_000 # 1TB per node - 16TB total CPU pool
+1
View File
@@ -45,6 +45,7 @@ weight_decay = 0.01
[orchestrator]
batch_size = 2048
group_size = 8
[orchestrator.concurrency]
initial_inflight = 4096
@@ -42,6 +42,7 @@ lr = 1e-6
[orchestrator]
batch_size = 512
group_size = 8
max_off_policy_steps = 8
[orchestrator.concurrency]
+1
View File
@@ -43,6 +43,7 @@ lr = 1e-6
[orchestrator]
batch_size = 512
group_size = 8
max_off_policy_steps = 16
[orchestrator.concurrency]
+1 -1
View File
@@ -10,7 +10,7 @@ dependencies = [
"renderers>=0.1.11",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.3.0",
"verifiers>=0.3.2.dev143",
]
[build-system]
@@ -5,7 +5,7 @@ from pydantic import AliasChoices, Field, model_validator
from prime_rl.configs.monitors import EvalMonitorsConfig, MonitorsConfig
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
from prime_rl.configs.shared import ClientConfig, LogConfig, RunConfig
from prime_rl.configs.shared import ClientConfig, HeartbeatConfig, LogConfig, RunConfig
from prime_rl.configs.trainer import WeightBroadcastConfig
from prime_rl.utils.config import default_output_dir
@@ -21,6 +21,18 @@ class ServedEvalConfig(EvalSourcesConfig):
"""Adaptive in-flight episode concurrency, sized by the same controller as
``[orchestrator.concurrency]``. Set ``min_inflight = max_inflight`` to pin it."""
tasks_per_minute: int | None = Field(None, ge=1)
"""Global rate limit on episode dispatch, in tasks per minute. Use it for
sandbox-backed environments to pace provisioning during autoscaling. None disables
rate limiting."""
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat for the run: one ping per landed episode — the first
landed episode is the first beat, so the run's boot never shows up as a
stale-prone silence. When episodes stop landing, the pings stop and the heartbeat
goes stale on Better Stack after its grace period. Size that period + grace above
the longest legitimate gap between episodes."""
@property
def env_addresses(self) -> dict[tuple[str, str], str | None]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
@@ -132,6 +132,12 @@ class VllmConfig(BaseConfig):
enable_eplb: bool = False
"""Enable expert parallel load balancer (EPLB)."""
enable_ep_weight_filter: bool = True
"""Skip non-local expert weights at load time under expert parallelism, so each
rank reads only its own expert shard from disk. No-op for non-MoE models, when
expert parallelism is disabled, or under EPLB (redundant expert slots need all
logical expert weights)."""
enable_dbo: bool = False
"""Enable dual batch overlap (DBO)."""
@@ -305,6 +311,9 @@ class VllmRouterConfig(BaseConfig):
type: Literal["vllm-router"] = "vllm-router"
request_timeout_secs: int = Field(14400, ge=1)
"""Maximum lifetime of a routed request, including streamed completions."""
policy: str = "sticky_least_loaded"
"""Routing policy. Defaults to session-affine least-loaded routing; alternatives include ``consistent_hash`` and ``round_robin``."""
@@ -464,7 +473,7 @@ class InferenceConfig(BaseConfig):
"""Return per-token sampling masks (``sampling_mask``) on ``/inference/v1/generate`` responses via vLLM's native ``--return-sampling-mask`` (>= 0.28). The ``rl`` entrypoint enables this field for truncated policy sampling. Standalone inference must set it explicitly because no orchestrator sampling config is available. The field persists into per-node configs and selects the V2 model runner before vLLM starts. Capture is engine-wide: vLLM rejects requests with ``temperature <= 0`` or without ``top_k > 0`` while it is on."""
enable_fp32_lm_head: bool = True
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented natively by vLLM's LogitsProcessor, which reads ``head_dtype`` off the HF config, so this flag injects ``hf_overrides = {"head_dtype": "float32"}``."""
enable_fp32_router_logits: bool = True
"""Emit fp32 MoE router logits: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented natively by vLLM, which reads ``moe_router_dtype`` off the HF config — this flag injects ``hf_overrides = {"moe_router_dtype": "float32"}`` (GLM-5.x gets fp32 routing regardless)."""
@@ -638,6 +647,13 @@ class InferenceConfig(BaseConfig):
hf_overrides.setdefault("moe_router_dtype", "float32")
namespace.hf_overrides = hf_overrides
# vLLM's LogitsProcessor reads `head_dtype` off the HF config to pick the
# lm_head projection dtype (fp32 runs as a native bf16xbf16 -> fp32 GEMM).
if self.enable_fp32_lm_head:
hf_overrides = getattr(namespace, "hf_overrides", None) or {}
hf_overrides.setdefault("head_dtype", "float32")
namespace.hf_overrides = hf_overrides
if self.enable_return_sampling_mask:
namespace.return_sampling_mask = True
@@ -645,12 +661,4 @@ class InferenceConfig(BaseConfig):
if kv_transfer_config is not None:
namespace.kv_transfer_config = kv_transfer_config
# Pass prime-rl-specific flags through vLLM's additional_config dict;
# workers read these via get_current_vllm_config().additional_config.
additional_config = getattr(namespace, "additional_config", None) or {}
if self.enable_fp32_lm_head:
additional_config["fp32_lm_head"] = True
if additional_config:
namespace.additional_config = additional_config
return namespace
@@ -3,7 +3,7 @@ from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
import verifiers.v1 as vf
from pydantic import Field, SerializeAsAny, model_validator
from pydantic import Field, SerializeAsAny, ValidationError, model_validator
from renderers import AutoRendererConfig, RendererConfig
from prime_rl.configs.algorithm import (
@@ -166,6 +166,9 @@ class EnvConfig(BaseConfig):
name: str | None = None
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
shuffle: bool = False
"""Shuffle the source's finite taskset once with a fixed seed. The shuffled order is fixed for the whole run; infinite tasksets cannot be shuffled."""
@model_validator(mode="before")
@classmethod
def _resolve_env(cls, data):
@@ -191,6 +194,22 @@ class EnvConfig(BaseConfig):
return self
def merge_group_env(data: Any) -> Any:
"""Shared ``mode="before"`` body for source groups: layer the group's ``env`` block
under the ``env`` block of each raw source."""
if not isinstance(data, dict) or data.get("env") is None:
return data
try:
shared = vf.SharedEnvConfig.model_validate(data["env"])
except ValidationError:
return data # the ``env`` field reports the errors once, not once per source
data["source"] = [
{**source, "env": vf.merge_env_defaults(shared, source.get("env"))} if isinstance(source, dict) else source
for source in data.get("source") or []
]
return data
class StandardSamplerConfig(BaseConfig):
type: Literal["standard"] = "standard"
@@ -305,9 +324,18 @@ class TrainConfig(BaseConfig):
source: list[TrainSourceConfig] = Field(default_factory=list)
"""Training sources."""
env: vf.SharedEnvConfig = vf.SharedEnvConfig()
"""Env knobs that every training source inherits: the fields every env and taskset
has, such as ``retries`` and ``timeout``. A source's own ``env`` values win."""
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Shared training sampling configuration."""
@model_validator(mode="before")
@classmethod
def resolve_group_env(cls, data):
return merge_group_env(data)
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
@@ -338,6 +366,10 @@ class EvalSourcesConfig(BaseConfig):
source: list[EvalSourceConfig] = Field(default_factory=list)
"""Evaluation sources."""
env: vf.SharedEnvConfig = vf.SharedEnvConfig()
"""Env knobs that every eval source inherits: the fields every env and taskset
has, such as ``retries`` and ``timeout``. A source's own ``env`` values win."""
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
"""Shared eval sampling configuration; can differ from training sampling."""
@@ -347,6 +379,11 @@ class EvalSourcesConfig(BaseConfig):
group_size: int = Field(1, ge=1)
"""Default rollouts per example. Can be overridden per env."""
@model_validator(mode="before")
@classmethod
def resolve_group_env(cls, data):
return merge_group_env(data)
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling, num_examples and
@@ -91,6 +91,9 @@ class SFTDataConfig(BaseDataConfig):
name: str = "PrimeIntellect/Reverse-Text-SFT"
"""HF dataset name or path."""
revision: str | None = None
"""HF dataset revision to load. Ignored for a local path."""
subsets: list[str] | None = None
"""Subsets to load from the HF dataset."""
@@ -171,7 +171,7 @@ class DynamoConfig(BaseConfig):
class ClientConfig(BaseConfig):
wait_for_ready_timeout: int = 1800
wait_for_ready_timeout: int = 3600
"""Seconds to wait at startup for the inference pool to become ready."""
base_url: str = "http://localhost:8000/v1"
@@ -85,6 +85,9 @@ class CompileConfig(BaseConfig):
fullgraph: bool = False
"""Compile transformer blocks with ``fullgraph=True``."""
mode: Literal["reduce-overhead", "max-autotune", "max-autotune-no-cudagraphs", "lite"] | None = None
"""``torch.compile`` mode. ``reduce-overhead`` records CUDA graphs to cut kernel launch overhead; ``max-autotune`` modes trade longer compile times for tuned kernels (``max-autotune`` also records CUDA graphs, ``max-autotune-no-cudagraphs`` does not). CUDA-graphed layers re-record on new input shapes. ``None`` uses PyTorch's default mode."""
class FusionsConfig(BaseConfig):
enabled: list[Literal["gate_up", "qkv"]] = ["gate_up", "qkv"]
+19 -10
View File
@@ -29,7 +29,7 @@ dependencies = [
"rich>=14.0.0",
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"verifiers[harbor]>=0.3.1",
"verifiers[harbor]>=0.3.2.dev143",
"renderers[multimodal]>=0.1.12.dev2",
"pybase64>=1.4.2",
"orjson>=3.10",
@@ -56,7 +56,7 @@ gpu = [
"torchvision ; sys_platform == 'linux'",
"torchaudio ; sys_platform == 'linux'",
"torchdata>=0.11.0 ; sys_platform == 'linux'",
"vllm>=0.28.0 ; sys_platform == 'linux'",
"vllm>=0.29.0 ; sys_platform == 'linux'",
"mooncake-transfer-engine>=0.3.10.post2 ; sys_platform == 'linux'",
"ring-flash-attn>=0.1.8 ; sys_platform == 'linux'",
"torchtitan ; sys_platform == 'linux'",
@@ -146,7 +146,7 @@ override-dependencies = [
# Shared by vLLM, TileLang, and the pinned FlashAttention 4 runtime.
"apache-tvm-ffi==0.1.11",
"nvidia-cudnn-cu13>=9.15 ; sys_platform == 'linux'",
# vLLM 0.28.0 requires quack-kernels 0.6.4. It requires this exact CUTLASS version.
# vLLM 0.29.0 requires quack-kernels 0.6.4. It requires this exact CUTLASS version.
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
"nvidia-cutlass-dsl==4.6.2",
"transformers==5.6.2",
@@ -171,11 +171,14 @@ members = [
"deps/verifiers/environments/wiki_search",
"deps/verifiers/environments/wordle",
]
# tau2-synth and tau3-bench pin `tau2` forks/revs that conflict with the
# canonical tau2-bench; a workspace shares one lock, so these can't coexist.
# Tau tasksets require litellm<1.82.7, while Harbor requires litellm>=1.92.0.
# Apex pins a verifiers git revision instead of the editable workspace member.
# A workspace shares one lock, so these packages need separate environments.
exclude = [
"deps/prime-envs/environments/tool_use/tau2_bench",
"deps/prime-envs/environments/tool_use/tau2_synth",
"deps/prime-envs/environments/tool_use/tau3_bench",
"deps/prime-envs/environments/tool_use/apex_agents",
]
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
@@ -224,8 +227,6 @@ requires-dist = [
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
harbor = "2026-08-11T00:00:00Z"
# we want latest vllm, remove next patch
vllm = false
tokenspeed-mla = false
fastokens = false
flash_attn_3 = false
@@ -266,15 +267,15 @@ torchao = [
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
dion = { git = "https://github.com/samsja/dion.git", rev = "99e5f7e" }
dion = { git = "https://github.com/samsja/dion.git", rev = "6f9242d" }
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.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'" },
{ 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 == 'aarch64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
deep-ep = [
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
@@ -310,6 +311,14 @@ name = "pytorch-cu130-test"
url = "https://download.pytorch.org/whl/test/cu130"
explicit = true
# Environments Hub wheels carry no upload time, so the exclude-newer cooldown
# would reject every one of them. The Hub is first-party: skip the cutoff there.
[[tool.uv.index]]
name = "prime-hub"
url = "https://hub.primeintellect.ai/primeintellect/simple/"
explicit = true
exclude-newer = false
[tool.ruff.lint]
select = ["F", "I"]
+4 -1
View File
@@ -823,6 +823,8 @@ def message_text(message: dict) -> str:
def timeline_status(trace: dict) -> str:
if not trace.get("is_completed"):
return "running"
if trace.get("is_timeout"):
return "timeout"
if not trace.get("ok") and (trace.get("errors") or trace.get("stop_condition") == "error"):
return "failed"
return "completed"
@@ -1536,7 +1538,7 @@ def row_filter(
return False
if episode is not None and row.get("id") != episode:
return False
if errors_only and not (row.get("num_errors") or not row.get("ok")):
if errors_only and row.get("ok"):
return False
arrival = row.get("arrival") or 0
return not ((start is not None and arrival < start) or (end is not None and arrival >= end))
@@ -1822,6 +1824,7 @@ def episode_series(run: str, kind: str | None = None, etag: str | None = None, a
"ok",
"num_errors",
"truncated",
"timeout",
"stop_condition",
"duration",
"reward",
+119 -56
View File
@@ -423,7 +423,7 @@ function rowsChartHere() {
}
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 COMMON_REGEXES = ["effective/[^/]+/is_truncated/mean", "all/[^/]+/is_timeout/mean", "all/[^/]+/has_error/mean"];
const STABILITY_METRICS = ["optim/grad_norm", "entropy/all/mean", "mismatch_kl/all/mean", "kl_ent_ratio/mean"];
const PERFORMANCE_METRICS = ["perf/mfu", "time/step", "time/wait_for_batch", "time/wait_for_policy"];
const SFT_TRAIN_METRICS = ["loss/mean", "loss/perplexity", "val/loss", "val/perplexity", "progress/epoch"];
@@ -628,11 +628,11 @@ function evalProgressHtml(env, idx, live) {
cells =
idx
.map((i) => {
const err = series.ok?.[i] === false;
const mark = outcomeClass(series, i);
const reward = series.reward?.[i];
return (
`<span class="ep-cell done${err ? " err" : ""}" data-line="${series.line?.[i]}" ` +
`title="#${series.line?.[i]} · reward ${reward != null ? fmtReward(reward) : "n/a"}${err ? " · error" : ""}"></span>`
`<span class="ep-cell done ${mark}" data-line="${series.line?.[i]}" ` +
`title="#${series.line?.[i]} · reward ${reward != null ? fmtReward(reward) : "n/a"}${mark === "err" ? " · error" : mark === "timeout" ? " · timeout" : ""}"></span>`
);
})
.join("") +
@@ -745,7 +745,7 @@ function dotPlotSvg(entry, W, H) {
const col = Math.floor(j / perCol), rowN = j % perCol;
const cx = x0 + col * (2 * r + 1);
const cy = top + plotH - r - rowN * (2 * r + 1);
return `<circle data-i="${i}" class="${p.err ? "err" : ""}" cx="${cx.toFixed(1)}" cy="${cy.toFixed(1)}" r="${r}"></circle>`;
return `<circle data-i="${i}" class="${markClass(p)}" cx="${cx.toFixed(1)}" cy="${cy.toFixed(1)}" r="${r}"></circle>`;
})
.join("");
const n = counts.get(v);
@@ -829,7 +829,7 @@ function swarmSvg(entry, W, H) {
stacks.set(column, k + 1);
const offset = Math.ceil(k / 2) * d * (k % 2 ? -1 : 1);
const y = Math.max(r, Math.min(plotH - r, mid + offset));
return `<circle data-i="${i}" class="${points[i].err ? "err" : ""}" cx="${px.toFixed(1)}" cy="${y.toFixed(1)}" r="${r}"></circle>`;
return `<circle data-i="${i}" class="${markClass(points[i])}" cx="${px.toFixed(1)}" cy="${y.toFixed(1)}" r="${r}"></circle>`;
});
// the x axis: a baseline under the plot, round-valued ticks with grid lines
const label = (v) => tickLabel(v, entry.fmt);
@@ -868,6 +868,16 @@ function drawSwarms() {
const SWARM_STAT_ROWS = ["min", "p10", "median", "p90", "max"];
/* an episode's outcome mark: a timeout reads yellow, an error red, a clean one unmarked */
function outcomeClass(series, i) {
if (series.timeout?.[i] === true) return "timeout";
return series.ok?.[i] === false ? "err" : "";
}
function markClass(point) {
return point.timeout ? "timeout" : point.err ? "err" : "";
}
function swarmTipHtml(entry, point) {
const row = (k, v) => `<div class="tip-row"><span>${esc(k)}</span><span>${v}</span></div>`;
if (point) {
@@ -875,6 +885,7 @@ function swarmTipHtml(entry, point) {
? [row("rollouts", point.n), row(entry.label, entry.fmt(point.v))]
: [row(entry.label, entry.fmt(point.v)), ...(point.reward != null ? [row("reward", fmtReward(point.reward))] : [])];
if (point.err) rows.push(row("errors", point.group ? "in a rollout" : "yes"));
if (point.timeout) rows.push(row("timeout", point.group ? "in a rollout" : "yes"));
rows.push(row("", point.group ? "click opens its first rollout" : "click opens the trace"));
return `<div class="tip-head">${point.group ? `task ${esc(point.group.slice(0, 8))}` : `episode #${point.line}`}</div>${rows.join("")}`;
}
@@ -907,15 +918,16 @@ function evalScoreEntries(idx, filter) {
const reward = series.reward?.[i] ?? (series.ok?.[i] === false ? 0 : null);
if (reward == null) continue;
const task = series.group?.[i] ?? String(i);
if (!byTask.has(task)) byTask.set(task, { group: task, line: series.line?.[i], rewards: [], err: false });
if (!byTask.has(task)) byTask.set(task, { group: task, line: series.line?.[i], rewards: [], err: false, timeout: false });
const t = byTask.get(task);
t.rewards.push(reward);
if (series.ok?.[i] === false) t.err = true;
if (series.timeout?.[i] === true) t.timeout = true;
}
const tasks = [...byTask.values()];
if (!tasks.length) return entries;
const k = Math.max(...tasks.map((t) => t.rewards.length));
const taskPoint = (t, v) => ({ v, group: t.group, line: t.line, n: t.rewards.length, err: t.err });
const taskPoint = (t, v) => ({ v, group: t.group, line: t.line, n: t.rewards.length, err: t.err, timeout: t.timeout });
if (!filter || filter.test("avg@k"))
entries.push(swarmEntry("avg@k", `avg@${k}`, tasks.map((t) => taskPoint(t, t.rewards.reduce((a, b) => a + b, 0) / t.rewards.length)), fmtReward));
if ((!filter || filter.test("pass@k")) && tasks.every((t) => t.rewards.every((r) => r === 0 || r === 1))) {
@@ -1015,7 +1027,7 @@ function timingPaneHtml(idx) {
if (total == null) return null;
const parts = leaves.map((p) => ({ name: p.split("/").pop(), v: series[`timing/${p}`]?.[i] ?? 0 }));
parts.push({ name: "other", v: Math.max(0, total - parts.reduce((a, p) => a + p.v, 0)) });
return { i, line: series.line?.[i], err: series.ok?.[i] === false, total, parts };
return { i, line: series.line?.[i], err: series.ok?.[i] === false, timeout: series.timeout?.[i] === true, total, parts };
})
.filter(Boolean)
.sort((a, b) => b.total - a.total);
@@ -1037,7 +1049,7 @@ function tokensPaneHtml(idx) {
.map((i) => {
const input = series.input_tokens?.[i] ?? 0, output = series.output_tokens?.[i] ?? 0;
if (!input && !output) return null;
return { i, line: series.line?.[i], err: series.ok?.[i] === false, total: input + output, parts: [{ name: "input", v: input }, { name: "output", v: output }] };
return { i, line: series.line?.[i], err: series.ok?.[i] === false, timeout: series.timeout?.[i] === true, total: input + output, parts: [{ name: "input", v: input }, { name: "output", v: output }] };
})
.filter(Boolean)
.sort((a, b) => b.total - a.total);
@@ -1113,7 +1125,7 @@ function drawComposition(pane, model, { kind, fmt, time, color }) {
const t = tip(
`<div class="tip-head">episode #${r.line} · ${fmt(r.total)}</div>` +
parts.map((p) => rowTip(p.name, `${fmt(p.v)} · ${Math.round((p.v / (r.total || 1)) * 100)}%`)).join("") +
`${r.err ? rowTip("errors", "yes") : ""}${rowTip("", "click opens the trace")}`
`${r.err ? rowTip("errors", "yes") : ""}${r.timeout ? rowTip("timeout", "yes") : ""}${rowTip("", "click opens the trace")}`
);
const segs = parts
.map((p) => {
@@ -1126,7 +1138,7 @@ function drawComposition(pane, model, { kind, fmt, time, color }) {
.join("");
return (
`<rect class="tm-row-hit" data-tip="${t}" data-row="${n}" data-line="${r.line}" x="0" y="${y - GAP / 2}" width="${W}" height="${SH + GAP}"></rect>` +
`<text class="hax tm-line${r.err ? " err" : ""}" data-row="${n}" x="${PAD_L - 6}" y="${y + SH - 1}" style="text-anchor:end">#${r.line}</text>${segs}`
`<text class="hax tm-line ${markClass(r)}" data-row="${n}" x="${PAD_L - 6}" y="${y + SH - 1}" style="text-anchor:end">#${r.line}</text>${segs}`
);
})
.join("");
@@ -1174,13 +1186,19 @@ function summaryTilesHtml(idx, all, scoreEntries) {
const rows = entry.rows ?? SWARM_STAT_ROWS.map((k) => [k, entry.fmt(entry.stats[k])]);
tile(entry.label, entry.headline, `<div class="tip-head">${esc(entry.label)} · ${fmtCompact(entry.stats.n)} tasks</div>${rows.map(([k, v]) => rowTip(k, v)).join("")}`, { cls: " score" });
}
// failure rates count every landed episode, the errors filter notwithstanding
// failure rates count every landed episode, the errors filter notwithstanding;
// the timeout rate reads yellow as soon as any episode timed out
if (all.length) {
const errored = all.filter((i) => series.ok?.[i] === false || (series.num_errors?.[i] ?? 0) > 0).length;
const errored = all.filter((i) => series.ok?.[i] === false).length;
const truncated = all.filter((i) => (series.truncated?.[i] ?? TRUNCATING_STOPS.has(series.stop_condition?.[i])) === true).length;
for (const [label, n, what] of [["error rate", errored, "errored"], ["truncation rate", truncated, "truncated"]]) {
const timedOut = all.filter((i) => series.timeout?.[i] === true).length;
for (const [label, n, what, cls] of [
["error rate", errored, "errored", rateClass],
["truncation rate", truncated, "truncated", rateClass],
["timeout rate", timedOut, "timed out", (rate) => (rate > 0 ? " rate-timeout" : "")],
]) {
const rate = n / all.length;
tile(label, `${Math.round(rate * 100)}%`, `<div class="tip-head">${esc(label)}</div>${rowTip(what, `${n} of ${all.length} episodes`)}`, { cls: rateClass(rate) });
tile(label, `${Math.round(rate * 100)}%`, `<div class="tip-head">${esc(label)}</div>${rowTip(what, `${n} of ${all.length} episodes`)}`, { cls: cls(rate) });
}
}
const turns = distStats(idx.map((i) => series.turns?.[i]));
@@ -1236,6 +1254,7 @@ function renderEvalPane(body) {
line: series.line?.[i],
reward: series.reward?.[i],
err: series.ok?.[i] === false,
timeout: series.timeout?.[i] === true,
})),
fmt,
opts
@@ -3022,10 +3041,12 @@ function fmtSpan(dispatched, arrived, elapsed) {
}
function episodeRowHtml(ep) {
const failed = !ep.ok || !!ep.num_errors;
// an ok episode keeps the errors of the attempts it recovered from; they mark the
// row as retried, not as failed
const failed = !ep.ok;
const phase = failed ? "error" : "done";
const dispatched = ep.dispatch ?? (ep.arrival != null && ep.duration != null ? ep.arrival - ep.duration : null);
return `<tr data-line="${ep.line}" class="${failed ? "err" : ""}"${failed ? ` title="${ep.num_errors || 1} error${ep.num_errors === 1 ? "" : "s"}"` : ""}>
return `<tr data-line="${ep.line}" class="${episodeRowClass(ep)}" title="${esc(episodeRowTitle(ep))}">
<td class="muted">${ep.line}</td>
<td><span class="badge stage stage-${phase}">${phase}</span></td>
<td class="muted nowrap">${fmtSpan(dispatched, ep.arrival, ep.duration)}</td>
@@ -3209,7 +3230,7 @@ async function openLiveTrace(traceId, { refresh = false } = {}) {
semanticExpandedRuns.clear();
clearSemanticTranscriptOrigin();
$("#sg-inspector").hidden = true;
$("#tm-messages").innerHTML = `<div class="chart-empty">loading live trace…</div>`;
resetTranscript(`<div class="chart-empty">loading live trace…</div>`);
$("#tm-timeline").innerHTML = "";
$("#tm-meta").innerHTML = "";
}
@@ -3325,7 +3346,7 @@ function tmItemHtml(item) {
}
const e = item;
return (
`<div class="tm-item ${rolloutActive(item) ? "active" : ""}${e.num_errors || !e.ok ? " err" : ""}" data-line="${e.line}">` +
`<div class="tm-item ${rolloutActive(item) ? "active" : ""} ${episodeRowClass(e)}" data-line="${e.line}" title="${esc(episodeRowTitle(e))}">` +
`<span class="tm-num">#${e.line}</span><span class="tm-env muted" title="${esc(e.env ?? "")}">${esc(e.env ?? "")}</span>` +
`<span class="tm-reward ${rewardClass(e.reward)}">${fmtReward(e.reward)}</span></div>`
);
@@ -3426,7 +3447,7 @@ async function modalStep(delta) {
currentLine = null;
currentEpisode = null;
renderRolloutList();
$("#tm-messages").innerHTML = emptyState("no episodes", "this step has no rollouts for the current filters");
resetTranscript(emptyState("no episodes", "this step has no rollouts for the current filters"));
$("#tm-meta").innerHTML = "";
}
}
@@ -3474,6 +3495,15 @@ async function ensureTokens() {
currentEpisode = episode;
}
/* Every path that replaces the transcript with a placeholder goes through here, so the
previous episode's error strip never outlives its episode. */
function resetTranscript(html) {
const episodeErrors = $("#tm-episode-errors");
episodeErrors.hidden = true;
episodeErrors.innerHTML = "";
$("#tm-messages").innerHTML = html;
}
async function openEpisode(line, target = {}) {
currentLive = null;
$("#tm-live-label").textContent = "";
@@ -3486,7 +3516,7 @@ async function openEpisode(line, target = {}) {
currentEpisode = null;
renderModalStep();
renderRolloutList();
$("#tm-messages").innerHTML = `<div class="chart-empty">loading episode…</div>`;
resetTranscript(`<div class="chart-empty">loading episode…</div>`);
const timelineTarget = $("#tm-timeline");
timelineTarget.classList.remove("semantic-canvas");
delete timelineTarget.dataset.semanticEpisode;
@@ -3940,7 +3970,7 @@ function judgeEvidenceHtml(trace) {
function renderedTokensHtml(trace, branches) {
const rendered = trace.rendered_tokens;
const errors = errorBannersHtml(episodeErrors(currentEpisode, trace));
const errors = scopedErrorsHtml("trace", scopedErrors(currentEpisode, trace).trace);
if (!rendered) return errors + emptyState("rendered text not loaded", "select this view again to load recorded token IDs");
const path = currentPath(trace, branches);
const tokenCount = path.reduce((count, index) => count + (trace.nodes[index]?.token_ids?.length || 0), 0);
@@ -3980,43 +4010,70 @@ function renderedBoxHtml(tokenCount, body, canCopyText) {
let entriesObserver = null;
function episodeErrors(ep, trace) {
// one failure is often recorded twice, on the episode and on its trace; show it
// once, keeping whichever copy carries the traceback
const byMessage = new Map();
for (const error of [...(ep.errors || []), ...(trace?.errors || [])]) {
const record = error && typeof error === "object" ? error : { message: String(error) };
const key = `${record.type ?? "Error"}|${record.message ?? ""}`;
const kept = byMessage.get(key);
if (!kept || (!kept.traceback && record.traceback)) byMessage.set(key, record);
/* Errors carried by the episode and by the open trace, each split by what they mean.
Verifiers keeps every attempt's errors on the final record and stamps success as `ok`,
so the errors of an ok episode or trace are history it recovered from, while a failed
one's errors describe its outcome. A failure recorded on both the episode and its
trace shows once, as the trace's, keeping whichever copy carries the traceback. */
function scopedErrors(ep, trace) {
const record = (error) => (error && typeof error === "object" ? error : { message: String(error) });
const key = (r) => `${r.type ?? "Error"}|${r.message ?? ""}`;
const keep = (map, r) => {
const kept = map.get(key(r));
if (!kept || (!kept.traceback && r.traceback)) map.set(key(r), r);
};
const onTrace = new Map();
for (const error of trace?.errors || []) keep(onTrace, record(error));
const onEpisode = new Map();
for (const error of ep.errors || []) {
const r = record(error);
if (onTrace.has(key(r))) keep(onTrace, r);
else keep(onEpisode, r);
}
return [...byMessage.values()];
const split = (records, ok) => ({ failed: ok ? [] : records, recovered: ok ? records : [] });
return { episode: split([...onEpisode.values()], ep.ok), trace: split([...onTrace.values()], trace?.ok) };
}
function errorBannersHtml(errors) {
if (!errors.length) return "";
function errorEntryHtml(scope, record) {
const type = record.type ?? "Error";
const message = record.message ?? "No error message";
const traceback = Array.isArray(record.traceback) ? record.traceback.join("") : record.traceback;
return (
`<div class="trace-errors">` +
errors
.map((error) => {
const record = error && typeof error === "object" ? error : { message: String(error) };
const type = record.type ?? "Error";
const message = record.message ?? "No error message";
const traceback = Array.isArray(record.traceback) ? record.traceback.join("") : record.traceback;
return (
`<section class="trace-error-banner">` +
`<div class="trace-error-message"><span class="trace-error-type">${esc(type)}</span> ${esc(message)}</div>` +
(traceback
? `<details class="trace-error-tb"><summary><span>traceback</span><span class="entry-chev">›</span></summary><pre>${esc(traceback)}</pre></details>`
: "") +
`</section>`
);
})
.join("") +
`</div>`
`<div class="trace-error-message"><span class="trace-error-scope">${scope} error</span><span class="trace-error-type">${esc(type)}</span> ${esc(message)}</div>` +
(traceback
? `<details class="trace-error-tb"><summary><span>traceback</span><span class="entry-chev">›</span></summary><pre>${esc(traceback)}</pre></details>`
: "")
);
}
function scopedErrorsHtml(scope, { failed, recovered }) {
const banners = failed.length
? `<div class="trace-errors">${failed.map((record) => `<section class="trace-error-banner">${errorEntryHtml(scope, record)}</section>`).join("")}</div>`
: "";
const history = recovered.length
? `<details class="trace-recovered"><summary><span>recovered from ${recovered.length} ${scope} error${recovered.length === 1 ? "" : "s"} in earlier attempts</span><span class="entry-chev">›</span></summary>` +
recovered.map((record) => `<section class="trace-recovered-item">${errorEntryHtml(scope, record)}</section>`).join("") +
`</details>`
: "";
return banners + history;
}
function episodeRowClass(ep) {
if (ep.timeout) return "timeout";
if (!ep.ok) return "err";
return ep.num_errors ? "retried" : "";
}
function episodeRowTitle(ep) {
const n = ep.num_errors || 0;
const errors = `${n || 1} error${n === 1 ? "" : "s"}`;
const timeout = ep.timeout ? `timed out (${ep.stop_condition ?? "timeout"})` : "";
if (!ep.ok) return [timeout, errors].filter(Boolean).join(" · ");
if (timeout) return timeout;
return n ? `recovered from ${errors} in earlier attempts` : "";
}
function normalizedCallUsage(usage = {}) {
let input = usage.prompt_tokens;
let cached = usage.cached_input_tokens;
@@ -4036,7 +4093,7 @@ function normalizedCallUsage(usage = {}) {
function renderMessages(ep, trace, branches) {
const container = $("#tm-messages");
entriesObserver?.disconnect();
const errorsHtml = errorBannersHtml(episodeErrors(ep, trace));
const errorsHtml = scopedErrorsHtml("trace", scopedErrors(ep, trace).trace);
if (!trace) {
container.innerHTML = errorsHtml + emptyState("no traces", "this episode carries no trace data");
return;
@@ -4305,6 +4362,7 @@ function renderMeta(ep, trace, branches) {
parts.push(metaRow("stop_condition", trace.stop_condition));
parts.push(metaRow("is_completed", trace.is_completed));
parts.push(metaRow("is_truncated", traceTruncated(trace)));
parts.push(metaRow("is_timeout", !!trace.is_timeout));
parts.push(metaRow("ok", trace.ok));
const durations = [];
@@ -5487,12 +5545,17 @@ function renderEpisode() {
const trace = traces[currentTraceIdx];
const branches = trace ? traceBranches(trace) : [];
if (currentBranchIdx >= branches.length) currentBranchIdx = 0;
// the episode's own errors sit above the agent and branch selectors: they belong to
// the whole episode, not to whichever trace is open
const episodeErrors = $("#tm-episode-errors");
episodeErrors.innerHTML = scopedErrorsHtml("episode", scopedErrors(ep, trace).episode);
episodeErrors.hidden = !episodeErrors.innerHTML;
const traceTabs = $("#tm-trace-tabs");
traceTabs.hidden = traces.length <= 1;
traceTabs.innerHTML =
traces.length > 1
? traces
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}">${esc(trace.agent?.name || "agent")}</button>`)
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}${trace.is_timeout ? " timeout" : trace.ok ? "" : " err"}">${esc(trace.agent?.name || "agent")}</button>`)
.join("")
: "";
const branchTabs = $("#tm-branch-tabs");
@@ -6538,7 +6601,7 @@ async function reopenFirstEpisode() {
currentLine = null;
currentEpisode = null;
renderRolloutList();
$("#tm-messages").innerHTML = emptyState("no episodes", "nothing here for the current filters");
resetTranscript(emptyState("no episodes", "nothing here for the current filters"));
$("#tm-meta").innerHTML = "";
}
+1
View File
@@ -302,6 +302,7 @@
<button id="tm-expand" class="btn">expand</button>
<button id="drawer-close" class="btn">✕</button>
</div>
<div id="tm-episode-errors" hidden></div>
<div class="tm-head tm-tabs-row" id="tm-tabs-row" hidden>
<div id="tm-trace-tabs" class="seg" hidden></div>
<div id="tm-branch-tabs" class="seg" hidden></div>
+46 -1
View File
@@ -15,6 +15,7 @@
--accent: #b6ff3c;
--negative: #ff4539;
--timeout: #ffd166;
--positive: #b6ff3c;
--infra: #4a9eff;
--risk: #ff6b4a;
@@ -358,6 +359,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
.ep-cell { flex: 1; min-width: 0; background: var(--grey-2); border: 1px solid var(--hairline); }
.ep-cell.done { background: var(--accent); border-color: var(--accent); cursor: pointer; }
.ep-cell.done.err { background: var(--negative); border-color: var(--negative); }
.ep-cell.done.timeout { background: var(--timeout); border-color: var(--timeout); }
.ep-cell.done:hover { filter: brightness(1.2); }
.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; }
@@ -369,6 +371,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
.swarm .sw-bg { fill: transparent; }
.swarm circle { fill: var(--accent); fill-opacity: 0.7; cursor: pointer; }
.swarm circle.err { fill: var(--negative); }
.swarm circle.timeout { fill: var(--timeout); }
.swarm circle:hover { fill-opacity: 1; stroke: var(--grey-6); stroke-width: 1; }
.sw-axis { stroke: var(--grey-3); stroke-width: 1; }
.sw-grid { stroke: var(--hairline-faint); stroke-width: 1; }
@@ -392,6 +395,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
.tm-strip-seg.dim { opacity: 0.2; }
.tm-strip-seg:hover { filter: brightness(1.25); }
.tm-line.err { fill: var(--negative); }
.tm-line.timeout { fill: var(--timeout); }
.comp-pane [data-part].dim { opacity: 0.2; }
.comp-pane .tm-node.dim { opacity: 0.35; }
/* the summary is one row whatever the count: the tiles share the width equally */
@@ -401,6 +405,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
.sum-tile .stat-value { font-size: clamp(16px, 1.7vw, 24px); margin-top: 8px; }
.sum-tile.rate-warn .stat-value { color: #ffd166; }
.sum-tile.rate-bad .stat-value { color: var(--negative); }
.sum-tile.rate-timeout .stat-value { color: var(--timeout); }
.tm-note { font-size: 10px; margin-top: 4px; }
.tm-more { color: var(--grey-5); cursor: pointer; text-decoration: underline dotted; text-underline-offset: 3px; }
.tm-more:hover { color: var(--grey-6); }
@@ -834,6 +839,9 @@ mark.hit {
.tm-item.active { background: var(--grey-2); border-color: var(--grey-3); color: var(--grey-6); }
.tm-item.err { background: rgba(255, 69, 57, 0.08); border-color: var(--negative); }
.tm-item.err:hover, .tm-item.err.active { background: rgba(255, 69, 57, 0.16); }
.tm-item.timeout { background: rgba(255, 209, 102, 0.08); border-color: var(--timeout); }
.tm-item.timeout:hover, .tm-item.timeout.active { background: rgba(255, 209, 102, 0.16); }
.tm-item.retried { border-left: 2px dotted var(--grey-4); }
.tm-item .tm-reward { margin-left: auto; }
.tm-nav { padding: 0 8px; height: 24px; }
.tm-stephead { justify-content: space-between; background: var(--grey-2); min-height: 40px; }
@@ -935,6 +943,7 @@ mark.hit {
.tl-state { border: 1px solid var(--grey-3); padding: 1px 5px; white-space: nowrap; }
.tl-state.completed { color: var(--positive); }
.tl-state.failed { color: var(--negative); }
.tl-state.timeout { color: var(--timeout); }
.tl-state.running { color: var(--infra); }
.tl-tooltip {
position: fixed;
@@ -1169,7 +1178,7 @@ mark.hit {
#sg-open-transcript { margin: 0 12px 12px; min-height: 30px; }
/* the banners lead the transcript, so they stand off the first entry */
.trace-errors { margin-top: auto; padding-top: 12px; margin-bottom: 14px; }
.trace-errors { margin-top: auto; margin-bottom: 14px; }
.trace-error-banner {
border: 1px solid var(--negative);
background: rgba(255, 69, 57, 0.08);
@@ -1178,6 +1187,40 @@ mark.hit {
.trace-error-banner + .trace-error-banner { margin-top: 8px; }
.trace-error-message { padding: 10px 12px; font-size: 12px; white-space: pre-wrap; word-break: break-word; }
.trace-error-type { font-weight: 500; color: var(--negative); }
.trace-error-scope {
display: inline-block;
margin-right: 8px;
padding: 1px 6px;
border: 1px solid currentColor;
font-size: 9px;
line-height: 11px;
letter-spacing: var(--track-mono);
text-transform: uppercase;
color: var(--grey-4);
vertical-align: middle;
}
.trace-error-banner .trace-error-scope { color: var(--negative); }
#tm-episode-errors { padding: 12px 16px 0; border-bottom: 1px solid var(--hairline); }
#tm-episode-errors .trace-errors { margin-top: 0; margin-bottom: 12px; }
#tm-episode-errors .trace-recovered { margin-bottom: 12px; }
.trace-recovered { margin-bottom: 14px; border: 1px solid var(--grey-3); color: var(--grey-6); }
.trace-recovered > summary {
display: flex;
align-items: center;
gap: 10px;
padding: 6px 12px;
font-size: 11px;
color: var(--grey-4);
cursor: pointer;
list-style: none;
}
.trace-recovered > summary::-webkit-details-marker { display: none; }
.trace-recovered[open] > summary .entry-chev { transform: rotate(90deg); }
.trace-recovered-item { border-top: 1px solid var(--grey-3); }
.trace-recovered-item .trace-error-type { color: var(--grey-4); }
.trace-recovered-item .trace-error-tb > summary { border-top-color: var(--grey-3); }
.seg button.err, .seg button.err.active { color: var(--negative); }
.seg button.timeout, .seg button.timeout.active { color: var(--timeout); }
.trace-error-tb > summary {
display: flex;
align-items: center;
@@ -1697,6 +1740,8 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
place of their number set them apart */
.live-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); animation: live-pulse 2s ease-out infinite; }
#episode-table tr.err td:first-child { border-left: 2px solid var(--negative); }
#episode-table tr.timeout td:first-child { border-left: 2px solid var(--timeout); }
#episode-table tr.retried td:first-child { border-left: 2px dotted var(--grey-4); }
#episode-table tr.live.landing .live-dot { animation: none; opacity: 0.45; }
.badge.stage { font-size: 9px; padding: 2px 5px; line-height: 12px; border-radius: 3px; background: var(--hairline); border-color: transparent; color: var(--accent); }
#tm-live-label { margin-left: 8px; }
+5
View File
@@ -1,6 +1,7 @@
import os
import queue
import threading
import uuid
from functools import partial
from pathlib import Path
@@ -53,6 +54,10 @@ def run_server(config: EnvServerConfig):
def main():
"""Main entry-point for the env server. Run using `uv run env-server`"""
set_proc_title("EnvServer")
# verifiers keys run-scoped state (creation limiters) by $VF_RUN_ID. Every launcher,
# the Python entrypoints and the SLURM templates alike, hands env servers $PRL_RUN_ID;
# a standalone server is a run of its own.
os.environ.setdefault("VF_RUN_ID", os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex)
run_server(cli(EnvServerConfig))
+16 -9
View File
@@ -25,9 +25,10 @@ usage: uv run eval [<taskset-id>] [--env.<field> <value> ...] [-n N] [-r N] [-c
uv run eval @ eval.toml [options] multi-source runs ([[source]] blocks)
uv run eval @ eval.toml --run.name <name> --resume resume an interrupted run
Shorthands for a single-source run:
Shorthands:
<taskset-id> the taskset of the run's only source
--env.<field> <value> a field of that source's env block (e.g. --env.agent.harness.id bash)
--env.<field> <value> a field of that source's env block (e.g. --env.agent.harness.id bash); next to a
TOML with [[source]] blocks, a field of the shared env block (e.g. --env.retries.max-retries 3)
-c N pin the concurrency band (concurrency.min_inflight = max_inflight = N)
"""
@@ -46,17 +47,21 @@ def parse_value(raw: str) -> Any:
def expand_shorthands(argv: list[str]) -> list[str]:
"""Rewrite the single-source shorthands into flags ``EvalConfig`` parses.
"""Rewrite the shorthands into flags ``EvalConfig`` parses.
``<taskset-id>`` and ``--env.<path> <value>`` describe the run's only source and fold
into one JSON ``--source`` flag (pydantic-config has no list-index paths, so
``--source.0.env...`` cannot address it). ``-c N`` pins the concurrency band.
Everything else passes through untouched.
``--source.0.env...`` cannot address it). Next to a config file that defines
``[[source]]`` blocks, ``--env.*`` flags pass through to the shared ``env`` block.
``-c N`` pins the concurrency band. Everything else passes through untouched.
"""
out: list[str] = []
source: dict[str, Any] = {}
rest = list(argv)
if rest and not rest[0].startswith(("-", "@")):
positional = bool(rest) and not rest[0].startswith(("-", "@"))
sources_in_toml = any(toml_defines_source(path) for path in root_config_files(argv))
shared_env = sources_in_toml and not positional
if positional:
set_nested(source, ["env", "taskset", "id"], rest.pop(0))
i = 0
while i < len(rest):
@@ -67,7 +72,9 @@ def expand_shorthands(argv: list[str]) -> list[str]:
raise SystemExit(f"{flag} needs a value")
i += 1
value = rest[i]
if flag.startswith("--env."):
if flag.startswith("--env.") and shared_env:
out += [flag, value]
elif flag.startswith("--env."):
set_nested(source, [key.replace("-", "_") for key in flag[2:].split(".")], parse_value(value))
elif flag == "-c":
out += ["--concurrency.min_inflight", value, "--concurrency.max_inflight", value]
@@ -75,9 +82,9 @@ def expand_shorthands(argv: list[str]) -> list[str]:
out.append(arg)
i += 1
if source:
if any(toml_defines_source(path) for path in root_config_files(argv)):
if sources_in_toml:
raise SystemExit(
"The <taskset-id> / --env.* shorthands describe a single source and cannot be combined "
"The <taskset-id> shorthand describes a single source and cannot be combined "
"with a config file that defines [[source]] blocks - use one or the other"
)
out += ["--source", json.dumps([source])]
+2
View File
@@ -181,6 +181,8 @@ def start_router(config: InferenceConfig) -> subprocess.Popen:
str(config.vllm.data_parallel_size_local or config.vllm.data_parallel_size),
"--request-id-headers",
"x-session-id",
"--request-timeout-secs",
str(config.router.request_timeout_secs),
"--worker-startup-timeout-secs",
"4200",
"--prometheus-port",
+8 -5
View File
@@ -137,7 +137,7 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
def write_slurm_script(
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str | None = None
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str, wandb_shared: bool
) -> None:
"""Write the SLURM script to disk."""
from jinja2 import Environment, FileSystemLoader
@@ -210,6 +210,7 @@ def write_slurm_script(
gpus_per_node=config.deployment.gpus_per_node,
ranks_filter=",".join(map(str, config.log.ranks_filter)),
prl_run_id=prl_run_id,
wandb_shared=wandb_shared,
run_name=config.run.name,
online_eval=online_eval,
use_nccl_broadcast=(
@@ -249,16 +250,14 @@ def sft_slurm(config: SFTConfig):
write_config(config, config_path, exclude=exclude)
# Trainer and online-eval processes log to a single shared W&B run.
prl_run_id: str | None = None
if online_eval and config.monitors.wandb is not None:
prl_run_id = os.environ["PRL_RUN_ID"]
wandb_shared = online_eval and config.monitors.wandb is not None
launcher_dir = get_launcher_dir(config.run_dir)
if online_eval:
write_eval_subconfigs(config, config_dir, strip_router=True)
logger.info(f"Configs:\n{format_config_message(config_dir, 'sft', sft_config_components(config, config_dir))}")
script_path = launcher_dir / SFT_SBATCH
write_slurm_script(config, config_path, log_dir, script_path, prl_run_id)
write_slurm_script(config, config_path, log_dir, script_path, os.environ["PRL_RUN_ID"], wandb_shared)
logger.info(f"Wrote SLURM script to {script_path}")
num_nodes = config.deployment.num_train_nodes if config.deployment.type == "multi_node" else 1
@@ -544,8 +543,12 @@ def sft(config: SFTConfig):
if not config.dry_run:
from prime_rl.trainer.model import pre_download_model
from prime_rl.trainer.sft.data import pre_download_data
pre_download_model(config.model.name, skip_weights=config.model.debug.random_init)
pre_download_data(config.data, config.env_vars)
if config.val is not None:
pre_download_data(config.val.data, config.env_vars)
if config.slurm is not None:
sft_slurm(config)
-1
View File
@@ -27,7 +27,6 @@ class Eval:
landed: list[dict] = []
if config.resume:
# read and set aside before the monitors start: the resumed attempt writes a fresh stream
resume.check_config(resume.previous_config(config.run_dir), dump_resolved_config(config))
landed = resume.take_landed(config.run_dir)
get_logger().info(f"Initializing monitors ({config.monitors})")
await monitors.setup(
+4 -64
View File
@@ -8,16 +8,14 @@ ones the interruption cut off are owed again.
A landed episode counts toward the task with its ``task.key``, so a resumed run may
select more or fewer examples or rollouts per example than the interrupted one: the
kept episodes are matched to the new selection and the rest is owed. What defines the
measurement itself - the model, the sampling, each source's env - must not change
(``check_config``).
kept episodes are matched to the new selection and the rest is owed. The resumed
config is not checked against the interrupted one: any of it may be overridden.
"""
from __future__ import annotations
from collections import Counter, defaultdict
from collections.abc import Iterator
from fnmatch import fnmatch
from pathlib import Path
import orjson
@@ -28,29 +26,10 @@ from prime_rl.monitors.file.traces.chunks import chunk_numbers, open_chunk
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.utils.pathing import get_file_monitor_dir
RESUMABLE = (
"resume",
"clean",
"dry_run",
"dashboard",
"num_examples",
"group_size",
"concurrency",
"client",
"log",
"monitors",
"source.*.num_examples",
"source.*.group_size",
"source.*.serve",
)
"""Config paths a resumed run may change: how many rollouts to run and how to run them,
never what is measured."""
CONFIG_NAME = "eval.json"
"""The resolved config an attempt stamps into its file monitor directory once it is
running, beside the episodes it produces: a resume validates against the config those
episodes were measured with, never against an attempt that was rejected or dry."""
running, beside the episodes it produces, recording the config those episodes were
measured with."""
def stamp_config(run_dir: Path, config: dict) -> None:
@@ -59,45 +38,6 @@ def stamp_config(run_dir: Path, config: dict) -> None:
(directory / CONFIG_NAME).write_bytes(orjson.dumps(config, option=orjson.OPT_INDENT_2))
def previous_config(run_dir: Path) -> dict:
"""The config stamped beside the run's landed episodes: the current file monitor
directory's, else the newest archive's."""
for directory in [get_file_monitor_dir(run_dir), *reversed(archives(run_dir))]:
if (directory / CONFIG_NAME).is_file():
return orjson.loads((directory / CONFIG_NAME).read_bytes())
raise FileNotFoundError(f"Nothing to resume: {run_dir} holds no attempt that ran")
def config_diff(previous, current, prefix: str = "") -> list[str]:
"""Dotted paths at which two resolved configs differ (list items by index)."""
if isinstance(previous, dict) and isinstance(current, dict):
return [
path
for key in sorted(set(previous) | set(current))
for path in config_diff(previous.get(key), current.get(key), f"{prefix}.{key}" if prefix else key)
]
if isinstance(previous, list) and isinstance(current, list) and len(previous) == len(current):
return [
path
for index, (before, after) in enumerate(zip(previous, current, strict=True))
for path in config_diff(before, after, f"{prefix}.{index}")
]
return [] if previous == current else [prefix]
def check_config(previous: dict, current: dict) -> None:
changed = [
path
for path in config_diff(previous, current)
if not any(fnmatch(path, pattern) or fnmatch(path, f"{pattern}.*") for pattern in RESUMABLE)
]
if changed:
raise ValueError(
f"The run cannot resume with a different {', '.join(changed)} - the landed episodes would not "
"measure the same thing. Relaunch with --clean to start over."
)
def read_records(stream: Path) -> Iterator[dict]:
"""Every record of a trace stream, in order. A torn last line (the interrupted
process died mid-append) ends the stream."""
+15 -2
View File
@@ -45,6 +45,7 @@ from prime_rl.orchestrator.utils import (
intercept_vf_logging,
set_default_executor,
)
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import get_config_dir
@@ -71,11 +72,20 @@ class EvalRunner:
self.dispatcher: Dispatcher | None = None
self.inference_metrics: InferenceMetricsCollector | None = None
self.periodic_logger: PeriodicLogger | None = None
self.heart: Heartbeat | None = None
async def setup(self, *, skip_first_step: bool = False, is_resumed: bool = False) -> None:
config = self.config
set_default_executor()
# The heartbeat is beaten only by landed episodes — the first episode is its
# first beat. No startup ping on purpose: the run-start to first-episode gap
# (pool boot, env servers, the first episode's full duration) would otherwise
# sit inside the ping stream as an abnormally long silence and flip a healthy
# run stale. Until then the heartbeat has simply never been pinged.
if config.heartbeat is not None:
self.heart = Heartbeat(config.heartbeat.url)
# 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")
@@ -114,7 +124,7 @@ class EvalRunner:
progress=None,
initial_max_inflight=self.concurrency.max_inflight,
max_inflight_ceiling=config.concurrency.max_inflight,
tasks_per_minute=None,
tasks_per_minute=config.tasks_per_minute,
max_off_policy_steps=0,
run_id=self.run_id,
run_name=self.run_name,
@@ -224,6 +234,8 @@ class EvalRunner:
eval_batch = self.eval_sink.fail(item)
else:
stamp_arrival([item], "eval", eval_work(item).step)
if self.heart is not None:
self.heart.beat()
await self.land(item, pending)
continue
if eval_batch is not None:
@@ -291,7 +303,8 @@ class EvalRunner:
f"Evaluated {batch.env_name} (Step {batch.step}) | "
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%} | "
f"Timeout {full.is_timeout.mean():.1%}"
)
def collect_pipeline_view(self) -> tuple[str, dict[str, float]]:
+61 -114
View File
@@ -15,12 +15,12 @@ def apply_shared_vllm_patches():
_patch_lora_key_prefix()
_patch_qwen35_moe_lora_format()
monkey_patch_nano_v3_reasoning_parser()
monkey_patch_qwen3_coder_param_newline_trim()
monkey_patch_minimax_m2_think_end_passthrough()
monkey_patch_return_routed_experts_with_nixl_connector()
monkey_patch_kv_xfer_finished_tolerate_freed()
monkey_patch_online_fp8_parameter_cast()
monkey_patch_deepseek_v4_allowed_layer_types()
monkey_patch_deepseek_v4_request_tools_placement()
monkey_patch_deepseek_v4_per_layer_rope()
monkey_patch_deepseek_v4_bf16_o_proj()
@@ -42,6 +42,64 @@ def monkey_patch_deepseek_v4_allowed_layer_types():
allow_deepseek_v4_layer_types()
def monkey_patch_deepseek_v4_request_tools_placement():
"""Attach request-level tools to the first existing DSV4 system message.
vLLM 0.29.0's Python DeepSeek-V4 tokenizer always prepends a synthetic
system message for request-level tools. That puts the tool schema before
an existing system prompt, unlike DeepSeek's reference encoder, vLLM's
Rust renderer, and prime-rl's training renderer. Upstream fixed this in
https://github.com/vllm-project/vllm/pull/51856 (commit 2909ad8f).
The fix is expected to ship in vLLM 0.31.
Wrap the tokenizer factory so existing-system requests take the corrected
path through the stock implementation: shallow-copy the conversation,
attach tools to its first system message, and suppress the stock synthetic
insertion. Requests without a system message retain the stock behavior.
Remove this patch once the vLLM pin includes the upstream fix (likely 0.31).
"""
import copy
from vllm.tokenizers import deepseek_v4 as dsv4_tokenizer
original_get_tokenizer = dsv4_tokenizer.get_deepseek_v4_tokenizer
if getattr(original_get_tokenizer, "_prime_rl_places_request_tools", False):
return
def _get_deepseek_v4_tokenizer(tokenizer):
wrapped = original_get_tokenizer(tokenizer)
tokenizer_cls = wrapped.__class__
original_apply_chat_template = tokenizer_cls.apply_chat_template
# Each factory call creates a fresh dynamic tokenizer subclass, but be
# defensive if vLLM starts caching that class in a future release.
if getattr(original_apply_chat_template, "_prime_rl_places_request_tools", False):
return wrapped
def _apply_chat_template(self, messages, tools=None, **kwargs):
if tools:
conversation = kwargs.get("conversation", messages)
system_idx = next(
(i for i, message in enumerate(conversation) if message.get("role") == "system"),
None,
)
if system_idx is not None:
conversation = conversation.copy()
conversation[system_idx] = copy.copy(conversation[system_idx])
conversation[system_idx]["tools"] = tools
kwargs["conversation"] = conversation
tools = None
return original_apply_chat_template(self, messages, tools=tools, **kwargs)
_apply_chat_template._prime_rl_places_request_tools = True
tokenizer_cls.apply_chat_template = _apply_chat_template
return wrapped
_get_deepseek_v4_tokenizer._prime_rl_places_request_tools = True
dsv4_tokenizer.get_deepseek_v4_tokenizer = _get_deepseek_v4_tokenizer
def monkey_patch_online_fp8_parameter_cast():
"""Pass plain tensors to vLLM's compiled block-FP8 caster.
@@ -248,57 +306,6 @@ def monkey_patch_nano_v3_reasoning_parser():
ReasoningParserManager.register_module("nano_v3", module=NanoV3ReasoningParser)
def monkey_patch_qwen3_coder_param_newline_trim():
"""Restore vLLM 0.23's single-newline trim for qwen3_coder tool parameters.
vLLM 0.24's parser engine applies a full ``.strip()`` to every parameter
value in ``_qwen3_arg_converter``; 0.23's ``Qwen3CoderToolParser`` trimmed
exactly one leading and one trailing newline. A full strip corrupts
whitespace-significant string parameters (str_replace-style
``old_str``/``new_str``, file content with an indented first line, values
with intentional trailing newlines), silently changing tool execution and
rewards for agentic runs. Copy of ``_qwen3_arg_converter`` with only the
trim changed. Also covers ``nemotron_v3``, which reuses ``qwen3_config``.
"""
import json
from vllm.parser import qwen3
def _trim_one_newline(value: str) -> str:
if value.startswith("\n"):
value = value[1:]
if value.endswith("\n"):
value = value[:-1]
return value
def _patched_arg_converter(raw_args: str, partial: bool) -> str:
params: dict[str, object] = {}
for match in qwen3._PARAM_RE.finditer(raw_args):
name = match.group(1)
value = match.group(2)
## START PATCHED CODE (upstream: value.strip())
params[name] = _trim_one_newline(value)
## END PATCHED CODE
if partial:
remaining = qwen3._PARAM_RE.sub("", raw_args)
m = qwen3._PARTIAL_PARAM_RE.search(remaining)
if m:
name = m.group(1)
value = m.group(2)
if name:
## START PATCHED CODE (upstream: value.strip())
params[name] = _trim_one_newline(value)
## END PATCHED CODE
return json.dumps(params, ensure_ascii=False)
qwen3._qwen3_arg_converter = _patched_arg_converter
# qwen3_config captures the converter when first built; drop any cached configs.
qwen3.qwen3_config.cache_clear()
def monkey_patch_minimax_m2_think_end_passthrough():
"""Keep the literal ``</think>`` in MiniMax-M2 content on tool-calling turns.
@@ -757,68 +764,6 @@ def monkey_patch_no_moe_lora():
FusedMoEConfig.__post_init__ = _patched__post_init__
def monkey_patch_fp32_lm_head():
"""Run the lm_head projection in fp32, via a native bf16xbf16 -> fp32 GEMM.
Uses ``torch.mm(..., out_dtype=torch.float32)`` (PyTorch >= 2.10) so the
matmul accumulates and emits fp32 directly without zero-padding the bf16
operands or maintaining a separate fp32 weight copy. This avoids the
epilogue truncation to bf16 that `F.linear(bf16, bf16)` does, which is
where lm_head precision actually leaks before the sampler's softmax.
Activated by setting ``additional_config["fp32_lm_head"] = True`` on the
vLLM namespace; the launcher does this when ``inference.enable_fp32_lm_head``
is set. The flag is captured once on ``LogitsProcessor.__init__`` (where
vLLM guarantees a ``set_current_vllm_config()`` context) and stored on the
instance — reading it from ``_get_logits`` during serving doesn't work
because vLLM doesn't keep the context set during forwards.
Tracks vllm-project/vllm#24567 (which uses the operand-upcast approach).
Per @Jackmin801 on PR #2438, native ``out_dtype=fp32`` mm is more efficient
and just as correct.
"""
import torch
from vllm.config import get_current_vllm_config
from vllm.logger import init_logger
from vllm.model_executor.layers.logits_processor import LogitsProcessor
logger = init_logger(__name__)
_original_init = LogitsProcessor.__init__
_original_get_logits = LogitsProcessor._get_logits
def _patched_init(self, *args, **kwargs):
_original_init(self, *args, **kwargs)
vllm_config = get_current_vllm_config()
additional_config = vllm_config.additional_config or {}
self._fp32_lm_head_enabled = additional_config.get("fp32_lm_head", False)
if self._fp32_lm_head_enabled:
logger.warning("fp32 lm_head ENABLED for this LogitsProcessor instance.")
def _patched_get_logits(self, hidden_states, lm_head, embedding_bias):
if not getattr(self, "_fp32_lm_head_enabled", False):
return _original_get_logits(self, hidden_states, lm_head, embedding_bias)
# Native bf16xbf16 -> fp32 GEMM. torch.mm requires 2D inputs; vLLM v1's
# generative path passes 2D [num_tokens, hidden_size] hidden_states, but
# flatten defensively in case some future caller passes 3D.
flat = hidden_states.reshape(-1, hidden_states.shape[-1])
logits = torch.mm(flat, lm_head.weight.t(), out_dtype=torch.float32)
if embedding_bias is not None:
logits = logits + embedding_bias.to(torch.float32)
if hidden_states.dim() > 2:
logits = logits.reshape(*hidden_states.shape[:-1], -1)
logits = self._gather_logits(logits)
if logits is not None:
logits = logits[..., : self.org_vocab_size]
return logits
LogitsProcessor.__init__ = _patched_init
LogitsProcessor._get_logits = _patched_get_logits
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
def monkey_patch_dp_coordinator_startup_timeout():
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 120s.
@@ -935,6 +880,8 @@ def monkey_patch_deepseek_v4_per_layer_rope():
Note that nothing in vLLM's DeepSeek V4 calls the module's `forward`; every consumer reads
`cos_sin_cache` and hands it to a fused kernel. The class choice is therefore about the
cache's dtype and row count, not about which channels the module would rotate.
Remove this patch once the pin includes vllm-project/vllm#54815, which ships in 0.29.1.
"""
from vllm.models.deepseek_v4.common import rope as dsv4_rope
+10 -10
View File
@@ -6,10 +6,10 @@ from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
from starlette.datastructures import State
from vllm.engine.protocol import EngineClient
from vllm.entrypoints.openai.api_server import init_app_state
from vllm.entrypoints.openai.cli_args import make_arg_parser, validate_parsed_serve_args
from vllm.entrypoints.openai.engine.protocol import ErrorResponse
from vllm.entrypoints.launchers.api_server.app_state import init_app_state
from vllm.entrypoints.launchers.cli_args import make_arg_parser, validate_parsed_serve_args
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
from vllm.entrypoints.serve.lora.protocol import LoadLoRAAdapterRequest
from vllm.logger import init_logger
from vllm.utils.argparse_utils import FlexibleArgumentParser
@@ -26,7 +26,7 @@ from prime_rl.inference.patches import (
)
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
# Still needed in vLLM 0.28 — upstream rejects prompt_len > max_model_len - max_tokens
# Still needed in vLLM 0.29 — upstream rejects prompt_len > max_model_len - max_tokens
monkey_patch_tokenize_params_validation()
# NOTE: Register Nano V3 reasoning parser so configs can use
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
@@ -42,7 +42,7 @@ monkey_patch_strip_routed_experts_from_chat()
# weights concurrently (multi-node disaggregated deployments).
monkey_patch_dp_coordinator_startup_timeout()
logger = init_logger("vllm.entrypoints.openai.api_server")
logger = init_logger("vllm.entrypoints.launchers.api_server.entry")
# Create our own router for custom endpoints
router = APIRouter()
@@ -176,9 +176,9 @@ async def custom_init_app_state(
state.serving_tokens = prime_serving
import vllm.entrypoints.openai.api_server
import vllm.entrypoints.launchers.api_server.entry
import vllm.v1.utils
from vllm.entrypoints.openai.api_server import build_app as _original_build_app
from vllm.entrypoints.launchers.app import build_app as _original_build_app
from vllm.v1.utils import run_api_server_worker_proc as _original_run_api_server_worker_proc
@@ -201,8 +201,8 @@ def custom_run_api_server_worker_proc(listen_address, sock, args, client_config=
_original_run_api_server_worker_proc(listen_address, sock, args, client_config, **uvicorn_kwargs)
vllm.entrypoints.openai.api_server.init_app_state = custom_init_app_state
vllm.entrypoints.openai.api_server.build_app = custom_build_app
vllm.entrypoints.launchers.api_server.entry.init_app_state = custom_init_app_state
vllm.entrypoints.launchers.api_server.entry.build_app = custom_build_app
vllm.v1.utils.run_api_server_worker_proc = custom_run_api_server_worker_proc
@@ -213,7 +213,7 @@ def server(config: InferenceConfig):
import os
from vllm.entrypoints.cli.serve import run_headless, run_multi_api_server
from vllm.entrypoints.openai.api_server import run_server
from vllm.entrypoints.launchers.api_server.entry import run_server
# Signal worker processes to disable LoRA on MoE layers when LoRA targets don't include experts
lora_target_modules = config.vllm.lora_target_modules
+8 -37
View File
@@ -4,19 +4,11 @@ vLLM ships a generic tokens-in / tokens-out handler at
``vllm.entrypoints.scale_out.token_in_token_out.serving.ServingTokens`` that covers
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs,
priority, ``data_parallel_rank`` header routing, server-side ``max_tokens``
defaulting and ``usage`` reporting. We subclass it for the bits still missing
from the upstream handler:
1. Compact ``routed_experts`` export — when the engine emits routing
decisions, surface them as ``{data, shape, start, dtype}`` base64 raw-byte
objects (the form the PD router can merge and the renderers parse) instead
of upstream's single ``.npy`` base64 string.
2. ``kv_transfer_params`` bridging — upstream ``ServingTokens.serve_tokens``
parses ``request.kv_transfer_params`` but never threads it into the engine,
so PD disagg never fires on ``/inference/v1/generate``. Fixed upstream by
https://github.com/vllm-project/vllm/pull/42644, which missed the 0.28.0
cut — drop the bridge once we pin a release that includes it.
defaulting and ``usage`` reporting. We subclass it for the one bit still
missing from the upstream handler: compact ``routed_experts`` export — when the
engine emits routing decisions, surface them as ``{data, shape, start, dtype}``
base64 raw-byte objects (the form the PD router can merge and the renderers
parse) instead of upstream's single ``.npy`` base64 string.
Everything else (request/response schema, sampling params, error handling)
delegates to upstream so we track future vLLM changes for free.
@@ -27,17 +19,14 @@ from __future__ import annotations
from collections.abc import AsyncGenerator
from typing import Any
from fastapi import Request
from vllm.entrypoints.openai.engine.protocol import (
ErrorResponse,
RequestResponseMetadata,
)
from vllm.entrypoints.generate.base.protocol import RequestResponseMetadata
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
GenerateRequest,
GenerateResponse,
GenerateResponseChoice,
)
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
from vllm.outputs import RequestOutput
from prime_rl.inference.vllm.routed_experts import RoutedExpertsCapture
@@ -67,25 +56,7 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
class PrimeRlServingTokens(ServingTokens):
"""ServingTokens + compact routed experts + PD kv_transfer_params bridging."""
async def serve_tokens(
self,
request: GenerateRequest,
raw_request: Request | None = None,
) -> GenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
# Upstream parses ``request.kv_transfer_params`` but never threads it
# into the engine, so decode receives an empty NIXL handshake and
# re-prefills the prompt locally (~100x slower under concurrency).
# Bridge it through ``sampling_params.extra_args`` so the engine's KV
# connector picks the params up. Fixed upstream by vllm#42644 (merged
# after 0.28.0) — drop once we pin a release that includes it.
if request.kv_transfer_params is not None:
extra = request.sampling_params.extra_args or {}
extra["kv_transfer_params"] = request.kv_transfer_params
request.sampling_params.extra_args = extra
return await super().serve_tokens(request, raw_request)
"""ServingTokens + compact routed experts."""
async def serve_tokens_full_generator( # type: ignore[override]
self,
@@ -2,7 +2,6 @@ import logging
import os
from prime_rl.inference.patches import (
monkey_patch_fp32_lm_head,
monkey_patch_minimax_m2_for_lora,
monkey_patch_no_moe_lora,
)
@@ -17,6 +16,3 @@ if os.environ.get("PRIME_NO_MOE_LORA") == "1":
monkey_patch_no_moe_lora()
else:
logger.info("PRIME_NO_MOE_LORA=0: no patch applied")
# Install fp32 lm_head patch; self-gates on additional_config["fp32_lm_head"] at call time
monkey_patch_fp32_lm_head()
+6 -11
View File
@@ -50,9 +50,12 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
``line`` numbers the episode within the stream from 1, so the last of n reads as
n — it is what a reader sees and what addresses the episode."""
rewards, advantages = [], []
input_tokens = output_tokens = turns = branches = 0
input_tokens = rec.get("num_input_tokens")
output_tokens = rec.get("num_output_tokens")
turns = branches = 0
stop_condition = None
truncated = False
timeout = bool(rec.get("is_timeout"))
reward_parts: dict[str, list[float]] = {}
metric_parts: dict[str, list[float]] = {}
timing: dict[str, float] = {}
@@ -86,20 +89,11 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
if advantage is not None:
advantages.append(advantage)
for node in nodes:
n_tokens = len(node.get("token_ids") or [])
if node.get("sampled"):
output_tokens += n_tokens
else:
input_tokens += n_tokens
if (node.get("message") or {}).get("role") == "assistant":
turns += 1
stop_condition = trace.get("stop_condition", stop_condition)
truncated = truncated or trace_truncated(trace)
if input_tokens == 0 and output_tokens == 0: # some eval traces carry no token arrays
for call in trace.get("calls") or []:
usage = call.get("usage") or {}
input_tokens += usage.get("prompt_tokens") or 0
output_tokens += usage.get("completion_tokens") or 0
timeout = timeout or bool(trace.get("is_timeout"))
first_info = ((rec.get("traces") or [{}])[0].get("info")) or {}
return {
"rewards": {name: sum(v) / len(v) for name, v in reward_parts.items()},
@@ -125,6 +119,7 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
"branches": branches,
"stop_condition": stop_condition,
"truncated": truncated,
"timeout": timeout,
# when the episode landed and how long it was alive: the stream's x axis,
# and the one duration worth sorting a stream by
"dispatch": (first_info.get("dispatch") or {}).get("time"),
+12 -12
View File
@@ -176,31 +176,31 @@ def message_text(message: dict[str, Any]) -> str:
return ""
def trace_row(trace: dict[str, Any]) -> dict[str, Any]:
def trace_row(record: dict[str, Any]) -> dict[str, Any]:
"""The live table's view of one trace: phase, turns, tokens, cost, last message."""
calls = trace.get("calls") or []
calls = record.get("calls") or []
usage = [call.get("usage") or {} for call in calls]
# The newest node is usually a tool result; the assistant's latest words say more.
last = ""
for node in reversed(trace.get("nodes") or []):
for node in reversed(record.get("nodes") or []):
message = node.get("message") or {}
if message.get("role") == "assistant" and (last := " ".join(message_text(message).split())):
break
costs = [u["cost"] for u in usage if u.get("cost") is not None]
nodes = trace.get("nodes") or []
nodes = record.get("nodes") or []
parents = {node.get("parent") for node in nodes if node.get("parent") is not None}
return {
"trace": trace.get("id"),
"agent": (trace.get("agent") or {}).get("name", "agent"),
"stage": stage(trace),
"trace": record.get("id"),
"agent": (record.get("agent") or {}).get("name", "agent"),
"stage": stage(record),
"turns": len(calls),
"branches": sum(1 for index in range(len(nodes)) if index not in parents),
"input_tokens": sum(u.get("prompt_tokens") or 0 for u in usage),
"output_tokens": sum(u.get("completion_tokens") or 0 for u in usage),
"input_tokens": record.get("num_input_tokens"),
"output_tokens": record.get("num_output_tokens"),
"cost": sum(costs) if costs else None,
"stop_condition": trace.get("stop_condition"),
"errors": len(trace.get("errors") or []),
"pending": len(trace.get("pending") or []),
"stop_condition": record.get("stop_condition"),
"errors": len(record.get("errors") or []),
"pending": len(record.get("pending") or []),
"last": last[:SNIPPET_CHARS],
}
+22 -1
View File
@@ -19,6 +19,7 @@ if TYPE_CHECKING:
import verifiers.v1 as vf
BASE_URL_VAR = "PRIME_API_BASE"
EVAL_ID_VAR = "PRIME_RUNS_EVAL_ID"
# How long finish() and the SDK's atexit crash hook let queued uploads drain. The SDK
# default (300 s) is sized for eval sample batches; a crashed training process should
# not linger that long, and a clean finish rarely has more than the last step queued.
@@ -160,6 +161,12 @@ class PrimeEvalMonitor(Monitor):
# episodes do not retry the platform on every arrival
self.runs: dict[tuple[str, int], pr.Run | None] = {}
self._lock = asyncio.Lock()
self.evaluation_id = os.getenv(EVAL_ID_VAR)
if self.evaluation_id and len(self.sources) != 1:
raise ValueError(
f"${EVAL_ID_VAR} names one platform evaluation, so the run needs "
f"exactly one eval source (got {len(self.sources)})"
)
if self.mode == "online":
self.logger.info("Streaming eval epochs to the Prime platform")
if output_dir is not None:
@@ -172,6 +179,19 @@ class PrimeEvalMonitor(Monitor):
def open(self, env_name: str, step: int, expected: int | None) -> pr.Run:
"""Open the platform evaluation of one epoch. Blocking: runs in a worker thread."""
if self.evaluation_id:
# A hosted launch pre-created the platform evaluation and injected its id -
# attach instead of registering a duplicate. The backend owns its failure
# marking then; a clean finish still completes it.
if self.runs:
raise RuntimeError(f"${EVAL_ID_VAR} holds one epoch, and it already took one")
return pr.init(
kind="eval",
mode=self.mode,
base_url=_base_url(),
id=self.evaluation_id,
finish_timeout=FINISH_TIMEOUT,
)
source = self.sources[env_name]
name = self.config.name if len(self.sources) == 1 else f"{self.config.name}--{env_name}"
return pr.init(
@@ -206,7 +226,8 @@ class PrimeEvalMonitor(Monitor):
return None
self.runs[key] = run
if run.url:
self.logger.info(f"Streaming {env_name} (Step {step}) evaluation - {run.url}")
attached = f" (attached via ${EVAL_ID_VAR})" if run.attached else ""
self.logger.info(f"Streaming {env_name} (Step {step}) evaluation - {run.url}{attached}")
if self.output_dir is not None:
record = read_platform_record(self.output_dir) or {
"kind": "eval",
+1
View File
@@ -40,6 +40,7 @@ COMMON_METRICS = [
COMMON_REGEXES = [
"all/[^/]+/has_error/mean",
"effective/[^/]+/is_truncated/mean",
"all/[^/]+/is_timeout/mean",
]
STABILITY_METRICS = ["optim/grad_norm", "entropy/all/mean", "mismatch_kl/all/mean", "kl_ent_ratio/mean"]
+1 -1
View File
@@ -333,7 +333,7 @@ async def check_health(
admin_clients: list[AsyncClient],
interval: int = 1,
log_interval: int = 30,
timeout: int = 1800,
timeout: int = 3600,
quiet: bool = False,
) -> None:
"""Wait until every client's /health responds. With ``quiet``, the periodic
+9 -2
View File
@@ -670,9 +670,16 @@ class Dispatcher:
episode.errors.append(vf.Error(type="EmptyEpisode", message="Episode returned with no traces"))
for trace in episode.traces:
if not trace.has_error and trace.num_turns == 0:
if trace.is_timeout and not trace.has_error and meta.kind == "train":
# Training keeps a timed-out rollout out of the batch: an error,
# like any other failure. Eval keeps it as a scored outcome.
trace.errors.append(vf.Error(type="Timeout", message=f"Trace stopped by {trace.stop_condition}"))
trace.ok = False
episode.ok = False
if not trace.has_error and not trace.is_timeout and trace.num_turns == 0:
# Empty trajectory: promote to an explicit error so the sink
# treats it like any other failure (``has_error`` reads ``ok``)
# treats it like any other failure (``has_error`` reads ``ok``).
# A timed-out eval trace with no turns stays a timeout: scored, no samples.
trace.errors.append(vf.Error(type="EmptyTrajectory", message="Trace returned with no trajectory steps"))
trace.ok = False
episode.ok = False
+10
View File
@@ -20,6 +20,7 @@ keeps the env's task-specific fields as extras (``WireTaskData`` allows them).
from __future__ import annotations
import asyncio
import random
import time
from collections.abc import Callable, Iterator, Sequence
from itertools import islice
@@ -40,6 +41,11 @@ from prime_rl.utils.pathing import env_address_file
# before serving.
ENV_SERVER_STARTUP_TIMEOUT = 600.0
# Fixed seed for shuffle=True sources: the finite taskset is shuffled once at
# startup and the shuffled order is fixed for the whole run (train curricula and
# eval selection both consume it).
TASKSET_SHUFFLE_SEED = 42
async def wait_for_address(path: Path, timeout: float) -> str:
"""The address a launcher-managed env server published, polling for the file the
@@ -98,11 +104,15 @@ class Env:
await self.env_client.wait_for_server_startup(timeout=ENV_SERVER_STARTUP_TIMEOUT)
taskset = vf.load_taskset(self.config.env.taskset)
if type(taskset).INFINITE:
if self.config.shuffle:
raise ValueError(f"Env {self.name} has an infinite taskset — cannot shuffle it")
self.tasks = iter(taskset)
self.num_tasks = None
else:
# Materialize off the event loop — iterating may pull a dataset.
materialized = await asyncio.to_thread(lambda: list(taskset))
if self.config.shuffle:
random.Random(TASKSET_SHUFFLE_SEED).shuffle(materialized)
self.tasks = iter(materialized)
self.num_tasks = len(materialized)
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
+5 -1
View File
@@ -197,7 +197,7 @@ class TraceMetrics(StatGroup):
"num_turns",
"num_branches",
)
RATES = ("is_truncated", "is_completed")
RATES = ("is_truncated", "is_timeout", "is_completed")
def stats(self) -> dict[str, Stat]:
return {
@@ -321,6 +321,10 @@ class EpisodeMetrics:
def is_truncated(self) -> Stat:
return Stat([float(record.trace.is_truncated) for record in self.records])
@property
def is_timeout(self) -> Stat:
return Stat([float(record.trace.is_timeout) for record in self.records])
@property
def has_error(self) -> Stat:
return Stat(
+12 -25
View File
@@ -89,9 +89,6 @@ monkey_patch_chat_completion_logprobs()
# shutdown wedges (env-server ZMQ recv, vLLM admin aclose, etc)
SHUTDOWN_TIMEOUT_S = 300
# Abort after this many consecutive train batches contain no samples.
MAX_CONSECUTIVE_EMPTY_BATCHES = 10
# Maximum batches the orchestrator may run ahead of the trainer. The
# dispatcher is paused via ``update_dispatch_gate`` once this is exceeded;
# resumed when the watcher advances ``policy.version``.
@@ -111,7 +108,6 @@ class Orchestrator:
stopped: asyncio.Event
draining: bool
last_batch_at: float | None
consecutive_empty_batches: int
eval_triggered_at: dict[tuple[str, int], float]
ckpt_manager: CheckpointManager
component_tasks: list[asyncio.Task]
@@ -161,7 +157,6 @@ class Orchestrator:
self.last_batch_at = None
# Trigger timestamps so eval success logs can report epoch duration
self.eval_triggered_at = {}
self.consecutive_empty_batches = 0
self.gate_closed_at = None
# Pulsed after inference applies a policy so held work can re-check it.
self.version_advanced = asyncio.Event()
@@ -437,6 +432,13 @@ class Orchestrator:
clean_exit = True
finally:
elapsed = format_time(time.perf_counter() - start_time)
# ``progress.step`` points at the next (unshipped) step; the last finished step is
# ``progress.step - 1``. Checkpoint it as ``step_{progress.step - 1}`` (no-op before the
# first ship). Saved before finalize, which tells the launcher the run is done.
if self.config.ckpt is not None and self.progress.step > 1:
self.progress.step -= 1
get_logger().info(f"Saving final checkpoint at step {self.progress.step}")
self.ckpt_manager.save(self.progress, self.train_source, step=self.progress.step)
if clean_exit:
get_logger().success(f"Orchestrator step loop done in {elapsed}")
# The background loggers write through the monitors, so they must
@@ -450,13 +452,6 @@ class Orchestrator:
await monitors.finalize()
else:
get_logger().warning(f"Orchestrator interrupted after {elapsed} — forcing cleanup (not a clean exit)")
# ``progress.step`` points at the next (unshipped) step; the last finished step is
# ``progress.step - 1``. Checkpoint it as ``step_{progress.step - 1}`` (no-op before the
# first ship).
if self.config.ckpt is not None and self.progress.step > 1:
self.progress.step -= 1
get_logger().info(f"Saving final checkpoint at step {self.progress.step}")
self.ckpt_manager.save(self.progress, self.train_source, step=self.progress.step)
await self.stop()
if clean_exit:
get_logger().success("Orchestrator finished")
@@ -597,19 +592,10 @@ class Orchestrator:
return
if not batch.samples:
self.consecutive_empty_batches += 1
get_logger().warning(
f"Step {step}: empty train batch after {len(batch.episodes)} finalized episodes "
f"(consecutive empty batches: "
f"{self.consecutive_empty_batches}/{MAX_CONSECUTIVE_EMPTY_BATCHES})"
f"Step {step}: skipping empty train batch after {len(batch.episodes)} finalized episodes"
)
if self.consecutive_empty_batches >= MAX_CONSECUTIVE_EMPTY_BATCHES:
raise RuntimeError(
f"{self.consecutive_empty_batches} consecutive empty train batches — "
"check algorithm credit and task difficulty."
)
return
self.consecutive_empty_batches = 0
effective = batch.cohort.effective
n_trainable = sum(is_trainable(record.trace) for record in effective.records)
if effective.num_traces and n_trainable / effective.num_traces <= 0.1:
@@ -897,7 +883,7 @@ class Orchestrator:
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Max Off-Policy {max_off_policy_steps} | "
f"Error {episodes.metrics.has_error.mean():.1%} | Cancelled {episodes.metrics.cancelled.mean():.1%} | "
f"Truncation {eff.is_truncated.mean():.1%}"
f"Truncation {eff.is_truncated.mean():.1%} | Timeout {episodes.metrics.is_timeout.mean():.1%}"
)
if len(self.train_envs) <= 1:
get_logger().success(head)
@@ -918,7 +904,7 @@ class Orchestrator:
f"Turns {env_eff.num_turns.mean():.1f} | Branches {env_eff.num_branches.mean():.1f} | "
f"Max Off-Policy {max((episode_staleness(episode, step)[0] for episode in env_eff_pool), default=0)} | "
f"Error {pool.metrics.has_error.mean():.1%} | Cancelled {pool.metrics.cancelled.mean():.1%} | "
f"Truncation {env_eff.is_truncated.mean():.1%}"
f"Truncation {env_eff.is_truncated.mean():.1%} | Timeout {pool.metrics.is_timeout.mean():.1%}"
)
get_logger().success("\n\t\t ".join(lines))
@@ -966,7 +952,8 @@ class Orchestrator:
f"Evaluated {batch.env_name} | "
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%} | "
f"Timeout {full.is_timeout.mean():.1%}"
)
async def maybe_save_ckpt(self, step: int) -> float:
+9 -14
View File
@@ -25,8 +25,6 @@ from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, min_
from prime_rl.transports.batch import TrainingSample
from prime_rl.utils.logger import get_logger
MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS = 10
def payload_tokens(samples: list[TrainingSample], trace: vf.Trace | None = None) -> int:
"""Token cost of one trainer-bound trace."""
@@ -315,9 +313,9 @@ class TrainSink:
self._drop_stale(samples_by_trace)
# A group's traces share one dispatch version, so the insertion sweep
# voids all or none of them. A fully-voided group shipped nothing —
# advance the zero-output budget instead of resetting it, or a stalled
# advance the zero-output tally instead of resetting it, or a stalled
# trainer plus a tight bound could void groups forever without ever
# tripping the abort.
# surfacing the warning.
if not any(trace_id in self.pending_batch for trace_id in samples_by_trace):
self._record_zero_output(group, [], n_owed)
return
@@ -333,7 +331,7 @@ class TrainSink:
def _record_zero_output(self, group: list[vf.Episode], survivors: list[vf.Trace], n_owed: int) -> None:
"""``n_owed`` counts the group's full episode budget (arrived +
cancelled), so dropped groups advance the zero-output budget at the
cancelled), so dropped groups advance the zero-output tally at the
same rate as fully-delivered ones."""
if self.batch_size is not None:
returned_traces = sum(len(episode.traces) for episode in group)
@@ -342,9 +340,12 @@ class TrainSink:
survivor_tokens = sum(trace.num_total_tokens for trace in survivors)
episode_tokens = sum(episode.num_total_tokens for episode in group)
self.zero_output_units += survivor_tokens or episode_tokens or self.config.seq_len * n_owed
self._check_zero_output_budget()
self._warn_zero_output()
def _check_zero_output_budget(self) -> None:
def _warn_zero_output(self) -> None:
"""Warn once per batch-equivalent of finalized units that shipped no
payload, so a run that produces no training signal stays visible in the
logs without aborting."""
target = self.batch_size if self.batch_size is not None else self.token_batch_size
assert target is not None
windows = self.zero_output_units // target
@@ -353,14 +354,8 @@ class TrainSink:
self.reported_zero_output_windows = windows
get_logger().warning(
f"No admitted train payload after {self.zero_output_units} finalized units "
f"(consecutive zero-output batch equivalents: "
f"{windows}/{MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS})"
f"({windows} zero-output batch equivalents)"
)
if windows >= MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS:
raise RuntimeError(
f"{windows} consecutive zero-output batch equivalents — "
"check the curriculum admission policy, task difficulty, and staleness drops."
)
def process_batch(self) -> TrainBatch:
items = list(self.pending_batch.items())
@@ -73,6 +73,7 @@ LLMD_EOF
echo "Starting $tag on $LOCAL_IP:$port" | tee "$log"
local -a cmd=(vllm-router --policy "$policy" --host 0.0.0.0 --port "$port"
--request-id-headers x-session-id
--request-timeout-secs {{ router.request_timeout_secs }}
--prometheus-port "$((port + 21000))"
--worker-startup-timeout-secs 4200 --log-level debug)
if [ "$mode" = pd ]; then
@@ -60,11 +60,11 @@ export EVAL_DONE=$LAUNCHER_DIR/.sft_eval_done_$SLURM_JOB_ID
mkdir -p "$LAUNCHER_DIR"
rm -f "$TRAINER_DONE"{% if online_eval %} "$EVAL_DONE"{% endif %}
{% if prl_run_id %}
# Trainer and online-eval log to one shared W&B run. The trainer creates the run,
# and the online-eval process finalizes it after the final epoch.
export PRL_RUN_ID={{ prl_run_id }}
export PRL_RUN_NAME={{ run_name }}
{% if wandb_shared %}
# Trainer and online-eval log to one shared W&B run. The trainer creates the run,
# and the online-eval process finalizes it after the final epoch.
export WANDB_RUN_ID=$PRL_RUN_ID
export WANDB_SHARED_MODE=1
export WANDB_SHARED_PRIMARY=trainer
@@ -32,6 +32,7 @@ MANDATORY_SAVE_NAMESPACES = frozenset({"deepep"})
MANDATORY_SAVE_OPERATIONS = frozenset(
{
"aten::topk",
"prime_rl::fp8_indexer",
"prime_rl::record_moe_routing_statistics",
}
)
@@ -268,8 +268,12 @@ class TorchTokenDispatcher(TokenDispatcherBase[TorchDispatchState]):
ep_degree = self.group.size()
with torch.no_grad():
num_tokens_per_expert_group = all_to_all_single_equal(num_tokens_per_expert, self.group)
input_splits = num_tokens_per_expert.view(ep_degree, -1).sum(dim=1)
output_splits = num_tokens_per_expert_group.view(ep_degree, -1).sum(dim=1)
input_splits, output_splits = torch.stack(
(
num_tokens_per_expert.view(ep_degree, -1).sum(dim=1),
num_tokens_per_expert_group.view(ep_degree, -1).sum(dim=1),
)
).cpu() # Transfer to CPU now once, so a2a can read this without sync
routed_input = self._dispatch_tokens(routed_input, output_splits, input_splits)
experts_per_rank = self.num_experts // ep_degree
+57 -20
View File
@@ -10,6 +10,7 @@ os.environ.setdefault("USE_HUB_KERNELS", "NO")
import torch
import torch._dynamo
import torch.distributed as dist
import torch.nn as nn
from huggingface_hub import snapshot_download
from jaxtyping import Int
@@ -240,38 +241,69 @@ def is_tt_moe_model(model: nn.Module) -> bool:
def get_load_balance_stats(
model: nn.Module, reset_stats: bool = True, try_to_avoid_padding_experts: bool = True
model: nn.Module,
group: dist.ProcessGroup | None = None,
) -> dict[str, Tensor | None]:
"""Compute routing stats after summing raw counts across the group, if given."""
per_layer_max_vio = []
per_layer_routing_confidence = []
language_model = get_language_model(model)
block_mlps = []
for transformer_block in language_model.layers:
# This is necessary for models that have mixed dense layers
block_mlp = getattr(transformer_block, "mlp", None)
if block_mlp is None or not hasattr(block_mlp, "tokens_per_expert"):
continue
tokens_per_expert: torch.Tensor = block_mlp.tokens_per_expert
if block_mlp is not None and hasattr(block_mlp, "tokens_per_expert"):
block_mlps.append(block_mlp)
if not block_mlps:
return {"max_vio": None, "routing_confidence": None}
layer_stats = [(block_mlp.tokens_per_expert, block_mlp.routing_confidence_sum) for block_mlp in block_mlps]
if group is not None:
sizes = [tokens_per_expert.numel() + 1 for tokens_per_expert, _ in layer_stats]
packed_stats = torch.cat(
[torch.cat((tokens_per_expert, confidence.reshape(1))) for tokens_per_expert, confidence in layer_stats]
)
dist.all_reduce(packed_stats, op=dist.ReduceOp.SUM, group=group)
layer_stats = [(stats[:-1], stats[-1]) for stats in packed_stats.split(sizes)]
for block_mlp, (tokens_per_expert, routing_confidence_sum) in zip(block_mlps, layer_stats):
num_routed_tokens = tokens_per_expert.sum() / block_mlp.router.top_k
if try_to_avoid_padding_experts:
tokens_per_expert = tokens_per_expert.sort(dim=0, descending=True).values[block_mlp.router.top_k :]
tokens_per_expert = tokens_per_expert.sort(dim=0, descending=True).values[block_mlp.router.top_k :]
balanced_load = tokens_per_expert.mean()
max_vio = (tokens_per_expert.max() - balanced_load) / balanced_load
per_layer_max_vio.append(max_vio.detach())
routing_confidence = block_mlp.routing_confidence_sum / num_routed_tokens
routing_confidence = routing_confidence_sum / num_routed_tokens
per_layer_routing_confidence.append(routing_confidence.detach())
if reset_stats:
block_mlp.tokens_per_expert.zero_()
block_mlp.routing_confidence_sum.zero_()
if len(per_layer_max_vio) == 0:
return {"max_vio": None, "routing_confidence": None}
block_mlp.tokens_per_expert.zero_()
block_mlp.routing_confidence_sum.zero_()
return {
"max_vio": torch.stack(per_layer_max_vio),
"routing_confidence": torch.stack(per_layer_routing_confidence),
}
def get_global_moe_stats(
model: nn.Module,
ep_group: dist.ProcessGroup | None,
dp_cp_group: dist.ProcessGroup,
) -> dict[str, Tensor]:
"""Reduce one microstep's routing stats across EP, then DP and CP ranks."""
stats = {}
for name, values in get_load_balance_stats(model, group=ep_group).items():
if values is None:
continue
value = values.max() if name == "max_vio" else values.mean()
if name == "max_vio":
dist.all_reduce(value, op=dist.ReduceOp.MAX, group=dp_cp_group)
else:
dist.all_reduce(value, op=dist.ReduceOp.SUM, group=dp_cp_group)
value /= dist.get_world_size(dp_cp_group)
stats[name] = value.to("cpu")
return stats
def get_model(
config: ModelConfig, device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.bfloat16
) -> nn.Module:
@@ -520,6 +552,8 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
reshard_after_forward=config.reshard_after_forward,
shard_placement_fn=shard_placement_fn,
)
# Keep the router reduction from waiting for the expert reduction's input buffer.
block_mlp.router.set_reduce_scatter_max_input_buffers(2)
fully_shard(
transformer_block,
@@ -833,8 +867,10 @@ def apply_compile(model: nn.Module, compile_config: CompileConfig):
language_model = get_language_model(model)
for layer_id in range(len(language_model.layers)):
# Doing it in-place avoids mangled fqn which can break checkpoint loading
language_model.layers[layer_id].compile(fullgraph=compile_config.fullgraph)
get_logger().info(f"Compiled {len(language_model.layers)} layers (fullgraph={compile_config.fullgraph})")
language_model.layers[layer_id].compile(fullgraph=compile_config.fullgraph, mode=compile_config.mode)
get_logger().info(
f"Compiled {len(language_model.layers)} layers (fullgraph={compile_config.fullgraph}, mode={compile_config.mode})"
)
def apply_quantization(model: nn.Module, config: ModelConfig) -> None:
@@ -850,9 +886,9 @@ def apply_quantization(model: nn.Module, config: ModelConfig) -> None:
replace_linear_with_fp8_blockwise_linear(model, ignore_modules=quant.ignore_patterns)
elif isinstance(quant, MXFP8Config):
capability = torch.cuda.get_device_capability()
if capability != (10, 0):
if capability[0] < 10:
raise ValueError(
f"MXFP8 quantization requires SM100 (Blackwell), but device is SM{capability[0]}{capability[1]}."
f"MXFP8 quantization requires Blackwell (SM100+), but device is SM{capability[0]}{capability[1]}."
)
replace_linear_with_mxfp8_linear(model, recipe=quant.recipe, ignore_modules=quant.ignore_patterns)
@@ -885,6 +921,7 @@ def _reset_runtime_moe_buffers(model: nn.Module) -> None:
for module in model.modules():
if isinstance(module, MoE) and module.tokens_per_expert.device.type != "meta":
module.tokens_per_expert.zero_()
module.routing_confidence_sum.zero_()
def _validate_flash_attn_4_installed() -> None:
@@ -910,14 +947,14 @@ def _validate_flash_attn_4_installed() -> None:
def resolve_auto_attn(config: ModelConfig) -> None:
"""Resolve ``attn='auto'`` to a concrete flash attention implementation based on GPU architecture.
FA4 on datacenter Blackwell (SM100), FA3 on Hopper (SM90), FA2 otherwise.
Workstation Blackwell GPUs (e.g. RTX PRO 6000, SM120) lack FA4 kernels and
can't run the Hopper-only FA3 kernels, so they fall back to FA2.
FA4 on datacenter Blackwell (SM10x/SM11x, e.g. B200, B300), FA3 on Hopper (SM90), FA2
otherwise. FA4 is built around the tcgen05/TMEM instructions of the SM10x/SM11x families.
Workstation Blackwell (SM12x, e.g. RTX PRO 6000) lacks them, so it gets FA2.
"""
if config.attn != "auto":
return
major, minor = torch.cuda.get_device_capability()
if (major, minor) == (10, 0):
if major in (10, 11):
resolved = "flash_attention_4"
elif major == 9:
resolved = "flash_attention_3"
@@ -51,7 +51,6 @@ layers), built from one `seq_lens` and carrying:
- `position_ids`: each token's position within its own document.
- `tok_doc_idx`: which document each token belongs to.
- `position_embeddings`: the RoPE tables, one per rope type, evaluated at `position_ids`.
- `window_indices`: for each query, the indices of the tokens its local window covers, causal
and clipped at document boundaries, with `IGNORE_SLOT` (-1) marking invalid/masked entries.
- `compression_layouts`: one `CompressionLayout` per compress rate in the architecture.
@@ -97,13 +96,11 @@ holds it once and shares it across rates.
Compression is only part of the story: every attention layer also reads a local sliding window of
the most recent tokens directly, and the compressed entries are how it reaches anything older.
That window is enumerated per document by `window_indices`, and every rotation in the block needs
`position_ids` together with the RoPE tables evaluated at them, `position_embeddings`. None of
those belongs to any single compress rate.
`position_ids`. Neither belongs to any single compress rate.
`PackedContext.build` takes `seq_lens` and derives every one of its fields from it. Nothing else is
an input, so a position that disagrees with a document boundary, a window slot that spans one, or a
RoPE table evaluated at positions other than the ones the causal thresholds count in, cannot be
constructed. It runs once per model forward.
an input, so a position that disagrees with a document boundary or a window slot that spans one
cannot be constructed. It runs once per model forward.
Context parallelism splits the queries across ranks and leaves everything else alone: every field
above has one entry per query token and so covers this rank's `n_queries` tokens, while
@@ -128,12 +125,14 @@ from dataclasses import dataclass
import torch
import torch.distributed as dist
import torch.distributed._functional_collectives as funcol
from torch import Tensor, nn
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
from prime_rl.trainer.models.deepseek_v4.hyperconnections import DeepseekV4UnweightedRMSNorm
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding, apply_rotary_pos_emb_interleaved
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT
from prime_rl.trainer.models.kernels.deepseek_v4.dsv4_rope import dsv4_q_norm_rope, dsv4_rope
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
from prime_rl.utils.cp import CPContext, gather_for_cp
@@ -234,13 +233,12 @@ class CompressionLayout:
class PackedContext:
"""Everything an attention layer needs to know about the packed row it is running on.
The window indices, the positions, the RoPE tables and the layouts all encode the same
document boundaries and are only correct together. As separate arguments they can contradict
each other: a window enumerated without document boundaries spans documents while a layout
does not, a sequence-global `position_ids` feeds `causal_threshold` a count that a
per-document `entry_local_idx` cannot be compared against, and a RoPE table evaluated at one
set of positions rotates queries the thresholds were not counted at. `build` derives every
field from one `seq_lens`, so none of those is reachable. It runs once per model forward.
The window indices, the positions and the layouts all encode the same document boundaries and
are only correct together. As separate arguments they can contradict each other: a window
enumerated without document boundaries spans documents while a layout does not, and a
sequence-global `position_ids` feeds `causal_threshold` a count that a per-document
`entry_local_idx` cannot be compared against. `build` derives every field from one `seq_lens`,
so neither is reachable. It runs once per model forward.
Context parallelism gives each rank a contiguous run of `n_queries` tokens to use as queries
and a full copy of the keys, so every field but `compression_layouts` has one entry per query
@@ -250,7 +248,6 @@ class PackedContext:
position_ids: Tensor # (1, n_queries) int64 - token position within its own document
tok_doc_idx: Tensor # (n_queries,) int64 - which document each query token belongs to
position_embeddings: dict[str, tuple[Tensor, Tensor]] # (cos, sin) keyed by rope type, at `position_ids`
window_indices: Tensor # (n_queries, sliding_window) int32 - global token per window slot, IGNORE_SLOT if unused
compression_layouts: dict[int, CompressionLayout] # keyed by compress rate
@@ -260,17 +257,14 @@ class PackedContext:
*,
rotary_emb: DeepseekV4RotaryEmbedding,
seq_lens: Tensor,
dtype: torch.dtype,
device: torch.device,
cp_rank: int = 0,
cp_world_size: int = 1,
) -> "PackedContext":
"""Derive every field from one `seq_lens`, ensuring mutual consistency.
`rotary_emb` supplies the RoPE tables and, through the config it was built from, the
sliding window and the compress rates in use. Taking the config from it rather than
alongside it keeps them from naming different architectures. `dtype` must be the dtype
attention runs at, since it types the RoPE tables. The sequence is as long as `seq_lens` says,
`rotary_emb` supplies the sliding window, the compress rates in use and the positions its
RoPE cache covers, all read from its config. The sequence is as long as `seq_lens` says,
padding included: both packers fold their padding into the last document.
`seq_lens` always describes the whole sequence. `cp_rank` and `cp_world_size` say which
@@ -283,6 +277,10 @@ class PackedContext:
assert total_tokens % cp_world_size == 0, (
f"{total_tokens} tokens do not split evenly across {cp_world_size} CP ranks"
)
# Document-local positions stay below the row's length; the RoPE kernels index the cache unchecked.
assert total_tokens <= config.max_position_embeddings, (
f"{total_tokens} tokens exceed the {config.max_position_embeddings} positions of the RoPE cache"
)
n_queries = total_tokens // cp_world_size
q_start = cp_rank * n_queries
@@ -300,9 +298,6 @@ class PackedContext:
# Document-local by construction: a token's position is its distance from its own
# document's start, which is what `causal_threshold` and the entry rotation count in.
position_ids = (tok_idx - cu_seqlens[tok_doc_idx])[None]
position_embeddings = {
rope_type: rotary_emb(position_ids, rope_type, dtype=dtype) for rope_type in rotary_emb.layer_types
}
# A token attends the last `sliding_window` positions (itself included), clipped to its own
# document.
@@ -313,7 +308,6 @@ class PackedContext:
return cls(
position_ids=position_ids,
tok_doc_idx=tok_doc_idx,
position_embeddings=position_embeddings,
compression_layouts={
rate: CompressionLayout.build(cu_seqlens=cu_seqlens, compress_rate=rate) for rate in compress_rates
},
@@ -398,8 +392,6 @@ class SparseAttnInputs:
# A surplus pick is `IGNORE_SLOT` (-1) and stays `IGNORE_SLOT`; a real one names an entry,
# which sits past the token stream in `kv_buf`, hence the shift by `n_tokens`.
# NOTE: the attention kernel recompiles for every unique `indices.shape[-1]` value. If
# recompilation becomes a bottleneck, consider padding to fixed length with `IGNORE_SLOT` values.
picks = torch.where(top_k_indices >= 0, top_k_indices + n_tokens, IGNORE_SLOT)
indices = torch.cat([window, picks[:, :, None, :].to(torch.int32)], dim=-1)
return cls(kv_buf=kv_buf, indices=indices)
@@ -427,7 +419,14 @@ class DeepseekV4Compressor(nn.Module):
rope_layer_type = "compress"
def __init__(self, config: DeepseekV4Config, head_dim: int, compress_rate: int, n_series: int):
def __init__(
self,
config: DeepseekV4Config,
head_dim: int,
compress_rate: int,
n_series: int,
rotary_emb: DeepseekV4RotaryEmbedding,
):
super().__init__()
if n_series not in (1, 2):
raise ValueError(f"n_series must be 1 or 2, got {n_series}")
@@ -438,7 +437,7 @@ class DeepseekV4Compressor(nn.Module):
self.gate_proj = nn.Linear(config.hidden_size, n_series * head_dim, bias=False)
self.position_bias = nn.Parameter(torch.zeros(compress_rate, n_series * head_dim))
self.kv_norm = RMSNorm(RMSNormConfig(hidden_size=head_dim, eps=config.rms_norm_eps))
self.rotary_emb = DeepseekV4RotaryEmbedding(config)
self.rotary_emb = rotary_emb
def _overlap_with_previous_window(
self, kv: torch.Tensor, gate: torch.Tensor, layout: CompressionLayout
@@ -468,7 +467,6 @@ class DeepseekV4Compressor(nn.Module):
cp_world_size: int = 1,
) -> torch.Tensor:
"""Compress `(batch, seq_len, hidden_size)` to `(batch, n_entries, head_dim)`."""
batch = hidden_states.shape[0]
layout = packed.compression_layouts[self.compress_rate]
width = self.n_series * self.head_dim
@@ -487,10 +485,8 @@ class DeepseekV4Compressor(nn.Module):
compressed = self.kv_norm((kv * weights).sum(dim=2))
entry_first_tok_pos = layout.entry_local_idx * self.compress_rate
cos, sin = self.rotary_emb(
entry_first_tok_pos.unsqueeze(0).expand(batch, -1), self.rope_layer_type, dtype=compressed.dtype
)
return apply_rotary_pos_emb_interleaved(compressed.unsqueeze(1), cos, sin).squeeze(1)
cos_sin_cache = self.rotary_emb.cos_sin_cache(self.rope_layer_type)
return dsv4_rope(compressed.unsqueeze(2), cos_sin_cache, entry_first_tok_pos).squeeze(2)
def causal_threshold(self, position_ids: torch.Tensor) -> torch.Tensor:
"""Number of compressed entries that query `t` may read, shaped like `position_ids`.
@@ -514,13 +510,17 @@ class DeepseekV4Indexer(nn.Module):
`IGNORE_SLOT` (-1).
"""
def __init__(self, config: DeepseekV4Config):
def __init__(self, config: DeepseekV4Config, rotary_emb: DeepseekV4RotaryEmbedding):
super().__init__()
self.head_dim = config.index_head_dim
self.num_heads = config.index_n_heads
self.index_topk = config.index_topk
self.compressor = DeepseekV4Compressor(
config, self.head_dim, config.compress_rates["compressed_sparse_attention"], n_series=2
config,
self.head_dim,
config.compress_rates["compressed_sparse_attention"],
n_series=2,
rotary_emb=rotary_emb,
)
self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False)
self.weights_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False)
@@ -539,9 +539,9 @@ class DeepseekV4Indexer(nn.Module):
compressed_kv = self.compressor.compress(hidden_states, packed, cp_group=cp_group, cp_world_size=cp_world_size)
n_entries = compressed_kv.shape[1]
cos, sin = packed.position_embeddings[self.compressor.rope_layer_type]
q = self.q_b_proj(q_residual).view(batch, seq_len, -1, self.head_dim).transpose(1, 2)
q = apply_rotary_pos_emb_interleaved(q, cos, sin).transpose(1, 2)
cos_sin_cache = self.compressor.rotary_emb.cos_sin_cache(self.compressor.rope_layer_type)
q = self.q_b_proj(q_residual).view(batch, seq_len, -1, self.head_dim)
q = dsv4_rope(q, cos_sin_cache, packed.position_ids)
w = self.weights_proj(hidden_states)
layout = packed.compression_layouts[self.compressor.compress_rate]
@@ -569,9 +569,15 @@ class DeepseekV4CSACompressor(DeepseekV4Compressor):
because the indexer only selects entries whose source tokens all lie at or before the query.
"""
def __init__(self, config: DeepseekV4Config):
super().__init__(config, config.head_dim, config.compress_rates["compressed_sparse_attention"], n_series=2)
self.indexer = DeepseekV4Indexer(config)
def __init__(self, config: DeepseekV4Config, rotary_emb: DeepseekV4RotaryEmbedding):
super().__init__(
config,
config.head_dim,
config.compress_rates["compressed_sparse_attention"],
n_series=2,
rotary_emb=rotary_emb,
)
self.indexer = DeepseekV4Indexer(config, rotary_emb)
def forward(
self,
@@ -603,8 +609,14 @@ class DeepseekV4HCACompressor(DeepseekV4Compressor):
the rest with `IGNORE_SLOT` (-1), as the indexer's surplus picks do.
"""
def __init__(self, config: DeepseekV4Config):
super().__init__(config, config.head_dim, config.compress_rates["heavily_compressed_attention"], n_series=1)
def __init__(self, config: DeepseekV4Config, rotary_emb: DeepseekV4RotaryEmbedding):
super().__init__(
config,
config.head_dim,
config.compress_rates["heavily_compressed_attention"],
n_series=1,
rotary_emb=rotary_emb,
)
def forward(
self,
@@ -654,7 +666,7 @@ class DeepseekV4Attention(nn.Module):
which is how a layer sees past the window.
"""
def __init__(self, config: DeepseekV4Config, layer_idx: int):
def __init__(self, config: DeepseekV4Config, layer_idx: int, rotary_emb: DeepseekV4RotaryEmbedding):
super().__init__()
self.config = config
self.layer_idx = layer_idx
@@ -671,7 +683,7 @@ class DeepseekV4Attention(nn.Module):
self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=False)
self.q_a_norm = RMSNorm(RMSNormConfig(hidden_size=config.q_lora_rank, eps=config.rms_norm_eps))
self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False)
self.q_b_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps)
self.q_b_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps, out_dtype=torch.float32)
self.kv_proj = nn.Linear(config.hidden_size, self.head_dim, bias=False)
self.kv_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
self.o_a_proj = DeepseekV4GroupedLinear(
@@ -681,6 +693,7 @@ class DeepseekV4Attention(nn.Module):
)
self.o_b_proj = nn.Linear(config.o_groups * config.o_lora_rank, config.hidden_size, bias=False)
self.sinks = nn.Parameter(torch.zeros(self.num_heads))
self.rotary_emb = rotary_emb
# Raised here rather than from the first forward, where it would surface as an ImportError
# or a tilelang compile failure a long way from the config that caused it.
blocker = _kernel_blocker(self.num_heads, self.head_dim)
@@ -688,7 +701,7 @@ class DeepseekV4Attention(nn.Module):
raise ValueError(f"DeepSeek V4 cannot run the fused sparse-attention kernel: {blocker}")
assert config.attention_dropout == 0.0, "the fused sparse attention kernel implements no dropout"
compressor_class = COMPRESSOR_CLASSES[self.layer_type]
self.compressor = compressor_class(config) if compressor_class is not None else None
self.compressor = compressor_class(config, rotary_emb) if compressor_class is not None else None
self.cp_context = CPContext()
@@ -710,19 +723,24 @@ class DeepseekV4Attention(nn.Module):
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim) # (b, t, h, d), the query view
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)
# 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)
cos_sin_cache = self.rotary_emb.cos_sin_cache(self.rope_layer_type) # (max_position, qk_rope_head_dim)
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)
kv = apply_rotary_pos_emb_interleaved(kv, cos, sin, unsqueeze_dim=2)
kv = dsv4_rope(kv, cos_sin_cache, packed.position_ids)
if self.cp_context.cp_enabled:
kv = gather_for_cp(kv, self.cp_context.cp_group) # (b, T, 1, d)
kv = kv.transpose(1, 2) # (b, 1, T, d)
# Launch on NCCL's communication stream; query/compressor work does not read KV.
kv = torch.ops._c10d_functional.all_gather_into_tensor(
kv.movedim(1, 0).contiguous(),
self.cp_context.cp_world_size,
self.cp_context.cp_group.group_name,
)
q_residual = self.q_a_norm(self.q_a_proj(hidden_states)) # (b, t, r)
# Keep the query in the sparse kernel's (batch, tokens, heads, dim) layout.
q = dsv4_q_norm_rope(
self.q_b_proj(q_residual).view(*hidden_shape), cos_sin_cache, packed.position_ids, self.q_b_norm.eps
) # (b, t, h, d)
compressed = (
self.compressor(
@@ -736,6 +754,9 @@ class DeepseekV4Attention(nn.Module):
else None
)
compressed_kv, top_k_indices = compressed if compressed is not None else (None, None)
if self.cp_context.cp_enabled:
kv = funcol.wait_tensor(kv).movedim(0, 1).contiguous() # (b, T, 1, d)
kv = kv.transpose(1, 2) # (b, 1, T, d)
inputs = SparseAttnInputs.build(
kv=kv,
compressed_kv=compressed_kv,
@@ -743,7 +764,7 @@ class DeepseekV4Attention(nn.Module):
window_indices=packed.window_indices,
)
attn_output, _ = dsv4_sparse_attn(
q.transpose(1, 2).contiguous(),
q,
inputs.kv_buf,
inputs.indices,
self.sinks,
@@ -752,7 +773,7 @@ class DeepseekV4Attention(nn.Module):
# The value stream is the key stream, so it arrived rotated. Rotating the output
# by the conjugate angle at the query position cancels that out.
attn_output = apply_rotary_pos_emb_interleaved(attn_output, cos, -sin, unsqueeze_dim=2)
attn_output = dsv4_rope(attn_output, cos_sin_cache, packed.position_ids, inverse=True)
# (b, t, g, h * d // g) -> (b, t, g, l) -> (b, t, g * l)
grouped = self.o_a_proj(attn_output.reshape(*input_shape, self.config.o_groups, -1)).flatten(2)
@@ -14,7 +14,43 @@ from torch import Tensor, nn
from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext, SparseAttnInputs
from prime_rl.trainer.models.deepseek_v4.rotary import apply_rotary_pos_emb_interleaved
def rotate_half_interleaved(x: torch.Tensor) -> torch.Tensor:
"""Rotate consecutive channel pairs: `(x0, x1, x2, x3, ...) -> (-x1, x0, -x3, x2, ...)`.
Not the same as `prime_rl.trainer.models.layers.rotary_emb.rotate_half`, which pairs
channel `i` with channel `i + dim / 2` (the GPT-NeoX layout). DeepSeek-V4 stores each
rotary pair adjacently, so the two are not interchangeable.
"""
x1 = x[..., 0::2]
x2 = x[..., 1::2]
return torch.stack((-x2, x1), dim=-1).flatten(-2)
def apply_rotary_pos_emb_interleaved(
x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, unsqueeze_dim: int = 1
) -> torch.Tensor:
"""Apply interleaved RoPE to the trailing rotary slice of `x`.
`cos` and `sin` arrive at half width (one entry per interleaved pair) and are widened
with `repeat_interleave`. Each head is laid out as `[nope | rope]`, so only the last
`2 * cos.shape[-1]` channels rotate and the leading ones pass through untouched.
The rotation itself runs in fp32 and is cast back to `x`'s dtype.
Args:
x: Tensor whose last dimension is the head dimension.
cos: Half-width cosines, shape `(batch, seq, rope_dim / 2)`.
sin: Half-width sines, same shape as `cos`.
unsqueeze_dim: Axis of `x` that `cos` / `sin` must broadcast over. Use `1` for a
`(batch, heads, seq, head_dim)` layout and `2` for `(batch, seq, heads, head_dim)`.
"""
cos = cos.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim)
sin = sin.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim)
rope_dim = cos.shape[-1]
nope, rope = x[..., :-rope_dim], x[..., -rope_dim:]
rotated = ((rope.float() * cos) + (rotate_half_interleaved(rope).float() * sin)).to(x.dtype)
return torch.cat([nope, rotated], dim=-1)
def eager_attention_with_sinks(
@@ -111,11 +147,11 @@ def eager_attention_forward(
"""
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, module.head_dim)
cos, sin = packed.position_embeddings[module.rope_layer_type]
cos, sin = module.rotary_emb(packed.position_ids, module.rope_layer_type, dtype=torch.float32)
q_residual = module.q_a_norm(module.q_a_proj(hidden_states))
q = module.q_b_proj(q_residual).view(*hidden_shape).transpose(1, 2)
q = apply_rotary_pos_emb_interleaved(module.q_b_norm(q), cos, sin)
q = apply_rotary_pos_emb_interleaved(module.q_b_norm(q), cos, sin).to(q.dtype)
kv = module.kv_norm(module.kv_proj(hidden_states))
kv = kv.view(*kv.shape[:2], 1, module.head_dim)
@@ -44,10 +44,10 @@ class DeepseekV4DecoderLayer(GradientCheckpointingLayer):
dtype before mixing, so the residual keeps the dtype it entered with.
"""
def __init__(self, config: DeepseekV4Config, layer_idx: int):
def __init__(self, config: DeepseekV4Config, layer_idx: int, rotary_emb: DeepseekV4RotaryEmbedding):
super().__init__()
self.layer_idx = layer_idx
self.self_attn = DeepseekV4Attention(config, layer_idx)
self.self_attn = DeepseekV4Attention(config, layer_idx, rotary_emb)
self.mlp = DeepseekV4MoE(config, layer_idx)
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
@@ -163,9 +163,8 @@ class DeepseekV4PreTrainedModel(PreTrainedModelPrimeRL):
def init_buffers_post_meta(self) -> None:
# `to_empty()` leaves every buffer uninitialized and this runs before `dcp_load`, so a
# buffer is restored either here or by the checkpoint. Rebuilt here are the ones no
# checkpoint carries: the rotary tables (non-persistent, and there is one rotary per
# compressor and per indexer on top of the model-level one, so every instance has to be
# walked) and `tokens_per_expert`. The router's persistent buffers, `selection_bias` and a
# checkpoint carries: the rotary tables (non-persistent, and the one rotary every attention
# layer shares) and `tokens_per_expert`. The router's persistent buffers, `selection_bias` and a
# hash layer's `tid2eid`, are in the checkpoint that `dcp_load` applies next, so they are
# left to it.
for module in self.modules():
@@ -182,11 +181,15 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
# Shared by every attention layer instead of passing RoPE tensors through forward, which FSDP casts to bf16.
self.rotary_emb = DeepseekV4RotaryEmbedding(config)
self.layers = nn.ModuleList(
[DeepseekV4DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
[
DeepseekV4DecoderLayer(config, layer_idx, self.rotary_emb)
for layer_idx in range(config.num_hidden_layers)
]
)
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.rotary_emb = DeepseekV4RotaryEmbedding(config)
self.hc_head = DeepseekV4HyperHead(config)
self.gradient_checkpointing = False
@@ -255,7 +258,6 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
packed = PackedContext.build(
rotary_emb=self.rotary_emb,
seq_lens=seq_lens,
dtype=inputs_embeds.dtype,
device=inputs_embeds.device,
cp_rank=cp_rank,
cp_world_size=cp_world_size,
@@ -12,54 +12,19 @@ from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import Deepse
SUPPORTED_ROPE_TYPES = frozenset({"default", "linear", "llama3", "proportional", "yarn"})
def rotate_half_interleaved(x: torch.Tensor) -> torch.Tensor:
"""Rotate consecutive channel pairs: `(x0, x1, x2, x3, ...) -> (-x1, x0, -x3, x2, ...)`.
Not the same as `prime_rl.trainer.models.layers.rotary_emb.rotate_half`, which pairs
channel `i` with channel `i + dim / 2` (the GPT-NeoX layout). DeepSeek-V4 stores each
rotary pair adjacently, so the two are not interchangeable.
"""
x1 = x[..., 0::2]
x2 = x[..., 1::2]
return torch.stack((-x2, x1), dim=-1).flatten(-2)
def apply_rotary_pos_emb_interleaved(
x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, unsqueeze_dim: int = 1
) -> torch.Tensor:
"""Apply interleaved RoPE to the trailing rotary slice of `x`.
`cos` and `sin` arrive at half width (one entry per interleaved pair) and are widened
with `repeat_interleave`. Each head is laid out as `[nope | rope]`, so only the last
`2 * cos.shape[-1]` channels rotate and the leading ones pass through untouched.
The rotation itself runs in fp32 and is cast back to `x`'s dtype.
Args:
x: Tensor whose last dimension is the head dimension.
cos: Half-width cosines, shape `(batch, seq, rope_dim / 2)`.
sin: Half-width sines, same shape as `cos`.
unsqueeze_dim: Axis of `x` that `cos` / `sin` must broadcast over. Use `1` for a
`(batch, heads, seq, head_dim)` layout and `2` for `(batch, seq, heads, head_dim)`.
"""
cos = cos.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim)
sin = sin.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim)
rope_dim = cos.shape[-1]
nope, rope = x[..., :-rope_dim], x[..., -rope_dim:]
rotated = ((rope.float() * cos) + (rotate_half_interleaved(rope).float() * sin)).to(x.dtype)
return torch.cat([nope, rotated], dim=-1)
class DeepseekV4RotaryEmbedding(nn.Module):
"""Rotary embedding carrying one inverse-frequency table per RoPE type.
DeepSeek-V4 keys its RoPE parameters by rope type (`main` / `compress`), which is
independent of `config.layer_types`: sliding-window layers read `main`, the two
compressed attention variants share `compress` with their compressor. Each type gets
its own `<type>_inv_freq` / `<type>_original_inv_freq` buffers and
`<type>_attention_scaling` scalar.
its own `<type>_inv_freq` buffer and `<type>_attention_scaling` scalar.
Because the rotation is interleaved, `forward` returns `cos` / `sin` at half the
rotary width (one entry per pair). `apply_rotary_pos_emb_interleaved` widens them.
rotary width (one entry per pair).
Each type also keeps a static fp32 `<type>_cos_sin_cache`, `[cos | sin]` at every position in
vLLM's layout, which the fused RoPE kernels index by position.
`rope_type` is checkpoint data rather than architecture: V4 ships `default` on `main` and
`default` or `yarn` on `compress`, but the config reads whatever the file says. Anything
@@ -70,8 +35,6 @@ class DeepseekV4RotaryEmbedding(nn.Module):
def __init__(self, config: DeepseekV4Config, device: torch.device | None = None):
super().__init__()
self.config = config
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
# Only the nested per-rope-type sub-dicts are real rope types; a flat leftover
# `rope_type` key at the top level is not one.
self.layer_types = [name for name, params in config.rope_parameters.items() if isinstance(params, dict)]
@@ -86,8 +49,10 @@ class DeepseekV4RotaryEmbedding(nn.Module):
)
inv_freq, attention_scaling = self._rope_init_fn(layer_type)(config, device, layer_type=layer_type)
self.register_buffer(f"{layer_type}_inv_freq", inv_freq, persistent=False)
self.register_buffer(f"{layer_type}_original_inv_freq", inv_freq.clone(), persistent=False)
setattr(self, f"{layer_type}_attention_scaling", attention_scaling)
self.register_buffer(
f"{layer_type}_cos_sin_cache", self._compute_cos_sin_cache(layer_type), persistent=False
)
def _rope_init_fn(self, layer_type: str) -> Callable[..., tuple[torch.Tensor, float]]:
rope_type = self.rope_type[layer_type]
@@ -96,7 +61,7 @@ class DeepseekV4RotaryEmbedding(nn.Module):
return ROPE_INIT_FUNCTIONS[rope_type]
def init_buffers_post_meta(self) -> None:
"""Re-derive the per-rope-type inverse frequencies in place.
"""Re-derive the per-rope-type inverse frequencies and cos/sin caches in place.
The tables are computed eagerly in `__init__` and registered non-persistently, so they
survive neither meta-device construction nor a `load_state_dict`. Re-deriving them is
@@ -108,8 +73,8 @@ class DeepseekV4RotaryEmbedding(nn.Module):
self.config, inv_freq_buffer.device, layer_type=layer_type
)
inv_freq_buffer.copy_(inv_freq)
getattr(self, f"{layer_type}_original_inv_freq").copy_(inv_freq)
setattr(self, f"{layer_type}_attention_scaling", attention_scaling)
getattr(self, f"{layer_type}_cos_sin_cache").copy_(self._compute_cos_sin_cache(layer_type))
@staticmethod
def compute_default_rope_parameters(
@@ -139,17 +104,28 @@ class DeepseekV4RotaryEmbedding(nn.Module):
device_type = device.type if isinstance(device.type, str) and device.type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False): # Force float32
# No `cat([freqs, freqs])`: interleaved RoPE needs one theta per pair, and
# `apply_rotary_pos_emb_interleaved` widens cos/sin next to the rotation.
# No `cat([freqs, freqs])`: interleaved RoPE needs one theta per pair.
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
cos = freqs.cos() * attention_scaling
sin = freqs.sin() * attention_scaling
return cos.to(dtype=dtype), sin.to(dtype=dtype)
def _compute_cos_sin_cache(self, layer_type: str) -> torch.Tensor:
"""`(max_position_embeddings, rope_dim)` fp32 `[cos | sin]` of `layer_type` at every position."""
inv_freq = getattr(self, f"{layer_type}_inv_freq")
if inv_freq.is_meta:
return torch.empty(
self.config.max_position_embeddings, 2 * inv_freq.shape[0], device="meta", dtype=torch.float32
)
# TODO: size to the run's seq_len; 1M positions cost 256 MiB per rope type.
positions = torch.arange(self.config.max_position_embeddings, device=inv_freq.device)
cos, sin = self(positions[None], layer_type, dtype=torch.float32)
return torch.cat([cos[0], sin[0]], dim=-1)
__all__ = [
"DeepseekV4RotaryEmbedding",
"apply_rotary_pos_emb_interleaved",
"rotate_half_interleaved",
]
def cos_sin_cache(self, layer_type: str) -> torch.Tensor:
"""The fp32 `[cos | sin]` cache of `layer_type`, one row per position."""
return getattr(self, f"{layer_type}_cos_sin_cache")
__all__ = ["DeepseekV4RotaryEmbedding"]
@@ -0,0 +1,201 @@
# Adapted from https://github.com/NVIDIA/Megatron-LM/blob/c16d981ca/megatron/core/fusions/fused_mla_yarn_rope_apply.py (BSD-3, Copyright NVIDIA)
"""Fused interleaved RoPE for DeepSeek-V4 attention, matching vLLM's numerics.
DeepSeek-V4 rotates only the trailing `rope_dim` channels of each head, with each rotary pair stored
adjacently. Eagerly, every rotation widens the cos/sin tables and rebuilds the whole head with
`torch.cat`, a large share of attention time. `dsv4_rope` rotates in one kernel pass, reading
fp32 cos and sin from a `[cos | sin]` cache by position, bit for bit with vLLM's `rotary_embedding`.
`dsv4_q_norm_rope` puts the query's RMSNorm in the same op so the query is rounded to bf16 once, as vLLM's
fused prefill kernel does.
"""
import torch
import triton
import triton.language as tl
from prime_rl.trainer.models.layers.norms import get_quack_rmsnorm
@triton.autotune(
configs=[triton.Config({"BLOCK_H": block_h}, num_warps=warps) for block_h in (1, 2, 4, 8, 16) for warps in (4, 8)],
key=["num_heads", "head_dim"],
)
@triton.jit
def _triton_rope_kernel(
X,
OUT,
COS_SIN,
POS,
num_heads,
head_dim: tl.constexpr,
rope_dim: tl.constexpr,
INVERSE: tl.constexpr,
BLOCK_H: tl.constexpr,
):
"""Rotate the trailing `rope_dim` channels of `BLOCK_H` heads of one token and copy the rest."""
token = tl.program_id(0).to(tl.int64)
heads = tl.program_id(1) * BLOCK_H + tl.arange(0, BLOCK_H)
rope_pairs = tl.arange(0, head_dim // 2) - (head_dim - rope_dim) // 2
is_rope = (rope_pairs >= 0)[None, :]
cos_sin = COS_SIN + tl.load(POS + token).to(tl.int64) * rope_dim
cos = tl.load(cos_sin + rope_pairs, mask=rope_pairs >= 0, other=1.0)
sin = tl.load(cos_sin + rope_dim // 2 + rope_pairs, mask=rope_pairs >= 0, other=0.0)
if INVERSE:
sin = -sin
offsets = (token * num_heads + heads[:, None]) * head_dim + tl.arange(0, head_dim)[None, :]
mask = heads[:, None] < num_heads
x = tl.load(X + offsets, mask=mask).to(tl.float32)
x1, x2 = tl.split(tl.reshape(x, (BLOCK_H, head_dim // 2, 2)))
# vLLM's contraction: letting the compiler pick flips a bf16 ULP on ~1e-5 of the outputs.
y1 = tl.where(is_rope, tl.fma(x1, cos, -(x2 * sin)), x1)
y2 = tl.where(is_rope, tl.fma(x1, sin, x2 * cos), x2)
y = tl.reshape(tl.join(y1, y2), (BLOCK_H, head_dim))
tl.store(OUT + offsets, y.to(OUT.dtype.element_ty), mask=mask)
def _triton_rope(
x: torch.Tensor,
cos_sin_cache: torch.Tensor,
position_ids: torch.Tensor,
inverse: bool,
out_dtype: torch.dtype | None = None,
) -> torch.Tensor:
"""Rotated copy of `x`, bypassing autograd, rounded once to `out_dtype` (default: `x`'s dtype)."""
x = x.contiguous()
out = x.new_empty(x.shape, dtype=out_dtype)
if out.numel() == 0:
return out
num_heads, head_dim = x.shape[-2:]
grid = lambda meta: (position_ids.numel(), triton.cdiv(num_heads, meta["BLOCK_H"]))
_triton_rope_kernel[grid](
x,
out,
cos_sin_cache,
position_ids.contiguous(),
num_heads,
head_dim,
cos_sin_cache.shape[-1],
INVERSE=inverse,
)
return out
@torch.library.custom_op("prime_rl::dsv4_rope", mutates_args=())
def dsv4_rope(
x: torch.Tensor, cos_sin_cache: torch.Tensor, position_ids: torch.Tensor, *, inverse: bool = False
) -> torch.Tensor:
"""Interleaved RoPE on the trailing `rope_dim` channels of each head, bit for bit with vLLM's `rotary_embedding`.
With `x1 = x[..., 2i]` and `x2 = x[..., 2i + 1]` of the rotary slice, the output holds
`x1 * cos - x2 * sin` and `x2 * cos + x1 * sin`, computed in fp32 with `cos` and `sin` read from row
`position_ids[t]` of `cos_sin_cache` for token `t`; the leading channels are copied. `inverse=True`
rotates by the opposite angle, which undoes the rotation.
Args:
x: `(..., heads, head_dim)`, one entry of `position_ids` per token; `head_dim` a power of two.
cos_sin_cache: `(max_position, rope_dim)` fp32 and contiguous, cos then sin, one entry per pair each.
position_ids: int32 or int64, one per token, each in `[0, max_position)`.
inverse: rotate by the opposite angle.
"""
return _triton_rope(x, cos_sin_cache, position_ids, inverse)
@dsv4_rope.register_fake
def _dsv4_rope_fake(
x: torch.Tensor, cos_sin_cache: torch.Tensor, position_ids: torch.Tensor, *, inverse: bool = False
) -> torch.Tensor:
return x.new_empty(x.shape)
def _dsv4_rope_setup_context(ctx, inputs, keyword_only_inputs, output) -> None:
_, cos_sin_cache, position_ids = inputs
ctx.save_for_backward(cos_sin_cache, position_ids)
ctx.inverse = keyword_only_inputs["inverse"]
def _dsv4_rope_autograd_backward(ctx, grad: torch.Tensor):
cos_sin_cache, position_ids = ctx.saved_tensors
return dsv4_rope(grad, cos_sin_cache, position_ids, inverse=not ctx.inverse), None, None
dsv4_rope.register_autograd(_dsv4_rope_autograd_backward, setup_context=_dsv4_rope_setup_context)
@torch.library.custom_op("prime_rl::dsv4_q_norm_rope", mutates_args=())
def _dsv4_q_norm_rope(
q: torch.Tensor, cos_sin_cache: torch.Tensor, position_ids: torch.Tensor, eps: float
) -> tuple[torch.Tensor, torch.Tensor]:
"""The normed and rotated `q` in `q`'s dtype, plus the fp32 per-row `rstd` that backward needs."""
rows = q.reshape(-1, q.shape[-1])
if get_quack_rmsnorm() is not None:
from quack.rmsnorm import rmsnorm_fwd
normed, _, rstd = rmsnorm_fwd(rows, out_dtype=torch.float32, eps=eps, store_rstd=True)
else:
rstd = torch.rsqrt(rows.float().square().mean(-1) + eps)
normed = rows.float() * rstd[:, None]
return _triton_rope(normed.view(q.shape), cos_sin_cache, position_ids, False, out_dtype=q.dtype), rstd
@_dsv4_q_norm_rope.register_fake
def _dsv4_q_norm_rope_fake(
q: torch.Tensor, cos_sin_cache: torch.Tensor, position_ids: torch.Tensor, eps: float
) -> tuple[torch.Tensor, torch.Tensor]:
return q.new_empty(q.shape), q.new_empty(q.numel() // q.shape[-1], dtype=torch.float32)
@torch.library.custom_op("prime_rl::dsv4_q_norm_rope_backward", mutates_args=())
def _dsv4_q_norm_rope_backward(
grad: torch.Tensor, q: torch.Tensor, cos_sin_cache: torch.Tensor, position_ids: torch.Tensor, rstd: torch.Tensor
) -> torch.Tensor:
rows = q.reshape(-1, q.shape[-1])
grad_normed = _triton_rope(grad, cos_sin_cache, position_ids, True).view(rows.shape)
if get_quack_rmsnorm() is not None:
from quack.rmsnorm import rmsnorm_bwd
return rmsnorm_bwd(rows, None, grad_normed, rstd)[0].view(q.shape)
normed = rows.float() * rstd[:, None]
grad_normed = grad_normed.float()
grad_rows = (grad_normed - normed * (grad_normed * normed).mean(-1, keepdim=True)) * rstd[:, None]
return grad_rows.to(q.dtype).view(q.shape)
@_dsv4_q_norm_rope_backward.register_fake
def _dsv4_q_norm_rope_backward_fake(
grad: torch.Tensor, q: torch.Tensor, cos_sin_cache: torch.Tensor, position_ids: torch.Tensor, rstd: torch.Tensor
) -> torch.Tensor:
return q.new_empty(q.shape)
def _dsv4_q_norm_rope_setup_context(ctx, inputs, output) -> None:
q, cos_sin_cache, position_ids, _ = inputs
ctx.save_for_backward(q, cos_sin_cache, position_ids, output[1])
def _dsv4_q_norm_rope_autograd_backward(ctx, grad: torch.Tensor, grad_rstd: torch.Tensor):
q, cos_sin_cache, position_ids, rstd = ctx.saved_tensors
return _dsv4_q_norm_rope_backward(grad, q, cos_sin_cache, position_ids, rstd), None, None, None
_dsv4_q_norm_rope.register_autograd(_dsv4_q_norm_rope_autograd_backward, setup_context=_dsv4_q_norm_rope_setup_context)
def dsv4_q_norm_rope(
q: torch.Tensor, cos_sin_cache: torch.Tensor, position_ids: torch.Tensor, eps: float
) -> torch.Tensor:
"""Unweighted RMSNorm over `head_dim`, then interleaved RoPE, both in fp32, rounded once to `q`'s dtype.
The norm and rotation form one op that autograd and Inductor cannot see into:
- Autograd: as separate nodes, backward would pass an fp32 gradient of the normalized query between
them, twice the size of `q` (4 GiB per layer for 32k tokens of 64 heads of 512). Here the
rotation's backward runs on the bf16 gradient and feeds the norm's backward directly.
- Inductor: without quack, the norm falls back to torch ops, which Inductor would fuse and reorder,
flipping a bf16 ULP on a few hundred outputs so compiled results drift from eager and from vLLM.
`q` is `(..., heads, head_dim)`; `cos_sin_cache` and `position_ids` are as in `dsv4_rope`.
"""
out, _ = _dsv4_q_norm_rope(q, cos_sin_cache, position_ids, eps)
return out
@@ -30,6 +30,7 @@ LOG2E = 1.44269504
# The forward tiles the gather-slot axis at `block_I = 64` and the backward at `block_size = 32`,
# so the slot count must be a multiple of `lcm(64, 32) = 64`.
SLOT_TILE = 64
BWD_SLOT_TILE = 32
def _pad_slots_to_tile(indices: torch.Tensor) -> torch.Tensor:
@@ -47,6 +48,20 @@ def _pad_slots_to_tile(indices: torch.Tensor) -> torch.Tensor:
return F.pad(indices, (0, SLOT_TILE - remainder), value=IGNORE_SLOT).contiguous()
def num_tiles_covering_valid_slots(indices: torch.Tensor, tile_size: int) -> torch.Tensor:
"""Per query, the number of leading tiles of `tile_size` slots it takes to contain every valid slot.
`indices` is `(batch, seq_len, num_kv_heads, n_slots)` and the result is
`(batch, seq_len, num_kv_heads)`, both int32.
"""
n_slots = indices.shape[-1]
assert n_slots % tile_size == 0, f"n_slots must be a multiple of tile_size {tile_size}, got {n_slots}"
slot_idxs = torch.arange(n_slots, device=indices.device, dtype=torch.int32)
is_valid_slot = indices >= 0
last_valid_slot_idx = torch.where(is_valid_slot, slot_idxs, -1).amax(dim=-1)
return last_valid_slot_idx // tile_size + 1
def sparse_attn_shape_error(heads: int, kv_group: int, dim: int) -> str | None:
"""The reason these kernels cannot serve this shape, or ``None`` if they can.
@@ -107,13 +122,14 @@ def dsv4_sparse_attn(
assert shape_error is None, shape_error
assert indices.shape[:3] == (batch, seq_len, kv_group)
assert sinks.shape == (heads,)
assert SLOT_TILE % block_I == 0, (
f"the slot axis is padded to a multiple of {SLOT_TILE}, so block_I must divide it, got {block_I}"
)
indices = _pad_slots_to_tile(indices)
topk = indices.shape[-1]
kernel = dsv4_sparse_attn_fwd(
heads,
dim,
topk,
kv_group,
sm_scale,
True,
@@ -121,7 +137,9 @@ def dsv4_sparse_attn(
num_stages=num_stages,
threads=threads,
)
out, lse = kernel(q, kv, indices, sinks.float().contiguous())
tiled_indices = indices.view(batch, seq_len, kv_group, -1, block_I)
tile_counts = num_tiles_covering_valid_slots(indices, block_I)
out, lse = kernel(q, kv, tiled_indices, sinks.float().contiguous(), tile_counts)
return out, lse
@@ -166,15 +184,16 @@ def dsv4_sparse_attn_backward(
assert indices.shape[:3] == (batch, seq_len, kv_group)
assert lse.shape == (batch, seq_len, heads)
indices = _pad_slots_to_tile(indices)
topk = indices.shape[-1]
preprocess_kernel = preprocess(heads, dim)
bwd_kernel = bwd(heads, dim, topk, kv_group, sm_scale, True)
bwd_kernel = bwd(heads, dim, kv_group, sm_scale, True, block_size=BWD_SLOT_TILE)
postprocess_kernel = postprocess(dim, kv_group)
delta = preprocess_kernel(out, grad_out)
dkv = torch.zeros_like(kv, dtype=torch.float32)
dq = bwd_kernel(q, kv, grad_out, indices, lse, delta, dkv)
tiled_indices = indices.view(batch, seq_len, kv_group, -1, BWD_SLOT_TILE)
tile_counts = num_tiles_covering_valid_slots(indices, BWD_SLOT_TILE)
dq = bwd_kernel(q, kv, grad_out, tiled_indices, lse, delta, tile_counts, dkv)
dkv = postprocess_kernel(dkv)
return dq, dkv, delta
@@ -15,6 +15,11 @@ Beyond the forward's tensors:
dQ[b, s, h, d] (B, S, H, D) bfloat16
dKV[b, n, g, d] (B, N, G, D) float32 until `postprocess`
`Indices` arrives tiled as in the forward, but at this kernel's own tile:
`(B, S, G, n_tiles, block_size)` with `n_tiles = K / block_size`, and only `n_tiles` symbolic. `TileCounts` is the
forward's too, counted in these tiles, and skipping the tiles past it is exact for the same reason:
a masked slot contributes nothing to any gradient.
[What it computes]
With `key[b,s,k,d] = KV[b, Indices[b,s,0,k], 0, d]` and `scale = D ** -0.5` as in the forward:
@@ -50,8 +55,8 @@ negative.
[How the loop runs]
The grid is `(query position, batch, head block)`, the third axis also carrying the KV head when
`G > 1`, and at `H <= 64` it is a single block covering every query head. The block walks the `K`
slots in tiles of `block_size`, half the forward's tile, and per tile:
`G > 1`, and at `H <= 64` it is a single block covering every query head. The block walks its first
`TileCounts[b,s,g]` tiles of `block_size` slots, half the forward's tile, and per tile:
1. gather `KV_shared[k,d]`, and seed `acc_p` to `0` or `-inf` from the mask
2. `acc_p[h,k] += Q_shared[h,d] KV_shared[k,d]` onto that seed, then `exp2(... - Lse)` in place,
@@ -167,7 +172,6 @@ def postprocess(
def bwd(
H,
D,
topk,
kv_group=1,
sm_scale=None,
is_causal=True,
@@ -179,7 +183,6 @@ def bwd(
accum_dtype=T.float32,
):
assert is_causal is True, "non-casual is not supported now"
assert topk % block_size == 0, "otherwise will load some index=0 thus causing wrong kv to be loaded"
assert dtype == T.bfloat16
assert accum_dtype == T.float32
assert indices_dtype == T.int32
@@ -191,13 +194,15 @@ def bwd(
B = T.dynamic("B")
S = T.dynamic("S")
S_kv = T.dynamic("S_kv")
n_tiles = T.dynamic("n_tiles")
H_kv = H // kv_group
q_shape = [B, S, H, D]
k_shape = [B, S_kv, kv_group, D]
o_shape = [B, S, H, D]
indices_shape = [B, S, kv_group, topk]
indices_shape = [B, S, kv_group, n_tiles, block_size]
delta_shape = [B, S, H]
tile_counts_shape = [B, S, kv_group]
lse_shape = [B, S, H]
H = H_kv
@@ -206,7 +211,6 @@ def bwd(
assert padded_H % block_H == 0
NH = padded_H // block_H
BS = block_size
NS = tilelang.cdiv(topk, block_size)
split_store = 2
# The acc_dkv accumulator's per-thread layout (from the GEMMs that produce it) is only
@@ -231,6 +235,7 @@ def bwd(
Indices: T.Tensor(indices_shape, indices_dtype),
Lse: T.Tensor(lse_shape, accum_dtype),
Delta: T.Tensor(delta_shape, accum_dtype),
TileCounts: T.Tensor(tile_counts_shape, indices_dtype),
dQ: T.Tensor(q_shape, dtype),
dKV: T.Tensor(k_shape, accum_dtype),
):
@@ -260,15 +265,18 @@ def bwd(
T.clear(acc_dq)
for i_i in T.Pipelined(NS, num_stages=num_stages):
# `TileCounts` never exceeds `n_tiles`, but TileLang cannot know that; the `min` lets it
# prove every `Indices` read in bounds. Without it, TileLang guards each read with a
# runtime check inside the hot loop, which noticeably slows the backward.
for i_i in T.Pipelined(T.min(TileCounts[by, s_i, bz // NH], n_tiles), num_stages=num_stages):
for bi_i in T.Parallel(BS):
mask[bi_i] = Indices[by, s_i, bz // NH, i_i * BS + bi_i] >= 0
mask[bi_i] = Indices[by, s_i, bz // NH, i_i, bi_i] >= 0
for h_i, bi_i in T.Parallel(block_H, BS):
acc_p[h_i, bi_i] = T.if_then_else(mask[bi_i], 0, -T.infinity(acc_p.dtype))
for bi_i, d_i in T.Parallel(BS, D):
KV_shared[bi_i, d_i] = KV[by, Indices[by, s_i, bz // NH, i_i * BS + bi_i], bz // NH, d_i]
KV_shared[bi_i, d_i] = KV[by, Indices[by, s_i, bz // NH, i_i, bi_i], bz // NH, d_i]
T.gemm(Q_shared, KV_shared, acc_p, transpose_B=True, policy=T.GemmWarpPolicy.FullCol)
@@ -313,9 +321,9 @@ def bwd(
# dKV. Do not add a predicate back: reading the `mask` fragment here compiles
# cleanly but pins this loop to the four threads owning those elements.
for bi_i, d_i in T.Parallel(BS // split_store, D // 4):
slot_i = i_i * BS + bi_i + s * (BS // split_store)
slot_i = bi_i + s * (BS // split_store)
T.atomic_addx4(
dKV[by, Indices[by, s_i, bz // NH, slot_i], bz // NH, d_i * 4],
dKV[by, Indices[by, s_i, bz // NH, i_i, slot_i], bz // NH, d_i * 4],
acc_dkv_shared[bi_i, d_i * 4],
)
@@ -12,6 +12,7 @@ Shapes, with the capital of an index letter naming that axis's size:
KV[b, n, g, d] (B, N, G, D) keys, bfloat16; V == K here, so one buffer is both
Indices[b, s, g, k] (B, S, G, K) int32 positions into KV's `n` axis
Sinks[h] (H,) float32, one learnable logit per query head
TileCounts[b, s, g] (B, S, G) int32, how many leading slot tiles the query reads
Output[b, s, h, d] (B, S, H, D) bfloat16
Lse[b, s, h] (B, S, H) float32
@@ -30,6 +31,12 @@ asserts `G == 1` outright, so the equations below fix `g = 0` and drop it. Note
is spelled `kv_group` but counts KV heads; the query heads per KV head are `H / G`, spelled
`head_kv`.
`Indices` is listed by its logical shape, but the kernel receives it split into
`n_tiles = K / block_I` tiles of `block_I` slots, as `(B, S, G, n_tiles, block_I)`. `K` is sized for
the most keys any query could need, and a given query will often have fewer. Only `n_tiles` is
symbolic, so one compiled kernel serves every `K`. Declaring `K` itself symbolic instead makes
TileLang bounds-check every slot read against it, a runtime check inside the innermost loop.
[What it computes]
Write `key[b,s,k,d] = KV[b, Indices[b,s,0,k], 0, d]` for the gathered keys. Summing over repeated
@@ -50,8 +57,10 @@ a shrunken combination of the gathered keys. That is how a head attends to nothi
[What the caller must guarantee]
`K` is fixed when the kernel compiles and is part of its compilation key, so it is sized for the
most keys any query could need and a given query will often have fewer.
`TileCounts[b,s,g]` must cover the query's last valid slot: every slot past its first
`TileCounts * block_I` has to be masked, because the kernel never reads those tiles. A fully masked
tile changes nothing in the online softmax, so skipping one is exact, and a query that reaches
only a few of the `K` slots pays for only those.
Every unused slot must hold a negative index, which is the masking condition:
@@ -69,8 +78,8 @@ would cost a sync, so an out-of-range index silently corrupts that query's softm
The grid is `(query position, batch, KV head)`, so with `G == 1` that is one block per query
position per batch index, holding all `H` query heads of that query at once, or a 64-head chunk
when `H > 64` (`REPLICATE_H`). The block walks the `K` slots in tiles of `block_I`,
software-pipelined `num_stages` deep, and per tile:
when `H > 64` (`REPLICATE_H`). The block walks its first `TileCounts[b,s,g]` tiles of `block_I`
slots, software-pipelined `num_stages` deep, and per tile:
1. gather `KV_shared[k,d] = KV[b, Indices[b,s,0,k], 0, d]` into one shared tile of keys
2. `acc_s[h,k] = Q_shared[h,d] KV_shared[k,d]`, pre-seeded to `-inf` at masked slots
@@ -122,7 +131,6 @@ LOG2E = 1.44269504
def dsv4_sparse_attn_fwd(
heads,
dim,
topk,
kv_group=1,
sm_scale=None,
is_causal=True,
@@ -132,7 +140,6 @@ def dsv4_sparse_attn_fwd(
):
assert dim == tilelang.math.next_power_of_2(dim), f"haven't check padding correctness yet, dim={dim}"
assert is_causal is True, "non-casual is not supported"
assert topk % block_I == 0, "otherwise will load some index=0 thus causing wrong kv to be loaded"
if sm_scale is None:
sm_scale = (1.0 / dim) ** 0.5
# Both names are kept: the sink logit enters the softmax unscaled, so seeding the running max
@@ -142,13 +149,15 @@ def dsv4_sparse_attn_fwd(
batch = T.dynamic("batch")
seq_len = T.dynamic("seq_len")
seq_len_kv = T.dynamic("seq_len_kv")
n_tiles = T.dynamic("n_tiles")
head_kv = heads // kv_group
q_shape = [batch, seq_len, heads, dim]
kv_shape = [batch, seq_len_kv, kv_group, dim]
o_shape = [batch, seq_len, heads, dim]
indices_shape = [batch, seq_len, kv_group, topk]
indices_shape = [batch, seq_len, kv_group, n_tiles, block_I]
sinks_shape = [heads]
tile_counts_shape = [batch, seq_len, kv_group]
lse_shape = [batch, seq_len, heads]
indices_dtype = T.int32
dtype = T.bfloat16
@@ -163,7 +172,6 @@ def dsv4_sparse_attn_fwd(
" automatically)"
)
BI = block_I
NI = tilelang.cdiv(topk, block_I)
D = dim
if head_kv > 64:
@@ -180,6 +188,7 @@ def dsv4_sparse_attn_fwd(
KV: T.Tensor(kv_shape, dtype), # type: ignore
Indices: T.Tensor(indices_shape, indices_dtype), # type: ignore
Sinks: T.Tensor(sinks_shape, accum_dtype), # type: ignore
TileCounts: T.Tensor(tile_counts_shape, indices_dtype), # type: ignore
Output: T.Tensor(o_shape, dtype), # type: ignore
Lse: T.Tensor(lse_shape, accum_dtype), # type: ignore
):
@@ -231,12 +240,15 @@ def dsv4_sparse_attn_fwd(
T.copy(Q[b_i, s_i, H0:H1, :], Q_shared)
for i_i in T.Pipelined(NI, num_stages=num_stages):
# `TileCounts` never exceeds `n_tiles`, but TileLang cannot know that; the `min` lets it
# prove every `Indices` read in bounds rather than guarding each one, which costs the
# backward 11-18%.
for i_i in T.Pipelined(T.min(TileCounts[b_i, s_i, g_i], n_tiles), num_stages=num_stages):
for bi_i in T.Parallel(BI):
mask[bi_i] = Indices[b_i, s_i, g_i, i_i * BI + bi_i] >= 0
mask[bi_i] = Indices[b_i, s_i, g_i, i_i, bi_i] >= 0
for bi_i, d_i in T.Parallel(BI, D):
KV_shared[bi_i, d_i] = KV[b_i, Indices[b_i, s_i, g_i, i_i * BI + bi_i], g_i, d_i]
KV_shared[bi_i, d_i] = KV[b_i, Indices[b_i, s_i, g_i, i_i, bi_i], g_i, d_i]
for h_i, bi_i in T.Parallel(H_per_block, BI):
acc_s[h_i, bi_i] = T.if_then_else(mask[bi_i], 0, -T.infinity(acc_s.dtype))
@@ -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,
):
@@ -97,7 +97,7 @@ def per_token_group_quant_fp8(
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=8, num_stages=3),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=8, num_stages=3),
],
key=["S_Q", "S_K"],
key=["S_Q", "S_K_BUCKET", "H", "D"],
)
@triton.jit
def _triton_fp8_indexer_kernel(
@@ -116,6 +116,7 @@ def _triton_fp8_indexer_kernel(
stride_ws,
H: tl.constexpr,
D: tl.constexpr,
S_K_BUCKET: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
):
@@ -168,7 +169,16 @@ def _triton_fp8_indexer_kernel(
tl.store(out_ptrs, acc, mask=out_mask)
def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
@torch.library.custom_op("prime_rl::fp8_indexer", mutates_args=())
def fp8_indexer(
q: torch.Tensor,
k: torch.Tensor,
w: torch.Tensor,
ks: torch.Tensor,
ke: torch.Tensor,
topk: int,
weight_scale: float = 1.0,
) -> torch.Tensor:
"""Triton FP8 indexer: UE8M0 quantization + fused scoring kernel + topk.
Args:
@@ -221,6 +231,9 @@ def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
w.stride(0),
H=H,
D=D,
# Packed document tails change S_k between batches. Reuse tuning within
# a size bucket; exact S_k still controls strides and all bounds masks.
S_K_BUCKET=triton.next_power_of_2(S_k),
)
actual_topk = min(topk, S_k)
@@ -236,3 +249,8 @@ def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
indices = indices.masked_fill(out_of_range, S_k)
return indices.to(torch.int32)
@fp8_indexer.register_fake
def _fp8_indexer_fake(q, k, w, ks, ke, topk, weight_scale=1.0):
return q.new_empty((q.shape[0], topk), dtype=torch.int32)
@@ -6,7 +6,8 @@ import torch
import triton
import triton.language as tl
FP8_MAX = 448.0
FP8_MAX = tl.constexpr(448.0)
FP8_MIN = tl.constexpr(-448.0)
MIN_SCALE = 1e-4
GROUP_ALIGNMENT = 128
@@ -188,11 +189,11 @@ def _per_token_fp8_kernel(
mask=mask,
other=0.0,
).to(tl.float32)
amax = tl.max(tl.abs(x), axis=1)
scale = tl.maximum(amax / 448.0, 1e-4)
amax = tl.maximum(tl.max(tl.abs(x), axis=1), 1e-10)
scale = tl.math.div_rn(amax, FP8_MAX)
if USE_UE8M0:
scale = tl.exp2(tl.ceil(tl.log2(scale)))
y = x / scale[:, None]
y = tl.clamp(tl.math.div_rn(x, scale[:, None]), FP8_MIN, FP8_MAX)
tl.store(
out_ptr + row_offsets_i64[:, None] * stride_ym + col_offsets_i64[None, :] * stride_yn,
y.to(tl.float8e4nv),
@@ -242,11 +243,11 @@ def _grouped_per_token_fp8_kernel(
mask=valid_rows[:, None] & valid_cols[None, :],
other=0.0,
).to(tl.float32)
amax = tl.max(tl.abs(x), axis=1)
scale = tl.maximum(amax / 448.0, 1e-4)
amax = tl.maximum(tl.max(tl.abs(x), axis=1), 1e-10)
scale = tl.math.div_rn(amax, FP8_MAX)
if USE_UE8M0:
scale = tl.exp2(tl.ceil(tl.log2(scale)))
y = x / scale[:, None]
y = tl.clamp(tl.math.div_rn(x, scale[:, None]), FP8_MIN, FP8_MAX)
tl.store(
out_ptr + dst_rows_i64[:, None] * stride_ym + col_offsets_i64[None, :] * stride_yn,
y.to(tl.float8e4nv),
@@ -295,11 +296,11 @@ def _grouped_per_channel_fp8_kernel(
mask=valid_rows[:, None] & valid_cols[None, :],
other=0.0,
).to(tl.float32)
amax = tl.max(tl.abs(x), axis=0)
scale = tl.maximum(amax / 448.0, 1e-4)
amax = tl.maximum(tl.max(tl.abs(x), axis=0), 1e-10)
scale = tl.math.div_rn(amax, FP8_MAX)
if USE_UE8M0:
scale = tl.exp2(tl.ceil(tl.log2(scale)))
y = x / scale[None, :]
y = tl.clamp(tl.math.div_rn(x, scale[None, :]), FP8_MIN, FP8_MAX)
flat_base = block_start.to(tl.int64) * BLOCK_K * cols
if K_MAJOR:
out_ptrs = out_ptr + flat_base + col_offsets_i64[:, None] * aligned_m + row_offsets_i64[None, :]
@@ -355,7 +356,7 @@ def _grouped_per_block_fp8_kernel(
other=0.0,
).to(tl.float32)
amax = tl.max(tl.abs(x))
scale = tl.maximum(amax / 448.0, 1e-4)
scale = tl.maximum(amax / FP8_MAX, 1e-4)
if USE_UE8M0:
scale = tl.exp2(tl.ceil(tl.log2(scale)))
y = x / scale
@@ -426,7 +427,7 @@ def per_token_cast_to_fp8_triton(
sf.stride(0),
sf.stride(1),
USE_UE8M0=use_ue8m0,
BLOCK_M=8,
BLOCK_M=32,
BLOCK_K=gran_k,
num_warps=4,
)
@@ -453,7 +454,7 @@ def grouped_per_token_cast_to_fp8_triton(
)
if block_to_group.numel() == 0:
return out, sf
grid = (block_to_group.numel(), GROUP_ALIGNMENT // 8, ceil_div(x.size(1), gran_k))
grid = (block_to_group.numel(), GROUP_ALIGNMENT // 32, ceil_div(x.size(1), gran_k))
_grouped_per_token_fp8_kernel[grid](
x,
block_to_group,
@@ -470,7 +471,7 @@ def grouped_per_token_cast_to_fp8_triton(
sf.stride(0),
sf.stride(1),
USE_UE8M0=use_ue8m0,
BLOCK_M=8,
BLOCK_M=32,
BLOCK_K=gran_k,
GROUP_BLOCK_M=GROUP_ALIGNMENT,
num_warps=4,
@@ -496,7 +497,8 @@ def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
sf = torch.empty((total_blocks, x.size(1)), device=x.device, dtype=torch.float32)
if block_to_group.numel() == 0:
return out, sf.T
grid = (block_to_group.numel(), ceil_div(x.size(1), 128))
block_n = 16
grid = (block_to_group.numel(), ceil_div(x.size(1), block_n))
_grouped_per_channel_fp8_kernel[grid](
x,
block_to_group,
@@ -514,8 +516,8 @@ def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
USE_UE8M0=use_ue8m0,
K_MAJOR=True,
BLOCK_K=gran_k,
BLOCK_N=128,
num_warps=4,
BLOCK_N=block_n,
num_warps=2,
)
return out, sf.T
@@ -538,7 +540,8 @@ def grouped_per_channel_cast_to_fp8_rowmajor_triton(
sf = torch.empty((total_blocks, x.size(1)), device=x.device, dtype=torch.float32)
if block_to_group.numel() == 0:
return out, sf
grid = (block_to_group.numel(), ceil_div(x.size(1), 128))
block_n = 64
grid = (block_to_group.numel(), ceil_div(x.size(1), block_n))
_grouped_per_channel_fp8_kernel[grid](
x,
block_to_group,
@@ -556,7 +559,7 @@ def grouped_per_channel_cast_to_fp8_rowmajor_triton(
USE_UE8M0=use_ue8m0,
K_MAJOR=False,
BLOCK_K=gran_k,
BLOCK_N=128,
BLOCK_N=block_n,
num_warps=4,
)
return out, sf
@@ -672,7 +675,7 @@ def per_token_cast_to_fp8_tp_triton(
sf.stride(0),
sf.stride(1),
USE_UE8M0=use_ue8m0,
BLOCK_M=8,
BLOCK_M=32,
BLOCK_K=gran_k,
num_warps=4,
)
@@ -105,8 +105,8 @@ class NemotronHMamba2(nn.Module):
bias=config.use_conv_bias,
)
self.dt_bias = nn.Parameter(torch.empty(self.num_heads))
self.A_log = nn.Parameter(torch.log(torch.arange(1, self.num_heads + 1, dtype=torch.float32)))
self.D = nn.Parameter(torch.ones(self.num_heads, dtype=torch.float32))
self.A_log = nn.Parameter(torch.arange(1, self.num_heads + 1, dtype=torch.get_default_dtype()).log())
self.D = nn.Parameter(torch.ones(self.num_heads))
self.norm = GatedRMSNorm(
self.intermediate_size,
group_size=self.intermediate_size // self.num_groups,
@@ -142,7 +142,7 @@ class NemotronHMamba2(nn.Module):
conv_weight = self.conv1d.weight
conv_bias = self.conv1d.bias
state_decay = -torch.exp(self.A_log.float())
skip = self.D
skip = self.D.float()
dt_bias = self.dt_bias
norm_weight = self.norm.weight
+7 -10
View File
@@ -42,7 +42,7 @@ from prime_rl.trainer.model import (
get_full_offload_dtype_policy,
setup_model,
is_tt_moe_model,
get_load_balance_stats,
get_global_moe_stats,
)
from prime_rl.trainer.parallel_dims import get_parallel_dims, resolve_ep
from prime_rl.trainer.perf import get_perf_counter
@@ -193,6 +193,9 @@ def train(config: TrainerConfig):
if parallel_dims.cp_enabled:
setup_context_parallel(model, config.model, parallel_dims)
is_moe_model = is_tt_moe_model(model)
ep_group = parallel_dims.get_mesh("ep").get_group() if parallel_dims.ep_enabled else None
# Fresh adapter init after FSDP materialization (the pretrained checkpoint
# carries no adapter weights); a checkpoint resume below overwrites it.
if config.model.lora is not None:
@@ -539,11 +542,9 @@ def train(config: TrainerConfig):
annotation_writer.export(micro_batch, out)
if is_tt_moe_model(model):
load_balance_stats = get_load_balance_stats(model)
for k, v in load_balance_stats.items():
if v is not None:
tensors[k].append(v)
if is_moe_model:
for name, value in get_global_moe_stats(model, ep_group, dp_cp_group).items():
tensors[name].append(value.reshape(1))
# Add loss tensors to tensor dict for logging purposes
for key, loss_tensor in loss_tensors.items():
@@ -553,10 +554,6 @@ def train(config: TrainerConfig):
micro_step_message = f"Micro Step {micro_step + 1}/{len(micro_batches)} | Loss {tensors['loss'][-1].mean().item():.4f} | Entropy {tensors['entropy/all'][-1].mean().item():.4f}"
if has_mismatch_tokens:
micro_step_message += f" | Mismatch KL {tensors['mismatch_kl/all'][-1].mean().item():.4f}"
if "max_vio" in tensors:
micro_step_message += f" | Max Vio {tensors['max_vio'][-1].mean().item():.4f}"
if "routing_confidence" in tensors:
micro_step_message += f" | Routing Conf. {tensors['routing_confidence'][-1].mean().item():.4f}"
logger.debug(micro_step_message)
annotation_writer.flush()
+87 -12
View File
@@ -1,13 +1,17 @@
import json
import time
import uuid
from collections import defaultdict
from typing import Any, Literal, TypedDict, cast
from pathlib import Path
from typing import Any, Callable, Literal, TypedDict, cast
import numpy as np
import torch
from datasets import Dataset, interleave_datasets, load_dataset
from huggingface_hub import snapshot_download
from jaxtyping import Bool, Int
from renderers.base import MultiModalData, PlaceholderRange, Renderer, build_training_sample
from renderers import AutoRendererConfig, RendererConfig
from renderers.base import MultiModalData, PlaceholderRange, Renderer, build_training_sample, create_renderer
from torch import Tensor
from torch.distributed.checkpoint.stateful import Stateful
from torch.utils.data import IterableDataset, get_worker_info
@@ -18,6 +22,7 @@ from prime_rl.configs.sft import DataConfig, LossMaskConfig, SFTDataConfig
from prime_rl.trainer.world import get_world
from prime_rl.utils.chat_template import deserialize_tool_calls, normalize_messages
from prime_rl.utils.logger import get_logger
from prime_rl.utils.utils import format_time
class Sample(TypedDict):
@@ -204,13 +209,53 @@ def _truncate_mm_data(mm: MultiModalData, cut: int) -> MultiModalData:
return MultiModalData(mm_hashes=new_hashes, mm_placeholders=new_placeholders, mm_items=new_items)
def with_reasoning_effort(config: RendererConfig, reasoning_effort: Any) -> RendererConfig:
"""Copy ``config`` with its ``reasoning_effort`` field set, validated by the config class."""
if isinstance(config, AutoRendererConfig):
raise ValueError(
"A reasoning_effort column requires a typed renderer config (e.g. [renderer] name = 'qwen3.8'), "
"not renderer.name = 'auto'"
)
if "reasoning_effort" not in type(config).model_fields:
raise ValueError(f"Renderer {config.name!r} has no reasoning_effort field, but a row sets {reasoning_effort!r}")
return type(config).model_validate({**config.model_dump(), "reasoning_effort": reasoning_effort})
class RendererResolver:
"""Picks the renderer for a dataset row.
A ``reasoning_effort`` column overrides the configured renderer's field of
the same name per row. Renderer configs are frozen, so renderers are cached
per config and rows that resolve to the same config share one instance.
"""
def __init__(self, tokenizer: PreTrainedTokenizer, config: RendererConfig, processor: Any | None = None):
self.tokenizer = tokenizer
self.config = config
self.processor = processor
self.renderers: dict[RendererConfig, Renderer] = {}
def __call__(self, example: dict) -> Renderer:
config = self.config
reasoning_effort = example.get("reasoning_effort")
if reasoning_effort is not None:
config = with_reasoning_effort(config, reasoning_effort)
renderer = self.renderers.get(config)
if renderer is None:
renderer = create_renderer(self.tokenizer, config)
if self.processor is not None and hasattr(renderer, "_processor"):
renderer._processor = self.processor
self.renderers[config] = renderer
return renderer
class SFTDataset(StatefulIterableDataset):
"""A dataset wrapping a HF SFT dataset with prompt/completion or raw messages format."""
def __init__(
self,
dataset: Dataset,
renderer: Renderer,
renderers: Callable[[dict], Renderer],
shuffle: bool = True,
seed: int = 0,
seq_len: int = 128,
@@ -224,7 +269,7 @@ class SFTDataset(StatefulIterableDataset):
self.logger = get_logger()
self.dataset = dataset
self.num_examples = len(self.dataset)
self.renderer = renderer
self.renderers = renderers
self.shuffle = shuffle
self.seed = seed
self.seq_len = seq_len
@@ -311,8 +356,9 @@ class SFTDataset(StatefulIterableDataset):
# body-only path: the message content is trained, not the role
# scaffolding (e.g. <|im_start|>assistant) the harness emits.
content_sft_roles = {role for role in ("user", "system", "tool") if getattr(self.loss_mask_config, role)}
renderer = self.renderers(example)
sample = build_training_sample(
self.renderer,
renderer,
messages,
role_to_mask=role_to_mask,
tools=tools,
@@ -352,7 +398,7 @@ class SFTDataset(StatefulIterableDataset):
if mm.mm_items:
mm = _truncate_mm_data(mm, cut)
if was_mm_truncated and not set(self.renderer.get_stop_token_ids()) & set(target_ids):
if was_mm_truncated and not set(renderer.get_stop_token_ids()) & set(target_ids):
return None
if sum(loss_mask[: self.seq_len]) == 0:
@@ -365,7 +411,7 @@ class SFTDataset(StatefulIterableDataset):
f"input_ids, loss_mask and target_ids must have the same length, but got {len(input_ids)=}, {len(loss_mask)=}, {len(target_ids)=}"
)
assert sum(loss_mask) > 0, "There are no tokens in this sample that contribute to the loss"
assert set(self.renderer.get_stop_token_ids()) & set(target_ids), (
assert set(renderer.get_stop_token_ids()) & set(target_ids), (
"A renderer stop token must be present in target_ids"
)
@@ -575,18 +621,41 @@ def cat_collate(samples: list[Sample]) -> Batch:
}
def pre_download_data(data: DataConfig, env_vars: dict[str, str]) -> None:
if not isinstance(data, SFTDataConfig):
return
if Path(data.name).exists():
get_logger().info(f"Data {data.name} found at local path, skipping download")
return
dataset_name = data.name
t0 = time.perf_counter()
get_logger().info(f"Pre-downloading data {dataset_name} at revision {data.revision or 'main'}")
snapshot = snapshot_download(
repo_id=dataset_name,
repo_type="dataset",
revision=data.revision,
cache_dir=env_vars.get("HF_HUB_CACHE"),
)
data.name = snapshot
get_logger().debug(
f"Finished pre-downloading data {dataset_name} to {snapshot} in {format_time(time.perf_counter() - t0)}"
)
def setup_and_interleave_datasets(
dataset_name: str,
subsets_and_splits: list[tuple[str | None, str]],
probabilities: list[float] | None,
stopping_strategy: Literal["first_exhausted", "all_exhausted"],
seed: int = 0,
revision: str | None = None,
) -> Dataset:
logger = get_logger()
datasets = []
for subset, split in subsets_and_splits:
logger.debug(f"Loading dataset {dataset_name} with {subset=} and {split=}")
dataset = cast(Dataset, load_dataset(dataset_name, subset, split=split))
dataset = cast(Dataset, load_dataset(dataset_name, subset, split=split, revision=revision))
num_examples = len(dataset)
dataset = dataset.add_column("__subset", [subset] * num_examples, new_fingerprint=str(uuid.uuid4()))
dataset = dataset.add_column("__split", [split] * num_examples, new_fingerprint=str(uuid.uuid4()))
@@ -615,6 +684,7 @@ def load_sft_dataset(config: SFTDataConfig) -> Dataset:
subsets_and_splits=[(None, "train")],
probabilities=config.probabilities,
stopping_strategy=config.stopping_strategy,
revision=config.revision,
)
elif config.subsets is not None and config.splits is None:
logger.debug(f"Loading datasets for subsets {config.subsets} with default split 'train'")
@@ -623,6 +693,7 @@ def load_sft_dataset(config: SFTDataConfig) -> Dataset:
subsets_and_splits=[(subset, "train") for subset in config.subsets],
probabilities=config.probabilities,
stopping_strategy=config.stopping_strategy,
revision=config.revision,
)
elif config.subsets is None and config.splits is not None:
logger.debug(f"Loading datasets for splits {config.splits} with default subset 'None'")
@@ -631,6 +702,7 @@ def load_sft_dataset(config: SFTDataConfig) -> Dataset:
subsets_and_splits=[(None, split) for split in config.splits],
probabilities=config.probabilities,
stopping_strategy=config.stopping_strategy,
revision=config.revision,
)
else:
assert config.subsets is not None and config.splits is not None
@@ -640,6 +712,7 @@ def load_sft_dataset(config: SFTDataConfig) -> Dataset:
subsets_and_splits=list(zip(config.subsets, config.splits)),
probabilities=config.probabilities,
stopping_strategy=config.stopping_strategy,
revision=config.revision,
)
@@ -650,7 +723,8 @@ def setup_dataset(
*,
max_epochs: int | None = None,
raw_dataset: Dataset | None = None,
renderer: Renderer | None = None,
renderer_config: RendererConfig | None = None,
processor: Any | None = None,
multimodal: bool = False,
) -> StatefulIterableDataset:
if config.type == "fake":
@@ -663,13 +737,14 @@ def setup_dataset(
non_dp_size=non_dp_size,
)
elif config.type == "sft":
if renderer is None:
raise ValueError("SFT data requires a renderer.")
if renderer_config is None:
raise ValueError("SFT data requires a renderer config.")
if raw_dataset is None:
raw_dataset = load_sft_dataset(config)
renderers = RendererResolver(tokenizer, renderer_config, processor=processor)
return SFTDataset(
raw_dataset,
renderer,
renderers,
shuffle=config.shuffle,
seed=config.seed,
seq_len=config.seq_len,
+25 -27
View File
@@ -6,7 +6,6 @@ import asyncio
from contextlib import nullcontext
from datetime import timedelta
from renderers.base import create_renderer
from torch.nn import CrossEntropyLoss
# Import environment before any other imports
@@ -29,6 +28,7 @@ from prime_rl.trainer.scheduler import setup_scheduler
from prime_rl.trainer.model import (
forward,
get_full_offload_dtype_policy,
get_global_moe_stats,
get_load_balance_stats,
is_tt_moe_model,
setup_processor,
@@ -154,16 +154,6 @@ def train(config: SFTConfig):
if config.model.vlm is not None and processor is None:
raise ValueError(f"[model.vlm] is set but no multimodal processor could be loaded for {config.model.name!r}")
# Fake data never renders messages, so a model without a hand-coded renderer
# can still be used to benchmark step time / memory. Validation data is
# always real, so it needs the renderer even when training data is fake.
renderer = None
if config.data.type != "fake" or config.val is not None:
renderer = create_renderer(tokenizer, config.renderer)
if processor is not None and hasattr(renderer, "_processor"):
renderer._processor = processor
logger.debug(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}")
# Set up the optimizer
logger.info(f"Initializing optimizer ({config.optim})")
optimizer, gradient_manager = setup_optimizer(
@@ -192,12 +182,19 @@ def train(config: SFTConfig):
# Set up the dataset and dataloader
logger.info(f"Initializing data ({config.data})")
multimodal = config.model.vlm is not None
dataset = setup_dataset(tokenizer, config.data, config.model.cp, renderer=renderer, multimodal=multimodal)
dataset = setup_dataset(
tokenizer,
config.data,
config.model.cp,
renderer_config=config.renderer,
processor=processor,
multimodal=multimodal,
)
dataloader = setup_dataloader(dataset, config.data)
val_raw_dataset = None
if config.val is not None:
logger.info(f"Loading validation dataset ({config.val.data.name})")
logger.info(f"Loading validation dataset ({config.val.data})")
val_raw_dataset = load_sft_dataset(config.val.data)
# Optionally, resume training from a checkpoint
@@ -238,6 +235,7 @@ def train(config: SFTConfig):
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank() if cp_enabled else 0
cp_group = parallel_dims.world_mesh["cp"].get_group() if cp_enabled else None
dp_cp_group = parallel_dims.get_mesh("dp_cp").get_group()
ep_group = parallel_dims.get_mesh("ep").get_group() if parallel_dims.ep_enabled else None
cp_size = parallel_dims.cp
def compute_loss(micro_batch: dict) -> tuple[torch.Tensor, torch.Tensor]:
@@ -360,13 +358,17 @@ def train(config: SFTConfig):
config.model.cp,
max_epochs=1,
raw_dataset=val_raw_dataset,
renderer=renderer,
renderer_config=config.renderer,
processor=processor,
multimodal=multimodal,
)
val_dataloader = setup_dataloader(val_dataset, config.val.data)
# No train/eval switch: no dropout in these models, and toggling would trigger torch.compile recompilation
mean_loss, nan_count = run_eval_loop(val_dataloader)
if is_tt_moe_model(model):
# Keep validation routing out of the next training step's statistics.
get_load_balance_stats(model)
if nan_count > 0:
logger.warning(f"Validation at step {step}: {nan_count} batches had NaN loss")
if mean_loss != mean_loss:
@@ -434,8 +436,9 @@ def train(config: SFTConfig):
is_moe_model = is_tt_moe_model(model)
moe_stats = (
{
"max_vio": torch.tensor(0.0, device="cuda"),
"routing_confidence": torch.tensor(0.0, device="cuda"),
"max_vio/mean": torch.tensor(0.0),
"max_vio/max": torch.tensor(0.0),
"routing_confidence/mean": torch.tensor(0.0),
}
if is_moe_model
else {}
@@ -490,15 +493,10 @@ def train(config: SFTConfig):
finish_backward(gradient_manager)
if is_moe_model:
for name, values in get_load_balance_stats(model).items():
if values is None:
continue
value = values.mean()
reduce_op = dist.ReduceOp.MAX if name == "max_vio" else dist.ReduceOp.SUM
dist.all_reduce(value, op=reduce_op)
if reduce_op == dist.ReduceOp.SUM:
value /= dist.get_world_size()
moe_stats[name] += value / grad_accum_steps
for name, value in get_global_moe_stats(model, ep_group, dp_cp_group).items():
moe_stats[f"{name}/mean"] += value / grad_accum_steps
if name == "max_vio":
moe_stats["max_vio/max"] = torch.maximum(moe_stats["max_vio/max"], value)
forward_backward_time = time.perf_counter() - forward_backward_start_time
@@ -585,7 +583,7 @@ def train(config: SFTConfig):
step_message += f" | Grad. Norm {grad_norm:.4f}"
step_message += f" | LR {current_lr:.2e} | Throughput {throughput:.0f} tokens/s | MFU {mfu:.1f}% | Peak Mem. {peak_memory:.1f}/{max_memory:.1f} GiB ({peak_memory / max_memory * 100:.1f}%)"
if is_moe_model:
for name, label in (("max_vio", "Max Vio"), ("routing_confidence", "Routing Conf.")):
for name, label in (("max_vio/mean", "Max Vio"), ("routing_confidence/mean", "Routing Conf.")):
value = moe_stats[name].item()
if value > 0:
step_message += f" | {label} {value:.4f}"
@@ -659,7 +657,7 @@ def train(config: SFTConfig):
disk_metrics["step"] = progress.step
asyncio.run(monitors.log(disk_metrics, step=progress.step))
moe_log_metrics = {f"{name}/mean": value.item() for name, value in moe_stats.items() if value.item() > 0}
moe_log_metrics = {name: value.item() for name, value in moe_stats.items()}
if moe_log_metrics:
asyncio.run(monitors.log({**moe_log_metrics, "step": progress.step}, step=progress.step))
+16
View File
@@ -52,6 +52,22 @@ def test_expand_shorthands_refuses_shorthand_next_to_source_toml(tmp_path) -> No
toml.write_text('[[source]]\nenv.taskset.id = "gsm8k"\n')
with pytest.raises(SystemExit, match="cannot be combined"):
expand_shorthands(["wordle", "@", toml.as_posix()])
with pytest.raises(SystemExit, match="cannot be combined"):
expand_shorthands(["wordle", "@", toml.as_posix(), "--env.retries.max-retries", "3"])
def test_expand_shorthands_passes_env_flags_to_the_shared_block_next_to_source_toml(tmp_path) -> None:
toml = tmp_path / "eval.toml"
toml.write_text('[[source]]\nenv.taskset.id = "gsm8k"\n')
argv = ["@", toml.as_posix(), "--env.retries.max-retries", "3", "--env.timeout.episode=60"]
assert expand_shorthands(argv) == [
"@",
toml.as_posix(),
"--env.retries.max-retries",
"3",
"--env.timeout.episode",
"60",
]
def test_expand_shorthands_requires_a_value() -> None:
-31
View File
@@ -1,7 +1,6 @@
from types import SimpleNamespace
import orjson
import pytest
from prime_rl.eval import resume
from prime_rl.monitors.file.traces import get_trace_stream
@@ -64,28 +63,6 @@ def test_trigger_queues_only_owed_rollouts() -> None:
]
def test_check_config_allows_selection_changes_only() -> None:
previous = {
"model": "a",
"num_examples": 8,
"group_size": 2,
"sampling": {"temperature": 1.0},
"source": [{"env": {"taskset": {"id": "gsm8k"}}, "group_size": None, "serve": {"address": None}}],
}
resized = {
**previous,
"num_examples": 16,
"group_size": 4,
"source": [{"env": {"taskset": {"id": "gsm8k"}}, "group_size": 8, "serve": {"address": "tcp://x"}}],
}
resume.check_config(previous, resized)
with pytest.raises(ValueError, match="model, sampling.temperature"):
resume.check_config(previous, {**previous, "model": "b", "sampling": {"temperature": 0.5}})
with pytest.raises(ValueError, match="source"):
resume.check_config(previous, {**previous, "source": previous["source"] * 2})
def test_take_landed_reads_every_attempt_once(tmp_path) -> None:
def land(*keys: str) -> None:
stream = ChunkedJsonl(get_trace_stream(tmp_path), max_bytes=1 << 20, compress=False)
@@ -102,11 +79,3 @@ def test_take_landed_reads_every_attempt_once(tmp_path) -> None:
land("m0", "m2")
assert [record["id"] for record in resume.take_landed(tmp_path)] == ["m0", "m1", "m2"]
assert [path.name for path in resume.archives(tmp_path)] == ["file.attempt_1", "file.attempt_2"]
def test_previous_config_is_the_one_stamped_beside_the_results(tmp_path) -> None:
resume.stamp_config(tmp_path, {"model": "a"})
resume.take_landed(tmp_path) # the attempt that ran is archived; a rejected one never stamps
assert resume.previous_config(tmp_path) == {"model": "a"}
resume.stamp_config(tmp_path, {"model": "b"})
assert resume.previous_config(tmp_path) == {"model": "b"}
@@ -0,0 +1,79 @@
import copy
from vllm.tokenizers.deepseek_v4_encoding import encode_messages
from prime_rl.inference.patches import monkey_patch_deepseek_v4_request_tools_placement
class _StubTokenizer:
def get_added_vocab(self):
return {}
def encode(self, text, **_kwargs):
return text
def _request_tools():
return [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}
]
def _tokenizer():
from vllm.tokenizers import deepseek_v4
monkey_patch_deepseek_v4_request_tools_placement()
return deepseek_v4.get_deepseek_v4_tokenizer(_StubTokenizer())
def _render(messages, tools):
return _tokenizer().apply_chat_template(
messages,
tools=tools,
tokenize=False,
thinking=True,
reasoning_effort="low",
)
def _reference(messages):
return encode_messages(messages, thinking_mode="thinking", reasoning_effort="low")
def test_request_tools_attach_to_first_existing_system_without_mutation():
messages = [
{"role": "user", "content": "This may precede the system message."},
{"role": "system", "content": "You are helpful.", "tools": []},
{"role": "system", "content": "A later system message."},
{"role": "user", "content": "Weather in Paris?"},
]
snapshot = copy.deepcopy(messages)
tools = _request_tools()
prompt = _render(messages, tools)
expected_messages = messages.copy()
expected_messages[1] = {**messages[1], "tools": tools}
assert prompt == _reference(expected_messages)
assert prompt.count("## Tools") == 1
assert messages == snapshot
def test_request_tools_synthesize_system_only_when_none_exists():
messages = [{"role": "user", "content": "Weather in Paris?"}]
tools = _request_tools()
prompt = _render(messages, tools)
assert prompt == _reference([{"role": "system", "tools": tools}, *messages])
+6 -8
View File
@@ -4,7 +4,8 @@ The full happy-path is owned upstream by vLLM's
``vllm/entrypoints/serve/disagg`` test suite. We only cover the prime-RL
deltas here:
* ``serialize_routed_experts`` round-trips a compact raw-byte payload.
* The subclass attaches its overrides without monkey-patching the parent.
* The subclass overrides ``serve_tokens_full_generator`` without
monkey-patching the parent.
* ``post_process`` swaps in the compact routed_experts while preserving
the rest of the upstream response (``usage`` included).
"""
@@ -13,8 +14,8 @@ from __future__ import annotations
import numpy as np
import pybase64
from vllm.entrypoints.openai.engine.protocol import UsageInfo
from vllm.entrypoints.scale_out.token_in_token_out.protocol import GenerateResponse, GenerateResponseChoice
from vllm.entrypoints.serve.engine.protocol import UsageInfo
from prime_rl.inference.vllm.routed_experts import serialize_routed_experts
from prime_rl.inference.vllm.serving_tokens import (
@@ -35,12 +36,9 @@ async def _empty_request_outputs():
yield
def test_subclass_only_overrides_serve_tokens():
assert PrimeRlServingTokens.serve_tokens is not PrimeRlServingTokens.__mro__[1].serve_tokens
assert (
PrimeRlServingTokens.serve_tokens_full_generator
is not PrimeRlServingTokens.__mro__[1].serve_tokens_full_generator
)
def test_subclass_overrides_serve_tokens_full_generator():
upstream = PrimeRlServingTokens.__mro__[1]
assert PrimeRlServingTokens.serve_tokens_full_generator is not upstream.serve_tokens_full_generator
def test_serialize_routed_experts_uses_compact_raw_payload():
+2
View File
@@ -22,6 +22,7 @@ def mk(
num_turns: int = 1,
num_branches: int = 1,
is_truncated: bool = False,
is_timeout: bool = False,
is_completed: bool = True,
has_error: bool = False,
error_type: str = "error",
@@ -51,6 +52,7 @@ def mk(
num_turns=num_turns,
num_branches=num_branches,
is_truncated=is_truncated,
is_timeout=is_timeout,
is_completed=is_completed,
has_error=has_error,
last_error=SimpleNamespace(type=error_type) if has_error else None,
+1
View File
@@ -140,6 +140,7 @@ def test_to_namespace_resolves_parsers():
assert ns.tool_call_parser == "deepseek_v32"
assert ns.reasoning_parser == "deepseek_r1"
assert ns.enable_auto_tool_choice is True
assert ns.enable_ep_weight_filter is True
def test_to_namespace_none_strips_parser_attrs_from_namespace():
@@ -63,6 +63,10 @@ def test_selective_policy_saves_default_and_custom_targets():
_selective_checkpoint_policy(context, torch.ops.aten.topk.default, targets=custom_targets)
is CheckpointPolicy.MUST_SAVE
)
assert (
_selective_checkpoint_policy(context, torch.ops.prime_rl.fp8_indexer.default, targets=custom_targets)
is CheckpointPolicy.MUST_SAVE
)
@pytest.mark.parametrize("mode", ["full", "selective"])
@@ -99,6 +103,7 @@ def test_mandatory_policy_only_retains_non_replayable_ops():
context = SelectiveCheckpointContext(is_recompute=False)
assert _mandatory_checkpoint_policy(context, torch.ops.aten.topk.default) is CheckpointPolicy.MUST_SAVE
assert _mandatory_checkpoint_policy(context, torch.ops.prime_rl.fp8_indexer.default) is CheckpointPolicy.MUST_SAVE
assert (
_mandatory_checkpoint_policy(context, torch.ops.prime_rl.record_moe_routing_statistics.default)
is CheckpointPolicy.MUST_SAVE
+3 -4
View File
@@ -164,7 +164,7 @@ def prime_attention(layer_idx: int, dtype: torch.dtype = torch.bfloat16) -> nn.M
bit-identical to one from a config carrying only the attention keys.
"""
with torch.device("cuda"), default_dtype(dtype):
module = DeepseekV4Attention(MODEL_CONFIG, layer_idx=layer_idx)
module = DeepseekV4Attention(MODEL_CONFIG, layer_idx, DeepseekV4RotaryEmbedding(MODEL_CONFIG))
_randomize(module)
eager_reference.use_eager_attention(module)
return module
@@ -189,15 +189,14 @@ def _packed_context(doc_lens: tuple[int, ...], dtype: torch.dtype) -> PackedCont
"""The context `DeepseekV4Model` would hand its attention layers for a row of `doc_lens`.
A single-element `doc_lens` gives back the single-document context, which is what the unpacked
half of a packing comparison runs at. `dtype` types the mask and the rotary tables, and has to
be the one the caller runs at.
half of a packing comparison runs at. `dtype` is the default dtype the rotary embedding is built
under; the RoPE tables themselves are always fp32.
"""
with torch.device("cuda"), default_dtype(dtype):
rotary = DeepseekV4RotaryEmbedding(MODEL_CONFIG)
return PackedContext.build(
rotary_emb=rotary,
seq_lens=torch.tensor(doc_lens, device="cuda"),
dtype=dtype,
device=torch.device("cuda"),
)
@@ -11,10 +11,15 @@ from torch.utils._python_dispatch import TorchDispatchMode
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, eager_reference
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.deepseek_v4.eager_reference import (
apply_rotary_pos_emb_interleaved,
dense_mask_from_indices,
eager_attention_with_sinks,
)
from prime_rl.trainer.models.deepseek_v4.hyperconnections import DeepseekV4HyperConnection, DeepseekV4UnweightedRMSNorm
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT, dsv4_mhc
from prime_rl.trainer.models.kernels.deepseek_v4.dsv4_rope import dsv4_q_norm_rope, dsv4_rope
from prime_rl.utils.cp import CPContext
from prime_rl.utils.utils import default_dtype
@@ -87,8 +92,8 @@ def _packed_context(
"""The context `DeepseekV4Model` would hand its attention layers for a row of `doc_lens`.
A single-element `doc_lens` gives back the single-document context, which is what the unpacked
half of a packing comparison runs at. `dtype` types the mask and the rotary tables, and has to
be the one the caller runs at.
half of a packing comparison runs at. `dtype` is the default dtype the rotary embedding is built
under; the RoPE tables themselves are always fp32.
`doc_lens` always describes the whole row, `cp_world_size` shards included: the context
parallel tests below hand it the same layout every rank sees and vary only `cp_rank`.
@@ -98,7 +103,6 @@ def _packed_context(
return PackedContext.build(
rotary_emb=rotary,
seq_lens=torch.tensor(doc_lens, device="cuda"),
dtype=dtype,
device=torch.device("cuda"),
cp_rank=cp_rank,
cp_world_size=cp_world_size,
@@ -537,7 +541,7 @@ V4FLASH_DOC_IDS = ["two-docs", "no-entries", "one-short-doc", "three-docs", "sat
def v4flash_attention(layer_idx: int, dtype: torch.dtype = torch.float32, eager: bool = False) -> nn.Module:
"""One attention layer at the real DeepSeek V4 Flash shapes, 126M parameters of it."""
with torch.device("cuda"), default_dtype(dtype):
module = DeepseekV4Attention(V4FLASH_CONFIG, layer_idx=layer_idx)
module = DeepseekV4Attention(V4FLASH_CONFIG, layer_idx, DeepseekV4RotaryEmbedding(V4FLASH_CONFIG))
_randomize(module)
if eager:
eager_reference.use_eager_attention(module)
@@ -642,7 +646,7 @@ def test_deepseek_v4_refuses_a_shape_the_kernel_cannot_tile():
"""The constructor refuses a head count the kernels cannot tile, rather than the first forward."""
config = DeepseekV4Config(**{**V4FLASH_MODEL, "num_attention_heads": 16})
with pytest.raises(ValueError, match="cannot run the fused sparse-attention kernel"):
DeepseekV4Attention(config, layer_idx=V4FLASH_CSA_LAYER)
DeepseekV4Attention(config, V4FLASH_CSA_LAYER, DeepseekV4RotaryEmbedding(config))
@requires_sparse_attn_kernel
@@ -1167,9 +1171,11 @@ def _cp_gathered_projections(
"""
# One context per rank, not one per gather: a rank's gathers all read the same tables.
rope_tables = [
_packed_context(doc_lens, dtype, config, cp_rank=cp_rank, cp_world_size=cp_world_size).position_embeddings[
module.rope_layer_type
]
module.rotary_emb(
_packed_context(doc_lens, dtype, config, cp_rank=cp_rank, cp_world_size=cp_world_size).position_ids,
module.rope_layer_type,
dtype=torch.float32,
)
for cp_rank in range(cp_world_size)
]
@@ -1246,6 +1252,12 @@ def test_context_parallel_shards_reproduce_the_whole_row(layer_idx, cp_world_siz
for cp_rank, chunk in enumerate(chunks):
gather, pending = _fake_gather_for_cp(projections, chunks, cp_rank)
monkeypatch.setattr(dsv4_attention, "gather_for_cp", gather)
monkeypatch.setattr(
torch.ops._c10d_functional,
"all_gather_into_tensor",
lambda tensor, group_size, group_name: gather(tensor.movedim(0, 1), None).movedim(1, 0).contiguous(),
)
monkeypatch.setattr(dsv4_attention.funcol, "wait_tensor", lambda tensor: tensor)
module.cp_context = CPContext(MagicMock(), cp_rank, cp_world_size, "ring")
packed = _packed_context(doc_lens, torch.float32, V4FLASH_CONFIG, cp_rank=cp_rank, cp_world_size=cp_world_size)
@@ -1319,3 +1331,98 @@ def test_fused_post_bda_matches_the_eager_reference():
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)
ROPE_DIM = V4FLASH_MODEL["qk_rope_head_dim"]
def _rope_positions() -> torch.Tensor:
"""Three packed documents, the last starting deep into a long rollout: positions reset and reach ~128k."""
return torch.cat([torch.arange(700), torch.arange(1500), torch.arange(129000, 130896)]).cuda()
def _rope_table(n_rows: int) -> torch.Tensor:
"""A plain fp32 `[cos | sin]` table in vLLM's layout, one entry per interleaved pair."""
inv_freq = 1.0 / (V4FLASH_MODEL["rope_theta"] ** (torch.arange(0, ROPE_DIM, 2, dtype=torch.float32) / ROPE_DIM))
freqs = torch.outer(torch.arange(n_rows, dtype=torch.float32), inv_freq)
return torch.cat([freqs.cos(), freqs.sin()], dim=-1).cuda()
@pytest.mark.parametrize("inverse", [False, True], ids=["forward", "inverse"])
def test_dsv4_rope_matches_vllm_bit_for_bit(inverse):
"""The kernel and vLLM's in-place `rotary_embedding` op agree on every bit, nope channels included.
Both read the same table, so this isolates the rotation: fp32 math on a bf16 input, one rounding
on store, and the same multiply-add contraction.
"""
vllm_ops = pytest.importorskip("vllm._custom_ops")
positions = _rope_positions()
cos_sin = _rope_table(int(positions.max()) + 1)
heads, head_dim = V4FLASH_MODEL["num_attention_heads"], V4FLASH_MODEL["head_dim"]
x = torch.randn(positions.numel(), heads, head_dim, device="cuda", dtype=torch.bfloat16)
expected = x.clone()
vllm_ops.rotary_embedding(
positions, expected, None, head_dim, cos_sin, False, rope_dim_offset=head_dim - ROPE_DIM, inverse=inverse
)
actual = dsv4_rope(x.clone(), cos_sin, positions, inverse=inverse)
assert torch.equal(actual, expected)
def test_q_norm_rope_matches_vllm_fused_prefill_kernel():
"""q matches vLLM's fused prefill q norm + RoPE to the last ulp, and the kv rotation bit for bit.
vLLM rounds q to bf16 once after an fp32 RMSNorm and rotation, as `dsv4_q_norm_rope` does. The norm's
reduction order differs, so a few elements per million land one ulp apart.
"""
pytest.importorskip("vllm._custom_ops")
positions = _rope_positions()
cos_sin = _rope_table(int(positions.max()) + 1)
n_tokens, heads, head_dim = positions.numel(), V4FLASH_MODEL["num_attention_heads"], V4FLASH_MODEL["head_dim"]
eps, block_size = V4FLASH_MODEL["rms_norm_eps"], 64
q = torch.randn(n_tokens, heads, head_dim, device="cuda", dtype=torch.bfloat16)
kv = torch.randn(n_tokens, head_dim, device="cuda", dtype=torch.bfloat16)
kv_cache = torch.zeros(n_tokens // block_size, block_size, head_dim, device="cuda", dtype=torch.bfloat16)
expected_q = q.clone()
torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_full_cache_bf16_insert(
expected_q, kv, kv_cache, torch.arange(n_tokens, device="cuda"), positions, cos_sin, eps, block_size
)
rotated_q = dsv4_q_norm_rope(q, cos_sin, positions, eps)
assert (rotated_q != expected_q).float().mean() < 1e-5
_assert_relative(rotated_q, expected_q, torch.finfo(torch.bfloat16).eps, "q")
rotated_kv = dsv4_rope(kv.clone().unsqueeze(1), cos_sin, positions)
assert torch.equal(rotated_kv, kv_cache.view(n_tokens, 1, head_dim))
def test_q_norm_rope_matches_the_composed_norm_and_rotation():
"""Bit for bit with an fp32 RMSNorm, the rotation and one bf16 cast, eager and compiled.
Gradients agree with the composed ops to bf16 precision rather than bit for bit: the composed
backward carries an fp32 gradient through the rotation, where `dsv4_q_norm_rope` keeps it in bf16.
"""
positions = _rope_positions()
cos_sin = _rope_table(int(positions.max()) + 1)
heads, head_dim = V4FLASH_MODEL["num_attention_heads"], V4FLASH_MODEL["head_dim"]
eps = V4FLASH_MODEL["rms_norm_eps"]
leaf = torch.randn(1, positions.numel(), heads, head_dim, device="cuda", dtype=torch.bfloat16)
fused_leaf, compiled_leaf, composed_leaf = _leaves(leaf, leaf, leaf)
weight = torch.randn_like(leaf, dtype=torch.float32)
def composed(q: torch.Tensor) -> torch.Tensor:
normed = DeepseekV4UnweightedRMSNorm(eps=eps, out_dtype=torch.float32)(q)
return dsv4_rope(normed, cos_sin, positions).to(q.dtype)
fused = dsv4_q_norm_rope(fused_leaf * 1, cos_sin, positions, eps)
compiled = torch.compile(lambda q: dsv4_q_norm_rope(q * 1, cos_sin, positions, eps), fullgraph=True)(compiled_leaf)
expected = composed(composed_leaf * 1)
for out in (fused, compiled, expected):
(out.float() * weight).sum().backward()
assert fused.dtype == torch.bfloat16
assert torch.equal(fused, expected)
assert torch.equal(compiled, fused)
assert torch.equal(compiled_leaf.grad, fused_leaf.grad)
_assert_relative(fused_leaf.grad, composed_leaf.grad, torch.finfo(torch.bfloat16).eps, "q gradient")
+22
View File
@@ -47,3 +47,25 @@ def test_token_tp_cast_matches_materialized_transpose(rows, cols):
assert tp_q.is_contiguous()
assert torch.equal(tp_q.view(torch.uint8), ref_q.view(torch.uint8))
assert torch.equal(tp_s, ref_s)
@pytest.mark.parametrize(
"rows,cols,input_scale",
[(256, 256, 1.0), (256, 512, 0.3), (512, 256, 0.02), (1024, 768, 0.02), (384, 128, 0.005)],
)
def test_token_cast_matches_vllm_cuda_quant(rows, cols, input_scale):
"""The per-token cast is *bit-identical* to vLLM's production CUDA quantizer."""
pytest.importorskip("vllm")
from vllm.model_executor.layers.quantization.utils.fp8_utils import per_token_group_quant_fp8
torch.manual_seed(rows + cols)
x = torch.randn(rows, cols, device="cuda", dtype=torch.bfloat16) * input_scale
assert x.is_contiguous()
ref_q, ref_s = per_token_group_quant_fp8(x, 128, use_ue8m0=False)
q, s = per_token_cast_to_fp8_triton(x, False)
assert q.shape == ref_q.shape == (rows, cols)
assert s.shape == ref_s.shape == (rows, cols // 128)
assert torch.equal(s, ref_s)
assert torch.equal(q.view(torch.uint8), ref_q.view(torch.uint8))
@@ -125,6 +125,17 @@ def test_nemotron_h_context_parallel_setup_finds_wrapped_mamba_layer():
assert mamba_layer.mamba.cp_context.cp_world_size == 2
def test_nemotron_h_mamba_parameters_follow_default_dtype():
config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
with torch.device("meta"), default_dtype(torch.bfloat16):
model = NemotronHForCausalLM(config)
mamba = model.model.layers[0].mamba
assert isinstance(mamba, NemotronHMamba2)
assert mamba.A_log.dtype == torch.bfloat16
assert mamba.D.dtype == torch.bfloat16
def test_nemotron_h_no_latent_projection():
"""Verify model works without latent projections (moe_latent_size=None)."""
prime_config = NemotronHConfig(
+1 -1
View File
@@ -181,7 +181,7 @@ def test_dataloader_shards_across_ranks_and_workers(
)
dataset = SFTDataset(
raw_dataset,
dummy_renderer,
lambda _: dummy_renderer,
shuffle=False,
seq_len=config.seq_len,
non_dp_size=non_dp_size,
+18 -18
View File
@@ -51,7 +51,7 @@ def test_drop_null_fields_preserves_tool_call_arguments(arguments):
def test_init_sft_dataset(build_dummy_dataset, dummy_renderer):
"""Tests basic initialization."""
dataset = build_dummy_dataset("a", 1)
sft_dataset = SFTDataset(dataset, dummy_renderer)
sft_dataset = SFTDataset(dataset, lambda _: dummy_renderer)
assert sft_dataset is not None
@@ -59,7 +59,7 @@ def test_raise_error_if_no_prompt_and_completion(build_dummy_dataset):
"""Tests that an error is raised if no supported SFT message fields are provided."""
dataset = Dataset.from_list([{"text": "a0"}])
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
sft_dataset = SFTDataset(dataset, create_renderer(tokenizer))
sft_dataset = SFTDataset(dataset, lambda _: create_renderer(tokenizer))
with pytest.raises(ValueError):
next(iter(sft_dataset))
@@ -70,7 +70,7 @@ def test_sft_first_exhausted(build_dummy_dataset, dummy_renderer, max_epochs: in
b = build_dummy_dataset("b", 2)
ds = [a, b]
dataset = interleave_datasets(ds, stopping_strategy="first_exhausted")
dataset = SFTDataset(dataset, dummy_renderer, shuffle=False, max_epochs=max_epochs)
dataset = SFTDataset(dataset, lambda _: dummy_renderer, shuffle=False, max_epochs=max_epochs)
num_samples = 0
sampling_order = []
for x in dataset:
@@ -86,7 +86,7 @@ def test_sft_all_exhausted(build_dummy_dataset, dummy_renderer, max_epochs: int)
b = build_dummy_dataset("b", 2)
ds = [a, b]
dataset = interleave_datasets(ds, stopping_strategy="all_exhausted")
dataset = SFTDataset(dataset, dummy_renderer, shuffle=False, max_epochs=max_epochs)
dataset = SFTDataset(dataset, lambda _: dummy_renderer, shuffle=False, max_epochs=max_epochs)
num_samples = 0
sampling_order = []
for x in dataset:
@@ -120,7 +120,7 @@ def test_sft_all_exhausted_with_probs(build_dummy_dataset, dummy_renderer, probs
b = build_dummy_dataset("b", int(10e3))
ds = [a, b]
dataset = interleave_datasets(ds, stopping_strategy="all_exhausted", probabilities=probs)
dataset = SFTDataset(dataset, dummy_renderer, shuffle=False, max_epochs=1)
dataset = SFTDataset(dataset, lambda _: dummy_renderer, shuffle=False, max_epochs=1)
num_samples = 0
sampling_freq = []
for x in dataset:
@@ -140,7 +140,7 @@ def test_sft_all_exhausted_with_probs(build_dummy_dataset, dummy_renderer, probs
def test_sft_dataset_state(build_dummy_dataset, dummy_renderer):
"""Tests the state of the dataset within and across epochs."""
dataset = build_dummy_dataset("", 4)
dataset = SFTDataset(dataset, dummy_renderer, shuffle=False, max_epochs=2)
dataset = SFTDataset(dataset, lambda _: dummy_renderer, shuffle=False, max_epochs=2)
dataiter = iter(dataset)
# Initial state
@@ -166,7 +166,7 @@ def test_sft_dataset_state_resume(build_dummy_dataset, dummy_renderer):
"""Tests resuming the dataset from checkpoint in between epochs."""
dataset = SFTDataset(
build_dummy_dataset("", 4),
dummy_renderer,
lambda _: dummy_renderer,
shuffle=False,
max_epochs=2,
)
@@ -186,7 +186,7 @@ def test_sft_dataset_state_resume(build_dummy_dataset, dummy_renderer):
del dataset
dataset = SFTDataset(
build_dummy_dataset("", 4),
dummy_renderer,
lambda _: dummy_renderer,
shuffle=False,
max_epochs=2,
)
@@ -204,7 +204,7 @@ def test_sft_dataset_state_resume(build_dummy_dataset, dummy_renderer):
del dataset
dataset = SFTDataset(
build_dummy_dataset("", 4),
dummy_renderer,
lambda _: dummy_renderer,
shuffle=False,
max_epochs=2,
)
@@ -235,7 +235,7 @@ def test_multiturn_loss_mask():
]
)
tokenizer = AutoTokenizer.from_pretrained("PrimeIntellect/Qwen3-0.6B") # Properly handles multi-turn think
dataset = SFTDataset(dataset, create_renderer(tokenizer), max_examples=1)
dataset = SFTDataset(dataset, lambda _: create_renderer(tokenizer), max_examples=1)
sample = next(iter(dataset))
print_sample(sample["input_ids"], sample["loss_mask"], tokenizer)
@@ -298,7 +298,7 @@ def test_multiturn_loss_mask_with_tools():
dataset = Dataset.from_list([tool_example])
tokenizer = AutoTokenizer.from_pretrained("PrimeIntellect/Qwen3-0.6B") # Properly handles multi-turn think
dataset = SFTDataset(dataset, create_renderer(tokenizer), max_examples=1)
dataset = SFTDataset(dataset, lambda _: create_renderer(tokenizer), max_examples=1)
sample = next(iter(dataset))
print_sample(sample["input_ids"], sample["loss_mask"], tokenizer)
@@ -325,12 +325,12 @@ def test_messages_rows_are_equivalent_to_empty_prompt_completion():
tokenizer = AutoTokenizer.from_pretrained("PrimeIntellect/Qwen3-0.6B")
messages_dataset = SFTDataset(
Dataset.from_list([{"messages": messages}]),
create_renderer(tokenizer),
lambda _: create_renderer(tokenizer),
max_examples=1,
)
split_dataset = SFTDataset(
Dataset.from_list([{"prompt": [], "completion": messages}]),
create_renderer(tokenizer),
lambda _: create_renderer(tokenizer),
max_examples=1,
)
@@ -351,12 +351,12 @@ def test_messages_take_precedence_over_prompt_and_completion():
messages_dataset = SFTDataset(
Dataset.from_list([row]),
create_renderer(tokenizer),
lambda _: create_renderer(tokenizer),
max_examples=1,
)
expected_dataset = SFTDataset(
Dataset.from_list([{"prompt": [], "completion": row["messages"]}]),
create_renderer(tokenizer),
lambda _: create_renderer(tokenizer),
max_examples=1,
)
@@ -372,12 +372,12 @@ def test_null_messages_falls_back_to_prompt_and_completion():
mixed_row_dataset = SFTDataset(
Dataset.from_list([{"messages": None, "prompt": prompt, "completion": completion}]),
create_renderer(tokenizer),
lambda _: create_renderer(tokenizer),
max_examples=1,
)
expected_dataset = SFTDataset(
Dataset.from_list([{"prompt": prompt, "completion": completion}]),
create_renderer(tokenizer),
lambda _: create_renderer(tokenizer),
max_examples=1,
)
@@ -399,7 +399,7 @@ def test_vlm_truncation_does_not_append_trainable_eos(monkeypatch, dummy_rendere
)
monkeypatch.setattr(sft_data, "build_training_sample", fake_build_training_sample)
dataset = SFTDataset(Dataset.from_list([]), dummy_renderer, seq_len=2, multimodal=True)
dataset = SFTDataset(Dataset.from_list([]), lambda _: dummy_renderer, seq_len=2, multimodal=True)
assert dataset._process({"messages": [{"role": "assistant", "content": "ignored"}]}) is None
Generated
+332 -401
View File
File diff suppressed because it is too large Load Diff