Compare commits

...
Author SHA1 Message Date
daedc1dbc6 fix(orchestrator): scope example_id by env_name to prevent cross-env collisions (#2366)
Release / Push CUDA image to Docker (push) Canceled after 0s
Auto-generated example_ids start at 0 for every dataset, so multi-env
runs silently merge rollouts from different envs in global metrics
(solve rates, reward averages, problem counts). Scope all global
groupby/set operations by (env_name, example_id) instead of example_id
alone.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-28 11:54:34 -07:00
3719abcfbb feat: rollout timeout config + verifiers 0.1.13.dev8 (#2371)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: rollout timeout config + verifiers 0.1.13.dev8

- Bump verifiers pin to v0.1.13.dev8 (rollout timeout, sandbox lifetime
  auto-derive, per-turn timing display).
- New EnvConfig.timeout_seconds: float | None field on the orchestrator
  config. When set, a model_validator auto-populates
  extra_env_kwargs["timeout_seconds"], which the env server forwards to
  the env constructor. MultiTurnEnv reads it as the per-rollout
  asyncio.wait_for cap. Mirrors the existing
  max_total_completion_tokens auto-populate pattern.

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

* refactor: rename env timeout_seconds to timeout (with alias)

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

* chore: pin verifiers to 980a9ea

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-28 11:53:46 -07:00
93cbc75b81 feat(orchestrator): make inference pool startup timeout configurable (#2355)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(orchestrator): make inference pool startup timeout configurable

Adds wait_for_ready_timeout to ClientConfig (default 1800s, matching
prior hardcoded value), threaded through StaticInferencePool and
ElasticInferencePool so it can be overridden via TOML per-client (e.g.
student vs teacher pools).

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

* chore: ruff format

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-28 05:09:34 +02:00
4e4390be87 feat: debug.force_balanced_routing for MoE smoke tests (#2368)
Release / Push CUDA image to Docker (push) Canceled after 0s
Fake-data MoE training produces severely skewed expert assignments,
which under EP causes per-rank memory blowup and OOM. This adds an
opt-in DebugModelConfig flag that overrides token-choice routing with
a round-robin assignment so every expert receives an equal share of
tokens. Gating scores are gathered from the override indices to keep
the forward pass self-consistent. Gradient flow through the router is
broken, so this is for benchmarking memory/timing only.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 20:04:24 -07:00
Jackmin801andGitHub 8457b601d6 [Fix] gpt oss (#2365)
Release / Push CUDA image to Docker (push) Canceled after 0s
* custom gpt oss impl

* gpt oss multilora impl

* gpt oss experts

* add gpt oss to custom model mapping

* add GPToss experts to apply lora

* update warning message
2026-04-27 15:49:51 -07:00
273524e2fc chore: remove async level from orch step log (#2361)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 15:23:51 -07:00
d2f36c9f65 feat: per-batch loss type override for hosted SFT hard distill (#2271)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: per-batch loss type override for hosted SFT hard distill

Add loss_type field to TrainingSample and MicroBatch transport types so
the orchestrator can stamp samples with a loss override (e.g. "sft")
that the trainer dispatches per-batch. This allows a shared multi-tenant
trainer to handle both RL and SFT distill runs on the same cluster.

When teacher_rollout_model is configured, the orchestrator sets
loss_type="sft" on each sample. The trainer's compute_loss checks the
field and swaps to sft_loss_fn for that batch, falling back to the
configured default when None (fully backward compatible).

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

* refactor: explicit loss_type field, sft_loss bool, no auto-derive

Address review feedback:
- Replace loss_type: str | None with sft_loss: bool on TrainingSample
  and MicroBatch (simpler, no string matching)
- Add explicit loss_type: Literal["rl", "sft"] on OrchestratorConfig
  instead of auto-deriving from teacher_rollout_model presence
- Orchestrator stamps sample.sft_loss based on config.loss_type, not
  teacher presence — user explicitly opts in
- Update validator: loss_type="sft" requires teacher_rollout_model
  (direction reversed from "teacher implies sft")
- Update example TOML with explicit loss_type = "sft"

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

* change to boolean

* conistency

* refactor: rename need_sft_loss to use_sft_loss and tighten hosted SFT invariants

- Rename `OrchestratorConfig.need_sft_loss` to `use_sft_loss` (clearer intent).
- Move the orchestrator-only SFT distill invariants (use_sft_loss paired
  with teacher_rollout_model, use_token_client coupling) from RLConfig onto
  OrchestratorConfig so the hosted `orchestrator` entrypoint enforces them
  too, not just the combined `rl` entrypoint.
- Shrink RLConfig.validate_external_rollout_inference to the one truly
  cross-config check (teacher_rollout_model vs self.inference).
- Drop redundant `[trainer.loss] type = "sft"` from the alphabet_sort
  example so `use_sft_loss` is the single obvious knob.
- Access micro_batch["sft_loss"] directly in train.py (required TypedDict
  field, no fallback needed).
- Document the override in skills/config/SKILL.md.

* test: cover hosted SFT loss override

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-27 15:12:58 -07:00
2566de0bd5 chore: bump prime to >=0.5.73 (#2367)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 15:02:51 -07:00
0fca0d15c5 fix(models): document cache_position to silence auto_docstring warnings (#2363)
Release / Push CUDA image to Docker (push) Canceled after 0s
The transformers @auto_docstring decorator prints a warning at import
time for any forward-method param missing from the docstring. The five
custom *ForCausalLM models accept cache_position only for HuggingFace
API compatibility — training asserts use_cache is None and never decodes
autoregressively, so the param is unused. Documenting that fact makes
the behavior explicit and clears the warnings.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 17:48:58 +02:00
Jackmin801andGitHub 24a2af0054 patch warnings and turn off 3d for qwen (#2356)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-26 13:08:46 -07:00
Benjamin WarnerandGitHub 8342ccd0c8 feat: add entity, group, and tags to wandb config (#2350)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-25 13:15:55 -07:00
halleriteandGitHub 20454ecd7b fix(ring_attn): adapt FA3 varlen wrappers to flash_attn_3 3.0.0 kwargs (#2352)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-24 22:25:11 +02:00
4a42aa039e fix(trainer): wait for NCCL_READY on all ranks before broadcast (#2337)
Release / Push CUDA image to Docker (push) Canceled after 0s
`broadcast_weights` used to guard both the orchestrator-notify and the
file-wait behind `if self.world.is_master`. The non-master ranks
skipped the wait and entered `nccl_broadcast_sender.broadcast_weights`
directly. Inside that path the preparation (DTensor resolution +
quantization / checkpoint preprocessing) enqueues NCCL collectives on
all ranks (FSDP all_gather in _resolve_dtensors). Those collectives
then sit in-flight with no counter-party until the inference engines
are paused and join — but the master has not yet waited for the
NCCL_READY marker because... only it was doing that.

Net effect: if the orchestrator took more than ~10 minutes to signal
NCCL_READY (e.g. eval + rollout-gen contention at the same time),
NCCL's watchdog would fire on a non-master rank and SIGABRT the
trainer. We've hit this repeatedly in large-cluster RL runs, always
with a non-master rank as the one to signal the timeout first.

Fix: split the existing `_notify_orchestrator` into a pure
`_compute_notified_runs` (safe on every rank) plus an impure
`_notify_orchestrator(notified_runs)` (master-only, does the
filesystem side-effects). Call the first unconditionally, call the
second only on master, then have every rank wait on the NCCL_READY
marker before proceeding. The file poll is filesystem-only with no
NCCL involvement, so a slow orchestrator now just blocks the whole
trainer safely instead of tripping NCCL's watchdog.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 16:33:56 -07:00
Jackmin801andGitHub b0a7cad8a8 [fix] patch gdn with varlen for qwen (#2346)
Release / Push CUDA image to Docker (push) Canceled after 0s
* patch gdn with varlen

* claude just casually reverted this what?
2026-04-22 23:38:47 -07:00
Jackmin801andGitHub f1bbdf924e missed patch for nemotron state dict (#2340)
Release / Push CUDA image to Docker (push) Canceled after 0s
* missed patch for nemotron state dict

* allow implementing state dict map hook

* address comment
2026-04-22 21:40:56 -07:00
Jackmin801andGitHub 9bbed30eba [Fix] nemotron fixes (#2338)
Release / Push CUDA image to Docker (push) Canceled after 0s
* non gated grouped experts multilora layer

* do bias leveling to avoid overflow

* varlen mamba

---------

Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
2026-04-21 20:23:42 -07:00
halleriteandGitHub a6a6441a3b fix(ci): bump nightly test container /dev/shm to 16g (#2339)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-22 02:12:13 +02:00
samsjaandGitHub e8abfa264b chore: add conservative testing guidelines to AGENTS.md (#2330)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-19 19:18:33 -07:00
c3a24c35e2 feat(slurm): cleanup stale node-local state before launch (#2331)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(slurm): cleanup stale node-local state before launch

Add a pre-workload srun step to the multi-node RL, multi-node SFT and
inference sbatch templates. It runs once per node and:

- kills orphan python/torchrun/vllm/prime_rl processes left over from a
  prior job that wedged after scancel (SLURM doesn't always reap cleanly
  when a job sits in CG for hours)
- removes stale vLLM and torch IPC state under /dev/shm/vllm-*,
  /tmp/vllm-*, /tmp/torch-*, /tmp/torchelastic_*

Without this, decode engines on previously-used nodes can hang at
"Waiting for READY message from DP Coordinator" because the new vLLM
process finds a stale /dev/shm segment or port holder from the dead run.
Symptom we hit: a fresh job timing out after 1800s because 4 decode
engines never became READY; a manual pdsh cleanup of the same nodes
fixed it immediately.

Each node prints one line (hostname, residual proc count, total GPU
memory in use) so the sbatch log shows the nodes came up clean.

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

* feat(slurm): explicitly cover vllm-router in cleanup

Address review feedback: add vllm-router to the pkill list and the
procs-count regex so the intent is explicit, even though the broader
"vllm" patterns already match it as a substring.

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

* feat(slurm): also kill prctl-named vllm::router workers

pkill -f only matches the command line, so the vllm router's worker
processes — which set their kernel process name (comm) to "vllm::router"
via prctl but keep a different cmdline — slip through. Add process-name
pkill for "vllm" and "vllm::.*" to catch them.

Also broaden the post-cleanup procs count to look at both comm and args
(ps -eo comm,args) so we see these if any survive.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 16:19:58 -07:00
d2718f5f65 chore: rename deprecated orchestrator config keys (#2327)
Release / Push CUDA image to Docker (push) Canceled after 0s
Rename '[orchestrator.sampling]' -> '[orchestrator.train.sampling]',
'[[orchestrator.env]]' -> '[[orchestrator.train.env]]', and
'max_tokens' -> 'max_completion_tokens' across all configs to remove
reliance on the deprecated auto-translation.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 13:08:35 -07:00
d49f3939e7 update dependency (#2317)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
2026-04-18 13:00:52 -07:00
9eeffdb6fb feat: drop filtered rollouts instead of masking (#2277)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: drop filtered rollouts from training batch instead of masking

Previously, enforced filters zeroed the completion_mask on detected
rollouts but still sent them through the entire training pipeline.
This wastes compute on samples that contribute nothing to the loss.

Now, `apply_filters` returns the subset of rollouts that should be
sent to the trainer. Enforced-detected rollouts are excluded before
pretokenization, VLM cache building, and sample construction.

The trainer handles the resulting empty batches ("phantom steps") by
skipping forward/backward and logging `data/is_empty_batch`.

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

* feat: retry empty filtered batches instead of passing them to trainer

Keep the invariant that the trainer only receives non-empty batches. If
all rollouts are filtered out, regenerate the batch (up to 3 retries)
and crash the orchestrator on sustained failure. Warn at <=10% trainable.

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

* chore: drop redundant num_rollouts guard

The retry loop only breaks when len(filtered_rollouts) > 0, which implies
num_rollouts > 0, so the guard is unreachable.

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

* chore: expand low-trainable-ratio warning with env review hint

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

* chore: drop empty-df guard and inline filtered metrics

filtered_rollouts is guaranteed non-empty after the retry loop, so the
empty-df branch is unreachable and the intermediate locals add no value.

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

* chore: hoist MAX_EMPTY_BATCH_RETRIES to module scope

Also rename the loop var and warning message to "retry N/MAX" so the
counter excludes the initial attempt and reads less ambiguously.

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

* chore: adjust log style in filter retry warnings

Drop trailing periods and replace ";" with " - " as clause separator.

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

* chore: clarify low-trainable-ratio warning hint

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

* refactor: compute metrics over all rollouts, drop only from trainer

Metric logging reverts to main's semantics: all rollouts contribute to
prefill_len, decode_len, samples_per_rollout, and results_df. Filtered
rollouts are still pretokenized and interleaved, but their samples are
simply not added to train_examples. Also inline the generate_batch
coroutine since it is awaited immediately.

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

* refactor: move filter flags to rollout["filter"] + is_filtered

Per-filter detection booleans now live under rollout["filter"], and a
top-level rollout["is_filtered"] captures whether any enforcing filter
triggered. The orchestrator uses is_filtered directly as the keep gate
(no more id() mapping). apply_filters no longer returns filtered_rollouts
- the in-place flags are the single source of truth. Also unbound-var
fix for retry-loop locals, and per-env filter/<env>/<flag>_rate logging
that mirrors the metrics logging pattern.

Both new fields are serialized to train_rollouts.jsonl via save_rollouts,
which already writes all top-level rollout keys.

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

* chore: cap to 3 total batch-generation attempts, not 3 retries

Rename MAX_EMPTY_BATCH_RETRIES to MAX_EMPTY_BATCH_ATTEMPTS and have the
loop run exactly that many times. Warning now reports the attempt that
just failed ("Attempt N/3 ... retrying").

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

* chore: log error line before raising on exhausted retries

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

* chore: align filter metric key names with per-env logging

Rename filter/total_detected_rate -> filter/detected_rate and
filter/total_enforced_rate -> filter/is_filtered_rate so the overall
keys mirror the per-env filter/<env>/is_filtered_rate naming.

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

* refactor: unify filter logging under filter/{all,<env>}/{<filter>,is_filtered}

Move is_filtered into results_df so it can be aggregated per-env like
is_truncated. filter_df now holds just per-filter detection booleans.
apply_filters no longer returns an aggregate metrics dict - the
orchestrator derives the rates uniformly across the "all" and per-env
scopes, with symmetric key naming and no _rate/_count suffixes.

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

* chore: rename rollout["filter"] to rollout["filters"] + log keys

Aligns with the plural configs list and the rollout-level "filters"
namespace. Log keys change from filter/{all,<env>}/... to
filters/{all,<env>}/....

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

* feat: self-evict orchestrator when batches carry no learning signal

Write control/evicted.txt before raising, so the multi-run manager
skips the run on rediscovery instead of treating it as a hard crash.

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-18 09:22:28 -07:00
03689b8ac0 chore: remove prefix-cache-salt and reset-prefix-cache config flags (#2314)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore: remove prefix-cache-salt and reset-prefix-cache config flags

Hardcode the defaults: always set cache_salt on inference requests
(keyed by ckpt_step) and never reset the prefix cache after weight or
LoRA updates. The salt alone is sufficient to invalidate stale KV
states across policy updates, so the reset path is redundant.

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

* chore: keep empty experimental sub-configs as extension points

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 22:03:37 -07:00
f29e947585 Fix Prime monitor public API flow (#2205)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Use bearer auth for Prime monitor uploads

* Fix Prime monitor presign and finalize flow

* Sanitize non-finite Prime monitor payloads

* Simplify Prime monitor payload normalization

* Simplify Prime monitor public API contract

* Simplify public presign response parsing

* Simplify non-finite payload sanitization

* Inline public presign response parsing

* Inline non-finite payload sanitization logic

* Refine Prime monitor JSON sanitization

* Address review: inline auth headers and simplify sanitize

- Remove _api_headers() helper; store self._headers once in __init__
- Always sanitize payloads; drop silent try/except and log only when values are dropped
- Remove prime_cli sys.modules mocking from tests (real dep is installed)

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

---------

Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 22:01:27 -07:00
JupiterandGitHub bb7449c829 Add FA4 (flash_attn.cute) support to ring attention, enabling context (#2307)
Release / Push CUDA image to Docker (push) Canceled after 0s
parallel training with FA4 kernels. Mirrors the FA3 ring attention
pattern (all-gather K/V, compute per GQA stride, reduce-scatter grads)
using FA4 low-level _flash_attn_fwd/_flash_attn_bwd.

Changes:
- ring_attn.py: FA4 forward/backward wrappers, _RingFA4Varlen autograd
  Function, ring_fa4_varlen_func public API
- attn.py: route FA4 to ring_fa4_varlen_func in substitute_ring_attn
- trainer.py: allow CP with fa4 (requires model.impl='custom')
2026-04-17 20:00:52 -07:00
82fa41f4f2 fix: serialize env server spawn to avoid port race (#2310)
Release / Push CUDA image to Docker (push) Canceled after 0s
get_free_port() only holds the port until it returns, so parallel
env spawns under asyncio.gather could hand the same port to two
children — the loser died with EADDRINUSE. Serializing start()
and awaiting wait_for_server_startup() between envs ensures each
port is bound before the next one is picked.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 15:55:37 -07:00
1ade129004 fix: check rollout error before empty trajectory in scheduler (#2308)
Release / Push CUDA image to Docker (push) Canceled after 0s
When `verifiers` CliAgentEnv catches an agent crash pre-LLM-call, it
sets `state["error"]` but the trajectory stays `[]` because the agent
never produced any messages. The previous branch order fired the
"Empty trajectory" warning first and dropped the detailed AgentError
diagnostic. Swap the branches so error-bearing rollouts surface
"Rollout error ...: {error_chain_repr}" instead.

Related: PrimeIntellect-ai/verifiers#1127, #1130

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 22:23:13 +02:00
26ea8df85e chore: bump vllm-router to v0.1.22 (#2292)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 10:52:49 -07:00
Mika SenghaasandGitHub d4bddbaed7 fix: clean stale rollouts and broadcasts on fresh runs (#2304)
Release / Push CUDA image to Docker (push) Canceled after 0s
Previously `clean_future_steps` only ran when resuming from a checkpoint,
so a fresh run started in an output_dir containing stale rollouts or
broadcasts from a previous run would consume them: the trainer would
train on stale data and the orchestrator would compute a negative async
level because it sees a trainer that is seemingly ahead of it.

Run the same cleanup from step 0 when training from scratch so these
artifacts are removed before training begins.
2026-04-17 09:26:34 -07:00
samsjaandGitHub 6bf14b80f8 vf bump (#2302)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-17 08:11:50 -07:00
halleriteandGitHub 586e0f8e5d fix: work around transformers lazy_load_kernel offline regression (#2276)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-17 15:16:27 +02:00
JannikStandGitHub 18e895651e accept fully-qualified expert names in lora check (#2301)
Release / Push CUDA image to Docker (push) Canceled after 0s
* accept fully-qualified expert names in lora check

* ruff format
2026-04-17 14:56:58 +02:00
Matej SirovatkaandGitHub 2c54d5c834 Feat: fix cpu offloading patch to match upstream and remove a segfault (#2300)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-17 11:21:32 +02:00
3a6b46189a fix: always ensure X-Session-ID and propagate extra_headers_from_state in elastic pool (#2283)
Release / Push CUDA image to Docker (push) Canceled after 0s
Two fixes:
- Use setdefault so X-Session-ID: example_id is always present for
  sticky DP-aware routing, even if user provides other
  extra_headers_from_state entries
- Propagate extra_headers_from_state when rebuilding clients in the
  elastic pool, so session headers survive pool refreshes

Keeps dp_rank_count as-is for direct DP rank routing.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 12:11:58 -07:00
JannikStandGitHub ba86b9ba88 Support runtime verifiers version override (#2274)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Support runtime verifiers version override via VERIFIERS_VERSION env var

When set, the entrypoint reinstalls verifiers from the specified git ref
(tag, branch, or commit) before starting the main process.

* Drop --no-deps so transitive deps are updated with verifiers override

* Use --reinstall-package to only reinstall verifiers, not the entire dep tree
2026-04-16 09:38:18 -07:00
halleriteandGitHub 2d659eecc7 feat: context parallelism for NemotronH Mamba layers (#2231)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-16 09:12:49 +02:00
56cdd2c579 feat: pre-download model weights in launcher (#2282)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: pre-download model weights in launcher instead of using HF_HUB_OFFLINE

Remove hardcoded `HF_HUB_OFFLINE=1` from multi-node SLURM templates and
instead pre-download model weights via `snapshot_download` in the rl/sft
launchers before dispatching to local or SLURM execution. This ensures
weights are cached on the shared filesystem before training starts,
removing the need to manually pre-download models.

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

* feat: pre-download model weights in launcher instead of using HF_HUB_OFFLINE

Remove hardcoded `HF_HUB_OFFLINE=1` from multi-node SLURM templates and
instead pre-download model weights via `snapshot_download` in the rl/sft
launchers before dispatching to local or SLURM execution. This ensures
weights are cached on the shared filesystem before training starts,
removing the need to manually pre-download models.

Also replace `format_time` with the verifiers-style two-unit display
(e.g. "1h 30m" instead of "1.50h").

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

* refactor: move pre_download_model to trainer.model

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

* feat: log cache path when model is already downloaded

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

* chore: remove redundant cache log from pre_download_model

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

* chore: move pre_download_model import to module top

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

* feat: skip download and log cache path when model already cached

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

* Revert "feat: skip download and log cache path when model already cached"

This reverts commit 5b2bac9f2bb9e22ae898fe54f66f48357931dc40.

* chore: keep HF_HUB_OFFLINE=1 in SLURM templates

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 19:51:04 -07:00
4dcf86f0ea feat: set tool_call_parser default to 'auto' (#2285)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: set tool_call_parser default to 'auto'

Changed the default value of tool_call_parser from None to 'auto' to enable automatic tool call parser detection from model name by default. This provides better out-of-the-box experience for users working with tool-calling models.

* test: add unit tests for inference metrics collector

Tests parsing, aggregation (sum/max/mean), counter rates, histogram
latency, counter reset handling, server failures, and wandb logging.

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

* Revert "test: add unit tests for inference metrics collector"

This reverts commit 48eb049144b51ec9a2562358b398c2be46bc8eca.

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 18:16:10 -07:00
samsjaandGitHub ad3134ac03 fix 32-> 30 (#2287)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-15 16:34:23 -07:00
samsjaandGitHub 8c5aa67aa5 fix 2.5 -> qwen (#2286)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-15 16:22:56 -07:00
rasdaniandGitHub fde3006470 Add env_install_prerelease config option (#2279)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-15 02:26:25 -07:00
Mika SenghaasandGitHub 67783e4a6c chore: drop trajectory from saved rollout JSONL files (#2281)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-15 11:20:32 +02:00
114 changed files with 3207 additions and 653 deletions
+4 -1
View File
@@ -57,7 +57,10 @@ jobs:
runs-on: research-cluster
container:
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
options: --gpus all
# --shm-size: vLLM V1's DP engine/API-server IPC uses POSIX shm-backed
# MessageQueue (~160MB per queue); Docker's default 64MB /dev/shm triggers
# SIGBUS in DP engine cores on VLM runs (mm data overflows tmpfs).
options: --gpus all --shm-size=16g
timeout-minutes: 1440 # 24 hours
strategy:
fail-fast: false
+3
View File
@@ -43,6 +43,9 @@ You are responsible for maintaining the skills folder. When a workflow fails and
Write tests as plain functions with pytest fixtures. Don't use class-based tests.
- **Conservative test additions**: don't add new tests unless the user explicitly asks for them or it's clearly necessary. Editing existing tests is fine, but adding new test files or test functions should be the exception, not the default.
- **Test what matters**: only test code with clear, isolated logic — pure functions, abstract base classes, data transformations, well-defined algorithms. Don't test runtime-level code, framework glue, or anything that requires extensive mocking/patching just to get a test to pass. If you need to patch everything out to make it testable, it's probably not worth testing.
## Git
- **Branch prefixes**: use the following prefixes for branches: `feat/`, `fix/`, `chore/`
+1
View File
@@ -2,6 +2,7 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **`orchestrator.teacher_rollout_model` now requires `orchestrator.use_sft_loss = true`**: External teacher rollout configs no longer rely on `trainer.loss.type = "sft"` to select SFT loss. Existing hard-distill configs must set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; the orchestrator validates the pair and stamps training samples with the per-batch SFT loss bool. (2026-04-26)
- **`model.attn = "eager"` (NEW option)**: Added `eager` as a valid value for the `model.attn` field. Required for GPT-OSS models on non-Hopper GPUs, since the only flash attention kernel GPT-OSS supports (`kernels-community/vllm-flash-attn3`) is Hopper-only. A clear error message is raised at model load time if GPT-OSS is used without `eager` on unsupported hardware. Also added `kernels` as a core dependency. (2026-04-05)
- **`[[orchestrator.env]]` → `[[orchestrator.train.env]]`**: Training environments and sampling are now configured under `[orchestrator.train]`. The old `[[orchestrator.env]]` and `[orchestrator.sampling]` paths are auto-translated with a deprecation warning and will be removed in a future release. (2026-04-09)
- **Per-env sampling overrides (NEW)**: Both `TrainEnvConfig` and `EvalEnvConfig` now accept a `[sampling]` section for per-env overrides. Unset fields inherit from the group-level sampling config (`[orchestrator.train.sampling]` or `[orchestrator.eval.sampling]`). (2026-04-09)
+3 -3
View File
@@ -19,11 +19,11 @@ name = "stage1"
batch_size = 1024
rollouts_per_example = 8
[orchestrator.sampling]
[orchestrator.train.sampling]
temperature = 0.6
max_tokens = 8192
max_completion_tokens = 8192
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
+3 -3
View File
@@ -20,11 +20,11 @@ name = "stage2"
batch_size = 2048
rollouts_per_example = 16
[orchestrator.sampling]
[orchestrator.train.sampling]
temperature = 0.6
max_tokens = 16384
max_completion_tokens = 16384
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
+3 -3
View File
@@ -13,10 +13,10 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
batch_size = 512
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 512
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2 }
@@ -13,10 +13,10 @@ lr = 1e-5
batch_size = 128
rollouts_per_example = 8
[orchestrator.sampling]
max_tokens = 384
[orchestrator.train.sampling]
max_completion_tokens = 384
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
@@ -18,10 +18,10 @@ lr = 1e-5
batch_size = 128
rollouts_per_example = 8
[orchestrator.sampling]
max_tokens = 1024
[orchestrator.train.sampling]
max_completion_tokens = 1024
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "primeintellect/alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
+3 -3
View File
@@ -14,10 +14,10 @@ lr = 3e-6
batch_size = 128
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "reverse-text"
[inference]
+3 -3
View File
@@ -13,10 +13,10 @@ lr = 3e-6
batch_size = 128
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "reverse-text"
[inference]
+3 -3
View File
@@ -23,10 +23,10 @@ rollouts_per_example = 16
[orchestrator.model.lora]
name = "r8-1e-4"
[orchestrator.sampling]
max_tokens = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "reverse-text"
[inference]
+3 -3
View File
@@ -22,10 +22,10 @@ rollouts_per_example = 16
[orchestrator.model.lora]
name = "r8-1e-4"
[orchestrator.sampling]
max_tokens = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "reverse-text"
[inference]
+3 -3
View File
@@ -13,10 +13,10 @@ lr = 3e-6
batch_size = 128
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "reverse-text"
[inference]
@@ -11,10 +11,10 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[optim]
lr = 3e-5
[sampling]
max_tokens = 128
[train.sampling]
max_completion_tokens = 128
[[env]]
[[train.env]]
id = "reverse-text"
[ckpt]
+3 -3
View File
@@ -17,11 +17,11 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
batch_size = 1024
rollouts_per_example = 8
[orchestrator.sampling]
[orchestrator.train.sampling]
temperature = 0.6
max_tokens = 8192
max_completion_tokens = 8192
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "acereason-math"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
@@ -17,10 +17,10 @@ language_model_attr = "model.language_model"
batch_size = 256
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 64
[orchestrator.train.sampling]
max_completion_tokens = 64
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
+2 -2
View File
@@ -2,6 +2,6 @@ max_steps = 5
max_async_level = 5
batch_size = 16
[sampling]
max_tokens = 16
[train.sampling]
max_completion_tokens = 16
+3 -3
View File
@@ -19,11 +19,11 @@ interval = 100
batch_size = 1024
rollouts_per_example = 8
[orchestrator.sampling]
[orchestrator.train.sampling]
temperature = 0.6
max_tokens = 8192
max_completion_tokens = 8192
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "deepscaler"
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
+3 -3
View File
@@ -20,11 +20,11 @@ resume_step = 500
batch_size = 1024
rollouts_per_example = 8
[orchestrator.sampling]
[orchestrator.train.sampling]
temperature = 0.6
max_tokens = 16384
max_completion_tokens = 16384
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "deepscaler"
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
+3 -3
View File
@@ -20,11 +20,11 @@ resume_step = 1000
batch_size = 1024
rollouts_per_example = 8
[orchestrator.sampling]
[orchestrator.train.sampling]
temperature = 0.6
max_tokens = 24576
max_completion_tokens = 24576
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "deepscaler"
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
+3 -3
View File
@@ -32,15 +32,15 @@ lr = 1e-5
batch_size = 512
rollouts_per_example = 8
[orchestrator.sampling]
max_tokens = 768
[orchestrator.train.sampling]
max_completion_tokens = 768
[orchestrator.client.elastic]
hostname = "localhost"
port = 8000
sync_interval = 5.0
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
+5 -5
View File
@@ -16,27 +16,27 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
batch_size = 512
rollouts_per_example = 16
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "math"
args = { min_avg_reward = 0.1, rubric_max_workers = 128 }
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "code-env"
name = "code"
args = { min_avg_reward = 0.1 }
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "science-env"
name = "science"
args = { min_avg_reward = 0.1, pool_size = 128, rubric_max_workers = 128 }
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "logic-env"
name = "logic"
args = { min_avg_reward = 0.1 }
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "math-python"
args = { min_avg_reward = 0.1, sandbox_client_max_workers = 128, sandbox_timeout_minutes = 10, sandbox_memory_gb = 1, sandbox_disk_size_gb = 1, pip_install_packages = "numpy sympy", python_tool = true, rubric_max_workers = 128 }
+3 -3
View File
@@ -12,10 +12,10 @@ name = "PrimeIntellect/Qwen3-0.6B"
batch_size = 512
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[orchestrator.train.sampling]
max_completion_tokens = 2048
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "gsm8k"
args = { dataset_name = "openai/gsm8k", dataset_subset = "main", math_verify_max_workers = 128, math_verify_timeout = 60 }
+4 -4
View File
@@ -12,10 +12,10 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
batch_size = 512
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[orchestrator.train.sampling]
max_completion_tokens = 2048
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
@@ -28,7 +28,7 @@ hard_threshold = 0.0
interval = 10
[orchestrator.eval.sampling]
max_tokens = 2048
max_completion_tokens = 2048
[[orchestrator.eval.env]]
id = "math500"
+1 -1
View File
@@ -12,7 +12,7 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
batch_size = 512
rollouts_per_example = 8
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
name = "hendrycks-math"
+2 -2
View File
@@ -11,13 +11,13 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
batch_size = 256
rollouts_per_example = 8
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
ratio = 0.5
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "acereason-math"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem" }
+3 -3
View File
@@ -12,10 +12,10 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
batch_size = 512
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 512
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-python"
args = { sandbox_client_max_workers = 128, sandbox_timeout_minutes = 10, sandbox_memory_gb = 1, sandbox_disk_size_gb = 1, pip_install_packages = "numpy sympy" }
+3 -3
View File
@@ -13,10 +13,10 @@ batch_size = 256
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 64
[orchestrator.train.sampling]
max_completion_tokens = 64
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
@@ -13,10 +13,10 @@ language_model_attr = "model.language_model"
batch_size = 16
rollouts_per_example = 2
[orchestrator.sampling]
max_tokens = 32
[orchestrator.train.sampling]
max_completion_tokens = 32
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 2, num_examples = 100, seed = 42 }
+4 -4
View File
@@ -48,10 +48,10 @@ max_inflight_activations = 5
batch_size = 128
rollouts_per_example = 8
[orchestrator.sampling]
max_tokens = 2048
[orchestrator.train.sampling]
max_completion_tokens = 2048
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
@@ -64,7 +64,7 @@ hard_threshold = 0.0
interval = 10
[orchestrator.eval.sampling]
max_tokens = 2048
max_completion_tokens = 2048
[[orchestrator.eval.env]]
id = "math500"
+4 -4
View File
@@ -47,10 +47,10 @@ freq = 1
batch_size = 512
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 4096
[orchestrator.train.sampling]
max_completion_tokens = 4096
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
@@ -63,7 +63,7 @@ hard_threshold = 0.0
interval = 10
[orchestrator.eval.sampling]
max_tokens = 4096
max_completion_tokens = 4096
[[orchestrator.eval.env]]
id = "math500"
+3 -3
View File
@@ -30,13 +30,13 @@ batch_size = 512
rollouts_per_example = 16
oversampling_factor = 2.0
[orchestrator.sampling]
max_tokens = 512
[orchestrator.train.sampling]
max_completion_tokens = 512
[orchestrator.buffer]
online_difficulty_filtering = true
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "wiki-search"
[inference.model]
+1
View File
@@ -110,6 +110,7 @@ The eviction takes effect through two mechanisms:
- The orchestrator checks for `evicted.txt` at the start of each iteration in its main loop
- If found, it raises a `RuntimeError` with the eviction reason, causing the orchestrator to exit
- This surfaces the eviction reason to the user
- The orchestrator also self-evicts by writing `evicted.txt` if a training batch has no learning signal (all rollouts filtered out) on `MAX_EMPTY_BATCH_ATTEMPTS` (3) consecutive attempts
## LoRA Module Registration
+5 -5
View File
@@ -47,31 +47,31 @@ weight_decay = 0.01
batch_size = 2048
oversampling_factor = 2
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "mini-swe-agent-plus"
name = "swe"
ratio = 0.3
args = { max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "deepdive"
name = "deepdive"
ratio = 0.2
args = { finish_with_tool = true, open_max_workers = 128, cache_dir = "/tmp/i3_deepdive_cache_train" }
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "math"
ratio = 0.3
args = { min_avg_reward = 0.0, max_avg_reward = 0.874}
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "logic-env"
name = "logic"
ratio = 0.2
args = { min_avg_reward = 0.0, max_avg_reward = 0.874 }
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "code-env"
name = "code"
ratio = 0.2
+3 -3
View File
@@ -28,10 +28,10 @@ lr = 1e-5
batch_size = 512
rollouts_per_example = 8
[orchestrator.sampling]
max_tokens = 768
[orchestrator.train.sampling]
max_completion_tokens = 768
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "primeintellect/alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
+4 -6
View File
@@ -19,9 +19,6 @@ name = "qwen3-4b-hard-distill"
[trainer.optim]
lr = 1e-5
[trainer.loss]
type = "sft"
[trainer.model.lora]
rank = 16
alpha = 32
@@ -33,9 +30,10 @@ save_adapter_separately = true
batch_size = 256
rollouts_per_example = 4
use_token_client = false
use_sft_loss = true
[orchestrator.sampling]
max_tokens = 512
[orchestrator.train.sampling]
max_completion_tokens = 512
temperature = 0.7
[orchestrator.teacher_rollout_model.client]
@@ -45,7 +43,7 @@ api_key_var = "PRIME_API_KEY"
[orchestrator.teacher_rollout_model.model]
name = "qwen/qwen3-235b-a22b-instruct-2507"
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "primeintellect/alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
+1 -1
View File
@@ -16,7 +16,7 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
batch_size = 512
rollouts_per_example = 8
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env" # included in lock file
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
name = "hendrycks-math"
+1 -1
View File
@@ -49,7 +49,7 @@ oversampling_factor = 2
max_off_policy_steps = 16
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "mini-swe-agent-plus"
name = "swe"
args = { max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
+3 -3
View File
@@ -38,10 +38,10 @@ freq = 1
batch_size = 512
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[orchestrator.train.sampling]
max_completion_tokens = 2048
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
+2 -2
View File
@@ -1,6 +1,6 @@
# Qwen 2.5 32B Math
# Qwen 3 30B - A3B Math
This example guides you through RL training [Qwen2.5-32B](https://huggingface.co/Qwen/Qwen2.5-32B) on math tasks.
This example guides you through RL training [Qwen3-30B-A3B-Thinking-2507](https://huggingface.co/Qwen/Qwen3-30B-A3B-Thinking-2507) on math tasks.
## Requirements
+3 -3
View File
@@ -45,10 +45,10 @@ batch_size = 512
oversampling_factor = 2
max_off_policy_steps = 8
[orchestrator.sampling]
max_tokens = 32768
[orchestrator.train.sampling]
max_completion_tokens = 32768
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "math"
+2 -2
View File
@@ -1,6 +1,6 @@
# Qwen 2.5 32B SWE
# Qwen 3 30B - A3B SWE
This example guides you through RL training [Qwen2.5-32B](https://huggingface.co/Qwen/Qwen2.5-32B) on agentic SWE tasks.
This example guides you through RL training [Qwen3-30B-A3B-Thinking-2507](https://huggingface.co/Qwen/Qwen3-30B-A3B-Thinking-2507) on agentic SWE tasks.
## Requirements
+1 -1
View File
@@ -46,7 +46,7 @@ batch_size = 512
oversampling_factor = 2
max_off_policy_steps = 16
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "mini-swe-agent-plus"
name = "swe"
args = { max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
+3 -3
View File
@@ -12,10 +12,10 @@ name = "reverse-text"
batch_size = 128
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "reverse-text"
[trainer.optim]
+3 -3
View File
@@ -37,13 +37,13 @@ oversampling_factor = 2.0
[orchestrator.model.lora]
name = "qwen3-4b-wiki-search"
[orchestrator.sampling]
max_tokens = 512
[orchestrator.train.sampling]
max_completion_tokens = 512
[orchestrator.buffer]
online_difficulty_filtering = true
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "primeintellect/wiki-search"
[ckpt] # Checkpoint at the end of training
+3 -3
View File
@@ -18,12 +18,12 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
batch_size = 1024
rollouts_per_example = 16
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "primeintellect/wordle"
name = "wordle"
[orchestrator.sampling]
max_tokens = 1024
[orchestrator.train.sampling]
max_completion_tokens = 1024
[trainer] # Default trainer config
+5 -3
View File
@@ -22,7 +22,7 @@ dependencies = [
"vllm>=0.19.0",
"wandb>=0.24.2",
"ring-flash-attn>=0.1.8",
"prime>=0.5.37",
"prime>=0.5.73",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
"tenacity>=8.2.0",
@@ -91,6 +91,8 @@ all = [
"prime-rl[flash-attn]",
"prime-rl[disagg]",
"prime-rl[quack]",
"prime-rl[flash-attn-3]",
"prime-rl[flash-attn-cute]",
]
[dependency-groups]
@@ -123,13 +125,13 @@ override-dependencies = [
[tool.uv.sources]
torch = { index = "pytorch-cu128" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "0760204" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "980a9ea" }
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 = "abd9943b" }
pydantic-config = { git = "https://github.com/samsja/pydantic_config.git", branch = "main" }
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.20/vllm_router-0.1.20-cp38-abi3-manylinux_2_28_x86_64.whl" }
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl" }
reverse-text = { index = "primeintellect" }
alphabet-sort = { index = "primeintellect" }
wiki-search = { index = "primeintellect" }
+8
View File
@@ -4,5 +4,13 @@ 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 verifiers package version.
# VERIFIERS_VERSION can be a git tag, branch, or commit hash.
if [ -n "$VERIFIERS_VERSION" ]; then
echo "Installing verifiers version: $VERIFIERS_VERSION"
uv pip install --reinstall-package verifiers \
"verifiers @ git+https://github.com/PrimeIntellect-ai/verifiers.git@${VERIFIERS_VERSION}"
fi
# Execute the main command
exec "$@"
+4
View File
@@ -153,6 +153,10 @@ uv run sft --data.type fake --data.batch-size 4
If you wish to configure values of the default variant, you don't need to set the `type` field.
### SFT hard distill override
For hosted multi-tenant runs where the trainer image's `trainer.loss.type` is fixed, the orchestrator exposes a per-run override that forces SFT loss on every micro-batch without rebuilding the trainer. Set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; both must be configured together (the orchestrator validator enforces this). The orchestrator stamps each `TrainingSample.sft_loss = True`, which the trainer's `compute_loss` honors by dispatching to `sft_loss_fn` per batch — independent of the trainer's configured default loss.
### Model fields
For `BaseModel | None` fields (like `[ckpt]`, `[wandb]`, `[compile]`), a bare flag enables them with defaults:
+48 -14
View File
@@ -1,21 +1,55 @@
"""Compatibility shim: ring_flash_attn + transformers >= 5.4.
"""Compatibility shims for upstream regressions.
ring_flash_attn 0.1.8 imports `is_flash_attn_greater_or_equal_2_10` from
`transformers.modeling_flash_attention_utils`. This symbol was removed from
that module in transformers 5.4 (still available as a deprecated function
in `transformers.utils.import_utils`, scheduled for removal in 5.8).
ring_flash_attn's except-branch is a no-op (imports the same symbol again),
so the import crashes on transformers >= 5.4. We patch the symbol back in as
`True` — the check is dead code since no one uses flash_attn < 2.1.0 anymore.
Upstream fix: https://github.com/zhuzilin/ring-flash-attention/pull/85
Remove this shim once ring_flash_attn ships a fixed version.
Imported early (before any model code) by trainer and orchestrator entrypoints.
Each shim documents the upstream issue and removal condition.
"""
# ---------------------------------------------------------------------------
# ring_flash_attn + transformers >= 5.4
#
# ring_flash_attn 0.1.8 imports `is_flash_attn_greater_or_equal_2_10` from
# `transformers.modeling_flash_attention_utils`, removed in transformers 5.4.
#
# Upstream fix: https://github.com/zhuzilin/ring-flash-attention/pull/85
# Remove once ring_flash_attn ships a fixed version.
# ---------------------------------------------------------------------------
import transformers.modeling_flash_attention_utils as _mfau
if not hasattr(_mfau, "is_flash_attn_greater_or_equal_2_10"):
# ring_flash_attn uses this as a bare value (if x:), but other code may
# call it as a function (if x():). Use a callable that is also truthy.
_mfau.is_flash_attn_greater_or_equal_2_10 = lambda: True
# ---------------------------------------------------------------------------
# transformers >= 5.5 hub_kernels offline regression
#
# lazy_load_kernel() resolves kernel versions via HfApi().list_repo_refs(),
# which raises OfflineModeIsEnabled when HF_HUB_OFFLINE=1 — even if the
# kernel is already cached locally. Only FileNotFoundError and AssertionError
# are caught; OfflineModeIsEnabled (a ConnectionError subclass) is not.
#
# This breaks Mamba-based models (NemotronH, Zamba2, Jamba, etc.) on SLURM
# worker nodes where HF_HUB_OFFLINE=1 is set.
#
# Fix: patch the except clause to also catch ConnectionError.
# Remove once huggingface/transformers fixes lazy_load_kernel offline handling.
# ---------------------------------------------------------------------------
try:
import transformers.integrations.hub_kernels as _hub_kernels
except ImportError:
_hub_kernels = None # transformers < 5.5, no patch needed
if _hub_kernels is not None:
from huggingface_hub.errors import OfflineModeIsEnabled
_original_lazy_load_kernel = _hub_kernels.lazy_load_kernel
def _patched_lazy_load_kernel(kernel_name, mapping=_hub_kernels._KERNEL_MODULE_MAPPING):
try:
return _original_lazy_load_kernel(kernel_name, mapping)
except OfflineModeIsEnabled:
# Return None so NemotronH skips hub kernels; prime-rl's
# _patch_mamba2_use_triton_ssd() uses mamba_ssm directly.
mapping[kernel_name] = None
return None
_hub_kernels.lazy_load_kernel = _patched_lazy_load_kernel
+1
View File
@@ -13,6 +13,7 @@ class EnvServerConfig(BaseConfig):
env: EnvConfig = EnvConfig()
log: LogConfig = LogConfig()
env_install_prerelease: bool = False
output_dir: Annotated[
Path,
+1 -10
View File
@@ -85,7 +85,7 @@ class ModelConfig(BaseModelConfig):
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`. "
'Set to "auto" to infer from the model name.',
),
] = None
] = "auto"
reasoning_parser: Annotated[
str | None,
@@ -247,15 +247,6 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
class InferenceExperimentalConfig(BaseConfig):
"""Experimental features for inference."""
reset_prefix_cache_after_update: Annotated[
bool,
Field(
description="Whether to reset the prefix cache after weight updates (update_weights, load_lora_adapter). "
"Ensures all KV states are recomputed with the new weights at the cost of extra prefill. "
"When False, prefer using orchestrator.experimental.use_prefix_cache_salt to invalidate stale caches via salt instead.",
),
] = False
class InferenceConfig(BaseConfig):
"""Configures inference."""
+56 -12
View File
@@ -324,6 +324,14 @@ class EnvConfig(BaseConfig):
),
] = -1
timeout: Annotated[
float | None,
Field(
validation_alias=AliasChoices("timeout", "timeout_seconds"),
description="Per-rollout wall-clock timeout in seconds. Set to None (default) to disable.",
),
] = None
@property
def stripped_id(self) -> str:
"""Environment ID without the @version suffix."""
@@ -346,6 +354,12 @@ class EnvConfig(BaseConfig):
self.extra_env_kwargs["max_total_completion_tokens"] = self.max_total_completion_tokens
return self
@model_validator(mode="after")
def resolve_timeout(self):
if self.timeout is not None:
self.extra_env_kwargs["timeout_seconds"] = self.timeout
return self
class TrainEnvConfig(EnvConfig):
"""Configures a training environment."""
@@ -715,7 +729,7 @@ class GibberishFilterConfig(BaseModel):
enforce: Annotated[
bool,
Field(
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
description="If True, skip detected rollouts entirely so they are not sent to the trainer. If False, only track detection metrics."
),
] = False
token_id_threshold: Annotated[
@@ -739,7 +753,7 @@ class RepetitionFilterConfig(BaseModel):
enforce: Annotated[
bool,
Field(
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
description="If True, skip detected rollouts entirely so they are not sent to the trainer. If False, only track detection metrics."
),
] = False
window: Annotated[
@@ -765,7 +779,7 @@ class ZeroAdvantageFilterConfig(BaseModel):
enforce: Annotated[
bool,
Field(
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
description="If True, skip detected rollouts entirely so they are not sent to the trainer. If False, only track detection metrics."
),
] = True
@@ -812,15 +826,6 @@ WeightBroadcastConfig: TypeAlias = Annotated[
class OrchestratorExperimentalConfig(BaseConfig):
"""Experimental features for the orchestrator."""
use_prefix_cache_salt: Annotated[
bool,
Field(
description="Whether to set a cache_salt on inference requests that changes with each weight update. "
"This invalidates prefix-cached KV states from previous policies without resetting the entire cache, "
"while preserving cache hits for in-flight off-policy rollouts.",
),
] = True
class TeacherModelConfig(BaseConfig):
"""Configures the teacher model for computing teacher logprobs (e.g. for distillation)."""
@@ -889,6 +894,17 @@ class OrchestratorConfig(BaseConfig):
),
] = None
# When True, trainer uses SFT loss instead of RL loss (per-run override for hosted multi-tenant training)
use_sft_loss: Annotated[
bool,
Field(
description=(
"When True, use SFT masked NLL loss instead of the trainer's configured RL loss. "
"Requires a teacher_rollout_model to be configured."
),
),
] = False
# The evaluation configuration
eval: EvalConfig | None = None
@@ -1045,6 +1061,13 @@ class OrchestratorConfig(BaseConfig):
),
] = True
env_install_prerelease: Annotated[
bool,
Field(
description="Allow pre-release versions when installing environments (e.g. verifiers>=0.1.12.dev5). Passes --prerelease to prime env install."
),
] = False
experimental: Annotated[
OrchestratorExperimentalConfig,
Field(description="Experimental features for the orchestrator."),
@@ -1088,6 +1111,27 @@ class OrchestratorConfig(BaseConfig):
raise ValueError(f"Duplicate filter types: {types}. Each filter type may only appear once.")
return self
@model_validator(mode="after")
def validate_sft_distill_mode(self):
"""Enforce the SFT hard distill invariants that involve only orchestrator fields.
Runs at ``OrchestratorConfig`` level so hosted deployments (which load this
config standalone via the ``orchestrator`` entrypoint) get the same guarantees
as the combined ``rl`` entrypoint.
"""
has_teacher = self.teacher_rollout_model is not None
if self.use_sft_loss and not has_teacher:
raise ValueError(
"orchestrator.use_sft_loss = true requires orchestrator.teacher_rollout_model to be configured."
)
if has_teacher and not self.use_sft_loss:
raise ValueError("orchestrator.teacher_rollout_model requires orchestrator.use_sft_loss = true.")
if has_teacher and self.use_token_client:
raise ValueError(
"orchestrator.use_token_client must be false when orchestrator.teacher_rollout_model is configured."
)
return self
@model_validator(mode="after")
def nccl_max_async_level(self):
if self.weight_broadcast.type == "nccl":
+27 -16
View File
@@ -77,8 +77,14 @@ class SharedWandbConfig(BaseConfig):
project: Annotated[str | None, Field(description="The W&B project to use.")] = "prime-rl"
entity: Annotated[str | None, Field(description="The W&B entity to use.")] = None
name: Annotated[str | None, Field(description="The W&B run name to use.")] = None
group: Annotated[str | None, Field(description="The W&B group to use.")] = None
tags: Annotated[list[str] | None, Field(description="The W&B tags to attach to the run.")] = None
offline: Annotated[bool | None, Field(description="Whether to run W&B in offline mode.")] = False
shared: Annotated[
@@ -428,24 +434,18 @@ class RLConfig(BaseConfig):
return self
@model_validator(mode="after")
def validate_external_rollout_mode(self):
if self.orchestrator.teacher_rollout_model is None:
return self
def validate_external_rollout_inference(self):
"""Forbid configuring a local inference server when rollouts come from an external teacher.
if self.trainer.loss.type != "sft":
raise ValueError('orchestrator.teacher_rollout_model is only supported when trainer.loss.type = "sft".')
if self.inference is not None:
Orchestrator-only invariants (``use_sft_loss`` paired with ``teacher_rollout_model``,
and ``use_token_client`` coupling) live on ``OrchestratorConfig`` so the hosted
orchestrator entrypoint also enforces them.
"""
if self.orchestrator.teacher_rollout_model is not None and self.inference is not None:
raise ValueError(
"inference must be omitted when orchestrator.teacher_rollout_model is configured. "
"External rollout mode does not use the local inference server."
)
if self.orchestrator.use_token_client:
raise ValueError(
"orchestrator.use_token_client must be false when orchestrator.teacher_rollout_model is configured."
)
return self
### Auto-setup and validate shared configs
@@ -522,6 +522,10 @@ class RLConfig(BaseConfig):
self.trainer.wandb.project = self.wandb.project
self.orchestrator.wandb.project = self.wandb.project
if self.wandb.entity:
self.trainer.wandb.entity = self.wandb.entity
self.orchestrator.wandb.entity = self.wandb.entity
if self.wandb.shared:
if self.wandb.name:
self.trainer.wandb.name = self.wandb.name
@@ -531,6 +535,14 @@ class RLConfig(BaseConfig):
self.trainer.wandb.name = f"{self.wandb.name}-trainer"
self.orchestrator.wandb.name = f"{self.wandb.name}-orchestrator"
if self.wandb.group:
self.trainer.wandb.group = self.wandb.group
self.orchestrator.wandb.group = self.wandb.group
if self.wandb.tags:
self.trainer.wandb.tags = self.wandb.tags.copy()
self.orchestrator.wandb.tags = self.wandb.tags.copy()
if self.wandb.offline:
self.trainer.wandb.offline = self.wandb.offline
self.orchestrator.wandb.offline = self.wandb.offline
@@ -742,9 +754,8 @@ class RLConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_session_headers(self):
"""Auto-configure X-Session-ID header for sticky routing at the inference router."""
if "extra_headers_from_state" not in self.orchestrator.client.model_fields_set:
self.orchestrator.client.extra_headers_from_state = {"X-Session-ID": "example_id"}
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
self.orchestrator.client.extra_headers_from_state.setdefault("X-Session-ID", "example_id")
return self
@model_validator(mode="after")
+29
View File
@@ -184,6 +184,14 @@ class ClientConfig(BaseConfig):
),
] = 30.0
wait_for_ready_timeout: Annotated[
int,
Field(
description="Timeout in seconds for waiting for the inference pool to become ready at startup. "
"Applies to both the static health check and elastic DNS-based discovery. Defaults to 1800 seconds.",
),
] = 1800
base_url: Annotated[
list[str],
Field(
@@ -354,6 +362,13 @@ class WandbConfig(BaseConfig):
# Shared configs (May be overwritten by WandbConfig from `rl.py`)
project: Annotated[str, Field(description="The W&B project to log to.")] = "prime-rl"
entity: Annotated[
str | None,
Field(
description="The W&B entity to log to.",
),
] = None
name: Annotated[
str | None,
Field(
@@ -361,6 +376,20 @@ class WandbConfig(BaseConfig):
),
] = None
group: Annotated[
str | None,
Field(
description="The W&B group to use for logging.",
),
] = None
tags: Annotated[
list[str] | None,
Field(
description="The W&B tags to attach to the run.",
),
] = None
offline: Annotated[bool, Field(description="Whether to run W&B in offline mode.")] = False
+22 -7
View File
@@ -139,7 +139,13 @@ class LoRAConfig(BaseConfig):
target_modules: Annotated[
list[str],
Field(
description="Module names or regex patterns for modules to apply LoRA to. Simple names (e.g., 'q_proj') match any component in the module path. Regex patterns match anywhere in the name.",
description=(
"Module names or regex patterns for modules to apply LoRA to. Simple names (e.g., 'q_proj') "
"match any component in the module path. Regex patterns match anywhere in the name. "
"Names unknown to the current model are silently ignored, so defaults cover multiple architectures. "
"NemotronH note: 'experts' matches NonGatedGroupedExperts inside LatentMoE; 'fc1_latent_proj' and "
"'fc2_latent_proj' adapt the latent up/down projections. Add 'in_proj'/'out_proj' to also LoRA Mamba."
),
),
] = [
"q_proj",
@@ -150,6 +156,8 @@ class LoRAConfig(BaseConfig):
"up_proj",
"down_proj",
"experts",
"fc1_latent_proj",
"fc2_latent_proj",
]
modules_to_save: Annotated[
@@ -175,6 +183,13 @@ class DebugModelConfig(BaseConfig):
),
] = False
force_balanced_routing: Annotated[
bool,
Field(
description="If True, override MoE token-choice routing with a round-robin assignment so every expert receives an equal share of tokens. Intended for fake-data smoke tests where untrained routing would otherwise produce severe expert imbalance and OOM. Gating scores are still gathered from the override indices so the forward pass stays consistent.",
),
] = False
class ModelConfig(BaseModelConfig):
"""Configures the model for training."""
@@ -184,7 +199,7 @@ class ModelConfig(BaseModelConfig):
attn: Annotated[
AttnImplementation,
Field(
description="The attention implementation to use. When CP is enabled, ring attention uses the matching kernel family (FA2 for flash_attention_2, FA3 for flash_attention_3).",
description="The attention implementation to use. When CP is enabled, ring attention uses the matching kernel family (FA2 for flash_attention_2, FA3 for flash_attention_3, FA4 for fa4).",
),
] = "flash_attention_2"
@@ -368,12 +383,12 @@ class ModelConfig(BaseModelConfig):
@model_validator(mode="after")
def cp_only_with_flash_attn(self):
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3"]:
raise ValueError("CP is only supported with flash attention 2 or flash attention 3")
if self.cp > 1 and self.attn == "flash_attention_3" and self.impl != "custom":
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "fa4"]:
raise ValueError("CP is only supported with flash attention 2, flash attention 3, or fa4")
if self.cp > 1 and self.attn in ("flash_attention_3", "fa4") and self.impl != "custom":
raise ValueError(
"CP with flash_attention_3 requires model.impl='custom' "
"(the FA3 ring-attention kernel is only implemented for the custom model path)"
f"CP with {self.attn} requires model.impl='custom' "
"(the ring-attention kernel is only implemented for the custom model path)"
)
return self
+16 -4
View File
@@ -13,6 +13,7 @@ import pynvml
import tomli_w
from prime_rl.configs.rl import RLConfig
from prime_rl.trainer.model import pre_download_model
from prime_rl.utils.config import cli
from prime_rl.utils.logger import get_logger, setup_logger
from prime_rl.utils.pathing import (
@@ -547,15 +548,26 @@ def rl(config: RLConfig):
if ckpt_output_dir is not None:
ckpt_output_dir.mkdir(parents=True, exist_ok=True)
# Clean stale artifacts from steps after the resume point
# Clean stale rollouts and broadcasts. When resuming, anything past the resume
# step is stale. When training from scratch, every existing step directory is
# stale — without this, a fresh run in a dirty output_dir would pick up rollouts
# from a previous run and the orchestrator would see a negative async level.
resume_step: int | None = None
if resuming:
resume_step = config.ckpt.resume_step
if resume_step == -1:
ckpt_base = ckpt_output_dir if ckpt_output_dir is not None else config.output_dir
resume_step = resolve_latest_ckpt_step(get_ckpt_dir(ckpt_base))
if resume_step is not None:
get_logger().info(f"Resuming from step {resume_step}, cleaning future rollouts and broadcasts")
clean_future_steps(config.output_dir, resume_step)
if resume_step is not None:
get_logger().info(f"Resuming from step {resume_step}, cleaning future rollouts and broadcasts")
clean_future_steps(config.output_dir, resume_step)
else:
get_logger().info("Training from scratch, cleaning any stale rollouts and broadcasts")
clean_future_steps(config.output_dir, -1)
if not config.dry_run:
pre_download_model(config.trainer.model.name)
if config.slurm is not None:
rl_slurm(config)
+4
View File
@@ -9,6 +9,7 @@ from threading import Event, Thread
import tomli_w
from prime_rl.configs.sft import SFTConfig
from prime_rl.trainer.model import pre_download_model
from prime_rl.utils.config import cli
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir, validate_output_dir
@@ -196,6 +197,9 @@ def sft(config: SFTConfig):
validate_output_dir(config.output_dir, resuming=resuming, clean=clean)
config.output_dir.mkdir(parents=True, exist_ok=True)
if not config.dry_run:
pre_download_model(config.model.name)
if config.slurm is not None:
sft_slurm(config)
else:
+82 -19
View File
@@ -195,6 +195,7 @@ def _patch_qwen35_lora():
from vllm.model_executor.models.qwen3_5 import (
Qwen3_5ForCausalLMBase,
Qwen3_5ForConditionalGeneration,
Qwen3_5MoeForConditionalGeneration,
)
qkvz_fix = ["in_proj_q", "in_proj_k", "in_proj_v", "in_proj_z"]
@@ -202,6 +203,8 @@ def _patch_qwen35_lora():
Qwen3_5ForCausalLMBase.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
Qwen3_5ForConditionalGeneration.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
Qwen3_5MoeForConditionalGeneration.is_3d_moe_weight = False
from vllm.lora.layers.utils import _not_fully_sharded_can_replace
@classmethod
@@ -302,10 +305,14 @@ def _patch_lora_key_prefix():
# is embedded: "...experts.N.down_proj". Taking everything
# after ".experts" gives "experts.N.down_proj" which is
# never in the expected set even though "down_proj" is.
# Fix: always compare just the last component of the path.
# Qwen3-30B-A3B goes the other way: the expected set
# contains the fully-qualified per-expert name
# ("experts.N.down_proj") but not the bare suffix.
# Accept either form.
if ".experts" in module_name:
expert_suffix = module_name.split(".")[-1]
if expert_suffix not in expected_lora_modules:
experts_qualified = "experts" + module_name.split(".experts", 1)[-1]
if expert_suffix not in expected_lora_modules and experts_qualified not in expected_lora_modules:
unexpected_modules.append(module_name)
elif module_name.rsplit(".", 1)[-1] not in expected_lora_modules:
@@ -478,6 +485,65 @@ def monkey_patch_LRUCacheWorkerLoRAManager():
LRUCacheWorkerLoRAManager.add_adapter = _patched_add_adapter
# Monkeypatch WorkerLoRAManager._load_adapter to skip the per-module regex
# warning loop. On wide MoE models (Qwen3.5-35B-A3B) it spends minutes
# recompiling regex patterns inside is_supported_lora_module — purely to emit
# logger.warning_once about modules that will be ignored. Adapter validity is
# already enforced by from_local_checkpoint, so dropping the warnings is safe.
def monkey_patch_skip_lora_module_warnings():
from vllm.exceptions import LoRAAdapterNotFoundError
from vllm.lora.lora_model import LoRAModel
from vllm.lora.peft_helper import PEFTHelper
from vllm.lora.request import LoRARequest
from vllm.lora.utils import get_adapter_absolute_path
from vllm.lora.worker_manager import WorkerLoRAManager
def _patched_load_adapter(self: WorkerLoRAManager, lora_request: LoRARequest) -> LoRAModel:
try:
supported_lora_modules = self._adapter_manager.supported_lora_modules
packed_modules_mapping = self._adapter_manager.packed_modules_mapping
expected_lora_lst: list[str] = []
for module in supported_lora_modules:
if module in packed_modules_mapping:
expected_lora_lst.extend(packed_modules_mapping[module])
else:
expected_lora_lst.append(module)
if module == "experts":
expected_lora_lst.append(module)
expected_lora_modules = set(expected_lora_lst)
lora_path = get_adapter_absolute_path(lora_request.lora_path)
peft_helper = PEFTHelper.from_local_dir(
lora_path,
self.max_position_embeddings,
lora_request.tensorizer_config_dict,
)
peft_helper.validate_legal(self.lora_config)
model = self._adapter_manager.model
hf_to_vllm_mapper = getattr(model, "hf_to_vllm_mapper", None)
lora_skip_prefixes = getattr(model, "lora_skip_prefixes", None)
lora = self._lora_model_cls.from_local_checkpoint(
lora_path,
expected_lora_modules,
peft_helper=peft_helper,
lora_model_id=lora_request.lora_int_id,
device="cpu",
dtype=self.lora_config.lora_dtype,
model_vocab_size=self.vocab_size,
tensorizer_config_dict=lora_request.tensorizer_config_dict,
weights_mapper=hf_to_vllm_mapper,
skip_prefixes=lora_skip_prefixes,
)
except FileNotFoundError as e:
raise LoRAAdapterNotFoundError(lora_request.lora_name, lora_request.lora_path) from e
return lora
WorkerLoRAManager._load_adapter = _patched_load_adapter
# Monkeypatch TokenizeParams to fix overly conservative validation
def monkey_patch_tokenize_params_validation():
"""
@@ -957,18 +1023,15 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
def monkey_patch_offloading_connector_cpu_block_count():
"""Fix CPU block count miscalculation in OffloadingConnector.
CPUOffloadingSpec erroneously multiplies page_size_bytes by
len(kv_cache_config.kv_cache_tensors) when computing kv_bytes_per_block.
For UniformTypeKVCacheSpecs the page_size is already the total per-block
size across all layers, so the extra multiplier makes num_blocks far too
small. When the OffloadingManager later allocates block IDs past the
undersized CPU tensor, swap_blocks (cuMemcpyDtoHAsync_v2) segfaults on the
invalid pinned address.
CPUOffloadingSpec derives kv_bytes_per_block from page_size_bytes multiplied
by len(kv_cache_config.kv_cache_tensors), which double-counts: page_size is
already aggregated across layers in the group. The undersized CPU pool then
produces out-of-bounds block mappings and swap_blocks segfaults.
Fix: remove the num_tensors multiplier.
Fix: derive kv_bytes_per_block from the actual total GPU KV tensor size
divided by num_blocks, matching the upstream PR.
Upstream: https://github.com/vllm-project/vllm/pull/38395
Related: https://github.com/vllm-project/vllm/issues/39500
Upstream: https://github.com/vllm-project/vllm/pull/39617
"""
from vllm.v1.kv_offload.cpu.spec import CPUOffloadingSpec
@@ -977,18 +1040,18 @@ def monkey_patch_offloading_connector_cpu_block_count():
def _patched_init(self, vllm_config, kv_cache_config):
_original_init(self, vllm_config, kv_cache_config)
# Recalculate num_blocks WITHOUT the erroneous num_tensors multiplier.
cpu_bytes_to_use = self.extra_config.get("cpu_bytes_to_use")
if not cpu_bytes_to_use:
return
page_sizes = {g.kv_cache_spec.page_size_bytes for g in kv_cache_config.kv_cache_groups}
assert len(page_sizes) == 1
page_size_bytes = page_sizes.pop()
if kv_cache_config.num_blocks > 0:
total_gpu_kv_bytes = sum(t.size for t in kv_cache_config.kv_cache_tensors)
kv_bytes_per_block = (
total_gpu_kv_bytes // kv_cache_config.num_blocks
) * vllm_config.parallel_config.world_size
else:
kv_bytes_per_block = 0
# page_size_bytes already covers all layers in the group.
# Only multiply by world_size (each TP rank stores its own copy).
kv_bytes_per_block = page_size_bytes * vllm_config.parallel_config.world_size
kv_bytes_per_offloaded_block = kv_bytes_per_block * self.block_size_factor
self.num_blocks = (
int(cpu_bytes_to_use) // kv_bytes_per_offloaded_block if kv_bytes_per_offloaded_block > 0 else 0
+1 -12
View File
@@ -198,24 +198,16 @@ async def resume(request: Request):
async def update_weights(request: Request):
data = await request.json()
await engine_client(request).collective_rpc("update_weights_from_path", args=(data.get("weight_dir"),))
if request.app.state.reset_prefix_cache_after_update:
await engine_client(request).reset_prefix_cache()
return {"status": "ok"}
@router.post("/load_lora_adapter")
async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: Request):
"""Load a LoRA adapter, optionally resetting the prefix cache.
Wrapper around vLLM's /v1/load_lora_adapter that also resets the prefix cache
to invalidate KV states computed with old weights (unless disabled via config).
"""
"""Wrapper around vLLM's /v1/load_lora_adapter."""
handler = models(raw_request)
response = await handler.load_lora_adapter(lora_request)
if isinstance(response, ErrorResponse):
return JSONResponse(content=response.model_dump(), status_code=response.error.code)
if raw_request.app.state.reset_prefix_cache_after_update:
await engine_client(raw_request).reset_prefix_cache()
return {"status": "ok"}
@@ -274,8 +266,6 @@ async def custom_init_app_state(
"""
await init_app_state(engine_client, state, args, supported_tasks)
state.reset_prefix_cache_after_update = getattr(args, "reset_prefix_cache_after_update", True)
if "generate" in supported_tasks and state.openai_serving_chat is not None:
original_chat = state.openai_serving_chat
serving_chat = object.__new__(OpenAIServingChatWithTokens)
@@ -342,7 +332,6 @@ def server(config: InferenceConfig, vllm_extra: dict[str, Any] | None = None):
args.tool_call_parser = resolve_tool_call_parser(args.model, args.tool_call_parser)
args.enable_auto_tool_choice = args.tool_call_parser is not None
args.reset_prefix_cache_after_update = config.experimental.reset_prefix_cache_after_update
if args.tool_call_parser is not None:
logger.info(f"Using tool_call_parser='{args.tool_call_parser}' for model '{args.model}'")
@@ -5,12 +5,16 @@ from prime_rl.inference.patches import (
monkey_patch_LRUCacheWorkerLoRAManager,
monkey_patch_minimax_m2_for_lora,
monkey_patch_no_moe_lora,
monkey_patch_skip_lora_module_warnings,
)
logger = logging.getLogger(__name__)
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
monkey_patch_LRUCacheWorkerLoRAManager()
# Skip the per-module regex warning loop in WorkerLoRAManager._load_adapter
# (minutes-long stall on wide MoE models like Qwen3.5-35B-A3B)
monkey_patch_skip_lora_module_warnings()
# Monkeypatch MiniMaxM2 MoE gate dtype and adapter key mapping for LoRA compatibility
monkey_patch_minimax_m2_for_lora()
# Disable LoRA on MoE layers so vLLM picks better kernels (e.g. TRTLLMFlashInfer on Blackwell)
@@ -18,7 +18,7 @@ def run_server(config: EnvServerConfig):
env_ids_to_install = set()
env_ids_to_install.update(get_env_ids_to_install([config.env]))
for env_id in env_ids_to_install:
install_env(env_id)
install_env(env_id, prerelease=config.env_install_prerelease)
log_dir = (get_log_dir(config.output_dir) / config.env.resolved_name).as_posix()
+11 -10
View File
@@ -104,9 +104,7 @@ class Env:
self._env_server_process = process
return address
def _sampling_args_with_salt(self, cache_salt: str | None) -> dict:
if cache_salt is None:
return self.sampling_args
def _sampling_args_with_salt(self, cache_salt: str) -> dict:
sampling_args = {**self.sampling_args}
extra_body = {**sampling_args.get("extra_body", {}), "cache_salt": cache_salt}
sampling_args["extra_body"] = extra_body
@@ -117,7 +115,7 @@ class Env:
client: vf.ClientConfig,
example: dict,
model_name: str,
cache_salt: str | None = None,
cache_salt: str,
) -> vf.RolloutOutput:
"""Run a single rollout for an example."""
return await self.env.run_rollout(
@@ -136,7 +134,7 @@ class Env:
example: dict,
model_name: str,
rollouts_per_example: int,
cache_salt: str | None = None,
cache_salt: str,
) -> list[vf.RolloutOutput]:
"""Run a group of rollouts for an example. Required for group-scoring envs."""
return await self.env.run_group(
@@ -181,7 +179,7 @@ class EvalEnv(Env):
get_client: Callable[[], Awaitable[vf.ClientConfig]],
ckpt_step: int,
step: int,
cache_salt: str | None = None,
cache_salt: str,
) -> list[vf.RolloutOutput]:
num_examples = len(self.examples)
rollouts_per_example = self.config.rollouts_per_example
@@ -352,10 +350,13 @@ class Envs(Generic[EnvT]):
log_level: str | None = None,
json_logging: bool = False,
) -> None:
"""Spawn env servers (where needed) and connect all env clients in parallel."""
await asyncio.gather(
*(env.start(log_dir=log_dir, log_level=log_level, json_logging=json_logging) for env in self)
)
"""Spawn env servers (where needed) and connect env clients one at a time.
Serialized to avoid a TOCTOU port race: get_free_port() only holds the port
until it returns, so parallel spawns can hand the same port to two children.
"""
for env in self:
await env.start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
atexit.register(self.shutdown)
def shutdown(self) -> None:
+17 -40
View File
@@ -2,9 +2,8 @@
Filters run after rollouts complete, inspecting token IDs and logprobs to
detect gibberish or repetition. Detection metrics are always tracked.
When enforce=True, detected rollouts get their completion mask cleared so
they don't contribute to training. Reward is kept as-is for baseline
calculation.
When enforce=True, detected rollouts are skipped entirely during training and
are not sent to the trainer. Reward is kept as-is for baseline calculation.
"""
import math
@@ -149,63 +148,41 @@ def setup_filters(configs: list[FilterConfig], vocab_size: int) -> list[RolloutF
return filters
def apply_filters(
filters: list[RolloutFilter],
rollouts: list[vf.RolloutOutput],
) -> dict[str, float]:
"""Apply filters to rollouts. Detection metrics are always tracked.
def apply_filters(filters: list[RolloutFilter], rollouts: list[vf.RolloutOutput]) -> None:
"""Flag rollouts in-place with per-filter detection and drop decision.
When a filter has enforce=True, detected rollouts get their completion
mask cleared and stop_condition set. Reward is kept as-is for baseline
calculation.
First matching filter wins per rollout (no double-counting).
Returns aggregate metrics dict for logging.
Each rollout gets a `filters` dict with per-filter detection booleans and
an `is_filtered` bool that is True iff an enforcing filter detected it.
First matching filter wins per rollout (no double-counting). Reward and
trajectory tokens are left untouched so the rollout can still contribute
to baseline calculations and metric aggregation.
"""
for rollout in rollouts:
rollout["filters"] = {f.name: False for f in filters}
rollout["is_filtered"] = False
if not filters:
return {}
return
counts: dict[str, int] = {f.name: 0 for f in filters}
total_detected = 0
total_enforced = 0
for rollout in rollouts:
if rollout.get("metrics") is None:
rollout["metrics"] = {}
for filt in filters:
rollout["metrics"].setdefault(f"filter/{filt.name}", 0.0)
for filt in filters:
result = filt.check(rollout)
if result.detected:
counts[filt.name] += 1
total_detected += 1
rollout["metrics"][f"filter/{filt.name}"] = 1.0
rollout["filters"][filt.name] = True
if filt.enforce:
for step in rollout["trajectory"]:
tokens = step["tokens"]
if tokens is not None:
tokens["completion_mask"] = [0] * len(tokens["completion_mask"])
rollout["stop_condition"] = filt.name
rollout["is_filtered"] = True
total_enforced += 1
break
n = len(rollouts)
metrics: dict[str, float] = {}
for f in filters:
metrics[f"filter/{f.name}_count"] = float(counts[f.name])
metrics[f"filter/{f.name}_rate"] = counts[f.name] / n if n > 0 else 0.0
metrics["filter/total_detected_rate"] = total_detected / n if n > 0 else 0.0
metrics["filter/total_enforced_rate"] = total_enforced / n if n > 0 else 0.0
if total_detected > 0:
enforced_msg = f", enforced {total_enforced}" if total_enforced > 0 else ""
get_logger().info(
f"Detected {total_detected}/{n} rollouts "
f"Detected {total_detected}/{len(rollouts)} rollouts "
f"({', '.join(f'{name}={c}' for name, c in counts.items() if c > 0)})" + enforced_msg
)
return metrics
+94 -43
View File
@@ -76,6 +76,11 @@ from prime_rl.utils.utils import (
# and artifacts are persisted *before* this point, so a forced exit is safe.
SHUTDOWN_TIMEOUT_S = 300
# Maximum number of times to attempt generating a training batch when all
# rollouts are filtered out. After this many attempts, the orchestrator crashes
# rather than silently skipping training steps.
MAX_EMPTY_BATCH_ATTEMPTS = 3
@clean_exit
async def orchestrate(config: OrchestratorConfig):
@@ -108,7 +113,7 @@ async def orchestrate(config: OrchestratorConfig):
env_ids_to_install.update(get_env_ids_to_install(config.eval.env))
for env_id in env_ids_to_install:
install_env(env_id)
install_env(env_id, prerelease=config.env_install_prerelease)
# Setup rollout inference pool (handles both static and elastic modes)
rollout_client_config, rollout_model_name, enable_policy_updates = setup_external_rollout_model(config, logger)
@@ -236,7 +241,6 @@ async def orchestrate(config: OrchestratorConfig):
enable_policy_updates=enable_policy_updates,
lora_name=config.model.lora.name if config.model.lora else None,
config=config,
use_prefix_cache_salt=config.experimental.use_prefix_cache_salt,
)
scheduler.model_name = rollout_model_name
@@ -380,7 +384,6 @@ async def orchestrate(config: OrchestratorConfig):
logger.info("Cancelling in-flight training rollouts before starting evals to avoid congestion.")
await scheduler.cancel_inflight_rollouts()
eval_cache_salt = str(ckpt_step) if config.experimental.use_prefix_cache_salt else None
eval_results = await asyncio.gather(
*[
eval_env.evaluate(
@@ -388,7 +391,7 @@ async def orchestrate(config: OrchestratorConfig):
get_client=inference_pool.get_eval_client,
ckpt_step=ckpt_step,
step=progress.step,
cache_salt=eval_cache_salt,
cache_salt=str(ckpt_step),
)
for eval_env in envs_to_eval
]
@@ -398,7 +401,9 @@ async def orchestrate(config: OrchestratorConfig):
eval_rollouts = [o for outputs in eval_results for o in outputs]
if eval_rollouts:
step_path = get_step_path(get_rollout_dir(config.output_dir), progress.step)
await asyncio.to_thread(save_rollouts, eval_rollouts, step_path / "eval_rollouts.jsonl")
await asyncio.to_thread(
save_rollouts, eval_rollouts, step_path / "eval_rollouts.jsonl", exclude_keys={"trajectory"}
)
# Resume weight updates
scheduler.checkpoint_ready.set()
@@ -406,17 +411,61 @@ async def orchestrate(config: OrchestratorConfig):
# Update prev_ckpt_step for next iteration
prev_ckpt_step = ckpt_step
# Schedule generating the training batch
train_task = asyncio.create_task(scheduler.generate_batch(step=progress.step))
# Schedule generating the training batch. Retry on empty-after-filter
# batches so the trainer never receives an empty batch.
generate_completions_time = 0.0
train_rollouts: list[vf.RolloutOutput] = []
num_rollouts = 0
num_unique_examples = 0
n_trainable = 0
for attempt in range(MAX_EMPTY_BATCH_ATTEMPTS):
train_rollouts = await scheduler.generate_batch(step=progress.step)
generate_completions_time += scheduler.last_batch_generation_time
# Await train rollouts
await train_task
generate_completions_time = scheduler.last_batch_generation_time
train_rollouts = train_task.result()
# Compute advantages (in-place)
num_rollouts = len(train_rollouts)
num_unique_examples = len({(r["env_name"], r["example_id"]) for r in train_rollouts})
compute_advantages(train_rollouts, config.rollouts_per_example, config.advantage)
# Apply rollout filters — sets rollout["filters"] and rollout["is_filtered"]
apply_filters(rollout_filters, train_rollouts)
n_trainable = sum(1 for r in train_rollouts if not r["is_filtered"])
if n_trainable > 0:
break
if attempt == MAX_EMPTY_BATCH_ATTEMPTS - 1:
logger.error(
f"Attempt {attempt + 1}/{MAX_EMPTY_BATCH_ATTEMPTS} at step {progress.step} "
f"filtered out all {num_rollouts} rollouts - crashing orchestrator"
)
reason = (
f"All {num_rollouts} rollouts were filtered out on "
f"{MAX_EMPTY_BATCH_ATTEMPTS} consecutive attempts at step {progress.step}"
)
evicted_path = config.output_dir / "control" / "evicted.txt"
evicted_path.parent.mkdir(parents=True, exist_ok=True)
evicted_path.write_text(reason)
raise RuntimeError(reason)
logger.warning(
f"Attempt {attempt + 1}/{MAX_EMPTY_BATCH_ATTEMPTS} at step {progress.step} "
f"filtered out all {num_rollouts} rollouts - retrying batch generation"
)
trainable_ratio = n_trainable / num_rollouts
if trainable_ratio <= 0.1:
logger.warning(
f"Only {n_trainable}/{num_rollouts} rollouts in the batch are trainable "
f"({trainable_ratio:.1%}) - this can mean the tasks are too easy or too hard for the "
"model, consider reviewing the task difficulty of your environment(s)"
)
# Save train rollouts to disk (fire-and-forget background thread)
step_path = get_step_path(get_rollout_dir(config.output_dir), progress.step)
await asyncio.to_thread(save_rollouts, train_rollouts, step_path / "train_rollouts.jsonl")
await asyncio.to_thread(
save_rollouts, train_rollouts, step_path / "train_rollouts.jsonl", exclude_keys={"trajectory"}
)
# VLM: offload base64 images to disk immediately to free memory
if is_vlm:
@@ -427,15 +476,6 @@ async def orchestrate(config: OrchestratorConfig):
f"VLM offloaded {num_offloaded} unique images to disk in {time.perf_counter() - offload_start:.2f}s"
)
# Compute advantages (in-place)
example_ids = [r["example_id"] for r in train_rollouts]
num_rollouts = len(train_rollouts)
num_unique_examples = len(set(example_ids))
compute_advantages(train_rollouts, config.rollouts_per_example, config.advantage)
# Apply rollout filters (zeros reward/mask for degenerate generations)
filter_metrics = apply_filters(rollout_filters, train_rollouts)
# Convert rollouts to training samples
parallel_preprocess_start = time.perf_counter()
@@ -472,7 +512,8 @@ async def orchestrate(config: OrchestratorConfig):
*(asyncio.to_thread(process_rollout, r, rollout_idx) for rollout_idx, r in enumerate(train_rollouts))
)
# Collect results and assign advantages
# Collect results and assign advantages. Metrics are computed over all
# rollouts; only non-filtered samples are sent to the trainer.
train_examples: list[TrainingSample] = []
rollout_prefill_lens: list[int] = []
rollout_decode_lens: list[int] = []
@@ -482,18 +523,20 @@ async def orchestrate(config: OrchestratorConfig):
for rollout, samples in zip(train_rollouts, results):
rollout_prefill_tokens = 0
rollout_decode_tokens = 0
if samples is not None:
rollout_samples_per_rollout.append(len(samples))
for sample in samples:
sample.advantage = rollout["advantage"]
sample.reward = rollout["reward"]
sample_decode_tokens = sum(sample.completion_mask)
sample_prefill_tokens = len(sample.prompt_ids) + len(sample.completion_mask) - sample_decode_tokens
rollout_decode_tokens += sample_decode_tokens
rollout_prefill_tokens += sample_prefill_tokens
if samples is None:
samples = []
rollout_samples_per_rollout.append(len(samples))
for sample in samples:
sample.advantage = rollout["advantage"]
sample.reward = rollout["reward"]
if config.use_sft_loss:
sample.sft_loss = True
sample_decode_tokens = sum(sample.completion_mask)
sample_prefill_tokens = len(sample.prompt_ids) + len(sample.completion_mask) - sample_decode_tokens
rollout_decode_tokens += sample_decode_tokens
rollout_prefill_tokens += sample_prefill_tokens
if not rollout["is_filtered"]:
train_examples.append(sample)
else:
rollout_samples_per_rollout.append(0)
rollout_prefill_lens.append(rollout_prefill_tokens)
rollout_decode_lens.append(rollout_decode_tokens)
num_prefill_tokens += rollout_prefill_tokens
@@ -536,6 +579,7 @@ async def orchestrate(config: OrchestratorConfig):
"env_name": [rollout["env_name"] for rollout in train_rollouts],
"reward": [rollout["reward"] for rollout in train_rollouts],
"is_truncated": [rollout["is_truncated"] for rollout in train_rollouts],
"is_filtered": [rollout["is_filtered"] for rollout in train_rollouts],
"stop_condition": [rollout.get("stop_condition") for rollout in train_rollouts],
"seq_len": [get_seq_len(rollout) for rollout in train_rollouts],
"prefill_len": rollout_prefill_lens,
@@ -547,8 +591,9 @@ async def orchestrate(config: OrchestratorConfig):
}
)
# Separate DataFrame for env reward function metrics to avoid column name collisions
# Separate DataFrames for env reward function metrics and filter flags to avoid column name collisions
metrics_df = pd.DataFrame([rollout["metrics"] for rollout in train_rollouts])
filter_df = pd.DataFrame([rollout["filters"] for rollout in train_rollouts])
# Update progress metrics
num_tokens = int(results_df.seq_len.sum())
@@ -558,13 +603,13 @@ async def orchestrate(config: OrchestratorConfig):
def compute_solve_rates(df):
"""Compute solve_none, solve_all, effective_batch_size for a set of rollouts."""
reward_per_problem = df.groupby("example_id").reward.sum()
reward_per_problem = df.groupby(["env_name", "example_id"]).reward.sum()
solve_none = (reward_per_problem == 0).mean()
solve_all = (reward_per_problem == config.rollouts_per_example).mean()
return solve_none, solve_all, 1 - solve_none - solve_all
# Group by example_id to average across rollouts within each problem
by_example = results_df.groupby("example_id")
# Group by (env_name, example_id) to average across rollouts within each problem
by_example = results_df.groupby(["env_name", "example_id"])
solve_none, solve_all, effective_batch_size = compute_solve_rates(results_df)
to_log = {
@@ -630,8 +675,9 @@ async def orchestrate(config: OrchestratorConfig):
**buffer.get_metrics(),
# Event loop lag metrics
**event_loop_lag_monitor.get_metrics(),
# Rollout filter metrics
**filter_metrics,
# Rollout filter metrics (detection rate per filter + overall drop rate)
"filters/all/is_filtered": results_df.is_filtered.astype(float).mean(),
**{f"filters/all/{name}": filter_df[name].astype(float).mean() for name in filter_df.columns},
# W&B axis
"step": progress.step,
}
@@ -670,6 +716,10 @@ async def orchestrate(config: OrchestratorConfig):
env_metrics_df = metrics_df.loc[env_df.index]
for metric in metrics_df.columns:
to_log[f"metrics/{env}/{metric}"] = env_metrics_df.groupby(env_df["example_id"])[metric].mean().mean()
to_log[f"filters/{env}/is_filtered"] = env_df.is_filtered.astype(float).mean()
env_filter_df = filter_df.loc[env_df.index]
for name in filter_df.columns:
to_log[f"filters/{env}/{name}"] = env_filter_df[name].astype(float).mean()
# Log metrics to monitor(s)
monitor.log(to_log, step=progress.step)
@@ -694,7 +744,7 @@ async def orchestrate(config: OrchestratorConfig):
)
reward_mean = by_example.reward.mean().mean()
step_message = f"Step {progress.step} | Time: {step_time:.2f}s | Reward: {reward_mean:.4f} | Seq. Length: {by_example.seq_len.mean().mean():.1f} tokens/sample | Async Level: {scheduler.async_level} | Max. Off-Policy Level: {scheduler.max_off_policy_level}"
step_message = f"Step {progress.step} | Time: {step_time:.2f}s | Reward: {reward_mean:.4f} | Seq. Length: {by_example.seq_len.mean().mean():.1f} tokens/sample | Max. Off-Policy Level: {scheduler.max_off_policy_level}"
logger.success(step_message)
# Increment step
@@ -714,7 +764,6 @@ async def orchestrate(config: OrchestratorConfig):
if config.eval and eval_envs is not None:
logger.info("Running final evals")
final_cache_salt = str(ckpt_step) if config.experimental.use_prefix_cache_salt else None
eval_results = await asyncio.gather(
*[
eval_env.evaluate(
@@ -722,7 +771,7 @@ async def orchestrate(config: OrchestratorConfig):
get_client=inference_pool.get_eval_client,
ckpt_step=ckpt_step,
step=progress.step,
cache_salt=final_cache_salt,
cache_salt=str(ckpt_step),
)
for eval_env in eval_envs
]
@@ -732,7 +781,9 @@ async def orchestrate(config: OrchestratorConfig):
eval_rollouts = [o for outputs in eval_results for o in outputs]
if eval_rollouts:
step_path = get_step_path(get_rollout_dir(config.output_dir), progress.step)
await asyncio.to_thread(save_rollouts, eval_rollouts, step_path / "eval_rollouts.jsonl")
await asyncio.to_thread(
save_rollouts, eval_rollouts, step_path / "eval_rollouts.jsonl", exclude_keys={"trajectory"}
)
# Log final (immutable) samples and distributions to monitor(s)
monitor.log_final_samples()
+9 -11
View File
@@ -68,7 +68,6 @@ class Scheduler:
tasks_per_minute: int | None,
enable_policy_updates: bool = True,
lora_name: str | None = None,
use_prefix_cache_salt: bool = False,
):
self.logger = get_logger()
if tasks_per_minute is not None:
@@ -87,7 +86,6 @@ class Scheduler:
self.strict_async_level = strict_async_level
self.enable_policy_updates = enable_policy_updates
self.lora_name = lora_name
self.use_prefix_cache_salt = use_prefix_cache_salt
self.model_name = self.config.model.name
self.json_logging = config.log.json_logging
@@ -198,7 +196,7 @@ class Scheduler:
env_name = group.example["env_name"]
env = self.train_envs.get(env_name)
cache_salt = str(self.ckpt_step) if self.use_prefix_cache_salt else None
cache_salt = str(self.ckpt_step)
if env.requires_group_scoring:
rollout_count = group.rollouts_to_schedule
group.rollouts_to_schedule = 0
@@ -434,14 +432,7 @@ class Scheduler:
valid_rollouts = []
has_failures = False
for rollout in rollouts:
if len(rollout["trajectory"]) == 0:
self.empty_rollouts_by_env[env_name] += 1
has_failures = True
self.logger.warning(
f"Empty trajectory in group {group_id} ({env_name}), re-scheduling "
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete)"
)
elif rollout["error"] is not None:
if rollout["error"] is not None:
self.errored_rollouts_by_env[env_name] += 1
has_failures = True
self.logger.warning(
@@ -449,6 +440,13 @@ class Scheduler:
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete): "
f"{rollout['error']['error_chain_repr']}"
)
elif len(rollout["trajectory"]) == 0:
self.empty_rollouts_by_env[env_name] += 1
has_failures = True
self.logger.warning(
f"Empty trajectory in group {group_id} ({env_name}), re-scheduling "
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete)"
)
else:
rollout["env_name"] = env_name
valid_rollouts.append(rollout)
+1 -1
View File
@@ -797,7 +797,7 @@ def build_vlm_image_cache(rollouts: list[vf.RolloutOutput], processor) -> VLMIma
Caches per rollout to keep images aligned with divergent multi-turn trajectories.
"""
examples = [(idx, rollout) for idx, rollout in enumerate(rollouts)]
unique_example_ids = {rollout["example_id"] for rollout in rollouts}
unique_example_ids = {(rollout.get("env_name"), rollout["example_id"]) for rollout in rollouts}
# Extract images (also strips base64 data from rollout prompts to free memory)
extract_start = time.perf_counter()
+3 -2
View File
@@ -59,12 +59,13 @@ def get_model_completion_len(output: vf.RolloutOutput) -> int:
return sum(len(step["tokens"]["completion_ids"]) for step in output["trajectory"] if step.get("tokens"))
def save_rollouts(rollouts: list[vf.RolloutOutput], path: Path) -> None:
def save_rollouts(rollouts: list[vf.RolloutOutput], path: Path, exclude_keys: set[str] | None = None) -> None:
"""Save rollouts to a JSONL file using verifiers serialization."""
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w") as f:
for rollout in rollouts:
json.dump(rollout, f, default=make_serializable)
row = {k: v for k, v in rollout.items() if k not in exclude_keys} if exclude_keys else rollout
json.dump(row, f, default=make_serializable)
f.write("\n")
@@ -107,6 +107,27 @@ echo "INFER_URLS=${INFER_URLS}"
{{ pre_run_command }}
{% endif %}
# Cleanup stale node-local state from prior jobs. Orphan python/torchrun/vllm
# processes and vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM
# termination and cause the next launch to hang (e.g. decode engines stuck at
# "Waiting for READY message from DP Coordinator"). Harmless on clean nodes.
srun bash -c '
pkill -9 -f "python.*prime_rl" 2>/dev/null
pkill -9 -f "torchrun" 2>/dev/null
pkill -9 -f "vllm-router" 2>/dev/null
pkill -9 -f "vllm" 2>/dev/null
pkill -9 -f "prime_rl" 2>/dev/null
# Also match prctl-set process names (kernel comm) like "vllm::router"
# which pkill -f does not see because -f only matches the cmdline.
pkill -9 "vllm" 2>/dev/null
pkill -9 "vllm::.*" 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::" | 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"
'
# Run inference
srun bash -c '
cd $PROJECT_DIR
@@ -151,6 +151,27 @@ uv sync --all-extras
{{ pre_run_command }}
{% endif %}
# Cleanup stale node-local state from prior jobs. Orphan python/torchrun/vllm
# processes and vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM
# termination and cause the next launch to hang (e.g. decode engines stuck at
# "Waiting for READY message from DP Coordinator"). Harmless on clean nodes.
srun bash -c '
pkill -9 -f "python.*prime_rl" 2>/dev/null
pkill -9 -f "torchrun" 2>/dev/null
pkill -9 -f "vllm-router" 2>/dev/null
pkill -9 -f "vllm" 2>/dev/null
pkill -9 -f "prime_rl" 2>/dev/null
# Also match prctl-set process names (kernel comm) like "vllm::router"
# which pkill -f does not see because -f only matches the cmdline.
pkill -9 "vllm" 2>/dev/null
pkill -9 "vllm::.*" 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::" | 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"
'
# Run RL
srun bash -c '
# Source environment
@@ -59,6 +59,26 @@ cd $PROJECT_DIR && uv sync --all-extras
{{ pre_run_command }}
{% endif %}
# Cleanup stale node-local state from prior jobs. Orphan python/torchrun/vllm
# processes and vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM
# termination and cause the next launch to hang. Harmless on clean nodes.
srun bash -c '
pkill -9 -f "python.*prime_rl" 2>/dev/null
pkill -9 -f "torchrun" 2>/dev/null
pkill -9 -f "vllm-router" 2>/dev/null
pkill -9 -f "vllm" 2>/dev/null
pkill -9 -f "prime_rl" 2>/dev/null
# Also match prctl-set process names (kernel comm) like "vllm::router"
# which pkill -f does not see because -f only matches the cmdline.
pkill -9 "vllm" 2>/dev/null
pkill -9 "vllm::.*" 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::" | 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"
'
# Run SFT
srun bash -c '
# Setup environment
+5 -1
View File
@@ -76,6 +76,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
pixel_values=training_example.pixel_values,
pixel_values_shape=training_example.pixel_values_shape,
image_grid_thw=training_example.image_grid_thw,
sft_loss=training_example.sft_loss,
)
@@ -115,7 +116,10 @@ def packed_samples_into_micro_bs(
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:
if (
len(bin_content.input_ids) + len(sample.input_ids) <= max_seq_len
and bin_content.sft_loss == sample.sft_loss
):
bin_content.input_ids.extend(sample.input_ids)
bin_content.loss_mask.extend(sample.loss_mask)
bin_content.advantages.extend(sample.advantages)
+31 -5
View File
@@ -6,8 +6,12 @@ import torch.nn as nn
from prime_rl.configs.trainer import LoRAConfig
from prime_rl.trainer.models.layers.lora import MultiLoRALinear, MultiLoRAModule
from prime_rl.trainer.models.layers.lora.multi_moe import MultiLoRAGroupedExperts
from prime_rl.trainer.models.layers.moe import GroupedExperts
from prime_rl.trainer.models.layers.lora.multi_moe import (
MultiLoRAGptOssGroupedExperts,
MultiLoRAGroupedExperts,
MultiLoRANonGatedGroupedExperts,
)
from prime_rl.trainer.models.layers.moe import GptOssGroupedExperts, GroupedExperts, NonGatedGroupedExperts
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.utils.logger import get_logger
@@ -74,8 +78,8 @@ def _find_target_modules(model: nn.Module, target_patterns: List[str]) -> List[s
target_modules = []
for name, module in model.named_modules():
# Check if module is Linear or GroupedExperts
if not (isinstance(module, nn.Linear) or isinstance(module, GroupedExperts)):
# Check if module is Linear or one of the supported expert classes
if not isinstance(module, (nn.Linear, GroupedExperts, NonGatedGroupedExperts, GptOssGroupedExperts)):
continue
for pattern in target_patterns:
@@ -137,6 +141,10 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
config: LoRA configuration
"""
logger = get_logger()
from prime_rl.trainer.models import PreTrainedModelPrimeRL
if isinstance(model, PreTrainedModelPrimeRL):
get_multi_run_manager().register_adapter_state_dict_converter(type(model).convert_adapter_to_hf)
n_loras = get_multi_run_manager().max_runs
from torch.distributed.fsdp import FSDPModule
@@ -178,10 +186,28 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
alpha=config.alpha,
dropout=config.dropout,
)
# Handle NonGatedGroupedExperts (relu2 experts used by NemotronH's LatentMoE)
elif isinstance(base_module, NonGatedGroupedExperts):
lora_module = MultiLoRANonGatedGroupedExperts(
base_layer=base_module,
rank=config.rank,
n_adapters=n_loras,
alpha=config.alpha,
dropout=config.dropout,
)
# Handle GptOssGroupedExperts (gpt-oss fused gate_up + biases)
elif isinstance(base_module, GptOssGroupedExperts):
lora_module = MultiLoRAGptOssGroupedExperts(
base_layer=base_module,
rank=config.rank,
n_adapters=n_loras,
alpha=config.alpha,
dropout=config.dropout,
)
else:
logger.warning(
f"Module {module_name} is type {type(base_module).__name__}, "
f"expected nn.Linear or GroupedExperts. Skipping."
f"expected nn.Linear, GroupedExperts, NonGatedGroupedExperts, or GptOssGroupedExperts. Skipping."
)
continue
+207
View File
@@ -53,9 +53,23 @@ from prime_rl.trainer.weights import (
)
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.utils import format_time
from prime_rl.utils.vlm import get_language_model, get_vision_encoder, is_vlm_architecture
def pre_download_model(model_name: str) -> None:
"""Pre-download model from HuggingFace Hub so all nodes have cached weights before training."""
if Path(model_name).exists():
get_logger().info(f"Model {model_name} found at local path, skipping download")
return
get_logger().info(f"Pre-downloading model {model_name}")
t0 = time.perf_counter()
path = snapshot_download(repo_id=model_name, repo_type="model")
get_logger().debug(
f"Finished pre-downloading model {model_name} to {path} in {format_time(time.perf_counter() - t0)}"
)
def _patch_qwen3_5_moe_conversion_mapping():
"""Fix Qwen3.5 MoE conversion mapping incorrectly applying qwen2_moe expert weight splitting.
@@ -112,6 +126,173 @@ def _patch_qwen3_5_text_position_ids():
decoder_layer_cls.forward = _make_patched_forward(_original_forward)
def _patch_qwen3_5_linear_attn_varlen():
"""Thread cu_seqlens through Qwen3.5 GatedDeltaNet so packed batches don't
leak conv/SSM state across sequences.
HF's forward hardcodes seq_idx=None for causal_conv1d and omits cu_seqlens
for chunk_gated_delta_rule, so packed RL training sees ~0.23 Mismatch KL vs
vLLM (target <0.01). Mirrors the NemotronH mamba fix.
"""
import torch.nn.functional as F
from transformers.models.qwen3_5.modeling_qwen3_5 import (
Qwen3_5DecoderLayer,
Qwen3_5GatedDeltaNet,
Qwen3_5TextModel,
apply_mask_to_padding_states,
)
if getattr(Qwen3_5GatedDeltaNet.forward, "_prl_varlen_patched", False):
return
_gdn_orig = Qwen3_5GatedDeltaNet.forward
def _gdn_forward(self, hidden_states, cache_params=None, attention_mask=None, cu_seqlens=None):
if cu_seqlens is None or cache_params is not None:
return _gdn_orig(self, hidden_states, cache_params=cache_params, attention_mask=attention_mask)
hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
batch_size, seq_len, _ = hidden_states.shape
mixed_qkv = self.in_proj_qkv(hidden_states).transpose(1, 2)
z = self.in_proj_z(hidden_states).reshape(batch_size, seq_len, -1, self.head_v_dim)
b = self.in_proj_b(hidden_states)
a = self.in_proj_a(hidden_states)
if self.causal_conv1d_fn is not None:
seg_lens = cu_seqlens[1:] - cu_seqlens[:-1]
seq_idx = torch.repeat_interleave(
torch.arange(seg_lens.numel(), dtype=torch.int32, device=hidden_states.device),
seg_lens,
).unsqueeze(0)
mixed_qkv = self.causal_conv1d_fn(
x=mixed_qkv,
weight=self.conv1d.weight.squeeze(1),
bias=self.conv1d.bias,
activation=self.activation,
seq_idx=seq_idx,
)
else:
# Per-segment conv1d so the kernel-1 left pad only draws from within each sequence.
cu = cu_seqlens.tolist()
conv_outs = []
for i in range(len(cu) - 1):
s, e = cu[i], cu[i + 1]
if s == e:
continue
conv_outs.append(self.conv1d(mixed_qkv[:, :, s:e])[:, :, : e - s])
mixed_qkv = F.silu(torch.cat(conv_outs, dim=-1))
mixed_qkv = mixed_qkv.transpose(1, 2)
query, key, value = torch.split(mixed_qkv, [self.key_dim, self.key_dim, self.value_dim], dim=-1)
query = query.reshape(batch_size, seq_len, -1, self.head_k_dim)
key = key.reshape(batch_size, seq_len, -1, self.head_k_dim)
value = value.reshape(batch_size, seq_len, -1, self.head_v_dim)
beta = b.sigmoid()
g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
if self.num_v_heads // self.num_k_heads > 1:
query = query.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
core_attn_out, _ = self.chunk_gated_delta_rule(
query,
key,
value,
g=g,
beta=beta,
initial_state=None,
output_final_state=False,
use_qk_l2norm_in_kernel=True,
cu_seqlens=cu_seqlens,
)
core_attn_out = core_attn_out.reshape(-1, self.head_v_dim)
z = z.reshape(-1, self.head_v_dim)
core_attn_out = self.norm(core_attn_out, z)
core_attn_out = core_attn_out.reshape(batch_size, seq_len, -1)
return self.out_proj(core_attn_out)
_gdn_forward._prl_varlen_patched = True
Qwen3_5GatedDeltaNet.forward = _gdn_forward
_dec_orig = Qwen3_5DecoderLayer.forward
def _dec_forward(
self,
hidden_states,
position_embeddings,
attention_mask=None,
position_ids=None,
past_key_values=None,
cu_seqlens=None,
**kwargs,
):
if position_ids is not None and position_ids.ndim == 3:
position_ids = position_ids[0]
if self.layer_type != "linear_attention":
return _dec_orig(
self,
hidden_states,
position_embeddings=position_embeddings,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
**kwargs,
)
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
hidden_states = self.linear_attn(
hidden_states=hidden_states,
cache_params=past_key_values,
attention_mask=attention_mask,
cu_seqlens=cu_seqlens,
)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
return residual + hidden_states
Qwen3_5DecoderLayer.forward = _dec_forward
_text_orig = Qwen3_5TextModel.forward
def _text_forward(
self,
input_ids=None,
attention_mask=None,
position_ids=None,
past_key_values=None,
inputs_embeds=None,
use_cache=None,
**kwargs,
):
attn_impl = getattr(self.config, "_attn_implementation", None)
cu_seqlens = None
if attn_impl in ("flash_attention_2", "flash_attention_3", "fa4") and position_ids is not None:
pids = position_ids
if pids.ndim == 3:
pids = pids[0]
flat = pids.view(-1)
seqlens = torch.cat([flat[0:1], flat[:-1][(flat == 0)[1:]] + 1, flat[-1:] + 1])
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
kwargs["cu_seqlens"] = cu_seqlens
return _text_orig(
self,
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
**kwargs,
)
Qwen3_5TextModel.forward = _text_forward
# Add filter to the standard logging module for transformers.modeling_utils to supress the
# flash attention dtype warnings since FSDP is used to handle mixed precision.
transformers_modeling_utils_logger = logging.getLogger("transformers.modeling_utils")
@@ -170,6 +351,27 @@ def freeze_moe_router(model: nn.Module) -> None:
logger.info(f"Froze {num_frozen} MoE router 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()
language_model = get_language_model(model)
num_routers = 0
for layer in language_model.layers:
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
if isinstance(mlp, (MoE, LatentMoE)):
mlp.router.force_balanced = True
num_routers += 1
if num_routers == 0:
raise ValueError("No MoE routers found to force-balance. Is this a custom-impl MoE model?")
logger.warning(
f"Forced balanced routing on {num_routers} MoE layers (debug.force_balanced_routing=True). "
"Expert assignment is round-robin; gradient flow through the router is broken."
)
def is_tt_moe_model(model: nn.Module) -> bool:
return hasattr(model.config, "num_experts") or hasattr(model.config, "n_routed_experts")
@@ -224,6 +426,7 @@ def get_model(
if "Qwen3.5" in config.name or "qwen3_5" in config.name.lower():
_patch_qwen3_5_text_position_ids()
_patch_qwen3_5_moe_conversion_mapping()
_patch_qwen3_5_linear_attn_varlen()
model_config = cast(
PretrainedConfig,
@@ -262,6 +465,7 @@ def get_model(
if getattr(model_config, "model_type", "").startswith("qwen3_5_moe"):
_patch_qwen3_5_text_position_ids()
_patch_qwen3_5_moe_conversion_mapping()
_patch_qwen3_5_linear_attn_varlen()
for subconfig_key in getattr(model_config, "sub_configs", {}):
subconfig = getattr(model_config, subconfig_key, None)
if subconfig is not None and hasattr(subconfig, "use_cache"):
@@ -844,6 +1048,9 @@ def setup_model(
if config.freeze_moe_router:
freeze_moe_router(model)
if config.debug.force_balanced_routing:
apply_force_balanced_routing(model)
if parallel_dims.ep_enabled:
apply_ep(model, config, parallel_dims)
# EP replaces params with DTensors that default to requires_grad=True,
+3
View File
@@ -12,6 +12,7 @@ from prime_rl.trainer.models.afmoe import AfmoeConfig, AfmoeForCausalLM
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig, Glm4MoeForCausalLM
from prime_rl.trainer.models.glm_moe_dsa import GlmMoeDsaConfig, GlmMoeDsaForCausalLM
from prime_rl.trainer.models.gpt_oss import GptOssConfig, GptOssForCausalLM
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput, cast_float_and_contiguous
from prime_rl.trainer.models.llama import LlamaForCausalLM
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config, MiniMaxM2ForCausalLM
@@ -27,6 +28,7 @@ AutoConfig.register("minimax_m2", MiniMaxM2Config, exist_ok=True)
AutoConfig.register("nemotron_h", NemotronHConfig, exist_ok=True)
AutoConfig.register("qwen3_moe", Qwen3MoeConfig, exist_ok=True)
AutoConfig.register("qwen3_5_moe_text", Qwen3_5MoeConfig, exist_ok=True)
# GptOssConfig is just HF's class - already registered by transformers, no override needed.
_CUSTOM_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, OrderedDict())
_CUSTOM_CAUSAL_LM_MAPPING.register(LlamaConfig, LlamaForCausalLM, exist_ok=True)
@@ -37,6 +39,7 @@ _CUSTOM_CAUSAL_LM_MAPPING.register(MiniMaxM2Config, MiniMaxM2ForCausalLM, exist_
_CUSTOM_CAUSAL_LM_MAPPING.register(NemotronHConfig, NemotronHForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3MoeConfig, Qwen3MoeForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(GptOssConfig, GptOssForCausalLM, exist_ok=True)
class AutoModelForCausalLMPrimeRL(_BaseAutoModelClass):
+15
View File
@@ -103,6 +103,21 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
"""
raise NotImplementedError(f"convert_layer_to_prime is not implemented for {cls.__name__}")
@classmethod
def convert_adapter_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
"""
Convert a LoRA adapter state dict from PrimeRL training format to HuggingFace format.
Unlike convert_to_hf, this operates on a partial state dict containing only LoRA
adapter parameters (e.g. `model.layers.N.<submodule>.<proj>.lora_A.weight`). Models
whose HF naming differs from PrimeRL naming at the submodule level (e.g. NemotronH's
unified `mixer` attribute) should override this to perform the rename.
Implementations may mutate state_dict in-place or return a new dict; callers must
use the returned value. Default implementation is a no-op.
"""
return state_dict
@classmethod
def convert_layer_to_vllm_kernel(
cls,
@@ -278,6 +278,10 @@ class Glm4MoeForCausalLM(Glm4MoePreTrainedModel, GenerationMixin):
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
r"""
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
compatibility — prime-rl asserts `use_cache is None` since training does not
perform autoregressive decoding, so this argument is unused.
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels used by PrimeRL's wrapped LM head to optionally compute per-token logprobs/entropy.
If not provided, the wrapped LM head returns logits only.
@@ -307,6 +307,10 @@ class GlmMoeDsaForCausalLM(GlmMoeDsaPreTrainedModel, GenerationMixin):
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
r"""
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
compatibility — prime-rl asserts `use_cache is None` since training does not
perform autoregressive decoding, so this argument is unused.
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels used by PrimeRL's wrapped LM head to optionally compute per-token logprobs/entropy.
temperature (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
@@ -0,0 +1,13 @@
from prime_rl.trainer.models.gpt_oss.configuration_gpt_oss import GptOssConfig
from prime_rl.trainer.models.gpt_oss.modeling_gpt_oss import (
GptOssForCausalLM,
GptOssModel,
GptOssPreTrainedModel,
)
__all__ = [
"GptOssConfig",
"GptOssForCausalLM",
"GptOssModel",
"GptOssPreTrainedModel",
]
@@ -0,0 +1,6 @@
# Re-export HF's GptOssConfig so the parameter naming and rope/sliding-window defaults
# stay in sync with upstream. We don't need to subclass it: the only PrimeRL-specific
# behavior lives in modeling_gpt_oss.py (custom MoE for LoRA detection).
from transformers.models.gpt_oss.configuration_gpt_oss import GptOssConfig
__all__ = ["GptOssConfig"]
@@ -0,0 +1,28 @@
"""State-dict conversion for GPT-OSS.
The custom prime-rl GPT-OSS implementation mirrors HuggingFace's parameter naming
exactly (gate_up_proj/gate_up_proj_bias/down_proj/down_proj_bias plus router.weight
and router.bias as nn.Parameters). So loading the unsloth BF16 checkpoint requires
no key conversion - HF and prime formats are identical for this model.
"""
from torch import Tensor
def is_hf_state_dict(state_dict: dict[str, Tensor]) -> bool:
return any("mlp.experts.gate_up_proj" in name for name in state_dict.keys())
def is_prime_state_dict(state_dict: dict[str, Tensor]) -> bool:
# Prime format equals HF format for GPT-OSS, so we never claim to be a separate
# prime format - this disables the auto-conversion path in load_dcp_from_hf and
# lets DCP load HF safetensors directly.
return False
def convert_to_hf(state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
return state_dict
def convert_to_prime(state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
return state_dict
@@ -0,0 +1,349 @@
# GPT-OSS model with PrimeRL custom MoE.
#
# This file mirrors HuggingFace's modeling_gpt_oss.py but swaps the experts module for
# `GptOssGroupedExperts` so the LoRA detection logic in `prime_rl/trainer/lora.py` can
# find and adapt the expert weights. Attention, rotary embedding, and RMSNorm are reused
# from HF as-is - they correctly handle attention sinks and gpt-oss's split-rotate RoPE.
from typing import Union
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from transformers.cache_utils import Cache
from transformers.generation import GenerationMixin
from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import MoeModelOutputWithPast
from transformers.models.gpt_oss.modeling_gpt_oss import (
GptOssAttention,
GptOssRMSNorm,
GptOssRotaryEmbedding,
)
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.gpt_oss.configuration_gpt_oss import GptOssConfig
from prime_rl.trainer.models.gpt_oss.converting_gpt_oss import (
convert_to_hf,
convert_to_prime,
is_hf_state_dict,
is_prime_state_dict,
)
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.moe import GptOssGroupedExperts
class GptOssTopKRouter(nn.Module):
"""Token-choice top-k router matching HF's GptOssTopKRouter parameter naming.
Stores `weight` (num_experts, hidden_size) and `bias` (num_experts) as raw nn.Parameters
so the unsloth BF16 checkpoint loads with no key conversion. Returns the same outputs as
`TokenChoiceTopKRouter` so the surrounding MoE plumbing matches the rest of the repo.
"""
def __init__(self, config: GptOssConfig):
super().__init__()
self.num_experts = config.num_local_experts
self.top_k = config.num_experts_per_tok
self.hidden_size = config.hidden_size
self.weight = nn.Parameter(torch.empty(self.num_experts, self.hidden_size))
self.bias = nn.Parameter(torch.empty(self.num_experts))
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""x: (T, hidden). Returns (top_scores, top_indices, num_tokens_per_expert).
Matches HF's softmax-after-topk semantics: we softmax the top-k logits only,
not the full distribution.
"""
logits = F.linear(x, self.weight, self.bias) # (T, num_experts)
top_logits, top_indices = torch.topk(logits, self.top_k, dim=-1)
top_scores = F.softmax(top_logits, dim=-1, dtype=top_logits.dtype)
num_tokens_per_expert = torch.histc(
top_indices.reshape(-1).float(),
bins=self.num_experts,
min=0,
max=self.num_experts,
)
return top_scores, top_indices, num_tokens_per_expert
def init_weights(self, init_std: float):
nn.init.trunc_normal_(self.weight, mean=0.0, std=init_std)
nn.init.zeros_(self.bias)
class GptOssMoE(nn.Module):
"""GPT-OSS sparse MLP: top-k router + grouped experts with biases.
Wraps `GptOssGroupedExperts` (which expects pre-permuted tokens + num_tokens_per_expert)
with the standard MoE permute/unpermute pipeline. Routing weights are applied AFTER
the expert computation, matching HF's `routing_weights[token_idx, top_k_pos]` index_add.
"""
def __init__(self, config: GptOssConfig):
super().__init__()
self.num_experts = config.num_local_experts
self.top_k = config.num_experts_per_tok
self.router = GptOssTopKRouter(config)
self.experts = GptOssGroupedExperts(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
num_experts=self.num_experts,
use_grouped_mm=getattr(config, "use_grouped_mm", True),
)
def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
bs, slen, dim = hidden_states.shape
x = hidden_states.reshape(-1, dim) # (T, dim)
top_scores, top_indices, num_tokens_per_expert = self.router(x)
# top_scores, top_indices: (T, top_k)
# Sort tokens by expert. Each token contributes top_k entries (one per chosen expert).
flat_expert_indices = top_indices.reshape(-1) # (T*top_k,)
sorted_perm = torch.argsort(flat_expert_indices, stable=True) # (T*top_k,)
# token id of each (token, k) entry, in expert-sorted order
token_indices_experts_sorted = sorted_perm // self.top_k
# routing weight for each (token, k) entry, in expert-sorted order
top_scores_experts_sorted = top_scores.reshape(-1)[sorted_perm]
# Gather inputs for each expert in expert-sorted order
gather_indices = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
routed_input = torch.gather(x, dim=0, index=gather_indices) # (T*top_k, dim)
routed_output = self.experts(routed_input, num_tokens_per_expert) # (T*top_k, dim)
# Apply routing weights post-experts (HF: weighted_output = out * routing_weights)
routed_output = (routed_output.float() * top_scores_experts_sorted.reshape(-1, 1)).to(routed_output.dtype)
# Scatter-add back to original token positions
out = torch.zeros_like(x)
scatter_indices = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
out = out.scatter_add(dim=0, index=scatter_indices, src=routed_output)
out = out.reshape(bs, slen, dim)
return out, top_scores # router_scores returned only for compatibility; trainer ignores
class GptOssDecoderLayer(GradientCheckpointingLayer):
def __init__(self, config: GptOssConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = GptOssAttention(config=config, layer_idx=layer_idx)
self.mlp = GptOssMoE(config)
self.input_layernorm = GptOssRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = GptOssRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor | None = None,
position_ids: torch.LongTensor | None = None,
past_key_values: Cache | None = None,
use_cache: bool | None = False,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
**kwargs: Unpack[TransformersKwargs],
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states, _ = self.mlp(hidden_states)
hidden_states = residual + hidden_states
return hidden_states
@auto_docstring
class GptOssPreTrainedModel(PreTrainedModelPrimeRL):
config: GptOssConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["GptOssDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = False
_supports_flex_attn = True
_can_compile_fullgraph = False
_supports_attention_backend = True
_keep_in_fp32_modules = ["post_attention_layernorm", "input_layernorm", "norm"]
_compatible_flash_implementations = ["kernels-community/vllm-flash-attn3", "flash_attention_4"]
_can_record_outputs = {"hidden_states": GptOssDecoderLayer}
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return is_hf_state_dict(state_dict)
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return is_prime_state_dict(state_dict)
@classmethod
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
return convert_to_hf(state_dict)
@classmethod
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
return convert_to_prime(state_dict)
@auto_docstring
class GptOssModel(GptOssPreTrainedModel):
_no_split_modules = ["GptOssDecoderLayer"]
def __init__(self, config: GptOssConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.layers = nn.ModuleList(
[GptOssDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.norm = GptOssRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.rotary_emb = GptOssRotaryEmbedding(config=config)
self.gradient_checkpointing = False
self.post_init()
@auto_docstring
def forward(
self,
input_ids: torch.LongTensor | None = None,
attention_mask: torch.Tensor | None = None,
position_ids: torch.LongTensor | None = None,
past_key_values: Cache | None = None,
inputs_embeds: torch.FloatTensor | None = None,
use_cache: bool | None = None,
**kwargs: Unpack[TransformersKwargs],
) -> MoeModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
if not isinstance(causal_mask_mapping := attention_mask, dict):
mask_kwargs = {
"config": self.config,
"inputs_embeds": inputs_embeds,
"attention_mask": attention_mask,
"past_key_values": past_key_values,
"position_ids": position_ids,
}
causal_mask_mapping = {
"full_attention": create_causal_mask(**mask_kwargs),
"sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
}
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for i, decoder_layer in enumerate(self.layers):
hidden_states = decoder_layer(
hidden_states,
attention_mask=causal_mask_mapping[self.config.layer_types[i]],
position_embeddings=position_embeddings,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
**kwargs,
)
hidden_states = self.norm(hidden_states)
return MoeModelOutputWithPast(last_hidden_state=hidden_states, past_key_values=past_key_values)
@auto_docstring
class GptOssForCausalLM(GptOssPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_gather_output"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config: GptOssConfig):
super().__init__(config)
self.model = GptOssModel(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.num_experts = config.num_local_experts
self.num_experts_per_tok = config.num_experts_per_tok
self.post_init()
def set_decoder(self, decoder):
self.model = decoder
def get_decoder(self):
return self.model
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: torch.LongTensor | None = None,
attention_mask: torch.Tensor | None = None,
position_ids: torch.LongTensor | None = None,
past_key_values: Cache | None = None,
inputs_embeds: torch.FloatTensor | None = None,
labels: torch.LongTensor | None = None,
use_cache: bool | None = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
temperature: torch.Tensor | None = None,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
assert use_cache is None or not use_cache, "use_cache is not supported for custom GPT-OSS"
assert past_key_values is None, "past_key_values is not supported for custom GPT-OSS"
outputs: MoeModelOutputWithPast = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
**kwargs,
)
hidden_states = outputs.last_hidden_state
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
return self.lm_head(
hidden_states[:, slice_indices, :],
labels[:, slice_indices] if labels is not None else None,
temperature=temperature,
)
def init_buffers_post_meta(self):
buffer_names = [name for name, _ in self.named_buffers()]
if "model.rotary_emb.inv_freq" in buffer_names:
rotary_emb = self.model.rotary_emb
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
rope_init_fn = (
ROPE_INIT_FUNCTIONS[rotary_emb.rope_type]
if rotary_emb.rope_type != "default"
else rotary_emb.compute_default_rope_parameters
)
inv_freq, rotary_emb.attention_scaling = rope_init_fn(rotary_emb.config, rotary_emb.inv_freq.device)
rotary_emb.inv_freq.copy_(inv_freq)
if "model.rotary_emb.original_inv_freq" in buffer_names:
rotary_emb.original_inv_freq.copy_(inv_freq)
__all__ = [
"GptOssForCausalLM",
"GptOssModel",
"GptOssPreTrainedModel",
]
+15 -7
View File
@@ -93,14 +93,18 @@ class FlashAttention(nn.Module):
def _compute_attention(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, cu_seqlens, max_seqlen):
"""Run the flash attention kernel. q/k/v are [total_tokens, heads, dim]."""
args = [q, k, v, cu_seqlens, cu_seqlens]
if self._flash_attn_version != 4:
args.extend([max_seqlen, max_seqlen])
kwargs: dict = {"causal": True}
sliding_window = getattr(self, "sliding_window", None)
if sliding_window is not None:
kwargs["window_size"] = (sliding_window - 1, 0)
out = self._flash_attn_call(*args, **kwargs)
if self._flash_attn_version == 4:
# FA4's flash_attn_varlen_func has qv as the 4th positional arg,
# so cu_seqlens must be passed as keyword args to avoid misalignment.
kwargs["cu_seqlens_q"] = cu_seqlens
kwargs["cu_seqlens_k"] = cu_seqlens
out = self._flash_attn_call(q, k, v, **kwargs)
else:
out = self._flash_attn_call(q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen, **kwargs)
if isinstance(out, tuple):
out = out[0]
return out
@@ -291,10 +295,14 @@ def substitute_ring_attn(
"""Patch _compute_attention on FlashAttention variants to use ring attention."""
from ring_flash_attn import llama3_flash_attn_varlen_func
from .ring_attn import ring_fa3_varlen_func
from .ring_attn import ring_fa3_varlen_func, ring_fa4_varlen_func
use_fa3 = attn_impl == "flash_attention_3"
ring_func = ring_fa3_varlen_func if use_fa3 else llama3_flash_attn_varlen_func
if attn_impl == "fa4":
ring_func = ring_fa4_varlen_func
elif attn_impl == "flash_attention_3":
ring_func = ring_fa3_varlen_func
else:
ring_func = llama3_flash_attn_varlen_func
def _ring_compute_attention(self, q, k, v, cu_seqlens, max_seqlen):
from ring_flash_attn.adapters.hf_adapter import DATA_PARAMS
@@ -0,0 +1,240 @@
"""All-to-all context parallelism for Mamba-2 SSM layers.
Transposes between sequence-parallel and head-parallel layouts so that each
CP rank processes the full sequence on a subset of heads, then transposes
back. This avoids materializing the full [S, full_heads] tensor on any GPU.
Communication pattern per Mamba layer:
1. in_proj (token-parallel, no comm)
2. all-to-all: [B, S/cp, D] -> [B, S, D/cp] (seq-to-head)
3. conv1d + SSM on full sequence, local heads
4. all-to-all: [B, S, D/cp] -> [B, S/cp, D] (head-to-seq)
5. out_proj (token-parallel, no comm)
"""
from __future__ import annotations
import torch
import torch.distributed as dist
class _SeqToHeadParallel(torch.autograd.Function):
"""[B, S/cp, D] -> [B, S, D/cp] via all-to-all."""
@staticmethod
def forward(ctx, x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
ctx.cp_group = cp_group
ctx.cp_size = cp_size
return _all_to_all_seq_to_head(x, cp_group, cp_size)
@staticmethod
def backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None]:
return _all_to_all_head_to_seq(grad_output, ctx.cp_group, ctx.cp_size), None, None
class _HeadToSeqParallel(torch.autograd.Function):
"""[B, S, D/cp] -> [B, S/cp, D] via all-to-all."""
@staticmethod
def forward(ctx, x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
ctx.cp_group = cp_group
ctx.cp_size = cp_size
return _all_to_all_head_to_seq(x, cp_group, cp_size)
@staticmethod
def backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None]:
return _all_to_all_seq_to_head(grad_output, ctx.cp_group, ctx.cp_size), None, None
def _all_to_all_seq_to_head(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
"""Transpose [B, S_local, D] -> [B, S_global, D_local] via all-to-all.
Each rank sends its S_local tokens split into cp_size chunks along D,
and receives one D_local chunk from each of the cp_size ranks.
"""
B, S_local, D = x.shape
D_local = D // cp_size
# Split D into cp_size chunks, put cp dim first for all_to_all scatter
# [B, S_local, D] -> [B, S_local, cp, D_local] -> [cp, B, S_local, D_local]
x = x.reshape(B, S_local, cp_size, D_local).permute(2, 0, 1, 3).contiguous()
output = torch.empty_like(x)
dist.all_to_all_single(output, x, group=cp_group)
# output[i] = data from rank i (its S_local tokens, our D_local slice)
# [cp, B, S_local, D_local] -> [B, cp, S_local, D_local] -> [B, cp*S_local, D_local]
return output.permute(1, 0, 2, 3).reshape(B, cp_size * S_local, D_local).contiguous()
def _all_to_all_head_to_seq(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
"""Transpose [B, S_global, D_local] -> [B, S_local, D] via all-to-all.
Inverse of _all_to_all_seq_to_head.
"""
B, S_global, D_local = x.shape
S_local = S_global // cp_size
# Split S_global into cp_size chunks (one per rank), put cp dim first for scatter
# [B, S_global, D_local] -> [B, cp, S_local, D_local] -> [cp, B, S_local, D_local]
x = x.reshape(B, cp_size, S_local, D_local).permute(1, 0, 2, 3).contiguous()
output = torch.empty_like(x)
dist.all_to_all_single(output, x, group=cp_group)
# Each rank now has cp chunks of [B, S_local, D_local] — one D_local slice from each rank
# [cp, B, S_local, D_local] -> [B, S_local, cp, D_local] -> [B, S_local, D]
return output.permute(1, 2, 0, 3).reshape(B, S_local, cp_size * D_local).contiguous()
def seq_to_head_parallel(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
"""[B, S/cp, D] -> [B, S, D/cp] with correct backward."""
return _SeqToHeadParallel.apply(x, cp_group, cp_size)
def head_to_seq_parallel(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
"""[B, S, D/cp] -> [B, S/cp, D] with correct backward."""
return _HeadToSeqParallel.apply(x, cp_group, cp_size)
def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessGroup, cp_rank: int, cp_size: int):
"""CP-aware Mamba-2 forward: in_proj -> all-to-all -> conv+SSM(local heads) -> all-to-all -> out_proj.
Replaces the mixer's cuda_kernels_forward when CP > 1. Parameters are
sliced at runtime so FSDP / checkpoint shapes are unchanged.
"""
from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined
batch_size, seq_len, _ = hidden_states.shape # seq_len = S/cp here
# ── 1. in_proj (token-parallel, no communication needed) ──
projected_states = mixer.in_proj(hidden_states)
A = -torch.exp(mixer.A_log.float())
gate, hidden_states_B_C, time_step = torch.split(
projected_states,
[mixer.intermediate_size, mixer.conv_dim, mixer.num_heads],
dim=-1,
)
# ── 2. All-to-all: seq-parallel -> head-parallel ──
# gate: [B, S/cp, nheads * hdim] -> [B, S, (nheads/cp) * hdim]
# hidden_states_B_C: [B, S/cp, nheads*hdim + 2*ngroups*dstate] -> [B, S, ...]
# time_step: [B, S/cp, nheads] -> [B, S, nheads/cp]
gate = seq_to_head_parallel(gate, cp_group, cp_size)
time_step = seq_to_head_parallel(time_step, cp_group, cp_size)
# hidden_states_B_C needs special handling: x part shards by heads, B/C parts shard by groups
# conv_dim = intermediate_size + 2 * ngroups * dstate
groups_time_state_size = mixer.n_groups * mixer.ssm_state_size
x_part, B_part, C_part = torch.split(
hidden_states_B_C,
[mixer.intermediate_size, groups_time_state_size, groups_time_state_size],
dim=-1,
)
x_part = seq_to_head_parallel(x_part, cp_group, cp_size)
B_part = seq_to_head_parallel(B_part, cp_group, cp_size)
C_part = seq_to_head_parallel(C_part, cp_group, cp_size)
hidden_states_B_C = torch.cat([x_part, B_part, C_part], dim=-1)
full_seq_len = hidden_states_B_C.shape[1] # S (full sequence)
# ── 3. Local head dimensions ──
local_num_heads = mixer.num_heads // cp_size
local_intermediate_size = local_num_heads * mixer.head_dim
local_n_groups = mixer.n_groups // cp_size
# Slice parameters for local heads
head_start = cp_rank * local_num_heads
head_end = head_start + local_num_heads
local_A = A[head_start:head_end]
local_D = mixer.D[head_start:head_end]
local_dt_bias = mixer.dt_bias[head_start:head_end]
# Slice conv1d weight/bias for local channels
# conv1d channels = intermediate_size + 2 * ngroups * dstate (same as conv_dim)
# After all-to-all, we have local channels: local_intermediate + 2 * local_ngroups * dstate
local_conv_dim = local_intermediate_size + 2 * local_n_groups * mixer.ssm_state_size
conv_x_start = cp_rank * local_intermediate_size
conv_x_end = conv_x_start + local_intermediate_size
conv_b_start = mixer.intermediate_size + cp_rank * local_n_groups * mixer.ssm_state_size
conv_b_end = conv_b_start + local_n_groups * mixer.ssm_state_size
conv_c_start = mixer.intermediate_size + groups_time_state_size + cp_rank * local_n_groups * mixer.ssm_state_size
conv_c_end = conv_c_start + local_n_groups * mixer.ssm_state_size
conv_indices = torch.cat(
[
torch.arange(conv_x_start, conv_x_end, device=mixer.conv1d.weight.device),
torch.arange(conv_b_start, conv_b_end, device=mixer.conv1d.weight.device),
torch.arange(conv_c_start, conv_c_end, device=mixer.conv1d.weight.device),
]
)
local_conv_weight = mixer.conv1d.weight[conv_indices]
local_conv_bias = mixer.conv1d.bias[conv_indices] if mixer.conv1d.bias is not None else None
# ── 4. Conv1d on full sequence, local heads ──
hidden_states_B_C = torch.nn.functional.silu(
torch.nn.functional.conv1d(
hidden_states_B_C.transpose(1, 2),
local_conv_weight,
local_conv_bias,
groups=local_conv_dim,
padding=mixer.conv1d.weight.shape[2] - 1,
).transpose(1, 2)[:, :full_seq_len]
)
local_groups_time_state_size = local_n_groups * mixer.ssm_state_size
hidden_states_local, B_local, C_local = torch.split(
hidden_states_B_C,
[local_intermediate_size, local_groups_time_state_size, local_groups_time_state_size],
dim=-1,
)
# ── 5. SSM scan on full sequence, local heads ──
dt_limit_kwargs = {} if mixer.time_step_limit is None else {"dt_limit": mixer.time_step_limit}
scan_output, _ = mamba_chunk_scan_combined(
hidden_states_local.view(batch_size, full_seq_len, local_num_heads, mixer.head_dim),
time_step,
local_A,
B_local.view(batch_size, full_seq_len, local_n_groups, -1),
C_local.view(batch_size, full_seq_len, local_n_groups, -1),
chunk_size=mixer.chunk_size,
D=local_D,
z=None,
seq_idx=None,
return_final_states=True,
dt_bias=local_dt_bias,
dt_softplus=True,
**dt_limit_kwargs,
)
scan_output = scan_output.view(batch_size, full_seq_len, local_intermediate_size)
# ── 6. Gated RMSNorm with local weights ──
# Zamba2RMSNormGated normalizes within groups of size `group_size`.
# In head-parallel mode, we have local_intermediate_size features.
# The group_size stays the same, but group_count is reduced.
local_norm_weight = mixer.norm.weight[cp_rank * local_intermediate_size : (cp_rank + 1) * local_intermediate_size]
scan_output = _gated_rms_norm(
scan_output, gate, local_norm_weight, mixer.norm.variance_epsilon, mixer.norm.group_size
)
# ── 7. All-to-all: head-parallel -> seq-parallel ──
scan_output = head_to_seq_parallel(scan_output, cp_group, cp_size)
# ── 8. out_proj (token-parallel, no communication needed) ──
return mixer.out_proj(scan_output)
def _gated_rms_norm(
x: torch.Tensor, gate: torch.Tensor, weight: torch.Tensor, eps: float, group_size: int
) -> torch.Tensor:
"""Gated RMSNorm matching Zamba2RMSNormGated: gate -> group-wise RMSNorm -> weight."""
input_dtype = x.dtype
x = x.to(torch.float32)
if gate is not None:
x = x * torch.nn.functional.silu(gate.to(torch.float32))
*prefix_dims, last_dim = x.shape
group_count = last_dim // group_size
x_grouped = x.view(*prefix_dims, group_count, group_size)
variance = x_grouped.pow(2).mean(-1, keepdim=True)
x_grouped = x_grouped * torch.rsqrt(variance + eps)
x = x_grouped.view(*prefix_dims, last_dim)
return (weight * x).to(input_dtype)
@@ -6,12 +6,13 @@ from prime_rl.trainer.models.layers.lora.base import (
set_multilora_scaling,
)
from prime_rl.trainer.models.layers.lora.multi_linear import MultiLoRALinear
from prime_rl.trainer.models.layers.lora.multi_moe import MultiLoRAGroupedExperts
from prime_rl.trainer.models.layers.lora.multi_moe import MultiLoRAGroupedExperts, MultiLoRANonGatedGroupedExperts
__all__ = [
"MultiLoRAModule",
"MultiLoRALinear",
"MultiLoRAGroupedExperts",
"MultiLoRANonGatedGroupedExperts",
"set_lora_num_tokens",
"get_lora_num_tokens",
"set_multilora_scaling",
@@ -6,7 +6,14 @@ from torch import nn
from torch.distributed.tensor import DTensor
from prime_rl.trainer.models.layers.lora.base import MultiLoRAModule, get_lora_num_tokens, get_multilora_scaling
from prime_rl.trainer.models.layers.moe import GroupedExperts
from prime_rl.trainer.models.layers.moe import (
GptOssGroupedExperts,
GroupedExperts,
NonGatedGroupedExperts,
_broadcast_expert_bias,
_gpt_oss_apply_gate,
relu2,
)
def _run_lora_grouped_mm(
@@ -483,3 +490,585 @@ class MultiLoRAGroupedExperts(MultiLoRAModule):
f"alpha={self.alpha}, dropout={self.lora_dropout}, "
f"use_grouped_mm={self.use_grouped_mm})"
)
class MultiLoRANonGatedGroupedExperts(MultiLoRAModule):
"""
NonGatedGroupedExperts + multi-LoRA with grouped GEMM.
Adapts the two projections (w1: up, w2: down) of NemotronH-style relu2 experts.
"""
def __init__(
self,
base_layer: NonGatedGroupedExperts,
rank: int,
n_adapters: int,
alpha: float = 32.0,
dropout: float = 0.0,
use_grouped_mm: bool = True,
):
super().__init__(base_layer)
if rank <= 0 or n_adapters <= 0:
raise ValueError("rank and n_adapters must be > 0")
self.num_experts = base_layer.num_experts
# w1 shape: [num_experts, intermediate_dim, input_dim]
self.hidden_dim = base_layer.w1.shape[1]
self.dim = base_layer.w1.shape[2]
if rank % 8 != 0 or self.dim % 8 != 0 or self.hidden_dim % 8 != 0:
use_grouped_mm = False
self.rank = rank
self.n_adapters = n_adapters
self.alpha = alpha
self.lora_dropout = nn.Dropout(dropout) if dropout > 0.0 else nn.Identity()
self.use_grouped_mm = use_grouped_mm
self._lora_num_tokens = get_lora_num_tokens()
self._scaling_factors = get_multilora_scaling()
# w1 (up: dim -> hidden_dim)
self.w1_lora_A = nn.ParameterList(
[
nn.Parameter(
torch.empty(
self.num_experts,
rank,
self.dim,
device=base_layer.w1.device,
dtype=base_layer.w1.dtype,
)
)
for _ in range(n_adapters)
]
)
self.w1_lora_B = nn.ParameterList(
[
nn.Parameter(
torch.empty(
self.num_experts,
self.hidden_dim,
rank,
device=base_layer.w1.device,
dtype=base_layer.w1.dtype,
)
)
for _ in range(n_adapters)
]
)
# w2 (down: hidden_dim -> dim)
self.w2_lora_A = nn.ParameterList(
[
nn.Parameter(
torch.empty(
self.num_experts,
rank,
self.hidden_dim,
device=base_layer.w2.device,
dtype=base_layer.w2.dtype,
)
)
for _ in range(n_adapters)
]
)
self.w2_lora_B = nn.ParameterList(
[
nn.Parameter(
torch.empty(
self.num_experts,
self.dim,
rank,
device=base_layer.w2.device,
dtype=base_layer.w2.dtype,
)
)
for _ in range(n_adapters)
]
)
self.reset_parameters()
def reset_parameters(self, index: int | None = None) -> None:
if index is None:
for i in range(self.n_adapters):
self.reset_parameters(i)
else:
nn.init.kaiming_uniform_(self.w1_lora_A[index], a=math.sqrt(5))
nn.init.zeros_(self.w1_lora_B[index])
nn.init.kaiming_uniform_(self.w2_lora_A[index], a=math.sqrt(5))
nn.init.zeros_(self.w2_lora_B[index])
def named_parameters_for_adapter(self, idx: int) -> list[tuple[str, nn.Parameter]]:
return [
("w1_lora_A", self.w1_lora_A[idx]),
("w1_lora_B", self.w1_lora_B[idx]),
("w2_lora_A", self.w2_lora_A[idx]),
("w2_lora_B", self.w2_lora_B[idx]),
]
def get_lora_param_counts(self) -> tuple[int, int]:
adapter_params = (
self.w1_lora_A[0].numel()
+ self.w1_lora_B[0].numel()
+ self.w2_lora_A[0].numel()
+ self.w2_lora_B[0].numel()
)
adapted_params = self.base_layer.w1.numel() + self.base_layer.w2.numel()
return adapter_params, adapted_params
def state_dict_for_adapter(self, idx: int) -> dict[str, torch.Tensor]:
state_dict = {}
detached_w1_lora_a = self.w1_lora_A[idx].detach()
detached_w1_lora_b = self.w1_lora_B[idx].detach()
detached_w2_lora_a = self.w2_lora_A[idx].detach()
detached_w2_lora_b = self.w2_lora_B[idx].detach()
if isinstance(detached_w1_lora_a, DTensor):
detached_w1_lora_a = detached_w1_lora_a.full_tensor()
detached_w1_lora_b = detached_w1_lora_b.full_tensor()
detached_w2_lora_a = detached_w2_lora_a.full_tensor()
detached_w2_lora_b = detached_w2_lora_b.full_tensor()
for expert_id in range(self.num_experts):
state_dict[f"{expert_id}.up_proj.lora_A.weight"] = detached_w1_lora_a[expert_id].clone()
state_dict[f"{expert_id}.up_proj.lora_B.weight"] = detached_w1_lora_b[expert_id].clone()
state_dict[f"{expert_id}.down_proj.lora_A.weight"] = detached_w2_lora_a[expert_id].clone()
state_dict[f"{expert_id}.down_proj.lora_B.weight"] = detached_w2_lora_b[expert_id].clone()
return state_dict
def forward(self, x: torch.Tensor, num_tokens_per_expert: torch.Tensor) -> torch.Tensor:
adapter_idx = self._lora_num_tokens.argmax().item()
w1_lora_a = self.w1_lora_A[adapter_idx]
w1_lora_b = self.w1_lora_B[adapter_idx]
w2_lora_a = self.w2_lora_A[adapter_idx]
w2_lora_b = self.w2_lora_B[adapter_idx]
scaling = self._scaling_factors[adapter_idx].item()
base_w1 = self.base_layer.w1
base_w2 = self.base_layer.w2
permuted_indices = None
if isinstance(base_w1, DTensor):
base_w1 = base_w1.to_local()
base_w2 = base_w2.to_local()
w1_lora_a = w1_lora_a.to_local()
w1_lora_b = w1_lora_b.to_local()
w2_lora_a = w2_lora_a.to_local()
w2_lora_b = w2_lora_b.to_local()
if getattr(self.base_layer, "ep_comm_backend", "torch") != "deepep":
from torchtitan.distributed.expert_parallel import TOKEN_GROUP_ALIGN_SIZE_M
from torchtitan.experiments.kernels.moe.indices import generate_permute_indices
experts_per_ep_rank = base_w1.shape[0]
num_ep_ranks = num_tokens_per_expert.shape[0] // experts_per_ep_rank
with torch.no_grad():
permuted_indices, num_tokens_per_expert, _ = generate_permute_indices(
num_tokens_per_expert,
experts_per_ep_rank,
num_ep_ranks,
x.shape[0] + experts_per_ep_rank * TOKEN_GROUP_ALIGN_SIZE_M,
TOKEN_GROUP_ALIGN_SIZE_M,
)
x = torch.vstack((x, x.new_zeros((x.shape[-1]))))
input_shape = x.shape
x = x[permuted_indices, :]
offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32)
lora_x = self.lora_dropout(x)
if self.use_grouped_mm:
# Up (w1)
h_base = torch._grouped_mm(x.bfloat16(), base_w1.bfloat16().transpose(-2, -1), offs=offsets)
w1_lora_out = _run_lora_grouped_mm(lora_x, w1_lora_a, w1_lora_b, offsets)
h = relu2(h_base + scaling * w1_lora_out.bfloat16())
# Down (w2)
lora_h = self.lora_dropout(h)
out_base = torch._grouped_mm(h, base_w2.bfloat16().transpose(-2, -1), offs=offsets)
w2_lora_out = _run_lora_grouped_mm(lora_h, w2_lora_a, w2_lora_b, offsets)
out = out_base + scaling * w2_lora_out.bfloat16()
out = out.type_as(x)
else:
out = self._forward_for_loop(
x,
num_tokens_per_expert,
w1_lora_a,
w1_lora_b,
w2_lora_a,
w2_lora_b,
base_w1,
base_w2,
scaling,
)
if permuted_indices is not None:
if out.shape[0] < len(permuted_indices):
num_padding = len(permuted_indices) - out.shape[0]
out = torch.vstack((out, out.new_zeros((num_padding, out.shape[-1]))))
out_unpermuted = out.new_zeros(input_shape)
out_unpermuted[permuted_indices, :] = out
out = out_unpermuted[:-1]
return out
def _forward_for_loop(
self,
x: torch.Tensor,
num_tokens_per_expert: torch.Tensor,
w1_lora_a: torch.Tensor,
w1_lora_b: torch.Tensor,
w2_lora_a: torch.Tensor,
w2_lora_b: torch.Tensor,
base_w1: torch.Tensor,
base_w2: torch.Tensor,
scaling: float,
) -> torch.Tensor:
num_tokens_per_expert_list = num_tokens_per_expert.tolist()
out_splits = []
start = 0
for expert_idx, num_tokens in enumerate(num_tokens_per_expert_list):
if num_tokens == 0:
continue
end = start + num_tokens
x_expert = x[start:end]
x_expert_lora = self.lora_dropout(x_expert)
h_base = torch.matmul(x_expert, base_w1[expert_idx].transpose(-2, -1))
w1_lora_tmp = torch.matmul(x_expert_lora, w1_lora_a[expert_idx].transpose(-2, -1))
w1_lora_out = torch.matmul(w1_lora_tmp, w1_lora_b[expert_idx].transpose(-2, -1))
h = relu2(h_base + scaling * w1_lora_out)
h_lora = self.lora_dropout(h)
out_base = torch.matmul(h, base_w2[expert_idx].transpose(-2, -1))
w2_lora_tmp = torch.matmul(h_lora, w2_lora_a[expert_idx].transpose(-2, -1))
w2_lora_out = torch.matmul(w2_lora_tmp, w2_lora_b[expert_idx].transpose(-2, -1))
out = out_base + scaling * w2_lora_out
out_splits.append(out)
start = end
return torch.cat(out_splits, dim=0)
def __repr__(self) -> str:
return (
f"{self.__class__.__name__}(base={self.base_layer}, rank={self.rank}, "
f"n_adapters={self.n_adapters}, num_experts={self.num_experts}, "
f"alpha={self.alpha}, dropout={self.lora_dropout}, "
f"use_grouped_mm={self.use_grouped_mm})"
)
class MultiLoRAGptOssGroupedExperts(MultiLoRAModule):
"""
GptOssGroupedExperts + multi-LoRA.
Adapts the two projections of GPT-OSS experts: the fused gate_up projection
(hidden_size -> 2*intermediate_size) and the down projection (intermediate_size -> hidden_size).
"""
def __init__(
self,
base_layer: GptOssGroupedExperts,
rank: int,
n_adapters: int,
alpha: float = 32.0,
dropout: float = 0.0,
use_grouped_mm: bool = True,
):
super().__init__(base_layer)
if rank <= 0 or n_adapters <= 0:
raise ValueError("rank and n_adapters must be > 0")
self.num_experts = base_layer.num_experts
self.hidden_size = base_layer.hidden_size
self.intermediate_size = base_layer.intermediate_size
self.gate_up_out = 2 * self.intermediate_size
if rank % 8 != 0 or self.hidden_size % 8 != 0 or self.intermediate_size % 8 != 0:
use_grouped_mm = False
self.rank = rank
self.n_adapters = n_adapters
self.alpha = alpha
self.lora_dropout = nn.Dropout(dropout) if dropout > 0.0 else nn.Identity()
self.use_grouped_mm = use_grouped_mm
self._lora_num_tokens = get_lora_num_tokens()
self._scaling_factors = get_multilora_scaling()
self.gate_up_lora_A = nn.ParameterList(
[
nn.Parameter(
torch.empty(
self.num_experts,
rank,
self.hidden_size,
device=base_layer.gate_up_proj.device,
dtype=base_layer.gate_up_proj.dtype,
)
)
for _ in range(n_adapters)
]
)
self.gate_up_lora_B = nn.ParameterList(
[
nn.Parameter(
torch.empty(
self.num_experts,
self.gate_up_out,
rank,
device=base_layer.gate_up_proj.device,
dtype=base_layer.gate_up_proj.dtype,
)
)
for _ in range(n_adapters)
]
)
self.down_lora_A = nn.ParameterList(
[
nn.Parameter(
torch.empty(
self.num_experts,
rank,
self.intermediate_size,
device=base_layer.down_proj.device,
dtype=base_layer.down_proj.dtype,
)
)
for _ in range(n_adapters)
]
)
self.down_lora_B = nn.ParameterList(
[
nn.Parameter(
torch.empty(
self.num_experts,
self.hidden_size,
rank,
device=base_layer.down_proj.device,
dtype=base_layer.down_proj.dtype,
)
)
for _ in range(n_adapters)
]
)
self.reset_parameters()
def reset_parameters(self, index: int | None = None) -> None:
if index is None:
for i in range(self.n_adapters):
self.reset_parameters(i)
else:
nn.init.kaiming_uniform_(self.gate_up_lora_A[index], a=math.sqrt(5))
nn.init.zeros_(self.gate_up_lora_B[index])
nn.init.kaiming_uniform_(self.down_lora_A[index], a=math.sqrt(5))
nn.init.zeros_(self.down_lora_B[index])
def named_parameters_for_adapter(self, idx: int) -> list[tuple[str, nn.Parameter]]:
return [
("gate_up_lora_A", self.gate_up_lora_A[idx]),
("gate_up_lora_B", self.gate_up_lora_B[idx]),
("down_lora_A", self.down_lora_A[idx]),
("down_lora_B", self.down_lora_B[idx]),
]
def get_lora_param_counts(self) -> tuple[int, int]:
adapter_params = (
self.gate_up_lora_A[0].numel()
+ self.gate_up_lora_B[0].numel()
+ self.down_lora_A[0].numel()
+ self.down_lora_B[0].numel()
)
adapted_params = self.base_layer.gate_up_proj.numel() + self.base_layer.down_proj.numel()
return adapter_params, adapted_params
def state_dict_for_adapter(self, idx: int) -> dict[str, torch.Tensor]:
"""vLLM-compatible 3D MoE adapter format.
For 3D MoE models (gpt-oss in vLLM has `is_3d_moe_weight = True`), vLLM expects:
- `experts.base_layer.lora_{A,B}.weight` for the gate_up projection
- `experts.lora_{A,B}.weight` for the down projection
with experts stacked into the rank dim. See
vllm/lora/model_manager.py::_stack_moe_lora_weights, which reshapes
lora_A: (num_experts*rank, in) -> (num_experts, rank, in)
lora_B: (out, rank*num_experts) -> (out, rank, num_experts) -> (num_experts, out, rank)
"""
detached_gu_a = self.gate_up_lora_A[idx].detach()
detached_gu_b = self.gate_up_lora_B[idx].detach()
detached_d_a = self.down_lora_A[idx].detach()
detached_d_b = self.down_lora_B[idx].detach()
if isinstance(detached_gu_a, DTensor):
detached_gu_a = detached_gu_a.full_tensor()
detached_gu_b = detached_gu_b.full_tensor()
detached_d_a = detached_d_a.full_tensor()
detached_d_b = detached_d_b.full_tensor()
# lora_A: (num_experts, rank, in) -> (num_experts*rank, in)
gu_a_flat = detached_gu_a.reshape(self.num_experts * self.rank, self.hidden_size).clone()
d_a_flat = detached_d_a.reshape(self.num_experts * self.rank, self.intermediate_size).clone()
# lora_B: (num_experts, out, rank) -> (out, rank, num_experts) -> (out, rank*num_experts)
# vLLM's reshape treats the last dim of lora_B as (rank, num_experts) with experts fast-varying.
gu_b_flat = detached_gu_b.permute(1, 2, 0).contiguous().reshape(self.gate_up_out, self.rank * self.num_experts)
d_b_flat = detached_d_b.permute(1, 2, 0).contiguous().reshape(self.hidden_size, self.rank * self.num_experts)
return {
"base_layer.lora_A.weight": gu_a_flat,
"base_layer.lora_B.weight": gu_b_flat,
"lora_A.weight": d_a_flat,
"lora_B.weight": d_b_flat,
}
def forward(self, x: torch.Tensor, num_tokens_per_expert: torch.Tensor) -> torch.Tensor:
adapter_idx = self._lora_num_tokens.argmax().item()
gu_a = self.gate_up_lora_A[adapter_idx]
gu_b = self.gate_up_lora_B[adapter_idx]
d_a = self.down_lora_A[adapter_idx]
d_b = self.down_lora_B[adapter_idx]
scaling = self._scaling_factors[adapter_idx].item()
base_gu = self.base_layer.gate_up_proj
base_gu_bias = self.base_layer.gate_up_proj_bias
base_d = self.base_layer.down_proj
base_d_bias = self.base_layer.down_proj_bias
permuted_indices = None
if isinstance(base_gu, DTensor):
base_gu = base_gu.to_local()
base_gu_bias = base_gu_bias.to_local()
base_d = base_d.to_local()
base_d_bias = base_d_bias.to_local()
gu_a = gu_a.to_local()
gu_b = gu_b.to_local()
d_a = d_a.to_local()
d_b = d_b.to_local()
if getattr(self.base_layer, "ep_comm_backend", "torch") != "deepep":
from torchtitan.distributed.expert_parallel import TOKEN_GROUP_ALIGN_SIZE_M
from torchtitan.experiments.kernels.moe.indices import generate_permute_indices
experts_per_ep_rank = base_gu.shape[0]
num_ep_ranks = num_tokens_per_expert.shape[0] // experts_per_ep_rank
with torch.no_grad():
permuted_indices, num_tokens_per_expert, _ = generate_permute_indices(
num_tokens_per_expert,
experts_per_ep_rank,
num_ep_ranks,
x.shape[0] + experts_per_ep_rank * TOKEN_GROUP_ALIGN_SIZE_M,
TOKEN_GROUP_ALIGN_SIZE_M,
)
x = torch.vstack((x, x.new_zeros((x.shape[-1]))))
input_shape = x.shape
x = x[permuted_indices, :]
offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32)
lora_x = self.lora_dropout(x)
if self.use_grouped_mm:
gate_up_base = torch._grouped_mm(x.bfloat16(), base_gu.bfloat16(), offs=offsets)
gate_up_base = (
gate_up_base
+ _broadcast_expert_bias(base_gu_bias, num_tokens_per_expert, gate_up_base.shape[0]).bfloat16()
)
gate_up_lora = _run_lora_grouped_mm(lora_x, gu_a, gu_b, offsets)
gate_up = gate_up_base + scaling * gate_up_lora.bfloat16()
h = _gpt_oss_apply_gate(gate_up)
lora_h = self.lora_dropout(h)
out_base = torch._grouped_mm(h, base_d.bfloat16(), offs=offsets)
out_base = (
out_base + _broadcast_expert_bias(base_d_bias, num_tokens_per_expert, out_base.shape[0]).bfloat16()
)
out_lora = _run_lora_grouped_mm(lora_h, d_a, d_b, offsets)
out = out_base + scaling * out_lora.bfloat16()
out = out.type_as(x)
else:
out = self._forward_for_loop(
x,
num_tokens_per_expert,
gu_a,
gu_b,
d_a,
d_b,
base_gu,
base_gu_bias,
base_d,
base_d_bias,
scaling,
)
if permuted_indices is not None:
if out.shape[0] < len(permuted_indices):
num_padding = len(permuted_indices) - out.shape[0]
out = torch.vstack((out, out.new_zeros((num_padding, out.shape[-1]))))
out_unpermuted = out.new_zeros(input_shape)
out_unpermuted[permuted_indices, :] = out
out = out_unpermuted[:-1]
return out
def _forward_for_loop(
self,
x: torch.Tensor,
num_tokens_per_expert: torch.Tensor,
gu_a: torch.Tensor,
gu_b: torch.Tensor,
d_a: torch.Tensor,
d_b: torch.Tensor,
base_gu: torch.Tensor,
base_gu_bias: torch.Tensor,
base_d: torch.Tensor,
base_d_bias: torch.Tensor,
scaling: float,
) -> torch.Tensor:
n = num_tokens_per_expert.tolist()
out_splits = []
start = 0
for e, num_tokens in enumerate(n):
if num_tokens == 0:
continue
end = start + num_tokens
x_e = x[start:end]
x_e_lora = self.lora_dropout(x_e)
gate_up_base = x_e @ base_gu[e] + base_gu_bias[e]
gate_up_lora_tmp = x_e_lora @ gu_a[e].transpose(-2, -1)
gate_up_lora = gate_up_lora_tmp @ gu_b[e].transpose(-2, -1)
gate_up = gate_up_base + scaling * gate_up_lora
h = _gpt_oss_apply_gate(gate_up)
h_lora = self.lora_dropout(h)
out_base = h @ base_d[e] + base_d_bias[e]
out_lora_tmp = h_lora @ d_a[e].transpose(-2, -1)
out_lora = out_lora_tmp @ d_b[e].transpose(-2, -1)
out = out_base + scaling * out_lora
out_splits.append(out)
start = end
return torch.cat(out_splits, dim=0)
def __repr__(self) -> str:
return (
f"{self.__class__.__name__}(base={self.base_layer}, rank={self.rank}, "
f"n_adapters={self.n_adapters}, num_experts={self.num_experts}, "
f"alpha={self.alpha}, dropout={self.lora_dropout}, "
f"use_grouped_mm={self.use_grouped_mm})"
)
+161
View File
@@ -208,6 +208,161 @@ class GroupedExperts(nn.Module):
nn.init.trunc_normal_(self.w3, mean=0.0, std=init_std)
# GPT-OSS activation constants. Both clamping limit and the sigmoid alpha live here
# rather than as instance attrs so the function is JIT/compile-friendly.
GPT_OSS_LIMIT = 7.0
GPT_OSS_ALPHA = 1.702
def _gpt_oss_apply_gate(gate_up: torch.Tensor) -> torch.Tensor:
"""GPT-OSS expert activation: clamped sigmoid-glu over interleaved gate/up channels."""
gate, up = gate_up[..., ::2], gate_up[..., 1::2]
gate = gate.clamp(min=None, max=GPT_OSS_LIMIT)
up = up.clamp(min=-GPT_OSS_LIMIT, max=GPT_OSS_LIMIT)
glu = gate * torch.sigmoid(gate * GPT_OSS_ALPHA)
return (up + 1) * glu
def _broadcast_expert_bias(bias: torch.Tensor, num_tokens_per_expert: torch.Tensor, target_rows: int) -> torch.Tensor:
"""Repeat per-expert bias to per-token, padding to target_rows if EP added padding rows."""
# repeat_interleave on CUDA requires int counts; histc/router output is float.
bias_per_token = torch.repeat_interleave(bias, num_tokens_per_expert.to(torch.int64), dim=0)
if bias_per_token.shape[0] < target_rows:
pad_rows = target_rows - bias_per_token.shape[0]
bias_per_token = F.pad(bias_per_token, (0, 0, 0, pad_rows))
return bias_per_token
def _run_gpt_oss_experts_for_loop_impl(
gate_up_proj: torch.Tensor,
gate_up_proj_bias: torch.Tensor,
down_proj: torch.Tensor,
down_proj_bias: torch.Tensor,
x: torch.Tensor,
num_tokens_per_expert: torch.Tensor,
) -> torch.Tensor:
n = num_tokens_per_expert.tolist()
num_padding = x.shape[0] - sum(n)
x_split = torch.split(x[: sum(n)], split_size_or_sections=n, dim=0)
out_splits = []
for e, x_e in enumerate(x_split):
gate_up = x_e @ gate_up_proj[e] + gate_up_proj_bias[e]
h = _gpt_oss_apply_gate(gate_up)
out = h @ down_proj[e] + down_proj_bias[e]
out_splits.append(out)
out = torch.cat(out_splits, dim=0)
return torch.vstack((out, out.new_zeros((num_padding, out.shape[-1]))))
@expert_parallel
def _run_gpt_oss_experts_for_loop(
gate_up_proj: torch.Tensor,
gate_up_proj_bias: torch.Tensor,
down_proj: torch.Tensor,
down_proj_bias: torch.Tensor,
x: torch.Tensor,
num_tokens_per_expert: torch.Tensor,
) -> torch.Tensor:
return _run_gpt_oss_experts_for_loop_impl(
gate_up_proj, gate_up_proj_bias, down_proj, down_proj_bias, x, num_tokens_per_expert
)
def _run_gpt_oss_experts_grouped_mm_impl(
gate_up_proj: torch.Tensor,
gate_up_proj_bias: torch.Tensor,
down_proj: torch.Tensor,
down_proj_bias: torch.Tensor,
x: torch.Tensor,
num_tokens_per_expert: torch.Tensor,
) -> torch.Tensor:
offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32)
assert x.dim() == 2
gate_up = torch._grouped_mm(x.bfloat16(), gate_up_proj.bfloat16(), offs=offsets)
gate_up = gate_up + _broadcast_expert_bias(gate_up_proj_bias, num_tokens_per_expert, gate_up.shape[0]).bfloat16()
h = _gpt_oss_apply_gate(gate_up)
out = torch._grouped_mm(h, down_proj.bfloat16(), offs=offsets)
out = out + _broadcast_expert_bias(down_proj_bias, num_tokens_per_expert, out.shape[0]).bfloat16()
return out.type_as(x)
@expert_parallel
def _run_gpt_oss_experts_grouped_mm(
gate_up_proj: torch.Tensor,
gate_up_proj_bias: torch.Tensor,
down_proj: torch.Tensor,
down_proj_bias: torch.Tensor,
x: torch.Tensor,
num_tokens_per_expert: torch.Tensor,
) -> torch.Tensor:
return _run_gpt_oss_experts_grouped_mm_impl(
gate_up_proj, gate_up_proj_bias, down_proj, down_proj_bias, x, num_tokens_per_expert
)
class GptOssGroupedExperts(nn.Module):
"""GPT-OSS-style grouped experts.
Mirrors HF's `GptOssExperts` parameter naming (gate_up_proj/down_proj plus per-expert
biases, fused interleaved gate/up channels) so the unsloth BF16 checkpoint loads with
no key conversion. Forward signature matches `GroupedExperts` (`x`, `num_tokens_per_expert`)
so the surrounding MoE plumbing and LoRA wrapper follow the same convention.
"""
def __init__(
self,
hidden_size: int,
intermediate_size: int,
num_experts: int,
use_grouped_mm: bool,
):
super().__init__()
self.num_experts = num_experts
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.gate_up_proj = nn.Parameter(torch.empty(num_experts, hidden_size, 2 * intermediate_size))
self.gate_up_proj_bias = nn.Parameter(torch.empty(num_experts, 2 * intermediate_size))
self.down_proj = nn.Parameter(torch.empty(num_experts, intermediate_size, hidden_size))
self.down_proj_bias = nn.Parameter(torch.empty(num_experts, hidden_size))
self.use_grouped_mm = use_grouped_mm
self.ep_comm_backend: EPCommBackend = "torch"
def set_ep_comm_backend(self, backend: EPCommBackend) -> None:
self.ep_comm_backend = backend
def _forward_deepep(self, x: torch.Tensor, num_tokens_per_expert: torch.Tensor) -> torch.Tensor:
gate_up_proj = self.gate_up_proj.to_local()
gate_up_proj_bias = self.gate_up_proj_bias.to_local()
down_proj = self.down_proj.to_local()
down_proj_bias = self.down_proj_bias.to_local()
if self.use_grouped_mm:
return _run_gpt_oss_experts_grouped_mm_impl(
gate_up_proj, gate_up_proj_bias, down_proj, down_proj_bias, x, num_tokens_per_expert
)
return _run_gpt_oss_experts_for_loop_impl(
gate_up_proj, gate_up_proj_bias, down_proj, down_proj_bias, x, num_tokens_per_expert
)
def forward(self, x: torch.Tensor, num_tokens_per_expert: torch.Tensor) -> torch.Tensor:
if self.ep_comm_backend == "deepep":
return self._forward_deepep(x, num_tokens_per_expert)
if self.use_grouped_mm:
return _run_gpt_oss_experts_grouped_mm(
self.gate_up_proj, self.gate_up_proj_bias, self.down_proj, self.down_proj_bias, x, num_tokens_per_expert
)
return _run_gpt_oss_experts_for_loop(
self.gate_up_proj, self.gate_up_proj_bias, self.down_proj, self.down_proj_bias, x, num_tokens_per_expert
)
def init_weights(self, init_std: float):
nn.init.trunc_normal_(self.gate_up_proj, mean=0.0, std=0.02)
nn.init.zeros_(self.gate_up_proj_bias)
nn.init.trunc_normal_(self.down_proj, mean=0.0, std=init_std)
nn.init.zeros_(self.down_proj_bias)
class TokenChoiceTopKRouter(nn.Module):
"""This class implements token-choice routing. In token-choice top-K routing, each token is
routed to top K experts based on the router scores.
@@ -237,6 +392,7 @@ class TokenChoiceTopKRouter(nn.Module):
self.score_func = score_func
self.route_norm = route_norm
self.route_scale = route_scale
self.force_balanced = False
def forward(
self, x: torch.Tensor, expert_bias: torch.Tensor | None = None, routed_experts: torch.Tensor | None = None
@@ -278,6 +434,11 @@ class TokenChoiceTopKRouter(nn.Module):
if routed_experts is not None:
top_scores = scores.gather(dim=1, index=routed_experts)
selected_experts_indices = routed_experts
elif self.force_balanced:
num_tokens = scores.shape[0]
arange = torch.arange(num_tokens * self.top_k, device=scores.device)
selected_experts_indices = (arange % self.num_experts).view(num_tokens, self.top_k)
top_scores = scores.gather(dim=1, index=selected_experts_indices)
elif expert_bias is not None:
_, selected_experts_indices = torch.topk(scores + expert_bias, k=self.top_k, dim=1)
top_scores = scores.gather(dim=1, index=selected_experts_indices)
+301 -6
View File
@@ -30,11 +30,11 @@ def _fa3_varlen_forward(
"max_seqlen_q": max_seqlen_q,
"max_seqlen_k": max_seqlen_k,
"softmax_scale": softmax_scale,
"causal": causal,
"is_causal": causal,
"window_size_left": window_size[0],
"window_size_right": window_size[1],
}
)
if "window_size" in params:
params["window_size"] = window_size
out, lse, _, _ = _flash_attn_forward(**params)
return out, lse
@@ -76,11 +76,11 @@ def _fa3_varlen_backward(
"dk": dk,
"dv": dv,
"softmax_scale": softmax_scale,
"causal": causal,
"is_causal": causal,
"window_size_left": window_size[0],
"window_size_right": window_size[1],
}
)
if "window_size" in params:
params["window_size"] = window_size
_flash_attn_backward(**params)
@@ -297,3 +297,298 @@ def ring_fa3_varlen_func(
window_size[0],
window_size[1],
)
# ---------------------------------------------------------------------------
# FA4 (flash_attn.cute) ring attention
# ---------------------------------------------------------------------------
def _fa4_varlen_forward(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
softmax_scale: float,
causal: bool,
window_size: tuple[int, int] = (-1, -1),
) -> tuple[torch.Tensor, torch.Tensor]:
from flash_attn.cute.interface import _flash_attn_fwd
wl = window_size[0] if window_size[0] != -1 else None
wr = window_size[1] if window_size[1] != -1 else None
out, lse = _flash_attn_fwd(
q,
k,
v,
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=max_seqlen_q,
max_seqlen_k=max_seqlen_k,
softmax_scale=softmax_scale,
causal=causal,
window_size_left=wl,
window_size_right=wr,
return_lse=True,
)
return out, lse
def _fa4_varlen_backward(
dout: torch.Tensor,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
out: torch.Tensor,
softmax_lse: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
dq: torch.Tensor,
dk: torch.Tensor,
dv: torch.Tensor,
softmax_scale: float,
causal: bool,
window_size: tuple[int, int] = (-1, -1),
) -> None:
from flash_attn.cute.interface import _flash_attn_bwd
wl = window_size[0] if window_size[0] != -1 else None
wr = window_size[1] if window_size[1] != -1 else None
_flash_attn_bwd(
q,
k,
v,
out,
dout,
softmax_lse,
softmax_scale=softmax_scale,
causal=causal,
window_size_left=wl,
window_size_right=wr,
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=max_seqlen_q,
max_seqlen_k=max_seqlen_k,
dq=dq,
dk=dk,
dv=dv,
)
class _RingFA4Varlen(torch.autograd.Function):
"""Ring attention using FA4 (flash_attn.cute) kernels with all-gather communication.
Mirrors _RingFA3Varlen but calls the FA4 low-level forward/backward.
"""
@staticmethod
def forward(
ctx,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
local_k_slice_start: int,
local_k_slice_stop: int,
heads_k_stride: int,
causal: bool,
group_name: str,
window_size_left: int = -1,
window_size_right: int = -1,
) -> torch.Tensor:
group = dist.group.WORLD
for pg in dist.distributed_c10d._world.pg_map:
if pg.group_name == group_name:
group = pg
break
local_k_slice = slice(local_k_slice_start, local_k_slice_stop)
window_size = (window_size_left, window_size_right)
softmax_scale = q.shape[-1] ** (-0.5)
out_list = []
lse_list = []
nheads = q.shape[1]
total_k, nheads_k, head_dim = k.shape
world_size = dist.get_world_size(group)
kv_buffer = torch.empty((2, total_k * world_size, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
kv_buffer_copy = torch.empty_like(kv_buffer)
comm = AllGatherComm(group)
comm.all_gather(kv_buffer_copy[0], k[:, :heads_k_stride].contiguous())
comm.all_gather(kv_buffer_copy[1], v[:, :heads_k_stride].contiguous())
for i in range(0, nheads_k, heads_k_stride):
comm.wait()
kv_buffer, kv_buffer_copy = kv_buffer_copy, kv_buffer
if i < nheads_k - heads_k_stride:
left = i + heads_k_stride
right = left + heads_k_stride
comm.all_gather(kv_buffer_copy[0], k[:, left:right].contiguous())
comm.all_gather(kv_buffer_copy[1], v[:, left:right].contiguous())
q_i = q[:, i * nheads // nheads_k : (i + heads_k_stride) * nheads // nheads_k]
k_i = kv_buffer[0][local_k_slice]
v_i = kv_buffer[1][local_k_slice]
out_i, lse_i = _fa4_varlen_forward(
q=q_i,
k=k_i,
v=v_i,
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=max_seqlen_q,
max_seqlen_k=max_seqlen_k,
softmax_scale=softmax_scale,
causal=causal,
window_size=window_size,
)
out_list.append(out_i)
lse_list.append(lse_i)
out = torch.cat(out_list, dim=1)
lse = torch.cat(lse_list, dim=-2)
ctx.save_for_backward(q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k)
ctx.softmax_scale = softmax_scale
ctx.max_seqlen_q = max_seqlen_q
ctx.max_seqlen_k = max_seqlen_k
ctx.local_k_slice = local_k_slice
ctx.heads_k_stride = heads_k_stride
ctx.causal = causal
ctx.group_name = group_name
ctx.window_size = window_size
return out
@staticmethod
def backward(ctx, dout: torch.Tensor):
q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k = ctx.saved_tensors
heads_k_stride = ctx.heads_k_stride
local_k_slice = ctx.local_k_slice
causal = ctx.causal
group = dist.group.WORLD
for pg in dist.distributed_c10d._world.pg_map:
if pg.group_name == ctx.group_name:
group = pg
break
nheads = q.shape[1]
total_k, nheads_k, head_dim = k.shape
world_size = dist.get_world_size(group)
kv_buffer = torch.empty((2, total_k * world_size, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
kv_buffer_copy = torch.empty_like(kv_buffer)
dkv_buffer = torch.empty((2, total_k * world_size, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
kv_contiguous_buffer = None
if heads_k_stride != nheads_k:
kv_contiguous_buffer = torch.empty((2, total_k, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
dq = torch.empty_like(q)
dk = torch.empty_like(k)
dv = torch.empty_like(v)
comm = AllGatherComm(group)
comm.all_gather(kv_buffer_copy[0], k[:, :heads_k_stride].contiguous())
comm.all_gather(kv_buffer_copy[1], v[:, :heads_k_stride].contiguous())
for i in range(0, nheads_k, heads_k_stride):
dkv_buffer.zero_()
q_slice = slice(i * nheads // nheads_k, (i + heads_k_stride) * nheads // nheads_k)
q_i = q[:, q_slice]
dout_i = dout[:, q_slice]
out_i = out[:, q_slice]
dq_i = dq[:, q_slice]
lse_i = softmax_lse[q_slice].contiguous()
comm.wait()
kv_buffer, kv_buffer_copy = kv_buffer_copy, kv_buffer
if i < nheads_k - heads_k_stride:
left = i + heads_k_stride
right = left + heads_k_stride
comm.all_gather(kv_buffer_copy[0], k[:, left:right].contiguous())
comm.all_gather(kv_buffer_copy[1], v[:, left:right].contiguous())
k_i = kv_buffer[0][local_k_slice]
v_i = kv_buffer[1][local_k_slice]
dk_i = dkv_buffer[0][local_k_slice]
dv_i = dkv_buffer[1][local_k_slice]
_fa4_varlen_backward(
dout=dout_i,
q=q_i,
k=k_i,
v=v_i,
out=out_i,
softmax_lse=lse_i,
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=ctx.max_seqlen_q,
max_seqlen_k=ctx.max_seqlen_k,
dq=dq_i,
dk=dk_i,
dv=dv_i,
softmax_scale=ctx.softmax_scale,
causal=causal,
window_size=ctx.window_size,
)
if heads_k_stride != nheads_k:
dk_i = kv_contiguous_buffer[0]
dv_i = kv_contiguous_buffer[1]
else:
dk_i = dk
dv_i = dv
dist.reduce_scatter_tensor(dk_i, dkv_buffer[0], group=group)
dist.reduce_scatter_tensor(dv_i, dkv_buffer[1], group=group)
if heads_k_stride != nheads_k:
dk[:, i : i + heads_k_stride] = dk_i
dv[:, i : i + heads_k_stride] = dv_i
# Grads for: q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k,
# local_k_slice_start, local_k_slice_stop, heads_k_stride, causal, group_name,
# window_size_left, window_size_right
return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None
def ring_fa4_varlen_func(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
local_k_slice: slice,
causal: bool,
heads_k_stride: int,
group: dist.ProcessGroup,
window_size: tuple[int, int] = (-1, -1),
) -> torch.Tensor:
return _RingFA4Varlen.apply(
q,
k,
v,
cu_seqlens_q,
cu_seqlens_k,
max_seqlen_q,
max_seqlen_k,
local_k_slice.start,
local_k_slice.stop,
heads_k_stride,
causal,
group.group_name,
window_size[0],
window_size[1],
)
@@ -252,6 +252,10 @@ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
r"""
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
compatibility — prime-rl asserts `use_cache is None` since training does not
perform autoregressive decoding, so this argument is unused.
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels used by PrimeRL's wrapped LM head to optionally compute per-token logprobs/entropy.
If not provided, the wrapped LM head returns logits only.
@@ -240,6 +240,10 @@ class MiniMaxM2ForCausalLM(MiniMaxM2PreTrainedModel, GenerationMixin):
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
r"""
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
compatibility — prime-rl asserts `use_cache is None` since training does not
perform autoregressive decoding, so this argument is unused.
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss.
temperature (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
@@ -50,7 +50,14 @@ def _convert_hf_moe_layer_to_prime(state_dict: dict[str, Tensor], prefix: str):
if f"{mixer}gate.weight" in state_dict:
state_dict[f"{mlp}router.gate"] = state_dict.pop(f"{mixer}gate.weight")
if f"{mixer}gate.e_score_correction_bias" in state_dict:
state_dict[f"{mlp}router.e_score_correction_bias"] = state_dict.pop(f"{mixer}gate.e_score_correction_bias")
bias = state_dict.pop(f"{mixer}gate.e_score_correction_bias")
# Shift by per-row min so values land in a range bf16 can represent without
# collapsing. NemotronH biases sit ~57 with ~0.04 inter-expert spread, well
# under bf16's ~0.4 step at that magnitude. topk(scores + bias) is invariant
# to a constant shift of bias, and the returned routing weights are gathered
# from raw sigmoid scores (not biased), so this does not change routing math.
bias = bias - bias.min()
state_dict[f"{mlp}router.e_score_correction_bias"] = bias
# Experts: check if stored as individual weights (experts.{i}.up_proj.weight)
# or fused 3D tensors (experts.up_proj)
@@ -9,6 +9,7 @@ Hybrid Mamba-Transformer-MoE architecture with three distinct layer types:
from typing import Optional
import torch
import torch.distributed as dist
from torch import Tensor, nn
from transformers.generation import GenerationMixin
from transformers.modeling_layers import GradientCheckpointingLayer
@@ -18,6 +19,7 @@ from transformers.utils import auto_docstring, logging
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
from prime_rl.trainer.models.layers.cp_mamba import mamba_cp_forward
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.moe import LatentMoE, NemotronHRouter, NonGatedGroupedExperts
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
@@ -66,7 +68,78 @@ def _patch_mamba2_use_triton_ssd():
logger.warning_once("mamba_ssm not available; NemotronH Mamba layers will use torch_forward (bf16 softplus)")
return
def _patched_forward(self, hidden_states, cache_params=None, attention_mask=None):
def _varlen_mamba_forward(self, hidden_states, cu_seqlens):
"""Varlen-aware mamba forward. `cu_seqlens` is required: shape [num_seq+1],
e.g. [0, s1, s1+s2, ...]. Handles packed batches by:
- applying conv1d per-sequence (with kernel-1 leading zeros)
- passing seq_idx to mamba_chunk_scan_combined (SSM state resets at boundaries)
"""
batch_size, seq_len, _ = hidden_states.shape
assert batch_size == 1, "varlen mamba expects batch_size=1 (packed)"
groups_time_state_size = self.n_groups * self.ssm_state_size
# 1. Input projection (pointwise, no cross-seq mixing)
projected_states = self.in_proj(hidden_states)
A = -torch.exp(self.A_log.float())
dt_limit_kwargs = {} if self.time_step_limit is None else {"dt_limit": self.time_step_limit}
gate, hidden_states_B_C, time_step = torch.split(
projected_states,
[self.intermediate_size, self.conv_dim, self.num_heads],
dim=-1,
)
# 2. Per-sequence causal conv1d. self.conv1d already has padding=kernel-1 so
# applying it to each segment independently gives the correct causal output
# without cross-sequence history.
hbc_t = hidden_states_B_C.transpose(1, 2) # (1, C, L)
cu = cu_seqlens.tolist()
conv_outs = []
for i in range(len(cu) - 1):
s, e = cu[i], cu[i + 1]
if s == e:
continue
seg = hbc_t[:, :, s:e]
conv_out = self.conv1d(seg)[:, :, : e - s]
conv_outs.append(conv_out)
hidden_states_B_C = self.act(torch.cat(conv_outs, dim=-1).transpose(1, 2))
hidden_states, B, C = torch.split(
hidden_states_B_C,
[self.intermediate_size, groups_time_state_size, groups_time_state_size],
dim=-1,
)
# 3. SSM with seq_idx so state resets at sequence boundaries
seq_idx = torch.zeros(seq_len, dtype=torch.int32, device=hidden_states.device)
for i in range(len(cu) - 1):
s, e = cu[i], cu[i + 1]
if e > s:
seq_idx[s:e] = i
seq_idx = seq_idx.unsqueeze(0) # (1, L)
scan_output = _mamba_chunk_scan_combined(
hidden_states.view(batch_size, seq_len, -1, self.head_dim),
time_step,
A,
B.view(batch_size, seq_len, self.n_groups, -1),
C.view(batch_size, seq_len, self.n_groups, -1),
chunk_size=self.chunk_size,
D=self.D,
z=None,
seq_idx=seq_idx,
return_final_states=False,
dt_bias=self.dt_bias,
dt_softplus=True,
**dt_limit_kwargs,
)
scan_output = scan_output.view(batch_size, seq_len, -1)
scan_output = self.norm(scan_output, gate)
return self.out_proj(scan_output)
def _patched_forward(self, hidden_states, cache_params=None, attention_mask=None, cu_seqlens=None):
if cu_seqlens is not None and cache_params is None and "cuda" in self.in_proj.weight.device.type:
return _varlen_mamba_forward(self, hidden_states, cu_seqlens)
if "cuda" in self.in_proj.weight.device.type:
# Disable fused training path (needs causal_conv1d CUDA extension)
orig = self.use_mem_eff_path
@@ -78,7 +151,7 @@ def _patch_mamba2_use_triton_ssd():
NemotronHMamba2Mixer.forward = _patched_forward
_patch_applied = True
logger.info("Patched NemotronHMamba2Mixer to use mamba_ssm Triton SSD kernels")
logger.info("Patched NemotronHMamba2Mixer: Triton SSD kernels + varlen (cu_seqlens) support")
def _ensure_zamba2_compat(config: NemotronHConfig):
@@ -113,7 +186,12 @@ def _ensure_zamba2_compat(config: NemotronHConfig):
class NemotronHMambaLayer(GradientCheckpointingLayer):
"""Mamba-2 SSM layer: norm -> NemotronHMamba2Mixer -> residual."""
"""Mamba-2 SSM layer: norm -> NemotronHMamba2Mixer -> residual.
With context parallelism, uses all-to-all head partitioning: transposes
from sequence-parallel to head-parallel before the SSM, so each CP rank
processes the full sequence on a subset of heads, then transposes back.
"""
def __init__(self, config: NemotronHConfig, layer_idx: int):
super().__init__()
@@ -123,6 +201,21 @@ class NemotronHMambaLayer(GradientCheckpointingLayer):
self.mamba = NemotronHMamba2Mixer(config, layer_idx=layer_idx)
self.mlp = None # No MoE in this layer type
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
assert self.mamba.num_heads % cp_world_size == 0, (
f"num_heads ({self.mamba.num_heads}) must be divisible by cp_world_size ({cp_world_size})"
)
assert self.mamba.n_groups % cp_world_size == 0, (
f"n_groups ({self.mamba.n_groups}) must be divisible by cp_world_size ({cp_world_size})"
)
self._cp_group = cp_group
self._cp_rank = cp_rank
self._cp_world_size = cp_world_size
@property
def cp_enabled(self) -> bool:
return hasattr(self, "_cp_group")
def forward(
self,
hidden_states: torch.Tensor,
@@ -132,7 +225,15 @@ class NemotronHMambaLayer(GradientCheckpointingLayer):
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.norm(hidden_states)
hidden_states = self.mamba(hidden_states)
if self.cp_enabled:
# TODO: This path doesnt support cu_seqlens so packing makes it wrong
hidden_states = mamba_cp_forward(
self.mamba, hidden_states, self._cp_group, self._cp_rank, self._cp_world_size
)
else:
hidden_states = self.mamba(hidden_states, cu_seqlens=cu_seqlens)
return residual + hidden_states
@@ -273,6 +374,23 @@ class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
convert_hf_to_prime(state_dict, layers_block_type)
return state_dict
@classmethod
def convert_adapter_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
# HF NemotronH unifies attention/mlp under a single `mixer` attribute per layer.
import re
rename = [
(re.compile(r"(\.layers\.\d+)\.mlp\."), r"\1.mixer."),
(re.compile(r"(\.layers\.\d+)\.self_attn\."), r"\1.mixer."),
]
for old_key in list(state_dict.keys()):
new_key = old_key
for pattern, repl in rename:
new_key = pattern.sub(repl, new_key)
if new_key != old_key:
state_dict[new_key] = state_dict.pop(old_key)
return state_dict
@classmethod
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
from prime_rl.trainer.models.nemotron_h.converting_nemotron_h import _rename_keys
@@ -255,7 +255,11 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
conv1d_kernel_size=self.conv_kernel_size,
)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
def forward(
self,
hidden_states: torch.Tensor,
cu_seqlens: torch.LongTensor | None = None,
) -> torch.Tensor:
batch_size, seq_len, _ = hidden_states.shape
mixed_qkv = self.in_proj_qkv(hidden_states).transpose(1, 2)
@@ -263,15 +267,32 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
b = self.in_proj_b(hidden_states)
a = self.in_proj_a(hidden_states)
# Causal conv1d
# Causal conv1d — must reset at sequence boundaries for packed batches,
# otherwise the kernel-1 left pad leaks state across sequences.
if self._causal_conv1d_fn is not None:
seq_idx = None
if cu_seqlens is not None:
seg_lens = cu_seqlens[1:] - cu_seqlens[:-1]
seq_idx = torch.repeat_interleave(
torch.arange(seg_lens.numel(), dtype=torch.int32, device=hidden_states.device),
seg_lens,
).unsqueeze(0)
mixed_qkv = self._causal_conv1d_fn(
x=mixed_qkv,
weight=self.conv1d.weight.squeeze(1),
bias=self.conv1d.bias,
activation=self.activation,
seq_idx=None,
seq_idx=seq_idx,
)
elif cu_seqlens is not None:
cu = cu_seqlens.tolist()
conv_outs = []
for i in range(len(cu) - 1):
s, e = cu[i], cu[i + 1]
if s == e:
continue
conv_outs.append(self.conv1d(mixed_qkv[:, :, s:e])[:, :, : e - s])
mixed_qkv = F.silu(torch.cat(conv_outs, dim=-1))
else:
mixed_qkv = F.silu(self.conv1d(mixed_qkv)[:, :, :seq_len])
@@ -313,6 +334,7 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
initial_state=None,
output_final_state=False,
use_qk_l2norm_in_kernel=True,
cu_seqlens=cu_seqlens,
)
# Gated RMSNorm
@@ -606,7 +628,7 @@ class Qwen3_5MoeDecoderLayer(GradientCheckpointingLayer):
# Token mixer
if self.layer_type == "linear_attention":
hidden_states = self.linear_attn(hidden_states)
hidden_states = self.linear_attn(hidden_states, cu_seqlens=cu_seqlens)
elif self.layer_type == "full_attention":
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
@@ -374,6 +374,10 @@ class Qwen3MoeForCausalLM(Qwen3MoePreTrainedModel, GenerationMixin):
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
r"""
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
compatibility — prime-rl asserts `use_cache is None` since training does not
perform autoregressive decoding, so this argument is unused.
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+47 -29
View File
@@ -198,44 +198,62 @@ class NCCLWeightBroadcast(WeightBroadcast):
"""Broadcast the state dict of a model into the inference pool using NCCL and notifies the orchestrator."""
self.logger.debug("Starting broadcasting weights to inference engine via NCCL")
start_time = time.perf_counter()
notified_runs: list[tuple[int, Path]] = []
# `_compute_notified_runs` is a pure function of SPMD-replicated state on
# multi_run_manager, so every trainer rank derives the same list. Only
# the master touches the filesystem to notify the orchestrator, but all
# ranks must wait on NCCL_READY before entering the broadcast path:
# the broadcast preparation (DTensor resolution, quantization) enqueues
# collectives on non-master ranks, and if those ranks start prep before
# the orchestrator has paused inference, the collectives sit unmatched
# until NCCL's watchdog kills the process after 10 min.
notified_runs = self._compute_notified_runs()
if self.world.is_master:
notified_runs = self._notify_orchestrator()
# Wait for inference workers to signal readiness before starting NCCL broadcast
self._wait_for_nccl_ready(notified_runs)
self._notify_orchestrator(notified_runs)
self._wait_for_nccl_ready(notified_runs)
self.nccl_broadcast_sender.broadcast_weights(model, step)
self.logger.debug(f"Weights broadcasted in {time.perf_counter() - start_time:.2f}s")
def _notify_orchestrator(self) -> list[tuple[int, Path]]:
"""Notify the orchestrator to initiate weight broadcast.
def _compute_notified_runs(self) -> list[tuple[int, Path]]:
"""Derive the list of (run_idx, save_dir) pairs that need broadcasting.
Returns:
List of (run_idx, save_dir) tuples for runs that were notified.
Pure function of `multi_run_manager` state, which is replicated across
trainer ranks (SPMD). Returns the same list on every rank so master and
non-master ranks agree on which NCCL_READY markers to wait for.
"""
notified_runs: list[tuple[int, Path]] = []
if self.world.is_master:
for idx in self.multi_run_manager.used_idxs:
if not self.multi_run_manager.ready_to_update[idx]:
continue
try:
save_dir = get_step_path(
get_broadcast_dir(self.multi_run_manager.get_run_dir(idx)),
self.multi_run_manager.progress[idx].step,
)
save_dir.mkdir(parents=True, exist_ok=True)
stable_file = save_dir / "STABLE"
stable_file.touch()
notified_runs.append((idx, save_dir))
except FileNotFoundError:
self.logger.warning(f"Run {idx} is deleted, skipping")
except Exception as e:
self.logger.error(f"Error broadcasting weights for run {idx}: {e}")
finally:
self.multi_run_manager.ready_to_update[idx] = False
for idx in self.multi_run_manager.used_idxs:
if not self.multi_run_manager.ready_to_update[idx]:
continue
try:
save_dir = get_step_path(
get_broadcast_dir(self.multi_run_manager.get_run_dir(idx)),
self.multi_run_manager.progress[idx].step,
)
notified_runs.append((idx, save_dir))
except FileNotFoundError:
self.logger.warning(f"Run {idx} is deleted, skipping")
except Exception as e:
self.logger.error(f"Error resolving broadcast dir for run {idx}: {e}")
return notified_runs
def _notify_orchestrator(self, notified_runs: list[tuple[int, Path]]) -> None:
"""Create STABLE markers for each notified run and clear their ready flags.
Master-only side effects (filesystem writes + state mutation). Called
after `_compute_notified_runs`; non-master ranks skip this entirely.
"""
for idx, save_dir in notified_runs:
try:
save_dir.mkdir(parents=True, exist_ok=True)
stable_file = save_dir / "STABLE"
stable_file.touch()
except FileNotFoundError:
self.logger.warning(f"Run {idx} is deleted, skipping")
except Exception as e:
self.logger.error(f"Error broadcasting weights for run {idx}: {e}")
finally:
self.multi_run_manager.ready_to_update[idx] = False
def _wait_for_nccl_ready(self, notified_runs: list[tuple[int, Path]]):
"""Wait for inference workers to signal they are ready to receive NCCL broadcast."""
for idx, save_dir in notified_runs:
+6
View File
@@ -39,6 +39,9 @@ class TensorMicroBatch(TypedDict):
# mm_token_type_ids: token type per token [batch seq], int64 (0=text, 1=image, 2=video)
mm_token_type_ids: Int[Tensor, "batch seq"] | None
# When True, trainer uses SFT loss instead of RL loss for this batch
sft_loss: bool
class FakeDataLoader:
def __init__(self, config: FakeDataLoaderConfig, seq_len: int, dp_world_size: int):
@@ -111,6 +114,7 @@ class FakeDataLoader:
"pixel_values": None,
"image_grid_thw": None,
"mm_token_type_ids": None,
"sft_loss": False,
}
def _get_micro_batch(self, generator: torch.Generator) -> TensorMicroBatch:
@@ -137,6 +141,7 @@ class FakeDataLoader:
"pixel_values": None,
"image_grid_thw": None,
"mm_token_type_ids": None,
"sft_loss": False,
}
@@ -218,4 +223,5 @@ class DataLoader:
) # [1, seq_len, layers, topk]
if micro_batch.routed_experts is not None
else None,
sft_loss=micro_batch.sft_loss,
)
+5 -1
View File
@@ -203,6 +203,7 @@ def compute_loss(
loss_mask: list[Bool[Tensor, " seq_i"]],
loss_fn: LossFn,
loss_scale: int,
sft_loss: bool = False,
) -> tuple[Float[Tensor, ""], dict[str, Any]]:
"""
Compute loss for packed sequences (batch size = 1, multiple sequences packed along sequence dimension).
@@ -215,10 +216,13 @@ def compute_loss(
loss_mask: Loss mask for each sequence
loss_fn: Per-sequence loss function
loss_scale: Scale factor to normalize the loss
sft_loss: If True, use SFT loss instead of the configured loss_fn for this batch
Returns:
Tuple of (scaled_loss, aggregated_metrics)
"""
effective_loss_fn = sft_loss_fn if sft_loss else loss_fn
total_loss = 0.0
all_metrics: dict[str, list[Tensor]] = {}
@@ -236,7 +240,7 @@ def compute_loss(
loss_mask=mask,
)
result = loss_fn(inputs)
result = effective_loss_fn(inputs)
total_loss = total_loss + result.loss
+3 -1
View File
@@ -188,10 +188,11 @@ def train(config: TrainerConfig):
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank()
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.model.attn)
from prime_rl.utils.cp import setup_hybrid_cp, setup_sparse_mla_cp
from prime_rl.utils.cp import setup_hybrid_cp, setup_nemotron_h_cp, setup_sparse_mla_cp
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
setup_sparse_mla_cp(model, cp_group, cp_rank, parallel_dims.cp)
setup_nemotron_h_cp(model, cp_group, cp_rank, parallel_dims.cp)
# Optionally, resume training from a checkpoint
progress = Progress()
@@ -444,6 +445,7 @@ def train(config: TrainerConfig):
loss_mask=loss_mask.squeeze().split(response_lengths),
loss_fn=loss_fn,
loss_scale=loss_scale,
sft_loss=micro_batch["sft_loss"],
)
# Backward pass
+12
View File
@@ -60,6 +60,9 @@ class MultiRunManager:
# Store modules with their FQN prefixes for parameter management
self._modules: list[tuple[str, "MultiLoRALinear"]] = []
# Optional conversion applied to adapter state dicts (e.g. PrimeRL -> HF key rename)
self._adapter_state_dict_converter: Callable[[dict[str, torch.Tensor]], dict[str, torch.Tensor]] | None = None
# Initialize lora globals on device so runs.* ARE the global tensors
from prime_rl.trainer.models.layers.lora import (
get_lora_num_tokens,
@@ -140,6 +143,12 @@ class MultiRunManager:
# Module Registration and Parameter Management
# =========================================================================
def register_adapter_state_dict_converter(
self, converter: Callable[[dict[str, torch.Tensor]], dict[str, torch.Tensor]]
) -> None:
"""Register a converter applied in-place to adapter state dicts (e.g. model.convert_adapter_to_hf)."""
self._adapter_state_dict_converter = converter
def register_module(self, prefix: str, module: "MultiLoRALinear") -> None:
"""Register a MultiLoRALinear module with its FQN prefix.
@@ -188,6 +197,9 @@ class MultiRunManager:
# Default: use named_parameters_for_adapter
for name, param in module.named_parameters_for_adapter(idx):
state_dict[f"{prefix}.{name}.weight"] = param.detach()
if self._adapter_state_dict_converter is not None:
state_dict = self._adapter_state_dict_converter(state_dict)
return state_dict
def reset_run_parameters(self, idx: int) -> None:
+2 -1
View File
@@ -109,7 +109,7 @@ def train(config: SFTConfig):
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank()
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.model.attn)
from prime_rl.utils.cp import setup_hybrid_cp, setup_sparse_mla_cp
from prime_rl.utils.cp import setup_hybrid_cp, setup_nemotron_h_cp, setup_sparse_mla_cp
# Set up checkpoint manager
logger.info(f"Initializing checkpoint managers ({config.ckpt})")
@@ -131,6 +131,7 @@ def train(config: SFTConfig):
if parallel_dims.cp_enabled:
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
setup_sparse_mla_cp(model, cp_group, cp_rank, parallel_dims.cp)
setup_nemotron_h_cp(model, cp_group, cp_rank, parallel_dims.cp)
if config.model.lora is not None:
multi_run_manager = get_multi_run_manager()

Some files were not shown because too many files have changed in this diff Show More