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
40 changed files with 1909 additions and 1819 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",
@@ -30,20 +30,13 @@ class GCConfig(BaseConfig):
class ActivationCheckpointConfig(BaseConfig):
mode: Literal["full", "selective"] = "full"
"""``full`` checkpoints whole transformer blocks; ``selective`` checkpoints only the subcomponents listed in ``targets`` inside supported custom decoder layers."""
"""Both modes checkpoint whole transformer blocks. ``selective`` additionally retains selected operations."""
freq: int = Field(1, ge=1)
"""Apply activation checkpointing to every N layers."""
targets: list[str] = ["norm"]
"""Selective checkpoint targets. ``norm`` checkpoints every norm module inside selected layers. ``attn_proj`` checkpoints projection-side attention work outside the kernel (input/output projections, attention-local norms, RoPE, gating, model-specific MLA projection helpers). ``mlp`` checkpoints the entire dense MLP forward (not for MoE). ``mla_up_proj`` checkpoints MLA Q/KV up-projection where supported. ``linear_attn`` checkpoints non-softmax token mixers (NemotronH Mamba, Qwen3.5-MoE GatedDeltaNet, AFMoE sliding-window attention)."""
@model_validator(mode="after")
def validate_selective_targets(self):
self.targets = list(dict.fromkeys(self.targets))
if self.mode == "selective" and not self.targets:
raise ValueError("Selective activation checkpointing requires at least one target.")
return self
targets: list[str] | None = None
"""Operator names or namespaces retained in selective mode. ``None`` uses the default targets; an explicit list replaces them."""
class ActivationOffloadingConfig(BaseConfig):
@@ -347,12 +340,6 @@ class ModelConfig(BaseModelConfig):
self.ac = ActivationCheckpointConfig()
return self
@model_validator(mode="after")
def selective_ac_only_with_custom_impl(self):
if self.ac is not None and self.ac.mode == "selective" and self.impl not in ("custom", "auto"):
raise ValueError("Selective activation checkpointing requires model.impl='custom' or 'auto'")
return self
@model_validator(mode="after")
def cpu_offload_mutual_exclusion(self):
if self.fsdp_cpu_offload and (self.optim_cpu_offload or self.full_offload):
+4 -2
View File
@@ -27,7 +27,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"verifiers[harbor]>=0.3.1",
"renderers>=0.1.10",
"renderers[multimodal]>=0.1.11",
"pybase64>=1.4.2",
"orjson>=3.10",
"pandas>=2.0",
@@ -139,6 +139,8 @@ environments = [
# Override torch's pinned cuDNN to fix the Conv3d performance regression.
# See: https://github.com/pytorch/pytorch/issues/166122
override-dependencies = [
# Shared by vLLM, TileLang, and the pinned FlashAttention 4 runtime.
"apache-tvm-ffi==0.1.11",
"nvidia-cudnn-cu13>=9.15 ; sys_platform == 'linux'",
# vLLM 0.28.0 requires quack-kernels 0.6.4. It requires this exact CUTLASS version.
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
@@ -250,7 +252,7 @@ torchao = [
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "82d6441" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "0251105" }
vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
@@ -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:
-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
+205 -457
View File
File diff suppressed because it is too large Load Diff