Compare commits

...
Author SHA1 Message Date
faresobeidandGitHub c5406f8d09 perf(examples): use cudnn_flashmla DSA backend in GLM-5.3 RL example (#3968)
Sets `dsa_backend = "cudnn_flashmla"` for the trainer in the GLM-5.3 RL
example (`examples/advanced/glm-5.3/swe.toml`). The SFT example already
uses it (#3829); the RL example still ran the TileLang forward and
backward.

Measured on 1x8 H200 with the trainer settings of `swe.toml` (131k seq,
cp 4, ep 8, fp8 + `deepgemm_fp8`, full AC + offload, compile). Random
init, 8 layers (3 dense + 5 MoE), fake data, 2 micro-batches per dp
rank, balanced routing:

| `dsa_backend` | step 2 / 3 | sparse attn fwd per call | sparse attn
bwd per call |
|---|---|---|---|
| `tilelang` | 16.6 s / 15.5 s | 35 ms | 190 ms |
| `cudnn_flashmla` | 12.8 s / 12.1 s | 12 ms | 53 ms |

- Entropy and mismatch KL are identical to 4 decimals.
- With a 4-layer run (5.7 s), one MoE layer costs 1.6 s instead of 2.07
s. Extrapolated to 78 layers at this shape: ~124 s vs ~160 s per step
(-22%).
- Kernel check at the CP shape (8k local queries vs 32k keys, cp rank 0
and 3, top-k 2048, sentinel slots): out / dq / dkv relative error vs
TileLang 5e-4 to 9e-4, LSE 7e-8.
- Needs the `flash-mla` extra, which the README's `uv sync --all-extras`
installs.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Single example TOML knob with no production code changes; requires the
optional flash-mla dependency for the new backend.
> 
> **Overview**
> Aligns the GLM-5.3 RL example trainer config with the SFT example by
setting **`dsa_backend = "cudnn_flashmla"`** in
`examples/advanced/glm-5.3/swe.toml`, so sparse DSA attention uses the
cuDNN/FlashMLA path instead of the default TileLang forward/backward.
> 
> This is a **performance-only** example change for long-context RL
training (131k seq, CP/EP, fp8 MoE); behavior should match TileLang
within measured numerical tolerance when the `flash-mla` extra is
installed.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e2135c38262af40b51d866026cdfa3a83fb7c7b4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 18:29:07 +01:00
Florian BrandandGitHub 9b39a10949 refactor(sampling): share parameter resolution across eval and training (#3782)
Use Verifiers' shared sampling config and resolution path for evaluation
and rollout dispatch. Parameter names, provider options, source
defaults, and agent overrides follow the same rules in native Verifiers
and Prime-RL. Training retains its strict config for the distribution
the trainer replays.

## Sampling flow

```mermaid
flowchart TD
    T["Train source and agent config<br/>TrainSamplingConfig and replay bounds"] --> V["Validate live-policy sampling<br/>Source owns the distribution"]
    V --> S["Shared Verifiers SamplingConfig<br/>Normalize aliases and extra_body"]
    V --> A["AgentConfig.sampling<br/>Sparse overrides across config transport"]
    E["Eval source and agent config"] --> S
    E --> A
    S --> R["RunRequest to env server"]
    A --> M["Verifiers resolve_agent<br/>Shared merge_defaults"]
    R --> M
    M --> P["Provider request<br/>Non-null resolved parameters"]
    M --> C["Trace<br/>Complete resolved sampling"]
```

## Shared parameters

Verifiers normalizes `max_tokens` / `max_completion_tokens` and flattens
`extra_body` before merging each override layer. Source values replace
group defaults; agent values replace inherited sampling. An explicit
null clears an inherited parameter.

Within one sampling block, top-level values take precedence over
`extra_body`. A typed training `top_k=20`, or the automatic replay bound
of `512`, therefore takes precedence over `extra_body.top_k=-1`. With no
typed `top_k`, the disabled sentinel remains effective.

Prime-RL carries `vf.SamplingConfig` through dispatch and converts
`TrainSamplingConfig` once. Source defaults and agent overrides use
Verifiers' `merge_defaults`; duplicate eval schemas and
sampling-dictionary converters are removed. Request-specific cache salts
are copied onto the shared config.

Unresolved agent overrides remain sparse across env-server config
boundaries. `resolve_agent` materializes the sampling used for
generation, and traces record the complete resolved config. Provider
dialects and the renderer client omit nulls when constructing requests.

## Training ownership

Live-policy sources validate their sampling when the config loads.
Unsupported source parameters, including `frequency_penalty`, are
rejected before generation.

The source owns the distribution replayed by the trainer. Every agent in
a live-policy source, including non-trainable roles, may override only
`max_tokens`, `reasoning_effort`, and `chat_template_kwargs`.
Distribution parameters belong on the source, even when an agent would
repeat the same value. Policy logprobs remain enabled. Evaluation and
frozen-model sources retain general agent overrides.

This removes the post-rollout sampling comparison from `TrainSink`.

## Dependency

Pins Verifiers `2cb0a6d`, the merged commit for [Verifiers
#2762](https://github.com/PrimeIntellect-ai/verifiers/pull/2762), for
shared sampling normalization and resolution. This includes merging
per-call judge sampling overrides before constructing SDK requests,
preserving unrelated configured provider parameters. The lockfile
updates `prime-tunnel` to `0.1.14` to meet the merged dependency's
minimum.

Before publishing packages outside this source checkout, release that
Verifiers change and raise the `verifiers` minimum in both `prime-rl`
and `prime-rl-configs`. The current `>=0.3.2.dev158` package constraints
do not guarantee these semantics.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how sampling is resolved and validated for all rollouts;
mis-merged configs or rejected agent overrides could break existing
TOMLs, though unit tests cover the main inheritance and policy rules.
> 
> **Overview**
> **Unifies rollout sampling** on Verifiers' shared `SamplingConfig` and
merge rules instead of Prime-RL–specific eval schemas and
`to_sampling_args()` dict builders.
> 
> Eval sources and group defaults now use `vf.SamplingConfig`;
train/eval env wrappers carry a typed `SamplingConfig` through to the
env server (including per-request `cache_salt` via `model_copy`). Policy
train sources get **load-time validation**: the source owns distribution
parameters (`temperature`, `top_p`, etc.), while agents may only
override `max_tokens`, `reasoning_effort`, and
`chat_template_kwargs`—frozen-model and eval paths stay permissive.
`TrainSink` reads temperature from `env.config.sampling` instead of a
resolved args dict.
> 
> **Docs** describe alias normalization (`max_tokens` /
`max_completion_tokens`), `extra_body` merging, and live-policy override
limits. **Tests** cover inherited sampling merges and policy sampling
rejection cases. Lockfile bumps `prime-tunnel` to `0.1.14`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
671a5aa9857a39a4d44fa7902f1c89021b8fd380. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 00:30:12 -07:00
Florian BrandandGitHub f7e8ab6456 fix(eval): resume rollouts by task content and selected occurrence (#3808) 2026-10-09 15:47:46 -07:00
84e94bf05c perf(orchestrator): poll for new weight versions every 0.1s instead of 1s (#3952)
## Summary
- `WeightWatcher.poll_interval` default: 1.0s → 0.1s
- `WeightReceiver.wait_published` sleep: 0.2s → 0.1s

## Why
The trainer blocks in `WeightSender._wait_for_receiver_ready` until the
orchestrator notices `.sender_ready`. With a 1s poll, that adds 0–1s
(~0.5s avg) of idle trainer time on every step. NVIDIA flagged this
while benchmarking the ModelExpress broadcast (#3890).

A poll is one `glob("step_*")` on the broadcast dir (≤2 entries thanks
to `_clean`) plus a few `exists()` calls, so 10Hz is negligible.
Correctness relies on the marker handshake + `update_lock`, not on the
poll timing.

Caveat: these are sync FS calls on the orchestrator event loop. On a
very slow shared FS, that might show up in `EventLoopLagMonitor`. If it
does, we can move them to `asyncio.to_thread`.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Timing-only tuning on poll loops; no change to weight handshake logic,
though more frequent sync FS calls could add event-loop lag on very slow
filesystems.
> 
> **Overview**
> **Faster weight-version discovery** so the trainer spends less time
blocked waiting for the orchestrator to see `.sender_ready`.
> 
> The orchestrator `WeightWatcher` default `poll_interval` drops from
**1.0s to 0.1s**, cutting typical idle wait on each broadcast handshake
from ~0.5s toward ~0.05s. `WeightReceiver.wait_published` uses the same
**0.1s** sleep (was 0.2s) while waiting for the sender marker.
> 
> Handshake correctness is unchanged (markers + `update_lock`); cost is
slightly more frequent lightweight FS checks on the orchestrator event
loop.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5c825d0f126e16885eae77f4f6ebc2ddf306de59. 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-10-09 10:25:55 -07:00
IanandGitHub 37b48a996e security(ci): pin BuildKit builder to v0.33.1 and rotate registry buildcache (CVE-2026-93318) (#3889)
## security(ci): pin BuildKit builder to v0.33.1 and rotate the GHCR
registry buildcache (CVE-2026-93318)

### What changed (rebased onto current main)
`.github/workflows/build_image.yaml`:
1. **Builder pin** — `docker/setup-buildx-action@v4` now sets
`driver-opts: image=moby/buildkit:v0.33.1`. Without it the job starts
the rolling `moby/buildkit:buildx-stable-1` tag, and because these are
persistent self-hosted runners (`image-builder`,
`image-builder-arm-2204`), the builder version is not even guaranteed to
follow the tag — a stale local image can keep a pre-patch builder alive
indefinitely. The pin makes the builder version deterministic.
2. **Registry cache rotation** — both shared cache refs rotated:
- `:dependency-buildcache-<suffix>` ->
`:dependency-buildcache-v2-<suffix>`
- `:application-buildcache-<suffix>` ->
`:application-buildcache-v2-<suffix>`

### Why rotation (evidence)
- The registry-backed cache was introduced in d8f3d0101 (2026-08-16,
#3279) and has been written on nearly every run since — including all
runs before the patch was published.
- BuildKit v0.33.1 (the CVE fix) was released **2026-09-30T17:08Z**; the
rolling `moby/buildkit:buildx-stable-1` tag only moved to that digest at
**2026-09-30T17:32Z**. Every cache write before that timestamp came from
a builder older than v0.33.1, on runners that may also hold stale local
images.
- Per the CVE-2026-93318 playbook: stop importing a shared cache that
pre-fix builders wrote, rebuild from trusted inputs, and pin the patched
builder so every future write is attributable to a fixed version.

### Expected cost
The first run per platform suffix after merge does a cold build of the
dependency layer + application layer (no cache import). The old
`*-buildcache-*` tags can be deleted from the `prime-rl` GHCR package as
cleanup — they are cache-only refs, never deployed.

### Out of scope / notes
- `docker-push.yaml` (old Docker Hub publisher) no longer exists on main
— nothing to pin there.
- No GHA-scope (`type=gha`) caches exist in this repo's workflows
(verified by grep), so no Actions-cache cleanup applies.
- Build image runs are frequent and mostly manual dispatch; this PR
should merge before the next `main` image build.

### Security review requested
- Cache invalidation: confirm the `*-v2-*` refs fully replace the old
buildcache lineage.
- Published-image provenance: GHCR `prime-rl` images built before
2026-09-30T17:32Z were produced by a pre-patch builder; assess whether a
clean rebuild of the current release tags is warranted.
- No applicable CODEOWNERS entry exists in this repo; CI/build owner
please review.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> CI-only security remediation with intentional cache busting (slower
first builds); no application runtime code changes, but GHCR images
built before the fix may need a separate provenance/rebuild decision.
> 
> **Overview**
> Remediates **CVE-2026-93318** in the GHCR image build workflow by
making the BuildKit builder version fixed and breaking reuse of
artifacts produced before the patch.
> 
> **BuildKit pin:** `docker/setup-buildx-action` now sets `driver-opts`
to `moby/buildkit:v0.33.1` (digest-pinned) so self-hosted
`image-builder` runners do not keep serving a stale local
`buildx-stable-1` builder.
> 
> **Cache and deps lineage:** Shared registry cache refs move to
`dependency-buildcache-v2-*` and `application-buildcache-v2-*` so layers
written by pre-v0.33.1 builders are not imported. Dependency base tags
gain a `-v2-` epoch (`deps-${key}-v2-${suffix}`) so existing
`deps-${key}` images are not reused as the runtime base when only
Dockerfile/lock inputs are unchanged.
> 
> The first build per platform after merge is expected to be cold (no
old cache import); published runtime tags are unchanged—only CI
remediation naming and builder configuration.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0310e6d89608d9d34fd0c1a4c0e9a5c6ba5261bf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-09 08:22:03 -07:00
Konstantin DunasandGitHub 88faa6dc22 feat(sft): warn when renderer is not prefix stable (#3953)
Warn when SFT constructs a renderer that does not guarantee prefix
stability. The warning explains that each conversation is rendered once
into one training sample, that N assistant turns are not expanded into N
samples, and that earlier reasoning may be omitted by the template.
Cached renderers warn only on construction; stable renderers stay quiet.
Custom renderers without the capability are conservatively treated as
unknown.

Pin `deps/renderers` to merged main revision `41f9290`, which includes
https://github.com/PrimeIntellect-ai/renderers/pull/184. It provides the
resolved capability and the manual, opt-in witness audit. Sample
construction is unchanged.

Validation: all **73 SFT dataset tests passed**, including
stable/unstable renderer selection and cache-warning behavior. Prime-rl
unit-test CI passed on the preceding revision; this update changes only
the renderer gitlink to the merged revision. Dependency requirements are
unchanged apart from renderer Python >=3.11, compatible with prime-rl
Python 3.12. The manually invoked renderer audit passes **59 tests** and
is excluded from normal CI discovery.
2026-10-09 11:53:24 +02:00
Florian BrandandGitHub 083b8fe9ec ci: reduce GPU usage and parallelize test setup (#3944)
Reduce CI time and GPU usage by selecting the relevant test suites for
each PR, moving hosted eval to CPU, and running independent setup steps
in parallel.

- Select GPU unit tests, SFT, RL, and hosted eval from changed paths
before allocating runners. Shared runtime and dependency changes retain
broad coverage; pushes to `main` and manual runs execute the full suite.
- Keep RL/SFT coverage for checkpoint converters, dashboard code, and
the shared dashboard smoke helper.
- Run `gsm8k_eval` on `ubuntu-latest` because it uses hosted inference.
- Run public submodule initialization and `uv` setup concurrently, then
wait for both before installing dependencies. Keep dependency caching
keyed on `uv.lock` and the five-job limit on GPU integration tests.
- Cancel superseded CPU and style runs on the same PR.
- Give the GPU workflow read-only contents access and the test selector
PR read access.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Path-based GPU job gating can skip integration coverage on PRs if
filters miss a dependency; full suite still runs on main and manual
dispatch.
> 
> **Overview**
> **GPU CI now picks which jobs to run from the PR diff**, instead of
always running the full GPU unit + integration matrix on every non-draft
PR. A new **Select tests** job uses path filters for unit, SFT, RL, and
eval; pushes to `main` and `workflow_dispatch` still run everything.
RL/SFT integration scenarios are built dynamically (still capped at
`max-parallel: 5` on `prime-rl-2xh200`).
> 
> **`gsm8k_eval` is split out** into a dedicated job on `ubuntu-latest`
(hosted inference), so it no longer consumes GPU runners. Integration
pytest invocations use `tests/integration/test_${{ matrix.test }}.py`
from the dynamic matrix rather than per-row `pytest_args`.
> 
> **Setup and queueing tweaks:** submodule init and `setup-uv` run in
parallel in CPU/GPU jobs; CPU and style workflows cancel in-progress
runs per PR; GPU workflow gets `workflow_dispatch`, read-only
`contents`, and PR-scoped concurrency cancel. `docs/development.md`
documents the new triggers and runner split.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
20da35f30de85b2b18cf82e29598846a1228ca12. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 17:17:55 -07:00
853208336e feat(sft): pad to a multiple of cp and remove fp8 indexer dynamism (#3948)
SFT now pads packed rows only to a multiple of cp, as RL does, instead
of to `seq_len`. The fp8 indexer drops its autotuning, which
re-benchmarked configs on every new row length and made unpadded rows
slower than padded ones on DeepSeek-V4 (#3726).

- The indexer pads keys to a multiple of 16 and runs one fixed config,
within 1.05x of the best.
- Every rank, including RL on DeepSeek-V4 and GLM-5, runs that config
with bitwise-identical top-k.
- SFT and RL throughput count trained tokens, not `seq_len` × rows or
the first row × count.
- The SFT `seq_len % (2 * cp)` check is gone: CP only needs `seq_len %
cp`, which configs enforce.

Same samples per arm, time summed over steps 5 to 20, one H200 node:

| Workload | Padding on main | main | This PR | Speedup |
|---|---|---|---|---|
| DeepSeek-V4-Flash 6L, scaleswe, 256K rows, cp 8 | 19.8% | 61.2 s |
38.2 s | 1.60x |
| GLM-4.5-Air 8L, math, 131K rows, dp 4 cp 2 | 7.3% | 223.8 s | 200.1 s
| 1.12x |
| GLM-4.5-Air 8L, scaleswe, 131K rows, dp 4 cp 2 | 19.7% | 701.0 s |
623.0 s | 1.13x |

On DeepSeek-V4, the 1.60x exceeds the 1.25x that removing 19.8% of
tokens predicts because two effects multiply: main's token-0 pads crowd
onto the same experts, and the padding itself costs compute. The
DeepSeek-V4 ablation section below separates the two.

On GLM with scaleswe, removing 19.7% of the tokens would predict about
1.25x, but it measured 1.13x. Its 4 data-parallel ranks now get rows of
different lengths, and each step likely waits for the rank with the
longest rows.

Loss matches main to within 1e-3 per step. This overlaps
https://github.com/PrimeIntellect-ai/prime-rl/pull/3932 in
`CatDataset._finalize_pack`. Harness:
[`benchmarks/scripts/sft_pad_to_cp/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/0ed0e78b33e8533d7fd1e0d603759dc2ab50e5dd/benchmarks/scripts/sft_pad_to_cp)
(removed before merge).

## DeepSeek-V4 ablation

Each row changes one thing on the DeepSeek-V4 workload above, to
separate the cost of the padding length, of token-0 pads crowding onto
the same experts, and of indexer re-tuning:

| Arm | Time | Speedup vs main |
|---|---|---|
| main: pads every row to `seq_len` with token 0 | 61.2 s | 1.00x |
| main, but pads with the row's own tokens (#3932) | 49.6 s | 1.23x |
| pads only to a multiple of cp, indexer still autotuned | 73.6 s |
0.83x |
| pads only to a multiple of cp, fixed-config indexer (this PR) | 38.2 s
| **1.60x** |

## Alternatives considered

- Bucketing the autotune key on `next_power_of_2(S_q)` reached 1.47x on
DeepSeek-V4. Each bucket kept its first row's config (up to 1.44x slower
later), short rows paid extra tunes, and each rank still tuned on its
own rows, so ranks could run different kernels.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 19:13:22 -04:00
Konstantin DunasandGitHub 31281d88f9 feat(sft): pass per-message loss selection to renderers (#3950)
SFT samples can contain prefilled assistant turns that must remain in
context without becoming training targets. Read an optional
`message_loss_mask` dataset column and pass it directly to
`renderers.build_training_sample`; for a user/assistant/user/assistant
conversation, `[0, 0, 0, 1]` trains only the final assistant turn.

The renderer owns token attribution and mask validation, including GLM's
assistant-generated closing markers. prime-rl performs no owner walking
or template-specific mask reconstruction. Selection only removes
existing loss targets and preserves input/target token IDs. Missing or
null masks preserve normal supervision; fully masked samples follow the
existing skip behavior.

`data.columns.message_loss_mask` supports renamed columns. For
prompt/completion rows, the mask covers their concatenated message list.
This API reads a separate column; datasets with inline
`messages[].trainable_mask` need conversion before use.

Pins `deps/renderers` to upstream main commit
`e3ace557545274385abb30435975c134c7c2429d`, which merges
https://github.com/PrimeIntellect-ai/renderers/pull/181. The renderer
dependency is now merged.

Validation:
- Signed pin update `838828713` points to the merged renderer commit.
Its Git tree is identical to the previously tested renderer head; no
source changes accompany the pin update.
- The following tests and checks passed on signed implementation commit
`7e0800051`:
- 73 SFT dataset tests passed, including real GLM-5 and Qwen3
tokenizers, both dataset layouts, custom column names,
missing/null/all-enabled masks, excluded initial/final turns, fully
masked samples, and invalid values/lengths.
- Ruff 0.13.0 lint and formatting checks passed for the changed Python
files; `git diff --check` passed.
- CPU tests ran in an isolated Python 3.12 environment with Transformers
5.6.2 and PyTorch 2.14.1. No GPU training run performed.
- Commit signature verified locally.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes which tokens receive loss during SFT when datasets supply
masks; incorrect masks could silently train the wrong turns, though
behavior is opt-in and heavily tested against real renderers.
> 
> **Overview**
> Adds **optional per-message SFT loss selection** via a dataset
`message_loss_mask` column (0/1 or booleans, one entry per resolved
message—including prompt+completion rows). The trainer forwards the
column to `build_training_sample` so renderers drop supervision on
excluded turns **without changing token IDs** (e.g. `[0, 0, 0, 1]` keeps
context but trains only the last assistant reply). Missing/null masks
behave as today; all-zero masks still skip the sample.
> 
> **Config and docs:** `SFTColumnsConfig.message_loss_mask` defaults to
`"message_loss_mask"` and can be remapped (e.g. `"selection"`); dataset
init errors if a remap points at a missing column. `docs/training.md`
documents the format and semantics.
> 
> **Tests:** Coverage for GLM-5 and Qwen3, both dataset layouts, custom
column names, partial masks, fully masked rows, and invalid mask
values/lengths.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
838828713529afa49a57cf441071f946ec195cdf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-09 00:36:22 +02:00
samsjaandGitHub bc250759bf fix(ci): uv cache on h200 runners, drop phantom 4xa6000 job, cap fan-out (#3909)
## Why

Since **Sep 2** the `4xa6000` runner has been offline. Since then,
`benchmark_regression` has queued on a dead label on **every single GPU
Tests run**, hit GitHub's 24h self-hosted queue timeout, and failed the
workflow. There has not been one green GPU Tests run in over a month, so
the per-PR GPU check is permanently red and real regressions hide in the
noise. Measured over Sep 29-Oct 6: all 28 completed runs failed at
exactly 1440 +/- 1 min, and 20+ phantom `benchmark_regression` jobs were
sitting in the queue at any time.

## What changes

1. **uv cache on the GPU jobs** (`enable-cache: true`, keyed on
`uv.lock`, mirroring `cpu_tests.yaml`) — each h200 pod currently
re-resolves and re-downloads the full dependency set from PyPI on every
job.
2. **`benchmark_regression` removed from the PR matrix.** It cannot
simply move to `prime-rl-2xh200`: the test unconditionally runs a 1-GPU
**and** a 4-GPU benchmark (a 2-GPU pod cannot host the latter), and it
asserts against A6000-captured baselines with a 15% tolerance (H200
results would blow through it). It belongs on benchmark hardware
(`benchmarks.yaml`) or behind a 4-GPU scale set when one exists — happy
to re-add once either exists.
3. **`max-parallel: 5` on the integration matrix** — a concrete per-PR
ceiling:
- 9 integration jobs + unit-tests = **6 h200 pods peak per PR**, 2 waves
- at current job durations (~10-15 min each) a PR finishes in ~25-35 min
- with 2-3 PRs in flight: <= ~18 pods steady-state; the ARC scale set
`maxRunners` (suggest 16-20) is the complementary global cap
4. `docs/development.md` CI table updated to match (also adds
`gsm8k_eval`, which was missing, and the current runner).

## Result

GPU Tests runs **only** on the `prime-rl-2xh200` scale set, and every PR
gets a real green or red within ~30-60 min instead of a guaranteed 24h
failure.

## Not in this PR (follow-ups)

- Bake git/uv into the CI image to kill the per-job `apt-get install
git`
- PVC-backed `~/.cache/uv` mount to avoid per-pod cache archive
downloads
- Nightly Tests still target a `research-cluster` runner that does not
exist — needs the same treatment or a cron disable

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> CI workflow and documentation only; no runtime or auth changes.
Benchmark regression no longer runs on every PR until re-homed to
suitable hardware.
> 
> **Overview**
> **GPU Tests** is adjusted so PR runs can finish on live hardware
instead of timing out on a dead runner label.
> 
> Both GPU jobs now enable **uv dependency caching** keyed on `uv.lock`
(same pattern as `cpu_tests.yaml`), cutting repeated PyPI
resolves/downloads on each H200 pod. The integration matrix **drops
`benchmark_regression`** (it targeted offline `4xa6000` hardware and
cannot run meaningfully on 2×H200), and adds **`max-parallel: 5`** so at
most five integration jobs run at once per PR. **`docs/development.md`**
updates the CI table to list the current integration scenarios
(`gsm8k_eval` included), `max-parallel`, and **`prime-rl-2xh200`** as
the runner.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8207cc05d9a731a4c5d7c561354284f1a79792d4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 15:18:58 -07:00
1983d8dfed chore: bump verifiers to main (#3934)
## Summary

- Bump `deps/verifiers` from `1fa2bbc42` to main `da75527ca`. This pulls
in the Harbor adapter changes from PrimeIntellect-ai/verifiers#2808:
  - Honor reward-file precedence and select named rewards explicitly.
  - Resolve separate verifier definitions by Harbor image precedence.
  - Align the adapter with Harbor 0.24.0 and reject multi-step tasks.
- Move the `harbor` upload cutoff in `[tool.uv.exclude-newer-package]`
from 2026-08-11 to 2026-10-08, which matches `deps/verifiers`. verifiers
now pins `harbor==0.24.0`, which the old cutoff excluded.
- Relock: `harbor` 0.21.0 → 0.24.0, and `semver` 3.1.0 is new.

`deps/prime-envs` is already at its main head (`89dcc7ffc`). The current
verifiers pin already has the network notice
(PrimeIntellect-ai/verifiers#2769), so this bump supersedes #3734.

## Verification

- `uv sync --all-extras --all-packages --locked` succeeds.
- `uv run pytest -m "not gpu" tests/unit`: 663 passed.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Lockfile and uv policy changes only; risk is mainly behavioral shifts
from Harbor 0.24.0 and updated verifiers Harbor adapter usage in
eval/training paths.
> 
> **Overview**
> Updates dependency resolution so **`harbor` 0.24.0** (via the
`verifiers[harbor]` pin) can install under uv’s rolling
**exclude-newer** policy by moving the bounded **`harbor` cutoff** from
`2026-08-11` to **`2026-10-08`** in `pyproject.toml`, mirrored in
`uv.lock`.
> 
> The lockfile refresh bumps **`harbor` 0.21.0 → 0.24.0**, records new
transitive deps **`jsonschema`** and **`semver`**, and aligns the
verifiers harbor extra specifier to **`==0.24.0`**. This pairs with the
verifiers main bump described in the PR (Harbor adapter alignment and
reward/verifier precedence behavior), even though those code changes
live outside this diff.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
69e62c1fc116896ce99c79dbfc454959c748cb47. 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-10-08 15:18:33 -07:00
26681fc6c7 fix(models): pass contiguous router-replay experts to compiled layers (#3947)
On torch 2.13.0 with compile and router replay, some MoE layers silently
replay layer 0's routing instead of their own from the second training
step on. This PR calls `.contiguous()` on each layer's routed-experts
slice, which removes the bug.

Each decoder layer `l` receives `routed_experts[:, :, l]`, a view into
one shared int32 tensor with axes (batch, sequence, layer, expert slot).
When `top_k` is not a multiple of 4, that view starts at a byte offset
that is not 16-byte aligned for some layers (odd layers on DeepSeek V4,
`top_k = 6`).

Inductor copies a misaligned input into a fresh aligned buffer, which
starts at offset 0. Once automatic dynamic shapes recompile the layer,
AOTAutograd mistakenly applies that offset 0 to the original shared
tensor when it rebuilds the layer's routed-experts output. Offset 0 of
the shared tensor holds layer 0's experts. A contiguous slice is its own
aligned tensor, so Inductor never makes the copy.

- Applied to the eight models that passed the raw view. `glm4_moe`
already called `.contiguous()`.
- Fixed upstream in pytorch/pytorch#191002 (torch 2.14.0 and 2.14.1, no
2.13.x release). The copy is cheap, so it can stay after an upgrade.
- Models with `top_k = 8` (Qwen3-30B-A3B, Trinity-Mini, GLM-4.5-Air)
were unaffected.

DeepSeek V4 Flash RL probe (compile on, router replay on, lr 0),
mismatch KL mean, lower is better:

| trainer | step 1 | steps 2-10 |
|---|---|---|
| compiled, strided slice (main) | 0.0008 | 0.022-0.11 |
| compiled, contiguous slice (this PR) | 0.0009 | 0.0007-0.0025 |

With compile off, the same probe spans 0.0008-0.0032 over steps 1-10.

## Verification

A standalone torch reproducer was added in
66641b0b0b31da76082edaadd70b4f601b13a53a and removed again at the end of
this branch, so main never carries it. Run it on one CUDA device from
that commit with `TORCHINDUCTOR_FORCE_DISABLE_CACHES=1 uv run python
tools/repro_misaligned_replay_alias.py`. In earlier runs it printed `BUG
REPRODUCED` on torch 2.13.0 and was clean on the 2.14.0.dev20260809 and
2.16.0.dev20261008 nightlies.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 17:03:55 -04:00
Florian BrandandGitHub 6b0906c900 fix(eval): preserve sibling trace verdicts when an episode fails (#3824) 2026-10-08 12:12:16 -07:00
JannikStandGitHub 5e963f027a fix(monitors): send online-eval metrics to the parent training run (#3941)
Hosted runs with online evals score real rewards but the run dashboard
shows no `eval` metric group (ENG-6573).

The dashboard's `eval` group is built from the run's own metric keys
(`eval/{env}/...`). The orchestrator's in-process evals reach it through
the train monitor, but when evals run in a process of their own (SFT
online evals) the metrics are dropped: `PrimeEvalMonitor.log_metrics`
was a deliberate no-op.

- `PrimeEvalMonitor` now attaches to the parent training run via
`$RUN_ID` and forwards each epoch's `eval/...` metrics there.
- The eval process never reports the parent run's status: the SDK's
atexit crash hook is unregistered and `finalize()` only drains the
queue. Without that, an eval process exiting while the trainer is still
going would mark the whole run failed.
- No parent attached without `$RUN_ID`, so a standalone `prime eval` is
unchanged.

Note the ticket proposes exposing `environmentshub/resolve` on the
platform's internal API instead. That's a separate gap: it silences the
`EnvironmentResolutionError` warning and would create per-epoch
Evaluation records, but it does not produce the `eval` metric group, and
it needs four more `/evaluations` routes that the internal surface also
lacks.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how eval processes interact with the parent platform run
(metrics + SDK lifecycle hooks); mistakes could misreport run status or
drop metrics, but behavior is gated on $RUN_ID and explicitly avoids
finishing the parent.
> 
> **Overview**
> Fixes hosted runs where **SFT online evals** compute rewards but the
run dashboard never shows the **`eval`** metric group (keys like
`eval/{env}/...`).
> 
> **`PrimeEvalMonitor`** now attaches a metrics-only handle to the
parent training run when **`$RUN_ID`** is set, and **`log_metrics`**
forwards sanitized epoch aggregates there instead of being a no-op.
Standalone **`prime eval`** (no **`$RUN_ID`**) is unchanged.
> 
> Lifecycle is guarded so the eval subprocess cannot poison the parent
run: the SDK **atexit** hook on the attached parent is **unregistered**,
and **`finalize()`** only **`flush`**es the upload queue—never finishes
or reports status on the trainer’s run.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
892035628173119b14a591b2975a5b6176f4c357. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 19:44:51 +02:00
72834b3b52 feat(trainer): prepare RL micro batches on a background thread pool (#3917)
This is an alternative to #3907. The RL trainer decoded and preprocessed
each micro batch's images on the main thread right before its forward
pass, leaving the GPU idle. `WorkerPool`, a small ordered thread pool
configured by `data.num_workers` like torch's DataLoader, now prepares
micro batches ahead of the loop through a single `prepare_micro_batch`
hook.

- `num_workers` defaults to 0, which prepares on the main thread as
before, and one thread gives the full speedup. Here it counts threads,
unlike SFT's DataLoader processes.
- An earlier version used forked worker processes. They pickle data
through `/dev/shm`, risk copy-on-write memory, and were 0.6 s/step
slower than a thread.
- Pinned memory and `non_blocking` copies are left to a follow-up that
first removes the per-micro-step CUDA syncs.

Qwen3.5-9B trainer-only on 4 H200s, mock micro batches of 1024 px JPEGs
(about 1 s of CPU decoding each), median s/step, lower is better
(benchmark code added in
[`331fc83fe`](https://github.com/PrimeIntellect-ai/prime-rl/commit/331fc83fed9ff8b6fb435df5207a07e37b08c0e5)
and removed in the next commit):

| Arm | main thread | prepared ahead | time saved |
|---|---|---|---|
| this PR, 1 thread | 24.98 | 18.86 | 24.5% |
| this PR, 1 thread, optimizer CPU offload | 26.56 | 20.24 | 23.8% |
| earlier process version, 2 workers | 24.79 | 19.02 | 23.3% |
| #3907 (thread with pinned memory) | 24.98 | 18.63 | 25.4% |

Every arm matches the main-thread baseline bit for bit in loss and grad
norm. Host memory stays flat over 30 steps, 0.3 GiB above the baseline
for the prefetched images.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 12:15:19 -04:00
faresobeidandGitHub 0bcb868e91 fix(configs): size the single-node NCCL transfer group after the DP fill (#3841)
## Summary
Two bugs in how `rl` sets `weight_broadcast.inference_world_size` on
main:

1. **World size computed before the DP fill.**
`auto_setup_weight_broadcast` set
`trainer`/`orchestrator.weight_broadcast.inference_world_size = dp * tp`
before `auto_setup_deployment` fills the single-node inference GPUs with
DP ranks. With `num_infer_gpus = 4` and `data_parallel_size` unset, the
NCCL group was sized for 1 inference worker while vLLM started 4, so the
first weight update cannot form the group.
2. **A single-node SLURM job cannot re-parse its `rl.json`** (since
#3788). The resolved `rl.json` always contains
`weight_broadcast.inference_world_size` (default 1), and #3788's guard
rejects any config that sets it. So `rl @ rl.json` in the single-node
sbatch fails validation for every NCCL config.

## Fix
- Single-node: set
`trainer`/`orchestrator.weight_broadcast.inference_world_size = dp * tp`
right after the DP fill in `auto_setup_deployment` (non-filesystem
only). Multi-node already sets it there.
- `auto_setup_weight_broadcast` copies `weight_broadcast` to the trainer
and orchestrator without touching the world size, and the guard is
removed. The top-level value is now only passed through: `rl` overwrites
it whenever it knows the inference size.

This also fixes what #3924 fixes.

## Behavior change
Yes (bug fixes).
- Resolved configs for every TOML in `configs/`, `examples/`, `k8s/`
that parses as `RLConfig` (41 of 78) are identical before and after,
except `trainer`/`orchestrator.weight_broadcast.inference_world_size`
goes from 1 to 4 in `examples/basic/hendrycks-sanity/rl.toml` and
`configs/ci/nightly/multimodal_color_codeword.toml` (4 infer GPUs, DP
unset).
- Re-parsing the dumped config (as the single-node sbatch does) fails on
main for all 18 single-node NCCL configs and passes for all of them
here.
- With `inference = None` and NCCL against external servers, a user-set
`weight_broadcast.inference_world_size` is now passed through instead of
rejected.

## Checks
- `pytest tests/unit/test_configs.py tests/unit/orchestrator -m "not
gpu"`: 298 passed
- `ruff check`, `ruff format --check`: clean
- New test `test_single_node_nccl_resolved_json_roundtrips`: dumps a
single-node NCCL config like `rl`'s `write_config`, re-parses it, and
checks it is equal. It fails on main with the guard error.
- `rl @ examples/basic/reverse-text/rl.toml --deployment.num-infer-gpus
2 --slurm.partition all --dry-run`, then re-parse the written `rl.json`:
fails on main, passes here (world size 2).
- GPU (one node): running: `rl @ examples/basic/hendrycks-sanity/rl.toml
--max-steps 3` on main and on this branch, plus the rendered single-node
sbatch for reverse-text (2 infer GPUs) run end to end.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes when NCCL weight broadcast groups are sized for single-node
runs; mis-sizing previously caused deadlocks or init failures during
weight updates.
> 
> **Overview**
> Fixes incorrect **NCCL/NIXL** `inference_world_size` on single-node RL
runs when vLLM **data parallel size** is inferred from `num_infer_gpus`
rather than set explicitly.
> 
> **`auto_setup_weight_broadcast`** no longer derives
`trainer`/`orchestrator.weight_broadcast.inference_world_size` from
`data_parallel_size × tensor_parallel_size` (which ran before DP was
filled) and no longer rejects a user-set `inference_world_size`.
**`auto_setup_deployment`** (single-node) now sets
`inference_world_size` to `dp × tensor_parallel_size` immediately after
the DP/`api_server_count` fill, so the in-memory transfer group matches
every inference GPU that joins NCCL.
> 
> Unit tests assert the resolved world size (2 infer GPUs → size 2) and
that a dumped `rl.json` round-trips unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f5553f5c5dd2f91aa11003338ef13e285a6c9ee6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 12:56:47 +01:00
faresobeidandGitHub 746d8a96d0 chore(models): drop rms_norm re-export, move fp8 quantizer into its tool (#3858)
## Summary
- Delete `trainer/models/layers/rms_norm.py`. It only re-exported
`RMSNorm`/`RMSNormConfig` from `layers/norms.py`, and nothing imported
it.
- Move `quantize_to_fp8_blockwise` from `trainer/models/fp8.py` into
`tools/convert_bf16_to_fp8.py`, its only user.
`tools/convert_dcp_to_fp8.py` still imports it through
`convert_bf16_to_fp8`. While moving it, the 9-line zero-pad block
becomes `F.pad(weight, (0, pad_cols, 0, pad_rows)).contiguous()`; the
output is bitwise identical to the old function (bf16/fp16/fp32, padded
and unpadded shapes, contiguous and transposed inputs).

## Behavior change
None.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dead-code removal and relocating a tool-only quantizer; no trainer
inference or training path changes.
> 
> **Overview**
> Removes dead trainer surface area and keeps FP8 checkpoint conversion
self-contained in the tooling layer.
> 
> **`trainer/models/layers/rms_norm.py`** is deleted (it only
re-exported `RMSNorm` / `RMSNormConfig` with no importers).
**`trainer/models/fp8.py`** is removed and
**`quantize_to_fp8_blockwise`** now lives in
**`tools/convert_bf16_to_fp8.py`**, which was its only consumer;
**`convert_dcp_to_fp8.py`** continues to pull quantization helpers from
that script. Padding inside the moved helper uses **`F.pad`** instead of
manual zero-fill, with the same blockwise e4m3 logic otherwise
unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c35ca75057037c6d98f0080bdffae8efd24e2f85. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 12:46:12 +01:00
faresobeidandGitHub 765bbeba7b fix(launch): default TRITON_CACHE_DIR to a node-local path (#3877)
Processes that share `~/.triton` on a shared filesystem can hang or
crash (seen with Nemotron-H, where many ranks compile the Mamba Triton
kernels at once; reproduced below with Qwen3.5 and GLM-4.5-Air).

This PR adds `TRITON_CACHE_DIR = /tmp/triton-<uid>` to
`DEFAULT_COMMON_ENV_VARS`. It is per-user because `/tmp` is shared by
all users on a node. Like the other launcher defaults, it reaches every
launched component: the local `rl`/`sft`/`inference` launchers (also
used by the single-node sbatch scripts) and the trainer, orchestrator,
inference (incl. prefill/decode), and online-eval env blocks of the
multi-node and inference sbatch scripts. `[env_vars]` (or a component's
`env_vars`) overrides it; a value exported in the shell or `.env` does
not. It also removes the `TRITON_CACHE_DIR` overrides from six example
configs (glm-4.5-air swe/swe-budget/search/terminal, glm-5.3 and
qwen3-30b-a3b sft h200 base): they pointed every user at the same `/tmp`
dir and are now covered by the default. `docs/scaling.md` says so in one
paragraph.

vLLM 0.31's own default: when `TRITON_CACHE_DIR` is unset, its Inductor
adaptor points it at
`$VLLM_CACHE_ROOT/torch_compile_cache/<hash>/rank_<i>_<j>/triton_cache`
(`~/.cache/vllm` by default, so usually on the shared home). That only
covers Triton kernels compiled after torch.compile initializes, and it
is still on the shared filesystem. vLLM keeps a `TRITON_CACHE_DIR` that
is already set, so with this PR vLLM uses `/tmp/triton-<uid>` too.

### Measured cost (one H200 node, vLLM 0.31 venv, Triton 3.7.1)

Each run starts from a fresh process with the same config. "Ready" is
launch → first trainer step logged (Qwen) or launch → `/health` OK
(GLM). For GLM, the first generated token came 1.3–2 s after ready in
every run that came up. Inductor's cache dir was emptied before each run
except the warm node-local one.

| Triton cache | Qwen3.5-4B SFT, 8 GPUs, compiled blocks (step 1 time) |
GLM-4.5-Air vLLM TP8 |
|---|---|---|
| shared, cold (today on a new cluster / after a Triton or torch update)
| **failed 2/2**: `FileNotFoundError` on a cache file that another rank
was writing (`causal_conv1d_fwd_kernel.llir`, `l2norm_fwd_kernel.ptx`) |
**failed 2/2**: 4 of 8 ranks hit `FileNotFoundError` in the cache during
Inductor autotune, the other 4 hung in a collective until killed (1st
run). The 2nd run crashed instead of hanging. |
| shared, warm | not measured cleanly (see below) | 344 s |
| node-local, cold (this PR, first job on a node) | 233 s (step 1: 91
s), 164 kernels compiled | 375 s with vLLM's compile cache warm (106
kernels); 465 s if vLLM's cache is also cold (87 kernels) |
| node-local, warm (this PR, later jobs on the same node) | 138 s (step
1: 8.3 s) | 344 s |

- A cold node-local cache costs about **95 s per node for Qwen3.5** (FLA
+ Inductor kernels) and about **31 s for GLM-4.5-Air inference** when
vLLM's own compile cache is warm. Warm node-local and warm shared take
the same time.
- The rest of the GLM startup does not depend on the Triton cache: about
3.5 min of Python imports and process spawn from the shared venv, 13 s
to load weights.
- vLLM: `VLLM_CACHE_ROOT` (`~/.cache/vllm`, shared home) holds vLLM's
AOT/Inductor artifacts. With this PR it stays shared. On a new node,
vLLM loads those artifacts (`torch.compile` 0.6 s instead of 30 s), and
the Triton binaries are compiled into `/tmp/triton-<uid>` (106 kernels,
+31 s). `TORCHINDUCTOR_CACHE_DIR` (default `/tmp/torchinductor_<user>`,
already node-local) stayed empty in these runs. Inductor's Triton
kernels go to `TRITON_CACHE_DIR`.
- A crash on the shared cache can also break later starts. After the
first failed GLM run, the shared vLLM cache only had AOT artifacts from
the 4 ranks that got through. On the next start, those 4 ranks loaded
the artifacts and the other 4 recompiled, so the ranks diverged and hung
(Triton cache warm-ish, 60 kernels). For the same reason the Qwen
"shared, warm" run started from a partial cache and failed again. The
warm-shared GLM number comes from a shared dir seeded with a complete
cache.

### Possible middle ground (not implemented)

Because the cold cost is above 1 min per node for FLA-heavy models, a
run could seed the node-local cache from a shared read-only copy at job
start. For example, on each node before the components start:
`[ -n "$TRITON_CACHE_SEED" ] && cp -rn "$TRITON_CACHE_SEED"/.
"$TRITON_CACHE_DIR"/`
The seed would be a warm `/tmp/triton-<uid>` copied once to the shared
FS. Triton keys entries by source, compiler, and GPU, so stale entries
are never reused, only skipped. Only reads hit the shared FS, so the
concurrent-write race does not occur. I left it out to keep this PR
minimal.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Launch-time env default only; behavior is overridable via config and
fixes known multi-rank Triton cache races, with a one-time cold-compile
cost on each node.
> 
> **Overview**
> **Sets a global launcher default** so every trainer, orchestrator, and
inference process gets `TRITON_CACHE_DIR=/tmp/triton-<uid>` via
`DEFAULT_COMMON_ENV_VARS`, avoiding concurrent Triton kernel writes
under `~/.triton` on a shared filesystem (hangs / `FileNotFoundError`
under multi-rank compile).
> 
> **Removes redundant `[env_vars]` overrides** from six GLM-4.5-Air RL
and GLM-5.3 / Qwen3-30B SFT example configs that previously pinned
Triton cache paths under `/tmp`; those runs now inherit the per-user
node-local default (still overridable through config `env_vars`).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f21642046ea59cab0b9460863560b4df825f29c0. 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: faresobeid <111092724+faresobeid@users.noreply.github.com>
2026-10-08 11:59:17 +01:00
faresobeidandGitHub fec3acd8e7 chore(orchestrator): fold GenerationSource into TrainEnv (#3838)
## Summary
Fold `GenerationSource` into `TrainEnv`, its only owner. Move
`connect_frozen_client` from `algo/base.py` to `clients.py`, so `algo`
no longer imports `clients` lazily. Give `TrainEnv` `setup()`/`aclose()`
so orchestrator setup and teardown no longer reach into its parts.

## What changed
- `orchestrator/generation_source.py` is deleted. `TrainEnv` (`envs.py`)
now holds `clients`, `renderer_config`, `connected` (the frozen source
clients it connected) and `uses_live_policy`. Dropping `logprobs` for
frozen sources happens in `TrainEnv.__init__`.
- `TrainEnv.setup()` connects the frozen generation source and runs
`algorithm.setup()` concurrently. `TrainEnv.aclose()` closes `connected`
and `algorithm.connected`, never the shared policy clients.
- `connect_frozen_client` is a plain function in `clients.py`, next to
`check_inference_ready`. `algo/base.py` imports it at module level. It
is no longer re-exported from `prime_rl.orchestrator.algo`.
- `dispatcher.py` reads the `TrainEnv` directly at the four former
`generation_source` call sites. `orchestrator.py` calls `env.setup()`
and `env.aclose()`.
- `docs/algorithms.md` and the `algo/__init__.py` docstrings refer to
`TrainEnv`.

## Behavior change
None.

## Checks run
- `pytest tests/unit/orchestrator tests/unit/test_configs* -m "not
gpu"`: 297 passed.
- `ruff check`, `ruff format --check`: clean.
- Equivalence script, old `GenerationSource` (`origin/main`) vs new
`TrainEnv`, on 4 configs: policy, policy with `top_p=0.9`, sft with a
frozen `sampling.source`, opd with a frozen teacher. Identical
`sampling_args`, `requires_sampling_masks` and `uses_live_policy`. After
`setup()`, the same generation clients (policy object, or the frozen
endpoint with the same train client config) and the same algorithm
clients. Teardown closes the same clients.
- GPU smoke on one node (vLLM 0.31): reverse-text RL (15 steps), sft
with a frozen `sampling.source` (5 steps), opd with a frozen teacher (5
steps). All three ran to "Training finished" and exited 0.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Internal orchestrator refactor with stated behavioral equivalence and
no changes to training algorithms or dispatch semantics beyond
indirection.
> 
> **Overview**
> **Refactors train rollout sourcing** by deleting `GenerationSource`
and moving its responsibilities onto `TrainEnv`: inference `clients`,
live-vs-frozen policy detection (`uses_live_policy`), sampling-arg
tweaks (e.g. dropping `logprobs` for frozen endpoints), and frozen-pool
connection in `setup()`.
> 
> `TrainEnv.setup()` now connects frozen `sampling.source` endpoints and
runs `algorithm.setup()` together; `TrainEnv.aclose()` closes only
env-owned clients (`connected` + algorithm pools), not the shared policy
pool. The orchestrator and dispatcher call these surfaces instead of
reaching into a nested `generation_source`.
> 
> `connect_frozen_client` moves from `algo/base.py` to `clients.py`
(next to `check_inference_ready`); it is no longer re-exported from
`prime_rl.orchestrator.algo`. Docs and package docstrings now describe
`TrainEnv` as owning the sampling half of the algorithm config.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e89ca1a663ae6ae808b05ff3326ce9ed63c9b467. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 11:52:10 +01:00
Florian BrandandGitHub adda4731fe fix(eval): salt inference caches only when policy weights change (#3825)
Apply a policy-version cache salt only when inference weights can change
during a run. Standalone evaluations and frozen-model requests omit the
training salt; live RL rollouts and online evaluation retain it so
caches distinguish policy versions.

## Before

The dispatcher added the policy version as `cache_salt` to every request
using the live policy source. Standalone evaluation used that same
source path, so fixed-weight evaluations received a training cache salt
even though no weight updates occurred. Frozen-model requests already
omitted it.

```mermaid
flowchart TD
    Standalone["Standalone evaluation with fixed weights"] --> Live["Live policy source"]
    Training["RL or online evaluation with changing weights"] --> Live
    Live --> Salt["Always add policy-version cache_salt"]
    Salt --> Request["Verifiers provider request"]
    Frozen["Frozen model source"] --> Plain["Omit training cache_salt"]
    Plain --> Request
```

## After

```mermaid
flowchart TD
    Request["Prime-RL dispatcher builds request sampling"] --> Mode{"Live policy source with changing weights?"}
    Mode -->|"Yes: RL or online evaluation"| Salt["Set cache_salt to policy version"]
    Mode -->|"No: standalone evaluation or frozen model"| Plain["Omit training cache_salt"]
    Salt --> Client["Verifiers client builds provider request"]
    Plain --> Client
    Client --> Provider["Inference provider"]
```

The dispatcher records whether policy weights can change. The standalone
evaluator disables version salting, SFT online evaluation enables it,
and RL orchestration keeps it enabled. The request decision also checks
whether the source uses the live policy.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Narrow behavior change to cache salting on eval paths; RL and online
eval keep prior salting via the default flag.
> 
> **Overview**
> Adds a **`policy_weights_change`** flag on `Dispatcher` so inference
**`cache_salt`** (policy version) is only attached when weights can
actually change during the run.
> 
> **Standalone eval** (`EvalConfig`) sets the flag to **false**, so
fixed-weight evaluation no longer invalidates prefix caches on every
training policy version. **SFT online eval** and **RL orchestration**
(default **true**) still salt live-sourced requests so caches stay
correct across weight updates.
> 
> The cache decision is now **`live_sourced and policy_weights_change`**
instead of salting all live policy paths.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5a2d7d9652740106e63fee31a6e79da13816dae7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 01:52:39 -07:00
Florian BrandandGitHub a3f1f892c5 fix(eval): preserve empty outcomes and exclude zero-turn traces from training (#3809)
Keep successful empty environment outcomes in evaluation results. A
trace-less episode or clean zero-turn trace retains the verdict returned
by Verifiers, while training and curriculum logic exclude zero-turn
traces.

## Before

The dispatcher changed successful trace-less episodes into
`EmptyEpisode` failures. Clean, non-timeout zero-turn traces became
`EmptyTrajectory` failures, marking both the trace and episode
unsuccessful. Evaluation therefore recorded a failure even when the
environment had returned success, while training and curriculum filters
relied on those injected errors to exclude empty traces.

```mermaid
flowchart TD
    Env["Verifiers returns an empty successful outcome"] --> Dispatch["Prime-RL dispatcher"]
    Dispatch --> Episode["No traces: inject EmptyEpisode"]
    Dispatch --> Trace["Clean zero-turn trace: inject EmptyTrajectory"]
    Episode --> Failed["Rewrite outcome as failed"]
    Trace --> Failed
    Failed --> Eval["Evaluation records a failure"]
    Failed --> Training["Training and curriculum filter injected errors"]
```

## After

```mermaid
flowchart TD
    Env["Verifiers environment returns an episode"] --> Dispatch["Prime-RL dispatcher preserves empty outcome verdicts"]
    Dispatch --> Eval["Evaluation records and metrics"]
    Dispatch --> Filter["Training trace eligibility"]
    Filter --> Empty["Zero turns: no training sample"]
    Filter --> Sample["Eligible trace with sampled tokens: training sample"]
    Dispatch --> Curriculum["Curriculum ignores zero-turn traces and admits only trainable groups"]
```

Remove the synthetic `EmptyEpisode` and `EmptyTrajectory` errors.
`iter_trainable_traces()` filters empty traces alongside failed and
untrainable traces before advantages are assigned, so the advantage gate
needs no separate zero-turn check. Difficulty sampling also excludes
zero-turn traces. Empty groups finish without producing a trainer
payload, and mixed groups retain their eligible traces. Curriculum
admission also requires a trainable trace, so groups without training
samples cannot inflate admission metrics. Sampler observations of
completed turns are retained even when token metadata is unavailable.
Verifiers' no-agent validation and training timeout handling remain in
place.

[#3824](https://github.com/PrimeIntellect-ai/prime-rl/pull/3824) applies
the same ownership rule to partially failed episodes: preserve
environment results, then decide training eligibility explicitly.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes evaluation outcome recording and which rollouts feed
training/curriculum admission, which can shift eval metrics and training
batch composition without touching auth or data stores.
> 
> **Overview**
> Stops the dispatcher from **injecting** `EmptyEpisode` /
`EmptyTrajectory` errors on successful trace-less or zero-turn outcomes,
so **evaluation keeps Verifiers’ success verdict** instead of recording
synthetic failures.
> 
> Training and curriculum now **exclude zero-turn traces explicitly**:
`iter_trainable_traces()` skips `num_turns == 0`, difficulty-pool reward
updates require `num_turns > 0`, and curriculum admission requires
**both** passing gates **and** at least one trainable trace via
`iter_trainable_traces()`. Scored rollouts without token/advantage
metadata can still update sampler difficulty; groups with no trainable
samples no longer count as admitted.
> 
> Tests cover mixed groups with non-trainable traces, empty-only groups,
and reward-only observations for the sampler.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8582fb8c18e7cb4aa0dc7af58c6e0a4474bd7b40. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 01:51:52 -07:00
Florian BrandandGitHub e6acff78aa chore: align network prompt dependency pins (#3929) 2026-10-07 19:45:14 -07:00
3587b285f5 chore: require prime-runs 0.1.4 (#3928)
## Summary

Raises the `prime-runs[train]` floor from `>=0.1.3` to `>=0.1.4` and
updates `uv.lock` to match.

## Why

`prime-runs` 0.1.4 lets a run opt out of Prime Traces and upload its
samples to the legacy sample tables instead
(PrimeIntellect-ai/prime#998):

- `PRIME_TRACES_OPT_OUT=true`
- `prime config set-traces-opt-out true`, which sets `traces_opt_out` in
`~/.prime/config.json`
- `prime_runs.init(traces_opt_out=True)`

`prime-runs` 0.1.3 doesn't know about any of these. With 0.1.3
installed, which is what `uv sync` gives today, a user who sets the
environment variable or the config key gets no error and no warning, and
their runs keep uploading to Prime Traces. Requiring 0.1.4 makes the
setting take effect.

Nothing changes for runs that don't opt out. The Prime monitor calls
`prime_runs.init()` without the new argument, so the default (upload to
Prime Traces) is unchanged.

A training run that opts out needs pyarrow for the legacy sample
encoder. prime-rl already depends on `prime-runs[train]`, which includes
it.

## Changes

- `pyproject.toml`: `prime-runs[train]>=0.1.3` →
`prime-runs[train]>=0.1.4`.
- `uv.lock`: `prime-runs` 0.1.3 → 0.1.4. No other package moves;
`prime-traces` stays at 0.0.7.

The `deps/verifiers` submodule is not changed. Its own floor is raised
separately in PrimeIntellect-ai/verifiers#2805, and this PR doesn't
depend on it.

`uv lock --check` passes. I did not run the test suite.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dependency floor bump only; no application code changes and default
trace upload behavior stays the same.
> 
> **Overview**
> Raises the **`prime-runs[train]`** minimum from **`>=0.1.3`** to
**`>=0.1.4`** in `pyproject.toml` and pins **`prime-runs` 0.1.4** in
`uv.lock`.
> 
> This ensures installs pick up **Prime Traces opt-out** behavior
(`PRIME_TRACES_OPT_OUT`, `prime config set-traces-opt-out`, or
`prime_runs.init(traces_opt_out=True)`), which 0.1.3 silently ignored so
opted-out runs could still upload to Prime Traces. Default runs that do
not opt out are unchanged; `prime-rl` still depends on the **`[train]`**
extra for legacy sample encoding when opting out.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
06caa96109250b6b800d8e757de7133b4f152031. 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-10-07 19:38:03 -07:00
f3827c4ed2 perf(trainer): avoid eager fallback of MoE blocks with an fp32 router and activation checkpointing (#3925)
With `moe_router_dtype="float32"` (the RL default) and activation
checkpointing on, every MoE block ran eager under `torch.compile`. Two
things combine to cause it:

- The fp32 router is its own FSDP2 unit, and FSDP2 hooks are
dynamo-disabled, so the router always breaks the graph.
- Under `compile(AC(block))` the checkpoint compiles as a higher-order
op, which forbids breaks, so Dynamo ran the whole block eagerly.

This PR compiles inside the checkpoint instead: for any checkpointed
block that holds a nested FSDP unit (today, the fp32 router), an eager
checkpoint now wraps the compiled block (`AC(compile(block))`), so the
nested unit's break only splits the block into compiled graphs. To see
those units, compile now runs after FSDP. Compiling in place keeps the
same module object, so the order changes nothing at runtime.

The reorder is safe. The old `AC -> Compile -> FSDP` comment was ported
from TorchTitan in #923, when `apply_compile` still wrapped each block
with `torch.compile(block)`. #957 switched to in-place `.compile()` two
days later without revisiting it. With in-place compile, both orders
trace the same frames: graph breaks, loss and step time match on both
workloads, and `fullgraph=True` (with a bf16 router) still compiles with
zero graph breaks.

| Workload (8x H200, EP 8, full AC) | before (s/step) | after (s/step) |
MFU |
|---|---|---|---|
| GLM-4.5-Air, 16 layers, real data | 6.21, 6.17 | 5.22, 5.21 | 35% to
42% |
| Qwen3-30B-A3B, fake data | 5.96, 5.96 | 4.51, 4.51 | 32% to 42% |

Two runs per arm, each the median `time/step` over steps 5 to 20, no
offloading. Peak memory is unchanged, and loss and grad norm track the
baseline within run-to-run noise.

![Qwen3-30B-A3B MoE layer forward, before and
after](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/09e64ed1afc27e97fda6080556171522e29c9a0e/pr-figures/fp32-router-compile/qwen_layer_forward.png)

**Figure:** one MoE layer's forward on Qwen3-30B-A3B, before and after
this PR. The orange eager elementwise kernels collapse into a few pink
compiled Triton kernels, so the layer's forward drops from 16.4 to 11.3
ms.

<details><summary>Same view on GLM-4.5-Air</summary>

![GLM-4.5-Air MoE layer forward, before and
after](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/09e64ed1afc27e97fda6080556171522e29c9a0e/pr-figures/fp32-router-compile/glm_layer_forward.png)

</details>

## Alternative considered

Keeping recompute inside the compiler: drop the block-level checkpoint
and instead checkpoint two compiled regions that exclude the router, the
attention module and the post-router MoE work. It beat the baseline but
was slower than this PR (Qwen3-30B 5.50 vs 4.51 s/step, GLM-4.5-Air 5.85
vs 5.22 s/step) and used more memory, because the norms and the router's
fp32 activations stay outside any checkpoint.

## North star: fullgraph fp32 router support

Fullgraph compile with an fp32 router stays unsupported, and
`model.compile.fullgraph=true` still raises for it. The blocker is the
router's FSDP unit itself: FSDP2 applies one mixed-precision policy per
unit, so the fp32 router cannot share the block's bf16 unit, and its
dynamo-disabled hooks are the graph break above. PyTorch
[#196626](https://github.com/pytorch/pytorch/pull/196626) adds
per-parameter mixed precision, which lets the router stay in the block's
unit. That removes the break, enables fullgraph, and makes this PR's
compile-inside-AC path unnecessary, so it should be reverted then.
#196626 is on PyTorch `main` but not yet in a release.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 16:55:28 -04:00
faresobeidandGitHub 93a0fe0d6b refactor(trainer): add iter_moe_blocks for the MoE layer lookup (#3843)
## Summary
Add `iter_moe_blocks(model)` in `trainer/model.py`. It yields the `MoE`
MLP of each decoder layer. It replaces the five copies of the
decoder-layer MoE lookup in `freeze_moe_router`,
`apply_fp32_moe_router`, `get_full_offload_dtype_policy`,
`apply_force_balanced_routing` and `get_load_balance_stats`.

## What changed
- New `iter_moe_blocks` next to the helpers that use it. The helpers
stay in `model.py`, so no imports change.
- The four `layer.mlp if hasattr(...) else layer.feed_forward ...`
lookups and the `getattr(mlp)` + `hasattr(tokens_per_expert)` scan in
`get_load_balance_stats` now call `iter_moe_blocks`.
- Removed the stale "HF impl" comment in `get_expert_load_stats`. The HF
fallback was removed in #3773.

## Behavior change
None. The `feed_forward` fallback is gone. Every prime-rl decoder layer
uses `mlp`. `get_load_balance_stats` already looked only at `mlp`. Only
`MoE` registers `tokens_per_expert`, so it selects the same layers as
before.

## Checks
- CPU equivalence vs `main` (throwaway script, not in the repo). Tiny
Qwen3-MoE (`mlp_only_layers=[1]`) and GLM4-MoE
(`first_k_dense_replace=1`) models with fixed router-count buffers.
Compared `is_tt_moe_model`, `get_load_balance_stats`,
`get_global_moe_stats`, `compute_expert_load_stats`,
`get_expert_load_stats` and `get_full_offload_dtype_policy`, plus
parameter dtype and `requires_grad`, and router
`fp32_gate`/`force_balanced` after the three router helpers. All 16
outputs were bit-identical.
- `pytest tests/unit/train tests/unit/orchestrator
tests/unit/test_configs* -m "not gpu"`: 450 passed, 1 failed. The
failure is
`test_cpu_adam.py::test_native_cpu_adamw_matches_fused_torch_and_preserves_gradients`
(ninja build), which fails the same way on `main`.
- `ruff check` and `ruff format --check`.
- GPU: reverse-text MoE RL smoke vs `main` on one node, running.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Mechanical refactor of MoE traversal with no intended behavior change;
only risk is if a model relied on the removed feed_forward path (none in
this codebase).
> 
> **Overview**
> Introduces **`iter_moe_blocks`**, a single iterator over decoder
layers whose `mlp` is a **`MoE`**, and rewires MoE
router/offload/metrics helpers to use it instead of repeated per-layer
`mlp` / `feed_forward` lookups.
> 
> **`freeze_moe_router`**, **`apply_fp32_moe_router`**,
**`get_full_offload_dtype_policy`**, **`apply_force_balanced_routing`**,
and **`get_load_balance_stats`** now loop over that iterator; the unused
**`feed_forward`** fallback is removed. **`get_expert_load_stats`** only
drops an outdated comment on the empty tensor guard.
> 
> Intended as a no-op for supported models: same router freezing, fp32
gates, FSDP dtype policy, debug balanced routing, and load-balance /
expert-load metrics.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
2cf0399ca4e467c9ae028082c2a03f02604abbf8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-07 20:22:19 +01:00
faresobeidandGitHub db2c00e9ed feat(trainer): freeze MoE router by default in RL (#3797)
Make `trainer.model.freeze_moe_router` default to on for RL.

## What changes
- `model.freeze_moe_router` is now `bool | "auto"`, default `"auto"`. It
resolves to `True` on the RL `TrainerConfig` and to `False` on
`SFTConfig`, following the per-trainer pattern of `moe_router_dtype`. An
explicit `true`/`false` still wins.
- `freeze_moe_router()` no longer raises on non-MoE models; it does
nothing, so dense RL runs keep working with the new default.
- `docs/training.md` knobs table lists the field.

## Why
In RL, router updates amplify the train/inference routing mismatch: the
trainer's expert choices drift away from the ones inference sampled. So
RL keeps the pretrained router by default. SFT is unchanged.

What gets frozen: the router gate parameters (`mlp.router.gate.weight`,
plus `gate.bias` on gpt-oss). The aux-loss-free `selection_bias` buffer
is not a parameter, and nothing on main updates it. Shared-expert gates
(Qwen3.5) and Nemotron-H latent projections are not touched. Frozen
routers get no optimizer state.

## Breaking changes
- RL runs on MoE models no longer train the router. All MoE RL examples
are affected (glm-5.3, glm-4.5-air, intellect-3.1, qwen3-30b-a3b,
minimax-m2.5, nemotron-3-super). Set `trainer.model.freeze_moe_router =
false` for the old behavior.
- An explicit `freeze_moe_router = true` on a non-MoE model is now a
no-op instead of an error.
- Resuming: a checkpoint saved before this change (trainable router)
loads into a frozen-router run; the extra router optimizer state is
ignored. The reverse, resuming a frozen-router checkpoint with
`freeze_moe_router = false`, fails on missing DCP keys (noted in the
field docstring).
- With LoRA, a router listed in `lora.modules_to_save` is frozen again
by the new default unless `freeze_moe_router = false` is set.

## GPU check
One node (8×H200), FSDP over 8 ranks, `samsja/mini-glm-moe` (23 MoE
layers), SFT with fake data, `freeze_moe_router = true`,
`moe_router_dtype = "float32"` (so each router is its own fp32 FSDP unit
whose params are all frozen), 5 steps with a checkpoint every step:
- Log: "Froze 23 MoE router parameters", "Running 23 MoE router gates in
fp32"; all 5 steps ran with finite loss and grad norm.
- DCP checkpoints step 1 vs step 5: all 23 fp32 router gate weights are
bitwise unchanged; expert weights changed; no optimizer state exists for
any router parameter.
2026-10-07 19:15:26 +01:00
4250d895bc fix(trainer): run FA2 and FA3 through custom ops so fullgraph compile works (#3911)
#3753 let MoE blocks compile with `model.compile.fullgraph = true`, but
it was validated on B300 with FA4. On H200, where FA3 is the default,
fullgraph still failed at the first forward, because FA2's and FA3's
`flash_attn_varlen_func` are autograd.Functions and Dynamo rejects the
same `cu_seqlens` tensor passed as both `cu_seqlens_q` and
`cu_seqlens_k`. FA2 and FA3 now run through `prime_rl_attn` custom ops
like FA4 (#3754), so the checkpointed MoE blocks compile with fullgraph
and no graph breaks on H200 too.

- AFMoE, Ulysses CP and the Qwen3.5 vision encoder now call the op
wrappers; FA4's op takes optional `max_seqlen_q/k` for Ulysses.
- The ops match the library functions bitwise, except FA3's GQA
`dk`/`dv`, which the library itself doesn't reproduce run to run.
- `apply_compile` traces `max_seqlen` symbolically: as a constant, each
rank recompiled on its first new value and stalled every rank for ~6 s.
A
[benchmark](https://github.com/PrimeIntellect-ai/prime-rl/blob/9db5336241304a0263664c8408e03159cbb8767e/tools/benchmark_flash_attn_max_seqlen.py)
shows the symbolic int costs nothing measurable.

| GLM-4.5-Air, 24 layers, 2 x 8 H200, ep 8, bf16 router | s/step (lower
is better) | tok/s/GPU (higher is better) |
|---|---|---|
| main, FA3, fullgraph off (fullgraph fails) | 4.64 | 3533 |
| this PR, FA3, fullgraph on | 3.83 | 4282 |

That is 17.5% less time per step, or 21.2% more tokens per second per
GPU. Medians over steps 5 to 20; loss tracks main within 0.03 over 20
steps. The GPU is about 99% busy in both arms, so the gain is fusion:
per step, about 1030 ms of unfused aten kernels (MoE routing glue, RoPE)
become 262 ms of Inductor-fused Triton kernels.

![Layer 12 forward
timeline](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/8e12d604f167480f14a2a3a34452c38a95ad07f7/pr-figures/fa-custom-op/layer12-forward.png)

**Figure:** one layer's forward, before (`main`, fullgraph off) and
after (this PR, fullgraph on). The strings of small yellow and
red-orange aten kernels on `main` become a few fused Triton kernels
(pink), and the layer finishes in 35.9 ms instead of 45.4 ms.

![Layer 12 recompute and backward
timeline](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/8e12d604f167480f14a2a3a34452c38a95ad07f7/pr-figures/fa-custom-op/layer12-backward.png)

**Figure:** the same layer's recompute and backward, 106.7 ms after
versus 131.6 ms before. The bottom panel totals the whole step: about 1
s of unfused aten kernels became 262 ms of fused Triton kernels, while
FlashAttention and GEMM time barely changed.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 13:26:59 -04:00
faresobeidandGitHub 78bc69ccc4 fix(inference): let the LoRA adapter take the base model name on vLLM 0.31 (#3913)
## Problem
`Integration tests (reverse_text_lora)` has failed since the vLLM 0.31
bump (#3888's own CI run, and main's GPU Tests at b9c0bfe87). The first
`POST /load_lora_adapter` returns `400 Bad Request` and the orchestrator
exits.

Root cause: vLLM 0.31 added a check to
`OpenAIServingModels._check_load_lora_adapter_request`. It rejects a
`lora_name` equal to a served base model name ("conflicts with a served
base model", 400). vLLM 0.30 had no such check. prime-rl registers its
adapter under the model name (`model.name`) on purpose, because every
client (rollouts, evals, the renderer client) sends that name. vLLM
serves the base model under the same name by default, so the two
collide.

## Change
No vLLM patch. With LoRA on, the inference server serves the base model
under a different name, and the adapter keeps the name clients already
send.
- `InferenceConfig.to_namespace` sets `served_model_name =
[f"{vllm.model}-base"]` when `vllm.enable_lora` is on, unless the user
sets `served_model_name` explicitly. Every launch path builds the vLLM
args here: local `rl`/`sft`, standalone `uv run inference`, SLURM
single/multi-node, and P/D prefill/decode ranks.
- `maybe_check_has_model` (startup readiness) also accepts the name as a
model's `root`. Before the first weight sync, a LoRA server lists only
`<model>-base`, whose `root` is the model path.
- The `load_lora_adapter` docstring, an orchestrator comment, and the
LoRA section of `docs/advanced.md` now describe the served name.

## Checks
- **Nothing on the policy server asks for the base model by name.**
Rollouts, evals, and the renderer/prefill scorer all send `model.name`,
which is now the adapter. OPD teachers and frozen reference models are
separate endpoints. A LoRA server also cannot serve a frozen reference
under `model.name`. Before this change that name would already have
resolved to the adapter, and the base model can now be reached as
`<model>-base`. Admin routes (`/pause`, `/update_weights`,
`/load_lora_adapter`, health, liveness) do not take a model name.
vllm-router and llm-d configs do not reference model names. Dynamo
workers are external, so this change does not affect them.
- **The v0 adapter is loaded before the first request.** The
orchestrator and online evals wait for the trainer's startup broadcast
(v0, or the resume step). They load it through `/load_lora_adapter`
before they dispatch any rollout or eval. Readiness is the only earlier
check that uses the model name, and the `root` match covers it.
- **`/metrics`:** vLLM's `model_name` label becomes `<model>-base`. The
inference-metrics collector and the concurrency controller group samples
by the `engine` label only, and the dashboard does not read vLLM's
`/metrics`.

## Tests
- `configs/ci/integration/reverse-text-lora/start.toml` on one H200 node
(vLLM 0.31.0, this commit, patch module absent): all 15 steps run and
16/16 `/load_lora_adapter` calls return 200. There are no 400s or 404s.
Reward goes from 0.145 to 0.798, matching the patched version (0.14 to
0.79). Before the first sync, `/v1/models` lists only
`...-Reverse-Text-SFT-base` (root `...-Reverse-Text-SFT`). After it, the
list also has the adapter `...-Reverse-Text-SFT` (parent
`...-SFT-base`).
- `reverse-text-sft-lora/start.toml` (5 steps) passes.
- `pytest tests/unit/orchestrator tests/unit/inference
tests/unit/test_configs.py tests/unit/test_parsers.py -m "not gpu"` (469
passed), `ruff check`, and `ruff format --check` all pass.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how LoRA vLLM instances advertise models at startup and during
readiness checks; client-facing model IDs stay the same, but anything
expecting the base under the policy name would need `<model>-base`.
> 
> **Overview**
> Fixes LoRA inference startup on **vLLM 0.31**, which returns 400 when
an adapter is registered under the same name as a served base model.
> 
> When `enable_lora` is on and `served_model_name` is not set
explicitly, **`InferenceConfig.to_namespace`** now serves the base
weights as ``<vllm.model>-base`` so the reloaded policy adapter can keep
**`model.name`** for all rollout/eval clients.
**`maybe_check_has_model`** treats a match on either the model **`id`**
or **`root`**, so readiness passes before the first `/load_lora_adapter`
when only the `-base` entry is listed. Docs and comments describe the
naming split.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
18064f3367009c265c11ffd58fb9d5b989ca7ec1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-07 15:35:07 +01:00
faresobeidandGitHub 81052082a9 fix(logger): disable loguru diagnose so crashes with large tensors exit instead of hanging (#3876)
Turn off loguru's `diagnose` on every handler.

With loguru's default `diagnose=True`, every logged exception (including
the `Fatal error in …` that `clean_exit` logs) `repr()`s the variables
in each traceback frame. A `torch` storage repr walks the storage in
Python, element by element. When a frame holds a multi-GB tensor or
storage (a checkpoint state dict, a staging buffer, model shards),
formatting the traceback takes hours. The crashing trainer then looks
hung instead of exiting, and the real error never reaches the log.

Seen while debugging async DCP checkpoint saves: the trainer stopped at
`Saving checkpoint at step 2` with no error. A faulthandler dump showed
the main thread inside `loguru/_better_exceptions.py` →
`torch/storage.py __repr__`. The actual exception (a staging error) only
showed up through `traceback.print_exc`.

Repro on CPU (a frame whose failing line references an 8 MB
`UntypedStorage`):
- main: formatting took 19.1 s. It scales with size, so about 40 min per
GB.
- this PR: 0.0 s.

Tracebacks are still logged in full; only the per-variable value
annotations are dropped.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Logging-only change that reduces exception detail slightly; improves
reliability when failures involve large tensor locals.
> 
> **Overview**
> Disables loguru’s **`diagnose`** mode on every handler installed in
`setup_logger` (JSON console, colorized stdout, and optional file sink).
> 
> With the default **`diagnose=True`**, exception formatting
**`repr()`s** locals in each traceback frame. When those locals are
large PyTorch tensors or storages, that step can take minutes or hours,
so a fatal error during logging looks like a hang and the real exception
may never appear in logs. **Full tracebacks are still logged**; only the
per-variable value annotations are omitted.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
93a682f6fedf415561d4e5f31cbf0ee8b92a2a04. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-07 15:05:05 +01:00
Florian BrandandGitHub b9c0bfe87b fix(eval): resolve endpoints and credentials through Verifiers clients (#3827)
Use Verifiers' client configuration and resolvers for Prime-RL
endpoints, credentials, headers, and timeouts. Standalone evaluation
honors an explicit URL, then `PRIME_INFERENCE_URL`, the Prime CLI
config, and the default Prime endpoint. Partial overrides retain the
correct defaults for each run type.

## Before

Prime-RL owned a separate client schema and credential/header resolvers.
Standalone eval supplied a hardcoded Prime endpoint, so changing
`PRIME_INFERENCE_URL` did not change that default. Client setup resolved
environment headers into static values, prefill scoring constructed its
own SDK client, and admin authentication reused the inference
configuration instead of resolving against the admin URL.

```mermaid
flowchart TD
    Eval["Standalone eval hardcodes Prime URL and key defaults"] --> Config["Prime-RL ClientConfig"]
    Config --> Local["Prime-RL credential and header resolvers"]
    Local --> Inference["Construct Verifiers client with resolved static headers"]
    Inference --> Prefill["Prefill builds its own OpenAI SDK client"]
    Local --> Admin["Admin client resolves using inference config"]
    AdminURL["Separate admin URL"] --> Admin
```

## After

```mermaid
flowchart TD
    Eval["Standalone eval: Prime endpoint defaults"] --> Config["Verifiers BaseClientConfig"]
    Train["Training and online eval: localhost vLLM defaults"] --> Config
    Config --> Inference["Inference client configuration"]
    Config --> Prefill["Shared SDK builder for prefill scoring"]
    Config --> Admin["Admin configuration with its own URL"]
    Inference --> Resolve["Resolve credentials and headers for actual destination"]
    Prefill --> Resolve
    Admin --> Resolve
    Runtime["Environment values and Prime CLI config"] --> Resolve
    Resolve --> Endpoint["Target endpoint"]
```

Training and online evaluation retain their vLLM defaults, including
when only part of the client config is overridden. Frozen models require
an explicit endpoint. Environment-backed headers remain references in
saved configs, and header overrides compare names case-insensitively.
Admin authentication uses the admin destination. Prefill scoring uses
the shared SDK builder's timeout and retry policy.

Depends on [Verifiers
#2766](https://github.com/PrimeIntellect-ai/verifiers/pull/2766). When
combining this with
[#3782](https://github.com/PrimeIntellect-ai/prime-rl/pull/3782) and
[#3808](https://github.com/PrimeIntellect-ai/prime-rl/pull/3808), pin a
Verifiers revision containing all three companion fixes.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how eval and inference clients pick URLs, API keys, and
headers at runtime; mis-resolution could break eval or admin traffic,
though behavior is covered by new default-preservation tests.
> 
> **Overview**
> **Client configuration now delegates to Verifiers** instead of a
duplicate Prime-RL schema and local credential/header resolvers.
`ClientConfig` extends Verifiers' `BaseClientConfig`; training and
online eval use `VLLMClientConfig` (`localhost:8000` / `VLLM_API_KEY`).
Standalone `uv run eval` drops the hardcoded Prime URL and inherits
Prime Inference defaults from Verifiers (honoring `PRIME_INFERENCE_URL`,
Prime CLI, then the standard endpoint). Frozen external models require
an explicit `base_url`.
> 
> **Runtime client setup** forwards unresolved config into Verifiers
train/eval clients (`setup_client` dumps `BaseClientConfig` fields),
resolves auth per destination in admin clients (including separate admin
URLs), and builds prefill scoring via `build_async_openai`. Docs
describe the eval endpoint precedence; tests assert partial `[client]`
overrides keep the right defaults per run type.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c643ef25637bfafb13af555d56167fdbd3525e57. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-06 15:49:52 -07:00
faresobeidandGitHub 51879014fc chore(models): sqrtsoftplus in the shared router, drop the DeepseekV4Router copy (#3854)
## Summary
`TokenChoiceTopKRouter` gets a `"sqrtsoftplus"` score function
(`sqrt(softplus(logits.float()))`, DeepSeek V4's). The copied
`DeepseekV4Router` (its whole `forward` was restated for that one
scoring line) is deleted. Standard V4 layers use `TokenChoiceTopKRouter`
directly, and `DeepseekV4HashRouter` subclasses it, forwarding the
router kwargs and only adding `tid2eid` and `selection_bias=False`. The
router signature uses `ScoreFuncType` instead of repeating the
`Literal`. The `DeepseekV4MoE` guard that rejected any `scoring_func`
other than `sqrtsoftplus` is removed, because the shared router
implements every score function.

Clamped activation: `GroupedExperts` and `FeedForward` now take either
an activation name or an `Activation` object. A new shared
`ClampedSilu(limit)` in `layers/activations.py` holds V4's clamp
(`silu(gate.clamp(max=limit)) * up.clamp(-limit, limit)`, limit from
`config.swiglu_limit`). V4's routed experts are a plain
`GroupedExperts(activation=ClampedSilu(...))` and its shared expert a
plain `FeedForward(activation=ClampedSilu(...))`. Deleted from
`deepseek_v4/moe.py`: `ClampedSwiglu`, `DeepseekV4Experts` and
`DeepseekV4MLP`. The one init difference (HF draws expert `up_proj` at
std 0.02, not `initializer_range`) is a 3-line
`DeepseekV4MoE.init_weights` override. The hash-routing table and
forward stay in the V4 file. gpt-oss's `clamped_swiglu` is different
math (`(up+1) * gate * sigmoid(1.702 * gate)`, limit fixed at 7), so it
is not merged with this. Sonic MoE rejects `ClampedSilu`, as it rejected
the old V4 experts.

## Behavior change
None for V4 checkpoints, which all ship `sqrtsoftplus`. A V4 config with
another `scoring_func` now builds with that score function instead of
raising. `sqrtsoftplus` takes the non-softmax confidence branch
(`top/sum(scores)`), the same as the deleted copy. State dict keys are
unchanged.

## Equivalence
- CPU: router and full `DeepseekV4MoE` (hash and standard layers, with
and without replay, fp32/bf16, active clamp) are bitwise identical to
main: forward, all grads, buffers and state-dict keys. Other MoE archs
(qwen3_moe, glm4_moe, minimax_m2, afmoe, laguna, gpt_oss) are unchanged.
- GPU (8×H200): qwen3_moe, glm4_moe, laguna and nemotron_h are bitwise
identical to main. deepseek_v4 is not deterministic on GPU even main vs
main; the branch is within that run-to-run spread.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches shared MoE routing and expert activation paths used beyond V4;
behavior change only for non-default V4 `scoring_func`, but incorrect
`sqrtsoftplus` parity would affect training/inference for V4
checkpoints.
> 
> **Overview**
> **DeepSeek V4 MoE is refactored onto shared layer primitives** instead
of V4-only router, expert, and MLP subclasses.
> 
> `TokenChoiceTopKRouter` now supports **`sqrtsoftplus`**
(`sqrt(softplus(logits))`), so the duplicated `DeepseekV4Router` is
removed and standard V4 layers use the shared router directly.
`DeepseekV4HashRouter` subclasses `TokenChoiceTopKRouter` and only adds
the `tid2eid` buffer. The config no longer documents `scoring_func` as
V4-only, and `DeepseekV4MoE` drops the guard that rejected
non-`sqrtsoftplus` values (other score functions now build through the
shared router).
> 
> **Clamped SwiGLU** moves into shared `ClampedSilu(limit)`;
`FeedForward` and `GroupedExperts` accept either an activation name or
an `Activation` instance. V4 wires `GroupedExperts` and optional
`FeedForward` shared experts with `ClampedSilu(config.swiglu_limit)`;
`DeepseekV4Experts`, `DeepseekV4MLP`, and local `ClampedSwiglu` are
deleted. HF-style expert `up_proj` init (std 0.02) lives in a small
`DeepseekV4MoE.init_weights` override. Unit tests target
`GroupedExperts` + `ClampedSilu` instead of `DeepseekV4Experts`.
> 
> Shipped V4 checkpoints (`sqrtsoftplus`) should behave the same;
configs with other `scoring_func` values now construct instead of
raising.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
019f42b643266b8be15ce15985b8a82034925d4b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-06 18:53:29 +01:00
faresobeidandGitHub 52e985ae9d fix(dashboard): keep replay Home/End mode when the output fits (#3878)
The dashboard smoke check at the end of the `alphabet_sort` integration
test flakes at `tests/integration/dashboard_smoke.py:164`. It asserts
that `#replay-top` is active after Home. It failed on #3767 and #3774,
which don't touch the dashboard.

**Root cause.** The smoke test presses `t` and then Home. When thinking
is hidden, a trace that overflowed the replay pane gets shorter and
fits. The browser then clamps `scrollTop` and queues a scroll event.
That event fires after Home. At that point the pane fits, so the scroll
handler sees the view as "at bottom", switches back to follow mode, and
clears `#replay-top`. The same thing happens when the pane overflows by
less than the 24px threshold, because top and bottom then count as the
same position.

**Fix.** When the replay output fits (overflow < 24px), the scroll
handler leaves the follow mode alone. Home and End decide it, and that
choice still applies if the output grows later. Scrolling a long trace
by hand still switches between the modes as before.

**Check.** I ran headless Chromium against a dashboard serving synthetic
runs, with the same steps as the smoke test (skip inference, `t`, Home,
End):
- trace that fits after hiding thinking: 4/4 failed before the fix, 4/4
passed after
- 14px overflow: 4/4 failed before the fix, 4/4 passed after
- short trace that always fits: passed before and after
- long scrollable trace: passed before and after
- long trace, scrolling up and back down by hand: still toggles follow
mode and the top/live buttons

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Small dashboard UI scroll-handler guard with no auth, data, or API
impact.
> 
> **Overview**
> Fixes flaky replay **Home/End** behavior when the trace output
**fits** (or barely overflows) in the replay pane.
> 
> The `#replay-output` scroll listener now **bails out** when
`scrollHeight - clientHeight < 24`, so clamped or near-no-op scroll
events (e.g. after hiding thinking shrinks the content) no longer force
**follow/live** mode and clear **`#replay-top`**. **Home/End** and
manual scrolling on long traces are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
83d2f3f9b71e5b4309b98146eb1ffa944db08c23. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-06 16:02:03 +01:00
63b3e85864 chore: bump vllm to 0.31.0 (#3888)
- Bump vLLM 0.30.0 → 0.31.0 (exempt `flashinfer-python` 0.7.0.post1 from
the `exclude-newer` cooldown).
- Read `enable_return_routed_experts` from
`VllmConfig.aux_output_config` (moved in 0.31).
- Router replay now always uses the V2 runner; router replay with
disaggregated P/D is rejected at config time (0.31 has no NIXL
routed-expert capture).
- Resync the copied LoRA loader in `_patch_lora_key_prefix` with 0.31
(`modules_to_save`).

Removed patches:
- `monkey_patch_deepseek_v4_request_tools_placement`: fixed upstream
(vllm#51856).
- `monkey_patch_return_routed_experts_with_nixl_connector`: crashes the
engine on 0.31.

Tested end to end: multi-node RL on SLURM (1 trainer + 1 inference
node), Qwen3-0.6B reverse-text, 10 steps. Eval reward 0.08 → 0.81.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 15:46:51 +01:00
faresobeidandGitHub 7133f8f8f2 chore(tests): delete permanently skipped tests and the vendored HF AFMoE model (#3850)
Deletes tests that are skipped unconditionally, plus the 777-line
vendored HF AFMoE model that only the skipped AFMoE test used (rev-infra
P4).

Deleted:
- `tests/unit/train/models/test_afmoe.py` (whole module skipped: "HF
afmoe model does not support flash attention 2") and
`tests/unit/train/models/afmoe_hf_modeling/` (vendored HF model;
transformers 5.6.2 ships `transformers.models.afmoe` anyway).
- `tests/unit/train/test_model.py::test_model_with_sequence_packing`
(skipped since 2025-05, "Sequence packing for Qwen not working") and
`::test_model_forward_custom_impl` (skipped, "need special token for
meta stuff in ci").
-
`tests/unit/train/rl/test_fused_lm_head.py::test_full_model_fused_vs_vanilla`
(skipped, "Produces NaNs in bf16 with FA3").
- `tests/unit/transports/test_nccl_broadcast.py` (skipped since 2025-12,
"fail only in ci").
- The `free_port` fixture in `tests/conftest.py`: only the NCCL test
used it (and it called the int as a function, so it was broken too).

No source changes. Behavior change: none. These tests never ran.

## Checks
- CI test selection: `pytest --collect-only -q tests/unit -m "not gpu"`
gives the same 673 ids before and after. `-m gpu` goes from 190 to 182
ids, and the diff is exactly the 8 skipped ids listed above. Nothing
that ran before is gone.
- `pytest -m "not gpu" tests/unit/orchestrator
tests/unit/test_configs.py tests/unit/train/rl/test_fused_lm_head.py`:
297 passed.
- `ruff check .`, `ruff format --check .`: clean.
- GPU: none needed (only skipped tests are removed).

## Conflicts
- #3833 (remove transformers modeling) edits `test_afmoe.py`,
`test_model.py::test_model_with_sequence_packing` and
`test_fused_lm_head.py::test_full_model_fused_vs_vanilla` to port them
to the new model API, but keeps them skipped. Text conflict only.
Whichever PR lands second resolves it by keeping the deletion.
- #3794 and #3698 edit the import block of `test_fused_lm_head.py`. This
PR drops `selective_log_softmax` from the same import line. Expect a
trivial text conflict.
- If an AFMoE parity check is still wanted, port it to upstream
`transformers.models.afmoe` with `sdpa` in a follow-up. That would need
a GPU run to validate.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Test-only deletions with no application code changes; CI coverage for
tests that actually ran is unchanged per PR checks.
> 
> **Overview**
> **Removes dead test code** that never executed in CI: unconditionally
skipped GPU/unit tests and the vendored HuggingFace AFMoE copy they
depended on.
> 
> Deleted the whole `tests/unit/train/models/afmoe_hf_modeling/` tree
(~777 lines) plus `test_afmoe.py`, since upstream `transformers` already
ships AFMoE and the module was skipped for flash-attention
incompatibility. Also drops skipped cases in `test_model.py` (sequence
packing, Meta Llama custom forward),
`test_fused_lm_head.py::test_full_model_fused_vs_vanilla`, and the
entire `test_nccl_broadcast.py` module.
> 
> `tests/conftest.py` loses the unused `free_port` fixture and its
`socket` import (only the NCCL test used it, and incorrectly).
`test_fused_lm_head.py` no longer imports `selective_log_softmax` after
removing the skipped full-model test.
> 
> **No production/runtime behavior change** — only fewer collected tests
(8 GPU-marked ids removed).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
61235f155a74f04ee3119deb9a4b557839313bec. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-05 16:34:20 -07:00
JannikStandGitHub b029ef253e fix(ci): move all 2-GPU GPU Tests jobs to h200 k8s runners (#3835)
Moves every GPU Tests job that fits in 2 GPUs onto the `prime-rl-2xh200`
ARC scale set, so runs stop queueing behind the two `vm` runners.
Stacked on #3834.

**Assignment**
- `prime-rl-2xh200` (9): unit-tests, reverse_text, reverse_text_sft,
reverse_text_sft_lora, reverse_text_lora, reverse_text_moe,
reverse_text_rl_opd, reverse_text_rl_sft, alphabet_sort, gsm8k_eval
- `4xa6000` (1): benchmark_regression, unchanged

The `vm` runners are left registered and untouched - just no longer on
the GPU Tests path.

**Sizing checks**
- Integration configs put inference on GPU 0 and trainer on GPU 1, so 2
GPUs each.
- Unit tests peak at `world_size=2` (NCCL broadcast test); `gsm8k_eval`
needs no GPU.
- benchmark_regression stays put: baselines are A6000-pinned
(`benchmark-4xa6000-*.json`) and the 4-GPU case exceeds a job pod. Note
`4xa6000` has zero registered runners today, so it queues regardless of
this PR.

**Worth knowing:** 12 tests in `test_deepseek_v4_kernels.py` are gated
on `requires_datacenter_gpu` (compute capability 9/10). They skip on
A6000 and will begin running on H200 - new coverage, but they have not
run in CI before.

Runners use `containerMode: kubernetes`, so `container:` blocks work
unchanged - each job gets a fresh pod, no Docker daemon, no privileged
containers.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> CI-only runner reassignment can surface new failures when
datacenter-GPU-gated unit tests run on H200 for the first time;
production code paths are untouched.
> 
> **Overview**
> **GPU Tests** CI now targets the `prime-rl-2xh200` Kubernetes runner
scale set instead of `vm` for every job that needs at most two GPUs.
> 
> The **unit-tests** job and nine **integration-tests** matrix entries
(`reverse_text*`, `alphabet_sort`, `gsm8k_eval`, etc.) all use
`prime-rl-2xh200`. **`benchmark_regression`** is unchanged on `4xa6000`
because it needs four GPUs and A6000-pinned baselines.
> 
> No test commands, containers, or matrix structure change—only
`runs-on` / `runner` labels. Unit tests on H200 may start executing
tests gated by `requires_datacenter_gpu` in
`test_deepseek_v4_kernels.py` that previously skipped on
`vm`/A6000-class hardware.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
579a43fe10fbd114a1bf935bd43917fc63873a18. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-05 19:50:31 +02:00
minh hoangandGitHub eae8bd9462 fix(docker): include FlashMLA in docker image (#3887)
Hosted image `v0.9.1.dev200` fails when GLM-5 selects `model.dsa_backend
= "cudnn_flashmla"`: the forward path imports `flash_mla`, but Docker's
explicit sync extras omit `flash-mla`. The [dev200 build
log](https://github.com/PrimeIntellect-ai/prime-rl/actions/runs/37265534904)
confirms the missing extra; `nvidia-cudnn-frontend` is already
installed.

Add `--extra flash-mla` to the dependency-image sync and the
source-override entrypoint sync. Add an amd64 package-presence check
before publishing the dependency image. The existing Linux/x86_64 marker
excludes the wheel on arm64, and the Dockerfile change invalidates the
dependency-image fingerprint.

## Verification

- Compared locked requirement exports with the exact Docker extras
before and after the fix: amd64 adds only the pinned FlashMLA wheel;
arm64 requirements are unchanged. Neither platform loses dependencies,
and both include `nvidia-cudnn-frontend==1.30.0`.
- Confirmed Docker and source-override entrypoint extras match.
- Downloaded the pinned CPython 3.12/CUDA 13/PyTorch 2.13 wheel and
verified its lockfile SHA256. Confirmed it exports
`flash_mla_sparse_fwd` and includes the native extension.
- Docker Buildx Dockerfile checks: no warnings. Bash syntax and `git
diff --check`: passed.

GPU import and execution checks on a rebuilt image are still pending.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Build-time dependency and publish-time presence checks only; arm64 is
unchanged because the extra is x86_64-gated in the lockfile.
> 
> **Overview**
> Adds the **`flash-mla`** optional dependency to CUDA image builds and
runtime source overlays so GLM-5 paths using `model.dsa_backend =
"cudnn_flashmla"` can import `flash_mla` in hosted images.
> 
> **`Dockerfile.cuda`** includes `--extra flash-mla` in the builder `uv
sync` (alongside the other GPU extras) and, on **x86_64 only**, asserts
`flash-mla` is present in the published dependency image via
`importlib.metadata`. **`scripts/docker-entrypoint.sh`** adds the same
extra to `uv sync` when `PRIME_RL_REF` overlays a checkout, keeping the
entrypoint extras list aligned with the Dockerfile comment.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
12329d455836ab80ac581e18de7339718312e7a9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-05 09:15:35 -07:00
106 changed files with 1711 additions and 2405 deletions
+20 -5
View File
@@ -192,6 +192,12 @@ jobs:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
with:
# CVE-2026-93318: pin the BuildKit builder to the patched release so
# the version is deterministic on the self-hosted runners (otherwise
# the rolling moby/buildkit:buildx-stable-1 tag is used, and a
# persistent runner may keep a stale local copy of it).
driver-opts: image=moby/buildkit:v0.33.1@sha256:cec9f139f45e93c5c69c60f8b07cfad9f43f4ef6b6a6cd917527fea5ff2e3dea
- name: Set up uv
uses: astral-sh/setup-uv@v7
@@ -207,7 +213,12 @@ jobs:
run: |
set -euo pipefail
key=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py fingerprint .)
image="${REGISTRY}/${IMAGE_NAME}:deps-${key}-${SUFFIX}"
# deps-v2: remediation epoch for CVE-2026-93318 — the fingerprint
# hashes only Dockerfile/lock inputs, not the workflow or BuildKit
# version, so pre-fix deps-${key} images would otherwise be reused
# as the runtime base instead of being rebuilt by the pinned v0.33.1
# builder.
image="${REGISTRY}/${IMAGE_NAME}:deps-${key}-v2-${SUFFIX}"
digest=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py resolve "$image")
echo "image=${image}" >> "$GITHUB_OUTPUT"
echo "digest=${digest}" >> "$GITHUB_OUTPUT"
@@ -222,8 +233,10 @@ jobs:
file: ./Dockerfile.cuda
target: dependencies
outputs: type=image,push=true,compression=zstd,compression-level=3
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
# buildcache-v2: rotated 2026-10-05 for CVE-2026-93318 — the pre-v0.33.1
# builders (cache writers since 2026-08-16) must not be re-imported.
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-v2-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-v2-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
platforms: ${{ matrix.platform }}
tags: ${{ steps.dependency.outputs.image }}
@@ -240,8 +253,10 @@ jobs:
RENDERERS_PRETEND_VERSION=${{ steps.dependency.outputs.renderers }}
PYDANTIC_CONFIG_PRETEND_VERSION=${{ steps.dependency.outputs.pydantic_config }}
outputs: type=image,push=true,compression=zstd,compression-level=3
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
# buildcache-v2: rotated 2026-10-05 for CVE-2026-93318 — the pre-v0.33.1
# builders (cache writers since 2026-08-16) must not be re-imported.
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-v2-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-v2-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
platforms: ${{ matrix.platform }}
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
+14 -9
View File
@@ -6,6 +6,10 @@ on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: true
jobs:
unit-tests:
name: Unit tests
@@ -15,15 +19,16 @@ jobs:
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run tests
+157 -48
View File
@@ -5,20 +5,103 @@ on:
branches: [main]
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
changes:
name: Select tests
runs-on: ubuntu-latest
if: github.event_name != 'pull_request' || github.event.pull_request.draft == false
permissions:
pull-requests: read
outputs:
unit: ${{ github.event_name != 'pull_request' || steps.filter.outputs.unit == 'true' }}
integration: ${{ steps.matrix.outputs.tests }}
eval: ${{ github.event_name != 'pull_request' || steps.filter.outputs.eval == 'true' }}
steps:
- uses: dorny/paths-filter@v4
id: filter
if: github.event_name == 'pull_request'
with:
filters: |
unit:
- &runtime
- '.github/workflows/gpu_tests.yaml'
- '{pyproject.toml,uv.lock,.python-version,.gitmodules}'
- 'deps/**'
- 'packages/**/pyproject.toml'
- 'packages/prime-rl-configs/src/prime_rl/configs/{trainer,shared,__init__}.py'
- 'packages/prime-rl-configs/src/prime_rl/utils/**'
- 'src/prime_rl/*.py'
- 'src/prime_rl/{trainer,multimodal,transports,utils}/**'
- 'tests/{__init__.py,conftest.py,utils.py}'
- 'tests/integration/{__init__.py,conftest.py}'
- 'tests/unit/{train,inference}/**'
- 'src/prime_rl/inference/**'
sft:
- *runtime
- 'tools/convert_{dcp_to_bf16,dcp_to_fp8,bf16_to_fp8,fp8_to_bf16}.py'
- 'src/prime_rl/dashboard/**'
- 'tests/integration/dashboard_smoke.py'
- 'packages/prime-rl-configs/src/prime_rl/configs/{sft,eval,monitors}.py'
- 'src/prime_rl/entrypoints/{sft,dashboard}.py'
- 'src/prime_rl/monitors/**'
- 'src/prime_rl/eval/{online,runner}.py'
- 'tests/integration/test_reverse_text_sft{,_lora}.py'
- 'configs/ci/integration/reverse-text-sft{,-lora}/**'
rl:
- *runtime
- 'tools/convert_{dcp_to_bf16,dcp_to_fp8,bf16_to_fp8,fp8_to_bf16}.py'
- 'src/prime_rl/dashboard/**'
- 'tests/integration/dashboard_smoke.py'
- 'packages/prime-rl-configs/src/prime_rl/configs/{rl,orchestrator,inference,env_server,algorithm,eval,monitors}.py'
- 'src/prime_rl/entrypoints/{rl,trainer,inference,orchestrator,env_server,dashboard}.py'
- 'src/prime_rl/{inference,orchestrator,monitors}/**'
- 'src/prime_rl/eval/{online,runner}.py'
- 'tests/integration/test_reverse_text{,_lora,_moe,_rl_opd,_rl_sft}.py'
- 'tests/integration/test_alphabet_sort.py'
- 'configs/ci/integration/reverse-text{,-lora,-moe,-rl-opd,-rl-sft}/**'
- 'configs/ci/integration/alphabet_sort.toml'
eval:
- *runtime
- 'packages/prime-rl-configs/src/prime_rl/configs/{eval,orchestrator,inference,env_server,algorithm,monitors}.py'
- 'src/prime_rl/{eval,orchestrator,monitors}/**'
- 'src/prime_rl/entrypoints/{eval,env_server}.py'
- 'tests/integration/test_gsm8k_eval.py'
- 'configs/ci/integration/gsm8k-eval.toml'
- name: Build integration matrix
id: matrix
env:
# Main and manual runs retain the full suite.
RUN_ALL: ${{ github.event_name != 'pull_request' }}
SFT: ${{ steps.filter.outputs.sft || 'false' }}
RL: ${{ steps.filter.outputs.rl || 'false' }}
run: |
tests=$(jq -cn --argjson all "$RUN_ALL" --argjson sft "$SFT" --argjson rl "$RL" '[
if $all or $sft then "reverse_text_sft", "reverse_text_sft_lora" else empty end,
if $all or $rl then
"reverse_text", "reverse_text_rl_opd", "reverse_text_rl_sft",
"alphabet_sort", "reverse_text_lora", "reverse_text_moe"
else empty end
]')
echo "tests=$tests" >> "$GITHUB_OUTPUT"
unit-tests:
name: Unit tests
runs-on: vm
needs: changes
runs-on: prime-rl-2xh200
container:
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
options: --gpus all
timeout-minutes: 45
if: github.event_name == 'push' || github.event.pull_request.draft == false
if: needs.changes.outputs.unit == 'true'
steps:
- name: Install Git
run: |
@@ -29,12 +112,16 @@ jobs:
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run unit tests
@@ -50,46 +137,20 @@ jobs:
integration-tests:
name: Integration tests (${{ matrix.test }})
runs-on: ${{ matrix.runner }}
needs: changes
runs-on: prime-rl-2xh200
container:
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
options: --gpus all
timeout-minutes: 60
if: github.event_name == 'push' || github.event.pull_request.draft == false
if: needs.changes.outputs.integration != '[]'
strategy:
fail-fast: false
# Bound per-PR fan-out: at most 5 integration jobs at a time (plus unit-tests),
# i.e. 6 h200 pods per PR. Tune together with the ARC scale set maxRunners.
max-parallel: 5
matrix:
include:
- test: reverse_text_sft
runner: vm
pytest_args: "tests/integration/test_reverse_text_sft.py"
- test: reverse_text_sft_lora
runner: vm
pytest_args: "tests/integration/test_reverse_text_sft_lora.py"
- test: reverse_text
runner: vm
pytest_args: "tests/integration/test_reverse_text.py"
- test: reverse_text_rl_opd
runner: vm
pytest_args: "tests/integration/test_reverse_text_rl_opd.py"
- test: reverse_text_rl_sft
runner: vm
pytest_args: "tests/integration/test_reverse_text_rl_sft.py"
- test: alphabet_sort
runner: vm
pytest_args: "tests/integration/test_alphabet_sort.py"
- test: reverse_text_lora
runner: vm
pytest_args: "tests/integration/test_reverse_text_lora.py"
- test: reverse_text_moe
runner: vm
pytest_args: "tests/integration/test_reverse_text_moe.py"
- test: benchmark_regression
runner: 4xa6000
pytest_args: "tests/integration/test_benchmark_regression.py"
- test: gsm8k_eval
runner: vm
pytest_args: "tests/integration/test_gsm8k_eval.py"
test: ${{ fromJSON(needs.changes.outputs.integration) }}
steps:
- name: Install Git
run: |
@@ -100,12 +161,16 @@ jobs:
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run integration tests
@@ -120,7 +185,7 @@ jobs:
GITHUB_HEAD_REF: ${{ github.head_ref }}
PYTEST_OUTPUT_DIR: /tmp/outputs
VLLM_WORKER_MULTIPROC_METHOD: spawn
run: uv run pytest -vvs ${{ matrix.pytest_args }}
run: uv run pytest -vvs tests/integration/test_${{ matrix.test }}.py
- name: Upload run logs on failure
if: failure()
uses: actions/upload-artifact@v7
@@ -129,3 +194,47 @@ jobs:
path: /tmp/outputs/**/*.log
retention-days: 7
if-no-files-found: ignore
eval-tests:
name: Integration tests (gsm8k_eval)
needs: changes
if: needs.changes.outputs.eval == 'true'
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Checkout repository
uses: actions/checkout@v7
with:
submodules: false
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run eval tests
env:
USERNAME_CI: CI_RUNNER
WANDB_MODE: offline
HF_TOKEN: ${{ secrets.HF_TOKEN }}
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
GITHUB_REF_NAME: ${{ github.ref_name }}
GITHUB_HEAD_REF: ${{ github.head_ref }}
PYTEST_OUTPUT_DIR: /tmp/outputs
run: uv run pytest -vvs tests/integration/test_gsm8k_eval.py
- name: Upload run logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: gsm8k_eval-logs
path: /tmp/outputs/**/*.log
retention-days: 7
if-no-files-found: ignore
+4
View File
@@ -9,6 +9,10 @@ on:
# This will trigger the workflow for pull requests to any branch
types: [opened, synchronize, reopened]
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: true
jobs:
ruff:
name: Ruff
+5 -2
View File
@@ -94,7 +94,7 @@ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
# The runtime dependency image contains no first-party source or editable installs.
COPY --from=manifests /manifests /app
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
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 --locked --no-dev \
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra flash-mla --extra disagg --extra quack --extra kernels --locked --no-dev \
--no-install-local
# Build NIXL from source against the UCX 1.19 baked above. The PyPI nixl wheel
@@ -243,7 +243,10 @@ COPY --from=builder --chown=appuser:appuser \
--exclude=lib/python3.12/site-packages/flash_attn \
--exclude=lib/python3.12/site-packages/flash_attn_2_cuda*.so \
/app/.venv /app/.venv
RUN /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")]'
RUN /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")]' \
&& if [ "$(uname -m)" = "x86_64" ]; then \
/app/.venv/bin/python -c 'from importlib.metadata import version; version("flash-mla")'; \
fi
# Place executables in the environment at the front of the path
ENV PATH="/app/.venv/bin:$PATH"
+1 -1
+1 -1
+1 -1
View File
@@ -187,7 +187,7 @@ dropout = 0.0
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`).
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`). With LoRA on, the inference server registers the adapter under the model name and serves the base model as `<model>-base`.
## Disaggregated Prefill/Decode Inference
+1 -1
View File
@@ -139,7 +139,7 @@ algo.type = "echo"
### The Algorithm Classes
At runtime, each env's resolved config builds two objects: a `GenerationSource` (`prime_rl.orchestrator.generation_source`) that resolves the `sampling.source` model into the inference pool used for train episodes, and one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
At runtime, each env's `TrainEnv` (`prime_rl.orchestrator.envs`) resolves the `sampling.source` model into the inference pool used for train episodes, and its resolved config builds one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
| `algo.type` | Class | hook(s) — stage |
|---|---|---|
+4
View File
@@ -173,6 +173,10 @@ env.agent.runtime.type = "subprocess"
Each source group — `[orchestrator.train]`, `[orchestrator.eval]`, the `[eval]` block of `sft` and the top level of `eval` — holds defaults for its sources. Every field that a group and its sources both have is a default: `env`, `sampling`, `select` and `group_size`, plus `algo` on the train group and `interval` on the eval groups of a training run. Each source inherits the fields that its group sets. One rule applies to all of them: nested blocks merge key by key, a source's own values win, and a block whose `type` (e.g. of `algo`) differs from the group's is the source's alone.
Sampling parameters use Verifiers' shared normalization: `max_tokens` and `max_completion_tokens` name the same limit, and `extra_body` parameters merge like top-level parameters. Agent overrides apply after source defaults; an explicit null clears an inherited parameter. Resolved sampling is recorded on each trace.
For live-policy training, set distribution parameters (`temperature`, `top_p`, `top_k`) on the source's `sampling` block. Every agent in that source, including non-trainable roles, may override only `max_tokens`, `reasoning_effort`, and `chat_template_kwargs`. These rules are checked when loading the config; evaluation and frozen-model sources allow general agent sampling overrides.
```toml
[orchestrator.train]
group_size = 16
+1 -1
View File
@@ -42,7 +42,7 @@ uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenar
| Workflow | Trigger | What runs | Where |
|---|---|---|---|
| [`cpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/cpu_tests.yaml) | every PR + push to `main` | `pytest tests/unit -m "not gpu"`, plus a slim-wheel install check that `prime-rl-configs` imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in `sys.modules`) | `ubuntu-latest` |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | relevant changes in non-draft PRs; full suite on push to `main` or manual dispatch | `pytest tests/unit -m gpu`, plus RL/SFT integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_sft_lora`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `alphabet_sort`) with `max-parallel: 5`; separate hosted `gsm8k_eval` job | self-hosted `prime-rl-2xh200` k8s scale set (2xH200); `ubuntu-latest` for test selection and hosted eval |
| [`nightly_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/nightly_tests.yaml) | 03:00 PST daily + manual `workflow_dispatch` (single-file filter optional) | every file in `tests/nightly/`, one matrix job per file | `research-cluster` |
The GPU + Nightly workflows skip drafts — open the PR as **Draft** until you're ready to consume CI compute, then mark it ready for review to trigger the GPU matrix.
+4 -2
View File
@@ -25,6 +25,8 @@ uv run eval gsm8k -n 32 -r 4 -c 8 # Prime Infe
uv run eval @ configs/debug/eval/single-turn.toml # the same shape as a TOML
```
The default endpoint comes from `PRIME_INFERENCE_URL`, then the Prime CLI's `inference_url`, then the standard Prime Inference URL. An explicit `client.base_url` wins. API keys and environment-backed headers are resolved when clients are built; Prime CLI credential and team fallbacks apply only to Prime Inference hosts, including for a separate admin URL.
To evaluate a model you serve yourself, start a `uv run inference` vLLM server (or any OpenAI-compatible API) and point the client at it:
```bash
@@ -80,7 +82,7 @@ Every source's env server is spawned by the eval process unless the source sets
## Resume
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: the episodes that landed rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch) and only the rollouts still owed run. Errored episodes and the ones the interruption cut off run again.
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: saved episodes with `episode.ok` rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch), and only the rollouts still owed run. Failed episodes and the ones the interruption cut off run again. Saved records that fail schema validation stop the resume before the current stream is archived.
```bash
uv run eval @ eval.toml --run.name my-eval
@@ -90,7 +92,7 @@ uv run eval @ eval.toml --run.name my-eval --resume
The previous attempt's `monitors/file` is kept as `monitors/file.attempt_N`; the resumed attempt writes a fresh one. Nothing is deleted, and a resume reads every attempt's stream.
A landed episode counts toward the task with its `task.key`, so `select` and `group_size` may change between the two launches: 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, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. Rollouts that complete a task's landed group join that group, so pass@k and the dashboard see one group per task. Use `--clean` to start over instead.
A landed episode counts toward a selected task in the same source when their content hashes (`task.hash`) match. A task whose content changes runs again even if its public `task.key` stays the same. `select` and `group_size` may change between launches: each selected occurrence keeps up to `group_size` matching episodes, and only its missing rollouts run. The resumed config is not checked against the interrupted one: any of it may be overridden, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. Each selected occurrence owns a separate group containing its restored and new rollouts, even when the same task is selected more than once, so pass@k and the dashboard see one group per selected occurrence. Use `--clean` to start over instead.
## Monitors
+2 -2
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`. Standard deployments use the V2 model runner. 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`. Capture runs on vLLM's V2 model runner (forced automatically). Router replay is not supported with disaggregated P/D: vLLM does not capture routed experts across NIXL KV transfer.
```toml
[trainer]
@@ -313,6 +313,6 @@ top_k = 512 # optional, defaults to 512 under truncation (bounds each sampling
That's all — there are no replay flags. Truncated train sampling makes the inference server return sampling masks (`inference.enable_return_sampling_mask`, auto-enabled), and the trainer replays them. Train-sampling `top_k` above 512 is rejected: the trainer pads each micro batch to its largest sampling mask, so the bound caps trainer memory. Configs that would break under renormalized logprobs are rejected: `opd`/`opsd` and truncation knobs smuggled via `extra_body`. Frozen-source envs are exempt.
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run with router replay on standard deployments. The combination is not supported with disaggregated P/D because NIXL routed-expert capture uses V1. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run together with router replay. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
When launching the inference server standalone, set `inference.enable_return_sampling_mask = true` yourself; clients must sample with `0 < top_k <= 512`.
+5
View File
@@ -62,6 +62,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| `orchestrator.train.group_size` | Rollouts generated per task. |
| `orchestrator.max_off_policy_steps` | Maximum staleness of a trained rollout (default 8): the version a batch trains on minus the oldest version that generated the rollout, queue time included. Episodes past the bound are dropped; a group shares one dispatch version, so its episodes age out together. The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `off_policy/*` and `mismatch_kl/all/mean` when tuning. |
| `[orchestrator.train.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `trainer.model.freeze_moe_router` | Freeze MoE router gates (default `true` for RL, `false` for SFT). Router updates in RL shift the trainer's expert choices away from the ones inference sampled, amplifying the train-inference mismatch, so RL keeps the pretrained router. Set `false` to train it. |
| `[[orchestrator.train.source]]` | Training sources. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Training sources](configuration.md#training-sources-orchestratortrainsource). |
| `[[orchestrator.eval.source]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
@@ -158,6 +159,10 @@ messages = "conversation"
tools = "schemas"
```
**Per-message loss selection.** An optional `message_loss_mask` column contains one boolean or integer 0/1 per message. For example, `[0, 0, 0, 1]` on a user/assistant/user/assistant conversation trains only the final assistant turn while retaining the full context. For prompt-completion rows, the mask covers the concatenated prompt and completion messages. Zero excludes a message; one preserves the normal role and renderer loss settings. A missing or null mask leaves those settings unchanged. The renderer applies selection without changing token IDs, including ownership of assistant closing tokens. Invalid mask lengths or entries raise an error.
To read a differently named column, set `data.columns.message_loss_mask = "selection"`.
**Tool definitions and renderer controls.** For tool-use SFT, add a `tools` column in OpenAI function-calling format. Each row's value can be either a list of dicts or a JSON-encoded string of a list.
Renderer-backed SFT reads template controls from the typed `[renderer]` config in the SFT TOML. For example:
@@ -5,10 +5,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-search"
partition = "all"
@@ -23,11 +23,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
partition = "all"
-5
View File
@@ -19,11 +19,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-swe"
partition = "all"
@@ -6,10 +6,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-terminal"
partition = "all"
@@ -2,7 +2,6 @@ clean = true
[env_vars]
HF_HOME = "/home/huggingface"
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
[model]
name = "zai-org/GLM-5.3-BF16"
+1
View File
@@ -89,6 +89,7 @@ attn = "flash_attention_2" # ignored with GLM5
fused_lm_head_token_chunk_size = 1024
cp = 4 # context parallel for the 131K seq len
ep = 8
dsa_backend = "cudnn_flashmla"
[trainer.model.quantization]
type = "fp8"
@@ -2,7 +2,6 @@ clean = true
[env_vars]
HF_HOME = "/home/huggingface"
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
[model]
name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
@@ -40,11 +40,11 @@ import verifiers.v1 as vf
from pydantic import Field, model_validator
from renderers import AutoRendererConfig, RendererConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.configs.shared import VLLMClientConfig
from prime_rl.utils.config import BaseConfig
class FrozenModelConfig(ClientConfig):
class FrozenModelConfig(VLLMClientConfig):
"""An externally hosted model behind an OpenAI-compatible endpoint: the
client config plus the served model's ``name``.
@@ -57,14 +57,7 @@ class FrozenModelConfig(ClientConfig):
name: str
"""Served model name, sent as the ``model`` field of every request."""
@model_validator(mode="after")
def require_explicit_endpoint(self):
if "base_url" not in self.model_fields_set:
raise ValueError(
"a frozen model reference needs base_url — frozen models are externally "
"hosted; prime-rl only ever hosts the trainable policy."
)
return self
base_url: str
ModelReference: TypeAlias = Literal["policy"] | FrozenModelConfig
@@ -6,7 +6,14 @@ from pydantic import AliasChoices, Field, model_validator
from prime_rl.configs.monitors import EvalMonitorsConfig
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
from prime_rl.configs.shared import ClientConfig, HeartbeatConfig, LogConfig, RunConfig, WeightBroadcastConfig
from prime_rl.configs.shared import (
ClientConfig,
HeartbeatConfig,
LogConfig,
RunConfig,
VLLMClientConfig,
WeightBroadcastConfig,
)
from prime_rl.utils.config import default_output_dir
@@ -14,7 +21,7 @@ class ServedEvalConfig(EvalSourcesConfig):
"""Eval sources run against a live inference server: the server's client and the
adaptive concurrency band."""
client: ClientConfig = ClientConfig()
client: VLLMClientConfig = Field(default_factory=VLLMClientConfig)
"""Client of the inference server evals run against."""
concurrency: ConcurrencyConfig = ConcurrencyConfig()
@@ -43,9 +50,6 @@ class ServedEvalConfig(EvalSourcesConfig):
return {("eval", source.resolved_name): source.serve.address for source in self.source}
PRIME_INFERENCE_URL = "https://api.pinference.ai/api/v1"
class EvalConfig(ServedEvalConfig):
"""``uv run eval``: evaluate the configured sources once against a live inference
server, then exit. Every source's env server is spawned by the eval process unless
@@ -55,7 +59,7 @@ class EvalConfig(ServedEvalConfig):
model: str = Field("deepseek/deepseek-v4.1-flash", validation_alias=AliasChoices("model", "m"))
"""Model id — the ``model`` field of every eval request and the startup model check."""
client: ClientConfig = ClientConfig(base_url=PRIME_INFERENCE_URL, api_key_var="PRIME_API_KEY")
client: ClientConfig = Field(default_factory=ClientConfig)
"""Client of the inference server. Defaults to Prime Inference."""
select: vf.SelectCLIConfig = vf.SelectCLIConfig()
@@ -509,16 +509,12 @@ class InferenceConfig(BaseConfig):
return self
@model_validator(mode="after")
def validate_disaggregated_combined_replay(self):
"""NIXL routed-expert capture uses the V1 runner, while sampling replay needs V2."""
if (
self.deployment.type == "disaggregated"
and self.enable_return_sampling_mask
and self.vllm.enable_return_routed_experts
):
def validate_disaggregated_no_routed_experts(self):
"""vLLM rejects routed-expert capture with NIXL KV transfer."""
if self.deployment.type == "disaggregated" and self.vllm.enable_return_routed_experts:
raise ValueError(
"Combined router and sampling replay is not supported with disaggregated P/D: "
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
"Routed-expert return (enable_return_routed_experts) is not supported with disaggregated P/D: "
"vLLM does not capture routed experts across NIXL KV transfer."
)
return self
@@ -662,6 +658,11 @@ class InferenceConfig(BaseConfig):
if self.enable_return_sampling_mask:
namespace.return_sampling_mask = True
# The LoRA adapter is registered under the model name clients send, and vLLM rejects
# an adapter named like a served base model, so serve the base under another name.
if self.vllm.enable_lora and "served_model_name" not in extra_fields:
namespace.served_model_name = [f"{self.vllm.model}-base"]
kv_transfer_config = self.build_kv_transfer_config()
if kv_transfer_config is not None:
namespace.kv_transfer_config = kv_transfer_config
@@ -6,6 +6,7 @@ import verifiers.v1 as vf
from pydantic import AliasChoices, BaseModel, Field, SerializeAsAny, TypeAdapter, ValidationError, model_validator
from pydantic.fields import FieldInfo
from renderers import AutoRendererConfig, RendererConfig
from verifiers.v1.configs.agent import agent_config_fields
from prime_rl.configs.algorithm import (
AlgoConfig,
@@ -14,13 +15,13 @@ from prime_rl.configs.algorithm import (
from prime_rl.configs.monitors import TrainMonitorsConfig
from prime_rl.configs.shared import (
BaseModelConfig,
ClientConfig,
EnvVars,
FileSystemWeightBroadcastConfig,
HeartbeatConfig,
LogConfig,
ResumeConfig,
TransportConfig,
VLLMClientConfig,
WeightBroadcastConfig,
ZMQTransportConfig,
)
@@ -40,7 +41,7 @@ class ModelConfig(BaseModelConfig):
lora: LoRAConfig | None = None
"""Per-run LoRA configuration. If None, LoRA is disabled."""
client: ClientConfig = ClientConfig()
client: VLLMClientConfig = Field(default_factory=VLLMClientConfig)
"""Client of the live deployment (``[orchestrator.model.client]``)."""
@@ -90,70 +91,6 @@ class TrainSamplingConfig(BaseConfig):
)
return self
def to_sampling_args(self) -> dict[str, Any]:
"""Convert to OAI-compatible sampling args dict, omitting None values."""
args: dict[str, Any] = {
"temperature": self.temperature,
"top_p": self.top_p,
"logprobs": True,
}
if self.max_completion_tokens is not None:
args["max_completion_tokens"] = self.max_completion_tokens
# top_k rides extra_body (like EvalSamplingConfig), overriding the sentinel.
extra_body = dict(self.extra_body)
if self.top_k is not None:
extra_body["top_k"] = self.top_k
if extra_body:
args["extra_body"] = extra_body
return args
class EvalSamplingConfig(BaseConfig):
temperature: float | None = Field(None, ge=0, le=2.0)
"""Sampling temperature. None defers to the inference server default."""
top_p: float | None = None
"""Nucleus sampling threshold. None defers to the inference server default."""
top_k: int | None = None
"""Top-k sampling. None defers to the inference server default."""
min_p: float | None = Field(None, ge=0)
"""Min-p sampling threshold. None defers to the inference server default."""
max_completion_tokens: int | None = None
"""Maximum output tokens per turn. None defers to the inference server default."""
reasoning_effort: Literal["minimal", "low", "medium", "high"] | None = None
"""Reasoning effort constraint for reasoning models."""
extra_body: dict[str, Any] = {}
"""Extra body parameters forwarded to the inference server."""
def to_sampling_args(self) -> dict[str, Any]:
"""Convert to OAI-compatible sampling args dict. Only includes non-None fields."""
args: dict[str, Any] = {}
if self.temperature is not None:
args["temperature"] = self.temperature
if self.top_p is not None:
args["top_p"] = self.top_p
if self.max_completion_tokens is not None:
args["max_completion_tokens"] = self.max_completion_tokens
if self.reasoning_effort is not None:
args["reasoning_effort"] = self.reasoning_effort
extra_body = dict(self.extra_body)
if self.top_k is not None:
extra_body["top_k"] = self.top_k
if self.min_p is not None:
extra_body["min_p"] = self.min_p
if extra_body:
args["extra_body"] = extra_body
return args
class EnvConfig(BaseConfig):
"""One environment a run pulls from: the verifiers blocks it composes (``env`` — what
@@ -316,9 +253,37 @@ class TrainSourceConfig(EnvConfig):
"""User-authored task sampler and admission gates. The default cycles
through the taskset and admits every finalized group."""
@model_validator(mode="after")
def validate_policy_sampling(self):
if self.algo.sampling.source != "policy":
return self
# The source owns the distribution replayed by the trainer; agents may
# change generation limits and rendering without changing that distribution.
agent_options = {"max_tokens", "reasoning_effort", "chat_template_kwargs"}
supported = (
agent_options
| TrainSamplingConfig.model_fields.keys()
| {"min_p", "logprobs", "return_token_ids", "cache_salt"}
)
sampling = vf.SamplingConfig(**self.sampling.model_dump(exclude_none=True))
if unsupported := sampling.model_dump(exclude_none=True).keys() - supported:
raise ValueError(
f"Policy source '{self.resolved_name}' has unsupported sampling parameters: {sorted(unsupported)}"
)
for name, agent in agent_config_fields(self.env).items():
if agent.sampling is None:
continue
if unsupported := agent.sampling.model_dump(exclude_unset=True).keys() - agent_options:
raise ValueError(
f"Agent '{name}' in policy source '{self.resolved_name}' sets sampling {sorted(unsupported)}. "
"Set distribution parameters on the source's sampling config; agent sampling only supports "
f"{sorted(agent_options)}."
)
return self
class EvalSourceConfig(EnvConfig):
sampling: EvalSamplingConfig = EvalSamplingConfig()
sampling: vf.SamplingConfig = vf.SamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level eval sampling config."""
group_size: int = Field(1, ge=1)
@@ -409,7 +374,7 @@ class EvalSourcesConfig(SourceGroupConfig):
source: list[EvalSourceConfig] = Field(default_factory=list)
"""Evaluation sources."""
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
sampling: vf.SamplingConfig = Field(default_factory=vf.SamplingConfig)
"""Sampling that every eval source inherits; can differ from training sampling."""
select: vf.SelectConfig = vf.SelectConfig()
@@ -433,17 +433,8 @@ class RLConfig(BaseConfig):
"PEFT-shaped directory on disk (LoRAModel.from_local_checkpoint) - in-memory transports "
"have no disk artifact to load from."
)
if "inference_world_size" in self.weight_broadcast.model_fields_set:
raise ValueError("weight_broadcast.inference_world_size is set automatically by rl; remove it.")
update = {}
if self.weight_broadcast.type != "filesystem":
update["inference_world_size"] = (
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
if self.inference
else 1
)
self.trainer.weight_broadcast = self.weight_broadcast.model_copy(update=update)
self.orchestrator.weight_broadcast = self.weight_broadcast.model_copy(update=update)
self.trainer.weight_broadcast = self.weight_broadcast.model_copy()
self.orchestrator.weight_broadcast = self.weight_broadcast.model_copy()
if self.inference is not None:
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
return self
@@ -595,17 +586,17 @@ class RLConfig(BaseConfig):
return self
@model_validator(mode="after")
def validate_disaggregated_combined_replay(self):
def validate_disaggregated_no_routed_experts(self):
"""Runs after ``auto_setup_router_replay``, which sets the inference flag after InferenceConfig's validators."""
inference = self.inference
if (
inference is not None
and inference.deployment.type == "disaggregated"
and inference.enable_return_sampling_mask
and inference.vllm.enable_return_routed_experts
):
raise ValueError(
"Combined router and sampling replay is not supported with disaggregated P/D: "
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
"Router replay (inference.vllm.enable_return_routed_experts / trainer.enable_router_replay) "
"is not supported with disaggregated P/D: vLLM does not capture routed experts across NIXL KV transfer."
)
return self
@@ -659,6 +650,11 @@ class RLConfig(BaseConfig):
dp = self.inference.vllm.data_parallel_size
if self.inference.vllm.api_server_count < dp and not self.inference.vllm.enable_lora:
self.inference.vllm.api_server_count = dp
if self.weight_broadcast.type != "filesystem":
# Every inference GPU joins the in-memory transfer group, so size it after the DP fill.
world_size = dp * self.inference.vllm.tensor_parallel_size
self.trainer.weight_broadcast.inference_world_size = world_size
self.orchestrator.weight_broadcast.inference_world_size = world_size
elif self.deployment.type == "multi_node": # multi-node
self.orchestrator.num_train_workers = (
@@ -101,6 +101,9 @@ class SFTColumnsConfig(BaseConfig):
tools: str = "tools"
"""Column with the tool schemas in OpenAI function-calling format."""
message_loss_mask: str = "message_loss_mask"
"""Optional column of booleans or integer 0/1 flags, one per resolved message (prompt + completion for split rows). Zero excludes a message from loss; one preserves its normal supervision. Missing or null masks leave supervision unchanged."""
renderer: dict[str, str] = {"reasoning_effort": "reasoning_effort"}
"""Per-sample renderer arguments as ``renderer field = dataset column``, e.g. ``reasoning_effort = "effort"``. A row's non-null value overrides the ``[renderer]`` setting; rows and datasets without the column use it unchanged."""
@@ -283,6 +286,13 @@ class SFTConfig(BaseConfig):
self.optim.weight_decay = 0.01
return self
@model_validator(mode="after")
def resolve_freeze_moe_router_auto(self):
"""Resolve ``model.freeze_moe_router='auto'``: SFT trains the router."""
if self.model.freeze_moe_router == "auto":
self.model.freeze_moe_router = False
return self
@model_validator(mode="after")
def auto_setup_run_identity(self):
"""Auto-generate the run name (``<dataset>--<model>--<short-id>``) when unset and
@@ -4,6 +4,7 @@ from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from pydantic import AfterValidator, Field, model_validator
from verifiers.v1.configs.client import BaseClientConfig
from prime_rl.utils.config import BaseConfig
@@ -212,22 +213,10 @@ class DynamoConfig(BaseConfig):
"""Dynamo frontend URL used to discover inference workers for RL control."""
class ClientConfig(BaseConfig):
class ClientConfig(BaseClientConfig):
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"
"""Base URL for the OpenAI API. For multi-replica deployments, point this at a router in front of the replicas."""
api_key_var: str = "VLLM_API_KEY"
"""Environment variable name containing the API key, resolved via ``os.getenv``. Can be any string when the server is not protected by an API key; the same key is used for every URL."""
headers: dict[str, str] = {}
"""Static headers sent with every request."""
headers_from_env: dict[str, str] = {}
"""Maps HTTP header names to environment variable names; each entry is resolved via ``os.getenv`` and merged into request headers. e.g. ``{"X-Prime-Team-ID": "PRIME_TEAM_ID"}``."""
skip_model_check: bool = False
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
@@ -238,6 +227,13 @@ class ClientConfig(BaseConfig):
"""Dynamo RL worker-discovery configuration."""
class VLLMClientConfig(ClientConfig):
"""Client defaults for the live inference deployment managed by training."""
base_url: str = "http://localhost:8000/v1"
api_key_var: str = "VLLM_API_KEY"
class LogConfig(BaseConfig):
level: str = Field(default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"))
"""Log level for the process. Defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``."""
@@ -332,8 +332,8 @@ class ModelConfig(BaseModelConfig):
index_cache: IndexCacheConfig | None = None
"""DSA IndexCache sub-configuration. If set, sparse-attention top-k indices are reused across decoder layers per the configured schedule (mirrors vLLM's IndexCache HF overrides). If None, every layer recomputes its own indices."""
freeze_moe_router: bool = False
"""Freeze MoE router parameters during training."""
freeze_moe_router: bool | Literal["auto"] = "auto"
"""Freeze MoE router gate parameters. ``auto`` (default): ``True`` for RL, ``False`` for SFT; a no-op on non-MoE models. Frozen routers get no optimizer state, so resuming a checkpoint saved with a frozen router with ``freeze_moe_router=false`` fails on missing DCP keys."""
lora: LoRAConfig | None = None
"""LoRA configuration. If None, LoRA is disabled."""
@@ -612,6 +612,9 @@ class DataLoaderConfig(BaseConfig):
fake: FakeDataLoaderConfig | None = None
"""Use a fake data loader sampling random micro-batches (for debugging)."""
num_workers: int = Field(0, ge=0)
"""Number of background threads that prepare micro batches ahead of the training loop, analogous to torch DataLoader's ``num_workers`` but with threads instead of processes. 0 prepares them on the main thread."""
class TrainerConfig(BaseConfig):
model: ModelConfig = ModelConfig()
@@ -688,6 +691,13 @@ class TrainerConfig(BaseConfig):
self.optim.weight_decay = 0.0
return self
@model_validator(mode="after")
def resolve_freeze_moe_router_auto(self):
"""Resolve ``model.freeze_moe_router='auto'``: RL keeps the pretrained router."""
if self.model.freeze_moe_router == "auto":
self.model.freeze_moe_router = True
return self
@model_validator(mode="after")
def deepep_disables_grad_clipping(self):
if self.model.ep != 1 and self.model.moe.dispatch.type == "deepep" and self.optim.max_norm is not None:
+9 -7
View File
@@ -16,7 +16,7 @@ dependencies = [
"wandb>=0.26.1",
"wandb-workspaces>=0.4.3",
"prime>=0.8.0",
"prime-runs[train]>=0.1.3",
"prime-runs[train]>=0.1.4",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
"tenacity>=8.2.0",
@@ -53,7 +53,7 @@ gpu = [
"torchvision ; sys_platform == 'linux'",
"torchaudio ; sys_platform == 'linux'",
"torchdata>=0.11.0 ; sys_platform == 'linux'",
"vllm>=0.30.0 ; sys_platform == 'linux'",
"vllm>=0.31.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'",
@@ -147,7 +147,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.30.0 requires this exact CUTLASS DSL version and quack-kernels 0.6.5.
# vLLM 0.31.0 requires this exact CUTLASS DSL version and quack-kernels 0.6.5.
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
"nvidia-cutlass-dsl==4.7.1",
"transformers==5.6.2",
@@ -225,10 +225,12 @@ requires-dist = [
]
[tool.uv.exclude-newer-package]
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
# verifiers pins harbor==0.24.0, published inside the rolling window;
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
harbor = "2026-08-11T00:00:00Z"
harbor = "2026-10-08T00:00:00Z"
tokenspeed-mla = false
# vLLM 0.31.0 pins flashinfer-python 0.7.0.post1, published inside the rolling window
flashinfer-python = false
fastokens = false
flash_attn_3 = false
# PrimeIntellect-published packages in this project's dependency closure —
@@ -278,8 +280,8 @@ vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.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'" },
+1 -1
View File
@@ -113,7 +113,7 @@ HEAVY_PINS_PY
echo "[prime-rl] syncing ${DEST} into /app/.venv"
( cd "$DEST" && uv sync --inexact --locked --no-dev --all-packages \
--extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 \
--extra flash-attn-cute --extra disagg --extra quack --extra kernels )
--extra flash-attn-cute --extra flash-mla --extra disagg --extra quack --extra kernels )
# The chart's `uv run --no-sync <entrypoint>` commands resolve the
# project from the cwd; the venv itself stays /app/.venv via
# UV_PROJECT_ENVIRONMENT above.
+2
View File
@@ -7314,6 +7314,8 @@ $("#tm-messages").addEventListener(
"scroll",
(e) => {
if (!e.target.matches?.("#replay-output") || !replay) return;
// top and bottom coincide when the output fits; keep the mode Home/End chose
if (e.target.scrollHeight - e.target.clientHeight < 24) return;
const atBottom = e.target.scrollHeight - e.target.scrollTop - e.target.clientHeight < 24;
replay.followOutput = atBottom;
$("#replay-top")?.classList.toggle("active", !atBottom);
+5 -6
View File
@@ -8,6 +8,8 @@ rollouts still owed run (``prime_rl.eval.resume``)."""
from __future__ import annotations
import verifiers.v1 as vf
from prime_rl import monitors
from prime_rl.configs.eval import EvalConfig
from prime_rl.eval import resume
@@ -24,7 +26,7 @@ class Eval:
async def run(self) -> None:
config = self.config
landed: list[dict] = []
landed: list[vf.WireEpisode] = []
if config.resume:
# read and set aside before the monitors start: the resumed attempt writes a fresh stream
landed = resume.take_landed(config.run_dir)
@@ -41,17 +43,14 @@ class Eval:
)
resume.stamp_config(config.run_dir, dump_resolved_config(config))
await self.runner.setup()
restored: list = []
fired, restored = self.runner.eval_source.trigger(0, completed=landed)
if config.resume:
restored, owed, groups = resume.plan(landed, self.runner.eval_envs)
self.runner.eval_source.restore(owed, groups)
get_logger().info(
f"Resuming from the trace stream: {len(restored)} episodes restored, "
f"{sum(sum(counts.values()) for counts in owed.values())} rollouts owed"
f"{sum(request.rollouts or 0 for request in self.runner.eval_source.queue)} rollouts owed"
)
await self.runner.start()
fired = self.runner.eval_source.trigger(0)
await self.runner.run_epoch(fired, 0, restored=restored)
await self.runner.drain()
+1 -1
View File
@@ -178,7 +178,7 @@ class OnlineEval:
# Trigger before the reload: the dispatcher only schedules eval in PREFER_EVAL,
# so nothing dispatches until ``run_epoch`` switches modes below.
fired = runner.eval_source.trigger(step, force=force)
fired, _ = runner.eval_source.trigger(step, force=force)
self.last_step = max(self.last_step, step)
if reload_weights:
+14 -50
View File
@@ -1,20 +1,18 @@
"""Resume an interrupted eval from its trace stream.
The stream records what landed, so it is what a resume continues from. The run's ok
episodes are read back and rejoin the epoch as if they had just arrived - through the
monitors, so the rebuilt stream, the epoch's metrics and the platform upload cover the
whole epoch - and only the rollouts still owed run. Errored episodes and the in-flight
The stream records what landed, so it is what a resume continues from. Successful
episodes rejoin the epoch through the monitors as if they had just arrived,
so the rebuilt stream, the epoch's metrics and the platform upload cover the
whole epoch - and only the rollouts still owed run. Failed episodes and the in-flight
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. The resumed
config is not checked against the interrupted one: any of it may be overridden.
The shared Verifiers rollout planner matches these episodes to the current tasks
by content hash. 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 pathlib import Path
@@ -23,7 +21,6 @@ import verifiers.v1 as vf
from prime_rl.monitors.file.traces import get_trace_stream
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
CONFIG_NAME = "eval.json"
@@ -57,52 +54,19 @@ def archives(run_dir: Path) -> list[Path]:
return sorted(monitors.glob("file.attempt_*"), key=lambda path: int(path.name.rsplit("_", 1)[1]))
def take_landed(run_dir: Path) -> list[dict]:
"""The ok eval episodes the run has landed, each once, from every attempt's stream.
def take_landed(run_dir: Path) -> list[vf.WireEpisode]:
"""Successful episodes from every attempt; the planner deduplicates them.
The current file monitor directory joins the archives so the resumed attempt writes a
fresh stream, plan and metrics; nothing is deleted."""
current = get_file_monitor_dir(run_dir)
stream = get_trace_stream(run_dir).relative_to(current)
landed: dict[str, dict] = {}
landed: list[vf.WireEpisode] = []
for directory in [*archives(run_dir), current]:
if (directory / stream).is_dir():
for record in read_records(directory / stream):
if record.get("ok"):
landed.setdefault(record["id"], record)
episode = vf.WireEpisode.model_validate(record)
if episode.ok and "traces" in record:
landed.append(episode)
if current.is_dir():
current.rename(current.with_name(f"file.attempt_{len(archives(run_dir)) + 1}"))
return list(landed.values())
def plan(
landed: list[dict], eval_envs: EvalEnvs
) -> tuple[list[vf.WireEpisode], dict[str, dict[str, int]], dict[str, dict[str, str]]]:
"""Match the landed episodes to the run's tasks: the episodes to keep, in stream
order, the rollouts still owed per env and task key, and the group id a task's kept
episodes carry, so the owed ones complete that group rather than open another."""
targets: dict[str, Counter[str]] = {}
for env in eval_envs:
targets[env.name] = Counter(task.key for task in env.examples)
for key in targets[env.name]:
targets[env.name][key] *= env.config.group_size
kept: list[vf.WireEpisode] = []
counts: dict[str, Counter[str]] = defaultdict(Counter)
groups: dict[str, dict[str, str]] = defaultdict(dict)
for record in landed:
env_name = record["env"].get("name") or record["env"]["id"]
key = record["task"]["key"]
if counts[env_name][key] >= targets.get(env_name, Counter())[key]:
continue
kept.append(vf.WireEpisode.model_validate(record))
counts[env_name][key] += 1
if (group := record.get("group") or {}).get("id"):
groups[env_name].setdefault(key, group["id"])
owed = {
env_name: {
key: target - counts[env_name][key]
for key, target in target_counts.items()
if target > counts[env_name][key]
}
for env_name, target_counts in targets.items()
}
return kept, owed, dict(groups)
return landed
+2 -1
View File
@@ -105,7 +105,7 @@ class EvalRunner:
# Pessimistic per-episode token cost for the controller's starting cap,
# only used when the engine doesn't report its max context length.
fallback_cost = max((source.sampling.max_completion_tokens or 0) for source in config.source) or 8192
fallback_cost = max((source.sampling.max_tokens or 0) for source in config.source) or 8192
self.concurrency = ConcurrencyController(config.concurrency, fallback_cost=fallback_cost)
self.dispatcher = Dispatcher(
train_envs=None,
@@ -114,6 +114,7 @@ class EvalRunner:
eval_source=self.eval_source,
policy_clients=self.clients,
policy=self.policy,
policy_weights_change=isinstance(config, SFTOnlineEvalConfig),
progress=None,
initial_max_inflight=self.concurrency.max_inflight,
max_inflight_ceiling=config.concurrency.max_inflight,
+2 -106
View File
@@ -18,11 +18,9 @@ def apply_shared_vllm_patches():
_patch_qwen35_moe_lora_format()
monkey_patch_nano_v3_reasoning_parser()
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_tokenize_params_validation()
monkey_patch_strip_routed_experts_from_chat()
monkey_patch_dp_coordinator_startup_timeout()
@@ -49,64 +47,6 @@ 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.
@@ -243,51 +183,6 @@ def monkey_patch_minimax_m2_think_end_passthrough():
minimax_m2.minimax_m2_config = _patched_config
def monkey_patch_return_routed_experts_with_nixl_connector():
from vllm.config.vllm import VllmConfig
from vllm.logger import init_logger
logger = init_logger(__name__)
original_post_init = VllmConfig.__post_init__
if getattr(original_post_init, "_prime_rl_allows_nixl_routed_experts", False):
return
def _is_nixl_routed_experts_pd_config(config: VllmConfig) -> bool:
kv_transfer_config = config.kv_transfer_config
return (
config.model_config is not None
and config.model_config.enable_return_routed_experts
and kv_transfer_config is not None
and kv_transfer_config.kv_connector == "NixlConnector"
and kv_transfer_config.is_kv_transfer_instance
)
def _post_init(config: VllmConfig):
if not _is_nixl_routed_experts_pd_config(config):
return original_post_init(config)
if config.parallel_config.pipeline_parallel_size > 1:
raise ValueError("--enable-return-routed-experts is incompatible with pipeline parallelism (PP > 1).")
if config.use_v2_model_runner:
raise ValueError(
"Routed-expert capture with NIXL requires the V1 model runner. Set VLLM_USE_V2_MODEL_RUNNER=0."
)
# vLLM rejects every KV connector, but our P/D path uses NIXL and
# stitches prefill/decode routed experts in the router. CPU KV offload
# remains rejected by prime-rl config validation.
config.model_config.enable_return_routed_experts = False
try:
return original_post_init(config)
finally:
config.model_config.enable_return_routed_experts = True
_post_init._prime_rl_allows_nixl_routed_experts = True
VllmConfig.__post_init__ = _post_init
logger.warning("Enabled vLLM routed-experts capture with NIXL connector patch.")
def monkey_patch_strip_routed_experts_from_chat():
"""Drop routed_experts from chat-completions responses.
@@ -431,6 +326,7 @@ def _patch_lora_key_prefix():
if skip_prefixes and cls._should_skip_module(lora_module, skip_prefixes):
continue
module_name, _ = parse_fine_tuned_lora_name(lora_module, weights_mapper)
base_name = module_name.rsplit(".", 1)[-1]
# Case for expert lora weights.
## START PATCHED CODE (upstream only accepts the qualified form)
if ".experts" in module_name:
@@ -440,7 +336,7 @@ def _patch_lora_key_prefix():
unexpected_modules.append(module_name)
## END PATCHED CODE
elif module_name.rsplit(".", 1)[-1] not in expected_lora_modules:
elif base_name not in expected_lora_modules and base_name not in (peft_helper.modules_to_save or ()):
unexpected_modules.append(module_name)
if unexpected_modules:
+3 -8
View File
@@ -10,15 +10,10 @@ def setup_vllm_env(config: InferenceConfig):
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
# Standard deployments use V2 for both capture modes. NIXL P/D also uses V2
# for sampling-mask capture, but router replay remains on V1 because vLLM
# rejects routed-expert capture with KV connectors and prime-rl's stitching
# patch is V1-only. setdefault keeps an explicit env-var choice authoritative.
if config.enable_return_sampling_mask:
# vLLM captures sampling masks and routed experts only on the V2 model runner.
# setdefault keeps an explicit env-var choice authoritative.
if config.enable_return_sampling_mask or config.vllm.enable_return_routed_experts:
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1")
elif config.vllm.enable_return_routed_experts:
use_v2_runner = config.deployment.type != "disaggregated"
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1" if use_v2_runner else "0")
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
# grammar-constrains generation (xgrammar structural tags) for tool_choice
+6 -8
View File
@@ -62,14 +62,12 @@ async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: R
"""Wrapper around vLLM's /v1/load_lora_adapter.
prime-rl reloads a fixed-name adapter with fresh weights every step (the path
changes per policy version; the name is constant — the base model name, which
the adapter shadows: ``_maybe_get_adapters`` resolves ``lora_requests`` before
the base-model match, so requests keep addressing one stable name. If a future
vLLM rejects registering an adapter under a served model name, fall back to a
distinct constant adapter name set once at startup.) vLLM's native loader
rejects a same-name reload unless ``load_inplace=True``, so we force it here —
that makes the worker re-read the new weights during ``add_lora``, reusing the
existing ``lora_int_id``.
changes per policy version; the name is constant — the model name every client
sends. vLLM rejects an adapter named like a served base model, so with LoRA on
the base model is served as ``<model>-base``; see ``InferenceConfig.to_namespace``.)
vLLM's native loader rejects a same-name reload unless ``load_inplace=True``, so
we force it here — that makes the worker re-read the new weights during
``add_lora``, reusing the existing ``lora_int_id``.
We then reset the stored request's flag back to ``False``. ``load_inplace`` is
a sticky field on the ``LoRARequest`` that ``_maybe_get_adapters`` hands to
@@ -66,7 +66,7 @@ class PrimeRlServingTokens(ServingTokens):
request_metadata: RequestResponseMetadata,
) -> ErrorResponse | GenerateResponse:
routed_experts: _GenerateRoutedExpertsCapture | None = None
if self.model_config.enable_return_routed_experts:
if self.engine_client.vllm_config.aux_output_config.enable_return_routed_experts:
routed_experts = _GenerateRoutedExpertsCapture(
result_generator,
start=request.sampling_params.routed_experts_prompt_start,
+45 -2
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
import atexit
import fcntl
import os
import time
@@ -251,7 +252,12 @@ class PrimeEvalMonitor(Monitor):
evaluation per env and step, opened when the epoch starts (``log_eval_plan``), fed
every episode as it lands (``log_episodes``) and finished with the epoch's aggregates
(``log_eval_epoch``), so the platform page follows the run from its first episode.
Metrics are not forwarded; the evaluation is the epoch."""
Under a managed launch ($RUN_ID) the epoch's ``eval/{env}/...`` metrics ALSO go to
the parent training run, which is what the run dashboard groups into its `eval`
section. The orchestrator's in-process evals reach it through the train monitor, but
an eval process of its own (SFT online evals) has no other way there, so without
this the run shows every metric group except the one its evals produced."""
config: PrimeEvalMonitorConfig
@@ -268,6 +274,7 @@ class PrimeEvalMonitor(Monitor):
# (env, step) -> its open evaluation; None once opening it failed, so the epoch's
# episodes do not retry the platform on every arrival
self.runs: dict[tuple[str, int], pr.Run | None] = {}
self.parent: pr.Run | None = None
self._lock = asyncio.Lock()
self.evaluation_id = os.getenv(EVAL_ID_VAR)
if self.evaluation_id and len(self.sources) != 1:
@@ -277,6 +284,7 @@ class PrimeEvalMonitor(Monitor):
)
if self.mode == "online":
self.logger.info("Streaming eval epochs to the Prime platform")
self.parent = await asyncio.to_thread(self._attach_parent)
if output_dir is not None:
# Merge, not overwrite: when the eval process shares the
# trainer's run dir (SFT online evals), the train record's
@@ -294,8 +302,39 @@ class PrimeEvalMonitor(Monitor):
else:
self.logger.info(f"Platform evaluations disabled ({pr.MODE_ENV}=disabled)")
def _attach_parent(self) -> pr.Run | None:
"""The parent training run this eval process belongs to, for metrics only.
Blocking: runs in a worker thread.
Attaching is a local handle, not a request, so a run that turns out to be
unreachable costs the eval nothing. The caller owns the run's lifecycle: we
drop the SDK's atexit crash hook, because an eval process that exits while the
trainer is still going would otherwise report the WHOLE run failed."""
run_id = os.getenv("RUN_ID")
if not run_id:
return None
run = pr.init(
kind="train",
mode=self.mode,
base_url=_base_url(),
id=run_id,
finish_timeout=FINISH_TIMEOUT,
)
atexit.unregister(run._atexit_hook) # the SDK's own unregister handle
self.logger.info(f"Logging eval metrics to parent training run {run.id}")
return run
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
pass
"""An epoch's aggregates (``eval/{env}/...``) onto the parent training run.
Only there: a standalone eval has no parent, and the per-epoch evaluation
carries its own aggregates through ``log_eval_epoch``."""
if self.parent is None:
return
metrics, dropped = sanitize(metrics)
if dropped:
self.logger.warning(f"Dropping {len(dropped)} non-finite metric value(s): {', '.join(dropped[:5])}")
# A queue put that can block briefly under backpressure - off the loop.
await asyncio.to_thread(self.parent.log_metrics, metrics, step=step)
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."""
@@ -400,3 +439,7 @@ class PrimeEvalMonitor(Monitor):
await asyncio.to_thread(run.finish, status=pr.RunStatus.CANCELLED, error="interrupted")
except Exception as e:
self.logger.warning(f"Failed to close the {env_name} (Step {step}) evaluation: {type(e).__name__}: {e}")
if self.parent is not None:
# Drain only. The parent run belongs to the trainer and the platform: an
# eval process must never report its status, not even a clean completion.
await asyncio.to_thread(self.parent.flush, FINISH_TIMEOUT)
+4 -5
View File
@@ -2,8 +2,8 @@
The config side (``prime_rl.configs.algorithm``) defines *what* an algorithm
is — a bundle of sampling and the per-token training signal. This package
turns the signal half into runtime objects (the sampling half is the env's
:class:`~prime_rl.orchestrator.generation_source.GenerationSource`):
turns the signal half into runtime objects (the sampling half is interpreted by
:class:`~prime_rl.orchestrator.envs.TrainEnv`):
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``rae``,
``hierarchical_grpo``, ``opd``, ``opsd``, ``sft``, ``debug``) — each named
@@ -22,7 +22,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_client
from prime_rl.orchestrator.algo.base import Algorithm
from prime_rl.orchestrator.algo.debug import DebugAlgorithm
from prime_rl.orchestrator.algo.echo import EchoAlgorithm
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
@@ -56,7 +56,7 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
def build_algorithm(config: AlgoConfig, clients: InferenceClient) -> Algorithm:
cls = ALGORITHM_CLASSES[config.type]
# The Algorithm is the runtime of the algorithm config's training signal
# (its sibling GenerationSource interprets the sampling half). Every algorithm is
# (its TrainEnv interprets the sampling half). Every algorithm is
# handed the live policy pool — opsd self-distills against it, others may
# judge against it or ignore it. Other models (a frozen teacher, a hint
# renderer) are built from the algorithm's own config in setup().
@@ -75,7 +75,6 @@ __all__ = [
"RAEAlgorithm",
"SFTDistillAlgorithm",
"build_algorithm",
"connect_frozen_client",
"assign_advantages",
"stamp_loss_routing",
]
+2 -26
View File
@@ -2,41 +2,17 @@
from __future__ import annotations
from typing import TYPE_CHECKING
import verifiers.v1 as vf
from prime_rl.configs.algorithm import AlgoConfig, FrozenModelConfig
from prime_rl.utils.logger import get_logger
if TYPE_CHECKING:
from renderers import RendererConfig
from prime_rl.orchestrator.clients import InferenceClient
async def connect_frozen_client(
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
) -> InferenceClient:
"""Connect to an externally hosted frozen model and wait for it."""
from prime_rl.orchestrator.clients import InferenceClient, check_inference_ready
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
if renderer_config is not None:
clients = InferenceClient(
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
)
else:
clients = InferenceClient(config, model_name=config.name)
await check_inference_ready(config, config.name)
return clients
from prime_rl.orchestrator.clients import InferenceClient, connect_frozen_client
def iter_trainable_traces(episodes: list[vf.Episode]):
"""Yield clean trainable traces that contain sampled tokens."""
for episode in episodes:
for trace in episode.traces:
if trace.has_error or not trace.agent.trainable:
if not episode.ok or trace.has_error or not trace.agent.trainable or trace.num_turns == 0:
continue
if any(any(node.mask) for node in trace.nodes):
yield episode, trace
+2 -3
View File
@@ -696,11 +696,10 @@ def _distribute_group(
def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBatch:
"""
Pad a micro batch with the given padding size sample
Return the padded micro batch.
Pad a micro batch with loss-masked tokens up to the next multiple of `pad_to_multiple_of`.
Args:
micro_batch: The micro batch to pad.
padding_size: The number of padding tokens to add.
pad_to_multiple_of: The multiple to pad the sequence length up to.
Returns:
The padded micro batch.
"""
+33 -45
View File
@@ -1,7 +1,6 @@
from __future__ import annotations
import asyncio
import os
from collections.abc import Callable
from pathlib import Path
from typing import Literal
@@ -12,40 +11,20 @@ from httpx import AsyncClient
from openai import AsyncOpenAI
from renderers import RendererConfig
from tenacity import AsyncRetrying, retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
from verifiers.v1.configs.client import EvalClientConfig, TrainClientConfig
from verifiers.v1.clients.base import build_async_openai
from verifiers.v1.configs.client import (
BaseClientConfig,
EvalClientConfig,
TrainClientConfig,
resolve_api_key,
resolve_headers,
)
from prime_rl.configs.eval import PRIME_INFERENCE_URL
from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.logger import get_logger
def resolve_api_key(api_key_var: str) -> str:
"""The API key named by ``api_key_var``; ``PRIME_API_KEY`` also falls back to the prime
CLI config (``prime login``), like the verifiers client does. ``"EMPTY"`` when unset."""
api_key = os.environ.get(api_key_var)
if not api_key and api_key_var == "PRIME_API_KEY":
from prime_sandboxes import Config as PrimeConfig
api_key = PrimeConfig().api_key
return api_key or "EMPTY"
def resolve_headers(client_config: ClientConfig) -> dict[str, str]:
"""The static headers plus those read from the environment. A Prime Inference client
without a team header gets the team from ``$PRIME_TEAM_ID`` or the prime CLI config,
like the verifiers client: a team's internal models are served only under it."""
env_headers = {
k: v for k, v in ((k, os.getenv(v)) for k, v in client_config.headers_from_env.items()) if v is not None
}
headers = {**client_config.headers, **env_headers}
if client_config.base_url.startswith(PRIME_INFERENCE_URL) and "X-Prime-Team-ID" not in headers:
from prime_sandboxes import Config as PrimeConfig
if team_id := os.environ.get("PRIME_TEAM_ID") or PrimeConfig().team_id:
headers["X-Prime-Team-ID"] = team_id
return headers
class PrefillScorer:
"""Prefill-scores token ids against a pool's endpoint, lazily resolving
a single OpenAI client from the pool's train client config."""
@@ -55,14 +34,8 @@ class PrefillScorer:
async def score(self, config: vf.ClientConfig, model: str, token_ids: list[int]) -> list[float]:
if self._client is None:
# Build the OpenAI client straight from the config fields — works for any
# ClientConfig type; resolve_client would hand back an EvalClient (no `.openai`)
# for these chat-completions teacher configs.
self._client = AsyncOpenAI(
base_url=config.base_url,
api_key=resolve_api_key(config.api_key_var),
default_headers=config.headers or None,
)
# Prefill scoring uses the SDK even when generation uses the eval relay.
self._client = build_async_openai(config)
return await prefill_logprobs(self._client, model, token_ids)
async def aclose(self) -> None:
@@ -256,6 +229,21 @@ async def check_inference_ready(client_config: ClientConfig, model_name: str) ->
await admin.aclose()
async def connect_frozen_client(
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
) -> InferenceClient:
"""Connect to an externally hosted frozen model and wait for it."""
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
if renderer_config is not None:
clients = InferenceClient(
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
)
else:
clients = InferenceClient(config, model_name=config.name)
await check_inference_ready(config, config.name)
return clients
def setup_client(
client_config: ClientConfig,
client_type: str = "openai_chat_completions",
@@ -274,10 +262,7 @@ def setup_client(
"renderer": renderer_config,
"renderer_model_name": renderer_model_name,
}
headers = resolve_headers(client_config)
return config_cls(
base_url=client_config.base_url, api_key_var=client_config.api_key_var, headers=headers, **renderer_extra
)
return config_cls(**client_config.model_dump(include=set(BaseClientConfig.model_fields)), **renderer_extra)
def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
@@ -290,8 +275,9 @@ def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
urls = client_config.admin_base_url if client_config.admin_base_url else [client_config.base_url]
def _setup_admin_client(base_url: str) -> httpx.AsyncClient:
headers = resolve_headers(client_config)
api_key = resolve_api_key(client_config.api_key_var)
config = client_config.model_copy(update={"base_url": base_url})
headers = resolve_headers(config)
api_key = resolve_api_key(config)
if api_key != "EMPTY":
headers["Authorization"] = f"Bearer {api_key}"
@@ -324,7 +310,9 @@ async def maybe_check_has_model(
f"{result.text[:300]}"
)
models = body["data"]
if not any(model["id"] == model_name for model in models):
# A LoRA server lists the model name only once the adapter is loaded; until then
# the base model (served as ``<model>-base``) carries it as its ``root``.
if not any(model_name in (model["id"], model.get("root")) for model in models):
raise ValueError(f"Model {model_name} was not found in the inference pool on {admin_client.base_url}")
logger.debug(f"Model {model_name} was found in the inference pool")
+3 -2
View File
@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any
import verifiers.v1 as vf
from prime_rl.orchestrator.algo.base import iter_trainable_traces
from prime_rl.orchestrator.curriculum.gates import AdmissionGate
from prime_rl.orchestrator.curriculum.samplers import TaskSampler
@@ -48,7 +49,7 @@ class Curriculum:
self.gates[name] = gate
def on_result(self, group: list[vf.Episode]) -> bool:
"""Observe every result, evaluate every gate, and combine with AND."""
"""Observe every result and admit trainable groups that pass every gate."""
if not group:
raise ValueError("Cannot report an empty rollout group")
task_keys = {episode.task.key for episode in group}
@@ -63,7 +64,7 @@ class Curriculum:
if not isinstance(decision, bool):
raise TypeError(f"AdmissionGate {name!r}.admit() must return bool, got {type(decision).__name__}")
decisions.append(decision)
return all(decisions)
return all(decisions) and any(iter_trainable_traces(group))
def state_dict(self) -> dict[str, Any]:
return {
@@ -27,7 +27,7 @@ class AdvRangeGate(AdmissionGate):
advantage
for episode in group
for trace in episode.traces
if not trace.has_error and trace.agent.trainable
if episode.ok and not trace.has_error and trace.agent.trainable
for node in trace.nodes
for advantage in node.advantages or []
]
@@ -68,7 +68,7 @@ class DifficultyPoolSampler(TaskSampler):
trace.reward
for episode in group
for trace in episode.traces
if not trace.has_error and trace.agent.trainable
if episode.ok and not trace.has_error and trace.agent.trainable and trace.num_turns > 0
]
if not rewards:
return
+19 -25
View File
@@ -143,9 +143,11 @@ class Dispatcher:
max_off_policy_steps: int,
run_id: str,
run_name: str | None,
policy_weights_change: bool = True,
on_episode_complete: Callable[[int], None] | None = None,
) -> None:
self.policy = policy
self.policy_weights_change = policy_weights_change
self.progress = progress
self.train_envs = train_envs
self.eval_envs = eval_envs
@@ -214,10 +216,10 @@ class Dispatcher:
"""``(clients, model_name, is_live)`` for *train* rollouts of this env —
eval always uses the policy."""
assert self.train_envs is not None # train groups only exist when train is configured
source = self.train_envs.get(env_name).generation_source
if source.uses_live_policy:
return source.clients, self.policy.model_name, True
return source.clients, source.clients.model_name, False
env = self.train_envs.get(env_name)
if env.uses_live_policy:
return env.clients, self.policy.model_name, True
return env.clients, env.clients.model_name, False
@property
def inflight_train_count(self) -> int:
@@ -316,7 +318,7 @@ class Dispatcher:
return [
(self.progress.step - 1) - meta.policy_version
for meta in self.inflight.values()
if meta.kind == "train" and self.train_envs.get(meta.env_name).generation_source.uses_live_policy
if meta.kind == "train" and self.train_envs.get(meta.env_name).uses_live_policy
]
# ── lifecycle ──────────────────────────────────────────────────────────
@@ -423,7 +425,7 @@ class Dispatcher:
gid
for gid, group in self.groups.items()
if group.kind == "train"
and self.train_envs.get(group.env_name).generation_source.uses_live_policy
and self.train_envs.get(group.env_name).uses_live_policy
and group.policy_version_at_start < min_version
]
cancelled = 0
@@ -556,10 +558,8 @@ class Dispatcher:
if env_collection is None:
return False
env = env_collection.get(group.env_name)
# Frozen-sourced train rollouts hit a frozen pool; salting per policy
# version would invalidate its prefix cache every weight update for
# no reason.
if live_sourced:
# Only endpoints receiving policy weight updates need a cache salt.
if live_sourced and self.policy_weights_change:
cache_salt = str(group.policy_version_at_start)
else:
cache_salt = None
@@ -665,10 +665,6 @@ class Dispatcher:
)
return
if not episode.traces and episode.ok:
episode.ok = False
episode.errors.append(vf.Error(type="EmptyEpisode", message="Episode returned with no traces"))
for trace in episode.traces:
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,
@@ -676,14 +672,6 @@ class Dispatcher:
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``).
# 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
get_logger().warning(f"Empty trajectory in group {meta.group_id} ({meta.env_name})")
if trace.has_error:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if trace.last_error is not None:
@@ -691,8 +679,14 @@ class Dispatcher:
f"Trace failed in group {meta.group_id} ({meta.env_name}) — "
f"{trace.last_error.type}: {trace.last_error.message}"
)
if not episode.ok and not episode.traces:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if not episode.ok:
if not any(trace.has_error for trace in episode.traces):
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
error = episode.last_error
get_logger().warning(
f"Episode failed in group {meta.group_id} ({meta.env_name})"
+ (f" — {error.type}: {error.message}" if error is not None else "")
)
if self.on_episode_complete is not None and meta.started_at > 0:
self.on_episode_complete(episode.num_total_tokens)
await self.emit_episode(meta, group, episode)
@@ -722,7 +716,7 @@ class Dispatcher:
live_policy = meta.kind == "eval"
if meta.kind == "train":
assert self.train_envs is not None
live_policy = self.train_envs.get(meta.env_name).generation_source.uses_live_policy
live_policy = self.train_envs.get(meta.env_name).uses_live_policy
policy = vf.PolicySpan(start=policy_version, end=self.policy.version) if live_policy else None
work: vf.WorkInfo = (
vf.EvalWorkInfo(step=meta.step, policy=policy)
+42 -27
View File
@@ -26,11 +26,13 @@ from pathlib import Path
from typing import Generic, TypeVar
import verifiers.v1 as vf
from renderers import RendererConfig
from verifiers.v1.serve import EnvClient
from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
from prime_rl.orchestrator.generation_source import GenerationSource
from prime_rl.orchestrator.clients import InferenceClient, connect_frozen_client
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import env_address_file
@@ -65,7 +67,7 @@ class Env:
self.address_file = address_file
"""Where a launcher-managed server publishes its address; read when ``address``
is None."""
self.sampling_args: dict = {}
self.sampling = vf.SamplingConfig()
self.num_tasks: int | None = 0
"""Task count; ``None`` means the selected tasks never end."""
self.tasks: Iterator[vf.Task] | None = None
@@ -108,10 +110,10 @@ class Env:
get_logger().info(f"Env {self.name} ready in {format_time(time.perf_counter() - t0)} (num_tasks={num_tasks})")
def _sampling(self, cache_salt: str | None) -> vf.SamplingConfig:
sampling = {**self.sampling_args}
sampling = self.sampling
if cache_salt is not None:
sampling["extra_body"] = {**sampling.get("extra_body", {}), "cache_salt": cache_salt}
return vf.SamplingConfig(**sampling)
sampling = sampling.model_copy(update={"cache_salt": cache_salt})
return sampling
async def run(
self,
@@ -121,25 +123,16 @@ class Env:
task_data: dict,
on_delta: Callable[[dict], None] | None = None,
) -> vf.WireEpisode:
"""Run and return one typed episode. A failed multi-trace episode marks
its otherwise-clean traces failed so partial episodes never train.
"""Run and return the native typed episode.
``on_delta`` sees each delta of the env server's stream — a turn or a phase
change of one of the episode's traces — as it lands."""
episode = await self.env_client.run(
return await self.env_client.run(
task_data=task_data,
client=client,
model=model_name,
sampling=self._sampling(cache_salt),
on_delta=on_delta,
)
for trace in episode.traces:
if not episode.ok and trace.ok:
error = episode.last_error or vf.Error(
type="EpisodeFailed", message="A sibling trace in this episode failed"
)
trace.errors = [*trace.errors, error]
trace.ok = False
return episode
class TrainEnv(Env):
@@ -150,17 +143,39 @@ class TrainEnv(Env):
config: TrainSourceConfig,
address: str | None,
address_file: Path,
generation_source: GenerationSource,
clients: InferenceClient,
renderer_config: RendererConfig | None,
algorithm: Algorithm,
):
super().__init__(config, address, address_file)
self.generation_source = generation_source
# Train rollouts are generated from `clients`: the policy, or the frozen
# `sampling.source` connected in setup() with the renderer (token-in/out) client.
self.clients = clients
self.renderer_config = renderer_config
self.connected: InferenceClient | None = None
self.algorithm = algorithm
self.sampling_args = generation_source.sampling_args(config.sampling.to_sampling_args())
# Truncated policy sampling must ship the sampling masks the trainer replays.
self.requires_sampling_masks = (
config.sampling.truncates_distribution() and config.algo.sampling.source == "policy"
self.uses_live_policy = config.algo.sampling.source == "policy"
self.sampling = vf.SamplingConfig(
**config.sampling.model_dump(exclude_none=True),
# Only policy rollouts need sampling logprobs for importance ratios.
logprobs=True if self.uses_live_policy else None,
)
# Truncated policy sampling must ship the sampling masks the trainer replays.
self.requires_sampling_masks = config.sampling.truncates_distribution() and self.uses_live_policy
async def setup(self) -> None:
async def connect_source() -> None:
source = self.config.algo.sampling.source
if isinstance(source, FrozenModelConfig):
self.connected = await connect_frozen_client(source, renderer_config=self.renderer_config)
self.clients = self.connected
await asyncio.gather(connect_source(), self.algorithm.setup())
async def aclose(self) -> None:
for clients in (self.connected, self.algorithm.connected):
if clients is not None:
await clients.aclose()
class EvalEnv(Env):
@@ -168,7 +183,7 @@ class EvalEnv(Env):
def __init__(self, config: EvalSourceConfig, address: str | None, address_file: Path):
super().__init__(config, address, address_file)
self.sampling_args = config.sampling.to_sampling_args()
self.sampling = config.sampling
self.examples: list[vf.Task] = []
async def start(self) -> None:
@@ -218,9 +233,8 @@ class Envs(Generic[EnvT]):
class TrainEnvs(Envs[TrainEnv]):
"""Collection of training environments, each paired with its
:class:`GenerationSource` and runtime :class:`Algorithm`, built from the env's
resolved algorithm config."""
"""Collection of training environments, each with its runtime
:class:`Algorithm`, built from the env's resolved algorithm config."""
def __init__(
self,
@@ -238,7 +252,8 @@ class TrainEnvs(Envs[TrainEnv]):
config,
addresses[("train", config.resolved_name)],
env_address_file(config_dir, "train", config.resolved_name),
GenerationSource(config.algo.sampling, clients, renderer_config),
clients,
renderer_config,
build_algorithm(config.algo, clients),
)
self._envs[env.name] = env
+26 -27
View File
@@ -6,15 +6,18 @@ including startup. The dispatcher pulls via ``next_task()`` until
from __future__ import annotations
from collections import deque
import uuid
from collections import defaultdict, deque
from collections.abc import Iterable
from itertools import zip_longest
from typing import TYPE_CHECKING
import verifiers.v1 as vf
from verifiers.v1.utils.eval import plan_rollouts
from prime_rl.orchestrator.types import TaskRequest
if TYPE_CHECKING:
import verifiers.v1 as vf
from prime_rl.orchestrator.envs import EvalEnvs
@@ -42,54 +45,50 @@ class EvalSource:
self.intervals[env.name] = intervals[env.name] if intervals is not None else 1
self.queue: deque[TaskRequest] = deque()
self.owed: dict[str, dict[str, int]] | None = None
self.groups: dict[str, dict[str, str]] = {}
# A fresh run evaluates the base policy. Resumed runs apply interval
# rules to the loaded checkpoint and later policies.
self.first_trigger = not is_resumed
def restore(self, owed: dict[str, dict[str, int]], groups: dict[str, dict[str, str]]) -> None:
"""Rollouts the next trigger still owes per env and task key, the rest having
landed before a resume; a task without an entry is complete. ``groups`` is the
group id the landed rollouts of a task carry, which the owed ones join."""
self.owed = owed
self.groups = groups
def trigger(self, step: int, *, force: bool = False) -> list[str]:
"""Fire eligible envs for ``step`` and return their names. On resume
def trigger(
self, step: int, *, force: bool = False, completed: Iterable[vf.WireEpisode] = ()
) -> tuple[list[str], list[vf.WireEpisode]]:
"""Fire eligible envs and return their names and matched saved episodes. On resume
``first_trigger`` is False, so the startup/base eval doesn't re-run.
``force`` fires every env regardless of interval (e.g. the evals process's
final-checkpoint eval)."""
is_first, self.first_trigger = self.first_trigger, False
if is_first and self.skip_first_step:
return []
return [], []
fired = [
name
for name, interval in self.intervals.items()
if (is_first or force or step % interval == 0) and self.tasks_by_env[name]
]
owed, self.owed = self.owed, None
saved: dict[str, list[vf.WireEpisode]] = defaultdict(list)
for episode in completed:
saved[episode.env.name or episode.env.id].append(episode)
restored: list[vf.WireEpisode] = []
# Round-robin across fired envs (A₁, B₁, A₂, B₂, …) so the
# dispatcher rotates at example granularity. ``try_schedule``'s
# continue-group branch still keeps each example's group_size
# rollouts back-to-back, so per-example prefix-cache locality holds
iters = [iter(self.tasks_by_env[name]) for name in fired]
iters = [iter(plan_rollouts(self.tasks_by_env[name], self.group_sizes[name], saved[name])) for name in fired]
for round_tasks in zip_longest(*iters):
for env_name, task in zip(fired, round_tasks, strict=True):
if task is None:
for env_name, planned in zip(fired, round_tasks, strict=True):
if planned is None:
continue
rollouts = self.group_sizes[env_name]
if owed is not None:
# duplicate tasks share a key: each takes up to a group of what the key owes
rollouts = min(rollouts, owed[env_name].get(task.key, 0))
owed[env_name][task.key] = owed[env_name].get(task.key, 0) - rollouts
task, kept, rollouts = planned
# Each selected occurrence owns one group, including its restored episodes.
group = vf.GroupInfo(id=str(uuid.uuid4()))
for episode in kept:
episode.group = group
restored.extend(kept)
if rollouts > 0:
group_id = self.groups.get(env_name, {}).get(task.key)
self.queue.append(
TaskRequest(env_name=env_name, task=task, step=step, rollouts=rollouts, group_id=group_id)
TaskRequest(env_name=env_name, task=task, step=step, rollouts=rollouts, group_id=group.id)
)
return fired
return fired, restored
def next_task(self) -> TaskRequest | None:
"""Pop the next eval task, or ``None`` when the queue is empty."""
@@ -1,49 +0,0 @@
"""Resolve the model source used to generate an env's train episodes."""
from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.configs.algorithm import FrozenModelConfig, SamplingConfig
from prime_rl.orchestrator.algo import connect_frozen_client
if TYPE_CHECKING:
from renderers import RendererConfig
from prime_rl.orchestrator.clients import InferenceClient
class GenerationSource:
"""One env's generation model and inference clients.
``clients`` is what train rollouts are generated from: the policy clients,
swapped for a connected frozen endpoint in :meth:`setup` when the source is
an inline frozen model. A frozen source *generates* rollouts, so it uses
the renderer (token-in/out) client (built from ``renderer_config``) — the
rollout must carry tokens for training."""
def __init__(self, config: SamplingConfig, clients: InferenceClient, renderer_config: RendererConfig | None = None):
assert config.source is not None, "sampling.source must be resolved by config validation"
self.config = config
self.clients: InferenceClient = clients
self.renderer_config = renderer_config
self.connected: InferenceClient | None = None # frozen clients connected in setup(); closed at shutdown
async def setup(self) -> None:
"""Connect clients to a frozen generation source and wait for
readiness. Must run before dispatching."""
if isinstance(self.config.source, FrozenModelConfig):
self.clients = await connect_frozen_client(self.config.source, renderer_config=self.renderer_config)
self.connected = self.clients
@property
def uses_live_policy(self) -> bool:
return self.config.source == "policy"
def sampling_args(self, args: dict) -> dict:
"""Source-specific sampling-arg overrides. Sampling logprobs are only
needed for importance ratios on policy-sampled tokens — frozen
endpoints may reject the knob."""
if not self.uses_live_policy:
args.pop("logprobs", None)
return args
+6 -12
View File
@@ -282,16 +282,12 @@ class Orchestrator:
get_logger().success(f"Policy inference pool ready after {format_time(time.perf_counter() - t0)}")
# Build + ready pools for each env's frozen generation source and the
# algorithm's frozen reference model
await asyncio.gather(
*(env.generation_source.setup() for env in self.train_envs),
*(env.algorithm.setup() for env in self.train_envs),
)
await asyncio.gather(*(env.setup() for env in self.train_envs))
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
t0 = time.perf_counter()
# A LoRA run's adapter is registered under the base model name: the
# single adapter shadows it (vLLM resolves lora_requests before the
# base-model match), so requests keep addressing one stable name.
# A LoRA run's adapter is registered under the model name clients send;
# the inference server serves the base model as ``<model>-base``.
self.receiver = setup_weight_receiver(
get_broadcast_dir(config.output_dir),
config.weight_broadcast,
@@ -770,7 +766,7 @@ class Orchestrator:
if self.resume_step == step and self.config.eval is not None and not self.config.eval.retrigger_on_resume:
return
is_final = self.config.max_steps is not None and step >= self.config.max_steps
fired = self.eval_source.trigger(step, force=is_final)
fired, _ = self.eval_source.trigger(step, force=is_final)
if not fired:
return
self.eval_triggered_steps.add(step)
@@ -1025,11 +1021,9 @@ class Orchestrator:
if self.admin_plane is not None:
await self.admin_plane.aclose()
if self.train_envs is not None:
get_logger().debug("Stopping generation source and algorithm clients")
get_logger().debug("Stopping train env clients")
for env in self.train_envs:
for clients in (env.generation_source.connected, env.algorithm.connected):
if clients is not None:
await clients.aclose()
await env.aclose()
get_logger().info("Stopping orchestrator components")
t0 = time.perf_counter()
+1 -1
View File
@@ -255,7 +255,7 @@ class TrainSink:
return
samples_by_trace: dict[str, list[TrainingSample]] = {}
temperature = env.sampling_args["temperature"]
temperature = env.config.sampling.temperature
for trace in survivors:
samples = await asyncio.to_thread(trace_to_samples, trace, env_name=env_name)
for sample in samples:
+1 -1
View File
@@ -24,7 +24,7 @@ class WeightWatcher:
policy: Policy,
observers: list[VersionObserver],
ckpt_step: int = 0,
poll_interval: float = 1.0,
poll_interval: float = 0.1,
) -> None:
self.receiver = receiver
self.policy = policy
+65 -48
View File
@@ -1,7 +1,7 @@
import logging
import os
import time
from collections.abc import Callable
from collections.abc import Callable, Iterator
from pathlib import Path
from typing import cast
@@ -16,6 +16,7 @@ import torch.nn as nn
from huggingface_hub import snapshot_download
from jaxtyping import Int
from torch import Tensor
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointWrapper
from torch.distributed.checkpoint.hf_storage import HuggingFaceStorageReader
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
from torch.distributed.fsdp import CPUOffloadPolicy, FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
@@ -125,23 +126,26 @@ def freeze_vision_encoder(model: nn.Module, override_attr: str | None = None) ->
logger.info(f"Froze {num_frozen} parameters in vision encoder")
def iter_moe_blocks(model: nn.Module) -> Iterator[MoE]:
"""Yield the MoE MLP of each decoder layer, skipping dense layers."""
for layer in get_language_model(model).layers:
mlp = getattr(layer, "mlp", None)
if isinstance(mlp, MoE):
yield mlp
def freeze_moe_router(model: nn.Module) -> None:
"""Freeze MoE router parameters to maintain stable routing during training."""
logger = get_logger()
language_model = get_language_model(model)
num_frozen = 0
for moe in iter_moe_blocks(model):
for param in moe.router.parameters():
param.requires_grad = False
num_frozen += 1
for layer in language_model.layers:
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
if isinstance(mlp, MoE):
for param in mlp.router.parameters():
param.requires_grad = False
num_frozen += 1
if num_frozen == 0:
raise ValueError("No MoE router parameters found to freeze. Is this a MoE model?")
logger.info(f"Froze {num_frozen} MoE router parameters")
# No-op for non-MoE models: freeze_moe_router=True is the RL default.
if num_frozen > 0:
logger.info(f"Froze {num_frozen} MoE router parameters")
def apply_fp32_moe_router(model: nn.Module) -> None:
@@ -150,16 +154,12 @@ def apply_fp32_moe_router(model: nn.Module) -> None:
The FSDP bf16 cast exemption is applied separately in `setup_fsdp`.
"""
logger = get_logger()
language_model = get_language_model(model)
num_routers = 0
for layer in language_model.layers:
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
if isinstance(mlp, MoE):
mlp.router.to(torch.float32)
if isinstance(mlp.router, TokenChoiceTopKRouter):
mlp.router.fp32_gate = True
num_routers += 1
for moe in iter_moe_blocks(model):
moe.router.to(torch.float32)
if isinstance(moe.router, TokenChoiceTopKRouter):
moe.router.fp32_gate = True
num_routers += 1
# No-op for non-MoE models: moe_router_dtype='float32' is the default,
# so absence of MoE routers is the common case, not an error.
@@ -177,13 +177,10 @@ def get_full_offload_dtype_policy(
if config.moe_router_dtype != "float32":
return policy
language_model = get_language_model(model)
for layer in language_model.layers:
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
if isinstance(mlp, MoE):
for param in mlp.router.parameters():
if param.is_floating_point():
policy[id(param)] = (torch.float32, torch.float32)
for moe in iter_moe_blocks(model):
for param in moe.router.parameters():
if param.is_floating_point():
policy[id(param)] = (torch.float32, torch.float32)
return policy
@@ -215,14 +212,10 @@ def freeze_sparse_indexer(model: nn.Module) -> None:
def apply_force_balanced_routing(model: nn.Module) -> None:
"""Force MoE token-choice routers into round-robin assignment for fake-data smoke tests."""
logger = get_logger()
language_model = get_language_model(model)
num_routers = 0
for layer in language_model.layers:
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
if isinstance(mlp, MoE):
mlp.router.force_balanced = True
num_routers += 1
for moe in iter_moe_blocks(model):
moe.router.force_balanced = True
num_routers += 1
if num_routers == 0:
raise ValueError("No MoE routers found to force-balance. Is this a MoE model?")
@@ -248,13 +241,7 @@ def get_load_balance_stats(
"""
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 not None and hasattr(block_mlp, "tokens_per_expert"):
block_mlps.append(block_mlp)
block_mlps = list(iter_moe_blocks(model))
if not block_mlps:
return {"max_vio": None, "routing_confidence": None, "tokens_per_expert": torch.empty(0, 0)}
@@ -333,7 +320,7 @@ def compute_expert_load_stats(tokens_per_expert: Tensor) -> dict[str, Tensor]:
def get_expert_load_stats(tokens_per_expert: Tensor, group: dist.ProcessGroup) -> dict[str, float]:
"""Sum a step's per-layer expert counts across the group (every rank routes distinct tokens) and compute load stats."""
if tokens_per_expert.numel() == 0: # MoE model without prime-rl MoE layers (HF impl)
if tokens_per_expert.numel() == 0:
return {}
dist.all_reduce(tokens_per_expert, op=dist.ReduceOp.SUM, group=group)
return {name: value.item() for name, value in compute_expert_load_stats(tokens_per_expert).items()}
@@ -829,12 +816,41 @@ def apply_ac(model: nn.Module, ac_config: ActivationCheckpointConfig):
)
# Int args whose value changes between calls. torch.compile treats an int arg as a constant and recompiles
# whenever it changes, and every other rank waits in collectives until that rank finishes recompiling. Listed
# here, an arg is symbolic from the first compile instead.
DYNAMIC_INT_ARGS = (
# Longest document in the packed row. FlashAttention uses it to size the attention launch grid.
"max_seqlen",
)
def mark_dynamic_int_args() -> None:
"""Add DYNAMIC_INT_ARGS to torch.compiler.config.dynamic_sources, keeping entries already set."""
sources = [source for source in torch.compiler.config.dynamic_sources.split(",") if source]
for arg in DYNAMIC_INT_ARGS:
# Matches the arg passed directly (L['max_seqlen']) or through a wrapper's kwargs (L['kwargs']['max_seqlen']).
pattern = rf".*\['{arg}'\]"
if pattern not in sources:
sources.append(pattern)
torch.compiler.config.dynamic_sources = ",".join(sources)
def apply_compile(model: nn.Module, compile_config: CompileConfig):
torch._dynamo.config.capture_scalar_outputs = True
mark_dynamic_int_args()
language_model = get_language_model(model)
for layer_id in range(len(language_model.layers)):
layer = language_model.layers[layer_id]
if isinstance(layer, CheckpointWrapper) and any(
isinstance(module, FSDPModule) for module in layer._checkpoint_wrapped_module.modules()
):
# A nested FSDP unit's hooks always break the graph, and a break inside a compiled checkpoint
# sends the block to eager, so keep AC eager around the compiled block. pytorch/pytorch#196626
# removes the fp32 router's nested unit by letting it join the block's FSDP unit.
layer = layer._checkpoint_wrapped_module
# Doing it in-place avoids mangled fqn which can break checkpoint loading
language_model.layers[layer_id].compile(fullgraph=compile_config.fullgraph, mode=compile_config.mode)
layer.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})"
)
@@ -995,14 +1011,15 @@ def setup_model(
override_attr=config.vlm.vision_encoder_attr if config.vlm is not None else None,
)
# the right order is AC -> Compile -> FSDP
# the right order is AC -> FSDP -> Compile: compile needs to see which blocks hold nested FSDP units
if config.ac is not None:
apply_ac(model, config.ac)
if config.compile is not None:
apply_compile(model, config.compile)
setup_fsdp(model, config, parallel_dims)
if config.compile is not None:
apply_compile(model, config.compile)
if loading_from_checkpoint_later:
logger.warning(
"Skipping loading weights. Initializing an empty model on device, loading from checkpoint later."
@@ -15,9 +15,9 @@ from transformers.utils import TransformersKwargs
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import (
flash_attn_3_varlen_func,
flash_attn_4_varlen_func,
flash_attn_varlen_func,
flash_attn_2_varlen_op,
flash_attn_3_varlen_op,
flash_attn_4_varlen_op,
)
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import FeedForward
@@ -87,30 +87,25 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
"""AFMoE attention using Flash Attention varlen functions."""
_funcs = {
2: flash_attn_varlen_func,
3: flash_attn_3_varlen_func,
4: flash_attn_4_varlen_func,
2: flash_attn_2_varlen_op,
3: flash_attn_3_varlen_op,
4: flash_attn_4_varlen_op,
}
def __init__(self, config: AfmoeAttentionConfig, flash_attn_version: int = 4):
super().__init__(config)
self._flash_attn_version = flash_attn_version
self.func = self._funcs[flash_attn_version]
self._flash_attn_call = self.func
if self._flash_attn_version == 4:
self._flash_attn_call = torch._dynamo.disable(self.func)
def _compute_attention(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, cu_seqlens, max_seqlen):
"""Run the flash attention kernel. q/k/v are [total_tokens, heads, dim]."""
args = [q, k, v, cu_seqlens, cu_seqlens]
if self._flash_attn_version != 4:
args.extend([max_seqlen, max_seqlen])
kwargs: dict = {"causal": True}
if self.sliding_window is not None:
kwargs["window_size"] = (self.sliding_window - 1, 0)
out = self._flash_attn_call(*args, **kwargs)
if isinstance(out, tuple):
out = out[0]
if self._flash_attn_version == 4:
out, _ = self.func(q, k, v, cu_seqlens_q=cu_seqlens, cu_seqlens_k=cu_seqlens, **kwargs)
else:
out = self.func(q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen, **kwargs)
return out
def forward(
@@ -372,7 +367,9 @@ class AfmoeModel(AfmoePreTrainedModel):
for layer_idx, decoder_layer in enumerate(self.layers):
mask = causal_mask_mapping[decoder_layer.attention_type] if causal_mask_mapping is not None else None
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states = decoder_layer(
hidden_states,
@@ -61,8 +61,8 @@ class DeepseekV4Config(PretrainedConfig):
num_experts_per_tok: Number of routed experts activated per token.
n_routed_experts: Total number of routed experts.
n_shared_experts: Number of always-on shared experts.
scoring_func: Router activation. Only `sqrtsoftplus` is implemented; any other
value is rejected when the MoE layer is built.
scoring_func: Router score function, passed to the shared router: `sqrtsoftplus`
(V4's checkpoints), `sigmoid`, `softmax` or `topk_softmax`.
topk_method: Router top-k selection. Only `noaux_tc` (aux-loss-free bias correction) is
implemented; the field is carried because vLLM gates `e_score_correction_bias` on it.
norm_topk_prob: Whether to renormalize the top-k routing probabilities.
@@ -267,7 +267,9 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
mhc_states = inputs_embeds.unsqueeze(2).expand(-1, -1, self.config.hc_mult, -1).contiguous()
for layer_idx, decoder_layer in enumerate(self.layers):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
mhc_states = decoder_layer(
mhc_states,
input_ids=input_ids,
+21 -160
View File
@@ -6,96 +6,15 @@ selection with a frozen token-id lookup but keeps the learned gating weights.
"""
import torch
import torch.nn.functional as F
from torch import nn
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
from prime_rl.trainer.models.layers.activations import ClampedSilu
from prime_rl.trainer.models.layers.mlp import FeedForward
from prime_rl.trainer.models.layers.moe import GroupedExperts, MoE, TokenChoiceTopKRouter
class ClampedSwiglu:
"""SwiGLU with both branches clamped, as in HF's `DeepseekV4Experts`.
Structurally an `Activation`, but with `limit` as instance state: V4 reads its clamp
off `config.swiglu_limit`, while the shared `ActivationDispatch` holds stateless
classes keyed by name and so has nowhere to put a per-model number.
"""
def __init__(self, limit: float) -> None:
self.limit = limit
def apply(self, gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
assert gate is not None, "V4's routed experts are gated"
gate = gate.clamp(max=self.limit)
up = up.clamp(min=-self.limit, max=self.limit)
return F.silu(gate) * up
class DeepseekV4Router(TokenChoiceTopKRouter):
"""Token-choice router scored with `sqrt(softplus(.))`, V4's only scoring function.
`TokenChoiceTopKRouter.forward` picks its scoring function from an inline
`if/elif/else: raise` chain with no hook to extend, and `"sqrtsoftplus"` is outside
the `ScoreFuncType` it accepts, so the whole method is restated below. Only the
scoring line is new: the `routed_experts` bypass, the selection bias, the
normalization, the scaling and the per-expert token count are the base class's,
unchanged.
"""
def forward(
self, x: torch.Tensor, routed_experts: torch.Tensor | None = None
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
assert routed_experts is None or routed_experts.shape[-1] == self.top_k, (
f"routed_experts shape: {routed_experts.shape}, top_k: {self.top_k}"
)
if self.fp32_gate:
gate_bias = self.gate.bias.float() if self.gate.bias is not None else None
logits = F.linear(x.float(), self.gate.weight.float(), gate_bias)
else:
logits = self.gate(x)
# Scoring runs in float32 to avoid loss explosion, as in the base class. HF scores
# in the input dtype instead, so bf16 activations drift from HF by ~1e-3 here.
scores = F.softplus(logits.float()).sqrt()
# NOTE: the selection bias only steers selection. The gating value top_scores is
# still derived from the original scores.
if routed_experts is not None:
top_scores = scores.gather(dim=1, index=routed_experts)
selected_experts_indices = routed_experts
elif self.force_balanced:
num_tokens = scores.shape[0]
arange = torch.arange(num_tokens * self.top_k, device=scores.device)
selected_experts_indices = (arange % self.num_experts).view(num_tokens, self.top_k)
top_scores = scores.gather(dim=1, index=selected_experts_indices)
else:
selection_scores = scores
if self.selection_bias is not None:
selection_scores = selection_scores + self.selection_bias
_, selected_experts_indices = torch.topk(selection_scores, k=self.top_k, dim=1, sorted=self.topk_sorted)
top_scores = scores.gather(dim=1, index=selected_experts_indices)
with torch.no_grad():
selected_probability_mass = top_scores / (scores.sum(dim=-1, keepdim=True) + 1e-20)
routing_confidence_sum = selected_probability_mass.sum()
if self.route_norm:
denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
top_scores = top_scores / denominator
top_scores = top_scores * self.route_scale
num_tokens_per_expert = torch.histc(
selected_experts_indices.reshape(-1).float(),
bins=self.num_experts,
min=0,
max=self.num_experts,
).to(torch.int64)
return top_scores, selected_experts_indices, num_tokens_per_expert, routing_confidence_sum
class DeepseekV4HashRouter(DeepseekV4Router):
class DeepseekV4HashRouter(TokenChoiceTopKRouter):
"""A bootstrap layer's router: selection is a frozen token-id lookup, gating still learned.
`tid2eid` replaces the top-k of the scores with `tid2eid[token_id]`, read from the checkpoint
@@ -105,73 +24,9 @@ class DeepseekV4HashRouter(DeepseekV4Router):
unbuilt, keeping the state dict aligned with HF's.
"""
def __init__(
self,
dim: int,
num_experts: int,
top_k: int,
score_func: str,
route_norm: bool,
route_scale: float,
vocab_size: int,
) -> None:
super().__init__(
dim=dim,
num_experts=num_experts,
top_k=top_k,
score_func=score_func,
route_norm=route_norm,
route_scale=route_scale,
selection_bias=False,
)
self.register_buffer("tid2eid", torch.zeros(vocab_size, top_k, dtype=torch.long), persistent=True)
class DeepseekV4Experts(GroupedExperts):
"""Routed experts with V4's clamped SwiGLU.
The shared `GroupedExperts` already stores the stacked `gate_proj`/`up_proj`/`down_proj`
that the on-disk per-expert `w1`/`w2`/`w3` convert into, and its `forward` reaches the
activation through `self.activation`, so only that attribute and the initialization
spread differ from the base class.
"""
def __init__(self, dim: int, hidden_dim: int, num_experts: int, swiglu_limit: float) -> None:
super().__init__(dim, hidden_dim, num_experts, expert_type="gated")
self.activation = ClampedSwiglu(swiglu_limit)
def init_weights(self, init_std: float) -> None:
# Both halves of HF's fused gate_up_proj are drawn from the same std=0.02
# distribution, so gate and up match that here despite being separate tensors.
# The base class scales up_proj by init_std instead.
nn.init.trunc_normal_(self.gate_proj, mean=0.0, std=0.02)
nn.init.trunc_normal_(self.up_proj, mean=0.0, std=0.02)
nn.init.trunc_normal_(self.down_proj, mean=0.0, std=init_std)
class DeepseekV4MLP(FeedForward):
"""Dense SwiGLU MLP with V4's clamp, used as the MoE layer's shared expert.
The shared `FeedForward` already names its projections the way HF's `LlamaMLP` (which
HF's `DeepseekV4MLP` subclasses) does, and initializes them the same way, so only the
activation changes: gate and up are clamped before the SwiGLU. Unlike the routed
experts they are separate tensors here, so there is nothing to chunk.
"""
def __init__(self, config: DeepseekV4Config):
# `FeedForward` builds its projections without a bias whatever `bias` says.
assert not config.mlp_bias, "mlp_bias is not supported by the shared `FeedForward`"
super().__init__(
dim=config.hidden_size,
hidden_dim=config.moe_intermediate_size,
activation=config.hidden_act,
)
self.limit = config.swiglu_limit
def forward(self, x: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
gate = self.gate_proj(x).clamp(max=self.limit)
up = self.up_proj(x).clamp(min=-self.limit, max=self.limit)
return self.down_proj(F.silu(gate) * up)
def __init__(self, *, vocab_size: int, **router_kwargs) -> None:
super().__init__(**router_kwargs, selection_bias=False)
self.register_buffer("tid2eid", torch.zeros(vocab_size, self.top_k, dtype=torch.long), persistent=True)
class DeepseekV4MoE(MoE):
@@ -190,13 +45,9 @@ class DeepseekV4MoE(MoE):
def __init__(self, config: DeepseekV4Config, layer_idx: int):
assert config.hidden_act == "silu", (
f"the routed experts hardcode SiLU; hidden_act={config.hidden_act!r} is not supported"
f"the experts hardcode SiLU; hidden_act={config.hidden_act!r} is not supported"
)
if config.scoring_func != "sqrtsoftplus":
raise ValueError(
f"the router hardcodes sqrt(softplus(.)); scoring_func={config.scoring_func!r} is not supported"
)
assert not config.mlp_bias, "mlp_bias is not supported"
is_hash = layer_idx < config.num_hash_layers
router_kwargs = dict(
@@ -212,17 +63,22 @@ class DeepseekV4MoE(MoE):
router = (
DeepseekV4HashRouter(**router_kwargs, vocab_size=config.vocab_size)
if is_hash
else DeepseekV4Router(**router_kwargs, selection_bias=True)
else TokenChoiceTopKRouter(**router_kwargs, selection_bias=True)
)
experts = DeepseekV4Experts(
activation = ClampedSilu(config.swiglu_limit)
experts = GroupedExperts(
dim=config.hidden_size,
hidden_dim=config.moe_intermediate_size,
num_experts=config.n_routed_experts,
swiglu_limit=config.swiglu_limit,
activation=activation,
)
# HF sizes its shared expert at `moe_intermediate_size` regardless of
# `n_shared_experts`, which therefore only decides whether one exists at all.
shared_expert = DeepseekV4MLP(config) if config.n_shared_experts > 0 else None
shared_expert = (
FeedForward(dim=config.hidden_size, hidden_dim=config.moe_intermediate_size, activation=activation)
if config.n_shared_experts > 0
else None
)
super().__init__(
router=router,
@@ -235,6 +91,11 @@ class DeepseekV4MoE(MoE):
self.layer_idx = layer_idx
self.is_hash = is_hash
def init_weights(self, init_std: float, buffer_device: torch.device) -> None:
super().init_weights(init_std, buffer_device)
# HF draws both halves of its fused gate_up_proj from std=0.02; the shared init uses init_std for up.
nn.init.trunc_normal_(self.experts.up_proj, mean=0.0, std=0.02)
def forward(
self,
x: torch.Tensor,
-39
View File
@@ -1,39 +0,0 @@
import torch
from torch import Tensor
def quantize_to_fp8_blockwise(weight: Tensor, block_size: int = 128) -> tuple[Tensor, Tensor]:
"""Quantize a 2D tensor to FP8 e4m3 with per-block scales."""
if weight.ndim != 2:
raise ValueError(f"FP8 quantization expects a 2D tensor, got shape={tuple(weight.shape)}")
rows, cols = weight.shape
pad_rows = (block_size - rows % block_size) % block_size
pad_cols = (block_size - cols % block_size) % block_size
if pad_rows or pad_cols:
padded = torch.zeros(
rows + pad_rows,
cols + pad_cols,
dtype=weight.dtype,
device=weight.device,
)
padded[:rows, :cols] = weight
else:
padded = weight.contiguous()
padded_rows, padded_cols = padded.shape
blocks = padded.view(
padded_rows // block_size,
block_size,
padded_cols // block_size,
block_size,
).permute(0, 2, 1, 3)
fp8_max = torch.finfo(torch.float8_e4m3fn).max
max_abs = blocks.float().abs().amax(dim=(2, 3))
scales = (max_abs / fp8_max).clamp(min=1e-12)
blocks_fp8 = (blocks.float() / scales[:, :, None, None]).clamp(-fp8_max, fp8_max).to(torch.float8_e4m3fn)
quantized = blocks_fp8.permute(0, 2, 1, 3).reshape(padded_rows, padded_cols)[:rows, :cols].contiguous()
return quantized, scales.float().contiguous()
@@ -241,7 +241,9 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
cached_indices = None
use_index_cache = getattr(self.config, "use_index_cache", False)
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states, next_cached_indices = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
@@ -148,7 +148,7 @@ class GptOssModel(GptOssPreTrainedModel):
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for layer_idx, decoder_layer in enumerate(self.layers):
layer_routed_experts = routed_experts[:, :, layer_idx] if routed_experts is not None else None
layer_routed_experts = routed_experts[:, :, layer_idx].contiguous() if routed_experts is not None else None
hidden_states = decoder_layer(
hidden_states,
position_embeddings,
@@ -12,6 +12,7 @@ import triton.language as tl
FP8_MAX = 448.0
FP8_MIN = -448.0
FP8_EPS = 1e-10
KEY_ALIGNMENT = 16
@triton.jit
@@ -88,17 +89,6 @@ def per_token_group_quant_fp8(
return x_q, x_s
@triton.autotune(
configs=[
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=4, num_stages=2),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=4, num_stages=2),
triton.Config({"BLOCK_M": 128, "BLOCK_N": 64}, num_warps=8, num_stages=2),
triton.Config({"BLOCK_M": 128, "BLOCK_N": 128}, num_warps=8, num_stages=2),
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_BUCKET", "H", "D"],
)
@triton.jit
def _triton_fp8_indexer_kernel(
Q_fp8,
@@ -116,7 +106,6 @@ 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,
):
@@ -201,6 +190,8 @@ def fp8_indexer(
q_flat = q.reshape(S_q * H, D).contiguous()
q_fp8, q_scales = per_token_group_quant_fp8(q_flat, group_size=D, use_ue8m0=True)
S_k_aligned = triton.cdiv(S_k, KEY_ALIGNMENT) * KEY_ALIGNMENT
k = torch.nn.functional.pad(k, (0, 0, 0, S_k_aligned - S_k))
k_fp8, k_scales = per_token_group_quant_fp8(k.contiguous(), group_size=D, use_ue8m0=True)
q_fp8 = q_fp8.view(S_q, H, D).permute(1, 0, 2).contiguous()
@@ -209,12 +200,10 @@ def fp8_indexer(
q_scales = q_scales.view(S_q, H)
w = w * q_scales
logits = torch.empty(S_q, S_k, dtype=torch.float32, device=device)
logits = torch.empty(S_q, S_k_aligned, dtype=torch.float32, device=device)
grid = lambda meta: (
triton.cdiv(S_q, meta["BLOCK_M"]),
triton.cdiv(S_k, meta["BLOCK_N"]),
)
BLOCK_M, BLOCK_N = 64, 128
grid = (triton.cdiv(S_q, BLOCK_M), triton.cdiv(S_k_aligned, BLOCK_N))
_triton_fp8_indexer_kernel[grid](
q_fp8,
k_fp8,
@@ -224,16 +213,17 @@ def fp8_indexer(
ks,
ke,
S_q,
S_k,
S_k_aligned,
q_fp8.stride(0),
q_fp8.stride(1),
k_fp8.stride(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),
BLOCK_M=BLOCK_M,
BLOCK_N=BLOCK_N,
num_warps=4,
num_stages=2,
)
actual_topk = min(topk, S_k)
@@ -329,7 +329,9 @@ class LagunaModel(LagunaPreTrainedModel):
}
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states = decoder_layer(
hidden_states,
attention_mask=causal_mask_mapping[self.config.layer_types[layer_idx]],
@@ -18,6 +18,19 @@ class ClampedSwiglu(Activation):
return (up + 1) * gate * torch.sigmoid(gate * 1.702)
class ClampedSilu(Activation):
"""SwiGLU with the gate clamped to `max=limit` and up to `[-limit, limit]` (DeepSeek V4)."""
def __init__(self, limit: float) -> None:
self.limit = limit
def apply(self, gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
assert gate is not None
gate = gate.clamp(max=self.limit)
up = up.clamp(min=-self.limit, max=self.limit)
return F.silu(gate) * up
class Relu2(Activation):
@staticmethod
def apply(gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
+282 -11
View File
@@ -13,14 +13,19 @@ from .rotary_emb import apply_rotary_pos_emb
# flash-attention-2
try:
from flash_attn import flash_attn_varlen_func
from flash_attn.flash_attn_interface import _flash_attn_varlen_backward, _flash_attn_varlen_forward
except ImportError:
flash_attn_varlen_func = None # type: ignore
_flash_attn_varlen_backward = _flash_attn_varlen_forward = None # type: ignore
# flash-attention-3
try:
from flash_attn_interface import _flash_attn_backward as _flash_attn_3_bwd
from flash_attn_interface import _flash_attn_forward as _flash_attn_3_fwd
from flash_attn_interface import flash_attn_varlen_func as flash_attn_3_varlen_func
except ImportError:
flash_attn_3_varlen_func = None # type: ignore
_flash_attn_3_bwd = _flash_attn_3_fwd = None # type: ignore
try:
from flash_attn.cute import flash_attn_varlen_func as flash_attn_4_varlen_func
@@ -30,9 +35,11 @@ except ImportError:
_flash_attn_bwd = _flash_attn_fwd = None # type: ignore
# FA4's flash_attn_varlen_func is a Python autograd.Function that Dynamo cannot trace. Inside a
# checkpointed block that graph break drops the whole block to eager, so FA4 is exposed as an
# opaque custom op instead, which also lets selective activation checkpointing save its output.
# Each FlashAttention version's flash_attn_varlen_func is a Python autograd.Function that Dynamo
# cannot trace (FA2 and FA3 also reject the same cu_seqlens tensor passed as both cu_seqlens_q and
# cu_seqlens_k). Inside a checkpointed block that graph break drops the whole block to eager, so
# each version is exposed as an opaque custom op instead, which also lets selective activation
# checkpointing save its output.
@torch.library.custom_op("prime_rl_attn::flash_attn_4_varlen", mutates_args=())
def _flash_attn_4_varlen(
q: torch.Tensor,
@@ -40,6 +47,8 @@ def _flash_attn_4_varlen(
v: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int | None,
max_seqlen_k: int | None,
causal: bool,
window_size_left: int | None,
window_size_right: int | None,
@@ -50,6 +59,8 @@ def _flash_attn_4_varlen(
v,
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=max_seqlen_q,
max_seqlen_k=max_seqlen_k,
causal=causal,
window_size_left=window_size_left,
window_size_right=window_size_right,
@@ -59,7 +70,7 @@ def _flash_attn_4_varlen(
@_flash_attn_4_varlen.register_fake
def _(q, k, v, cu_seqlens_q, cu_seqlens_k, causal, window_size_left, window_size_right):
def _(q, k, v, *args):
out = q.new_empty((*q.shape[:-1], v.shape[-1]))
lse = q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
return out, lse
@@ -75,6 +86,8 @@ def _flash_attn_4_varlen_backward(
lse: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int | None,
max_seqlen_k: int | None,
causal: bool,
window_size_left: int | None,
window_size_right: int | None,
@@ -91,19 +104,24 @@ def _flash_attn_4_varlen_backward(
window_size_right=window_size_right,
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=max_seqlen_q,
max_seqlen_k=max_seqlen_k,
)
return dq, dk, dv
@_flash_attn_4_varlen_backward.register_fake
def _(dout, q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k, causal, window_size_left, window_size_right):
def _(dout, q, k, v, *args):
return torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
def _flash_attn_4_varlen_setup_context(ctx, inputs, output) -> None:
q, k, v, cu_seqlens_q, cu_seqlens_k, causal, window_size_left, window_size_right = inputs
q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, causal, window_size_left, window_size_right = (
inputs
)
out, lse = output
ctx.save_for_backward(q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k)
ctx.max_seqlen = (max_seqlen_q, max_seqlen_k)
ctx.causal = causal
ctx.window_size = (window_size_left, window_size_right)
@@ -111,9 +129,9 @@ def _flash_attn_4_varlen_setup_context(ctx, inputs, output) -> None:
def _flash_attn_4_varlen_autograd(ctx, dout: torch.Tensor, _dlse: torch.Tensor | None):
q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k = ctx.saved_tensors
dq, dk, dv = _flash_attn_4_varlen_backward(
dout.contiguous(), q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k, ctx.causal, *ctx.window_size
dout.contiguous(), q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k, *ctx.max_seqlen, ctx.causal, *ctx.window_size
)
return dq, dk, dv, None, None, None, None, None
return dq, dk, dv, None, None, None, None, None, None, None
_flash_attn_4_varlen.register_autograd(_flash_attn_4_varlen_autograd, setup_context=_flash_attn_4_varlen_setup_context)
@@ -126,11 +144,264 @@ def flash_attn_4_varlen_op(
*,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int | None = None,
max_seqlen_k: int | None = None,
causal: bool = False,
window_size: tuple[int | None, int | None] = (None, None),
) -> tuple[torch.Tensor, torch.Tensor]:
"""Drop-in for FA4's ``flash_attn_varlen_func`` as called by ``FlashAttention``, routed through the custom op."""
return _flash_attn_4_varlen(q, k, v, cu_seqlens_q, cu_seqlens_k, causal, window_size[0], window_size[1])
return _flash_attn_4_varlen(
q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, causal, window_size[0], window_size[1]
)
@torch.library.custom_op("prime_rl_attn::flash_attn_3_varlen", mutates_args=())
def _flash_attn_3_varlen(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
softmax_scale: float,
causal: bool,
window_size_left: int,
window_size_right: int,
) -> tuple[torch.Tensor, torch.Tensor]:
out, lse, _, _ = _flash_attn_3_fwd(
q,
k,
v,
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=max_seqlen_q,
max_seqlen_k=max_seqlen_k,
softmax_scale=softmax_scale,
causal=causal,
window_size_left=window_size_left,
window_size_right=window_size_right,
)
return out, lse
@_flash_attn_3_varlen.register_fake
def _(q, k, v, *args):
out = q.new_empty((*q.shape[:-1], v.shape[-1]))
lse = q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
return out, lse
@torch.library.custom_op("prime_rl_attn::flash_attn_3_varlen_backward", mutates_args=())
def _flash_attn_3_varlen_backward(
dout: torch.Tensor,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
out: torch.Tensor,
lse: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
softmax_scale: float,
causal: bool,
window_size_left: int,
window_size_right: int,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
_flash_attn_3_bwd(
dout,
q,
k,
v,
out,
lse,
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=max_seqlen_q,
max_seqlen_k=max_seqlen_k,
dq=dq,
dk=dk,
dv=dv,
softmax_scale=softmax_scale,
is_causal=causal,
window_size_left=window_size_left,
window_size_right=window_size_right,
)
return dq, dk, dv
@_flash_attn_3_varlen_backward.register_fake
def _(dout, q, k, v, *args):
return torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
# FA2's public flash_attn_varlen_func pads the head dim to a multiple of 8 around its kernels; these ops call
# the kernels directly, so they pad the same way.
def pad_head_dim_to_multiple_of_8_for_fa2(t: torch.Tensor) -> torch.Tensor:
head_dim = t.shape[-1]
if head_dim % 8 == 0:
return t
return torch.nn.functional.pad(t, [0, 8 - head_dim % 8])
@torch.library.custom_op("prime_rl_attn::flash_attn_2_varlen", mutates_args=())
def _flash_attn_2_varlen(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
softmax_scale: float,
causal: bool,
window_size_left: int,
window_size_right: int,
) -> tuple[torch.Tensor, torch.Tensor]:
head_dim = q.shape[-1]
q, k, v = (pad_head_dim_to_multiple_of_8_for_fa2(t) for t in (q, k, v))
out_padded, lse, _, _ = _flash_attn_varlen_forward(
q,
k,
v,
cu_seqlens_q,
cu_seqlens_k,
max_seqlen_q,
max_seqlen_k,
0.0,
softmax_scale,
causal=causal,
window_size_left=window_size_left,
window_size_right=window_size_right,
)
return out_padded[..., :head_dim], lse
# FA2's kernel allocates its outputs with empty_like on the padded inputs, so the fakes keep their strides and padding.
@_flash_attn_2_varlen.register_fake
def _(q, k, v, *args):
head_dim = q.shape[-1]
out = torch.empty_like(pad_head_dim_to_multiple_of_8_for_fa2(q))[..., :head_dim]
lse = q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
return out, lse
@torch.library.custom_op("prime_rl_attn::flash_attn_2_varlen_backward", mutates_args=())
def _flash_attn_2_varlen_backward(
dout: torch.Tensor,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
out: torch.Tensor,
lse: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
softmax_scale: float,
causal: bool,
window_size_left: int,
window_size_right: int,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
head_dim = q.shape[-1]
dout, q, k, v, out = (pad_head_dim_to_multiple_of_8_for_fa2(t) for t in (dout, q, k, v, out))
dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
_flash_attn_varlen_backward(
dout,
q,
k,
v,
out,
lse,
dq,
dk,
dv,
cu_seqlens_q,
cu_seqlens_k,
max_seqlen_q,
max_seqlen_k,
0.0,
softmax_scale,
causal,
window_size_left,
window_size_right,
0.0,
None,
False,
)
return dq[..., :head_dim], dk[..., :head_dim], dv[..., :head_dim]
@_flash_attn_2_varlen_backward.register_fake
def _(dout, q, k, v, *args):
head_dim = q.shape[-1]
return tuple(torch.empty_like(pad_head_dim_to_multiple_of_8_for_fa2(t))[..., :head_dim] for t in (q, k, v))
def _flash_attn_varlen_setup_context(ctx, inputs, output) -> None:
q, k, v, cu_seqlens_q, cu_seqlens_k, *scalar_args = inputs
out, lse = output
ctx.save_for_backward(q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k)
ctx.scalar_args = scalar_args
def _flash_attn_varlen_autograd(backward_op, ctx, dout: torch.Tensor, _dlse: torch.Tensor | None):
dq, dk, dv = backward_op(dout.contiguous(), *ctx.saved_tensors, *ctx.scalar_args)
return dq, dk, dv, None, None, None, None, None, None, None, None
_flash_attn_2_varlen.register_autograd(
functools.partial(_flash_attn_varlen_autograd, _flash_attn_2_varlen_backward),
setup_context=_flash_attn_varlen_setup_context,
)
_flash_attn_3_varlen.register_autograd(
functools.partial(_flash_attn_varlen_autograd, _flash_attn_3_varlen_backward),
setup_context=_flash_attn_varlen_setup_context,
)
def flash_attn_2_varlen_op(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
softmax_scale: float | None = None,
causal: bool = False,
window_size: tuple[int, int] = (-1, -1),
) -> torch.Tensor:
"""Drop-in for FA2's ``flash_attn_varlen_func``, routed through the custom op."""
if softmax_scale is None:
softmax_scale = q.shape[-1] ** -0.5
out, _ = _flash_attn_2_varlen(
q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, softmax_scale, causal, *window_size
)
return out
def flash_attn_3_varlen_op(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
softmax_scale: float | None = None,
causal: bool = False,
window_size: tuple[int, int] = (-1, -1),
) -> torch.Tensor:
"""Drop-in for FA3's ``flash_attn_varlen_func``, routed through the custom op."""
if softmax_scale is None:
softmax_scale = q.shape[-1] ** -0.5
out, _ = _flash_attn_3_varlen(
q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, softmax_scale, causal, *window_size
)
return out
@dataclass
@@ -158,8 +429,8 @@ class FlashAttention(nn.Module):
supported_fusions = {"qkv": fuse_qkv_projections}
_funcs = {
2: flash_attn_varlen_func,
3: flash_attn_3_varlen_func,
2: flash_attn_2_varlen_op,
3: flash_attn_3_varlen_op,
4: flash_attn_4_varlen_op,
}
+3 -3
View File
@@ -3,7 +3,7 @@ from typing import Literal
import torch
from torch import nn
from prime_rl.trainer.models.layers.activations import ActivationDispatch, ActivationType
from prime_rl.trainer.models.layers.activations import Activation, ActivationDispatch, ActivationType
ExpertType = Literal["gated", "non_gated"]
@@ -17,14 +17,14 @@ class FeedForward(nn.Module):
hidden_dim: int,
*,
expert_type: ExpertType = "gated",
activation: ActivationType = "silu",
activation: ActivationType | Activation = "silu",
bias: bool = False,
) -> None:
super().__init__()
self.gate_proj = nn.Linear(dim, hidden_dim, bias=bias) if expert_type == "gated" else None
self.up_proj = nn.Linear(dim, hidden_dim, bias=bias)
self.down_proj = nn.Linear(hidden_dim, dim, bias=bias)
self.activation = ActivationDispatch[activation]
self.activation = ActivationDispatch[activation] if isinstance(activation, str) else activation
def forward(self, x: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
gate = self.gate_proj(x) if self.gate_proj is not None else None
+9 -7
View File
@@ -13,11 +13,11 @@ from torch import nn
from prime_rl.trainer.distributed.token_dispatcher import LocalTokenDispatcher, TokenDispatcher
from prime_rl.trainer.models.fusions import fuse_gate_up_projections
from prime_rl.trainer.models.layers.activations import ActivationDispatch, ActivationType
from prime_rl.trainer.models.layers.activations import Activation, ActivationDispatch, ActivationType
from prime_rl.trainer.models.layers.expert_compute import BF16ExpertCompute, ExpertCompute
from prime_rl.trainer.models.layers.mlp import ExpertType, FeedForward
ScoreFuncType = Literal["softmax", "sigmoid", "topk_softmax"]
ScoreFuncType = Literal["softmax", "sigmoid", "topk_softmax", "sqrtsoftplus"]
@torch.library.custom_op(
@@ -76,7 +76,7 @@ class GroupedExperts(nn.Module):
num_experts: int,
*,
expert_type: ExpertType = "gated",
activation: ActivationType = "silu",
activation: ActivationType | Activation = "silu",
bias: bool = False,
compute: ExpertCompute | None = None,
):
@@ -93,7 +93,7 @@ class GroupedExperts(nn.Module):
self.up_proj_bias = nn.Parameter(torch.empty(num_experts, hidden_dim)) if bias else None
self.down_proj_bias = nn.Parameter(torch.empty(num_experts, dim)) if bias else None
self.activation = ActivationDispatch[activation]
self.activation = ActivationDispatch[activation] if isinstance(activation, str) else activation
if expert_type == "non_gated":
self.supported_fusions = {}
self.set_compute(compute or BF16ExpertCompute())
@@ -136,8 +136,8 @@ class TokenChoiceTopKRouter(nn.Module):
dim (int): Dimension of input tokens.
num_experts (int): Number of experts in each moe layer.
top_k (int): Number of experts each token will be routed to in token-choice routing.
score_func (Literal["softmax", "sigmoid", "topk_softmax"]): Score transform. ``topk_softmax``
selects experts from the logits and normalizes only the selected logits.
score_func (ScoreFuncType): Score transform. ``topk_softmax`` selects experts from the logits
and normalizes only the selected logits. ``sqrtsoftplus`` is DeepSeek V4's ``sqrt(softplus(.))``.
route_norm (bool): Whether to normalize the routing scores when using sigmoid.
route_scale (float): Scaling factor applied to the routing scores.
gate_bias (bool): Whether the gate has a trainable logit bias.
@@ -151,7 +151,7 @@ class TokenChoiceTopKRouter(nn.Module):
dim: int,
num_experts: int,
top_k: int,
score_func: Literal["softmax", "sigmoid", "topk_softmax"],
score_func: ScoreFuncType,
route_norm: bool,
route_scale: float,
*,
@@ -214,6 +214,8 @@ class TokenChoiceTopKRouter(nn.Module):
scores = F.softmax(logits.float(), dim=1)
elif self.score_func == "topk_softmax":
scores = logits
elif self.score_func == "sqrtsoftplus":
scores = F.softplus(logits.float()).sqrt()
else:
raise NotImplementedError(f"Unknown score function {self.score_func}")
@@ -1,3 +0,0 @@
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
__all__ = ["RMSNorm", "RMSNormConfig"]
@@ -176,15 +176,15 @@ def substitute_ulysses_attn(
# Resolve flash kernel + version from attn_impl.
if attn_impl == "flash_attention_4":
from flash_attn.cute import flash_attn_varlen_func as flash_fn
from prime_rl.trainer.models.layers.attn import flash_attn_4_varlen_op as flash_fn
flash_attn_version = 4
elif attn_impl == "flash_attention_3":
from flash_attn_interface import flash_attn_varlen_func as flash_fn
from prime_rl.trainer.models.layers.attn import flash_attn_3_varlen_op as flash_fn
flash_attn_version = 3
else:
from flash_attn import flash_attn_varlen_func as flash_fn
from prime_rl.trainer.models.layers.attn import flash_attn_2_varlen_op as flash_fn
flash_attn_version = 2
@@ -177,7 +177,9 @@ class MiniMaxM2Model(MiniMaxM2PreTrainedModel):
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
@@ -192,7 +192,7 @@ class NemotronHModel(NemotronHPreTrainedModel):
torch._dynamo.mark_dynamic(cu_seqlens, 0)
for layer_idx, decoder_layer in enumerate(self.layers):
layer_routed_experts = routed_experts[:, :, layer_idx] if routed_experts is not None else None
layer_routed_experts = routed_experts[:, :, layer_idx].contiguous() if routed_experts is not None else None
hidden_states = decoder_layer(
hidden_states,
cu_seqlens,
@@ -6,9 +6,9 @@ from torch import nn
from transformers.modeling_outputs import BaseModelOutputWithPooling
from prime_rl.trainer.models.layers.attn import (
flash_attn_3_varlen_func,
flash_attn_4_varlen_func,
flash_attn_varlen_func,
flash_attn_2_varlen_op,
flash_attn_3_varlen_op,
flash_attn_4_varlen_op,
)
from prime_rl.trainer.models.layers.rotary_emb import rotate_half
from prime_rl.trainer.models.qwen3_5.configuration_qwen3_5 import Qwen3_5VisionConfig
@@ -69,9 +69,9 @@ class Qwen3_5VisionMLP(nn.Module):
class Qwen3_5VisionAttention(nn.Module):
FLASH_ATTENTION_FUNCTIONS = {
"flash_attention_2": flash_attn_varlen_func,
"flash_attention_3": flash_attn_3_varlen_func,
"flash_attention_4": flash_attn_4_varlen_func,
"flash_attention_2": flash_attn_2_varlen_op,
"flash_attention_3": flash_attn_3_varlen_op,
"flash_attention_4": flash_attn_4_varlen_op,
}
def __init__(self, config: Qwen3_5VisionConfig) -> None:
@@ -210,7 +210,9 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
+3 -18
View File
@@ -112,7 +112,7 @@ class ParallelDims:
# Create all the submesh here to ensure all required process groups are
# initialized:
# Mesh for data loading (no communication on this mesh)
# Mesh for data loading and per-step token counts
dp_mesh_dim_names = []
# Mesh for param sharding
dp_shard_cp_mesh_dim_names = []
@@ -172,7 +172,7 @@ class ParallelDims:
# Create all the submesh here to ensure all required process groups are
# initialized:
# Mesh for data loading (no communication on this mesh)
# Mesh for data loading and per-step token counts
dp_mesh_dim_names = []
# Mesh for param sharding
dp_shard_cp_mesh_dim_names = []
@@ -263,13 +263,6 @@ class ParallelDims:
def non_data_parallel_size(self):
return self.cp * self.pp
@cached_property
def seq_len_divisor(self):
# Context Parallel requires that seq_len be divisible by 2 * CP degree,
# when load balancing is enabled (by default).
# https://github.com/pytorch/pytorch/blob/4f62dcc/torch/distributed/tensor/experimental/_attention.py#L1246
return self.cp * 2
@cached_property
def logger(self):
return get_logger()
@@ -309,7 +302,7 @@ def resolve_ep(config: ModelConfig) -> None:
get_logger().info(f"EP auto: world_size={world_size}, dp_replicate={dp_replicate} -> resolved ep={resolved_ep}")
def get_parallel_dims(config: ModelConfig, seq_len: int | None = None) -> ParallelDims:
def get_parallel_dims(config: ModelConfig) -> ParallelDims:
assert isinstance(config.ep, int), (
f"config.ep must be resolved to an int before get_parallel_dims; got {config.ep!r}. "
"Call resolve_ep(config) first."
@@ -325,12 +318,4 @@ def get_parallel_dims(config: ModelConfig, seq_len: int | None = None) -> Parall
world_size=dist.get_world_size(),
)
# Validate sequence length against parallel dimensions requirements
if seq_len is not None and seq_len % parallel_dims.seq_len_divisor != 0:
raise ValueError(
f"Sequence length ({seq_len}) must be divisible by "
f"seq_len_divisor ({parallel_dims.seq_len_divisor}) for the given parallel dimensions. "
f"This requirement comes from context parallel (CP={config.cp})."
)
return parallel_dims
+24 -2
View File
@@ -1,5 +1,5 @@
from pathlib import Path
from typing import TypedDict
from typing import Any, NotRequired, TypedDict
import numpy as np
import torch
@@ -7,6 +7,8 @@ from jaxtyping import Bool, Float, Int
from torch import Tensor
from prime_rl.configs.trainer import FakeDataLoaderConfig
from prime_rl.multimodal import ForwardPolicy, MultimodalAdapter
from prime_rl.trainer.multimodal import materialize_mm_refs
from prime_rl.trainer.world import get_world
from prime_rl.transports.batch import (
BatchReceiver,
@@ -47,8 +49,11 @@ class TensorMicroBatch(TypedDict):
# maximum mask size. A row containing only -1 has no mask.
sampling_mask: Int[Tensor, "batch seq mask"] | None
# Materialized immediately before this microbatch's forward pass.
# Multimodal inputs. The data loader sets mm_refs (undecoded image references), and prepare_micro_batch
# replaces them with mm_kwargs (CPU tensors for the vision encoder) and mm_forward_policy.
mm_refs: MMRefs | None
mm_kwargs: NotRequired[dict[str, Tensor] | None]
mm_forward_policy: NotRequired[ForwardPolicy | None]
# mm_token_type_ids: token type per token [batch seq], int64 (0=text, 1=image, 2=video)
mm_token_type_ids: Int[Tensor, "batch seq"] | None
@@ -172,6 +177,23 @@ class FakeDataLoader:
}
def prepare_micro_batch(
micro_batch: TensorMicroBatch, processor: Any | None, mm_adapter: MultimodalAdapter | None
) -> TensorMicroBatch:
"""Prepare a micro batch for the training loop. Currently only multimodal samples need preparation."""
micro_batch["mm_kwargs"] = None
micro_batch["mm_forward_policy"] = None
mm_refs = micro_batch.get("mm_refs")
if mm_refs is not None:
if processor is None or mm_adapter is None:
raise ValueError("Received multimodal samples but [model.vlm] is not set")
materialized = materialize_mm_refs(mm_refs, processor, mm_adapter)
micro_batch["mm_kwargs"] = materialized.kwargs
micro_batch["mm_forward_policy"] = materialized.forward_policy
micro_batch["mm_refs"] = None
return micro_batch
class DataLoader:
"""Receives packed micro batches from the orchestrator, one stream per DP rank."""
+17 -17
View File
@@ -1,6 +1,7 @@
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before import
from contextlib import nullcontext
from functools import partial
import time
import asyncio
from datetime import timedelta
@@ -17,7 +18,7 @@ from prime_rl.trainer.ckpt import Progress, setup_ckpt_manager
from prime_rl.trainer.optim import setup_optimizer
from prime_rl.trainer.scheduler import setup_scheduler
from prime_rl.configs.trainer import TrainerConfig
from prime_rl.trainer.rl.data import DataLoader, FakeDataLoader
from prime_rl.trainer.rl.data import DataLoader, FakeDataLoader, prepare_micro_batch
from prime_rl.utils.cp import (
gather_for_cp,
gather_for_cp_wo_grad,
@@ -37,7 +38,6 @@ from prime_rl.trainer.rl.loss import (
shift_tensor_right,
)
from prime_rl.multimodal import get_multimodal_adapter
from prime_rl.trainer.multimodal import materialize_mm_refs
from prime_rl.trainer.rl.annotations import AnnotationWriter
from prime_rl.trainer.model import (
forward,
@@ -71,6 +71,7 @@ from prime_rl.utils.heartbeat import Heartbeat
from prime_rl import monitors
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
from prime_rl.utils.worker_pool import WorkerPool
from prime_rl.utils.pathing import resolve_latest_ckpt_step
from prime_rl.utils.utils import clean_exit
@@ -147,6 +148,8 @@ def train(config: TrainerConfig):
if processor is None:
raise ValueError("Multimodal training requires a model image processor")
mm_adapter = get_multimodal_adapter(model.config.model_type)
prepare = partial(prepare_micro_batch, processor=processor, mm_adapter=mm_adapter)
micro_batch_workers = WorkerPool(config.data.num_workers)
if config.model.vlm is not None and not getattr(model, "supports_packed_multimodal_training", False):
raise ValueError("Packed multimodal training requires model support")
@@ -336,7 +339,9 @@ def train(config: TrainerConfig):
cp_size = parallel_dims.cp
step_tokens_per_expert = 0
for micro_step, micro_batch in enumerate(micro_batches):
step_local_num_tokens = 0
for micro_step, micro_batch in enumerate(micro_batch_workers(prepare, micro_batches)):
step_local_num_tokens += micro_batch["input_ids"].shape[1]
input_ids = micro_batch["input_ids"].to("cuda")
position_ids = micro_batch["position_ids"].to("cuda")
advantages = micro_batch["advantages"].to("cuda")
@@ -365,17 +370,10 @@ def train(config: TrainerConfig):
micro_batch["sampling_mask"].to("cuda") if micro_batch["sampling_mask"] is not None else None
)
mm_kwargs = None
mm_forward_policy = None
mm_refs = micro_batch.get("mm_refs")
if mm_refs is not None:
if processor is None or mm_adapter is None:
raise ValueError("Received multimodal samples but [model.vlm] is not set")
materialized = materialize_mm_refs(mm_refs, processor, mm_adapter)
mm_kwargs = {key: value.to("cuda") for key, value in materialized.kwargs.items()}
mm_forward_policy = materialized.forward_policy
micro_batch["mm_refs"] = None
del materialized, mm_refs
mm_kwargs = micro_batch.pop("mm_kwargs")
if mm_kwargs is not None:
mm_kwargs = {key: value.to("cuda") for key, value in mm_kwargs.items()}
mm_forward_policy = micro_batch.pop("mm_forward_policy")
mm_token_type_ids = (
micro_batch["mm_token_type_ids"].to("cuda")
if micro_batch.get("mm_token_type_ids") is not None
@@ -631,9 +629,10 @@ def train(config: TrainerConfig):
if is_moe_model:
tensor_stats.update(get_expert_load_stats(step_tokens_per_expert, dp_cp_group))
# Compute step metrics
num_local_tokens = seq_len * batch_size
num_tokens = parallel_dims.get_mesh("dp").size() * num_local_tokens
# The dp mesh excludes cp, whose ranks hold the same rows.
global_num_tokens = torch.tensor(step_local_num_tokens, dtype=torch.int64, device="cuda")
dist.all_reduce(global_num_tokens, op=dist.ReduceOp.SUM, group=parallel_dims.get_mesh("dp").get_group())
num_tokens = global_num_tokens.item()
progress.total_tokens += num_tokens
progress.total_samples += batch_size
perf_counter = get_perf_counter(model, seq_len)
@@ -732,6 +731,7 @@ def train(config: TrainerConfig):
if gradient_manager is not None:
gradient_manager.close()
micro_batch_workers.close()
logger.info(f"Peak memory: {max_peak_memory:.1f} GiB")
logger.success("RL trainer finished")
+16 -9
View File
@@ -249,6 +249,13 @@ class RendererResolver:
renderer = create_renderer(self.tokenizer, config)
if self.processor is not None and hasattr(renderer, "_processor"):
renderer._processor = self.processor
if not getattr(renderer, "is_prefix_stable", False):
get_logger().warning(
f"SFT renderer {type(renderer).__name__} does not guarantee prefix stability. "
"SFT renders each conversation once to produce one training sample; "
"it does not expand N assistant turns into N samples. Depending on the template, "
"reasoning from earlier turns may be omitted from the training sample."
)
self.renderers[config] = renderer
return renderer
@@ -279,7 +286,7 @@ class SFTDataset(StatefulIterableDataset):
# Default names are optional: a dataset carries either messages or
# prompt/completion, and tools only for tool use. A name set in the
# config must exist.
for field in ("messages", "prompt", "completion", "tools"):
for field in ("messages", "prompt", "completion", "tools", "message_loss_mask"):
column = getattr(columns, field)
if column != field and column not in dataset.column_names:
raise ValueError(f"data.columns.{field} is {column!r}, but the dataset has only {dataset.column_names}")
@@ -342,9 +349,7 @@ class SFTDataset(StatefulIterableDataset):
case _:
raise ValueError(f"Invalid message role: {message['role']}")
# Defer to the renderer's sampled_mask by default: a role filter would
# drop sampled stop markers attributed to the next message (e.g. GLM's
# turn-closing <|user|> / <|observation|>).
# Let the renderer identify sampled targets when assistant loss is enabled.
role_to_mask = None if self.loss_mask_config.assistant else should_mask
# Non-assistant roles are opted into the loss via the renderer's
@@ -359,6 +364,7 @@ class SFTDataset(StatefulIterableDataset):
tools=tools,
content_sft_roles=content_sft_roles or None,
ensure_final_stop=True,
message_loss_mask=example.get(self.columns.message_loss_mask),
)
input_ids = list(sample.token_ids)
loss_mask = list(sample.loss_mask)
@@ -474,12 +480,13 @@ class SFTDataset(StatefulIterableDataset):
class CatDataset(StatefulIterableDataset):
"""Concatenate text and multimodal samples into one fixed-length row."""
"""Pack samples into rows of at most `seq_len` tokens, padded to a multiple of `pad_to_multiple_of`."""
def __init__(self, dataset: StatefulIterableDataset, seq_len: int):
def __init__(self, dataset: StatefulIterableDataset, seq_len: int, pad_to_multiple_of: int):
self.logger = get_logger()
self.dataset = dataset
self.seq_len = seq_len
self.pad_to_multiple_of = pad_to_multiple_of
self.pending_sample: Sample | None = None
def state_dict(self) -> dict:
@@ -583,7 +590,7 @@ class CatDataset(StatefulIterableDataset):
if kept > 0:
result["seq_lens"].append(kept)
remaining -= kept
pad_len = seq_len - len(result["input_ids"])
pad_len = -len(result["input_ids"]) % self.pad_to_multiple_of
if pad_len > 0:
result["input_ids"].extend([0] * pad_len)
result["position_ids"].extend(range(pad_len))
@@ -753,8 +760,8 @@ def setup_dataset(
raise ValueError(f"Invalid dataset type: {config.type}")
def setup_dataloader(dataset: StatefulIterableDataset, config: DataConfig) -> StatefulDataLoader:
packing_dataset = CatDataset(dataset, config.seq_len * config.micro_batch_size)
def setup_dataloader(dataset: StatefulIterableDataset, config: DataConfig, cp: int) -> StatefulDataLoader:
packing_dataset = CatDataset(dataset, config.seq_len * config.micro_batch_size, pad_to_multiple_of=cp)
return StatefulDataLoader(
packing_dataset,
batch_size=1,
+10 -12
View File
@@ -113,7 +113,7 @@ def train(config: SFTConfig):
resolve_ep(config.model)
# Initialize parallel dimensions
parallel_dims = get_parallel_dims(config.model, config.data.seq_len)
parallel_dims = get_parallel_dims(config.model)
total_micro_batches = config.data.batch_size * config.model.cp
micro_batches_per_step = world.world_size * config.data.micro_batch_size
@@ -192,7 +192,7 @@ def train(config: SFTConfig):
processor=processor,
multimodal=multimodal,
)
dataloader = setup_dataloader(dataset, config.data)
dataloader = setup_dataloader(dataset, config.data, config.model.cp)
val_raw_dataset = None
if config.val is not None:
@@ -257,7 +257,7 @@ def train(config: SFTConfig):
if cp_enabled:
# CP requires the sequence length to be divisible by cp_size. CatDataset
# pads every pack to seq_len; shard_for_cp raises on violations.
# pads every pack to a multiple of it; shard_for_cp raises on violations.
defer_vlm_cp_to_model = (
mm_kwargs is not None and "image_grid_thw" in mm_kwargs and config.model.cp_style == "ulysses"
)
@@ -345,7 +345,7 @@ def train(config: SFTConfig):
processor=processor,
multimodal=multimodal,
)
val_dataloader = setup_dataloader(val_dataset, config.val.data)
val_dataloader = setup_dataloader(val_dataset, config.val.data, config.model.cp)
# 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)
@@ -451,7 +451,9 @@ def train(config: SFTConfig):
)
step_tokens_per_expert = 0
step_local_num_tokens = 0
for micro_step, micro_batch in enumerate(micro_batches):
step_local_num_tokens += micro_batch["input_ids"].shape[1]
if config.log.log_data:
print_sample(
micro_batch["input_ids"].flatten().tolist(), micro_batch["loss_mask"].flatten().tolist(), tokenizer
@@ -549,14 +551,10 @@ def train(config: SFTConfig):
if memory_profiler is not None:
memory_profiler.step()
# Compute step metrics. CP shards the same sequences across cp ranks
# (sequence-sharded data parallelism on the seq dim), so the unique
# training tokens per step is dp_size * (batch_per_dp_rank * seq).
# The `dp` mesh excludes cp by construction (parallel_dims.py), mirroring
# the RL trainer's accounting (rl/train.py).
dp_size = parallel_dims.get_mesh("dp").size()
num_local_tokens = config.data.seq_len * (config.data.batch_size // dp_size)
num_tokens = dp_size * num_local_tokens
# The dp mesh excludes cp, whose ranks hold the same rows.
global_num_tokens = torch.tensor(step_local_num_tokens, dtype=torch.int64, device="cuda")
dist.all_reduce(global_num_tokens, op=dist.ReduceOp.SUM, group=parallel_dims.get_mesh("dp").get_group())
num_tokens = global_num_tokens.item()
progress.total_tokens += num_tokens
dataset_progress = get_dataset_progress(dataloader)
progress.total_samples = dataset_progress["step"]
+1 -1
View File
@@ -153,7 +153,7 @@ class WeightReceiver(ABC):
while not sender_ready.exists():
if cancelled is not None and cancelled():
raise asyncio.CancelledError
await asyncio.sleep(0.2)
await asyncio.sleep(0.1)
def _ack(self, step: int) -> None:
"""Acknowledge the offered version — unblocks the waiting trainer."""
+4 -2
View File
@@ -143,11 +143,12 @@ def setup_logger(
if json_logging and tag:
logger = logger.bind(tag=tag)
# diagnose=False: repr()-ing frame locals that hold multi-GB tensors makes a crash look like a hang.
# Install console handler (enqueue=True only for JSON mode to avoid blocking in async contexts)
if json_logging:
logger.add(json_sink, level=(console_level or log_level).upper(), enqueue=True)
logger.add(json_sink, level=(console_level or log_level).upper(), enqueue=True, diagnose=False)
else:
logger.add(sys.stdout, format=format, level=(console_level or log_level).upper(), colorize=True)
logger.add(sys.stdout, format=format, level=(console_level or log_level).upper(), colorize=True, diagnose=False)
if log_file is not None:
# The console format carries raw ANSI codes; the file gets a plain layout.
logger.add(
@@ -155,6 +156,7 @@ def setup_logger(
format="{time:HH:mm:ss} {level: >7} " + f"{tag_prefix}{{message}}",
level=log_level.upper(),
colorize=False,
diagnose=False,
)
# Disable critical logging
+2
View File
@@ -22,6 +22,8 @@ DEFAULT_COMMON_ENV_VARS: dict[str, str] = {
"PYTHONUNBUFFERED": "1",
"OMP_NUM_THREADS": "1",
"GIT_LFS_SKIP_SMUDGE": "1",
# Processes sharing ~/.triton on a shared FS hang or crash. Per-user because /tmp is shared by all users.
"TRITON_CACHE_DIR": f"/tmp/triton-{os.getuid()}",
}
DEFAULT_TRAINER_ENV_VARS: dict[str, str] = {
+55
View File
@@ -0,0 +1,55 @@
from collections import deque
from collections.abc import Callable, Iterable, Iterator
from concurrent.futures import Future, ThreadPoolExecutor
from typing import TypeVar
T = TypeVar("T")
R = TypeVar("R")
class WorkerPool:
"""Persistent background threads that map a function over an iterator in order, or the calling thread when ``num_workers`` is 0.
``map_fn`` runs concurrently on up to ``num_workers`` threads, so it must be thread-safe.
"""
def __init__(self, num_workers: int):
self.num_workers = num_workers
self.executor: ThreadPoolExecutor | None = None
if num_workers > 0:
# Threads share the trainer's memory, so items and results pass by reference: no pickling,
# no /dev/shm copies, and no forked copy-on-write memory, unlike worker processes.
self.executor = ThreadPoolExecutor(max_workers=num_workers, thread_name_prefix="worker-pool")
def __call__(self, map_fn: Callable[[T], R], items: Iterable[T]) -> Iterator[R]:
"""Yield ``map_fn(item)`` in input order, with at most ``2 * num_workers`` items submitted but not yet yielded.
The factor 2 plays the role of torch DataLoader's ``prefetch_factor`` (batches loaded ahead per worker),
hard-coded to its torch default for simplicity. Any bound above ``num_workers`` keeps every worker busy while
the caller holds a result; the extra slack absorbs items that take unusually long.
"""
if self.executor is None:
yield from map(map_fn, items)
return
max_in_flight = 2 * self.num_workers
pending: deque[Future[R]] = deque()
try:
for item in items:
pending.append(self.executor.submit(map_fn, item))
if len(pending) >= max_in_flight:
yield pending.popleft().result()
while pending:
yield pending.popleft().result()
finally:
for future in pending:
future.cancel()
def close(self) -> None:
if self.executor is not None:
self.executor.shutdown(cancel_futures=True)
def __enter__(self) -> "WorkerPool":
return self
def __exit__(self, *exc_info: object) -> None:
self.close()
-9
View File
@@ -1,6 +1,5 @@
import os
import signal
import socket
import subprocess
from pathlib import Path
from typing import Callable, Generator
@@ -46,14 +45,6 @@ def cleanup_zombies():
yield
@pytest.fixture
def free_port() -> int:
"""Fixture to get a free port per tests"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("", 0))
return s.getsockname()[1]
@pytest.fixture(scope="session")
def user() -> str:
"""Fixture for current user from environment for test session."""
+87 -27
View File
@@ -1,6 +1,11 @@
import uuid
from types import SimpleNamespace
import orjson
import pytest
import verifiers.v1 as vf
from pydantic import ValidationError
from verifiers.v1.utils.eval import plan_rollouts
from prime_rl.eval import resume
from prime_rl.monitors.file.traces import get_trace_stream
@@ -21,6 +26,7 @@ def _env(name: str, task_keys: list[str], *, group_size: int = 1) -> SimpleNames
def _record(env: str, key: str, *, ok: bool = True, group: str | None = None) -> dict:
return {
"id": uuid.uuid4().hex,
"env": {"id": env, "name": env},
"task": {"type": "Task", "data": {"idx": 0}, "key": key, "hash": key},
"group": {"id": group or f"group-{key}"},
@@ -29,38 +35,64 @@ def _record(env: str, key: str, *, ok: bool = True, group: str | None = None) ->
}
def test_plan_keeps_landed_rollouts_up_to_the_target_and_owes_the_rest() -> None:
envs = [_env("math", ["m0", "m1", "m2"], group_size=2), _env("code", ["c0"])]
landed = [
_record("math", "m0"),
_record("math", "m0"),
_record("math", "m0"), # a third rollout of m0 exceeds group_size 2
_record("math", "m1"),
_record("math", "m9"), # no longer selected (select.limit shrank)
_record("code", "c0", ok=False), # errored: owed again
]
@pytest.mark.parametrize(
"hashes,rollouts,landed,expected_kept,expected_missing",
[
(["a", "b"], 2, [], [[], []], [2, 2]),
(["a"], 1, [("e1", "a")], [["e1"]], [0]),
(["changed"], 1, [("e1", "a")], [[]], [1]),
(["a"], 3, [("e1", "a"), ("e2", "a")], [["e1", "e2"]], [1]),
(["a"], 1, [("e1", "a"), ("e2", "a")], [["e1"]], [0]),
(["a", "a"], 2, [("e1", "a")], [["e1"], []], [1, 2]),
(["a", "changed"], 1, [("e1", "a"), ("e2", "a")], [["e1"], []], [0, 1]),
(["a"], 2, [("e1", "a"), ("e1", "a")], [["e1"]], [1]),
(["a"], 1, [("e1", "removed")], [[]], [1]),
([], 1, [("e1", "a")], [], []),
],
)
def test_plan_keeps_landed_rollouts_up_to_the_target_and_owes_the_rest(
hashes, rollouts, landed, expected_kept, expected_missing
) -> None:
tasks = [SimpleNamespace(key="stable-key", hash=content_hash) for content_hash in hashes]
episodes = []
for episode_id, content_hash in landed:
row = _record("math", "stable-key")
row["id"] = episode_id
row["task"]["hash"] = content_hash
episodes.append(vf.WireEpisode.model_validate(row))
kept, owed, groups = resume.plan([record for record in landed if record["ok"]], envs)
plan = plan_rollouts(tasks, rollouts, episodes)
assert [(episode.env.name, episode.task.key) for episode in kept] == [
("math", "m0"),
("math", "m0"),
("math", "m1"),
]
assert owed == {"math": {"m1": 1, "m2": 2}, "code": {"c0": 1}}
# the owed rollout of m1 completes the group its landed rollout opened
assert groups == {"math": {"m0": "group-m0", "m1": "group-m1"}}
assert [task for task, _, _ in plan] == tasks
assert [[episode.id for episode in kept] for _, kept, _ in plan] == expected_kept
assert [missing for _, _, missing in plan] == expected_missing
assert all(len(kept) + missing == rollouts for _, kept, missing in plan)
def test_trigger_queues_only_owed_rollouts() -> None:
source = EvalSource([_env("math", ["m0", "m1", "m2"], group_size=2), _env("code", ["c0"])])
source.restore({"math": {"m1": 1, "m2": 2}, "code": {}}, {"math": {"m1": "group-m1"}})
source = EvalSource([_env("math", ["m0", "m1", "m1"], group_size=2), _env("code", ["m1"])])
episodes = [vf.WireEpisode.model_validate(_record("math", key)) for key in ["m0", "m0", "m1"]]
assert source.trigger(0) == ["math", "code"]
assert [(request.env_name, request.task.key, request.rollouts, request.group_id) for request in source.queue] == [
("math", "m1", 1, "group-m1"),
("math", "m2", 2, None),
fired, restored = source.trigger(0, completed=episodes)
assert fired == ["math", "code"]
requests = list(source.queue)
assert [(request.env_name, request.task.key, request.rollouts) for request in requests] == [
("code", "m1", 1),
("math", "m1", 1),
("math", "m1", 2),
]
assert restored == episodes
assert len({request.group_id for request in requests}) == 3
assert restored[-1].group.id == requests[1].group_id
assert restored[0].group == restored[1].group
assert restored[0].group != restored[-1].group
assert all(str(uuid.UUID(request.group_id)) == request.group_id for request in requests)
# Saved episodes affect only this epoch; later triggers plan every rollout again.
source.queue.clear()
assert source.trigger(1) == (["math", "code"], [])
assert [request.rollouts for request in source.queue] == [2, 1, 2, 2]
def test_take_landed_reads_every_attempt_once(tmp_path) -> None:
@@ -71,11 +103,39 @@ def test_take_landed_reads_every_attempt_once(tmp_path) -> None:
stream.close()
land("m0", "m1")
assert [record["id"] for record in resume.take_landed(tmp_path)] == ["m0", "m1"]
assert [episode.id for episode in resume.take_landed(tmp_path)] == ["m0", "m1"]
assert not get_file_monitor_dir(tmp_path).exists()
assert [path.name for path in resume.archives(tmp_path)] == ["file.attempt_1"]
# the resumed attempt re-logged one episode and landed a new one before it died
land("m0", "m2")
assert [record["id"] for record in resume.take_landed(tmp_path)] == ["m0", "m1", "m2"]
landed = resume.take_landed(tmp_path)
source = EvalSource([_env("math", ["m0", "m1", "m2"], group_size=2)])
_, kept = source.trigger(0, completed=landed)
assert [episode.id for episode in kept] == ["m0", "m1", "m2"]
assert [request.rollouts for request in source.queue] == [1, 1, 1]
assert [path.name for path in resume.archives(tmp_path)] == ["file.attempt_1", "file.attempt_2"]
@pytest.mark.parametrize("ok", [True, False])
@pytest.mark.parametrize("traces,valid", [([], True), (None, False), ([{}], False)])
def test_resume_validates_saved_episodes(tmp_path, ok, traces, valid) -> None:
record = {**_record("math", "m0", ok=ok), "id": "saved", "traces": traces}
stream = ChunkedJsonl(get_trace_stream(tmp_path), max_bytes=1 << 20, compress=False)
for row in [{key: value for key, value in record.items() if key != "traces"}, record]:
stream.append(orjson.dumps(row, option=orjson.OPT_APPEND_NEWLINE))
stream.close()
if not valid:
with pytest.raises(ValidationError):
resume.take_landed(tmp_path)
assert get_file_monitor_dir(tmp_path).is_dir()
assert resume.archives(tmp_path) == []
return
landed = resume.take_landed(tmp_path)
source = EvalSource([_env("math", ["m0"], group_size=2)])
_, restored = source.trigger(0, completed=landed)
assert [episode.id for episode in restored] == (["saved"] if ok else [])
assert [request.rollouts for request in source.queue] == [1 if ok else 2]
@@ -1,79 +0,0 @@
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])
@@ -110,6 +110,7 @@ def _build_episode(
task=trace.task,
group=vf.GroupInfo(id="group"),
traces=[trace],
ok=True,
)
return episode
@@ -9,6 +9,7 @@ from verifiers.v1.types import AssistantMessage, ToolMessage, UserMessage
from prime_rl.configs.algorithm import AlgoConfig, FrozenModelConfig
from prime_rl.orchestrator.algo import EchoAlgorithm, assign_advantages, stamp_loss_routing
from prime_rl.orchestrator.algo.base import iter_trainable_traces
from prime_rl.orchestrator.trajectories import trace_to_samples
from prime_rl.transports.batch.types import TrainingSample
@@ -201,10 +202,33 @@ def _make_episode() -> vf.Episode:
task=trace.task,
group=vf.GroupInfo(id="group"),
traces=[trace],
ok=True,
)
return episode
@pytest.mark.parametrize("failure", ["participant", "untrainable_participant", "environment"])
def test_trainable_traces_exclude_failed_episodes_without_changing_verdicts(failure):
good = _make_episode()
good.errors = [vf.Error(type="RecoveredError", message="Previous attempt failed")]
good.traces[0].errors = list(good.errors)
failed = _make_episode()
failed.ok = False
if failure == "environment":
failed.errors = [vf.Error(type="EnvError", message="Finalization failed")]
else:
sibling = failed.traces[0].model_copy(deep=True)
sibling.id = "failed-sibling"
sibling.ok = False
sibling.errors = [vf.Error(type="AgentError", message="Participant failed")]
sibling.agent.trainable = failure == "participant"
failed.traces.append(sibling)
before = failed.model_dump()
assert list(iter_trainable_traces([failed, good])) == [(good, good.traces[0])]
assert failed.model_dump() == before
def test_assign_advantages_full_length_stream():
# The advantage stream is full-length-N: 0.0 on prompt + non-trainable
# positions, the rl credit on trainable (mask True) tokens.
+4
View File
@@ -93,6 +93,8 @@ def test_setup_client_creates_renderer_client():
base_url="http://worker-a:8000/v1",
api_key_var="PRIME_API_KEY",
headers={"X-Test": "test"},
headers_from_env={"X-Token": "PROVIDER_TOKEN"},
timeout={"read": 12},
)
renderer_settings = Qwen3VLRendererConfig()
@@ -108,6 +110,8 @@ def test_setup_client_creates_renderer_client():
assert client.base_url == "http://worker-a:8000/v1"
assert "X-data-parallel-rank" not in client.headers
assert client.headers["X-Test"] == "test"
assert client.headers_from_env == {"X-Token": "PROVIDER_TOKEN"}
assert client.timeout.read == 12
def test_check_health_retries_non_success_status():
+21 -2
View File
@@ -42,7 +42,7 @@ def make_rollout(
)
]
if advantages is not None
else []
else [vf.MessageNode(message=vf.AssistantMessage(content="answer"), sampled=True)]
)
trace = vf.Trace(
task=vf.TraceTask(
@@ -61,6 +61,7 @@ def make_rollout(
task=trace.task,
group=vf.GroupInfo(id=str(uuid.uuid4())),
traces=[trace],
ok=True,
)
return [episode]
@@ -111,7 +112,12 @@ def test_train_source_composes_sampler_and_all_gates_with_state_and_metrics() ->
source = TrainSource([env])
sampled = source.next_task(step=1).task
assert source.on_result(make_rollout(sampled, reward=0.25, advantages=[0.0])) is False
empty = make_rollout(sampled, reward=1.0)
empty[0].traces[0].nodes[0].sampled = False
group = make_rollout(sampled, reward=0.25, advantages=[0.0])
failed = make_rollout(sampled, reward=1.0, advantages=[1.0])
failed[0].ok = False
assert source.on_result(group + failed + empty) is False
assert source.metrics() == {
"curriculum/test/admission_rate": 0.0,
"curriculum/test/sampler/pool/unseen": 2.0,
@@ -127,6 +133,19 @@ def test_train_source_composes_sampler_and_all_gates_with_state_and_metrics() ->
"admit": {},
}
assert source.on_result(empty) is False
assert source.metrics()["curriculum/test/admission_rate"] == 0.0
assert source.curricula["test"].sampler.task_rewards == {sampled.key: 0.25}
# A scored rollout without token metadata still informs task difficulty.
assert source.on_result(make_rollout(sampled, reward=0.5)) is False
assert source.metrics()["curriculum/test/admission_rate"] == 0.0
assert source.curricula["test"].sampler.task_rewards == {sampled.key: 0.5}
assert source.on_result(make_rollout(sampled, reward=0.75, advantages=[1.0])) is True
assert source.metrics()["curriculum/test/admission_rate"] == 1.0
assert source.curricula["test"].sampler.task_rewards == {sampled.key: 0.75}
def test_difficulty_pools_stack_with_advantage_gate_and_resume_sampling() -> None:
tasks = [make_task(i) for i in range(3)]
+132 -4
View File
@@ -4,6 +4,7 @@ from typing import Annotated, Literal, get_args
import pytest
import tomli_w
import verifiers.v1 as vf
from pydantic import BaseModel, Field, ValidationError
from pydantic_config import ConfigFileError
from renderers import custom_renderer_config
@@ -17,6 +18,10 @@ from prime_rl.configs.orchestrator import (
RLOnlineEvalConfig,
ScheduledEvalConfig,
TrainConfig,
TrainSourceConfig,
)
from prime_rl.configs.orchestrator import (
ModelConfig as OrchestratorModelConfig,
)
from prime_rl.configs.rl import RLConfig
from prime_rl.configs.sft import SFTConfig
@@ -340,6 +345,16 @@ def test_moe_router_dtype_auto_resolves_per_trainer():
assert config_cls.model_validate({"model": {"moe_router_dtype": dtype}}).model.moe_router_dtype == dtype
def test_freeze_moe_router_auto_resolves_per_trainer():
"""``freeze_moe_router='auto'`` (the default) freezes the router for RL, not SFT; explicit values are kept."""
assert TrainerConfig.model_validate({}).model.freeze_moe_router is True
assert SFTConfig.model_validate({}).model.freeze_moe_router is False
for config_cls in (TrainerConfig, SFTConfig):
for freeze in (True, False):
assert config_cls.model_validate({"model": {"freeze_moe_router": freeze}}).model.freeze_moe_router is freeze
@pytest.mark.parametrize("config_cls", [TrainerConfig, SFTConfig])
def test_full_optimizer_offload_disables_gradient_clipping(config_cls):
with pytest.warns(UserWarning, match="Gradient clipping prevents optimizer-in-backward"):
@@ -393,6 +408,36 @@ def test_resolved_json_roundtrips_explicit_none(tmp_path):
assert reloaded == config
@pytest.mark.parametrize(
"config_class,source_args,expected_url,expected_key",
[
(
EvalConfig,
["--source", '[{"env":{"id":"single_agent"}}]'],
"https://configured.pinference.ai/api/v1",
"PRIME_API_KEY",
),
(
SFTOnlineEvalConfig,
["--source", '[{"env":{"id":"single_agent"}}]'],
"http://localhost:8000/v1",
"VLLM_API_KEY",
),
(OrchestratorModelConfig, [], "http://localhost:8000/v1", "VLLM_API_KEY"),
],
)
@pytest.mark.parametrize("overrides", [[], ["--client.skip-model-check"], ["--client.wait-for-ready-timeout", "10"]])
def test_client_defaults_survive_partial_overrides(
monkeypatch, config_class, source_args, expected_url, expected_key, overrides
):
monkeypatch.setenv("PRIME_INFERENCE_URL", "https://configured.pinference.ai/api/v1")
config = cli(config_class, args=source_args + overrides)
assert config.client.base_url == expected_url
assert config.client.api_key_var == expected_key
reloaded = config_class.model_validate_json(config.model_dump_json())
assert reloaded.client == config.client
def test_env_algo_inherits_the_group_algo():
config = OrchestratorConfig.model_validate(
{
@@ -419,11 +464,25 @@ def test_env_algo_inherits_the_group_algo():
assert [env.algo.type for env in reloaded.train.source] == ["grpo", "echo", "echo"]
def test_sources_inherit_the_group_fields_they_leave_unset():
@pytest.mark.parametrize("group_token_key", ["max_tokens", "max_completion_tokens"])
@pytest.mark.parametrize("source_token_key", ["max_tokens", "max_completion_tokens"])
@pytest.mark.parametrize("source_token_limit", [200, None])
@pytest.mark.parametrize("nested_sampling", [False, True])
def test_sources_inherit_the_group_fields_they_leave_unset(
group_token_key, source_token_key, source_token_limit, nested_sampling
):
overrides = {source_token_key: source_token_limit, "top_k": 20}
config = EvalConfig.model_validate(
{
"r": 4,
"sampling": {"temperature": 0.5, "extra_body": {"a": 1}},
"sampling": {
group_token_key: 100,
"temperature": 3.0,
"reasoning_effort": "xhigh",
"top_k": 40,
"frequency_penalty": 0.5,
"extra_body": {"a": 1},
},
"select": {"limit": 8, "include": {"idx": [":100"]}},
"env": {"retries": {"max_retries": 3}},
"source": [
@@ -432,7 +491,11 @@ def test_sources_inherit_the_group_fields_they_leave_unset():
"name": "b",
"env": {"taskset": {"id": "gsm8k"}},
"group_size": 2,
"sampling": {"extra_body": {"b": 2}},
"sampling": {
**({} if nested_sampling else overrides),
"reasoning_effort": "max",
"extra_body": {"b": 2, **(overrides if nested_sampling else {})},
},
"select": {"include": {"names": ["x"]}},
},
],
@@ -440,7 +503,18 @@ def test_sources_inherit_the_group_fields_they_leave_unset():
)
a, b = config.source
assert (a.group_size, b.group_size) == (4, 2)
assert b.sampling.temperature == 0.5 and b.sampling.extra_body == {"a": 1, "b": 2}
assert isinstance(a.sampling, vf.SamplingConfig) and isinstance(b.sampling, vf.SamplingConfig)
assert a.sampling.max_tokens == 100 and b.sampling.max_tokens == source_token_limit
assert a.sampling.reasoning_effort == "xhigh" and a.sampling.top_k == 40
assert b.sampling.model_dump(exclude_none=True) == {
**({"max_tokens": source_token_limit} if source_token_limit is not None else {}),
"temperature": 3.0,
"reasoning_effort": "max",
"top_k": 20,
"frequency_penalty": 0.5,
"a": 1,
"b": 2,
}
assert b.select.limit == 8 and b.select.include.idx == [":100"] and b.select.include.names == ["x"]
assert a.env.retries.max_retries == 3 and b.env.retries.max_retries == 3
reloaded = EvalConfig.model_validate(config.model_dump(mode="json"))
@@ -521,6 +595,39 @@ def test_policy_sources_accept_different_top_p_values():
assert [source.sampling.top_k for source in config.train.source] == [512, 512]
@pytest.mark.parametrize("frozen", [False, True])
@pytest.mark.parametrize(
"sampling,agent_sampling,rejected",
[
({}, {}, False),
({"top_p": 0.9}, {"max_completion_tokens": 200, "reasoning_effort": "high"}, False),
({}, {"extra_body": {"chat_template_kwargs": {"enable_thinking": True}}}, False),
({}, {"temperature": 1.0}, True),
({}, {"temperature": None}, True),
({}, {"extra_body": {"top_k": 20}}, True),
({}, {"frequency_penalty": 0.5}, True),
({}, {"extra_body": {"frequency_penalty": 0.5}}, True),
({"extra_body": {"frequency_penalty": 0.5}}, {}, True),
],
)
def test_policy_sampling_is_validated_before_rollouts(sampling, agent_sampling, rejected, frozen):
source = {
"env": {"taskset": {"id": "reverse-text"}, "agent": {"sampling": agent_sampling}},
"sampling": sampling,
}
if frozen:
source["algo"] = {
"type": "sft",
"sampling": {"source": {"name": "teacher", "base_url": "http://localhost:8000/v1"}},
}
if rejected and not frozen:
with pytest.raises(ValidationError, match="sampling"):
TrainSourceConfig.model_validate(source)
else:
config = TrainSourceConfig.model_validate(source)
assert TrainSourceConfig.model_validate_json(config.model_dump_json()) == config
def test_policy_sources_reject_mixed_top_k_capture():
with pytest.warns(UserWarning, match="defaulting top_k"):
with pytest.raises(ValidationError, match="cannot mix top_k > 0 and top_k = -1"):
@@ -561,10 +668,31 @@ def test_single_node_auto_inference_ports_follow_server_port():
assert config.inference is not None
assert config.inference.vllm.data_parallel_size == 2
assert config.trainer.weight_broadcast.inference_world_size == 2
assert config.orchestrator.weight_broadcast.inference_world_size == 2
assert config.inference.backend_port == 8101
assert config.orchestrator.model.client.admin_base_url == ["http://localhost:8101/v1"]
def test_single_node_nccl_resolved_json_roundtrips(tmp_path):
"""The resolved rl.json re-parses (as a SLURM launch does) to the same config."""
import json
config = RLConfig.model_validate(
{
"trainer": {},
"orchestrator": {},
"inference": {"vllm": {"tensor_parallel_size": 1}},
"deployment": {"type": "single_node", "gpus_per_node": 4, "num_train_gpus": 2, "num_infer_gpus": 2},
}
)
path = tmp_path / "rl.json"
path.write_text(json.dumps(dump_resolved_config(config, exclude={"slurm", "dry_run", "clean"})))
reloaded = cli(RLConfig, args=["@", str(path)])
assert reloaded.trainer.weight_broadcast.inference_world_size == 2
assert reloaded == config
def test_multi_node_auto_inference_parallelism():
config = RLConfig.model_validate(
{
@@ -1,132 +0,0 @@
# coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from transformers.configuration_utils import PretrainedConfig, layer_type_validation
from transformers.utils import logging
logger = logging.get_logger(__name__)
class AfmoeConfig(PretrainedConfig):
"""
n_group (`int`, *optional*, defaults to 1):
Number of groups for routed experts.
topk_group (`int`, *optional*, defaults to 1):
Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
"""
model_type = "afmoe"
base_model_pp_plan = {
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
"norm": (["hidden_states"], ["hidden_states"]),
}
def __init__(
self,
num_hidden_layers: int = 32,
vocab_size: int = 200192,
hidden_size: int = 2048,
intermediate_size: int = 6144,
moe_intermediate_size=1408,
num_dense_layers=1,
num_attention_heads=16,
num_key_value_heads=None,
head_dim=128,
hidden_act="silu",
max_position_embeddings=16384,
initializer_range=0.02,
rms_norm_eps=1e-5,
use_cache=True,
tie_word_embeddings=False,
rope_theta=10000.0,
rope_scaling=None,
num_experts=64,
num_experts_per_tok=6,
num_shared_experts=2,
num_expert_groups=1,
num_limited_groups=1,
score_func="sigmoid",
route_norm=True,
route_scale=1.0,
load_balance_coeff: float | None = None,
use_grouped_mm: bool = True,
global_attn_every_n_layers=4,
sliding_window=1024,
mup_enabled=False,
layer_types=None,
attention_dropout: float = 0.0,
n_group: int = 1,
topk_group: int = 1,
pad_token_id: int | None = None,
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_dense_layers = num_dense_layers
self.num_attention_heads = num_attention_heads
self.head_dim = head_dim
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.rope_theta = rope_theta
self.rope_scaling = rope_scaling
# MoE specific
self.moe_intermediate_size = moe_intermediate_size
self.num_experts_per_tok = num_experts_per_tok
self.n_group = n_group
self.topk_group = topk_group
self.num_experts = num_experts
self.num_shared_experts = num_shared_experts
self.num_expert_groups = num_expert_groups
self.num_limited_groups = num_limited_groups
self.score_func = score_func
self.route_norm = route_norm
self.route_scale = route_scale
self.load_balance_coeff = load_balance_coeff
self.use_grouped_mm = use_grouped_mm
# Attention specific
self.attention_dropout = attention_dropout
self.global_attn_every_n_layers = global_attn_every_n_layers
self.sliding_window = sliding_window
self.layer_types = layer_types
if self.layer_types is None:
self.layer_types = [
"sliding_attention" if bool((i + 1) % global_attn_every_n_layers) else "full_attention"
for i in range(self.num_hidden_layers)
]
layer_type_validation(self.layer_types)
# muP specific
self.mup_enabled = mup_enabled
if num_key_value_heads is None:
num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.pad_token_id = pad_token_id
super().__init__(
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
__all__ = ["AfmoeConfig"]
@@ -1,645 +0,0 @@
from typing import Callable, Optional, Tuple, Union
import torch
import torch.nn.functional as F
from torch import nn
from transformers.activations import ACT2FN
from transformers.cache_utils import Cache, DynamicCache
from transformers.generation import GenerationMixin
from transformers.integrations import use_kernel_forward_from_hub
from transformers.masking_utils import (
create_causal_mask,
create_sliding_window_causal_mask,
)
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import (
MoeCausalLMOutputWithPast,
MoeModelOutputWithPast,
)
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs
try:
from .configuration_afmoe import AfmoeConfig
except:
from configuration_afmoe import AfmoeConfig
class AfmoeRotaryEmbedding(nn.Module):
def __init__(self, config: AfmoeConfig, device=None):
super().__init__()
# BC: "rope_type" was originally "type"
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
else:
self.rope_type = "default"
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.config = config
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.original_inv_freq = self.inv_freq
def compute_default_rope_parameters(self, config=None, device=None, seq_len=None, layer_type=None):
"""Required by transformers 5.0.0 for weight initialization when rope_type is 'default'."""
cfg = config or self.config
cfg.standardize_rope_params()
rope_params = cfg.rope_parameters[layer_type] if layer_type is not None else cfg.rope_parameters
base = rope_params["rope_theta"]
partial_rotary_factor = rope_params.get("partial_rotary_factor", 1.0)
head_dim = getattr(cfg, "head_dim", None) or cfg.hidden_size // cfg.num_attention_heads
dim = int(head_dim * partial_rotary_factor)
inv_freq = 1.0 / (
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
)
return inv_freq, 1.0
def _dynamic_frequency_update(self, position_ids, device):
"""
dynamic RoPE layers should recompute `inv_freq` in the following situations:
1 - growing beyond the cached sequence length (allow scaling)
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
"""
seq_len = torch.max(position_ids) + 1
if seq_len > self.max_seq_len_cached: # growth
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.max_seq_len_cached = seq_len
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
# This .to() is needed if the model has been moved to a device after being initialized (because
# the buffer is automatically moved, but not the original copy)
self.original_inv_freq = self.original_inv_freq.to(device)
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
self.max_seq_len_cached = self.original_max_seq_len
@torch.no_grad()
def forward(self, x, position_ids):
if "dynamic" in self.rope_type:
self._dynamic_frequency_update(position_ids, device=x.device)
# Core RoPE block
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
position_ids_expanded = position_ids[:, None, :].float()
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
device_type = x.device.type
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False):
freqs = (inv_freq_expanded.float().to(x.device) @ position_ids_expanded.float()).transpose(1, 2)
emb = torch.cat((freqs, freqs), dim=-1)
cos = emb.cos()
sin = emb.sin()
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
cos = cos * self.attention_scaling
sin = sin * self.attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
def rotate_half(x):
"""Rotates half the hidden dims of the input."""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
"""Applies Rotary Position Embedding to the query and key tensors.
Args:
q (`torch.Tensor`): The query tensor.
k (`torch.Tensor`): The key tensor.
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
position_ids (`torch.Tensor`, *optional*):
Deprecated and unused.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
"""
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
if n_rep == 1:
return hidden_states
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
@use_kernel_forward_from_hub("RMSNorm")
class AfmoeRMSNorm(nn.Module):
def __init__(self, hidden_size: int, eps: float):
"""
AfmoeRMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states):
input_dtype = hidden_states.dtype
hidden_states = hidden_states.to(torch.float32)
variance = hidden_states.pow(2).mean(-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
return self.weight * hidden_states.to(input_dtype)
def extra_repr(self):
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
def eager_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Optional[torch.Tensor],
scaling: float,
dropout: float = 0.0,
**kwargs,
):
key_states = repeat_kv(key, module.num_key_value_groups)
value_states = repeat_kv(value, module.num_key_value_groups)
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
if attention_mask is not None:
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
attn_weights = attn_weights + causal_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
attn_output = torch.matmul(attn_weights, value_states)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
class AfmoeMLP(nn.Module):
def __init__(self, config, intermediate_size=None):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.intermediate_size = intermediate_size or config.intermediate_size
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
self.act_fn = ACT2FN[config.hidden_act]
def forward(self, x):
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
class AfmoeTokenChoiceRouter(nn.Module):
"""Token-choice top-K router for MoE routing."""
def __init__(self, config):
super().__init__()
self.config = config
self.top_k = config.num_experts_per_tok
self.num_experts = config.num_experts
self.score_func = config.score_func
self.route_norm = config.route_norm
self.route_scale = config.route_scale
self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
def forward(self, hidden_states, expert_bias: torch.Tensor | None):
_, _, hidden_dim = hidden_states.shape
hidden_states = hidden_states.view(-1, hidden_dim)
scores = self.gate(hidden_states)
# Apply scoring function in float32 for stability
if self.score_func == "sigmoid":
scores = torch.sigmoid(scores.to(torch.float32))
else:
scores = F.softmax(scores.to(torch.float32), dim=-1)
if expert_bias is not None:
_, selected_experts = torch.topk(scores + expert_bias, k=self.top_k, dim=1)
top_scores = scores.gather(dim=1, index=selected_experts)
else:
top_scores, selected_experts = torch.topk(scores, k=self.top_k, dim=1)
# Normalize weights if using sigmoid
if self.score_func == "sigmoid" and self.route_norm:
denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
top_scores = top_scores / denominator
top_scores = top_scores * self.route_scale
return top_scores, selected_experts
class AfmoeMoE(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.router = AfmoeTokenChoiceRouter(config)
self.shared_experts = None
if config.num_shared_experts > 0:
self.shared_experts = AfmoeMLP(config, config.moe_intermediate_size * config.num_shared_experts)
self.experts = nn.ModuleList(
[AfmoeMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(config.num_experts)]
)
self.expert_bias = nn.Parameter(torch.zeros(config.num_experts, dtype=torch.float32), requires_grad=False)
def forward(self, hidden_states):
batch_size, seq_len, hidden_dim = hidden_states.shape
hidden_states_flat = hidden_states.view(-1, hidden_dim)
# Get routing decisions
top_scores, selected_experts = self.router(hidden_states, self.expert_bias)
# Process through shared experts
if self.shared_experts is not None:
shared_output = self.shared_experts(hidden_states_flat)
else:
shared_output = torch.zeros_like(hidden_states_flat)
# Reorder tokens by expert for efficient processing
token_indices_sorted = torch.argsort(selected_experts.view(-1), stable=True)
top_scores_sorted = top_scores.view(-1)[token_indices_sorted]
token_to_expert = selected_experts.view(-1)[token_indices_sorted]
token_indices_sorted = token_indices_sorted // self.config.num_experts_per_tok
# Gather input tokens
token_indices_expanded = token_indices_sorted.unsqueeze(-1).expand(-1, hidden_dim)
routed_input = torch.gather(hidden_states_flat, dim=0, index=token_indices_expanded)
routed_output = torch.zeros_like(routed_input)
for expert_id in range(self.config.num_experts):
mask = token_to_expert == expert_id
if mask.any():
expert_input = routed_input[mask]
expert_out = self.experts[expert_id](expert_input)
routed_output[mask] = expert_out
routed_output = (routed_output.to(torch.float32) * top_scores_sorted.unsqueeze(-1)).to(hidden_states.dtype)
# Scatter back to original positions
output = shared_output.scatter_add(dim=0, index=token_indices_expanded, src=routed_output)
return output.view(batch_size, seq_len, hidden_dim)
class AfmoeAttention(nn.Module):
"""Multi-headed attention with local/global pattern and gating."""
def __init__(self, config: AfmoeConfig, layer_idx: int):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
self.num_heads = config.num_attention_heads
self.num_key_value_heads = config.num_key_value_heads
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
self.scaling = self.head_dim**-0.5
self.attention_dropout = config.attention_dropout
self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
self.sliding_window = config.sliding_window if self.is_local_attention else None
self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False)
self.k_proj = nn.Linear(config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
self.v_proj = nn.Linear(config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=False)
self.q_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.k_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.gate_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: Optional[torch.Tensor],
past_key_value: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> torch.Tensor:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states).view(hidden_shape)
key_states = self.k_proj(hidden_states).view(hidden_shape)
value_states = self.v_proj(hidden_states).view(hidden_shape)
gate_states = self.gate_proj(hidden_states)
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
value_states = value_states.transpose(1, 2)
if self.is_local_attention:
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
if past_key_value is not None:
cache_kwargs = {"cache_position": cache_position}
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
output, _ = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask=attention_mask,
dropout=0.0 if not self.training else self.attention_dropout,
scaling=self.scaling,
sliding_window=self.sliding_window,
**kwargs,
)
output = output.view(*input_shape, -1).contiguous()
output = output * F.sigmoid(gate_states)
return self.o_proj(output)
class AfmoeDecoderLayer(GradientCheckpointingLayer):
def __init__(self, config: AfmoeConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.layer_idx = layer_idx
self.self_attn = AfmoeAttention(config=config, layer_idx=layer_idx)
self.attention_type = config.layer_types[layer_idx]
# Dual normalization for attention
self.input_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
# Dual normalization for FFN
self.pre_mlp_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_mlp_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
# MoE or dense FFN
self.moe_enabled = layer_idx >= config.num_dense_layers
if self.moe_enabled:
self.mlp = AfmoeMoE(config)
else:
self.mlp = AfmoeMLP(config)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_value: Optional[Cache] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
**kwargs: Unpack[TransformersKwargs],
) -> torch.FloatTensor:
residual = hidden_states
# Self Attention with dual normalization
hidden_states = self.input_layernorm(hidden_states)
hidden_states = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_value=past_key_value,
use_cache=use_cache,
cache_position=cache_position,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = residual + hidden_states
# FFN with dual normalization
residual = hidden_states
hidden_states = self.pre_mlp_layernorm(hidden_states)
if self.moe_enabled:
hidden_states = self.mlp(hidden_states)
else:
hidden_states = self.mlp(hidden_states)
hidden_states = self.post_mlp_layernorm(hidden_states)
hidden_states = residual + hidden_states
return hidden_states
class AfmoePreTrainedModel(PreTrainedModel):
config_class = AfmoeConfig
base_model_prefix = "model"
_no_split_modules = ["AfmoeDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_keep_in_fp32_modules = [
"input_layernorm",
"post_attention_layernorm",
"pre_mlp_layernorm",
"post_mlp_layernorm",
"q_norm",
"k_norm",
"norm",
]
_supports_sdpa = True
_supports_attention_backend = True
supports_gradient_checkpointing = True
class AfmoeModel(AfmoePreTrainedModel):
_no_split_modules = ["AfmoeDecoderLayer"]
def __init__(self, config: AfmoeConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.layers = nn.ModuleList(
[AfmoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.norm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.rotary_emb = AfmoeRotaryEmbedding(config=config)
self.gradient_checkpointing = False
self.post_init()
def get_input_embeddings(self):
return self.embed_tokens
def set_input_embeddings(self, value):
self.embed_tokens = value
def forward(
self,
input_ids: torch.LongTensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[list[torch.FloatTensor]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> MoeModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if use_cache and past_key_values is None:
past_key_values = DynamicCache()
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if cache_position is None:
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
cache_position = torch.arange(
past_seen_tokens,
past_seen_tokens + inputs_embeds.shape[1],
device=inputs_embeds.device,
)
if position_ids is None:
position_ids = cache_position.unsqueeze(0)
# It may already have been prepared by e.g. `generate`
if not isinstance(causal_mask_mapping := attention_mask, dict):
mask_kwargs = {
"config": self.config,
"inputs_embeds": inputs_embeds,
"attention_mask": attention_mask,
"cache_position": cache_position,
"past_key_values": past_key_values,
}
causal_mask_mapping = {
"full_attention": create_causal_mask(**mask_kwargs),
"sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
}
hidden_states = inputs_embeds
# Apply muP input scaling if enabled
if self.config.mup_enabled:
hidden_states = hidden_states * (self.config.hidden_size**0.5)
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for decoder_layer in self.layers:
hidden_states = decoder_layer(
hidden_states,
attention_mask=causal_mask_mapping[decoder_layer.attention_type],
position_ids=position_ids,
past_key_value=past_key_values,
use_cache=use_cache,
cache_position=cache_position,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = self.norm(hidden_states)
return MoeModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=past_key_values,
)
class AfmoeForCausalLM(AfmoePreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config):
super().__init__(config)
self.model = AfmoeModel(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.model.embed_tokens
def set_input_embeddings(self, value):
self.model.embed_tokens = value
def get_output_embeddings(self):
return self.lm_head
def set_output_embeddings(self, new_embeddings):
self.lm_head = new_embeddings
def set_decoder(self, decoder):
self.model = decoder
def get_decoder(self):
return self.model
def forward(
self,
input_ids: torch.LongTensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
token_type_ids: Optional[torch.Tensor] = None, # will be ignored
**kwargs: Unpack[TransformersKwargs],
) -> Union[Tuple, MoeCausalLMOutputWithPast]:
outputs: MoeModelOutputWithPast = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
cache_position=cache_position,
**kwargs,
)
hidden_states = outputs.last_hidden_state
# Only compute necessary logits
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None
if labels is not None:
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
return MoeCausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
router_logits=outputs.router_logits,
)
__all__ = [
"AfmoeForCausalLM",
"AfmoeModel",
"AfmoePreTrainedModel",
]
-183
View File
@@ -1,183 +0,0 @@
import pytest
import torch
from torch import nn
from prime_rl.trainer.models.afmoe import AfmoeForCausalLM as PrimeRLAfmoeForCausalLM
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.utils.utils import default_dtype
from tests.unit.train.models.afmoe_hf_modeling.configuration_afmoe import AfmoeConfig
from tests.unit.train.models.afmoe_hf_modeling.modeling_afmoe import (
AfmoeForCausalLM as HFAfmoeForCausalLM,
)
pytestmark = [pytest.mark.gpu, pytest.mark.skip(reason="HF afmoe model does not support flash attention 2")]
def get_model_pairs():
hf_config = AfmoeConfig(
architectures=["AfmoeForCausalLM"],
attention_dropout=0.0,
global_attn_every_n_layers=2,
head_dim=64,
hidden_act="silu",
hidden_size=256,
initializer_range=0.02,
intermediate_size=512,
layer_types=[
"sliding_attention",
"full_attention",
"sliding_attention",
"full_attention",
],
load_balance_coeff=0.001,
max_position_embeddings=512,
moe_intermediate_size=128,
mup_enabled=True,
n_group=1,
num_attention_heads=4,
num_dense_layers=2,
num_expert_groups=1,
num_experts=4,
num_experts_per_tok=2,
num_hidden_layers=4,
num_key_value_heads=2,
num_limited_groups=1,
num_shared_experts=1,
rms_norm_eps=1e-5,
rope_scaling=None,
rope_theta=10000.0,
route_norm=True,
route_scale=2.826,
score_func="sigmoid",
sliding_window=128,
tie_word_embeddings=False,
topk_group=1,
use_cache=True,
use_grouped_mm=False,
vocab_size=256,
)
hf_config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFAfmoeForCausalLM._from_config(hf_config)
prime_model = PrimeRLAfmoeForCausalLM._from_config(hf_config)
with torch.no_grad():
state_dict = hf_model.state_dict()
prime_state_keys = prime_model.state_dict().keys()
prime_model.convert_to_prime(state_dict)
prime_model.load_state_dict(state_dict)
inject_prime_lm_head(prime_model, chunk_size=None)
assert set(prime_state_keys) - set(state_dict.keys()) == set()
return hf_model, prime_model
class _IdentityMLP(nn.Identity):
def forward(self, x, **kwargs):
return super().forward(x)
def test_afmoe_attn_only() -> None:
hf_model, prime_model = get_model_pairs()
for layer in hf_model.model.layers:
layer.mlp = nn.Identity()
for layer in prime_model.model.layers:
layer.mlp = _IdentityMLP()
with torch.device("cuda"), default_dtype(torch.float32):
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
position_ids = torch.arange(1, 101).unsqueeze(0)
hf_output = hf_model(input_ids, position_ids=position_ids)
prime_output = prime_model(
input_ids,
position_ids=position_ids,
seq_lens=torch.tensor([input_ids.shape[1]], device="cuda"),
)
hf_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
def test_afmoe_mlp_only() -> None:
hf_model, prime_model = get_model_pairs()
# HF AfmoeAttention.forward() returns a single tensor
def identity_attn_hf(hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
return hidden_states
# PrimeRL attention returns a tuple (output, attn_weights)
def identity_attn_prime(hidden_states: torch.Tensor, *args, **kwargs) -> tuple[torch.Tensor, None]:
return hidden_states, None
for layer in hf_model.model.layers:
layer.self_attn.forward = identity_attn_hf
for layer in prime_model.model.layers:
layer.self_attn.forward = identity_attn_prime
with torch.device("cuda"), default_dtype(torch.float32):
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
position_ids = torch.arange(1, 101).unsqueeze(0)
hf_output = hf_model(input_ids, position_ids=position_ids)
prime_output = prime_model(
input_ids,
position_ids=position_ids,
seq_lens=torch.tensor([input_ids.shape[1]], device="cuda"),
)
hf_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
def test_afmoe() -> None:
hf_model, prime_model = get_model_pairs()
with torch.device("cuda"), default_dtype(torch.float32):
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
position_ids = torch.arange(1, 101).unsqueeze(0)
hf_output = hf_model(input_ids, position_ids=position_ids)
prime_output = prime_model(
input_ids,
position_ids=position_ids,
seq_lens=torch.tensor([input_ids.shape[1]], device="cuda"),
)
hf_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
with torch.device("cuda"), default_dtype(torch.float32):
hf_from_prime_model = HFAfmoeForCausalLM._from_config(hf_model.config)
converted_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
hf_from_prime_model.load_state_dict(converted_state_dict)
hf_from_prime_output = hf_from_prime_model(input_ids, position_ids=position_ids)
hf_from_prime_output.logits.sum().backward()
logits_diff = hf_from_prime_output.logits - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
grad_diff = hf_from_prime_model.model.embed_tokens.weight.grad - hf_model.model.embed_tokens.weight.grad
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
if __name__ == "__main__":
test_afmoe()
+2 -3
View File
@@ -5,9 +5,8 @@ import torch.nn.functional as F
from prime_rl.configs.trainer import ModelConfig
from prime_rl.trainer.distributed.token_dispatcher import LocalTokenDispatcher
from prime_rl.trainer.model import compute_expert_load_stats, is_tt_moe_model
from prime_rl.trainer.models.deepseek_v4.moe import DeepseekV4Experts
from prime_rl.trainer.models.fusions import fuse_gate_up_projections
from prime_rl.trainer.models.layers.activations import ActivationDispatch
from prime_rl.trainer.models.layers.activations import ActivationDispatch, ClampedSilu
from prime_rl.trainer.models.layers.expert_compute import BF16ExpertCompute, GroupedGemmExpertCompute
from prime_rl.trainer.models.layers.mlp import FeedForward
from prime_rl.trainer.models.layers.moe import (
@@ -69,7 +68,7 @@ def test_unselected_moe_uses_bf16_without_loading_compute_backend(selection, com
pytest.param(GroupedExperts, {"activation": "relu2"}, True, "standard SwiGLU", id="relu2"),
pytest.param(GroupedExperts, {"activation": "clamped_swiglu"}, True, "standard SwiGLU", id="clamped-swiglu"),
pytest.param(GroupedExperts, {"bias": True}, True, "bias-free", id="bias"),
pytest.param(DeepseekV4Experts, {"swiglu_limit": 10.0}, True, "standard SwiGLU", id="deepseek-v4"),
pytest.param(GroupedExperts, {"activation": ClampedSilu(10.0)}, True, "standard SwiGLU", id="deepseek-v4"),
],
)
def test_set_compute_validates_sonic_expert_structure(expert_cls, kwargs, fused, error):
+1 -90
View File
@@ -5,7 +5,7 @@ from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
from prime_rl.trainer.models import cast_float_and_contiguous
from prime_rl.trainer.models.layers.lm_head import FusedOutputLinear, VanillaOutputLinear, inject_prime_lm_head
from prime_rl.trainer.models.qwen3 import Qwen3ForCausalLM
from prime_rl.trainer.rl.loss import compute_entropy, selective_log_softmax, shift_tensor_left, shift_tensor_right
from prime_rl.trainer.rl.loss import compute_entropy, shift_tensor_left, shift_tensor_right
from prime_rl.utils.utils import default_dtype
@@ -160,95 +160,6 @@ def test_fused_vs_vanilla_integration():
torch.testing.assert_close(fused_out["entropy"], vanilla_entropy, rtol=1e-3, atol=1e-4)
@pytest.mark.gpu
@pytest.mark.skip(reason="Produces NaNs in bf16 with FA3; needs investigation")
def test_full_model_fused_vs_vanilla():
"""Full model integration test comparing fused vs vanilla LM head across multiple training steps."""
torch.manual_seed(123)
# Create tiny Qwen3 model for fast testing
config = Qwen3Config(
hidden_size=128,
intermediate_size=256,
max_position_embeddings=512,
num_attention_heads=4,
num_key_value_heads=2,
head_dim=32,
num_hidden_layers=2,
vocab_size=1000,
rms_norm_eps=1e-5,
rope_theta=10000.0,
attention_bias=False,
)
with torch.device("cuda"), default_dtype(torch.bfloat16):
# Create two identical models
model_vanilla = Qwen3ForCausalLM._from_config(config)
model_fused = Qwen3ForCausalLM._from_config(config)
# Share weights between models
model_fused.load_state_dict(model_vanilla.state_dict())
# Wrap with different LM heads
inject_prime_lm_head(model_vanilla, chunk_size=None) # Vanilla
inject_prime_lm_head(model_fused, chunk_size=32) # Fused with chunking
# Setup optimizers
optimizer_vanilla = torch.optim.AdamW(model_vanilla.parameters(), lr=1e-4)
optimizer_fused = torch.optim.AdamW(model_fused.parameters(), lr=1e-4)
# Run a few training steps
num_steps = 3
batch_size, seq_len = 2, 64
temp_value = 1.5
for step in range(num_steps):
# Generate random batch
with torch.device("cuda"):
labels = torch.randint(0, config.vocab_size, (batch_size, seq_len))
position_ids = torch.arange(seq_len).unsqueeze(0).expand(batch_size, -1)
temperature = torch.full((batch_size, seq_len), temp_value, dtype=torch.float32, device="cuda")
seq_lens = torch.tensor([seq_len])
# Vanilla forward (returns logits, compute logprobs/entropy using RL train functions)
optimizer_vanilla.zero_grad()
out_vanilla = cast_float_and_contiguous(
model_vanilla(labels, position_ids, labels=labels, temperature=temperature, seq_lens=seq_lens)
)
if out_vanilla.get("logprobs") is None:
assert out_vanilla.get("logits") is not None
logits = out_vanilla["logits"] / temp_value
out_vanilla["logprobs"] = selective_log_softmax(logits, labels)
out_vanilla["entropy"] = compute_entropy(logits)
loss_vanilla = -out_vanilla["logprobs"].mean()
loss_vanilla.backward()
optimizer_vanilla.step()
# Fused forward (returns logprobs and entropy directly)
optimizer_fused.zero_grad()
out_fused = cast_float_and_contiguous(
model_fused(labels, position_ids, labels=labels, temperature=temperature, seq_lens=seq_lens)
)
if out_fused.get("logprobs") is None:
assert out_fused.get("logits") is not None
logits = out_fused["logits"] / temp_value
out_fused["logprobs"] = selective_log_softmax(logits, labels)
out_fused["entropy"] = compute_entropy(logits)
loss_fused = -out_fused["logprobs"].mean()
loss_fused.backward()
optimizer_fused.step()
# Compare outputs (should be very close since models started identical)
torch.testing.assert_close(out_fused["logprobs"], out_vanilla["logprobs"], rtol=1e-3, atol=1e-4)
torch.testing.assert_close(out_fused["entropy"], out_vanilla["entropy"], rtol=1e-3, atol=1e-4)
torch.testing.assert_close(loss_fused, loss_vanilla, rtol=1e-3, atol=1e-4)
# After training, weights should still be close (optimizer steps should be similar)
for (name_v, param_v), (name_f, param_f) in zip(model_vanilla.named_parameters(), model_fused.named_parameters()):
if "lm_head" not in name_v: # Compare non-lm_head params
torch.testing.assert_close(param_f, param_v, rtol=1e-3, atol=1e-4)
def test_fused_lm_head_correct_shift():
"""
End-to-end test that the fused LM head with shifted labels, after shift_tensor_right,
+5 -4
View File
@@ -19,7 +19,7 @@ def setup_fake_dataloader(config: FakeDataConfig, non_dp_size: int = 1):
seed=config.seed,
non_dp_size=non_dp_size,
)
return dataset, setup_dataloader(dataset, config)
return dataset, setup_dataloader(dataset, config, cp=1)
def test_fake_dataset_single_rank_state():
@@ -88,7 +88,7 @@ def test_fake_dataset_single_rank_resume():
# Reload dataloader
state_dict = dataloader.state_dict()
dataloader = setup_dataloader(dataset, config)
dataloader = setup_dataloader(dataset, config, cp=1)
dataloader.load_state_dict(state_dict)
dataiter = iter(dataloader)
@@ -110,7 +110,8 @@ def test_fake_dataset_single_rank_state_with_packing():
micro_batch = next(dataiter)
num_packed_examples = len(micro_batch["input_ids"][micro_batch["loss_mask"]].unique())
step += num_packed_examples
assert micro_batch["input_ids"].shape == (1, 128)
assert micro_batch["input_ids"].shape[0] == 1
assert micro_batch["input_ids"].shape[1] <= 128
assert micro_batch["seq_lens"].sum() == micro_batch["input_ids"].shape[1]
worker_state = dataloader.state_dict()["_snapshot"]["_worker_snapshots"]["worker_0"]["dataset_state"]
pending_sample = worker_state.get("pending_sample")
@@ -186,7 +187,7 @@ def test_dataloader_shards_across_ranks_and_workers(
seq_len=config.seq_len,
non_dp_size=non_dp_size,
)
return setup_dataloader(dataset, config)
return setup_dataloader(dataset, config, cp=1)
dataloader = setup_epoch_dataloader()
dataiter = iter(dataloader)

Some files were not shown because too many files have changed in this diff Show More