Compare commits

...
Author SHA1 Message Date
Konstantin DunasandGitHub c176840626 chore: bump renderers to 0.1.11, verifiers and prime-envs to main (#3441) 2026-08-31 22:14:00 +02:00
Mika SenghaasandGitHub bb0c103f08 fix: shard SFT data and report worker progress (#3417)
## Summary

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

## Verification

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

## Verification

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

Validated on GLM-4.5-Air SWE

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

## Verification

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

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> A broad inference dependency bump plus behavioral changes to MoE
routing, model-runner selection, and P/D KV transfer bridging;
misconfiguration could affect logprob fidelity, router replay, or
disaggregated decode performance until upstream fixes land.
> 
> **Overview**
> Upgrades the GPU inference stack from **vLLM 0.27.1 to 0.28.0**, with
matching lockfile and wheel pins (`nvidia-cutlass-dsl` 4.6.2,
`quack-kernels` 0.6.4).
> 
> **Config / launcher:** `to_namespace()` now defaults
**`enable_prompt_tokens_details`** so `/inference/v1/generate` `usage`
includes cached prompt tokens for router billing.
**`enable_fp32_router_logits`** no longer sets `additional_config`; it
injects **`hf_overrides.moe_router_dtype = "float32"`** so vLLM’s native
MoE routing path applies. **`VLLM_USE_V2_MODEL_RUNNER=0`** is set only
when **`enable_return_routed_experts`** is on (V2 never captures routed
experts); other models follow vLLM’s V1/V2 resolution.
> 
> **Removed patches** superseded by 0.28: harmony stop-token merge on
chat completions, `DeepseekV2MoE` fp32 router monkey-patch, and most of
the custom `ServingTokens` fork (DP routing, `max_tokens` defaulting,
manual `usage` assembly). **`PrimeRlServingTokens`** now delegates to
upstream `serve_tokens` except for **`kv_transfer_params` →
`sampling_params.extra_args`** (PD disagg until vllm#42644 ships) and
compact **`routed_experts`** post-processing.
> 
> **Other:** NIXL routed-experts guard uses
**`config.use_v2_model_runner`** instead of the env flag. Unit tests for
deleted helpers are trimmed; post-process test asserts `usage` is
preserved from upstream responses.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
77c9264df8bb12af89eda7c238e2415e9a339857. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-28 21:57:26 -07:00
Mika SenghaasandGitHub 70117046ac fix: bump torch 2.13 + vllm 0.27.1 + custom wheels for cuda 13 (#3425)
## Summary

- upgrade Torch to 2.13 and vLLM to 0.27.1 on CUDA 13
- pin matching CUDA 13 wheels for FlashAttention, prime-kernels, DeepEP,
DeepGEMM, TorchAO, NIXL, CUTLASS DSL, cuDNN, and vLLM
- load DeepGEMM only when FP8 kernels execute so CPU imports do not
require a CUDA toolkit
- reject TorchAO MXFP8 on GPUs other than SM100
- move native wheel builds to prime-kernels and remove the duplicate
PrimeRL workflow and build scripts
- use the CUDA 13 toolkit and runtime in the PrimeRL CUDA image

Validated against GLM-4.5-Air SWE run

<img width="295" height="227" alt="Screenshot 2026-08-28 at 7 29 36 PM"
src="https://github.com/user-attachments/assets/d125177e-86e0-4a2e-bb78-3a44bb4f15ce"
/>

<img width="294" height="239" alt="Screenshot 2026-08-28 at 7 30 05 PM"
src="https://github.com/user-attachments/assets/ea277670-c42a-49b6-a2cc-b10c5d9b8713"
/>

## Breaking

- remove `scripts/install_deep_gemm.sh` and
`scripts/install_ep_kernels.sh`; use the builders under
`deps/prime-kernels/scripts/` for source builds

## Verification

- `uv lock --check`
- `git diff --check`
- `bash -n deps/prime-kernels/scripts/install_deep_gemm.sh
deps/prime-kernels/scripts/install_ep_kernels.sh`
- Ruff check and format checks for the changed Python files
- verified that importing `prime_rl.trainer.model` does not import
DeepGEMM
- verified that MXFP8 rejects the local SM120 GPU with an SM100
requirement
- ran FlashAttention 2 forward on the local SM120 GPU
- `uv run pytest tests/unit -m "not gpu"`: 476 passed and one unrelated
Qwen3-VL fake-response assertion failed
- after merging `main`, focused config and MoE tests passed: 148 passed
and 3 skipped


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Wide dependency and Docker CUDA migration affects training, inference,
MoE/FP8, and disaggregated NIXL paths; MXFP8 now fails on non-SM100 GPUs
that previously passed the SM100+ check.
> 
> **Overview**
> Moves the GPU stack from **CUDA 12.8 / torch 2.9 / vLLM 0.26** to
**CUDA 13 / torch 2.13 / vLLM 0.27.1**, with matching prebuilt wheels
(FlashAttention, prime-kernels, DeepEP, DeepGEMM, torchao, NIXL, cuDNN,
CUTLASS) pinned via `[tool.uv.sources]` to **prime-kernels** release
assets instead of prime-rl releases. `uv` **dependency-metadata**
overrides steer NIXL and CUTLASS toward CUDA 13 variants so cu12
packages are not pulled alongside extras.
> 
> **CI and packaging:** Deletes `.github/workflows/build_kernels.yaml`
and the release jobs that built kernel wheels before publishing; native
wheel builds are documented as owned by the **prime-kernels** repo.
Removes in-repo `install_deep_gemm.sh` / `install_ep_kernels.sh` in
favor of `deps/prime-kernels/scripts/`.
> 
> **Docker:** `Dockerfile.cuda` uses **nvidia/cuda 13.0.1** end-to-end,
drops the sidecar CUDA 13 runtime copy used for deep-gemm, and installs
**nixl_cu13** when building NIXL from source.
> 
> **Runtime behavior:** **DeepGEMM** is imported lazily inside FP8
autograd paths so CPU-only imports do not require the CUDA toolkit.
**MXFP8** quantization is restricted to **exactly SM100** (not
“SM100+”), and torchao’s MXFP8 linear helper import path is updated.
Benchmark baseline JSON files are refreshed for the new commit and
benchmark harness fields.
> 
> **Docs/skills:** Install and kernels skills describe `uv sync --extra
disagg` and prime-kernels release workflow instead of the removed
PrimeRL kernel CI.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
4f6159cbe8333759cb55720ca2abaeeb7ff8b40b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-28 21:01:28 -07:00
Matej SirovatkaandGitHub b2c6fe9aec refactor(moe): unify runtime and checkpoint layout (#3411)
## Summary

### Model and checkpoint contract

- Replace the separate standard, GPT-OSS, and Nemotron expert/router
implementations with one canonical MoE tree.
- Store routed expert weights as separate `gate_proj`, `up_proj`, and
`down_proj` parameters. Non-gated experts omit `gate_proj`.
- Nest every custom router at `mlp.router.gate`, routed experts at
`mlp.experts`, and optional shared experts inside `mlp`.
- Store the single selection-only router bias at
`mlp.router.selection_bias`; model-specific checkpoint names are
converted only at the HF boundary.
- Keep shared expert projections canonical. Qwen3.5 alone nests its
scalar sigmoid gate at `mlp.shared_expert.output_gate`, with conversion
mapping the standalone Hugging Face key at the boundary.
- Use the same activation protocol and `FeedForward` implementation for
dense MLPs, shared experts, and grouped experts.
- Make shared-expert construction exclusively parent-owned: model layers
pass an explicit `FeedForward`/subclass or `None`, while `MoEArgs` and
`MoE` never infer or construct one.
- Keep existing HF source layouts at the conversion boundary. GPT-OSS
alone adds the structural split/join required for its interleaved source
tensor.
- Require `.prime-v1` in reusable `<conversion_dir>/prime` caches so
legacy Prime layouts fail before loading.

### MoE runtime contract

- Use one routed execution sequence for every backend: dispatch tokens,
run canonical grouped experts, combine tokens.
- Select grouped expert compute through explicit BF16, DeepGEMM FP8, or
MXFP8 implementations. `MoEArgs` remains architecture-only.
- Select local/Torch or DeepEP token dispatch once during model setup.
Dispatchers own routing metadata, communication, padding, chunking, and
synchronization.
- Keep `TokenDispatcher` as the structural interface while a shared base
owns the canonical run/synchronize sequence; local, Torch, and DeepEP
implementations own only their dispatch/combine details.
- Keep DeepEP combine events, concatenate streams, and flattened
dispatch state owned by each dispatcher; chunking uses the equal input
shape shared by EP ranks and does not synthesize empty chunks.
- Ignore dispatch configuration when expert parallelism resolves to one
rank; local dispatch remains active and DeepEP has no optimizer side
effects.
- Keep grouped expert execution directly in `GroupedExperts.forward` and
router confidence accounting directly in
`TokenChoiceTopKRouter.forward`.
- Shard every canonical expert parameter with one backend-independent
`Shard(0)` placement.
- Keep dense linear quantization, routed-expert compute, and EP
transport independent.
- Remove the TorchTitan module hooks, expert decorator, dynamically
attached process group, backend attributes, tensor-subclass
interception, and process-global MXFP8 patches from the reachable path.
- Vendor the narrow MXFP8 grouped-GEMM and Torch EP transport
implementation in [prime-kernels PR
#1](https://github.com/PrimeIntellect-ai/prime-kernels/pull/1),
preserving the pinned torchao revision and BSD license.

## Public contracts

Checkpoint tree:

- `mlp.router.gate`: `nn.Linear`
- `mlp.router.selection_bias`: optional persistent selection-only buffer
- `mlp.experts.gate_proj`: stacked `nn.Parameter` for gated experts,
absent for non-gated experts
- `mlp.experts.up_proj`: stacked `nn.Parameter`
- `mlp.experts.down_proj`: stacked `nn.Parameter`
- `mlp.shared_expert.{gate_proj,up_proj,down_proj}`: `FeedForward`
projections when present
- `mlp.shared_expert.output_gate`: Qwen3.5-only scalar `nn.Linear`
- expert matrices: `[num_experts, output_features, input_features]`

Runtime configuration:

```toml
[trainer.model.moe.compute]
type = "bf16"  # bf16 | deepgemm_fp8 | mxfp8

[trainer.model.moe.dispatch]
type = "torch"  # torch | deepep
transport = "bf16"  # bf16 | mxfp8 for torch dispatch
```

DeepEP owns its tuning fields:

```toml
[trainer.model.moe.dispatch]
type = "deepep"
num_sms = 20
token_chunk_size = 4096
```

This is intentionally breaking. `enable_grouped_gemm`, `enable_a2a`,
`ep_comm_backend`, `deepep_num_sms`, and `deepep_token_chunk_size` are
removed without aliases.

## Validation completed

- Foundation conversion, detector, marker, state-loading, checkpoint,
NIXL graph, and wire-format tests passed.
- Focused CPU configuration and MoE contracts: 143 passed.
- Focused MoE runtime configuration parametrizations after the EP=1
no-op change: 6 passed.
- Affected custom-model CUDA suite: 24 passed, 3 skipped across AFMoE,
GLM, GPT-OSS, Nemotron, Qwen3/Qwen3.5, and state loading.
- Final H200 model suite after execution-path cleanup: 81 passed, 3
skipped (Slurm 2597).
- Torch EP on two H200 GPUs passed with BF16 and DeepGEMM FP8, top-k 2,
both score locations, shared experts, gated/non-gated/bias variants,
uneven routing, a rank receiving zero routed tokens, and
input/router/expert gradients.
- Final Torch EP BF16 and DeepGEMM FP8 matrix passed after the cleanup
(Slurm 2596).
- DeepEP on two H200 GPUs passed with BF16 and DeepGEMM FP8, chunking
on/off, both score locations, shared experts, a rank receiving zero
routed tokens, and gradients.
- Final DeepEP BF16 and DeepGEMM FP8 matrix passed after the cleanup
(Slurm 2595).
- Parent-owned shared-expert construction: 16 focused CPU tests and 64
H200 model tests passed, with 3 expected skips (Slurm 2600).
- Full-graph MoE and shared `FeedForward` compile validation passed
after the ownership cleanup (Slurm 2601).
- Local DeepGEMM FP8 passed across all supported topology, activation,
and bias combinations.
- `torch.compile(fullgraph=True)` forward/backward passed for the full
MoE and shared `FeedForward` across all supported topology/activation
combinations.
- Single-rank DCP and Torch EP + FSDP DCP model/optimizer resume passed.
- The `mxfp8_moe` wheel build includes its public module, manifest, and
license; the module imports against the pinned torchao build.
- Unsupported H200 MXFP8 selection fails before model mutation.
- Review audit: every queued DeepEP combine event is now synchronized,
including chunked execution (two-H200 Slurm 2604).
- Dispatcher review cleanup passed on two H200s: DeepEP BF16/DeepGEMM
with chunking and a zero-receive rank (Slurm 2847), plus Torch EP
topology/bias/zero-receive coverage (Slurm 2848).
- The exact `reverse_text_moe` integration passed end-to-end on two
H200s with an isolated conversion cache (Slurm 2607).
- Conversion ranks now make the create decision on master and validate
`.prime-v1` only after the final all-rank barrier.
- Canonical router selection bias: 12 CPU MoE/conversion tests passed;
CUDA checkpoint loading, Nemotron, and GLM model tests passed, with the
existing GLM BF16 gradient comparison passing on isolated rerun after
one threshold-edge miss (Slurm 2851/2852).
- Ruff, Ruff formatting, compileall, and `git diff --check` passed.

## Deliberate exclusions

- MultiLoRA is not adapted to the new runtime and may fail.
- Fused-MoE trainer integration is removed and will be reconsidered only
after the canonical runtime is finalized.
- Routed-expert selective activation checkpointing is removed; the
remaining selective targets are unchanged.

## Remaining before marking ready

- Run numerical MXFP8 grouped-GEMM and MXFP8 Torch EP transport
forward/backward on SM100 hardware. The available Slurm fleet currently
has only H200 nodes.
- Merge prime-kernels PR #1, publish wheels containing `mxfp8_moe`, and
update the `pyproject.toml`/lock wheel pins. The currently pinned v0.8.0
wheel does not contain this module.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> This changes the MoE forward/backward path, expert-parallel dispatch,
checkpoint key layout, and trainer TOML in breaking ways across all
custom MoE models.
> 
> **Overview**
> **Breaking trainer config:** MoE is configured via
`[trainer.model.moe.compute]` (`bf16`, `deepgemm_fp8`, `mxfp8`) and
`[trainer.model.moe.dispatch]` (`torch` with `transport`, or `deepep`
with `num_sms` / `token_chunk_size`). Dense
`[trainer.model.quantization]` no longer drives expert GEMMs or EP
transport. Removed flags include `ep_comm_backend`, `deepep_*`,
`moe_use_grouped_mm`, `moe_fused_kernel`, and quantization
`enable_grouped_gemm` / `enable_a2a`.
> 
> **Unified MoE execution:** All custom models share one `MoE`
path—`TokenChoiceTopKRouter`, stacked `GroupedExperts` (`gate_proj` /
`up_proj` / `down_proj`), and a pluggable `TokenDispatcher`
(`LocalTokenDispatcher`, `TorchTokenDispatcher`,
`MXFP8TorchTokenDispatcher`, `DeepEPTokenDispatcher`).
`configure_moe_runtime` wires grouped GEMM backends and dispatch at
setup; EP weight sharding is only `ExpertWeightParallel`. DeepEP
dispatch/combine, grouped-GEMM permutation, and chunk pipelining live in
the new dispatcher layer instead of ad hoc `MoE` hooks.
> 
> **Checkpoint and model surface:** PrimeRL checkpoints rename routed
weights from `w1/w2/w3` to `gate/down/up_proj`, move selection bias to
`mlp.router.selection_bias`, and add GPT-OSS HF↔prime conversion.
`LatentMoE` / Nemotron-specific expert classes are folded into the
canonical tree; dense layers use `FeedForward`. Reusable `prime`
conversion caches must include a `.prime-v1` marker.
> 
> **Removed / docs:** Fused `flash_moe` trainer integration and
`bench_fused_moe.py` are dropped; `routed_experts` selective activation
checkpointing is removed. Docs and examples (e.g. GLM-5) are updated for
the new tables.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ffd5be7d48d28b889f9d73c8815ab0eb618b9dc9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-29 01:03:32 +02:00
Yaser AfsharandGitHub 66e1c2cb07 chore(nixl): use canonical VRAM mem_type (#3215)
## Change

`prep_xfer_dlist(mem_type=...)` passed `"cuda"`, which nixl marks
deprecated in
favor of `"VRAM"` (`src/api/python/_api.py`):

    "VRAM": nixlBind.VRAM_SEG,
    "cuda": nixlBind.VRAM_SEG,  # deprecated

Both resolve to `VRAM_SEG`, so this is a no-op at runtime. `"VRAM"` is
also the
spelling nixl's own `_tensor_mem_type()` helper emits.

## Note

The accelerator-derived `UCX_TLS` defaults this PR originally carried
are dropped
per review. Since `set_ucx_env_defaults()` uses `setdefault`, a non-CUDA
accelerator supplies its own copy transport from the launcher
environment.

---------

Signed-off-by: Yaser Afshar <yaser.afshar@intel.com>
2026-08-29 00:27:17 +02:00
Matej SirovatkaandGitHub 26af0c49e6 perf(nixl): pipeline reusable weight pulls (#3341)
## Summary

- use ModelExpress only for startup peer discovery and the trainer
tensor table, then use exact versioned NIXL notifications for all policy
transfers, including startup
- prepare static NIXL READ requests once, repost them after completion,
and post every trainer-rank pull in a group before waiting
- attach trainer arena credits to READ completion instead of performing
a separate acknowledgement handshake
- add explicit, opt-in two-arena overlap through
`weight_broadcast.overlap_transfer_and_replay`

The path remains receiver-driven PULL. The default remains one arena
because the second arena has a model-dependent GPU-memory cost. This PR
adds no fallback protocol, runtime sizing heuristic, profiling
instrumentation, or inference-scheduler change.

## Protocol

ModelExpress is the one-time startup discovery plane. It exchanges the
trainer tensor table and NIXL agent metadata, after which the fixed
peers establish NIXL/UCX connections. The shared
`WeightSender`/`WeightReceiver` sentinel handshake offers and
acknowledges every policy version before the NIXL transport runs; this
is the same outer lifecycle used by the other transports. MX source
statuses are not used. Policy 0 and later policies use exact NIXL ready
and complete notifications for the transfer itself.

```mermaid
sequenceDiagram
    participant T as Trainer ranks
    participant B as Broadcast directory
    participant R as NIXL weight receiver
    participant MX as ModelExpress
    participant I as Inference ranks

    Note over T,I: One-time setup
    I->>MX: Publish inference NIXL metadata
    R->>MX: Publish receiver NIXL metadata

    loop Each policy version
        T->>B: Offer version with sender ready marker
        R->>B: Acknowledge with receiver ready marker
        T->>B: Mark transfer started
        alt First version
            T->>MX: Publish tensor table and trainer metadata
            T->>MX: Fetch inference and receiver metadata
            R->>MX: Fetch trainer table and metadata
            Note over T,I: Establish NIXL and UCX connections once
        end
        T-->>R: NIXL policy ready notification
        R->>I: Update weights
        loop Each transfer group
            T-->>I: NIXL group ready notification
            I->>T: Post READs to every trainer rank
            T-->>I: RDMA payload
            I-->>T: READ completion returns arena credit
        end
        I-->>R: Update complete
        R-->>T: NIXL policy complete notification
        T->>B: Commit version with finished marker
    end
```

Each group signal contains `(group index, generation)`, and each policy
signal contains `(step, event)`, so it is consumed exactly once. A
trainer staging slot is reused only after every inference rank completes
its READ from that slot.

`NIXLWeightReceiver` owns the ModelExpress discovery session, local NIXL
agent, and typed trainer peer in the orchestrator process. The generic
orchestrator and `WeightWatcher` only use the `WeightReceiver` API and
contain no NIXL-specific state. Transfer plans and the trainer
broadcaster store ordered `NixlPeer` lists, so positional trainer-agent
indices stay direct list lookups and raw NIXL agent names remain inside
the adapter. On the trainer, `finish_transfer_group` waits for every
inference rank to complete a group before advancing its generation and
allowing its arena slot to be reused.

Tensor addresses, shard routes, peers, and descriptor lists remain
static for the worker lifetime. Requests are therefore prepared once and
reposted after completion. For each group, inference waits for every
serving trainer rank, posts all trainer-rank READs, and then waits for
completion. Inference ranks rotate their trainer order, while #3340 pins
each process to the active InfiniBand port nearest its GPU.

With overlap enabled, trainer and inference allocate exactly two
largest-group-sized arenas. Inference replays and quantizes group N
while receiving group N+1. Allocation is explicit: there is no
free-memory probe, automatic downgrade, or hidden retry.

## Measured results

Every populated cell below is the median of the positive framework
`time/broadcast_weights` samples; terminal zero entries are excluded.
This is the only timing definition used in the description. Parentheses
contain Slurm job IDs, and blank cells mean that configuration was not
measured.

| Model | Old NIXL | New NIXL | New NIXL + overlap | NCCL |
|---|---:|---:|---:|---:|
| Qwen3-30B-A3B | 4.651 s (2260) | 1.898 s (2278) |  |  |
| GLM-4.5-Air | 8.676 s (2286) | 4.125 s (2288) | 3.043 s (2305) | 7.616
s (2289) |
| GLM-5.2 |  | 12.513 s (2297) | 8.577 s (2317, EP32) |  |

All NIXL baselines use the correct rail pinning, and router replay is
disabled. The GLM-4.5-Air old, new, and overlap measurements are 20-step
Hendrycks-math runs with 4096 maximum sampling tokens; the NCCL
comparison uses the same model and node roles over three positive
broadcasts. NCCL uses BF16 checkpoint-format transfer with
`quantize_in_weight_transfer = false`.

GLM-5.2 job 2317 completed 20 rollout steps and 18 steady trainer
broadcasts on 64 trainer and 32 inference H200s. Framework
`time/broadcast_weights` was 8.577s median and 12.987s p95. At the
inference client, end-to-end synchronization was 7.899s median and
12.577s p95: pause was 5.204s median / 9.882s p95, while the weight
update itself was 2.842s median / 2.960s p95. Each inference GPU
received 82.501 GB per policy; across all 576 rank/version samples, RDMA
was 1.864s median / 2.027s p95, replay was 1.954s median / 1.993s p95,
and their overlapped process time was 2.682s median / 2.836s p95. Median
payload was 44.26 GB/s per GPU, or approximately 354 GB/s across an
eight-GPU inference node. The [W&B
run](https://wandb.ai/primeintellect/prime-rl/runs/c3bee790465640d88958f100fb3d74f4)
contains the completed training metrics.

On this single framework metric, Qwen improves by 59.2% from old to new.
GLM-4.5-Air improves by 52.5% from old to new and 64.9% from old to the
final overlapped path; the final path is 60.1% faster than NCCL. GLM-5.2
improves by 31.5% from the measured EP16 one-arena path to the EP32
overlap run. Holding overlap constant, EP32 reduces median framework
broadcast time by 11.4% from the EP16 result (9.683s, job 2301), while
median client update time falls by 19.4% from 3.524s to 2.842s.
Framework timing includes the unchanged vLLM pause/resume interval,
whose variance dominates the EP32 tail, so it should not be interpreted
as raw fabric bandwidth.

## Memory and scope

Overlap adds one largest-group arena rather than another model copy. For
GLM-5.2, that is 0.308 GB per trainer GPU and 3.807 GB per inference
GPU. The EP32 run therefore used a 7.613 GB two-buffer arena per
inference GPU and added 141.5 GB across the tested
64-trainer/32-inference topology. The option is disabled by default;
models without that headroom retain the one-arena path.

GLM-5.2 uses 64 trainer H200s with EP=8 and full offload, plus DP/EP
inference with online blockwise FP8 and DeepGEMM. EP16 receives 127.800
GB per inference GPU and retains 5,056 host-side handles per rank; EP32
receives 82.501 GB per GPU and prepares 72,819 descriptors across 79
transfer groups per rank. These request structures add no model-sized
GPU allocation.

Every serving trainer rank connects to every inference rank so
completion returns exact source credits. Static membership is the
expected hot path; elastic scaling and fault tolerance remain out of
scope.

## Numerical validation

Jobs 2286 and 2305 completed the configured 20 GLM-4.5-Air rollout steps
and finalized metrics. Step 20 of job 2305 contained 0/8 trainable
traces, so it correctly emitted no optimizer or mismatch-KL row. Across
the 19 steps with measurements in both runs, mean mismatch KL was
0.002602538 before and 0.002608075 after (+0.2%); median was 0.002786405
before and 0.002702605 after (-3.0%). Router replay was deliberately
disabled, so individual steps include normal sampling variation.

## Validation

- Ruff 0.15.14: `uv run ruff format --check` and `uv run ruff check`
- `uv run python -m compileall` on changed Python modules
- `uv run pytest -q tests/unit/test_configs.py`
- ported onto main at `21a4a3245` through #3340 at `0d809b1e4`; the
generic orchestrator and `WeightWatcher` are unchanged
- two-node, three-step Qwen3-0.6B end-to-end NIXL smoke (Slurm job
2451): startup policy v0 and policies v1-v3 synchronized; trainer and
orchestrator completed
- Qwen3-30B-A3B and GLM-4.5-Air eight-rail transfer benchmarks
- GLM-5.2 ten-node EP16 and twelve-node EP32 runs with full trainer
offload, online blockwise FP8 inference, and DeepGEMM
- matched NCCL comparison on GLM-4.5-Air
- final 20-step GLM-4.5-Air Hendrycks-math run with 4096 sampling tokens
and router replay disabled

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes core distributed weight-sync choreography between trainer,
orchestrator, and vLLM; mis-sync would cause stale weights or hangs,
though scope is limited to the NIXL transport path.
> 
> **Overview**
> **NIXL weight broadcast** is reworked so ModelExpress is only used for
one-time peer discovery (trainer tensor table and NIXL agent metadata).
Per-group and per-policy coordination now uses **versioned NIXL
notifications** instead of ModelExpress READY/INITIALIZING buffer
sessions.
> 
> The NIXL adapter gains **`PreparedRead`** / **`NixlPeer`**: READ
descriptor lists are prepared once, reposted each update, and all
trainer-rank pulls in a group are posted before waiting. Arena reuse is
tied to READ completion via group `(index, generation)` signals; the
orchestrator participates with policy `ready` / `complete` notifications
over NIXL.
> 
> Inference follows the trainer’s **`staging_buffer_count`** (no GPU
free-memory sizing heuristic). Optional
**`weight_broadcast.overlap_transfer_and_replay`** allocates exactly
**two** largest-group arenas on trainer and inference so the next group
can be received while the current one is replayed; default remains one
arena.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0dc85f865aa7850e5a123fbb2791a9670c631d44. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-28 23:04:08 +02:00
Matej SirovatkaandGitHub fc12ef2c66 feat(slurm): launch ModelExpress for NIXL transfers (#3340)
## Summary

- start a job-scoped Redis and ModelExpress service when
`slurm.launch_modelexpress = true`
- inject the trainer-head service address into trainer, inference, and
orchestrator processes, or use the configured host when
`slurm.launch_modelexpress = false`
- pin every NIXL process to the active InfiniBand HCA nearest its GPU,
so an eight-GPU node uses all eight rails
- add a pinned, idempotent installer for ModelExpress v0.3.0 and Redis
7.4.2
- remove stale job-scoped ModelExpress and Redis processes before
managed-service startup

This is the launch prerequisite for the stacked transfer optimization in
#3341. It does not change the NIXL transfer protocol itself.

## Design

With `slurm.launch_modelexpress = true`, the generated job removes stale
ModelExpress and Redis processes from an interrupted managed launch,
then starts both services on the trainer head before launching the three
prime-rl components. The resolved ModelExpress address is passed to
every component, and service logs stay in the run directory. With
`slurm.launch_modelexpress = false`, the launcher performs no service
cleanup, starts no service, and uses `weight_broadcast.host` and
`weight_broadcast.port` unchanged.

Rail selection remains local to each NIXL process. Unless
`UCX_NET_DEVICES` is explicitly configured, startup resolves the process
GPU's PCI path, selects the nearest active InfiniBand port, and
constrains UCX to that port. TP8 therefore uses one distinct local rail
per GPU instead of relying on UCX's cluster-dependent default choice.
`UCX_NET_DEVICES` remains an explicit site override.

The installer pins both service versions, verifies their checksums, and
reuses valid existing installations. Generated jobs fail directly if a
required binary or UCX capability is missing.

## Scope

- ModelExpress provides startup discovery for a fixed Slurm allocation.
- Elastic discovery, autoscaling, and fault tolerance are intentionally
out of scope.
- The local service adds two small CPU processes on the trainer head and
no GPU allocation.

## Validation

- `bash -n scripts/install_modelexpress.sh`
- ran `scripts/install_modelexpress.sh` twice and verified that the
pinned binaries are reused
- rebased onto `main` at `21a4a3245`; rendered and shell-checked managed
and external ModelExpress modes for single-node and multi-node NIXL
Slurm jobs, including main’s trainer/orchestrator completion markers
- verified stale-service cleanup is present only in managed ModelExpress
renders and absent in external-service renders
- Ruff 0.15.14: `uv run ruff format --check` and `uv run ruff check`
- `uv run python -m compileall` on changed Python modules
- `uv run pytest -q tests/unit/test_configs.py` (122 passed)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes multi-node SLURM launch and NIXL UCX/IB selection for weight
sync; misconfiguration or rail selection bugs could break or degrade
policy updates, but scope is limited to NIXL SLURM paths.
> 
> **Overview**
> Adds **job-scoped ModelExpress + Redis** startup for SLURM RL when
`[weight_broadcast] type = "nixl"` and **`slurm.launch_modelexpress`**
is true (default). Single- and multi-node sbatch templates verify the
**`third_party/ucx`** build, optionally start pinned
**modelexpress-server** / **redis-server** (new
**`scripts/install_modelexpress.sh`**), wait for readiness, and pass
**`--weight-broadcast.host`** into trainer, orchestrator, and the local
`rl` launcher. With **`launch_modelexpress = false`**, jobs use
configured **`weight_broadcast.host`** / **`port`** and skip
managed-service cleanup.
> 
> **NIXL networking** now picks **`UCX_NET_DEVICES`** per process from
the **InfiniBand port nearest each GPU** (unless already set), and
inference workers **rotate which trainer ranks they pull from** so
concurrent pulls spread across rails.
> 
> Docs and the start-run skill describe install steps and the new SLURM
flag. **Does not change the NIXL transfer protocol** (prerequisite for
stacked transfer work).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0d809b1e4d24121690faab3a22b1f7f832de4f53. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-28 22:43:22 +02:00
Mika SenghaasandGitHub 95734aa1dd feat: make ipo the default rl loss (#3418)
## Summary

- Remove the DPPO loss and make IPO the default RL loss.
- Rename the IPO trust-region setting from `ipo_threshold` to `eps`.
- Update token exports, metrics, docs, tests, and agent skills for IPO.

## Breaking

- Remove `[trainer.loss] type = "default"`, `DefaultLossConfig`, and
`default_loss_fn`. Omit `[trainer.loss]` or set `type = "ipo"`.
- Rename `ipo_threshold` to `eps`. Update all IPO loss configs to use
`eps`.
- Remove the DPPO-only `dppo_mask_low` and `dppo_mask_high` settings.
- Remove the DPPO-only `is_masked_low`, `is_masked_high`, and
`masked_advantage_*` trainer metrics. Use `is_masked` for the IPO
trust-region mask.

## Verification

- RL loss GPU tests: 10 passed.
- Nemotron-H KL pipeline GPU tests: 7 passed.
- Ruff check and format hooks passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Removes the default RL loss and changes default training dynamics for
every run that relied on implicit DPPO; configs using `type = "default"`
or DPPO fields will fail or need migration.
> 
> **Overview**
> Makes **Importance Policy Optimization (IPO)** the only built-in RL
loss and the default when `[trainer.loss]` is omitted. The DPPO-based
`default` loss (`DefaultLossConfig`, `default_loss_fn`, `dppo_mask_low`
/ `dppo_mask_high`) is removed.
> 
> IPO trust-region config is renamed from `ipo_threshold` to **`eps`**
(default `0.1`). `setup_rl_loss_fn` always routes non-custom configs to
`ipo_loss_fn`.
> 
> **Breaking for configs:** use `type = "ipo"` or omit the section;
`type = "default"` and DPPO knobs no longer exist.
> 
> Monitoring and exports align with symmetric IPO masking: docs/skills
point to **`is_masked/mean`** instead of DPPO `masked_advantage_*`
metrics; W&B filtering drops the old DPPO-only series; token export
computes mask flags from `|prob_delta| > eps`. Unit tests now exercise
IPO instead of the default loss.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
2c4227527992519e8ff7e1d08c8866c5068febb1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-27 11:35:01 -07:00
124 changed files with 4193 additions and 5696 deletions
-155
View File
@@ -1,155 +0,0 @@
name: Build Kernels
# Builds the `prime-kernels` wheel for x86_64 and aarch64 from the deps/prime-kernels submodule.
# Runs on every bump of that submodule to catch build breakage, and with `release_tag` to
# attach the wheels to a GitHub release — which is how they are consumed (see the `kernels`
# skill).
#
# `tag-and-release.yaml` calls this for every release, before it promotes the draft, so a
# published release always carries the wheels its `[tool.uv.sources]` pin can point at.
# `workflow_dispatch` does the same by hand, for backfilling an already published release.
#
# No GPU is needed: nvcc cross compiles for the architectures kernels.toml declares.
on:
pull_request:
paths:
- "deps/prime-kernels"
- ".gitmodules"
- ".github/workflows/build_kernels.yaml"
push:
branches: [main]
paths:
- "deps/prime-kernels"
- ".gitmodules"
- ".github/workflows/build_kernels.yaml"
workflow_dispatch:
inputs:
release_tag:
description: "Existing release tag to attach the wheels to (e.g. v0.7.0). Empty = artifacts only."
required: false
type: string
ref:
description: "Ref to build the kernels from. Empty = the ref the workflow was started on."
required: false
type: string
workflow_call:
inputs:
release_tag:
description: "Release tag to attach the wheels to. The release may still be a draft."
required: false
type: string
ref:
description: "Ref to build the kernels from. Empty = the caller's ref."
required: false
type: string
env:
# Keep in sync with the CUDA the prime-rl image is built against (Dockerfile.cuda);
# the job container image below must be edited alongside it (no env context there).
CUDA_TAG: cu128
jobs:
build:
name: Build wheel (${{ matrix.arch }})
# Uploading the wheels to a release needs write; on workflow_call the caller
# must grant it too (tag-and-release.yaml does).
permissions:
contents: write
strategy:
fail-fast: false
matrix:
include:
- runner: image-builder
arch: x86_64
- runner: image-builder-arm-2204
arch: aarch64
runs-on: ${{ matrix.runner }}
container: nvidia/cuda:12.8.1-devel-ubuntu24.04
steps:
- name: Install build tooling
run: |
apt-get update
apt-get install -y --no-install-recommends git curl ca-certificates build-essential gh
- name: Checkout
uses: actions/checkout@v5
with:
submodules: false
ref: ${{ inputs.ref }}
# deps/prime-kernels is the prime-kernels submodule and carries every kernel's sources.
- name: Init the kernels submodule
run: |
git config --global --add safe.directory "$GITHUB_WORKSPACE"
git submodule update --init -- deps/prime-kernels
- name: Install uv
run: |
curl -LsSf https://astral.sh/uv/install.sh | env INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR=/usr/local/bin sh
uv --version
# The wheel only imports under the exact torch it was compiled against, so build
# against the torch prime-rl resolves rather than whatever is newest today.
- name: Create build environment
env:
UV_TORCH_BACKEND: ${{ env.CUDA_TAG }}
run: |
TORCH_PIN=$(grep -A1 '^name = "torch"$' uv.lock | sed -n 's/^version = "\([^"+]*\).*"$/\1/p' | head -n1)
if [ -z "$TORCH_PIN" ]; then
echo "Could not read torch's version from uv.lock" >&2
exit 1
fi
echo "Building against torch==$TORCH_PIN"
uv venv --python 3.12 /tmp/build-env
VIRTUAL_ENV=/tmp/build-env uv pip install "torch==$TORCH_PIN" setuptools wheel ninja
# torch C++ extensions are bound to the torch and CUDA they were compiled against, so
# the wheel carries both in its local version.
- name: Stamp ABI into the version
run: |
TORCH_VERSION=$(/tmp/build-env/bin/python -c 'import torch; print(torch.__version__.split("+")[0])')
LOCAL="${CUDA_TAG}torch${TORCH_VERSION}"
sed -i -E "s/^version = \"([^\"]+)\"$/version = \"\1+${LOCAL}\"/" deps/prime-kernels/pyproject.toml
grep '^version' deps/prime-kernels/pyproject.toml
- name: Build wheel
env:
VIRTUAL_ENV: /tmp/build-env
CUDA_HOME: /usr/local/cuda
PRIME_KERNELS_REQUIRE: "1"
MAX_JOBS: "8"
run: uv build --wheel --no-build-isolation --out-dir dist deps/prime-kernels
- name: Inspect wheel
run: |
ls -lh dist/
/tmp/build-env/bin/python - <<'PY'
import pathlib, zipfile
wheel = next(pathlib.Path("dist").glob("*.whl"))
extensions = [n for n in zipfile.ZipFile(wheel).namelist() if n.endswith(".so")]
assert extensions, f"{wheel.name} contains no compiled kernels"
print(wheel.name, *extensions, sep="\n ")
PY
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: prime-kernels-${{ matrix.arch }}
path: dist/*.whl
if-no-files-found: error
- name: Attach to release
if: inputs.release_tag != ''
env:
GH_TOKEN: ${{ github.token }}
# gh must not resolve the repo from the checkout: inside the container the
# workspace is owned by another uid, which git rejects as dubious ownership.
GH_REPO: ${{ github.repository }}
TAG: ${{ inputs.release_tag }}
run: |
gh release upload "$TAG" dist/*.whl --clobber
# The `[tool.uv.sources]` pin has to name the wheel exactly, ABI suffix and all.
WHEEL=$(basename dist/*.whl)
URL="https://github.com/${GITHUB_REPOSITORY}/releases/download/${TAG}/${WHEEL}"
echo "\`{ url = \"$URL\", marker = \"platform_machine == '${{ matrix.arch }}'\" },\`" >> "$GITHUB_STEP_SUMMARY"
+2 -24
View File
@@ -113,21 +113,8 @@ jobs:
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$NEW_VERSION" >> "$GITHUB_OUTPUT"
# Wheels are attached while the release is still a draft, so it is never published without
# them — `[tool.uv.sources]` pins prime-kernels at a release asset, and an install that
# resolves to a wheel-less release would fall back to compiling CUDA from source.
kernels-from-auto-tag:
needs: auto-tag-on-main
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
permissions:
contents: write
uses: ./.github/workflows/build_kernels.yaml
with:
release_tag: ${{ needs.auto-tag-on-main.outputs.tag }}
ref: ${{ needs.auto-tag-on-main.outputs.tag }}
release-from-auto-tag:
needs: [auto-tag-on-main, kernels-from-auto-tag]
needs: auto-tag-on-main
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
runs-on: ubuntu-latest
permissions:
@@ -219,17 +206,8 @@ jobs:
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
kernels-from-tag:
needs: resolve-release
permissions:
contents: write
uses: ./.github/workflows/build_kernels.yaml
with:
release_tag: ${{ needs.resolve-release.outputs.tag }}
ref: ${{ needs.resolve-release.outputs.tag }}
publish-release:
needs: [resolve-release, kernels-from-tag]
needs: resolve-release
runs-on: ubuntu-latest
permissions:
contents: write
+10 -23
View File
@@ -6,7 +6,7 @@
# Every pyproject.toml + uv.lock, so the dependency sync below caches
# independently of source edits.
FROM nvidia/cuda:12.8.1-base-ubuntu24.04 AS manifests
FROM nvidia/cuda:13.0.1-base-ubuntu24.04 AS manifests
# .git is ~735 MB, changes every commit, and would land in the registry cache.
COPY --exclude=.git . /ctx
RUN mkdir -p /manifests \
@@ -15,7 +15,7 @@ RUN mkdir -p /manifests \
&& cp uv.lock /manifests/
# Build stage - multi-arch base (supports amd64 + arm64)
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu24.04 AS builder
FROM nvidia/cuda:13.0.1-cudnn-devel-ubuntu24.04 AS builder
LABEL maintainer="prime intellect"
LABEL repository="prime-rl"
@@ -150,8 +150,8 @@ RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
&& PKG_CONFIG_PATH=/opt/ucx/lib/pkgconfig \
LD_LIBRARY_PATH=/opt/ucx/lib:/opt/ucx/lib/ucx \
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/app/deps \
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /app/deps/nixl_cu12-*.whl \
&& rm -rf /tmp/nixl /app/deps/nixl_cu12-*.whl; \
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /app/deps/nixl_cu13-*.whl \
&& rm -rf /tmp/nixl /app/deps/nixl_cu13-*.whl; \
fi
# Trim the CUDA toolkit to the nvcc-JIT essentials in a separate stage, so the runtime
@@ -161,19 +161,14 @@ RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
# (uses pinned nvidia-* wheels) needs them. Keeps nvcc/nvvm/ptxas + headers +
# libcudart/libnvrtc/libcudadevrt for JIT compile+link.
FROM builder AS cuda-trim
RUN find /usr/local/cuda-12.8/targets/*/lib \
RUN find /usr/local/cuda-13.0/targets/*/lib \
\( -name 'libcublas*' -o -name 'libcusparse*' -o -name 'libcufft*' \
-o -name 'libcusolver*' -o -name 'libcurand*' -o -name 'libnpp*' \
-o -name 'libnvjpeg*' -o -name 'libnvblas*' \) -delete \
&& find /usr/local/cuda-12.8 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
# CUDA 13 runtime libs source
FROM nvidia/cuda:13.0.1-runtime-ubuntu24.04 AS cuda13
RUN mkdir -p /cu13 && cp -d $(find /usr/local \
-name 'libcudart.so.13*' -o -name 'libnvrtc.so.13*' -o -name 'libnvrtc-builtins.so.13*') /cu13/
&& find /usr/local/cuda-13.0 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
# Runtime image
FROM nvidia/cuda:12.8.1-base-ubuntu24.04
FROM nvidia/cuda:13.0.1-base-ubuntu24.04
ENV DEBIAN_FRONTEND=noninteractive
@@ -207,20 +202,12 @@ RUN apt-get update && apt-get install -y \
&& apt-get clean autoclean \
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# CUDA 12.8 toolkit (TileLang's runtime nvcc JIT)
COPY --from=cuda-trim /usr/local/cuda-12.8 /usr/local/cuda-12.8
RUN ln -sfn /usr/local/cuda-12.8 /usr/local/cuda && test -x /usr/local/cuda/bin/nvcc
# CUDA 13.0 toolkit (TileLang's runtime nvcc JIT)
COPY --from=cuda-trim /usr/local/cuda-13.0 /usr/local/cuda-13.0
RUN ln -sfn /usr/local/cuda-13.0 /usr/local/cuda && test -x /usr/local/cuda/bin/nvcc
ENV CUDA_HOME=/usr/local/cuda
ENV PATH="/usr/local/cuda/bin:${PATH}"
# CUDA 13 runtime libs for deep-gemm
COPY --from=cuda13 /cu13/ /opt/cuda13/lib64/
RUN echo /opt/cuda13/lib64 > /etc/ld.so.conf.d/cuda13.conf \
&& ldconfig \
&& ldconfig -p | grep -q libcudart.so.13 \
&& ldconfig -p | grep -q libnvrtc.so.13
ARG USER_ID=1000
ARG GROUP_ID=1000
@@ -6,43 +6,46 @@
"lora_rank": null,
"seq_len": 65536,
"ac": "Recompute",
"selective_targets": null,
"attention": "flash_attention_2",
"output": "benchmark_result.json",
"output": "benchmarks/baselines/benchmark-1xa6000-Qwen--Qwen3-0.6B-rl-full-1gpu-Recompute-flash_attention_2-65536-cp1-ep1.json",
"dry_run": false,
"timeout": 1500,
"timeout": 600,
"max_steps": 4,
"micro_batches": 2,
"ep": 1,
"cp": 1,
"fused_lm_head_token_chunk_size": 1024,
"docker_image": null,
"device_name": "NVIDIA RTX A6000",
"commit_sha": "c88d08fdf",
"timestamp": "2026-06-24T22:50:40+00:00",
"commit_sha": "7007d2ef",
"timestamp": "2026-08-29T02:35:31.543870+00:00",
"success": true,
"error_reason": null,
"time_taken": 276.12556480802596
"time_taken": 295.5118532651104
},
"metrics": {
"mfu": {
"mean": 20.802552047875178,
"std": 0.16199364988631793,
"min": 20.664358307416567,
"max": 20.98082222151257
"mean": 16.701924322664684,
"std": 0.0999595293790186,
"min": 16.586575698092034,
"max": 16.763194274056005
},
"throughput": {
"mean": 2484.411208996455,
"std": 19.346608946709658,
"min": 2467.9069802355616,
"max": 2505.7016937694384
"mean": 1994.6806480062144,
"std": 11.937986005933869,
"min": 1980.9047701633856,
"max": 2001.998007610024
},
"step_time": {
"mean": 52.79691480938345,
"std": 0.4071756223542672,
"min": 52.35017399210483,
"max": 53.14720633160323
"mean": 65.74198961785685,
"std": 0.3962098986964774,
"min": 65.49867434287444,
"max": 66.19917749473825
},
"peak_memory": {
"gib": 11.728515625,
"pct": 24.742767157118376
"gib": 11.591145833333334,
"pct": 24.45296844104
}
}
}
}
@@ -6,43 +6,46 @@
"lora_rank": null,
"seq_len": 65536,
"ac": "Recompute",
"selective_targets": null,
"attention": "flash_attention_2",
"output": "benchmark_result.json",
"output": "benchmarks/baselines/benchmark-4xa6000-Qwen--Qwen3-0.6B-rl-full-4gpu-Recompute-flash_attention_2-65536-cp1-ep1.json",
"dry_run": false,
"timeout": 1500,
"timeout": 600,
"max_steps": 4,
"micro_batches": 2,
"ep": 1,
"cp": 1,
"fused_lm_head_token_chunk_size": 1024,
"docker_image": null,
"device_name": "NVIDIA RTX A6000",
"commit_sha": "c88d08fdf",
"timestamp": "2026-06-24T22:55:54+00:00",
"commit_sha": "7007d2ef",
"timestamp": "2026-08-29T02:28:40.728120+00:00",
"success": true,
"error_reason": null,
"time_taken": 291.91085167229176
"time_taken": 317.33935201819986
},
"metrics": {
"mfu": {
"mean": 17.217465998339005,
"std": 0.02905058130694137,
"min": 17.19503698271855,
"max": 17.250282374540514
"mean": 15.880248465863398,
"std": 0.005915779562921215,
"min": 15.873443653590638,
"max": 15.884167926432548
},
"throughput": {
"mean": 8225.003435798719,
"std": 13.877833769765575,
"min": 8214.288808538377,
"max": 8240.68023789224
"mean": 7586.197539502296,
"std": 2.826043462792163,
"min": 7582.946793757898,
"max": 7588.069915881657
},
"step_time": {
"mean": 63.90305413212627,
"std": 0.11015530079183487,
"min": 63.77801387012005,
"max": 63.985770548693836
"mean": 69.21047159920757,
"std": 0.022114607283211834,
"min": 69.19065106380731,
"max": 69.234325167723
},
"peak_memory": {
"gib": 6.298828125,
"pct": 13.288163877053583
"gib": 8.55078125,
"pct": 18.038939985655993
}
}
}
}
-113
View File
@@ -1,113 +0,0 @@
#!/usr/bin/env python3
"""
Time the routed-expert compute three ways: the fused MoE kernel (bf16 and mxfp8) against
the grouped-mm path a `model.moe_fused_kernel=false` run takes.
Forward and backward are timed separately, because only the forward is a kernel — the
backward is prime-rl's own closed-form bf16 gradients or, for mxfp8, autograd through the
grouped-mm reference. A speedup on the forward can be spent again on the backward.
uv run benchmarks/scripts/bench_fused_moe.py
uv run benchmarks/scripts/bench_fused_moe.py --tokens 16384 --num-experts 128
"""
from __future__ import annotations
import argparse
import torch
from prime_rl.trainer.models.layers.moe import _FusedMoE, _load_fused_moe_kernel, _run_experts_fused_reference
MODES = ("grouped_mm", "fused_bf16", "fused_mxfp8")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--tokens", type=int, default=8192, help="routed tokens (batch * seq)")
parser.add_argument("--dim", type=int, default=2048, help="model dim; must be a multiple of 256")
parser.add_argument("--hidden-dim", type=int, default=768, help="expert intermediate size; multiple of 128")
parser.add_argument("--num-experts", type=int, default=64)
parser.add_argument("--top-k", type=int, default=8)
parser.add_argument("--iters", type=int, default=20)
parser.add_argument("--warmup", type=int, default=5)
return parser.parse_args()
def make_inputs(args: argparse.Namespace) -> tuple[torch.Tensor, ...]:
torch.manual_seed(0)
randn = lambda *shape: torch.randn(*shape, device="cuda", dtype=torch.bfloat16)
x = (randn(args.tokens, args.dim) * 0.2).requires_grad_(True)
w1 = (randn(args.num_experts, args.hidden_dim, args.dim) * 0.05).requires_grad_(True)
w3 = (randn(args.num_experts, args.hidden_dim, args.dim) * 0.05).requires_grad_(True)
w2 = (randn(args.num_experts, args.dim, args.hidden_dim) * 0.05).requires_grad_(True)
logits = torch.randn(args.tokens, args.num_experts, device="cuda", dtype=torch.float32)
top_scores, selected = torch.softmax(logits, dim=-1).topk(args.top_k, dim=-1)
return x, w1, w2, w3, selected, top_scores.requires_grad_(True)
def run_forward(mode: str, inputs: tuple[torch.Tensor, ...], num_experts: int) -> torch.Tensor:
x, w1, w2, w3, selected, top_scores = inputs
if mode == "grouped_mm":
return _run_experts_fused_reference(x, w1, w2, w3, selected, top_scores, num_experts)
return _FusedMoE.apply(x, w1, w2, w3, selected, top_scores, num_experts, mode == "fused_mxfp8")
def time_mode(mode: str, inputs: tuple[torch.Tensor, ...], args: argparse.Namespace) -> tuple[float, float, float]:
"""Median forward ms, median backward ms, peak MiB."""
forward_ms, backward_ms = [], []
grad_out = torch.randn(args.tokens, args.dim, device="cuda", dtype=torch.bfloat16)
start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
torch.cuda.reset_peak_memory_stats()
for i in range(args.warmup + args.iters):
for tensor in inputs[:4] + (inputs[5],):
tensor.grad = None
torch.cuda.synchronize()
start.record()
out = run_forward(mode, inputs, args.num_experts)
end.record()
torch.cuda.synchronize()
if i >= args.warmup:
forward_ms.append(start.elapsed_time(end))
start.record()
out.backward(grad_out)
end.record()
torch.cuda.synchronize()
if i >= args.warmup:
backward_ms.append(start.elapsed_time(end))
median = lambda values: sorted(values)[len(values) // 2]
return median(forward_ms), median(backward_ms), torch.cuda.max_memory_allocated() / 2**20
def main() -> None:
args = parse_args()
if not torch.cuda.is_available():
raise SystemExit("no CUDA device")
kernel = _load_fused_moe_kernel()
for mxfp8 in (False, True):
reason = kernel.unsupported_shape_reason(args.dim, args.hidden_dim, mxfp8=mxfp8)
if reason is not None:
raise SystemExit(f"shape unsupported by the fused kernel: {reason}")
inputs = make_inputs(args)
print(
f"tokens={args.tokens} dim={args.dim} hidden_dim={args.hidden_dim} "
f"experts={args.num_experts} top_k={args.top_k} "
f"({args.iters} iters, {args.warmup} warmup, median)\n"
)
print(f"{'mode':<12} {'fwd ms':>9} {'bwd ms':>9} {'total ms':>9} {'speedup':>9} {'peak MiB':>10}")
baseline = None
for mode in MODES:
forward, backward, peak = time_mode(mode, inputs, args)
total = forward + backward
baseline = baseline or total
print(f"{mode:<12} {forward:>9.3f} {backward:>9.3f} {total:>9.3f} {baseline / total:>8.2f}x {peak:>10.0f}")
if __name__ == "__main__":
main()
+1 -1
+1 -1
+29 -10
View File
@@ -35,31 +35,50 @@ 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 you to set EP, CP, selective activation checkpointing, low-precision training (`[trainer.model.quantization]`), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
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.
### Low-precision training
Set `[trainer.model.quantization]` to train dense linears and MoE expert GEMMs in low precision. Two backends are available via the `type` discriminator:
Dense linear precision and routed-expert precision are configured independently. `[trainer.model.quantization]` applies only to dense `Linear` modules:
- `type = "fp8"` — DeepGEMM FP8 blockwise (requires SM90+ / Hopper). Options: `enable_grouped_gemm` (FP8 MoE expert GEMM). Both default on.
- `type = "mxfp8"` — torchao MXFP8 microscaling (requires SM100+ / Blackwell). Options: `enable_grouped_gemm`, `enable_a2a` (MXFP8 expert-parallel all-to-all), and `recipe` (`mxfp8_rceil` default or `mxfp8_rceil_wgrad_with_hp`).
- `type = "fp8"` — DeepGEMM FP8 blockwise linears (requires SM90+).
- `type = "mxfp8"` — torchao MXFP8 linears (requires SM100). `recipe` is `mxfp8_rceil` or `mxfp8_rceil_wgrad_with_hp`.
`[trainer.model.moe.compute]` selects routed-expert grouped GEMMs independently:
- `type = "bf16"` (default)
- `type = "deepgemm_fp8"` (requires DeepGEMM and SM90+)
- `type = "mxfp8"` (requires `prime-kernels`, torchao, and SM100)
```toml
[trainer.model.quantization]
type = "mxfp8"
recipe = "mxfp8_rceil"
enable_a2a = true
[trainer.model.moe.compute]
type = "mxfp8"
recipe = "mxfp8_rceil"
[trainer.model.moe.dispatch]
type = "torch"
transport = "mxfp8"
```
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
### Expert Parallelism Backends
`model.ep_comm_backend` picks the all-to-all kernel used for EP dispatch/combine:
`[trainer.model.moe.dispatch]` selects how routed tokens are dispatched and combined:
- **`torch`** (default): TorchTitan's all-to-all collective. Works everywhere, no extra install.
- **`deepep`**: Utilizes DeepEP's custom all-to-all collectives. This provides better performance if EP dimension spans multiple nodes. We provide pre-built binaries for H100/H200 with cuda runtime 12.9 installed, you can install them by running `uv sync --all-extras`.
DeepEP requires some careful tuning to achieve optimal performance, tuning parameters are `deepep_num_sms` and `deepep_token_chunk_size`.
- **`torch`** (default): torch all-to-all with `transport = "bf16"` or, when MXFP8 expert compute is selected, `transport = "mxfp8"` on SM100.
- **`deepep`**: DeepEP custom dispatch/combine kernels. Set `num_sms` and optional `token_chunk_size` in the same table. Pre-built H100/H200 binaries use CUDA 13.0 and are installed by `uv sync --all-extras`.
```toml
[trainer.model.moe.dispatch]
type = "deepep"
num_sms = 20
token_chunk_size = 4096
```
With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is set to `None` automatically.)
@@ -141,7 +160,7 @@ If prefill queues and decode is idle, add prefill nodes (and vice versa).
```bash
salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh'
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
uv pip install --reinstall --no-deps deps/nixl_cu13-*.whl
```
The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version. Re-run both commands after every `uv sync`, since the lock pins the wheel.
+14 -25
View File
@@ -13,7 +13,7 @@ This page covers the math and the configurable algorithmic components: the algor
- [Async / Off-Policy Training](#async--off-policy-training)
- [Loss](#loss)
- [Loss Components](#loss-components)
- [Default RL Loss](#default-rl-loss)
- [IPO Loss](#ipo-loss)
- [Custom Loss](#custom-loss)
- [Advantage](#advantage)
- [Default Advantage](#default-advantage)
@@ -184,47 +184,36 @@ $$
\mathcal{L} = \frac{\sum \mathcal{L}_{rl}}{N_{rl}} + \frac{\sum \mathcal{L}_{ce}}{N_{ce}} + \frac{\sum \mathcal{L}_{ref\_kl}}{N_{ref\_kl}}
$$
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
- `rl` — the configured RL loss (`[trainer.loss]`): IPO by default, or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
The orchestrator stamps each sample's component membership as per-token weight streams (`rl_weights` / `ce_weights` / `ref_kl_weights` on the wire): a weight scales that component's per-token loss, `0.0` leaves the token out of the component entirely (mask *and* denominator), and components may overlap on the same token — their gradients sum. Each $N$ is the global (all-reduced) count of that component's member tokens, so the components don't dilute each other: adding echo observation tokens never changes the rl term's effective per-token learning rate, and an sft env packed next to a GRPO env doesn't soften its gradient. Tokens of different components pack freely into the same micro batch, and a plain GRPO run ships no weight streams at all (absent streams mean rl weight 1.0 on every trainable token — the unchanged hot path). Advantages always ship per token (`advantages` on the wire), assigned as per-token streams from the start — uniform group credit is broadcast over completion tokens at assignment; algorithms with no rl credit (opd, opsd) ship none.
### Default RL Loss
### IPO Loss
The default RL loss is a DPPO policy-gradient term combined with a KL regularizer similar to Kimi-K2.5. For each prompt $x_j$ we sample a group of $G$ rollouts $\{y_i\}_{i=1}^G$, score them to get $s_i$, then optimize:
The default RL loss is Importance Policy Optimization (IPO). It combines an importance-weighted policy-gradient term with a squared log-ratio KL regularizer. A symmetric trust region removes tokens whose absolute probability change exceeds $\epsilon$:
$$
\mathcal{L}(\theta) = -\,\mathcal{J}_{\text{PG}}(\theta) \;+\; \tau_{KL}\,\mathcal{L}_{KL}(\theta)
\mathcal{L}(\theta) = \frac{1}{N}\sum_t
\left[
-\mathbb{1}\!\left(\left|\pi(y_t)-\mu(y_t)\right| \le \epsilon\right)
\tau_A \hat{A}_t \frac{\pi(y_t)}{\mu(y_t)}
+ \tau_{KL}\log^2\!\left(\frac{\pi(y_t)}{\mu(y_t)}\right)
\right].
$$
where the policy-gradient term is
$\mu$ is the policy that generated the rollout. $\pi$ is the current trainer policy. $\hat{A}_t$ is the token-level advantage. The trust region uses the sampled token probabilities, not their ratio.
$$
\mathcal{J}_{\text{PG}}(\theta)
= \frac{1}{\sum_{j,i} |y_i^{(j)}|}
\sum_{j,i,t}
\min\!\left(\frac{\pi(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}{\mu(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}, \delta\right) \hat{A}^{(j)}_{i,t}
$$
and the KL regularizer penalizes drift between trainer and inference policies via the squared log importance ratio:
$$
\mathcal{L}_{KL}(\theta) = \frac{1}{\sum_{j,i} |y_i^{(j)}|}
\sum_{j,i,t} \log^2\!\left(\frac{\pi(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}{\mu(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}\right).
$$
$\mu$ is the policy that generated the rollout (inference), $\pi$ is the current policy (trainer), $\hat{A}_{i,t}$ is the token-level advantage, $\delta$ is the importance-sampling clipping ratio, and $\tau_{KL}$ is the KL temperature. The `min` clamps the importance ratio from above so a stale rollout assigning very low probability to a high-reward token doesn't produce a runaway gradient.
The knobs (under `[trainer.loss]` with `type = "default"`):
The knobs under `[trainer.loss]` are:
| Knob | Default | What it does |
|---|---|---|
| `dppo_mask_low` / `dppo_mask_high` | 0.2 / 0.2 | Lower / upper thresholds for DPPO-style token-level masking. |
| `eps` | 0.1 | Maximum absolute probability change before a token is masked. |
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 to drop the policy-gradient term, leaving only the KL regularizer. |
| `kl_tau` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
Set `[trainer.loss] type = "default"` and configure via the knobs above. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
Omit `[trainer.loss]` to use these defaults. Set `type = "ipo"` when you specify the section. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
### Custom Loss
+24 -3
View File
@@ -99,11 +99,14 @@ EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP
```toml
[trainer.model]
impl = "custom"
ep = 8 # explicit EP degree; must divide num_experts
ep_comm_backend = "torch" # or "deepep"
ep = 8 # explicit EP degree; must divide num_experts
[trainer.model.moe.dispatch]
type = "torch"
transport = "bf16"
```
`ep_comm_backend = "deepep"` uses DeepEP's custom dispatch/combine kernels for speed, with two extra knobs (`deepep_num_sms`, `deepep_token_chunk_size`) — tune on your hardware.
For DeepEP, set `type = "deepep"` and tune `num_sms` plus optional `token_chunk_size` in the same dispatch table. Routed-expert precision is selected separately with `[trainer.model.moe.compute]` (`bf16`, `deepgemm_fp8`, or `mxfp8`).
### Context Parallelism
@@ -231,6 +234,24 @@ Full multi-node configs ship under [`examples/advanced/`](https://github.com/Pri
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
### NIXL weight broadcast
Set `[weight_broadcast] type = "nixl"` to use receiver-driven NIXL weight transfer. Before the first SLURM run, install the NIXL/UCX build and the ModelExpress service binaries on the shared filesystem:
```bash
bash scripts/install_nixl_from_source.sh
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
bash scripts/install_modelexpress.sh
```
The generated job starts a job-scoped ModelExpress server and Redis backend on the trainer head node and passes that address to every component. To use an existing service, set `slurm.launch_modelexpress = false` and configure `weight_broadcast.host` and `weight_broadcast.port`.
The launcher requires the CUDA and InfiniBand transports from `third_party/ucx`. Each NIXL process selects the active InfiniBand port nearest its GPU; an explicitly configured `UCX_NET_DEVICES` takes precedence. Inference ranks start their pulls at different trainer ranks so concurrent workers distribute traffic across all available source rails.
ModelExpress exchanges peer metadata during startup. Weight updates reuse prepared NIXL requests, post every trainer-rank read in a transfer group concurrently, and use versioned NIXL notifications for source readiness and buffer credits.
By default, the trainer and inference worker each allocate one transfer arena. Set `weight_broadcast.overlap_transfer_and_replay = true` to allocate two arenas on both sides and replay one weight group while receiving the next. The additional arena is the size of the largest transfer group per GPU; allocation errors are reported instead of silently disabling overlap.
### Custom Templates
For unusual partitions, module loads, or environment setup, supply your own Jinja2 template:
+1 -1
View File
@@ -125,7 +125,7 @@ Pulled from the console logs and mirrored to W&B.
- `mismatch_kl/{all,env}/{mean,std,max}` — KL between trainer's current policy and the (older) inference policy that generated the rollouts. A sustained, growing mean is the early-warning sign for off-policy collapse.
- `entropy/{all,env}/mean` — too low means mode-collapse; too high means the model isn't committing.
- `masked_advantage_{positive,negative}/mean` — fraction of DPPO-masked tokens, split by sign.
- `is_masked/mean` — fraction of tokens masked by the IPO trust region.
- `optim/grad_norm` — spikes precede divergence; check the loss config or lower the LR.
**Performance** (trainer + orchestrator step independently):
+3
View File
@@ -97,6 +97,9 @@ ep = 8
[trainer.model.quantization]
type = "fp8"
[trainer.model.moe.compute]
type = "deepgemm_fp8"
[trainer.model.ac]
freq = 1
+1 -1
View File
@@ -7,7 +7,7 @@ requires-python = "~=3.12.0"
dependencies = [
"pydantic>=1.10.13",
"prime-pydantic-config>=0.4.3",
"renderers>=0.1.10",
"renderers>=0.1.11",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.3.0",
@@ -462,7 +462,7 @@ class InferenceConfig(BaseConfig):
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
enable_fp32_router_logits: bool = True
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x) by setting ``out_dtype=float32`` on the gate: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented as a monkey-patch over vLLM's DeepseekV2MoE, activated by setting ``additional_config["fp32_router_logits"] = True`` on the vLLM config."""
"""Emit fp32 MoE router logits: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented natively by vLLM, which reads ``moe_router_dtype`` off the HF config — this flag injects ``hf_overrides = {"moe_router_dtype": "float32"}`` (GLM-5.x gets fp32 routing regardless)."""
# Launcher-only fields
@@ -607,6 +607,18 @@ class InferenceConfig(BaseConfig):
if not hasattr(namespace, "logprobs_mode"):
namespace.logprobs_mode = "processed_logprobs"
# Always surface cached prompt tokens in `usage` — the router's
# cache-discount billing counters parse them off /inference/v1/generate.
if "enable_prompt_tokens_details" not in extra_fields:
namespace.enable_prompt_tokens_details = True
# vLLM's DeepseekV2-family (and transformers-backend MoE) gates read
# `moe_router_dtype` off the HF config to pick the router logits dtype.
if self.enable_fp32_router_logits:
hf_overrides = getattr(namespace, "hf_overrides", None) or {}
hf_overrides.setdefault("moe_router_dtype", "float32")
namespace.hf_overrides = hf_overrides
kv_transfer_config = self.build_kv_transfer_config()
if kv_transfer_config is not None:
namespace.kv_transfer_config = kv_transfer_config
@@ -616,8 +628,6 @@ class InferenceConfig(BaseConfig):
additional_config = getattr(namespace, "additional_config", None) or {}
if self.enable_fp32_lm_head:
additional_config["fp32_lm_head"] = True
if self.enable_fp32_router_logits:
additional_config["fp32_router_logits"] = True
if additional_config:
namespace.additional_config = additional_config
@@ -408,6 +408,9 @@ class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
session_id: str = "default"
"""ModelExpress session ID."""
overlap_transfer_and_replay: bool = False
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
@@ -158,6 +158,9 @@ class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
session_id: str = "default"
"""ModelExpress session ID."""
overlap_transfer_and_replay: bool = False
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
class SharedFileSystemWeightBroadcastConfig(BaseConfig):
type: Literal["filesystem"] = "filesystem"
@@ -490,7 +493,10 @@ class RLConfig(BaseConfig):
trainer_config_type = TrainerNCCLWeightBroadcastConfig
orchestrator_config_type = OrchestratorNCCLWeightBroadcastConfig
else:
transport_config = dict(session_id=self.weight_broadcast.session_id)
transport_config = dict(
session_id=self.weight_broadcast.session_id,
overlap_transfer_and_replay=self.weight_broadcast.overlap_transfer_and_replay,
)
trainer_config_type = TrainerNIXLWeightBroadcastConfig
orchestrator_config_type = OrchestratorNIXLWeightBroadcastConfig
self.trainer.weight_broadcast = trainer_config_type(**common_config, **transport_config)
@@ -324,7 +324,7 @@ class SFTConfig(BaseConfig):
@model_validator(mode="after")
def deepep_disables_grad_clipping(self):
if self.model.ep_comm_backend == "deepep" and self.optim.max_norm is not None:
if self.model.ep != 1 and self.model.moe.dispatch.type == "deepep" and self.optim.max_norm is not None:
warnings.warn(
"Gradient clipping is not compatible with DeepEP. "
"Automatically setting optim.max_norm to None (disabled).",
@@ -106,6 +106,9 @@ class SlurmConfig(BaseConfig):
pre_run_command: str | None = None
"""Shell command to run on the head node after cd, .env sourcing, and venv activation. Useful for cleanup like ``sudo pkill -f vllm``; wrap with ``srun bash -c '...'`` to fan out to all nodes."""
launch_modelexpress: bool = True
"""Start a job-scoped ModelExpress service for NIXL weight transfer."""
cleanup_grace_period: int = Field(3600, ge=0)
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
@@ -21,7 +21,6 @@ from prime_rl.utils.config import BaseConfig, default_output_dir
# -- Shared trainer configs (used by both SFT and RL trainers) --
AttnImplementation: TypeAlias = Literal["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]
EPCommBackend: TypeAlias = Literal["torch", "deepep"]
class GCConfig(BaseConfig):
@@ -37,7 +36,7 @@ class ActivationCheckpointConfig(BaseConfig):
"""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. ``routed_experts`` checkpoints routed expert compute in MoE layers (including LatentMoE). ``linear_attn`` checkpoints non-softmax token mixers (NemotronH Mamba, Qwen3.5-MoE GatedDeltaNet, AFMoE sliding-window attention)."""
"""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):
@@ -123,7 +122,7 @@ class LoRAConfig(BaseConfig):
"fc1_latent_proj",
"fc2_latent_proj",
]
"""Module names or regex patterns to apply LoRA to. Simple names (e.g. ``q_proj``) match any component in the module path; regex patterns match anywhere in the name. Names unknown to the current model are silently ignored, so defaults cover multiple architectures. NemotronH note: ``experts`` matches NonGatedGroupedExperts inside LatentMoE; ``fc1_latent_proj``/``fc2_latent_proj`` adapt the latent up/down projections. Add ``in_proj``/``out_proj`` to also LoRA Mamba."""
"""Module names or regex patterns to apply LoRA to. Simple names (e.g. ``q_proj``) match any component in the module path; regex patterns match anywhere in the name. Names unknown to the current model are silently ignored, so defaults cover multiple architectures. NemotronH note: ``experts`` matches the ReLU² grouped experts; ``fc1_latent_proj``/``fc2_latent_proj`` adapt the latent projections. Add ``in_proj``/``out_proj`` to also LoRA Mamba."""
modules_to_save: list[str] = []
"""Module names or regex patterns to keep fully trainable (not freeze). Same matching rules as ``target_modules``."""
@@ -151,7 +150,7 @@ _DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [
# in BF16 on the trainer while inference quantized it to FP8, causing
# hidden-state drift before the MoE router.
r"mlp\.gate\.",
"shared_expert_gate", # Qwen3.5 MoE: nn.Linear(hidden, 1, bias=False)
r"shared_expert\.output_gate", # Qwen3.5 MoE: nn.Linear(hidden, 1, bias=False)
"eh_proj",
"weights_proj",
"in_proj_a",
@@ -161,21 +160,80 @@ _DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [
class FP8Config(BaseConfig):
type: Literal["fp8"] = "fp8"
enable_grouped_gemm: bool = True
ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS
"""Dense linear module names excluded from DeepGEMM FP8 replacement."""
class MXFP8Config(BaseConfig):
type: Literal["mxfp8"] = "mxfp8"
recipe: MXFP8Recipe = "mxfp8_rceil"
enable_grouped_gemm: bool = True
enable_a2a: bool = True
"""MXFP8 recipe for dense linear modules."""
ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS
"""Dense linear module names excluded from torchao MXFP8 replacement."""
QuantizationConfig: TypeAlias = Annotated[FP8Config | MXFP8Config, Field(discriminator="type")]
class BF16MoEComputeConfig(BaseConfig):
"""Run routed-expert grouped GEMMs in bfloat16."""
type: Literal["bf16"] = "bf16"
class DeepGemmFP8MoEComputeConfig(BaseConfig):
"""Run routed-expert grouped GEMMs with DeepGEMM FP8 kernels."""
type: Literal["deepgemm_fp8"] = "deepgemm_fp8"
class MXFP8MoEComputeConfig(BaseConfig):
"""Run routed-expert grouped GEMMs with Prime's vendored MXFP8 implementation."""
type: Literal["mxfp8"] = "mxfp8"
recipe: MXFP8Recipe = "mxfp8_rceil"
"""MXFP8 expert-compute recipe."""
MoEComputeConfig: TypeAlias = Annotated[
BF16MoEComputeConfig | DeepGemmFP8MoEComputeConfig | MXFP8MoEComputeConfig,
Field(discriminator="type"),
]
class TorchMoEDispatchConfig(BaseConfig):
"""Dispatch and combine routed tokens with torch all-to-all collectives."""
type: Literal["torch"] = "torch"
transport: Literal["bf16", "mxfp8"] = "bf16"
"""Wire format for routed activations and their reverse-path gradients."""
class DeepEPMoEDispatchConfig(BaseConfig):
"""Dispatch and combine routed tokens with DeepEP."""
type: Literal["deepep"] = "deepep"
num_sms: int = Field(20, ge=1)
"""SMs allocated to DeepEP communication kernels."""
token_chunk_size: int | None = Field(None, ge=1)
"""Optional chunk size used to pipeline dispatch with local expert compute."""
MoEDispatchConfig: TypeAlias = Annotated[
TorchMoEDispatchConfig | DeepEPMoEDispatchConfig,
Field(discriminator="type"),
]
class MoERuntimeConfig(BaseConfig):
"""Independent routed-expert compute and token-dispatch choices."""
compute: MoEComputeConfig = BF16MoEComputeConfig()
dispatch: MoEDispatchConfig = TorchMoEDispatchConfig()
class ModelConfig(BaseModelConfig):
conversion_dir: Path | None = None
"""Directory for the auto-converted weights (written to a `prime`/`hf` subdirectory). If not set, we write into the model snapshot directory."""
@@ -213,14 +271,8 @@ class ModelConfig(BaseModelConfig):
ep: int | Literal["auto"] = "auto"
"""Expert parallelism degree for MoE layers. 1 disables EP. ``auto`` resolves to ``min(fsdp_island_size, 8)`` for MoE models (where ``fsdp_island_size = world_size // dp_replicate``), and to 1 for non-MoE models. Set an explicit integer to override."""
ep_comm_backend: EPCommBackend = "torch"
"""Communication backend for expert parallelism. ``torch`` uses TorchTitan all-to-all collectives; ``deepep`` uses DeepEP custom kernels."""
deepep_num_sms: int = Field(20, ge=1)
"""SMs allocated for DeepEP intranode dispatch/combine kernels. Also determines internode RDMA channel count (``num_channels = num_sms / 2``). Lower values leave more SMs for compute; higher values speed up dispatch/combine. The optimal value depends on EP degree and hardware. Only used when ``ep_comm_backend='deepep'``."""
deepep_token_chunk_size: int | None = Field(None, ge=1)
"""Token chunk size for DeepEP MoE pipelining. When set, DeepEP dispatch for chunk i+1 is launched while experts compute chunk i. Only used when ``ep_comm_backend='deepep'``."""
moe: MoERuntimeConfig = MoERuntimeConfig()
"""Routed-expert compute and token-dispatch runtime."""
cp: int = 1
"""Context parallelism degree. 1 disables CP."""
@@ -240,12 +292,6 @@ class ModelConfig(BaseModelConfig):
moe_router_dtype: Literal["bfloat16", "float32"] = "float32"
"""Compute dtype for MoE router gates. ``float32`` (default) keeps router gate weights in fp32 through forward and backward (exempt from FSDP bf16 parameter casting) and computes the gate GEMM and routing logits in fp32, matching models trained with fp32 routing (e.g. GLM-5.x via Megatron's ``--moe-router-dtype fp32``). ``bfloat16`` computes the gate GEMM in the model compute dtype. Router score functions (sigmoid/softmax) run in fp32 regardless. Only affects the custom MoE implementation; a no-op for non-MoE and HF-impl models."""
moe_use_grouped_mm: bool = True
"""Use grouped mm for MoE layers. Requires compute capability ≥ 9.0."""
moe_fused_kernel: bool = False
"""Run MoE routed experts through the vendored fused MoE CUDA kernel (``prime_kernels.flash_moe``) in forward; backward recomputes the reference grouped-mm path. Picks the mxfp8 kernel when ``quantization`` is MXFP8 with ``enable_grouped_gemm`` (which additionally needs ``hidden_size`` divisible by 256), otherwise the bf16 one. Requires the ``prime-kernels`` wheel, Blackwell (SM100) GPUs, ``ep=1``, ``model.impl='custom'``, MoE layers with output-weighted scores (``score_before_experts=False``), and ``moe_intermediate_size`` divisible by 128."""
quantization: QuantizationConfig | None = None
index_cache: IndexCacheConfig | None = None
@@ -332,19 +378,18 @@ class ModelConfig(BaseModelConfig):
return self
@model_validator(mode="after")
def validate_ep_comm_backend(self):
if self.ep_comm_backend == "torch":
def validate_moe_runtime(self):
if self.ep == 1:
return self
if isinstance(self.ep, int) and self.ep <= 1:
raise ValueError(f"model.ep_comm_backend='{self.ep_comm_backend}' requires model.ep > 1.")
return self
@model_validator(mode="after")
def mxfp8_only_with_torch_ep_backend(self):
if isinstance(self.quantization, MXFP8Config) and self.ep_comm_backend != "torch":
raise ValueError("MXFP8 quantization requires model.ep_comm_backend='torch'.")
compute = self.moe.compute
dispatch = self.moe.dispatch
if isinstance(dispatch, DeepEPMoEDispatchConfig):
if isinstance(compute, MXFP8MoEComputeConfig):
raise ValueError("MXFP8 expert compute does not support DeepEP dispatch.")
elif dispatch.transport == "mxfp8":
if not isinstance(compute, MXFP8MoEComputeConfig):
raise ValueError("MXFP8 transport requires model.moe.compute.type='mxfp8'.")
return self
@@ -492,26 +537,10 @@ class CheckpointConfig(BaseConfig):
"""Skip loading the optimizer state from checkpoint."""
class DefaultLossConfig(BaseConfig):
type: Literal["default"] = "default"
dppo_mask_low: float = Field(0.2, ge=0)
"""Lower DPPO masking threshold."""
dppo_mask_high: float = Field(0.2, ge=0)
"""Upper DPPO masking threshold."""
adv_tau: float = Field(1.0, ge=0)
"""Temperature for the advantage term."""
kl_tau: float = Field(1e-3, ge=0)
"""Temperature for the KL term."""
class IPOLossConfig(BaseConfig):
type: Literal["ipo"] = "ipo"
ipo_threshold: float = Field(0.1, ge=0)
"""Upper DPPO masking threshold."""
eps: float = Field(0.1, ge=0)
"""Maximum absolute probability change before a token is masked."""
adv_tau: float = Field(1.0, ge=0)
"""Temperature for the advantage term."""
@@ -530,7 +559,7 @@ class CustomLossConfig(BaseConfig):
"""Kwargs forwarded to the loss function."""
LossConfig: TypeAlias = Annotated[DefaultLossConfig | IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
LossConfig: TypeAlias = Annotated[IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
class FakeDataLoaderConfig(BaseConfig):
@@ -581,6 +610,9 @@ class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
session_id: str = "default"
"""ModelExpress session ID."""
overlap_transfer_and_replay: bool = False
"""Allocate two staging arenas so inference can replay one weight group while receiving the next."""
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
@@ -595,7 +627,7 @@ class TrainerConfig(BaseConfig):
data: DataLoaderConfig = DataLoaderConfig()
loss: LossConfig = DefaultLossConfig()
loss: LossConfig = IPOLossConfig()
"""Loss config for the rl loss component (see ``setup_rl_loss_fn``). The ce / ref_kl components are fixed and do not read this."""
optim: OptimizerConfig = AdamWConfig()
@@ -657,7 +689,7 @@ class TrainerConfig(BaseConfig):
@model_validator(mode="after")
def deepep_disables_grad_clipping(self):
if self.model.ep_comm_backend == "deepep" and self.optim.max_norm is not None:
if self.model.ep != 1 and self.model.moe.dispatch.type == "deepep" and self.optim.max_norm is not None:
warnings.warn(
"Gradient clipping is not compatible with DeepEP. "
"Automatically setting optim.max_norm to None (disabled).",
+55 -33
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",
@@ -49,11 +49,11 @@ prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
[project.optional-dependencies]
gpu = [
"torch>=2.9.0 ; sys_platform == 'linux'",
"torch>=2.13.0 ; sys_platform == 'linux'",
"torchvision ; sys_platform == 'linux'",
"torchaudio ; sys_platform == 'linux'",
"torchdata>=0.11.0 ; sys_platform == 'linux'",
"vllm>=0.26.0 ; sys_platform == 'linux'",
"vllm>=0.28.0 ; sys_platform == 'linux'",
"mooncake-transfer-engine>=0.3.10.post2 ; sys_platform == 'linux'",
"ring-flash-attn>=0.1.8 ; sys_platform == 'linux'",
"torchtitan ; sys_platform == 'linux'",
@@ -61,20 +61,21 @@ gpu = [
"tilelang>=0.1.8 ; sys_platform == 'linux'",
"flash-linear-attention ; sys_platform == 'linux'",
"nvidia-ml-py>=12.575.51 ; sys_platform == 'linux'",
"torchao>=0.17.0 ; sys_platform == 'linux'",
"torchao>=0.18.0 ; sys_platform == 'linux'",
"modelexpress==0.3.0 ; sys_platform == 'linux'",
"nixl-cu13==0.10.1 ; sys_platform == 'linux'",
]
dashboard = [
"fastapi>=0.115",
"uvicorn>=0.30",
]
# Both wheels are the same flash-attn 2.8.3 / cu128 / torch 2.11 / cp312 build and carry
# Both wheels are the same flash-attn 2.8.3 / cu130 / torch 2.13 / cp312 build and carry
# sm_80 / sm_90 / sm_100 / sm_120 cubins. `attn="auto"` picks FA4 on sm_100 and FA3 on
# sm_90, so FA2 is the resolved backend on sm_120 (see `_resolve_attn_impl` in
# trainer/model.py).
flash-attn = [
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.4/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.22/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_aarch64.whl ; platform_machine == 'aarch64'",
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.47/flash_attn-2.8.3+cu130torch2.13-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.48/flash_attn-2.8.3+cu130torch2.13-cp312-cp312-linux_aarch64.whl ; platform_machine == 'aarch64'",
]
flash-attn-3 = ["flash_attn_3 ; sys_platform == 'linux'"]
@@ -85,7 +86,7 @@ disagg = [
"deep-ep ; sys_platform == 'linux'",
"deep-gemm ; sys_platform == 'linux'",
"nixl ; sys_platform == 'linux'",
"nixl-cu12 ; sys_platform == 'linux' and platform_machine == 'x86_64'",
"nixl-cu13==0.10.1 ; sys_platform == 'linux'",
"vllm-router ; sys_platform == 'linux'",
]
gpt-oss = [
@@ -135,13 +136,15 @@ environments = [
"sys_platform == 'linux' and platform_machine == 'aarch64'",
"sys_platform == 'darwin' and platform_machine == 'arm64'",
]
# Override torch's pinned cuDNN to fix Conv3d performance regression (torch 2.9 + cuDNN 9.8-9.14)
# Override torch's pinned cuDNN to fix the Conv3d performance regression.
# See: https://github.com/pytorch/pytorch/issues/166122
override-dependencies = [
"nvidia-cudnn-cu12>=9.15",
"nvidia-cutlass-dsl>=4.4.1",
"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.
"nvidia-cutlass-dsl==4.6.2",
"transformers==5.6.2",
"torch>=2.9.0",
"torch>=2.13.0",
"openenv-core",
]
@@ -178,13 +181,30 @@ version = "0.3.0"
requires-dist = [
"grpcio>=1.66.2",
"huggingface_hub>=0.20.0",
"nixl[cu12]",
"nixl",
"numpy>=1.24.0",
"protobuf>=5.27.0,<7.0.0",
"pydantic>=2.0.0",
"torch>=2.6.0",
]
# NIXL publishes its CUDA 12 package as a base dependency even when the
# caller requests its CUDA 13 extra. Use the requested CUDA 13 package only.
[[tool.uv.dependency-metadata]]
name = "nixl"
version = "0.10.1"
requires-dist = ["nixl-cu13==0.10.1"]
# CUTLASS DSL has the same CUDA 12 default. vLLM requests its CUDA 13 extra,
# so resolve that variant without installing both runtime packages.
[[tool.uv.dependency-metadata]]
name = "nvidia-cutlass-dsl"
version = "4.6.2"
requires-dist = [
"nvidia-cutlass-dsl-libs-base==4.6.2",
"nvidia-cutlass-dsl-libs-cu13==4.6.2",
]
[tool.uv.exclude-newer-package]
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
@@ -210,7 +230,7 @@ vllm-router = false
dion = false
deep-ep = false
deep-gemm = false
nixl-cu12 = false
nixl-cu13 = false
torchao = false
prime-kernels = false
@@ -221,36 +241,38 @@ prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
verifiers = { path = "deps/verifiers", editable = true }
renderers = { path = "deps/renderers", editable = true }
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
torch = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
torchvision = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
torchaudio = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
torch = [{ index = "pytorch-cu130", marker = "sys_platform == 'linux'" }]
torchvision = [{ index = "pytorch-cu130", marker = "sys_platform == 'linux'" }]
torchaudio = [{ index = "pytorch-cu130", marker = "sys_platform == 'linux'" }]
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "23e4dfc" }
torchao = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.6.0/torchao-0.17.0+git02105d46c-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" }
torchao = [
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ 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 = "96bd151" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "82d6441" }
vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
deep-ep = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.1.0+1fd57b0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
deep-gemm = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
prime-kernels = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
nixl-cu12 = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
flash_attn_3 = { index = "pytorch-cu128-test" }
flash_attn_3 = { index = "pytorch-cu130-test" }
[tool.uv.extra-build-dependencies]
flash-attn = [{ requirement = "torch", match-runtime = true }]
@@ -261,13 +283,13 @@ mamba-ssm = [{ requirement = "torch", match-runtime = true }]
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
[[tool.uv.index]]
name = "pytorch-cu128"
url = "https://download.pytorch.org/whl/cu128"
name = "pytorch-cu130"
url = "https://download.pytorch.org/whl/cu130"
explicit = true
[[tool.uv.index]]
name = "pytorch-cu128-test"
url = "https://download.pytorch.org/whl/test/cu128"
name = "pytorch-cu130-test"
url = "https://download.pytorch.org/whl/test/cu130"
explicit = true
[tool.ruff.lint]
-90
View File
@@ -1,90 +0,0 @@
#!/usr/bin/env bash
# Build and install DeepGEMM from source for FP8 MoE inference + FP8 training.
#
# Pinned to d30fc36 — the commit our FP8 grouped-GEMM training path requires
# (newer than the 477618c that vLLM 0.17/0.19 used). The matching prebuilt
# wheel lives at tools/wheels/deep_gemm-2.3.0+d30fc36-cp312-cp312-linux_x86_64.whl
# and is what `pyproject.toml` consumes by default; this script is for
# rebuilding when torch / CUDA / vllm bumps invalidate that wheel.
#
# Requires CUDA 12.8+ and a Hopper/Blackwell GPU.
#
# Usage:
# bash scripts/install_deep_gemm.sh # build + install in-place
# bash scripts/install_deep_gemm.sh --wheel-dir tools/wheels # build wheel only
#
# Options:
# --ref REF DeepGEMM commit hash (default: d30fc36)
# --wheel-dir DIR Output wheel to DIR instead of installing
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
DEEPGEMM_GIT_REPO="https://github.com/deepseek-ai/DeepGEMM.git"
DEEPGEMM_GIT_REF="d30fc36c8f229f4f873b90a492f6e19e6e610923"
WHEEL_DIR=""
while [[ $# -gt 0 ]]; do
case $1 in
--ref) DEEPGEMM_GIT_REF="$2"; shift 2 ;;
--wheel-dir) WHEEL_DIR="$2"; shift 2 ;;
*) echo "Unknown argument: $1" >&2; exit 1 ;;
esac
done
# Skip if already installed at the right version
INSTALLED_VER=$(python -c "import deep_gemm; print(deep_gemm.__version__)" 2>/dev/null || echo "")
SHORT_REF="${DEEPGEMM_GIT_REF:0:7}"
if [[ "$INSTALLED_VER" == *"$SHORT_REF"* ]]; then
echo "DeepGEMM ${INSTALLED_VER} already installed, skipping."
exit 0
fi
# Auto-detect CUDA version
CUDA_VERSION=$(nvcc --version 2>/dev/null | grep -oP 'release \K[\d.]+' || echo "")
if [ -z "$CUDA_VERSION" ]; then
echo "ERROR: nvcc not found. CUDA toolkit required." >&2
exit 1
fi
CUDA_MAJOR="${CUDA_VERSION%%.*}"
CUDA_MINOR="${CUDA_VERSION#*.}"
CUDA_MINOR="${CUDA_MINOR%%.*}"
if [ "$CUDA_MAJOR" -lt 12 ] || { [ "$CUDA_MAJOR" -eq 12 ] && [ "$CUDA_MINOR" -lt 8 ]; }; then
echo "Skipping DeepGEMM (requires CUDA 12.8+, got ${CUDA_VERSION})"
exit 0
fi
echo "================================================================"
echo " Building DeepGEMM (${SHORT_REF})"
echo " CUDA: ${CUDA_VERSION}"
echo "================================================================"
TMPDIR=$(mktemp -d)
cleanup() { rm -rf "$TMPDIR"; }
trap cleanup EXIT
git clone --recurse-submodules "$DEEPGEMM_GIT_REPO" "$TMPDIR/DeepGEMM" 2>&1
cd "$TMPDIR/DeepGEMM"
git checkout "$DEEPGEMM_GIT_REF"
git submodule update --init --recursive
cd "$REPO_ROOT"
if [ -n "$WHEEL_DIR" ]; then
mkdir -p "$WHEEL_DIR"
uv build --no-build-isolation --wheel --out-dir "$WHEEL_DIR" "$TMPDIR/DeepGEMM"
echo ""
echo "Wheel built:"
ls -lh "$WHEEL_DIR"/deep_gemm*.whl
else
uv pip install --no-build-isolation --reinstall "$TMPDIR/DeepGEMM"
echo ""
echo "Installed: $(python -c 'import deep_gemm; print(deep_gemm.__version__)')"
fi
echo "================================================================"
echo " DeepGEMM build complete"
echo "================================================================"
-170
View File
@@ -1,170 +0,0 @@
#!/usr/bin/env bash
# Install DeepEP kernels for expert-parallel disaggregated inference.
#
# Builds NVSHMEM + DeepEP from source and installs into the project venv.
# Required for disaggregated prefill/decode deployments with expert parallelism.
#
# Auto-detects the CUDA toolkit version that matches the installed PyTorch
# and looks for it at /usr/local/cuda-X.Y. Fails if not found.
#
# Prerequisites:
# - Matching CUDA toolkit installed (e.g. `sudo apt install cuda-toolkit-12-8`)
# - For multi-node: IBGDA driver configured (see --configure-drivers)
#
# Usage:
# bash scripts/install_ep_kernels.sh
#
# Options:
# --workspace DIR Build directory (default: ./ep_kernels_workspace)
# --deepep-ref REF DeepEP commit hash (default: 73b6ea4)
# --nvshmem-ver VER NVSHMEM version (default: 3.3.24)
# --configure-drivers Also configure IBGDA drivers (requires sudo, needs reboot)
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
DEEPEP_COMMIT_HASH="73b6ea4"
NVSHMEM_VER="3.3.24"
WORKSPACE="$REPO_ROOT/ep_kernels_workspace"
CONFIGURE_DRIVERS=0
while [[ $# -gt 0 ]]; do
case $1 in
--workspace) WORKSPACE="$2"; shift 2 ;;
--deepep-ref) DEEPEP_COMMIT_HASH="$2"; shift 2 ;;
--nvshmem-ver) NVSHMEM_VER="$2"; shift 2 ;;
--configure-drivers) CONFIGURE_DRIVERS=1; shift ;;
*) echo "Unknown argument: $1" >&2; exit 1 ;;
esac
done
# Skip if DeepEP is already installed
if python -c "import deep_ep" 2>/dev/null; then
echo "DeepEP already installed, skipping."
exit 0
fi
# ── Auto-detect CUDA toolkit matching torch ───────────────────────────────────
TORCH_CUDA_VER=$(python -c "import torch; print(torch.version.cuda)")
CUDA_MAJOR_MINOR=$(echo "$TORCH_CUDA_VER" | grep -oP '^\d+\.\d+')
CUDA_MAJOR=$(echo "$CUDA_MAJOR_MINOR" | cut -d. -f1)
CUDA_HOME="/usr/local/cuda-${CUDA_MAJOR_MINOR}"
if [ ! -x "$CUDA_HOME/bin/nvcc" ]; then
echo "ERROR: Could not find CUDA toolkit matching torch (cuda ${TORCH_CUDA_VER}) at ${CUDA_HOME}" >&2
echo "Install it with: sudo apt install cuda-toolkit-${CUDA_MAJOR_MINOR//./-}" >&2
exit 1
fi
export CUDA_HOME
# Verify versions actually match
NVCC_VER=$("$CUDA_HOME/bin/nvcc" --version | grep -oP 'release \K[\d.]+')
echo "Torch CUDA: ${TORCH_CUDA_VER}, nvcc: ${NVCC_VER} (${CUDA_HOME})"
# ── Auto-detect GPU architecture ──────────────────────────────────────────────
GPU_NAME=$(nvidia-smi --query-gpu=gpu_name --format=csv,noheader,nounits -i 0 2>/dev/null)
case "$GPU_NAME" in
*H100*|*H200*|*H800*) TORCH_CUDA_ARCH_LIST="9.0" ;;
*B100*|*B200*|*GB200*) TORCH_CUDA_ARCH_LIST="10.0" ;;
*)
echo "Could not auto-detect GPU arch from '$GPU_NAME'. Set TORCH_CUDA_ARCH_LIST manually." >&2
echo " Hopper (H100/H200): TORCH_CUDA_ARCH_LIST=9.0" >&2
echo " Blackwell (B200): TORCH_CUDA_ARCH_LIST=10.0" >&2
exit 1
;;
esac
export TORCH_CUDA_ARCH_LIST
echo "================================================================"
echo " Installing DeepEP kernels"
echo " CUDA: ${CUDA_HOME} (${NVCC_VER})"
echo " GPU: ${GPU_NAME} (arch ${TORCH_CUDA_ARCH_LIST})"
echo " DeepEP: ${DEEPEP_COMMIT_HASH}"
echo " NVSHMEM: ${NVSHMEM_VER}"
echo " Workspace: ${WORKSPACE}"
echo "================================================================"
mkdir -p "$WORKSPACE"
# ── Step 1: Install build deps ────────────────────────────────────────────────
echo ""
echo "--- Installing build dependencies ---"
cd "$REPO_ROOT"
uv pip install cmake ninja
# ── Step 2: Download and extract NVSHMEM ──────────────────────────────────────
echo ""
echo "--- Setting up NVSHMEM ${NVSHMEM_VER} ---"
ARCH=$(uname -m)
case "${ARCH,,}" in
x86_64|amd64) NVSHMEM_SUBDIR="linux-x86_64" ;;
aarch64|arm64) NVSHMEM_SUBDIR="linux-sbsa" ;;
*) echo "Unsupported architecture: ${ARCH}" >&2; exit 1 ;;
esac
NVSHMEM_DIR="$WORKSPACE/nvshmem"
if [ ! -d "$NVSHMEM_DIR/lib" ]; then
NVSHMEM_FILE="libnvshmem-${NVSHMEM_SUBDIR}-${NVSHMEM_VER}_cuda${CUDA_MAJOR}-archive.tar.xz"
NVSHMEM_URL="https://developer.download.nvidia.com/compute/nvshmem/redist/libnvshmem/${NVSHMEM_SUBDIR}/${NVSHMEM_FILE}"
echo "Downloading ${NVSHMEM_URL}"
curl -fSL "${NVSHMEM_URL}" -o "$WORKSPACE/${NVSHMEM_FILE}"
tar -xf "$WORKSPACE/${NVSHMEM_FILE}" -C "$WORKSPACE"
mv "$WORKSPACE/${NVSHMEM_FILE%.tar.xz}" "$NVSHMEM_DIR"
rm -f "$WORKSPACE/${NVSHMEM_FILE}"
rm -rf "$NVSHMEM_DIR/lib/bin" "$NVSHMEM_DIR/lib/share"
echo "NVSHMEM extracted to ${NVSHMEM_DIR}"
else
echo "NVSHMEM already present at ${NVSHMEM_DIR}, skipping download"
fi
export CMAKE_PREFIX_PATH="${NVSHMEM_DIR}/lib/cmake:${CMAKE_PREFIX_PATH:-}"
export NVSHMEM_DIR
# ── Step 3: Build and install DeepEP ──────────────────────────────────────────
echo ""
echo "--- Building DeepEP (${DEEPEP_COMMIT_HASH}) ---"
DEEPEP_DIR="$WORKSPACE/DeepEP"
if [ ! -d "$DEEPEP_DIR/.git" ]; then
git clone https://github.com/deepseek-ai/DeepEP "$DEEPEP_DIR"
fi
cd "$DEEPEP_DIR"
git fetch origin
git checkout "$DEEPEP_COMMIT_HASH"
WHEEL_DIR="$REPO_ROOT/deps"
mkdir -p "$WHEEL_DIR"
python setup.py bdist_wheel --dist-dir "$WHEEL_DIR"
WHEEL=$(ls "$WHEEL_DIR"/deep_ep*.whl | head -1)
echo ""
echo "--- DeepEP wheel built at: $WHEEL ---"
# ── Step 4 (optional): Configure IBGDA drivers ───────────────────────────────
if [ "$CONFIGURE_DRIVERS" -eq 1 ]; then
echo ""
echo "--- Configuring IBGDA drivers (requires sudo) ---"
echo 'options nvidia NVreg_EnableStreamMemOPs=1 NVreg_RegistryDwords="PeerMappingOverride=1;"' | sudo tee -a /etc/modprobe.d/nvidia.conf
if command -v update-initramfs &> /dev/null; then
sudo update-initramfs -u
elif command -v dracut &> /dev/null; then
sudo dracut --force
else
echo "No supported initramfs update tool found." >&2
exit 1
fi
echo ""
echo "IBGDA configured. Please REBOOT the system to apply changes."
fi
echo ""
echo "================================================================"
echo " DeepEP installation complete"
echo " NVSHMEM: ${NVSHMEM_DIR}"
echo " To verify: uv run python -c 'import deep_ep; print(deep_ep.__file__)'"
echo "================================================================"
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env bash
# Build the ModelExpress metadata server and Redis backend used by SLURM RL jobs.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
MODELEXPRESS_REPOSITORY="https://github.com/ai-dynamo/modelexpress.git"
MODELEXPRESS_REF="v0.3.0"
REDIS_VERSION="7.4.2"
REDIS_SHA256="4ddebbf09061cbb589011786febdb34f29767dd7f89dbe712d2b68e808af6a1f"
if [[ $# -gt 0 ]]; then
echo "This installer does not accept arguments" >&2
exit 1
fi
BIN_DIR="$PROJECT_DIR/third_party/modelexpress/bin"
mkdir -p "$BIN_DIR"
if [[ -x "$BIN_DIR/modelexpress-server" ]] \
&& "$BIN_DIR/modelexpress-server" --version 2>/dev/null | grep -q "${MODELEXPRESS_REF#v}"; then
echo "modelexpress-server $MODELEXPRESS_REF already installed at $BIN_DIR"
else
command -v cargo >/dev/null || {
echo "cargo not found; install Rust 1.90 or newer before running this script" >&2
exit 1
}
command -v protoc >/dev/null || {
echo "protoc not found; install Protocol Buffers before running this script" >&2
exit 1
}
BUILD_DIR=$(mktemp -d)
trap 'rm -rf "$BUILD_DIR"' EXIT
git clone --depth 1 --branch "$MODELEXPRESS_REF" "$MODELEXPRESS_REPOSITORY" "$BUILD_DIR/modelexpress"
(
cd "$BUILD_DIR/modelexpress"
cargo build --release --bin modelexpress-server
)
cp "$BUILD_DIR/modelexpress/target/release/modelexpress-server" "$BIN_DIR/"
fi
if [[ -x "$BIN_DIR/redis-server" ]] \
&& "$BIN_DIR/redis-server" --version | grep -q "v=$REDIS_VERSION"; then
echo "redis-server $REDIS_VERSION already installed at $BIN_DIR"
else
BUILD_DIR="${BUILD_DIR:-$(mktemp -d)}"
trap 'rm -rf "$BUILD_DIR"' EXIT
REDIS_ARCHIVE="$BUILD_DIR/redis-${REDIS_VERSION}.tar.gz"
curl --fail --location --silent --show-error \
--output "$REDIS_ARCHIVE" \
"https://download.redis.io/releases/redis-${REDIS_VERSION}.tar.gz"
echo "$REDIS_SHA256 $REDIS_ARCHIVE" | sha256sum --check
tar -xzf "$REDIS_ARCHIVE" -C "$BUILD_DIR"
make -C "$BUILD_DIR/redis-${REDIS_VERSION}" -j redis-server MALLOC=libc
cp "$BUILD_DIR/redis-${REDIS_VERSION}/src/redis-server" "$BIN_DIR/"
fi
echo "Installed ModelExpress server dependencies in $BIN_DIR"
-3
View File
@@ -98,7 +98,6 @@ ARCH_PRESETS = {
first_k_dense_replace=1,
norm_topk_prob=True,
use_qk_norm=False,
use_grouped_mm=False,
pad_token_id=151329,
eos_token_id=[151329, 151336, 151338],
),
@@ -127,7 +126,6 @@ ARCH_PRESETS = {
use_routing_bias=True,
use_qk_norm=True,
qk_norm_type="per_layer",
use_grouped_mm=False,
auto_map={"AutoModelForCausalLM": "MiniMaxAI/MiniMax-M2.1--modeling_minimax_m2.MiniMaxM2ForCausalLM"},
),
"hf_model_class": None, # uses AutoModelForCausalLM with trust_remote_code
@@ -173,7 +171,6 @@ ARCH_PRESETS = {
num_experts_per_tok=4,
mlp_layer_types=["dense"] + ["sparse"] * 11,
moe_routed_scaling_factor=2.5,
use_grouped_mm=False,
pad_token_id=9,
bos_token_id=2,
eos_token_id=[2, 24],
+2
View File
@@ -73,6 +73,8 @@ The `sft` entrypoint takes the same eval shape at the top level for online evals
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.algo] type = "max_rl"`). Omit `type` to keep the default variant.
**RL loss** — `[trainer.loss]` defaults to IPO with `eps = 0.1`, `adv_tau = 1.0`, and `kl_tau = 1e-3`. Omit the section to use these defaults. Set `type = "custom"` with `import_path` and optional `kwargs` to load a custom RL loss. The `ce` and `ref_kl` components are fixed.
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "rae" | "hierarchical_grpo" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). `hierarchical_grpo` is only valid with a proposer-solver env: it compares solvers with attempts on the same proposed problem and proposers with other proposals in the group. There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-source override: `[orchestrator.train.source.algo] type = "opd"` (the source assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
**`BaseModel | None` fields** — bare flag enables defaults; nested override enables and sets:
+15 -4
View File
@@ -66,13 +66,24 @@ Requires `nvcc`. Without `mamba-ssm`, NemotronH falls back to HF's pure-PyTorch
### Trainer DeepEP backend
`scripts/install_ep_kernels.sh` auto-detects the CUDA toolkit matching torch and the GPU arch, builds NVSHMEM + DeepEP from source, and skips if `deep_ep` already imports.
The `disagg` extra installs the prebuilt DeepEP wheel pinned in `[tool.uv.sources]`:
```bash
bash scripts/install_ep_kernels.sh
uv sync --extra disagg
```
Flags: `--workspace DIR`, `--deepep-ref REF` (default `73b6ea4`), `--nvshmem-ver VER` (default `3.3.24`), `--configure-drivers` (multi-node IBGDA; needs sudo + reboot).
The prime-kernels repository owns source builds for DeepEP, DeepGEMM, and TorchAO. Use
its scripts when a local rebuild is required:
```bash
git submodule update --init deps/prime-kernels
bash deps/prime-kernels/scripts/install_ep_kernels.sh --wheel-dir /tmp/prime-kernels-wheels
uv pip install --reinstall --no-deps /tmp/prime-kernels-wheels/deep_ep-*.whl
```
The build needs a CUDA toolkit whose version matches torch. Set
`TORCH_CUDA_ARCH_LIST` when the build host has no GPU or when the wheel must support
more than the local GPU architecture.
Verify: `uv run python -c 'import deep_ep; print(deep_ep.__file__)'`.
@@ -91,4 +102,4 @@ Binaries land in `third_party/llmd/bin/{epp,envoy,pd-sidecar}` (a shared path, s
- `pyproject.toml` — dependencies, extras, dependency groups
- `uv.lock` — pinned lockfile (refresh with `uv sync --all-extras`)
- `scripts/install.sh` — bootstrap installer
- `scripts/install_ep_kernels.sh` — DeepEP build script
- `deps/prime-kernels/scripts/` — native wheel build scripts
+48 -50
View File
@@ -10,13 +10,13 @@ CUDA kernels live in their own monorepo,
git submodule `deps/prime-kernels`, alongside prime-rl's other submodules. That repo is the
wheel root (`setup.py`, `pyproject.toml`) and `prime_kernels/` inside it is the importable
package: one folder per kernel, holding the
kernel's Python surface *and* its C++/CUDA sources under `csrc/`, all declared in the single
kernel's Python surface and, for compiled kernels, its C++/CUDA sources under `csrc/`, all declared in the single
manifest `prime_kernels/kernels.toml`. See `deps/prime-kernels/README.md` once the submodule
is initialized.
Nothing about a kernel lives in prime-rl. prime-rl pins a prime-kernels commit, builds the
wheel from it, and installs the result — and stays a pure-Python wheel itself; never add
compiled extensions to it.
Nothing about a kernel lives in prime-rl. prime-rl pins a prime-kernels commit for local
source builds and a prime-kernels release for installs. prime-kernels builds and publishes
its own wheels. prime-rl stays a pure-Python wheel; never add compiled extensions to it.
Living under `deps/` means `tool.ruff.extend-exclude = ["deps"]` in `pyproject.toml`
already covers it — prime-rl lints none of it.
@@ -38,15 +38,18 @@ it once at startup rather than failing a run halfway through. `unavailable_reaso
the same answer for one kernel (`None` when it is usable), which is what a test's skip guard
wants; `is_available` is just that call compared to `None`.
`flash_moe` is the one kernel today: fused MoE forward (bf16 + mxfp8) on Blackwell
tcgen05, reached through `model.moe_fused_kernel=true`.
`flash_moe` is a compiled fused MoE forward kernel (bf16 + mxfp8) on Blackwell
tcgen05. Its trainer integration is dormant. `mxfp8_moe` is a Python-only registered
kernel package for MXFP8 grouped GEMM and torch EP transport on SM100; it owns the
MoE-specific torchao-derived orchestration and exports explicit BF16 boundaries instead
of tensor-subclass interception.
What a kernel requires of its inputs — block sizes, alignments, shape constraints — belongs
to prime-kernels, which exports it: `flash_moe.BLOCK_M`, `flash_moe.MXFP8_SCALE_BLOCK`, and
`flash_moe.unsupported_shape_reason(dim, hidden_dim, mxfp8=...)`, which
`apply_fused_moe_kernel` calls once at setup so an unsupported model fails before training
rather than mid-step. Never hardcode a `128` on this side: then every requirement change is
a change in both repos.
`flash_moe.unsupported_shape_reason(dim, hidden_dim, mxfp8=...)`. When the trainer integration
is restored, call this once during setup so an unsupported model fails before training rather
than mid-step. Never hardcode a `128` on this side: then every requirement change is a change
in both repos.
## Building locally
@@ -72,14 +75,15 @@ The work happens in the prime-kernels repo, not here. Inside `deps/prime-kernels
1. Commit the sources under `prime_kernels/<name>/csrc/`.
2. Add a `[<name>]` table to `prime_kernels/kernels.toml` — `sources`, `include-dirs`,
`arch`, `cxx-std`; paths are relative to the kernel folder.
`arch`, `cxx-std`; paths are relative to the kernel folder. A vendored Python kernel
uses `python-only = true`, may declare import checks in `requires`, and omits compiled
extension fields.
3. Write `prime_kernels/<name>/__init__.py` — `from . import _C`, then per op a wrapper
calling `torch.ops.<ns>.<op>` and a `torch.library.register_fake`. No
`torch.library.custom_op` decorator: that defines a *Python* op, and `TORCH_LIBRARY`
has already defined these C++ side — only the fake (meta) kernel is missing. A kernel
used in training also needs `torch.library.register_autograd`, since a schema carries
no backward. (`flash_moe` is forward only; prime-rl wraps it in an `autograd.Function`
of its own.)
no backward. `flash_moe` is forward only and currently has no trainer integration.
4. Nothing else: `setup.py` and the runtime registry both read the manifest.
Rules the build assumes:
@@ -112,69 +116,63 @@ Then, in order:
- Read the diff for **host-side contract changes**, not just kernel internals. A change to
what the caller must pass (weight layout, scale packing, argument order) is silently wrong
numbers, not a build error, and prime-rl's call sites have to absorb it.
- Rebuild and re-run whatever exercises the kernel — the ABI is not checked for you. For
`flash_moe` that is `tests/unit/train/models/test_fused_moe.py`, which compares its
forward and its hand-written backward against the grouped-mm expert path; it is
`gpu`-marked and skips itself unless the kernel is available, so it only means anything
on a machine the kernel was built for.
- Rebuild and re-run the kernel repository's numerical coverage plus every PrimeRL runtime
path that calls the changed kernel; the ABI is not checked for you.
- The bump alone ships nothing: installs resolve `prime-kernels` from a release wheel, so the
new code only reaches users once a release rebuilds the wheels and the pin below moves.
## Prebuilt wheels
[`build_kernels.yaml`](../../.github/workflows/build_kernels.yaml) builds the wheel for
x86_64 and aarch64 in the CUDA devel image (no GPU needed — nvcc cross compiles). It inits
the `deps/prime-kernels` submodule itself, runs on every bump of it, and attaches the wheels
to a release when given a `release_tag`, alongside the deep-ep/deep-gemm/torchao wheels.
The [prime-kernels](https://github.com/PrimeIntellect-ai/prime-kernels) repository owns
`build_kernels.yaml`. It builds `prime-kernels`, `deep-ep`, `deep-gemm`, and `torchao` for
x86_64 and aarch64. It publishes the wheels as prime-kernels release assets.
Its `paths` trigger is `deps/prime-kernels` (the gitlink), **not** `deps/prime-kernels/**` —
no file under it is tracked by prime-rl, so a `**` pattern would match nothing and submodule
bumps would build no wheels.
Every release gets them: [`tag-and-release.yaml`](../../.github/workflows/tag-and-release.yaml)
calls this workflow after the tag is cut and **before** it promotes the draft, so a published
release always carries its wheels. To backfill a release that predates this, dispatch by hand:
Run that workflow in prime-kernels for each torch or CUDA bump:
```bash
gh workflow run build_kernels.yaml -f release_tag=vX.Y.Z -f ref=vX.Y.Z
gh workflow run build_kernels.yaml \
--repo PrimeIntellect-ai/prime-kernels \
-f release_tag=vX.Y.Z
```
The wheel version carries the ABI it was built against, e.g.
`prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl` — it imports only under
that exact torch, so the build installs the torch pinned in `uv.lock`, not the newest one.
The base version comes from `deps/prime-kernels/pyproject.toml` in the prime-kernels repo.
`prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl`. It imports only under
that exact torch and CUDA ABI. prime-kernels CI controls the build dependency pins.
### Pinning installs at the prebuilt wheels
`uv sync --extra kernels` installs `prime-kernels` from the wheels named in
`[tool.uv.sources]` — the pattern deep-ep, deep-gemm and vllm already use, and the only form
the extra may take, since a sync must never compile:
`[tool.uv.sources]`. deep-ep, deep-gemm, torchao, and vLLM use the same pattern. A sync must
never compile these packages:
```toml
[tool.uv.sources]
prime-kernels = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/vX.Y.Z/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/vX.Y.Z/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
```
The wheels are prime-rl release assets — the kernels live in their own repo, but they ship
with prime-rl's releases. To move the pin, the build prints both lines, ready to paste, in
its job summary. Then `uv lock`.
The wheels are prime-kernels release assets. Get the exact names before you move all pins:
The pin necessarily trails by one release: a release's own assets do not exist until that
release is built, so `vX.Y.Z` can only point at wheels from an already published tag. Move it
whenever the kernels or the torch/CUDA pin change — a stale pin ships stale kernels, and a
pin whose torch no longer matches the lock fails at import, not at install.
```bash
gh release view vX.Y.Z \
--repo PrimeIntellect-ai/prime-kernels \
--json assets
```
Then run `uv lock`.
Move the pin when a kernel, torch, or CUDA pin changes. A stale pin ships stale kernels. A
torch ABI mismatch fails at import, not at install.
## Gotchas
- prime-kernels' `pyproject.toml` mirrors prime-rl's own `torch>=2.9.0`; keep the two
identical, and build against the torch in `uv.lock` (`build_kernels.yaml` reads it) — the
wheel imports only under the torch it was compiled against.
- Keep the torch floor in prime-kernels aligned with prime-rl. The wheel imports only under
the torch version it was compiled against.
- Never reintroduce `prime-kernels` as a path source: uv cannot read a source tree's metadata
without building it, so every `uv lock` would then need nvcc. A release-asset URL has static
metadata and does not.
- A fresh clone without the submodule still installs and trains — only the source build needs
it. `build_kernels.yaml` inits it and sets `PRIME_KERNELS_REQUIRE=1`, so a wheel is never
published with kernels silently skipped.
- A fresh prime-rl clone without the submodule still installs and trains. Only a local source
build needs it. prime-kernels CI sets `PRIME_KERNELS_REQUIRE=1`, so a release cannot omit
kernels silently.
+1 -1
View File
@@ -135,7 +135,7 @@ All metrics print to the console log (and W&B when configured).
|--------|-------------|
| `mismatch_kl/{all,env}/{mean,std,max}` | KL between trainer and (old) inference policy over trainable tokens |
| `entropy/{all,env}/{mean,std,max}` | policy entropy over trainable tokens |
| `masked_advantage_{positive,negative}/mean` | fraction of DPPO-masked tokens with +/- advantage |
| `is_masked/mean` | fraction of tokens masked by the IPO trust region |
| `optim/grad_norm` | spikes may precede divergence |
**Performance** — trainer and orchestrator step independently, so comparing step times shows who's waiting on whom.
+1
View File
@@ -46,6 +46,7 @@ uv run rl @ examples/basic/reverse-text/rl.toml --dry-run
- Entrypoint: `src/prime_rl/entrypoints/rl.py`
- SLURM: single- and multi-node
- Multi-node SLURM stops after `.trainer.done` for trainer-only fake-data runs. Runs with inference stop after both `.trainer.done` and `.orchestrator.done`.
- NIXL on SLURM: install NIXL and ModelExpress with the provided scripts. The job starts ModelExpress and Redis unless `slurm.launch_modelexpress = false`.
- Environment packages: before launching a config with a non-core verifier env id,
verify the package imports under `uv run` (for example
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym'))"`).
+17
View File
@@ -454,9 +454,24 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
train_env_names = env_server_names(config, "train")
eval_env_names = env_server_names(config, "eval")
nixl_broadcast = (
config.weight_broadcast
if config.weight_broadcast is not None and config.weight_broadcast.type == "nixl"
else None
)
launch_modelexpress = nixl_broadcast is not None and config.slurm.launch_modelexpress
modelexpress_vars = {
"use_nixl_broadcast": nixl_broadcast is not None,
"launch_modelexpress": launch_modelexpress,
"modelexpress_host": nixl_broadcast.host if nixl_broadcast is not None else "",
"modelexpress_port": nixl_broadcast.port if nixl_broadcast is not None else 0,
"modelexpress_redis_port": 6380 if nixl_broadcast is not None and nixl_broadcast.port == 6379 else 6379,
}
if config.deployment.type == "single_node":
script = template.render(
**config.slurm.template_vars,
**modelexpress_vars,
config_path=config_dir / RL_CONFIG,
config_dir=config_dir,
log_dir=log_dir,
@@ -510,6 +525,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
train_env_names=train_env_names,
eval_env_names=eval_env_names,
**modelexpress_vars,
)
else:
script = template.render(
@@ -550,6 +566,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
inference_env_vars=inference_env_vars,
train_env_names=train_env_names,
eval_env_names=eval_env_names,
**modelexpress_vars,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
+5 -68
View File
@@ -207,7 +207,6 @@ def monkey_patch_minimax_m2_think_end_passthrough():
def monkey_patch_return_routed_experts_with_nixl_connector():
from vllm import envs
from vllm.config.vllm import VllmConfig
from vllm.logger import init_logger
@@ -233,8 +232,11 @@ def monkey_patch_return_routed_experts_with_nixl_connector():
if config.parallel_config.pipeline_parallel_size > 1:
raise ValueError("--enable-return-routed-experts is incompatible with pipeline parallelism (PP > 1).")
if envs.VLLM_USE_V2_MODEL_RUNNER:
raise ValueError("VLLM_USE_V2_MODEL_RUNNER does not yet support: routed experts capture")
if config.use_v2_model_runner:
raise ValueError(
"The V2 model runner does not support routed experts capture - "
"set VLLM_USE_V2_MODEL_RUNNER=0 (the prime-rl launcher does this automatically)."
)
# vLLM rejects every KV connector, but our P/D path uses NIXL and
# stitches prefill/decode routed experts in the router. CPU KV offload
@@ -609,32 +611,6 @@ def monkey_patch_minimax_m2_for_lora():
)
def monkey_patch_harmony_stop_token_propagation():
"""Fix: vLLM doesn't merge harmony stop tokens into per-request SamplingParams.
The harmony mode sets stop_token_ids (including <|call|> and <|return|>) in
default_sampling_params at server init, but ChatCompletionRequest.to_sampling_params()
ignores them, using only self.stop_token_ids (which defaults to []).
Upstream: https://github.com/vllm-project/vllm/issues/22519
"""
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
_original_to_sampling_params = ChatCompletionRequest.to_sampling_params
def _patched_to_sampling_params(self, max_tokens, default_sampling_params):
params = _original_to_sampling_params(self, max_tokens, default_sampling_params)
# Merge harmony stop tokens from default_sampling_params
default_stop_ids = default_sampling_params.get("stop_token_ids", [])
if default_stop_ids:
existing = set(params.stop_token_ids or [])
merged = list(existing | set(default_stop_ids))
params.stop_token_ids = merged
return params
ChatCompletionRequest.to_sampling_params = _patched_to_sampling_params
def monkey_patch_no_moe_lora():
"""This disables LoRA for MoE layers and makes them pick better kernels.
@@ -717,45 +693,6 @@ def monkey_patch_fp32_lm_head():
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
def monkey_patch_fp32_router_logits():
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x glm_moe_dsa).
vLLM's DeepseekV2MoE gate is a GateLinear with a bf16 weight and no out_dtype,
so router logits are rounded to bf16 before expert scoring. GLM-5.x was trained
with fp32 routing (Megatron ``--moe-router-dtype fp32``); upstream now runs its
gate fully in fp32 (vllm-project/vllm#47410, not in the pinned release).
Setting ``out_dtype=float32`` routes the gate through GateLinear's cuBLAS
bf16xbf16->fp32 tier: same GEMM, but the fp32 accumulator is written out
unrounded. Unlike the upstream PR, the gate weight stays bf16, so the LoRA
Triton kernel dtype assert and the bf16 weight-broadcast path are unaffected.
Activated by ``additional_config["fp32_router_logits"] = True``; the launcher
sets this when ``inference.enable_fp32_router_logits`` is set. The flag is read
at module construction, where vLLM guarantees a ``set_current_vllm_config()``
context. No-op if something else already set an out_dtype (e.g. the ROCm AITER
branch, whose kernel wants matching dtypes).
"""
import torch
from vllm.config import get_current_vllm_config
from vllm.logger import init_logger
from vllm.model_executor.models.deepseek_v2 import DeepseekV2MoE
logger = init_logger(__name__)
_original_init = DeepseekV2MoE.__init__
def _patched_init(self, *args, **kwargs):
_original_init(self, *args, **kwargs)
additional_config = get_current_vllm_config().additional_config or {}
if not additional_config.get("fp32_router_logits", False):
return
if self.gate.out_dtype is None:
self.gate.set_out_dtype(torch.float32)
DeepseekV2MoE.__init__ = _patched_init
logger.info("Installed fp32 router logits patch (self-gates on additional_config['fp32_router_logits']).")
def monkey_patch_dp_coordinator_startup_timeout():
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 120s.
+5 -5
View File
@@ -10,11 +10,11 @@ def setup_vllm_env(config: InferenceConfig):
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
# Force the V1 GPU model runner. vLLM routes Llama/Mistral/Qwen3 plus MoE archs
# (DeepseekV2, Qwen2Moe, GraniteMoe) to the V2 runner by default, but V2 doesn't
# support routed-experts capture (the NIXL PD path rejects it). setdefault so it
# stays overridable.
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
# Router replay needs the V1 GPU model runner: V2 silently never captures
# routed experts. Everything else follows vLLM's own V1/V2 resolution.
# setdefault so it stays overridable.
if config.vllm.enable_return_routed_experts:
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
# grammar-constrains generation (xgrammar structural tags) for tool_choice
+1 -5
View File
@@ -20,17 +20,13 @@ from prime_rl.utils.logger import get_logger
logger = get_logger()
from prime_rl.inference.patches import (
monkey_patch_dp_coordinator_startup_timeout,
monkey_patch_harmony_stop_token_propagation,
monkey_patch_nano_v3_reasoning_parser,
monkey_patch_strip_routed_experts_from_chat,
monkey_patch_tokenize_params_validation,
)
# NOTE: Fix harmony stop token propagation for GPT-OSS models
# Upstream issue still open: https://github.com/vllm-project/vllm/issues/22519
monkey_patch_harmony_stop_token_propagation()
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
# Still needed in vLLM 0.20 — upstream rejects prompt_len > max_model_len - max_tokens
# Still needed in vLLM 0.28 — upstream rejects prompt_len > max_model_len - max_tokens
monkey_patch_tokenize_params_validation()
# NOTE: Register Nano V3 reasoning parser so configs can use
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
+31 -271
View File
@@ -3,22 +3,20 @@
vLLM ships a generic tokens-in / tokens-out handler at
``vllm.entrypoints.scale_out.token_in_token_out.serving.ServingTokens`` that covers
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs,
priority, ``data_parallel_rank`` header routing and server-side ``max_tokens``
defaulting. We subclass it for the bits still missing from the upstream handler:
priority, ``data_parallel_rank`` header routing, server-side ``max_tokens``
defaulting and ``usage`` reporting. We subclass it for the bits still missing
from the upstream handler:
1. ``data_parallel_rank`` routing — read from the ``X-data-parallel-rank``
header and forwarded to ``engine_client.generate``. Upstream ``ServingTokens``
now does this too; we keep the equivalent path for the DP-replicated
inference servers prime-RL runs.
1. Compact ``routed_experts`` export — when the engine emits routing
decisions, surface them as ``{data, shape, start, dtype}`` base64 raw-byte
objects (the form the PD router can merge and the renderers parse) instead
of upstream's single ``.npy`` base64 string.
2. Compact ``routed_experts`` export — when the engine emits routing
decisions, surface them as base64 raw-byte payloads without requiring a vLLM
source fork.
3. Server-side ``max_tokens`` defaulting — upstream ``ServingTokens`` now applies
this itself (via ``GenerateRequest.is_sampling_param_provided`` +
``get_max_tokens``); we keep an equivalent guard so callers that omit
``max_tokens`` don't truncate at vLLM's 16-token ``SamplingParams`` default.
2. ``kv_transfer_params`` bridging — upstream ``ServingTokens.serve_tokens``
parses ``request.kv_transfer_params`` but never threads it into the engine,
so PD disagg never fires on ``/inference/v1/generate``. Fixed upstream by
https://github.com/vllm-project/vllm/pull/42644, which missed the 0.28.0
cut — drop the bridge once we pin a release that includes it.
Everything else (request/response schema, sampling params, error handling)
delegates to upstream so we track future vLLM changes for free.
@@ -26,16 +24,13 @@ delegates to upstream so we track future vLLM changes for free.
from __future__ import annotations
from collections.abc import AsyncGenerator, AsyncIterable
from functools import cached_property
from collections.abc import AsyncGenerator
from typing import Any
from fastapi import Request
from vllm.entrypoints.openai.engine.protocol import (
ErrorResponse,
PromptTokenUsageInfo,
RequestResponseMetadata,
UsageInfo,
)
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
GenerateRequest,
@@ -43,25 +38,20 @@ from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
GenerateResponseChoice,
)
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
from vllm.entrypoints.serve.utils.api_utils import get_max_tokens
from vllm.outputs import RequestOutput
from vllm.sampling_params import RequestOutputKind, SamplingParams
from prime_rl.inference.vllm.routed_experts import RoutedExpertsCapture
class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
routed_experts: dict[str, Any] | None = None
# Overrides upstream's base64 ``.npy`` string form with the compact
# ``{data, shape, start, dtype}`` object the PD router merges and the
# renderers parse.
routed_experts: dict[str, Any] | None = None # type: ignore[assignment]
class PrimeRlGenerateResponse(GenerateResponse):
choices: list[PrimeRlGenerateResponseChoice]
# Upstream ``GenerateResponse`` doesn't declare a ``usage`` field, so the
# parent ``ServingTokens.serve_tokens_full_generator`` constructs it and
# Pydantic silently drops it on serialization. Declare it here so the
# router can extract per-run token counts (and cached-prefix tokens) for
# platform billing — see https://github.com/PrimeIntellect-ai/router/pull/43.
usage: UsageInfo | None = None
class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
@@ -73,236 +63,29 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
)
for choice in response.choices
]
return PrimeRlGenerateResponse(
request_id=response.request_id,
choices=choices,
prompt_logprobs=response.prompt_logprobs,
kv_transfer_params=response.kv_transfer_params,
)
class _FinalOutputCapture:
"""Wraps a ``RequestOutput`` async generator to record the last yielded item.
Needed so the response builder can construct a ``usage`` block from
``final_res.prompt_token_ids`` / ``output.token_ids`` / ``num_cached_tokens``
after delegating iteration to upstream.
"""
def __init__(self, source: AsyncIterable[RequestOutput]) -> None:
# ``source`` may be any async-iterable — including
# ``_GenerateRoutedExpertsCapture``, which exposes the protocol via
# ``async def __aiter__`` (an async generator function) and has no
# ``__anext__`` method. Drive it through ``async for`` rather than
# poking ``__anext__`` directly so both shapes work.
self._source = source
self.final_res: RequestOutput | None = None
async def __aiter__(self) -> AsyncGenerator[RequestOutput, None]:
async for item in self._source:
self.final_res = item
yield item
def _build_usage(final_res: RequestOutput) -> UsageInfo:
assert final_res.prompt_token_ids is not None
num_prompt_tokens = len(final_res.prompt_token_ids)
if final_res.encoder_prompt_token_ids is not None:
num_prompt_tokens += len(final_res.encoder_prompt_token_ids)
num_generated_tokens = sum(len(output.token_ids) for output in final_res.outputs)
usage = UsageInfo(
prompt_tokens=num_prompt_tokens,
completion_tokens=num_generated_tokens,
total_tokens=num_prompt_tokens + num_generated_tokens,
)
# Always emit cached tokens when vLLM reports any. Upstream gates this on
# ``enable_prompt_tokens_details`` (default False) for OpenAI-API compat,
# but ``/inference/v1/generate`` is prime-rl internal — the cache-discount
# billing pipeline always wants the cached subset surfaced.
if final_res.num_cached_tokens:
usage.prompt_tokens_details = PromptTokenUsageInfo(cached_tokens=final_res.num_cached_tokens)
return usage
async def _client_set_max_tokens(raw_request: Request | None) -> bool:
"""Whether the inbound JSON body carried ``sampling_params.max_tokens``.
``GenerateRequest.sampling_params`` is parsed into a ``SamplingParams``
instance, which means an unset ``max_tokens`` is indistinguishable from
an explicit ``max_tokens=16`` once the request reaches the handler —
both surface as ``sampling_params.max_tokens == 16``. We re-read the
cached body to recover that distinction. When we can't (no raw_request,
non-JSON body, or read error), pessimistically assume the client did
set it so we never clobber an explicit value.
"""
if raw_request is None:
return True
try:
body = await raw_request.json()
except Exception:
return True
if not isinstance(body, dict):
return True
sp = body.get("sampling_params")
return isinstance(sp, dict) and "max_tokens" in sp
return PrimeRlGenerateResponse(**{**dict(response), "choices": choices})
class PrimeRlServingTokens(ServingTokens):
"""ServingTokens + DP-rank routing + compact routed experts + max_tokens defaulting."""
@cached_property
def _max_tokens_defaults(self) -> tuple[dict, int | None]:
"""Server-side ``max_tokens`` defaulting inputs, mirroring upstream ``ServingTokens``.
Computed lazily because ``custom_init_app_state`` swaps in this
subclass via ``object.__new__`` + ``__dict__.update`` (so our
``__init__`` never runs).
"""
diff = self.model_config.get_diff_sampling_param()
mc = self.model_config
override = (
diff.get("max_tokens")
if mc.generation_config not in ("auto", "vllm")
# Upstream uses ``getattr(..., {})`` directly. Defensive ``or {}``
# in case a downstream caller ever sets the attribute to ``None``
# (``getattr``'s default only fires when the attribute is missing,
# not when it exists with a ``None`` value).
else (getattr(mc, "override_generation_config", None) or {}).get("max_new_tokens")
)
return diff, override
"""ServingTokens + compact routed experts + PD kv_transfer_params bridging."""
async def serve_tokens(
self,
request: GenerateRequest,
raw_request: Request | None = None,
) -> PrimeRlGenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
# Mirrors upstream ``ServingTokens.serve_tokens``. Diffs:
# (a) inject ``data_parallel_rank`` from the inbound header into
# ``engine_client.generate``; (b) default ``sampling_params.max_tokens``
# to ``max_model_len - prompt_len`` when the caller didn't set it; and
# (c) dispatch to our overridden response builder so ``routed_experts``
# makes it into the JSON.
error_check_ret = await self._check_model(request)
if error_check_ret is not None:
return error_check_ret
if self.engine_client.errored:
raise self.engine_client.dead_error
lora_request = self._maybe_get_adapters(request, supports_default_mm_loras=True)
model_name = self.models.model_name(lora_request)
request_id = f"generate-tokens-{self._base_request_id(raw_request, request.request_id)}"
request_metadata = RequestResponseMetadata(request_id=request_id)
if raw_request:
raw_request.state.request_metadata = request_metadata
# Build the engine input — features-aware (MM) or text-only fallback.
# Identical to upstream so we keep tracking it.
if features := request.features:
from vllm.entrypoints.scale_out.token_in_token_out.mm_serde import decode_mm_kwargs_item
from vllm.inputs import mm_input
from vllm.multimodal.inputs import (
MultiModalKwargsItem,
MultiModalKwargsItems,
PlaceholderRange,
)
mm_placeholders = {
modality: [PlaceholderRange(offset=p.offset, length=p.length) for p in ranges]
for modality, ranges in features.mm_placeholders.items()
}
mm_kwargs: dict[str, list[MultiModalKwargsItem | None]] = {}
if features.kwargs_data is not None:
for modality, items in features.kwargs_data.items():
mm_kwargs[modality] = [decode_mm_kwargs_item(item) if item is not None else None for item in items]
else:
for modality, hashes in features.mm_hashes.items():
mm_kwargs[modality] = [None] * len(hashes)
engine_input = mm_input(
prompt_token_ids=request.token_ids,
mm_kwargs=MultiModalKwargsItems(mm_kwargs),
mm_hashes=features.mm_hashes,
mm_placeholders=mm_placeholders,
cache_salt=request.cache_salt,
)
else:
(engine_input,) = await self.online_renderer.preprocess_completion(
request,
prompt_input=request.token_ids,
prompt_embeds=None,
skip_mm_cache=True,
)
sampling_params: SamplingParams = request.sampling_params
# Upstream ``ServingTokens.serve_tokens`` parses ``request.kv_transfer_params``
# but never threads it into the engine, so PD disagg never fires on
# ``/inference/v1/generate`` — decode receives an empty NIXL handshake
# and ends up re-prefilling the prompt locally (~100× slower under
# concurrency). Bridge it through ``sampling_params.extra_args`` so the
# engine's KV connector picks the params up.
#
# Upstream fix: https://github.com/vllm-project/vllm/pull/42644 — drop
# this block once we pin a vLLM version that includes it.
) -> GenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
# Upstream parses ``request.kv_transfer_params`` but never threads it
# into the engine, so decode receives an empty NIXL handshake and
# re-prefills the prompt locally (~100x slower under concurrency).
# Bridge it through ``sampling_params.extra_args`` so the engine's KV
# connector picks the params up. Fixed upstream by vllm#42644 (merged
# after 0.28.0) — drop once we pin a release that includes it.
if request.kv_transfer_params is not None:
extra = sampling_params.extra_args or {}
extra = request.sampling_params.extra_args or {}
extra["kv_transfer_params"] = request.kv_transfer_params
sampling_params.extra_args = extra
request.sampling_params.extra_args = extra
# Server-side ``max_tokens`` defaulting — see module docstring. Upstream
# ``ServingTokens`` now does this too; kept here so callers that omit
# ``max_tokens`` don't get capped at vLLM's 16-token ``SamplingParams``
# default.
if not await _client_set_max_tokens(raw_request):
diff_sp, override = self._max_tokens_defaults
sampling_params.max_tokens = get_max_tokens(
max_model_len=self.model_config.max_model_len,
max_tokens=None,
input_length=len(request.token_ids),
default_sampling_params=diff_sp,
override_max_tokens=override,
)
if self.force_no_detokenize:
sampling_params.detokenize = False
if request.stream:
sampling_params.output_kind = RequestOutputKind.DELTA
self._log_inputs(
request_id,
engine_input,
params=sampling_params,
lora_request=lora_request,
)
trace_headers = None if raw_request is None else await self._get_trace_headers(raw_request.headers)
result_generator = self.engine_client.generate(
engine_input,
sampling_params,
request_id,
lora_request=lora_request,
trace_headers=trace_headers,
priority=request.priority,
data_parallel_rank=self._get_data_parallel_rank(raw_request),
)
if request.stream:
# Streaming path: defer to upstream — prime-RL's renderer client
# only consumes the full response, so adding routed_experts to the
# streaming choice schema is unnecessary churn.
return self.serve_tokens_stream_generator(
request,
result_generator,
request_id,
model_name,
request_metadata,
)
return await self.serve_tokens_full_generator(
request, result_generator, request_id, model_name, request_metadata
)
return await super().serve_tokens(request, raw_request)
async def serve_tokens_full_generator( # type: ignore[override]
self,
@@ -317,40 +100,17 @@ class PrimeRlServingTokens(ServingTokens):
# experts surface in the JSON.
capture: _GenerateRoutedExpertsCapture | None = None
if self.model_config.enable_return_routed_experts:
start = request.sampling_params.routed_experts_prompt_start
capture = _GenerateRoutedExpertsCapture(
result_generator,
start=start,
start=request.sampling_params.routed_experts_prompt_start,
)
result_generator = capture
# Always capture the final ``RequestOutput`` so we can attach a
# ``usage`` block to the response. The router parses ``usage`` for
# per-run billing metrics; without it the cache-discount counter
# (``vllm_router_run_cached_prompt_tokens_total``) stays at zero.
final_capture = _FinalOutputCapture(result_generator)
result_generator = final_capture
response = await super().serve_tokens_full_generator(
request, result_generator, request_id, model_name, request_metadata
)
if not isinstance(response, GenerateResponse):
return response
if capture is not None:
if capture is not None and isinstance(response, GenerateResponse):
response = capture.post_process(response)
elif not isinstance(response, PrimeRlGenerateResponse):
# Upgrade to the prime-rl subclass so the declared ``usage`` field
# actually surfaces in JSON (the parent class would drop it).
response = PrimeRlGenerateResponse(
request_id=response.request_id,
choices=[PrimeRlGenerateResponseChoice(**choice.model_dump()) for choice in response.choices],
prompt_logprobs=response.prompt_logprobs,
kv_transfer_params=response.kv_transfer_params,
)
if final_capture.final_res is not None:
response.usage = _build_usage(final_capture.final_res)
return response
@@ -3,7 +3,6 @@ import os
from prime_rl.inference.patches import (
monkey_patch_fp32_lm_head,
monkey_patch_fp32_router_logits,
monkey_patch_minimax_m2_for_lora,
monkey_patch_no_moe_lora,
)
@@ -21,6 +20,3 @@ else:
# Install fp32 lm_head patch; self-gates on additional_config["fp32_lm_head"] at call time
monkey_patch_fp32_lm_head()
# Install fp32 router logits patch; self-gates on additional_config["fp32_router_logits"]
monkey_patch_fp32_router_logits()
+52 -106
View File
@@ -13,17 +13,21 @@ from typing import TYPE_CHECKING, Any, cast
import torch
import torch.nn as nn
from modelexpress import p2p_pb2
from modelexpress.client import MxClient
from vllm.config import set_current_vllm_config
from vllm.logger import init_logger
from prime_rl.inference.vllm.worker.weight_transfer import update_mla_absorbed_weights
from prime_rl.transports.weights.nixl.agent import MemDesc, NixlAgent, make_agent_name, set_ucx_env_defaults
from prime_rl.transports.weights.nixl.cuda_malloc_memory import (
size_cuda_buffers,
use_cuda_malloc_pool,
from prime_rl.transports.weights.nixl.agent import (
MemDesc,
NixlAgent,
NixlPeer,
PreparedRead,
group_notification,
make_agent_name,
set_ucx_env_defaults,
)
from prime_rl.transports.weights.nixl.cuda_malloc_memory import use_cuda_malloc_pool
from prime_rl.transports.weights.nixl.graph import (
Destination,
OperationChain,
@@ -44,7 +48,6 @@ else:
Worker = object
logger = init_logger("vllm.inference.vllm.worker_nixl")
_BUFFER_POLL_INTERVAL = 0.01
@dataclass
@@ -69,13 +72,14 @@ class LayerWeightTransferPlan:
class WeightTransferGroup:
name: str
layers: list[LayerWeightTransferPlan]
pulls: list[tuple[Any, Any, list[int]]]
pulls: list[PreparedRead]
@dataclass
class WeightTransferPlan:
receive_arenas: dict[torch.dtype, torch.Tensor]
receive_buffer_count: int
trainer_peers: list[NixlPeer]
groups: list[WeightTransferGroup]
@@ -100,7 +104,7 @@ class NIXLWeightUpdateWorker(Worker):
del inference_world_size, quantize_in_weight_transfer
global_rank = rank_offset + self.device.index
server_url = f"{host}:{port}"
set_ucx_env_defaults()
set_ucx_env_defaults(self.device.index)
self.nixl_agent = NixlAgent(make_agent_name("inference", global_rank))
self.model_express = ModelExpressSession(
client=MxClient(server_url=server_url),
@@ -109,6 +113,7 @@ class NIXLWeightUpdateWorker(Worker):
session_id=session_id,
worker_id=f"inference-{global_rank}",
)
self.model_express.publish(nixl_metadata=self.nixl_agent.get_metadata())
self.weight_transfer_timeout = timeout
self.weight_transfer_plan: WeightTransferPlan | None = None
logger.info(
@@ -126,30 +131,13 @@ class NIXLWeightUpdateWorker(Worker):
trainer_ref = self.model_express.wait_for(
"trainer",
count=1,
status=None,
timeout=self.weight_transfer_timeout,
)[0]
table = TrainerTensorTable.decode(self.model_express.fetch(trainer_ref).nixl_metadata)
copies = self.trace_weight_loads(table)
plan = self.build_transfer_plan(table, copies)
self.buffer_sessions = []
for buffer_index in range(table.staging_buffer_count):
session = ModelExpressSession(
client=self.model_express.client,
role="inference",
rank=self.model_express.rank,
session_id=f"{self.model_express.session_id}:layers:{buffer_index}",
worker_id=f"inference-buffer-{self.model_express.rank}-{buffer_index}",
)
session.publish()
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
self.buffer_sessions.append(session)
# Join the current generation directly. Publishing a transient READY
# before the first pull would let the trainer mistake initialization
# for a completed acknowledgement.
self.model_express.publish(nixl_metadata=self.nixl_agent.get_metadata())
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
self.weight_transfer_plan = plan
self.group_generations = [0] * len(plan.groups)
logger.info(
"Initialized NIXL transfer plan on rank %d with %d groups",
self.model_express.rank,
@@ -255,14 +243,16 @@ class NIXLWeightUpdateWorker(Worker):
copies,
replay_plans,
)
receive_buffer_count = self.choose_receive_buffer_count(
receive_buffer_elements,
table.staging_buffer_count,
)
receive_buffer_count = table.staging_buffer_count
receive_arenas = self.allocate_receive_arenas(
receive_buffer_elements,
receive_buffer_count,
)
peers: list[NixlPeer] = []
for agent in table.agents:
peer = self.nixl_agent.add_remote_agent(agent.metadata)
self.nixl_agent.make_connection(peer)
peers.append(peer)
groups = self.build_transfer_groups(
table,
copies,
@@ -270,10 +260,12 @@ class NIXLWeightUpdateWorker(Worker):
receive_buffer_elements,
receive_arenas,
receive_buffer_count,
peers,
)
return WeightTransferPlan(
receive_arenas=receive_arenas,
receive_buffer_count=receive_buffer_count,
trainer_peers=peers,
groups=groups,
)
@@ -310,31 +302,6 @@ class NIXLWeightUpdateWorker(Worker):
group_elements[source_dtype][tensor_groups[source.name]] += prod(replay_plans[id(copy)].source_shape)
return {dtype: max(elements, default=0) for dtype, elements in group_elements.items()}
def choose_receive_buffer_count(
self,
receive_buffer_elements: dict[torch.dtype, int],
staging_buffer_count: int,
) -> int:
receive_buffer_bytes = max(
1,
sum(elements * dtype.itemsize for dtype, elements in receive_buffer_elements.items()),
)
allocated_bytes = torch.cuda.memory_allocated(self.device)
peak_growth_bytes = max(
0,
torch.cuda.max_memory_allocated(self.device) - allocated_bytes,
)
free_bytes, _ = torch.cuda.mem_get_info(self.device)
max_receive_buffers = min(2, staging_buffer_count) if peak_growth_bytes else 1
if peak_growth_bytes or free_bytes < receive_buffer_bytes:
torch.cuda.empty_cache()
return size_cuda_buffers(
receive_buffer_bytes,
max_receive_buffers,
self.device,
extra_headroom_bytes=receive_buffer_bytes + peak_growth_bytes,
)
def allocate_receive_arenas(
self,
receive_buffer_elements: dict[torch.dtype, int],
@@ -362,6 +329,7 @@ class NIXLWeightUpdateWorker(Worker):
receive_buffer_elements: dict[torch.dtype, int],
receive_arenas: dict[torch.dtype, torch.Tensor],
receive_buffer_count: int,
peers: list[NixlPeer],
) -> list[WeightTransferGroup]:
tensors = {tensor.name: tensor for group in table.groups for tensor in group.tensors}
tensor_groups = {
@@ -390,7 +358,6 @@ class NIXLWeightUpdateWorker(Worker):
)
agent_devices = {agent_index: agent.device_id for agent_index, agent in enumerate(table.agents)}
peer_names: dict[int, str] = {}
transfer_groups: list[WeightTransferGroup] = []
for group_index, group in enumerate(table.groups):
@@ -432,10 +399,9 @@ class NIXLWeightUpdateWorker(Worker):
persistent_plans_by_layer,
),
pulls=self.prepare_group_pulls(
table,
local_descs,
remote_descs,
peer_names,
peers,
),
)
)
@@ -486,40 +452,37 @@ class NIXLWeightUpdateWorker(Worker):
def prepare_group_pulls(
self,
table: TrainerTensorTable,
local_descs: dict[int, list[MemDesc]],
remote_descs: dict[int, list[MemDesc]],
peer_names: dict[int, str],
) -> list[tuple[Any, Any, list[int]]]:
pulls: list[tuple[Any, Any, list[int]]] = []
for agent_index, remote in sorted(remote_descs.items()):
peer_name = peer_names.get(agent_index)
if peer_name is None:
peer_name = self.nixl_agent.add_remote_agent(table.agents[agent_index].metadata)
self.nixl_agent.make_connection(peer_name)
peer_names[agent_index] = peer_name
peers: list[NixlPeer],
) -> list[PreparedRead]:
pulls: list[PreparedRead] = []
agent_indices = sorted(remote_descs)
rotation = self.model_express.rank % len(agent_indices) if agent_indices else 0
agent_indices = agent_indices[rotation:] + agent_indices[:rotation]
for agent_index in agent_indices:
remote = remote_descs[agent_index]
peer = peers[agent_index]
local_prepared = self.nixl_agent.prepare_xfer_dlist(local_descs[agent_index])
remote_prepared = self.nixl_agent.prepare_xfer_dlist(remote, agent_name=peer_name)
pulls.append((local_prepared, remote_prepared, list(range(len(remote)))))
remote_prepared = self.nixl_agent.prepare_xfer_dlist(remote, peer=peer)
pulls.append(
self.nixl_agent.prepare_read(
local_prepared,
list(range(len(remote))),
remote_prepared,
)
)
return pulls
@torch.no_grad()
def update_weights_from_path(self, weight_dir: str | None = None) -> None:
del weight_dir
plan = self.initialize_transfer()
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
self.model_express.wait_for(
"trainer",
count=1,
status=p2p_pb2.SOURCE_STATUS_READY,
timeout=self.weight_transfer_timeout,
)
started = time.perf_counter()
self.apply_transfer_plan(plan)
update_mla_absorbed_weights(self.raw_model)
torch.cuda.synchronize(self.device)
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_READY)
logger.info(
"Applied NIXL policy update on rank %d in %.2fs",
self.model_express.rank,
@@ -542,44 +505,30 @@ class NIXLWeightUpdateWorker(Worker):
def pull_group(group_index: int) -> WeightTransferGroup:
transfer_group = plan.groups[group_index]
session = self.buffer_sessions[group_index % len(self.buffer_sessions)]
session.wait_for(
"trainer",
count=1,
status=p2p_pb2.SOURCE_STATUS_READY,
notification = group_notification(group_index, self.group_generations[group_index])
self.nixl_agent.wait_for_notification(
plan.trainer_peers,
notification,
timeout=self.weight_transfer_timeout,
poll_interval=_BUFFER_POLL_INTERVAL,
cancelled=cancelled.is_set,
)
for local, remote, indices in transfer_group.pulls:
handle = self.nixl_agent.post_read(local, indices, remote)
for read in transfer_group.pulls:
self.nixl_agent.post_read(read, notification)
for read in transfer_group.pulls:
self.nixl_agent.wait(
handle,
read,
context=f"weight pull for {transfer_group.name}",
timeout=self.weight_transfer_timeout,
cancelled=cancelled.is_set,
)
return transfer_group
def acknowledge_group(group_index: int) -> None:
session = self.buffer_sessions[group_index % len(self.buffer_sessions)]
session.set_status(p2p_pb2.SOURCE_STATUS_READY)
session.wait_for(
"trainer",
count=1,
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
timeout=self.weight_transfer_timeout,
poll_interval=_BUFFER_POLL_INTERVAL,
cancelled=cancelled.is_set,
)
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
self.group_generations[group_index] += 1
return transfer_group
def prefetch_group(group_index: int) -> WeightTransferGroup:
torch.cuda.set_device(self.device)
transfer_group = pull_group(group_index)
acknowledge_group(group_index)
return transfer_group
return pull_group(group_index)
def replay_group(transfer_group: WeightTransferGroup) -> None:
for layer_plan in transfer_group.layers:
@@ -625,9 +574,6 @@ class NIXLWeightUpdateWorker(Worker):
replay_group(transfer_group)
torch.cuda.synchronize(self.device)
if not pipelined:
acknowledge_group(group_index)
finally:
cancelled.set()
if executor is not None:
-1
View File
@@ -33,7 +33,6 @@ OVERVIEW_NAME = "overview"
# agent. Only the score metric differs — train scores with "reward/mean", eval with "avg@k" (its k
# dynamic, so also a regex) — and each section builder prepends its own.
COMMON_METRICS = [
"all/dispatch_failure/mean",
"effective/num_total_tokens/mean",
"effective/num_turns/mean",
"effective/num_branches/mean",
+6 -17
View File
@@ -854,10 +854,9 @@ class Orchestrator:
"""Per-step ``Step …`` success line. Multi-env runs append an indented ``╰─`` line per env.
Every quality metric (Reward, Trainable, Turns, Branches, Max Off-Policy, Truncation) is
computed over exactly the traces shipped to the trainer this step (``batch.cohort``).
``Error``, ``Dispatch Failure``, ``Cancelled``, and ``Ratio`` describe the step's full arrival window —
over the shipped set they are 0/0/share-of-shipped by construction, so the window is the
only scope where they carry signal (and they stay disjoint: a cancellation is a pipeline
decision, an episode error came from the environment, and a dispatch failure produced no episode)."""
``Error``, ``Cancelled``, and ``Ratio`` describe the step's full arrival window. Over the
shipped set they are 0/0/share-of-shipped by construction, so the window is the only scope
where they carry signal. A cancellation is a pipeline decision, not a rollout failure."""
episodes = batch.episodes
effective = batch.cohort.effective
eff = effective.metrics
@@ -866,16 +865,13 @@ class Orchestrator:
n_trainable = sum(is_trainable(record.trace) for record in effective.records)
trainable_rate = (n_trainable / n_effective) if n_effective else 0.0
max_off_policy_steps = max((episode_staleness(episode, step)[0] for episode in effective), default=0)
num_attempts = len(episodes) + len(batch.failures)
dispatch_failure_rate = len(batch.failures) / num_attempts if num_attempts else 0.0
head = (
f"Step {step} | {format_time(step_time):>7} | Reward {eff.reward.mean():.4f} | "
f"Trainable {n_trainable}/{n_effective} ({trainable_rate:.1%}) | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Max Off-Policy {max_off_policy_steps} | "
f"Error {episodes.metrics.has_error.mean():.1%} | Dispatch Failure {dispatch_failure_rate:.1%} | "
f"Cancelled {episodes.metrics.cancelled.mean():.1%} | "
f"Error {episodes.metrics.has_error.mean():.1%} | Cancelled {episodes.metrics.cancelled.mean():.1%} | "
f"Truncation {eff.is_truncated.mean():.1%}"
)
if len(self.train_envs) <= 1:
@@ -884,10 +880,7 @@ class Orchestrator:
window_by_env = episodes.by_env()
shipped_by_env = effective.by_env()
failures_by_env: dict[str, list[DispatchFailure]] = {}
for failure in batch.failures:
failures_by_env.setdefault(failure.env_name, []).append(failure)
env_names = sorted(set(window_by_env) | set(shipped_by_env) | set(failures_by_env))
env_names = sorted(set(window_by_env) | set(shipped_by_env))
name_width = max((len(name) for name in env_names), default=0)
lines = [head]
for env_name in env_names:
@@ -895,15 +888,11 @@ class Orchestrator:
env_eff_pool = shipped_by_env.get(env_name, TrainEpisodes())
env_eff = env_eff_pool.metrics
ratio = (pool.num_traces / n_generated) if n_generated else 0.0
env_failures = failures_by_env.get(env_name, [])
env_attempts = len(pool) + len(env_failures)
env_failure_rate = len(env_failures) / env_attempts if env_attempts else 0.0
lines.append(
f"╰─ {env_name:<{name_width}} | Ratio {ratio:.1%} | Reward {env_eff.reward.mean():.4f} | "
f"Turns {env_eff.num_turns.mean():.1f} | Branches {env_eff.num_branches.mean():.1f} | "
f"Max Off-Policy {max((episode_staleness(episode, step)[0] for episode in env_eff_pool), default=0)} | "
f"Error {pool.metrics.has_error.mean():.1%} | Dispatch Failure {env_failure_rate:.1%} | "
f"Cancelled {pool.metrics.cancelled.mean():.1%} | "
f"Error {pool.metrics.has_error.mean():.1%} | Cancelled {pool.metrics.cancelled.mean():.1%} | "
f"Truncation {env_eff.is_truncated.mean():.1%}"
)
get_logger().success("\n\t\t ".join(lines))
+95 -1
View File
@@ -138,6 +138,17 @@ export MASTER_ADDR="${HOSTNAMES[$NUM_INFER_NODES]}"
export MASTER_PORT=29500
echo "MASTER_ADDR=${MASTER_ADDR}"
echo "MASTER_PORT=${MASTER_PORT}"
{% if use_nixl_broadcast -%}
{% if launch_modelexpress -%}
export WEIGHT_BROADCAST_HOST="$MASTER_ADDR"
{% else -%}
export WEIGHT_BROADCAST_HOST="{{ modelexpress_host }}"
{% endif -%}
export MODEL_EXPRESS_PORT={{ modelexpress_port }}
export MODEL_EXPRESS_REDIS_PORT={{ modelexpress_redis_port }}
echo "WEIGHT_BROADCAST_HOST=${WEIGHT_BROADCAST_HOST}"
echo "MODEL_EXPRESS_PORT=${MODEL_EXPRESS_PORT}"
{% endif %}
# The orchestrator runs on trainer rank 0's node (SLURM_PROCID == NUM_INFER_NODES) by
# default; with orchestrator_on_inference it moves to the last inference node (a decode
@@ -198,6 +209,10 @@ srun bash -s <<'CLEANUP_SH'
# the exact process name, so it never hits the worktree path (e.g. mooncake-baby).
pkill -9 -x mooncake_master 2>/dev/null
pkill -9 -x mooncake_client 2>/dev/null
{% if use_nixl_broadcast and launch_modelexpress %}
pkill -9 -f "[m]odelexpress-server" 2>/dev/null
pkill -9 -x redis-server 2>/dev/null
{% endif %}
sleep 2
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_|[e]pp |envoy|pd-sidecar" | grep -v grep | wc -l)
@@ -234,6 +249,83 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
IB_HCA=$(ibv_devinfo | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" |paste -sd,)
export NCCL_IB_HCA=$IB_HCA
{% if use_nixl_broadcast -%}
UCX_DIR="$PROJECT_DIR/third_party/ucx"
if [ ! -x "$UCX_DIR/bin/ucx_info" ]; then
echo "NIXL requires the UCX build installed by scripts/install_nixl_from_source.sh" >&2
exit 1
fi
export LD_LIBRARY_PATH="$UCX_DIR/lib:$UCX_DIR/lib/ucx:${LD_LIBRARY_PATH:-}"
UCX_TRANSPORTS=$("$UCX_DIR/bin/ucx_info" -d)
grep -q "Transport: cuda_copy" <<< "$UCX_TRANSPORTS" || {
echo "NIXL requires UCX cuda_copy support" >&2
exit 1
}
grep -q "Transport: rc_verbs" <<< "$UCX_TRANSPORTS" || {
echo "NIXL requires UCX rc_verbs support" >&2
exit 1
}
{% if launch_modelexpress %}
if [ "$SLURM_PROCID" -eq "$NUM_INFER_NODES" ]; then
MX_BIN="$PROJECT_DIR/third_party/modelexpress/bin"
if [ ! -x "$MX_BIN/modelexpress-server" ] || [ ! -x "$MX_BIN/redis-server" ]; then
echo "ModelExpress server dependencies are missing; run scripts/install_modelexpress.sh" >&2
exit 1
fi
MX_STATE_DIR="$LOG_DIR/modelexpress"
mkdir -p "$MX_STATE_DIR/cache"
"$MX_BIN/redis-server" \
--port "$MODEL_EXPRESS_REDIS_PORT" \
--bind 127.0.0.1 \
--protected-mode no \
--save "" \
--appendonly no \
--dir "$MX_STATE_DIR" \
> "$MX_STATE_DIR/redis.log" 2>&1 &
REDIS_PID=$!
trap '[ -z "${MODEL_EXPRESS_PID:-}" ] || kill -TERM "$MODEL_EXPRESS_PID" 2>/dev/null; kill -TERM "$REDIS_PID" 2>/dev/null || true' EXIT
for _ in $(seq 1 60); do
timeout 1 bash -c "echo > /dev/tcp/127.0.0.1/$MODEL_EXPRESS_REDIS_PORT" 2>/dev/null && break
kill -0 "$REDIS_PID" 2>/dev/null || {
tail -50 "$MX_STATE_DIR/redis.log" >&2
exit 1
}
sleep 1
done
timeout 1 bash -c "echo > /dev/tcp/127.0.0.1/$MODEL_EXPRESS_REDIS_PORT" 2>/dev/null || {
echo "Redis did not become ready on port $MODEL_EXPRESS_REDIS_PORT" >&2
exit 1
}
MX_METADATA_BACKEND=redis \
REDIS_URL="redis://127.0.0.1:$MODEL_EXPRESS_REDIS_PORT" \
MX_HEARTBEAT_TIMEOUT_SECS=31536000 \
"$MX_BIN/modelexpress-server" \
--port "$MODEL_EXPRESS_PORT" \
--database-path "$MX_STATE_DIR/models.db" \
--cache-directory "$MX_STATE_DIR/cache" \
> "$MX_STATE_DIR/server.log" 2>&1 &
MODEL_EXPRESS_PID=$!
fi
{% endif %}
for _ in $(seq 1 120); do
timeout 1 bash -c "echo > /dev/tcp/$WEIGHT_BROADCAST_HOST/$MODEL_EXPRESS_PORT" 2>/dev/null && break
if [ -n "${MODEL_EXPRESS_PID:-}" ] && ! kill -0 "$MODEL_EXPRESS_PID" 2>/dev/null; then
tail -50 "$MX_STATE_DIR/server.log" >&2
exit 1
fi
sleep 1
done
timeout 1 bash -c "echo > /dev/tcp/$WEIGHT_BROADCAST_HOST/$MODEL_EXPRESS_PORT" 2>/dev/null || {
echo "ModelExpress is not reachable at $WEIGHT_BROADCAST_HOST:$MODEL_EXPRESS_PORT" >&2
exit 1
}
{% endif %}
{% if num_infer_nodes > 0 -%}
if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
@@ -423,7 +515,8 @@ else
--local-ranks-filter={{ ranks_filter }} \
-m prime_rl.trainer.rl.train \
@ $CONFIG_DIR/trainer.json \
{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
{% if use_nixl_broadcast %}--weight-broadcast.host $WEIGHT_BROADCAST_HOST \
{% endif %}{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
COMPONENT_CODE=$?
if [ "$COMPONENT_CODE" -eq 0 ] && [ "$TRAIN_NODE_RANK" -eq 0 ]; then
@@ -468,6 +561,7 @@ if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
(
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
{% elif use_nixl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $WEIGHT_BROADCAST_HOST"
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $ORCH_ADDR"
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
2>&1 | tee $LOG_DIR/orchestrator.log
@@ -40,4 +40,87 @@ uv sync --all-extras --all-packages
{{ pre_run_command }}
{% endif %}
export PRL_RUN_ID=${PRL_RUN_ID:-$(python3 -c "import uuid; print(uuid.uuid4().hex)")}
uv run rl @ {{ config_path }}
{% if use_nixl_broadcast %}
{% if launch_modelexpress -%}
export WEIGHT_BROADCAST_HOST="127.0.0.1"
{% else -%}
export WEIGHT_BROADCAST_HOST="{{ modelexpress_host }}"
{% endif -%}
export MODEL_EXPRESS_PORT={{ modelexpress_port }}
UCX_DIR="$PROJECT_DIR/third_party/ucx"
if [ ! -x "$UCX_DIR/bin/ucx_info" ]; then
echo "NIXL requires the UCX build installed by scripts/install_nixl_from_source.sh" >&2
exit 1
fi
export LD_LIBRARY_PATH="$UCX_DIR/lib:$UCX_DIR/lib/ucx:${LD_LIBRARY_PATH:-}"
UCX_TRANSPORTS=$("$UCX_DIR/bin/ucx_info" -d)
grep -q "Transport: cuda_copy" <<< "$UCX_TRANSPORTS" || {
echo "NIXL requires UCX cuda_copy support" >&2
exit 1
}
grep -q "Transport: rc_verbs" <<< "$UCX_TRANSPORTS" || {
echo "NIXL requires UCX rc_verbs support" >&2
exit 1
}
{% if launch_modelexpress %}
MX_BIN="$PROJECT_DIR/third_party/modelexpress/bin"
if [ ! -x "$MX_BIN/modelexpress-server" ] || [ ! -x "$MX_BIN/redis-server" ]; then
echo "ModelExpress server dependencies are missing; run scripts/install_modelexpress.sh" >&2
exit 1
fi
pkill -9 -f "[m]odelexpress-server" 2>/dev/null || true
pkill -9 -x redis-server 2>/dev/null || true
MX_STATE_DIR="{{ output_dir }}/modelexpress"
mkdir -p "$MX_STATE_DIR/cache"
"$MX_BIN/redis-server" \
--port {{ modelexpress_redis_port }} \
--bind 127.0.0.1 \
--protected-mode no \
--save "" \
--appendonly no \
--dir "$MX_STATE_DIR" \
> "$MX_STATE_DIR/redis.log" 2>&1 &
REDIS_PID=$!
trap '[ -z "${MODEL_EXPRESS_PID:-}" ] || kill -TERM "$MODEL_EXPRESS_PID" 2>/dev/null; kill -TERM "$REDIS_PID" 2>/dev/null || true' EXIT
for _ in $(seq 1 60); do
timeout 1 bash -c "echo > /dev/tcp/127.0.0.1/{{ modelexpress_redis_port }}" 2>/dev/null && break
kill -0 "$REDIS_PID" 2>/dev/null || {
tail -50 "$MX_STATE_DIR/redis.log" >&2
exit 1
}
sleep 1
done
timeout 1 bash -c "echo > /dev/tcp/127.0.0.1/{{ modelexpress_redis_port }}" 2>/dev/null || {
echo "Redis did not become ready on port {{ modelexpress_redis_port }}" >&2
exit 1
}
MX_METADATA_BACKEND=redis \
REDIS_URL="redis://127.0.0.1:{{ modelexpress_redis_port }}" \
MX_HEARTBEAT_TIMEOUT_SECS=31536000 \
"$MX_BIN/modelexpress-server" \
--port {{ modelexpress_port }} \
--database-path "$MX_STATE_DIR/models.db" \
--cache-directory "$MX_STATE_DIR/cache" \
> "$MX_STATE_DIR/server.log" 2>&1 &
MODEL_EXPRESS_PID=$!
{% endif %}
for _ in $(seq 1 120); do
timeout 1 bash -c "echo > /dev/tcp/$WEIGHT_BROADCAST_HOST/$MODEL_EXPRESS_PORT" 2>/dev/null && break
{% if launch_modelexpress %}
kill -0 "$MODEL_EXPRESS_PID" 2>/dev/null || {
tail -50 "$MX_STATE_DIR/server.log" >&2
exit 1
}
{% endif %}
sleep 1
done
timeout 1 bash -c "echo > /dev/tcp/$WEIGHT_BROADCAST_HOST/$MODEL_EXPRESS_PORT" 2>/dev/null || {
echo "ModelExpress is not reachable at $WEIGHT_BROADCAST_HOST:$MODEL_EXPRESS_PORT" >&2
exit 1
}
{% endif %}
uv run rl @ {{ config_path }}{% if use_nixl_broadcast %} --weight-broadcast.host "$WEIGHT_BROADCAST_HOST"{% endif %}
+2 -2
View File
@@ -1,3 +1,3 @@
from prime_rl.trainer.distributed.expert_parallel import DeepEPExpertParallel, MXFP8AllToAllExpertParallel, get_ep_group
from prime_rl.trainer.distributed.expert_parallel import ExpertWeightParallel
__all__ = ["DeepEPExpertParallel", "MXFP8AllToAllExpertParallel", "get_ep_group"]
__all__ = ["ExpertWeightParallel"]
+175 -57
View File
@@ -5,11 +5,18 @@ from deep_ep import Buffer
from deep_ep.utils import EventHandle, EventOverlap
from torch.distributed import ProcessGroup
from prime_rl.trainer.distributed.token_dispatcher import (
ExpertFunction,
PermutationState,
TokenDispatcherBase,
permute_for_grouped_gemm,
unpermute_from_grouped_gemm,
)
_buffer: Buffer | None = None
_handle_cache: dict[int, object] = {}
_pending_dispatch_events: dict[int, EventOverlap] = {}
_handle_counter = 0
_pending_combine_event: EventOverlap | None = None
_deepep_cuda_ops_registered = False
_deepep_cuda_lib: torch.library.Library | None = None
@@ -115,9 +122,12 @@ def _dispatch_backward(
class _DeepEPCombine(torch.autograd.Function):
@staticmethod
def forward(ctx, x: torch.Tensor, handle_id: torch.Tensor) -> torch.Tensor:
global _pending_combine_event
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()}"
@@ -130,12 +140,12 @@ class _DeepEPCombine(torch.autograd.Function):
async_finish=True,
allocate_on_comm_stream=True,
)
_pending_combine_event = after_event
pending_events.append(after_event)
ctx.handle = handle
return combined
@staticmethod
def backward(ctx, grad_combined: torch.Tensor) -> tuple[torch.Tensor, None]:
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."
@@ -154,16 +164,7 @@ class _DeepEPCombine(torch.autograd.Function):
allocate_on_comm_stream=True,
)
after_event.current_stream_wait()
return grad_x, None
@torch.compiler.disable()
def sync_combine() -> None:
global _pending_combine_event
if _pending_combine_event is not None:
_pending_combine_event.current_stream_wait()
_pending_combine_event = None
return grad_x, None, None
@torch.compiler.disable()
@@ -235,14 +236,6 @@ def _unpermute_tokens(
return output_hidden_states
@dataclass
class _DispatchState:
handle_id: torch.Tensor
permuted_indices: torch.Tensor
num_recv_tokens: int
permuted_scores: torch.Tensor | None = None
@dataclass
class _PendingDispatchState:
hidden_states: torch.Tensor
@@ -295,50 +288,175 @@ def dispatch_tokens_async(
)
def finalize_dispatch_tokens(pending_state: _PendingDispatchState) -> tuple[torch.Tensor, torch.Tensor, _DispatchState]:
_sync_dispatch(pending_state.handle_id)
@dataclass(frozen=True)
class DeepEPDispatchState:
handle_id: torch.Tensor
deep_ep_permuted_indices: torch.Tensor
num_received_tokens: int
scores_after_experts: torch.Tensor | None
grouped_gemm_permutation: PermutationState
hidden_states = pending_state.hidden_states
num_recv_tokens = hidden_states.shape[0]
hidden_states, permuted_scores, permuted_indices = _permute_tokens(
hidden_states,
pending_state.dispatched_indices,
pending_state.dispatched_scores,
)
num_tokens_per_expert = pending_state.num_tokens_per_expert.to(hidden_states.device)
if pending_state.score_before_experts and permuted_scores is not None:
hidden_states = (hidden_states.to(torch.float32) * permuted_scores.to(torch.float32).reshape(-1, 1)).to(
hidden_states.dtype
class DeepEPTokenDispatcher(TokenDispatcherBase[DeepEPDispatchState]):
def __init__(
self,
*,
num_experts: int,
token_group_alignment: int,
group: ProcessGroup,
num_sms: int,
token_chunk_size: int | None,
) -> None:
super().__init__(num_experts, token_group_alignment)
self.num_local_experts = num_experts // group.size()
self.group = group
self.token_chunk_size = token_chunk_size
self._pending_combine_events: list[EventOverlap] = []
self._concatenate_stream: torch.cuda.Stream | None = None
self._output_event: torch.cuda.Event | None = None
configure_num_sms(num_sms)
def _finalize_dispatch(
self, pending_state: _PendingDispatchState
) -> tuple[torch.Tensor, torch.Tensor, DeepEPDispatchState]:
_sync_dispatch(pending_state.handle_id)
hidden_states = pending_state.hidden_states
num_received_tokens = hidden_states.shape[0]
hidden_states, permuted_scores, deep_ep_permuted_indices = _permute_tokens(
hidden_states,
pending_state.dispatched_indices,
pending_state.dispatched_scores,
)
permuted_scores_for_state = None
else:
permuted_scores_for_state = permuted_scores
num_tokens_per_expert = pending_state.num_tokens_per_expert.to(hidden_states.device)
state = _DispatchState(
handle_id=pending_state.handle_id,
permuted_indices=permuted_indices,
num_recv_tokens=num_recv_tokens,
permuted_scores=permuted_scores_for_state,
)
return hidden_states, num_tokens_per_expert, state
if pending_state.score_before_experts:
hidden_states = (hidden_states.float() * permuted_scores.float().reshape(-1, 1)).to(hidden_states.dtype)
scores_after_experts = None
else:
scores_after_experts = permuted_scores
def combine_tokens(hidden_states: torch.Tensor, state: _DispatchState) -> torch.Tensor:
if state.permuted_scores is not None:
hidden_states = (hidden_states.to(torch.float32) * state.permuted_scores.to(torch.float32).reshape(-1, 1)).to(
hidden_states.dtype
hidden_states, num_tokens_per_expert, grouped_gemm_permutation = permute_for_grouped_gemm(
hidden_states,
num_tokens_per_expert,
experts_per_rank=self.num_local_experts,
num_ranks=1,
alignment=self.token_group_alignment,
)
hidden_states = _unpermute_tokens(hidden_states, state.permuted_indices, state.num_recv_tokens)
return _DeepEPCombine.apply(hidden_states, state.handle_id)
state = DeepEPDispatchState(
handle_id=pending_state.handle_id,
deep_ep_permuted_indices=deep_ep_permuted_indices,
num_received_tokens=num_received_tokens,
scores_after_experts=scores_after_experts,
grouped_gemm_permutation=grouped_gemm_permutation,
)
return hidden_states, num_tokens_per_expert, state
def dispatch(
self,
x: torch.Tensor,
top_scores: torch.Tensor,
selected_experts_indices: torch.Tensor,
*,
score_before_experts: bool,
) -> tuple[torch.Tensor, torch.Tensor, DeepEPDispatchState]:
pending_state = dispatch_tokens_async(
x,
selected_experts_indices,
top_scores,
num_experts=self.num_experts,
group=self.group,
score_before_experts=score_before_experts,
)
return self._finalize_dispatch(pending_state)
def combine(self, routed_output: torch.Tensor, state: DeepEPDispatchState) -> torch.Tensor:
routed_output = unpermute_from_grouped_gemm(routed_output, state.grouped_gemm_permutation)
if state.scores_after_experts is not None:
routed_output = (routed_output.float() * state.scores_after_experts.float().reshape(-1, 1)).to(
routed_output.dtype
)
routed_output = _unpermute_tokens(
routed_output,
state.deep_ep_permuted_indices,
state.num_received_tokens,
)
combined = _DeepEPCombine.apply(routed_output, state.handle_id, self._pending_combine_events)
return combined
def _run_dispatched_chunk(
self,
pending_state: _PendingDispatchState,
experts: ExpertFunction,
) -> torch.Tensor:
hidden_states, num_tokens_per_expert, dispatch_state = self._finalize_dispatch(pending_state)
routed_output = experts(hidden_states, num_tokens_per_expert)
return self.combine(routed_output, dispatch_state)
@torch.compiler.disable()
def _synchronize_combines(self) -> None:
for event in self._pending_combine_events:
event.current_stream_wait()
self._pending_combine_events.clear()
def run(
self,
x: torch.Tensor,
top_scores: torch.Tensor,
selected_experts_indices: torch.Tensor,
experts: ExpertFunction,
*,
score_before_experts: bool,
) -> torch.Tensor:
if self.token_chunk_size is None:
chunk_ranges = [(0, x.shape[0])]
else:
chunk_ranges = [
(start, min(start + self.token_chunk_size, x.shape[0]))
for start in range(0, x.shape[0], self.token_chunk_size)
]
pending_states = (
dispatch_tokens_async(
x[start:end],
selected_experts_indices[start:end],
top_scores[start:end],
num_experts=self.num_experts,
group=self.group,
score_before_experts=score_before_experts,
)
for start, end in chunk_ranges
)
pending_state = next(pending_states)
routed_outputs: list[torch.Tensor] = []
for next_pending_state in pending_states:
routed_outputs.append(self._run_dispatched_chunk(pending_state, experts))
pending_state = next_pending_state
routed_outputs.append(self._run_dispatched_chunk(pending_state, experts))
if len(routed_outputs) == 1:
return routed_outputs[0]
if self._concatenate_stream is None:
self._concatenate_stream = torch.cuda.Stream()
with torch.cuda.stream(self._concatenate_stream):
self._synchronize_combines()
output = torch.cat(routed_outputs, dim=0)
self._output_event = self._concatenate_stream.record_event()
return output
def synchronize(self) -> None:
if self._output_event is not None:
torch.cuda.current_stream().wait_event(self._output_event)
self._output_event = None
return
self._synchronize_combines()
register_deepep_cuda_ops()
__all__ = [
"combine_tokens",
"configure_num_sms",
"DeepEPTokenDispatcher",
"dispatch_tokens_async",
"finalize_dispatch_tokens",
"sync_combine",
]
@@ -1,87 +1,14 @@
import torch
import torch.distributed as dist
import torch.nn as nn
from torch.distributed import ProcessGroup
from torch.distributed.distributed_c10d import _resolve_process_group
from torch.distributed.tensor import DeviceMesh, Shard, distribute_module, distribute_tensor
from torch.distributed.tensor.parallel import ParallelStyle
from torchao.prototype.moe_training.ep import a2a_combine_hp_fwd_mxfp8_bwd, a2a_dispatch_mxfp8_fwd_hp_bwd
from torchao.prototype.mx_formats.mx_tensor import MXTensor
from torchtitan.distributed.expert_parallel import ExpertParallel
class _MXFP8Dispatch(torch.autograd.Function):
class ExpertWeightParallel(ParallelStyle):
@staticmethod
def forward(ctx, routed_input, output_splits, input_splits, group_name):
mx_routed_input = a2a_dispatch_mxfp8_fwd_hp_bwd(routed_input, output_splits, input_splits, group_name)
ctx.input_splits = input_splits
ctx.output_splits = output_splits
ctx.group = _resolve_process_group(group_name)
return mx_routed_input.dequantize(routed_input.dtype)
@staticmethod
def backward(ctx, grad_output):
grad_input = grad_output.new_empty((sum(ctx.input_splits),) + tuple(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
class _DequantMXGradInBwd(torch.autograd.Function):
@staticmethod
def forward(ctx, x, hp_dtype):
ctx.hp_dtype = hp_dtype
return x
@staticmethod
def backward(ctx, grad_output):
if isinstance(grad_output, MXTensor):
grad_output = grad_output.dequantize(ctx.hp_dtype)
return grad_output, None
class MXFP8AllToAllExpertParallel(ExpertParallel):
def _token_dispatch(self, mod, inputs, device_mesh):
routed_input, num_tokens_per_expert = inputs
with torch.no_grad():
num_tokens_per_expert_group = num_tokens_per_expert.new_empty(num_tokens_per_expert.shape[0])
dist.all_to_all_single(num_tokens_per_expert_group, num_tokens_per_expert, group=device_mesh.get_group())
self.input_splits = num_tokens_per_expert.view(device_mesh.shape[0], -1).sum(dim=1).tolist()
self.output_splits = num_tokens_per_expert_group.view(device_mesh.shape[0], -1).sum(dim=1).tolist()
routed_input = _MXFP8Dispatch.apply(
routed_input, self.output_splits, self.input_splits, device_mesh.get_group().group_name
)
return routed_input, num_tokens_per_expert_group
def _token_combine(self, mod, routed_output, device_mesh):
routed_output = _DequantMXGradInBwd.apply(routed_output, routed_output.dtype)
return a2a_combine_hp_fwd_mxfp8_bwd(
routed_output,
self.input_splits,
self.output_splits,
device_mesh.get_group().group_name,
)
class DeepEPExpertParallel(ParallelStyle):
"""Expert-parallel style backed by DeepEP dispatch/combine.
Only handles weight sharding (Shard(0) on expert dim) and stores the EP
process group on the module. PrimeRL drives DeepEP dispatch/combine from
`MoE.forward()` so communication stays outside the selective-AC checkpoint
boundary while local expert matmuls remain checkpointable.
"""
@staticmethod
def _partition_fn(name: str, mod: nn.Module, device_mesh: DeviceMesh) -> None:
for param_name, param in mod.named_parameters(recurse=False):
mod.register_parameter(param_name, nn.Parameter(distribute_tensor(param, device_mesh, [Shard(0)])))
mod._ep_group = device_mesh.get_group()
def _partition_fn(_name: str, module: nn.Module, device_mesh: DeviceMesh) -> None:
for parameter_name, parameter in module.named_parameters(recurse=False):
sharded = distribute_tensor(parameter, device_mesh, [Shard(0)])
module.register_parameter(parameter_name, nn.Parameter(sharded))
def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
return distribute_module(module, device_mesh, partition_fn=self._partition_fn)
def get_ep_group(experts: nn.Module) -> ProcessGroup:
return experts._ep_group
@@ -0,0 +1,364 @@
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
class ExpertFunction(Protocol):
def __call__(self, x: torch.Tensor, num_tokens_per_expert: torch.Tensor) -> torch.Tensor: ...
class TokenDispatcher(Protocol):
def run(
self,
x: torch.Tensor,
top_scores: torch.Tensor,
selected_experts_indices: torch.Tensor,
experts: ExpertFunction,
*,
score_before_experts: bool,
) -> torch.Tensor: ...
def synchronize(self) -> None: ...
DispatchState = TypeVar("DispatchState")
class TokenDispatcherBase(ABC, Generic[DispatchState]):
def __init__(self, num_experts: int, token_group_alignment: int) -> None:
self.num_experts = num_experts
self.token_group_alignment = token_group_alignment
@abstractmethod
def dispatch(
self,
x: torch.Tensor,
top_scores: torch.Tensor,
selected_experts_indices: torch.Tensor,
*,
score_before_experts: bool,
) -> tuple[torch.Tensor, torch.Tensor, DispatchState]: ...
@abstractmethod
def combine(self, routed_output: torch.Tensor, state: DispatchState) -> torch.Tensor: ...
def run(
self,
x: torch.Tensor,
top_scores: torch.Tensor,
selected_experts_indices: torch.Tensor,
experts: ExpertFunction,
*,
score_before_experts: bool,
) -> torch.Tensor:
routed_input, num_tokens_per_expert, state = self.dispatch(
x,
top_scores,
selected_experts_indices,
score_before_experts=score_before_experts,
)
routed_output = experts(routed_input, num_tokens_per_expert)
return self.combine(routed_output, state)
def synchronize(self) -> None:
return None
@dataclass(frozen=True)
class PermutationState:
input_shape: torch.Size
permuted_indices: torch.Tensor
@dataclass(frozen=True)
class LocalDispatchState:
num_tokens: int
token_indices_experts_sorted: torch.Tensor
scores_after_experts: torch.Tensor | None
permutation: PermutationState
@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)
def permute_for_grouped_gemm(
x: torch.Tensor,
num_tokens_per_expert_group: torch.Tensor,
*,
experts_per_rank: int,
num_ranks: int,
alignment: int,
) -> tuple[torch.Tensor, torch.Tensor, PermutationState]:
from torchtitan.experiments.kernels.moe.indices import generate_permute_indices
max_len = x.shape[0] + experts_per_rank * alignment
max_len = (max_len + alignment - 1) // alignment * alignment
with torch.no_grad():
permuted_indices, num_tokens_per_expert, _ = generate_permute_indices(
num_tokens_per_expert_group,
experts_per_rank,
num_ranks,
max_len,
alignment,
use_cpu=x.device.type == "cpu",
)
x = torch.vstack((x, x.new_zeros((1, x.shape[-1]))))
state = PermutationState(input_shape=x.shape, permuted_indices=permuted_indices)
return x[permuted_indices], num_tokens_per_expert, state
def unpermute_from_grouped_gemm(x: torch.Tensor, state: PermutationState) -> torch.Tensor:
output = x.new_empty(state.input_shape)
output[state.permuted_indices] = x
return output[:-1]
def _local_reorder(
x: torch.Tensor,
top_scores: torch.Tensor,
selected_experts_indices: torch.Tensor,
*,
num_experts: int,
top_k: int,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
flattened_experts = selected_experts_indices.reshape(-1)
num_tokens_per_expert = torch.histc(
flattened_experts.float(),
bins=num_experts,
min=0,
max=num_experts,
).to(torch.int64)
token_indices_experts_sorted = torch.argsort(flattened_experts, stable=True)
top_scores_experts_sorted = top_scores.reshape(-1)[token_indices_experts_sorted]
token_indices_experts_sorted = token_indices_experts_sorted // top_k
routed_input = x[token_indices_experts_sorted]
return routed_input, token_indices_experts_sorted, top_scores_experts_sorted, num_tokens_per_expert
def _scatter_routed_output(
routed_output: torch.Tensor,
*,
num_tokens: int,
token_indices_experts_sorted: torch.Tensor,
scores_after_experts: torch.Tensor | None,
) -> torch.Tensor:
if scores_after_experts is not None:
routed_output = (routed_output.float() * scores_after_experts.reshape(-1, 1)).to(routed_output.dtype)
dim = routed_output.shape[-1]
output = routed_output.new_zeros((num_tokens, dim))
routed_indices = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
return output.scatter_add(0, routed_indices, routed_output)
class LocalTokenDispatcher(TokenDispatcherBase[LocalDispatchState]):
def __init__(self, num_experts: int, top_k: int, token_group_alignment: int) -> None:
super().__init__(num_experts, token_group_alignment)
self.top_k = top_k
def dispatch(
self,
x: torch.Tensor,
top_scores: torch.Tensor,
selected_experts_indices: torch.Tensor,
*,
score_before_experts: bool,
) -> tuple[torch.Tensor, torch.Tensor, LocalDispatchState]:
routed_input, token_indices, sorted_scores, num_tokens_per_expert = _local_reorder(
x,
top_scores,
selected_experts_indices,
num_experts=self.num_experts,
top_k=self.top_k,
)
scores_after_experts = None
if score_before_experts:
routed_input = (routed_input.float() * sorted_scores.reshape(-1, 1)).to(x.dtype)
else:
scores_after_experts = sorted_scores
routed_input, num_tokens_per_expert, permutation = permute_for_grouped_gemm(
routed_input,
num_tokens_per_expert,
experts_per_rank=self.num_experts,
num_ranks=1,
alignment=self.token_group_alignment,
)
state = LocalDispatchState(
num_tokens=x.shape[0],
token_indices_experts_sorted=token_indices,
scores_after_experts=scores_after_experts,
permutation=permutation,
)
return routed_input, num_tokens_per_expert, state
def combine(self, routed_output: torch.Tensor, state: LocalDispatchState) -> torch.Tensor:
routed_output = unpermute_from_grouped_gemm(routed_output, state.permutation)
return _scatter_routed_output(
routed_output,
num_tokens=state.num_tokens,
token_indices_experts_sorted=state.token_indices_experts_sorted,
scores_after_experts=state.scores_after_experts,
)
class TorchTokenDispatcher(TokenDispatcherBase[TorchDispatchState]):
def __init__(
self,
num_experts: int,
top_k: int,
token_group_alignment: int,
group: ProcessGroup,
) -> None:
super().__init__(num_experts, token_group_alignment)
self.top_k = top_k
self.group = group
def _dispatch_tokens(
self,
x: torch.Tensor,
output_splits: list[int],
input_splits: list[int],
) -> torch.Tensor:
return _all_to_all(x, output_splits, input_splits, self.group)
def _combine_tokens(
self,
x: torch.Tensor,
output_splits: list[int],
input_splits: list[int],
) -> torch.Tensor:
return _all_to_all(x, output_splits, input_splits, self.group)
def dispatch(
self,
x: torch.Tensor,
top_scores: torch.Tensor,
selected_experts_indices: torch.Tensor,
*,
score_before_experts: bool,
) -> tuple[torch.Tensor, torch.Tensor, TorchDispatchState]:
routed_input, token_indices, sorted_scores, num_tokens_per_expert = _local_reorder(
x,
top_scores,
selected_experts_indices,
num_experts=self.num_experts,
top_k=self.top_k,
)
scores_after_experts = None
if score_before_experts:
routed_input = (routed_input.float() * sorted_scores.reshape(-1, 1)).to(x.dtype)
else:
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()
routed_input = self._dispatch_tokens(routed_input, output_splits, input_splits)
experts_per_rank = self.num_experts // ep_degree
routed_input, num_tokens_per_expert, permutation = permute_for_grouped_gemm(
routed_input,
num_tokens_per_expert_group,
experts_per_rank=experts_per_rank,
num_ranks=ep_degree,
alignment=self.token_group_alignment,
)
state = TorchDispatchState(
num_tokens=x.shape[0],
token_indices_experts_sorted=token_indices,
scores_after_experts=scores_after_experts,
permutation=permutation,
input_splits=input_splits,
output_splits=output_splits,
)
return routed_input, num_tokens_per_expert, state
def combine(self, routed_output: torch.Tensor, state: TorchDispatchState) -> torch.Tensor:
routed_output = unpermute_from_grouped_gemm(routed_output, state.permutation)
routed_output = self._combine_tokens(routed_output, state.input_splits, state.output_splits)
return _scatter_routed_output(
routed_output,
num_tokens=state.num_tokens,
token_indices_experts_sorted=state.token_indices_experts_sorted,
scores_after_experts=state.scores_after_experts,
)
class MXFP8TorchTokenDispatcher(TorchTokenDispatcher):
def __init__(
self,
num_experts: int,
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],
) -> torch.Tensor:
return self.kernel.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],
) -> torch.Tensor:
return self.kernel.all_to_all_combine(x, output_splits, input_splits, self.group)
+14 -23
View File
@@ -18,7 +18,7 @@ from prime_rl.trainer.models.layers.lora.multi_moe import (
MultiLoRAGroupedExperts,
MultiLoRANonGatedGroupedExperts,
)
from prime_rl.trainer.models.layers.moe import GptOssGroupedExperts, GroupedExperts, NonGatedGroupedExperts
from prime_rl.trainer.models.layers.moe import GroupedExperts
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
@@ -156,8 +156,8 @@ def _find_target_modules(model: nn.Module, target_patterns: List[str]) -> List[s
target_modules = []
for name, module in model.named_modules():
# Check if module is Linear or one of the supported expert classes
if not isinstance(module, (nn.Linear, GroupedExperts, NonGatedGroupedExperts, GptOssGroupedExperts)):
# Check if module is Linear or a supported expert class
if not isinstance(module, (nn.Linear, GroupedExperts)):
continue
for pattern in target_patterns:
@@ -224,6 +224,9 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
lora_state = setup_lora_state(config, torch.device("cuda", get_world().local_rank))
if isinstance(model, PreTrainedModelPrimeRL):
lora_state.register_adapter_state_dict_converter(type(model).convert_adapter_to_hf)
uses_gpt_oss_moe_adapter = (
isinstance(model, PreTrainedModelPrimeRL) and getattr(model.config, "model_type", None) == "gpt_oss"
)
from torch.distributed.fsdp import FSDPModule
@@ -256,25 +259,13 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
)
# Handle GroupedExperts (MoE)
elif isinstance(base_module, GroupedExperts):
lora_module = MultiLoRAGroupedExperts(
base_layer=base_module,
rank=config.rank,
n_adapters=1,
alpha=config.alpha,
dropout=config.dropout,
)
# Handle NonGatedGroupedExperts (relu2 experts used by NemotronH's LatentMoE)
elif isinstance(base_module, NonGatedGroupedExperts):
lora_module = MultiLoRANonGatedGroupedExperts(
base_layer=base_module,
rank=config.rank,
n_adapters=1,
alpha=config.alpha,
dropout=config.dropout,
)
# Handle GptOssGroupedExperts (gpt-oss fused gate_up + biases)
elif isinstance(base_module, GptOssGroupedExperts):
lora_module = MultiLoRAGptOssGroupedExperts(
if uses_gpt_oss_moe_adapter:
wrapper = MultiLoRAGptOssGroupedExperts
elif base_module.gate_proj is not None:
wrapper = MultiLoRAGroupedExperts
else:
wrapper = MultiLoRANonGatedGroupedExperts
lora_module = wrapper(
base_layer=base_module,
rank=config.rank,
n_adapters=1,
@@ -284,7 +275,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
else:
logger.warning(
f"Module {module_name} is type {type(base_module).__name__}, "
f"expected nn.Linear, GroupedExperts, NonGatedGroupedExperts, or GptOssGroupedExperts. Skipping."
"expected nn.Linear or GroupedExperts. Skipping."
)
continue
+30 -112
View File
@@ -20,8 +20,6 @@ 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
from torch.distributed.fsdp import CPUOffloadPolicy, FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
from torch.distributed.tensor.parallel import parallelize_module
from torchtitan.distributed.expert_parallel import ExpertParallel
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, GenerationConfig, PretrainedConfig
from transformers.tokenization_utils import PreTrainedTokenizer
from transformers.utils.import_utils import is_flash_attn_3_available
@@ -32,10 +30,8 @@ from prime_rl.configs.trainer import (
FP8Config,
ModelConfig,
MXFP8Config,
QuantizationConfig,
TokenizerConfig,
)
from prime_rl.trainer.distributed import DeepEPExpertParallel, MXFP8AllToAllExpertParallel
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,
@@ -53,9 +49,9 @@ from prime_rl.trainer.models.layers.checkpointing import (
)
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 LatentMoE, MoE, TokenChoiceTopKRouter, _load_fused_moe_kernel
from prime_rl.trainer.models.layers.mxfp8_grouped_gemm import apply_mxfp8_moe_grouped_gemm
from prime_rl.trainer.models.layers.moe import MoE, TokenChoiceTopKRouter
from prime_rl.trainer.models.layers.mxfp8_linear import replace_linear_with_mxfp8_linear
from prime_rl.trainer.moe_runtime import configure_moe_runtime
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
@@ -403,8 +399,8 @@ def freeze_moe_router(model: nn.Module) -> None:
if mlp is None:
continue
# Custom implementation: MoE/LatentMoE class with router attribute
if isinstance(mlp, (MoE, LatentMoE)):
# Custom implementation
if isinstance(mlp, MoE):
for param in mlp.router.parameters():
param.requires_grad = False
num_frozen += 1
@@ -431,7 +427,7 @@ def apply_fp32_moe_router(model: nn.Module) -> None:
for layer in language_model.layers:
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
if isinstance(mlp, (MoE, LatentMoE)):
if isinstance(mlp, MoE):
mlp.router.to(torch.float32)
if isinstance(mlp.router, TokenChoiceTopKRouter):
mlp.router.fp32_gate = True
@@ -443,39 +439,6 @@ def apply_fp32_moe_router(model: nn.Module) -> None:
logger.info(f"Running {num_routers} MoE router gates in fp32")
def apply_fused_moe_kernel(model: nn.Module, quantization: QuantizationConfig | None) -> None:
"""
Route MoE routed-expert compute through the our fused bf16/mxfp8 MoE CUDA kernel.
Forward runs the kernel, backward recomputes the reference grouped-mm path.
"""
logger = get_logger()
language_model = get_language_model(model)
num_moe_layers = 0
# MXFP8 with grouped GEMM is the one setting that quantizes the experts themselves, so this also picks the MXFP8 kernel."""
dtype = "mxfp8" if isinstance(quantization, MXFP8Config) and quantization.enable_grouped_gemm else "bf16"
kernel = _load_fused_moe_kernel()
for layer in language_model.layers:
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
if isinstance(mlp, MoE):
if mlp.score_before_experts:
raise ValueError(
"model.moe_fused_kernel=true requires MoE layers with score_before_experts=false, because the fused kernel applies the routing scores to the expert outputs."
)
_, hidden_dim, dim = mlp.experts.w1.shape
reason = kernel.unsupported_shape_reason(dim, hidden_dim, mxfp8=dtype == "mxfp8")
if reason is not None:
raise ValueError(f"model.moe_fused_kernel=true does not support this model: {reason}")
mlp.fused_kernel = dtype
num_moe_layers += 1
if num_moe_layers == 0:
raise ValueError("model.moe_fused_kernel=true but no MoE layers found. Is this a custom-impl MoE model?")
logger.info(f"Using the fused {dtype} MoE kernel for {num_moe_layers} MoE layers")
def get_full_offload_dtype_policy(
model: nn.Module,
config: ModelConfig,
@@ -489,7 +452,7 @@ def get_full_offload_dtype_policy(
language_model = get_language_model(model)
for layer in language_model.layers:
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
if isinstance(mlp, (MoE, LatentMoE)):
if isinstance(mlp, MoE):
for param in mlp.router.parameters():
if param.is_floating_point():
policy[id(param)] = (torch.float32, torch.float32)
@@ -527,7 +490,7 @@ def apply_force_balanced_routing(model: nn.Module) -> None:
for layer in language_model.layers:
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
if isinstance(mlp, (MoE, LatentMoE)):
if isinstance(mlp, MoE):
mlp.router.force_balanced = True
num_routers += 1
@@ -544,20 +507,6 @@ def is_tt_moe_model(model: nn.Module) -> bool:
return hasattr(model.config, "num_experts") or hasattr(model.config, "n_routed_experts")
def configure_moe_ep_backend(model: nn.Module, config: ModelConfig) -> None:
backend = config.ep_comm_backend
if backend == "deepep":
from prime_rl.trainer.distributed.deepep import configure_num_sms
configure_num_sms(config.deepep_num_sms)
language_model = get_language_model(model)
for transformer_block in language_model.layers:
if not isinstance(transformer_block.mlp, (MoE, LatentMoE)):
continue
transformer_block.mlp.set_ep_comm_backend(backend)
transformer_block.mlp.set_deepep_token_chunk_size(config.deepep_token_chunk_size)
def get_load_balance_stats(
model: nn.Module, reset_stats: bool = True, try_to_avoid_padding_experts: bool = True
) -> dict[str, Tensor | None]:
@@ -647,13 +596,6 @@ def get_model(
subconfig = getattr(model_config, subconfig_key, None)
if subconfig is not None and hasattr(subconfig, "use_cache"):
subconfig.use_cache = False
model_config.use_grouped_mm = config.moe_use_grouped_mm
# MoEArgs.fp8 (read via getattr(config, "fp8") in the modeling files) gates the
# DeepGEMM FP8 grouped GEMM. MXFP8 grouped GEMM is applied by wrapping the expert
# weights with torchao (see apply_quantization), so it leaves this flag False and
# the experts keep calling torch._grouped_mm — which the wrapper tensor intercepts.
model_config.fp8 = isinstance(config.quantization, FP8Config) and config.quantization.enable_grouped_gemm
if config.index_cache is not None:
model_config.use_index_cache = True
model_config.index_topk_freq = config.index_cache.topk_freq
@@ -855,12 +797,12 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
for transformer_block in transformer_layers:
block_mlp = getattr(transformer_block, "mlp", None)
if parallel_dims.ep_enabled and block_mlp is not None and isinstance(block_mlp, (MoE, LatentMoE)):
if parallel_dims.ep_enabled and block_mlp is not None and isinstance(block_mlp, MoE):
fully_shard(block_mlp.experts, mesh=dp_mod_ep_mesh, **fsdp_config)
block_mlp.experts.set_gradient_divide_factor(parallel_dims.fsdp_gradient_divide_factor)
if config.moe_router_dtype == "float32" and isinstance(block_mlp, (MoE, LatentMoE)):
if config.moe_router_dtype == "float32" and isinstance(block_mlp, MoE):
# Own FSDP unit with an fp32 policy so the gate weight is not cast to
# bf16 for forward and its gradients reduce in fp32.
fully_shard(
@@ -923,7 +865,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
for transformer_block, next_transformer_block in zip(transformer_blocks, next_transformer_blocks):
if next_transformer_block is not None:
next_mlp = getattr(next_transformer_block, "mlp", None)
if next_mlp is not None and isinstance(next_mlp, (MoE, LatentMoE)):
if next_mlp is not None and isinstance(next_mlp, MoE):
prefetch_modules = [next_transformer_block]
if isinstance(next_mlp.router, FSDPModule):
prefetch_modules.append(next_mlp.router)
@@ -948,7 +890,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
for transformer_block, prev_transformer_block in zip(reversed_transformer_blocks, prev_transformer_blocks):
if prev_transformer_block is not None:
prev_mlp = getattr(prev_transformer_block, "mlp", None)
if prev_mlp is not None and isinstance(prev_mlp, (MoE, LatentMoE)):
if prev_mlp is not None and isinstance(prev_mlp, MoE):
prefetch_modules = [prev_transformer_block, prev_mlp.experts]
if isinstance(prev_mlp.router, FSDPModule):
prefetch_modules.append(prev_mlp.router)
@@ -994,6 +936,9 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
snapshot_keys = dict.fromkeys(load_state_dict_keys(source_path))
model_keys = dict.fromkeys(model.state_dict().keys())
if source_path.name == "prime" and not (source_path / ".prime-v1").is_file():
raise RuntimeError(f"PrimeRL conversion cache {source_path} is missing the required .prime-v1 marker")
snapshot_is_hf = model.is_hf_state_dict(snapshot_keys)
snapshot_is_prime = model.is_prime_state_dict(snapshot_keys)
@@ -1009,6 +954,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
snapshot_state_dict = load_state_dict(source_path)
model.convert_to_prime(snapshot_state_dict)
save_state_dict(snapshot_state_dict, snapshot_path)
(snapshot_path / ".prime-v1").touch()
del snapshot_state_dict
elif snapshot_is_prime and not snapshot_is_hf and model.is_hf_state_dict(model_keys):
@@ -1027,6 +973,12 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
# All ranks wait for master rank to finish conversion
torch.distributed.barrier()
if (
isinstance(model, PreTrainedModelPrimeRL)
and snapshot_path.name == "prime"
and not (snapshot_path / ".prime-v1").is_file()
):
raise RuntimeError(f"PrimeRL conversion cache {snapshot_path} is missing the required .prime-v1 marker")
logger.info(f"Loading weights using HF DCP from {snapshot_path}")
load_dcp_start_time = time.perf_counter()
@@ -1079,7 +1031,9 @@ def can_reinit_empty_buffers(model: nn.Module):
if not (name.startswith("model.layers.") and name.endswith("mlp.tokens_per_expert"))
]
buffer_names = [
name for name in buffer_names if not (name.startswith("model.layers.") and name.endswith("mlp.expert_bias"))
name
for name in buffer_names
if not (name.startswith("model.layers.") and name.endswith("mlp.router.selection_bias"))
]
# HF standard transformer model
if len(buffer_names) == 1 and buffer_names[0] == "model.rotary_emb.inv_freq":
@@ -1195,13 +1149,9 @@ def apply_compile(model: nn.Module, compile_config: CompileConfig):
def apply_quantization(model: nn.Module, config: ModelConfig) -> None:
"""Swap dense linears and MoE expert GEMMs to the configured low-precision path.
"""Swap dense linear modules to the configured low-precision path.
Runs after the LM head is injected but before LoRA / EP / FSDP so the swapped
modules and wrapped parameters are picked up by the later parallelisms. The
FP8 grouped GEMM (DeepGEMM) is gated separately via ``model_config.fp8`` since
it lives inside the modeling code; here we only handle the dense-linear swap
and the torchao MXFP8 expert-weight wrapping.
Routed-expert compute is configured independently by ``model.moe.compute``.
"""
quant = config.quantization
if quant is None:
@@ -1211,33 +1161,11 @@ def apply_quantization(model: nn.Module, config: ModelConfig) -> None:
replace_linear_with_fp8_blockwise_linear(model, ignore_modules=quant.ignore_patterns)
elif isinstance(quant, MXFP8Config):
capability = torch.cuda.get_device_capability()
if capability < (10, 0):
if capability != (10, 0):
raise ValueError(
f"MXFP8 quantization requires SM100 (Blackwell) or newer, but device is SM{capability[0]}{capability[1]}."
f"MXFP8 quantization requires SM100 (Blackwell), but device is SM{capability[0]}{capability[1]}."
)
replace_linear_with_mxfp8_linear(model, recipe=quant.recipe, ignore_modules=quant.ignore_patterns)
if quant.enable_grouped_gemm:
apply_mxfp8_moe_grouped_gemm(model, recipe=quant.recipe)
def apply_ep(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims):
language_model = get_language_model(model)
for transformer_block in language_model.layers:
block_mlp = getattr(transformer_block, "mlp", None)
if block_mlp is not None and isinstance(block_mlp, (MoE, LatentMoE)):
if config.ep_comm_backend == "torch":
quant = config.quantization
if isinstance(quant, MXFP8Config) and quant.enable_a2a:
parallelize_plan = MXFP8AllToAllExpertParallel()
else:
parallelize_plan = ExpertParallel()
else:
parallelize_plan = DeepEPExpertParallel()
parallelize_module(
block_mlp.experts,
device_mesh=parallel_dims.get_mesh("ep"),
parallelize_plan=parallelize_plan,
)
def configure_trainable_parameters(model: nn.Module, config: ModelConfig) -> nn.Module | None:
@@ -1266,7 +1194,7 @@ def _move_buffers_to_cuda(model: nn.Module, config: ModelConfig) -> None:
def _reset_runtime_moe_buffers(model: nn.Module) -> None:
for module in model.modules():
if isinstance(module, (MoE, LatentMoE)) and module.tokens_per_expert.device.type != "meta":
if isinstance(module, MoE) and module.tokens_per_expert.device.type != "meta":
module.tokens_per_expert.zero_()
@@ -1330,7 +1258,6 @@ def setup_model(
# 1. We load to meta device by default
model = get_model(config, device=torch.device("meta"), dtype=DTYPE_MAP[config.optimization_dtype])
configure_moe_ep_backend(model, config)
possible_to_load_to_meta = can_reinit_empty_buffers(model)
@@ -1343,7 +1270,6 @@ def setup_model(
if not possible_to_load_to_meta:
logger.warning("Cannot load model to meta device only, loading to CPU instead.")
model = get_model(config, device=torch.device("cpu"), dtype=DTYPE_MAP[config.optimization_dtype])
configure_moe_ep_backend(model, config)
lm_head_chunk_size: int | None = None
if isinstance(config.fused_lm_head_token_chunk_size, int):
@@ -1361,14 +1287,6 @@ def setup_model(
if config.moe_router_dtype == "float32":
apply_fp32_moe_router(model)
if config.moe_fused_kernel:
if parallel_dims.ep_enabled:
raise ValueError(
"model.moe_fused_kernel=true requires ep=1: the fused kernel bypasses the EP "
"all-to-all and indexes experts with global ids."
)
apply_fused_moe_kernel(model, config.quantization)
# The DSA sparse-attention indexer runs its forward under torch.no_grad(), so it is
# never trainable. Freeze it so optimizer state stays symmetric across checkpoint
# save/resume. No-op for models without a sparse indexer.
@@ -1377,8 +1295,8 @@ def setup_model(
if config.debug.force_balanced_routing:
apply_force_balanced_routing(model)
configure_moe_runtime(model, config, parallel_dims)
if parallel_dims.ep_enabled:
apply_ep(model, config, parallel_dims)
# EP replaces params with DTensors that default to requires_grad=True,
# re-freeze base params that LoRA froze earlier.
if config.lora is not None:
@@ -37,21 +37,16 @@ class AfmoeConfig(PretrainedConfig):
num_experts=64,
num_experts_per_tok=6,
num_shared_experts=2,
num_expert_groups=1,
num_limited_groups=1,
score_func="sigmoid",
route_norm=True,
route_scale=1.0,
score_before_experts: bool = False,
load_balance_coeff: float = 5e-4,
use_grouped_mm: bool = True,
global_attn_every_n_layers=4,
sliding_window=1024,
mup_enabled=False,
layer_types=None,
attention_dropout: float = 0.0,
n_group: int = 1,
topk_group: int = 1,
**kwargs,
):
self.vocab_size = vocab_size
@@ -71,18 +66,13 @@ class AfmoeConfig(PretrainedConfig):
# MoE specific
self.moe_intermediate_size = moe_intermediate_size
self.num_experts_per_tok = num_experts_per_tok
self.n_group = n_group
self.topk_group = topk_group
self.num_experts = num_experts
self.num_shared_experts = num_shared_experts
self.num_expert_groups = num_expert_groups
self.num_limited_groups = num_limited_groups
self.score_func = score_func
self.route_norm = route_norm
self.route_scale = route_scale
self.score_before_experts = score_before_experts
self.load_balance_coeff = load_balance_coeff
self.use_grouped_mm = use_grouped_mm
# Attention specific
self.attention_dropout = attention_dropout
self.global_attn_every_n_layers = global_attn_every_n_layers
@@ -3,11 +3,12 @@
AFMoE specifics:
* Per-layer MLP prefix is ``model.layers.{i}.mlp``.
* The router shares its name between HF and prime, so it is *not* renamed.
* Shared experts: HF ``shared_experts.{gate,down,up}_proj.weight`` map to prime
``shared_expert.{w1,w2,w3}`` (no ``.weight`` suffix on the prime side).
* The router gate shares its name between HF and prime, while HF
``mlp.expert_bias`` maps to PrimeRL ``mlp.router.selection_bias``.
* Shared experts: HF ``shared_experts.{gate,down,up}_proj.weight`` map to PrimeRL
``shared_expert.{gate,down,up}_proj.weight``.
* Routed experts: HF per-expert ``experts.{e}.{gate,down,up}_proj.weight`` stack
into prime ``experts.{w1,w2,w3}`` along dim 0 (no fused gate_up layout).
into PrimeRL ``experts.{gate,down,up}_proj`` along dim 0.
* Prime-only runtime buffers ``mlp.tokens_per_expert`` and ``mlp.reorderer.*``
are dropped on the way back to HF.
"""
@@ -21,8 +22,9 @@ def conversion_chain(config) -> list[ConvOp]:
ops: list[ConvOp] = []
for i in range(config.num_hidden_layers):
p = f"model.layers.{i}.mlp"
ops.append(Rename(f"{p}.expert_bias", f"{p}.router.selection_bias"))
for wn, hf_proj in GATE_DOWN_UP:
ops.append(Rename(f"{p}.shared_experts.{hf_proj}.weight", f"{p}.shared_expert.{wn}"))
ops.append(Rename(f"{p}.shared_experts.{hf_proj}.weight", f"{p}.shared_expert.{wn}.weight"))
for wn, hf_proj in GATE_DOWN_UP:
ops.append(Stack(stacked=f"{p}.experts.{wn}", item=f"{p}.experts.{{e}}.{hf_proj}.weight"))
ops.append(Drop(f"{p}.tokens_per_expert"))
@@ -20,7 +20,7 @@ from prime_rl.trainer.models.layers.attn import (
flash_attn_varlen_func,
)
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
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 (
@@ -242,28 +242,38 @@ class AfmoeDecoderLayer(GradientCheckpointingLayer):
self.post_mlp_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.moe_enabled = layer_idx >= config.num_dense_layers
mlp_config = MLPConfig(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
gate_act=config.hidden_act,
bias=False,
)
moe_args = MoEArgs(
num_experts=config.num_experts,
num_shared_experts=config.num_shared_experts,
expert_type="gated",
activation=config.hidden_act,
score_func=config.score_func,
route_norm=config.route_norm,
route_scale=config.route_scale,
score_before_experts=getattr(config, "score_before_experts", False),
top_k=config.num_experts_per_tok,
use_grouped_mm=getattr(config, "use_grouped_mm", True),
load_balance_coeff=config.load_balance_coeff,
fp8=getattr(config, "fp8", False),
)
if self.moe_enabled:
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
shared_expert = None
if config.num_shared_experts > 0:
shared_expert = FeedForward(
dim=config.hidden_size,
hidden_dim=config.moe_intermediate_size * config.num_shared_experts,
expert_type=moe_args.expert_type,
activation=moe_args.activation,
)
self.mlp = MoE.from_args(
moe_args,
dim=config.hidden_size,
hidden_dim=config.moe_intermediate_size,
shared_expert=shared_expert,
)
else:
self.mlp = MLP(mlp_config)
self.mlp = FeedForward(
dim=config.hidden_size,
hidden_dim=config.intermediate_size,
activation=config.hidden_act,
)
def forward(
self,
@@ -325,7 +335,7 @@ class AfmoePreTrainedModel(PreTrainedModelPrimeRL):
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, torch.Tensor]) -> bool:
return any("mlp.experts.w1" in module_name for module_name in state_dict.keys())
return any("mlp.experts.gate_proj" in module_name for module_name in state_dict.keys())
@classmethod
def conversion_chain(cls, config):
+13 -28
View File
@@ -213,24 +213,6 @@ class SplitConcat(ConvOp):
sd[self.combined] = torch.cat(tensors, dim=self.dim)
@dataclass
class Synthetic(ConvOp):
"""A prime-only tensor with no HF counterpart, created on forward and
dropped on backward (e.g. NemotronH's dummy ``experts.w3`` of shape (0,)).
``factory`` builds the tensor from the current state dict (so it can match
device/dtype of a sibling)."""
prime: str
factory: Callable[[StateDict], Tensor]
def hf_to_prime(self, sd: StateDict) -> None:
sd[self.prime] = self.factory(sd)
def prime_to_hf(self, sd: StateDict) -> None:
sd.pop(self.prime, None)
@dataclass
class MapValue(ConvOp):
"""Apply a value transform to one key. ``forward`` runs HF->prime,
@@ -314,11 +296,11 @@ def key_present(name: str) -> Callable[[StateDict], bool]:
# --------------------------------------------------------------------------- #
# Shared composition helper for Llama-style routed experts (prime w1=gate,
# w2=down, w3=up). Used by several models' converting_<model>.py.
# Shared composition helper for Llama-style routed experts (prime gate_proj=gate,
# down_proj=down, up_proj=up). Used by several models' converting_<model>.py.
# --------------------------------------------------------------------------- #
GATE_DOWN_UP = (("w1", "gate_proj"), ("w2", "down_proj"), ("w3", "up_proj"))
GATE_DOWN_UP = (("gate_proj", "gate_proj"), ("down_proj", "down_proj"), ("up_proj", "up_proj"))
def routed_experts_op(
@@ -335,14 +317,14 @@ def routed_experts_op(
Per-expert HF weights <-> stacked prime tensors is a :class:`Stack` per
proj. ``hf_experts``/``prime_experts`` are the (relative) expert container
names (e.g. ``mlp.experts`` / ``block_sparse_moe.experts``); ``proj_order``
maps prime ``wN`` to the HF per-expert proj name.
maps prime projection names to the HF per-expert proj name.
With ``fused`` set, the transformers-v5 fused ``gate_up_proj`` input is also
accepted: a :class:`Conditional` on its presence splits it (dim 1) into
w1/w3 and renames ``down_proj`` -> w2; otherwise the per-expert ``Stack``s
run. Prime always stores split w1/w2/w3, so the backward path always goes
through the per-expert ``Stack`` unstack (the fused key is absent in prime,
so the conditional takes the else branch)."""
gate_proj/up_proj and renames ``down_proj``; otherwise the per-expert
``Stack``s run. Prime always stores split gate/down/up projections, so the
backward path always goes through the per-expert ``Stack`` unstack (the
fused key is absent in prime, so the conditional takes the else branch)."""
stacks = [
Stack(
stacked=f"{prefix}.{prime_experts}.{wn}",
@@ -356,9 +338,12 @@ def routed_experts_op(
fused_then = [
SplitConcat(
combined=gate_up,
parts=[(f"{prefix}.{prime_experts}.w1", None), (f"{prefix}.{prime_experts}.w3", None)],
parts=[
(f"{prefix}.{prime_experts}.gate_proj", None),
(f"{prefix}.{prime_experts}.up_proj", None),
],
dim=1,
),
Rename(f"{prefix}.{hf_experts}.down_proj", f"{prefix}.{prime_experts}.w2"),
Rename(f"{prefix}.{hf_experts}.down_proj", f"{prefix}.{prime_experts}.down_proj"),
]
return Conditional(key_present(gate_up), then=fused_then, else_=stacks)
@@ -1,5 +1,3 @@
import warnings
from transformers.configuration_utils import PretrainedConfig
@@ -97,10 +95,6 @@ class Glm4MoeConfig(PretrainedConfig):
Number of routed experts.
routed_scaling_factor (`float`, *optional*, defaults to 1.0):
Scaling factor or routed experts.
n_group (`int`, *optional*, defaults to 1):
Number of groups for routed experts.
topk_group (`int`, *optional*, defaults to 1):
Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
first_k_dense_replace (`int`, *optional*, defaults to 1):
Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
\--k dense layers--/
@@ -128,9 +122,9 @@ class Glm4MoeConfig(PretrainedConfig):
"layers.*.self_attn.k_proj": "colwise",
"layers.*.self_attn.v_proj": "colwise",
"layers.*.self_attn.o_proj": "rowwise",
"layers.*.mlp.experts.*.gate_proj": "colwise",
"layers.*.mlp.experts.*.up_proj": "colwise",
"layers.*.mlp.experts.*.down_proj": "rowwise",
"layers.*.mlp.experts.gate_proj": "colwise",
"layers.*.mlp.experts.up_proj": "colwise",
"layers.*.mlp.experts.down_proj": "rowwise",
"layers.*.mlp.gate_proj": "colwise",
"layers.*.mlp.up_proj": "colwise",
"layers.*.mlp.down_proj": "rowwise",
@@ -165,12 +159,9 @@ class Glm4MoeConfig(PretrainedConfig):
n_shared_experts=1,
n_routed_experts=128,
routed_scaling_factor=1.0,
n_group=1,
topk_group=1,
first_k_dense_replace=1,
norm_topk_prob=True,
use_qk_norm=False,
use_grouped_mm=True,
pad_token_id=None,
**kwargs,
):
@@ -196,18 +187,12 @@ class Glm4MoeConfig(PretrainedConfig):
# MoE arguments
self.moe_intermediate_size = moe_intermediate_size
self.num_experts_per_tok = num_experts_per_tok
self.n_group = n_group
self.topk_group = topk_group
self.n_shared_experts = n_shared_experts
self.n_routed_experts = n_routed_experts
self.routed_scaling_factor = routed_scaling_factor
self.first_k_dense_replace = first_k_dense_replace
self.norm_topk_prob = norm_topk_prob
self.use_qk_norm = use_qk_norm
self.use_grouped_mm = use_grouped_mm
if not self.use_grouped_mm:
warnings.warn("not using grouped mm for moe is very slow, should only be used for debugging")
super().__init__(
tie_word_embeddings=tie_word_embeddings,
@@ -4,15 +4,14 @@ GLM-4 MoE specifics:
* Router: HF ``mlp.gate.weight`` -> prime ``mlp.router.gate.weight``.
* Expert bias: HF ``mlp.gate.e_score_correction_bias`` -> prime
``mlp.expert_bias``.
``mlp.router.selection_bias``.
* Routed experts: HF per-expert ``mlp.experts.{e}.{gate,down,up}_proj.weight``
stack into prime ``mlp.experts.{w1,w2,w3}`` along dim 0; the fused
stack into prime ``mlp.experts.{gate,down,up}_proj`` along dim 0; the fused
transformers-v5 ``mlp.experts.gate_up_proj`` / ``down_proj`` layout is also
accepted on the way in (split along dim 1).
* Shared experts: HF ``mlp.shared_experts.{gate,down,up}_proj.weight`` map to
prime ``mlp.shared_expert.{w1,w2,w3}`` (no ``.weight`` suffix on prime; this
is a plain rename forward). On the way back to HF, GLM strips a leading
singleton dim from each shared-expert tensor when present
prime ``mlp.shared_expert.{gate,down,up}_proj.weight``. On the way back to HF,
GLM strips a leading singleton dim from each shared-expert tensor when present
(:class:`~prime_rl.trainer.models.conversion_ops.SqueezeLeading`,
backward-only).
* Prime-only runtime buffer ``mlp.tokens_per_expert`` is dropped on the way
@@ -42,7 +41,7 @@ def glm_moe_layer_ops(layer_idx: int) -> list[ConvOp]:
p = f"model.layers.{layer_idx}.mlp"
ops: list[ConvOp] = [
Rename(f"{p}.gate.weight", f"{p}.router.gate.weight"),
Rename(f"{p}.gate.e_score_correction_bias", f"{p}.expert_bias"),
Rename(f"{p}.gate.e_score_correction_bias", f"{p}.router.selection_bias"),
routed_experts_op(
f"model.layers.{layer_idx}",
hf_experts="mlp.experts",
@@ -55,7 +54,7 @@ def glm_moe_layer_ops(layer_idx: int) -> list[ConvOp]:
# restored the HF key, so it precedes the Rename in the forward list
# (apply_prime_to_hf plays the chain in reverse).
ops.append(SqueezeLeading(f"{p}.shared_experts.{hf_proj}.weight"))
ops.append(Rename(f"{p}.shared_experts.{hf_proj}.weight", f"{p}.shared_expert.{wn}"))
ops.append(Rename(f"{p}.shared_experts.{hf_proj}.weight", f"{p}.shared_expert.{wn}.weight"))
ops.append(Drop(f"{p}.tokens_per_expert"))
return ops
@@ -30,7 +30,7 @@ from prime_rl.trainer.models.glm4_moe.configuration_glm4_moe import Glm4MoeConfi
from prime_rl.trainer.models.glm4_moe.converting_glm4_moe import conversion_chain
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
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 RotaryEmbedding, RotaryEmbeddingConfig
@@ -55,27 +55,36 @@ class Glm4MoeDecoderLayer(GradientCheckpointingLayer):
moe_args = MoEArgs(
num_experts=config.n_routed_experts,
num_shared_experts=config.n_shared_experts,
expert_type="gated",
activation=config.hidden_act,
score_func="sigmoid",
route_norm=config.norm_topk_prob,
route_scale=config.routed_scaling_factor,
score_before_experts=False,
top_k=config.num_experts_per_tok,
load_balance_coeff=1e-3,
use_grouped_mm=config.use_grouped_mm,
fp8=getattr(config, "fp8", False),
)
mlp_config = MLPConfig(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
gate_act=config.hidden_act,
bias=False,
)
if layer_idx >= config.first_k_dense_replace:
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
shared_expert = None
if config.n_shared_experts > 0:
shared_expert = FeedForward(
dim=config.hidden_size,
hidden_dim=config.moe_intermediate_size * config.n_shared_experts,
expert_type=moe_args.expert_type,
activation=moe_args.activation,
)
self.mlp = MoE.from_args(
moe_args,
dim=config.hidden_size,
hidden_dim=config.moe_intermediate_size,
shared_expert=shared_expert,
)
else:
self.mlp = MLP(mlp_config)
self.mlp = FeedForward(
dim=config.hidden_size,
hidden_dim=config.intermediate_size,
activation=config.hidden_act,
)
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
@@ -126,7 +135,7 @@ class Glm4MoePreTrainedModel(PreTrainedModelPrimeRL):
@classmethod
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
return name.endswith("mlp.expert_bias")
return name.endswith("mlp.router.selection_bias")
def _init_weights(self, module):
super()._init_weights(module)
@@ -140,7 +149,7 @@ class Glm4MoePreTrainedModel(PreTrainedModelPrimeRL):
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
"""Check if the state dict contains MoE layers in PrimeRL training format."""
return any("mlp.experts.w1" in module_name for module_name in state_dict.keys())
return any("mlp.experts.gate_proj" in name for name in state_dict)
@classmethod
def conversion_chain(cls, config):
@@ -1,5 +1,3 @@
import warnings
from transformers.configuration_utils import PretrainedConfig
@@ -56,10 +54,6 @@ class GlmMoeDsaConfig(PretrainedConfig):
Dimension of value heads.
qk_nope_head_dim (`int`, defaults to 192):
Dimension of query/key heads that don't use rotary position embeddings.
n_group (`int`, defaults to 1):
Number of groups for routed experts.
topk_group (`int`, defaults to 1):
Number of selected groups per token.
num_experts_per_tok (`int`, defaults to 8):
Number of active experts per token.
first_k_dense_replace (`int`, defaults to 3):
@@ -101,8 +95,6 @@ class GlmMoeDsaConfig(PretrainedConfig):
field is absent from the config).
topk_method (`str`, defaults to `"noaux_tc"`):
MoE routing top-k method used by GLM-5 checkpoints.
use_grouped_mm (`bool`, defaults to `True`):
Whether to use grouped matrix multiplication for MoE.
"""
model_type = "glm_moe_dsa"
@@ -111,9 +103,9 @@ class GlmMoeDsaConfig(PretrainedConfig):
base_model_tp_plan = {
"layers.*.self_attn.o_proj": "rowwise",
"layers.*.mlp.experts.*.gate_proj": "colwise",
"layers.*.mlp.experts.*.up_proj": "colwise",
"layers.*.mlp.experts.*.down_proj": "rowwise",
"layers.*.mlp.experts.gate_proj": "colwise",
"layers.*.mlp.experts.up_proj": "colwise",
"layers.*.mlp.experts.down_proj": "rowwise",
"layers.*.mlp.gate_proj": "colwise",
"layers.*.mlp.up_proj": "colwise",
"layers.*.mlp.down_proj": "rowwise",
@@ -141,8 +133,6 @@ class GlmMoeDsaConfig(PretrainedConfig):
qk_rope_head_dim=64,
v_head_dim=256,
qk_nope_head_dim=192,
n_group=1,
topk_group=1,
num_experts_per_tok=8,
first_k_dense_replace=3,
norm_topk_prob=True,
@@ -169,7 +159,6 @@ class GlmMoeDsaConfig(PretrainedConfig):
indexer_types=None,
scoring_func="sigmoid",
topk_method="noaux_tc",
use_grouped_mm=True,
**kwargs,
):
self.vocab_size = vocab_size
@@ -194,8 +183,6 @@ class GlmMoeDsaConfig(PretrainedConfig):
self.n_shared_experts = n_shared_experts
self.n_routed_experts = n_routed_experts
self.routed_scaling_factor = routed_scaling_factor
self.n_group = n_group
self.topk_group = topk_group
self.num_experts_per_tok = num_experts_per_tok
self.first_k_dense_replace = first_k_dense_replace
self.norm_topk_prob = norm_topk_prob
@@ -226,12 +213,8 @@ class GlmMoeDsaConfig(PretrainedConfig):
self.indexer_types = indexer_types
self.scoring_func = scoring_func
self.topk_method = topk_method
self.use_grouped_mm = use_grouped_mm
self.pad_token_id = pad_token_id
if not self.use_grouped_mm:
warnings.warn("not using grouped mm for moe is very slow, should only be used for debugging")
# head_dim is derived from qk_rope_head_dim (the RoPE slice). Some checkpoints (e.g. GLM-5.2)
# set head_dim=qk_nope_head_dim in config.json; drop it so PretrainedConfig.__init__ can't
# overwrite self.head_dim and break the rotary embedding dimension.
@@ -90,13 +90,13 @@ def convert_tt_layer_to_vllm_kernel(
router_key = f"{prefix}.mlp.router.gate.weight"
if router_key in state_dict:
add(f"{prefix}.mlp.gate.weight", state_dict[router_key])
expert_bias_key = f"{prefix}.mlp.expert_bias"
if expert_bias_key in state_dict:
add(f"{prefix}.mlp.gate.e_score_correction_bias", state_dict[expert_bias_key])
selection_bias_key = f"{prefix}.mlp.router.selection_bias"
if selection_bias_key in state_dict:
add(f"{prefix}.mlp.gate.e_score_correction_bias", state_dict[selection_bias_key])
w1_key = f"{prefix}.mlp.experts.w1"
w2_key = f"{prefix}.mlp.experts.w2"
w3_key = f"{prefix}.mlp.experts.w3"
w1_key = f"{prefix}.mlp.experts.gate_proj"
w2_key = f"{prefix}.mlp.experts.down_proj"
w3_key = f"{prefix}.mlp.experts.up_proj"
if w1_key in state_dict and w2_key in state_dict and w3_key in state_dict:
w1 = state_dict[w1_key]
w2 = state_dict[w2_key]
@@ -124,9 +124,9 @@ def convert_tt_layer_to_vllm_kernel(
out[f"{prefix}.mlp.experts.w13_weight"] = w13
out[f"{prefix}.mlp.experts.w2_weight"] = w2
sw1_key = f"{prefix}.mlp.shared_expert.w1"
sw2_key = f"{prefix}.mlp.shared_expert.w2"
sw3_key = f"{prefix}.mlp.shared_expert.w3"
sw1_key = f"{prefix}.mlp.shared_expert.gate_proj.weight"
sw2_key = f"{prefix}.mlp.shared_expert.down_proj.weight"
sw3_key = f"{prefix}.mlp.shared_expert.up_proj.weight"
if sw1_key in state_dict and sw2_key in state_dict and sw3_key in state_dict:
sw1 = state_dict[sw1_key]
sw2 = state_dict[sw2_key]
@@ -20,7 +20,7 @@ from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import (
)
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import GlmMoeDsaAttention, SparseMlaAttentionArgs
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
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 RotaryEmbedding, RotaryEmbeddingConfig
@@ -56,27 +56,36 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
moe_args = MoEArgs(
num_experts=config.n_routed_experts,
num_shared_experts=config.n_shared_experts,
expert_type="gated",
activation=config.hidden_act,
score_func="sigmoid",
route_norm=config.norm_topk_prob,
route_scale=config.routed_scaling_factor,
score_before_experts=False,
top_k=config.num_experts_per_tok,
load_balance_coeff=1e-3,
use_grouped_mm=config.use_grouped_mm,
fp8=getattr(config, "fp8", False),
)
mlp_config = MLPConfig(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
gate_act=config.hidden_act,
bias=False,
)
if layer_idx >= config.first_k_dense_replace:
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
shared_expert = None
if config.n_shared_experts > 0:
shared_expert = FeedForward(
dim=config.hidden_size,
hidden_dim=config.moe_intermediate_size * config.n_shared_experts,
expert_type=moe_args.expert_type,
activation=moe_args.activation,
)
self.mlp = MoE.from_args(
moe_args,
dim=config.hidden_size,
hidden_dim=config.moe_intermediate_size,
shared_expert=shared_expert,
)
else:
self.mlp = MLP(mlp_config)
self.mlp = FeedForward(
dim=config.hidden_size,
hidden_dim=config.intermediate_size,
activation=config.hidden_act,
)
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
@@ -136,7 +145,7 @@ class GlmMoeDsaPreTrainedModel(PreTrainedModelPrimeRL):
@classmethod
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
return name.endswith("mlp.expert_bias")
return name.endswith("mlp.router.selection_bias")
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
@@ -144,7 +153,7 @@ class GlmMoeDsaPreTrainedModel(PreTrainedModelPrimeRL):
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any("mlp.experts.w1" in module_name for module_name in state_dict.keys())
return any("mlp.experts.gate_proj" in module_name for module_name in state_dict.keys())
@classmethod
def conversion_chain(cls, config):
@@ -1,6 +1,6 @@
# Re-export HF's GptOssConfig so the parameter naming and rope/sliding-window defaults
# stay in sync with upstream. We don't need to subclass it: the only PrimeRL-specific
# behavior lives in modeling_gpt_oss.py (custom MoE for LoRA detection).
# behavior lives in the model and checkpoint conversion modules.
from transformers.models.gpt_oss.configuration_gpt_oss import GptOssConfig
__all__ = ["GptOssConfig"]
@@ -1,27 +1,58 @@
"""State-dict conversion for GPT-OSS.
The custom prime-rl GPT-OSS implementation mirrors HuggingFace's parameter naming
exactly (gate_up_proj/gate_up_proj_bias/down_proj/down_proj_bias plus router.weight
and router.bias as nn.Parameters). So loading the unsloth BF16 checkpoint requires
no key conversion - HF and prime formats are identical for this model.
"""
"""HF <-> PrimeRL weight conversion for GPT-OSS."""
from torch import Tensor
from prime_rl.trainer.models.conversion_ops import ConvOp
from prime_rl.trainer.models.conversion_ops import ConvOp, Rename
class GptOssExperts(ConvOp):
def __init__(self, prefix: str) -> None:
self.prefix = prefix
def hf_to_prime(self, state_dict: dict[str, Tensor]) -> None:
gate_up_name = f"{self.prefix}.gate_up_proj"
gate_up = state_dict.pop(gate_up_name)
gate_up_bias = state_dict.pop(f"{self.prefix}.gate_up_proj_bias")
state_dict[f"{self.prefix}.gate_proj"] = gate_up[..., ::2].transpose(-2, -1)
state_dict[f"{self.prefix}.up_proj"] = gate_up[..., 1::2].transpose(-2, -1)
state_dict[f"{self.prefix}.gate_proj_bias"] = gate_up_bias[..., ::2]
state_dict[f"{self.prefix}.up_proj_bias"] = gate_up_bias[..., 1::2]
state_dict[f"{self.prefix}.down_proj"] = state_dict[f"{self.prefix}.down_proj"].transpose(-2, -1)
def prime_to_hf(self, state_dict: dict[str, Tensor]) -> None:
gate_name = f"{self.prefix}.gate_proj"
gate = state_dict.pop(gate_name).transpose(-2, -1)
up = state_dict.pop(f"{self.prefix}.up_proj").transpose(-2, -1)
gate_bias = state_dict.pop(f"{self.prefix}.gate_proj_bias")
up_bias = state_dict.pop(f"{self.prefix}.up_proj_bias")
state_dict[f"{self.prefix}.gate_up_proj"] = gate.new_empty((*gate.shape[:-1], 2 * gate.shape[-1]))
state_dict[f"{self.prefix}.gate_up_proj"][..., ::2] = gate
state_dict[f"{self.prefix}.gate_up_proj"][..., 1::2] = up
state_dict[f"{self.prefix}.gate_up_proj_bias"] = gate_bias.new_empty(
(*gate_bias.shape[:-1], 2 * gate_bias.shape[-1])
)
state_dict[f"{self.prefix}.gate_up_proj_bias"][..., ::2] = gate_bias
state_dict[f"{self.prefix}.gate_up_proj_bias"][..., 1::2] = up_bias
state_dict[f"{self.prefix}.down_proj"] = state_dict[f"{self.prefix}.down_proj"].transpose(-2, -1)
def is_hf_state_dict(state_dict: dict[str, Tensor]) -> bool:
return any("mlp.experts.gate_up_proj" in name for name in state_dict.keys())
return any("mlp.experts.gate_up_proj" in name for name in state_dict)
def is_prime_state_dict(state_dict: dict[str, Tensor]) -> bool:
# Prime format equals HF format for GPT-OSS, so we never claim to be a separate
# prime format - this disables the auto-conversion path in load_dcp_from_hf and
# lets DCP load HF safetensors directly.
return False
return any("mlp.experts.gate_proj" in name for name in state_dict)
def conversion_chain(config) -> list[ConvOp]:
# HF and prime layouts coincide for GPT-OSS, so the conversion is the identity.
return []
operations: list[ConvOp] = []
for layer_idx in range(config.num_hidden_layers):
prefix = f"model.layers.{layer_idx}.mlp"
operations.extend(
[
Rename(f"{prefix}.router.weight", f"{prefix}.router.gate.weight"),
Rename(f"{prefix}.router.bias", f"{prefix}.router.gate.bias"),
GptOssExperts(f"{prefix}.experts"),
]
)
return operations
@@ -1,14 +1,9 @@
# GPT-OSS model with PrimeRL custom MoE.
#
# This file mirrors HuggingFace's modeling_gpt_oss.py but swaps the experts module for
# `GptOssGroupedExperts` so the LoRA detection logic in `prime_rl/trainer/lora.py` can
# find and adapt the expert weights. Attention, rotary embedding, and RMSNorm are reused
# from HF as-is - they correctly handle attention sinks and gpt-oss's split-rotate RoPE.
# GPT-OSS model with PrimeRL grouped experts. Attention, rotary embedding, and
# RMSNorm are reused from HuggingFace.
from typing import Union
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from transformers.cache_utils import Cache
from transformers.generation import GenerationMixin
@@ -31,101 +26,11 @@ from prime_rl.trainer.models.gpt_oss.converting_gpt_oss import (
is_prime_state_dict,
)
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.moe import GptOssGroupedExperts
class GptOssTopKRouter(nn.Module):
"""Token-choice top-k router matching HF's GptOssTopKRouter parameter naming.
Stores `weight` (num_experts, hidden_size) and `bias` (num_experts) as raw nn.Parameters
so the unsloth BF16 checkpoint loads with no key conversion. Returns the same outputs as
`TokenChoiceTopKRouter` so the surrounding MoE plumbing matches the rest of the repo.
"""
def __init__(self, config: GptOssConfig):
super().__init__()
self.num_experts = config.num_local_experts
self.top_k = config.num_experts_per_tok
self.hidden_size = config.hidden_size
self.weight = nn.Parameter(torch.empty(self.num_experts, self.hidden_size))
self.bias = nn.Parameter(torch.empty(self.num_experts))
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""x: (T, hidden). Returns (top_scores, top_indices, num_tokens_per_expert).
Matches HF's softmax-after-topk semantics: we softmax the top-k logits only,
not the full distribution.
"""
logits = F.linear(x, self.weight, self.bias) # (T, num_experts)
top_logits, top_indices = torch.topk(logits, self.top_k, dim=-1)
top_scores = F.softmax(top_logits, dim=-1, dtype=top_logits.dtype)
num_tokens_per_expert = torch.histc(
top_indices.reshape(-1).float(),
bins=self.num_experts,
min=0,
max=self.num_experts,
)
return top_scores, top_indices, num_tokens_per_expert
def init_weights(self, init_std: float):
nn.init.trunc_normal_(self.weight, mean=0.0, std=init_std)
nn.init.zeros_(self.bias)
class GptOssMoE(nn.Module):
"""GPT-OSS sparse MLP: top-k router + grouped experts with biases.
Wraps `GptOssGroupedExperts` (which expects pre-permuted tokens + num_tokens_per_expert)
with the standard MoE permute/unpermute pipeline. Routing weights are applied AFTER
the expert computation, matching HF's `routing_weights[token_idx, top_k_pos]` index_add.
"""
def __init__(self, config: GptOssConfig):
super().__init__()
# GptOssGroupedExperts has fused gate_up_proj + per-expert biases; the
# current FP8 grouped-GEMM path doesn't model that yet.
assert not getattr(config, "fp8", False), "FP8 training is not supported for GPT-OSS"
self.num_experts = config.num_local_experts
self.top_k = config.num_experts_per_tok
self.router = GptOssTopKRouter(config)
self.experts = GptOssGroupedExperts(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
num_experts=self.num_experts,
use_grouped_mm=getattr(config, "use_grouped_mm", True),
)
def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
bs, slen, dim = hidden_states.shape
x = hidden_states.reshape(-1, dim) # (T, dim)
top_scores, top_indices, num_tokens_per_expert = self.router(x)
# top_scores, top_indices: (T, top_k)
# Sort tokens by expert. Each token contributes top_k entries (one per chosen expert).
flat_expert_indices = top_indices.reshape(-1) # (T*top_k,)
sorted_perm = torch.argsort(flat_expert_indices, stable=True) # (T*top_k,)
# token id of each (token, k) entry, in expert-sorted order
token_indices_experts_sorted = sorted_perm // self.top_k
# routing weight for each (token, k) entry, in expert-sorted order
top_scores_experts_sorted = top_scores.reshape(-1)[sorted_perm]
# Gather inputs for each expert in expert-sorted order
gather_indices = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
routed_input = torch.gather(x, dim=0, index=gather_indices) # (T*top_k, dim)
routed_output = self.experts(routed_input, num_tokens_per_expert) # (T*top_k, dim)
# Apply routing weights post-experts (HF: weighted_output = out * routing_weights)
routed_output = (routed_output.float() * top_scores_experts_sorted.reshape(-1, 1)).to(routed_output.dtype)
# Scatter-add back to original token positions
out = torch.zeros_like(x)
scatter_indices = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
out = out.scatter_add(dim=0, index=scatter_indices, src=routed_output)
out = out.reshape(bs, slen, dim)
return out, top_scores # router_scores returned only for compatibility; trainer ignores
from prime_rl.trainer.models.layers.moe import (
GroupedExperts,
MoE,
TokenChoiceTopKRouter,
)
class GptOssDecoderLayer(GradientCheckpointingLayer):
@@ -133,7 +38,30 @@ class GptOssDecoderLayer(GradientCheckpointingLayer):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = GptOssAttention(config=config, layer_idx=layer_idx)
self.mlp = GptOssMoE(config)
router = TokenChoiceTopKRouter(
dim=config.hidden_size,
num_experts=config.num_local_experts,
top_k=config.num_experts_per_tok,
score_func="topk_softmax",
route_norm=False,
route_scale=1.0,
gate_bias=True,
)
experts = GroupedExperts(
dim=config.hidden_size,
hidden_dim=config.intermediate_size,
num_experts=config.num_local_experts,
expert_type="gated",
activation="clamped_swiglu",
bias=True,
)
self.mlp = MoE(
router=router,
experts=experts,
shared_expert=None,
score_before_experts=False,
load_balance_coeff=None,
)
self.input_layernorm = GptOssRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = GptOssRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
@@ -162,7 +90,7 @@ class GptOssDecoderLayer(GradientCheckpointingLayer):
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states, _ = self.mlp(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states
return hidden_states
@@ -21,12 +21,13 @@ class LagunaConfig(PretrainedConfig):
"layers.*.mlp.gate_proj": "colwise",
"layers.*.mlp.up_proj": "colwise",
"layers.*.mlp.down_proj": "rowwise",
"layers.*.mlp.experts.gate_up_proj": "packed_colwise",
"layers.*.mlp.experts.gate_proj": "colwise",
"layers.*.mlp.experts.up_proj": "colwise",
"layers.*.mlp.experts.down_proj": "rowwise",
"layers.*.mlp.experts": "moe_tp_experts",
"layers.*.shared_expert.w1": "colwise",
"layers.*.shared_expert.w2": "rowwise",
"layers.*.shared_expert.w3": "colwise",
"layers.*.mlp.shared_expert.gate_proj": "colwise",
"layers.*.mlp.shared_expert.up_proj": "colwise",
"layers.*.mlp.shared_expert.down_proj": "rowwise",
}
base_model_pp_plan = {
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
@@ -72,7 +73,6 @@ class LagunaConfig(PretrainedConfig):
moe_apply_router_weight_on_input: bool = False,
moe_router_logit_softcapping: float = 0.0,
load_balance_coeff: float | None = 1e-3,
use_grouped_mm: bool = True,
**kwargs,
):
raw_rope_parameters = rope_parameters if rope_parameters is not None else rope_scaling
@@ -107,7 +107,6 @@ class LagunaConfig(PretrainedConfig):
self.moe_apply_router_weight_on_input = moe_apply_router_weight_on_input
self.moe_router_logit_softcapping = moe_router_logit_softcapping
self.load_balance_coeff = load_balance_coeff
self.use_grouped_mm = use_grouped_mm
super().__init__(
pad_token_id=pad_token_id,
@@ -5,14 +5,14 @@ Laguna specifics:
* Router: HF ``mlp.gate.weight`` maps to prime ``mlp.router.gate.weight``.
* Expert bias: the HF input is *either* ``mlp.experts.e_score_correction_bias``
*or* ``mlp.gate.e_score_correction_bias`` (the former wins when both are
present); it maps to prime ``mlp.expert_bias``. Backward always emits the
present); it maps to prime ``mlp.router.selection_bias``. Backward always emits the
canonical ``mlp.experts.e_score_correction_bias``.
* Routed experts: HF per-expert ``mlp.experts.{e}.{gate,down,up}_proj.weight``
*or* the fused ``mlp.experts.gate_up_proj`` / ``down_proj`` layout stack into
prime ``mlp.experts.{w1,w2,w3}`` (w1=gate, w2=down, w3=up).
prime ``mlp.experts.{gate,down,up}_proj``.
* Shared expert: the HF input is *either* ``mlp.shared_expert.*`` *or*
``mlp.shared_experts.*`` (singular wins); it maps to prime
``shared_expert.{w1,w2,w3}.weight`` (no ``mlp.`` prefix, keeps ``.weight``).
``mlp.shared_expert.{gate,down,up}_proj.weight``.
Backward always emits the singular ``mlp.shared_expert.*``.
* Prime-only ``mlp.tokens_per_expert`` is dropped on the way back to HF.
"""
@@ -41,14 +41,14 @@ def conversion_chain(config) -> list[ConvOp]:
# the (always-singular) backward; the conditional adds the forward-only
# `gate.` alternate, firing only when the canonical input is absent so it
# matches the imperative's "experts wins" preference.
ops.append(Rename(f"{p}.mlp.experts.e_score_correction_bias", f"{p}.mlp.expert_bias"))
ops.append(Rename(f"{p}.mlp.experts.e_score_correction_bias", f"{p}.mlp.router.selection_bias"))
ops.append(
Conditional(
predicate=lambda sd, p=p: (
f"{p}.mlp.gate.e_score_correction_bias" in sd
and f"{p}.mlp.experts.e_score_correction_bias" not in sd
),
then=[Rename(f"{p}.mlp.gate.e_score_correction_bias", f"{p}.mlp.expert_bias")],
then=[Rename(f"{p}.mlp.gate.e_score_correction_bias", f"{p}.mlp.router.selection_bias")],
)
)
@@ -58,7 +58,7 @@ def conversion_chain(config) -> list[ConvOp]:
# Shared expert. Base Renames handle the singular input + singular
# backward; the conditional adds the forward-only plural alternate.
for wn, hf_proj in GATE_DOWN_UP:
ops.append(Rename(f"{p}.mlp.shared_expert.{hf_proj}.weight", f"{p}.shared_expert.{wn}.weight"))
ops.append(Rename(f"{p}.mlp.shared_expert.{hf_proj}.weight", f"{p}.mlp.shared_expert.{wn}.weight"))
ops.append(
Conditional(
predicate=lambda sd, p=p: (
@@ -66,7 +66,7 @@ def conversion_chain(config) -> list[ConvOp]:
and f"{p}.mlp.shared_expert.gate_proj.weight" not in sd
),
then=[
Rename(f"{p}.mlp.shared_experts.{hf_proj}.weight", f"{p}.shared_expert.{wn}.weight")
Rename(f"{p}.mlp.shared_experts.{hf_proj}.weight", f"{p}.mlp.shared_expert.{wn}.weight")
for wn, hf_proj in GATE_DOWN_UP
],
)
@@ -18,8 +18,8 @@ from prime_rl.trainer.models.laguna.configuration_laguna import LagunaConfig
from prime_rl.trainer.models.laguna.converting_laguna import conversion_chain
from prime_rl.trainer.models.layers.attn import AttentionConfig, FlashAttention
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
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.utils.sequence import get_cu_seqlens_from_seq_lens
@@ -171,32 +171,34 @@ class LagunaDecoderLayer(GradientCheckpointingLayer):
if self.mlp_layer_type == "sparse":
moe_args = MoEArgs(
num_experts=config.num_experts,
num_shared_experts=0,
expert_type="gated",
activation=config.hidden_act,
score_func="sigmoid",
route_norm=True,
route_scale=config.moe_routed_scaling_factor,
score_before_experts=False,
top_k=config.num_experts_per_tok,
use_grouped_mm=config.use_grouped_mm,
load_balance_coeff=config.load_balance_coeff,
fp8=getattr(config, "fp8", False),
)
if config.moe_router_logit_softcapping:
raise NotImplementedError("Laguna router logit softcapping is not supported by PrimeRL MoE yet.")
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
self.shared_expert = FeedForward(
self.mlp = MoE.from_args(
moe_args,
dim=config.hidden_size,
hidden_dim=config.shared_expert_intermediate_size,
hidden_dim=config.moe_intermediate_size,
shared_expert=FeedForward(
dim=config.hidden_size,
hidden_dim=config.shared_expert_intermediate_size,
expert_type=moe_args.expert_type,
activation=moe_args.activation,
),
)
else:
mlp_config = MLPConfig(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
gate_act=config.hidden_act,
bias=False,
self.mlp = FeedForward(
dim=config.hidden_size,
hidden_dim=config.intermediate_size,
activation=config.hidden_act,
)
self.mlp = MLP(mlp_config)
self.shared_expert = None
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
@@ -224,10 +226,6 @@ class LagunaDecoderLayer(GradientCheckpointingLayer):
residual = hidden_states
mlp_input = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(mlp_input, routed_experts=routed_experts)
if self.shared_expert is not None:
bs, slen, dim = hidden_states.shape
shared_output = self.shared_expert(mlp_input.view(-1, dim)).view(bs, slen, dim)
hidden_states = hidden_states + shared_output
hidden_states = residual + hidden_states
return hidden_states
@@ -257,7 +255,7 @@ class LagunaPreTrainedModel(PreTrainedModelPrimeRL):
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any("mlp.experts.w1" in name for name in state_dict)
return any("mlp.experts.gate_proj" in name for name in state_dict)
@classmethod
def conversion_chain(cls, config):
@@ -402,8 +400,8 @@ class LagunaForCausalLM(LagunaPreTrainedModel, GenerationMixin):
for module in self.modules():
if isinstance(module, MoE) and module.tokens_per_expert.device.type != "meta":
module.tokens_per_expert.zero_()
if module.expert_bias is not None:
module.expert_bias.zero_()
if module.router.selection_bias is not None:
module.router.selection_bias.zero_()
__all__ = [
@@ -0,0 +1,43 @@
from typing import Literal, Protocol
import torch
import torch.nn.functional as F
class Activation(Protocol):
@staticmethod
def apply(gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor: ...
class ClampedSwiglu(Activation):
@staticmethod
def apply(gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
assert gate is not None
gate = gate.clamp(max=7.0)
up = up.clamp(min=-7.0, max=7.0)
return (up + 1) * gate * torch.sigmoid(gate * 1.702)
class Relu2(Activation):
@staticmethod
def apply(gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
if gate is not None:
return F.relu(gate).square() * up
return F.relu(up).square()
class Silu(Activation):
@staticmethod
def apply(gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
if gate is None:
return F.silu(up)
return F.silu(gate) * up
ActivationType = Literal["silu", "relu2", "clamped_swiglu"]
ActivationDispatch: dict[ActivationType, type[Activation]] = {
"clamped_swiglu": ClampedSwiglu,
"silu": Silu,
"relu2": Relu2,
}
@@ -14,10 +14,7 @@ New model integration contract:
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 `_run_routed_experts` or `tokens_per_expert`.
- `routed_experts`: expose `layer.mlp._run_routed_experts(...)` for the MoE
expert path, and optionally `layer.mlp._run_local_routed_experts(...)` when
local expert compute is separated from dispatch/combine.
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"`.
@@ -33,7 +30,7 @@ import torch
import torch.nn as nn
from torch.utils.checkpoint import checkpoint
SELECTIVE_AC_TARGETS = frozenset({"norm", "attn_proj", "mlp", "mla_up_proj", "routed_experts", "linear_attn"})
SELECTIVE_AC_TARGETS = frozenset({"norm", "attn_proj", "mlp", "mla_up_proj", "linear_attn"})
_PATCHED_METHODS_ATTR = "_prime_rl_selective_ac_patched_methods"
@@ -74,7 +71,7 @@ def _configure_norm_checkpointing(layer: nn.Module) -> None:
def _is_dense_mlp(mlp: nn.Module) -> bool:
return not hasattr(mlp, "_run_routed_experts") and not hasattr(mlp, "tokens_per_expert")
return not hasattr(mlp, "tokens_per_expert")
def _supports_attn_proj(self_attn: nn.Module | None) -> bool:
@@ -109,8 +106,6 @@ def get_supported_targets(layer: nn.Module) -> frozenset[str]:
supported_targets.add("mla_up_proj")
if mlp is not None and _is_dense_mlp(mlp):
supported_targets.add("mlp")
if mlp is not None and (hasattr(mlp, "_run_routed_experts") or hasattr(mlp, "_run_local_routed_experts")):
supported_targets.add("routed_experts")
if linear_attn is not None:
supported_targets.add("linear_attn")
@@ -136,11 +131,6 @@ def set_selective_activation_checkpointing(layer: nn.Module, targets: Iterable[s
checkpoint_method(self_attn, "mla_up_proj")
if mlp is not None and "mlp" in enabled_targets:
checkpoint_method(mlp, "forward")
if mlp is not None and "routed_experts" in enabled_targets:
if hasattr(mlp, "_run_routed_experts"):
checkpoint_method(mlp, "_run_routed_experts")
if hasattr(mlp, "_run_local_routed_experts"):
checkpoint_method(mlp, "_run_local_routed_experts")
if linear_attn is not None and "linear_attn" in enabled_targets:
checkpoint_method(linear_attn, "forward")
if "norm" in enabled_targets:
@@ -2,13 +2,6 @@ from __future__ import annotations
import torch
try:
import deep_gemm
except ImportError:
deep_gemm = None # CPU-only environments don't ship deep_gemm; FP8 paths
# are GPU-only at runtime, so leaving the symbol None is safe — only the
# autograd Function bodies below actually call into it.
from prime_rl.trainer.models.kernels.fp8_utils import (
GROUP_ALIGNMENT,
build_grouped_layout,
@@ -33,6 +26,8 @@ def _compute_grad_weight(
block_starts_tensor: torch.Tensor,
aligned_ms: list[int],
) -> torch.Tensor:
import deep_gemm
is_sm100 = torch.cuda.get_device_capability(x.device)[0] >= 10
if is_sm100:
x_fp8 = grouped_per_channel_cast_to_fp8_rowmajor_triton(
@@ -103,6 +98,8 @@ class _GroupedFP8Gemm(torch.autograd.Function):
weight: torch.Tensor,
offs: torch.Tensor,
) -> torch.Tensor:
import deep_gemm
(
total_m,
padded_total_m,
@@ -168,6 +165,8 @@ class _GroupedFP8Gemm(torch.autograd.Function):
@staticmethod
def backward(ctx, grad_output: torch.Tensor):
import deep_gemm
(
x,
weight,
@@ -5,13 +5,6 @@ import re
import torch
from torch import nn
try:
import deep_gemm
except ImportError:
deep_gemm = None # CPU-only environments don't ship deep_gemm; FP8 paths
# are GPU-only at runtime, so leaving the symbol None is safe — only the
# autograd Function bodies below actually call into it.
from prime_rl.trainer.models.kernels.fp8_utils import (
per_block_cast_to_fp8_tp_triton,
per_block_cast_to_fp8_triton,
@@ -25,6 +18,8 @@ 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
x_shape = x.shape
x_2d = x.reshape(-1, x_shape[-1]).contiguous()
use_ue8m0 = ue8m0_for_device(x.device)
@@ -41,6 +36,8 @@ class _FP8BlockwiseMM(torch.autograd.Function):
@staticmethod
def backward(ctx, grad_output):
import deep_gemm
x_2d, weight = ctx.saved_tensors
block_size = ctx.block_size
grad_output_2d = grad_output.reshape(-1, grad_output.shape[-1]).contiguous()
@@ -119,7 +116,7 @@ def replace_linear_with_fp8_blockwise_linear(model: nn.Module, ignore_modules: l
The default ignore list covers layers that should never be quantized:
- lm_head
- MoE routers and gates (router, mlp.gate., shared_expert_gate)
- MoE routers and gates (router, mlp.gate., shared_expert.output_gate)
- sparse-MLA scalar projection (weights_proj)
- GLM-5.1 MTP head (eh_proj)
- hybrid-Mamba projections (in_proj_a, in_proj_b)
@@ -0,0 +1,68 @@
from dataclasses import dataclass
from types import ModuleType
from typing import Protocol
import torch
class GroupedGemm(Protocol):
token_group_alignment: int
def __call__(
self,
x: torch.Tensor,
weight_t: torch.Tensor,
*,
offs: torch.Tensor,
) -> torch.Tensor: ...
@dataclass(frozen=True)
class BF16GroupedGemm:
token_group_alignment: int = 8
def __call__(
self,
x: torch.Tensor,
weight_t: torch.Tensor,
*,
offs: torch.Tensor,
) -> torch.Tensor:
return torch._grouped_mm(x, weight_t, offs=offs)
@dataclass(frozen=True)
class DeepGemmFP8GroupedGemm:
token_group_alignment: int = 8
def __call__(
self,
x: torch.Tensor,
weight_t: torch.Tensor,
*,
offs: torch.Tensor,
) -> torch.Tensor:
from prime_rl.trainer.models.layers.fp8_grouped_gemm import grouped_fp8_gemm
return grouped_fp8_gemm(x, weight_t, offs)
@dataclass(frozen=True)
class MXFP8GroupedGemm:
kernel: ModuleType
high_precision_wgrad: bool
token_group_alignment: int
def __call__(
self,
x: torch.Tensor,
weight_t: torch.Tensor,
*,
offs: torch.Tensor,
) -> torch.Tensor:
return self.kernel.grouped_gemm(
x,
weight_t,
offs,
high_precision_wgrad=self.high_precision_wgrad,
)
File diff suppressed because it is too large Load Diff
+34 -21
View File
@@ -1,29 +1,42 @@
from dataclasses import dataclass
from typing import Literal
import torch
from torch import nn
from transformers.activations import ACT2FN
from prime_rl.trainer.models.layers.activations import ActivationDispatch, ActivationType
ExpertType = Literal["gated", "non_gated"]
@dataclass
class MLPConfig:
hidden_size: int
intermediate_size: int
gate_act: str
bias: bool
class FeedForward(nn.Module):
"""Dense feed-forward layer using the canonical projection names."""
class MLP(nn.Module):
def __init__(self, config: MLPConfig):
def __init__(
self,
dim: int,
hidden_dim: int,
*,
expert_type: ExpertType = "gated",
activation: ActivationType = "silu",
bias: bool = False,
) -> None:
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.intermediate_size = config.intermediate_size
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
self.gate_act_fn = ACT2FN[config.gate_act]
self.gate_proj = nn.Linear(dim, hidden_dim, bias=bias) if expert_type == "gated" else None
self.up_proj = nn.Linear(dim, hidden_dim, bias=bias)
self.down_proj = nn.Linear(hidden_dim, dim, bias=bias)
self.activation = ActivationDispatch[activation]
def forward(self, x, routed_experts: torch.Tensor | None = None):
down_proj = self.down_proj(self.gate_act_fn(self.gate_proj(x)) * self.up_proj(x))
return down_proj
def forward(self, x: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
gate = self.gate_proj(x) if self.gate_proj is not None else None
up = self.up_proj(x)
return self.down_proj(self.activation.apply(gate, up))
def init_weights(self, init_std: float = 0.02) -> None:
first_projection = self.gate_proj if self.gate_proj is not None else self.up_proj
nn.init.trunc_normal_(first_projection.weight, mean=0.0, std=0.02)
remaining = (self.up_proj, self.down_proj) if self.gate_proj is not None else (self.down_proj,)
for linear in remaining:
nn.init.trunc_normal_(linear.weight, mean=0.0, std=init_std)
for linear in (self.gate_proj, self.up_proj, self.down_proj):
if linear is not None and linear.bias is not None:
nn.init.zeros_(linear.bias)
File diff suppressed because it is too large Load Diff
@@ -1,114 +0,0 @@
from __future__ import annotations
import torch
from torch import nn
from torchao.prototype.moe_training import conversion_utils as cu
from torchao.prototype.moe_training import mxfp8_grouped_mm as tao_mxfp8_gmm
from torchao.prototype.moe_training.config import MXFP8TrainingOpConfig, MXFP8TrainingRecipe
from torchao.prototype.moe_training.kernels.mxfp8 import triton_mx_block_rearrange_2d_M_groups
from torchao.prototype.moe_training.tensor import MXFP8TrainingWeightWrapperTensor
from torchao.quantization.quant_api import quantize_
from torchtitan.distributed.expert_parallel import set_token_group_alignment_size_m
from torchtitan.experiments.kernels.moe import indices as tt_indices
from prime_rl.configs.trainer import MXFP8Recipe
from prime_rl.trainer.models.layers.moe import GroupedExperts, NonGatedGroupedExperts
from prime_rl.utils.logger import get_logger
_MXFP8_TOKEN_GROUP_ALIGN: int = 32
# torchao CUDA scale rearrange kernel supports at most 32 token groups,
# the Triton variant has no such cap and produces the same swizzled layout, so fall back to it for wider MoEs
_CUDA_REARRANGE_MAX_GROUPS: int = 32
# torchao's dim0 quantize Triton kernel indexes with int32 and corrupts mem when numel >= INT_MAX=2^31
_QUANT_NUMEL_LIMIT: int = 1 << 31
_QUANT_CHUNK_NUMEL: int = 1 << 30
def _fallback_to_triton_rearrange_for_wide_moes() -> None:
if getattr(tao_mxfp8_gmm.mx_block_rearrange_2d_M_groups_cuda, "_prime_rl_wide_moe", False):
return
original = tao_mxfp8_gmm.mx_block_rearrange_2d_M_groups_cuda
def mx_block_rearrange_2d_M_groups(
scales_tensor: torch.Tensor, input_group_end_offsets: torch.Tensor, chunks_per_tb: int = 4
) -> torch.Tensor:
if input_group_end_offsets.shape[0] > _CUDA_REARRANGE_MAX_GROUPS:
return triton_mx_block_rearrange_2d_M_groups(scales_tensor, input_group_end_offsets)
return original(scales_tensor, input_group_end_offsets, chunks_per_tb)
mx_block_rearrange_2d_M_groups._prime_rl_wide_moe = True
tao_mxfp8_gmm.mx_block_rearrange_2d_M_groups_cuda = mx_block_rearrange_2d_M_groups
def _chunk_dim0_quantize_for_large_inputs() -> None:
if getattr(tao_mxfp8_gmm.triton_to_mxfp8_dim0, "_prime_rl_chunked", False):
return
original = tao_mxfp8_gmm.triton_to_mxfp8_dim0
def triton_to_mxfp8_dim0(x: torch.Tensor, inner_block_size: int = 32, scaling_mode: str = "rceil") -> torch.Tensor:
if x.ndim != 2 or x.numel() < _QUANT_NUMEL_LIMIT:
return original(x, inner_block_size=inner_block_size, scaling_mode=scaling_mode)
rows_per_chunk = max(1, _QUANT_CHUNK_NUMEL // x.shape[1])
outs, scales = zip(
*(
original(chunk, inner_block_size=inner_block_size, scaling_mode=scaling_mode)
for chunk in x.split(rows_per_chunk, dim=0)
)
)
return torch.cat(outs, dim=0), torch.cat(scales, dim=0)
triton_to_mxfp8_dim0._prime_rl_chunked = True
tao_mxfp8_gmm.triton_to_mxfp8_dim0 = triton_to_mxfp8_dim0
def _relax_torchao_mxfp8_version_gate() -> None:
if getattr(cu._get_tensor_cls_for_config, "_prime_rl_relaxed", False):
return
original = cu._get_tensor_cls_for_config
def _get_tensor_cls_for_config(config):
if isinstance(config, MXFP8TrainingOpConfig):
return MXFP8TrainingWeightWrapperTensor
return original(config)
_get_tensor_cls_for_config._prime_rl_relaxed = True
cu._get_tensor_cls_for_config = _get_tensor_cls_for_config
def _align_permute_indices_buffer() -> None:
"""
Align the permuted index buffer to a multiple of alignment as the kernel requires rows % 32 = 0 and cols % 32 = 0.
"""
if getattr(tt_indices.generate_permute_indices, "_prime_rl_aligned", False):
return
original = tt_indices.generate_permute_indices
def generate_permute_indices(
tokens_per_expert_group, experts_per_rank, num_ranks, max_len, alignment, use_cpu=False
):
al_mask = alignment - 1
assert alignment > 0 and (alignment & al_mask) == 0
max_len = (max_len + al_mask) & ~al_mask
return original(tokens_per_expert_group, experts_per_rank, num_ranks, max_len, alignment, use_cpu=use_cpu)
generate_permute_indices._prime_rl_aligned = True
tt_indices.generate_permute_indices = generate_permute_indices
def apply_mxfp8_moe_grouped_gemm(model: nn.Module, recipe: MXFP8Recipe) -> None:
_relax_torchao_mxfp8_version_gate()
_align_permute_indices_buffer()
_fallback_to_triton_rearrange_for_wide_moes()
_chunk_dim0_quantize_for_large_inputs()
set_token_group_alignment_size_m(_MXFP8_TOKEN_GROUP_ALIGN)
op_config = MXFP8TrainingOpConfig.from_recipe(MXFP8TrainingRecipe(recipe))
def filter_fn(module: nn.Module, fqn: str) -> bool:
return isinstance(module, (GroupedExperts, NonGatedGroupedExperts))
quantize_(model, config=op_config, filter_fn=filter_fn)
get_logger().info(
f"Wrapped MoE expert weights with MXFP8 grouped GEMM (recipe={recipe}, "
f"token_group_align={_MXFP8_TOKEN_GROUP_ALIGN})"
)
@@ -4,8 +4,8 @@ import re
import torch
from torch import nn
from torchao.prototype.moe_training.mxfp8_linear import _to_mxfp8_then_scaled_mm
from torchao.prototype.mx_formats import ScaleCalculationMode
from torchao.prototype.mx_formats.mx_linear import _to_mxfp8_then_scaled_mm
from torchao.quantization.quantize_.common import KernelPreference
from prime_rl.configs.trainer import MXFP8Recipe
@@ -37,7 +37,7 @@ from transformers.utils.deprecation import deprecate_kwarg
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
from prime_rl.trainer.models.layers.mlp import FeedForward
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
@@ -62,13 +62,12 @@ class LlamaDecoderLayer(GradientCheckpointingLayer):
)
self.self_attn = ATTN_IMPL2CLASS[config._attn_implementation](attn_config)
mlp_config = MLPConfig(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
gate_act=config.hidden_act,
self.mlp = FeedForward(
dim=config.hidden_size,
hidden_dim=config.intermediate_size,
activation=config.hidden_act,
bias=config.mlp_bias,
)
self.mlp = MLP(mlp_config)
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
@@ -44,8 +44,6 @@ class MiniMaxM2Config(PretrainedConfig):
Type of QK normalization. "per_layer" means each head has its own scale.
attention_bias (`bool`, *optional*, defaults to `False`):
Whether to use bias in attention projections.
use_grouped_mm (`bool`, *optional*, defaults to `True`):
Whether to use grouped matmul for experts.
"""
model_type = "minimax_m2"
@@ -96,7 +94,6 @@ class MiniMaxM2Config(PretrainedConfig):
output_router_logits=False,
router_aux_loss_coef=0.001,
router_jitter_noise=0.0,
use_grouped_mm=True,
**kwargs,
):
self.vocab_size = vocab_size
@@ -138,9 +135,6 @@ class MiniMaxM2Config(PretrainedConfig):
self.use_qk_norm = use_qk_norm
self.qk_norm_type = qk_norm_type
# Training
self.use_grouped_mm = use_grouped_mm
super().__init__(
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
@@ -1,8 +1,8 @@
"""HF<->prime weight conversion for MiniMax M2, as a declarative op chain.
Per layer: router ``block_sparse_moe.gate.weight`` <-> ``mlp.router.gate.weight``,
the ``e_score_correction_bias`` <-> ``mlp.expert_bias``, and the routed experts
(per-expert w1/w2/w3 ``nn.Linear`` <-> stacked w1/w2/w3). The prime-only runtime
the ``e_score_correction_bias`` <-> ``mlp.router.selection_bias``, and the routed experts
(per-expert w1/w2/w3 ``nn.Linear`` <-> stacked gate/down/up projections). The prime-only runtime
buffer ``mlp.tokens_per_expert`` is dropped on the way to HF.
"""
@@ -11,8 +11,8 @@ from __future__ import annotations
from prime_rl.trainer.models.conversion_ops import ConvOp, Drop, Rename, routed_experts_op
# HF stores per-expert projections under the literal names w1/w2/w3 (nn.Linear,
# so each carries a `.weight` suffix); prime stacks them as w1/w2/w3.
_MINIMAX_PROJ_ORDER = (("w1", "w1"), ("w2", "w2"), ("w3", "w3"))
# so each carries a `.weight` suffix); PrimeRL uses canonical projection names.
_MINIMAX_PROJ_ORDER = (("gate_proj", "w1"), ("down_proj", "w2"), ("up_proj", "w3"))
def conversion_chain(config) -> list[ConvOp]:
@@ -20,7 +20,7 @@ def conversion_chain(config) -> list[ConvOp]:
for i in range(config.num_hidden_layers):
p = f"model.layers.{i}"
ops.append(Rename(f"{p}.block_sparse_moe.gate.weight", f"{p}.mlp.router.gate.weight"))
ops.append(Rename(f"{p}.block_sparse_moe.e_score_correction_bias", f"{p}.mlp.expert_bias"))
ops.append(Rename(f"{p}.block_sparse_moe.e_score_correction_bias", f"{p}.mlp.router.selection_bias"))
ops.append(
routed_experts_op(
p,
@@ -42,17 +42,21 @@ class MiniMaxM2DecoderLayer(GradientCheckpointingLayer):
moe_args = MoEArgs(
num_experts=config.num_local_experts,
num_shared_experts=0,
expert_type="gated",
activation=config.hidden_act,
score_func=config.scoring_func,
route_norm=True,
route_scale=1.0,
score_before_experts=False,
top_k=config.num_experts_per_tok,
use_grouped_mm=config.use_grouped_mm,
load_balance_coeff=1e-3 if config.use_routing_bias else None,
fp8=getattr(config, "fp8", False),
)
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.intermediate_size)
self.mlp = MoE.from_args(
moe_args,
dim=config.hidden_size,
hidden_dim=config.intermediate_size,
shared_expert=None,
)
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
@@ -104,7 +108,7 @@ class MiniMaxM2PreTrainedModel(PreTrainedModelPrimeRL):
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any("mlp.experts.w1" in name for name in state_dict.keys())
return any("mlp.experts.gate_proj" in name for name in state_dict.keys())
@classmethod
def conversion_chain(cls, config):
@@ -6,7 +6,7 @@ class NemotronHConfig(PretrainedConfig):
The model architecture is defined by `layers_block_type`, a list where each element is
one of "mamba", "attention", or "moe". The 120B model uses a pattern like MEMEMEM*EMEMEMEM*...
(M=Mamba-2, E=LatentMoE, *=Attention) repeated across 88 layers.
(M=Mamba-2, E=MoE with latent projections, *=Attention) repeated across 88 layers.
Args:
vocab_size: Vocabulary size.
@@ -46,8 +46,6 @@ class NemotronHConfig(PretrainedConfig):
moe_latent_size: Latent projection size (None means use hidden_size).
num_experts_per_tok: Top-k routing parameter.
routed_scaling_factor: Scaling factor for routed expert outputs.
n_group: Number of groups for expert routing.
topk_group: Top-k group parameter.
norm_topk_prob: Whether to normalize top-k probabilities.
use_bias: Global bias setting.
initializer_range: Standard deviation for weight initialization.
@@ -55,7 +53,6 @@ class NemotronHConfig(PretrainedConfig):
residual_in_fp32: Whether to keep residuals in fp32.
rescale_prenorm_residual: Whether to rescale pre-norm residuals.
load_balance_coeff: Auxiliary-loss-free load balancing coefficient.
use_grouped_mm: Whether to use grouped MM for experts.
"""
model_type = "nemotron_h"
@@ -109,8 +106,6 @@ class NemotronHConfig(PretrainedConfig):
moe_latent_size=None,
num_experts_per_tok=2,
routed_scaling_factor=1.0,
n_group=1,
topk_group=1,
norm_topk_prob=True,
# General training
use_bias=False,
@@ -120,7 +115,6 @@ class NemotronHConfig(PretrainedConfig):
rescale_prenorm_residual=True,
# PrimeRL training features
load_balance_coeff=None,
use_grouped_mm=True,
# RoPE
rope_theta=10000.0,
rope_scaling=None,
@@ -191,8 +185,6 @@ class NemotronHConfig(PretrainedConfig):
self.moe_latent_size = moe_latent_size
self.num_experts_per_tok = num_experts_per_tok
self.routed_scaling_factor = routed_scaling_factor
self.n_group = n_group
self.topk_group = topk_group
self.norm_topk_prob = norm_topk_prob
# General training config
@@ -204,7 +196,6 @@ class NemotronHConfig(PretrainedConfig):
# PrimeRL training features
self.load_balance_coeff = load_balance_coeff
self.use_grouped_mm = use_grouped_mm
super().__init__(
pad_token_id=pad_token_id,
@@ -5,14 +5,11 @@ split into prime's ``mamba`` / ``self_attn`` / ``mlp`` by layer type, the
checkpoint uses a ``backbone.`` prefix, and the MoE router bias is shifted by
its per-tensor min on the way in (and intentionally *not* restored on the way
out — a lossy roundtrip the chain reproduces via a :class:`MapValue` whose
backward is the identity). Experts are up/down only (no gate); a dummy ``w3``
of shape ``(0,)`` is synthesised for expert-parallel compatibility.
backward is the identity). Experts are up/down only, with no gate projection.
"""
from __future__ import annotations
import torch
from prime_rl.trainer.models.conversion_ops import (
Conditional,
ConvOp,
@@ -21,47 +18,42 @@ from prime_rl.trainer.models.conversion_ops import (
PrefixRename,
Rename,
Stack,
Synthetic,
key_present,
)
def _empty_w3(prefix: str):
def factory(sd):
w1 = f"{prefix}.mlp.experts.w1"
device = sd[w1].device if w1 in sd else "cpu"
return torch.empty(0, device=device)
return factory
def _moe_layer_ops(prefix: str) -> list[ConvOp]:
return [
# Router: gate.weight -> router.gate (note: prime drops the .weight),
# Router gate and selection bias.
# plus the load-balancing bias which is shifted by its min on the way in
# and not undone on the way out (MapValue backward = identity).
Rename(f"{prefix}.mixer.gate.weight", f"{prefix}.mlp.router.gate"),
Rename(f"{prefix}.mixer.gate.e_score_correction_bias", f"{prefix}.mlp.router.e_score_correction_bias"),
Rename(f"{prefix}.mixer.gate.weight", f"{prefix}.mlp.router.gate.weight"),
Rename(f"{prefix}.mixer.gate.e_score_correction_bias", f"{prefix}.mlp.router.selection_bias"),
MapValue(
f"{prefix}.mlp.router.e_score_correction_bias",
f"{prefix}.mlp.router.selection_bias",
forward=lambda x: x - x.min(),
backward=lambda x: x,
),
# Experts: w1=up, w2=down (no gate). HF is either per-expert weights or
# Experts are up/down only. HF is either per-expert weights or
# a 3-D fused-at-experts-level up_proj/down_proj. Backward always emits
# per-expert (the predicate's HF key is absent in prime -> else branch).
Conditional(
predicate=key_present(f"{prefix}.mixer.experts.up_proj"),
then=[
Rename(f"{prefix}.mixer.experts.up_proj", f"{prefix}.mlp.experts.w1"),
Rename(f"{prefix}.mixer.experts.down_proj", f"{prefix}.mlp.experts.w2"),
Rename(f"{prefix}.mixer.experts.up_proj", f"{prefix}.mlp.experts.up_proj"),
Rename(f"{prefix}.mixer.experts.down_proj", f"{prefix}.mlp.experts.down_proj"),
],
else_=[
Stack(stacked=f"{prefix}.mlp.experts.w1", item=f"{prefix}.mixer.experts.{{e}}.up_proj.weight"),
Stack(stacked=f"{prefix}.mlp.experts.w2", item=f"{prefix}.mixer.experts.{{e}}.down_proj.weight"),
Stack(
stacked=f"{prefix}.mlp.experts.up_proj",
item=f"{prefix}.mixer.experts.{{e}}.up_proj.weight",
),
Stack(
stacked=f"{prefix}.mlp.experts.down_proj",
item=f"{prefix}.mixer.experts.{{e}}.down_proj.weight",
),
],
),
Synthetic(f"{prefix}.mlp.experts.w3", factory=_empty_w3(prefix)),
PrefixRename(f"{prefix}.mixer.shared_experts.", f"{prefix}.mlp.shared_expert."),
PrefixRename(f"{prefix}.mixer.fc1_latent_proj.", f"{prefix}.mlp.fc1_latent_proj."),
PrefixRename(f"{prefix}.mixer.fc2_latent_proj.", f"{prefix}.mlp.fc2_latent_proj."),
@@ -74,13 +66,13 @@ def _layer_op(prefix: str) -> ConvOp:
namespace is disambiguated by which sub-key is present (and, on the way
back, by which prime namespace is present, so the predicates work both
directions). Mamba/attention keep a bulk ``PrefixRename`` (robust to params
we didn't enumerate); MoE needs its specific ops (and the gated
``Synthetic`` w3, which is why this is a Conditional rather than a plain
catch-all)."""
we didn't enumerate); MoE needs its specific ops."""
is_attention = lambda sd: ( # noqa: E731
f"{prefix}.mixer.q_proj.weight" in sd or f"{prefix}.self_attn.q_proj.weight" in sd
)
is_moe = lambda sd: f"{prefix}.mixer.gate.weight" in sd or f"{prefix}.mlp.router.gate" in sd # noqa: E731
is_moe = lambda sd: ( # noqa: E731
f"{prefix}.mixer.gate.weight" in sd or f"{prefix}.mlp.router.gate.weight" in sd
)
return Conditional(
is_attention,
then=[PrefixRename(f"{prefix}.mixer.", f"{prefix}.self_attn.")],
@@ -2,7 +2,7 @@
Hybrid Mamba-Transformer-MoE architecture with three distinct layer types:
- Mamba-2 layers (using NemotronHMamba2Mixer from HF transformers)
- LatentMoE layers (non-gated experts with latent projections)
- MoE layers with non-gated experts and latent projections
- Attention layers (using shared FlashAttention/SDPA from prime-rl)
"""
@@ -23,7 +23,12 @@ from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
from prime_rl.trainer.models.layers.cp_mamba import mamba_cp_forward
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.moe import LatentMoE, NemotronHRouter, NonGatedGroupedExperts
from prime_rl.trainer.models.layers.mlp import FeedForward
from prime_rl.trainer.models.layers.moe import (
GroupedExperts,
MoE,
TokenChoiceTopKRouter,
)
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.ulysses_attn import ULYSSES_PARAMS
from prime_rl.trainer.models.nemotron_h.configuration_nemotron_h import NemotronHConfig
@@ -233,27 +238,65 @@ class NemotronHMambaLayer(GradientCheckpointingLayer):
return residual + hidden_states
class NemotronHMoE(MoE):
def __init__(self, *, hidden_size: int, latent_size: int, **kwargs):
super().__init__(**kwargs)
self.fc1_latent_proj = nn.Linear(hidden_size, latent_size, bias=False)
self.fc2_latent_proj = nn.Linear(latent_size, hidden_size, bias=False)
def prepare_expert_input(self, x: torch.Tensor) -> torch.Tensor:
return self.fc1_latent_proj(x)
def prepare_expert_output(self, x: torch.Tensor) -> torch.Tensor:
return self.fc2_latent_proj(x)
class NemotronHMoELayer(GradientCheckpointingLayer):
"""MoE layer: norm -> LatentMoE -> residual."""
"""MoE layer with latent routed experts."""
def __init__(self, config: NemotronHConfig):
super().__init__()
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.layer_norm_epsilon))
self.mlp = LatentMoE(
effective_latent_dim = config.moe_latent_size if config.moe_latent_size is not None else config.hidden_size
router = TokenChoiceTopKRouter(
dim=config.hidden_size,
latent_dim=config.moe_latent_size,
moe_intermediate_size=config.moe_intermediate_size,
shared_expert_intermediate_size=config.moe_shared_expert_intermediate_size,
num_experts=config.n_routed_experts,
top_k=config.num_experts_per_tok,
n_group=config.n_group,
topk_group=config.topk_group,
norm_topk_prob=config.norm_topk_prob,
routed_scaling_factor=config.routed_scaling_factor,
use_grouped_mm=config.use_grouped_mm,
load_balance_coeff=config.load_balance_coeff,
fp8=getattr(config, "fp8", False),
score_func="sigmoid",
route_norm=config.norm_topk_prob,
route_scale=config.routed_scaling_factor,
selection_bias=True,
topk_sorted=False,
)
router.fp32_gate = True
experts = GroupedExperts(
dim=effective_latent_dim,
hidden_dim=config.moe_intermediate_size,
num_experts=config.n_routed_experts,
expert_type="non_gated",
activation=config.mlp_hidden_act,
)
shared_expert = FeedForward(
dim=config.hidden_size,
hidden_dim=config.moe_shared_expert_intermediate_size,
expert_type="non_gated",
activation=config.mlp_hidden_act,
)
moe_kwargs = dict(
router=router,
experts=experts,
shared_expert=shared_expert,
score_before_experts=False,
load_balance_coeff=config.load_balance_coeff,
)
if config.moe_latent_size is None:
self.mlp = MoE(**moe_kwargs)
else:
self.mlp = NemotronHMoE(
hidden_size=config.hidden_size,
latent_size=config.moe_latent_size,
**moe_kwargs,
)
def forward(
self,
@@ -336,7 +379,7 @@ class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
@classmethod
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
return name.endswith(("mamba.A_log", "mamba.D", "mlp.router.e_score_correction_bias"))
return name.endswith(("mamba.A_log", "mamba.D", "mlp.router.selection_bias"))
def _init_weights(self, module):
std = self.config.initializer_range
@@ -348,7 +391,7 @@ class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
module.weight.data.normal_(mean=0.0, std=std)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
elif isinstance(module, (NonGatedGroupedExperts, NemotronHRouter)):
elif isinstance(module, (GroupedExperts, TokenChoiceTopKRouter)):
module.init_weights(std)
@classmethod
@@ -359,7 +402,7 @@ class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any(
"mamba." in name
or "mlp.experts.w1" in name
or "mlp.experts.up_proj" in name
or "self_attn." in name
or "model.embed_tokens." in name
or "model.norm." in name
@@ -13,7 +13,7 @@ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tu
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
from prime_rl.trainer.models.layers.mlp import FeedForward
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
@@ -52,13 +52,11 @@ class Qwen3DecoderLayer(GradientCheckpointingLayer):
if self.layer_type == "sliding_attention":
self.self_attn.sliding_window = config.sliding_window
mlp_config = MLPConfig(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
gate_act=config.hidden_act,
bias=False,
self.mlp = FeedForward(
dim=config.hidden_size,
hidden_dim=config.intermediate_size,
activation=config.hidden_act,
)
self.mlp = MLP(mlp_config)
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
@@ -18,7 +18,7 @@ from transformers.utils import TransformersKwargs
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
from prime_rl.trainer.models.layers.mlp import FeedForward
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
Qwen3_5MoeGatedAttentionConfig,
Qwen3_5MoeGatedDeltaNet,
@@ -84,13 +84,11 @@ class Qwen3_5DecoderLayer(GradientCheckpointingLayer):
else:
raise ValueError(f"Unsupported Qwen3.5 layer type: {self.layer_type}")
mlp_config = MLPConfig(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
gate_act=config.hidden_act,
bias=False,
self.mlp = FeedForward(
dim=config.hidden_size,
hidden_dim=config.intermediate_size,
activation=config.hidden_act,
)
self.mlp = MLP(mlp_config)
self.input_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
@@ -50,7 +50,6 @@ class Qwen3_5MoeConfig(PretrainedConfig):
layer_types=None,
# PrimeRL additions
load_balance_coeff=None,
use_grouped_mm=True,
pad_token_id=None,
**kwargs,
):
@@ -100,7 +99,6 @@ class Qwen3_5MoeConfig(PretrainedConfig):
# PrimeRL additions
self.load_balance_coeff = load_balance_coeff
self.use_grouped_mm = use_grouped_mm
super().__init__(
tie_word_embeddings=tie_word_embeddings,
@@ -1,10 +1,7 @@
"""HF<->prime weight conversion for Qwen3.5-MoE, as a declarative op chain.
Per layer: router ``mlp.gate.weight`` <-> ``mlp.router.gate.weight``, the routed
experts (per-expert gate/down/up <-> stacked w1/w2/w3, with the fused
transformers-v5 ``gate_up_proj`` input also accepted), the shared expert
(``mlp.shared_expert.{gate,down,up}_proj`` <-> ``shared_expert.{w1,w2,w3}``) and
its gate (``mlp.shared_expert_gate`` <-> ``shared_expert_gate``).
Per layer: the router and shared-expert output gate are nested under their
PrimeRL modules, and routed experts use stacked canonical projections.
"""
from __future__ import annotations
@@ -18,14 +15,8 @@ def _conversion_chain(config, model_prefix: str) -> list[ConvOp]:
p = f"{model_prefix}.layers.{i}"
# Router: mlp.gate.weight -> mlp.router.gate.weight
ops.append(Rename(f"{p}.mlp.gate.weight", f"{p}.mlp.router.gate.weight"))
# Routed experts: per-expert (gate/down/up) or fused gate_up_proj -> w1/w2/w3
ops.append(Rename(f"{p}.mlp.shared_expert_gate.weight", f"{p}.mlp.shared_expert.output_gate.weight"))
ops.append(routed_experts_op(p, hf_experts="mlp.experts", prime_experts="mlp.experts", fused=True))
# Shared expert: mlp.shared_expert.{gate,down,up}_proj.weight -> shared_expert.{w1,w2,w3}.weight
ops.append(Rename(f"{p}.mlp.shared_expert.gate_proj.weight", f"{p}.shared_expert.w1.weight"))
ops.append(Rename(f"{p}.mlp.shared_expert.down_proj.weight", f"{p}.shared_expert.w2.weight"))
ops.append(Rename(f"{p}.mlp.shared_expert.up_proj.weight", f"{p}.shared_expert.w3.weight"))
# Shared expert gate
ops.append(Rename(f"{p}.mlp.shared_expert_gate.weight", f"{p}.shared_expert_gate.weight"))
return ops
@@ -26,7 +26,8 @@ from prime_rl.trainer.models.layers.attn import (
flash_attn_varlen_func,
)
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
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.rotary_emb import apply_rotary_pos_emb
from prime_rl.utils.cp import setup_cp_attention_params, shard_for_cp, shard_position_ids_for_cp
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
@@ -421,6 +422,24 @@ def _get_gated_attention(config: Qwen3_5MoeConfig) -> nn.Module:
return QWEN35MOE_ATTN_IMPL2CLASS[attn_impl](attn_config)
class Qwen3_5MoeSharedExpert(FeedForward):
def __init__(self, config: Qwen3_5MoeConfig) -> None:
super().__init__(
dim=config.hidden_size,
hidden_dim=config.shared_expert_intermediate_size,
expert_type="gated",
activation=config.hidden_act,
)
self.output_gate = nn.Linear(config.hidden_size, 1, bias=False)
def forward(self, x: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
return torch.sigmoid(self.output_gate(x)) * super().forward(x, routed_experts)
def init_weights(self, init_std: float = 0.02) -> None:
super().init_weights(init_std)
nn.init.trunc_normal_(self.output_gate.weight, mean=0.0, std=init_std)
class Qwen3_5MoeDecoderLayer(GradientCheckpointingLayer):
def __init__(self, config: Qwen3_5MoeConfig, layer_idx: int):
super().__init__()
@@ -433,24 +452,23 @@ class Qwen3_5MoeDecoderLayer(GradientCheckpointingLayer):
elif self.layer_type == "full_attention":
self.self_attn = _get_gated_attention(config)
# MoE: routed experts via shared MoE class (no shared experts in MoE itself)
moe_args = MoEArgs(
num_experts=config.num_experts,
num_shared_experts=0,
expert_type="gated",
activation=config.hidden_act,
score_func="softmax",
route_norm=True,
route_scale=1.0,
score_before_experts=False,
top_k=config.num_experts_per_tok,
use_grouped_mm=config.use_grouped_mm,
load_balance_coeff=config.load_balance_coeff,
fp8=getattr(config, "fp8", False),
)
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
# Separate gated shared expert
self.shared_expert = FeedForward(dim=config.hidden_size, hidden_dim=config.shared_expert_intermediate_size)
self.shared_expert_gate = nn.Linear(config.hidden_size, 1, bias=False)
self.mlp = MoE.from_args(
moe_args,
dim=config.hidden_size,
hidden_dim=config.moe_intermediate_size,
shared_expert=Qwen3_5MoeSharedExpert(config),
)
# Layer norms with (1+weight) parameterization
self.input_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
@@ -483,21 +501,9 @@ class Qwen3_5MoeDecoderLayer(GradientCheckpointingLayer):
hidden_states = residual + hidden_states
# MLP: routed experts + gated shared expert
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
# Routed experts
routed_output = self.mlp(hidden_states, routed_experts=routed_experts)
# Gated shared expert
bs, slen, dim = hidden_states.shape
hidden_flat = hidden_states.view(-1, dim)
shared_output = self.shared_expert(hidden_flat)
shared_output = F.sigmoid(self.shared_expert_gate(hidden_flat)) * shared_output
shared_output = shared_output.view(bs, slen, dim)
hidden_states = residual + routed_output + shared_output
hidden_states = residual + self.mlp(hidden_states, routed_experts=routed_experts)
return hidden_states
@@ -643,16 +649,11 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any(
"mlp.experts.1.up_proj" in name
or "mlp.experts.gate_up_proj" in name
or "mlp.shared_expert.gate_proj" in name
for name in state_dict.keys()
)
return any("mlp.experts.1.up_proj" in name or "mlp.experts.gate_up_proj" in name for name in state_dict.keys())
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any("mlp.experts.w1" in name for name in state_dict.keys())
return any("mlp.experts.gate_proj" in name for name in state_dict.keys())
@classmethod
def conversion_chain(cls, config):
@@ -927,16 +928,11 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any(
"mlp.experts.gate_up_proj" in name
or "mlp.experts.1.up_proj" in name
or "mlp.shared_expert.gate_proj" in name
for name in state_dict
)
return any("mlp.experts.gate_up_proj" in name or "mlp.experts.1.up_proj" in name for name in state_dict)
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any("mlp.experts.w1" in name for name in state_dict)
return any("mlp.experts.gate_proj" in name for name in state_dict)
# ------------------------------------------------------------------
# Forward
@@ -126,9 +126,9 @@ class Qwen3MoeConfig(PretrainedConfig):
"layers.*.self_attn.k_proj": "colwise",
"layers.*.self_attn.v_proj": "colwise",
"layers.*.self_attn.o_proj": "rowwise",
"layers.*.mlp.experts.*.gate_proj": "colwise",
"layers.*.mlp.experts.*.up_proj": "colwise",
"layers.*.mlp.experts.*.down_proj": "rowwise",
"layers.*.mlp.experts.gate_proj": "colwise",
"layers.*.mlp.experts.up_proj": "colwise",
"layers.*.mlp.experts.down_proj": "rowwise",
"layers.*.mlp.gate_proj": "colwise",
"layers.*.mlp.up_proj": "colwise",
"layers.*.mlp.down_proj": "rowwise",
@@ -168,7 +168,6 @@ class Qwen3MoeConfig(PretrainedConfig):
router_aux_loss_coef=0.001,
mlp_only_layers=None,
load_balance_coeff=None,
use_grouped_mm=True,
pad_token_id=None,
**kwargs,
):
@@ -202,7 +201,6 @@ class Qwen3MoeConfig(PretrainedConfig):
self.router_aux_loss_coef = router_aux_loss_coef
self.mlp_only_layers = [] if mlp_only_layers is None else mlp_only_layers
self.load_balance_coeff = load_balance_coeff
self.use_grouped_mm = use_grouped_mm
super().__init__(
tie_word_embeddings=tie_word_embeddings,
@@ -29,7 +29,7 @@ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tu
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
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 RotaryEmbedding, RotaryEmbeddingConfig
@@ -60,29 +60,30 @@ class Qwen3MoeDecoderLayer(GradientCheckpointingLayer):
moe_args = MoEArgs(
num_experts=config.num_experts,
num_shared_experts=0,
expert_type="gated",
activation=config.hidden_act,
score_func="softmax",
route_norm=config.norm_topk_prob,
route_scale=1.0,
score_before_experts=False,
top_k=config.num_experts_per_tok,
use_grouped_mm=config.use_grouped_mm,
load_balance_coeff=config.load_balance_coeff,
fp8=getattr(config, "fp8", False),
)
mlp_config = MLPConfig(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
gate_act=config.hidden_act,
bias=False,
)
if (layer_idx not in config.mlp_only_layers) and (
config.num_experts > 0 and (layer_idx + 1) % config.decoder_sparse_step == 0
):
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
self.mlp = MoE.from_args(
moe_args,
dim=config.hidden_size,
hidden_dim=config.moe_intermediate_size,
shared_expert=None,
)
else:
self.mlp = MLP(mlp_config)
self.mlp = FeedForward(
dim=config.hidden_size,
hidden_dim=config.intermediate_size,
activation=config.hidden_act,
)
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
@@ -139,7 +140,7 @@ class Qwen3MoePreTrainedModel(PreTrainedModelPrimeRL):
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
"""Check if the state dict contains MoE layers in PrimeRL training format."""
return any("mlp.experts.w1" in module_name for module_name in state_dict.keys())
return any("mlp.experts.gate_proj" in name for name in state_dict)
@classmethod
def conversion_chain(cls, config):
+119
View File
@@ -0,0 +1,119 @@
import importlib.util
import torch
from torch import nn
from torch.distributed.tensor.parallel import parallelize_module
from prime_rl.configs.trainer import (
BF16MoEComputeConfig,
DeepEPMoEDispatchConfig,
DeepGemmFP8MoEComputeConfig,
ModelConfig,
MoERuntimeConfig,
MXFP8MoEComputeConfig,
TorchMoEDispatchConfig,
)
from prime_rl.trainer.distributed.expert_parallel import ExpertWeightParallel
from prime_rl.trainer.distributed.token_dispatcher import (
LocalTokenDispatcher,
MXFP8TorchTokenDispatcher,
TorchTokenDispatcher,
)
from prime_rl.trainer.models.layers.grouped_gemm import (
BF16GroupedGemm,
DeepGemmFP8GroupedGemm,
GroupedGemm,
MXFP8GroupedGemm,
)
from prime_rl.trainer.models.layers.moe import MoE
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.utils.logger import get_logger
def _resolve_grouped_gemm(config: ModelConfig) -> GroupedGemm:
compute = config.moe.compute
if isinstance(compute, BF16MoEComputeConfig):
return BF16GroupedGemm()
if isinstance(compute, DeepGemmFP8MoEComputeConfig):
if importlib.util.find_spec("deep_gemm") is None:
raise RuntimeError("DeepGEMM FP8 expert compute requires the deep-gemm package.")
capability = torch.cuda.get_device_capability()
if capability < (9, 0):
raise RuntimeError(
f"DeepGEMM FP8 expert compute requires SM90 or newer, but this device is SM{capability[0]}{capability[1]}."
)
return DeepGemmFP8GroupedGemm()
if isinstance(compute, MXFP8MoEComputeConfig):
import prime_kernels
kernel = prime_kernels.load("mxfp8_moe")
return MXFP8GroupedGemm(
kernel=kernel,
high_precision_wgrad=compute.recipe == "mxfp8_rceil_wgrad_with_hp",
token_group_alignment=kernel.TOKEN_GROUP_ALIGNMENT,
)
raise TypeError(f"Unsupported MoE compute config: {type(compute).__name__}")
def configure_moe_runtime(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims) -> None:
moe_layers = [module for module in model.modules() if isinstance(module, MoE)]
if not moe_layers:
if config.moe != MoERuntimeConfig():
raise ValueError("A non-default model.moe runtime was configured, but the model has no custom MoE layers.")
return
grouped_gemm = _resolve_grouped_gemm(config)
ep_mesh = parallel_dims.get_mesh("ep") if parallel_dims.ep_enabled else None
dispatch = config.moe.dispatch
for moe in moe_layers:
if ep_mesh is not None and moe.experts.num_experts % parallel_dims.ep:
raise ValueError(
f"MoE expert count {moe.experts.num_experts} must be divisible by model.ep={parallel_dims.ep}."
)
moe.experts.set_grouped_gemm(grouped_gemm)
if ep_mesh is None:
token_dispatcher = LocalTokenDispatcher(
num_experts=moe.experts.num_experts,
top_k=moe.router.top_k,
token_group_alignment=grouped_gemm.token_group_alignment,
)
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(
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(),
)
elif isinstance(dispatch, DeepEPMoEDispatchConfig):
from prime_rl.trainer.distributed.deepep import DeepEPTokenDispatcher
token_dispatcher = DeepEPTokenDispatcher(
num_experts=moe.experts.num_experts,
token_group_alignment=grouped_gemm.token_group_alignment,
group=ep_mesh.get_group(),
num_sms=dispatch.num_sms,
token_chunk_size=dispatch.token_chunk_size,
)
else:
raise TypeError(f"Unsupported MoE dispatch config: {type(dispatch).__name__}")
moe.set_token_dispatcher(token_dispatcher)
if ep_mesh is not None:
parallelize_module(moe.experts, device_mesh=ep_mesh, parallelize_plan=ExpertWeightParallel())
get_logger().info(
f"Configured {len(moe_layers)} MoE layers with compute={config.moe.compute.type}, "
f"dispatch={config.moe.dispatch.type}, ep={parallel_dims.ep}"
)
-7
View File
@@ -313,13 +313,6 @@ def resolve_ep(config: ModelConfig) -> None:
config.ep = resolved_ep
get_logger().info(f"EP auto: world_size={world_size}, dp_replicate={dp_replicate} -> resolved ep={resolved_ep}")
if config.ep_comm_backend != "torch" and config.ep <= 1:
raise ValueError(
f"model.ep_comm_backend='{config.ep_comm_backend}' requires ep > 1, "
f"but auto-resolved ep=1 (world_size={world_size}). "
"Set ep explicitly or use ep_comm_backend='torch'."
)
def get_parallel_dims(config: ModelConfig, seq_len: int | None = None) -> ParallelDims:
assert isinstance(config.ep, int), (
+6 -65
View File
@@ -6,7 +6,7 @@ from beartype import beartype as typechecker
from jaxtyping import Bool, Float, Int, jaxtyped
from torch import Tensor
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, IPOLossConfig, LossConfig
from prime_rl.configs.trainer import CustomLossConfig, IPOLossConfig, LossConfig
from prime_rl.utils.utils import import_object
@@ -106,64 +106,9 @@ def compute_importance_ratio_and_mismatch_kl(
return log_importance_ratio, importance_ratio, mismatch_kl
def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossOutputs:
"""
DPPO+KL loss for RL training, combining:
- DPPO-Binary TV Loss (https://arxiv.org/pdf/2602.04879)
- Kimi-K2.5 KL Loss (https://arxiv.org/pdf/2602.02276)
The mask is conditioned on the advantage sign: for positive advantages,
we mask tokens whose probability increased too much (trust region violation
in the upweight direction); for negative advantages, we mask tokens whose
probability decreased too much (trust region violation in the downweight
direction).
"""
trainer_logprobs = inputs.trainer_logprobs
inference_logprobs = inputs.inference_logprobs
advantages = inputs.advantages
loss_mask = inputs.loss_mask
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
trainer_logprobs, inference_logprobs
)
probs_diff = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
dppo_invalid_mask_high = probs_diff > loss_config.dppo_mask_high
dppo_invalid_mask_low = probs_diff < -loss_config.dppo_mask_low
positive_advantages = advantages > 0
negative_advantages = advantages < 0
dppo_invalid_mask = torch.where(positive_advantages, dppo_invalid_mask_high, dppo_invalid_mask_low)
is_masked = dppo_invalid_mask
is_masked_high = positive_advantages & dppo_invalid_mask_high
is_masked_low = negative_advantages & dppo_invalid_mask_low
drop_mask = loss_mask & is_masked
keep_mask = loss_mask & ~is_masked
advantages = loss_config.adv_tau * advantages
pg_loss = keep_mask * advantages * importance_ratio
kl_loss = loss_mask * log_importance_ratio**2
per_token_loss = -pg_loss + loss_config.kl_tau * kl_loss
if inputs.loss_weights is not None:
per_token_loss = per_token_loss * inputs.loss_weights
loss = per_token_loss.sum()
metrics = {
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked), # all trainable, masked tokens
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask), # all trainable, unmasked tokens
"is_masked": _safe_mean(is_masked, loss_mask),
"is_masked_low": _safe_mean(is_masked_low, loss_mask),
"is_masked_high": _safe_mean(is_masked_high, loss_mask),
"masked_advantage_positive": _safe_mean(positive_advantages, drop_mask),
"masked_advantage_negative": _safe_mean(negative_advantages, drop_mask),
}
return LossOutputs(loss=loss, metrics=metrics)
def ipo_loss_fn(inputs: LossInputs, loss_config: IPOLossConfig) -> LossOutputs:
"""IPO loss type: a symmetric trust region (mask tokens whose probability
moved more than ``ipo_threshold`` in absolute terms), policy gradient via
moved more than ``eps`` in absolute terms), policy gradient via
the importance ratio, and a squared-log-ratio KL regularizer."""
trainer_logprobs = inputs.trainer_logprobs
inference_logprobs = inputs.inference_logprobs
@@ -176,7 +121,7 @@ def ipo_loss_fn(inputs: LossInputs, loss_config: IPOLossConfig) -> LossOutputs:
abs_probs_diff = torch.abs(torch.exp(trainer_logprobs) - torch.exp(inference_logprobs))
is_masked = abs_probs_diff > loss_config.ipo_threshold
is_masked = abs_probs_diff > loss_config.eps
keep_mask = loss_mask & ~is_masked
advantages = loss_config.adv_tau * advantages
@@ -261,8 +206,8 @@ def ce_loss_fn(inputs: LossInputs) -> LossOutputs:
def setup_rl_loss_fn(loss_config: LossConfig) -> LossFn:
"""Build the loss fn for the rl component from ``trainer.loss``:
``default_loss_fn`` (``DefaultLossConfig``), ``ipo_loss_fn``
(``IPOLossConfig``), or the imported function (``CustomLossConfig``).
``ipo_loss_fn`` (``IPOLossConfig``) or the imported function
(``CustomLossConfig``).
The ce / ref_kl loss types are fixed and unaffected by ``trainer.loss``."""
if isinstance(loss_config, CustomLossConfig):
custom_fn = import_object(loss_config.import_path)
@@ -270,14 +215,10 @@ def setup_rl_loss_fn(loss_config: LossConfig) -> LossFn:
def rl_fn(inputs: LossInputs) -> LossOutputs:
return custom_fn(inputs, **kwargs)
elif isinstance(loss_config, IPOLossConfig):
def rl_fn(inputs: LossInputs) -> LossOutputs:
return ipo_loss_fn(inputs, loss_config)
else:
def rl_fn(inputs: LossInputs) -> LossOutputs:
return default_loss_fn(inputs, loss_config)
return ipo_loss_fn(inputs, loss_config)
return rl_fn
+7 -11
View File
@@ -8,7 +8,7 @@ from typing import Any
import torch
from torch import Tensor
from prime_rl.configs.trainer import DefaultLossConfig, TrainerConfig
from prime_rl.configs.trainer import IPOLossConfig, TrainerConfig
from prime_rl.trainer.rl.loss import compute_importance_ratio_and_mismatch_kl
SCHEMA_VERSION = 1
@@ -181,7 +181,6 @@ def _compute_export_tensors(
inference_logprobs = micro_batch["inference_logprobs"].to(trainer_logprobs.device)
loss_mask = micro_batch["loss_mask"].to(trainer_logprobs.device)
advantages = micro_batch["advantages"].to(trainer_logprobs.device)
with torch.no_grad():
log_ratio, ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(trainer_logprobs, inference_logprobs)
prob_delta = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
@@ -189,15 +188,12 @@ def _compute_export_tensors(
fields["importance_ratio"] = ratio
fields["mismatch_kl"] = mismatch_kl
fields["prob_delta"] = prob_delta
if isinstance(loss_config, DefaultLossConfig):
invalid_high = prob_delta > loss_config.dppo_mask_high
invalid_low = prob_delta < -loss_config.dppo_mask_low
positive_advantages = advantages > 0
negative_advantages = advantages < 0
invalid = torch.where(positive_advantages, invalid_high, invalid_low)
fields["is_masked"] = loss_mask & invalid
fields["is_masked_high"] = loss_mask & positive_advantages & invalid_high
fields["is_masked_low"] = loss_mask & negative_advantages & invalid_low
if isinstance(loss_config, IPOLossConfig):
invalid_high = prob_delta > loss_config.eps
invalid_low = prob_delta < -loss_config.eps
fields["is_masked"] = loss_mask & (invalid_high | invalid_low)
fields["is_masked_high"] = loss_mask & invalid_high
fields["is_masked_low"] = loss_mask & invalid_low
return fields
+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))
-4
View File
@@ -293,10 +293,6 @@ def filter_rl_trainer_tensor_stats_for_wandb(metrics: dict[str, float | int]) ->
skip_prefixes = ("trainer_probs/", "inference_probs/")
mean_max_only_prefixes = (
"is_masked/",
"is_masked_low/",
"is_masked_high/",
"masked_advantage_positive/",
"masked_advantage_negative/",
"mismatch_kl/",
"masked_mismatch_kl/",
"unmasked_mismatch_kl/",
+133 -17
View File
@@ -5,6 +5,8 @@ from __future__ import annotations
import os
import socket
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Sequence
from torch import Tensor
@@ -12,6 +14,23 @@ from torch import Tensor
MemDesc = tuple[int, int, int]
@dataclass(slots=True)
class PreparedRead:
"""Reusable READ request with descriptor lists kept alive for its lifetime."""
local_descriptors: Any
remote_descriptors: Any
handle: Any
def group_notification(group_index: int, generation: int) -> str:
return f"{group_index:08x}:{generation:016x}"
def policy_notification(step: int, event: str) -> str:
return f"policy:{step:016x}:{event}"
class NixlAgent:
def __init__(self, name: str) -> None:
try:
@@ -21,6 +40,7 @@ class NixlAgent:
self.name = name
self._agent = nixl_agent(name, nixl_agent_config(backends=["UCX"]))
self._notifications: dict[str, list[bytes]] = {}
def register_tensor(self, tensor: Tensor) -> None:
self._agent.register_memory(tensor, backends=["UCX"])
@@ -28,21 +48,24 @@ class NixlAgent:
def get_metadata(self) -> bytes:
return self._agent.get_agent_metadata()
def add_remote_agent(self, metadata: bytes) -> str:
return self._agent.add_remote_agent(metadata)
def add_remote_agent(self, metadata: bytes) -> NixlPeer:
return NixlPeer(
local_agent=self,
remote_agent_name=self._agent.add_remote_agent(metadata).decode(),
)
def make_connection(self, peer_name: str) -> None:
self._agent.make_connection(peer_name)
def make_connection(self, peer: NixlPeer) -> None:
self._agent.make_connection(peer.remote_agent_name)
def prepare_xfer_dlist(self, descs: Sequence[MemDesc], agent_name: str | None = None) -> Any:
def prepare_xfer_dlist(self, descs: Sequence[MemDesc], peer: NixlPeer | None = None) -> Any:
return self._agent.prep_xfer_dlist(
agent_name=agent_name or "",
agent_name=peer.remote_agent_name if peer is not None else "",
xfer_list=list(descs),
mem_type="cuda",
mem_type="VRAM",
backends=["UCX"],
)
def post_read(self, local: Any, indices: Sequence[int], remote: Any) -> Any:
def prepare_read(self, local: Any, indices: Sequence[int], remote: Any) -> PreparedRead:
handle = self._agent.make_prepped_xfer(
operation="READ",
local_xfer_side=local,
@@ -51,14 +74,49 @@ class NixlAgent:
remote_indices=list(indices),
backends=["UCX"],
)
state = self._agent.transfer(handle)
return PreparedRead(
local_descriptors=local,
remote_descriptors=remote,
handle=handle,
)
def post_read(self, read: PreparedRead, notification: str) -> None:
state = self._agent.transfer(read.handle, notification.encode())
if state in ("ERR", "ERROR", "FAIL"):
raise RuntimeError(f"NIXL READ post failed with state {state}")
return handle
def send_notification(self, peer: NixlPeer, notification: str) -> None:
self._agent.send_notif(peer.remote_agent_name, notification)
def wait_for_notification(
self,
peers: Sequence[NixlPeer],
notification: str,
*,
timeout: float,
cancelled: Callable[[], bool] | None = None,
) -> None:
pending = {peer.remote_agent_name for peer in peers}
encoded_notification = notification.encode()
deadline = time.monotonic() + timeout
while pending:
if cancelled is not None and cancelled():
raise RuntimeError("NIXL notification wait cancelled")
for sender, messages in self._agent.get_new_notifs(backends=["UCX"]).items():
self._notifications.setdefault(sender, []).extend(messages)
for sender in list(pending):
messages = self._notifications.get(sender, [])
if encoded_notification in messages:
messages.remove(encoded_notification)
pending.remove(sender)
if pending and time.monotonic() >= deadline:
raise TimeoutError(f"NIXL notification wait timed out after {timeout}s, missing={sorted(pending)}")
if pending:
time.sleep(0.0005)
def wait(
self,
handle: Any,
read: PreparedRead,
context: str = "",
timeout: float | None = None,
cancelled: Callable[[], bool] | None = None,
@@ -66,26 +124,84 @@ class NixlAgent:
deadline = None if timeout is None else time.monotonic() + timeout
while True:
if cancelled is not None and cancelled():
self._agent.release_xfer_handle(handle)
self._agent.release_xfer_handle(read.handle)
raise RuntimeError(f"NIXL transfer cancelled, context={context!r}")
state = self._agent.check_xfer_state(handle)
state = self._agent.check_xfer_state(read.handle)
if state in ("DONE", "SUCCESS"):
self._agent.release_xfer_handle(handle)
return
if state in ("ERR", "ERROR", "FAIL"):
self._agent.release_xfer_handle(handle)
self._agent.release_xfer_handle(read.handle)
raise RuntimeError(f"NIXL transfer failed with state={state}, context={context!r}")
if deadline is not None and time.monotonic() >= deadline:
self._agent.release_xfer_handle(handle)
self._agent.release_xfer_handle(read.handle)
raise TimeoutError(f"NIXL transfer timed out after {timeout}s, context={context!r}")
time.sleep(0.0005)
@dataclass(frozen=True, slots=True)
class NixlPeer:
local_agent: NixlAgent
remote_agent_name: str
def make_agent_name(role: str, global_rank: int) -> str:
return f"{role}-{socket.gethostname()}-r{global_rank}"
def set_ucx_env_defaults() -> None:
def set_ucx_env_defaults(device_index: int) -> None:
if "UCX_NET_DEVICES" not in os.environ:
import pynvml
visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES")
visible_device = str(device_index)
if visible_devices:
visible_device = visible_devices.split(",")[device_index].strip()
pynvml.nvmlInit()
try:
if visible_device.isdecimal():
handle = pynvml.nvmlDeviceGetHandleByIndex(int(visible_device))
elif visible_device.startswith("GPU-"):
handle = pynvml.nvmlDeviceGetHandleByUUID(visible_device.encode())
else:
raise RuntimeError(f"Unsupported CUDA_VISIBLE_DEVICES entry for NIXL: {visible_device}")
bus_id = pynvml.nvmlDeviceGetPciInfo(handle).busId
finally:
pynvml.nvmlShutdown()
if isinstance(bus_id, bytes):
bus_id = bus_id.decode()
domain, bus, device = bus_id.rsplit(":", 2)
gpu_path = Path("/sys/bus/pci/devices") / f"{int(domain, 16):04x}:{bus.lower()}:{device.lower()}"
if not gpu_path.exists():
raise RuntimeError(f"GPU PCI device is missing from sysfs: {gpu_path}")
rdma_ports: list[tuple[str, Path]] = []
for hca_path in sorted(Path("/sys/class/infiniband").glob("*")):
for port_path in sorted((hca_path / "ports").glob("*")):
if (port_path / "link_layer").read_text().strip() != "InfiniBand":
continue
if "ACTIVE" not in (port_path / "state").read_text():
continue
rdma_ports.append((f"{hca_path.name}:{port_path.name}", (hca_path / "device").resolve()))
if not rdma_ports:
raise RuntimeError("NIXL requires an active InfiniBand port")
gpu_parts = gpu_path.resolve().parts
ports_by_distance: list[tuple[int, str]] = []
for port, device_path in rdma_ports:
device_parts = device_path.parts
common_parts = 0
for gpu_part, device_part in zip(gpu_parts, device_parts):
if gpu_part != device_part:
break
common_parts += 1
distance = len(gpu_parts) + len(device_parts) - 2 * common_parts
ports_by_distance.append((distance, port))
os.environ["UCX_NET_DEVICES"] = min(ports_by_distance)[1]
os.environ.setdefault("UCX_MAX_RNDV_RAILS", "1")
os.environ.setdefault("UCX_MAX_RMA_RAILS", "1")
os.environ.setdefault("UCX_TLS", "rc_x,rc,dc_x,dc,cuda_copy")
os.environ.setdefault("UCX_IB_GPU_DIRECT_RDMA", "y")
os.environ.setdefault("UCX_RNDV_SCHEME", "get_zcopy")
@@ -1,4 +1,4 @@
"""CUDA memory sizing and a cudaMalloc-backed pool for NIXL arenas."""
"""cudaMalloc-backed pool for NIXL arenas."""
from __future__ import annotations
@@ -19,17 +19,6 @@ _pool: torch.cuda.MemPool | None = None
_allocator: torch.cuda.memory.CUDAPluggableAllocator | None = None
def size_cuda_buffers(
buffer_bytes: int,
max_buffers: int,
device: torch.device,
extra_headroom_bytes: int,
) -> int:
free_bytes, total_bytes = torch.cuda.mem_get_info(device)
headroom_bytes = max(4 * 1024**3, int(total_bytes * 0.02)) + extra_headroom_bytes
return max(1, min(max_buffers, (free_bytes - headroom_bytes) // buffer_bytes))
def _get_pool() -> torch.cuda.MemPool:
global _pool, _allocator
if _pool is not None:
@@ -1,15 +1,10 @@
"""Role-scoped synchronization over ModelExpress.
The policy session coordinates a complete weight update with the orchestrator.
A separate layer session uses the same READY/INITIALIZING handshake to keep a
bounded transfer arena live until every inference worker has acknowledged it.
"""
"""ModelExpress startup discovery for NIXL peers."""
from __future__ import annotations
import time
from collections.abc import Callable
from dataclasses import dataclass, field
from dataclasses import dataclass
from typing import Any, Literal
import grpc
@@ -26,13 +21,6 @@ class ModelExpressSession:
rank: int
session_id: str
worker_id: str
_source_id: str | None = field(init=False, default=None, repr=False)
@property
def source_id(self) -> str:
if self._source_id is None:
raise RuntimeError("ModelExpress metadata must be published before updating status")
return self._source_id
def identity(self, role: Role) -> p2p_pb2.SourceIdentity:
return p2p_pb2.SourceIdentity(
@@ -65,28 +53,23 @@ class ModelExpressSession:
worker_rank=self.rank,
nixl_metadata=nixl_metadata,
)
self._source_id = self._rpc(
lambda: self.client.publish_metadata(self.identity(self.role), worker, self.worker_id)
return self._rpc(
lambda: self.client.publish_metadata(
self.identity(self.role),
worker,
self.worker_id,
)
)
return self._source_id
def set_status(self, status: int) -> None:
if not self._rpc(lambda: self.client.update_status(self.source_id, self.worker_id, self.rank, status)):
raise RuntimeError(f"failed to set ModelExpress status {status} for {self.role} rank {self.rank}")
def list_sources(self, role: Role, status: int | None) -> list[p2p_pb2.SourceInstanceRef]:
response = self._rpc(lambda: self.client.list_sources(self.identity(role), status_filter=status))
def list_sources(self, role: Role) -> list[p2p_pb2.SourceInstanceRef]:
response = self._rpc(lambda: self.client.list_sources(self.identity(role)))
return list(response.instances)
def exists_role_with_status(self, role: Role, status: int) -> bool:
return bool(self.list_sources(role, status))
def wait_for(
self,
role: Role,
*,
count: int,
status: int | None,
timeout: float,
poll_interval: float = 0.05,
cancelled: Callable[[], bool] | None = None,
@@ -96,14 +79,14 @@ class ModelExpressSession:
while True:
if cancelled is not None and cancelled():
raise RuntimeError(f"cancelled waiting for {count} {role} worker(s) in session {self.session_id!r}")
refs = self.list_sources(role, status)
refs = self.list_sources(role)
by_rank = {ref.worker_rank: ref for ref in refs}
if expected_ranks.issubset(by_rank):
return [by_rank[rank] for rank in range(count)]
if time.monotonic() >= deadline:
raise TimeoutError(
f"timed out waiting for {count} {role} worker(s) in session {self.session_id!r} "
f"with status={status}; found ranks={sorted(by_rank)}"
f"with ranks={sorted(by_rank)}"
)
time.sleep(poll_interval)
+94 -110
View File
@@ -15,7 +15,6 @@ from typing import cast
import torch
import torch.distributed as dist
import torch.nn as nn
from modelexpress import p2p_pb2
from modelexpress.client import MxClient
from torch.distributed.tensor import DTensor
from torch.distributed.tensor._utils import compute_local_shape_and_global_offset
@@ -25,11 +24,15 @@ from prime_rl.orchestrator.clients import init_nixl_broadcast, update_weights
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.transports.weights.base import WeightReceiver, WeightSender
from prime_rl.transports.weights.nixl.agent import NixlAgent, make_agent_name, set_ucx_env_defaults
from prime_rl.transports.weights.nixl.cuda_malloc_memory import (
size_cuda_buffers,
use_cuda_malloc_pool,
from prime_rl.transports.weights.nixl.agent import (
NixlAgent,
NixlPeer,
group_notification,
make_agent_name,
policy_notification,
set_ucx_env_defaults,
)
from prime_rl.transports.weights.nixl.cuda_malloc_memory import use_cuda_malloc_pool
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
from prime_rl.transports.weights.nixl.trainer_tensor_table import (
TrainerAgent,
@@ -40,8 +43,6 @@ from prime_rl.transports.weights.nixl.trainer_tensor_table import (
)
LAYER_RE = re.compile(r"(?:^|\.)layers\.(\d+)(?=\.|$)")
BUFFER_POLL_INTERVAL = 0.01
MAX_STAGING_BUFFER_COUNT = 8
@dataclass
@@ -79,7 +80,7 @@ class NIXLWeightSender(WeightSender):
self.config = config
self.parallel_dims = parallel_dims
if self.is_serving_rank:
set_ucx_env_defaults()
set_ucx_env_defaults(torch.cuda.current_device())
self.nixl_agent = NixlAgent(make_agent_name("trainer", self.world.rank))
self.initialized = False
self.transfer_group_names: list[str] = []
@@ -87,8 +88,10 @@ class NIXLWeightSender(WeightSender):
self.staged_shards_by_group: dict[int, list[StagedTensorShard]] = {}
self.staging_arenas: dict[torch.dtype, torch.Tensor] = {}
self.staging_buffer_count: int
self.model_express: ModelExpressSession | None = None
self.buffer_sessions: list[ModelExpressSession] = []
self.inference_peers: list[NixlPeer]
self.orchestrator_peer: NixlPeer
self.group_generations: list[int]
self.broadcast_count = 0
@property
def is_serving_rank(self) -> bool:
@@ -184,31 +187,6 @@ class NIXLWeightSender(WeightSender):
)
return local_shards
def choose_staging_buffer_count(self, largest_group_bytes: int) -> int:
local_buffer_count = min(len(self.transfer_group_names), MAX_STAGING_BUFFER_COUNT)
if self.is_serving_rank and largest_group_bytes:
device = self.staged_shards[0].source_tensor.device
allocated_bytes = torch.cuda.memory_allocated()
peak_growth_bytes = max(0, torch.cuda.max_memory_allocated() - allocated_bytes)
free_bytes, _ = torch.cuda.mem_get_info(device)
max_buffers = local_buffer_count if peak_growth_bytes else 1
if peak_growth_bytes or free_bytes < largest_group_bytes:
torch.cuda.empty_cache()
local_buffer_count = size_cuda_buffers(
largest_group_bytes,
max_buffers,
device,
extra_headroom_bytes=peak_growth_bytes,
)
staging_buffer_count = torch.tensor(
local_buffer_count,
dtype=torch.int64,
device=torch.device("cuda", torch.cuda.current_device()),
)
dist.all_reduce(staging_buffer_count, op=dist.ReduceOp.MIN)
return int(staging_buffer_count.item())
def allocate_staging_arenas(self, largest_group_elements: dict[torch.dtype, int]) -> None:
if not self.is_serving_rank or not any(largest_group_elements.values()):
return
@@ -248,8 +226,10 @@ class NIXLWeightSender(WeightSender):
for shard in self.staged_shards:
group_elements[shard.wire_dtype][shard.group_index] += shard.source_tensor.numel()
largest_group_elements = {dtype: max(elements, default=0) for dtype, elements in group_elements.items()}
largest_group_bytes = sum(elements * dtype.itemsize for dtype, elements in largest_group_elements.items())
self.staging_buffer_count = self.choose_staging_buffer_count(largest_group_bytes)
self.staging_buffer_count = min(
len(self.transfer_group_names),
2 if self.config.overlap_transfer_and_replay else 1,
)
self.allocate_staging_arenas(largest_group_elements)
grouped: dict[int, list[StagedTensorShard]] = defaultdict(list)
@@ -363,18 +343,6 @@ class NIXLWeightSender(WeightSender):
table = self.merge_trainer_table_fragments(table_fragments)
server_url = f"{self.config.host}:{self.config.port}"
client = MxClient(server_url=server_url)
self.buffer_sessions = []
for buffer_index in range(self.staging_buffer_count):
session = ModelExpressSession(
client=client,
role="trainer",
rank=0,
session_id=f"{self.config.session_id}:layers:{buffer_index}",
worker_id=f"trainer-buffer-{buffer_index}",
)
session.publish()
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
self.buffer_sessions.append(session)
self.model_express = ModelExpressSession(
client=client,
role="trainer",
@@ -383,7 +351,6 @@ class NIXLWeightSender(WeightSender):
worker_id="trainer-table",
)
self.model_express.publish(nixl_metadata=table.encode())
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
tensor_count = sum(len(group.tensors) for group in table.groups)
self.logger.info(
f"Published {tensor_count} trainer tensors in {len(table.groups)} groups "
@@ -391,59 +358,75 @@ class NIXLWeightSender(WeightSender):
)
self.initialized = True
def finish_staging_buffer_transfer(self, buffer_index: int) -> None:
if self.world.is_master:
session = self.buffer_sessions[buffer_index]
session.wait_for(
"inference",
count=self.config.inference_world_size,
status=p2p_pb2.SOURCE_STATUS_READY,
timeout=self.config.timeout,
poll_interval=BUFFER_POLL_INTERVAL,
)
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
session.wait_for(
"inference",
count=self.config.inference_world_size,
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
timeout=self.config.timeout,
poll_interval=BUFFER_POLL_INTERVAL,
)
dist.barrier()
def finish_transfer_group(self, group_index: int) -> None:
if not self.is_serving_rank:
return
notification = group_notification(group_index, self.group_generations[group_index])
self.nixl_agent.wait_for_notification(
self.inference_peers,
notification,
timeout=self.config.timeout,
)
self.group_generations[group_index] += 1
@torch.no_grad()
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
self.initialize_transfer(model)
start = time.perf_counter()
if self.world.is_master:
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_READY)
self.model_express.wait_for(
startup = self.broadcast_count == 0
if self.world.is_master and startup:
orchestrator_ref = self.model_express.wait_for(
"orchestrator",
count=1,
status=p2p_pb2.SOURCE_STATUS_READY,
timeout=self.config.timeout,
)
self.model_express.wait_for(
)[0]
inference_refs = self.model_express.wait_for(
"inference",
count=self.config.inference_world_size,
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
timeout=self.config.timeout,
)
inference_metadata: list[bytes] | None = [
self.model_express.fetch(ref).nixl_metadata for ref in inference_refs
]
orchestrator_metadata = self.model_express.fetch(orchestrator_ref).nixl_metadata
else:
inference_metadata = None
if startup:
objects = [inference_metadata]
dist.broadcast_object_list(objects, src=0)
if self.is_serving_rank:
self.inference_peers = []
for metadata in cast(list[bytes], objects[0]):
peer = self.nixl_agent.add_remote_agent(metadata)
self.nixl_agent.make_connection(peer)
self.inference_peers.append(peer)
self.group_generations = [0] * len(self.transfer_group_names)
if self.world.is_master:
self.orchestrator_peer = self.nixl_agent.add_remote_agent(orchestrator_metadata)
self.nixl_agent.make_connection(self.orchestrator_peer)
if self.world.is_master:
self.nixl_agent.send_notification(
self.orchestrator_peer,
policy_notification(step, "ready"),
)
for group, group_name in enumerate(self.transfer_group_names):
group_start = time.perf_counter()
buffer_index = group % self.staging_buffer_count
if group >= self.staging_buffer_count:
self.finish_staging_buffer_transfer(buffer_index)
self.finish_transfer_group(group - self.staging_buffer_count)
if self.is_serving_rank:
for shard in self.staged_shards_by_group.get(group, ()):
shard.copy_to_staging()
torch.cuda.synchronize()
dist.barrier()
notification = group_notification(group, self.group_generations[group])
for peer in self.inference_peers:
self.nixl_agent.send_notification(peer, notification)
if self.world.is_master:
self.buffer_sessions[buffer_index].set_status(p2p_pb2.SOURCE_STATUS_READY)
self.logger.debug(
f"NIXL+ModelExpress policy v{step} group {group_name} staged in buffer {buffer_index} in "
f"{time.perf_counter() - group_start:.2f}s"
@@ -451,35 +434,28 @@ class NIXLWeightSender(WeightSender):
first_pending_group = max(0, len(self.transfer_group_names) - self.staging_buffer_count)
for group in range(first_pending_group, len(self.transfer_group_names)):
buffer_index = group % self.staging_buffer_count
self.finish_staging_buffer_transfer(buffer_index)
self.finish_transfer_group(group)
if self.world.is_master:
self.model_express.wait_for(
"inference",
count=self.config.inference_world_size,
status=p2p_pb2.SOURCE_STATUS_READY,
self.nixl_agent.wait_for_notification(
[self.orchestrator_peer],
policy_notification(step, "complete"),
timeout=self.config.timeout,
)
self.model_express.wait_for(
"orchestrator",
count=1,
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
timeout=self.config.timeout,
)
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
dist.barrier()
self.broadcast_count += 1
self.logger.info(f"NIXL+ModelExpress policy v{step} synchronized in {time.perf_counter() - start:.2f}s")
class NIXLWeightReceiver(WeightReceiver):
"""Drives the orchestrator's side of the ModelExpress rendezvous. Version
discovery runs on the shared sentinels; the unversioned ModelExpress
statuses only choreograph the transfer itself."""
"""Drives NIXL discovery and policy synchronization for the orchestrator."""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.session = ModelExpressSession(
set_ucx_env_defaults(0)
self.nixl_agent = NixlAgent(make_agent_name("orchestrator", 0))
self.trainer_peer: NixlPeer | None = None
self.model_express = ModelExpressSession(
client=MxClient(server_url=f"{self.config.host}:{self.config.port}"),
role="orchestrator",
rank=0,
@@ -496,23 +472,31 @@ class NIXLWeightReceiver(WeightReceiver):
self.config.inference_world_size,
self.config.session_id,
)
self.session.publish()
await self.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
async def set_status(self, status: int) -> None:
await asyncio.to_thread(self.session.set_status, status)
self.model_express.publish(nixl_metadata=self.nixl_agent.get_metadata())
async def receive(self, step: int) -> None:
# ACK the trainer (it waits for the orchestrator's READY before the
# engines' INITIALIZING), run the transfer, then close the cycle.
self._ack(step)
await self.set_status(p2p_pb2.SOURCE_STATUS_READY)
await update_weights(self.admin_clients, None, step=step)
await self.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
if self.trainer_peer is None:
trainer_refs = await asyncio.to_thread(
self.model_express.wait_for,
"trainer",
count=1,
timeout=self.config.timeout,
)
trainer_worker = await asyncio.to_thread(self.model_express.fetch, trainer_refs[0])
trainer_table = TrainerTensorTable.decode(trainer_worker.nixl_metadata)
self.trainer_peer = self.nixl_agent.add_remote_agent(trainer_table.agents[0].metadata)
self.nixl_agent.make_connection(self.trainer_peer)
trainer_peer = self.trainer_peer
await asyncio.to_thread(
self.session.wait_for,
"trainer",
count=1,
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
self.nixl_agent.wait_for_notification,
[trainer_peer],
policy_notification(step, "ready"),
timeout=self.config.timeout,
)
await update_weights(self.admin_clients, None, step=step)
self.nixl_agent.send_notification(
trainer_peer,
policy_notification(step, "complete"),
)

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