Compare commits

...
Author SHA1 Message Date
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
33 changed files with 413 additions and 569 deletions
+2
View File
@@ -325,6 +325,8 @@ 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.
### 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
View File
@@ -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:**
@@ -208,6 +208,9 @@ 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."""
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
@@ -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
@@ -456,7 +457,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 +508,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
@@ -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
@@ -659,48 +660,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()
@@ -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
+10 -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,7 @@ 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
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 +29,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 +42,12 @@ 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)
+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 -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
-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
+42 -5
View File
@@ -252,7 +252,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 +266,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 +293,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 +301,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 +319,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:
+7 -1
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,
@@ -344,6 +345,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 +561,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 +638,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
+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)
+25 -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])
+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 -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)