Compare commits
49
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e03be50a86 | ||
|
|
625b93c5e4 | ||
|
|
961c11f4cf | ||
|
|
b7b1f874b5 | ||
|
|
d334ea5294 | ||
|
|
57d2b84330 | ||
|
|
4f5e06fcb6 | ||
|
|
390dfdc556 | ||
|
|
2fdffa7d3d | ||
|
|
7cbc77a27f | ||
|
|
21c072a8f9 | ||
|
|
cb43db2ad1 | ||
|
|
2c6ac2bd47 | ||
|
|
4d64d38a60 | ||
|
|
d3fe2a8044 | ||
|
|
df5f991bf4 | ||
|
|
546fd69709 | ||
|
|
321c8aa825 | ||
|
|
84b413fd73 | ||
|
|
9e0d242cd0 | ||
|
|
b127f0375b | ||
|
|
4bbf967a57 | ||
|
|
cdb1480c66 | ||
|
|
f34efdbf49 | ||
|
|
9b47b777aa | ||
|
|
1877714656 | ||
|
|
77766bb59c | ||
|
|
1caebf8a1b | ||
|
|
db04385acf | ||
|
|
2bc136cf85 | ||
|
|
6bfbd64aef | ||
|
|
b453f40d8c | ||
|
|
1b028ca1d1 | ||
|
|
e96bbae2dd | ||
|
|
df2acf4874 | ||
|
|
5ff9abd8b5 | ||
|
|
5448f5a722 | ||
|
|
8a977ecc9c | ||
|
|
1ab29c0587 | ||
|
|
5e6b641574 | ||
|
|
16f5c7222b | ||
|
|
5c0a6dbdba | ||
|
|
dbe95b799a | ||
|
|
07e6bec87a | ||
|
|
9fede0ac78 | ||
|
|
d16981b533 | ||
|
|
b2b4f3f711 | ||
|
|
50aeb3c7d6 | ||
|
|
4beb553525 |
@@ -1,19 +1,3 @@
|
||||
# BugBot Instructions
|
||||
|
||||
## Changelog Enforcement
|
||||
|
||||
Any PR that introduces **breaking** configuration changes must update `CHANGELOG.md`. Breaking changes are those that require users to update existing configs:
|
||||
|
||||
- **Renamed** config fields (old name no longer accepted)
|
||||
- **Removed** config fields (field deleted or moved to a different path)
|
||||
- **Moved** config fields (field relocated in the config hierarchy)
|
||||
|
||||
Additive changes (new fields with defaults, new optional features) and default value changes do **not** require a changelog entry.
|
||||
|
||||
Config files live in:
|
||||
|
||||
- `src/prime_rl/configs/`
|
||||
|
||||
If breaking changes are detected without a corresponding `CHANGELOG.md` update, request that the author add an entry.
|
||||
|
||||
Any PR that introduces a new custom model must also provide a table showing mean KL mismatch across 20 steps on math environment on this new model with `batch_size=64`. All the entries in the table must lower than 0.015. If this is not present, request the author to add such a table.
|
||||
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
run: uv sync --extra flash-attn --all-packages --locked
|
||||
- name: Run tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
@@ -90,14 +90,24 @@ jobs:
|
||||
assert find_package_resource("templates") is None, "templates should not be in slim wheel"
|
||||
print("slim install OK — configs import with no heavy deps loaded")
|
||||
PY
|
||||
- name: Verify a real config (with [slurm]) parses on slim install
|
||||
- name: Verify real configs (with [slurm]) parse on slim install
|
||||
run: |
|
||||
/tmp/slim/bin/python - <<'PY'
|
||||
from pydantic_config import cli
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
rl = cli(RLConfig, args=["@", "examples/Intellect-3.1/rl.toml"])
|
||||
assert rl.slurm is not None, "expected [slurm] in example config"
|
||||
# On slim, template_path can't be auto-resolved (heavy wheel absent) — must stay None.
|
||||
assert rl.slurm.template_path is None, f"unexpected template_path on slim: {rl.slurm.template_path}"
|
||||
# Configs that don't pull in a v1 env package parse on the slim
|
||||
# (prime-rl-configs-only) install: the SFT config has no env sections, and the
|
||||
# reverse_text RL recipe uses a v0 env id (resolved lazily, not imported at parse).
|
||||
# RL configs on a v1 taskset can't parse here because vf.EnvServerConfig imports the
|
||||
# (uninstalled) env package at parse time.
|
||||
for cfg_cls, args in [
|
||||
(SFTConfig, ["@", "examples/reverse_text/slurm_sft.toml"]),
|
||||
(RLConfig, ["@", "examples/reverse_text/rl.toml", "@", "examples/reverse_text/slurm_rl.toml"]),
|
||||
]:
|
||||
cfg = cli(cfg_cls, args=args)
|
||||
assert cfg.slurm is not None, f"expected [slurm] in {args}"
|
||||
# On slim, template_path can't be auto-resolved (heavy wheel absent) — must stay None.
|
||||
assert cfg.slurm.template_path is None, f"unexpected template_path on slim: {cfg.slurm.template_path}"
|
||||
print("slim parse OK")
|
||||
PY
|
||||
|
||||
@@ -36,7 +36,7 @@ jobs:
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run unit tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
@@ -107,7 +107,7 @@ jobs:
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run integration tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
|
||||
@@ -86,7 +86,7 @@ jobs:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run experiment
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
|
||||
-187
@@ -1,187 +0,0 @@
|
||||
# Changelog
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **`orchestrator.algo.length_penalty` restructured to a single `linear` shape; `tokens`/`turns` length penalties removed**: The `grpo`-family length penalty keeps the `[orchestrator.algo.length_penalty]` key but is collapsed to a single `type = "linear"` shape; the discriminated `type = "tokens" | "turns"` efficiency-shaping variants (and the `efficiency_shaping` helper) are removed. The linear penalty subtracts a `pass_rate`-scaled penalty from each reward before the GRPO baseline, summing three terms — `num_output_tokens_weight` × output tokens, `num_input_tokens_weight` × input (non-output) tokens, and `num_turns_weight` × turns — each normalized by the group's own max for that quantity. Field renames within the penalty: `coef` → `num_output_tokens_weight` (default `0.25`), `context_coef` → `num_input_tokens_weight` (default `0.1`), `turns_coef` → `num_turns_weight` (default `0.1`); the `gate_by_correctness` flag is removed. `extra="forbid"` rejects the old keys, so existing configs must migrate. (2026-06-29)
|
||||
- **`model.fused_lm_head_token_chunk_size` `"auto"` option removed**: The `"auto"` value is no longer accepted. Use an explicit integer (e.g. `8192`) or `"disabled"`. The `"auto"` value previously resolved to `8192` for RL training — set `fused_lm_head_token_chunk_size = 8192` explicitly to get the same behavior.
|
||||
- **Memory-saving defaults enabled**: `trainer.model.ac`, `trainer.model.ac_offloading`, `trainer.model.compile`, `trainer.model.optim_cpu_offload`, and `trainer.model.fused_lm_head_token_chunk_size` are now enabled by default to provide sane memory-efficient defaults out of the box. Specifically: `ac` defaults to `ActivationCheckpointConfig()` (full mode), `ac_offloading` defaults to `ActivationOffloadingConfig()`, `compile` defaults to `CompileConfig()` (`fullgraph=false`), `optim_cpu_offload` defaults to `true`, and `fused_lm_head_token_chunk_size` defaults to `1024`. SFT training silently disables `fused_lm_head_token_chunk_size` (sets it to `"disabled"`). Configs using `max_concurrent_runs > 1` must explicitly set `optim_cpu_offload = false`. To disable any of these, set the field to `None` / `"None"` / `false` / `"disabled"` as appropriate.
|
||||
- **`model.ep` defaults to `"auto"`**: The `ep` field type changed from `int` to `int | Literal["auto"]`, defaulting to `"auto"`. At trainer startup, `resolve_ep()` checks if the model is MoE (via `AutoConfig`); if so, it resolves to `min(fsdp_island_size, 8)` where `fsdp_island_size = world_size // dp_replicate`. For non-MoE models, `"auto"` resolves to 1 (no-op). Set `ep` to an explicit integer to override.
|
||||
- **verifiers v1 training integration** (collection of removals/renames). The orchestrator now trains against a v1 env server returning `vf.Trace` rollouts, renderer-only, with a unified token schema.
|
||||
- **`[[orchestrator.train.env]]` is now a v1 `vf.EnvServerConfig`**: a v1 env is `taskset = { id = "<id>" }` + `harness = { id = "default", runtime = { type = "subprocess" } }`. A bare `id = "<id>"` (optionally with `args`) runs the v0 env through the verifiers legacy bridge — old flat `id`/`args`-only configs keep working as legacy envs; v1 envs must use the `taskset`/`harness` shape.
|
||||
- **`orchestrator.train.env` no longer defaults to a `reverse-text` env**: the default is now empty (`[]`), so configs must declare `[[orchestrator.train.env]]` explicitly.
|
||||
- **`...env[].num_workers` → `pool`**: per-env worker sizing moves to a `pool` config (`static`/`elastic`). Back-compat: `num_workers = N` maps to `pool = { type = "static", num_workers = N }` and `"auto"` to the default elastic pool; the group-level `orchestrator.train.num_workers` / `orchestrator.eval.num_workers` are removed.
|
||||
- **`orchestrator.renderer` is now required (MITO removed)**: it was `RendererConfig | None`, where `renderer = None` selected the MITO path; training is now renderer-only, so `renderer` is non-optional. Drop `renderer = None` / `renderer = "None"`.
|
||||
- **`...client.timeout` / `...client.connect_timeout` removed**: the v1 rollout client manages its own timeouts. Drop these from `[orchestrator.student.client]` and `[orchestrator.teacher.client]`. (2026-06-23)
|
||||
- **`orchestrator.advantage` length-penalty overhaul + length-weighted baseline**: `length_penalty` is now a single shape — a linear penalty that subtracts `coef * pass_rate * (model completion tokens / orchestrator.seq_len)` from each reward before the baseline subtraction (`pass_rate` = group mean reward, so solved-often problems get the strongest concision pressure and never-solved groups get none), with an optional `gate_by_correctness` flag (default `false`) that restricts the penalty to correct rollouts (`reward == 1`). The previous discriminated `type = "tokens" | "turns"` efficiency-shaping variants and the per-penalty `max_length` field have been removed — configure `[orchestrator.advantage.length_penalty]` with `coef` (and optionally `gate_by_correctness`) instead; the denominator is always `orchestrator.seq_len`. Also adds `orchestrator.advantage.length_weighted_baseline` (default `false`): when enabled, the GRPO baseline is the token-length-weighted mean reward (`sum(len_i * reward_i) / sum(len_i)`) instead of the plain mean. (2026-06-03)
|
||||
- **`trainer.experimental.token_export` removed → `trainer.enable_token_export`**: `TrainerExperimentalConfig` and the `[trainer.experimental] token_export = true` setting have been removed with no migration alias. Existing trainer configs must delete the `[trainer.experimental]` block and set the new top-level trainer flag instead: `enable_token_export = true` in a trainer config file, or `trainer.enable_token_export = true` when nested under `[trainer]` in an RL config. The trainer entrypoint CLI flag is `--enable-token-export`. (2026-06-10)
|
||||
- **`inference.kv_cache_offload.cpu_bytes` removed → discriminated `type` config**: The flat `[inference.kv_cache_offload]` block with a single `cpu_bytes` field is replaced by a backend-discriminated union with composable `cpu`/`disk` tiers. Migrate native CPU offload from `[inference.kv_cache_offload]\ncpu_bytes = N` to `[inference.kv_cache_offload]\ntype = "native"` plus `[inference.kv_cache_offload.cpu]\nnum_bytes = N`. A `type = "mooncake"` backend (per-node distributed store; multi-node/SLURM only) and an optional `[inference.kv_cache_offload.disk]\npath = "..."` tier (layered behind cpu) are also available. `extra="forbid"` rejects the old `cpu_bytes` key, so existing configs must migrate. (2026-06-02)
|
||||
- **Orchestrator async-pipeline rewrite** (collection of removals/renames). The orchestrator was rewritten to overlap train/eval rollouts on a shared concurrency limiter; several config fields were removed or renamed.
|
||||
- **`orchestrator.seed` removed**: was only consumed by the deleted buffer; no replacement.
|
||||
- **`orchestrator.eval.eval_base_model` → `orchestrator.eval.skip_first_step`** (semantics inverted): `eval_base_model = true` becomes `skip_first_step = false` (the default — run the step-0 eval before any train rollouts). No alias; configs setting `eval_base_model` must rename.
|
||||
- **`orchestrator.eval.skip_eval_on_resume` (and its alias `skip_eval_on_restart`) removed**: folded into `skip_first_step`. Resume no longer re-fires an already-completed eval (deduped via per-env last-eval-step tracking in the checkpointed progress).
|
||||
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval` removed**: the drain-switch overlap (stop scheduling new train, let in-flight train drain while eval queues) is now the only eval transition mode.
|
||||
- **`ckpt.skip_buffer` removed**: there is no buffer to skip.
|
||||
- **`[orchestrator.buffer]` removed** (difficulty pools): the whole block and every key (`seed`, `easy_threshold`, `hard_threshold`, `easy_fraction`, `hard_fraction`, `online_difficulty_filtering`, `hash_keys`) are gone, with no alias — `extra="forbid"` rejects the block, so existing configs must delete it. To preserve `online_difficulty_filtering = true`, enforce the zero-advantage pre-batch filter: `[[orchestrator.pre_batch_filters]]\ntype = "zero_advantage"\nenforce = true`.
|
||||
- **`orchestrator.filters` → `orchestrator.post_batch_filters`** (renamed, no alias): existing configs setting `[[orchestrator.filters]]` must rename to `[[orchestrator.post_batch_filters]]` (`extra="forbid"` rejects the old key). A new `pre_batch_filters` list is also available. Filters are **train-only** now — eval rollouts are no longer filtered.
|
||||
- **`orchestrator.max_off_policy_steps` now also applies to eval** (behavior change, field unchanged): eval rollouts that fall more than `max_off_policy_steps` versions behind the policy are cancelled, same as train. (2026-05-29)
|
||||
- **`sampling.min_tokens`, `sampling.repetition_penalty`, `sampling.seed` removed**: Dropped from both `TrainSamplingConfig` and `EvalSamplingConfig` (group-level `[orchestrator.train.sampling]` / `[orchestrator.eval.sampling]` and per-env `[[orchestrator.train.env.sampling]]` / `[[orchestrator.eval.env.sampling]]`). `min_tokens` suppressed natural EOS, `repetition_penalty` distorts the on-policy sampling distribution, and `seed` wasn't pulling its weight — none belonged on the supported config surface. Existing configs setting any of these must delete the field. Hard-deprecation, no migration window. (2026-05-27)
|
||||
- **`wandb.shared` removed**: The deprecation shim that popped `wandb.shared` from input dicts with a `FutureWarning` (introduced in #2649) is gone. The `rl` entrypoint always uses shared W&B mode now, and existing configs that still set `wandb.shared = true` (or `false`) will fail validation. Drop the field from your config. (2026-05-27)
|
||||
- **`max_async_level` and `strict_async_level` removed**: The async-execution semantics between trainer and orchestrator are now design invariants, not config knobs. The trainer always runs exactly one step ahead of inference, and the orchestrator always adopts the freshest checkpoint that doesn't violate the one-step barrier. The shared top-level `max_async_level`, the per-sub-config `trainer.max_async_level` / `orchestrator.max_async_level`, and `orchestrator.strict_async_level` have all been removed. Existing configs setting any of these must drop the field; the previous defaults (`max_async_level = 1`, `strict_async_level = false`) match the new hardcoded behavior. Bench mode no longer bypasses the weight-ckpt wait (the `int(1e9)` workaround is gone) and `multimodal/rl_color_codeword_feat_renderer.toml`'s prior `max_async_level = 0` (fully synchronous on-policy) is no longer expressible. (2026-05-25)
|
||||
- **`teacher_inference` removed from RL entrypoint**: The `[teacher_inference]` config block and the `deployment.num_teacher_gpus` / `deployment.num_teacher_nodes` fields have been removed. The `rl` entrypoint now only manages the student-policy inference server. External teachers (used by OPD and local-vLLM SFT) must be started manually (e.g. `CUDA_VISIBLE_DEVICES=1 uv run inference --model.name <teacher> --server.port 8001 ...`) and pointed at via `[orchestrator.teacher.client]`. Existing configs using `[teacher_inference]` or `deployment.num_teacher_gpus` / `deployment.num_teacher_nodes` must drop those fields and bring up the teacher out-of-band. (2026-05-25)
|
||||
- **`rollouts_per_example` → `group_size`**: The orchestrator-level field, the group-level `[orchestrator.eval]` field, and the per-env `[[orchestrator.eval.env]]` field have all been renamed. The old name still parses as a validation alias (in both TOML and CLI), so existing configs keep working without changes; new configs should prefer `group_size`. (2026-05-22)
|
||||
- **`AdvantageInputs` / `AdvantageOutputs` are now per-group, and `AdvantageOutputs.advantages` is a plain `list[float]`** (second breaking change to this API in three weeks). `AdvantageInputs.rollouts` is now `list[vf.RolloutOutput]` (a single group) instead of `list[list[vf.RolloutOutput]]`, and `AdvantageOutputs.advantages` is now `list[float]` instead of a 2D `Float[Tensor, "num_examples rollouts_per_example"]`. `compute_advantages` calls `advantage_fn` once per group, which lets partial-group training (groups smaller than `rollouts_per_example` after rollout errors) round-trip without the previous bucket-by-size workaround. Custom advantage functions must drop the outer list dimension and return a list of floats — e.g. `AdvantageOutputs(advantages=(rewards - rewards.mean(dim=1, keepdim=True)).tolist())` becomes `AdvantageOutputs(advantages=[r - mean for r in rewards])` (or `.tolist()` if you keep torch internally). (2026-05-22)
|
||||
- **`[model.vlm]` requires `orchestrator.use_renderer = true`**: VLMs must go through the renderer path; the `vlm_requires_renderer` validator rejects `use_renderer = false` when `[model.vlm]` is set. The renderer owns the HF processor per-slot and ships generic `mm_kwargs` keyed by the model's forward signature. Since `use_renderer` already defaults to `true`, most VLM configs need no change. (2026-05-19)
|
||||
- **First-class `training_mode` + batch-driven loss dispatch** (collection of removals/renames). Loss selection is now driven by `TrainingSample.training_mode` (`rl` / `opd` / `sft`), set under `[orchestrator]`. The trainer is mode-agnostic and dispatches per batch.
|
||||
- **`orchestrator.use_sft_loss` removed**: replaced by `[orchestrator] training_mode = "sft"`. The orchestrator stamps each sample's `training_mode` and the trainer dispatches to `sft_loss_fn` per batch.
|
||||
- **`orchestrator.teacher_rollout_model` removed (no alias)**: configs must rename to `[orchestrator.teacher]` (`teacher_model` is also accepted as a back-compat alias for `teacher`). Used in both opd and sft modes; the role is determined by `training_mode`.
|
||||
- **`orchestrator.model` → `orchestrator.student`**: renamed for symmetry with `orchestrator.teacher`. Legacy `[orchestrator.model]` and a flat `[orchestrator.model.lora]`-style layout are aliased via a back-compat shim, so most existing configs still parse. New code should use `[orchestrator.student.*]`.
|
||||
- **`trainer.loss.type = "sft"` removed (`SFTLossConfig` deleted)**: zero-field discriminator that is now implied by `training_mode = "sft"`. `trainer.loss` collapsed to a `DefaultLossConfig | CustomLossConfig` union. Existing configs setting `[trainer.loss] type = "sft"` must remove that line; the orchestrator-level `training_mode = "sft"` is enough.
|
||||
- **`trainer.loss.teacher_tau` removed from `DefaultLossConfig`**: the teacher-KL term is now exclusive to `opd_loss_fn` (which inlines `teacher_tau = 1.0`). `default_loss_fn` only handles reward-driven RL and no longer accepts a `teacher_tau`. Configs that set `teacher_tau` on `[trainer.loss]` will fail validation — switch to `[orchestrator] training_mode = "opd"` (which uses `opd_loss_fn` with the value baked in).
|
||||
- **`trainer.loss` only applies to rl-mode batches**: opd and sft don't read `trainer.loss`. `opd_loss_fn`'s knobs (dppo_mask_*, kl_tau) are inlined as literals; tweak them by editing the function. `CustomLossConfig` overrides the rl-mode loss only — opd and sft always use their dedicated fns. (2026-05-19)
|
||||
- **`orchestrator.use_token_client` removed**: The server-tokenized TITO path has been deprecated end-to-end. The orchestrator-side config flag (`use_token_client`), the verifiers client_type (`openai_chat_completions_token`), and the inference server's `/v1/chat/completions/tokens` route (along with the `OpenAIServingChatWithTokens` wrapper) are all gone. The orchestrator now picks between renderer-backed TITO (`use_renderer = true`, default) and MITO (`use_renderer = false`, fallback). Existing configs with `use_token_client = true` must migrate to `use_renderer = true` (or `use_renderer = false` for MITO); configs with `use_token_client = false` can simply drop the field. (2026-05-19)
|
||||
- **`orchestrator.advantage.length_penalty` → discriminated sub-config**: The scalar `length_penalty: Literal["tokens","turns"] | None` is replaced by a `LengthPenaltyConfig | None` discriminated on `type`. Token shaping now takes weighted completion + tool-response token costs. Migration: `length_penalty = "tokens"` becomes `[orchestrator.advantage.length_penalty]\ntype = "tokens"` (default weights `completion_weight = 1.0`, `tool_response_weight = 1.0` — total context). `length_penalty = "turns"` becomes `[orchestrator.advantage.length_penalty]\ntype = "turns"`. (2026-05-06)
|
||||
- **`orchestrator.advantage.length_shaping` → `orchestrator.advantage.length_penalty`**: The boolean `length_shaping` flag has been replaced by `length_penalty: Literal["tokens", "turns"] | None` (default: `None`). `length_shaping = true` becomes `length_penalty = "tokens"`; `length_shaping = false` becomes `length_penalty = None`. The new `"turns"` option applies the same correctness-gated efficiency shaping using trajectory turn count instead of completion-token count. (2026-05-01)
|
||||
- **`AdvantageInputs` API**: Replaced the `rewards`/`completion_lengths`/`num_turns` tensor fields with a single `rollouts: list[list[vf.RolloutOutput]]` (grouped by problem). Custom advantage functions can now access any rollout metadata. Existing custom advantages must update their signatures and extract per-rollout fields directly (e.g. `torch.tensor([[r["reward"] for r in g] for g in inputs.rollouts])`). (2026-05-01)
|
||||
- **`orchestrator.teacher_rollout_model` now requires `orchestrator.use_sft_loss = true`**: External teacher rollout configs no longer rely on `trainer.loss.type = "sft"` to select SFT loss. Existing hard-distill configs must set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; the orchestrator validates the pair and stamps training samples with the per-batch SFT loss bool. (2026-04-26)
|
||||
- **`model.attn = "eager"` (NEW option)**: Added `eager` as a valid value for the `model.attn` field. Required for GPT-OSS models on non-Hopper GPUs, since the only flash attention kernel GPT-OSS supports (`kernels-community/vllm-flash-attn3`) is Hopper-only. A clear error message is raised at model load time if GPT-OSS is used without `eager` on unsupported hardware. Also added `kernels` as a core dependency. (2026-04-05)
|
||||
- **`[[orchestrator.env]]` → `[[orchestrator.train.env]]`**: Training environments and sampling are now configured under `[orchestrator.train]`. The old `[[orchestrator.env]]` and `[orchestrator.sampling]` paths are auto-translated with a deprecation warning and will be removed in a future release. (2026-04-09)
|
||||
- **Per-env sampling overrides (NEW)**: Both `TrainEnvConfig` and `EvalEnvConfig` now accept a `[sampling]` section for per-env overrides. Unset fields inherit from the group-level sampling config (`[orchestrator.train.sampling]` or `[orchestrator.eval.sampling]`). (2026-04-09)
|
||||
- **Per-env eval sampling overrides**: `EvalEnvConfig` now accepts a `[sampling]` section. Unset fields inherit from `[orchestrator.eval.sampling]`. All `EvalSamplingConfig` fields remain nullable (None = defer to inference server default). (2026-04-09)
|
||||
- **`orchestrator.buffer.env_ratios` → per-env `orchestrator.train.env[].ratio`**: `buffer.env_ratios` has been removed. Set `ratio` on each `[[orchestrator.train.env]]` entry instead. Ratios must be all-or-nothing across envs (either all have a ratio or none do). (2026-04-05)
|
||||
- **`orchestrator.val` removed**: The `[orchestrator.val]` config section (`ValConfig`) has been removed. Existing configs must delete this section. (2026-04-05)
|
||||
- **`orchestrator.max_concurrent` removed**: Concurrency limiting via `max_concurrent` and the global semaphore have been removed. Existing configs must delete this field. (2026-04-05)
|
||||
- **`orchestrator.buffer.hash_keys` default changed**: Default changed from `["task", "prompt"]` to `["env_name", "prompt"]`. The `task` field is no longer overridden by the orchestrator for env identification; `env_name` is used instead. Buffer checkpoints using the old default may not resume correctly. (2026-04-05)
|
||||
- **`orchestrator.eval.env[].failed_rollouts` metric is now a ratio**: The `eval/{name}/failed_rollouts` metric now reports a ratio (0.0–1.0) instead of a raw count. Dashboards keying on this metric should be updated. (2026-04-05)
|
||||
- **`orchestrator.sampling.temp_scheduler` removed**: Temperature scheduling (`TemperatureSchedulerConfig`) has been removed. `sampling.temperature` is now a required `float` (default `1.0`). Existing configs using `temp_scheduler` must replace it with a fixed `temperature` value. (2026-04-05)
|
||||
- **`orchestrator.verification` removed**: The `[orchestrator.verification]` config section (`VerificationConfig`) has been removed. Rollout scoring is now always enabled. Existing configs must delete this section. (2026-04-05)
|
||||
- **`orchestrator.eval.env[].skip_first` removed**: The `skip_first` field on `EvalEnvConfig` has been removed. Existing configs using this field must delete it. (2026-04-05)
|
||||
- **`EvalSaveHFConfig` removed**: Unused config class removed. (2026-04-09)
|
||||
- **`orchestrator.env[].max_total_completion_tokens` (NEW)**: Added `max_total_completion_tokens: int` to `EnvConfig` (default: `-1`, disabled). Limits the total completion tokens across all turns in a multi-turn rollout. Auto-populated into `extra_env_kwargs` and applied via the verifiers `set_max_total_completion_tokens()` setter. Works for both training and eval environments. (2026-04-06)
|
||||
- **`sampling.max_tokens` → `sampling.max_completion_tokens`**: Renamed `max_tokens` to `max_completion_tokens` in both `SamplingConfig` and `EvalSamplingConfig` for consistency with OpenAI API naming. The old name is accepted with a deprecation warning. (2026-04-06)
|
||||
- **`log.file` and `log.env_worker_logs` removed**: Removed `log.file` (from `LogConfig` and `SharedLogConfig`) and `log.env_worker_logs` (from `LogConfig`). Python file logging is replaced by deployment-level capture. Existing configs using these fields must delete them. Log paths unified: `.stdout` files renamed to `.log`, SLURM logs moved from `slurm/` to `logs/`. (2026-03-31)
|
||||
- **`trainer.log.ranks_filter` (NEW)**: Added `ranks_filter: list[int]` to `TrainerLogConfig` (default: `[0]`). Controls which ranks appear in trainer console output via torchrun's `--local-ranks-filter`. (2026-03-31)
|
||||
- **`wandb.log_extras.sample_ratio` / monitor sample logging defaults**: `wandb.log_extras.sample_ratio` is now actually applied to W&B sample-table logging via the shared monitor sampler (it was previously a no-op for WandB). Separately, the orchestrator no longer hard-caps sample logging to 8 rollouts before monitor-level sampling runs, so when monitor `sample_ratio` is `None`, monitors now receive and may log the full rollout batch for a step instead of at most 8 rollouts. This affects both W&B and Prime monitor sample logging behavior. (2026-03-27)
|
||||
- **`[model.vlm].freeze_vision_encoder`**: Added to `VLMConfig`. Controls whether the vision encoder is frozen (default: `true`). When `false`, the vision encoder is trainable and FSDP-sharded per-block. Has no effect with LoRA. Moved from `[trainer.model].freeze_vision_encoder` into the VLM sub-config. (2026-03-25)
|
||||
- **`loss_impl = "quack_fused"` (SFT)**: Added `quack_fused` option for the SFT `loss_impl` field. Uses quack-kernels for chunked linear + cross-entropy with CuTe DSL CUDA kernels, avoiding full logits materialization. Requires `quack-kernels` package. Does not support Gemma logit softcapping. Custom model impl (`model.impl = "custom"`) also gains quack RMSNorm acceleration on CUDA automatically. (2026-03-26)
|
||||
- **`model.ac.targets`**: Removed the `mamba` selective activation checkpoint target and folded that behavior into the broader `linear_attn` target. Existing configs using `targets = ["mamba"]` will now fail validation at runtime with `ValueError`; switch them to `targets = ["linear_attn"]`. The `linear_attn` target description now covers supported token mixers outside the standard softmax-attention path, including NemotronH Mamba layers, Qwen3.5-MoE GatedDeltaNet layers, and AFMoE sliding-window attention layers. (2026-03-28)
|
||||
- **`model.tp` (trainer `ModelConfig`)**: Removed from the trainer model config. Existing trainer configs must delete this field; it is no longer accepted. (2026-03-26)
|
||||
- **`orchestrator.env[].num_workers`**: Added configurable env server worker count (`int | "auto"`, default: `"auto"`). When `"auto"`, scales based on concurrency (1 worker per 256 concurrent rollouts). Only used when the orchestrator spawns the env server (i.e. `address` is not set). (2026-03-25)
|
||||
- **`[model.vlm]` (NEW — replaces auto-detection)**: VLM mode is now opt-in via a `[model.vlm]` sub-config with required `vision_encoder_attr` and `language_model_attr` fields. There is no auto-detection — if you train a VLM, you must add `[model.vlm]`. Existing multimodal configs need the new section. See `docs/multimodal.md` for the table of known model attrs. (2026-03-24)
|
||||
- **`model.optimization_dtype` / `model.reduce_dtype` (VLM models, RL only)**: VLM dtype validation now only applies to RL training (`TrainerConfig`), not SFT. VLM models used with `sft` no longer require `optimization_dtype='bfloat16'` / `reduce_dtype='bfloat16'`. RL training still enforces both to match vLLM inference. (2026-03-24)
|
||||
- **`model.ep_comm_backend`**: Added expert-parallel communication backend selection. Accepted values are `torch` (default, uses TorchTitan all-to-all collectives) and `deepep` (uses DeepEP custom kernels). This field only affects configurations with expert parallelism enabled via `model.ep > 1`. (2026-03-22)
|
||||
- **`model.deepep_num_sms`**: Added DeepEP SM allocation control for intranode dispatch/combine kernels (default: `20`, minimum: `1`). This field is only used when `model.ep_comm_backend='deepep'`; it also determines the internode RDMA channel count (`num_channels = num_sms / 2`). (2026-03-22)
|
||||
- **`model.deepep_token_chunk_size`**: Added optional token chunk size for DeepEP MoE pipelining (default: `None`, minimum: `1`). When set, DeepEP dispatch for chunk `i+1` overlaps expert compute for chunk `i`. This field is only used when `model.ep_comm_backend='deepep'`. (2026-03-22)
|
||||
- **`model.optimization_dtype` / `model.reduce_dtype` (VLM models)**: Added validation that VLM models must use `optimization_dtype='bfloat16'` and `reduce_dtype='bfloat16'` to match vLLM inference. Previously valid configs with `float32` (the default) are now rejected for VLM model names. Set both fields to `"bfloat16"` when training VLMs. (2026-03-21)
|
||||
- **`model.ac.mode`** and **`model.ac.targets`**: Added selective activation checkpointing configuration. `model.ac.mode` accepts `full` (default) or `selective`. When `selective`, `model.ac.targets` selects subcomponents to checkpoint. Supported public targets are currently `norm`, `attention_sdpa`, `mla_up_proj`, and `routed_experts`; runtime validation remains the source of truth. `model.ac.targets` defaults to `["norm"]`, and selective mode requires at least one target. (2026-03-20)
|
||||
- **`orchestrator.advantage.length_shaping_alpha` → `orchestrator.advantage.length_shaping`**: Replaced GR³ (`length_shaping_alpha: float | None`) with correctness-gated efficiency shaping (`length_shaping: bool`, default: `false`). No hyperparameter needed, no `online_difficulty_filtering` requirement. Existing configs using `length_shaping_alpha` must switch to `length_shaping = true`. (2026-04-13)
|
||||
- **`orchestrator.advantage.length_weighted_mean`**: Removed. The default advantage now always uses the plain per-problem mean baseline unless `orchestrator.advantage.length_shaping` is enabled. Existing configs must delete this field. (2026-03-19)
|
||||
- **`prime_monitor.log_extras.sample_ratio`**: Added ratio-based rollout sampling (0.0–1.0, default: None). When set, caps the number of rollouts logged per step to `len(rollouts) * sample_ratio`. `None` preserves current behavior (log all rollouts). Interacts with existing `interval` gate which still runs first. (2026-03-12)
|
||||
- **`client.connect_timeout`**: Added configurable TCP connect timeout for inference API requests (default: 30.0s). Previously hardcoded to 5.0s. Helps with vLLM or cluster flakiness (2026-03-11)
|
||||
- **`model.fused_lm_head_token_chunk_size`**: Added as the fused LM-head chunking field for the token-chunked implementation. Unlike the removed `model.fused_lm_head_chunk_size`, this chunks over flattened sequence tokens rather than vocabulary rows. `model.fused_lm_head_chunk_size` is no longer accepted; switch configs to `model.fused_lm_head_token_chunk_size` explicitly. (2026-03-09)
|
||||
- **`slurm.pre_run_command`**: Added optional shell command to run on the head node before starting the job. Useful for cleanup routines (e.g. killing stale processes, removing lock files). For all-nodes execution, wrap with `srun` in the command string (default: None) (2026-03-08)
|
||||
- **`slurm.nodelist`**, **`slurm.exclude`**, **`slurm.account`**, **`slurm.time`**: Added common SLURM scheduling options (all default: None) (2026-03-08)
|
||||
- **`orchestrator.verification.enabled`**: Added top-level rollout verification switch. `orchestrator.buffer.skip_verification` has been removed; use `verification.enabled = false` instead. When disabled, rewards are always 0 and reward-dependent buffer features (`online_difficulty_filtering`, `easy_threshold`, `hard_threshold`) must be unset (2026-03-03)
|
||||
- **`client.dp_rank_count`**: Added configuration for data-parallel inference routing. When > 1, each `client.base_url` is expanded into `dp_rank_count` logical clients and pinned via `X-data-parallel-rank` to keep multi-turn rollouts on a consistent DP rank (default: 1) (2026-03-03)
|
||||
- **`model.lora`**: Moved from `model.experimental.lora` to `model.lora` (no longer experimental) (#1440, 2025-12-16)
|
||||
- Auto-set `api_server_count=1` on inference when LoRA is enabled, because vLLM doesn't support hotloading for multiple API servers (#1422, 2025-12-17)
|
||||
- **`inference.model.rope_scaling`**: Added RoPE scaling configuration passthrough to vLLM (#1447 2025-12-17)
|
||||
- **`orchestrator.env_mix`**: Deprecated in favor of `orchestrator.buffer.env_ratios` (#1450, 2025-12-18)
|
||||
- **`orchestrator.buffer.hash_keys`**: Added hash keys configuration for buffer checkpointing (#1450, 2025-12-18)
|
||||
- **`orchestrator.buffer.env_ratios`**: Added environment ratio configuration for buffer sampling (#1450, 2025-12-18)
|
||||
- **`orchestrator.buffer.skip_verification`**: Added configuration to skip verification of rollouts using the environment's rubric. If True, rewards are always set to 0. Cannot be used with `online_difficulty_filtering=True` or when `easy_threshold`/`hard_threshold` are set (default: False)
|
||||
- **`orchestrator.ckpt.buffer_path`**: Deprecated (#1450, 2025-12-18)
|
||||
- **`orchestrator.buffer.easy_fraction`** and **`orchestrator.buffer.hard_fraction`**: Easy and hard fraction now defines the fraction of easy and hard problems to convert to normal when resuming, whereas previously it was the ratio of easy/ hard samples to sample per step (#1450, 2025-12-18)
|
||||
- **`orchestrator.teacher_model`**: Added teacher model configuration for computing teacher logprobs (e.g. for distillation). Supports `TeacherModelConfig` (custom model) or `None` (disabled). Renamed from `reference_model` (2025-12-20)
|
||||
- **`seq_len`**: Added root-level `seq_len` config that sets both `trainer.model.seq_len` and `orchestrator.seq_len`. Added validation that `trainer.model.seq_len >= orchestrator.seq_len` (2025-12-18)
|
||||
- **`trainer.loss.sequence_mask_ratio_low`** and **`trainer.loss.sequence_mask_ratio_high`**: Renamed to `trainer.loss.sequence_mask_low` and `trainer.loss.sequence_mask_high` (2025-12-19)
|
||||
- **`trainer.loss.token_mask_high`** and **`trainer.loss.token_mask_low`**: Added token-level importance ratio masking thresholds (2025-12-19)
|
||||
- **`trainer.loss.sequence_clip_high`**: Added sequence-level importance ratio clipping threshold (2025-12-19)
|
||||
- **`trainer.loss.geo_mask_high`** and **`trainer.loss.geo_mask_low`**: Added geometric importance ratio masking thresholds (2025-12-19)
|
||||
- **`trainer.loss.adv_tau`**: Added tau parameter for advantages (default: 1.0)
|
||||
- **`trainer.loss.teacher_tau`**: Added tau parameter for teacher logprobs (default: 0.0). Renamed from `ref_tau`
|
||||
- **`teacher_gpu_ids`**: Added GPU IDs for teacher inference server. When set, automatically starts a teacher inference server and configures `orchestrator.teacher_model`
|
||||
- **`teacher_inference`**: Added optional teacher inference config. Defaults to copying from `inference` config with port 8001
|
||||
- **`{orchestrator,trainer}.transport.zmq`**: Added ZMQ transport for training batches and micro batches (#1446, 2025-12-22)
|
||||
- **`model.impl`**: Changed default from `hf` to `auto`. With `auto`, the implementation automatically selects `custom` if supported for the model, otherwise falls back to `hf` (#1488, 2025-12-27)
|
||||
- **`orchestrator.eval.skip_eval_on_resume`**: Added flag (default `True`) to skip the first potentially redundant online eval immediately after resuming from a checkpoint (#1491, 2025-12-27)
|
||||
- **`trainer.weight_broadcast.adapter_only`**: Removed. Adapter-only behavior is now automatically derived from the presence of LoRA configuration (2025-12-27)
|
||||
- **`ckpt.keep`**: Renamed to `ckpt.keep_last`. Added `ckpt.keep_interval` to keep checkpoints at every N steps permanently (2025-12-31)
|
||||
- **`MultiLoRAMoE`**: QwenMoE now supports training expert loras and this is enabled by default in the `target_modules`. (2026-01-01)
|
||||
- **`model.fused_lm_head_chunk_size`**: Added chunk size configuration for fused LM head to enable memory-efficient chunked logprob computation. When set, splits vocabulary into chunks to avoid materializing full [N, V] logit tensor (default: None) (#1525, 2026-01-03)
|
||||
- **`model.fused_lm_head_chunk_size`**: RL training now auto-sets this to 2048 if not specified (except when `impl='liger_kernel'`). SFT training continues to use None (2026-01-05)
|
||||
- **`trainer.metrics_server`**: Added optional Prometheus metrics server for trainer observability. Exposes `/metrics` endpoint with step, loss, throughput, grad_norm, etc. Disabled by default (default: None) (#1547, 2026-01-06)
|
||||
- **`model.lora.alpha`**: Changed default from 16.0 to 32.0 (2026-01-10)
|
||||
- **`orchestrator.env.log`**: Added logging configuration for environment workers. If set, enables logging with `level` (str, default: "warn") and `vf_level` (str, default: "warn") fields. If None (default), logging is disabled (#1561, 2026-01-13)
|
||||
- **`eval.watcher`**: Added flag (default `False`) to watch `weights_dir` for newly-created stable checkpoints and evaluate them as they appear (2026-01-14)
|
||||
- **`orchestrator.log.env_worker_logs`**: Added flag (default `False`) to write env worker logs to `logs/env_workers/{env_name}.log` (2026-01-15)
|
||||
- **`orchestrator.env.log`**: Removed. Use `orchestrator.log` for env worker logging instead (2026-01-15)
|
||||
- **`orchestrator.eval.retry.reraise`**: Changed default from `True` to `False`. When `False`, raises `tenacity.RetryError` after retries are exhausted instead of the original exception, allowing failed eval environments to be skipped with a warning (#1586, 2026-01-14)
|
||||
- **`model.ep`**: Expert parallelism now supported (with auto/custom impl only), changed from the old behaviour when `ep>1` was a no-op to a proper parallelization of the MoE layers. (#1595, 2026-01-15)
|
||||
- **`orchestrator.reload_weights_on_start`**: Removed. The reload was a no-op in practice since vLLM servers already start with base weights, and LoRA runs skipped it. (#1829, 2026-02-19)
|
||||
- **`orchestrator.client.elastic`**: Added elastic inference pool with DNS-based service discovery. Supports dynamic server scaling via any DNS hostname with multiple A records (Kubernetes headless services, Consul, Route53, etc.). Automatically syncs LoRA adapters on new servers and only exposes ready servers to workers (#1617, 2026-01-19)
|
||||
- **`model.fused_lm_head_chunk_size`**: Replaced chunk size `int | None` setting with `int | Literal["auto", "disabled"]` setting. `auto` auto-sets to 2048 if possible. `disabled` explicitly disables chunked loss (use vanilla LM head). Default behaviour is to use `auto` for RL training and `disabled` for SFT training. (not changed from previous version) (#1649, 2026-01-23)
|
||||
- **`client.skip_model_check`**: Added configuration to skip checking if the model is available in the inference pool. Useful for external APIs or API keys that don't support the /models endpoint (default: False) (#1543, 2026-01-06)
|
||||
- **`orchestrator.sampling.temp_scheduler`**: Added optional temperature schedule configuration with linear and cosine schedules. Set either `sampling.temperature` (constant) or `sampling.temp_scheduler` (schedule), not both. Default remains 1.0 if neither is set. (2026-01-27)
|
||||
- **`orchestrator.trajectory_strategy`**: Deprecated. Interleaving now automatically handles extension breaks by starting a new sample when the prefix doesn't match, achieving best-of-both behavior. The setting is ignored and interleaved mode is always used. (2026-01-30)
|
||||
- **`model.impl`**: Removed `liger_kernel` model implementation from supported options. The Liger kernel dependency remains for SFT loss. (2026-01-30)
|
||||
- **`log.json_logging`**: Added JSON structured logging option for log aggregation systems (Loki, Grafana, etc.). Outputs flat newline-delimited JSON with `timestamp`, `level`, `message`, `module`, `function`, `line` fields. Available on root `log`, `trainer.log`, and `orchestrator.log` (default: False) (2026-01-28)
|
||||
- **`model.optim_cpu_offload`**: Added flag to offload optimizer states to CPU without moving parameters (default: False) (2026-01-31)
|
||||
- **`orchestrator.tasks_per_minute`**: Added optional rate limiting for sandbox tasks per environment worker. Uses token bucket algorithm. If None (default), no rate limiting is applied (2026-02-02)
|
||||
- **`model.cp`**: When `cp>1` with `attn="flash_attention_3"`, require `model.impl="custom"` (FA3 ring-attention kernel only in custom path) (2026-02-06)
|
||||
- **`model.attn`**: Added `fa4` as an attention implementation option. Flash attention 4 is only supported with the custom implementation (#1726, 2026-02-06)
|
||||
- **`inference.model.enable_prefix_caching`**: Added flag to enable prefix caching in vLLM. Passed to vLLM as `--enable-prefix-caching` (default: None) (2026-02-08)
|
||||
- **`orchestrator.env.address`**: Added address field on `EnvConfig`. If set, connect to an environment server at this address; if None, spawn a server in a subprocess (2026-02-06)
|
||||
- **`orchestrator.env.extra_env_kwargs`**: Added on `EnvConfig`. Extra kwargs passed to the env (e.g. seq_len, interleaved_rollouts, score_rollouts). Auto-populated by the orchestrator for training envs; generally not recommended for user override. Main use case is to match these kwargs when running an env in an isolated environment server (default: {}) (2026-02-06)
|
||||
- **`OrchestratorConfig`**: Removed `workers_per_env`, `max_env_worker_restarts`, and `mask_env_responses` (2026-02-06)
|
||||
- **`EvalSaveDiskConfig`**, **`EvalSaveConfig`**, **`RetryConfig`**, **`OnlineEvalConfig`**: Removed (2026-02-06)
|
||||
- **`TemperatureScheduleConfig`**: Renamed to `TemperatureSchedulerConfig` (2026-02-06)
|
||||
- **`optim.mu`**: Added Muon momentum (`mu`) config field (default: 0.95). Previously hardcoded to Muon class default. Also fixed `optim.betas1`/`optim.betas2` not being passed through to the Muon optimizer (2026-02-09)
|
||||
- **`dump_config`**: Added `--dump-config <path>` flag to the `rl` command. When set, writes the resolved subconfigs (trainer, orchestrator, inference, teacher_inference) to the given directory and exits without starting any processes (2026-02-12)
|
||||
- **`client.api_key_var`**: Changed default from "OPENAI_API_KEY" to "VLLM_API_KEY" (2026-02-12)
|
||||
- **`orchestrator.filters`**: Added orchestrator-side rollout filters for detecting degenerate generations. Supports `[[filters]] type = "gibberish"` (rare tokens at high entropy) and `[[filters]] type = "repetition"` (high-confidence token streaks). Detected rollouts get reward zeroed and completion mask cleared (2026-02-13)
|
||||
- **`inference.model.tool_call_parser`**: Changed default from `"hermes"` to auto-detection from model name. Uses `MODEL_TOOL_CALL_PARSER` dict to infer the correct vLLM tool call parser (e.g. Qwen3→`hermes`, GLM-4.5→`glm45`, GLM-4.7→`glm47`, MiniMax-M2→`minimax_m2`, INTELLECT-3→`hermes`). Unknown models default to `None`. Explicit values still take priority. (#1795, 2026-02-16)
|
||||
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval`**: Added flag to optionally cancel in-flight training rollouts before starting online evals. When enabled, avoids congestion by preventing training and eval rollouts from running simultaneously, but slows training as the rollout pipeline must refill after each eval (default: False) (2026-02-16)
|
||||
- **`orchestrator.use_token_client`**: Added flag to use the token-in-token-out (TITO) client for training across all environments. When enabled, uses `openai_chat_completions_token` client type instead of `openai_chat_completions`. Only use when environments have linear history and the chat template has the extension property (default: False) (2026-02-21)
|
||||
- **`model.cp` + AFMoE**: Context parallelism now works with AFMoE models via unified `substitute_ring_attn` which patches `_compute_attention` on both `FlashAttention` and `AfmoeFlashAttention` to use ring attention. Sliding window layers automatically get per-layer `window_size`; full attention layers default to `(-1, -1)`. Also plumbed `window_size` through the FA3 ring attention wrapper (`ring_fa3_varlen_func`). (2026-02-21)
|
||||
- **`orchestrator.token_batch_size`** and **`orchestrator.max_inflight_rollouts`**: Added token-based batching via `token_batch_size` and explicit in-flight rollout control via `max_inflight_rollouts` (2026-02-23)
|
||||
- **`orchestrator.batch_size`**: Now optional and mutually exclusive with `token_batch_size`. If neither is set, defaults to rollout mode with `batch_size=128` (2026-02-23)
|
||||
- **`inference.enable_expert_parallel`**, **`inference.all2all_backend`**, and **`inference.enable_eplb`**: Added expert-parallel inference controls passed to vLLM as `--enable-expert-parallel`, `--all2all-backend`, and `--enable-eplb` (defaults: `False`, `"allgather_reducescatter"`, `False`) (2026-02-23)
|
||||
- **`rl_slurm` / `sft_slurm` entrypoints**: Removed. SLURM submission is now handled by the unified `rl` and `sft` entrypoints. Add a `[slurm]` section to your config to submit via SLURM instead of running locally (2026-02-23)
|
||||
- **`inference_gpu_ids` / `trainer_gpu_ids` / `teacher_gpu_ids`**: Removed from `RLConfig`. Replaced by `[deployment]` section with `type = "single_node"` (fields: `num_train_gpus`, `num_infer_gpus`, `num_teacher_gpus`) or `type = "multi_node"` (fields: `num_train_nodes`, `num_infer_nodes`, `num_teacher_nodes`, `nodes_per_fsdp_group`). Default is `single_node` with 1 train GPU and 1 infer GPU (2026-02-23)
|
||||
- **`RLSLURMConfig`**: Removed. Fields `job_name`, `num_train_nodes`, `num_infer_nodes`, `gpus_per_node`, `nodes_per_fsdp_group`, `project_dir`, `slurm_template`, `dry_run` are now under `[slurm]` and `[deployment]` in the unified `RLConfig` (2026-02-23)
|
||||
- **`SFTSLURMConfig`**: Removed. Fields `job_name`, `num_nodes`, `gpus_per_node`, `nodes_per_fsdp_group`, `project_dir`, `slurm_template`, `dry_run` are now under `[slurm]` and `[deployment]` in `SFTConfig` (2026-02-23)
|
||||
- **`[deployment]` (RL)**: Added deployment configuration. `type = "single_node"` auto-derives contiguous GPU assignments from `num_infer_gpus`, `num_train_gpus`, `num_teacher_gpus`. `type = "multi_node"` requires `[slurm]` and uses `num_train_nodes`, `num_infer_nodes` (2026-02-23)
|
||||
- **`[deployment]` (SFT)**: Added deployment configuration. `type = "single_node"` with `num_gpus` (default: 1). `type = "multi_node"` with `num_nodes`, `nodes_per_fsdp_group`, `hf_hub_offline` (2026-02-23)
|
||||
- **`[slurm]` (RL)**: Added SLURM configuration with `job_name`, `project_dir`, `template_path`, `partition`, `dry_run`. When present, `uv run rl` generates and submits an sbatch script instead of running locally. Template is auto-selected based on deployment type (2026-02-23)
|
||||
- **`[slurm]` (SFT)**: Added SLURM configuration with `job_name`, `project_dir`, `template_path`, `partition`, `dry_run`. When present, `uv run sft` generates and submits an sbatch script instead of running locally (2026-02-23)
|
||||
- **`hf_hub_offline` (RL/SFT SLURM)**: Removed. `HF_HUB_OFFLINE=1` is now hardcoded in the multi-node SLURM templates (2026-02-23)
|
||||
- **SLURM templates**: Moved from `src/prime_rl/slurm/` to `src/prime_rl/templates/` and renamed to `single_node_rl.sbatch.j2`, `multi_node_rl.sbatch.j2`, `single_node_sft.sbatch.j2`, `multi_node_sft.sbatch.j2` (2026-02-23)
|
||||
- **Entrypoints**: Moved `rl` and `sft` entrypoints from `prime_rl.rl` / `prime_rl.sft` to `prime_rl.entrypoints.rl` / `prime_rl.entrypoints.sft`. No change to CLI usage (`uv run rl`, `uv run sft`) (2026-02-24)
|
||||
- **`output_dir` (RL)**: Changed from `Path | None` (default `None`) to `Path` (default `Path("outputs")`). The SLURM-specific validation that rejected the default has been removed — `output_dir` now works the same for local and SLURM runs (2026-02-24)
|
||||
- **`clean_output_dir`**: Added to `RLConfig` and `SFTConfig` (default: `False`). Training now raises `FileExistsError` when `output_dir` contains checkpoints from a previous run and not resuming. Set `clean_output_dir=true` to delete and start fresh, or set `ckpt.resume_step` to resume (2026-02-24)
|
||||
- **`clean`**: Removed from `RLConfig`. The old `clean` flag (default: `True`) silently deleted logs, rollouts, and broadcasts on every local RL run. Superseded by the explicit `clean_output_dir` flag (2026-02-24)
|
||||
- **Config consolidation**: All config modules moved into `prime_rl.configs` subpackage. `utils/config.py` + `transport/config.py` → `configs/shared.py`; `trainer/config.py` + `trainer/rl/config.py` → `configs/trainer.py`; `trainer/sft/config.py` → `configs/sft.py`; `orchestrator/config.py` → `configs/orchestrator.py`; `inference/config.py` → `configs/inference.py`; `rl_config.py` → `configs/rl.py`. Class renames: `SFTTrainerConfig` → `SFTConfig`, `RLTrainerConfig` → `TrainerConfig`. Component prefixes dropped from orchestrator and inference config classes (e.g. `OrchestratorCheckpointConfig` → `CheckpointConfig`). TypeAlias renames: dropped `Type` suffix (e.g. `LossConfigType` → `LossConfig`, `TransportConfigType` → `TransportConfig`), renamed `LossConfig` class → `DefaultLossConfig`. No TOML key changes. (2026-02-24)
|
||||
- **`trainer.enable_router_replay`**: Added flag to enable router replay. If True, will return routed experts in the batch. This is only supported if `enable_return_routed_experts=True` in the inference config or pass `--enable-return-routed-experts` to vLLM server. This is only supported for custom models. (2026-02-22)
|
||||
- **`inference.enable_return_routed_experts`**: Added flag to enable return routed experts. Passed to vLLM as `--enable-return-routed-experts` (2026-02-22)
|
||||
- **`orchestrator.oversampling_factor`**: Added rollout-only over-sampling config that resolves `max_inflight_rollouts = int(batch_size * oversampling_factor)` when `max_inflight_rollouts` is unset. Cannot be used with `token_batch_size` or together with explicit `max_inflight_rollouts` (2026-02-25)
|
||||
- **`sft.val`**: Added optional periodic SFT validation with `val/loss` and `val/num_tokens` logging. Configure via `sft.val.data` (validation dataset) and `sft.val.interval` (every N steps, default 50). Runs the full validation dataset each pass. (2026-02-26)
|
||||
- **`model.fused_lm_head_chunk_size`**: Changed default value from 2048 to 8192 for RL training (2026-02-26)
|
||||
- **`inference.data_parallel_size_local`** and **`inference.data_parallel_rpc_port`**: Added data-parallel node-local controls for vLLM, passed as `--data-parallel-size-local` and `--data-parallel-rpc-port` (defaults: `None`, `13345`) (2026-02-26)
|
||||
- **`dump_config`**: Removed from `RLConfig`. Replaced by `dry_run` (see below) (2026-02-26)
|
||||
- **`slurm.dry_run`**: Removed from `SlurmConfig`. Replaced by top-level `dry_run` (see below) (2026-02-26)
|
||||
- **`dry_run`**: Added to `RLConfig` and `SFTConfig` (default: `False`). When set, validates the config, writes resolved subconfigs to `output_dir/configs/`, and exits without starting any processes. Works the same for both local and SLURM runs (2026-02-26)
|
||||
- **Config output location**: Resolved subconfigs are now always written to `output_dir/configs/` instead of `.pydantic_config/<uuid>/`. This applies to both local and SLURM entrypoints, and for both single-node and multi-node deployments (2026-02-26)
|
||||
- **SFT config filename**: The resolved SFT trainer config is now written as `sft.toml` instead of `trainer.toml` (2026-02-26)
|
||||
- **Inference entrypoint**: Moved from `prime_rl.inference.server` to `prime_rl.entrypoints.inference`. No change to CLI usage (`uv run inference`) (2026-02-26)
|
||||
- **`[slurm]` (inference)**: Added SLURM configuration to `InferenceConfig`. When present, `uv run inference` generates and submits an sbatch script instead of running locally. Each SLURM node runs an independent vLLM replica (no cross-node parallelism) (2026-02-26)
|
||||
- **`[deployment]` (inference)**: Added deployment configuration. `type = "single_node"` (default) with `gpus_per_node`. `type = "multi_node"` with `num_nodes` and `gpus_per_node` — requires `[slurm]` (2026-02-26)
|
||||
- **`inference.output_dir`**: Added directory for SLURM logs and generated scripts (default: `"outputs"`) (2026-02-26)
|
||||
- **`inference.dry_run`**: Added flag (default: `False`). When set, validates config, writes resolved config to `output_dir/configs/`, and exits without starting inference or submitting SLURM jobs (2026-02-26)
|
||||
- **`orchestrator.teacher_rollout_model`**: Added optional external rollout model configuration. When set, rollouts are generated from this endpoint/model instead of the student inference server. Accepts a `TeacherRolloutModelConfig` with `client` and `model` sub-fields, or `None` (default: `None`) (2026-02-26)
|
||||
- **`trainer.loss.type = "sft"`**: Added SFT loss variant. Set `trainer.loss.type = "sft"` to use masked negative log-likelihood loss instead of the default RL loss (2026-02-26)
|
||||
- **`trainer.loss.type = "custom"`**: Added custom loss variant. Set `trainer.loss.type = "custom"` with `import_path` (e.g. `"my_module.my_loss"`) and optional `kwargs` to use an external loss function (2026-02-26)
|
||||
- **`trainer.loss` (default loss)**: Made IPO (DPPO-Binary TV variant ([arxiv](https://arxiv.org/pdf/2602.04879)) + Kimi-K2.5 KL ([Kimi-K2.5](https://arxiv.org/pdf/2602.02276))) the default loss. Removed `ratio_type`, `token_mask_low`, `token_mask_high`, `sequence_clip_high`, `geo_mask_low`, `geo_mask_high`, `sequence_mask_low`, `sequence_mask_high`. Added `ipo_mask_low` (default: 0.2) and `ipo_mask_high` (default: 0.2) for token-level probability-difference masking. Changed `kl_tau` default from `0.0` to `1e-3`. (2026-03-02)
|
||||
- **Metrics logging overhaul**: All orchestrator metrics now follow a `{metric}/{scope}/{stat}` naming convention where scope is `all` (global) or an env name. Per-env breakdowns are always logged (previously only when >1 env). Key renames: `reward/mean` → `reward/all/mean`, `batch/solve_none` → `solve_none/all`, `val_reward/` → `val/reward/`, `metrics/{name}` → `metrics/{env}/{name}`, `stop_condition/{sc}` → `stop_condition/all/{sc}`, `error/mean` → `error/all/mean`. New per-env metrics: `solve_none/{env}`, `solve_all/{env}`, `effective_batch_size/{env}`, `stop_condition/{env}/generation_truncated`, `stop_condition/{env}/{sc}`, `error/{env}/mean`, plus per-env breakdowns for `seq_len`, `prefill_len`, `decode_len`, `is_truncated`, `samples_per_rollout`, `num_turns`, `generation_ms`, `scoring_ms`. Removed: `reward/std`, `reward/median`, per-error-type breakdown (`error/{error_type}`). Env name `"all"` is reserved and rejected at config validation. Env name validation now strips `@version` suffixes to match runtime behavior (e.g. `math@1.0` and `math@2.0` correctly detected as duplicates). Solve stats now use `example_id` grouping instead of index arithmetic (pre-existing bug fix). (2026-03-08)
|
||||
- **`wandb.shared`** (experimental): Added shared W&B mode that logs trainer and orchestrator metrics to a single W&B run instead of two separate runs. Uses `wandb.Settings(mode="shared")` (requires wandb SDK >= 0.19.9). Enabled by default on the RL entrypoint. Disable with `--wandb.shared False`. Run ID is communicated via `WANDB_SHARED_RUN_ID` env var; process role via `WANDB_SHARED_LABEL`. Non-primary processes retry `wandb.init` up to 30 times waiting for the primary to create the run. Works with multi-node SLURM. (2026-03-18)
|
||||
- **`wandb.id`**: Removed from `WandbConfig`. Run IDs are now managed internally via env vars for shared mode. (2026-03-18)
|
||||
- **`trainer.ckpt.skip_optimizer`**: Added flag to skip loading optimizer states when resuming training. When set, only the model weights are loaded from the checkpoint. (2026-03-24)
|
||||
+1
-1
@@ -111,7 +111,7 @@ RUN --mount=type=cache,target=/app/.cache/uv \
|
||||
&& \
|
||||
EXTRA_DISAGG_FLAG=""; if [ "$INCLUDE_DISAGG_EXTRAS" = "1" ]; then EXTRA_DISAGG_FLAG="--extra disagg"; fi \
|
||||
&& \
|
||||
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --extra gpt-oss --extra modelexpress $EXTRA_DISAGG_FLAG --group mamba-ssm --locked --no-dev
|
||||
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra gpt-oss --extra modelexpress $EXTRA_DISAGG_FLAG --group mamba-ssm --locked --no-dev
|
||||
|
||||
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
|
||||
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
|
||||
|
||||
@@ -111,6 +111,8 @@ source $HOME/.local/bin/env
|
||||
uv sync --all-extras
|
||||
```
|
||||
|
||||
> *NOTE*: Environments are opt-in uv workspace members — `uv sync --all-extras` does not install them. To train on them, install all with `uv sync --all-extras --all-packages`, or a subset with `uv sync --package prime-rl --package <env>`.
|
||||
|
||||
4.1. On aarch64 hosts: build flash-attn from source for your GPU
|
||||
|
||||
> *NOTE*: aarch64 has no prebuilt flash-attn wheel. This step compiles the CUDA extension for your local GPU (~20-30 minutes). Compute capability is auto-detected from `nvidia-smi`; override with `TORCH_CUDA_ARCH_LIST=9.0` (Hopper) / `10.0` (Blackwell) if needed.
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
max_steps = 10
|
||||
seq_len = 2048
|
||||
|
||||
[weight_broadcast]
|
||||
# TEMP: NCCL weight broadcast currently crashes the trainer on CI GPU runners
|
||||
# (trainer exits during NCCL init). Use filesystem transport until the NCCL
|
||||
# path is fixed. See CI RL integration test failures on main.
|
||||
type = "filesystem"
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[weight_broadcast]
|
||||
# TEMP: NCCL weight broadcast currently crashes the trainer on CI GPU runners
|
||||
# (trainer exits during NCCL init). Use filesystem transport until the NCCL
|
||||
# path is fixed. See CI RL integration test failures on main.
|
||||
type = "filesystem"
|
||||
|
||||
[ckpt]
|
||||
resume_step = 15
|
||||
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
max_steps = 15
|
||||
seq_len = 2048
|
||||
|
||||
[weight_broadcast]
|
||||
# TEMP: NCCL weight broadcast currently crashes the trainer on CI GPU runners
|
||||
# (trainer exits during NCCL init). Use filesystem transport until the NCCL
|
||||
# path is fixed. See CI RL integration test failures on main.
|
||||
type = "filesystem"
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[weight_broadcast]
|
||||
# TEMP: NCCL weight broadcast currently crashes the trainer on CI GPU runners
|
||||
# (trainer exits during NCCL init). Use filesystem transport until the NCCL
|
||||
# path is fixed. See CI RL integration test failures on main.
|
||||
type = "filesystem"
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
|
||||
@@ -8,3 +8,6 @@ gpu_memory_utilization = 0.7
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
max_model_len = 2048
|
||||
|
||||
[weight_broadcast]
|
||||
type = "filesystem"
|
||||
|
||||
|
||||
@@ -21,6 +21,9 @@ id = "reverse-text"
|
||||
interval = 10
|
||||
resume_step = -1
|
||||
|
||||
[weight_broadcast]
|
||||
type = "filesystem"
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -16,3 +16,6 @@ freq = 1
|
||||
|
||||
[model.compile]
|
||||
fullgraph = false
|
||||
|
||||
[weight_broadcast]
|
||||
type = "filesystem"
|
||||
|
||||
@@ -7,6 +7,12 @@
|
||||
max_steps = 15
|
||||
seq_len = 2048
|
||||
|
||||
[weight_broadcast]
|
||||
# TEMP: NCCL weight broadcast currently crashes the trainer on CI GPU runners
|
||||
# (trainer exits during NCCL init). Use filesystem transport until the NCCL
|
||||
# path is fixed. See CI RL integration test failures on main.
|
||||
type = "filesystem"
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
|
||||
@@ -7,6 +7,12 @@
|
||||
max_steps = 15
|
||||
seq_len = 2048
|
||||
|
||||
[weight_broadcast]
|
||||
# TEMP: NCCL weight broadcast currently crashes the trainer on CI GPU runners
|
||||
# (trainer exits during NCCL init). Use filesystem transport until the NCCL
|
||||
# path is fixed. See CI RL integration test failures on main.
|
||||
type = "filesystem"
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "color-codeword"
|
||||
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
|
||||
taskset = { id = "color-codeword-v1", images_per_turn = 1 }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[trainer]
|
||||
|
||||
@@ -14,9 +14,9 @@ max_inflight_rollouts = 512
|
||||
group_size = 8
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
name = "hendrycks-math"
|
||||
taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
@@ -41,7 +41,7 @@ max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "color-codeword"
|
||||
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
|
||||
taskset = { id = "color-codeword-v1", images_per_turn = 1 }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
# Default renderer (AutoRendererConfig) resolves Qwen3-VL-4B-Instruct from
|
||||
|
||||
@@ -36,7 +36,7 @@ max_completion_tokens = 768
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "alphabet-sort"
|
||||
taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, power_per_turn = false }
|
||||
taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[inference] # Default inference config
|
||||
|
||||
@@ -41,7 +41,7 @@ name = "qwen3"
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
# v1 general-agent solver taskset; the tool server is colocated in the harness's modal sandbox.
|
||||
taskset = { id = "general-agent-v1", tools = { colocated = true } }
|
||||
taskset = { id = "general-agent-v1", task = { tools = { colocated = true } } }
|
||||
harness = { id = "null", runtime = { type = "modal" } }
|
||||
|
||||
[inference]
|
||||
|
||||
@@ -16,7 +16,8 @@ rollouts_per_example = 4
|
||||
max_completion_tokens = 4096
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "general-agent-solver-rlm"
|
||||
taskset = { id = "general-agent-v1", task = { tools = { colocated = true } } }
|
||||
harness = { id = "null", runtime = { type = "modal" } }
|
||||
|
||||
[trainer]
|
||||
|
||||
|
||||
@@ -36,7 +36,8 @@ rollouts_per_example = 16
|
||||
max_off_policy_steps = 32
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "general-agent-solver-rlm"
|
||||
taskset = { id = "general-agent-v1", task = { tools = { colocated = true } } }
|
||||
harness = { id = "null", runtime = { type = "modal" } }
|
||||
|
||||
[orchestrator.train.env.args]
|
||||
min_tier = 1
|
||||
|
||||
@@ -32,7 +32,8 @@ rollouts_per_example = 8
|
||||
max_off_policy_steps = 32
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "general-agent-solver-rlm"
|
||||
taskset = { id = "general-agent-v1", task = { tools = { colocated = true } } }
|
||||
harness = { id = "null", runtime = { type = "modal" } }
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
# exp: GLM-4.5-Air (100B MoE) RL across our v1 SEARCH-domain envs — bring-your-own-search QA, run
|
||||
# through the rlm harness (its built-in `search` skill) on a prime sandbox. GRPO + linear length
|
||||
# penalty. 2 train + 4 infer nodes. Single run label (glm45air-search) for all envs.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-search"
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-search" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
|
||||
[wandb]
|
||||
project = "search-ablations"
|
||||
name = "glm45air-search"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 8
|
||||
cp_style = "ulysses"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
optim_cpu_offload = true
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_rollouts = 512
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.algo.length_penalty]
|
||||
type = "linear"
|
||||
num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.0
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
# --- Train: the search envs with usable training data (rlm `search` skill, prime sandbox) ---
|
||||
|
||||
# openseeker/redsearcher pre-plug a `reference` judge; declaring `judges` here replaces that
|
||||
# entry wholesale (keep `name`/`question_field`/`choices` in sync with the taskset defaults —
|
||||
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
|
||||
[[orchestrator.train.env]]
|
||||
name = "openseeker"
|
||||
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
|
||||
|
||||
[orchestrator.train.env.taskset]
|
||||
id = "openseeker-v1"
|
||||
|
||||
[[orchestrator.train.env.taskset.task.judges]]
|
||||
id = "reference"
|
||||
name = "correct"
|
||||
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
||||
question_field = "question"
|
||||
choices = ["A", "B"]
|
||||
|
||||
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
|
||||
# [[orchestrator.train.env.taskset.task.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "redsearcher"
|
||||
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
|
||||
|
||||
[orchestrator.train.env.taskset]
|
||||
id = "redsearcher-v1" # optional `difficulty` filter (easy/medium/hard)
|
||||
|
||||
[[orchestrator.train.env.taskset.task.judges]]
|
||||
id = "reference"
|
||||
name = "correct"
|
||||
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
||||
question_field = "question"
|
||||
choices = ["A", "B"]
|
||||
|
||||
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
|
||||
# [[orchestrator.train.env.taskset.task.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# --- Eval: BrowseComp held-out test, every 20 steps (incl. step 0) ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "browsecomp"
|
||||
num_examples = 500 # full set is 1266; cap eval at 500
|
||||
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.env.taskset]
|
||||
id = "browsecomp-v1"
|
||||
task = { judge = { model = "Qwen/Qwen3-235B-A22B-Instruct-2507" } }
|
||||
|
||||
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
|
||||
# [[orchestrator.eval.env.taskset.task.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
enable_return_routed_experts = true
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp.
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 131072
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
+15
-19
@@ -3,9 +3,9 @@
|
||||
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
|
||||
# a glm4_moe model, which supports routed_experts.
|
||||
#
|
||||
# GRPO uses the linear length penalty with the output-token, input-token, and turns coefficients all
|
||||
# set to 0.1. Each term is pass_rate-scaled and normalized by the group's own max before the GRPO
|
||||
# baseline subtraction.
|
||||
# GRPO uses the linear length penalty with the input-token and turns coefficients set to 0.1. Each
|
||||
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
|
||||
# subtraction.
|
||||
#
|
||||
# 2 train + 4 infer nodes. Trainer uses cp=8 (ulysses) plus
|
||||
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
|
||||
@@ -14,19 +14,18 @@
|
||||
# configs/debug/v1/scaleswe.toml + GLM-4.5-Air model settings from the int5 opencode configs.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 65536
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
|
||||
# slow/contended shared-FS caches and FS lock deadlocks.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/triton-cache-$USER-$SLURM_JOB_ID"
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-swe"
|
||||
project_dir = "."
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (label == SLURM job name).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "$SLURM_JOB_NAME" -y || true'
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
@@ -89,9 +88,9 @@ max_inflight_rollouts = 512
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
# Linear length penalty at coef 0.1 on all three terms (output tokens, input tokens, turns).
|
||||
[orchestrator.algo.length_penalty]
|
||||
num_output_tokens_weight = 0.1
|
||||
type = "linear"
|
||||
num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.1
|
||||
|
||||
@@ -101,8 +100,8 @@ thinking_retention = "all"
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "scaleswe"
|
||||
taskset = { id = "scaleswe-v1" }
|
||||
harness = { id = "rlm", runtime = { type = "prime", labels = ["glm45air-swe"] } }
|
||||
taskset = { id = "scaleswe-v1", use_prime_registry = true }
|
||||
harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
@@ -110,28 +109,25 @@ harness = { id = "rlm", runtime = { type = "prime", labels = ["glm45air-swe"] }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
skip_first_step = false
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "swebench-verified"
|
||||
taskset = { id = "swebench-verified-v1", use_prime_registry = true }
|
||||
harness = { id = "rlm", runtime = { type = "prime", labels = ["glm45air-swe"] } }
|
||||
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
enable_prefix_caching = true
|
||||
enable_return_routed_experts = true
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm_cache_$(whoami)"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/flashinfer-$(whoami)"
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 65536
|
||||
max_model_len = 131072
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
# exp: GLM-4.5-Air (100B MoE) RL across our v1 TERMINAL-domain envs — agentic shell/sandbox tasks
|
||||
# run through the rlm harness (ipython-only) on a prime sandbox. Each task ships its own Docker image
|
||||
# (NEEDS_CONTAINER) injected into the sandbox; grading is host-side inside the container. GRPO +
|
||||
# linear length penalty. 2 train + 4 infer nodes. Single run label (glm45air-terminal) for all envs.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-terminal"
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-terminal" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
|
||||
[wandb]
|
||||
project = "terminal-ablations"
|
||||
name = "glm45air-terminal"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 8
|
||||
cp_style = "ulysses"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
optim_cpu_offload = true
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_rollouts = 512
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.algo.length_penalty]
|
||||
type = "linear"
|
||||
num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.1
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
# --- Train: tmax (per-task Docker image in a prime sandbox, rlm ipython) ---
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "tmax"
|
||||
harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
|
||||
|
||||
[orchestrator.train.env.taskset]
|
||||
id = "tmax-v1"
|
||||
|
||||
# # Metric-only monitors (weight 0): rlm harness-mechanics + swe code-usage rubrics, judged by GLM-5.2.
|
||||
# [[orchestrator.train.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.train.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
# path = "deps/research-environments/rubrics/swe.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# --- Eval: swebench-verified (avg@1) + terminal-bench-2 (full, avg@4) every 20 steps, incl. step 0 ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "swebench-verified"
|
||||
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.env.taskset]
|
||||
id = "swebench-verified-v1"
|
||||
use_prime_registry = true
|
||||
|
||||
# [[orchestrator.eval.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.eval.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
# path = "deps/research-environments/rubrics/swe.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "terminal-bench-2"
|
||||
group_size = 4 # avg@4
|
||||
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.env.taskset]
|
||||
id = "terminal-bench-2-v1"
|
||||
|
||||
# [[orchestrator.eval.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.eval.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
# path = "deps/research-environments/rubrics/swe.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
enable_return_routed_experts = true
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp.
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 131072
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
@@ -1,4 +1,4 @@
|
||||
# GLM-5.2-FP8 16-node P/D, FULL STACK: mooncake + llm-d router, vLLM 0.23.
|
||||
# GLM-5.2-FP8 16-node P/D, FULL STACK: mooncake + llm-d router, vLLM 0.24.
|
||||
# Step 3 / goal target. Topology mirrors the proven original glm5.1_llmd_inference
|
||||
# (job 348 succeeded): 8 prefill nodes (4 replicas x 2) + 8 decode nodes (1 replica).
|
||||
#
|
||||
@@ -31,9 +31,9 @@ num_bytes = 1_000_000_000_000
|
||||
|
||||
[deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 8
|
||||
prefill_nodes_per_replica = 2
|
||||
num_prefill_replicas = 4
|
||||
num_decode_nodes = 8
|
||||
decode_nodes_per_replica = 8
|
||||
num_decode_replicas = 1
|
||||
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
|
||||
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
|
||||
|
||||
@@ -10,8 +10,8 @@ reasoning_parser = "glm45"
|
||||
|
||||
[deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 4
|
||||
num_decode_nodes = 2
|
||||
prefill_nodes_per_replica = 4
|
||||
decode_nodes_per_replica = 2
|
||||
gpus_per_node = 8
|
||||
|
||||
[slurm]
|
||||
|
||||
@@ -16,9 +16,9 @@ group_size = 16
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "gsm8k"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
taskset = { id = "gsm8k-v1", split = "train" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[trainer] # Default trainer config
|
||||
|
||||
|
||||
@@ -16,9 +16,9 @@ group_size = 16
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
taskset = { id = "math-env-v1", dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", task = { math_verify_timeout = 60 } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 10
|
||||
|
||||
@@ -5,7 +5,7 @@ seq_len = 2048
|
||||
|
||||
[slurm]
|
||||
job_name = "nemotron-4node"
|
||||
pre_run_command = "uv sync --all-extras --group mamba-ssm"
|
||||
pre_run_command = "uv sync --all-extras --all-packages --group mamba-ssm"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
@@ -51,9 +51,9 @@ group_size = 8
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
taskset = { id = "math-env-v1", dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", task = { math_verify_timeout = 60 } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 10
|
||||
|
||||
@@ -50,9 +50,9 @@ group_size = 16
|
||||
max_completion_tokens = 4096
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
taskset = { id = "math-env-v1", dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", task = { math_verify_timeout = 60 } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 10
|
||||
|
||||
@@ -23,7 +23,7 @@ batch_size = 128
|
||||
group_size = 8
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/wordle"
|
||||
id = "wordle"
|
||||
name = "wordle"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
|
||||
Vendored
+1
-1
Submodule deps/renderers updated: a5efbb97e4...5904fa24aa
Vendored
+1
-1
Submodule deps/research-environments updated: de32ad4af2...06232831fd
Vendored
+1
-1
Submodule deps/verifiers updated: 22d6333a00...31415cd32a
+1
-1
@@ -106,7 +106,7 @@ dropout = 0.0
|
||||
|
||||
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
|
||||
|
||||
LoRA is supported across SFT and RL. For RL, `weight_broadcast.type = "nccl"` is **not** supported with LoRA — use the default filesystem transport. To save the raw adapter alongside the merged HF weights:
|
||||
LoRA is supported across SFT and RL. For RL, NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. To save the raw adapter alongside the merged HF weights:
|
||||
|
||||
```toml
|
||||
[ckpt.weights]
|
||||
|
||||
+1
-1
@@ -157,7 +157,7 @@ At step $n = 1, 2, 3, \dots$:
|
||||
- **Trainer** produces policy $\pi_n$ with weights $\theta_n$ from rollouts $(x_n, y_n)$.
|
||||
- **Inference** produces rollouts $(x_n, y_n)$ from policy $\pi_{\max(0,\,n-1)}$.
|
||||
|
||||
Step indices are 0-indexed so the gap holds at startup — inference is exactly one step behind the trainer.
|
||||
Step indices are 1-indexed; policy versions are 0-indexed, with $\pi_0$ the base model. At step 1 inference samples from $\pi_0$.
|
||||
|
||||
## Loss
|
||||
|
||||
|
||||
@@ -151,10 +151,11 @@ Training environments are an array of tables — set one per env, optionally wit
|
||||
id = "math-env"
|
||||
name = "gsm8k"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
ratio = 3 # 75% of batches
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
ratio = 0.25 # 25% of batches; remaining 75% goes to math-env
|
||||
ratio = 1 # default — 25% of batches
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math-env"
|
||||
@@ -162,6 +163,8 @@ name = "gsm8k-eval"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
```
|
||||
|
||||
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
|
||||
|
||||
`args` is forwarded verbatim to the environment's `load_environment(**args)`.
|
||||
|
||||
The same `id` can appear multiple times across train and eval (or with different `args`) — useful for evaluating on a held-out split of the env you're training on, or comparing two configurations of the same env side by side. When `id` is reused, set a distinct `name` on each entry; `name` defaults to `id` and must be unique across all envs in the same group.
|
||||
@@ -215,7 +218,7 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
|
||||
|
||||
- [**Qwen 3 30B – A3B Math**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/qwen30b_math) — `Qwen3-30B-A3B` on hard math.
|
||||
- [**Qwen 3 30B – A3B SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/qwen30b_swe) — `Qwen3-30B-A3B` on hard SWE.
|
||||
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/Intellect-3.1) — reproduces our INTELLECT-3.1 training run.
|
||||
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/intellect-3.1) — reproduces our INTELLECT-3.1 training run.
|
||||
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/minimax_m2.5_swe) — `MiniMax-M2.5` on agentic SWE.
|
||||
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/glm5_pd_disag) — `GLM-5` with P/D disaggregation and FP8 inference.
|
||||
|
||||
|
||||
+9
-11
@@ -128,41 +128,39 @@ This configuration will run 2 vLLM processes, each with `data_parallel_size_loca
|
||||
|
||||
This is the most advanced deployment shape. It allows you to disaggregate the prefill and decode stages, with KV cache flowing between them. This is useful for large scale deployments, where there are high requirements on latency, such as agentic workflows spanning 100s of turns.
|
||||
|
||||
This deployment shape is defined by setting `inference.deployment.type = "disaggregated"` and `inference.deployment.num_prefill_nodes` and `inference.deployment.num_decode_nodes` to the number of nodes you want to run the prefill and decode stages on.
|
||||
This deployment shape is defined by setting `inference.deployment.type = "disaggregated"` and choosing how many nodes each prefill and decode replica spans.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 2
|
||||
num_decode_nodes = 2
|
||||
prefill_nodes_per_replica = 2
|
||||
decode_nodes_per_replica = 2
|
||||
```
|
||||
|
||||
Sometimes, you may want to run multiple independent vLLM instances within the prefill and decode node groups. You can do this by setting `inference.deployment.num_prefill_replicas` and `inference.deployment.num_decode_replicas` to the number of replicas you want to run.
|
||||
Sometimes, you may want to run multiple independent vLLM instances within the prefill and decode stages. You can do this by setting `inference.deployment.num_prefill_replicas` and `inference.deployment.num_decode_replicas` to the number of role replicas you want to run.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 2
|
||||
num_decode_nodes = 2
|
||||
|
||||
prefill_nodes_per_replica = 2
|
||||
num_prefill_replicas = 2
|
||||
decode_nodes_per_replica = 2
|
||||
num_decode_replicas = 1
|
||||
```
|
||||
|
||||
Now the total deployment will span 6 nodes - 2x2 for prefill and 1x2 for decode. 2 prefill replicas will run on 2 nodes each - total of 4 nodes for prefill. 1 decode replica will run on 2 nodes for decode.
|
||||
Now each prefill replica spans 2 nodes and each decode replica spans 2 nodes. With 2 prefill replicas and 1 decode replica, one inference island spans 6 nodes.
|
||||
|
||||
We also allow you to configure the total amount of inference replicas - this is useful if you'd like to multiply the above configuration by a factor of `k`, each running behind a separate `vllm-router` instance.
|
||||
For RL runs, the top-level deployment can multiply that whole inference island by setting `deployment.num_infer_replicas`. `deployment.num_infer_nodes` is inferred from the nested inference deployment when you omit it.
|
||||
|
||||
```toml
|
||||
[deployment] # this is a top-level RL deployment, not inference.deployment!!
|
||||
type = "multi_node"
|
||||
num_train_nodes = 4
|
||||
num_infer_nodes = 6 # this is per-replica
|
||||
|
||||
num_infer_replicas = 3
|
||||
```
|
||||
|
||||
This will run 3 inference replicas, each running on 6 nodes. Each replica will run on 2x2 nodes for prefill and 1x2 nodes for decode. The total deployment will span 18 nodes. This will also spin-up 3 separate `vllm-router` instances.
|
||||
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes and start 3 separate router instances.
|
||||
|
||||
|
||||
## Router
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ A `prime-rl` RL run is three cooperating processes:
|
||||
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
|
||||
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [training documentation](training.md).
|
||||
|
||||
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses the filesystem (or NCCL for synchronous setups). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
|
||||
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
|
||||
|
||||
## Installation
|
||||
|
||||
|
||||
+2
-2
@@ -179,7 +179,7 @@ The defaults already cover: fused LM head chunking (`1024`), `torch.compile` (fu
|
||||
|
||||
The `rl`, `sft`, and `inference` entrypoints all submit to SLURM when a `[slurm]` table is present — there's no separate entrypoint.
|
||||
|
||||
> **The prime-rl checkout and its `uv` venv must live on a shared filesystem** visible to every node. The generated sbatch script runs a single `uv sync --all-extras` on the batch node (not once per node), so all ranks share that one environment — a node-local venv would leave the other nodes stale.
|
||||
> **The prime-rl checkout and its `uv` venv must live on a shared filesystem** visible to every node. The generated sbatch script runs a single `uv sync --all-extras --all-packages` on the batch node (not once per node), so all ranks share that one environment — a node-local venv would leave the other nodes stale.
|
||||
|
||||
### Activation
|
||||
|
||||
@@ -208,7 +208,7 @@ uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes the sbatch script
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_nodes = 1 # optional when inference.deployment defines the node topology
|
||||
gpus_per_node = 8 # default
|
||||
nodes_per_fsdp_group = 1 # optional — controls FSDP island size
|
||||
```
|
||||
|
||||
+3
-1
@@ -226,7 +226,7 @@ uv run rl @ rl.toml --ckpt.interval 25 --ckpt.keep-interval 100 # …plus perma
|
||||
Re-run the same launch command and pass `--ckpt.resume-step <N>` (or `-1` for "latest"). Make sure `--max-steps` is at least the target final step, not the remaining delta:
|
||||
|
||||
```bash
|
||||
# First run: steps 0–10
|
||||
# First run: steps 1–10
|
||||
uv run rl @ rl.toml --max-steps 10 --ckpt
|
||||
|
||||
# Resume: continue to step 20
|
||||
@@ -307,6 +307,8 @@ uv run rl @ rl.toml --wandb \
|
||||
--no-trainer.wandb.log-extras.distributions
|
||||
```
|
||||
|
||||
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, W&B mode **auto-creates an `overview` saved view** on the first run into a project — curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
|
||||
|
||||
### Platform Monitoring
|
||||
|
||||
Register a run on the Prime Intellect platform (Prime Lab) and stream training metrics, samples, and distributions to the platform dashboard. Bare flag uses defaults:
|
||||
|
||||
@@ -32,7 +32,7 @@ group_size = 8
|
||||
max_completion_tokens = 768
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
id = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ You also need prime-rl cloned on your cluster into the shared filesystem.
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
### Install llm-d
|
||||
|
||||
@@ -19,15 +19,14 @@ quantize_in_weight_transfer = true
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 16
|
||||
num_infer_nodes = 16
|
||||
gpus_per_node = 8
|
||||
num_infer_replicas = 1
|
||||
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 8
|
||||
prefill_nodes_per_replica = 2
|
||||
num_prefill_replicas = 4
|
||||
num_decode_nodes = 8
|
||||
decode_nodes_per_replica = 8
|
||||
num_decode_replicas = 1
|
||||
# skip warmup for faster start in cost of some jit overhead early
|
||||
# ucx needs to be set else random segfaults, vllm can't autoset before importing for some reason
|
||||
|
||||
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
|
||||
|
||||
@@ -15,14 +15,13 @@ quantize_in_weight_transfer = true
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 16
|
||||
num_infer_nodes = 8
|
||||
gpus_per_node = 8
|
||||
num_infer_replicas = 2
|
||||
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 4
|
||||
num_decode_nodes = 4
|
||||
prefill_nodes_per_replica = 4
|
||||
decode_nodes_per_replica = 4
|
||||
|
||||
[slurm]
|
||||
job_name = "glm5-pd-disag"
|
||||
@@ -73,9 +72,9 @@ name = "zai-org/GLM-5-FP8"
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "mini-swe-agent-plus"
|
||||
name = "swe-bench-verified-quick"
|
||||
args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
|
||||
name = "swe-bench-verified"
|
||||
taskset = { id = "swebench-verified-v1" }
|
||||
harness = { id = "default", runtime = { type = "prime", labels = ["glm5-pd-disag", "swe-bench-verified"] } }
|
||||
|
||||
[[orchestrator.post_batch_filters]]
|
||||
type = "gibberish"
|
||||
|
||||
@@ -17,16 +17,17 @@ group_size = 8
|
||||
seq_len = 8192
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env" # included in lock file
|
||||
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
name = "hendrycks-math"
|
||||
taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "primeintellect/aime2024"
|
||||
name = "aime2024"
|
||||
taskset = { id = "aime24-v1" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
group_size = 32
|
||||
|
||||
[trainer.model]
|
||||
|
||||
@@ -15,7 +15,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
|
||||
@@ -48,34 +48,34 @@ batch_size = 2048
|
||||
oversampling_factor = 2
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "mini-swe-agent-plus"
|
||||
name = "swe"
|
||||
ratio = 0.3
|
||||
args = { max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
|
||||
taskset = { id = "r2e-gym-v1" }
|
||||
harness = { id = "default", runtime = { type = "prime", labels = ["intellect-3.1", "swe"] } }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "deepdive"
|
||||
name = "deepdive"
|
||||
ratio = 0.2
|
||||
args = { finish_with_tool = true, open_max_workers = 128, cache_dir = "/tmp/i3_deepdive_cache_train" }
|
||||
taskset = { id = "deepdive-v1" }
|
||||
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], runtime = { type = "prime", labels = ["intellect-3.1", "deepdive"] } }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "math"
|
||||
ratio = 0.3
|
||||
args = { min_avg_reward = 0.0, max_avg_reward = 0.874}
|
||||
taskset = { id = "i3_math_v1" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "logic-env"
|
||||
name = "logic"
|
||||
ratio = 0.2
|
||||
args = { min_avg_reward = 0.0, max_avg_reward = 0.874 }
|
||||
taskset = { id = "i3_logic_v1", filter = { max = 0.874 } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "code-env"
|
||||
name = "code"
|
||||
ratio = 0.2
|
||||
args = { pool_size = 512 }
|
||||
taskset = { id = "i3_code_v1" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[[orchestrator.pre_batch_filters]]
|
||||
type = "zero_advantage"
|
||||
@@ -85,12 +85,14 @@ enforce = true
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "mini-swe-agent-plus"
|
||||
name = "swe-bench-verified-quick"
|
||||
args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
|
||||
name = "swe-bench-verified"
|
||||
taskset = { id = "swebench-verified-v1" }
|
||||
harness = { id = "default", runtime = { type = "prime", labels = ["intellect-3.1", "swe-bench-verified"] } }
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "aime2025"
|
||||
name = "aime2025"
|
||||
taskset = { id = "aime25-v1" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
|
||||
|
||||
@@ -50,17 +50,17 @@ max_off_policy_steps = 16
|
||||
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "mini-swe-agent-plus"
|
||||
name = "swe"
|
||||
args = { max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
|
||||
taskset = { id = "r2e-gym-v1" }
|
||||
harness = { id = "default", runtime = { type = "prime", labels = ["minimax-swe", "swe"] } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "mini-swe-agent-plus"
|
||||
name = "swe-bench-verified-quick"
|
||||
args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
|
||||
name = "swe-bench-verified"
|
||||
taskset = { id = "swebench-verified-v1" }
|
||||
harness = { id = "default", runtime = { type = "prime", labels = ["minimax-swe", "swe-bench-verified"] } }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
|
||||
@@ -42,9 +42,9 @@ group_size = 16
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
taskset = { id = "math-env-v1", dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", task = { math_verify_timeout = 60 } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 4
|
||||
|
||||
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
|
||||
|
||||
@@ -49,14 +49,17 @@ max_off_policy_steps = 8
|
||||
max_completion_tokens = 32768
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "math"
|
||||
taskset = { id = "i3_math_v1" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "aime2025"
|
||||
name = "aime2025"
|
||||
taskset = { id = "aime25-v1" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
|
||||
|
||||
@@ -47,17 +47,17 @@ oversampling_factor = 2
|
||||
max_off_policy_steps = 16
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "mini-swe-agent-plus"
|
||||
name = "swe"
|
||||
args = { max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
|
||||
taskset = { id = "r2e-gym-v1" }
|
||||
harness = { id = "default", runtime = { type = "prime", labels = ["qwen30b-swe", "swe"] } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "mini-swe-agent-plus"
|
||||
name = "swe-bench-verified-quick"
|
||||
args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
|
||||
name = "swe-bench-verified"
|
||||
taskset = { id = "swebench-verified-v1" }
|
||||
harness = { id = "default", runtime = { type = "prime", labels = ["qwen30b-swe", "swe-bench-verified"] } }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
@@ -45,7 +45,7 @@ type = "zero_advantage"
|
||||
enforce = true
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/wiki-search"
|
||||
id = "wiki-search"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ batch_size = 1024
|
||||
group_size = 16
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/wordle"
|
||||
id = "wordle"
|
||||
name = "wordle"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
|
||||
@@ -10,7 +10,7 @@ dependencies = [
|
||||
"renderers>=0.1.8.dev28",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"verifiers>=0.1.15.dev390",
|
||||
"verifiers>=0.2.0",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
|
||||
@@ -274,25 +274,22 @@ class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
|
||||
|
||||
# Disaggregated prefill/decode inference. Each replica is split into separate
|
||||
# prefill and decode node groups. Requires NIXL for KV transfer and a vllm-router
|
||||
# for request routing. Multi-replica: set ``num_prefill_replicas`` /
|
||||
# ``num_decode_replicas`` to run multiple independent vLLM instances within the
|
||||
# prefill / decode node groups. E.g. ``num_prefill_nodes=4, num_prefill_replicas=2``
|
||||
# creates two prefill vLLM instances each spanning 2 nodes (EP16 with 8 GPUs/node).
|
||||
# prefill and decode node groups. Requires NIXL for KV transfer and a router for
|
||||
# request routing.
|
||||
class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
type: Literal["disaggregated"] = "disaggregated"
|
||||
|
||||
num_prefill_nodes: int = Field(1, ge=1)
|
||||
"""Total prefill nodes."""
|
||||
prefill_nodes_per_replica: int = Field(1, ge=1)
|
||||
"""Nodes in each prefill vLLM instance."""
|
||||
|
||||
num_decode_nodes: int = Field(1, ge=1)
|
||||
"""Total decode nodes."""
|
||||
decode_nodes_per_replica: int = Field(1, ge=1)
|
||||
"""Nodes in each decode vLLM instance."""
|
||||
|
||||
num_prefill_replicas: int = Field(1, ge=1)
|
||||
"""Independent prefill vLLM instances. Must evenly divide ``num_prefill_nodes``."""
|
||||
"""Independent prefill vLLM instances."""
|
||||
|
||||
num_decode_replicas: int = Field(1, ge=1)
|
||||
"""Independent decode vLLM instances. Must evenly divide ``num_decode_nodes``."""
|
||||
"""Independent decode vLLM instances."""
|
||||
|
||||
prefill_port: int = 8100
|
||||
"""Port for prefill vLLM instances."""
|
||||
@@ -312,24 +309,18 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
decode_vllm_overrides: dict[str, Any] = {}
|
||||
"""Extra vLLM config options merged into --vllm-extra only for decode ranks (SLURM only)."""
|
||||
|
||||
@property
|
||||
def num_prefill_nodes(self) -> int:
|
||||
return self.prefill_nodes_per_replica * self.num_prefill_replicas
|
||||
|
||||
@property
|
||||
def num_decode_nodes(self) -> int:
|
||||
return self.decode_nodes_per_replica * self.num_decode_replicas
|
||||
|
||||
@property
|
||||
def num_nodes(self) -> int:
|
||||
return self.num_prefill_nodes + self.num_decode_nodes
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_replicas_divide_nodes(self):
|
||||
if self.num_prefill_nodes % self.num_prefill_replicas != 0:
|
||||
raise ValueError(
|
||||
f"num_prefill_replicas ({self.num_prefill_replicas}) must evenly divide "
|
||||
f"num_prefill_nodes ({self.num_prefill_nodes})"
|
||||
)
|
||||
if self.num_decode_nodes % self.num_decode_replicas != 0:
|
||||
raise ValueError(
|
||||
f"num_decode_replicas ({self.num_decode_replicas}) must evenly divide "
|
||||
f"num_decode_nodes ({self.num_decode_nodes})"
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
InferenceDeploymentConfig: TypeAlias = Annotated[
|
||||
SingleNodeInferenceDeploymentConfig | MultiNodeInferenceDeploymentConfig | DisaggregatedInferenceDeploymentConfig,
|
||||
@@ -416,6 +407,9 @@ class InferenceConfig(BaseConfig):
|
||||
enable_fp32_lm_head: bool = True
|
||||
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
|
||||
|
||||
enable_fp32_router_logits: bool = True
|
||||
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x) by setting ``out_dtype=float32`` on the gate: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented as a monkey-patch over vLLM's DeepseekV2MoE, activated by setting ``additional_config["fp32_router_logits"] = True`` on the vLLM config."""
|
||||
|
||||
vllm_extra: dict[str, Any] = {}
|
||||
"""Extra arguments forwarded to vLLM. Applied as attributes on the vLLM namespace after config translation."""
|
||||
|
||||
@@ -608,6 +602,10 @@ class InferenceConfig(BaseConfig):
|
||||
existing = getattr(namespace, "additional_config", None) or {}
|
||||
existing["fp32_lm_head"] = True
|
||||
rsetattr(namespace, "additional_config", existing)
|
||||
if self.enable_fp32_router_logits:
|
||||
existing = getattr(namespace, "additional_config", None) or {}
|
||||
existing["fp32_router_logits"] = True
|
||||
rsetattr(namespace, "additional_config", existing)
|
||||
|
||||
# Remove chat_template if not set (vLLM doesn't accept None)
|
||||
if namespace.chat_template is None:
|
||||
|
||||
@@ -50,7 +50,7 @@ class ModelConfig(BaseModelConfig):
|
||||
|
||||
|
||||
class TrainSamplingConfig(BaseConfig):
|
||||
temperature: float = Field(1.0, ge=0)
|
||||
temperature: float = Field(1.0, ge=0, le=2.0)
|
||||
"""Sampling temperature."""
|
||||
|
||||
max_completion_tokens: int | None = Field(
|
||||
@@ -92,7 +92,7 @@ class TrainSamplingConfig(BaseConfig):
|
||||
|
||||
|
||||
class EvalSamplingConfig(BaseConfig):
|
||||
temperature: float | None = Field(None, ge=0)
|
||||
temperature: float | None = Field(None, ge=0, le=2.0)
|
||||
"""Sampling temperature. None defers to the inference server default."""
|
||||
|
||||
top_p: float | None = None
|
||||
@@ -157,8 +157,8 @@ class EnvConfig(vf.EnvServerConfig):
|
||||
address: str | None = None
|
||||
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to this server instead of spawning one; when None, a subprocess env server is spawned automatically. The ``pool`` sizes the spawned server."""
|
||||
|
||||
ratio: float | None = Field(None, gt=0)
|
||||
"""Sampling weight for this environment in the buffer. When None for all envs, samples uniformly across all available problems. When set, must be set on all envs — values are relative weights normalized to probabilities (e.g. [1, 1] and [0.5, 0.5] are equivalent)."""
|
||||
ratio: float = Field(1.0, gt=0)
|
||||
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
@@ -268,15 +268,6 @@ class TrainConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_env_ratios(self):
|
||||
ratios = [env.ratio for env in self.env]
|
||||
if all(r is None for r in ratios):
|
||||
return self
|
||||
if any(r is None for r in ratios):
|
||||
raise ValueError("Either all envs must have a ratio or none of them. Got a mix of set and unset ratios.")
|
||||
return self
|
||||
|
||||
|
||||
class EvalConfig(BaseConfig):
|
||||
env: list[EvalEnvConfig] = Field(default_factory=list)
|
||||
|
||||
@@ -111,7 +111,7 @@ class SharedModelConfig(BaseConfig):
|
||||
|
||||
|
||||
class SharedWeightBroadcastConfig(BaseConfig):
|
||||
type: Literal["nccl", "filesystem"] = "filesystem"
|
||||
type: Literal["nccl", "filesystem"] = "nccl"
|
||||
"""Weight broadcast transport."""
|
||||
|
||||
port: int = 29501
|
||||
@@ -155,8 +155,8 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
num_train_nodes: int
|
||||
"""Training nodes."""
|
||||
|
||||
num_infer_nodes: int = Field(ge=0)
|
||||
"""Inference nodes per replica. Set to 0 to skip inference and orchestrator (requires fake data)."""
|
||||
num_infer_nodes: int | None = Field(None, ge=0)
|
||||
"""Inference nodes per replica. If unset, inferred from ``inference.deployment``. Set to 0 to skip inference and orchestrator (requires fake data)."""
|
||||
|
||||
num_infer_replicas: int = Field(1, ge=1)
|
||||
"""Independent inference replicas. Total inference nodes = ``num_infer_nodes * num_infer_replicas``."""
|
||||
@@ -167,9 +167,13 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
orchestrator_on_inference: bool = False
|
||||
"""Run the orchestrator on the last inference node instead of trainer rank 0 (frees host RAM on the trainer node)."""
|
||||
|
||||
@property
|
||||
def infer_nodes_per_replica(self) -> int:
|
||||
return self.num_infer_nodes or 0
|
||||
|
||||
@property
|
||||
def total_infer_nodes(self) -> int:
|
||||
return self.num_infer_nodes * self.num_infer_replicas
|
||||
return self.infer_nodes_per_replica * self.num_infer_replicas
|
||||
|
||||
|
||||
DeploymentConfig: TypeAlias = Annotated[
|
||||
@@ -232,19 +236,47 @@ class RLConfig(BaseConfig):
|
||||
|
||||
### Validate configs (e.g. raise for unsupported (combinations of) configs)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_infer_nodes(self):
|
||||
if self.deployment.type != "multi_node":
|
||||
return self
|
||||
|
||||
if self.inference is None:
|
||||
inferred_nodes = 0
|
||||
elif self.inference.deployment.type == "multi_node":
|
||||
inferred_nodes = self.inference.deployment.num_nodes
|
||||
elif self.inference.deployment.type == "disaggregated":
|
||||
inferred_nodes = self.inference.deployment.num_nodes
|
||||
else:
|
||||
inferred_nodes = 1
|
||||
|
||||
if self.deployment.num_infer_nodes is None:
|
||||
self.deployment.num_infer_nodes = inferred_nodes
|
||||
elif (
|
||||
self.inference is not None
|
||||
and self.inference.deployment.type == "multi_node"
|
||||
and self.deployment.num_infer_nodes != inferred_nodes
|
||||
):
|
||||
raise ValueError(
|
||||
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal "
|
||||
f"inference.deployment.num_nodes ({inferred_nodes}) for multi-node inference."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_deployment(self):
|
||||
if self.deployment.type == "multi_node":
|
||||
if self.slurm is None:
|
||||
raise ValueError("Must use SLURM for multi-node deployment.")
|
||||
if self.deployment.num_infer_nodes > 0 and not self.inference:
|
||||
num_infer_nodes = self.deployment.infer_nodes_per_replica
|
||||
if num_infer_nodes > 0 and not self.inference:
|
||||
raise ValueError("Must configure inference when using multi-node deployment with inference nodes.")
|
||||
if self.deployment.num_infer_nodes == 0 and self.inference:
|
||||
if num_infer_nodes == 0 and self.inference:
|
||||
raise ValueError(
|
||||
"Cannot configure inference with num_infer_nodes = 0. "
|
||||
"Either set num_infer_nodes > 0 or remove the inference config."
|
||||
)
|
||||
if self.deployment.num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
|
||||
if num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
|
||||
raise ValueError(
|
||||
"Must use fake data (trainer.data.fake or bench = true) when num_infer_nodes = 0, "
|
||||
"since no orchestrator or inference server will be running."
|
||||
@@ -304,29 +336,46 @@ class RLConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_weight_broadcast(self):
|
||||
"""Auto-setup shared weight broadcast config for trainer, orchestrator, and inference."""
|
||||
if self.weight_broadcast is not None:
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
|
||||
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
inference_world_size=inference_world_size,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
inference_world_size=inference_world_size,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
elif self.weight_broadcast.type == "filesystem":
|
||||
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
|
||||
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
|
||||
if self.inference is not None:
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
"""Auto-setup shared weight broadcast config for trainer, orchestrator, and inference.
|
||||
|
||||
Defaults to NCCL broadcast when no ``weight_broadcast`` is configured. Falls back to
|
||||
filesystem when LoRA is enabled (not yet supported with NCCL) or when no inference
|
||||
server is configured (NCCL requires a running inference pool).
|
||||
"""
|
||||
if self.weight_broadcast is None:
|
||||
if self.trainer.model.lora is not None or self.inference is None:
|
||||
self.weight_broadcast = SharedWeightBroadcastConfig(type="filesystem")
|
||||
else:
|
||||
self.weight_broadcast = SharedWeightBroadcastConfig()
|
||||
if self.weight_broadcast.type == "nccl" and self.trainer.model.lora is not None:
|
||||
# LoRA adapters are transferred via the filesystem (loaded from disk by the inference
|
||||
# servers); NCCL broadcast only writes a STABLE marker, so LoRA over NCCL cannot transfer
|
||||
# an adapter and would hang/fail on the startup weight sync.
|
||||
raise ValueError(
|
||||
"LoRA training is not yet supported with NCCL weight broadcast. "
|
||||
"Set weight_broadcast.type = 'filesystem'."
|
||||
)
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
|
||||
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
inference_world_size=inference_world_size,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
inference_world_size=inference_world_size,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
elif self.weight_broadcast.type == "filesystem":
|
||||
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
|
||||
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
|
||||
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)
|
||||
|
||||
@@ -531,7 +580,7 @@ class RLConfig(BaseConfig):
|
||||
)
|
||||
|
||||
inferred_dp_local = self.deployment.gpus_per_node // inference_tp
|
||||
total_infer_gpus = self.deployment.num_infer_nodes * self.deployment.gpus_per_node
|
||||
total_infer_gpus = self.deployment.infer_nodes_per_replica * self.deployment.gpus_per_node
|
||||
expected_global_world_size = self.inference.parallel.dp * inference_tp
|
||||
if expected_global_world_size != total_infer_gpus:
|
||||
raise ValueError(
|
||||
@@ -593,12 +642,11 @@ class RLConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
infer_deploy = self.inference.deployment
|
||||
expected_infer_nodes = infer_deploy.num_prefill_nodes + infer_deploy.num_decode_nodes
|
||||
if self.deployment.num_infer_nodes != expected_infer_nodes:
|
||||
expected_infer_nodes = infer_deploy.num_nodes
|
||||
if self.deployment.infer_nodes_per_replica != expected_infer_nodes:
|
||||
raise ValueError(
|
||||
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal "
|
||||
f"inference.deployment.num_prefill_nodes ({infer_deploy.num_prefill_nodes}) + "
|
||||
f"inference.deployment.num_decode_nodes ({infer_deploy.num_decode_nodes}) = {expected_infer_nodes}"
|
||||
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal the derived "
|
||||
f"disaggregated inference nodes per replica ({expected_infer_nodes})."
|
||||
)
|
||||
|
||||
total_infer_gpus = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
|
||||
|
||||
@@ -58,6 +58,9 @@ class SlurmConfig(BaseConfig):
|
||||
cleanup_grace_period: int = Field(3600, ge=0)
|
||||
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
|
||||
|
||||
shared_fs: bool = True
|
||||
"""Whether the project filesystem (including the venv) is shared across nodes (e.g. NFS). When True, a single ``uv sync`` on the batch node suffices. Set to False when the venv is node-local (e.g. ``UV_PROJECT_ENVIRONMENT`` on ``/tmp``) so ``uv sync`` runs on every node via srun."""
|
||||
|
||||
@property
|
||||
def template_vars(self) -> dict:
|
||||
"""Common template variables for all SLURM templates."""
|
||||
@@ -71,6 +74,7 @@ class SlurmConfig(BaseConfig):
|
||||
"time": self.time,
|
||||
"pre_run_command": self.pre_run_command,
|
||||
"cleanup_grace_period": self.cleanup_grace_period,
|
||||
"shared_fs": self.shared_fs,
|
||||
}
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -117,6 +117,9 @@ class DebugModelConfig(BaseConfig):
|
||||
|
||||
|
||||
class ModelConfig(BaseModelConfig):
|
||||
conversion_dir: Path | None = None
|
||||
"""Directory for the auto-converted weights (written to a `prime`/`hf` subdirectory). If not set, we write into the model snapshot directory."""
|
||||
|
||||
seq_len: int = 2048
|
||||
"""Sequence length the model is trained on."""
|
||||
|
||||
@@ -171,6 +174,9 @@ class ModelConfig(BaseModelConfig):
|
||||
reduce_dtype: Literal["bfloat16", "float32"] = "float32"
|
||||
"""dtype for gradient/parameter reductions."""
|
||||
|
||||
moe_router_dtype: Literal["bfloat16", "float32"] = "float32"
|
||||
"""Compute dtype for MoE router gates. ``float32`` (default) keeps router gate weights in fp32 through forward and backward (exempt from FSDP bf16 parameter casting) and computes the gate GEMM and routing logits in fp32, matching models trained with fp32 routing (e.g. GLM-5.x via Megatron's ``--moe-router-dtype fp32``). ``bfloat16`` computes the gate GEMM in the model compute dtype. Router score functions (sigmoid/softmax) run in fp32 regardless. Only affects the custom MoE implementation; a no-op for non-MoE and HF-impl models."""
|
||||
|
||||
moe_use_grouped_mm: bool = True
|
||||
"""Use grouped mm for MoE layers. Requires compute capability ≥ 9.0."""
|
||||
|
||||
@@ -649,7 +655,7 @@ class TrainerConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_broadcast(self):
|
||||
if self.model.lora is not None and self.weight_broadcast.type == "nccl":
|
||||
# TODO: Support this
|
||||
# TODO: Support NCCL broadcast with LoRA
|
||||
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
|
||||
return self
|
||||
|
||||
|
||||
@@ -1,10 +1,45 @@
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_config import BaseConfig as BaseConfig # noqa: F401
|
||||
from pydantic_config import cli # noqa: F401
|
||||
|
||||
|
||||
def to_toml_dict(config: BaseModel, exclude: set[str] | None = None) -> dict:
|
||||
"""Dump a config to a TOML-serializable dict.
|
||||
|
||||
TOML cannot represent null, so None fields left at their default are dropped
|
||||
(they re-resolve identically on re-parse) while explicitly-set None fields
|
||||
are encoded as the string ``"None"``, which ``BaseConfig`` converts back to
|
||||
``None``. Dropping those too would silently revert explicit None overrides
|
||||
(e.g. ``--trainer.model.compile None``) to their non-None defaults when the
|
||||
written config is re-parsed.
|
||||
"""
|
||||
return _encode_model(config, config.model_dump(exclude=exclude, mode="json"))
|
||||
|
||||
|
||||
def _encode_model(model: BaseModel, dumped: dict) -> dict:
|
||||
encoded = {}
|
||||
for name, value in dumped.items():
|
||||
if value is None:
|
||||
if name in model.model_fields_set:
|
||||
encoded[name] = "None"
|
||||
continue
|
||||
encoded[name] = _encode_value(getattr(model, name), value)
|
||||
return encoded
|
||||
|
||||
|
||||
def _encode_value(attr: Any, value: Any) -> Any:
|
||||
if isinstance(attr, BaseModel) and isinstance(value, dict):
|
||||
return _encode_model(attr, value)
|
||||
if isinstance(value, list) and isinstance(attr, (list, tuple)):
|
||||
return [_encode_value(a, v) for a, v in zip(attr, value)]
|
||||
if isinstance(value, dict) and isinstance(attr, dict):
|
||||
return {k: _encode_value(a, v) for (k, v), a in zip(value.items(), attr.values())}
|
||||
return "None" if value is None else value
|
||||
|
||||
|
||||
def find_package_resource(subdir: str) -> Path | None:
|
||||
"""Find a directory contributed to the `prime_rl` namespace package by any installed wheel.
|
||||
|
||||
|
||||
+33
-141
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "prime-rl"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
description = "Async RL Training at Scale"
|
||||
readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
@@ -19,9 +19,10 @@ dependencies = [
|
||||
"torchaudio",
|
||||
"torchdata>=0.11.0",
|
||||
"transformers==5.6.2",
|
||||
"vllm>=0.23.0",
|
||||
"vllm>=0.24.0",
|
||||
"mooncake-transfer-engine>=0.3.10.post2",
|
||||
"wandb>=0.26.1",
|
||||
"wandb-workspaces>=0.4.3",
|
||||
"ring-flash-attn>=0.1.8",
|
||||
"prime>=0.6.4",
|
||||
"pyzmq>=27.1.0",
|
||||
@@ -33,7 +34,7 @@ dependencies = [
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
"torchtitan",
|
||||
"verifiers[harbor]>=0.1.15.dev411",
|
||||
"verifiers[harbor]>=0.2.0",
|
||||
"renderers",
|
||||
"dion",
|
||||
"tilelang>=0.1.8",
|
||||
@@ -54,7 +55,7 @@ orchestrator = "prime_rl.entrypoints.orchestrator:main"
|
||||
env-server = "prime_rl.orchestrator.env_server.env_server:main"
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
|
||||
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
|
||||
|
||||
[project.optional-dependencies]
|
||||
flash-attn = [
|
||||
@@ -65,78 +66,12 @@ flash-attn-3 = ["flash_attn_3"]
|
||||
flash-attn-cute = [
|
||||
"flash-attn-4",
|
||||
]
|
||||
envs = [
|
||||
"aime24-v1",
|
||||
"aime25-v1",
|
||||
"aime26-v1",
|
||||
"alphabet-sort",
|
||||
"alphabet-sort-v1",
|
||||
"apex-shortlist-v1",
|
||||
"browsecomp-v1",
|
||||
"code-golf-v1",
|
||||
"color-codeword-v1",
|
||||
"deepdive-v1",
|
||||
"deepwiki-v1",
|
||||
"forth-lang-v1",
|
||||
"general-agent",
|
||||
"general-agent-v1",
|
||||
"glossary-v1",
|
||||
"gpqa-v1",
|
||||
"graphwalks-v1",
|
||||
"gsm8k-v1",
|
||||
"i3-code-v1",
|
||||
"i3-science-v1",
|
||||
"ifbench-v1",
|
||||
"ifeval-v1",
|
||||
"lean-v1",
|
||||
"livecodebench-v1",
|
||||
"logic-env",
|
||||
"longcot-mini-v1",
|
||||
"longcot-v1",
|
||||
"longpdfs-v1",
|
||||
"math-env",
|
||||
"math-env-v1",
|
||||
"math-python",
|
||||
"math500-v1",
|
||||
"mmlu-pro-v1",
|
||||
"mrcr-v2-v1",
|
||||
"oolong-pairs-v1",
|
||||
"oolong-real-v1",
|
||||
"oolong-synth-v1",
|
||||
"openseeker-v1",
|
||||
"openthoughts-tblite-v1",
|
||||
"papersearchqa-v1",
|
||||
"patterned-needle-in-haystack-v1",
|
||||
"prolog-v1",
|
||||
"r2e-gym-v1",
|
||||
"redsearcher-v1",
|
||||
"reverse-text",
|
||||
"reverse-text-v1",
|
||||
"rlm-search",
|
||||
"scaleswe-v1",
|
||||
"simpleqa-v1",
|
||||
"simpleqa-verified-v1",
|
||||
"swebench-pro-v1",
|
||||
"swebench-verified-v1",
|
||||
"swelego-v1",
|
||||
"tau2-bench-v1",
|
||||
"terminal-bench-2-v1",
|
||||
"unscramble-v1",
|
||||
"uuid-ctf-v1",
|
||||
"verbatim-copy-v1",
|
||||
"wideseek-v1",
|
||||
"wiki-search",
|
||||
"wiki-search-v1",
|
||||
"wikispeedia-v1",
|
||||
"wordle",
|
||||
"wordle-v1",
|
||||
]
|
||||
disagg = [
|
||||
"deep-ep ; platform_machine == 'x86_64'",
|
||||
"deep-gemm ; platform_machine == 'x86_64'",
|
||||
"deep-gemm",
|
||||
"nixl",
|
||||
"nixl-cu12 ; platform_machine == 'x86_64'",
|
||||
"vllm-router ; platform_machine == 'x86_64'",
|
||||
"vllm-router",
|
||||
]
|
||||
gpt-oss = [
|
||||
"kernels",
|
||||
@@ -190,6 +125,21 @@ override-dependencies = [
|
||||
"openenv-core",
|
||||
]
|
||||
|
||||
# Environment packages (research-environments + verifiers) are auto-discovered as
|
||||
# workspace members, so new envs need no per-package registration. Install them
|
||||
# with `uv sync --all-packages`.
|
||||
[tool.uv.workspace]
|
||||
members = [
|
||||
"deps/research-environments/environments/*/*",
|
||||
"deps/verifiers/environments/*",
|
||||
]
|
||||
# tau2-synth-v1 and tau3-bench-v1 pin `tau2` forks/revs that conflict with the
|
||||
# canonical tau2-bench-v1; a workspace shares one lock, so these can't coexist.
|
||||
exclude = [
|
||||
"deps/research-environments/environments/tool_use/tau2_synth_v1",
|
||||
"deps/research-environments/environments/tool_use/tau3_bench_v1",
|
||||
]
|
||||
|
||||
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
|
||||
# compatible with protobuf 6. prime-sandboxes requires protobuf>=6.31.1; keep
|
||||
# this capped to the validated protobuf major.
|
||||
@@ -239,83 +189,25 @@ prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
|
||||
verifiers = { path = "deps/verifiers", editable = true }
|
||||
renderers = { path = "deps/renderers", editable = true }
|
||||
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
|
||||
aime24-v1 = { path = "deps/research-environments/environments/aime24_v1", editable = true }
|
||||
aime25-v1 = { path = "deps/research-environments/environments/aime25_v1", editable = true }
|
||||
aime26-v1 = { path = "deps/research-environments/environments/aime26_v1", editable = true }
|
||||
alphabet-sort = { path = "deps/verifiers/environments/alphabet_sort", editable = true }
|
||||
alphabet-sort-v1 = { path = "deps/verifiers/environments/alphabet_sort_v1", editable = true }
|
||||
apex-shortlist-v1 = { path = "deps/research-environments/environments/apex_shortlist_v1", editable = true }
|
||||
browsecomp-v1 = { path = "deps/research-environments/environments/browsecomp_v1", editable = true }
|
||||
code-golf-v1 = { path = "deps/verifiers/environments/code_golf_v1", editable = true }
|
||||
color-codeword-v1 = { path = "deps/verifiers/environments/color_codeword_v1", editable = true }
|
||||
deepdive-v1 = { path = "deps/research-environments/environments/deepdive_v1", editable = true }
|
||||
deepwiki-v1 = { path = "deps/verifiers/environments/deepwiki_v1", editable = true }
|
||||
forth-lang-v1 = { path = "deps/research-environments/environments/forth_lang_v1", editable = true }
|
||||
general-agent = { path = "deps/research-environments/environments/general_agent", editable = true }
|
||||
general-agent-v1 = { path = "deps/research-environments/environments/general_agent_v1", editable = true }
|
||||
glossary-v1 = { path = "deps/verifiers/environments/glossary_v1", editable = true }
|
||||
gpqa-v1 = { path = "deps/research-environments/environments/gpqa_v1", editable = true }
|
||||
graphwalks-v1 = { path = "deps/research-environments/environments/graphwalks_v1", editable = true }
|
||||
gsm8k-v1 = { path = "deps/verifiers/environments/gsm8k_v1", editable = true }
|
||||
i3-code-v1 = { path = "deps/research-environments/environments/i3_code_v1", editable = true }
|
||||
i3-science-v1 = { path = "deps/research-environments/environments/i3_science_v1", editable = true }
|
||||
ifbench-v1 = { path = "deps/research-environments/environments/ifbench_v1", editable = true }
|
||||
ifeval-v1 = { path = "deps/research-environments/environments/ifeval_v1", editable = true }
|
||||
lean-v1 = { path = "deps/research-environments/environments/lean_v1", editable = true }
|
||||
livecodebench-v1 = { path = "deps/research-environments/environments/livecodebench_v1", editable = true }
|
||||
logic-env = { path = "deps/research-environments/environments/logic_env", editable = true }
|
||||
longcot-mini-v1 = { path = "deps/research-environments/environments/longcot_mini_v1", editable = true }
|
||||
longcot-v1 = { path = "deps/research-environments/environments/longcot_v1", editable = true }
|
||||
longpdfs-v1 = { path = "deps/research-environments/environments/longpdfs_v1", editable = true }
|
||||
math-env = { path = "deps/research-environments/environments/math_env", editable = true }
|
||||
math-env-v1 = { path = "deps/research-environments/environments/math_env_v1", editable = true }
|
||||
math-python = { path = "deps/verifiers/environments/math_python", editable = true }
|
||||
math500-v1 = { path = "deps/research-environments/environments/math500_v1", editable = true }
|
||||
mmlu-pro-v1 = { path = "deps/research-environments/environments/mmlu_pro_v1", editable = true }
|
||||
mrcr-v2-v1 = { path = "deps/research-environments/environments/mrcr_v2_v1", editable = true }
|
||||
oolong-pairs-v1 = { path = "deps/research-environments/environments/oolong_pairs_v1", editable = true }
|
||||
oolong-real-v1 = { path = "deps/research-environments/environments/oolong_real_v1", editable = true }
|
||||
oolong-synth-v1 = { path = "deps/research-environments/environments/oolong_synth_v1", editable = true }
|
||||
openseeker-v1 = { path = "deps/research-environments/environments/openseeker_v1", editable = true }
|
||||
openthoughts-tblite-v1 = { path = "deps/research-environments/environments/openthoughts_tblite_v1", editable = true }
|
||||
papersearchqa-v1 = { path = "deps/research-environments/environments/papersearchqa_v1", editable = true }
|
||||
patterned-needle-in-haystack-v1 = { path = "deps/research-environments/environments/patterned_needle_in_haystack_v1", editable = true }
|
||||
prolog-v1 = { path = "deps/research-environments/environments/prolog_v1", editable = true }
|
||||
r2e-gym-v1 = { path = "deps/research-environments/environments/r2e_gym_v1", editable = true }
|
||||
redsearcher-v1 = { path = "deps/research-environments/environments/redsearcher_v1", editable = true }
|
||||
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
|
||||
reverse-text-v1 = { path = "deps/verifiers/environments/reverse_text_v1", editable = true }
|
||||
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
|
||||
scaleswe-v1 = { path = "deps/research-environments/environments/scaleswe_v1", editable = true }
|
||||
simpleqa-v1 = { path = "deps/research-environments/environments/simpleqa_v1", editable = true }
|
||||
simpleqa-verified-v1 = { path = "deps/research-environments/environments/simpleqa_verified_v1", editable = true }
|
||||
swebench-pro-v1 = { path = "deps/research-environments/environments/swebench_pro_v1", editable = true }
|
||||
swebench-verified-v1 = { path = "deps/research-environments/environments/swebench_verified_v1", editable = true }
|
||||
swelego-v1 = { path = "deps/research-environments/environments/swelego_v1", editable = true }
|
||||
tau2-bench-v1 = { path = "deps/research-environments/environments/tau2_bench_v1", editable = true }
|
||||
terminal-bench-2-v1 = { path = "deps/research-environments/environments/terminal_bench_2_v1", editable = true }
|
||||
unscramble-v1 = { path = "deps/research-environments/environments/unscramble_v1", editable = true }
|
||||
uuid-ctf-v1 = { path = "deps/research-environments/environments/uuid_ctf_v1", editable = true }
|
||||
verbatim-copy-v1 = { path = "deps/research-environments/environments/verbatim_copy_v1", editable = true }
|
||||
wideseek-v1 = { path = "deps/research-environments/environments/wideseek_v1", editable = true }
|
||||
wiki-search = { path = "deps/verifiers/environments/wiki_search", editable = true }
|
||||
wiki-search-v1 = { path = "deps/verifiers/environments/wiki_search_v1", editable = true }
|
||||
wikispeedia-v1 = { path = "deps/research-environments/environments/wikispeedia_v1", editable = true }
|
||||
wordle = { path = "deps/verifiers/environments/wordle", editable = true }
|
||||
wordle-v1 = { path = "deps/verifiers/environments/wordle_v1", editable = true }
|
||||
torch = { index = "pytorch-cu128" }
|
||||
torchvision = { index = "pytorch-cu128" }
|
||||
torchaudio = { index = "pytorch-cu128" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "23e4dfc" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
|
||||
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
vllm-router = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
nixl-cu12 = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
|
||||
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
|
||||
flash_attn_3 = { index = "pytorch-cu128-test" }
|
||||
|
||||
@@ -59,9 +59,9 @@ if [ -n "$PRIME_RL_REF" ]; then
|
||||
# startup. --inexact keeps the seeded venv's pre-built wheels
|
||||
# (flash-attn-3, mamba-ssm) in place; uv only rebuilds them if the
|
||||
# override's lockfile pins different versions.
|
||||
( cd "$DEST" && uv sync --inexact --no-dev \
|
||||
( cd "$DEST" && uv sync --inexact --no-dev --all-packages \
|
||||
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
|
||||
--extra envs --extra gpt-oss --extra modelexpress \
|
||||
--extra gpt-oss --extra modelexpress \
|
||||
--group mamba-ssm )
|
||||
export VIRTUAL_ENV="$DEST/.venv"
|
||||
export PATH="$DEST/.venv/bin:$PATH"
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Export a verifiers v1 eval run (traces.jsonl) as an SFT dataset for `uv run sft`.
|
||||
|
||||
Reads a finished run's saved traces and reshapes them into the dataset shape the SFT trainer
|
||||
consumes directly (see `prime_rl.trainer.sft.data`): a `messages` column (OpenAI chat wire
|
||||
shape) plus a `tools` column (the tools the model was shown, from `Trace.tools`,
|
||||
JSON-encoded — heterogeneous JSON-schema dicts don't fit a fixed Arrow schema). One row per
|
||||
branch: a linear rollout contributes one sample, a compacted/subagent rollout one per branch
|
||||
(one training sample is built per branch).
|
||||
|
||||
Selection: generation-errored traces (`stop_condition == "error"`) always drop — a broken
|
||||
transcript is not a sample. A scoring-only error keeps the generation outcome as its stop
|
||||
condition and a complete conversation, so it stays; its reward may be partial/zero, which
|
||||
`--min-reward` handles.
|
||||
|
||||
Usage (from the prime-rl repo):
|
||||
uv run python scripts/export_sft.py <run-dir> [--min-reward 1.0] [--drop-truncated]
|
||||
[-o OUT_DIR] [--push HF_REPO_ID]
|
||||
|
||||
Writes `<run-dir>/sft/train.parquet` by default — point the trainer at it with
|
||||
`--data.name <run-dir>/sft`. Requires a verifiers release carrying `Trace.tools`
|
||||
(PrimeIntellect-ai/verifiers#1963).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from datasets import Dataset
|
||||
from verifiers.v1 import Trace, WireTrace
|
||||
from verifiers.v1.dialects.chat import message_to_wire
|
||||
|
||||
|
||||
def sft_rows(trace: Trace) -> list[dict]:
|
||||
"""A trace's SFT rows — one per branch: the branch's conversation as OpenAI chat wire
|
||||
dicts plus the trace's advertised tools, JSON-encoded."""
|
||||
tools = json.dumps([t.model_dump(mode="json", exclude_none=True) for t in trace.tools or []])
|
||||
return [
|
||||
{
|
||||
"messages": [message_to_wire(m) for m in branch.messages],
|
||||
"tools": tools,
|
||||
}
|
||||
for branch in trace.branches
|
||||
if branch.messages
|
||||
]
|
||||
|
||||
|
||||
def keep(trace: Trace, min_reward: float | None, drop_truncated: bool) -> bool:
|
||||
"""Whether a trace is worth training on (see module docstring for the error semantics)."""
|
||||
if trace.stop_condition == "error":
|
||||
return False
|
||||
if drop_truncated and trace.is_truncated:
|
||||
return False
|
||||
return min_reward is None or trace.reward >= min_reward
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("run_dir", type=Path, help="the eval run dir (holds traces.jsonl)")
|
||||
parser.add_argument("--min-reward", type=float, default=None, help="keep traces with reward >= this")
|
||||
parser.add_argument("--drop-truncated", action="store_true", help="drop budget-cut traces")
|
||||
parser.add_argument("-o", "--output-dir", type=Path, default=None, help="default: <run-dir>/sft")
|
||||
parser.add_argument("--push", default=None, help="HF repo id to push to instead of writing parquet")
|
||||
args = parser.parse_args()
|
||||
|
||||
traces_path = args.run_dir / "traces.jsonl"
|
||||
if not traces_path.exists():
|
||||
raise SystemExit(f"no traces.jsonl in {args.run_dir}")
|
||||
|
||||
total, rows = 0, []
|
||||
with traces_path.open(encoding="utf-8") as f:
|
||||
for line in f:
|
||||
if not line.strip():
|
||||
continue
|
||||
total += 1
|
||||
trace = WireTrace.model_validate(json.loads(line))
|
||||
if keep(trace, args.min_reward, args.drop_truncated):
|
||||
rows.extend(sft_rows(trace))
|
||||
print(f"export-sft: {total} trace(s) -> {len(rows)} row(s)")
|
||||
if not rows:
|
||||
raise SystemExit("export-sft: no rows to export after selection")
|
||||
|
||||
dataset = Dataset.from_list(rows)
|
||||
if args.push:
|
||||
dataset.push_to_hub(args.push)
|
||||
print(f"export-sft: pushed to {args.push}")
|
||||
return
|
||||
out = args.output_dir or args.run_dir / "sft"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
dataset.to_parquet(str(out / "train.parquet"))
|
||||
print(f"export-sft: wrote {out / 'train.parquet'} -> train with --data.name {out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+6
-10
@@ -22,12 +22,14 @@ git submodule update --init --recursive
|
||||
## Sync
|
||||
|
||||
```bash
|
||||
uv sync # core only
|
||||
uv sync --group dev # + pytest, ruff, pre-commit
|
||||
uv sync --all-extras # recommended: envs, flash-attn, flash-attn-cute, etc.
|
||||
uv sync # core only
|
||||
uv sync --group dev # + pytest, ruff, pre-commit
|
||||
uv sync --all-extras # + extras (flash-attn, flash-attn-cute, …)
|
||||
uv sync --all-extras --all-packages # + all env packages (needed to train on them)
|
||||
uv sync --package prime-rl --package gsm8k-v1 # core + just one env
|
||||
```
|
||||
|
||||
The `envs` extra installs environments listed under `[project.optional-dependencies].envs`, resolved through `[tool.uv.sources]`. Adding a new env means adding its package name to `envs` and its editable source path to `[tool.uv.sources]`.
|
||||
Environment packages under `deps/research-environments/environments/*/*` and `deps/verifiers/environments/*` are uv **workspace members**, auto-discovered — adding a new env needs no `pyproject.toml` change. They are opt-in: a plain `uv sync` / `--all-extras` does not install them (and would remove them if already present — re-run with `--all-packages`, or `--inexact` to keep them). Install all with `--all-packages`, or a subset with repeated `--package <env>` (include `--package prime-rl` to keep the core). If two envs pin conflicting transitive versions (all members share one lock), add the loser to `[tool.uv.workspace].exclude`.
|
||||
|
||||
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
|
||||
|
||||
@@ -41,12 +43,6 @@ CUDA_HOME=/usr/local/cuda uv pip install mamba-ssm
|
||||
|
||||
Requires `nvcc`. Without `mamba-ssm`, NemotronH falls back to HF's pure-PyTorch SSD path, which computes softplus in bf16 and yields ~0.4 KL divergence vs vLLM. Do **not** install `causal-conv1d` unless your GPU arch matches the prebuilt kernels — the code falls back to `nn.Conv1d` when it's absent.
|
||||
|
||||
### FP8 inference (GLM-5-FP8, etc.)
|
||||
|
||||
```bash
|
||||
uv sync --group fp8-inference # installs the prebuilt deep-gemm wheel
|
||||
```
|
||||
|
||||
### Trainer DeepEP backend
|
||||
|
||||
`scripts/install_ep_kernels.sh` auto-detects the CUDA toolkit matching torch and the GPU arch, builds NVSHMEM + DeepEP from source, and skips if `deep_ep` already imports.
|
||||
|
||||
@@ -34,6 +34,8 @@ Default cadence: **1 hour** (researcher can override). At each check-in:
|
||||
**Notes**: anything unusual (errors, restarts, hangs). Omit if nothing notable.
|
||||
```
|
||||
|
||||
In W&B, each project auto-gets an **"overview" saved view** (train / eval / stability / performance sections) on its first run — use it for a quick check instead of the auto-generated default workspace.
|
||||
|
||||
### Restarting a run
|
||||
|
||||
**Never restart unless the researcher explicitly asked.** Confirm the exact restart command and the conditions that warrant one.
|
||||
@@ -56,7 +58,7 @@ After a restart, verify all processes are back up and progress resumed before th
|
||||
- `scripts/tmux.sh` launches the run with a `Launcher` window in the named tmux session. The Claude window receives the output dir and session name in its appended prompt — if either is missing, **ask** rather than guess.
|
||||
- `{output_dir}/configs/` — resolved TOMLs (`rl.toml` has the full picture).
|
||||
- `{output_dir}/logs/` — see below.
|
||||
- `{output_dir}/rollouts/step_N/` — saved rollouts.
|
||||
- `{output_dir}/rollouts/step_N/{train,eval}/` — saved rollout traces (see Traces below).
|
||||
|
||||
### Logs
|
||||
|
||||
@@ -128,21 +130,28 @@ curl -s http://localhost:8000/metrics | grep -E "num_requests|gpu_cache_usage"
|
||||
# vllm:num_requests_running, vllm:num_requests_waiting, vllm:gpu_cache_usage_perc (→1.0 = KV cache saturated)
|
||||
```
|
||||
|
||||
### Rollouts
|
||||
### Traces
|
||||
|
||||
```
|
||||
{output_dir}/rollouts/step_N/
|
||||
├── train_rollouts.jsonl # all train rollouts (vf.RolloutOutput, trajectory excluded)
|
||||
├── eval_rollouts.jsonl # only present when eval ran
|
||||
└── train_rollouts.bin # binary batch consumed by the trainer
|
||||
{output_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per rollout as it completes
|
||||
{output_dir}/rollouts/step_N/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
|
||||
```
|
||||
|
||||
JSONL files of `vf.Trace` records (training tensors excluded). `all` gets every completed
|
||||
rollout the moment it arrives — errored, filtered, and never-batched ones included — so it's
|
||||
crash-durable; `effective` gets the clean subset that went into the step's train batch (eval:
|
||||
the non-errored epoch cohort; multiple eval envs share the step file). Each record carries
|
||||
`kind`, `env_name`, `group_id`, `policy_version`, and `eval_step`, plus `runtime` (config +
|
||||
provisioned resource id, e.g. the sandbox id).
|
||||
|
||||
```bash
|
||||
wc -l {output_dir}/rollouts/step_42/train_rollouts.jsonl
|
||||
head -1 {output_dir}/rollouts/step_42/train_rollouts.jsonl | python -m json.tool
|
||||
jq '.reward' {output_dir}/rollouts/step_42/train_rollouts.jsonl
|
||||
wc -l {output_dir}/rollouts/step_42/train/{all,effective}/traces.jsonl
|
||||
jq '.rewards' {output_dir}/rollouts/step_42/train/effective/traces.jsonl
|
||||
jq 'select(.errors != []) | {id, env_name, runtime}' {output_dir}/rollouts/step_*/train/all/traces.jsonl
|
||||
```
|
||||
|
||||
The binary batches consumed by the trainer still live at `{output_dir}/rollouts/step_N/train_rollouts.bin`, next to the trace subtrees.
|
||||
|
||||
### Common failure modes
|
||||
|
||||
A few warnings are normal. Escalate when errors are persistent, growing, or hit a large fraction of rollouts.
|
||||
|
||||
@@ -37,9 +37,10 @@ uv run rl @ examples/reverse_text/rl.toml --dry-run
|
||||
- Environment packages: before launching a config with a non-core verifier env id,
|
||||
verify the package imports under `uv run` (for example
|
||||
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym_v1'))"`).
|
||||
If a local env exists under `deps/research-environments/environments/` but does not
|
||||
import, add it to the root `pyproject.toml` env extra, workspace members, and
|
||||
`[tool.uv.sources]`, then run `uv sync --all-extras`.
|
||||
If a local env exists under `deps/research-environments/environments/` or
|
||||
`deps/verifiers/environments/` but does not import, install the env workspace
|
||||
members with `uv sync --all-packages` (all) or `uv sync --package prime-rl
|
||||
--package <env>` (one) — they're auto-discovered, no `pyproject.toml` edit needed.
|
||||
|
||||
## `sft` — SFT training
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ from typing import Any
|
||||
import tomli_w
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.config import cli, to_toml_dict
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir
|
||||
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, DEFAULT_INFERENCE_ENV_VARS, set_proc_title
|
||||
@@ -33,7 +33,7 @@ def write_config(config: InferenceConfig, output_dir: Path, exclude: set[str] |
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
config_path = output_dir / INFERENCE_TOML
|
||||
with open(config_path, "wb") as f:
|
||||
tomli_w.dump(config.model_dump(exclude=exclude, exclude_none=True, mode="json"), f)
|
||||
tomli_w.dump(to_toml_dict(config, exclude=exclude), f)
|
||||
return config_path
|
||||
|
||||
|
||||
@@ -76,6 +76,8 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
template_vars.update(
|
||||
num_prefill_nodes=config.deployment.num_prefill_nodes,
|
||||
num_decode_nodes=config.deployment.num_decode_nodes,
|
||||
prefill_nodes_per_replica=config.deployment.prefill_nodes_per_replica,
|
||||
decode_nodes_per_replica=config.deployment.decode_nodes_per_replica,
|
||||
num_prefill_replicas=config.deployment.num_prefill_replicas,
|
||||
num_decode_replicas=config.deployment.num_decode_replicas,
|
||||
prefill_port=config.deployment.prefill_port,
|
||||
|
||||
@@ -16,7 +16,7 @@ from prime_rl.configs.algorithm import FrozenModelConfig
|
||||
from prime_rl.configs.inference import VllmRouterConfig
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.entrypoints.inference import vllm_overrides_fragment
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.config import cli, to_toml_dict
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
@@ -56,9 +56,8 @@ def get_physical_gpu_ids() -> list[int]:
|
||||
def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None = None) -> None:
|
||||
"""Write resolved config to disk, excluding launcher-only fields."""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
config_dict = config.model_dump(exclude=exclude, exclude_none=True, mode="json")
|
||||
with open(output_dir / RL_TOML, "wb") as f:
|
||||
tomli_w.dump(config_dict, f)
|
||||
tomli_w.dump(to_toml_dict(config, exclude=exclude), f)
|
||||
|
||||
|
||||
def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
@@ -66,16 +65,16 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with open(output_dir / TRAINER_TOML, "wb") as f:
|
||||
tomli_w.dump(config.trainer.model_dump(exclude_none=True, mode="json"), f)
|
||||
tomli_w.dump(to_toml_dict(config.trainer), f)
|
||||
|
||||
with open(output_dir / ORCHESTRATOR_TOML, "wb") as f:
|
||||
tomli_w.dump(config.orchestrator.model_dump(exclude_none=True, mode="json"), f)
|
||||
tomli_w.dump(to_toml_dict(config.orchestrator), f)
|
||||
|
||||
if config.inference is not None:
|
||||
# Exclude launcher-only fields that are not needed by the vLLM server
|
||||
exclude_inference = {"deployment", "slurm", "output_dir", "dry_run"}
|
||||
with open(output_dir / INFERENCE_TOML, "wb") as f:
|
||||
tomli_w.dump(config.inference.model_dump(exclude=exclude_inference, exclude_none=True, mode="json"), f)
|
||||
tomli_w.dump(to_toml_dict(config.inference, exclude=exclude_inference), f)
|
||||
|
||||
|
||||
def rl_local(config: RLConfig):
|
||||
@@ -410,6 +409,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
num_infer_replicas=config.deployment.num_infer_replicas,
|
||||
num_prefill_nodes=infer_deploy.num_prefill_nodes,
|
||||
num_decode_nodes=infer_deploy.num_decode_nodes,
|
||||
prefill_nodes_per_replica=infer_deploy.prefill_nodes_per_replica,
|
||||
decode_nodes_per_replica=infer_deploy.decode_nodes_per_replica,
|
||||
num_prefill_replicas=infer_deploy.num_prefill_replicas,
|
||||
num_decode_replicas=infer_deploy.num_decode_replicas,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
@@ -441,11 +442,11 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
orchestrator_output_dir=config.orchestrator.output_dir,
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.total_infer_nodes,
|
||||
nodes_per_infer_replica=config.deployment.num_infer_nodes,
|
||||
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
|
||||
num_infer_replicas=config.deployment.num_infer_replicas,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router=config.inference.deployment.router if config.inference else VllmRouterConfig(),
|
||||
infer_nodes_per_replica=config.deployment.num_infer_nodes,
|
||||
infer_nodes_per_replica=config.deployment.infer_nodes_per_replica,
|
||||
backend_port=config.inference.deployment.backend_port if config.inference else 8100,
|
||||
inference_tp=config.inference.parallel.tp if config.inference else 1,
|
||||
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
|
||||
@@ -496,7 +497,7 @@ def rl_slurm(config: RLConfig):
|
||||
train_env_names = [env.resolved_name for env in config.orchestrator.train.env]
|
||||
eval_env_names = [env.resolved_name for env in config.orchestrator.eval.env] if config.orchestrator.eval else []
|
||||
|
||||
has_infer = config.deployment.num_infer_nodes > 0
|
||||
has_infer = config.deployment.infer_nodes_per_replica > 0
|
||||
log_message = format_log_message(
|
||||
log_dir=log_dir,
|
||||
trainer=True,
|
||||
|
||||
@@ -9,7 +9,7 @@ from threading import Event, Thread
|
||||
import tomli_w
|
||||
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.config import cli, to_toml_dict
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir, validate_output_dir
|
||||
from prime_rl.utils.process import (
|
||||
@@ -28,9 +28,8 @@ SFT_SBATCH = "sft.sbatch"
|
||||
def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None = None) -> None:
|
||||
"""Write resolved config to disk, excluding launcher-only fields."""
|
||||
config_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
config_dict = config.model_dump(exclude=exclude, exclude_none=True, mode="json")
|
||||
with open(config_path, "wb") as f:
|
||||
tomli_w.dump(config_dict, f)
|
||||
tomli_w.dump(to_toml_dict(config, exclude=exclude), f)
|
||||
|
||||
|
||||
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path) -> None:
|
||||
|
||||
+173
-226
@@ -3,20 +3,19 @@ import torch
|
||||
from prime_rl.inference.vllm.padded_input_scrub import monkey_patch_vllm_padded_input_scrub
|
||||
|
||||
|
||||
def transformers_v5_compat():
|
||||
"""vLLM general plugin: patch transformers v5 config attrs that vLLM still expects.
|
||||
def apply_shared_vllm_patches():
|
||||
"""vLLM general plugin: prime-rl patches that must run in every vLLM process.
|
||||
|
||||
Registered as a ``vllm.general_plugins`` entry-point so it runs automatically
|
||||
in every vLLM process, including spawned workers.
|
||||
in every vLLM process, including spawned workers. Note vLLM swallows plugin
|
||||
load failures (``load_plugins_by_group`` logs and continues), so a broken
|
||||
entry-point target silently skips ALL of these patches.
|
||||
"""
|
||||
from transformers import Qwen3VLMoeTextConfig
|
||||
|
||||
if not hasattr(Qwen3VLMoeTextConfig, "tie_word_embeddings"):
|
||||
Qwen3VLMoeTextConfig.tie_word_embeddings = False
|
||||
|
||||
_patch_lora_key_prefix()
|
||||
_patch_qwen35_moe_lora_format()
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
monkey_patch_qwen3_coder_param_newline_trim()
|
||||
monkey_patch_minimax_m2_think_end_passthrough()
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
monkey_patch_kv_xfer_finished_tolerate_freed()
|
||||
@@ -100,6 +99,91 @@ def monkey_patch_nano_v3_reasoning_parser():
|
||||
ReasoningParserManager.register_module("nano_v3", module=NanoV3ReasoningParser)
|
||||
|
||||
|
||||
def monkey_patch_qwen3_coder_param_newline_trim():
|
||||
"""Restore vLLM 0.23's single-newline trim for qwen3_coder tool parameters.
|
||||
|
||||
vLLM 0.24's parser engine applies a full ``.strip()`` to every parameter
|
||||
value in ``_qwen3_arg_converter``; 0.23's ``Qwen3CoderToolParser`` trimmed
|
||||
exactly one leading and one trailing newline. A full strip corrupts
|
||||
whitespace-significant string parameters (str_replace-style
|
||||
``old_str``/``new_str``, file content with an indented first line, values
|
||||
with intentional trailing newlines), silently changing tool execution and
|
||||
rewards for agentic runs. Copy of ``_qwen3_arg_converter`` with only the
|
||||
trim changed. Also covers ``nemotron_v3``, which reuses ``qwen3_config``.
|
||||
"""
|
||||
import json
|
||||
|
||||
from vllm.parser import qwen3
|
||||
|
||||
def _trim_one_newline(value: str) -> str:
|
||||
if value.startswith("\n"):
|
||||
value = value[1:]
|
||||
if value.endswith("\n"):
|
||||
value = value[:-1]
|
||||
return value
|
||||
|
||||
def _patched_arg_converter(raw_args: str, partial: bool) -> str:
|
||||
params: dict[str, object] = {}
|
||||
|
||||
for match in qwen3._PARAM_RE.finditer(raw_args):
|
||||
name = match.group(1)
|
||||
value = match.group(2)
|
||||
## START PATCHED CODE (upstream: value.strip())
|
||||
params[name] = _trim_one_newline(value)
|
||||
## END PATCHED CODE
|
||||
|
||||
if partial:
|
||||
remaining = qwen3._PARAM_RE.sub("", raw_args)
|
||||
m = qwen3._PARTIAL_PARAM_RE.search(remaining)
|
||||
if m:
|
||||
name = m.group(1)
|
||||
value = m.group(2)
|
||||
if name:
|
||||
## START PATCHED CODE (upstream: value.strip())
|
||||
params[name] = _trim_one_newline(value)
|
||||
## END PATCHED CODE
|
||||
|
||||
return json.dumps(params, ensure_ascii=False)
|
||||
|
||||
qwen3._qwen3_arg_converter = _patched_arg_converter
|
||||
# qwen3_config captures the converter when first built; drop any cached configs.
|
||||
qwen3.qwen3_config.cache_clear()
|
||||
|
||||
|
||||
def monkey_patch_minimax_m2_think_end_passthrough():
|
||||
"""Keep the literal ``</think>`` in MiniMax-M2 content on tool-calling turns.
|
||||
|
||||
prime-rl serves MiniMax-M2 with ``reasoning=minimax_m2_append_think``, which
|
||||
returns content as ``<think>`` + the full completion so think tags round-trip
|
||||
through multi-turn re-serialization. vLLM 0.24's minimax_m2 parser engine
|
||||
added a ``(CONTENT, THINK_END) -> no-events`` transition that silently
|
||||
swallows the ``</think>`` (0.23's regex tool parser passed it through
|
||||
untouched), and it also ``.strip()``s content whenever tool calls are
|
||||
present. Drop the transition — the engine emits unmatched terminals as plain
|
||||
state content — and disable the content strip.
|
||||
"""
|
||||
import dataclasses
|
||||
import functools
|
||||
|
||||
from vllm.parser import minimax_m2
|
||||
from vllm.parser.engine.parser_engine_config import ParserState
|
||||
|
||||
original_config = minimax_m2.minimax_m2_config
|
||||
|
||||
@functools.cache
|
||||
def _patched_config():
|
||||
config = original_config()
|
||||
transitions = dict(config.transitions)
|
||||
del transitions[(ParserState.CONTENT, "THINK_END")]
|
||||
return dataclasses.replace(
|
||||
config,
|
||||
transitions=transitions,
|
||||
strip_content_whitespace_with_tools=False,
|
||||
)
|
||||
|
||||
minimax_m2.minimax_m2_config = _patched_config
|
||||
|
||||
|
||||
def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
from vllm import envs
|
||||
from vllm.config.vllm import VllmConfig
|
||||
@@ -185,7 +269,7 @@ def monkey_patch_strip_routed_experts_from_chat():
|
||||
def _patch_qwen35_moe_lora_format():
|
||||
"""Force Qwen3.5-MoE onto vLLM's 2D per-expert LoRA format.
|
||||
|
||||
vLLM 0.23.0 defaults ``Qwen3_5MoeForConditionalGeneration.is_3d_moe_weight = True``,
|
||||
vLLM 0.24.0 still defaults ``Qwen3_5MoeForConditionalGeneration.is_3d_moe_weight = True``,
|
||||
which makes the LoRA loader expect 3D stacked-expert adapters
|
||||
(``base_layer.lora_{A,B}.weight`` / ``lora_{A,B}.weight``, experts folded into the
|
||||
rank dim; see ``_stack_moe_lora_weights``). Our trainer instead emits the 2D
|
||||
@@ -206,16 +290,23 @@ def _patch_qwen35_moe_lora_format():
|
||||
|
||||
|
||||
def _patch_lora_key_prefix():
|
||||
"""Patch vLLM's LoRA loading to handle keys without base_model.model. prefix.
|
||||
"""Accept both bare-suffix and fully-qualified expert module names in LoRA adapters.
|
||||
|
||||
This is a copy of the upstream patch: https://github.com/vllm-project/vllm/pull/38522
|
||||
We can remove this patch once that PR makes it into a release.
|
||||
Copy of vLLM 0.24.0's ``LoRAModel.from_local_checkpoint`` with one change: the
|
||||
``.experts`` branch of ``check_unexpected_modules`` accepts either the bare suffix
|
||||
(``down_proj``) or the qualified per-expert name (``experts.N.down_proj``), where
|
||||
upstream only accepts the qualified form. Our trainer's 2D per-expert adapters
|
||||
(Qwen3.5-MoE) carry names whose qualified form is not in the expected set while
|
||||
the bare suffix is; Qwen3-30B-A3B adapters go the other way. Upstream fix
|
||||
vllm-project/vllm#38522 was closed unmerged, so this stays.
|
||||
"""
|
||||
from vllm.lora.lora_model import (
|
||||
LoRAModel,
|
||||
MoEEPLoadSpec,
|
||||
PEFTHelper,
|
||||
TensorizerConfig,
|
||||
WeightsMapper,
|
||||
_is_remote_expert_key,
|
||||
get_lora_id,
|
||||
is_base_embedding_weights,
|
||||
os,
|
||||
@@ -236,6 +327,7 @@ def _patch_lora_key_prefix():
|
||||
weights_mapper: WeightsMapper | None = None,
|
||||
tensorizer_config_dict: dict | None = None,
|
||||
skip_prefixes: list[str] | None = None,
|
||||
moe_ep_spec: MoEEPLoadSpec | None = None,
|
||||
) -> "LoRAModel":
|
||||
"""Create a LoRAModel from a local checkpoint.
|
||||
|
||||
@@ -251,6 +343,11 @@ def _patch_lora_key_prefix():
|
||||
skip_prefixes: List of module name prefixes to skip during loading.
|
||||
Models can define this to skip modules not used in inference
|
||||
(e.g., MTP layers). Format: ["mtp."]
|
||||
moe_ep_spec: When 2D FusedMoE LoRA modules are present with
|
||||
expert parallelism enabled, the (ep_rank, local, global)
|
||||
slicing metadata shared across all MoE layers. Non-local
|
||||
expert weights are skipped at read time instead of being
|
||||
loaded and discarded later.
|
||||
|
||||
Returns:
|
||||
Loaded LoRA Model.
|
||||
@@ -275,22 +372,13 @@ def _patch_lora_key_prefix():
|
||||
continue
|
||||
module_name, _ = parse_fine_tuned_lora_name(lora_module, weights_mapper)
|
||||
# Case for expert lora weights.
|
||||
# For standard MoE models the name ends in "...experts",
|
||||
# so expert_idx+1 yields "experts" which is in
|
||||
# expected_lora_modules.
|
||||
# For Qwen 3.5 MoE (and similar models) the expert index
|
||||
# is embedded: "...experts.N.down_proj". Taking everything
|
||||
# after ".experts" gives "experts.N.down_proj" which is
|
||||
# never in the expected set even though "down_proj" is.
|
||||
# Qwen3-30B-A3B goes the other way: the expected set
|
||||
# contains the fully-qualified per-expert name
|
||||
# ("experts.N.down_proj") but not the bare suffix.
|
||||
# Accept either form.
|
||||
## START PATCHED CODE (upstream only accepts the qualified form)
|
||||
if ".experts" in module_name:
|
||||
expert_suffix = module_name.split(".")[-1]
|
||||
experts_qualified = "experts" + module_name.split(".experts", 1)[-1]
|
||||
if expert_suffix not in expected_lora_modules and experts_qualified not in expected_lora_modules:
|
||||
unexpected_modules.append(module_name)
|
||||
## END PATCHED CODE
|
||||
|
||||
elif module_name.rsplit(".", 1)[-1] not in expected_lora_modules:
|
||||
unexpected_modules.append(module_name)
|
||||
@@ -307,11 +395,15 @@ def _patch_lora_key_prefix():
|
||||
from tensorizer import TensorDeserializer
|
||||
|
||||
tensorizer_config = TensorizerConfig(**tensorizer_config_dict)
|
||||
lora_tensor_path = os.path.join(tensorizer_config.tensorizer_dir, "adapter_model.tensors")
|
||||
tensorizer_dir = tensorizer_config.tensorizer_dir
|
||||
if tensorizer_dir is None:
|
||||
raise ValueError("tensorizer_dir must be set in tensorizer config.")
|
||||
lora_tensor_path = os.path.join(tensorizer_dir, "adapter_model.tensors")
|
||||
tensorizer_args = tensorizer_config._construct_tensorizer_args()
|
||||
tensors = TensorDeserializer(
|
||||
lora_tensor_path,
|
||||
dtype=tensorizer_config.dtype,
|
||||
device=device,
|
||||
**tensorizer_args.deserialization_kwargs,
|
||||
)
|
||||
check_unexpected_modules(tensors)
|
||||
@@ -328,11 +420,18 @@ def _patch_lora_key_prefix():
|
||||
# Load tensors if there are only expected modules.
|
||||
check_unexpected_modules(f)
|
||||
for module in f.keys(): # noqa
|
||||
if moe_ep_spec is not None and _is_remote_expert_key(module, moe_ep_spec):
|
||||
continue
|
||||
tensors[module] = f.get_tensor(module)
|
||||
elif os.path.isfile(lora_bin_file_path) or os.path.isfile(lora_pt_file_path):
|
||||
lora_file_path = lora_bin_file_path if os.path.isfile(lora_bin_file_path) else lora_pt_file_path
|
||||
tensors = torch.load(lora_file_path, map_location=device, weights_only=True)
|
||||
check_unexpected_modules(tensors)
|
||||
if moe_ep_spec is not None:
|
||||
# `.bin`/`.pt` adapters can't be lazy-loaded, but pruning
|
||||
# the dict here still frees the non-local expert tensors
|
||||
# before the dtype cast / pin_memory work that follows.
|
||||
tensors = {k: v for k, v in tensors.items() if not _is_remote_expert_key(k, moe_ep_spec)}
|
||||
else:
|
||||
raise ValueError(f"{lora_dir} doesn't contain tensors")
|
||||
|
||||
@@ -350,177 +449,6 @@ def _patch_lora_key_prefix():
|
||||
LoRAModel.from_local_checkpoint = classmethod(_patched_from_local_checkpoint)
|
||||
|
||||
|
||||
# Monkeypatch LoadLoRAAdapter to allow loading the same adapter multiple times
|
||||
# TODO: may be removable if we pass load_inplace=True (supported since vLLM 0.18, PR #31326)
|
||||
def monkey_patch_load_lora_adapter():
|
||||
from http import HTTPStatus
|
||||
|
||||
from vllm.entrypoints.openai.engine.protocol import ErrorResponse
|
||||
from vllm.entrypoints.openai.models.serving import (
|
||||
OpenAIServingModels,
|
||||
create_error_response,
|
||||
)
|
||||
from vllm.entrypoints.serve.lora.protocol import LoadLoRAAdapterRequest
|
||||
from vllm.logger import init_logger
|
||||
from vllm.lora.request import LoRARequest
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
async def _patched_load_lora_adapter(
|
||||
self: OpenAIServingModels, request: LoadLoRAAdapterRequest, base_model_name: str | None = None
|
||||
) -> ErrorResponse | str:
|
||||
lora_name = request.lora_name
|
||||
|
||||
# Ensure atomicity based on the lora name
|
||||
async with self.lora_resolver_lock[lora_name]:
|
||||
lora_path = request.lora_path
|
||||
## START PATCHED CODE
|
||||
if lora_name in self.lora_requests:
|
||||
lora_request = self.lora_requests[lora_name]
|
||||
lora_request.lora_path = lora_path
|
||||
else:
|
||||
unique_id = self.lora_id_counter.inc(1)
|
||||
lora_request = LoRARequest(lora_name=lora_name, lora_int_id=unique_id, lora_path=lora_path)
|
||||
## END PATCHED CODE
|
||||
if base_model_name is not None and self.is_base_model(base_model_name):
|
||||
lora_request.base_model_name = base_model_name
|
||||
|
||||
# Validate that the adapter can be loaded into the engine
|
||||
# This will also preload it for incoming requests
|
||||
try:
|
||||
await self.engine_client.add_lora(lora_request)
|
||||
except Exception as e:
|
||||
error_type = "BadRequestError"
|
||||
status_code = HTTPStatus.BAD_REQUEST
|
||||
if "No adapter found" in str(e):
|
||||
error_type = "NotFoundError"
|
||||
status_code = HTTPStatus.NOT_FOUND
|
||||
|
||||
return create_error_response(message=str(e), err_type=error_type, status_code=status_code)
|
||||
|
||||
self.lora_requests[lora_name] = lora_request
|
||||
logger.info("Loaded new LoRA adapter: name '%s', path '%s'", lora_name, lora_path)
|
||||
return f"Success: LoRA adapter '{lora_name}' added successfully."
|
||||
|
||||
OpenAIServingModels.load_lora_adapter = _patched_load_lora_adapter
|
||||
|
||||
|
||||
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
|
||||
# TODO: may be removable if we pass load_inplace=True (supported since vLLM 0.18, PR #31326)
|
||||
def monkey_patch_LRUCacheWorkerLoRAManager():
|
||||
from vllm.lora.worker_manager import LoRARequest, LRUCacheLoRAModelManager, LRUCacheWorkerLoRAManager
|
||||
|
||||
# The dunder is intended. It's a private method that we're patching.
|
||||
def _patched__apply_adapters(self: LRUCacheWorkerLoRAManager, lora_requests: set[LoRARequest]) -> None:
|
||||
loras_map = {lora_request.lora_int_id: lora_request for lora_request in lora_requests if lora_request}
|
||||
if len(loras_map) > self._adapter_manager.lora_slots:
|
||||
raise RuntimeError(
|
||||
f"Number of requested LoRAs ({len(loras_map)}) is greater "
|
||||
"than the number of GPU LoRA slots "
|
||||
f"({self._adapter_manager.lora_slots})."
|
||||
)
|
||||
for lora in loras_map.values():
|
||||
## START PATCHED CODE
|
||||
self.add_adapter(lora, force_load=False)
|
||||
## END PATCHED CODE
|
||||
|
||||
def _patched_add_adapter(
|
||||
self: LRUCacheWorkerLoRAManager, lora_request: LoRARequest, force_load: bool = True
|
||||
) -> bool:
|
||||
# Note that this method is not thread-safe. It may be invoked multiple
|
||||
# times for the same adapter when using multiple API servers.
|
||||
# This is ok because it's currently only called from
|
||||
# the single-threaded core engine loop.
|
||||
|
||||
## START PATCHED CODE
|
||||
if lora_request.lora_int_id not in self.list_adapters() or force_load:
|
||||
## END PATCHED CODE
|
||||
# Load the new adapter first to ensure it is actually valid, before
|
||||
# evicting any existing adapters.
|
||||
# This may cause the # of loaded lora adapters to very temporarily
|
||||
# exceed `--max-cpu-loras`.
|
||||
lora = self._load_adapter(lora_request)
|
||||
## START PATCHED CODE
|
||||
self._adapter_manager.remove_adapter(lora.id)
|
||||
## END PATCHED CODE
|
||||
|
||||
# Loading succeeded, now check if we will exceed cache capacity and
|
||||
# evict if the oldest adapter if so
|
||||
if len(self._adapter_manager) + 1 > self._adapter_manager.capacity:
|
||||
assert isinstance(self._adapter_manager, LRUCacheLoRAModelManager)
|
||||
self._adapter_manager.remove_oldest_adapter()
|
||||
# Then add the new adapter to the cache
|
||||
loaded = self._adapter_manager.add_adapter(lora)
|
||||
else:
|
||||
# If the lora is already loaded, just touch it to
|
||||
# update its position in the caches
|
||||
loaded = self._adapter_manager.get_adapter(lora_request.lora_int_id) is not None
|
||||
self._adapter_manager.activate_adapter(lora_request.lora_int_id)
|
||||
return loaded
|
||||
|
||||
LRUCacheWorkerLoRAManager._apply_adapters = _patched__apply_adapters
|
||||
LRUCacheWorkerLoRAManager.add_adapter = _patched_add_adapter
|
||||
|
||||
|
||||
# Monkeypatch WorkerLoRAManager._load_adapter to skip the per-module regex
|
||||
# warning loop. On wide MoE models (Qwen3.5-35B-A3B) it spends minutes
|
||||
# recompiling regex patterns inside is_supported_lora_module — purely to emit
|
||||
# logger.warning_once about modules that will be ignored. Adapter validity is
|
||||
# already enforced by from_local_checkpoint, so dropping the warnings is safe.
|
||||
def monkey_patch_skip_lora_module_warnings():
|
||||
from vllm.exceptions import LoRAAdapterNotFoundError
|
||||
from vllm.lora.lora_model import LoRAModel
|
||||
from vllm.lora.peft_helper import PEFTHelper
|
||||
from vllm.lora.request import LoRARequest
|
||||
from vllm.lora.utils import get_adapter_absolute_path
|
||||
from vllm.lora.worker_manager import WorkerLoRAManager
|
||||
|
||||
def _patched_load_adapter(self: WorkerLoRAManager, lora_request: LoRARequest) -> LoRAModel:
|
||||
try:
|
||||
supported_lora_modules = self._adapter_manager.supported_lora_modules
|
||||
packed_modules_mapping = self._adapter_manager.packed_modules_mapping
|
||||
expected_lora_lst: list[str] = []
|
||||
for module in supported_lora_modules:
|
||||
if module in packed_modules_mapping:
|
||||
expected_lora_lst.extend(packed_modules_mapping[module])
|
||||
else:
|
||||
expected_lora_lst.append(module)
|
||||
if module == "experts":
|
||||
expected_lora_lst.append(module)
|
||||
expected_lora_modules = set(expected_lora_lst)
|
||||
lora_path = get_adapter_absolute_path(lora_request.lora_path)
|
||||
|
||||
peft_helper = PEFTHelper.from_local_dir(
|
||||
lora_path,
|
||||
self.max_position_embeddings,
|
||||
lora_request.tensorizer_config_dict,
|
||||
)
|
||||
peft_helper.validate_legal(self.lora_config)
|
||||
|
||||
model = self._adapter_manager.model
|
||||
hf_to_vllm_mapper = getattr(model, "hf_to_vllm_mapper", None)
|
||||
lora_skip_prefixes = getattr(model, "lora_skip_prefixes", None)
|
||||
|
||||
lora = self._lora_model_cls.from_local_checkpoint(
|
||||
lora_path,
|
||||
expected_lora_modules,
|
||||
peft_helper=peft_helper,
|
||||
lora_model_id=lora_request.lora_int_id,
|
||||
device="cpu",
|
||||
dtype=self.lora_config.lora_dtype,
|
||||
model_vocab_size=self.vocab_size,
|
||||
tensorizer_config_dict=lora_request.tensorizer_config_dict,
|
||||
weights_mapper=hf_to_vllm_mapper,
|
||||
skip_prefixes=lora_skip_prefixes,
|
||||
)
|
||||
except FileNotFoundError as e:
|
||||
raise LoRAAdapterNotFoundError(lora_request.lora_name, lora_request.lora_path) from e
|
||||
|
||||
return lora
|
||||
|
||||
WorkerLoRAManager._load_adapter = _patched_load_adapter
|
||||
|
||||
|
||||
# Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
def monkey_patch_tokenize_params_validation():
|
||||
"""
|
||||
@@ -608,7 +536,7 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
asserts inputs are float16/bfloat16. Qwen3 MoE doesn't have this
|
||||
problem because its gate uses the model dtype.
|
||||
Fix: rebuild the gate as GateLinear with a bf16 weight (out_dtype=float32
|
||||
keeps fp32 router logits). vLLM 0.23.0's own forward already drops the
|
||||
keeps fp32 router logits). vLLM 0.24.0's own forward already drops the
|
||||
float32 input cast. FusedMoE also has router_logits_dtype=float32, so
|
||||
routing precision is preserved inside the expert dispatch.
|
||||
|
||||
@@ -634,7 +562,7 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
_original_init(self, config, quant_config, prefix)
|
||||
from vllm.model_executor.layers.fused_moe.router.gate_linear import GateLinear
|
||||
|
||||
# vLLM 0.23.0 builds the gate as GateLinear with a float32 weight; rebuild it
|
||||
# vLLM 0.24.0 builds the gate as GateLinear with a float32 weight; rebuild it
|
||||
# with a bf16 weight (model dtype) so the LoRA Triton kernel's float16/bfloat16
|
||||
# assertion passes, keeping out_dtype=float32 so router logits stay fp32 (the
|
||||
# GateLinear bf16xbf16->fp32 path).
|
||||
@@ -646,19 +574,7 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
prefix=f"{prefix}.gate",
|
||||
)
|
||||
|
||||
def _patched_forward(self, hidden_states):
|
||||
from vllm.distributed import tensor_model_parallel_all_reduce
|
||||
|
||||
num_tokens, hidden_dim = hidden_states.shape
|
||||
hidden_states = hidden_states.view(-1, hidden_dim)
|
||||
router_logits, _ = self.gate(hidden_states)
|
||||
final_hidden_states = self.experts(hidden_states=hidden_states, router_logits=router_logits)
|
||||
if self.tp_size > 1:
|
||||
final_hidden_states = tensor_model_parallel_all_reduce(final_hidden_states)
|
||||
return final_hidden_states.view(num_tokens, hidden_dim)
|
||||
|
||||
MiniMaxM2MoE.__init__ = _patched_init
|
||||
MiniMaxM2MoE.forward = _patched_forward
|
||||
|
||||
# --- Adapter key remapping (only read by vLLM's LoRA adapter loader) ---
|
||||
MiniMaxM2ForCausalLM.hf_to_vllm_mapper = WeightsMapper(
|
||||
@@ -703,23 +619,15 @@ def monkey_patch_no_moe_lora():
|
||||
Otherwise, the oracle will always try to pick TritonExperts.
|
||||
For blackwells, we want TRTLLMFlashInfer.
|
||||
"""
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEConfig, logger
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEConfig
|
||||
|
||||
original_post_init = FusedMoEConfig.__post_init__
|
||||
|
||||
def _patched__post_init__(self: FusedMoEConfig):
|
||||
if self.dp_size > 1:
|
||||
logger.debug_once("Using FusedMoEConfig::max_num_tokens=%d", self.max_num_tokens)
|
||||
|
||||
assert self.max_num_tokens > 0
|
||||
|
||||
if self.router_logits_dtype is None:
|
||||
self.router_logits_dtype = self.in_dtype
|
||||
|
||||
if self.hidden_dim_unpadded is None:
|
||||
self.hidden_dim_unpadded = self.hidden_dim
|
||||
if self.intermediate_size_per_partition_unpadded is None:
|
||||
self.intermediate_size_per_partition_unpadded = self.intermediate_size_per_partition
|
||||
|
||||
# Disable LoRA for MoE layers
|
||||
original_post_init(self)
|
||||
# Disable LoRA for MoE layers. `is_lora_enabled` is only read later during
|
||||
# kernel selection (modular_kernel / unquantized oracle), never inside
|
||||
# `__post_init__`, so flipping it after the original runs is sufficient.
|
||||
self.is_lora_enabled = False
|
||||
|
||||
FusedMoEConfig.__post_init__ = _patched__post_init__
|
||||
@@ -787,12 +695,51 @@ def monkey_patch_fp32_lm_head():
|
||||
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
|
||||
|
||||
|
||||
def monkey_patch_fp32_router_logits():
|
||||
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x glm_moe_dsa).
|
||||
|
||||
vLLM's DeepseekV2MoE gate is a GateLinear with a bf16 weight and no out_dtype,
|
||||
so router logits are rounded to bf16 before expert scoring. GLM-5.x was trained
|
||||
with fp32 routing (Megatron ``--moe-router-dtype fp32``); upstream now runs its
|
||||
gate fully in fp32 (vllm-project/vllm#47410, not in the pinned release).
|
||||
Setting ``out_dtype=float32`` routes the gate through GateLinear's cuBLAS
|
||||
bf16xbf16->fp32 tier: same GEMM, but the fp32 accumulator is written out
|
||||
unrounded. Unlike the upstream PR, the gate weight stays bf16, so the LoRA
|
||||
Triton kernel dtype assert and the bf16 weight-broadcast path are unaffected.
|
||||
|
||||
Activated by ``additional_config["fp32_router_logits"] = True``; the launcher
|
||||
sets this when ``inference.enable_fp32_router_logits`` is set. The flag is read
|
||||
at module construction, where vLLM guarantees a ``set_current_vllm_config()``
|
||||
context. No-op if something else already set an out_dtype (e.g. the ROCm AITER
|
||||
branch, whose kernel wants matching dtypes).
|
||||
"""
|
||||
import torch
|
||||
from vllm.config import get_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.models.deepseek_v2 import DeepseekV2MoE
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_original_init = DeepseekV2MoE.__init__
|
||||
|
||||
def _patched_init(self, *args, **kwargs):
|
||||
_original_init(self, *args, **kwargs)
|
||||
additional_config = get_current_vllm_config().additional_config or {}
|
||||
if not additional_config.get("fp32_router_logits", False):
|
||||
return
|
||||
if self.gate.out_dtype is None:
|
||||
self.gate.set_out_dtype(torch.float32)
|
||||
|
||||
DeepseekV2MoE.__init__ = _patched_init
|
||||
logger.info("Installed fp32 router logits patch (self-gates on additional_config['fp32_router_logits']).")
|
||||
|
||||
|
||||
def monkey_patch_dp_coordinator_startup_timeout():
|
||||
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 30s.
|
||||
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 120s.
|
||||
|
||||
The coordinator child process is spawned on the DP-rank-0 API server while
|
||||
every engine-core rank on the node is importing and loading weights, so its
|
||||
own spawn-time re-import can take well over 30s under that CPU/IO
|
||||
own spawn-time re-import can exceed the hard-coded timeout under that CPU/IO
|
||||
contention (seen on multi-node disaggregated GLM-5.1 launches). Configurable
|
||||
via PRIME_DP_COORDINATOR_STARTUP_TIMEOUT (seconds, default 300).
|
||||
"""
|
||||
|
||||
@@ -10,7 +10,8 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
|
||||
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
|
||||
# Force the V1 GPU model runner. vLLM 0.23.0 routes dense Llama/Mistral/Qwen3 to the
|
||||
# Force the V1 GPU model runner. vLLM 0.24.0 routes Llama/Mistral/Qwen3 plus MoE archs
|
||||
# (DeepseekV2, Qwen2Moe, GraniteMoe; the 0.23 MoE/quantized guard was removed) to the
|
||||
# V2 runner, which has no `_preprocess` hook for our padded-input scrub (see
|
||||
# inference/vllm/padded_input_scrub.py) and doesn't zero the padded decode tail
|
||||
# itself; that stale tail poisons CUDA-graph replay as NaN logits (reproduced on
|
||||
@@ -19,6 +20,12 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# (the NIXL PD path rejects V2). setdefault so it stays overridable.
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
|
||||
|
||||
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
|
||||
# grammar-constrains generation (xgrammar structural tags) for tool_choice
|
||||
# "required"/named and strict tools — a sampling distribution the trainer never
|
||||
# sees. Keep it off so rollout logprobs stay faithful for importance ratios.
|
||||
os.environ.setdefault("VLLM_ENFORCE_STRICT_TOOL_CALLING", "0")
|
||||
|
||||
deep_gemm_enabled = "1" if config.use_deep_gemm else "0"
|
||||
os.environ["VLLM_USE_DEEP_GEMM"] = deep_gemm_enabled
|
||||
os.environ["VLLM_MOE_USE_DEEP_GEMM"] = deep_gemm_enabled
|
||||
|
||||
@@ -22,7 +22,6 @@ logger = get_logger()
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_dp_coordinator_startup_timeout,
|
||||
monkey_patch_harmony_stop_token_propagation,
|
||||
monkey_patch_load_lora_adapter,
|
||||
monkey_patch_nano_v3_reasoning_parser,
|
||||
monkey_patch_strip_routed_experts_from_chat,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
@@ -32,9 +31,6 @@ from prime_rl.inference.patches import (
|
||||
# NOTE: Fix harmony stop token propagation for GPT-OSS models
|
||||
# Upstream issue still open: https://github.com/vllm-project/vllm/issues/22519
|
||||
monkey_patch_harmony_stop_token_propagation()
|
||||
# NOTE: Monkeypatch LoadLoRAAdapter to allow loading the same adapter multiple times
|
||||
# May be removable if we pass load_inplace=True (supported since vLLM 0.18, PR #31326)
|
||||
monkey_patch_load_lora_adapter()
|
||||
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
# Still needed in vLLM 0.20 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
monkey_patch_tokenize_params_validation()
|
||||
@@ -50,7 +46,7 @@ monkey_patch_vllm_padded_input_scrub()
|
||||
# routed_experts from chat responses since the server-wide enable flag has no
|
||||
# per-request toggle.
|
||||
monkey_patch_strip_routed_experts_from_chat()
|
||||
# NOTE: vLLM hard-codes a 30s DP coordinator startup timeout, which the rank-0
|
||||
# NOTE: vLLM hard-codes a 120s DP coordinator startup timeout, which the rank-0
|
||||
# API server blows through when all engine-core ranks on the node are loading
|
||||
# weights concurrently (multi-node disaggregated deployments).
|
||||
monkey_patch_dp_coordinator_startup_timeout()
|
||||
@@ -97,9 +93,29 @@ async def update_weights(request: Request):
|
||||
|
||||
@router.post("/load_lora_adapter")
|
||||
async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: Request):
|
||||
"""Wrapper around vLLM's /v1/load_lora_adapter."""
|
||||
"""Wrapper around vLLM's /v1/load_lora_adapter.
|
||||
|
||||
prime-rl reloads a fixed-name adapter with fresh weights every step (the path
|
||||
changes per policy version; the name is constant, see orchestrator.lora_name).
|
||||
vLLM's native loader rejects a same-name reload unless ``load_inplace=True``,
|
||||
so we force it here — that makes the worker re-read the new weights during
|
||||
``add_lora``, reusing the existing ``lora_int_id``.
|
||||
|
||||
We then reset the stored request's flag back to ``False``. ``load_inplace`` is
|
||||
a sticky field on the ``LoRARequest`` that ``_maybe_get_adapters`` hands to
|
||||
every generation request; left ``True`` it would force a disk reload on each
|
||||
scheduler step. The orchestrator awaits this endpoint before dispatching
|
||||
rollouts for the new version, so the reset always lands before generation.
|
||||
The reset runs regardless of success/error: vLLM only stores the adapter on
|
||||
success today, but resetting whatever is stored keeps us correct even if a
|
||||
future version were to leave a ``load_inplace=True`` request behind on error.
|
||||
"""
|
||||
handler = models(raw_request)
|
||||
lora_request.load_inplace = True
|
||||
response = await handler.load_lora_adapter(lora_request)
|
||||
stored = handler.lora_requests.get(lora_request.lora_name)
|
||||
if stored is not None:
|
||||
stored.load_inplace = False
|
||||
if isinstance(response, ErrorResponse):
|
||||
return JSONResponse(content=response.model_dump(), status_code=response.error.code)
|
||||
return {"status": "ok"}
|
||||
|
||||
@@ -3,19 +3,13 @@ import os
|
||||
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_fp32_lm_head,
|
||||
monkey_patch_LRUCacheWorkerLoRAManager,
|
||||
monkey_patch_fp32_router_logits,
|
||||
monkey_patch_minimax_m2_for_lora,
|
||||
monkey_patch_no_moe_lora,
|
||||
monkey_patch_skip_lora_module_warnings,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
|
||||
monkey_patch_LRUCacheWorkerLoRAManager()
|
||||
# Skip the per-module regex warning loop in WorkerLoRAManager._load_adapter
|
||||
# (minutes-long stall on wide MoE models like Qwen3.5-35B-A3B)
|
||||
monkey_patch_skip_lora_module_warnings()
|
||||
# Monkeypatch MiniMaxM2 MoE gate dtype and adapter key mapping for LoRA compatibility
|
||||
monkey_patch_minimax_m2_for_lora()
|
||||
# Disable LoRA on MoE layers so vLLM picks better kernels (e.g. TRTLLMFlashInfer on Blackwell)
|
||||
@@ -27,3 +21,6 @@ else:
|
||||
|
||||
# Install fp32 lm_head patch; self-gates on additional_config["fp32_lm_head"] at call time
|
||||
monkey_patch_fp32_lm_head()
|
||||
|
||||
# Install fp32 router logits patch; self-gates on additional_config["fp32_router_logits"]
|
||||
monkey_patch_fp32_router_logits()
|
||||
|
||||
@@ -24,42 +24,6 @@ else:
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_nccl")
|
||||
|
||||
# NemotronH mixer.D is dropped by vLLM's layerwise online-reload path (left uninitialized).
|
||||
_RELOAD_CORRUPTED_SUFFIXES = (".mixer.D",)
|
||||
|
||||
|
||||
def _restore_reload_corrupted_params(model: Module, received: dict[str, torch.Tensor]) -> None:
|
||||
"""Work around a vLLM layerwise-reload bug for NemotronH (present through vLLM 0.23.0).
|
||||
|
||||
The online reload drops the weight load for every Mamba layer's ``mixer.D`` (the SSD skip
|
||||
connection), leaving it as uninitialized ``empty_strided`` memory -- it reads back as garbage
|
||||
(NaN/inf) and the logits go NaN after a weight update. Root cause: ``mixer.A`` is loaded with
|
||||
``composed_weight_loader`` (an extra in-place transform copy), so the reload element counter
|
||||
double-counts ``A`` and finalizes the layer before ``D`` (loaded last) is loaded. The received
|
||||
broadcast value is correct, so restore D from it via the param's own ``weight_loader``.
|
||||
|
||||
Fixed upstream by vllm-project/vllm#44814 (merged 2026-06-10) but NOT in the pinned 0.23.0
|
||||
release; remove this shim once we bump to a vLLM release that includes it.
|
||||
"""
|
||||
|
||||
def _layer_key(name: str) -> str:
|
||||
index = name.find("layers.")
|
||||
return name[index:] if index >= 0 else name
|
||||
|
||||
received_by_key = {_layer_key(name): tensor for name, tensor in received.items()}
|
||||
for name, param in model.named_parameters():
|
||||
if not name.endswith(_RELOAD_CORRUPTED_SUFFIXES):
|
||||
continue
|
||||
tensor = received_by_key.get(_layer_key(name))
|
||||
if tensor is None:
|
||||
continue
|
||||
tensor = tensor.to(device=param.device)
|
||||
weight_loader = getattr(param, "weight_loader", None)
|
||||
if weight_loader is not None:
|
||||
weight_loader(param, tensor)
|
||||
elif tensor.shape == param.shape:
|
||||
param.data.copy_(tensor.to(param.dtype))
|
||||
|
||||
|
||||
def receive_integer(communicator: PyNcclCommunicator) -> int:
|
||||
"""Receive an integer from the trainer master rank using NCCL communicator."""
|
||||
@@ -184,20 +148,9 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
update_mla_absorbed_weights(model)
|
||||
return
|
||||
|
||||
# vLLM's layerwise reload drops NemotronH mixer.D's weight load (see
|
||||
# _restore_reload_corrupted_params). Capture the correct received value to restore after.
|
||||
received_reload_fix: dict[str, torch.Tensor] = {}
|
||||
|
||||
def _capture_reload_fix(weights):
|
||||
for name, tensor in weights:
|
||||
if name.endswith(_RELOAD_CORRUPTED_SUFFIXES):
|
||||
received_reload_fix[name] = tensor.detach().to("cpu", copy=True)
|
||||
yield name, tensor
|
||||
|
||||
load_weights_checkpoint_layerwise(
|
||||
model,
|
||||
_capture_reload_fix(state_iter),
|
||||
state_iter,
|
||||
self.model_runner.model_config,
|
||||
self.vllm_config,
|
||||
)
|
||||
_restore_reload_corrupted_params(model, received_reload_fix)
|
||||
|
||||
@@ -5,6 +5,7 @@ from torch.nn import Module
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.reload import finalize_layerwise_reload, initialize_layerwise_reload
|
||||
from vllm.model_executor.model_loader.weight_utils import remap_moe_expert_weights
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_weight_transfer")
|
||||
|
||||
@@ -47,20 +48,20 @@ def _invert_logical_to_physical_map(logical_to_physical_map: torch.Tensor, num_p
|
||||
return physical_to_logical
|
||||
|
||||
|
||||
def _build_expert_source_indices(module) -> torch.Tensor | None:
|
||||
if module._expert_map is None:
|
||||
def _build_expert_source_indices(routed_experts, router) -> torch.Tensor | None:
|
||||
if routed_experts._expert_map is None:
|
||||
return None
|
||||
|
||||
physical_indices = torch.where(module._expert_map >= 0)[0]
|
||||
local_indices = module._expert_map[physical_indices]
|
||||
physical_indices = torch.where(routed_experts._expert_map >= 0)[0]
|
||||
local_indices = routed_experts._expert_map[physical_indices]
|
||||
physical_indices = physical_indices[local_indices.argsort()]
|
||||
|
||||
eplb_layer_state = getattr(module, "eplb_state", None)
|
||||
eplb_layer_state = getattr(router, "eplb_state", None)
|
||||
logical_to_physical_map = getattr(eplb_layer_state, "logical_to_physical_map", None)
|
||||
if logical_to_physical_map is None:
|
||||
return physical_indices
|
||||
|
||||
physical_to_logical = _invert_logical_to_physical_map(logical_to_physical_map, module.global_num_experts)
|
||||
physical_to_logical = _invert_logical_to_physical_map(logical_to_physical_map, routed_experts.global_num_experts)
|
||||
logical_indices = physical_to_logical[physical_indices.to(physical_to_logical.device)]
|
||||
if (logical_indices < 0).any():
|
||||
missing = physical_indices[(logical_indices < 0).to(physical_indices.device)].tolist()
|
||||
@@ -70,14 +71,23 @@ def _build_expert_source_indices(module) -> torch.Tensor | None:
|
||||
|
||||
|
||||
def build_expert_map(model: Module) -> dict[str, torch.Tensor]:
|
||||
"""Map FusedMoE module names to source expert indices local to this worker."""
|
||||
from vllm.model_executor.layers.fused_moe.layer import FusedMoE
|
||||
"""Map MoE module names to source expert indices local to this worker.
|
||||
|
||||
vLLM 0.24 turned ``FusedMoE`` into a factory returning a ``MoERunner`` and
|
||||
split the state that used to live on the ``FusedMoE`` module: the expert map
|
||||
(``_expert_map`` / ``global_num_experts``) now lives on
|
||||
``MoERunner.routed_experts`` (a ``RoutedExperts``), and the EPLB state on
|
||||
``MoERunner.router``. Keying by the ``MoERunner`` name prefix-matches the
|
||||
nested ``routed_experts.*`` weight params after ``load_weights_kernel``
|
||||
remaps incoming flat names via ``remap_moe_expert_weights``.
|
||||
"""
|
||||
from vllm.model_executor.layers.fused_moe import MoERunner
|
||||
|
||||
source_indices_by_module: dict[str, torch.Tensor] = {}
|
||||
for module_name, module in model.named_modules():
|
||||
if not isinstance(module, FusedMoE):
|
||||
if not isinstance(module, MoERunner):
|
||||
continue
|
||||
source_indices = _build_expert_source_indices(module)
|
||||
source_indices = _build_expert_source_indices(module.routed_experts, module.router)
|
||||
if source_indices is None:
|
||||
continue
|
||||
source_indices_by_module[module_name] = source_indices
|
||||
@@ -94,7 +104,10 @@ def load_weights_kernel(model: Module, state_iter: Generator[tuple[str, torch.Te
|
||||
skipped: list[str] = []
|
||||
shape_mismatches: list[str] = []
|
||||
|
||||
for name, tensor in state_iter:
|
||||
# The trainer emits pre-0.24 flat kernel names (``...experts.w13_weight``); since
|
||||
# vLLM 0.24 the expert params are nested (``...experts.routed_experts.w13_weight``).
|
||||
# ``remap_moe_expert_weights`` is upstream's compat shim for exactly this transition.
|
||||
for name, tensor in remap_moe_expert_weights(state_iter, params):
|
||||
if name not in params:
|
||||
skipped.append(name)
|
||||
continue
|
||||
|
||||
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Callable
|
||||
|
||||
from prime_rl.configs.algorithm import EchoAlgoConfig
|
||||
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
|
||||
from prime_rl.orchestrator.trajectories import iter_trainable_branches
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -55,7 +56,9 @@ class EchoAlgorithm(GRPOAlgorithm):
|
||||
(role tags, separators, tool-response wraps) is excluded. Nodes without
|
||||
attribution (the default renderer, or relay turns with no token ids)
|
||||
fall back to weighting the whole non-sampled span."""
|
||||
trainable_branches = [branch for branch in rollout.branches if any(branch.sampled_mask)]
|
||||
# Same branch selection as ``trace_to_samples``, so the zip with ``rollout.samples``
|
||||
# stays aligned when fork dedup drops a branch.
|
||||
trainable_branches = [branch for branch, _ in iter_trainable_branches(rollout)]
|
||||
filter_masks = self._filter_masks(rollout, trainable_branches) if self.filter_fn is not None else None
|
||||
for sample_idx, (sample, branch) in enumerate(zip(rollout.samples, trainable_branches)):
|
||||
weights = [0.0] * len(sample.token_ids)
|
||||
|
||||
@@ -53,11 +53,11 @@ class OPSDAlgorithm(Algorithm):
|
||||
def _demonstration(self, rollout: Rollout) -> str:
|
||||
demonstration = rollout.info.get(self.demo_key)
|
||||
if demonstration is None:
|
||||
demonstration = getattr(rollout.task, self.demo_key, None)
|
||||
demonstration = getattr(rollout.task.data, self.demo_key, None)
|
||||
if demonstration is None:
|
||||
raise ValueError(
|
||||
f"opsd requires '{self.demo_key}' in the trace info dict or on the task "
|
||||
f"(env '{rollout.env_name}', task {rollout.task.idx})."
|
||||
f"(env '{rollout.env_name}', task {rollout.task.data.idx})."
|
||||
)
|
||||
return demonstration
|
||||
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
from dataclasses import asdict
|
||||
from pathlib import Path
|
||||
@@ -27,8 +30,17 @@ class CheckpointManager:
|
||||
ckpt_path = self.get_ckpt_path(step)
|
||||
ckpt_path.mkdir(parents=True, exist_ok=True)
|
||||
start = time.perf_counter()
|
||||
with open(ckpt_path / "progress.pt", "wb") as f:
|
||||
torch.save({"progress": progress}, f)
|
||||
# Save to a temporary file and do an atomic rename, to avoid corrupting the last
|
||||
# file if the process gets killed while writing
|
||||
fd, tmp_name = tempfile.mkstemp(dir=ckpt_path, prefix="progress.pt.", suffix=".tmp")
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as f:
|
||||
torch.save({"progress": progress}, f)
|
||||
os.replace(tmp_name, ckpt_path / "progress.pt")
|
||||
except BaseException:
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(tmp_name)
|
||||
raise
|
||||
get_logger().debug(
|
||||
f"Orchestrator checkpoint saved to {ckpt_path} in {format_time(time.perf_counter() - start)}"
|
||||
)
|
||||
|
||||
@@ -506,7 +506,10 @@ class RolloutDispatcher:
|
||||
except Exception as exc:
|
||||
get_logger().warning(f"Rollout task failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
|
||||
task_idx = group.task_idx if group is not None else -1
|
||||
rollouts = [Rollout(task=vf.Task(idx=task_idx, prompt=None)) for _ in range(meta.rollout_count)]
|
||||
rollouts = [
|
||||
Rollout(task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)))
|
||||
for _ in range(meta.rollout_count)
|
||||
]
|
||||
for r in rollouts:
|
||||
r.capture_error(exc)
|
||||
is_synth_exception = True
|
||||
@@ -574,7 +577,7 @@ class RolloutDispatcher:
|
||||
for _, meta in claimed:
|
||||
for _ in range(meta.rollout_count):
|
||||
trace = Rollout(
|
||||
task=vf.Task(idx=task_idx, prompt=None),
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
|
||||
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
|
||||
stop_condition="error",
|
||||
)
|
||||
@@ -600,7 +603,7 @@ class RolloutDispatcher:
|
||||
unscheduled_cancelled = group.rollouts_to_schedule
|
||||
for _ in range(unscheduled_cancelled):
|
||||
trace = Rollout(
|
||||
task=vf.Task(idx=task_idx, prompt=None),
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
|
||||
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
|
||||
stop_condition="error",
|
||||
)
|
||||
|
||||
@@ -5,12 +5,12 @@ external one given by ``config.address``) and an ``EnvClient`` to drive it. The
|
||||
orchestrator never *runs* an environment: it asks the server for ``info``
|
||||
(``num_tasks`` + whether group scoring is needed), then runs rollouts purely by
|
||||
**task index**. The server returns a ``Trace`` (a plain ``model_dump`` — derived values are
|
||||
properties, not serialized) which we validate into a ``Trace[WireTask]`` — a real ``vf.Trace``
|
||||
properties, not serialized) which we validate into a ``Trace[WireTaskData]`` — a real ``vf.Trace``
|
||||
(never a loose dict) whose task keeps the env's
|
||||
task-specific fields as extras (``WireTask`` allows them). The orchestrator never imports the
|
||||
task-specific fields as extras (``WireTaskData`` allows them). The orchestrator never imports the
|
||||
env package: the env's *type* and *runtime* both live only in the server, and the orchestrator
|
||||
drives it purely by task index. (Nothing here reads typed env task fields — only ``task.idx``
|
||||
and a full ``task.model_dump``, both of which ``WireTask`` preserves.)
|
||||
and a full ``task.model_dump``, both of which ``WireTaskData`` preserves.)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -35,10 +35,10 @@ from prime_rl.orchestrator.sampler import Sampler
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
# Every wire trace validates into this type. WireTask (extra="allow") keeps the env's task
|
||||
# Every wire trace validates into this type. WireTaskData (extra="allow") keeps the env's task
|
||||
# fields without importing the env package — the orchestrator never reads them typed (only
|
||||
# task.idx + task.model_dump).
|
||||
ROLLOUT_TYPE = Rollout[vf.WireTask]
|
||||
ROLLOUT_TYPE = Rollout[vf.WireTaskData]
|
||||
|
||||
# Max wait for a spawned env server to bind and report its address. The child
|
||||
# loads the taskset (possibly downloading a dataset) before reporting, so this
|
||||
@@ -83,7 +83,8 @@ class Env:
|
||||
def __init__(self, config: EnvConfig):
|
||||
self.config = config
|
||||
self.sampling_args: dict = {}
|
||||
self.num_tasks: int = 0
|
||||
self.num_tasks: int | None = 0
|
||||
"""Task count reported by the server; ``None`` means the taskset is infinite."""
|
||||
self.requires_group_scoring: bool = False
|
||||
self._env_client: EnvClient | None = None
|
||||
self._env_server_process: BaseProcess | None = None
|
||||
@@ -112,9 +113,8 @@ class Env:
|
||||
info = await self.env_client.info()
|
||||
self.num_tasks = info.num_tasks
|
||||
self.requires_group_scoring = info.requires_group_scoring
|
||||
get_logger().info(
|
||||
f"Env {self.name} ready: num_tasks={self.num_tasks} group_scoring={self.requires_group_scoring}"
|
||||
)
|
||||
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
|
||||
get_logger().info(f"Env {self.name} ready: num_tasks={num_tasks} group_scoring={self.requires_group_scoring}")
|
||||
|
||||
async def _spawn(self, log_dir: Path, log_level: str, json_logging: bool) -> str:
|
||||
"""Spawn a v1 EnvServer child process (it loads the env; we never do).
|
||||
@@ -220,7 +220,12 @@ class EvalEnv(Env):
|
||||
|
||||
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
|
||||
await super().start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
|
||||
n = self.num_tasks if self.config.num_examples < 0 else min(self.config.num_examples, self.num_tasks)
|
||||
if self.num_tasks is None:
|
||||
if self.config.num_examples < 0:
|
||||
raise ValueError(f"Eval env {self.name} has an infinite taskset — set num_examples to bound it")
|
||||
n = self.config.num_examples
|
||||
else:
|
||||
n = self.num_tasks if self.config.num_examples < 0 else min(self.config.num_examples, self.num_tasks)
|
||||
self.examples = [{"task_idx": i} for i in range(n)]
|
||||
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ class EvalSink:
|
||||
if not group:
|
||||
return
|
||||
env_name = group[0].env_name
|
||||
task_idx = group[0].task.idx
|
||||
task_idx = group[0].task.data.idx
|
||||
eval_step = group[0].eval_step
|
||||
bucket = self.pending_batches[(env_name, eval_step)]
|
||||
bucket.extend(group)
|
||||
|
||||
@@ -72,10 +72,11 @@ from prime_rl.trainer.model import setup_tokenizer
|
||||
from prime_rl.transport import TrainingBatch, setup_training_batch_sender
|
||||
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
|
||||
from prime_rl.utils.client import init_nccl_broadcast
|
||||
from prime_rl.utils.config import to_toml_dict
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.monitor import setup_monitor
|
||||
from prime_rl.utils.pathing import get_log_dir, get_rollout_dir, get_step_path
|
||||
from prime_rl.utils.pathing import get_log_dir, get_trace_path
|
||||
from prime_rl.utils.usage_reporter import UsageReporter
|
||||
from prime_rl.utils.utils import (
|
||||
clean_exit,
|
||||
@@ -100,6 +101,11 @@ MAX_CONSECUTIVE_EMPTY_BATCHES = 10
|
||||
# resumed when the watcher advances ``policy.version``.
|
||||
TARGET_LAG = 1
|
||||
|
||||
# Default wait for the trainer's startup weight broadcast when no ckpt block
|
||||
# configures ``wait_for_weights_timeout`` (e.g. a from-scratch run). The
|
||||
# broadcast is always coming, so wait rather than fail immediately.
|
||||
STARTUP_WEIGHT_WAIT_TIMEOUT_S = 1200
|
||||
|
||||
|
||||
class Orchestrator:
|
||||
# Set in ``__init__``
|
||||
@@ -165,6 +171,8 @@ class Orchestrator:
|
||||
# Trigger timestamps so eval success logs can report epoch duration
|
||||
self.eval_triggered_at = {}
|
||||
self.consecutive_empty_batches = 0
|
||||
self.gate_closed_at = None
|
||||
self.wait_for_policy_time = 0.0
|
||||
self.component_tasks = []
|
||||
|
||||
# Optional attributes — ``setup()`` populates them when the relevant
|
||||
@@ -193,7 +201,7 @@ class Orchestrator:
|
||||
config_dir = config.output_dir / "control"
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
with open(config_dir / "orch.toml", "wb") as f:
|
||||
tomli_w.dump(config.model_dump(exclude_none=True, mode="json"), f)
|
||||
tomli_w.dump(to_toml_dict(config), f)
|
||||
|
||||
get_logger().info(f"Initializing tokenizer ({config.tokenizer})")
|
||||
self.tokenizer = setup_tokenizer(config.tokenizer)
|
||||
@@ -222,6 +230,8 @@ class Orchestrator:
|
||||
tokenizer=self.tokenizer,
|
||||
run_config=config,
|
||||
keep_full_history=config.bench,
|
||||
train_env_names=[env.resolved_name for env in config.train.env],
|
||||
eval_env_names=[env.resolved_name for env in config.eval.env] if config.eval is not None else [],
|
||||
)
|
||||
|
||||
if config.heartbeat is not None:
|
||||
@@ -305,20 +315,34 @@ class Orchestrator:
|
||||
|
||||
if self.resume_step is not None and self.ckpt_manager is not None:
|
||||
self.ckpt_manager.load(self.progress, step=self.resume_step)
|
||||
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
|
||||
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
|
||||
# trainer even when ``ckpt.skip_progress`` left the counter unrestored.
|
||||
self.progress.step = self.resume_step + 1
|
||||
get_logger().info(f"Resuming orchestrator from checkpoint step {self.resume_step}")
|
||||
check_exists = config.weight_broadcast.type != "nccl"
|
||||
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else None
|
||||
weights_path = get_weight_dir(
|
||||
config.output_dir, self.progress.step, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
)
|
||||
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=self.progress.step)
|
||||
if self.lora_name is not None:
|
||||
self.policy_inference.update_model_name(self.lora_name)
|
||||
self.policy.model_name = self.lora_name
|
||||
self.policy.version = self.progress.step
|
||||
else:
|
||||
get_logger().info("Training from scratch")
|
||||
|
||||
# Sync inference to the incoming policy before the first step, whether fresh (v0 = base) or
|
||||
# resumed (v{resume_step}). This pauses inference and rendezvouses with the trainer's
|
||||
# first-step broadcast (train.py), so inference serves the correct policy from step 1. Keeping
|
||||
# it unconditional makes trainer/orchestrator startup symmetric and avoids the resume deadlock
|
||||
# where inference waited for weights the trainer only sent at the end of a step.
|
||||
sync_version = self.resume_step if self.resume_step is not None else 0
|
||||
check_exists = config.weight_broadcast.type != "nccl"
|
||||
# Wait for the trainer's startup broadcast to land. On a fresh start there is no ckpt block,
|
||||
# so fall back to a default timeout instead of not waiting at all (which would raise before
|
||||
# broadcasts/step_0/STABLE is written when using filesystem weight broadcast).
|
||||
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else STARTUP_WEIGHT_WAIT_TIMEOUT_S
|
||||
weights_path = get_weight_dir(
|
||||
config.output_dir, sync_version, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
)
|
||||
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=sync_version)
|
||||
if self.lora_name is not None:
|
||||
self.policy_inference.update_model_name(self.lora_name)
|
||||
self.policy.model_name = self.lora_name
|
||||
self.policy.version = sync_version
|
||||
|
||||
self.train_source = TrainSource(self.train_envs, seed=42)
|
||||
self.eval_source: EvalSource | None = (
|
||||
EvalSource(
|
||||
@@ -361,7 +385,7 @@ class Orchestrator:
|
||||
inference=self.policy_inference,
|
||||
observers=[self.dispatcher, self],
|
||||
lora_name=self.lora_name,
|
||||
ckpt_step=self.progress.step,
|
||||
ckpt_step=self.policy.version,
|
||||
)
|
||||
# Single periodic logger for the whole pipeline. It's the only
|
||||
# consumer of ``dispatcher.metrics.drained()`` (which clears on read)
|
||||
@@ -407,11 +431,11 @@ class Orchestrator:
|
||||
asyncio.create_task(self.watcher.start(), name="watcher"),
|
||||
]
|
||||
|
||||
# Default step-0 base-model eval — fires before any train rollouts
|
||||
# unless ``eval.skip_first_step=True`` (or this is a resume)
|
||||
# Base-model eval (policy v0) — fires before any train rollouts, logged at the first
|
||||
# step, unless ``eval.skip_first_step=True`` (or this is a resume)
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
|
||||
# Anchor step-time clock so step 0 measures startup → first batch
|
||||
# Anchor step-time clock so the first step measures startup → first batch
|
||||
self.last_batch_at = time.perf_counter()
|
||||
|
||||
# ``clean_exit`` stays False if ``main_loop`` raises (signal-driven
|
||||
@@ -428,7 +452,11 @@ class Orchestrator:
|
||||
else:
|
||||
get_logger().warning(f"Orchestrator interrupted after {elapsed} — forcing cleanup (not a clean exit)")
|
||||
self.monitor.save_final_summary()
|
||||
if self.ckpt_manager is not None:
|
||||
# ``progress.step`` points at the next (unshipped) step; the last finished step is
|
||||
# ``progress.step - 1``. Checkpoint it as ``step_{progress.step - 1}`` (no-op before the
|
||||
# first ship).
|
||||
if self.ckpt_manager is not None and self.progress.step > 1:
|
||||
self.progress.step -= 1
|
||||
get_logger().info("Writing final checkpoint")
|
||||
self.ckpt_manager.save(self.progress, step=self.progress.step)
|
||||
await self.stop()
|
||||
@@ -453,6 +481,18 @@ class Orchestrator:
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
|
||||
# Every completed rollout — errored, filtered, or never batched — lands in the
|
||||
# ``all`` trace file the moment it arrives, so it survives crashes and drains.
|
||||
# Train rollouts belong to the batch window currently collecting (``progress.step``),
|
||||
# eval rollouts to the step whose eval triggered them.
|
||||
step = rollout.eval_step if rollout.kind == "eval" else self.progress.step
|
||||
assert step is not None
|
||||
await asyncio.to_thread(
|
||||
save_rollouts,
|
||||
[rollout.to_record()],
|
||||
get_trace_path(self.config.output_dir, step, rollout.kind, "all"),
|
||||
)
|
||||
|
||||
if rollout.kind == "eval":
|
||||
assert self.eval_sink is not None # eval rollouts only emitted when eval is configured
|
||||
eval_batch = self.eval_sink.add(rollout)
|
||||
@@ -481,9 +521,7 @@ class Orchestrator:
|
||||
step_time = (now - self.last_batch_at) if self.last_batch_at is not None else 0.0
|
||||
self.last_batch_at = now
|
||||
|
||||
save_ckpt_time = await self.maybe_save_ckpt(step)
|
||||
|
||||
if config.max_steps is not None and step >= config.max_steps:
|
||||
if config.max_steps is not None and step > config.max_steps:
|
||||
self.draining = True
|
||||
self.dispatcher.disable_train_scheduling()
|
||||
n_cancelled = await self.dispatcher.cancel_inflight_train_rollouts()
|
||||
@@ -514,20 +552,23 @@ class Orchestrator:
|
||||
f"({n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
|
||||
)
|
||||
|
||||
# Serialize the typed Trace at the I/O boundary (disk + wandb sample tables); to_record
|
||||
# drops the per-node training tensors — they're for training, not the rollout record, and
|
||||
# can't round-trip json (raw numpy bytes).
|
||||
rollout_dicts = [r.to_record() for r in batch.rollouts]
|
||||
step_path = get_step_path(get_rollout_dir(config.output_dir), step)
|
||||
await asyncio.to_thread(save_rollouts, rollout_dicts, step_path / "train_rollouts.jsonl")
|
||||
# The effective (clean, trained-on) subset lands in the per-step ``effective`` trace file
|
||||
# at ship time; the full arrival window already streamed into ``all`` on arrival.
|
||||
# to_record drops the per-node training tensors — they're for training, not the rollout
|
||||
# record, and can't round-trip json (raw numpy bytes).
|
||||
effective = batch.rollouts.effective
|
||||
records = [r.to_record() for r in effective]
|
||||
await asyncio.to_thread(save_rollouts, records, get_trace_path(config.output_dir, step, "train", "effective"))
|
||||
|
||||
await self.sender.send(TrainingBatch(examples=batch.samples, step=step))
|
||||
self.progress.step += 1
|
||||
self.update_dispatch_gate()
|
||||
# Checkpoint the step we just shipped (resume point: continue at step + 1).
|
||||
save_ckpt_time = await self.maybe_save_ckpt(step)
|
||||
trim_process_memory()
|
||||
|
||||
# Rollout metrics over the {agg,<env>} × {all,effective} matrix. ``batch.rollouts`` is the
|
||||
# full arrival window (errored + filtered included); ``.effective`` is the clean subset.
|
||||
effective = batch.rollouts.effective
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", batch.rollouts), ("effective", effective)):
|
||||
metrics |= pool.metrics.to_wandb(prefix="train/agg", subset=subset)
|
||||
@@ -554,6 +595,7 @@ class Orchestrator:
|
||||
"progress/total_tasks": self.progress.total_problems,
|
||||
"time/step": step_time,
|
||||
"time/save_ckpt": save_ckpt_time,
|
||||
"time/wait_for_policy": self.wait_for_policy_time,
|
||||
"step": step,
|
||||
}
|
||||
for env_name, env_pool in batch.rollouts.by_env().items():
|
||||
@@ -565,6 +607,7 @@ class Orchestrator:
|
||||
for name, count in self.train_sink.pre_filter_dropped_by_name.items():
|
||||
metrics[f"pre_filters/all/{name}/rate"] = count / self.train_sink.pre_filter_seen
|
||||
self.monitor.log(metrics, step=step)
|
||||
self.wait_for_policy_time = 0.0
|
||||
self.monitor.log_samples(effective.rollouts, step=step)
|
||||
self.monitor.log_distributions(
|
||||
distributions={
|
||||
@@ -592,7 +635,6 @@ class Orchestrator:
|
||||
self.log_train_batch(batch, step=step, step_time=step_time)
|
||||
|
||||
self.train_sink.reset_pre_filter_stats()
|
||||
self.progress.step += 1
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
trim_process_memory()
|
||||
|
||||
@@ -726,12 +768,13 @@ class Orchestrator:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no rollouts returned, skipping log")
|
||||
return
|
||||
|
||||
rollout_dicts = [r.to_record() for r in batch.rollouts]
|
||||
step_path = get_step_path(get_rollout_dir(self.config.output_dir), batch.step)
|
||||
# The non-errored subset lands in the per-step ``effective`` trace file on epoch
|
||||
# completion (multiple eval envs share the step file — each epoch appends its cohort
|
||||
# once, and every record carries ``env_name``); the full returned cohort already
|
||||
# streamed into ``all`` on arrival.
|
||||
records = [r.to_record() for r in batch.rollouts.effective]
|
||||
await asyncio.to_thread(
|
||||
save_rollouts,
|
||||
rollout_dicts,
|
||||
step_path / f"eval_rollouts_{batch.env_name}.jsonl",
|
||||
save_rollouts, records, get_trace_path(self.config.output_dir, batch.step, "eval", "effective")
|
||||
)
|
||||
self.monitor.log_eval_samples(batch.rollouts, env_name=batch.env_name, step=batch.step)
|
||||
policy_versions = {r.policy_version for r in batch.rollouts}
|
||||
@@ -764,19 +807,13 @@ class Orchestrator:
|
||||
)
|
||||
|
||||
async def maybe_save_ckpt(self, step: int) -> float:
|
||||
"""Save the checkpoint if we're at an interval boundary. Returns
|
||||
"""Checkpoint the step just shipped if it's an interval boundary. Returns
|
||||
elapsed time (0.0 when no save happened)."""
|
||||
if self.ckpt_manager is None or self.config.ckpt is None or not self.config.ckpt.interval:
|
||||
return 0.0
|
||||
if step <= 0:
|
||||
return 0.0
|
||||
# Skip only the drain-entry step (step == max_steps, which never ships):
|
||||
# it would double-save with the final checkpoint in ``start()`` (also at
|
||||
# progress.step == max_steps). The last *shipped* step (max_steps - 1) is
|
||||
# NOT skipped — the trainer saves there (its is_last_step is max_steps),
|
||||
# so the orchestrator must too or resume from that interval ckpt breaks.
|
||||
near_end = self.config.max_steps is not None and step >= self.config.max_steps
|
||||
if near_end:
|
||||
# The final step's checkpoint is written once in ``start()``'s teardown; skip it here so
|
||||
# we don't double-save. This mirrors the trainer (its is_last_step skips the in-loop save).
|
||||
if self.config.max_steps is not None and step >= self.config.max_steps:
|
||||
return 0.0
|
||||
if step % self.config.ckpt.interval != 0:
|
||||
return 0.0
|
||||
@@ -786,22 +823,37 @@ class Orchestrator:
|
||||
return time.perf_counter() - t
|
||||
|
||||
def update_dispatch_gate(self) -> None:
|
||||
"""Pause/resume the dispatcher based on how far the orchestrator's
|
||||
next batch would run ahead of ``policy.version``. Called from two
|
||||
sites: after shipping a batch (step advances) and from
|
||||
``on_new_version`` (policy advances)."""
|
||||
lead = (self.progress.step + 1) - self.policy.version
|
||||
"""Pause/resume the dispatcher based on how far the in-flight batch runs
|
||||
ahead of ``policy.version``. ``progress.step`` is always the batch being
|
||||
collected — advanced right after shipping — so both call sites (ship time
|
||||
here, policy update in ``on_new_version``) share one lead formula. Steps
|
||||
are 1-indexed while policy versions stay 0-indexed, so the shipped-batch
|
||||
count is ``progress.step - 1``."""
|
||||
lead = (self.progress.step - 1) - self.policy.version
|
||||
# The trainer skips the final NCCL weight broadcast (inference group is
|
||||
# torn down), so policy.version never reaches the last step. Without this
|
||||
# the gate deadlocks waiting for a version that will never be published.
|
||||
# The last batch uses the penultimate policy anyway, so let it through.
|
||||
building_final_batch_nccl = (
|
||||
self.config.weight_broadcast.type == "nccl"
|
||||
and self.config.max_steps is not None
|
||||
and self.progress.step >= self.config.max_steps - 1
|
||||
)
|
||||
gate = self.dispatcher.dispatch_allowed
|
||||
was_set = gate.is_set()
|
||||
if lead > TARGET_LAG:
|
||||
if lead > TARGET_LAG and not building_final_batch_nccl:
|
||||
if was_set:
|
||||
get_logger().info(
|
||||
"Pausing dispatcher to prevent orchestrator from racing from trainer. Waiting for new policy..."
|
||||
)
|
||||
self.gate_closed_at = time.perf_counter()
|
||||
gate.clear()
|
||||
else:
|
||||
if not was_set:
|
||||
get_logger().info("Resuming dispatcher")
|
||||
if self.gate_closed_at is not None:
|
||||
self.wait_for_policy_time += time.perf_counter() - self.gate_closed_at
|
||||
self.gate_closed_at = None
|
||||
gate.set()
|
||||
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
|
||||
@@ -30,6 +30,19 @@ from prime_rl.transport import TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
def payload_tokens(rollout: Rollout) -> int:
|
||||
"""Token cost of the rollout's trainer-bound payload — the samples built by
|
||||
``process_rollout``. This is what actually ships: forked traces can drop
|
||||
branches with no trainable tokens, so ``Trace.num_total_tokens`` (which sums
|
||||
over all branches) may overcount. For linear traces the two agree.
|
||||
|
||||
Zero-payload rollouts (no trainable samples at all) fall back to the trace
|
||||
total so they still advance token batching — a degenerate all-zero-payload
|
||||
stream then ships empty batches and trips the orchestrator's
|
||||
consecutive-empty-batch abort instead of stalling the readiness check."""
|
||||
return sum(len(sample.token_ids) for sample in rollout.samples) or rollout.num_total_tokens
|
||||
|
||||
|
||||
class TrainSink:
|
||||
"""Three-level train sink. Constructed once, fed via ``add(rollout)``."""
|
||||
|
||||
@@ -57,15 +70,18 @@ class TrainSink:
|
||||
self.pre_filters = pre_filters
|
||||
self.post_filters = post_filters
|
||||
|
||||
# Observation window for the next shipped batch: rollouts of groups
|
||||
# finalized since the last ship (errored + filtered + survivors).
|
||||
# In-progress groups stay out until they finalize.
|
||||
self.pending_rollouts: TrainRollouts = TrainRollouts()
|
||||
# Keyed by the dispatcher's group UUID. ``(env_name, task_idx)``
|
||||
# isn't unique — the same task can be re-sampled while an
|
||||
# earlier group is still in flight
|
||||
self.pending_rollouts: TrainRollouts = TrainRollouts()
|
||||
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
|
||||
self.pending_batch: list[Rollout] = []
|
||||
# Running token total of ``pending_batch`` (token-batched runs), kept in
|
||||
# sync on append/pop so the readiness check never re-walks the uncached
|
||||
# ``Trace.num_total_tokens`` graph property per arrival.
|
||||
# Running payload-token total of ``pending_batch`` (token-batched
|
||||
# runs), kept in sync on append/pop so the readiness check never
|
||||
# re-sums per arrival.
|
||||
self.pending_tokens: int = 0
|
||||
|
||||
# Reset by the orchestrator after each ship via ``reset_pre_filter_stats``
|
||||
@@ -117,13 +133,18 @@ class TrainSink:
|
||||
|
||||
async def add(self, rollout: Rollout) -> TrainBatch | None:
|
||||
"""Process one arrival; finalize the group on the ``group_size``-th
|
||||
arrival; return a ``TrainBatch`` if the batch threshold is met."""
|
||||
arrival; return a ``TrainBatch`` if the finalization pushed (or left)
|
||||
the batch over its threshold. Arrivals into still-incomplete groups
|
||||
never ship a batch."""
|
||||
await self.process_rollout(rollout)
|
||||
env_name = rollout.env_name
|
||||
self.pending_rollouts.append(rollout)
|
||||
self.pending_groups[rollout.group_id].append(rollout)
|
||||
if len(self.pending_groups[rollout.group_id]) >= self.group_size_for(env_name):
|
||||
await self.process_group(rollout.group_id)
|
||||
if len(self.pending_groups[rollout.group_id]) < self.group_size_for(env_name):
|
||||
return None
|
||||
await self.process_group(rollout.group_id)
|
||||
# ``pending_batch`` only grows on group finalization, so readiness is
|
||||
# only re-checked here — the window of a shipped batch then always
|
||||
# contains at least the group that finalized it.
|
||||
ready = (
|
||||
len(self.pending_batch) >= self.batch_size
|
||||
if self.batch_size is not None
|
||||
@@ -159,8 +180,14 @@ class TrainSink:
|
||||
group = self.pending_groups.pop(group_id, [])
|
||||
if not group:
|
||||
return
|
||||
# Window membership follows group finalization, not arrival: a rollout
|
||||
# only becomes observable (metrics / persistence) once its whole group
|
||||
# is finalized, so a batch's window never claims rollouts of a group
|
||||
# that ships later. Dropped groups still land here — they were observed.
|
||||
for r in group:
|
||||
self.pending_rollouts.append(r)
|
||||
env_name = group[0].env_name
|
||||
task_idx = group[0].task.idx
|
||||
task_idx = group[0].task.data.idx
|
||||
survivors = [r for r in group if not r.has_error]
|
||||
num_errored = len(group) - len(survivors)
|
||||
|
||||
@@ -211,7 +238,7 @@ class TrainSink:
|
||||
r.is_filtered = False
|
||||
self.pending_batch.append(r)
|
||||
if self.token_batch_size is not None:
|
||||
self.pending_tokens += r.num_total_tokens
|
||||
self.pending_tokens += payload_tokens(r)
|
||||
|
||||
# Per-group summary. One line per finalized group; per-filter
|
||||
# detection breakdown lives at debug level in ``apply_filters``
|
||||
@@ -238,7 +265,7 @@ class TrainSink:
|
||||
cut = 0
|
||||
running = 0
|
||||
for i, r in enumerate(self.pending_batch):
|
||||
running += r.num_total_tokens
|
||||
running += payload_tokens(r)
|
||||
cut = i + 1
|
||||
if running >= self.token_batch_size:
|
||||
break
|
||||
@@ -253,11 +280,12 @@ class TrainSink:
|
||||
# advantage stream and loss routing on each sample. Filtered rollouts don't ship.
|
||||
samples: list[TrainingSample] = [sample for r in cohort if not r.is_filtered for sample in r.samples]
|
||||
|
||||
# ``rollouts`` is the whole arrival window (errored + filtered + survivors); ``samples`` is
|
||||
# the shipped cohort's trainable payload. ``rollouts.effective`` / ``rollouts.metrics`` derive
|
||||
# the clean subset + metric views on demand. Reset the window only when the batch actually
|
||||
# ships (non-empty samples) — an empty batch is dropped unlogged by the orchestrator, so keep
|
||||
# accumulating its arrivals (and any overflow) into the next shipped batch's window.
|
||||
# ``rollouts`` is the observation window — every rollout of every group finalized since the
|
||||
# last ship (errored + filtered + survivors) — while ``samples`` is the shipped cohort's
|
||||
# trainable payload. ``rollouts.effective`` / ``rollouts.metrics`` derive the clean subset +
|
||||
# metric views on demand. Reset the window only when the batch actually ships (non-empty
|
||||
# samples) — an empty batch is dropped unlogged by the orchestrator, so keep accumulating its
|
||||
# finalized groups (and any overflow) into the next shipped batch's window.
|
||||
rollouts = self.pending_rollouts
|
||||
if samples:
|
||||
self.pending_rollouts = TrainRollouts()
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
"""TrainSource: weighted round-robin across train envs, infinite pull.
|
||||
|
||||
Weights default to configured ``ratio`` (when every env sets one) or to
|
||||
per-env dataset size. ``next_example`` reshuffles on cursor exhaustion."""
|
||||
Weights are each env's configured ``ratio`` (default 1, i.e. equal weight
|
||||
per env). A finite env serves a shuffled task-index table, reshuffled on
|
||||
cursor exhaustion; an infinite env (``num_tasks is None``) streams a
|
||||
monotonic ``task_idx`` — the server generates tasks on demand, so every
|
||||
pull is a fresh task and there are no epochs to shuffle."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -22,26 +25,27 @@ class TrainSource:
|
||||
if not self.envs:
|
||||
raise ValueError("TrainSource needs at least one train env")
|
||||
|
||||
self.examples: dict[str, list[dict]] = {}
|
||||
# A finite env's shuffled index table; ``None`` for an infinite env,
|
||||
# whose cursor alone is the (monotonic) task_idx stream.
|
||||
self.examples: dict[str, list[dict] | None] = {}
|
||||
self.cursors: dict[str, int] = {}
|
||||
# Group-scoring envs reserve ``group_size`` permits up front;
|
||||
# per-rollout envs need 1
|
||||
self.env_costs: dict[str, int] = {}
|
||||
for env in self.envs:
|
||||
# The orchestrator never loads the env: sample over the task-index
|
||||
# range the server reported via info() (num_tasks).
|
||||
rows: list[dict] = [{"task_idx": i, "env_name": env.name} for i in range(env.num_tasks)]
|
||||
self.rng.shuffle(rows)
|
||||
self.examples[env.name] = rows
|
||||
# range the server reported via info() (num_tasks; None = infinite).
|
||||
if env.num_tasks is None:
|
||||
self.examples[env.name] = None
|
||||
else:
|
||||
rows: list[dict] = [{"task_idx": i, "env_name": env.name} for i in range(env.num_tasks)]
|
||||
self.rng.shuffle(rows)
|
||||
self.examples[env.name] = rows
|
||||
self.cursors[env.name] = 0
|
||||
self.env_costs[env.name] = env.config.group_size if env.requires_group_scoring else 1
|
||||
|
||||
self.env_names = [e.name for e in self.envs]
|
||||
configured_ratios = [e.config.ratio for e in self.envs]
|
||||
if all(r is not None for r in configured_ratios):
|
||||
self.weights: list[float] = [float(r) for r in configured_ratios] # type: ignore[arg-type]
|
||||
else:
|
||||
self.weights = [float(len(self.examples[name])) for name in self.env_names]
|
||||
self.weights: list[float] = [float(e.config.ratio) for e in self.envs]
|
||||
|
||||
def next_example(self, available_permits: int) -> dict | None:
|
||||
env_name = self.rng.choices(self.env_names, weights=self.weights, k=1)[0]
|
||||
@@ -49,6 +53,9 @@ class TrainSource:
|
||||
return None
|
||||
rows = self.examples[env_name]
|
||||
cursor = self.cursors[env_name]
|
||||
if rows is None: # infinite env: the cursor is the task_idx
|
||||
self.cursors[env_name] = cursor + 1
|
||||
return {"task_idx": cursor, "env_name": env_name}
|
||||
if cursor >= len(rows):
|
||||
self.rng.shuffle(rows)
|
||||
cursor = 0
|
||||
|
||||
@@ -15,6 +15,8 @@ the images it introduced (`branch.multi_modal_data`), rebuilt here into the flat
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator
|
||||
|
||||
import numpy as np
|
||||
import verifiers.v1 as vf
|
||||
|
||||
@@ -64,6 +66,29 @@ def _encode_routed_experts(arr: np.ndarray | None, num_tokens: int) -> RoutedExp
|
||||
return RoutedExperts(data=arr.tobytes(), shape=list(arr.shape), dtype=str(arr.dtype))
|
||||
|
||||
|
||||
def iter_trainable_branches(trace: vf.Trace) -> Iterator[tuple[vf.Branch, list[bool]]]:
|
||||
"""Yield each branch that yields a training sample, with its trainable-token mask.
|
||||
|
||||
The mask is `branch.sampled_mask` except that a sampled node shared by several branches
|
||||
(a mid-trajectory fork) is trainable only in the first branch containing it; later
|
||||
branches carry its tokens as context (mask False). Branches left with no trainable
|
||||
tokens are skipped, so consumers pairing branches with `trace_to_samples` output
|
||||
(e.g. echo's observation weighting) must filter through here to stay aligned.
|
||||
"""
|
||||
trained_nodes: set[int] = set()
|
||||
for branch in trace.branches:
|
||||
mask: list[bool] = []
|
||||
for node in branch.nodes:
|
||||
if node.sampled and any(node.mask) and id(node) in trained_nodes:
|
||||
mask.extend([False] * len(node.mask))
|
||||
else:
|
||||
if node.sampled and any(node.mask):
|
||||
trained_nodes.add(id(node))
|
||||
mask.extend(node.mask)
|
||||
if any(mask):
|
||||
yield branch, mask
|
||||
|
||||
|
||||
def trace_to_samples(
|
||||
trace: vf.Trace,
|
||||
*,
|
||||
@@ -82,10 +107,7 @@ def trace_to_samples(
|
||||
yield nothing.
|
||||
"""
|
||||
samples: list[TrainingSample] = []
|
||||
for branch in trace.branches:
|
||||
mask = branch.sampled_mask
|
||||
if not any(mask):
|
||||
continue
|
||||
for branch, mask in iter_trainable_branches(trace):
|
||||
token_ids = branch.token_ids
|
||||
mm_kwargs: dict[str, EncodedTensor] | None = None
|
||||
mm_token_type_ids: list[int] | None = None
|
||||
|
||||
@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, Generic, Literal, Protocol
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import ConfigDict, Field
|
||||
from verifiers.v1.task import TaskT
|
||||
from verifiers.v1.task import DataT
|
||||
|
||||
from prime_rl.transport import TrainingSample
|
||||
|
||||
@@ -27,9 +27,9 @@ class Policy:
|
||||
|
||||
@dataclass
|
||||
class Progress:
|
||||
"""Persistent counters; ``step`` is the trainer-aligned step."""
|
||||
"""Persistent counters; ``step`` is the trainer-aligned step (1-indexed)."""
|
||||
|
||||
step: int = 0
|
||||
step: int = 1
|
||||
total_tokens: int = 0
|
||||
total_samples: int = 0
|
||||
total_problems: int = 0
|
||||
@@ -69,12 +69,12 @@ class GroupState:
|
||||
policy_version_at_start: int = 0
|
||||
|
||||
|
||||
class Rollout(vf.Trace[TaskT], Generic[TaskT]):
|
||||
class Rollout(vf.Trace[DataT], Generic[DataT]):
|
||||
"""A completed rollout: the env's typed ``vf.Trace`` *is* the rollout — prime-rl's
|
||||
orchestration metadata lives on it directly (set by the dispatcher once the rollout
|
||||
returns), so there's no wrapper. Train vs eval is the ``kind`` discriminator. All metadata
|
||||
fields are ``exclude=True``, so dumping a Rollout yields a plain trace — the on-disk
|
||||
``results.jsonl`` is unchanged.
|
||||
fields are ``exclude=True``, so dumping a Rollout yields a plain trace on the wire;
|
||||
:meth:`to_record` adds the small metadata fields back for the on-disk trace files.
|
||||
|
||||
It is also the single currency the scoring hooks receive: a hook reads the trace
|
||||
directly (``rollout.reward``, ``rollout.nodes``, ``rollout.num_turns``) and writes
|
||||
@@ -98,6 +98,19 @@ class Rollout(vf.Trace[TaskT], Generic[TaskT]):
|
||||
filter_results: dict[str, bool] = Field(default_factory=dict, exclude=True)
|
||||
eval_step: int | None = Field(default=None, exclude=True)
|
||||
|
||||
def to_record(self) -> dict:
|
||||
"""The plain trace record plus the orchestration metadata (excluded from the pydantic
|
||||
dump), so a record stays fully placeable — kind, env, policy — even when trace files
|
||||
are merged or read away from their paths. ``eval_step`` is the eval trigger step (None
|
||||
for train rollouts)."""
|
||||
return super().to_record() | {
|
||||
"kind": self.kind,
|
||||
"env_name": self.env_name,
|
||||
"group_id": str(self.group_id),
|
||||
"policy_version": self.policy_version,
|
||||
"eval_step": self.eval_step,
|
||||
}
|
||||
|
||||
def assign_advantages(self, values: float | list[float]) -> None:
|
||||
"""Write the rl advantage stream: a scalar broadcast over the
|
||||
rollout's trainable (mask-True) tokens (0.0 elsewhere), or a per-token
|
||||
@@ -134,11 +147,12 @@ class Rollout(vf.Trace[TaskT], Generic[TaskT]):
|
||||
|
||||
@dataclass
|
||||
class TrainBatch:
|
||||
"""``rollouts`` is the full arrival window since the last ship (errored + filtered included; its
|
||||
``.effective`` / ``.metrics`` views drive logging). ``samples`` is the trainer-bound payload (the
|
||||
shipped cohort's post-filter survivors) — an empty list means nothing ships, which would stall the
|
||||
trainer. Trainable counts derive from ``rollouts`` (``r.is_trainable``) and token totals from
|
||||
``samples``, so neither is carried as a field."""
|
||||
"""``rollouts`` is the observation window since the last ship — every rollout of every group
|
||||
finalized in that span (errored + filtered included; rollouts of still-incomplete groups wait
|
||||
for a later window). Its ``.effective`` / ``.metrics`` views drive logging. ``samples`` is the
|
||||
trainer-bound payload (the shipped cohort's post-filter survivors) — an empty list means nothing
|
||||
ships, which would stall the trainer. Trainable counts derive from ``rollouts``
|
||||
(``r.is_trainable``) and token totals from ``samples``, so neither is carried as a field."""
|
||||
|
||||
rollouts: TrainRollouts
|
||||
samples: list[TrainingSample]
|
||||
|
||||
@@ -51,10 +51,12 @@ async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
|
||||
|
||||
|
||||
def save_rollouts(rollouts: list[dict], path: Path) -> None:
|
||||
"""Save rollouts (Trace dicts, already JSON-serializable) to a JSONL file."""
|
||||
"""Append rollouts (Trace record dicts, already JSON-serializable) to a JSONL file.
|
||||
The trace streams are append-only: ``all`` grows one rollout at a time as they
|
||||
complete, ``effective`` one batch at a time on finalize."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
|
||||
with open(path, "wb") as f:
|
||||
with open(path, "ab") as f:
|
||||
for rollout in rollouts:
|
||||
f.write(orjson.dumps(rollout, default=str, option=opts))
|
||||
|
||||
|
||||
@@ -34,8 +34,8 @@ export NUM_DECODE_NODES={{ num_decode_nodes }}
|
||||
export NUM_PREFILL_REPLICAS={{ num_prefill_replicas }}
|
||||
export NUM_DECODE_REPLICAS={{ num_decode_replicas }}
|
||||
export NODES_PER_REPLICA=$((NUM_PREFILL_NODES + NUM_DECODE_NODES))
|
||||
export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
|
||||
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
|
||||
export NODES_PER_PREFILL_REPLICA={{ prefill_nodes_per_replica }}
|
||||
export NODES_PER_DECODE_REPLICA={{ decode_nodes_per_replica }}
|
||||
export PREFILL_PORT={{ prefill_port }}
|
||||
export DECODE_PORT={{ decode_port }}
|
||||
export ROUTER_PORT={{ router.port }}
|
||||
@@ -61,7 +61,17 @@ ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
uv sync --all-extras
|
||||
{% if not shared_fs %}
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
|
||||
# build the batch node, so srun runs it on every node (one task each) and blocks until
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
uv sync --all-extras --all-packages
|
||||
{% endif %}
|
||||
|
||||
# Print inference URLs
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
|
||||
@@ -41,8 +41,8 @@ export NUM_PREFILL_NODES={{ num_prefill_nodes }}
|
||||
export NUM_DECODE_NODES={{ num_decode_nodes }}
|
||||
export NUM_PREFILL_REPLICAS={{ num_prefill_replicas }}
|
||||
export NUM_DECODE_REPLICAS={{ num_decode_replicas }}
|
||||
export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
|
||||
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
|
||||
export NODES_PER_PREFILL_REPLICA={{ prefill_nodes_per_replica }}
|
||||
export NODES_PER_DECODE_REPLICA={{ decode_nodes_per_replica }}
|
||||
export PREFILL_PORT={{ prefill_port }}
|
||||
export DECODE_PORT={{ decode_port }}
|
||||
{%- if router.type == "llm-d" %}
|
||||
@@ -144,7 +144,17 @@ echo "MASTER_PORT=${MASTER_PORT}"
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
uv sync --all-extras
|
||||
{% if not shared_fs %}
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
|
||||
# build the batch node, so srun runs it on every node (one task each) and blocks until
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
uv sync --all-extras --all-packages
|
||||
{% endif %}
|
||||
|
||||
{% if pre_run_command %}
|
||||
# Pre-run command
|
||||
|
||||
@@ -48,9 +48,17 @@ echo "MASTER_PORT=${MASTER_PORT}"
|
||||
# Install environment
|
||||
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
|
||||
source $PROJECT_DIR/.venv/bin/activate
|
||||
|
||||
# Install environment as local package
|
||||
cd $PROJECT_DIR && uv sync --all-extras
|
||||
{% if not shared_fs %}
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
|
||||
# build the batch node, so srun runs it on every node (one task each) and blocks until
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
cd $PROJECT_DIR && uv sync --all-extras --all-packages
|
||||
{% endif %}
|
||||
|
||||
|
||||
{% if pre_run_command %}
|
||||
|
||||
@@ -31,7 +31,7 @@ export PROJECT_DIR={{ project_dir }}
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
|
||||
{% if pre_run_command %}
|
||||
# Pre-run command
|
||||
|
||||
@@ -31,7 +31,7 @@ export PROJECT_DIR={{ project_dir }}
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
|
||||
{% if pre_run_command %}
|
||||
# Pre-run command
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user