Compare commits

...
Author SHA1 Message Date
Mika SenghaasandGitHub 7ad1bb9123 feat: chunk and seal trace streams (#3465)
## Summary

- Each trace stream (`traces/stream`, `traces/annotations/<producer>`)
is now a directory of numbered chunks. `ChunkedJsonl`
(`monitors/file/traces/chunks.py`) rolls at `monitors.file.chunk_bytes`
(default 5 GiB; a line never spans chunks) and, with
`monitors.file.compress` (default on), seals each full chunk with zstd
in a background thread. The live chunk stays plain text; a finished run
seals its live chunk too. A relaunch resumes the live chunk it finds and
seals anything a crash left mid-seal.
- Sealed chunks use zstd's seekable format (`pyzstd`, 4 MiB frames), so
a seek costs one frame, not the chunk. `zstd -dcf stream/* | jq` reads a
whole stream, sealed and live alike.
- Index rows carry `chunk` beside `offset`; the dashboard resolves both
through `open_chunk` (plain or sealed) for episodes and annotation
records, keys its caches and etags on the index size, and parses chunked
streams for the series view through the index, one chunk open at a time.
Annotation readers rely on the producer's index (the file monitor always
writes one).
- `monitors.file.float_decimals` (default 4, `None` for every digit)
sets the precision of per-token float streams in both the episode
records (`to_record(float_decimals=...)`) and the trainer's annotation
streams. Trainer streams also hold `null` outside the loss mask - the
fold keeps sampled tokens only, so nothing a reader sees changes, and
runs of nulls seal to nothing. The trainer finalizes its monitors on
exit so its live chunk seals.
- Submodule bump to verifiers main `cfc7c474`
(PrimeIntellect-ai/verifiers#2495, merged): JSON records round per-token
floats to `to_record(float_decimals=...)`, 4 by default. The msgpack
wire keeps full precision, so the importance ratio is unaffected.

## Measurements

Replayed the 100-step, 33,342-episode scaleswe baseline
(`ipo-baseline-rollouts-steps1-100`, 15.17 GB as one `stream.jsonl`)
through the new writer with 5 GiB chunks:

| | raw | 4 dp | on disk (sealed) | total |
|---|---|---|---|---|
| 10 steps (5,696 episodes) | 1.06 GB | 0.89 GB | **0.10 GB** | 11.0x |
| 100 steps (33,342 episodes) | 15.17 GB | 12.66 GB | **1.38 GB** |
11.0x |
| 1000 steps (extrapolated from steps 11-100: 307 episodes, 157 MB raw
per step) | 156 GB | 130 GB | **14.2 GB** | 11.0x |

Rounding contributes 1.20x on the plain bytes and lifts zstd from 6.9x
to 9.2x, since mantissa digits were the incompressible part. Writing 33K
episodes took 81.8 s with sealing vs 80.4 s plain: sealing runs beside
the writer, not in front of it. The final 2.7 GB live chunk sealed in 4
s.

Dashboard against the sealed run (same box, 5 GiB chunks): open one
episode 5.8 ms cold / 4.0 ms warm vs 3.9 / 3.4 ms plain; table page 17
ms cold (index only, unchanged); series view full parse of all 33K
records 35.7 s sealed vs 39.7 s plain (orjson-bound, cached and
persisted after the first pass). Browser check: traces table renders,
episode viewer opens from a sealed chunk, no console errors. Unit suite:
571 passed.

## Breaking

- On-disk trace layout: `traces/stream.jsonl` →
`traces/stream/<NNNNN>.jsonl[.zst]`,
`traces/annotations/<producer>.jsonl` →
`traces/annotations/<producer>/<NNNNN>.jsonl[.zst]`; index rows gain
`chunk` and their `offset` is chunk-relative. Read a stream with `zstd
-dcf <stream dir>/* | jq`. The dashboard reads only the new layout.
- Per-token floats in records (`logprobs`, `reference_logprobs`,
`advantages`, trainer `trainer_logprobs`/`entropies`) are written with 4
decimals by default; set `monitors.file.float_decimals = None`
(orchestrator and trainer) to keep full precision.
- New dependency `pyzstd`.


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking on-disk trace layout and default float precision affect
observability and external readers; dashboard and monitor paths are
heavily touched but training wire precision is unchanged per PR notes.
> 
> **Overview**
> **Trace on-disk layout is now chunked directories** instead of single
`stream.jsonl` / `annotations/<producer>.jsonl` files. The file monitor
writes through `ChunkedJsonl`: rolls at `monitors.file.chunk_bytes`
(default 5 GiB), optionally seals full chunks with seekable zstd in
background threads (`monitors.file.compress`, default on), and seals the
live chunk on `finalize()` (trainer now calls
`asyncio.run(monitors.finalize())` at shutdown). Index rows add
**`chunk`** beside chunk-relative **`offset`**.
> 
> **`monitors.file.float_decimals`** (default 4) rounds per-token floats
in episode `to_record(...)` and trainer annotation streams; trainer
streams also emit **`null`** outside the loss mask for better
compression without changing what readers fold onto traces.
> 
> The **dashboard** detects chunked streams via the index, reads
episodes and annotations with `open_chunk` (plain or `.zst`), versions
caches/etags on index size, and builds series summaries by walking the
index one chunk at a time. **Breaking:** tools and scripts must use
`zstd -dcf <stream-dir>/*` and per-producer chunk dirs under
`annotations/`. New dependency **`pyzstd`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
62a6893f75cbc770cbad06fd65d640aec13f058b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-02 11:37:29 -07:00
5990b1b9ba feat: add deepseek v4 (step 0) (#3325)
Initial commit for adding deepseek v4 flash. 

This architecture brings in multiple new ingredients and will require
multiple commits for a fully mature implementation to be ready. The
present PR should be regarded as the very rough first draft, focused on
unblocking basic SFT runs.

Other notes:
* I am attempting to isolate most changes to live under
`trainer/models/deepseek_v4/` to keep the PR clean and easier to iterate
on later without entangling this code with other `prime-rl` changes.
E.g. the `deepseek_v4/attention.py` impls may eventually get hoisted to
`attn.py`
* Does not yet implement methods needed for RL weight broadcasting
(blocking evals as well)
* We will incrementally pull in kernels to replace the current
pure-eager torch impl

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-02 11:34:01 -04:00
ffb845c13c fix(trainer): zero-index position_ids fallback in LM-head wrapper (#3466)
Use the standard zero-indexing convention for `position_ids` in patched
LM head forward, (`_patch_model_forward`), rather than one-indexing.

A uniform shift is mathematically invisible to RoPE, which sees only
query-key angle differences, but it is wrong for attention that keys off
absolute token indices (as is important for deepseek v4 where
compression boundaries are tied to absolute positions).

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-02 10:05:32 -04:00
Mika SenghaasandGitHub 421198cb93 feat: constant trainer batch size (#3463) 2026-09-01 20:22:40 -07:00
e3fdadedc5 feat: trainer trace annotations + dashboard overlays (#3444)
## Summary

Every rollout episode is written to disk exactly once, as an
arrival-ordered stream, and everything learned about it afterwards is an
append-only annotation folded back on read. The trainer's recomputed
per-token streams ride that mechanism, and the trace viewer renders them
as overlays (entropy, the trainer↔sampling mismatch, the IPO stable
mask) next to the loss mask.

**Layout** (replaces
`rollouts/step_N/{train,eval}/{all,effective}/traces.jsonl`):

```
<run_dir>/monitors/file/metrics.jsonl                              # every metric row, tagged by producer
<run_dir>/monitors/file/traces/stream.jsonl                        # every episode, appended as it arrives
<run_dir>/monitors/file/traces/stream.index.jsonl                  # one compact row per episode, with its byte offset
<run_dir>/monitors/file/traces/annotations/<producer>.jsonl        # trace updates: orch ship-time facts, trainer per-token streams
<run_dir>/monitors/file/traces/annotations/<producer>.index.jsonl  # each update's scalars and where its record sits
```

Everything the file monitor dumps lives under its own directory, and
nothing is written there when the monitor is off. The traces and
everything written about them sit under `traces/`, and every index is
named for the stream it indexes and sits beside it. Each file is
append-only with exactly one writer, so there are no locks and live
tailing keeps working.

**Steps are events, not locations.** A trace is dispatched at one step,
arrives at another and is trained at a third, so a step directory could
only ever be honest about one of them — and picking arrival forced the
arrival step onto the batch wire just so the trainer could find the
right directory. Instead each step is stamped as its own event on the
record. `orchestrator/annotations.py` owns both events: `stamp_arrival`
puts `info.kind` plus `info.dispatch` / `info.arrival` (`{step, time}`)
on a trace as its episode lands, and `stamp_ship` produces the update
carrying `info.effective` and `info.ship` — the orchestrator step whose
batch shipped the cohort, or for eval the policy version the epoch
measured. Staleness is `ship.step - dispatch.step`; the trace viewer
shows all three for a train trace, and an eval trace shows the step it
measured instead (it never ships in a batch and never goes stale).

- **Annotations**: one record format and one fold, in
`prime_rl.monitors.trace_updates`, used by the file monitor, the trainer
writer and the dashboard. An update names a trace and carries an `info`
dict merged into the trace's own plus per-branch token streams,
full-length over the branch's token prefix (nulls mark unknown
positions) so folding never depends on the producer's loss mask.
- **Indexes**: the file monitor summarises each episode into
`stream.index.jsonl` as it writes it, and each update's scalars into the
producer's `.index.jsonl`, both with byte offsets. A reader browses the
indexes and seeks for the one episode it opens, so the cost of listing a
run stops scaling with the token streams — which outweigh the episodes
themselves.
- **Branch identity on the batch wire**: `TrainingSample` gains
`trace_id` / `branch_index`; `MicroBatch` carries them per sequence,
parallel to `sequence_lengths`, preserved through packing/padding and
nulled on dummy micro batches.
- **Trainer**: accumulates one update per trained sequence per forward
(packing-boundary first value and non-finite values are null), gathers
them to rank 0 at the end of each step, and logs them through its own
file monitor — the same monitor it already logs metrics through — rather
than writing to disk behind it. Always on; the token-export path is
gone.
- **Dashboard**: same HTTP API shape. The traces tab opens on the whole
stream — newest first, paged as you scroll, with a histogram of episodes
finished per interval you can click to narrow to a moment — and switches
to step mode for the cohort that shipped at one step (arrow keys walk
the step bar). Episode reads fold every annotation onto the record, so
the overlays work in both views. Token signals are Advantage, Entropy,
Mismatch (`r − log r − 1`, computed client-side from the trainer and
sampling logprobs), Stable mask (`|Δp|` vs the run's IPO `eps`), Loss
Mask and Content Mask; an overlay the open episode cannot colour is
disabled in the selector and names the input it is missing, rather than
silently painting nothing. In a token overlay the reasoning renders
inside the token spans that already cover it instead of in its own box.
- Verifiers gained only the two per-token node fields the records land
on (`MessageNode.trainer_logprobs` / `entropies`, with matching `Branch`
spread properties) —
[verifiers#2481](https://github.com/PrimeIntellect-ai/verifiers/pull/2481),
merged; `deps/verifiers` tracks verifiers main.

## Verification

Reverse-text, 4 steps: 645 episodes on one stream, 496 annotated by both
producers, 55,694 masked tokens folded with every node's compact arrays
equal to its masked-token count. Mean KL mismatch 0.0014, mean entropy
0.61. Staleness came out as 336 traces shipped at their dispatch step
and 160 a step later — the lag the old layout could not express. Re-run
end to end on a 20-step reverse-text run after the layout change.
SFT-online-eval and verifiers `uv run eval` run shapes checked through
the real API with a FastAPI test client; the dashboard's browser smoke
suite covers the stream/step views, the histogram, the step bar and
every token signal.

## Breaking

- The `rollouts/` trace tree is gone. Episodes now live in one
`monitors/file/traces/stream.jsonl` stream, written once at arrival,
with the effective cohort expressed as
`monitors/file/traces/annotations/<producer>.jsonl` records instead of
duplicate episode copies (per-token advantages and the scalar advantage
now arrive via annotations). The dashboard reads only the new layout;
runs recorded before this change need the old dashboard.
- `metrics.jsonl` moves from the run root to
`monitors/file/metrics.jsonl`.
- `trainer.enable_token_export` is removed and `token_exports/` is no
longer written; the trainer's per-token streams are always logged as
annotations.
- The filesystem batch transport writes packed micro batches to
`batches/step_<n>/rank_<r>.bin` (previously `rollouts/step_<n>/`).

## 20-step GLM-Air ScaleSWE comparison

- The baseline ran `main`; the comparison ran this PR. The code change
was the only behavioral difference. Run names, output directories, and
conversion cache paths were isolated.
- Trainer step 1: before 874.0 s; after 822.0 s (-5.9%).
- Trainer steps 1–20: before 3,179.2 s; after 2,995.2 s (-5.8%).
- Steady trainer steps 2–20: before 121.3 s mean / 120.0 s median; after
114.4 s mean / 99.0 s median. The after run was 5.7% faster by mean step
time.
- Trace data at each run's trainer step-20 cutoff: before 3.516 GB
across duplicated `all` and `effective` traces; after 3.476 GB across
the arrival stream plus orchestrator and trainer annotations. The after
layout was 1.1% smaller despite 864 MB of per-token trainer logprob and
entropy annotations.
- Dashboard on the after run at step 20: a 128-episode page took 15.7
ms, a 2.22 MB annotated episode took 42.7 ms, and its timeline took 9.7
ms.

The after job was cancelled after step 24 at the researcher's request.
The baseline completed trainer step 20.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Large observability and on-disk contract change (breaking paths and
removed `trainer.enable_token_export`); training/orchestration logic is
mostly additive but any tool still expecting `rollouts/` or root
`metrics.jsonl` will break.
> 
> **Overview**
> Replaces the per-step `rollouts/.../traces.jsonl` tree with a **file
monitor layout** under `monitors/file/`: metrics at `metrics.jsonl`,
episodes in one append-only `traces/stream.jsonl` plus sidecar indexes,
and **append-only trace annotations** per producer (orchestrator
ship-time facts, trainer per-token streams).
> 
> **Orchestrator/evals** stamp arrival metadata on episodes at log time
and log **effective cohort** membership, advantages, and ship step via
`log_annotations` instead of duplicating episode files. **Trainer**
drops `enable_token_export` / `token_exports/`; per-token logprobs and
entropies always go through the same annotation path. **Dashboard**
reads the new layout: stream vs step cohort views, paged
`/api/runs/.../episodes`, arrival histogram, and token overlays
(entropy, mismatch KL, IPO stable mask, masks) folded from annotations.
> 
> Docs, skills, configs, and `run_single_benchmark.py` are updated for
the new paths and for skipping non-step metric rows. Filesystem batch
transport writes to `batches/step_*` instead of under `rollouts/`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
16bf663b7805ecfe7d993ff6b6d34c8b7bc47308. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-01 17:17:54 -07:00
Mika SenghaasandGitHub 84e7312f33 feat: top-p/top-k train sampling with native sampling replay (#3431)
## Summary

- Add typed top-p and top-k settings for policy rollouts.
- Capture vLLM 0.28 sampling masks and replay the truncated distribution
in the trainer.
- Bound sampling masks with a default `top_k = 512` when truncation is
enabled.
- Use Model Runner V2 for router replay on standard deployments.
- Support router replay and sampling replay together on Model Runner V2.
- Keep NIXL P/D router replay on V1 and reject the unsupported combined
P/D mode.
- Use `SamplingMask` and `sampling_mask` across Renderers, Verifiers,
and prime-rl.
- Pin merged Renderers and require its published `0.1.12.dev2` build.
- Pin Verifiers to the latest `main` after its sampling-mask merge.
- Document standalone capture, the NIXL replay matrix, and sampling-mask
layout examples.
- Shard sampling masks with labels for multimodal context-parallel
training.
- Reject mixed enabled and disabled top-k settings across live-policy
train sources.

This builds on vLLM 0.28.0 from #3430. It supersedes #3235. The capture
side uses vLLM's native sampling-mask support from
[vllm#49577](https://github.com/vllm-project/vllm/pull/49577).

## Usage

```toml
[orchestrator.train.sampling]
top_p = 0.95
top_k = 20
```

There are no replay flags for sampling replay. Truncated policy sampling
enables mask capture and trainer replay automatically.

Set `trainer.enable_router_replay = true` to combine router replay with
sampling replay. Standard deployments use Model Runner V2 for both
captures. Disaggregated NIXL deployments keep router replay on V1 and
cannot combine both replay modes.

## Behavior

- Policy sampling with `top_p < 1` or `top_k` gets a bounded sampling
mask.
- Truncation without an explicit `top_k` defaults to 512.
- Different truncating sources can use different top-p values; each gets
a positive top-k.
- Mixed top-k capture modes across live-policy sources are rejected.
- Values above 512 are rejected to bound trainer memory.
- The trainer renormalizes each sampled token over the same mask as
inference.
- Frozen-source environments do not require masks.
- `opd` and `opsd` reject truncated policy sampling because their
reference scores use the full vocabulary.
- vLLM rejects sampling-mask requests with `temperature <= 0` or without
an effective `top_k > 0`.

## Runs

GLM-4.5-Air on `scaleswe` on 4 nodes

| Run | Runner | Router replay | Top-p | Effective top-k | Nodes |
| --- | --- | --- | --- | --- | --- |
| `glm-air-v1-baseline` | V1 | Off | 1.0 | Off | 6 |
| `glm-air-v2-baseline` | V2 | Off | 1.0 | Off | 6 |
| `glm-air-v2-router-replay` | V2 | On | 1.0 | Off | 6 |
| `glm-air-v2-top-p-0.95` | V2 | Off | 0.95 | 512 | 6 |
| `glm-air-v2-router-replay-top-p-0.95` | V2 | On | 0.95 | 512 | 6 |

<img width="279" height="238" alt="Screenshot 2026-09-01 at 3 45 20 PM"
src="https://github.com/user-attachments/assets/bbbf5334-4b06-4573-9232-80d9207a97e6"
/>

<img width="286" height="226" alt="Screenshot 2026-09-01 at 3 46 03 PM"
src="https://github.com/user-attachments/assets/8d048fb1-3e2a-4484-a437-8084d845d47e"
/>

<img width="285" height="238" alt="Screenshot 2026-09-01 at 3 45 39 PM"
src="https://github.com/user-attachments/assets/ca5c21c7-6355-497f-a553-adade238dc1a"
/>

Sampling replay leads to
- no reduction in step 0 KL mismatch
- more stable KL mismatch in conjunction with router replay
- more stable entropy (not rising)
- slower step time (follow-up perf investigation TBD)

## Verification

- `uv run pytest -q tests/unit/test_configs.py -k 'policy_sources'`: 2
passed.
- `uv run pytest -q tests/unit/test_configs.py -k 'not
test_load_configs'`: 69 passed and 67 deselected.
- Pre-commit checks passed for the changed config and test files.

- `uv run pytest tests/unit/train/rl/test_fused_lm_head.py
tests/unit/train/rl/test_loss.py -q`: 19 passed and 1 skipped after the
context-parallel fix.

- `uv run pytest
tests/unit/test_configs.py::test_combined_replay_uses_v2_runner -q`:
passed after the documentation review.

- `uv sync --all-extras`: passed with merged Renderers and Verifiers
dependencies.
- `uv run pytest tests/unit/orchestrator tests/unit/inference
tests/unit/train/rl/test_loss.py
tests/unit/train/rl/test_fused_lm_head.py
--ignore=tests/unit/orchestrator/test_qwen3_vl_e2e.py -q`: 108 passed
and 1 skipped.
- The excluded Qwen3-VL test has an existing fake-response fixture
mismatch.
- `uv run rl @ examples/basic/reverse-text/rl.toml --max-steps 5
--orchestrator.train.sampling.top-p 0.95`: completed five trainer and
orchestrator steps on the final dependency chain.
- The end-to-end run used Model Runner V2, effective `top_k = 512`, and
sampling-mask capture. Final mismatch KL was 0.0035 with no rollout
errors.
- Renderers: `uv run pytest tests/test_client.py -q`: 21 passed and 5
skipped. Ruff and format checks pass.
- Latest Verifiers main: `uv run pytest
deps/verifiers/tests/v1/test_graph.py
deps/verifiers/tests/v1/test_trace.py -q`: 21 passed. Ruff, format,
type, and pre-commit checks pass.
- Reverse-text baseline, top-p 0.95, and top-p 0.95 plus top-k 20 runs
completed with 100% sampling-mask coverage.

W&B:
`reverse-text/reverse-text-native-replay-{baseline,topp095,topp095-topk20}`.

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





<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Changes core RL logprob/importance-ratio math and vLLM runner
selection; misconfiguration or missing masks can bias training or fail
at runtime, though validation and runtime checks aim to catch
incompatible modes.
> 
> **Overview**
> Adds **sampling replay** so policy rollouts with `top_p < 1` or
`top_k` stay aligned with trainer importance ratios: vLLM 0.28 returns
per-token sampling masks (`enable_return_sampling_mask` /
`--return-sampling-mask`), and the trainer renormalizes logprobs over
the same mask instead of the full vocabulary.
> 
> **Config & orchestration:** `TrainSamplingConfig` gains typed `top_p`
and `top_k` (truncation via `extra_body` is rejected). The `rl`
entrypoint auto-enables mask capture when policy sampling truncates;
unbounded truncation defaults `top_k = 512`, values above 512 are
rejected, `temperature = 0` and `opd`/`opsd` are blocked. Policy train
sources must agree on top-k capture mode (engine-wide). **Inference:**
new `enable_return_sampling_mask`; vLLM env setup prefers **V2** for
sampling capture and for router replay on standard deployments, while
**disaggregated NIXL P/D** keeps routed-expert capture on V1 and
**rejects** router + sampling replay together.
> 
> **Data path:** `SamplingMask` on `TrainingSample` / `MicroBatch`,
encoding in trajectories, packing/padding in the trainer batch builder,
and a hard error in `TrainSink` if truncated rollouts lack masks.
**Trainer:** masks flow through CP sharding; fused `lm_head` and
vanilla-path `selective_log_softmax_with_sampling_mask` compute
mask-renormalized logprobs (Gemma softcap heads explicitly unsupported).
Docs cover sampling replay; `renderers` is bumped for mask support in
the rollout stack.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
cee517e2266a2b819765612ccf3a10ba8801a23e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-01 15:47:54 -07:00
Mika SenghaasandGitHub fe325ac460 chore: bump verifiers (#3460)
## Summary

- advance the `deps/verifiers` submodule from `e2103d6` to `d4a2177`
- include merged Bash and RLM context compaction from verifiers #2454
and #2459
- pick up nano-rlm compaction commit `4ef3438` through the default RLM
harness pin
- refresh `uv.lock` for verifiers' `aiohttp>=3.14.1` requirement
- migrate three RLM examples to `compaction.summarize_at_tokens`; use
the former range's `98_304` midpoint
- include the optional ACP semantic-edge and shared harness utility
changes already on verifiers `main`

Companions: [verifiers
#2454](https://github.com/PrimeIntellect-ai/verifiers/pull/2454),
[verifiers
#2459](https://github.com/PrimeIntellect-ai/verifiers/pull/2459), and
[nano-rlm #147](https://github.com/PrimeIntellect-ai/nano-rlm/pull/147).

## Breaking

- RLM harness configs must move `summarize_at_tokens` to
`compaction.summarize_at_tokens`.
- Leave `compaction` unset to disable proactive and reactive compaction.

## Verification

- `git diff --check`
- `uv lock`
- `uv lock --check`
- `uv run pytest -q tests/unit/test_configs.py` — 133 passed
- `git submodule status deps/verifiers` —
`d4a217794fc0bfd70369a8230e56653c193da8ce`
- verified that `d4a2177` descends from the previous `e2103d6` pin

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Submodule bump plus a breaking harness config shape affects all RLM
runs still using the old `summarize_at_tokens` field; example migrations
are mechanical but custom configs must be updated.
> 
> **Overview**
> Advances the **`deps/verifiers`** submodule to pick up merged Bash/RLM
**context compaction** (and related harness defaults), with
**`uv.lock`** refreshed so **`aiohttp`** meets the new **`>=3.14.1`**
floor.
> 
> **Breaking for RLM harness TOML:** flat
**`env.agent.harness.summarize_at_tokens`** is replaced by
**`env.agent.harness.compaction.summarize_at_tokens`**. The three
advanced examples (**`glm-4.5-air/search`**, **`glm-4.5-air/terminal`**,
**`nemotron-3-super/swe`**) are updated accordingly—train sources that
used a two-threshold list **`[65536, 131072]`** now use a single
**`98304`** threshold; eval sources keep **`98304`** but under the
nested **`compaction`** key.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7429aba97da77a30db191432d5295827c64ae621. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-01 11:46:35 -07:00
samsjaandGitHub 0f22eeb862 feat(evals): add resumable standalone runs (#3413)
## Summary

- add top-level `[ckpt]` and `[resume]` support to standalone `uv run
evals`
- write atomic cursor checkpoints at
`<output_dir>/checkpoints/step_N/evals/progress.pt`, where N is the
durable eval-source task cursor
- store only the cursor in eval progress checkpoints; generated episode
records are not copied into checkpoint payloads
- resume with `--resume`, `--resume.step N`, or `--resume.dir
path/to/checkpoints/step_N` by skipping the durable cursor prefix
- retry partial groups and out-of-order completions beyond the durable
cursor
- size resumed eval batches to the remaining queued task suffix
- reject checkpointing in online mode, where progress is coupled to the
trainer weight-broadcast lifecycle
- keep the training start-run skill current with the new workflow
- clarify that checkpoint writes use temp-file replacement so resume
never observes a partial pickle

## Verification

- `uv run pytest tests/unit/evals/test_ckpt.py` — 3 passed
- focused `ruff check` — passed
- focused Python `ruff format --check` — passed
- `git diff --check` — passed

Local note: `uv run evals --help` is currently blocked before CLI
loading by the locked `prime-sandboxes==0.2.39` / `connectrpc==0.11.1`
import mismatch (`connectrpc.client` is missing).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Shared orchestrator types (`Dispatcher`, `EvalSource`, `EvalSink`)
change, but checkpoint/resume logic is gated to standalone evals with
config validation; unit tests cover cursor and I/O semantics.
> 
> **Overview**
> Standalone `uv run evals` can now be made **interruptible** via
optional `[ckpt]` and `[resume]` on `EvalsConfig` (rejected when
`[online]` is set).
> 
> Progress is a **task cursor** over round-robin eval tasks:
`EvalSource` assigns `source_index`, advances the durable cursor only
over a fully completed prefix (`mark_completed`), and on resume skips
tasks below the loaded cursor. `CheckpointManager` writes only
`{"cursor": N}` to `<output_dir>/checkpoints/step_N/evals/progress.pt`
using atomic temp-file replace; saves run every `ckpt.interval`
completed groups in standalone mode.
> 
> The evals loop loads resume state at setup, sizes epochs with
`EvalSink.set_batch_size` from remaining queued tasks, and on each
finished eval group calls `dispatcher.pop_source_index` to drive
checkpointing. Online eval rollout totals use the triggered queue
instead of full env example counts.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d4dc69fac552a55cb6c7c412a0d4e1b194a39c03. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-31 19:31:16 -07:00
JannikStandGitHub 1fbf0b47a4 bugfix: install EFA userspace stack in-place in the runtime stage (#3454)
## Why

`libfabric` needs a newer `libefa.so.1` (symbol version `EFA_1.4`) than
this image's own apt-installed rdma-core provides, so NCCL fails to load
the OFI plugin: `version 'EFA_1.4' not found`.

## What

- The AWS EFA installer upgrades rdma-core system-wide via its own
apt/dpkg step, but running it in a separate build stage and copying out
only `/opt/amazon` left that system-wide upgrade behind — libfabric
ended up paired with the older, separately-apt-installed rdma-core.
- Run the installer directly in the runtime stage instead, so its
rdma-core upgrade lands in place with no copy-forwarding gap.
- Verified locally: before the installer, stock rdma-core
(50.0-2ubuntu0.2); after, upgraded to 61.0-1 system-wide,
`libfabric.so.1` resolves `libefa.so.1` cleanly, and
`libnccl-net-ofi.so` dlopens with zero missing dependencies.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes CUDA image build and RDMA/EFA library versions used for
multi-node NCCL; incorrect pairing could still break distributed
training on EFA hosts, but the change targets a known symbol-version
mismatch.
> 
> **Overview**
> Fixes NCCL OFI plugin load failures (`EFA_1.4` not found) by changing
**how** the CUDA image gets the AWS EFA stack, not by adding new runtime
behavior.
> 
> The dedicated `efa-installer` build stage and `COPY
--from=efa-installer /opt/amazon` are removed. The same AWS
`efa_installer.sh` run (still with `--skip-kmod` and
`--skip-limit-conf`) now executes **in the final runtime image**,
immediately after the base `apt` install of `libibverbs` / `librdmacm`
and related packages. That way the installer’s system-wide rdma-core
upgrades stay in the image libfabric actually runs in, instead of
shipping only `/opt/amazon` from an isolated stage paired with older
distro rdma-core.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6f879a4bf88704c58b5719b1c8635258121ae2de. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-01 02:45:32 +02:00
JannikStandGitHub 799ac26258 bugfix: install libhwloc15 for aws-ofi-nccl in runtime image (#3452)
## Why

NCCL now finds `libnccl-net-ofi.so` but fails to load it:
`libhwloc.so.15: cannot open shared object file`, falling back to
sockets.

## What

- Add `libhwloc15` to the runtime stage's apt install list.
- The EFA installer stage pulls in libhwloc as one of its own
dependencies, but only `/opt/amazon` gets copied forward into the
runtime stage — the shared lib itself never did.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Single-package addition to the Docker runtime image with no
application code or auth/data-path changes.
> 
> **Overview**
> Fixes NCCL failing to load the AWS OFI network plugin
(`libnccl-net-ofi.so`) because **`libhwloc.so.15`** was missing at
runtime, which forced a fallback to sockets.
> 
> The CUDA **runtime** stage now **`apt install`s `libhwloc15`**
alongside the other RDMA/EFA-related packages. The EFA installer stage
already pulled in hwloc as a dependency, but only **`/opt/amazon`** is
copied into the final image—not the distro **`libhwloc`** package—so the
shared library never landed in the runtime filesystem.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a1d18804238afc171a4e8b856e86c24818d2b95d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-01 00:57:11 +02:00
JannikStandGitHub d5b38216a5 bugfix: install prime-kernels extra in Docker build (#3449)
## Why

Trainer crashes with `ModuleNotFoundError: No module named
'prime_kernels'` on startup. `collectives.py` imports it unconditionally
at the top of the file.

## What

- `prime-kernels` is declared and pinned in `pyproject.toml`/`uv.lock`
under its own `kernels` extra, but that extra was never passed to `uv
sync` in `Dockerfile.cuda` — so it resolves but never actually installs.
- Add `--extra kernels` to both `uv sync` calls.
- Add `prime-kernels` to the post-sync version-check so a missing
install fails the build loudly instead of shipping silently.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Docker build-only dependency wiring with no runtime logic changes;
slightly larger images when the kernels extra is enabled.
> 
> **Overview**
> Fixes CUDA Docker images that could start the trainer without
**`prime-kernels`**, causing **`ModuleNotFoundError: No module named
'prime_kernels'`** even though the package is pinned under the
**`kernels`** optional extra.
> 
> Both **`uv sync`** stages in **`Dockerfile.cuda`** now pass **`--extra
kernels`**, so the wheel is actually installed into the venv. The
post-sync **`importlib.metadata`** smoke check also includes
**`prime-kernels`**, so a missing install fails the image build instead
of surfacing only at runtime.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
180ec8e7944f5be98a55a24200959fff882b652d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-01 00:28:16 +02:00
JannikStandGitHub f87ebcc239 improvement(docker): bundle AWS EFA libfabric + aws-ofi-nccl (#3448)
## Summary
- Bundles libfabric + the aws-ofi-nccl NCCL plugin into the image via
AWS's official installer, so NCCL can find the OFI plugin at runtime
instead of silently falling back to sockets
- Inert by default — only takes effect where a deployment's config
points `LD_LIBRARY_PATH` at it

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Docker build-only change that adds optional EFA libraries without
altering default runtime env or application code; main risk is larger
images and relying on the pinned AWS installer URL/version.
> 
> **Overview**
> The CUDA runtime image now **ships the AWS EFA userspace stack**
(libfabric and the **aws-ofi-nccl** NCCL plugin) so multi-node jobs on
EFA-capable hosts can use NCCL’s OFI path instead of silently falling
back to sockets.
> 
> A new **`efa-installer` build stage** on the same Ubuntu 24.04 base as
runtime downloads AWS’s official installer (default **1.47.0**), runs it
with **`--skip-kmod`** and **`--skip-limit-conf`**, and copies
**`/opt/amazon`** into the final image. **`LD_LIBRARY_PATH` is
unchanged** in the Dockerfile—deployments that have EFA on the host are
expected to prepend those libraries when needed; elsewhere the bundle
stays inert.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
007d6d6b8af5e5f567fa94fce5e2b6f06e02d62a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-31 23:41:31 +02:00
Matej SirovatkaandGitHub 866c3e1438 refactor(trainer): make activation checkpointing operator-based (#3419)
## Summary

- Replace method- and attribute-based selective activation checkpointing
with one non-reentrant checkpoint region around each selected
transformer block.
- Keep `mode = "full"` as the default. Full mode retains only mandatory
non-replayable operations and recomputes everything else; selective mode
additionally retains configured expensive operations through the same
Prime-owned policy.
- Allow selective mode to replace its public default targets with
explicit operator names or namespaces. Correctness-required targets
remain active for every selective configuration.
- Register real runtime boundaries for Torch EP/CP collectives, DeepEP
combine, ring attention, sparse MLA, dense/grouped DeepGEMM, MXFP8
transport, and MoE routing telemetry so checkpointing, autograd, and
compile observe the same operations.
- Keep sparse MLA dispatcher, fake, and autograd registration beside the
vendored forward/backward kernel entrypoints rather than in GLM model
code.
- Collapse ring attention into one backend-neutral forward/backward
custom-op pair. Its adapters call only the pinned FA2, FA3, and FA4 APIs
explicitly, without signature probing or generated per-backend
registrations.
- Remove checkpoint-only attention helpers and the model-specific
checkpointing module. Generic attention, AFMoE, Qwen3.5, and Laguna keep
their projection/output logic directly in `forward`; GLM DSA keeps only
its substantive `mla_latents` and `mla_up_proj` helpers.
- Rebase onto the Torch 2.13, CUDA 13, and vLLM 0.28 runtime from
current `main`, and update FlashAttention 4 to `0251105` with the shared
TVM FFI version required by vLLM.
- Ignore FSDP replay-only profiler markers when selective checkpointing
validates the saved forward operation sequence.
- Prefetch the final MoE block, experts, and separately wrapped router
before backward replay so FSDP collectives occur in the same order as
the saved forward.

## Runtime contract

- Model implementations do not expose checkpoint target names or
checkpoint-only methods.
- `freq` selects whole transformer blocks; the dispatched operator and
selected target set determine whether selective AC saves or recomputes
its result.
- Both modes retain mandatory MoE routing, telemetry, non-replayable
DeepEP, and CUDA-to-CPU metadata operations so they execute once. Full
mode recomputes every other operation; selective mode additionally
retains its configured targets.
- The default selective targets retain supported attention, matrix
multiplication, grouped GEMM, and distributed communication operators.
Elementwise operations, norms, reshapes, and RoPE replay.
- Custom targets replace the selective defaults and match either an
exact operator name or an operator namespace. They cannot exclude
mandatory routing, telemetry, non-replayable communication, or
CUDA-to-CPU metadata operations.
- Unsupported or missing backend operators fail at their normal call
site; there is no checkpoint fallback layer.
- MXFP8 transport resolves `mxfp8_moe` inside its custom-op
implementation. MXFP8 grouped compute still resolves it during runtime
setup because the exported grouped GEMM is already an operator boundary.

## Configuration

```toml
[trainer.model.ac]
mode = "selective" # full | selective
freq = 1
# targets = ["aten::mm", "prime_rl_collectives"]
```

Omitting `targets` uses the public Prime defaults. Any explicit list
replaces those defaults; an empty list retains only the mandatory
operations.

## Validation

- Ruff, Ruff formatting, `uv lock --check`, and `git diff --check`
passed.
- Focused config, checkpointing, and Qwen3.5 CP tests on the rebased
dependency stack: 138 passed.
- A6000 CI regression suite passed all eight checks: four-GPU peak
memory was 6.2467 GiB against the 6.2988 GiB baseline (down from 6.6185
GiB before the fix); one-GPU peak memory was 10.6738 GiB.
- Compiled selective AC with DeepEP completed a two-GPU, two-step
`samsja/mini-glm-moe` training smoke after rebasing onto the merged MoE
runtime.
- The pinned FA2, FA3, and FA4 varlen backends all use the `[heads,
total_tokens]` LSE layout; the ring fake and backward paths enforce that
single contract.
- Two-H200 compiled ring validation matched each backend's direct
attention reference exactly for FA2, FA3, and FA4 output and `dq`, `dk`,
and `dv`.
- Full H200 unit suite: 574 passed, 9 skipped.
- Eager and compiled output/gradient/replay validation passed for local
MoE, Torch EP, DeepEP with and without chunking, CP, FA2/FA3 ring
attention, sparse MLA, dense DeepGEMM, grouped DeepGEMM, and the
production MXFP8 transport boundary with a fake numerical kernel.
- FSDP parameter/state-dict parity and selective AC plus activation
offloading passed.
- Whole-model parity passed for Llama, Nemotron-H, GPT-OSS, AFMoE,
Laguna, and Qwen3.5 full-attention layers. Sparse MLA parity also passed
after restoring its substantive helper structure.
- On the stacked Qwen3.8 Flash Next implementation, selective and full
activation checkpointing each completed 20 RL steps on 24 H200s with
compile, FSDP, expert parallelism, SignSGD, NIXL policy reload, and CPU
optimizer-state offload. Steps 2-20 averaged 8,008 tokens/s for
selective and 7,211 tokens/s for full; both peaked at 130.4 GiB and held
mismatch KL at 0.0014-0.0021 with a final value of 0.0016.

## Hardware boundary

- Numerical MXFP8 grouped GEMM and transport still require SM100
hardware. The H200 validation exercised the production
custom-op/autograd/compile boundary with a BF16 fake transport kernel.
- FA4 forward/backward numerical validation passed on H200 (SM90);
Blackwell remains untested in this PR.
- Qwen3.5 GatedDeltaNet whole-model parity did not reach execution
because the no-AC reference forward remained in FLA kernel compilation
until the diagnostic jobs were cancelled. Qwen3.5 full-attention parity
passed, and the GatedDeltaNet runtime code itself is unchanged.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Touches core training memory/throughput (activation checkpointing),
distributed MoE/DeepEP/ring attention autograd, and compile
boundaries—incorrect replay or double-counted routing would show up as
silent wrong grads or NCCL deadlocks.
> 
> **Overview**
> **Replaces layer-specific selective activation checkpointing** with
whole-block non-reentrant checkpointing driven by a PyTorch selective
operator policy (`activation_checkpointing.py`). Semantic targets like
`norm` / `attn_proj` are gone; `model.ac.targets` is now optional
operator names or namespaces that replace Prime’s defaults, while
mandatory saves still cover MoE routing/top-k, DeepEP, and CUDA→CPU
copies.
> 
> **Registers distributed and kernel paths as `torch.library` custom
ops** so checkpoint replay, autograd, and compile see the same
boundaries: new `prime_rl_collectives` for EP/CP all-to-all and
gather/reduce-scatter, `deepep::combine`, unified `prime_rl_ring` ring
attention (FA2/FA3/FA4), `prime_rl::sparse_mla`, FP8/grouped FP8 GEMMs,
and `record_moe_routing_statistics` so routing counters are not
double-applied on recompute. Inline `autograd.Function` wrappers in
token dispatch, Mamba CP, and ring attention are removed in favor of
these ops.
> 
> **Simplifies trainer wiring and models**: `apply_ac` always wraps
whole transformer blocks; the old `layers/checkpointing.py` hook layer
is deleted and attention modules no longer expose checkpoint-only
`attn_projections` / `output_proj` splits. FSDP backward prefetch now
includes the last block’s MoE experts/router. Docs, examples, and
benchmarks drop legacy selective target lists; **flash-attn-4** is
bumped to `0251105` with a pinned **apache-tvm-ffi** override.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3a51c78f1ed46b0603ec42c1011c36e14533b710. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-31 22:52:33 +02:00
Konstantin DunasandGitHub c176840626 chore: bump renderers to 0.1.11, verifiers and prime-envs to main (#3441) 2026-08-31 22:14:00 +02:00
Mika SenghaasandGitHub bb0c103f08 fix: shard SFT data and report worker progress (#3417)
## Summary

- Resolve SFT data shard identities after worker processes start.
- Shard fake data by DP rank while replicating it across CP ranks.
- Read epoch and sample progress from the furthest worker cursor.
- Aggregate per-source sample and token counters across workers.
- Preserve worker counters across dataloader checkpoint resume.
- Extend the existing CPU dataloader suite with tiny in-memory SFT data
across worker, DP, and CP layouts.
- Clarify the dummy renderer token decode in the sharding test.

## Verification

A one-GPU SFT run used two local dataset splits, two data workers, and
four logged steps.

- Before: sample progress was `5, 5, 9, 9`, and source ratio metrics
were absent.
- After: sample progress was `9, 10, 17, 18`, and source sample and
token ratios were present at every step.
- Before the sharding fix, two workers yielded `0, 0, 1, 1, 2, 2, 3, 3`
from increasing fake data.
- The CPU regression matrix verifies unique DP shards, CP replicas,
checkpoint resume, counters, and the `0 → 1` epoch transition.
- The fake-data test verifies distinct samples across DP ranks and
identical samples across CP ranks.
- The uneven-packing regression verifies that worker progress never
moves backward.
- `uv run pytest tests/unit/train/sft/test_dataloader.py -q` passed with
16 tests.
- `uv run ruff check tests/unit/train/sft/test_dataloader.py
src/prime_rl/trainer/sft/data.py src/prime_rl/trainer/sft/train.py`
passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes distributed data partitioning and checkpointed iterator state,
which can silently skew training if wrong; behavior is covered by
expanded unit tests but affects core SFT loops.
> 
> **Overview**
> Fixes **incorrect SFT data sharding and stale progress metrics** when
using multiple DataLoader workers and/or context-parallel (CP) ranks.
> 
> **Sharding:** `data_rank` / `data_world_size` are now derived from
**DP rank only** (`rank // non_dp_size`), so CP ranks see the same
samples while DP ranks stay distinct. Rank/worker identity is resolved
in **`__iter__` via `_setup_world_info()`** instead of at dataset
construction, so worker processes get the right shard after fork.
> 
> **Progress & checkpoints:** `CatDataset` state now stores and restores
per-source **`num_samples` / `num_tokens`**. New
**`get_dataset_progress()`** reads worker snapshots, uses the **furthest
worker** for `step`/`epoch`, and **sums** counters across workers. SFT
training logs **`progress/*`** from the dataloader instead of the
main-process dataset object (which stayed at zero after resume).
> 
> **Tests:** Dataloader tests drop the heavy tokenizer/GPU mark, add a
shared dummy renderer, and cover multi-rank/worker sharding, resume, CP
replication, and monotonic progress under uneven packing.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
30f7de1d229f8e88e0f334be6b8baaa7d2dccf14. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-31 13:00:38 -07:00
124 changed files with 8673 additions and 2847 deletions
+30 -3
View File
@@ -96,7 +96,7 @@ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
# mount here: .git would bust the cache every commit.
COPY --from=manifests /manifests /app
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
--no-install-workspace \
--no-install-package prime-rl-configs \
--no-install-package verifiers \
@@ -132,9 +132,9 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "quack-kernels", "vllm", "vllm-router")]'
/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")]'
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
@@ -198,10 +198,37 @@ RUN apt-get update && apt-get install -y \
libibverbs1 \
ibverbs-providers \
librdmacm1 \
libhwloc15 \
&& ln -sf /usr/bin/python3.12 /usr/local/bin/python \
&& apt-get clean autoclean \
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# AWS EFA userspace stack: libfabric + the aws-ofi-nccl NCCL net plugin,
# installed as one version-matched unit via AWS's official installer rather
# than picking versions by hand. Do not substitute a host-mounted copy of
# these libraries instead of building them in -- symbol-version mismatches
# between a host's rdma-core and a container's can silently break the NCCL
# plugin. Run directly in this stage (not a separate one COPY'd in after):
# the installer's own apt-get/dpkg step upgrades system rdma-core packages
# (libibverbs, ibverbs-providers, librdmacm) in place to versions libfabric
# actually links against -- copying only /opt/amazon out of an isolated
# stage leaves that system-wide upgrade behind, so libfabric ends up paired
# with whatever older rdma-core this image's own apt install pulled in and
# fails to load (symbol version mismatch on libefa.so.1). --skip-kmod:
# containers share the host kernel and must never build/load a kernel
# module themselves; the EFA driver is expected to already be present on
# the host. --skip-limit-conf: ulimits config doesn't apply inside a build.
ARG EFA_INSTALLER_VERSION=1.47.0
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates tar gzip \
&& curl -fsSL "https://efa-installer.amazonaws.com/aws-efa-installer-${EFA_INSTALLER_VERSION}.tar.gz" \
-o /tmp/aws-efa-installer.tar.gz \
&& tar -xzf /tmp/aws-efa-installer.tar.gz -C /tmp \
&& cd /tmp/aws-efa-installer \
&& ./efa_installer.sh -y --skip-kmod --skip-limit-conf \
&& cd / && rm -rf /tmp/aws-efa-installer.tar.gz /tmp/aws-efa-installer \
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/*
# CUDA 13.0 toolkit (TileLang's runtime nvcc JIT)
COPY --from=cuda-trim /usr/local/cuda-13.0 /usr/local/cuda-13.0
RUN ln -sfn /usr/local/cuda-13.0 /usr/local/cuda && test -x /usr/local/cuda/bin/nvcc
+8 -10
View File
@@ -23,6 +23,7 @@ import torch
from pydantic import Field
from prime_rl.utils.config import BaseConfig, cli
from prime_rl.utils.pathing import get_file_monitor_dir
MAX_LORAS = 4
@@ -70,11 +71,6 @@ class BenchmarkConfig(BaseConfig):
Field(description="Activation checkpointing type"),
] = "Recompute"
selective_targets: Annotated[
list[str] | None,
Field(description="Selective activation checkpoint targets when ac=Selective"),
] = None
attention: Annotated[
Literal["sdpa", "flash_attention_2", "flash_attention_3", "flash_attention_4"],
Field(description="Attention implementation"),
@@ -160,8 +156,6 @@ def build_command(config: BenchmarkConfig, output_dir: Path) -> list[str]:
cmd.append("--model.ac")
elif config.ac == "Selective":
cmd.extend(["--model.ac", "--model.ac.mode", "selective"])
if config.selective_targets:
cmd.extend(["--model.ac.targets", json.dumps(config.selective_targets)])
elif config.ac == "Offload":
cmd.append("--model.ac-offloading")
@@ -214,13 +208,16 @@ def aggregate_metrics(metrics_path: Path) -> dict:
Each metrics.jsonl line is one monitor.log call (``{"step": N, ...}``);
merge the lines per step, drop the first (warmup) step, and compute
mean/std/min/max per metric like the old --bench JSON export did.
mean/std/min/max per metric like the old --bench JSON export did. Rows
keyed by wall time rather than step (``step: null``) are not per-step and
are skipped.
"""
per_step: dict[int, dict] = {}
with open(metrics_path) as f:
for line in f:
row = json.loads(line)
per_step.setdefault(row["step"], {}).update(row)
if row.get("step") is not None:
per_step.setdefault(row["step"], {}).update(row)
steps = sorted(per_step)[1:] # Exclude first warmup step
columns = {
@@ -262,7 +259,8 @@ def run_benchmark(config: BenchmarkConfig) -> None:
return
# The SFT entrypoint writes to output_dir/<run.name>, the RL trainer to output_dir directly
metrics_path = output_dir / "bench" / "metrics.jsonl" if config.type == "sft" else output_dir / "metrics.jsonl"
run_dir = output_dir / "bench" if config.type == "sft" else output_dir
metrics_path = get_file_monitor_dir(run_dir) / "metrics.jsonl"
start_time = time.perf_counter()
try:
+1 -1
+1 -1
+1 -1
View File
@@ -35,7 +35,7 @@ impl = "custom" # or "hf" to force the HF path
| GLM-4 / GLM-4.5 / INTELLECT-3 | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | ✅ | ✅ |
| GPT-OSS (HF MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | ❌ | ✅ |
The custom path enables EP, CP, selective activation checkpointing, low-precision training, and grouped MoE kernels. Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
Selective activation checkpointing works with either implementation. The custom path additionally enables EP, CP, low-precision training, and grouped MoE kernels. Forcing `impl = "hf"` is mostly useful when debugging and disables those model-specific runtime features.
### Low-precision training
+4 -2
View File
@@ -413,7 +413,9 @@ demo_key = "demonstration"
Scoring runs before curriculum admission, so a rollout that is later rejected still costs its reference compute.
By default, zero-advantage RL tokens are removed after a complete batch cohort has been collected and before its payload is packed for the trainer. This does not backfill the batch. Samples that still carry CE or reference-KL components are retained, while pure zero-advantage RL samples are not shipped. Removing an RL token also removes its trainer/inference mismatch-KL contribution. Set `orchestrator.train.filter_zero_advantages = false` to retain them.
The orchestrator filters samples with no training signal. This includes samples with zero advantage on all RL tokens. Samples that still carry CE or reference-KL components are retained. Filtering an RL token also removes its trainer/inference mismatch-KL contribution.
`orchestrator.constant_trainer_batch_size` defaults to `true`. The orchestrator filters samples before they count toward the batch target. It collects replacements, so rollout-based batches contain `orchestrator.batch_size` training traces. Set the option to `false` to filter after collection without replacement. This setting can improve orchestrator throughput, but it produces smaller trainer batches.
## Curricula
@@ -425,7 +427,7 @@ Three small implementations are included:
- `StandardSampler` is the default: it advances the task iterator and cycles finite tasksets in source order.
- `DifficultyPoolSampler` samples finite tasksets with replacement and tracks each task's latest valid mean group reward. Each named pool has an inclusive reward threshold and a relative per-task sampling weight; weight `0` disables sampling from that pool. Unseen tasks use neutral weight `1.0`, so pool observations affect sampling immediately without waiting for a full taskset pass.
- `AdvRangeGate` rejects a group when every trainable-token advantage falls inside `reject_min` through `reject_max`. Unlike the built-in post-batch zero-advantage filtering, rejection requests replacement work. Groups without an advantage stream are admitted.
- `AdvRangeGate` rejects a group when every trainable-token advantage falls inside `reject_min` through `reject_max`. Unlike the built-in token filter, it can reject a configurable advantage range. Groups without an advantage stream are admitted.
```toml
[orchestrator.train.source.curriculum.sampler]
+1 -1
View File
@@ -2,7 +2,7 @@
Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config): TOML files for reproducible base configs, CLI flags for one-off overrides.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `enable_token_export` flag) that aren't surfaced here.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions) that aren't surfaced here.
## Table of Contents
+17 -1
View File
@@ -285,7 +285,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`.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. vLLM 0.28 uses the V2 model runner for standard deployments. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
```toml
[trainer]
@@ -298,3 +298,19 @@ enable_return_routed_experts = true
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.
### Sampling Replay
Truncated sampling (`top_p < 1`, `top_k`) renormalizes the sampling distribution over a sampling mask of surviving token ids. The rollout logprobs reflect that (`logprobs_mode = "processed_logprobs"`), so the trainer must renormalize over the same mask — otherwise every importance ratio is biased and training collapses (DeepSeek V3.2's "Keep Sampling Mask", [arXiv:2512.02556](https://arxiv.org/abs/2512.02556) §3.1; Cognition's [SWE-1.7 post](https://cognition.com/blog/swe-1-7)). prime-rl handles this automatically: vLLM records the sampling mask at sampling time (`--return-sampling-mask`, native since vLLM 0.28) and the trainer renormalizes its logprobs over it.
```toml
[orchestrator.train.sampling]
top_p = 0.95
top_k = 512 # optional, defaults to 512 under truncation (bounds each sampling mask)
```
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`; Gemma-family (softcapped) lm_heads fail loudly. 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.
When launching the inference server standalone, set `inference.enable_return_sampling_mask = true` yourself; clients must sample with `0 < top_k <= 512`.
+8 -5
View File
@@ -110,7 +110,7 @@ For DeepEP, set `type = "deepep"` and tune `num_sms` plus optional `token_chunk_
### Context Parallelism
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. We reccomend using `ulysses` style CP for most of the models to get the most throughput. Some models (e.g. GLM-5) only support `ring` style CP. Wrong setting will be rejected on validation.
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. Prefer `ulysses`: it gets the most throughput and is the only style that works for hybrid linear-attention/Mamba models (Qwen3.5, NemotronH) and for VLMs. Each model class declares its supported styles in `cp_support`; an unsupported `cp_style`, or a model with no CP support at all (DeepSeek V4, GPT-OSS), is rejected at setup.
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Hybrid Mamba layers head-shard independently (`cp_mamba`), which requires the CP degree to divide `mamba_num_heads` and `n_groups`.
@@ -130,15 +130,18 @@ cp_style = "ulysses" # "ring"
| `trainer.model.ac.mode = "selective"` | medium | small |
| `trainer.model.ac_offloading` | extra | a bit more |
AC and AC offloading are enabled by default (full mode). For the best memory/throughput tradeoff, switch to selective AC (custom impl only):
AC and AC offloading are enabled by default (full mode). Both AC modes retain stateful MoE routing updates and DeepEP communication that cannot safely replay. Selective AC uses the same transformer-block boundaries and additionally retains distributed communication, expensive matrix multiplications, grouped GEMMs, and supported attention kernels:
```toml
[trainer.model.ac]
mode = "selective"
targets = ["norm", "attn_proj"] # see Reference for the full list per architecture
```
`ac_offloading` is also on by default with `max_inflight_activations = 5`. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only lossing ~3-5% of throughput. To disable either, set `model.ac = "None"` or `model.ac_offloading = "None"`.
Set `targets` to operator names (for example, `"aten::mm"`) or namespaces (for example, `"prime_rl_collectives"`) to replace the default selective targets. Correctness-required operations remain retained.
Activation offloading still applies to tensors saved by autograd, but tensors retained by the checkpoint policy remain on the accelerator.
`ac_offloading` is also on by default with `max_inflight_activations = 5`. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only losing ~3-5% of throughput. To disable either, set `model.ac = "None"` or `model.ac_offloading = "None"`.
### Optimizer Offloading
@@ -274,4 +277,4 @@ uv run sft @ sft.toml --data.type fake --max-steps 4
uv run trainer @ train.toml --data.fake --max-steps 4
```
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes `metrics.jsonl` to the run's output directory by default (`monitors.file`); aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes `monitors/file/metrics.jsonl` under the run's output directory by default (`monitors.file`); aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
+6 -3
View File
@@ -58,6 +58,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| Knob | What it does |
|---|---|
| `orchestrator.batch_size` | Tasks per trainer step. |
| `orchestrator.constant_trainer_batch_size` | Keep trainer batches constant when samples have no training signal, such as zero advantage on all tokens. Enabled by default. Disable it for faster collection with variable trainer batch sizes. |
| `orchestrator.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.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
@@ -133,7 +134,9 @@ Pulled from the console logs and mirrored to W&B.
| Source | Metric | Reading |
|---|---|---|
| trainer | `time/wait_for_batch` | **high → orchestrator bottleneck** |
| orchestrator | `time/wait_for_ckpt` | **high → trainer bottleneck** |
| orchestrator | `time/wait_for_policy` | **high → trainer bottleneck** |
The trainer warns when batch wait time exceeds active trainer time. Add inference nodes when this warning persists. The orchestrator warns when policy wait time exceeds active orchestrator time. Add trainer nodes when this warning persists. The orchestrator also warns when it discards more than half of an episode window. This warning reports stale, errored, and no-signal counts.
## SFT Trainer
@@ -351,13 +354,13 @@ tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
### Dashboard
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from `metrics.jsonl`), the resolved configs, a rollout trace viewer with a per-token advantage/logprob view, merged component logs, and markdown reports from `<run>/reports/`. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from the file monitor's `metrics.jsonl`), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
A coding agent on the same machine can drive the open dashboard: `POST /api/view` with an on-disk address (`{"run", "tab", "step", "kind", "subset", "episode", "highlight": [...]}`) navigates every connected tab there and paints quote-anchored highlights in the trace viewer. Reports cite traces with `[^id]` markers whose JSON definitions carry the same address plus a verbatim quote; the dashboard re-checks each quote against the trace files and marks the citation verified or broken, so answers stay grounded in what is actually on disk. The `dashboard` skill documents the full contract.
### Weights & Biases
W&B is off by default (the file monitor, which writes `metrics.jsonl` and the per-step trace files to the run directory, is on by default):
W&B is off by default (the file monitor, which writes the metrics and the trace stream under the run's `monitors/file/` directory, is on by default):
```bash
uv run rl @ rl.toml --monitors.wandb # default project, random name
+1 -1
View File
@@ -12,6 +12,6 @@ End-to-end usage examples for prime-rl, referenced from the top-level [README](.
- **[`advanced/`](advanced)** — larger, mostly multi-node runs on frontier models, one folder
per model: `qwen3-30b-a3b` (math/swe/tool), `glm-4.5-air` (search/swe/terminal), `glm-5.2`
(large-scale + PD-disaggregated inference), `minimax-m2.5` (swe), `nemotron-3-super` (swe),
`intellect-3.1` (swe).
`intellect-3.1` (swe), `deepseek-v4-flash` (sft + a standalone vLLM serving pre-flight).
Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
@@ -0,0 +1,35 @@
# Standalone vLLM serving pre-flight: does this cluster's vLLM serve the real DeepSeek V4 Flash
# checkpoint at all, independent of the trainer? Uses vLLM's own native DeepSeek V4 support, not
# this repo's trainer port. Run directly on one allocated 8xH200 node (no [slurm] block):
#
# uv run inference @ examples/advanced/deepseek-v4-flash/inference.toml
#
# Then check /health and a /v1/chat/completions request from another shell on the same node, and
# confirm a coherent response before trusting the model for a real run.
#
# Reference: https://recipes.vllm.ai/deepseek-ai/DeepSeek-V4-Flash
# Mandatory for the fp8 checkpoint, not an optimization: without it the UE8M0-scaled fp8 weights
# route to a CUTLASS kernel that crashes on boot. That crash was observed during SM120 bring-up and
# has not been re-tested on Hopper, but the vLLM recipe sets the flag on every NVIDIA configuration.
# The mHC pre-norm GEMM does not need it on H200: measured there, the TileLang fallback matches the
# reference to 1.3e-06 relative at every token count, including the >= 1024 block-M kernel.
use_deep_gemm = true
[server]
port = 8000
[vllm]
model = "deepseek-ai/DeepSeek-V4-Flash-0731"
tensor_parallel_size = 8
enable_expert_parallel = true
gpu_memory_utilization = 0.85
max_model_len = 8192
# Required, not a tuning choice. Every DeepSeek V4 attention class sets
# `use_fp8_ds_mla_layout = True`, and the sparse-MLA layout then asserts
# "DeepseekV4 fp8_ds_mla layout only supports fp8 kv-cache" against the `auto` default. The vLLM
# recipe sets it on every vendor and every architecture.
kv_cache_dtype = "fp8"
# Recipe-derived rather than measured here: every NVIDIA configuration in the vLLM recipe pairs
# the fp8 KV cache with this block size.
block_size = 256
@@ -0,0 +1,62 @@
# Real-data SFT for deepseek-ai/DeepSeek-V4-Flash-0731 at full depth (all 43 layers, no
# `debug.num_layers` truncation) on 4 train nodes. Trainer only: no online eval, no inference
# node, and so no weight broadcast. Tested on 8xH200.
#
# uv run sft @ examples/advanced/deepseek-v4-flash/sft.toml --run.name ds-v4-sft-torch-4node
#
# Note: on 4 8xH200 nodes, this config is near the memory limit, using ~94%+ GPU memory.
#
# `dist_timeout_seconds = 14400` is needed on any run that has to build the HF -> prime-rl
# conversion cache, which takes far longer than the 3600s default.
#
# To buy memory back for quicker testing on fewer nodes, set `full_offload = true` under `[model]`,
# which keeps the fp32 masters, moments and gradients in CPU RAM and needs `optim_cpu_offload =
# false` and `optim.max_norm = "None"` set alongside it; the lighter `optim_cpu_offload = true` is
# already the default here.
#
# There is no `[ckpt]` block. The trainer saves unconditionally at the last step, and a 43-layer
# checkpoint (fp32 master weights plus two fp32 AdamW moments) is ~3 TiB. Add one with
# `ckpt.output_dir` pointed at a volume that can hold it if you need the trained weights.
dist_timeout_seconds = 14400
max_steps = 20
[model]
name = "deepseek-ai/DeepSeek-V4-Flash-0731"
impl = "custom"
ep = 8
# Torch all-to-all, not DeepEP. At full depth DeepEP dies on the first backward with
# "RuntimeError: Autograd not support dtype: Byte", raised from `Tensor.float()` in
# `DeepEPTokenDispatcher.combine` while the activation-checkpoint recompute replays through a
# `__torch_dispatch__` mode that hands back a uint8 tensor. Reproduced deterministically on 4
# nodes against the same weights and conversion cache this config trains on.
[model.moe.dispatch]
type = "torch"
[model.ac]
freq = 1
[model.ac_offloading]
max_inflight_activations = 5
[data]
name = "PrimeIntellect/Reverse-Text-SFT"
seq_len = 2048
batch_size = 32
[optim]
lr = 1e-5
[monitors.wandb]
project = "deepseek-v4-flash"
name = "deepseek-v4-flash-sft"
# `num_infer_nodes` defaults to 0, so this allocates 4 nodes and runs only the trainer.
[deployment]
type = "multi_node"
num_train_nodes = 4
[slurm]
job_name = "ds-v4-sft"
partition = "all"
+3 -3
View File
@@ -100,7 +100,7 @@ name = "openseeker"
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-search"]
env.taskset.id = "openseeker"
@@ -124,7 +124,7 @@ name = "redsearcher"
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-search"]
env.taskset.id = "redsearcher" # optional `difficulty` filter (easy/medium/hard)
@@ -154,7 +154,7 @@ num_examples = 500 # full set is 1266; cap eval at 500
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.harness.summarize_at_tokens = 98304
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-search"]
env.agent.timeout.rollout = 3600
env.taskset.id = "browsecomp"
+3 -3
View File
@@ -96,7 +96,7 @@ num_turns_weight = 0.1
[[orchestrator.train.source]]
name = "tmax"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-terminal"]
env.taskset.id = "tmax"
@@ -123,7 +123,7 @@ interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = 98304
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-terminal"]
env.agent.timeout.rollout = 3600
env.taskset.id = "swebench-verified"
@@ -144,7 +144,7 @@ env.taskset.id = "swebench-verified"
name = "terminal-bench-2"
group_size = 4 # avg@4
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = 98304
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-terminal"]
env.agent.timeout.rollout = 3600
env.taskset.id = "terminal-bench-2"
-1
View File
@@ -84,7 +84,6 @@ partition = "all" # FILL IN: set to your cluster's partition
[trainer]
dist_timeout_seconds = 1800
enable_token_export = true
[trainer.model]
name = "zai-org/GLM-5.1"
+2 -2
View File
@@ -89,7 +89,7 @@ truncate_history_thinking = false
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["nemotron-3-super-swe"]
[orchestrator.eval]
@@ -99,7 +99,7 @@ interval = 20
name = "swebench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = 98304
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["nemotron-3-super-swe"]
env.agent.timeout.rollout = 3600
+13
View File
@@ -21,6 +21,19 @@ env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 5
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text-eval"
num_examples = 256
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
-3
View File
@@ -23,11 +23,8 @@ rank = 32
alpha = 32
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", "experts"]
# MoE + mode="full" recomputes the router, whose non-deterministic top-k routing
# raises CheckpointError; selective AC excluding routed_experts avoids that.
[model.ac]
mode = "selective"
targets = ["norm", "attn_proj", "linear_attn"]
[data]
type = "sft"
+1 -1
View File
@@ -7,7 +7,7 @@ requires-python = "~=3.12.0"
dependencies = [
"pydantic>=1.10.13",
"prime-pydantic-config>=0.4.3",
"renderers>=0.1.10",
"renderers>=0.1.11",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.3.0",
@@ -4,7 +4,7 @@ from pydantic import Field, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalConfig
from prime_rl.configs.shared import ClientConfig, LogConfig
from prime_rl.configs.shared import ClientConfig, LogConfig, ResumeConfig
from prime_rl.configs.trainer import WeightBroadcastConfig
from prime_rl.utils.config import BaseConfig, default_output_dir
@@ -66,6 +66,13 @@ class OnlineConfig(BaseConfig):
this step."""
class CheckpointConfig(BaseConfig):
"""Checkpoint progress for an interruptible standalone eval run."""
interval: int = Field(1, ge=1)
"""Save after the task cursor advances by N completed groups."""
class EvalsConfig(BaseConfig):
"""``uv run evals``: run the configured evals against a live inference server.
Standalone (no ``[online]``), one epoch of every eval source runs against the
@@ -95,6 +102,12 @@ class EvalsConfig(BaseConfig):
"""Directory to write outputs to — rollout traces and logs are written as
subdirectories. Shared with the trainer for online evals. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
ckpt: CheckpointConfig | None = None
"""Checkpoint standalone eval progress. Checkpoint steps are task cursor positions."""
resume: ResumeConfig | None = None
"""Resume a standalone eval run from a cursor checkpoint. A bare block loads the latest checkpoint."""
log: LogConfig = LogConfig()
monitors: MonitorsConfig = MonitorsConfig()
@@ -117,3 +130,12 @@ class EvalsConfig(BaseConfig):
"would skip its only eval epoch. Remove it or add an [online] block."
)
return self
@model_validator(mode="after")
def validate_checkpointing_is_standalone_only(self):
if self.online is not None and (self.ckpt is not None or self.resume is not None):
raise ValueError(
"evals ckpt/resume only supports standalone evals - online evals are coordinated "
"with the trainer's live weight-broadcast lifecycle"
)
return self
@@ -458,6 +458,9 @@ class InferenceConfig(BaseConfig):
use_pd_kv_transfer: bool = False
"""Auto-set for disaggregated P/D: emit the NIXL transfer connector. Persisted into the per-node config (which drops ``deployment``) so the connector is still built per worker. Not meant to be set by hand."""
enable_return_sampling_mask: bool = False
"""Return per-token sampling masks (``sampling_mask``) on ``/inference/v1/generate`` responses via vLLM's native ``--return-sampling-mask`` (>= 0.28). The ``rl`` entrypoint enables this field for truncated policy sampling. Standalone inference must set it explicitly because no orchestrator sampling config is available. The field persists into per-node configs and selects the V2 model runner before vLLM starts. Capture is engine-wide: vLLM rejects requests with ``temperature <= 0`` or without ``top_k > 0`` while it is on."""
enable_fp32_lm_head: bool = True
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
@@ -494,6 +497,20 @@ 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
):
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."
)
return self
@model_validator(mode="after")
def validate_router_deployment(self):
"""The llm-d router (EPP + Envoy) is launched by the SLURM templates only; multi-node deployments need a router to front the per-rank engines."""
@@ -619,6 +636,9 @@ class InferenceConfig(BaseConfig):
hf_overrides.setdefault("moe_router_dtype", "float32")
namespace.hf_overrides = hf_overrides
if self.enable_return_sampling_mask:
namespace.return_sampling_mask = True
kv_transfer_config = self.build_kv_transfer_config()
if kv_transfer_config is not None:
namespace.kv_transfer_config = kv_transfer_config
@@ -25,7 +25,22 @@ class WandbMonitorConfig(BaseConfig):
class FileMonitorConfig(BaseConfig):
path: Path = Path("metrics.jsonl")
"""Path of the JSONL file, relative to the component's ``output_dir`` (absolute paths win)."""
"""Path of the metrics JSONL file, relative to the file monitor's directory under the
component's ``output_dir`` (``monitors/file/``; absolute paths win)."""
chunk_bytes: int = 5 * 1024**3
"""Size at which a trace stream (the episodes, each producer's annotations) rolls to
a new numbered chunk file. A line never spans chunks."""
compress: bool = True
"""Seal full chunks with zstd once the stream rolls past them (the live chunk stays
plain text). Sealed chunks use seekable frames: a reader still lands on one line,
and ``zstd -dcf stream/* | jq`` reads a whole stream."""
float_decimals: int | None = 4
"""Decimals kept for per-token float streams (logprobs, entropies, advantages) in
trace and annotation records; ``None`` keeps every digit. Training reads the wire,
not the records, so this only trades record size against overlay precision."""
class PrimeMonitorConfig(BaseConfig):
@@ -1,3 +1,4 @@
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
@@ -45,6 +46,16 @@ class TrainSamplingConfig(BaseConfig):
temperature: float = Field(1.0, ge=0, le=2.0)
"""Sampling temperature."""
top_p: float = Field(1.0, gt=0, le=1.0)
"""Nucleus (top-p) sampling for train rollouts. Values below 1.0 truncate the sampling
distribution; the ``rl`` entrypoint auto-enables sampling replay so trainer and
rollout distributions stay consistent — see docs/inference.md (Sampling Replay)."""
top_k: int | None = Field(None, ge=1)
"""Top-k sampling for train rollouts. Truncation triggers sampling replay, and
a default top-k is injected when only top-p truncates so sampling masks stay
bounded — see docs/inference.md (Sampling Replay)."""
max_completion_tokens: int | None = None
"""Maximum output tokens per turn. If None, generates until max context length or EOS."""
@@ -53,18 +64,46 @@ class TrainSamplingConfig(BaseConfig):
extra_body: dict[str, Any] = {}
"""Extra body forwarded with each request to the inference server."""
def truncates_distribution(self) -> bool:
return self.top_p < 1.0 or self.top_k is not None
@model_validator(mode="after")
def validate_no_extra_body_truncation(self):
"""Truncating values must come from the typed fields — the replay policy reads
them. Disabled values pass so resolved configs (where ``resolve_env_config``
stamped the ``top_k = -1`` / ``min_p = 0.0`` sentinels) re-validate cleanly."""
smuggled = [
key
for key, truncates in (
("top_p", self.extra_body.get("top_p", 1.0) < 1.0),
("top_k", self.extra_body.get("top_k") not in (None, -1, 0)),
("min_p", self.extra_body.get("min_p", 0.0) > 0.0),
)
if truncates
]
if smuggled:
raise ValueError(
f"extra_body carries truncating {smuggled}; set them as fields on the train "
"sampling config instead (they drive sampling replay)."
)
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": 1.0,
"top_p": self.top_p,
"logprobs": True,
}
if self.max_completion_tokens is not None:
args["max_completion_tokens"] = self.max_completion_tokens
if self.extra_body:
args["extra_body"] = dict(self.extra_body)
# 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
@@ -265,9 +304,6 @@ class TrainConfig(BaseConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Shared training sampling configuration."""
filter_zero_advantages: bool = True
"""Remove zero-advantage RL tokens after collecting a batch, before shipping it."""
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
@@ -442,6 +478,15 @@ class ConcurrencyConfig(BaseConfig):
return self
# Top-k injected on truncated policy sampling that has none, and the hard upper
# bound for explicit top-k. vLLM's native sampling-mask capture requires a
# per-request top_k > 0 to bound mask sizes, and the trainer pads each micro
# batch's masks to the largest sampling mask, so the bound also caps trainer
# mask tensors. Large enough that a 0.95-0.99 nucleus rarely reaches it (the
# sampling policy is essentially unchanged).
TRAIN_TOP_K_BOUND = 512
class OrchestratorConfig(BaseConfig):
algo: AlgoConfig = GRPOAlgoConfig()
"""Training algorithm: sampling plus the per-token training signal (credit
@@ -506,6 +551,9 @@ class OrchestratorConfig(BaseConfig):
batch_size: int | None = Field(None, ge=1)
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
constant_trainer_batch_size: bool = True
"""Require each batch to reach its effective sample target."""
token_batch_size: int | None = Field(None, ge=1)
"""Tokens to train on per step (token-based batching). Set this OR ``batch_size``."""
@@ -568,6 +616,55 @@ class OrchestratorConfig(BaseConfig):
env_cfg.algo.validate_env(env_cfg.env)
return self
@model_validator(mode="after")
def setup_truncated_sampling(self):
"""Truncated policy sampling trains with sampling replay (rollout
logprobs are renormalized — see docs/inference.md, Sampling Replay).
Owned here: every truncating config gets a top-k bound (bounds the sampling
masks); opd/opsd is rejected (full-vocab prefill refs would mix
normalizations). Frozen-source envs sample externally and are exempt."""
policy_samplings = [
env.sampling for env in self.train.source if env.algo is not None and env.algo.sampling.source == "policy"
] or ([self.train.sampling] if not self.train.source else [])
truncating = [sampling for sampling in policy_samplings if sampling.truncates_distribution()]
if not truncating:
return self
if any(sampling.temperature == 0 for sampling in truncating):
raise ValueError(
"Truncated train sampling (top_p/top_k) requires temperature > 0: greedy sampling has "
"no truncated distribution to replay, and the inference server rejects such requests "
"while sampling-mask capture is on."
)
oversized = [sampling.top_k for sampling in truncating if (sampling.top_k or 0) > TRAIN_TOP_K_BOUND]
if oversized:
raise ValueError(
f"Truncated train sampling with top_k = {max(oversized)} exceeds the sampling-replay "
f"bound ({TRAIN_TOP_K_BOUND}): the trainer pads each micro batch's masks to the largest "
f"sampling mask, so unbounded masks blow up trainer memory. Use top_k <= {TRAIN_TOP_K_BOUND}."
)
unbounded = [sampling for sampling in truncating if sampling.top_k is None]
if unbounded:
warnings.warn(
f"Truncated train sampling: defaulting top_k = {TRAIN_TOP_K_BOUND} so every sampling mask is "
"bounded and sampling replay stays exact. Set top_k explicitly to override.",
stacklevel=2,
)
for sampling in unbounded:
sampling.top_k = TRAIN_TOP_K_BOUND
algos = [env.algo for env in self.train.source if env.algo is not None] or [self.algo]
if any(algo.type in ("opd", "opsd") for algo in algos):
raise ValueError(
"opd/opsd is not supported with truncated train sampling: reference logprobs are full-vocab "
"prefill scores while trainer logprobs are renormalized over the sampling mask, biasing the "
"ref_kl term. Remove the truncation (top_p/top_k) or the opd/opsd algo."
)
return self
@property
def any_policy_sourced(self) -> bool:
"""True when at least one train env samples rollouts from the live policy."""
@@ -646,6 +743,23 @@ class OrchestratorConfig(BaseConfig):
env.sampling.extra_body.setdefault("return_token_ids", True)
return self
@model_validator(mode="after")
def validate_policy_top_k_consistency(self):
"""Require one top-k capture mode across the live policy server."""
policy_sources = [
env for env in self.train.source if env.algo is not None and env.algo.sampling.source == "policy"
]
enabled = [env for env in policy_sources if env.sampling.top_k is not None]
disabled = [env for env in policy_sources if env.sampling.top_k is None]
if enabled and disabled:
names = ", ".join(env.resolved_name for env in disabled)
raise ValueError(
"Live-policy train sources cannot mix top_k > 0 and top_k = -1 because "
"sampling-mask capture is engine-wide. Set top_k > 0 for these sources: "
f"{names}."
)
return self
@property
def env_sources(self) -> list[tuple[str, EnvConfig]]:
"""Every ``(split, source)`` this run pulls from, train first then eval — the
@@ -100,7 +100,7 @@ class SharedMonitorsConfig(BaseConfig):
"""Shared W&B config. Propagated to trainer and orchestrator."""
file: FileMonitorConfig | None = None
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/metrics.jsonl`` on both trainer and orchestrator."""
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/monitors/file/metrics.jsonl`` on both trainer and orchestrator."""
prime: PrimeMonitorConfig | None = None
"""Prime platform monitor. Propagated to the orchestrator only — the trainer has no platform integration."""
@@ -640,6 +640,53 @@ class RLConfig(BaseConfig):
raise ValueError("Multi-node deployments require inference.router to front the per-rank engines.")
return self
@model_validator(mode="after")
def auto_setup_sampling_mask_capture(self):
"""Truncated train sampling needs the inference server to return the sampling
masks the trainer replays (OrchestratorConfig guarantees truncating
configs are bounded by TRAIN_TOP_K_BOUND). Capture is engine-wide: while it is
on, vLLM rejects requests with ``temperature <= 0`` or without ``top_k > 0``,
so eval sampling against the same server must set both."""
policy_samplings = [
env.sampling
for env in self.orchestrator.train.source
if env.algo is not None and env.algo.sampling.source == "policy"
] or ([self.orchestrator.train.sampling] if not self.orchestrator.train.source else [])
if not any(sampling.truncates_distribution() for sampling in policy_samplings):
return self
if self.inference is None:
warnings.warn(
"Truncated train sampling with no managed inference server: set "
"`enable_return_sampling_mask = true` on the standalone server's config so it "
"returns the sampling masks the trainer replays.",
stacklevel=2,
)
return self
self.inference.enable_return_sampling_mask = True
if self.orchestrator.eval is not None:
warnings.warn(
"Sampling-mask capture is engine-wide: eval requests without top_k > 0 (from the "
"eval sampling config or the model's generation config) or with temperature 0 are "
"rejected by the inference server while truncated train sampling is on.",
stacklevel=2,
)
return self
@model_validator(mode="after")
def validate_disaggregated_combined_replay(self):
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."
)
return self
@model_validator(mode="after")
def validate_router_replay_without_kv_offload(self):
if (
@@ -30,20 +30,13 @@ class GCConfig(BaseConfig):
class ActivationCheckpointConfig(BaseConfig):
mode: Literal["full", "selective"] = "full"
"""``full`` checkpoints whole transformer blocks; ``selective`` checkpoints only the subcomponents listed in ``targets`` inside supported custom decoder layers."""
"""Both modes checkpoint whole transformer blocks. ``selective`` additionally retains selected operations."""
freq: int = Field(1, ge=1)
"""Apply activation checkpointing to every N layers."""
targets: list[str] = ["norm"]
"""Selective checkpoint targets. ``norm`` checkpoints every norm module inside selected layers. ``attn_proj`` checkpoints projection-side attention work outside the kernel (input/output projections, attention-local norms, RoPE, gating, model-specific MLA projection helpers). ``mlp`` checkpoints the entire dense MLP forward (not for MoE). ``mla_up_proj`` checkpoints MLA Q/KV up-projection where supported. ``linear_attn`` checkpoints non-softmax token mixers (NemotronH Mamba, Qwen3.5-MoE GatedDeltaNet, AFMoE sliding-window attention)."""
@model_validator(mode="after")
def validate_selective_targets(self):
self.targets = list(dict.fromkeys(self.targets))
if self.mode == "selective" and not self.targets:
raise ValueError("Selective activation checkpointing requires at least one target.")
return self
targets: list[str] | None = None
"""Operator names or namespaces retained in selective mode. ``None`` uses the default targets; an explicit list replaces them."""
class ActivationOffloadingConfig(BaseConfig):
@@ -347,12 +340,6 @@ class ModelConfig(BaseModelConfig):
self.ac = ActivationCheckpointConfig()
return self
@model_validator(mode="after")
def selective_ac_only_with_custom_impl(self):
if self.ac is not None and self.ac.mode == "selective" and self.impl not in ("custom", "auto"):
raise ValueError("Selective activation checkpointing requires model.impl='custom' or 'auto'")
return self
@model_validator(mode="after")
def cpu_offload_mutual_exclusion(self):
if self.fsdp_cpu_offload and (self.optim_cpu_offload or self.full_offload):
@@ -681,9 +668,6 @@ class TrainerConfig(BaseConfig):
metrics_server: MetricsServerConfig | None = None
"""Prometheus metrics server configuration. If set, exposes a ``/metrics`` endpoint for scraping."""
enable_token_export: bool = False
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
env_vars: EnvVars = {}
"""Extra environment variables for the trainer process(es). Merged on top of the launcher defaults."""
@@ -5,6 +5,7 @@ TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
# Trinity-Large-Thinking uses the Qwen3-Coder tool format; the rest of the family is Hermes.
(re.compile(r"^arcee-ai/Trinity-Large-Thinking"), "qwen3_coder"),
(re.compile(r"^arcee-ai/Trinity-"), "hermes"),
(re.compile(r"^deepseek-ai/DeepSeek-V4"), "deepseek_v4"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.2"), "deepseek_v32"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.1"), "deepseek_v31"),
(re.compile(r"^zai-org/GLM-4\.5"), "glm45"),
@@ -25,6 +26,9 @@ TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
# Trinity-Large-Preview doesn't reason; the Thinking/Mini/Nano variants do.
(re.compile(r"^arcee-ai/Trinity-(Large-Thinking|Mini|Nano)"), "deepseek_r1"),
# V4 reasons inside <think> blocks, but vLLM only splits them out into `reasoning_content`
# when this parser is set; the checkpoint ships no chat template, so nothing else supplies it.
(re.compile(r"^deepseek-ai/DeepSeek-V4"), "deepseek_v4"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.[12]"), "deepseek_r1"),
(re.compile(r"^zai-org/GLM-"), "glm45"),
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2_append_think"),
+5 -2
View File
@@ -23,11 +23,12 @@ dependencies = [
"openai>=1.106.1",
"orjson>=3.11.0",
"psutil>=7.0.0",
"pyzstd>=0.16.2",
"rich>=14.0.0",
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"verifiers[harbor]>=0.3.1",
"renderers>=0.1.10",
"renderers[multimodal]>=0.1.12.dev2",
"pybase64>=1.4.2",
"orjson>=3.10",
"pandas>=2.0",
@@ -139,6 +140,8 @@ environments = [
# Override torch's pinned cuDNN to fix the Conv3d performance regression.
# See: https://github.com/pytorch/pytorch/issues/166122
override-dependencies = [
# Shared by vLLM, TileLang, and the pinned FlashAttention 4 runtime.
"apache-tvm-ffi==0.1.11",
"nvidia-cudnn-cu13>=9.15 ; sys_platform == 'linux'",
# vLLM 0.28.0 requires quack-kernels 0.6.4. It requires this exact CUTLASS version.
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
@@ -250,7 +253,7 @@ torchao = [
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "82d6441" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "0251105" }
vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
-10
View File
@@ -86,16 +86,6 @@ The `sft` entrypoint takes the same eval shape at the top level for online evals
In TOML, an empty section header (`[ckpt]`) does the same.
## RL trainer token exports
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `<run_dir>/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, component weight streams (rl/ce/ref_kl), advantages, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
```toml
enable_token_export = true
```
Leave it unset for normal training. When enabled, it exports every sequence from each exporting rank.
## Key files
- `packages/prime-rl-configs/src/prime_rl/` — config classes under `configs/`; `utils/config.py` re-exports `BaseConfig` and `cli`
+3 -1
View File
@@ -73,7 +73,9 @@ curl -sS -X POST $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/view
`run` is required; other fields are optional and leave unspecified UI state
unchanged. For trace evidence, supply `step`, `kind`, and `subset` together and
address the episode by stable `id`. Use optional `trace` and `branch` indices
address the episode by stable `id`. The traces tab opens on the whole stream;
`subset: "effective"` switches it to the cohort that shipped at one step. Use
optional `trace` and `branch` indices
for multi-agent traces and `highlight` entries shaped as `{node, quote,
reason, field?}`. On `409`, tell the user to open the returned `url`; the stored
command applies when the tab connects.
+47 -18
View File
@@ -50,15 +50,15 @@ In W&B, each project auto-gets an **"overview" saved view** (train / eval / stab
- `{run_dir}/configs/latest/` — the current attempt's command, launch TOML, and `resolved/` JSON files. Each launch stays under `configs/attempt_<n>/`.
- `{run_dir}/logs/latest/` — the current attempt's logs (each launch gets `logs/attempt_<n>/`; resumes never overwrite earlier attempts). See below.
- `{run_dir}/rollouts/step_{n}/{train,eval}/` — saved episodes (see Episodes below).
- `{run_dir}/monitors/file/` — the metrics, and the traces with the annotations about them (see Episodes below).
### Dashboard
`uv run dashboard [output_dir ...]` (default `outputs/`, or `$PRL_OUTPUT_DIR` if set; several dirs can be tracked at
once) serves a local web dashboard at `http://localhost:7788` with four views per run:
metrics (the W&B overview sections, read from `metrics.jsonl`), per-attempt config
files, a rollout trace viewer with a per-token advantage/logprob view, and merged
component logs. It only reads the run dirs — safe to run against a live run.
files, a rollout trace viewer with per-token overlays (advantage, trainer logprob,
entropy, KL mismatch, stable/loss/content masks), and merged component logs. It only reads the run dirs — safe to run against a live run.
`--port`/`--host` pick the bind address; a taken port automatically bumps to the next
free one, so several dashboards run side by side without coordination. GPU deps live
behind the `gpu` extra, so `uv sync --extra dashboard && uv run dashboard` works
@@ -152,6 +152,10 @@ All metrics print to the console log (and W&B when configured).
| orchestrator | `off_policy/{mean,max}`, `off_policy/{in_flight,in_queue}/{mean,max}`, `off_policy/dropped` | per-step staleness of trained rollouts |
| env server | event loop lag (min/mean/p90/p99/max), active task distribution | periodic |
The trainer warns when batch wait time exceeds active trainer time. Add inference nodes when this warning persists. The orchestrator warns when policy wait time exceeds active orchestrator time. Add trainer nodes when this warning persists. The orchestrator also warns when it discards more than half of an episode window and reports stale, errored, and no-signal counts.
`orchestrator.constant_trainer_batch_size` defaults to `true`. It keeps each rollout batch at `orchestrator.batch_size` effective episodes. Set it to `false` for faster collection with variable trainer batch sizes.
For live vLLM stats, query Prometheus directly:
```bash
@@ -162,27 +166,52 @@ curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage"
### Episodes
```
{run_dir}/rollouts/step_{n}/{train,eval}/all/traces.jsonl # appended per episode as it completes
{run_dir}/rollouts/step_{n}/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
{run_dir}/monitors/file/metrics.jsonl # every metric row, tagged by producer
{run_dir}/monitors/file/traces/stream/00000.jsonl.zst # every episode, appended as it arrives: sealed chunks ...
{run_dir}/monitors/file/traces/stream/00001.jsonl # ... and the live one, plain text
{run_dir}/monitors/file/traces/stream.index.jsonl # one compact row per episode, with its chunk and byte offset
{run_dir}/monitors/file/traces/annotations/{producer}/00000.jsonl # trace updates: orch ship-time facts, trainer per-token streams
{run_dir}/monitors/file/traces/annotations/{producer}.index.jsonl # each update's scalars and where its record sits
```
JSONL files of native `vf.Episode` records (training tensors excluded), one line per episode.
`all` gets every completed episode as it arrives — including trace-less failures,
curriculum-rejected work, and work that never enters a batch — so it is crash-durable.
`effective` contains the admitted clean trainable traces grouped into their original episodes
(eval: the non-errored trainable epoch cohort). Each record carries its provenance at the
episode level: `env` (`id` plus the orchestrator's `name`), full `task`, `group` (`id`),
and `run`. Training-run records discriminate train/eval work and include dispatch
step plus an optional live-policy version span. Traces retain their own task,
verifiers, agent, and runtime fields.
Everything the file monitor dumps lives under `monitors/file/`; nothing is written
there when the monitor is off. The traces and everything written about them sit under
`traces/`. Each stream is a directory of numbered chunks — the writer rolls to a new
chunk at `monitors.file.chunk_bytes` (5 GiB) and, with `monitors.file.compress` (on),
seals the full one with zstd in the background; a finished run seals its live chunk
too. Sealed chunks use seekable frames, so a seek still costs one frame, and
`zstd -dcf` streams them together with the plain live chunk. Every index is named for
the stream it indexes and sits beside it. Those indexes are what keep reading a run
cheap: a consumer browses them instead of the streams, and seeks by the chunk and
offset they carry to read a single episode or its token streams. Both are derived, so
deleting them only costs a reader the work of rebuilding what it needs. The stream
holds native `vf.Episode` records (training tensors excluded; per-token floats rounded
to `monitors.file.float_decimals`, 4 by default), one line per episode in arrival order, whatever kind of work it did —
including trace-less failures, curriculum-rejected work, and work that never enters a
batch, so it is crash-durable. Each record carries its provenance: `env` (`id` plus the
orchestrator's `name`), full `task`, `group` (`id`), and `run`.
A trace has several steps, so each is stamped as its own event rather than implied by
where the record sits. The file monitor stamps `info.kind` and `info.dispatch`/
`info.arrival` (`{step, time}` each) as an episode lands; the ship-time annotation adds
`info.effective` and `info.ship` — the orchestrator step whose batch shipped the
cohort, or for eval the step that produced the policy it measured. Staleness is
`ship.step - dispatch.step`. Only `effective` ties to a step; `all` is the whole stream.
Everything learned after arrival is an append-only trace update keyed by `trace_id`,
one file per producer so each has a single writer: the orchestrator records cohort
membership, the scalar advantage and per-branch advantage streams; the trainer records
its recomputed per-token logprobs and entropies. Readers fold the updates onto the
stream records, newest winning.
```bash
wc -l {run_dir}/rollouts/step_42/train/{all,effective}/traces.jsonl
jq '.traces[].rewards' {run_dir}/rollouts/step_42/train/effective/traces.jsonl
jq 'select(.ok | not) | {id, env: .env.id, errors}' {run_dir}/rollouts/step_*/train/all/traces.jsonl
wc -l {run_dir}/monitors/file/traces/stream.index.jsonl
zstd -dcf {run_dir}/monitors/file/traces/stream/* | jq '.traces[].rewards'
zstd -dcf {run_dir}/monitors/file/traces/stream/* | jq 'select(.ok | not) | {id, env: .env.id, errors}'
jq '{trace_id, info}' {run_dir}/monitors/file/traces/annotations/orch.index.jsonl
```
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/rollouts/step_{n}/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the episode subtrees.
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/batches/step_{n}/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank).
### Common failure modes
+4 -1
View File
@@ -97,7 +97,7 @@ curl http://localhost:8000/v1/chat/completions \
## `evals` — multi-env evals
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. With `[online]` (`broadcasts_dir`, `max_steps`, `resume_step`): watch the broadcasts dir for stable `step_{n}` weight broadcasts and evaluate each — the `sft` launcher writes this config for online evals. By default a newer checkpoint cancels unfinished episodes from the prior eval. Set `eval.cancel_on_new_checkpoint = false` to drain every epoch. The trainer can idle while it waits for slow evals. Launcher-managed SFT evals use NCCL weight broadcast by default, including multi-node SLURM deployments. LoRA and external inference use filesystem broadcast.
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. Add `[ckpt]` (`interval` counts completed task groups in the eval-source order) to make the run interruptible, then use `--resume`, `--resume.step N`, or `--resume.dir path/to/checkpoints/step_N`; for standalone evals, checkpoint step N means resume from task cursor N. Checkpoints store only the cursor, not generated episode records; partially completed groups and groups beyond the durable cursor are retried. Resume loads without `[ckpt]` but does not save new checkpoints. Checkpoint/resume is rejected with `[online]` because that process is coupled to the trainer's live broadcast handshake. With `[online]` (`broadcasts_dir`, `max_steps`, `resume_step`): watch the broadcasts dir for stable `step_{n}` weight broadcasts and evaluate each — the `sft` launcher writes this config for online evals. By default a newer checkpoint cancels unfinished episodes from the prior eval. Set `eval.cancel_on_new_checkpoint = false` to drain every epoch. The trainer can idle while it waits for slow evals. Launcher-managed SFT evals use NCCL weight broadcast by default, including multi-node SLURM deployments. LoRA and external inference use filesystem broadcast.
```bash
uv run inference --vllm.model Qwen/Qwen3-4B # start inference separately
@@ -122,6 +122,9 @@ group_size = 4
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[ckpt] # optional: make a standalone eval resumable
interval = 10 # completed task groups between cursor saves
```
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/latest/envs/eval/{name}.log`.
+485 -243
View File
@@ -2,8 +2,8 @@
This package is fully AI-generated and maintained by agents - it is not meant to be read or edited by humans. Change it by asking an agent, and verify through the browser smoke tests.
Reads everything from run output directories (metrics.jsonl, logs/attempt_N,
rollouts/step_N) — no wandb or network required. Usage:
Reads everything from run output directories (the file monitor's metrics and trace
streams, logs/attempt_N) — no wandb or network required. Usage:
uv run dashboard [output_dir ...] [--port 7788] [--host 127.0.0.1]
@@ -13,17 +13,24 @@ Multiple output directories can be tracked at once.
import argparse
import asyncio
import hashlib
import math
import os
import sys
import threading
import time
from collections import OrderedDict
from itertools import groupby
from pathlib import Path
import orjson
from prime_rl.entrypoints.dashboard import DAEMON_FILE, DIRS_FILE, STATE_DIR, registry_lock
from prime_rl.monitors.file.traces import get_annotations_dir, get_index_path, get_trace_stream
from prime_rl.monitors.file.traces.chunks import open_chunk
from prime_rl.monitors.file.traces.index import summarize_episode
from prime_rl.monitors.file.traces.update import branch_node_paths, fold_trace_updates
from prime_rl.utils.config import default_output_dir
from prime_rl.utils.pathing import get_file_monitor_dir
from prime_rl.utils.process import set_proc_title
try:
@@ -68,16 +75,18 @@ def _lru_put(cache: OrderedDict, key, value) -> None:
# Append-only file caches keyed by absolute path: line-start offsets and per-episode summaries.
_offsets_cache: OrderedDict[Path, tuple[int, bytes, list[int]]] = OrderedDict()
_summaries_cache: OrderedDict[Path, tuple[int, list[dict]]] = OrderedDict()
_annotations_cache: OrderedDict[Path, tuple[tuple, dict[str, dict], dict[Path, int]]] = OrderedDict()
_index_cache: OrderedDict[Path, tuple[int, list[dict]]] = OrderedDict()
_rows_cache: OrderedDict[Path, tuple] = OrderedDict() # key, rows, entered, by_trace, consumed, last row
_tokenizer_cache: dict[str, object] = {}
_piece_cache: dict[tuple[str, int], str] = {}
_json_cache: dict[Path, tuple[tuple[int, float], dict]] = {}
_steps_cache: dict[Path, tuple[float, list[int]]] = {}
def is_run_dir(path: Path) -> bool:
if not path.is_dir() or path.name.startswith("."):
return False
return any((path / marker).exists() for marker in ("configs", "logs", "metrics.jsonl", "rollouts"))
return any((path / marker).exists() for marker in ("configs", "logs", "monitors", "traces.jsonl"))
_dirs_file_state: tuple[float, list[Path]] = (0.0, [])
@@ -193,15 +202,6 @@ def numbered_dirs(parent: Path, prefix: str) -> list[tuple[int, Path]]:
)
def size_etag(path: Path, etag: str | None) -> tuple[str, dict | None]:
"""Etag = file size: the trace files are append-only, so an unchanged size means
an unchanged response. Returns (current_etag, short-circuit response or None)."""
current = str(path.stat().st_size)
if etag is not None and etag == current:
return current, {"unchanged": True, "etag": current}
return current, None
def model_name(config: dict) -> str | None:
"""`model` is a string on eval configs, a {name} object on rl/sft ones."""
model = config.get("model")
@@ -248,22 +248,14 @@ def attempt_numbers(run_dir: Path) -> list[int]:
return [n for n, _ in numbered_dirs(run_dir / "logs", "attempt_")]
def metrics_file(run_dir: Path) -> Path:
"""The run's metric stream, as the file monitor dumps it."""
return get_file_monitor_dir(run_dir) / "metrics.jsonl"
def step_numbers(run_dir: Path) -> list[int]:
"""Rollout step numbers, cached by the rollouts dir mtime (which changes when a
step dir is created) — polled per run on every /api/runs tick."""
rollouts = run_dir / "rollouts"
try:
mtime = rollouts.stat().st_mtime
except OSError:
return []
with _lock:
cached = _steps_cache.get(rollouts)
if cached and cached[0] == mtime:
return cached[1]
steps = [n for n, _ in numbered_dirs(rollouts, "step_")]
with _lock:
_steps_cache[rollouts] = (mtime, steps)
return steps
"""The steps a cohort shipped at — what a run's progress is measured in."""
return sorted({step for _, step in effective_steps(run_dir)})
def run_meta(run_dir: Path) -> dict:
@@ -275,7 +267,7 @@ def run_meta(run_dir: Path) -> dict:
return sorted(p.stem for p in (resolved / "envs" / split).glob("*.json"))
steps = step_numbers(run_dir)
metrics_path = run_dir / "metrics.jsonl"
metrics_path = metrics_file(run_dir)
started = updated = None
if metrics_path.is_file():
updated = metrics_path.stat().st_mtime
@@ -286,9 +278,9 @@ def run_meta(run_dir: Path) -> dict:
started = orjson.loads(f.readline()).get("time")
except orjson.JSONDecodeError:
started = None
root_traces = run_dir / "traces.jsonl"
if updated is None and root_traces.is_file(): # eval runs have no metrics.jsonl
updated = root_traces.stat().st_mtime
stream = traces_file(run_dir)
if updated is None and stream is not None: # eval runs have no metrics
updated = stream.stat().st_mtime
started = configs.stat().st_mtime if configs.is_dir() else None
return {
"name": run_dir.name,
@@ -504,7 +496,7 @@ so the first charts paint long before a 100MB metrics.jsonl finishes loading."""
@app.get("/api/runs/{run}/metrics")
def read_metrics(run: str, offset: int = 0) -> dict:
path = get_run_dir(run) / "metrics.jsonl"
path = metrics_file(get_run_dir(run))
if not path.is_file():
return {"rows": [], "offset": 0, "size": 0}
size = path.stat().st_size
@@ -528,49 +520,49 @@ def read_metrics(run: str, offset: int = 0) -> dict:
# ------------------------------------------------------------------------ rollouts
RECENT_STEPS = 64
_avail_cache: dict[Path, dict[str, bool]] = {} # step dir -> known-present subsets
_avail_scan_counter = 0
def _file_size(path: Path) -> int:
try:
return path.stat().st_size
except OSError:
return -1
EVAL_ROOT_STEP = (0, "eval", "all")
"""The virtual address of a stepless `uv run eval` run's root traces.jsonl —
the one convention shared by the step listing and traces_path."""
def traces_file(run_dir: Path) -> Path | None:
"""The run's episode stream: the chunk directory the file monitor writes, browsed
through its index, or the single ``traces.jsonl`` a verifiers ``uv run eval`` run
writes at the run root."""
stream = get_trace_stream(run_dir)
if _file_size(get_index_path(stream)) > 0:
return stream
bare = run_dir / "traces.jsonl"
if bare.is_file() and bare.stat().st_size > 0:
return bare
return None
def eval_root_traces(run_dir: Path) -> Path | None:
root = run_dir / "traces.jsonl"
return root if root.is_file() and root.stat().st_size > 0 else None
def stream_version(path: Path) -> int:
"""What a stream's readers key their caches on. Both shapes are append-only, so
a size is a version: the index for a chunked stream, the file itself for a bare one."""
return _file_size(get_index_path(path)) if path.is_dir() else _file_size(path)
def require_stream(run_dir: Path) -> Path:
path = traces_file(run_dir)
if path is None:
raise HTTPException(404, "no traces for this run")
return path
def rollout_steps(run_dir: Path) -> list[dict]:
"""Presence only — never reads trace files. Presence is monotonic (files only
appear), so known-present subsets are cached forever; absent ones re-stat every
poll only for the newest steps — older gaps (an eval landing late at its trigger
step) are picked up by a full rescan every 10th call."""
global _avail_scan_counter
_avail_scan_counter += 1
full_rescan = _avail_scan_counter % 10 == 1
numbered = numbered_dirs(run_dir / "rollouts", "step_")
recent_cutoff = numbered[-1][0] - RECENT_STEPS if numbered else 0
steps = []
for number, step_dir in numbered:
available = _avail_cache.setdefault(step_dir, {})
if len(available) < 4 and (full_rescan or number >= recent_cutoff):
for kind in ("train", "eval"):
for subset in ("all", "effective"):
key = f"{kind}/{subset}"
if key in available:
continue
path = step_dir / kind / subset / "traces.jsonl"
if path.is_file() and path.stat().st_size > 0:
available[key] = True
if available:
steps.append({"step": number, "available": available})
root = eval_root_traces(run_dir)
if not steps and root is not None:
steps.append({"step": EVAL_ROOT_STEP[0], "available": {f"{EVAL_ROOT_STEP[1]}/{EVAL_ROOT_STEP[2]}": True}})
return steps
"""The steps a cohort can be addressed by, and the kinds of work each one holds.
Only a cohort ties to a step — the orchestrator step whose batch shipped it, or
for eval the policy version it measured — so the steps come from the annotations.
The stream itself is not addressed by step."""
by_step: dict[int, set[str]] = {}
for kind, step in effective_steps(run_dir):
by_step.setdefault(step, set()).add(kind)
return [{"step": step, "kinds": sorted(kinds)} for step, kinds in sorted(by_step.items())]
def line_offsets(path: Path) -> list[int]:
@@ -616,89 +608,12 @@ def line_offsets(path: Path) -> list[int]:
return current
def walk_timing(obj: dict, prefix: str, out: dict[str, float]) -> None:
"""Flatten a trace timing tree to phase -> seconds (same walk as the viewer)."""
if isinstance(obj.get("duration"), (int, float)):
out[prefix] = out.get(prefix, 0.0) + obj["duration"]
elif isinstance(obj.get("start"), (int, float)) and isinstance(obj.get("end"), (int, float)):
out[prefix] = out.get(prefix, 0.0) + (obj["end"] - obj["start"])
for key, value in obj.items():
if isinstance(value, dict):
walk_timing(value, f"{prefix}/{key}" if prefix else key, out)
def summarize_episode(line: int, rec: dict) -> dict:
rewards, advantages = [], []
input_tokens = output_tokens = turns = branches = 0
stop_condition = None
reward_parts: dict[str, list[float]] = {}
metric_parts: dict[str, list[float]] = {}
timing: dict[str, float] = {}
costs: list[float] = []
for trace in rec.get("traces") or []:
costs.extend(
usage["cost"]
for call in trace.get("calls") or []
if isinstance(usage := call.get("usage") or {}, dict) and isinstance(usage.get("cost"), (int, float))
)
nodes = trace.get("nodes") or []
parents = {node.get("parent") for node in nodes if "parent" in node}
branches += max(0, len(nodes) - len(parents))
if trace.get("rewards"): # skip reward-less seats (e.g. a judge) in the episode mean
rewards.append(
sum(
(r.get("score") or 0) * (r.get("weight") if r.get("weight") is not None else 1)
for r in trace["rewards"].values()
if isinstance(r, dict)
)
)
for name, r in (trace.get("rewards") or {}).items():
if isinstance(r, dict) and isinstance(r.get("score"), (int, float)):
reward_parts.setdefault(name, []).append(r["score"])
for name, value in (trace.get("metrics") or {}).items():
if isinstance(value, (int, float)):
metric_parts.setdefault(name, []).append(value)
if isinstance(trace.get("timing"), dict):
walk_timing(trace["timing"], "", timing)
advantage = (trace.get("info") or {}).get("advantage")
if advantage is not None:
advantages.append(advantage)
for node in nodes:
n_tokens = len(node.get("token_ids") or [])
if node.get("sampled"):
output_tokens += n_tokens
else:
input_tokens += n_tokens
if (node.get("message") or {}).get("role") == "assistant":
turns += 1
stop_condition = trace.get("stop_condition", stop_condition)
if input_tokens == 0 and output_tokens == 0: # some eval traces carry no token arrays
for call in trace.get("calls") or []:
usage = call.get("usage") or {}
input_tokens += usage.get("prompt_tokens") or 0
output_tokens += usage.get("completion_tokens") or 0
return {
"rewards": {name: sum(v) / len(v) for name, v in reward_parts.items()},
"metrics": {name: sum(v) / len(v) for name, v in metric_parts.items()},
"timing": timing,
"cost": sum(costs) if costs else None,
"line": line,
"id": rec.get("id"),
"env": (rec.get("env") or {}).get("id") or (rec.get("env") or {}).get("name"),
"group": (rec.get("group") or {}).get("id"),
"ok": rec.get("ok"),
"num_errors": len(rec.get("errors") or []),
"reward": sum(rewards) / len(rewards) if rewards else None,
"advantage": sum(advantages) / len(advantages) if advantages else None,
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"turns": turns,
"branches": branches,
"stop_condition": stop_condition,
}
def episode_summaries(path: Path) -> list[dict]:
"""Every episode's full summary, nested reward/metric/timing maps included. Parsed
from the records themselves, resuming from the last one summarised, and persisted
so a revisit skips the parse."""
if path.is_dir():
return chunked_summaries(path)
offsets = line_offsets(path)
with _lock:
cached_count, summaries = _lru_get(_summaries_cache, path) or (0, [])
@@ -719,20 +634,54 @@ def episode_summaries(path: Path) -> list[dict]:
for line_no in range(cached_count, len(offsets)):
raw = f.readline()
try:
summaries.append(summarize_episode(line_no, orjson.loads(raw)))
summaries.append(summarize_episode(line_no + 1, orjson.loads(raw)))
except orjson.JSONDecodeError:
summaries.append({"line": line_no, "id": None, "error": "unparseable"})
summaries.append({"line": line_no + 1, "id": None, "error": "unparseable"})
with _lock:
_lru_put(_summaries_cache, path, (len(offsets), summaries))
write_sidecar(path, summaries)
return summaries
def chunked_summaries(stream: Path) -> list[dict]:
"""The summaries of a chunked stream: its index says where each record sits, so the
walk opens each chunk once and seeks record to record."""
index = get_index_path(stream)
rows = index_rows(index) or []
with _lock:
cached_count, summaries = _lru_get(_summaries_cache, stream) or (0, [])
if cached_count > len(rows):
cached_count, summaries = 0, []
if cached_count == 0:
loaded = load_sidecar(index)
if loaded is not None:
summaries = loaded[: len(rows)]
cached_count = len(summaries)
if cached_count == len(rows):
with _lock:
_lru_put(_summaries_cache, stream, (cached_count, summaries))
return summaries
summaries = list(summaries[:cached_count])
for chunk, chunk_rows in groupby(rows[cached_count:], key=lambda row: row.get("chunk", 0)):
with open_chunk(stream, chunk) as f:
for row in chunk_rows:
f.seek(row.get("offset", 0))
try:
summaries.append(summarize_episode(row["line"], orjson.loads(f.readline())))
except orjson.JSONDecodeError:
summaries.append({"line": row["line"], "id": None, "error": "unparseable"})
with _lock:
_lru_put(_summaries_cache, stream, (len(rows), summaries))
write_sidecar(index, summaries)
return summaries
# ------------------------------------------------------- summary sidecars
# Parsing a step's traces file for the table can mean reading gigabytes; the
# result is persisted outside the run dir (the dashboard never writes there),
# so a revisit — or a dashboard restart — skips the parse entirely.
SIDECAR_DIR = STATE_DIR
SIDECAR_FORMAT = 4
SIDECAR_WRITE_INTERVAL_S = 20.0
_sidecar_written: dict[Path, tuple[float, int]] = {} # path -> (last write time, count)
@@ -758,7 +707,8 @@ def load_sidecar(path: Path) -> list[dict] | None:
data = read_json(sidecar_path(path))
try:
if (
data.get("path") != str(path.resolve())
data.get("format") != SIDECAR_FORMAT
or data.get("path") != str(path.resolve())
or path.stat().st_size < data["size"]
or data.get("checkpoint") != file_checkpoint(path, data["size"]).hex()
):
@@ -777,6 +727,7 @@ def write_sidecar(path: Path, summaries: list[dict]) -> None:
SIDECAR_DIR.mkdir(parents=True, exist_ok=True)
size = path.stat().st_size
payload = {
"format": SIDECAR_FORMAT,
"path": str(path.resolve()),
"size": size,
"checkpoint": file_checkpoint(path, size).hex(),
@@ -789,26 +740,11 @@ def write_sidecar(path: Path, summaries: list[dict]) -> None:
def traces_path(run: str, step: int, kind: str, subset: str) -> Path:
"""The run's episode stream. ``step``/``kind``/``subset`` never select a file —
every episode is on disk exactly once — they select the read-time filter."""
if kind not in ("train", "eval") or subset not in ("all", "effective"):
raise HTTPException(400, "kind must be train|eval, subset all|effective")
run_dir = get_run_dir(run)
path = run_dir / "rollouts" / f"step_{step}" / kind / subset / "traces.jsonl"
if path.is_file():
return path
if (step, kind, subset) == EVAL_ROOT_STEP:
root = eval_root_traces(run_dir)
if root is not None:
return root
raise HTTPException(404, "no traces for this step/kind/subset")
def read_episode_record(path: Path, line: int) -> dict:
offsets = line_offsets(path)
if not 0 <= line < len(offsets):
raise HTTPException(404, "episode line out of range")
with path.open("rb") as f:
f.seek(offsets[line])
return orjson.loads(f.readline())
return require_stream(get_run_dir(run))
def message_text(message: dict) -> str:
@@ -838,22 +774,74 @@ def timeline_reward(trace: dict) -> float | None:
)
def trace_branch_paths(nodes: list[dict]) -> list[list[int]]:
"""Return VF-native root-to-leaf branches in leaf-index order."""
if not nodes:
def annotation_streams(run_dir: Path) -> list[Path]:
"""The annotation streams, one chunk directory per producer, each indexed beside it."""
directory = get_annotations_dir(run_dir)
if not directory.is_dir():
return []
parents = {parent for node in nodes if isinstance((parent := node.get("parent")), int) and 0 <= parent < len(nodes)}
paths = []
for leaf in (index for index in range(len(nodes)) if index not in parents):
path = []
seen = set()
node_index: int | None = leaf
while isinstance(node_index, int) and 0 <= node_index < len(nodes) and node_index not in seen:
seen.add(node_index)
path.append(node_index)
node_index = nodes[node_index].get("parent")
paths.append(list(reversed(path)))
return paths
return sorted(path for path in directory.iterdir() if path.is_dir())
def annotation_rows(stream: Path) -> list[dict]:
"""A producer's updates as its index rows - ``{trace_id, info, chunk, offset}``."""
return index_rows(get_index_path(stream)) or []
def annotation_index(run_dir: Path) -> dict[str, dict]:
"""Trace id -> the scalars its updates carry, and where each record sits.
Reads the producers' indexes when they exist, so answering "which cohort, what
credit" never touches the token streams — they can outweigh the traces themselves.
A producer that wrote no index is read in full."""
files = annotation_streams(run_dir)
key = tuple((data.name, stream_version(data)) for data in files)
cache_key = get_annotations_dir(run_dir)
with _lock:
cached = _lru_get(_annotations_cache, cache_key)
if cached and cached[0] == key:
return cached[1]
# Producers only append, so the fold resumes from the row each one was last read
# to. The map is copied rather than grown in place: a request already iterating
# the previous one must not see it change size under it.
consumed, index = ({}, {}) if cached is None else (dict(cached[2]), dict(cached[1]))
def note(trace_id: str | None, info: dict, data: Path, chunk: int, offset: int) -> None:
if not trace_id:
return
entry = index.setdefault(trace_id, {"info": {}, "at": []})
entry["info"].update(info)
entry["at"].append((data, chunk, offset))
for data in files:
rows = annotation_rows(data)
for row in rows[consumed.get(data, 0) :]:
note(row.get("trace_id"), row.get("info") or {}, data, row.get("chunk", 0), row.get("offset", 0))
consumed[data] = len(rows)
with _lock:
_lru_put(_annotations_cache, cache_key, (key, index, consumed))
return index
def trace_updates(run_dir: Path, trace_id: str) -> list[dict]:
"""Every update recorded against one trace, read by seeking to each record."""
entry = annotation_index(run_dir).get(trace_id)
updates = []
for stream, chunk, offset in (entry or {}).get("at", []):
try:
with open_chunk(stream, chunk) as f:
f.seek(offset)
updates.append(orjson.loads(f.readline()))
except (OSError, orjson.JSONDecodeError):
continue
return updates
def ipo_eps(run_dir: Path) -> float:
"""The run's IPO threshold: how far a token's probability may move before the
loss drops it. It is what the stable-mask overlay colours against."""
loss = read_json(resolved_config_dir(run_dir) / "trainer.json").get("loss") or {}
eps = loss.get("eps") if loss.get("type") == "ipo" else None
return eps if isinstance(eps, (int, float)) else 0.1
def token_usage(usage: dict) -> tuple[int | None, int | None, int | None]:
@@ -1015,7 +1003,7 @@ def project_episode_timeline(episode: dict) -> dict:
lane_groups = []
for trace_index, trace in enumerate(episode.get("traces") or []):
nodes = trace.get("nodes") or []
branch_paths = trace_branch_paths(nodes)
branch_paths = branch_node_paths(nodes)
node_branch_counts: dict[int, int] = {}
for path in branch_paths:
for node_index in path:
@@ -1102,40 +1090,260 @@ def project_episode_timeline(episode: dict) -> dict:
return {"lanes": lanes}
NICE_BINS = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600, 7200, 10800, 21600, 43200, 86400]
def nice_bin(ideal: float) -> float:
"""The smallest round interval at least this wide, so bars land on seconds,
minutes or hours a reader recognises rather than 93.4s."""
return next((step for step in NICE_BINS if step >= ideal), NICE_BINS[-1])
SORT_KEYS = {"arrival", "duration", "reward", "output_tokens", "turns", "group"}
def stream_index_file(run_dir: Path) -> Path:
"""Where the stream's index would sit — beside the stream, named for it. A stream
written by a producer that indexes nothing simply has no file there."""
stream = traces_file(run_dir)
return get_index_path(stream) if stream else get_index_path(get_trace_stream(run_dir))
def index_rows(path: Path) -> list[dict] | None:
"""The rows of an index the file monitor wrote, read incrementally: an index is
append-only, so only the bytes past the last read are parsed. ``None`` when there
is no index, which is the reader's cue to derive what it needs itself."""
if not path.is_file():
return None
size = path.stat().st_size
with _lock:
cached = _lru_get(_index_cache, path)
if cached and cached[0] == size:
return cached[1]
rows, read_from = (list(cached[1]), cached[0]) if cached and cached[0] < size else ([], 0)
with path.open("rb") as f:
f.seek(read_from)
for raw in f:
if not raw.endswith(b"\n"):
break # a torn tail line: the writer is mid-append
try:
rows.append(orjson.loads(raw))
except orjson.JSONDecodeError:
break
read_from += len(raw)
with _lock:
_lru_put(_index_cache, path, (read_from, rows))
return rows
def written_index(run_dir: Path) -> list[dict] | None:
"""The stream's own index, when the stream's producer wrote one."""
return index_rows(stream_index_file(run_dir))
def episode_rows(run_dir: Path) -> list[dict]:
"""The run's episode index: one row per episode of the stream, in arrival order,
carrying the cohort step its annotations give it.
Everything here is append-only, so the work tracks the growth rather than the run:
new episodes are entered as they arrive, and a new ship-time update stamps only the
episodes that own its trace. A browse request pays for what changed since the last
one, however long the run gets."""
path = traces_file(run_dir)
if path is None:
return []
files = annotation_streams(run_dir)
key = (stream_version(path), *(stream_version(f) for f in files))
with _lock:
cached = _lru_get(_rows_cache, run_dir)
if cached and cached[0] == key:
return cached[1]
rows = written_index(run_dir)
if rows is None:
rows = episode_summaries(path)
# Resume only over the very rows stamped last time: a shorter list is a rewrite,
# and a list rebuilt from disk holds new dicts the trace map would no longer reach.
entered = cached[2] if cached else 0
resume = bool(cached) and len(rows) >= entered and (entered == 0 or rows[entered - 1] is cached[5])
by_trace, consumed = (cached[3], dict(cached[4])) if resume else ({}, {})
if not resume:
entered = 0
for row in rows[entered:]:
row["step"] = None
for trace_id in row.get("trace_ids") or []:
by_trace.setdefault(trace_id, []).append(row)
for data in files:
updates = annotation_rows(data)
for update in updates[consumed.get(data, 0) :]:
info = update.get("info") or {}
step = (info.get("ship") or {}).get("step")
if not info.get("effective") or not isinstance(step, int):
continue
for row in by_trace.get(update.get("trace_id"), ()):
row["step"] = step if row["step"] is None else min(row["step"], step)
consumed[data] = len(updates)
with _lock:
_lru_put(_rows_cache, run_dir, (key, rows, len(rows), by_trace, consumed, rows[-1] if rows else None))
return rows
def row_filter(
*,
step: int | None = None,
kind: str | None = None,
env: str | None = None,
episode: str | None = None,
errors_only: bool = False,
start: float | None = None,
end: float | None = None,
):
"""A predicate over index rows. A step selects the cohort shipped at it — for
train work the orchestrator step, for eval the policy version — which is the only
sense in which an episode belongs to a step."""
def keep(row: dict) -> bool:
if step is not None and row.get("step") != step:
return False
if kind and row.get("kind") != kind:
return False
if env and row.get("env") != env:
return False
if episode is not None and row.get("id") != episode:
return False
if errors_only and not (row.get("num_errors") or not row.get("ok")):
return False
arrival = row.get("arrival") or 0
return not ((start is not None and arrival < start) or (end is not None and arrival >= end))
return keep
def filter_rows(rows: list[dict], **narrow) -> list[dict]:
keep = row_filter(**narrow)
return [row for row in rows if keep(row)]
def index_facets(run_dir: Path) -> tuple[list[str], list[str]]:
"""The envs and kinds the stream holds, for the filter controls."""
rows = episode_rows(run_dir)
envs = {row["env"] for row in rows if row.get("env")}
kinds = {row.get("kind") for row in rows}
return sorted(envs), [kind for kind in ("train", "eval") if kind in kinds]
@app.get("/api/runs/{run}/episodes")
def list_stream_episodes(
run: str,
step: int | None = None,
kind: str | None = None,
env: str | None = None,
episode: str | None = None,
errors_only: bool = False,
sort: str = "arrival",
order: str = "desc",
offset: int = Query(default=0, ge=0),
limit: int = Query(default=128, ge=1, le=512),
start: float | None = None,
end: float | None = None,
etag: str | None = None,
upto: int | None = Query(default=None, ge=0),
) -> dict:
"""One page of the stream. The client scrolls by asking for the next offset, so a
run of any length costs the same to browse.
A live stream grows at its head, which would shift every offset under a reader
mid-scroll. ``upto`` pins the page to the stream as it stood at that many lines -
the length the first page reported - so later pages address a list that no longer
moves, whatever the sort."""
run_dir = get_run_dir(run)
path = require_stream(run_dir)
current_etag = stream_etag(run_dir, path)
if etag is not None and etag == current_etag and offset == 0:
return {"unchanged": True, "etag": current_etag}
rows = episode_rows(run_dir)
lines = len(rows)
if upto is not None:
rows = rows[:upto]
envs, kinds = index_facets(run_dir)
keep = row_filter(step=step, kind=kind, env=env, episode=episode, errors_only=errors_only, start=start, end=end)
if sort == "arrival":
# the index is already in arrival order: walk it from the right end and stop
# once the page is full, so the common view costs a page rather than a run
ordered = reversed(rows) if order == "desc" else rows
page, total = [], 0
for row in ordered:
if not keep(row):
continue
if offset <= total < offset + limit:
page.append(row)
total += 1
else:
matching = [row for row in rows if keep(row)]
blank = "" if sort == "group" else 0
if sort in SORT_KEYS:
matching.sort(key=lambda row: (row.get(sort) is None, row.get(sort) or blank), reverse=order == "desc")
page, total = matching[offset : offset + limit], len(matching)
return {
"etag": current_etag,
"lines": lines,
"total": total,
"offset": offset,
"envs": envs,
"kinds": kinds,
"episodes": page,
}
@app.get("/api/runs/{run}/episodes/histogram")
def episode_histogram(
run: str,
step: int | None = None,
kind: str | None = None,
env: str | None = None,
errors_only: bool = False,
bars: int = Query(default=80, ge=8, le=500),
) -> dict:
"""Episodes finishing per time bin, over the same filters as the table — the
stream's shape, and the thing you click to narrow it to a moment. The range fits
the episodes and the bin is the roundest interval that keeps the bar count sane,
so a run of any length reads the same."""
run_dir = get_run_dir(run)
rows = filter_rows(episode_rows(run_dir), step=step, kind=kind, env=env, errors_only=errors_only)
arrivals = sorted(row["arrival"] for row in rows if isinstance(row.get("arrival"), (int, float)))
if not arrivals:
return {"bins": [], "bin": 60, "start": None, "end": None, "total": 0}
bin = nice_bin(max(arrivals[-1] - arrivals[0], 1e-9) / bars)
# square the edges to bin boundaries so the bars carry round timestamps
start = math.floor(arrivals[0] / bin) * bin
end = math.floor(arrivals[-1] / bin) * bin + bin
counts: dict[int, int] = {}
for arrival in arrivals:
index = int((arrival - start) // bin)
counts[index] = counts.get(index, 0) + 1
span = max(1, int(round((end - start) / bin)))
return {
"bins": [[start + index * bin, counts.get(index, 0)] for index in range(span)],
"bin": bin,
"start": start,
"end": end,
"total": sum(counts.values()),
}
@app.get("/api/runs/{run}/rollouts")
def list_rollouts(run: str) -> dict:
return {"steps": rollout_steps(get_run_dir(run))}
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}")
def list_episodes(
run: str,
step: int,
kind: str,
subset: str,
limit: int = Query(default=5000, ge=1, le=5000),
episode: str | None = None,
env: str | None = None,
errors_only: bool = False,
sort: str = "line",
order: str = "asc",
etag: str | None = None,
) -> dict:
path = traces_path(run, step, kind, subset)
current_etag, unchanged = size_etag(path, etag)
if unchanged:
return unchanged
summaries = episode_summaries(path)
envs = sorted({s["env"] for s in summaries if s.get("env")})
if episode is not None:
summaries = [s for s in summaries if s.get("id") == episode]
if env:
summaries = [s for s in summaries if s.get("env") == env]
if errors_only:
summaries = [s for s in summaries if s.get("num_errors") or not s.get("ok")]
if sort in ("reward", "advantage", "output_tokens", "turns", "group"):
summaries = sorted(summaries, key=lambda s: (s.get(sort) is None, s.get(sort) or 0), reverse=(order == "desc"))
return {"total": len(summaries), "etag": current_etag, "envs": envs, "episodes": summaries[:limit]}
def stream_etag(run_dir: Path, path: Path) -> str:
"""What a listing depends on: the stream, and the annotations that give its rows
their cohort and credit. Both are append-only, so their sizes are the version."""
return f"{stream_version(path)}-{sum(stream_version(f) for f in annotation_streams(run_dir))}"
def effective_steps(run_dir: Path) -> set[tuple[str, int]]:
"""The (kind, step) pairs an effective cohort can be addressed by."""
return {(row["kind"], row["step"]) for row in episode_rows(run_dir) if row.get("step") is not None}
def get_tokenizer(model: str):
@@ -1217,16 +1425,17 @@ def rendered_token_text(trace: dict, model: str | None) -> dict:
}
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/series")
def episode_series(run: str, step: int, kind: str, subset: str, etag: str | None = None, after: int = 0) -> dict:
"""Per-episode series over a traces file (x = episode order): reward, shape, and the
@app.get("/api/runs/{run}/episodes/series")
def episode_series(run: str, kind: str | None = None, etag: str | None = None, after: int = 0) -> dict:
"""Per-episode series over the stream (x = arrival order): reward, shape, and the
nested rewards/metrics/timing keys — the metrics view for eval runs. `after` returns
only episodes past that index, so a growing file ships increments, not the world."""
path = traces_path(run, step, kind, subset)
current_etag, unchanged = size_etag(path, etag)
if unchanged:
return unchanged
summaries = episode_summaries(path)
only episodes past that index, so a growing stream ships increments, not the world."""
run_dir = get_run_dir(run)
path = require_stream(run_dir)
current_etag = stream_etag(run_dir, path)
if etag is not None and etag == current_etag:
return {"unchanged": True, "etag": current_etag}
summaries = [s for s in episode_summaries(path) if not kind or s.get("kind") == kind]
keys: set[str] = set()
for s in summaries:
keys.update(
@@ -1246,30 +1455,62 @@ def episode_series(run: str, step: int, kind: str, subset: str, etag: str | None
return {"etag": current_etag, "count": len(summaries), "after": max(0, after), "series": series}
def read_episode_at(path: Path, line: int) -> dict:
offsets = line_offsets(path)
if not 0 <= line < len(offsets):
def read_episode_at(path: Path, line: int, at: tuple[int, int] | None = None) -> dict:
"""One episode. A written index says which chunk and byte offset it sits at, so
reading it never touches the rest of the stream; a bare file is scanned for its
line offsets instead."""
if at is None:
offsets = line_offsets(path)
if not 1 <= line <= len(offsets):
raise HTTPException(404, "episode line out of range")
f, offset = path.open("rb"), offsets[line - 1]
else:
chunk, offset = at
f = open_chunk(path, chunk)
with f:
f.seek(offset)
try:
return orjson.loads(f.readline())
except orjson.JSONDecodeError as error:
# a record torn by a crash, or the stream's last line caught mid-append
raise HTTPException(422, f"episode {line} is unparseable") from error
def episode_at(run_dir: Path, line: int) -> tuple[int, int] | None:
"""Where the written index puts an episode: ``(chunk, offset)``. None only when the
stream has no index; an index that exists is authoritative for what lines there are."""
rows = written_index(run_dir)
if rows is None:
return None
if not 1 <= line <= len(rows):
raise HTTPException(404, "episode line out of range")
with path.open("rb") as f:
f.seek(offsets[line])
return orjson.loads(f.readline())
row = rows[line - 1]
return row.get("chunk", 0), row.get("offset", 0)
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/{line}")
@app.get("/api/runs/{run}/episodes/{line}")
def get_episode(
run: str,
step: int,
kind: str,
subset: str,
line: int,
tokens: bool = False,
rendered: bool = False,
) -> dict:
path = traces_path(run, step, kind, subset)
rec = read_episode_at(path, line)
"""One episode, by its line in the stream, with every annotation folded on."""
run_dir = get_run_dir(run)
path = require_stream(run_dir)
rec = read_episode_at(path, line, episode_at(run_dir, line))
# only the opened episode's streams are read, by seeking to each of its records
for trace in rec.get("traces") or []:
updates = trace_updates(run_dir, trace.get("id") or "")
if not updates:
continue
stamped = fold_trace_updates(trace, updates)
if stamped:
ship_step = ((trace.get("info") or {}).get("ship") or {}).get("step")
trace["train_annotations"] = {"step": ship_step, "nodes": stamped, "eps": ipo_eps(run_dir)}
if not tokens and not rendered:
return rec
fallback_model = model_name(main_config(get_run_dir(run))[1])
fallback_model = model_name(main_config(run_dir)[1])
for trace in rec.get("traces") or []:
client = ((trace.get("agent") or {}).get("config") or {}).get("client") or {}
model = client.get("renderer_model_name") or fallback_model
@@ -1364,7 +1605,7 @@ def validate_view_command(cmd: dict) -> dict:
rec = None
if episode is not None:
matches = [s["line"] for s in episode_summaries(path) if s.get("id") == episode]
matches = [row["line"] for row in episode_rows(get_run_dir(run)) if row.get("id") == episode]
if not matches:
raise HTTPException(404, f"episode id {episode!r} not found in {kind}/{subset} at step {step}")
if len(matches) > 1:
@@ -1468,9 +1709,10 @@ async def view_events() -> "StreamingResponse":
)
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/{line}/timeline")
def get_episode_timeline(run: str, step: int, kind: str, subset: str, line: int) -> dict:
return project_episode_timeline(read_episode_at(traces_path(run, step, kind, subset), line))
@app.get("/api/runs/{run}/episodes/{line}/timeline")
def get_episode_timeline(run: str, line: int) -> dict:
run_dir = get_run_dir(run)
return project_episode_timeline(read_episode_at(require_stream(run_dir), line, episode_at(run_dir, line)))
# -------------------------------------------------------------------------- static
File diff suppressed because it is too large Load Diff
+79 -63
View File
@@ -78,48 +78,60 @@
</section>
<section id="tab-traces" hidden>
<div class="controls" id="step-bar">
<div class="controls" id="trace-bar">
<div class="seg" id="trace-mode">
<button data-mode="stream" class="active" title="every episode, newest first">Stream</button>
<button data-mode="step" title="the cohort shipped at one step">Step</button>
</div>
<div id="trace-filter-wrap" class="dd-wrap">
<button id="trace-filter-btn" class="btn dd-btn" title="filter">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
filter
<span id="trace-filter-count" class="badge" hidden></span>
</button>
<div class="dd-menu dd-filters" id="trace-filter-menu" hidden>
<div class="dd-sec">filter</div>
<div class="dd-row"><span class="t-label">kind</span>
<div class="seg toggle-seg" id="trace-kinds">
<button data-kind="train" class="on">train</button>
<button data-kind="eval" class="on">eval</button>
</div>
</div>
<label class="dd-row"><span class="t-label">env</span>
<select id="trace-env"><option value="">all envs</option></select>
</label>
<label class="toggle dd-row"><input type="checkbox" id="trace-errors"><span class="dot"></span>errors only</label>
</div>
</div>
<select id="trace-sort" title="sort" data-label="sort">
<option value="arrival:desc">arrival ↓</option>
<option value="arrival:asc">arrival ↑</option>
<option value="group:asc">group</option>
<option value="duration:desc">total time ↓</option>
<option value="duration:asc">total time ↑</option>
<option value="reward:desc">reward ↓</option>
<option value="reward:asc">reward ↑</option>
<option value="output_tokens:desc">tokens ↓</option>
</select>
<span id="trace-status" class="muted"></span>
<div class="spacer"></div>
<button id="trace-clear-bin" class="btn" hidden>clear selection</button>
</div>
<div class="controls" id="step-bar" hidden>
<button id="step-prev" class="btn tm-nav" title="previous step">‹</button>
<div id="step-blocks"></div>
<button id="step-next" class="btn tm-nav" title="next step">›</button>
<span id="step-label" class="t-label"></span>
</div>
<div class="controls">
<div id="trace-filter-wrap" class="dd-wrap">
<button id="trace-filter-btn" class="btn dd-btn" title="filter &amp; sort">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
filter
</button>
<div id="trace-filter-menu" class="dd-menu" hidden>
<label class="t-label">env</label>
<select id="trace-env"><option value="">all envs</option></select>
<label class="t-label">sort</label>
<select id="trace-sort">
<option value="line:asc">order: arrival</option>
<option value="reward:desc">reward ↓</option>
<option value="reward:asc">reward ↑</option>
<option value="advantage:desc">advantage ↓</option>
<option value="advantage:asc">advantage ↑</option>
<option value="output_tokens:desc">tokens ↓</option>
<option value="group:asc">group</option>
</select>
<label class="toggle"><input type="checkbox" id="trace-errors"><span class="dot"></span>errors only</label>
</div>
</div>
<div class="seg" id="trace-kind">
<button data-kind="train" class="active">Train</button>
<button data-kind="eval">Eval</button>
</div>
<div class="seg" id="trace-subset">
<button data-subset="all">All</button>
<button data-subset="effective" class="active">Effective</button>
</div>
<span id="trace-status" class="muted"></span>
<div id="trace-chart">
<div class="chart-head"><span class="chart-title">Episodes finished</span><span id="trace-chart-sub" class="muted"></span></div>
<div id="trace-hist"></div>
<div id="hist-tip" hidden></div>
</div>
<div id="episode-table-wrap">
<table id="episode-table">
<thead><tr>
<th>#</th><th>env</th><th>group</th><th>reward</th><th>adv</th>
<th>#</th><th>arrived</th><th>took</th><th>kind</th><th>env</th><th>group</th><th>reward</th>
<th>tok</th><th>turns</th><th>branches</th><th>stop</th><th>status</th>
</tr></thead>
<tbody></tbody>
@@ -165,44 +177,46 @@
<div id="drawer-backdrop" hidden></div>
<div id="trace-modal" hidden>
<aside id="tm-left">
<div class="tm-head tm-stephead">
<div class="tm-head tm-stephead" id="tm-stephead">
<button id="tm-step-prev" class="btn tm-nav" title="previous step">‹</button>
<span id="tm-step-label"></span>
<button id="tm-step-next" class="btn tm-nav" title="next step">›</button>
</div>
<div class="tm-head tm-ctlrow">
<div id="tm-filter-wrap" class="dd-wrap">
<button id="tm-filter-btn" class="btn dd-btn" title="filter &amp; sort">
<button id="tm-filter-btn" class="btn dd-btn" title="filter">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
filter
</button>
<div id="tm-filter-menu" class="dd-menu" hidden>
<label class="t-label">env</label>
<select id="tm-env"><option value="">all envs</option></select>
<label class="t-label">sort</label>
<select id="tm-sort">
<option value="line:asc">order: arrival</option>
<option value="reward:desc">reward ↓</option>
<option value="reward:asc">reward ↑</option>
<option value="advantage:desc">advantage ↓</option>
<option value="advantage:asc">advantage ↑</option>
<option value="output_tokens:desc">tokens ↓</option>
<option value="group:asc">group</option>
</select>
<label class="toggle"><input type="checkbox" id="tm-errors"><span class="dot"></span>errors only</label>
<div class="dd-menu dd-filters" id="tm-filter-menu" hidden>
<div class="dd-sec">filter</div>
<div class="dd-row"><span class="t-label">kind</span>
<div class="seg toggle-seg" id="tm-kinds">
<button data-kind="train" class="on">train</button>
<button data-kind="eval" class="on">eval</button>
</div>
</div>
<label class="dd-row"><span class="t-label">env</span>
<select id="tm-env"><option value="">all envs</option></select>
</label>
<label class="toggle dd-row"><input type="checkbox" id="tm-errors"><span class="dot"></span>errors only</label>
</div>
</div>
<select id="tm-sort" title="sort" data-label="sort">
<option value="arrival:desc">arrival ↓</option>
<option value="arrival:asc">arrival ↑</option>
<option value="group:asc">group</option>
<option value="duration:desc">total time ↓</option>
<option value="duration:asc">total time ↑</option>
<option value="reward:desc">reward ↓</option>
<option value="reward:asc">reward ↑</option>
<option value="output_tokens:desc">tokens ↓</option>
</select>
</div>
<div class="tm-head tm-ctlrow" id="tm-kind-row">
<div class="seg" id="tm-kind">
<button data-kind="train">Train</button>
<button data-kind="eval">Eval</button>
</div>
</div>
<div class="tm-head tm-ctlrow" id="tm-subset-row">
<div class="seg" id="tm-subset">
<button data-subset="all">All</button>
<button data-subset="effective">Effective</button>
<div class="tm-head tm-ctlrow" id="tm-mode-row">
<div class="seg" id="tm-mode">
<button data-mode="stream">Stream</button>
<button data-mode="step">Step</button>
</div>
</div>
<div class="tm-head">
@@ -224,12 +238,14 @@
<button data-mode="messages" class="active">Messages</button>
<button data-mode="rendered">Rendered</button>
</div>
<select id="token-signal" title="Choose the token signal for either view. Text is uncolored; other options color recorded tokens by advantage, log probability, training mask, or message-content membership.">
<select id="token-signal" title="Choose the token signal for either view. Text is uncolored; other options color recorded tokens by advantage, loss/content mask membership, or the trainer's annotations (entropy, the mismatch between its recomputed logprobs and the sampling ones, and the IPO stable mask).">
<option value="">Text</option>
<option value="advantage">Advantage</option>
<option value="logprob">Logprob</option>
<option value="mask">Mask</option>
<option value="is_content">Content</option>
<option value="entropy">Entropy</option>
<option value="mismatch_kl">Mismatch</option>
<option value="stable_mask">Stable mask</option>
<option value="mask">Loss Mask</option>
<option value="is_content">Content Mask</option>
</select>
<button id="tm-collapse" class="btn">collapse</button>
<button id="tm-expand" class="btn">expand</button>
+89 -2
View File
@@ -135,9 +135,26 @@ select:focus, .search:focus { border-color: var(--grey-6); }
.dd-opt:hover { background: var(--grey-2); color: var(--grey-6); }
.dd-opt.active { color: var(--accent); }
.dd-opt.disabled { color: var(--grey-3); cursor: default; }
/* an option with nothing to offer greys out and names its reason */
.dd-opt.unavailable { display: flex; justify-content: space-between; gap: 28px; }
.dd-opt.unavailable:hover { background: none; color: var(--grey-3); }
.dd-why { color: var(--grey-3); }
.dd-note {
padding: 5px 12px 7px;
margin-bottom: 4px;
border-bottom: 1px solid var(--hairline);
font-size: 10px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
color: var(--grey-4);
}
.dd-btn.unavailable { color: var(--grey-4); }
.dd-menu {
position: absolute;
top: 34px;
/* anchor to the trigger's left edge: without it the menu lays out from its
static position and runs off the side of the window */
left: 0;
z-index: 40;
background: var(--grey-1);
border: 1px solid var(--grey-3);
@@ -792,7 +809,8 @@ mark.hit {
.tl-tooltip dd { color: var(--grey-6); margin: 0; }
.tl-tooltip-hint { color: var(--grey-4); border-top: 1px solid var(--hairline); margin-top: 9px; padding-top: 7px; font-size: 9.5px; }
.trace-errors { margin-top: auto; padding-top: 12px; }
/* the banners lead the transcript, so they stand off the first entry */
.trace-errors { margin-top: auto; padding-top: 12px; margin-bottom: 14px; }
.trace-error-banner {
border: 1px solid var(--negative);
background: rgba(255, 69, 57, 0.08);
@@ -892,7 +910,7 @@ details.sub .sub-name { font-weight: 500; color: var(--grey-6); }
details.sub > .entry-body { border-top: 1px solid var(--hairline); }
/* tool definitions are model context, but deliberately sit outside numbered messages */
details.tool-definitions, details.rendered-transcript {
details.tool-definitions, .rendered-transcript {
border: 1px solid var(--grey-3);
margin-bottom: 12px;
background: rgba(183, 166, 250, 0.025);
@@ -1091,3 +1109,72 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
font-size: 12px;
}
#view-toast .toast-text { color: var(--grey-6); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* filter & sort popover */
.dd-filters { min-width: 210px; display: flex; flex-direction: column; gap: 6px; }
.dd-sec {
text-transform: uppercase;
font-size: 10px;
letter-spacing: 0.08em;
color: var(--grey-4);
border-bottom: 1px solid var(--grey-3);
padding-bottom: 3px;
margin-top: 2px;
}
.dd-filters .dd-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin: 0; }
/* controls sit right, sized to their content, so the label reads as the row's subject */
.dd-filters .dd-row select, .dd-filters .dd-row .dd-select, .dd-filters .dd-row .seg { margin-left: auto; }
.dd-filters .dd-row .dd-btn { justify-content: space-between; gap: 8px; }
.dd-filters .t-label { white-space: nowrap; }
/* episodes-finished histogram */
#trace-chart { padding: 8px 12px 4px; border-bottom: 1px solid var(--grey-2); }
#trace-chart .chart-head { display: flex; align-items: baseline; gap: 10px; margin-bottom: 4px; }
#trace-chart .chart-title { font-size: 12px; font-weight: 600; }
#trace-hist { overflow-x: auto; }
#trace-hist svg { display: block; max-width: 100%; }
.hbar { fill: var(--accent); opacity: 0.7; cursor: pointer; }
.hbar:hover { opacity: 1; }
.hbar.on { opacity: 1; fill: #fff; }
.hgrid { stroke: var(--grey-3); stroke-width: 1; vector-effect: non-scaling-stroke; }
.hax { fill: var(--grey-4); font-size: 10px; }
.hval { text-anchor: end; }
#episode-table td.nowrap { white-space: nowrap; }
/* kind filter: each side toggles on its own, so both or one can be shown */
.toggle-seg button { opacity: 0.4; }
.toggle-seg button.on { opacity: 1; color: var(--accent); }
.toggle-seg button.absent.on { color: var(--grey-4); }
/* histogram hover card */
#trace-chart { position: relative; }
#hist-tip {
position: absolute;
z-index: 50;
pointer-events: none;
background: var(--grey-1);
border: 1px solid var(--grey-3);
padding: 6px 8px;
min-width: 150px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
font-size: 11px;
}
#hist-tip .tip-head { color: var(--accent); margin-bottom: 4px; }
#hist-tip .tip-row { display: flex; justify-content: space-between; gap: 14px; }
#hist-tip .tip-row span:first-child { color: var(--grey-4); }
/* the label reads as the button's own name, so it takes the button's colour */
.dd-select .dd-btn .dd-label { text-transform: uppercase; font-weight: 400; color: inherit; }
/* rendered tokens: a header row over the sequence, not a disclosure */
.rendered-head {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
padding: 7px 12px;
background: var(--grey-2);
border-bottom: 1px solid var(--hairline);
}
+66
View File
@@ -0,0 +1,66 @@
"""Checkpoint standalone eval progress cursor."""
from __future__ import annotations
import contextlib
import os
import pickle
import tempfile
import time
from pathlib import Path
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_ckpt_dir, get_step_path
class CheckpointManager:
def __init__(self, output_dir: Path) -> None:
self.ckpt_dir = get_ckpt_dir(output_dir)
def get_ckpt_path(self, step: int) -> Path:
return get_step_path(self.ckpt_dir, step) / "evals"
def latest_step(self) -> int:
steps = [
step for step in get_all_ckpt_steps(self.ckpt_dir) if (self.get_ckpt_path(step) / "progress.pt").is_file()
]
if not steps:
raise FileNotFoundError(f"No evals checkpoints found in {self.ckpt_dir}")
return steps[-1]
def save(self, eval_source: EvalSource) -> None:
cursor = eval_source.cursor
ckpt_path = self.get_ckpt_path(cursor)
ckpt_path.mkdir(parents=True, exist_ok=True)
start = time.perf_counter()
# Replace atomically so resume never observes a partially written pickle.
fd, tmp_name = tempfile.mkstemp(dir=ckpt_path, prefix="progress.pt.", suffix=".tmp")
try:
with os.fdopen(fd, "wb") as f:
pickle.dump(eval_source.state_dict(), f)
os.replace(tmp_name, ckpt_path / "progress.pt")
except BaseException:
with contextlib.suppress(OSError):
os.unlink(tmp_name)
raise
get_logger().debug(
f"Evals checkpoint saved to {ckpt_path} (cursor={cursor}) in {format_time(time.perf_counter() - start)}"
)
def load(
self,
step: int,
eval_source: EvalSource,
path: Path | None = None,
) -> None:
ckpt_path = path if path is not None else self.get_ckpt_path(step)
state_file = ckpt_path / "progress.pt"
if not state_file.is_file():
raise FileNotFoundError(f"Evals checkpoint not found at {state_file}")
get_logger().info(f"Loading evals checkpoint from {state_file}")
with open(state_file, "rb") as f:
state = pickle.load(f)
if state["cursor"] != step:
raise ValueError(f"Evals checkpoint contains cursor {state['cursor']}, expected step {step}")
eval_source.load_state_dict(state)
+61 -4
View File
@@ -35,6 +35,8 @@ from subprocess import Popen
from prime_rl import monitors
from prime_rl.configs.evals import EvalsConfig
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
from prime_rl.evals.ckpt import CheckpointManager
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
@@ -49,7 +51,12 @@ from prime_rl.orchestrator.patches import (
)
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation, Policy
from prime_rl.orchestrator.utils import eval_work, intercept_vf_logging, set_default_executor
from prime_rl.orchestrator.utils import (
episode_group_id,
eval_work,
intercept_vf_logging,
set_default_executor,
)
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
from prime_rl.utils.config import dump_resolved_config
from prime_rl.utils.logger import format_time, get_logger, setup_logger
@@ -84,6 +91,8 @@ class Evals:
# The last weight-checkpoint step already handled (evaluated or skipped).
self.last_step = (config.online.resume_step if config.online is not None else None) or 0
self.eval_triggered_at: dict[tuple[str, int], float] = {}
self.ckpt_manager = CheckpointManager(config.output_dir)
self.last_saved_cursor = 0
self.env_server_procs: list[Popen] = []
self.dispatcher_task: asyncio.Task | None = None
@@ -147,6 +156,20 @@ class Evals:
is_resumed = config.online is not None and config.online.resume_step is not None
self.eval_source = EvalSource(self.eval_envs, config.eval, is_resumed=is_resumed)
self.eval_sink = EvalSink(eval_envs=self.eval_envs)
if config.resume is not None:
if config.resume.dir is not None:
resume_step = config.resume.dir_step
resume_path = config.resume.dir / "evals"
else:
resume_step = config.resume.step or self.ckpt_manager.latest_step()
resume_path = None
self.ckpt_manager.load(
resume_step,
self.eval_source,
path=resume_path,
)
self.last_saved_cursor = self.eval_source.cursor
get_logger().info(f"Resuming evals from task cursor {self.eval_source.cursor}")
self.policy = Policy(version=0, model_name=config.model)
# Pessimistic per-episode token cost for the controller's starting cap,
@@ -253,6 +276,8 @@ class Evals:
else:
await self.watch()
self.maybe_save_checkpoint(force=True)
# The periodic logger and the collector log to the W&B run, so they
# must stop before finalize marks the run finished.
await self.periodic_logger.stop()
@@ -379,12 +404,17 @@ class Evals:
if not fired:
return
for env_name in fired:
task_count = self.eval_source.triggered_task_count(env_name, step)
self.eval_sink.set_batch_size(env_name, step, task_count * self.eval_sink.group_size_for(env_name))
now = time.perf_counter()
for env_name in fired:
self.eval_triggered_at[(env_name, step)] = now
total_rollouts = sum(
self.eval_envs.get(env_name).config.group_size * len(self.eval_envs.get(env_name).examples)
for env_name in fired
self.eval_envs.get(request.env_name).config.group_size
for request in self.eval_source.queue
if request.step == step and request.env_name in fired
)
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
@@ -397,7 +427,7 @@ class Evals:
async def consume_epoch(self, fired: list[str], step: int) -> None:
"""Consume one epoch, preempting it when a newer checkpoint is ready."""
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name) > 0}
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name, step) > 0}
cancellation_task: asyncio.Task[int] | None = None
superseding_step: int | None = None
online = self.config.online
@@ -428,15 +458,30 @@ class Evals:
if isinstance(item, GroupCancellation):
eval_batch = self.eval_sink.cancel(item)
group_completed = False
group_id = item.group_id
elif isinstance(item, DispatchFailure):
eval_batch = self.eval_sink.fail(item)
group_completed = not self.eval_sink.has_pending_group(item.group_id)
group_id = item.group_id
else:
item_step = eval_work(item).step
stamp_arrival([item], "eval", item_step)
await monitors.log([item], item_step, "eval", "all")
eval_batch = self.eval_sink.add(item)
group_id = episode_group_id(item)
group_completed = not self.eval_sink.has_pending_group(group_id)
if eval_batch is not None:
await self.finalize_eval_batch(eval_batch)
pending.discard(eval_batch.env_name)
if group_completed:
source_index = self.dispatcher.pop_source_index(group_id)
if self.config.online is not None:
continue
if source_index is None:
raise RuntimeError(f"Eval group {group_id} is missing its source cursor")
if self.eval_source.mark_completed(source_index):
self.maybe_save_checkpoint()
if cancellation_task is not None:
cancelled = await cancellation_task
@@ -445,6 +490,17 @@ class Evals:
f"advancing to checkpoint {superseding_step}"
)
def maybe_save_checkpoint(self, *, force: bool = False) -> None:
if self.config.ckpt is None:
return
cursor = self.eval_source.cursor
if cursor <= 0 or cursor == self.last_saved_cursor:
return
if not force and cursor - self.last_saved_cursor < self.config.ckpt.interval:
return
self.ckpt_manager.save(self.eval_source)
self.last_saved_cursor = cursor
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch through the monitors, mirroring the
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
@@ -454,6 +510,7 @@ class Evals:
if batch.episodes.effective:
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
await monitors.log_annotations(stamp_batch(batch.episodes.effective.vf_episodes, batch.step))
episodes = batch.episodes
effective = episodes.effective
+246 -2
View File
@@ -17,6 +17,26 @@ def apply_shared_vllm_patches():
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_per_layer_rope()
monkey_patch_deepseek_v4_bf16_o_proj()
def monkey_patch_deepseek_v4_allowed_layer_types():
"""Let vLLM's `DeepseekV4Config` construct under a transformers pin below 5.15.
`vllm/transformers_utils/configs/deepseek_v4.py` leaves `layer_types` to
`PretrainedConfig`, whose validator checks it against a vocabulary that only gained V4's
compressed attention names in transformers 5.15, so `AutoConfig.from_pretrained` on any
DeepSeek V4 checkpoint raises. vLLM declares `transformers>=5.5.3`, so this is a gap in
upstream's own version floor rather than something prime-rl introduced.
`EngineArgs.__post_init__` loads general plugins before `create_model_config`, which is why
patching here is early enough. The trainer applies the same shim on its own import path.
"""
from prime_rl.utils.transformers_compat import allow_deepseek_v4_layer_types
allow_deepseek_v4_layer_types()
def monkey_patch_online_fp8_parameter_cast():
@@ -104,6 +124,110 @@ def monkey_patch_kv_xfer_finished_tolerate_freed():
logger.warning("Patched Scheduler._update_from_kv_xfer_finished to tolerate freed (aborted) KV-transfer reqs.")
def monkey_patch_deepseek_v4_bf16_o_proj():
"""Run DeepSeek V4's output projection in bf16 when the weights are not FP8.
vLLM's DeepSeek V4 output projection is FP8-only. All three CUDA attention
classes (``DeepseekV4FlashMLAAttention``,
``DeepseekV4FlashInferMLAAttention``, ``DeepseekV4FlashInferSM120Attention``)
implement ``_o_proj`` by calling ``deep_gemm_fp8_o_proj``
(``vllm/models/deepseek_v4/nvidia/ops/o_proj.py``), which dereferences
``wo_a.weight_scale``, falling back to ``wo_a.weight_scale_inv``, and hands
the result to DeepGEMM's ``fp8_einsum``. There is no branch on quant config
or weight dtype, and ``_o_proj`` is an ``@abstractmethod`` dispatched purely
by platform subclass, so no attention backend routes around it. A bf16
checkpoint has neither attribute and therefore fails with
``AttributeError: 'ColumnParallelLinear' object has no attribute
'weight_scale_inv'``.
Quantizing is not an answer, because nothing quantizes by default:
``[inference.vllm] quantization`` is unset, which leaves vLLM to infer the
scheme from the checkpoint. bf16 DeepSeek V4 checkpoints are a first-class
artifact here, written by ``tools/convert_fp8_to_bf16.py``,
``tools/convert_dcp_to_bf16.py``, and trainer exports, and they carry no
scales for the op to find. Passing ``--quantization fp8_per_block`` does
produce a correct ``weight_scale_inv`` and is a genuine alternative on
hardware whose DeepGEMM build has block-scaled FP8 kernels, but it changes
the served numerics, so it is a deployment decision rather than a fix for
serving the bf16 weights as given.
Only the unquantized case is redirected: an FP8 weight keeps using vLLM's own
kernel, so a real FP8-serialized checkpoint behaves exactly as before. The
condition is the weight dtype rather than the presence of
``weight_scale_inv``, so a checkpoint that *is* quantized but whose scales
ended up in the wrong layout still fails loudly instead of being silently
rerouted.
The replacement mirrors the Triton kernel's arithmetic
(``vllm/models/deepseek_v4/common/ops/fused_inv_rope_fp8_quant.py:95-105``)
without the quantization step. The trailing ``rope_dim`` channels of each head
carry an inverse RoPE over interleaved pairs, with ``cos_sin_cache`` holding
``rope_dim // 2`` cosines followed by the matching sines:
y[even] = x[even] * cos + x[odd] * sin
y[odd] = x[odd] * cos - x[even] * sin
The remaining ``nope_dim`` channels pass through. The projection is the same
grouped contraction ``fp8_einsum`` performs, with the group axis recovered by
reshaping: head ``g * heads_per_group + i`` belongs to group ``g`` at offset
``i * head_dim``, matching the kernel's own
``g = pid_gh // heads_per_group`` indexing.
Rotation is computed in fp32 and the contraction runs in bf16, whose CUDA
matmuls accumulate in fp32. That is strictly more accurate than the FP8 path
it replaces, and it avoids materializing an fp32 copy of the attention output.
"""
from vllm.models.deepseek_v4.nvidia import flashinfer_sparse, flashmla
from vllm.models.deepseek_v4.nvidia.ops import o_proj as o_proj_module
original_o_proj = o_proj_module.deep_gemm_fp8_o_proj
if getattr(original_o_proj, "_prime_rl_has_bf16_fallback", False):
return
def _inverse_rope(o, positions, cos_sin_cache, rope_dim):
num_tokens, num_heads, head_dim = o.shape
half_rope = rope_dim // 2
cos_sin = cos_sin_cache[positions].float()
cos = cos_sin[:, :half_rope].view(num_tokens, 1, half_rope)
sin = cos_sin[:, half_rope:].view(num_tokens, 1, half_rope)
rotated = o[:, :, head_dim - rope_dim :].float().reshape(num_tokens, num_heads, half_rope, 2)
even, odd = rotated[..., 0], rotated[..., 1]
pairs = torch.stack((even * cos + odd * sin, odd * cos - even * sin), dim=-1)
out = o.clone()
out[:, :, head_dim - rope_dim :] = pairs.reshape(num_tokens, num_heads, rope_dim).to(o.dtype)
return out
def _patched_o_proj(o, positions, cos_sin_cache, wo_a, wo_b, *, n_groups, heads_per_group, **kwargs):
if wo_a.weight.dtype == torch.float8_e4m3fn:
return original_o_proj(
o,
positions,
cos_sin_cache,
wo_a,
wo_b,
n_groups=n_groups,
heads_per_group=heads_per_group,
**kwargs,
)
x = _inverse_rope(o, positions, cos_sin_cache, kwargs["rope_dim"])
x = x.reshape(o.shape[0], n_groups, heads_per_group * o.shape[-1])
weight = wo_a.weight.view(n_groups, kwargs["o_lora_rank"], -1)
z = torch.einsum("tgr,gdr->tgd", x, weight)
return wo_b(z.flatten(1))
_patched_o_proj._prime_rl_has_bf16_fallback = True
o_proj_module.deep_gemm_fp8_o_proj = _patched_o_proj
# Both attention modules did `from ...ops.o_proj import deep_gemm_fp8_o_proj` at
# import time, so patching the defining module alone would not reach the names
# their `_o_proj` methods actually call.
flashmla.deep_gemm_fp8_o_proj = _patched_o_proj
flashinfer_sparse.deep_gemm_fp8_o_proj = _patched_o_proj
def monkey_patch_nano_v3_reasoning_parser():
from vllm.reasoning.abs_reasoning_parsers import ReasoningParserManager
from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser
@@ -234,8 +358,7 @@ def monkey_patch_return_routed_experts_with_nixl_connector():
raise ValueError("--enable-return-routed-experts is incompatible with pipeline parallelism (PP > 1).")
if config.use_v2_model_runner:
raise ValueError(
"The V2 model runner does not support routed experts capture - "
"set VLLM_USE_V2_MODEL_RUNNER=0 (the prime-rl launcher does this automatically)."
"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
@@ -724,3 +847,124 @@ def monkey_patch_dp_coordinator_startup_timeout():
zmq_addr_pipe.close()
DPCoordinator._wait_for_zmq_addrs = _patched_wait_for_zmq_addrs
_DEEPSEEK_V4_YARN_ROPE_TYPES = frozenset({"yarn", "deepseek_yarn", "deepseek_llama_scaling"})
def _deepseek_v4_rope_parameters(rope_parameters, *, compress_ratio, max_position_embeddings):
"""Flat, single-layer rope parameters for `build_deepseek_v4_rope`.
Handles both on-disk schemas. The real checkpoint ships a flat legacy `rope_scaling`, which
vLLM's config shim normalizes in place. HF's own `DeepseekV4Config` nests the parameters
under `main`/`compress` rope-type labels instead, and so does this repo's port. vLLM's shim
cannot read that: `is_rope_parameters_nested` only recognizes nesting by *attention* layer
type, so transformers leaves the sub-dicts alone and injects a top-level
`rope_type="default"` beside them. Upstream then builds unscaled RoPE for every layer and
hands `get_rope` a cache key containing a dict, which is unhashable. Selecting the branch
this layer wants resolves both. Upstream picks the base from `config.rope_theta` /
`config.compress_rope_theta` on its own either way.
"""
rope_parameters = rope_parameters if isinstance(rope_parameters, dict) else {}
# `compress_ratio` is already clamped to >= 1 by the caller, so <= 1 is "no compressor",
# i.e. the reference's `else` branch. vLLM lumps the MTP layers in here too.
is_sliding = compress_ratio <= 1
if any(isinstance(value, dict) for value in rope_parameters.values()):
label = "main" if is_sliding else "compress"
branch = rope_parameters.get(label)
if not isinstance(branch, dict):
raise ValueError(
f"DeepSeek V4 rope_parameters is nested by rope type but has no {label!r} "
f"sub-dict; found {sorted(rope_parameters)}."
)
parameters = dict(branch)
else:
parameters = dict(rope_parameters)
rope_type = parameters.get("rope_type", parameters.get("type", "default"))
if is_sliding or rope_type not in _DEEPSEEK_V4_YARN_ROPE_TYPES:
# Plain RoPE, written as YaRN with `factor=1` rather than as `rope_type="default"`.
# The table is the same either way, since `_compute_inv_freq`'s interpolated and
# extrapolated frequencies coincide at `factor=1` and `yarn_get_mscale` returns 1.0,
# but `"default"` would route `get_rope` to a plain `RotaryEmbedding`, whose cache
# follows the ambient dtype and so fails the fp32 assertion in
# `vllm/models/deepseek_v4/common/ops/fused_inv_rope_fp8_quant.py`.
# `original_max_position_embeddings` is widened because the cache is
# `original_max * factor` rows and must still span the context.
rope_type = "yarn"
parameters["factor"] = 1
parameters["original_max_position_embeddings"] = max_position_embeddings
parameters["rope_type"] = rope_type
return parameters
def monkey_patch_deepseek_v4_per_layer_rope():
"""Give each DeepSeek V4 layer the RoPE its reference implementation uses.
DeepSeek ships the reference inside the checkpoint we serve, at
https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-0731/tree/main/inference. Its
`model.py:481-485` picks the frequencies per layer:
if self.compress_ratio:
original_seq_len, rope_theta = args.original_seq_len, args.compress_rope_theta
else:
# disable YaRN and use base rope_theta in pure sliding-window attention
original_seq_len, rope_theta = 0, args.rope_theta
and `precompute_freqs_cis` (`model.py:206-235`) applies the NTK-by-parts ramp only when
`original_seq_len > 0`. So a pure sliding-window layer gets plain RoPE at `rope_theta` and
every compressed layer gets YaRN at `compress_rope_theta`. HF's `DeepseekV4Config` splits its
`rope_parameters` into `main`/`compress` for the same reason, and so does this repo's trainer.
`vllm/models/deepseek_v4/common/rope.py`'s `build_deepseek_v4_rope` branches the base on
`compress_ratio` but never the scaling, so on the real checkpoint it hands YaRN to layers 0
and 1 as well. No config value can correct that: `rope_type` is one global field there.
So this patch resolves `rope_parameters` per layer instead, which also gives upstream a
schema and a dtype it can handle; see `_deepseek_v4_rope_parameters` above.
Measured against the reference's own frequencies, at the test's `factor=16`,
`original_max_position_embeddings=4096` geometry, this takes the sliding layers from 5.1e-03
max absolute error to 6e-08, the float32 residual the compressed layers already have. The
rope tests in `tests/unit/train/models/test_deepseek_v4.py` are that comparison, over both
on-disk schemas and both scaled and unscaled configs.
Note that nothing in vLLM's DeepSeek V4 calls the module's `forward`; every consumer reads
`cos_sin_cache` and hands it to a fused kernel. The class choice is therefore about the
cache's dtype and row count, not about which channels the module would rotate.
"""
from vllm.models.deepseek_v4.common import rope as dsv4_rope
original_build = dsv4_rope.build_deepseek_v4_rope
if getattr(original_build, "_prime_rl_matches_deepseek_reference", False):
return
def _patched_build(config, *, head_dim, rope_head_dim, max_position_embeddings, compress_ratio):
# Swapping a copy in also spares `config.rope_parameters` upstream's in-place mutation,
# which otherwise leaves the last-built layer's `rope_theta` on the shared config.
original_parameters = config.rope_parameters
config.rope_parameters = _deepseek_v4_rope_parameters(
original_parameters,
compress_ratio=compress_ratio,
max_position_embeddings=max_position_embeddings,
)
try:
return original_build(
config,
head_dim=head_dim,
rope_head_dim=rope_head_dim,
max_position_embeddings=max_position_embeddings,
compress_ratio=compress_ratio,
)
finally:
config.rope_parameters = original_parameters
_patched_build._prime_rl_matches_deepseek_reference = True
dsv4_rope.build_deepseek_v4_rope = _patched_build
# `attention.py` imports the builder into its own namespace, so the defining module alone
# would not reach the already-bound reference.
from vllm.models.deepseek_v4 import attention as dsv4_attention
dsv4_attention.build_deepseek_v4_rope = _patched_build
+9 -5
View File
@@ -10,11 +10,15 @@ 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")
# Router replay needs the V1 GPU model runner: V2 silently never captures
# routed experts. Everything else follows vLLM's own V1/V2 resolution.
# setdefault so it stays overridable.
if config.vllm.enable_return_routed_experts:
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
# 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:
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
+9
View File
@@ -122,6 +122,15 @@ async def log(
get_logger().warning(f"Failed to log to {monitor.__class__.__name__}: {e}")
async def log_annotations(updates: list[dict[str, Any]]) -> None:
"""Log trace updates to all registered monitors."""
for monitor in MONITORS:
try:
await monitor.log_annotations(updates)
except Exception as e:
get_logger().warning(f"Failed to log to {monitor.__class__.__name__}: {e}")
async def finalize() -> None:
"""Finalize the run on all registered monitors."""
for monitor in MONITORS:
+4
View File
@@ -53,5 +53,9 @@ class Monitor(ABC):
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
"""Log episodes."""
async def log_annotations(self, updates: list[dict[str, Any]]) -> None:
"""Log trace updates — post-hoc facts about traces this run already logged.
Monitors that only carry scalars ignore them."""
async def finalize(self) -> None:
"""Finalize run."""
-67
View File
@@ -1,67 +0,0 @@
from __future__ import annotations
import asyncio
import json
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any, TextIO
import orjson
from prime_rl.configs.monitors import FileMonitorConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.utils.utils import sanitize
if TYPE_CHECKING:
import verifiers.v1 as vf
class FileMonitor(Monitor):
"""Logs metrics and episodes to local JSONL files."""
config: FileMonitorConfig
file: TextIO
async def init(self, output_dir: Path, producer: str | None = None) -> None:
self.output_dir = output_dir
self.producer = producer
self.path = output_dir / self.config.path
self.path.parent.mkdir(parents=True, exist_ok=True)
# Line-buffered append so a concurrently-running dashboard can tail the file.
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
self.logger.info(f"Logging metrics and episodes to the local filesystem ({output_dir})")
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
"""``step=None`` logs a time-keyed row (e.g. inference metrics, which are
sampled on wall time rather than the training step)."""
sanitized, dropped = sanitize(metrics)
if dropped:
self.logger.warning(
f"Dropping {len(dropped)} non-finite value(s) from {self.config.path}: {', '.join(dropped[:5])}"
)
row = {"step": step, "time": time.time(), **sanitized}
if self.producer is not None:
row["producer"] = self.producer
self.file.write(json.dumps(row) + "\n")
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
"""Append the cohort to its per-step episode file. ``all`` grows one
episode at a time as they complete, ``effective`` one batch at a time on finalize,
so an in-progress run can be inspected live. Episode-level failures are
preserved even when no trace was produced."""
def write() -> None:
path = self.output_dir / "rollouts" / f"step_{step}" / kind / subset / "traces.jsonl"
path.parent.mkdir(parents=True, exist_ok=True)
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
with open(path, "ab") as f:
for episode in episodes:
f.write(orjson.dumps(episode.to_record(), default=str, option=opts))
# Record serialization is heavy pure-Python work; keep it off the event loop.
# Awaited (not fire-and-forget) so appends to one file never interleave.
await asyncio.to_thread(write)
async def finalize(self) -> None:
self.logger.info(f"Finalized metrics at {self.path}")
+3
View File
@@ -0,0 +1,3 @@
from prime_rl.monitors.file.monitor import FileMonitor
__all__ = ["FileMonitor"]
+115
View File
@@ -0,0 +1,115 @@
from __future__ import annotations
import asyncio
import json
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any, BinaryIO, TextIO
import orjson
from prime_rl.configs.monitors import FileMonitorConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.monitors.file.traces import get_annotations_dir, get_index_path, get_trace_stream
from prime_rl.monitors.file.traces.chunks import ChunkedJsonl
from prime_rl.monitors.file.traces.index import index_row
from prime_rl.monitors.file.traces.update import update_index_row
from prime_rl.utils.pathing import get_file_monitor_dir
from prime_rl.utils.utils import sanitize
if TYPE_CHECKING:
import verifiers.v1 as vf
OPTS = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
class FileMonitor(Monitor):
"""Logs metrics and episodes to local JSONL files."""
config: FileMonitorConfig
file: TextIO
async def init(self, output_dir: Path, producer: str | None = None) -> None:
self.output_dir = output_dir
self.producer = producer
index = get_index_path(get_trace_stream(output_dir))
# a relaunch appends to the stream it finds, so the numbering carries on
self._logged = sum(1 for _ in index.open("rb")) if index.is_file() else 0
self.path = get_file_monitor_dir(output_dir) / self.config.path
self.path.parent.mkdir(parents=True, exist_ok=True)
# Line-buffered append so a concurrently-running dashboard can tail the file.
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
self._streams: dict[Path, tuple[ChunkedJsonl, BinaryIO]] = {}
self.logger.info(f"Logging metrics and episodes to the local filesystem ({output_dir})")
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
"""``step=None`` logs a time-keyed row (e.g. inference metrics, which are
sampled on wall time rather than the training step)."""
sanitized, dropped = sanitize(metrics)
if dropped:
self.logger.warning(
f"Dropping {len(dropped)} non-finite value(s) from {self.config.path}: {', '.join(dropped[:5])}"
)
row = {"step": step, "time": time.time(), **sanitized}
if self.producer is not None:
row["producer"] = self.producer
self.file.write(json.dumps(row) + "\n")
def _stream(self, directory: Path) -> tuple[ChunkedJsonl, BinaryIO]:
"""A stream and its index, opened on first use and kept open. Writers flush the
stream before the index: a row a reader sees points at a record it can read."""
if directory not in self._streams:
stream = ChunkedJsonl(directory, self.config.chunk_bytes, self.config.compress)
self._streams[directory] = (stream, open(get_index_path(directory), "ab"))
return self._streams[directory]
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
"""Append each episode to the trace stream as it completes — every episode is
serialized exactly once, in arrival order, whatever its kind, so an in-progress
run can be tailed. Episode-level failures are preserved even when no trace was
produced. The shipped cohort writes no second copy: what it learns arrives as
annotations that readers fold back onto the stream."""
if subset == "effective":
return
def write() -> None:
stream, index = self._stream(get_trace_stream(self.output_dir))
# An index row goes out with every episode: summarising the record here,
# while it is already in hand, saves every reader from parsing a stream
# that outgrows memory long before the run does.
for episode in episodes:
record = episode.to_record(float_decimals=self.config.float_decimals)
chunk, offset = stream.append(orjson.dumps(record, default=str, option=OPTS))
self._logged += 1
index.write(orjson.dumps(index_row(self._logged, record, chunk, offset), default=str, option=OPTS))
stream.flush()
index.flush()
# Record serialization is heavy pure-Python work; keep it off the event loop.
# Awaited (not fire-and-forget) so appends to one stream never interleave.
await asyncio.to_thread(write)
async def log_annotations(self, updates: list[dict[str, Any]]) -> None:
"""Append trace updates to this producer's annotation stream — one writer per
stream, so producers never interleave."""
if not updates:
return
def write() -> None:
stream, index = self._stream(get_annotations_dir(self.output_dir) / (self.producer or "unknown"))
# the scalars go to a sibling index so a reader can answer "which cohort,
# what credit" without touching the token streams
for update in updates:
chunk, offset = stream.append(orjson.dumps(update, option=OPTS))
index.write(orjson.dumps(update_index_row(update, chunk, offset), option=OPTS))
stream.flush()
index.flush()
await asyncio.to_thread(write)
async def finalize(self) -> None:
for stream, index in self._streams.values():
stream.close()
index.close()
self.logger.info(f"Finalized metrics at {self.path}")
@@ -0,0 +1,33 @@
"""Where the file monitor puts the traces, and everything written about them.
The stream and its annotations live under one directory so nothing beside them has to
be read as belonging to them. Each stream is a directory of chunks (see ``chunks``),
and every index is named for the stream it indexes and sits beside it.
"""
from pathlib import Path
from prime_rl.utils.pathing import get_file_monitor_dir
def get_trace_dir(output_dir: Path) -> Path:
return get_file_monitor_dir(output_dir) / "traces"
def get_trace_stream(output_dir: Path) -> Path:
"""Every episode, appended as it arrives."""
return get_trace_dir(output_dir) / "stream"
def get_annotations_dir(output_dir: Path) -> Path:
"""One stream per producer of trace updates: orch ship-time facts, trainer streams."""
return get_trace_dir(output_dir) / "annotations"
def get_index_path(stream: Path) -> Path:
"""A stream's index, beside it, so a reader pairs the two without knowing who
wrote them."""
return stream.with_name(stream.name.removesuffix(".jsonl") + ".index.jsonl")
__all__ = ["get_annotations_dir", "get_index_path", "get_trace_dir", "get_trace_stream"]
+115
View File
@@ -0,0 +1,115 @@
"""Chunked JSONL — an append-only stream split into numbered files, sealed as it grows.
stream/00000.jsonl.zst sealed: zstd in seekable frames, so a reader still lands on one line
stream/00001.jsonl live: plain text, so it can be tailed
A line never spans chunks. Once a chunk reaches its size the writer moves on and seals it
in the background: the compressed twin is written beside it and the plain file removed
only once the twin is complete, so a reader that misses the plain file finds the sealed
one. ``zstd -dcf stream/* | jq`` reads a whole stream, sealed and live alike.
"""
import shutil
import threading
from pathlib import Path
from typing import BinaryIO
import pyzstd
LEVEL = 3
"""zstd level: ~7x on episode records at hundreds of MB/s, so sealing keeps up with a run."""
FRAME_BYTES = 4 << 20
"""Independent frames in a sealed chunk: a seek decompresses one of these, not the chunk."""
def chunk_path(directory: Path, number: int) -> Path:
return directory / f"{number:05d}.jsonl"
def chunk_numbers(directory: Path) -> dict[int, bool]:
"""Chunk number -> whether its plain file is present (a sealed chunk has none)."""
numbers: dict[int, bool] = {}
for path in directory.glob("*.jsonl*"):
number = int(path.name.split(".", 1)[0])
numbers[number] = numbers.get(number, False) or path.suffix == ".jsonl"
return numbers
def open_chunk(directory: Path, number: int) -> BinaryIO:
"""A chunk for seeking reads, whether still plain or already sealed."""
path = chunk_path(directory, number)
try:
return open(path, "rb")
except FileNotFoundError:
return pyzstd.SeekableZstdFile(path.with_name(path.name + ".zst"), "rb")
def seal(path: Path) -> None:
"""Compress a finished chunk beside itself, then drop the plain file."""
target = path.with_name(path.name + ".zst")
partial = target.with_name(target.name + ".tmp")
with (
open(path, "rb") as src,
pyzstd.SeekableZstdFile(partial, "wb", level_or_option=LEVEL, max_frame_content_size=FRAME_BYTES) as dst,
):
shutil.copyfileobj(src, dst, 1 << 20)
partial.replace(target)
path.unlink()
class ChunkedJsonl:
"""Appends lines to the live chunk of a stream and reports where each one landed."""
def __init__(self, directory: Path, max_bytes: int, compress: bool) -> None:
directory.mkdir(parents=True, exist_ok=True)
self.directory = directory
self.max_bytes = max_bytes
self.compress = compress
self._sealing: list[threading.Thread] = []
numbers = chunk_numbers(directory)
last = max(numbers, default=-1)
# A relaunch appends to the live chunk it finds and starts a new one after a sealed
# last chunk; anything else still plain was left mid-seal by a crash.
self.number = last if numbers.get(last) else last + 1
for number, plain in numbers.items():
if plain and number != self.number and compress:
self._seal(number)
self.file = open(chunk_path(directory, self.number), "ab")
self.size = self.file.tell()
def append(self, line: bytes) -> tuple[int, int]:
"""Write one line; returns ``(chunk, offset)``, the address a reader seeks to."""
if self.size and self.size + len(line) > self.max_bytes:
self._roll()
offset = self.size
self.file.write(line)
self.size += len(line)
return self.number, offset
def flush(self) -> None:
self.file.flush()
def close(self) -> None:
"""Seal the live chunk too, so a finished run keeps nothing plain."""
self.file.close()
if not self.size:
chunk_path(self.directory, self.number).unlink()
elif self.compress:
self._seal(self.number)
for thread in self._sealing:
thread.join()
def _roll(self) -> None:
self.file.close()
if self.compress:
self._seal(self.number)
self.number += 1
self.file = open(chunk_path(self.directory, self.number), "ab")
self.size = 0
def _seal(self, number: int) -> None:
# not a daemon: a process that exits mid-seal waits for it rather than leaving a torn twin
thread = threading.Thread(target=seal, args=(chunk_path(self.directory, number),))
thread.start()
self._sealing.append(thread)
+134
View File
@@ -0,0 +1,134 @@
"""The episode index - one compact row per episode, so a reader never has to parse
the stream to browse it.
The file monitor writes a row as each episode lands, when the record is already in
hand and summarising it is nearly free, and records the chunk and byte offset it wrote
the episode at so a reader can seek straight to one. A stream another producer wrote
has no index, so its reader derives the same rows itself.
"""
def walk_timing(obj: dict, prefix: str, out: dict[str, float]) -> None:
"""Flatten a trace timing tree to phase -> seconds (same walk as the viewer)."""
if isinstance(obj.get("duration"), (int, float)):
out[prefix] = out.get(prefix, 0.0) + obj["duration"]
elif isinstance(obj.get("start"), (int, float)) and isinstance(obj.get("end"), (int, float)):
out[prefix] = out.get(prefix, 0.0) + (obj["end"] - obj["start"])
for key, value in obj.items():
if isinstance(value, dict):
walk_timing(value, f"{prefix}/{key}" if prefix else key, out)
def episode_kind(rec: dict) -> str:
"""The kind of work an episode did. The file monitor stamps it as the episode
lands; a stream written by another producer (a verifiers ``uv run eval`` run) is
read off its run info instead."""
for trace in rec.get("traces") or []:
if (kind := (trace.get("info") or {}).get("kind")) in ("train", "eval"):
return kind
run = rec.get("run") or {}
return (run.get("work") or {}).get("type") or run.get("type") or "eval"
def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
"""One index row: what the table, the filters, the chart and the sort need.
``line`` numbers the episode within the stream from 1, so the last of n reads as
n — it is what a reader sees and what addresses the episode."""
rewards, advantages = [], []
input_tokens = output_tokens = turns = branches = 0
stop_condition = None
reward_parts: dict[str, list[float]] = {}
metric_parts: dict[str, list[float]] = {}
timing: dict[str, float] = {}
costs: list[float] = []
for trace in rec.get("traces") or []:
costs.extend(
usage["cost"]
for call in trace.get("calls") or []
if isinstance(usage := call.get("usage") or {}, dict) and isinstance(usage.get("cost"), (int, float))
)
nodes = trace.get("nodes") or []
parents = {node.get("parent") for node in nodes if "parent" in node}
branches += max(0, len(nodes) - len(parents))
if trace.get("rewards"): # skip reward-less seats (e.g. a judge) in the episode mean
rewards.append(
sum(
(r.get("score") or 0) * (r.get("weight") if r.get("weight") is not None else 1)
for r in trace["rewards"].values()
if isinstance(r, dict)
)
)
for name, r in (trace.get("rewards") or {}).items():
if isinstance(r, dict) and isinstance(r.get("score"), (int, float)):
reward_parts.setdefault(name, []).append(r["score"])
for name, value in (trace.get("metrics") or {}).items():
if isinstance(value, (int, float)):
metric_parts.setdefault(name, []).append(value)
if isinstance(trace.get("timing"), dict):
walk_timing(trace["timing"], "", timing)
advantage = (trace.get("info") or {}).get("advantage")
if advantage is not None:
advantages.append(advantage)
for node in nodes:
n_tokens = len(node.get("token_ids") or [])
if node.get("sampled"):
output_tokens += n_tokens
else:
input_tokens += n_tokens
if (node.get("message") or {}).get("role") == "assistant":
turns += 1
stop_condition = trace.get("stop_condition", stop_condition)
if input_tokens == 0 and output_tokens == 0: # some eval traces carry no token arrays
for call in trace.get("calls") or []:
usage = call.get("usage") or {}
input_tokens += usage.get("prompt_tokens") or 0
output_tokens += usage.get("completion_tokens") or 0
first_info = ((rec.get("traces") or [{}])[0].get("info")) or {}
return {
"rewards": {name: sum(v) / len(v) for name, v in reward_parts.items()},
"metrics": {name: sum(v) / len(v) for name, v in metric_parts.items()},
"timing": timing,
"cost": sum(costs) if costs else None,
"line": line,
"offset": offset,
"id": rec.get("id"),
"kind": episode_kind(rec),
"trace_ids": [trace_id for trace in rec.get("traces") or [] if (trace_id := trace.get("id"))],
"env": (rec.get("env") or {}).get("id") or (rec.get("env") or {}).get("name"),
"group": (rec.get("group") or {}).get("id"),
"ok": rec.get("ok"),
"num_errors": len(rec.get("errors") or []),
"reward": sum(rewards) / len(rewards) if rewards else None,
"advantage": sum(advantages) / len(advantages) if advantages else None,
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"turns": turns,
"branches": branches,
"stop_condition": stop_condition,
# when the episode landed and how long it was alive: the stream's x axis,
# and the one duration worth sorting a stream by
"arrival": (first_info.get("arrival") or {}).get("time"),
"duration": _episode_duration(first_info, timing),
}
def _episode_duration(info: dict, timing: dict[str, float]) -> float | None:
"""Wall-clock seconds from dispatch to arrival, or the summed phases for a record
that predates those stamps."""
dispatched = (info.get("dispatch") or {}).get("time")
arrived = (info.get("arrival") or {}).get("time")
if isinstance(dispatched, (int, float)) and isinstance(arrived, (int, float)):
return max(0.0, arrived - dispatched)
phases = [value for key, value in timing.items() if "/" not in key]
return sum(phases) if phases else None
def index_row(line: int, rec: dict, chunk: int, offset: int) -> dict:
"""The row the file monitor writes. The nested reward/metric/timing maps are left
out: only the per-episode series view needs them, and they dominate the size."""
row = summarize_episode(line, rec, offset)
row["chunk"] = chunk
for key in ("rewards", "metrics", "timing"):
row.pop(key, None)
return row
+100
View File
@@ -0,0 +1,100 @@
"""Trace updates — post-hoc facts about a completed trace, recorded beside it.
An episode is serialized once, when it arrives. Everything a consumer learns later
is an update naming the trace: an ``info`` dict merged into the trace's own, plus
per-token streams over a branch, full-length across the branch's token prefix (nulls
mark unknown positions, so a stream never depends on the producer's loss mask).
Each producer appends its own stream under the trace directory's ``annotations/``, so
every stream has exactly one writer. Readers fold the updates onto the arrival records
in write order, newest wins.
"""
from typing import Any
UPDATE_VERSION = 1
STREAM_FIELDS = ("advantages", "trainer_logprobs", "entropies")
"""Per-token streams an update may carry, compacted onto node fields of the same name."""
def update_index_row(update: dict[str, Any], chunk: int, offset: int) -> dict[str, Any]:
"""An update's scalars plus where its record sits. The per-token streams stay in
the annotation stream: a reader browsing a run needs the scalars, and only the
episode it opens needs the streams."""
return {"trace_id": update.get("trace_id"), "chunk": chunk, "offset": offset, "info": update.get("info") or {}}
def make_update(
trace_id: str,
*,
info: dict[str, Any] | None = None,
branches: dict[int, dict[str, list]] | None = None,
) -> dict[str, Any]:
"""One update record. ``branches`` maps a branch index to its token streams."""
return {
"version": UPDATE_VERSION,
"trace_id": trace_id,
"info": info or {},
"branches": [{"index": index, **streams} for index, streams in (branches or {}).items()],
}
def branch_node_paths(nodes: list[dict]) -> list[list[int]]:
"""Root-to-leaf node indexes, one path per branch, in leaf order."""
if not nodes:
return []
parents = {parent for node in nodes if isinstance((parent := node.get("parent")), int) and 0 <= parent < len(nodes)}
paths = []
for leaf in (index for index in range(len(nodes)) if index not in parents):
path: list[int] = []
seen: set[int] = set()
node_index: int | None = leaf
while isinstance(node_index, int) and 0 <= node_index < len(nodes) and node_index not in seen:
seen.add(node_index)
path.append(node_index)
node_index = nodes[node_index].get("parent")
paths.append(list(reversed(path)))
return paths
def _deep_merge(old: Any, new: Any) -> Any:
if isinstance(old, dict) and isinstance(new, dict):
return {**old, **{key: _deep_merge(old.get(key), value) for key, value in new.items()}}
return new
def fold_trace_updates(trace: dict, updates: list[dict]) -> int:
"""Apply updates onto a raw trace record in write order, newest winning.
Merges each ``info`` and projects every branch stream onto the branch's nodes,
compact over each node's mask like the node's own ``logprobs``. A node takes a
stream only when it is fully covered with non-null values at every sampled
position, so a truncated stream leaves the tail nodes untouched. Returns how many
nodes carry trainer logprobs afterwards."""
nodes = trace.get("nodes") or []
paths = branch_node_paths(nodes)
for update in updates:
if update.get("info"):
trace["info"] = _deep_merge(trace.get("info") or {}, update["info"])
for branch in update.get("branches") or []:
branch_index = branch.get("index")
if not isinstance(branch_index, int) or not 0 <= branch_index < len(paths):
continue
for field in STREAM_FIELDS:
stream = branch.get(field)
if not stream:
continue
cursor = 0
for node_index in paths[branch_index]:
node = nodes[node_index]
token_ids = node.get("token_ids") or []
span = stream[cursor : cursor + len(token_ids)]
cursor += len(token_ids)
if len(span) < len(token_ids):
break
values = [v for v, sampled in zip(span, node.get("mask") or []) if sampled]
if not values or any(v is None for v in values):
continue
node[field] = values
return sum(1 for node in nodes if node.get("trainer_logprobs"))
+49
View File
@@ -0,0 +1,49 @@
"""What the orchestrator knows about an episode, recorded as it learns it.
An episode is serialized once, when it arrives, so a trace's later facts cannot be
implied by where its record sits. Both events below are stamped explicitly: what the
orchestrator knows at arrival goes onto the trace before it is logged, and what a batch
adds when it takes the episode becomes an append-only update the reader folds back on.
"""
from __future__ import annotations
import time
from typing import Any
import verifiers.v1 as vf
from prime_rl.monitors.base import Kind
from prime_rl.monitors.file.traces.update import make_update
def stamp_arrival(episodes: list[vf.Episode], kind: Kind, step: int) -> None:
"""Stamp what an episode's traces are known to have done as they land: the kind of
work, the step that dispatched them, and the step they came back at."""
now = time.time()
for episode in episodes:
work = getattr(episode.run, "work", None)
for trace in episode.traces:
trace.info["kind"] = kind
if work is not None:
trace.info["dispatch"] = {"step": work.step, "time": trace.timing.start}
trace.info["arrival"] = {"step": step, "time": now}
def stamp_batch(episodes: list[vf.Episode], step: int) -> list[dict[str, Any]]:
"""The updates a batched cohort adds over its arrival records: membership, the step
it ties to, the scalar advantage, and the per-token advantage streams."""
now = time.time()
updates = []
for episode in episodes:
for trace in episode.traces:
info: dict[str, Any] = {"effective": True, "ship": {"step": step, "time": now}}
if (advantage := trace.info.get("advantage")) is not None:
info["advantage"] = advantage
branches = {
branch.index: {"advantages": advantages}
for branch in trace.branches
if (advantages := branch.advantages) is not None
}
updates.append(make_update(trace.id, info=info, branches=branches))
return updates
+10
View File
@@ -190,6 +190,7 @@ class Dispatcher:
self.inflight: dict[asyncio.Task, InflightEpisode] = {}
self.groups: dict[uuid.UUID, GroupState] = {}
self.source_indices_by_group: dict[str, int] = {}
# Bounded so the dispatcher backpressures on a slow sink (unbounded
# when no hard ceiling is configured — the dynamic cap still bounds
@@ -466,6 +467,8 @@ class Dispatcher:
return False
gid = uuid.uuid4()
self.groups[gid] = fresh
if fresh.source_index is not None:
self.source_indices_by_group[str(gid)] = fresh.source_index
return await self.schedule_group_episode(gid, fresh)
def next_fresh_group(self, kind: WorkKind, envs) -> GroupState | None:
@@ -493,8 +496,12 @@ class Dispatcher:
episodes_to_schedule=group_size,
target_episodes=group_size,
policy_version_at_start=self.policy.version,
source_index=request.source_index,
)
def pop_source_index(self, group_id: str) -> int | None:
return self.source_indices_by_group.pop(group_id, None)
async def schedule_group_episode(self, group_id: uuid.UUID, group: GroupState) -> bool:
"""Dispatch one ``run`` task for this group.
@@ -545,6 +552,7 @@ class Dispatcher:
task=group.task,
policy_version=group.policy_version_at_start,
step=group.step,
source_index=group.source_index,
client_config=client,
started_at=time.monotonic(),
)
@@ -710,6 +718,7 @@ class Dispatcher:
if claimed:
await safe_cancel_all([task for task, _ in claimed])
self.source_indices_by_group.pop(str(group_id), None)
return cancelled
async def cancel_inflight_episodes(self) -> None:
@@ -721,6 +730,7 @@ class Dispatcher:
tasks = list(self.inflight.keys())
self.inflight.clear()
self.groups.clear()
self.source_indices_by_group.clear()
if tasks:
await safe_cancel_all(tasks)
+6
View File
@@ -131,6 +131,12 @@ class TrainEnv(Env):
self.generation_source = generation_source
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 is not None
and config.algo.sampling.source == "policy"
)
class EvalEnv(Env):
+25 -7
View File
@@ -3,8 +3,7 @@
from __future__ import annotations
from collections import defaultdict
import verifiers.v1 as vf
from typing import TYPE_CHECKING
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.metrics import EvalEpisodes
@@ -12,6 +11,9 @@ from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancell
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, eval_work
from prime_rl.utils.logger import get_logger
if TYPE_CHECKING:
import verifiers.v1 as vf
class EvalSink:
"""Collect completed evaluation episodes into per-environment epochs."""
@@ -24,6 +26,7 @@ class EvalSink:
self.pending_batches: dict[tuple[str, int], list[vf.Episode]] = defaultdict(list)
self.pending_batch_failures: dict[tuple[str, int], list[DispatchFailure]] = defaultdict(list)
self.pending_batch_cancellations: dict[tuple[str, int], int] = defaultdict(int)
self.expected_batch_sizes: dict[tuple[str, int], int] = {}
def add(self, episode: vf.Episode) -> EvalBatch | None:
env_name = episode_env_name(episode)
@@ -34,7 +37,7 @@ class EvalSink:
group.append(episode)
if self._group_size(group_id) >= self.group_size_for(env_name):
self.process_group(group_id)
if self._batch_size(bkey) >= self.batch_size_for(env_name):
if self._batch_size(bkey) >= self.batch_size_for(env_name, eval_step):
return self.process_batch(bkey)
return None
@@ -48,7 +51,7 @@ class EvalSink:
self.pending_group_failures[group_id].append(failure)
if self._group_size(group_id) >= self.group_size_for(failure.env_name):
self.process_group(group_id)
if self._batch_size(bkey) >= self.batch_size_for(failure.env_name):
if self._batch_size(bkey) >= self.batch_size_for(failure.env_name, failure.step):
return self.process_batch(bkey)
return None
@@ -61,7 +64,7 @@ class EvalSink:
self.pending_group_cancellations[group_id] = cancellation
if self._group_size(group_id) >= self.group_size_for(cancellation.env_name):
self.process_group(group_id)
if self._batch_size(bkey) >= self.batch_size_for(cancellation.env_name):
if self._batch_size(bkey) >= self.batch_size_for(cancellation.env_name, cancellation.step):
return self.process_batch(bkey)
return None
@@ -83,7 +86,14 @@ class EvalSink:
def group_size_for(self, env_name: str) -> int:
return self.eval_envs.get(env_name).config.group_size
def batch_size_for(self, env_name: str) -> int:
def set_batch_size(self, env_name: str, step: int, size: int) -> None:
self.expected_batch_sizes[(env_name, step)] = size
def batch_size_for(self, env_name: str, step: int | None = None) -> int:
if step is not None:
key = (env_name, step)
if key in self.expected_batch_sizes:
return self.expected_batch_sizes[key]
env = self.eval_envs.get(env_name)
return len(env.examples) * env.config.group_size
@@ -119,12 +129,19 @@ class EvalSink:
env_name,
eval_step,
batch_counts.get((env_name, eval_step), 0),
self.batch_size_for(env_name),
self.batch_size_for(env_name, eval_step),
buffered.get((env_name, eval_step), 0),
)
for env_name, eval_step in set(batch_counts) | set(buffered)
]
def has_pending_group(self, group_id: str) -> bool:
return bool(
self.pending_groups.get(group_id)
or self.pending_group_failures.get(group_id)
or self.pending_group_cancellations.get(group_id)
)
def process_group(self, group_id: str) -> None:
group = self.pending_groups.pop(group_id, [])
failures = self.pending_group_failures.pop(group_id, [])
@@ -164,6 +181,7 @@ class EvalSink:
episodes = self.pending_batches.pop(key, [])
failures = self.pending_batch_failures.pop(key, [])
cancelled = self.pending_batch_cancellations.pop(key, 0)
self.expected_batch_sizes.pop(key, None)
return EvalBatch(
env_name=env_name,
step=step,
+49 -8
View File
@@ -6,15 +6,18 @@ including startup. The dispatcher pulls via ``next_task()`` until
from __future__ import annotations
from collections import deque
from collections import Counter, deque
from itertools import zip_longest
from typing import TYPE_CHECKING
import verifiers.v1 as vf
from prime_rl.configs.orchestrator import EvalConfig
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.types import TaskRequest
if TYPE_CHECKING:
import verifiers.v1 as vf
from prime_rl.configs.orchestrator import EvalConfig
from prime_rl.orchestrator.envs import EvalEnvs
class EvalSource:
"""Finite-per-epoch source of eval examples."""
@@ -36,6 +39,10 @@ class EvalSource:
self.intervals[env.name] = env.config.interval
self.queue: deque[TaskRequest] = deque()
self.cursor = 0
self._next_index = 0
self._completed: set[int] = set()
self._triggered_task_counts: dict[tuple[str, int], int] = {}
# A fresh run evaluates the base policy. Resumed runs apply interval
# rules to the loaded checkpoint and later policies.
@@ -51,8 +58,9 @@ class EvalSource:
return []
fired: list[str] = []
for name, interval in self.intervals.items():
if is_first or force or step % interval == 0:
if (is_first or force or step % interval == 0) and self.tasks_by_env[name]:
fired.append(name)
queued_counts: Counter[str] = Counter()
# 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
@@ -62,8 +70,41 @@ class EvalSource:
for env_name, task in zip(fired, round_tasks, strict=True):
if task is None:
continue
self.queue.append(TaskRequest(env_name=env_name, task=task, step=step))
return fired
source_index = self._next_index
self._next_index += 1
if source_index < self.cursor:
continue
self.queue.append(TaskRequest(env_name=env_name, task=task, step=step, source_index=source_index))
queued_counts[env_name] += 1
for env_name, count in queued_counts.items():
self._triggered_task_counts[(env_name, step)] = count
return [name for name in fired if queued_counts[name]]
def triggered_task_count(self, env_name: str, step: int) -> int:
return self._triggered_task_counts.get((env_name, step), 0)
def mark_completed(self, source_index: int) -> bool:
"""Advance the durable cursor only across a fully completed prefix."""
if source_index < self.cursor:
return False
self._completed.add(source_index)
previous = self.cursor
while self.cursor in self._completed:
self._completed.remove(self.cursor)
self.cursor += 1
return self.cursor != previous
def state_dict(self) -> dict:
return {"cursor": self.cursor}
def load_state_dict(self, state_dict: dict) -> None:
if set(state_dict) != {"cursor"}:
raise ValueError("Eval source checkpoint must contain only a cursor")
cursor = state_dict["cursor"]
if type(cursor) is not int or cursor < 0:
raise ValueError(f"Eval source checkpoint cursor must be a non-negative integer, got {cursor!r}")
self.cursor = cursor
self._completed.clear()
def next_task(self) -> TaskRequest | None:
"""Pop the next eval task, or ``None`` when the queue is empty."""
+39 -2
View File
@@ -37,6 +37,7 @@ import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before tr
from prime_rl import monitors
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.algo.routing import is_trainable
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
from prime_rl.orchestrator.concurrency import ConcurrencyController
@@ -559,6 +560,7 @@ class Orchestrator:
raise ValueError("Orchestrated episode is missing training-run provenance")
kind = episode.run.work.type
step = episode.run.work.step if kind == "eval" else self.progress.step
stamp_arrival([episode], kind, step)
await monitors.log([episode], step, kind, "all")
if kind == "eval":
@@ -649,9 +651,11 @@ class Orchestrator:
await self.version_advanced.wait()
self.wait_for_policy_time += time.perf_counter() - hold_start
# The effective (clean, trained-on) subset is logged at ship time; the full arrival
# window already streamed into the ``all`` cohort on arrival.
# The effective (clean, trained-on) subset is logged at ship time as annotation
# records against each trace's arrival record - membership, advantages, the step
# it shipped at - never a second episode copy.
await monitors.log(effective.vf_episodes, step, "train", "effective")
await monitors.log_annotations(stamp_batch(effective.vf_episodes, step))
pack_start_time = time.perf_counter()
micro_batch_grid = await asyncio.to_thread(self.packer.pack, batch.samples)
@@ -731,6 +735,38 @@ class Orchestrator:
metrics[f"batch/{env_name}"] = env_pool.num_traces / batch.episodes.num_traces
metrics |= self.train_source.metrics()
await monitors.log(metrics, step=step)
active_step_time = max(step_time - self.wait_for_policy_time, 0.0)
if step_time > 0 and self.wait_for_policy_time >= active_step_time:
get_logger().warning(
f"Orchestrator waited {format_time(self.wait_for_policy_time)} for policy updates, at least as long "
f"as its {format_time(active_step_time)} active step time. Train-inference compute is imbalanced; "
"add more trainer nodes."
)
shipped_episode_ids = {episode.id for episode in batch.cohort}
discarded_episodes = [
episode
for episode in batch.episodes
if episode.id not in shipped_episode_ids and episode.id not in batch.buffered_episode_ids
]
stale_episodes = sum(episode.id in batch.episodes.cancelled for episode in discarded_episodes)
errored_episodes = sum(
episode.id not in batch.episodes.cancelled
and (not episode.ok or any(trace.has_error for trace in episode.traces))
for episode in discarded_episodes
)
num_attempts = len(batch.episodes) + len(batch.failures) + batch.cancelled_attempts
num_discarded = len(discarded_episodes) + len(batch.failures) + batch.cancelled_attempts
num_stale = stale_episodes + batch.stale_attempts
num_errored = errored_episodes + len(batch.failures)
num_no_signal = num_discarded - num_stale - num_errored
if num_attempts and num_discarded / num_attempts > 0.5:
get_logger().warning(
f"Discarded {num_discarded}/{num_attempts} episodes ({num_discarded / num_attempts:.1%}): "
f"stale={num_stale}, errored={num_errored}, no_signal={num_no_signal}. Review max_off_policy_steps, "
"episode errors, and reward signal."
)
self.wait_for_policy_time = 0.0
if self.heart is not None:
@@ -908,6 +944,7 @@ class Orchestrator:
# ``env_name``); the full returned cohort already streamed into ``all`` on arrival.
if batch.episodes.effective:
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
await monitors.log_annotations(stamp_batch(batch.episodes.effective.vf_episodes, batch.step))
policy_spans = [eval_work(episode).policy for episode in batch.episodes]
if any(span is None for span in policy_spans):
raise ValueError(f"Eval {batch.env_name} step {batch.step} is missing policy provenance")
+32 -2
View File
@@ -88,6 +88,8 @@ class TrainSink:
self.pending_episodes = TrainEpisodes()
self.pending_failures: list[DispatchFailure] = []
self.pending_cancelled_attempts = 0
self.pending_stale_attempts = 0
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
self.pending_group_failures: dict[str, list[DispatchFailure]] = defaultdict(list)
# A dropped group's terminal marker; its ``count`` fills in for the
@@ -243,6 +245,10 @@ class TrainSink:
)
n_owed = len(group) + len(failures) + (cancellation.count if cancellation is not None else 0)
self.pending_failures.extend(failures)
if cancellation is not None:
self.pending_cancelled_attempts += cancellation.count
if cancellation.reason == "stale":
self.pending_stale_attempts += cancellation.count
# A stale drop voids the whole group: every member shares the dispatch
# version, so the arrived episodes are exactly as stale as the
@@ -277,7 +283,18 @@ class TrainSink:
samples = await asyncio.to_thread(trace_to_samples, trace, env_name=env_name)
for sample in samples:
sample.temperatures = [temperature] * len(sample.token_ids)
if env.requires_sampling_masks and sample.sampling_mask is None:
# Rollout logprobs are mask-renormalized; training without the masks
# silently biases every importance ratio.
raise RuntimeError(
f"env '{env_name}' samples with truncation (top_p/top_k) but its rollouts "
"carry no sampling masks. Set `enable_return_sampling_mask = true` on "
"the inference server config (the rl entrypoint does this automatically) - "
"it requires vLLM's native sampling-mask capture (>= 0.28)."
)
stamp_loss_routing(sample, env.algorithm.action_loss_type)
if self.config.constant_trainer_batch_size:
samples = [sample for sample in samples if _prune_zero_advantages(sample)]
if samples:
samples_by_trace[trace.id] = samples
@@ -366,7 +383,7 @@ class TrainSink:
for trace_id in selected_ids:
del self.pending_batch[trace_id]
if self.config.train.filter_zero_advantages:
if not self.config.constant_trainer_batch_size:
selected_by_trace = {
trace_id: [sample for sample in samples if _prune_zero_advantages(sample)]
for trace_id, samples in selected
@@ -375,6 +392,7 @@ class TrainSink:
samples = [sample for trace_samples in selected_by_trace.values() for sample in trace_samples]
shipped_ids = set(selected_by_trace)
buffered_episode_ids = {self.episode_by_trace[trace_id].id for trace_id in self.pending_batch}
traces_by_episode: dict[int, list[vf.Trace]] = defaultdict(list)
selected_episodes: dict[int, vf.Episode] = {}
for trace_id in selected_ids:
@@ -390,7 +408,19 @@ class TrainSink:
episodes = self.pending_episodes
failures = self.pending_failures
cancelled_attempts = self.pending_cancelled_attempts
stale_attempts = self.pending_stale_attempts
if samples:
self.pending_episodes = TrainEpisodes()
self.pending_failures = []
return TrainBatch(episodes=episodes, cohort=cohort, samples=samples, failures=failures)
self.pending_cancelled_attempts = 0
self.pending_stale_attempts = 0
return TrainBatch(
episodes=episodes,
cohort=cohort,
samples=samples,
failures=failures,
buffered_episode_ids=buffered_episode_ids,
cancelled_attempts=cancelled_attempts,
stale_attempts=stale_attempts,
)
+26 -1
View File
@@ -21,7 +21,7 @@ import numpy as np
import verifiers.v1 as vf
from prime_rl.transports.batch import TrainingSample
from prime_rl.transports.batch.types import EncodedTensor, RoutedExperts
from prime_rl.transports.batch.types import EncodedTensor, RoutedExperts, SamplingMask
from prime_rl.utils.logger import get_logger
@@ -66,6 +66,28 @@ def _encode_routed_experts(arr: np.ndarray | None, num_tokens: int) -> RoutedExp
return RoutedExperts(data=arr.tobytes(), shape=list(arr.shape), dtype=str(arr.dtype))
def _encode_sampling_mask(mask: vf.SamplingMask | None, num_tokens: int) -> SamplingMask | None:
"""Encode a branch sampling mask for a fixed token count.
The mask stores row sizes in `counts` and concatenates every row in `ids`.
For example, `counts=[2, 1]` and `ids=[4, 7, 9]` become `counts=[2]` and
`ids=[4, 7]` for one token. For three tokens, they become
`counts=[2, 1, 0]` with unchanged ids. Zero-count rows disable replay.
"""
if mask is None:
return None
ids, counts = mask.ids, mask.counts
if len(counts) > num_tokens:
counts = counts[:num_tokens]
ids = ids[: int(counts.sum())]
elif len(counts) < num_tokens:
counts = np.concatenate([counts, np.zeros(num_tokens - len(counts), dtype=np.int32)])
return SamplingMask(
ids=np.ascontiguousarray(ids, dtype=np.int32).tobytes(),
counts=np.ascontiguousarray(counts, dtype=np.int32).tobytes(),
)
def iter_trainable_branches(trace: vf.Trace) -> Iterator[tuple[vf.Branch, list[bool]]]:
"""Yield each branch that yields a training sample, with its trainable-token mask.
@@ -143,6 +165,9 @@ def trace_to_samples(trace: vf.Trace, *, env_name: str = "") -> list[TrainingSam
ce_weights=_loss_weights(branch, "ce", trained_loss_nodes["ce"]),
ref_kl_weights=_loss_weights(branch, "ref_kl", trained_loss_nodes["ref_kl"]),
advantages=branch.advantages,
sampling_mask=_encode_sampling_mask(branch.sampling_mask, len(token_ids)),
trace_id=trace.id,
branch_index=branch.index,
)
)
if not samples:
+16 -4
View File
@@ -4,13 +4,13 @@ from __future__ import annotations
import uuid
from dataclasses import dataclass
from typing import TYPE_CHECKING, Literal, Protocol, TypeAlias
import verifiers.v1 as vf
from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeAlias
from prime_rl.transports.batch import TrainingSample
if TYPE_CHECKING:
import verifiers.v1 as vf
from prime_rl.orchestrator.metrics import EvalEpisodes, TrainEpisodes
@@ -68,7 +68,10 @@ class DispatchFailure:
error: vf.Error
DispatchResult: TypeAlias = vf.WireEpisode | DispatchFailure | GroupCancellation
if TYPE_CHECKING:
DispatchResult: TypeAlias = vf.WireEpisode | DispatchFailure | GroupCancellation
else:
DispatchResult: TypeAlias = Any
@dataclass(frozen=True)
@@ -78,6 +81,7 @@ class TaskRequest:
env_name: str
task: vf.Task
step: int
source_index: int | None = None
@dataclass
@@ -90,6 +94,7 @@ class InflightEpisode:
task: vf.Task
policy_version: int
step: int
source_index: int | None = None
client_config: vf.ClientConfig | None = None
started_at: float = 0.0
"""``time.monotonic()`` at dispatch; feeds episode-duration estimates."""
@@ -108,6 +113,7 @@ class GroupState:
target_episodes: int
emitted: int = 0
policy_version_at_start: int = 0
source_index: int | None = None
@dataclass
@@ -118,6 +124,12 @@ class TrainBatch:
cohort: TrainEpisodes
samples: list[TrainingSample]
failures: list[DispatchFailure]
# Episodes with traces retained for a later batch are not discarded.
buffered_episode_ids: set[str]
# Group cancellations can account for attempts that returned no episode.
cancelled_attempts: int = 0
# Stale attempts are a subset of cancelled_attempts.
stale_attempts: int = 0
@dataclass
@@ -0,0 +1,132 @@
"""Whole-block activation checkpointing with an operator-based policy."""
from collections.abc import Callable
from functools import partial
import torch
from torch import nn
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointImpl, checkpoint_wrapper
from torch.utils.checkpoint import (
SAC_IGNORED_OPS,
CheckpointPolicy,
SelectiveCheckpointContext,
create_selective_checkpoint_contexts,
)
from prime_rl.configs.trainer import ActivationCheckpointConfig
# FSDP's replay-specific hooks emit a different number of profiler markers.
SAC_IGNORED_OPS.update(
{
torch.ops.profiler._record_function_enter.default,
torch.ops.profiler._record_function_enter_new.default,
torch.ops.profiler._record_function_exit.default,
torch.ops.profiler._record_function_exit._RecordFunction,
}
)
# Adapted from TorchTitan's whole-block selective activation checkpointing policy.
# These targets and the CUDA-to-CPU copy rule are correctness requirements. They
# must remain active when custom targets replace the default selective targets.
MANDATORY_SAVE_NAMESPACES = frozenset({"deepep"})
MANDATORY_SAVE_OPERATIONS = frozenset(
{
"aten::topk",
"prime_rl::record_moe_routing_statistics",
}
)
DEFAULT_SELECTIVE_SAVE_NAMESPACES = frozenset(
{
"_c10d_functional",
"flash_attn",
"flash_attn_3",
"prime_rl_collectives",
"prime_rl_ring",
}
)
DEFAULT_SELECTIVE_SAVE_OPERATIONS = frozenset(
{
"aten::_efficient_attention_forward",
"aten::_flash_attention_forward",
"aten::_scaled_dot_product_attention_math",
"aten::_scaled_dot_product_cudnn_attention",
"aten::_scaled_dot_product_efficient_attention",
"aten::_scaled_dot_product_flash_attention",
"aten::_scaled_dot_product_flash_attention_for_cpu",
"aten::_scaled_dot_product_fused_attention_overrideable",
"aten::_scaled_grouped_mm",
"aten::_scaled_mm",
"aten::_scaled_mm_v2",
"aten::_grouped_mm",
"aten::addmm",
"aten::bmm",
"aten::convolution",
"aten::linear",
"aten::mm",
"prime_rl::fp8_blockwise_mm",
"prime_rl::grouped_fp8_gemm",
"prime_rl::sparse_mla",
}
)
# An operation target matches one qualified operator name, while a namespace
# target matches every operation registered in that namespace.
DEFAULT_SELECTIVE_TARGETS = DEFAULT_SELECTIVE_SAVE_NAMESPACES | DEFAULT_SELECTIVE_SAVE_OPERATIONS
# PyTorch calls checkpoint policies with the dispatched operation's operands.
# Keyword operands let us distinguish CUDA-to-CPU copies from other _to_copy calls.
def _mandatory_checkpoint_policy(
_context: SelectiveCheckpointContext,
operation: torch._ops.OpOverload | torch._ops.HigherOrderOperator,
*args,
**kwargs,
) -> CheckpointPolicy:
if operation.namespace in MANDATORY_SAVE_NAMESPACES or operation.name() in MANDATORY_SAVE_OPERATIONS:
return CheckpointPolicy.MUST_SAVE
if operation.name() == "aten::_to_copy":
device = kwargs.get("device")
if isinstance(device, torch.device) and device.type == "cpu":
return CheckpointPolicy.MUST_SAVE
return CheckpointPolicy.PREFER_RECOMPUTE
def _selective_checkpoint_policy(
context: SelectiveCheckpointContext,
operation: torch._ops.OpOverload | torch._ops.HigherOrderOperator,
*args,
targets: frozenset[str] = DEFAULT_SELECTIVE_TARGETS,
**kwargs,
) -> CheckpointPolicy:
runtime_policy = _mandatory_checkpoint_policy(context, operation, *args, **kwargs)
if runtime_policy is CheckpointPolicy.MUST_SAVE:
return runtime_policy
if operation.namespace in targets or operation.name() in targets:
return CheckpointPolicy.MUST_SAVE
return CheckpointPolicy.PREFER_RECOMPUTE
def get_activation_checkpoint_wrapper(config: ActivationCheckpointConfig) -> Callable[[nn.Module], nn.Module]:
if config.mode == "full":
policy = _mandatory_checkpoint_policy
else:
targets = DEFAULT_SELECTIVE_TARGETS if config.targets is None else frozenset(config.targets)
policy = partial(_selective_checkpoint_policy, targets=targets)
return partial(
checkpoint_wrapper,
checkpoint_impl=CheckpointImpl.NO_REENTRANT,
context_fn=partial(create_selective_checkpoint_contexts, policy),
)
__all__ = [
"DEFAULT_SELECTIVE_SAVE_NAMESPACES",
"DEFAULT_SELECTIVE_SAVE_OPERATIONS",
"DEFAULT_SELECTIVE_TARGETS",
"MANDATORY_SAVE_NAMESPACES",
"MANDATORY_SAVE_OPERATIONS",
"get_activation_checkpoint_wrapper",
]
+80 -2
View File
@@ -6,7 +6,7 @@ from typing import Any
import numpy as np
from prime_rl.transports.batch.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
from prime_rl.transports.batch.types import EncodedTensor, MicroBatch, RoutedExperts, SamplingMask, TrainingSample
# Backfill value per component weight stream when a packed sample doesn't
# carry it: absent rl means weight 1.0 on the loss mask, absent ce/ref_kl
@@ -278,6 +278,31 @@ def _pad_routed_experts(micro_batch: MicroBatch, padding_size: int) -> None:
routed_experts.shape[0] += padding_size
_SAMPLING_MASK_ITEMSIZE = np.dtype(np.int32).itemsize
def _empty_sampling_mask(num_tokens: int) -> SamplingMask:
return SamplingMask(ids=b"", counts=b"\0" * (num_tokens * _SAMPLING_MASK_ITEMSIZE))
def _slice_sampling_mask(sampling_mask: SamplingMask, seq_len: int) -> SamplingMask:
counts = np.frombuffer(sampling_mask.counts, dtype=np.int32)[:seq_len]
return SamplingMask(
ids=sampling_mask.ids[: int(counts.sum()) * _SAMPLING_MASK_ITEMSIZE],
counts=counts.tobytes(),
)
def _pad_sampling_mask(micro_batch: MicroBatch, padding_size: int) -> None:
"""Add zero-count mask rows for sequence-padding tokens.
Padding adds token positions but no eligible token ids, so only `counts` grows.
"""
sampling_mask = micro_batch.sampling_mask
assert sampling_mask is not None
sampling_mask.counts += b"\0" * (padding_size * _SAMPLING_MASK_ITEMSIZE)
def _slice_encoded(tensor: EncodedTensor, n_rows: int) -> EncodedTensor:
"""First `n_rows` rows of a dim-0-stacked encoded tensor (e.g. pixel_values, image_grid_thw)."""
row = int(np.prod(tensor.shape[1:])) if len(tensor.shape) > 1 else 1
@@ -383,6 +408,9 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
routed_experts = (
_copy_routed_experts(training_example.routed_experts) if training_example.routed_experts is not None else None
)
# No copy needed: SamplingMask holds immutable bytes, and _pad_sampling_mask only
# ever mutates _materialize_bin's own accumulator.
sampling_mask = training_example.sampling_mask
if len(input_ids) > seq_len:
# Multimodal: never split an image's placeholder block — cut to a whole-image boundary
@@ -406,6 +434,8 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
ref_kl_weights = ref_kl_weights[:cut]
if routed_experts is not None:
routed_experts = _slice_routed_experts(routed_experts, cut)
if sampling_mask is not None:
sampling_mask = _slice_sampling_mask(sampling_mask, cut)
if mm_token_type_ids is not None:
mm_token_type_ids = mm_token_type_ids[:cut]
env_names = env_names[:cut]
@@ -436,6 +466,13 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
)
assert len(routed_experts.data) == len(input_ids) * _routed_experts_row_size(routed_experts)
if sampling_mask is not None:
mask_counts = np.frombuffer(sampling_mask.counts, dtype=np.int32)
assert len(mask_counts) == len(input_ids), (
f"sampling_mask counts: {len(mask_counts)}, input_ids: {len(input_ids)}"
)
assert len(sampling_mask.ids) == int(mask_counts.sum()) * _SAMPLING_MASK_ITEMSIZE
assert len(env_names) == len(input_ids), f"env_names: {len(env_names)}, input_ids: {len(input_ids)}"
return MicroBatch(
@@ -448,6 +485,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
ref_logprobs=ref_logprobs,
temperatures=temperatures,
routed_experts=routed_experts,
sampling_mask=sampling_mask,
mm_token_type_ids=mm_token_type_ids,
env_names=env_names,
mm_kwargs=mm_kwargs,
@@ -455,6 +493,8 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
ce_weights=ce_weights,
ref_kl_weights=ref_kl_weights,
seq_lens=[len(input_ids)],
trace_ids=[training_example.trace_id or ""],
branch_indices=[training_example.branch_index if training_example.branch_index is not None else -1],
)
@@ -541,6 +581,9 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
# A weight stream materializes as soon as one packed sample carries it; the
# samples that lack it get the stream's identity fill (STREAM_FILL).
has_stream = {name: any(getattr(s, name) is not None for s in bin_content.samples) for name in STREAM_FILL}
# Sampling masks are per-token optional (unlike routed_experts): samples
# without them get zero-count backfill instead of constraining packing.
has_sampling_mask = any(sample.sampling_mask is not None for sample in bin_content.samples)
input_ids: list[int] = []
loss_mask: list[bool] = []
@@ -555,6 +598,9 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
streams: dict[str, list[float] | None] = {name: ([] if has_stream[name] else None) for name in STREAM_FILL}
seq_lens: list[int] = []
routed_experts: RoutedExperts | None = None
sampling_mask: SamplingMask | None = SamplingMask(ids=b"", counts=b"") if has_sampling_mask else None
trace_ids: list[str] = []
branch_indices: list[int] = []
for sample in bin_content.samples:
sample_len = len(sample.input_ids)
@@ -592,6 +638,12 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
mm_kwargs[key].data += sample.mm_kwargs[key].data
mm_kwargs[key].shape[0] += sample.mm_kwargs[key].shape[0]
seq_lens.extend(sample.seq_lens)
if sampling_mask is not None:
sample_mask = sample.sampling_mask if sample.sampling_mask is not None else _empty_sampling_mask(sample_len)
sampling_mask.ids += sample_mask.ids
sampling_mask.counts += sample_mask.counts
trace_ids.extend(sample.trace_ids or [""] * len(sample.sequence_lengths))
branch_indices.extend(sample.branch_indices or [-1] * len(sample.sequence_lengths))
sequence_lengths = [len(sample.input_ids) for sample in bin_content.samples]
assert sum(sequence_lengths) == len(input_ids), (sequence_lengths, len(input_ids))
@@ -607,6 +659,7 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
ref_logprobs=ref_logprobs,
temperatures=temperatures,
routed_experts=routed_experts,
sampling_mask=sampling_mask,
mm_token_type_ids=mm_token_type_ids,
env_names=env_names,
mm_kwargs=mm_kwargs,
@@ -614,6 +667,8 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
ce_weights=streams["ce_weights"],
ref_kl_weights=streams["ref_kl_weights"],
seq_lens=seq_lens,
trace_ids=trace_ids,
branch_indices=branch_indices,
)
@@ -724,7 +779,8 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
micro_batch.ref_logprobs.extend([0.0] * padding_size)
# Padding is loss-masked, so no component trains it; fill every stream
# with 0.0 (not the pack-boundary defaults) so a padded pure-ce batch
# still reads as rl-empty in token export, which keys off nonzero weights.
# still reads as rl-empty to consumers that key off nonzero weights
# (e.g. the per-env mismatch metrics).
for stream_name in STREAM_FILL:
stream = getattr(micro_batch, stream_name)
if stream is not None:
@@ -733,6 +789,8 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
micro_batch.mm_token_type_ids.extend([0] * padding_size)
if micro_batch.routed_experts is not None:
_pad_routed_experts(micro_batch, padding_size)
if micro_batch.sampling_mask is not None:
_pad_sampling_mask(micro_batch, padding_size)
micro_batch.env_names.extend([""] * padding_size)
return micro_batch
@@ -764,11 +822,26 @@ def _assert_token_arrays_aligned(micro_batch: MicroBatch) -> None:
assert sum(micro_batch.sequence_lengths) == num_tokens, (
f"sequence_lengths sum {sum(micro_batch.sequence_lengths)} != {num_tokens} tokens"
)
num_sequences = len(micro_batch.sequence_lengths)
for name in ("trace_ids", "branch_indices"):
values = getattr(micro_batch, name)
assert values is None or len(values) == num_sequences, (
f"{name} misaligned after packing: {len(values)} != {num_sequences} sequences"
)
assert sum(micro_batch.seq_lens) == num_tokens, f"seq_lens sum {sum(micro_batch.seq_lens)} != {num_tokens} tokens"
if micro_batch.routed_experts is not None:
assert micro_batch.routed_experts.shape[0] == num_tokens, (
f"routed_experts misaligned after packing: {micro_batch.routed_experts.shape[0]} != {num_tokens} tokens"
)
if micro_batch.sampling_mask is not None:
mask_counts = np.frombuffer(micro_batch.sampling_mask.counts, dtype=np.int32)
assert len(mask_counts) == num_tokens, (
f"sampling_mask misaligned after packing: {len(mask_counts)} != {num_tokens} tokens"
)
assert len(micro_batch.sampling_mask.ids) == int(mask_counts.sum()) * _SAMPLING_MASK_ITEMSIZE, (
f"sampling_mask ids/counts inconsistent after packing: "
f"{len(micro_batch.sampling_mask.ids)} bytes != {int(mask_counts.sum())} ids"
)
def _make_dummy_batch(source: MicroBatch) -> MicroBatch:
@@ -781,6 +854,11 @@ def _make_dummy_batch(source: MicroBatch) -> MicroBatch:
dummy.rl_weights = None
dummy.ce_weights = None
dummy.ref_kl_weights = None
# Fully loss-masked, so replaying sampling masks would be pure wasted work.
dummy.sampling_mask = None
# The copied identity would double-annotate the source's traces.
dummy.trace_ids = None
dummy.branch_indices = None
return dummy
@@ -0,0 +1,263 @@
"""Autograd and compile-friendly distributed collectives."""
import prime_kernels
import torch
import torch.distributed as dist
from torch.distributed import ProcessGroup
@torch.library.custom_op("prime_rl_collectives::all_to_all_single", mutates_args=())
def _all_to_all_single(
x: torch.Tensor,
output_splits: torch.Tensor,
input_splits: torch.Tensor,
group_name: str,
) -> torch.Tensor:
output_split_list = output_splits.tolist()
input_split_list = input_splits.tolist()
output = x.new_empty((sum(output_split_list), *x.shape[1:]))
dist.all_to_all_single(
output,
x.contiguous(),
output_split_list,
input_split_list,
group=dist.distributed_c10d._resolve_process_group(group_name),
)
return output
@_all_to_all_single.register_fake
def _all_to_all_single_fake(
x: torch.Tensor,
output_splits: torch.Tensor,
input_splits: torch.Tensor,
group_name: str,
) -> torch.Tensor:
output_size = torch.library.get_ctx().new_dynamic_size()
return x.new_empty((output_size, *x.shape[1:]))
def _all_to_all_setup_context(ctx, inputs, output) -> None:
_, output_splits, input_splits, group_name = inputs
ctx.save_for_backward(output_splits, input_splits)
ctx.group_name = group_name
def _all_to_all_backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None, None]:
output_splits, input_splits = ctx.saved_tensors
return (
_all_to_all_single(
grad_output,
input_splits,
output_splits,
ctx.group_name,
),
None,
None,
None,
)
_all_to_all_single.register_autograd(_all_to_all_backward, setup_context=_all_to_all_setup_context)
@torch.library.custom_op("prime_rl_collectives::all_to_all_single_equal", mutates_args=())
def _all_to_all_single_equal(x: torch.Tensor, group_name: str) -> torch.Tensor:
output = x.new_empty(x.shape)
dist.all_to_all_single(
output,
x.contiguous(),
group=dist.distributed_c10d._resolve_process_group(group_name),
)
return output
@_all_to_all_single_equal.register_fake
def _all_to_all_single_equal_fake(x: torch.Tensor, group_name: str) -> torch.Tensor:
return x.new_empty(x.shape)
def _all_to_all_equal_backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None]:
return _all_to_all_single_equal(grad_output, ctx.group_name), None
def _all_to_all_equal_setup_context(ctx, inputs, output) -> None:
_, group_name = inputs
ctx.group_name = group_name
_all_to_all_single_equal.register_autograd(
_all_to_all_equal_backward,
setup_context=_all_to_all_equal_setup_context,
)
@torch.library.custom_op("prime_rl_collectives::mxfp8_all_to_all", mutates_args=())
def _mxfp8_all_to_all(
x: torch.Tensor,
output_splits: torch.Tensor,
input_splits: torch.Tensor,
group_name: str,
quantized: bool,
) -> torch.Tensor:
kernel = prime_kernels.load("mxfp8_moe")
operation = kernel.all_to_all_dispatch if quantized else kernel.all_to_all_combine
return operation(
x,
output_splits.tolist(),
input_splits.tolist(),
dist.distributed_c10d._resolve_process_group(group_name),
)
@_mxfp8_all_to_all.register_fake
def _mxfp8_all_to_all_fake(
x: torch.Tensor,
output_splits: torch.Tensor,
input_splits: torch.Tensor,
group_name: str,
quantized: bool,
) -> torch.Tensor:
output_size = torch.library.get_ctx().new_dynamic_size()
return x.new_empty((output_size, *x.shape[1:]))
def _mxfp8_all_to_all_setup_context(ctx, inputs, output) -> None:
_, output_splits, input_splits, group_name, quantized = inputs
ctx.save_for_backward(output_splits, input_splits)
ctx.group_name = group_name
ctx.quantized = quantized
def _mxfp8_all_to_all_backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None, None, None]:
output_splits, input_splits = ctx.saved_tensors
return (
_mxfp8_all_to_all(
grad_output,
input_splits,
output_splits,
ctx.group_name,
not ctx.quantized,
),
None,
None,
None,
None,
)
_mxfp8_all_to_all.register_autograd(
_mxfp8_all_to_all_backward,
setup_context=_mxfp8_all_to_all_setup_context,
)
@torch.library.custom_op("prime_rl_collectives::all_gather", mutates_args=())
def _all_gather(x: torch.Tensor, dim: int, group_size: int, group_name: str) -> torch.Tensor:
gathered = x.movedim(dim, 0).contiguous()
output = gathered.new_empty((gathered.shape[0] * group_size, *gathered.shape[1:]))
dist.all_gather_into_tensor(
output,
gathered,
group=dist.distributed_c10d._resolve_process_group(group_name),
)
return output.movedim(0, dim).contiguous()
@_all_gather.register_fake
def _all_gather_fake(x: torch.Tensor, dim: int, group_size: int, group_name: str) -> torch.Tensor:
shape = list(x.shape)
shape[dim] *= group_size
return x.new_empty(shape)
@torch.library.custom_op("prime_rl_collectives::reduce_scatter_sum", mutates_args=())
def _reduce_scatter_sum(x: torch.Tensor, dim: int, group_size: int, group_name: str) -> torch.Tensor:
scattered = x.movedim(dim, 0).contiguous()
output = scattered.new_empty((scattered.shape[0] // group_size, *scattered.shape[1:]))
dist.reduce_scatter_tensor(
output,
scattered,
group=dist.distributed_c10d._resolve_process_group(group_name),
)
return output.movedim(0, dim).contiguous()
@_reduce_scatter_sum.register_fake
def _reduce_scatter_sum_fake(x: torch.Tensor, dim: int, group_size: int, group_name: str) -> torch.Tensor:
shape = list(x.shape)
shape[dim] //= group_size
return x.new_empty(shape)
def _collective_setup_context(ctx, inputs, output) -> None:
_, dim, group_size, group_name = inputs
ctx.dim = dim
ctx.group_size = group_size
ctx.group_name = group_name
def _all_gather_backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None, None]:
return (
_reduce_scatter_sum(grad_output, ctx.dim, ctx.group_size, ctx.group_name),
None,
None,
None,
)
def _reduce_scatter_backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None, None]:
return (
_all_gather(grad_output, ctx.dim, ctx.group_size, ctx.group_name),
None,
None,
None,
)
_all_gather.register_autograd(_all_gather_backward, setup_context=_collective_setup_context)
_reduce_scatter_sum.register_autograd(_reduce_scatter_backward, setup_context=_collective_setup_context)
def all_to_all_single(
x: torch.Tensor,
output_splits: torch.Tensor,
input_splits: torch.Tensor,
group: ProcessGroup,
) -> torch.Tensor:
return _all_to_all_single(x, output_splits, input_splits, group.group_name)
def all_to_all_single_equal(x: torch.Tensor, group: ProcessGroup) -> torch.Tensor:
return _all_to_all_single_equal(x, group.group_name)
def mxfp8_all_to_all_dispatch(
x: torch.Tensor,
output_splits: torch.Tensor,
input_splits: torch.Tensor,
group: ProcessGroup,
) -> torch.Tensor:
return _mxfp8_all_to_all(x, output_splits, input_splits, group.group_name, True)
def mxfp8_all_to_all_combine(
x: torch.Tensor,
output_splits: torch.Tensor,
input_splits: torch.Tensor,
group: ProcessGroup,
) -> torch.Tensor:
return _mxfp8_all_to_all(x, output_splits, input_splits, group.group_name, False)
def all_gather(x: torch.Tensor, dim: int, group: ProcessGroup) -> torch.Tensor:
return _all_gather(x, dim, group.size(), group.group_name)
__all__ = [
"all_gather",
"all_to_all_single",
"all_to_all_single_equal",
"mxfp8_all_to_all_combine",
"mxfp8_all_to_all_dispatch",
]
+56 -43
View File
@@ -1,4 +1,7 @@
from __future__ import annotations
from dataclasses import dataclass
from weakref import WeakValueDictionary
import torch
from deep_ep import Buffer
@@ -15,6 +18,9 @@ from prime_rl.trainer.distributed.token_dispatcher import (
_buffer: Buffer | None = None
_handle_cache: dict[int, object] = {}
_combine_backward_handles: dict[int, object] = {}
# The custom-op schema can carry only the dispatcher ID; weak values avoid extending dispatcher lifetimes.
_combine_dispatchers: WeakValueDictionary[int, DeepEPTokenDispatcher] = WeakValueDictionary()
_pending_dispatch_events: dict[int, EventOverlap] = {}
_handle_counter = 0
_deepep_cuda_ops_registered = False
@@ -44,10 +50,13 @@ def register_deepep_cuda_ops() -> None:
"Tensor is_token_in_rank, Tensor num_tokens_per_expert) "
"-> (Tensor, Tensor, Tensor, Tensor, Tensor)"
)
_deepep_cuda_lib.define("combine(Tensor x, Tensor handle_id, int dispatcher_id) -> Tensor")
torch.library.impl(_deepep_cuda_lib, "dispatch", "CUDA")(_dispatch_op_impl)
torch.library.impl(_deepep_cuda_lib, "combine", "CUDA")(_combine_op_impl)
torch.library.register_autograd("deepep::dispatch", _dispatch_backward, setup_context=_dispatch_setup_context)
torch.library.register_autograd("deepep::combine", _combine_backward, setup_context=_combine_setup_context)
_deepep_cuda_ops_registered = True
@@ -120,51 +129,53 @@ def _dispatch_backward(
return grad_x, None, grad_topk_weights, None, None, None, None
class _DeepEPCombine(torch.autograd.Function):
@staticmethod
def forward(
ctx,
x: torch.Tensor,
handle_id: torch.Tensor,
pending_events: list[EventOverlap],
) -> torch.Tensor:
assert _buffer is not None, "DeepEP buffer must be initialized before combine."
handle = _handle_cache.pop(handle_id.item(), None)
assert handle is not None, f"Handle not found for handle_id={handle_id.item()}"
def _combine_op_impl(x: torch.Tensor, handle_id: torch.Tensor, dispatcher_id: int) -> torch.Tensor:
assert _buffer is not None, "DeepEP buffer must be initialized before combine."
handle_key = handle_id.item()
handle = _handle_cache.pop(handle_key, None)
assert handle is not None, f"Handle not found for handle_id={handle_key}"
previous_event = _new_event_overlap()
combined, _, after_event = _buffer.combine(
x=x,
handle=handle,
previous_event=previous_event,
async_finish=True,
allocate_on_comm_stream=True,
)
pending_events.append(after_event)
ctx.handle = handle
return combined
previous_event = _new_event_overlap()
combined, _, after_event = _buffer.combine(
x=x,
handle=handle,
previous_event=previous_event,
async_finish=True,
allocate_on_comm_stream=True,
)
dispatcher = _combine_dispatchers.get(dispatcher_id)
assert dispatcher is not None, "DeepEP dispatcher was released before combine completed."
dispatcher._pending_combine_events.append(after_event)
if x.requires_grad:
_combine_backward_handles[handle_key] = handle
return combined
@staticmethod
def backward(ctx, grad_combined: torch.Tensor) -> tuple[torch.Tensor, None, None]:
handle = ctx.handle
assert handle is not None, "Handle not found in DeepEP combine backward."
previous_event = _new_event_overlap()
grad_x, _, _, _, _, after_event = _buffer.dispatch(
x=grad_combined,
topk_idx=None,
topk_weights=None,
num_tokens_per_rank=None,
num_tokens_per_rdma_rank=None,
is_token_in_rank=None,
num_tokens_per_expert=None,
handle=handle,
previous_event=previous_event,
async_finish=True,
allocate_on_comm_stream=True,
)
after_event.current_stream_wait()
return grad_x, None, None
def _combine_setup_context(ctx, inputs, output) -> None:
_, handle_id, _ = inputs
ctx.handle = _combine_backward_handles.pop(handle_id.item(), None)
def _combine_backward(ctx, grad_combined: torch.Tensor) -> tuple[torch.Tensor, None, None]:
handle = ctx.handle
assert handle is not None, "Handle not found in DeepEP combine backward."
previous_event = _new_event_overlap()
grad_x, _, _, _, _, after_event = _buffer.dispatch(
x=grad_combined,
topk_idx=None,
topk_weights=None,
num_tokens_per_rank=None,
num_tokens_per_rdma_rank=None,
is_token_in_rank=None,
num_tokens_per_expert=None,
handle=handle,
previous_event=previous_event,
async_finish=True,
allocate_on_comm_stream=True,
)
after_event.current_stream_wait()
return grad_x, None, None
@torch.compiler.disable()
@@ -312,6 +323,8 @@ class DeepEPTokenDispatcher(TokenDispatcherBase[DeepEPDispatchState]):
self.group = group
self.token_chunk_size = token_chunk_size
self._pending_combine_events: list[EventOverlap] = []
self._dispatcher_id = id(self)
_combine_dispatchers[self._dispatcher_id] = self
self._concatenate_stream: torch.cuda.Stream | None = None
self._output_event: torch.cuda.Event | None = None
configure_num_sms(num_sms)
@@ -381,7 +394,7 @@ class DeepEPTokenDispatcher(TokenDispatcherBase[DeepEPDispatchState]):
state.deep_ep_permuted_indices,
state.num_received_tokens,
)
combined = _DeepEPCombine.apply(routed_output, state.handle_id, self._pending_combine_events)
combined = torch.ops.deepep.combine(routed_output, state.handle_id, self._dispatcher_id)
return combined
def _run_dispatched_chunk(
@@ -1,12 +1,17 @@
from abc import ABC, abstractmethod
from dataclasses import dataclass
from types import ModuleType
from typing import Generic, Protocol, TypeVar
import torch
import torch.distributed as dist
from torch.distributed import ProcessGroup
from prime_rl.trainer.distributed.collectives import (
all_to_all_single,
all_to_all_single_equal,
mxfp8_all_to_all_combine,
mxfp8_all_to_all_dispatch,
)
class ExpertFunction(Protocol):
def __call__(self, x: torch.Tensor, num_tokens_per_expert: torch.Tensor) -> torch.Tensor: ...
@@ -85,46 +90,8 @@ class LocalDispatchState:
@dataclass(frozen=True)
class TorchDispatchState(LocalDispatchState):
input_splits: list[int]
output_splits: list[int]
class _AllToAll(torch.autograd.Function):
@staticmethod
def forward(
ctx,
x: torch.Tensor,
output_splits: list[int],
input_splits: list[int],
group: ProcessGroup,
) -> torch.Tensor:
output = x.new_empty((sum(output_splits), *x.shape[1:]))
dist.all_to_all_single(output, x.contiguous(), output_splits, input_splits, group=group)
ctx.output_splits = output_splits
ctx.input_splits = input_splits
ctx.group = group
return output
@staticmethod
def backward(ctx, grad_output: torch.Tensor):
grad_input = grad_output.new_empty((sum(ctx.input_splits), *grad_output.shape[1:]))
dist.all_to_all_single(
grad_input,
grad_output.contiguous(),
ctx.input_splits,
ctx.output_splits,
group=ctx.group,
)
return grad_input, None, None, None
def _all_to_all(
x: torch.Tensor,
output_splits: list[int],
input_splits: list[int],
group: ProcessGroup,
) -> torch.Tensor:
return _AllToAll.apply(x, output_splits, input_splits, group)
input_splits: torch.Tensor
output_splits: torch.Tensor
def permute_for_grouped_gemm(
@@ -264,18 +231,18 @@ class TorchTokenDispatcher(TokenDispatcherBase[TorchDispatchState]):
def _dispatch_tokens(
self,
x: torch.Tensor,
output_splits: list[int],
input_splits: list[int],
output_splits: torch.Tensor,
input_splits: torch.Tensor,
) -> torch.Tensor:
return _all_to_all(x, output_splits, input_splits, self.group)
return all_to_all_single(x, output_splits, input_splits, self.group)
def _combine_tokens(
self,
x: torch.Tensor,
output_splits: list[int],
input_splits: list[int],
output_splits: torch.Tensor,
input_splits: torch.Tensor,
) -> torch.Tensor:
return _all_to_all(x, output_splits, input_splits, self.group)
return all_to_all_single(x, output_splits, input_splits, self.group)
def dispatch(
self,
@@ -299,11 +266,10 @@ class TorchTokenDispatcher(TokenDispatcherBase[TorchDispatchState]):
scores_after_experts = sorted_scores
ep_degree = self.group.size()
num_tokens_per_expert_group = torch.empty_like(num_tokens_per_expert)
with torch.no_grad():
dist.all_to_all_single(num_tokens_per_expert_group, num_tokens_per_expert, group=self.group)
input_splits = num_tokens_per_expert.view(ep_degree, -1).sum(dim=1).tolist()
output_splits = num_tokens_per_expert_group.view(ep_degree, -1).sum(dim=1).tolist()
num_tokens_per_expert_group = all_to_all_single_equal(num_tokens_per_expert, self.group)
input_splits = num_tokens_per_expert.view(ep_degree, -1).sum(dim=1)
output_splits = num_tokens_per_expert_group.view(ep_degree, -1).sum(dim=1)
routed_input = self._dispatch_tokens(routed_input, output_splits, input_splits)
experts_per_rank = self.num_experts // ep_degree
@@ -342,23 +308,21 @@ class MXFP8TorchTokenDispatcher(TorchTokenDispatcher):
top_k: int,
token_group_alignment: int,
group: ProcessGroup,
kernel: ModuleType,
) -> None:
super().__init__(num_experts, top_k, token_group_alignment, group)
self.kernel = kernel
def _dispatch_tokens(
self,
x: torch.Tensor,
output_splits: list[int],
input_splits: list[int],
output_splits: torch.Tensor,
input_splits: torch.Tensor,
) -> torch.Tensor:
return self.kernel.all_to_all_dispatch(x, output_splits, input_splits, self.group)
return mxfp8_all_to_all_dispatch(x, output_splits, input_splits, self.group)
def _combine_tokens(
self,
x: torch.Tensor,
output_splits: list[int],
input_splits: list[int],
output_splits: torch.Tensor,
input_splits: torch.Tensor,
) -> torch.Tensor:
return self.kernel.all_to_all_combine(x, output_splits, input_splits, self.group)
return mxfp8_all_to_all_combine(x, output_splits, input_splits, self.group)
+37 -45
View File
@@ -15,7 +15,6 @@ 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 checkpoint_wrapper
from torch.distributed.checkpoint.hf_storage import HuggingFaceStorageReader
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
from torch.distributed.device_mesh import DeviceMesh
@@ -32,21 +31,18 @@ from prime_rl.configs.trainer import (
MXFP8Config,
TokenizerConfig,
)
from prime_rl.trainer.activation_checkpointing import get_activation_checkpoint_wrapper
from prime_rl.trainer.lora import apply_lora_to_model, freeze_all_except_lora_and_specified, strip_lora_from_state_dict
from prime_rl.trainer.models import (
AutoModelForCausalLMPrimeRL,
PreTrainedModelPrimeRL,
PrimeLmOutput,
cast_float_and_contiguous,
get_custom_causal_lm_cls,
get_custom_vlm_cls,
supports_custom_impl,
)
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import Indexer
from prime_rl.trainer.models.layers.checkpointing import (
get_supported_targets,
set_selective_activation_checkpointing,
supports_selective_activation_checkpointing,
)
from prime_rl.trainer.models.layers.fp8_linear import replace_linear_with_fp8_blockwise_linear
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.layers.moe import MoE, TokenChoiceTopKRouter
@@ -685,6 +681,18 @@ def get_model(
"but this architecture resolved to model.impl='hf'."
)
# Past the check above, cp > 1 implies impl_to_use == "custom", so the model class always
# resolves. Queried here so a misconfigured job dies at setup rather than at the first forward.
if config.cp > 1:
cp_model_cls = custom_vlm_cls or get_custom_causal_lm_cls(model_config)
support = cp_model_cls.cp_support(model_config)
if config.cp_style not in support.styles:
supported = f"supported styles: {sorted(support.styles)}" if support.styles else "set cp=1"
raise ValueError(
f"{model_config.model_type!r} does not support cp_style={config.cp_style!r} "
f"({support.reason}); {supported}."
)
if config.vlm is not None and not (is_vlm_arch and custom_vlm_cls):
raise ValueError(
"VLM training requires a registered custom PrimeRL VLM implementation; "
@@ -882,10 +890,18 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
prev_transformer_blocks = reversed_transformer_blocks[1:] + [None]
if language_model.norm is not None and model.lm_head is not None and len(language_model.layers) > 0:
last_transformer_block = reversed_transformer_blocks[0]
prefetch_modules = [last_transformer_block]
last_mlp = getattr(last_transformer_block, "mlp", None)
if last_mlp is not None and isinstance(last_mlp, MoE):
prefetch_modules.append(last_mlp.experts)
if isinstance(last_mlp.router, FSDPModule):
prefetch_modules.append(last_mlp.router)
if shard_norm_and_lm_head:
model.lm_head.set_modules_to_backward_prefetch([reversed_transformer_blocks[0]])
model.lm_head.set_modules_to_backward_prefetch(prefetch_modules)
else:
model.set_modules_to_backward_prefetch([reversed_transformer_blocks[0]])
model.set_modules_to_backward_prefetch(prefetch_modules)
for transformer_block, prev_transformer_block in zip(reversed_transformer_blocks, prev_transformer_blocks):
if prev_transformer_block is not None:
@@ -1093,50 +1109,20 @@ def reshard_module(model: nn.Module):
def apply_ac(model: nn.Module, ac_config: ActivationCheckpointConfig):
logger = get_logger()
language_model = get_language_model(model)
target_list = sorted(frozenset(ac_config.targets))
selective_layers = 0
full_layers = 0
fallback_layer_types: set[str] = set()
model_supported_targets: set[str] = set()
wrap_block = get_activation_checkpoint_wrapper(ac_config)
checkpointed_layers = 0
for layer_id, (layer_name, transformer_block) in enumerate(language_model.layers.named_children()):
if layer_id % ac_config.freq != 0:
continue
if ac_config.mode == "selective" and supports_selective_activation_checkpointing(transformer_block):
model_supported_targets.update(get_supported_targets(transformer_block))
set_selective_activation_checkpointing(transformer_block, target_list)
selective_layers += 1
else:
if ac_config.mode == "selective":
fallback_layer_types.add(type(transformer_block).__name__)
transformer_block = checkpoint_wrapper(transformer_block, preserve_rng_state=False)
full_layers += 1
language_model.layers.register_module(layer_name, wrap_block(transformer_block))
checkpointed_layers += 1
language_model.layers.register_module(layer_name, transformer_block)
if ac_config.mode == "selective":
unsupported_targets = frozenset(target_list) - model_supported_targets
if unsupported_targets:
raise ValueError(
f"Selective activation checkpoint targets {sorted(unsupported_targets)} are not supported "
f"by the selected model layers. Supported targets across the model: {sorted(model_supported_targets)}"
)
if fallback_layer_types:
logger.warning(
"Selective activation checkpointing is not supported for layer types "
f"{sorted(fallback_layer_types)}; falling back to full checkpointing for those layers."
)
logger.info(
"Applied selective activation checkpointing "
f"(freq={ac_config.freq}, targets={target_list}, selective_layers={selective_layers}, "
f"full_fallback_layers={full_layers})"
)
return
logger.info(f"Applied activation checkpointing (freq={ac_config.freq})")
get_logger().info(
f"Applied {ac_config.mode} activation checkpointing to {checkpointed_layers} layers (freq={ac_config.freq})"
)
def apply_compile(model: nn.Module, compile_config: CompileConfig):
@@ -1355,6 +1341,7 @@ def forward(
labels: Int[Tensor, "batch seq"] | None = None,
temperature: Tensor | None = None,
routed_experts: Int[Tensor, "batch seq layers topk"] | None = None,
sampling_mask: Int[Tensor, "batch seq mask"] | None = None,
# Generic multimodal kwargs (e.g. {"pixel_values": ...,
# "image_grid_thw": ...} for Qwen3-VL; just {"pixel_values": ...}
# for Gemma3). Passed straight through to ``model(**kwargs)`` so
@@ -1372,6 +1359,11 @@ def forward(
"temperature": temperature,
}
# Sampling masks are consumed by the injected prime lm_head; HF
# forwards don't know the kwarg, so only pass it when present.
if sampling_mask is not None:
kwargs["sampling_mask"] = sampling_mask
if mm_kwargs:
# Forward the per-model multimodal tensors verbatim, plus the
# renderer-supplied ``mm_token_type_ids`` (renderer owns the
+3
View File
@@ -12,6 +12,7 @@ from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
from prime_rl.trainer.models.afmoe import AfmoeConfig, AfmoeForCausalLM
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, DeepseekV4ForCausalLM
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig, Glm4MoeForCausalLM
from prime_rl.trainer.models.glm_moe_dsa import GlmMoeDsaConfig, GlmMoeDsaForCausalLM
from prime_rl.trainer.models.gpt_oss import GptOssConfig, GptOssForCausalLM
@@ -27,6 +28,7 @@ from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalL
# Make custom config discoverable by AutoConfig
AutoConfig.register("afmoe", AfmoeConfig, exist_ok=True)
AutoConfig.register("deepseek_v4", DeepseekV4Config, exist_ok=True)
AutoConfig.register("glm4_moe", Glm4MoeConfig, exist_ok=True)
AutoConfig.register("glm_moe_dsa", GlmMoeDsaConfig, exist_ok=True)
AutoConfig.register("laguna", LagunaConfig, exist_ok=True)
@@ -45,6 +47,7 @@ _CUSTOM_CAUSAL_LM_MODELS: tuple[
(LlamaConfig, LlamaForCausalLM),
(Qwen3Config, Qwen3ForCausalLM),
(AfmoeConfig, AfmoeForCausalLM),
(DeepseekV4Config, DeepseekV4ForCausalLM),
(Glm4MoeConfig, Glm4MoeForCausalLM),
(GlmMoeDsaConfig, GlmMoeDsaForCausalLM),
(LagunaConfig, LagunaForCausalLM),
@@ -82,18 +82,6 @@ class AfmoeAttentionBase(nn.Module):
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
def output_proj(
self,
attn_output: torch.Tensor,
gate_states: torch.Tensor,
) -> torch.Tensor:
input_shape = gate_states.shape[:-1]
if attn_output.dim() == 4:
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.contiguous().view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate_states)
return self.o_proj(attn_output)
class AfmoeFlashAttention(AfmoeAttentionBase):
"""AFMoE attention using Flash Attention varlen functions."""
@@ -125,21 +113,14 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
out = out[0]
return out
def _attention_core(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> torch.Tensor:
return self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
def attn_projections(
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
attention_mask: torch.Tensor | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, None]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
@@ -159,25 +140,10 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
return query_states, key_states, value_states, gate_states
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: torch.Tensor | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, None]:
query_states, key_states, value_states, gate_states = self.attn_projections(hidden_states, position_embeddings)
attn_output = self._attention_core(
query_states,
key_states,
value_states,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
return self.output_proj(attn_output, gate_states), None
attn_output = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
attn_output = attn_output.contiguous().view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate_states)
return self.o_proj(attn_output), None
AFMOE_ATTN_IMPL2CLASS = {
+25 -1
View File
@@ -1,6 +1,20 @@
from dataclasses import dataclass
from typing import Literal
from torch import Tensor
from transformers.modeling_utils import PreTrainedModel
CPStyle = Literal["ring", "ulysses"]
ALL_CP_STYLES: frozenset[CPStyle] = frozenset({"ring", "ulysses"})
@dataclass(frozen=True)
class CPSupport:
"""Which context-parallel styles an architecture can train under, and why not the rest."""
styles: frozenset[CPStyle]
reason: str = ""
class PreTrainedModelPrimeRL(PreTrainedModel):
"""
@@ -11,6 +25,16 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
after loading with meta device.
"""
@classmethod
def cp_support(cls, config) -> CPSupport:
"""CP styles this architecture supports, given its config.
Softmax attention runs through the shared ``FlashAttention._compute_attention``, which both
``substitute_ring_attn`` and ``substitute_ulysses_attn`` rebind, so the default is both styles.
Architectures whose attention sits outside that path declare their own support.
"""
return CPSupport(ALL_CP_STYLES)
@classmethod
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
"""Whether a tensor is stored in FP32 in the source checkpoint.
@@ -145,4 +169,4 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
raise NotImplementedError(f"init_buffers_post_meta is not implemented for {self.__class__.__name__}")
__all__ = ["PreTrainedModelPrimeRL"]
__all__ = ["ALL_CP_STYLES", "CPStyle", "CPSupport", "PreTrainedModelPrimeRL"]
@@ -0,0 +1,7 @@
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
from prime_rl.trainer.models.deepseek_v4.modeling_deepseek_v4 import DeepseekV4ForCausalLM
__all__ = [
"DeepseekV4Config",
"DeepseekV4ForCausalLM",
]
@@ -0,0 +1,714 @@
"""
[DeepSeek V4 Attention Layers]
The attention layers in this architecture generally begin with a few sliding-window attention layers
(just the first two layers in V4 Flash) followed by interleaved complex compressed attention
variants involving either Compressed Sparse Attention (CSA) or Heavily Compressed Attention (HCA).
CSA compresses with a smaller window (~4 toks) and adds additional sparsity on top via a "Lightning
Indexer", while HCA uses a more aggressive window (~128 toks) with no additional sparsity. A sketch
of the compressed variants is below, tensors flowing downwards:
hidden_states
│
┌──────────────┴──────────────┐
│ │
local KV long-range KV
sliding_window ~ 128 compress hidden states
│ into compact entries
│ │
│ ┌──────────────┴──────────────┐
│ │ (choose one) │
│ │ │
│ CSA HCA
│ compress_rate ~ 4 compress_rate ~ 128
│ index_topk sparsity via │
│ Lightning Indexer │
│ │ │
│ └──────────────┬──────────────┘
│ │
RoPE RoPE
at token positions at each entry's
│ first token position
│ │
└────────── concatenate ──────┘
│
QKᵀ (with {compression,position}-aware masking)
│
softmax + sink
│
values (= keys) softmax weighting
│
de-rotate output (undo RoPE on values = keys)
│
grouped output projection
[Packing Details]
We describe our abstractions and nomenclature for DeepSeek V4 packed sequences below, which are
useful due to the complexities introduced by the compressed attention variants. Ultimately, all
necessary attention data is organized into a `PackedContext` object (directly consumed by attention
layers), built from one `seq_lens` and carrying:
- `attention_mask`: causal, local-window, clipped at document boundaries.
- `position_ids`: each token's position within its own document.
- `tok_doc_idx`: which document each token belongs to.
- `position_embeddings`: the RoPE tables, one per rope type, evaluated at `position_ids`.
- `compression_layouts`: one `CompressionLayout` per compress rate in the architecture.
The last of those characterizes the token-compression mechanism of DeepSeek V4. We start with it
below.
We pack several documents end to end in a flat token stream. Each compressed attention variant
defines a `compress_rate`: that variant compresses each group of `compress_rate` consecutive tokens
into an individual `entry`. For packed sequence and each `compress_rate` in the architecture, we
build one `CompressionLayout` object whose responsibility is to handle the document-aware bookkeeping
for such packed-document compression.
Take the following illustrative example of two packed documents and `compress_rate = 4`:
token 0 1 2 3 4 5 6 7 8 │ 9 10 11 12 13
└───────── doc 0 ─────────┘ └─── doc 1 ───┘
entry └─── e0 ───┘└─── e1 ───┘ x └─── e2 ───┘ x
We've indicated which tokens get pooled into which entries (tokens marked `x` belong to no entry) .
A complete, generic description of the packed and compressed state requires four pieces of data:
- Which tokens belong to which entries: `entry_tok_idx`.
- Which document each entry belongs to (for causality): `entry_doc_idx`.
- Where an entry sits within its own document (useful for RoPE + causality): `entry_local_idx`.
- Which document each token belongs to (causality, again): `tok_doc_idx`.
For the above example:
token 0 1 2 3 4 5 6 7 8 │ 9 10 11 12 13
└───────── doc 0 ─────────┘ └─── doc 1 ───┘
entry └─── e0 ───┘└─── e1 ───┘ x └─── e2 ───┘ x
entry_tok_idx [0 1 2 3][4 5 6 7] [9 10 11 12]
entry_doc_idx 0 0 1
entry_local_idx 0 1 0
tok_doc_idx 0 0 0 0 0 0 0 0 0 1 1 1 1 1
The first three depend on the compress rate and are stored on the `CompressionLayout` abstraction
used below. The fourth does not: `tok_doc_idx` describes the token stream alone, so `PackedContext`
holds it once and shares it across rates.
Compression is only part of the story: every attention layer also reads a local sliding window of
the most recent tokens directly, and the compressed entries are how it reaches anything older.
That window needs a causal sliding-window mask applied per document, `attention_mask`, and every
rotation in the block needs `position_ids` together with the RoPE tables evaluated at them,
`position_embeddings`. None of those belongs to any single compress rate.
`PackedContext.build` takes `seq_lens` and derives every one of its fields from it. Nothing else is
an input, so a position that disagrees with a document boundary, a mask that spans one, or a RoPE
table evaluated at positions other than the ones the causal thresholds count in, cannot be
constructed. It runs once per model forward, since none of this depends on depth.
"""
from dataclasses import dataclass
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
from prime_rl.trainer.models.deepseek_v4.hyperconnections import DeepseekV4UnweightedRMSNorm
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding, apply_rotary_pos_emb_interleaved
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
class DeepseekV4GroupedLinear(nn.Linear):
"""Block-diagonal grouped linear, the first half of the output projection.
The stacked attention output is `num_attention_heads * head_dim` wide, so a direct
projection to `hidden_size` would dominate the per-token cost. Instead the heads are split
into `n_groups` groups, each projected independently to `out_features / n_groups` channels;
a single follow-up linear (`o_b_proj`) mixes the concatenation back to `hidden_size`.
Input is `(..., n_groups, in_features_per_group)`, output `(..., n_groups, out_features / n_groups)`.
"""
def __init__(self, in_features_per_group: int, out_features: int, n_groups: int, bias: bool = False):
super().__init__(in_features_per_group, out_features, bias=bias)
self.n_groups = n_groups
def forward(self, x: torch.Tensor) -> torch.Tensor:
input_shape = x.shape[:-2]
hidden_dim = x.shape[-1]
w = self.weight.view(self.n_groups, -1, hidden_dim).transpose(1, 2)
x = x.reshape(-1, self.n_groups, hidden_dim).transpose(0, 1)
y = torch.bmm(x, w).transpose(0, 1)
return y.reshape(*input_shape, self.n_groups, -1)
def eager_attention_with_sinks(
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
sinks: torch.Tensor,
attention_mask: torch.Tensor,
scaling: float,
dropout: float = 0.0,
training: bool = False,
) -> torch.Tensor:
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
attn_weights = attn_weights + attention_mask
sink_logits = sinks.reshape(1, -1, 1, 1).expand(query.shape[0], -1, query.shape[-2], -1)
combined_logits = torch.cat([attn_weights, sink_logits], dim=-1)
# Row-max subtraction is not free here: without it the exponentials overflow in bf16.
combined_logits = combined_logits - combined_logits.max(dim=-1, keepdim=True).values
probs = F.softmax(combined_logits, dim=-1, dtype=combined_logits.dtype)
scores = F.dropout(probs[..., :-1], p=dropout, training=training).to(value.dtype)
attn_output = torch.matmul(scores, value)
return attn_output.transpose(1, 2).contiguous()
def build_sliding_window_mask(*, tok_doc_idx: Tensor, sliding_window: int, dtype: torch.dtype) -> Tensor:
"""Additive `(1, 1, seq_len, seq_len)` mask over query rows and key columns.
A key is readable when it lies in the query's own document and within the `sliding_window`
tokens up to and including the query.
A padded micro-batch folds its padding into the last document, so the padding is masked as a
continuation of the last document. Causality already keeps it away from every real token, and it
is loss-masked.
"""
seq_len = tok_doc_idx.shape[0]
device = tok_doc_idx.device
tok_idx = torch.arange(seq_len, device=device)
distance = tok_idx[:, None] - tok_idx[None, :]
in_causal_window = (distance >= 0) & (distance < sliding_window)
same_document = tok_doc_idx[:, None] == tok_doc_idx[None, :]
readable = in_causal_window & same_document
mask = torch.zeros(seq_len, seq_len, dtype=dtype, device=device)
return mask.masked_fill_(~readable, torch.finfo(dtype).min)[None, None]
@dataclass(frozen=True)
class CompressionLayout:
"""Per-document compressed-entry layout for one compress rate.
An entry is one compressed KV vector: a compressor pools a window of `compress_rate`
consecutive tokens of the packed input sequence, the entry's source tokens, into a single
`head_dim` vector, and the attention block reads the resulting series as extra keys and values
along with its local sliding window.
"""
entry_tok_idx: Tensor # (n_entries, compress_rate) int64 - token index in the packed sequence, per entry
entry_doc_idx: Tensor # (n_entries,) int64 - which document each entry belongs to
entry_local_idx: Tensor # (n_entries,) int64 - entry index within its own document
@classmethod
def build(cls, *, cu_seqlens: Tensor, compress_rate: int) -> "CompressionLayout":
"""Lay out the compressed entries of a packed sequence, document by document.
Document `doc` of length `L_doc` gets `L_doc // compress_rate` entries; its entry `e` covers
the `compress_rate` source tokens starting at `cu_seqlens[doc] + e * compress_rate`. The
trailing `L_doc % compress_rate` tokens get no entry, exactly as the unpacked case drops
its trailing partial window; they stay visible through the local sliding window.
A packed sequence whose every document is shorter than `compress_rate` yields zero entries,
which is well-formed: the compressors then contribute nothing beyond their local window.
"""
device = cu_seqlens.device
starts = cu_seqlens[:-1].to(torch.int64)
lengths = cu_seqlens[1:].to(torch.int64) - starts
counts = lengths // compress_rate
entry_doc_idx = torch.repeat_interleave(torch.arange(counts.numel(), device=device), counts)
first_entry_of_doc = counts.cumsum(0) - counts
entry_local_idx = torch.arange(int(counts.sum()), device=device) - first_entry_of_doc[entry_doc_idx]
entry_pos = entry_local_idx * compress_rate
entry_tok_idx = (
starts[entry_doc_idx, None] + entry_pos[:, None] + torch.arange(compress_rate, device=device)[None, :]
)
return cls(
entry_tok_idx=entry_tok_idx,
entry_doc_idx=entry_doc_idx,
entry_local_idx=entry_local_idx,
)
@dataclass(frozen=True)
class PackedContext:
"""Everything an attention layer needs to know about the packed row it is running on.
The mask, the positions, the RoPE tables and the layouts all encode the same document
boundaries and are only correct together. As separate arguments they can contradict each
other: a mask built without document boundaries spans documents while a layout does not, a
sequence-global `position_ids` feeds `causal_threshold` a count that a per-document
`entry_local_idx` cannot be compared against, and a RoPE table evaluated at one set of
positions rotates queries the thresholds were not counted at. `build` derives every field
from one `seq_lens`, so none of those is reachable. It runs once per model forward, since
none of this depends on depth.
"""
attention_mask: Tensor # (1, 1, seq_len, seq_len) additive - causal, local window, document-clipped
position_ids: Tensor # (1, seq_len) int64 - token position within its own document
tok_doc_idx: Tensor # (seq_len,) int64 - which document each packed token belongs to
position_embeddings: dict[str, tuple[Tensor, Tensor]] # (cos, sin) keyed by rope type
compression_layouts: dict[int, CompressionLayout] # keyed by compress rate
def __post_init__(self) -> None:
# Only reachable by constructing the dataclass directly; `build` cannot violate it.
total_tokens = self.tok_doc_idx.shape[0]
if self.attention_mask.shape[-2] != total_tokens or self.position_ids.shape[-1] != total_tokens:
raise ValueError(
f"attention_mask covers {self.attention_mask.shape[-2]} query rows and position_ids "
f"{self.position_ids.shape[-1]} tokens, but the row has {total_tokens}"
)
@classmethod
def build(
cls,
*,
rotary_emb: DeepseekV4RotaryEmbedding,
seq_lens: Tensor,
dtype: torch.dtype,
device: torch.device,
) -> "PackedContext":
"""Derive every field from one `seq_lens`, ensuring mutual consistency.
`rotary_emb` supplies the RoPE tables and, through the config it was built from, the
sliding window and the compress rates in use. Taking the config from it rather than
alongside it keeps them from naming different architectures. `dtype` must be the dtype
attention runs at, since the mask is additive. The row is as wide as `seq_lens` says,
padding included: both packers fold their padding into the last document.
"""
config = rotary_emb.config
# Read the width before `seq_lens` moves: on a CPU `seq_lens` that costs no device sync.
total_tokens = int(seq_lens.sum())
cu_seqlens, _ = get_cu_seqlens_from_seq_lens(seq_lens.to(device=device))
tok_idx = torch.arange(total_tokens, device=device)
tok_doc_idx = torch.searchsorted(cu_seqlens[1:].to(tok_idx.dtype), tok_idx, right=True)
# Document-local by construction: a token's position is its distance from its own
# document's start, which is what `causal_threshold` and the entry rotation count in.
position_ids = (tok_idx - cu_seqlens[tok_doc_idx])[None]
compress_rates = {
config.compress_rates[layer_type]
for layer_type in set(config.layer_types)
if layer_type in config.compress_rates
}
return cls(
attention_mask=build_sliding_window_mask(
tok_doc_idx=tok_doc_idx, sliding_window=config.sliding_window, dtype=dtype
),
position_ids=position_ids,
tok_doc_idx=tok_doc_idx,
position_embeddings={
rope_type: rotary_emb(position_ids, rope_type, dtype=dtype) for rope_type in rotary_emb.layer_types
},
compression_layouts={
rate: CompressionLayout.build(cu_seqlens=cu_seqlens, compress_rate=rate) for rate in compress_rates
},
)
def check_position_ids(self, position_ids: Tensor) -> None:
"""Raise unless `position_ids` agrees with the document boundaries this context came from.
A document starts exactly where the derived positions are zero, so the check is that the
caller's positions vanish there too. A padded micro-batch restarts `position_ids` at 0
inside its last document, which this permits: padding sits mid-document, never at a start.
A sequence-global `arange` over a packed row never restarts, and a 1-based one never
reaches zero at all; both are rejected.
"""
disagrees = (self.position_ids == 0) & (position_ids != 0)
if disagrees.any():
token = int(disagrees.any(dim=0).nonzero()[0])
raise ValueError(
f"position_ids must restart at 0 at every document boundary of seq_lens: token "
f"{token} starts a document but carries {position_ids[:, token].tolist()}. A caller "
"that passes none of its own gets the 1-based arange the injected LM head "
"substitutes (see `prime_rl.trainer.models.layers.lm_head`), which this rejects."
)
def token_entry_causal_mask(self, compress_rate: int, threshold: Tensor) -> Tensor:
"""`(1, seq_len, n_entries)` bool: which compressed entries each query token may read.
Element `[0, t, e]` is true when query token `t` may read entry `e` of the rate's layout.
Both of these have to hold:
- `e` belongs to `t`'s own document, so no query reads another document's history;
- `e` closed before `t` arrived, i.e. its index within that document is below
`threshold[0, t]`, the count of entries the query's position has completed.
One `seq_lens` describes one packed row, so the leading axis is 1 and broadcasts over the
batch, as `threshold` does.
`threshold` counts per document, so it is compared against `entry_local_idx` and not
against the sequence-global entry number; those two coordinate systems disagree for every
document after the first.
"""
layout = self.compression_layouts[compress_rate]
same_document = self.tok_doc_idx[None, :, None] == layout.entry_doc_idx[None, None, :]
return same_document & (threshold.unsqueeze(-1) > layout.entry_local_idx[None, None, :])
class DeepseekV4Compressor(nn.Module):
"""Softmax-gated pooling of the token stream into one entry per `compress_rate` tokens, per the
`CompressionLayout` specification. Schematic output:
`C[e,d] = sum_s softmax_s(gate[e,s,d] + position_bias[s,d]) * kv[e,s,d]`
`kv` and `gate` are this compressor's own projections of the hidden state, gathered at the
source tokens of entry `e`'s pooling window, and `d` runs over `head_dim`. Each entry is
RMSNormed and rotated with the `compress` RoPE at its window's first source position, which
is what makes it comparable with the attention block's locally rotated KV stream. `forward`
returns the entries alongside an additive `block_bias` saying which query may read which, for
`DeepseekV4Attention` to concatenate onto its local sliding window.
`n_series` sets the slots `s` the gate ranges over. With `1` a token joins only its own
window, so windows are disjoint. With `2` the projections emit two `head_dim`-wide series
`Ca` and `Cb`, and entry `e` pools `Ca` from entry `e - 1`'s tokens together with `Cb` from
its own, so windows overlap at stride `compress_rate`; a document's first entry has no
predecessor, so its `Ca` slots are gated with `-inf`.
"""
rope_layer_type = "compress"
def __init__(self, config: DeepseekV4Config, head_dim: int, compress_rate: int, n_series: int):
super().__init__()
if n_series not in (1, 2):
raise ValueError(f"n_series must be 1 or 2, got {n_series}")
self.compress_rate = compress_rate
self.head_dim = head_dim
self.n_series = n_series
self.kv_proj = nn.Linear(config.hidden_size, n_series * head_dim, bias=False)
self.gate_proj = nn.Linear(config.hidden_size, n_series * head_dim, bias=False)
self.position_bias = nn.Parameter(torch.zeros(compress_rate, n_series * head_dim))
self.kv_norm = RMSNorm(RMSNormConfig(hidden_size=head_dim, eps=config.rms_norm_eps))
self.rotary_emb = DeepseekV4RotaryEmbedding(config)
def _overlap_with_previous_window(
self, kv: torch.Tensor, gate: torch.Tensor, layout: CompressionLayout
) -> tuple[torch.Tensor, torch.Tensor]:
"""Widen each entry from `compress_rate` slots to `2 * compress_rate`, the `n_series == 2` case."""
n_entries = layout.entry_tok_idx.shape[0]
# Shift the `Ca` series one entry later so entry `e` sees entry `e - 1`'s. The first
# entry of every document has no predecessor, and the entry sitting before it in the
# packed sequence belongs to another document, so both halves are cleared: the gate to
# `-inf` and the values to zero. Zeroing is not redundant with the gate, because a
# zero softmax weight against a non-finite value would still yield NaN.
previous = (torch.arange(n_entries, device=kv.device) - 1).clamp(min=0)
is_first_entry_in_doc = (layout.entry_local_idx == 0)[None, :, None, None]
previous_kv = kv[:, previous, :, : self.head_dim].masked_fill(is_first_entry_in_doc, 0.0)
previous_gate = gate[:, previous, :, : self.head_dim].masked_fill(is_first_entry_in_doc, float("-inf"))
return (
torch.cat([previous_kv, kv[..., self.head_dim :]], dim=2),
torch.cat([previous_gate, gate[..., self.head_dim :]], dim=2),
)
def compress(self, hidden_states: torch.Tensor, packed: PackedContext) -> torch.Tensor:
"""Compress `(batch, seq_len, hidden_size)` to `(batch, n_entries, head_dim)`.
The layout at this compressor's own rate decides which source tokens each entry pools.
"""
batch = hidden_states.shape[0]
layout = packed.compression_layouts[self.compress_rate]
kv = self.kv_proj(hidden_states)[:, layout.entry_tok_idx]
gate = self.gate_proj(hidden_states)[:, layout.entry_tok_idx] + self.position_bias
if self.n_series == 2:
kv, gate = self._overlap_with_previous_window(kv, gate, layout)
# fp32 softmax: in bf16 the gate logits of a wide window collapse onto each other.
weights = gate.softmax(dim=2, dtype=torch.float32).to(kv.dtype)
compressed = self.kv_norm((kv * weights).sum(dim=2))
entry_first_tok_pos = layout.entry_local_idx * self.compress_rate
cos, sin = self.rotary_emb(
entry_first_tok_pos.unsqueeze(0).expand(batch, -1), self.rope_layer_type, dtype=compressed.dtype
)
return apply_rotary_pos_emb_interleaved(compressed.unsqueeze(1), cos, sin).squeeze(1)
def causal_threshold(self, position_ids: torch.Tensor) -> torch.Tensor:
"""Number of compressed entries that query `t` may read, shaped like `position_ids`.
Entry `e` pools source tokens up to index `(e + 1) * compress_rate - 1`, so it only
becomes readable once the query has reached that token.
"""
return (position_ids + 1) // self.compress_rate
def init_weights(self, init_std: float) -> None:
# `init_std` is unused: the projections are initialized by the caller and the
# position bias starts at zero, i.e. a uniform gate over the pooling window.
nn.init.zeros_(self.position_bias)
class DeepseekV4IndexerScorer(nn.Module):
"""Lightning-Indexer score `score[t,e] = sum_h w[t,h] * ReLU(q[t,h,d] * k[e,d])`.
Query token `t` against compressed entry `e`, over indexer heads `h` and `index_head_dim`
channels `d`. The per-head weights `w[t,h]` come off the hidden state directly rather than
from a query-key interaction, which keeps the scorer one matmul deep. It runs in fp32: the
scores only feed a top-k, so the width costs little and near-ties are not decided by bf16
rounding.
"""
def __init__(self, config: DeepseekV4Config):
super().__init__()
self.softmax_scale = config.index_head_dim**-0.5
self.weights_scaling = config.index_n_heads**-0.5
self.weights_proj = nn.Linear(config.hidden_size, config.index_n_heads, bias=False)
def forward(self, q: torch.Tensor, compressed_kv: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor:
"""Score `q` `(batch, seq, heads, dim)` against `compressed_kv` `(batch, entries, dim)`."""
scores = torch.matmul(q.float(), compressed_kv.transpose(-1, -2).float().unsqueeze(1))
scores = F.relu(scores) * self.softmax_scale
weights = self.weights_proj(hidden_states).float() * self.weights_scaling
return (scores * weights.unsqueeze(-1)).sum(dim=2)
class DeepseekV4Indexer(nn.Module):
"""Lightning Indexer: picks the `index_topk` compressed entries each query may read.
It owns a compressor at the narrow `index_head_dim` and scores each query against its
entries. The indices it returns address the entries of the compressor that owns it: both
share `compress_rate` and the `compress` RoPE base, so entry `e` in one covers the same
source tokens as entry `e` in the other, and the scores depend only on the query-key
distance.
Each query gets `min(index_topk, entries)` picks. An early query has fewer entries whose
source tokens all lie at or before it, and its surplus picks come back as `-1`.
"""
def __init__(self, config: DeepseekV4Config):
super().__init__()
self.head_dim = config.index_head_dim
self.num_heads = config.index_n_heads
self.index_topk = config.index_topk
self.compressor = DeepseekV4Compressor(
config, self.head_dim, config.compress_rates["compressed_sparse_attention"], n_series=2
)
self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False)
self.scorer = DeepseekV4IndexerScorer(config)
def forward(self, hidden_states: torch.Tensor, q_residual: torch.Tensor, packed: PackedContext) -> torch.Tensor:
batch, seq_len, _ = hidden_states.shape
compressed_kv = self.compressor.compress(hidden_states, packed)
compressed_len = compressed_kv.shape[1]
top_k = min(self.index_topk, compressed_len)
# The token-position table for this rope type is already on `packed`; the compressor's own
# rotary is only ever evaluated at entry positions.
cos, sin = packed.position_embeddings[self.compressor.rope_layer_type]
q = self.q_b_proj(q_residual).view(batch, seq_len, -1, self.head_dim).transpose(1, 2)
q = apply_rotary_pos_emb_interleaved(q, cos, sin).transpose(1, 2)
scores = self.scorer(q, compressed_kv, hidden_states)
if compressed_len == 0:
return scores.topk(top_k, dim=-1).indices
threshold = self.compressor.causal_threshold(packed.position_ids)
readable = packed.token_entry_causal_mask(self.compressor.compress_rate, threshold).expand_as(scores)
scores = scores.masked_fill(~readable, float("-inf"))
top_k_indices = scores.topk(top_k, dim=-1).indices
# An early query has fewer than `top_k` readable entries, so top-k still hands back
# masked-out ones. Mark those `-1` rather than letting them leak into attention.
return torch.where(readable.gather(-1, top_k_indices), top_k_indices, torch.full_like(top_k_indices, -1))
def init_weights(self, init_std: float) -> None:
self.compressor.init_weights(init_std)
class DeepseekV4CSACompressor(DeepseekV4Compressor):
"""Compressed Sparse Attention compressor: the sparse long-range half of a CSA layer.
Two series at a fine compress rate, with overlapping windows. A Lightning Indexer scores
the entries and keeps the `index_topk` best per query, and the returned `block_bias` is
that selection: `0` on the selected entries, `-inf` everywhere else. It needs no separate
causal term, because the indexer only selects entries whose source tokens all lie at or
before the query.
"""
def __init__(self, config: DeepseekV4Config):
super().__init__(config, config.head_dim, config.compress_rates["compressed_sparse_attention"], n_series=2)
self.indexer = DeepseekV4Indexer(config)
def forward(
self, hidden_states: torch.Tensor, q_residual: torch.Tensor, packed: PackedContext
) -> tuple[torch.Tensor, torch.Tensor]:
batch, seq_len, _ = hidden_states.shape
compressed_kv = self.compress(hidden_states, packed).unsqueeze(1)
compressed_len = compressed_kv.shape[2]
# The indexer reads the same layout: it compresses the same source windows at a narrower
# head dim, so its entry `e` and this compressor's entry `e` are the same window.
top_k_indices = self.indexer(hidden_states, q_residual, packed)
# The `-1` sentinels are scattered into one throwaway column that is sliced back off.
safe_indices = torch.where(top_k_indices >= 0, top_k_indices, torch.full_like(top_k_indices, compressed_len))
block_bias = compressed_kv.new_full((batch, 1, seq_len, compressed_len + 1), float("-inf"))
block_bias.scatter_(-1, safe_indices.unsqueeze(1), 0.0)
return compressed_kv, block_bias[..., :compressed_len]
def init_weights(self, init_std: float) -> None:
super().init_weights(init_std)
self.indexer.init_weights(init_std)
class DeepseekV4HCACompressor(DeepseekV4Compressor):
"""Heavily Compressed Attention compressor: the dense long-range half of an HCA layer.
One series at a coarse compress rate, with disjoint windows. There is no indexer: a query
reads every entry whose source tokens all lie at or before it, and the returned
`block_bias` carries that rule.
"""
def __init__(self, config: DeepseekV4Config):
super().__init__(config, config.head_dim, config.compress_rates["heavily_compressed_attention"], n_series=1)
def forward(
self, hidden_states: torch.Tensor, q_residual: torch.Tensor, packed: PackedContext
) -> tuple[torch.Tensor, torch.Tensor]:
"""`q_residual` is part of the compressor contract but unused: HCA has no indexer."""
batch, seq_len, _ = hidden_states.shape
compressed_kv = self.compress(hidden_states, packed).unsqueeze(1)
compressed_len = compressed_kv.shape[2]
threshold = self.causal_threshold(packed.position_ids)
readable = packed.token_entry_causal_mask(self.compress_rate, threshold).unsqueeze(1)
block_bias = compressed_kv.new_zeros((batch, 1, seq_len, compressed_len))
return compressed_kv, block_bias.masked_fill_(~readable, float("-inf"))
COMPRESSOR_CLASSES = {
"sliding_attention": None,
"compressed_sparse_attention": DeepseekV4CSACompressor,
"heavily_compressed_attention": DeepseekV4HCACompressor,
}
class DeepseekV4Attention(nn.Module):
"""DeepSeek-V4 self-attention.
Four things set it apart from a standard attention block:
1. Shared-KV multi-query attention. `kv_proj` emits a single `head_dim`-wide vector
per token that serves as both key and value for every query head.
2. Partial interleaved RoPE on the trailing `qk_rope_head_dim` channels of each head.
Because the value carries that rotation too, the conjugate rotation is applied to
the attention output, which leaves each key's contribution a function of its
relative distance to the query.
3. A per-head learnable attention sink.
4. A grouped low-rank output projection (`o_a_proj` then `o_b_proj`).
Every layer type runs that same core over its local sliding window. The two compressed
types additionally own a `compressor` whose output is concatenated onto the local KV,
which is how a layer sees past the window.
"""
def __init__(self, config: DeepseekV4Config, layer_idx: int):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.layer_type = config.layer_types[layer_idx]
# Rope types are labelled `main` / `compress`, independently of `layer_types`:
# sliding layers take the plain base, the compressed variants share their
# compressor's base.
self.rope_layer_type = "main" if self.layer_type == "sliding_attention" else "compress"
self.num_heads = config.num_attention_heads
self.head_dim = config.head_dim
self.attention_dropout = config.attention_dropout
self.scaling = self.head_dim**-0.5
self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=False)
self.q_a_norm = RMSNorm(RMSNormConfig(hidden_size=config.q_lora_rank, eps=config.rms_norm_eps))
self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False)
self.q_b_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps)
self.kv_proj = nn.Linear(config.hidden_size, self.head_dim, bias=False)
self.kv_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
self.o_a_proj = DeepseekV4GroupedLinear(
self.num_heads * self.head_dim // config.o_groups,
config.o_groups * config.o_lora_rank,
config.o_groups,
)
self.o_b_proj = nn.Linear(config.o_groups * config.o_lora_rank, config.hidden_size, bias=False)
self.sinks = nn.Parameter(torch.zeros(self.num_heads))
compressor_class = COMPRESSOR_CLASSES[self.layer_type]
self.compressor = compressor_class(config) if compressor_class is not None else None
def forward(self, hidden_states: torch.Tensor, packed: PackedContext) -> tuple[torch.Tensor, None]:
"""`packed` carries the document boundaries every pathway below is clipped at."""
# Shape keys in the comments below:
#
# - `b`: batch
# - `t`: token in the packed row
# - `h`: attention head
# - `d`: head_dim
# - `e`: compressed entry
# - `r`: q_lora_rank
# - `g`: o_groups
# - `l`: o_lora_rank
#
# `hidden_states` is (b, t, hidden_size).
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim) # (b, t, -1, d): the -1 is h for q, 1 for kv
cos, sin = packed.position_embeddings[self.rope_layer_type] # (1, t, qk_rope_head_dim // 2) each
q_residual = self.q_a_norm(self.q_a_proj(hidden_states)) # (b, t, r)
q = self.q_b_proj(q_residual).view(*hidden_shape).transpose(1, 2) # (b, h, t, d)
q = apply_rotary_pos_emb_interleaved(self.q_b_norm(q), cos, sin)
kv = self.kv_norm(self.kv_proj(hidden_states)).view(*hidden_shape).transpose(1, 2) # (b, 1, t, d)
kv = apply_rotary_pos_emb_interleaved(kv, cos, sin)
attention_mask = packed.attention_mask # (1, 1, t, t)
if self.compressor is not None:
# (b, 1, e, d), (b, 1, t, e)
compressed_kv, block_bias = self.compressor(hidden_states, q_residual, packed)
kv = torch.cat([kv, compressed_kv], dim=2) # (b, 1, t + e, d)
# The compressed entries live outside the local window, so the sliding mask says
# nothing about them; `block_bias` carries their per-query causality and the
# indexer's selection. Zero-padding instead would let every query read every one.
attention_mask = torch.cat(
[attention_mask.expand(*block_bias.shape[:-1], -1), block_bias.to(attention_mask.dtype)], dim=-1
) # (b, 1, t, t + e)
attn_output = eager_attention_with_sinks(
q,
kv,
kv,
self.sinks,
attention_mask,
scaling=self.scaling,
dropout=self.attention_dropout,
training=self.training,
) # (b, t, h, d)
# The value stream is the key stream, so it arrived rotated. Rotating the output
# by the conjugate angle at the query position cancels that out.
attn_output = apply_rotary_pos_emb_interleaved(attn_output, cos, -sin, unsqueeze_dim=2)
# (b, t, g, h * d // g) -> (b, t, g, l) -> (b, t, g * l)
grouped = self.o_a_proj(attn_output.reshape(*input_shape, self.config.o_groups, -1)).flatten(2)
return self.o_b_proj(grouped), None # (b, t, hidden_size)
def init_weights(self, init_std: float) -> None:
# `init_std` is only passed through: the sinks are the only parameter this owns
# outright and they start at zero.
nn.init.zeros_(self.sinks)
if self.compressor is not None:
self.compressor.init_weights(init_std)
__all__ = [
"CompressionLayout",
"DeepseekV4Attention",
"DeepseekV4CSACompressor",
"DeepseekV4GroupedLinear",
"DeepseekV4HCACompressor",
"DeepseekV4Indexer",
"DeepseekV4IndexerScorer",
"PackedContext",
"build_sliding_window_mask",
"eager_attention_with_sinks",
]
@@ -0,0 +1,360 @@
from typing import Any
from huggingface_hub.dataclasses import strict
from transformers.configuration_utils import PretrainedConfig
from prime_rl.utils.transformers_compat import DEEPSEEK_V4_LAYER_TYPES, allow_deepseek_v4_layer_types
# Below transformers 5.15 the base `validate_layer_type` rejects V4's layer types outright, and
# it runs from `super().__init__()`, ahead of this class's own override. The inference half of
# the repo needs the same shim (see `inference/patches.py`).
allow_deepseek_v4_layer_types()
@strict
class DeepseekV4Config(PretrainedConfig):
"""Configuration for DeepSeek-V4 (Flash / Pro) models.
DeepSeek-V4 differs from V3 in three structural ways, all controlled from here:
1. The residual stream is `hc_mult` parallel streams tied together by
manifold-constrained hyper-connections (mHC), governed by `hc_mult`,
`hc_sinkhorn_iters` and `hc_eps`.
2. Attention is a per-layer mix of compressed variants selected by `layer_types`,
with the per-type compression rate given by `compress_rates` and a Lightning
Indexer sized by `index_n_heads` / `index_head_dim` / `index_topk`.
3. The MLP schedule bootstraps the first `num_hash_layers` layers with a frozen hash
router before switching to standard top-k routed MoE.
Args:
vocab_size: Vocabulary size.
hidden_size: Dimension of the hidden representations.
moe_intermediate_size: Intermediate dimension of each expert. Also aliased as
`intermediate_size` (the shared expert reads that name).
num_hidden_layers: Number of decoder layers.
num_attention_heads: Number of attention query heads.
num_key_value_heads: Number of key/value heads. V4 is MQA, so this is 1.
head_dim: Dimension of each attention head.
q_lora_rank: Rank of the query down-projection.
partial_rotary_factor: Fraction of `head_dim` that gets RoPE. Defaults to
`qk_rope_head_dim / head_dim` if `qk_rope_head_dim` is given, else 64/512.
qk_rope_head_dim: Legacy way to express `partial_rotary_factor`. Only read when
`partial_rotary_factor` is not given; the derived value is always stored as
the `qk_rope_head_dim` attribute.
rope_theta: RoPE base for the main self-attention rotary.
compress_rope_theta: RoPE base for the compressed attention branches.
rope_parameters: RoPE parameters, nested under the `main` and `compress` rope
types. A flat dict is broadcast into both.
rope_scaling: Legacy alias for `rope_parameters`.
max_position_embeddings: Maximum sequence length.
sliding_window: Local window size used by every attention block's
sliding-window branch.
o_groups: Number of head groups in the grouped output projection.
o_lora_rank: Per-group intermediate dimension of the grouped output projection.
layer_types: Per-layer attention schedule, entries drawn from
`DEEPSEEK_V4_LAYER_TYPES`. Defaults to two heavily-compressed bootstrap
layers followed by an alternating heavy/sparse interleave.
compress_rates: Per-layer-type compression rate.
index_n_heads: Number of Lightning Indexer query heads.
index_head_dim: Lightning Indexer head dimension.
index_topk: Number of compressed entries the Lightning Indexer keeps per query.
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.
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.
routed_scaling_factor: Scaling factor applied to the routed expert output.
num_hash_layers: Number of leading hash-routed layers; the remaining layers use
standard top-k routed MoE.
swiglu_limit: Clamp applied to the expert gate/up pre-activations.
hc_mult: Number of parallel residual streams carried by mHC.
hc_sinkhorn_iters: Sinkhorn-Knopp iterations used to project the mHC combine
matrix onto the doubly-stochastic manifold.
hc_eps: Numerical floor for the Sinkhorn-Knopp normalization.
hidden_act: Activation function of the MLPs.
initializer_range: Standard deviation of the weight initializer.
rms_norm_eps: Epsilon of the RMS normalization layers.
use_cache: Whether to return past key/values.
tie_word_embeddings: Whether to tie the input and output embeddings.
attention_bias: Whether the attention projections carry a bias.
mlp_bias: Whether the MLP projections carry a bias.
attention_dropout: Dropout ratio on the attention probabilities.
output_router_logits: Whether to return the router logits.
router_aux_loss_coef: Coefficient of the router auxiliary loss.
router_jitter_noise: Jitter noise added to the router inputs during training.
"""
model_type = "deepseek_v4"
keys_to_ignore_at_inference = ["past_key_values"]
# `num_local_experts` is the name FP8 / EP integrations read; `intermediate_size` is
# what the shared-expert MLP reads, and V4 only ships `moe_intermediate_size`.
attribute_map = {
"num_local_experts": "n_routed_experts",
"intermediate_size": "moe_intermediate_size",
}
# `rope_parameters` is keyed by rope type, not by `layer_types`.
_rope_type_labels = ("main", "compress")
# `qk_rope_head_dim` (64) / `head_dim` (512).
default_partial_rotary_factor = 64 / 512
def __init__(
self,
vocab_size: int = 129280,
hidden_size: int = 4096,
moe_intermediate_size: int = 2048,
num_hidden_layers: int = 43,
num_attention_heads: int = 64,
num_key_value_heads: int = 1,
head_dim: int = 512,
q_lora_rank: int = 1024,
partial_rotary_factor: float | None = None,
qk_rope_head_dim: int | None = None,
rope_theta: float = 10000.0,
compress_rope_theta: float = 160000.0,
rope_parameters: dict[str, Any] | None = None,
rope_scaling: dict[str, Any] | None = None,
max_position_embeddings: int = 1048576,
sliding_window: int = 128,
o_groups: int = 8,
o_lora_rank: int = 1024,
layer_types: list[str] | None = None,
compress_rates: dict[str, int] | None = None,
index_n_heads: int = 64,
index_head_dim: int = 128,
index_topk: int = 512,
num_experts_per_tok: int = 6,
n_routed_experts: int = 256,
n_shared_experts: int = 1,
scoring_func: str = "sqrtsoftplus",
topk_method: str = "noaux_tc",
norm_topk_prob: bool = True,
routed_scaling_factor: float = 1.5,
num_hash_layers: int = 3,
swiglu_limit: float = 10.0,
hc_mult: int = 4,
hc_sinkhorn_iters: int = 20,
hc_eps: float = 1e-6,
hidden_act: str = "silu",
initializer_range: float = 0.02,
rms_norm_eps: float = 1e-6,
use_cache: bool = True,
tie_word_embeddings: bool = False,
attention_bias: bool = False,
mlp_bias: bool = False,
attention_dropout: float = 0.0,
output_router_logits: bool = False,
router_aux_loss_coef: float = 0.001,
router_jitter_noise: float = 0.0,
pad_token_id: int | None = None,
bos_token_id: int | None = 0,
eos_token_id: int | list[int] | None = 1,
**kwargs,
):
# Real checkpoints ship the V3-flavoured legacy schema (a flat per-layer
# `compress_ratios` list of 0/CSA-rate/HCA-rate) instead of `layer_types`. Pop it before
# `super().__init__(**kwargs)` sees it, so it can't silently overwrite the derived
# `self.compress_ratios` below without ever informing `self.layer_types`.
legacy_compress_ratios = kwargs.pop("compress_ratios", None)
raw_rope_parameters = rope_parameters if rope_parameters is not None else rope_scaling
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.moe_intermediate_size = moe_intermediate_size
self.num_hidden_layers = num_hidden_layers
self.max_position_embeddings = max_position_embeddings
# Attention
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.head_dim = head_dim
self.q_lora_rank = q_lora_rank
self.rope_theta = rope_theta
self.compress_rope_theta = compress_rope_theta
self.sliding_window = sliding_window
self.o_groups = o_groups
self.o_lora_rank = o_lora_rank
self.attention_bias = attention_bias
self.attention_dropout = attention_dropout
self.index_n_heads = index_n_heads
self.index_head_dim = index_head_dim
self.index_topk = index_topk
self.partial_rotary_factor = (
partial_rotary_factor
if partial_rotary_factor is not None
else (qk_rope_head_dim / head_dim if qk_rope_head_dim is not None else self.default_partial_rotary_factor)
)
self.qk_rope_head_dim = int(head_dim * self.partial_rotary_factor)
self.compress_rates = (
dict(compress_rates)
if compress_rates is not None
else {"compressed_sparse_attention": 4, "heavily_compressed_attention": 128}
)
if layer_types is None and legacy_compress_ratios is not None:
ratio_to_layer_type = {0: "sliding_attention", **{rate: lt for lt, rate in self.compress_rates.items()}}
layer_types = [ratio_to_layer_type[ratio] for ratio in legacy_compress_ratios[:num_hidden_layers]]
if layer_types is None:
# Two heavily-compressed bootstrap layers, then alternate sparse / heavy.
interleave = [
"compressed_sparse_attention" if i % 2 else "heavily_compressed_attention"
for i in range(max(num_hidden_layers - 2, 0))
]
layer_types = ["heavily_compressed_attention"] * min(num_hidden_layers, 2) + interleave
self.layer_types = list(layer_types)
# We don't use this, but vLLM's attention code reads it directly.
self.compress_ratios = [self.compress_rates.get(lt, 0) for lt in self.layer_types]
# MoE
self.num_experts_per_tok = num_experts_per_tok
self.n_routed_experts = n_routed_experts
self.n_shared_experts = n_shared_experts
self.scoring_func = scoring_func
self.topk_method = topk_method
self.norm_topk_prob = norm_topk_prob
self.routed_scaling_factor = routed_scaling_factor
self.num_hash_layers = num_hash_layers
self.swiglu_limit = swiglu_limit
self.output_router_logits = output_router_logits
self.router_aux_loss_coef = router_aux_loss_coef
self.router_jitter_noise = router_jitter_noise
# Manifold-constrained hyper-connections
self.hc_mult = hc_mult
self.hc_sinkhorn_iters = hc_sinkhorn_iters
self.hc_eps = hc_eps
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.mlp_bias = mlp_bias
super().__init__(
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
# Set after the base __init__: its `validate_layer_type` hook is registered at
# class-decoration time on `PretrainedConfig` (so a subclass override never runs)
# and only accepts the generic "dense" / "sparse" labels, not V4's hash_moe / moe.
# Only exists for duck-typing with HF's real modeling code (see `to_dict`) --
# `num_hash_layers` is this class's own source of truth.
self.mlp_layer_types = ["hash_moe"] * min(num_hidden_layers, num_hash_layers) + ["moe"] * max(
0, num_hidden_layers - num_hash_layers
)
self.rope_parameters = self._nest_rope_parameters(raw_rope_parameters)
self.validate_architecture()
def _nest_rope_parameters(self, raw_rope_parameters: dict[str, Any] | None) -> dict[str, dict[str, Any]]:
"""Split RoPE parameters into the `main` and `compress` sets the rotary reads."""
rope_parameters = raw_rope_parameters or {}
if isinstance(rope_parameters.get("main"), dict) and isinstance(rope_parameters.get("compress"), dict):
return {"main": dict(rope_parameters["main"]), "compress": dict(rope_parameters["compress"])}
scaling = {key: value for key, value in rope_parameters.items() if key not in ("main", "compress")}
main = {
"rope_type": "default",
"rope_theta": self.rope_theta,
"partial_rotary_factor": self.partial_rotary_factor,
}
compress = {
**scaling,
"rope_theta": self.compress_rope_theta,
"partial_rotary_factor": self.partial_rotary_factor,
}
# Real checkpoints store the compress branch's YaRN scaling under the legacy flat
# `rope_scaling` key, which only ever carries `"type"`, never `"rope_type"` -- HF's
# own config gets that renamed for free via a generic mixin method that runs before
# its DS4-specific post-init logic, but our manual __init__ never goes through it.
compress["rope_type"] = scaling.get("rope_type", scaling.get("type", "default"))
if compress["rope_type"] == "yarn":
# The V4 reference does not scale cos/sin by YaRN's computed mscale; leaving the
# key unset lets `_compute_yarn_parameters` derive `0.1*log(factor)+1 != 1.0`.
compress.setdefault("attention_factor", 1.0)
return {"main": main, "compress": compress}
def convert_rope_params_to_dict(self, **kwargs):
# Dead code: `rope_theta`/`rope_scaling` never reach here via `**kwargs`, and
# `self.rope_parameters` is overwritten by `_nest_rope_parameters` right after
# `super().__init__()` returns regardless. Kept for parity with the same
# (also-dead) override in `laguna/configuration_laguna.py`.
return kwargs
def validate_architecture(self) -> None:
"""Compress_rates completeness: every non-sliding layer type needs a rate."""
for layer_type in set(self.layer_types) - {"sliding_attention"}:
if layer_type not in self.compress_rates:
raise ValueError(f"compress_rates is missing a rate for layer type {layer_type!r}.")
def validate_rope(self) -> None:
"""Validate the `main`/`compress` rope-type-keyed sub-dicts directly.
The base `RotaryEmbeddingConfigMixin.validate_rope` checks `keys ⊆ layer_types`
against the *attention* layer types and falls back to treating the whole
`rope_parameters` dict as one rope type's params when that fails -- which is always,
for V4, since it's keyed by `main`/`compress` rope-type labels instead. Iterate
those labels directly, matching upstream HF's own `DeepseekV4Config.validate_rope`.
"""
rope_parameters_dict = self.rope_parameters or {}
ignore_keys = self.ignore_keys_at_rope_validation
for rope_type_label in self._rope_type_labels:
rope_parameters = rope_parameters_dict.get(rope_type_label)
if not isinstance(rope_parameters, dict):
continue
rope_type = rope_parameters.get("rope_type", rope_parameters.get("type", "default"))
rope_parameters["rope_type"] = rope_type
validation_fn = getattr(self, f"_validate_{rope_type}_rope_parameters", None)
if validation_fn is None:
continue
self.rope_parameters = rope_parameters
try:
validation_fn(rope_parameters, ignore_keys=ignore_keys)
finally:
self.rope_parameters = rope_parameters_dict
def to_dict(self) -> dict[str, Any]:
"""Drop the derived `mlp_layer_types` duck-typing shim before serializing.
`num_hash_layers` is the on-disk source of truth (matching the real checkpoint);
`mlp_layer_types` only exists in memory so HF's real `DeepseekV4SparseMoeBlock`
(which reads `config.mlp_layer_types[layer_idx]` directly) still works when this
config is handed to it, e.g. in HF-parity tests.
"""
output = super().to_dict()
output.pop("mlp_layer_types", None)
return output
def validate_layer_type(self) -> None:
"""Narrow `@strict`'s generic layer-type check to V4's own attention vocabulary.
Re-decorating this class with `@strict` (matching upstream HF's own
`DeepseekV4Config`) makes `@strict` rediscover validators scoped to this
class, so this override is what runs after `__init__` returns, unlike a
plain method override on an undecorated subclass, whose `validate()`
closure would keep calling the base `PretrainedConfig.validate_layer_type`.
The base one still runs first, from `super().__init__()`, but it checks
`layer_types` against transformers' generic vocabulary, which
`allow_deepseek_v4_layer_types` widened above precisely so V4's names get
through it. Narrowing them to `DEEPSEEK_V4_LAYER_TYPES` is what this adds.
"""
if len(self.layer_types) != self.num_hidden_layers:
raise ValueError(
f"layer_types length ({len(self.layer_types)}) must equal num_hidden_layers ({self.num_hidden_layers})."
)
unknown = sorted({layer_type for layer_type in self.layer_types if layer_type not in DEEPSEEK_V4_LAYER_TYPES})
if unknown:
raise ValueError(f"layer_types entries must be one of {DEEPSEEK_V4_LAYER_TYPES}; got {unknown}.")
if not 0 <= self.num_hash_layers <= self.num_hidden_layers:
raise ValueError(
f"num_hash_layers ({self.num_hash_layers}) must be between 0 and num_hidden_layers ({self.num_hidden_layers})."
)
__all__ = ["DeepseekV4Config"]
@@ -0,0 +1,109 @@
"""On-disk <-> PrimeRL weight conversion for DeepSeek V4.
"On-disk" means the safetensors keys DeepSeek publishes for
`deepseek-ai/DeepSeek-V4-Flash-0731`, listed in its `model.safetensors.index.json`: a compact
naming (`attn`, `ffn`, `wkv`, `wq_a`, `hc_attn_base`, per-expert `w1`/`w2`/`w3`) that carries no
`model.` prefix on any of its 72317 keys.
Nothing else translates those names. The pinned `transformers` ships no DeepSeek V4 model and no
`conversion_mapping` entry for one, and prime-rl reads the raw safetensors directly for DCP
sharding rather than going through `from_pretrained`, so the chain below is the only mapping
between the published checkpoint and prime-rl's module tree.
It runs both ways: forward for `load_dcp_from_hf`, and reversed (`convert_to_hf`) for the weight
broadcast, whose output vLLM's own loader reads back under the published names.
"""
from __future__ import annotations
from prime_rl.trainer.models.conversion_ops import (
ConvOp,
Drop,
PrefixRename,
Rename,
routed_experts_op,
)
def _layer_ops(layer_idx: int, layer_type: str) -> list[ConvOp]:
"""One layer's published names -> prime-rl's module names, one hop per key."""
p = f"layers.{layer_idx}"
attn, moe = f"{p}.attn", f"{p}.ffn"
prime_attn, prime_moe = f"{p}.self_attn", f"{p}.mlp"
ops: list[ConvOp] = [
Rename(f"{p}.attn_norm.weight", f"{p}.input_layernorm.weight"),
Rename(f"{p}.ffn_norm.weight", f"{p}.post_attention_layernorm.weight"),
Rename(f"{p}.hc_attn_fn", f"{p}.attn_hc.fn"),
Rename(f"{p}.hc_attn_base", f"{p}.attn_hc.base"),
Rename(f"{p}.hc_attn_scale", f"{p}.attn_hc.scale"),
Rename(f"{p}.hc_ffn_fn", f"{p}.ffn_hc.fn"),
Rename(f"{p}.hc_ffn_base", f"{p}.ffn_hc.base"),
Rename(f"{p}.hc_ffn_scale", f"{p}.ffn_hc.scale"),
Rename(f"{attn}.wq_a.weight", f"{prime_attn}.q_a_proj.weight"),
Rename(f"{attn}.q_norm.weight", f"{prime_attn}.q_a_norm.weight"),
Rename(f"{attn}.wq_b.weight", f"{prime_attn}.q_b_proj.weight"),
Rename(f"{attn}.wkv.weight", f"{prime_attn}.kv_proj.weight"),
# Attention's own kv_norm keeps its leaf name; only the parent module differs.
Rename(f"{attn}.kv_norm.weight", f"{prime_attn}.kv_norm.weight"),
Rename(f"{attn}.wo_a.weight", f"{prime_attn}.o_a_proj.weight"),
Rename(f"{attn}.wo_b.weight", f"{prime_attn}.o_b_proj.weight"),
Rename(f"{attn}.attn_sink", f"{prime_attn}.sinks"),
Rename(f"{moe}.gate.weight", f"{prime_moe}.router.gate.weight"),
Rename(f"{moe}.gate.bias", f"{prime_moe}.router.selection_bias"),
Rename(f"{moe}.gate.tid2eid", f"{prime_moe}.router.tid2eid"),
Rename(f"{moe}.shared_experts.w1.weight", f"{prime_moe}.shared_expert.gate_proj.weight"),
Rename(f"{moe}.shared_experts.w2.weight", f"{prime_moe}.shared_expert.down_proj.weight"),
Rename(f"{moe}.shared_experts.w3.weight", f"{prime_moe}.shared_expert.up_proj.weight"),
# The routed experts' per-expert w1/w2/w3 stack into prime's per-expert-batched tensors,
# named as in every other prime-rl MoE.
routed_experts_op(
p,
hf_experts="ffn.experts",
prime_experts="mlp.experts",
proj_order=(("gate_proj", "w1"), ("down_proj", "w2"), ("up_proj", "w3")),
),
]
if layer_type in ("compressed_sparse_attention", "heavily_compressed_attention"):
comp, prime_comp = f"{attn}.compressor", f"{prime_attn}.compressor"
ops += [
Rename(f"{comp}.wkv.weight", f"{prime_comp}.kv_proj.weight"),
Rename(f"{comp}.wgate.weight", f"{prime_comp}.gate_proj.weight"),
Rename(f"{comp}.norm.weight", f"{prime_comp}.kv_norm.weight"),
Rename(f"{comp}.ape", f"{prime_comp}.position_bias"),
]
if layer_type == "compressed_sparse_attention":
# PrimeRL hangs the indexer off the CSA compressor rather than beside it, so its whole
# subtree moves one level in. Its own (much narrower) compressor nests inside either way.
idx, prime_idx = f"{attn}.indexer", f"{prime_attn}.compressor.indexer"
ops += [
Rename(f"{idx}.wq_b.weight", f"{prime_idx}.q_b_proj.weight"),
Rename(f"{idx}.weights_proj.weight", f"{prime_idx}.scorer.weights_proj.weight"),
Rename(f"{idx}.compressor.wkv.weight", f"{prime_idx}.compressor.kv_proj.weight"),
Rename(f"{idx}.compressor.wgate.weight", f"{prime_idx}.compressor.gate_proj.weight"),
Rename(f"{idx}.compressor.norm.weight", f"{prime_idx}.compressor.kv_norm.weight"),
Rename(f"{idx}.compressor.ape", f"{prime_idx}.compressor.position_bias"),
]
return ops
def conversion_chain(config) -> list[ConvOp]:
# Neither HF nor prime-rl instantiates the multi-token-prediction heads a V4 checkpoint
# ships. They sit at the top level (`mtp.0.hc_attn_base`, ...), never nested inside a layer.
ops: list[ConvOp] = [
Drop("mtp.", is_prefix=True),
Rename("head.weight", "lm_head.weight"),
]
for layer_idx in range(config.num_hidden_layers):
ops.extend(_layer_ops(layer_idx, config.layer_types[layer_idx]))
# Every op above is written in the bare on-disk spelling, so the `model.` prefix that
# prime-rl's module tree carries goes on last: the non-layer parameters individually, and
# everything under `layers.` in one reparenting pass.
ops += [
Rename("embed.weight", "model.embed_tokens.weight"),
Rename("norm.weight", "model.norm.weight"),
Rename("hc_head_fn", "model.hc_head.hc_fn"),
Rename("hc_head_base", "model.hc_head.hc_base"),
Rename("hc_head_scale", "model.hc_head.hc_scale"),
PrefixRename("layers.", "model.layers."),
]
return ops
@@ -0,0 +1,81 @@
"""Dequantize the real DeepSeek V4 Flash checkpoint's on-disk fp8/MXFP4 weights.
The real `deepseek-ai/DeepSeek-V4-Flash-0731` checkpoint ships dense linear layers as
block-quantized FP8 (`float8_e4m3fn` weight + `float8_e8m0fnu` per-block scale, 128x128
blocks) and MoE expert weights as packed MXFP4 (two 4-bit e2m1 values per `int8` byte,
`float8_e8m0fnu` scale, 1x32 blocks after unpacking). Neither prime-rl's model code nor its
DCP loading path can consume either format directly, so this module turns both back into
plain `bfloat16` tensors before the checkpoint's state dict reaches the model.
This is intentionally a one-way, plain preprocessing pass, not a `ConvOp`
(`prime_rl.trainer.models.conversion_ops`): that framework is for two-way *structural*
conversions between per-key HF and PrimeRL names, whereas dequantization merges two source
keys (`*.weight`, `*.scale`) into one output key and is never reversed.
"""
from __future__ import annotations
import torch
from torch import Tensor
from prime_rl.trainer.models.conversion_ops import StateDict
_FP4_E2M1_LUT = torch.tensor(
[0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0],
dtype=torch.float32,
)
def _unpack_mxfp4(packed: Tensor) -> Tensor:
"""Two packed e2m1 nibbles per `int8` byte -> `float32`, doubling the last dim."""
lut = _FP4_E2M1_LUT.to(packed.device)
u8 = packed.contiguous().view(torch.uint8)
low_nibble = (u8 & 0xF).long()
high_nibble = ((u8 >> 4) & 0xF).long()
unpacked = torch.stack([lut[low_nibble], lut[high_nibble]], dim=-1)
return unpacked.reshape(*packed.shape[:-1], 2 * packed.shape[-1])
def dequantize_weight(weight: Tensor, scale: Tensor) -> Tensor:
"""Dequantize one on-disk `(weight, scale)` pair to `bfloat16`.
Dispatches on `weight.dtype`: `torch.int8` is a packed MXFP4 MoE expert weight
(unpacked before scaling); `torch.float8_e4m3fn` is a dense fp8 weight. Both apply the
same per-block scale multiply, with block size derived from the ratio between the
(unpacked) weight's shape and the scale's shape, since dense layers use 128x128 blocks
and MoE experts use 1x32 blocks. `scale` is `float8_e8m0fnu`, which decodes correctly via
a plain `.float()` cast.
"""
if weight.dtype == torch.int8:
values = _unpack_mxfp4(weight)
elif weight.dtype == torch.float8_e4m3fn:
values = weight.float()
else:
raise ValueError(f"Unsupported quantized weight dtype: {weight.dtype}")
rows, cols = values.shape[-2:]
scale_rows, scale_cols = scale.shape[-2:]
if rows % scale_rows or cols % scale_cols:
raise ValueError(
f"Weight shape {tuple(values.shape[-2:])} not divisible by scale grid {tuple(scale.shape[-2:])}"
)
block_rows, block_cols = rows // scale_rows, cols // scale_cols
scale_expanded = scale.float().repeat_interleave(block_rows, dim=-2).repeat_interleave(block_cols, dim=-1)
return (values * scale_expanded).bfloat16()
def dequantize_state_dict_(state_dict: StateDict) -> None:
"""Dequantize every on-disk `*.weight` / `*.scale` pair in place, dropping the scale.
Must run on raw on-disk key names (e.g. `layers.0.attn.wq_a.weight`,
`layers.0.ffn.experts.0.w1.weight`), before any renaming. Keys with no `.scale` sibling
(plain `bfloat16`/`float32` params, the `int64` `tid2eid` routing table) have no sibling
to pop and are left untouched.
"""
for key in [k for k in state_dict if k.endswith(".weight")]:
scale_key = key.removesuffix(".weight") + ".scale"
scale = state_dict.pop(scale_key, None)
if scale is None:
continue
state_dict[key] = dequantize_weight(state_dict[key], scale)
@@ -0,0 +1,102 @@
import torch
import torch.nn.functional as F
from torch import nn
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
class DeepseekV4UnweightedRMSNorm(nn.Module):
"""RMS normalization without a learnable gain, computed in fp32."""
def __init__(self, eps: float = 1e-6):
super().__init__()
self.eps = eps
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x * torch.rsqrt(x.float().square().mean(-1, keepdim=True) + self.eps).to(x.dtype)
class DeepseekV4HyperConnection(nn.Module):
"""Manifold-constrained hyper-connection (mHC) around one sublayer.
The residual is `hc_mult` parallel streams shaped `(B, S, hc_mult, hidden_size)`.
A single projection of the normalized, flattened streams produces three gates:
- `pre`: weights that collapse the streams into the single sequence fed to the
sublayer. Returned already applied, as `collapsed`.
- `post`: weights in `[0, 2]` that broadcast the sublayer output back over the
streams. Returned for the caller to apply.
- `comb`: an `hc_mult x hc_mult` matrix that remixes the streams. It is projected
onto the doubly-stochastic manifold by Sinkhorn-Knopp (alternating row and column
normalization), which is what makes signal propagation non-expansive across depth.
The projection and the Sinkhorn iterations run in fp32; only `collapsed` is cast
back to the input dtype.
"""
def __init__(self, config: DeepseekV4Config):
super().__init__()
self.hc_mult = config.hc_mult
self.hc_sinkhorn_iters = config.hc_sinkhorn_iters
self.hc_eps = config.hc_eps
self.input_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps)
mix = (2 + self.hc_mult) * self.hc_mult
self.fn = nn.Parameter(torch.empty(mix, self.hc_mult * config.hidden_size))
self.base = nn.Parameter(torch.empty(mix))
# One scale per gate: `pre`, `post`, `comb`.
self.scale = nn.Parameter(torch.empty(3))
def forward(self, hidden_streams: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
hc = self.hc_mult
flat = self.input_norm(hidden_streams.flatten(start_dim=2).float())
pre_w, post_w, comb_w = F.linear(flat, self.fn.float()).split([hc, hc, hc * hc], dim=-1)
pre_b, post_b, comb_b = self.base.split([hc, hc, hc * hc])
pre_scale, post_scale, comb_scale = self.scale.unbind(0)
pre = torch.sigmoid(pre_w * pre_scale + pre_b) + self.hc_eps
post = 2 * torch.sigmoid(post_w * post_scale + post_b)
comb_logits = comb_w.view(*comb_w.shape[:-1], hc, hc) * comb_scale + comb_b.view(hc, hc)
comb = torch.softmax(comb_logits, dim=-1) + self.hc_eps
comb = comb / (comb.sum(dim=-2, keepdim=True) + self.hc_eps)
for _ in range(self.hc_sinkhorn_iters - 1):
comb = comb / (comb.sum(dim=-1, keepdim=True) + self.hc_eps)
comb = comb / (comb.sum(dim=-2, keepdim=True) + self.hc_eps)
collapsed = (pre.unsqueeze(-1) * hidden_streams).sum(dim=2).to(hidden_streams.dtype)
return post, comb, collapsed
def init_weights(self, init_std: float) -> None:
nn.init.normal_(self.fn, mean=0.0, std=init_std)
nn.init.zeros_(self.base)
nn.init.ones_(self.scale)
class DeepseekV4HyperHead(nn.Module):
"""Final collapse of the `hc_mult` residual streams, before the model's last norm."""
def __init__(self, config: DeepseekV4Config):
super().__init__()
self.hc_mult = config.hc_mult
self.input_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps)
self.eps = config.hc_eps
self.hc_fn = nn.Parameter(torch.empty(self.hc_mult, self.hc_mult * config.hidden_size))
self.hc_base = nn.Parameter(torch.empty(self.hc_mult))
self.hc_scale = nn.Parameter(torch.empty(1))
def forward(self, x: torch.Tensor) -> torch.Tensor:
flat = self.input_norm(x.flatten(2).float())
mixes = F.linear(flat, self.hc_fn.float())
pre = torch.sigmoid(mixes * self.hc_scale.float() + self.hc_base.float()) + self.eps
return (pre.unsqueeze(-1) * x).sum(dim=2).to(x.dtype)
def init_weights(self, init_std: float) -> None:
nn.init.normal_(self.hc_fn, mean=0.0, std=init_std)
nn.init.zeros_(self.hc_base)
nn.init.ones_(self.hc_scale)
__all__ = [
"DeepseekV4HyperConnection",
"DeepseekV4HyperHead",
"DeepseekV4UnweightedRMSNorm",
]
@@ -0,0 +1,343 @@
"""DeepSeek V4 decoder stack, model and causal-LM head.
This is where the pieces built in `attention.py`, `moe.py`, `hyperconnections.py` and
`rotary.py` come together. The one structural surprise is the residual: it is not a single
stream but `hc_mult` parallel ones, carried as `(batch, seq, hc_mult, hidden)` from the
embedding all the way to `hc_head`, which collapses them back before the final norm.
"""
from __future__ import annotations
import torch
from torch import Tensor, nn
from transformers.generation import GenerationMixin
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import MoeModelOutputWithPast
from prime_rl.trainer.models.base import CPSupport, PreTrainedModelPrimeRL
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
from prime_rl.trainer.models.deepseek_v4.converting_deepseek_v4 import conversion_chain
from prime_rl.trainer.models.deepseek_v4.dequantize import dequantize_state_dict_
from prime_rl.trainer.models.deepseek_v4.hyperconnections import DeepseekV4HyperConnection, DeepseekV4HyperHead
from prime_rl.trainer.models.deepseek_v4.moe import DeepseekV4MoE
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.moe import MoE
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
class DeepseekV4DecoderLayer(GradientCheckpointingLayer):
"""One hyper-connected block: mHC, attention, mHC, MoE.
Both sublayers read the single sequence their `DeepseekV4HyperConnection` collapsed the
streams into, and write back through two gates. `post` broadcasts the sublayer output
over the streams; `comb` remixes the streams among themselves and is consumed
transposed, i.e. summing over the *source* stream axis. Sinkhorn leaves `comb` doubly
stochastic but not symmetric, so that direction is not a free choice.
Both gates come out of the hyper-connection in fp32 and are cast back to the residual's
dtype before mixing, so the residual keeps the dtype it entered with.
"""
def __init__(self, config: DeepseekV4Config, layer_idx: int):
super().__init__()
self.layer_idx = layer_idx
self.self_attn = DeepseekV4Attention(config, layer_idx)
self.mlp = DeepseekV4MoE(config, layer_idx)
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.attn_hc = DeepseekV4HyperConnection(config)
self.ffn_hc = DeepseekV4HyperConnection(config)
def forward(
self,
hidden_states: torch.Tensor,
input_ids: torch.Tensor | None = None,
routed_experts: torch.Tensor | None = None,
*,
packed: PackedContext,
) -> torch.Tensor:
dtype = hidden_states.dtype
post, comb, collapsed = self.attn_hc(hidden_states)
attn_output, _ = self.self_attn(self.input_layernorm(collapsed), packed=packed)
hidden_states = post.to(dtype).unsqueeze(-1) * attn_output.unsqueeze(-2) + torch.matmul(
comb.to(dtype).transpose(-1, -2), hidden_states
)
post, comb, collapsed = self.ffn_hc(hidden_states)
mlp_output = self.mlp(
self.post_attention_layernorm(collapsed), input_ids=input_ids, routed_experts=routed_experts
)
return post.to(dtype).unsqueeze(-1) * mlp_output.unsqueeze(-2) + torch.matmul(
comb.to(dtype).transpose(-1, -2), hidden_states
)
# Mirrors HF's `_keep_in_fp32_modules_strict`, with `e_score_correction_bias` renamed to
# the `selection_bias` prime-rl's router keeps it under. The bare `norm` entry subsumes the
# named norms; both are kept so the list stays a one-to-one image of HF's.
_KEEP_IN_FP32_MODULES = (
"attn_hc",
"ffn_hc",
"hc_head",
"sinks",
"position_bias",
"selection_bias",
"q_a_norm",
"kv_norm",
"input_layernorm",
"post_attention_layernorm",
"norm",
)
class DeepseekV4PreTrainedModel(PreTrainedModelPrimeRL):
config: DeepseekV4Config
config_class = DeepseekV4Config
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["DeepseekV4DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
# V4 attention is eager-only, as in HF: FlashAttention caps the head dim at 256 while
# V4 uses 512, SDPA carries no per-head sink logit, and FlexAttention's BlockMask
# cannot grow to cover the compressed entries the block concatenates onto the KV axis.
# `DeepseekV4Attention` reads no dispatch table, so `config._attn_implementation` is
# inert here; these flags only keep transformers from advertising a backend we lack.
_supports_flash_attn = False
_supports_sdpa = False
_supports_flex_attn = False
_can_compile_fullgraph = False
_supports_attention_backend = True
_can_record_outputs = {"hidden_states": DeepseekV4DecoderLayer}
_keys_to_ignore_on_load_unexpected = [r"(^|\.)mtp\..*"]
@classmethod
def cp_support(cls, config) -> CPSupport:
return CPSupport(
frozenset(),
"its sliding window is a dense local mask built from post-shard document boundaries, "
"which CP's global (pre-shard) boundaries cannot address",
)
def _init_weights(self, module: nn.Module) -> None:
super()._init_weights(module)
init_std = self.config.initializer_range
if isinstance(module, (DeepseekV4Attention, DeepseekV4HyperConnection, DeepseekV4HyperHead)):
module.init_weights(init_std)
elif isinstance(module, DeepseekV4MoE):
module.init_weights(init_std, module.tokens_per_expert.device)
elif isinstance(module, DeepseekV4RotaryEmbedding):
module.init_buffers_post_meta()
@classmethod
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
return any(module_name in name for module_name in _KEEP_IN_FP32_MODULES)
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
# The published checkpoint's `ffn.*` naming, the only unconverted naming that exists --
# see `converting_deepseek_v4.py`'s module docstring.
return any(name.endswith("ffn.gate.weight") or "ffn.shared_experts." in name for name in state_dict)
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
# The NCCL transport broadcasts one decoder layer at a time, plus everything outside
# `model.layers.` as its own group, and asks this of each group separately. That last group
# (embeddings, final norm, `hc_head`, `lm_head`) holds no MoE key, so `model.hc_head.` is
# what stops it claiming to be unconverted and skipping the chain.
return any(
name.endswith("mlp.router.gate.weight") or "mlp.shared_expert." in name or "model.hc_head." in name
for name in state_dict
)
@classmethod
def conversion_chain(cls, config):
return conversion_chain(config)
def convert_to_prime(self, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
"""Convert a HuggingFace state dict to PrimeRL format in-place.
Dequantizes the real checkpoint's fp8/MXFP4 weights to `bfloat16` first, on the raw
on-disk key names: a no-op for any snapshot that doesn't carry `.scale` siblings
(e.g. the plain-`bfloat16` mini test checkpoint).
"""
dequantize_state_dict_(state_dict)
return super().convert_to_prime(state_dict)
def init_buffers_post_meta(self) -> None:
# `to_empty()` leaves every buffer uninitialized and this runs before `dcp_load`, so a
# buffer is restored either here or by the checkpoint. Rebuilt here are the ones no
# checkpoint carries: the rotary tables (non-persistent, and there is one rotary per
# compressor and per indexer on top of the model-level one, so every instance has to be
# walked) and `tokens_per_expert`. The router's persistent buffers, `selection_bias` and a
# hash layer's `tid2eid`, are in the checkpoint that `dcp_load` applies next, so they are
# left to it.
for module in self.modules():
if isinstance(module, DeepseekV4RotaryEmbedding):
module.init_buffers_post_meta()
elif isinstance(module, MoE) and module.tokens_per_expert.device.type != "meta":
module.tokens_per_expert.zero_()
class DeepseekV4Model(DeepseekV4PreTrainedModel):
def __init__(self, config: DeepseekV4Config):
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(
[DeepseekV4DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.rotary_emb = DeepseekV4RotaryEmbedding(config)
self.hc_head = DeepseekV4HyperHead(config)
self.gradient_checkpointing = False
self.post_init()
def forward(
self,
input_ids: torch.LongTensor | None = None,
position_ids: torch.LongTensor | None = None,
inputs_embeds: torch.FloatTensor | None = None,
routed_experts: torch.LongTensor | None = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
) -> MoeModelOutputWithPast:
"""
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Token ids. Threaded down to every decoder layer, not just the embedding: the
bootstrap layers route on `tid2eid[input_ids]` and cannot run without them.
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Each token's position within its own document. Only checked, never consulted: the
positions every rotation and every causal threshold reads are derived from
`seq_lens`, so the two cannot disagree.
NOTE: omitting it is not the same as having no positions. `inject_prime_lm_head`
rebinds this model's forward and substitutes a 1-based `arange(1, N + 1)`, which is
wrong for V4 twice over, since entries are numbered and rotated from 0: it shifts
every query-entry RoPE distance by one and admits an entry whose last source token
is one past the query. `check_position_ids` rejects it, so a caller that passes
nothing gets a `ValueError` rather than a working default.
TODO: make that substitution 0-based, matching HF's convention and every other
model's own fallback, after which an omitted `position_ids` would just be accepted.
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
Routed experts for each token in the sequence. Only used for router replay.
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
Per-document lengths of the packed row (PrimeRL packed-batch contract). Clips the
sliding window at document boundaries and lays out the compressors' entries per
document, so a packed row gives every document what running it alone would.
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
Whether `seq_lens` holds pre-CP-shard (global) document boundaries. Rejected: the
window mask is dense and local, so global boundaries cannot address it.
"""
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if seq_lens_are_pre_shard:
raise NotImplementedError(
"DeepSeek V4 does not support context parallelism: pre-shard document boundaries "
"do not address the local sliding-window mask."
)
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
# Every layer type attends over the same local window; the compressed variants add their
# own out-of-window entries and the per-query bias that gates them. One layout per distinct
# compress rate, shared by every layer that pools at that rate; sliding layers own no
# compressor and contribute no rate.
packed = PackedContext.build(
rotary_emb=self.rotary_emb,
seq_lens=seq_lens,
dtype=inputs_embeds.dtype,
device=inputs_embeds.device,
)
if position_ids is not None:
packed.check_position_ids(position_ids)
hidden_states = inputs_embeds.unsqueeze(2).expand(-1, -1, self.config.hc_mult, -1).contiguous()
for layer_idx, decoder_layer in enumerate(self.layers):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
hidden_states = decoder_layer(
hidden_states,
input_ids=input_ids,
routed_experts=routed_experts_layer,
packed=packed,
)
hidden_states = self.norm(self.hc_head(hidden_states))
return MoeModelOutputWithPast(last_hidden_state=hidden_states)
class DeepseekV4ForCausalLM(DeepseekV4PreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_gather_output"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config: DeepseekV4Config):
super().__init__(config)
self.model = DeepseekV4Model(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.post_init()
def get_decoder(self):
return self.model
def set_decoder(self, decoder):
self.model = decoder
def forward(
self,
input_ids: torch.LongTensor | None = None,
position_ids: torch.LongTensor | None = None,
inputs_embeds: torch.FloatTensor | None = None,
labels: torch.LongTensor | None = None,
logits_to_keep: int | torch.Tensor = 0,
temperature: torch.Tensor | None = None,
routed_experts: torch.LongTensor | None = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
**kwargs,
) -> PrimeLmOutput:
"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels used by PrimeRL's wrapped LM head to optionally compute per-token
logprobs/entropy.
temperature (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Per-token temperatures for logprobs/entropy computation when `labels` are given.
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
Per-document lengths of the packed row. Required rather than defaulting to one
document, so a caller that forgets it fails instead of silently getting a window
that spans neighbouring rollouts.
"""
outputs = self.model(
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
routed_experts=routed_experts,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
hidden_states = outputs.last_hidden_state
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
return self.lm_head(
hidden_states[:, slice_indices, :],
labels[:, slice_indices] if labels is not None else None,
temperature=temperature,
)
__all__ = [
"DeepseekV4DecoderLayer",
"DeepseekV4ForCausalLM",
"DeepseekV4Model",
"DeepseekV4PreTrainedModel",
]
@@ -0,0 +1,259 @@
"""DeepSeek V4 mixture of experts: router, routed experts and shared expert.
Both MLP layer types live here. `num_hash_layers` picks between standard token-choice
routing and the hash routing of the bootstrap layers, which replaces the learned
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.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):
"""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
and zeros until one fills it. A frozen selection cannot be steered, so a hash layer has no use
for the aux-loss-free load-balancing bias, and HF's `DeepseekV4HashRouter` carries no
`e_score_correction_bias` to load into it either; `selection_bias=False` leaves that buffer
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)
class DeepseekV4MoE(MoE):
"""A V4 MoE layer, hash-routed or standard according to `config.num_hash_layers`.
Subclasses the shared `MoE` so `configure_moe_runtime` / `setup_fsdp` keep recognizing
it, then hands the three V4-specific pieces to the base constructor. `MoE.forward`'s
orchestration is unchanged.
A hash layer routes each token to `tid2eid[token_id]`, the frozen table its
`DeepseekV4HashRouter` carries, instead of to the top-k of the router's scores. That is
precisely what the shared router's `routed_experts` bypass does, so only the `forward` below
differs between the two layer types: it reads the indices out of the table and lets the base
class weight them with the learned scores as usual.
"""
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"
)
if config.scoring_func != "sqrtsoftplus":
raise ValueError(
f"the router hardcodes sqrt(softplus(.)); scoring_func={config.scoring_func!r} is not supported"
)
is_hash = layer_idx < config.num_hash_layers
router_kwargs = dict(
dim=config.hidden_size,
num_experts=config.n_routed_experts,
top_k=config.num_experts_per_tok,
score_func=config.scoring_func,
# HF normalizes the top-k scores unconditionally and never reads
# `config.norm_topk_prob`, so neither do we.
route_norm=True,
route_scale=config.routed_scaling_factor,
)
router = (
DeepseekV4HashRouter(**router_kwargs, vocab_size=config.vocab_size)
if is_hash
else DeepseekV4Router(**router_kwargs, selection_bias=True)
)
experts = DeepseekV4Experts(
dim=config.hidden_size,
hidden_dim=config.moe_intermediate_size,
num_experts=config.n_routed_experts,
swiglu_limit=config.swiglu_limit,
)
# 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
super().__init__(
router=router,
experts=experts,
shared_expert=shared_expert,
# HF scales each expert's output by its routing weight after `down_proj`.
score_before_experts=False,
load_balance_coeff=None if is_hash else 1e-3,
)
self.layer_idx = layer_idx
self.is_hash = is_hash
def forward(
self,
x: torch.Tensor,
input_ids: torch.Tensor | None = None,
routed_experts: torch.Tensor | None = None,
) -> torch.Tensor:
"""
Args:
x (torch.Tensor): Input tensor with shape ``(bs, slen, dim)``.
input_ids (torch.Tensor | None, optional): Token ids with shape ``(bs, slen)``.
Required by a hash layer, ignored by a standard one.
routed_experts (torch.Tensor | None, optional): Optional tensor with shape
``(bs, slen, top_k)``. Replayed expert indices take precedence over the table.
Returns:
out (torch.Tensor): Output tensor with shape ``(bs, slen, dim)``.
"""
if self.is_hash and routed_experts is None:
assert input_ids is not None, f"layer {self.layer_idx} is hash-routed and needs input_ids"
# `(vocab_size, top_k)` indexed by `(bs, slen)` token ids gives `(bs, slen, top_k)`.
routed_experts = self.router.tid2eid[input_ids]
return super().forward(x, routed_experts=routed_experts)
@@ -0,0 +1,155 @@
from collections.abc import Callable
import torch
from torch import nn
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
# The rope types whose inverse frequencies are fixed once computed. The two left out,
# `dynamic` and `longrope`, rescale theirs per forward against the running sequence length,
# which the buffers below, written once in `__init__`, never do.
_SUPPORTED_ROPE_TYPES = frozenset({"default", "linear", "llama3", "proportional", "yarn"})
def rotate_half_interleaved(x: torch.Tensor) -> torch.Tensor:
"""Rotate consecutive channel pairs: `(x0, x1, x2, x3, ...) -> (-x1, x0, -x3, x2, ...)`.
Not the same as `prime_rl.trainer.models.layers.rotary_emb.rotate_half`, which pairs
channel `i` with channel `i + dim / 2` (the GPT-NeoX layout). DeepSeek-V4 stores each
rotary pair adjacently, so the two are not interchangeable.
"""
x1 = x[..., 0::2]
x2 = x[..., 1::2]
return torch.stack((-x2, x1), dim=-1).flatten(-2)
def apply_rotary_pos_emb_interleaved(
x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, unsqueeze_dim: int = 1
) -> torch.Tensor:
"""Apply interleaved RoPE to the trailing rotary slice of `x`.
`cos` and `sin` arrive at half width (one entry per interleaved pair) and are widened
with `repeat_interleave`. Each head is laid out as `[nope | rope]`, so only the last
`2 * cos.shape[-1]` channels rotate and the leading ones pass through untouched.
The rotation itself runs in fp32 and is cast back to `x`'s dtype.
Args:
x: Tensor whose last dimension is the head dimension.
cos: Half-width cosines, shape `(batch, seq, rope_dim / 2)`.
sin: Half-width sines, same shape as `cos`.
unsqueeze_dim: Axis of `x` that `cos` / `sin` must broadcast over. Use `1` for a
`(batch, heads, seq, head_dim)` layout and `2` for `(batch, seq, heads, head_dim)`.
"""
cos = cos.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim)
sin = sin.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim)
rope_dim = cos.shape[-1]
nope, rope = x[..., :-rope_dim], x[..., -rope_dim:]
rotated = ((rope.float() * cos) + (rotate_half_interleaved(rope).float() * sin)).to(x.dtype)
return torch.cat([nope, rotated], dim=-1)
class DeepseekV4RotaryEmbedding(nn.Module):
"""Rotary embedding carrying one inverse-frequency table per RoPE type.
DeepSeek-V4 keys its RoPE parameters by rope type (`main` / `compress`), which is
independent of `config.layer_types`: sliding-window layers read `main`, the two
compressed attention variants share `compress` with their compressor. Each type gets
its own `<type>_inv_freq` / `<type>_original_inv_freq` buffers and
`<type>_attention_scaling` scalar.
Because the rotation is interleaved, `forward` returns `cos` / `sin` at half the
rotary width (one entry per pair). `apply_rotary_pos_emb_interleaved` widens them.
`rope_type` is checkpoint data rather than architecture: V4 ships `default` on `main` and
`default` or `yarn` on `compress`, but the config reads whatever the file says. Anything
outside `_SUPPORTED_ROPE_TYPES` is refused at construction, rather than rotating at
frequencies that were meant to be rescaled and never were.
"""
def __init__(self, config: DeepseekV4Config, device: torch.device | None = None):
super().__init__()
self.config = config
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
# Only the nested per-rope-type sub-dicts are real rope types; a flat leftover
# `rope_type` key at the top level is not one.
self.layer_types = [name for name, params in config.rope_parameters.items() if isinstance(params, dict)]
self.rope_type: dict[str, str] = {}
for layer_type in self.layer_types:
self.rope_type[layer_type] = config.rope_parameters[layer_type]["rope_type"]
if self.rope_type[layer_type] not in _SUPPORTED_ROPE_TYPES:
raise ValueError(
f"rope type {self.rope_type[layer_type]!r} on {layer_type!r} is not supported; "
f"the supported types are {sorted(_SUPPORTED_ROPE_TYPES)}, whose inverse "
"frequencies are computed once here and never rescaled per forward"
)
inv_freq, attention_scaling = self._rope_init_fn(layer_type)(config, device, layer_type=layer_type)
self.register_buffer(f"{layer_type}_inv_freq", inv_freq, persistent=False)
self.register_buffer(f"{layer_type}_original_inv_freq", inv_freq.clone(), persistent=False)
setattr(self, f"{layer_type}_attention_scaling", attention_scaling)
def _rope_init_fn(self, layer_type: str) -> Callable[..., tuple[torch.Tensor, float]]:
rope_type = self.rope_type[layer_type]
if rope_type == "default":
return self.compute_default_rope_parameters
return ROPE_INIT_FUNCTIONS[rope_type]
def init_buffers_post_meta(self) -> None:
"""Re-derive the per-rope-type inverse frequencies in place.
The tables are computed eagerly in `__init__` and registered non-persistently, so they
survive neither meta-device construction nor a `load_state_dict`. Re-deriving them is
cheap and idempotent.
"""
for layer_type in self.layer_types:
inv_freq_buffer = getattr(self, f"{layer_type}_inv_freq")
inv_freq, attention_scaling = self._rope_init_fn(layer_type)(
self.config, inv_freq_buffer.device, layer_type=layer_type
)
inv_freq_buffer.copy_(inv_freq)
getattr(self, f"{layer_type}_original_inv_freq").copy_(inv_freq)
setattr(self, f"{layer_type}_attention_scaling", attention_scaling)
@staticmethod
def compute_default_rope_parameters(
config: DeepseekV4Config,
device: torch.device | None = None,
seq_len: int | None = None,
layer_type: str | None = None,
) -> tuple[torch.Tensor, float]:
"""Unscaled inverse frequencies for one rope type's partial rotary slice."""
rope_parameters = config.rope_parameters[layer_type]
base = rope_parameters["rope_theta"]
partial_rotary_factor = rope_parameters.get("partial_rotary_factor", 1.0)
head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
dim = int(head_dim * partial_rotary_factor)
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float, device=device) / dim))
return inv_freq, 1.0
@torch.no_grad()
def forward(
self, position_ids: torch.Tensor, layer_type: str, *, dtype: torch.dtype
) -> tuple[torch.Tensor, torch.Tensor]:
device = position_ids.device
inv_freq = getattr(self, f"{layer_type}_inv_freq")
attention_scaling = getattr(self, f"{layer_type}_attention_scaling")
inv_freq_expanded = inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(device)
position_ids_expanded = position_ids[:, None, :].float()
device_type = device.type if isinstance(device.type, str) and device.type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False): # Force float32
# No `cat([freqs, freqs])`: interleaved RoPE needs one theta per pair, and
# `apply_rotary_pos_emb_interleaved` widens cos/sin next to the rotation.
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
cos = freqs.cos() * attention_scaling
sin = freqs.sin() * attention_scaling
return cos.to(dtype=dtype), sin.to(dtype=dtype)
__all__ = [
"DeepseekV4RotaryEmbedding",
"apply_rotary_pos_emb_interleaved",
"rotate_half_interleaved",
]
@@ -10,11 +10,9 @@ from prime_rl.trainer.models.layers.rotary_emb import rotate_half
from prime_rl.utils.cp import gather_for_cp
try:
from prime_rl.trainer.models.kernels.sparse_mla_bwd import sparse_mla_bwd
from prime_rl.trainer.models.kernels.sparse_mla_fwd import sparse_mla_fwd_interface
from prime_rl.trainer.models.kernels.sparse_mla_fwd import sparse_mla
except ImportError:
sparse_mla_fwd_interface = None # type: ignore
sparse_mla_bwd = None # type: ignore
sparse_mla = None # type: ignore
@dataclass(frozen=True)
@@ -36,23 +34,6 @@ class SparseMlaAttentionArgs:
skip_topk: bool = False
class _SparseMLA(torch.autograd.Function):
"""Autograd wrapper for tilelang sparse MLA forward/backward kernels."""
@staticmethod
def forward(ctx, q, kv, indices, sm_scale):
out, lse = sparse_mla_fwd_interface(q, kv, indices, sm_scale=sm_scale)
ctx.save_for_backward(q, kv, out, indices, lse)
ctx.sm_scale = sm_scale
return out
@staticmethod
def backward(ctx, do):
q, kv, out, indices, lse = ctx.saved_tensors
dq, dkv = sparse_mla_bwd(q, kv, out, do.contiguous(), indices, lse, sm_scale=ctx.sm_scale)
return dq, dkv, None, None
def apply_rope_interleave_single(
t: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, unsqueeze_dim: int = 1
) -> torch.Tensor:
@@ -177,7 +158,7 @@ class GlmMoeDsaAttention(nn.Module):
def cp_enabled(self) -> bool:
return self._cp_world_size > 1
def attn_projections(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
def mla_latents(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
q_latent = self.q_a_layernorm(self.q_a_proj(hidden_states))
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
k_compressed, k_rope = compressed_kv.split([self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
@@ -224,15 +205,6 @@ class GlmMoeDsaAttention(nn.Module):
assert sparse_kv.shape[1] == s_full + 1
return sparse_q, sparse_kv, w_v
def _mla_unabsorb(self, out: torch.Tensor, w_v: torch.Tensor) -> torch.Tensor:
return torch.einsum("bshk,hdk->bshd", out, w_v)
def output_proj(self, attn_output: torch.Tensor, w_v: torch.Tensor) -> torch.Tensor:
attn_output = self._mla_unabsorb(attn_output, w_v)
batch_size, total_tokens = attn_output.shape[:2]
attn_output = attn_output.reshape(batch_size, total_tokens, -1)
return self.o_proj(attn_output)
def forward(
self,
hidden_states: torch.Tensor,
@@ -241,7 +213,7 @@ class GlmMoeDsaAttention(nn.Module):
ke: torch.Tensor | None = None,
cached_indices: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
q_latent, k_compressed_normed, k_rope = self.attn_projections(hidden_states)
q_latent, k_compressed_normed, k_rope = self.mla_latents(hidden_states)
if self.cp_enabled:
k_compressed_normed = gather_for_cp(k_compressed_normed, self._cp_group)
@@ -268,6 +240,9 @@ class GlmMoeDsaAttention(nn.Module):
position_embeddings_full=position_embeddings,
)
out = _SparseMLA.apply(sparse_q, sparse_kv, indices, self.scaling)
out, _ = sparse_mla(sparse_q, sparse_kv, indices, self.scaling)
out = torch.einsum("bshk,hdk->bshd", out, w_v)
batch_size, total_tokens = out.shape[:2]
out = out.reshape(batch_size, total_tokens, -1)
cached_indices = indices if self.use_index_cache else None
return self.output_proj(out, w_v), cached_indices
return self.o_proj(out), cached_indices
@@ -18,7 +18,7 @@ from transformers.models.gpt_oss.modeling_gpt_oss import (
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.base import CPSupport, PreTrainedModelPrimeRL
from prime_rl.trainer.models.gpt_oss.configuration_gpt_oss import GptOssConfig
from prime_rl.trainer.models.gpt_oss.converting_gpt_oss import (
conversion_chain,
@@ -111,6 +111,15 @@ class GptOssPreTrainedModel(PreTrainedModelPrimeRL):
_compatible_flash_implementations = ["kernels-community/vllm-flash-attn3", "flash_attention_4"]
_can_record_outputs = {"hidden_states": GptOssDecoderLayer}
@classmethod
def cp_support(cls, config) -> CPSupport:
return CPSupport(
frozenset(),
"its attention is HuggingFace's GptOssAttention, which passes per-head sink logits as "
"`s_aux`; neither the ring nor the ulysses path forwards them, so CP would silently drop "
"the sinks",
)
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return is_hf_state_dict(state_dict)
@@ -276,11 +276,21 @@ def bwd(
return sparse_mla_bwd_kernel
def sparse_mla_bwd(q, kv, o, do, indices, lse, sm_scale=None):
@torch.library.custom_op("prime_rl::sparse_mla_backward", mutates_args=())
def sparse_mla_backward(
q: torch.Tensor,
kv: torch.Tensor,
out: torch.Tensor,
grad_out: torch.Tensor,
indices: torch.Tensor,
lse: torch.Tensor,
sm_scale: float | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
assert q.is_contiguous()
assert kv.is_contiguous()
assert indices.is_contiguous()
assert lse.is_contiguous()
grad_out = grad_out.contiguous()
B, S, H, dim_plus_tail_dim = q.shape
_, S_kv, kv_group, _ = kv.shape
assert kv.shape[-1] == dim_plus_tail_dim
@@ -295,9 +305,22 @@ def sparse_mla_bwd(q, kv, o, do, indices, lse, sm_scale=None):
bwd_kernel = bwd(H, D, D_tail, topk, kv_group, sm_scale, True)
postprocess_kernel = postprocess(D, D_tail, kv_group)
delta = preprocess_kernel(o, do)
delta = preprocess_kernel(out, grad_out)
dkv = torch.zeros_like(kv, dtype=torch.float32)
dq = bwd_kernel(q, kv, do, indices, lse, delta, dkv)
dq = bwd_kernel(q, kv, grad_out, indices, lse, delta, dkv)
dkv = postprocess_kernel(dkv)
return dq, dkv
@sparse_mla_backward.register_fake
def _sparse_mla_backward_fake(
q: torch.Tensor,
kv: torch.Tensor,
out: torch.Tensor,
grad_out: torch.Tensor,
indices: torch.Tensor,
lse: torch.Tensor,
sm_scale: float | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
return torch.empty_like(q), torch.empty_like(kv)
@@ -14,8 +14,11 @@ except Exception:
pass
import tilelang
import torch
from tilelang import language as T
from prime_rl.trainer.models.kernels.sparse_mla_bwd import sparse_mla_backward
@tilelang.jit(
out_idx=[-2, -1],
@@ -183,7 +186,17 @@ def sparse_mla_fwd(
return main
def sparse_mla_fwd_interface(q, kv, indices, sm_scale=None, d_v=512, block_I=64, num_stages=2, threads=256):
@torch.library.custom_op("prime_rl::sparse_mla", mutates_args=())
def sparse_mla(
q: torch.Tensor,
kv: torch.Tensor,
indices: torch.Tensor,
sm_scale: float | None = None,
d_v: int = 512,
block_I: int = 64,
num_stages: int = 2,
threads: int = 256,
) -> tuple[torch.Tensor, torch.Tensor]:
assert q.is_contiguous() and kv.is_contiguous() and indices.is_contiguous()
batch, seq_len, heads, dim_plus_tail_dim = q.shape
_, seq_len_kv, kv_group, _ = kv.shape
@@ -210,3 +223,42 @@ def sparse_mla_fwd_interface(q, kv, indices, sm_scale=None, d_v=512, block_I=64,
)
out, lse = kernel(q, kv, indices)
return out, lse
@sparse_mla.register_fake
def _sparse_mla_fake(
q: torch.Tensor,
kv: torch.Tensor,
indices: torch.Tensor,
sm_scale: float | None = None,
d_v: int = 512,
block_I: int = 64,
num_stages: int = 2,
threads: int = 256,
) -> tuple[torch.Tensor, torch.Tensor]:
return q.new_empty((*q.shape[:-1], d_v)), q.new_empty(q.shape[:-1], dtype=torch.float32)
def _sparse_mla_setup_context(ctx, inputs, output) -> None:
q, kv, indices, sm_scale, _d_v, _block_I, _num_stages, _threads = inputs
out, lse = output
ctx.save_for_backward(q, kv, out, indices, lse)
ctx.sm_scale = sm_scale
ctx.mark_non_differentiable(lse)
def _sparse_mla_autograd_backward(ctx, grad_out: torch.Tensor, _grad_lse: torch.Tensor | None):
q, kv, out, indices, lse = ctx.saved_tensors
dq, dkv = sparse_mla_backward(
q.detach(),
kv.detach(),
out.detach(),
grad_out,
indices,
lse.detach(),
ctx.sm_scale,
)
return dq, dkv, None, None, None, None, None, None
sparse_mla.register_autograd(_sparse_mla_autograd_backward, setup_context=_sparse_mla_setup_context)
@@ -21,6 +21,7 @@ from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import FeedForward
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.rotary_emb import apply_rotary_pos_emb
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
@@ -126,16 +127,39 @@ class LagunaFlashAttention(FlashAttention):
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
query_states, key_states, value_states = self.attn_projections(hidden_states, position_embeddings)
attn_output = self._attention_core(
query_states,
key_states,
value_states,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
input_shape = hidden_states.shape[:-1]
attn_output = attn_output.view(*input_shape, self.num_heads, self.head_dim)
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
if self.use_qk_norm and self.qk_norm_type == "per_layer":
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
query_states = query_states.view(hidden_shape)
key_states = key_states.view(hidden_shape)
value_states = value_states.view(hidden_shape)
if self.use_qk_norm and self.qk_norm_type == "per_head":
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 position_embeddings is not None:
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
value_states = value_states.transpose(1, 2)
attn_output = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
attn_output = attn_output.contiguous().view(*input_shape, self.num_heads, self.head_dim)
if self.gating:
gate = F.softplus(self.g_proj(hidden_states).float()).to(attn_output.dtype)
# per-head gates broadcast across head_dim; per-element gates are already
+10 -48
View File
@@ -109,22 +109,13 @@ class FlashAttention(nn.Module):
out = out[0]
return out
def _attention_core(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> torch.Tensor:
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
return out.contiguous().view(1, out.shape[0], -1)
def attn_projections(
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
@@ -157,28 +148,9 @@ class FlashAttention(nn.Module):
key_states = key_states.transpose(1, 2)
value_states = value_states.transpose(1, 2)
return query_states, key_states, value_states
def output_proj(self, attn_output: torch.Tensor) -> torch.Tensor:
return self.o_proj(attn_output)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
query_states, key_states, value_states = self.attn_projections(hidden_states, position_embeddings)
attn_output = self._attention_core(
query_states,
key_states,
value_states,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
attn_output = self.output_proj(attn_output)
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
attn_output = out.contiguous().view(1, out.shape[0], -1)
attn_output = self.o_proj(attn_output)
return attn_output, None
@@ -195,16 +167,7 @@ def substitute_ring_attn(
attn_impl: str = "flash_attention_2",
) -> None:
"""Patch _compute_attention on FlashAttention variants to use ring attention."""
from ring_flash_attn import llama3_flash_attn_varlen_func
from .ring_attn import ring_fa3_varlen_func, ring_fa4_varlen_func
if attn_impl == "flash_attention_4":
ring_func = ring_fa4_varlen_func
elif attn_impl == "flash_attention_3":
ring_func = ring_fa3_varlen_func
else:
ring_func = llama3_flash_attn_varlen_func
from .ring_attn import ring_varlen_attention
def _ring_compute_attention(self, q, k, v, cu_seqlens, max_seqlen):
from ring_flash_attn.adapters.hf_adapter import DATA_PARAMS
@@ -214,7 +177,7 @@ def substitute_ring_attn(
if sliding_window is not None:
window_size = (sliding_window - 1, 0)
out = ring_func(
out = ring_varlen_attention(
q,
k,
v,
@@ -227,9 +190,8 @@ def substitute_ring_attn(
window_size=window_size,
group=process_group,
heads_k_stride=heads_k_stride,
attention_backend=attn_impl,
)
if isinstance(out, tuple):
out = out[0]
return out
FlashAttention._compute_attention = _ring_compute_attention
@@ -1,141 +0,0 @@
"""Selective activation checkpointing hooks for custom decoder layers.
New model integration contract:
- `norm`: no explicit hook is required. Every child module whose type name
contains `norm` is checkpointed through `forward()`.
- `attn_proj`: expose `layer.self_attn.attn_projections(...)` for
projection-side attention work before the core kernel, plus
`layer.self_attn.output_proj(...)` for the post-attention output projection.
This target is meant for attention-local work outside the main attention
kernel, such as q/k/v projections, attention-local norms, RoPE, gating, and
similar model-specific helpers.
- `mla_up_proj`: expose `layer.self_attn.mla_up_proj(...)` when MLA-style
up-projection work should be checkpointed separately from
`attn_projections(...)`.
- `mlp`: expose a dense `layer.mlp.forward(...)`. A module is treated as dense
when it does not define `tokens_per_expert`.
- `linear_attn`: expose a token-mixer module on `layer.linear_attn` or
`layer.mamba`, or reuse `layer.self_attn` when
`layer.attention_type == "sliding_attention"`.
These hook names are an intentional public interface for custom model support,
so new models should follow them directly rather than adding private aliases.
"""
from collections.abc import Iterable
from functools import wraps
import torch
import torch.nn as nn
from torch.utils.checkpoint import checkpoint
SELECTIVE_AC_TARGETS = frozenset({"norm", "attn_proj", "mlp", "mla_up_proj", "linear_attn"})
_PATCHED_METHODS_ATTR = "_prime_rl_selective_ac_patched_methods"
def _is_norm_module(module: nn.Module) -> bool:
return "norm" in type(module).__name__.lower()
def _should_checkpoint(module: nn.Module) -> bool:
return torch.is_grad_enabled() and module.training
def checkpoint_method(module: nn.Module, method_name: str) -> None:
patched_methods = frozenset(getattr(module, _PATCHED_METHODS_ATTR, ()))
if method_name in patched_methods:
return
original = getattr(module, method_name)
@wraps(original)
def checkpointed(*args, **kwargs):
if not _should_checkpoint(module):
return original(*args, **kwargs)
def fn(*checkpoint_args):
return original(*checkpoint_args, **kwargs)
return checkpoint(fn, *args, use_reentrant=False, preserve_rng_state=False)
setattr(module, method_name, checkpointed)
setattr(module, _PATCHED_METHODS_ATTR, patched_methods.union({method_name}))
def _configure_norm_checkpointing(layer: nn.Module) -> None:
for module in layer.modules():
if module is layer or not _is_norm_module(module):
continue
checkpoint_method(module, "forward")
def _is_dense_mlp(mlp: nn.Module) -> bool:
return not hasattr(mlp, "tokens_per_expert")
def _supports_attn_proj(self_attn: nn.Module | None) -> bool:
return self_attn is not None and hasattr(self_attn, "attn_projections") and hasattr(self_attn, "output_proj")
def _get_linear_attn_module(layer: nn.Module) -> nn.Module | None:
linear_attn = getattr(layer, "linear_attn", None)
if linear_attn is not None:
return linear_attn
mamba = getattr(layer, "mamba", None)
if mamba is not None:
return mamba
if getattr(layer, "attention_type", None) == "sliding_attention":
return getattr(layer, "self_attn", None)
return None
def get_supported_targets(layer: nn.Module) -> frozenset[str]:
"""Infer which selective activation checkpoint targets a decoder layer supports."""
supported_targets = {"norm"}
self_attn = getattr(layer, "self_attn", None)
mlp = getattr(layer, "mlp", None)
linear_attn = _get_linear_attn_module(layer)
if _supports_attn_proj(self_attn):
supported_targets.add("attn_proj")
if self_attn is not None and hasattr(self_attn, "mla_up_proj"):
supported_targets.add("mla_up_proj")
if mlp is not None and _is_dense_mlp(mlp):
supported_targets.add("mlp")
if linear_attn is not None:
supported_targets.add("linear_attn")
return frozenset(supported_targets)
def set_selective_activation_checkpointing(layer: nn.Module, targets: Iterable[str]) -> None:
target_set = frozenset(targets)
invalid_targets = target_set - SELECTIVE_AC_TARGETS
if invalid_targets:
raise ValueError(f"Unsupported selective activation checkpoint targets: {sorted(invalid_targets)}")
enabled_targets = target_set & get_supported_targets(layer)
self_attn = getattr(layer, "self_attn", None)
mlp = getattr(layer, "mlp", None)
linear_attn = _get_linear_attn_module(layer)
attn_proj_is_subsumed = "linear_attn" in enabled_targets and linear_attn is self_attn
if self_attn is not None and "attn_proj" in enabled_targets and not attn_proj_is_subsumed:
checkpoint_method(self_attn, "attn_projections")
checkpoint_method(self_attn, "output_proj")
if self_attn is not None and "mla_up_proj" in enabled_targets:
checkpoint_method(self_attn, "mla_up_proj")
if mlp is not None and "mlp" in enabled_targets:
checkpoint_method(mlp, "forward")
if linear_attn is not None and "linear_attn" in enabled_targets:
checkpoint_method(linear_attn, "forward")
if "norm" in enabled_targets:
_configure_norm_checkpointing(layer)
def supports_selective_activation_checkpointing(layer: nn.Module) -> bool:
return type(layer).__module__.startswith("prime_rl.trainer.models.")
+5 -33
View File
@@ -19,33 +19,7 @@ import torch.distributed as dist
from fla.modules.conv import causal_conv1d as fla_causal_conv1d
from fla.ops.utils import prepare_sequence_ids
class _SeqToHeadParallel(torch.autograd.Function):
"""[B, S/cp, D] -> [B, S, D/cp] via all-to-all."""
@staticmethod
def forward(ctx, x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
ctx.cp_group = cp_group
ctx.cp_size = cp_size
return _all_to_all_seq_to_head(x, cp_group, cp_size)
@staticmethod
def backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None]:
return _all_to_all_head_to_seq(grad_output, ctx.cp_group, ctx.cp_size), None, None
class _HeadToSeqParallel(torch.autograd.Function):
"""[B, S, D/cp] -> [B, S/cp, D] via all-to-all."""
@staticmethod
def forward(ctx, x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
ctx.cp_group = cp_group
ctx.cp_size = cp_size
return _all_to_all_head_to_seq(x, cp_group, cp_size)
@staticmethod
def backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None]:
return _all_to_all_seq_to_head(grad_output, ctx.cp_group, ctx.cp_size), None, None
from prime_rl.trainer.distributed.collectives import all_to_all_single_equal
def _all_to_all_seq_to_head(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
@@ -60,8 +34,7 @@ def _all_to_all_seq_to_head(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_siz
# Split D into cp_size chunks, put cp dim first for all_to_all scatter
# [B, S_local, D] -> [B, S_local, cp, D_local] -> [cp, B, S_local, D_local]
x = x.reshape(B, S_local, cp_size, D_local).permute(2, 0, 1, 3).contiguous()
output = torch.empty_like(x)
dist.all_to_all_single(output, x, group=cp_group)
output = all_to_all_single_equal(x, cp_group)
# output[i] = data from rank i (its S_local tokens, our D_local slice)
# [cp, B, S_local, D_local] -> [B, cp, S_local, D_local] -> [B, cp*S_local, D_local]
return output.permute(1, 0, 2, 3).reshape(B, cp_size * S_local, D_local).contiguous()
@@ -78,8 +51,7 @@ def _all_to_all_head_to_seq(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_siz
# Split S_global into cp_size chunks (one per rank), put cp dim first for scatter
# [B, S_global, D_local] -> [B, cp, S_local, D_local] -> [cp, B, S_local, D_local]
x = x.reshape(B, cp_size, S_local, D_local).permute(1, 0, 2, 3).contiguous()
output = torch.empty_like(x)
dist.all_to_all_single(output, x, group=cp_group)
output = all_to_all_single_equal(x, cp_group)
# Each rank now has cp chunks of [B, S_local, D_local] — one D_local slice from each rank
# [cp, B, S_local, D_local] -> [B, S_local, cp, D_local] -> [B, S_local, D]
return output.permute(1, 2, 0, 3).reshape(B, S_local, cp_size * D_local).contiguous()
@@ -87,12 +59,12 @@ def _all_to_all_head_to_seq(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_siz
def seq_to_head_parallel(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
"""[B, S/cp, D] -> [B, S, D/cp] with correct backward."""
return _SeqToHeadParallel.apply(x, cp_group, cp_size)
return _all_to_all_seq_to_head(x, cp_group, cp_size)
def head_to_seq_parallel(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
"""[B, S, D/cp] -> [B, S/cp, D] with correct backward."""
return _HeadToSeqParallel.apply(x, cp_group, cp_size)
return _all_to_all_head_to_seq(x, cp_group, cp_size)
def mamba_cp_forward(
@@ -90,30 +90,104 @@ def _compute_grad_weight(
return grad_weight.to(torch.bfloat16)
class _GroupedFP8Gemm(torch.autograd.Function):
@staticmethod
def forward(
ctx,
x: torch.Tensor,
weight: torch.Tensor,
offs: torch.Tensor,
) -> torch.Tensor:
import deep_gemm
@torch.library.custom_op("prime_rl::grouped_fp8_gemm", mutates_args=())
def _grouped_fp8_gemm(x: torch.Tensor, weight: torch.Tensor, offs: torch.Tensor) -> torch.Tensor:
import deep_gemm
(
total_m,
(
total_m,
padded_total_m,
grouped_layout,
block_to_group,
_,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
) = build_grouped_layout(offs, total_m=x.size(0))
use_ue8m0 = ue8m0_for_device(x.device)
x_fp8 = grouped_per_token_cast_to_fp8_triton(
x,
padded_total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
use_ue8m0,
GROUP_ALIGNMENT,
)
weight_fp8 = grouped_per_block_cast_to_fp8_triton(
weight.transpose(1, 2),
use_ue8m0,
GROUP_ALIGNMENT,
)
out_padded = torch.empty((padded_total_m, weight.size(2)), device=x.device, dtype=x.dtype)
deep_gemm.m_grouped_fp8_gemm_nt_contiguous(
x_fp8,
weight_fp8,
out_padded,
grouped_layout,
use_psum_layout=False,
)
return unpack_rows_triton(
out_padded,
total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
)
@_grouped_fp8_gemm.register_fake
def _grouped_fp8_gemm_fake(x: torch.Tensor, weight: torch.Tensor, offs: torch.Tensor) -> torch.Tensor:
return x.new_empty((x.shape[0], weight.shape[2]))
@torch.library.custom_op("prime_rl::grouped_fp8_gemm_backward", mutates_args=())
def _grouped_fp8_gemm_backward(
grad_output: torch.Tensor,
x: torch.Tensor,
weight: torch.Tensor,
offs: torch.Tensor,
needs_grad_x: bool,
needs_grad_weight: bool,
) -> tuple[torch.Tensor, torch.Tensor]:
(
_,
padded_total_m,
grouped_layout,
block_to_group,
ks_tensor,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
) = build_grouped_layout(offs, total_m=x.size(0))
grad_output = grad_output.contiguous()
grad_x = torch.empty_like(x)
grad_weight = torch.empty_like(weight)
if needs_grad_weight:
grad_weight = _compute_grad_weight(
x,
grad_output,
weight.shape,
padded_total_m,
grouped_layout,
block_to_group,
ks_tensor,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
) = build_grouped_layout(offs, total_m=x.size(0))
ks_tensor.tolist(),
)
use_ue8m0 = ue8m0_for_device(x.device)
x_fp8 = grouped_per_token_cast_to_fp8_triton(
x,
if needs_grad_x:
import deep_gemm
use_ue8m0 = ue8m0_for_device(grad_output.device)
dy_fp8 = grouped_per_token_cast_to_fp8_triton(
grad_output,
padded_total_m,
block_to_group,
starts_tensor,
@@ -122,120 +196,66 @@ class _GroupedFP8Gemm(torch.autograd.Function):
use_ue8m0,
GROUP_ALIGNMENT,
)
weight_fp8 = grouped_per_block_cast_to_fp8_triton(
weight.transpose(1, 2),
use_ue8m0,
GROUP_ALIGNMENT,
)
out_padded = torch.empty(
(padded_total_m, weight.size(2)),
device=x.device,
dtype=x.dtype,
weight_dx_fp8 = grouped_per_block_cast_to_fp8_triton(weight, use_ue8m0, GROUP_ALIGNMENT)
grad_x_padded = torch.empty(
(padded_total_m, weight.size(1)),
device=grad_output.device,
dtype=grad_output.dtype,
)
deep_gemm.m_grouped_fp8_gemm_nt_contiguous(
x_fp8,
weight_fp8,
out_padded,
dy_fp8,
weight_dx_fp8,
grad_x_padded,
grouped_layout,
use_psum_layout=False,
)
out = unpack_rows_triton(
out_padded,
total_m,
grad_x = unpack_rows_triton(
grad_x_padded,
x.size(0),
block_to_group,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
)
ctx.padded_total_m = padded_total_m
ctx.aligned_ms = ks_tensor.tolist()
ctx.save_for_backward(
x,
weight,
grouped_layout,
block_to_group,
ks_tensor,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
)
return out
return grad_x, grad_weight
@staticmethod
def backward(ctx, grad_output: torch.Tensor):
import deep_gemm
(
x,
weight,
grouped_layout,
block_to_group,
ks_tensor,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
) = ctx.saved_tensors
padded_total_m = ctx.padded_total_m
aligned_ms = ctx.aligned_ms
grad_output = grad_output.contiguous()
@_grouped_fp8_gemm_backward.register_fake
def _grouped_fp8_gemm_backward_fake(
grad_output: torch.Tensor,
x: torch.Tensor,
weight: torch.Tensor,
offs: torch.Tensor,
needs_grad_x: bool,
needs_grad_weight: bool,
) -> tuple[torch.Tensor, torch.Tensor]:
return torch.empty_like(x), torch.empty_like(weight)
grad_x = grad_weight = None
if ctx.needs_input_grad[1]:
grad_weight = _compute_grad_weight(
x,
grad_output,
weight.shape,
padded_total_m,
block_to_group,
ks_tensor,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
aligned_ms,
)
def _grouped_fp8_gemm_setup_context(ctx, inputs, output) -> None:
x, weight, offs = inputs
ctx.save_for_backward(x, weight, offs)
if ctx.needs_input_grad[0]:
use_ue8m0 = ue8m0_for_device(grad_output.device)
dy_fp8 = grouped_per_token_cast_to_fp8_triton(
grad_output,
padded_total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
use_ue8m0,
GROUP_ALIGNMENT,
)
weight_dx_fp8 = grouped_per_block_cast_to_fp8_triton(
weight,
use_ue8m0,
GROUP_ALIGNMENT,
)
grad_x_padded = torch.empty(
(padded_total_m, weight.size(1)),
device=grad_output.device,
dtype=grad_output.dtype,
)
deep_gemm.m_grouped_fp8_gemm_nt_contiguous(
dy_fp8,
weight_dx_fp8,
grad_x_padded,
grouped_layout,
use_psum_layout=False,
)
grad_x = unpack_rows_triton(
grad_x_padded,
x.size(0),
block_to_group,
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
)
return grad_x, grad_weight, None
def _grouped_fp8_gemm_autograd_backward(ctx, grad_output: torch.Tensor):
x, weight, offs = ctx.saved_tensors
needs_grad_x, needs_grad_weight, _ = ctx.needs_input_grad
grad_x, grad_weight = _grouped_fp8_gemm_backward(
grad_output,
x.detach(),
weight.detach(),
offs,
needs_grad_x,
needs_grad_weight,
)
return grad_x if needs_grad_x else None, grad_weight if needs_grad_weight else None, None
_grouped_fp8_gemm.register_autograd(
_grouped_fp8_gemm_autograd_backward,
setup_context=_grouped_fp8_gemm_setup_context,
)
def grouped_fp8_gemm(
@@ -253,4 +273,4 @@ def grouped_fp8_gemm(
Returns:
(M, N) output tensor in bfloat16.
"""
return _GroupedFP8Gemm.apply(x, weight, offs)
return _grouped_fp8_gemm(x, weight, offs)
@@ -15,68 +15,108 @@ from prime_rl.trainer.models.kernels.fp8_utils import (
from prime_rl.utils.logger import get_logger
class _FP8BlockwiseMM(torch.autograd.Function):
@staticmethod
def forward(ctx, x, weight, block_size, out_dtype=torch.bfloat16):
import deep_gemm
@torch.library.custom_op("prime_rl::fp8_blockwise_mm", mutates_args=())
def _fp8_blockwise_mm(x: torch.Tensor, weight: torch.Tensor, block_size: int) -> torch.Tensor:
import deep_gemm
x_shape = x.shape
x_2d = x.reshape(-1, x_shape[-1]).contiguous()
use_ue8m0 = ue8m0_for_device(x.device)
x_fp8 = per_token_cast_to_fp8_triton(x_2d, use_ue8m0, block_size)
weight_fp8 = per_block_cast_to_fp8_triton(weight, use_ue8m0, block_size)
x_2d = x.reshape(-1, x.shape[-1]).contiguous()
use_ue8m0 = ue8m0_for_device(x.device)
x_fp8 = per_token_cast_to_fp8_triton(x_2d, use_ue8m0, block_size)
weight_fp8 = per_block_cast_to_fp8_triton(weight, use_ue8m0, block_size)
out = torch.empty((x_2d.size(0), weight.size(0)), device=x.device, dtype=out_dtype)
deep_gemm.fp8_gemm_nt(x_fp8, weight_fp8, out)
out = torch.empty((x_2d.size(0), weight.size(0)), device=x.device, dtype=torch.bfloat16)
deep_gemm.fp8_gemm_nt(x_fp8, weight_fp8, out)
return out.reshape(*x.shape[:-1], out.size(-1))
ctx.save_for_backward(x_2d, weight)
ctx.x_shape = x_shape
ctx.block_size = block_size
return out.reshape(*x_shape[:-1], out.size(-1))
@staticmethod
def backward(ctx, grad_output):
import deep_gemm
@_fp8_blockwise_mm.register_fake
def _fp8_blockwise_mm_fake(x: torch.Tensor, weight: torch.Tensor, block_size: int) -> torch.Tensor:
return x.new_empty((*x.shape[:-1], weight.shape[0]), dtype=torch.bfloat16)
x_2d, weight = ctx.saved_tensors
block_size = ctx.block_size
grad_output_2d = grad_output.reshape(-1, grad_output.shape[-1]).contiguous()
use_ue8m0 = ue8m0_for_device(grad_output.device)
grad_x = grad_weight = None
if ctx.needs_input_grad[0]:
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, use_ue8m0, block_size)
weight_dx_fp8 = per_block_cast_to_fp8_tp_triton(weight, use_ue8m0, block_size)
grad_x_2d = torch.empty_like(x_2d)
deep_gemm.fp8_gemm_nt(grad_output_fp8, weight_dx_fp8, grad_x_2d)
grad_x = grad_x_2d.reshape(ctx.x_shape)
@torch.library.custom_op("prime_rl::fp8_blockwise_mm_backward", mutates_args=())
def _fp8_blockwise_mm_backward(
grad_output: torch.Tensor,
x: torch.Tensor,
weight: torch.Tensor,
block_size: int,
needs_grad_x: bool,
needs_grad_weight: bool,
) -> tuple[torch.Tensor, torch.Tensor]:
import deep_gemm
if ctx.needs_input_grad[1]:
# deep_gemm.fp8_gemm_nt with recipe=(1, 1, 128) requires the K (token)
# dim to be a multiple of 128. Zero-pad along the token axis so non-
# aligned per-rank batches (from sequence packing) don't trip the kernel.
M_tok = grad_output_2d.size(0)
M_pad = (M_tok + block_size - 1) // block_size * block_size
if M_pad != M_tok:
pad_rows = M_pad - M_tok
grad_output_2d_padded = torch.nn.functional.pad(grad_output_2d, (0, 0, 0, pad_rows))
x_2d_padded = torch.nn.functional.pad(x_2d, (0, 0, 0, pad_rows))
else:
grad_output_2d_padded = grad_output_2d
x_2d_padded = x_2d
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d_padded, use_ue8m0, block_size)
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d_padded, use_ue8m0, block_size)
grad_weight_fp32 = torch.zeros_like(weight, dtype=torch.float32)
deep_gemm.fp8_gemm_nt(
grad_output_t_fp8,
x_t_fp8,
grad_weight_fp32,
c=grad_weight_fp32,
recipe=(1, 1, 128),
)
grad_weight = grad_weight_fp32.to(weight.dtype)
x_2d = x.reshape(-1, x.shape[-1]).contiguous()
grad_output_2d = grad_output.reshape(-1, grad_output.shape[-1]).contiguous()
use_ue8m0 = ue8m0_for_device(grad_output.device)
grad_x = torch.empty_like(x)
grad_weight = torch.empty_like(weight)
return grad_x, grad_weight, None, None
if needs_grad_x:
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, use_ue8m0, block_size)
weight_dx_fp8 = per_block_cast_to_fp8_tp_triton(weight, use_ue8m0, block_size)
grad_x_2d = torch.empty_like(x_2d)
deep_gemm.fp8_gemm_nt(grad_output_fp8, weight_dx_fp8, grad_x_2d)
grad_x = grad_x_2d.reshape(x.shape)
if needs_grad_weight:
# DeepGEMM's (1, 1, 128) recipe requires the token dimension to be aligned.
num_tokens = grad_output_2d.size(0)
padded_tokens = (num_tokens + block_size - 1) // block_size * block_size
if padded_tokens != num_tokens:
pad_rows = padded_tokens - num_tokens
grad_output_2d = torch.nn.functional.pad(grad_output_2d, (0, 0, 0, pad_rows))
x_2d = torch.nn.functional.pad(x_2d, (0, 0, 0, pad_rows))
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d, use_ue8m0, block_size)
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d, use_ue8m0, block_size)
grad_weight_fp32 = torch.zeros_like(weight, dtype=torch.float32)
deep_gemm.fp8_gemm_nt(
grad_output_t_fp8,
x_t_fp8,
grad_weight_fp32,
c=grad_weight_fp32,
recipe=(1, 1, 128),
)
grad_weight = grad_weight_fp32.to(weight.dtype)
return grad_x, grad_weight
@_fp8_blockwise_mm_backward.register_fake
def _fp8_blockwise_mm_backward_fake(
grad_output: torch.Tensor,
x: torch.Tensor,
weight: torch.Tensor,
block_size: int,
needs_grad_x: bool,
needs_grad_weight: bool,
) -> tuple[torch.Tensor, torch.Tensor]:
return torch.empty_like(x), torch.empty_like(weight)
def _fp8_blockwise_mm_setup_context(ctx, inputs, output) -> None:
x, weight, block_size = inputs
ctx.save_for_backward(x, weight)
ctx.block_size = block_size
def _fp8_blockwise_mm_autograd_backward(ctx, grad_output: torch.Tensor):
x, weight = ctx.saved_tensors
needs_grad_x, needs_grad_weight, _ = ctx.needs_input_grad
grad_x, grad_weight = _fp8_blockwise_mm_backward(
grad_output,
x.detach(),
weight.detach(),
ctx.block_size,
needs_grad_x,
needs_grad_weight,
)
return grad_x if needs_grad_x else None, grad_weight if needs_grad_weight else None, None
_fp8_blockwise_mm.register_autograd(
_fp8_blockwise_mm_autograd_backward,
setup_context=_fp8_blockwise_mm_setup_context,
)
class Float8BlockwiseLinear(nn.Linear):
@@ -94,7 +134,7 @@ class Float8BlockwiseLinear(nn.Linear):
self.block_size = block_size
def forward(self, x: torch.Tensor) -> torch.Tensor:
return _FP8BlockwiseMM.apply(x, self.weight, self.block_size, torch.bfloat16)
return _fp8_blockwise_mm(x, self.weight, self.block_size)
@classmethod
def from_linear(cls, mod: nn.Linear) -> "Float8BlockwiseLinear":
+75 -9
View File
@@ -44,6 +44,7 @@ class FusedOutputLinear(torch.nn.Linear):
hidden_states: torch.Tensor,
labels: torch.Tensor | None = None,
temperature: Tensor | None = None,
sampling_mask: Tensor | None = None,
) -> PrimeLmOutput:
assert labels is not None, "FusedOutputLinear requires labels for chunked logprob computation"
assert temperature is not None, "FusedOutputLinear requires per-token temperatures"
@@ -52,9 +53,11 @@ class FusedOutputLinear(torch.nn.Linear):
hidden_states = hidden_states.reshape(b * s, h).contiguous()
labels = labels.reshape(b * s).contiguous()
inv_t = 1.0 / temperature.reshape(b * s).contiguous() # [N]
if sampling_mask is not None:
sampling_mask = sampling_mask.reshape(b * s, sampling_mask.shape[-1]).contiguous()
logprobs, entropy = _SequenceChunkedLogProbEntropyFn.apply(
hidden_states, self.weight, labels, inv_t, self.chunk_size
hidden_states, self.weight, labels, inv_t, self.chunk_size, sampling_mask
)
logprobs = logprobs.reshape(b, s)
@@ -67,9 +70,14 @@ class VanillaOutputLinear(torch.nn.Linear):
super().__init__(in_features, out_features, bias=False)
def forward(
self, hidden_states: torch.Tensor, labels: torch.Tensor | None = None, temperature: Tensor | None = None
self,
hidden_states: torch.Tensor,
labels: torch.Tensor | None = None,
temperature: Tensor | None = None,
sampling_mask: Tensor | None = None,
) -> PrimeLmOutput:
# VanillaOutputLinear just returns logits - temperature scaling is done externally in train.py
# VanillaOutputLinear just returns logits. train.py applies temperature
# scaling and sampling-mask replay.
return PrimeLmOutput(logits=super().forward(hidden_states))
@@ -86,6 +94,23 @@ def _online_logsumexp_and_weighted_update(
return m_new, s_new, t_new
def sampling_replay_mask(sampling_mask: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
"""Positions replayable against their sampling mask: non-empty (-1 is padding)
and containing the label (a label outside its mask means misaligned data —
fall back to full-vocab rather than emit a corrupt logprob)."""
return (sampling_mask >= 0).any(dim=-1) & (sampling_mask == labels.unsqueeze(-1)).any(dim=-1)
def _sampling_mask_local_indices(
mask_chunk: torch.Tensor, vocab_start: int, vocab_end: int
) -> tuple[torch.Tensor, torch.Tensor]:
"""Sampling-mask ids mapped into a vocab chunk as clamped local indices
plus the in-chunk validity mask (-1 entries are padding)."""
in_range = (mask_chunk >= vocab_start) & (mask_chunk < vocab_end)
local = (mask_chunk - vocab_start).clamp(0, vocab_end - vocab_start - 1)
return local, in_range
class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
@staticmethod
def forward( # type: ignore[override]
@@ -95,9 +120,15 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
labels: torch.Tensor, # [N]
inv_temperature: torch.Tensor, # [N]
chunk_size: int,
sampling_mask: torch.Tensor | None = None, # [N, K] int32, -1-padded
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Returns per-token logprobs and entropy by chunking over flattened sequence tokens.
Positions with a usable ``sampling_mask`` (see ``sampling_replay_mask``) are
renormalized over that mask: ``logprob = scaled_logits[label] -
logsumexp(scaled_logits[mask])``. Other positions — and entropy, a
full-distribution diagnostic — keep full-vocab normalization.
"""
assert hidden.dim() == 2, f"expected hidden [N,H], got {tuple(hidden.shape)}"
assert weight.dim() == 2, f"expected weight [V,H], got {tuple(weight.shape)}"
@@ -107,6 +138,10 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
assert hidden.shape[1] == weight.shape[1], "hidden/weight H mismatch"
assert hidden.shape[0] == inv_temperature.shape[0], "hidden/inv_temperature N mismatch"
assert chunk_size > 0
if sampling_mask is not None:
assert sampling_mask.dim() == 2 and sampling_mask.shape[0] == hidden.shape[0], (
f"expected sampling_mask [N,K], got {tuple(sampling_mask.shape)}"
)
device = hidden.device
n = hidden.shape[0]
@@ -115,6 +150,7 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
logprobs = torch.empty((n,), device=device, dtype=torch.float32)
entropy = torch.empty((n,), device=device, dtype=torch.float32)
logz = torch.empty((n,), device=device, dtype=torch.float32)
replay = torch.zeros((n,), device=device, dtype=torch.bool) if sampling_mask is not None else None
for start in range(0, n, chunk_size):
end = min(start + chunk_size, n)
@@ -128,6 +164,13 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
t = torch.zeros((token_count,), device=device, dtype=torch.float32)
target_logits = torch.zeros((token_count,), device=device, dtype=torch.float32)
mask_chunk = sampling_mask[start:end].to(torch.long) if sampling_mask is not None else None
if mask_chunk is not None:
replay_chunk = sampling_replay_mask(mask_chunk, labels_chunk)
# Each mask id lives in exactly one vocab chunk; collect its logit
# into a [tokens, K] buffer and logsumexp once after the loop.
mask_logits = torch.full_like(mask_chunk, float("-inf"), dtype=torch.float32)
for vocab_start in range(0, vocab, vocab_chunk_size):
vocab_end = min(vocab_start + vocab_chunk_size, vocab)
weight_chunk = weight[vocab_start:vocab_end]
@@ -136,21 +179,30 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
m, s, t = _online_logsumexp_and_weighted_update(m, s, t, scaled_logits)
if mask_chunk is not None:
mask_local, mask_in_range = _sampling_mask_local_indices(mask_chunk, vocab_start, vocab_end)
mask_logits = torch.where(mask_in_range, scaled_logits.gather(1, mask_local), mask_logits)
# Branchless target extraction - we don't want to stall the GPU here (because: if torch.any()) calls bool(Tensor) calls Tensor.items() <- sync here we don't want
in_range = (labels_chunk >= vocab_start) & (labels_chunk < vocab_end)
local_idx = (labels_chunk - vocab_start).clamp(0, vocab_end - vocab_start - 1).to(torch.int64)
chunk_target = scaled_logits.gather(1, local_idx.unsqueeze(1)).squeeze(1)
target_logits = torch.where(in_range, chunk_target, target_logits)
logz_chunk = m + torch.log(s)
logz_full = m + torch.log(s)
if mask_chunk is not None:
logz_chunk = torch.where(replay_chunk, torch.logsumexp(mask_logits, dim=-1), logz_full)
replay[start:end] = replay_chunk
else:
logz_chunk = logz_full
logz[start:end] = logz_chunk
logprobs[start:end] = target_logits - logz_chunk
entropy[start:end] = logz_chunk - (t / s)
entropy[start:end] = logz_full - (t / s)
ctx.set_materialize_grads(
False
) # Without materialized grads unused outputs get grad None instead of zeros and backward can reject them without a sync
ctx.save_for_backward(hidden, weight, labels, inv_temperature, logz)
ctx.save_for_backward(hidden, weight, labels, inv_temperature, logz, sampling_mask, replay)
ctx.chunk_size = chunk_size
return logprobs, entropy
@@ -161,7 +213,7 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
assert grad_entropy is None, "Backward through entropy is not implemented in FusedOutputLinear"
assert grad_logprobs is not None, "FusedOutputLinear backward requires logprobs gradients"
hidden, weight, labels, inv_temperature, logz = ctx.saved_tensors
hidden, weight, labels, inv_temperature, logz, sampling_mask, replay = ctx.saved_tensors
chunk_size: int = ctx.chunk_size
n, _ = hidden.shape
@@ -179,12 +231,24 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
grad_chunk = grad_logprobs[start:end].to(torch.float32)
inv_t_chunk = inv_temperature[start:end].unsqueeze(-1)
logz_chunk = logz[start:end]
mask_chunk = sampling_mask[start:end].to(torch.long) if sampling_mask is not None else None
replay_chunk = replay[start:end] if replay is not None else None
for vocab_start in range(0, vocab, vocab_chunk_size):
vocab_end = min(vocab_start + vocab_chunk_size, vocab)
weight_chunk = weight[vocab_start:vocab_end]
logits_chunk = hidden_chunk @ weight_chunk.t()
scaled_logits = logits_chunk.to(torch.float32) * inv_t_chunk
if mask_chunk is not None:
# Replayed rows get softmax gradient only on mask ids. Set masked-out
# logits to -inf before exp: a masked-out logit above the sampling-mask
# logZ would overflow exp() to inf (and inf * 0 = NaN in the grads).
local, in_range = _sampling_mask_local_indices(mask_chunk, vocab_start, vocab_end)
mask_indicator = torch.zeros(scaled_logits.shape, dtype=torch.int8, device=scaled_logits.device)
mask_indicator.scatter_add_(1, local, in_range.to(torch.int8))
masked_out = replay_chunk.unsqueeze(-1) & (mask_indicator == 0)
scaled_logits.masked_fill_(masked_out, float("-inf"))
probs = torch.exp(scaled_logits - logz_chunk.unsqueeze(-1))
grad_logits = (-grad_chunk).unsqueeze(-1) * probs
@@ -199,7 +263,7 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
if needs_weight:
grad_weight[vocab_start:vocab_end].add_(grad_logits.to(weight.dtype).t() @ hidden_chunk)
return grad_hidden, grad_weight, None, None, None
return grad_hidden, grad_weight, None, None, None, None
def inject_prime_lm_head(
@@ -262,13 +326,14 @@ def _patch_model_forward(model: nn.Module) -> None:
labels: torch.Tensor | None = None,
logits_to_keep: int = 0,
temperature: torch.Tensor | None = None,
sampling_mask: torch.Tensor | None = None,
**kwargs: object,
) -> PrimeLmOutput:
# For VLM with images, don't create position_ids - let model compute MRoPE internally
is_multimodal = kwargs.get("pixel_values") is not None
if position_ids is None and not is_multimodal:
reference_tensor = input_ids if input_ids is not None else inputs_embeds
position_ids = torch.arange(1, reference_tensor.shape[1] + 1, device=reference_tensor.device).unsqueeze(0)
position_ids = torch.arange(reference_tensor.shape[1], device=reference_tensor.device).unsqueeze(0)
model_kwargs = {"input_ids": input_ids, "position_ids": position_ids, **kwargs}
if inputs_embeds is not None:
model_kwargs["inputs_embeds"] = inputs_embeds
@@ -285,6 +350,7 @@ def _patch_model_forward(model: nn.Module) -> None:
hidden_states[:, slice_indices, :],
labels[:, slice_indices] if labels is not None else None,
temperature=temperature[:, slice_indices] if temperature is not None else None,
sampling_mask=sampling_mask[:, slice_indices] if sampling_mask is not None else None,
)
# Bind the new forward to the model
@@ -23,9 +23,11 @@ class GemmaFusedOutputLinear(torch.nn.Linear):
hidden_states: torch.Tensor,
labels: torch.Tensor | None = None,
temperature: Tensor | None = None,
sampling_mask: Tensor | None = None,
) -> PrimeLmOutput:
assert labels is not None, "GemmaFusedOutputLinear requires labels for chunked logprob computation"
assert temperature is not None, "GemmaFusedOutputLinear requires per-token temperatures"
assert sampling_mask is None, "sampling-mask replay is not supported with Gemma softcapped lm_heads"
b, s, h = hidden_states.shape
hidden_states = hidden_states.reshape(b * s, h).contiguous()
@@ -47,7 +49,11 @@ class GemmaVanillaOutputLinear(torch.nn.Linear):
self.softcap = softcap
def forward(
self, hidden_states: torch.Tensor, labels: torch.Tensor | None = None, temperature: Tensor | None = None
self,
hidden_states: torch.Tensor,
labels: torch.Tensor | None = None,
temperature: Tensor | None = None,
sampling_mask: Tensor | None = None,
) -> PrimeLmOutput:
logits = super().forward(hidden_states)
logits = self.softcap * torch.tanh(logits / self.softcap)
+30 -2
View File
@@ -20,6 +20,30 @@ from prime_rl.trainer.models.layers.mlp import ExpertType, FeedForward
ScoreFuncType = Literal["softmax", "sigmoid", "topk_softmax"]
@torch.library.custom_op(
"prime_rl::record_moe_routing_statistics",
mutates_args=("tokens_per_expert", "routing_confidence_sum"),
)
def record_moe_routing_statistics(
tokens_per_expert: torch.Tensor,
routing_confidence_sum: torch.Tensor,
token_counts: torch.Tensor,
confidence: torch.Tensor,
) -> None:
tokens_per_expert.add_(token_counts)
routing_confidence_sum.add_(confidence)
@record_moe_routing_statistics.register_fake
def _record_moe_routing_statistics_fake(
tokens_per_expert: torch.Tensor,
routing_confidence_sum: torch.Tensor,
token_counts: torch.Tensor,
confidence: torch.Tensor,
) -> None:
return None
@dataclass
class MoEArgs:
num_experts: int = 8
@@ -393,8 +417,12 @@ class MoE(nn.Module):
# Accumulate expert usage for selection-bias updates and metrics.
with torch.no_grad():
self.tokens_per_expert.add_(num_tokens_per_expert)
self.routing_confidence_sum.add_(routing_confidence_sum)
record_moe_routing_statistics(
self.tokens_per_expert,
self.routing_confidence_sum,
num_tokens_per_expert,
routing_confidence_sum,
)
routed_output = self.token_dispatcher.run(
self.prepare_expert_input(x),
+399 -508
View File
@@ -5,23 +5,10 @@ import prime_rl._compat # noqa: F401
import torch
import torch.distributed as dist
from ring_flash_attn.utils import AllGatherComm, get_default_args
from ring_flash_attn.utils import AllGatherComm
def _set_fa3_signature_params(params: dict, causal: bool, window_size: tuple[int, int]) -> None:
if "is_causal" in params:
params["is_causal"] = causal
else:
params["causal"] = causal
if "window_size" in params:
params["window_size"] = window_size
else:
params["window_size_left"] = window_size[0]
params["window_size_right"] = window_size[1]
def _fa3_varlen_forward(
def _flash_attention_forward(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
@@ -31,29 +18,74 @@ def _fa3_varlen_forward(
max_seqlen_k: int,
softmax_scale: float,
causal: bool,
window_size: tuple[int, int] = (-1, -1),
window_size: tuple[int, int],
attention_backend: str,
) -> tuple[torch.Tensor, torch.Tensor]:
from flash_attn_interface import _flash_attn_forward
if attention_backend == "flash_attention_2":
from flash_attn.flash_attn_interface import _flash_attn_varlen_forward
params = get_default_args(_flash_attn_forward).copy()
params.update(
{
"q": q,
"k": k,
"v": 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,
}
)
_set_fa3_signature_params(params, causal, window_size)
out, lse, _, _ = _flash_attn_forward(**params)
return out, lse
out, softmax_lse, _, _ = _flash_attn_varlen_forward(
q=q,
k=k,
v=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,
dropout_p=0.0,
softmax_scale=softmax_scale,
causal=causal,
window_size_left=window_size[0],
window_size_right=window_size[1],
softcap=0.0,
alibi_slopes=None,
return_softmax=False,
)
return out, softmax_lse
if attention_backend == "flash_attention_3":
from flash_attn_interface import _flash_attn_forward
out, softmax_lse, _, _ = _flash_attn_forward(
q=q,
k=k,
v=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[0],
window_size_right=window_size[1],
)
return out, softmax_lse
if attention_backend == "flash_attention_4":
from flash_attn.cute.interface import _flash_attn_fwd
window_size_left = window_size[0] if window_size[0] != -1 else None
window_size_right = window_size[1] if window_size[1] != -1 else None
out, softmax_lse, _, _ = _flash_attn_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_lse=True,
)
return out, softmax_lse
raise ValueError(f"Unsupported ring attention backend: {attention_backend}")
def _fa3_varlen_backward(
def _flash_attention_backward(
dout: torch.Tensor,
q: torch.Tensor,
k: torch.Tensor,
@@ -69,217 +101,92 @@ def _fa3_varlen_backward(
dv: torch.Tensor,
softmax_scale: float,
causal: bool,
window_size: tuple[int, int] = (-1, -1),
window_size: tuple[int, int],
attention_backend: str,
) -> None:
from flash_attn_interface import _flash_attn_backward
if attention_backend == "flash_attention_2":
from flash_attn.flash_attn_interface import _flash_attn_varlen_backward
params = get_default_args(_flash_attn_backward).copy()
params.update(
{
"dout": dout,
"q": q,
"k": k,
"v": v,
"out": out,
"softmax_lse": softmax_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,
}
)
_set_fa3_signature_params(params, causal, window_size)
_flash_attn_backward(**params)
_flash_attn_varlen_backward(
dout=dout,
q=q,
k=k,
v=v,
out=out,
softmax_lse=softmax_lse,
dq=dq,
dk=dk,
dv=dv,
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=max_seqlen_q,
max_seqlen_k=max_seqlen_k,
dropout_p=0.0,
softmax_scale=softmax_scale,
causal=causal,
window_size_left=window_size[0],
window_size_right=window_size[1],
softcap=0.0,
alibi_slopes=None,
deterministic=False,
)
return
if attention_backend == "flash_attention_3":
from flash_attn_interface import _flash_attn_backward
_flash_attn_backward(
dout=dout,
q=q,
k=k,
v=v,
out=out,
softmax_lse=softmax_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[0],
window_size_right=window_size[1],
)
return
if attention_backend == "flash_attention_4":
from flash_attn.cute.interface import _flash_attn_bwd
window_size_left = window_size[0] if window_size[0] != -1 else None
window_size_right = window_size[1] if window_size[1] != -1 else None
_flash_attn_bwd(
q,
k,
v,
out,
dout,
softmax_lse,
softmax_scale=softmax_scale,
causal=causal,
window_size_left=window_size_left,
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,
dq=dq,
dk=dk,
dv=dv,
)
return
raise ValueError(f"Unsupported ring attention backend: {attention_backend}")
class _RingFA3Varlen(torch.autograd.Function):
"""Ring attention using FA3 kernels with all-gather communication.
Mirrors the llama3_flash_attn_varlen pattern from ring-flash-attn but
calls flash-attention-3 low-level forward/backward instead of FA2.
"""
@staticmethod
def forward(
ctx,
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,
local_k_slice_start: int,
local_k_slice_stop: int,
heads_k_stride: int,
causal: bool,
group_name: str,
window_size_left: int = -1,
window_size_right: int = -1,
) -> torch.Tensor:
group = dist.group.WORLD
for pg in dist.distributed_c10d._world.pg_map:
if pg.group_name == group_name:
group = pg
break
local_k_slice = slice(local_k_slice_start, local_k_slice_stop)
window_size = (window_size_left, window_size_right)
softmax_scale = q.shape[-1] ** (-0.5)
out_list = []
lse_list = []
nheads = q.shape[1]
total_k, nheads_k, head_dim = k.shape
world_size = dist.get_world_size(group)
kv_buffer = torch.empty((2, total_k * world_size, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
kv_buffer_copy = torch.empty_like(kv_buffer)
comm = AllGatherComm(group)
comm.all_gather(kv_buffer_copy[0], k[:, :heads_k_stride].contiguous())
comm.all_gather(kv_buffer_copy[1], v[:, :heads_k_stride].contiguous())
for i in range(0, nheads_k, heads_k_stride):
comm.wait()
kv_buffer, kv_buffer_copy = kv_buffer_copy, kv_buffer
if i < nheads_k - heads_k_stride:
left = i + heads_k_stride
right = left + heads_k_stride
comm.all_gather(kv_buffer_copy[0], k[:, left:right].contiguous())
comm.all_gather(kv_buffer_copy[1], v[:, left:right].contiguous())
q_i = q[:, i * nheads // nheads_k : (i + heads_k_stride) * nheads // nheads_k]
k_i = kv_buffer[0][local_k_slice]
v_i = kv_buffer[1][local_k_slice]
out_i, lse_i = _fa3_varlen_forward(
q=q_i,
k=k_i,
v=v_i,
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=window_size,
)
out_list.append(out_i)
lse_list.append(lse_i)
out = torch.cat(out_list, dim=1)
lse = torch.cat(lse_list, dim=-2)
ctx.save_for_backward(q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k)
ctx.softmax_scale = softmax_scale
ctx.max_seqlen_q = max_seqlen_q
ctx.max_seqlen_k = max_seqlen_k
ctx.local_k_slice = local_k_slice
ctx.heads_k_stride = heads_k_stride
ctx.causal = causal
ctx.group_name = group_name
ctx.window_size = window_size
return out
@staticmethod
def backward(ctx, dout: torch.Tensor):
q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k = ctx.saved_tensors
heads_k_stride = ctx.heads_k_stride
local_k_slice = ctx.local_k_slice
causal = ctx.causal
group = dist.group.WORLD
for pg in dist.distributed_c10d._world.pg_map:
if pg.group_name == ctx.group_name:
group = pg
break
nheads = q.shape[1]
total_k, nheads_k, head_dim = k.shape
world_size = dist.get_world_size(group)
kv_buffer = torch.empty((2, total_k * world_size, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
kv_buffer_copy = torch.empty_like(kv_buffer)
dkv_buffer = torch.empty((2, total_k * world_size, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
kv_contiguous_buffer = None
if heads_k_stride != nheads_k:
kv_contiguous_buffer = torch.empty((2, total_k, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
dq = torch.empty_like(q)
dk = torch.empty_like(k)
dv = torch.empty_like(v)
comm = AllGatherComm(group)
comm.all_gather(kv_buffer_copy[0], k[:, :heads_k_stride].contiguous())
comm.all_gather(kv_buffer_copy[1], v[:, :heads_k_stride].contiguous())
for i in range(0, nheads_k, heads_k_stride):
dkv_buffer.zero_()
q_slice = slice(i * nheads // nheads_k, (i + heads_k_stride) * nheads // nheads_k)
q_i = q[:, q_slice]
dout_i = dout[:, q_slice]
out_i = out[:, q_slice]
dq_i = dq[:, q_slice]
lse_i = softmax_lse[q_slice].contiguous()
comm.wait()
kv_buffer, kv_buffer_copy = kv_buffer_copy, kv_buffer
if i < nheads_k - heads_k_stride:
left = i + heads_k_stride
right = left + heads_k_stride
comm.all_gather(kv_buffer_copy[0], k[:, left:right].contiguous())
comm.all_gather(kv_buffer_copy[1], v[:, left:right].contiguous())
k_i = kv_buffer[0][local_k_slice]
v_i = kv_buffer[1][local_k_slice]
dk_i = dkv_buffer[0][local_k_slice]
dv_i = dkv_buffer[1][local_k_slice]
_fa3_varlen_backward(
dout=dout_i,
q=q_i,
k=k_i,
v=v_i,
out=out_i,
softmax_lse=lse_i,
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=ctx.max_seqlen_q,
max_seqlen_k=ctx.max_seqlen_k,
dq=dq_i,
dk=dk_i,
dv=dv_i,
softmax_scale=ctx.softmax_scale,
causal=causal,
window_size=ctx.window_size,
)
if heads_k_stride != nheads_k:
dk_i = kv_contiguous_buffer[0]
dv_i = kv_contiguous_buffer[1]
else:
dk_i = dk
dv_i = dv
dist.reduce_scatter_tensor(dk_i, dkv_buffer[0], group=group)
dist.reduce_scatter_tensor(dv_i, dkv_buffer[1], group=group)
if heads_k_stride != nheads_k:
dk[:, i : i + heads_k_stride] = dk_i
dv[:, i : i + heads_k_stride] = dv_i
# Grads for: q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k,
# local_k_slice_start, local_k_slice_stop, heads_k_stride, causal, group_name,
# window_size_left, window_size_right
return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None
def ring_fa3_varlen_func(
@torch.library.custom_op("prime_rl_ring::attention", mutates_args=())
def ring_attention_forward(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
@@ -287,36 +194,68 @@ def ring_fa3_varlen_func(
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
local_k_slice: slice,
causal: bool,
local_k_slice_start: int,
local_k_slice_stop: int,
heads_k_stride: int,
group: dist.ProcessGroup,
window_size: tuple[int, int] = (-1, -1),
) -> torch.Tensor:
return _RingFA3Varlen.apply(
q,
k,
v,
cu_seqlens_q,
cu_seqlens_k,
max_seqlen_q,
max_seqlen_k,
local_k_slice.start,
local_k_slice.stop,
heads_k_stride,
causal,
group.group_name,
window_size[0],
window_size[1],
)
causal: bool,
group_name: str,
window_size_left: int,
window_size_right: int,
attention_backend: str,
) -> tuple[torch.Tensor, torch.Tensor]:
group = dist.distributed_c10d._resolve_process_group(group_name)
local_k_slice = slice(local_k_slice_start, local_k_slice_stop)
window_size = (window_size_left, window_size_right)
softmax_scale = q.shape[-1] ** -0.5
_, num_query_heads, _ = q.shape
local_k_tokens, num_kv_heads, head_dim = k.shape
world_size = group.size()
gathered_kv_shape = (2, local_k_tokens * world_size, heads_k_stride, head_dim)
gathered_kv = torch.empty(gathered_kv_shape, dtype=k.dtype, device=k.device)
next_gathered_kv = torch.empty_like(gathered_kv)
communication = AllGatherComm(group)
communication.all_gather(next_gathered_kv[0], k[:, :heads_k_stride].contiguous())
communication.all_gather(next_gathered_kv[1], v[:, :heads_k_stride].contiguous())
outputs = []
softmax_lses = []
query_heads_per_kv_head = num_query_heads // num_kv_heads
for kv_head_start in range(0, num_kv_heads, heads_k_stride):
communication.wait()
gathered_kv, next_gathered_kv = next_gathered_kv, gathered_kv
next_kv_head_start = kv_head_start + heads_k_stride
if next_kv_head_start < num_kv_heads:
next_kv_head_stop = next_kv_head_start + heads_k_stride
communication.all_gather(next_gathered_kv[0], k[:, next_kv_head_start:next_kv_head_stop].contiguous())
communication.all_gather(next_gathered_kv[1], v[:, next_kv_head_start:next_kv_head_stop].contiguous())
query_head_start = kv_head_start * query_heads_per_kv_head
query_head_stop = (kv_head_start + heads_k_stride) * query_heads_per_kv_head
query_head_slice = slice(query_head_start, query_head_stop)
out, softmax_lse = _flash_attention_forward(
q=q[:, query_head_slice],
k=gathered_kv[0][local_k_slice],
v=gathered_kv[1][local_k_slice],
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=window_size,
attention_backend=attention_backend,
)
outputs.append(out)
softmax_lses.append(softmax_lse)
return torch.cat(outputs, dim=1), torch.cat(softmax_lses, dim=-2)
# ---------------------------------------------------------------------------
# FA4 (flash_attn.cute) ring attention
# ---------------------------------------------------------------------------
def _fa4_varlen_forward(
@ring_attention_forward.register_fake
def _ring_attention_forward_fake(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
@@ -324,32 +263,20 @@ def _fa4_varlen_forward(
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
softmax_scale: float,
local_k_slice_start: int,
local_k_slice_stop: int,
heads_k_stride: int,
causal: bool,
window_size: tuple[int, int] = (-1, -1),
group_name: str,
window_size_left: int,
window_size_right: int,
attention_backend: str,
) -> tuple[torch.Tensor, torch.Tensor]:
from flash_attn.cute.interface import _flash_attn_fwd
wl = window_size[0] if window_size[0] != -1 else None
wr = window_size[1] if window_size[1] != -1 else None
out, lse = _flash_attn_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=wl,
window_size_right=wr,
return_lse=True,
)
return out, lse
return torch.empty_like(q), q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
def _fa4_varlen_backward(
@torch.library.custom_op("prime_rl_ring::attention_backward", mutates_args=())
def ring_attention_backward(
dout: torch.Tensor,
q: torch.Tensor,
k: torch.Tensor,
@@ -360,221 +287,182 @@ def _fa4_varlen_backward(
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
dq: torch.Tensor,
dk: torch.Tensor,
dv: torch.Tensor,
softmax_scale: float,
local_k_slice_start: int,
local_k_slice_stop: int,
heads_k_stride: int,
causal: bool,
window_size: tuple[int, int] = (-1, -1),
) -> None:
from flash_attn.cute.interface import _flash_attn_bwd
group_name: str,
window_size_left: int,
window_size_right: int,
attention_backend: str,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
group = dist.distributed_c10d._resolve_process_group(group_name)
local_k_slice = slice(local_k_slice_start, local_k_slice_stop)
window_size = (window_size_left, window_size_right)
softmax_scale = q.shape[-1] ** -0.5
wl = window_size[0] if window_size[0] != -1 else None
wr = window_size[1] if window_size[1] != -1 else None
_flash_attn_bwd(
_, num_query_heads, _ = q.shape
local_k_tokens, num_kv_heads, head_dim = k.shape
world_size = group.size()
gathered_kv_shape = (2, local_k_tokens * world_size, heads_k_stride, head_dim)
gathered_kv = torch.empty(gathered_kv_shape, dtype=k.dtype, device=k.device)
next_gathered_kv = torch.empty_like(gathered_kv)
gathered_kv_grad = torch.empty_like(gathered_kv)
local_kv_grad = (
torch.empty((2, local_k_tokens, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
if heads_k_stride != num_kv_heads
else None
)
dq = torch.empty_like(q)
dk = torch.empty_like(k)
dv = torch.empty_like(v)
communication = AllGatherComm(group)
communication.all_gather(next_gathered_kv[0], k[:, :heads_k_stride].contiguous())
communication.all_gather(next_gathered_kv[1], v[:, :heads_k_stride].contiguous())
query_heads_per_kv_head = num_query_heads // num_kv_heads
for kv_head_start in range(0, num_kv_heads, heads_k_stride):
gathered_kv_grad.zero_()
communication.wait()
gathered_kv, next_gathered_kv = next_gathered_kv, gathered_kv
next_kv_head_start = kv_head_start + heads_k_stride
if next_kv_head_start < num_kv_heads:
next_kv_head_stop = next_kv_head_start + heads_k_stride
communication.all_gather(next_gathered_kv[0], k[:, next_kv_head_start:next_kv_head_stop].contiguous())
communication.all_gather(next_gathered_kv[1], v[:, next_kv_head_start:next_kv_head_stop].contiguous())
query_head_start = kv_head_start * query_heads_per_kv_head
query_head_stop = (kv_head_start + heads_k_stride) * query_heads_per_kv_head
query_head_slice = slice(query_head_start, query_head_stop)
# FA2, FA3, and FA4 varlen kernels all return LSE as [heads, total_tokens].
head_softmax_lse = softmax_lse[query_head_slice].contiguous()
_flash_attention_backward(
dout=dout[:, query_head_slice],
q=q[:, query_head_slice],
k=gathered_kv[0][local_k_slice],
v=gathered_kv[1][local_k_slice],
out=out[:, query_head_slice],
softmax_lse=head_softmax_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[:, query_head_slice],
dk=gathered_kv_grad[0][local_k_slice],
dv=gathered_kv_grad[1][local_k_slice],
softmax_scale=softmax_scale,
causal=causal,
window_size=window_size,
attention_backend=attention_backend,
)
if local_kv_grad is None:
reduced_dk = dk
reduced_dv = dv
else:
reduced_dk = local_kv_grad[0]
reduced_dv = local_kv_grad[1]
dist.reduce_scatter_tensor(reduced_dk, gathered_kv_grad[0], group=group)
dist.reduce_scatter_tensor(reduced_dv, gathered_kv_grad[1], group=group)
if local_kv_grad is not None:
kv_head_stop = kv_head_start + heads_k_stride
dk[:, kv_head_start:kv_head_stop] = reduced_dk
dv[:, kv_head_start:kv_head_stop] = reduced_dv
return dq, dk, dv
@ring_attention_backward.register_fake
def _ring_attention_backward_fake(
dout: torch.Tensor,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
out: torch.Tensor,
softmax_lse: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
local_k_slice_start: int,
local_k_slice_stop: int,
heads_k_stride: int,
causal: bool,
group_name: str,
window_size_left: int,
window_size_right: int,
attention_backend: str,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
return torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
def _ring_attention_setup_context(ctx, inputs, output) -> None:
(
q,
k,
v,
out,
dout,
softmax_lse,
softmax_scale=softmax_scale,
causal=causal,
window_size_left=wl,
window_size_right=wr,
cu_seqlens_q,
cu_seqlens_k,
max_seqlen_q,
max_seqlen_k,
local_k_slice_start,
local_k_slice_stop,
heads_k_stride,
causal,
group_name,
window_size_left,
window_size_right,
attention_backend,
) = inputs
out, softmax_lse = output
ctx.save_for_backward(q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k)
ctx.max_seqlen_q = max_seqlen_q
ctx.max_seqlen_k = max_seqlen_k
ctx.local_k_slice_start = local_k_slice_start
ctx.local_k_slice_stop = local_k_slice_stop
ctx.heads_k_stride = heads_k_stride
ctx.causal = causal
ctx.group_name = group_name
ctx.window_size_left = window_size_left
ctx.window_size_right = window_size_right
ctx.attention_backend = attention_backend
ctx.mark_non_differentiable(softmax_lse)
def _ring_attention_autograd_backward(ctx, dout: torch.Tensor, _dsoftmax_lse: torch.Tensor | None):
q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k = ctx.saved_tensors
dq, dk, dv = ring_attention_backward(
dout=dout.contiguous(),
q=q.detach(),
k=k.detach(),
v=v.detach(),
out=out.detach(),
softmax_lse=softmax_lse.detach(),
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,
max_seqlen_q=ctx.max_seqlen_q,
max_seqlen_k=ctx.max_seqlen_k,
local_k_slice_start=ctx.local_k_slice_start,
local_k_slice_stop=ctx.local_k_slice_stop,
heads_k_stride=ctx.heads_k_stride,
causal=ctx.causal,
group_name=ctx.group_name,
window_size_left=ctx.window_size_left,
window_size_right=ctx.window_size_right,
attention_backend=ctx.attention_backend,
)
return (dq, dk, dv) + (None,) * 12
class _RingFA4Varlen(torch.autograd.Function):
"""Ring attention using FA4 (flash_attn.cute) kernels with all-gather communication.
Mirrors _RingFA3Varlen but calls the FA4 low-level forward/backward.
"""
@staticmethod
def forward(
ctx,
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,
local_k_slice_start: int,
local_k_slice_stop: int,
heads_k_stride: int,
causal: bool,
group_name: str,
window_size_left: int = -1,
window_size_right: int = -1,
) -> torch.Tensor:
group = dist.group.WORLD
for pg in dist.distributed_c10d._world.pg_map:
if pg.group_name == group_name:
group = pg
break
local_k_slice = slice(local_k_slice_start, local_k_slice_stop)
window_size = (window_size_left, window_size_right)
softmax_scale = q.shape[-1] ** (-0.5)
out_list = []
lse_list = []
nheads = q.shape[1]
total_k, nheads_k, head_dim = k.shape
world_size = dist.get_world_size(group)
kv_buffer = torch.empty((2, total_k * world_size, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
kv_buffer_copy = torch.empty_like(kv_buffer)
comm = AllGatherComm(group)
comm.all_gather(kv_buffer_copy[0], k[:, :heads_k_stride].contiguous())
comm.all_gather(kv_buffer_copy[1], v[:, :heads_k_stride].contiguous())
for i in range(0, nheads_k, heads_k_stride):
comm.wait()
kv_buffer, kv_buffer_copy = kv_buffer_copy, kv_buffer
if i < nheads_k - heads_k_stride:
left = i + heads_k_stride
right = left + heads_k_stride
comm.all_gather(kv_buffer_copy[0], k[:, left:right].contiguous())
comm.all_gather(kv_buffer_copy[1], v[:, left:right].contiguous())
q_i = q[:, i * nheads // nheads_k : (i + heads_k_stride) * nheads // nheads_k]
k_i = kv_buffer[0][local_k_slice]
v_i = kv_buffer[1][local_k_slice]
out_i, lse_i = _fa4_varlen_forward(
q=q_i,
k=k_i,
v=v_i,
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=window_size,
)
out_list.append(out_i)
lse_list.append(lse_i)
out = torch.cat(out_list, dim=1)
lse = torch.cat(lse_list, dim=-2)
ctx.save_for_backward(q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k)
ctx.softmax_scale = softmax_scale
ctx.max_seqlen_q = max_seqlen_q
ctx.max_seqlen_k = max_seqlen_k
ctx.local_k_slice = local_k_slice
ctx.heads_k_stride = heads_k_stride
ctx.causal = causal
ctx.group_name = group_name
ctx.window_size = window_size
return out
@staticmethod
def backward(ctx, dout: torch.Tensor):
q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k = ctx.saved_tensors
heads_k_stride = ctx.heads_k_stride
local_k_slice = ctx.local_k_slice
causal = ctx.causal
group = dist.group.WORLD
for pg in dist.distributed_c10d._world.pg_map:
if pg.group_name == ctx.group_name:
group = pg
break
nheads = q.shape[1]
total_k, nheads_k, head_dim = k.shape
world_size = dist.get_world_size(group)
kv_buffer = torch.empty((2, total_k * world_size, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
kv_buffer_copy = torch.empty_like(kv_buffer)
dkv_buffer = torch.empty((2, total_k * world_size, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
kv_contiguous_buffer = None
if heads_k_stride != nheads_k:
kv_contiguous_buffer = torch.empty((2, total_k, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
dq = torch.empty_like(q)
dk = torch.empty_like(k)
dv = torch.empty_like(v)
comm = AllGatherComm(group)
comm.all_gather(kv_buffer_copy[0], k[:, :heads_k_stride].contiguous())
comm.all_gather(kv_buffer_copy[1], v[:, :heads_k_stride].contiguous())
for i in range(0, nheads_k, heads_k_stride):
dkv_buffer.zero_()
q_slice = slice(i * nheads // nheads_k, (i + heads_k_stride) * nheads // nheads_k)
q_i = q[:, q_slice]
dout_i = dout[:, q_slice]
out_i = out[:, q_slice]
dq_i = dq[:, q_slice]
lse_i = softmax_lse[q_slice].contiguous()
comm.wait()
kv_buffer, kv_buffer_copy = kv_buffer_copy, kv_buffer
if i < nheads_k - heads_k_stride:
left = i + heads_k_stride
right = left + heads_k_stride
comm.all_gather(kv_buffer_copy[0], k[:, left:right].contiguous())
comm.all_gather(kv_buffer_copy[1], v[:, left:right].contiguous())
k_i = kv_buffer[0][local_k_slice]
v_i = kv_buffer[1][local_k_slice]
dk_i = dkv_buffer[0][local_k_slice]
dv_i = dkv_buffer[1][local_k_slice]
_fa4_varlen_backward(
dout=dout_i,
q=q_i,
k=k_i,
v=v_i,
out=out_i,
softmax_lse=lse_i,
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=ctx.max_seqlen_q,
max_seqlen_k=ctx.max_seqlen_k,
dq=dq_i,
dk=dk_i,
dv=dv_i,
softmax_scale=ctx.softmax_scale,
causal=causal,
window_size=ctx.window_size,
)
if heads_k_stride != nheads_k:
dk_i = kv_contiguous_buffer[0]
dv_i = kv_contiguous_buffer[1]
else:
dk_i = dk
dv_i = dv
dist.reduce_scatter_tensor(dk_i, dkv_buffer[0], group=group)
dist.reduce_scatter_tensor(dv_i, dkv_buffer[1], group=group)
if heads_k_stride != nheads_k:
dk[:, i : i + heads_k_stride] = dk_i
dv[:, i : i + heads_k_stride] = dv_i
# Grads for: q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k,
# local_k_slice_start, local_k_slice_stop, heads_k_stride, causal, group_name,
# window_size_left, window_size_right
return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None
ring_attention_forward.register_autograd(
_ring_attention_autograd_backward,
setup_context=_ring_attention_setup_context,
)
def ring_fa4_varlen_func(
def ring_varlen_attention(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
@@ -586,21 +474,24 @@ def ring_fa4_varlen_func(
causal: bool,
heads_k_stride: int,
group: dist.ProcessGroup,
attention_backend: str,
window_size: tuple[int, int] = (-1, -1),
) -> torch.Tensor:
return _RingFA4Varlen.apply(
q,
k,
v,
cu_seqlens_q,
cu_seqlens_k,
max_seqlen_q,
max_seqlen_k,
local_k_slice.start,
local_k_slice.stop,
heads_k_stride,
causal,
group.group_name,
window_size[0],
window_size[1],
out, _ = ring_attention_forward(
q=q,
k=k,
v=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,
local_k_slice_start=local_k_slice.start,
local_k_slice_stop=local_k_slice.stop,
heads_k_stride=heads_k_stride,
causal=causal,
group_name=group.group_name,
window_size_left=window_size[0],
window_size_right=window_size[1],
attention_backend=attention_backend,
)
return out
@@ -37,7 +37,8 @@ from __future__ import annotations
import torch
import torch.distributed as dist
import torch.distributed.nn.functional as dist_nn
from prime_rl.trainer.distributed.collectives import all_to_all_single_equal
# Populated by `update_ulysses_params` before each forward pass. Mirrors
# ring_flash_attn's DATA_PARAMS pattern so the patched attention path can
@@ -68,18 +69,11 @@ def _replicate_kv_heads(t: torch.Tensor, cp_size: int) -> torch.Tensor:
return t.repeat_interleave(cp_size // h, dim=1)
@torch._dynamo.disable
def _all_to_all_seq_to_head(t: torch.Tensor, cp_size: int, cp_group: dist.ProcessGroup) -> torch.Tensor:
"""Redistribute [S_local, H, D] -> [S_global, H_local, D].
Splits the head dim into cp_size groups and exchanges them so each rank
ends up with the full sequence but only H/cp_size heads. Differentiable.
Disabled for dynamo: the collective must execute eagerly so it is scheduled
by the autograd engine in a consistent order across ranks, not reordered by
the compiled backward graph. Otherwise FSDP's post_backward reduce-scatter
and the all-to-all backward can interleave differently per rank, deadlocking
NCCL (see PR #3186 job 1578).
"""
s_local, h, d = t.shape
assert h % cp_size == 0, (
@@ -90,14 +84,12 @@ def _all_to_all_seq_to_head(t: torch.Tensor, cp_size: int, cp_group: dist.Proces
# [S_local, cp_size, H_local, D] -> [cp_size, S_local, H_local, D]
t = t.reshape(s_local, cp_size, h_local, d).transpose(0, 1).contiguous()
output = torch.empty_like(t)
out = dist_nn.all_to_all_single(output, t, group=cp_group)
out = all_to_all_single_equal(t, cp_group)
# out[i] is the chunk that source-rank i had at position my_rank, i.e.
# source-rank i's local sequence shard for *my* head slice.
return out.reshape(cp_size * s_local, h_local, d)
@torch._dynamo.disable
def _all_to_all_head_to_seq(t: torch.Tensor, cp_size: int, cp_group: dist.ProcessGroup) -> torch.Tensor:
"""Inverse of `_all_to_all_seq_to_head`: [S_global, H_local, D] -> [S_local, H, D]."""
s_global, h_local, d = t.shape
@@ -106,8 +98,7 @@ def _all_to_all_head_to_seq(t: torch.Tensor, cp_size: int, cp_group: dist.Proces
h = h_local * cp_size
t = t.reshape(cp_size, s_local, h_local, d).contiguous()
output = torch.empty_like(t)
out = dist_nn.all_to_all_single(output, t, group=cp_group)
out = all_to_all_single_equal(t, cp_group)
# out[s']: original chunk for sequence-rank s' (which now becomes head-rank s').
return out.transpose(0, 1).contiguous().reshape(s_local, h, d)
@@ -19,7 +19,7 @@ from transformers.modeling_outputs import BaseModelOutputWithPast
from transformers.models.nemotron_h.modular_nemotron_h import NemotronHMamba2Mixer
from transformers.utils import auto_docstring, logging
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.base import CPSupport, PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
from prime_rl.trainer.models.layers.cp_mamba import mamba_cp_forward
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
@@ -377,6 +377,14 @@ class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
_supports_sdpa = False
_can_compile_fullgraph = False
@classmethod
def cp_support(cls, config) -> CPSupport:
return CPSupport(
frozenset({"ulysses"}),
"ring CP is a softmax-attention algorithm and cannot run this model's Mamba layers, "
"whereas ulysses' all-to-all on Q/K/V leaves the SSM kernel unchanged",
)
@classmethod
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
return name.endswith(("mamba.A_log", "mamba.D", "mlp.router.selection_bias"))
@@ -16,7 +16,7 @@ from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5VisionModel
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.base import ALL_CP_STYLES, CPSupport, PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import FeedForward
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
@@ -137,6 +137,19 @@ class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
"hidden_states": Qwen3_5DecoderLayer,
}
@classmethod
def cp_support(cls, config) -> CPSupport:
# VLM configs nest the layer schedule under `text_config`.
text_config = getattr(config, "text_config", config)
if "linear_attention" in (getattr(text_config, "layer_types", None) or ()):
return CPSupport(
frozenset({"ulysses"}),
"ring CP is a softmax-attention algorithm and cannot run this model's DeltaNet "
"layers, whereas ulysses' all-to-all on Q/K/V leaves the linear-attention kernel "
"unchanged",
)
return CPSupport(ALL_CP_STYLES)
@classmethod
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
return name.endswith(("linear_attn.A_log", "linear_attn.norm.weight"))
@@ -19,7 +19,7 @@ from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeVisio
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs, logging
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.base import ALL_CP_STYLES, CPSupport, PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import (
flash_attn_3_varlen_func,
flash_attn_4_varlen_func,
@@ -278,18 +278,6 @@ class Qwen3_5MoeGatedAttentionBase(nn.Module):
self.q_norm = Qwen3_5MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.k_norm = Qwen3_5MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
def output_proj(
self,
attn_output: torch.Tensor,
gate: torch.Tensor,
) -> torch.Tensor:
input_shape = gate.shape[:-1]
if attn_output.dim() == 4:
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.contiguous().view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate)
return self.o_proj(attn_output)
class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
"""Gated softmax attention using Flash Attention varlen functions."""
@@ -326,21 +314,13 @@ class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
out = out[0]
return out
def _attention_core(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> torch.Tensor:
return self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
def attn_projections(
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, None]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
@@ -360,24 +340,10 @@ class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
return query_states, key_states, value_states, gate
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, None]:
query_states, key_states, value_states, gate = self.attn_projections(hidden_states, position_embeddings)
attn_output = self._attention_core(
query_states,
key_states,
value_states,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
return self.output_proj(attn_output, gate), None
attn_output = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
attn_output = attn_output.contiguous().view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate)
return self.o_proj(attn_output), None
QWEN35MOE_ATTN_IMPL2CLASS = {
@@ -632,6 +598,19 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
"hidden_states": Qwen3_5MoeDecoderLayer,
}
@classmethod
def cp_support(cls, config) -> CPSupport:
# VLM configs nest the layer schedule under `text_config`.
text_config = getattr(config, "text_config", config)
if "linear_attention" in (getattr(text_config, "layer_types", None) or ()):
return CPSupport(
frozenset({"ulysses"}),
"ring CP is a softmax-attention algorithm and cannot run this model's DeltaNet "
"layers, whereas ulysses' all-to-all on Q/K/V leaves the linear-attention kernel "
"unchanged",
)
return CPSupport(ALL_CP_STYLES)
@classmethod
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
return name.endswith(("linear_attn.A_log", "linear_attn.norm.weight"))
-3
View File
@@ -80,14 +80,11 @@ def configure_moe_runtime(model: nn.Module, config: ModelConfig, parallel_dims:
)
elif isinstance(dispatch, TorchMoEDispatchConfig):
if dispatch.transport == "mxfp8":
import prime_kernels
token_dispatcher = MXFP8TorchTokenDispatcher(
num_experts=moe.experts.num_experts,
top_k=moe.router.top_k,
token_group_alignment=grouped_gemm.token_group_alignment,
group=ep_mesh.get_group(),
kernel=prime_kernels.load("mxfp8_moe"),
)
else:
token_dispatcher = TorchTokenDispatcher(
+90
View File
@@ -0,0 +1,90 @@
import asyncio
import math
from collections.abc import Mapping
from typing import Any
import torch
import torch.distributed as dist
from torch import Tensor
from prime_rl import monitors
from prime_rl.monitors.file.traces.update import make_update
class AnnotationWriter:
"""Collects the trainer's per-token streams (recomputed logprobs, entropies) during
a step and logs them as trace updates — one record per trained sequence, keyed by
``(trace_id, branch_index)``. Streams are full-length over the sample's token prefix
so readers can fold them onto trace nodes without knowing the trainer's loss mask;
positions outside that mask hold null, since a fold keeps sampled tokens only and a
run of nulls costs nothing once the stream is sealed.
``export`` accumulates locally per micro batch; ``flush`` gathers every rank's
records to rank 0, the only rank running monitors. CP ranks past the first
accumulate nothing since they share their micro batches."""
def __init__(self, parallel_dims: Any, world: Any, float_decimals: int | None) -> None:
self.world = world
self.float_decimals = float_decimals
self.is_duplicate_rank = parallel_dims.cp_enabled and parallel_dims.world_mesh["cp"].get_local_rank() != 0
self._pending: list[dict[str, Any]] = []
def export(self, micro_batch: Mapping[str, Any], model_output: Mapping[str, Tensor]) -> None:
if self.is_duplicate_rank:
return
trace_ids = micro_batch["trace_ids"]
branch_indices = micro_batch["branch_indices"]
if not trace_ids or not branch_indices:
return
sequence_lengths = micro_batch["sequence_lengths"]
loss_mask = [bool(v) for v in micro_batch["loss_mask"].detach().cpu().reshape(-1).tolist()]
env_names = micro_batch["env_names"]
trainer_logprobs = _tensor_to_floats(model_output["logprobs"], self.float_decimals)
entropies = _tensor_to_floats(model_output["entropy"], self.float_decimals)
start = 0
for trace_id, branch_index, length in zip(trace_ids, branch_indices, sequence_lengths):
span_start, end = start, start + length
start = end
if not trace_id or branch_index < 0:
continue
# Trailing padding is appended to the last sample and folded into its length.
while end > span_start and env_names[end - 1] == "" and not loss_mask[end - 1]:
end -= 1
if end <= span_start or not any(loss_mask[span_start:end]):
continue
trained = loss_mask[span_start:end]
logprob_span = [v if m else None for v, m in zip(trainer_logprobs[span_start:end], trained)]
entropy_span = [v if m else None for v, m in zip(entropies[span_start:end], trained)]
# After the right shift, a sample's first value crosses the packing boundary.
logprob_span[0] = None
entropy_span[0] = None
self._pending.append(
make_update(
trace_id,
branches={branch_index: {"trainer_logprobs": logprob_span, "entropies": entropy_span}},
)
)
def flush(self) -> None:
"""Gather the step's records to rank 0 and log them; collective, so every rank
must call it once per step."""
records, self._pending = self._pending, []
if dist.is_initialized() and self.world.world_size > 1:
gathered: list[list[dict[str, Any]]] | None = None
if self.world.rank == 0:
gathered = [[] for _ in range(self.world.world_size)]
dist.gather_object(records, gathered, dst=0)
if gathered is None:
return
records = [record for rank_records in gathered for record in rank_records]
asyncio.run(monitors.log_annotations(records))
def _tensor_to_floats(tensor: Tensor, decimals: int | None) -> list[float | None]:
"""Rounded like the record's own logprobs: the streams only ever colour an overlay,
and full-precision digits are the least compressible bytes a run writes."""
values = tensor.detach().to(dtype=torch.float32, device="cpu").reshape(-1).tolist()
if decimals is None:
return [value if math.isfinite(value) else None for value in values]
return [round(value, decimals) if math.isfinite(value) else None for value in values]
+29
View File
@@ -1,6 +1,7 @@
from pathlib import Path
from typing import TypedDict
import numpy as np
import torch
from jaxtyping import Bool, Float, Int
from torch import Tensor
@@ -29,6 +30,11 @@ class TensorMicroBatch(TypedDict):
env_names: list[str]
sequence_lengths: list[int]
# Per-sequence branch identity, parallel to sequence_lengths; None on
# synthetic data. "" / -1 mark an unknown sequence (e.g. a dummy batch).
trace_ids: list[str] | None
branch_indices: list[int] | None
# Batch level
lora_num_tokens: Int[Tensor, "n_loras"]
seq_lens: Int[Tensor, "segments"]
@@ -36,6 +42,10 @@ class TensorMicroBatch(TypedDict):
# MoE router replay
routed_experts: Int[Tensor, "batch seq layers topk"] | None
# Sampling-mask token ids per position, padded with -1 to the micro batch's
# maximum mask size. A row containing only -1 has no mask.
sampling_mask: Int[Tensor, "batch seq mask"] | None
# Generic multimodal kwargs — flat dict matching the model's forward
# signature (e.g. ``{"pixel_values": ..., "image_grid_thw": ...}`` for
# Qwen3-VL; ``{"pixel_values": ...}`` for Gemma3-VL). The trainer
@@ -118,10 +128,13 @@ class FakeDataLoader:
"temperatures": torch.ones(input_ids.shape[0]).unsqueeze(0),
"env_names": ["fake"] * input_ids.shape[0],
"sequence_lengths": sequence_lengths,
"trace_ids": None,
"branch_indices": None,
"loss_mask": loss_mask.unsqueeze(0),
"lora_num_tokens": torch.tensor([input_ids.shape[0]], dtype=torch.int32),
"seq_lens": torch.tensor(sequence_lengths, dtype=torch.long),
"routed_experts": None,
"sampling_mask": None,
"mm_kwargs": None,
"mm_token_type_ids": None,
"rl_weights": None,
@@ -147,10 +160,13 @@ class FakeDataLoader:
"temperatures": torch.ones(self.seq_len).unsqueeze(0),
"env_names": ["fake"] * self.seq_len,
"sequence_lengths": [self.seq_len],
"trace_ids": None,
"branch_indices": None,
"loss_mask": torch.ones(self.seq_len, dtype=torch.bool).unsqueeze(0),
"lora_num_tokens": torch.tensor([self.seq_len], dtype=torch.int32),
"seq_lens": torch.tensor([self.seq_len], dtype=torch.long),
"routed_experts": None,
"sampling_mask": None,
"mm_kwargs": None,
"mm_token_type_ids": None,
"rl_weights": None,
@@ -206,6 +222,16 @@ class DataLoader:
.to(torch.int32)
.unsqueeze(0)
)
sampling_mask = None
packed_sampling_mask = micro_batch.sampling_mask
if packed_sampling_mask is not None:
counts = np.frombuffer(packed_sampling_mask.counts, dtype=np.int32)
ids = np.frombuffer(packed_sampling_mask.ids, dtype=np.int32)
# Boolean assignment fills row-major, matching the flat concat order.
max_mask_size = max(int(counts.max()), 1) if counts.size else 1
padded = np.full((len(counts), max_mask_size), -1, dtype=np.int32)
padded[np.arange(max_mask_size)[None, :] < counts[:, None]] = ids
sampling_mask = torch.from_numpy(padded).unsqueeze(0)
return TensorMicroBatch(
input_ids=torch.tensor(micro_batch.input_ids, dtype=torch.long).unsqueeze(0),
position_ids=torch.tensor(micro_batch.position_ids, dtype=torch.long).unsqueeze(0),
@@ -218,6 +244,8 @@ class DataLoader:
temperatures=torch.tensor(micro_batch.temperatures, dtype=torch.float).unsqueeze(0),
env_names=micro_batch.env_names,
sequence_lengths=micro_batch.sequence_lengths,
trace_ids=micro_batch.trace_ids,
branch_indices=micro_batch.branch_indices,
# Single adapter: every token in the batch belongs to it (padding included).
lora_num_tokens=torch.tensor([len(micro_batch.input_ids)], dtype=torch.int32),
seq_lens=torch.tensor(micro_batch.seq_lens, dtype=torch.long),
@@ -226,6 +254,7 @@ class DataLoader:
if micro_batch.mm_token_type_ids is not None
else None,
routed_experts=routed_experts,
sampling_mask=sampling_mask,
rl_weights=torch.tensor(micro_batch.rl_weights, dtype=torch.float).unsqueeze(0)
if micro_batch.rl_weights is not None
else None,
+29 -6
View File
@@ -7,6 +7,7 @@ from jaxtyping import Bool, Float, Int, jaxtyped
from torch import Tensor
from prime_rl.configs.trainer import CustomLossConfig, IPOLossConfig, LossConfig
from prime_rl.trainer.models.layers.lm_head import sampling_replay_mask
from prime_rl.utils.utils import import_object
@@ -54,6 +55,27 @@ def selective_log_softmax(
return torch.gather(logprobs, dim=-1, index=index.unsqueeze(-1)).squeeze(-1)
@jaxtyped(typechecker=typechecker)
def selective_log_softmax_with_sampling_mask(
logits: Float[Tensor, "batch seq vocab"],
index: Int[Tensor, "batch seq"],
sampling_mask: Int[Tensor, "batch seq mask"],
) -> Float[Tensor, "batch seq"]:
"""Per-token logprobs with sampling-mask replay: positions with a usable
mask (see ``sampling_replay_mask``) get ``logits[index] -
logsumexp(logits[mask])``, others full-vocab. Non-replayed rows are zeroed
before the logsumexp so the unselected ``where`` branch can't emit NaN grads.
"""
full_logprobs = selective_log_softmax(logits, index)
replay = sampling_replay_mask(sampling_mask, index)
mask_logits = torch.gather(logits, -1, sampling_mask.clamp_min(0).long())
mask_logits = torch.where(sampling_mask >= 0, mask_logits, float("-inf"))
mask_logits = torch.where(replay.unsqueeze(-1), mask_logits, 0.0)
logz_masked = torch.logsumexp(mask_logits, dim=-1)
target_logits = torch.gather(logits, -1, index.unsqueeze(-1)).squeeze(-1)
return torch.where(replay, target_logits - logz_masked, full_logprobs)
@jaxtyped(typechecker=typechecker)
@torch.compile(dynamic=True)
def compute_entropy(shifted_logits: Float[Tensor, "batch seq vocab"]) -> Float[Tensor, "batch seq"]:
@@ -63,14 +85,15 @@ def compute_entropy(shifted_logits: Float[Tensor, "batch seq vocab"]) -> Float[T
return entropy
def shift_tensor_left(t: Float[Tensor, "batch seq"]) -> Float[Tensor, "batch seq"]:
"""Shifts the tensor one token to the left.
def shift_tensor_left(t: Tensor, pad_value: float = 0.0) -> Tensor:
"""Shifts the tensor one position to the left along dim 1.
Used to create labels from input_ids: labels[i] = input_ids[i+1].
The last position is padded with 0 (a valid token index) since this value
will be shifted off by shift_tensor_right and never used.
Used to create labels from input_ids: labels[i] = input_ids[i+1]. The last
position is padded with ``pad_value`` (0 is a valid token index but gets
shifted off by shift_tensor_right and never used). Works for [batch, seq]
labels and label-aligned [batch, seq, ...] fields like sampling_mask.
"""
return torch.cat([t[:, 1:], torch.full((t.shape[0], 1), 0, device=t.device, dtype=t.dtype)], dim=1)
return torch.cat([t[:, 1:], torch.full_like(t[:, :1], pad_value)], dim=1)
def shift_tensor_right(t: Float[Tensor, "batch seq"], pad_value: float | None = None) -> Float[Tensor, "batch seq"]:
-256
View File
@@ -1,256 +0,0 @@
import atexit
import json
import math
from collections.abc import Mapping, Sequence
from pathlib import Path
from typing import Any
import torch
from torch import Tensor
from prime_rl.configs.trainer import IPOLossConfig, TrainerConfig
from prime_rl.trainer.rl.loss import compute_importance_ratio_and_mismatch_kl
SCHEMA_VERSION = 1
class DisabledTokenExporter:
def export(self, *args: Any, **kwargs: Any) -> None:
return
def mark_stable(self) -> None:
return
def close(self) -> None:
return
class TokenExporter:
def __init__(
self,
output_dir: Path,
rank: int,
) -> None:
self.rank = rank
self.output_dir = output_dir / "token_exports"
self._closed = False
self._initialized_files: set[tuple[int, int]] = set()
self._sequences_by_file: dict[tuple[int, int], int] = {}
self._pending_stable_dirs: set[Path] = set()
atexit.register(self.close)
def export(
self,
step: int,
micro_step: int,
micro_batch: Mapping[str, Any],
model_output: Mapping[str, Tensor],
sequence_lengths: list[int],
loss_config: Any,
) -> None:
columns = _export_columns(micro_batch, model_output, loss_config)
_check_lengths(columns)
file_key = (step, self.rank)
start = 0
for micro_sequence_idx, length in enumerate(sequence_lengths):
raw_end = start + length
end = _trim_padding(columns, start, raw_end)
if end > start and any(columns["loss_mask"][start:end]):
self._write(
{
"schema_version": SCHEMA_VERSION,
"step": step,
"rank": self.rank,
"micro_step": micro_step,
"micro_sequence_idx": micro_sequence_idx,
"export_sequence_idx": self._sequences_by_file.get(file_key, 0),
"env_name": _first_non_empty(columns["env_names"][start:end]),
**_slice_columns(columns, start, end),
},
step,
)
self._sequences_by_file[file_key] = self._sequences_by_file.get(file_key, 0) + 1
start = raw_end
def close(self) -> None:
if self._closed:
return
self._closed = True
def mark_stable(self) -> None:
# The caller barriers first so a STABLE only lands after every rank flushed.
while self._pending_stable_dirs:
stable_dir = self._pending_stable_dirs.pop()
(stable_dir / "STABLE").touch()
def _export_dir(self, step: int) -> Path:
return self.output_dir / f"step_{step}"
def _export_file(self, step: int) -> Path:
if self._closed:
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
step_dir = self._export_dir(step)
try:
step_dir.mkdir(parents=True, exist_ok=True)
except FileExistsError:
if not step_dir.is_dir():
raise
return step_dir / f"rank_{self.rank}.jsonl"
def _write(self, record: dict[str, Any], step: int) -> None:
if self._closed:
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
file_key = (step, self.rank)
mode = "a" if file_key in self._initialized_files else "w"
export_file = self._export_file(step)
with export_file.open(mode, encoding="utf-8") as file:
file.write(json.dumps(record, separators=(",", ":"), allow_nan=False) + "\n")
self._initialized_files.add(file_key)
self._pending_stable_dirs.add(export_file.parent)
def setup_token_exporter(
config: TrainerConfig, parallel_dims: Any, world: Any, logger: Any
) -> TokenExporter | DisabledTokenExporter:
if not config.enable_token_export:
return DisabledTokenExporter()
if parallel_dims.cp_enabled and parallel_dims.world_mesh["cp"].get_local_rank() != 0:
return DisabledTokenExporter()
exporter = TokenExporter(config.output_dir, world.rank)
logger.info(f"Writing token exports under {exporter.output_dir}")
return exporter
def _export_columns(
micro_batch: Mapping[str, Any], model_output: Mapping[str, Tensor], loss_config: Any
) -> dict[str, list[Any]]:
token_ids = _tensor_to_ints(micro_batch["input_ids"])
seq_len = len(token_ids)
trainer_logprobs = model_output["logprobs"]
export_tensors = _compute_export_tensors(micro_batch, trainer_logprobs, loss_config)
return {
"token_ids": token_ids,
"position_ids": _tensor_to_ints(micro_batch["position_ids"]),
"loss_mask": _tensor_to_bools(micro_batch["loss_mask"]),
"advantages": _tensor_to_floats(micro_batch["advantages"]),
"inference_logprobs": _tensor_to_floats(micro_batch["inference_logprobs"]),
"trainer_logprobs": _tensor_to_floats(trainer_logprobs),
"entropy": _tensor_to_floats(model_output["entropy"]),
"mismatch_kl": _optional_tensor_to_floats(export_tensors["mismatch_kl"], seq_len),
"log_importance_ratio": _optional_tensor_to_floats(export_tensors["log_importance_ratio"], seq_len),
"importance_ratio": _optional_tensor_to_floats(export_tensors["importance_ratio"], seq_len),
"prob_delta": _optional_tensor_to_floats(export_tensors["prob_delta"], seq_len),
"is_masked": _optional_tensor_to_bools(export_tensors["is_masked"], seq_len),
"is_masked_high": _optional_tensor_to_bools(export_tensors["is_masked_high"], seq_len),
"is_masked_low": _optional_tensor_to_bools(export_tensors["is_masked_low"], seq_len),
# Component weight streams; ``None`` columns mean the defaults (rl 1.0
# on the loss mask, no ce/ref_kl component).
"rl_weights": _optional_tensor_to_floats(micro_batch.get("rl_weights"), seq_len),
"ce_weights": _optional_tensor_to_floats(micro_batch.get("ce_weights"), seq_len),
"ref_kl_weights": _optional_tensor_to_floats(micro_batch.get("ref_kl_weights"), seq_len),
"env_names": list(micro_batch["env_names"]),
}
def _compute_export_tensors(
micro_batch: Mapping[str, Any], trainer_logprobs: Tensor, loss_config: Any
) -> dict[str, Tensor | None]:
fields: dict[str, Tensor | None] = {
"log_importance_ratio": None,
"importance_ratio": None,
"mismatch_kl": None,
"prob_delta": None,
"is_masked": None,
"is_masked_high": None,
"is_masked_low": None,
}
# Ratio-based fields are meaningless when no token has sampling logprobs
# (e.g. pure CE batches distilling frozen-model tokens): no rl member
# (stream present but all-zero) and no ref_kl member.
rl_weights = micro_batch.get("rl_weights")
ref_kl_weights = micro_batch.get("ref_kl_weights")
no_rl = rl_weights is not None and not bool((rl_weights != 0).any())
no_ref_kl = ref_kl_weights is None or not bool((ref_kl_weights != 0).any())
if no_rl and no_ref_kl:
return fields
inference_logprobs = micro_batch["inference_logprobs"].to(trainer_logprobs.device)
loss_mask = micro_batch["loss_mask"].to(trainer_logprobs.device)
with torch.no_grad():
log_ratio, ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(trainer_logprobs, inference_logprobs)
prob_delta = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
fields["log_importance_ratio"] = log_ratio
fields["importance_ratio"] = ratio
fields["mismatch_kl"] = mismatch_kl
fields["prob_delta"] = prob_delta
if isinstance(loss_config, IPOLossConfig):
invalid_high = prob_delta > loss_config.eps
invalid_low = prob_delta < -loss_config.eps
fields["is_masked"] = loss_mask & (invalid_high | invalid_low)
fields["is_masked_high"] = loss_mask & invalid_high
fields["is_masked_low"] = loss_mask & invalid_low
return fields
def _tensor_to_ints(tensor: Tensor) -> list[int]:
return [int(value) for value in tensor.detach().cpu().reshape(-1).tolist()]
def _tensor_to_bools(tensor: Tensor) -> list[bool]:
return [bool(value) for value in tensor.detach().cpu().reshape(-1).tolist()]
def _tensor_to_floats(tensor: Tensor) -> list[float | None]:
values = tensor.detach().to(dtype=torch.float32, device="cpu").reshape(-1).tolist()
return [_json_float(value) for value in values]
def _optional_tensor_to_floats(tensor: Tensor | None, seq_len: int) -> list[float | None]:
if tensor is None:
return [None] * seq_len
return _tensor_to_floats(tensor)
def _optional_tensor_to_bools(tensor: Tensor | None, seq_len: int) -> list[bool | None]:
if tensor is None:
return [None] * seq_len
return _tensor_to_bools(tensor)
def _check_lengths(columns: Mapping[str, Sequence[Any]]) -> None:
lengths = {key: len(values) for key, values in columns.items()}
if len(set(lengths.values())) != 1:
raise ValueError(f"Token export fields must have aligned lengths, got {lengths}")
def _slice_columns(columns: Mapping[str, Sequence[Any]], start: int, end: int) -> dict[str, list[Any]]:
return {key: list(values[start:end]) for key, values in columns.items() if key != "env_names"}
def _trim_padding(columns: Mapping[str, Sequence[Any]], start: int, end: int) -> int:
env_names = columns["env_names"]
loss_mask = columns["loss_mask"]
while end > start and env_names[end - 1] == "" and not loss_mask[end - 1]:
end -= 1
return end
def _json_float(value: float | None) -> float | None:
if value is None:
return None
value = float(value)
if not math.isfinite(value):
return None
return value
def _first_non_empty(values: Sequence[str]) -> str | None:
for value in values:
if value:
return value
return None

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