Compare commits

...
Author SHA1 Message Date
faresobeidandGitHub 0bd0a71254 chore(orchestrator): remove token_batch_size batching (#3775)
Removes the orchestrator `token_batch_size` option (token-budget batch
cutting). Batches are now always cut by sample count (`batch_size`).

**Why:** the train sink had two parallel batch-cut paths. Sample-count
batching is the one every shipped config uses, including GLM-5.3.
Removing the token path drops the `pending_tokens` / `payload_tokens`
accounting and the token branches in `process_batch`, `_drop_stale`,
`_maybe_batch` and `_record_zero_output`.

**Changes**
- `OrchestratorConfig.batch_size` is now a plain `int = 128` field.
Before, it was `int | None` and the validator set the 128 default.
- Removed `token_batch_size` and the "set exactly one of batch_size or
token_batch_size" check. The `batch_size` divisibility check by group
size stays.
- `TrainSink` takes `batch_size: int` only. `batch_progress()` now
returns `(count, target)` without the unit string. Its only caller is
the orchestrator status log.
- `constant_trainer_batch_size` is unchanged. No metric keys changed.

**Breaking:** configs that set `orchestrator.token_batch_size` now fail
validation. Use `batch_size` instead. No config, example, doc or skill
in the repo set it.

## Validation
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 300 passed
- `ruff check .` and `ruff format --check .`: clean
- GPU and integration tests were not run (no GPU on this machine).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how train batches are formed at the orchestrator; configs
using token batching break, but sample-count batching behavior for
existing runs should be unchanged.
> 
> **Overview**
> Removes **token-budget batching** from the orchestrator so training
batches are always cut by **sample count** (`batch_size`).
> 
> `OrchestratorConfig` drops `token_batch_size` and the mutual-exclusion
validator; `batch_size` is now a required `int` defaulting to **128**
(no longer optional with a validator fallback). `TrainSink` only tracks
trace count for readiness, staleness drops, zero-output warnings, and
`process_batch`—`pending_tokens`, `payload_tokens`, and token-based
partial cuts are gone. `batch_progress()` returns `(count, target)`
only; pipeline status logs no longer show a traces/tokens unit.
> 
> **Breaking:** configs that set `orchestrator.token_batch_size` fail
validation; use `batch_size` instead.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
be797adb554eb5ba99aeb0cd3c3c210eac6e2e0d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 16:06:23 -07:00
faresobeidandGitHub a27c5f195a feat: opt-in exact prompt-mean loss aggregation for GRPO (#3798)
Adds `GRPOAlgoConfig.loss_aggregation: Literal["token", "prompt"] =
"token"`. `echo` gets it too because it subclasses GRPO.

**Why:** the trainer averages the `rl` loss over every loss token in the
batch. Prompts whose groups produce long trajectories therefore dominate
the gradient. SWE groups can differ by about 10x in total tokens.
`"prompt"` implements MiMo-V2.6's prompt-mean aggregation exactly (Eq.
1, p8): `L = mean_q (1/T_q) Σ_{i,t ∈ q} ℓ_{i,t}`. MiMo uses it to keep
response length from growing too fast.

**How:**
- **Trainer:** the `rl` component now divides by the global sum of its
per-token weights, not by the count of nonzero-weight tokens. Every `rl`
weight set in prime-rl today is 0/1, so the sum equals the old count,
and the default path is bit-identical to main. `ce` and `ref_kl` still
divide by their token counts. This is on purpose: echo's fractional `ce`
weight (`alpha`) must keep scaling the loss instead of cancelling out.
- **Orchestrator:** with `"prompt"`, `GRPOAlgorithm.score_group` gives
each trainable token of group q the `rl` weight `1/T_q`. `T_q` is the
group's trainable tokens, the same tokens the advantage is assigned to.
Each group's weights sum to 1, so the `rl` denominator becomes the
number of groups in the step, all-reduced across ranks like before.
There is no extra state.
- **Config:** a validator rejects runs that mix `"token"` and `"prompt"`
across envs with an `rl` loss. In a mixed batch, a whole prompt-mean
group would weigh as much as one token of a token-mean env.
- **Known difference from MiMo:** zero-advantage pruning still drops
zero-advantage tokens from `rl`. A group with a zero-advantage rollout
therefore keeps less than its full weight of 1. MiMo divides by all of
the group's tokens.
- **#3789 (length-weighted baseline):** compatible. Within a group the
weights are uniform, so a length-weighted baseline still keeps the
per-token advantage zero-mean.

**Breaking changes:** none for the default. One behavior change: an `rl`
weight stream with fractional weights would now be normalized by its
sum. Nothing in the repo produces such a stream today.

## Validation
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 301 passed. This includes an updated test in `test_advantage.py`:
each group's `rl` weights are exactly `1/T_q` and sum to 1, for two
groups of different length.
- Manual check that the config validator rejects mixed
`loss_aggregation` across envs.
- `ruff check .` and `ruff format --check .`: clean.
- Not run, because this machine has no GPU:
- `tests/unit/train/rl/test_loss.py`, which needs CUDA and also fails
here on main.
  - The trainer denominator change in `train.py`.
  - GPU and integration tests.
  - A training run.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how the RL loss denominator is computed globally; default
token aggregation should be numerically equivalent, but prompt-mean
alters gradient weighting for long trajectories and mixed configs are
blocked at validation time.
> 
> **Overview**
> Adds **opt-in prompt-mean RL loss aggregation** for GRPO and echo via
`loss_aggregation = "prompt"` (default `"token"` stays unchanged).
> 
> When enabled, **`GRPOAlgorithm.score_group`** stamps each trainable
token with `rl` weight `1/T_q` so each prompt group’s weights sum to 1
(MiMo-style prompt mean). The **trainer** now normalizes the `rl`
component by the **global sum of `rl_weights`** (not nonzero-token
count); with the default 0/1 weights this matches prior behavior. **`ce`
/ `ref_kl`** still divide by token counts so fractional echo `ce`
weights behave correctly.
> 
> **Orchestrator config** rejects mixing `"token"` and `"prompt"` across
envs that use an `rl` loss. **Docs** describe the knob; a **unit test**
checks per-group `rl` weights sum to 1.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
91cf0629f13c3fa39d7c78f476e549b097efa025. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 16:02:59 -07:00
faresobeidandGitHub c8ce6fa283 chore(trainer): remove HF model-implementation fallback (model.impl) (#3773)
## What

Removes the Hugging Face model-implementation fallback (`model.impl =
"hf"`). The trainer now only builds PrimeRL model implementations
(`src/prime_rl/trainer/models/`). An unsupported architecture fails at
setup with `'<model_type>' has no PrimeRL model implementation`.

- `model.impl` is removed. With `"hf"` gone, `"auto"` and `"custom"`
resolved to the same thing.
- `trainer/model.py`: removed impl resolution, `AutoModelForCausalLM` /
`AutoModelForImageTextToText` loading, the CPU-load fallback
(`can_reinit_empty_buffers`, `fix_model_post_empty`), HF weight
re-tying, the HF router-freeze branch, and the HF output handling in
`forward`.
- Removed `lm_head_gemma.py` and its hook in `inject_prime_lm_head`. It
only served HF-impl models with final-logit softcapping.
- Removed the HF CP patches (`substitute_hf_flash_attn`,
`substitute_hf_ulysses_attn`). The config already rejected CP for the HF
impl.
- Removed the `qwen3_vl`, `qwen3_vl_moe` and `gemma4` entries from the
trainer VLM registry. They could only be loaded through the HF path.
Orchestrator and inference multimodal adapters are unchanged.
- Removed the config validators that only checked `impl` (EP, CP, FA4,
quantization, router replay, VLM, trust_remote_code).
- `hendrycks-sanity` (`examples/basic`, `configs/basic`,
`configs/ci/nightly-fft`) used
`deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B` (Qwen2 architecture, which
has no PrimeRL implementation). It now uses `Qwen/Qwen3-1.7B`. No other
settings changed.
- Dropped `impl = ...` from all configs/examples/docs, and updated
README, docs, and tests.
- `test_fused_lm_head.py`: the HF-model tests now use a tiny PrimeRL
Qwen3 (same config as #3768, which removes PrimeRL Llama), built in bf16
because the PrimeRL attention is FlashAttention-only (the fp32 build
failed CI with `FlashAttention only supports fp16, bf16, and fp8_e4m3`).

## Why

The HF fallback is an aging path: added 2025-09, last changed on its own
on 2026-07-17. It keeps a second loading, buffer-reinit, LM-head and CP
code path alive next to the custom implementations. After the
hendrycks-sanity switch, custom implementations cover every shipped
example and config.

## Breaking changes

- `model.impl` / `--trainer.model.impl` is no longer accepted. Configs
that set it fail validation (`extra_forbidden`), so delete the line.
- Architectures without a PrimeRL implementation (for example Qwen2,
Gemma, Qwen3-VL, Mistral) can no longer be trained.
- hendrycks-sanity now trains `Qwen3-1.7B`. Its dataset
(`mikasenghaas/Sanity-Test-R1D-1.5B`) was filtered to problems that
R1-Distill-Qwen-1.5B solves 20-80% of the time, and that band was not
measured for Qwen3-1.7B. **The expected reward, curves, and the nightly
thresholds (`MIN_TRAIN_REWARD = 0.75`, the mismatch-KL band in
`tests/nightly/test_hendrycks_sanity.py`) need GPU re-validation.**

## Validation

- `pytest tests/unit/test_configs.py tests/unit/train -m "not gpu"`: 356
passed, 2 failed. The 2 failures are in `test_cpu_adam.py` (ninja is
missing on this machine). They fail the same way on `origin/main`.
- `ruff check .` and `ruff format --check .`: clean.
- `test_fused_lm_head.py` inject tests: checked on CPU that the tiny
Qwen3 resolves to `flash_attention_3` / `FlashAttention`; the GPU run is
left to CI.
- Manual CPU check: `get_model` builds `Qwen/Qwen3-1.7B` on the meta
device, and a Qwen2 config raises the new setup error.
- Not run: GPU unit tests (including the edited `test_fused_lm_head.py`,
`test_model.py`, `qwen3_5/test_vlm.py`), integration tests, and nightly
runs. There is no GPU on this machine.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> This is a breaking API and behavior change: unsupported architectures
hard-fail, and the hendrycks-sanity model swap can invalidate nightly
reward/KL gates until re-validated on GPU.
> 
> **Overview**
> **Removes the Hugging Face training path** by deleting `model.impl`
(`hf` / `custom` / `auto`). The trainer always loads PrimeRL classes
from `src/prime_rl/trainer/models/`; unknown `model_type` values fail at
setup with a clear error.
> 
> **Trainer/runtime cleanup:** `get_model` no longer branches to
`AutoModelForCausalLM` or HF VLMs, drops the CPU/meta fallback
(`can_reinit_empty_buffers`, `fix_model_post_empty`), and always uses
PrimeRL weight conversion and `init_buffers_post_meta`. **Removed**
Gemma softcapped LM head (`lm_head_gemma.py`), HF context-parallel
patches, and HF-specific MoE router freeze / forward handling.
> 
> **Config & docs:** `impl = "custom"` (and related validators tying EP,
CP, VLM, etc. to `impl`) are stripped from Pydantic configs, examples,
and docs. VLM registry narrows to Qwen3.5 families (drops `qwen3_vl`,
`gemma4` trainer paths). Sampling-replay docs no longer mention Gemma
rejection.
> 
> **Hendrycks sanity** now trains **`Qwen/Qwen3-1.7B`** instead of
`DeepSeek-R1-Distill-Qwen-1.5B` (no PrimeRL Qwen2 impl); dataset
filtering is still keyed to the distill model’s 20–80% band.
> 
> **Breaking:** configs with `model.impl` fail validation;
Qwen2/Gemma/Qwen3-VL and other unregistered archs cannot be trained.
Nightly sanity thresholds may need re-baselining on GPU.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3524e2eeabd2642b1e607a0b59ff0af6489ad3a8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

rebased on main 243cfba0f; resolved conflicts in
src/prime_rl/trainer/model.py (kept main's parallelize_module import),
src/prime_rl/utils/vlm.py (kept native qwen4_exp from #3434), and
dropped configs/basic/hendrycks-sanity + configs/debug/concurrency.toml
(deleted on main by #3777).
2026-10-03 15:45:27 -07:00
samsjaandGitHub 4c7c0d5d18 feat(configs): default optim.weight_decay to "auto" (0.0 for RL, 0.01 for SFT) (#3815)
## Summary

`optim.weight_decay` defaults to `"auto"` and resolves per trainer at
config-construction time: **`0.0` for RL**, **`0.01` for SFT** (the
historical default). Explicit values are untouched.

Follow-up to #2422, which flipped the shared default to `0.0` for both
trainers. Resolving per trainer keeps the RL motivation (no silent L2
decay of the policy during reward optimization) without changing SFT
behavior.

## How it works

Same pattern as `model.moe_router_dtype = "auto"`:

- `BaseOptimizerConfig.weight_decay` is now `Annotated[float,
Field(ge=0)] | Literal["auto"] = "auto"`.
- A `resolve_weight_decay_auto` model validator on `TrainerConfig` (RL)
resolves to `0.0`, and one on `SFTConfig` resolves to `0.01`.
- Because resolution happens at model construction, dumped configs
(`trainer.json` / `sft.json`) and `--help` always show the concrete
float — a resumed or reparsed run never sees `"auto"`.
- TOML / JSON / CLI overrides all keep working, including `weight_decay
= "auto"` explicitly.

| Trainer | `weight_decay` default |
| ------- | ---------------------- |
| RL (`rl`, `trainer`) | `0.0` |
| SFT (`sft`) | `0.01` (unchanged) |

## Notes

- Example configs that already set `weight_decay` explicitly are left
as-is; `examples/basic/wiki-search/rl.toml` and
`examples/advanced/glm-5.3/swe.toml` (`0.0`) now match the default and
could be simplified in a follow-up.
- LoRA runs resolve the same way (the optimizer is built from the same
`config.optim`).

## Testing

-
`tests/unit/test_configs.py::test_weight_decay_auto_resolves_per_trainer`
covers defaults, explicit floats, and the explicit `"auto"` string.
- Verified end-to-end locally: defaults, `RLConfig` sub-config,
`dump_resolved_config` output, TOML round-trip through `cli()`, and the
param group the optimizer receives.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Config-default change only at construction time; RL gets no weight
decay by default while SFT behavior stays at 0.01 unless users override.
> 
> **Overview**
> **`optim.weight_decay` now defaults to `"auto"`** on shared optimizer
config instead of a fixed `0.01`. At config construction, each trainer
resolves it to a concrete float—the same pattern as
`model.moe_router_dtype`.
> 
> RL **`TrainerConfig`** maps `"auto"` → **`0.0`** so policy training
does not apply L2 decay toward zero by default. SFT **`SFTConfig`** maps
`"auto"` → **`0.01`**, preserving the historical supervised default.
Explicit numeric values (and leaving `"auto"` in user input until
validation) behave as before; resolved dumps should show floats, not
`"auto"`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5219af74484473a3b4d884ec0569530e3521fa93. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 15:24:19 -07:00
faresobeidandGitHub 1f537d187b feat(trainer): MoE expert-load metrics (cv, max/mean, cold fraction) (#3799)
## What

Adds step-level MoE expert-load metrics to the RL and SFT trainers,
logged as mean and max over MoE layers:

- `expert_load/cv/{mean,max}`: std/mean of the per-expert token counts
in a layer.
- `expert_load/max_mean/{mean,max}`: the busiest expert's count divided
by the mean count.
- `expert_load/cold_frac/{mean,max}`: the fraction of experts that
receive under 0.1x the mean count. This is the MiMo-V2.6 §5.4
definition, so values compare directly with the paper.

## Why

MiMo-V2.6 §5.4 uses these three numbers to show that a trainable router
collapses expert load during RL (CV 0.78→2.0, cold experts 0.5%→22%
within 20 steps) and that freezing the router prevents it. We need the
same evidence to validate #3797 (freeze the router by default for RL) on
our models. The metrics also help catch EP load imbalance.

## How

- The MoE layers already add routed-token counts into the
`tokens_per_expert` buffer inside the forward pass. This uses the
existing `record_moe_routing_statistics` custom op, so it works with
compile without graph breaks. It covers both the torch and DeepEP
dispatch paths because the counts come from the router. **No model or
compiled code changes.**
- `get_global_moe_stats` now also returns this rank's raw per-layer
counts for the micro-step, captured before the existing EP reduction and
reset. The train loop sums them over the step. At step end, one
`all_reduce(SUM)` over `dp_cp` (which includes the EP ranks) produces
global counts, and the stats are computed from them. Extra cost: one
`[num_moe_layers, num_experts]` add per micro-step and one all-reduce
per step.
- Only aggregates over layers are logged, with no per-layer keys. This
follows the existing `max_vio`/`routing_confidence` convention, which
also reduces over layers. It also keeps the key count fixed for 75-layer
models. The max over layers catches a single collapsing layer, like
MiMo's layer 9.
- `max_vio` and `routing_confidence` are unchanged: they are still
per-micro-step.
- `docs/training.md` describes the new metrics.

No breaking changes. Existing metric keys are unchanged;
`get_global_moe_stats` now returns `(stats, tokens_per_expert)`
(internal function).

## Validation

- `pytest
tests/unit/train/models/{test_moe,test_checkpointing,test_qwen3_moe,test_glm4_moe,test_gpt_oss,test_deepseek_v4_cpu}.py
tests/unit/train/test_model.py tests/unit/test_configs.py -m "not gpu"`:
243 passed. This includes one new CPU test of the metric computation.
- `ruff check .` and `ruff format --check .`

Not run: there is no GPU on this machine. GPU checks still needed:
- [ ] EP>1 run (torch and DeepEP dispatch): `expert_load/*` values are
identical across ranks and plausible.
- [ ] Compiled run: no new recompiles or graph breaks
(`TORCH_LOGS=recompiles`).
- [ ] A short RL run with a frozen router vs a trainable router: the
trainable run should show `cv`/`cold_frac` rising.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Logging-only path using existing routing counters plus one optional
all_reduce per MoE step; no changes to loss, routing, or model forward
behavior.
> 
> **Overview**
> Adds **step-level MoE expert-load observability** aligned with
MiMo-V2.6 §5.4: trainers now log
`expert_load/{cv,max_mean,cold_frac}/{mean,max}` (coefficient of
variation, hottest-expert/mean ratio, and fraction of “cold” experts
under 0.1× mean load), aggregated as mean and max over MoE layers.
> 
> **Implementation:** `get_load_balance_stats` captures each rank’s
per-layer `tokens_per_expert` before EP reduction; micro-steps
accumulate counts across the step; `get_expert_load_stats` sums globally
over `dp_cp` and computes the three stats. Existing per-microstep
`max_vio` and `routing_confidence` logging is unchanged. RL and SFT
training loops wire the new metrics into step logs; `docs/training.md`
documents how to read them (e.g. rising `cv`/`cold_frac` when a
trainable router drifts).
> 
> A CPU unit test covers `compute_expert_load_stats`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9dde6e6ac625b4469c67ad2d20350d1bfbde9311. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 14:19:49 -07:00
faresobeidandGitHub f6fc1f7adc refactor(configs): define the weight-broadcast config once (#3788)
## Summary

The weight-broadcast config (filesystem | nccl | nixl) was declared four
times: the inference `WeightBroadcastConfig`, the trainer
`*WeightBroadcastConfig`, the orchestrator `*WeightBroadcastConfig`, and
the rl.py `Shared*WeightBroadcastConfig`.
`RLConfig.auto_setup_weight_broadcast` then copied each field between
them by hand. Every new transport field had to be added in four places
and in the copy code.

Design: one discriminated union `WeightBroadcastConfig` (`FileSystem` /
`NCCL` / `NIXL` variants) in `configs/shared.py`. The trainer,
orchestrator, inference, RLConfig, SFTConfig and the online eval config
all use it.
- `auto_setup_weight_broadcast` now does `model_copy()` of
`[weight_broadcast]` into the trainer and orchestrator, and sets
`inference_world_size` for in-memory transports. Inference gets a plain
copy. The inference server still reads only `type`.
- `validate_shared_weight_broadcast` is deleted. All three sub-configs
are now copies of the same object, so their types can't differ.
- SFT assigns the whole object to inference instead of mutating
`inference.weight_broadcast.type`.
- All three transports are kept.

Net: 82 lines added, 223 removed. Three class hierarchies, the
field-copy mapping and one validator are gone. No new abstractions.

## Breaking changes (all minor)

- `[weight_broadcast]` in `rl` now accepts `inference_world_size`. Like
before, the value is ignored: rl computes it.
- `[inference.weight_broadcast]` now accepts the transport fields
(`host`, `port`, `timeout`, ...). The inference server ignores them. The
resolved `inference.json` now contains them.
- Standalone `trainer.weight_broadcast.inference_world_size` must now be
`>= 1`. This matches the orchestrator, which already enforced it.
Before, `0` was accepted.
- Import paths: the classes now live in `prime_rl.configs.shared`. They
are no longer in `prime_rl.configs.trainer`, `.orchestrator` or
`.inference`.

## Validation

- Throwaway script (not committed): for every TOML in `configs/` and
`examples/`, parse it with every config class, plus sibling-base
overlays such as `glm-5.3/swe.toml @ swe-llmd.toml`. Dump the resolved
config on base and on this branch, then diff. Also covered: CLI cases
for rl/trainer/orchestrator/inference/sft with nccl/nixl/filesystem and
custom host/port/timeout/session_id. The only differences are the
additive or tightened cases listed under breaking changes. The trainer
and orchestrator `weight_broadcast` values are identical everywhere,
including glm-5.3 `swe.toml`, `swe.toml@swe-llmd.toml` and
nemotron-3-super.
- `rl --dry-run` / `sft --dry-run` on base vs branch for glm-5.3 swe,
glm-5.3 swe+llmd, nemotron-3-super swe, minimax-m2.5 swe, glm-4.5-air
swe+2-node, reverse-text (nccl and nixl), reverse-text sft and dynamo.
After normalizing paths, `trainer.json`, `orchestrator.json`, env
configs and `rl.sbatch` are byte-identical. `inference.json` only gains
the extra `weight_broadcast` fields.
- `pytest tests/unit -m "not gpu"`: 683 passed. 1 failure
(`test_cpu_adam`) also fails on main.
- `ruff check` and `ruff format --check` pass.
- No GPU on this machine, so GPU and integration tests (actual NCCL/NIXL
transfers) were not run.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches how RL/SFT wire trainer–orchestrator–inference weight transfer
(NCCL/NIXL sizing and config propagation); behavior is intended to match
prior dry-runs but import-path and validation changes could break custom
configs.
> 
> **Overview**
> **Consolidates trainer-to-inference weight broadcast settings** into a
single discriminated union (`filesystem` / `nccl` / `nixl`) in
`prime_rl.configs.shared`, removing parallel class hierarchies that
lived under trainer, orchestrator, RL `Shared*`, and manual per-field
copying.
> 
> `RLConfig.auto_setup_weight_broadcast` now **`model_copy()`**s the
shared `[weight_broadcast]` onto trainer and orchestrator (auto-filling
`inference_world_size` for in-memory transports) and sets inference to a
type-only config. **SFT** does the same for inference instead of
mutating `.type` alone. **`validate_shared_weight_broadcast`** is
dropped because all components share one schema.
> 
> Weight transport code (`transports/weights/*`, online eval) **imports
the shared types** instead of `configs.trainer`. Minor behavior/doc
shifts: RL rejects user-set `inference_world_size`, standalone trainer
enforces `inference_world_size >= 1`, and resolved `inference.json` may
include full broadcast fields the server ignores.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
937fc8a870e5559f40bc390653dd6c45dbd912d5. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 14:11:26 -07:00
faresobeidandGitHub 716d1cfac8 feat(orchestrator): optional length-weighted GRPO baseline (#3789)
Adds `length_weighted_baseline: bool = False` to `GRPOAlgoConfig`.

When enabled, the GRPO group baseline is the token-length-weighted mean
reward `b = sum_i(L_i * r_i) / sum_i(L_i)` instead of the plain mean.
`L_i` is the number of trainable (mask-True, policy-sampled) tokens of
rollout `i`, summed across all turns. Advantage is `r_i - b`. The
baseline is applied after the length penalty, same as the plain mean.
There is no fallback for a group with zero trainable tokens: then every
trace has `L_i = 0`, so `assign_advantages` writes no tokens, and no
metric, annotation or sample reads the (NaN) baseline.

Why: with token-level loss normalization, long rollouts carry more
gradient weight. A length-weighted baseline makes the per-token
advantage zero-mean across the group's tokens instead of across
rollouts.

- `routing.py`: pulls the trainable-node selection out of
`assign_advantages` into `trainable_nodes(trace)`, so `L_i` counts
exactly the tokens that receive the advantage.
- `echo` inherits the option because it subclasses GRPO.
- With the flag off, results are bit-identical to today: same `rewards -
rewards.mean()` computation.
- No breaking changes.

## Validation
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 301 passed. Includes the new
`test_grpo_length_weighted_baseline`, which covers the flag alone and
the flag combined with the length penalty (ordering).
- `ruff check .` and `ruff format --check .`: clean.
- GPU and integration tests were not run (no GPU on this machine).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Opt-in GRPO baseline change with default off; touches advantage math
only on the orchestrator scoring path, with targeted unit tests.
> 
> **Overview**
> Adds an opt-in **`length_weighted_baseline`** flag on GRPO-family
config (`GRPOAlgoConfig`, inherited by `echo`). When enabled, the group
baseline becomes the trainable-token-weighted mean of
(length-penalty-)shaped rewards instead of a plain rollout mean, so
advantages are **zero-mean per token** rather than per rollout—aligned
with token-normalized RL loss when long completions dominate gradient
mass.
> 
> **`GRPOAlgorithm.score_group`** now computes `shaped_rewards` first,
then either `mean(shaped_rewards)` or `sum(L_i * r_i) / sum(L_i)` with
`L_i` counting mask-True policy tokens across turns.
**`routing.trainable_nodes`** is extracted so `L_i` matches the tokens
that receive broadcast advantages via `assign_advantages`. Default
`false` preserves the existing centered-mean behavior.
> 
> Docs describe the math and ordering (after length penalty). Unit tests
cover the flag alone and combined with linear length penalty.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8f8d988d4957d02e61f28dfe0e46b1af3fefab7d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 14:00:33 -07:00
faresobeidandGitHub 87766fda3c refactor(launcher): share local launch-and-monitor code between rl and sft (#3792)
Unifies the local launch-and-monitor code in `rl_local` and `sft_local`.
Before this PR, both repeated the same machinery: Popen → log file →
monitor thread → error queue → SIGTERM/Ctrl-C/exception cleanup, GPU
partitioning from `CUDA_VISIBLE_DEVICES`, and the trainer torchrun
command. Each copy had small differences, which made the two launchers
drift.

## Design
`utils/process.py` already holds the launcher primitives
(`monitor_process`, `cleanup_processes`, env defaults). This PR adds
three small pieces there:
- `ProcessGroup`: a context manager. `start(name, cmd, env, log_path)`
starts a process with its log file and monitor thread. `wait(*names)`
blocks until the named processes exit and fails fast (exit 1) on the
first error from any process. SIGTERM, Ctrl-C, exceptions and normal
exit all clean up every process. The messages and ordering are the same
as the old inline code.
- `partition_gpus(num_infer, num_train)`: splits the physical GPUs into
inference GPUs followed by trainer GPUs, and raises the same
`ValueError` as before.
- `torchrun_cmd(module, config_path, nproc, log_dir, ranks_filter)`: the
shared single-node trainer command.

`rl_local` and `sft_local` keep their own commands and env dicts
unchanged. Only the plumbing moves. Net: −126 lines.

`inference.py` is not changed. Its only subprocess is the vllm-router.
The router inherits stdout (no log file), and its watcher SIGTERMs the
inference process itself. That does not fit the start/monitor/fail-fast
pattern, and forcing it in would change behavior. `eval.py` env servers
are also unmonitored on purpose, so they stay as they are. SLURM
rendering is not touched.

## Behavior
Behavior is the same: commands, env vars (including key order), log
paths, start order, kill order, exit codes and info/warning/error logs.
Two small differences:
- rl `--log-level debug` "command" lines now read `Inference command:
...` / `Train env server <name> command: ...` / `Trainer command: ...`
instead of `... start command: ...`.
- The rl wait loop is now the sft one: it checks errors before it checks
completion. Before, if the trainer failed *after* the orchestrator had
already exited, rl logged `Trainer failed with exit code N` from a
post-loop check. Now it logs `Error: Trainer failed with exit code N` /
`Terminating all processes...`. The exit code (1) and cleanup are the
same. The post-loop returncode checks could no longer be reached, so
they are removed. Side effect: if inference or an env server crashes in
the last ~1s, when the trainer and orchestrator also finish, the run now
fails instead of being ignored.

No config, metric, or checkpoint changes. No breaking changes.

## Validation
- I ran a throwaway (uncommitted) script against `rl_local`/`sft_local`,
once on `origin/main` and once on this branch, and diffed the results.
It fakes `subprocess.Popen` and `cleanup_process`, pins the free port,
uuid and `CUDA_VISIBLE_DEVICES=3,5,6,7`, and records each launch's exact
cmd, env delta, log path, kill sequence, exit code and logs. Configs:
reverse-text `rl.toml`, `configs/debug/multi-env/rl.toml`, reverse-text
`sft.toml` (online eval + inference), `configs/debug/fake/sft.toml`.
Scenarios: success;
trainer/orchestrator/inference/env-server/online-eval failure; trainer
failing after the orchestrator exits; SIGTERM; SIGINT; too many GPUs
requested. All records and exit codes were identical. The only log
differences are the two listed above.
- `pytest tests/unit -m "not gpu"`: 683 passed, 1 failed. The failure is
`test_cpu_adam.py::test_native_cpu_adamw_matches_fused_torch_and_preserves_gradients`,
which also fails on `origin/main` on this machine.
- `ruff check .` and `ruff format --check .` pass.
- No GPU on this machine, so I did not run any real launch or
integration test.

## Reviewer GPU checks (not run here)
- rl reverse-text e2e exits 0, and inference/env servers have no late
non-zero exits.
- SIGTERM and Ctrl-C mid-run leave no vLLM or torchrun workers.
- Trainer and inference logs are unchanged.
- sft with online eval waits for the eval to drain before it exits.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches core multi-process launcher lifecycle (spawn, monitor,
teardown) for training runs; behavior is mostly preserved but wait/error
ordering changes can alter exit outcomes at run end.
> 
> **Overview**
> **Refactors local RL and SFT launchers** so they no longer duplicate
subprocess orchestration; shared behavior lives in
`prime_rl.utils.process`.
> 
> Adds **`ProcessGroup`** (context manager with `start` / `wait`),
**`partition_gpus`**, and **`torchrun_cmd`**. Both `rl` and `sft`
entrypoints now start inference, env servers, orchestrator/online-eval,
and trainer through `ProcessGroup` instead of inline `Popen`, monitor
threads, error queues, and hand-rolled SIGTERM/Ctrl-C cleanup.
> 
> Commands, env vars, log paths, and start order are intended to stay
the same. **Minor differences:** debug log lines drop the `"start"`
prefix on command logs; RL’s wait loop now checks the error queue before
completion (aligned with SFT), so late failures from non-terminal
processes (e.g. inference/env server in the last second) can fail the
run where RL previously might have exited successfully.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fb27b22cf76aa28b094caedb07a646b7d5db7c7e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 13:53:33 -07:00
faresobeidandGitHub 73c4736352 refactor: move packing to orchestrator, DSv4 eager reference to tests, inline conversion_utils (#3785)
Pure moves + import updates. No logic change.

**Design / target structure**
- `trainer/batch.py` -> `orchestrator/batch.py`. Only
`orchestrator/packing.py` uses it. Nothing in `trainer/` imports it. Its
test already lives at `tests/unit/orchestrator/test_batch.py`.
- `trainer/models/deepseek_v4/eager_reference.py` ->
`tests/unit/train/models/deepseek_v4_eager_reference.py`. Only the DSv4
tests import it. Its docstring says nothing in production calls it.
- `trainer/conversion_utils.py` (one 10-line function) is inlined into
`transports/weights/nccl.py`, its only user.

**Left as is (not equivalent)**
- FLOPs models: `orchestrator/batch.py` (forward-cost coefficients for
bin balancing) and `trainer/perf.py` `_get_num_flop_per_token` (train
FLOPs for MFU, LoRA-aware) give different numbers. For example, o_proj
is `2*h*h` vs `h*heads*head_dim`, router params are counted only in
perf, and attention uses `head_dim` vs `h/heads`. On Qwen3-0.6B/1.7B,
Qwen3-VL-4B, Qwen3.5-2B and debug-moe they differ by 4-11%, so merging
them would change either the packing or the MFU metric.
- `list_shards` duplicate in `tools/convert_fp8_to_bf16.py` and
`tools/convert_bf16_to_fp8.py`: kept so `convert_fp8_to_bf16.py` stays
standalone (torch + safetensors only, no `prime_rl` import).
- Blockwise FP8 dequant: the tools version takes the block size from
`quantization_config` and handles shapes that are not multiples of the
block (via ceil + slice). The DSv4 version infers the block size from
the shape ratio, needs exact divisibility, and also handles MXFP4. They
are not interchangeable.
- `tools/convert_dcp_to_fp8.py` sibling imports: these already work from
the repo root and from any cwd. Python puts the script's directory on
`sys.path`, and the same holds under `torchrun`. I checked `--help` from
the repo root and from `/tmp`. No change needed.

**Breaking changes**
- Import paths: `prime_rl.trainer.batch` ->
`prime_rl.orchestrator.batch`. `prime_rl.trainer.conversion_utils` and
`prime_rl.trainer.models.deepseek_v4.eager_reference` are removed from
the package.

**Validation**
- `pytest tests/unit/orchestrator/test_batch.py
tests/unit/train/models/test_deepseek_v4_cpu.py
tests/unit/train/models/test_deepseek_v4.py
tests/unit/train/models/test_deepseek_v4_kernels.py
tests/unit/transports tests/unit/train/test_perf.py -m "not gpu"`: 31
passed, 97 deselected. Both DSv4 test modules import fine. No GPU on
this machine, so the GPU DSv4 tests and integration tests were not run.
- `ruff check .` and `ruff format --check .` both pass.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Import-path-only refactor with inlined helper code; no training,
packing, or NCCL broadcast logic changes, aside from downstream breakage
if anything still imports the removed modules.
> 
> **Overview**
> This PR reorganizes modules so orchestrator-only, test-only, and
single-use code no longer lives under `trainer/`. **Batch packing**
moves from `prime_rl.trainer.batch` to `prime_rl.orchestrator.batch`,
with `packing.py` and orchestrator unit tests updated to the new import
path.
> 
> **DeepSeek V4 eager reference** implementations move out of the
production package into
`tests/unit/train/models/deepseek_v4_eager_reference.py`; DSv4 GPU tests
import from there instead of
`prime_rl.trainer.models.deepseek_v4.eager_reference`.
> 
> **Layer counting for NCCL weight broadcast** drops the standalone
`trainer/conversion_utils.py` module: `get_max_layer_num` is defined
inline in `transports/weights/nccl.py`, its only caller. Behavior is
unchanged; callers must switch imports for batch and remove use of the
deleted trainer modules.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9287ae8ce22ba8731b80ebc1634ee0d5bbb25ea3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 13:42:11 -07:00
76 changed files with 626 additions and 1455 deletions
+4 -6
View File
@@ -36,7 +36,7 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
3. Native integration with [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) environments through the [Environments Hub](https://app.primeintellect.ai/dashboard/environments?ex_sort=most_stars), including built-in support for SWE and agentic environments.
4. End-to-end post-training: SFT, RL training, and evals.
5. Multi-node deployment with Slurm and Kubernetes support.
6. Multimodal support for VLMs such as Qwen3-VL.
6. Multimodal support for VLMs such as Qwen3.5.
7. Hackable, modular, and extensible by design.
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/advanced/glm-5.3/).
@@ -44,16 +44,14 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
## Models support
The trainer works with both Hugging Face and Prime custom `ModelForCausalLM` out of the box. For selected families (especially large MoE) we also ship highly optimized training code under `src/prime_rl/trainer/models/`, including expert parallelism (EP) for MoE layers and context parallelism (CP) for long sequences (see the table), and additional kernels like [quack-kernels](https://github.com/quack-kernels/quack-kernels).
With `[model] impl = "auto"` (the default), the trainer selects that custom stack when the Hugging Face config type is registered.
The trainer runs the PrimeRL model implementations under `src/prime_rl/trainer/models/`: dense Llama, Qwen3 and Qwen3.5, plus the families in the table below, with expert parallelism (EP) for MoE layers, context parallelism (CP) for long sequences, and additional kernels like [quack-kernels](https://github.com/quack-kernels/quack-kernels). Other architectures fail at trainer setup.
| Family | Example IDs | MoE | EP | CP |
|--------|-------------|-----|----|-----|
| GLM-5 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8` | yes | ✅ | ✅ |
| Qwen3 MoE (`qwen3_moe`) | `Qwen/Qwen3-30B-A3B`, … | yes | ✅ | ✅ |
| Qwen3.5 MoE (`qwen3_5_moe`) | `Qwen/Qwen3.5-35B-A3B`, … | yes | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#multimodal-training) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
| Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#multimodal-training) (`qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ✅ |
@@ -178,7 +176,7 @@ Follow this guide to learn the basics of prime-rl. You can train your own models
2. [**Wordle**](examples/basic/wordle/README.md): Train `Qwen3-1.7B` to play Wordle. A fun example of multi-turn SFT and RL training. Can be trained on a 2-4 H100 GPUs in a few hours. Ideal for exploring the multi-turn training capabilities of the framework.
3. [**Alphabet Sort**](examples/basic/alphabet-sort/README.md): Train `Qwen3-4B-Instruct-2507` to sort names alphabetically. Demonstrates multi-turn RL training via LoRA without SFT warmup. Can be trained on a single H100 GPU in just over an hour. Ideal for exploring LoRA-based training.
4. [**Wiki Search**](examples/basic/wiki-search/README.md): Train `Qwen3-4B-Instruct-2507` to answer trivia questions by searching through a Wikipedia. Demonstrates multi-turn with web search tool use.
5. [**Hendrycks Sanity**](examples/basic/hendrycks-sanity/README.md): Run a sanity check experiment on `DeepSeek-R1-Distill-Qwen-1.5B` using a filtered subset of MATH where the model already partially solves 20-80% of problems. Useful for algorithm ablations.
5. [**Hendrycks Sanity**](examples/basic/hendrycks-sanity/README.md): Run a sanity check experiment on `Qwen3-1.7B` using a subset of MATH filtered to problems that `DeepSeek-R1-Distill-Qwen-1.5B` partially solves (20-80%). Useful for algorithm ablations.
### Advanced Training: 32 - 2048 GPUs:
@@ -23,7 +23,6 @@ max_steps = 20
[model]
name = "deepseek-ai/DeepSeek-V4-Flash-0731"
impl = "custom"
ep = 8
# Torch all-to-all, not DeepEP. At full depth DeepEP dies on the first backward with
-1
View File
@@ -24,7 +24,6 @@ interval = 100
project = "minimax-swe"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
ep = 8
cp = 4
@@ -40,7 +40,6 @@ dist_timeout_seconds = 3600
enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
# Hybrid-Mamba model: ring CP is unsupported, so use ulysses (capped at 8 by n_groups).
cp = 8
@@ -15,9 +15,6 @@ name = "samsja/mini-glm-moe"
[trainer.optim]
lr = 3e-6
[trainer.model]
impl = "custom"
[orchestrator]
batch_size = 128
+1 -1
View File
@@ -11,7 +11,7 @@ name = "hendrycks-sanity"
[ckpt]
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
name = "Qwen/Qwen3-1.7B"
[orchestrator]
batch_size = 512
@@ -35,7 +35,6 @@ env.agent.runtime.type = "subprocess"
[trainer]
[trainer.model]
impl = "custom"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
+2 -10
View File
@@ -16,19 +16,14 @@ This page covers the specialized features layered on top of the core training st
## Custom Modeling
`prime-rl` ships custom optimized model implementations for several MoE families. With `model.impl = "auto"` (default) the trainer picks the custom path when the HF config type is registered, falling back to plain HF otherwise. To force one:
```toml
[trainer.model]
impl = "custom" # or "hf" to force the HF path
```
The trainer only runs `prime-rl`'s own model implementations, selected from the HF config type. Besides dense Llama, Qwen3 and Qwen3.5, these cover the families below. Other architectures fail at trainer setup.
| Family | HF config types | EP | CP |
|---|---|---|---|
| GLM-5 / GLM-5.2 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8`, `zai-org/GLM-5.2`, `zai-org/GLM-5.2-FP8` | ✅ | ✅ |
| Qwen3 MoE | `Qwen/Qwen3-30B-A3B`, … | ✅ | ✅ |
| Qwen3.5 MoE | `Qwen/Qwen3.5-35B-A3B`, … | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
| Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
| Laguna | `poolside/Laguna-XS.2` | ✅ | ✅ |
| MiniMax M2 | `MiniMax/MiniMax-M2` | ✅ | ✅ |
| Nemotron H | `nvidia/Nemotron-3-Nano-30B-A3B`, … | ✅ | ❌ |
@@ -37,8 +32,6 @@ impl = "custom" # or "hf" to force the HF path
| GPT-OSS | `unsloth/gpt-oss-20b-BF16`, … | ✅ | ✅ |
| DeepSeek V4 | `deepseek-ai/DeepSeek-V4-Flash-0731` | ✅ | ✅ |
Selective activation checkpointing works with either implementation. The custom path additionally enables EP, CP, low-precision training, and grouped MoE kernels. Forcing `impl = "hf"` is mostly useful when debugging and disables those model-specific runtime features.
GPT-OSS uses FlashAttention 4 with learned attention sinks. Training requires SM90 or SM100/SM110 GPUs
and a BF16 checkpoint such as `unsloth/gpt-oss-20b-BF16`; the original MXFP4 checkpoints are not supported.
@@ -161,7 +154,6 @@ Add `[model.vlm]` and bfloat16 dtypes:
```toml
[model]
name = "Qwen/Qwen3.5-4B"
impl = "custom"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
+11 -1
View File
@@ -188,7 +188,7 @@ $$
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
The orchestrator stamps each sample's component membership as per-token weight streams (`rl_weights` / `ce_weights` / `ref_kl_weights` on the wire): a weight scales that component's per-token loss, `0.0` leaves the token out of the component entirely (mask *and* denominator), and components may overlap on the same token — their gradients sum. Each $N$ is the global (all-reduced) count of that component's member tokens, so the components don't dilute each other: adding echo observation tokens never changes the rl term's effective per-token learning rate, and an sft env packed next to a GRPO env doesn't soften its gradient. Tokens of different components pack freely into the same micro batch, and a plain GRPO run ships no weight streams at all (absent streams mean rl weight 1.0 on every trainable token — the unchanged hot path). Advantages always ship per token (`advantages` on the wire), assigned as per-token streams from the start — uniform group credit is broadcast over completion tokens at assignment; algorithms with no rl credit (opd, opsd) ship none.
The orchestrator stamps each sample's component membership as per-token weight streams (`rl_weights` / `ce_weights` / `ref_kl_weights` on the wire): a weight scales that component's per-token loss, `0.0` leaves the token out of the component entirely (mask *and* denominator), and components may overlap on the same token — their gradients sum. Each $N$ is the global (all-reduced) count of that component's member tokens — for `rl`, the sum of its weights, which is the same count while weights are 0/1 — so the components don't dilute each other: adding echo observation tokens never changes the rl term's effective per-token learning rate, and an sft env packed next to a GRPO env doesn't soften its gradient. Tokens of different components pack freely into the same micro batch, and a plain GRPO run ships no weight streams at all (absent streams mean rl weight 1.0 on every trainable token — the unchanged hot path). Advantages always ship per token (`advantages` on the wire), assigned as per-token streams from the start — uniform group credit is broadcast over completion tokens at assignment; algorithms with no rl credit (opd, opsd) ship none.
### IPO Loss
@@ -325,6 +325,16 @@ type = "grpo"
type = "linear"
```
A **length-weighted baseline** (`length_weighted_baseline = true` on the `grpo`-family algorithms) replaces the plain group mean with $b = \sum_i L_i s_i / \sum_i L_i$, where $L_i$ is the number of trainable (policy-sampled, loss-masked) tokens of rollout $i$, summed across all its turns; it applies after the length penalty. With token-level loss normalization, long rollouts carry more gradient weight, so this baseline makes the per-token advantage zero-mean across the group's tokens rather than across rollouts.
**Prompt-mean loss aggregation** (`loss_aggregation = "prompt"` on `grpo` and `echo`; default `"token"`). By default every `rl` token in the batch weighs the same, so prompts whose groups produce long trajectories dominate the gradient. With `"prompt"`, the loss is MiMo-V2.6's prompt-mean (Eq. 1): the mean over prompt groups $q$ of $\frac{1}{T_q}\sum_{t \in q} \mathcal{L}_{rl,t}$, where $T_q$ is the group's total trainable tokens. MiMo uses it to keep response length from growing too fast. `score_group` gives each trainable token of the group the `rl` weight $1/T_q$, so each group's weights sum to 1 and $N_{rl}$ (the summed weights) is the number of groups in the step. Zero-advantage tokens are still dropped from the `rl` component, so a group with a zero-advantage rollout keeps less than its full weight of 1. All envs with an `rl` loss in a run must use the same `loss_aggregation`.
```toml
[orchestrator.train.algo]
type = "grpo"
loss_aggregation = "prompt"
```
### Hierarchical GRPO
GRPO gives each rollout its reward minus the average reward of comparable rollouts. In an ordinary single-agent group, every rollout answers the same task, so one group average is enough.
+1 -1
View File
@@ -246,7 +246,7 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
- [**Wordle**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/wordle) — `Qwen3-1.7B` playing Wordle. Multi-turn SFT + RL; 2–4 H100s.
- [**Alphabet Sort**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/alphabet-sort) — `Qwen3-4B-Instruct-2507` sorting names alphabetically. Multi-turn LoRA RL without SFT warmup; one H100.
- [**Wiki Search**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/wiki-search) — `Qwen3-4B-Instruct-2507` answering trivia by searching a Wikipedia corpus. Multi-turn with tool use.
- [**Hendrycks Sanity**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/hendrycks-sanity) — `DeepSeek-R1-Distill-Qwen-1.5B` on a filtered MATH subset. Useful for algorithm ablations.
- [**Hendrycks Sanity**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/hendrycks-sanity) — `Qwen3-1.7B` on a filtered MATH subset. Useful for algorithm ablations.
**Advanced** (32–2048 GPUs, SLURM):
-1
View File
@@ -117,7 +117,6 @@ Then run the full RL stack on reverse-text:
```bash
uv run rl @ configs/ci/integration/reverse-text-moe/start.toml \
--model.name samsja/mini-glm-moe \
--trainer.model.impl custom \
--inference.vllm.gpu-memory-utilization 0.7 \
--inference.vllm.max-model-len 2048
```
+1 -1
View File
@@ -311,7 +311,7 @@ top_p = 0.95
top_k = 512 # optional, defaults to 512 under truncation (bounds each sampling mask)
```
That's all — there are no replay flags. Truncated train sampling makes the inference server return sampling masks (`inference.enable_return_sampling_mask`, auto-enabled), and the trainer replays them. Train-sampling `top_k` above 512 is rejected: the trainer pads each micro batch to its largest sampling mask, so the bound caps trainer memory. Configs that would break under renormalized logprobs are rejected: `opd`/`opsd` and truncation knobs smuggled via `extra_body`; Gemma-family (softcapped) lm_heads fail loudly. Frozen-source envs are exempt.
That's all — there are no replay flags. Truncated train sampling makes the inference server return sampling masks (`inference.enable_return_sampling_mask`, auto-enabled), and the trainer replays them. Train-sampling `top_k` above 512 is rejected: the trainer pads each micro batch to its largest sampling mask, so the bound caps trainer memory. Configs that would break under renormalized logprobs are rejected: `opd`/`opsd` and truncation knobs smuggled via `extra_body`. Frozen-source envs are exempt.
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run with router replay on standard deployments. The combination is not supported with disaggregated P/D because NIXL routed-expert capture uses V1. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
+2 -5
View File
@@ -92,13 +92,12 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
### Expert Parallelism
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput.
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is at most 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
```toml
[trainer.model]
impl = "custom"
ep = 8 # explicit EP degree; must divide num_experts
[trainer.model.moe.dispatch]
@@ -116,7 +115,6 @@ CP shards a single sequence across multiple GPUs along the token dimension — f
```toml
[trainer.model]
impl = "custom"
attn = "auto" # auto = FA3 on Hopper, FA4 on datacenter Blackwell, FA2 otherwise; or flash_attention_2/3/4
cp = 2 # CP degree
cp_style = "ulysses" # "ring"
@@ -157,7 +155,7 @@ fused_lm_head_token_chunk_size = 1024 # default
# fused_lm_head_token_chunk_size = "disabled" # vanilla LM head
```
Drop the chunk size further when peak memory is still tight (e.g. with very long sequences); raise it to amortize kernel-launch overhead. SFT training silently disables this (not supported yet). Only available with `model.impl = "custom"`.
Drop the chunk size further when peak memory is still tight (e.g. with very long sequences); raise it to amortize kernel-launch overhead. SFT training silently disables this (not supported yet).
## Memory-Tight Recipe
@@ -165,7 +163,6 @@ The kitchen-sink config for fitting large MoE on limited GPUs at acceptable thro
```toml
[trainer.model]
impl = "custom"
ep = 8
cp = 2
+2 -1
View File
@@ -191,7 +191,7 @@ The same config selects the renderer for RL under `[orchestrator.renderer]`. The
**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 `<think>` 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, and VLM families such as Qwen3-VL/Qwen3.5.
**VLM training requires a custom PrimeRL implementation.** Training a model with `[model.vlm]` set (SFT or RL) requires `model.impl = "custom"` and only works for models with a registered PrimeRL VLM class (currently Qwen3.5 dense and MoE).
**VLM training requires a custom PrimeRL implementation.** Training a model with `[model.vlm]` set (SFT or RL) only works for models with a registered PrimeRL VLM class (currently Qwen3.5 dense and MoE).
See [Algorithms § Multi-Turn Trajectories](algorithms.md#multi-turn-trajectories) for the full picture.
@@ -280,6 +280,7 @@ Pulled from the console log and mirrored to W&B.
- `optim/grad_norm` — spikes precede divergence.
- `optim/lr` — LR schedule.
- For MoE: `max_vio/mean`, `max_vio/max` — mean and max over the step's microsteps of the largest load-balancing violation across layers and EP groups, computed from expert token counts summed across each EP group. `routing_confidence/mean` — mean routing confidence.
- For MoE: `expert_load/{cv,max_mean,cold_frac}/{mean,max}` — expert load per layer over the whole step, from token counts summed across all ranks, as the mean and max over MoE layers. `cv` is std/mean of the per-expert token counts, `max_mean` the busiest expert's count over the mean, and `cold_frac` the fraction of experts receiving under 0.1x the mean. A trainable router that drifts shows up as a rising `cv`/`cold_frac` (MiMo-V2.6 §5.4).
**Performance:**
@@ -45,7 +45,6 @@ dist_timeout_seconds = 3600
enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
@@ -59,7 +59,6 @@ enable_router_replay = true
name = "zai-org/GLM-4.5-Air"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
-1
View File
@@ -60,7 +60,6 @@ enable_router_replay = true
name = "zai-org/GLM-4.5-Air"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
@@ -46,7 +46,6 @@ dist_timeout_seconds = 3600
enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
@@ -6,7 +6,6 @@ TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
[model]
name = "zai-org/GLM-5.3-BF16"
impl = "custom"
attn = "flash_attention_2"
cp = 8
ep = 8
-1
View File
@@ -85,7 +85,6 @@ dist_timeout_seconds = 1800
[trainer.model]
name = "zai-org/GLM-5.3-BF16"
impl = "custom"
attn = "flash_attention_2" # ignored with GLM5
fused_lm_head_token_chunk_size = 1024
cp = 4 # context parallel for the 131K seq len
-1
View File
@@ -24,7 +24,6 @@ interval = 100
project = "intellect-3.1"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
ep = 8
cp = 2
@@ -24,7 +24,6 @@ interval = 100
project = "qwen30b-math"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
ep = 8
@@ -6,7 +6,6 @@ TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
[model]
name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
impl = "custom"
attn = "flash_attention_3"
ep = 8
-1
View File
@@ -24,7 +24,6 @@ interval = 100
project = "qwen30b-swe"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
ep = 8
cp = 2
-3
View File
@@ -11,9 +11,6 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
project = "alphabet-sort"
name = "alphabet-sort"
[trainer.model]
impl = "auto"
[trainer.model.ac]
freq = 1
+1 -1
View File
@@ -1,6 +1,6 @@
# Hendrycks Sanity
This example runs the Hendrycks Sanity Check experiment proposed in [Defeating the Training-Inference Mismatch](https://arxiv.org/abs/2510.26788). The sanity check tests whether an RL algorithm can reliably improve a model on problems it can *already partially solve*. The dataset is filtered from MATH to only include problems where the base model (`DeepSeek-R1-Distill-Qwen-1.5B`) solves 20-80% of the time across 40 rollouts. A reliable algorithm should push training accuracy on this "perfectible" subset above 95%.
This example runs the Hendrycks Sanity Check experiment proposed in [Defeating the Training-Inference Mismatch](https://arxiv.org/abs/2510.26788). The sanity check tests whether an RL algorithm can reliably improve a model on problems it can *already partially solve*. The dataset is filtered from MATH to only include problems that `DeepSeek-R1-Distill-Qwen-1.5B` solves 20-80% of the time across 40 rollouts. A reliable algorithm should push training accuracy on this "perfectible" subset above 95%. This example trains `Qwen3-1.7B` on that subset; the 20-80% band was measured for the distill model, not for `Qwen3-1.7B`.
Because our trainer is asynchronous, we perform only one gradient step per batch (the inference engine generates the next batch while the trainer processes the current one).
+1 -1
View File
@@ -9,7 +9,7 @@ num_train_gpus = 4
num_infer_gpus = 4
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
name = "Qwen/Qwen3-1.7B"
[orchestrator]
batch_size = 512
+1 -1
View File
@@ -1,6 +1,6 @@
# VLM SFT
Multimodal (VLM) supervised fine-tuning configs, dense and MoE. VLM training requires a custom PrimeRL implementation (`impl = "custom"`, `[model.vlm]` set — see [Advanced § Multimodal Training](../../../docs/advanced.md#multimodal-training)); these configs use the Qwen3.5 dense and Qwen3.6 MoE VLM implementations. Both LoRA-finetune with a frozen vision encoder and assistant-only loss masking.
Multimodal (VLM) supervised fine-tuning configs, dense and MoE. VLM training (`[model.vlm]` set) requires a PrimeRL VLM implementation (see [Advanced § Multimodal Training](../../../docs/advanced.md#multimodal-training)); these configs use the Qwen3.5 dense and Qwen3.6 MoE VLM implementations. Both LoRA-finetune with a frozen vision encoder and assistant-only loss masking.
| Config | Model | Hardware |
|---|---|---|
-1
View File
@@ -6,7 +6,6 @@ dist_timeout_seconds = 3600
name = "Qwen/Qwen3.6-35B-A3B"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
impl = "custom"
attn = "flash_attention_2"
ep = 8 # keep in sync with deployment.num_train_gpus
-1
View File
@@ -6,7 +6,6 @@ max_steps = 20
name = "Qwen/Qwen3.5-0.8B"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
impl = "custom"
[renderer]
name = "auto"
@@ -208,6 +208,12 @@ class GRPOAlgoConfig(BaseAlgoConfig):
length_penalty: LengthPenaltyConfig | None = None
"""Linear length penalty subtracted from each reward before the GRPO baseline (see ``LinearLengthPenaltyConfig``): a ``pass_rate``-scaled sum of output-token, input-token, and turns terms, each normalized by the group's own max for that quantity. None disables it."""
length_weighted_baseline: bool = False
"""Use the token-length-weighted group mean reward ``sum_i(L_i * r_i) / sum_i(L_i)`` as the baseline instead of the plain mean, where ``L_i`` is the number of trainable (mask-True, policy-sampled) tokens of rollout ``i`` summed across all its turns."""
loss_aggregation: Literal["token", "prompt"] = "token"
"""How the rl loss weights tokens across prompt groups. ``token``: every loss token in the batch weighs the same, so groups with more total tokens dominate the gradient. ``prompt``: prompt-mean (MiMo-V2.6 Eq. 1) — each trainable token of group ``q`` gets rl weight ``1 / T_q`` (``T_q`` = the group's trainable tokens), and the trainer divides the rl loss by the summed weights, i.e. the number of groups. All rl envs of a run must use the same value."""
class EchoAlgoConfig(GRPOAlgoConfig):
type: Literal["echo"] = "echo" # type: ignore[assignment]
@@ -6,8 +6,7 @@ from pydantic import AliasChoices, Field, model_validator
from prime_rl.configs.monitors import EvalMonitorsConfig
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
from prime_rl.configs.shared import ClientConfig, HeartbeatConfig, LogConfig, RunConfig
from prime_rl.configs.trainer import WeightBroadcastConfig
from prime_rl.configs.shared import ClientConfig, HeartbeatConfig, LogConfig, RunConfig, WeightBroadcastConfig
from prime_rl.utils.config import default_output_dir
@@ -14,13 +14,14 @@ from prime_rl.configs.algorithm import (
from prime_rl.configs.monitors import TrainMonitorsConfig
from prime_rl.configs.shared import (
BaseModelConfig,
BaseWeightBroadcastConfig,
ClientConfig,
EnvVars,
FileSystemWeightBroadcastConfig,
HeartbeatConfig,
LogConfig,
ResumeConfig,
TransportConfig,
WeightBroadcastConfig,
ZMQTransportConfig,
)
from prime_rl.configs.trainer import TokenizerConfig
@@ -484,47 +485,6 @@ class CheckpointConfig(BaseConfig):
"""Skip loading the progress from checkpoint."""
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
type: Literal["filesystem"] = "filesystem"
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
host: str = "localhost"
"""Weight transfer host."""
port: int
"""Weight transfer port."""
inference_world_size: int = Field(1, ge=1)
"""Total inference workers across all servers."""
class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nccl"] = "nccl"
port: int = 29501
"""Port for the NCCL broadcast rendezvous."""
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
port: int = 8001
"""ModelExpress gRPC port."""
session_id: str = "default"
"""ModelExpress session ID."""
overlap_transfer_and_replay: bool = False
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
Field(discriminator="type"),
]
class ConcurrencyConfig(BaseConfig):
"""Adaptive in-flight concurrency control. The orchestrator sizes the
in-flight episode cap from engine KV capacity and learned per-env episode
@@ -610,15 +570,12 @@ class OrchestratorConfig(BaseConfig):
tasks_per_minute: int | None = Field(None, ge=1)
"""Global rate limit on task dispatch, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. None disables rate limiting."""
batch_size: int | None = Field(None, ge=1)
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
batch_size: int = Field(128, ge=1)
"""Samples to train on per step."""
constant_trainer_batch_size: bool = True
"""Require each batch to reach its effective sample target."""
token_batch_size: int | None = Field(None, ge=1)
"""Tokens to train on per step (token-based batching). Set this OR ``batch_size``."""
concurrency: ConcurrencyConfig = ConcurrencyConfig()
"""Adaptive in-flight concurrency control (``[orchestrator.concurrency]``)."""
@@ -665,6 +622,19 @@ class OrchestratorConfig(BaseConfig):
env_cfg.algo.validate_env(env_cfg.env)
return self
@model_validator(mode="after")
def validate_loss_aggregation(self):
"""The trainer divides the rl loss by the batch's summed rl weights, so token-mean (weight
1 per token) and prompt-mean (weight 1 per group) envs can't share a batch."""
algos = [env.algo for env in self.train.source if env.algo.action_loss_type == "rl"]
aggregations = {algo.loss_aggregation if isinstance(algo, GRPOAlgoConfig) else "token" for algo in algos}
if len(aggregations) > 1:
raise ValueError(
"All train envs with an rl loss must use the same loss_aggregation: a prompt-mean group "
"would weigh as much as a single token of a token-mean env."
)
return self
@model_validator(mode="after")
def setup_truncated_sampling(self):
"""Truncated policy sampling trains with sampling replay (rollout
@@ -755,17 +725,8 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def resolve_batching(self):
has_rollout_batch = self.batch_size is not None
has_token_batch = self.token_batch_size is not None
if has_rollout_batch and has_token_batch:
raise ValueError("Set exactly one of batch_size or token_batch_size")
if not has_rollout_batch and not has_token_batch:
self.batch_size = 128
group_sizes = [source.group_size for source in self.train.source] or [self.train.group_size]
if self.batch_size is not None and any(self.batch_size % size for size in group_sizes):
if any(self.batch_size % size for size in group_sizes):
raise ValueError(
f"Batch size {self.batch_size} must be divisible by every train source's group_size {sorted(set(group_sizes))}"
)
@@ -8,34 +8,17 @@ from pydantic import Field, model_validator
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
from prime_rl.configs.monitors import FileMonitorConfig, PrimeTrainMonitorConfig
from prime_rl.configs.orchestrator import (
FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig,
)
from prime_rl.configs.orchestrator import (
NCCLWeightBroadcastConfig as OrchestratorNCCLWeightBroadcastConfig,
)
from prime_rl.configs.orchestrator import (
NIXLWeightBroadcastConfig as OrchestratorNIXLWeightBroadcastConfig,
)
from prime_rl.configs.orchestrator import (
OrchestratorConfig,
)
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.configs.shared import (
EnvVars,
FileSystemWeightBroadcastConfig,
NCCLWeightBroadcastConfig,
ResumeConfig,
RunConfig,
SlurmConfig,
TransportConfig,
VLMConfig,
)
from prime_rl.configs.trainer import (
FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig,
)
from prime_rl.configs.trainer import (
NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig,
)
from prime_rl.configs.trainer import (
NIXLWeightBroadcastConfig as TrainerNIXLWeightBroadcastConfig,
WeightBroadcastConfig,
)
from prime_rl.configs.trainer import (
TokenizerConfig,
@@ -50,7 +33,6 @@ from prime_rl.utils.validation import (
validate_shared_seq_len,
validate_shared_tokenizer,
validate_shared_wandb_config,
validate_shared_weight_broadcast,
)
@@ -128,50 +110,6 @@ class SharedModelConfig(BaseConfig):
"""VLM configuration. Set this to enable vision-language model support."""
class SharedInMemoryWeightBroadcastConfig(BaseConfig):
host: str = "localhost"
"""Weight transfer host."""
port: int
"""Weight transfer port."""
timeout: int = 1200
"""Timeout in seconds for the broadcast handshake and transfer."""
class SharedNCCLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
type: Literal["nccl"] = "nccl"
port: int = 29501
"""Port for NCCL weight broadcast."""
class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
port: int = 8001
"""ModelExpress gRPC port."""
session_id: str = "default"
"""ModelExpress session ID."""
overlap_transfer_and_replay: bool = False
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
class SharedFileSystemWeightBroadcastConfig(BaseConfig):
type: Literal["filesystem"] = "filesystem"
timeout: int = 1200
"""Timeout in seconds for the broadcast handshake and transfer."""
SharedWeightBroadcastConfig: TypeAlias = Annotated[
SharedFileSystemWeightBroadcastConfig | SharedNCCLWeightBroadcastConfig | SharedNIXLWeightBroadcastConfig,
Field(discriminator="type"),
]
class BaseDeploymentConfig(BaseConfig):
gpus_per_node: int = 8
"""GPUs per node."""
@@ -290,7 +228,7 @@ class RLConfig(BaseConfig):
seq_len: int | None = None
"""Shared sequence length. Propagates to ``trainer.model.seq_len`` and ``orchestrator.seq_len`` only when those values were not explicitly set; explicit per-component values always win."""
weight_broadcast: SharedWeightBroadcastConfig | None = None
weight_broadcast: WeightBroadcastConfig | None = None
rollout_transport: TransportConfig | None = None
@@ -446,52 +384,28 @@ class RLConfig(BaseConfig):
"""
if self.weight_broadcast is None:
if self.trainer.model.lora is not None or self.inference is None:
self.weight_broadcast = SharedFileSystemWeightBroadcastConfig()
self.weight_broadcast = FileSystemWeightBroadcastConfig()
else:
self.weight_broadcast = SharedNCCLWeightBroadcastConfig()
self.weight_broadcast = NCCLWeightBroadcastConfig()
if self.weight_broadcast.type != "filesystem" and self.trainer.model.lora is not None:
raise ValueError(
"LoRA requires weight_broadcast.type = 'filesystem': vLLM loads adapters only from a "
"PEFT-shaped directory on disk (LoRAModel.from_local_checkpoint) - in-memory transports "
"have no disk artifact to load from."
)
if self.weight_broadcast.type in ("nccl", "nixl"):
inference_world_size = (
if "inference_world_size" in self.weight_broadcast.model_fields_set:
raise ValueError("weight_broadcast.inference_world_size is set automatically by rl; remove it.")
update = {}
if self.weight_broadcast.type != "filesystem":
update["inference_world_size"] = (
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
if self.inference
else 1
)
common_config = dict(
host=self.weight_broadcast.host,
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
inference_world_size=inference_world_size,
)
if self.weight_broadcast.type == "nccl":
transport_config = {}
trainer_config_type = TrainerNCCLWeightBroadcastConfig
orchestrator_config_type = OrchestratorNCCLWeightBroadcastConfig
else:
transport_config = dict(
session_id=self.weight_broadcast.session_id,
overlap_transfer_and_replay=self.weight_broadcast.overlap_transfer_and_replay,
)
trainer_config_type = TrainerNIXLWeightBroadcastConfig
orchestrator_config_type = OrchestratorNIXLWeightBroadcastConfig
self.trainer.weight_broadcast = trainer_config_type(**common_config, **transport_config)
self.orchestrator.weight_broadcast = orchestrator_config_type(**common_config, **transport_config)
elif self.weight_broadcast.type == "filesystem":
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig(
timeout=self.weight_broadcast.timeout
)
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig(
timeout=self.weight_broadcast.timeout
)
self.trainer.weight_broadcast = self.weight_broadcast.model_copy(update=update)
self.orchestrator.weight_broadcast = self.weight_broadcast.model_copy(update=update)
if self.inference is not None:
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
validate_shared_weight_broadcast(self.trainer, self.orchestrator, self.inference)
return self
@model_validator(mode="after")
@@ -10,27 +10,28 @@ from renderers.base import MODEL_RENDERER_MAP
from prime_rl.configs.eval import SFTOnlineEvalConfig
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
from prime_rl.configs.monitors import TrainMonitorsConfig
from prime_rl.configs.shared import (
EnvVars,
FileSystemWeightBroadcastConfig,
HeartbeatConfig,
NCCLWeightBroadcastConfig,
ResumeConfig,
RunConfig,
SlurmConfig,
TrainerLogConfig,
WeightBroadcastConfig,
)
from prime_rl.configs.trainer import (
AdamWConfig,
CheckpointConfig,
ConstantSchedulerConfig,
FileSystemWeightBroadcastConfig,
GCConfig,
ModelConfig,
NCCLWeightBroadcastConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
WeightBroadcastConfig,
validate_scheduler,
)
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
@@ -275,6 +276,13 @@ class SFTConfig(BaseConfig):
self.model.moe_router_dtype = "bfloat16"
return self
@model_validator(mode="after")
def resolve_weight_decay_auto(self):
"""Resolve ``optim.weight_decay='auto'``: SFT keeps the historical 0.01 default — standard L2 regularization for supervised training."""
if self.optim.weight_decay == "auto":
self.optim.weight_decay = 0.01
return self
@model_validator(mode="after")
def auto_setup_run_identity(self):
"""Auto-generate the run name (``<dataset>--<model>--<short-id>``) when unset and
@@ -456,7 +464,7 @@ class SFTConfig(BaseConfig):
self.weight_broadcast.inference_world_size = (
self.deployment.num_infer_nodes * self.deployment.gpus_per_node
)
self.inference.weight_broadcast.type = self.weight_broadcast.type
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
if self.max_steps is None:
warnings.warn(
"Online evals without max_steps: the evals process never sees a final checkpoint, "
@@ -507,7 +515,7 @@ class SFTConfig(BaseConfig):
vllm.api_server_count = vllm.data_parallel_size
if self.weight_broadcast.type == "nccl":
self.weight_broadcast.inference_world_size = vllm.data_parallel_size * vllm.tensor_parallel_size
self.inference.weight_broadcast.type = self.weight_broadcast.type
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
host = self.inference.server.host or "localhost"
client = self.eval.client
@@ -609,13 +617,6 @@ class SFTConfig(BaseConfig):
raise ValueError("Muon optimizer does not support FSDP CPU offload")
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"):
raise ValueError("EP is only supported with the custom implementation or auto mode")
return self
### Auto-setup and validate shared configs
@model_validator(mode="after")
@@ -43,6 +43,48 @@ class BaseWeightBroadcastConfig(BaseConfig):
fails the run when no consumer acknowledges an offered version in time."""
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
type: Literal["filesystem"] = "filesystem"
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
host: str = "localhost"
"""Weight transfer host."""
port: int
"""Weight transfer port."""
inference_world_size: int = Field(1, ge=1)
"""Total inference workers across all servers. Set automatically by ``rl`` and ``sft``."""
class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nccl"] = "nccl"
port: int = 29501
"""Port for the NCCL broadcast rendezvous."""
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
port: int = 8001
"""ModelExpress gRPC port."""
session_id: str = "default"
"""ModelExpress session ID."""
overlap_transfer_and_replay: bool = False
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
Field(discriminator="type"),
]
"""Weight transfer from trainer to inference. ``rl`` copies its ``[weight_broadcast]`` to the trainer and orchestrator."""
class RunConfig(BaseConfig):
name: str | None = None
"""Run name. Auto-generated as ``<envs>--<model>--<short-id>`` when unset, so every launch gets a fresh, readable run directory; set an explicit name (e.g. an experiment name) to get a predictable run directory, which is also required to resume a previous run. Unless set explicitly, the W&B run name and the Prime platform run name inherit it."""
@@ -8,13 +8,14 @@ from pydantic import BeforeValidator, Field, field_validator, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.shared import (
BaseModelConfig,
BaseWeightBroadcastConfig,
EnvVars,
FileSystemWeightBroadcastConfig,
HeartbeatConfig,
MetricsServerConfig,
ResumeConfig,
TrainerLogConfig,
TransportConfig,
WeightBroadcastConfig,
ZMQTransportConfig,
)
from prime_rl.utils.config import BaseConfig, default_output_dir
@@ -314,9 +315,6 @@ class ModelConfig(BaseModelConfig):
cp_style: Literal["ring", "ulysses"] = "ring"
"""CP communication style. ``ring`` uses ring-attention all-gather/reduce-scatter (requires custom kernels per attention type). ``ulysses`` uses all-to-all to redistribute Q/K/V from sequence-sharded to head-sharded, runs vanilla attention locally on the full sequence, then all-to-all back — works out-of-the-box with any attention kernel (softmax FA, linear attention, mamba, etc.)."""
impl: Literal["hf", "custom", "auto"] = "auto"
"""Model implementation. ``auto`` selects ``custom`` if supported by the model, otherwise ``hf``."""
optimization_dtype: Literal["bfloat16", "float32"] = "float32"
"""dtype for model optimization."""
@@ -324,7 +322,7 @@ class ModelConfig(BaseModelConfig):
"""dtype for gradient/parameter reductions."""
moe_router_dtype: Literal["bfloat16", "float32", "auto"] = "auto"
"""Compute dtype for MoE router gates. ``float32`` keeps router gate weights in fp32 through forward and backward (exempt from FSDP bf16 parameter casting) and computes the gate GEMM and routing logits in fp32, matching models trained with fp32 routing (e.g. GLM-5.x via Megatron's ``--moe-router-dtype fp32``). ``bfloat16`` computes the gate GEMM in the model compute dtype. ``auto`` (default) resolves to ``float32`` for RL and ``bfloat16`` for SFT. Router score functions (sigmoid/softmax) run in fp32 regardless. Only affects the custom MoE implementation; a no-op for non-MoE and HF-impl models."""
"""Compute dtype for MoE router gates. ``float32`` keeps router gate weights in fp32 through forward and backward (exempt from FSDP bf16 parameter casting) and computes the gate GEMM and routing logits in fp32, matching models trained with fp32 routing (e.g. GLM-5.x via Megatron's ``--moe-router-dtype fp32``). ``bfloat16`` computes the gate GEMM in the model compute dtype. ``auto`` (default) resolves to ``float32`` for RL and ``bfloat16`` for SFT. Router score functions (sigmoid/softmax) run in fp32 regardless. A no-op for non-MoE models."""
quantization: QuantizationConfig | None = None
@@ -343,20 +341,6 @@ class ModelConfig(BaseModelConfig):
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 8192
"""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. In SFT the fused head computes the summed cross-entropy and its gradients chunk by chunk, holding one chunk's full-vocab logits at a time."""
@model_validator(mode="after")
def trust_remote_code_only_with_hf(self):
"""Trust remote code only if the model is from HF."""
if self.trust_remote_code:
if self.impl not in ("hf", "auto"):
raise ValueError("Trust remote code is only supported with the HF implementation or auto mode.")
return self
@model_validator(mode="after")
def vlm_only_with_custom_impl(self):
if self.vlm is not None and self.impl != "custom":
raise ValueError("VLM training requires model.impl='custom'")
return self
@model_validator(mode="after")
def vlm_cp_requires_ulysses(self):
if self.vlm is not None and self.cp > 1 and self.cp_style != "ulysses":
@@ -367,11 +351,6 @@ class ModelConfig(BaseModelConfig):
def validate_cp(self):
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]:
raise ValueError("CP is only supported with flash attention 2, 3, or 4")
if self.cp > 1 and self.impl not in ("custom", "auto"):
raise ValueError(
"Context parallelism requires model.impl='custom' or 'auto' "
"(resolved to a custom PrimeRL implementation)"
)
return self
@model_validator(mode="after")
@@ -392,19 +371,6 @@ class ModelConfig(BaseModelConfig):
)
return self
@model_validator(mode="after")
def flash_attention_4_only_with_custom_impl(self):
# "auto" may resolve to FA4 on Blackwell, so apply the same impl constraint.
if self.attn in ("flash_attention_4", "auto") 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 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")
def validate_moe_runtime(self):
if self.ep == 1:
@@ -490,8 +456,8 @@ class BaseOptimizerConfig(BaseConfig):
lr: float = Field(1e-6, ge=0)
"""Peak learning rate."""
weight_decay: float = Field(0.01, ge=0)
"""L2 weight-decay coefficient."""
weight_decay: Annotated[float, Field(ge=0)] | Literal["auto"] = "auto"
"""L2 weight-decay coefficient. ``"auto"`` (default) resolves to ``0.0`` for RL and ``0.01`` for SFT."""
max_norm: float | None = Field(1.0, ge=0)
"""Maximum gradient norm to clip to. If None, gradient clipping is disabled."""
@@ -659,48 +625,6 @@ class DataLoaderConfig(BaseConfig):
"""Use a fake data loader sampling random micro-batches (for debugging)."""
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
type: Literal["filesystem"] = "filesystem"
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
host: str = "localhost"
"""Weight transfer host."""
port: int
"""Weight transfer port."""
# TODO: Should not be configurable, but auto-inferred
inference_world_size: int = 1
"""Number of inference workers."""
class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nccl"] = "nccl"
port: int = 29501
"""Port for the NCCL broadcast rendezvous."""
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
port: int = 8001
"""ModelExpress gRPC port."""
session_id: str = "default"
"""ModelExpress session ID."""
overlap_transfer_and_replay: bool = False
"""Allocate two staging arenas so inference can replay one weight group while receiving the next."""
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
Field(discriminator="type"),
]
class TrainerConfig(BaseConfig):
model: ModelConfig = ModelConfig()
@@ -772,6 +696,13 @@ class TrainerConfig(BaseConfig):
self.model.moe_router_dtype = "float32"
return self
@model_validator(mode="after")
def resolve_weight_decay_auto(self):
"""Resolve ``optim.weight_decay='auto'``: RL optimizes the reward objective, not a fixed dataset — L2 decay toward zero fights it, so default to no weight decay."""
if self.optim.weight_decay == "auto":
self.optim.weight_decay = 0.0
return self
@model_validator(mode="after")
def deepep_disables_grad_clipping(self):
if self.model.ep != 1 and self.model.moe.dispatch.type == "deepep" and self.optim.max_norm is not None:
@@ -852,17 +783,3 @@ class TrainerConfig(BaseConfig):
if self.tokenizer.trust_remote_code is None:
self.tokenizer.trust_remote_code = self.model.trust_remote_code
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"):
raise ValueError("EP is only supported with the custom implementation or auto mode")
return self
@model_validator(mode="after")
def router_replay_only_with_custom_impl(self):
if self.enable_router_replay and self.model.impl not in ("custom", "auto"):
raise ValueError("Router replay is only supported with the custom implementation or auto mode")
return self
@@ -302,18 +302,3 @@ def validate_shared_tokenizer(
f"the shared tokenizer chat_template ({trainer.tokenizer.chat_template!r}). "
f"Use the shared [tokenizer] config to set chat_template for all components."
)
def validate_shared_weight_broadcast(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
inference: Optional[InferenceConfig] = None,
) -> None:
if trainer.weight_broadcast.type != orchestrator.weight_broadcast.type:
raise ValueError(
f"Trainer weight broadcast type ({trainer.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
)
if inference is not None and inference.weight_broadcast.type != trainer.weight_broadcast.type:
raise ValueError(
f"Inference weight broadcast type ({inference.weight_broadcast.type}) and trainer/orchestrator weight broadcast type ({trainer.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for all components."
)
+62 -216
View File
@@ -1,13 +1,9 @@
import json
import os
import signal
import subprocess
import sys
import time
import uuid
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
from urllib.parse import urlparse
from prime_rl.configs.algorithm import FrozenModelConfig
@@ -35,11 +31,10 @@ from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
DEFAULT_INFERENCE_ENV_VARS,
DEFAULT_TRAINER_ENV_VARS,
cleanup_processes,
cleanup_threads,
get_physical_gpu_ids,
monitor_process,
ProcessGroup,
partition_gpus,
set_proc_title,
torchrun_cmd,
)
RL_CONFIG = "rl.json"
@@ -141,25 +136,9 @@ def rl_local(config: RLConfig):
)
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
# Derive launcher-local GPU IDs from deployment config
gpu_offset = 0
num_infer_gpus = config.deployment.num_infer_gpus if config.inference is not None else 0
infer_local_gpu_ids = list(range(gpu_offset, gpu_offset + num_infer_gpus))
gpu_offset += num_infer_gpus
trainer_local_gpu_ids = list(range(gpu_offset, gpu_offset + config.deployment.num_train_gpus))
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus
physical_gpu_ids = get_physical_gpu_ids()
if total_requested_gpus > len(physical_gpu_ids):
raise ValueError(
f"Requested {total_requested_gpus} GPUs via deployment settings, but only "
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
)
physical_gpu_mapping = {local_id: physical_gpu_ids[local_id] for local_id in range(total_requested_gpus)}
logger.info(f"Using local->physical GPU mapping: {physical_gpu_mapping}")
infer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in infer_local_gpu_ids]
trainer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in trainer_local_gpu_ids]
infer_gpu_ids, trainer_gpu_ids = partition_gpus(num_infer_gpus, config.deployment.num_train_gpus)
logger.info(f"Using local->physical GPU mapping: {dict(enumerate(infer_gpu_ids + trainer_gpu_ids))}")
start_command = sys.argv
logger.debug(f"RL start command: {' '.join(start_command)}")
@@ -185,53 +164,22 @@ def rl_local(config: RLConfig):
f"Update the base_url to use port {expected_port} to match the inference server."
)
# Start processes
processes: list[Popen] = []
monitor_threads: list[Thread] = []
error_queue: list[Exception] = []
stop_events: dict[str, Event] = {}
def sigterm_handler(signum, frame):
logger.warning("Received SIGTERM, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
signal.signal(signal.SIGTERM, sigterm_handler)
try:
# Optionally, start inference process
with ProcessGroup() as processes:
if config.inference:
inference_cmd = ["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()]
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
logger.debug(f"Inference start command: {' '.join(inference_cmd)}")
# If we don't log stdout, the server hangs
with open(log_dir / "inference.log", "w") as log_file:
inference_process = Popen(
inference_cmd,
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_INFERENCE_ENV_VARS,
**config.env_vars,
**config.inference.env_vars,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
},
stdout=log_file,
stderr=log_file,
)
processes.append(inference_process)
# Start monitoring thread
stop_event = Event()
stop_events["inference"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(inference_process, stop_event, error_queue, "inference"),
daemon=True,
processes.start(
"inference",
["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()],
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_INFERENCE_ENV_VARS,
**config.env_vars,
**config.inference.env_vars,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
},
log_path=log_dir / "inference.log",
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
else:
logger.warning(
"No [inference] block configured - the policy inference server will not be started here. "
@@ -259,167 +207,65 @@ def rl_local(config: RLConfig):
# orchestrator start in parallel.
for split, source in env_servers(config):
name = source.resolved_name
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()]
logger.info(f"Starting {name} server")
logger.debug(f"Env server start command: {' '.join(env_server_cmd)}")
env_server_log = log_dir / ENVS_DIR / split / f"{name}.log"
env_server_log.parent.mkdir(parents=True, exist_ok=True)
with open(env_server_log, "w") as log_file:
env_server_process = Popen(
env_server_cmd,
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**config.env_vars,
**config.orchestrator.env_vars,
},
stdout=log_file,
stderr=log_file,
)
processes.append(env_server_process)
# Start monitoring thread
stop_event = Event()
stop_events[f"env/{split}/{name}"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(env_server_process, stop_event, error_queue, f"{split} env server {name}"),
daemon=True,
processes.start(
f"{split} env server {name}",
["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()],
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars, **config.orchestrator.env_vars},
log_path=log_dir / ENVS_DIR / split / f"{name}.log",
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()]
logger.info("Starting orchestrator")
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
with open(log_dir / "orchestrator.log", "w") as log_file:
orchestrator_process = Popen(
orchestrator_cmd,
stdout=log_file,
stderr=log_file,
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
**config.env_vars,
**config.orchestrator.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "orchestrator",
},
)
processes.append(orchestrator_process)
# Start monitoring thread
stop_event = Event()
stop_events["orchestrator"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(orchestrator_process, stop_event, error_queue, "orchestrator"),
daemon=True,
processes.start(
"orchestrator",
["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()],
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
**config.env_vars,
**config.orchestrator.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "orchestrator",
},
log_path=log_dir / "orchestrator.log",
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Start training process
from prime_rl.utils.utils import get_free_port
trainer_cmd = [
"torchrun",
"--role=trainer",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
# Pipe all logs to file, and only master rank logs to stdout
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
f"--local-ranks-filter={','.join(map(str, config.trainer.log.ranks_filter))}",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={len(trainer_gpu_ids)}",
"-m",
"prime_rl.trainer.rl.train",
"@",
(config_dir / TRAINER_CONFIG).as_posix(),
]
logger.info(f"Starting trainer on GPU(s) {' '.join(map(str, trainer_gpu_ids))}")
logger.debug(f"Training start command: {' '.join(trainer_cmd)}")
with open(log_dir / "trainer.log", "w") as log_file:
trainer_process = Popen(
trainer_cmd,
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_TRAINER_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
**config.env_vars,
**config.trainer.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "trainer",
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
},
stdout=log_file,
stderr=log_file,
)
processes.append(trainer_process)
# Start monitoring thread
stop_event = Event()
stop_events["trainer"] = stop_event
monitor_thread = Thread(
target=monitor_process, args=(trainer_process, stop_event, error_queue, "trainer"), daemon=True
processes.start(
"trainer",
torchrun_cmd(
"prime_rl.trainer.rl.train",
config_dir / TRAINER_CONFIG,
len(trainer_gpu_ids),
log_dir,
config.trainer.log.ranks_filter,
),
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_TRAINER_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
**config.env_vars,
**config.trainer.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "trainer",
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
},
log_path=log_dir / "trainer.log",
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
logger.success("Launcher complete")
log_dashboard_url(logger, dashboard_url)
# Trainer and orchestrator completion is the successful stop condition.
completion_events = (stop_events["trainer"], stop_events["orchestrator"])
while not all(event.is_set() for event in completion_events):
if error_queue:
error = error_queue[0]
logger.error(f"Error: {error}")
logger.error("Terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
# Small delay to avoid busy waiting
time.sleep(1)
# Check if any critical process failed
if orchestrator_process.returncode != 0:
logger.error(f"Orchestrator failed with exit code {orchestrator_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
if trainer_process.returncode != 0:
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
processes.wait("trainer", "orchestrator")
logger.success("Training finished!")
# Cleanup threads and processes
cleanup_threads(monitor_threads)
cleanup_processes(processes)
except KeyboardInterrupt:
logger.warning("Received interrupt signal, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
except Exception as e:
logger.error(f"Error occurred: {e}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
raise
def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script_path: Path) -> None:
"""Write the SLURM script to disk."""
+25 -101
View File
@@ -1,12 +1,9 @@
import json
import os
import signal
import subprocess
import sys
import uuid
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
from prime_rl.configs.eval import SFTOnlineEvalConfig
from prime_rl.configs.monitors import EvalMonitorsConfig, PrimeEvalMonitorConfig, TrainMonitorsConfig
@@ -34,11 +31,10 @@ from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
DEFAULT_INFERENCE_ENV_VARS,
DEFAULT_TRAINER_ENV_VARS,
cleanup_processes,
cleanup_threads,
get_physical_gpu_ids,
monitor_process,
ProcessGroup,
partition_gpus,
set_proc_title,
torchrun_cmd,
)
SFT_CONFIG = "sft.json"
@@ -333,21 +329,14 @@ def sft_local(config: SFTConfig):
)
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
# launcher must partition GPUs between processes; plain SFT leaves them to torchrun.
# Partition GPUs (inference first, then the trainer) only when the launcher must split
# them between processes; plain SFT leaves them to torchrun.
infer_gpu_ids: list[int] = []
trainer_gpu_ids: list[int] = []
if config.inference is not None:
num_infer_gpus = config.deployment.num_infer_gpus
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus
physical_gpu_ids = get_physical_gpu_ids()
if total_requested_gpus > len(physical_gpu_ids):
raise ValueError(
f"Requested {total_requested_gpus} GPUs via deployment settings, but only "
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
)
infer_gpu_ids = physical_gpu_ids[:num_infer_gpus]
trainer_gpu_ids = physical_gpu_ids[num_infer_gpus:total_requested_gpus]
infer_gpu_ids, trainer_gpu_ids = partition_gpus(
config.deployment.num_infer_gpus, config.deployment.num_train_gpus
)
# Trainer and online-eval log to a single shared W&B run whose id ($WANDB_RUN_ID)
# equals $PRL_RUN_ID, one label per process.
@@ -364,37 +353,11 @@ def sft_local(config: SFTConfig):
"WANDB_ARGS": json.dumps(sys.argv),
}
processes: list[Popen] = []
monitor_threads: list[Thread] = []
error_queue: list[Exception] = []
stop_events: dict[str, Event] = {}
def sigterm_handler(signum, frame):
logger.warning("Received SIGTERM, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
signal.signal(signal.SIGTERM, sigterm_handler)
def start_process(name: str, cmd: list[str], env: dict[str, str], log_path: Path) -> Popen:
logger.debug(f"{name.capitalize()} command: {' '.join(cmd)}")
log_path.parent.mkdir(parents=True, exist_ok=True)
with open(log_path, "w") as log_file:
process = Popen(cmd, env=env, stdout=log_file, stderr=log_file)
processes.append(process)
stop_event = Event()
stop_events[name] = stop_event
monitor_thread = Thread(target=monitor_process, args=(process, stop_event, error_queue, name), daemon=True)
monitor_thread.start()
monitor_threads.append(monitor_thread)
return process
try:
with ProcessGroup() as processes:
# Optionally, start the inference server for online evals
if config.inference is not None:
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
start_process(
processes.start(
"inference",
["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()],
env={
@@ -413,7 +376,7 @@ def sft_local(config: SFTConfig):
for source in eval_env_servers(config):
name = source.resolved_name
logger.info(f"Starting {name} server")
start_process(
processes.start(
f"env/eval/{name}",
["env-server", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()],
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars},
@@ -422,7 +385,7 @@ def sft_local(config: SFTConfig):
if config.eval is not None:
logger.info("Starting online evals")
start_process(
processes.start(
"online-eval",
[sys.executable, "-m", "prime_rl.eval.online", "@", (config_dir / ONLINE_EVAL_CONFIG).as_posix()],
env={
@@ -439,23 +402,6 @@ def sft_local(config: SFTConfig):
log_path=log_dir / "eval.log",
)
from prime_rl.utils.utils import get_free_port
trainer_cmd = [
"torchrun",
"--role=trainer",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
f"--local-ranks-filter={','.join(map(str, config.log.ranks_filter))}",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={config.deployment.num_train_gpus}",
"-m",
"prime_rl.trainer.sft.train",
"@",
config_path.as_posix(),
]
gpus_suffix = f" on GPU(s) {' '.join(map(str, trainer_gpu_ids))}" if trainer_gpu_ids else ""
logger.info(f"Starting SFT trainer with {config.deployment.num_train_gpus} GPU(s){gpus_suffix}")
trainer_env = {
@@ -470,48 +416,26 @@ def sft_local(config: SFTConfig):
trainer_env["WANDB_SHARED_LABEL"] = "trainer"
if trainer_gpu_ids:
trainer_env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, trainer_gpu_ids))
trainer_process = start_process("trainer", trainer_cmd, env=trainer_env, log_path=log_dir / "trainer.log")
processes.start(
"trainer",
torchrun_cmd(
"prime_rl.trainer.sft.train",
config_path,
config.deployment.num_train_gpus,
log_dir,
config.log.ranks_filter,
),
env=trainer_env,
log_path=log_dir / "trainer.log",
)
logger.success("Launcher complete")
log_dashboard_url(logger, dashboard_url)
# Wait for the trainer (and the online-eval process, which drains its final evals
# after the trainer's last checkpoint) while surfacing any process failure.
terminal_events = [stop_events["trainer"]]
if "online-eval" in stop_events:
terminal_events.append(stop_events["online-eval"])
while True:
pending = [event for event in terminal_events if not event.is_set()]
if error_queue:
logger.error(f"Error: {error_queue[0]}")
logger.error("Terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
if not pending:
break
pending[0].wait(timeout=1)
if trainer_process.returncode != 0:
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
processes.wait("trainer", *(["online-eval"] if config.eval is not None else []))
logger.success("SFT training finished!")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
except KeyboardInterrupt:
logger.warning("Received interrupt signal, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
except Exception as e:
logger.error(f"Error occurred: {e}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
raise
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
+1 -1
View File
@@ -18,7 +18,7 @@ import os
from prime_rl import monitors
from prime_rl.configs.eval import SFTOnlineEvalConfig
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
from prime_rl.configs.shared import FileSystemWeightBroadcastConfig
from prime_rl.eval.runner import POLL_INTERVAL_S, EvalRunner
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
from prime_rl.utils.config import cli, dump_resolved_config
+18 -3
View File
@@ -6,7 +6,7 @@ import verifiers.v1 as vf
from prime_rl.configs.algorithm import GRPOAlgoConfig
from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
from prime_rl.orchestrator.algo.routing import assign_advantages
from prime_rl.orchestrator.algo.routing import assign_advantages, trainable_nodes
if TYPE_CHECKING:
from prime_rl.orchestrator.clients import InferenceClient
@@ -20,6 +20,8 @@ class GRPOAlgorithm(Algorithm):
def __init__(self, config: GRPOAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.length_penalty = config.length_penalty
self.length_weighted_baseline = config.length_weighted_baseline
self.loss_aggregation = config.loss_aggregation
async def score_group(self, episodes: list[vf.Episode]) -> None:
import torch # only the trainer-side extras ship torch; an eval process never scores a group
@@ -28,7 +30,7 @@ class GRPOAlgorithm(Algorithm):
rewards = torch.tensor([trace.reward for trace in traces], dtype=torch.float32)
length_penalty = self.length_penalty
if length_penalty is None:
advantages = rewards - rewards.mean()
shaped_rewards = rewards
else:
output = torch.tensor([trace.num_output_tokens for trace in traces], dtype=rewards.dtype)
total = torch.tensor([trace.num_total_tokens for trace in traces], dtype=rewards.dtype)
@@ -41,6 +43,19 @@ class GRPOAlgorithm(Algorithm):
)
penalty = rewards.mean() * penalty_frac
shaped_rewards = rewards - penalty
advantages = shaped_rewards - shaped_rewards.mean()
baseline = shaped_rewards.mean()
if self.length_weighted_baseline:
lengths = torch.tensor(
[sum(sum(node.mask) for node in trainable_nodes(trace)) for trace in traces], dtype=rewards.dtype
)
baseline = (lengths * shaped_rewards).sum() / lengths.sum()
advantages = shaped_rewards - baseline
for trace, advantage in zip(traces, advantages.tolist(), strict=True):
assign_advantages(trace, advantage)
nodes = [node for trace in traces for node in trainable_nodes(trace)]
if self.loss_aggregation == "prompt" and nodes:
# rl weight 1/T_q per token: each group's weights sum to 1, and the trainer divides the
# rl loss by the sum of rl weights, i.e. the number of groups.
weight = 1.0 / sum(sum(node.mask) for node in nodes)
for node in nodes:
node.loss_weights = {**(node.loss_weights or {}), "rl": [weight if m else 0.0 for m in node.mask]}
+7 -2
View File
@@ -8,10 +8,15 @@ from prime_rl.configs.algorithm import ActionLossType
from prime_rl.transports.batch import TrainingSample
def trainable_nodes(trace: vf.Trace) -> list[vf.MessageNode]:
"""Nodes with sampled (mask-True) tokens on the trace's trainable branches, in graph order."""
on_trainable_branch = {id(node) for branch in trace.branches if branch.trainable for node in branch.nodes}
return [node for node in trace.nodes if id(node) in on_trainable_branch and any(node.mask)]
def assign_advantages(trace: vf.Trace, values: float | list[float]) -> None:
"""Assign credit in compact sampled-token order across trainable graph paths."""
trainable_nodes = {id(node) for branch in trace.branches if branch.trainable for node in branch.nodes}
nodes = [node for node in trace.nodes if id(node) in trainable_nodes and any(node.mask)]
nodes = trainable_nodes(trace)
for node in nodes:
if len(node.mask) != len(node.token_ids):
raise ValueError(
+1 -2
View File
@@ -372,7 +372,6 @@ class Orchestrator:
train_envs=self.train_envs,
progress=self.progress,
batch_size=config.batch_size,
token_batch_size=config.token_batch_size,
on_result=self.train_source.on_result,
)
@@ -814,7 +813,7 @@ class Orchestrator:
inflight_by_env = self.dispatcher.inflight_by_env
inflight_train = self.dispatcher.inflight_train_count
inflight_eval = self.dispatcher.inflight_eval_count
train_batch, train_target, _train_unit = self.train_sink.batch_progress()
train_batch, train_target = self.train_sink.batch_progress()
train_buffered = self.train_sink.buffered_count()
train_batch_by_env = self.train_sink.pending_batch_by_env()
eval_batches = self.eval_sink.batch_progress() if self.eval_sink is not None else []
+1 -1
View File
@@ -1,7 +1,7 @@
from transformers import AutoConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.trainer.batch import build_bin_cost, prepare_batch
from prime_rl.orchestrator.batch import build_bin_cost, prepare_batch
from prime_rl.transports.batch.types import MicroBatch, TrainingSample
from prime_rl.utils.logger import get_logger
+9 -58
View File
@@ -26,11 +26,6 @@ from prime_rl.transports.batch import TrainingSample
from prime_rl.utils.logger import get_logger
def payload_tokens(samples: list[TrainingSample], trace: vf.Trace | None = None) -> int:
"""Token cost of one trainer-bound trace."""
return sum(len(sample.token_ids) for sample in samples) or (trace.num_total_tokens if trace is not None else 0)
def _prune_zero_advantages(sample: TrainingSample) -> bool:
"""Remove zero-advantage tokens from the RL component."""
if sample.advantages is None:
@@ -69,19 +64,14 @@ class TrainSink:
tokenizer,
train_envs: TrainEnvs,
progress: Progress,
batch_size: int | None,
token_batch_size: int | None,
batch_size: int,
on_result: Callable[[list[vf.Episode]], bool] | None = None,
) -> None:
assert (batch_size is None) != (token_batch_size is None), (
"Exactly one of batch_size / token_batch_size must be set"
)
self.config = config
self.tokenizer = tokenizer
self.train_envs = train_envs
self.progress = progress
self.batch_size = batch_size
self.token_batch_size = token_batch_size
self.on_result = on_result
self.pending_episodes = TrainEpisodes()
@@ -95,7 +85,6 @@ class TrainSink:
self.pending_group_cancellations: dict[str, GroupCancellation] = {}
self.pending_batch: dict[str, list[TrainingSample]] = {}
self.episode_by_trace: dict[str, vf.Episode] = {}
self.pending_tokens = 0
# Queued traces voided by the staleness sweep since the last ship;
# read and reset by the orchestrator's per-step metrics.
self.stale_drops = 0
@@ -108,11 +97,8 @@ class TrainSink:
def group_size_for(self, env_name: str) -> int:
return self.train_envs.get(env_name).config.group_size
def batch_progress(self) -> tuple[int, int, str]:
if self.batch_size is not None:
return len(self.pending_batch), self.batch_size, "traces"
assert self.token_batch_size is not None
return self.pending_tokens, self.token_batch_size, "tokens"
def batch_progress(self) -> tuple[int, int]:
return len(self.pending_batch), self.batch_size
def buffered_count(self) -> int:
episodes = sum(len(group) for group in self.pending_groups.values())
@@ -170,12 +156,7 @@ class TrainSink:
"""Sweep stale queued traces, then cut a batch if the survivors still
meet the threshold."""
self._drop_stale()
ready = (
len(self.pending_batch) >= self.batch_size
if self.batch_size is not None
else self.pending_tokens >= (self.token_batch_size or 0)
)
return self.process_batch() if ready else None
return self.process_batch() if len(self.pending_batch) >= self.batch_size else None
def _drop_stale(self, trace_ids: Iterable[str] | None = None) -> None:
"""Void queued traces past ``max_off_policy_steps``. The batch being
@@ -205,9 +186,7 @@ class TrainSink:
policy = train_work(episode).policy
if policy is None or policy.start >= min_version:
continue
samples = self.pending_batch.pop(trace_id)
if self.token_batch_size is not None:
self.pending_tokens -= payload_tokens(samples, self._trace(trace_id))
del self.pending_batch[trace_id]
del self.episode_by_trace[trace_id]
self.pending_episodes.cancelled.add(episode.id)
dropped += 1
@@ -306,10 +285,6 @@ class TrainSink:
for trace in episode.traces:
if trace.id in samples_by_trace:
self.episode_by_trace[trace.id] = episode
if self.token_batch_size is not None:
self.pending_tokens += sum(
payload_tokens(samples, self._trace(trace_id)) for trace_id, samples in samples_by_trace.items()
)
self._drop_stale(samples_by_trace)
# A group's traces share one dispatch version, so the insertion sweep
# voids all or none of them. A fully-voided group shipped nothing —
@@ -322,10 +297,6 @@ class TrainSink:
self.zero_output_units = 0
self.reported_zero_output_windows = 0
def _trace(self, trace_id: str) -> vf.Trace:
episode = self.episode_by_trace[trace_id]
return next(trace for trace in episode.traces if trace.id == trace_id)
def _admit(self, group: list[vf.Episode]) -> bool:
return self.on_result(group) if self.on_result is not None else True
@@ -333,22 +304,15 @@ class TrainSink:
"""``n_owed`` counts the group's full episode budget (arrived +
cancelled), so dropped groups advance the zero-output tally at the
same rate as fully-delivered ones."""
if self.batch_size is not None:
returned_traces = sum(len(episode.traces) for episode in group)
self.zero_output_units += len(survivors) or returned_traces or n_owed
else:
survivor_tokens = sum(trace.num_total_tokens for trace in survivors)
episode_tokens = sum(episode.num_total_tokens for episode in group)
self.zero_output_units += survivor_tokens or episode_tokens or self.config.seq_len * n_owed
returned_traces = sum(len(episode.traces) for episode in group)
self.zero_output_units += len(survivors) or returned_traces or n_owed
self._warn_zero_output()
def _warn_zero_output(self) -> None:
"""Warn once per batch-equivalent of finalized units that shipped no
payload, so a run that produces no training signal stays visible in the
logs without aborting."""
target = self.batch_size if self.batch_size is not None else self.token_batch_size
assert target is not None
windows = self.zero_output_units // target
windows = self.zero_output_units // self.batch_size
if windows <= self.reported_zero_output_windows:
return
self.reported_zero_output_windows = windows
@@ -358,20 +322,7 @@ class TrainSink:
)
def process_batch(self) -> TrainBatch:
items = list(self.pending_batch.items())
if self.batch_size is not None:
selected = items[: self.batch_size]
else:
assert self.token_batch_size is not None
cut = 0
running = 0
for index, (trace_id, samples) in enumerate(items):
running += payload_tokens(samples, self._trace(trace_id))
cut = index + 1
if running >= self.token_batch_size:
break
selected = items[:cut]
self.pending_tokens -= running
selected = list(self.pending_batch.items())[: self.batch_size]
selected_by_trace = dict(selected)
selected_ids = set(selected_by_trace)
-13
View File
@@ -1,13 +0,0 @@
from torch import Tensor
def get_max_layer_num(state_dict: dict[str, Tensor], layer_prefix: str = "model.layers.") -> int:
"""Get the maximum number of layers in the model."""
max_num = -1
for key in state_dict:
if not key.startswith(layer_prefix):
continue
layer_num_str = key[len(layer_prefix) :].split(".")[0]
if layer_num_str.isdigit():
max_num = max(max_num, int(layer_num_str))
return max_num + 1
+105 -233
View File
@@ -23,7 +23,7 @@ from torch.distributed.fsdp._fully_shard._fsdp_common import FSDPMeshInfo, Shard
from torch.distributed.fsdp._fully_shard._fsdp_init import _get_mesh_info
from torch.distributed.tensor import Shard
from torch.distributed.tensor.parallel import parallelize_module
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, GenerationConfig, PretrainedConfig
from transformers import AutoConfig, AutoTokenizer, GenerationConfig, PretrainedConfig
from transformers.tokenization_utils import PreTrainedTokenizer
from transformers.utils.import_utils import is_flash_attn_3_available
@@ -41,7 +41,6 @@ from prime_rl.trainer.distributed.embedding_parallel import EmbeddingParallel
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,
PreTrainedModelPrimeRL,
PrimeLmOutput,
cast_float_and_contiguous,
get_custom_causal_lm_cls,
@@ -134,19 +133,10 @@ def freeze_moe_router(model: nn.Module) -> None:
for layer in language_model.layers:
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
if mlp is None:
continue
# Custom implementation
if isinstance(mlp, MoE):
for param in mlp.router.parameters():
param.requires_grad = False
num_frozen += 1
# HuggingFace implementation: gate may have been wrapped with LoRA.
elif hasattr(mlp, "gate") and isinstance(mlp.gate, nn.Module):
for param in mlp.gate.parameters():
param.requires_grad = False
num_frozen += 1
if num_frozen == 0:
raise ValueError("No MoE router parameters found to freeze. Is this a MoE model?")
@@ -171,8 +161,8 @@ def apply_fp32_moe_router(model: nn.Module) -> None:
mlp.router.fp32_gate = True
num_routers += 1
# No-op for non-MoE and HF-impl models: moe_router_dtype='float32' is the default,
# so absence of custom-impl MoE routers is the common case, not an error.
# No-op for non-MoE models: moe_router_dtype='float32' is the default,
# so absence of MoE routers is the common case, not an error.
if num_routers > 0:
logger.info(f"Running {num_routers} MoE router gates in fp32")
@@ -235,7 +225,7 @@ def apply_force_balanced_routing(model: nn.Module) -> None:
num_routers += 1
if num_routers == 0:
raise ValueError("No MoE routers found to force-balance. Is this a custom-impl MoE model?")
raise ValueError("No MoE routers found to force-balance. Is this a MoE model?")
logger.warning(
f"Forced balanced routing on {num_routers} MoE layers (debug.force_balanced_routing=True). "
@@ -252,7 +242,10 @@ def get_load_balance_stats(
model: nn.Module,
group: dist.ProcessGroup | None = None,
) -> dict[str, Tensor | None]:
"""Compute routing stats after summing raw counts across the group, if given."""
"""Compute routing stats after summing raw counts across the group, if given.
Also returns this rank's raw per-layer expert counts (`[num_moe_layers, num_experts]`) for step-level stats.
"""
per_layer_max_vio = []
per_layer_routing_confidence = []
language_model = get_language_model(model)
@@ -263,8 +256,9 @@ def get_load_balance_stats(
if block_mlp is not None and hasattr(block_mlp, "tokens_per_expert"):
block_mlps.append(block_mlp)
if not block_mlps:
return {"max_vio": None, "routing_confidence": None}
return {"max_vio": None, "routing_confidence": None, "tokens_per_expert": torch.empty(0, 0)}
local_tokens_per_expert = torch.stack([block_mlp.tokens_per_expert for block_mlp in block_mlps])
layer_stats = [(block_mlp.tokens_per_expert, block_mlp.routing_confidence_sum) for block_mlp in block_mlps]
if group is not None:
sizes = [tokens_per_expert.numel() + 1 for tokens_per_expert, _ in layer_stats]
@@ -289,6 +283,7 @@ def get_load_balance_stats(
return {
"max_vio": torch.stack(per_layer_max_vio),
"routing_confidence": torch.stack(per_layer_routing_confidence),
"tokens_per_expert": local_tokens_per_expert,
}
@@ -296,10 +291,15 @@ def get_global_moe_stats(
model: nn.Module,
ep_group: dist.ProcessGroup | None,
dp_cp_group: dist.ProcessGroup,
) -> dict[str, Tensor]:
"""Reduce one microstep's routing stats across EP, then DP and CP ranks."""
) -> tuple[dict[str, Tensor], Tensor]:
"""Reduce one microstep's routing stats across EP, then DP and CP ranks.
Also returns this rank's unreduced per-layer expert counts, to accumulate over the step for `get_expert_load_stats`.
"""
stats = {}
for name, values in get_load_balance_stats(model, group=ep_group).items():
load_balance_stats = get_load_balance_stats(model, group=ep_group)
tokens_per_expert = load_balance_stats.pop("tokens_per_expert")
for name, values in load_balance_stats.items():
if values is None:
continue
value = values.max() if name == "max_vio" else values.mean()
@@ -309,9 +309,36 @@ def get_global_moe_stats(
dist.all_reduce(value, op=dist.ReduceOp.SUM, group=dp_cp_group)
value /= dist.get_world_size(dp_cp_group)
stats[name] = value.to("cpu")
return stats, tokens_per_expert
def compute_expert_load_stats(tokens_per_expert: Tensor) -> dict[str, Tensor]:
"""Per-layer expert-load balance from `[num_moe_layers, num_experts]` token counts, as mean and max over layers.
`cv` is std/mean of the expert loads, `max_mean` the busiest expert's load over the mean load, and `cold_frac`
the fraction of experts receiving under 0.1x the mean load (the MiMo-V2.6 definition).
"""
mean_load = tokens_per_expert.mean(dim=1)
per_layer = {
"cv": tokens_per_expert.std(dim=1, correction=0) / mean_load,
"max_mean": tokens_per_expert.amax(dim=1) / mean_load,
"cold_frac": (tokens_per_expert < 0.1 * mean_load[:, None]).float().mean(dim=1),
}
stats = {}
for name, values in per_layer.items():
stats[f"expert_load/{name}/mean"] = values.mean()
stats[f"expert_load/{name}/max"] = values.max()
return stats
def get_expert_load_stats(tokens_per_expert: Tensor, group: dist.ProcessGroup) -> dict[str, float]:
"""Sum a step's per-layer expert counts across the group (every rank routes distinct tokens) and compute load stats."""
if tokens_per_expert.numel() == 0: # MoE model without prime-rl MoE layers (HF impl)
return {}
dist.all_reduce(tokens_per_expert, op=dist.ReduceOp.SUM, group=group)
return {name: value.item() for name, value in compute_expert_load_stats(tokens_per_expert).items()}
def get_model(
config: ModelConfig, device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.bfloat16
) -> nn.Module:
@@ -395,31 +422,14 @@ def get_model(
)
target_config.num_hidden_layers = num_hidden_layers
# Determine the implementation to use
custom_vlm_cls = get_custom_vlm_cls(model_config) if is_vlm_arch else None
if config.impl == "auto":
if is_vlm_arch:
impl_to_use = "custom" if custom_vlm_cls is not None else "hf"
else:
impl_to_use = "custom" if supports_custom_impl(model_config) else "hf"
logger.info(f"Auto-selected implementation: {impl_to_use}")
else:
impl_to_use = config.impl
if config.attn in ("flash_attention_3", "flash_attention_4") and impl_to_use == "hf":
if custom_vlm_cls is None and not supports_custom_impl(model_config):
raise ValueError(
f"{config.attn} requires model.impl='custom' or 'auto' (resolved to 'custom'), "
f"but model.impl resolved to 'hf'. Set model.impl='custom' explicitly."
f"{model_config.model_type!r} has no PrimeRL model implementation. "
"The trainer only supports the architectures in prime_rl.trainer.models."
)
if config.cp > 1 and config.impl == "auto" and impl_to_use != "custom":
raise ValueError(
"Context parallelism with model.impl='auto' requires a supported custom PrimeRL implementation, "
"but this architecture resolved to model.impl='hf'."
)
# Past the check above, cp > 1 implies impl_to_use == "custom", so the model class always
# resolves. Queried here so a misconfigured job dies at setup rather than at the first forward.
# Queried here so a misconfigured job dies at setup rather than at the first forward.
if config.cp > 1:
cp_model_cls = custom_vlm_cls or get_custom_causal_lm_cls(model_config)
support = cp_model_cls.cp_support(model_config)
@@ -430,40 +440,25 @@ def get_model(
f"({support.reason}); {supported}."
)
if config.vlm is not None and not (is_vlm_arch and custom_vlm_cls):
if config.vlm is not None and custom_vlm_cls is None:
raise ValueError(
"VLM training requires a registered custom PrimeRL VLM implementation; "
f"{getattr(model_config, 'model_type', config.name)!r} has none."
f"VLM training requires a registered PrimeRL VLM implementation; {model_config.model_type!r} has none."
)
with device:
if impl_to_use == "custom" and custom_vlm_cls is not None:
model_cls = custom_vlm_cls
elif is_vlm_arch:
from transformers import AutoModelForImageTextToText
model_cls = AutoModelForImageTextToText
else:
match impl_to_use:
case "hf":
model_cls = AutoModelForCausalLM
case "custom":
model_cls = AutoModelForCausalLMPrimeRL
model_cls = custom_vlm_cls or AutoModelForCausalLMPrimeRL
load_model_start_time = time.perf_counter()
# HF VLM models require torch_dtype; custom PrimeRL models and text Auto models use dtype
use_torch_dtype = is_vlm_arch and model_cls is not custom_vlm_cls
dtype_kwarg = {"torch_dtype": dtype} if use_torch_dtype else {"dtype": dtype}
if device == torch.device("meta"):
logger.info(f"Loading model {config.name} using {model_cls.__name__} to meta device")
model = model_cls.from_config(model_config, trust_remote_code=config.trust_remote_code, **dtype_kwarg)
model = model_cls.from_config(model_config, trust_remote_code=config.trust_remote_code, dtype=dtype)
else:
logger.info(f"Loading model {config.name} using {model_cls.__name__} to CPU")
model = model_cls.from_pretrained(
pretrained_model_name_or_path=config.name,
config=model_config,
trust_remote_code=config.trust_remote_code,
**dtype_kwarg,
dtype=dtype,
)
logger.debug(f"Loaded model {config.name} in {format_time(time.perf_counter() - load_model_start_time)}")
@@ -717,10 +712,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
torch.distributed.barrier()
# Must run before any weight loading: reinit can zero persistent buffers that ship in checkpoints
if isinstance(model, PreTrainedModelPrimeRL):
model.init_buffers_post_meta()
else:
fix_model_post_empty(model)
model.init_buffers_post_meta()
logger = get_logger()
if config.debug.random_init:
@@ -739,54 +731,49 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
# Dynamically convert between different weight formats if needed.
# 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):
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())
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 source_path.name == "prime" and not (source_path / ".prime-v1").is_file():
raise RuntimeError(f"PrimeRL conversion cache {source_path} is missing the required .prime-v1 marker")
if source_path.name == "prime" and not (source_path / ".prime-v1").is_file():
raise RuntimeError(f"PrimeRL conversion cache {source_path} is missing the required .prime-v1 marker")
snapshot_is_hf = model.is_hf_state_dict(snapshot_keys)
snapshot_is_prime = model.is_prime_state_dict(snapshot_keys)
snapshot_is_hf = model.is_hf_state_dict(snapshot_keys)
snapshot_is_prime = model.is_prime_state_dict(snapshot_keys)
if snapshot_is_hf and not snapshot_is_prime 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..."
if snapshot_is_hf and not snapshot_is_prime 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 = 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_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(source_path)
model.convert_to_prime(snapshot_state_dict)
save_state_dict(snapshot_state_dict, snapshot_path)
(snapshot_path / ".prime-v1").touch()
del snapshot_state_dict
snapshot_state_dict = load_state_dict(source_path)
model.convert_to_prime(snapshot_state_dict)
save_state_dict(snapshot_state_dict, snapshot_path)
(snapshot_path / ".prime-v1").touch()
del snapshot_state_dict
elif snapshot_is_prime and not snapshot_is_hf and model.is_hf_state_dict(model_keys):
logger.warning(
"Found PrimeRL weight format in snapshot state dict and HF weight format in model state dict. Trying to auto-convert..."
elif snapshot_is_prime and not snapshot_is_hf and model.is_hf_state_dict(model_keys):
logger.warning(
"Found PrimeRL weight format in snapshot state dict and HF weight format in model state dict. Trying to auto-convert..."
)
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_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(source_path)
model.convert_to_hf(snapshot_state_dict)
save_state_dict(snapshot_state_dict, snapshot_path)
del snapshot_state_dict
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
# All ranks wait for master rank to finish conversion
torch.distributed.barrier()
if (
isinstance(model, PreTrainedModelPrimeRL)
and snapshot_path.name == "prime"
and not (snapshot_path / ".prime-v1").is_file()
):
if snapshot_path.name == "prime" and not (snapshot_path / ".prime-v1").is_file():
raise RuntimeError(f"PrimeRL conversion cache {snapshot_path} is missing the required .prime-v1 marker")
logger.info(f"Loading weights using HF DCP from {snapshot_path}")
@@ -800,10 +787,6 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
storage_reader=HuggingFaceStorageReader(path=snapshot_path.as_posix()),
)
write_back_loaded_packed_parameters(model, state_dict)
# Restore weight tying broken by to_empty() for HF models
if not isinstance(model, PreTrainedModelPrimeRL) and model.config.tie_word_embeddings:
model.tie_weights()
_move_buffers_to_cuda(model, config)
lora_modules = [m for m in model.modules() if hasattr(m, "_init_lora_parameters")]
@@ -822,80 +805,6 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
logger.debug(f"Loaded weights using HF DCP in {format_time(time.perf_counter() - load_dcp_start_time)}")
def can_reinit_empty_buffers(model: nn.Module):
"""Whether the model will be loaded correctly by load_dcp_from_hf.
The main issue is with anything that is not in the checkpoint.
This is usually any non-persistent buffers.
"""
# Custom PrimeRL models handle buffer reinit via init_buffers_post_meta
if isinstance(model, PreTrainedModelPrimeRL):
return True
buffer_names = [name for name, _ in model.named_buffers()]
# TT MoE buffers
buffer_names = [
name
for name in buffer_names
if not (name.startswith("model.layers.") and name.endswith("mlp.tokens_per_expert"))
]
buffer_names = [
name
for name in buffer_names
if not (name.startswith("model.layers.") and name.endswith("mlp.router.selection_bias"))
]
# HF standard transformer model
if len(buffer_names) == 1 and buffer_names[0] == "model.rotary_emb.inv_freq":
return True
# GPT-OSS (has original_inv_freq alongside inv_freq from dynamic rope scaling)
gpt_oss_buffers = {"model.rotary_emb.inv_freq", "model.rotary_emb.original_inv_freq"}
if set(buffer_names) == gpt_oss_buffers:
return True
# Gemma3 model (has embed_scale and local rotary emb)
gemma3_buffers = {"model.embed_tokens.embed_scale", "model.rotary_emb.inv_freq", "model.rotary_emb_local.inv_freq"}
if set(buffer_names) == gemma3_buffers:
return True
get_logger().warning(f"Model cannot be loaded using meta device because of buffers: {buffer_names}")
return False
def fix_model_post_empty(model: nn.Module):
buffer_names = [name for name, _ in model.named_buffers()]
# HF standard transformer model
if "model.rotary_emb.inv_freq" in buffer_names:
rotary_emb = model.model.rotary_emb
if hasattr(rotary_emb, "rope_init_fn"):
rope_init_fn = rotary_emb.rope_init_fn
else:
# GPT-OSS stores rope_init_fn only as a local in __init__; re-derive it
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
rope_init_fn = (
ROPE_INIT_FUNCTIONS[rotary_emb.rope_type]
if rotary_emb.rope_type != "default"
else rotary_emb.compute_default_rope_parameters
)
inv_freq, rotary_emb.attention_scaling = rope_init_fn(rotary_emb.config, rotary_emb.inv_freq.device)
rotary_emb.inv_freq.copy_(inv_freq)
if "model.rotary_emb.original_inv_freq" in buffer_names:
rotary_emb.original_inv_freq.copy_(inv_freq)
# Gemma3 local rotary emb
if "model.rotary_emb_local.inv_freq" in buffer_names:
rotary_emb_local = model.model.rotary_emb_local
inv_freq_local, rotary_emb_local.attention_scaling = rotary_emb_local.rope_init_fn(
rotary_emb_local.config, rotary_emb_local.inv_freq.device
)
rotary_emb_local.inv_freq.copy_(inv_freq_local)
# Gemma3 embed_scale (scalar computed from hidden_size)
if "model.embed_tokens.embed_scale" in buffer_names:
embed_scale = model.config.hidden_size**0.5
model.model.embed_tokens.embed_scale.fill_(embed_scale)
def reshard_module(model: nn.Module):
for module in model.modules():
if isinstance(module, FSDPModule):
@@ -1039,21 +948,9 @@ def setup_model(
logger = get_logger()
# 1. We load to meta device by default
# Build on the meta device; weights are materialized after FSDP sharding.
model = get_model(config, device=torch.device("meta"), dtype=DTYPE_MAP[config.optimization_dtype])
possible_to_load_to_meta = can_reinit_empty_buffers(model)
if config.debug.random_init and not possible_to_load_to_meta:
raise ValueError(
"It's not possible to load to meta device and random initialize is enabled. Please disable random initialize or use a different model."
)
# 1a. We load to CPU if we cannot reinit empty buffers
if not possible_to_load_to_meta:
logger.warning("Cannot load model to meta device only, loading to CPU instead.")
model = get_model(config, device=torch.device("cpu"), dtype=DTYPE_MAP[config.optimization_dtype])
if config.fusions.enabled and config.lora is not None:
logger.warning("Skipping runtime model fusions because LoRA targets the unfused projections")
elif config.fusions.enabled:
@@ -1105,31 +1002,17 @@ def setup_model(
setup_fsdp(model, config, parallel_dims)
if not possible_to_load_to_meta:
if loading_from_checkpoint_later:
logger.warning(
"Skipping loading weights. Initializing an empty model on device, loading from checkpoint later."
)
device = "cpu" if config.fsdp_cpu_offload else "cuda"
model.to_empty(device=device)
torch.distributed.barrier()
model.init_buffers_post_meta()
_move_buffers_to_cuda(model, config)
# 2. if we can load to meta, we either:
if possible_to_load_to_meta:
# - load from checkpoint later if needed
if loading_from_checkpoint_later:
logger.warning(
"Skipping loading weights. Initializing an empty model on device, loading from checkpoint later."
)
device = "cpu" if config.fsdp_cpu_offload else "cuda"
model.to_empty(device=device)
torch.distributed.barrier()
if isinstance(model, PreTrainedModelPrimeRL):
model.init_buffers_post_meta()
else:
fix_model_post_empty(model)
# Restore weight tying broken by to_empty() for HF models
if model.config.tie_word_embeddings:
model.tie_weights()
_move_buffers_to_cuda(model, config)
# - or load from HF with dcp
else:
load_dcp_from_hf(model, config, parallel_dims)
else:
load_dcp_from_hf(model, config, parallel_dims)
_reset_runtime_moe_buffers(model)
return model
@@ -1156,13 +1039,9 @@ def forward(
"input_ids": input_ids,
"labels": labels,
"temperature": temperature,
"sampling_mask": sampling_mask,
}
# Sampling masks are consumed by the injected prime lm_head; HF
# forwards don't know the kwarg, so only pass it when present.
if sampling_mask is not None:
kwargs["sampling_mask"] = sampling_mask
if mm_kwargs:
kwargs.update(mm_kwargs)
if mm_token_type_ids is not None:
@@ -1177,17 +1056,10 @@ def forward(
else:
kwargs["position_ids"] = position_ids
if isinstance(model, PreTrainedModelPrimeRL):
kwargs["seq_lens"] = seq_lens
kwargs["seq_lens_are_pre_shard"] = seq_lens_are_pre_shard
kwargs["seq_lens"] = seq_lens
kwargs["seq_lens_are_pre_shard"] = seq_lens_are_pre_shard
if routed_experts is not None:
kwargs["routed_experts"] = routed_experts
out = model(**kwargs)
# PrimeLmOutput is a TypedDict (dict at runtime), HF outputs are dataclass-like objects
if isinstance(out, dict):
return cast_float_and_contiguous(out)
return cast_float_and_contiguous(PrimeLmOutput(logits=out.logits))
return cast_float_and_contiguous(model(**kwargs))
@@ -9,7 +9,6 @@ import torch.nn.functional as F
from torch import Tensor
from prime_rl.utils.logger import get_logger
from prime_rl.utils.vlm import get_final_logit_softcapping
# Same as torch's cross entropy loss
IGNORE_INDEX = -100
@@ -385,14 +384,6 @@ def inject_prime_lm_head(
logger = get_logger()
# Check for Gemma-style softcapping - dispatch to specialized implementation.
final_logit_softcapping = get_final_logit_softcapping(model.config)
if final_logit_softcapping:
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
# Replace the lm_head with the appropriate wrapper
old_lm_head = model.lm_head
if isinstance(chunk_size, int):
@@ -1,213 +0,0 @@
from __future__ import annotations
import torch
import torch.nn as nn
from torch import Tensor
from prime_rl.trainer.models.layers.lm_head import (
IGNORE_INDEX,
PrimeLmOutput,
_online_logsumexp_and_weighted_update,
_patch_model_forward,
cross_entropy_sum,
)
from prime_rl.utils.logger import get_logger
class GemmaFusedOutputLinear(torch.nn.Linear):
def __init__(self, in_features: int, out_features: int, chunk_size: int, softcap: float):
super().__init__(in_features, out_features, bias=False)
self.chunk_size = chunk_size
self.softcap = softcap
def forward(
self,
hidden_states: torch.Tensor,
labels: torch.Tensor | None = None,
temperature: Tensor | None = None,
sampling_mask: Tensor | None = None,
) -> PrimeLmOutput:
assert labels is not None, "GemmaFusedOutputLinear requires labels for chunked logprob computation"
assert sampling_mask is None, "sampling-mask replay is not supported with Gemma softcapped lm_heads"
b, s, h = hidden_states.shape
hidden_states = hidden_states.reshape(b * s, h).contiguous()
labels = labels.reshape(b * s).contiguous()
if temperature is None:
# Summed cross-entropy through the logprob path; IGNORE_INDEX rows are masked at the sum.
inv_t = torch.ones(b * s, device=hidden_states.device, dtype=torch.float32)
logprobs, _ = _GemmaChunkedLogProbEntropyFn.apply(
hidden_states, self.weight, labels, inv_t, self.chunk_size, self.softcap
)
return PrimeLmOutput(loss=-logprobs[labels != IGNORE_INDEX].sum())
inv_t = 1.0 / temperature.reshape(b * s).contiguous() # [N]
logprobs, entropy = _GemmaChunkedLogProbEntropyFn.apply(
hidden_states, self.weight, labels, inv_t, self.chunk_size, self.softcap
)
logprobs = logprobs.reshape(b, s)
entropy = entropy.reshape(b, s)
return PrimeLmOutput(logprobs=logprobs, entropy=entropy)
class GemmaVanillaOutputLinear(torch.nn.Linear):
def __init__(self, in_features: int, out_features: int, softcap: float):
super().__init__(in_features, out_features, bias=False)
self.softcap = softcap
def forward(
self,
hidden_states: torch.Tensor,
labels: torch.Tensor | None = None,
temperature: Tensor | None = None,
sampling_mask: Tensor | None = None,
) -> PrimeLmOutput:
logits = super().forward(hidden_states)
logits = self.softcap * torch.tanh(logits / self.softcap)
if labels is not None and temperature is None:
return PrimeLmOutput(loss=cross_entropy_sum(logits, labels))
return PrimeLmOutput(logits=logits)
class _GemmaChunkedLogProbEntropyFn(torch.autograd.Function):
@staticmethod
def forward( # type: ignore[override]
ctx,
hidden: torch.Tensor, # [N, H]
weight: torch.Tensor, # [V, H]
labels: torch.Tensor, # [N]
inv_temperature: torch.Tensor, # [N]
chunk_size: int,
softcap: float,
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Returns per-token logprobs and entropy by chunking over flattened sequence tokens.
"""
assert hidden.dim() == 2, f"expected hidden [N,H], got {tuple(hidden.shape)}"
assert weight.dim() == 2, f"expected weight [V,H], got {tuple(weight.shape)}"
assert labels.dim() == 1, f"expected labels [N], got {tuple(labels.shape)}"
assert inv_temperature.dim() == 1, f"expected inv_temperature [N], got {tuple(inv_temperature.shape)}"
assert hidden.shape[0] == labels.shape[0], "hidden/labels N mismatch"
assert hidden.shape[1] == weight.shape[1], "hidden/weight H mismatch"
assert hidden.shape[0] == inv_temperature.shape[0], "hidden/inv_temperature N mismatch"
assert chunk_size > 0
device = hidden.device
n = hidden.shape[0]
vocab = weight.shape[0]
vocab_chunk_size = min(vocab, 8192)
logprobs = torch.empty((n,), device=device, dtype=torch.float32)
entropy = torch.empty((n,), device=device, dtype=torch.float32)
logz = torch.empty((n,), device=device, dtype=torch.float32)
for start in range(0, n, chunk_size):
end = min(start + chunk_size, n)
hidden_chunk = hidden[start:end]
labels_chunk = labels[start:end]
inv_t_chunk = inv_temperature[start:end].unsqueeze(-1)
token_count = end - start
m = torch.full((token_count,), float("-inf"), device=device, dtype=torch.float32)
s = torch.zeros((token_count,), device=device, dtype=torch.float32)
t = torch.zeros((token_count,), device=device, dtype=torch.float32)
target_logits = torch.zeros((token_count,), device=device, dtype=torch.float32)
for vocab_start in range(0, vocab, vocab_chunk_size):
vocab_end = min(vocab_start + vocab_chunk_size, vocab)
weight_chunk = weight[vocab_start:vocab_end]
logits_chunk = hidden_chunk @ weight_chunk.t()
scaled_logits = logits_chunk.to(torch.float32)
scaled_logits = softcap * torch.tanh(scaled_logits / softcap)
scaled_logits = scaled_logits * inv_t_chunk
m, s, t = _online_logsumexp_and_weighted_update(m, s, t, scaled_logits)
mask = (labels_chunk >= vocab_start) & (labels_chunk < vocab_end)
if torch.any(mask):
idx = (labels_chunk[mask] - vocab_start).to(torch.long)
target_logits[mask] = scaled_logits[mask, idx]
logz_chunk = m + torch.log(s)
logz[start:end] = logz_chunk
logprobs[start:end] = target_logits - logz_chunk
entropy[start:end] = logz_chunk - (t / s)
ctx.save_for_backward(hidden, weight, labels, inv_temperature, logz)
ctx.chunk_size = chunk_size
ctx.softcap = softcap
return logprobs, entropy
@staticmethod
def backward(ctx, grad_logprobs: torch.Tensor, grad_entropy: torch.Tensor | None):
assert grad_entropy is None or torch.all(grad_entropy == 0.0), (
"Backward through entropy is not implemented in GemmaFusedOutputLinear"
)
hidden, weight, labels, inv_temperature, logz = ctx.saved_tensors
chunk_size: int = ctx.chunk_size
softcap: float = ctx.softcap
n, _ = hidden.shape
vocab = weight.shape[0]
vocab_chunk_size = min(vocab, 8192)
grad_hidden = torch.zeros_like(hidden)
grad_weight = torch.zeros_like(weight)
for start in range(0, n, chunk_size):
end = min(start + chunk_size, n)
hidden_chunk = hidden[start:end]
labels_chunk = labels[start:end]
grad_chunk = grad_logprobs[start:end].to(torch.float32)
inv_t_chunk = inv_temperature[start:end].unsqueeze(-1)
logz_chunk = logz[start:end]
for vocab_start in range(0, vocab, vocab_chunk_size):
vocab_end = min(vocab_start + vocab_chunk_size, vocab)
weight_chunk = weight[vocab_start:vocab_end]
logits_chunk = hidden_chunk @ weight_chunk.t()
logits_f = logits_chunk.to(torch.float32)
tanh_val = torch.tanh(logits_f / softcap)
scaled_logits = softcap * tanh_val
scaled_logits = scaled_logits * inv_t_chunk
probs = torch.exp(scaled_logits - logz_chunk.unsqueeze(-1))
grad_logits = (-grad_chunk).unsqueeze(-1) * probs
mask = (labels_chunk >= vocab_start) & (labels_chunk < vocab_end)
if torch.any(mask):
idx = (labels_chunk[mask] - vocab_start).to(torch.long)
grad_logits[mask, idx] += grad_chunk[mask]
grad_logits = grad_logits * inv_t_chunk
grad_logits = grad_logits * (1 - tanh_val**2)
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)
return grad_hidden, grad_weight, None, None, None, None
def inject_gemma_lm_head(model: nn.Module, chunk_size: int | None, softcap: float) -> None:
logger = get_logger()
logger.info(f"Injecting Gemma LM head with chunk size {chunk_size}, softcap={softcap}")
old_lm_head = model.lm_head
if chunk_size is not None:
model.lm_head = GemmaFusedOutputLinear(
in_features=old_lm_head.in_features,
out_features=old_lm_head.out_features,
chunk_size=chunk_size,
softcap=softcap,
)
else:
model.lm_head = GemmaVanillaOutputLinear(
in_features=old_lm_head.in_features,
out_features=old_lm_head.out_features,
softcap=softcap,
)
model.lm_head.weight = old_lm_head.weight
del old_lm_head
_patch_model_forward(model)
@@ -226,109 +226,3 @@ def substitute_ulysses_attn(
from prime_rl.trainer.models.gpt_oss.attention import substitute_gpt_oss_ulysses_attention
substitute_gpt_oss_ulysses_attention(process_group)
def substitute_hf_ulysses_attn(process_group: dist.ProcessGroup) -> None:
"""Patch HF's `_flash_attention_forward` to use Ulysses all-to-all + local FA2.
Used for HF (non-custom) model paths, e.g. qwen2/qwen3 dense models. Mirrors
ring_flash_attn's `substitute_hf_flash_attn` but with all-to-all instead of
ring all-gather.
"""
import transformers
import transformers.modeling_flash_attention_utils
from flash_attn import flash_attn_varlen_func
cp_size = dist.get_world_size(group=process_group)
def _ulysses_flash_attention_forward(
query_states: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
attention_mask,
query_length: int,
is_causal: bool,
dropout: float = 0.0,
position_ids=None,
softmax_scale=None,
sliding_window=None,
use_top_left_mask: bool = False,
softcap=None,
deterministic=None,
**kwargs,
):
assert is_causal, "ulysses CP only supports causal attention"
assert softcap is None, "ulysses CP path does not support softcap"
assert query_states.size(0) == 1, "varlen data should be processed with batch=1"
cu_seqlens = ULYSSES_PARAMS["cu_seqlens"]
max_seqlen = ULYSSES_PARAMS["max_seqlen"]
window_size = (-1, -1)
if sliding_window is not None and key_states.shape[1] > sliding_window:
window_size = (sliding_window, sliding_window)
out = ulysses_flash_attn_varlen_func(
flash_attn_varlen_func,
query_states.squeeze(0),
key_states.squeeze(0),
value_states.squeeze(0),
cu_seqlens_q=cu_seqlens,
cu_seqlens_k=cu_seqlens,
max_seqlen_q=max_seqlen,
max_seqlen_k=max_seqlen,
causal=True,
cp_group=process_group,
cp_size=cp_size,
flash_attn_version=2,
window_size=window_size,
softmax_scale=softmax_scale,
dropout_p=dropout,
deterministic=deterministic,
)
return out.unsqueeze(0)
transformers.modeling_flash_attention_utils._flash_attention_forward = _ulysses_flash_attention_forward
# Newer transformers route attention through ALL_ATTENTION_FUNCTIONS["flash_attention_2"].
try:
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
except ImportError:
ALL_ATTENTION_FUNCTIONS = None
if ALL_ATTENTION_FUNCTIONS is not None:
def _ulysses_flash_attention_forward_v2(
module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask=None,
dropout: float = 0.0,
scaling=None,
sliding_window=None,
softcap=None,
**kw,
):
# Match HF v2 entrypoint: query/key/value arrive as [B, H, S, D].
seq_len = query.shape[2]
query = query.transpose(1, 2)
key = key.transpose(1, 2)
value = value.transpose(1, 2)
kw.pop("is_causal", None)
attn_out = _ulysses_flash_attention_forward(
query,
key,
value,
attention_mask,
query_length=seq_len,
is_causal=module.is_causal,
dropout=dropout,
softmax_scale=scaling,
sliding_window=sliding_window,
softcap=softcap,
)
return attn_out, None
ALL_ATTENTION_FUNCTIONS["flash_attention_2"] = _ulysses_flash_attention_forward_v2
-6
View File
@@ -294,12 +294,6 @@ def resolve_ep(config: ModelConfig) -> None:
if config.ep != "auto":
return
# EP requires the custom implementation; skip auto-resolution for HF impl
if config.impl not in ("custom", "auto"):
config.ep = 1
get_logger().info(f"EP auto: impl='{config.impl}' does not support EP, resolving ep=1")
return
world_size = dist.get_world_size()
if not _is_moe_model(config):
+6 -5
View File
@@ -384,15 +384,16 @@ def compute_loss(
ce_weights: list[Float[Tensor, " seq_i"]] | None,
ref_kl_weights: list[Float[Tensor, " seq_i"]] | None,
rl_loss_fn: Loss,
rl_scale: int,
ce_scale: int,
ref_kl_scale: int,
rl_scale: float,
ce_scale: float,
ref_kl_scale: float,
) -> tuple[Float[Tensor, ""], dict[str, Any]]:
"""
Compute loss for packed sequences (batch size = 1, multiple sequences packed along sequence dimension).
The loss is a sum of three components, each running over its own per-token
weight stream and normalized by its own global token count:
weight stream and normalized by its own global denominator (rl: sum of its
weights; ce / ref_kl: token count):
- rl → ``rl_loss_fn`` (built by ``setup_rl_loss_fn``) on
``loss_mask & (rl_weights != 0)``; an absent stream means weight 1.0 on
@@ -415,7 +416,7 @@ def compute_loss(
ce_weights: Per-token ce weights for each sequence, or None (no ce component)
ref_kl_weights: Per-token ref_kl weights for each sequence, or None (no ref_kl component)
rl_loss_fn: RL loss object built by setup_rl_loss_fn()
rl_scale: Global rl-token count normalizing the rl component
rl_scale: Global sum of rl weights normalizing the rl component
ce_scale: Global ce-token count normalizing the ce component
ref_kl_scale: Global ref_kl-token count normalizing the ref_kl component
+17 -8
View File
@@ -42,6 +42,7 @@ from prime_rl.trainer.rl.annotations import AnnotationWriter
from prime_rl.trainer.model import (
forward,
get_full_offload_dtype_policy,
get_expert_load_stats,
get_global_moe_stats,
is_tt_moe_model,
setup_model,
@@ -308,29 +309,32 @@ def train(config: TrainerConfig):
forward_backward_start_time = time.perf_counter()
seq_len = micro_batches[0]["input_ids"].shape[1]
# Normalize each loss component by its own global (dp_cp) token count, so every rank
# divides by the same denominator. With a per-rank denominator, ranks with fewer loss
# Normalize each loss component by its own global (dp_cp) denominator, so every rank
# divides by the same value. With a per-rank denominator, ranks with fewer loss
# tokens implicitly upweight their per-token gradient contribution after FSDP averaging.
# FSDP's per-rank divide is undone after the microbatch loop via
# fsdp_gradient_divide_factor. One batched collective keeps every rank issuing the same
# op regardless of which components its samples carry.
local_rl_scale = 0
# op regardless of which components its samples carry. rl divides by the sum of its
# weights (the token count for 0/1 weights; the group count under prompt-mean
# aggregation); ce and ref_kl divide by their token counts, so a fractional ce weight
# (echo's alpha) scales the loss instead of cancelling out.
local_rl_scale = 0.0
local_ce_scale = 0
local_ref_kl_scale = 0
for micro_batch in micro_batches:
mask = micro_batch["loss_mask"]
rl_w = micro_batch["rl_weights"]
local_rl_scale += int((mask & (rl_w != 0)).sum()) if rl_w is not None else int(mask.sum())
local_rl_scale += float(rl_w[mask].sum(dtype=torch.float64)) if rl_w is not None else int(mask.sum())
if micro_batch["ce_weights"] is not None:
local_ce_scale += int((micro_batch["ce_weights"] != 0).sum())
if micro_batch["ref_kl_weights"] is not None:
local_ref_kl_scale += int((micro_batch["ref_kl_weights"] != 0).sum())
global_scales = torch.tensor(
[local_rl_scale, local_ce_scale, local_ref_kl_scale], dtype=torch.int64, device="cuda"
[local_rl_scale, local_ce_scale, local_ref_kl_scale], dtype=torch.float64, device="cuda"
)
dp_cp_group = parallel_dims.get_mesh("dp_cp").get_group()
dist.all_reduce(global_scales, op=dist.ReduceOp.SUM, group=dp_cp_group)
rl_scale, ce_scale, ref_kl_scale = (max(scale, 1) for scale in global_scales.tolist())
rl_scale, ce_scale, ref_kl_scale = (scale if scale > 0 else 1 for scale in global_scales.tolist())
prepare_gradient_offload(
gradient_manager,
parallel_dims.fsdp_gradient_divide_factor,
@@ -344,6 +348,7 @@ def train(config: TrainerConfig):
cp_group = parallel_dims.world_mesh["cp"].get_group() if cp_enabled else None
cp_size = parallel_dims.cp
step_tokens_per_expert = 0
for micro_step, micro_batch in enumerate(micro_batches):
input_ids = micro_batch["input_ids"].to("cuda")
position_ids = micro_batch["position_ids"].to("cuda")
@@ -559,8 +564,10 @@ def train(config: TrainerConfig):
annotation_writer.export(micro_batch, out)
if is_moe_model:
for name, value in get_global_moe_stats(model, ep_group, dp_cp_group).items():
moe_stats, tokens_per_expert = get_global_moe_stats(model, ep_group, dp_cp_group)
for name, value in moe_stats.items():
tensors[name].append(value.reshape(1))
step_tokens_per_expert += tokens_per_expert
# Add loss tensors to tensor dict for logging purposes
for key, loss_tensor in loss_tensors.items():
@@ -634,6 +641,8 @@ def train(config: TrainerConfig):
# Synchronize the tensor metrics across all steps and ranks
tensor_stats = tensors.compute_stats()
if is_moe_model:
tensor_stats.update(get_expert_load_stats(step_tokens_per_expert, dp_cp_group))
# Compute step metrics
num_local_tokens = seq_len * batch_size
+7 -2
View File
@@ -27,6 +27,7 @@ from prime_rl.trainer.scheduler import setup_scheduler
from prime_rl.trainer.model import (
forward,
get_full_offload_dtype_policy,
get_expert_load_stats,
get_global_moe_stats,
get_load_balance_stats,
is_tt_moe_model,
@@ -450,6 +451,7 @@ def train(config: SFTConfig):
overlap_optimizer=not run_validation_this_step,
)
step_tokens_per_expert = 0
for micro_step, micro_batch in enumerate(micro_batches):
if config.log.log_data:
print_sample(
@@ -476,12 +478,15 @@ def train(config: SFTConfig):
finish_backward(gradient_manager)
if is_moe_model:
for name, value in get_global_moe_stats(model, ep_group, dp_cp_group).items():
micro_moe_stats, tokens_per_expert = get_global_moe_stats(model, ep_group, dp_cp_group)
for name, value in micro_moe_stats.items():
moe_stats[f"{name}/mean"] += value / grad_accum_steps
if name == "max_vio":
moe_stats["max_vio/max"] = torch.maximum(moe_stats["max_vio/max"], value)
step_tokens_per_expert += tokens_per_expert
forward_backward_time = time.perf_counter() - forward_backward_start_time
expert_load_stats = get_expert_load_stats(step_tokens_per_expert, dp_cp_group) if is_moe_model else {}
if gradient_manager is None:
global_step_token_count = step_local_token_count.clone()
@@ -646,7 +651,7 @@ def train(config: SFTConfig):
disk_metrics["step"] = progress.step
asyncio.run(monitors.log(disk_metrics, step=progress.step))
moe_log_metrics = {name: value.item() for name, value in moe_stats.items()}
moe_log_metrics = {name: value.item() for name, value in moe_stats.items()} | expert_load_stats
if moe_log_metrics:
asyncio.run(monitors.log({**moe_log_metrics, "step": progress.step}, step=progress.step))
+2 -1
View File
@@ -2,7 +2,8 @@ from pathlib import Path
import torch
from prime_rl.configs.trainer import LoRAConfig, WeightBroadcastConfig
from prime_rl.configs.shared import WeightBroadcastConfig
from prime_rl.configs.trainer import LoRAConfig
from prime_rl.orchestrator.clients import AdminPlane
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.transports.weights.base import WeightReceiver, WeightSender, prune_broadcasts_beyond
+1 -1
View File
@@ -8,7 +8,7 @@ from typing import final
import torch.nn as nn
from prime_rl.configs.trainer import WeightBroadcastConfig
from prime_rl.configs.shared import WeightBroadcastConfig
from prime_rl.orchestrator.clients import AdminPlane
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
@@ -4,7 +4,8 @@ import torch.distributed as dist
import torch.nn as nn
from torch.distributed.tensor import DTensor
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig, LoRAConfig
from prime_rl.configs.shared import FileSystemWeightBroadcastConfig
from prime_rl.configs.trainer import LoRAConfig
from prime_rl.orchestrator.clients import load_lora_adapter
from prime_rl.trainer.lora import get_lora_state, save_lora_config
from prime_rl.transports.weights.base import FINISHED_MARKER, WeightReceiver, WeightSender
+13 -2
View File
@@ -10,8 +10,7 @@ from torch.distributed.tensor import DTensor
from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
from vllm.distributed.utils import StatelessProcessGroup
from prime_rl.configs.trainer import NCCLWeightBroadcastConfig
from prime_rl.trainer.conversion_utils import get_max_layer_num
from prime_rl.configs.shared import NCCLWeightBroadcastConfig
from prime_rl.trainer.models import PreTrainedModelPrimeRL
from prime_rl.trainer.utils import get_world
from prime_rl.transports.weights.base import WeightReceiver, WeightSender
@@ -21,6 +20,18 @@ from prime_rl.utils.vlm import get_layer_prefix
from prime_rl.utils.weights import resolve_wire_dtype
def get_max_layer_num(state_dict: dict[str, Tensor], layer_prefix: str = "model.layers.") -> int:
"""Get the maximum number of layers in the model."""
max_num = -1
for key in state_dict:
if not key.startswith(layer_prefix):
continue
layer_num_str = key[len(layer_prefix) :].split(".")[0]
if layer_num_str.isdigit():
max_num = max(max_num, int(layer_num_str))
return max_num + 1
def broadcast_integer(integer: int, communicator: PyNcclCommunicator) -> None:
"""Broadcast an integer to a process group using NCCL communicator."""
integer_tensor = torch.tensor([integer], dtype=torch.long).cuda()
+1 -1
View File
@@ -19,7 +19,7 @@ from modelexpress.client import MxClient
from torch.distributed.tensor import DTensor
from torch.distributed.tensor._utils import compute_local_shape_and_global_offset
from prime_rl.configs.trainer import NIXLWeightBroadcastConfig
from prime_rl.configs.shared import NIXLWeightBroadcastConfig
from prime_rl.orchestrator.clients import init_nixl_broadcast
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.parallel_dims import ParallelDims
+2 -4
View File
@@ -9,7 +9,7 @@ from typing import TYPE_CHECKING
import torch
import torch.distributed as dist
import torch.nn as nn
from ring_flash_attn import substitute_hf_flash_attn, update_ring_flash_attn_params
from ring_flash_attn import update_ring_flash_attn_params
from prime_rl.trainer.distributed.collectives import all_gather
from prime_rl.utils.logger import get_logger
@@ -46,12 +46,10 @@ def setup_context_parallel(model: nn.Module, config: ModelConfig, parallel_dims:
# prime_rl.utils — a top-level import would deadlock at startup.
from prime_rl.trainer.models.layers.attn import substitute_ring_attn
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.attn)
elif config.cp_style == "ulysses":
from prime_rl.trainer.models.layers.ulysses_attn import substitute_hf_ulysses_attn, substitute_ulysses_attn
from prime_rl.trainer.models.layers.ulysses_attn import substitute_ulysses_attn
substitute_hf_ulysses_attn(cp_group)
substitute_ulysses_attn(cp_group, attn_impl=config.attn)
else:
raise ValueError(f"Unknown cp_style: {config.cp_style}")
+100
View File
@@ -2,6 +2,9 @@ import contextlib
import os
import signal
import subprocess
import sys
import uuid
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
@@ -44,6 +47,41 @@ def get_physical_gpu_ids() -> list[int]:
return [int(token.strip()) for token in raw_visible.split(",") if token.strip()]
def partition_gpus(num_infer: int, num_train: int) -> tuple[list[int], list[int]]:
"""Split the launcher's physical GPUs into inference GPUs followed by trainer GPUs."""
physical_gpu_ids = get_physical_gpu_ids()
if num_infer + num_train > len(physical_gpu_ids):
raise ValueError(
f"Requested {num_infer + num_train} GPUs via deployment settings, but only "
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
)
return physical_gpu_ids[:num_infer], physical_gpu_ids[num_infer : num_infer + num_train]
def torchrun_cmd(
module: str, config_path: Path, nproc_per_node: int, log_dir: Path, ranks_filter: list[int]
) -> list[str]:
"""Single-node torchrun command for a trainer module."""
from prime_rl.utils.utils import get_free_port
return [
"torchrun",
"--role=trainer",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
# Pipe all logs to file, and only master rank logs to stdout
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
f"--local-ranks-filter={','.join(map(str, ranks_filter))}",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={nproc_per_node}",
"-m",
module,
"@",
config_path.as_posix(),
]
def set_proc_title(name: str) -> None:
"""Set the process title for visibility in tools like ``ps`` and ``htop``.
@@ -103,3 +141,65 @@ def monitor_process(process: Popen, stop_event: Event, error_queue: list, proces
err_msg += f"\n{process.stderr.read().decode('utf-8')}"
error_queue.append(RuntimeError(err_msg))
stop_event.set()
class ProcessGroup:
"""Launcher subprocesses, each logging to its own file and watched by a monitor thread.
As a context manager, SIGTERM, Ctrl-C, errors and normal exit all terminate every
started process."""
def __init__(self):
self.processes: list[Popen] = []
self.monitor_threads: list[Thread] = []
self.error_queue: list[Exception] = []
self.stop_events: dict[str, Event] = {}
def __enter__(self) -> "ProcessGroup":
signal.signal(signal.SIGTERM, self._sigterm_handler)
return self
def __exit__(self, exc_type, exc, tb) -> None:
if exc_type is KeyboardInterrupt:
get_logger().warning("Received interrupt signal, terminating all processes...")
elif isinstance(exc, Exception):
get_logger().error(f"Error occurred: {exc}")
self.cleanup()
if exc_type is KeyboardInterrupt:
sys.exit(1)
def _sigterm_handler(self, signum, frame):
get_logger().warning("Received SIGTERM, terminating all processes...")
# Clean up here too: a SIGTERM during __exit__'s cleanup would otherwise leave orphans.
self.cleanup()
sys.exit(1)
def cleanup(self) -> None:
cleanup_threads(self.monitor_threads)
cleanup_processes(self.processes)
def start(self, name: str, cmd: list[str], env: dict[str, str], log_path: Path) -> None:
get_logger().debug(f"{name[:1].upper() + name[1:]} command: {' '.join(cmd)}")
log_path.parent.mkdir(parents=True, exist_ok=True)
# If we don't log stdout, the inference server hangs
with open(log_path, "w") as log_file:
process = Popen(cmd, env=env, stdout=log_file, stderr=log_file)
self.processes.append(process)
stop_event = Event()
self.stop_events[name] = stop_event
monitor_thread = Thread(target=monitor_process, args=(process, stop_event, self.error_queue, name), daemon=True)
monitor_thread.start()
self.monitor_threads.append(monitor_thread)
def wait(self, *names: str) -> None:
"""Block until the named processes exit; exit with code 1 as soon as any started process fails."""
events = [self.stop_events[name] for name in names]
while True:
pending = [event for event in events if not event.is_set()]
if self.error_queue:
get_logger().error(f"Error: {self.error_queue[0]}")
get_logger().error("Terminating all processes...")
sys.exit(1)
if not pending:
return
pending[0].wait(timeout=1)
-13
View File
@@ -25,12 +25,9 @@ class VLMModelInfo:
# Central registry: model_type -> architecture info.
VLM_REGISTRY: dict[str, VLMModelInfo] = {
"qwen3_vl": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
"qwen3_5": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
"qwen3_5_moe": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
"qwen4_exp": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
"qwen3_vl_moe": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
"gemma4": VLMModelInfo(vision_encoder_attr="model.vision_tower", language_model_attr="model.language_model"),
}
# Text-only default
@@ -88,16 +85,6 @@ def is_vlm_architecture(model_config: PretrainedConfig) -> bool:
return _get_model_info_from_config(model_config) is not None
def get_final_logit_softcapping(model_config: PretrainedConfig) -> float | None:
"""Read ``final_logit_softcapping`` from the text config.
For composite VLM configs (e.g. Gemma) the value lives under ``text_config``;
``get_text_config()`` returns that for VLMs and the config itself for text-only
models, so a plain top-level ``getattr`` would miss it and silently drop softcapping.
"""
return getattr(model_config.get_text_config(), "final_logit_softcapping", None)
def get_layer_prefix(model_config: PretrainedConfig, override: str | None = None) -> str:
"""Return the weight key prefix for language model layers.
+1 -3
View File
@@ -38,8 +38,6 @@ def rl_process(
"@",
"configs/ci/integration/reverse-text-moe/start.toml",
"--clean",
"--trainer.model.impl",
"custom",
"--trainer.model.conversion-dir",
(output_dir / RUN_NAME / "model-conversion").as_posix(),
"--monitors.wandb.project",
@@ -60,4 +58,4 @@ def test_no_error(rl_process: ProcessResult, run_dir: Path):
def test_moe_runs(rl_process: ProcessResult, test_no_error):
"""MoE RL with custom model impl completes without error."""
"""MoE RL completes without error."""
+36 -2
View File
@@ -151,9 +151,11 @@ def _scalar(episode: vf.Episode) -> float:
raise AssertionError("episode has no trainable token")
def _grpo(group: list[vf.Episode], length_penalty=None) -> list[float]:
def _grpo(group: list[vf.Episode], length_penalty=None, length_weighted_baseline=False) -> list[float]:
"""Drive ``GRPOAlgorithm.score_group`` and read back each per-rollout scalar."""
algo = GRPOAlgorithm(GRPOAlgoConfig(length_penalty=length_penalty), clients=None)
algo = GRPOAlgorithm(
GRPOAlgoConfig(length_penalty=length_penalty, length_weighted_baseline=length_weighted_baseline), clients=None
)
asyncio.run(algo.score_group(group))
return [_scalar(episode) for episode in group]
@@ -181,6 +183,27 @@ def test_grpo_singleton_group_is_zero():
assert _grpo([_build_episode(0.7, sampled_lengths=[2])]) == pytest.approx([0.0], abs=1e-6)
def test_grpo_length_weighted_baseline():
# L = [10 + 20 (two turns, observation excluded), 10]: b = (30 * 1 + 10 * 0) / 40 = 0.75
group = [
_build_episode(1.0, sampled_lengths=[10, 20], obs_lengths=[5]),
_build_episode(0.0, sampled_lengths=[10]),
]
advs = _grpo(group, length_weighted_baseline=True)
assert advs == pytest.approx([0.25, -0.75])
# per-token advantage is zero-mean across the group's trainable tokens
assert 30 * advs[0] + 10 * advs[1] == pytest.approx(0.0, abs=1e-6)
# with a length penalty, the weighted baseline applies to the shaped rewards:
# penalty = mean(r) * 0.5 * L / max(L) = [0.25, 1/12], shaped = [0.75, -1/12], b = (30 * 0.75 - 10 / 12) / 40
cfg = LinearLengthPenaltyConfig(num_output_tokens_weight=0.5, num_input_tokens_weight=0.0, num_turns_weight=0.0)
group = [
_build_episode(1.0, sampled_lengths=[10, 20], obs_lengths=[5]),
_build_episode(0.0, sampled_lengths=[10]),
]
advs = _grpo(group, length_penalty=cfg, length_weighted_baseline=True)
assert advs == pytest.approx([0.75 - 65 / 120, -1 / 12 - 65 / 120])
def test_max_rl_mean_normalized():
# mean 0.25: the success gets (1 - 0.25)/0.25 = 3, failures (0 - 0.25)/0.25 = -1
assert _max_rl(_make_group(rewards=[1.0, 0.0, 0.0, 0.0])) == pytest.approx([3.0, -1.0, -1.0, -1.0])
@@ -190,6 +213,17 @@ def test_max_rl_mean_normalized():
assert _max_rl(_make_group(rewards=[1.0, 1.0])) == pytest.approx([0.0, 0.0])
def test_grpo_prompt_loss_aggregation_weights_sum_to_one_per_group():
"""Each group's rl weights total 1, spread as 1/T_q over its trainable tokens, whatever its length."""
algo = GRPOAlgorithm(GRPOAlgoConfig(loss_aggregation="prompt"), clients=None)
for lengths in ([10, 30], [100, 300]):
group = _make_group(rewards=[1.0, 0.0], completion_lengths=lengths)
asyncio.run(algo.score_group(group))
weights = [w for episode in group for sample in trace_to_samples(episode.traces[0]) for w in sample.rl_weights]
assert set(weights) == {0.0, 1.0 / sum(lengths)}
assert sum(weights) == pytest.approx(1.0)
# --------------------------------------------------------------------------
# GRPO linear length penalty: pass_rate-scaled penalty before the baseline.
# --------------------------------------------------------------------------
+7 -1
View File
@@ -3,7 +3,13 @@ from types import SimpleNamespace
import numpy as np
import pytest
from prime_rl.trainer.batch import _is_multimodal_sample, build_bin_cost, pad_micro_batch, prepare_batch, prepare_sample
from prime_rl.orchestrator.batch import (
_is_multimodal_sample,
build_bin_cost,
pad_micro_batch,
prepare_batch,
prepare_sample,
)
from prime_rl.transports.batch.types import MicroBatch, MMImageRef, MMRefs, RoutedExperts, TrainingSample
+2 -3
View File
@@ -624,7 +624,6 @@ def test_trainer_rejects_vlm_cp_with_ring():
config = {
"model": {
"cp": 2,
"impl": "custom",
"optimization_dtype": "bfloat16",
"reduce_dtype": "bfloat16",
"vlm": {
@@ -880,12 +879,12 @@ def test_shared_and_subconfig_disjoint_fields_coexist():
config = RLConfig.model_validate(
{
"model": {"name": "Qwen/Qwen3-0.6B"},
"trainer": {"model": {"impl": "custom"}},
"trainer": {"model": {"attn": "flash_attention_3"}},
"orchestrator": {"renderer": {"name": "default"}},
}
)
assert config.trainer.model.name == "Qwen/Qwen3-0.6B"
assert config.trainer.model.impl == "custom"
assert config.trainer.model.attn == "flash_attention_3"
def test_run_dir_propagates_through_cli(tmp_path):
+1 -3
View File
@@ -2,7 +2,7 @@ import pytest
import torch
from prime_rl.configs.trainer import ModelConfig
from prime_rl.trainer.model import can_reinit_empty_buffers, resolve_auto_attn
from prime_rl.trainer.model import resolve_auto_attn
from prime_rl.trainer.models import AutoModelForCausalLMPrimeRL
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.qwen3_5 import (
@@ -180,8 +180,6 @@ def test_vlm_meta_device_and_buffer_reinit():
config = get_vlm_config()
model = get_model(config, device="meta")
assert can_reinit_empty_buffers(model)
model.to_empty(device="cuda")
model.init_buffers_post_meta()
+2 -1
View File
@@ -8,13 +8,14 @@ from torch import nn
from prime_rl.configs.trainer import ModelConfig
from prime_rl.trainer.model import load_dcp_from_hf
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, DeepseekV4ForCausalLM, eager_reference
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, DeepseekV4ForCausalLM
from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
from prime_rl.trainer.models.layers import norms
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.utils.utils import default_dtype
from tests.unit.train.models import deepseek_v4_eager_reference as eager_reference
# Every layer is built through `DeepseekV4Attention.__init__`, which refuses to construct without
# the kernel it would dispatch to, so the whole file needs tilelang even though nothing here calls it.
@@ -8,20 +8,21 @@ import torch
from torch import nn
from torch.utils._python_dispatch import TorchDispatchMode
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, eager_reference
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config
from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext
from prime_rl.trainer.models.deepseek_v4.eager_reference import (
apply_rotary_pos_emb_interleaved,
dense_mask_from_indices,
eager_attention_with_sinks,
)
from prime_rl.trainer.models.deepseek_v4.hyperconnections import DeepseekV4HyperConnection, DeepseekV4UnweightedRMSNorm
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT, dsv4_mhc
from prime_rl.trainer.models.kernels.deepseek_v4.dsv4_rope import dsv4_q_norm_rope, dsv4_rope
from prime_rl.utils.cp import CPContext
from prime_rl.utils.utils import default_dtype
from tests.unit.train.models import deepseek_v4_eager_reference as eager_reference
from tests.unit.train.models.deepseek_v4_eager_reference import (
apply_rotary_pos_emb_interleaved,
dense_mask_from_indices,
eager_attention_with_sinks,
)
try:
import tilelang
+18 -1
View File
@@ -4,7 +4,7 @@ import torch.nn.functional as F
from prime_rl.configs.trainer import ModelConfig
from prime_rl.trainer.distributed.token_dispatcher import LocalTokenDispatcher
from prime_rl.trainer.model import is_tt_moe_model
from prime_rl.trainer.model import compute_expert_load_stats, is_tt_moe_model
from prime_rl.trainer.models.deepseek_v4.moe import DeepseekV4Experts
from prime_rl.trainer.models.fusions import fuse_gate_up_projections
from prime_rl.trainer.models.layers.activations import ActivationDispatch
@@ -235,3 +235,20 @@ def test_expert_type_and_activation_are_independent(expert_type, activation):
assert moe.experts.activation is ActivationDispatch[activation]
assert (moe.shared_expert.gate_proj is not None) == has_gate
assert moe.shared_expert.activation is ActivationDispatch[activation]
def test_expert_load_stats():
# Layer 0 is balanced; layer 1 sends 8 of 16 tokens to one expert and leaves one expert cold (< 0.1x mean).
tokens_per_expert = torch.tensor([[4.0, 4.0, 4.0, 4.0], [8.0, 4.0, 4.0, 0.0]])
stats = compute_expert_load_stats(tokens_per_expert)
expected = {
"expert_load/cv/mean": 2**0.5 / 4,
"expert_load/cv/max": 2**0.5 / 2,
"expert_load/max_mean/mean": 1.5,
"expert_load/max_mean/max": 2.0,
"expert_load/cold_frac/mean": 0.125,
"expert_load/cold_frac/max": 0.25,
}
assert stats.keys() == expected.keys()
for name, value in expected.items():
assert stats[name].item() == pytest.approx(value)
+31 -85
View File
@@ -1,11 +1,10 @@
import pytest
import torch
from transformers import AutoModelForCausalLM
from transformers.models.llama.configuration_llama import LlamaConfig
from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
from prime_rl.trainer.models import cast_float_and_contiguous
from prime_rl.trainer.models.layers.lm_head import FusedOutputLinear, VanillaOutputLinear, inject_prime_lm_head
from prime_rl.trainer.models.llama import LlamaForCausalLM as PrimeRLLlamaForCausalLM
from prime_rl.trainer.models.qwen3 import Qwen3ForCausalLM
from prime_rl.trainer.rl.loss import compute_entropy, selective_log_softmax, shift_tensor_left, shift_tensor_right
from prime_rl.utils.utils import default_dtype
@@ -167,25 +166,25 @@ def test_full_model_fused_vs_vanilla():
"""Full model integration test comparing fused vs vanilla LM head across multiple training steps."""
torch.manual_seed(123)
# Create tiny Llama model for fast testing
config = LlamaConfig(
# Create tiny Qwen3 model for fast testing
config = Qwen3Config(
hidden_size=128,
intermediate_size=256,
max_position_embeddings=512,
num_attention_heads=4,
num_key_value_heads=2,
head_dim=32,
num_hidden_layers=2,
vocab_size=1000,
rms_norm_eps=1e-5,
rope_theta=10000.0,
attention_bias=False,
mlp_bias=False,
)
with torch.device("cuda"), default_dtype(torch.bfloat16):
# Create two identical models
model_vanilla = PrimeRLLlamaForCausalLM._from_config(config)
model_fused = PrimeRLLlamaForCausalLM._from_config(config)
model_vanilla = Qwen3ForCausalLM._from_config(config)
model_fused = Qwen3ForCausalLM._from_config(config)
# Share weights between models
model_fused.load_state_dict(model_vanilla.state_dict())
@@ -300,26 +299,25 @@ def test_fused_lm_head_correct_shift():
@pytest.mark.gpu
def test_inject_prime_lm_head_vanilla():
"""Test that inject_prime_lm_head correctly wraps HF model with VanillaOutputLinear."""
"""Test that inject_prime_lm_head correctly wraps the model with VanillaOutputLinear."""
torch.manual_seed(123)
# Create tiny Llama model using HuggingFace AutoModelForCausalLM
config = LlamaConfig(
config = Qwen3Config(
hidden_size=128,
intermediate_size=256,
max_position_embeddings=512,
num_attention_heads=4,
num_key_value_heads=2,
head_dim=32,
num_hidden_layers=2,
vocab_size=1000,
rms_norm_eps=1e-5,
rope_theta=10000.0,
attention_bias=False,
mlp_bias=False,
)
with torch.device("cuda"), default_dtype(torch.float32):
model = AutoModelForCausalLM.from_config(config)
with torch.device("cuda"), default_dtype(torch.bfloat16):
model = Qwen3ForCausalLM._from_config(config)
# Wrap with VanillaOutputLinear (chunk_size=None)
inject_prime_lm_head(model, chunk_size=None)
@@ -336,7 +334,13 @@ def test_inject_prime_lm_head_vanilla():
temperature = torch.full((batch_size, seq_len), 1.5, dtype=torch.float32)
with torch.autocast("cuda", dtype=torch.bfloat16):
out = model(input_ids=input_ids, position_ids=position_ids, labels=labels, temperature=temperature)
out = model(
input_ids=input_ids,
position_ids=position_ids,
labels=labels,
temperature=temperature,
seq_lens=torch.tensor([seq_len], device="cuda"),
)
# VanillaOutputLinear returns logits
assert isinstance(out, dict), "Output should be PrimeLmOutput (dict)"
@@ -347,26 +351,25 @@ def test_inject_prime_lm_head_vanilla():
@pytest.mark.gpu
def test_inject_prime_lm_head_fused():
"""Test that inject_prime_lm_head correctly wraps HF model with FusedOutputLinear."""
"""Test that inject_prime_lm_head correctly wraps the model with FusedOutputLinear."""
torch.manual_seed(123)
# Create tiny Llama model using HuggingFace AutoModelForCausalLM
config = LlamaConfig(
config = Qwen3Config(
hidden_size=128,
intermediate_size=256,
max_position_embeddings=512,
num_attention_heads=4,
num_key_value_heads=2,
head_dim=32,
num_hidden_layers=2,
vocab_size=1000,
rms_norm_eps=1e-5,
rope_theta=10000.0,
attention_bias=False,
mlp_bias=False,
)
with torch.device("cuda"), default_dtype(torch.float32):
model = AutoModelForCausalLM.from_config(config)
with torch.device("cuda"), default_dtype(torch.bfloat16):
model = Qwen3ForCausalLM._from_config(config)
# Wrap with FusedOutputLinear
inject_prime_lm_head(model, chunk_size=512)
@@ -383,7 +386,13 @@ def test_inject_prime_lm_head_fused():
temperature = torch.full((batch_size, seq_len), 1.5, dtype=torch.float32)
with torch.autocast("cuda", dtype=torch.bfloat16):
out = model(input_ids=input_ids, position_ids=position_ids, labels=labels, temperature=temperature)
out = model(
input_ids=input_ids,
position_ids=position_ids,
labels=labels,
temperature=temperature,
seq_lens=torch.tensor([seq_len], device="cuda"),
)
# FusedOutputLinear returns logprobs and entropy
assert isinstance(out, dict), "Output should be PrimeLmOutput (dict)"
@@ -392,66 +401,3 @@ def test_inject_prime_lm_head_fused():
assert out.get("logits") is None, "Fused path should not return logits"
assert out["logprobs"].shape == (batch_size, seq_len), "Logprobs shape mismatch"
assert out["entropy"].shape == (batch_size, seq_len), "Entropy shape mismatch"
@pytest.mark.gpu
def test_hf_model_fused_vs_vanilla_matches():
"""Test that fused and vanilla paths produce equivalent results for HF models."""
torch.manual_seed(42)
# Create tiny Llama model using HuggingFace AutoModelForCausalLM
config = LlamaConfig(
hidden_size=128,
intermediate_size=256,
max_position_embeddings=512,
num_attention_heads=4,
num_key_value_heads=2,
num_hidden_layers=2,
vocab_size=1000,
rms_norm_eps=1e-5,
rope_theta=10000.0,
attention_bias=False,
mlp_bias=False,
)
with torch.device("cuda"), default_dtype(torch.float32):
model_vanilla = AutoModelForCausalLM.from_config(config)
model_fused = AutoModelForCausalLM.from_config(config)
# Share weights
model_fused.load_state_dict(model_vanilla.state_dict())
# Wrap models
inject_prime_lm_head(model_vanilla, chunk_size=None)
inject_prime_lm_head(model_fused, chunk_size=32)
# Test data
batch_size, seq_len = 2, 64
temp_value = 1.5
with torch.device("cuda"):
input_ids = torch.randint(0, config.vocab_size, (batch_size, seq_len))
position_ids = torch.arange(seq_len).unsqueeze(0).expand(batch_size, -1)
labels = torch.randint(0, config.vocab_size, (batch_size, seq_len))
temperature = torch.full((batch_size, seq_len), temp_value, dtype=torch.float32)
# Run vanilla model
with torch.autocast("cuda", dtype=torch.bfloat16):
out_vanilla = model_vanilla(
input_ids=input_ids, position_ids=position_ids, labels=labels, temperature=temperature
)
# Compute logprobs and entropy from vanilla logits
logits = out_vanilla["logits"].float() / temp_value
vanilla_logprobs = selective_log_softmax(logits, labels)
vanilla_entropy = compute_entropy(logits)
# Run fused model
with torch.autocast("cuda", dtype=torch.bfloat16):
out_fused = model_fused(input_ids=input_ids, position_ids=position_ids, labels=labels, temperature=temperature)
fused_logprobs = out_fused["logprobs"].float()
fused_entropy = out_fused["entropy"].float()
# Compare results
torch.testing.assert_close(fused_logprobs, vanilla_logprobs, rtol=1e-3, atol=1e-4)
torch.testing.assert_close(fused_entropy, vanilla_entropy, rtol=1e-3, atol=1e-4)
+6 -13
View File
@@ -3,26 +3,20 @@ import torch
import torch.nn.functional as F
from prime_rl.trainer.models.layers.lm_head import IGNORE_INDEX, FusedOutputLinear, VanillaOutputLinear
from prime_rl.trainer.models.layers.lm_head_gemma import GemmaFusedOutputLinear, GemmaVanillaOutputLinear
B, S, H, V = 2, 7, 8, 37
SOFTCAP = 5.0
UPSTREAM = 0.25 # stands in for the 1 / grad_accum_steps scaling in the SFT loop
HEADS = {
"fused": (lambda chunk_size: FusedOutputLinear(H, V, chunk_size=chunk_size), None),
"vanilla": (lambda chunk_size: VanillaOutputLinear(H, V), None),
"gemma_fused": (lambda chunk_size: GemmaFusedOutputLinear(H, V, chunk_size=chunk_size, softcap=SOFTCAP), SOFTCAP),
"gemma_vanilla": (lambda chunk_size: GemmaVanillaOutputLinear(H, V, softcap=SOFTCAP), SOFTCAP),
"fused": lambda chunk_size: FusedOutputLinear(H, V, chunk_size=chunk_size),
"vanilla": lambda chunk_size: VanillaOutputLinear(H, V),
}
def _reference_and_grads(hidden, weight, target_ids, loss_mask, softcap):
def _reference_and_grads(hidden, weight, target_ids, loss_mask):
hidden = hidden.detach().clone().requires_grad_(True)
weight = weight.detach().clone().requires_grad_(True)
logits = hidden @ weight.t()
if softcap is not None:
logits = softcap * torch.tanh(logits / softcap)
loss = F.cross_entropy(logits.view(-1, V), target_ids.view(-1), reduction="none")[loss_mask.view(-1)].sum()
(loss * UPSTREAM).backward()
return loss.detach(), hidden.grad, weight.grad
@@ -40,11 +34,10 @@ def _inputs():
@pytest.mark.parametrize("head", list(HEADS))
@pytest.mark.parametrize("chunk_size", [1, 5, 64])
def test_lm_head_labels_without_temperature_returns_summed_cross_entropy(head, chunk_size):
make_head, softcap = HEADS[head]
hidden, weight, target_ids, loss_mask = _inputs()
reference, ref_hidden_grad, ref_weight_grad = _reference_and_grads(hidden, weight, target_ids, loss_mask, softcap)
reference, ref_hidden_grad, ref_weight_grad = _reference_and_grads(hidden, weight, target_ids, loss_mask)
lm_head = make_head(chunk_size)
lm_head = HEADS[head](chunk_size)
lm_head.weight = torch.nn.Parameter(weight.clone())
hidden = hidden.clone().requires_grad_(True)
out = lm_head(hidden, target_ids.masked_fill(~loss_mask, IGNORE_INDEX))
@@ -59,7 +52,7 @@ def test_lm_head_labels_without_temperature_returns_summed_cross_entropy(head, c
@pytest.mark.parametrize("chunk_size", [1, 5, 64])
def test_fused_lm_head_with_temperature_keeps_logprob_path(chunk_size):
hidden, weight, target_ids, loss_mask = _inputs()
reference, ref_hidden_grad, ref_weight_grad = _reference_and_grads(hidden, weight, target_ids, loss_mask, None)
reference, ref_hidden_grad, ref_weight_grad = _reference_and_grads(hidden, weight, target_ids, loss_mask)
lm_head = FusedOutputLinear(H, V, chunk_size=chunk_size)
lm_head.weight = torch.nn.Parameter(weight.clone())
+2 -2
View File
@@ -125,7 +125,7 @@ def test_model_with_sequence_packing(model, correct_position_ids):
def test_moe_custom_impl():
config = ModelConfig(name="PrimeIntellect/GLM-0.5B", attn="flash_attention_2", impl="custom")
config = ModelConfig(name="PrimeIntellect/GLM-0.5B", attn="flash_attention_2")
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
@@ -141,7 +141,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="flash_attention_2")
config = ModelConfig(name=model_name, 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)