Compare commits

...
Author SHA1 Message Date
samsjaandGitHub cac463e795 feat: use FA3 as default, rename fa4 to flash_attention_4, remove eager (#3057)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: use FA3 as default, rename fa4 to flash_attention_4, remove eager

Three changes:

1. Default attention implementation changed from flash_attention_2 to flash_attention_3.
2. Renamed internal 'fa4' alias to 'flash_attention_4' everywhere for consistency.
   The _ATTN_ALIASES mapping and _normalize_attn_alias validator are removed since
   flash_attention_4 is now the canonical name. The _register_fa4_attention_interface
   noop is also removed since transformers already registers flash_attention_4 in
   AttentionInterface._global_mapping.
3. Removed 'eager' from AttnImplementation Literal. GPT-OSS non-Hopper fallback
   updated to suggest 'sdpa' instead of 'eager'.

* fix: allow impl='auto' with FA3/FA4 + CP, fix ruff format

- Update CP+FA3/FA4 validator to also accept impl='auto' (which resolves
  to 'custom' at runtime for supported models). This fixes the config
  test for rl_qwen3_30b_a3b.toml which uses cp=2 with the new FA3 default.
- Apply ruff format to qwen3_5 and qwen3_5_moe model files (multi-line
  tuple formatting for long in-check).

* feat: remove sdpa and eager attention support

Remove 'sdpa' and 'eager' from AttnImplementation. Only flash_attention_2,
flash_attention_3, and flash_attention_4 are now supported.

Changes:
- Remove 'sdpa' from AttnImplementation Literal in trainer config
- Remove SDPAAttention class from layers/attn.py
- Remove all SDPA attention classes from custom models (AfmoeSDPAAttention,
  LagunaSDPAAttention, Qwen3_5MoeGatedSDPAAttention, Qwen3_5GatedSDPAAttention)
- Remove 'sdpa' entries from all ATTN_IMPL2CLASS dispatch dicts
- Remove eager->sdpa fallback logic in afmoe, laguna, qwen3_5_moe
- Set _supports_sdpa = False on all custom model configs
- Remove GPT-OSS non-Hopper SDPA fallback (now errors on non-Hopper)
- Update normalize_qwen3_5_attn_implementation to drop eager alias
- Update default attn_impl in qwen3_5/qwen3_5_moe _check_and_adjust
- Update configs and tests to use flash_attention_2 instead of sdpa
- Mark test_qwen3_5_dense_matches_hf_state_keys_on_meta as GPU test
  (HF model validates flash attn availability at init, requires GPU)

* fix: accept impl='auto' for flash_attention_4 validator

Same pattern as the CP+FA3/FA4 validator fix: 'auto' resolves to 'custom'
at runtime for supported models, so it should be accepted at config validation
time. Also improve error message to match.

* fix: bypass flash attention availability check for custom models

Override _check_and_adjust_attn_implementation on PreTrainedModelPrimeRL
to skip transformers' flash attention package/device validation.

This restores the behavior of the old _register_fa4_attention_interface()
noop that was removed when fa4 was renamed to flash_attention_4. Without
this override, instantiating a custom model with _from_config fails on
machines where flash_attn_3 or flash_attn_cute is not installed, because
transformers recognizes flash_attention_3/4 as flash attention and tries
to validate availability before our own ATTN_IMPL2CLASS dispatch runs.

Custom models use their own attention dispatch (ATTN_IMPL2CLASS) and never
call transformers' ALL_ATTENTION_FUNCTIONS, so the availability check is
unnecessary. qwen3_5 and qwen3_5_moe already override this method with
their own validation; those overrides take precedence via MRO.
2026-07-16 22:33:03 -07:00
e0d60e4d85 refactor(sft): unify the loss path with the RL trainer (#3044)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* refactor(sft): unify the loss path with the RL trainer

Remove loss_impl (torch / liger / liger_fused / quack_fused) and route SFT
through the same chunked LM head the RL trainer uses:

- fused_lm_head_token_chunk_size (int, default 1024) selects FusedOutputLinear;
  per-token cross-entropy is the negative target logprob computed in token
  chunks — full [N, V] logits are never materialized. "disabled" falls back to
  the vanilla logits + CrossEntropyLoss path.
- The same [model] block now behaves identically across SFT and RL, and SFT
  drops the ~17 GB logits tax that loss_impl="torch" carried at long context.
- Delete the liger/quack fused-CE heads, the fused_cross_entropy plumbing in
  setup_model/inject_prime_lm_head, the SFT validator that force-disabled
  chunking, and the liger-kernel dependency.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: relock without liger-kernel

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: restore _online_logsumexp_and_weighted_update

The fused-CE class removal also swallowed this helper (defined between the
deleted classes) which the chunked logprob head uses at runtime.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* style: ruff

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-16 21:50:49 -07:00
d7bcd1b1f5 Add MXFP8 Support (#2910)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* Add MXFP8 Linear Layer

* Add MXFP8 Receipe

* Add MXFP8

* Refractor, remove constants, cleanup

* Remove import from local path

* Reformat

* Add MXFP8 expert parallel impl to support TorchAO's MXTensor in backward for all2all in MXFP8

* Build torchao from source for py3.12 MXFP8 CUDA kernel

Pin torchao to the pytorch/ao git source (rev 02105d4) and build its CUDA
kernels from source against the local torch cu128 / cpython-3.12. The PyPI
wheel ships the MXFP8 kernel as a cpython-310-only .so that fails to load on
prime-rl's Python 3.12, so torchao::mxfp8_quantize was never registered with a
CUDA backend and MXFP8 died in backward. Building from source produces a
cpython-312 extension (_C_mxfp8.cpython-312-*.so).

- no-build-isolation-package += torchao (build against local torch)
- extra-build-variables: CUDA_HOME=/usr/local/cuda-12.8,
  TORCH_CUDA_ARCH_LIST=10.0a (B200/sm_100a), USE_CPP=1

Enables the MXFP8 all-to-all and dense-linear paths (verified on 8xB200).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Relax torchao MXFP8 grouped-GEMM torch-nightly gate

torchao's _get_tensor_cls_for_config (added in pytorch/ao#4141, "require torch
nightly and cuda 12.8+", Mar 2026) asserts two post-2.11.0 DTensor symbols
(_ops.scaled_mm_single_dim_strategy, _dispatch.is_pinned_handler) exist, else
raises "install the latest torch nightly". This blanket-blocks all MXFP8 training,
but is over-broad for us: prime-rl's EP path pulls expert weights local
(.to_local()) before the grouped GEMM, so the DTensor scaled-mm strategy is never
hit, and current torch's non-single-dim scaled_mm_strategy covers the rest.

Neutralize just that assert (MXFP8 branch only) before quantize_, so
enable_grouped_gemm works on our pinned torch 2.11 without a nightly bump.

Verified 8xB200 SFT (GLM-0.5B, ep=8, grouped_gemm + a2a): 8/8 steps, all ranks;
numerics vs bf16 within mxfp8 range (out ~4.8%, grads ~6-7%) for both
mxfp8_rceil and mxfp8_rceil_wgrad_with_hp recipes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Use prebuilt torchao wheel from v0.6.0 release (x86_64)

Replace the torchao build-from-source git dependency with the prebuilt
cp312 CUDA wheel hosted on the prime-rl v0.6.0 release, matching how
deep-ep / deep-gemm / nixl-cu12 are shipped. Avoids requiring the CUDA
toolchain at install time on x86_64.

- torchao source -> release wheel URL, scoped to platform_machine == 'x86_64'
  (aarch64 continues to resolve torchao from the default index, untouched)
- drop torchao from no-build-isolation-package + the extra-build-variables block
- add torchao to the exclude-newer-package trusted-sources list

Wheel is H100 (sm90a) + B200 (sm100a), built from pytorch/ao@02105d4,
verified in a fresh py3.12 env (mxfp8 op registers, a2a imports).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Sort imports in expert_parallel.py (ruff I001)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Fix comments

* Fix alignment of 32 for grouped gemm backward

* Apply Samis Suggestions

* Add back default ignore patterns

* Fix name bug

* Reformat with ruff

* Config verifier

* Fix kernel redirect for > 32 token groups

* Ruff reformat

* chore: update uv.lock for torchao dependency

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* style: fix import sorting in MXFP8 files

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Move config check to config code

* Fix ruff

* Move config check to trainer

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 01:26:22 +02:00
minh hoangandGitHub 4d8df5120e chore(ci): remove ghcr-publish environment approval gate (#3059)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The build job in build_image.yaml opted into the ghcr-publish
environment solely for its required-reviewers protection rule, which
paused every ghcr build (release + .dev-tag dispatch on merge to main)
pending manual approval. The environment held no scoped secrets or
variables, so it provided nothing functional. The job already has
packages: write and authenticates via GITHUB_TOKEN, and ref
restrictions are enforced in the prepare job, so ghcr builds now
publish automatically.
2026-07-16 15:55:06 -07:00
6b1604380c feat(inference): uint16 routed-experts payload for >256-expert models (#3051)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(inference): uint16 routed-experts payload for >256-expert models

serialize_routed_experts packed expert indices as uint8, which overflows for
models with >256 experts — NemotronH Super/Ultra route top-22 over 512
experts, so every /generate call with routed-experts capture 500'd
(assert array.max() <= iinfo(uint8).max), stalling router-replay training.

Make the payload self-describing: pick uint8 when indices fit, uint16
otherwise, and emit the chosen dtype in the payload. Consumers default to
uint8 when the field is absent, so payloads from <=256-expert models are
byte-identical to before. Decoder half: verifiers feat/routed-experts-dtype
(must land first and be pinned here before a >256-expert model enables
enable_return_routed_experts).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(trainer): dtype-agnostic routed-experts row size

The batch packer sized routed-experts rows via a hardcoded
dtype->itemsize table that lacked uint16 (KeyError on the first >256-expert
batch). Use np.dtype(...).itemsize instead of maintaining the table.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers to main (dtype-aware routed-experts decode)

PrimeIntellect-ai/verifiers#2043 merged — the decoder half of the
self-describing routed-experts payload. This pin makes the pair complete:
uint16 payloads from this branch's encoder are decoded correctly.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: relock for the verifiers bump

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-16 11:47:20 -07:00
Mika SenghaasandGitHub 013a7f8c25 Revert "chore: remove fsdp_cpu_offload (#3049)" (#3052)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
This reverts commit c9acaa3c90.
2026-07-16 11:32:26 -07:00
samsjaandGitHub 3ff7902a73 fix(docker): bake optional dependencies into CUDA image (#3053)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-16 11:21:34 -07:00
c9acaa3c90 chore: remove fsdp_cpu_offload (#3049)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: remove fsdp_cpu_offload

The knob was effectively unusable: it breaks NCCL weight broadcast in RL
(state-dict tensors stay on CPU and the communicator asserts), muon rejects
it, it is mutually exclusive with optim_cpu_offload, and no config in the
repo uses it. Remove the field and all wiring instead of patching around it:
FSDP CPUOffloadPolicy selection, the buffer-migration helper, the gloo
backend plumbing in setup_torch_distributed, both muon validators, and docs.

optim_cpu_offload remains the supported CPU-offload knob. Default behavior
is unchanged: fully_shard's own default offload policy is OffloadPolicy().

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: drop offload_policy kwargs from direct fully_shard calls

Three fully_shard call sites passed offload_policy=offload_policy directly
(not via fsdp_config) and were missed by the removal — setup_fsdp raised
NameError. fully_shard's default is OffloadPolicy(), so omitting the kwarg
is behavior-identical. Verified by importing the trainer modules and
checking setup_fsdp's symbol table.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 17:59:21 -07:00
c7dc7929a0 chore: bump renderers to v0.1.8 (#3048)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 16:54:16 -07:00
0d2a7f5a12 chore: bump verifiers + research-environments (#3041)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: bump verifiers + research-environments to latest main

verifiers -> 1cfdd39c (incl. docker-runtime entrypoint fix #2015).
research-environments -> dd80d75b (incl. terminal-bench-2 use_prime_registry
fix #668).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test: carry provider usage in advantage test rollouts

verifiers #2040 made Trace token counts usage-based, so the synthetic
rollouts (which only had token ids) reported 0 output/input tokens and the
length-penalty tests failed. Attach provider usage to the final sampled
turn so num_output_tokens / num_input_tokens reflect the intended lengths.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 16:16:59 -07:00
1cb5d91ab2 feat(trainer): ulysses CP beyond num_kv_heads via GQA KV-head replication (#3042)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(trainer): fuse relu2 MoE activation via torch.compile

F.relu(x).square() ran eagerly (the expert path graph-breaks out of the
layer-level compile at the @expert_parallel all-to-all and the _grouped_mm
custom op), materializing an extra full-size copy of the MoE intermediate —
the largest activation for high top-k models (NemotronH Super: top-22,
moe_intermediate 2688; 57.75 GiB at 65k tokens/GPU) and the empirical OOM
site. An explicit torch.compile on relu2 fuses relu+square into a single
pointwise kernel. Measured on Nemotron Super (2xH200 nodes, 16k tokens/GPU):
OOM -> fits at 126.5/139.8 GiB peak.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(trainer): ulysses CP beyond num_kv_heads via GQA KV-head replication

Ulysses CP head-shards Q/K/V, capping the CP degree at num_key_value_heads —
for hybrid-Mamba GQA models like NemotronH Super/Ultra/Nano (2 KV heads) that
means cp <= 2, i.e. at most 2-way context sharding regardless of node count.
(NVIDIA post-trained Super at 256k-512k with CP=64 on Megatron's
sequence-sharded, Mamba-aware CP; prime-rl's ring CP is softmax-only.)

Replicate each KV head cp/num_kv_heads times before the existing seq->head
all-to-all. GQA groups query heads contiguously, so rank r's query-head slice
[r*Hq/cp, (r+1)*Hq/cp) attends KV head floor(r*Hkv/cp) — exactly the replica
the all-to-all lands on rank r. Backward of repeat_interleave sums gradients
over replicas, the exact GQA KV gradient. Q path and the num_kv_heads >= cp
case are unchanged; the Mamba layers already head-shard independently via
cp_mamba (128 heads, n_groups=8 -> cp <= 8 for NemotronH).

New constraint: cp % num_kv_heads == 0 when num_kv_heads < cp (asserted).
Unlocks cp=4/8 for NemotronH on H200 where cp=2 made 131k context
memory-infeasible (65k tokens/GPU through a top-22/512-expert MoE).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: drop relu2 comment

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-16 00:35:58 +02:00
samsjaandGitHub d05744678e feat: allow choosing between claude code and codex in tmux agent window (#3040)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: allow choosing between claude code and codex in tmux agent window

Add --agent flag (claude|codex, default claude) to scripts/tmux.sh.
The agent window now launches the chosen coding agent with the same
monitoring context (log paths, tmux session info).

* fix: use codex --yolo instead of --dangerously-bypass-approvals-and-sandbox
2026-07-15 09:26:32 -07:00
Matej SirovatkaandGitHub 67c20ba8c8 fix(inference): emit SM100 FP8 kernel scales (#3036)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-15 07:50:33 -07:00
Matej SirovatkaandGitHub 683377520e fix: install DeepEP wheel by architecture (#3035)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-15 12:03:18 +02:00
Matej SirovatkaandGitHub 7a7dd80291 feat(inference): add online quantization config (#3031)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(inference): add online quantization config

* fix(config): report missing torch for mxfp8
2026-07-15 01:12:49 +02:00
Sebastian MüllerandGitHub c012c45cf7 fix: restrict startup weight sync to resume and NCCL (#3030)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
#3004 made the trainer/orchestrator startup weight sync unconditional.
The trainer broadcasts startup weights exactly once, for the runs
discovered at its first step, so multi-run orchestrators that register
later wait forever for broadcasts/step_0 and never start —
reverse_text_multi_run has timed out on every run since (beta/gamma/
alpha_resume start staggered). A fresh filesystem start with a [ckpt]
block but no wait_for_weights_timeout also raised FileNotFoundError
immediately instead of waiting.

Filesystem broadcast needs no startup rendezvous: a fresh orchestrator
already serves the base model, which is policy v0, and a resumed one
reads v{resume_step} from its checkpoint dir. Only NCCL has a receiver
that must rendezvous with a trainer-side send — and NCCL is never
combined with multi-run, since multi-run implies LoRA and NCCL+LoRA is
rejected at config validation (also added in #3004).

Gate the orchestrator's startup sync to resume-or-NCCL and the
trainer's first-step broadcast to NCCL, preserving #3004's resume
deadlock fix on the NCCL path while restoring the pre-#3004 filesystem
startup behavior.
2026-07-14 15:56:59 -07:00
HubertandGitHub 5af45e4310 feat(sft): require renderer-based tokenization (#2988)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(sft): renderer-only SFT tokenization

SFT tokenization now goes exclusively through the renderers library:
- build_training_sample with a hand-coded renderer replaces the
  incremental apply_chat_template masking path, which corrupted loss
  masks under position-dependent chat templates (e.g. Qwen3 stripping
  past thinking blocks across user turns). DefaultRenderer is rejected
  in setup_renderer; fake data skips renderer construction entirely.
- [renderer] config defaults to auto-resolution from the tokenizer;
  template controls (e.g. enable_thinking) are set run-wide via the
  typed renderer config.
- Non-assistant roles opt into the loss via the renderer's body-only
  path (content_sft_roles).
- _drop_null_fields strips Arrow phantom nulls before tool-call
  deserialization so genuine nulls inside argument strings survive.
- Null-check rather than key-check for messages vs prompt/completion
  resolution (Arrow schema union adds messages: null to prompt/
  completion rows).
- seq_len default 256 (FakeDataConfig keeps 128); loss_impl defaults
  to liger_fused; CI reverse-text configs pin [renderer] name=qwen3.
2026-07-14 15:31:21 -07:00
Matej SirovatkaandGitHub e03be50a86 fix(laguna): use factor-derived YaRN scaling (#3028)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(laguna): use factor-derived YaRN scaling

* docs(laguna): explain YaRN compatibility override
2026-07-14 10:48:23 -07:00
625b93c5e4 chore: remove CHANGELOG.md (#3029)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Breaking config changes are documented in each PR's ## Breaking section
instead; drop the file and the BugBot rule that enforced it.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-14 10:40:57 -07:00
961c11f4cf feat(orchestrator): support infinite tasksets (#2993)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(orchestrator): support infinite tasksets

An env server may now report num_tasks=None (verifiers#1969: an
infinite, procedurally generated taskset). TrainSource streams a
monotonic task_idx for such an env - the server generates tasks on
demand, so every pull is a fresh task and there are no epochs to
shuffle - while finite envs keep their shuffled index table. An eval
env with an infinite taskset must set num_examples explicitly.

Dormant until the verifiers pin includes #1969: a finite taskset still
reports an int count and takes the existing paths.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers to main (infinite tasksets) + relock

Activates the orchestrator's infinite-taskset support: verifiers main
now includes #1969, so the procedural v1 tasksets report
num_tasks=None. The color-codeword-v1 configs drop their num_examples
taskset field (the knob no longer exists - the taskset is
unconditionally infinite and the train env streams); CHANGELOG entry
for the removed size knobs.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: drop CHANGELOG entry

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 19:05:55 -07:00
Sebastian MüllerandGitHub b7b1f874b5 fix(trainer): skip unneeded gradients in fused LM-head backward (#3011)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
_SequenceChunkedLogProbEntropyFn.backward unconditionally allocated and
accumulated both grad_hidden and grad_weight, ignoring
ctx.needs_input_grad. With a frozen output head (e.g. LoRA without head
adaptation) this allocated a full vocab-size gradient buffer and ran the
weight-gradient matmuls for a result autograd discards. Allocate and
accumulate each gradient only when required; return None otherwise.
2026-07-14 03:25:41 +02:00
d334ea5294 chore: release v0.7.0 (#2998)
Tag and Release / auto-tag-on-main (push) Canceled after 0s
Tag and Release / release-from-auto-tag (push) Canceled after 0s
Tag and Release / tag-and-release (push) Canceled after 0s
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: release v0.7.0

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: sync uv.lock to 0.7.0

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 18:22:09 -07:00
57d2b84330 feat(config): allow prime-rl conversions to be stored separately from model (#3023)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(config): allow prime-rl conversions to be stored separately from model

Add primerl_conversion_dir config field to decouple converted weight
storage from the (potentially immutable) model snapshot directory. When
set, HF<->PrimeRL format conversions are written there instead of inside
the model directory. Defaults to None (existing behavior).

Also fixes load_state_dict to always read from the original source_path
instead of the converted snapshot path's parent.

Signed-off-by: Sami Jaghouar <sami.jaghouar@gmail.com>

* chore: rename primerl_conversion_dir to conversion_dir

Address review: shorter field name and clarify the docstring that converted
weights land in a prime/hf subdirectory. Keep the /prime subdir layout.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Signed-off-by: Sami Jaghouar <sami.jaghouar@gmail.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 18:13:32 -07:00
Matej SirovatkaandGitHub 4f5e06fcb6 fix: install vllm-router on aarch64 (#3025)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-14 02:20:25 +02:00
Matej SirovatkaandGitHub 390dfdc556 fix: support DeepGEMM FP8 training on SM100 (#3022)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix: support DeepGEMM grouped GEMM on SM100

* Remove FP8 inference instructions

Remove FP8 inference section from SKILL.md.

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>

* refactor: inline DeepGEMM scale mode

* fix: support FP8 linears on SM100

---------

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
2026-07-14 02:19:24 +02:00
2fdffa7d3d fix(trainer): broadcast resumed policy weights before training loop (#3004)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(trainer): broadcast resumed policy weights before training loop

On resume, the orchestrator advances to v{checkpoint_step} and pauses
inference to receive those weights over NCCL. Since #2896 moved the
in-loop weight broadcast to the END of a step, the trainer would start
step {checkpoint_step+1} first — which blocks on rollouts the paused
inference engines cannot produce until they get v{checkpoint_step}.
Both sides then wait forever (confirmed on GLM-5.2 resume: orchestrator
"Created NCCL_READY marker" then silent, trainer stuck "Looking for
batches" for the next step).

Restore the pre-#2896 top-of-loop sync with a one-shot broadcast right
after checkpoint load. Runs are only registered during batch collection
(packer.discover_runs), so discover run 0 first (mirroring optim.py's
wait-for-run-0 pattern) to populate used_idxs before broadcasting.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(resume): broadcast startup weights on the first step (fresh or resume)

Address review: instead of a resume-only pre-loop broadcast, always sync
inference to the incoming policy on the first training step.

- trainer: broadcast v{step-1} at the top of the loop's first iteration
  (fresh -> v0, resume -> v{checkpoint_step}), replacing the pre-loop block.
- orchestrator: always pause + sync inference at startup (previously
  resume-only), so it rendezvouses with the trainer's first-step broadcast
  in both cases and startup is symmetric.
- factor the "wait for run 0 to be discovered" loop into
  MultiRunManager.wait_for_run(); reuse it in optim.py (dedupes the
  copy that lived there) and the first-step broadcast.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(orchestrator): wait for startup broadcast on fresh start

The unconditional startup weight sync fell back to wait_timeout=None when
there was no ckpt block (from-scratch run). With filesystem weight broadcast
(check_exists=True), get_weight_dir then raised FileNotFoundError immediately
instead of waiting for the trainer to write broadcasts/step_0/STABLE.

Fall back to a default timeout so the orchestrator waits for the trainer's
startup broadcast, which is always coming.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(config): reject NCCL weight broadcast with LoRA

LoRA adapters are transferred via the filesystem (loaded from disk by the
inference servers); NCCL broadcast only writes a STABLE marker. The now
unconditional startup weight sync makes a fresh LoRA + NCCL run try to load an
adapter from a disk path NCCL never populates, hanging/failing during setup
(and LoRA over NCCL is broken for training-time updates too).

The auto weight-broadcast setup already falls back to filesystem for LoRA when
unset; enforce the same invariant for an explicitly configured NCCL broadcast
instead of failing at runtime.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 17:00:52 -07:00
7cbc77a27f fix: respect packed document boundaries in Qwen3.5 DeltaNet CP (#3003)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Under Ulysses CP the DeltaNet layer built its fla CP context from a
fabricated single-sequence cu_seqlens, so the gated delta rule carried
state across packed documents. The causal conv used shard-local
cu_seqlens, resetting mid-document at every shard boundary even for
unpacked rows.

Build the CP context from the full pre-shard cu_seqlens published by
setup_cp_params (fla derives per-rank boundaries and document-aware
state passing from them) and run the convolution through fla's CP conv,
which resets at true document boundaries and exchanges tail tokens
across ranks for straddling documents.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
2026-07-13 16:06:13 -07:00
21c072a8f9 fix: reset Nemotron-H CP state at packed boundaries (#3001)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix: reset Nemotron-H CP state at packed boundaries

* chore: simplify packed-boundary plumbing in CP mamba

- read ULYSSES_PARAMS["cu_seqlens"] directly via a module-level import,
  matching the ulysses attention path (no try/except wrapper)
- convert cu_seqlens to a boundary list once per forward and share it
  between the conv and seq_idx helpers (one host sync instead of four)
- import cp_mamba as a normal package module in the test

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: drop unused final states from CP mamba scan

return_final_states=True computed and returned states the CP path
discards; return_final_states=False matches the non-CP varlen path
and skips the dfinal_states backward work. Flagged by Cursor Bugbot
(its assert/mishandling claim does not reproduce against mamba_ssm
2.3.1 — outputs and grads verified bit-identical on GPU either way).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
2026-07-13 16:05:36 -07:00
cb43db2ad1 feat: make all envs uv workspace members, drop the envs extra (#3019)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: make research-environment envs uv workspace members

Research envs under deps/research-environments/environments/*/* are now
auto-discovered uv workspace members instead of being hand-registered in
the `envs` extra + [tool.uv.sources]. Adding a new research env needs no
pyproject.toml change - the glob picks it up and it's locked automatically.

They are opt-in: `uv sync` / `--all-extras` no longer install them; use
`uv sync --all-packages`. Env-running sites (sbatch training templates,
gpu/nightly CI, Docker image + entrypoint, nemotron config, example
READMEs) gain --all-packages; dev quickstart and cpu unit tests stay lean.

tau2-synth-v1 and tau3-bench-v1 are excluded - they pin `tau2` forks/revs
that conflict with the canonical tau2-bench-v1 in the workspace's shared lock.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat: make verifiers envs workspace members, drop the envs extra

Extends the workspace glob to deps/verifiers/environments/*, so verifiers-repo
envs are auto-discovered members alongside the research envs. Removes the
now-empty `envs` optional-dependency and all its [tool.uv.sources] entries, and
drops the defunct `--extra envs` from cpu_tests, Dockerfile.cuda, and
docker-entrypoint.sh (env members install via --all-packages instead).

All 94 env members (66 research + 28 verifiers) lock, install, and import.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(ci): install all env packages in cpu_tests

test_load_configs parses every config, and parsing a v1-taskset config makes
verifiers import the env package to derive its taskset config type. With envs
now workspace members, the lean `uv sync --extra flash-attn` left them
uninstalled, so 28 config tests failed with ModuleNotFoundError. Add
--all-packages so the referenced env packages are importable.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 15:46:33 -07:00
Sebastian MüllerandGitHub 2c6ac2bd47 fix(orchestrator): scope the train batch observation window to finalized groups (#3013)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
TrainSink filled the observation window (TrainBatch.rollouts) on arrival,
so a ready overflow batch triggered by the first rollout of a new,
incomplete group claimed that rollout in its window; the window then
reset, leaving the rollout missing from the window of the batch its own
group eventually shipped in. Metrics and persisted per-step traces could
therefore describe rollouts that belong to a different batch.

Window membership now follows group finalization: arrivals accumulate in
pending_groups only, a finalized group moves all its rollouts (errored,
filtered, and survivors) into the window, and batches only ship at
finalization points. Every rollout lands in exactly one batch's window.
2026-07-13 14:07:48 -07:00
Sebastian MüllerandGitHub 4d64d38a60 fix(orchestrator): count token batches by shipped sample payload (#3010)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Token-batched TrainSink accounting used Trace.num_total_tokens, which sums
over all branches — but trace_to_samples skips branches left with no
trainable tokens after fork dedup, so forked traces overcounted vs the
actual trainer payload. Count sum(len(sample.token_ids)) at both accounting
sites (accumulation and batch cut) instead. Linear traces are unchanged.

Zero-payload survivors (no trainable samples) fall back to the trace total
so they still advance the readiness check; a degenerate all-zero-payload
stream then ships empty batches and hits the orchestrator's
consecutive-empty-batch abort rather than stalling batching.
2026-07-13 14:07:10 -07:00
98 changed files with 3195 additions and 1496 deletions
-16
View File
@@ -1,19 +1,3 @@
# BugBot Instructions
## Changelog Enforcement
Any PR that introduces **breaking** configuration changes must update `CHANGELOG.md`. Breaking changes are those that require users to update existing configs:
- **Renamed** config fields (old name no longer accepted)
- **Removed** config fields (field deleted or moved to a different path)
- **Moved** config fields (field relocated in the config hierarchy)
Additive changes (new fields with defaults, new optional features) and default value changes do **not** require a changelog entry.
Config files live in:
- `src/prime_rl/configs/`
If breaking changes are detected without a corresponding `CHANGELOG.md` update, request that the author add an entry.
Any PR that introduces a new custom model must also provide a table showing mean KL mismatch across 20 steps on math environment on this new model with `batch_size=64`. All the entries in the table must lower than 0.015. If this is not present, request the author to add such a table.
-1
View File
@@ -116,7 +116,6 @@ jobs:
build:
name: Build and push (${{ matrix.suffix }})
needs: prepare
environment: ghcr-publish
strategy:
fail-fast: true
matrix: ${{ fromJson(needs.prepare.outputs.matrix) }}
+1 -1
View File
@@ -25,7 +25,7 @@ jobs:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --extra flash-attn --extra envs --locked
run: uv sync --extra flash-attn --all-packages --locked
- name: Run tests
env:
USERNAME_CI: CI_RUNNER
+2 -2
View File
@@ -36,7 +36,7 @@ jobs:
- name: Install uv
uses: astral-sh/setup-uv@v5
- name: Install dependencies
run: uv sync --all-extras --locked
run: uv sync --all-extras --all-packages --locked
- name: Run unit tests
env:
USERNAME_CI: CI_RUNNER
@@ -107,7 +107,7 @@ jobs:
- name: Install uv
uses: astral-sh/setup-uv@v5
- name: Install dependencies
run: uv sync --all-extras --locked
run: uv sync --all-extras --all-packages --locked
- name: Run integration tests
env:
USERNAME_CI: CI_RUNNER
+1 -1
View File
@@ -86,7 +86,7 @@ jobs:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --locked
run: uv sync --all-extras --all-packages --locked
- name: Run experiment
env:
USERNAME_CI: CI_RUNNER
-189
View File
@@ -1,189 +0,0 @@
# Changelog
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **fp32 MoE routing enabled by default**: `trainer.model.moe_router_dtype` (new field) defaults to `"float32"` — custom-impl MoE router gates keep fp32 weights through forward/backward (exempt from the FSDP bf16 cast) and compute the gate GEMM and routing logits in fp32. `inference.enable_fp32_router_logits` (new field) defaults to `true` — DeepSeek-family models served by vLLM (incl. GLM-5.x) emit fp32 router logits via `out_dtype=float32` on the gate. Both change MoE numerics for existing runs (routing logits are no longer rounded to bf16; near-tie expert selections can differ). Set `moe_router_dtype = "bfloat16"` / `enable_fp32_router_logits = false` to restore the previous behavior. Non-MoE and HF-impl models are unaffected. (2026-07-04)
- **`[[orchestrator.train.env]].ratio` now defaults to `1` and no longer accepts unset/`None`**: Each train env's sampling weight defaults to `1` (equal weight per env) instead of `None`. The `None`-for-all-envs mode — which sampled proportional to each env's dataset size (the "natural task distribution") — is removed, along with the all-or-none constraint (any subset of envs may now set `ratio`; the rest default to `1`). Multi-env configs that relied on the old default now sample each env equally rather than proportional to dataset size; set each env's `ratio` explicitly to restore a proportional (or any other) mix. (2026-07-02)
- **`orchestrator.algo.length_penalty` restructured to a single `linear` shape; `tokens`/`turns` length penalties removed**: The `grpo`-family length penalty keeps the `[orchestrator.algo.length_penalty]` key but is collapsed to a single `type = "linear"` shape; the discriminated `type = "tokens" | "turns"` efficiency-shaping variants (and the `efficiency_shaping` helper) are removed. The linear penalty subtracts a `pass_rate`-scaled penalty from each reward before the GRPO baseline, summing three terms — `num_output_tokens_weight` × output tokens, `num_input_tokens_weight` × input (non-output) tokens, and `num_turns_weight` × turns — each normalized by the group's own max for that quantity. Field renames within the penalty: `coef` → `num_output_tokens_weight` (default `0.25`), `context_coef` → `num_input_tokens_weight` (default `0.1`), `turns_coef` → `num_turns_weight` (default `0.1`); the `gate_by_correctness` flag is removed. `extra="forbid"` rejects the old keys, so existing configs must migrate. (2026-06-29)
- **`model.fused_lm_head_token_chunk_size` `"auto"` option removed**: The `"auto"` value is no longer accepted. Use an explicit integer (e.g. `8192`) or `"disabled"`. The `"auto"` value previously resolved to `8192` for RL training — set `fused_lm_head_token_chunk_size = 8192` explicitly to get the same behavior.
- **Memory-saving defaults enabled**: `trainer.model.ac`, `trainer.model.ac_offloading`, `trainer.model.compile`, `trainer.model.optim_cpu_offload`, and `trainer.model.fused_lm_head_token_chunk_size` are now enabled by default to provide sane memory-efficient defaults out of the box. Specifically: `ac` defaults to `ActivationCheckpointConfig()` (full mode), `ac_offloading` defaults to `ActivationOffloadingConfig()`, `compile` defaults to `CompileConfig()` (`fullgraph=false`), `optim_cpu_offload` defaults to `true`, and `fused_lm_head_token_chunk_size` defaults to `1024`. SFT training silently disables `fused_lm_head_token_chunk_size` (sets it to `"disabled"`). Configs using `max_concurrent_runs > 1` must explicitly set `optim_cpu_offload = false`. To disable any of these, set the field to `None` / `"None"` / `false` / `"disabled"` as appropriate.
- **`model.ep` defaults to `"auto"`**: The `ep` field type changed from `int` to `int | Literal["auto"]`, defaulting to `"auto"`. At trainer startup, `resolve_ep()` checks if the model is MoE (via `AutoConfig`); if so, it resolves to `min(fsdp_island_size, 8)` where `fsdp_island_size = world_size // dp_replicate`. For non-MoE models, `"auto"` resolves to 1 (no-op). Set `ep` to an explicit integer to override.
- **verifiers v1 training integration** (collection of removals/renames). The orchestrator now trains against a v1 env server returning `vf.Trace` rollouts, renderer-only, with a unified token schema.
- **`[[orchestrator.train.env]]` is now a v1 `vf.EnvServerConfig`**: a v1 env is `taskset = { id = "<id>" }` + `harness = { id = "default", runtime = { type = "subprocess" } }`. A bare `id = "<id>"` (optionally with `args`) runs the v0 env through the verifiers legacy bridge — old flat `id`/`args`-only configs keep working as legacy envs; v1 envs must use the `taskset`/`harness` shape.
- **`orchestrator.train.env` no longer defaults to a `reverse-text` env**: the default is now empty (`[]`), so configs must declare `[[orchestrator.train.env]]` explicitly.
- **`...env[].num_workers` → `pool`**: per-env worker sizing moves to a `pool` config (`static`/`elastic`). Back-compat: `num_workers = N` maps to `pool = { type = "static", num_workers = N }` and `"auto"` to the default elastic pool; the group-level `orchestrator.train.num_workers` / `orchestrator.eval.num_workers` are removed.
- **`orchestrator.renderer` is now required (MITO removed)**: it was `RendererConfig | None`, where `renderer = None` selected the MITO path; training is now renderer-only, so `renderer` is non-optional. Drop `renderer = None` / `renderer = "None"`.
- **`...client.timeout` / `...client.connect_timeout` removed**: the v1 rollout client manages its own timeouts. Drop these from `[orchestrator.student.client]` and `[orchestrator.teacher.client]`. (2026-06-23)
- **`orchestrator.advantage` length-penalty overhaul + length-weighted baseline**: `length_penalty` is now a single shape — a linear penalty that subtracts `coef * pass_rate * (model completion tokens / orchestrator.seq_len)` from each reward before the baseline subtraction (`pass_rate` = group mean reward, so solved-often problems get the strongest concision pressure and never-solved groups get none), with an optional `gate_by_correctness` flag (default `false`) that restricts the penalty to correct rollouts (`reward == 1`). The previous discriminated `type = "tokens" | "turns"` efficiency-shaping variants and the per-penalty `max_length` field have been removed — configure `[orchestrator.advantage.length_penalty]` with `coef` (and optionally `gate_by_correctness`) instead; the denominator is always `orchestrator.seq_len`. Also adds `orchestrator.advantage.length_weighted_baseline` (default `false`): when enabled, the GRPO baseline is the token-length-weighted mean reward (`sum(len_i * reward_i) / sum(len_i)`) instead of the plain mean. (2026-06-03)
- **`trainer.experimental.token_export` removed → `trainer.enable_token_export`**: `TrainerExperimentalConfig` and the `[trainer.experimental] token_export = true` setting have been removed with no migration alias. Existing trainer configs must delete the `[trainer.experimental]` block and set the new top-level trainer flag instead: `enable_token_export = true` in a trainer config file, or `trainer.enable_token_export = true` when nested under `[trainer]` in an RL config. The trainer entrypoint CLI flag is `--enable-token-export`. (2026-06-10)
- **`inference.kv_cache_offload.cpu_bytes` removed → discriminated `type` config**: The flat `[inference.kv_cache_offload]` block with a single `cpu_bytes` field is replaced by a backend-discriminated union with composable `cpu`/`disk` tiers. Migrate native CPU offload from `[inference.kv_cache_offload]\ncpu_bytes = N` to `[inference.kv_cache_offload]\ntype = "native"` plus `[inference.kv_cache_offload.cpu]\nnum_bytes = N`. A `type = "mooncake"` backend (per-node distributed store; multi-node/SLURM only) and an optional `[inference.kv_cache_offload.disk]\npath = "..."` tier (layered behind cpu) are also available. `extra="forbid"` rejects the old `cpu_bytes` key, so existing configs must migrate. (2026-06-02)
- **Orchestrator async-pipeline rewrite** (collection of removals/renames). The orchestrator was rewritten to overlap train/eval rollouts on a shared concurrency limiter; several config fields were removed or renamed.
- **`orchestrator.seed` removed**: was only consumed by the deleted buffer; no replacement.
- **`orchestrator.eval.eval_base_model` → `orchestrator.eval.skip_first_step`** (semantics inverted): `eval_base_model = true` becomes `skip_first_step = false` (the default — run the step-0 eval before any train rollouts). No alias; configs setting `eval_base_model` must rename.
- **`orchestrator.eval.skip_eval_on_resume` (and its alias `skip_eval_on_restart`) removed**: folded into `skip_first_step`. Resume no longer re-fires an already-completed eval (deduped via per-env last-eval-step tracking in the checkpointed progress).
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval` removed**: the drain-switch overlap (stop scheduling new train, let in-flight train drain while eval queues) is now the only eval transition mode.
- **`ckpt.skip_buffer` removed**: there is no buffer to skip.
- **`[orchestrator.buffer]` removed** (difficulty pools): the whole block and every key (`seed`, `easy_threshold`, `hard_threshold`, `easy_fraction`, `hard_fraction`, `online_difficulty_filtering`, `hash_keys`) are gone, with no alias — `extra="forbid"` rejects the block, so existing configs must delete it. To preserve `online_difficulty_filtering = true`, enforce the zero-advantage pre-batch filter: `[[orchestrator.pre_batch_filters]]\ntype = "zero_advantage"\nenforce = true`.
- **`orchestrator.filters` → `orchestrator.post_batch_filters`** (renamed, no alias): existing configs setting `[[orchestrator.filters]]` must rename to `[[orchestrator.post_batch_filters]]` (`extra="forbid"` rejects the old key). A new `pre_batch_filters` list is also available. Filters are **train-only** now — eval rollouts are no longer filtered.
- **`orchestrator.max_off_policy_steps` now also applies to eval** (behavior change, field unchanged): eval rollouts that fall more than `max_off_policy_steps` versions behind the policy are cancelled, same as train. (2026-05-29)
- **`sampling.min_tokens`, `sampling.repetition_penalty`, `sampling.seed` removed**: Dropped from both `TrainSamplingConfig` and `EvalSamplingConfig` (group-level `[orchestrator.train.sampling]` / `[orchestrator.eval.sampling]` and per-env `[[orchestrator.train.env.sampling]]` / `[[orchestrator.eval.env.sampling]]`). `min_tokens` suppressed natural EOS, `repetition_penalty` distorts the on-policy sampling distribution, and `seed` wasn't pulling its weight — none belonged on the supported config surface. Existing configs setting any of these must delete the field. Hard-deprecation, no migration window. (2026-05-27)
- **`wandb.shared` removed**: The deprecation shim that popped `wandb.shared` from input dicts with a `FutureWarning` (introduced in #2649) is gone. The `rl` entrypoint always uses shared W&B mode now, and existing configs that still set `wandb.shared = true` (or `false`) will fail validation. Drop the field from your config. (2026-05-27)
- **`max_async_level` and `strict_async_level` removed**: The async-execution semantics between trainer and orchestrator are now design invariants, not config knobs. The trainer always runs exactly one step ahead of inference, and the orchestrator always adopts the freshest checkpoint that doesn't violate the one-step barrier. The shared top-level `max_async_level`, the per-sub-config `trainer.max_async_level` / `orchestrator.max_async_level`, and `orchestrator.strict_async_level` have all been removed. Existing configs setting any of these must drop the field; the previous defaults (`max_async_level = 1`, `strict_async_level = false`) match the new hardcoded behavior. Bench mode no longer bypasses the weight-ckpt wait (the `int(1e9)` workaround is gone) and `multimodal/rl_color_codeword_feat_renderer.toml`'s prior `max_async_level = 0` (fully synchronous on-policy) is no longer expressible. (2026-05-25)
- **`teacher_inference` removed from RL entrypoint**: The `[teacher_inference]` config block and the `deployment.num_teacher_gpus` / `deployment.num_teacher_nodes` fields have been removed. The `rl` entrypoint now only manages the student-policy inference server. External teachers (used by OPD and local-vLLM SFT) must be started manually (e.g. `CUDA_VISIBLE_DEVICES=1 uv run inference --model.name <teacher> --server.port 8001 ...`) and pointed at via `[orchestrator.teacher.client]`. Existing configs using `[teacher_inference]` or `deployment.num_teacher_gpus` / `deployment.num_teacher_nodes` must drop those fields and bring up the teacher out-of-band. (2026-05-25)
- **`rollouts_per_example` → `group_size`**: The orchestrator-level field, the group-level `[orchestrator.eval]` field, and the per-env `[[orchestrator.eval.env]]` field have all been renamed. The old name still parses as a validation alias (in both TOML and CLI), so existing configs keep working without changes; new configs should prefer `group_size`. (2026-05-22)
- **`AdvantageInputs` / `AdvantageOutputs` are now per-group, and `AdvantageOutputs.advantages` is a plain `list[float]`** (second breaking change to this API in three weeks). `AdvantageInputs.rollouts` is now `list[vf.RolloutOutput]` (a single group) instead of `list[list[vf.RolloutOutput]]`, and `AdvantageOutputs.advantages` is now `list[float]` instead of a 2D `Float[Tensor, "num_examples rollouts_per_example"]`. `compute_advantages` calls `advantage_fn` once per group, which lets partial-group training (groups smaller than `rollouts_per_example` after rollout errors) round-trip without the previous bucket-by-size workaround. Custom advantage functions must drop the outer list dimension and return a list of floats — e.g. `AdvantageOutputs(advantages=(rewards - rewards.mean(dim=1, keepdim=True)).tolist())` becomes `AdvantageOutputs(advantages=[r - mean for r in rewards])` (or `.tolist()` if you keep torch internally). (2026-05-22)
- **`[model.vlm]` requires `orchestrator.use_renderer = true`**: VLMs must go through the renderer path; the `vlm_requires_renderer` validator rejects `use_renderer = false` when `[model.vlm]` is set. The renderer owns the HF processor per-slot and ships generic `mm_kwargs` keyed by the model's forward signature. Since `use_renderer` already defaults to `true`, most VLM configs need no change. (2026-05-19)
- **First-class `training_mode` + batch-driven loss dispatch** (collection of removals/renames). Loss selection is now driven by `TrainingSample.training_mode` (`rl` / `opd` / `sft`), set under `[orchestrator]`. The trainer is mode-agnostic and dispatches per batch.
- **`orchestrator.use_sft_loss` removed**: replaced by `[orchestrator] training_mode = "sft"`. The orchestrator stamps each sample's `training_mode` and the trainer dispatches to `sft_loss_fn` per batch.
- **`orchestrator.teacher_rollout_model` removed (no alias)**: configs must rename to `[orchestrator.teacher]` (`teacher_model` is also accepted as a back-compat alias for `teacher`). Used in both opd and sft modes; the role is determined by `training_mode`.
- **`orchestrator.model` → `orchestrator.student`**: renamed for symmetry with `orchestrator.teacher`. Legacy `[orchestrator.model]` and a flat `[orchestrator.model.lora]`-style layout are aliased via a back-compat shim, so most existing configs still parse. New code should use `[orchestrator.student.*]`.
- **`trainer.loss.type = "sft"` removed (`SFTLossConfig` deleted)**: zero-field discriminator that is now implied by `training_mode = "sft"`. `trainer.loss` collapsed to a `DefaultLossConfig | CustomLossConfig` union. Existing configs setting `[trainer.loss] type = "sft"` must remove that line; the orchestrator-level `training_mode = "sft"` is enough.
- **`trainer.loss.teacher_tau` removed from `DefaultLossConfig`**: the teacher-KL term is now exclusive to `opd_loss_fn` (which inlines `teacher_tau = 1.0`). `default_loss_fn` only handles reward-driven RL and no longer accepts a `teacher_tau`. Configs that set `teacher_tau` on `[trainer.loss]` will fail validation — switch to `[orchestrator] training_mode = "opd"` (which uses `opd_loss_fn` with the value baked in).
- **`trainer.loss` only applies to rl-mode batches**: opd and sft don't read `trainer.loss`. `opd_loss_fn`'s knobs (dppo_mask_*, kl_tau) are inlined as literals; tweak them by editing the function. `CustomLossConfig` overrides the rl-mode loss only — opd and sft always use their dedicated fns. (2026-05-19)
- **`orchestrator.use_token_client` removed**: The server-tokenized TITO path has been deprecated end-to-end. The orchestrator-side config flag (`use_token_client`), the verifiers client_type (`openai_chat_completions_token`), and the inference server's `/v1/chat/completions/tokens` route (along with the `OpenAIServingChatWithTokens` wrapper) are all gone. The orchestrator now picks between renderer-backed TITO (`use_renderer = true`, default) and MITO (`use_renderer = false`, fallback). Existing configs with `use_token_client = true` must migrate to `use_renderer = true` (or `use_renderer = false` for MITO); configs with `use_token_client = false` can simply drop the field. (2026-05-19)
- **`orchestrator.advantage.length_penalty` → discriminated sub-config**: The scalar `length_penalty: Literal["tokens","turns"] | None` is replaced by a `LengthPenaltyConfig | None` discriminated on `type`. Token shaping now takes weighted completion + tool-response token costs. Migration: `length_penalty = "tokens"` becomes `[orchestrator.advantage.length_penalty]\ntype = "tokens"` (default weights `completion_weight = 1.0`, `tool_response_weight = 1.0` — total context). `length_penalty = "turns"` becomes `[orchestrator.advantage.length_penalty]\ntype = "turns"`. (2026-05-06)
- **`orchestrator.advantage.length_shaping` → `orchestrator.advantage.length_penalty`**: The boolean `length_shaping` flag has been replaced by `length_penalty: Literal["tokens", "turns"] | None` (default: `None`). `length_shaping = true` becomes `length_penalty = "tokens"`; `length_shaping = false` becomes `length_penalty = None`. The new `"turns"` option applies the same correctness-gated efficiency shaping using trajectory turn count instead of completion-token count. (2026-05-01)
- **`AdvantageInputs` API**: Replaced the `rewards`/`completion_lengths`/`num_turns` tensor fields with a single `rollouts: list[list[vf.RolloutOutput]]` (grouped by problem). Custom advantage functions can now access any rollout metadata. Existing custom advantages must update their signatures and extract per-rollout fields directly (e.g. `torch.tensor([[r["reward"] for r in g] for g in inputs.rollouts])`). (2026-05-01)
- **`orchestrator.teacher_rollout_model` now requires `orchestrator.use_sft_loss = true`**: External teacher rollout configs no longer rely on `trainer.loss.type = "sft"` to select SFT loss. Existing hard-distill configs must set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; the orchestrator validates the pair and stamps training samples with the per-batch SFT loss bool. (2026-04-26)
- **`model.attn = "eager"` (NEW option)**: Added `eager` as a valid value for the `model.attn` field. Required for GPT-OSS models on non-Hopper GPUs, since the only flash attention kernel GPT-OSS supports (`kernels-community/vllm-flash-attn3`) is Hopper-only. A clear error message is raised at model load time if GPT-OSS is used without `eager` on unsupported hardware. Also added `kernels` as a core dependency. (2026-04-05)
- **`[[orchestrator.env]]` → `[[orchestrator.train.env]]`**: Training environments and sampling are now configured under `[orchestrator.train]`. The old `[[orchestrator.env]]` and `[orchestrator.sampling]` paths are auto-translated with a deprecation warning and will be removed in a future release. (2026-04-09)
- **Per-env sampling overrides (NEW)**: Both `TrainEnvConfig` and `EvalEnvConfig` now accept a `[sampling]` section for per-env overrides. Unset fields inherit from the group-level sampling config (`[orchestrator.train.sampling]` or `[orchestrator.eval.sampling]`). (2026-04-09)
- **Per-env eval sampling overrides**: `EvalEnvConfig` now accepts a `[sampling]` section. Unset fields inherit from `[orchestrator.eval.sampling]`. All `EvalSamplingConfig` fields remain nullable (None = defer to inference server default). (2026-04-09)
- **`orchestrator.buffer.env_ratios` → per-env `orchestrator.train.env[].ratio`**: `buffer.env_ratios` has been removed. Set `ratio` on each `[[orchestrator.train.env]]` entry instead. Ratios must be all-or-nothing across envs (either all have a ratio or none do). (2026-04-05)
- **`orchestrator.val` removed**: The `[orchestrator.val]` config section (`ValConfig`) has been removed. Existing configs must delete this section. (2026-04-05)
- **`orchestrator.max_concurrent` removed**: Concurrency limiting via `max_concurrent` and the global semaphore have been removed. Existing configs must delete this field. (2026-04-05)
- **`orchestrator.buffer.hash_keys` default changed**: Default changed from `["task", "prompt"]` to `["env_name", "prompt"]`. The `task` field is no longer overridden by the orchestrator for env identification; `env_name` is used instead. Buffer checkpoints using the old default may not resume correctly. (2026-04-05)
- **`orchestrator.eval.env[].failed_rollouts` metric is now a ratio**: The `eval/{name}/failed_rollouts` metric now reports a ratio (0.0–1.0) instead of a raw count. Dashboards keying on this metric should be updated. (2026-04-05)
- **`orchestrator.sampling.temp_scheduler` removed**: Temperature scheduling (`TemperatureSchedulerConfig`) has been removed. `sampling.temperature` is now a required `float` (default `1.0`). Existing configs using `temp_scheduler` must replace it with a fixed `temperature` value. (2026-04-05)
- **`orchestrator.verification` removed**: The `[orchestrator.verification]` config section (`VerificationConfig`) has been removed. Rollout scoring is now always enabled. Existing configs must delete this section. (2026-04-05)
- **`orchestrator.eval.env[].skip_first` removed**: The `skip_first` field on `EvalEnvConfig` has been removed. Existing configs using this field must delete it. (2026-04-05)
- **`EvalSaveHFConfig` removed**: Unused config class removed. (2026-04-09)
- **`orchestrator.env[].max_total_completion_tokens` (NEW)**: Added `max_total_completion_tokens: int` to `EnvConfig` (default: `-1`, disabled). Limits the total completion tokens across all turns in a multi-turn rollout. Auto-populated into `extra_env_kwargs` and applied via the verifiers `set_max_total_completion_tokens()` setter. Works for both training and eval environments. (2026-04-06)
- **`sampling.max_tokens` → `sampling.max_completion_tokens`**: Renamed `max_tokens` to `max_completion_tokens` in both `SamplingConfig` and `EvalSamplingConfig` for consistency with OpenAI API naming. The old name is accepted with a deprecation warning. (2026-04-06)
- **`log.file` and `log.env_worker_logs` removed**: Removed `log.file` (from `LogConfig` and `SharedLogConfig`) and `log.env_worker_logs` (from `LogConfig`). Python file logging is replaced by deployment-level capture. Existing configs using these fields must delete them. Log paths unified: `.stdout` files renamed to `.log`, SLURM logs moved from `slurm/` to `logs/`. (2026-03-31)
- **`trainer.log.ranks_filter` (NEW)**: Added `ranks_filter: list[int]` to `TrainerLogConfig` (default: `[0]`). Controls which ranks appear in trainer console output via torchrun's `--local-ranks-filter`. (2026-03-31)
- **`wandb.log_extras.sample_ratio` / monitor sample logging defaults**: `wandb.log_extras.sample_ratio` is now actually applied to W&B sample-table logging via the shared monitor sampler (it was previously a no-op for WandB). Separately, the orchestrator no longer hard-caps sample logging to 8 rollouts before monitor-level sampling runs, so when monitor `sample_ratio` is `None`, monitors now receive and may log the full rollout batch for a step instead of at most 8 rollouts. This affects both W&B and Prime monitor sample logging behavior. (2026-03-27)
- **`[model.vlm].freeze_vision_encoder`**: Added to `VLMConfig`. Controls whether the vision encoder is frozen (default: `true`). When `false`, the vision encoder is trainable and FSDP-sharded per-block. Has no effect with LoRA. Moved from `[trainer.model].freeze_vision_encoder` into the VLM sub-config. (2026-03-25)
- **`loss_impl = "quack_fused"` (SFT)**: Added `quack_fused` option for the SFT `loss_impl` field. Uses quack-kernels for chunked linear + cross-entropy with CuTe DSL CUDA kernels, avoiding full logits materialization. Requires `quack-kernels` package. Does not support Gemma logit softcapping. Custom model impl (`model.impl = "custom"`) also gains quack RMSNorm acceleration on CUDA automatically. (2026-03-26)
- **`model.ac.targets`**: Removed the `mamba` selective activation checkpoint target and folded that behavior into the broader `linear_attn` target. Existing configs using `targets = ["mamba"]` will now fail validation at runtime with `ValueError`; switch them to `targets = ["linear_attn"]`. The `linear_attn` target description now covers supported token mixers outside the standard softmax-attention path, including NemotronH Mamba layers, Qwen3.5-MoE GatedDeltaNet layers, and AFMoE sliding-window attention layers. (2026-03-28)
- **`model.tp` (trainer `ModelConfig`)**: Removed from the trainer model config. Existing trainer configs must delete this field; it is no longer accepted. (2026-03-26)
- **`orchestrator.env[].num_workers`**: Added configurable env server worker count (`int | "auto"`, default: `"auto"`). When `"auto"`, scales based on concurrency (1 worker per 256 concurrent rollouts). Only used when the orchestrator spawns the env server (i.e. `address` is not set). (2026-03-25)
- **`[model.vlm]` (NEW — replaces auto-detection)**: VLM mode is now opt-in via a `[model.vlm]` sub-config with required `vision_encoder_attr` and `language_model_attr` fields. There is no auto-detection — if you train a VLM, you must add `[model.vlm]`. Existing multimodal configs need the new section. See `docs/multimodal.md` for the table of known model attrs. (2026-03-24)
- **`model.optimization_dtype` / `model.reduce_dtype` (VLM models, RL only)**: VLM dtype validation now only applies to RL training (`TrainerConfig`), not SFT. VLM models used with `sft` no longer require `optimization_dtype='bfloat16'` / `reduce_dtype='bfloat16'`. RL training still enforces both to match vLLM inference. (2026-03-24)
- **`model.ep_comm_backend`**: Added expert-parallel communication backend selection. Accepted values are `torch` (default, uses TorchTitan all-to-all collectives) and `deepep` (uses DeepEP custom kernels). This field only affects configurations with expert parallelism enabled via `model.ep > 1`. (2026-03-22)
- **`model.deepep_num_sms`**: Added DeepEP SM allocation control for intranode dispatch/combine kernels (default: `20`, minimum: `1`). This field is only used when `model.ep_comm_backend='deepep'`; it also determines the internode RDMA channel count (`num_channels = num_sms / 2`). (2026-03-22)
- **`model.deepep_token_chunk_size`**: Added optional token chunk size for DeepEP MoE pipelining (default: `None`, minimum: `1`). When set, DeepEP dispatch for chunk `i+1` overlaps expert compute for chunk `i`. This field is only used when `model.ep_comm_backend='deepep'`. (2026-03-22)
- **`model.optimization_dtype` / `model.reduce_dtype` (VLM models)**: Added validation that VLM models must use `optimization_dtype='bfloat16'` and `reduce_dtype='bfloat16'` to match vLLM inference. Previously valid configs with `float32` (the default) are now rejected for VLM model names. Set both fields to `"bfloat16"` when training VLMs. (2026-03-21)
- **`model.ac.mode`** and **`model.ac.targets`**: Added selective activation checkpointing configuration. `model.ac.mode` accepts `full` (default) or `selective`. When `selective`, `model.ac.targets` selects subcomponents to checkpoint. Supported public targets are currently `norm`, `attention_sdpa`, `mla_up_proj`, and `routed_experts`; runtime validation remains the source of truth. `model.ac.targets` defaults to `["norm"]`, and selective mode requires at least one target. (2026-03-20)
- **`orchestrator.advantage.length_shaping_alpha` → `orchestrator.advantage.length_shaping`**: Replaced GR³ (`length_shaping_alpha: float | None`) with correctness-gated efficiency shaping (`length_shaping: bool`, default: `false`). No hyperparameter needed, no `online_difficulty_filtering` requirement. Existing configs using `length_shaping_alpha` must switch to `length_shaping = true`. (2026-04-13)
- **`orchestrator.advantage.length_weighted_mean`**: Removed. The default advantage now always uses the plain per-problem mean baseline unless `orchestrator.advantage.length_shaping` is enabled. Existing configs must delete this field. (2026-03-19)
- **`prime_monitor.log_extras.sample_ratio`**: Added ratio-based rollout sampling (0.0–1.0, default: None). When set, caps the number of rollouts logged per step to `len(rollouts) * sample_ratio`. `None` preserves current behavior (log all rollouts). Interacts with existing `interval` gate which still runs first. (2026-03-12)
- **`client.connect_timeout`**: Added configurable TCP connect timeout for inference API requests (default: 30.0s). Previously hardcoded to 5.0s. Helps with vLLM or cluster flakiness (2026-03-11)
- **`model.fused_lm_head_token_chunk_size`**: Added as the fused LM-head chunking field for the token-chunked implementation. Unlike the removed `model.fused_lm_head_chunk_size`, this chunks over flattened sequence tokens rather than vocabulary rows. `model.fused_lm_head_chunk_size` is no longer accepted; switch configs to `model.fused_lm_head_token_chunk_size` explicitly. (2026-03-09)
- **`slurm.pre_run_command`**: Added optional shell command to run on the head node before starting the job. Useful for cleanup routines (e.g. killing stale processes, removing lock files). For all-nodes execution, wrap with `srun` in the command string (default: None) (2026-03-08)
- **`slurm.nodelist`**, **`slurm.exclude`**, **`slurm.account`**, **`slurm.time`**: Added common SLURM scheduling options (all default: None) (2026-03-08)
- **`orchestrator.verification.enabled`**: Added top-level rollout verification switch. `orchestrator.buffer.skip_verification` has been removed; use `verification.enabled = false` instead. When disabled, rewards are always 0 and reward-dependent buffer features (`online_difficulty_filtering`, `easy_threshold`, `hard_threshold`) must be unset (2026-03-03)
- **`client.dp_rank_count`**: Added configuration for data-parallel inference routing. When > 1, each `client.base_url` is expanded into `dp_rank_count` logical clients and pinned via `X-data-parallel-rank` to keep multi-turn rollouts on a consistent DP rank (default: 1) (2026-03-03)
- **`model.lora`**: Moved from `model.experimental.lora` to `model.lora` (no longer experimental) (#1440, 2025-12-16)
- Auto-set `api_server_count=1` on inference when LoRA is enabled, because vLLM doesn't support hotloading for multiple API servers (#1422, 2025-12-17)
- **`inference.model.rope_scaling`**: Added RoPE scaling configuration passthrough to vLLM (#1447 2025-12-17)
- **`orchestrator.env_mix`**: Deprecated in favor of `orchestrator.buffer.env_ratios` (#1450, 2025-12-18)
- **`orchestrator.buffer.hash_keys`**: Added hash keys configuration for buffer checkpointing (#1450, 2025-12-18)
- **`orchestrator.buffer.env_ratios`**: Added environment ratio configuration for buffer sampling (#1450, 2025-12-18)
- **`orchestrator.buffer.skip_verification`**: Added configuration to skip verification of rollouts using the environment's rubric. If True, rewards are always set to 0. Cannot be used with `online_difficulty_filtering=True` or when `easy_threshold`/`hard_threshold` are set (default: False)
- **`orchestrator.ckpt.buffer_path`**: Deprecated (#1450, 2025-12-18)
- **`orchestrator.buffer.easy_fraction`** and **`orchestrator.buffer.hard_fraction`**: Easy and hard fraction now defines the fraction of easy and hard problems to convert to normal when resuming, whereas previously it was the ratio of easy/ hard samples to sample per step (#1450, 2025-12-18)
- **`orchestrator.teacher_model`**: Added teacher model configuration for computing teacher logprobs (e.g. for distillation). Supports `TeacherModelConfig` (custom model) or `None` (disabled). Renamed from `reference_model` (2025-12-20)
- **`seq_len`**: Added root-level `seq_len` config that sets both `trainer.model.seq_len` and `orchestrator.seq_len`. Added validation that `trainer.model.seq_len >= orchestrator.seq_len` (2025-12-18)
- **`trainer.loss.sequence_mask_ratio_low`** and **`trainer.loss.sequence_mask_ratio_high`**: Renamed to `trainer.loss.sequence_mask_low` and `trainer.loss.sequence_mask_high` (2025-12-19)
- **`trainer.loss.token_mask_high`** and **`trainer.loss.token_mask_low`**: Added token-level importance ratio masking thresholds (2025-12-19)
- **`trainer.loss.sequence_clip_high`**: Added sequence-level importance ratio clipping threshold (2025-12-19)
- **`trainer.loss.geo_mask_high`** and **`trainer.loss.geo_mask_low`**: Added geometric importance ratio masking thresholds (2025-12-19)
- **`trainer.loss.adv_tau`**: Added tau parameter for advantages (default: 1.0)
- **`trainer.loss.teacher_tau`**: Added tau parameter for teacher logprobs (default: 0.0). Renamed from `ref_tau`
- **`teacher_gpu_ids`**: Added GPU IDs for teacher inference server. When set, automatically starts a teacher inference server and configures `orchestrator.teacher_model`
- **`teacher_inference`**: Added optional teacher inference config. Defaults to copying from `inference` config with port 8001
- **`{orchestrator,trainer}.transport.zmq`**: Added ZMQ transport for training batches and micro batches (#1446, 2025-12-22)
- **`model.impl`**: Changed default from `hf` to `auto`. With `auto`, the implementation automatically selects `custom` if supported for the model, otherwise falls back to `hf` (#1488, 2025-12-27)
- **`orchestrator.eval.skip_eval_on_resume`**: Added flag (default `True`) to skip the first potentially redundant online eval immediately after resuming from a checkpoint (#1491, 2025-12-27)
- **`trainer.weight_broadcast.adapter_only`**: Removed. Adapter-only behavior is now automatically derived from the presence of LoRA configuration (2025-12-27)
- **`ckpt.keep`**: Renamed to `ckpt.keep_last`. Added `ckpt.keep_interval` to keep checkpoints at every N steps permanently (2025-12-31)
- **`MultiLoRAMoE`**: QwenMoE now supports training expert loras and this is enabled by default in the `target_modules`. (2026-01-01)
- **`model.fused_lm_head_chunk_size`**: Added chunk size configuration for fused LM head to enable memory-efficient chunked logprob computation. When set, splits vocabulary into chunks to avoid materializing full [N, V] logit tensor (default: None) (#1525, 2026-01-03)
- **`model.fused_lm_head_chunk_size`**: RL training now auto-sets this to 2048 if not specified (except when `impl='liger_kernel'`). SFT training continues to use None (2026-01-05)
- **`trainer.metrics_server`**: Added optional Prometheus metrics server for trainer observability. Exposes `/metrics` endpoint with step, loss, throughput, grad_norm, etc. Disabled by default (default: None) (#1547, 2026-01-06)
- **`model.lora.alpha`**: Changed default from 16.0 to 32.0 (2026-01-10)
- **`orchestrator.env.log`**: Added logging configuration for environment workers. If set, enables logging with `level` (str, default: "warn") and `vf_level` (str, default: "warn") fields. If None (default), logging is disabled (#1561, 2026-01-13)
- **`eval.watcher`**: Added flag (default `False`) to watch `weights_dir` for newly-created stable checkpoints and evaluate them as they appear (2026-01-14)
- **`orchestrator.log.env_worker_logs`**: Added flag (default `False`) to write env worker logs to `logs/env_workers/{env_name}.log` (2026-01-15)
- **`orchestrator.env.log`**: Removed. Use `orchestrator.log` for env worker logging instead (2026-01-15)
- **`orchestrator.eval.retry.reraise`**: Changed default from `True` to `False`. When `False`, raises `tenacity.RetryError` after retries are exhausted instead of the original exception, allowing failed eval environments to be skipped with a warning (#1586, 2026-01-14)
- **`model.ep`**: Expert parallelism now supported (with auto/custom impl only), changed from the old behaviour when `ep>1` was a no-op to a proper parallelization of the MoE layers. (#1595, 2026-01-15)
- **`orchestrator.reload_weights_on_start`**: Removed. The reload was a no-op in practice since vLLM servers already start with base weights, and LoRA runs skipped it. (#1829, 2026-02-19)
- **`orchestrator.client.elastic`**: Added elastic inference pool with DNS-based service discovery. Supports dynamic server scaling via any DNS hostname with multiple A records (Kubernetes headless services, Consul, Route53, etc.). Automatically syncs LoRA adapters on new servers and only exposes ready servers to workers (#1617, 2026-01-19)
- **`model.fused_lm_head_chunk_size`**: Replaced chunk size `int | None` setting with `int | Literal["auto", "disabled"]` setting. `auto` auto-sets to 2048 if possible. `disabled` explicitly disables chunked loss (use vanilla LM head). Default behaviour is to use `auto` for RL training and `disabled` for SFT training. (not changed from previous version) (#1649, 2026-01-23)
- **`client.skip_model_check`**: Added configuration to skip checking if the model is available in the inference pool. Useful for external APIs or API keys that don't support the /models endpoint (default: False) (#1543, 2026-01-06)
- **`orchestrator.sampling.temp_scheduler`**: Added optional temperature schedule configuration with linear and cosine schedules. Set either `sampling.temperature` (constant) or `sampling.temp_scheduler` (schedule), not both. Default remains 1.0 if neither is set. (2026-01-27)
- **`orchestrator.trajectory_strategy`**: Deprecated. Interleaving now automatically handles extension breaks by starting a new sample when the prefix doesn't match, achieving best-of-both behavior. The setting is ignored and interleaved mode is always used. (2026-01-30)
- **`model.impl`**: Removed `liger_kernel` model implementation from supported options. The Liger kernel dependency remains for SFT loss. (2026-01-30)
- **`log.json_logging`**: Added JSON structured logging option for log aggregation systems (Loki, Grafana, etc.). Outputs flat newline-delimited JSON with `timestamp`, `level`, `message`, `module`, `function`, `line` fields. Available on root `log`, `trainer.log`, and `orchestrator.log` (default: False) (2026-01-28)
- **`model.optim_cpu_offload`**: Added flag to offload optimizer states to CPU without moving parameters (default: False) (2026-01-31)
- **`orchestrator.tasks_per_minute`**: Added optional rate limiting for sandbox tasks per environment worker. Uses token bucket algorithm. If None (default), no rate limiting is applied (2026-02-02)
- **`model.cp`**: When `cp>1` with `attn="flash_attention_3"`, require `model.impl="custom"` (FA3 ring-attention kernel only in custom path) (2026-02-06)
- **`model.attn`**: Added `fa4` as an attention implementation option. Flash attention 4 is only supported with the custom implementation (#1726, 2026-02-06)
- **`inference.model.enable_prefix_caching`**: Added flag to enable prefix caching in vLLM. Passed to vLLM as `--enable-prefix-caching` (default: None) (2026-02-08)
- **`orchestrator.env.address`**: Added address field on `EnvConfig`. If set, connect to an environment server at this address; if None, spawn a server in a subprocess (2026-02-06)
- **`orchestrator.env.extra_env_kwargs`**: Added on `EnvConfig`. Extra kwargs passed to the env (e.g. seq_len, interleaved_rollouts, score_rollouts). Auto-populated by the orchestrator for training envs; generally not recommended for user override. Main use case is to match these kwargs when running an env in an isolated environment server (default: {}) (2026-02-06)
- **`OrchestratorConfig`**: Removed `workers_per_env`, `max_env_worker_restarts`, and `mask_env_responses` (2026-02-06)
- **`EvalSaveDiskConfig`**, **`EvalSaveConfig`**, **`RetryConfig`**, **`OnlineEvalConfig`**: Removed (2026-02-06)
- **`TemperatureScheduleConfig`**: Renamed to `TemperatureSchedulerConfig` (2026-02-06)
- **`optim.mu`**: Added Muon momentum (`mu`) config field (default: 0.95). Previously hardcoded to Muon class default. Also fixed `optim.betas1`/`optim.betas2` not being passed through to the Muon optimizer (2026-02-09)
- **`dump_config`**: Added `--dump-config <path>` flag to the `rl` command. When set, writes the resolved subconfigs (trainer, orchestrator, inference, teacher_inference) to the given directory and exits without starting any processes (2026-02-12)
- **`client.api_key_var`**: Changed default from "OPENAI_API_KEY" to "VLLM_API_KEY" (2026-02-12)
- **`orchestrator.filters`**: Added orchestrator-side rollout filters for detecting degenerate generations. Supports `[[filters]] type = "gibberish"` (rare tokens at high entropy) and `[[filters]] type = "repetition"` (high-confidence token streaks). Detected rollouts get reward zeroed and completion mask cleared (2026-02-13)
- **`inference.model.tool_call_parser`**: Changed default from `"hermes"` to auto-detection from model name. Uses `MODEL_TOOL_CALL_PARSER` dict to infer the correct vLLM tool call parser (e.g. Qwen3→`hermes`, GLM-4.5→`glm45`, GLM-4.7→`glm47`, MiniMax-M2→`minimax_m2`, INTELLECT-3→`hermes`). Unknown models default to `None`. Explicit values still take priority. (#1795, 2026-02-16)
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval`**: Added flag to optionally cancel in-flight training rollouts before starting online evals. When enabled, avoids congestion by preventing training and eval rollouts from running simultaneously, but slows training as the rollout pipeline must refill after each eval (default: False) (2026-02-16)
- **`orchestrator.use_token_client`**: Added flag to use the token-in-token-out (TITO) client for training across all environments. When enabled, uses `openai_chat_completions_token` client type instead of `openai_chat_completions`. Only use when environments have linear history and the chat template has the extension property (default: False) (2026-02-21)
- **`model.cp` + AFMoE**: Context parallelism now works with AFMoE models via unified `substitute_ring_attn` which patches `_compute_attention` on both `FlashAttention` and `AfmoeFlashAttention` to use ring attention. Sliding window layers automatically get per-layer `window_size`; full attention layers default to `(-1, -1)`. Also plumbed `window_size` through the FA3 ring attention wrapper (`ring_fa3_varlen_func`). (2026-02-21)
- **`orchestrator.token_batch_size`** and **`orchestrator.max_inflight_rollouts`**: Added token-based batching via `token_batch_size` and explicit in-flight rollout control via `max_inflight_rollouts` (2026-02-23)
- **`orchestrator.batch_size`**: Now optional and mutually exclusive with `token_batch_size`. If neither is set, defaults to rollout mode with `batch_size=128` (2026-02-23)
- **`inference.enable_expert_parallel`**, **`inference.all2all_backend`**, and **`inference.enable_eplb`**: Added expert-parallel inference controls passed to vLLM as `--enable-expert-parallel`, `--all2all-backend`, and `--enable-eplb` (defaults: `False`, `"allgather_reducescatter"`, `False`) (2026-02-23)
- **`rl_slurm` / `sft_slurm` entrypoints**: Removed. SLURM submission is now handled by the unified `rl` and `sft` entrypoints. Add a `[slurm]` section to your config to submit via SLURM instead of running locally (2026-02-23)
- **`inference_gpu_ids` / `trainer_gpu_ids` / `teacher_gpu_ids`**: Removed from `RLConfig`. Replaced by `[deployment]` section with `type = "single_node"` (fields: `num_train_gpus`, `num_infer_gpus`, `num_teacher_gpus`) or `type = "multi_node"` (fields: `num_train_nodes`, `num_infer_nodes`, `num_teacher_nodes`, `nodes_per_fsdp_group`). Default is `single_node` with 1 train GPU and 1 infer GPU (2026-02-23)
- **`RLSLURMConfig`**: Removed. Fields `job_name`, `num_train_nodes`, `num_infer_nodes`, `gpus_per_node`, `nodes_per_fsdp_group`, `project_dir`, `slurm_template`, `dry_run` are now under `[slurm]` and `[deployment]` in the unified `RLConfig` (2026-02-23)
- **`SFTSLURMConfig`**: Removed. Fields `job_name`, `num_nodes`, `gpus_per_node`, `nodes_per_fsdp_group`, `project_dir`, `slurm_template`, `dry_run` are now under `[slurm]` and `[deployment]` in `SFTConfig` (2026-02-23)
- **`[deployment]` (RL)**: Added deployment configuration. `type = "single_node"` auto-derives contiguous GPU assignments from `num_infer_gpus`, `num_train_gpus`, `num_teacher_gpus`. `type = "multi_node"` requires `[slurm]` and uses `num_train_nodes`, `num_infer_nodes` (2026-02-23)
- **`[deployment]` (SFT)**: Added deployment configuration. `type = "single_node"` with `num_gpus` (default: 1). `type = "multi_node"` with `num_nodes`, `nodes_per_fsdp_group`, `hf_hub_offline` (2026-02-23)
- **`[slurm]` (RL)**: Added SLURM configuration with `job_name`, `project_dir`, `template_path`, `partition`, `dry_run`. When present, `uv run rl` generates and submits an sbatch script instead of running locally. Template is auto-selected based on deployment type (2026-02-23)
- **`[slurm]` (SFT)**: Added SLURM configuration with `job_name`, `project_dir`, `template_path`, `partition`, `dry_run`. When present, `uv run sft` generates and submits an sbatch script instead of running locally (2026-02-23)
- **`hf_hub_offline` (RL/SFT SLURM)**: Removed. `HF_HUB_OFFLINE=1` is now hardcoded in the multi-node SLURM templates (2026-02-23)
- **SLURM templates**: Moved from `src/prime_rl/slurm/` to `src/prime_rl/templates/` and renamed to `single_node_rl.sbatch.j2`, `multi_node_rl.sbatch.j2`, `single_node_sft.sbatch.j2`, `multi_node_sft.sbatch.j2` (2026-02-23)
- **Entrypoints**: Moved `rl` and `sft` entrypoints from `prime_rl.rl` / `prime_rl.sft` to `prime_rl.entrypoints.rl` / `prime_rl.entrypoints.sft`. No change to CLI usage (`uv run rl`, `uv run sft`) (2026-02-24)
- **`output_dir` (RL)**: Changed from `Path | None` (default `None`) to `Path` (default `Path("outputs")`). The SLURM-specific validation that rejected the default has been removed — `output_dir` now works the same for local and SLURM runs (2026-02-24)
- **`clean_output_dir`**: Added to `RLConfig` and `SFTConfig` (default: `False`). Training now raises `FileExistsError` when `output_dir` contains checkpoints from a previous run and not resuming. Set `clean_output_dir=true` to delete and start fresh, or set `ckpt.resume_step` to resume (2026-02-24)
- **`clean`**: Removed from `RLConfig`. The old `clean` flag (default: `True`) silently deleted logs, rollouts, and broadcasts on every local RL run. Superseded by the explicit `clean_output_dir` flag (2026-02-24)
- **Config consolidation**: All config modules moved into `prime_rl.configs` subpackage. `utils/config.py` + `transport/config.py` → `configs/shared.py`; `trainer/config.py` + `trainer/rl/config.py` → `configs/trainer.py`; `trainer/sft/config.py` → `configs/sft.py`; `orchestrator/config.py` → `configs/orchestrator.py`; `inference/config.py` → `configs/inference.py`; `rl_config.py` → `configs/rl.py`. Class renames: `SFTTrainerConfig` → `SFTConfig`, `RLTrainerConfig` → `TrainerConfig`. Component prefixes dropped from orchestrator and inference config classes (e.g. `OrchestratorCheckpointConfig` → `CheckpointConfig`). TypeAlias renames: dropped `Type` suffix (e.g. `LossConfigType` → `LossConfig`, `TransportConfigType` → `TransportConfig`), renamed `LossConfig` class → `DefaultLossConfig`. No TOML key changes. (2026-02-24)
- **`trainer.enable_router_replay`**: Added flag to enable router replay. If True, will return routed experts in the batch. This is only supported if `enable_return_routed_experts=True` in the inference config or pass `--enable-return-routed-experts` to vLLM server. This is only supported for custom models. (2026-02-22)
- **`inference.enable_return_routed_experts`**: Added flag to enable return routed experts. Passed to vLLM as `--enable-return-routed-experts` (2026-02-22)
- **`orchestrator.oversampling_factor`**: Added rollout-only over-sampling config that resolves `max_inflight_rollouts = int(batch_size * oversampling_factor)` when `max_inflight_rollouts` is unset. Cannot be used with `token_batch_size` or together with explicit `max_inflight_rollouts` (2026-02-25)
- **`sft.val`**: Added optional periodic SFT validation with `val/loss` and `val/num_tokens` logging. Configure via `sft.val.data` (validation dataset) and `sft.val.interval` (every N steps, default 50). Runs the full validation dataset each pass. (2026-02-26)
- **`model.fused_lm_head_chunk_size`**: Changed default value from 2048 to 8192 for RL training (2026-02-26)
- **`inference.data_parallel_size_local`** and **`inference.data_parallel_rpc_port`**: Added data-parallel node-local controls for vLLM, passed as `--data-parallel-size-local` and `--data-parallel-rpc-port` (defaults: `None`, `13345`) (2026-02-26)
- **`dump_config`**: Removed from `RLConfig`. Replaced by `dry_run` (see below) (2026-02-26)
- **`slurm.dry_run`**: Removed from `SlurmConfig`. Replaced by top-level `dry_run` (see below) (2026-02-26)
- **`dry_run`**: Added to `RLConfig` and `SFTConfig` (default: `False`). When set, validates the config, writes resolved subconfigs to `output_dir/configs/`, and exits without starting any processes. Works the same for both local and SLURM runs (2026-02-26)
- **Config output location**: Resolved subconfigs are now always written to `output_dir/configs/` instead of `.pydantic_config/<uuid>/`. This applies to both local and SLURM entrypoints, and for both single-node and multi-node deployments (2026-02-26)
- **SFT config filename**: The resolved SFT trainer config is now written as `sft.toml` instead of `trainer.toml` (2026-02-26)
- **Inference entrypoint**: Moved from `prime_rl.inference.server` to `prime_rl.entrypoints.inference`. No change to CLI usage (`uv run inference`) (2026-02-26)
- **`[slurm]` (inference)**: Added SLURM configuration to `InferenceConfig`. When present, `uv run inference` generates and submits an sbatch script instead of running locally. Each SLURM node runs an independent vLLM replica (no cross-node parallelism) (2026-02-26)
- **`[deployment]` (inference)**: Added deployment configuration. `type = "single_node"` (default) with `gpus_per_node`. `type = "multi_node"` with `num_nodes` and `gpus_per_node` — requires `[slurm]` (2026-02-26)
- **`inference.output_dir`**: Added directory for SLURM logs and generated scripts (default: `"outputs"`) (2026-02-26)
- **`inference.dry_run`**: Added flag (default: `False`). When set, validates config, writes resolved config to `output_dir/configs/`, and exits without starting inference or submitting SLURM jobs (2026-02-26)
- **`orchestrator.teacher_rollout_model`**: Added optional external rollout model configuration. When set, rollouts are generated from this endpoint/model instead of the student inference server. Accepts a `TeacherRolloutModelConfig` with `client` and `model` sub-fields, or `None` (default: `None`) (2026-02-26)
- **`trainer.loss.type = "sft"`**: Added SFT loss variant. Set `trainer.loss.type = "sft"` to use masked negative log-likelihood loss instead of the default RL loss (2026-02-26)
- **`trainer.loss.type = "custom"`**: Added custom loss variant. Set `trainer.loss.type = "custom"` with `import_path` (e.g. `"my_module.my_loss"`) and optional `kwargs` to use an external loss function (2026-02-26)
- **`trainer.loss` (default loss)**: Made IPO (DPPO-Binary TV variant ([arxiv](https://arxiv.org/pdf/2602.04879)) + Kimi-K2.5 KL ([Kimi-K2.5](https://arxiv.org/pdf/2602.02276))) the default loss. Removed `ratio_type`, `token_mask_low`, `token_mask_high`, `sequence_clip_high`, `geo_mask_low`, `geo_mask_high`, `sequence_mask_low`, `sequence_mask_high`. Added `ipo_mask_low` (default: 0.2) and `ipo_mask_high` (default: 0.2) for token-level probability-difference masking. Changed `kl_tau` default from `0.0` to `1e-3`. (2026-03-02)
- **Metrics logging overhaul**: All orchestrator metrics now follow a `{metric}/{scope}/{stat}` naming convention where scope is `all` (global) or an env name. Per-env breakdowns are always logged (previously only when >1 env). Key renames: `reward/mean` → `reward/all/mean`, `batch/solve_none` → `solve_none/all`, `val_reward/` → `val/reward/`, `metrics/{name}` → `metrics/{env}/{name}`, `stop_condition/{sc}` → `stop_condition/all/{sc}`, `error/mean` → `error/all/mean`. New per-env metrics: `solve_none/{env}`, `solve_all/{env}`, `effective_batch_size/{env}`, `stop_condition/{env}/generation_truncated`, `stop_condition/{env}/{sc}`, `error/{env}/mean`, plus per-env breakdowns for `seq_len`, `prefill_len`, `decode_len`, `is_truncated`, `samples_per_rollout`, `num_turns`, `generation_ms`, `scoring_ms`. Removed: `reward/std`, `reward/median`, per-error-type breakdown (`error/{error_type}`). Env name `"all"` is reserved and rejected at config validation. Env name validation now strips `@version` suffixes to match runtime behavior (e.g. `math@1.0` and `math@2.0` correctly detected as duplicates). Solve stats now use `example_id` grouping instead of index arithmetic (pre-existing bug fix). (2026-03-08)
- **`wandb.shared`** (experimental): Added shared W&B mode that logs trainer and orchestrator metrics to a single W&B run instead of two separate runs. Uses `wandb.Settings(mode="shared")` (requires wandb SDK >= 0.19.9). Enabled by default on the RL entrypoint. Disable with `--wandb.shared False`. Run ID is communicated via `WANDB_SHARED_RUN_ID` env var; process role via `WANDB_SHARED_LABEL`. Non-primary processes retry `wandb.init` up to 30 times waiting for the primary to create the run. Works with multi-node SLURM. (2026-03-18)
- **`wandb.id`**: Removed from `WandbConfig`. Run IDs are now managed internally via env vars for shared mode. (2026-03-18)
- **`trainer.ckpt.skip_optimizer`**: Added flag to skip loading optimizer states when resuming training. When set, only the model weights are loaded from the checkpoint. (2026-03-24)
+2 -6
View File
@@ -91,10 +91,6 @@ COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pr
# Use submodule git metadata from the build context when present. Docker copies
# only the submodule .git pointer files into /app/deps, so we temporarily link
# /app/.git/modules to the read-only context before resolving versions.
# Opt-in extras for disaggregated P/D inference (deep-ep, deep-gemm, quack).
# Default off — they're heavy source builds only the disagg-MoE path needs.
# Enable via `--build-arg INCLUDE_DISAGG_EXTRAS=1`.
ARG INCLUDE_DISAGG_EXTRAS=0
ARG VERIFIERS_PRETEND_VERSION
ARG RENDERERS_PRETEND_VERSION
RUN --mount=type=cache,target=/app/.cache/uv \
@@ -109,9 +105,9 @@ RUN --mount=type=cache,target=/app/.cache/uv \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
EXTRA_DISAGG_FLAG=""; if [ "$INCLUDE_DISAGG_EXTRAS" = "1" ]; then EXTRA_DISAGG_FLAG="--extra disagg"; fi \
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra modelexpress --extra quack --group mamba-ssm --locked --no-dev \
&& \
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --extra gpt-oss --extra modelexpress $EXTRA_DISAGG_FLAG --group mamba-ssm --locked --no-dev
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "quack-kernels", "vllm", "vllm-router")]'
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
+2
View File
@@ -111,6 +111,8 @@ source $HOME/.local/bin/env
uv sync --all-extras
```
> *NOTE*: Environments are opt-in uv workspace members — `uv sync --all-extras` does not install them. To train on them, install all with `uv sync --all-extras --all-packages`, or a subset with `uv sync --package prime-rl --package <env>`.
4.1. On aarch64 hosts: build flash-attn from source for your GPU
> *NOTE*: aarch64 has no prebuilt flash-attn wheel. This step compiles the CUDA extension for your local GPU (~20-30 minutes). Compute capability is auto-detected from `nvidia-smi`; override with `TORCH_CUDA_ARCH_LIST=9.0` (Hopper) / `10.0` (Blackwell) if needed.
@@ -22,7 +22,7 @@ max_completion_tokens = 64
[[orchestrator.train.env]]
name = "color-codeword"
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
taskset = { id = "color-codeword-v1", images_per_turn = 1 }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer]
+1 -1
View File
@@ -4,7 +4,7 @@ max_steps = 5
name = "PrimeIntellect/GLM-0.5B"
moe_use_grouped_mm = false
impl = "custom"
attn = "sdpa"
attn = "flash_attention_2"
[model.compile]
+1 -1
View File
@@ -41,7 +41,7 @@ max_completion_tokens = 64
[[orchestrator.train.env]]
name = "color-codeword"
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
taskset = { id = "color-codeword-v1", images_per_turn = 1 }
harness = { id = "null", runtime = { type = "subprocess" } }
# Default renderer (AutoRendererConfig) resolves Qwen3-VL-4B-Instruct from
+1 -1
View File
@@ -5,7 +5,7 @@ seq_len = 2048
[slurm]
job_name = "nemotron-4node"
pre_run_command = "uv sync --all-extras --group mamba-ssm"
pre_run_command = "uv sync --all-extras --all-packages --group mamba-ssm"
[deployment]
type = "multi_node"
+1 -1
+1 -1
+15 -1
View File
@@ -36,7 +36,21 @@ 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, FP8 training (`model.fp8 = true`, requires SM90+), 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 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.
### 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:
- `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`).
```toml
[trainer.model.quantization]
type = "mxfp8"
recipe = "mxfp8_rceil"
enable_a2a = true
```
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`).
+3 -1
View File
@@ -107,6 +107,8 @@ ep_comm_backend = "torch" # or "deepep"
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. We reccomend using `ulysses` style CP for most of the models to get the most throughput. Some models (e.g. GLM-5) only support `ring` style CP. Wrong setting will be rejected on validation.
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Hybrid Mamba layers head-shard independently (`cp_mamba`), which requires the CP degree to divide `mamba_num_heads` and `n_groups`.
```toml
[trainer.model]
impl = "custom"
@@ -179,7 +181,7 @@ The defaults already cover: fused LM head chunking (`1024`), `torch.compile` (fu
The `rl`, `sft`, and `inference` entrypoints all submit to SLURM when a `[slurm]` table is present — there's no separate entrypoint.
> **The prime-rl checkout and its `uv` venv must live on a shared filesystem** visible to every node. The generated sbatch script runs a single `uv sync --all-extras` on the batch node (not once per node), so all ranks share that one environment — a node-local venv would leave the other nodes stale.
> **The prime-rl checkout and its `uv` venv must live on a shared filesystem** visible to every node. The generated sbatch script runs a single `uv sync --all-extras --all-packages` on the batch node (not once per node), so all ranks share that one environment — a node-local venv would leave the other nodes stale.
### Activation
+12 -4
View File
@@ -144,12 +144,20 @@ Two accepted layouts:
If both columns are present, `messages` takes precedence.
**Tool definitions.** For tool-use SFT, add a `tools` column (OpenAI function-calling format) or `tool_defs` ([`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) rollout format). Each row's value can be either a list of dicts or a JSON-encoded string of a list — both are accepted, and `tool_defs` rows are auto-converted to OAI shape before being passed into the chat template's `tools=...` argument. The `chat_template_kwargs` column, if present, is forwarded verbatim into `apply_chat_template`.
**Tool definitions and renderer controls.** For tool-use SFT, add a `tools` column (OpenAI function-calling format) or `tool_defs` ([`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) rollout format). Each row's value can be either a list of dicts or a JSON-encoded string of a list — both are accepted, and `tool_defs` rows are auto-converted to OAI shape before being passed into the renderer.
**Position-dependent chat templates.** Multi-turn SFT under the default tokenization path (`build_incremental_token_mask`) requires that tokenizing the first _k_ turns of a conversation be a strict prefix of tokenizing all _n ≥ k_ turns. Qwen3's upstream template _violates_ this — it strips past `<think>` blocks across user turns, silently corrupting the loss mask. Two fixes:
Renderer-backed SFT reads template controls from the typed `[renderer]` config in the SFT TOML. For example:
```toml
[renderer]
name = "qwen3"
enable_thinking = false
```
If a model needs another template control, add it to that model's renderer config in `renderers` (for example a new field on the relevant `*RendererConfig`) and consume it in the renderer implementation.
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `—` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS.
- **Enable the renderer** (set a typed `[renderer]` config, e.g. `name = "qwen3"`, recommended; defaults to `"auto"` for RL). The [`renderers`](algorithms.md#renderers) package owns tokenization end-to-end and is robust to position-dependent templates. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS. Not supported for VLMs.
- **Patched chat template** — the prime-rl–patched checkpoints (e.g. `PrimeIntellect/Qwen3-0.6B`, used in `examples/reverse_text/sft.toml`) ship a chat template that preserves thinking. Or supply your own.
See [Algorithms § Multi-Turn Trajectories](algorithms.md#multi-turn-trajectories) for the full picture.
+1 -1
View File
@@ -13,7 +13,7 @@ You also need prime-rl cloned on your cluster into the shared filesystem.
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
uv sync --all-extras
uv sync --all-extras --all-packages
```
### Install llm-d
+3 -1
View File
@@ -61,7 +61,9 @@ fused_lm_head_token_chunk_size = 1024
cp = 4 # context parallel for the 131K seq len
ep = 8
optim_cpu_offload = true
fp8 = true
[trainer.model.quantization]
type = "fp8"
[trainer.model.ac]
freq = 1
+1 -1
View File
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
uv sync --all-extras
uv sync --all-extras --all-packages
```
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
+1 -1
View File
@@ -15,7 +15,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
uv sync --all-extras
uv sync --all-extras --all-packages
```
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
+1 -1
View File
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
uv sync --all-extras
uv sync --all-extras --all-packages
```
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
+1 -1
View File
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
uv sync --all-extras
uv sync --all-extras --all-packages
```
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
+1 -1
View File
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
uv sync --all-extras
uv sync --all-extras --all-packages
```
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
+2 -5
View File
@@ -30,9 +30,6 @@ max_completion_tokens = 1024
[inference.parallel]
dp = 6
# Qwen3 finetune with the standard PI template patch (byte-identical to
# PrimeIntellect/Qwen3-0.6B base); always re-emits prior <think> blocks.
# Match that with renderer thinking_retention.
# Fine-tune inherits the PrimeIntellect Qwen3 template byte-for-byte.
[orchestrator.renderer]
name = "qwen3"
thinking_retention = "all"
name = "prime-qwen3"
@@ -366,6 +366,9 @@ class InferenceConfig(BaseConfig):
gpu_memory_utilization: float = 0.9
"""GPU memory utilization. Forwarded as ``--gpu-memory-utilization``."""
quantization: Literal["mxfp8", "fp8_per_block"] | None = None
"""Online inference quantization method. Forwarded as ``--quantization``."""
api_server_count: int = Field(1, ge=0)
"""API servers to run. Forwarded as ``--api-server-count``. Set to 0 for headless mode."""
@@ -432,6 +435,24 @@ class InferenceConfig(BaseConfig):
raise ValueError("Must use SLURM for multi-node / disaggregated deployment.")
return self
@model_validator(mode="after")
def validate_mxfp8_requires_sm100(self):
"""Reject MXFP8 when validation runs on a non-SM100 CUDA host."""
if self.quantization != "mxfp8":
return self
try:
import torch
except ModuleNotFoundError as exc:
raise ValueError("inference.quantization='mxfp8' requires torch to validate SM100 support.") from exc
if torch.cuda.is_available():
capability = torch.cuda.get_device_capability()
if capability != (10, 0):
detected = f"SM{capability[0]}{capability[1]}"
raise ValueError(f"inference.quantization='mxfp8' requires SM100, detected {detected}.")
return self
@model_validator(mode="after")
def validate_llmd_no_routed_experts(self):
"""Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node)."""
@@ -576,6 +597,7 @@ class InferenceConfig(BaseConfig):
"max_lora_rank": "max_lora_rank",
"lora_target_modules": "lora_target_modules",
"gpu_memory_utilization": "gpu_memory_utilization",
"quantization": "quantization",
"api_server_count": "api_server_count",
"enable_return_routed_experts": "enable_return_routed_experts",
"enable_expert_parallel": "enable_expert_parallel",
@@ -625,6 +647,10 @@ class InferenceConfig(BaseConfig):
if hasattr(namespace, "lora_target_modules") and namespace.lora_target_modules is None:
delattr(namespace, "lora_target_modules")
# Remove quantization if not set so vLLM can infer it from the checkpoint.
if namespace.quantization is None:
delattr(namespace, "quantization")
# Remove rope_scaling if not set (vLLM doesn't accept None)
if hasattr(namespace, "rope_scaling"):
if namespace.rope_scaling is None:
@@ -347,6 +347,14 @@ class RLConfig(BaseConfig):
self.weight_broadcast = SharedWeightBroadcastConfig(type="filesystem")
else:
self.weight_broadcast = SharedWeightBroadcastConfig()
if self.weight_broadcast.type == "nccl" and self.trainer.model.lora is not None:
# LoRA adapters are transferred via the filesystem (loaded from disk by the inference
# servers); NCCL broadcast only writes a STABLE marker, so LoRA over NCCL cannot transfer
# an adapter and would hang/fail on the startup weight sync.
raise ValueError(
"LoRA training is not yet supported with NCCL weight broadcast. "
"Set weight_broadcast.type = 'filesystem'."
)
if self.weight_broadcast.type == "nccl":
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
@@ -3,7 +3,8 @@ from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from pydantic import Field, model_validator
from renderers import RendererConfig
from renderers import AutoRendererConfig, DefaultRendererConfig, RendererConfig
from renderers.base import MODEL_RENDERER_MAP
from prime_rl.configs.shared import (
EnvVars,
@@ -175,13 +176,8 @@ class SFTConfig(BaseConfig):
tokenizer: TokenizerConfig = TokenizerConfig()
renderer: RendererConfig | None = None
"""Typed renderer config (``renderers.RendererConfig`` discriminated
union). When set, SFT tokenizes samples through the ``renderers``
library (single ``render()`` + ``message_indices`` mask) instead of
the default ``build_incremental_token_mask`` path. Required for chat
templates that render position-dependently (e.g. Qwen3, Qwen3.5).
``None`` (default) uses the legacy tokenization path."""
renderer: RendererConfig = AutoRendererConfig()
"""Renderer config. Defaults to auto-selecting from the tokenizer model name."""
data: DataConfig = SFTDataConfig()
@@ -225,9 +221,6 @@ class SFTConfig(BaseConfig):
dist_timeout_seconds: int = 3600
"""Timeout in seconds for torch distributed ops."""
loss_impl: Literal["liger", "torch", "liger_fused", "quack_fused"] = "torch"
"""Cross-entropy loss implementation. ``liger_fused`` fuses the lm_head projection with the CE loss to avoid materializing full logits. ``quack_fused`` uses quack-kernels for chunked linear + CE with CuTe DSL CUDA kernels."""
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
@@ -271,6 +264,28 @@ class SFTConfig(BaseConfig):
raise ValueError("Must use SLURM for multi-node deployment.")
return self
@model_validator(mode="after")
def validate_typed_renderer(self):
"""Require a typed renderer whenever SFT renders real samples."""
if self.data.type == "fake" and self.val is None:
return self
model_id = self.tokenizer.name or self.model.name
if isinstance(self.renderer, AutoRendererConfig):
if model_id in MODEL_RENDERER_MAP:
return self
reason = f"no typed renderer is registered for {model_id!r}"
elif isinstance(self.renderer, DefaultRendererConfig):
reason = "renderer.name='default' selects DefaultRenderer"
else:
return self
raise ValueError(
f"SFT requires a typed renderer with sampled-token and content attribution, but {reason}. "
"Implement and register the renderer in the renderers package, or explicitly select an existing "
"typed renderer only when its template is verified to match."
)
@model_validator(mode="after")
def validate_pack_function(self):
if self.model.cp > 1:
@@ -319,9 +334,9 @@ class SFTConfig(BaseConfig):
@model_validator(mode="after")
def validate_renderer_vs_vlm(self):
if self.renderer is not None and self.model.vlm is not None:
if self.model.vlm is not None:
raise ValueError(
"renderer is not supported for VLMs in SFT. The renderer tokenizes "
"renderer-only SFT does not support VLMs yet. The renderer tokenizes "
"text-only message dicts client-side and cannot handle image inputs."
)
return self
@@ -343,11 +358,6 @@ class SFTConfig(BaseConfig):
raise ValueError("Muon optimizer does not support FSDP CPU offload")
return self
@model_validator(mode="after")
def validate_and_disable_chunked_loss(self):
self.model.fused_lm_head_token_chunk_size = "disabled"
return self
@model_validator(mode="after")
def ep_only_with_custom_impl(self):
if self.model.ep != 1 and self.model.ep != "auto" and self.model.impl not in ("custom", "auto"):
@@ -18,15 +18,9 @@ from prime_rl.utils.config import BaseConfig
# -- Shared trainer configs (used by both SFT and RL trainers) --
AttnImplementation: TypeAlias = Literal["eager", "sdpa", "flash_attention_2", "flash_attention_3", "fa4"]
AttnImplementation: TypeAlias = Literal["flash_attention_2", "flash_attention_3", "flash_attention_4"]
EPCommBackend: TypeAlias = Literal["torch", "deepep"]
# User-facing name -> internal name. Users set `flash_attention_4` in configs,
# which gets rewritten to `fa4` before pydantic validation.
# We use `fa4` internally because `flash_attention_*` triggers transformers
# to attempt installing a kernel from hub.
_ATTN_ALIASES = {"flash_attention_4": "fa4"}
class GCConfig(BaseConfig):
interval: int = Field(50, ge=1)
@@ -116,11 +110,50 @@ class DebugModelConfig(BaseConfig):
"""Replace MoE token-choice routing with a round-robin assignment so every expert sees an equal share. Intended for fake-data smoke tests where untrained routing would otherwise OOM under severe imbalance. Gating scores are still gathered from the override indices so the forward pass stays consistent."""
MXFP8Recipe: TypeAlias = Literal["mxfp8_rceil", "mxfp8_rceil_wgrad_with_hp"]
_DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [
"lm_head",
"router",
# Use escaped dots — re.search treats `.` as any-char, so the previous
# "mlp.gate." pattern was also matching dense MLP `mlp.gate_proj` (the
# trailing `.` was matching `_`). That left the dense MLP gate projection
# 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)
"eh_proj",
"weights_proj",
"in_proj_a",
"in_proj_b",
]
class FP8Config(BaseConfig):
type: Literal["fp8"] = "fp8"
enable_grouped_gemm: bool = True
ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS
class MXFP8Config(BaseConfig):
type: Literal["mxfp8"] = "mxfp8"
recipe: MXFP8Recipe = "mxfp8_rceil"
enable_grouped_gemm: bool = True
enable_a2a: bool = True
ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS
QuantizationConfig: TypeAlias = Annotated[FP8Config | MXFP8Config, Field(discriminator="type")]
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."""
seq_len: int = 2048
"""Sequence length the model is trained on."""
attn: AttnImplementation = "flash_attention_2"
attn: AttnImplementation = "flash_attention_3"
"""Attention implementation. With CP enabled, ring attention uses the matching kernel family (FA2/FA3/FA4)."""
compile: CompileConfig | None = CompileConfig()
@@ -177,8 +210,7 @@ class ModelConfig(BaseModelConfig):
moe_use_grouped_mm: bool = True
"""Use grouped mm for MoE layers. Requires compute capability ≥ 9.0."""
fp8: bool = False
"""FP8 training via DeepGEMM. Replaces ``nn.Linear`` with FP8 blockwise linear and uses FP8 grouped GEMM for MoE experts. Requires SM90 (Hopper) GPUs and ``model.impl='custom'``."""
quantization: QuantizationConfig | None = None
index_cache: IndexCacheConfig | None = None
"""DSA IndexCache sub-configuration. If set, sparse-attention top-k indices are reused across decoder layers per the configured schedule (mirrors vLLM's IndexCache HF overrides). If None, every layer recomputes its own indices."""
@@ -195,14 +227,6 @@ class ModelConfig(BaseModelConfig):
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 1024
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. SFT training silently disables this (not supported yet)."""
@model_validator(mode="before")
@classmethod
def _normalize_attn_alias(cls, data):
"""Rewrite user-facing `flash_attention_4` to internal `fa4` before validation."""
if isinstance(data, dict) and data.get("attn") in _ATTN_ALIASES:
data["attn"] = _ATTN_ALIASES[data["attn"]]
return data
@model_validator(mode="after")
def trust_remote_code_only_with_hf(self):
"""Trust remote code only if the model is from HF."""
@@ -213,15 +237,19 @@ class ModelConfig(BaseModelConfig):
@model_validator(mode="after")
def cp_only_with_flash_attn(self):
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "fa4"]:
raise ValueError("CP is only supported with flash attention 2, flash attention 3, or fa4")
if self.cp > 1 and self.attn in ("flash_attention_3", "fa4") and self.impl != "custom":
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "flash_attention_4"]:
raise ValueError("CP is only supported with flash attention 2, 3, or 4")
if (
self.cp > 1
and self.attn in ("flash_attention_3", "flash_attention_4")
and self.impl not in ("custom", "auto")
):
# Both ring and ulysses route FA3/FA4 through our custom FlashAttention class:
# ring patches `_compute_attention` with the ring kernel, ulysses patches it with
# the all-to-all wrapper around the FA3/FA4 kernel. The HF path patches
# `_flash_attention_forward` which only wraps FA2.
raise ValueError(
f"CP with {self.attn} requires model.impl='custom' "
f"CP with {self.attn} requires model.impl='custom' or 'auto' "
"(FA3/FA4 paths are only implemented for the custom model attention class)"
)
return self
@@ -247,14 +275,14 @@ class ModelConfig(BaseModelConfig):
@model_validator(mode="after")
def flash_attention_4_only_with_custom_impl(self):
if self.attn == "fa4" and self.impl != "custom":
raise ValueError("Flash attention 4 is only supported with the custom implementation")
if self.attn == "flash_attention_4" and self.impl not in ("custom", "auto"):
raise ValueError("Flash attention 4 is only supported with model.impl='custom' or 'auto'")
return self
@model_validator(mode="after")
def fp8_only_with_custom_impl(self):
if self.fp8 and self.impl not in ("custom", "auto"):
raise ValueError("FP8 training is only supported with model.impl='custom' or 'auto'.")
def quantization_only_with_custom_impl(self):
if self.quantization is not None and self.impl not in ("custom", "auto"):
raise ValueError(f"{self.quantization.type} training is only supported with model.impl='custom' or 'auto'.")
return self
@model_validator(mode="after")
@@ -267,6 +295,12 @@ class ModelConfig(BaseModelConfig):
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'.")
return self
class TokenizerConfig(BaseConfig):
name: str | None = None
+34 -140
View File
@@ -1,6 +1,6 @@
[project]
name = "prime-rl"
version = "0.6.0"
version = "0.7.0"
description = "Async RL Training at Scale"
readme = "README.md"
requires-python = "~=3.12.0"
@@ -10,7 +10,6 @@ dependencies = [
"beartype>=0.21.0",
"datasets>=4.0.0",
"jaxtyping>=0.3.2",
"liger-kernel>=0.5.10",
"loguru>=0.7.3",
"pyarrow>=21.0.0",
"numpy>=2.2.6",
@@ -44,6 +43,7 @@ dependencies = [
"orjson>=3.10",
"pandas>=2.0",
"msgspec>=0.18",
"torchao>=0.17.0",
]
[project.scripts]
@@ -66,79 +66,12 @@ flash-attn-3 = ["flash_attn_3"]
flash-attn-cute = [
"flash-attn-4",
]
envs = [
"aime24-v1",
"aime25-v1",
"aime26-v1",
"alphabet-sort",
"alphabet-sort-v1",
"apex-shortlist-v1",
"arxivmath-v1",
"browsecomp-v1",
"code-golf-v1",
"color-codeword-v1",
"deepdive-v1",
"deepwiki-v1",
"forth-lang-v1",
"general-agent-v1",
"glossary-v1",
"gpqa-v1",
"graphwalks-v1",
"gsm8k-v1",
"i3-code-v1",
"i3-logic-v1",
"i3-math-v1",
"i3-science-v1",
"ifbench-v1",
"ifeval-v1",
"lean-v1",
"livecodebench-v1",
"longcot-mini-v1",
"longcot-v1",
"longpdfs-v1",
"math-env-v1",
"math-python",
"math500-v1",
"mmlu-pro-v1",
"mrcr-v2-v1",
"oolong-pairs-v1",
"oolong-real-v1",
"oolong-synth-v1",
"openseeker-v1",
"openthoughts-tblite-v1",
"papersearchqa-v1",
"patterned-needle-in-haystack-v1",
"prolog-v1",
"r2e-gym-v1",
"redsearcher-v1",
"reverse-text",
"reverse-text-v1",
"s1-deepresearch-v1",
"scaleswe-v1",
"simpleqa-v1",
"simpleqa-verified-v1",
"swebench-pro-v1",
"swebench-verified-v1",
"swelego-v1",
"tau2-bench-v1",
"terminal-bench-2-v1",
"tmax-v1",
"unscramble-v1",
"uuid-ctf-v1",
"verbatim-copy-v1",
"wideseek-v1",
"wiki-search",
"wiki-search-v1",
"wikispeedia-v1",
"wordle",
"wordle-v1",
]
disagg = [
"deep-ep ; platform_machine == 'x86_64'",
"deep-gemm ; platform_machine == 'x86_64'",
"deep-ep ; platform_machine == 'x86_64' or platform_machine == 'aarch64'",
"deep-gemm",
"nixl",
"nixl-cu12 ; platform_machine == 'x86_64'",
"vllm-router ; platform_machine == 'x86_64'",
"vllm-router",
]
gpt-oss = [
"kernels",
@@ -192,6 +125,21 @@ override-dependencies = [
"openenv-core",
]
# Environment packages (research-environments + verifiers) are auto-discovered as
# workspace members, so new envs need no per-package registration. Install them
# with `uv sync --all-packages`.
[tool.uv.workspace]
members = [
"deps/research-environments/environments/*/*",
"deps/verifiers/environments/*",
]
# tau2-synth-v1 and tau3-bench-v1 pin `tau2` forks/revs that conflict with the
# canonical tau2-bench-v1; a workspace shares one lock, so these can't coexist.
exclude = [
"deps/research-environments/environments/tool_use/tau2_synth_v1",
"deps/research-environments/environments/tool_use/tau3_bench_v1",
]
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
# compatible with protobuf 6. prime-sandboxes requires protobuf>=6.31.1; keep
# this capped to the validated protobuf major.
@@ -231,6 +179,7 @@ dion = false
deep-ep = false
deep-gemm = false
nixl-cu12 = false
torchao = false
[tool.uv.sources]
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
@@ -241,84 +190,29 @@ 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 }
aime24-v1 = { path = "deps/research-environments/environments/math/aime24_v1", editable = true }
aime25-v1 = { path = "deps/research-environments/environments/math/aime25_v1", editable = true }
aime26-v1 = { path = "deps/research-environments/environments/math/aime26_v1", editable = true }
alphabet-sort = { path = "deps/verifiers/environments/alphabet_sort", editable = true }
alphabet-sort-v1 = { path = "deps/verifiers/environments/alphabet_sort_v1", editable = true }
apex-shortlist-v1 = { path = "deps/research-environments/environments/math/apex_shortlist_v1", editable = true }
arxivmath-v1 = { path = "deps/research-environments/environments/math/arxivmath_v1", editable = true }
browsecomp-v1 = { path = "deps/research-environments/environments/search/browsecomp_v1", editable = true }
code-golf-v1 = { path = "deps/verifiers/environments/code_golf_v1", editable = true }
color-codeword-v1 = { path = "deps/verifiers/environments/color_codeword_v1", editable = true }
deepdive-v1 = { path = "deps/research-environments/environments/search/deepdive_v1", editable = true }
deepwiki-v1 = { path = "deps/verifiers/environments/deepwiki_v1", editable = true }
forth-lang-v1 = { path = "deps/research-environments/environments/code/forth_lang_v1", editable = true }
general-agent-v1 = { path = "deps/research-environments/environments/tool_use/general_agent_v1", editable = true }
glossary-v1 = { path = "deps/verifiers/environments/glossary_v1", editable = true }
gpqa-v1 = { path = "deps/research-environments/environments/science/gpqa_v1", editable = true }
graphwalks-v1 = { path = "deps/research-environments/environments/long_context/graphwalks_v1", editable = true }
gsm8k-v1 = { path = "deps/verifiers/environments/gsm8k_v1", editable = true }
i3-code-v1 = { path = "deps/research-environments/environments/code/i3_code_v1", editable = true }
i3-logic-v1 = { path = "deps/research-environments/environments/reasoning/i3_logic_v1", editable = true }
i3-math-v1 = { path = "deps/research-environments/environments/math/i3_math_v1", editable = true }
i3-science-v1 = { path = "deps/research-environments/environments/science/i3_science_v1", editable = true }
ifbench-v1 = { path = "deps/research-environments/environments/if/ifbench_v1", editable = true }
ifeval-v1 = { path = "deps/research-environments/environments/if/ifeval_v1", editable = true }
lean-v1 = { path = "deps/research-environments/environments/math/lean_v1", editable = true }
livecodebench-v1 = { path = "deps/research-environments/environments/code/livecodebench_v1", editable = true }
longcot-mini-v1 = { path = "deps/research-environments/environments/long_context/longcot_mini_v1", editable = true }
longcot-v1 = { path = "deps/research-environments/environments/long_context/longcot_v1", editable = true }
longpdfs-v1 = { path = "deps/research-environments/environments/long_context/longpdfs_v1", editable = true }
math-env-v1 = { path = "deps/research-environments/environments/math/math_env_v1", editable = true }
math-python = { path = "deps/verifiers/environments/math_python", editable = true }
math500-v1 = { path = "deps/research-environments/environments/math/math500_v1", editable = true }
mmlu-pro-v1 = { path = "deps/research-environments/environments/knowledge/mmlu_pro_v1", editable = true }
mrcr-v2-v1 = { path = "deps/research-environments/environments/long_context/mrcr_v2_v1", editable = true }
oolong-pairs-v1 = { path = "deps/research-environments/environments/long_context/oolong_pairs_v1", editable = true }
oolong-real-v1 = { path = "deps/research-environments/environments/long_context/oolong_real_v1", editable = true }
oolong-synth-v1 = { path = "deps/research-environments/environments/long_context/oolong_synth_v1", editable = true }
openseeker-v1 = { path = "deps/research-environments/environments/search/openseeker_v1", editable = true }
openthoughts-tblite-v1 = { path = "deps/research-environments/environments/terminal/openthoughts_tblite_v1", editable = true }
papersearchqa-v1 = { path = "deps/research-environments/environments/search/papersearchqa_v1", editable = true }
patterned-needle-in-haystack-v1 = { path = "deps/research-environments/environments/long_context/patterned_needle_in_haystack_v1", editable = true }
prolog-v1 = { path = "deps/research-environments/environments/reasoning/prolog_v1", editable = true }
r2e-gym-v1 = { path = "deps/research-environments/environments/swe/r2e_gym_v1", editable = true }
redsearcher-v1 = { path = "deps/research-environments/environments/search/redsearcher_v1", editable = true }
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
reverse-text-v1 = { path = "deps/verifiers/environments/reverse_text_v1", editable = true }
s1-deepresearch-v1 = { path = "deps/research-environments/environments/search/s1_deepresearch_v1", editable = true }
scaleswe-v1 = { path = "deps/research-environments/environments/swe/scaleswe_v1", editable = true }
simpleqa-v1 = { path = "deps/research-environments/environments/knowledge/simpleqa_v1", editable = true }
simpleqa-verified-v1 = { path = "deps/research-environments/environments/knowledge/simpleqa_verified_v1", editable = true }
swebench-pro-v1 = { path = "deps/research-environments/environments/swe/swebench_pro_v1", editable = true }
swebench-verified-v1 = { path = "deps/research-environments/environments/swe/swebench_verified_v1", editable = true }
swelego-v1 = { path = "deps/research-environments/environments/swe/swelego_v1", editable = true }
tau2-bench-v1 = { path = "deps/research-environments/environments/tool_use/tau2_bench_v1", editable = true }
terminal-bench-2-v1 = { path = "deps/research-environments/environments/terminal/terminal_bench_2_v1", editable = true }
tmax-v1 = { path = "deps/research-environments/environments/terminal/tmax_v1", editable = true }
unscramble-v1 = { path = "deps/research-environments/environments/reasoning/unscramble_v1", editable = true }
uuid-ctf-v1 = { path = "deps/research-environments/environments/reasoning/uuid_ctf_v1", editable = true }
verbatim-copy-v1 = { path = "deps/research-environments/environments/long_context/verbatim_copy_v1", editable = true }
wideseek-v1 = { path = "deps/research-environments/environments/search/wideseek_v1", editable = true }
wiki-search = { path = "deps/verifiers/environments/wiki_search", editable = true }
wiki-search-v1 = { path = "deps/verifiers/environments/wiki_search_v1", editable = true }
wikispeedia-v1 = { path = "deps/research-environments/environments/reasoning/wikispeedia_v1", editable = true }
wordle = { path = "deps/verifiers/environments/wordle", editable = true }
wordle-v1 = { path = "deps/verifiers/environments/wordle_v1", editable = true }
torch = { index = "pytorch-cu128" }
torchvision = { index = "pytorch-cu128" }
torchaudio = { index = "pytorch-cu128" }
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'" }
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" }
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl" }
vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.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.24.0/vllm-0.24.0+cu129-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" }
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" }
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'" },
]
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'" },
]
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" }
+2 -2
View File
@@ -59,9 +59,9 @@ if [ -n "$PRIME_RL_REF" ]; then
# startup. --inexact keeps the seeded venv's pre-built wheels
# (flash-attn-3, mamba-ssm) in place; uv only rebuilds them if the
# override's lockfile pins different versions.
( cd "$DEST" && uv sync --inexact --no-dev \
( cd "$DEST" && uv sync --inexact --no-dev --all-packages \
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
--extra envs --extra gpt-oss --extra modelexpress \
--extra gpt-oss --extra modelexpress \
--group mamba-ssm )
export VIRTUAL_ENV="$DEST/.venv"
export PATH="$DEST/.venv/bin:$PATH"
+32 -6
View File
@@ -2,11 +2,13 @@
SESSION_NAME="prime-rl"
OUTPUT_DIR="outputs"
AGENT="claude"
# Optional CLI parsing
# Supports:
# -s|--session-name NAME
# -o|--output-dir DIR
# -a|--agent AGENT (claude|codex, default: claude)
# Positional: [SESSION_NAME [OUTPUT_DIR]]
POSITIONAL=()
while [[ $# -gt 0 ]]; do
@@ -27,8 +29,17 @@ while [[ $# -gt 0 ]]; do
OUTPUT_DIR="$2"
shift 2
;;
-a|--agent)
if [[ -z "$2" ]]; then
echo "Error: --agent requires a value (claude|codex)" >&2
exit 1
fi
AGENT="$2"
shift 2
;;
-h|--help)
echo "Usage: $0 [-s SESSION_NAME] [-o OUTPUT_DIR] [SESSION_NAME [OUTPUT_DIR]]" >&2
echo "Usage: $0 [-s SESSION_NAME] [-o OUTPUT_DIR] [-a AGENT] [SESSION_NAME [OUTPUT_DIR]]" >&2
echo " -a, --agent claude|codex (default: claude)" >&2
exit 0
;;
--)
@@ -86,10 +97,10 @@ tmux send-keys -t "$SESSION_NAME:Logs.2" \
tmux send-keys -t "$SESSION_NAME:Logs.3" \
"tail -F ${LOG_DIR}/inference.log 2>/dev/null" C-m
# Window 2: Claude Code with log context
tmux new-window -t "$SESSION_NAME" -n "Claude"
tmux send-keys -t "$SESSION_NAME:Claude" \
"claude --permission-mode auto --append-system-prompt 'You are monitoring a prime-rl training run. The output directory is ${OUTPUT_DIR}. Log paths:
# Window 2: Agent (claude code or codex) with log context
tmux new-window -t "$SESSION_NAME" -n "Agent"
AGENT_PROMPT="You are monitoring a prime-rl training run. The output directory is ${OUTPUT_DIR}. Log paths:
Trainer: ${LOG_DIR}/trainer.log
All nodes: ${LOG_DIR}/trainer/node_*.log
All ranks: ${LOG_DIR}/trainer/torchrun/*/*/*/*.log
@@ -98,7 +109,22 @@ tmux send-keys -t "$SESSION_NAME:Claude" \
Envs: ${LOG_DIR}/envs/*/*.log
Train envs: ${LOG_DIR}/envs/train/*.log
You are running inside tmux session \"${SESSION_NAME}\". The Launcher window (window 0) is where the user runs launch commands. You can read its contents with: tmux capture-pane -t ${SESSION_NAME}:Launcher -p
Help the user monitor and debug this run.'" C-m
Help the user monitor and debug this run."
case "$AGENT" in
claude)
tmux send-keys -t "$SESSION_NAME:Agent" \
"claude --permission-mode auto --append-system-prompt \"${AGENT_PROMPT}\"" C-m
;;
codex)
tmux send-keys -t "$SESSION_NAME:Agent" \
"codex --yolo \"${AGENT_PROMPT}\"" C-m
;;
*)
echo "Error: unknown agent '$AGENT' (expected claude|codex)" >&2
exit 1
;;
esac
# Pane title styling
tmux set-option -t "$SESSION_NAME" -g pane-border-status top
+6 -10
View File
@@ -22,12 +22,14 @@ git submodule update --init --recursive
## Sync
```bash
uv sync # core only
uv sync --group dev # + pytest, ruff, pre-commit
uv sync --all-extras # recommended: envs, flash-attn, flash-attn-cute, etc.
uv sync # core only
uv sync --group dev # + pytest, ruff, pre-commit
uv sync --all-extras # + extras (flash-attn, flash-attn-cute, …)
uv sync --all-extras --all-packages # + all env packages (needed to train on them)
uv sync --package prime-rl --package gsm8k-v1 # core + just one env
```
The `envs` extra installs environments listed under `[project.optional-dependencies].envs`, resolved through `[tool.uv.sources]`. Adding a new env means adding its package name to `envs` and its editable source path to `[tool.uv.sources]`.
Environment packages under `deps/research-environments/environments/*/*` and `deps/verifiers/environments/*` are uv **workspace members**, auto-discovered — adding a new env needs no `pyproject.toml` change. They are opt-in: a plain `uv sync` / `--all-extras` does not install them (and would remove them if already present — re-run with `--all-packages`, or `--inexact` to keep them). Install all with `--all-packages`, or a subset with repeated `--package <env>` (include `--package prime-rl` to keep the core). If two envs pin conflicting transitive versions (all members share one lock), add the loser to `[tool.uv.workspace].exclude`.
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
@@ -41,12 +43,6 @@ CUDA_HOME=/usr/local/cuda uv pip install mamba-ssm
Requires `nvcc`. Without `mamba-ssm`, NemotronH falls back to HF's pure-PyTorch SSD path, which computes softplus in bf16 and yields ~0.4 KL divergence vs vLLM. Do **not** install `causal-conv1d` unless your GPU arch matches the prebuilt kernels — the code falls back to `nn.Conv1d` when it's absent.
### FP8 inference (GLM-5-FP8, etc.)
```bash
uv sync --group fp8-inference # installs the prebuilt deep-gemm wheel
```
### 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.
+4 -3
View File
@@ -37,9 +37,10 @@ uv run rl @ examples/reverse_text/rl.toml --dry-run
- 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_v1'))"`).
If a local env exists under `deps/research-environments/environments/` but does not
import, add it to the root `pyproject.toml` env extra, workspace members, and
`[tool.uv.sources]`, then run `uv sync --all-extras`.
If a local env exists under `deps/research-environments/environments/` or
`deps/verifiers/environments/` but does not import, install the env workspace
members with `uv sync --all-packages` (all) or `uv sync --package prime-rl
--package <env>` (one) — they're auto-discovered, no `pyproject.toml` edit needed.
## `sft` — SFT training
+25
View File
@@ -19,6 +19,31 @@ def apply_shared_vllm_patches():
monkey_patch_vllm_padded_input_scrub()
monkey_patch_return_routed_experts_with_nixl_connector()
monkey_patch_kv_xfer_finished_tolerate_freed()
monkey_patch_online_fp8_parameter_cast()
def monkey_patch_online_fp8_parameter_cast():
"""Pass plain tensors to vLLM's compiled block-FP8 caster.
Layerwise reload restores ``ModelWeightParameter`` objects before online
quantization. TorchDynamo recursively dispatches that tensor subclass while
tracing ``per_block_cast_to_fp8``. ``Parameter.data`` shares storage but is
a plain tensor, matching the input accepted during the initial model load.
"""
from torch.nn import Parameter
from vllm.model_executor.layers.quantization.online import fp8
original_cast = fp8.per_block_cast_to_fp8
if getattr(original_cast, "_prime_rl_unwraps_parameters", False):
return
def _per_block_cast_to_fp8(x, *args, **kwargs):
if isinstance(x, Parameter):
x = x.data
return original_cast(x, *args, **kwargs)
_per_block_cast_to_fp8._prime_rl_unwraps_parameters = True
fp8.per_block_cast_to_fp8 = _per_block_cast_to_fp8
def monkey_patch_kv_xfer_finished_tolerate_freed():
@@ -15,15 +15,21 @@ def serialize_routed_experts(routed_experts: Any, start: int = 0) -> dict[str, A
array = np.asarray(routed_experts)
assert array.ndim == 3
assert np.issubdtype(array.dtype, np.integer)
dtype = np.uint8
if array.size:
assert array.min() >= 0
assert array.max() <= np.iinfo(np.uint8).max
if array.max() > np.iinfo(np.uint8).max:
# Models with >256 experts (e.g. NemotronH Super/Ultra: 512) need wider
# indices. The payload self-describes via "dtype" so consumers pick it up.
assert array.max() <= np.iinfo(np.uint16).max
dtype = np.uint16
compact = np.ascontiguousarray(array.astype(np.uint8, copy=False))
compact = np.ascontiguousarray(array.astype(dtype, copy=False))
return {
"data": pybase64.b64encode(memoryview(compact)).decode("ascii"),
"shape": list(compact.shape),
"start": start,
"dtype": np.dtype(dtype).name,
}
+10 -5
View File
@@ -83,7 +83,8 @@ class Env:
def __init__(self, config: EnvConfig):
self.config = config
self.sampling_args: dict = {}
self.num_tasks: int = 0
self.num_tasks: int | None = 0
"""Task count reported by the server; ``None`` means the taskset is infinite."""
self.requires_group_scoring: bool = False
self._env_client: EnvClient | None = None
self._env_server_process: BaseProcess | None = None
@@ -112,9 +113,8 @@ class Env:
info = await self.env_client.info()
self.num_tasks = info.num_tasks
self.requires_group_scoring = info.requires_group_scoring
get_logger().info(
f"Env {self.name} ready: num_tasks={self.num_tasks} group_scoring={self.requires_group_scoring}"
)
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
get_logger().info(f"Env {self.name} ready: num_tasks={num_tasks} group_scoring={self.requires_group_scoring}")
async def _spawn(self, log_dir: Path, log_level: str, json_logging: bool) -> str:
"""Spawn a v1 EnvServer child process (it loads the env; we never do).
@@ -220,7 +220,12 @@ class EvalEnv(Env):
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
await super().start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
n = self.num_tasks if self.config.num_examples < 0 else min(self.config.num_examples, self.num_tasks)
if self.num_tasks is None:
if self.config.num_examples < 0:
raise ValueError(f"Eval env {self.name} has an infinite taskset — set num_examples to bound it")
n = self.config.num_examples
else:
n = self.num_tasks if self.config.num_examples < 0 else min(self.config.num_examples, self.num_tasks)
self.examples = [{"task_idx": i} for i in range(n)]
+19 -6
View File
@@ -101,6 +101,11 @@ MAX_CONSECUTIVE_EMPTY_BATCHES = 10
# resumed when the watcher advances ``policy.version``.
TARGET_LAG = 1
# Default wait for the trainer's startup weight broadcast when no ckpt block
# configures ``wait_for_weights_timeout`` (e.g. a from-scratch run). The
# broadcast is always coming, so wait rather than fail immediately.
STARTUP_WEIGHT_WAIT_TIMEOUT_S = 1200
class Orchestrator:
# Set in ``__init__``
@@ -315,18 +320,26 @@ class Orchestrator:
# trainer even when ``ckpt.skip_progress`` left the counter unrestored.
self.progress.step = self.resume_step + 1
get_logger().info(f"Resuming orchestrator from checkpoint step {self.resume_step}")
else:
get_logger().info("Training from scratch")
# Sync inference to the incoming policy before the first step when resuming or when using
# NCCL, which rendezvouses with the trainer's first-step broadcast (train.py). A fresh
# filesystem run needs no sync (the base model IS policy v0) and must not wait for a
# startup broadcast: runs registered after the trainer's first step never receive one.
if self.resume_step is not None or config.weight_broadcast.type == "nccl":
sync_version = self.resume_step if self.resume_step is not None else 0
check_exists = config.weight_broadcast.type != "nccl"
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else None
# Without a ckpt block, fall back to a default timeout instead of not waiting at all.
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else STARTUP_WEIGHT_WAIT_TIMEOUT_S
weights_path = get_weight_dir(
config.output_dir, self.resume_step, check_exists=check_exists, wait_timeout=wait_timeout
config.output_dir, sync_version, check_exists=check_exists, wait_timeout=wait_timeout
)
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=self.resume_step)
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=sync_version)
if self.lora_name is not None:
self.policy_inference.update_model_name(self.lora_name)
self.policy.model_name = self.lora_name
self.policy.version = self.resume_step
else:
get_logger().info("Training from scratch")
self.policy.version = sync_version
self.train_source = TrainSource(self.train_envs, seed=42)
self.eval_source: EvalSource | None = (
+43 -15
View File
@@ -30,6 +30,19 @@ from prime_rl.transport import TrainingSample
from prime_rl.utils.logger import get_logger
def payload_tokens(rollout: Rollout) -> int:
"""Token cost of the rollout's trainer-bound payload — the samples built by
``process_rollout``. This is what actually ships: forked traces can drop
branches with no trainable tokens, so ``Trace.num_total_tokens`` (which sums
over all branches) may overcount. For linear traces the two agree.
Zero-payload rollouts (no trainable samples at all) fall back to the trace
total so they still advance token batching — a degenerate all-zero-payload
stream then ships empty batches and trips the orchestrator's
consecutive-empty-batch abort instead of stalling the readiness check."""
return sum(len(sample.token_ids) for sample in rollout.samples) or rollout.num_total_tokens
class TrainSink:
"""Three-level train sink. Constructed once, fed via ``add(rollout)``."""
@@ -57,15 +70,18 @@ class TrainSink:
self.pre_filters = pre_filters
self.post_filters = post_filters
# Observation window for the next shipped batch: rollouts of groups
# finalized since the last ship (errored + filtered + survivors).
# In-progress groups stay out until they finalize.
self.pending_rollouts: TrainRollouts = TrainRollouts()
# Keyed by the dispatcher's group UUID. ``(env_name, task_idx)``
# isn't unique — the same task can be re-sampled while an
# earlier group is still in flight
self.pending_rollouts: TrainRollouts = TrainRollouts()
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
self.pending_batch: list[Rollout] = []
# Running token total of ``pending_batch`` (token-batched runs), kept in
# sync on append/pop so the readiness check never re-walks the uncached
# ``Trace.num_total_tokens`` graph property per arrival.
# Running payload-token total of ``pending_batch`` (token-batched
# runs), kept in sync on append/pop so the readiness check never
# re-sums per arrival.
self.pending_tokens: int = 0
# Reset by the orchestrator after each ship via ``reset_pre_filter_stats``
@@ -117,13 +133,18 @@ class TrainSink:
async def add(self, rollout: Rollout) -> TrainBatch | None:
"""Process one arrival; finalize the group on the ``group_size``-th
arrival; return a ``TrainBatch`` if the batch threshold is met."""
arrival; return a ``TrainBatch`` if the finalization pushed (or left)
the batch over its threshold. Arrivals into still-incomplete groups
never ship a batch."""
await self.process_rollout(rollout)
env_name = rollout.env_name
self.pending_rollouts.append(rollout)
self.pending_groups[rollout.group_id].append(rollout)
if len(self.pending_groups[rollout.group_id]) >= self.group_size_for(env_name):
await self.process_group(rollout.group_id)
if len(self.pending_groups[rollout.group_id]) < self.group_size_for(env_name):
return None
await self.process_group(rollout.group_id)
# ``pending_batch`` only grows on group finalization, so readiness is
# only re-checked here — the window of a shipped batch then always
# contains at least the group that finalized it.
ready = (
len(self.pending_batch) >= self.batch_size
if self.batch_size is not None
@@ -159,6 +180,12 @@ class TrainSink:
group = self.pending_groups.pop(group_id, [])
if not group:
return
# Window membership follows group finalization, not arrival: a rollout
# only becomes observable (metrics / persistence) once its whole group
# is finalized, so a batch's window never claims rollouts of a group
# that ships later. Dropped groups still land here — they were observed.
for r in group:
self.pending_rollouts.append(r)
env_name = group[0].env_name
task_idx = group[0].task.data.idx
survivors = [r for r in group if not r.has_error]
@@ -211,7 +238,7 @@ class TrainSink:
r.is_filtered = False
self.pending_batch.append(r)
if self.token_batch_size is not None:
self.pending_tokens += r.num_total_tokens
self.pending_tokens += payload_tokens(r)
# Per-group summary. One line per finalized group; per-filter
# detection breakdown lives at debug level in ``apply_filters``
@@ -238,7 +265,7 @@ class TrainSink:
cut = 0
running = 0
for i, r in enumerate(self.pending_batch):
running += r.num_total_tokens
running += payload_tokens(r)
cut = i + 1
if running >= self.token_batch_size:
break
@@ -253,11 +280,12 @@ class TrainSink:
# advantage stream and loss routing on each sample. Filtered rollouts don't ship.
samples: list[TrainingSample] = [sample for r in cohort if not r.is_filtered for sample in r.samples]
# ``rollouts`` is the whole arrival window (errored + filtered + survivors); ``samples`` is
# the shipped cohort's trainable payload. ``rollouts.effective`` / ``rollouts.metrics`` derive
# the clean subset + metric views on demand. Reset the window only when the batch actually
# ships (non-empty samples) — an empty batch is dropped unlogged by the orchestrator, so keep
# accumulating its arrivals (and any overflow) into the next shipped batch's window.
# ``rollouts`` is the observation window — every rollout of every group finalized since the
# last ship (errored + filtered + survivors) — while ``samples`` is the shipped cohort's
# trainable payload. ``rollouts.effective`` / ``rollouts.metrics`` derive the clean subset +
# metric views on demand. Reset the window only when the batch actually ships (non-empty
# samples) — an empty batch is dropped unlogged by the orchestrator, so keep accumulating its
# finalized groups (and any overflow) into the next shipped batch's window.
rollouts = self.pending_rollouts
if samples:
self.pending_rollouts = TrainRollouts()
+17 -6
View File
@@ -1,7 +1,10 @@
"""TrainSource: weighted round-robin across train envs, infinite pull.
Weights are each env's configured ``ratio`` (default 1, i.e. equal weight
per env). ``next_example`` reshuffles on cursor exhaustion."""
per env). A finite env serves a shuffled task-index table, reshuffled on
cursor exhaustion; an infinite env (``num_tasks is None``) streams a
monotonic ``task_idx`` — the server generates tasks on demand, so every
pull is a fresh task and there are no epochs to shuffle."""
from __future__ import annotations
@@ -22,17 +25,22 @@ class TrainSource:
if not self.envs:
raise ValueError("TrainSource needs at least one train env")
self.examples: dict[str, list[dict]] = {}
# A finite env's shuffled index table; ``None`` for an infinite env,
# whose cursor alone is the (monotonic) task_idx stream.
self.examples: dict[str, list[dict] | None] = {}
self.cursors: dict[str, int] = {}
# Group-scoring envs reserve ``group_size`` permits up front;
# per-rollout envs need 1
self.env_costs: dict[str, int] = {}
for env in self.envs:
# The orchestrator never loads the env: sample over the task-index
# range the server reported via info() (num_tasks).
rows: list[dict] = [{"task_idx": i, "env_name": env.name} for i in range(env.num_tasks)]
self.rng.shuffle(rows)
self.examples[env.name] = rows
# range the server reported via info() (num_tasks; None = infinite).
if env.num_tasks is None:
self.examples[env.name] = None
else:
rows: list[dict] = [{"task_idx": i, "env_name": env.name} for i in range(env.num_tasks)]
self.rng.shuffle(rows)
self.examples[env.name] = rows
self.cursors[env.name] = 0
self.env_costs[env.name] = env.config.group_size if env.requires_group_scoring else 1
@@ -45,6 +53,9 @@ class TrainSource:
return None
rows = self.examples[env_name]
cursor = self.cursors[env_name]
if rows is None: # infinite env: the cursor is the task_idx
self.cursors[env_name] = cursor + 1
return {"task_idx": cursor, "env_name": env_name}
if cursor >= len(rows):
self.rng.shuffle(rows)
cursor = 0
+6 -5
View File
@@ -147,11 +147,12 @@ class Rollout(vf.Trace[DataT], Generic[DataT]):
@dataclass
class TrainBatch:
"""``rollouts`` is the full arrival window since the last ship (errored + filtered included; its
``.effective`` / ``.metrics`` views drive logging). ``samples`` is the trainer-bound payload (the
shipped cohort's post-filter survivors) — an empty list means nothing ships, which would stall the
trainer. Trainable counts derive from ``rollouts`` (``r.is_trainable``) and token totals from
``samples``, so neither is carried as a field."""
"""``rollouts`` is the observation window since the last ship — every rollout of every group
finalized in that span (errored + filtered included; rollouts of still-incomplete groups wait
for a later window). Its ``.effective`` / ``.metrics`` views drive logging. ``samples`` is the
trainer-bound payload (the shipped cohort's post-filter survivors) — an empty list means nothing
ships, which would stall the trainer. Trainable counts derive from ``rollouts``
(``r.is_trainable``) and token totals from ``samples``, so neither is carried as a field."""
rollouts: TrainRollouts
samples: list[TrainingSample]
+2 -2
View File
@@ -67,10 +67,10 @@ source .venv/bin/activate
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
# inside the task because unexported vars in .env don't cross srun even with normal
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras'
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
{% else %}
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
uv sync --all-extras
uv sync --all-extras --all-packages
{% endif %}
# Print inference URLs
@@ -150,10 +150,10 @@ source .venv/bin/activate
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
# inside the task because unexported vars in .env don't cross srun even with normal
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras'
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
{% else %}
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
uv sync --all-extras
uv sync --all-extras --all-packages
{% endif %}
{% if pre_run_command %}
@@ -54,10 +54,10 @@ source $PROJECT_DIR/.venv/bin/activate
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
# inside the task because unexported vars in .env don't cross srun even with normal
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras'
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
{% else %}
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
cd $PROJECT_DIR && uv sync --all-extras
cd $PROJECT_DIR && uv sync --all-extras --all-packages
{% endif %}
@@ -31,7 +31,7 @@ export PROJECT_DIR={{ project_dir }}
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
uv sync --all-extras
uv sync --all-extras --all-packages
{% if pre_run_command %}
# Pre-run command
@@ -31,7 +31,7 @@ export PROJECT_DIR={{ project_dir }}
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
uv sync --all-extras
uv sync --all-extras --all-packages
{% if pre_run_command %}
# Pre-run command
+1 -7
View File
@@ -7,12 +7,6 @@ import numpy as np
from prime_rl.trainer.utils import balanced_partition
from prime_rl.transport.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
ROUTED_EXPERTS_DTYPE_ITEMSIZE = {
"uint8": 1,
"int16": 2,
"int32": 4,
}
# Backfill value per component weight stream when a packed sample doesn't
# carry it: absent rl means weight 1.0 on the loss mask, absent ce/ref_kl
# means no component (weight 0.0).
@@ -28,7 +22,7 @@ def _copy_routed_experts(routed_experts: RoutedExperts) -> RoutedExperts:
def _routed_experts_row_size(routed_experts: RoutedExperts) -> int:
return routed_experts.shape[1] * routed_experts.shape[2] * ROUTED_EXPERTS_DTYPE_ITEMSIZE[routed_experts.dtype]
return routed_experts.shape[1] * routed_experts.shape[2] * np.dtype(routed_experts.dtype).itemsize
def _slice_routed_experts(routed_experts: RoutedExperts, seq_len: int) -> RoutedExperts:
+2 -2
View File
@@ -1,3 +1,3 @@
from prime_rl.trainer.distributed.expert_parallel import DeepEPExpertParallel, get_ep_group
from prime_rl.trainer.distributed.expert_parallel import DeepEPExpertParallel, MXFP8AllToAllExpertParallel, get_ep_group
__all__ = ["DeepEPExpertParallel", "get_ep_group"]
__all__ = ["DeepEPExpertParallel", "MXFP8AllToAllExpertParallel", "get_ep_group"]
@@ -1,7 +1,67 @@
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):
@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):
+64 -41
View File
@@ -26,8 +26,15 @@ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, Genera
from transformers.tokenization_utils import PreTrainedTokenizer
from transformers.utils.import_utils import is_flash_attn_3_available
from prime_rl.configs.trainer import ActivationCheckpointConfig, CompileConfig, ModelConfig, TokenizerConfig
from prime_rl.trainer.distributed import DeepEPExpertParallel
from prime_rl.configs.trainer import (
ActivationCheckpointConfig,
CompileConfig,
FP8Config,
ModelConfig,
MXFP8Config,
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,
@@ -46,6 +53,8 @@ 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
from prime_rl.trainer.models.layers.mxfp8_grouped_gemm import apply_mxfp8_moe_grouped_gemm
from prime_rl.trainer.models.layers.mxfp8_linear import replace_linear_with_mxfp8_linear
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.trainer.weights import (
load_state_dict,
@@ -273,7 +282,7 @@ def _patch_qwen3_5_linear_attn_varlen():
):
attn_impl = getattr(self.config, "_attn_implementation", None)
cu_seqlens = None
if attn_impl in ("flash_attention_2", "flash_attention_3", "fa4") and position_ids is not None:
if attn_impl in ("flash_attention_2", "flash_attention_3", "flash_attention_4") and position_ids is not None:
pids = position_ids
if pids.ndim == 3:
pids = pids[0]
@@ -501,17 +510,14 @@ def get_model(
)
# GPT-OSS only supports FlashAttention via kernels-community/vllm-flash-attn3, which requires Hopper (SM 90).
# On other architectures (e.g. Blackwell), users must fall back to eager attention.
HOPPER_MAJOR = 9
if getattr(model_config, "model_type", "") == "gpt_oss":
if config.attn != "eager":
major, minor = torch.cuda.get_device_capability()
if major != HOPPER_MAJOR:
raise ValueError(
f"GPT-OSS requires 'attn = \"eager\"' on non-Hopper GPUs (detected SM {major}{minor}). "
f"The only flash attention kernel supported by GPT-OSS (kernels-community/vllm-flash-attn3) is Hopper-only. "
f'Set [trainer.model] attn = "eager" in your config.'
)
major, minor = torch.cuda.get_device_capability()
if major != HOPPER_MAJOR:
raise ValueError(
f"GPT-OSS requires Hopper (SM 90) for flash attention, detected SM {major}{minor}. "
f"GPT-OSS is not supported on non-Hopper GPUs."
)
# Enable hub kernels for GPT-OSS (disabled by default to avoid interfering with other models).
import transformers.integrations.hub_kernels as _hub_kernels
@@ -527,7 +533,11 @@ def get_model(
if subconfig is not None and hasattr(subconfig, "use_cache"):
subconfig.use_cache = False
model_config.use_grouped_mm = config.moe_use_grouped_mm
model_config.fp8 = config.fp8
# 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
@@ -834,19 +844,21 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
# All ranks read just the key names (cheap) to determine the path independently.
# Only master loads the full state dict when conversion is actually needed.
if isinstance(model, PreTrainedModelPrimeRL):
snapshot_keys = dict.fromkeys(load_state_dict_keys(snapshot_path))
source_path = snapshot_path
convert_dir = config.conversion_dir or source_path
snapshot_keys = dict.fromkeys(load_state_dict_keys(source_path))
model_keys = dict.fromkeys(model.state_dict().keys())
if model.is_hf_state_dict(snapshot_keys) and model.is_prime_state_dict(model_keys):
logger.warning(
"Found HF weight format in snapshot state dict and PrimeRL weight format in model state dict. Trying to auto-convert..."
)
snapshot_path = snapshot_path / "prime"
snapshot_path = convert_dir / "prime"
if not snapshot_path.exists() and get_world().is_master:
logger.debug(
f"Converting snapshot state dict to PrimeRL format and saving to {snapshot_path} on master rank. This is a one-time operation."
)
snapshot_state_dict = load_state_dict(snapshot_path.parent)
snapshot_state_dict = load_state_dict(source_path)
model.convert_to_prime(snapshot_state_dict)
save_state_dict(snapshot_state_dict, snapshot_path)
del snapshot_state_dict
@@ -855,12 +867,12 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
logger.warning(
"Found PrimeRL weight format in snapshot state dict and HF weight format in model state dict. Trying to auto-convert..."
)
snapshot_path = snapshot_path / "hf"
snapshot_path = convert_dir / "hf"
if not snapshot_path.exists() and get_world().is_master:
logger.debug(
f"Converting snapshot state dict to HF format and saving to {snapshot_path} on master rank. This is a one-time operation."
)
snapshot_state_dict = load_state_dict(snapshot_path.parent)
snapshot_state_dict = load_state_dict(source_path)
model.convert_to_hf(snapshot_state_dict)
save_state_dict(snapshot_state_dict, snapshot_path)
del snapshot_state_dict
@@ -1035,13 +1047,43 @@ def apply_compile(model: nn.Module, compile_config: CompileConfig):
get_logger().info(f"Compiled {len(language_model.layers)} layers (fullgraph={compile_config.fullgraph})")
def apply_quantization(model: nn.Module, config: ModelConfig) -> None:
"""Swap dense linears and MoE expert GEMMs 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.
"""
quant = config.quantization
if quant is None:
return
if isinstance(quant, FP8Config):
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):
raise ValueError(
f"MXFP8 quantization requires SM100 (Blackwell) or newer, 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":
parallelize_plan = ExpertParallel()
quant = config.quantization
if isinstance(quant, MXFP8Config) and quant.enable_a2a:
parallelize_plan = MXFP8AllToAllExpertParallel()
else:
parallelize_plan = ExpertParallel()
else:
parallelize_plan = DeepEPExpertParallel()
parallelize_module(
@@ -1086,36 +1128,18 @@ def _validate_flash_attn_4_installed() -> None:
)
def _register_fa4_attention_interface() -> None:
"""Register a dummy `fa4` attention with transformers so AutoConfig accepts it.
The `flash_attention_*` naming pattern triggers transformers to attempt
installing a kernel from the hub, so we use the short name `fa4` internally.
This dummy is never called because fa4 is only supported with our custom
model implementation.
"""
from transformers import AttentionInterface
def _noop(*args, **kwargs) -> None:
pass
AttentionInterface.register("fa4", _noop)
def setup_model(
config: ModelConfig,
parallel_dims: ParallelDims,
loading_from_checkpoint_later: bool = False,
fused_cross_entropy: bool | str = False,
) -> nn.Module:
if config.attn == "flash_attention_3" and not is_flash_attn_3_available():
raise ValueError(
"Flash attention 3 is only supported if the flash_attn_3 package is installed. Install with `uv pip install 'flash-attn-3 @ git+https://github.com/Dao-AILab/flash-attention.git@main#subdirectory=hopper' --no-build-isolation`"
)
if config.attn == "fa4":
if config.attn == "flash_attention_4":
_validate_flash_attn_4_installed()
_register_fa4_attention_interface()
logger = get_logger()
@@ -1140,10 +1164,9 @@ def setup_model(
if isinstance(config.fused_lm_head_token_chunk_size, int):
lm_head_chunk_size = config.fused_lm_head_token_chunk_size
inject_prime_lm_head(model, chunk_size=lm_head_chunk_size, fused_cross_entropy=fused_cross_entropy)
inject_prime_lm_head(model, chunk_size=lm_head_chunk_size)
if config.fp8:
replace_linear_with_fp8_blockwise_linear(model)
apply_quantization(model, config)
# Apply LoRA before FSDP setup
if config.lora is not None:
@@ -3,7 +3,6 @@ from dataclasses import dataclass
from typing import Optional, Union
import torch
import torch.nn.functional as F
from torch import nn
from transformers.cache_utils import Cache
from transformers.generation import GenerationMixin
@@ -105,78 +104,6 @@ class AfmoeAttentionBase(nn.Module):
return self.o_proj(attn_output)
class AfmoeSDPAAttention(AfmoeAttentionBase):
"""AFMoE attention using PyTorch's scaled_dot_product_attention."""
def attn_projections(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states).view(hidden_shape)
key_states = self.k_proj(hidden_states).view(hidden_shape)
value_states = self.v_proj(hidden_states).view(hidden_shape)
gate_states = self.gate_proj(hidden_states)
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
value_states = value_states.transpose(1, 2)
if self.is_local_attention:
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
key_states = _repeat_kv(key_states, self.num_key_value_groups)
value_states = _repeat_kv(value_states, self.num_key_value_groups)
return query_states, key_states, value_states, gate_states
def _attention_core(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
attention_mask: torch.Tensor | None = None,
dropout_p: float = 0.0,
) -> torch.Tensor:
return F.scaled_dot_product_attention(
query_states,
key_states,
value_states,
attn_mask=attention_mask,
dropout_p=dropout_p,
is_causal=attention_mask is None,
scale=self.scaling,
)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: torch.Tensor | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, None]:
query_states, key_states, value_states, gate_states = self.attn_projections(hidden_states, position_embeddings)
dropout_p = self.attention_dropout if self.training else 0.0
attn_output = self._attention_core(
query_states,
key_states,
value_states,
attention_mask=attention_mask,
dropout_p=dropout_p,
)
return self.output_proj(attn_output, gate_states), None
class AfmoeFlashAttention(AfmoeAttentionBase):
"""AFMoE attention using Flash Attention varlen functions."""
@@ -263,10 +190,9 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
AFMOE_ATTN_IMPL2CLASS = {
"sdpa": AfmoeSDPAAttention,
"flash_attention_2": functools.partial(AfmoeFlashAttention, flash_attn_version=2),
"flash_attention_3": functools.partial(AfmoeFlashAttention, flash_attn_version=3),
"fa4": functools.partial(AfmoeFlashAttention, flash_attn_version=4),
"flash_attention_4": functools.partial(AfmoeFlashAttention, flash_attn_version=4),
}
@@ -299,8 +225,6 @@ def _get_afmoe_attention(config: AfmoeConfig, layer_idx: int) -> nn.Module:
)
attn_impl = config._attn_implementation
if attn_impl == "eager":
attn_impl = "sdpa"
if attn_impl not in AFMOE_ATTN_IMPL2CLASS:
supported = list(AFMOE_ATTN_IMPL2CLASS.keys())
@@ -394,7 +318,7 @@ class AfmoePreTrainedModel(PreTrainedModelPrimeRL):
"k_norm",
"norm",
]
_supports_sdpa = True
_supports_sdpa = False
_supports_flash_attn = True
_supports_flex_attn = False
_supports_attention_backend = True
@@ -478,7 +402,7 @@ class AfmoeModel(AfmoePreTrainedModel):
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
use_flash = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4")
use_flash = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4")
if use_flash:
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
+16
View File
@@ -21,6 +21,22 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
"""PrimeRL models use custom MoE implementations and don't support dynamic experts implementation."""
return False
def _check_and_adjust_attn_implementation(
self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
) -> str:
"""Bypass transformers' flash attention availability checks.
PrimeRL custom models dispatch attention through their own ``ATTN_IMPL2CLASS``
dictionaries, not through transformers' ``ALL_ATTENTION_FUNCTIONS``. The default
``_check_and_adjust_attn_implementation`` validates that the requested flash
attention package is installed and the device is supported, which fails on
CPU-only machines and is unnecessary because we never call transformers'
attention dispatch for custom models.
"""
if attn_implementation is None:
attn_implementation = "flash_attention_3"
return attn_implementation
def get_correct_experts_implementation(self, requested_experts: str | None) -> str:
"""PrimeRL models always use eager experts implementation."""
return "eager"
+25
View File
@@ -37,3 +37,28 @@ def quantize_to_fp8_blockwise(weight: Tensor, block_size: int = 128) -> tuple[Te
quantized = blocks_fp8.permute(0, 2, 1, 3).reshape(padded_rows, padded_cols)[:rows, :cols].contiguous()
return quantized, scales.float().contiguous()
def quantize_to_vllm_kernel_format(weight: Tensor, block_size: int = 128) -> tuple[Tensor, Tensor]:
"""Quantize a weight into the FP8 layout used by vLLM kernels.
Hopper kernels consume the regular blockwise scale grid. On SM100, vLLM's
DeepGEMM kernels instead use UE8M0 scales in an architecture-specific packed
layout. Reuse vLLM's own post-processing so tensors sent over the kernel
weight-transfer path have the same representation as the loaded parameters.
"""
quantized, scales = quantize_to_fp8_blockwise(weight, block_size)
if not weight.is_cuda or torch.cuda.get_device_capability(weight.device) != (10, 0):
return quantized, scales
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
deepgemm_post_process_fp8_weight_block,
)
return deepgemm_post_process_fp8_weight_block(
wq=quantized,
ws=scales,
quant_block_shape=(block_size, block_size),
use_e8m0=True,
)
@@ -121,7 +121,7 @@ class Glm4MoePreTrainedModel(PreTrainedModelPrimeRL):
_no_split_modules = ["Glm4MoeDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_supports_flex_attn = True
_can_compile_fullgraph = False
_supports_attention_backend = True
@@ -216,7 +216,7 @@ class Glm4MoeModel(Glm4MoePreTrainedModel):
if inputs_embeds is None:
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
else:
@@ -2,7 +2,7 @@ import torch
from torch import Tensor
from prime_rl.trainer.conversion_utils import get_max_layer_num
from prime_rl.trainer.models.fp8 import quantize_to_fp8_blockwise
from prime_rl.trainer.models.fp8 import quantize_to_vllm_kernel_format
def _is_moe_layer(state_dict: dict[str, Tensor], layer_idx: int) -> bool:
@@ -157,7 +157,7 @@ def convert_tt_layer_to_vllm_kernel(
def add_maybe_fp8(name: str, tensor: Tensor) -> None:
if quantize_fp8 and tensor.ndim == 2:
fp8_weight, scale = quantize_to_fp8_blockwise(tensor)
fp8_weight, scale = quantize_to_vllm_kernel_format(tensor)
out[name] = fp8_weight
scale_name = name.removesuffix(".weight") + ".weight_scale_inv"
out[scale_name] = scale
@@ -231,8 +231,8 @@ def convert_tt_layer_to_vllm_kernel(
w2_fp8: list[Tensor] = []
w2_scales: list[Tensor] = []
for expert_idx in range(w1.shape[0]):
expert_w13_fp8, expert_w13_scales = quantize_to_fp8_blockwise(w13[expert_idx])
expert_w2_fp8, expert_w2_scales = quantize_to_fp8_blockwise(w2[expert_idx])
expert_w13_fp8, expert_w13_scales = quantize_to_vllm_kernel_format(w13[expert_idx])
expert_w2_fp8, expert_w2_scales = quantize_to_vllm_kernel_format(w2[expert_idx])
w13_fp8.append(expert_w13_fp8)
w13_scales.append(expert_w13_scales)
w2_fp8.append(expert_w2_fp8)
@@ -126,7 +126,7 @@ class GlmMoeDsaPreTrainedModel(PreTrainedModelPrimeRL):
_no_split_modules = ["GlmMoeDsaDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_supports_flex_attn = True
_can_compile_fullgraph = False
_supports_attention_backend = True
@@ -249,7 +249,7 @@ def _grouped_per_token_fp8_kernel(
@triton.jit
def _grouped_per_channel_fp8_sm90_kmajor_kernel(
def _grouped_per_channel_fp8_kernel(
x_ptr,
block_to_group_ptr,
starts_ptr,
@@ -264,6 +264,7 @@ def _grouped_per_channel_fp8_sm90_kmajor_kernel(
stride_sf0,
stride_sf1,
USE_UE8M0: tl.constexpr,
K_MAJOR: tl.constexpr,
BLOCK_K: tl.constexpr,
BLOCK_N: tl.constexpr,
):
@@ -293,8 +294,20 @@ def _grouped_per_channel_fp8_sm90_kmajor_kernel(
scale = tl.exp2(tl.ceil(tl.log2(scale)))
y = x / scale[None, :]
flat_base = block_start.to(tl.int64) * BLOCK_K * cols
out_ptrs = out_ptr + flat_base + col_offsets_i64[:, None] * aligned_m + row_offsets_i64[None, :]
tl.store(out_ptrs, tl.trans(y).to(tl.float8e4nv), mask=valid_cols[:, None] & (row_offsets[None, :] < aligned_m))
if K_MAJOR:
out_ptrs = out_ptr + flat_base + col_offsets_i64[:, None] * aligned_m + row_offsets_i64[None, :]
tl.store(
out_ptrs,
tl.trans(y).to(tl.float8e4nv),
mask=valid_cols[:, None] & (row_offsets[None, :] < aligned_m),
)
else:
out_ptrs = out_ptr + flat_base + row_offsets_i64[:, None] * cols + col_offsets_i64[None, :]
tl.store(
out_ptrs,
y.to(tl.float8e4nv),
mask=(row_offsets[:, None] < aligned_m) & valid_cols[None, :],
)
tl.store(
sf_ptr + pid_blk * stride_sf0 + col_offsets_i64 * stride_sf1,
scale,
@@ -477,7 +490,7 @@ def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
if block_to_group.numel() == 0:
return out, sf.T
grid = (block_to_group.numel(), ceil_div(x.size(1), 128))
_grouped_per_channel_fp8_sm90_kmajor_kernel[grid](
_grouped_per_channel_fp8_kernel[grid](
x,
block_to_group,
starts_tensor,
@@ -492,6 +505,7 @@ def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
sf.stride(0),
sf.stride(1),
USE_UE8M0=use_ue8m0,
K_MAJOR=True,
BLOCK_K=gran_k,
BLOCK_N=128,
num_warps=4,
@@ -499,6 +513,48 @@ def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
return out, sf.T
def grouped_per_channel_cast_to_fp8_rowmajor_triton(
x: torch.Tensor,
padded_total_m: int,
block_to_group: torch.Tensor,
starts_tensor: torch.Tensor,
actual_ms_tensor: torch.Tensor,
ks_tensor: torch.Tensor,
block_starts_tensor: torch.Tensor,
use_ue8m0: bool,
gran_k: int = GROUP_ALIGNMENT,
) -> Tuple[torch.Tensor, torch.Tensor]:
assert x.dim() == 2
assert gran_k == GROUP_ALIGNMENT
out = torch.empty((padded_total_m, x.size(1)), device=x.device, dtype=torch.float8_e4m3fn)
total_blocks = padded_total_m // gran_k
sf = torch.empty((total_blocks, x.size(1)), device=x.device, dtype=torch.float32)
if block_to_group.numel() == 0:
return out, sf
grid = (block_to_group.numel(), ceil_div(x.size(1), 128))
_grouped_per_channel_fp8_kernel[grid](
x,
block_to_group,
starts_tensor,
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
out,
sf,
x.size(1),
x.stride(0),
x.stride(1),
sf.stride(0),
sf.stride(1),
USE_UE8M0=use_ue8m0,
K_MAJOR=False,
BLOCK_K=gran_k,
BLOCK_N=128,
num_warps=4,
)
return out, sf
def grouped_per_block_cast_to_fp8_triton(
x: torch.Tensor, use_ue8m0: bool, gran_k: int = GROUP_ALIGNMENT
) -> Tuple[torch.Tensor, torch.Tensor]:
@@ -148,6 +148,9 @@ class LagunaConfig(PretrainedConfig):
for params in nested.values():
params.setdefault("rope_type", "default")
# vLLM ignores this override and derives YaRN scaling from factor; match it for rollout/trainer parity.
nested["full_attention"].pop("attention_factor", None)
self.rope_parameters = nested
self.partial_rotary_factor = None
@@ -22,7 +22,7 @@ from prime_rl.trainer.models.laguna.converting_laguna import (
convert_prime_layer_to_hf,
convert_prime_to_hf,
)
from prime_rl.trainer.models.layers.attn import AttentionConfig, FlashAttention, SDPAAttention
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
@@ -138,70 +138,16 @@ class LagunaFlashAttention(FlashAttention):
return self.o_proj(attn_output), None
class LagunaSDPAAttention(SDPAAttention):
def __init__(self, config: LagunaConfig, layer_idx: int, num_heads: int):
super().__init__(_laguna_attention_config(config, num_heads))
self.num_heads = num_heads
self.config = config
self.layer_idx = layer_idx
self.attention_dropout = config.attention_dropout
self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
self.sliding_window = config.sliding_window if self.is_local_attention else None
self.g_proj = nn.Linear(config.hidden_size, num_heads, bias=False)
self.o_proj = nn.Linear(num_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)
def _attention_core(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
attention_mask: torch.Tensor | None = None,
) -> torch.Tensor:
key_states = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
value_states = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
dropout_p = 0.0 if not self.training else self.attention_dropout
out = F.scaled_dot_product_attention(
query_states,
key_states,
value_states,
attn_mask=attention_mask,
dropout_p=dropout_p,
is_causal=attention_mask is None,
)
out = out.transpose(1, 2).contiguous()
return out.view(out.shape[0], out.shape[1], -1)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
attention_mask: torch.Tensor | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
query_states, key_states, value_states = self.attn_projections(hidden_states, position_embeddings)
attn_output = self._attention_core(query_states, key_states, value_states, attention_mask=attention_mask)
input_shape = hidden_states.shape[:-1]
attn_output = attn_output.view(*input_shape, self.num_heads, self.head_dim)
gate = F.softplus(self.g_proj(hidden_states).float()).to(attn_output.dtype)
attn_output = (attn_output * gate.unsqueeze(-1)).view(*input_shape, -1)
return self.o_proj(attn_output), None
def _get_laguna_attention(config: LagunaConfig, layer_idx: int):
attn_impl = config._attn_implementation
if attn_impl == "eager":
attn_impl = "sdpa"
num_heads = config.num_attention_heads_per_layer[layer_idx]
match attn_impl:
case "flash_attention_2":
return LagunaFlashAttention(config, layer_idx, num_heads, flash_attn_version=2)
case "flash_attention_3":
return LagunaFlashAttention(config, layer_idx, num_heads, flash_attn_version=3)
case "fa4":
case "flash_attention_4":
return LagunaFlashAttention(config, layer_idx, num_heads, flash_attn_version=4)
case "sdpa":
return LagunaSDPAAttention(config, layer_idx, num_heads)
case _:
raise ValueError(f"Laguna attention does not support '{config._attn_implementation}'.")
@@ -286,7 +232,7 @@ class LagunaPreTrainedModel(PreTrainedModelPrimeRL):
_no_split_modules = ["LagunaDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_supports_flex_attn = False
_can_compile_fullgraph = False
_supports_attention_backend = True
@@ -354,7 +300,7 @@ class LagunaModel(LagunaPreTrainedModel):
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
causal_mask_mapping = dict.fromkeys(set(self.config.layer_types), None)
+3 -102
View File
@@ -3,7 +3,6 @@ from dataclasses import dataclass
from typing import Literal
import torch
import torch.nn.functional as F
from torch import nn
from .norms import RMSNorm, RMSNormConfig
@@ -42,7 +41,7 @@ class AttentionConfig:
# TODO: Does torch compile support config._attn_implementation forking?
# If so, we can combine FlashAttention and SDPAAttention into one class
# If so, we can combine FlashAttention variants into one class
# Otherwise, do ABC or something to make the signatures match
@@ -183,108 +182,10 @@ class FlashAttention(nn.Module):
return attn_output, None
class SDPAAttention(nn.Module):
"""SDPA Attention"""
def __init__(self, config: AttentionConfig):
super().__init__()
self.head_dim = config.head_dim
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
self.scaling = self.head_dim**-0.5
self.is_causal = config.is_causal
self.q_proj = nn.Linear(
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
)
self.k_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.v_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.output_bias)
self.use_qk_norm = config.use_qk_norm
self.qk_norm_type = config.qk_norm_type
if self.use_qk_norm:
if self.qk_norm_type == "per_layer":
self.q_norm = RMSNorm(
RMSNormConfig(hidden_size=config.num_attention_heads * self.head_dim, eps=config.rms_norm_eps)
)
self.k_norm = RMSNorm(
RMSNormConfig(hidden_size=config.num_key_value_heads * self.head_dim, eps=config.rms_norm_eps)
)
else:
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
def attn_projections(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
if self.use_qk_norm and self.qk_norm_type == "per_layer":
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
query_states = query_states.view(hidden_shape)
key_states = key_states.view(hidden_shape)
value_states = value_states.view(hidden_shape)
if self.use_qk_norm and self.qk_norm_type == "per_head":
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
value_states = value_states.transpose(1, 2)
if position_embeddings is not None:
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
return query_states, key_states, value_states
def _attention_core(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
) -> torch.Tensor:
key_states = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
value_states = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
out = F.scaled_dot_product_attention(query_states, key_states, value_states, is_causal=True)
out = out.transpose(1, 2).contiguous()
return out.view(out.shape[0], out.shape[1], -1)
def output_proj(self, attn_output: torch.Tensor) -> torch.Tensor:
return self.o_proj(attn_output)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
query_states, key_states, value_states = self.attn_projections(hidden_states, position_embeddings)
attn_output = self._attention_core(query_states, key_states, value_states)
attn_output = self.output_proj(attn_output)
return attn_output, None
ATTN_IMPL2CLASS = {
"flash_attention_2": functools.partial(FlashAttention, flash_attn_version=2),
"sdpa": SDPAAttention,
"flash_attention_3": functools.partial(FlashAttention, flash_attn_version=3),
"fa4": functools.partial(FlashAttention, flash_attn_version=4),
"flash_attention_4": functools.partial(FlashAttention, flash_attn_version=4),
}
@@ -298,7 +199,7 @@ def substitute_ring_attn(
from .ring_attn import ring_fa3_varlen_func, ring_fa4_varlen_func
if attn_impl == "fa4":
if attn_impl == "flash_attention_4":
ring_func = ring_fa4_varlen_func
elif attn_impl == "flash_attention_3":
ring_func = ring_fa3_varlen_func
+54 -13
View File
@@ -18,6 +18,45 @@ import torch
import torch.distributed as dist
def _build_seq_idx(boundaries: list[int], seq_len: int, device: torch.device) -> torch.Tensor:
"""Return the packed-document id for each token in a full CP sequence."""
if boundaries[0] != 0 or boundaries[-1] != seq_len:
raise ValueError(f"cu_seqlens must span the full sequence length {seq_len}, got {boundaries}")
seq_idx = torch.empty(seq_len, dtype=torch.int32, device=device)
for sequence_id, (start, end) in enumerate(zip(boundaries[:-1], boundaries[1:])):
if end <= start:
raise ValueError(f"cu_seqlens must be strictly increasing, got {boundaries}")
seq_idx[start:end] = sequence_id
return seq_idx.unsqueeze(0)
def _causal_conv1d_varlen(
hidden_states: torch.Tensor,
weight: torch.Tensor,
bias: torch.Tensor | None,
boundaries: list[int],
) -> torch.Tensor:
"""Apply a depthwise causal convolution independently to packed documents."""
batch_size, _, channels = hidden_states.shape
if batch_size != 1:
raise ValueError(f"packed CP Mamba expects batch_size=1, got {batch_size}")
inputs = hidden_states.transpose(1, 2)
outputs = []
for start, end in zip(boundaries[:-1], boundaries[1:]):
convolved = torch.nn.functional.conv1d(
inputs[:, :, start:end],
weight,
bias,
groups=channels,
padding=weight.shape[2] - 1,
)
outputs.append(convolved[:, :, : end - start])
return torch.cat(outputs, dim=-1).transpose(1, 2)
class _SeqToHeadParallel(torch.autograd.Function):
"""[B, S/cp, D] -> [B, S, D/cp] via all-to-all."""
@@ -93,7 +132,14 @@ def head_to_seq_parallel(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size:
return _HeadToSeqParallel.apply(x, cp_group, cp_size)
def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessGroup, cp_rank: int, cp_size: int):
def mamba_cp_forward(
mixer,
hidden_states: torch.Tensor,
cp_group: dist.ProcessGroup,
cp_rank: int,
cp_size: int,
cu_seqlens: torch.Tensor,
):
"""CP-aware Mamba-2 forward: in_proj -> all-to-all -> conv+SSM(local heads) -> all-to-all -> out_proj.
Replaces the mixer's cuda_kernels_forward when CP > 1. Parameters are
@@ -134,6 +180,8 @@ def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessG
hidden_states_B_C = torch.cat([x_part, B_part, C_part], dim=-1)
full_seq_len = hidden_states_B_C.shape[1] # S (full sequence)
boundaries = cu_seqlens.tolist()
seq_idx = _build_seq_idx(boundaries, full_seq_len, hidden_states.device)
# ── 3. Local head dimensions ──
local_num_heads = mixer.num_heads // cp_size
@@ -151,7 +199,6 @@ def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessG
# Slice conv1d weight/bias for local channels
# conv1d channels = intermediate_size + 2 * ngroups * dstate (same as conv_dim)
# After all-to-all, we have local channels: local_intermediate + 2 * local_ngroups * dstate
local_conv_dim = local_intermediate_size + 2 * local_n_groups * mixer.ssm_state_size
conv_x_start = cp_rank * local_intermediate_size
conv_x_end = conv_x_start + local_intermediate_size
conv_b_start = mixer.intermediate_size + cp_rank * local_n_groups * mixer.ssm_state_size
@@ -169,15 +216,9 @@ def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessG
local_conv_weight = mixer.conv1d.weight[conv_indices]
local_conv_bias = mixer.conv1d.bias[conv_indices] if mixer.conv1d.bias is not None else None
# ── 4. Conv1d on full sequence, local heads ──
# ── 4. Conv1d on each packed document, local heads ──
hidden_states_B_C = torch.nn.functional.silu(
torch.nn.functional.conv1d(
hidden_states_B_C.transpose(1, 2),
local_conv_weight,
local_conv_bias,
groups=local_conv_dim,
padding=mixer.conv1d.weight.shape[2] - 1,
).transpose(1, 2)[:, :full_seq_len]
_causal_conv1d_varlen(hidden_states_B_C, local_conv_weight, local_conv_bias, boundaries)
)
local_groups_time_state_size = local_n_groups * mixer.ssm_state_size
@@ -190,7 +231,7 @@ def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessG
# ── 5. SSM scan on full sequence, local heads ──
dt_limit_kwargs = {} if mixer.time_step_limit is None else {"dt_limit": mixer.time_step_limit}
scan_output, _ = mamba_chunk_scan_combined(
scan_output = mamba_chunk_scan_combined(
hidden_states_local.view(batch_size, full_seq_len, local_num_heads, mixer.head_dim),
time_step,
local_A,
@@ -199,8 +240,8 @@ def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessG
chunk_size=mixer.chunk_size,
D=local_D,
z=None,
seq_idx=None,
return_final_states=True,
seq_idx=seq_idx,
return_final_states=False,
dt_bias=local_dt_bias,
dt_softplus=True,
**dt_limit_kwargs,
@@ -1,17 +1,19 @@
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.
import torch
from prime_rl.trainer.models.kernels.fp8_utils import (
GROUP_ALIGNMENT,
build_grouped_layout,
grouped_per_block_cast_to_fp8_triton,
grouped_per_channel_cast_to_fp8_rowmajor_triton,
grouped_per_channel_cast_to_fp8_sm90_kmajor_triton,
grouped_per_token_cast_to_fp8_triton,
unpack_rows_triton,
@@ -30,32 +32,60 @@ def _compute_grad_weight(
block_starts_tensor: torch.Tensor,
aligned_ms: list[int],
) -> torch.Tensor:
x_k_major = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
x,
padded_total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
False,
GROUP_ALIGNMENT,
)
dy_k_major = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
grad_output,
padded_total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
False,
GROUP_ALIGNMENT,
)
is_sm100 = torch.cuda.get_device_capability(x.device)[0] >= 10
if is_sm100:
x_fp8 = grouped_per_channel_cast_to_fp8_rowmajor_triton(
x,
padded_total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
True,
GROUP_ALIGNMENT,
)
dy_fp8 = grouped_per_channel_cast_to_fp8_rowmajor_triton(
grad_output,
padded_total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
True,
GROUP_ALIGNMENT,
)
grouped_weight_grad = deep_gemm.k_grouped_fp8_gemm_tn_contiguous
else:
x_fp8 = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
x,
padded_total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
True,
GROUP_ALIGNMENT,
)
dy_fp8 = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
grad_output,
padded_total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
True,
GROUP_ALIGNMENT,
)
grouped_weight_grad = deep_gemm.k_grouped_fp8_gemm_nt_contiguous
grad_weight = torch.zeros(weight_shape, device=x.device, dtype=torch.float32)
deep_gemm.k_grouped_fp8_gemm_nt_contiguous(
x_k_major,
dy_k_major,
grouped_weight_grad(
x_fp8,
dy_fp8,
grad_weight,
aligned_ms,
ks_tensor,
@@ -90,12 +120,12 @@ class _GroupedFP8Gemm(torch.autograd.Function):
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
False,
True,
GROUP_ALIGNMENT,
)
weight_fp8 = grouped_per_block_cast_to_fp8_triton(
weight.transpose(1, 2),
False,
True,
GROUP_ALIGNMENT,
)
@@ -174,12 +204,12 @@ class _GroupedFP8Gemm(torch.autograd.Function):
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
False,
True,
GROUP_ALIGNMENT,
)
weight_dx_fp8 = grouped_per_block_cast_to_fp8_triton(
weight,
False,
True,
GROUP_ALIGNMENT,
)
grad_x_padded = torch.empty(
@@ -2,14 +2,15 @@ from __future__ import annotations
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.
import torch
from torch import nn
from prime_rl.trainer.models.kernels.fp8_utils import (
per_block_cast_to_fp8_tp_triton,
@@ -25,8 +26,8 @@ class _FP8BlockwiseMM(torch.autograd.Function):
def forward(ctx, x, weight, block_size, out_dtype=torch.bfloat16):
x_shape = x.shape
x_2d = x.reshape(-1, x_shape[-1]).contiguous()
x_fp8 = per_token_cast_to_fp8_triton(x_2d, False, block_size)
weight_fp8 = per_block_cast_to_fp8_triton(weight, False, block_size)
x_fp8 = per_token_cast_to_fp8_triton(x_2d, True, block_size)
weight_fp8 = per_block_cast_to_fp8_triton(weight, True, block_size)
out = torch.empty((x_2d.size(0), weight.size(0)), device=x.device, dtype=out_dtype)
deep_gemm.fp8_gemm_nt(x_fp8, weight_fp8, out)
@@ -44,8 +45,8 @@ class _FP8BlockwiseMM(torch.autograd.Function):
grad_x = grad_weight = None
if ctx.needs_input_grad[0]:
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, False, block_size)
weight_dx_fp8 = per_block_cast_to_fp8_tp_triton(weight, False, block_size)
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, True, block_size)
weight_dx_fp8 = per_block_cast_to_fp8_tp_triton(weight, True, block_size)
grad_x_2d = torch.empty_like(x_2d)
deep_gemm.fp8_gemm_nt(grad_output_fp8, weight_dx_fp8, grad_x_2d)
grad_x = grad_x_2d.reshape(ctx.x_shape)
@@ -63,8 +64,8 @@ class _FP8BlockwiseMM(torch.autograd.Function):
else:
grad_output_2d_padded = grad_output_2d
x_2d_padded = x_2d
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d_padded, False, block_size)
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d_padded, False, block_size)
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d_padded, True, block_size)
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d_padded, True, block_size)
grad_weight_fp32 = torch.zeros_like(weight, dtype=torch.float32)
deep_gemm.fp8_gemm_nt(
grad_output_t_fp8,
@@ -82,7 +83,7 @@ class Float8BlockwiseLinear(nn.Linear):
"""nn.Linear replacement that uses FP8 blockwise matmul via DeepGEMM.
Requires:
- SM90 (Hopper) GPU
- SM90 (Hopper) or SM100 (Blackwell) GPU
- bfloat16 inputs/weights
- No bias
- in_features and out_features divisible by 128
@@ -109,24 +110,7 @@ class Float8BlockwiseLinear(nn.Linear):
return new_mod
DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [
"lm_head",
"router",
# Use escaped dots — re.search treats `.` as any-char, so the previous
# "mlp.gate." pattern was also matching dense MLP `mlp.gate_proj` (the
# trailing `.` was matching `_`). That left the dense MLP gate projection
# 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)
"eh_proj",
"weights_proj",
"in_proj_a",
"in_proj_b",
]
def replace_linear_with_fp8_blockwise_linear(model: nn.Module, ignore_modules: list[str] | None = None) -> None:
def replace_linear_with_fp8_blockwise_linear(model: nn.Module, ignore_modules: list[str]) -> None:
"""Replace nn.Linear in `model` with Float8BlockwiseLinear, skipping any
module whose qualified name matches an ignore pattern (substring or regex).
@@ -146,8 +130,6 @@ def replace_linear_with_fp8_blockwise_linear(model: nn.Module, ignore_modules: l
Conv1d, layer norms, and embedding tables are not nn.Linear and are
skipped automatically by the type check; we don't need to list them.
"""
if ignore_modules is None:
ignore_modules = list(DEFAULT_FP8_IGNORE_PATTERNS)
logger = get_logger()
logger.info(f"Replacing linear layers with FP8 blockwise linear layers (ignore={ignore_modules})")
replaced_modules = []
+12 -107
View File
@@ -10,8 +10,6 @@ from torch import Tensor
from prime_rl.utils.logger import get_logger
from prime_rl.utils.vlm import get_final_logit_softcapping
FUSED_CE_IGNORE_INDEX = -100
class PrimeLmOutput(TypedDict, total=False):
"""Output from LM head - a TypedDict so pytree can find tensors for FSDP2 hooks."""
@@ -75,78 +73,6 @@ class VanillaOutputLinear(torch.nn.Linear):
return PrimeLmOutput(logits=super().forward(hidden_states))
class FusedCrossEntropyOutputLinear(torch.nn.Linear):
"""Fused lm_head + cross-entropy loss using Liger kernel.
Avoids materializing the full [N, V] logits tensor by fusing the linear
projection with the cross-entropy loss computation.
"""
IGNORE_INDEX = FUSED_CE_IGNORE_INDEX
def __init__(self, in_features: int, out_features: int, softcap: float | None = None):
super().__init__(in_features, out_features, bias=False)
from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
self.fused_ce = LigerFusedLinearCrossEntropyLoss(
ignore_index=self.IGNORE_INDEX, reduction="mean", softcap=softcap
)
def forward(
self,
hidden_states: torch.Tensor,
labels: torch.Tensor | None = None,
temperature: Tensor | None = None,
) -> PrimeLmOutput:
if labels is None:
return PrimeLmOutput(logits=super().forward(hidden_states))
b, s, h = hidden_states.shape
hidden_flat = hidden_states.reshape(b * s, h).contiguous()
labels_flat = labels.reshape(b * s).contiguous()
loss = self.fused_ce(self.weight, hidden_flat, labels_flat)
return PrimeLmOutput(loss=loss)
class QuackFusedCrossEntropyOutputLinear(torch.nn.Linear):
"""Fused lm_head + cross-entropy loss using quack-kernels.
Chunks the linear projection and cross-entropy computation to avoid
materializing the full [N, V] logits tensor, using quack's optimized
CuTe DSL kernels for CE and GEMM.
"""
IGNORE_INDEX = FUSED_CE_IGNORE_INDEX
def __init__(self, in_features: int, out_features: int, chunk_size: int = 4096):
super().__init__(in_features, out_features, bias=False)
self.chunk_size = chunk_size
def forward(
self,
hidden_states: torch.Tensor,
labels: torch.Tensor | None = None,
temperature: Tensor | None = None,
) -> PrimeLmOutput:
if labels is None:
return PrimeLmOutput(logits=super().forward(hidden_states))
from quack.linear_cross_entropy import chunked_linear_cross_entropy
b, s, h = hidden_states.shape
hidden_flat = hidden_states.reshape(b * s, h).contiguous()
labels_flat = labels.reshape(b * s).contiguous()
loss = chunked_linear_cross_entropy(
hidden_flat,
self.weight,
labels_flat,
chunk_size=self.chunk_size,
ignore_index=self.IGNORE_INDEX,
reduction="mean",
)
return PrimeLmOutput(loss=loss)
def _online_logsumexp_and_weighted_update(
m: torch.Tensor, s: torch.Tensor, t: torch.Tensor, chunk_logits: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
@@ -238,8 +164,9 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
vocab = weight.shape[0]
vocab_chunk_size = min(vocab, 8192)
grad_hidden = torch.zeros_like(hidden)
grad_weight = torch.zeros_like(weight)
needs_hidden, needs_weight = ctx.needs_input_grad[0], ctx.needs_input_grad[1]
grad_hidden = torch.zeros_like(hidden) if needs_hidden else None
grad_weight = torch.zeros_like(weight) if needs_weight else None
for start in range(0, n, chunk_size):
end = min(start + chunk_size, n)
@@ -263,8 +190,10 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
grad_logits[mask, idx] += grad_chunk[mask]
grad_logits = grad_logits * inv_t_chunk
grad_hidden[start:end].add_(grad_logits.to(hidden.dtype) @ weight_chunk)
grad_weight[vocab_start:vocab_end].add_(grad_logits.to(weight.dtype).t() @ hidden_chunk)
if needs_hidden:
grad_hidden[start:end].add_(grad_logits.to(hidden.dtype) @ weight_chunk)
if needs_weight:
grad_weight[vocab_start:vocab_end].add_(grad_logits.to(weight.dtype).t() @ hidden_chunk)
return grad_hidden, grad_weight, None, None, None
@@ -272,7 +201,6 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
def inject_prime_lm_head(
model: nn.Module,
chunk_size: int | None = None,
fused_cross_entropy: bool | str = False,
) -> None:
"""
Inject a PrimeRL LM head into a model.
@@ -283,11 +211,7 @@ def inject_prime_lm_head(
Args:
model: The model to wrap.
chunk_size: When set to an int, uses FusedOutputLinear with sequence-token chunked
logprob/entropy computation (for RL).
fused_cross_entropy: Controls fused lm_head + CE loss. Accepts:
- False: no fusion
- True or "liger": Liger kernel fusion
- "quack": quack-kernels fusion (chunked linear + CE with CuTe DSL kernels)
logprob/entropy computation.
"""
# Guards so we have nicer error messages when a non-standard model is used
assert hasattr(model, "model"), f"model doesnt have backbone in model.model:\n{model}"
@@ -303,33 +227,14 @@ def inject_prime_lm_head(
# Check for Gemma-style softcapping - dispatch to specialized implementation.
final_logit_softcapping = get_final_logit_softcapping(model.config)
if final_logit_softcapping:
if fused_cross_entropy == "quack":
raise ValueError(
"quack_fused does not support Gemma logit softcapping. "
"Use loss_impl='liger_fused' or loss_impl='torch' instead."
)
if not fused_cross_entropy:
from prime_rl.trainer.models.layers.lm_head_gemma import inject_gemma_lm_head
from prime_rl.trainer.models.layers.lm_head_gemma import inject_gemma_lm_head
inject_gemma_lm_head(model, chunk_size, final_logit_softcapping)
return
inject_gemma_lm_head(model, chunk_size, final_logit_softcapping)
return
# Replace the lm_head with the appropriate wrapper
old_lm_head = model.lm_head
if fused_cross_entropy == "quack":
logger.info("Injecting fused cross-entropy LM head (quack-kernels)")
model.lm_head = QuackFusedCrossEntropyOutputLinear(
in_features=old_lm_head.in_features,
out_features=old_lm_head.out_features,
)
elif fused_cross_entropy:
logger.info("Injecting fused cross-entropy LM head (Liger kernel)")
model.lm_head = FusedCrossEntropyOutputLinear(
in_features=old_lm_head.in_features,
out_features=old_lm_head.out_features,
softcap=final_logit_softcapping,
)
elif isinstance(chunk_size, int):
if isinstance(chunk_size, int):
logger.info(f"Injecting chunked LM head with chunk size {chunk_size}")
model.lm_head = FusedOutputLinear(
in_features=old_lm_head.in_features, out_features=old_lm_head.out_features, chunk_size=chunk_size
@@ -798,6 +798,7 @@ class MoE(nn.Module):
self.expert_bias = torch.zeros(self.experts.num_experts, dtype=torch.float32)
@torch.compile(dynamic=True)
def relu2(x: torch.Tensor) -> torch.Tensor:
return F.relu(x).square()
@@ -0,0 +1,88 @@
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
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 _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()
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})"
)
@@ -0,0 +1,99 @@
from __future__ import annotations
import re
import torch
from torch import nn
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
from prime_rl.utils.logger import get_logger
class MXFP8Linear(nn.Linear):
def __init__(
self,
in_features: int,
out_features: int,
bias: bool = True,
*,
kernel_preference: KernelPreference = KernelPreference.AUTO,
wgrad_with_hp: bool = False,
scale_calculation_mode: ScaleCalculationMode = ScaleCalculationMode.RCEIL,
device=None,
dtype=None,
) -> None:
super().__init__(in_features, out_features, bias, device=device, dtype=dtype)
self.kernel_preference = kernel_preference
self.wgrad_with_hp = wgrad_with_hp
self.scale_calculation_mode = scale_calculation_mode
def forward(self, input: torch.Tensor) -> torch.Tensor:
output = _to_mxfp8_then_scaled_mm(
input,
self.weight,
self.kernel_preference,
self.scale_calculation_mode,
wgrad_with_hp=self.wgrad_with_hp,
)
if self.bias is not None:
output = output + self.bias
return output
@classmethod
def from_linear(
cls,
mod: nn.Linear,
*,
kernel_preference: KernelPreference = KernelPreference.AUTO,
wgrad_with_hp: bool = False,
scale_calculation_mode: ScaleCalculationMode = ScaleCalculationMode.RCEIL,
) -> "MXFP8Linear":
with torch.device("meta"):
new_mod = cls(
mod.in_features,
mod.out_features,
bias=mod.bias is not None,
kernel_preference=kernel_preference,
wgrad_with_hp=wgrad_with_hp,
scale_calculation_mode=scale_calculation_mode,
)
new_mod.weight = mod.weight
new_mod.bias = mod.bias
return new_mod
def replace_linear_with_mxfp8_linear(model: nn.Module, recipe: MXFP8Recipe, ignore_modules: list[str]) -> None:
wgrad_with_hp = recipe == "mxfp8_rceil_wgrad_with_hp"
logger = get_logger()
logger.info(f"Replacing linear layers with MXFP8 linear layers (recipe={recipe}, ignore={ignore_modules})")
replaced_modules: list[str] = []
skipped_modules: list[str] = []
skipped_unaligned: list[str] = []
for name, module in dict(model.named_modules()).items():
if not isinstance(module, nn.Linear):
continue
if any(re.search(pattern, name) for pattern in ignore_modules):
skipped_modules.append(name)
continue
if (module.in_features & 31) != 0 or (module.out_features & 31) != 0:
skipped_unaligned.append(f"{name}({module.in_features}->{module.out_features})")
continue
parent_name, attr_name = name.rsplit(".", 1) if "." in name else ("", name)
parent = model.get_submodule(parent_name) if parent_name else model
setattr(
parent,
attr_name,
MXFP8Linear.from_linear(module, kernel_preference=KernelPreference.AUTO, wgrad_with_hp=wgrad_with_hp),
)
replaced_modules.append(name)
logger.info(
f"Replaced {len(replaced_modules)} linear layers with MXFP8 linear "
f"(skipped {len(skipped_modules)} by name, {len(skipped_unaligned)} by 32-div); "
f"first replaced={replaced_modules[:3]}, "
f"first skipped(name)={skipped_modules[:3]}, "
f"first skipped(unaligned)={skipped_unaligned[:3]}"
)
@@ -19,8 +19,17 @@ Key benefit: the attention kernel itself does not need to be CP-aware. The
all-to-all is purely on Q/K/V tensors, so this works out of the box with
softmax flash-attn, linear attention, mamba, etc., without rewriting kernels.
GQA models with fewer KV heads than cp_size (e.g. NemotronH: 32 query heads, 2
KV heads) are handled by replicating each KV head cp_size / num_key_value_heads
times before the seq->head all-to-all. Query heads are grouped contiguously in
GQA, so the replicated layout lands every rank on exactly the KV head its local
query-head slice attends to; the backward of the replication sums gradients
over replicas, which is the exact GQA KV gradient.
Constraints:
- cp_size must divide both num_attention_heads and num_key_value_heads.
- cp_size must divide num_attention_heads.
- cp_size must divide num_key_value_heads, OR num_key_value_heads must divide
cp_size (the KV-replication path).
- Sequence length must be divisible by cp_size.
"""
@@ -41,6 +50,24 @@ def update_ulysses_params(cu_seqlens: torch.Tensor, max_seqlen: int) -> None:
ULYSSES_PARAMS["max_seqlen"] = int(max_seqlen)
def _replicate_kv_heads(t: torch.Tensor, cp_size: int) -> torch.Tensor:
"""Replicate KV heads so a GQA tensor with fewer heads than cp_size can be
head-sharded: [S_local, H_kv, D] -> [S_local, cp_size, D].
Each KV head is repeated cp_size / H_kv times. GQA groups query heads
contiguously (query head j attends KV head j // (H_q / H_kv)), so after the
seq->head all-to-all rank r holds query heads [r * H_q/cp, (r+1) * H_q/cp)
— all attending KV head floor(r * H_kv / cp) — and replica index r maps to
the same head: floor(r / (cp / H_kv)). The backward sums gradients over
replicas, which is exactly the GQA KV gradient.
"""
s_local, h, d = t.shape
assert cp_size % h == 0, (
f"num_key_value_heads ({h}) must divide cp_size ({cp_size}) for the ulysses KV-replication path"
)
return t.repeat_interleave(cp_size // h, dim=1)
def _all_to_all_seq_to_head(t: torch.Tensor, cp_size: int, cp_group: dist.ProcessGroup) -> torch.Tensor:
"""Redistribute [S_local, H, D] -> [S_global, H_local, D].
@@ -48,7 +75,10 @@ def _all_to_all_seq_to_head(t: torch.Tensor, cp_size: int, cp_group: dist.Proces
ends up with the full sequence but only H/cp_size heads. Differentiable.
"""
s_local, h, d = t.shape
assert h % cp_size == 0, f"num_heads ({h}) must be divisible by cp_size ({cp_size})"
assert h % cp_size == 0, (
f"num_heads ({h}) must be divisible by cp_size ({cp_size}); "
"for GQA KV tensors with fewer heads than cp_size, replicate first via _replicate_kv_heads"
)
h_local = h // cp_size
# [S_local, cp_size, H_local, D] -> [cp_size, S_local, H_local, D]
@@ -96,8 +126,15 @@ def ulysses_flash_attn_varlen_func(
`cu_seqlens_*` and `max_seqlen_*` describe the *full* (un-sharded) sequence,
because after the seq->head all-to-all each rank holds the full sequence.
GQA with num_key_value_heads < cp_size: K/V heads are replicated up to
cp_size before the all-to-all (see `_replicate_kv_heads`), so each rank runs
grouped attention on its query-head slice with the single matching KV head.
"""
q = _all_to_all_seq_to_head(q, cp_size, cp_group)
if k.shape[1] < cp_size:
k = _replicate_kv_heads(k, cp_size)
v = _replicate_kv_heads(v, cp_size)
k = _all_to_all_seq_to_head(k, cp_size, cp_group)
v = _all_to_all_seq_to_head(v, cp_size, cp_group)
@@ -136,7 +173,7 @@ def substitute_ulysses_attn(
cp_size = dist.get_world_size(group=process_group)
# Resolve flash kernel + version from attn_impl.
if attn_impl == "fa4":
if attn_impl == "flash_attention_4":
from flash_attn.cute import flash_attn_varlen_func as flash_fn
flash_attn_version = 4
@@ -107,7 +107,7 @@ class LlamaPreTrainedModel(PreTrainedModelPrimeRL):
_no_split_modules = ["LlamaDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_supports_flex_attn = True
_can_compile_fullgraph = True
@@ -188,7 +188,7 @@ class LlamaModel(LlamaPreTrainedModel):
if inputs_embeds is None:
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
else:
@@ -95,7 +95,7 @@ class MiniMaxM2PreTrainedModel(PreTrainedModelPrimeRL):
_no_split_modules = ["MiniMaxM2DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_supports_flex_attn = True
_can_compile_fullgraph = False
_supports_attention_backend = True
@@ -177,7 +177,7 @@ class MiniMaxM2Model(MiniMaxM2PreTrainedModel):
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
else:
@@ -23,6 +23,7 @@ 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.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
from prime_rl.trainer.models.nemotron_h.converting_nemotron_h import (
convert_hf_layer_to_prime,
@@ -229,9 +230,15 @@ class NemotronHMambaLayer(GradientCheckpointingLayer):
hidden_states = self.norm(hidden_states)
if self.cp_enabled:
# TODO: This path doesnt support cu_seqlens so packing makes it wrong
# The local cu_seqlens cover only this shard; conv/scan need the full
# pre-shard document boundaries published by setup_cp_params.
hidden_states = mamba_cp_forward(
self.mamba, hidden_states, self._cp_group, self._cp_rank, self._cp_world_size
self.mamba,
hidden_states,
self._cp_group,
self._cp_rank,
self._cp_world_size,
ULYSSES_PARAMS["cu_seqlens"],
)
else:
hidden_states = self.mamba(hidden_states, cu_seqlens=cu_seqlens)
@@ -335,7 +342,7 @@ class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
supports_gradient_checkpointing = True
_no_split_modules = ["NemotronHMambaLayer", "NemotronHMoELayer", "NemotronHAttentionLayer"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_can_compile_fullgraph = False
def _init_weights(self, module):
@@ -515,7 +522,7 @@ class NemotronHModel(NemotronHPreTrainedModel):
inputs_embeds = self.embed_tokens(input_ids)
# Compute cu_seqlens and max_seqlen for flash attention
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
else:
@@ -50,8 +50,6 @@ class Qwen3DecoderLayer(GradientCheckpointingLayer):
)
self.self_attn = ATTN_IMPL2CLASS[config._attn_implementation](attn_config)
if self.layer_type == "sliding_attention":
if config._attn_implementation == "sdpa":
raise ValueError("Qwen3 sliding attention is only supported by the custom model with flash attention.")
self.self_attn.sliding_window = config.sliding_window
mlp_config = MLPConfig(
@@ -95,7 +93,7 @@ class Qwen3PreTrainedModel(PreTrainedModelPrimeRL):
_no_split_modules = ["Qwen3DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_supports_flex_attn = True
_can_compile_fullgraph = True
_supports_attention_backend = True
@@ -165,7 +163,7 @@ class Qwen3Model(Qwen3PreTrainedModel):
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
else:
@@ -21,7 +21,6 @@ from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
Qwen3_5MoeGatedAttentionConfig,
Qwen3_5MoeGatedDeltaNet,
Qwen3_5MoeGatedFlashAttention,
Qwen3_5MoeGatedSDPAAttention,
Qwen3_5MoeRMSNorm,
Qwen3_5MoeRotaryEmbedding,
normalize_qwen3_5_attn_implementation,
@@ -29,19 +28,14 @@ from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
class Qwen3_5GatedSDPAAttention(Qwen3_5MoeGatedSDPAAttention):
pass
class Qwen3_5GatedFlashAttention(Qwen3_5MoeGatedFlashAttention):
pass
QWEN35_ATTN_IMPL2CLASS = {
"sdpa": Qwen3_5GatedSDPAAttention,
"flash_attention_2": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=2),
"flash_attention_3": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=3),
"fa4": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=4),
"flash_attention_4": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=4),
}
@@ -130,7 +124,7 @@ class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
_no_split_modules = ["Qwen3_5DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_supports_flex_attn = False
_supports_attention_backend = True
_can_compile_fullgraph = False
@@ -141,7 +135,7 @@ class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
def _check_and_adjust_attn_implementation(
self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
) -> str:
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "sdpa")
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "flash_attention_3")
if attn_impl not in QWEN35_ATTN_IMPL2CLASS:
supported = list(QWEN35_ATTN_IMPL2CLASS.keys())
raise ValueError(
@@ -206,7 +200,11 @@ class Qwen3_5Model(Qwen3_5PreTrainedModel):
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
flash_attn_enabled = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4")
flash_attn_enabled = self.config._attn_implementation in (
"flash_attention_2",
"flash_attention_3",
"flash_attention_4",
)
if flash_attn_enabled:
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
@@ -24,6 +24,7 @@ from prime_rl.trainer.models.layers.attn import (
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.rotary_emb import apply_rotary_pos_emb
from prime_rl.trainer.models.layers.ulysses_attn import ULYSSES_PARAMS
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids, get_cu_seqlens_from_seq_lens
from .configuration_qwen3_5_moe import Qwen3_5MoeConfig
@@ -43,6 +44,7 @@ except ImportError:
try:
from fla.modules import FusedRMSNormGated
from fla.modules.conv import causal_conv1d as fla_causal_conv1d
from fla.ops.cp import FLACPContext, build_cp_context
from fla.ops.gated_delta_rule import chunk_gated_delta_rule
except ImportError:
@@ -50,6 +52,7 @@ except ImportError:
FusedRMSNormGated = None # type: ignore
FLACPContext = None # type: ignore
build_cp_context = None # type: ignore
fla_causal_conv1d = None # type: ignore
logger = logging.get_logger(__name__)
@@ -233,16 +236,16 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
self._causal_conv1d_fn = causal_conv1d_fn
self._chunk_gated_delta_rule = chunk_gated_delta_rule or torch_chunk_gated_delta_rule
def _build_cp_context(self, local_seq_len: int, device: torch.device) -> "FLACPContext | None":
"""Build fla CP context from the local (sharded) sequence length."""
def _build_cp_context(self) -> "FLACPContext | None":
"""Build fla CP context from the full pre-shard document boundaries."""
cp_group = getattr(self, "cp_group", None)
if cp_group is None or build_cp_context is None:
return None
# Reconstruct global cu_seqlens: single contiguous sequence across all CP ranks
global_seq_len = local_seq_len * self.cp_world_size
global_cu_seqlens = torch.tensor([0, global_seq_len], dtype=torch.int32, device=device)
# Local cu_seqlens cannot describe documents straddling shard boundaries;
# use the full (un-sharded) cu_seqlens published by setup_cp_params. fla
# derives per-rank boundaries and document-aware state passing from them.
return build_cp_context(
cu_seqlens=global_cu_seqlens,
cu_seqlens=ULYSSES_PARAMS["cu_seqlens"],
group=cp_group,
conv1d_kernel_size=self.conv_kernel_size,
)
@@ -259,9 +262,23 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
b = self.in_proj_b(hidden_states)
a = self.in_proj_a(hidden_states)
cp_context = self._build_cp_context()
# Causal conv1d — must reset at sequence boundaries for packed batches,
# otherwise the kernel-1 left pad leaks state across sequences.
if self._causal_conv1d_fn is not None:
if cp_context is not None:
# fla's CP conv resets at the true document boundaries and exchanges
# tail tokens with the previous rank for documents straddling the
# shard boundary; the local cu_seqlens can express neither.
conv_out, _ = fla_causal_conv1d(
x=mixed_qkv.transpose(1, 2),
weight=self.conv1d.weight.squeeze(1),
bias=self.conv1d.bias,
activation=self.activation,
cp_context=cp_context,
)
mixed_qkv = conv_out.transpose(1, 2)
elif self._causal_conv1d_fn is not None:
seq_idx = None
if cu_seqlens is not None:
seg_lens = cu_seqlens[1:] - cu_seqlens[:-1]
@@ -303,7 +320,6 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
# Use fla's native CP when available, otherwise fall back to PyTorch kernel
cp_context = self._build_cp_context(seq_len, hidden_states.device)
if cp_context is not None:
cu_seqlens = cp_context.cu_seqlens
core_attn_out, _ = self._chunk_gated_delta_rule(
@@ -401,59 +417,6 @@ class Qwen3_5MoeGatedAttentionBase(nn.Module):
return self.o_proj(attn_output)
class Qwen3_5MoeGatedSDPAAttention(Qwen3_5MoeGatedAttentionBase):
"""Gated softmax attention using PyTorch's scaled_dot_product_attention."""
def attn_projections(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states, gate = torch.chunk(
self.q_proj(hidden_states).view(*input_shape, -1, self.head_dim * 2), 2, dim=-1
)
gate = gate.reshape(*input_shape, -1)
query_states = self.q_norm(query_states.view(hidden_shape)).transpose(1, 2)
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
return query_states, key_states, value_states, gate
def _attention_core(
self,
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
) -> torch.Tensor:
key_states = _repeat_kv(key_states, self.num_key_value_groups)
value_states = _repeat_kv(value_states, self.num_key_value_groups)
return F.scaled_dot_product_attention(
query_states,
key_states,
value_states,
is_causal=True,
scale=self.scaling,
)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, None]:
query_states, key_states, value_states, gate = self.attn_projections(hidden_states, position_embeddings)
attn_output = self._attention_core(query_states, key_states, value_states)
return self.output_proj(attn_output, gate), None
class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
"""Gated softmax attention using Flash Attention varlen functions."""
@@ -544,16 +507,13 @@ class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
QWEN35MOE_ATTN_IMPL2CLASS = {
"sdpa": Qwen3_5MoeGatedSDPAAttention,
"flash_attention_2": functools.partial(Qwen3_5MoeGatedFlashAttention, flash_attn_version=2),
"flash_attention_3": functools.partial(Qwen3_5MoeGatedFlashAttention, flash_attn_version=3),
"fa4": functools.partial(Qwen3_5MoeGatedFlashAttention, flash_attn_version=4),
"flash_attention_4": functools.partial(Qwen3_5MoeGatedFlashAttention, flash_attn_version=4),
}
def normalize_qwen3_5_attn_implementation(attn_impl: str) -> str:
if attn_impl == "eager":
return "sdpa"
if attn_impl == "kernels-community/vllm-flash-attn3":
return "flash_attention_3"
return attn_impl
@@ -782,7 +742,7 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
_no_split_modules = ["Qwen3_5MoeDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_supports_flex_attn = False
_supports_attention_backend = True
_can_compile_fullgraph = False
@@ -793,7 +753,7 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
def _check_and_adjust_attn_implementation(
self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
) -> str:
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "sdpa")
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "flash_attention_3")
if attn_impl not in QWEN35MOE_ATTN_IMPL2CLASS:
supported = list(QWEN35MOE_ATTN_IMPL2CLASS.keys())
raise ValueError(
@@ -869,7 +829,11 @@ class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
flash_attn_enabled = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4")
flash_attn_enabled = self.config._attn_implementation in (
"flash_attention_2",
"flash_attention_3",
"flash_attention_4",
)
if flash_attn_enabled:
if position_ids.ndim == 3:
if inputs_embeds.shape[0] != 1:
@@ -127,7 +127,7 @@ class Qwen3MoePreTrainedModel(PreTrainedModelPrimeRL):
_no_split_modules = ["Qwen3MoeDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_sdpa = False
_supports_flex_attn = True
_can_compile_fullgraph = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
_supports_attention_backend = True
@@ -217,7 +217,7 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
else:
+1 -10
View File
@@ -1,5 +1,4 @@
import copy
import time
from typing import Callable
import torch
@@ -12,7 +11,6 @@ from prime_rl.configs.trainer import OptimizerConfig
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.trainer.sign_sgd import SignSGD
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
@@ -121,14 +119,7 @@ def setup_optimizer(
# Wait for run 0 to be created in the multi run manager
# Otherwise, the creation will reset the parameters
multi_run_manager = get_multi_run_manager()
world = get_world()
logger = get_logger()
while 0 not in multi_run_manager.idx_2_id:
if world.is_master:
multi_run_manager.discover_runs()
multi_run_manager.synchronize_state()
logger.info(f"Waiting for run 0 to be created {multi_run_manager.id_2_idx=}")
time.sleep(1)
multi_run_manager.wait_for_run(0)
named_params = multi_run_manager.get_named_parameters_for_run(0)
optimizer = _create_optimizer(config, named_params, parallel_dims)
+14
View File
@@ -255,6 +255,7 @@ def train(config: TrainerConfig):
logger.info(f"Tracing to {config.trace_path}")
prof = profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], record_shapes=True).__enter__()
maybe_record_function = record_function
start_step = progress.step
while True:
# Reset peak memory stats
torch.cuda.reset_peak_memory_stats()
@@ -265,6 +266,19 @@ def train(config: TrainerConfig):
logger.debug(f"Starting training step {progress.step}")
step_start_time = time.perf_counter()
# With NCCL, broadcast the incoming policy (v{progress.step-1}) before waiting for its
# rollouts: #2896 broadcasts at the END of a step, so the first step would otherwise block
# on rollouts the paused inference engines cannot produce until they receive
# v{progress.step-1}. Filesystem broadcast needs no startup rendezvous (fresh: base model
# = v0; resume: the orchestrator reads its checkpoint dir), and a one-shot startup
# broadcast would miss multi-run runs registered after the first step.
if progress.step == start_step and weight_broadcast is not None and config.weight_broadcast.type == "nccl":
logger.info(f"Broadcasting startup policy weights (v{progress.step - 1}) to inference engines")
multi_run_manager.wait_for_run(0)
for idx in multi_run_manager.used_idxs:
multi_run_manager.ready_to_update[idx] = True
weight_broadcast.broadcast_weights(model, step=progress.step - 1)
# Wait for the batch to be available
logger.debug("Waiting for training batch to arrive")
wait_for_batch_start_time = time.perf_counter()
+15
View File
@@ -1,4 +1,5 @@
import pickle
import time
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Callable, Optional
@@ -463,6 +464,20 @@ class MultiRunManager:
# Properties and Accessors
# =========================================================================
def wait_for_run(self, idx: int = 0, poll_interval: float = 1.0) -> None:
"""Block until run ``idx`` is registered. Master discovers from disk; all ranks synchronize.
Runs are otherwise only discovered during batch collection (``packer.discover_runs``), so
callers that need a run before the first batch (optimizer setup, first-step weight sync)
use this to populate ``idx_2_id``/``used_idxs``.
"""
while idx not in self.idx_2_id:
if self.world.is_master:
self.discover_runs()
self.synchronize_state()
self.logger.info(f"Waiting for run {idx} to be created ({self.id_2_idx=})")
time.sleep(poll_interval)
@property
def used_idxs(self):
return sorted(self.idx_2_id.keys())
+71 -86
View File
@@ -1,7 +1,7 @@
import json
import uuid
from collections import defaultdict
from typing import Literal, TypedDict, cast
from typing import Any, Literal, TypedDict, cast
import torch
from datasets import Dataset, interleave_datasets, load_dataset
@@ -15,13 +15,7 @@ from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.configs.sft import DataConfig, LossMaskConfig, SFTDataConfig
from prime_rl.trainer.world import get_world
from prime_rl.utils.chat_template import (
IncrementalTokenizationError,
build_incremental_token_mask,
deserialize_tool_calls,
normalize_messages,
strip_message_content,
)
from prime_rl.utils.chat_template import deserialize_tool_calls, normalize_messages
from prime_rl.utils.logger import get_logger
STACKING_DATASET_BUCKET_TIMEOUT = 10
@@ -114,13 +108,33 @@ class FakeDataset(StatefulIterableDataset):
yield fake_sample
def _drop_null_fields(value: Any, path: tuple[str, ...] = ()) -> Any:
"""Recursively strip ``None``-valued keys from dict structures.
PyArrow's JSON loader unifies schemas across rows, so heterogeneous
OAI content blocks (text vs image_url) end up with all union keys
filled with ``None`` where absent. That confuses permissive
content-type predicates inside renderers (e.g. ``"image_url" in item``
returns ``True`` even when the value is null). Strip the noise before
handing messages off to the renderer. Tool-call arguments are opaque
JSON payloads, so preserve their null values.
"""
if path[-3:] == ("tool_calls", "function", "arguments"):
return value
if isinstance(value, dict):
return {k: _drop_null_fields(v, (*path, k)) for k, v in value.items() if v is not None}
if isinstance(value, list):
return [_drop_null_fields(v, path) for v in value]
return value
class SFTDataset(StatefulIterableDataset):
"""A dataset wrapping a HF SFT dataset with prompt/completion or raw messages format."""
def __init__(
self,
dataset: Dataset,
tokenizer: PreTrainedTokenizer | None,
renderer: Renderer,
shuffle: bool = True,
seed: int = 0,
seq_len: int = 128,
@@ -128,24 +142,18 @@ class SFTDataset(StatefulIterableDataset):
loss_mask_config: LossMaskConfig = LossMaskConfig(),
max_examples: int | None = None,
max_epochs: int | None = None,
renderer: Renderer | None = None,
):
super().__init__()
self.logger = get_logger()
self.dataset = dataset
self.num_examples = len(self.dataset)
self.tokenizer = tokenizer
self.renderer = renderer
self.shuffle = shuffle
self.seed = seed
self.seq_len = seq_len
self.loss_mask_config = loss_mask_config
self.max_examples = max_examples
self.max_epochs = max_epochs
self.renderer = renderer
self._warned_chat_template_kwargs = False
if self.tokenizer is None:
self.logger.warning("No tokenizer provided, will not process examples")
# If specified, select a subset of the dataset
if self.max_examples is not None:
@@ -163,16 +171,14 @@ class SFTDataset(StatefulIterableDataset):
self.data_world_size = get_world().world_size // non_dp_size * num_workers
def _process(self, example: dict) -> dict | None:
# Skip processing if no tokenizer was provided
if self.tokenizer is None:
return example
def resolve_messages(example: dict) -> list[dict]:
# `messages` takes precedence over explicit split fields and is interpreted
# as a whole-chat training sample with an empty prompt.
if "messages" in example:
# as a whole-chat training sample with an empty prompt. Null-check rather
# than key-check: Arrow schema union adds `messages: null` to
# prompt/completion rows whenever other rows have a `messages` column.
if example.get("messages") is not None:
messages = normalize_messages(example["messages"], default_role="assistant")
elif "prompt" in example and "completion" in example:
elif example.get("prompt") is not None and example.get("completion") is not None:
messages = normalize_messages(example["prompt"], default_role="user") + normalize_messages(
example["completion"], default_role="assistant"
)
@@ -182,22 +188,17 @@ class SFTDataset(StatefulIterableDataset):
"or both 'prompt' and 'completion' columns for SFT"
)
# Deserialize tool call arguments from message list, if present - assumes OAI format
# Reference: https://platform.openai.com/docs/guides/function-calling#handling-function-calls
messages = deserialize_tool_calls(messages)
# Strip content from all messages so that incremental tokenization works
# NOTE: This has the side effect that we do never train on leading or trailing whitespace
return strip_message_content(messages)
# Strip nulls before deserializing so genuine nulls inside tool-call
# argument strings survive.
messages = [_drop_null_fields(m) for m in messages]
return deserialize_tool_calls(messages)
messages = resolve_messages(example)
# Parse available tools, if present - assumes OAI format
# Reference: https://platform.openai.com/docs/guides/function-calling#function-tool-example
# Accepts either `tools` or `tool_defs` (the verifiers rollout format),
# as either a JSON-encoded string of a list or a list of dicts. Tools
# arriving in the verifiers shape are converted to OAI form so any
# downstream chat template can consume them.
# Parse available tools, if present - assumes OAI format. Accepts either
# `tools` or `tool_defs` (the verifiers rollout format), as either a
# JSON-encoded string of a list or a list of dicts; verifiers-shaped
# tools are converted to OAI form for the chat template.
raw_tools = example.get("tools", example.get("tool_defs"))
if not raw_tools:
tools = []
@@ -223,55 +224,37 @@ class SFTDataset(StatefulIterableDataset):
assert "role" in message, "Message must have a role"
match message["role"]:
case "user":
return True if self.loss_mask_config.user else False
return self.loss_mask_config.user
case "assistant":
return True if self.loss_mask_config.assistant else False
return self.loss_mask_config.assistant
case "system":
return True if self.loss_mask_config.system else False
return self.loss_mask_config.system
case "tool":
return True if self.loss_mask_config.tool else False
return self.loss_mask_config.tool
case _:
raise ValueError(f"Invalid message role: {message['role']}")
if self.renderer is not None:
if example.get("chat_template_kwargs") and not self._warned_chat_template_kwargs:
self.logger.warning(
"Example carries chat_template_kwargs but a renderer is configured; "
"renderers don't forward chat_template_kwargs (model-specific "
"renderers bake their template behavior in). These kwargs will "
"be ignored. Further warnings suppressed for this dataset."
)
self._warned_chat_template_kwargs = True
# Defer to the renderer's sampled_mask by default: a role filter would
# drop sampled stop markers attributed to the next message (e.g. GLM's
# turn-closing <|user|> / <|observation|>).
role_to_mask = None if self.loss_mask_config.assistant else should_mask
input_ids, loss_mask = build_training_sample(
self.renderer,
messages,
role_to_mask=should_mask,
tools=tools,
)
else:
try:
input_ids, loss_mask = build_incremental_token_mask(
self.tokenizer,
messages,
role_to_mask=should_mask,
tools=tools,
chat_template_kwargs=example.get("chat_template_kwargs", {}),
collapse_consecutive_tool_messages=True,
)
except IncrementalTokenizationError as e:
self.logger.warning(f"Skipping example {example.get('__index', '')}: {e}")
return None
# Non-assistant roles are opted into the loss via the renderer's
# body-only path: the message content is trained, not the role
# scaffolding (e.g. <|im_start|>assistant) the harness emits.
content_sft_roles = {role for role in ("user", "system", "tool") if getattr(self.loss_mask_config, role)}
sample = build_training_sample(
self.renderer,
messages,
role_to_mask=role_to_mask,
tools=tools,
content_sft_roles=content_sft_roles or None,
ensure_final_stop=True,
)
input_ids = list(sample.token_ids)
loss_mask = list(sample.loss_mask)
# If EOS token is not found, manually append it
if not self.tokenizer.eos_token_id in input_ids:
self.logger.warning(
f"Did not find EOS token ID {self.tokenizer.eos_token_id} in input_ids. Is something wrong with the chat template? Manually appending EOS token..."
)
input_ids.append(cast(int, self.tokenizer.eos_token_id))
loss_mask.append(True)
# Prepare inputs
# Causal shift: model predicts next token from current.
target_ids = input_ids.copy()[1:]
loss_mask = loss_mask[1:]
input_ids = input_ids[:-1]
@@ -280,15 +263,16 @@ class SFTDataset(StatefulIterableDataset):
self.logger.warning(
f"Skipping example {example.get('__index', '')} because no trainable tokens were found within the context window ({self.seq_len}). This is to prevent NaN loss."
)
return
return None
assert len(input_ids) == len(loss_mask) == len(target_ids), (
f"input_ids, loss_mask and target_ids must have the same length, but got {len(input_ids)=}, {len(loss_mask)=}, {len(target_ids)=}"
)
assert sum(loss_mask) > 0, "There are no tokens in this sample that contribute to the loss"
assert self.tokenizer.eos_token_id in target_ids, "EOS token ID must be present in target_ids"
assert set(self.renderer.get_stop_token_ids()) & set(target_ids), (
"A renderer stop token must be present in target_ids"
)
# Create sample (with one fake target for the last token)
return {
"input_ids": input_ids,
"target_ids": target_ids,
@@ -297,9 +281,6 @@ class SFTDataset(StatefulIterableDataset):
}
def __iter__(self):
"""
Apply chat template and tokenize a single example in prompt + completion format (https://github.com/huggingface/trl/blob/de27d612b026526ba39b88eee348994d7636e033/trl/trainer/sft_trainer.py#L661)
"""
dataset = self.dataset.shuffle(seed=self.epoch + self.seed) if self.shuffle else self.dataset
while True:
self.step += 1
@@ -585,21 +566,25 @@ def setup_dataset(
) -> StatefulIterableDataset:
if config.type == "fake":
return FakeDataset(
vocab_size=tokenizer.vocab_size, seq_len=config.seq_len, length=config.length, input_ids=config.input_ids
vocab_size=tokenizer.vocab_size,
seq_len=config.seq_len,
length=config.length,
input_ids=config.input_ids,
)
elif config.type == "sft":
if renderer is None:
raise ValueError("SFT data requires a renderer.")
if raw_dataset is None:
raw_dataset = load_sft_dataset(config)
return SFTDataset(
raw_dataset,
tokenizer,
renderer,
shuffle=config.shuffle,
seed=config.seed,
seq_len=config.seq_len,
loss_mask_config=config.loss_mask,
non_dp_size=non_dp_size,
max_epochs=max_epochs,
renderer=renderer,
)
else:
raise ValueError(f"Invalid dataset type: {config.type}")
+13 -31
View File
@@ -5,7 +5,6 @@ from contextlib import nullcontext
from datetime import timedelta
from renderers.base import create_renderer
from renderers.default import DefaultRenderer
from ring_flash_attn import substitute_hf_flash_attn
from torch.nn import CrossEntropyLoss
@@ -52,8 +51,6 @@ from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
from prime_rl.utils.utils import clean_exit, to_col_format
import torch.distributed as dist
from liger_kernel.transformers.cross_entropy import LigerCrossEntropyLoss
from prime_rl.trainer.models.layers.lm_head import FUSED_CE_IGNORE_INDEX
from torchtitan.distributed.utils import clip_grad_norm_
@@ -139,8 +136,7 @@ def train(config: SFTConfig):
# Initialize the model and tokenizer
logger.info(f"Initializing model ({config.model})")
loading_from_ckpt_later = config.ckpt and checkpoint_step is not None
fused_cross_entropy: bool | str = {"liger_fused": "liger", "quack_fused": "quack"}.get(config.loss_impl, False)
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later, fused_cross_entropy=fused_cross_entropy)
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later)
if parallel_dims.cp_enabled:
from prime_rl.utils.cp import assert_cp_style_supports_model
@@ -162,17 +158,12 @@ def train(config: SFTConfig):
logger.info(f"Initializing tokenizer ({config.tokenizer})")
tokenizer = setup_tokenizer(config.tokenizer)
# Fake data never renders messages, so a model without a hand-coded renderer
# can still be used to benchmark step time / memory. Validation data is
# always real, so it needs the renderer even when training data is fake.
renderer = None
if config.renderer is not None:
if config.data.type != "fake" or config.val is not None:
renderer = create_renderer(tokenizer, config.renderer)
if isinstance(renderer, DefaultRenderer):
raise ValueError(
f"renderer set for {config.tokenizer.name!r} resolved to DefaultRenderer. "
"DefaultRenderer falls back to incremental apply_chat_template and does NOT "
"fix position-dependent chat templates — the bug the renderer client is meant to solve. "
"Either use a model with a hand-coded renderer (see renderers.base.MODEL_RENDERER_MAP), "
"set [renderer] name=<hand-coded renderer> explicitly, or remove the [renderer] block."
)
logger.info(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}")
# Set up the optimizer
@@ -231,17 +222,6 @@ def train(config: SFTConfig):
dp_cp_group = parallel_dims.get_mesh("dp_cp").get_group()
cp_size = parallel_dims.cp
ce_loss = None
match config.loss_impl:
case "liger":
ce_loss = LigerCrossEntropyLoss(reduction="none")
case "torch":
ce_loss = CrossEntropyLoss(reduction="none")
case "liger_fused" | "quack_fused":
pass # loss is computed inside the fused lm_head
case _:
raise ValueError(f"Invalid loss implementation: {config.loss_impl}")
def compute_loss(micro_batch: dict) -> tuple[torch.Tensor, torch.Tensor]:
"""Forward pass returning (loss_sum, token_count) over unmasked tokens."""
input_ids = micro_batch["input_ids"].to("cuda")
@@ -262,16 +242,18 @@ def train(config: SFTConfig):
token_count = loss_mask.sum(dtype=torch.int64)
with maybe_activation_offloading(config.model.ac_offloading):
if config.loss_impl in ("liger_fused", "quack_fused"):
masked_target_ids = target_ids.clone()
masked_target_ids[~loss_mask] = FUSED_CE_IGNORE_INDEX
out = forward(model, input_ids, position_ids, labels=masked_target_ids)
loss_sum = out["loss"] * token_count
if isinstance(config.model.fused_lm_head_token_chunk_size, int):
# Same path as the RL trainer: the chunked LM head computes per-token
# logprobs without materializing the [N, V] logits, and per-token
# cross-entropy is the negative target logprob.
temperature = torch.ones_like(target_ids, dtype=torch.float32)
out = forward(model, input_ids, position_ids, labels=target_ids, temperature=temperature)
loss_sum = -out["logprobs"][loss_mask].sum()
else:
out = forward(model, input_ids, position_ids)
logits = out["logits"]
B, L, V = logits.shape
token_loss = ce_loss(logits.view(-1, V), target_ids.view(-1)).view(B, L)
token_loss = CrossEntropyLoss(reduction="none")(logits.view(-1, V), target_ids.view(-1)).view(B, L)
loss_sum = token_loss[loss_mask].sum()
del logits
+1 -85
View File
@@ -1,13 +1,5 @@
import json
from typing import Any, Callable
from transformers.tokenization_utils import PreTrainedTokenizer
class IncrementalTokenizationError(ValueError):
"""Raised when incremental tokenization produces inconsistent token prefixes."""
pass
from typing import Any
def normalize_messages(messages: Any, default_role: str) -> list[dict[str, Any]]:
@@ -56,79 +48,3 @@ def deserialize_tool_calls(messages: list[dict[str, Any]]) -> list[dict[str, Any
)
return deserialized_messages
def strip_message_content(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
def _strip(message: dict[str, Any]) -> dict[str, Any]:
content = message.get("content")
if isinstance(content, str):
return {**message, "content": content.strip()}
return message
return [_strip(message) for message in messages]
def should_add_generation_prompt(messages: list[dict[str, Any]], idx: int) -> bool:
role = messages[idx].get("role")
if role not in ("user", "tool"):
return False
if idx + 1 >= len(messages):
return False
return messages[idx + 1].get("role") == "assistant"
def render_messages(
tokenizer: PreTrainedTokenizer,
messages: list[dict[str, Any]],
*,
tools: list[dict[str, Any]] | None = None,
chat_template_kwargs: dict[str, Any] | None = None,
add_generation_prompt: bool = False,
) -> list[int]:
kwargs = dict(chat_template_kwargs or {})
kwargs["add_generation_prompt"] = add_generation_prompt
if tools is not None:
kwargs["tools"] = tools
kwargs["return_dict"] = False
return list(tokenizer.apply_chat_template(messages, **kwargs))
def build_incremental_token_mask(
tokenizer: PreTrainedTokenizer,
messages: list[dict[str, Any]],
*,
role_to_mask: Callable[[dict[str, Any]], bool],
tools: list[dict[str, Any]] | None = None,
chat_template_kwargs: dict[str, Any] | None = None,
collapse_consecutive_tool_messages: bool = False,
) -> tuple[list[int], list[bool]]:
token_mask: list[bool] = []
prev_ids: list[int] = []
prev_len = 0
for idx, message in enumerate(messages):
role = message.get("role")
if collapse_consecutive_tool_messages and role == "tool" and idx + 1 < len(messages):
if messages[idx + 1].get("role") == "tool":
continue
cur_ids = render_messages(
tokenizer,
messages[: idx + 1],
tools=tools,
chat_template_kwargs=chat_template_kwargs,
add_generation_prompt=should_add_generation_prompt(messages, idx),
)
if prev_ids != cur_ids[:prev_len]:
raise IncrementalTokenizationError(
f"Mismatch in incremental tokenization with chat template at message {idx} (role={role}). "
"This usually means the chat template is not stable under incremental application. "
"The sample will be skipped."
)
token_mask.extend([role_to_mask(message)] * (len(cur_ids) - prev_len))
prev_ids = cur_ids
prev_len = len(cur_ids)
return prev_ids, token_mask
@@ -55,8 +55,15 @@ def _build_rollout(
)
parent = len(nodes) - 1
# Trace token counts are usage-based, so carry provider usage on the final sampled turn:
# every model-generated token as completion, the leading prompt + tool observations as the
# fed-in context (num_input_tokens = num_total_tokens - num_output_tokens).
output_tokens = sum(sampled_lengths)
input_tokens = 1 + sum(obs_lengths)
for i, n_sampled in enumerate(sampled_lengths):
ids = _take(n_sampled)
is_last = i == len(sampled_lengths) - 1
nodes.append(
vf.MessageNode(
message=vf.AssistantMessage(content="a"),
@@ -65,6 +72,7 @@ def _build_rollout(
logprobs=[-0.1] * n_sampled,
sampled=True,
parent=parent,
usage=vf.Usage(prompt_tokens=input_tokens, completion_tokens=output_tokens) if is_last else None,
)
)
parent = len(nodes) - 1
+20
View File
@@ -547,6 +547,26 @@ def test_orchestrator_renderer_auto_accepts_mapped_model():
assert config.renderer.name == "auto"
def test_sft_renderer_auto_accepts_prime_qwen_model():
config = SFTConfig.model_validate({"model": {"name": "PrimeIntellect/Qwen3-0.6B"}})
assert config.renderer.name == "auto"
def test_sft_rejects_default_renderer_for_real_data():
with pytest.raises(ValidationError, match="requires a typed renderer"):
SFTConfig.model_validate({"renderer": {"name": "default"}})
def test_sft_allows_unused_default_renderer_for_fake_data():
config = SFTConfig.model_validate(
{
"data": {"type": "fake"},
"renderer": {"name": "default"},
}
)
assert config.renderer.name == "default"
def test_orchestrator_explicit_renderer_skips_unmapped_check():
"""Explicit renderer.name bypasses the auto-resolution check — user opted in."""
config = OrchestratorConfig.model_validate(
+1 -1
View File
@@ -56,7 +56,7 @@ def get_model_pairs():
use_grouped_mm=False,
vocab_size=256,
)
hf_config._attn_implementation = "sdpa"
hf_config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFAfmoeForCausalLM._from_config(hf_config)
prime_model = PrimeRLAfmoeForCausalLM._from_config(hf_config)
+71
View File
@@ -0,0 +1,71 @@
import sys
import types
import pytest
import torch
from prime_rl.trainer.models.layers import cp_mamba
class _FakeMixer(torch.nn.Module):
def __init__(self):
super().__init__()
self.intermediate_size = 1
self.conv_dim = 3
self.num_heads = 1
self.n_groups = 1
self.ssm_state_size = 1
self.head_dim = 1
self.chunk_size = 1
self.time_step_limit = None
self.variance_epsilon = 1e-5
self.in_proj = torch.nn.Linear(1, 5, bias=False)
self.in_proj.weight.data.copy_(torch.tensor([[1.0], [1.0], [1.0], [1.0], [1.0]]))
self.A_log = torch.nn.Parameter(torch.zeros(1))
self.D = torch.nn.Parameter(torch.ones(1))
self.dt_bias = torch.nn.Parameter(torch.zeros(1))
self.conv1d = torch.nn.Conv1d(3, 3, kernel_size=2, groups=3, bias=False)
self.conv1d.weight.data.fill_(1.0)
self.norm = types.SimpleNamespace(weight=torch.ones(1), variance_epsilon=self.variance_epsilon, group_size=1)
self.out_proj = torch.nn.Identity()
def _install_fake_scan(monkeypatch, seen_seq_idx: list[torch.Tensor]) -> None:
def fake_scan(hidden_states, time_step, A, B, C, **kwargs):
assert kwargs["return_final_states"] is False
seen_seq_idx.append(kwargs["seq_idx"].clone())
return hidden_states
ssd_combined = types.ModuleType("mamba_ssm.ops.triton.ssd_combined")
ssd_combined.mamba_chunk_scan_combined = fake_scan
monkeypatch.setitem(sys.modules, "mamba_ssm", types.ModuleType("mamba_ssm"))
monkeypatch.setitem(sys.modules, "mamba_ssm.ops", types.ModuleType("mamba_ssm.ops"))
monkeypatch.setitem(sys.modules, "mamba_ssm.ops.triton", types.ModuleType("mamba_ssm.ops.triton"))
monkeypatch.setitem(sys.modules, "mamba_ssm.ops.triton.ssd_combined", ssd_combined)
def test_mamba_cp_forward_resets_conv_and_scan_at_packed_boundaries(monkeypatch):
"""Changing document A must not change document B under Ulysses CP."""
seen_seq_idx: list[torch.Tensor] = []
_install_fake_scan(monkeypatch, seen_seq_idx)
monkeypatch.setattr(cp_mamba, "seq_to_head_parallel", lambda value, *_: value)
monkeypatch.setattr(cp_mamba, "head_to_seq_parallel", lambda value, *_: value)
mixer = _FakeMixer()
cu_seqlens = torch.tensor([0, 2, 4], dtype=torch.int32)
first = torch.tensor([[[1.0], [2.0], [3.0], [4.0]]])
second = first.clone()
second[0, 1, 0] = 200.0
first_out = cp_mamba.mamba_cp_forward(mixer, first, None, 0, 1, cu_seqlens)
second_out = cp_mamba.mamba_cp_forward(mixer, second, None, 0, 1, cu_seqlens)
assert torch.equal(seen_seq_idx[0], torch.tensor([[0, 0, 1, 1]], dtype=torch.int32))
assert torch.equal(seen_seq_idx[1], seen_seq_idx[0])
torch.testing.assert_close(first_out[:, 2:], second_out[:, 2:])
def test_mamba_cp_forward_rejects_local_boundaries():
with pytest.raises(ValueError, match="full sequence length 4"):
cp_mamba._build_seq_idx([0, 2], 4, torch.device("cpu"))
+1 -1
View File
@@ -32,7 +32,7 @@ def get_model_pairs() -> tuple[HFGlm4MoeForCausalLM, PrimeRLGlm4MoeForCausalLM]:
# TODO: We should test this path because it's the most performant
# But the grad seems to be off in attn because of precision
# hf_config._attn_implementation = "flash_attention_2"
hf_config._attn_implementation = "sdpa"
hf_config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFGlm4MoeForCausalLM._from_config(hf_config)
prime_model = PrimeRLGlm4MoeForCausalLM._from_config(hf_config)
+1 -1
View File
@@ -25,7 +25,7 @@ def get_model_pairs():
attention_bias=False,
mlp_bias=False,
)
hf_config._attn_implementation = "sdpa"
hf_config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFLlamaForCausalLM._from_config(hf_config)
prime_model = PrimeRLLlamaForCausalLM._from_config(hf_config)
+4 -4
View File
@@ -47,14 +47,14 @@ _BASE = dict(
def get_model_pairs():
"""Create an HF model and a PrimeRL model with shared weights."""
hf_config = HFNemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
hf_config._attn_implementation = "sdpa"
hf_config._attn_implementation = "flash_attention_2"
prime_config = NemotronHConfig(
**_BASE,
layers_block_type=["mamba", "moe", "attention", "moe"],
use_grouped_mm=False,
)
prime_config._attn_implementation = "sdpa"
prime_config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFNemotronHForCausalLM._from_config(hf_config)
@@ -110,10 +110,10 @@ def test_nemotron_h_reverse():
layers_block_type=["mamba", "moe", "attention", "moe"],
use_grouped_mm=False,
)
prime_config._attn_implementation = "sdpa"
prime_config._attn_implementation = "flash_attention_2"
hf_config = HFNemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
hf_config._attn_implementation = "sdpa"
hf_config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.float32):
prime_model = NemotronHForCausalLM._from_config(prime_config)
@@ -55,7 +55,7 @@ def _make_model(device="cuda"):
layers_block_type=["mamba", "moe", "attention", "moe"],
use_grouped_mm=False,
)
config._attn_implementation = "sdpa"
config._attn_implementation = "flash_attention_2"
with torch.device(device), default_dtype(torch.float32):
model = NemotronHForCausalLM._from_config(config)
inject_prime_lm_head(model, chunk_size=None)
@@ -186,7 +186,7 @@ def test_kl_with_fused_lm_head():
layers_block_type=["mamba", "moe", "attention", "moe"],
use_grouped_mm=False,
)
config._attn_implementation = "sdpa"
config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.float32):
model = NemotronHForCausalLM._from_config(config)
+3 -2
View File
@@ -12,7 +12,7 @@ from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAt
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig
def _tiny_text_config(attn_impl: str = "sdpa") -> Qwen3_5TextConfig:
def _tiny_text_config(attn_impl: str = "flash_attention_2") -> Qwen3_5TextConfig:
config = Qwen3_5TextConfig(
vocab_size=128,
hidden_size=64,
@@ -33,7 +33,7 @@ def _tiny_text_config(attn_impl: str = "sdpa") -> Qwen3_5TextConfig:
return config
def _tiny_moe_config(attn_impl: str = "sdpa") -> Qwen3_5MoeConfig:
def _tiny_moe_config(attn_impl: str = "flash_attention_2") -> Qwen3_5MoeConfig:
config = Qwen3_5MoeConfig(
vocab_size=128,
hidden_size=64,
@@ -58,6 +58,7 @@ def _tiny_moe_config(attn_impl: str = "sdpa") -> Qwen3_5MoeConfig:
return config
@pytest.mark.gpu
def test_qwen3_5_dense_matches_hf_state_keys_on_meta():
config = _tiny_text_config()
with torch.device("meta"):
+1 -1
View File
@@ -31,7 +31,7 @@ def get_model_pairs():
linear_num_value_heads=8,
use_grouped_mm=False,
)
config._attn_implementation = "sdpa"
config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFQwen3_5MoeForCausalLM._from_config(config)
prime_model = PrimeRLQwen3_5MoeForCausalLM._from_config(config)
@@ -15,7 +15,9 @@ pytestmark = [pytest.mark.gpu]
def _tiny_vlm_config():
"""HF composite config shrunk for unit testing."""
config = AutoConfig.from_pretrained("Qwen/Qwen3.5-35B-A3B", trust_remote_code=True, attn_implementation="sdpa")
config = AutoConfig.from_pretrained(
"Qwen/Qwen3.5-35B-A3B", trust_remote_code=True, attn_implementation="flash_attention_2"
)
config.use_cache = False
tc = config.text_config
tc.vocab_size = 256
+1 -1
View File
@@ -31,7 +31,7 @@ def get_model_pairs():
# TODO: We should test this path because it's the most performant
# But the grad seems to be off in attn because of precision
# hf_config._attn_implementation = "flash_attention_2"
hf_config._attn_implementation = "sdpa"
hf_config._attn_implementation = "flash_attention_2"
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFQwen3MoeForCausalLM._from_config(hf_config)
prime_model = PrimeRLQwen3MoeForCausalLM._from_config(hf_config)
+28
View File
@@ -61,6 +61,34 @@ def test_fused_lm_head_matches_full_logits_forward_and_backward_cpu():
torch.testing.assert_close(grad_weight1, grad_weight0, rtol=0, atol=1e-5)
def test_fused_lm_head_frozen_weight_backward_cpu():
"""Frozen LM-head weight: hidden gradient matches baseline, no weight gradient is produced."""
torch.manual_seed(0)
b, s, h, v = 2, 4, 8, 37
temperature = torch.full((b, s), 1.7, dtype=torch.float32)
chunk_size = 3
hidden0 = torch.randn(b, s, h, dtype=torch.float32, requires_grad=True)
labels = torch.randint(0, v, (b, s), dtype=torch.long)
weight0 = torch.randn(v, h, dtype=torch.float32)
# Baseline (weight frozen)
logp0, _ = _baseline_logprobs_and_entropy(hidden0, weight0, labels, temperature=temperature)
logp0.sum().backward()
grad_hidden0 = hidden0.grad.detach().clone()
# Fused (weight frozen)
hidden1 = hidden0.detach().clone().requires_grad_(True)
lm = FusedOutputLinear(in_features=h, out_features=v, chunk_size=chunk_size)
lm.weight = torch.nn.Parameter(weight0.clone(), requires_grad=False)
out = lm(hidden1, labels, temperature=temperature)
out["logprobs"].sum().backward()
torch.testing.assert_close(hidden1.grad, grad_hidden0, rtol=0, atol=1e-5)
assert lm.weight.grad is None
def test_fused_lm_head_requires_labels():
"""Test that FusedOutputLinear raises assertion error when labels is None."""
torch.manual_seed(0)
+126 -39
View File
@@ -2,64 +2,125 @@ from collections import Counter
import pytest
from datasets import Dataset, interleave_datasets
from renderers import create_renderer
from renderers.base import RenderedTokens
from transformers import AutoTokenizer
from prime_rl.trainer.sft.data import SFTDataset
from prime_rl.trainer.sft.data import SFTDataset, _drop_null_fields
from prime_rl.trainer.utils import print_sample
_BOS_TOKEN_ID = 0
_STOP_TOKEN_ID = 1
def _sample_token_ids(value: str) -> list[int]:
return [ord(char) + 2 for char in value]
class _DummyRenderer:
def render(self, messages, **kwargs):
content_ids = _sample_token_ids(messages[-1]["content"])
token_ids = [_BOS_TOKEN_ID, *content_ids, _STOP_TOKEN_ID]
return RenderedTokens(
token_ids=token_ids,
message_indices=[-1, *([len(messages) - 1] * (len(content_ids) + 1))],
sampled_mask=[False, *([True] * (len(content_ids) + 1))],
)
def get_stop_token_ids(self):
return [_STOP_TOKEN_ID]
@pytest.fixture(scope="module")
def build_dummy_dataset():
return lambda letter, num_examples: Dataset.from_list([{"text": f"{letter}{i}"} for i in range(num_examples)])
return lambda letter, num_examples: Dataset.from_list(
[{"messages": [{"role": "assistant", "content": f"{letter}{i}"}]} for i in range(num_examples)]
)
def test_init_sft_dataset(build_dummy_dataset):
@pytest.fixture
def dummy_renderer():
return _DummyRenderer()
@pytest.mark.parametrize(
"arguments",
[
pytest.param('{"reasoning_effort": null}', id="json-string"),
pytest.param({"reasoning_effort": None}, id="dict"),
],
)
def test_drop_null_fields_preserves_tool_call_arguments(arguments):
message = {
"role": "assistant",
"content": [{"type": "text", "text": "Calling a tool", "image_url": None}],
"tool_calls": [{"function": {"name": "listReasoningModels", "arguments": arguments}}],
"metadata": {"arguments": {"unrelated_null": None}},
}
cleaned = _drop_null_fields(message)
assert cleaned["tool_calls"][0]["function"]["arguments"] == arguments
assert cleaned["content"] == [{"type": "text", "text": "Calling a tool"}]
assert cleaned["metadata"] == {"arguments": {}}
def test_init_sft_dataset(build_dummy_dataset, dummy_renderer):
"""Tests basic initialization."""
dataset = build_dummy_dataset("a", 1)
sft_dataset = SFTDataset(dataset, tokenizer=None)
sft_dataset = SFTDataset(dataset, dummy_renderer)
assert sft_dataset is not None
def test_raise_error_if_no_prompt_and_completion(build_dummy_dataset):
"""Tests that an error is raised if no supported SFT message fields are provided."""
dataset = build_dummy_dataset("a", 1)
dataset = Dataset.from_list([{"text": "a0"}])
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
sft_dataset = SFTDataset(dataset, tokenizer=tokenizer)
sft_dataset = SFTDataset(dataset, create_renderer(tokenizer))
with pytest.raises(ValueError):
next(iter(sft_dataset))
@pytest.mark.parametrize("max_epochs", [1, 2, 4])
def test_sft_first_exhausted(build_dummy_dataset, max_epochs: int):
def test_sft_first_exhausted(build_dummy_dataset, dummy_renderer, max_epochs: int):
a = build_dummy_dataset("a", 1)
b = build_dummy_dataset("b", 2)
ds = [a, b]
dataset = interleave_datasets(ds, stopping_strategy="first_exhausted")
dataset = SFTDataset(dataset, tokenizer=None, shuffle=False, max_epochs=max_epochs)
dataset = SFTDataset(dataset, dummy_renderer, shuffle=False, max_epochs=max_epochs)
num_samples = 0
sampling_order = []
for x in dataset:
sampling_order.append(x["text"])
sampling_order.append(x["target_ids"][:-1])
num_samples += 1
assert num_samples == max_epochs * min([len(d) for d in ds]) * len(ds)
assert sampling_order == ["a0", "b0"] * max_epochs
assert sampling_order == [_sample_token_ids("a0"), _sample_token_ids("b0")] * max_epochs
@pytest.mark.parametrize("max_epochs", [1, 2, 4])
def test_sft_all_exhausted(build_dummy_dataset, max_epochs: int):
def test_sft_all_exhausted(build_dummy_dataset, dummy_renderer, max_epochs: int):
a = build_dummy_dataset("a", 1)
b = build_dummy_dataset("b", 2)
ds = [a, b]
dataset = interleave_datasets(ds, stopping_strategy="all_exhausted")
dataset = SFTDataset(dataset, tokenizer=None, shuffle=False, max_epochs=max_epochs)
dataset = SFTDataset(dataset, dummy_renderer, shuffle=False, max_epochs=max_epochs)
num_samples = 0
sampling_order = []
for x in dataset:
sampling_order.append(x["text"])
sampling_order.append(x["target_ids"][:-1])
num_samples += 1
assert num_samples == max_epochs * max([len(d) for d in ds]) * len(ds)
print(sampling_order)
assert sampling_order == ["a0", "b0", "a0", "b1"] * max_epochs
assert (
sampling_order
== [
_sample_token_ids("a0"),
_sample_token_ids("b0"),
_sample_token_ids("a0"),
_sample_token_ids("b1"),
]
* max_epochs
)
@pytest.mark.parametrize(
@@ -70,21 +131,21 @@ def test_sft_all_exhausted(build_dummy_dataset, max_epochs: int):
pytest.param((9 / 10, 1 / 10), id="high_low_probs"),
],
)
def test_sft_all_exhausted_with_probs(build_dummy_dataset, probs: list[float]):
def test_sft_all_exhausted_with_probs(build_dummy_dataset, dummy_renderer, probs: list[float]):
"""Tests that the ratio of samples from different datasets is as specified, in expectation."""
a = build_dummy_dataset("a", int(1e3))
b = build_dummy_dataset("b", int(10e3))
ds = [a, b]
dataset = interleave_datasets(ds, stopping_strategy="all_exhausted", probabilities=probs)
dataset = SFTDataset(dataset, tokenizer=None, shuffle=False, max_epochs=1)
dataset = SFTDataset(dataset, dummy_renderer, shuffle=False, max_epochs=1)
num_samples = 0
sampling_freq = []
for x in dataset:
sampling_freq.append(x["text"][0])
sampling_freq.append(x["target_ids"][0])
num_samples += 1
sampling_freq = Counter(sampling_freq)
ratio_a = sampling_freq["a"] / num_samples
ratio_b = sampling_freq["b"] / num_samples
ratio_a = sampling_freq[ord("a") + 2] / num_samples
ratio_b = sampling_freq[ord("b") + 2] / num_samples
assert ratio_a > probs[0] * 0.8 and ratio_a < probs[0] * 1.2, (
f"Expected frequency of samples from a to be between {probs[0] * 0.8} and {probs[0] * 1.2}, but got {ratio_a}"
)
@@ -93,10 +154,10 @@ def test_sft_all_exhausted_with_probs(build_dummy_dataset, probs: list[float]):
)
def test_sft_dataset_state(build_dummy_dataset):
def test_sft_dataset_state(build_dummy_dataset, dummy_renderer):
"""Tests the state of the dataset within and across epochs."""
dataset = build_dummy_dataset("", 4)
dataset = SFTDataset(dataset, tokenizer=None, shuffle=False, max_epochs=2)
dataset = SFTDataset(dataset, dummy_renderer, shuffle=False, max_epochs=2)
dataiter = iter(dataset)
# Initial state
@@ -105,24 +166,24 @@ def test_sft_dataset_state(build_dummy_dataset):
# Epoch 1
for i in range(4):
sample = next(dataiter)
assert sample["text"] == str(i)
assert sample["target_ids"][:-1] == _sample_token_ids(str(i))
assert dataset.state_dict() == {"epoch": 0, "step": i + 1}
# Epoch 2
for i in range(4):
sample = next(dataiter)
assert sample["text"] == str(i)
assert sample["target_ids"][:-1] == _sample_token_ids(str(i))
assert dataset.state_dict() == {"epoch": 1, "step": 4 + i + 1}
with pytest.raises(StopIteration):
next(dataiter)
def test_sft_dataset_state_resume(build_dummy_dataset):
def test_sft_dataset_state_resume(build_dummy_dataset, dummy_renderer):
"""Tests resuming the dataset from checkpoint in between epochs."""
dataset = SFTDataset(
build_dummy_dataset("", 4),
tokenizer=None,
dummy_renderer,
shuffle=False,
max_epochs=2,
)
@@ -134,8 +195,7 @@ def test_sft_dataset_state_resume(build_dummy_dataset):
# Epoch 1
for i in range(4):
sample = next(dataiter)
print(sample["text"])
assert sample["text"] == str(i)
assert sample["target_ids"][:-1] == _sample_token_ids(str(i))
assert dataset.state_dict() == {"epoch": 0, "step": i + 1}
# Resuming from checkpoint cross epoch
@@ -143,7 +203,7 @@ def test_sft_dataset_state_resume(build_dummy_dataset):
del dataset
dataset = SFTDataset(
build_dummy_dataset("", 4),
tokenizer=None,
dummy_renderer,
shuffle=False,
max_epochs=2,
)
@@ -153,8 +213,7 @@ def test_sft_dataset_state_resume(build_dummy_dataset):
# Epoch 2.1
for i in range(2):
sample = next(dataiter)
print(sample["text"])
assert sample["text"] == str(i)
assert sample["target_ids"][:-1] == _sample_token_ids(str(i))
assert dataset.state_dict() == {"epoch": 1, "step": 4 + i + 1}
# Resuming from checkpoint mid epoch
@@ -162,7 +221,7 @@ def test_sft_dataset_state_resume(build_dummy_dataset):
del dataset
dataset = SFTDataset(
build_dummy_dataset("", 4),
tokenizer=None,
dummy_renderer,
shuffle=False,
max_epochs=2,
)
@@ -172,8 +231,7 @@ def test_sft_dataset_state_resume(build_dummy_dataset):
# Epoch 2.2
for i in range(2, 4):
sample = next(dataiter)
print(sample["text"])
assert sample["text"] == str(i)
assert sample["target_ids"][:-1] == _sample_token_ids(str(i))
assert dataset.state_dict() == {"epoch": 1, "step": 4 + i + 1}
with pytest.raises(StopIteration):
@@ -194,7 +252,7 @@ def test_multiturn_loss_mask():
]
)
tokenizer = AutoTokenizer.from_pretrained("PrimeIntellect/Qwen3-0.6B") # Properly handles multi-turn think
dataset = SFTDataset(dataset, tokenizer=tokenizer, max_examples=1)
dataset = SFTDataset(dataset, create_renderer(tokenizer), max_examples=1)
sample = next(iter(dataset))
print_sample(sample["input_ids"], sample["loss_mask"], tokenizer)
@@ -257,7 +315,7 @@ def test_multiturn_loss_mask_with_tools():
dataset = Dataset.from_list([tool_example])
tokenizer = AutoTokenizer.from_pretrained("PrimeIntellect/Qwen3-0.6B") # Properly handles multi-turn think
dataset = SFTDataset(dataset, tokenizer=tokenizer, max_examples=1)
dataset = SFTDataset(dataset, create_renderer(tokenizer), max_examples=1)
sample = next(iter(dataset))
print_sample(sample["input_ids"], sample["loss_mask"], tokenizer)
@@ -282,10 +340,14 @@ def test_messages_rows_are_equivalent_to_empty_prompt_completion():
]
tokenizer = AutoTokenizer.from_pretrained("PrimeIntellect/Qwen3-0.6B")
messages_dataset = SFTDataset(Dataset.from_list([{"messages": messages}]), tokenizer=tokenizer, max_examples=1)
messages_dataset = SFTDataset(
Dataset.from_list([{"messages": messages}]),
create_renderer(tokenizer),
max_examples=1,
)
split_dataset = SFTDataset(
Dataset.from_list([{"prompt": [], "completion": messages}]),
tokenizer=tokenizer,
create_renderer(tokenizer),
max_examples=1,
)
@@ -304,11 +366,36 @@ def test_messages_take_precedence_over_prompt_and_completion():
"completion": [{"role": "assistant", "content": "Ignored completion"}],
}
messages_dataset = SFTDataset(Dataset.from_list([row]), tokenizer=tokenizer, max_examples=1)
messages_dataset = SFTDataset(
Dataset.from_list([row]),
create_renderer(tokenizer),
max_examples=1,
)
expected_dataset = SFTDataset(
Dataset.from_list([{"prompt": [], "completion": row["messages"]}]),
tokenizer=tokenizer,
create_renderer(tokenizer),
max_examples=1,
)
assert next(iter(messages_dataset)) == next(iter(expected_dataset))
def test_null_messages_falls_back_to_prompt_and_completion():
# Arrow schema union adds `messages: None` to prompt/completion rows when
# other rows in the file have a `messages` column
tokenizer = AutoTokenizer.from_pretrained("PrimeIntellect/Qwen3-0.6B")
prompt = [{"role": "user", "content": "What is 2+2?"}]
completion = [{"role": "assistant", "content": "4"}]
mixed_row_dataset = SFTDataset(
Dataset.from_list([{"messages": None, "prompt": prompt, "completion": completion}]),
create_renderer(tokenizer),
max_examples=1,
)
expected_dataset = SFTDataset(
Dataset.from_list([{"prompt": prompt, "completion": completion}]),
create_renderer(tokenizer),
max_examples=1,
)
assert next(iter(mixed_row_dataset)) == next(iter(expected_dataset))
+5 -3
View File
@@ -14,7 +14,7 @@ pytestmark = [
]
@pytest.fixture(params=["sdpa", "flash_attention_2"])
@pytest.fixture(params=["flash_attention_2"])
def attn(request) -> AttnImplementation:
"""
Fixture to test different attention implementations.
@@ -117,7 +117,9 @@ def test_model_with_sequence_packing(model, correct_position_ids):
def test_moe_custom_impl():
config = ModelConfig(name="PrimeIntellect/GLM-0.5B", attn="sdpa", impl="custom", moe_use_grouped_mm=False)
config = ModelConfig(
name="PrimeIntellect/GLM-0.5B", attn="flash_attention_2", impl="custom", moe_use_grouped_mm=False
)
model = get_model(config)
model = model.to("cuda")
# we need to wrap the lm head as custom forward only works with it, this is done in setup_model
@@ -133,7 +135,7 @@ def test_moe_custom_impl():
@pytest.mark.skip(reason="need special token for meta stuff in ci")
@pytest.mark.parametrize("model_name", ["meta-llama/Llama-3.2-1B-Instruct"])
def test_model_forward_custom_impl(model_name):
config = ModelConfig(name=model_name, impl="custom", attn="sdpa")
config = ModelConfig(name=model_name, impl="custom", attn="flash_attention_2")
model = get_model(config)
# we need to wrap the lm head as custom forward only works with it, this is done in setup_model
inject_prime_lm_head(model, chunk_size=None)
Generated
+1740 -160
View File
File diff suppressed because it is too large Load Diff