Compare commits

...
Author SHA1 Message Date
Maxwill LinandGitHub f04c8d988c fix(vlm): dispatch Gemma 4 as a VLM and read softcapping from the text config (#2844)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-22 02:23:13 +02:00
4d361adacc fix(orchestrator): drain off-policy rollouts before pausing for weight update (#2841)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The off-policy drain (cancelling rollouts past max_off_policy_steps) ran via
on_new_version *after* the inference engines resumed from the weight-update
pause. In a NIXL P/D deployment this reliably crashed the decode engines.

Aborting a rollout cancels its /generate request; vLLM marks the request
FINISHED_ABORTED and frees it, recording it in the NIXL connector's
_reqs_not_processed set so the worker suppresses its in-flight KV-transfer
completion. That suppression only propagates to the workers while the engine is
stepping. Pausing with mode="keep" (PAUSED_ALL) skips step(), so KV transfers
that complete during the pause are flushed on the first step after resume — at
the same moment the drain fires its aborts. The abort frees the request before
its suppression reaches the worker, so the flushed completion hits
`assert req_id in self.requests` in the decode scheduler's
_update_from_kv_xfer_finished, killing the engine and cascading to every DP
rank via the gloo finish-state all-reduce.

With max_off_policy_steps=8 the first mass drop lands at the 9th weight update,
which is why the run always died at step 8/9.

Move the drain to a new on_version_pending observer hook that the watcher calls
*before* update_weights (before the pause), so the aborts are processed under
normal stepping and the connector's native cleanup completes before the engine
freezes. on_new_version still runs post-update for the orchestrator's dispatch
gate, which needs the live policy version.

Co-authored-by: faresobeid <fares@primeintellect.ai>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 20:04:08 -07:00
faresobeidandGitHub 7f77713886 update length penalty and add back length weighted baseline (#2702)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-19 02:09:32 +02:00
samsjaandGitHub efeddae6bb add rlm uuid ctf env (#2832)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-18 16:00:38 -07:00
8dfe8734e3 Fix routed SLURM inference DP rank client config (#2830)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Codex <codex@primeintellect.ai>
2026-06-18 01:29:48 +02:00
faresobeidandGitHub fa21395a68 improve sequence packing (#2723)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* improve sequence packing

* ruff

* clean tests

* add config

* make balancy by flops non-optinal

* fix

* refactor

* merge utils

* remove bin_cost option

* fix

---------

Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
2026-06-15 03:00:33 +01:00
samsjaandGitHub b5daec1cbb Clear inference slurm logs on launch (#2814)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-14 14:12:07 -07:00
b452660025 fix(inference): strip routed_experts from chat-completions responses (#2813)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(inference): strip routed_experts from chat-completions responses

routed_experts are consumed only via the serialized /generate (serving_tokens)
path used for router-replay training, which emits them as a {data, shape, start}
object the PD router merges. The stock chat-completions path encodes them as a
base64 np.save string instead, which the PD router rejects ("prefill routed_experts
must be an object with base64 data and shape") — failing every eval rollout, since
evals go through chat completions. enable_return_routed_experts is a server-wide
model-config flag with no per-request toggle, so strip the field on the chat path.

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

* chore: format routed experts chat patch

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 13:09:08 -07:00
060f25bb3a feat(deployment): optionally run orchestrator on an inference node (#2811)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Adds MultiNodeDeploymentConfig.orchestrator_on_inference (default False). When
False, the orchestrator launches on trainer rank 0 (unchanged behavior). When
True, it launches on the last inference node (a decode node) instead — useful
when trainer nodes are host-RAM-saturated (large CPU-offloaded optimizer state)
and the orchestrator's rollout buffer + env workers would otherwise exhaust
memory there; inference nodes keep weights/KV on GPU with ample free host RAM.

The orchestrator launch is now a single top-level block in multi_node_rl.sbatch.j2
gated on a flag-selected SLURM_PROCID (NUM_INFER_NODES for trainer rank 0, or
NUM_INFER_NODES-1 for the last inference node), so both placements share one code
path. No effect when num_infer_nodes == 0.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 11:51:39 -07:00
faresobeidGitHubfaresobeidcopilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
77af037537 IPO config (#2798)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* IPO config

* fix: apply Ruff formatting in RL loss module

---------

Co-authored-by: faresobeid <fares@primeintellect.ai>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-06-14 17:41:42 +01:00
samsjaandGitHub 9281c5589a add nixl to gigitngore (#2805)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-13 16:25:11 -07:00
9dbb523933 fix: raise vLLM DP coordinator startup timeout (hard-coded 30s) (#2804)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The coordinator child spawns on the DP-rank-0 API server while every
engine-core rank on the node is importing and loading weights, so its
spawn-time re-import can exceed 30s under that CPU/IO contention (seen
on multi-node disaggregated GLM-5.1 launches). Patch _wait_for_zmq_addrs
with a configurable timeout via PRIME_DP_COORDINATOR_STARTUP_TIMEOUT
(default 300s).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-13 16:23:08 -07:00
5789850d4d fix(trainer): freeze DSA sparse indexer so checkpoint resume doesn't crash-loop (#2800)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The DSA sparse-attention indexer runs its forward under torch.no_grad(), so its
params (wq_b, wk, k_norm, weights_proj) never receive a gradient. They were left
with requires_grad=True and handed to AdamW, which lazily creates per-param state
only on the first step where a grad exists -- so the indexer params stayed
stateless.

This breaks strict checkpoint resume. At save time DCP's _init_optim_state
returns early (optim.state already non-empty), so the stateless indexer params
are omitted from the saved optimizer state. At load time the optimizer is fresh,
so _init_optim_state runs a zero-grad step over every requires_grad param and
materializes exp_avg/exp_avg_sq/step for the indexer too. DCP then demands those
keys, the checkpoint doesn't have them, and load dies with:

    RuntimeError: Missing key in checkpoint state_dict:
        app.optimizers.state.model.layers.0.self_attn.indexer.wq_b.weight.step

With resume_step=-1 every restart re-picks the same checkpoint and crashes
identically -> crash-loop.

Fix:
- freeze_sparse_indexer(): set requires_grad=False on all Indexer params, called
  unconditionally in setup_model (no-op for non-DSA models). The indexer is never
  trainable anyway, so this only makes save/load state symmetric.
- _create_optimizer(): hand only trainable params to AdamW/SGD/SignSGD (Muon
  already filtered internally), so frozen params carry no optimizer state.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 23:46:59 +02:00
JannikStandGitHub 146fcd0136 fix(inference): restore usage block on /inference/v1/generate (#2784)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(inference): restore usage block on /inference/v1/generate response

* fix(inference): apply ruff formatting

* fix(inference): drive _FinalOutputCapture through async-for, not __anext__

* fix(inference): always emit cached_tokens, drop enable_prompt_tokens_details gate

* chore: bump verifiers to fix/hatch-vcs-fallback-version

Pin to the fallback-version fix (PrimeIntellect-ai/verifiers#1650) so the
prime-rl Docker build resolves a version without VCS metadata. Temporary
pin to the PR branch; should move to verifiers main once #1650 lands.

* fix(inference): annotate _FinalOutputCapture source as AsyncIterable
2026-06-12 19:07:09 +02:00
samsjaandGitHub b0612a0e1f add rlm search (#2783)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* add rlm search

* bump dep
2026-06-11 21:25:18 -07:00
DominikandGitHub c0a026c0d4 Send Prime monitor display config to platform (#2709)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-12 02:27:05 +02:00
Jackmin801andGitHub 7c9c1308dc Register Nano V3 reasoning parser (#2767)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix: register nano v3 reasoning parser

* chore: apply ruff formatting
2026-06-11 16:38:51 -07:00
941019f2e3 [feat] multiplex trainer token export and agg to prime monitor on orch side (#2641)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* multiplex trainer output

* update skill

* test: cover multi-run token exports

* feat: export token metrics from orchestrator

* refactor: store token export run fields on microbatch

* refactor: send microbatches without payload wrapper

* test: cover orchestrator token-export metric collection

Adds an integration test asserting the orchestrator's per-step read path
(collect_token_export_metrics) surfaces finite mismatch_kl/entropy mean/max
from real multi-run exports. Complements the file-writing coverage in
test_token_exports_are_run_local; reuses the existing fixture.

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

* fix: defer token-export STABLE until run step fully consumed

A single orchestrator run_step can span multiple trainer steps when the
packer splits its samples across packs (token budget). mark_stable() ran
every trainer step and marked any dir touched that step, so the orchestrator
could read a run step's exports as complete from only the first pack's
sequences and advance its cursor, never aggregating the remainder.

Mark a run's export dir STABLE only once that run step is fully consumed —
gated on the same ready_to_update signal that drives its optimizer step.
Dirs for runs not yet ready carry over to a later trainer step. run_id=None
(single-run export) never spans trainer steps, so it is marked immediately.

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

* feat: stamp token-export metrics with their trainer step

Token exports lag the orchestrator step they're logged under (the trainer
runs behind), so on the default W&B step axis mismatch_kl/entropy appear
shifted right. Log the run step the exports actually belong to as
`trainer/step` so the metrics can be plotted against a lag-corrected axis.

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

* refactor: fold token-export metrics into MetricsBuilder under trainer/

Move the token-export collection from the orchestrator mainline into
MetricsBuilder.build, which now owns the last-logged-step cursor (seeded from
the resumed step via start_step). Namespace the metrics under trainer/
(trainer/mismatch_kl/*, trainer/entropy/*) alongside trainer/step so they
group in W&B and can be plotted against a lag-corrected axis.

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

* refactor: drop redundant max_step from token-export reader

Exports always lag the orchestrator (the current step's batch is shipped just
before metrics are built and trained afterward), so no stable export at or
beyond the current step can exist on disk. The `step <= max_step` filter was
always satisfied; the last_logged_step cursor alone drives correctness.

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

* refactor: return log-ready dict from token-export reader

Drop the TokenExportMetricsResult dataclass that was unpacked into a dict one
line later. collect_next_token_export_metrics now returns the trainer/-prefixed
metrics (including trainer/step) directly, so the builder just updates the log
dict and reads trainer/step back to advance its cursor.

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

* refactor: guard token-export log update under the truthiness check

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

* refactor: drop redundant run_idx guard in SinglePacker

The receiver always stamps batch.run_idx from used_idxs (a key of idx_2_id),
so the is-not-None/in-idx_2_id check was always true. Index directly, matching
MultiPacker.

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

* refactor: mark token-export STABLE with a barrier instead of all_gather

The all_gather_object did barrier + dir-union + rank-0 write. Replace it with a
plain dist.barrier() (so STABLE only lands after every rank flushed its
rank_*.jsonl), then each rank touches STABLE for the dirs it wrote. touch is
idempotent, so ranks sharing a (run, step) dir converge harmlessly, and the
union is covered without shipping dir lists.

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

* refactor: barrier at the call site, drop participate_in_stable_marking

The barrier lived inside the exporter, so the disabled variant needed a
participate_in_stable_marking flag to opt into it. Move the barrier to the
single train-loop call site, gated on token export being enabled (uniform
across ranks): every rank barriers together, then writers touch STABLE and
disabled ranks no-op. DisabledTokenExporter is a pure no-op again and the
exporter does no collectives.

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

* refactor: drop dist.is_initialized guard before token-export barrier

train() always calls setup_torch_distributed before the training loop, so dist
is initialized by the time the barrier runs.

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

* chore: drop redundant comments around token-export barrier

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

* refactor: derive token-export root from output_dir.parent

root_output_dir was just output_dir.parent of self.output_dir and used in one
place; drop the redundant attribute.

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

* fix: skip malformed token-export records instead of aborting the step

Token-export metrics are best-effort monitoring read inside MetricsBuilder.build
every step. A malformed JSONL line or a loss_mask/value length mismatch raised
ValueError, which would abort the orchestrator step. Guard each record, skip and
count failures, and warn once per step dir; good records still aggregate.

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

* feat: drain trailing token-export metrics after max_steps

Token exports lag the orchestrator, so the last shipped steps are finalized by
the trainer after the main loop ends — and build() no longer runs to log them,
dropping the tail. Add an end-of-run drain that polls for the remaining stable
steps up to max_steps-1 and logs each under its own trainer/step (a local W&B
step axis, leaving progress.step for the final checkpoint untouched). Gated on
token export being on for the run; early-returns when build() already kept up;
bounded by a timeout. Shared collection extracted to
MetricsBuilder.next_token_export_metrics.

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

* make token export a top-level trainer flag

* chore: fold token export into multi-run integration config

* chore: revert multi-run trainer config override

* chore: remove token export unit tests

* docs: document token export config migration

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-10 15:05:10 -07:00
9e1f0521e3 fix(scripts): verify IB support in UCX build for NIXL (#2761)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
UCX's --with-verbs silently disables IB when the rdma-core dev headers
are missing, producing a TCP-only build that only fails much later at
runtime with NIXL_ERR_BACKEND. On hosts with RDMA devices, require the
headers before building and verify the rc_verbs transport made it into
the built UCX. Also pass --with-rdmacm so the rdmacm connection manager
is built when available.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 14:32:58 -07:00
e466d233e9 fix(slurm): portable GLOO/UCX NIC selection in sbatch templates (#2760)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
GLOO_SOCKET_IFNAME was hardcoded to bond0 and UCX_NET_DEVICES to all,
both of which break on clusters with different NIC naming or with RDMA
devices UCX cannot open (e.g. a non-functional Ethernet bond, which
fails NIXL backend creation with NIXL_ERR_BACKEND). Derive the gloo
interface from LOCAL_IP and enumerate RDMA ports from sysfs (ibv_devices
is not on the job PATH), preferring InfiniBand, falling back to RoCE,
and keeping "all" on hosts without RDMA devices.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 14:32:09 -07:00
9ea9fb193e fix(client): retry all admin ops with bounded timeouts (#2759)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
/resume and /update_weights previously had no retry and no per-attempt
timeout, so a transient failure or stuck server during a weight update
could leave engines paused indefinitely (the admin AsyncClient uses
timeout=None). Factor the /pause retry into a shared _admin_post helper
with a single default timeout, overridable per call; /update_weights
gets a longer one since the collective NCCL receive can take a while.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 14:29:47 -07:00
alelpoanandGitHub 91c86b7383 fix(docs): fix broken links (404) in overview and advanced pages (#2744)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-10 12:15:09 -07:00
alelpoanandGitHub d4b30bf3ae fix(docs): escape invalid MDX character in inference.md (#2740)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>
2026-06-10 12:14:33 -07:00
samsjaandGitHub d5ce4ce84d Update README.md (#2750)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* Update README.md

Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>

* Update README.md

Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>

---------

Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
2026-06-09 21:20:07 -07:00
samsjaandGitHub 04d067145f update deps (#2736)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* update deps

* update deps

* update deps
2026-06-09 19:31:19 -07:00
samsjaandGitHub 632ef2b318 chore: remove private configs submodule (#2741)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Remove the configs/private submodule (research-configs) and all
references to it throughout the codebase:

- Remove submodule from .gitmodules and git tracking
- Simplify install.sh: use plain git submodule update --init --recursive
  now that no private submodule can fail for users without access
- Update skills/install/SKILL.md to reflect simplified submodule init
- Remove configs/private/ entry from skills/configs/SKILL.md key files
- Simplify test_configs.py: no longer need to filter out private/ path
2026-06-09 19:31:08 -07:00
faresobeidandGitHub c8759c370a add router replay to latentMoE models (#2738)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-10 00:01:11 +01:00
Tim KostolanskyandGitHub 0695f9caa5 fix: allow sft without teacher (#2720)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-09 12:34:20 -07:00
halleriteandGitHub e0f8a35c78 feat(orchestrator): per-env advantage strategy (#2721)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-09 05:05:13 +02:00
faresobeidandGitHub 54012df504 orch improvements (#2725)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* orch improvements

* fixes
2026-06-09 01:48:12 +01:00
samsjaandGitHub 53b22b55c8 fix: add prime-pydantic-config as direct dep so uv uses editable path source (#2733)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The [tool.uv.sources] override for prime-pydantic-config was being ignored
because it was only a transitive dependency (via prime-rl-configs). uv only
applies source overrides for packages that appear in project.dependencies.
Adding it as a direct dependency makes uv resolve from the local editable
path (deps/pydantic-config) instead of PyPI.
2026-06-08 16:34:24 -07:00
minh hoangandGitHub c2a5fa466c chore(renderers): bump to submodule to renderers-v0.1.8.dev41 (#2732)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-08 15:16:58 -07:00
Matej SirovatkaandGitHub 90b074492e Feat: fix weight reload to cpu optim (#2729)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-08 17:58:23 +02:00
766e36f000 Feat/fp8 fused transpose cast (#2724)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(fp8): fuse transpose into the dX block-fp8 weight cast

The dX backward built `weight.transpose(0, 1).contiguous()` and re-cast it to
fp8 every step, materializing a full bf16 transpose buffer plus an extra
read/write pass. Add `per_block_cast_to_fp8_tp_triton`, which produces the
block-fp8 of `weight.T` directly by reusing the existing per-block kernel with
swapped output/scale strides — no intermediate buffer.

128x128 block quantization is transpose-symmetric, so the result is
bit-identical to casting the materialized transpose; DeepGEMM receives an
identical B tensor. Verified byte-for-byte across shapes; ~14x faster on a
4096x4096 weight (373 -> 27 us).

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

* deslopified

* also add fused implementation for per-token

* Fix: skip tests on <Hopper

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: S1ro1 <matej.sirovatka@gmail.com>
2026-06-07 17:51:36 +02:00
209f76eb52 fix(install): support aarch64 hosts with any compute capability (#2587)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The aarch64 host install path was broken: `uv sync` installs flash-attn
from PyPI source but pyproject sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE,
so the compiled extension never builds. `scripts/docker-arm64-post-install.sh`
fixed it for Docker GB200 builds but hardcoded sm_100 and /app/.venv,
leaving Hopper hosts (H100/H200/GH200) without a recipe.

Changes:
- `scripts/docker-arm64-post-install.sh`: auto-detect compute capability
  via nvidia-smi when available; parameterize venv path. Preserves the
  sm_100 default when no GPU is visible (Docker buildx).
- `scripts/install.sh`: call the post-install for aarch64 hosts after
  `uv sync --all-extras`. Previously the script ran uv sync and exited,
  leaving aarch64 users with a broken venv.
- `README.md`: document the aarch64 post-install step (mirrors the
  existing 3.1 Flash Attention 3 pattern).

Validated on GH200 (sm_90, aarch64):
- forward + backward parity vs torch SDPA (max diff < 0.05 / 0.25)
- 383/384 unit tests pass (the 1 failure is unrelated TileLang/MoE)
- SFT trainer smoke test (5 steps, Qwen3-0.6B) runs with flash_attention_2

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-05 20:21:11 -07:00
68 changed files with 2999 additions and 1055 deletions
+3 -2
View File
@@ -23,7 +23,8 @@ configs/endpoints.py
final_summary.json
.pydantic_config
.chroma_db
deps/nixl_*
nixl_workspace/*
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
@@ -202,4 +203,4 @@ debug_I2_zero_band
outputs/
third_party/
third_party/
-3
View File
@@ -7,9 +7,6 @@
[submodule "research-environments"]
path = deps/research-environments
url = git@github.com:PrimeIntellect-ai/research-environments.git
[submodule "configs/private"]
path = configs/private
url = git@github.com:PrimeIntellect-ai/research-configs.git
[submodule "pydantic-config"]
path = deps/pydantic-config
url = https://github.com/PrimeIntellect-ai/pydantic-config
+2
View File
@@ -2,6 +2,8 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **`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.
+11 -2
View File
@@ -55,10 +55,10 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#vision-language-models) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ❌ |
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ✅ |
| Trinity (`afmoe`) | `arcee-ai/Trinity-Mini`, … | yes | ✅ | ✅ |
| GLM-4 · GLM-4.5 MoE · INTELLECT-3 (`glm4_moe`) | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5-Air`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | yes | ✅ | ✅ |
| GPT-OSS (HF, MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | yes | ❌ | ✅ |
| GPT-OSS (HF, MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | yes | ✅ | ✅ |
| Other HF causal LMs | Qwen3 dense, Mistral, … (`impl = "hf"`) | varies | ❌ | ✅ |
@@ -110,6 +110,15 @@ source $HOME/.local/bin/env
uv sync --all-extras
```
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.
> *NOTE*: After this step, you can't run `uv sync --all-extras` or `uv run` as it will uninstall the package, you can avoid it by running `uv sync --inexact` or `uv run --no-sync`.
```bash
bash scripts/docker-arm64-post-install.sh
```
3.1. Optional: Install Flash Attention 3 (on Hopper GPUs only, for flash_attention_3 attention backend)
> *NOTE*: This step will take a while, as it builds the Flash Attention 3 extension from source, as it has no wheels prebuilt.
@@ -1,5 +1,6 @@
# Trainer config for multi-run RL integration test
max_concurrent_runs = 2
enable_token_export = true
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
Submodule configs/private deleted from 70c3503e1d
+1 -1
+1 -1
+1 -1
View File
@@ -115,7 +115,7 @@ LoRA pairs naturally with [multi-tenant training](#multi-tenant-training) — ea
## Multi-Tenant Training
Multi-tenant training lets a single trainer + inference deployment serve many concurrent LoRA "tenants" — each a fully isolated run with its own orchestrator, LoRA adapter, optimizer, scheduler, checkpoints, and progress tracking — sharing the same backbone weights and the same vLLM server. This is the topology behind hosted training on the [Prime Intellect platform (Lab)](https://app.primeintellect.ai). The trainer-side implementation is the `MultiRunManager` singleton, enabled by setting `trainer.max_concurrent_runs > 1`. For the full API surface, see [`src/prime_rl/trainer/runs/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/src/prime_rl/trainer/runs).
Multi-tenant training lets a single trainer + inference deployment serve many concurrent LoRA "tenants" — each a fully isolated run with its own orchestrator, LoRA adapter, optimizer, scheduler, checkpoints, and progress tracking — sharing the same backbone weights and the same vLLM server. This is the topology behind hosted training on the [Prime Intellect platform (Lab)](https://app.primeintellect.ai). The trainer-side implementation is the `MultiRunManager` singleton, enabled by setting `trainer.max_concurrent_runs > 1`. For the full API surface, see [`src/prime_rl/trainer/runs.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/src/prime_rl/trainer/runs.py).
## Disaggregated Prefill/Decode Inference
+29 -3
View File
@@ -136,10 +136,20 @@ The default advantage is per-group reward minus per-group baseline (DR-GRPO with
This is intentionally simple — it does the right thing for most envs. Switch to a [custom advantage](#custom-advantage) when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …).
Two built-in **length penalties** can be layered on top of any advantage to discourage rambling:
A **length penalty** can be layered on top of the default advantage to discourage rambling. Configured under `[orchestrator.advantage.length_penalty]`, it subtracts a `coef * pass_rate * (completion tokens / orchestrator.seq_len)` term from every reward before the baseline subtraction, where `pass_rate` is the problem's mean reward across the group. The pass-rate factor means problems the model already solves reliably get the strongest push toward concise outputs, while rarely-solved problems are barely penalized (a never-solved group, mean reward 0, gets none). Set `gate_by_correctness = true` to apply the penalty only to correct rollouts (`reward == 1`), leaving incorrect ones untouched:
- `[orchestrator.length_penalty] type = "tokens"` — penalizes long completions in tokens, with configurable target and slope.
- `[orchestrator.length_penalty] type = "turns"` — penalizes long multi-turn rollouts by turn count.
```toml
[orchestrator.advantage.length_penalty]
coef = 0.25 # effective penalty is coef * pass_rate * (completion_tokens / seq_len)
gate_by_correctness = false # when true, only penalize rollouts with reward == 1
```
By default the baseline is the plain group mean reward. Set `length_weighted_baseline = true` to instead use the token-length-weighted mean — `sum(len_i * reward_i) / sum(len_i)` — which centers advantages by per-token expected reward when rollouts vary a lot in length:
```toml
[orchestrator.advantage]
length_weighted_baseline = true
```
### Custom Advantage
@@ -167,6 +177,22 @@ kwargs = { eps = 1e-8 }
`AdvantageInputs.rollouts` is a list of `verifiers.RolloutOutput`, so you have access to the full rollout (turns, tool calls, custom metadata) — not just the reward. Use this for anything reward-shaping-like that needs trajectory context.
### Per-Env Advantage
`advantage` can be set per training environment. Each env inherits the top-level `[orchestrator.advantage]` when it doesn't set its own, so mixed-env runs can give each env its own advantage computation:
```toml
[orchestrator.advantage]
type = "default" # the default every env inherits unless it overrides
[[orchestrator.train.env]]
id = "math-env" # inherits the default above
[[orchestrator.train.env]]
id = "agent-env"
advantage = { type = "custom", import_path = "my_module.normalized_advantage" }
```
## Filters
Filters drop rollouts between scoring and training. Built-ins (composable):
+1 -1
View File
@@ -2,7 +2,7 @@
Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config): TOML files for reproducible base configs, CLI flags for one-off overrides.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `token_export` flag) that aren't surfaced here.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `enable_token_export` flag) that aren't surfaced here.
## Table of Contents
+1 -1
View File
@@ -252,7 +252,7 @@ headless = true
### Router Replay
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer<->inference mismatch by an order of magnitude, resulting in more stable training.
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
To enable router replay, you can set `inference.enable_return_routed_experts = true`.
+1 -1
View File
@@ -10,7 +10,7 @@ A `prime-rl` RL run is three cooperating processes:
- **Inference** — vLLM-backed server (or fleet) holding the current policy. The orchestrator drives rollouts through the token-in `/v1/generate` route via the [`renderers`](https://github.com/PrimeIntellect-ai/renderers) package (OpenAI-compatible chat/completions routes are also exposed for external clients). We are trying to stay up-to-date with the latest vLLM features, you can read more about the supported features and deployment options in the dedicated [inference documentation](inference.md).
- **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 [trainer documentation](trainer.md).
- **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.
@@ -143,6 +143,40 @@ class EvalSamplingConfig(BaseConfig):
return data
class LinearLengthPenaltyConfig(BaseConfig):
coef: float = Field(0.25, ge=0, allow_inf_nan=False)
"""Scale on the linear length penalty. Each reward is reduced by ``coef * pass_rate * (model completion tokens / orchestrator.seq_len)`` — where ``pass_rate`` is the group's mean reward — before the GRPO baseline subtraction. Finite and non-negative."""
gate_by_correctness: bool = False
"""When True, scale each rollout's penalty by its reward (``penalty * reward``), so correct rollouts (``reward == 1``) are penalized and incorrect ones (``reward == 0``) are not. When False, every rollout is penalized equally."""
class DefaultAdvantageConfig(BaseConfig):
type: Literal["default"] = "default"
length_penalty: LinearLengthPenaltyConfig | None = None
"""Length penalty applied during advantage computation. Subtracts a ``coef * pass_rate * (completion tokens / orchestrator.seq_len)`` term from each reward (``pass_rate`` = group mean reward) before the baseline subtraction, so solved-often problems get the strongest concision pressure and never-solved groups get none. None disables the penalty."""
length_weighted_baseline: bool = False
"""When True, the GRPO baseline is the token-length-weighted mean reward (``sum(len_i * reward_i) / sum(len_i)``) instead of the plain group mean, centering advantages by per-token expected reward."""
class CustomAdvantageConfig(BaseConfig):
type: Literal["custom"] = "custom"
import_path: str
"""Import path to the advantage function (e.g. ``my_module.my_advantage``)."""
kwargs: dict[str, Any] = Field(default_factory=dict)
"""Kwargs forwarded to the advantage function."""
AdvantageConfig: TypeAlias = Annotated[
DefaultAdvantageConfig | CustomAdvantageConfig,
Field(discriminator="type"),
]
class EnvConfig(BaseConfig):
id: str = "reverse-text"
"""Registered verifiers environment ID (e.g. ``math-env``, ``primeintellect/math-env``). May include an ``@version`` suffix for installation."""
@@ -214,6 +248,11 @@ class TrainEnvConfig(EnvConfig):
"""Rollouts generated per example for GRPO group-relative advantages.
Inherits from ``orchestrator.group_size`` when unset."""
advantage: AdvantageConfig | None = None
"""Advantage strategy for this env's GRPO groups. Inherits from the top-level
``orchestrator.advantage`` when unset; set a different ``default``/``custom``
config to give this env its own advantage computation."""
class EvalEnvConfig(EnvConfig):
sampling: EvalSamplingConfig = EvalSamplingConfig()
@@ -374,49 +413,6 @@ class CheckpointConfig(BaseConfig):
"""Skip loading the progress from checkpoint."""
class TokensLengthPenaltyConfig(BaseConfig):
type: Literal["tokens"] = "tokens"
completion_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
"""Weight on model completion tokens. Finite and non-negative."""
tool_response_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
"""Weight on tool-response tokens (read from the rollout's ``*_total_tool_response_tokens`` harness metric; 0 if absent). Finite and non-negative."""
class TurnsLengthPenaltyConfig(BaseConfig):
type: Literal["turns"] = "turns"
LengthPenaltyConfig: TypeAlias = Annotated[
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
Field(discriminator="type"),
]
class DefaultAdvantageConfig(BaseConfig):
type: Literal["default"] = "default"
length_penalty: LengthPenaltyConfig | None = None
"""Correctness-gated length penalty. ``tokens`` shapes by weighted token cost; ``turns`` shapes by trajectory turn count; None disables shaping. In mixed groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost rollouts get advantage in [0, 1], others get 0."""
class CustomAdvantageConfig(BaseConfig):
type: Literal["custom"] = "custom"
import_path: str
"""Import path to the advantage function (e.g. ``my_module.my_advantage``)."""
kwargs: dict[str, Any] = Field(default_factory=dict)
"""Kwargs forwarded to the advantage function."""
AdvantageConfig: TypeAlias = Annotated[
DefaultAdvantageConfig | CustomAdvantageConfig,
Field(discriminator="type"),
]
# Flags rare tokens generated at high entropy (Section 5.2, https://arxiv.org/abs/2510.02387).
class GibberishFilterConfig(BaseConfig):
type: Literal["gibberish"] = "gibberish"
@@ -517,7 +513,7 @@ class OrchestratorConfig(BaseConfig):
"""Typed renderer config (``renderers.RendererConfig`` discriminated
union). Defaults to ``"auto"``, which resolves from
``tokenizer.name_or_path`` via ``MODEL_RENDERER_MAP``. ``None``
opts into MITO (``openai_chat_completions``); SFT mode forces this."""
opts into MITO (``openai_chat_completions``)."""
pool_size: int | None = Field(None, ge=1)
"""Number of renderer slots shared across concurrent rollouts. Bump
@@ -754,11 +750,10 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def _force_no_renderer_for_sft(self):
"""SFT rolls out via the teacher's plain chat-completions endpoint; the
renderer client doesn't apply. Force ``renderer=None`` so the user
doesn't have to remember to set it. Declared before the renderer
validators below so they see the corrected value."""
if self.training_mode == "sft":
"""Teacher-backed SFT rolls out via the teacher's plain chat-completions
endpoint; the renderer client doesn't apply. When no teacher is
configured, SFT uses the student rollout path and keeps the renderer."""
if self.training_mode == "sft" and self.teacher is not None:
self.renderer = None
return self
@@ -768,8 +763,8 @@ class OrchestratorConfig(BaseConfig):
has_teacher = self.teacher is not None
if self.training_mode == "rl" and has_teacher:
raise ValueError("orchestrator.teacher must not be set when training_mode = 'rl'.")
if self.training_mode in ("opd", "sft") and not has_teacher:
raise ValueError(f"orchestrator.teacher must be configured when training_mode = '{self.training_mode}'.")
if self.training_mode == "opd" and not has_teacher:
raise ValueError("orchestrator.teacher must be configured when training_mode = 'opd'.")
return self
@model_validator(mode="after")
@@ -876,6 +871,11 @@ class OrchestratorConfig(BaseConfig):
if "group_size" not in env_cfg.model_fields_set:
env_cfg.group_size = self.group_size
# Propagate the top-level ``advantage`` into each train env that didn't set its own.
for env_cfg in self.train.env:
if "advantage" not in env_cfg.model_fields_set:
env_cfg.advantage = self.advantage
# Resolve train env num_workers from max_inflight_rollouts
for env_cfg in self.train.env:
if env_cfg.num_workers == "auto":
@@ -167,6 +167,9 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
nodes_per_fsdp_group: int | None = None
"""Training nodes per FSDP island. Auto-sets ``trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
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 total_infer_nodes(self) -> int:
return self.num_infer_nodes * self.num_infer_replicas
@@ -603,16 +606,20 @@ class RLConfig(BaseConfig):
def auto_setup_inference_client(self):
"""Auto-configure orchestrator student client from the inference server config.
For all modes, sets dp_rank_count from inference DP size. For SFT mode,
also sets base_url - rl/opd rely on the ClientConfig default
(``["http://localhost:8000/v1"]``) which already matches the auto-launched
student vLLM at inference.server.port = 8000.
Direct single-node runs expose all local DP ranks behind one base URL,
so pin logical clients with ``X-data-parallel-rank``. Multi-node SLURM
runs expose a vllm-router URL instead; the router balances across
per-rank backend URLs and forwards request headers, so the orchestrator
must not inject a DP-rank header there.
"""
if self.inference is None:
return self
client = self.orchestrator.student.client
if "dp_rank_count" not in client.model_fields_set:
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
if self.deployment.type == "multi_node":
client.dp_rank_count = 1
else:
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
if self.orchestrator.training_mode == "sft" and "base_url" not in client.model_fields_set:
host = self.inference.server.host or "localhost"
port = self.inference.server.port
@@ -425,6 +425,18 @@ class DefaultLossConfig(BaseConfig):
"""Temperature for the KL term."""
class IPOLossConfig(BaseConfig):
type: Literal["ipo"] = "ipo"
ipo_threshold: float = Field(0.1, ge=0)
"""Upper DPPO masking threshold."""
adv_tau: float = Field(1.0, ge=0)
"""Temperature for the advantage term."""
kl_tau: float = Field(1e-3, ge=0)
"""Temperature for the KL term."""
class CustomLossConfig(BaseConfig):
type: Literal["custom"] = "custom"
@@ -435,7 +447,7 @@ class CustomLossConfig(BaseConfig):
"""Kwargs forwarded to the loss function."""
LossConfig: TypeAlias = Annotated[DefaultLossConfig | CustomLossConfig, Field(discriminator="type")]
LossConfig: TypeAlias = Annotated[DefaultLossConfig | IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
class FakeDataLoaderConfig(BaseConfig):
@@ -490,15 +502,6 @@ WeightBroadcastConfig: TypeAlias = Annotated[
]
class TokenExportConfig(BaseConfig):
"""Configures per-token rollout exports from the RL trainer."""
class TrainerExperimentalConfig(BaseConfig):
token_export: TokenExportConfig | None = None
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
class TrainerConfig(BaseConfig):
model: ModelConfig = ModelConfig()
@@ -562,7 +565,8 @@ class TrainerConfig(BaseConfig):
max_concurrent_runs: int = Field(1, ge=1)
"""Maximum number of concurrent runs to allow. If 1, only one run may run at a time."""
experimental: TrainerExperimentalConfig = TrainerExperimentalConfig()
enable_token_export: bool = False
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
@model_validator(mode="after")
def deepep_disables_grad_clipping(self):
@@ -22,6 +22,8 @@ REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
(re.compile(r"^zai-org/GLM-"), "glm45"),
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2_append_think"),
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "deepseek_r1"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Super"), "nemotron_v3"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Nano"), "nano_v3"),
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
# Only Qwen3 Thinking models reason — Instruct/base models do not.
(re.compile(r"^Qwen/Qwen3-.*Thinking"), "deepseek_r1"),
+9 -2
View File
@@ -6,6 +6,7 @@ readme = "README.md"
requires-python = "~=3.12.0"
dependencies = [
"prime-rl-configs",
"prime-pydantic-config",
"beartype>=0.21.0",
"datasets>=4.0.0",
"jaxtyping>=0.3.2",
@@ -27,6 +28,7 @@ dependencies = [
"aiolimiter>=1.2.1",
"tenacity>=8.2.0",
"openai>=1.106.1",
"orjson>=3.11.0",
"rich>=14.0.0",
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
@@ -77,7 +79,6 @@ envs = [
"math-python",
"math500",
"mini-swe-agent-plus",
"mini-swe-agent-plus-rlm",
"mmlu-pro",
"opencode-cp",
"opencode-deepdive",
@@ -86,6 +87,8 @@ envs = [
"opencode-swe",
"reverse-text",
"rlm-swe",
"rlm-search",
"rlm-uuid-ctf",
"science-env",
"simpleqa-verified",
"tau2-bench",
@@ -150,6 +153,7 @@ override-dependencies = [
"transformers==5.6.2",
"torch>=2.9.0",
"openenv-core",
"verifiers[packages]>=0.1.15.dev150",
]
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
@@ -207,6 +211,7 @@ color-codeword = { path = "deps/research-environments/environments/color_codewor
deepdive = { path = "deps/research-environments/environments/deepdive", editable = true }
general-agent = { path = "deps/research-environments/environments/general_agent", editable = true }
gpqa = { path = "deps/research-environments/environments/gpqa", editable = true }
harnesses = { path = "deps/verifiers/packages/harnesses", editable = true }
hle = { path = "deps/research-environments/environments/hle", editable = true }
ifeval = { path = "deps/research-environments/environments/ifeval", editable = true }
livecodebench = { path = "deps/research-environments/environments/livecodebench", editable = true }
@@ -215,7 +220,6 @@ math-env = { path = "deps/research-environments/environments/math_env", editable
math-python = { path = "deps/verifiers/environments/math_python", editable = true }
math500 = { path = "deps/research-environments/environments/math500", editable = true }
mini-swe-agent-plus = { path = "deps/research-environments/environments/mini_swe_agent_plus", editable = true }
mini-swe-agent-plus-rlm = { path = "deps/research-environments/environments/mini_swe_agent_plus_rlm", editable = true }
mmlu-pro = { path = "deps/research-environments/environments/mmlu_pro", editable = true }
opencode-cp = { path = "deps/research-environments/environments/opencode_cp", editable = true }
opencode-deepdive = { path = "deps/research-environments/environments/opencode_deepdive", editable = true }
@@ -224,9 +228,12 @@ opencode-science = { path = "deps/research-environments/environments/opencode_sc
opencode-swe = { path = "deps/research-environments/environments/opencode_swe", editable = true }
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
rlm-swe = { path = "deps/research-environments/environments/rlm_swe", editable = true }
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
rlm-uuid-ctf = { path = "deps/research-environments/environments/rlm_uuid_ctf", editable = true }
science-env = { path = "deps/research-environments/environments/science_env", editable = true }
simpleqa-verified = { path = "deps/research-environments/environments/simpleqa_verified", editable = true }
tau2-bench = { path = "deps/research-environments/environments/tau2_bench", editable = true }
tasksets = { path = "deps/verifiers/packages/tasksets", editable = true }
wiki-search = { path = "deps/verifiers/environments/wiki_search", editable = true }
wordle = { path = "deps/verifiers/environments/wordle", editable = true }
torch = { index = "pytorch-cu128" }
+37 -10
View File
@@ -1,17 +1,44 @@
#!/bin/bash
# arm64 post-install fixups for Docker builds.
set -e
# arm64 post-install fixups: rebuild flash-attn from source for the target GPU.
#
# Why this exists: pyproject.toml sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE to keep
# `uv sync` fast; on x86_64 it pins a prebuilt wheel to fill in the binary, but no
# such wheel exists for aarch64. Without this script, `import flash_attn` fails on
# aarch64 with `ModuleNotFoundError: No module named 'flash_attn_2_cuda'`.
#
# Defaults preserve the existing Docker behavior (sm_100 / GB200). On a host with
# `nvidia-smi` available, the compute capability is auto-detected from the local
# GPU. Override via env vars if needed:
# TORCH_CUDA_ARCH_LIST e.g. 9.0 (Hopper), 10.0 (Blackwell)
# VENV_PATH path to the venv (default: $(pwd)/.venv)
# MAX_JOBS parallel nvcc jobs (default: 4)
set -euo pipefail
echo "=== building flash-attn from source (sm_100 / GB200) ==="
# Run from /tmp so uv doesn't read pyproject.toml's [tool.uv.extra-build-variables]
# which sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and prevents CUDA kernel compilation.
export TORCH_CUDA_ARCH_LIST="10.0"
export MAX_JOBS=4
if [ -z "${TORCH_CUDA_ARCH_LIST:-}" ]; then
# Try to detect from the local GPU. Tolerate any failure mode (binary missing,
# driver not loaded, Docker buildx without --gpus) and fall back to GB200.
TORCH_CUDA_ARCH_LIST="$(nvidia-smi --query-gpu=compute_cap --format=csv,noheader 2>/dev/null | head -1 | tr -d ' ' || true)"
: "${TORCH_CUDA_ARCH_LIST:=10.0}"
fi
export TORCH_CUDA_ARCH_LIST
VENV_PATH="${VENV_PATH:-$(pwd)/.venv}"
if [ ! -x "$VENV_PATH/bin/python" ]; then
echo "ERROR: no python at $VENV_PATH/bin/python. Run from the project root or set VENV_PATH." >&2
exit 1
fi
export MAX_JOBS="${MAX_JOBS:-4}"
export FLASH_ATTENTION_FORCE_BUILD=TRUE
export FLASH_ATTENTION_SKIP_CUDA_BUILD=FALSE
(cd /tmp && uv pip install --python /app/.venv/bin/python \
"flash-attn==2.8.3" --no-build-isolation --no-binary flash-attn --no-cache)
echo "=== building flash-attn from source (TORCH_CUDA_ARCH_LIST=$TORCH_CUDA_ARCH_LIST, MAX_JOBS=$MAX_JOBS) ==="
echo " target venv: $VENV_PATH"
# Run from /tmp so uv ignores the project's [tool.uv.extra-build-variables],
# which sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and would prevent kernel compilation.
(cd /tmp && uv pip install --python "$VENV_PATH/bin/python" \
"flash-attn==2.8.3" --no-build-isolation --no-binary flash-attn --no-cache --reinstall-package flash-attn)
echo "=== reinstalling flash-attn-cute (flash-attn overwrites it with a stub) ==="
uv pip install --reinstall --no-deps \
uv pip install --python "$VENV_PATH/bin/python" --reinstall --no-deps \
"flash-attn-4 @ git+https://github.com/Dao-AILab/flash-attention.git@96bd151#subdirectory=flash_attn/cute"
+11 -17
View File
@@ -74,27 +74,11 @@ ensure_known_hosts() {
fi
}
# Initialize each submodule independently so that a missing private repo
# (e.g. configs/private when the user lacks access) does not abort the install.
init_submodules() {
if [ ! -f .gitmodules ]; then
return 0
fi
local paths failures
paths=$(git config -f .gitmodules --get-regexp '^submodule\..*\.path$' | awk '{print $2}')
failures=()
for path in $paths; do
log_info "Initializing submodule: ${path}"
if git submodule update --init --recursive -- "$path"; then
:
else
log_warn "Could not initialize submodule '${path}' (likely no access). Continuing without it."
failures+=("$path")
fi
done
if [ "${#failures[@]}" -gt 0 ]; then
log_warn "Skipped submodules: ${failures[*]}"
fi
git submodule update --init --recursive
}
main() {
@@ -159,6 +143,16 @@ main() {
log_info "Installing pre-commit hooks..."
uv run pre-commit install
# aarch64 has no prebuilt flash-attn wheel; build it from source for the local GPU.
# Without this, `import flash_attn` fails with `ModuleNotFoundError: flash_attn_2_cuda`.
# Run last so no subsequent uv operation (which implicitly syncs against the lockfile)
# rebuilds flash-attn from PyPI with FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and undoes this.
if [ "$(uname -m)" = "aarch64" ]; then
log_info "aarch64 detected: building flash-attn from source (this takes 20-30 minutes)..."
log_warn "Future 'uv sync --all-extras' or 'uv run' will remove this build. Use 'uv sync --inexact' or 'uv run --no-sync' to keep it."
bash scripts/docker-arm64-post-install.sh
fi
log_info "Installation completed!"
}
+25
View File
@@ -10,6 +10,19 @@ PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
VENV_BIN="$PROJECT_DIR/.venv/bin"
PYTHON="$VENV_BIN/python"
# UCX's --with-verbs silently disables IB/RoCE support when the rdma-core *dev*
# headers (verbs.h / rdma_cma.h) are missing, yielding a TCP-only build. On hosts
# with RDMA devices, require the headers up front instead of failing at runtime.
HAVE_RDMA=0
if compgen -G "/sys/class/infiniband/*" > /dev/null; then
HAVE_RDMA=1
if [ ! -f /usr/include/infiniband/verbs.h ] || [ ! -f /usr/include/rdma/rdma_cma.h ]; then
echo "ERROR: host has RDMA devices but the rdma-core dev headers are missing." >&2
echo "Install them first, e.g.: apt-get install -y libibverbs-dev librdmacm-dev" >&2
exit 1
fi
fi
WORKSPACE="$PROJECT_DIR/nixl_workspace"
mkdir -p "$WORKSPACE"
UCX_SRC="$WORKSPACE/ucx_source"
@@ -40,11 +53,23 @@ if [ ! -f "$UCX_INSTALL/lib/libucs.so" ]; then
--enable-devel-headers \
--enable-mt \
--with-verbs \
--with-rdmacm \
--with-cuda="$CUDA_PATH" \
--with-ze=no
make -j"$NPROC"
make install
echo "=== UCX installed to $UCX_INSTALL ==="
# Fail loudly if the IB transports didn't make it into the build.
if [ "$HAVE_RDMA" = 1 ]; then
ucx_transports=$(LD_LIBRARY_PATH="$UCX_INSTALL/lib:$UCX_INSTALL/lib/ucx:${LD_LIBRARY_PATH:-}" \
"$UCX_INSTALL/bin/ucx_info" -d)
if ! grep -q "Transport: rc_verbs" <<< "$ucx_transports"; then
echo "ERROR: UCX built without IB (rc_verbs) transport despite RDMA devices being present." >&2
echo "Check that libibverbs-dev / librdmacm-dev were present at configure time." >&2
exit 1
fi
fi
else
echo "=== UCX already built, skipping ==="
fi
+2 -3
View File
@@ -62,10 +62,10 @@ In TOML, an empty section header (`[ckpt]`) does the same.
## RL trainer token exports
For rollout debugging, enable trainer-side token export under `trainer.experimental.token_export` (or `experimental.token_export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence. Single-run/fallback exports go under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`; multi-run trainer exports with packer metadata go under the owning run directory, `output_dir/<run_id>/token_exports/step_<run_step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
```toml
[trainer.experimental.token_export]
enable_token_export = true
```
Leave it unset for normal training. When enabled, it exports every sequence from each exporting rank.
@@ -74,5 +74,4 @@ Leave it unset for normal training. When enabled, it exports every sequence from
- `packages/prime-rl-configs/src/prime_rl/` — config classes under `configs/`; `utils/config.py` re-exports `BaseConfig` and `cli`
- `configs/debug/` — minimal debug configs
- `configs/private/` — private configs submodule (internal)
- `examples/` — full example configs
+2 -4
View File
@@ -16,11 +16,9 @@ bash scripts/install.sh # clones, inits submodules, installs uv, runs `uv sync
For an existing clone, init submodules explicitly:
```bash
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init --recursive
```
Do **not** run `git submodule update --init --recursive` without paths — it tries to clone the private `configs/private` submodule and aborts for users without access. `scripts/install.sh` walks submodules one at a time and skips failures, so it works for everyone.
## Sync
```bash
@@ -29,7 +27,7 @@ uv sync --group dev # + pytest, ruff, pre-commit
uv sync --all-extras # recommended: envs, flash-attn, flash-attn-cute, etc.
```
The `envs` extra installs every env workspace listed in `[tool.uv.workspace]`. Adding a new env means adding it to `members`, the `envs` extra, and `[tool.uv.sources]`.
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]`.
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`.
+2
View File
@@ -383,6 +383,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
**mooncake_vars,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
)
else:
script = template.render(
@@ -405,6 +406,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
**mooncake_vars,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
+89
View File
@@ -17,11 +17,29 @@ def transformers_v5_compat():
_patch_qwen35_lora()
_patch_lora_key_prefix()
monkey_patch_nano_v3_reasoning_parser()
monkey_patch_deep_gemm_silu_mul_quant_int64()
monkey_patch_vllm_padded_input_scrub()
monkey_patch_return_routed_experts_with_nixl_connector()
def monkey_patch_nano_v3_reasoning_parser():
from vllm.reasoning.abs_reasoning_parsers import ReasoningParserManager
from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser
class NanoV3ReasoningParser(DeepSeekR1ReasoningParser):
def extract_reasoning(self, model_output, request):
reasoning_content, final_content = super().extract_reasoning(model_output, request)
chat_template_kwargs = getattr(request, "chat_template_kwargs", None)
if chat_template_kwargs and chat_template_kwargs.get("enable_thinking") is False and final_content is None:
reasoning_content, final_content = final_content, reasoning_content
return reasoning_content, final_content
ReasoningParserManager.register_module("nano_v3", module=NanoV3ReasoningParser)
def monkey_patch_return_routed_experts_with_nixl_connector():
from vllm import envs
from vllm.config.vllm import VllmConfig
@@ -66,6 +84,44 @@ def monkey_patch_return_routed_experts_with_nixl_connector():
logger.warning("Enabled vLLM routed-experts capture with NIXL connector patch.")
def monkey_patch_strip_routed_experts_from_chat():
"""Drop routed_experts from chat-completions responses.
routed_experts are only consumed via the serialized ``/generate``
(serving_tokens) path used for router-replay training, which encodes them as a
``{data, shape, start}`` object the PD router can merge. The stock
chat-completions path instead encodes them as a base64 ``np.save`` *string*,
which the PD router rejects ("prefill routed_experts must be an object with
base64 data and shape") and fails every eval rollout (evals go through chat
completions). ``enable_return_routed_experts`` is a server-wide model-config
flag with no per-request toggle, so strip the field on the chat path here.
"""
from vllm.entrypoints.openai.chat_completion.serving import OpenAIServingChat
from vllm.logger import init_logger
logger = init_logger(__name__)
if getattr(OpenAIServingChat.chat_completion_full_generator, "_prime_rl_strips_routed_experts", False):
return
_original = OpenAIServingChat.chat_completion_full_generator
async def _strip(result_generator):
async for res in result_generator:
for output in res.outputs:
output.routed_experts = None
yield res
async def _patched(self, request, result_generator, *args, **kwargs):
return await _original(self, request, _strip(result_generator), *args, **kwargs)
_patched._prime_rl_strips_routed_experts = True
OpenAIServingChat.chat_completion_full_generator = _patched
logger.info(
"Stripped routed_experts from chat-completions responses (PD router merges only the /generate object form)."
)
@triton.jit
def _silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel(
y_ptr,
@@ -836,3 +892,36 @@ def monkey_patch_fp32_lm_head():
LogitsProcessor.__init__ = _patched_init
LogitsProcessor._get_logits = _patched_get_logits
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
def monkey_patch_dp_coordinator_startup_timeout():
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 30s.
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
contention (seen on multi-node disaggregated GLM-5.1 launches). Configurable
via PRIME_DP_COORDINATOR_STARTUP_TIMEOUT (seconds, default 300).
"""
import multiprocessing.connection
import os
from vllm.v1.engine.coordinator import DPCoordinator
timeout = float(os.environ.get("PRIME_DP_COORDINATOR_STARTUP_TIMEOUT", "300"))
def _patched_wait_for_zmq_addrs(self, zmq_addr_pipe):
try:
ready = multiprocessing.connection.wait([zmq_addr_pipe, self.proc.sentinel], timeout=timeout)
if not ready:
raise RuntimeError(
f"DP Coordinator process failed to report ZMQ addresses within {timeout}s during startup."
)
try:
return zmq_addr_pipe.recv()
except EOFError:
raise RuntimeError("DP Coordinator process failed during startup.") from None
finally:
zmq_addr_pipe.close()
DPCoordinator._wait_for_zmq_addrs = _patched_wait_for_zmq_addrs
+16
View File
@@ -20,8 +20,11 @@ from prime_rl.utils.logger import get_logger
logger = get_logger()
from prime_rl.inference.patches import (
monkey_patch_dp_coordinator_startup_timeout,
monkey_patch_harmony_stop_token_propagation,
monkey_patch_load_lora_adapter,
monkey_patch_nano_v3_reasoning_parser,
monkey_patch_strip_routed_experts_from_chat,
monkey_patch_tokenize_params_validation,
monkey_patch_vllm_padded_input_scrub,
)
@@ -35,9 +38,22 @@ 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()
# NOTE: Register Nano V3 reasoning parser so configs can use
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
monkey_patch_nano_v3_reasoning_parser()
# NOTE: Optional mitigation for vLLM padded decode inputs until the native fix
# is available in our pinned runtime.
monkey_patch_vllm_padded_input_scrub()
# NOTE: routed_experts are consumed only via the serialized /generate path (router
# replay). The chat-completions path encodes them as a base64 np.save string the PD
# router cannot merge, which fails eval rollouts (they use chat completions). Strip
# 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
# 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()
logger = init_logger("vllm.entrypoints.openai.api_server")
+79 -3
View File
@@ -30,12 +30,17 @@ delegates to upstream so we track future vLLM changes for free.
from __future__ import annotations
from collections.abc import AsyncGenerator
from collections.abc import AsyncGenerator, AsyncIterable
from functools import cached_property
from typing import Any
from fastapi import Request
from vllm.entrypoints.openai.engine.protocol import ErrorResponse, RequestResponseMetadata
from vllm.entrypoints.openai.engine.protocol import (
ErrorResponse,
PromptTokenUsageInfo,
RequestResponseMetadata,
UsageInfo,
)
from vllm.entrypoints.serve.disagg.protocol import (
GenerateRequest,
GenerateResponse,
@@ -55,6 +60,12 @@ class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
class PrimeRlGenerateResponse(GenerateResponse):
choices: list[PrimeRlGenerateResponseChoice]
# Upstream ``GenerateResponse`` doesn't declare a ``usage`` field, so the
# parent ``ServingTokens.serve_tokens_full_generator`` constructs it and
# Pydantic silently drops it on serialization. Declare it here so the
# router can extract per-run token counts (and cached-prefix tokens) for
# platform billing — see https://github.com/PrimeIntellect-ai/router/pull/43.
usage: UsageInfo | None = None
class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
@@ -74,6 +85,49 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
)
class _FinalOutputCapture:
"""Wraps a ``RequestOutput`` async generator to record the last yielded item.
Needed so the response builder can construct a ``usage`` block from
``final_res.prompt_token_ids`` / ``output.token_ids`` / ``num_cached_tokens``
after delegating iteration to upstream.
"""
def __init__(self, source: AsyncIterable[RequestOutput]) -> None:
# ``source`` may be any async-iterable — including
# ``_GenerateRoutedExpertsCapture``, which exposes the protocol via
# ``async def __aiter__`` (an async generator function) and has no
# ``__anext__`` method. Drive it through ``async for`` rather than
# poking ``__anext__`` directly so both shapes work.
self._source = source
self.final_res: RequestOutput | None = None
async def __aiter__(self) -> AsyncGenerator[RequestOutput, None]:
async for item in self._source:
self.final_res = item
yield item
def _build_usage(final_res: RequestOutput) -> UsageInfo:
assert final_res.prompt_token_ids is not None
num_prompt_tokens = len(final_res.prompt_token_ids)
if final_res.encoder_prompt_token_ids is not None:
num_prompt_tokens += len(final_res.encoder_prompt_token_ids)
num_generated_tokens = sum(len(output.token_ids) for output in final_res.outputs)
usage = UsageInfo(
prompt_tokens=num_prompt_tokens,
completion_tokens=num_generated_tokens,
total_tokens=num_prompt_tokens + num_generated_tokens,
)
# Always emit cached tokens when vLLM reports any. Upstream gates this on
# ``enable_prompt_tokens_details`` (default False) for OpenAI-API compat,
# but ``/inference/v1/generate`` is prime-rl internal — the cache-discount
# billing pipeline always wants the cached subset surfaced.
if final_res.num_cached_tokens:
usage.prompt_tokens_details = PromptTokenUsageInfo(cached_tokens=final_res.num_cached_tokens)
return usage
async def _client_set_max_tokens(raw_request: Request | None) -> bool:
"""Whether the inbound JSON body carried ``sampling_params.max_tokens``.
@@ -273,11 +327,33 @@ class PrimeRlServingTokens(ServingTokens):
)
result_generator = capture
# Always capture the final ``RequestOutput`` so we can attach a
# ``usage`` block to the response. The router parses ``usage`` for
# per-run billing metrics; without it the cache-discount counter
# (``vllm_router_run_cached_prompt_tokens_total``) stays at zero.
final_capture = _FinalOutputCapture(result_generator)
result_generator = final_capture
response = await super().serve_tokens_full_generator(
request, result_generator, request_id, model_name, request_metadata
)
if capture is not None and isinstance(response, GenerateResponse):
if not isinstance(response, GenerateResponse):
return response
if capture is not None:
response = capture.post_process(response)
elif not isinstance(response, PrimeRlGenerateResponse):
# Upgrade to the prime-rl subclass so the declared ``usage`` field
# actually surfaces in JSON (the parent class would drop it).
response = PrimeRlGenerateResponse(
request_id=response.request_id,
choices=[PrimeRlGenerateResponseChoice(**choice.model_dump()) for choice in response.choices],
prompt_logprobs=response.prompt_logprobs,
kv_transfer_params=response.kv_transfer_params,
)
if final_capture.final_res is not None:
response.usage = _build_usage(final_capture.final_res)
return response
+29 -60
View File
@@ -5,8 +5,6 @@ from typing import TYPE_CHECKING, Callable
import torch
import verifiers as vf
from jaxtyping import Float
from torch import Tensor
if TYPE_CHECKING:
from prime_rl.orchestrator.types import TrainRollout
@@ -14,11 +12,9 @@ if TYPE_CHECKING:
from prime_rl.configs.orchestrator import (
AdvantageConfig,
CustomAdvantageConfig,
LengthPenaltyConfig,
TokensLengthPenaltyConfig,
TurnsLengthPenaltyConfig,
LinearLengthPenaltyConfig,
)
from prime_rl.orchestrator.utils import get_model_completion_len, get_tool_response_len
from prime_rl.orchestrator.utils import get_model_completion_len
from prime_rl.utils.utils import import_object
@@ -50,68 +46,36 @@ entry per rollout. `assign_advantages` calls it on one already-grouped cohort.
def default_advantage_fn(
inputs: AdvantageInputs,
length_penalty: LengthPenaltyConfig | None = None,
length_penalty: LinearLengthPenaltyConfig | None = None,
max_seq_len: int | None = None,
length_weighted_baseline: bool = False,
) -> AdvantageOutputs:
"""Default GRPO advantage for a single group: reward minus per-group baseline.
`length_penalty` enables correctness-gated efficiency shaping over a per-rollout
cost: tokens (weighted completion + tool-response) or trajectory turn count.
``length_penalty`` subtracts ``coef * pass_rate * (completion tokens / max_seq_len)``
from each reward (``pass_rate`` = group mean reward), optionally gated to correct
(``reward == 1``) rollouts. ``length_weighted_baseline`` uses the token-length-weighted
mean reward as the baseline instead of the plain mean.
"""
rewards = torch.tensor([r["reward"] for r in inputs.rollouts], dtype=torch.float32)
lengths = torch.tensor([get_model_completion_len(r) for r in inputs.rollouts], dtype=rewards.dtype)
if isinstance(length_penalty, TokensLengthPenaltyConfig):
w_c = length_penalty.completion_weight
w_t = length_penalty.tool_response_weight
costs = torch.tensor(
[w_c * get_model_completion_len(r) + w_t * get_tool_response_len(r) for r in inputs.rollouts],
dtype=rewards.dtype,
)
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
if isinstance(length_penalty, TurnsLengthPenaltyConfig):
costs = torch.tensor([len(r["trajectory"]) for r in inputs.rollouts], dtype=rewards.dtype)
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
if length_penalty is not None:
if max_seq_len is None:
raise ValueError("max_seq_len is required when length_penalty is enabled")
penalty = length_penalty.coef * rewards.mean() * (lengths / max_seq_len)
if length_penalty.gate_by_correctness:
penalty = penalty * rewards
rewards = rewards - penalty
return AdvantageOutputs(advantages=(rewards - rewards.mean()).tolist())
if length_weighted_baseline:
baseline = (lengths * rewards).sum() / lengths.sum()
else:
baseline = rewards.mean()
return AdvantageOutputs(advantages=(rewards - baseline).tolist())
def _efficiency_shaping(
rewards: Float[Tensor, "group_size"],
costs: Float[Tensor, "group_size"],
) -> Float[Tensor, "group_size"]:
"""Correctness-gated efficiency shaping with bounded advantages.
Shapes rewards with a bounded efficiency bonus before standard GRPO subtraction,
preserving zero-mean advantages within the group. `costs` is a per-rollout cost
(e.g., completion length in tokens or number of turns).
Correct rollouts get reward amplified by up to 2x based on relative efficiency.
Incorrect rollouts are untouched. Lower-cost correct rollouts get higher advantage.
"""
max_reward = rewards.max()
correct_mask = rewards >= max_reward
num_correct = correct_mask.sum()
# No shaping when max reward is 0 — no correct rollouts to differentiate
if max_reward <= 0:
return rewards - rewards.mean()
# Mean cost of correct rollouts
mean_correct_cost = (costs * correct_mask).sum() / num_correct.clamp(min=1)
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above.
# When mean_correct_cost is 0 (e.g. tool-only shaping with no harness metric, or
# all-zero turn counts), no rollouts can be differentiated — fall back to no bonus.
if mean_correct_cost <= 0:
return rewards - rewards.mean()
bonus = (1 - costs / mean_correct_cost).clamp(0, 1)
# Shape rewards: correct rollouts amplified by up to 2x, incorrect untouched
shaped_rewards = rewards * (1 + bonus * correct_mask)
return shaped_rewards - shaped_rewards.mean()
def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
def setup_advantage_fn(config: AdvantageConfig, max_seq_len: int | None = None) -> AdvantageFn:
"""Setup advantage function from config."""
if isinstance(config, CustomAdvantageConfig):
custom_fn = import_object(config.import_path)
@@ -123,7 +87,12 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
return advantage_fn
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
return default_advantage_fn(inputs, length_penalty=config.length_penalty)
return default_advantage_fn(
inputs,
length_penalty=config.length_penalty,
max_seq_len=max_seq_len,
length_weighted_baseline=config.length_weighted_baseline,
)
return advantage_fn
+42 -29
View File
@@ -11,8 +11,11 @@
schedule next. Transitions are level-triggered (driven by the eval
source's emptiness), so in-flight rollouts of the opposite kind drain
naturally on either side of an eval boundary.
- ``on_new_version`` (called by the watcher) bumps ``off_policy_steps`` on
every in-flight rollout and drops groups past ``max_off_policy_steps``.
- ``on_version_pending`` (called by the watcher before the engines pause for
the weight update) bumps ``off_policy_steps`` on in-flight train rollouts and
drops groups past ``max_off_policy_steps``.
Eval rollouts are measurements for the policy version they started with,
so they are allowed to finish even if training advances.
Cancellations surface as synthetic ``Cancelled`` markers so the sink's
count-to-``group_size`` finalization still fires.
"""
@@ -114,7 +117,7 @@ class RolloutDispatcher:
"""``await dispatcher.start()`` runs the dispatch loop until ``stop()``.
Pulls examples from ``TrainSource`` / ``EvalSource``, schedules
rollouts under shared capacity, and emits ``FinishedRollout``\\ s to
``out_q``. The watcher drives ``on_new_version`` for off-policy
``out_q``. The watcher drives ``on_version_pending`` for off-policy
cancellation; the orchestrator triggers eval epochs."""
def __init__(
@@ -131,6 +134,7 @@ class RolloutDispatcher:
tasks_per_minute: float | None,
max_off_policy_steps: int,
training_mode: Literal["rl", "opd", "sft"],
use_cache_salt: bool = True,
) -> None:
self.policy = policy
self.train_envs = train_envs
@@ -142,6 +146,7 @@ class RolloutDispatcher:
self.train_source = train_source
self.eval_source = eval_source
self.training_mode = training_mode
self.use_cache_salt = use_cache_salt
self.max_off_policy_steps = max_off_policy_steps
self.max_inflight = max_inflight_rollouts
@@ -259,35 +264,44 @@ class RolloutDispatcher:
await safe_cancel(self.task)
self.task = None
async def on_new_version(self, step: int) -> None:
async def on_version_pending(self, step: int) -> None:
"""Bump off-policy counters and drop groups past
``max_off_policy_steps`` (drop_group emits ``Cancelled`` markers so
the sink still finalizes the partial group)."""
stale_groups: dict[uuid.UUID, RolloutKind] = {}
cancelled_by_kind: dict[RolloutKind, int] = {"train": 0, "eval": 0}
the sink still finalizes the partial group). Eval rollouts are not
aged because they are tied to their start-time policy version.
Runs *before* the inference engines are paused for the weight update so
the resulting aborts are processed while the engine is still stepping —
otherwise the orphaned KV transfers crash the decode engine on resume
(see ``WeightWatcher.apply_policy_update``)."""
stale_groups: set[uuid.UUID] = set()
cancelled = 0
for meta in self.inflight.values():
if meta.kind != "train":
continue
meta.off_policy_steps += 1
if meta.off_policy_steps > self.max_off_policy_steps:
stale_groups[meta.group_id] = meta.kind
stale_groups.add(meta.group_id)
for gid, kind in stale_groups.items():
for gid in stale_groups:
removed = await self.drop_group(gid)
cancelled_by_kind[kind] += removed
cancelled += removed
for kind in ("train", "eval"):
n = cancelled_by_kind[kind]
if n:
get_logger().warning(
f"Cancelled {n} {kind} rollouts past max_off_policy_steps={self.max_off_policy_steps}. "
"Consider increasing it to avoid this."
)
if cancelled:
get_logger().warning(
f"Cancelled {cancelled} train rollouts past max_off_policy_steps={self.max_off_policy_steps}. "
"Consider increasing it to avoid this."
)
async def on_new_version(self, step: int) -> None:
"""No-op: the dispatcher drains in ``on_version_pending`` (pre-pause)."""
async def fill_inflight(self) -> None:
"""Schedule new rollouts up to ``max_inflight``, honoring
``self.mode``. When ``PREFER_EVAL``'s source exhausts we flip back
to ``PREFER_TRAIN`` so the eval tail drains alongside fresh train."""
if not self.dispatch_allowed.is_set():
return
``self.mode``. Eval scheduling ignores the orchestrator's dispatch
gate (evals are version-pinned measurements); only train scheduling
respects it. When ``PREFER_EVAL``'s source exhausts we flip back to
``PREFER_TRAIN`` so the eval tail drains alongside fresh train."""
while True:
if self.available_permits <= 0:
return
@@ -308,7 +322,9 @@ class RolloutDispatcher:
scheduled = await self.try_schedule("eval")
if not scheduled:
return
else: # PREFER_TRAIN
else: # PREFER_TRAIN — respects the orchestrator's dispatch gate
if not self.dispatch_allowed.is_set():
return
scheduled = await self.try_schedule("train")
if not scheduled:
return
@@ -408,13 +424,10 @@ class RolloutDispatcher:
if env_collection is None:
return False
env = env_collection.get(group.env_name)
# SFT-mode train rollouts hit the frozen teacher pool; salting per
# policy version would invalidate the teacher's prefix cache every
# weight update for no reason.
if self.training_mode == "sft" and group.kind == "train":
cache_salt = None
else:
if group.kind == "eval" or self.use_cache_salt:
cache_salt = str(group.policy_version_at_start)
else:
cache_salt = None
if env.requires_group_scoring:
permits = group.rollouts_to_schedule
@@ -598,7 +611,7 @@ class RolloutDispatcher:
# markers for those too so the sink hits ``target_rollouts``
#
# ``last_meta`` can be ``None`` if the only inflight task for this
# group completed naturally between ``on_new_version``'s snapshot
# group completed naturally between ``on_version_pending``'s snapshot
# and us reaching it — synthesize a stand-in from the group state
unscheduled_cancelled = 0
if group is not None and group.rollouts_to_schedule > 0:
+11 -152
View File
@@ -1,24 +1,19 @@
from __future__ import annotations
import asyncio
import atexit
import multiprocessing as mp
import time
from collections.abc import Awaitable, Callable, Iterator, Sequence
from collections.abc import Iterator, Sequence
from multiprocessing.process import BaseProcess
from pathlib import Path
from typing import Generic, TypeVar
import pandas as pd
import verifiers as vf
from verifiers.serve import ZMQEnvClient, ZMQEnvServer
from verifiers.utils.serve_utils import get_free_port
from prime_rl.configs.orchestrator import EnvConfig, EvalEnvConfig, TrainEnvConfig
from prime_rl.orchestrator.eval_utils import compute_pass_at_k
from prime_rl.utils.logger import ProgressTracker, get_logger
from prime_rl.utils.monitor import get_monitor
from prime_rl.utils.utils import capitalize
from prime_rl.orchestrator.advantage import AdvantageFn, setup_advantage_fn
from prime_rl.utils.logger import get_logger
REQUIRED_STATE_COLUMNS = ["trajectory"]
@@ -167,9 +162,14 @@ class Env:
class TrainEnv(Env):
config: TrainEnvConfig
def __init__(self, config: TrainEnvConfig):
def __init__(self, config: TrainEnvConfig, max_seq_len: int):
super().__init__(config)
self.sampling_args = config.sampling.to_sampling_args()
# Built once — custom advantage funcs do an ``import_object`` we don't
# want to pay per group. ``None`` = reward-only path.
self.advantage_fn: AdvantageFn | None = (
setup_advantage_fn(config.advantage, max_seq_len=max_seq_len) if config.advantage is not None else None
)
def get_dataset(self, seed: int | None = None):
return self.env.get_dataset(seed=seed)
@@ -183,147 +183,6 @@ class EvalEnv(Env):
self.sampling_args = config.sampling.to_sampling_args()
self.examples = self.env.get_eval_dataset(n=config.num_examples).to_list()
async def evaluate(
self,
model_name: str,
get_client: Callable[[], Awaitable[vf.ClientConfig]],
step: int,
cache_salt: str,
) -> list[vf.RolloutOutput]:
num_examples = len(self.examples)
group_size = self.config.group_size
get_logger().info(f"Evaluating {self.name} ({num_examples=}, {group_size=})")
total_rollouts = num_examples * group_size
pbar = ProgressTracker(total=total_rollouts, desc=f"Evaluating {self.name}")
eval_start = time.perf_counter()
if self.requires_group_scoring:
async def run_with_progress(example: dict) -> list[vf.RolloutOutput] | None:
"""Run group_size rollouts as a scored group for one example."""
try:
client = await get_client()
outputs = await self.run_group(
client=client,
example=example,
model_name=model_name,
group_size=group_size,
cache_salt=cache_salt,
)
pbar.update(group_size)
return outputs
except Exception as e:
get_logger().warning(f"Group failed: {e}")
pbar.update(group_size)
return None
coros = [run_with_progress(example) for example in self.examples]
else:
async def run_with_progress(example: dict) -> list[vf.RolloutOutput] | None:
"""Run a single rollout for one example."""
try:
client = await get_client()
output = await self.run_rollout(
client=client, example=example, model_name=model_name, cache_salt=cache_salt
)
pbar.update(1)
return [output]
except Exception as e:
get_logger().warning(f"Rollout failed: {e}")
pbar.update(1)
return None
coros = [run_with_progress(example) for example in self.examples for _ in range(group_size)]
try:
results = await asyncio.gather(*coros)
finally:
pbar.close()
successful_outputs = [o for group in results if group is not None for o in group]
failed_count = total_rollouts - len(successful_outputs)
eval_time = time.perf_counter() - eval_start
if failed_count:
get_logger().warning(
f"{failed_count}/{total_rollouts} ({failed_count / total_rollouts * 100:.1f}%) rollouts failed"
)
if not successful_outputs:
get_logger().warning(f"All rollouts failed for {self.name}, skipping logging metrics")
get_monitor().log(
{
f"eval/{self.name}/failed_rollouts": failed_count / total_rollouts,
"step": step,
},
step=step,
)
return []
# Log metrics
monitor = get_monitor()
rows = [
{
"example_id": o["example_id"],
"reward": o["reward"],
"completion_len": o["token_usage"]["final_output_tokens"],
"is_truncated": o["is_truncated"],
"has_error": o.get("error") is not None,
"no_response": not o.get("completion"),
}
for o in successful_outputs
]
results_df = pd.DataFrame(rows)
unique_rewards = results_df.reward.dropna().unique()
could_be_binary = set(unique_rewards).issubset({0.0, 1.0})
if could_be_binary:
pass_at_k = (
results_df.groupby("example_id")
.apply(lambda x: compute_pass_at_k(x.reward.dropna()), include_groups=False)
.apply(pd.Series)
)
else:
pass_at_k = None
get_logger().warning("Skipping computing pass@k rates because the task rewards appear to be non-binary")
message = f"Evaluated {self.name} in {eval_time:.2f}s (Avg@{group_size}={results_df.reward.mean():.4f}"
if could_be_binary:
assert pass_at_k is not None
for pass_rate, pass_rate_score in pd.Series(pass_at_k.mean()).items():
message += f", {capitalize(str(pass_rate))}: {pass_rate_score:.4f}"
message += (
f", No-response: {results_df.no_response.mean() * 100:.1f}%"
f", Completion Length: {results_df.completion_len.mean():.2f} (±{results_df.completion_len.std():.2f}, ∈[{results_df.completion_len.min():.2f}, {results_df.completion_len.max():.2f}])"
f", Truncated: {results_df.is_truncated.mean() * 100:.1f}%)"
)
get_logger().success(message)
eval_metrics = {
f"avg@{group_size}": float(results_df.reward.mean()),
"no_response/mean": float(results_df.no_response.mean()),
"no_response/count": int(results_df.no_response.sum()),
"completion_len/mean": results_df.completion_len.mean().item(),
"completion_len/max": results_df.completion_len.max().item(),
"completion_len/min": results_df.completion_len.min().item(),
"is_truncated/mean": results_df.is_truncated.mean().item(),
"failed_rollouts": failed_count / total_rollouts,
"time": eval_time,
}
if could_be_binary:
assert pass_at_k is not None
eval_metrics.update(pd.Series(pass_at_k.mean()).to_dict())
eval_metrics = {f"eval/{self.name}/{key}": v for key, v in eval_metrics.items()}
eval_metrics["step"] = step
monitor.log(eval_metrics, step=step)
monitor.log_eval_samples(successful_outputs, env_name=self.name, step=step)
return successful_outputs
EnvT = TypeVar("EnvT", bound=Env)
@@ -387,10 +246,10 @@ class Envs(Generic[EnvT]):
class TrainEnvs(Envs[TrainEnv]):
"""Collection of training environments."""
def __init__(self, configs: Sequence[TrainEnvConfig]):
def __init__(self, configs: Sequence[TrainEnvConfig], max_seq_len: int):
self._envs: dict[str, TrainEnv] = {}
for config in configs:
env = TrainEnv(config)
env = TrainEnv(config, max_seq_len=max_seq_len)
self._envs[env.name] = env
+32 -2
View File
@@ -1,4 +1,9 @@
"""MetricsBuilder: assembles the per-step W&B dict. No I/O, no side effects."""
"""MetricsBuilder: assembles the per-step W&B dict.
The only I/O / state is the trainer's token-export metrics, which lag the
orchestrator: ``build`` folds in the oldest unlogged stable step it finds on
disk and tracks the last step logged so it never re-logs one.
"""
from __future__ import annotations
@@ -7,12 +12,16 @@ from typing import Any
import pandas as pd
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.token_export_metrics import collect_next_token_export_metrics
from prime_rl.orchestrator.types import Progress, TrainBatchMetrics, TrainRollout
class MetricsBuilder:
def __init__(self, config: OrchestratorConfig) -> None:
def __init__(self, config: OrchestratorConfig, start_step: int = 0) -> None:
self.config = config
# Token exports are read back one step behind the orchestrator; track the
# last run step whose metrics we've folded in so we never re-log a step.
self._last_token_export_step_logged = start_step - 1
def build(
self,
@@ -179,8 +188,29 @@ class MetricsBuilder:
for name, count in pre_filter_dropped_by_name.items():
to_log[f"pre_filters/all/{name}/rate"] = count / pre_filter_seen
# Fold in the trainer's token-export metrics for the oldest unlogged stable
# step (exports always lag the orchestrator, so this is a past step).
to_log.update(self.next_token_export_metrics())
return to_log
@property
def last_token_export_step_logged(self) -> int:
return self._last_token_export_step_logged
def next_token_export_metrics(self) -> dict[str, float | int]:
"""Log-ready token-export metrics for the next unlogged stable step (empty if
none), advancing the cursor. They arrive under trainer/, including trainer/step
(the run step they belong to) for plotting against a lag-corrected axis. Shared
by build() and the orchestrator's end-of-run drain."""
token_export = collect_next_token_export_metrics(
self.config.output_dir,
last_logged_step=self._last_token_export_step_logged,
)
if token_export:
self._last_token_export_step_logged = token_export["trainer/step"]
return token_export
@staticmethod
def timing_df(rollouts: list[TrainRollout]) -> pd.DataFrame:
return pd.DataFrame(
+62 -14
View File
@@ -108,6 +108,11 @@ MAX_CONSECUTIVE_EMPTY_BATCHES = 10
# resumed when the watcher advances ``policy.version``.
TARGET_LAG = 1
# After max_steps, how long to wait for the trainer to finalize the trailing
# token-export steps it hadn't flushed yet, and how often to poll for them.
TOKEN_EXPORT_DRAIN_TIMEOUT_S = 300.0
TOKEN_EXPORT_DRAIN_POLL_S = 2.0
class Orchestrator:
# Set in ``__init__``
@@ -263,7 +268,7 @@ class Orchestrator:
post_filters = setup_filters(config.post_batch_filters, vocab_size=self.tokenizer.vocab_size, kind="post-batch")
get_logger().info("Loading training environments")
self.train_envs = TrainEnvs(config.train.env)
self.train_envs = TrainEnvs(config.train.env, max_seq_len=config.seq_len)
if config.training_mode == "sft":
for env in self.train_envs:
env.sampling_args.pop("logprobs", None)
@@ -345,13 +350,14 @@ class Orchestrator:
else:
get_logger().info("Training from scratch")
# SFT generates rollouts via the teacher (the student is trained on
# the teacher's outputs); RL / OPD generate via the student
if config.training_mode == "sft":
assert self.teacher_inference is not None, "sft mode requires teacher inference"
# SFT train rollouts come from the teacher when configured; otherwise
# they use the existing student rollout pool.
if config.training_mode == "sft" and self.teacher_inference is not None:
rollout_inference = self.teacher_inference
use_cache_salt = False
else:
rollout_inference = self.student_inference
use_cache_salt = True
self.train_source = TrainSource(self.train_envs, seed=42)
self.eval_source: EvalSource | None = (
@@ -379,8 +385,9 @@ class Orchestrator:
tasks_per_minute=config.tasks_per_minute,
max_off_policy_steps=config.max_off_policy_steps,
training_mode=config.training_mode,
use_cache_salt=use_cache_salt,
)
self.metrics = MetricsBuilder(config)
self.metrics = MetricsBuilder(config, start_step=self.progress.step)
self.train_sink = TrainSink(
config,
tokenizer=self.tokenizer,
@@ -389,7 +396,6 @@ class Orchestrator:
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
batch_size=config.batch_size,
token_batch_size=config.token_batch_size,
advantage_config=config.advantage,
pre_filters=pre_filters,
post_filters=post_filters,
)
@@ -459,6 +465,7 @@ class Orchestrator:
clean_exit = False
try:
await self.main_loop()
await self._drain_token_export_metrics()
clean_exit = True
finally:
elapsed = format_time(time.perf_counter() - start_time)
@@ -499,7 +506,7 @@ class Orchestrator:
assert self.eval_sink is not None # eval rollouts only emitted when eval is configured
eval_batch = self.eval_sink.add(rollout)
if eval_batch is not None:
self.finalize_eval_batch(eval_batch)
await self.finalize_eval_batch(eval_batch)
continue
assert isinstance(rollout, TrainRollout)
@@ -509,6 +516,35 @@ class Orchestrator:
if train_batch is not None and not self.draining and not self.stopped.is_set():
await self.finalize_train_batch(train_batch)
async def _drain_token_export_metrics(self) -> None:
"""Token exports lag the orchestrator, so once the loop ends the trainer is
still finalizing the last shipped steps and ``build`` no longer runs to pick
them up. Poll for the remaining stable steps up to ``max_steps - 1`` and log
each under its own ``trainer/step`` (a local W&B step axis, so the final
checkpoint's ``progress.step`` is untouched)."""
if self.config.max_steps is None:
return
if not (self.config.output_dir / "token_exports").exists():
return # token export not enabled for this run — don't block shutdown
target = self.config.max_steps - 1
if self.metrics.last_token_export_step_logged >= target:
return # build() already kept up — nothing trailing to flush
wandb_step = self.progress.step
deadline = time.perf_counter() + TOKEN_EXPORT_DRAIN_TIMEOUT_S
while time.perf_counter() < deadline:
token_export = self.metrics.next_token_export_metrics()
if not token_export:
await asyncio.sleep(TOKEN_EXPORT_DRAIN_POLL_S)
continue
self.monitor.log(token_export, step=wandb_step)
wandb_step += 1
if self.metrics.last_token_export_step_logged >= target:
return
get_logger().warning(
f"Token-export drain timed out before step {target} "
f"(last logged {self.metrics.last_token_export_step_logged})"
)
async def finalize_train_batch(self, batch: TrainBatch) -> None:
"""Ship one ``TrainBatch`` out to the trainer and handle the I/O
side-effects (ckpt, save_rollouts, teacher logprobs, sender.send,
@@ -761,7 +797,7 @@ class Orchestrator:
)
get_logger().success("\n\t\t ".join(lines))
def finalize_eval_batch(self, batch: EvalBatch) -> None:
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch (save_rollouts,
monitor.log_eval_samples, monitor.log)."""
if not batch.rollouts:
@@ -770,24 +806,32 @@ class Orchestrator:
rollout_dicts = [r.to_dict() for r in batch.rollouts]
step_path = get_step_path(get_rollout_dir(self.config.output_dir), batch.step)
save_rollouts(
await asyncio.to_thread(
save_rollouts,
rollout_dicts,
step_path / f"eval_rollouts_{batch.env_name}.jsonl",
exclude_keys={"trajectory"},
)
self.monitor.log_eval_samples(rollout_dicts, env_name=batch.env_name, step=batch.step)
self.monitor.log(batch.metrics.to_wandb_dict(env_name=batch.env_name, step=batch.step), step=batch.step)
policy_versions = {r.policy_version for r in batch.rollouts}
policy_version = min(policy_versions)
if len(policy_versions) > 1:
get_logger().warning(
f"Eval {batch.env_name} step {batch.step} had mixed policy versions: {sorted(policy_versions)}"
)
metrics = batch.metrics.to_wandb_dict(env_name=batch.env_name, step=batch.step)
metrics[f"eval/{batch.env_name}/policy_version"] = float(policy_version)
self.monitor.log(metrics, step=batch.step)
n_total = batch.metrics.n_rollouts
error_rate = ((batch.metrics.n_cancelled + batch.metrics.n_errored) / n_total) if n_total else 0.0
max_off_policy = max((r.off_policy_steps for r in batch.rollouts), default=0)
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
get_logger().success(
f"Evaluated {batch.env_name} (Step {batch.step}) | "
f"{format_time(elapsed):>7} | Reward {batch.metrics.reward_mean:.4f} | "
f"Turns {batch.metrics.num_turns_mean:.1f} | Max Off-Policy {max_off_policy} | "
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {batch.metrics.reward_mean:.4f} | "
f"Turns {batch.metrics.num_turns_mean:.1f} | "
f"Error {error_rate:.1%} | Truncation {batch.metrics.truncation_rate:.1%}"
)
@@ -832,6 +876,10 @@ class Orchestrator:
get_logger().info("Resuming dispatcher")
gate.set()
async def on_version_pending(self, step: int) -> None:
"""No-op: the dispatch gate is re-evaluated in ``on_new_version`` once
the new policy version is live."""
async def on_new_version(self, step: int) -> None:
"""``VersionObserver`` hook: the watcher just advanced ``policy.version``;
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
@@ -0,0 +1,116 @@
from __future__ import annotations
import json
import math
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from prime_rl.utils.logger import get_logger
TOKEN_EXPORT_METRIC_FIELDS = ("mismatch_kl", "entropy")
@dataclass
class _Stats:
total: float = 0.0
count: int = 0
maximum: float = -math.inf
def add(self, value: Any) -> None:
if not isinstance(value, int | float):
return
value = float(value)
if not math.isfinite(value):
return
self.total += value
self.count += 1
self.maximum = max(self.maximum, value)
def as_metrics(self, prefix: str) -> dict[str, float]:
if self.count == 0:
return {}
return {
f"{prefix}/mean": self.total / self.count,
f"{prefix}/max": self.maximum,
}
def collect_next_token_export_metrics(output_dir: Path, *, last_logged_step: int) -> dict[str, float | int]:
"""Log-ready metrics for the oldest unlogged stable step, namespaced under
``trainer/`` and stamped with ``trainer/step`` (the run step they belong to).
Empty when there is no new stable step."""
stable_steps = [step for step in _stable_token_export_steps(output_dir) if step > last_logged_step]
if not stable_steps:
return {}
step = min(stable_steps)
metrics: dict[str, float | int] = {
f"trainer/{key}": value for key, value in collect_token_export_metrics(output_dir, step).items()
}
metrics["trainer/step"] = step
return metrics
def collect_token_export_metrics(output_dir: Path, step: int) -> dict[str, float | int]:
step_dir = output_dir / "token_exports" / f"step_{step}"
if not (step_dir / "STABLE").exists():
return {}
stats_by_key: dict[str, _Stats] = {}
sequence_count = 0
skipped_count = 0
for export_file in sorted(step_dir.glob("rank_*.jsonl")):
with export_file.open(encoding="utf-8") as file:
for line in file:
if not line.strip():
continue
# Token exports are best-effort monitoring; a malformed line or a
# length-mismatched record shouldn't abort the orchestrator step.
try:
record = json.loads(line)
values_by_field = {field: _loss_token_values(record, field) for field in TOKEN_EXPORT_METRIC_FIELDS}
except ValueError:
skipped_count += 1
continue
sequence_count += 1
for field, values in values_by_field.items():
for value in values:
stats_by_key.setdefault(field, _Stats()).add(value)
if skipped_count:
get_logger().warning(f"Skipped {skipped_count} malformed token-export record(s) in {step_dir}")
metrics: dict[str, float | int] = {}
if sequence_count == 0:
return metrics
for key, stats in sorted(stats_by_key.items()):
metrics.update(stats.as_metrics(key))
return metrics
def _stable_token_export_steps(output_dir: Path) -> list[int]:
token_exports_dir = output_dir / "token_exports"
if not token_exports_dir.exists():
return []
steps = []
for step_dir in token_exports_dir.glob("step_*"):
if not (step_dir / "STABLE").exists():
continue
try:
steps.append(int(step_dir.name.removeprefix("step_")))
except ValueError:
continue
return sorted(steps)
def _loss_token_values(record: dict[str, Any], field: str) -> list[Any]:
loss_mask = record.get("loss_mask", [])
values = record.get(field, [])
if len(loss_mask) != len(values):
raise ValueError(
f"Token export record has mismatched loss_mask and {field} lengths: {len(loss_mask)} != {len(values)}"
)
return [value for value, keep in zip(values, loss_mask) if keep]
+3 -7
View File
@@ -17,8 +17,8 @@ import asyncio
import uuid
from collections import defaultdict
from prime_rl.configs.orchestrator import AdvantageConfig, OrchestratorConfig
from prime_rl.orchestrator.advantage import assign_advantages, setup_advantage_fn
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.advantage import assign_advantages
from prime_rl.orchestrator.envs import TrainEnvs
from prime_rl.orchestrator.filters import RolloutFilter, apply_filters
from prime_rl.orchestrator.trajectories import (
@@ -44,7 +44,6 @@ class TrainSink:
mm_token_type_ids_mapping: dict[int, int] | None,
batch_size: int | None,
token_batch_size: int | None,
advantage_config: AdvantageConfig | None,
pre_filters: list[RolloutFilter],
post_filters: list[RolloutFilter],
) -> None:
@@ -58,9 +57,6 @@ class TrainSink:
self.mm_token_type_ids_mapping = mm_token_type_ids_mapping
self.batch_size = batch_size
self.token_batch_size = token_batch_size
# Built once — custom advantage funcs do an ``import_object`` and
# we don't want to pay that per group. ``None`` = reward-only path
self.advantage_fn = setup_advantage_fn(advantage_config) if advantage_config is not None else None
self.pre_filters = pre_filters
self.post_filters = post_filters
@@ -200,7 +196,7 @@ class TrainSink:
)
return
assign_advantages(survivors, self.advantage_fn)
assign_advantages(survivors, self.train_envs.get(env_name).advantage_fn)
# Propagate to the pre-tokenized samples so the orchestrator can
# collect samples at ship time without re-walking rollouts. The env
+7 -2
View File
@@ -202,7 +202,12 @@ class EvalBatch:
class VersionObserver(Protocol):
"""Notified after each policy update; walked by the watcher after it
mutates ``Policy``."""
"""Notified around each policy update; walked by the watcher.
``on_version_pending`` fires *before* the inference engines are paused for
the weight update; ``on_new_version`` fires *after* the new weights are live
and ``Policy`` has been mutated."""
async def on_version_pending(self, step: int) -> None: ...
async def on_new_version(self, step: int) -> None: ...
+18
View File
@@ -92,6 +92,24 @@ class WeightWatcher:
f"Orchestrator resumed: checkpoint {next_step} ready (after {format_time(self.last_wait_for_ckpt_time)})"
)
# Drain off-policy rollouts BEFORE pausing the inference engines.
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
# ``_reqs_not_processed``), which is only propagated to the workers
# while the engine is stepping. If we drain after resume instead,
# the aborts race with the flush of KV transfers that completed
# during the pause and trip ``assert req_id in self.requests`` in
# the decode scheduler's ``_update_from_kv_xfer_finished`` — killing
# the engine and cascading to every DP rank. Draining first lets the
# aborts settle under normal stepping. ``on_new_version`` (below)
# still runs post-update for observers that need the live version.
for observer in self.observers:
try:
await observer.on_version_pending(next_step)
except Exception as exc:
get_logger().warning(
f"Observer {type(observer).__name__}.on_version_pending({next_step}) raised: {exc!r}"
)
get_logger().debug(f"Updating weights to step {next_step}")
t1 = time.perf_counter()
await self.inference.update_weights(weights_path, lora_name=self.lora_name, step=next_step)
+21 -2
View File
@@ -51,6 +51,7 @@ export PROJECT_DIR={{ project_dir }}
export CONFIG_PATH={{ config_path }}
export OUTPUT_DIR={{ output_dir }}
mkdir -p $OUTPUT_DIR/logs/inference
rm -f $OUTPUT_DIR/logs/inference/*.log
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
# General
@@ -194,10 +195,28 @@ srun --kill-on-bad-exit=1 bash -c '
export VLLM_MOE_USE_DEEP_GEMM=1
{%- endif %}
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:False"
export GLOO_SOCKET_IFNAME=bond0
# Bind gloo to the interface that owns LOCAL_IP (the rendezvous IP) — NIC
# names vary across clusters (bond0, eth0, ...). If the lookup fails, leave
# GLOO_SOCKET_IFNAME unset so gloo falls back to its own detection.
GLOO_IFNAME=$(ip -o -4 addr show to "$LOCAL_IP" 2>/dev/null | awk "{print \$2; exit}")
if [ -n "$GLOO_IFNAME" ]; then export GLOO_SOCKET_IFNAME=$GLOO_IFNAME; fi
export VLLM_ENGINE_READY_TIMEOUT_S=4200
export UCX_TLS=all
export UCX_NET_DEVICES=all
# Enumerate RDMA NICs for UCX/NIXL from sysfs (ibv_devices is not on the job
# PATH). Prefer InfiniBand ports and fall back to RoCE: "all" would also pick
# up non-functional devices (e.g. an Ethernet bond UCX cannot open), which
# fails NIXL backend creation. Hosts without RDMA devices keep "all" (TCP).
rdma_ports() {
for port in /sys/class/infiniband/*/ports/*; do
[ "$(cat "$port/link_layer" 2>/dev/null)" = "$1" ] || continue
grep -q ACTIVE "$port/state" 2>/dev/null || continue
dev=${port%/ports/*}
echo "$(basename "$dev"):$(basename "$port")"
done | paste -sd,
}
UCX_NET_DEVICES=$(rdma_ports InfiniBand)
[ -n "$UCX_NET_DEVICES" ] || UCX_NET_DEVICES=$(rdma_ports Ethernet)
export UCX_NET_DEVICES=${UCX_NET_DEVICES:-all}
export LD_LIBRARY_PATH="$PROJECT_DIR/third_party/ucx/lib:$PROJECT_DIR/third_party/ucx/lib/ucx:${LD_LIBRARY_PATH:-}"
export VLLM_NIXL_SIDE_CHANNEL_HOST=$LOCAL_IP
+36 -11
View File
@@ -57,6 +57,7 @@ export CONFIG_DIR={{ config_dir }}
export OUTPUT_DIR={{ output_dir }}
export ORCHESTRATOR_OUTPUT_DIR={{ orchestrator_output_dir }}
mkdir -p $OUTPUT_DIR/logs/trainer $OUTPUT_DIR/logs/inference
rm -f $OUTPUT_DIR/logs/inference/*.log
ln -sfn trainer/node_0.log $OUTPUT_DIR/logs/trainer.log
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
@@ -239,10 +240,28 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
export VLLM_MOE_USE_DEEP_GEMM=1
{%- endif %}
export GLOO_SOCKET_IFNAME=bond0
# Bind gloo to the interface that owns LOCAL_IP (the rendezvous IP) — NIC
# names vary across clusters (bond0, eth0, ...). If the lookup fails, leave
# GLOO_SOCKET_IFNAME unset so gloo falls back to its own detection.
GLOO_IFNAME=$(ip -o -4 addr show to "$LOCAL_IP" 2>/dev/null | awk "{print \$2; exit}")
if [ -n "$GLOO_IFNAME" ]; then export GLOO_SOCKET_IFNAME=$GLOO_IFNAME; fi
export VLLM_ENGINE_READY_TIMEOUT_S=4200
export UCX_TLS=all
export UCX_NET_DEVICES=all
# Enumerate RDMA NICs for UCX/NIXL from sysfs (ibv_devices is not on the job
# PATH). Prefer InfiniBand ports and fall back to RoCE: "all" would also pick
# up non-functional devices (e.g. an Ethernet bond UCX cannot open), which
# fails NIXL backend creation. Hosts without RDMA devices keep "all" (TCP).
rdma_ports() {
for port in /sys/class/infiniband/*/ports/*; do
[ "$(cat "$port/link_layer" 2>/dev/null)" = "$1" ] || continue
grep -q ACTIVE "$port/state" 2>/dev/null || continue
dev=${port%/ports/*}
echo "$(basename "$dev"):$(basename "$port")"
done | paste -sd,
}
UCX_NET_DEVICES=$(rdma_ports InfiniBand)
[ -n "$UCX_NET_DEVICES" ] || UCX_NET_DEVICES=$(rdma_ports Ethernet)
export UCX_NET_DEVICES=${UCX_NET_DEVICES:-all}
export LD_LIBRARY_PATH="$PROJECT_DIR/third_party/ucx/lib:$PROJECT_DIR/third_party/ucx/lib/ucx:${LD_LIBRARY_PATH:-}"
export VLLM_NIXL_SIDE_CHANNEL_HOST=$LOCAL_IP
export VLLM_NIXL_SIDE_CHANNEL_PORT=5600
@@ -335,15 +354,6 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
else
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
if [ "$TRAIN_NODE_RANK" -eq 0 ]; then
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.base-url $INFER_URLS"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.admin-base-url $ADMIN_URLS"
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
fi
{%- else %}
TRAIN_NODE_RANK=$SLURM_PROCID
{%- endif %}
@@ -370,6 +380,21 @@ else
@ $CONFIG_DIR/trainer.toml \
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log &
{% if num_infer_nodes > 0 %} fi{% endif %}
{% if num_infer_nodes > 0 %}
# Launch the orchestrator on one node. Default is trainer rank 0 (SLURM_PROCID ==
# NUM_INFER_NODES). With orchestrator_on_inference it moves to the last inference node
# (a decode node) to keep its rollout buffer + env workers off host-RAM-saturated
# trainer nodes. Top-level (after the role if/else) so the wait -n teardown covers it.
{% if orchestrator_on_inference %}ORCH_PROCID=$((NUM_INFER_NODES - 1)){% else %}ORCH_PROCID=$NUM_INFER_NODES{% endif %}
if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.base-url $INFER_URLS"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.admin-base-url $ADMIN_URLS"
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
fi
{% endif %}
# Wait for the first background job to exit and propagate its exit code. This
# turns background process crashes (router, orchestrator) into task failures
+185 -76
View File
@@ -1,5 +1,8 @@
import copy
from collections.abc import Callable, Sequence
from dataclasses import dataclass
from prime_rl.trainer.utils import balanced_partition
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingSample
ROUTED_EXPERTS_DTYPE_ITEMSIZE = {
@@ -30,17 +33,6 @@ def _slice_routed_experts(routed_experts: RoutedExperts, seq_len: int) -> Routed
)
def _append_routed_experts(dst: MicroBatch, src: MicroBatch) -> None:
dst_routed = dst.routed_experts
src_routed = src.routed_experts
assert dst_routed is not None
assert src_routed is not None
assert dst_routed.dtype == src_routed.dtype
assert dst_routed.shape[1:] == src_routed.shape[1:]
dst_routed.data += src_routed.data
dst_routed.shape[0] += src_routed.shape[0]
def _pad_routed_experts(micro_batch: MicroBatch, padding_size: int) -> None:
routed_experts = micro_batch.routed_experts
assert routed_experts is not None
@@ -125,6 +117,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
loss_mask=loss_mask,
position_ids=position_ids,
inference_logprobs=inference_logprobs,
sequence_lengths=[len(input_ids)],
teacher_logprobs=teacher_logprobs,
temperatures=temperatures,
rewards=rewards,
@@ -141,8 +134,149 @@ def _is_multimodal_sample(sample: MicroBatch) -> bool:
return sample.mm_kwargs is not None
@dataclass
class _MicroBatchBin:
samples: list[tuple[int, MicroBatch]]
length: int
@classmethod
def from_sample(cls, lora_idx: int, sample: MicroBatch) -> "_MicroBatchBin":
return cls(samples=[(lora_idx, sample)], length=len(sample.input_ids))
@property
def first_sample(self) -> MicroBatch:
return self.samples[0][1]
def can_add(self, sample: MicroBatch, max_seq_len: int) -> bool:
first_sample = self.first_sample
return (
not _is_multimodal_sample(first_sample)
and not _is_multimodal_sample(sample)
and self.length + len(sample.input_ids) <= max_seq_len
and first_sample.training_mode == sample.training_mode
and (first_sample.routed_experts is None) == (sample.routed_experts is None)
)
def add(self, lora_idx: int, sample: MicroBatch) -> None:
self.samples.append((lora_idx, sample))
self.length += len(sample.input_ids)
def workload(self, bin_cost: Callable[[Sequence[int]], int]) -> int:
return bin_cost([len(sample.input_ids) for _, sample in self.samples])
def split_by_workload(self, bin_cost: Callable[[Sequence[int]], int]) -> tuple["_MicroBatchBin", "_MicroBatchBin"]:
# Greedily place the heaviest sample on the currently lighter side (longest-processing-time).
ranked = sorted(self.samples, key=lambda pair: -bin_cost([len(pair[1].input_ids)]))
left: list[tuple[int, MicroBatch]] = []
right: list[tuple[int, MicroBatch]] = []
left_workload = right_workload = 0
for lora_idx, sample in ranked:
sample_workload = bin_cost([len(sample.input_ids)])
if left_workload <= right_workload:
left.append((lora_idx, sample))
left_workload += sample_workload
else:
right.append((lora_idx, sample))
right_workload += sample_workload
return (
_MicroBatchBin(left, sum(len(sample.input_ids) for _, sample in left)),
_MicroBatchBin(right, sum(len(sample.input_ids) for _, sample in right)),
)
def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
has_rewards = any(sample.rewards is not None for _, sample in bin_content.samples)
has_teacher_logprobs = any(sample.teacher_logprobs is not None for _, sample in bin_content.samples)
has_mm_token_type_ids = any(sample.mm_token_type_ids is not None for _, sample in bin_content.samples)
input_ids: list[int] = []
loss_mask: list[bool] = []
advantages: list[float] = []
inference_logprobs: list[float] = []
position_ids: list[int] = []
temperatures: list[float] = []
env_names: list[str] = []
rewards: list[float] | None = [] if has_rewards else None
teacher_logprobs: list[float] | None = [] if has_teacher_logprobs else None
mm_token_type_ids: list[int] | None = [] if has_mm_token_type_ids else None
routed_experts: RoutedExperts | None = None
lora_num_tokens = [0] * num_loras
for lora_idx, sample in bin_content.samples:
sample_len = len(sample.input_ids)
input_ids.extend(sample.input_ids)
loss_mask.extend(sample.loss_mask)
advantages.extend(sample.advantages)
inference_logprobs.extend(sample.inference_logprobs)
position_ids.extend(sample.position_ids)
temperatures.extend(sample.temperatures)
env_names.extend(sample.env_names)
if rewards is not None:
rewards.extend(sample.rewards if sample.rewards is not None else [float("nan")] * sample_len)
if teacher_logprobs is not None:
teacher_logprobs.extend(
sample.teacher_logprobs if sample.teacher_logprobs is not None else [0.0] * sample_len
)
if mm_token_type_ids is not None:
mm_token_type_ids.extend(
sample.mm_token_type_ids if sample.mm_token_type_ids is not None else [0] * sample_len
)
if sample.routed_experts is not None:
if routed_experts is None:
routed_experts = _copy_routed_experts(sample.routed_experts)
else:
assert routed_experts.dtype == sample.routed_experts.dtype
assert routed_experts.shape[1:] == sample.routed_experts.shape[1:]
routed_experts.data += sample.routed_experts.data
routed_experts.shape[0] += sample.routed_experts.shape[0]
lora_num_tokens[lora_idx] += sample_len
sequence_lengths = [len(sample.input_ids) for _, sample in bin_content.samples]
assert sum(sequence_lengths) == len(input_ids), (sequence_lengths, len(input_ids))
first_sample = bin_content.first_sample
return MicroBatch(
input_ids=input_ids,
advantages=advantages,
loss_mask=loss_mask,
position_ids=position_ids,
inference_logprobs=inference_logprobs,
sequence_lengths=sequence_lengths,
teacher_logprobs=teacher_logprobs,
temperatures=temperatures,
rewards=rewards,
lora_num_tokens=lora_num_tokens,
routed_experts=routed_experts,
mm_token_type_ids=mm_token_type_ids,
env_names=env_names,
mm_kwargs=first_sample.mm_kwargs if _is_multimodal_sample(first_sample) else None,
training_mode=first_sample.training_mode,
)
def _expand_bins_by_splitting(
bins: list[_MicroBatchBin], target_count: int, bin_cost: Callable[[Sequence[int]], int]
) -> None:
while len(bins) < target_count:
candidates = [
(bin_content.workload(bin_cost), idx)
for idx, bin_content in enumerate(bins)
if len(bin_content.samples) > 1
]
if not candidates:
break
_, idx = max(candidates)
left, right = bins[idx].split_by_workload(bin_cost)
bins[idx] = left
bins.append(right)
def packed_samples_into_micro_bs(
samples: list[tuple[int, MicroBatch]], max_seq_len: int, num_loras: int
samples: list[tuple[int, MicroBatch]],
max_seq_len: int,
num_loras: int,
num_train_workers: int,
bin_cost: Callable[[Sequence[int]], int],
) -> list[MicroBatch]:
"""
Pack samples into micro_batch efficiently.
@@ -155,63 +289,40 @@ def packed_samples_into_micro_bs(
# Sort by (lora_idx, -length) for packing efficiency
samples.sort(key=lambda x: (x[0], -len(x[1].input_ids)))
## we create bins
micro_batches: list[MicroBatch] = []
bins: list[_MicroBatchBin] = []
for idx, sample in samples:
# Multimodal samples cannot be packed - each becomes its own micro batch
if _is_multimodal_sample(sample):
sample.lora_num_tokens = [0] * num_loras
sample.lora_num_tokens[idx] = len(sample.input_ids)
micro_batches.append(sample)
continue
# Try to find a bin that can fit this sequence (only pack text-only samples)
for bin_content in micro_batches:
# Don't pack into multimodal micro batches
if _is_multimodal_sample(bin_content):
continue
# Check if sequence fits in this bin
if (
len(bin_content.input_ids) + len(sample.input_ids) <= max_seq_len
and bin_content.training_mode == sample.training_mode
):
existing_len = len(bin_content.input_ids)
bin_content.input_ids.extend(sample.input_ids)
bin_content.loss_mask.extend(sample.loss_mask)
bin_content.advantages.extend(sample.advantages)
if sample.rewards is not None:
if bin_content.rewards is None:
bin_content.rewards = [float("nan")] * existing_len
bin_content.rewards.extend(sample.rewards)
elif bin_content.rewards is not None:
bin_content.rewards.extend([float("nan")] * len(sample.input_ids))
bin_content.inference_logprobs.extend(sample.inference_logprobs)
bin_content.temperatures.extend(sample.temperatures)
if sample.teacher_logprobs is not None:
if bin_content.teacher_logprobs is None:
bin_content.teacher_logprobs = []
bin_content.teacher_logprobs.extend(sample.teacher_logprobs)
assert (bin_content.routed_experts is None) == (sample.routed_experts is None)
if sample.routed_experts is not None:
if bin_content.routed_experts is None:
bin_content.routed_experts = _copy_routed_experts(sample.routed_experts)
else:
_append_routed_experts(bin_content, sample)
if sample.mm_token_type_ids is not None:
if bin_content.mm_token_type_ids is None:
bin_content.mm_token_type_ids = []
bin_content.mm_token_type_ids.extend(sample.mm_token_type_ids)
bin_content.env_names.extend(sample.env_names)
bin_content.position_ids.extend(sample.position_ids)
bin_content.lora_num_tokens[idx] += len(sample.input_ids)
for bin_content in bins:
if bin_content.can_add(sample, max_seq_len):
bin_content.add(idx, sample)
break
else:
sample.lora_num_tokens = [0] * num_loras
sample.lora_num_tokens[idx] = len(sample.input_ids)
micro_batches.append(sample)
bins.append(_MicroBatchBin.from_sample(idx, sample))
return micro_batches
if num_train_workers > 1:
target_count = max(
((len(bins) + num_train_workers - 1) // num_train_workers) * num_train_workers,
num_train_workers,
)
_expand_bins_by_splitting(bins, target_count, bin_cost)
return [_materialize_bin(bin_content, num_loras) for bin_content in bins]
def _distribute_group(
group: list[MicroBatch],
num_train_workers: int,
bin_cost: Callable[[Sequence[int]], int],
) -> list[list[MicroBatch]]:
# Callers pad each group to a positive multiple of num_train_workers first.
assert len(group) % num_train_workers == 0, "Number of micro batches is not divisible by number of data ranks"
if not group:
return [[] for _ in range(num_train_workers)]
weights = [bin_cost(micro_batch.sequence_lengths) for micro_batch in group]
partitions = balanced_partition(weights, num_train_workers)
return [[group[i] for i in partition] for partition in partitions]
def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBatch:
@@ -242,14 +353,16 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
micro_batch.rewards.extend([float("nan")] * padding_size)
micro_batch.loss_mask.extend([False] * padding_size)
micro_batch.position_ids.extend(list(range(padding_size)))
micro_batch.sequence_lengths.append(padding_size)
micro_batch.inference_logprobs.extend([0.0] * padding_size)
# Use temperature 1.0 for padding tokens (doesn't matter since loss_mask is False)
micro_batch.temperatures.extend([1.0] * padding_size)
if micro_batch.teacher_logprobs is not None:
micro_batch.teacher_logprobs.extend([0.0] * padding_size)
micro_batch.lora_num_tokens[-1] += (
padding_size # We send padding to the last lora so that tokens have ascending lora idx
)
if micro_batch.lora_num_tokens is not None:
micro_batch.lora_num_tokens[-1] += (
padding_size # We send padding to the last lora so that tokens have ascending lora idx
)
if micro_batch.mm_token_type_ids is not None:
micro_batch.mm_token_type_ids.extend([0] * padding_size)
if micro_batch.routed_experts is not None:
@@ -282,6 +395,7 @@ def prepare_batch(
num_train_workers: int,
idxs: list[int],
num_loras: int,
bin_cost: Callable[[Sequence[int]], int],
pad_to_multiple_of: int = 1,
) -> list[list[MicroBatch]]:
"""
@@ -295,7 +409,7 @@ def prepare_batch(
"""
all_samples = [(idx, prepare_sample(rollout, seq_len)) for idx, rollout in zip(idxs, rollouts)]
micro_batches = packed_samples_into_micro_bs(all_samples, seq_len, num_loras)
micro_batches = packed_samples_into_micro_bs(all_samples, seq_len, num_loras, num_train_workers, bin_cost)
micro_batches = [pad_micro_batch(micro_batch, pad_to_multiple_of) for micro_batch in micro_batches]
# Separate by modality so each step index has uniform modality across all ranks
@@ -306,15 +420,10 @@ def prepare_batch(
mm_batches = _pad_group_for_distribution(mm_batches, num_train_workers)
text_batches = _pad_group_for_distribution(text_batches, num_train_workers)
# Combine: all multimodal first, then all text-only. Since each group's length is
# divisible by num_train_workers, the modality boundary aligns with distribution rows.
ordered = mm_batches + text_batches
assert len(ordered) % num_train_workers == 0, "Number of micro batches is not divisible by number of data ranks"
# Distribute in strided order so each step index has the same modality across ranks
batches_per_gpu: list[list[MicroBatch]] = [[] for _ in range(num_train_workers)]
for i, batch in enumerate(ordered):
batches_per_gpu[i % num_train_workers].append(batch)
for group in (mm_batches, text_batches):
group_batches_per_gpu = _distribute_group(group, num_train_workers, bin_cost)
for worker_idx, worker_batches in enumerate(group_batches_per_gpu):
batches_per_gpu[worker_idx].extend(worker_batches)
return batches_per_gpu
+52 -22
View File
@@ -9,7 +9,7 @@ from typing import Any
import torch
from torch import Tensor, nn
from torch.distributed.checkpoint.state_dict import get_state_dict, set_state_dict
from torch.distributed.checkpoint.state_dict import get_state_dict, set_model_state_dict, set_state_dict
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
from torch.distributed.checkpoint.state_dict_saver import save as dcp_save
from torch.distributed.checkpoint.stateful import Stateful
@@ -67,8 +67,13 @@ class AppState(Stateful):
"""Extract base optimizers from wrappers like CPUOffloadOptimizer."""
return [opt.base_optimizer if isinstance(opt, CPUOffloadOptimizer) else opt for opt in self.optimizers]
def _has_cpu_offload(self) -> bool:
return any(isinstance(opt, CPUOffloadOptimizer) for opt in self.optimizers)
def state_dict(self) -> dict[str, Any]:
# Move CPU-offloaded states to GPU before checkpointing
# get_state_dict requires optimizer states to live on param.device. For an
# already-initialized CPU-offload optimizer that means staging back to GPU
# before the call; the matching offload happens after the dict is built.
for opt in self.optimizers:
if isinstance(opt, CPUOffloadOptimizer) and opt._initialized:
opt._move_states("cuda")
@@ -88,26 +93,53 @@ class AppState(Stateful):
progress_state_dict = asdict(self.progress)
state_dict["progress"] = progress_state_dict
# Move states back to CPU
# Offload optimizer states to CPU for every CPUOffloadOptimizer, including
# ones that were uninitialized on entry. dcp_load calls this method to build
# a template, and get_state_dict's internal _init_optim_state populates an
# empty optim.state with GPU tensors. Optimizer.state_dict() returns those
# values via shallow copy, so optimizer_state_dict["state"][fqn] is the same
# dict object as optim.state[param]. Replacing the entries with CPU tensors
# in place therefore flips the template too — dcp_load reads bytes from disk
# straight into CPU storage and optim.state is loaded by the time the load
# returns, without GPU optimizer state ever existing for the duration of the
# read.
has_cpu_offload = self._has_cpu_offload()
for opt in self.optimizers:
if isinstance(opt, CPUOffloadOptimizer) and opt._initialized:
if isinstance(opt, CPUOffloadOptimizer):
opt._move_states("cpu")
if has_cpu_offload:
gc.collect()
torch.cuda.empty_cache()
return state_dict
def load_state_dict(self, state_dict: dict[str, Any]):
base_optimizers = self._get_base_optimizers()
set_state_dict(
self.model, base_optimizers, model_state_dict=state_dict["model"], optim_state_dict=state_dict["optimizers"]
)
has_cpu_offload = self._has_cpu_offload()
# Re-initialize CPU offload wrappers after loading
has_cpu_offload = False
for opt in self.optimizers:
if isinstance(opt, CPUOffloadOptimizer):
opt._move_states("cpu")
opt._initialized = True
has_cpu_offload = True
if has_cpu_offload:
# When CPU offload is on, the optimizer is already loaded by the time we
# get here: state_dict() handed dcp_load a template whose tensors share
# storage with optim.state[p][k], and dcp_load wrote the checkpoint bytes
# directly into those tensors via target_tensor.copy_(...). Running
# set_state_dict on the optimizer would route the loaded CPU values
# through Optimizer.load_state_dict, whose _cast hook does
# value.to(param.dtype, param.device) and would allocate a fresh GPU
# copy of every state tensor — undoing the in-place CPU load and
# detaching optim.state from the tensors we just populated. So we only
# apply the model side here and flip the wrappers to initialized so
# subsequent steps take the steady-state path.
set_model_state_dict(self.model, model_state_dict=state_dict["model"])
for opt in self.optimizers:
if isinstance(opt, CPUOffloadOptimizer):
opt._initialized = True
else:
set_state_dict(
self.model,
base_optimizers,
model_state_dict=state_dict["model"],
optim_state_dict=state_dict["optimizers"],
)
if self.scheduler is not None:
self.scheduler.load_state_dict(state_dict["scheduler"])
@@ -115,15 +147,13 @@ class AppState(Stateful):
for key, value in state_dict["progress"].items():
setattr(self.progress, key, value)
# Reclaim GPU memory freed by moving optimizer states to CPU.
# After set_state_dict + _move_states("cpu"), the optimizer states live on CPU,
# but the state_dict (owned by dcp_load) still holds references to stale GPU
# optimizer tensors. Clearing them and flushing the CUDA cache prevents OOM on
# the first training step.
# state_dict is the same dict object that dcp_load held internally; clearing
# it drops the last references to the loaded tensor wrappers so the cuda
# allocator can release whatever blocks it cached during the read.
if has_cpu_offload:
state_dict.clear() # drop stale GPU tensor references from dcp_load
gc.collect() # break any circular references so tensors are freed
torch.cuda.empty_cache() # return freed GPU memory to CUDA
state_dict.clear()
gc.collect()
torch.cuda.empty_cache()
class CheckpointManager:
+29
View File
@@ -37,6 +37,7 @@ from prime_rl.trainer.models import (
get_custom_vlm_cls,
supports_custom_impl,
)
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import Indexer
from prime_rl.trainer.models.layers.checkpointing import (
get_supported_targets,
set_selective_activation_checkpointing,
@@ -350,6 +351,29 @@ def freeze_moe_router(model: nn.Module) -> None:
logger.info(f"Froze {num_frozen} MoE router parameters")
def freeze_sparse_indexer(model: nn.Module) -> None:
"""Freeze DSA sparse-attention indexer parameters.
The indexer's `compute_sparse_indices` forward runs under `torch.no_grad()`, so its
params never receive a gradient and cannot be trained. Left with requires_grad=True
they stay stateless in the optimizer, which breaks strict checkpoint resume: DCP
materializes optimizer state for every requires_grad param at load time, but the
stateless params were never saved -> "Missing key in checkpoint state_dict". Freezing
them keeps the saved and loaded optimizer state symmetric.
"""
logger = get_logger()
num_frozen = 0
for module in model.modules():
if isinstance(module, Indexer):
for param in module.parameters():
param.requires_grad = False
num_frozen += 1
if num_frozen > 0:
logger.info(f"Froze {num_frozen} sparse indexer parameters")
def apply_force_balanced_routing(model: nn.Module) -> None:
"""Force MoE token-choice routers into round-robin assignment for fake-data smoke tests."""
logger = get_logger()
@@ -1075,6 +1099,11 @@ def setup_model(
if config.freeze_moe_router:
freeze_moe_router(model)
# The DSA sparse-attention indexer runs its forward under torch.no_grad(), so it is
# never trainable. Freeze it so optimizer state stays symmetric across checkpoint
# save/resume. No-op for models without a sparse indexer.
freeze_sparse_indexer(model)
if config.debug.force_balanced_routing:
apply_force_balanced_routing(model)
@@ -550,3 +550,71 @@ def per_block_cast_to_fp8_triton(
gran_k,
)
return out[0], sf[0]
def per_block_cast_to_fp8_tp_triton(
x: torch.Tensor, use_ue8m0: bool, gran_k: int = GROUP_ALIGNMENT
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Block-fp8 cast of ``x.T`` without materializing the transpose."""
assert x.dim() == 2
assert gran_k == GROUP_ALIGNMENT
rows, cols = x.shape
x3 = x.unsqueeze(0)
out = torch.empty((cols, rows), device=x.device, dtype=torch.float8_e4m3fn)
sf = torch.empty((ceil_div(cols, gran_k), ceil_div(rows, gran_k)), device=x.device, dtype=torch.float32)
grid = (1, ceil_div(rows, gran_k), ceil_div(cols, gran_k))
_grouped_per_block_fp8_kernel[grid](
x3,
out,
sf,
1,
rows,
cols,
x3.stride(0),
x3.stride(1),
x3.stride(2),
# transposed output: x's element (row, col) lands at out[col, row]
cols * rows,
1,
rows,
# transposed scales: x's tile (pid_m, pid_n) lands at sf[pid_n, pid_m]
ceil_div(cols, gran_k) * ceil_div(rows, gran_k),
1,
ceil_div(rows, gran_k),
USE_UE8M0=use_ue8m0,
BLOCK_M=gran_k,
BLOCK_N=gran_k,
num_warps=8,
)
return out, sf
def per_token_cast_to_fp8_tp_triton(
x: torch.Tensor, use_ue8m0: bool, gran_k: int = GROUP_ALIGNMENT
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Per-token fp8 cast of ``x.T`` without materializing the transpose."""
assert x.dim() == 2
assert gran_k == GROUP_ALIGNMENT
rows, cols = x.shape
out = torch.empty((cols, rows), device=x.device, dtype=torch.float8_e4m3fn)
sf = torch.empty((cols, ceil_div(rows, gran_k)), device=x.device, dtype=torch.float32)
grid = lambda meta: (ceil_div(cols, meta["BLOCK_M"]), ceil_div(rows, meta["BLOCK_K"]))
_per_token_fp8_kernel[grid](
x,
out,
sf,
cols,
rows,
# transposed read: the kernel's per-row amax reduces over x's rows
x.stride(1),
x.stride(0),
out.stride(0),
out.stride(1),
sf.stride(0),
sf.stride(1),
USE_UE8M0=use_ue8m0,
BLOCK_M=8,
BLOCK_K=gran_k,
num_warps=4,
)
return out, sf
@@ -12,7 +12,9 @@ import torch
from torch import nn
from prime_rl.trainer.models.kernels.fp8_utils import (
per_block_cast_to_fp8_tp_triton,
per_block_cast_to_fp8_triton,
per_token_cast_to_fp8_tp_triton,
per_token_cast_to_fp8_triton,
)
from prime_rl.utils.logger import get_logger
@@ -43,8 +45,7 @@ class _FP8BlockwiseMM(torch.autograd.Function):
grad_x = grad_weight = None
if ctx.needs_input_grad[0]:
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, False, block_size)
weight_t = weight.transpose(0, 1).contiguous()
weight_dx_fp8 = per_block_cast_to_fp8_triton(weight_t, False, block_size)
weight_dx_fp8 = per_block_cast_to_fp8_tp_triton(weight, False, block_size)
grad_x_2d = torch.empty_like(x_2d)
deep_gemm.fp8_gemm_nt(grad_output_fp8, weight_dx_fp8, grad_x_2d)
grad_x = grad_x_2d.reshape(ctx.x_shape)
@@ -62,10 +63,8 @@ class _FP8BlockwiseMM(torch.autograd.Function):
else:
grad_output_2d_padded = grad_output_2d
x_2d_padded = x_2d
grad_output_t = grad_output_2d_padded.transpose(0, 1).contiguous()
x_t = x_2d_padded.transpose(0, 1).contiguous()
grad_output_t_fp8 = per_token_cast_to_fp8_triton(grad_output_t, False, block_size)
x_t_fp8 = per_token_cast_to_fp8_triton(x_t, False, block_size)
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d_padded, False, block_size)
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d_padded, False, block_size)
grad_weight_fp32 = torch.zeros_like(weight, dtype=torch.float32)
deep_gemm.fp8_gemm_nt(
grad_output_t_fp8,
@@ -8,6 +8,7 @@ import torch.nn as nn
from torch import Tensor
from prime_rl.utils.logger import get_logger
from prime_rl.utils.vlm import get_final_logit_softcapping
FUSED_CE_IGNORE_INDEX = -100
@@ -299,8 +300,8 @@ def inject_prime_lm_head(
logger = get_logger()
# Check for Gemma-style softcapping - dispatch to specialized implementation
final_logit_softcapping = getattr(model.config, "final_logit_softcapping", None)
# Check for Gemma-style softcapping - dispatch to specialized implementation.
final_logit_softcapping = get_final_logit_softcapping(model.config)
if final_logit_softcapping:
if fused_cross_entropy == "quack":
raise ValueError(
+39 -22
View File
@@ -955,32 +955,44 @@ class NemotronHRouter(nn.Module):
self.norm_topk_prob = norm_topk_prob
def forward(
self, x: torch.Tensor, expert_bias: torch.Tensor | None = None
self,
x: torch.Tensor,
expert_bias: torch.Tensor | None = None,
routed_experts: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
scores = F.linear(x.float(), self.gate.float()).sigmoid()
scores_for_choice = scores + self.e_score_correction_bias
if expert_bias is not None:
scores_for_choice = scores_for_choice + expert_bias
if routed_experts is not None:
# Router replay: reuse the inference engine's expert selection and
# only recompute the gating weights from the trainer's scores. The
# correction/load-balancing biases only affect selection, so they
# are intentionally skipped here.
selected_experts_indices = routed_experts
else:
scores_for_choice = scores + self.e_score_correction_bias
# Group-based routing
if self.n_group > 1:
group_scores = (
scores_for_choice.view(-1, self.n_group, self.num_experts // self.n_group)
.topk(2, dim=-1)[0]
.sum(dim=-1)
)
group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
group_mask = torch.zeros_like(group_scores)
group_mask.scatter_(1, group_idx, 1)
score_mask = (
group_mask.unsqueeze(-1)
.expand(-1, self.n_group, self.num_experts // self.n_group)
.reshape(-1, self.num_experts)
)
scores_for_choice = scores_for_choice.masked_fill(~score_mask.bool(), 0.0)
if expert_bias is not None:
scores_for_choice = scores_for_choice + expert_bias
# Group-based routing
if self.n_group > 1:
group_scores = (
scores_for_choice.view(-1, self.n_group, self.num_experts // self.n_group)
.topk(2, dim=-1)[0]
.sum(dim=-1)
)
group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
group_mask = torch.zeros_like(group_scores)
group_mask.scatter_(1, group_idx, 1)
score_mask = (
group_mask.unsqueeze(-1)
.expand(-1, self.n_group, self.num_experts // self.n_group)
.reshape(-1, self.num_experts)
)
scores_for_choice = scores_for_choice.masked_fill(~score_mask.bool(), 0.0)
selected_experts_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
selected_experts_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
top_scores = scores.gather(1, selected_experts_indices)
routing_confidence_sum = _selected_probability_mass_sum(scores, top_scores, "sigmoid")
@@ -1181,8 +1193,13 @@ class LatentMoE(nn.Module):
bs, slen, dim = x.shape
x_flat = x.view(-1, dim)
if routed_experts is not None:
# Flatten to (bs * slen, top_k); reshape (not view) since the slice is non-contiguous.
_, _, top_k = routed_experts.shape
routed_experts = routed_experts.reshape(-1, top_k)
top_scores, selected_experts_indices, num_tokens_per_expert, routing_confidence_sum = self.router(
x_flat, self.expert_bias
x_flat, self.expert_bias, routed_experts=routed_experts
)
with torch.no_grad():
@@ -223,6 +223,7 @@ class NemotronHMambaLayer(GradientCheckpointingLayer):
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
routed_experts: torch.Tensor | None = None,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.norm(hidden_states)
@@ -266,10 +267,11 @@ class NemotronHMoELayer(GradientCheckpointingLayer):
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
routed_experts: torch.Tensor | None = None,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.norm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = self.mlp(hidden_states, routed_experts=routed_experts)
return residual + hidden_states
@@ -298,6 +300,7 @@ class NemotronHAttentionLayer(GradientCheckpointingLayer):
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
routed_experts: torch.Tensor | None = None,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.norm(hidden_states)
@@ -498,7 +501,13 @@ class NemotronHModel(NemotronHPreTrainedModel):
input_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
routed_experts: Optional[torch.LongTensor] = None,
) -> BaseModelOutputWithPast:
"""
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
Routed experts for each token, indexed by global layer index. Only used for router replay; slots
for non-MoE (Mamba/attention) layers are ignored.
"""
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
@@ -516,12 +525,15 @@ class NemotronHModel(NemotronHPreTrainedModel):
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids) if self.rotary_emb is not None else None
for decoder_layer in self.layers:
for layer_idx, decoder_layer in enumerate(self.layers):
# routed_experts is indexed by global layer index; non-MoE layers ignore it.
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
routed_experts=routed_experts_layer,
)
hidden_states = self.norm(hidden_states)
@@ -550,6 +562,7 @@ class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
labels: Optional[torch.LongTensor] = None,
logits_to_keep: int = 0,
temperature: Optional[torch.Tensor] = None,
routed_experts: Optional[torch.LongTensor] = None,
**kwargs,
) -> PrimeLmOutput:
if position_ids is None:
@@ -562,6 +575,7 @@ class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
routed_experts=routed_experts,
)
hidden_states = outputs.last_hidden_state
+8 -3
View File
@@ -149,10 +149,15 @@ def _create_optimizer(
"""Create optimizer. If lr is None, uses config.lr."""
if lr is None:
lr = config.lr
# Only hand trainable params to the optimizer. Frozen params (e.g. the DSA sparse
# indexer, which runs under no_grad) carry no optimizer state, and including them
# breaks strict checkpoint resume (DCP materializes state for every requires_grad
# param at load time, mismatching the saved state). Muon filters internally below.
trainable_params = [p for _, p in named_params if p.requires_grad]
match config.type:
case "sgd":
return SGD(
params=[p for _, p in named_params],
params=trainable_params,
lr=lr,
weight_decay=config.weight_decay,
momentum=config.momentum,
@@ -160,7 +165,7 @@ def _create_optimizer(
)
case "adamw":
return AdamW(
params=[p for _, p in named_params],
params=trainable_params,
lr=lr,
weight_decay=config.weight_decay,
betas=(config.betas1, config.betas2),
@@ -169,7 +174,7 @@ def _create_optimizer(
return _create_muon_optimizer(config, named_params, parallel_dims, lr)
case "sign_sgd":
return SignSGD(
params=[p for _, p in named_params],
params=trainable_params,
lr=lr,
weight_decay=config.weight_decay,
)
+25 -1
View File
@@ -1,3 +1,4 @@
from collections.abc import Callable, Sequence
from pathlib import Path
from typing import TypedDict
@@ -10,7 +11,12 @@ from prime_rl.configs.trainer import FakeDataLoaderConfig
from prime_rl.trainer.rl.packer import BasePacker, setup_packer
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.trainer.world import get_world
from prime_rl.transport import MicroBatch, MicroBatchReceiver, TransportConfig, setup_micro_batch_receiver
from prime_rl.transport import (
MicroBatch,
MicroBatchReceiver,
TransportConfig,
setup_micro_batch_receiver,
)
class TensorMicroBatch(TypedDict):
@@ -26,6 +32,7 @@ class TensorMicroBatch(TypedDict):
loss_mask: Bool[Tensor, "batch seq"]
temperatures: Float[Tensor, "batch seq"] # Per-token temperatures
env_names: list[str]
sequence_lengths: list[int]
# Batch level
lora_num_tokens: Int[Tensor, "n_loras"]
@@ -46,6 +53,10 @@ class TensorMicroBatch(TypedDict):
# sft → sft loss). All samples in a micro batch share the same mode.
training_mode: str
# Packer-derived metadata used for run-local debug exports.
run_id: str | None
run_step: int | None
class FakeDataLoader:
def __init__(self, config: FakeDataLoaderConfig, seq_len: int, dp_world_size: int):
@@ -84,6 +95,7 @@ class FakeDataLoader:
total_seq_len = 0
input_ids = []
position_ids = []
sequence_lengths = []
while total_seq_len < self.seq_len:
# Generate reasonably long documents
@@ -91,6 +103,7 @@ class FakeDataLoader:
if seq_len_to_generate + total_seq_len > self.seq_len:
seq_len_to_generate = self.seq_len - total_seq_len
total_seq_len += seq_len_to_generate
sequence_lengths.append(seq_len_to_generate)
tmp_input_ids = torch.randint(0, 120000, (seq_len_to_generate,), generator=generator).long()
tmp_position_ids = torch.arange(seq_len_to_generate).long()
@@ -114,12 +127,15 @@ class FakeDataLoader:
"teacher_logprobs": None,
"temperatures": torch.ones(input_ids.shape[0]).unsqueeze(0),
"env_names": ["fake"] * input_ids.shape[0],
"sequence_lengths": sequence_lengths,
"loss_mask": loss_mask.unsqueeze(0),
"lora_num_tokens": lora_num_tokens,
"routed_experts": None,
"mm_kwargs": None,
"mm_token_type_ids": None,
"training_mode": "rl",
"run_id": None,
"run_step": None,
}
def _get_micro_batch(self, generator: torch.Generator) -> TensorMicroBatch:
@@ -142,12 +158,15 @@ class FakeDataLoader:
"teacher_logprobs": None,
"temperatures": torch.ones(self.seq_len).unsqueeze(0),
"env_names": ["fake"] * self.seq_len,
"sequence_lengths": [self.seq_len],
"loss_mask": torch.ones(self.seq_len, dtype=torch.bool).unsqueeze(0),
"lora_num_tokens": lora_num_tokens,
"routed_experts": None,
"mm_kwargs": None,
"mm_token_type_ids": None,
"training_mode": "rl",
"run_id": None,
"run_step": None,
}
@@ -162,6 +181,7 @@ class DataLoader:
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
bin_cost: Callable[[Sequence[int]], int],
config: TransportConfig,
):
self.world = get_world()
@@ -173,6 +193,7 @@ class DataLoader:
tokenizer=tokenizer,
transport_config=config,
pad_to_multiple_of=pad_to_multiple_of,
bin_cost=bin_cost,
start_step=start_step,
)
@@ -236,6 +257,7 @@ class DataLoader:
loss_mask=torch.tensor(micro_batch.loss_mask, dtype=torch.bool).unsqueeze(0),
temperatures=torch.tensor(micro_batch.temperatures, dtype=torch.float).unsqueeze(0),
env_names=micro_batch.env_names,
sequence_lengths=micro_batch.sequence_lengths,
lora_num_tokens=torch.tensor(micro_batch.lora_num_tokens, dtype=torch.int32),
mm_kwargs=mm_kwargs,
mm_token_type_ids=torch.tensor(micro_batch.mm_token_type_ids, dtype=torch.long).unsqueeze(0)
@@ -243,6 +265,8 @@ class DataLoader:
else None,
routed_experts=routed_experts,
training_mode=micro_batch.training_mode,
run_id=micro_batch.run_id,
run_step=micro_batch.run_step,
)
+36 -2
View File
@@ -6,7 +6,7 @@ from beartype import beartype as typechecker
from jaxtyping import Bool, Float, Int, jaxtyped
from torch import Tensor
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, LossConfig
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, IPOLossConfig, LossConfig
from prime_rl.utils.utils import import_object
@@ -165,6 +165,35 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
return LossOutputs(loss=loss, metrics=metrics)
def ipo_loss_fn(inputs: LossInputs, loss_config: IPOLossConfig) -> LossOutputs:
trainer_logprobs = inputs.trainer_logprobs
inference_logprobs = inputs.inference_logprobs
advantages = inputs.advantages
loss_mask = inputs.loss_mask
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
trainer_logprobs, inference_logprobs
)
abs_probs_diff = torch.abs(torch.exp(trainer_logprobs) - torch.exp(inference_logprobs))
is_masked = abs_probs_diff > loss_config.ipo_threshold
keep_mask = loss_mask & ~is_masked
advantages = loss_config.adv_tau * advantages
pg_loss = keep_mask * advantages * importance_ratio
kl_loss = loss_mask * log_importance_ratio**2
loss = (-pg_loss + loss_config.kl_tau * kl_loss).sum()
metrics = {
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked), # all trainable, masked tokens
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask), # all trainable, unmasked tokens
"is_masked": _safe_mean(is_masked, loss_mask),
}
return LossOutputs(loss=loss, metrics=metrics)
def opd_loss_fn(inputs: LossInputs) -> LossOutputs:
"""
On-policy distillation loss: the default DPPO+KL math with the tau knobs
@@ -240,7 +269,8 @@ def setup_loss_fns(loss_config: LossConfig) -> dict[str, LossFn]:
- ``"opd"`` → ``opd_loss_fn`` (teacher KL as gradient signal, hardcoded
DPPO + KL knobs)
- ``"rl"`` → ``default_loss_fn(loss_config)`` for ``DefaultLossConfig``,
or the imported function for ``CustomLossConfig``.
``ipo_loss_fn(loss_config)`` for ``IPOLossConfig``, or the imported
function for ``CustomLossConfig``.
``trainer.loss`` only affects the rl path - opd and sft are independent.
"""
@@ -250,6 +280,10 @@ def setup_loss_fns(loss_config: LossConfig) -> dict[str, LossFn]:
def rl_fn(inputs: LossInputs) -> LossOutputs:
return custom_fn(inputs, **kwargs)
elif isinstance(loss_config, IPOLossConfig):
def rl_fn(inputs: LossInputs) -> LossOutputs:
return ipo_loss_fn(inputs, loss_config)
else:
def rl_fn(inputs: LossInputs) -> LossOutputs:
+31 -4
View File
@@ -4,6 +4,7 @@ import threading
import time
from abc import ABC, abstractmethod
from collections import deque
from collections.abc import Callable, Sequence
from transformers.tokenization_utils import PreTrainedTokenizer
@@ -32,6 +33,7 @@ class BasePacker(ABC):
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
):
self.logger = get_logger()
@@ -40,6 +42,7 @@ class BasePacker(ABC):
self.seq_len = seq_len
self.pad_to_multiple_of = pad_to_multiple_of
self.tokenizer = tokenizer
self.bin_cost = bin_cost
self.receiver = setup_training_batch_receiver(config)
shutil.rmtree(get_rollout_dir(self.multi_run_manager.output_dir), ignore_errors=True)
self.sender: MicroBatchSender = setup_micro_batch_sender(
@@ -84,9 +87,10 @@ class SinglePacker(BasePacker):
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
):
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, start_step)
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, bin_cost, start_step)
assert self.multi_run_manager.max_runs == 1, "SinglePacker only supports one run"
def pack(self):
@@ -110,7 +114,14 @@ class SinglePacker(BasePacker):
num_train_workers=self.dp_world_size,
idxs=[0] * len(batch.examples),
num_loras=self.multi_run_manager.max_runs,
bin_cost=self.bin_cost,
)
# The receiver always stamps run_idx from used_idxs (a key of idx_2_id).
run_id = self.multi_run_manager.idx_2_id[batch.run_idx]
for worker_batches in micro_batch_grid:
for micro_batch in worker_batches:
micro_batch.run_id = run_id
micro_batch.run_step = batch.step
self.sender.send(micro_batch_grid)
@@ -123,9 +134,10 @@ class MultiPacker(BasePacker):
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
):
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, start_step)
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, bin_cost, start_step)
# Per-run buffer: stores (TrainingSample, step) tuples
self.buffers: list[deque[tuple[TrainingSample, int]]] = [
deque() for _ in range(self.multi_run_manager.max_runs)
@@ -300,10 +312,14 @@ class MultiPacker(BasePacker):
# Group samples by run_idx - each microbatch must contain samples from only ONE run
# because MultiLoRAGroupedExperts (MoE) only supports one adapter per microbatch
samples_by_run: dict[int, list[TrainingSample]] = {}
steps_by_run: dict[int, int] = {}
per_run_stats: dict[int, tuple[int, int]] = {}
for run_idx, sample, step in selected_samples:
if run_idx not in samples_by_run:
samples_by_run[run_idx] = []
steps_by_run[run_idx] = step
else:
assert steps_by_run[run_idx] == step, "Micro batches for a run must come from a single run step"
samples_by_run[run_idx].append(sample)
num_tokens = len(sample.prompt_ids) + len(sample.completion_ids)
@@ -327,9 +343,15 @@ class MultiPacker(BasePacker):
num_train_workers=self.dp_world_size,
idxs=[run_idx] * len(run_samples),
num_loras=self.multi_run_manager.max_runs,
bin_cost=self.bin_cost,
)
run_id = self.multi_run_manager.idx_2_id[run_idx]
run_step = steps_by_run[run_idx]
# Merge into combined grid
for worker_idx, worker_batches in enumerate(run_micro_batch_grid):
for micro_batch in worker_batches:
micro_batch.run_id = run_id
micro_batch.run_step = run_step
all_micro_batches[worker_idx].extend(worker_batches)
self.sender.send(all_micro_batches)
@@ -341,10 +363,15 @@ def setup_packer(
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
transport_config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
) -> BasePacker:
multi_run_manager = get_multi_run_manager()
if multi_run_manager.max_runs == 1:
return SinglePacker(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, start_step)
return SinglePacker(
dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, bin_cost, start_step
)
else:
return MultiPacker(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, start_step)
return MultiPacker(
dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, bin_cost, start_step
)
+49 -27
View File
@@ -18,6 +18,9 @@ class DisabledTokenExporter:
def export(self, *args: Any, **kwargs: Any) -> None:
return
def mark_stable(self, ready_run_ids: set[str] | None = None) -> None:
return
def close(self) -> None:
return
@@ -30,10 +33,10 @@ class TokenExporter:
) -> None:
self.rank = rank
self.output_dir = output_dir / "token_exports"
self._file: Any | None = None
self._closed = False
self._current_step: int | None = None
self._sequences_this_step = 0
self._initialized_files: set[tuple[str | None, int, int]] = set()
self._sequences_by_file: dict[tuple[str | None, int, int], int] = {}
self._pending_stable_dirs: dict[str | None, set[Path]] = {}
atexit.register(self.close)
def export(
@@ -42,17 +45,17 @@ class TokenExporter:
micro_step: int,
micro_batch: Mapping[str, Any],
model_output: Mapping[str, Tensor],
response_lengths: list[int],
sequence_lengths: list[int],
loss_config: Any,
) -> None:
if self._current_step != step:
self._start_step(step)
columns = _export_columns(micro_batch, model_output, loss_config)
_check_lengths(columns)
run_id = micro_batch.get("run_id")
export_step = micro_batch.get("run_step") if micro_batch.get("run_step") is not None else step
file_key = (run_id, export_step, self.rank)
start = 0
for micro_sequence_idx, length in enumerate(response_lengths):
for micro_sequence_idx, length in enumerate(sequence_lengths):
raw_end = start + length
end = _trim_padding(columns, start, raw_end)
if end > start and any(columns["loss_mask"][start:end]):
@@ -60,54 +63,73 @@ class TokenExporter:
{
"schema_version": SCHEMA_VERSION,
"step": step,
"export_step": export_step,
"rank": self.rank,
"micro_step": micro_step,
"micro_sequence_idx": micro_sequence_idx,
"export_sequence_idx": self._sequences_this_step,
"export_sequence_idx": self._sequences_by_file.get(file_key, 0),
"run_id": run_id,
"env_name": _first_non_empty(columns["env_names"][start:end]),
"training_mode": str(micro_batch["training_mode"]),
**_slice_columns(columns, start, end),
}
},
run_id,
export_step,
)
self._sequences_this_step += 1
self._sequences_by_file[file_key] = self._sequences_by_file.get(file_key, 0) + 1
start = raw_end
def close(self) -> None:
if self._closed:
return
self._closed = True
if self._file is not None:
self._file.close()
self._file = None
def _start_step(self, step: int) -> None:
def mark_stable(self, ready_run_ids: set[str] | None = None) -> None:
# A single run step's sequences can span multiple trainer steps (the packer
# splits a run step across packs when it exceeds the token budget). Only
# finalize a run's export dir once that run step is fully consumed — the same
# `ready_to_update` signal that gates its optimizer step. ``run_id is None``
# is single-run export, where a step never spans trainer steps, so mark it now.
# The caller barriers first so a STABLE only lands after every rank flushed.
ready_run_ids = ready_run_ids or set()
for run_id in [rid for rid in self._pending_stable_dirs if rid is None or rid in ready_run_ids]:
for stable_dir in self._pending_stable_dirs.pop(run_id):
(stable_dir / "STABLE").touch()
def _export_dir(self, export_step: int, run_id: str | None) -> Path:
if run_id is not None:
return self.output_dir.parent / run_id / "token_exports" / f"step_{export_step}"
return self.output_dir / f"step_{export_step}"
def _export_file(self, export_step: int, run_id: str | None) -> Path:
if self._closed:
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
if self._file is not None:
self._file.close()
self._current_step = step
self._sequences_this_step = 0
step_dir = self.output_dir / f"step_{step}"
step_dir = self._export_dir(export_step, run_id)
try:
step_dir.mkdir(parents=True, exist_ok=True)
except FileExistsError:
if not step_dir.is_dir():
raise
self._file = (step_dir / f"rank_{self.rank}.jsonl").open("w", encoding="utf-8")
return step_dir / f"rank_{self.rank}.jsonl"
def _write(self, record: dict[str, Any]) -> None:
def _write(self, record: dict[str, Any], run_id: str | None, export_step: int) -> None:
if self._closed:
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
if self._file is None:
raise RuntimeError("Token exporter has no active step file")
self._file.write(json.dumps(record, separators=(",", ":"), allow_nan=False) + "\n")
file_key = (run_id, export_step, self.rank)
mode = "a" if file_key in self._initialized_files else "w"
export_file = self._export_file(export_step, run_id)
with export_file.open(mode, encoding="utf-8") as file:
file.write(json.dumps(record, separators=(",", ":"), allow_nan=False) + "\n")
self._initialized_files.add(file_key)
self._pending_stable_dirs.setdefault(run_id, set()).add(export_file.parent)
def setup_token_exporter(
config: TrainerConfig, parallel_dims: Any, world: Any, logger: Any
) -> TokenExporter | DisabledTokenExporter:
token_export_config = config.experimental.token_export
if token_export_config is None:
if not config.enable_token_export:
return DisabledTokenExporter()
if parallel_dims.cp_enabled and parallel_dims.world_mesh["cp"].get_local_rank() != 0:
return DisabledTokenExporter()
+25 -8
View File
@@ -46,6 +46,7 @@ from prime_rl.trainer.model import (
from prime_rl.trainer.parallel_dims import get_parallel_dims
from prime_rl.trainer.perf import get_perf_counter
from prime_rl.trainer.utils import (
build_bin_cost,
GarbageCollection,
MemoryProfiler,
Tensors,
@@ -55,7 +56,6 @@ from prime_rl.trainer.utils import (
get_ckpt_disk_metrics,
setup_torch_distributed,
print_benchmark,
get_response_lengths,
)
from prime_rl.trainer.world import get_world
from prime_rl.trainer.runs import setup_multi_run_manager, Progress, get_multi_run_manager
@@ -237,6 +237,7 @@ def train(config: TrainerConfig):
config.model.seq_len,
config.model.cp,
tokenizer,
build_bin_cost(model.config),
config.rollout_transport,
)
@@ -472,15 +473,15 @@ def train(config: TrainerConfig):
)
# Compute loss
response_lengths = get_response_lengths(position_ids)
sequence_lengths = micro_batch["sequence_lengths"]
loss, loss_tensors = compute_loss(
trainer_logprobs=out["logprobs"].squeeze().split(response_lengths),
inference_logprobs=inference_logprobs.squeeze().split(response_lengths),
teacher_logprobs=teacher_logprobs.squeeze().split(response_lengths)
trainer_logprobs=out["logprobs"].squeeze().split(sequence_lengths),
inference_logprobs=inference_logprobs.squeeze().split(sequence_lengths),
teacher_logprobs=teacher_logprobs.squeeze().split(sequence_lengths)
if teacher_logprobs is not None
else None,
advantages=advantages.squeeze().split(response_lengths),
loss_mask=loss_mask.squeeze().split(response_lengths),
advantages=advantages.squeeze().split(sequence_lengths),
loss_mask=loss_mask.squeeze().split(sequence_lengths),
loss_fns=loss_fns,
loss_scale=loss_scale,
training_mode=micro_batch["training_mode"],
@@ -512,7 +513,14 @@ def train(config: TrainerConfig):
for env_name, indices in env_to_indices.items():
tensors[f"mismatch_kl/{env_name}"].append(mismatch_kl[indices])
token_exporter.export(progress.step, micro_step, micro_batch, out, response_lengths, config.loss)
token_exporter.export(
progress.step,
micro_step,
micro_batch,
out,
sequence_lengths,
config.loss,
)
if is_tt_moe_model(model):
load_balance_stats = get_load_balance_stats(model)
@@ -534,6 +542,15 @@ def train(config: TrainerConfig):
micro_step_message += f" | Routing Conf. {tensors['routing_confidence'][-1].mean().item():.4f}"
logger.debug(micro_step_message)
if config.enable_token_export:
dist.barrier()
ready_run_ids = {
multi_run_manager.idx_2_id[idx]
for idx in multi_run_manager.ready_to_update_idxs
if idx in multi_run_manager.idx_2_id
}
token_exporter.mark_stable(ready_run_ids)
# compute_loss already divided by the global token count. Undo FSDP's per-rank averaging
# across dp_cp so the final gradient is the true per-token mean over the global batch.
for param in model.parameters():
+238 -37
View File
@@ -1,10 +1,12 @@
import gc
import heapq
import json
import pickle
import shutil
import time
from collections import defaultdict
from collections.abc import Iterable
from collections.abc import Callable, Iterable, Sequence
from dataclasses import dataclass, field
from datetime import timedelta
from pathlib import Path
from typing import Any
@@ -28,6 +30,241 @@ from prime_rl.utils.utils import format_num, format_time, get_step_path
DEFAULT_TIMEOUT = timedelta(seconds=600)
def _text_config(model_config: Any) -> Any:
"""Unwrap a multimodal model's text config, else return the config unchanged."""
return getattr(model_config, "text_config", model_config)
def _is_mla(config: Any) -> bool:
return bool(getattr(config, "multi_latent_attention", False) or hasattr(config, "q_lora_rank"))
def _kv_channels(config: Any) -> int:
return getattr(config, "kv_channels", getattr(config, "head_dim", config.hidden_size // config.num_attention_heads))
def _qkv_projection_flops_per_token(config: Any) -> int:
"""Linear-in-seqlen FLOPs of the Q/K/V projections (per token)."""
hidden_size = config.hidden_size
num_attention_heads = config.num_attention_heads
kv_channels = _kv_channels(config)
is_mla = _is_mla(config)
qk_head_dim = getattr(config, "qk_head_dim", 0)
qk_pos_emb_head_dim = getattr(config, "qk_pos_emb_head_dim", 0)
if is_mla and getattr(config, "q_lora_rank", None) is not None:
q_flops = 2 * config.q_lora_rank * (hidden_size + num_attention_heads * (qk_head_dim + qk_pos_emb_head_dim))
else:
q_head_dim = (qk_head_dim + qk_pos_emb_head_dim) if is_mla else kv_channels
q_flops = 2 * hidden_size * num_attention_heads * q_head_dim
if is_mla and getattr(config, "kv_lora_rank", None) is not None:
v_head_dim = getattr(config, "v_head_dim", 0)
kv_flops = 2 * (
config.kv_lora_rank * (hidden_size + num_attention_heads * (qk_head_dim + v_head_dim))
+ hidden_size * qk_pos_emb_head_dim
)
else:
num_query_groups = getattr(
config, "num_query_groups", getattr(config, "num_key_value_heads", num_attention_heads)
)
kv_flops = 4 * hidden_size * num_query_groups * kv_channels
return q_flops + kv_flops
def _attention_flops_per_token_squared(config: Any) -> int:
"""Quadratic-in-seqlen FLOPs of the attention scores and values (per token^2)."""
num_attention_heads = config.num_attention_heads
kv_channels = _kv_channels(config)
if _is_mla(config):
qk_head_dim = getattr(config, "qk_head_dim", 0)
qk_pos_emb_head_dim = getattr(config, "qk_pos_emb_head_dim", 0)
v_head_dim = getattr(config, "v_head_dim", kv_channels)
return num_attention_heads * (qk_head_dim + qk_pos_emb_head_dim) + num_attention_heads * v_head_dim
return 2 * num_attention_heads * kv_channels
def _ffn_flops_per_token(hidden_size: int, ffn_hidden_size: int) -> int:
return 6 * hidden_size * ffn_hidden_size
def _dense_ffn_hidden_size(config: Any) -> int:
return getattr(
config, "ffn_hidden_size", getattr(config, "intermediate_size", getattr(config, "moe_intermediate_size", 0))
)
def _moe_ffn_hidden_size(config: Any) -> int:
"""Effective FFN width of an MoE layer: routed experts (topk) plus shared experts."""
dense_ffn = _dense_ffn_hidden_size(config)
routed_topk = getattr(config, "moe_router_topk", getattr(config, "num_experts_per_tok", 1))
moe_ffn = getattr(config, "moe_ffn_hidden_size", getattr(config, "moe_intermediate_size", dense_ffn))
return moe_ffn * routed_topk + (getattr(config, "moe_shared_expert_intermediate_size", None) or 0)
def _count_dense_and_moe_layers(config: Any) -> tuple[int, int]:
"""Split the model's layers into (dense, moe) counts."""
num_experts = getattr(config, "num_experts", getattr(config, "n_routed_experts", None))
if num_experts is None:
return config.num_hidden_layers, 0
moe_layer_freq = getattr(config, "moe_layer_freq", None)
if isinstance(moe_layer_freq, list):
num_dense = sum(1 for freq in moe_layer_freq if freq == 0)
num_moe = sum(1 for freq in moe_layer_freq if freq > 0)
elif isinstance(moe_layer_freq, int):
num_dense = sum(1 for i in range(config.num_hidden_layers) if i % moe_layer_freq != 0)
num_moe = config.num_hidden_layers - num_dense
elif getattr(config, "first_k_dense_replace", None) is not None:
num_dense = config.first_k_dense_replace
num_moe = config.num_hidden_layers - num_dense
else:
num_dense = 0
num_moe = config.num_hidden_layers
return num_dense, num_moe
def _packing_cost_coeffs(config: Any) -> tuple[int, int]:
"""Return the (linear, quadratic) coefficients of the per-sequence forward FLOPs."""
hidden_size = config.hidden_size
num_dense_layers, num_moe_layers = _count_dense_and_moe_layers(config)
qkv_per_token = _qkv_projection_flops_per_token(config)
attn_per_token_squared = _attention_flops_per_token_squared(config)
def layer_linear(ffn_hidden_size: int) -> int:
return qkv_per_token + 2 * hidden_size * hidden_size + _ffn_flops_per_token(hidden_size, ffn_hidden_size)
linear = (
num_dense_layers * layer_linear(_dense_ffn_hidden_size(config))
+ num_moe_layers * layer_linear(_moe_ffn_hidden_size(config))
+ 2 * hidden_size * config.vocab_size
)
quadratic = (num_dense_layers + num_moe_layers) * attn_per_token_squared
return linear, quadratic
def build_bin_cost(model_config: Any | None) -> Callable[[Sequence[int]], int]:
"""Build a closure scoring a packed bin by estimated forward compute.
With ``model_config=None`` the linear/quadratic coefficients are ``(1, 0)``, so
the cost reduces to the token count and balancing falls back to sequence length.
"""
if model_config is None:
linear, quadratic = 1, 0
else:
linear, quadratic = _packing_cost_coeffs(_text_config(model_config))
def bin_cost(seqlens: Sequence[int]) -> int:
return linear * sum(seqlens) + quadratic * sum(n * n for n in seqlens)
return bin_cost
@dataclass
class _WeightedSet:
total: int = 0
items: list[int] = field(default_factory=list)
def add(self, idx: int, weight: int) -> None:
self.items.append(idx)
self.total += weight
def merge(self, other: "_WeightedSet") -> None:
self.items.extend(other.items)
self.total += other.total
def __lt__(self, other: "_WeightedSet") -> bool:
if self.total != other.total:
return self.total < other.total
return self.items < other.items
class _KKState:
def __init__(self, items: list[tuple[int, int]], k: int):
self.sets = [_WeightedSet() for _ in range(k)]
for set_idx, (idx, weight) in enumerate(items):
self.sets[set_idx].add(idx, weight)
self.sets.sort(reverse=True)
@property
def spread(self) -> int:
return self.sets[0].total - self.sets[-1].total
def merge(self, other: "_KKState") -> None:
k = len(self.sets)
for i in range(k):
self.sets[i].merge(other.sets[k - 1 - i])
self.sets.sort(reverse=True)
def partitions(self) -> list[list[int]]:
return [sorted(weighted_set.items) for weighted_set in self.sets]
def __lt__(self, other: "_KKState") -> bool:
if self.spread != other.spread:
return self.spread > other.spread
return self.sets[0] > other.sets[0]
def _karmarkar_karp(weights: Sequence[int], num_partitions: int) -> list[list[int]]:
assert len(weights) >= num_partitions
assert len(weights) % num_partitions == 0
weighted_indices = sorted((weight, idx) for idx, weight in enumerate(weights))
states: list[_KKState] = []
for offset in range(0, len(weighted_indices), num_partitions):
items = [(idx, weight) for weight, idx in weighted_indices[offset : offset + num_partitions]]
heapq.heappush(states, _KKState(items, num_partitions))
while len(states) > 1:
state = heapq.heappop(states)
state.merge(heapq.heappop(states))
heapq.heappush(states, state)
return states[0].partitions()
def _partition_loads(weights: Sequence[int], partitions: list[list[int]]) -> list[int]:
return [sum(weights[i] for i in partition) for partition in partitions]
def _refine_by_swapping(weights: Sequence[int], partitions: list[list[int]]) -> list[list[int]]:
partitions = [list(partition) for partition in partitions]
loads = _partition_loads(weights, partitions)
while True:
best_swap = None
best_score = (max(loads), max(loads) - min(loads))
for left_rank in range(len(partitions)):
for right_rank in range(left_rank + 1, len(partitions)):
for left_pos, left_idx in enumerate(partitions[left_rank]):
for right_pos, right_idx in enumerate(partitions[right_rank]):
new_left = loads[left_rank] - weights[left_idx] + weights[right_idx]
new_right = loads[right_rank] - weights[right_idx] + weights[left_idx]
new_loads = list(loads)
new_loads[left_rank] = new_left
new_loads[right_rank] = new_right
score = (max(new_loads), max(new_loads) - min(new_loads))
if score < best_score:
best_score = score
best_swap = (left_rank, right_rank, left_pos, right_pos, new_loads)
if best_swap is None:
return partitions
left_rank, right_rank, left_pos, right_pos, loads = best_swap
partitions[left_rank][left_pos], partitions[right_rank][right_pos] = (
partitions[right_rank][right_pos],
partitions[left_rank][left_pos],
)
def balanced_partition(weights: Sequence[int], num_partitions: int) -> list[list[int]]:
"""Partition item indices into ``num_partitions`` groups of near-equal total weight.
Requires ``len(weights)`` to be a positive multiple of ``num_partitions``.
"""
partitions = _karmarkar_karp(weights, num_partitions)
return _refine_by_swapping(weights, partitions)
class GarbageCollection:
"""Controls Python garbage collection to avoid stragglers in distributed training.
@@ -143,42 +380,6 @@ def setup_torch_distributed(timeout: timedelta = DEFAULT_TIMEOUT, enable_gloo: b
dist.init_process_group(backend=backend, timeout=timeout, device_id=device_id)
def get_response_lengths(position_ids: torch.Tensor) -> list[int]:
"""
Compute lengths of concatenated sequences from position_ids.
Each sequence starts at 0 and increments. When position_ids resets to 0,
it indicates the start of a new sequence. Trailing zeros (padding) are
counted as part of the last sequence.
Args:
position_ids: Tensor of shape [total_seqlen]
Returns:
List of sequence lengths
"""
position_ids = position_ids.flatten()
boundaries = [0] # Start of first sequence
for i in range(1, len(position_ids)):
if position_ids[i] == 0 and position_ids[i - 1] != 0:
# This is a potential sequence boundary (0 after non-zero)
# But only if the next element is 1 (indicating a new incrementing sequence)
# Otherwise, this 0 is padding and belongs to current sequence
if i + 1 < len(position_ids) and position_ids[i + 1] == 1:
boundaries.append(i)
# Calculate lengths based on boundaries
lengths = []
for i in range(len(boundaries)):
start = boundaries[i]
end = boundaries[i + 1] if i + 1 < len(boundaries) else len(position_ids)
lengths.append(end - start)
return lengths
def print_sample(input_ids: list[int], loss_mask: list[bool], tokenizer: PreTrainedTokenizer):
"""
Visualize the loss mask of a tokenized sample using rich.
+6 -1
View File
@@ -8,7 +8,12 @@ from prime_rl.transport.filesystem import (
FileSystemTrainingBatchReceiver,
FileSystemTrainingBatchSender,
)
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingBatch, TrainingSample
from prime_rl.transport.types import (
MicroBatch,
RoutedExperts,
TrainingBatch,
TrainingSample,
)
from prime_rl.transport.zmq import (
ZMQMicroBatchReceiver,
ZMQMicroBatchSender,
+5
View File
@@ -76,6 +76,7 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
position_ids: list[int]
temperatures: list[float] # Per-token temperatures used during generation
env_names: list[str]
sequence_lengths: list[int]
teacher_logprobs: list[float] | None = None
lora_num_tokens: list[int] | None = None
routed_experts: RoutedExperts | None = None
@@ -89,3 +90,7 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
# sft → sft loss). All samples packed into a micro batch share the same mode.
training_mode: TrainingMode = "rl"
rewards: list[float] | None = None
# Packer-derived metadata used for run-local token exports.
run_id: str | None = None
run_step: int | None = None
+6 -3
View File
@@ -2,6 +2,7 @@ from pathlib import Path
from time import time
import zmq
import zmq.asyncio
from prime_rl.configs.shared import ZMQTransportConfig
from prime_rl.trainer.runs import get_multi_run_manager
@@ -20,8 +21,10 @@ class ZMQTrainingBatchSender(TrainingBatchSender):
def __init__(self, output_dir: Path, transport: ZMQTransportConfig):
super().__init__(output_dir)
self.context = zmq.Context.instance()
self.socket: zmq.Socket = self.context.socket(zmq.PUSH)
# Async context so ``send`` yields instead of blocking the orchestrator
# event loop when the trainer is slow and we hit SNDHWM.
self.context = zmq.asyncio.Context.instance()
self.socket: zmq.asyncio.Socket = self.context.socket(zmq.PUSH)
self.socket.setsockopt(zmq.SNDHWM, transport.hwm)
self.socket.connect(f"tcp://{transport.host}:{transport.port}")
@@ -35,7 +38,7 @@ class ZMQTrainingBatchSender(TrainingBatchSender):
async def send(self, batch: TrainingBatch) -> None:
payload = self.encoder.encode(batch)
self.logger.debug(f"Sending batch {batch.step} to {self.sender_id}")
self.socket.send_multipart([self.sender_id, payload], copy=False)
await self.socket.send_multipart([self.sender_id, payload], copy=False)
def close(self) -> None:
try:
+51 -38
View File
@@ -12,7 +12,7 @@ import verifiers as vf
from httpx import AsyncClient
from openai import NotFoundError
from renderers import RendererConfig
from tenacity import retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
from tenacity import AsyncRetrying, retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.logger import get_logger
@@ -303,8 +303,8 @@ async def check_health(
NCCL_READY_MARKER = "NCCL_READY"
def _is_retryable_pause_error(exception: BaseException) -> bool:
"""Check if an exception should trigger a retry for pausing engines."""
def _is_retryable_admin_error(exception: BaseException) -> bool:
"""Check if an exception should trigger a retry for an admin op (pause/resume/update_weights)."""
if isinstance(exception, httpx.HTTPStatusError):
# Retry on transient server errors (5xx, e.g. engine briefly unresponsive);
# client errors (4xx) won't fix themselves on retry.
@@ -317,47 +317,55 @@ def _is_retryable_pause_error(exception: BaseException) -> bool:
return False
# Per-attempt and total bounds for `/pause`. Pausing drains in-flight requests
# (mode="keep"), so a single attempt can legitimately take a while, but the global
# admin AsyncClient uses `timeout=None`, so a stuck server would hang the weight
# update forever. `_READ_TIMEOUT` converts a hang into a TimeoutException so
# tenacity retries; `_TOTAL` is the wall-clock budget across all retries.
PAUSE_READ_TIMEOUT_S = 120.0
PAUSE_TOTAL_TIMEOUT_S = 300.0
# Per-attempt read timeout for admin ops, overridable per call. The admin
# AsyncClient uses `timeout=None`, so without this a stuck server would hang the
# weight update forever: the read timeout converts a hang into a TimeoutException
# that tenacity retries. Sized for `/pause`, which drains in-flight requests
# (mode="keep") and so can legitimately take a while.
ADMIN_TIMEOUT_S = 300.0
# `/update_weights` runs a collective NCCL receive across all DP workers, which
# can take longer than the other admin ops.
UPDATE_WEIGHTS_TIMEOUT_S = 720.0
async def _admin_post(client: AsyncClient, path: str, *, timeout_s: float = ADMIN_TIMEOUT_S, **kwargs) -> None:
"""POST an admin op with a bounded per-attempt timeout, retrying transient errors.
The total wall-clock budget across all retries is twice the per-attempt timeout.
"""
async for attempt in AsyncRetrying(
retry=retry_if_exception(_is_retryable_admin_error),
stop=stop_after_delay(2 * timeout_s) | stop_after_attempt(10),
wait=wait_exponential(multiplier=1, min=1, max=10),
reraise=True,
):
with attempt:
response = await client.post(
path,
timeout=httpx.Timeout(connect=10.0, read=timeout_s, write=60.0, pool=10.0),
**kwargs,
)
response.raise_for_status()
async def _pause_engines(admin_clients: list[AsyncClient], *, step: int) -> None:
"""Pause all inference engines, waiting for in-flight requests to drain."""
logger = get_logger()
logger.info(f"Updating policy in-flight to v{step}")
@retry(
retry=retry_if_exception(_is_retryable_pause_error),
stop=stop_after_delay(PAUSE_TOTAL_TIMEOUT_S) | stop_after_attempt(10),
wait=wait_exponential(multiplier=1, min=1, max=10),
reraise=True,
await asyncio.gather(
*[_admin_post(client, "/pause", params={"mode": "keep", "clear_cache": "false"}) for client in admin_clients]
)
async def _pause(client: AsyncClient) -> None:
response = await client.post(
"/pause",
params={"mode": "keep", "clear_cache": "false"},
timeout=httpx.Timeout(connect=10.0, read=PAUSE_READ_TIMEOUT_S, write=60.0, pool=10.0),
)
response.raise_for_status()
await asyncio.gather(*[_pause(client) for client in admin_clients])
logger.debug("All inference engines paused")
async def _resume_engines(admin_clients: list[AsyncClient]) -> None:
"""Resume all inference engines after weight update."""
"""Resume all inference engines after weight update.
Resuming is idempotent (it just clears the paused flag), so retrying transient
failures is safe; a dropped /resume would leave engines paused indefinitely.
"""
logger = get_logger()
async def _resume(client: AsyncClient) -> None:
response = await client.post("/resume")
response.raise_for_status()
await asyncio.gather(*[_resume(client) for client in admin_clients])
await asyncio.gather(*[_admin_post(client, "/resume") for client in admin_clients])
logger.debug("All inference engines resumed")
@@ -383,11 +391,6 @@ async def update_weights(
if lora_name is not None and weight_dir is not None:
await load_lora_adapter(admin_clients, lora_name, weight_dir)
else:
async def _update_weights(admin_client: AsyncClient, weight_dir: str | None) -> None:
response = await admin_client.post("/update_weights", json={"weight_dir": weight_dir})
response.raise_for_status()
# Pause engines so all DP workers drain in-flight work and can join the NCCL broadcast
await _pause_engines(admin_clients, step=step)
@@ -399,7 +402,17 @@ async def update_weights(
nccl_ready_file.touch()
logger.debug(f"Created NCCL_READY marker at {nccl_ready_file}")
await asyncio.gather(*[_update_weights(admin_client, weight_dir_posix) for admin_client in admin_clients])
await asyncio.gather(
*[
_admin_post(
admin_client,
"/update_weights",
json={"weight_dir": weight_dir_posix},
timeout_s=UPDATE_WEIGHTS_TIMEOUT_S,
)
for admin_client in admin_clients
]
)
finally:
await _resume_engines(admin_clients)
+15 -14
View File
@@ -16,8 +16,8 @@ import verifiers as vf
from prime_cli.core.config import Config as PrimeConfig
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.configs.shared import PrimeMonitorConfig
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.monitor.base import Monitor, sample_items_for_logging
@@ -112,7 +112,7 @@ class PrimeMonitor(Monitor):
config: PrimeMonitorConfig | None,
output_dir: Path | None = None,
tokenizer: PreTrainedTokenizer | None = None,
run_config: BaseConfig | None = None,
run_config: OrchestratorConfig | None = None,
keep_full_history: bool = True,
):
self.config = config
@@ -185,7 +185,7 @@ class PrimeMonitor(Monitor):
if config.log_extras.distributions:
self.last_log_distributions_step = -1
def _register_run(self, config: PrimeMonitorConfig, run_config: BaseConfig | None) -> str | None:
def _register_run(self, config: PrimeMonitorConfig, run_config: OrchestratorConfig | None) -> str | None:
"""Register an external run with the platform. Returns run_id on success, None on failure."""
prime_config = None
team_id = config.team_id
@@ -197,22 +197,23 @@ class PrimeMonitor(Monitor):
if frontend_url is None:
frontend_url = prime_config.frontend_url
model = getattr(run_config, "model", None) if run_config else None
environments = getattr(run_config, "env", None) if run_config else None
wandb = getattr(run_config, "wandb", None) if run_config else None
payload: dict = {
"base_model": model.name if model else "unknown",
"max_steps": getattr(run_config, "max_steps", None) or 0,
payload: dict[str, Any] = {
"base_model": run_config.student.model.name if run_config else "unknown",
"max_steps": (run_config.max_steps if run_config else None) or 0,
}
if run_config:
if run_config.batch_size is not None:
payload["batch_size"] = run_config.batch_size
payload["rollouts_per_example"] = run_config.group_size
payload["seq_len"] = run_config.seq_len
payload["environments"] = [{"id": env.id} for env in run_config.train.env]
payload["run_config"] = run_config.model_dump(exclude_none=True, mode="json")
if run_config.wandb:
payload["wandb_project"] = run_config.wandb.project
if config.run_name:
payload["name"] = config.run_name
if team_id:
payload["team_id"] = team_id
if environments:
payload["environments"] = [{"id": env.id} for env in environments if hasattr(env, "id")]
if wandb and getattr(wandb, "project", None):
payload["wandb_project"] = wandb.project
try:
response = httpx.post(
+11
View File
@@ -29,6 +29,7 @@ VLM_REGISTRY: dict[str, VLMModelInfo] = {
"qwen3_5": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
"qwen3_5_moe": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
"qwen3_vl_moe": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
"gemma4": VLMModelInfo(vision_encoder_attr="model.vision_tower", language_model_attr="model.language_model"),
}
# Text-only default
@@ -86,6 +87,16 @@ def is_vlm_architecture(model_config: PretrainedConfig) -> bool:
return _get_model_info_from_config(model_config) is not None
def get_final_logit_softcapping(model_config: PretrainedConfig) -> float | None:
"""Read ``final_logit_softcapping`` from the text config.
For composite VLM configs (e.g. Gemma) the value lives under ``text_config``;
``get_text_config()`` returns that for VLMs and the config itself for text-only
models, so a plain top-level ``getattr`` would miss it and silently drop softcapping.
"""
return getattr(model_config.get_text_config(), "final_logit_softcapping", None)
def get_layer_prefix(model_config: PretrainedConfig, override: str | None = None) -> str:
"""Return the weight key prefix for language model layers.
+152
View File
@@ -14,12 +14,17 @@ import asyncio
import numpy as np
import pybase64
from vllm.entrypoints.openai.engine.protocol import UsageInfo
from vllm.entrypoints.serve.disagg.protocol import GenerateResponse, GenerateResponseChoice
from prime_rl.inference.vllm.routed_experts import serialize_routed_experts
from prime_rl.inference.vllm.serving_tokens import (
PrimeRlGenerateResponse,
PrimeRlGenerateResponseChoice,
PrimeRlServingTokens,
_build_usage,
_client_set_max_tokens,
_FinalOutputCapture,
_GenerateRoutedExpertsCapture,
)
@@ -105,6 +110,153 @@ def test_client_set_max_tokens_detects_unset():
assert asyncio.run(_client_set_max_tokens(_FakeRawRequest(body_without_sp))) is False
class _FakeOutput:
def __init__(self, token_ids):
self.token_ids = token_ids
class _FakeRequestOutput:
"""Minimal stand-in for ``vllm.outputs.RequestOutput``.
``_build_usage`` only touches four attributes; constructing a real
``RequestOutput`` would require a full ``CompletionOutput`` graph and
isn't worth it for a serialization-shape test.
"""
def __init__(self, prompt_token_ids, output_token_ids_list, num_cached_tokens=0, encoder_prompt_token_ids=None):
self.prompt_token_ids = prompt_token_ids
self.encoder_prompt_token_ids = encoder_prompt_token_ids
self.outputs = [_FakeOutput(t) for t in output_token_ids_list]
self.num_cached_tokens = num_cached_tokens
def test_prime_rl_generate_response_serializes_usage_block():
# Regression for prime-rl PR #2408: parent ``GenerateResponse`` doesn't
# declare ``usage``, so the field must be declared on the subclass for
# Pydantic to emit it in JSON. Without this the router can't extract
# per-run token / cache counts for billing.
response = PrimeRlGenerateResponse(
request_id="req-1",
choices=[PrimeRlGenerateResponseChoice(index=0, token_ids=[1, 2, 3])],
usage=UsageInfo(prompt_tokens=4, completion_tokens=3, total_tokens=7),
)
payload = response.model_dump(mode="json")
assert payload["usage"] == {
"prompt_tokens": 4,
"completion_tokens": 3,
"total_tokens": 7,
"prompt_tokens_details": None,
}
def test_build_usage_sums_prompt_and_completion_tokens():
final_res = _FakeRequestOutput(
prompt_token_ids=[1, 2, 3, 4, 5],
output_token_ids_list=[[10, 11], [20, 21, 22]],
)
usage = _build_usage(final_res)
assert usage.prompt_tokens == 5
assert usage.completion_tokens == 5 # 2 + 3
assert usage.total_tokens == 10
assert usage.prompt_tokens_details is None
def test_build_usage_includes_encoder_prompt_tokens():
final_res = _FakeRequestOutput(
prompt_token_ids=[1, 2, 3],
output_token_ids_list=[[10]],
encoder_prompt_token_ids=[100, 101],
)
usage = _build_usage(final_res)
assert usage.prompt_tokens == 5 # 3 + 2
assert usage.total_tokens == 6
def test_build_usage_reports_cached_tokens_unconditionally():
# Unlike upstream's ``enable_prompt_tokens_details`` gate, prime-rl always
# surfaces cached tokens — the cache-discount billing pipeline needs them.
final_res = _FakeRequestOutput(
prompt_token_ids=[1, 2, 3, 4],
output_token_ids_list=[[10, 11]],
num_cached_tokens=3,
)
usage = _build_usage(final_res)
assert usage.prompt_tokens_details is not None
assert usage.prompt_tokens_details.cached_tokens == 3
def test_build_usage_skips_cached_tokens_when_zero():
# Don't emit a details block with cached=0, which would be misleading
# to the router's billing extractor.
final_res = _FakeRequestOutput(
prompt_token_ids=[1, 2, 3, 4],
output_token_ids_list=[[10, 11]],
num_cached_tokens=0,
)
usage = _build_usage(final_res)
assert usage.prompt_tokens_details is None
def test_final_output_capture_records_last_item():
async def _gen():
for r in [
_FakeRequestOutput(prompt_token_ids=[1], output_token_ids_list=[[1]]),
_FakeRequestOutput(prompt_token_ids=[1, 2], output_token_ids_list=[[1, 2]]),
_FakeRequestOutput(prompt_token_ids=[1, 2, 3], output_token_ids_list=[[1, 2, 3]]),
]:
yield r
async def _drain(capture):
async for _ in capture:
pass
capture = _FinalOutputCapture(_gen())
asyncio.run(_drain(capture))
assert capture.final_res is not None
assert capture.final_res.prompt_token_ids == [1, 2, 3]
def test_final_output_capture_works_over_async_def_aiter_source():
# ``_GenerateRoutedExpertsCapture`` exposes the async-iterator protocol
# via ``async def __aiter__`` (an async generator function) and has no
# ``__anext__``. The wrapper must drive it through ``async for`` rather
# than poking ``__anext__`` directly, or routed-experts runs raise
# AttributeError before the response is built.
class _AsyncGenAiterSource:
def __init__(self, items):
self._items = items
async def __aiter__(self):
for item in self._items:
yield item
items = [
_FakeRequestOutput(prompt_token_ids=[1], output_token_ids_list=[[1]]),
_FakeRequestOutput(prompt_token_ids=[1, 2], output_token_ids_list=[[1, 2]]),
]
capture = _FinalOutputCapture(_AsyncGenAiterSource(items))
async def _drain():
async for _ in capture:
pass
asyncio.run(_drain())
assert capture.final_res is not None
assert capture.final_res.prompt_token_ids == [1, 2]
def test_final_output_capture_handles_empty_stream():
capture = _FinalOutputCapture(_empty_request_outputs())
async def _drain():
async for _ in capture:
pass
asyncio.run(_drain())
assert capture.final_res is None
def test_client_set_max_tokens_assumes_set_when_body_unreadable():
# No raw_request → can't tell, don't override.
assert asyncio.run(_client_set_max_tokens(None)) is True
+124 -190
View File
@@ -1,4 +1,3 @@
import math
import uuid
import pytest
@@ -6,8 +5,8 @@ import pytest
from prime_rl.configs.orchestrator import (
CustomAdvantageConfig,
DefaultAdvantageConfig,
TokensLengthPenaltyConfig,
TurnsLengthPenaltyConfig,
LinearLengthPenaltyConfig,
OrchestratorConfig,
)
from prime_rl.orchestrator.advantage import (
AdvantageInputs,
@@ -16,48 +15,29 @@ from prime_rl.orchestrator.advantage import (
default_advantage_fn,
setup_advantage_fn,
)
from prime_rl.orchestrator.envs import Env, TrainEnv
from prime_rl.orchestrator.types import TrainRollout
def _make_rollout(
reward: float,
completion_len: int = 0,
num_turns: int = 1,
env_name: str = "test",
example_id: int = 0,
) -> dict:
"""Create a minimal rollout dict for advantage testing.
`completion_len` tokens are split across `num_turns` trajectory steps.
"""
per_turn, rem = divmod(completion_len, max(num_turns, 1))
trajectory = [
{"tokens": {"prompt_ids": [0], "completion_ids": list(range(per_turn + (rem if i == 0 else 0)))}}
for i in range(num_turns)
]
def _make_rollout(reward: float, completion_len: int = 0) -> dict:
"""Minimal single-turn rollout dict with ``completion_len`` completion tokens."""
return {
"reward": reward,
"trajectory": trajectory,
"env_name": env_name,
"example_id": example_id,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(completion_len))}}],
"env_name": "test",
"example_id": 0,
}
def _make_group(rewards, completion_lengths=None, num_turns=None) -> AdvantageInputs:
"""Build single-group AdvantageInputs from 1D arrays of rewards/lengths/turns."""
def _make_group(rewards, completion_lengths=None) -> AdvantageInputs:
"""Build single-group AdvantageInputs from 1D arrays of rewards/lengths."""
rollouts = []
for i, reward in enumerate(rewards):
cl = int(completion_lengths[i]) if completion_lengths is not None else 0
nt = int(num_turns[i]) if num_turns is not None else 1
rollouts.append(_make_rollout(float(reward), cl, nt))
rollouts.append(_make_rollout(float(reward), cl))
return AdvantageInputs(rollouts=rollouts)
# Helper aliases for readability — completion-only and tool-only token shaping.
_TOKENS_COMPLETION = TokensLengthPenaltyConfig(completion_weight=1.0, tool_response_weight=0.0)
_TOKENS_TOOL_ONLY = TokensLengthPenaltyConfig(completion_weight=0.0, tool_response_weight=1.0)
def test_default_advantage_fn_simple_mean():
inputs = _make_group(rewards=[1.0, 0.5, 0.8], completion_lengths=[10, 12, 8])
result = default_advantage_fn(inputs)
@@ -66,187 +46,141 @@ def test_default_advantage_fn_simple_mean():
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
def test_efficiency_mixed_group():
"""Mixed group: reward shaping preserves zero-mean, shorter correct gets higher advantage."""
inputs = _make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20])
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
def test_linear_length_penalty_scales_by_pass_rate():
"""Linear penalty subtracts coef * pass_rate * (completion tokens / max_seq_len), then mean-centers.
# mean_correct_len = (10+30+20)/3 = 20
# bonus = clamp(1 - [10,30,20,20]/20, 0, 1) = [0.5, 0, 0, 0]
# shaped_rewards = R * (1 + bonus * correct_mask) = [1.5, 1, 0, 1]
# baseline = mean(shaped_rewards) = 0.875
# A = shaped_rewards - baseline = [0.625, 0.125, -0.875, 0.125]
assert result.advantages == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
``pass_rate`` is the group's mean reward, so a half-solved group scales the penalty by 0.5.
"""
rewards = [1.0, 1.0, 0.0, 0.0]
inputs = _make_group(rewards=rewards, completion_lengths=[10, 20, 30, 40])
result = default_advantage_fn(inputs, length_penalty=LinearLengthPenaltyConfig(coef=2.0), max_seq_len=100)
# Zero-mean per group
pass_rate = sum(rewards) / len(rewards) # 0.5
penalized = [r - 2.0 * pass_rate * (length / 100) for r, length in zip(rewards, (10, 20, 30, 40))]
mean = sum(penalized) / len(penalized)
assert result.advantages == pytest.approx([p - mean for p in penalized], abs=1e-6)
# Zero-mean per group, and within each reward tier shorter output → higher advantage
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
# All correct rollouts have positive advantage
for rollout, adv in zip(inputs.rollouts, result.advantages):
if rollout["reward"] >= 1.0:
assert adv > 0
assert result.advantages[0] > result.advantages[1]
assert result.advantages[2] > result.advantages[3]
def test_efficiency_all_correct_group():
"""All-correct group: zero-mean, shorter gets higher advantage."""
inputs = _make_group(rewards=[1.0, 1.0, 1.0], completion_lengths=[10, 20, 40])
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
# mean_len = 70/3 ≈ 23.33
# bonus = clamp(1 - [10, 20, 40] / (70/3), 0, 1) = [4/7, 1/7, 0]
# shaped_rewards = [1+4/7, 1+1/7, 1] = [11/7, 8/7, 1]
shaped = [11.0 / 7, 8.0 / 7, 1.0]
mean_shaped = sum(shaped) / len(shaped)
expected = [s - mean_shaped for s in shaped]
assert result.advantages == pytest.approx(expected, abs=1e-6)
# Zero-mean
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
# Shortest has highest advantage
assert result.advantages[0] > result.advantages[1] > result.advantages[2]
def test_linear_length_penalty_zero_pass_rate_disables_penalty():
"""A never-solved group (mean reward 0) gets no length pressure — falls back to plain GRPO."""
inputs = _make_group(rewards=[0.0, 0.0, 0.0], completion_lengths=[10, 50, 200])
penalized = default_advantage_fn(inputs, length_penalty=LinearLengthPenaltyConfig(coef=5.0), max_seq_len=100)
plain = default_advantage_fn(inputs)
assert penalized.advantages == pytest.approx(plain.advantages, abs=1e-6)
def test_efficiency_all_zero_rewards():
"""When all rewards are 0, no length shaping — falls back to standard GRPO."""
inputs = _make_group(rewards=[0.0, 0.0, 0.0], completion_lengths=[10, 20, 15])
result_with = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
result_without = default_advantage_fn(inputs)
def test_linear_length_penalty_gate_by_correctness():
"""Gating scales each rollout's penalty by its reward, so reward-0 rollouts are untouched."""
rewards = [1.0, 1.0, 0.0, 0.0]
inputs = _make_group(rewards=rewards, completion_lengths=[10, 20, 30, 40])
cfg = LinearLengthPenaltyConfig(coef=2.0, gate_by_correctness=True)
result = default_advantage_fn(inputs, length_penalty=cfg, max_seq_len=100)
assert result_with.advantages == pytest.approx(result_without.advantages, abs=1e-6)
pass_rate = sum(rewards) / len(rewards) # 0.5
penalized = [r - r * 2.0 * pass_rate * (length / 100) for r, length in zip(rewards, (10, 20, 30, 40))]
mean = sum(penalized) / len(penalized)
assert result.advantages == pytest.approx([p - mean for p in penalized], abs=1e-6)
def test_efficiency_single_correct():
"""Single correct rollout: bonus=0 (at its own mean), same as standard GRPO."""
inputs = _make_group(rewards=[1.0, 0.0, 0.0, 0.0], completion_lengths=[100, 50, 200, 150])
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
def test_setup_advantage_fn_threads_max_seq_len():
"""``setup_advantage_fn`` threads ``max_seq_len`` into the linear penalty denominator."""
rewards = [1.0, 1.0]
inputs = _make_group(rewards=rewards, completion_lengths=[10, 30])
fn = setup_advantage_fn(DefaultAdvantageConfig(length_penalty=LinearLengthPenaltyConfig(coef=1.0)), max_seq_len=100)
result = fn(inputs)
assert result.advantages == pytest.approx([0.75, -0.25, -0.25, -0.25], abs=1e-6)
pass_rate = sum(rewards) / len(rewards) # 1.0
penalized = [1.0 - 1.0 * pass_rate * (length / 100) for length in (10, 30)]
mean = sum(penalized) / len(penalized)
assert result.advantages == pytest.approx([p - mean for p in penalized], abs=1e-6)
def test_efficiency_shorter_correct_higher_advantage():
"""Among correct rollouts in a mixed group, shorter always gets higher advantage."""
inputs = _make_group(rewards=[1.0, 1.0, 1.0, 0.0, 0.0], completion_lengths=[50, 100, 200, 80, 120])
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
def test_train_env_threads_max_seq_len_into_advantage_fn(monkeypatch):
"""TrainEnv-built advantage funcs use orchestrator seq_len for length penalties."""
advs = result.advantages
assert advs[0] > advs[1] > advs[2]
assert all(a > 0 for a in advs[:3])
assert all(a < 0 for a in advs[3:])
def fake_env_init(self, config):
self.config = config
self._env = None
self._env_client = None
self._env_server_process = None
def test_efficiency_zero_mean_per_group():
"""Reward shaping preserves zero-mean advantages within each group."""
mixed = default_advantage_fn(
_make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20]),
length_penalty=_TOKENS_COMPLETION,
)
all_correct = default_advantage_fn(
_make_group(rewards=[1.0, 1.0, 1.0, 1.0], completion_lengths=[10, 20, 40, 80]),
length_penalty=_TOKENS_COMPLETION,
monkeypatch.setattr(Env, "__init__", fake_env_init)
config = OrchestratorConfig(
seq_len=100,
advantage={"type": "default", "length_penalty": {"coef": 1.0}},
)
assert sum(mixed.advantages) == pytest.approx(0.0, abs=1e-6)
assert sum(all_correct.advantages) == pytest.approx(0.0, abs=1e-6)
env = TrainEnv(config.train.env[0], max_seq_len=config.seq_len)
assert env.advantage_fn is not None
result = env.advantage_fn(_make_group(rewards=[1.0, 1.0], completion_lengths=[10, 30]))
assert result.advantages == pytest.approx([0.1, -0.1], abs=1e-6)
def test_efficiency_amplification_bounded():
"""Even with extreme length outliers, reward amplification is capped at 2x."""
inputs = _make_group(rewards=[1.0, 1.0, 0.0], completion_lengths=[1, 10000, 5000])
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
# Shortest correct gets bonus ≈ 1, so shaped_reward ≈ 2
# Standard reward = 1, so amplification ≈ 2x
# shaped_rewards ≈ [2, 1, 0], baseline ≈ 1, max advantage ≈ 1
assert result.advantages[0] < 1.0 + 1e-3
def test_efficiency_tokens_with_tool_response_weight():
"""`tool_response_weight` shifts shaping onto tool-response tokens read from rollout metrics."""
rollouts = [
{
"reward": 1.0,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
"metrics": {"rlm_total_tool_response_tokens": 200},
def test_per_env_linear_advantage_uses_runtime_schema():
config = OrchestratorConfig(
seq_len=100,
train={
"env": [
{
"advantage": {
"type": "default",
"length_penalty": {"coef": 1.0},
},
}
],
},
{
"reward": 1.0,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
"metrics": {"rlm_total_tool_response_tokens": 0},
},
{
"reward": 1.0,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
"metrics": {"rlm_total_tool_response_tokens": 100},
},
]
inputs = AdvantageInputs(rollouts=rollouts)
# completion tokens identical (10 each) → completion-only shaping is a no-op
result_completion_only = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
assert result_completion_only.advantages == pytest.approx([0.0, 0.0, 0.0], abs=1e-6)
# tool-response only: costs are [200, 0, 100], mean=100, bonus is one-sided
# so only the below-mean rollout (idx 1) gets amplified; the at/above-mean tie.
result_tool_only = default_advantage_fn(inputs, length_penalty=_TOKENS_TOOL_ONLY)
advs = result_tool_only.advantages
assert advs[1] > advs[0]
assert advs[1] > advs[2]
assert advs[0] == pytest.approx(advs[2], abs=1e-6)
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
def test_efficiency_fractional_weight_with_int_rewards():
"""Fractional weights must not truncate when rollout rewards are emitted as ints."""
rollouts_int = [
{"reward": 1, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(7))}}]},
{"reward": 1, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(11))}}]},
{"reward": 0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(13))}}]},
]
rollouts_float = [{**r, "reward": float(r["reward"])} for r in rollouts_int]
fractional = TokensLengthPenaltyConfig(completion_weight=0.3, tool_response_weight=0.0)
int_result = default_advantage_fn(AdvantageInputs(rollouts=rollouts_int), length_penalty=fractional)
float_result = default_advantage_fn(AdvantageInputs(rollouts=rollouts_float), length_penalty=fractional)
assert int_result.advantages == pytest.approx(float_result.advantages, abs=1e-6)
def test_efficiency_zero_costs_falls_back_to_plain_grpo():
"""When all effective costs are zero, shaping is a no-op (no NaNs from div-by-zero)."""
# tool-only weights but no harness metric → all costs == 0
rollouts = [
{"reward": 1.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
{"reward": 1.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
{"reward": 0.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
]
inputs = AdvantageInputs(rollouts=rollouts)
result = default_advantage_fn(inputs, length_penalty=_TOKENS_TOOL_ONLY)
expected = default_advantage_fn(inputs) # plain GRPO
assert not any(math.isnan(a) for a in result.advantages)
assert result.advantages == pytest.approx(expected.advantages, abs=1e-6)
def test_efficiency_tokens_default_weights_match_completion_when_no_metric():
"""Default TokensLengthPenaltyConfig (1,1) reduces to completion-only when rollouts lack the metric."""
inputs = _make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20])
result_default = default_advantage_fn(inputs, length_penalty=TokensLengthPenaltyConfig())
result_completion = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
assert result_default.advantages == pytest.approx(result_completion.advantages, abs=1e-6)
def test_efficiency_turns_penalty():
"""`TurnsLengthPenaltyConfig` shapes by trajectory turn count rather than token count."""
inputs = _make_group(
rewards=[1.0, 1.0, 0.0, 1.0],
# token counts identical, but turns differ — turns penalty should still differentiate
completion_lengths=[100, 100, 100, 100],
num_turns=[1, 3, 2, 2],
)
result = default_advantage_fn(inputs, length_penalty=TurnsLengthPenaltyConfig())
# mean_correct_turns = (1+3+2)/3 = 2
# bonus = clamp(1 - [1,3,2,2]/2, 0, 1) = [0.5, 0, 0, 0]
assert result.advantages == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
advantage = config.train.env[0].advantage
assert isinstance(advantage, DefaultAdvantageConfig)
assert isinstance(advantage.length_penalty, LinearLengthPenaltyConfig)
fn = setup_advantage_fn(advantage, max_seq_len=config.seq_len)
result = fn(_make_group(rewards=[1.0, 1.0], completion_lengths=[10, 30]))
assert result.advantages == pytest.approx([0.1, -0.1], abs=1e-6)
def test_per_env_custom_advantage_uses_runtime_schema():
config = OrchestratorConfig(
train={
"env": [
{
"advantage": {
"type": "custom",
"import_path": "tests.unit.orchestrator.test_advantage._dummy_custom_advantage",
"kwargs": {"scale": 3.0},
},
}
],
},
)
advantage = config.train.env[0].advantage
assert isinstance(advantage, CustomAdvantageConfig)
fn = setup_advantage_fn(advantage)
result = fn(_make_group(rewards=[1.0, 0.5], completion_lengths=[10, 20]))
assert result.advantages == pytest.approx([3.0, 1.5], abs=1e-6)
def test_length_weighted_baseline():
"""Length-weighted baseline uses sum(len_i * reward_i) / sum(len_i) instead of the plain mean."""
rewards = [1.0, 0.0, 0.0]
inputs = _make_group(rewards=rewards, completion_lengths=[10, 30, 60])
result = default_advantage_fn(inputs, length_weighted_baseline=True)
baseline = (10 * 1.0 + 30 * 0.0 + 60 * 0.0) / (10 + 30 + 60) # 0.1
assert result.advantages == pytest.approx([r - baseline for r in rewards], abs=1e-6)
# Token-weighted mean of advantages is zero
assert sum(length * adv for length, adv in zip((10, 30, 60), result.advantages)) == pytest.approx(0.0, abs=1e-5)
def _train_rollouts(rewards: list[float]) -> list[TrainRollout]:
+154 -83
View File
@@ -1,8 +1,15 @@
from types import SimpleNamespace
import numpy as np
import pytest
from prime_rl.trainer.batch import prepare_batch, prepare_sample
from prime_rl.transport.types import RoutedExperts, TrainingSample
from prime_rl.trainer.batch import (
pad_micro_batch,
prepare_batch,
prepare_sample,
)
from prime_rl.trainer.utils import build_bin_cost
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingSample
def _routed_experts(data, dtype=np.uint8):
@@ -37,51 +44,80 @@ def make_training_example():
return _make_training_example
def test_training_sample_requires_env_name():
with pytest.raises(TypeError, match="env_name"):
TrainingSample(
prompt_ids=[1, 2],
prompt_mask=[False, False],
completion_ids=[3, 4],
completion_mask=[True, True],
completion_logprobs=[-0.1, -0.2],
completion_temperatures=[1.0, 1.0],
advantage=1.0,
)
@pytest.mark.parametrize(
("rollout_count", "num_train_workers", "expected_batches_per_worker"), [(4, 2, 2), (5, 2, 3), (7, 1, 7), (11, 4, 3)]
)
def test_prepare_batch_balances_micro_batches_across_workers(
make_training_example, rollout_count, num_train_workers, expected_batches_per_worker
):
examples = [make_training_example() for i in range(rollout_count)]
batches_per_gpu = prepare_batch(
rollouts=examples,
seq_len=4,
num_train_workers=num_train_workers,
idxs=[0] * rollout_count,
num_loras=1,
def make_sized_training_example(length: int, env_name: str = "test-env") -> TrainingSample:
assert length >= 1
prompt_len = length - 1
return TrainingSample(
prompt_ids=[1] * prompt_len,
prompt_mask=[False] * prompt_len,
completion_ids=[2],
completion_mask=[True],
completion_logprobs=[-0.1],
completion_temperatures=[1.0],
advantage=1.0,
env_name=env_name,
)
assert all(len(worker_batches) == expected_batches_per_worker for worker_batches in batches_per_gpu)
flat_batches = [batch for worker_batches in batches_per_gpu for batch in worker_batches]
assert len(examples) <= len(flat_batches) < len(examples) + num_train_workers
print(flat_batches)
def _flatten_batches(batches_per_gpu):
return [batch for worker_batches in batches_per_gpu for batch in worker_batches]
# Verify real rollouts have expected non-zero advantages and loss mask
for batch in flat_batches[: len(examples)]:
print(batch)
assert sum(1 for advantage in batch.advantages if advantage != 0.0) == 4
assert sum(1 for loss_mask in batch.loss_mask if loss_mask) == 2
# Verify padded batches have zero advantages and loss mask
for batch in flat_batches[len(examples) :]:
assert sum(1 for advantage in batch.advantages if advantage != 0.0) == 0
assert sum(1 for loss_mask in batch.loss_mask if loss_mask) == 0
def _worker_token_sums(batches_per_gpu) -> list[int]:
return [sum(len(batch.input_ids) for batch in worker_batches) for worker_batches in batches_per_gpu]
def _has_loss_tokens(batch: MicroBatch) -> bool:
return any(batch.loss_mask)
def make_flops_config():
return SimpleNamespace(
hidden_size=16,
num_attention_heads=2,
num_key_value_heads=2,
vocab_size=32,
intermediate_size=64,
num_hidden_layers=2,
head_dim=8,
)
def test_randomized_packing_invariants():
rng = np.random.default_rng(0)
for case_idx in range(80):
seq_len = int(rng.choice([8, 16, 32, 64]))
num_train_workers = int(rng.choice([1, 2, 4, 8]))
num_samples = int(rng.integers(1, 65))
lengths = [int(x) for x in rng.integers(1, seq_len + 1, size=num_samples)]
examples = [make_sized_training_example(length, env_name=f"env-{case_idx}") for length in lengths]
bin_cost = build_bin_cost(make_flops_config() if case_idx % 2 == 0 else None)
batches_per_gpu = prepare_batch(
rollouts=examples,
seq_len=seq_len,
num_train_workers=num_train_workers,
idxs=[0] * len(examples),
num_loras=1,
bin_cost=bin_cost,
)
flat_batches = _flatten_batches(batches_per_gpu)
real_batches = [batch for batch in flat_batches if _has_loss_tokens(batch)]
dummy_batches = [batch for batch in flat_batches if not _has_loss_tokens(batch)]
assert all(len(worker_batches) == len(batches_per_gpu[0]) for worker_batches in batches_per_gpu)
assert sorted(length for batch in real_batches for length in batch.sequence_lengths) == sorted(lengths)
for batch in flat_batches:
assert len(batch.input_ids) <= seq_len
assert sum(batch.sequence_lengths) == len(batch.input_ids)
assert sum(batch.lora_num_tokens) == len(batch.input_ids)
assert len(batch.env_names) == len(batch.input_ids)
for batch in dummy_batches:
assert not any(batch.loss_mask)
assert not any(batch.advantages)
def test_prepare_batch_packs_different_temperatures(make_training_example):
@@ -95,9 +131,10 @@ def test_prepare_batch_packs_different_temperatures(make_training_example):
num_train_workers=1,
idxs=[0, 0],
num_loras=1,
bin_cost=build_bin_cost(None),
)
flat_batches = [batch for worker_batches in batches_per_gpu for batch in worker_batches]
flat_batches = _flatten_batches(batches_per_gpu)
# With per-token temperatures, samples can now be packed together
assert len(flat_batches) == 1
# Each sample has 4 tokens (2 prompt + 2 completion), so 8 total tokens
@@ -107,14 +144,18 @@ def test_prepare_batch_packs_different_temperatures(make_training_example):
# Second sample (4 tokens): all get temp 1.1
assert flat_batches[0].temperatures[4:8] == [1.1, 1.1, 1.1, 1.1]
assert flat_batches[0].env_names == ["env-a"] * 4 + ["env-b"] * 4
assert flat_batches[0].sequence_lengths == [4, 4]
def test_prepare_sample_propagates_training_mode(make_training_example):
example = make_training_example(training_mode="sft")
def test_pad_micro_batch_preserves_explicit_sequence_lengths(make_training_example):
micro_batch = prepare_sample(make_training_example(), seq_len=16)
micro_batch = prepare_sample(example, seq_len=16)
padded = pad_micro_batch(micro_batch, pad_to_multiple_of=6)
assert micro_batch.training_mode == "sft"
assert len(padded.input_ids) == 6
assert padded.sequence_lengths == [4, 2]
assert sum(padded.sequence_lengths) == len(padded.input_ids)
assert padded.loss_mask[-2:] == [False, False]
def test_prepare_batch_does_not_pack_mixed_training_mode(make_training_example):
@@ -127,33 +168,80 @@ def test_prepare_batch_does_not_pack_mixed_training_mode(make_training_example):
num_train_workers=1,
idxs=[0, 0],
num_loras=1,
bin_cost=build_bin_cost(None),
)
flat_batches = [batch for worker_batches in batches_per_gpu for batch in worker_batches]
flat_batches = _flatten_batches(batches_per_gpu)
assert len(flat_batches) == 2
assert {batch.training_mode for batch in flat_batches} == {"rl", "sft"}
assert [batch.sequence_lengths for batch in flat_batches] == [[4], [4]]
def test_prepare_sample_with_routed_experts():
"""Routed experts are passed through prepare_sample and match input_ids length."""
# 2 prompt + 2 completion = 4 tokens, 2 layers, topk=2
routed_experts = [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[0, 2], [1, 3]], [[1, 0], [3, 2]]]
routed_payload = _routed_experts(routed_experts)
sample = TrainingSample(
prompt_ids=[1, 2],
prompt_mask=[False, False],
completion_ids=[3, 4],
completion_mask=[True, True],
completion_logprobs=[-0.1, -0.2],
completion_temperatures=[1.0, 1.0],
advantage=1.0,
env_name="test-env",
routed_experts=routed_payload,
def test_split_to_align_avoids_dummy_micro_batches():
examples = [make_sized_training_example(length) for length in [6, 6, 5, 5, 4, 4]]
batches_per_gpu = prepare_batch(
rollouts=examples,
seq_len=12,
num_train_workers=4,
idxs=[0] * len(examples),
num_loras=1,
bin_cost=build_bin_cost(None),
)
micro_batch = prepare_sample(sample, seq_len=8)
assert micro_batch.routed_experts is not None
assert micro_batch.routed_experts == routed_payload
assert all(_has_loss_tokens(batch) for batch in _flatten_batches(batches_per_gpu))
assert len(_flatten_batches(batches_per_gpu)) == 4
def test_pack_first_then_balance_distributes_micro_batches_by_tokens_without_model_config():
examples = [make_sized_training_example(length) for length in [100, 90, 80, 70]]
balanced = prepare_batch(
rollouts=examples,
seq_len=100,
num_train_workers=2,
idxs=[0] * len(examples),
num_loras=1,
bin_cost=build_bin_cost(None),
)
assert _worker_token_sums(balanced) == [170, 170]
def test_flop_aware_balancing_pairs_long_and_short_sequence_workloads():
examples = [make_sized_training_example(length) for length in [32, 32, 16, 16, 16, 16]]
bin_cost = build_bin_cost(make_flops_config())
balanced = prepare_batch(
rollouts=examples,
seq_len=32,
num_train_workers=2,
idxs=[0] * len(examples),
num_loras=1,
bin_cost=bin_cost,
)
assert sorted([sorted(batch.sequence_lengths) for batch in balanced[0]]) == [[16, 16], [32]]
assert sorted([sorted(batch.sequence_lengths) for batch in balanced[1]]) == [[16, 16], [32]]
assert bin_cost([32]) > bin_cost([16, 16])
def test_flop_aware_split_to_align_splits_heaviest_flop_bin():
examples = [make_sized_training_example(length) for length in [20, 18, 9, 9, 8, 8, 8]]
batches_per_gpu = prepare_batch(
rollouts=examples,
seq_len=64,
num_train_workers=4,
idxs=[0] * len(examples),
num_loras=1,
bin_cost=build_bin_cost(make_flops_config()),
)
real_batches = [batch for batch in _flatten_batches(batches_per_gpu) if _has_loss_tokens(batch)]
assert len(real_batches) == 4
assert sorted(length for batch in real_batches for length in batch.sequence_lengths) == [8, 8, 8, 9, 9, 18, 20]
assert sum(len(batch.sequence_lengths) > 1 for batch in real_batches) == 3
def test_prepare_sample_truncates_routed_experts():
@@ -177,20 +265,3 @@ def test_prepare_sample_truncates_routed_experts():
assert micro_batch.routed_experts is not None
assert micro_batch.routed_experts == expected_payload
assert micro_batch.env_names == ["test-env"] * 3
def test_prepare_sample_none_routed_experts():
"""When routed_experts is None, micro_batch.routed_experts is None."""
sample = TrainingSample(
prompt_ids=[1, 2],
prompt_mask=[False, False],
completion_ids=[3, 4],
completion_mask=[True, True],
completion_logprobs=[-0.1, -0.2],
completion_temperatures=[1.0, 1.0],
advantage=1.0,
env_name="test-env",
)
micro_batch = prepare_sample(sample, seq_len=8)
assert micro_batch.routed_experts is None
+49 -3
View File
@@ -26,9 +26,8 @@ CONFIG_CLASSES = [
def get_config_files() -> list[Path]:
"""Any TOML file inside `configs/` or `examples/` (skips the configs/private/ submodule)."""
private = Path("configs/private")
config_files = [p for p in Path("configs").rglob("*.toml") if private not in p.parents]
"""Any TOML file inside `configs/` or `examples/`."""
config_files = list(Path("configs").rglob("*.toml"))
example_files = list(Path("examples").rglob("*.toml"))
return config_files + example_files
@@ -168,6 +167,53 @@ def test_removed_fused_lm_head_chunk_size_field_is_rejected():
TrainerModelConfig.model_validate({"fused_lm_head_chunk_size": "auto"})
def test_trainer_enable_token_export_cli_flag():
assert not cli(TrainerConfig, args=[]).enable_token_export
assert cli(TrainerConfig, args=["--enable-token-export"]).enable_token_export
def test_single_node_auto_inference_client_dp_rank_count_matches_local_dp():
config = RLConfig.model_validate(
{
"trainer": {},
"orchestrator": {},
"inference": {"parallel": {"tp": 1}},
"deployment": {
"type": "single_node",
"gpus_per_node": 4,
"num_train_gpus": 2,
"num_infer_gpus": 2,
},
}
)
assert config.inference is not None
assert config.inference.parallel.dp == 2
assert config.orchestrator.student.client.dp_rank_count == 2
def test_multi_node_auto_inference_client_dp_rank_count_uses_router_url():
config = RLConfig.model_validate(
{
"trainer": {},
"orchestrator": {},
"inference": {"parallel": {"tp": 4}},
"deployment": {
"type": "multi_node",
"gpus_per_node": 8,
"num_train_nodes": 1,
"num_infer_nodes": 2,
},
"slurm": {},
}
)
assert config.inference is not None
assert config.inference.data_parallel_size_local == 2
assert config.inference.parallel.dp == 2
assert config.orchestrator.student.client.dp_rank_count == 1
def test_orchestrator_vlm_requires_renderer():
with pytest.raises(ValidationError, match="orchestrator.renderer must be set when model.vlm is set"):
OrchestratorConfig.model_validate(
+2 -2
View File
@@ -38,8 +38,8 @@ EXPECTED_PARSERS: list[tuple[str, str | None, str | None]] = [
("PrimeIntellect/INTELLECT-3-FP8", "qwen3_coder", "deepseek_r1"),
("PrimeIntellect/INTELLECT-3.1", "qwen3_coder", "deepseek_r1"),
# NemotronH
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "qwen3_coder", None),
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "qwen3_coder", None),
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "qwen3_coder", "nemotron_v3"),
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "qwen3_coder", "nano_v3"),
# StepFun
("stepfun-ai/Step-3.5-Flash", "step3p5", "step3p5"),
# Qwen3 dense
+49
View File
@@ -0,0 +1,49 @@
import pytest
import torch
from prime_rl.trainer.models.kernels.fp8_utils import (
per_block_cast_to_fp8_tp_triton,
per_block_cast_to_fp8_triton,
per_token_cast_to_fp8_tp_triton,
per_token_cast_to_fp8_triton,
)
pytestmark = [
pytest.mark.gpu,
pytest.mark.skipif(
not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] < 9,
reason="block-fp8 cast kernels use Triton fp8e4nv (e4m3), only supported on Hopper (SM90) and newer",
),
]
@pytest.mark.parametrize("rows,cols", [(256, 256), (256, 512), (512, 256), (1024, 768), (384, 128)])
def test_block_tp_cast_matches_materialized_transpose(rows, cols):
"""The fused transpose+cast is *bit-identical* to unfused."""
torch.manual_seed(rows + cols)
x = torch.randn(rows, cols, device="cuda", dtype=torch.bfloat16) * 0.3
ref_q, ref_s = per_block_cast_to_fp8_triton(x.transpose(0, 1).contiguous(), False)
tp_q, tp_s = per_block_cast_to_fp8_tp_triton(x, False)
assert tp_q.shape == ref_q.shape == (cols, rows)
assert tp_s.shape == ref_s.shape
assert tp_q.is_contiguous()
assert torch.equal(tp_q.view(torch.uint8), ref_q.view(torch.uint8))
assert torch.equal(tp_s, ref_s)
@pytest.mark.parametrize("rows,cols", [(256, 512), (512, 256), (128, 1024), (1024, 768), (384, 512)])
def test_token_tp_cast_matches_materialized_transpose(rows, cols):
"""The fused transpose+cast is *bit-identical* to unfused."""
torch.manual_seed(rows + cols)
x = torch.randn(rows, cols, device="cuda", dtype=torch.bfloat16) * 0.3
ref_q, ref_s = per_token_cast_to_fp8_triton(x.transpose(0, 1).contiguous(), False)
tp_q, tp_s = per_token_cast_to_fp8_tp_triton(x, False)
assert tp_q.shape == ref_q.shape == (cols, rows)
assert tp_s.shape == ref_s.shape
assert tp_q.is_contiguous()
assert torch.equal(tp_q.view(torch.uint8), ref_q.view(torch.uint8))
assert torch.equal(tp_s, ref_s)
+5
View File
@@ -10,6 +10,7 @@ import prime_rl.trainer.runs as runs
from prime_rl.configs.shared import FileSystemTransportConfig
from prime_rl.trainer.rl.packer import MultiPacker
from prime_rl.trainer.runs import setup_multi_run_manager
from prime_rl.trainer.utils import build_bin_cost
from prime_rl.trainer.world import reset_world
from prime_rl.transport.types import TrainingSample
@@ -94,6 +95,7 @@ def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytes
pad_to_multiple_of=1,
tokenizer=None,
config=FileSystemTransportConfig(),
bin_cost=build_bin_cost(None),
start_step=0,
)
@@ -110,3 +112,6 @@ def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytes
sender = sender_holder["sender"]
assert len(sender.sent) == 1
assert len(sender.sent[0][0]) == 1
micro_batch = sender.sent[0][0][0]
assert micro_batch.run_id == "run_test123"
assert micro_batch.run_step == 0
Generated
+779 -106
View File
File diff suppressed because it is too large Load Diff