Compare commits

...
Author SHA1 Message Date
38494ccb41 fix: sync uv.lock to v0.6.0 (#2858)
Tag and Release / auto-tag-on-main (push) Canceled after 0s
Tag and Release / release-from-auto-tag (push) Canceled after 0s
Tag and Release / tag-and-release (push) Canceled after 0s
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The release bump (#2855) updated pyproject.toml but not uv.lock, so
`uv sync --locked` fails on main (CPU Tests, Docker Push).

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 18:52:13 -07:00
375d8596d8 chore: release v0.6.0 (#2855)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 18:00:59 -07:00
e035135126 feat: llm-d (EPP+Envoy) router backend (#2697)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* refactor: drop client-side DP-rank pinning for external-LB

With external-LB data parallelism each DP rank is its own API server on its
own port (the URL is the rank selector), so the client no longer needs the
hybrid-LB `X-data-parallel-rank` header to pin a rollout to an internal DP
shard. Remove the `dp_rank_count` client field + its auto-setup and the
per-rank client expansion: one client per base URL, no rank header. The
router (vllm-router or llm-d EPP) balances across the per-rank endpoints.

This also fixes llm-d routing: the EPP forwards the header to the dp=1
backend, which rejected it ("data_parallel_rank N is out of range").

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

* feat: llm-d (EPP+Envoy) router backend

Add llm-d as a second router backend alongside vllm-router, selected via
`[inference.deployment.router] type = "llm-d"`. Built on the external-LB
launch substrate — the per-rank vLLM engines launch identically; only the
router control plane differs.

- `LlmdRouterConfig`: discriminated-union member with `scorers` (base) +
  per-profile `prefill_scorer_overrides`/`decode_scorer_overrides`,
  `non_cached_tokens`, `decode_sidecar_port`, and a known-scorer validator.
- `launch_router` helper gains an llm-d branch: renders per-replica EPP +
  Envoy + file-discovery endpoints and launches `epp` + `envoy` instead of
  vllm-router. Call sites stay router-agnostic.
- pd-sidecar on each decode node (P/D) for remote-prefill orchestration + NIXL.
- Entrypoints pass the `router` config object to the templates.
- Reject `enable_return_routed_experts` with llm-d (breaks P/D, unverified
  for multi-node).
- SLURM cleanup also clears stale `epp`/`envoy`/`pd-sidecar` processes.
- Presets under `templates/llmd/` + `scripts/install_llmd.sh`; docs + install skill.

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

* fix(inference): mooncake-store + llm-d EPP coexistence on SLURM P/D

- per-rank VLLM_RPC_BASE_PATH: external-LB runs one engine per process (all
  data_parallel_rank_local 0), so the mooncake-store lookup ipc socket collided
  on a node-shared dir; key it by $port. Also avoids an absent submit-node TMPDIR.
- EPP --grpc-health-port 9003 -> 9013: 9003 collided with mooncake_master's
  metrics server on the shared replica-head node, which killed the EPP.
- mooncake_master -default_kv_lease_ttl=3600000: KV blocks were expiring (5s
  default) before the decode side reused them.
- envoy circuit_breakers raised to 100000 on backend + epp clusters: the default
  (~1024) overflowed at high inflight concurrency -> "reset reason: overflow" 500s.
- pd-sidecar launches on every decode node (not just the replica head), else
  decode nodes past the head advertise endpoints nothing serves.

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

* Feat: dockerless llmd install

* chore(configs): add GLM-5.1 llm-d disaggregated RL config

End-to-end RL config used for the GLM-5.1-FP8 llm-d (EPP+Envoy) P/D run:
12 train nodes + 16 inference nodes (8 prefill x2 / 8 decode x2), mooncake KV
store, r2e env. Lives alongside the existing glm5 disaggregated inference preset.

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

* chore(configs): move GLM-5.1 llm-d RL config to dedicated configs/glm5_llmd/

Relocate the end-to-end GLM-5.1-FP8 llm-d (EPP+Envoy) P/D RL config into its own
configs/glm5_llmd/rl.toml (out of glm5_disagg_inference) and refresh it to the
latest tuned version.

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

* feat(inference): per-role prefill/decode vLLM overrides for disaggregated P/D

Add `prefill_vllm_overrides` / `decode_vllm_overrides` to the disaggregated
inference deployment config (mirrors the existing `*_env_overrides`): extra
vLLM config options merged into the per-role `--vllm-extra` JSON for prefill
vs decode ranks on SLURM. Rendered via a small `vllm_overrides_fragment` helper
into the `ROLE_EXTRA` string in the inference / multi-node-RL sbatch templates.

Needed by configs/glm5_llmd/rl.toml (sets `decode_vllm_overrides`), which
otherwise fails `extra="forbid"` validation in test_load_configs.

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

* chore(configs): enable prefill dual-batch-overlap in glm5_llmd config

Set prefill_vllm_overrides = {enable_dbo = true} (the inference-side perf knob
tuned during the GLM-5.1 run). Batch size / num-concurrent / node-scale knobs
left as-is — those are run-specific, not portable config.

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

* chore(configs): tune glm5_llmd prefill/decode replicas (4 prefill / 1 decode)

num_prefill_replicas 2->4, num_decode_replicas 2->1 — the disaggregation split
found to perform best for GLM-5.1 (prefill is the bottleneck; one wide decode
replica maximizes decode KV/batching).

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

* docs: add GLM-5 llm-d example (16-node / 131K trainer) (#2854)

* docs: add GLM-5 llm-d example (16-node / 131K trainer)

Move the glm5_llmd config from configs/ into examples/glm5_llmd/ with a
README, mirroring the other GLM-5 example. Frame llm-d as the faster
router for GLM-5 and document the placeholders users must tweak
(output_dir, slurm partition, mooncake device_name).

Tune the example for a 16-node trainer: seq_len=131072, num_train_nodes=16,
cp=4, and adamw optimizer.

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

* docs: reword GLM-5 llm-d example entry as one-line SLURM deploy

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

* docs: highlight GLM-5 llm-d one-line SLURM deploy in Overview

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

---------

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

---------

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: faresobeid <fares@primeintellect.ai>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
2026-06-22 16:08:07 -07:00
533e992ad2 fix(inference): tolerate KV-transfer finish for already-freed (aborted) reqs (#2843)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(inference): tolerate KV-transfer finish for already-freed (aborted) reqs

In disaggregated P/D (NIXL, optionally + a KV store), a request can be finished
— most often FINISHED_ABORTED from an off-policy cancel, client disconnect, or
request timeout — while it still has in-flight KV transfers. When such a
request's finished_recving and finished_sending both arrive in the same
Scheduler.update_from_output step, the stock
Scheduler._update_from_kv_xfer_finished frees it in the recving branch
(_free_blocks -> del self.requests[req_id]) and then the sending branch hits
`assert req_id in self.requests`, killing the EngineCore. On a DP deployment
that one death cascades to every rank via the gloo finish-state all-reduce and
takes down the whole decode pool.

Observed on two llm-d P/D runs: the genuine crash is always one rank asserting
in _update_from_kv_xfer_finished, the rest are gloo "Connection closed by peer"
cascade victims. It is abort-triggered, not pause/resume-related: it reproduced
during normal stepping (~19k log lines after the last resume, engine actively
running model batches) and on a run with max_off_policy_steps=80000 / zero
off-policy cancellations — driven purely by incidental client-side aborts.

Monkey-patch _update_from_kv_xfer_finished to skip request ids no longer in
self.requests instead of asserting. Their blocks are already freed, so dropping
the stale notification is safe. Installed via the vllm.general_plugins entry
point so it applies in the EngineCore process where the Scheduler runs.

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

* docs: link upstream vLLM issue #46240 in the KV-xfer patch

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

---------

Co-authored-by: faresobeid <fares@primeintellect.ai>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 16:05:22 -07:00
858207d340 add glm 5.2 training support (#2851)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* add glm 5.2 training support

* simplify

* chore: revert accidental research-environments submodule bump

The "add glm 5.2 training support" commit unintentionally moved the
deps/research-environments submodule pointer. Restore it to main's SHA.

---------

Co-authored-by: faresobeid <fares@primeintellect.ai>
2026-06-22 15:33:01 -07:00
minh hoangandGitHub 570463cca2 chore(renderers): bump to submodule to renderers-v0.1.8.dev49 (#2852)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-22 12:28:27 -07:00
JannikStandGitHub 31e81e5b18 feat: support PRIME_RL_REF for runtime source override (#2850)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: support PRIME_RL_REF for runtime source override

Mirrors the existing VERIFIERS_VERSION hook so researchers can dispatch
a run against an arbitrary prime-rl commit/branch/tag without rebuilding
the image. Clones into a per-ref dir under /tmp, seeds the venv from
/app/.venv so heavy wheels (flash-attn, mamba-ssm) survive, then
uv sync --inexact re-installs prime_rl from the override source.

* fix: address bugbot findings on PRIME_RL_REF entrypoint

- Slugify ref for cache dir name so branch names with slashes work.
- Always fetch + checkout on cache hit so mutable refs (branches/tags)
  pick up new commits between pod restarts.
- Move VERIFIERS_VERSION install after the PRIME_RL_REF swap so when
  both are set the install lands in the override venv.

* fix: init submodules and hash-key the override cache dir

- git clone --recurse-submodules so deps/* (verifiers, renderers,
  research-environments, pydantic-config) are populated on cold
  checkout, and refresh on every entrypoint via
  'git submodule update --init --recursive'.
- Rewrite git@github.com SSH URLs to https at runtime so the SSH
  submodule URLs work from pods that have no ssh keys.
- Append md5 hash of the ref to the cache dir name so distinct refs
  that slugify the same way ('feat/foo' vs 'feat-foo') get distinct
  cache dirs.

* fix: drop hardlink seed and key cache on repo+ref

- cp -al hardlinked /app/.venv into the override tree, so the
  subsequent uv sync wrote through to the baked venv on filesystems
  shared with /tmp. Plain cp -a always copies.
- Include PRIME_RL_REPO in the cache-dir hash so the same ref on
  different forks gets distinct cache dirs.

* fix: --all-extras on override sync

uv sync --inexact --no-dev only installed base deps, so env / gpt-oss /
modelexpress changes in the override branch were silently missed. With
--all-extras the override picks them up, and --inexact still keeps
flash-attn-3 / mamba-ssm from the seeded venv.

* fix: mirror image extras explicitly instead of --all-extras

--all-extras pulled in disagg/quack which the baked image does not
ship; their deps (deep-ep, deep-gemm, quack-kernels) would trigger
heavy source builds at pod startup. Mirror Dockerfile.cuda:82's set
exactly so the override venv lines up with the image.

* fix: submodule sync before update to pick up .gitmodules URL changes
2026-06-22 12:15:37 -07:00
samsjaandGitHub 137f8f49c8 [codex] trim orchestrator memory after train steps (#2837)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(orchestrator): trim process memory each train step

* fix(orchestrator): collect garbage before memory trim
2026-06-22 12:13:26 -07:00
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
minh hoangandGitHub e5c9169566 chore: add tasksets/harnesses to exclude-newer ignore list (#2716)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-04 21:48:04 -07:00
65914f924f fix(configs): size dense multi-node NCCL world by inference GPU count (#2707)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The dense multi-node external-LB weight-broadcast world size was computed as total_infer_nodes * api_server_count * tp. api_server_count can resolve to the global DP size (e.g. when parallel.dp is set, or via validator ordering), which double-counts the node dimension, so the trainer's NCCL broadcast waits for more ranks than exist and init deadlocks.

Every allocated inference GPU is one NCCL rank, and the external-LB launcher starts dp_per_node TP-sharded servers per node (gpus_per_node workers/node), so size the world directly as total_infer_nodes * gpus_per_node. This matches the disaggregated path.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 15:40:54 -07:00
halleriteandGitHub b67fd12fe6 chore(renderers): bump submodule to renderers-v0.1.8.dev40 (#2718)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-04 22:13:50 +02:00
JannikStandGitHub e6998a6f41 feat: json logging for inference (vLLM) (#2466)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: json logging for inference (vLLM)

Adds [log] config to InferenceConfig and routes vLLM's stdlib loggers
(plus uvicorn / fastapi / root) through a JSON formatter matching the
trainer/orchestrator shape. Driven via VLLM_LOGGING_CONFIG_PATH so the
config crosses the multiprocessing.spawn boundary into vLLM workers.

* chore: ruff format

* fix: force VLLM_CONFIGURE_LOGGING=1 when setting LOGGING_CONFIG_PATH

vLLM raises at import if VLLM_CONFIGURE_LOGGING=0 and
VLLM_LOGGING_CONFIG_PATH is set. Setting json_logging is an explicit
opt-in to configure vLLM's logger, so override the env var rather than
crash on jobs that have it preset to 0.

* fix: emit tz-aware UTC timestamps in JsonFormatter

Match loguru's tz-aware ISO output so the platform's JsonLogsViewer
parses inference timestamps correctly. Naive timestamps are interpreted
as the viewer's local time, off by the viewer-vs-pod offset.

* fix: propagate top-level [log] settings to inference subconfig

RLConfig.auto_setup_logs already mirrors [log] into trainer and
orchestrator subconfigs. Now that InferenceConfig has its own [log]
field, propagate there too — without this, an RL run with
[log] json_logging=true at the root still emits text vLLM logs because
inference.log defaults to non-JSON.

* fix: guard None inference in auto_setup_logs

RLConfig.inference is Optional and defaults to None for setups like
elastic-inference-pool runs. The previous commit propagated [log]
unconditionally, crashing the validator on any RLConfig without an
[inference] section (caught by the test_load_configs unit tests on
configs/elastic/rl.toml).

* fix: propagate top-level [log] settings to teacher_inference

Mirrors the auto_setup_logs propagation to inference, so teacher
inference servers also pick up shared level / json_logging when they
are configured separately or auto-created without a rollout inference
to deep-copy from.

* fix: map loguru-only levels (TRACE, SUCCESS) before dictConfig

Stdlib logging does not know TRACE/SUCCESS, so setting [log] level =
"trace" or PRIME_LOG_LEVEL=trace would crash setup_vllm_env when JSON
logging is enabled. Map TRACE→DEBUG and SUCCESS→INFO before building
the dictConfig payload.

* fix: route transformers logs through JSON handler

The docstring claimed transformers was covered but the named-loggers
tuple omitted it, so HF model-loading warnings/info were emitted as
plain text in otherwise-JSON inference logs (transformers sets
propagate=False on its own logger).

* fix: preserve per-component json_logging when shared [log] omits it

Codex P2: SharedLogConfig.json_logging defaulted to False, so auto_setup_logs would clobber any per-component (inference, teacher_inference) override back to text whenever the shared [log] section wasn't set. Mirrors the existing 'level' pattern: nullable on SharedLogConfig, gate propagation on the shared value being explicitly set.
2026-06-04 22:05:52 +02:00
halleriteandGitHub 7f6ca61ecc fix(inference): restore NemotronH mixer.D after vLLM 0.22 layerwise reload (#2714)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-04 22:00:06 +02:00
minh hoangandGitHub 434c9c0a42 docker: bump to ubuntu24.04 (#2717)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
mooncake-transfer-engine 0.3.11.post1 only publishes a
manylinux_2_39_aarch64 wheel for ARM (needs glibc ≥ 2.39) and 22.04
ships with glibc 2.35
2026-06-04 12:44:09 -07:00
halleriteandGitHub 3979894bae fix(trainer): disable NemotronH HF-Hub mamba kernels for offline init (#2713)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-04 16:47:47 +02:00
JannikStandGitHub 63af82343d fix(trainer): guard against validation hook crash taking down trainer (#2698)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(trainer): don't crash trainer when validation hook fails

validate_lora_rank dereferenced student.model.lora without a None
check, so an orchestrator config with no LoRA section raised
AttributeError. The hook was called outside get_orchestrator_config's
try/except, so the exception propagated out of discover_runs through
the train loop, killed the master rank, and left worker ranks waiting
forever on rollouts that would never be written.

- Guard model.lora is None in validate_lora_rank so we reject cleanly
- Wrap hook calls in get_orchestrator_config in try/except so any
  future hook bug returns the run to the retry path instead of taking
  down the trainer

* fix(trainer): use safe fallback for hook name in error message

Validation hooks are typed as Callable, so hook.__name__ isn't
guaranteed (callable objects and functools.partial don't have it). If
such a hook raised, the exception handler itself would raise
AttributeError and defeat the try/except.

Per Codex review on #2698.
2026-06-04 18:41:03 +08:00
samsjaandGitHub 5b5f234053 add worlde (#2704)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-04 12:18:42 +02:00
f619e36b63 fix(ckpt): master-only mkdir + barrier to avoid concurrent-mkdir race on parallel FS (#2699)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Path.mkdir(exist_ok=True) re-checks self.is_dir() after EEXIST and re-raises if
it returns False. On a parallel filesystem (beegfs) with concurrent mkdir from
every trainer rank, a non-master rank can hit EEXIST while its metadata cache
hasn't seen the new inode yet -> is_dir() returns False -> FileExistsError,
crashing the trainer mid-save (observed at weights/step_180).

Guard the three all-ranks mkdir sites behind world.is_master + a barrier so only
the master creates the dir and the others wait until it exists:
- CheckpointManager.save_to_path: dataloader_dir
- CheckpointManager.save: ckpt_path.parent
- WeightCheckpointManager.save: step_path

Mirrors the existing master-only guard in WeightCheckpointManager.save_to_path.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-03 18:16:43 +02:00
samsjaandGitHub 563b37a9c7 fix: preserve Qwen3.5 broadcast weight names (#2690)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* exp: add qwen35 kl debug configs

* exp: lower qwen35 wordle kl drift

* fix: preserve qwen3.5 broadcast weight names

* chore: keep qwen35 debug configs local

* chore: clarify qwen3.5 weight naming bypass

* fix: use upstream qwen3.5 conversion mapping

* chore: use released transformers package

* chore: drop qwen3.5 cp patch

* chore: remove wordle env packaging
2026-06-03 07:50:18 -07:00
e7517948f2 chore(slurm): use external-LB everywhere, drop hybrid-LB (#2696)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore(slurm): use external-LB everywhere, drop hybrid-LB

Unify every router-fronted vLLM launch path on external load balancing:
one API server per DP rank on PORT+k, each pinned to its TP slice of GPUs,
with the router balancing across the per-rank endpoints. This removes the
hybrid-LB mode (data_parallel_hybrid_lb / data_parallel_start_rank /
--intra-node-data-parallel-size) from both the RL and standalone-inference
SLURM templates, across multi-node and disaggregated (P/D) deployments.

- Extract the duplicated per-rank vLLM launch into a shared
  `_launch_rank.sh.j2` helper, included once and called from every launch
  site in both templates.
- Build per-rank router worker URLs (BACKEND_PORT+k for multi-node;
  PREFILL_PORT+k / DECODE_PORT+k for P/D).
- TP-correct DP group sizing (DP = nodes_per_role_replica * dp_per_node),
  fixing the latent tp>1 bug where the disaggregated inference path sized
  the group as nodes * gpus_per_node.
- Pass data_parallel_rpc_port + enable_expert_parallel to the multi-node
  standalone-inference template so per-rank MoE EP groups rendezvous
  node-locally.
- Drop the now-dead USE_DISTRIBUTED_EP gate (EP is decided directly by
  enable_expert_parallel).
- Fix a latent apostrophe in a bash -c comment ("can't" -> "cannot") that
  broke `bash -n` on multi-node non-disaggregated renders.
- Route DP rank 0 to the node-level log (node_<rank>.log, the target of the
  top-level inference.log symlink) via a shared `rank_log` helper, so
  inference.log captures real server output again instead of just the preamble;
  ranks 1+ keep their own node_<rank>_rank<k>.log.

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

* refactor(slurm): extract router launch into _launch_router helper

Pull the per-replica vllm-router invocation (repeated across the multi-node
and disaggregated launch sites in both templates) into a shared
`_launch_router.sh.j2` helper: `launch_router <mode:pd|regular> <worker_args>
<port> <policy> <log> [replica_idx]`. Call sites now resolve the worker URLs
and call the helper, instead of inlining the `vllm-router` command four times.

This localizes the router launch to one place — a future llm-d (EPP+Envoy)
backend slots in as a single branch inside the helper rather than touching
every call site.

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

* fix(slurm): per-rank metrics roles + multi-node EP DP coordinator address

Two correctness fixes for the external-LB paths:

- inference_metrics_roles: external-LB exposes one admin client per DP rank,
  but the role list was built per node. Expand it per rank
  (stride = gpus_per_node / tp) so prefill/decode labels line up with the
  per-rank ADMIN_URLS the orchestrator collects metrics from.
- multi-node MoE EP: data_parallel_address was chosen on the global DP rank,
  so every local rank after the first on the replica head got the head
  hostname instead of the head's own IP — non-zero local ranks on the head
  could fail to rendezvous with the DP coordinator when dp_local > 1. Choose
  the address per node (head ranks use LOCAL_IP, other nodes use the head
  hostname), matching the disaggregated path.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-03 04:29:56 +02:00
43f6261454 refactor(inference): RouterConfig on the base inference deployment (#2695)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Introduce a `RouterConfig` (currently just `vllm-router`, with `type`/`port`/
`policy`) and put `router: RouterConfig` on `BaseInferenceDeploymentConfig`,
alongside `backend_port`. Previously `router_port`/`router_policy` lived only on
the multi-node / disaggregated deployment types, so the RL launcher needed
`getattr(inference.deployment, "router_port", 8000)` to cover a multi-node
allocation running a single-node inference deployment (e.g. general_agent).

Now every deployment type carries the router config and the launchers read
`deployment.router.port` / `deployment.router.policy` directly. These are
external-LB serving config — only used when the inference is served as a fleet
behind the router (a multi-node allocation, or a standalone multi-node /
disaggregated inference); a co-located single-node server ignores them.

`RouterConfig` is a `type`-discriminated alias (single member for now), so other
router backends can be added to the union without touching call sites. The SLURM
templates are unchanged — the entrypoints still pass the same `router_port` /
`router_policy` template vars — so the rendered scripts are byte-identical.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-03 04:16:14 +02:00
bf7eab0640 fix(inference): require SLURM for disaggregated deployment (#2694)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
`validate_multi_node_requires_slurm` only checked `multi_node`, but a
disaggregated (P/D) deployment is equally multi-node (separate prefill/decode
node groups + NIXL) and needs SLURM. Without this, a disaggregated
`InferenceConfig` with no slurm passed validation and fell through to the local
launcher, which cannot run it.

The same `InferenceConfig` is also used nested inside `RLConfig`, where slurm
lives at the top level — so also forward top-level `[slurm]` into the nested
inference (RL P/D, e.g. examples/glm5_pd_disag, sets `[slurm]` but not
`[inference.slurm]`). The per-rank `inference.toml` already excludes `slurm`, so
each rank still runs locally — no SLURM-in-SLURM.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-03 02:33:43 +02:00
halleriteandGitHub 8d88f5e302 chore: bump verifiers submodule to main (v1 seq_len fix) (#2692)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-03 00:20:45 +02:00
92 changed files with 4731 additions and 1556 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.
+2 -1
View File
@@ -1,7 +1,7 @@
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
# Build stage - multi-arch base (supports amd64 + arm64)
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu22.04 AS builder
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu24.04 AS builder
LABEL maintainer="prime intellect"
LABEL repository="prime-rl"
@@ -97,6 +97,7 @@ RUN apt-get update && apt-get install -y \
tmux \
iperf \
openssh-server \
git \
git-lfs \
gpg \
sudo \
+13 -2
View File
@@ -38,6 +38,7 @@ PRIME-RL is a framework for large-scale reinforcement learning. It is designed t
5. Multi-node deployment with Slurm and Kubernetes support.
6. Multimodal support for VLMs such as Qwen3-VL.
7. Hackable, modular, and extensible by design.
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/glm5_llmd/README.md).
## Models support
@@ -55,10 +56,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 +111,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.
@@ -212,6 +222,7 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
3. [**Intellect-3.1**](examples/Intellect-3.1/README.md): Reproduce our `INTELLECT-3.1` training run.
4. [**MiniMax-M2.5 SWE**](examples/minimax_m2.5_swe/README.md): Train `MiniMax-M2.5` on agentic SWE tasks.
5. [**High-throughput GLM-5**](examples/glm5_pd_disag/README.md): Train `GLM-5` with PD disaggregation and FP8 inference on SWE.
6. [**High-throughput GLM-5 (llm-d)**](examples/glm5_llmd/README.md): One-line SLURM deployment for `GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload — the faster way to run `GLM-5`.
## Docs
@@ -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
+4 -2
View File
@@ -25,7 +25,7 @@ impl = "custom" # or "hf" to force the HF path
| Family | HF config types | EP | CP |
|---|---|---|---|
| GLM-5 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8` | ✅ | ✅ |
| GLM-5 / GLM-5.2 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8`, `zai-org/GLM-5.2`, `zai-org/GLM-5.2-FP8` | ✅ | ✅ |
| Qwen3 MoE | `Qwen/Qwen3-30B-A3B`, … | ✅ | ✅ |
| Qwen3.5 MoE | `Qwen/Qwen3.5-35B-A3B`, … | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
@@ -38,6 +38,8 @@ impl = "custom" # or "hf" to force the HF path
The custom path enables you to set EP, CP, selective activation checkpointing, FP8 training (`model.fp8 = true`, requires SM90+), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
### Expert Parallelism Backends
`model.ep_comm_backend` picks the all-to-all kernel used for EP dispatch/combine:
@@ -115,7 +117,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
+18 -5
View File
@@ -30,7 +30,7 @@ We support 3 distinct deployment shapes:
Most of the features are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `router_port`, `backend_port`, etc.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `backend_port`, and a `[...deployment.router]` block, etc.
```toml
[inference.deployment]
@@ -102,7 +102,7 @@ tp = 2
dp = 4
```
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing will be handled by the `vllm-router` instance running on the same node as the 1st replica. We aim to support more advanced routing options, such as `llm-d` or `dynamo` in the future. You can read more about the supported routing options in the [router](#router) section.
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing is handled by a router instance running on the same node as the 1st replica — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[...deployment.router]` block. You can read more about the supported routing options in the [router](#router) section.
### Wide-EP
@@ -167,9 +167,22 @@ This will run 3 inference replicas, each running on 6 nodes. Each replica will r
## Router
We use our own fork of [vllm-router](https://github.com/PrimeIntellect-ai/router) as the request handler. We plan to support more advanced proxy options in the future.
Multi-node and disaggregated deployments front their vLLM backends with a router, configured via a discriminated `[...deployment.router]` block (`type = "vllm-router" | "llm-d"`):
Right now, router handles 2 most important things:
```toml
[inference.deployment.router] # or [deployment.router] for the standalone inference entrypoint
type = "llm-d" # "vllm-router" (default) or "llm-d"
# llm-d-only knobs (all optional):
scorers = { "prefix-cache-scorer" = 3.0, "active-request-scorer" = 2.0 } # base, applied to every profile
prefill_scorer_overrides = { "queue-scorer" = 2.0, "kv-cache-utilization-scorer" = 2.0 } # merged onto the P/D prefill profile
decode_scorer_overrides = {} # merged onto the P/D decode profile
non_cached_tokens = 16 # below this many non-cached prompt tokens, skip remote prefill (P/D)
```
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`.
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy. Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
Both backends support the 2 most important things:
- Request routing - KV cache re-use and balanced routing
- P/D disaggregation - handling the prefill and decode stages separately
@@ -252,7 +265,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.
+87
View File
@@ -0,0 +1,87 @@
# High-throughput GLM-5 with llm-d
This example trains `GLM-5.1` with RL on agentic SWE tasks using P/D disaggregation, FP8 inference, and a Mooncake distributed CPU KV store — fronted by the upstream [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy).
**llm-d is the faster way to run GLM-5.** It is the recommended router backend for large GLM-5 runs: its `active-request-scorer` is an in-flight load balancer that spreads requests across ranks immediately, instead of relying on metrics that are scraped on a delay (as the default `vllm-router` does). Combined with prefix-cache affinity for grouped rollouts, this keeps prefill and decode ranks evenly loaded under the bursty request pattern of RL. If you want the simpler default router instead, see the [GLM-5 PD disaggregation example](../glm5_pd_disag/README.md).
## Requirements
You need access to a Slurm cluster with at least **32 nodes** (16 trainer + 16 inference, 8 GPUs each) and a shared filesystem. In this guide we assume the NFS is mounted at `/shared`; you can change it to your own path.
You also need prime-rl cloned on your cluster into the shared filesystem.
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
uv sync --all-extras
```
### Install llm-d
The llm-d router ships as vendored binaries (`epp`, `envoy`, `pd-sidecar`). Build them once into `third_party/llmd/bin`:
```bash
bash scripts/install_llmd.sh
```
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
```bash
touch .env
echo "WANDB_API_KEY=your_wandb_api_key" >> .env
echo "HUGGINGFACE_TOKEN=your_huggingface_token" >> .env
```
### sandbox
The SWE environment is configured to use Prime Intellect Sandboxes. You can find more information about the sandboxes [here](https://docs.primeintellect.ai/sandboxes/overview). You will need to create a sandbox account and add the credentials to the `.env` file. Alternatively, you can adapt the code of the environment to use your own sandbox implementation.
## Tweak before launching
This config is tuned for our cluster — a few values **must** be adapted to yours before you run. Search the config for these markers:
- **`output_dir`** (`# FILL IN`) — point it at your shared filesystem.
- **`[slurm] partition`** (`# FILL IN`) — set it to your cluster's Slurm partition.
- **`[inference.kv_cache_offload] device_name`** (`# do it yourself`) — the list of RDMA NICs for Mooncake. Auto-detection is unreliable, so set it by hand from `nvidia-smi topo -m` on your nodes.
A few more knobs you may want to tune for your hardware:
- **Trainer parallelism** — this config assumes **16 trainer nodes** at **131K** sequence length with `cp = 4` (context parallel) and the `adamw` optimizer. If you have fewer trainer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` accordingly.
- **Scorer weights** (`[inference.deployment.router]`) — the `scorers` / `prefill_scorer_overrides` / `decode_scorer_overrides` weights follow the upstream llm-d P/D guide and are a good starting point; tune them if your prefill/decode balance drifts.
- **Mooncake CPU pool** (`[inference.kv_cache_offload.cpu] num_bytes`) — defaults to 1TB/node; lower it if your nodes have less RAM.
## Tmux session
We recommend using the tmux helper to start the run and look at the logs.
From your Slurm head node:
```bash
bash scripts/tmux.sh glm5-llmd /shared/outputs/glm5-llmd
```
You can then attach to it by doing `tmux attach -t glm5-llmd`.
## Start the run
Run the following command to start the RL training:
PS: If using the tmux helper, you can run the command in the `Terminal` (window 0) pane and look at the logs in the `Logs` (window 1) pane.
```bash
uv run rl @ examples/glm5_llmd/rl.toml --output-dir /shared/outputs/glm5-llmd
```
Output of the command:
```
XXX:XX:XX INFO Wrote subconfigs to /shared/outputs/glm5-llmd/configs [rl.py::515]
XXX:XX:XX INFO Wrote SLURM script to /shared/outputs/glm5-llmd/rl.sbatch [rl.py::534]
XXX:XX:XX INFO Submitting: sbatch /shared/outputs/glm5-llmd/rl.sbatch [rl.py::540]
XXX:XX:XX SUCCESS Submitted batch job YYYY
Logs:
Trainer: tail -F /shared/outputs/glm5-llmd/logs/trainer.log
Orchestrator: tail -F /shared/outputs/glm5-llmd/logs/orchestrator.log
Inference: tail -F /shared/outputs/glm5-llmd/logs/inference.log
Envs: tail -F /shared/outputs/glm5-llmd/logs/envs/*/*/*.log
```
+140
View File
@@ -0,0 +1,140 @@
max_steps = 10000000
seq_len = 131072
output_dir = "/shared/outputs/glm5-llmd" # FILL IN: point at your shared filesystem
clean_output_dir = true
[log]
level = "debug"
[wandb]
project = "glm5-llmd"
name = "base"
[weight_broadcast]
type = "nccl"
port = 29502
timeout = 12000
quantize_in_weight_transfer = true
[deployment]
type = "multi_node"
num_train_nodes = 16
num_infer_nodes = 16
gpus_per_node = 8
num_infer_replicas = 1
[inference.deployment]
type = "disaggregated"
num_prefill_nodes = 8
num_prefill_replicas = 4
num_decode_nodes = 8
num_decode_replicas = 1
# skip warmup for faster start in cost of some jit overhead early
# ucx needs to be set else random segfaults, vllm can't autoset before importing for some reason
prefill_env_overrides = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
decode_env_overrides = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
# gives the most KV cache while keeping decent throughput, KV cache increase comes in from lower deep-ep LL static buffers
prefill_vllm_overrides = {"enable_dbo"=true}
decode_vllm_overrides = {"max_num_batched_tokens"=96, "max_num_seqs"=96}
[inference.deployment.router]
type = "llm-d"
scorers = { "prefix-cache-scorer" = 3.0 } # need some prefix-cache routing, however due to shared mooncake pool do low prio
prefill_scorer_overrides = { "queue-scorer" = 4.0, "active-request-scorer" = 5.0 } # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
decode_scorer_overrides = { "active-request-scorer" = 5.0, "kv-cache-utilization-scorer" = 4.0, "queue-scorer" = 3.0 } # decode doesn't really create queue, it fills in KV cache fast, give 4.0
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
[slurm]
job_name = "glm5-llmd"
partition = "all" # FILL IN: set to your cluster's partition
[trainer]
dist_timeout_seconds = 1800
enable_token_export = true
[trainer.model]
name = "zai-org/GLM-5.1"
impl = "custom"
attn = "flash_attention_2" # ignored with GLM5
fused_lm_head_token_chunk_size = 1024
cp = 4 # context parallel for the 131K seq len
ep = 8
optim_cpu_offload = true
fp8 = true
[trainer.model.ac]
freq = 1
[trainer.model.compile]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.optim]
type = "adamw"
lr = 1e-6
weight_decay = 0.0
[orchestrator]
batch_size = 256
rollouts_per_example = 16
max_inflight_rollouts = 2048
max_off_policy_steps = 8 # 16/32 can be better, 8 is more CPU stable
[orchestrator.model]
name = "zai-org/GLM-5.1-FP8"
[orchestrator.renderer]
name = "glm-5.1"
preserve_all_thinking = true
[orchestrator.train.sampling]
temperature = 1.0
extra_body = {chat_template_kwargs = {clear_thinking = false}}
[[orchestrator.train.env]]
id = "rlm_swe"
name = "r2e"
num_workers = 16
[orchestrator.train.env.args]
max_turns = 300
timeout_seconds = 21600
summarize_at_tokens = [35000, 80000]
poll_interval = 5
rlm_ref = "907115a79b2a50d193863e7ea1f3550acb4386f0"
labels = ["glm5-llmd"]
[orchestrator.advantage]
type = "default"
[inference]
enable_expert_parallel = true
# <0.80 because glm5 layers are too large for 0.85
gpu_memory_utilization = 0.75
enable_eplb = false
use_deep_gemm = true
enable_fp32_lm_head = true
[inference.model]
name = "zai-org/GLM-5.1-FP8"
max_model_len = 131072
tool_call_parser = "glm47"
reasoning_parser = "glm45"
# Speed up GLM-5.1 weight load: EP weight filtering + safetensors prefetch.
[inference.vllm_extra]
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
# Mooncake distributed CPU KV store: 1TB/node shared pool across all inference nodes.
[inference.kv_cache_offload]
type = "mooncake"
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
[inference.kv_cache_offload.cpu]
num_bytes = 1_000_000_000_000 # 1TB per node - 16TB total CPU pool
@@ -5,7 +5,7 @@ from typing import Annotated, Any, Literal, TypeAlias
from pydantic import Field, model_validator
from pydantic_config import BaseConfig
from prime_rl.configs.shared import BaseModelConfig, SlurmConfig
from prime_rl.configs.shared import BaseModelConfig, LogConfig, SlurmConfig
from prime_rl.utils.config import find_package_resource, rgetattr, rsetattr
from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser
@@ -167,10 +167,99 @@ All2AllBackend = Literal[
]
# Known llm-d EPP scorer plugins (used to guard the ``scorers`` map against typos).
KNOWN_SCORERS = frozenset(
{
"prefix-cache-scorer",
"precise-prefix-cache-scorer",
"queue-scorer",
"kv-cache-utilization-scorer",
"active-request-scorer",
"load-aware-scorer",
"running-requests-size-scorer",
"token-load-scorer",
"latency-scorer",
"session-affinity-scorer",
"lora-affinity-scorer",
}
)
class VllmRouterConfig(BaseConfig):
"""PrimeIntellect vllm-router."""
type: Literal["vllm-router"] = "vllm-router"
port: int = 8000
"""Port the router listens on — becomes the client-facing router URL."""
policy: str = "consistent_hash"
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
class LlmdRouterConfig(BaseConfig):
"""llm-d router backend (EPP + Envoy)."""
type: Literal["llm-d"] = "llm-d"
port: int = 8000
"""Port the Envoy gateway listens on — becomes the client-facing router URL."""
scorers: dict[str, float] = {
"prefix-cache-scorer": 3.0,
"active-request-scorer": 2.0,
}
"""EPP scorer name → weight, applied to every routing profile (before the per-profile P/D overrides). Defaults to prefix-cache affinity plus in-flight (active-request) load balancing. Unknown scorer names are rejected."""
prefill_scorer_overrides: dict[str, float] = {
"queue-scorer": 2.0,
"kv-cache-utilization-scorer": 2.0,
}
"""P/D only: scorer → weight merged onto ``scorers`` for the prefill profile (a per-profile weight overrides the base)."""
decode_scorer_overrides: dict[str, float] = {}
"""P/D only: scorer → weight merged onto ``scorers`` for the decode profile (a per-profile weight overrides the base); empty by default."""
non_cached_tokens: int = 16
"""P/D only: requests with fewer than this many non-cached prompt tokens skip remote prefill and run decode-only."""
decode_sidecar_port: int = 8300
"""P/D only: port the decode-side llm-d sidecar listens on."""
@property
def prefill_scorers(self) -> dict[str, float]:
"""Effective prefill-profile scorers: ``scorers`` merged with ``prefill_scorer_overrides``."""
return {**self.scorers, **self.prefill_scorer_overrides}
@property
def decode_scorers(self) -> dict[str, float]:
"""Effective decode-profile scorers: ``scorers`` merged with ``decode_scorer_overrides``."""
return {**self.scorers, **self.decode_scorer_overrides}
@model_validator(mode="after")
def validate_scorers(self):
unknown = (
set(self.scorers) | set(self.prefill_scorer_overrides) | set(self.decode_scorer_overrides)
) - KNOWN_SCORERS
if unknown:
raise ValueError(f"Unknown llm-d scorer(s): {sorted(unknown)}. Known scorers: {sorted(KNOWN_SCORERS)}.")
return self
# Discriminated on ``type`` so the launch path can pick the router backend.
RouterConfig: TypeAlias = Annotated[VllmRouterConfig | LlmdRouterConfig, Field(discriminator="type")]
class BaseInferenceDeploymentConfig(BaseConfig):
gpus_per_node: int = 8
"""GPUs per node."""
backend_port: int = 8100
"""Port for the per-rank vLLM backend instances."""
router: RouterConfig = VllmRouterConfig()
"""Router fronting the per-rank endpoints."""
class SingleNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
type: Literal["single_node"] = "single_node"
@@ -183,15 +272,6 @@ class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
num_nodes: int = Field(2, ge=1)
"""Inference nodes."""
router_port: int = 8000
"""Port for the vllm-router."""
backend_port: int = 8100
"""Port for vLLM backend instances."""
router_policy: str = "consistent_hash"
"""vllm-router routing policy (e.g. ``consistent_hash``, ``round_robin``)."""
# Disaggregated prefill/decode inference. Each replica is split into separate
# prefill and decode node groups. Requires NIXL for KV transfer and a vllm-router
@@ -214,24 +294,24 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
num_decode_replicas: int = Field(1, ge=1)
"""Independent decode vLLM instances. Must evenly divide ``num_decode_nodes``."""
router_port: int = 8000
"""Port for the vllm-router on each replica."""
prefill_port: int = 8100
"""Port for prefill vLLM instances."""
decode_port: int = 8200
"""Port for decode vLLM instances."""
router_policy: str = "consistent_hash"
"""vllm-router routing policy (e.g. ``consistent_hash``, ``round_robin``)."""
prefill_env_overrides: dict[str, str] = {}
"""Extra environment variables exported only on prefill nodes."""
decode_env_overrides: dict[str, str] = {}
"""Extra environment variables exported only on decode nodes."""
prefill_vllm_overrides: dict[str, Any] = {}
"""Extra vLLM config options merged into --vllm-extra only for prefill ranks (SLURM only)."""
decode_vllm_overrides: dict[str, Any] = {}
"""Extra vLLM config options merged into --vllm-extra only for decode ranks (SLURM only)."""
@property
def num_nodes(self) -> int:
return self.num_prefill_nodes + self.num_decode_nodes
@@ -269,6 +349,9 @@ class InferenceConfig(BaseConfig):
parallel: ParallelConfig = ParallelConfig()
"""Multi-node and multi-GPU parallelism (TP, DP, PP)."""
log: LogConfig = LogConfig()
"""Logging configuration."""
enable_lora: bool = False
"""Enable LoRA. Forwarded as ``--enable-lora``."""
@@ -354,8 +437,20 @@ class InferenceConfig(BaseConfig):
@model_validator(mode="after")
def validate_multi_node_requires_slurm(self):
if self.deployment.type == "multi_node" and self.slurm is None:
raise ValueError("Must use SLURM for multi-node deployment.")
if self.deployment.type in ("multi_node", "disaggregated") and self.slurm is None:
raise ValueError("Must use SLURM for multi-node / disaggregated deployment.")
return self
@model_validator(mode="after")
def validate_llmd_no_routed_experts(self):
"""Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node)."""
router = getattr(self.deployment, "router", None)
if router is not None and router.type == "llm-d" and self.enable_return_routed_experts:
raise ValueError(
"The llm-d router backend does not support routed-expert return "
"(enable_return_routed_experts): it breaks P/D and is unverified for multi-node. "
"Use router type 'vllm-router' for routed-expert runs."
)
return self
@model_validator(mode="after")
@@ -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":
@@ -51,10 +51,10 @@ class RLExperimentalConfig(BaseConfig):
class SharedLogConfig(BaseConfig):
level: str | None = None
"""Log level for trainer and orchestrator. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``)."""
"""Log level for trainer, orchestrator, and inference. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``)."""
json_logging: bool = False
"""Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.)."""
"""Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.). Propagated to trainer, orchestrator, and inference."""
class SharedWandbConfig(BaseConfig):
@@ -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
@@ -435,6 +438,25 @@ class RLConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_llmd_no_routed_experts(self):
"""Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node).
Runs after ``auto_setup_router_replay`` so it also catches the
``trainer.enable_router_replay`` path, which sets the inference flag here
(after InferenceConfig's own validators, which therefore miss it).
"""
if self.inference is not None and self.inference.enable_return_routed_experts:
router = getattr(self.inference.deployment, "router", None)
if router is not None and router.type == "llm-d":
raise ValueError(
"The llm-d router backend does not support routed-expert return "
"(inference.enable_return_routed_experts / trainer.enable_router_replay): it "
"breaks P/D and is unverified for multi-node. Use router type 'vllm-router' "
"for router-replay runs."
)
return self
@model_validator(mode="after")
def validate_router_replay_without_kv_offload(self):
if (
@@ -548,11 +570,14 @@ class RLConfig(BaseConfig):
self.inference.api_server_count = dp_per_node
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
# Compute inference_world_size from actual worker count per server:
# each api_server runs tp workers that participate in collective_rpc.
api_server_count = self.inference.api_server_count if self.inference else 1
tp = self.inference.parallel.tp if self.inference else 1
total_infer_workers = self.deployment.total_infer_nodes * api_server_count * tp
# Every allocated inference GPU is a NCCL rank in the weight broadcast.
# The external-LB launcher starts dp_per_node (= gpus_per_node / tp)
# TP-sharded servers per node, i.e. gpus_per_node workers per node, so use
# the GPU count directly. Deriving it from api_server_count double-counts:
# api_server_count can resolve to the *global* DP size, making the node
# factor count twice and NCCL wait for ranks that never connect. Matches
# the disaggregated path below.
total_infer_workers = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
assert self.trainer.weight_broadcast.type == "nccl"
self.trainer.weight_broadcast.host = "0.0.0.0"
self.trainer.weight_broadcast.inference_world_size = total_infer_workers
@@ -580,7 +605,13 @@ class RLConfig(BaseConfig):
total_infer_gpus = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
if "inference_metrics_roles" not in self.orchestrator.model_fields_set:
role_order = ["prefill"] * infer_deploy.num_prefill_nodes + ["decode"] * infer_deploy.num_decode_nodes
# External-LB: one admin client per DP rank, so roles expand per rank
# (stride = dp_local = gpus_per_node / tp). ADMIN_URLS lists all prefill
# ranks, then all decode ranks, per replica — match that order.
stride = self.deployment.gpus_per_node // self.inference.parallel.tp
role_order = ["prefill"] * (infer_deploy.num_prefill_nodes * stride) + ["decode"] * (
infer_deploy.num_decode_nodes * stride
)
self.orchestrator.inference_metrics_roles = role_order * self.deployment.num_infer_replicas
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
assert self.trainer.weight_broadcast.type == "nccl"
@@ -594,16 +625,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"),
@@ -84,8 +84,13 @@ def propagate_shared_fields(data: Any) -> Any:
)
# [log]
propagate("log.level", "trainer.log.level", "orchestrator.log.level")
propagate("log.json_logging", "trainer.log.json_logging", "orchestrator.log.json_logging")
propagate("log.level", "trainer.log.level", "orchestrator.log.level", "inference.log.level")
propagate(
"log.json_logging",
"trainer.log.json_logging",
"orchestrator.log.json_logging",
"inference.log.json_logging",
)
# [ckpt] leaves. (Bare empty ``[ckpt]`` block enablement is at the end.)
# ``orchestrator.ckpt`` has no ``output_dir`` field — trainer-only.
@@ -127,6 +132,12 @@ def propagate_shared_fields(data: Any) -> Any:
propagate("max_steps", "trainer.max_steps", "orchestrator.max_steps")
propagate("seq_len", "trainer.model.seq_len", "orchestrator.seq_len")
# [slurm] → inference: a multi-node RL run drives its inference deployment under
# the same SLURM allocation, so the nested inference inherits [slurm]. This is
# what lets the nested InferenceConfig's multi-node / disaggregated SLURM check
# pass (the per-rank inference.toml drops slurm, so each rank still runs locally).
propagate("slurm", "inference.slurm")
# output_dir: orchestrator gets a ``/run_default`` subdir so trainer +
# orchestrator nest under the same experiment root without colliding.
# Conflicts are reported against the *transformed* sub-config value, not
+16 -7
View File
@@ -1,11 +1,12 @@
[project]
name = "prime-rl"
version = "0.5.0"
version = "0.6.0"
description = "Async RL Training at Scale"
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",
@@ -17,7 +18,7 @@ dependencies = [
"torchvision",
"torchaudio",
"torchdata>=0.11.0",
"transformers",
"transformers==5.6.2",
"vllm>=0.22.0",
"mooncake-transfer-engine>=0.3.10.post2",
"wandb>=0.26.1",
@@ -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,10 +87,13 @@ envs = [
"opencode-swe",
"reverse-text",
"rlm-swe",
"rlm-search",
"rlm-uuid-ctf",
"science-env",
"simpleqa-verified",
"tau2-bench",
"wiki-search",
"wordle",
]
disagg = [
"deep-ep ; platform_machine == 'x86_64'",
@@ -128,7 +132,6 @@ dev = [
"ruff>=0.12.1",
]
[tool.uv]
# Enforce a uv version that supports the friendly-duration form
# (`"7 days"`) in the static pyproject parser. Older uvs silently parse
@@ -147,9 +150,10 @@ environments = [
override-dependencies = [
"nvidia-cudnn-cu12>=9.15",
"nvidia-cutlass-dsl>=4.4.1",
"transformers>=5.1.0.dev0",
"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
@@ -184,6 +188,8 @@ prime-tunnel = false
prime-evals = false
verifiers = false
renderers = false
tasksets = false
harnesses = false
prime-pydantic-config = false
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
vllm-router = false
@@ -205,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 }
@@ -213,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 }
@@ -222,16 +228,19 @@ 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" }
torchvision = { index = "pytorch-cu128" }
torchaudio = { index = "pytorch-cu128" }
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "c1c3424" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl" }
vllm = [
+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"
+67 -1
View File
@@ -4,8 +4,74 @@ set -e
# Set higher ulimit for file descriptors to prevent API timeout issues
ulimit -n 32000 2>/dev/null || echo "Warning: Could not set ulimit (may need --ulimit flag in docker run)"
# Allow runtime override of the prime-rl source itself.
# PRIME_RL_REF can be a git tag, branch, or commit hash. PRIME_RL_REPO
# optionally points at a fork; defaults to the upstream repo.
#
# We clone into a per-ref dir under /tmp, seed the venv from the baked
# /app/.venv so heavy wheels (flash-attn, mamba-ssm, …) survive, then
# `uv sync --inexact` re-installs prime_rl from the override source.
# Workdir + PATH swap so the chart's `uv run trainer/inference/orchestrator`
# resolves the entrypoints from the override venv.
if [ -n "$PRIME_RL_REF" ]; then
PRIME_RL_REPO="${PRIME_RL_REPO:-https://github.com/PrimeIntellect-ai/prime-rl.git}"
# Slug + content hash for the cache dir name. Slug keeps the path
# human-readable; the hash (over repo + ref) prevents collisions
# between distinct refs that slugify the same way (e.g. `feat/foo`
# vs `feat-foo`) and between the same ref on different forks.
REF_SLUG="${PRIME_RL_REF//\//-}"
REF_HASH=$(echo -n "${PRIME_RL_REPO}|${PRIME_RL_REF}" | md5sum | cut -c1-12)
DEST="/tmp/prime-rl-${REF_SLUG}-${REF_HASH}"
# Rewrite ssh://git@github.com URLs to https so submodules listed
# with SSH URLs (deps/verifiers, deps/renderers, deps/research-envs)
# can be cloned from the pod without ssh keys.
git config --global url."https://github.com/".insteadOf "git@github.com:"
if [ ! -d "$DEST/.git" ]; then
echo "[prime-rl] cloning ${PRIME_RL_REPO} for ${PRIME_RL_REF}"
rm -rf "$DEST"
git clone --recurse-submodules "$PRIME_RL_REPO" "$DEST"
fi
# Always fetch + checkout so mutable refs (branches/tags) pick up new
# commits between pod restarts. No-op for immutable SHAs.
echo "[prime-rl] refreshing ${PRIME_RL_REF}"
git -C "$DEST" fetch --quiet --tags --force origin
git -C "$DEST" checkout --quiet --force "$PRIME_RL_REF"
# Fast-forward to upstream tip when PRIME_RL_REF is a branch name.
# Silently no-ops for SHAs/tags (no `origin/<sha>` exists).
git -C "$DEST" reset --hard --quiet "origin/${PRIME_RL_REF}" 2>/dev/null || true
# Refresh submodules to whatever the parent commit pins. `sync`
# picks up URL changes in .gitmodules between checkouts on cache
# hit; `update --init --recursive` applies the pinned SHAs.
git -C "$DEST" submodule sync --recursive
git -C "$DEST" submodule update --init --recursive
if [ ! -d "$DEST/.venv" ]; then
# Seed from the baked venv so the heavy wheels (flash-attn,
# mamba-ssm, …) don't have to be rebuilt. Plain `cp -a` (no
# hardlinks): a subsequent `uv sync` writes into this tree, and
# hardlinks would leak those writes back into /app/.venv when
# /tmp and /app share a filesystem.
cp -a /app/.venv "$DEST/.venv"
fi
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
# Mirror the image's extras (Dockerfile.cuda:82) — explicit instead
# of --all-extras so we don't pull in `disagg` / `quack` and trigger
# heavy source builds (deep-ep, deep-gemm, quack-kernels) at pod
# startup. --inexact keeps the seeded venv's pre-built wheels
# (flash-attn-3, mamba-ssm) in place; uv only rebuilds them if the
# override's lockfile pins different versions.
( cd "$DEST" && uv sync --inexact --no-dev \
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
--extra envs --extra gpt-oss --extra modelexpress \
--group mamba-ssm )
export VIRTUAL_ENV="$DEST/.venv"
export PATH="$DEST/.venv/bin:$PATH"
cd "$DEST"
fi
# Allow runtime override of the verifiers package version.
# VERIFIERS_VERSION can be a git tag, branch, or commit hash.
# VERIFIERS_VERSION can be a git tag, branch, or commit hash. Runs after the
# PRIME_RL_REF swap so when both are set the install lands in the override
# venv (uv pip install targets $VIRTUAL_ENV when exported).
if [ -n "$VERIFIERS_VERSION" ]; then
echo "Installing verifiers version: $VERIFIERS_VERSION"
uv pip install --reinstall-package verifiers \
+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!"
}
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env bash
# Install the llm-d standalone (no-Kubernetes) routing binaries into
# third_party/llmd/bin:
# - epp : llm-d-router Endpoint Picker (the routing brain)
# - pd-sidecar : decode-side proxy for P/D disaggregation
# - envoy : the data-plane proxy that calls the EPP via ext_proc
#
# epp/pd-sidecar are built from a pinned llm-d-router commit. We currently build
# from a small fork that adds P/D disaggregation for vLLM's token-in
# /inference/v1/generate endpoint (prime-rl's renderer / TITO rollout path) —
# upstream's pd-sidecar only disaggregates the OpenAI endpoints, so token-in P/D
# silently runs decode-only. The fork is pending upstream PR
# llm-d/llm-d-router#1458; switch LLMD_ROUTER_REPO back to the upstream repo and
# bump LLMD_ROUTER_REF once it merges. The fork is branched off the upstream
# commit that added the EPP vllmhttp parser (PR #1248), which the renderer path
# also needs.
#
# System Go is not required: a Go toolchain is vendored under third_party/llmd/go
# and used to bootstrap; GOTOOLCHAIN=auto fetches the exact version the module
# pins. Envoy is extracted as a static binary from its release container image
# WITHOUT docker: we build `crane` (pure-Go, talks straight to the OCI registry)
# with the same vendored toolchain and use it to export the image filesystem.
# This is the only step that previously required a docker daemon, which cluster
# compute nodes don't have.
set -euo pipefail
LLMD_ROUTER_REPO="${LLMD_ROUTER_REPO:-https://github.com/S1ro1/llm-d-router.git}"
LLMD_ROUTER_REF="${LLMD_ROUTER_REF:-1ca4243ec84c657b4a5f507a1776d6c15a618d5b}"
GO_BOOTSTRAP_VERSION="${GO_BOOTSTRAP_VERSION:-1.23.4}"
ENVOY_VERSION="${ENVOY_VERSION:-1.36.0}"
ENVOY_IMAGE="${ENVOY_IMAGE:-envoyproxy/envoy:v${ENVOY_VERSION}}"
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
PROJECT_DIR=$(cd "$SCRIPT_DIR/.." && pwd)
LLMD_DIR="$PROJECT_DIR/third_party/llmd"
BIN_DIR="$LLMD_DIR/bin"
GO_ROOT="$LLMD_DIR/go"
SRC_DIR="$LLMD_DIR/src"
GO_TOOLS_BIN="$LLMD_DIR/gotools/bin"
mkdir -p "$BIN_DIR" "$GO_TOOLS_BIN"
# --- Go toolchain (vendored bootstrap; auto-upgrades to the module's version) ---
if [ ! -x "$GO_ROOT/bin/go" ]; then
echo "[install_llmd] downloading bootstrap Go $GO_BOOTSTRAP_VERSION"
rm -rf "$GO_ROOT"
curl -fsSL "https://go.dev/dl/go${GO_BOOTSTRAP_VERSION}.linux-amd64.tar.gz" | tar -xz -C "$LLMD_DIR"
fi
export GOROOT="$GO_ROOT"
export PATH="$GO_ROOT/bin:$PATH"
export GOTOOLCHAIN=auto
echo "[install_llmd] bootstrap $(go version)"
# --- Fetch llm-d-router source at the pinned ref ---
echo "[install_llmd] fetching ${LLMD_ROUTER_REPO}@${LLMD_ROUTER_REF}"
if [ ! -d "$SRC_DIR/.git" ]; then
rm -rf "$SRC_DIR"
git clone --quiet "$LLMD_ROUTER_REPO" "$SRC_DIR"
fi
git -C "$SRC_DIR" remote set-url origin "$LLMD_ROUTER_REPO"
git -C "$SRC_DIR" fetch --quiet origin
git -C "$SRC_DIR" checkout --quiet "$LLMD_ROUTER_REF"
# --- Build epp + pd-sidecar ---
echo "[install_llmd] building epp + pd-sidecar"
( cd "$SRC_DIR" && go build -o "$BIN_DIR/epp" ./cmd/epp && go build -o "$BIN_DIR/pd-sidecar" ./cmd/pd-sidecar )
# --- Envoy static binary (extract from the release image; keep if present) ---
# No docker: build crane with the vendored toolchain and export the image's
# filesystem straight from the registry, then pull out the static envoy binary.
if [ ! -x "$BIN_DIR/envoy" ]; then
if [ ! -x "$GO_TOOLS_BIN/crane" ]; then
echo "[install_llmd] building crane (OCI registry client, no docker needed)"
GOBIN="$GO_TOOLS_BIN" GOFLAGS=-mod=mod \
go install github.com/google/go-containerregistry/cmd/crane@latest
fi
echo "[install_llmd] extracting Envoy ${ENVOY_VERSION} from ${ENVOY_IMAGE}"
"$GO_TOOLS_BIN/crane" export "$ENVOY_IMAGE" - \
| tar -xf - -O usr/local/bin/envoy > "$BIN_DIR/envoy"
chmod +x "$BIN_DIR/envoy"
fi
echo "[install_llmd] installed binaries in $BIN_DIR:"
"$BIN_DIR/epp" --version 2>&1 | head -1 || true
"$BIN_DIR/envoy" --version 2>&1 | head -1 || true
"$BIN_DIR/pd-sidecar" --help >/dev/null 2>&1 && echo " pd-sidecar OK" || true
echo "[install_llmd] done"
+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
+12 -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`.
@@ -61,6 +59,16 @@ Flags: `--workspace DIR`, `--deepep-ref REF` (default `73b6ea4`), `--nvshmem-ver
Verify: `uv run python -c 'import deep_ep; print(deep_ep.__file__)'`.
### llm-d router backend
Multi-node / disaggregated deployments can route through the upstream llm-d Endpoint Picker instead of `vllm-router` (set `[...deployment.router] type = "llm-d"`). It needs three native binaries — install once:
```bash
bash scripts/install_llmd.sh # builds epp + pd-sidecar from a pinned llm-d-router commit (vendored Go), fetches envoy
```
Binaries land in `third_party/llmd/bin/{epp,envoy,pd-sidecar}` (a shared path, so SLURM nodes see them). `epp` is pinned to the commit that includes the `vllmhttp-parser` (PR #1248) so prime-rl's renderer/TITO `/inference/v1/generate` path routes correctly. Override the pin with `LLMD_ROUTER_REF=<sha>`. The EPP + Envoy + endpoints configs are rendered from `templates/llmd/*.yaml.j2` (included into the SLURM script); only the per-node IPv4 addresses are filled in inline at launch time.
## Key files
- `pyproject.toml` — dependencies, extras, dependency groups
+6
View File
@@ -34,6 +34,12 @@ uv run rl @ examples/reverse_text/rl.toml --dry-run
- Config: `RLConfig` (`packages/prime-rl-configs/src/prime_rl/configs/rl.py`)
- Entrypoint: `src/prime_rl/entrypoints/rl.py`
- SLURM: single- and multi-node
- Environment packages: before launching a config with a non-core verifier env id,
verify the package imports under `uv run` (for example
`uv run python -c "import importlib.util; print(importlib.util.find_spec('rlm_swe'))"`).
If a local env exists under `deps/research-environments/environments/` but does not
import, add it to the root `pyproject.toml` env extra, workspace members, and
`[tool.uv.sources]`, then run `uv sync --all-extras`.
## `sft` — SFT training
+23 -7
View File
@@ -1,6 +1,8 @@
import json
import subprocess
import sys
from pathlib import Path
from typing import Any
import tomli_w
@@ -14,6 +16,17 @@ INFERENCE_TOML = "inference.toml"
INFERENCE_SBATCH = "inference.sbatch"
def vllm_overrides_fragment(overrides: dict[str, Any]) -> str:
"""Render per-role vLLM overrides as a JSON fragment for the ROLE_EXTRA bash string.
Returns a leading-comma fragment with quotes escaped for the double-quoted assignment
(e.g. `, \\"max_num_seqs\\": 256`), or an empty string when there are no overrides.
"""
if not overrides:
return ""
return ", " + json.dumps(overrides)[1:-1].replace('"', '\\"')
def write_config(config: InferenceConfig, output_dir: Path, exclude: set[str] | None = None) -> Path:
"""Write resolved config to disk."""
output_dir.mkdir(parents=True, exist_ok=True)
@@ -47,7 +60,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
dp_per_node=dp_per_node,
num_nodes=getattr(config.deployment, "num_nodes", 1),
port=config.server.port,
disaggregated=is_disaggregated,
is_disaggregated=is_disaggregated,
kv_offload=offload is not None,
kv_offload_mooncake=is_mooncake,
kv_offload_cpu_bytes=int(offload.cpu.num_bytes) if is_mooncake else 0,
@@ -65,18 +78,21 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
num_decode_replicas=config.deployment.num_decode_replicas,
prefill_port=config.deployment.prefill_port,
decode_port=config.deployment.decode_port,
router_port=config.deployment.router_port,
router_policy=config.deployment.router_policy,
router=config.deployment.router,
data_parallel_rpc_port=config.data_parallel_rpc_port,
use_deep_gemm=config.use_deep_gemm,
prefill_env_overrides=config.deployment.prefill_env_overrides,
decode_env_overrides=config.deployment.decode_env_overrides,
prefill_vllm_extra_json=vllm_overrides_fragment(config.deployment.prefill_vllm_overrides),
decode_vllm_extra_json=vllm_overrides_fragment(config.deployment.decode_vllm_overrides),
)
elif is_multi_node:
template_vars.update(
router_port=config.deployment.router_port,
router=config.deployment.router,
backend_port=config.deployment.backend_port,
router_policy=config.deployment.router_policy,
data_parallel_rpc_port=config.data_parallel_rpc_port,
enable_expert_parallel=config.enable_expert_parallel,
infer_nodes_per_replica=config.deployment.num_nodes,
)
script = template.render(**template_vars)
@@ -89,7 +105,7 @@ def inference_slurm(config: InferenceConfig):
"""Run inference via SLURM."""
assert config.slurm is not None
logger = setup_logger("info")
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
config_dir = get_config_dir(config.output_dir)
exclude = (
@@ -125,7 +141,7 @@ def inference_local(config: InferenceConfig):
"""Run inference locally."""
from prime_rl.inference.server import setup_vllm_env
logger = setup_logger("info")
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
if config.dry_run:
logger.success("Dry run complete. To start inference locally, remove --dry-run from your command.")
+10 -3
View File
@@ -12,7 +12,9 @@ from threading import Event, Thread
import pynvml
import tomli_w
from prime_rl.configs.inference import VllmRouterConfig
from prime_rl.configs.rl import RLConfig
from prime_rl.entrypoints.inference import vllm_overrides_fragment
from prime_rl.utils.config import cli
from prime_rl.utils.logger import get_logger, setup_logger
from prime_rl.utils.pathing import (
@@ -371,7 +373,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
num_prefill_replicas=infer_deploy.num_prefill_replicas,
num_decode_replicas=infer_deploy.num_decode_replicas,
gpus_per_node=config.deployment.gpus_per_node,
router_port=infer_deploy.router_port,
router=infer_deploy.router,
prefill_port=infer_deploy.prefill_port,
decode_port=infer_deploy.decode_port,
inference_tp=config.inference.parallel.tp,
@@ -379,10 +381,13 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
use_deep_gemm=config.inference.use_deep_gemm,
prefill_env_overrides=infer_deploy.prefill_env_overrides,
decode_env_overrides=infer_deploy.decode_env_overrides,
prefill_vllm_extra_json=vllm_overrides_fragment(infer_deploy.prefill_vllm_overrides),
decode_vllm_extra_json=vllm_overrides_fragment(infer_deploy.decode_vllm_overrides),
dp_per_node=config.deployment.gpus_per_node // config.inference.parallel.tp,
**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(
@@ -396,8 +401,9 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
nodes_per_infer_replica=config.deployment.num_infer_nodes,
num_infer_replicas=config.deployment.num_infer_replicas,
gpus_per_node=config.deployment.gpus_per_node,
router_port=getattr(config.inference.deployment, "router_port", 8000) if config.inference else 8000,
backend_port=getattr(config.inference.deployment, "backend_port", 8100) if config.inference else 8100,
router=config.inference.deployment.router if config.inference else VllmRouterConfig(),
infer_nodes_per_replica=config.deployment.num_infer_nodes,
backend_port=config.inference.deployment.backend_port if config.inference else 8100,
inference_tp=config.inference.parallel.tp if config.inference else 1,
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port if config.inference else 29600,
@@ -405,6 +411,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)
+88
View File
@@ -0,0 +1,88 @@
"""Stdlib `logging`-based JSON formatter and dictConfig for vLLM.
Trainer and orchestrator emit JSON via loguru
(`prime_rl.utils.logger.json_sink`). vLLM uses Python's stdlib
`logging` and spawns workers via `multiprocessing.spawn`, so we can't
share the loguru sink directly. We emit the same flat shape from a
stdlib `Formatter` and drive it via a dictConfig file pointed to by
`VLLM_LOGGING_CONFIG_PATH` — env vars cross the spawn boundary, so
worker processes inherit the same logging config.
"""
import datetime
import json
import logging
import tempfile
import traceback
from pathlib import Path
from typing import Any
class JsonFormatter(logging.Formatter):
"""Emit one JSON object per record matching `build_log_entry` in
`prime_rl.utils.logger` so the platform's JsonLogsViewer renders
inference rows identically to trainer / orchestrator rows."""
def format(self, record: logging.LogRecord) -> str:
entry: dict[str, Any] = {
"timestamp": datetime.datetime.fromtimestamp(record.created, tz=datetime.timezone.utc).isoformat(),
"level": record.levelname,
"message": record.getMessage(),
"module": record.module,
"function": record.funcName,
"line": record.lineno,
}
if record.exc_info:
entry["exception"] = "".join(traceback.format_exception(*record.exc_info))
return json.dumps(entry, default=str)
# Loguru-only level names that stdlib `logging` doesn't recognize.
# Mapped to the nearest stdlib level so `dictConfig` accepts them.
_LOGURU_TO_STDLIB = {"TRACE": "DEBUG", "SUCCESS": "INFO"}
def build_dict_config(level: str = "info") -> dict[str, Any]:
"""`logging.config.dictConfig` payload that routes vLLM, uvicorn,
fastapi, and the root logger through `JsonFormatter` to stdout.
Used inline for the parent process and serialized to disk for vLLM
workers (via `VLLM_LOGGING_CONFIG_PATH`).
"""
upper = _LOGURU_TO_STDLIB.get(level.upper(), level.upper())
handler = {
"class": "logging.StreamHandler",
"formatter": "prime_rl_json",
"level": upper,
"stream": "ext://sys.stdout",
}
# Each named logger is configured explicitly: vLLM, uvicorn, and
# transformers all set propagate=False on their own loggers, so a
# root-only setup wouldn't reach them.
named = ("vllm", "uvicorn", "uvicorn.error", "uvicorn.access", "fastapi", "transformers")
return {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"prime_rl_json": {
"()": "prime_rl.inference.json_logging.JsonFormatter",
},
},
"handlers": {"stdout_json": handler},
"loggers": {
"": {"handlers": ["stdout_json"], "level": upper},
**{name: {"handlers": ["stdout_json"], "level": upper, "propagate": False} for name in named},
},
}
def write_logging_config(level: str = "info") -> Path:
"""Persist a dictConfig JSON to a temp path. Caller sets the path on
`VLLM_LOGGING_CONFIG_PATH` so vLLM (and its spawned workers) load
the same config at import time."""
config = build_dict_config(level)
fd, path_str = tempfile.mkstemp(prefix="prime_rl_logging_", suffix=".json")
path = Path(path_str)
with open(fd, "w", encoding="utf-8") as f:
json.dump(config, f)
return path
+143 -25
View File
@@ -17,10 +17,89 @@ 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_layerwise_reload_alias_buffers()
monkey_patch_vllm_padded_input_scrub()
monkey_patch_return_routed_experts_with_nixl_connector()
monkey_patch_kv_xfer_finished_tolerate_freed()
def monkey_patch_kv_xfer_finished_tolerate_freed():
"""Tolerate KV-transfer finish notifications for already-freed requests.
In disaggregated P/D (NIXL, optionally + a KV store connector) a request can
be finished — most often ``FINISHED_ABORTED`` from an off-policy cancel, a
client disconnect, or a request timeout — while it still has in-flight KV
transfers. When such a request's ``finished_recving`` and ``finished_sending``
both land in the same ``Scheduler.update_from_output`` step, the stock
``_update_from_kv_xfer_finished`` frees it in the recving branch
(``_free_blocks`` -> ``del self.requests[req_id]``) and then the sending
branch hits ``assert req_id in self.requests`` and kills the EngineCore. On a
DP deployment that one death cascades to every rank via the gloo finish-state
all-reduce, taking down the whole inference pool.
The trigger is the abort itself, not weight-update pause/resume: it reproduces
during normal stepping whenever an aborted request's recv and send complete in
the same step (observed with zero off-policy cancellations, driven only by
incidental client-side aborts). Skip already-freed request ids instead of
asserting — their blocks are freed either way, so dropping the stale
notification is safe.
Upstream issue: https://github.com/vllm-project/vllm/issues/46240
"""
from vllm.logger import init_logger
from vllm.v1.core.sched.scheduler import Scheduler
from vllm.v1.request import RequestStatus
logger = init_logger("vllm.v1.core.sched.scheduler")
if getattr(Scheduler._update_from_kv_xfer_finished, "_prime_rl_tolerates_freed", False):
return
def _update_from_kv_xfer_finished(self, kv_connector_output):
if self.connector is not None:
self.connector.update_connector_output(kv_connector_output)
for req_id in kv_connector_output.finished_recving or ():
logger.debug("Finished recving KV transfer for request %s", req_id)
# Stale notification for a request freed earlier this step (e.g. an
# aborted request whose send completion freed it). Nothing to do.
if req_id not in self.requests:
continue
req = self.requests[req_id]
if req.status == RequestStatus.WAITING_FOR_REMOTE_KVS:
self.finished_recving_kv_req_ids.add(req_id)
else:
assert RequestStatus.is_finished(req.status)
self._free_blocks(self.requests[req_id])
for req_id in kv_connector_output.finished_sending or ():
logger.debug("Finished sending KV transfer for request %s", req_id)
# See above: the recving branch may have already freed an aborted
# request whose send also completed this step.
if req_id not in self.requests:
continue
self._free_blocks(self.requests[req_id])
_update_from_kv_xfer_finished._prime_rl_tolerates_freed = True
Scheduler._update_from_kv_xfer_finished = _update_from_kv_xfer_finished
logger.warning("Patched Scheduler._update_from_kv_xfer_finished to tolerate freed (aborted) KV-transfer reqs.")
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():
@@ -67,36 +146,42 @@ def monkey_patch_return_routed_experts_with_nixl_connector():
logger.warning("Enabled vLLM routed-experts capture with NIXL connector patch.")
def monkey_patch_vllm_layerwise_reload_alias_buffers():
# vLLM's layerwise reload materializes each buffer as an independent tensor
# and then copies it back into the original kernel storage. When a buffer
# aliases a parameter (e.g. NemotronH Mamba's mixer.conv_weights, a view of
# mixer.conv1d.weight), the buffer copy stamps garbage into the parameter's
# storage *after* the parameter has been correctly reloaded. Skip the copy
# for any buffer that shares storage with a parameter; _place_kernel_tensors
# re-registers the original view, which trivially reflects the parameter.
# Remove this patch once https://github.com/vllm-project/vllm/pull/42481 is
# included in the vLLM release we pin/use.
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
from vllm.model_executor.model_loader.reload import layerwise as reload_layerwise
logger = init_logger(__name__)
def _copy_and_restore_kernel_tensors(layer: torch.nn.Module, info: reload_layerwise.LayerReloadingInfo):
assert info.kernel_tensors is not None
parameters, buffers = info.kernel_tensors
param_storage_ptrs = {p.untyped_storage().data_ptr() for p in layer.parameters(recurse=True)}
for name, param in parameters.items():
param.data.copy_(getattr(layer, name))
for name, buffer in buffers.items():
if buffer.untyped_storage().data_ptr() in param_storage_ptrs:
continue
buffer.data.copy_(getattr(layer, name))
if getattr(OpenAIServingChat.chat_completion_full_generator, "_prime_rl_strips_routed_experts", False):
return
reload_layerwise._place_kernel_tensors(layer, info)
_original = OpenAIServingChat.chat_completion_full_generator
reload_layerwise._copy_and_restore_kernel_tensors = _copy_and_restore_kernel_tensors
logger.warning("Enabled vLLM layerwise reload alias-buffer patch.")
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
@@ -869,3 +954,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
@@ -1,3 +1,4 @@
import logging.config
import os
from prime_rl.configs.inference import InferenceConfig
@@ -17,6 +18,21 @@ def setup_vllm_env(config: InferenceConfig):
if config.enable_lora:
os.environ["VLLM_ALLOW_RUNTIME_LORA_UPDATING"] = "True"
if config.log.json_logging:
# Route vLLM's stdlib loggers through a JSON formatter matching
# trainer / orchestrator. The env var (not in-process dictConfig)
# is what reaches vLLM's spawned workers.
from prime_rl.inference.json_logging import build_dict_config, write_logging_config
config_path = write_logging_config(config.log.level)
# vLLM raises if VLLM_LOGGING_CONFIG_PATH is set while
# VLLM_CONFIGURE_LOGGING=0 (its supported way to disable logger
# setup). Force it on — opting into JSON logging is an explicit
# request to configure vLLM's logger.
os.environ["VLLM_CONFIGURE_LOGGING"] = "1"
os.environ["VLLM_LOGGING_CONFIG_PATH"] = str(config_path)
logging.config.dictConfig(build_dict_config(config.log.level))
def main():
config = cli(InferenceConfig)
+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
+43 -1
View File
@@ -24,6 +24,37 @@ else:
logger = init_logger("vllm.inference.vllm.worker_nccl")
# NemotronH mixer.D is dropped by vLLM 0.22's layerwise online-reload path (left uninitialized).
_RELOAD_CORRUPTED_SUFFIXES = (".mixer.D",)
def _restore_reload_corrupted_params(model: Module, received: dict[str, torch.Tensor]) -> None:
"""Work around a vLLM 0.22 layerwise-reload bug for NemotronH.
The online reload drops the weight load for every Mamba layer's ``mixer.D`` (the SSD skip
connection), leaving it as uninitialized ``empty_strided`` memory -- it reads back as garbage
(NaN/inf) and the logits go NaN after a weight update. The received broadcast value is correct,
so restore D from it via the param's own ``weight_loader``. Remove once the upstream bug is fixed.
"""
def _layer_key(name: str) -> str:
index = name.find("layers.")
return name[index:] if index >= 0 else name
received_by_key = {_layer_key(name): tensor for name, tensor in received.items()}
for name, param in model.named_parameters():
if not name.endswith(_RELOAD_CORRUPTED_SUFFIXES):
continue
tensor = received_by_key.get(_layer_key(name))
if tensor is None:
continue
tensor = tensor.to(device=param.device)
weight_loader = getattr(param, "weight_loader", None)
if weight_loader is not None:
weight_loader(param, tensor)
elif tensor.shape == param.shape:
param.data.copy_(tensor.to(param.dtype))
def receive_integer(communicator: PyNcclCommunicator) -> int:
"""Receive an integer from the trainer master rank using NCCL communicator."""
@@ -148,9 +179,20 @@ class NCCLWeightUpdateWorker(Worker):
update_mla_absorbed_weights(model)
return
# vLLM 0.22's layerwise reload drops NemotronH mixer.D's weight load (see
# _restore_reload_corrupted_params). Capture the correct received value to restore after.
received_reload_fix: dict[str, torch.Tensor] = {}
def _capture_reload_fix(weights):
for name, tensor in weights:
if name.endswith(_RELOAD_CORRUPTED_SUFFIXES):
received_reload_fix[name] = tensor.detach().to("cpu", copy=True)
yield name, tensor
load_weights_checkpoint_layerwise(
model,
state_iter,
_capture_reload_fix(state_iter),
self.model_runner.model_config,
self.vllm_config,
)
_restore_reload_corrupted_params(model, received_reload_fix)
+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(
+65 -19
View File
@@ -21,7 +21,6 @@ in ``setup()`` and drives them from ``main_loop()``.
from __future__ import annotations
import asyncio
import ctypes
import logging
import os
import time
@@ -72,6 +71,7 @@ from prime_rl.orchestrator.utils import (
save_rollouts,
set_default_executor,
setup_student_inference_pool,
trim_process_memory,
)
from prime_rl.orchestrator.watcher import WeightWatcher
from prime_rl.trainer.model import setup_tokenizer
@@ -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)
@@ -475,10 +482,7 @@ class Orchestrator:
get_logger().success("Orchestrator finished.")
else:
get_logger().warning("Orchestrator cleanup complete (forced).")
try:
ctypes.CDLL("libc.so.6").malloc_trim(0)
except Exception as e:
get_logger().debug(f"malloc_trim(0) failed: {e}")
trim_process_memory()
async def main_loop(self) -> None:
"""Consume ``FinishedRollout``\\ s from the dispatcher and route them
@@ -499,7 +503,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 +513,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,
@@ -578,6 +611,7 @@ class Orchestrator:
await self.sender.send(TrainingBatch(examples=batch.samples, step=step))
self.update_dispatch_gate()
trim_process_memory()
metrics = self.metrics.build(
step=step,
@@ -761,7 +795,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 +804,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 +874,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: ...
+11
View File
@@ -1,4 +1,6 @@
import asyncio
import ctypes
import gc
import logging
import time
from concurrent.futures import ThreadPoolExecutor
@@ -96,6 +98,15 @@ def set_default_executor(max_workers: int = 64) -> None:
asyncio.get_event_loop().set_default_executor(ThreadPoolExecutor(max_workers=max_workers))
def trim_process_memory() -> None:
"""Return freed heap pages to the OS on glibc systems."""
gc.collect()
try:
ctypes.CDLL("libc.so.6").malloc_trim(0)
except Exception as exc:
get_logger().debug(f"malloc_trim(0) failed: {exc!r}")
async def compute_teacher_logprobs(
clients: list[vf.ClientConfig],
model_name: str,
+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)
+34
View File
@@ -0,0 +1,34 @@
{# Shared external-LB vLLM launch helper, included once per template and called
from every per-rank launch site (multi-node and disaggregated).
One vLLM API server per DP rank, pinned to its GPU slice. #}
# rank_log <node_rank> <k> — DP rank 0 logs to the node-level file (node_<rank>.log,
# the target of the top-level inference.log symlink) so it captures real server output;
# ranks 1+ get their own node_<rank>_rank<k>.log.
rank_log() {
if [ "$2" -eq 0 ]; then
echo "$OUTPUT_DIR/logs/inference/node_$1.log"
else
echo "$OUTPUT_DIR/logs/inference/node_$1_rank$2.log"
fi
}
# launch_inference_rank <port> <cuda_visible_devices> <dp> <rpc_port> <vllm_extra_json|""> <nixl_side_channel_port|""> <log_file>
launch_inference_rank() {
local port="$1" gpus="$2" dp="$3" rpc="$4" extra="$5" nixl="$6" log="$7"
# Per-rank dir for the mooncake-store lookup ipc socket. It must be unique per process:
# external-LB runs one engine per process, all with data_parallel_rank_local 0, so the
# lookup socket name collides on bind if the dir is shared node-wide. $port is unique per
# rank on the node. Node-local /tmp also avoids inheriting an absent submit-node TMPDIR.
local rpcbase="/tmp/vllm-rpc-$USER-$SLURM_JOB_ID-$port"
mkdir -p "$rpcbase"
local -a cmd=(uv run inference @ "$CONFIG_PATH"
--server.host 0.0.0.0 --server.port "$port"
--parallel.dp "$dp" --data-parallel-size-local 1 --api-server-count 1)
[ -n "$rpc" ] && cmd+=(--data-parallel-rpc-port "$rpc")
[ -n "$extra" ] && cmd+=(--vllm-extra "$extra")
if [ -n "$nixl" ]; then
CUDA_VISIBLE_DEVICES="$gpus" VLLM_NIXL_SIDE_CHANNEL_PORT="$nixl" VLLM_RPC_BASE_PATH="$rpcbase" "${cmd[@]}" 2>&1 | tee -a "$log" &
else
CUDA_VISIBLE_DEVICES="$gpus" VLLM_RPC_BASE_PATH="$rpcbase" "${cmd[@]}" 2>&1 | tee -a "$log" &
fi
}
@@ -0,0 +1,68 @@
{# Shared router launch helper, included once per template and called by the
replica-head rank. The router backend (vllm-router vs llm-d EPP+Envoy) is
chosen here via router.type, so the call sites stay router-agnostic.
node_base/node_count locate this replica's nodes in HOSTNAMES for llm-d
endpoint discovery (disagg uses NUM_PREFILL_NODES/NUM_DECODE_NODES). #}
# launch_router <mode:pd|regular> <worker_args> <port> <policy> <log> <replica_idx> <node_base> [node_count]
launch_router() {
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5" replica="${6:-0}" node_base="${7:-0}" node_count="${8:-0}"
{%- if router.type == "llm-d" %}
echo "Starting llm-d router (EPP+Envoy) on $LOCAL_IP:$port for replica $replica" | tee "$log"
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
local LLMD_DIR="$OUTPUT_DIR/logs/inference/llmd_${replica}"
mkdir -p "$LLMD_DIR"
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
{%- if is_disaggregated %}
{%- set ep_disaggregated = true %}
{%- set ep_num_prefill = num_prefill_nodes %}
{%- set ep_num_decode = num_decode_nodes %}
{%- set ep_dp = dp_per_node %}
{%- set ep_prefill_port = prefill_port %}
{%- set ep_sidecar_port = router.decode_sidecar_port %}
cat > "$LLMD_DIR/epp.yaml" <<LLMD_EOF
{% include 'llmd/epp_pd.yaml.j2' %}
LLMD_EOF
cat > "$LLMD_DIR/endpoints.yaml" <<LLMD_EOF
{% include 'llmd/endpoints.yaml.j2' %}
LLMD_EOF
local node=0 ip
for ((p=0; p<NUM_PREFILL_NODES; p++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + p))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1)); done
for ((d=0; d<NUM_DECODE_NODES; d++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + NUM_PREFILL_NODES + d))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1)); done
{%- else %}
{%- set ep_disaggregated = false %}
{%- set ep_num_nodes = infer_nodes_per_replica %}
{%- set ep_dp = dp_per_node %}
{%- set ep_backend_port = backend_port %}
cat > "$LLMD_DIR/epp.yaml" <<LLMD_EOF
{% include 'llmd/epp_estimate.yaml.j2' %}
LLMD_EOF
cat > "$LLMD_DIR/endpoints.yaml" <<LLMD_EOF
{% include 'llmd/endpoints.yaml.j2' %}
LLMD_EOF
local ip
for ((n=0; n<node_count; n++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + n))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${n}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; done
{%- endif %}
cat > "$LLMD_DIR/envoy.yaml" <<LLMD_EOF
{% include 'llmd/envoy.yaml.j2' %}
LLMD_EOF
# grpc-health-port avoids 9003: mooncake_master runs its metrics server on 9003 and
# shares the replica-head node with the EPP, so 9003 would fail to bind and kill the EPP.
epp --pool-name prime-rl --pool-namespace slurm \
--config-file "$LLMD_DIR/epp.yaml" \
--grpc-port 9002 --grpc-health-port 9013 --metrics-port 9090 \
--secure-serving=false --metrics-endpoint-auth=false --tracing=false \
>> "$log" 2>&1 &
envoy -c "$LLMD_DIR/envoy.yaml" >> "$log" 2>&1 &
{%- else %}
local tag="vllm-router"; [ "$mode" = pd ] && tag="vllm-router (PD)"
echo "Starting $tag on $LOCAL_IP:$port${replica:+ for replica $replica}" | tee "$log"
local -a cmd=(vllm-router --policy "$policy" --host 0.0.0.0 --port "$port"
--worker-startup-timeout-secs 4200 --log-level debug)
if [ "$mode" = pd ]; then
cmd+=(--vllm-pd-disaggregation $worker_args)
else
cmd+=(--worker-urls $worker_args)
fi
"${cmd[@]}" >> "$log" 2>&1 &
{%- endif %}
}
+6 -3
View File
@@ -5,7 +5,8 @@
SLURM templates inside the per-node `bash -c` body, so NO single quotes / apostrophes.
Requires shell vars: LOCAL_IP, INFER_NODE_RANK, OUTPUT_DIR (and SLURM env).
Requires jinja vars: kv_offload_cpu_bytes, kv_offload_disk_path, kv_offload_device_name.
Exports PYTHONHASHSEED + MOONCAKE_CONFIG_PATH for the vLLM process on this node. -#}
Exports PYTHONHASHSEED + MOONCAKE_CONFIG_PATH for the vLLM process. (VLLM_RPC_BASE_PATH,
used by the mooncake-store lookup ipc socket, is set per-rank in _launch_rank.sh.j2.) -#}
# ---- Mooncake distributed store (shared pool across inference nodes) ----
MC_DIR="$OUTPUT_DIR/mooncake/node_${INFER_NODE_RANK}"
mkdir -p "$MC_DIR"
@@ -23,9 +24,11 @@
{%- endif %}
if [ "$SLURMD_NODENAME" = "$MC_HEAD" ]; then
{%- if kv_offload_disk_path %}
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -enable_offload=true -root_fs_dir={{ kv_offload_disk_path }} > "$MC_DIR/master.log" 2>&1 &
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -default_kv_lease_ttl=3600000 -enable_offload=true -root_fs_dir={{ kv_offload_disk_path }} > "$MC_DIR/master.log" 2>&1 &
{%- else %}
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 > "$MC_DIR/master.log" 2>&1 &
# default_kv_lease_ttl raised from 5s: KV blocks were expiring before the decode side
# reused them ("invalid KV blocks ... may have expired"), the real non-NIC config issue.
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -default_kv_lease_ttl=3600000 > "$MC_DIR/master.log" 2>&1 &
{%- endif %}
fi
# Every node waits for the shared master + metadata, then contributes its segment.
+110 -76
View File
@@ -28,7 +28,7 @@ set -e
# Configs
export NUM_NODES={{ num_nodes }}
export GPUS_PER_NODE={{ gpus_per_node }}
{% if disaggregated -%}
{% if is_disaggregated -%}
export NUM_PREFILL_NODES={{ num_prefill_nodes }}
export NUM_DECODE_NODES={{ num_decode_nodes }}
export NUM_PREFILL_REPLICAS={{ num_prefill_replicas }}
@@ -38,11 +38,15 @@ export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
export PREFILL_PORT={{ prefill_port }}
export DECODE_PORT={{ decode_port }}
export ROUTER_PORT={{ router_port }}
export ROUTER_PORT={{ router.port }}
export RPC_PORT={{ data_parallel_rpc_port }}
{%- if router.type == "llm-d" %}
export DECODE_SIDECAR_PORT={{ router.decode_sidecar_port }}
{%- endif %}
{%- elif num_nodes > 1 %}
export ROUTER_PORT={{ router_port }}
export ROUTER_PORT={{ router.port }}
export BACKEND_PORT={{ backend_port }}
export RPC_PORT={{ data_parallel_rpc_port }}
{%- endif %}
# Paths
@@ -50,6 +54,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
@@ -68,7 +73,7 @@ uv sync --all-extras
# Print inference URLs
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
export HOSTNAMES_STR="${HOSTNAMES[*]}"
{% if disaggregated -%}
{% if is_disaggregated -%}
# Build per-replica router URLs
INFER_URLS=""
ALL_ROUTER_ARGS=""
@@ -78,26 +83,32 @@ for ((r=0; r<NUM_NODES/NODES_PER_REPLICA; r++)); do
INFER_URLS="${INFER_URLS:+$INFER_URLS,}http://${router_host}:${ROUTER_PORT}/v1"
REPLICA_ROUTER_ARGS=""
# External-LB: one --prefill/--decode endpoint per DP rank (PORT + k) on each node.
for ((p=0; p<NUM_PREFILL_NODES; p++)); do
node_idx=$((replica_base + p))
host="${HOSTNAMES[$node_idx]}"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --prefill http://${host}:${PREFILL_PORT}"
host="${HOSTNAMES[$((replica_base + p))]}"
for ((k=0; k<{{ dp_per_node }}; k++)); do
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --prefill http://${host}:$((PREFILL_PORT + k))"
done
done
for ((d=0; d<NUM_DECODE_NODES; d++)); do
node_idx=$((replica_base + NUM_PREFILL_NODES + d))
host="${HOSTNAMES[$node_idx]}"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --decode http://${host}:${DECODE_PORT}"
host="${HOSTNAMES[$((replica_base + NUM_PREFILL_NODES + d))]}"
for ((k=0; k<{{ dp_per_node }}; k++)); do
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --decode http://${host}:$((DECODE_PORT + k))"
done
done
ALL_ROUTER_ARGS="${ALL_ROUTER_ARGS:+$ALL_ROUTER_ARGS|}$REPLICA_ROUTER_ARGS"
done
export INFER_URLS
export ALL_ROUTER_ARGS
{%- elif num_nodes > 1 %}
# Single router on node 0, all nodes as backends
# External LB: one router on node 0; one endpoint per DP rank (BACKEND_PORT + dp_local) on every node.
INFER_URLS="http://${HOSTNAMES[0]}:${ROUTER_PORT}/v1"
DP_PER_NODE={{ dp_per_node }}
ROUTER_ARGS=""
for host in ${HOSTNAMES[@]}; do
ROUTER_ARGS="$ROUTER_ARGS http://${host}:${BACKEND_PORT}"
for ((d=0; d<DP_PER_NODE; d++)); do
ROUTER_ARGS="$ROUTER_ARGS http://${host}:$((BACKEND_PORT + d))"
done
done
export INFER_URLS
export ROUTER_ARGS
@@ -124,6 +135,10 @@ srun bash -s <<'CLEANUP_SH'
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
pkill -9 -f "[t]orchrun" 2>/dev/null
pkill -9 -f "[v]llm-router" 2>/dev/null
# llm-d router procs (EPP + Envoy + decode pd-sidecar) left over from a prior run.
pkill -9 -f "[e]pp.*pool-name" 2>/dev/null
pkill -9 -f "[e]nvoy.*envoy.yaml" 2>/dev/null
pkill -9 -f "[p]d-sidecar" 2>/dev/null
pkill -9 -f "[v]llm" 2>/dev/null
pkill -9 -f "[p]rime_rl" 2>/dev/null
# Also match prctl-set process names (kernel comm) like "vllm::router"
@@ -136,7 +151,7 @@ srun bash -s <<'CLEANUP_SH'
pkill -9 -x mooncake_client 2>/dev/null
sleep 2
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_" | grep -v grep | wc -l)
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_|[e]pp |envoy|pd-sidecar" | grep -v grep | wc -l)
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
CLEANUP_SH
@@ -162,6 +177,8 @@ srun --kill-on-bad-exit=1 bash -c '
INFER_NODE_RANK=$SLURM_PROCID
LOCAL_IP=$(hostname -I | awk "{print \$1}")
{% include '_launch_rank.sh.j2' %}
{% include '_launch_router.sh.j2' %}
{%- if kv_offload %}
ulimit -l unlimited
{%- endif %}
@@ -169,7 +186,7 @@ srun --kill-on-bad-exit=1 bash -c '
{% include "_mooncake_store.sh.j2" %}
{%- endif %}
{% if disaggregated -%}
{% if is_disaggregated -%}
# NVSHMEM libs for DeepEP — ensure the rpath target exists on all nodes
if [ ! -d /tmp/deepep_build/nvshmem/lib ] && [ -d "$OUTPUT_DIR/nvshmem/lib" ]; then
mkdir -p /tmp/deepep_build/nvshmem
@@ -185,10 +202,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
@@ -199,6 +234,9 @@ srun --kill-on-bad-exit=1 bash -c '
DECODE_COMPILE_CFG='"'"'{"cudagraph_mode":"FULL_DECODE_ONLY"}'"'"'
DP_PER_NODE={{ dp_per_node }}
TP=$((GPUS_PER_NODE / DP_PER_NODE))
# Determine outer replica (P/D pair) and role
REPLICA_IDX=$((INFER_NODE_RANK / NODES_PER_REPLICA))
RANK_IN_REPLICA=$((INFER_NODE_RANK % NODES_PER_REPLICA))
@@ -209,21 +247,14 @@ srun --kill-on-bad-exit=1 bash -c '
ROLE="prefill"
SUB_REPLICA=$((RANK_IN_REPLICA / NODES_PER_PREFILL_REPLICA))
ROLE_RANK=$((RANK_IN_REPLICA % NODES_PER_PREFILL_REPLICA))
EP=$((NODES_PER_PREFILL_REPLICA * GPUS_PER_NODE))
DP=$((NODES_PER_PREFILL_REPLICA * DP_PER_NODE))
PORT=$PREFILL_PORT
START_RANK=$((ROLE_RANK * GPUS_PER_NODE))
HEAD_HOST="${HOSTNAMES[$((REPLICA_BASE + SUB_REPLICA * NODES_PER_PREFILL_REPLICA))]}"
{% for key, value in prefill_env_overrides.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\""
if [ "$ROLE_RANK" -eq 0 ]; then
VLLM_EXTRA="{\"data_parallel_address\": \"$LOCAL_IP\", \"data_parallel_hybrid_lb\": true, $ROLE_EXTRA}"
else
VLLM_EXTRA="{\"data_parallel_address\": \"$HEAD_HOST\", \"data_parallel_start_rank\": $START_RANK, \"data_parallel_hybrid_lb\": true, $ROLE_EXTRA}"
fi
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\"{{ prefill_vllm_extra_json }}"
else
# ── Decode node ──
export UCX_NET_DEVICES=mlx5_0:1
@@ -231,80 +262,83 @@ srun --kill-on-bad-exit=1 bash -c '
RANK_IN_DECODE=$((RANK_IN_REPLICA - NUM_PREFILL_NODES))
SUB_REPLICA=$((RANK_IN_DECODE / NODES_PER_DECODE_REPLICA))
ROLE_RANK=$((RANK_IN_DECODE % NODES_PER_DECODE_REPLICA))
EP=$((NODES_PER_DECODE_REPLICA * GPUS_PER_NODE))
DP=$((NODES_PER_DECODE_REPLICA * DP_PER_NODE))
PORT=$DECODE_PORT
START_RANK=$((ROLE_RANK * GPUS_PER_NODE))
HEAD_HOST="${HOSTNAMES[$((REPLICA_BASE + NUM_PREFILL_NODES + SUB_REPLICA * NODES_PER_DECODE_REPLICA))]}"
{% for key, value in decode_env_overrides.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG"
if [ "$ROLE_RANK" -eq 0 ]; then
VLLM_EXTRA="{\"data_parallel_address\": \"$LOCAL_IP\", \"data_parallel_hybrid_lb\": true, $ROLE_EXTRA}"
else
VLLM_EXTRA="{\"data_parallel_address\": \"$HEAD_HOST\", \"data_parallel_start_rank\": $START_RANK, \"data_parallel_hybrid_lb\": true, $ROLE_EXTRA}"
fi
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG{{ decode_vllm_extra_json }}"
fi
echo "NODE_RANK=$INFER_NODE_RANK ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK EP=$EP PORT=$PORT LOCAL_IP=$LOCAL_IP" \
echo "NODE_RANK=$INFER_NODE_RANK ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT LOCAL_IP=$LOCAL_IP" \
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
# Start vllm-router on the first prefill node of each replica (background)
# Start the router on the first prefill node of each replica (external LB across per-rank endpoints)
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
ROUTER_LOG="$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log"
echo "Starting vllm-router on $LOCAL_IP:$ROUTER_PORT for replica $REPLICA_IDX" | tee $ROUTER_LOG
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
vllm-router \
--policy {{ router_policy }} \
--vllm-pd-disaggregation \
$REPLICA_ROUTER_ARGS \
--host 0.0.0.0 \
--port $ROUTER_PORT \
--intra-node-data-parallel-size {{ dp_per_node }} \
--worker-startup-timeout-secs 4200 \
--log-level debug \
>> $ROUTER_LOG 2>&1 &
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$REPLICA_BASE"
fi
{%- if router.type == "llm-d" %}
# pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT
# + rank) -> vLLM decode (DECODE_PORT + rank) after orchestrating remote prefill.
# Every decode node fronts its own local ranks, so launch on each (not just the
# replica head), or decode nodes beyond the head get advertised but unserved endpoints.
if [ "$ROLE" = "decode" ]; then
SIDECAR_LOG="$OUTPUT_DIR/logs/inference/sidecar_${INFER_NODE_RANK}.log"
echo "Starting pd-sidecar on $LOCAL_IP:$DECODE_SIDECAR_PORT(+rank) -> vLLM $DECODE_PORT(+rank)" | tee $SIDECAR_LOG
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
pd-sidecar \
--port $DECODE_SIDECAR_PORT \
--vllm-port $DECODE_PORT \
--kv-connector nixlv2 \
--secure-proxy=false \
--enable-ssrf-protection=false \
--inference-pool prime-rl \
--data-parallel-size {{ dp_per_node }} \
>> $SIDECAR_LOG 2>&1 &
fi
{%- endif %}
uv run inference \
@ $CONFIG_PATH \
--server.host 0.0.0.0 \
--server.port $PORT \
--parallel.dp $EP \
--data-parallel-rpc-port $RPC_PORT \
--vllm-extra "$VLLM_EXTRA" \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
# External-LB: one vLLM API server per local DP rank (PORT + k), each pinned to its TP
# slice of GPUs with a unique NIXL side-channel port. Each role is its own external-LB DP
# group rooted on the role-replica head (HEAD_HOST); the router balances across the per-rank
# endpoints. The kv_transfer_config is built in InferenceConfig.to_vllm() from the config.
if [ "$ROLE_RANK" -eq 0 ]; then DP_ADDR=$LOCAL_IP; else DP_ADDR=$HEAD_HOST; fi
for k in $(seq 0 $((DP_PER_NODE - 1))); do
GLOBAL_RANK=$((ROLE_RANK * DP_PER_NODE + k))
RANK_GPUS=$(seq -s, $((k * TP)) $((k * TP + TP - 1)))
RANK_EXTRA="{\"data_parallel_address\": \"$DP_ADDR\", \"data_parallel_rank\": $GLOBAL_RANK, $ROLE_EXTRA}"
launch_inference_rank "$((PORT + k))" "$RANK_GPUS" "$DP" "$RPC_PORT" "$RANK_EXTRA" "$((5600 + k))" "$(rank_log "$INFER_NODE_RANK" "$k")"
done
{%- elif num_nodes > 1 %}
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" \
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False
DP_PER_NODE={{ dp_per_node }}
TP=$((GPUS_PER_NODE / DP_PER_NODE))
EP={{ "1" if enable_expert_parallel else "0" }}
# Start router on node 0
# Start the router on node 0 (balances across per-rank endpoints — no intra-node DP header)
if [ "$INFER_NODE_RANK" -eq 0 ]; then
ROUTER_LOG="$OUTPUT_DIR/logs/inference/router.log"
echo "Starting vllm-router on $LOCAL_IP:$ROUTER_PORT" | tee $ROUTER_LOG
vllm-router \
--policy {{ router_policy }} \
--worker-urls $ROUTER_ARGS \
--host 0.0.0.0 \
--port $ROUTER_PORT \
--intra-node-data-parallel-size {{ dp_per_node }} \
--worker-startup-timeout-secs 4200 \
--log-level debug \
>> $ROUTER_LOG 2>&1 &
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log" 0 0 "$NUM_NODES"
fi
uv run inference \
@ $CONFIG_PATH \
--server.host 0.0.0.0 \
--server.port $BACKEND_PORT \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local),
# each pinned to its TP slice of GPUs. Each node is an independent replica, so any MoE EP
# group is node-local (rendezvous on LOCAL_IP); dense models run independent engines.
for ((d=0; d<DP_PER_NODE; d++)); do
RANK_GPUS=$(seq -s, $((d * TP)) $((d * TP + TP - 1)))
RANK_LOG=$(rank_log "$INFER_NODE_RANK" "$d")
if [ "$EP" -eq 1 ]; then
RANK_EXTRA="{\"data_parallel_rank\": $d, \"data_parallel_address\": \"$LOCAL_IP\"}"
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" "$DP_PER_NODE" "$RPC_PORT" "$RANK_EXTRA" "" "$RANK_LOG"
else
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" 1 "" "" "" "$RANK_LOG"
fi
done
{%- else %}
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" | tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
# Required for graph compilation to work
@@ -0,0 +1,41 @@
{# llm-d file-discovery endpoints: one entry per DP rank. Rendered (via include)
into the sbatch; the per-node address is the __LLMD_ADDR_<node>__ placeholder,
filled with each SLURM host's IPv4 inline in the sbatch (file-discovery rejects
hostnames). Node ordering matches the sbatch's host loop: prefill then decode.
The including sbatch sets ep_* via {% set %}. #}
endpoints:
{%- if ep_disaggregated %}
{%- for node in range(ep_num_prefill) %}
{%- for rank in range(ep_dp) %}
- name: prefill-{{ node }}-rank-{{ rank }}
address: __LLMD_ADDR_{{ node }}__
port: "{{ ep_prefill_port + rank }}"
namespace: default
labels:
llm-d.ai/pool: prime-rl
llm-d.ai/role: prefill
{%- endfor %}
{%- endfor %}
{%- for node in range(ep_num_decode) %}
{%- for rank in range(ep_dp) %}
- name: decode-{{ node }}-rank-{{ rank }}
address: __LLMD_ADDR_{{ ep_num_prefill + node }}__
port: "{{ ep_sidecar_port + rank }}"
namespace: default
labels:
llm-d.ai/pool: prime-rl
llm-d.ai/role: decode
{%- endfor %}
{%- endfor %}
{%- else %}
{%- for node in range(ep_num_nodes) %}
{%- for rank in range(ep_dp) %}
- name: backend-{{ node }}-rank-{{ rank }}
address: __LLMD_ADDR_{{ node }}__
port: "{{ ep_backend_port + rank }}"
namespace: default
labels:
llm-d.ai/pool: prime-rl
{%- endfor %}
{%- endfor %}
{%- endif %}
+97
View File
@@ -0,0 +1,97 @@
{# Envoy data plane: EPP picks the backend (ext_proc) and sets
x-gateway-destination-endpoint; the ORIGINAL_DST cluster routes there. Both
/v1/ (MITO) and /inference/v1/ (TITO) go through the picker. EPP gRPC is on
loopback 9002; the gateway listens on the configured port. #}
admin:
address: { socket_address: { address: 127.0.0.1, port_value: 9901 } }
static_resources:
listeners:
- name: prime_rl
address: { socket_address: { address: 0.0.0.0, port_value: {{ router.port }} } }
filter_chains:
- filters:
- name: envoy.filters.network.http_connection_manager
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
stat_prefix: prime_rl
codec_type: AUTO
stream_idle_timeout: 0s
request_timeout: 0s
route_config:
virtual_hosts:
- name: prime_rl
domains: ["*"]
routes:
- match: { prefix: "/v1/" }
route: { cluster: backend_cluster, timeout: 0s, idle_timeout: 86400s }
- match: { prefix: "/inference/v1/" }
route: { cluster: backend_cluster, timeout: 0s, idle_timeout: 86400s }
http_filters:
- name: envoy.filters.http.ext_proc
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.ext_proc.v3.ExternalProcessor
grpc_service:
envoy_grpc: { cluster_name: epp_cluster }
timeout: 10s
processing_mode:
request_header_mode: SEND
response_header_mode: SEND
request_body_mode: FULL_DUPLEX_STREAMED
response_body_mode: FULL_DUPLEX_STREAMED
request_trailer_mode: SEND
response_trailer_mode: SEND
message_timeout: 1000s
- name: envoy.filters.http.router
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
suppress_envoy_headers: true
clusters:
- name: backend_cluster
type: ORIGINAL_DST
lb_policy: CLUSTER_PROVIDED
original_dst_lb_config:
use_http_header: true
http_header_name: x-gateway-destination-endpoint
connect_timeout: 5s
# Default circuit breakers (~1024) overflow at high inflight concurrency (>=1536),
# causing "reset reason: overflow" 500s. Raise far above the max concurrent rollouts.
circuit_breakers:
thresholds:
- priority: DEFAULT
max_connections: 100000
max_pending_requests: 100000
max_requests: 100000
max_retries: 1000
- priority: HIGH
max_connections: 100000
max_pending_requests: 100000
max_requests: 100000
max_retries: 1000
- name: epp_cluster
type: STRICT_DNS
typed_extension_protocol_options:
envoy.extensions.upstreams.http.v3.HttpProtocolOptions:
"@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions
explicit_http_config:
http2_protocol_options: {}
load_assignment:
cluster_name: epp_cluster
endpoints:
- lb_endpoints:
- endpoint:
address: { socket_address: { address: 127.0.0.1, port_value: 9002 } }
connect_timeout: 5s
# ext_proc (EPP) connection pool overflows at high concurrency without this — the
# gRPC ext_proc calls are 1:1 with inflight requests, so cap well above max rollouts.
circuit_breakers:
thresholds:
- priority: DEFAULT
max_connections: 100000
max_pending_requests: 100000
max_requests: 100000
max_retries: 1000
- priority: HIGH
max_connections: 100000
max_pending_requests: 100000
max_requests: 100000
max_retries: 1000
@@ -0,0 +1,34 @@
{# llm-d EPP config: single-pool (non-P/D) routing with approximate prefix-cache
scoring. The vllmhttp parser embeds the OpenAI parser and also handles
/inference/v1/generate (token_ids), so MITO + TITO both get prefix-cache
scoring. Included into the sbatch as a heredoc; $LLMD_DIR is the per-replica
config dir, expanded at launch time. #}
apiVersion: inference.networking.x-k8s.io/v1alpha1
kind: EndpointPickerConfig
plugins:
- name: file-disc
type: file-discovery
parameters:
path: $LLMD_DIR/endpoints.yaml
watchFile: true
- name: vllmhttp-parser
type: vllmhttp-parser
{%- for scorer in router.scorers %}
- type: {{ scorer }}
{%- endfor %}
- type: max-score-picker
- type: single-profile-handler
schedulingProfiles:
- name: default
plugins:
{%- for scorer, weight in router.scorers.items() %}
- pluginRef: {{ scorer }}
weight: {{ weight }}
{%- endfor %}
- pluginRef: max-score-picker
requestHandler:
parser:
pluginRef: vllmhttp-parser
dataLayer:
discovery:
pluginRef: file-disc
@@ -0,0 +1,56 @@
{# llm-d EPP config: prefill/decode disaggregation. disagg-profile-handler runs
the prefill profile when prefix-based-pd-decider sees >= nonCachedTokens
non-cached prompt tokens, else decode-only. Mirrors the upstream llm-d PD
guide: the prefill profile uses prefill_scorers (prefix + queue/kv) and the
decode profile uses scorers (prefix + active-request); prefill-filter /
decode-filter select endpoints by llm-d.ai/role label. Included into the
sbatch as a heredoc; $LLMD_DIR is the per-replica config dir, expanded at
launch time. #}
apiVersion: inference.networking.x-k8s.io/v1alpha1
kind: EndpointPickerConfig
plugins:
- name: file-disc
type: file-discovery
parameters:
path: $LLMD_DIR/endpoints.yaml
watchFile: true
- name: vllmhttp-parser
type: vllmhttp-parser
- name: pd-decider
type: prefix-based-pd-decider
parameters:
nonCachedTokens: {{ router.non_cached_tokens }}
- name: profile-handler
type: disagg-profile-handler
parameters:
deciders:
prefill: pd-decider
- type: prefill-filter
- type: decode-filter
{%- for scorer in ((router.prefill_scorers.keys() | list) + (router.decode_scorers.keys() | list)) | unique %}
- type: {{ scorer }}
{%- endfor %}
- type: max-score-picker
schedulingProfiles:
- name: prefill
plugins:
- pluginRef: prefill-filter
{%- for scorer, weight in router.prefill_scorers.items() %}
- pluginRef: {{ scorer }}
weight: {{ weight }}
{%- endfor %}
- pluginRef: max-score-picker
- name: decode
plugins:
- pluginRef: decode-filter
{%- for scorer, weight in router.decode_scorers.items() %}
- pluginRef: {{ scorer }}
weight: {{ weight }}
{%- endfor %}
- pluginRef: max-score-picker
requestHandler:
parser:
pluginRef: vllmhttp-parser
dataLayer:
discovery:
pluginRef: file-disc
+121 -99
View File
@@ -32,7 +32,7 @@ export NODES_PER_INFER_REPLICA={{ nodes_per_infer_replica }}
export NUM_INFER_REPLICAS={{ num_infer_replicas }}
export GPUS_PER_NODE={{ gpus_per_node }}
{% if num_infer_nodes > 0 -%}
export ROUTER_PORT={{ router_port }}
export ROUTER_PORT={{ router.port }}
export INFERENCE_TP={{ inference_tp }}
export INFERENCE_DP_LOCAL=$((GPUS_PER_NODE / INFERENCE_TP))
export INFERENCE_DATA_PARALLEL_RPC_PORT={{ inference_data_parallel_rpc_port }}
@@ -45,15 +45,12 @@ export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
export PREFILL_PORT={{ prefill_port }}
export DECODE_PORT={{ decode_port }}
{%- if router.type == "llm-d" %}
export DECODE_SIDECAR_PORT={{ router.decode_sidecar_port }}
{%- endif %}
{%- else -%}
export BACKEND_PORT={{ backend_port }}
export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parallel else "0" }}
# Enable distributed EP mode only when expert parallelism spans multiple inference nodes per replica.
export USE_DISTRIBUTED_EP=0
if [ "$INFERENCE_ENABLE_EXPERT_PARALLEL" -eq 1 ] && [ "$NODES_PER_INFER_REPLICA" -gt 1 ]; then
USE_DISTRIBUTED_EP=1
fi
{%- endif %}
{%- endif %}
@@ -63,6 +60,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
@@ -94,17 +92,22 @@ for ((r=0; r<NUM_INFER_REPLICAS; r++)); do
INFER_URLS="${INFER_URLS:+$INFER_URLS }http://${router_host}:${ROUTER_PORT}/v1"
REPLICA_ROUTER_ARGS=""
# External-LB: one prefill/decode endpoint per DP rank (PORT + k) on each node.
for ((p=0; p<NUM_PREFILL_NODES; p++)); do
node_idx=$((replica_base + p))
host="${INFER_HOSTS[$node_idx]}"
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:${PREFILL_PORT}/v1"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --prefill http://${host}:${PREFILL_PORT}"
for ((k=0; k<INFERENCE_DP_LOCAL; k++)); do
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((PREFILL_PORT + k))/v1"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --prefill http://${host}:$((PREFILL_PORT + k))"
done
done
for ((d=0; d<NUM_DECODE_NODES; d++)); do
node_idx=$((replica_base + NUM_PREFILL_NODES + d))
host="${INFER_HOSTS[$node_idx]}"
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:${DECODE_PORT}/v1"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --decode http://${host}:${DECODE_PORT}"
for ((k=0; k<INFERENCE_DP_LOCAL; k++)); do
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((DECODE_PORT + k))/v1"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --decode http://${host}:$((DECODE_PORT + k))"
done
done
ALL_ROUTER_ARGS="${ALL_ROUTER_ARGS:+$ALL_ROUTER_ARGS|}$REPLICA_ROUTER_ARGS"
done
@@ -118,8 +121,11 @@ for ((r=0; r<NUM_INFER_REPLICAS; r++)); do
for ((n=0; n<NODES_PER_INFER_REPLICA; n++)); do
node_idx=$((head_idx + n))
host="${INFER_HOSTS[$node_idx]}"
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:${BACKEND_PORT}/v1"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS http://${host}:${BACKEND_PORT}"
# External-LB: one endpoint per DP rank (BACKEND_PORT + dp_local) on each node.
for ((k=0; k<INFERENCE_DP_LOCAL; k++)); do
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((BACKEND_PORT + k))/v1"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS http://${host}:$((BACKEND_PORT + k))"
done
done
ALL_ROUTER_ARGS="${ALL_ROUTER_ARGS:+$ALL_ROUTER_ARGS|}$REPLICA_ROUTER_ARGS"
done
@@ -130,9 +136,6 @@ export ALL_ROUTER_ARGS
echo "INFER_HOSTS=${INFER_HOSTS[*]}"
echo "INFER_URLS=${INFER_URLS}"
echo "ADMIN_URLS=${ADMIN_URLS}"
{%- if not is_disaggregated %}
echo "USE_DISTRIBUTED_EP=${USE_DISTRIBUTED_EP}"
{%- endif %}
{%- endif %}
echo "HOSTNAMES=${HOSTNAMES[*]}"
@@ -166,6 +169,10 @@ srun bash -s <<'CLEANUP_SH'
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
pkill -9 -f "[t]orchrun" 2>/dev/null
pkill -9 -f "[v]llm-router" 2>/dev/null
# llm-d router procs (EPP + Envoy + decode pd-sidecar) left over from a prior run.
pkill -9 -f "[e]pp.*pool-name" 2>/dev/null
pkill -9 -f "[e]nvoy.*envoy.yaml" 2>/dev/null
pkill -9 -f "[p]d-sidecar" 2>/dev/null
pkill -9 -f "[v]llm" 2>/dev/null
pkill -9 -f "[p]rime_rl" 2>/dev/null
# Also match prctl-set process names (kernel comm) like "vllm::router"
@@ -178,7 +185,7 @@ srun bash -s <<'CLEANUP_SH'
pkill -9 -x mooncake_client 2>/dev/null
sleep 2
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_" | grep -v grep | wc -l)
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_|[e]pp |envoy|pd-sidecar" | grep -v grep | wc -l)
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
CLEANUP_SH
@@ -228,6 +235,10 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
echo "INFER_NODE_RANK=$INFER_NODE_RANK REPLICA=$REPLICA_IDX RANK_IN_REPLICA=$RANK_IN_REPLICA LOCAL_IP=$LOCAL_IP" \
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
CONFIG_PATH="$CONFIG_DIR/inference.toml"
{% include '_launch_rank.sh.j2' %}
{% include '_launch_router.sh.j2' %}
{% if is_disaggregated -%}
# PD disaggregated: NIXL KV transfer + role-based inference
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
@@ -236,10 +247,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
@@ -262,7 +291,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
{% for key, value in prefill_env_overrides.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\""
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\"{{ prefill_vllm_extra_json }}"
else
export UCX_NET_DEVICES=mlx5_0:1
ROLE="decode"
@@ -276,104 +305,82 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
{% for key, value in decode_env_overrides.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG"
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG{{ decode_vllm_extra_json }}"
fi
echo "ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT" \
| tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
if [ "$DP" -gt 1 ]; then
if [ "$ROLE_RANK" -eq 0 ]; then
VLLM_EXTRA="{\"data_parallel_address\": \"$LOCAL_IP\", \"data_parallel_hybrid_lb\": true, $ROLE_EXTRA}"
else
VLLM_EXTRA="{\"data_parallel_address\": \"$HEAD_HOST\", \"data_parallel_start_rank\": $START_RANK, \"data_parallel_hybrid_lb\": true, $ROLE_EXTRA}"
fi
else
VLLM_EXTRA="{$ROLE_EXTRA}"
fi
# Start vllm-router on the first node of each replica (PD mode)
# Start the router on the first node of each replica (PD mode, external LB across per-rank endpoints)
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
ROUTER_LOG="$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log"
echo "Starting vllm-router (PD) on $LOCAL_IP:$ROUTER_PORT for replica $REPLICA_IDX" | tee $ROUTER_LOG
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
vllm-router \
--policy consistent_hash \
--vllm-pd-disaggregation \
$REPLICA_ROUTER_ARGS \
--host 0.0.0.0 \
--port $ROUTER_PORT \
--intra-node-data-parallel-size {{ dp_per_node }} \
--worker-startup-timeout-secs 4200 \
>> $ROUTER_LOG 2>&1 &
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$REPLICA_BASE"
fi
{%- if router.type == "llm-d" %}
# pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT
# + rank) -> vLLM decode (DECODE_PORT + rank) after orchestrating remote prefill.
# Every decode node fronts its own local ranks, so launch on each (not just the
# replica head), or decode nodes beyond the head get advertised but unserved endpoints.
if [ "$ROLE" = "decode" ]; then
SIDECAR_LOG="$OUTPUT_DIR/logs/inference/sidecar_${INFER_NODE_RANK}.log"
echo "Starting pd-sidecar on $LOCAL_IP:$DECODE_SIDECAR_PORT(+rank) -> vLLM $DECODE_PORT(+rank)" | tee $SIDECAR_LOG
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
pd-sidecar \
--port $DECODE_SIDECAR_PORT \
--vllm-port $DECODE_PORT \
--kv-connector nixlv2 \
--secure-proxy=false \
--enable-ssrf-protection=false \
--inference-pool prime-rl \
--data-parallel-size $INFERENCE_DP_LOCAL \
>> $SIDECAR_LOG 2>&1 &
fi
{%- endif %}
uv run inference \
@ $CONFIG_DIR/inference.toml \
--server.host 0.0.0.0 \
--server.port $PORT \
--parallel.dp $DP \
--data-parallel-rpc-port $INFERENCE_DATA_PARALLEL_RPC_PORT \
--vllm-extra "$VLLM_EXTRA" \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
# External-LB: one vLLM API server per local DP rank (PORT + k), each pinned to its TP
# slice of GPUs with a unique NIXL side-channel port. Each role is its own external-LB DP
# group rooted on the role-replica head (HEAD_HOST); the router balances across the per-rank
# endpoints. The kv_transfer_config is built in InferenceConfig.to_vllm() from the config.
if [ "$ROLE_RANK" -eq 0 ]; then DP_ADDR=$LOCAL_IP; else DP_ADDR=$HEAD_HOST; fi
for k in $(seq 0 $((INFERENCE_DP_LOCAL - 1))); do
GLOBAL_RANK=$((START_RANK + k))
RANK_GPUS=$(seq -s, $((k * INFERENCE_TP)) $((k * INFERENCE_TP + INFERENCE_TP - 1)))
RANK_EXTRA="{\"data_parallel_address\": \"$DP_ADDR\", \"data_parallel_rank\": $GLOBAL_RANK, $ROLE_EXTRA}"
launch_inference_rank "$((PORT + k))" "$RANK_GPUS" "$DP" "$INFERENCE_DATA_PARALLEL_RPC_PORT" "$RANK_EXTRA" "$((5600 + k))" "$(rank_log "$INFER_NODE_RANK" "$k")"
done
{%- else -%}
# Start vllm-router on the first node of each replica
# Start the router on the first node of each replica
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
ROUTER_LOG="$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log"
echo "Starting vllm-router on $LOCAL_IP:$ROUTER_PORT for replica $REPLICA_IDX" | tee $ROUTER_LOG
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
vllm-router \
--policy consistent_hash \
--worker-urls $REPLICA_ROUTER_ARGS \
--host 0.0.0.0 \
--port $ROUTER_PORT \
--intra-node-data-parallel-size {{ dp_per_node }} \
--worker-startup-timeout-secs 4200 \
>> $ROUTER_LOG 2>&1 &
launch_router regular "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$((REPLICA_IDX * NODES_PER_INFER_REPLICA))" "$NODES_PER_INFER_REPLICA"
fi
if [ "$USE_DISTRIBUTED_EP" -eq 1 ]; then
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
REPLICA_HEAD_HOST="${HOSTNAMES[$((REPLICA_IDX * NODES_PER_INFER_REPLICA))]}"
INFER_DP_START_RANK=$((RANK_IN_REPLICA * INFERENCE_DP_LOCAL))
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
VLLM_EXTRA="{\"data_parallel_address\": \"$LOCAL_IP\", \"data_parallel_hybrid_lb\": true}"
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + d),
# each pinned to its TP slice of GPUs; the router balances across the per-rank
# endpoints. For MoE the ranks form one external-LB DP group (EP all2all spans
# them) rooted on the replica-head DP coordinator. data_parallel_address is
# per-node, not per-rank: every rank on the head reaches the coordinator via the
# head LOCAL_IP, ranks on other nodes via the head hostname (matches the P/D path).
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
REPLICA_HEAD_HOST="${HOSTNAMES[$((REPLICA_IDX * NODES_PER_INFER_REPLICA))]}"
INFER_GROUP_DP=$((NODES_PER_INFER_REPLICA * INFERENCE_DP_LOCAL))
if [ "$RANK_IN_REPLICA" -eq 0 ]; then DP_ADDR="$LOCAL_IP"; else DP_ADDR="$REPLICA_HEAD_HOST"; fi
for ((d=0; d<INFERENCE_DP_LOCAL; d++)); do
RANK_GPUS=$(seq -s, $((d * INFERENCE_TP)) $((d * INFERENCE_TP + INFERENCE_TP - 1)))
RANK_LOG=$(rank_log "$INFER_NODE_RANK" "$d")
if [ "$INFERENCE_ENABLE_EXPERT_PARALLEL" -eq 1 ]; then
GLOBAL_DP_RANK=$((RANK_IN_REPLICA * INFERENCE_DP_LOCAL + d))
RANK_EXTRA="{\"data_parallel_rank\": $GLOBAL_DP_RANK, \"data_parallel_address\": \"$DP_ADDR\"}"
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" "$INFER_GROUP_DP" "$INFERENCE_DATA_PARALLEL_RPC_PORT" "$RANK_EXTRA" "" "$RANK_LOG"
else
VLLM_EXTRA="{\"data_parallel_address\": \"$REPLICA_HEAD_HOST\", \"data_parallel_start_rank\": $INFER_DP_START_RANK, \"data_parallel_hybrid_lb\": true}"
# Dense: independent single-engine servers (no DP linkage).
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" 1 "" "" "" "$RANK_LOG"
fi
uv run inference \
@ $CONFIG_DIR/inference.toml \
--server.host 0.0.0.0 \
--server.port $BACKEND_PORT \
--data-parallel-rpc-port $INFERENCE_DATA_PARALLEL_RPC_PORT \
--vllm-extra "$VLLM_EXTRA" \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
else
uv run inference \
@ $CONFIG_DIR/inference.toml \
--server.host 0.0.0.0 \
--server.port $BACKEND_PORT \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
fi
done
{%- endif %}
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 %}
@@ -400,6 +407,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
@@ -415,7 +437,7 @@ REMAINING_PIDS=$(jobs -p)
# in-flight trainer checkpoint on this node finish, and — because the task has
# not exited yet — keeps --kill-on-bad-exit from reaping checkpointing trainers
# on peer nodes. We then propagate the exit code so the allocation tears down. A
# clean (zero) exit can't trip --kill-on-bad-exit, so we tear down immediately.
# clean (zero) exit cannot trip --kill-on-bad-exit, so we tear down immediately.
if [ "$EXIT_CODE" -ne 0 ]; then
echo "[$(hostname)] component exited with code $EXIT_CODE - waiting up to {{ cleanup_grace_period }}s for in-flight checkpoints to flush before teardown"
sleep {{ cleanup_grace_period }}
+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
+68 -26
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:
@@ -171,7 +201,12 @@ class CheckpointManager:
# Checkpoint the local dataloader
if dataloader is not None:
dataloader_dir = path / "dataloader"
dataloader_dir.mkdir(parents=True, exist_ok=True)
# Only the master creates the dir; the rest wait at a barrier. On a
# parallel FS (beegfs), concurrent mkdir from every rank can re-raise
# FileExistsError (EEXIST + stale is_dir() metadata).
if self.world.is_master:
dataloader_dir.mkdir(parents=True, exist_ok=True)
torch.distributed.barrier()
torch.save(dataloader.state_dict(), dataloader_dir / f"rank_{self.world.rank}.pt")
# Save sharded state
@@ -239,7 +274,11 @@ class CheckpointManager:
) -> None:
"""Save the full checkpoint state for a specified step."""
ckpt_path = self.get_ckpt_path(step)
ckpt_path.parent.mkdir(parents=True, exist_ok=True)
# Master-only mkdir + barrier: concurrent mkdir from every rank can
# re-raise FileExistsError on a parallel FS (see save_to_path).
if self.world.is_master:
ckpt_path.parent.mkdir(parents=True, exist_ok=True)
torch.distributed.barrier()
self.save_to_path(ckpt_path, model, optimizers, scheduler, progress, dataloader)
bisect.insort(self.ckpt_steps, step)
@@ -390,7 +429,11 @@ class WeightCheckpointManager:
):
"""Save a HF-compatible weight-only checkpoint for a given step."""
step_path = self.get_step_path(step)
step_path.mkdir(parents=True, exist_ok=True)
# Master-only mkdir + barrier: concurrent mkdir from every rank can
# re-raise FileExistsError on a parallel FS (EEXIST + stale is_dir()).
if self.world.is_master:
step_path.mkdir(parents=True, exist_ok=True)
torch.distributed.barrier()
# Gather all weights on master rank
self.logger.debug("Gathering weights on master rank for weight checkpoint")
@@ -420,7 +463,6 @@ class WeightCheckpointManager:
f"Converted PrimeRL format to HF format in {time.perf_counter() - start_time:.2f} seconds"
)
else:
# For regular transformers models, revert internal format to original HF hub format
from transformers.core_model_loading import revert_weight_conversion
self.logger.debug("Reverting transformers internal format to HF hub format for weight checkpoint")
+52 -2
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,
@@ -79,7 +80,7 @@ def _patch_qwen3_5_moe_conversion_mapping():
incorrectly maps qwen3_5_moe → qwen2_moe, which assumes per-expert 2D checkpoint weights,
causing revert_weight_conversion to produce wrong shapes during weight broadcasting.
Remove once the pinned transformers commit fixes this.
Remove once an official Transformers release fixes this.
"""
from transformers.conversion_mapping import (
get_checkpoint_conversion_mapping,
@@ -99,7 +100,7 @@ def _patch_qwen3_5_text_position_ids():
"""Fix Qwen3.5 passing 3D MRoPE position_ids to decoder layers instead of 2D text_position_ids.
Upstream fix: https://github.com/huggingface/transformers/pull/44399
Remove once the pinned transformers commit includes this fix.
Remove once an official Transformers release includes this fix.
"""
import inspect
@@ -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()
@@ -486,6 +510,18 @@ def get_model(
model_config.use_index_cache = True
model_config.index_topk_freq = config.index_cache.topk_freq
model_config.index_topk_pattern = config.index_cache.topk_pattern
# Explicit override supersedes the model's native IndexShare schedule.
model_config.indexer_types = None
else:
# Auto-enable IndexShare from the model's own indexer schedule (e.g. GLM-5.2). The model
# reads `indexer_types` directly: shared layers reuse cached indices and carry no indexer weights.
indexer_types = getattr(model_config, "indexer_types", None)
if indexer_types and any(t == "shared" for t in indexer_types):
model_config.use_index_cache = True
logger.info(
f"Auto-enabled IndexShare from indexer_types schedule "
f"({sum(t == 'full' for t in indexer_types)}/{len(indexer_types)} full layers)"
)
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
@@ -518,6 +554,15 @@ def get_model(
logger.debug(f"Loaded model config ({model_config.to_dict()})")
# NemotronH: transformers' Mamba2 mixer __init__ calls lazy_load_kernel("mamba-ssm" /
# "causal-conv1d") whenever config.use_mamba_kernels is set. That hub-kernel path is gated only
# by whether the `kernels` package is importable (NOT by USE_HUB_KERNELS) and resolves from the
# HF Hub, which hard-crashes under HF_HUB_OFFLINE=1. prime-rl swaps in its own mamba_ssm Triton
# SSD kernels via _patch_mamba2_use_triton_ssd, so the hub kernels are redundant; disable them
# to keep model init offline-safe.
if getattr(model_config, "model_type", "") == "nemotron_h":
model_config.use_mamba_kernels = False
if config.debug.num_layers is not None:
# VLM configs nest num_hidden_layers under text_config
target_config = getattr(model_config, "text_config", model_config)
@@ -1066,6 +1111,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)
@@ -11,6 +11,10 @@ def _index_cache_skip_topk(config, layer_idx: int) -> bool:
if index_topk_pattern is not None:
return layer_idx < len(index_topk_pattern) and index_topk_pattern[layer_idx] == "S"
indexer_types = getattr(config, "indexer_types", None)
if indexer_types is not None:
return layer_idx < len(indexer_types) and indexer_types[layer_idx] == "shared"
return layer_idx % getattr(config, "index_topk_freq", 1) != 0
@@ -162,6 +166,7 @@ class GlmMoeDsaConfig(PretrainedConfig):
use_index_cache=False,
index_topk_freq=1,
index_topk_pattern=None,
indexer_types=None,
scoring_func="sigmoid",
topk_method="noaux_tc",
use_grouped_mm=True,
@@ -218,6 +223,7 @@ class GlmMoeDsaConfig(PretrainedConfig):
self.use_index_cache = use_index_cache
self.index_topk_freq = index_topk_freq
self.index_topk_pattern = index_topk_pattern
self.indexer_types = indexer_types
self.scoring_func = scoring_func
self.topk_method = topk_method
self.use_grouped_mm = use_grouped_mm
@@ -226,6 +232,10 @@ class GlmMoeDsaConfig(PretrainedConfig):
if not self.use_grouped_mm:
warnings.warn("not using grouped mm for moe is very slow, should only be used for debugging")
# head_dim is derived from qk_rope_head_dim (the RoPE slice). Some checkpoints (e.g. GLM-5.2)
# set head_dim=qk_nope_head_dim in config.json; drop it so PretrainedConfig.__init__ can't
# overwrite self.head_dim and break the rotary embedding dimension.
kwargs.pop("head_dim", None)
super().__init__(
pad_token_id=pad_token_id,
tie_word_embeddings=tie_word_embeddings,
@@ -158,7 +158,8 @@ class GlmMoeDsaAttention(nn.Module):
)
self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, args.hidden_size, bias=args.attention_bias)
self.indexer = Indexer(args)
# IndexShare (GLM-5.2): layers that reuse cached indices carry no indexer weights.
self.indexer = Indexer(args) if not args.skip_topk else None
self.use_index_cache = args.use_index_cache
self.skip_topk = args.skip_topk
self.scaling = self.qk_head_dim ** (-0.5)
@@ -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,
)
@@ -46,7 +46,6 @@ class FileSystemWeightBroadcast(WeightBroadcast):
if isinstance(model, PreTrainedModelPrimeRL) and model.is_prime_state_dict(state_dict):
model.convert_to_hf(state_dict)
else:
# For regular transformers models, revert internal format to original HF hub format
from transformers.core_model_loading import revert_weight_conversion
state_dict = revert_weight_conversion(model, state_dict)
+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():
+8 -1
View File
@@ -247,7 +247,12 @@ class MultiRunManager:
# Run registered validation hooks
for hook in self._config_validation_hooks:
is_valid, error_message = hook(config)
try:
is_valid, error_message = hook(config)
except Exception as e:
hook_name = getattr(hook, "__name__", type(hook).__name__)
is_valid = False
error_message = f"Validation hook {hook_name} crashed: {e}"
if not is_valid:
self.logger.error(f"Run {run_id}: {error_message}")
if error_path.parent.exists():
@@ -510,6 +515,8 @@ def setup_multi_run_manager(
trainer_lora = lora_config
def validate_lora_rank(orch_config: "OrchestratorConfig") -> tuple[bool, str]:
if orch_config.student.model.lora is None:
return False, "student.model.lora is required when trainer is configured with LoRA"
# Default to trainer's rank/alpha if not specified
if orch_config.student.model.lora.rank is None:
orch_config.student.model.lora.rank = trainer_lora.rank
+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
+1107 -352
View File
File diff suppressed because it is too large Load Diff