Compare commits

...
Author SHA1 Message Date
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
64 changed files with 2571 additions and 1812 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
@@ -70,11 +70,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 +155,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")
+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
+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`.
+6 -3
View File
@@ -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
+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"
+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
-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
@@ -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
@@ -442,6 +481,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
@@ -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
@@ -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):
+4 -2
View File
@@ -27,7 +27,7 @@ dependencies = [
"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 +139,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 +252,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'" },
+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`.
+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)
+58 -4
View File
@@ -35,6 +35,7 @@ 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.clients import AdminClients, InferenceClient
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
@@ -49,7 +50,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 +90,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 +155,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 +275,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 +403,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 +426,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 +457,29 @@ 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
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 +488,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."""
+1 -2
View File
@@ -234,8 +234,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
+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
+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."""
+9
View File
@@ -277,6 +277,15 @@ 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 samples:
samples_by_trace[trace.id] = samples
+24 -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,7 @@ 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)),
)
)
if not samples:
+10 -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
@@ -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",
]
+61 -1
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,
@@ -541,6 +579,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 +596,7 @@ 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
for sample in bin_content.samples:
sample_len = len(sample.input_ids)
@@ -592,6 +634,10 @@ 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
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 +653,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,
@@ -733,6 +780,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
@@ -769,6 +818,15 @@ def _assert_token_arrays_aligned(micro_batch: MicroBatch) -> 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 +839,8 @@ 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
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)
+24 -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,6 +31,7 @@ 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,
@@ -42,11 +42,6 @@ from prime_rl.trainer.models import (
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
@@ -882,10 +877,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 +1096,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 +1328,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 +1346,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
@@ -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 = {
@@ -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
@@ -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":
+74 -8
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,6 +326,7 @@ 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
@@ -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)
@@ -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 = {
-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(
+18
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
@@ -36,6 +37,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
@@ -122,6 +127,7 @@ class FakeDataLoader:
"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,
@@ -151,6 +157,7 @@ class FakeDataLoader:
"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 +213,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),
@@ -226,6 +243,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"]:
+24 -1
View File
@@ -31,6 +31,7 @@ from prime_rl.trainer.rl.loss import (
compute_loss,
compute_importance_ratio_and_mismatch_kl,
selective_log_softmax,
selective_log_softmax_with_sampling_mask,
setup_rl_loss_fn,
shift_tensor_left,
shift_tensor_right,
@@ -377,6 +378,10 @@ def train(config: TrainerConfig):
# we could've gotten routed experts from the inference server, but we didn't enable router replay
routed_experts = None
sampling_mask = (
micro_batch["sampling_mask"].to("cuda") if micro_batch["sampling_mask"] is not None else None
)
# Multimodal kwargs are an opaque per-model dict (e.g.
# {"pixel_values": ..., "image_grid_thw": ...} for Qwen3-VL,
# just {"pixel_values": ...} for Gemma3-VL) — we move every
@@ -397,6 +402,10 @@ def train(config: TrainerConfig):
seq_lens = micro_batch["seq_lens"].to("cuda")
labels = shift_tensor_left(input_ids)
if sampling_mask is not None:
# Sampling masks ride at the sampled token's own position (like inference
# logprobs); shift to align with the label each position predicts.
sampling_mask = shift_tensor_left(sampling_mask, pad_value=-1)
seq_lens_are_pre_shard = False
@@ -417,6 +426,10 @@ def train(config: TrainerConfig):
labels = shard_for_cp(labels, cp_rank=cp_rank, cp_world_size=cp_size)
if routed_experts is not None and not defer_vlm_cp_to_model:
routed_experts = shard_for_cp(routed_experts, cp_rank=cp_rank, cp_world_size=cp_size)
if sampling_mask is not None:
# The LM head consumes masks after any deferred VLM sharding, so
# they must follow the label shard rather than the input shard.
sampling_mask = shard_for_cp(sampling_mask, cp_rank=cp_rank, cp_world_size=cp_size)
if config.model.lora:
lora_num_tokens = micro_batch["lora_num_tokens"].to("cuda")
@@ -436,6 +449,12 @@ def train(config: TrainerConfig):
if cp_enabled:
temperatures = shard_for_cp(temperatures, cp_rank=cp_rank, cp_world_size=cp_size)
if sampling_mask is not None:
assert sampling_mask.shape[:2] == labels.shape, (
f"sampling_mask shape {tuple(sampling_mask.shape)} is not aligned with "
f"labels shape {tuple(labels.shape)}"
)
# Forward pass with per-token temperatures
with maybe_record_function("forward"), maybe_activation_offloading(config.model.ac_offloading):
out = forward(
@@ -449,6 +468,7 @@ def train(config: TrainerConfig):
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
routed_experts=routed_experts,
sampling_mask=sampling_mask,
)
if out.get("logprobs") is None:
@@ -457,7 +477,10 @@ def train(config: TrainerConfig):
logits = out["logits"]
# Per-token temperature scaling: temperatures is [batch, seq], logits is [batch, seq, vocab]
scaled_logits = logits / temperatures.unsqueeze(-1)
out["logprobs"] = selective_log_softmax(scaled_logits, labels)
if sampling_mask is not None:
out["logprobs"] = selective_log_softmax_with_sampling_mask(scaled_logits, labels, sampling_mask)
else:
out["logprobs"] = selective_log_softmax(scaled_logits, labels)
out["entropy"] = compute_entropy(scaled_logits)
# else: FusedOutputLinear was used - logprobs already computed with per-token temperatures
@@ -9,6 +9,7 @@ from prime_rl.transports.batch.filesystem import (
from prime_rl.transports.batch.types import (
MicroBatch,
RoutedExperts,
SamplingMask,
TrainingSample,
)
from prime_rl.transports.batch.zmq import (
@@ -48,6 +49,7 @@ __all__ = [
"BatchSender",
"TrainingSample",
"MicroBatch",
"SamplingMask",
"RoutedExperts",
"setup_batch_sender",
"setup_batch_receiver",
+14
View File
@@ -18,6 +18,13 @@ class RoutedExperts(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tru
dtype: str
# Sampling masks for top-p/top-k replay: flat int32 token-id bytes plus an
# int32 count per token position (0 = no mask); len(ids) == 4 * counts.sum().
class SamplingMask(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
ids: bytes
counts: bytes
# Produced by the orchestrator's train sink; consumed in-process by
# ``prepare_batch``, which packs samples into per-rank ``MicroBatch``es.
class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
@@ -69,6 +76,10 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
# samples without live rl member tokens (the trainer raises otherwise).
advantages: list[float] | None = None
# Last field on purpose: array_like structs encode positionally, so appending
# keeps the wire layout of earlier fields stable across versions.
sampling_mask: SamplingMask | None = None
# Orchestrator -> Trainer
class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
@@ -97,3 +108,6 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
rl_weights: list[float] | None = None
ce_weights: list[float] | None = None
ref_kl_weights: list[float] | None = None
# See TrainingSample.sampling_mask; appended last for wire-layout stability.
sampling_mask: SamplingMask | None = None
+2 -4
View File
@@ -7,10 +7,10 @@ from typing import Literal
import torch
import torch.distributed as dist
import torch.distributed.nn as dist_nn
import torch.nn as nn
from ring_flash_attn import update_ring_flash_attn_params
from prime_rl.trainer.distributed.collectives import all_gather
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
CPStyle = Literal["ring", "ulysses"]
@@ -126,9 +126,7 @@ def shard_position_ids_for_cp(position_ids: torch.Tensor, cp_rank: int, cp_world
def gather_for_cp(t: torch.Tensor, cp_group: dist.ProcessGroup) -> torch.Tensor:
gathered_t = dist_nn.all_gather(t, group=cp_group)
return torch.cat(gathered_t, dim=1)
return all_gather(t, 1, cp_group)
def gather_for_cp_wo_grad(t: torch.Tensor, cp_world_size: int, cp_group: dist.ProcessGroup) -> torch.Tensor:
+93
View File
@@ -0,0 +1,93 @@
import pickle
from types import SimpleNamespace
import pytest
from prime_rl.evals.ckpt import CheckpointManager
from prime_rl.orchestrator.eval_source import EvalSource
def _task(key: str) -> SimpleNamespace:
return SimpleNamespace(key=key, hash=key)
def _env(name: str, task_keys: list[str], *, interval: int = 1) -> SimpleNamespace:
return SimpleNamespace(
name=name,
examples=[_task(key) for key in task_keys],
config=SimpleNamespace(interval=interval),
)
def _eval_config() -> SimpleNamespace:
return SimpleNamespace(skip_first_step=False)
def _queued_tasks(eval_source: EvalSource) -> list[tuple[str, str, int | None]]:
return [(request.env_name, request.task.key, request.source_index) for request in eval_source.queue]
def test_eval_source_cursor_advances_only_over_completed_prefix() -> None:
eval_source = EvalSource(
[_env("math", ["m0", "m1"]), _env("code", ["c0", "c1"])],
_eval_config(),
)
assert eval_source.trigger(0) == ["math", "code"]
assert _queued_tasks(eval_source) == [
("math", "m0", 0),
("code", "c0", 1),
("math", "m1", 2),
("code", "c1", 3),
]
assert eval_source.mark_completed(1) is False
assert eval_source.cursor == 0
assert eval_source.mark_completed(3) is False
assert eval_source.cursor == 0
assert eval_source.mark_completed(0) is True
assert eval_source.cursor == 2
assert eval_source.mark_completed(2) is True
assert eval_source.cursor == 4
def test_eval_checkpoint_saves_only_cursor_and_resume_skips_completed_prefix(tmp_path) -> None:
eval_envs = [_env("math", ["m0", "m1"]), _env("code", ["c0", "c1"])]
eval_source = EvalSource(eval_envs, _eval_config())
eval_source.load_state_dict({"cursor": 2})
assert eval_source.trigger(0) == ["math", "code"]
assert _queued_tasks(eval_source) == [
("math", "m1", 2),
("code", "c1", 3),
]
assert eval_source.triggered_task_count("math", 0) == 1
assert eval_source.triggered_task_count("code", 0) == 1
ckpt = CheckpointManager(tmp_path)
ckpt.save(eval_source)
with (ckpt.get_ckpt_path(2) / "progress.pt").open("rb") as f:
assert pickle.load(f) == {"cursor": 2}
assert ckpt.latest_step() == 2
restored_source = EvalSource(eval_envs, _eval_config())
ckpt.load(2, restored_source)
assert restored_source.state_dict() == {"cursor": 2}
def test_eval_checkpoint_rejects_step_cursor_mismatch(tmp_path) -> None:
eval_source = EvalSource([_env("math", ["m0"])], _eval_config())
eval_source.load_state_dict({"cursor": 1})
ckpt = CheckpointManager(tmp_path)
ckpt.save(eval_source)
restored_source = EvalSource([_env("math", ["m0"])], _eval_config())
with pytest.raises(ValueError, match="contains cursor 1, expected step 2"):
ckpt.load(2, restored_source, path=ckpt.get_ckpt_path(1))
+65 -5
View File
@@ -1,3 +1,4 @@
import os
from pathlib import Path
from typing import Annotated, Literal
@@ -356,6 +357,54 @@ def test_env_algo_overrides_top_level():
)
def test_policy_sources_accept_different_top_p_values():
with pytest.warns(UserWarning, match="defaulting top_k"):
config = OrchestratorConfig.model_validate(
{
"renderer": {"name": "qwen3"},
"train": {
"source": [
{
"name": "top-p-95",
"env": {"taskset": {"id": "reverse-text"}},
"sampling": {"top_p": 0.95},
},
{
"name": "top-p-97",
"env": {"taskset": {"id": "reverse-text"}},
"sampling": {"top_p": 0.97},
},
]
},
}
)
assert [source.sampling.top_k for source in config.train.source] == [512, 512]
def test_policy_sources_reject_mixed_top_k_capture():
with pytest.warns(UserWarning, match="defaulting top_k"):
with pytest.raises(ValidationError, match="cannot mix top_k > 0 and top_k = -1"):
OrchestratorConfig.model_validate(
{
"renderer": {"name": "qwen3"},
"train": {
"source": [
{
"name": "truncated",
"env": {"taskset": {"id": "reverse-text"}},
"sampling": {"top_p": 0.95},
},
{
"name": "untruncated",
"env": {"taskset": {"id": "reverse-text"}},
},
]
},
}
)
def test_trainer_enable_token_export_cli_flag():
assert not cli(TrainerConfig, args=[]).enable_token_export
assert cli(TrainerConfig, args=["--enable-token-export"]).enable_token_export
@@ -451,11 +500,6 @@ def test_trainer_rejects_vlm_cp_with_ring():
TrainerConfig.model_validate(config)
def test_selective_activation_checkpointing_requires_custom_impl():
with pytest.raises(ValidationError, match="Selective activation checkpointing requires model.impl='custom'"):
TrainerModelConfig.model_validate({"impl": "hf", "ac": {"mode": "selective"}})
def test_shared_model_name_propagates_to_subconfigs():
model_name = "PrimeIntellect/test-model"
config = RLConfig.model_validate(
@@ -832,3 +876,19 @@ def test_explicit_inference_parser_wins_over_auto():
)
assert config.inference is not None
assert config.inference.vllm.tool_call_parser == "hermes"
def test_combined_replay_uses_v2_runner(monkeypatch):
from prime_rl.inference.server import setup_vllm_env
monkeypatch.delenv("VLLM_USE_V2_MODEL_RUNNER", raising=False)
config = InferenceConfig(
enable_return_sampling_mask=True,
vllm={"enable_return_routed_experts": True},
)
setup_vllm_env(config)
assert config.enable_return_sampling_mask is True
assert config.vllm.enable_return_routed_experts is True
assert os.environ["VLLM_USE_V2_MODEL_RUNNER"] == "1"
+105 -37
View File
@@ -1,49 +1,117 @@
import torch.nn as nn
import pytest
import torch
from torch import nn
from torch.utils.checkpoint import CheckpointPolicy, SelectiveCheckpointContext
from prime_rl.trainer.models.layers.checkpointing import (
get_supported_targets,
set_selective_activation_checkpointing,
from prime_rl.configs.trainer import ActivationCheckpointConfig
from prime_rl.trainer.activation_checkpointing import (
_mandatory_checkpoint_policy,
_selective_checkpoint_policy,
get_activation_checkpoint_wrapper,
)
_PATCHED_METHODS_ATTR = "_prime_rl_selective_ac_patched_methods"
from prime_rl.trainer.models.layers.moe import MoE, TokenChoiceTopKRouter
class DummySelfAttention(nn.Module):
def attn_projections(self, hidden_states, position_embeddings=None):
return hidden_states
class IdentityExperts(nn.Module):
num_experts = 2
token_group_alignment = 1
def output_proj(self, attn_output):
return attn_output
def forward(self, hidden_states):
return hidden_states
def forward(self, x: torch.Tensor, _token_counts: torch.Tensor) -> torch.Tensor:
return x
class DummySlidingAttentionLayer(nn.Module):
def __init__(self):
super().__init__()
self.self_attn = DummySelfAttention()
self.attention_type = "sliding_attention"
def test_selective_policy_saves_default_and_custom_targets():
context = SelectiveCheckpointContext(is_recompute=False)
assert _selective_checkpoint_policy(context, torch.ops.aten.topk.default) is CheckpointPolicy.MUST_SAVE
assert (
_selective_checkpoint_policy(context, torch.ops.aten._scaled_dot_product_flash_attention.default)
is CheckpointPolicy.MUST_SAVE
)
assert _selective_checkpoint_policy(context, torch.ops.aten.mm.default) is CheckpointPolicy.MUST_SAVE
assert _selective_checkpoint_policy(context, torch.ops.aten.addmm.default) is CheckpointPolicy.MUST_SAVE
assert _selective_checkpoint_policy(context, torch.ops.aten.bmm.default) is CheckpointPolicy.MUST_SAVE
assert _selective_checkpoint_policy(context, torch.ops.aten._grouped_mm.default) is CheckpointPolicy.MUST_SAVE
assert (
_selective_checkpoint_policy(context, torch.ops.prime_rl_collectives.all_to_all_single_equal.default)
is CheckpointPolicy.MUST_SAVE
)
assert (
_selective_checkpoint_policy(context, torch.ops.prime_rl_collectives.mxfp8_all_to_all.default)
is CheckpointPolicy.MUST_SAVE
)
assert _selective_checkpoint_policy(context, torch.ops.aten.silu.default) is CheckpointPolicy.PREFER_RECOMPUTE
custom_targets = frozenset({"aten::silu", "prime_rl_collectives"})
assert (
_selective_checkpoint_policy(context, torch.ops.aten.silu.default, targets=custom_targets)
is CheckpointPolicy.MUST_SAVE
)
assert (
_selective_checkpoint_policy(
context,
torch.ops.prime_rl_collectives.all_to_all_single_equal.default,
targets=custom_targets,
)
is CheckpointPolicy.MUST_SAVE
)
assert (
_selective_checkpoint_policy(context, torch.ops.aten.mm.default, targets=custom_targets)
is CheckpointPolicy.PREFER_RECOMPUTE
)
assert (
_selective_checkpoint_policy(context, torch.ops.aten.topk.default, targets=custom_targets)
is CheckpointPolicy.MUST_SAVE
)
class DummyMamba(nn.Module):
def forward(self, hidden_states):
return hidden_states
@pytest.mark.parametrize("mode", ["full", "selective"])
def test_checkpoint_records_moe_routing_once(mode):
moe = MoE(
router=TokenChoiceTopKRouter(
dim=4,
num_experts=2,
top_k=1,
score_func="softmax",
route_norm=False,
route_scale=1.0,
),
experts=IdentityExperts(),
shared_expert=None,
score_before_experts=True,
load_balance_coeff=0.1,
)
checkpointed = get_activation_checkpoint_wrapper(ActivationCheckpointConfig(mode=mode))(moe)
hidden_states = torch.randn(1, 3, 4, requires_grad=True)
output = checkpointed(hidden_states)
tokens_after_forward = moe.tokens_per_expert.clone()
confidence_after_forward = moe.routing_confidence_sum.clone()
output.sum().backward()
assert tokens_after_forward.sum() == 3
torch.testing.assert_close(moe.tokens_per_expert, tokens_after_forward)
torch.testing.assert_close(moe.routing_confidence_sum, confidence_after_forward)
assert hidden_states.grad is not None
class DummyMambaLayer(nn.Module):
def __init__(self):
super().__init__()
self.mamba = DummyMamba()
def test_mandatory_policy_only_retains_non_replayable_ops():
context = SelectiveCheckpointContext(is_recompute=False)
def test_get_supported_targets_treats_mamba_as_linear_attention():
assert get_supported_targets(DummyMambaLayer()) == frozenset({"norm", "linear_attn"})
def test_sliding_attention_linear_attn_subsumes_attn_proj_hooks():
layer = DummySlidingAttentionLayer()
set_selective_activation_checkpointing(layer, ["attn_proj", "linear_attn"])
assert getattr(layer.self_attn, _PATCHED_METHODS_ATTR) == frozenset({"forward"})
assert _mandatory_checkpoint_policy(context, torch.ops.aten.topk.default) is CheckpointPolicy.MUST_SAVE
assert (
_mandatory_checkpoint_policy(context, torch.ops.prime_rl.record_moe_routing_statistics.default)
is CheckpointPolicy.MUST_SAVE
)
assert (
_mandatory_checkpoint_policy(context, torch.ops.prime_rl_collectives.all_to_all_single_equal.default)
is CheckpointPolicy.PREFER_RECOMPUTE
)
assert (
_mandatory_checkpoint_policy(context, torch.ops.prime_rl_collectives.mxfp8_all_to_all.default)
is CheckpointPolicy.PREFER_RECOMPUTE
)
assert (
_mandatory_checkpoint_policy(context, torch.ops.aten._scaled_dot_product_flash_attention.default)
is CheckpointPolicy.PREFER_RECOMPUTE
)
Generated
+212 -468
View File
File diff suppressed because it is too large Load Diff