Compare commits

...
Author SHA1 Message Date
JannikStandGitHub f87ebcc239 improvement(docker): bundle AWS EFA libfabric + aws-ofi-nccl (#3448)
## Summary
- Bundles libfabric + the aws-ofi-nccl NCCL plugin into the image via
AWS's official installer, so NCCL can find the OFI plugin at runtime
instead of silently falling back to sockets
- Inert by default — only takes effect where a deployment's config
points `LD_LIBRARY_PATH` at it

<!-- CURSOR_SUMMARY -->
---

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

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

## Runtime contract

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

## Configuration

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

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

## Validation

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

## Hardware boundary

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

<!-- CURSOR_SUMMARY -->
---

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

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

## Verification

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

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes distributed data partitioning and checkpointed iterator state,
which can silently skew training if wrong; behavior is covered by
expanded unit tests but affects core SFT loops.
> 
> **Overview**
> Fixes **incorrect SFT data sharding and stale progress metrics** when
using multiple DataLoader workers and/or context-parallel (CP) ranks.
> 
> **Sharding:** `data_rank` / `data_world_size` are now derived from
**DP rank only** (`rank // non_dp_size`), so CP ranks see the same
samples while DP ranks stay distinct. Rank/worker identity is resolved
in **`__iter__` via `_setup_world_info()`** instead of at dataset
construction, so worker processes get the right shard after fork.
> 
> **Progress & checkpoints:** `CatDataset` state now stores and restores
per-source **`num_samples` / `num_tokens`**. New
**`get_dataset_progress()`** reads worker snapshots, uses the **furthest
worker** for `step`/`epoch`, and **sums** counters across workers. SFT
training logs **`progress/*`** from the dataloader instead of the
main-process dataset object (which stayed at zero after resume).
> 
> **Tests:** Dataloader tests drop the heavy tokenizer/GPU mark, add a
shared dummy renderer, and cover multi-rank/worker sharding, resume, CP
replication, and monotonic progress under uneven packing.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
30f7de1d229f8e88e0f334be6b8baaa7d2dccf14. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-31 13:00:38 -07:00
Mika SenghaasandGitHub 3fc28ddfb3 fix: remove dispatch failures from summaries (#3432)
## Summary

- Remove dispatch-failure rates from per-step success logs.
- Exclude dispatch-failure metrics from curated W&B overview panels.
- Keep raw dispatch-failure metrics unchanged.

## Verification

Before: training success lines and W&B overview panels showed
dispatch-failure rates.

After: both summaries omit dispatch failures while the raw metrics
remain available.

- `uv run ruff check src/prime_rl/orchestrator/orchestrator.py
src/prime_rl/monitors/wandb/overview.py`
- `UV_PROJECT_ENVIRONMENT=/home/ubuntu/prime-rl/.venv uv run --no-sync
pytest tests/unit/orchestrator/test_metrics.py`

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Presentation-only changes to logs and W&B overview panels; dispatch
failure metrics and pipeline handling are unchanged.
> 
> **Overview**
> **Dispatch failure rates are removed from operator-facing train
summaries** while leaving underlying W&B metrics intact.
> 
> The per-step **Step …** success log (aggregate and per-env `╰─` lines)
no longer computes or prints **Dispatch Failure**; multi-env breakdowns
also stop folding `batch.failures` into env name lists. Docstrings now
describe window metrics as **Error**, **Cancelled**, and **Ratio** only,
and clarify that cancellations are pipeline decisions rather than
rollout failures.
> 
> The curated W&B **overview** saved view drops
`all/dispatch_failure/mean` from `COMMON_METRICS`, so the default
dashboard panels no longer highlight dispatch-failure rate alongside
turns, tokens, and error/truncation signals. `dispatch_failure_metrics`
in `finalize_train_batch` is unchanged, so raw
`train/*/all/dispatch_failure/*` series remain available outside the
overview.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
db0d538c93bbcfa9e764e9f9f295dca9c1b45ab3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-28 22:06:11 -07:00
Mika SenghaasandGitHub eaad03b9df chore: bump vllm to 0.28.0 (#3430)
## Summary

Builds on the CUDA 13, Torch 2.13, and vLLM 0.27.1 stack from #3425.

- Bump vLLM to 0.28.0. Torch stays at 2.13.0+cu130; only the wheel pins
move. vLLM 0.28 requires `nvidia-cutlass-dsl == 4.6.2` and
`quack-kernels == 0.6.4`, so the override pin and its dependency
metadata move with it.
- Drop patches obsoleted by the pinned release (reviewed the
0.27.0/0.27.1/0.28.0 release notes and diffed the patched vLLM sources
between 0.27.1 and 0.28.0):
- `monkey_patch_harmony_stop_token_propagation` — fixed upstream by
vllm#35076 (in the release since 0.27.1).
- `monkey_patch_fp32_router_logits` — vLLM reads `moe_router_dtype` off
the HF config (vllm#47410) and forces fp32 routing for GLM-5.x.
`inference.enable_fp32_router_logits` keeps its name and default but now
injects `hf_overrides = {"moe_router_dtype": "float32"}` instead of
patching `DeepseekV2MoE`.
- `PrimeRlServingTokens` — upstream `serve_tokens` now handles DP-rank
header routing, server-side `max_tokens` defaulting, and `usage`
reporting (cached tokens surface via `--enable-prompt-tokens-details`,
which the launcher now sets). The subclass shrinks to the compact
`routed_experts` export and the `kv_transfer_params` engine bridge
(vllm#42644 merged 6h after the 0.28.0 cut — drop at the next bump).
- Follow vLLM's own V1/V2 model runner resolution instead of pinning V1
globally. vLLM resolves non-MoE generate models (plus an arch allowlist)
to the V2 runner. Only routed-experts capture still requires V1 (the V2
runner silently never captures routing decisions): the launcher pins
`VLLM_USE_V2_MODEL_RUNNER=0` when `enable_return_routed_experts` is set,
and the NIXL routed-experts patch rejects a V2 resolution explicitly.

Patches verified still needed on 0.28.0 (targets byte-identical or issue
still open): kv-xfer freed-request assert (vllm#46240), qwen3_coder
param newline trim, minimax-m2 think-end passthrough, TokenizeParams
validation, DP coordinator startup timeout, LoRA expert-key acceptance
(vllm#38522 closed unmerged), Qwen3.5-MoE 2D LoRA format, online-fp8
Parameter cast, nano_v3 reasoning parser, fp32 lm_head (kept over vLLM's
`head_dtype=float32`, which upcasts the weight per forward instead of
using an fp32-out GEMM), chat routed-experts strip.

Known 0.28 caveats:
- NIXL connector handshake version bumps 5 → 7: a 0.27 and a 0.28 engine
refuse to transfer KV to each other, so rolling P/D upgrades need a full
pool restart.
- vllm#50465 (batch-sharded sampling, merged after 0.28.0) silently
drops sampling masks under TP; re-check vllm#53826 before the next bump.

Validated on GLM-4.5-Air SWE

<img width="882" height="241" alt="Screenshot 2026-08-28 at 9 08 56 PM"
src="https://github.com/user-attachments/assets/d1af34c4-a80a-410b-bcdc-afdf0ffabd81"
/>

## Verification

- `uv lock --check`
- `uv run --frozen pytest -q tests/unit/test_configs.py
tests/unit/inference` (137 passed)
- Ruff check and format checks for the changed Python files
- E2E reverse-text RL on this branch (Qwen3-0.6B-Reverse-Text-SFT, 20
steps, 1 trainer + 1 inference GPU, NCCL broadcast): reward 0.18 → 0.81,
0% rollout errors, 100% trainable, mismatch KL 0.003–0.005. The engine
ran the V2 model runner (vLLM's default for this model) with the fp32
lm_head patch active. W&B: `reverse-text/reverse-text-vllm028-smoke`.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> A broad inference dependency bump plus behavioral changes to MoE
routing, model-runner selection, and P/D KV transfer bridging;
misconfiguration could affect logprob fidelity, router replay, or
disaggregated decode performance until upstream fixes land.
> 
> **Overview**
> Upgrades the GPU inference stack from **vLLM 0.27.1 to 0.28.0**, with
matching lockfile and wheel pins (`nvidia-cutlass-dsl` 4.6.2,
`quack-kernels` 0.6.4).
> 
> **Config / launcher:** `to_namespace()` now defaults
**`enable_prompt_tokens_details`** so `/inference/v1/generate` `usage`
includes cached prompt tokens for router billing.
**`enable_fp32_router_logits`** no longer sets `additional_config`; it
injects **`hf_overrides.moe_router_dtype = "float32"`** so vLLM’s native
MoE routing path applies. **`VLLM_USE_V2_MODEL_RUNNER=0`** is set only
when **`enable_return_routed_experts`** is on (V2 never captures routed
experts); other models follow vLLM’s V1/V2 resolution.
> 
> **Removed patches** superseded by 0.28: harmony stop-token merge on
chat completions, `DeepseekV2MoE` fp32 router monkey-patch, and most of
the custom `ServingTokens` fork (DP routing, `max_tokens` defaulting,
manual `usage` assembly). **`PrimeRlServingTokens`** now delegates to
upstream `serve_tokens` except for **`kv_transfer_params` →
`sampling_params.extra_args`** (PD disagg until vllm#42644 ships) and
compact **`routed_experts`** post-processing.
> 
> **Other:** NIXL routed-experts guard uses
**`config.use_v2_model_runner`** instead of the env flag. Unit tests for
deleted helpers are trimmed; post-process test asserts `usage` is
preserved from upstream responses.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
77c9264df8bb12af89eda7c238e2415e9a339857. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-28 21:57:26 -07:00
49 changed files with 2158 additions and 2483 deletions
+33
View File
@@ -167,6 +167,34 @@ RUN find /usr/local/cuda-13.0/targets/*/lib \
-o -name 'libnvjpeg*' -o -name 'libnvblas*' \) -delete \
&& find /usr/local/cuda-13.0 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
# 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. --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. Same base OS as the runtime stage
# below for glibc/rdma-core ABI compatibility.
FROM nvidia/cuda:13.0.1-base-ubuntu24.04 AS efa-installer
ENV DEBIAN_FRONTEND=noninteractive
ARG EFA_INSTALLER_VERSION=1.47.0
# One RUN: efa_installer.sh apt-get installs its own deps (pciutils,
# libnl-3-200, tcl, ...) internally, so the package index has to survive
# until after it runs. Purging /var/lib/apt/lists/* only at the very end
# (not between the curl/tar deps and the installer invocation) keeps that
# available.
RUN apt-get update && apt-get install -y --no-install-recommends \
curl 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/*
# Runtime image
FROM nvidia/cuda:13.0.1-base-ubuntu24.04
@@ -239,6 +267,11 @@ COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packa
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so /app/.venv/lib/python3.12/site-packages/
COPY --from=builder /opt/ucx /opt/ucx
# EFA userspace stack from the dedicated stage above. Not added to
# LD_LIBRARY_PATH here -- deployment configs opt into that only where
# EFA is actually available, so this is inert everywhere else.
COPY --from=efa-installer /opt/amazon /opt/amazon
# Copy and set up entrypoint script
COPY --chown=appuser:appuser scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
RUN chmod +x /app/docker-entrypoint.sh
@@ -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
+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
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",
@@ -462,7 +462,7 @@ class InferenceConfig(BaseConfig):
"""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."""
enable_fp32_router_logits: bool = True
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x) by setting ``out_dtype=float32`` on the gate: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented as a monkey-patch over vLLM's DeepseekV2MoE, activated by setting ``additional_config["fp32_router_logits"] = True`` on the vLLM config."""
"""Emit fp32 MoE router logits: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented natively by vLLM, which reads ``moe_router_dtype`` off the HF config — this flag injects ``hf_overrides = {"moe_router_dtype": "float32"}`` (GLM-5.x gets fp32 routing regardless)."""
# Launcher-only fields
@@ -607,6 +607,18 @@ class InferenceConfig(BaseConfig):
if not hasattr(namespace, "logprobs_mode"):
namespace.logprobs_mode = "processed_logprobs"
# Always surface cached prompt tokens in `usage` — the router's
# cache-discount billing counters parse them off /inference/v1/generate.
if "enable_prompt_tokens_details" not in extra_fields:
namespace.enable_prompt_tokens_details = True
# vLLM's DeepseekV2-family (and transformers-backend MoE) gates read
# `moe_router_dtype` off the HF config to pick the router logits dtype.
if self.enable_fp32_router_logits:
hf_overrides = getattr(namespace, "hf_overrides", None) or {}
hf_overrides.setdefault("moe_router_dtype", "float32")
namespace.hf_overrides = hf_overrides
kv_transfer_config = self.build_kv_transfer_config()
if kv_transfer_config is not None:
namespace.kv_transfer_config = kv_transfer_config
@@ -616,8 +628,6 @@ class InferenceConfig(BaseConfig):
additional_config = getattr(namespace, "additional_config", None) or {}
if self.enable_fp32_lm_head:
additional_config["fp32_lm_head"] = True
if self.enable_fp32_router_logits:
additional_config["fp32_router_logits"] = True
if additional_config:
namespace.additional_config = additional_config
@@ -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):
+12 -10
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.11",
"pybase64>=1.4.2",
"orjson>=3.10",
"pandas>=2.0",
@@ -53,7 +53,7 @@ gpu = [
"torchvision ; sys_platform == 'linux'",
"torchaudio ; sys_platform == 'linux'",
"torchdata>=0.11.0 ; sys_platform == 'linux'",
"vllm>=0.27.1 ; sys_platform == 'linux'",
"vllm>=0.28.0 ; sys_platform == 'linux'",
"mooncake-transfer-engine>=0.3.10.post2 ; sys_platform == 'linux'",
"ring-flash-attn>=0.1.8 ; sys_platform == 'linux'",
"torchtitan ; sys_platform == 'linux'",
@@ -139,10 +139,12 @@ 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.27.1 requires quack-kernels 0.6.1. It requires this exact CUTLASS version.
# 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.
"nvidia-cutlass-dsl==4.6.0",
"nvidia-cutlass-dsl==4.6.2",
"transformers==5.6.2",
"torch>=2.13.0",
"openenv-core",
@@ -199,10 +201,10 @@ requires-dist = ["nixl-cu13==0.10.1"]
# so resolve that variant without installing both runtime packages.
[[tool.uv.dependency-metadata]]
name = "nvidia-cutlass-dsl"
version = "4.6.0"
version = "4.6.2"
requires-dist = [
"nvidia-cutlass-dsl-libs-base==4.6.0",
"nvidia-cutlass-dsl-libs-cu13==4.6.0",
"nvidia-cutlass-dsl-libs-base==4.6.2",
"nvidia-cutlass-dsl-libs-cu13==4.6.2",
]
[tool.uv.exclude-newer-package]
@@ -250,14 +252,14 @@ 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'" },
]
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.27.1/vllm-0.27.1-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.27.1/vllm-0.27.1-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
deep-ep = [
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
+5 -68
View File
@@ -207,7 +207,6 @@ def monkey_patch_minimax_m2_think_end_passthrough():
def monkey_patch_return_routed_experts_with_nixl_connector():
from vllm import envs
from vllm.config.vllm import VllmConfig
from vllm.logger import init_logger
@@ -233,8 +232,11 @@ def monkey_patch_return_routed_experts_with_nixl_connector():
if config.parallel_config.pipeline_parallel_size > 1:
raise ValueError("--enable-return-routed-experts is incompatible with pipeline parallelism (PP > 1).")
if envs.VLLM_USE_V2_MODEL_RUNNER:
raise ValueError("VLLM_USE_V2_MODEL_RUNNER does not yet support: routed experts capture")
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)."
)
# vLLM rejects every KV connector, but our P/D path uses NIXL and
# stitches prefill/decode routed experts in the router. CPU KV offload
@@ -609,32 +611,6 @@ def monkey_patch_minimax_m2_for_lora():
)
def monkey_patch_harmony_stop_token_propagation():
"""Fix: vLLM doesn't merge harmony stop tokens into per-request SamplingParams.
The harmony mode sets stop_token_ids (including <|call|> and <|return|>) in
default_sampling_params at server init, but ChatCompletionRequest.to_sampling_params()
ignores them, using only self.stop_token_ids (which defaults to []).
Upstream: https://github.com/vllm-project/vllm/issues/22519
"""
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
_original_to_sampling_params = ChatCompletionRequest.to_sampling_params
def _patched_to_sampling_params(self, max_tokens, default_sampling_params):
params = _original_to_sampling_params(self, max_tokens, default_sampling_params)
# Merge harmony stop tokens from default_sampling_params
default_stop_ids = default_sampling_params.get("stop_token_ids", [])
if default_stop_ids:
existing = set(params.stop_token_ids or [])
merged = list(existing | set(default_stop_ids))
params.stop_token_ids = merged
return params
ChatCompletionRequest.to_sampling_params = _patched_to_sampling_params
def monkey_patch_no_moe_lora():
"""This disables LoRA for MoE layers and makes them pick better kernels.
@@ -717,45 +693,6 @@ def monkey_patch_fp32_lm_head():
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
def monkey_patch_fp32_router_logits():
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x glm_moe_dsa).
vLLM's DeepseekV2MoE gate is a GateLinear with a bf16 weight and no out_dtype,
so router logits are rounded to bf16 before expert scoring. GLM-5.x was trained
with fp32 routing (Megatron ``--moe-router-dtype fp32``); upstream now runs its
gate fully in fp32 (vllm-project/vllm#47410, not in the pinned release).
Setting ``out_dtype=float32`` routes the gate through GateLinear's cuBLAS
bf16xbf16->fp32 tier: same GEMM, but the fp32 accumulator is written out
unrounded. Unlike the upstream PR, the gate weight stays bf16, so the LoRA
Triton kernel dtype assert and the bf16 weight-broadcast path are unaffected.
Activated by ``additional_config["fp32_router_logits"] = True``; the launcher
sets this when ``inference.enable_fp32_router_logits`` is set. The flag is read
at module construction, where vLLM guarantees a ``set_current_vllm_config()``
context. No-op if something else already set an out_dtype (e.g. the ROCm AITER
branch, whose kernel wants matching dtypes).
"""
import torch
from vllm.config import get_current_vllm_config
from vllm.logger import init_logger
from vllm.model_executor.models.deepseek_v2 import DeepseekV2MoE
logger = init_logger(__name__)
_original_init = DeepseekV2MoE.__init__
def _patched_init(self, *args, **kwargs):
_original_init(self, *args, **kwargs)
additional_config = get_current_vllm_config().additional_config or {}
if not additional_config.get("fp32_router_logits", False):
return
if self.gate.out_dtype is None:
self.gate.set_out_dtype(torch.float32)
DeepseekV2MoE.__init__ = _patched_init
logger.info("Installed fp32 router logits patch (self-gates on additional_config['fp32_router_logits']).")
def monkey_patch_dp_coordinator_startup_timeout():
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 120s.
+5 -5
View File
@@ -10,11 +10,11 @@ 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")
# Force the V1 GPU model runner. vLLM routes Llama/Mistral/Qwen3 plus MoE archs
# (DeepseekV2, Qwen2Moe, GraniteMoe) to the V2 runner by default, but V2 doesn't
# support routed-experts capture (the NIXL PD path rejects it). setdefault so it
# stays overridable.
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
# 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")
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
# grammar-constrains generation (xgrammar structural tags) for tool_choice
+1 -5
View File
@@ -20,17 +20,13 @@ from prime_rl.utils.logger import get_logger
logger = get_logger()
from prime_rl.inference.patches import (
monkey_patch_dp_coordinator_startup_timeout,
monkey_patch_harmony_stop_token_propagation,
monkey_patch_nano_v3_reasoning_parser,
monkey_patch_strip_routed_experts_from_chat,
monkey_patch_tokenize_params_validation,
)
# NOTE: Fix harmony stop token propagation for GPT-OSS models
# Upstream issue still open: https://github.com/vllm-project/vllm/issues/22519
monkey_patch_harmony_stop_token_propagation()
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
# Still needed in vLLM 0.20 — upstream rejects prompt_len > max_model_len - max_tokens
# Still needed in vLLM 0.28 — upstream rejects prompt_len > max_model_len - max_tokens
monkey_patch_tokenize_params_validation()
# NOTE: Register Nano V3 reasoning parser so configs can use
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
+31 -271
View File
@@ -3,22 +3,20 @@
vLLM ships a generic tokens-in / tokens-out handler at
``vllm.entrypoints.scale_out.token_in_token_out.serving.ServingTokens`` that covers
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs,
priority, ``data_parallel_rank`` header routing and server-side ``max_tokens``
defaulting. We subclass it for the bits still missing from the upstream handler:
priority, ``data_parallel_rank`` header routing, server-side ``max_tokens``
defaulting and ``usage`` reporting. We subclass it for the bits still missing
from the upstream handler:
1. ``data_parallel_rank`` routing — read from the ``X-data-parallel-rank``
header and forwarded to ``engine_client.generate``. Upstream ``ServingTokens``
now does this too; we keep the equivalent path for the DP-replicated
inference servers prime-RL runs.
1. Compact ``routed_experts`` export — when the engine emits routing
decisions, surface them as ``{data, shape, start, dtype}`` base64 raw-byte
objects (the form the PD router can merge and the renderers parse) instead
of upstream's single ``.npy`` base64 string.
2. Compact ``routed_experts`` export — when the engine emits routing
decisions, surface them as base64 raw-byte payloads without requiring a vLLM
source fork.
3. Server-side ``max_tokens`` defaulting — upstream ``ServingTokens`` now applies
this itself (via ``GenerateRequest.is_sampling_param_provided`` +
``get_max_tokens``); we keep an equivalent guard so callers that omit
``max_tokens`` don't truncate at vLLM's 16-token ``SamplingParams`` default.
2. ``kv_transfer_params`` bridging — upstream ``ServingTokens.serve_tokens``
parses ``request.kv_transfer_params`` but never threads it into the engine,
so PD disagg never fires on ``/inference/v1/generate``. Fixed upstream by
https://github.com/vllm-project/vllm/pull/42644, which missed the 0.28.0
cut — drop the bridge once we pin a release that includes it.
Everything else (request/response schema, sampling params, error handling)
delegates to upstream so we track future vLLM changes for free.
@@ -26,16 +24,13 @@ delegates to upstream so we track future vLLM changes for free.
from __future__ import annotations
from collections.abc import AsyncGenerator, AsyncIterable
from functools import cached_property
from collections.abc import AsyncGenerator
from typing import Any
from fastapi import Request
from vllm.entrypoints.openai.engine.protocol import (
ErrorResponse,
PromptTokenUsageInfo,
RequestResponseMetadata,
UsageInfo,
)
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
GenerateRequest,
@@ -43,25 +38,20 @@ from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
GenerateResponseChoice,
)
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
from vllm.entrypoints.serve.utils.api_utils import get_max_tokens
from vllm.outputs import RequestOutput
from vllm.sampling_params import RequestOutputKind, SamplingParams
from prime_rl.inference.vllm.routed_experts import RoutedExpertsCapture
class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
routed_experts: dict[str, Any] | None = None
# Overrides upstream's base64 ``.npy`` string form with the compact
# ``{data, shape, start, dtype}`` object the PD router merges and the
# renderers parse.
routed_experts: dict[str, Any] | None = None # type: ignore[assignment]
class PrimeRlGenerateResponse(GenerateResponse):
choices: list[PrimeRlGenerateResponseChoice]
# Upstream ``GenerateResponse`` doesn't declare a ``usage`` field, so the
# parent ``ServingTokens.serve_tokens_full_generator`` constructs it and
# Pydantic silently drops it on serialization. Declare it here so the
# router can extract per-run token counts (and cached-prefix tokens) for
# platform billing — see https://github.com/PrimeIntellect-ai/router/pull/43.
usage: UsageInfo | None = None
class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
@@ -73,236 +63,29 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
)
for choice in response.choices
]
return PrimeRlGenerateResponse(
request_id=response.request_id,
choices=choices,
prompt_logprobs=response.prompt_logprobs,
kv_transfer_params=response.kv_transfer_params,
)
class _FinalOutputCapture:
"""Wraps a ``RequestOutput`` async generator to record the last yielded item.
Needed so the response builder can construct a ``usage`` block from
``final_res.prompt_token_ids`` / ``output.token_ids`` / ``num_cached_tokens``
after delegating iteration to upstream.
"""
def __init__(self, source: AsyncIterable[RequestOutput]) -> None:
# ``source`` may be any async-iterable — including
# ``_GenerateRoutedExpertsCapture``, which exposes the protocol via
# ``async def __aiter__`` (an async generator function) and has no
# ``__anext__`` method. Drive it through ``async for`` rather than
# poking ``__anext__`` directly so both shapes work.
self._source = source
self.final_res: RequestOutput | None = None
async def __aiter__(self) -> AsyncGenerator[RequestOutput, None]:
async for item in self._source:
self.final_res = item
yield item
def _build_usage(final_res: RequestOutput) -> UsageInfo:
assert final_res.prompt_token_ids is not None
num_prompt_tokens = len(final_res.prompt_token_ids)
if final_res.encoder_prompt_token_ids is not None:
num_prompt_tokens += len(final_res.encoder_prompt_token_ids)
num_generated_tokens = sum(len(output.token_ids) for output in final_res.outputs)
usage = UsageInfo(
prompt_tokens=num_prompt_tokens,
completion_tokens=num_generated_tokens,
total_tokens=num_prompt_tokens + num_generated_tokens,
)
# Always emit cached tokens when vLLM reports any. Upstream gates this on
# ``enable_prompt_tokens_details`` (default False) for OpenAI-API compat,
# but ``/inference/v1/generate`` is prime-rl internal — the cache-discount
# billing pipeline always wants the cached subset surfaced.
if final_res.num_cached_tokens:
usage.prompt_tokens_details = PromptTokenUsageInfo(cached_tokens=final_res.num_cached_tokens)
return usage
async def _client_set_max_tokens(raw_request: Request | None) -> bool:
"""Whether the inbound JSON body carried ``sampling_params.max_tokens``.
``GenerateRequest.sampling_params`` is parsed into a ``SamplingParams``
instance, which means an unset ``max_tokens`` is indistinguishable from
an explicit ``max_tokens=16`` once the request reaches the handler —
both surface as ``sampling_params.max_tokens == 16``. We re-read the
cached body to recover that distinction. When we can't (no raw_request,
non-JSON body, or read error), pessimistically assume the client did
set it so we never clobber an explicit value.
"""
if raw_request is None:
return True
try:
body = await raw_request.json()
except Exception:
return True
if not isinstance(body, dict):
return True
sp = body.get("sampling_params")
return isinstance(sp, dict) and "max_tokens" in sp
return PrimeRlGenerateResponse(**{**dict(response), "choices": choices})
class PrimeRlServingTokens(ServingTokens):
"""ServingTokens + DP-rank routing + compact routed experts + max_tokens defaulting."""
@cached_property
def _max_tokens_defaults(self) -> tuple[dict, int | None]:
"""Server-side ``max_tokens`` defaulting inputs, mirroring upstream ``ServingTokens``.
Computed lazily because ``custom_init_app_state`` swaps in this
subclass via ``object.__new__`` + ``__dict__.update`` (so our
``__init__`` never runs).
"""
diff = self.model_config.get_diff_sampling_param()
mc = self.model_config
override = (
diff.get("max_tokens")
if mc.generation_config not in ("auto", "vllm")
# Upstream uses ``getattr(..., {})`` directly. Defensive ``or {}``
# in case a downstream caller ever sets the attribute to ``None``
# (``getattr``'s default only fires when the attribute is missing,
# not when it exists with a ``None`` value).
else (getattr(mc, "override_generation_config", None) or {}).get("max_new_tokens")
)
return diff, override
"""ServingTokens + compact routed experts + PD kv_transfer_params bridging."""
async def serve_tokens(
self,
request: GenerateRequest,
raw_request: Request | None = None,
) -> PrimeRlGenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
# Mirrors upstream ``ServingTokens.serve_tokens``. Diffs:
# (a) inject ``data_parallel_rank`` from the inbound header into
# ``engine_client.generate``; (b) default ``sampling_params.max_tokens``
# to ``max_model_len - prompt_len`` when the caller didn't set it; and
# (c) dispatch to our overridden response builder so ``routed_experts``
# makes it into the JSON.
error_check_ret = await self._check_model(request)
if error_check_ret is not None:
return error_check_ret
if self.engine_client.errored:
raise self.engine_client.dead_error
lora_request = self._maybe_get_adapters(request, supports_default_mm_loras=True)
model_name = self.models.model_name(lora_request)
request_id = f"generate-tokens-{self._base_request_id(raw_request, request.request_id)}"
request_metadata = RequestResponseMetadata(request_id=request_id)
if raw_request:
raw_request.state.request_metadata = request_metadata
# Build the engine input — features-aware (MM) or text-only fallback.
# Identical to upstream so we keep tracking it.
if features := request.features:
from vllm.entrypoints.scale_out.token_in_token_out.mm_serde import decode_mm_kwargs_item
from vllm.inputs import mm_input
from vllm.multimodal.inputs import (
MultiModalKwargsItem,
MultiModalKwargsItems,
PlaceholderRange,
)
mm_placeholders = {
modality: [PlaceholderRange(offset=p.offset, length=p.length) for p in ranges]
for modality, ranges in features.mm_placeholders.items()
}
mm_kwargs: dict[str, list[MultiModalKwargsItem | None]] = {}
if features.kwargs_data is not None:
for modality, items in features.kwargs_data.items():
mm_kwargs[modality] = [decode_mm_kwargs_item(item) if item is not None else None for item in items]
else:
for modality, hashes in features.mm_hashes.items():
mm_kwargs[modality] = [None] * len(hashes)
engine_input = mm_input(
prompt_token_ids=request.token_ids,
mm_kwargs=MultiModalKwargsItems(mm_kwargs),
mm_hashes=features.mm_hashes,
mm_placeholders=mm_placeholders,
cache_salt=request.cache_salt,
)
else:
(engine_input,) = await self.online_renderer.preprocess_completion(
request,
prompt_input=request.token_ids,
prompt_embeds=None,
skip_mm_cache=True,
)
sampling_params: SamplingParams = request.sampling_params
# Upstream ``ServingTokens.serve_tokens`` parses ``request.kv_transfer_params``
# but never threads it into the engine, so PD disagg never fires on
# ``/inference/v1/generate`` — decode receives an empty NIXL handshake
# and ends up re-prefilling the prompt locally (~100× slower under
# concurrency). Bridge it through ``sampling_params.extra_args`` so the
# engine's KV connector picks the params up.
#
# Upstream fix: https://github.com/vllm-project/vllm/pull/42644 — drop
# this block once we pin a vLLM version that includes it.
) -> GenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
# Upstream parses ``request.kv_transfer_params`` but never threads it
# into the engine, so decode receives an empty NIXL handshake and
# re-prefills the prompt locally (~100x slower under concurrency).
# Bridge it through ``sampling_params.extra_args`` so the engine's KV
# connector picks the params up. Fixed upstream by vllm#42644 (merged
# after 0.28.0) — drop once we pin a release that includes it.
if request.kv_transfer_params is not None:
extra = sampling_params.extra_args or {}
extra = request.sampling_params.extra_args or {}
extra["kv_transfer_params"] = request.kv_transfer_params
sampling_params.extra_args = extra
request.sampling_params.extra_args = extra
# Server-side ``max_tokens`` defaulting — see module docstring. Upstream
# ``ServingTokens`` now does this too; kept here so callers that omit
# ``max_tokens`` don't get capped at vLLM's 16-token ``SamplingParams``
# default.
if not await _client_set_max_tokens(raw_request):
diff_sp, override = self._max_tokens_defaults
sampling_params.max_tokens = get_max_tokens(
max_model_len=self.model_config.max_model_len,
max_tokens=None,
input_length=len(request.token_ids),
default_sampling_params=diff_sp,
override_max_tokens=override,
)
if self.force_no_detokenize:
sampling_params.detokenize = False
if request.stream:
sampling_params.output_kind = RequestOutputKind.DELTA
self._log_inputs(
request_id,
engine_input,
params=sampling_params,
lora_request=lora_request,
)
trace_headers = None if raw_request is None else await self._get_trace_headers(raw_request.headers)
result_generator = self.engine_client.generate(
engine_input,
sampling_params,
request_id,
lora_request=lora_request,
trace_headers=trace_headers,
priority=request.priority,
data_parallel_rank=self._get_data_parallel_rank(raw_request),
)
if request.stream:
# Streaming path: defer to upstream — prime-RL's renderer client
# only consumes the full response, so adding routed_experts to the
# streaming choice schema is unnecessary churn.
return self.serve_tokens_stream_generator(
request,
result_generator,
request_id,
model_name,
request_metadata,
)
return await self.serve_tokens_full_generator(
request, result_generator, request_id, model_name, request_metadata
)
return await super().serve_tokens(request, raw_request)
async def serve_tokens_full_generator( # type: ignore[override]
self,
@@ -317,40 +100,17 @@ class PrimeRlServingTokens(ServingTokens):
# experts surface in the JSON.
capture: _GenerateRoutedExpertsCapture | None = None
if self.model_config.enable_return_routed_experts:
start = request.sampling_params.routed_experts_prompt_start
capture = _GenerateRoutedExpertsCapture(
result_generator,
start=start,
start=request.sampling_params.routed_experts_prompt_start,
)
result_generator = capture
# Always capture the final ``RequestOutput`` so we can attach a
# ``usage`` block to the response. The router parses ``usage`` for
# per-run billing metrics; without it the cache-discount counter
# (``vllm_router_run_cached_prompt_tokens_total``) stays at zero.
final_capture = _FinalOutputCapture(result_generator)
result_generator = final_capture
response = await super().serve_tokens_full_generator(
request, result_generator, request_id, model_name, request_metadata
)
if not isinstance(response, GenerateResponse):
return response
if capture is not None:
if capture is not None and isinstance(response, GenerateResponse):
response = capture.post_process(response)
elif not isinstance(response, PrimeRlGenerateResponse):
# Upgrade to the prime-rl subclass so the declared ``usage`` field
# actually surfaces in JSON (the parent class would drop it).
response = PrimeRlGenerateResponse(
request_id=response.request_id,
choices=[PrimeRlGenerateResponseChoice(**choice.model_dump()) for choice in response.choices],
prompt_logprobs=response.prompt_logprobs,
kv_transfer_params=response.kv_transfer_params,
)
if final_capture.final_res is not None:
response.usage = _build_usage(final_capture.final_res)
return response
@@ -3,7 +3,6 @@ import os
from prime_rl.inference.patches import (
monkey_patch_fp32_lm_head,
monkey_patch_fp32_router_logits,
monkey_patch_minimax_m2_for_lora,
monkey_patch_no_moe_lora,
)
@@ -21,6 +20,3 @@ else:
# Install fp32 lm_head patch; self-gates on additional_config["fp32_lm_head"] at call time
monkey_patch_fp32_lm_head()
# Install fp32 router logits patch; self-gates on additional_config["fp32_router_logits"]
monkey_patch_fp32_router_logits()
-1
View File
@@ -33,7 +33,6 @@ OVERVIEW_NAME = "overview"
# agent. Only the score metric differs — train scores with "reward/mean", eval with "avg@k" (its k
# dynamic, so also a regex) — and each section builder prepends its own.
COMMON_METRICS = [
"all/dispatch_failure/mean",
"effective/num_total_tokens/mean",
"effective/num_turns/mean",
"effective/num_branches/mean",
+6 -17
View File
@@ -854,10 +854,9 @@ class Orchestrator:
"""Per-step ``Step …`` success line. Multi-env runs append an indented ``╰─`` line per env.
Every quality metric (Reward, Trainable, Turns, Branches, Max Off-Policy, Truncation) is
computed over exactly the traces shipped to the trainer this step (``batch.cohort``).
``Error``, ``Dispatch Failure``, ``Cancelled``, and ``Ratio`` describe the step's full arrival window —
over the shipped set they are 0/0/share-of-shipped by construction, so the window is the
only scope where they carry signal (and they stay disjoint: a cancellation is a pipeline
decision, an episode error came from the environment, and a dispatch failure produced no episode)."""
``Error``, ``Cancelled``, and ``Ratio`` describe the step's full arrival window. Over the
shipped set they are 0/0/share-of-shipped by construction, so the window is the only scope
where they carry signal. A cancellation is a pipeline decision, not a rollout failure."""
episodes = batch.episodes
effective = batch.cohort.effective
eff = effective.metrics
@@ -866,16 +865,13 @@ class Orchestrator:
n_trainable = sum(is_trainable(record.trace) for record in effective.records)
trainable_rate = (n_trainable / n_effective) if n_effective else 0.0
max_off_policy_steps = max((episode_staleness(episode, step)[0] for episode in effective), default=0)
num_attempts = len(episodes) + len(batch.failures)
dispatch_failure_rate = len(batch.failures) / num_attempts if num_attempts else 0.0
head = (
f"Step {step} | {format_time(step_time):>7} | Reward {eff.reward.mean():.4f} | "
f"Trainable {n_trainable}/{n_effective} ({trainable_rate:.1%}) | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Max Off-Policy {max_off_policy_steps} | "
f"Error {episodes.metrics.has_error.mean():.1%} | Dispatch Failure {dispatch_failure_rate:.1%} | "
f"Cancelled {episodes.metrics.cancelled.mean():.1%} | "
f"Error {episodes.metrics.has_error.mean():.1%} | Cancelled {episodes.metrics.cancelled.mean():.1%} | "
f"Truncation {eff.is_truncated.mean():.1%}"
)
if len(self.train_envs) <= 1:
@@ -884,10 +880,7 @@ class Orchestrator:
window_by_env = episodes.by_env()
shipped_by_env = effective.by_env()
failures_by_env: dict[str, list[DispatchFailure]] = {}
for failure in batch.failures:
failures_by_env.setdefault(failure.env_name, []).append(failure)
env_names = sorted(set(window_by_env) | set(shipped_by_env) | set(failures_by_env))
env_names = sorted(set(window_by_env) | set(shipped_by_env))
name_width = max((len(name) for name in env_names), default=0)
lines = [head]
for env_name in env_names:
@@ -895,15 +888,11 @@ class Orchestrator:
env_eff_pool = shipped_by_env.get(env_name, TrainEpisodes())
env_eff = env_eff_pool.metrics
ratio = (pool.num_traces / n_generated) if n_generated else 0.0
env_failures = failures_by_env.get(env_name, [])
env_attempts = len(pool) + len(env_failures)
env_failure_rate = len(env_failures) / env_attempts if env_attempts else 0.0
lines.append(
f"╰─ {env_name:<{name_width}} | Ratio {ratio:.1%} | Reward {env_eff.reward.mean():.4f} | "
f"Turns {env_eff.num_turns.mean():.1f} | Branches {env_eff.num_branches.mean():.1f} | "
f"Max Off-Policy {max((episode_staleness(episode, step)[0] for episode in env_eff_pool), default=0)} | "
f"Error {pool.metrics.has_error.mean():.1%} | Dispatch Failure {env_failure_rate:.1%} | "
f"Cancelled {pool.metrics.cancelled.mean():.1%} | "
f"Error {pool.metrics.has_error.mean():.1%} | Cancelled {pool.metrics.cancelled.mean():.1%} | "
f"Truncation {env_eff.is_truncated.mean():.1%}"
)
get_logger().success("\n\t\t ".join(lines))
@@ -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",
]
@@ -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)
+18 -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):
@@ -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":
+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(
+43 -16
View File
@@ -43,11 +43,12 @@ class Batch(TypedDict):
class StatefulIterableDataset(Stateful, IterableDataset):
"""SFT dataset are iterable (infinite) and stateful (can be checkpointed)."""
def __init__(self):
def __init__(self, non_dp_size: int = 1):
self.step, self.epoch = 0, 0
self.num_samples = defaultdict(int)
self.num_tokens = defaultdict(int)
self.fast_forward = False
self.non_dp_size = non_dp_size
self._setup_world_info()
def state_dict(self) -> dict:
@@ -66,8 +67,10 @@ class StatefulIterableDataset(Stateful, IterableDataset):
num_workers = worker_info.num_workers
else:
worker_id, num_workers = 0, 1
self.data_rank = get_world().rank * num_workers + worker_id
self.data_world_size = get_world().world_size * num_workers
world = get_world()
assert world.world_size % self.non_dp_size == 0, "world_size must be divisible by non_dp_size"
self.data_rank = world.rank // self.non_dp_size * num_workers + worker_id
self.data_world_size = world.world_size // self.non_dp_size * num_workers
class FakeDataset(StatefulIterableDataset):
@@ -80,8 +83,9 @@ class FakeDataset(StatefulIterableDataset):
length: Literal["fixed", "variable"] = "fixed",
input_ids: Literal["increasing", "random"] = "random",
seed: int = 0,
non_dp_size: int = 1,
):
super().__init__()
super().__init__(non_dp_size)
self.vocab_size = vocab_size
self.seq_len = seq_len
self.length = length
@@ -103,6 +107,7 @@ class FakeDataset(StatefulIterableDataset):
return seq_len, random_input_ids
def __iter__(self):
self._setup_world_info()
# use a rank seeded PRNG instead of torch global default PRNG because with num workers > 0
# the data loader reseeds the global PRNG per worker process
generator = torch.Generator().manual_seed(self.seed + self.data_rank)
@@ -215,7 +220,7 @@ class SFTDataset(StatefulIterableDataset):
max_epochs: int | None = None,
multimodal: bool = False,
):
super().__init__()
super().__init__(non_dp_size)
self.logger = get_logger()
self.dataset = dataset
self.num_examples = len(self.dataset)
@@ -233,16 +238,6 @@ class SFTDataset(StatefulIterableDataset):
self.num_examples = min(self.num_examples, self.max_examples)
self.dataset = self.dataset.take(self.max_examples)
# Get the data rank and world size
worker_info = get_worker_info()
worker_id, num_workers = 0, 1
if worker_info is not None:
worker_id = worker_info.id
num_workers = worker_info.num_workers
assert get_world().world_size % non_dp_size == 0, "world_size must be divisible by non_dp_size"
self.data_rank = get_world().rank // non_dp_size * num_workers + worker_id
self.data_world_size = get_world().world_size // non_dp_size * num_workers
def _process(self, example: dict) -> dict | None:
def resolve_messages(example: dict) -> list[dict]:
# `messages` takes precedence over explicit split fields and is interpreted
@@ -393,6 +388,7 @@ class SFTDataset(StatefulIterableDataset):
}
def __iter__(self):
self._setup_world_info()
dataset = self.dataset.shuffle(seed=self.epoch + self.seed) if self.shuffle else self.dataset
while True:
self.step += 1
@@ -446,13 +442,22 @@ class CatDataset(StatefulIterableDataset):
self.pending_sample: Sample | None = None
def state_dict(self) -> dict:
state = {"dataset": self.dataset.state_dict()}
state = {
"dataset": self.dataset.state_dict(),
"progress": {
"num_samples": dict(self.dataset.num_samples),
"num_tokens": dict(self.dataset.num_tokens),
},
}
if self.pending_sample is not None:
state["pending_sample"] = self.pending_sample
return state
def load_state_dict(self, state_dict: dict):
self.dataset.load_state_dict(state_dict["dataset"])
progress = state_dict.get("progress", {})
self.dataset.num_samples.update(progress.get("num_samples", {}))
self.dataset.num_tokens.update(progress.get("num_tokens", {}))
self.pending_sample = state_dict.get("pending_sample")
def __iter__(self):
@@ -655,6 +660,7 @@ def setup_dataset(
length=config.length,
input_ids=config.input_ids,
seed=config.seed,
non_dp_size=non_dp_size,
)
elif config.type == "sft":
if renderer is None:
@@ -697,3 +703,24 @@ def get_dataset_state(dataloader: StatefulDataLoader) -> dict:
private worker-snapshot layout."""
snapshots = dataloader.state_dict()["_snapshot"]["_worker_snapshots"]
return {wid: snap["dataset_state"]["dataset"] for wid, snap in sorted(snapshots.items())}
def get_dataset_progress(dataloader: StatefulDataLoader) -> dict:
"""Dataset position and aggregate counters from dataloader workers."""
snapshot = dataloader.state_dict()["_snapshot"]
worker_snapshots = snapshot["_worker_snapshots"]
positions = [worker_snapshot["dataset_state"]["dataset"] for worker_snapshot in worker_snapshots.values()]
furthest = max(positions, key=lambda position: position["step"])
num_samples = defaultdict(int)
num_tokens = defaultdict(int)
for worker_snapshot in worker_snapshots.values():
progress = worker_snapshot["dataset_state"].get("progress", {})
for name, count in progress.get("num_samples", {}).items():
num_samples[name] += count
for name, count in progress.get("num_tokens", {}).items():
num_tokens[name] += count
return {
**furthest,
"num_samples": dict(num_samples),
"num_tokens": dict(num_tokens),
}
+17 -8
View File
@@ -40,7 +40,13 @@ from prime_rl.trainer.model import (
)
from prime_rl.trainer.parallel_dims import get_parallel_dims, resolve_ep
from prime_rl.trainer.perf import get_perf_counter
from prime_rl.trainer.sft.data import get_dataset_state, load_sft_dataset, setup_dataloader, setup_dataset
from prime_rl.trainer.sft.data import (
get_dataset_progress,
get_dataset_state,
load_sft_dataset,
setup_dataloader,
setup_dataset,
)
from prime_rl.trainer.utils import (
GarbageCollection,
MemoryProfiler,
@@ -590,7 +596,8 @@ def train(config: SFTConfig):
num_local_tokens = config.data.seq_len * (config.data.batch_size // dp_size)
num_tokens = dp_size * num_local_tokens
progress.total_tokens += num_tokens
progress.total_samples = dataset.step
dataset_progress = get_dataset_progress(dataloader)
progress.total_samples = dataset_progress["step"]
perf_counter = get_perf_counter(model, config.data.seq_len)
perf_counter.count_tokens(num_tokens)
throughput = perf_counter.get_tokens_per_second() or 0
@@ -612,24 +619,26 @@ def train(config: SFTConfig):
logger.success(step_message)
# Log progress metrics
total_samples = sum(dataset.num_samples.values())
total_tokens = sum(dataset.num_tokens.values())
samples_by_source = dataset_progress["num_samples"]
tokens_by_source = dataset_progress["num_tokens"]
total_samples = sum(samples_by_source.values())
total_tokens = sum(tokens_by_source.values())
progress_metrics = {
"progress/epoch": dataset.epoch,
"progress/epoch": dataset_progress["epoch"],
"progress/num_samples": progress.total_samples,
"progress/num_tokens": progress.total_tokens,
"step": progress.step,
}
# At least two subsets/splits
if len(dataset.num_samples) > 1:
if len(samples_by_source) > 1:
progress_metrics.update(
**{
f"progress/{subset_or_split}/ratio_samples": num_samples / total_samples
for subset_or_split, num_samples in dataset.num_samples.items()
for subset_or_split, num_samples in samples_by_source.items()
},
**{
f"progress/{subset_or_split}/ratio_tokens": num_tokens / total_tokens
for subset_or_split, num_tokens in dataset.num_tokens.items()
for subset_or_split, num_tokens in tokens_by_source.items()
},
)
asyncio.run(monitors.log(progress_metrics, step=progress.step))
+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:
+12 -191
View File
@@ -5,13 +5,12 @@ The full happy-path is owned upstream by vLLM's
deltas here:
* ``serialize_routed_experts`` round-trips a compact raw-byte payload.
* The subclass attaches its overrides without monkey-patching the parent.
* ``_client_set_max_tokens`` distinguishes raw-body shapes correctly.
* ``post_process`` swaps in the compact routed_experts while preserving
the rest of the upstream response (``usage`` included).
"""
from __future__ import annotations
import asyncio
import numpy as np
import pybase64
from vllm.entrypoints.openai.engine.protocol import UsageInfo
@@ -19,12 +18,7 @@ from vllm.entrypoints.scale_out.token_in_token_out.protocol import GenerateRespo
from prime_rl.inference.vllm.routed_experts import serialize_routed_experts
from prime_rl.inference.vllm.serving_tokens import (
PrimeRlGenerateResponse,
PrimeRlGenerateResponseChoice,
PrimeRlServingTokens,
_build_usage,
_client_set_max_tokens,
_FinalOutputCapture,
_GenerateRoutedExpertsCapture,
)
@@ -36,17 +30,6 @@ def _decode_routed_experts(encoded: dict) -> np.ndarray:
).reshape(encoded["shape"])
class _FakeRawRequest:
def __init__(self, body):
self._body = body
self._raise = isinstance(body, Exception)
async def json(self):
if self._raise:
raise self._body
return self._body
async def _empty_request_outputs():
if False:
yield
@@ -81,8 +64,10 @@ def test_generate_response_post_process_replaces_upstream_routed_experts():
compact_routed_experts = {"data": "AQID", "shape": [1, 1, 3], "start": 0}
capture = _GenerateRoutedExpertsCapture(_empty_request_outputs())
capture.routed_experts[0] = compact_routed_experts
usage = UsageInfo(prompt_tokens=4, completion_tokens=3, total_tokens=7)
response = GenerateResponse(
request_id="request-id",
model="test-model",
choices=[
GenerateResponseChoice(
index=0,
@@ -90,180 +75,16 @@ def test_generate_response_post_process_replaces_upstream_routed_experts():
routed_experts="upstream-npy-payload",
)
],
usage=usage,
)
processed = capture.post_process(response)
assert processed.choices[0].routed_experts == compact_routed_experts
def test_client_set_max_tokens_recognizes_explicit_value():
body = {"token_ids": [1, 2, 3], "sampling_params": {"max_tokens": 256}}
assert asyncio.run(_client_set_max_tokens(_FakeRawRequest(body))) is True
def test_client_set_max_tokens_detects_unset():
body = {"token_ids": [1, 2, 3], "sampling_params": {}}
assert asyncio.run(_client_set_max_tokens(_FakeRawRequest(body))) is False
body_without_sp = {"token_ids": [1, 2, 3]}
assert asyncio.run(_client_set_max_tokens(_FakeRawRequest(body_without_sp))) is False
class _FakeOutput:
def __init__(self, token_ids):
self.token_ids = token_ids
class _FakeRequestOutput:
"""Minimal stand-in for ``vllm.outputs.RequestOutput``.
``_build_usage`` only touches four attributes; constructing a real
``RequestOutput`` would require a full ``CompletionOutput`` graph and
isn't worth it for a serialization-shape test.
"""
def __init__(self, prompt_token_ids, output_token_ids_list, num_cached_tokens=0, encoder_prompt_token_ids=None):
self.prompt_token_ids = prompt_token_ids
self.encoder_prompt_token_ids = encoder_prompt_token_ids
self.outputs = [_FakeOutput(t) for t in output_token_ids_list]
self.num_cached_tokens = num_cached_tokens
def test_prime_rl_generate_response_serializes_usage_block():
# Regression for prime-rl PR #2408: parent ``GenerateResponse`` doesn't
# declare ``usage``, so the field must be declared on the subclass for
# Pydantic to emit it in JSON. Without this the router can't extract
# per-run token / cache counts for billing.
response = PrimeRlGenerateResponse(
request_id="req-1",
choices=[PrimeRlGenerateResponseChoice(index=0, token_ids=[1, 2, 3])],
usage=UsageInfo(prompt_tokens=4, completion_tokens=3, total_tokens=7),
)
payload = response.model_dump(mode="json")
assert payload["usage"] == {
"prompt_tokens": 4,
"completion_tokens": 3,
"total_tokens": 7,
"prompt_tokens_details": None,
}
def test_build_usage_sums_prompt_and_completion_tokens():
final_res = _FakeRequestOutput(
prompt_token_ids=[1, 2, 3, 4, 5],
output_token_ids_list=[[10, 11], [20, 21, 22]],
)
usage = _build_usage(final_res)
assert usage.prompt_tokens == 5
assert usage.completion_tokens == 5 # 2 + 3
assert usage.total_tokens == 10
assert usage.prompt_tokens_details is None
def test_build_usage_includes_encoder_prompt_tokens():
final_res = _FakeRequestOutput(
prompt_token_ids=[1, 2, 3],
output_token_ids_list=[[10]],
encoder_prompt_token_ids=[100, 101],
)
usage = _build_usage(final_res)
assert usage.prompt_tokens == 5 # 3 + 2
assert usage.total_tokens == 6
def test_build_usage_reports_cached_tokens_unconditionally():
# Unlike upstream's ``enable_prompt_tokens_details`` gate, prime-rl always
# surfaces cached tokens — the cache-discount billing pipeline needs them.
final_res = _FakeRequestOutput(
prompt_token_ids=[1, 2, 3, 4],
output_token_ids_list=[[10, 11]],
num_cached_tokens=3,
)
usage = _build_usage(final_res)
assert usage.prompt_tokens_details is not None
assert usage.prompt_tokens_details.cached_tokens == 3
def test_build_usage_skips_cached_tokens_when_zero():
# Don't emit a details block with cached=0, which would be misleading
# to the router's billing extractor.
final_res = _FakeRequestOutput(
prompt_token_ids=[1, 2, 3, 4],
output_token_ids_list=[[10, 11]],
num_cached_tokens=0,
)
usage = _build_usage(final_res)
assert usage.prompt_tokens_details is None
def test_final_output_capture_records_last_item():
async def _gen():
for r in [
_FakeRequestOutput(prompt_token_ids=[1], output_token_ids_list=[[1]]),
_FakeRequestOutput(prompt_token_ids=[1, 2], output_token_ids_list=[[1, 2]]),
_FakeRequestOutput(prompt_token_ids=[1, 2, 3], output_token_ids_list=[[1, 2, 3]]),
]:
yield r
async def _drain(capture):
async for _ in capture:
pass
capture = _FinalOutputCapture(_gen())
asyncio.run(_drain(capture))
assert capture.final_res is not None
assert capture.final_res.prompt_token_ids == [1, 2, 3]
def test_final_output_capture_works_over_async_def_aiter_source():
# ``_GenerateRoutedExpertsCapture`` exposes the async-iterator protocol
# via ``async def __aiter__`` (an async generator function) and has no
# ``__anext__``. The wrapper must drive it through ``async for`` rather
# than poking ``__anext__`` directly, or routed-experts runs raise
# AttributeError before the response is built.
class _AsyncGenAiterSource:
def __init__(self, items):
self._items = items
async def __aiter__(self):
for item in self._items:
yield item
items = [
_FakeRequestOutput(prompt_token_ids=[1], output_token_ids_list=[[1]]),
_FakeRequestOutput(prompt_token_ids=[1, 2], output_token_ids_list=[[1, 2]]),
]
capture = _FinalOutputCapture(_AsyncGenAiterSource(items))
async def _drain():
async for _ in capture:
pass
asyncio.run(_drain())
assert capture.final_res is not None
assert capture.final_res.prompt_token_ids == [1, 2]
def test_final_output_capture_handles_empty_stream():
capture = _FinalOutputCapture(_empty_request_outputs())
async def _drain():
async for _ in capture:
pass
asyncio.run(_drain())
assert capture.final_res is None
def test_client_set_max_tokens_assumes_set_when_body_unreadable():
# No raw_request → can't tell, don't override.
assert asyncio.run(_client_set_max_tokens(None)) is True
# body read raises → can't tell, don't override.
err = ValueError("bad json")
assert asyncio.run(_client_set_max_tokens(_FakeRawRequest(err))) is True
# non-dict body → can't tell, don't override.
assert asyncio.run(_client_set_max_tokens(_FakeRawRequest([1, 2, 3]))) is True
assert processed.model == "test-model"
assert processed.usage == usage
# The compact object form must survive JSON serialization (the parent
# declares ``routed_experts`` as a base64 string).
payload = processed.model_dump(mode="json")
assert payload["choices"][0]["routed_experts"] == compact_routed_experts
assert payload["usage"]["total_tokens"] == 7
-5
View File
@@ -451,11 +451,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(
+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
)
+21
View File
@@ -0,0 +1,21 @@
import pytest
from renderers.base import RenderedTokens
class DummyRenderer:
def render(self, messages, **kwargs):
content_ids = [ord(char) + 2 for char in messages[-1]["content"]]
token_ids = [0, *content_ids, 1]
return RenderedTokens(
token_ids=token_ids,
message_indices=[-1, *([len(messages) - 1] * (len(content_ids) + 1))],
sampled_mask=[False, *([True] * (len(content_ids) + 1))],
)
def get_stop_token_ids(self):
return [1]
@pytest.fixture
def dummy_renderer():
return DummyRenderer()
+154 -37
View File
@@ -1,22 +1,31 @@
import gc
import os
import pytest
import torch
from transformers import AutoTokenizer
from datasets import Dataset
from prime_rl.configs.sft import FakeDataConfig
from prime_rl.trainer.sft.data import get_dataset_state, setup_dataloader, setup_dataset
from prime_rl.configs.sft import FakeDataConfig, SFTDataConfig
from prime_rl.trainer.sft.data import FakeDataset, SFTDataset, get_dataset_progress, get_dataset_state, setup_dataloader
from prime_rl.trainer.world import reset_world
pytestmark = [pytest.mark.gpu]
def setup_fake_dataloader(config: FakeDataConfig, non_dp_size: int = 1):
dataset = FakeDataset(
vocab_size=32,
seq_len=config.seq_len,
length=config.length,
input_ids=config.input_ids,
seed=config.seed,
non_dp_size=non_dp_size,
)
return dataset, setup_dataloader(dataset, config)
def test_fake_dataset_single_rank_state():
# Setup stateful dataloader
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
config = FakeDataConfig(length="fixed", input_ids="increasing", batch_size=1)
dataset = setup_dataset(tokenizer, config)
dataloader = setup_dataloader(dataset, config)
_, dataloader = setup_fake_dataloader(config)
dataiter = iter(dataloader)
# Initial state
@@ -39,7 +48,8 @@ def test_fake_dataset_single_rank_state():
@pytest.mark.parametrize("rank", [0, 1], ids=["rank0", "rank1"])
def test_fake_dataset_multi_rank_state(rank: int):
@pytest.mark.parametrize("non_dp_size", [1, 2], ids=["dp", "cp"])
def test_fake_dataset_multi_rank_state(rank: int, non_dp_size: int):
# Setup world
reset_world()
os.environ["RANK"] = str(rank)
@@ -48,40 +58,25 @@ def test_fake_dataset_multi_rank_state(rank: int):
os.environ["LOCAL_WORLD_SIZE"] = str(2)
# Setup stateful dataloader
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
config = FakeDataConfig(length="fixed", input_ids="increasing", batch_size=1)
dataset = setup_dataset(tokenizer, config)
dataloader = setup_dataloader(dataset, config)
_, dataloader = setup_fake_dataloader(config, non_dp_size)
dataiter = iter(dataloader)
# Initial state
assert get_dataset_state(dataloader) == {"worker_0": {"step": 0, "epoch": 0}}
micro_batch = next(dataiter)
assert micro_batch["input_ids"].unique().item() == 0 + rank
assert get_dataset_state(dataloader) == {"worker_0": {"step": 1 + rank, "epoch": 0}}
micro_batch = next(dataiter)
assert micro_batch["input_ids"].unique().item() == 2 + rank
assert get_dataset_state(dataloader) == {"worker_0": {"step": 3 + rank, "epoch": 0}}
micro_batch = next(dataiter)
assert micro_batch["input_ids"].unique().item() == 4 + rank
assert get_dataset_state(dataloader) == {"worker_0": {"step": 5 + rank, "epoch": 0}}
micro_batch = next(dataiter)
assert micro_batch["input_ids"].unique().item() == 6 + rank
assert get_dataset_state(dataloader) == {"worker_0": {"step": 7 + rank, "epoch": 0}}
micro_batch = next(dataiter)
assert micro_batch["input_ids"].unique().item() == 8 + rank
assert get_dataset_state(dataloader) == {"worker_0": {"step": 9 + rank, "epoch": 0}}
micro_batch = next(dataiter)
assert micro_batch["input_ids"].unique().item() == 10 + rank
assert get_dataset_state(dataloader) == {"worker_0": {"step": 11 + rank, "epoch": 0}}
data_rank = rank // non_dp_size
data_world_size = 2 // non_dp_size
for index in range(6):
expected_sample = index * data_world_size + data_rank
micro_batch = next(dataiter)
assert micro_batch["input_ids"].unique().item() == expected_sample
assert get_dataset_state(dataloader) == {"worker_0": {"step": expected_sample + 1, "epoch": 0}}
def test_fake_dataset_single_rank_resume():
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
config = FakeDataConfig(length="fixed", input_ids="increasing", batch_size=1)
dataset = setup_dataset(tokenizer, config)
dataloader = setup_dataloader(dataset, config)
dataset, dataloader = setup_fake_dataloader(config)
dataiter = iter(dataloader)
# First 2 samples
@@ -106,10 +101,8 @@ def test_fake_dataset_single_rank_resume():
def test_fake_dataset_single_rank_state_with_packing():
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
config = FakeDataConfig(length="variable", input_ids="increasing", batch_size=1)
dataset = setup_dataset(tokenizer, config)
dataloader = setup_dataloader(dataset, config)
_, dataloader = setup_fake_dataloader(config)
dataiter = iter(dataloader)
step = 0
@@ -130,8 +123,7 @@ def test_fake_dataset_single_rank_state_with_packing():
rng_state = torch.random.get_rng_state()
expected_batch = next(dataiter)
resumed_dataset = setup_dataset(tokenizer, config)
resumed_dataloader = setup_dataloader(resumed_dataset, config)
_, resumed_dataloader = setup_fake_dataloader(config)
resumed_dataloader.load_state_dict(state_dict)
resumed_dataiter = iter(resumed_dataloader)
torch.random.set_rng_state(rng_state)
@@ -139,3 +131,128 @@ def test_fake_dataset_single_rank_state_with_packing():
for key in ("input_ids", "position_ids", "target_ids", "loss_mask", "seq_lens"):
torch.testing.assert_close(resumed_batch[key], expected_batch[key])
@pytest.mark.parametrize("num_workers", [1, 2])
@pytest.mark.parametrize(
("world_size", "non_dp_size"),
[
pytest.param(1, 1, id="1dp"),
pytest.param(2, 1, id="2dp"),
pytest.param(2, 2, id="1dp-2cp"),
pytest.param(4, 2, id="2dp-2cp"),
],
)
def test_dataloader_shards_across_ranks_and_workers(
num_workers: int, world_size: int, non_dp_size: int, dummy_renderer
):
rounds_before_resume = 3
rounds_after_resume = 1
data_world_size = world_size // non_dp_size
num_examples = 2 * data_world_size * num_workers
samples_before_resume = rounds_before_resume * num_workers
samples_per_rank = (rounds_before_resume + rounds_after_resume) * num_workers
samples_by_rank = []
for rank in range(world_size):
reset_world()
os.environ["RANK"] = str(rank)
os.environ["WORLD_SIZE"] = str(world_size)
os.environ["LOCAL_RANK"] = str(rank)
os.environ["LOCAL_WORLD_SIZE"] = str(world_size)
config = SFTDataConfig(
batch_size=1,
micro_batch_size=1,
seq_len=7,
num_workers=num_workers,
shuffle=False,
)
def setup_epoch_dataloader():
raw_dataset = Dataset.from_list(
[
{
"messages": [{"role": "assistant", "content": str(index) * 6}],
"__split": "fake",
}
for index in range(num_examples)
]
)
dataset = SFTDataset(
raw_dataset,
dummy_renderer,
shuffle=False,
seq_len=config.seq_len,
non_dp_size=non_dp_size,
)
return setup_dataloader(dataset, config)
dataloader = setup_epoch_dataloader()
dataiter = iter(dataloader)
epochs = set()
def next_sample(dataiter, dataloader, index: int) -> int:
micro_batch = next(dataiter)
# After the causal shift, the first target is DummyRenderer's first character, offset by its two special tokens.
sample = micro_batch["target_ids"][0, 0].item() - ord("0") - 2
worker_id = index % num_workers
worker_round = index // num_workers
data_rank = rank // non_dp_size
position = worker_round * data_world_size * num_workers + data_rank * num_workers + worker_id
progress = get_dataset_progress(dataloader)
assert sample == position % num_examples
assert progress["step"] == position + 1
assert progress["epoch"] == position // num_examples
assert progress["num_samples"] == {"fake": index + 1}
assert progress["num_tokens"] == {"fake": (index + 1) * config.seq_len}
epochs.add(progress["epoch"])
return sample
samples = [next_sample(dataiter, dataloader, index) for index in range(samples_before_resume)]
state_dict = dataloader.state_dict()
del dataiter, dataloader
gc.collect()
dataloader = setup_epoch_dataloader()
dataloader.load_state_dict(state_dict)
dataiter = iter(dataloader)
samples.extend(
next_sample(dataiter, dataloader, index) for index in range(samples_before_resume, samples_per_rank)
)
samples_by_rank.append(samples)
assert epochs == {0, 1}
del dataiter, dataloader
gc.collect()
for data_rank in range(data_world_size):
cp_samples = samples_by_rank[data_rank * non_dp_size : (data_rank + 1) * non_dp_size]
assert all(samples == cp_samples[0] for samples in cp_samples)
unique_samples = [samples_by_rank[data_rank * non_dp_size] for data_rank in range(data_world_size)]
expected = sorted(list(range(num_examples)) * 2)
assert sorted(sample for samples in unique_samples for sample in samples) == expected
def test_dataloader_progress_is_monotonic_with_uneven_workers():
config = FakeDataConfig(
batch_size=1,
micro_batch_size=1,
seq_len=32,
num_workers=2,
length="variable",
input_ids="increasing",
)
_, dataloader = setup_fake_dataloader(config)
dataiter = iter(dataloader)
positions = []
for _ in range(12):
next(dataiter)
positions.append(get_dataset_progress(dataloader)["step"])
del dataiter, dataloader
gc.collect()
assert positions == sorted(positions)
+3 -22
View File
@@ -4,7 +4,7 @@ import pytest
import torch
from datasets import Dataset, interleave_datasets
from renderers import create_renderer
from renderers.base import MultiModalData, PlaceholderRange, RenderedTokens, RenderedTrainingSample
from renderers.base import MultiModalData, PlaceholderRange, RenderedTrainingSample
from transformers import AutoTokenizer
import prime_rl.trainer.sft.data as sft_data
@@ -19,20 +19,6 @@ def _sample_token_ids(value: str) -> list[int]:
return [ord(char) + 2 for char in value]
class _DummyRenderer:
def render(self, messages, **kwargs):
content_ids = _sample_token_ids(messages[-1]["content"])
token_ids = [_BOS_TOKEN_ID, *content_ids, _STOP_TOKEN_ID]
return RenderedTokens(
token_ids=token_ids,
message_indices=[-1, *([len(messages) - 1] * (len(content_ids) + 1))],
sampled_mask=[False, *([True] * (len(content_ids) + 1))],
)
def get_stop_token_ids(self):
return [_STOP_TOKEN_ID]
@pytest.fixture(scope="module")
def build_dummy_dataset():
return lambda letter, num_examples: Dataset.from_list(
@@ -40,11 +26,6 @@ def build_dummy_dataset():
)
@pytest.fixture
def dummy_renderer():
return _DummyRenderer()
@pytest.mark.parametrize(
"arguments",
[
@@ -403,7 +384,7 @@ def test_null_messages_falls_back_to_prompt_and_completion():
assert next(iter(mixed_row_dataset)) == next(iter(expected_dataset))
def test_vlm_truncation_does_not_append_trainable_eos(monkeypatch):
def test_vlm_truncation_does_not_append_trainable_eos(monkeypatch, dummy_renderer):
mm = MultiModalData(
mm_placeholders={"image": [PlaceholderRange(offset=1, length=1)]},
mm_items={"image": [{"pixel_values": torch.ones(1, 1), "image_grid_thw": torch.tensor([[1, 1, 1]])}]},
@@ -418,7 +399,7 @@ def test_vlm_truncation_does_not_append_trainable_eos(monkeypatch):
)
monkeypatch.setattr(sft_data, "build_training_sample", fake_build_training_sample)
dataset = SFTDataset(Dataset.from_list([]), _DummyRenderer(), seq_len=2, multimodal=True)
dataset = SFTDataset(Dataset.from_list([]), dummy_renderer, seq_len=2, multimodal=True)
assert dataset._process({"messages": [{"role": "assistant", "content": "ignored"}]}) is None
Generated
+373 -548
View File
File diff suppressed because it is too large Load Diff