Compare commits

..
Author SHA1 Message Date
3dd48be5bf feat: integrate FP8 weight transfer format (#2038)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: integrate GLM5 FP8 kernel-format weight transfer

* refactor: clean fp8 transfer flow and model-name split

* refactor: unify quantized transfer config and enforce strict kernel updates

* fix: restore pre-existing nccl receiver log levels

* refactor: unify preprocess flow and validate kernel transfer method

* refactor: simplify transfer validation and flatten nccl preprocess flow

* refactor: use module-level preprocess functions for nccl broadcast

* refactor: split nccl worker loaders and postprocessors

* chore: remove fp8 weight transfer config tests per PR review

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

---------

Co-authored-by: Sami Jaghouar <sami.jaghouar@hotmail.fr>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 18:46:59 -07:00
40da51a235 SFT distillation: bug fixes, VLM support, and pretokenization optimization (#2053)
Release / Push CUDA image to Docker (push) Canceled after 0s
* SFT distillation with teacher endpoint

* streamline SFT distillation rollout/eval model split

* fix sft reconstruction and default loss scaling regressions

* simplify SFT distillation by removing eval inference split

* chore: apply ruff formatting

* docs: add changelog entries for RolloutModelConfig, SFTLossConfig, and CustomLossConfig

Co-authored-by: will brown <willccbb@users.noreply.github.com>

* refine external SFT rollout path and cleanup tests

* refactor shared SFT chat-template tokenization logic

* fix: remove dead store in _tokenize_step_from_messages

full_ids was tokenized via _render_messages then immediately overwritten
by build_incremental_token_mask, wasting a tokenization pass per step.

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

* fix: remove unused _should_add_generation_prompt from trajectories

Duplicate of should_add_generation_prompt in utils/chat_template.py,
never called anywhere.

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

* fix: pass top_k and min_p for both token and non-token client paths

Explicitly disable top-k and min-p filtering on all vLLM requests,
not just the token client path.

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

* chore: remove redundant test_rl_config_external_rollout_mode_rejects_inference

Redundant with the Pydantic model validator definition.

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

* fix: correct CHANGELOG field name to teacher_rollout_model

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

* fix: pass tool definitions through pretokenize pipeline

When external teacher rollouts have tool_defs, convert them to OAI
format and pass through to build_incremental_token_mask so that
tokenization includes tool definition tokens from the chat template.

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

* fix: enable collapse_consecutive_tool_messages in pretokenization

Matches the SFT data pipeline behavior. Without this, parallel tool
call responses cause an assertion failure in incremental tokenization
when the chat template re-renders consecutive tool messages.

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

* fix: handle dict tool_defs in _convert_tools_to_oai_format

Tool definitions arrive as plain dicts after ZMQ msgpack serialization
(verifiers' msgpack_encoder calls model_dump() on Tool pydantic objects).
Use duck-typed accessor to support both dict and object forms.

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

* feat: VLM processor support in SFT distillation pretokenization

For VLM models, the tokenizer alone produces only 1 <|image_pad|> token
per image, but the model expects the count to match actual image patches.
Thread the processor through pretokenize → render_messages →
build_incremental_token_mask so that processor.apply_chat_template
(which expands image placeholders correctly) is used when available.

Also move pretokenize before build_vlm_image_cache in the orchestrator,
since the cache build strips image data from messages.

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

* perf: replace incremental token mask with direct completion masking

In the SFT distillation path, completion is always a single assistant
message (enforced by verifiers' parse_response_message), so the
completion mask is trivially all-True. Replace N incremental
tokenizer/processor calls from build_incremental_token_mask with a
single render_messages call. For VLM models this avoids redundant
image preprocessing on every incremental prefix.

Added assertion to guard the single-assistant-role assumption.

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

* chore: remove duplicate SFT distillation configs

Keep examples/alphabet_sort/sft_distill_hard.toml as the canonical
example config.

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

* fix: always request logprobs in sampling args

logprobs=True was only set when use_token_client=True, but non-token-
client paths (e.g. external APIs) also need logprobs for RL training.
return_token_ids remains gated behind use_token_client since it is
vLLM-specific.

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

* chore: remove test_rl_config_external_rollout_mode_rejects_token_client

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

* fix: set checkpoint_ready in non-policy-update path

When enable_policy_updates is False (SFT distillation), generate_batch
skipped calling checkpoint_ready.set(). This worked by accident because
the event starts set and is only cleared inside maybe_update_policy
(which is never called in this path), but would deadlock if anything
else ever cleared the event.

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

* Address PR review feedback

- Revert loss_scale regression: use loss_mask-based scaling unconditionally
- Move setup_external_rollout_model to orchestrator/utils.py
- Clarify log message to say "SFT distillation mode"

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

* fix: truncate prompt_ids to common prefix to prevent corrupted token sequences

When tokenizing trajectory steps from messages, the prompt-only and
full (prompt+completion) tokenizations can diverge at a boundary
(non-prefix split). Previously, the full prompt_ids was returned even
when split_idx < len(prompt_ids), producing corrupted sequences where
prompt_ids + completion_ids != full_ids. This broke interleaving
(extension property checks fail on mismatched prefixes) and fed
invalid token sequences to the trainer.

Fix: use full_ids[:split_idx] as prompt_ids so the concatenation
always equals full_ids exactly.

Verified across GLM-4, Qwen3, Qwen2.5, Qwen2.5-VL tokenizers and
tested end-to-end SFT distillation on alphabet-sort, wiki-search,
tic-tac-toe, and color-codeword (VLM) environments.

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

* fix: restore non-prefix tokenization debug log after prompt_ids truncation

The previous commit truncating prompt_ids to full_ids[:split_idx] made
the debug log condition always false (split_idx < split_idx). Track the
original prompt length before overwrite so the log fires correctly.

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

---------

Co-authored-by: William Brown <williambrown97@gmail.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: will brown <willccbb@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 17:49:00 -07:00
rasdaniandGitHub bb4c23b122 breakdown difficulty pool metrics per env (#2070)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-21 23:55:10 +01:00
1bc1021a0f validate VLM dtype in configs (#2060)
Release / Push CUDA image to Docker (push) Canceled after 0s
* validate VLM dtype in configs

* ruff

* Add changelog entry for VLM bfloat16 validation requirement

Co-authored-by: rasdani <rasdani@users.noreply.github.com>

* Remove VLM bfloat16 dtype test

Co-authored-by: rasdani <rasdani@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: rasdani <rasdani@users.noreply.github.com>
2026-03-21 23:01:05 +01:00
Philipp NormannandGitHub 4875c101c2 Add SFT LoRA support (#1849)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Add SFT LoRA support

* Fix ruff formatting and add missing comment

* Use MultiRunManager for SFT LoRA adapter export

* Rename SFT LoRA run adapter export helper
2026-03-20 20:18:15 -07:00
Shayon MukherjeeandGitHub fc6fd48fae Fix: typo in comment for sample_ratio (#2058)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-20 22:34:25 +01:00
DominikandGitHub d5c7240676 Feature: Add platform integration. (#1896)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-20 02:34:11 +01:00
3dcff28e02 fix: use mean().mean() for console metrics to match wandb (#2056)
Release / Push CUDA image to Docker (push) Canceled after 0s
Console reward was using results_df.reward.mean() (flat mean across all
rollouts) while wandb logged by_example.reward.mean().mean() (mean per
example, then across examples). These diverge when rollouts_per_example
varies across problems. Now both use the same aggregation.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 18:20:49 -07:00
JannikStandGitHub 58f4b37d5b Add router_url support for elastic inference pool (#2049)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Add router_url support for elastic inference pool

When configured, inference requests route through a vllm-router
while admin operations (weight updates, LoRA loading) still go
directly to discovered pods via elastic DNS discovery.

* Gate router traffic on ready servers

Only expose the router client when there are actually ready backends,
preventing requests from being sent to a router with no healthy pods
during weight updates or scale-down.
2026-03-20 02:11:39 +01:00
47f6bb8307 fix: remove misleading orchestrator throughput metric (#2048)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: remove misleading orchestrator throughput metric

The orchestrator's perf/throughput (tokens/s) was computed as
num_tokens / generate_completions_time, but with in-flight rollouts
some tokens are generated during the previous training step. This makes
generate_completions_time shorter than the actual total inference time,
inflating the reported throughput. Per-rollout generation_ms metrics
remain available for accurate inference speed tracking.

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

* fix: remove throughput from orchestrator benchmark table

Same misleading metric — remove it from print_benchmark as well.

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-03-19 13:10:28 -07:00
1f6de8fff4 chore: bump verifiers to 1960e77 (#2051)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 11:53:03 -07:00
c1bbbf9231 add Group Relative Reward Rescaling as length penalty (#2029)
Release / Push CUDA image to Docker (push) Canceled after 0s
* add Group Relative Reward Rescaling as length penalty

* require online difficulty filtering

* add config validation

* fix mean

* refactor

* move `baseline`

* GR3 length penalty: Advantage config validator bug (#2039)

The validate_gr3_alpha validator in AdvantageConfig was incorrectly
accessing self.online_difficulty_filtering, which belongs to BufferConfig,
not AdvantageConfig. This caused an AttributeError whenever gr3_alpha was
set to a truthy value, making the GR3 feature unusable.

Fixed by moving the online_difficulty_filtering check to OrchestratorConfig
where both advantage and buffer configs are accessible.

Co-authored-by: Cursor Agent <cursoragent@cursor.com>

* fix baseline

* fix dtype

* changelog

* rename to `length_shaping_alpha`

* deprecate `length_weighte_mean`

* add test

---------

Signed-off-by: rasdani <73563550+rasdani@users.noreply.github.com>
Co-authored-by: rasdani <3563550+rasdani@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-03-19 02:00:36 +01:00
halleriteandGitHub f399e2664c add weights-only checkpointing (#2033)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-18 15:10:37 -07:00
Mika SenghaasandGitHub 0f236d322c shared wandb mode (#2044)
Release / Push CUDA image to Docker (push) Canceled after 0s
* poc of shared run mode

* deprecate wandb.id

* style

* use step metric to align x-axis

* remove flush + fix signatures

* init monitor earlier

* retry shared run creation

* add note

* update changelog
2026-03-18 13:47:11 -07:00
Shayon MukherjeeandGitHub f7192e15f3 Add sample_ratio to LogExtrasConfig for gradual rollout data control (#2023)
Release / Push CUDA image to Docker (push) Canceled after 0s
Add a sample_ratio field (0.0–1.0) to LogExtrasConfig that controls
what fraction of rollouts are logged per step. When set, the effective
sample cap is computed from the actual rollout count at runtime:
int(len(rollouts) * sample_ratio).

  1.0  = all rollouts (full data)
  0.5  = half of rollouts
  0.0  = disable sample logging
  None (default) = current behavior (log all)

Usage: --prime-monitor.log-extras.sample-ratio 0.5
2026-03-18 13:49:55 -04:00
JannikStandGitHub bd110a10e9 fix: cleanup env subprocesses on orchestrator crash (#2028)
Release / Push CUDA image to Docker (push) Canceled after 0s
atexit handler ensures spawned env server processes are terminated when
the orchestrator crashes, preventing orphaned subprocesses that keep the
container alive and leave the run stuck in RUNNING.
2026-03-18 05:13:42 +01:00
d1c36af4b3 fix: handle DTensor weights in MultiLoRAGroupedExperts for EP (#2035)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: handle DTensor weights in MultiLoRAGroupedExperts for EP compatibility

When Expert Parallelism is enabled, distribute_module() converts all
parameters to DTensors sharded across the EP mesh. The base GroupedExperts
path handles this via the @expert_parallel decorator, but
MultiLoRAGroupedExperts.forward() bypassed the decorator entirely,
passing DTensors directly to torch._grouped_mm alongside regular tensors.

Mirror the @expert_parallel decorator logic: convert DTensors to local
shards, apply generate_permute_indices for token reordering and alignment
padding, and unpermute the output.

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

* fix: gather EP-sharded LoRA weights in state_dict and exclude base_layer from modules_to_save

Two fixes for EP + LoRA MoE weight broadcast:

1. state_dict_for_adapter: call full_tensor() on DTensor LoRA weights
   before per-expert indexing. With EP, these weights are sharded across
   ranks and direct indexing triggers a DTensor redistribute assertion.

2. save_lora_config: exclude "base_layer" params from modules_to_save
   detection. After EP/FSDP wrapping, base layer params can have
   requires_grad=True, causing them to be incorrectly added to
   modules_to_save which vLLM rejects.

Tested end-to-end: Qwen3-30B-A3B EP=4, LoRA rank 16, 30 steps at
batch sizes 128 and 256 on H200.

* fix: re-freeze base params after EP replaces them with DTensors

ExpertParallel() replaces expert params with DTensors that default to
requires_grad=True, overriding the freeze applied by LoRA setup.
Re-run freeze_all_except_lora_and_specified after apply_ep to restore
correct grad state.

This also reverts the save_lora_config workaround (base_layer filter)
since the root cause is now fixed.

* fix: use new_zeros instead of new_empty for unpermuted output buffer

new_empty leaves uninitialized memory in positions not covered by
permuted_indices, which could leak garbage values into the output.

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 18:39:32 -07:00
rasdaniandGitHub eba667d9c0 bump verifiers (#2036)
Release / Push CUDA image to Docker (push) Canceled after 0s
* bump verifiers

bumps to verifiers `de2ed50`

https://github.com/PrimeIntellect-ai/verifiers/commit/de2ed50f015ed1af0990b218de1df0853d9b3973

Signed-off-by: rasdani <73563550+rasdani@users.noreply.github.com>

* update lock file

---------

Signed-off-by: rasdani <73563550+rasdani@users.noreply.github.com>
2026-03-17 16:22:18 -07:00
7e06730200 fix: use token-level loss normalization for all loss types (#2034)
Release / Push CUDA image to Docker (push) Canceled after 0s
Previously, custom losses were normalized by batch_size (number of
sequences) while the default loss was normalized by the number of
unmasked tokens. This made the effective learning rate depend on
sequence length for custom losses. Now all loss types consistently
normalize by the number of unmasked tokens.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 09:49:41 -07:00
6c55a9aab2 make the loss equal weight per unmaked token (#1961)
Release / Push CUDA image to Docker (push) Canceled after 0s
* make the loss equal weight per unmaked token

* minor fixes

* run ruff

* prevent nan-poisoning

* update

---------

Co-authored-by: hallerite <git@hallerite.com>
2026-03-16 12:41:06 -07:00
33d266b41f fix: patch sharded LoRA slice_lora_a for Qwen3.5 MoE (#2027)
Release / Push CUDA image to Docker (push) Canceled after 0s
MergedColumnParallelLinearWithShardedLoRA.slice_lora_a was hardcoded
for exactly 2 subloras, causing IndexError with Qwen3.5's 4-way
qkvz fusion when fully_sharded_loras=True.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-13 13:41:49 -07:00
8fa0dde0be feat: make max_retries configurable per training env (#2025)
Release / Push CUDA image to Docker (push) Canceled after 0s
Move max_retries from EvalEnvConfig to EnvConfig so it applies to both
training and eval environments. The scheduler now looks up max_retries
per task from the env config instead of hardcoding 0.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 01:57:33 -07:00
76946689cf add Qwen 3.5 MoE model support with EP and VLM weight broadcast (#2026)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: add Qwen 3.5 MoE model support with EP and CP integration

Adds a custom Qwen 3.5 MoE (GatedDeltaNet + MoE) implementation with:
- HF <-> PrimeRL weight conversion (fused/unfused expert formats)
- Expert Parallelism support (MoE layers auto-detected by apply_ep)
- Context Parallelism support (ring attention patching for flash attention layers)
- Router replay via routed_experts argument
- Unit tests for forward pass, weight roundtrip, router replay, and CP patching

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

* remove vflm warning

* feat: add custom VLM support for Qwen 3.5 MoE

Extend Qwen3_5MoeForCausalLM to handle both text-only and VLM configs.
When the config has a vision_config, the model creates a composite body
(HF frozen vision encoder + custom PrimeRL text model). Weight conversion
auto-detects VLM keys and remaps accordingly.

- Unified model class (no separate VLM file) driven by config
- Config-based VLM detection fallback for local model paths
- VLM dispatch in get_model() via _CUSTOM_VLM_MAPPING
- mini_moe.py preset for qwen3_5_moe_vlm testing
- 6 new GPU tests covering forward/backward/weights/roundtrip/router/meta

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

* chore: add debug SFT config for real Qwen3.5-35B-A3B VLM

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

* fix: support VLM layer key format in weight broadcast

VLM models use `model.language_model.layers.*` instead of
`model.layers.*`, which crashed get_max_layer_num and caused
filter_state_dict_by_layers to silently drop layer weights.

Also fixes off-by-one in filter_state_dict_by_layers that
skipped layer 0.

* use registry-based approach

* run ruff

* chore: remove debug SFT configs for Qwen3.5 MoE

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

---------

Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: sami jaghouar <sami.jaghouar@gmail.com>
2026-03-13 00:51:53 -07:00
67de232773 fix: avoid duplicate policy updates during scheduler cancellation (#2004)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Fix duplicate policy updates during cancellation

* fix: cancel inflight scheduler policy update on stop

---------

Co-authored-by: Sebastian <sebastian@primeintellect.ai>
2026-03-12 10:47:04 -07:00
cab621fc5d fix: improve rollout error logging and normalize error/empty metrics (#2020)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: use repr for rollout error log to show full error chain

The rollout error warning was using str formatting which only showed
the short error_chain_str. Using repr shows the full error_chain_repr
with the actual error message, making debugging much easier.

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

* fix: print error_chain_repr instead of full error dict

Show only the error_chain_repr from the rollout error dict in the
warning log, which contains the actual useful error message rather
than the entire dict.

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

* simplify: index directly into error dict

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

* feat: make errored_rollouts and empty_rollouts metrics rates per step

Instead of logging raw counts, divide by total rollouts in the step
to get the fraction of errored/empty rollouts. This makes the metrics
comparable across steps with different numbers of rollouts.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 01:22:37 -07:00
275914349a make httpx connect timout configurable (#2017)
Release / Push CUDA image to Docker (push) Canceled after 0s
* make httpx connect timout configurable

* Set default connect_timeout to 30s and add CHANGELOG entry

Co-authored-by: rasdani <rasdani@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: rasdani <rasdani@users.noreply.github.com>
2026-03-12 00:29:07 +01:00
rasdaniandGitHub 9b2fb9afbe feat: save checkpoints and weights to separate path (#2018)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-11 15:50:27 -07:00
halleriteandGitHub be9f9f8d83 add monkeypatch for qwen3.5 lora (#2019)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-11 14:48:04 -07:00
51fcbae998 fix: re-schedule errored rollouts (#2016)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: re-schedule errored rollouts instead of filtering after group completion

Rollouts with a populated "error" field are now re-scheduled (like empty
trajectories) instead of being accepted into the group. Both conditions
are checked independently so a rollout that is both empty and errored
increments both counters. Adds scheduler/errored_rollouts metric.

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

* chore: remove now-dead error/mean metrics from orchestrator

Errored rollouts are filtered in the scheduler before reaching the
batch, so error is always None in results_df. Remove the error column
and the error/all/mean and error/{env}/mean metrics. Error tracking
is now handled by scheduler/errored_rollouts.

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

* feat: per-env metrics for empty and errored rollouts

Track empty_rollouts and errored_rollouts counts per task. Report both
global (scheduler/empty_rollouts/all, scheduler/errored_rollouts/all)
and per-env (scheduler/empty_rollouts/{task}, scheduler/errored_rollouts/{task})
metrics.

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

* chore: move empty/errored rollout metrics to their own section

Use empty_rollouts/ and errored_rollouts/ prefixes instead of nesting
under scheduler/.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 12:42:39 -07:00
faresobeidandGitHub 74a13f0ee2 add zero grad tracking (#1966)
Release / Push CUDA image to Docker (push) Canceled after 0s
* add zero grad tracking

* address comments
2026-03-11 10:48:00 -07:00
051c8bac23 feat: allow num_infer_nodes=0 with fake data in multi-node SLURM RL (#2012)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: allow num_infer_nodes=0 with fake data in multi-node SLURM RL

Skip launching inference servers and orchestrator when num_infer_nodes=0,
running only the trainer with fake data. Useful for benchmarking multi-node
training without needing inference resources.

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

* feat: skip weight broadcast when using fake data

No inference server exists in fake data mode, so broadcasting weights
would either hang (NCCL) or write unnecessary files (filesystem).

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 10:43:37 -07:00
a7db21723e feat: per-env metrics logging (#1989)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: per-env metrics logging with consistent naming convention

Adopt {metric}/{scope}/{stat} naming where scope is "all" (global) or
an env name. All metrics that were previously global-only now get
per-env breakdowns when multiple envs are present.

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

* feat: always show per-env breakdown and drop reward std/median

Remove the nunique() > 1 gate so per-env metrics are always logged,
even with a single env. Remove std and median from reward stats.

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

* chore: metrics/{env}/{metric} format, remove error type breakdown

- Change verifier/filter metrics to metrics/{env}/{metric} (no global, no stat suffix)
- Remove per-error-type logging (error/{error_type})

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

* fix: remove redundant batch/{env}/{env} keys

Env ratios only make sense at the global level (batch/all/{env}).

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

* feat: separate solve/batch/off_policy metrics, flatten async_level

- Extract solve_none, solve_all, effective_batch_size as top-level
  metrics with /all and /{env} breakdowns
- Move off_policy_level to off_policy_level/all/{stat}
- Make async_level a flat key
- batch/ now only contains env ratios and inflight/cancelled counts

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

* feat: per-env off_policy_level tracking

Add task field to InflightRolloutInfo so off_policy_level can be
reported per env as off_policy_level/{env}/{stat}.

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

* chore: rename batch/ inflight/cancelled to progress/, simplify batch/{env}

- batch/inflight_rollouts, batch/inflight_samples, batch/cancelled_rollouts
  moved to progress/ prefix
- batch/all/{env} simplified to batch/{env}
- async_level moved to scheduler/async_level

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

* refactor: inline grouped_stats, separate global and per-env sections

Remove grouped_stats helper in favor of explicit inlined metrics.
Global metrics come first, per-env metrics in a dedicated section after.
All metrics consistently group by example_id before aggregating.

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

* fix: validate that env name is not "all" (reserved for global metrics)

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

* update scheduler config

* fix: use example_id grouping for solve stats instead of index arithmetic

The previous index-based approach (index // rollouts_per_example)
assumed rollouts were contiguous by example, which is not guaranteed
when the scheduler interleaves groups from different envs.

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

* fix: update scheduler test for new task field on InflightRolloutInfo

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

* docs: add changelog entry for metrics logging overhaul

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

* chore: validate unique env names, use notna(), simplify metrics_df access

- Add unique env name validation on OrchestratorConfig and EvalConfig
- Use notna() instead of ~isna() for error rate
- Use index-based loc instead of copying metrics_df with task/example_id

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

* refactor: extract compute_solve_rates, inline _off_policy_steps_by_task

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

* refactor: inline solve_stats, use compute_solve_rates directly

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

* also log per_env stop conditions

* minor

* style

* address bugbot

* min diff in changelog

* update changelog

* revert metrics_df

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 05:23:17 -07:00
00a4752a49 fix: re-schedule empty trajectories instead of filtering after group completion (#2014)
Release / Push CUDA image to Docker (push) Canceled after 0s
Empty trajectories were filtered after sampling from the buffer, which
could yield incomplete groups and break the advantage computation's
assumption that each group has exactly `rollouts_per_example` rollouts.

Now empty trajectories are detected per-rollout as they complete. When
one is found, `rollouts_to_schedule` is incremented so the group
naturally re-fills via `_fill_inflight_requests`, and the group is only
yielded once it has the full count of non-empty rollouts.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 18:34:19 -07:00
halleriteandGitHub fa95af173c Revert "chore: add Claude Code review GitHub Action (#2000)" (#2015)
Release / Push CUDA image to Docker (push) Canceled after 0s
This reverts commit bcb504bd4f.
2026-03-10 17:41:22 -07:00
rasdaniandGitHub 51bd1ad5d4 disinguish is_truncated and log stop_conditions (#2009)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-10 17:55:03 +01:00
samsjaandGitHub 93cd1fa37f feature: switch fused lm head to sequence chunking (#1987)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feature: switch fused lm head to sequence chunking

* fix: deprecate old fused lm head chunk config

* fix: update benchmark token chunk flag

* fix: stream vocab shards inside sequence chunked lm head

* fix: retune benchmark token chunk to 1024

* fix: treat benchmark memory as an upper bound

* fix: remove fused lm head chunk alias

* fix: remove token chunk size validation
2026-03-09 21:42:19 -07:00
00778b5a22 feat: disk-backed image offloading for VLM memory (#2006)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: disk-backed image offloading for VLM orchestrator memory

Replace base64 image data in rollout trajectories with file paths
immediately after receiving from ZMQ. This eliminates the triangle
duplication problem where 15-turn rollouts store 120 copies of
screenshot base64 strings in memory.

Images are written to {output_dir}/assets/images/{sha256}.png and
deduped by content hash. The VLM image cache reads from disk instead
of decoding from base64 strings.

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

* chore: add VLM memory benchmark for disk offloading

Benchmark generates synthetic rollouts with triangle-duplicated
screenshots, simulates ZMQ msgpack roundtrip, and measures RSS
with and without disk-backed image offloading.

Results with 32 rollouts, 15 turns, 512x384 screenshots (~770KB each):
- Without offload: +2.9 GB (91 MB/rollout)
- With offload: +7.8 MB (0.24 MB/rollout)
- 99.7% memory reduction

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

* fix: ruff lint fixes in vlm_memory_bench

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

* fix: ruff format

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

* chore: remove benchmarks folder

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

* Revert "chore: remove benchmarks folder"

This reverts commit 79918131a8c06be55b5a7450a24f2ca82e9aa206.

* revert: restore benchmarks folder, only remove vlm_memory_bench.py

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

* fix: handle file:// URLs in _extract_images_from_messages

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 20:13:59 -07:00
Philipp NormannandGitHub 447cafedea Add SFT validation eval with val_data (#1850)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-09 19:54:05 -07:00
halleriteandGitHub aa432f2c1f fix: patch HF tokenizer 'Already borrowed' crash under concurrent load (#1999)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-09 18:11:53 -07:00
7994d6c1aa fix: filter empty trajectory rollouts in scheduler (#2003)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: filter empty trajectory rollouts in scheduler

Empty trajectories consume batch slots without producing training signal.
Filter them after sampling so they don't count toward batch progress,
and track the count as a metric for observability.

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

* rename to empty_rollouts for consistency

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

* remove empty batch retry logic from orchestrator

The scheduler already filters empty trajectories, so the orchestrator
should not silently retry on empty batches — better to fail fast.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 17:30:47 -07:00
JannikStandGitHub 3639f0ab4f fix _tied_weights_keys for transformers v5 compat (#1998)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-09 16:07:05 -07:00
8eecadc943 fix: use pydantic-config dict coercion instead of local workaround (#1997)
Release / Push CUDA image to Docker (push) Canceled after 0s
Point pydantic-config to main which now includes proper string-to-type
coercion for dict fields in BaseConfig (samsja/pydantic_config#23).

Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 14:54:46 -07:00
bcb504bd4f chore: add Claude Code review GitHub Action (#2000)
Release / Push CUDA image to Docker (push) Canceled after 0s
Adds automated PR review using anthropics/claude-code-action@v1.
Reviews run on PR open/sync/reopen and responds to @claude mentions.

Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 13:07:17 -07:00
samsjaandGitHub 2041d93132 feat: fused linear cross-entropy loss for SFT (#1958)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-09 12:16:16 -07:00
46f26ce195 chore: move env packages to dedicated envs extras group (#1993)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore: move env packages to dedicated `envs` extras group

Move math-env and reverse-text from main dependencies into a new
`envs` optional-dependencies group alongside all other environment
packages used in configs (aime2024, aime2025, alphabet-sort, code-env,
color-codeword, logic-env, math-python, math500, science-env,
wiki-search). All sourced from the primeintellect index.

Install with: uv sync --extra envs

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

* chore: remove primeintellect/ prefix from env IDs in configs

Envs are now installed directly via the envs extras group, so the
primeintellect/ prefix is no longer needed for runtime installation.

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

* chore: mark primeintellect index as explicit

Prevents uv from querying the primeintellect index for every package
during resolution, drastically speeding up uv sync/lock.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 12:00:38 -07:00
e113981a4e feat: add pre_run_command and common SLURM scheduling options (#1988)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: add configurable pre_run_command for SLURM jobs

Allow running a cleanup command on compute nodes before starting
the job (e.g. `sudo pkill -f vllm`). Configured via `slurm.pre_run_command`.
For multi-node jobs, the command runs on all nodes via srun.

Replaces the hardcoded `pkill -9 -f vllm` in the inference template
with the configurable option.

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

* fix: tighten whitespace in template pre_run_command blocks

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

* fix: run pre_run_command on head node only, avoid shell quoting issues

Drop the srun bash -c wrapper from multi-node templates. The command
now runs directly on the head node (same as single-node), which avoids
single-quote injection when the user's command contains quotes.

Users who need all-nodes execution can wrap with srun themselves:
  pre_run_command = "srun bash -c \"pkill -f vllm || true\""

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

* chore: add CHANGELOG entry for slurm.pre_run_command

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

* feat: add nodelist, exclude, account, and time SLURM options

Add commonly needed SLURM scheduling fields to SlurmConfig:
- nodelist: target specific nodes
- exclude: exclude specific nodes
- account: charge to a SLURM account
- time: set maximum wall time

Also extract common slurm fields into SlurmConfig.template_vars
to avoid duplicating them across every template.render() call.

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

* fix: clean up Jinja2 whitespace for optional SBATCH directives

Use {%- if %} to strip leading newlines so no blank lines appear
when optional fields are unset.

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

* fix: run pre_run_command after env setup in single-node templates

Single-node templates ran pre_run_command before cd, .env sourcing,
and venv activation. Move it after setup to match multi-node and
inference templates. Update docs to clarify execution context.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 11:39:09 -07:00
JannikStandGitHub deecddc4af fix crash when pad_token_id is a list in model config (#1991)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-09 17:08:57 +01:00
Shayon MukherjeeandGitHub 26fd0e34be fix: route env install output through structured logger (#1985)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-08 09:15:02 -07:00
rasdaniandGitHub 710c9b32e9 fix: Patch get_encode_kwargs to prevent HF tokenizer left-truncation (#1986)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-08 04:26:16 -07:00
4d91edc9e6 add dp-rank-routing (#1940)
Release / Push CUDA image to Docker (push) Canceled after 0s
* add dp-rank-routing

* docs: add changelog entry for client.dp_rank_count

Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>

* fix elastic

* fix

* dp-rank-route

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>
2026-03-08 06:20:21 +00:00
2c5c69da8b chore: config warnings (#1984)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: remove orchestrator W&B resume ID warning

The warning about missing W&B run ID for orchestrator when resuming
training is not useful and creates noise.

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

* fix: remove trainer W&B resume ID warning

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

* fix: replace warnings.warn with get_logger().warning in configs

Use prime-rl's logger instead of Python's warnings module for
config validation warnings.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 18:28:14 -08:00
5f0dcc8a1b chore: upgrade vllm from 0.17.0rc0 to 0.17.0 stable (#1980)
Release / Push CUDA image to Docker (push) Canceled after 0s
Use the stable PyPI release instead of pre-built wheels from wheels.vllm.ai.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 18:27:51 -08:00
rasdaniandGitHub 8ea7bd4834 fix: wire verifiers max_seq_len correctly (#1983)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-08 00:19:09 +01:00
302ef6d084 fix: only pass --weight_broadcast.host to orchestrator when nccl broadcast is configured (#1979)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-07 15:07:42 -08:00
JannikStandGitHub 89a5343780 fix arm64 flash-attn-cute: revert to 2b5db43 for sm100 pipeline fix (#1982)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix arm64 flash-attn-cute: use 2b5db43 rev with sm100 pipeline fix

* also update fix-flash-attn-cute.sh to 2b5db43
2026-03-07 23:23:26 +01:00
22f0ae7640 fix: reduce orchestrator memory usage for VLM rollouts (#1964)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: reduce orchestrator memory usage for VLM rollouts

The orchestrator's RSS grew unboundedly when processing VLM rollouts
with images (e.g. 1.2 GB → 25+ GB over 10 steps, spiking to 38 GB).
Three root causes:

1. Base64 image data in rollout prompts stayed alive through the entire
   step pipeline (preprocessing, training batch, wandb logging). Now
   stripped immediately after image extraction in _extract_images_from_examples.

2. Intermediate objects (PIL images, torch tensors, chunk results) in
   _preprocess_images_batched were held simultaneously. Now freed eagerly
   with del/clear() after each conversion step.

3. Python's GC and glibc malloc arenas retained freed memory across steps.
   Now explicitly gc.collect() + malloc_trim(0) at end of each step.

Result: baseline 3-5 GB (stable), spikes 5-9 GB (bounded).

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

* refactor: extract strip_base64_images into a standalone function

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

* fix: delete chunks before clearing images to actually free PIL objects

chunks holds shallow-copy references to the same PIL images, so
images.clear() alone doesn't free them during peak memory usage.

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

* Update src/prime_rl/orchestrator/trajectories.py

Signed-off-by: hallerite <git@hallerite.com>

---------

Signed-off-by: hallerite <git@hallerite.com>
Co-authored-by: root <root@vivid-capybara-of-dignity.datacrunch.io>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: hallerite <git@hallerite.com>
2026-03-06 18:06:09 -08:00
JannikStandGitHub f0746566e9 fix arm64 flash-attn: run uv pip from /tmp to avoid pyproject.toml build vars (#1975)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-07 02:10:43 +01:00
JannikStandGitHub 99c02bba6c fix arm64 flash-attn build: override FLASH_ATTENTION_SKIP_CUDA_BUILD (#1974)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix arm64 flash-attn build: override FLASH_ATTENTION_SKIP_CUDA_BUILD

* also set FLASH_ATTENTION_FORCE_BUILD to bypass cached wheel download
2026-03-07 00:12:09 +01:00
JannikStandGitHub ebb5a1cac2 add --no-cache to force flash-attn source build on arm64 (#1973)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-06 21:43:45 +01:00
JannikStandGitHub d19ce7919f force flash-attn source build on arm64 with --no-binary (#1972)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-06 21:02:18 +01:00
JannikStandGitHub e2175c11ae add aarch64 vllm wheel and restrict uv environments to linux x86_64/aarch64 (#1970)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-06 10:53:20 +01:00
103 changed files with 6469 additions and 2299 deletions
+17 -1
View File
@@ -2,7 +2,16 @@
Documenting changes which affect configuration usage patterns (added/moved/removed/renamed fields, notable logic changes).
- **`model.optimization_dtype` / `model.reduce_dtype` (VLM models)**: Added validation that VLM models must use `optimization_dtype='bfloat16'` and `reduce_dtype='bfloat16'` to match vLLM inference. Previously valid configs with `float32` (the default) are now rejected for VLM model names. Set both fields to `"bfloat16"` when training VLMs. (2026-03-21)
- **`orchestrator.advantage.length_weighted_mean`**: Removed. The default advantage now always uses the plain per-problem mean baseline unless `orchestrator.advantage.length_shaping_alpha` is set. Existing configs must delete this field. (2026-03-19)
- **`orchestrator.advantage.length_shaping_alpha`**: Added Group Relative Reward Rescaling coefficient to the default advantage config. When set, applies length-based GR3 shaping during advantage computation and requires `orchestrator.buffer.online_difficulty_filtering = true` (default: `None`) (2026-03-18)
- **`prime_monitor.log_extras.sample_ratio`**: Added ratio-based rollout sampling (0.0–1.0, default: None). When set, caps the number of rollouts logged per step to `len(rollouts) * sample_ratio`. `None` preserves current behavior (log all rollouts). Interacts with existing `interval` gate which still runs first. (2026-03-12)
- **`client.connect_timeout`**: Added configurable TCP connect timeout for inference API requests (default: 30.0s). Previously hardcoded to 5.0s. Helps with vLLM or cluster flakiness (2026-03-11)
- **`model.fused_lm_head_token_chunk_size`**: Added as the fused LM-head chunking field for the token-chunked implementation. Unlike the removed `model.fused_lm_head_chunk_size`, this chunks over flattened sequence tokens rather than vocabulary rows. `model.fused_lm_head_chunk_size` is no longer accepted; switch configs to `model.fused_lm_head_token_chunk_size` explicitly. (2026-03-09)
- **`slurm.pre_run_command`**: Added optional shell command to run on the head node before starting the job. Useful for cleanup routines (e.g. killing stale processes, removing lock files). For all-nodes execution, wrap with `srun` in the command string (default: None) (2026-03-08)
- **`slurm.nodelist`**, **`slurm.exclude`**, **`slurm.account`**, **`slurm.time`**: Added common SLURM scheduling options (all default: None) (2026-03-08)
- **`orchestrator.verification.enabled`**: Added top-level rollout verification switch. `orchestrator.buffer.skip_verification` has been removed; use `verification.enabled = false` instead. When disabled, rewards are always 0 and reward-dependent buffer features (`online_difficulty_filtering`, `easy_threshold`, `hard_threshold`) must be unset (2026-03-03)
- **`client.dp_rank_count`**: Added configuration for data-parallel inference routing. When > 1, each `client.base_url` is expanded into `dp_rank_count` logical clients and pinned via `X-data-parallel-rank` to keep multi-turn rollouts on a consistent DP rank (default: 1) (2026-03-03)
- **`model.lora`**: Moved from `model.experimental.lora` to `model.lora` (no longer experimental) (#1440, 2025-12-16)
- Auto-set `api_server_count=1` on inference when LoRA is enabled, because vLLM doesn't support hotloading for multiple API servers (#1422, 2025-12-17)
- **`inference.model.rope_scaling`**: Added RoPE scaling configuration passthrough to vLLM (#1447 2025-12-17)
@@ -85,6 +94,7 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
- **`trainer.enable_router_replay`**: Added flag to enable router replay. If True, will return routed experts in the batch. This is only supported if `enable_return_routed_experts=True` in the inference config or pass `--enable-return-routed-experts` to vLLM server. This is only supported for custom models. (2026-02-22)
- **`inference.enable_return_routed_experts`**: Added flag to enable return routed experts. Passed to vLLM as `--enable-return-routed-experts` (2026-02-22)
- **`orchestrator.oversampling_factor`**: Added rollout-only over-sampling config that resolves `max_inflight_rollouts = int(batch_size * oversampling_factor)` when `max_inflight_rollouts` is unset. Cannot be used with `token_batch_size` or together with explicit `max_inflight_rollouts` (2026-02-25)
- **`sft.val`**: Added optional periodic SFT validation with `val/loss` and `val/num_tokens` logging. Configure via `sft.val.data` (validation dataset) and `sft.val.interval` (every N steps, default 50). Runs the full validation dataset each pass. (2026-02-26)
- **`model.fused_lm_head_chunk_size`**: Changed default value from 2048 to 8192 for RL training (2026-02-26)
- **`inference.data_parallel_size_local`** and **`inference.data_parallel_rpc_port`**: Added data-parallel node-local controls for vLLM, passed as `--data-parallel-size-local` and `--data-parallel-rpc-port` (defaults: `None`, `13345`) (2026-02-26)
- **`dump_config`**: Removed from `RLConfig`. Replaced by `dry_run` (see below) (2026-02-26)
@@ -97,4 +107,10 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
- **`[deployment]` (inference)**: Added deployment configuration. `type = "single_node"` (default) with `gpus_per_node`. `type = "multi_node"` with `num_nodes` and `gpus_per_node` — requires `[slurm]` (2026-02-26)
- **`inference.output_dir`**: Added directory for SLURM logs and generated scripts (default: `"outputs"`) (2026-02-26)
- **`inference.dry_run`**: Added flag (default: `False`). When set, validates config, writes resolved config to `output_dir/configs/`, and exits without starting inference or submitting SLURM jobs (2026-02-26)
- **`trainer.loss` (default loss)**: Made IPO (DPPO-Binary TV variant ([arxiv](https://arxiv.org/pdf/2602.04879)) + Kimi-K2.5 KL ([Kimi-K2.5](https://arxiv.org/pdf/2602.02276))) the default loss. Removed `ratio_type`, `token_mask_low`, `token_mask_high`, `sequence_clip_high`, `geo_mask_low`, `geo_mask_high`, `sequence_mask_low`, `sequence_mask_high`. Added `ipo_mask_low` (default: 0.2) and `ipo_mask_high` (default: 0.2) for token-level probability-difference masking. Changed `kl_tau` default from `0.0` to `1e-3`. (2026-03-02)
- **`orchestrator.teacher_rollout_model`**: Added optional external rollout model configuration. When set, rollouts are generated from this endpoint/model instead of the student inference server. Accepts a `TeacherRolloutModelConfig` with `client` and `model` sub-fields, or `None` (default: `None`) (2026-02-26)
- **`trainer.loss.type = "sft"`**: Added SFT loss variant. Set `trainer.loss.type = "sft"` to use masked negative log-likelihood loss instead of the default RL loss (2026-02-26)
- **`trainer.loss.type = "custom"`**: Added custom loss variant. Set `trainer.loss.type = "custom"` with `import_path` (e.g. `"my_module.my_loss"`) and optional `kwargs` to use an external loss function (2026-02-26)
- **`trainer.loss` (default loss)**: Made IPO (DPPO-Binary TV variant ([arxiv](https://arxiv.org/pdf/2602.04879)) + Kimi-K2.5 KL ([Kimi-K2.5](https://arxiv.org/pdf/2602.02276))) the default loss. Removed `ratio_type`, `token_mask_low`, `token_mask_high`, `sequence_clip_high`, `geo_mask_low`, `geo_mask_high`, `sequence_mask_low`, `sequence_mask_high`. Added `ipo_mask_low` (default: 0.2) and `ipo_mask_high` (default: 0.2) for token-level probability-difference masking. Changed `kl_tau` default from `0.0` to `1e-3`. (2026-03-02)
- **Metrics logging overhaul**: All orchestrator metrics now follow a `{metric}/{scope}/{stat}` naming convention where scope is `all` (global) or an env name. Per-env breakdowns are always logged (previously only when >1 env). Key renames: `reward/mean` → `reward/all/mean`, `batch/solve_none` → `solve_none/all`, `val_reward/` → `val/reward/`, `metrics/{name}` → `metrics/{env}/{name}`, `stop_condition/{sc}` → `stop_condition/all/{sc}`, `error/mean` → `error/all/mean`. New per-env metrics: `solve_none/{env}`, `solve_all/{env}`, `effective_batch_size/{env}`, `stop_condition/{env}/generation_truncated`, `stop_condition/{env}/{sc}`, `error/{env}/mean`, plus per-env breakdowns for `seq_len`, `prefill_len`, `decode_len`, `is_truncated`, `samples_per_rollout`, `num_turns`, `generation_ms`, `scoring_ms`. Removed: `reward/std`, `reward/median`, per-error-type breakdown (`error/{error_type}`). Env name `"all"` is reserved and rejected at config validation. Env name validation now strips `@version` suffixes to match runtime behavior (e.g. `math@1.0` and `math@2.0` correctly detected as duplicates). Solve stats now use `example_id` grouping instead of index arithmetic (pre-existing bug fix). (2026-03-08)
- **`wandb.shared`** (experimental): Added shared W&B mode that logs trainer and orchestrator metrics to a single W&B run instead of two separate runs. Uses `wandb.Settings(mode="shared")` (requires wandb SDK >= 0.19.9). Enabled by default on the RL entrypoint. Disable with `--wandb.shared False`. Run ID is communicated via `WANDB_SHARED_RUN_ID` env var; process role via `WANDB_SHARED_LABEL`. Non-primary processes retry `wandb.init` up to 30 times waiting for the primary to create the run. Works with multi-node SLURM. (2026-03-18)
- **`wandb.id`**: Removed from `WandbConfig`. Run IDs are now managed internally via env vars for shared mode. (2026-03-18)
+4 -4
View File
@@ -83,9 +83,9 @@ class BenchmarkConfig(BaseConfig):
cp: Annotated[int, Field(ge=1, description="Context parallelism size (1 = no CP)")] = 1
fused_lm_head_chunk_size: Annotated[
fused_lm_head_token_chunk_size: Annotated[
int | None,
Field(description="Fused LM head chunk size (None uses trainer default)"),
Field(description="Fused LM head token chunk size (None uses trainer default)"),
] = None
docker_image: Annotated[str | None, Field(description="Docker image used for the benchmark")] = None
@@ -158,8 +158,8 @@ def build_command(config: BenchmarkConfig) -> list[str]:
cmd.extend(["--model.cp", str(config.cp)])
# Fused LM head chunk size
if config.fused_lm_head_chunk_size is not None:
cmd.extend(["--model.fused-lm-head-chunk-size", str(config.fused_lm_head_chunk_size)])
if config.fused_lm_head_token_chunk_size is not None:
cmd.extend(["--model.fused-lm-head-token-chunk-size", str(config.fused_lm_head_token_chunk_size)])
# Data configuration differs between RL and SFT
if config.type.startswith("rl"):
+1 -1
View File
@@ -17,7 +17,7 @@ rollouts_per_example = 16
max_tokens = 512
[[orchestrator.env]]
id = "primeintellect/alphabet-sort"
id = "alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2 }
@@ -17,7 +17,7 @@ rollouts_per_example = 8
max_tokens = 384
[[orchestrator.env]]
id = "primeintellect/alphabet-sort"
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 }
@@ -0,0 +1,29 @@
max_steps = 10
seq_len = 2048
[deployment]
type = "single_node"
num_infer_gpus = 1
num_train_gpus = 1
[ckpt]
[model]
name = "Qwen/Qwen3-0.6B"
[trainer.optim]
lr = 1e-5
[orchestrator]
batch_size = 128
rollouts_per_example = 8
[orchestrator.sampling]
max_tokens = 1024
[[orchestrator.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 }
[inference]
@@ -5,7 +5,7 @@ max_async_level = 5
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
seq_len = 65536
fused_lm_head_chunk_size = 8192
fused_lm_head_token_chunk_size = 8192
[model.lora]
rank = 8
@@ -0,0 +1,30 @@
max_steps = 20
[ckpt]
resume_step = 10
[ckpt.weights]
save_adapter_separately = true
[model]
name = "PrimeIntellect/Qwen3-0.6B"
[model.lora]
rank = 8
target_modules = [
"q_proj",
"k_proj",
"v_proj",
"o_proj",
"gate_proj",
"up_proj",
"down_proj",
]
[data]
name = "PrimeIntellect/Reverse-Text-SFT"
batch_size = 4
seq_len = 1024
[optim]
lr = 1.5e-5
@@ -0,0 +1,29 @@
max_steps = 10
[ckpt]
[ckpt.weights]
save_adapter_separately = true
[model]
name = "PrimeIntellect/Qwen3-0.6B"
[model.lora]
rank = 8
target_modules = [
"q_proj",
"k_proj",
"v_proj",
"o_proj",
"gate_proj",
"up_proj",
"down_proj",
]
[data]
name = "PrimeIntellect/Reverse-Text-SFT"
batch_size = 4
seq_len = 1024
[optim]
lr = 1.5e-5
+1 -1
View File
@@ -22,7 +22,7 @@ temperature = 0.6
max_tokens = 8192
[[orchestrator.env]]
id = "primeintellect/math-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,7 +17,7 @@ rollouts_per_example = 16
max_tokens = 64
[[orchestrator.env]]
id = "primeintellect/color-codeword"
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
[orchestrator.val]
+1 -1
View File
@@ -41,6 +41,6 @@ port = 8000
sync_interval = 5.0
[[orchestrator.env]]
id = "primeintellect/alphabet-sort"
id = "alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
+1 -1
View File
@@ -16,7 +16,7 @@ rollouts_per_example = 16
max_tokens = 2048
[[orchestrator.env]]
id = "primeintellect/math-env"
id = "math-env"
name = "gsm8k"
args = { dataset_name = "openai/gsm8k", dataset_subset = "main", math_verify_max_workers = 128, math_verify_timeout = 60 }
+2 -2
View File
@@ -16,7 +16,7 @@ rollouts_per_example = 16
max_tokens = 2048
[[orchestrator.env]]
id = "primeintellect/math-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 }
@@ -35,7 +35,7 @@ interval = 10
max_tokens = 2048
[[orchestrator.eval.env]]
id = "primeintellect/math500"
id = "math500"
num_examples = 30
rollouts_per_example = 4
+2 -2
View File
@@ -13,7 +13,7 @@ batch_size = 512
rollouts_per_example = 8
[[orchestrator.env]]
id = "primeintellect/math-env"
id = "math-env"
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
name = "hendrycks-math"
@@ -21,7 +21,7 @@ name = "hendrycks-math"
interval = 50
[[orchestrator.eval.env]]
id = "primeintellect/aime2024"
id = "aime2024"
name = "aime2024"
rollouts_per_example = 16
+3 -3
View File
@@ -13,12 +13,12 @@ rollouts_per_example = 16
oversampling_factor = 1.5
[[orchestrator.env]]
id = "primeintellect/math-env"
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
[[orchestrator.env]]
id = "primeintellect/math-env"
id = "math-env"
name = "acereason-math"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem" }
@@ -34,7 +34,7 @@ num_examples = 128
interval = 50
[[orchestrator.eval.env]]
id = "primeintellect/aime2024"
id = "aime2024"
name = "aime2024"
num_examples = 30
rollouts_per_example = 4
+1 -1
View File
@@ -13,7 +13,7 @@ rollouts_per_example = 16
max_tokens = 64
[[orchestrator.env]]
id = "primeintellect/color-codeword"
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
[orchestrator.val]
+1 -1
View File
@@ -37,7 +37,7 @@ max_tokens = 512
online_difficulty_filtering = true
[[orchestrator.env]]
id = "primeintellect/wiki-search"
id = "wiki-search"
[inference.model]
tool_call_parser = "hermes"
+1
View File
@@ -7,6 +7,7 @@ This directory maintains the documentation for PRIME-RL. It is organized into th
- [**Environments**](environments.md) - Installing and using verifiers environments from the Environments Hub
- [**Async Training**](async.md) - Understanding asynchronous off-policy training and step semantics
- [**Logging**](logging.md) - Logging with loguru, torchrun, and Weights & Biases
- [**Platform Monitoring**](platform-monitoring.md) - Register runs on the Prime Intellect platform and stream training metrics
- [**MultiRunManager**](multi_run_manager.md) - Multi-run training with the MultiRunManager object for concurrent LoRA adapters
- [**Checkpointing**](checkpointing.md) - Saving and resuming training from checkpoints
- [**Benchmarking**](benchmarking.md) - Performance benchmarking and throughput measurement
+41
View File
@@ -62,6 +62,47 @@ enabled = false # Skip expensive verification
This runs pure on-policy distillation: the student learns to match the teacher without needing any reward signal.
## SFT Distillation ("Hard Distillation") From Teacher Rollouts
Use this mode when you want to train from teacher-generated completions directly (hard distillation), without teacher token-level logprobs.
```toml
[trainer.loss]
type = "sft"
[orchestrator]
use_token_client = false
[orchestrator.teacher_rollout_model.client]
base_url = ["https://your-openai-compatible-endpoint/v1"]
skip_model_check = true
[orchestrator.teacher_rollout_model.model]
name = "teacher-model-name"
```
In this mode:
- Rollouts are generated from `orchestrator.teacher_rollout_model`
- The orchestrator uses text-level reconstruction with the student tokenizer
- The RL trainer optimizes masked NLL (`trainer.loss.type = "sft"`)
- Omit `[inference]` (no local inference server required)
### Image Input (VLM) Support
Yes, image input is supported in SFT/hard-distillation mode when the student model is multimodal (VLM).
- Prompts can include OpenAI-style image items in `message.content`, e.g. `{"type": "image_url", "image_url": {"url": "data:image/..."}}`
- The orchestrator extracts and preprocesses images from trajectory prompts and attaches `pixel_values`/`image_grid_thw` to training samples
- No teacher token IDs/logprobs are required; reconstruction still happens from messages
Notes:
- This path currently expects `data:image/...` payloads in message content
- The teacher rollout endpoint still needs to be able to handle the same multimodal prompts during generation
Reference configs:
- `configs/alphabet_sort/sft_distill_hard_qwen4b_lora_prime_teacher.toml`
- `examples/alphabet_sort/sft_distill_hard.toml`
## Parameters
| Parameter | Default | Description |
+48
View File
@@ -0,0 +1,48 @@
# Platform Monitoring
Use `orchestrator.prime_monitor` to register a run on the Prime Intellect platform and stream training metrics, samples, and distributions.
> **Internal-only for now:** external run registration is currently only enabled for internal / allowlisted teams.
## Prerequisites
You need a Prime API key with `rft:write` scope.
Use the CLI:
```bash
prime login
```
Or set an environment variable directly:
```bash
export PRIME_API_KEY=pit_...
```
## Minimal config
```toml
[orchestrator.prime_monitor]
run_name = "my-experiment"
```
You can also override from the CLI:
```bash
uv run rl @ config.toml --orchestrator.prime_monitor.run_name "my-experiment"
```
## Troubleshooting
### `API key not found`
Set the env var from `api_key_var` or run:
```bash
prime login
```
### `External training runs are not enabled for this team`
Your team is not allowlisted yet. This feature is currently internal-only.
+5
View File
@@ -47,6 +47,11 @@ For **multi-node** jobs, sub-configs are written separately and `srun` dispatche
| `project_dir` | Path to the project root on the cluster | `"."` |
| `template_path` | Path to a custom Jinja2 template | auto-selected |
| `partition` | SLURM partition | `"cluster"` |
| `nodelist` | Comma-separated list of specific nodes to run on (`--nodelist`) | `None` |
| `exclude` | Comma-separated list of nodes to exclude (`--exclude`) | `None` |
| `account` | SLURM account to charge (`--account`) | `None` |
| `time` | Maximum wall time, e.g. `"24:00:00"` (`--time`) | `None` |
| `pre_run_command` | Shell command to run on head node after env setup, before starting the job (e.g. cleanup) | `None` |
### `[deployment]` — Node and GPU allocation
@@ -0,0 +1,51 @@
max_steps = 24
seq_len = 2048
[deployment]
type = "single_node"
gpus_per_node = 2
num_train_gpus = 2
num_infer_gpus = 0
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[wandb]
project = "alphabet-sort-sft-distill"
name = "qwen3-4b-hard-distill"
[ckpt]
[trainer.optim]
lr = 1e-5
[trainer.loss]
type = "sft"
[trainer.model.lora]
rank = 16
alpha = 32
[trainer.ckpt.weights]
save_adapter_separately = true
[orchestrator]
batch_size = 256
rollouts_per_example = 4
use_token_client = false
[orchestrator.sampling]
max_tokens = 512
temperature = 0.7
[orchestrator.teacher_rollout_model.client]
base_url = ["https://api.pinference.ai/api/v1"]
api_key_var = "PRIME_API_KEY"
[orchestrator.teacher_rollout_model.model]
name = "qwen/qwen3-235b-a22b-instruct-2507"
[[orchestrator.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 }
+33 -12
View File
@@ -19,13 +19,12 @@ dependencies = [
"torch>=2.9.0",
"torchdata>=0.11.0",
"transformers",
"vllm>=0.16.1.dev",
"vllm>=0.17.0",
"wandb>=0.24.2",
"ring-flash-attn>=0.1.8",
"prime>=0.5.37",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
"math-env",
"tenacity>=8.2.0",
"openai>=1.106.1",
"rich>=14.0.0",
@@ -33,7 +32,6 @@ dependencies = [
"torchtitan",
"verifiers",
"dion",
"reverse-text",
"tilelang>=0.1.8",
]
@@ -52,13 +50,27 @@ prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
flash-attn = [
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3+cu128torch2.10-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
]
flash-attn-3 = [
"flash_attn_3 @ https://github.com/samsja/flash-attn-builds/releases/download/v0.1/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl ; platform_machine == 'x86_64'",
]
flash-attn-cute = [
"flash-attn-cute",
]
envs = [
"reverse-text",
"alphabet-sort",
"wiki-search",
"math-python",
"math-env",
"code-env",
"science-env",
"logic-env",
"color-codeword",
"math500",
"aime2024",
"aime2025",
]
[dependency-groups]
fp8-inference = [
"deep-gemm @ https://github.com/hallerite/DeepGEMM/releases/download/v2.3.0-torch2.9/deep_gemm-2.3.0+35c4bc8-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
@@ -75,6 +87,10 @@ dev = [
[tool.uv]
preview = true
no-build-isolation-package = ["flash-attn"]
environments = [
"sys_platform == 'linux' and platform_machine == 'x86_64'",
"sys_platform == 'linux' and platform_machine == 'aarch64'",
]
# Override torch's pinned cuDNN to fix Conv3d performance regression (torch 2.9 + cuDNN 9.8-9.14)
# See: https://github.com/pytorch/pytorch/issues/166122
override-dependencies = [
@@ -86,15 +102,24 @@ override-dependencies = [
[tool.uv.sources]
torch = { index = "pytorch-cu128" }
vllm = { url = "https://wheels.vllm.ai/097eb544e9a22810c9b7a59e586b61627b308362/vllm-0.17.0rc0-cp38-abi3-manylinux_2_31_x86_64.whl" }
math-env = { index = "primeintellect" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "45fae8d" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "1960e77" }
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 = "5c1c72b" }
flash-attn-cute = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "e2743ab5" }
pydantic-config = { git = "https://github.com/samsja/pydantic_config.git", branch = "main" }
reverse-text = { index = "primeintellect" }
alphabet-sort = { index = "primeintellect" }
wiki-search = { index = "primeintellect" }
math-python = { index = "primeintellect" }
math-env = { index = "primeintellect" }
code-env = { index = "primeintellect" }
science-env = { index = "primeintellect" }
logic-env = { index = "primeintellect" }
color-codeword = { index = "primeintellect" }
math500 = { index = "primeintellect" }
aime2024 = { index = "primeintellect" }
aime2025 = { index = "primeintellect" }
[tool.uv.extra-build-dependencies]
flash-attn = [{ requirement = "torch", match-runtime = true }]
@@ -106,17 +131,13 @@ flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
[[tool.uv.index]]
name = "primeintellect"
url = "https://hub.primeintellect.ai/primeintellect/simple/"
explicit = true
[[tool.uv.index]]
name = "pytorch-cu128"
url = "https://download.pytorch.org/whl/cu128"
explicit = true
[[tool.uv.index]]
name = "vllm-nightly"
url = "https://wheels.vllm.ai/nightly"
explicit = true
[tool.ruff.lint]
select = ["F", "I"]
+9 -3
View File
@@ -3,12 +3,18 @@
set -e
echo "=== building flash-attn from source (sm_100 / GB200) ==="
TORCH_CUDA_ARCH_LIST="10.0" MAX_JOBS=4 \
uv pip install "flash-attn==2.8.3" --no-build-isolation
# Run from /tmp so uv doesn't read pyproject.toml's [tool.uv.extra-build-variables]
# which sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and prevents CUDA kernel compilation.
export TORCH_CUDA_ARCH_LIST="10.0"
export MAX_JOBS=4
export FLASH_ATTENTION_FORCE_BUILD=TRUE
export FLASH_ATTENTION_SKIP_CUDA_BUILD=FALSE
(cd /tmp && uv pip install --python /app/.venv/bin/python \
"flash-attn==2.8.3" --no-build-isolation --no-binary flash-attn --no-cache)
echo "=== reinstalling flash-attn-cute (flash-attn overwrites it with a stub) ==="
uv pip install --reinstall --no-deps \
"flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@e2743ab5#subdirectory=flash_attn/cute"
"flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@2b5db43#subdirectory=flash_attn/cute"
# TODO: remove once flash-attn gates the ampere_helpers import or cutlass-dsl re-adds it.
echo "=== copying ampere_helpers.py from flashinfer vendor ==="
+1 -1
View File
@@ -11,7 +11,7 @@
set -e
echo "Reinstalling flash-attn-cute to fix namespace conflict with flash-attn..."
uv pip install --reinstall --no-deps "flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@e2743ab5#subdirectory=flash_attn/cute"
uv pip install --reinstall --no-deps "flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@2b5db43#subdirectory=flash_attn/cute"
# Verify installation
LINES=$(wc -l < "$(python -c 'import flash_attn.cute.interface as m; print(m.__file__)')")
+91 -17
View File
@@ -17,17 +17,60 @@ from pathlib import Path
import torch
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
from transformers import Glm4MoeForCausalLM as HFGlm4MoeForCausalLM
from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import (
Qwen3_5MoeForConditionalGeneration as HFQwen3_5MoeVLM,
)
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig
from prime_rl.trainer.models.glm4_moe import Glm4MoeForCausalLM as PrimeRLGlm4MoeForCausalLM
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2ForCausalLM as PrimeRLMiniMaxM2ForCausalLM
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeForCausalLM as PrimeRLQwen3_5MoeVLM
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.utils import default_dtype
setup_logger("info")
def _qwen3_5_moe_vlm_config():
"""Build a tiny composite VLM config for Qwen3.5 MoE."""
config = AutoConfig.from_pretrained("Qwen/Qwen3.5-35B-A3B", trust_remote_code=True, attn_implementation="sdpa")
config.use_cache = False
tc = config.text_config
tc.vocab_size = 256
tc.hidden_size = 256
tc.num_hidden_layers = 2
tc.num_attention_heads = 4
tc.num_key_value_heads = 2
tc.head_dim = 64
tc.moe_intermediate_size = 128
tc.shared_expert_intermediate_size = 128
tc.num_experts = 4
tc.num_experts_per_tok = 2
tc.max_position_embeddings = 512
tc.linear_key_head_dim = 32
tc.linear_value_head_dim = 32
tc.linear_num_key_heads = 4
tc.linear_num_value_heads = 8
tc.layer_types = ["full_attention", "linear_attention"]
tc.use_cache = False
vc = config.vision_config
vc.depth = 2
vc.hidden_size = 128
vc.intermediate_size = 256
vc.num_heads = 4
vc.out_hidden_size = tc.hidden_size
config.image_token_id = 250
config.video_token_id = 251
config.vision_start_token_id = 252
config.vision_end_token_id = 253
return config
ARCH_PRESETS = {
"glm4_moe": {
"config_class": Glm4MoeConfig,
@@ -87,6 +130,13 @@ ARCH_PRESETS = {
"prime_model_class": PrimeRLMiniMaxM2ForCausalLM,
"tokenizer_source": "MiniMaxAI/MiniMax-M2.1",
},
"qwen3_5_moe_vlm": {
"config_fn": _qwen3_5_moe_vlm_config,
"hf_model_class": HFQwen3_5MoeVLM,
"prime_model_class": PrimeRLQwen3_5MoeVLM,
"tokenizer_source": "Qwen/Qwen3.5-35B-A3B",
"is_vlm": True,
},
# glm_moe_dsa: HF implementation is incorrect, not supported here
}
@@ -115,12 +165,20 @@ def _create_hf_model_from_config(preset, config):
return AutoModelForCausalLM.from_config(config, trust_remote_code=True)
def _build_config(preset):
"""Build model config from preset (handles both config_class and config_fn styles)."""
if "config_fn" in preset:
return preset["config_fn"]()
return preset["config_class"](**preset["config_kwargs"])
def create(arch: str, output_dir: Path) -> None:
preset = ARCH_PRESETS[arch]
config = preset["config_class"](**preset["config_kwargs"])
config = _build_config(preset)
text_config = getattr(config, "text_config", config)
print(f"Creating mini {arch} model...")
print(f" hidden_size={config.hidden_size}, layers={config.num_hidden_layers}")
print(f" hidden_size={text_config.hidden_size}, layers={text_config.num_hidden_layers}")
with torch.device("cpu"):
model = _create_hf_model(preset, config)
@@ -139,14 +197,20 @@ def create(arch: str, output_dir: Path) -> None:
def verify(arch: str, model_dir: Path) -> None:
preset = ARCH_PRESETS[arch]
is_vlm = preset.get("is_vlm", False)
print(f"Verifying HF <-> PrimeRL roundtrip for {model_dir}...")
trust_remote_code = preset["hf_model_class"] is None
config = AutoConfig.from_pretrained(str(model_dir), trust_remote_code=trust_remote_code)
config._attn_implementation = "sdpa"
if hasattr(config, "text_config"):
config.text_config._attn_implementation = "sdpa"
text_config = getattr(config, "text_config", config)
vocab_size = text_config.vocab_size
hf_model = _load_hf_model(preset, model_dir, config).to(device="cuda", dtype=torch.float32)
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = _load_hf_model(preset, model_dir, config)
prime_model = preset["prime_model_class"]._from_config(config)
with torch.no_grad():
@@ -156,29 +220,39 @@ def verify(arch: str, model_dir: Path) -> None:
inject_prime_lm_head(prime_model, chunk_size=None)
# Use tokens in safe range (avoid special VLM token IDs)
max_token = min(vocab_size, 200) if is_vlm else vocab_size
with torch.device("cuda"), default_dtype(torch.float32):
input_ids = torch.randint(0, config.vocab_size, (1, 64))
input_ids = torch.randint(0, max_token, (1, 64))
position_ids = torch.arange(1, 65).unsqueeze(0)
hf_output = hf_model(input_ids=input_ids, position_ids=position_ids)
prime_output = prime_model(input_ids, position_ids)
logits_diff = prime_output["logits"] - hf_output.logits
max_diff = logits_diff.abs().max().item()
print(f" HF vs PrimeRL max logits diff: {max_diff:.6f}")
assert max_diff < 0.1, f"HF vs PrimeRL logits mismatch: max diff {max_diff}"
if is_vlm:
# HF GatedDeltaNet has a dtype bug in float32 mode; just verify non-NaN output
assert not torch.isnan(prime_output["logits"]).any(), "PrimeRL VLM output contains NaN"
assert prime_output["logits"].shape == hf_output.logits.shape
print(" VLM forward pass verified (shape match, no NaN)")
else:
logits_diff = prime_output["logits"] - hf_output.logits
max_diff = logits_diff.abs().max().item()
print(f" HF vs PrimeRL max logits diff: {max_diff:.6f}")
assert max_diff < 0.1, f"HF vs PrimeRL logits mismatch: max diff {max_diff}"
# Roundtrip weight conversion: HF -> PrimeRL -> HF
# Normalize both through the same roundtrip to handle expert format differences
prime_cls = preset["prime_model_class"]
with torch.no_grad():
roundtrip_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
with torch.device("cuda"), default_dtype(torch.float32):
hf_roundtrip = _create_hf_model_from_config(preset, config)
hf_roundtrip.load_state_dict(roundtrip_state_dict)
roundtrip_sd = prime_cls.convert_to_hf(dict(prime_model.state_dict()))
orig_sd = dict(hf_model.state_dict())
prime_cls.convert_to_prime(orig_sd)
prime_cls.convert_to_hf(orig_sd)
hf_roundtrip_output = hf_roundtrip(input_ids=input_ids, position_ids=position_ids)
roundtrip_diff = hf_roundtrip_output.logits - hf_output.logits
max_roundtrip_diff = roundtrip_diff.abs().max().item()
print(f" HF -> PrimeRL -> HF roundtrip max logits diff: {max_roundtrip_diff:.6f}")
assert max_roundtrip_diff < 0.1, f"Roundtrip logits mismatch: max diff {max_roundtrip_diff}"
for key in orig_sd:
assert key in roundtrip_sd, f"Missing key after roundtrip: {key}"
assert torch.equal(orig_sd[key], roundtrip_sd[key]), f"Roundtrip mismatch at {key}"
print(" HF -> PrimeRL -> HF weight roundtrip verified")
print(" Verification passed.")
+26
View File
@@ -116,6 +116,32 @@ SFT deployment follows the same pattern as RL:
- `output_dir` must be explicitly set when using SLURM
- Multi-node deployment requires `[slurm]` to be set
## SFT Distillation (Hard Distillation) With Teacher Rollouts
Use this when the teacher is an external OpenAI-compatible endpoint and you want to train from teacher completions directly (no teacher token logprobs required).
```toml
[trainer.loss]
type = "sft"
[orchestrator]
use_token_client = false
[orchestrator.teacher_rollout_model.client]
base_url = ["https://your-openai-compatible-endpoint/v1"]
skip_model_check = true
[orchestrator.teacher_rollout_model.model]
name = "teacher-model-name"
```
Notes:
- `orchestrator.teacher_rollout_model` switches rollout generation to the external teacher endpoint.
- `use_token_client = false` is required when `orchestrator.teacher_rollout_model` is set.
- `trainer.loss.type = "sft"` makes the RL trainer optimize masked NLL like SFT.
- In this mode, omit `[inference]`.
- Image input is supported when using a VLM student model and OpenAI-style image messages (`data:image/...`).
## Available commands
All accept `@ config.toml` and CLI overrides:
+76 -13
View File
@@ -287,6 +287,25 @@ class EnvConfig(BaseConfig):
),
),
] = {}
max_retries: Annotated[
int,
Field(
ge=0,
description="Maximum number of times the environment will retry a failed rollout.",
),
] = 0
@property
def resolved_name(self) -> str:
return self.name or self.id.split("@")[0]
@model_validator(mode="after")
def validate_env_name(self):
if self.resolved_name == "all":
raise ValueError(
'Environment name "all" is reserved for global metric aggregation. Use a different name or id.'
)
return self
class EvalEnvConfig(EnvConfig):
@@ -312,17 +331,6 @@ class EvalEnvConfig(EnvConfig):
),
] = 0
# TODO: should live on the EnvConfig and also apply to training envs but
# this is hard right now because we use the vf.EnvGroup which treats all
# envs as one. for now training envs hardcode no retries, but we should
# probably treat them like environment groups long-term
max_retries: Annotated[
int,
Field(
description="Maximum number of times the environment will try to retry running a rollout.",
),
] = 0
class ValConfig(BaseConfig):
"""Configures the validation of the model."""
@@ -382,6 +390,14 @@ class EvalConfig(BaseConfig):
),
] = False
@model_validator(mode="after")
def validate_unique_env_names(self):
env_names = [env.resolved_name for env in self.env]
duplicates = [n for n in env_names if env_names.count(n) > 1]
if duplicates:
raise ValueError(f"Duplicate eval environment names: {set(duplicates)}. Each env must have a unique name.")
return self
class CheckpointConfig(BaseConfig):
"""Configures checkpointing the orchestrator."""
@@ -535,7 +551,10 @@ class DefaultAdvantageConfig(BaseModel):
model_config = ConfigDict(extra="forbid")
type: Literal["default"] = "default"
length_weighted_mean: bool = False
length_shaping_alpha: Annotated[
float | None,
Field(description="Penalty coefficient for Group Relative Reward Rescaling (GR³). Recommended value: 0.33"),
] = None
class CustomAdvantageConfig(BaseModel):
@@ -626,6 +645,10 @@ class NCCLWeightBroadcastConfig(BaseModel):
host: Annotated[str, Field(description="The host to use for the NCCL broadcast.")] = "localhost"
port: Annotated[int, Field(description="The port to use for the NCCL broadcast.")] = 29501
timeout: Annotated[int, Field(description="The timeout in seconds to use for the NCCL broadcast.")] = 1200
quantize_in_weight_transfer: Annotated[
bool,
Field(description="Use kernel-format FP8 quantized NCCL transfer for weight updates."),
] = False
WeightBroadcastConfig: TypeAlias = Annotated[
@@ -647,6 +670,20 @@ class TeacherModelConfig(BaseConfig):
] = ModelConfig()
class TeacherRolloutModelConfig(BaseConfig):
"""Configures an external teacher model used to generate rollout text."""
client: Annotated[
ClientConfig,
Field(description="The OAI client configuration for rollout generation."),
] = ClientConfig()
model: Annotated[
ModelConfig,
Field(description="The model configuration for rollout generation."),
] = ModelConfig()
class OrchestratorConfig(BaseConfig):
"""Configures the orchestrator for RL training."""
@@ -669,6 +706,17 @@ class OrchestratorConfig(BaseConfig):
),
] = None
# External teacher rollout model configuration (optional)
teacher_rollout_model: Annotated[
TeacherRolloutModelConfig | None,
Field(
description=(
"Optional external teacher model used for rollout generation. "
"When set, rollouts are generated from this endpoint/model instead of the student inference server."
),
),
] = None
# The sampling configuration
sampling: SamplingConfig = SamplingConfig()
@@ -893,6 +941,14 @@ class OrchestratorConfig(BaseConfig):
raise ValueError("max_inflight_rollouts must be at least the number of rollouts per example")
return self
@model_validator(mode="after")
def validate_unique_env_names(self):
env_names = [env.resolved_name for env in self.env]
duplicates = [n for n in env_names if env_names.count(n) > 1]
if duplicates:
raise ValueError(f"Duplicate environment names: {set(duplicates)}. Each env must have a unique name.")
return self
@model_validator(mode="after")
def validate_env_ratios(self):
if self.buffer.env_ratios is not None:
@@ -921,6 +977,13 @@ class OrchestratorConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_length_shaping_requires_online_difficulty_filtering(self):
if isinstance(self.advantage, DefaultAdvantageConfig) and self.advantage.length_shaping_alpha is not None:
if not self.buffer.online_difficulty_filtering:
raise ValueError("Group Relative Reward (GR³) scaling requires online difficulty filtering")
return self
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench:
@@ -939,7 +1002,7 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def resolve_extra_env_kwargs(self):
train_extra_env_kwargs = dict(
seq_len=self.seq_len,
max_seq_len=self.seq_len,
score_rollouts=self.verification.enabled,
)
for env in self.env:
+128 -28
View File
@@ -1,4 +1,3 @@
import warnings
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
@@ -38,6 +37,7 @@ from prime_rl.configs.trainer import (
NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig,
)
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.validation import (
validate_shared_ckpt_config,
validate_shared_max_async_level,
@@ -71,10 +71,31 @@ class SharedWandbConfig(BaseConfig):
offline: Annotated[bool | None, Field(description="Whether to run W&B in offline mode.")] = False
shared: Annotated[
bool,
Field(
description="Use shared W&B mode to log trainer and orchestrator metrics to a single run. "
"Requires wandb SDK >= 0.19.9. Incompatible with offline mode.",
),
] = True
@model_validator(mode="after")
def validate_shared_not_offline(self):
if self.shared and self.offline:
raise ValueError("W&B shared mode requires server connectivity and is incompatible with offline mode")
return self
class SharedCheckpointConfig(BaseConfig):
"""Configures shared checkpoint configs."""
output_dir: Annotated[
Path | None,
Field(
description="Override directory for checkpoints and weights. When set, checkpoints and weight snapshots are written here instead of under the trainer output_dir.",
),
] = None
interval: Annotated[int | None, Field(description="The interval at which to save checkpoints.")] = None
resume_step: Annotated[
@@ -116,6 +137,15 @@ class SharedWeightBroadcastConfig(BaseConfig):
port: Annotated[int, Field(description="The port to use for NCCL weight broadcast.")] = 29501
timeout: Annotated[int, Field(description="The timeout in seconds for NCCL weight broadcast.")] = 1200
quantize_in_weight_transfer: Annotated[
bool,
Field(
description=(
"Use kernel-format FP8 quantized NCCL transfer for weight updates. "
"When disabled, uses default HF checkpoint-format transfer."
),
),
] = False
class BaseDeploymentConfig(BaseModel):
@@ -152,7 +182,13 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
type: Literal["multi_node"] = "multi_node"
num_train_nodes: Annotated[int, Field(description="Number of training nodes.")]
num_infer_nodes: Annotated[int, Field(description="Number of inference nodes.")]
num_infer_nodes: Annotated[
int,
Field(
ge=0,
description="Number of inference nodes. Set to 0 to skip inference and orchestrator (requires fake data).",
),
]
num_teacher_nodes: Annotated[int | None, Field(description="Number of teacher inference nodes.")] = None
nodes_per_fsdp_group: Annotated[
@@ -291,8 +327,18 @@ class RLConfig(BaseConfig):
if self.deployment.type == "multi_node":
if self.slurm is None:
raise ValueError("Must use SLURM for multi-node deployment.")
if not self.inference:
raise ValueError("Must configure inference when using multi-node deployment.")
if self.deployment.num_infer_nodes > 0 and not self.inference:
raise ValueError("Must configure inference when using multi-node deployment with inference nodes.")
if self.deployment.num_infer_nodes == 0 and self.inference:
raise ValueError(
"Cannot configure inference with num_infer_nodes = 0. "
"Either set num_infer_nodes > 0 or remove the inference config."
)
if self.deployment.num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
raise ValueError(
"Must use fake data (trainer.data.fake or bench = true) when num_infer_nodes = 0, "
"since no orchestrator or inference server will be running."
)
return self
# TODO: fix this
@@ -315,6 +361,22 @@ class RLConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_quantize_in_weight_transfer(self):
if self.weight_broadcast is None or not self.weight_broadcast.quantize_in_weight_transfer:
return self
if self.weight_broadcast.type != "nccl":
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires weight_broadcast.type = 'nccl'.")
if self.inference is None:
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires an inference config.")
if self.trainer.model.impl != "custom":
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires trainer.model.impl = 'custom'.")
return self
@model_validator(mode="after")
def validate_teacher_model(self):
if (
@@ -326,6 +388,27 @@ 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
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:
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
@model_validator(mode="after")
@@ -363,6 +446,10 @@ class RLConfig(BaseConfig):
if self.orchestrator.ckpt is None:
self.orchestrator.ckpt = OrchestratorCheckpointConfig()
# If specified, override checkpoint output directory
if self.ckpt.output_dir is not None:
self.trainer.ckpt.output_dir = self.ckpt.output_dir
# If specified, use the same ckpt interval
if self.ckpt.interval is not None:
self.trainer.ckpt.interval = self.ckpt.interval
@@ -399,18 +486,25 @@ class RLConfig(BaseConfig):
self.trainer.wandb.project = self.wandb.project
self.orchestrator.wandb.project = self.wandb.project
# If specified, automatically use shared W&B name for orchestrator and trainer with suffixes
if self.wandb.name:
self.trainer.wandb.name = f"{self.wandb.name}-trainer"
self.orchestrator.wandb.name = f"{self.wandb.name}-orchestrator"
if self.wandb.shared:
if self.wandb.name:
self.trainer.wandb.name = self.wandb.name
self.orchestrator.wandb.name = self.wandb.name
else:
if self.wandb.name:
self.trainer.wandb.name = f"{self.wandb.name}-trainer"
self.orchestrator.wandb.name = f"{self.wandb.name}-orchestrator"
# If specified, automatically use shared W&B offline mode for orchestrator and trainer
if self.wandb.offline:
self.trainer.wandb.offline = self.wandb.offline
self.orchestrator.wandb.offline = self.wandb.offline
validate_shared_wandb_config(self.trainer, self.orchestrator)
if self.orchestrator.prime_monitor is not None and self.orchestrator.prime_monitor.run_name is None:
if self.wandb and self.wandb.name:
self.orchestrator.prime_monitor.run_name = self.wandb.name
return self
@model_validator(mode="after")
@@ -418,9 +512,13 @@ class RLConfig(BaseConfig):
"""Auto-setup shared model config for trainer, orchestrator, and inference."""
if self.model is not None:
self.trainer.model.name = self.model.name
self.orchestrator.model.name = self.model.name
if self.inference is not None:
self.inference.model.name = self.model.name
inference_model_explicitly_set = "name" in self.inference.model.model_fields_set
if not inference_model_explicitly_set:
self.inference.model.name = self.model.name
self.orchestrator.model.name = self.inference.model.name
else:
self.orchestrator.model.name = self.model.name
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
@@ -480,11 +578,13 @@ class RLConfig(BaseConfig):
inference_world_size=inference_world_size,
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
)
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type,
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
)
elif self.weight_broadcast.type == "filesystem":
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
@@ -560,7 +660,7 @@ class RLConfig(BaseConfig):
self.inference.enable_lora = True
self.inference.max_lora_rank = self.trainer.model.lora.rank
else:
warnings.warn(
get_logger().warning(
"LoRA is enabled, but inference is not configured. When manually starting the inference server, "
"make sure to set --enable_lora and --max-lora-rank."
)
@@ -572,12 +672,12 @@ class RLConfig(BaseConfig):
if self.trainer.enable_router_replay:
if self.inference is not None:
if self.inference.enable_return_routed_experts is False:
warnings.warn(
get_logger().warning(
"Router replay is enabled, but inference.enable_return_routed_experts is False. Setting to True."
)
self.inference.enable_return_routed_experts = True
else:
warnings.warn(
get_logger().warning(
"Router replay is enabled, but inference is not configured. When manually starting the inference server, make sure to pass `--enable-return-routed-experts` to the vLLM server."
)
return self
@@ -649,6 +749,20 @@ class RLConfig(BaseConfig):
return self
@model_validator(mode="after")
def auto_setup_dp_rank_count(self):
"""Auto-set orchestrator client dp_rank_count from inference DP size.
Uses data_parallel_size_local (per-node DP) when set, since each base URL
points to a single node whose API server only knows about its local ranks.
Falls back to the global parallel.dp for single-node setups.
"""
if self.inference is not None and "dp_rank_count" not in self.orchestrator.client.model_fields_set:
self.orchestrator.client.dp_rank_count = (
self.inference.data_parallel_size_local or self.inference.parallel.dp
)
return self
@model_validator(mode="after")
def auto_setup_teacher_inference(self):
"""Auto-configure teacher inference server and orchestrator teacher_model client."""
@@ -704,17 +818,3 @@ class RLConfig(BaseConfig):
return self
### Warnings
@model_validator(mode="after")
def warn_wandb_resume_id_missing(self):
if self.trainer.ckpt is not None and self.trainer.ckpt.resume_step is not None:
if self.trainer.wandb and not self.trainer.wandb.id:
warnings.warn(
"W&B run ID is not set for trainer even though resuming training. The current run will be created as a new run."
)
if self.orchestrator.ckpt is not None and self.orchestrator.ckpt.resume_step is not None:
if self.orchestrator.wandb and not self.orchestrator.wandb.id:
warnings.warn(
"W&B run ID is not set for orchestrator even though resuming training. The current run will be created as a new run."
)
return self
+37 -13
View File
@@ -106,6 +106,12 @@ class SFTDataConfig(BaseDataConfig):
return self
class SFTValConfig(BaseConfig):
interval: Annotated[int, Field(ge=1, description="Run validation every N training steps.")] = 50
eval_on_start: Annotated[bool, Field(description="Run validation before the first training step.")] = False
data: SFTDataConfig
DataConfig: TypeAlias = Annotated[FakeDataConfig | SFTDataConfig, Field(discriminator="type")]
@@ -163,6 +169,9 @@ class SFTConfig(BaseConfig):
# The data configuration
data: DataConfig = SFTDataConfig()
# Optional validation configuration
val: SFTValConfig | None = None
# The optimizer configuration
optim: OptimizerConfig = AdamWConfig()
@@ -216,7 +225,11 @@ class SFTConfig(BaseConfig):
] = 600
loss_impl: Annotated[
Literal["liger", "torch"], Field(description="Implementation of the cross entropy loss function to use.")
Literal["liger", "torch", "liger_fused"],
Field(
description="Implementation of the cross entropy loss function to use. "
"'liger_fused' fuses the lm_head projection with the CE loss to avoid materializing full logits."
),
] = "torch"
heartbeat: Annotated[
@@ -257,27 +270,37 @@ class SFTConfig(BaseConfig):
@model_validator(mode="after")
def validate_pack_function(self):
if self.model.cp > 1 and self.data.pack_function != "cat":
raise ValueError("Packing function must be 'cat' when CP is enabled")
if self.model.cp > 1:
if self.data.pack_function != "cat":
raise ValueError("Packing function must be 'cat' when CP is enabled")
if self.val is not None and self.val.data.pack_function != "cat":
raise ValueError("Validation packing function must be 'cat' when CP is enabled")
return self
@model_validator(mode="after")
def validate_cp_seq_len(self):
if self.model.cp > 1 and self.data.seq_len % self.model.cp != 0:
raise ValueError("Sequence length must be divisible by CP degree")
if self.model.cp > 1:
if self.data.seq_len % self.model.cp != 0:
raise ValueError("Sequence length must be divisible by CP degree")
if self.val is not None and self.val.data.seq_len % self.model.cp != 0:
raise ValueError("Validation sequence length must be divisible by CP degree")
return self
@model_validator(mode="after")
def validate_cp_micro_batch_size(self):
if self.model.cp > 1 and self.data.micro_batch_size != 1:
raise ValueError("Micro batch size must be 1 when CP is enabled")
if self.model.cp > 1:
if self.data.micro_batch_size != 1:
raise ValueError("Micro batch size must be 1 when CP is enabled")
if self.val is not None and self.val.data.micro_batch_size != 1:
raise ValueError("Validation micro batch size must be 1 when CP is enabled")
return self
@model_validator(mode="after")
def validate_seq_len(self):
if self.data.pack_function == "stack":
if self.data.seq_len % 256 != 0:
raise ValueError("The sequence length must be divisible by 256 when using pack function stack")
if self.data.pack_function == "stack" and self.data.seq_len % 256 != 0:
raise ValueError("The sequence length must be divisible by 256 when using pack function stack")
if self.val is not None and self.val.data.pack_function == "stack" and self.val.data.seq_len % 256 != 0:
raise ValueError("The validation sequence length must be divisible by 256 when using pack function stack")
return self
@model_validator(mode="after")
@@ -310,12 +333,13 @@ class SFTConfig(BaseConfig):
@model_validator(mode="after")
def validate_and_disable_chunked_loss(self):
if isinstance(self.model.fused_lm_head_chunk_size, int):
if isinstance(self.model.fused_lm_head_token_chunk_size, int):
raise ValueError(
"Chunked loss is not supported for SFT training yet, please set `model.fused_lm_head_chunk_size` to 'disabled'"
"Chunked loss is not supported for SFT training yet, please set "
"`model.fused_lm_head_token_chunk_size` to 'disabled'"
)
self.model.fused_lm_head_chunk_size = "disabled"
self.model.fused_lm_head_token_chunk_size = "disabled"
return self
@model_validator(mode="after")
+108 -9
View File
@@ -27,6 +27,50 @@ class SlurmConfig(BaseConfig):
str, Field(description="The SLURM partition to use. Will be passed as #SBATCH --partition.")
] = "cluster"
nodelist: Annotated[
str | None,
Field(description="Comma-separated list of specific nodes to run on. Passed as #SBATCH --nodelist."),
] = None
exclude: Annotated[
str | None,
Field(description="Comma-separated list of nodes to exclude. Passed as #SBATCH --exclude."),
] = None
account: Annotated[
str | None,
Field(description="SLURM account to charge. Passed as #SBATCH --account."),
] = None
time: Annotated[
str | None,
Field(description="Maximum wall time (e.g. '24:00:00', '7-00:00:00'). Passed as #SBATCH --time."),
] = None
pre_run_command: Annotated[
str | None,
Field(
description="Shell command to run on the head node before starting the job. "
"Runs after cd into project dir, .env sourcing, and venv activation. "
"Useful for cleanup routines like 'sudo pkill -f vllm'. "
"To run on all nodes, wrap with srun: 'srun bash -c \"pkill -f vllm || true\"'.",
),
] = None
@property
def template_vars(self) -> dict:
"""Common template variables for all SLURM templates."""
return {
"job_name": self.job_name,
"project_dir": self.project_dir,
"partition": self.partition,
"nodelist": self.nodelist,
"exclude": self.exclude,
"account": self.account,
"time": self.time,
"pre_run_command": self.pre_run_command,
}
@model_validator(mode="after")
def resolve_project_dir(self):
self.project_dir = self.project_dir.resolve()
@@ -94,6 +138,13 @@ class ClientConfig(BaseConfig):
),
] = 1200
connect_timeout: Annotated[
float,
Field(
description="TCP connect timeout in seconds for inference API requests.",
),
] = 30.0
base_url: Annotated[
list[str],
Field(
@@ -122,6 +173,22 @@ class ClientConfig(BaseConfig):
),
] = False
dp_rank_count: Annotated[
int,
Field(
ge=1,
description=(
"Number of data-parallel ranks behind each base URL. When > 1, "
"each URL is expanded into dp_rank_count logical clients, each "
"pinned to a specific DP rank via the X-data-parallel-rank header. "
"This ensures all requests within a multi-turn rollout hit the same "
"DP engine, maximizing KV cache reuse. Auto-set from "
"inference.data_parallel_size_local (or inference.parallel.dp) "
"when using the RL entrypoint."
),
),
] = 1
elastic: Annotated[
ElasticConfig | None,
Field(
@@ -129,6 +196,13 @@ class ClientConfig(BaseConfig):
),
] = None
router_url: Annotated[
str | None,
Field(
description="URL of a vllm-router for load-aware inference routing. When set with elastic mode, inference requests go through the router while admin operations (weight updates, LoRA loading) still go directly to discovered pods.",
),
] = None
@property
def is_elastic(self) -> bool:
"""Check if elastic mode is enabled."""
@@ -202,6 +276,18 @@ class LogExtrasConfig(BaseConfig):
),
] = 10
sample_ratio: Annotated[
float | None,
Field(
ge=0.0,
le=1.0,
description="Fraction of rollouts to log per step (0.0–1.0). "
"When set, the effective sample cap is len(rollouts) * sample_ratio. "
"1.0 = all rollouts, 0.5 = half, 0.0 = none. "
"None (default)",
),
] = None
class WandbConfig(BaseConfig):
"""Configures logging to Weights and Biases."""
@@ -218,14 +304,6 @@ class WandbConfig(BaseConfig):
offline: Annotated[bool, Field(description="Whether to run W&B in offline mode.")] = False
# Individual configs (can only be specified on trainer or orchestrator)
id: Annotated[
str | None,
Field(
description="The W&B run ID to log to. If None, a random ID will be generated. If you want to resume a run, you can set the ID to the run ID you want to resume.",
),
] = None
class WandbWithExtrasConfig(WandbConfig):
"""Configures logging to Weights and Biases with extras."""
@@ -246,7 +324,7 @@ class PrimeMonitorConfig(BaseConfig):
Field(
description="The base URL for Prime Intellect monitoring API.",
),
] = "https://api.primeintellect.ai/api/internal/rft"
] = "https://api.primeintellect.ai/api/v1/rft"
api_key_var: Annotated[
str,
@@ -262,6 +340,27 @@ class PrimeMonitorConfig(BaseConfig):
),
] = LogExtrasConfig()
run_name: Annotated[
str | None,
Field(
description="Name for the run shown on the platform. Defaults to the W&B run name if set, otherwise auto-generated by the platform.",
),
] = None
team_id: Annotated[
str | None,
Field(
description="Team ID to associate the run with.",
),
] = None
frontend_url: Annotated[
str | None,
Field(
description="Frontend base URL used for the dashboard link shown after registration. Defaults to the Prime CLI frontend URL when unset.",
),
] = None
class HeartbeatConfig(BaseConfig):
"""Configures the heartbeat for BetterStack."""
+45 -24
View File
@@ -1,4 +1,3 @@
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
@@ -14,6 +13,7 @@ from prime_rl.configs.shared import (
WandbConfig,
)
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.vlm import is_vlm_model
# -- Shared trainer configs (used by both SFT and RL trainers) --
@@ -269,13 +269,13 @@ class ModelConfig(BaseModelConfig):
),
] = DebugModelConfig()
fused_lm_head_chunk_size: Annotated[
fused_lm_head_token_chunk_size: Annotated[
int | Literal["auto", "disabled"],
Field(
description=(
"The chunk size to use for the fused LM head. "
"The flattened token chunk size to use for the fused LM head. "
"Three behaviors: "
"(1) int >= 512: explicitly set chunk size for fused LM head; "
"(1) int >= 1: explicitly set the number of tokens per LM-head chunk; "
"(2) 'auto': auto-enable (RL training auto-sets to 8192); "
"(3) 'disabled': explicitly disable fused LM head (use vanilla). "
"Explicitly setting an integer value for this feature isn't supported for SFT training."
@@ -299,6 +299,14 @@ class ModelConfig(BaseModelConfig):
raise ValueError("Trust remote code is only supported with the HF implementation or auto mode.")
return self
@model_validator(mode="after")
def vlms_require_bfloat16(self):
if is_vlm_model(self.name) and (self.optimization_dtype != "bfloat16" or self.reduce_dtype != "bfloat16"):
raise ValueError(
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
)
return self
@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"]:
@@ -323,22 +331,6 @@ class ModelConfig(BaseModelConfig):
raise ValueError("Cannot enable both fsdp_cpu_offload and optim_cpu_offload. Use one or the other.")
return self
@model_validator(mode="after")
def fused_lm_head_chunk_size_is_valid(self):
if isinstance(self.fused_lm_head_chunk_size, int):
low = 512
warn_threshold = 8192
if self.fused_lm_head_chunk_size < low:
raise ValueError(
f"Fused LM head chunk size must be at least {low}, got {self.fused_lm_head_chunk_size}"
)
if self.fused_lm_head_chunk_size < warn_threshold:
warnings.warn(
f"Fused LM head chunk size is set to {self.fused_lm_head_chunk_size}, which is less than the recommended threshold of {warn_threshold}. This may cause some runs to diverge due to numerical instability in floating point arithmetic."
)
return self
@model_validator(mode="after")
def flash_attention_4_only_with_custom_impl(self):
if self.attn == "fa4" and self.impl != "custom":
@@ -474,6 +466,13 @@ class WeightCheckpointConfig(BaseConfig):
class CheckpointConfig(BaseConfig):
"""Configures checkpointing the full model, optimizer and training state for resuming training."""
output_dir: Annotated[
Path | None,
Field(
description="Override directory for checkpoints and weights. When set, checkpoints and weight snapshots are written here instead of under the trainer output_dir. Useful for writing large checkpoints to a separate storage volume.",
),
] = None
interval: Annotated[
int | None,
Field(
@@ -484,6 +483,13 @@ class CheckpointConfig(BaseConfig):
weights: WeightCheckpointConfig | None = WeightCheckpointConfig()
weights_only: Annotated[
bool,
Field(
description="When true, only save weight checkpoints (no optimizer/scheduler state). Much faster and smaller than full checkpoints, but cannot resume training.",
),
] = False
resume_step: Annotated[
int | None,
Field(
@@ -542,6 +548,12 @@ class DefaultLossConfig(BaseModel):
kl_tau: Annotated[float, Field(ge=0, description="The tau for KL divergence.")] = 1e-3
class SFTLossConfig(BaseModel):
"""Config for SFT-style masked negative log-likelihood loss."""
type: Literal["sft"] = "sft"
class CustomLossConfig(BaseModel):
"""Config for a custom external loss function."""
@@ -551,7 +563,7 @@ class CustomLossConfig(BaseModel):
kwargs: Annotated[dict[str, Any], Field(default_factory=dict, description="Kwargs to pass to the loss function")]
LossConfig: TypeAlias = Annotated[DefaultLossConfig | CustomLossConfig, Field(discriminator="type")]
LossConfig: TypeAlias = Annotated[DefaultLossConfig | SFTLossConfig | CustomLossConfig, Field(discriminator="type")]
class FakeDataLoaderConfig(BaseConfig):
@@ -594,6 +606,15 @@ class NCCLWeightBroadcastConfig(BaseWeightBroadcastConfig):
timeout: Annotated[int, Field(description="The timeout in seconds to use for the NCCL broadcast.")] = 1200
# TODO: Should not be configurable, but auto-inferred
inference_world_size: Annotated[int, Field(description="The number of GPUs used for inference.")] = 1
quantize_in_weight_transfer: Annotated[
bool,
Field(
description=(
"Use kernel-format FP8 quantized NCCL transfer for weight updates. "
"When disabled, uses default HF checkpoint-format transfer."
),
),
] = False
WeightBroadcastConfig: TypeAlias = Annotated[
@@ -765,9 +786,9 @@ class TrainerConfig(BaseConfig):
return self
@model_validator(mode="after")
def auto_setup_fused_lm_head_chunk_size(self):
if self.model.fused_lm_head_chunk_size == "auto":
self.model.fused_lm_head_chunk_size = 8192
def auto_setup_fused_lm_head_token_chunk_size(self):
if self.model.fused_lm_head_token_chunk_size == "auto":
self.model.fused_lm_head_token_chunk_size = 8192
return self
+1 -3
View File
@@ -33,12 +33,10 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
template = env.get_template(config.slurm.template_path.name)
script = template.render(
**config.slurm.template_vars,
config_path=config_path,
output_dir=config.output_dir,
job_name=config.slurm.job_name,
project_dir=config.slurm.project_dir,
gpus_per_node=config.deployment.gpus_per_node,
partition=config.slurm.partition,
num_nodes=config.deployment.num_nodes if config.deployment.type == "multi_node" else 1,
port=config.server.port,
)
+34 -21
View File
@@ -132,6 +132,12 @@ def rl_local(config: RLConfig):
logger.info("Starting RL run")
logger.debug(f"RL start command: {' '.join(start_command)}")
# Build shared W&B env vars for subprocesses
wandb_shared_env: dict[str, str] = {}
if config.wandb and config.wandb.shared:
wandb_shared_env["WANDB_SHARED_MODE"] = "1"
wandb_shared_env["WANDB_SHARED_RUN_ID"] = uuid.uuid4().hex
# Check for existing processes on GPUs
all_gpu_ids = list(set(infer_gpu_ids + trainer_gpu_ids + teacher_gpu_ids))
check_gpus_available(all_gpu_ids)
@@ -191,9 +197,14 @@ def rl_local(config: RLConfig):
monitor_thread.start()
monitor_threads.append(monitor_thread)
else:
logger.warning(
"No inference config specified, skipping starting inference server. Make sure your inference server is running."
)
if config.orchestrator.teacher_rollout_model is None:
logger.warning(
"No inference config specified, skipping starting inference server. Make sure your inference server is running."
)
else:
logger.info(
"No inference config specified, using orchestrator.teacher_rollout_model for rollout generation."
)
# Optionally, start teacher inference process
if config.teacher_inference:
@@ -254,6 +265,8 @@ def rl_local(config: RLConfig):
stderr=log_file,
env={
**os.environ,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "orchestrator",
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
@@ -300,6 +313,8 @@ def rl_local(config: RLConfig):
trainer_cmd,
env={
**os.environ,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "trainer",
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
"LOGURU_FORCE_COLORS": "1",
@@ -382,30 +397,26 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
if config.deployment.type == "single_node":
script = template.render(
**config.slurm.template_vars,
config_path=config_dir / RL_TOML,
job_name=config.slurm.job_name,
project_dir=config.slurm.project_dir,
partition=config.slurm.partition,
output_dir=config.output_dir,
gpus_per_node=config.deployment.gpus_per_node,
)
else:
assert config.inference is not None
script = template.render(
**config.slurm.template_vars,
config_dir=config_dir, # TODO: should prob have each subconfig path separately
job_name=config.slurm.job_name,
project_dir=config.slurm.project_dir,
partition=config.slurm.partition,
output_dir=config.output_dir,
orchestrator_output_dir=config.orchestrator.output_dir,
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=config.deployment.num_infer_nodes,
num_teacher_nodes=config.deployment.num_teacher_nodes,
gpus_per_node=config.deployment.gpus_per_node,
inference_tp=config.inference.parallel.tp,
inference_enable_expert_parallel=config.inference.enable_expert_parallel,
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port,
inference_tp=config.inference.parallel.tp if config.inference else 1,
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port if config.inference else 29600,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
wandb_shared=config.wandb is not None and config.wandb.shared,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
@@ -434,12 +445,11 @@ def rl_slurm(config: RLConfig):
logger.info(f"Wrote subconfigs to {config_dir}")
slurm_log_dir = config.output_dir / "slurm"
log_message = (
f"Logs:\n"
f" Trainer: tail -F {slurm_log_dir}/latest_train_node_rank_0.log\n"
f" Orchestrator: tail -F {slurm_log_dir}/latest_orchestrator.log\n"
f" Inference: tail -F {slurm_log_dir}/latest_infer_node_rank_0.log"
)
log_lines = [f" Trainer: tail -F {slurm_log_dir}/latest_train_node_rank_0.log"]
if config.deployment.num_infer_nodes > 0:
log_lines.append(f" Orchestrator: tail -F {slurm_log_dir}/latest_orchestrator.log")
log_lines.append(f" Inference: tail -F {slurm_log_dir}/latest_infer_node_rank_0.log")
log_message = "Logs:\n" + "\n".join(log_lines)
script_path = config.output_dir / RL_SBATCH
write_slurm_script(config, config_dir, script_path)
@@ -461,8 +471,11 @@ def rl_slurm(config: RLConfig):
def rl(config: RLConfig):
resuming = config.ckpt is not None and config.ckpt.resume_step is not None
clean = config.clean_output_dir and not os.environ.get("NEVER_CLEAN_OUTPUT_DIR")
validate_output_dir(config.output_dir, resuming=resuming, clean=clean)
ckpt_output_dir = config.ckpt.output_dir if config.ckpt else None
validate_output_dir(config.output_dir, resuming=resuming, clean=clean, ckpt_output_dir=ckpt_output_dir)
config.output_dir.mkdir(parents=True, exist_ok=True)
if ckpt_output_dir is not None:
ckpt_output_dir.mkdir(parents=True, exist_ok=True)
if config.slurm is not None:
rl_slurm(config)
+2 -6
View File
@@ -39,22 +39,18 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path)
if config.deployment.type == "single_node":
script = template.render(
**config.slurm.template_vars,
config_path=config_path,
output_dir=config.output_dir,
job_name=config.slurm.job_name,
project_dir=config.slurm.project_dir,
gpus_per_node=config.deployment.gpus_per_node,
partition=config.slurm.partition,
)
else:
script = template.render(
**config.slurm.template_vars,
config_path=config_path,
output_dir=config.output_dir,
job_name=config.slurm.job_name,
project_dir=config.slurm.project_dir,
num_nodes=config.deployment.num_nodes,
gpus_per_node=config.deployment.gpus_per_node,
partition=config.slurm.partition,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
+108
View File
@@ -9,6 +9,59 @@ def transformers_v5_compat():
if not hasattr(Qwen3VLMoeTextConfig, "tie_word_embeddings"):
Qwen3VLMoeTextConfig.tie_word_embeddings = False
_patch_qwen35_lora()
def _patch_qwen35_lora():
"""Fix Qwen3.5 LoRA: align packed_modules_mapping with output_sizes.
Qwen3.5's GDN layers use create_qkvz_proj with 4 output_sizes (q, k, v, z)
but packed_modules_mapping only lists 2 entries, causing an IndexError
during LoRA initialization.
Also generalizes MergedColumnParallelLinearWithLoRA.can_replace_layer
to accept any number of packed modules (not just 2), and generalizes
MergedColumnParallelLinearWithShardedLoRA.slice_lora_a to handle N
subloras instead of the hardcoded 2 (needed for fully_sharded_loras=True).
Upstream: https://github.com/vllm-project/vllm/issues/36372
"""
from vllm.lora.layers.column_parallel_linear import (
MergedColumnParallelLinearWithLoRA,
MergedColumnParallelLinearWithShardedLoRA,
)
from vllm.model_executor.models.qwen3_5 import (
Qwen3_5ForCausalLMBase,
Qwen3_5ForConditionalGeneration,
)
qkvz_fix = ["in_proj_q", "in_proj_k", "in_proj_v", "in_proj_z"]
Qwen3_5ForCausalLMBase.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
Qwen3_5ForConditionalGeneration.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
from vllm.lora.layers.utils import _not_fully_sharded_can_replace
@classmethod
@_not_fully_sharded_can_replace
def can_replace_layer(cls, source_layer, lora_config, packed_modules_list, model_config=None):
from vllm.model_executor.layers.linear import MergedColumnParallelLinear
return type(source_layer) is MergedColumnParallelLinear and len(packed_modules_list) == len(
source_layer.output_sizes
)
MergedColumnParallelLinearWithLoRA.can_replace_layer = can_replace_layer
def slice_lora_a(self, lora_a):
output_shard_size = self.lora_a_stacked[0].shape[2]
output_start_idx = self.tp_rank * output_shard_size
return [
a[output_start_idx : output_start_idx + output_shard_size, :] if a is not None else None for a in lora_a
]
MergedColumnParallelLinearWithShardedLoRA.slice_lora_a = slice_lora_a
# Monkeypatch PrometheusStatLogger to avoid NotImplementedError for LoRA in DP mode
def monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode():
@@ -201,8 +254,27 @@ def monkey_patch_tokenize_params_validation():
)
return text
def _patched_get_encode_kwargs(self):
"""Use max_total_tokens (max_model_len) instead of max_input_tokens for HF tokenizer truncation.
The original uses max_input_tokens (= max_model_len - max_tokens) + 1, which causes HuggingFace's
tokenizer.encode() to left-truncate prompts before _token_len_check even runs.
"""
max_length = self.truncate_prompt_tokens
if max_length is not None and max_length < 0:
max_length = self.max_total_tokens
elif max_length is None and self.max_total_tokens is not None:
max_length = self.max_total_tokens + 1
return dict(
truncation=max_length is not None,
max_length=max_length,
add_special_tokens=self.add_special_tokens,
)
TokenizeParams._token_len_check = _patched_token_len_check
TokenizeParams._text_len_check = _patched_text_len_check
TokenizeParams.get_encode_kwargs = _patched_get_encode_kwargs
def monkey_patch_hermes_tool_parser_thread_safety():
@@ -272,6 +344,42 @@ def monkey_patch_hermes_tool_parser_thread_safety():
Hermes2ProToolParser.__init__ = _patched_init
def monkey_patch_tokenizer_thread_safety():
"""Patch HuggingFace tokenizer to make _encode_plus thread-safe.
Under concurrent request load, vLLM's API server calls _encode_plus from
multiple async handlers simultaneously. _encode_plus mutates the Rust
tokenizer's internal state via set_truncation_and_padding (enable_truncation/
enable_padding) and encode_special_tokens. The Rust backend uses RefCell-style
borrow tracking (PyO3), and concurrent mutable borrows cause it to panic
with ``RuntimeError: Already borrowed``.
Fix: wrap the entire _encode_plus method in a per-tokenizer threading lock
so that state mutation and the subsequent encode call are atomic.
"""
import threading
from transformers import PreTrainedTokenizerFast
_original_encode_plus = PreTrainedTokenizerFast._encode_plus
_locks: dict[int, threading.Lock] = {}
_meta_lock = threading.Lock()
def _get_lock(tokenizer_id: int) -> threading.Lock:
if tokenizer_id not in _locks:
with _meta_lock:
if tokenizer_id not in _locks:
_locks[tokenizer_id] = threading.Lock()
return _locks[tokenizer_id]
def _patched_encode_plus(self, *args, **kwargs):
lock = _get_lock(id(self._tokenizer))
with lock:
return _original_encode_plus(self, *args, **kwargs)
PreTrainedTokenizerFast._encode_plus = _patched_encode_plus
def monkey_patch_minimax_m2_for_lora():
"""Patch vLLM's MiniMaxM2 model for LoRA compatibility.
+6 -1
View File
@@ -133,6 +133,7 @@ from prime_rl.inference.patches import (
monkey_patch_load_lora_adapter,
monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode,
monkey_patch_tokenize_params_validation,
monkey_patch_tokenizer_thread_safety,
)
from prime_rl.inference.vllm.serving_chat_with_tokens import (
ChatCompletionRequestWithTokens,
@@ -147,6 +148,9 @@ monkey_patch_load_lora_adapter()
monkey_patch_tokenize_params_validation()
# NOTE: Monkeypatch Hermes tool parser to fix "Already borrowed" RuntimeError under concurrent load
monkey_patch_hermes_tool_parser_thread_safety()
# NOTE: Monkeypatch HF tokenizer to fix "Already borrowed" RuntimeError during concurrent chat template processing
# Can be removed once https://github.com/vllm-project/vllm/pull/36557 is merged and we upgrade vllm
monkey_patch_tokenizer_thread_safety()
logger = init_logger("vllm.entrypoints.openai.api_server")
@@ -207,12 +211,13 @@ async def init_broadcaster(request: Request):
host = data.get("host")
port = data.get("port")
timeout = data.get("timeout")
quantize_in_weight_transfer = data.get("quantize_in_weight_transfer", False)
# Support both legacy and new field names
server_rank = data.get("server_rank")
num_inference_server = data.get("num_inference_server")
await engine_client(request).collective_rpc(
"init_broadcaster",
args=(host, port, server_rank, num_inference_server, timeout),
args=(host, port, server_rank, num_inference_server, timeout, quantize_in_weight_transfer),
)
return {"status": "ok"}
+33 -8
View File
@@ -1,5 +1,5 @@
import pickle
from typing import TYPE_CHECKING, Generator, cast
from typing import TYPE_CHECKING, Callable, Generator, cast
import torch
from torch.nn import Module
@@ -7,7 +7,13 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
from vllm.distributed.parallel_state import get_dp_group, get_tp_group
from vllm.distributed.utils import StatelessProcessGroup
from vllm.logger import init_logger
from vllm.model_executor.model_loader.utils import process_weights_after_loading
from prime_rl.inference.vllm.worker.weight_transfer import (
load_weights_checkpoint,
load_weights_kernel,
postprocess_weights_checkpoint,
postprocess_weights_kernel,
)
# This is to get type hints for the Worker class but not actually extend it at runtime as this is required by vLLM worker extension
if TYPE_CHECKING:
@@ -86,8 +92,17 @@ class NCCLWeightBroadcastReceiver:
class NCCLWeightUpdateWorker(Worker):
"""vLLM worker extension for updating weights in-place using NCCL."""
def init_broadcaster(self, host: str, port: int, server_rank: int, num_inference_server: int, timeout: int) -> None:
def init_broadcaster(
self,
host: str,
port: int,
server_rank: int,
num_inference_server: int,
timeout: int,
quantize_in_weight_transfer: bool = False,
) -> None:
"""Initialize the NCCL broadcast receiver."""
self.quantize_in_weight_transfer = quantize_in_weight_transfer
tp_size = get_tp_group().world_size
tp_rank = get_tp_group().rank_in_group
dp_size = get_dp_group().world_size
@@ -111,12 +126,22 @@ class NCCLWeightUpdateWorker(Worker):
def update_weights_from_path(self, weight_dir: str) -> None:
"""Update weights with the nccl communicator."""
model_runner = self.model_runner
model = model_runner.model.runnable
if hasattr(model_runner.model, "runnable"):
model = model_runner.model.runnable
else:
model = model_runner.model
assert isinstance(model, Module)
state_iter = self.nccl_broadcast_receiver.receive_state_dict()
model.load_weights(state_iter) # type: ignore
# # Process weights after loading (important for some models)
device = next(model.parameters()).device
process_weights_after_loading(model, self.model_runner.model_config, device)
loader_fn: Callable[[Module, Generator[tuple[str, torch.Tensor], None, None]], None]
postprocess_fn: Callable[[Module, object, torch.device], None]
if self.quantize_in_weight_transfer:
loader_fn = load_weights_kernel
postprocess_fn = postprocess_weights_kernel
else:
loader_fn = load_weights_checkpoint
postprocess_fn = postprocess_weights_checkpoint
loader_fn(model, state_iter)
postprocess_fn(model, self.model_runner.model_config, device)
@@ -0,0 +1,108 @@
from typing import Generator
import torch
from torch.nn import Module
from vllm.logger import init_logger
from vllm.model_executor.model_loader.utils import process_weights_after_loading
logger = init_logger("vllm.inference.vllm.worker_weight_transfer")
def load_weights_checkpoint(model: Module, state_iter: Generator[tuple[str, torch.Tensor], None, None]) -> None:
model.load_weights(state_iter) # type: ignore
def postprocess_weights_checkpoint(model: Module, model_config, device: torch.device) -> None:
process_weights_after_loading(model, model_config, device)
def build_expert_map(model: Module) -> dict[str, torch.Tensor]:
"""Map FusedMoE module names to global expert indices local to this worker."""
from vllm.model_executor.layers.fused_moe.layer import FusedMoE
expert_slices: dict[str, torch.Tensor] = {}
for module_name, module in model.named_modules():
if not isinstance(module, FusedMoE):
continue
if module._expert_map is None:
continue
global_indices = torch.where(module._expert_map >= 0)[0]
local_indices = module._expert_map[global_indices]
global_indices = global_indices[local_indices.argsort()]
expert_slices[module_name] = global_indices
return expert_slices
@torch.no_grad()
def load_weights_kernel(model: Module, state_iter: Generator[tuple[str, torch.Tensor], None, None]) -> None:
"""Load vLLM kernel-format tensors using in-place copy_ updates."""
params = dict(model.named_parameters())
expert_slices = build_expert_map(model)
loaded = 0
skipped: list[str] = []
shape_mismatches: list[str] = []
for name, tensor in state_iter:
if name not in params:
skipped.append(name)
continue
param = params[name]
if param.shape != tensor.shape:
sliced = False
for module_name, global_indices in expert_slices.items():
if not name.startswith(f"{module_name}."):
continue
tensor = tensor[global_indices.to(tensor.device)]
sliced = True
break
if not sliced or param.shape != tensor.shape:
shape_mismatches.append(f"{name}: param={list(param.shape)} != received={list(tensor.shape)}")
continue
param.copy_(tensor)
loaded += 1
if shape_mismatches:
raise ValueError(f"Kernel weight transfer had {len(shape_mismatches)} shape mismatches: {shape_mismatches}")
if skipped:
raise ValueError(f"Kernel weight transfer skipped {len(skipped)} weights not found in model: {skipped}")
logger.debug(f"Kernel weight transfer copied {loaded} weights in-place")
@torch.no_grad()
def update_mla_absorbed_weights(model: Module) -> None:
"""Recompute MLA absorbed KV weights after in-place kv_b_proj updates."""
from vllm.model_executor.layers.quantization.utils.quant_utils import get_and_maybe_dequant_weights
for name, module in model.named_modules():
has_absorbed_weights = hasattr(module, "W_UV") or hasattr(module, "W_UK_T")
if not has_absorbed_weights or not hasattr(module, "kv_b_proj"):
continue
if hasattr(module, "W_UV"):
out_dtype = module.W_UV.dtype
else:
out_dtype = torch.bfloat16
kv_b_proj_weight = get_and_maybe_dequant_weights(module.kv_b_proj, out_dtype=out_dtype).T
kv_b_proj_weight = kv_b_proj_weight.view(
module.kv_lora_rank,
module.num_heads,
module.qk_nope_head_dim + module.v_head_dim,
)
w_uk, w_uv = kv_b_proj_weight.split([module.qk_nope_head_dim, module.v_head_dim], dim=-1)
if hasattr(module, "W_UV"):
module.W_UV.copy_(w_uv.transpose(0, 1))
if hasattr(module, "W_UK_T"):
module.W_UK_T.copy_(w_uk.permute(1, 2, 0))
logger.debug(f"Updated MLA absorbed weights for module {name}")
def postprocess_weights_kernel(model: Module, _model_config, _device: torch.device) -> None:
update_mla_absorbed_weights(model)
+17 -9
View File
@@ -33,16 +33,21 @@ Expected signature:
"""
def default_advantage_fn(inputs: AdvantageInputs, length_weighted_mean: bool = False) -> AdvantageOutputs:
def default_advantage_fn(
inputs: AdvantageInputs,
length_shaping_alpha: float | None = None,
) -> AdvantageOutputs:
"""Default GRPO advantage: reward minus per-problem baseline."""
if length_weighted_mean:
baseline = (inputs.rewards * inputs.completion_lengths).sum(
dim=1, keepdim=True
) / inputs.completion_lengths.sum(dim=1, keepdim=True)
else:
baseline = inputs.rewards.mean(dim=1, keepdim=True)
rewards = inputs.rewards
return AdvantageOutputs(advantages=inputs.rewards - baseline)
if length_shaping_alpha is not None:
completion_lengths = inputs.completion_lengths.to(dtype=rewards.dtype)
lengths_normalized = completion_lengths / completion_lengths.mean(dim=1, keepdim=True)
length_shaping = (1 + length_shaping_alpha * lengths_normalized) ** -1
rewards = rewards * length_shaping
baseline = rewards.mean(dim=1, keepdim=True)
return AdvantageOutputs(advantages=rewards - baseline)
def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
@@ -57,7 +62,10 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
return advantage_fn
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
return default_advantage_fn(inputs, length_weighted_mean=config.length_weighted_mean)
return default_advantage_fn(
inputs,
length_shaping_alpha=config.length_shaping_alpha,
)
return advantage_fn
+31
View File
@@ -261,6 +261,12 @@ class Buffer:
"""Returns the buffer metrics for the current step."""
metrics = {}
easy_examples_per_env = defaultdict(int)
hard_examples_per_env = defaultdict(int)
for example in self.easy_examples:
easy_examples_per_env[example["task"]] += 1
for example in self.hard_examples:
hard_examples_per_env[example["task"]] += 1
# sum over envs (e.g. log globally)
num_examples_per_step_per_pool = {
@@ -284,6 +290,31 @@ class Buffer:
for pool, pool_ratio in zip(self.POOLS, pool_ratios):
metrics[f"pool/{pool}"] = pool_ratio
for env in self.env_names:
env_num_examples_per_step_per_pool = self.num_examples_per_step[env]
env_num_rollouts_per_step_per_pool = self.num_rollouts_per_step[env]
env_num_examples_per_step = sum(env_num_examples_per_step_per_pool.values())
env_num_rollouts_per_step = sum(env_num_rollouts_per_step_per_pool.values())
for pool in ["easy", "hard"]:
if env_num_examples_per_step:
metrics[f"evicted_examples/{env}/{pool}"] = (
env_num_examples_per_step_per_pool[pool] / env_num_examples_per_step
)
if env_num_rollouts_per_step:
metrics[f"filtered_rollouts/{env}/{pool}"] = (
env_num_rollouts_per_step_per_pool[pool] / env_num_rollouts_per_step
)
env_pool_counts = [
easy_examples_per_env[env],
len(self.example_buffer[env]),
hard_examples_per_env[env],
]
env_pool_ratios = mean_normalize(env_pool_counts)
for pool, pool_ratio in zip(self.POOLS, env_pool_ratios):
metrics[f"pool/{env}/{pool}"] = pool_ratio
self.reset_step_metrics()
return metrics
+184 -144
View File
@@ -1,4 +1,6 @@
import asyncio
import atexit
import gc
import multiprocessing as mp
import random
import time
@@ -10,7 +12,12 @@ from prime_rl.orchestrator.advantage import compute_advantages
from prime_rl.orchestrator.eval_utils import compute_eval_ckpt_step, get_eval_sampling_args
from prime_rl.orchestrator.event_loop_lag import EventLoopLagMonitor
from prime_rl.orchestrator.patches import monkey_patch_chat_completion_logprobs, monkey_patch_oai_iterable_types
from prime_rl.orchestrator.trajectories import build_vlm_image_cache, interleave_rollout
from prime_rl.orchestrator.trajectories import (
build_vlm_image_cache,
interleave_rollout,
offload_images_to_disk,
pretokenize_rollout_trajectory,
)
from prime_rl.transport import TrainingBatch, TrainingSample, setup_training_batch_sender
from prime_rl.utils.pathing import get_log_dir
@@ -39,6 +46,7 @@ from prime_rl.orchestrator.utils import (
get_weight_dir,
print_benchmark,
set_semaphore,
setup_external_rollout_model,
)
from prime_rl.orchestrator.vf_utils import (
generate,
@@ -103,14 +111,18 @@ async def orchestrate(config: OrchestratorConfig):
for env_id in env_ids_to_install:
install_env(env_id)
# Setup inference pool (handles both static and elastic modes)
# 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)
client_type = "openai_chat_completions_token" if config.use_token_client else "openai_chat_completions"
if config.use_token_client:
logger.warning(
"Token-in-token-out (TITO) client is enabled. Only use this if your environment has a linear "
"history and the chat template has the extension property."
)
inference_pool = await setup_inference_pool(config.client, model_name=config.model.name, client_type=client_type)
inference_pool = await setup_inference_pool(
rollout_client_config, model_name=rollout_model_name, client_type=client_type
)
# Setup teacher inference pool if configured
if config.teacher_model:
@@ -138,11 +150,6 @@ async def orchestrate(config: OrchestratorConfig):
config.model.name, trust_remote_code=config.model.trust_remote_code, use_fast=True
)
# Build rollout filters
rollout_filters = setup_filters(config.filters, vocab_size=tokenizer.vocab_size)
if rollout_filters:
logger.info(f"Initialized {len(rollout_filters)} rollout filter(s): {[f.name for f in rollout_filters]}")
# Setup monitor
logger.info(f"Initializing monitor (wandb={config.wandb}, prime_monitor={config.prime_monitor})")
monitor = setup_monitor(
@@ -159,6 +166,11 @@ async def orchestrate(config: OrchestratorConfig):
logger.info("Initializing heartbeat")
heart = Heartbeat(config.heartbeat.url)
# Build rollout filters
rollout_filters = setup_filters(config.filters, vocab_size=tokenizer.vocab_size)
if rollout_filters:
logger.info(f"Initialized {len(rollout_filters)} rollout filter(s): {[f.name for f in rollout_filters]}")
# Load environment and extract dataset
logger.info(
f"Loading {len(config.env)} training environment(s) ({', '.join(env.name or env.id for env in config.env)})"
@@ -192,6 +204,17 @@ async def orchestrate(config: OrchestratorConfig):
train_env_addresses = []
env_processes: list[mp.Process] = []
def _cleanup_env_processes():
for proc in env_processes:
proc.terminate()
proc.join(timeout=5)
if proc.is_alive():
proc.kill()
proc.join(timeout=5)
atexit.register(_cleanup_env_processes)
for env_id, env, env_name in zip(env_ids, config.env, train_env_names):
if env.address is None:
address, process = spawn_env_server(
@@ -298,18 +321,21 @@ async def orchestrate(config: OrchestratorConfig):
max_off_policy_steps=config.max_off_policy_steps,
strict_async_level=config.strict_async_level,
tasks_per_minute=config.tasks_per_minute,
enable_policy_updates=enable_policy_updates,
lora_name=config.model.lora.name if config.model.lora else None,
deferred_group_scoring_tasks=train_env_deferred_group_scoring_tasks,
config=config,
)
scheduler.model_name = rollout_model_name
if checkpoint_step is not None and config.model.lora is not None:
if checkpoint_step is not None and config.model.lora is not None and enable_policy_updates:
assert config.model.lora.name is not None
scheduler.model_name = config.model.lora.name
# Check health of the inference pool
logger.info("Waiting for inference pool to be ready")
await inference_pool.wait_for_ready(config.model.name)
await inference_pool.wait_for_ready(rollout_model_name)
logger.success("Inference pool ready")
# Check health of teacher inference server if configured
@@ -319,14 +345,18 @@ async def orchestrate(config: OrchestratorConfig):
logger.success("Teacher inference pool ready")
# Set up weight broadcast backend
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
if config.weight_broadcast.type == "nccl":
await init_nccl_broadcast(
inference_pool.admin_clients,
config.weight_broadcast.host,
config.weight_broadcast.port,
config.weight_broadcast.timeout,
)
if enable_policy_updates:
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
if config.weight_broadcast.type == "nccl":
await init_nccl_broadcast(
inference_pool.admin_clients,
config.weight_broadcast.host,
config.weight_broadcast.port,
config.weight_broadcast.timeout,
quantize_in_weight_transfer=config.weight_broadcast.quantize_in_weight_transfer,
)
else:
logger.info("Skipping weight broadcast initialization (SFT distillation mode)")
# Setup training batch sender for sending training examples to trainer
logger.info(f"Initializing training batch sender ({config.rollout_transport})")
@@ -352,14 +382,15 @@ async def orchestrate(config: OrchestratorConfig):
# Allow eval at resumed step by setting prev_ckpt_step one behind
prev_ckpt_step = scheduler.ckpt_step - 1
# In NCCL mode, skip existence check - weights are broadcasted, not stored on disk
check_exists = config.weight_broadcast.type != "nccl"
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else None
weights_path = get_weight_dir(
config.output_dir, scheduler.ckpt_step, check_exists=check_exists, wait_timeout=wait_timeout
)
lora_name = config.model.lora.name if config.model.lora else None
await inference_pool.update_weights(weights_path, lora_name=lora_name, step=scheduler.ckpt_step)
if enable_policy_updates:
# In NCCL mode, skip existence check - weights are broadcasted, not stored on disk
check_exists = config.weight_broadcast.type != "nccl"
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else None
weights_path = get_weight_dir(
config.output_dir, scheduler.ckpt_step, check_exists=check_exists, wait_timeout=wait_timeout
)
lora_name = config.model.lora.name if config.model.lora else None
await inference_pool.update_weights(weights_path, lora_name=lora_name, step=scheduler.ckpt_step)
else:
logger.info("Training from scratch")
@@ -369,10 +400,6 @@ async def orchestrate(config: OrchestratorConfig):
is_first_step = True
await set_semaphore(config.max_concurrent or -1)
# Track consecutive empty batches for retry logic
empty_batch_retries = 0
max_empty_batch_retries = 5
# Persistent ThreadPoolExecutor for parallel rollout processing
rollout_executor = ThreadPoolExecutor(max_workers=64)
@@ -384,7 +411,8 @@ async def orchestrate(config: OrchestratorConfig):
raise RuntimeError(f"Run evicted by trainer: {reason}")
# Capture ckpt_step once for consistency (it's updated inside the scheduler)
ckpt_step = scheduler.ckpt_step
ckpt_step = scheduler.ckpt_step if enable_policy_updates else progress.step
scheduler.ckpt_step = ckpt_step
# Save checkpoint (if we are at an interval step and not at the first or last step)
is_last_step = config.max_steps is not None and progress.step == config.max_steps - 1
@@ -462,7 +490,9 @@ async def orchestrate(config: OrchestratorConfig):
# Schedule generating the training batch
temperature = compute_temperature(progress.step, config.sampling, config.max_steps)
sampling_args = get_sampling_args(config.sampling, temperature=temperature)
sampling_args = get_sampling_args(
config.sampling, temperature=temperature, use_token_client=config.use_token_client
)
scheduler.set_sampling_args(sampling_args)
train_task = asyncio.create_task(scheduler.generate_batch(step=progress.step))
@@ -489,6 +519,15 @@ async def orchestrate(config: OrchestratorConfig):
generate_completions_time = scheduler.last_batch_generation_time
train_rollouts = train_task.result()
# VLM: offload base64 images to disk immediately to free memory
if is_vlm:
offload_start = time.perf_counter()
num_offloaded = offload_images_to_disk(train_rollouts, config.output_dir)
if num_offloaded:
logger.info(
f"VLM offloaded {num_offloaded} unique images to disk in {time.perf_counter() - offload_start:.2f}s"
)
# Apply rollout filters (zeros reward/mask for degenerate generations)
filter_metrics = apply_filters(rollout_filters, train_rollouts)
@@ -508,6 +547,10 @@ async def orchestrate(config: OrchestratorConfig):
# Convert rollouts to training samples
parallel_preprocess_start = time.perf_counter()
# Pretokenize before VLM image cache build (which strips image data from messages)
for rollout in train_rollouts:
pretokenize_rollout_trajectory(rollout, tokenizer, processor=processor)
# VLM: build image cache for efficient batched preprocessing
if is_vlm:
vlm_cache = build_vlm_image_cache(train_rollouts, processor)
@@ -582,31 +625,14 @@ async def orchestrate(config: OrchestratorConfig):
step=progress.step,
)
# Retry with exponential backoff if batch is empty (e.g., inference temporarily unavailable)
if len(training_batch.examples) == 0:
empty_batch_retries += 1
if empty_batch_retries >= max_empty_batch_retries:
raise RuntimeError(
f"Step {progress.step} failed after {max_empty_batch_retries} consecutive empty batches"
)
backoff = min(30 * (2 ** (empty_batch_retries - 1)), 300) # 30s, 60s, 120s, 240s, 300s cap
logger.warning(
f"Step {progress.step} produced 0 training samples "
f"(attempt {empty_batch_retries}/{max_empty_batch_retries}). Retrying in {backoff}s..."
)
# Cancel validation task to avoid accumulating background tasks
val_task.cancel()
await asyncio.sleep(backoff)
continue
# Reset retry counter on successful batch
empty_batch_retries = 0
training_batch_sender.send(training_batch)
# Await and process val results
await val_task
val_outputs = val_task.result()
step_time = time.perf_counter() - step_start_time
# Gather metrics in dataframes
results_df = pd.DataFrame(
{
@@ -614,7 +640,7 @@ async def orchestrate(config: OrchestratorConfig):
"task": [rollout["task"] for rollout in train_rollouts],
"reward": [rollout["reward"] for rollout in train_rollouts],
"is_truncated": [rollout["is_truncated"] for rollout in train_rollouts],
"error": [rollout["error"] 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,
"decode_len": rollout_decode_lens,
@@ -625,7 +651,7 @@ async def orchestrate(config: OrchestratorConfig):
}
)
# Gather individual reward function metrics
# Separate DataFrame for env reward function metrics to avoid column name collisions
metrics_df = pd.DataFrame([rollout["metrics"] for rollout in train_rollouts])
val_results_df = (
@@ -640,21 +666,23 @@ async def orchestrate(config: OrchestratorConfig):
else None
)
# Update progress metrics and throughput
# Update progress metrics
num_tokens = int(results_df.seq_len.sum())
progress.total_tokens += num_tokens
progress.total_samples += num_rollouts
progress.total_problems += num_unique_examples
throughput = num_tokens / generate_completions_time
# Compute solve all and none tensors
problem_indices = results_df.index // config.rollouts_per_example
reward_sum_per_problem = results_df.groupby(problem_indices).reward.sum()
solve_all = (reward_sum_per_problem == config.rollouts_per_example).mean()
solve_none = (reward_sum_per_problem == 0).mean()
effective_batch_size = 1 - solve_none - solve_all
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()
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
step_time = time.perf_counter() - step_start_time
# Group by example_id to average across rollouts within each problem
by_example = results_df.groupby("example_id")
solve_none, solve_all, effective_batch_size = compute_solve_rates(results_df)
to_log = {
# Progress metrics
"progress/tokens": num_tokens,
@@ -667,57 +695,47 @@ async def orchestrate(config: OrchestratorConfig):
"progress/total_problems": progress.total_problems,
"progress/ckpt_step": ckpt_step, # Shared W&B axis
# Sequence length metrics
"seq_len/mean": results_df.groupby("example_id").seq_len.mean().mean(),
"seq_len/max": results_df.groupby("example_id").seq_len.mean().max(),
"seq_len/min": results_df.groupby("example_id").seq_len.mean().min(),
"prefill_len/mean": results_df.groupby("example_id").prefill_len.mean().mean(),
"prefill_len/max": results_df.groupby("example_id").prefill_len.mean().max(),
"prefill_len/min": results_df.groupby("example_id").prefill_len.mean().min(),
"decode_len/mean": results_df.groupby("example_id").decode_len.mean().mean(),
"decode_len/max": results_df.groupby("example_id").decode_len.mean().max(),
"decode_len/min": results_df.groupby("example_id").decode_len.mean().min(),
"is_truncated/mean": results_df.groupby("example_id").is_truncated.mean().mean(),
"is_truncated/max": results_df.groupby("example_id").is_truncated.mean().max(),
"is_truncated/min": results_df.groupby("example_id").is_truncated.mean().min(),
# Seqs per rollout metrics
"samples_per_rollout/mean": results_df.groupby("example_id").samples_per_rollout.mean().mean(),
"samples_per_rollout/max": results_df.groupby("example_id").samples_per_rollout.mean().max(),
"samples_per_rollout/min": results_df.groupby("example_id").samples_per_rollout.mean().min(),
# Turn metrics
"num_turns/mean": results_df.groupby("example_id").num_turns.mean().mean(),
"num_turns/max": results_df.groupby("example_id").num_turns.mean().max(),
"num_turns/min": results_df.groupby("example_id").num_turns.mean().min(),
# Verifier timing metrics
"generation_ms/mean": results_df.groupby("example_id").generation_ms.mean().mean(),
"generation_ms/max": results_df.groupby("example_id").generation_ms.mean().max(),
"generation_ms/min": results_df.groupby("example_id").generation_ms.mean().min(),
"scoring_ms/mean": results_df.groupby("example_id").scoring_ms.mean().mean(),
"scoring_ms/max": results_df.groupby("example_id").scoring_ms.mean().max(),
"scoring_ms/min": results_df.groupby("example_id").scoring_ms.mean().min(),
# Performance metrics
"perf/throughput": throughput,
# Train reward
"reward/mean": results_df.reward.mean(),
"reward/std": results_df.reward.std(),
"reward/min": results_df.reward.min(),
"reward/max": results_df.reward.max(),
"reward/median": results_df.reward.median(),
"sampling/temperature": temperature,
# Batch metrics
"batch/solve_none": solve_none,
"batch/solve_all": solve_all,
"batch/effective_batch_size": effective_batch_size,
# Error metrics
"error/mean": (~results_df.error.isna()).mean(),
"seq_len/all/mean": by_example.seq_len.mean().mean(),
"seq_len/all/max": by_example.seq_len.mean().max(),
"seq_len/all/min": by_example.seq_len.mean().min(),
"prefill_len/all/mean": by_example.prefill_len.mean().mean(),
"prefill_len/all/max": by_example.prefill_len.mean().max(),
"prefill_len/all/min": by_example.prefill_len.mean().min(),
"decode_len/all/mean": by_example.decode_len.mean().mean(),
"decode_len/all/max": by_example.decode_len.mean().max(),
"decode_len/all/min": by_example.decode_len.mean().min(),
"is_truncated/all/mean": by_example.is_truncated.mean().mean(),
"is_truncated/all/max": by_example.is_truncated.mean().max(),
"is_truncated/all/min": by_example.is_truncated.mean().min(),
"stop_condition/all/generation_truncated": (
results_df.is_truncated & (results_df.stop_condition != "prompt_too_long")
).mean(),
**{
f"error/{error}": error_rate
for error, error_rate in results_df.error.dropna()
.apply(lambda e: e.get("error") if isinstance(e, dict) else e)
.value_counts(normalize=True)
.items()
f"stop_condition/all/{sc}": rate
for sc, rate in results_df.stop_condition.dropna().value_counts(normalize=True).items()
},
# Env metrics
**{f"metrics/{metric}": metrics_df[metric].mean() for metric in metrics_df.columns},
"samples_per_rollout/all/mean": by_example.samples_per_rollout.mean().mean(),
"samples_per_rollout/all/max": by_example.samples_per_rollout.mean().max(),
"samples_per_rollout/all/min": by_example.samples_per_rollout.mean().min(),
"num_turns/all/mean": by_example.num_turns.mean().mean(),
"num_turns/all/max": by_example.num_turns.mean().max(),
"num_turns/all/min": by_example.num_turns.mean().min(),
"generation_ms/all/mean": by_example.generation_ms.mean().mean(),
"generation_ms/all/max": by_example.generation_ms.mean().max(),
"generation_ms/all/min": by_example.generation_ms.mean().min(),
"scoring_ms/all/mean": by_example.scoring_ms.mean().mean(),
"scoring_ms/all/max": by_example.scoring_ms.mean().max(),
"scoring_ms/all/min": by_example.scoring_ms.mean().min(),
# Train reward
"reward/all/mean": by_example.reward.mean().mean(),
"reward/all/max": by_example.reward.mean().max(),
"reward/all/min": by_example.reward.mean().min(),
"sampling/temperature": temperature,
# Solve / batch metrics
"solve_none/all": solve_none,
"solve_all/all": solve_all,
"effective_batch_size/all": effective_batch_size,
**{f"batch/{env}": r for env, r in results_df.task.value_counts(normalize=True).items()},
# Time metrics
"time/step": step_time,
"time/generate_completions": generate_completions_time,
@@ -736,32 +754,51 @@ async def orchestrate(config: OrchestratorConfig):
"step": progress.step,
}
# If more than one env, add per-env metrics
if results_df.task.nunique() > 1:
per_env_reward = results_df.groupby("task").reward.mean().to_dict()
to_log.update({f"reward/{env}": reward for env, reward in per_env_reward.items()})
# Per-env metrics
per_env_columns = [
"seq_len",
"prefill_len",
"decode_len",
"is_truncated",
"samples_per_rollout",
"num_turns",
"generation_ms",
"scoring_ms",
]
per_env_ratio = results_df.task.value_counts(normalize=True).to_dict()
to_log.update({f"batch/{env}": ratio for env, ratio in per_env_ratio.items()})
for env, env_df in results_df.groupby("task"):
env_by_example = env_df.groupby("example_id")
for col in per_env_columns:
to_log[f"{col}/{env}/mean"] = env_by_example[col].mean().mean()
to_log[f"{col}/{env}/max"] = env_by_example[col].mean().max()
to_log[f"{col}/{env}/min"] = env_by_example[col].mean().min()
to_log[f"reward/{env}/mean"] = env_by_example.reward.mean().mean()
to_log[f"reward/{env}/max"] = env_by_example.reward.mean().max()
to_log[f"reward/{env}/min"] = env_by_example.reward.mean().min()
solve_none, solve_all, effective_batch_size = compute_solve_rates(env_df)
to_log[f"solve_none/{env}"] = solve_none
to_log[f"solve_all/{env}"] = solve_all
to_log[f"effective_batch_size/{env}"] = effective_batch_size
to_log[f"stop_condition/{env}/generation_truncated"] = (
env_df.is_truncated & (env_df.stop_condition != "prompt_too_long")
).mean()
for sc, rate in env_df.stop_condition.dropna().value_counts(normalize=True).items():
to_log[f"stop_condition/{env}/{sc}"] = rate
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()
# Optionally, add val metrics
if val_results_df is not None:
to_log.update(
{
"val_reward/mean": val_results_df.reward.mean(),
"val_reward/std": val_results_df.reward.std(),
"val_reward/min": val_results_df.reward.min(),
"val_reward/max": val_results_df.reward.max(),
"val_reward/median": val_results_df.reward.median(),
}
)
if val_results_df.task.nunique() > 1:
per_env_reward = val_results_df.groupby("task").reward.mean().to_dict()
to_log.update({f"val_reward/{env}": reward for env, reward in per_env_reward.items()})
per_env_ratio = val_results_df.task.value_counts(normalize=True).to_dict()
to_log.update({f"val_batch/{env}": ratio for env, ratio in per_env_ratio.items()})
val_by_example = val_results_df.groupby("example_id")
to_log["val/reward/all/mean"] = val_by_example.reward.mean().mean()
to_log["val/reward/all/max"] = val_by_example.reward.mean().max()
to_log["val/reward/all/min"] = val_by_example.reward.mean().min()
for env, env_df in val_results_df.groupby("task"):
env_by_example = env_df.groupby("example_id")
to_log[f"val/reward/{env}/mean"] = env_by_example.reward.mean().mean()
to_log[f"val/reward/{env}/max"] = env_by_example.reward.mean().max()
to_log[f"val/reward/{env}/min"] = env_by_example.reward.mean().min()
# Log metrics to monitor(s)
monitor.log(to_log, step=progress.step)
@@ -779,16 +816,23 @@ async def orchestrate(config: OrchestratorConfig):
step=progress.step,
)
# Flush all accumulated metrics for this step
monitor.flush(step=progress.step)
step_message = f"Step {progress.step} | Time: {step_time:.2f}s | Reward: {results_df.reward.mean():.4f} |{f' Val. Reward: {val_results_df.reward.mean():.4f} |' if val_results_df is not None else ''} Throughput: {throughput:.1f} tokens/s | Seq. Length: {results_df.groupby('example_id').seq_len.mean().mean():.1f} tokens/sample | Async Level: {scheduler.async_level} | Max. Off-Policy Level: {scheduler.max_off_policy_level}"
reward_mean = by_example.reward.mean().mean()
val_reward_str = ""
if val_results_df is not None:
val_reward_mean = val_results_df.groupby("example_id").reward.mean().mean()
val_reward_str = f" Val. Reward: {val_reward_mean:.4f} |"
step_message = f"Step {progress.step} | Time: {step_time:.2f}s | Reward: {reward_mean:.4f} |{val_reward_str} 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}"
logger.success(step_message)
# Increment step
progress.step += 1
is_first_step = False
# Free large per-step objects to prevent memory accumulation
del train_rollouts, train_examples, training_batch, vlm_cache
del results_df, metrics_df, val_results_df
gc.collect()
event_loop_lag_monitor.reset()
# Send heartbeat if configured
@@ -842,13 +886,9 @@ async def orchestrate(config: OrchestratorConfig):
# Cancel event loop lag monitor task
event_loop_lag_monitor_task.cancel()
# Shutdown env processes
for process in env_processes:
process.terminate()
process.join(timeout=5)
if process.is_alive():
process.kill()
process.join(timeout=5)
# Shutdown env processes (also registered as atexit handler for crash safety)
atexit.unregister(_cleanup_env_processes)
_cleanup_env_processes()
logger.success("Orchestrator finished.")
+161 -59
View File
@@ -2,7 +2,7 @@ from __future__ import annotations
import asyncio
import time
from collections import Counter
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from typing import NamedTuple, cast
@@ -30,6 +30,7 @@ class InflightRolloutInfo(NamedTuple):
off_policy_steps: int
client_config: vf.ClientConfig
task: str
group_id: int | None = None
@@ -40,6 +41,7 @@ class GroupState:
example: dict
rollouts_to_schedule: int
completed_rollouts: list[vf.RolloutOutput] = field(default_factory=list)
pinned_client: vf.ClientConfig | None = None
class Scheduler:
@@ -64,6 +66,7 @@ class Scheduler:
max_off_policy_steps: int,
strict_async_level: bool,
tasks_per_minute: int | None,
enable_policy_updates: bool = True,
lora_name: str | None = None,
deferred_group_scoring_tasks: set[str] | None = None,
):
@@ -82,15 +85,19 @@ class Scheduler:
self.max_async_level = max_async_level
self.max_off_policy_steps = max_off_policy_steps
self.strict_async_level = strict_async_level
self.enable_policy_updates = enable_policy_updates
self.lora_name = lora_name
initial_temp = compute_temperature(step=0, sampling_config=config.sampling, max_steps=config.max_steps)
self.sampling_args = get_sampling_args(config.sampling, temperature=initial_temp)
self.sampling_args = get_sampling_args(
config.sampling, temperature=initial_temp, use_token_client=config.use_token_client
)
self.model_name = self.config.model.name
self.json_logging = config.log.json_logging
# Inference pool - used for admin operations (adapter sync) and metrics
self.inference_pool = inference_pool
self.max_retries_by_task = {env.resolved_name: env.max_retries for env in config.env}
self.deferred_group_scoring_tasks = set(deferred_group_scoring_tasks or ())
if self.deferred_group_scoring_tasks:
task_list = ", ".join(sorted(self.deferred_group_scoring_tasks))
@@ -108,7 +115,12 @@ class Scheduler:
self.checkpoint_ready.set()
self.update_weights_time, self.wait_for_ckpt_time = 0, 0
self.update_policy_task: asyncio.Task | None = None
self.inflight_policy_update_task: asyncio.Task | None = None
self.policy_update_lock = asyncio.Lock()
self.cancelled_rollouts_count = 0
self.empty_rollouts_by_task: dict[str, int] = defaultdict(int)
self.errored_rollouts_by_task: dict[str, int] = defaultdict(int)
self.total_rollouts_by_task: dict[str, int] = defaultdict(int)
self.last_batch_generation_time = 0.0
@property
@@ -145,16 +157,22 @@ class Scheduler:
self.groups.clear()
self.cancelled_rollouts_count += count
@staticmethod
def _client_identity(c: vf.ClientConfig) -> tuple[str, str | None]:
return (c.api_base_url, c.extra_headers.get("X-data-parallel-rank"))
async def _select_least_loaded_client(self) -> vf.ClientConfig:
"""Select the client with the fewest in-flight tasks."""
"""Select the client with the fewest in-flight tasks.
Uses (api_base_url, dp_rank) as identity rather than client_idx so that
load tracking survives elastic pool refreshes (which reassign indices).
"""
clients = self.inference_pool.clients
while not clients:
await asyncio.sleep(1)
clients = self.inference_pool.clients
inflight_by_url = Counter()
for info in self.inflight_requests.values():
inflight_by_url[info.client_config.api_base_url] += 1
return min(clients, key=lambda c: inflight_by_url[c.api_base_url])
inflight = Counter(self._client_identity(info.client_config) for info in self.inflight_requests.values())
return min(clients, key=lambda c: inflight[self._client_identity(c)])
async def drop_group(self, group_id: int) -> int:
"""Drop a group and cancel any remaining in-flight rollouts for it."""
@@ -176,9 +194,13 @@ class Scheduler:
if group is None or group.rollouts_to_schedule <= 0:
return
group.rollouts_to_schedule -= 1
client_config = await self._select_least_loaded_client()
if group_id not in self.groups:
return
if group.pinned_client is not None:
client_config = group.pinned_client
else:
client_config = await self._select_least_loaded_client()
if group_id not in self.groups:
return
group.pinned_client = client_config
run_rollout_task = asyncio.create_task(
run_rollout(
env=self.env,
@@ -186,11 +208,11 @@ class Scheduler:
example=group.example,
model_name=self.model_name,
sampling_args=self.sampling_args,
max_retries=0, # TODO: make configurable
max_retries=self.max_retries_by_task.get(group.example["task"], 0),
)
)
self.inflight_requests[run_rollout_task] = InflightRolloutInfo(
off_policy_steps=0, client_config=client_config, group_id=group_id
off_policy_steps=0, client_config=client_config, task=group.example["task"], group_id=group_id
)
@property
@@ -229,47 +251,76 @@ class Scheduler:
await self.maybe_update_policy()
await asyncio.sleep(1)
async def maybe_update_policy(self):
"""Updates the policy to the latest available checkpoint. Aborts rollout requests that are older than the max retention steps."""
def _compute_next_ckpt_step(self) -> int:
latest_ckpt_step = get_latest_ckpt_step(get_broadcast_dir(self.config.output_dir)) or 0
async_away_ckpt_step = max(self.step - self.max_async_level, 0)
next_ckpt_step = (
async_away_ckpt_step if self.strict_async_level else max(async_away_ckpt_step, latest_ckpt_step)
)
if self.strict_async_level:
return async_away_ckpt_step
return max(async_away_ckpt_step, latest_ckpt_step)
if next_ckpt_step > self.ckpt_step:
if next_ckpt_step == async_away_ckpt_step:
self.logger.info(
f"Orchestrator paused: waiting for trainer process to complete checkpoint {next_ckpt_step} "
f"(>{self.max_async_level} step(s) ahead). Training is progressing normally."
)
self.checkpoint_ready.clear()
wait_for_ckpt_start_time = time.perf_counter()
await wait_for_path(get_step_path(get_broadcast_dir(self.config.output_dir), next_ckpt_step) / "STABLE")
self.wait_for_ckpt_time = time.perf_counter() - wait_for_ckpt_start_time
self.logger.info(
f"Orchestrator resumed: checkpoint {next_ckpt_step} ready (after {self.wait_for_ckpt_time:.2f}s)"
)
self.logger.debug(
f"Got new policy with step {next_ckpt_step}. Updating weights and cancelling old rollout requests."
async def _apply_policy_update(self, next_ckpt_step: int) -> None:
async_away_ckpt_step = max(self.step - self.max_async_level, 0)
if next_ckpt_step == async_away_ckpt_step:
self.logger.info(
f"Orchestrator paused: waiting for trainer process to complete checkpoint {next_ckpt_step} "
f"(>{self.max_async_level} step(s) ahead). Training is progressing normally."
)
self.checkpoint_ready.clear()
wait_for_ckpt_start_time = time.perf_counter()
await wait_for_path(get_step_path(get_broadcast_dir(self.config.output_dir), next_ckpt_step) / "STABLE")
self.wait_for_ckpt_time = time.perf_counter() - wait_for_ckpt_start_time
self.logger.info(
f"Orchestrator resumed: checkpoint {next_ckpt_step} ready (after {self.wait_for_ckpt_time:.2f}s)"
)
# Update weights on inference servers
update_weights_start_time = time.perf_counter()
weights_path = get_step_path(get_broadcast_dir(self.config.output_dir), next_ckpt_step)
await self.inference_pool.update_weights(weights_path, lora_name=self.lora_name, step=next_ckpt_step)
self.update_weights_time = time.perf_counter() - update_weights_start_time
self.logger.debug(f"Updated weights to step {next_ckpt_step} in {self.update_weights_time:.2f}s")
self.logger.debug(
f"Got new policy with step {next_ckpt_step}. Updating weights and cancelling old rollout requests."
)
if self.lora_name is not None:
self.model_name = self.lora_name
self.inference_pool.update_model_name(self.model_name)
update_weights_start_time = time.perf_counter()
weights_path = get_step_path(get_broadcast_dir(self.config.output_dir), next_ckpt_step)
await self.inference_pool.update_weights(weights_path, lora_name=self.lora_name, step=next_ckpt_step)
self.update_weights_time = time.perf_counter() - update_weights_start_time
self.logger.debug(f"Updated weights to step {next_ckpt_step} in {self.update_weights_time:.2f}s")
self.ckpt_step = next_ckpt_step
if self.lora_name is not None:
self.model_name = self.lora_name
self.inference_pool.update_model_name(self.model_name)
self.checkpoint_ready.set()
await self._update_off_policy()
async def _get_or_start_policy_update_task(self, next_ckpt_step: int) -> asyncio.Task:
async with self.policy_update_lock:
task = self.inflight_policy_update_task
if task is not None and not task.done():
return task
task = asyncio.create_task(self._apply_policy_update(next_ckpt_step))
self.inflight_policy_update_task = task
def _clear_inflight_policy_update(done_task: asyncio.Task) -> None:
if self.inflight_policy_update_task is done_task:
self.inflight_policy_update_task = None
task.add_done_callback(_clear_inflight_policy_update)
return task
async def maybe_update_policy(self):
"""Updates the policy to the latest available checkpoint. Aborts rollout requests that are older than the max retention steps."""
if not self.enable_policy_updates:
self.ckpt_step = self.step
self.checkpoint_ready.set()
return
await self._update_off_policy()
self.ckpt_step = next_ckpt_step
while True:
next_ckpt_step = self._compute_next_ckpt_step()
if next_ckpt_step <= self.ckpt_step:
return
task = await self._get_or_start_policy_update_task(next_ckpt_step)
await asyncio.shield(task)
async def _update_off_policy(self) -> None:
stale_group_ids = {
@@ -315,14 +366,18 @@ class Scheduler:
"""Continuously generates a batch of rollouts."""
self.step = step
# Cancel the previous update policy task to avoid concurrent updates
if self.update_policy_task is not None:
await safe_cancel(self.update_policy_task)
if self.enable_policy_updates:
# Cancel the previous update policy task to avoid concurrent updates
if self.update_policy_task is not None:
await safe_cancel(self.update_policy_task)
# Check the async barrier before starting, then re-create the update policy loop.
# This ensures we respect max_async_level while still listening for policy updates mid-step.
await self.maybe_update_policy()
self.update_policy_task = asyncio.create_task(self.update_policy_loop())
# Manually check the async barrier before starting the step, then re-create the update policy loop
# This ensures that we respect max_async_level, while still listening for policy updates mid-step
await self.maybe_update_policy()
self.update_policy_task = asyncio.create_task(self.update_policy_loop())
else:
self.ckpt_step = step
self.checkpoint_ready.set()
batch_start_time = time.perf_counter()
@@ -358,7 +413,31 @@ class Scheduler:
group = self.groups.get(group_id)
if group is None:
continue
group.completed_rollouts.append(finished_task.result())
rollout = finished_task.result()
task = rollout_info.task
self.total_rollouts_by_task[task] += 1
should_reschedule = False
if len(rollout["trajectory"]) == 0:
self.empty_rollouts_by_task[task] += 1
should_reschedule = True
self.logger.warning(
f"Empty trajectory in group {group_id} ({task}), re-scheduling "
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete)"
)
if rollout["error"] is not None:
self.errored_rollouts_by_task[task] += 1
should_reschedule = True
self.logger.warning(
f"Rollout error in group {group_id} ({task}), re-scheduling "
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete): "
f"{rollout['error']['error_chain_repr']}"
)
if should_reschedule:
group.rollouts_to_schedule += 1
continue
group.completed_rollouts.append(rollout)
if len(group.completed_rollouts) < self.rollouts_per_example:
continue
completed_rollouts = self.groups.pop(group_id).completed_rollouts
@@ -375,6 +454,7 @@ class Scheduler:
self.buffer.update(completed_rollouts)
accepted_rollouts = self.buffer.sample_rollouts(n=self.rollouts_per_example)
batch_rollouts.extend(accepted_rollouts)
progress_increment = self.get_batch_progress_increment(accepted_rollouts)
batch_progress += progress_increment
@@ -392,6 +472,9 @@ class Scheduler:
if self.update_policy_task is not None:
await safe_cancel(self.update_policy_task)
self.update_policy_task = None
if self.inflight_policy_update_task is not None:
await safe_cancel(self.inflight_policy_update_task)
self.inflight_policy_update_task = None
@property
def max_off_policy_level(self) -> int:
@@ -419,18 +502,37 @@ class Scheduler:
return self.step - self.ckpt_step
def get_metrics(self) -> dict[str, float]:
total_rollouts = sum(self.total_rollouts_by_task.values())
metrics = {
"time/wait_for_ckpt": self.wait_for_ckpt_time,
"time/update_weights": self.update_weights_time,
"batch/async_level": self.async_level,
"batch/inflight_rollouts": self.inflight_rollout_count,
"batch/inflight_samples": self.inflight_sample_count,
"batch/off_policy_level/max": self.max_off_policy_level,
"batch/off_policy_level/mean": self.mean_off_policy_level,
"batch/off_policy_level/min": self.min_off_policy_level,
"batch/cancelled_rollouts": self.cancelled_rollouts_count,
"scheduler/async_level": self.async_level,
"scheduler/inflight_rollouts": self.inflight_rollout_count,
"scheduler/inflight_samples": self.inflight_sample_count,
"scheduler/cancelled_rollouts": self.cancelled_rollouts_count,
"empty_rollouts/all": sum(self.empty_rollouts_by_task.values()) / max(total_rollouts, 1),
"errored_rollouts/all": sum(self.errored_rollouts_by_task.values()) / max(total_rollouts, 1),
"off_policy_level/all/max": self.max_off_policy_level,
"off_policy_level/all/mean": self.mean_off_policy_level,
"off_policy_level/all/min": self.min_off_policy_level,
}
for task, count in self.empty_rollouts_by_task.items():
task_total = max(self.total_rollouts_by_task[task], 1)
metrics[f"empty_rollouts/{task}"] = count / task_total
for task, count in self.errored_rollouts_by_task.items():
task_total = max(self.total_rollouts_by_task[task], 1)
metrics[f"errored_rollouts/{task}"] = count / task_total
by_task: dict[str, list[int]] = {}
for info in self.inflight_requests.values():
by_task.setdefault(info.task, []).append(info.off_policy_steps)
for task, steps in by_task.items():
metrics[f"off_policy_level/{task}/max"] = max(steps)
metrics[f"off_policy_level/{task}/mean"] = sum(steps) / len(steps)
metrics[f"off_policy_level/{task}/min"] = min(steps)
self.cancelled_rollouts_count = 0
self.empty_rollouts_by_task.clear()
self.errored_rollouts_by_task.clear()
self.total_rollouts_by_task.clear()
# Add inference pool metrics (e.g. elastic pool server counts)
metrics.update(self.inference_pool.get_metrics())
+342 -30
View File
@@ -1,13 +1,24 @@
import base64
import hashlib
import time
from concurrent.futures import ThreadPoolExecutor
from io import BytesIO
from pathlib import Path
from typing import Any
import torch
import verifiers as vf
from PIL import Image
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.transport import TrainingSample
from prime_rl.utils.chat_template import (
common_prefix_len,
deserialize_tool_calls,
normalize_messages,
render_messages,
strip_message_content,
)
from prime_rl.utils.logger import get_logger
# We use list() instead of deepcopy() for flat lists (token IDs, logprobs) - safe because
@@ -35,6 +46,187 @@ def _align_routed_experts(
return routed_experts + [zero_entry for _ in range(deficit)]
def _common_prefix_len(a: list[int], b: list[int]) -> int:
return common_prefix_len(a, b)
def _normalize_messages(messages: Any, default_role: str) -> list[dict[str, Any]]:
return normalize_messages(messages, default_role)
def _deserialize_tool_calls(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
return deserialize_tool_calls(messages)
def _strip_message_content(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
return strip_message_content(messages)
def _render_messages(
tokenizer: PreTrainedTokenizer,
messages: list[dict[str, Any]],
add_generation_prompt: bool = False,
tools: list[dict[str, Any]] | None = None,
processor=None,
) -> list[int]:
return render_messages(
tokenizer,
messages,
add_generation_prompt=add_generation_prompt,
tools=tools,
processor=processor,
)
def _prepare_messages_for_processor(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Convert messages to the format expected by the VLM processor.
- Converts image_url items to image items with loaded PIL Images
- Strips extra fields (e.g. image_url on text items) that confuse the processor
- Ensures all message content is in list format (processor requires this)
"""
prepared = []
for msg in messages:
content = msg.get("content")
if isinstance(content, str):
prepared.append({**msg, "content": [{"type": "text", "text": content}]})
continue
if not isinstance(content, list):
prepared.append(msg)
continue
new_content = []
for item in content:
if item.get("type") == "image_url":
url = item.get("image_url", {}).get("url", "")
if url.startswith(_FILE_URL_PREFIX):
img = _load_file_image(url)
elif url.startswith("data:image"):
b64_data = url.split(",", 1)[1]
img = Image.open(BytesIO(base64.b64decode(b64_data)))
else:
new_content.append(item)
continue
new_content.append({"type": "image", "image": img})
elif item.get("type") == "text":
new_content.append({"type": "text", "text": item.get("text", "")})
else:
new_content.append(item)
prepared.append({**msg, "content": new_content})
return prepared
def _tokenize_step_from_messages(
step: vf.TrajectoryStep,
tokenizer: PreTrainedTokenizer,
tools: list[dict[str, Any]] | None = None,
processor=None,
) -> dict[str, Any]:
prompt = _normalize_messages(step.get("prompt"), default_role="user")
completion = _normalize_messages(step.get("completion"), default_role="assistant")
prompt = _strip_message_content(_deserialize_tool_calls(prompt))
completion = _strip_message_content(_deserialize_tool_calls(completion))
assert all(m.get("role") == "assistant" for m in completion), (
"Expected all completion messages to be assistant role for SFT distillation, "
f"got roles: {[m.get('role') for m in completion]}"
)
if processor is not None:
prompt = _prepare_messages_for_processor(prompt)
completion = _prepare_messages_for_processor(completion)
all_messages = prompt + completion
prompt_has_assistant_completion = len(completion) > 0 and completion[0].get("role") == "assistant"
prompt_ids = _render_messages(
tokenizer,
prompt,
add_generation_prompt=prompt_has_assistant_completion,
tools=tools,
processor=processor,
)
full_ids = _render_messages(
tokenizer,
all_messages,
tools=tools,
processor=processor,
)
split_idx = _common_prefix_len(prompt_ids, full_ids)
original_prompt_len = len(prompt_ids)
prompt_ids = full_ids[:split_idx]
completion_ids = full_ids[split_idx:]
completion_mask = [True] * len(completion_ids)
completion_logprobs = [0.0] * len(completion_ids)
return {
"prompt_ids": prompt_ids,
"prompt_mask": [False] * len(prompt_ids),
"completion_ids": completion_ids,
"completion_mask": completion_mask,
"completion_logprobs": completion_logprobs,
"routed_experts": None,
"prompt_prefix_len": split_idx,
"original_prompt_len": original_prompt_len,
}
def _convert_tools_to_oai_format(tool_defs: list) -> list[dict[str, Any]] | None:
"""Convert verifiers Tool objects or dicts to OAI function-calling format."""
if not tool_defs:
return None
def _get(tool: Any, key: str) -> Any:
if isinstance(tool, dict):
return tool.get(key)
return getattr(tool, key, None)
return [
{
"type": "function",
"function": {
"name": _get(tool, "name"),
"description": _get(tool, "description"),
"parameters": _get(tool, "parameters"),
**({} if _get(tool, "strict") is None else {"strict": _get(tool, "strict")}),
},
}
for tool in tool_defs
]
def pretokenize_rollout_trajectory(
output: vf.RolloutOutput,
tokenizer: PreTrainedTokenizer,
processor=None,
) -> bool:
"""Populate missing step tokens from prompt/completion messages."""
logger = get_logger()
tools = _convert_tools_to_oai_format(output.get("tool_defs", []))
for step_idx, step in enumerate(output["trajectory"]):
if step["tokens"] is not None:
continue
reconstructed = _tokenize_step_from_messages(step, tokenizer, tools=tools, processor=processor)
if reconstructed["prompt_prefix_len"] < reconstructed["original_prompt_len"]:
logger.debug(
f"Prompt tokenization was non-prefix for example {output['example_id']} step {step_idx}. "
f"Using longest common prefix length {reconstructed['prompt_prefix_len']} "
f"(original prompt had {reconstructed['original_prompt_len']} tokens)."
)
reconstructed.pop("prompt_prefix_len")
reconstructed.pop("original_prompt_len")
step["tokens"] = reconstructed
return True
def interleave_rollout(
output: vf.RolloutOutput,
vlm_cache: "VLMImageCache | None" = None,
@@ -67,17 +259,41 @@ def interleave_rollout(
trajectory = output["trajectory"]
if len(trajectory) == 0:
logger.warning(f"No trajectory steps for example {output['example_id']}. Skipping rollout.")
error = output.get("error")
stop = output.get("stop_condition")
logger.warning(
f"No trajectory steps for example {output['example_id']} (error={error}, stop={stop}). Skipping rollout."
)
return None
has_error = output["error"] is not None
# this field should be guaranteed because we set temperature in get_sampling_args
temperature = output["sampling_args"]["temperature"]
def make_sample(step: vf.TrajectoryStep) -> TrainingSample:
"""Create a new TrainingSample from a trajectory step."""
def prepare_step_tokens(step: vf.TrajectoryStep, step_idx: int) -> dict[str, Any] | None:
tokens = step["tokens"]
assert tokens is not None
if tokens is not None:
return {
"prompt_ids": list(tokens["prompt_ids"]),
"prompt_mask": [bool(i) for i in tokens["prompt_mask"]],
"completion_ids": list(tokens["completion_ids"]),
"completion_mask": [bool(i) for i in tokens["completion_mask"]],
"completion_logprobs": list(tokens["completion_logprobs"]),
"routed_experts": tokens.get("routed_experts"),
}
logger.warning(f"Missing rollout tokens for example {output['example_id']} step {step_idx}.")
return None
prepared_steps: list[dict[str, Any]] = []
for step_idx, step in enumerate(trajectory):
prepared = prepare_step_tokens(step, step_idx)
if prepared is None:
return None
prepared_steps.append(prepared)
def make_sample(tokens: dict[str, Any]) -> TrainingSample:
"""Create a new TrainingSample from a trajectory step."""
if has_error:
completion_mask = [False] * len(tokens["completion_mask"])
else:
@@ -101,10 +317,9 @@ def interleave_rollout(
routed_experts=routed_experts,
)
def extend_sample(sample: TrainingSample, step: vf.TrajectoryStep, prefix_len: int) -> None:
def extend_sample(sample: TrainingSample, prefix_len: int, step_idx: int) -> None:
"""Extend an existing sample with a new trajectory step (extension property holds)."""
tokens = step["tokens"]
assert tokens is not None
tokens = prepared_steps[step_idx]
# Extend with new prompt tokens (mask=False, no gradient)
new_prompt_ids = tokens["prompt_ids"][prefix_len:]
@@ -138,12 +353,12 @@ def interleave_rollout(
# Track [prefix_tokens, sample, last_step_idx] per active sample
active_samples: list[list] = []
first_tokens = trajectory[0]["tokens"]
first_tokens = prepared_steps[0]
first_prefix = first_tokens["prompt_ids"] + first_tokens["completion_ids"]
active_samples.append([first_prefix, make_sample(trajectory[0]), 0])
active_samples.append([first_prefix, make_sample(first_tokens), 0])
for step_idx, step in enumerate(trajectory[1:], start=1):
tokens = step["tokens"]
for step_idx, _step in enumerate(trajectory[1:], start=1):
tokens = prepared_steps[step_idx]
step_prompt_ids = tokens["prompt_ids"]
# Check if this step extends ANY active prefix
@@ -156,7 +371,7 @@ def interleave_rollout(
if matched_idx is not None:
# Extension holds - merge into matched sample
prefix_tokens, sample, _ = active_samples[matched_idx]
extend_sample(sample, step, len(prefix_tokens))
extend_sample(sample, len(prefix_tokens), step_idx=step_idx)
active_samples[matched_idx][0] = tokens["prompt_ids"] + tokens["completion_ids"]
active_samples[matched_idx][2] = step_idx
else:
@@ -166,7 +381,7 @@ def interleave_rollout(
f"Starting new sample (active_prefixes={len(active_samples)}, step_prompt_len={len(step_prompt_ids)})."
)
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
active_samples.append([new_prefix, make_sample(step), step_idx])
active_samples.append([new_prefix, make_sample(tokens), step_idx])
# Attach images once per sample using only the last merged step
if vlm_cache is not None:
@@ -185,8 +400,61 @@ def interleave_rollout(
# =============================================================================
_FILE_URL_PREFIX = "file://"
def offload_images_to_disk(rollouts: list[vf.RolloutOutput], output_dir: Path) -> int:
"""Replace base64 image data in rollout trajectories with file paths on disk.
Scans all trajectory step prompts for data:image URLs, writes the decoded
image bytes to ``{output_dir}/assets/images/{hash}.png``, and replaces the
URL in-place with ``file://{path}``. Deduplicates by content hash so each
unique image is written only once.
Returns the number of unique images written to disk.
"""
images_dir = output_dir / "assets" / "images"
images_dir.mkdir(parents=True, exist_ok=True)
written: set[str] = set()
for output in rollouts:
for step in output.get("trajectory", []):
prompt = step.get("prompt")
if not prompt or not isinstance(prompt, list):
continue
for msg in prompt:
content = msg.get("content", [])
if not isinstance(content, list):
continue
for item in content:
if item.get("type") != "image_url":
continue
url = item.get("image_url", {}).get("url", "")
if not url.startswith("data:image"):
continue
b64_data = url.split(",", 1)[1]
content_hash = hashlib.sha256(b64_data.encode()).hexdigest()[:16]
path = images_dir / f"{content_hash}.png"
if content_hash not in written:
if not path.exists():
path.write_bytes(base64.b64decode(b64_data))
written.add(content_hash)
item["image_url"]["url"] = f"{_FILE_URL_PREFIX}{path}"
return len(written)
def _load_file_image(path_str: str) -> Image.Image:
"""Load an image from a file:// path."""
return Image.open(path_str.removeprefix(_FILE_URL_PREFIX))
def _extract_images_from_messages(messages: list) -> list[tuple[Image.Image, str]]:
"""Extract (image, b64_key) pairs from OpenAI-style chat messages."""
"""Extract (image, key) pairs from OpenAI-style chat messages.
Handles both base64 data URLs and file:// paths from disk offloading.
"""
images = []
if not messages or not isinstance(messages, list):
return images
@@ -197,7 +465,10 @@ def _extract_images_from_messages(messages: list) -> list[tuple[Image.Image, str
for item in content:
if item.get("type") == "image_url":
url = item.get("image_url", {}).get("url", "")
if url.startswith("data:image"):
if url.startswith(_FILE_URL_PREFIX):
img = _load_file_image(url)
images.append((img, url))
elif url.startswith("data:image"):
b64_data = url.split(",", 1)[1]
img_bytes = base64.b64decode(b64_data)
img = Image.open(BytesIO(img_bytes))
@@ -205,8 +476,11 @@ def _extract_images_from_messages(messages: list) -> list[tuple[Image.Image, str
return images
def _collect_b64_keys_from_messages(messages: list) -> list[str]:
"""Extract base64 keys from OpenAI-style chat messages without decoding."""
def _collect_image_keys_from_messages(messages: list) -> list[str]:
"""Extract image keys from OpenAI-style chat messages without decoding.
Handles both base64 data URLs and file:// paths from disk offloading.
"""
keys = []
if not messages or not isinstance(messages, list):
return keys
@@ -218,17 +492,45 @@ def _collect_b64_keys_from_messages(messages: list) -> list[str]:
url = item.get("image_url", {}).get("url", "")
if url.startswith("data:image"):
keys.append(url.split(",", 1)[1])
elif url.startswith(_FILE_URL_PREFIX):
keys.append(url)
return keys
def _decode_b64_image(b64_data: str) -> Image.Image:
"""Decode a single base64 string into a PIL Image."""
return Image.open(BytesIO(base64.b64decode(b64_data)))
def _decode_image(key: str) -> Image.Image:
"""Decode an image from a base64 string or load from a file:// path."""
if key.startswith(_FILE_URL_PREFIX):
return _load_file_image(key)
return Image.open(BytesIO(base64.b64decode(key)))
_PARALLEL_DECODE_THRESHOLD = 4
_IMAGE_STRIPPED_PLACEHOLDER = "[preprocessed image]"
def strip_base64_images(examples: list[tuple[int, vf.RolloutOutput]]) -> None:
"""Strip image data from rollout prompts to free memory.
Handles both base64 data URLs and file:// paths from disk offloading.
The images have been decoded and indexed; the original data is no longer needed.
"""
for _, output in examples:
for step in output.get("trajectory", []):
prompt = step.get("prompt")
if not prompt or not isinstance(prompt, list):
continue
for msg in prompt:
content = msg.get("content", [])
if isinstance(content, list):
for item in content:
if item.get("type") == "image_url":
url = item.get("image_url", {}).get("url", "")
if url.startswith("data:image") or url.startswith(_FILE_URL_PREFIX):
item["image_url"]["url"] = _IMAGE_STRIPPED_PLACEHOLDER
def _extract_images_from_examples(
examples: list[tuple[int, vf.RolloutOutput]],
) -> tuple[list[Image.Image], dict[int, list[list[int]]]]:
@@ -262,9 +564,9 @@ def _extract_images_from_examples(
step_image_indices = []
for step in trajectory:
prompt = step.get("prompt")
b64_keys = _collect_b64_keys_from_messages(prompt)
image_keys = _collect_image_keys_from_messages(prompt)
indices = []
for key in b64_keys:
for key in image_keys:
if key not in key_to_index:
key_to_index[key] = len(unique_keys)
unique_keys.append(key)
@@ -276,9 +578,12 @@ def _extract_images_from_examples(
# Pass 2: decode unique images (parallel when worthwhile)
if len(unique_keys) > _PARALLEL_DECODE_THRESHOLD:
with ThreadPoolExecutor(max_workers=min(len(unique_keys), 16)) as pool:
all_images = list(pool.map(_decode_b64_image, unique_keys))
all_images = list(pool.map(_decode_image, unique_keys))
else:
all_images = [_decode_b64_image(k) for k in unique_keys]
all_images = [_decode_image(k) for k in unique_keys]
del unique_keys, key_to_index
strip_base64_images(examples)
return all_images, step_image_indices_per_example
@@ -363,14 +668,19 @@ def _preprocess_images_batched(
else:
results = [_process_chunk(chunks[0])]
# Free PIL images now that preprocessing is done
del chunks
images.clear()
all_pixel_values_list = [r[0] for r in results]
all_grid_thw_list = [r[1] for r in results]
all_pixel_values = torch.cat(all_pixel_values_list, dim=0)
all_grid_thw = torch.cat(all_grid_thw_list, dim=0)
del all_pixel_values_list, all_grid_thw_list, results
logger.debug(
f"VLM image processing: {len(images)} images, sizes={image_sizes}, "
f"VLM image processing: {len(image_sizes)} images, sizes={image_sizes}, "
f"pixel_values={all_pixel_values.shape}, grid_thw={all_grid_thw.tolist()}"
)
@@ -381,15 +691,16 @@ def _preprocess_images_batched(
patch_dim = all_pixel_values.shape[1]
# Store per-image bytes once
# Convert to bytes per-image and free the tensor immediately after
image_bytes_list: list[bytes] = []
image_num_patches_list: list[int] = []
image_grids_list: list[list[int]] = []
for i in range(len(images)):
for i in range(len(image_sizes)):
img_slice = all_pixel_values[patch_starts[i] : patch_starts[i + 1]]
image_bytes_list.append(img_slice.numpy().tobytes())
image_num_patches_list.append(img_slice.shape[0])
image_grids_list.append(all_grid_thw[i].tolist())
del all_pixel_values, all_grid_thw
store = _ImageStore(
image_bytes=image_bytes_list,
@@ -483,12 +794,13 @@ def build_vlm_image_cache(rollouts: list[vf.RolloutOutput], processor) -> VLMIma
examples = [(idx, rollout) for idx, rollout in enumerate(rollouts)]
unique_example_ids = {rollout["example_id"] for rollout in rollouts}
# Extract images
# Extract images (also strips base64 data from rollout prompts to free memory)
extract_start = time.perf_counter()
all_images, images_per_example = _extract_images_from_examples(examples)
num_unique_images = len(all_images)
extract_time = time.perf_counter() - extract_start
# Preprocess images
# Preprocess images (clears PIL image list when done)
preprocess_start = time.perf_counter()
store, step_indices = _preprocess_images_batched(all_images, images_per_example, processor)
preprocess_time = time.perf_counter() - preprocess_start
@@ -497,7 +809,7 @@ def build_vlm_image_cache(rollouts: list[vf.RolloutOutput], processor) -> VLMIma
store=store,
step_indices=step_indices,
num_unique_examples=len(unique_example_ids),
num_unique_images=len(all_images),
num_unique_images=num_unique_images,
extract_time=extract_time,
preprocess_time=preprocess_time,
)
+43 -17
View File
@@ -13,10 +13,9 @@ from rich.table import Table
from verifiers.utils.async_utils import maybe_semaphore
from verifiers.utils.client_utils import setup_openai_client
from prime_rl.configs.orchestrator import SamplingConfig
from prime_rl.configs.orchestrator import OrchestratorConfig, SamplingConfig
from prime_rl.transport import TrainingSample
from prime_rl.utils.utils import (
format_num,
format_time,
get_broadcast_dir,
get_ckpt_dir,
@@ -37,22 +36,34 @@ async def get_semaphore() -> AsyncContextManager:
return SEMAPHORE
def get_sampling_args(sampling_config: SamplingConfig, temperature: float) -> dict:
def get_sampling_args(sampling_config: SamplingConfig, temperature: float, use_token_client: bool = True) -> dict:
# Convert SamplingConfig to vLLM OAI sampling args
# https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html#extra-parameters_2
sampling_args = dict(sampling_config)
sampling_args.pop("temp_scheduler", None)
sampling_args["temperature"] = temperature
sampling_args["top_p"] = 1.0
extra_body = dict(sampling_config.extra_body)
min_tokens = sampling_args.pop("min_tokens")
repetition_penalty = sampling_args.pop("repetition_penalty")
if min_tokens > 0:
extra_body["min_tokens"] = min_tokens
if repetition_penalty != 1.0:
extra_body["repetition_penalty"] = repetition_penalty
extra_body["top_k"] = -1
extra_body["min_p"] = 0.0
sampling_args["logprobs"] = True
sampling_args["extra_body"] = {
**sampling_config.extra_body,
"return_token_ids": True, # Always return token IDs
"top_k": -1,
"min_p": 0.0,
}
sampling_args["extra_body"]["min_tokens"] = sampling_args.pop("min_tokens")
sampling_args["extra_body"]["repetition_penalty"] = sampling_args.pop("repetition_penalty")
if use_token_client:
extra_body["return_token_ids"] = True
if extra_body:
sampling_args["extra_body"] = extra_body
return sampling_args
@@ -92,9 +103,9 @@ def parse_is_truncated_completions(responses: list[list[ChatCompletion]]) -> lis
def print_benchmark(history: dict[str, list[Any]]) -> None:
"""
Print benchmark results as rich table. Shows formatted values for the
inference throughput and overall step time. First first N rows show the
per-step values, and the last row shows the mean, std, min, and max values.
Print benchmark results as rich table. Shows formatted step time values.
First N rows show the per-step values, and the last row shows the mean,
std, min, and max values.
"""
history.pop("step")
assert all(len(v) for v in history.values()), "All metrics must have logged the same number of steps"
@@ -102,7 +113,6 @@ def print_benchmark(history: dict[str, list[Any]]) -> None:
# Turn metric history into pd.DataFrame
df = pd.DataFrame(dict(history.items()))
columns = {
"perf/throughput": "Throughput",
"time/step": "Step Time",
}
df = df.rename(columns=columns)
@@ -121,7 +131,6 @@ def print_benchmark(history: dict[str, list[Any]]) -> None:
# Add formatted rows
formatted_df = pd.DataFrame(columns=df.columns)
formatted_df["Step Time"] = df["Step Time"].apply(format_time)
formatted_df["Throughput"] = df["Throughput"].apply(format_num, precision=2)
for step, row in formatted_df.iterrows():
table.add_row(*([str(step)] + [str(x) for x in row]))
@@ -133,7 +142,6 @@ def print_benchmark(history: dict[str, list[Any]]) -> None:
mean_df = df.describe().loc[["mean", "std", "min", "max"], :]
formatted_mean_df = pd.DataFrame(columns=mean_df.columns)
formatted_mean_df["Step Time"] = mean_df["Step Time"].apply(format_time)
formatted_mean_df["Throughput"] = mean_df["Throughput"].apply(format_num, precision=2)
mean_row = ["Overall"] + formatted_mean_df.T.apply(
lambda row: f"{row['mean']} ± {row['std']} [{row['min']}, {row['max']}]", axis=1
).tolist()
@@ -219,3 +227,21 @@ def get_weight_dir(output_dir: Path, step: int, check_exists: bool = True, wait_
return broadcast_weight_dir
raise FileNotFoundError(f"No weight directory found for checkpoint step {step}")
def setup_external_rollout_model(config: OrchestratorConfig, logger) -> tuple[Any, str, bool]:
"""Resolve rollout client/model and whether policy updates should be enabled."""
rollout_client_config = config.client
rollout_model_name = config.model.name
enable_policy_updates = True
if config.teacher_rollout_model is not None:
rollout_client_config = config.teacher_rollout_model.client
rollout_model_name = config.teacher_rollout_model.model.name
enable_policy_updates = False
logger.info(
f"Using external teacher rollout model (base_url={', '.join(rollout_client_config.base_url)}, "
f"model={rollout_model_name})"
)
return rollout_client_config, rollout_model_name, enable_policy_updates
+16 -2
View File
@@ -5,6 +5,18 @@
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --partition={{ partition }}
{%- if account %}
#SBATCH --account={{ account }}
{%- endif %}
{%- if time %}
#SBATCH --time={{ time }}
{%- endif %}
{%- if nodelist %}
#SBATCH --nodelist={{ nodelist }}
{%- endif %}
{%- if exclude %}
#SBATCH --exclude={{ exclude }}
{%- endif %}
#SBATCH --exclusive
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
@@ -43,8 +55,10 @@ done
echo "HOSTNAMES=${HOSTNAMES[@]}"
echo "INFER_URLS=${INFER_URLS}"
# Cleanup any leftover vLLM processes
srun bash -c "pkill -9 -f vllm || true"
{% if pre_run_command %}
# Pre-run command
{{ pre_run_command }}
{% endif %}
# Run inference (each node runs an independent vLLM replica)
srun bash -c '
+42 -10
View File
@@ -5,6 +5,18 @@
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --partition={{ partition }}
{%- if account %}
#SBATCH --account={{ account }}
{%- endif %}
{%- if time %}
#SBATCH --time={{ time }}
{%- endif %}
{%- if nodelist %}
#SBATCH --nodelist={{ nodelist }}
{%- endif %}
{%- if exclude %}
#SBATCH --exclude={{ exclude }}
{%- endif %}
#SBATCH --exclusive
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
@@ -13,6 +25,7 @@
export NUM_TRAIN_NODES={{ num_train_nodes }}
export NUM_INFER_NODES={{ num_infer_nodes }}
export GPUS_PER_NODE={{ gpus_per_node }}
{% if num_infer_nodes > 0 -%}
export INFERENCE_TP={{ inference_tp }}
export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parallel else "0" }}
export INFERENCE_DATA_PARALLEL_RPC_PORT={{ inference_data_parallel_rpc_port }}
@@ -23,6 +36,7 @@ export USE_DISTRIBUTED_EP=0
if [ "$INFERENCE_ENABLE_EXPERT_PARALLEL" -eq 1 ] && [ "$NUM_INFER_NODES" -gt 1 ]; then
USE_DISTRIBUTED_EP=1
fi
{%- endif %}
# Paths
export PROJECT_DIR={{ project_dir }}
@@ -43,13 +57,20 @@ export CUDA_DEVICE_ORDER=PCI_BUS_ID
export PYTHONUNBUFFERED=1
export OMP_NUM_THREADS=1
{% if wandb_shared -%}
export WANDB_SHARED_MODE=1
export WANDB_SHARED_RUN_ID=$(python3 -c "import uuid; print(uuid.uuid4().hex)")
{%- endif %}
# Networking
HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
INFER_HOSTS=( ${HOSTNAMES[@]:0:$NUM_INFER_NODES} )
TRAIN_HOSTS=( ${HOSTNAMES[@]:$NUM_INFER_NODES:$SLURM_JOB_NUM_NODES} )
export INFER_HEAD_HOST="${INFER_HOSTS[0]}"
export HOSTNAMES_STR="${HOSTNAMES[*]}"
{% if num_infer_nodes > 0 -%}
INFER_HOSTS=( ${HOSTNAMES[@]:0:$NUM_INFER_NODES} )
export INFER_HEAD_HOST="${INFER_HOSTS[0]}"
INFER_URLS=""
if [ "$USE_DISTRIBUTED_EP" -eq 1 ]; then
INFER_URLS="http://${INFER_HEAD_HOST}:8000/v1"
@@ -63,11 +84,13 @@ else
done
fi
export INFER_URLS
echo "HOSTNAMES=${HOSTNAMES[*]}"
echo "TRAIN_HOSTS=${TRAIN_HOSTS[*]}"
echo "INFER_HOSTS=${INFER_HOSTS[*]}"
echo "INFER_URLS=${INFER_URLS}"
echo "USE_DISTRIBUTED_EP=${USE_DISTRIBUTED_EP}"
{%- endif %}
echo "HOSTNAMES=${HOSTNAMES[*]}"
echo "TRAIN_HOSTS=${TRAIN_HOSTS[*]}"
export MASTER_ADDR="${HOSTNAMES[$NUM_INFER_NODES]}"
export MASTER_PORT=29500
@@ -80,6 +103,11 @@ cd $PROJECT_DIR
source .venv/bin/activate
uv sync --all-extras
{% if pre_run_command %}
# Pre-run command
{{ pre_run_command }}
{% endif %}
# Run RL
srun bash -c '
# Source environment
@@ -96,6 +124,7 @@ srun bash -c '
IB_HCA=$(ibv_devinfo | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" |paste -sd,)
export NCCL_IB_HCA=$IB_HCA
{% if num_infer_nodes > 0 -%}
if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:False"
INFER_NODE_RANK=$SLURM_PROCID
@@ -128,12 +157,15 @@ else
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
if [ "$TRAIN_NODE_RANK" -eq 0 ]; then
uv run orchestrator \
@ $CONFIG_DIR/orchestrator.toml \
--weight_broadcast.host $MASTER_ADDR \
--client.base-url $INFER_URLS \
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --client.base-url $INFER_URLS"
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
{% endif %}{% if wandb_shared %}WANDB_SHARED_LABEL=orchestrator {% endif %}uv run orchestrator $ORCHESTRATOR_ARGS \
2>&1 | tee $OUTPUT_DIR/slurm/latest_orchestrator.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_orchestrator.log &
fi
{%- else %}
TRAIN_NODE_RANK=$SLURM_PROCID
{%- endif %}
export HF_HUB_OFFLINE=1
@@ -142,7 +174,7 @@ else
echo $HOSTNAMES_STR | tee $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log
uv run torchrun \
{% if wandb_shared %}WANDB_SHARED_LABEL=trainer {% endif %}uv run torchrun \
--nnodes=$NUM_TRAIN_NODES \
--nproc-per-node=$GPUS_PER_NODE \
--node-rank=$TRAIN_NODE_RANK \
@@ -155,5 +187,5 @@ else
-m prime_rl.trainer.rl.train \
@ $CONFIG_DIR/trainer.toml \
2>&1 | tee -a $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_train_node_rank_${TRAIN_NODE_RANK}.log
fi
{% if num_infer_nodes > 0 %} fi{% endif %}
'
@@ -5,6 +5,18 @@
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --partition={{ partition }}
{%- if account %}
#SBATCH --account={{ account }}
{%- endif %}
{%- if time %}
#SBATCH --time={{ time }}
{%- endif %}
{%- if nodelist %}
#SBATCH --nodelist={{ nodelist }}
{%- endif %}
{%- if exclude %}
#SBATCH --exclude={{ exclude }}
{%- endif %}
#SBATCH --exclusive
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
@@ -41,6 +53,11 @@ source $PROJECT_DIR/.venv/bin/activate
cd $PROJECT_DIR && uv sync --all-extras
{% if pre_run_command %}
# Pre-run command
{{ pre_run_command }}
{% endif %}
# Run SFT
srun bash -c '
# Setup environment
@@ -6,6 +6,18 @@
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --exclusive
#SBATCH --partition={{ partition }}
{%- if account %}
#SBATCH --account={{ account }}
{%- endif %}
{%- if time %}
#SBATCH --time={{ time }}
{%- endif %}
{%- if nodelist %}
#SBATCH --nodelist={{ nodelist }}
{%- endif %}
{%- if exclude %}
#SBATCH --exclude={{ exclude }}
{%- endif %}
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
@@ -17,4 +29,8 @@ cd $PROJECT_DIR
source .venv/bin/activate
uv sync --all-extras
{% if pre_run_command %}
# Pre-run command
{{ pre_run_command }}
{% endif %}
uv run rl @ {{ config_path }}
@@ -6,6 +6,18 @@
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --exclusive
#SBATCH --partition={{ partition }}
{%- if account %}
#SBATCH --account={{ account }}
{%- endif %}
{%- if time %}
#SBATCH --time={{ time }}
{%- endif %}
{%- if nodelist %}
#SBATCH --nodelist={{ nodelist }}
{%- endif %}
{%- if exclude %}
#SBATCH --exclude={{ exclude }}
{%- endif %}
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
@@ -17,4 +29,8 @@ cd $PROJECT_DIR
source .venv/bin/activate
uv sync --all-extras
{% if pre_run_command %}
# Pre-run command
{{ pre_run_command }}
{% endif %}
uv run sft @ {{ config_path }}
+26 -10
View File
@@ -12,6 +12,7 @@ from torch.distributed.checkpoint.state_dict import get_state_dict, set_state_di
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
from torch.distributed.checkpoint.state_dict_saver import save as dcp_save
from torch.distributed.checkpoint.stateful import Stateful
from torch.distributed.tensor import DTensor
from torch.nn import Module
from torch.optim.lr_scheduler import LRScheduler
from torch.optim.optimizer import Optimizer
@@ -22,10 +23,9 @@ from prime_rl.configs.trainer import CheckpointConfig, LoRAConfig, WeightCheckpo
from prime_rl.trainer.lora import has_lora_layers, save_lora_config
from prime_rl.trainer.models import PreTrainedModelPrimeRL
from prime_rl.trainer.optim import CPUOffloadOptimizer
from prime_rl.trainer.runs import Progress
from prime_rl.trainer.runs import Progress, get_multi_run_manager
from prime_rl.trainer.weights import (
gather_weights_on_master,
get_adapter_state_dict,
save_state_dict,
)
from prime_rl.trainer.world import get_world
@@ -304,6 +304,19 @@ class WeightCheckpointManager:
step_path = self.get_step_path(step)
(step_path / "STABLE").touch()
def get_run_adapter_state_dict(self) -> dict[str, Tensor]:
lora_state_dict = {
f"base_model.model.{key}": (value.full_tensor() if isinstance(value, DTensor) else value).to(
"cpu", non_blocking=False
)
for key, value in get_multi_run_manager().get_state_dict_for_run(0).items()
}
if not lora_state_dict:
raise ValueError("The LoRA state dict is empty. Something went wrong.")
return lora_state_dict
def save_to_path(
self,
path: Path,
@@ -339,10 +352,12 @@ class WeightCheckpointManager:
gen_config.save_pretrained(path)
tokenizer.save_pretrained(path)
if self.config.save_adapter_separately and lora_state_dict is not None:
if lora_state_dict is not None:
adapter_path = path / "lora_adapters"
adapter_path.mkdir(parents=True, exist_ok=True)
torch.save(lora_state_dict, adapter_path / "adapter_model.bin")
save_state_dict(
lora_state_dict, adapter_path, self.config.save_format, save_sharded=False, adapter=True
)
if self.lora_config:
save_lora_config(
model,
@@ -374,11 +389,11 @@ class WeightCheckpointManager:
for key in getattr(model, "_tied_weights_keys", []):
state_dict.pop(key, None)
if has_lora_layers(model):
self.logger.debug("Getting LoRA state dict on master rank for weight checkpoint")
if has_lora_layers(model) and self.config.save_adapter_separately:
self.logger.debug("Getting run adapter state dict for weight checkpoint")
start_time = time.perf_counter()
lora_state_dict = get_adapter_state_dict(model, self.world.is_master)
self.logger.debug(f"Got LoRA state dict on master rank in {time.perf_counter() - start_time:.2f} seconds")
lora_state_dict = self.get_run_adapter_state_dict()
self.logger.debug(f"Got run adapter state dict in {time.perf_counter() - start_time:.2f} seconds")
else:
lora_state_dict = None
@@ -443,10 +458,11 @@ def setup_ckpt_managers(
) -> tuple[CheckpointManager | None, WeightCheckpointManager | None]:
if ckpt_config is None:
return None, None
ckpt_manager = CheckpointManager(output_dir, ckpt_config)
ckpt_output_dir = ckpt_config.output_dir or output_dir
ckpt_manager = CheckpointManager(ckpt_output_dir, ckpt_config)
if ckpt_config.weights:
weight_ckpt_manager = WeightCheckpointManager(
output_dir,
ckpt_output_dir,
ckpt_config.weights,
lora_config=lora_config,
keep_last=ckpt_config.keep_last,
+50 -24
View File
@@ -22,12 +22,13 @@ from transformers.tokenization_utils import PreTrainedTokenizer
from transformers.utils.import_utils import is_flash_attn_3_available
from prime_rl.configs.trainer import ActivationCheckpointConfig, CompileConfig, ModelConfig, TokenizerConfig
from prime_rl.trainer.lora import apply_lora_to_model, strip_lora_from_state_dict
from prime_rl.trainer.lora import apply_lora_to_model, freeze_all_except_lora_and_specified, strip_lora_from_state_dict
from prime_rl.trainer.models import (
AutoModelForCausalLMPrimeRL,
PreTrainedModelPrimeRL,
PrimeLmOutput,
cast_float_and_contiguous,
get_custom_vlm_cls,
supports_custom_impl,
)
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
@@ -40,7 +41,7 @@ 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.vlm import is_vlm_model
from prime_rl.utils.vlm import is_vlm_config, is_vlm_model
def _patch_qwen3_5_moe_conversion_mapping():
@@ -217,10 +218,8 @@ def get_model(
f"Loading model config (name={config.name}, attn={config.attn}, trust_remote_code={config.trust_remote_code})"
)
# Check if this is a vision-language model
# Check if this is a vision-language model (by name pattern first)
is_vlm = is_vlm_model(config.name)
if is_vlm:
logger.info(f"Detected vision-language model: {config.name}")
if "Qwen3.5" in config.name or "qwen3_5" in config.name.lower():
_patch_qwen3_5_text_position_ids()
@@ -233,6 +232,17 @@ def get_model(
),
)
model_config.use_cache = False
# Fallback VLM detection from loaded config (catches local paths)
if not is_vlm and is_vlm_config(model_config):
is_vlm = True
if is_vlm:
logger.info(f"Detected vision-language model: {config.name}")
# Fallback Qwen3.5 patch detection from loaded config model_type
if getattr(model_config, "model_type", "").startswith("qwen3_5_moe"):
_patch_qwen3_5_text_position_ids()
_patch_qwen3_5_moe_conversion_mapping()
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"):
@@ -254,6 +264,11 @@ def get_model(
)
model_config.pad_token_id = pad_token_id
# Some HF configs (e.g. Llama 3.2) set pad_token_id to a list, which crashes
# transformers' GenerationConfig.validate() when it does `pad_token_id < 0`.
if isinstance(getattr(model_config, "pad_token_id", None), list):
model_config.pad_token_id = model_config.pad_token_id[0]
# NOTE: For VLM models, we do NOT propagate dtype to sub_configs.
# The model should load in its default dtype (bf16) to match vLLM inference.
# The FSDP MixedPrecisionPolicy handles compute dtype separately.
@@ -268,25 +283,24 @@ def get_model(
model_config.num_hidden_layers = num_hidden_layers
# Determine the implementation to use
custom_vlm_cls = get_custom_vlm_cls(model_config) if is_vlm else None
if config.impl == "auto":
impl_to_use = "custom" if supports_custom_impl(model_config) else "hf"
logger.info(
f"Auto-selected implementation: {impl_to_use} (custom implementation {'supported' if supports_custom_impl(model_config) else 'not supported'})"
)
if is_vlm:
impl_to_use = "custom" if custom_vlm_cls is not None else "hf"
else:
impl_to_use = "custom" if supports_custom_impl(model_config) else "hf"
logger.info(f"Auto-selected implementation: {impl_to_use}")
else:
impl_to_use = config.impl
if is_vlm and impl_to_use != "hf":
raise ValueError(
f"VLM models only support impl='hf', but got impl='{config.impl}' (resolved to '{impl_to_use}'). "
f"Set impl='hf' or impl='auto' in your model config."
)
with device:
if is_vlm:
from transformers import AutoModelForImageTextToText
if impl_to_use == "custom" and custom_vlm_cls is not None:
model_cls = custom_vlm_cls
else:
from transformers import AutoModelForImageTextToText
model_cls = AutoModelForImageTextToText
model_cls = AutoModelForImageTextToText
else:
match impl_to_use:
case "hf":
@@ -295,8 +309,9 @@ def get_model(
model_cls = AutoModelForCausalLMPrimeRL
load_model_start_time = time.perf_counter()
# VLM models use standard HF API which requires torch_dtype, custom models use dtype
dtype_kwarg = {"torch_dtype": dtype} if is_vlm else {"dtype": dtype}
# HF VLM models require torch_dtype; custom PrimeRL models and text Auto models use dtype
use_torch_dtype = is_vlm and model_cls is not custom_vlm_cls
dtype_kwarg = {"torch_dtype": dtype} if use_torch_dtype else {"dtype": dtype}
if device == torch.device("meta"):
logger.info(f"Loading model {config.name} using {model_cls.__name__} to meta device")
model = model_cls.from_config(model_config, trust_remote_code=config.trust_remote_code, **dtype_kwarg)
@@ -352,7 +367,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
# For VLM models, shard the frozen vision encoder as a single unit
# This allows FSDP to manage the memory while keeping it frozen
is_vlm = is_vlm_model(config.name)
is_vlm = is_vlm_model(config.name) or (hasattr(model, "model") and hasattr(model.model, "visual"))
if is_vlm:
if hasattr(model, "model") and hasattr(model.model, "visual"):
vision_encoder = model.model.visual
@@ -568,6 +583,10 @@ def can_reinit_empty_buffers(model: nn.Module):
The main issue is with anything that is not in the checkpoint.
This is usually any non-persistent buffers.
"""
# Custom PrimeRL models handle buffer reinit via init_buffers_post_meta
if isinstance(model, PreTrainedModelPrimeRL):
return True
buffer_names = [name for name, _ in model.named_buffers()]
# TT MoE buffers
@@ -693,7 +712,10 @@ def _register_fa4_attention_interface() -> None:
def setup_model(
config: ModelConfig, parallel_dims: ParallelDims, loading_from_checkpoint_later: bool = False
config: ModelConfig,
parallel_dims: ParallelDims,
loading_from_checkpoint_later: bool = False,
fused_cross_entropy: bool = False,
) -> nn.Module:
if config.attn == "flash_attention_3" and not is_flash_attn_3_available():
raise ValueError(
@@ -722,10 +744,10 @@ def setup_model(
model = get_model(config, device=torch.device("cpu"), dtype=DTYPE_MAP[config.optimization_dtype])
lm_head_chunk_size: int | None = None
if isinstance(config.fused_lm_head_chunk_size, int):
lm_head_chunk_size = config.fused_lm_head_chunk_size
if isinstance(config.fused_lm_head_token_chunk_size, int):
lm_head_chunk_size = config.fused_lm_head_token_chunk_size
inject_prime_lm_head(model, chunk_size=lm_head_chunk_size)
inject_prime_lm_head(model, chunk_size=lm_head_chunk_size, fused_cross_entropy=fused_cross_entropy)
# Apply LoRA before FSDP setup
if config.lora is not None:
@@ -736,6 +758,10 @@ def setup_model(
if parallel_dims.ep_enabled:
apply_ep(model, parallel_dims)
# EP replaces params with DTensors that default to requires_grad=True,
# re-freeze base params that LoRA froze earlier.
if config.lora is not None:
freeze_all_except_lora_and_specified(model, config.lora)
# the right order is AC -> Compile -> FSDP
if config.ac is not None:
+17
View File
@@ -15,6 +15,7 @@ from prime_rl.trainer.models.glm_moe_dsa import GlmMoeDsaConfig, GlmMoeDsaForCau
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
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM
from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalLM
# Make custom config discoverable by AutoConfig
@@ -23,6 +24,7 @@ AutoConfig.register("glm4_moe", Glm4MoeConfig, exist_ok=True)
AutoConfig.register("glm_moe_dsa", GlmMoeDsaConfig, exist_ok=True)
AutoConfig.register("minimax_m2", MiniMaxM2Config, exist_ok=True)
AutoConfig.register("qwen3_moe", Qwen3MoeConfig, exist_ok=True)
AutoConfig.register("qwen3_5_moe_text", Qwen3_5MoeConfig, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, OrderedDict())
_CUSTOM_CAUSAL_LM_MAPPING.register(LlamaConfig, LlamaForCausalLM, exist_ok=True)
@@ -31,6 +33,7 @@ _CUSTOM_CAUSAL_LM_MAPPING.register(Glm4MoeConfig, Glm4MoeForCausalLM, exist_ok=T
_CUSTOM_CAUSAL_LM_MAPPING.register(GlmMoeDsaConfig, GlmMoeDsaForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(MiniMaxM2Config, MiniMaxM2ForCausalLM, 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)
class AutoModelForCausalLMPrimeRL(_BaseAutoModelClass):
@@ -52,10 +55,24 @@ def supports_custom_impl(model_config: PretrainedConfig) -> bool:
return type(model_config) in _CUSTOM_CAUSAL_LM_MAPPING
# Mapping from HF composite VLM model_type to custom PrimeRL class.
# Used by get_model() to dispatch VLMs that have a custom text model implementation.
# Points to the same unified class — the config drives text-only vs VLM behavior.
_CUSTOM_VLM_MAPPING: dict[str, type] = {
"qwen3_5_moe": Qwen3_5MoeForCausalLM,
}
def get_custom_vlm_cls(model_config: PretrainedConfig) -> type | None:
"""Return the custom PrimeRL VLM class for this config, or None if unsupported."""
return _CUSTOM_VLM_MAPPING.get(getattr(model_config, "model_type", None))
__all__ = [
"AutoModelForCausalLMPrimeRL",
"PreTrainedModelPrimeRL",
"supports_custom_impl",
"get_custom_vlm_cls",
"PrimeLmOutput",
"cast_float_and_contiguous",
]
@@ -512,7 +512,7 @@ class AfmoeModel(AfmoePreTrainedModel):
class AfmoeForCausalLM(AfmoePreTrainedModel, GenerationMixin):
_tied_weights_keys = ["lm_head.weight"]
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+22
View File
@@ -11,6 +11,11 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
after loading with meta device.
"""
@classmethod
def from_config(cls, config, **kwargs):
"""Public from_config that mirrors the Auto class API."""
return cls._from_config(config, **kwargs)
@classmethod
def _can_set_experts_implementation(cls) -> bool:
"""PrimeRL models use custom MoE implementations and don't support dynamic experts implementation."""
@@ -98,6 +103,23 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
"""
raise NotImplementedError(f"convert_layer_to_prime is not implemented for {cls.__name__}")
@classmethod
def convert_layer_to_vllm_kernel(
cls,
state_dict: dict[str, Tensor],
layer_idx: int,
quantize_fp8: bool = False,
) -> dict[str, Tensor]:
"""
Convert a single layer's state dict from PrimeRL format to vLLM kernel format.
Args:
state_dict: Layer weights in PrimeRL format.
layer_idx: Layer index to convert.
quantize_fp8: Whether to emit FP8 (e4m3) kernel weights with per-block scales.
"""
raise NotImplementedError(f"convert_layer_to_vllm_kernel is not implemented for {cls.__name__}")
def init_buffers_post_meta(self) -> None:
"""
Initialize buffers that are not in the state dict after loading with meta device.
+39
View File
@@ -0,0 +1,39 @@
import torch
from torch import Tensor
def quantize_to_fp8_blockwise(weight: Tensor, block_size: int = 128) -> tuple[Tensor, Tensor]:
"""Quantize a 2D tensor to FP8 e4m3 with per-block scales."""
if weight.ndim != 2:
raise ValueError(f"FP8 quantization expects a 2D tensor, got shape={tuple(weight.shape)}")
rows, cols = weight.shape
pad_rows = (block_size - rows % block_size) % block_size
pad_cols = (block_size - cols % block_size) % block_size
if pad_rows or pad_cols:
padded = torch.zeros(
rows + pad_rows,
cols + pad_cols,
dtype=weight.dtype,
device=weight.device,
)
padded[:rows, :cols] = weight
else:
padded = weight.contiguous()
padded_rows, padded_cols = padded.shape
blocks = padded.view(
padded_rows // block_size,
block_size,
padded_cols // block_size,
block_size,
).permute(0, 2, 1, 3)
fp8_max = torch.finfo(torch.float8_e4m3fn).max
max_abs = blocks.float().abs().amax(dim=(2, 3))
scales = (max_abs / fp8_max).clamp(min=1e-12)
blocks_fp8 = (blocks.float() / scales[:, :, None, None]).clamp(-fp8_max, fp8_max).to(torch.float8_e4m3fn)
quantized = blocks_fp8.permute(0, 2, 1, 3).reshape(padded_rows, padded_cols)[:rows, :cols].contiguous()
return quantized, scales.float().contiguous()
@@ -249,7 +249,7 @@ class Glm4MoeModel(Glm4MoePreTrainedModel):
@auto_docstring
class Glm4MoeForCausalLM(Glm4MoePreTrainedModel, GenerationMixin):
_tied_weights_keys = ["lm_head.weight"]
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
@@ -1,6 +1,8 @@
import torch
from torch import Tensor
from prime_rl.trainer.models.fp8 import quantize_to_fp8_blockwise
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
@@ -142,3 +144,116 @@ def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]):
num_layers = get_max_layer_num(state_dict)
for i in range(num_layers):
convert_tt_layer_to_hf(state_dict, i)
def convert_tt_layer_to_vllm_kernel(
state_dict: dict[str, Tensor],
layer_idx: int,
quantize_fp8: bool = False,
) -> dict[str, Tensor]:
"""Convert a single GLM layer from PrimeRL format to vLLM kernel format."""
out: dict[str, Tensor] = {}
prefix = f"model.layers.{layer_idx}"
def add(name: str, tensor: Tensor) -> None:
out[name] = tensor
def add_maybe_fp8(name: str, tensor: Tensor) -> None:
if quantize_fp8 and tensor.ndim == 2:
fp8_weight, scale = quantize_to_fp8_blockwise(tensor)
out[name] = fp8_weight
scale_name = name.removesuffix(".weight") + ".weight_scale_inv"
out[scale_name] = scale
return
out[name] = tensor
for name in [f"{prefix}.input_layernorm.weight", f"{prefix}.post_attention_layernorm.weight"]:
if name in state_dict:
add(name, state_dict[name])
q_a_key = f"{prefix}.self_attn.q_a_proj.weight"
kv_a_key = f"{prefix}.self_attn.kv_a_proj_with_mqa.weight"
if q_a_key in state_dict and kv_a_key in state_dict:
add_maybe_fp8(
f"{prefix}.self_attn.fused_qkv_a_proj.weight", torch.cat([state_dict[q_a_key], state_dict[kv_a_key]], dim=0)
)
for suffix in ["q_a_layernorm.weight", "kv_a_layernorm.weight"]:
key = f"{prefix}.self_attn.{suffix}"
if key in state_dict:
add(key, state_dict[key])
for suffix in ["q_b_proj.weight", "kv_b_proj.weight", "o_proj.weight"]:
key = f"{prefix}.self_attn.{suffix}"
if key in state_dict:
add_maybe_fp8(key, state_dict[key])
for suffix in ["indexer.wq_b.weight", "indexer.wk.weight"]:
key = f"{prefix}.self_attn.{suffix}"
if key in state_dict:
add_maybe_fp8(key, state_dict[key])
for suffix in ["indexer.k_norm.weight", "indexer.k_norm.bias", "indexer.weights_proj.weight"]:
key = f"{prefix}.self_attn.{suffix}"
if key in state_dict:
add(key, state_dict[key])
gate_key = f"{prefix}.mlp.gate_proj.weight"
up_key = f"{prefix}.mlp.up_proj.weight"
down_key = f"{prefix}.mlp.down_proj.weight"
if gate_key in state_dict and up_key in state_dict:
add_maybe_fp8(f"{prefix}.mlp.gate_up_proj.weight", torch.cat([state_dict[gate_key], state_dict[up_key]], dim=0))
if down_key in state_dict:
add_maybe_fp8(f"{prefix}.mlp.down_proj.weight", state_dict[down_key])
router_key = f"{prefix}.mlp.router.gate.weight"
if router_key in state_dict:
add(f"{prefix}.mlp.gate.weight", state_dict[router_key])
expert_bias_key = f"{prefix}.mlp.expert_bias"
if expert_bias_key in state_dict:
add(f"{prefix}.mlp.gate.e_score_correction_bias", state_dict[expert_bias_key])
w1_key = f"{prefix}.mlp.experts.w1"
w2_key = f"{prefix}.mlp.experts.w2"
w3_key = f"{prefix}.mlp.experts.w3"
if w1_key in state_dict and w2_key in state_dict and w3_key in state_dict:
w1 = state_dict[w1_key]
w2 = state_dict[w2_key]
w3 = state_dict[w3_key]
w13 = torch.cat([w1, w3], dim=1)
if quantize_fp8:
w13_fp8: list[Tensor] = []
w13_scales: list[Tensor] = []
w2_fp8: list[Tensor] = []
w2_scales: list[Tensor] = []
for expert_idx in range(w1.shape[0]):
expert_w13_fp8, expert_w13_scales = quantize_to_fp8_blockwise(w13[expert_idx])
expert_w2_fp8, expert_w2_scales = quantize_to_fp8_blockwise(w2[expert_idx])
w13_fp8.append(expert_w13_fp8)
w13_scales.append(expert_w13_scales)
w2_fp8.append(expert_w2_fp8)
w2_scales.append(expert_w2_scales)
out[f"{prefix}.mlp.experts.w13_weight"] = torch.stack(w13_fp8)
out[f"{prefix}.mlp.experts.w13_weight_scale_inv"] = torch.stack(w13_scales)
out[f"{prefix}.mlp.experts.w2_weight"] = torch.stack(w2_fp8)
out[f"{prefix}.mlp.experts.w2_weight_scale_inv"] = torch.stack(w2_scales)
else:
out[f"{prefix}.mlp.experts.w13_weight"] = w13
out[f"{prefix}.mlp.experts.w2_weight"] = w2
sw1_key = f"{prefix}.mlp.shared_expert.w1"
sw2_key = f"{prefix}.mlp.shared_expert.w2"
sw3_key = f"{prefix}.mlp.shared_expert.w3"
if sw1_key in state_dict and sw2_key in state_dict and sw3_key in state_dict:
sw1 = state_dict[sw1_key]
sw2 = state_dict[sw2_key]
sw3 = state_dict[sw3_key]
if sw1.ndim == 3:
sw1 = sw1.squeeze(0)
sw2 = sw2.squeeze(0)
sw3 = sw3.squeeze(0)
add_maybe_fp8(f"{prefix}.mlp.shared_experts.gate_up_proj.weight", torch.cat([sw1, sw3], dim=0))
add_maybe_fp8(f"{prefix}.mlp.shared_experts.down_proj.weight", sw2)
return out
@@ -18,6 +18,7 @@ from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import (
convert_hf_layer_to_tt,
convert_hf_to_tt_moe,
convert_tt_layer_to_hf,
convert_tt_layer_to_vllm_kernel,
convert_tt_to_hf_moe,
)
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
@@ -307,6 +308,12 @@ class GlmMoeDsaPreTrainedModel(PreTrainedModelPrimeRL):
convert_hf_layer_to_tt(state_dict, layer_idx)
return state_dict
@classmethod
def convert_layer_to_vllm_kernel(
cls, state_dict: dict[str, Tensor], layer_idx: int, quantize_fp8: bool = False
) -> dict[str, Tensor]:
return convert_tt_layer_to_vllm_kernel(state_dict, layer_idx, quantize_fp8=quantize_fp8)
@auto_docstring
class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
@@ -376,7 +383,7 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
@auto_docstring
class GlmMoeDsaForCausalLM(GlmMoeDsaPreTrainedModel, GenerationMixin):
_tied_weights_keys = ["lm_head.weight"]
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+5 -1
View File
@@ -246,7 +246,7 @@ def substitute_ring_attn(
heads_k_stride: int,
attn_impl: str = "flash_attention_2",
) -> None:
"""Patch _compute_attention on FlashAttention (and AfmoeFlashAttention) to use ring attention."""
"""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
@@ -285,3 +285,7 @@ def substitute_ring_attn(
from prime_rl.trainer.models.afmoe.modeling_afmoe import AfmoeFlashAttention
AfmoeFlashAttention._compute_attention = _ring_compute_attention
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
Qwen3_5MoeGatedFlashAttention._compute_attention = _ring_compute_attention
+123 -87
View File
@@ -16,6 +16,7 @@ class PrimeLmOutput(TypedDict, total=False):
logits: Tensor | None
logprobs: Tensor | None
entropy: Tensor | None
loss: Tensor | None
def cast_float_and_contiguous(output: PrimeLmOutput) -> PrimeLmOutput:
@@ -28,6 +29,7 @@ def cast_float_and_contiguous(output: PrimeLmOutput) -> PrimeLmOutput:
logits=_float_and_contiguous(output.get("logits")),
logprobs=_float_and_contiguous(output.get("logprobs")),
entropy=_float_and_contiguous(output.get("entropy")),
loss=output.get("loss"),
)
@@ -50,7 +52,9 @@ class FusedOutputLinear(torch.nn.Linear):
labels = labels.reshape(b * s).contiguous()
inv_t = 1.0 / temperature.reshape(b * s).contiguous() # [N]
logprobs, entropy = _ChunkedLogProbEntropyFn.apply(hidden_states, self.weight, labels, inv_t, self.chunk_size)
logprobs, entropy = _SequenceChunkedLogProbEntropyFn.apply(
hidden_states, self.weight, labels, inv_t, self.chunk_size
)
logprobs = logprobs.reshape(b, s)
entropy = entropy.reshape(b, s)
@@ -68,7 +72,53 @@ class VanillaOutputLinear(torch.nn.Linear):
return PrimeLmOutput(logits=super().forward(hidden_states))
class _ChunkedLogProbEntropyFn(torch.autograd.Function):
class FusedCrossEntropyOutputLinear(torch.nn.Linear):
"""Fused lm_head + cross-entropy loss using Liger kernel.
Avoids materializing the full [N, V] logits tensor by fusing the linear
projection with the cross-entropy loss computation.
"""
IGNORE_INDEX = -100
def __init__(self, in_features: int, out_features: int, softcap: float | None = None):
super().__init__(in_features, out_features, bias=False)
from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
self.fused_ce = LigerFusedLinearCrossEntropyLoss(
ignore_index=self.IGNORE_INDEX, reduction="mean", softcap=softcap
)
def forward(
self,
hidden_states: torch.Tensor,
labels: torch.Tensor | None = None,
temperature: Tensor | None = None,
) -> PrimeLmOutput:
if labels is None:
return PrimeLmOutput(logits=super().forward(hidden_states))
b, s, h = hidden_states.shape
hidden_flat = hidden_states.reshape(b * s, h).contiguous()
labels_flat = labels.reshape(b * s).contiguous()
loss = self.fused_ce(self.weight, hidden_flat, labels_flat)
return PrimeLmOutput(loss=loss)
def _online_logsumexp_and_weighted_update(
m: torch.Tensor, s: torch.Tensor, t: torch.Tensor, chunk_logits: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
chunk_m = torch.amax(chunk_logits, dim=-1)
m_new = torch.maximum(m, chunk_m)
exp_old = torch.exp(m - m_new)
chunk_exp = torch.exp(chunk_logits - m_new.unsqueeze(-1))
s_new = s * exp_old + chunk_exp.sum(dim=-1)
t_new = t * exp_old + (chunk_exp * chunk_logits).sum(dim=-1)
return m_new, s_new, t_new
class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
@staticmethod
def forward( # type: ignore[override]
ctx,
@@ -79,10 +129,7 @@ class _ChunkedLogProbEntropyFn(torch.autograd.Function):
chunk_size: int,
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Returns (per-token logprobs, per-token entropy) without materializing [N, V].
Important: entropy is computed from the *same* per-chunk logits used for the softmax
normalization (no extra W @ hidden matmul).
Returns per-token logprobs and entropy by chunking over flattened sequence tokens.
"""
assert hidden.dim() == 2, f"expected hidden [N,H], got {tuple(hidden.shape)}"
assert weight.dim() == 2, f"expected weight [V,H], got {tuple(weight.shape)}"
@@ -96,40 +143,44 @@ class _ChunkedLogProbEntropyFn(torch.autograd.Function):
device = hidden.device
n = hidden.shape[0]
vocab = weight.shape[0]
vocab_chunk_size = min(vocab, 8192)
logprobs = torch.empty((n,), device=device, dtype=torch.float32)
entropy = torch.empty((n,), device=device, dtype=torch.float32)
logz = torch.empty((n,), device=device, dtype=torch.float32)
# Running stats in fp32.
m = torch.full((n,), float("-inf"), device=device, dtype=torch.float32)
s = torch.zeros((n,), device=device, dtype=torch.float32)
t = torch.zeros((n,), device=device, dtype=torch.float32)
target_logits = torch.zeros((n,), device=device, dtype=torch.float32)
for start in range(0, n, chunk_size):
end = min(start + chunk_size, n)
hidden_chunk = hidden[start:end]
labels_chunk = labels[start:end]
inv_t_chunk = inv_temperature[start:end].unsqueeze(-1)
token_count = end - start
inv_t_broadcast = inv_temperature.unsqueeze(-1) # [N, 1]
m = torch.full((token_count,), float("-inf"), device=device, dtype=torch.float32)
s = torch.zeros((token_count,), device=device, dtype=torch.float32)
t = torch.zeros((token_count,), device=device, dtype=torch.float32)
target_logits = torch.zeros((token_count,), device=device, dtype=torch.float32)
for start in range(0, vocab, chunk_size):
end = min(start + chunk_size, vocab)
w_chunk = weight[start:end] # [C, H]
logits = hidden @ w_chunk.t() # [N, C] (model dtype)
logits_f = logits.to(torch.float32) * inv_t_broadcast # [N, C] fp32
for vocab_start in range(0, vocab, vocab_chunk_size):
vocab_end = min(vocab_start + vocab_chunk_size, vocab)
weight_chunk = weight[vocab_start:vocab_end]
logits_chunk = hidden_chunk @ weight_chunk.t()
scaled_logits = logits_chunk.to(torch.float32) * inv_t_chunk
# Shared intermediates for logZ and entropy stats.
m, s, t = _online_logsumexp_and_weighted_update(m, s, t, logits_f)
m, s, t = _online_logsumexp_and_weighted_update(m, s, t, scaled_logits)
# Fill target logits for labels that fall in this chunk.
mask = (labels >= start) & (labels < end)
if torch.any(mask):
idx = (labels[mask] - start).to(torch.long)
target_logits[mask] = logits_f[mask, idx]
mask = (labels_chunk >= vocab_start) & (labels_chunk < vocab_end)
if torch.any(mask):
idx = (labels_chunk[mask] - vocab_start).to(torch.long)
target_logits[mask] = scaled_logits[mask, idx]
logz = m + torch.log(s)
logprobs = target_logits - logz
entropy = logz - (t / s)
logz_chunk = m + torch.log(s)
logz[start:end] = logz_chunk
logprobs[start:end] = target_logits - logz_chunk
entropy[start:end] = logz_chunk - (t / s)
# Save for backward (recompute logits per chunk for grad)
ctx.save_for_backward(hidden, weight, labels, logz)
ctx.inv_temperature = inv_temperature # float or Tensor[N]
ctx.save_for_backward(hidden, weight, labels, inv_temperature, logz)
ctx.chunk_size = chunk_size
# Return fp32 for numerical stability (matching baseline behavior).
return logprobs, entropy
@staticmethod
@@ -138,79 +189,57 @@ class _ChunkedLogProbEntropyFn(torch.autograd.Function):
"Backward through entropy is not implemented in FusedOutputLinear"
)
hidden, weight, labels, logz = ctx.saved_tensors
inv_temperature: torch.Tensor = ctx.inv_temperature # [N]
hidden, weight, labels, inv_temperature, logz = ctx.saved_tensors
chunk_size: int = ctx.chunk_size
n, h = hidden.shape
n, _ = hidden.shape
vocab = weight.shape[0]
vocab_chunk_size = min(vocab, 8192)
grad_hidden = torch.zeros_like(hidden)
grad_weight = torch.zeros_like(weight)
g = grad_logprobs.to(torch.float32) # [N] fp32 for stable scaling
for start in range(0, n, chunk_size):
end = min(start + chunk_size, n)
hidden_chunk = hidden[start:end]
labels_chunk = labels[start:end]
grad_chunk = grad_logprobs[start:end].to(torch.float32)
inv_t_chunk = inv_temperature[start:end].unsqueeze(-1)
logz_chunk = logz[start:end]
inv_t_broadcast = inv_temperature.unsqueeze(-1) # [N, 1]
for vocab_start in range(0, vocab, vocab_chunk_size):
vocab_end = min(vocab_start + vocab_chunk_size, vocab)
weight_chunk = weight[vocab_start:vocab_end]
logits_chunk = hidden_chunk @ weight_chunk.t()
scaled_logits = logits_chunk.to(torch.float32) * inv_t_chunk
probs = torch.exp(scaled_logits - logz_chunk.unsqueeze(-1))
for start in range(0, vocab, chunk_size):
end = min(start + chunk_size, vocab)
w_chunk = weight[start:end] # [C, H]
grad_logits = (-grad_chunk).unsqueeze(-1) * probs
mask = (labels_chunk >= vocab_start) & (labels_chunk < vocab_end)
if torch.any(mask):
idx = (labels_chunk[mask] - vocab_start).to(torch.long)
grad_logits[mask, idx] += grad_chunk[mask]
grad_logits = grad_logits * inv_t_chunk
logits = hidden @ w_chunk.t() # [N, C] (model dtype)
logits_f = logits.to(torch.float32) * inv_t_broadcast # [N, C] fp32
# p = softmax(logits_f) chunk = exp(logits_f - logz)
p = torch.exp(logits_f - logz.unsqueeze(-1)) # [N, C] fp32
# dL/dlogits = g * (1_{label} - p)
grad_logits = (-g).unsqueeze(-1) * p # [N, C] fp32
mask = (labels >= start) & (labels < end)
if torch.any(mask):
idx = (labels[mask] - start).to(torch.long)
grad_logits[mask, idx] += g[mask]
# Chain through temperature scaling: logits_f = logits * inv_temperature
grad_logits = grad_logits * inv_t_broadcast
grad_hidden.add_(grad_logits.to(hidden.dtype) @ w_chunk)
grad_w_chunk = grad_logits.to(weight.dtype).t() @ hidden # [C, H]
grad_weight[start:end].add_(grad_w_chunk)
grad_hidden[start:end].add_(grad_logits.to(hidden.dtype) @ weight_chunk)
grad_weight[vocab_start:vocab_end].add_(grad_logits.to(weight.dtype).t() @ hidden_chunk)
return grad_hidden, grad_weight, None, None, None
def _online_logsumexp_and_weighted_update(
m: torch.Tensor, s: torch.Tensor, t: torch.Tensor, chunk_logits: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
def inject_prime_lm_head(model: nn.Module, chunk_size: int | None = None, fused_cross_entropy: bool = False) -> None:
"""
Online logsumexp + weighted-sum accumulator for entropy.
Maintains:
m: running max
s: running sum(exp(x - m))
t: running sum(exp(x - m) * x)
"""
chunk_m = torch.amax(chunk_logits, dim=-1) # [N]
m_new = torch.maximum(m, chunk_m) # [N]
exp_old = torch.exp(m - m_new)
chunk_exp = torch.exp(chunk_logits - m_new.unsqueeze(-1)) # [N, C]
s_new = s * exp_old + chunk_exp.sum(dim=-1)
t_new = t * exp_old + (chunk_exp * chunk_logits).sum(dim=-1)
return m_new, s_new, t_new
def inject_prime_lm_head(model: nn.Module, chunk_size: int | None = None) -> None:
"""
Inject a PrimeRL LM head (FusedOutputLinear or VanillaOutputLinear) into a model.
Inject a PrimeRL LM head into a model.
This replaces the model's lm_head and overrides the forward method to use labels
and temperature for chunked loss computation.
Args:
model: The model to wrap.
chunk_size: If int, use FusedOutputLinear with chunked logprob/entropy computation with the given chunk size.
If None, use VanillaOutputLinear which just returns logits.
chunk_size: When set to an int, uses FusedOutputLinear with sequence-token chunked
logprob/entropy computation (for RL).
fused_cross_entropy: When True, uses FusedCrossEntropyOutputLinear which fuses the lm_head
projection with cross-entropy loss to avoid materializing full logits (for SFT).
"""
# Guards so we have nicer error messages when a non-standard model is used
assert hasattr(model, "model"), f"model doesnt have backbone in model.model:\n{model}"
@@ -225,21 +254,28 @@ def inject_prime_lm_head(model: nn.Module, chunk_size: int | None = None) -> Non
# Check for Gemma-style softcapping - dispatch to specialized implementation
final_logit_softcapping = getattr(model.config, "final_logit_softcapping", None)
if final_logit_softcapping:
if final_logit_softcapping and not fused_cross_entropy:
from prime_rl.trainer.models.layers.lm_head_gemma import inject_gemma_lm_head
inject_gemma_lm_head(model, chunk_size, final_logit_softcapping)
return
logger.info(f"Injecting Prime LM head with chunk size {chunk_size}")
# Replace the lm_head with the appropriate wrapper
old_lm_head = model.lm_head
if chunk_size is not None:
if fused_cross_entropy:
logger.info("Injecting fused cross-entropy LM head (Liger kernel)")
model.lm_head = FusedCrossEntropyOutputLinear(
in_features=old_lm_head.in_features,
out_features=old_lm_head.out_features,
softcap=final_logit_softcapping,
)
elif isinstance(chunk_size, int):
logger.info(f"Injecting chunked LM head with chunk size {chunk_size}")
model.lm_head = FusedOutputLinear(
in_features=old_lm_head.in_features, out_features=old_lm_head.out_features, chunk_size=chunk_size
)
else:
logger.info("Injecting vanilla LM head")
model.lm_head = VanillaOutputLinear(in_features=old_lm_head.in_features, out_features=old_lm_head.out_features)
model.lm_head.weight = old_lm_head.weight
del old_lm_head
@@ -66,10 +66,7 @@ class _GemmaChunkedLogProbEntropyFn(torch.autograd.Function):
softcap: float,
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Returns (per-token logprobs, per-token entropy) without materializing [N, V].
Important: entropy is computed from the *same* per-chunk logits used for the softmax
normalization (no extra W @ hidden matmul).
Returns per-token logprobs and entropy by chunking over flattened sequence tokens.
"""
assert hidden.dim() == 2, f"expected hidden [N,H], got {tuple(hidden.shape)}"
assert weight.dim() == 2, f"expected weight [V,H], got {tuple(weight.shape)}"
@@ -83,45 +80,47 @@ class _GemmaChunkedLogProbEntropyFn(torch.autograd.Function):
device = hidden.device
n = hidden.shape[0]
vocab = weight.shape[0]
vocab_chunk_size = min(vocab, 8192)
logprobs = torch.empty((n,), device=device, dtype=torch.float32)
entropy = torch.empty((n,), device=device, dtype=torch.float32)
logz = torch.empty((n,), device=device, dtype=torch.float32)
# Running stats in fp32.
m = torch.full((n,), float("-inf"), device=device, dtype=torch.float32)
s = torch.zeros((n,), device=device, dtype=torch.float32)
t = torch.zeros((n,), device=device, dtype=torch.float32)
target_logits = torch.zeros((n,), device=device, dtype=torch.float32)
for start in range(0, n, chunk_size):
end = min(start + chunk_size, n)
hidden_chunk = hidden[start:end]
labels_chunk = labels[start:end]
inv_t_chunk = inv_temperature[start:end].unsqueeze(-1)
token_count = end - start
inv_t_broadcast = inv_temperature.unsqueeze(-1) # [N, 1]
m = torch.full((token_count,), float("-inf"), device=device, dtype=torch.float32)
s = torch.zeros((token_count,), device=device, dtype=torch.float32)
t = torch.zeros((token_count,), device=device, dtype=torch.float32)
target_logits = torch.zeros((token_count,), device=device, dtype=torch.float32)
for start in range(0, vocab, chunk_size):
end = min(start + chunk_size, vocab)
w_chunk = weight[start:end] # [C, H]
logits = hidden @ w_chunk.t() # [N, C] (model dtype)
logits_f = logits.to(torch.float32) # [N, C] fp32
for vocab_start in range(0, vocab, vocab_chunk_size):
vocab_end = min(vocab_start + vocab_chunk_size, vocab)
weight_chunk = weight[vocab_start:vocab_end]
logits_chunk = hidden_chunk @ weight_chunk.t()
scaled_logits = logits_chunk.to(torch.float32)
scaled_logits = softcap * torch.tanh(scaled_logits / softcap)
scaled_logits = scaled_logits * inv_t_chunk
# Apply final logit softcapping (Gemma2/3) before temperature
logits_f = softcap * torch.tanh(logits_f / softcap)
logits_f = logits_f * inv_t_broadcast # [N, C] fp32
m, s, t = _online_logsumexp_and_weighted_update(m, s, t, scaled_logits)
# Shared intermediates for logZ and entropy stats.
m, s, t = _online_logsumexp_and_weighted_update(m, s, t, logits_f)
mask = (labels_chunk >= vocab_start) & (labels_chunk < vocab_end)
if torch.any(mask):
idx = (labels_chunk[mask] - vocab_start).to(torch.long)
target_logits[mask] = scaled_logits[mask, idx]
# Fill target logits for labels that fall in this chunk.
mask = (labels >= start) & (labels < end)
if torch.any(mask):
idx = (labels[mask] - start).to(torch.long)
target_logits[mask] = logits_f[mask, idx]
logz_chunk = m + torch.log(s)
logz[start:end] = logz_chunk
logprobs[start:end] = target_logits - logz_chunk
entropy[start:end] = logz_chunk - (t / s)
logz = m + torch.log(s)
logprobs = target_logits - logz
entropy = logz - (t / s)
# Save for backward (recompute logits per chunk for grad)
ctx.save_for_backward(hidden, weight, labels, logz)
ctx.inv_temperature = inv_temperature
ctx.save_for_backward(hidden, weight, labels, inv_temperature, logz)
ctx.chunk_size = chunk_size
ctx.softcap = softcap
# Return fp32 for numerical stability (matching baseline behavior).
return logprobs, entropy
@staticmethod
@@ -130,52 +129,45 @@ class _GemmaChunkedLogProbEntropyFn(torch.autograd.Function):
"Backward through entropy is not implemented in GemmaFusedOutputLinear"
)
hidden, weight, labels, logz = ctx.saved_tensors
inv_temperature: torch.Tensor = ctx.inv_temperature # [N]
hidden, weight, labels, inv_temperature, logz = ctx.saved_tensors
chunk_size: int = ctx.chunk_size
softcap: float = ctx.softcap
n, h = hidden.shape
n, _ = hidden.shape
vocab = weight.shape[0]
vocab_chunk_size = min(vocab, 8192)
grad_hidden = torch.zeros_like(hidden)
grad_weight = torch.zeros_like(weight)
g = grad_logprobs.to(torch.float32) # [N] fp32 for stable scaling
for start in range(0, n, chunk_size):
end = min(start + chunk_size, n)
hidden_chunk = hidden[start:end]
labels_chunk = labels[start:end]
grad_chunk = grad_logprobs[start:end].to(torch.float32)
inv_t_chunk = inv_temperature[start:end].unsqueeze(-1)
logz_chunk = logz[start:end]
inv_t_broadcast = inv_temperature.unsqueeze(-1) # [N, 1]
for vocab_start in range(0, vocab, vocab_chunk_size):
vocab_end = min(vocab_start + vocab_chunk_size, vocab)
weight_chunk = weight[vocab_start:vocab_end]
logits_chunk = hidden_chunk @ weight_chunk.t()
logits_f = logits_chunk.to(torch.float32)
tanh_val = torch.tanh(logits_f / softcap)
scaled_logits = softcap * tanh_val
scaled_logits = scaled_logits * inv_t_chunk
probs = torch.exp(scaled_logits - logz_chunk.unsqueeze(-1))
for start in range(0, vocab, chunk_size):
end = min(start + chunk_size, vocab)
w_chunk = weight[start:end] # [C, H]
grad_logits = (-grad_chunk).unsqueeze(-1) * probs
mask = (labels_chunk >= vocab_start) & (labels_chunk < vocab_end)
if torch.any(mask):
idx = (labels_chunk[mask] - vocab_start).to(torch.long)
grad_logits[mask, idx] += grad_chunk[mask]
grad_logits = grad_logits * inv_t_chunk
grad_logits = grad_logits * (1 - tanh_val**2)
logits = hidden @ w_chunk.t() # [N, C] (model dtype)
logits_f = logits.to(torch.float32) # [N, C] fp32
# Apply final logit softcapping (Gemma2/3) before temperature
tanh_val = torch.tanh(logits_f / softcap)
logits_f = softcap * tanh_val
logits_f = logits_f * inv_t_broadcast # [N, C] fp32
# p = softmax(logits_f) chunk = exp(logits_f - logz)
p = torch.exp(logits_f - logz.unsqueeze(-1)) # [N, C] fp32
# dL/dlogits = g * (1_{label} - p)
grad_logits = (-g).unsqueeze(-1) * p # [N, C] fp32
mask = (labels >= start) & (labels < end)
if torch.any(mask):
idx = (labels[mask] - start).to(torch.long)
grad_logits[mask, idx] += g[mask]
# Chain through temperature scaling
grad_logits = grad_logits * inv_t_broadcast
# Chain through softcapping: d/dx[c*tanh(x/c)] = 1 - tanh^2(x/c)
grad_logits = grad_logits * (1 - tanh_val**2)
grad_hidden.add_(grad_logits.to(hidden.dtype) @ w_chunk)
grad_w_chunk = grad_logits.to(weight.dtype).t() @ hidden # [C, H]
grad_weight[start:end].add_(grad_w_chunk)
grad_hidden[start:end].add_(grad_logits.to(hidden.dtype) @ weight_chunk)
grad_weight[vocab_start:vocab_end].add_(grad_logits.to(weight.dtype).t() @ hidden_chunk)
return grad_hidden, grad_weight, None, None, None, None
@@ -3,6 +3,7 @@ import math
import torch
import torch.nn.functional as F
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
@@ -285,6 +286,16 @@ class MultiLoRAGroupedExperts(MultiLoRAModule):
detached_w3_lora_a = self.w3_lora_A[idx].detach()
detached_w3_lora_b = self.w3_lora_B[idx].detach()
# With EP, LoRA weights are DTensors sharded across expert-parallel ranks.
# Gather them before per-expert indexing.
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()
detached_w3_lora_a = detached_w3_lora_a.full_tensor()
detached_w3_lora_b = detached_w3_lora_b.full_tensor()
# The clone is necessary to avoid views that cause giant memory spikes
# TODO: There's probably a better way to do this
for expert_id in range(self.num_experts):
@@ -320,6 +331,39 @@ class MultiLoRAGroupedExperts(MultiLoRAModule):
base_w2 = self.base_layer.w2 # [num_experts, dim, hidden_dim]
base_w3 = self.base_layer.w3 # [num_experts, hidden_dim, dim]
# EP handling: mirror the @expert_parallel decorator — convert DTensors
# to local shards and permute tokens by local expert with alignment padding.
permuted_indices = None
if isinstance(base_w1, DTensor):
from torchtitan.distributed.expert_parallel import TOKEN_GROUP_ALIGN_SIZE_M
from torchtitan.experiments.kernels.moe.indices import generate_permute_indices
base_w1 = base_w1.to_local()
base_w2 = base_w2.to_local()
base_w3 = base_w3.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()
w3_lora_a = w3_lora_a.to_local()
w3_lora_b = w3_lora_b.to_local()
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, :]
# Compute offsets for grouped_mm
offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32)
@@ -345,10 +389,9 @@ class MultiLoRAGroupedExperts(MultiLoRAModule):
w2_lora_out = _run_lora_grouped_mm(lora_h, w2_lora_a, w2_lora_b, offsets)
out = h2_base + scaling * w2_lora_out.bfloat16()
return out.type_as(x)
out = out.type_as(x)
else:
# For-loop fallback for older GPUs
return self._forward_for_loop(
out = self._forward_for_loop(
x,
num_tokens_per_expert,
w1_lora_a,
@@ -363,6 +406,19 @@ class MultiLoRAGroupedExperts(MultiLoRAModule):
scaling,
)
# EP handling: unpermute output back to dispatched token order
if permuted_indices is not None:
# For-loop may produce fewer rows than permuted input (no padding rows),
# pad to match before unpermuting
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,
@@ -222,7 +222,7 @@ class LlamaModel(LlamaPreTrainedModel):
@auto_docstring
class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
_tied_weights_keys = ["lm_head.weight"]
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
@@ -210,7 +210,7 @@ class MiniMaxM2Model(MiniMaxM2PreTrainedModel):
@auto_docstring
class MiniMaxM2ForCausalLM(MiniMaxM2PreTrainedModel, GenerationMixin):
_tied_weights_keys = ["lm_head.weight"]
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
@@ -0,0 +1,13 @@
from prime_rl.trainer.models.qwen3_5_moe.configuration_qwen3_5_moe import Qwen3_5MoeConfig
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
Qwen3_5MoeForCausalLM,
Qwen3_5MoeModel,
Qwen3_5MoePreTrainedModel,
)
__all__ = [
"Qwen3_5MoeConfig",
"Qwen3_5MoeForCausalLM",
"Qwen3_5MoeModel",
"Qwen3_5MoePreTrainedModel",
]
@@ -0,0 +1,108 @@
from transformers.configuration_utils import PretrainedConfig
class Qwen3_5MoeConfig(PretrainedConfig):
r"""
Configuration class for the custom PrimeRL Qwen3.5-MoE model.
This matches the HuggingFace `Qwen3_5MoeTextConfig` architecture:
hybrid attention (GatedDeltaNet linear + gated softmax), MoE with gated shared expert,
and (1+weight) RMSNorm parameterization.
Defaults match Qwen3.5-35B-A3B.
"""
model_type = "qwen3_5_moe_text"
keys_to_ignore_at_inference = ["past_key_values"]
def __init__(
self,
vocab_size=248320,
hidden_size=2048,
num_hidden_layers=40,
num_attention_heads=16,
num_key_value_heads=2,
hidden_act="silu",
max_position_embeddings=32768,
initializer_range=0.02,
rms_norm_eps=1e-6,
use_cache=True,
tie_word_embeddings=False,
rope_theta=10000.0,
rope_scaling=None,
attention_bias=False,
attention_dropout=0.0,
head_dim=256,
# Linear attention (GatedDeltaNet) params
linear_conv_kernel_dim=4,
linear_key_head_dim=128,
linear_value_head_dim=128,
linear_num_key_heads=16,
linear_num_value_heads=32,
# MoE params
moe_intermediate_size=512,
shared_expert_intermediate_size=512,
num_experts_per_tok=8,
num_experts=256,
output_router_logits=False,
router_aux_loss_coef=0.001,
# Layer type configuration
layer_types=None,
# PrimeRL additions
load_balance_coeff=None,
use_grouped_mm=True,
pad_token_id=None,
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.rope_theta = rope_theta
self.rope_scaling = rope_scaling
self.attention_bias = attention_bias
self.attention_dropout = attention_dropout
self.head_dim = head_dim
self.pad_token_id = pad_token_id
# Partial RoPE: only rotate 25% of head_dim
kwargs.setdefault("partial_rotary_factor", 0.25)
# Layer types: default every 4th layer is full_attention, rest linear_attention
self.layer_types = layer_types
if self.layer_types is None:
interval_pattern = kwargs.pop("full_attention_interval", 4)
self.layer_types = [
"linear_attention" if bool((i + 1) % interval_pattern) else "full_attention"
for i in range(self.num_hidden_layers)
]
# Linear attention (GatedDeltaNet) params
self.linear_conv_kernel_dim = linear_conv_kernel_dim
self.linear_key_head_dim = linear_key_head_dim
self.linear_value_head_dim = linear_value_head_dim
self.linear_num_key_heads = linear_num_key_heads
self.linear_num_value_heads = linear_num_value_heads
# MoE params
self.moe_intermediate_size = moe_intermediate_size
self.shared_expert_intermediate_size = shared_expert_intermediate_size
self.num_experts_per_tok = num_experts_per_tok
self.num_experts = num_experts
self.output_router_logits = output_router_logits
self.router_aux_loss_coef = router_aux_loss_coef
# PrimeRL additions
self.load_balance_coeff = load_balance_coeff
self.use_grouped_mm = use_grouped_mm
super().__init__(
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
@@ -0,0 +1,125 @@
import torch
from torch import Tensor
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
"""Get the maximum number of layers in the model."""
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
"""Convert a single layer from HF to PrimeRL format in-place.
Handles:
- Router: mlp.gate.weight -> mlp.router.gate.weight
- Routed experts: fused gate_up_proj/down_proj or per-expert -> w1/w2/w3
- Shared expert: mlp.shared_expert.{gate,up,down}_proj.weight -> shared_expert.{w1,w3,w2}.weight
- Shared expert gate: mlp.shared_expert_gate.weight -> shared_expert_gate.weight
"""
i = layer_idx
# Router: mlp.gate.weight -> mlp.router.gate.weight
gate_key = f"model.layers.{i}.mlp.gate.weight"
if gate_key not in state_dict:
return
state_dict[f"model.layers.{i}.mlp.router.gate.weight"] = state_dict.pop(gate_key)
# Routed experts: convert to fused w1/w2/w3 format
if f"model.layers.{i}.mlp.experts.gate_up_proj" in state_dict:
# New fused format (transformers 5.0+): gate_up_proj shape (num_experts, 2*moe_dim, dim)
gate_up_proj = state_dict.pop(f"model.layers.{i}.mlp.experts.gate_up_proj")
down_proj = state_dict.pop(f"model.layers.{i}.mlp.experts.down_proj")
moe_dim = gate_up_proj.shape[1] // 2
w1 = gate_up_proj[:, :moe_dim, :] # gate
w3 = gate_up_proj[:, moe_dim:, :] # up
w2 = down_proj # down
else:
# Old per-expert format
num_experts = len([k for k in state_dict.keys() if f"model.layers.{i}.mlp.experts" in k and "gate_proj" in k])
if num_experts == 0:
return
dim, moe_dim = state_dict[f"model.layers.{i}.mlp.experts.0.down_proj.weight"].shape
dtype = state_dict[f"model.layers.{i}.mlp.experts.0.down_proj.weight"].dtype
w1 = torch.empty((num_experts, moe_dim, dim), dtype=dtype)
w2 = torch.empty((num_experts, dim, moe_dim), dtype=dtype)
w3 = torch.empty((num_experts, moe_dim, dim), dtype=dtype)
for j in range(num_experts):
w1[j].copy_(state_dict.pop(f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"))
w2[j].copy_(state_dict.pop(f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"))
w3[j].copy_(state_dict.pop(f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"))
state_dict[f"model.layers.{i}.mlp.experts.w1"] = w1
state_dict[f"model.layers.{i}.mlp.experts.w2"] = w2
state_dict[f"model.layers.{i}.mlp.experts.w3"] = w3
# Shared expert: mlp.shared_expert.{gate,up,down}_proj -> shared_expert.{w1,w3,w2}
se_gate_key = f"model.layers.{i}.mlp.shared_expert.gate_proj.weight"
if se_gate_key in state_dict:
state_dict[f"model.layers.{i}.shared_expert.w1.weight"] = state_dict.pop(se_gate_key)
state_dict[f"model.layers.{i}.shared_expert.w2.weight"] = state_dict.pop(
f"model.layers.{i}.mlp.shared_expert.down_proj.weight"
)
state_dict[f"model.layers.{i}.shared_expert.w3.weight"] = state_dict.pop(
f"model.layers.{i}.mlp.shared_expert.up_proj.weight"
)
# Shared expert gate: mlp.shared_expert_gate.weight -> shared_expert_gate.weight
seg_key = f"model.layers.{i}.mlp.shared_expert_gate.weight"
if seg_key in state_dict:
state_dict[f"model.layers.{i}.shared_expert_gate.weight"] = state_dict.pop(seg_key)
def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int):
"""Convert a single layer from PrimeRL to HF format in-place."""
i = layer_idx
# Router
router_key = f"model.layers.{i}.mlp.router.gate.weight"
if router_key not in state_dict:
return
state_dict[f"model.layers.{i}.mlp.gate.weight"] = state_dict.pop(router_key)
# Routed experts: w1/w2/w3 -> per-expert format
w1 = state_dict.pop(f"model.layers.{i}.mlp.experts.w1")
w2 = state_dict.pop(f"model.layers.{i}.mlp.experts.w2")
w3 = state_dict.pop(f"model.layers.{i}.mlp.experts.w3")
num_experts = w1.shape[0]
for j in range(num_experts):
state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"] = w1[j]
state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"] = w2[j]
state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"] = w3[j]
# Shared expert: shared_expert.{w1,w2,w3} -> mlp.shared_expert.{gate,down,up}_proj
se_w1_key = f"model.layers.{i}.shared_expert.w1.weight"
if se_w1_key in state_dict:
state_dict[f"model.layers.{i}.mlp.shared_expert.gate_proj.weight"] = state_dict.pop(se_w1_key)
state_dict[f"model.layers.{i}.mlp.shared_expert.down_proj.weight"] = state_dict.pop(
f"model.layers.{i}.shared_expert.w2.weight"
)
state_dict[f"model.layers.{i}.mlp.shared_expert.up_proj.weight"] = state_dict.pop(
f"model.layers.{i}.shared_expert.w3.weight"
)
# Shared expert gate
seg_key = f"model.layers.{i}.shared_expert_gate.weight"
if seg_key in state_dict:
state_dict[f"model.layers.{i}.mlp.shared_expert_gate.weight"] = state_dict.pop(seg_key)
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]):
"""Convert all MoE weights from HF to PrimeRL format in-place."""
num_layers = get_max_layer_num(state_dict)
for i in range(num_layers):
convert_hf_layer_to_tt(state_dict, i)
def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]):
"""Convert all MoE weights from PrimeRL to HF format in-place."""
num_layers = get_max_layer_num(state_dict)
for i in range(num_layers):
convert_tt_layer_to_hf(state_dict, i)
@@ -0,0 +1,971 @@
import functools
from dataclasses import dataclass
from typing import Optional, Union
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from transformers.cache_utils import Cache
from transformers.configuration_utils import PretrainedConfig
from transformers.generation import GenerationMixin
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import MoeModelOutputWithPast
from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeVisionModel
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs, logging
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig, apply_rotary_pos_emb
from .configuration_qwen3_5_moe import Qwen3_5MoeConfig
from .converting_qwen3_5_moe import (
convert_hf_layer_to_tt,
convert_hf_to_tt_moe,
convert_tt_layer_to_hf,
convert_tt_to_hf_moe,
)
# Flash attention imports
try:
from flash_attn import flash_attn_varlen_func
except ImportError:
flash_attn_varlen_func = None # type: ignore
try:
from flash_attn_interface import flash_attn_varlen_func as flash_attn_3_varlen_func
except ImportError:
flash_attn_3_varlen_func = None # type: ignore
try:
from flash_attn.cute import flash_attn_varlen_func as flash_attn_4_varlen_func
except ImportError:
flash_attn_4_varlen_func = None # type: ignore
# Flash linear attention imports (for GatedDeltaNet fast path)
try:
from causal_conv1d import causal_conv1d_fn
except ImportError:
causal_conv1d_fn = None # type: ignore
try:
from fla.modules import FusedRMSNormGated
from fla.ops.gated_delta_rule import chunk_gated_delta_rule
except ImportError:
chunk_gated_delta_rule = None # type: ignore
FusedRMSNormGated = None # type: ignore
logger = logging.get_logger(__name__)
# ---------------------------------------------------------------------------
# RMSNorm variants
# ---------------------------------------------------------------------------
class Qwen3_5MoeRMSNorm(nn.Module):
"""RMSNorm with (1+weight) parameterization. Weight initialized to zeros."""
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.zeros(dim))
def _norm(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x):
output = self._norm(x.float())
output = output * (1.0 + self.weight.float())
return output.type_as(x)
class Qwen3_5MoeRMSNormGated(nn.Module):
"""RMSNorm with SiLU gating for GatedDeltaNet output."""
def __init__(self, hidden_size, eps=1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states, gate=None):
input_dtype = hidden_states.dtype
hidden_states = hidden_states.to(torch.float32)
variance = hidden_states.pow(2).mean(-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
hidden_states = self.weight * hidden_states.to(input_dtype)
hidden_states = hidden_states * F.silu(gate.to(torch.float32))
return hidden_states.to(input_dtype)
# ---------------------------------------------------------------------------
# GatedDeltaNet linear attention
# ---------------------------------------------------------------------------
def l2norm(x: torch.FloatTensor, dim: int = -1, eps: float = 1e-6):
inv_norm = torch.rsqrt((x * x).sum(dim=dim, keepdim=True) + eps)
return x * inv_norm
def torch_chunk_gated_delta_rule(
query,
key,
value,
g,
beta,
chunk_size=64,
initial_state=None,
output_final_state=False,
use_qk_l2norm_in_kernel=False,
):
"""Pure-PyTorch fallback for chunk_gated_delta_rule."""
initial_dtype = query.dtype
if use_qk_l2norm_in_kernel:
query = l2norm(query, dim=-1, eps=1e-6)
key = l2norm(key, dim=-1, eps=1e-6)
query, key, value, beta, g = [
x.transpose(1, 2).contiguous().to(torch.float32) for x in (query, key, value, beta, g)
]
batch_size, num_heads, sequence_length, k_head_dim = key.shape
v_head_dim = value.shape[-1]
pad_size = (chunk_size - sequence_length % chunk_size) % chunk_size
query = F.pad(query, (0, 0, 0, pad_size))
key = F.pad(key, (0, 0, 0, pad_size))
value = F.pad(value, (0, 0, 0, pad_size))
beta = F.pad(beta, (0, pad_size))
g = F.pad(g, (0, pad_size))
total_sequence_length = sequence_length + pad_size
scale = 1 / (query.shape[-1] ** 0.5)
query = query * scale
v_beta = value * beta.unsqueeze(-1)
k_beta = key * beta.unsqueeze(-1)
query, key, value, k_beta, v_beta = [
x.reshape(x.shape[0], x.shape[1], -1, chunk_size, x.shape[-1]) for x in (query, key, value, k_beta, v_beta)
]
g = g.reshape(g.shape[0], g.shape[1], -1, chunk_size)
mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device), diagonal=0)
g = g.cumsum(dim=-1)
decay_mask = ((g.unsqueeze(-1) - g.unsqueeze(-2)).tril().exp().float()).tril()
attn = -((k_beta @ key.transpose(-1, -2)) * decay_mask).masked_fill(mask, 0)
for i in range(1, chunk_size):
row = attn[..., i, :i].clone()
sub = attn[..., :i, :i].clone()
attn[..., i, :i] = row + (row.unsqueeze(-1) * sub).sum(-2)
attn = attn + torch.eye(chunk_size, dtype=attn.dtype, device=attn.device)
value = attn @ v_beta
k_cumdecay = attn @ (k_beta * g.exp().unsqueeze(-1))
last_recurrent_state = (
torch.zeros(batch_size, num_heads, k_head_dim, v_head_dim).to(value)
if initial_state is None
else initial_state.to(value)
)
core_attn_out = torch.zeros_like(value)
mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device), diagonal=1)
for i in range(0, total_sequence_length // chunk_size):
q_i, k_i, v_i = query[:, :, i], key[:, :, i], value[:, :, i]
attn = (q_i @ k_i.transpose(-1, -2) * decay_mask[:, :, i]).masked_fill_(mask, 0)
v_prime = (k_cumdecay[:, :, i]) @ last_recurrent_state
v_new = v_i - v_prime
attn_inter = (q_i * g[:, :, i, :, None].exp()) @ last_recurrent_state
core_attn_out[:, :, i] = attn_inter + attn @ v_new
last_recurrent_state = (
last_recurrent_state * g[:, :, i, -1, None, None].exp()
+ (k_i * (g[:, :, i, -1, None] - g[:, :, i]).exp()[..., None]).transpose(-1, -2) @ v_new
)
if not output_final_state:
last_recurrent_state = None
core_attn_out = core_attn_out.reshape(core_attn_out.shape[0], core_attn_out.shape[1], -1, core_attn_out.shape[-1])
core_attn_out = core_attn_out[:, :, :sequence_length]
core_attn_out = core_attn_out.transpose(1, 2).contiguous().to(initial_dtype)
return core_attn_out, last_recurrent_state
class Qwen3_5MoeGatedDeltaNet(nn.Module):
"""GatedDeltaNet linear attention with Conv1d, beta/gamma gates, and chunk delta rule."""
def __init__(self, config: Qwen3_5MoeConfig):
super().__init__()
self.hidden_size = config.hidden_size
self.num_v_heads = config.linear_num_value_heads
self.num_k_heads = config.linear_num_key_heads
self.head_k_dim = config.linear_key_head_dim
self.head_v_dim = config.linear_value_head_dim
self.key_dim = self.head_k_dim * self.num_k_heads
self.value_dim = self.head_v_dim * self.num_v_heads
self.conv_kernel_size = config.linear_conv_kernel_dim
self.activation = config.hidden_act
self.layer_norm_epsilon = config.rms_norm_eps
# QKV convolution (depthwise)
self.conv_dim = self.key_dim * 2 + self.value_dim
self.conv1d = nn.Conv1d(
in_channels=self.conv_dim,
out_channels=self.conv_dim,
bias=False,
kernel_size=self.conv_kernel_size,
groups=self.conv_dim,
padding=self.conv_kernel_size - 1,
)
# Time step projection
self.dt_bias = nn.Parameter(torch.ones(self.num_v_heads))
A = torch.empty(self.num_v_heads).uniform_(0, 16)
self.A_log = nn.Parameter(torch.log(A))
# Gated RMSNorm on output (per-head)
if FusedRMSNormGated is not None:
self.norm = FusedRMSNormGated(self.head_v_dim, eps=self.layer_norm_epsilon)
else:
self.norm = Qwen3_5MoeRMSNormGated(self.head_v_dim, eps=self.layer_norm_epsilon)
self.out_proj = nn.Linear(self.value_dim, self.hidden_size, bias=False)
# Input projections
self.in_proj_qkv = nn.Linear(self.hidden_size, self.key_dim * 2 + self.value_dim, bias=False)
self.in_proj_z = nn.Linear(self.hidden_size, self.value_dim, bias=False)
self.in_proj_b = nn.Linear(self.hidden_size, self.num_v_heads, bias=False)
self.in_proj_a = nn.Linear(self.hidden_size, self.num_v_heads, bias=False)
# Select best available kernel
self._causal_conv1d_fn = causal_conv1d_fn
self._chunk_gated_delta_rule = chunk_gated_delta_rule or torch_chunk_gated_delta_rule
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
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)
# Causal conv1d
if self._causal_conv1d_fn is not None:
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,
)
else:
mixed_qkv = F.silu(self.conv1d(mixed_qkv)[:, :, :seq_len])
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,
)
# Gated RMSNorm
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)
# ---------------------------------------------------------------------------
# Gated softmax attention (for full_attention layers)
# ---------------------------------------------------------------------------
@dataclass
class Qwen3_5MoeGatedAttentionConfig:
hidden_size: int
head_dim: int
num_attention_heads: int
num_key_value_heads: int
rms_norm_eps: float
attention_bias: bool = False
attention_dropout: float = 0.0
def _repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
if n_rep == 1:
return hidden_states
batch, num_kv_heads, slen, head_dim = hidden_states.shape
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_kv_heads, n_rep, slen, head_dim)
return hidden_states.reshape(batch, num_kv_heads * n_rep, slen, head_dim)
class Qwen3_5MoeGatedAttentionBase(nn.Module):
"""Base class for gated softmax attention (Q projects 2x: query + gate)."""
def __init__(self, config: Qwen3_5MoeGatedAttentionConfig):
super().__init__()
self.head_dim = config.head_dim
self.num_heads = config.num_attention_heads
self.num_key_value_heads = config.num_key_value_heads
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
self.scaling = self.head_dim**-0.5
self.attention_dropout = config.attention_dropout
# Q projects 2x: query + gate
self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim * 2, bias=config.attention_bias)
self.k_proj = nn.Linear(
config.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.v_proj = nn.Linear(
config.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)
# QK normalization with (1+weight) parameterization
self.q_norm = Qwen3_5MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.k_norm = Qwen3_5MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
class Qwen3_5MoeGatedSDPAAttention(Qwen3_5MoeGatedAttentionBase):
"""Gated softmax attention using PyTorch's scaled_dot_product_attention."""
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, None]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
# Split Q into query + gate
query_states, gate = torch.chunk(
self.q_proj(hidden_states).view(*input_shape, -1, self.head_dim * 2), 2, dim=-1
)
gate = gate.reshape(*input_shape, -1)
query_states = self.q_norm(query_states.view(hidden_shape)).transpose(1, 2)
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
key_states = _repeat_kv(key_states, self.num_key_value_groups)
value_states = _repeat_kv(value_states, self.num_key_value_groups)
attn_output = F.scaled_dot_product_attention(
query_states,
key_states,
value_states,
is_causal=True,
scale=self.scaling,
)
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate)
attn_output = self.o_proj(attn_output)
return attn_output, None
class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
"""Gated softmax attention using Flash Attention varlen functions."""
_funcs = {
2: flash_attn_varlen_func,
3: flash_attn_3_varlen_func,
4: flash_attn_4_varlen_func,
}
def __init__(self, config: Qwen3_5MoeGatedAttentionConfig, flash_attn_version: int = 4):
super().__init__(config)
self._flash_attn_version = flash_attn_version
self.func = self._funcs[flash_attn_version]
self._flash_attn_call = self.func
if self._flash_attn_version == 4:
self._flash_attn_call = torch._dynamo.disable(self.func)
def _compute_attention(self, q, k, v, cu_seqlens, max_seqlen):
args = [q, k, v, cu_seqlens, cu_seqlens]
if self._flash_attn_version != 4:
args.extend([max_seqlen, max_seqlen])
kwargs: dict = {"causal": True}
out = self._flash_attn_call(*args, **kwargs)
if isinstance(out, tuple):
out = out[0]
return out
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, None]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
# Split Q into query + gate
query_states, gate = torch.chunk(
self.q_proj(hidden_states).view(*input_shape, -1, self.head_dim * 2), 2, dim=-1
)
gate = gate.reshape(*input_shape, -1)
query_states = self.q_norm(query_states.view(hidden_shape))
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape))
value_states = self.v_proj(hidden_states).view(hidden_shape)
# Apply RoPE (need transpose for apply_rotary_pos_emb format)
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
attn_output = out.contiguous().view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate)
attn_output = self.o_proj(attn_output)
return attn_output, None
QWEN35MOE_ATTN_IMPL2CLASS = {
"sdpa": Qwen3_5MoeGatedSDPAAttention,
"flash_attention_2": functools.partial(Qwen3_5MoeGatedFlashAttention, flash_attn_version=2),
"flash_attention_3": functools.partial(Qwen3_5MoeGatedFlashAttention, flash_attn_version=3),
"fa4": functools.partial(Qwen3_5MoeGatedFlashAttention, flash_attn_version=4),
}
# ---------------------------------------------------------------------------
# Decoder layer
# ---------------------------------------------------------------------------
def _get_gated_attention(config: Qwen3_5MoeConfig) -> nn.Module:
attn_config = Qwen3_5MoeGatedAttentionConfig(
hidden_size=config.hidden_size,
head_dim=config.head_dim,
num_attention_heads=config.num_attention_heads,
num_key_value_heads=config.num_key_value_heads,
rms_norm_eps=config.rms_norm_eps,
attention_bias=config.attention_bias,
attention_dropout=config.attention_dropout,
)
attn_impl = config._attn_implementation
if attn_impl == "eager":
attn_impl = "sdpa"
if attn_impl not in QWEN35MOE_ATTN_IMPL2CLASS:
supported = list(QWEN35MOE_ATTN_IMPL2CLASS.keys())
raise ValueError(
f"Qwen3.5-MoE attention does not support '{config._attn_implementation}'. "
f"Supported implementations: {supported}."
)
return QWEN35MOE_ATTN_IMPL2CLASS[attn_impl](attn_config)
class Qwen3_5MoeDecoderLayer(GradientCheckpointingLayer):
def __init__(self, config: Qwen3_5MoeConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.layer_type = config.layer_types[layer_idx]
# Token mixer: either GatedDeltaNet or gated softmax attention
if self.layer_type == "linear_attention":
self.linear_attn = Qwen3_5MoeGatedDeltaNet(config)
elif self.layer_type == "full_attention":
self.self_attn = _get_gated_attention(config)
# MoE: routed experts via shared MoE class (no shared experts in MoE itself)
moe_args = MoEArgs(
num_experts=config.num_experts,
num_shared_experts=0,
score_func="softmax",
route_norm=True,
route_scale=1.0,
score_before_experts=False,
top_k=config.num_experts_per_tok,
use_grouped_mm=config.use_grouped_mm,
load_balance_coeff=config.load_balance_coeff,
)
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
# Separate gated shared expert
self.shared_expert = FeedForward(dim=config.hidden_size, hidden_dim=config.shared_expert_intermediate_size)
self.shared_expert_gate = nn.Linear(config.hidden_size, 1, bias=False)
# Layer norms with (1+weight) parameterization
self.input_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
routed_experts: Optional[torch.LongTensor] = None,
) -> torch.FloatTensor:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Token mixer
if self.layer_type == "linear_attention":
hidden_states = self.linear_attn(hidden_states)
elif self.layer_type == "full_attention":
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
position_embeddings=position_embeddings,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
hidden_states = residual + hidden_states
# MLP: routed experts + gated shared expert
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
# Routed experts
routed_output = self.mlp(hidden_states, routed_experts=routed_experts)
# Gated shared expert
bs, slen, dim = hidden_states.shape
hidden_flat = hidden_states.view(-1, dim)
shared_output = self.shared_expert(hidden_flat)
shared_output = F.sigmoid(self.shared_expert_gate(hidden_flat)) * shared_output
shared_output = shared_output.view(bs, slen, dim)
hidden_states = residual + routed_output + shared_output
return hidden_states
# ---------------------------------------------------------------------------
# Model classes
# ---------------------------------------------------------------------------
def _create_rotary_emb(config: Qwen3_5MoeConfig) -> RotaryEmbedding:
if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type", "default"))
else:
rope_type = "default"
rotary_config = RotaryEmbeddingConfig(
max_position_embeddings=config.max_position_embeddings,
rope_type=rope_type,
model_config=config,
)
return RotaryEmbedding(rotary_config)
class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
config_class = Qwen3_5MoeConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["Qwen3_5MoeDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = False
_supports_attention_backend = True
_can_compile_fullgraph = False
_can_record_outputs = {
"hidden_states": Qwen3_5MoeDecoderLayer,
}
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any(
"mlp.experts.1.up_proj" in name
or "mlp.experts.gate_up_proj" in name
or "mlp.shared_expert.gate_proj" in name
for name in state_dict.keys()
)
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any("mlp.experts.w1" in name for name in state_dict.keys())
@classmethod
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
convert_tt_to_hf_moe(state_dict)
return state_dict
@classmethod
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
convert_hf_to_tt_moe(state_dict)
return state_dict
@classmethod
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
convert_tt_layer_to_hf(state_dict, layer_idx)
return state_dict
@classmethod
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
convert_hf_layer_to_tt(state_dict, layer_idx)
return state_dict
class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
def __init__(self, config: Qwen3_5MoeConfig):
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(
[Qwen3_5MoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.norm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.rotary_emb = _create_rotary_emb(config)
self.gradient_checkpointing = False
self.post_init()
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
routed_experts: Optional[torch.LongTensor] = None,
) -> 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 self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
flat_position_ids = position_ids.view(-1)
seqlens = torch.cat(
[
flat_position_ids[0:1],
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
flat_position_ids[-1:] + 1,
]
)
max_seqlen = seqlens.max().item()
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
else:
max_seqlen = None
cu_seqlens = None
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for layer_idx, decoder_layer in enumerate(self.layers):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
routed_experts=routed_experts_layer,
)
hidden_states = self.norm(hidden_states)
return MoeModelOutputWithPast(last_hidden_state=hidden_states)
# ---------------------------------------------------------------------------
# VLM composite model body
# ---------------------------------------------------------------------------
def _build_text_config(composite_config: PretrainedConfig) -> Qwen3_5MoeConfig:
"""Build custom PrimeRL text config from HF's composite VLM config."""
text_dict = composite_config.text_config.to_dict()
text_config = Qwen3_5MoeConfig(**text_dict)
attn_impl = getattr(
composite_config.text_config,
"_attn_implementation",
getattr(composite_config, "_attn_implementation", None),
)
if attn_impl is not None:
text_config._attn_implementation = attn_impl
return text_config
class Qwen3_5MoeVLMModel(nn.Module):
"""Composite VLM body: HF vision encoder + custom PrimeRL text model."""
def __init__(self, config: PretrainedConfig):
super().__init__()
self.config = config
self.visual = Qwen3_5MoeVisionModel._from_config(config.vision_config)
self.language_model = Qwen3_5MoeModel(_build_text_config(config))
def get_input_embeddings(self):
return self.language_model.embed_tokens
def set_input_embeddings(self, value):
self.language_model.embed_tokens = value
def forward(
self,
input_ids: torch.LongTensor | None = None,
position_ids: torch.LongTensor | None = None,
inputs_embeds: torch.FloatTensor | None = None,
pixel_values: torch.Tensor | None = None,
image_grid_thw: torch.LongTensor | None = None,
routed_experts: torch.LongTensor | None = None,
**kwargs,
) -> MoeModelOutputWithPast:
if inputs_embeds is None:
inputs_embeds = self.language_model.embed_tokens(input_ids)
if pixel_values is not None:
pixel_values = pixel_values.type(self.visual.dtype)
vision_output = self.visual(pixel_values, grid_thw=image_grid_thw, return_dict=True)
image_embeds = vision_output.pooler_output.to(inputs_embeds.device, inputs_embeds.dtype)
image_mask = input_ids == self.config.image_token_id
image_mask = image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
return self.language_model(
inputs_embeds=inputs_embeds,
position_ids=position_ids,
routed_experts=routed_experts,
)
# ---------------------------------------------------------------------------
# Unified CausalLM / VLM class
# ---------------------------------------------------------------------------
def _has_vlm_keys(state_dict: dict[str, Tensor]) -> bool:
return any(k.startswith("model.language_model.") for k in state_dict)
def _remap_lm_keys(state_dict: dict[str, Tensor], to_flat: bool = True) -> None:
"""Remap language model keys between VLM and flat format for weight conversion.
to_flat=True: model.language_model.* -> model.*
to_flat=False: model.* -> model.language_model.*
Vision keys (model.visual.*) are never touched.
"""
src = "model.language_model." if to_flat else "model."
dst = "model." if to_flat else "model.language_model."
for k in [k for k in list(state_dict.keys()) if k.startswith(src) and not k.startswith("model.visual.")]:
state_dict[dst + k[len(src) :]] = state_dict.pop(k)
class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
"""Unified Qwen3.5 MoE model for both text-only and VLM configs.
When config has a vision_config, creates a composite model with HF's frozen
vision encoder + custom text model. Otherwise creates a text-only model.
"""
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_checkpoint_conversion_mapping = {}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config, **kwargs):
super().__init__(config, **kwargs)
self._is_vlm = hasattr(config, "vision_config")
if self._is_vlm:
self.model = Qwen3_5MoeVLMModel(config)
text_config = config.text_config
self._tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
else:
self.model = Qwen3_5MoeModel(config)
text_config = config
self.vocab_size = text_config.vocab_size
self.lm_head = nn.Linear(text_config.hidden_size, text_config.vocab_size, bias=False)
self.post_init()
def get_input_embeddings(self):
if self._is_vlm:
return self.model.get_input_embeddings()
return self.model.embed_tokens
def set_input_embeddings(self, value):
if self._is_vlm:
self.model.set_input_embeddings(value)
else:
self.model.embed_tokens = value
def set_decoder(self, decoder):
self.model = decoder
def get_decoder(self):
return self.model
# ------------------------------------------------------------------
# State dict detection & conversion (handles both text-only and VLM)
# ------------------------------------------------------------------
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any(
"mlp.experts.gate_up_proj" in name
or "mlp.experts.1.up_proj" in name
or "mlp.shared_expert.gate_proj" in name
for name in state_dict
)
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any("mlp.experts.w1" in name for name in state_dict)
@classmethod
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
vlm = _has_vlm_keys(state_dict)
if vlm:
_remap_lm_keys(state_dict, to_flat=True)
convert_tt_to_hf_moe(state_dict)
if vlm:
_remap_lm_keys(state_dict, to_flat=False)
return state_dict
@classmethod
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
vlm = _has_vlm_keys(state_dict)
if vlm:
_remap_lm_keys(state_dict, to_flat=True)
convert_hf_to_tt_moe(state_dict)
if vlm:
_remap_lm_keys(state_dict, to_flat=False)
return state_dict
@classmethod
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
vlm = _has_vlm_keys(state_dict)
if vlm:
_remap_lm_keys(state_dict, to_flat=True)
convert_tt_layer_to_hf(state_dict, layer_idx)
if vlm:
_remap_lm_keys(state_dict, to_flat=False)
return state_dict
@classmethod
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
vlm = _has_vlm_keys(state_dict)
if vlm:
_remap_lm_keys(state_dict, to_flat=True)
convert_hf_layer_to_tt(state_dict, layer_idx)
if vlm:
_remap_lm_keys(state_dict, to_flat=False)
return state_dict
# ------------------------------------------------------------------
# Forward
# ------------------------------------------------------------------
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
temperature: Union[torch.Tensor, None] = None,
routed_experts: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.Tensor] = None,
image_grid_thw: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
assert use_cache is None, "use_cache is not supported for custom qwen3_5_moe for now"
assert past_key_values is None, "past_key_values is not supported for custom qwen3_5_moe for now"
if position_ids is None:
if inputs_embeds is not None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
elif input_ids is not None:
position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0)
if self._is_vlm:
outputs: MoeModelOutputWithPast = self.model(
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
routed_experts=routed_experts,
)
else:
outputs = self.model(
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
routed_experts=routed_experts,
)
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,
)
# ------------------------------------------------------------------
# Buffer init after meta-device loading
# ------------------------------------------------------------------
def init_buffers_post_meta(self):
if self._is_vlm:
lm_rope = self.model.language_model.rotary_emb
else:
lm_rope = self.model.rotary_emb
if hasattr(lm_rope, "rope_init_fn"):
inv_freq, lm_rope.attention_scaling = lm_rope.rope_init_fn(lm_rope.config, lm_rope.inv_freq.device)
lm_rope.inv_freq.copy_(inv_freq)
if self._is_vlm:
vis_rope = self.model.visual.rotary_pos_emb
if hasattr(vis_rope, "inv_freq"):
dim = vis_rope.inv_freq.shape[0]
inv_freq = 1.0 / (
10000.0
** (torch.arange(0, dim * 2, 2, dtype=torch.float32, device=vis_rope.inv_freq.device) / (dim * 2))
)
vis_rope.inv_freq.copy_(inv_freq)
__all__ = [
"Qwen3_5MoeForCausalLM",
"Qwen3_5MoeModel",
"Qwen3_5MoePreTrainedModel",
]
@@ -333,7 +333,7 @@ def load_balancing_loss_func(
@auto_docstring
class Qwen3MoeForCausalLM(Qwen3MoePreTrainedModel, GenerationMixin):
_tied_weights_keys = ["lm_head.weight"]
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+62 -28
View File
@@ -1,7 +1,7 @@
import pickle
import time
from pathlib import Path
from typing import Generator, cast
from typing import Callable, Generator, cast
import torch
import torch.nn as nn
@@ -19,6 +19,7 @@ from prime_rl.trainer.weights import get_max_layer_num
from prime_rl.utils.logger import get_logger
from prime_rl.utils.pathing import sync_wait_for_path
from prime_rl.utils.utils import get_broadcast_dir, get_step_path
from prime_rl.utils.vlm import get_layer_prefix
NCCL_READY_MARKER = "NCCL_READY"
@@ -67,22 +68,46 @@ def broadcast_state_dict(state_dict: dict[str, Tensor], communicator: PyNcclComm
def filter_state_dict_by_layers(
state_dict: dict[str, torch.Tensor], num_layers: int
state_dict: dict[str, torch.Tensor], num_layers: int, layer_prefix: str
) -> Generator[tuple[int, dict[str, torch.Tensor]], None, None]:
"""Yield a generator of state dicts for each layer as well as the remaining weights."""
yield 0, {key: value for key, value in state_dict.items() if "model.layers" not in key}
"""Yield non-layer weights first, then each layer's weights.
for i in range(1, num_layers + 1): # +1 because layer indices start from 1
Yields (layer_idx, layer_state_dict) where layer_idx is -1 for the non-layer
dict and the actual layer index (0, 1, ...) for layer dicts.
"""
yield -1, {key: value for key, value in state_dict.items() if not key.startswith(layer_prefix)}
for i in range(num_layers):
yield (
i,
{
key: value
for key, value in state_dict.items()
if key.startswith(f"model.layers.{i}.") or key == f"model.layers.{i}"
},
{key: value for key, value in state_dict.items() if key.startswith(f"{layer_prefix}{i}.")},
)
def preprocess_layer_checkpoint(
model: nn.Module,
layer_state_dict: dict[str, Tensor],
layer_idx: int,
) -> dict[str, Tensor]:
if isinstance(model, PreTrainedModelPrimeRL) and model.is_prime_state_dict(layer_state_dict):
model.convert_layer_to_hf(layer_state_dict, layer_idx)
return layer_state_dict
from transformers.core_model_loading import revert_weight_conversion
return revert_weight_conversion(model, layer_state_dict)
def preprocess_layer_quantized(
model: nn.Module,
layer_state_dict: dict[str, Tensor],
layer_idx: int,
) -> dict[str, Tensor]:
if layer_idx < 0:
return layer_state_dict
return model.convert_layer_to_vllm_kernel(layer_state_dict, layer_idx, quantize_fp8=True)
class NCCLWeightBroadcastSender:
def __init__(
self,
@@ -93,10 +118,12 @@ class NCCLWeightBroadcastSender:
device: int | str | torch.device,
timeout: int,
dtype: torch.dtype = torch.bfloat16,
quantize_in_weight_transfer: bool = False,
):
self.logger = get_logger()
self.world = get_world()
self.dtype = dtype
self.quantize_in_weight_transfer = quantize_in_weight_transfer
if self.world.is_master:
# Trainer is on rank 0 in process group with all inference GPUs
@@ -112,31 +139,31 @@ class NCCLWeightBroadcastSender:
def broadcast_weights(self, model: nn.Module, step: int) -> None:
"""Broadcast the state dict of a model into the inference pool using NCCL."""
state_dict = model.state_dict()
num_layers = get_max_layer_num(state_dict)
layer_prefix = get_layer_prefix(model.config)
num_layers = get_max_layer_num(state_dict, layer_prefix)
num_state_dict_to_send = num_layers + 1 # we send all layer plus the remaining weights
if self.world.is_master:
broadcast_integer(num_state_dict_to_send, self.communicator)
self.logger.debug(f"Broadcasting {num_state_dict_to_send} layer state dicts")
preprocess_fn: Callable[[nn.Module, dict[str, Tensor], int], dict[str, Tensor]]
if self.quantize_in_weight_transfer:
preprocess_fn = preprocess_layer_quantized
else:
preprocess_fn = preprocess_layer_checkpoint
for layer_id, state_dict in filter_state_dict_by_layers(state_dict, num_layers):
for key, value in list(state_dict.items()):
if isinstance(value, DTensor):
value = cast(DTensor, value.to(self.dtype)).full_tensor()
state_dict[key] = value
# Convert to HF hub format for this layer if needed
if isinstance(model, PreTrainedModelPrimeRL) and model.is_prime_state_dict(state_dict):
model.convert_layer_to_hf(state_dict, layer_id)
else:
# For regular transformers models, revert internal format to original HF hub format
from transformers.core_model_loading import revert_weight_conversion
state_dict = revert_weight_conversion(model, state_dict)
for layer_id, layer_state_dict in filter_state_dict_by_layers(state_dict, num_layers, layer_prefix):
layer_state_dict = self._resolve_dtensors(layer_state_dict)
layer_state_dict = preprocess_fn(model, layer_state_dict, layer_id)
if self.world.is_master:
broadcast_state_dict(state_dict, self.communicator)
broadcast_state_dict(layer_state_dict, self.communicator)
def _resolve_dtensors(self, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
for key, value in list(state_dict.items()):
if isinstance(value, DTensor):
state_dict[key] = cast(DTensor, value.to(self.dtype)).full_tensor()
return state_dict
class NCCLWeightBroadcast(WeightBroadcast):
@@ -154,7 +181,14 @@ class NCCLWeightBroadcast(WeightBroadcast):
self.world = get_world()
self.multi_run_manager = get_multi_run_manager()
self.nccl_broadcast_sender = NCCLWeightBroadcastSender(
config.host, config.port, 0, config.inference_world_size + 1, device, config.timeout, dtype
config.host,
config.port,
0,
config.inference_world_size + 1,
device,
config.timeout,
dtype,
quantize_in_weight_transfer=config.quantize_in_weight_transfer,
)
@torch.no_grad()
+16 -1
View File
@@ -6,7 +6,7 @@ from beartype import beartype as typechecker
from jaxtyping import Bool, Float, Int, jaxtyped
from torch import Tensor
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, LossConfig
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, LossConfig, SFTLossConfig
from prime_rl.utils.utils import import_object
@@ -163,6 +163,18 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
return LossOutputs(loss=loss, metrics=metrics)
def sft_loss_fn(inputs: LossInputs) -> LossOutputs:
"""SFT-style masked negative log-likelihood over trainable tokens."""
trainer_logprobs = inputs.trainer_logprobs
loss_mask = inputs.loss_mask
loss = -(trainer_logprobs[loss_mask]).sum()
metrics = {
"nll": _safe_mean(-trainer_logprobs, loss_mask),
}
return LossOutputs(loss=loss, metrics=metrics)
def setup_loss_fn(loss_config: LossConfig) -> LossFn:
"""Setup the loss function based on config."""
if isinstance(loss_config, CustomLossConfig):
@@ -174,6 +186,9 @@ def setup_loss_fn(loss_config: LossConfig) -> LossFn:
return loss_fn
if isinstance(loss_config, SFTLossConfig):
return sft_loss_fn
def loss_fn(inputs: LossInputs) -> LossOutputs:
return default_loss_fn(inputs, loss_config)
+43 -32
View File
@@ -16,7 +16,7 @@ from prime_rl.trainer.ckpt import setup_ckpt_managers
from prime_rl.trainer.multi_ckpt import setup_multi_checkpoint_manager
from prime_rl.trainer.optim import setup_optimizer, setup_multi_optimizer
from prime_rl.trainer.scheduler import setup_scheduler, setup_multi_scheduler
from prime_rl.configs.trainer import DefaultLossConfig, TrainerConfig
from prime_rl.configs.trainer import TrainerConfig
from prime_rl.trainer.rl.data import DataLoader, FakeDataLoader
from prime_rl.utils.cp import (
setup_cp_params,
@@ -44,6 +44,7 @@ from prime_rl.trainer.utils import (
MemoryProfiler,
Tensors,
export_benchmark_json,
get_zero_gradient_ratio,
get_ckpt_disk_metrics,
setup_torch_distributed,
print_benchmark,
@@ -166,9 +167,13 @@ def train(config: TrainerConfig):
logger.info(f"Using `{config.scheduler.type}` scheduler ({config.scheduler})")
# Set up weight broadcast
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
weight_broadcast = setup_weight_broadcast(config.output_dir, config.weight_broadcast, config.model.lora)
# Set up weight broadcast (skip when using fake data since there's no inference server)
if config.data.fake:
weight_broadcast = None
logger.info("Skipping weight broadcast setup (fake data mode)")
else:
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
weight_broadcast = setup_weight_broadcast(config.output_dir, config.weight_broadcast, config.model.lora)
if parallel_dims.cp_enabled:
substitute_hf_flash_attn(parallel_dims.world_mesh["cp"].get_group(), heads_k_stride=1)
@@ -217,21 +222,24 @@ def train(config: TrainerConfig):
# Broadcast weights at every step, (except step 0, because no need to broadcast the base model)
# Also, with NCCL broadcast, we do not broadcast weights the last async level step as the orchestrator is already finished and will not initialize the receive on the inference; for filesystem broadcast, we do "broadcast" until the final step to allow to resume from the broadcast directory
last_async_level_steps = config.max_steps and progress.step >= config.max_steps - config.max_async_level
if progress.step > 0 and (not last_async_level_steps or config.weight_broadcast.type == "filesystem"):
broadcast_weights_start_time = time.perf_counter()
weight_broadcast.broadcast_weights(model, step=progress.step)
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
# Clean up old broadcast directories (unless at ckpt interval if using filesystem weight broadcast)
ckpt_interval = config.ckpt and config.ckpt.interval
interval_to_keep = ckpt_interval if config.weight_broadcast.type == "filesystem" else None
if config.weight_broadcast.type == "filesystem":
weight_broadcast.maybe_clean(config.max_async_level, interval_to_keep)
else:
if weight_broadcast is None:
broadcast_weights_time = 0
# Usually the broadcast will set this. If broadcast is skipped, we need to reset this here.
for idx in multi_run_manager.used_idxs:
multi_run_manager.ready_to_update[idx] = False
else:
last_async_level_steps = config.max_steps and progress.step >= config.max_steps - config.max_async_level
if progress.step > 0 and (not last_async_level_steps or config.weight_broadcast.type == "filesystem"):
broadcast_weights_start_time = time.perf_counter()
weight_broadcast.broadcast_weights(model, step=progress.step)
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
# Clean up old broadcast directories (unless at ckpt interval if using filesystem weight broadcast)
ckpt_interval = config.ckpt and config.ckpt.interval
interval_to_keep = ckpt_interval if config.weight_broadcast.type == "filesystem" else None
if config.weight_broadcast.type == "filesystem":
weight_broadcast.maybe_clean(config.max_async_level, interval_to_keep)
else:
broadcast_weights_time = 0
# Usually the broadcast will set this. If broadcast is skipped, we need to reset this here.
for idx in multi_run_manager.used_idxs:
multi_run_manager.ready_to_update[idx] = False
if (
ckpt_manager is not None
@@ -239,21 +247,23 @@ def train(config: TrainerConfig):
and not (is_first_step or is_last_step)
and progress.step % config.ckpt.interval == 0
):
# Single-run: Save full checkpoint
logger.info(f"Saving checkpoint at step {progress.step}")
save_ckpt_start_time = time.perf_counter()
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
save_ckpt_time = time.perf_counter() - save_ckpt_start_time
save_ckpt_time = 0
if not config.ckpt.weights_only:
# Single-run: Save full checkpoint
logger.info(f"Saving checkpoint at step {progress.step}")
save_ckpt_start_time = time.perf_counter()
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
# Maybe clean up old checkpoints
ckpt_manager.maybe_clean()
# Save weight checkpoint
if weight_ckpt_manager is not None:
logger.info(f"Saving weight checkpoint at step {progress.step}")
save_ckpt_start_time = time.perf_counter()
weight_ckpt_manager.save(progress.step, model, tokenizer)
# Maybe clean up old weight checkpoint
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
weight_ckpt_manager.maybe_clean()
elif config.max_concurrent_runs > 1:
# Multi-run: Save per-run checkpoints (each run has its own interval from orchestrator config)
@@ -294,10 +304,7 @@ def train(config: TrainerConfig):
seq_len = micro_batches[0]["input_ids"].shape[1]
# Normalize by the local number of unmasked tokens in the batch (per-batch length normalization)
if isinstance(config.loss, DefaultLossConfig):
loss_scale = sum(micro_batch["loss_mask"].sum().item() for micro_batch in micro_batches)
else:
loss_scale = batch_size
loss_scale = sum(micro_batch["loss_mask"].sum().item() for micro_batch in micro_batches)
loss_scale = max(loss_scale, 1)
logger.debug(f"Starting forward and backward pass ({batch_size=})")
@@ -460,6 +467,7 @@ def train(config: TrainerConfig):
)
if grad_norm.device.type == "cpu":
grad_norm = grad_norm.to(torch.device("cuda"))
zero_grad_ratio = get_zero_gradient_ratio(model.parameters(), parallel_dims.dp_replicate)
# Update the model parameters
optimizer.step()
@@ -516,6 +524,7 @@ def train(config: TrainerConfig):
optim_metrics = {
"optim/lr": current_lr,
"optim/grad_norm": grad_norm.item(),
"optim/zero_grad_ratio": zero_grad_ratio,
"step": progress.step,
}
monitor.log(optim_metrics, step=progress.step)
@@ -559,6 +568,7 @@ def train(config: TrainerConfig):
mfu=mfu,
entropy=tensor_stats.get("entropy/mean", 0.0),
mismatch_kl=tensor_stats.get("mismatch_kl/mean", 0.0),
zero_grad_ratio=zero_grad_ratio,
)
# Update run/LoRA metrics
multi_run_manager = get_multi_run_manager()
@@ -603,8 +613,9 @@ def train(config: TrainerConfig):
# Write final checkpoint (only for single-run mode; multi-run checkpoints are managed by MultiCheckpointManager)
if config.max_concurrent_runs == 1 and ckpt_manager is not None:
logger.info("Writing final checkpoint")
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
if not (config.ckpt and config.ckpt.weights_only):
logger.info("Writing final checkpoint")
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
ckpt_manager.maybe_clean()
if config.max_concurrent_runs == 1 and weight_ckpt_manager is not None:
+65 -121
View File
@@ -12,8 +12,9 @@ from torch.utils.data import IterableDataset, get_worker_info
from torchdata.stateful_dataloader import StatefulDataLoader
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.configs.sft import DataConfig, LossMaskConfig
from prime_rl.configs.sft import DataConfig, LossMaskConfig, SFTDataConfig
from prime_rl.trainer.world import get_world
from prime_rl.utils.chat_template import build_incremental_token_mask, deserialize_tool_calls, strip_message_content
from prime_rl.utils.logger import get_logger
STACKING_DATASET_BUCKET_TIMEOUT = 10
@@ -160,41 +161,6 @@ class SFTDataset(StatefulIterableDataset):
if "prompt" not in example or "completion" not in example:
raise ValueError("All examples in the dataset must have a 'prompt' and 'completion' column for SFT")
def deserialize_tool_calls(messages: list[dict]) -> list[dict]:
"""
Deserialize tool calls in messages, if any are present. Iterates
over all messages in a message list and tries to find
"tool_calls" key. If found, assumes it is a OAI format and has
key "function" with "arguments" key which is stringified. It
will then deserialize the argument so that chat tmeplates like
Qwen3's can be used.
"""
def deserialize_tool_call(tool_call: dict) -> dict:
return {
**tool_call,
"function": {
**tool_call["function"],
"arguments": json.loads(tool_call["function"]["arguments"]),
},
}
return [
{
**message,
"tool_calls": [deserialize_tool_call(tool_call) for tool_call in message.get("tool_calls") or []],
}
for message in messages
]
def strip_content(messages: list[dict]) -> list[dict]:
def _strip_content(message: dict) -> dict:
if isinstance(message.get("content"), str):
return {**message, "content": message["content"].strip()}
return message
return [_strip_content(message) for message in messages]
# Deserialize tool call arguments from message list, if present - assumes OAI format
# Reference: https://platform.openai.com/docs/guides/function-calling#handling-function-calls
prompt = deserialize_tool_calls(example["prompt"])
@@ -202,71 +168,36 @@ class SFTDataset(StatefulIterableDataset):
# Strip content from all messages so that incremental tokenization works
# NOTE: This has the side effect that we do never train on leading or trailing whitespace
prompt = strip_content(prompt)
completion = strip_content(completion)
prompt = strip_message_content(prompt)
completion = strip_message_content(completion)
# Parse available tools, if present - assumes OAI format
# Reference: https://platform.openai.com/docs/guides/function-calling#function-tool-example
tools = json.loads(example.get("tools") or "[]")
def should_mask(message: dict, loss_mask_config: LossMaskConfig) -> bool:
def should_mask(message: dict) -> bool:
assert "role" in message, "Message must have a role"
match message["role"]:
case "user":
return True if loss_mask_config.user else False
return True if self.loss_mask_config.user else False
case "assistant":
return True if loss_mask_config.assistant else False
return True if self.loss_mask_config.assistant else False
case "system":
return True if loss_mask_config.system else False
return True if self.loss_mask_config.system else False
case "tool":
return True if loss_mask_config.tool else False
return True if self.loss_mask_config.tool else False
case _:
raise ValueError(f"Invalid message role: {message['role']}")
def build_loss_mask(prompt, completion, tokenizer, loss_mask_config: LossMaskConfig) -> list[bool]:
messages = prompt + completion
loss_mask: list[bool] = []
prev_ids, prev_len = [], 0
for i, message in enumerate(messages):
assert "role" in message, "Message must have a role"
# Support parallel tool call outputs (treat them as one message for loss mask)
if message["role"] == "tool" and i + 1 < len(messages) and messages[i + 1]["role"] == "tool":
continue
cur_ids = tokenizer.apply_chat_template(
messages[: i + 1],
tools=tools,
# This is to mask out the generation prompt after user and tool messages
# It leads to us not training on <|im_start|>assistant
add_generation_prompt=True
if (
message["role"] in ["user", "tool"]
and i + 1 < len(messages)
and messages[i + 1]["role"] == "assistant"
)
else False,
**{**example.get("chat_template_kwargs", {}), "return_dict": False},
)
assert prev_ids == cur_ids[:prev_len], (
f"Got mismatch in incremental tokenization with chat template at message {i}. Previous ids: {prev_ids} != {cur_ids[:prev_len]=}.\nDecoded prev_ids:\n{tokenizer.decode(prev_ids)}\nDecoded cur_ids:\n{tokenizer.decode(cur_ids[:prev_len])}"
)
loss_mask.extend([should_mask(message, loss_mask_config)] * (len(cur_ids) - prev_len))
prev_ids, prev_len = cur_ids, len(cur_ids)
return loss_mask
# Build input_ids
input_ids = cast(
list[int],
self.tokenizer.apply_chat_template(
prompt + completion,
tools=tools,
**{**example.get("chat_template_kwargs", {}), "return_dict": False},
),
input_ids, loss_mask = build_incremental_token_mask(
self.tokenizer,
prompt + completion,
role_to_mask=should_mask,
tools=tools,
chat_template_kwargs=example.get("chat_template_kwargs", {}),
collapse_consecutive_tool_messages=True,
)
# Build loss_mask
loss_mask = build_loss_mask(prompt, completion, self.tokenizer, self.loss_mask_config)
# If EOS token is not found, manually append it
if not self.tokenizer.eos_token_id in input_ids:
self.logger.warning(
@@ -541,54 +472,67 @@ def setup_and_interleave_datasets(
return dataset
def setup_dataset(tokenizer: PreTrainedTokenizer, config: DataConfig, non_dp_size: int = 1) -> StatefulIterableDataset:
def load_sft_dataset(config: SFTDataConfig) -> Dataset:
"""Load and interleave the raw HF dataset. This is the expensive I/O step."""
logger = get_logger()
if config.subsets is None and config.splits is None:
return setup_and_interleave_datasets(
dataset_name=config.name,
subsets_and_splits=[(None, "train")],
probabilities=config.probabilities,
stopping_strategy=config.stopping_strategy,
)
elif config.subsets is not None and config.splits is None:
logger.debug(f"Loading datasets for subsets {config.subsets} with default split 'train'")
return setup_and_interleave_datasets(
dataset_name=config.name,
subsets_and_splits=[(subset, "train") for subset in config.subsets],
probabilities=config.probabilities,
stopping_strategy=config.stopping_strategy,
)
elif config.subsets is None and config.splits is not None:
logger.debug(f"Loading datasets for splits {config.splits} with default subset 'None'")
return setup_and_interleave_datasets(
dataset_name=config.name,
subsets_and_splits=[(None, split) for split in config.splits],
probabilities=config.probabilities,
stopping_strategy=config.stopping_strategy,
)
else:
assert config.subsets is not None and config.splits is not None
logger.debug(f"Loading datasets for subsets {config.subsets} with splits {config.splits}")
return setup_and_interleave_datasets(
dataset_name=config.name,
subsets_and_splits=list(zip(config.subsets, config.splits)),
probabilities=config.probabilities,
stopping_strategy=config.stopping_strategy,
)
def setup_dataset(
tokenizer: PreTrainedTokenizer,
config: DataConfig,
non_dp_size: int = 1,
*,
max_epochs: int | None = None,
raw_dataset: Dataset | None = None,
) -> StatefulIterableDataset:
if config.type == "fake":
# Shouldnt matter to handle non_dp_size if dataset is random
return FakeDataset(
vocab_size=tokenizer.vocab_size, seq_len=config.seq_len, length=config.length, input_ids=config.input_ids
)
elif config.type == "sft":
logger = get_logger()
if config.subsets is None and config.splits is None:
dataset = setup_and_interleave_datasets(
dataset_name=config.name,
subsets_and_splits=[(None, "train")],
probabilities=config.probabilities,
stopping_strategy=config.stopping_strategy,
)
elif config.subsets is not None and config.splits is None:
logger.debug(f"Loading datasets for subsets {config.subsets} with default split 'train'")
dataset = setup_and_interleave_datasets(
dataset_name=config.name,
subsets_and_splits=[(subset, "train") for subset in config.subsets],
probabilities=config.probabilities,
stopping_strategy=config.stopping_strategy,
)
elif config.subsets is None and config.splits is not None:
logger.debug(f"Loading datasets for splits {config.splits} with default subset 'None'")
dataset = setup_and_interleave_datasets(
dataset_name=config.name,
subsets_and_splits=[(None, split) for split in config.splits],
probabilities=config.probabilities,
stopping_strategy=config.stopping_strategy,
)
else:
assert config.subsets is not None and config.splits is not None
logger.debug(f"Loading datasets for subsets {config.subsets} with splits {config.splits}")
dataset = setup_and_interleave_datasets(
dataset_name=config.name,
subsets_and_splits=list(zip(config.subsets, config.splits)),
probabilities=config.probabilities,
stopping_strategy=config.stopping_strategy,
)
if raw_dataset is None:
raw_dataset = load_sft_dataset(config)
return SFTDataset(
dataset,
raw_dataset,
tokenizer,
shuffle=config.shuffle,
seed=config.seed,
seq_len=config.seq_len,
loss_mask_config=config.loss_mask,
non_dp_size=non_dp_size,
max_epochs=max_epochs,
)
else:
raise ValueError(f"Invalid dataset type: {config.type}")
+169 -81
View File
@@ -16,7 +16,8 @@ from prime_rl.trainer.ckpt import setup_ckpt_managers
from prime_rl.utils.pathing import resolve_latest_ckpt_step
from prime_rl.configs.sft import SFTConfig
from prime_rl.utils.cp import setup_cp_params, shard_for_cp
from prime_rl.trainer.runs import Progress
from prime_rl.trainer.runs import Progress, get_multi_run_manager, setup_multi_run_manager
from prime_rl.trainer.models.layers.lora import set_lora_num_tokens
from prime_rl.utils.logger import setup_logger
from prime_rl.trainer.optim import setup_optimizer
from prime_rl.trainer.scheduler import setup_scheduler
@@ -29,10 +30,11 @@ from prime_rl.trainer.model import (
)
from prime_rl.trainer.parallel_dims import get_parallel_dims
from prime_rl.trainer.perf import get_perf_counter
from prime_rl.trainer.sft.data import setup_dataloader, setup_dataset
from prime_rl.trainer.sft.data import load_sft_dataset, setup_dataloader, setup_dataset
from prime_rl.trainer.utils import (
MemoryProfiler,
export_benchmark_json,
get_zero_gradient_ratio,
get_ckpt_disk_metrics,
print_sample,
setup_torch_distributed,
@@ -45,6 +47,7 @@ from prime_rl.utils.config import cli
from prime_rl.utils.utils import clean_exit, to_col_format
import torch.distributed as dist
from liger_kernel.transformers.cross_entropy import LigerCrossEntropyLoss
from prime_rl.trainer.models.layers.lm_head import FusedCrossEntropyOutputLinear
from torchtitan.distributed.utils import clip_grad_norm_
@@ -80,6 +83,9 @@ def train(config: SFTConfig):
)
torch.set_float32_matmul_precision("high")
if config.model.lora is not None:
setup_multi_run_manager(config.output_dir, 1, torch.device("cuda", world.local_rank), config.model.lora)
# Initialize parallel dimensions
parallel_dims = get_parallel_dims(config.model, config.data.seq_len)
@@ -114,7 +120,14 @@ def train(config: SFTConfig):
# Initialize the model and tokenizer
logger.info(f"Initializing model ({config.model})")
loading_from_ckpt_later = config.ckpt and checkpoint_step is not None
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later)
model = setup_model(
config.model, parallel_dims, loading_from_ckpt_later, fused_cross_entropy=config.loss_impl == "liger_fused"
)
if config.model.lora is not None:
multi_run_manager = get_multi_run_manager()
multi_run_manager.reset_run_parameters(0)
multi_run_manager.scaling_factors[0] = config.model.lora.alpha / config.model.lora.rank
logger.info(f"Initializing tokenizer ({config.tokenizer})")
tokenizer = setup_tokenizer(config.tokenizer)
@@ -141,6 +154,11 @@ def train(config: SFTConfig):
dataloader = setup_dataloader(dataset, config.data)
dataiter = iter(dataloader)
val_raw_dataset = None
if config.val is not None:
logger.info(f"Loading validation dataset ({config.val.data.name})")
val_raw_dataset = load_sft_dataset(config.val.data)
# Optionally, resume training from a checkpoint
progress = Progress()
@@ -164,24 +182,101 @@ def train(config: SFTConfig):
cp_enabled = parallel_dims.cp_enabled
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank() if cp_enabled else 0
cp_group = parallel_dims.world_mesh["cp"].get_group() if cp_enabled else None
dp_cp_group = parallel_dims.get_mesh("dp_cp").get_group()
cp_size = parallel_dims.cp
ce_loss = None
match config.loss_impl:
case "liger":
ce_loss = LigerCrossEntropyLoss(reduction="none")
case "torch":
ce_loss = CrossEntropyLoss(reduction="none")
case "liger_fused":
pass # loss is computed inside the fused lm_head
case _:
raise ValueError(f"Invalid loss implementation: {config.loss_impl}")
def compute_loss(micro_batch: dict) -> tuple[torch.Tensor, torch.Tensor]:
"""Forward pass returning (loss_sum, token_count) over unmasked tokens."""
input_ids = micro_batch["input_ids"].to("cuda")
position_ids = micro_batch["position_ids"].to("cuda")
target_ids = micro_batch["target_ids"].to("cuda")
loss_mask = micro_batch["loss_mask"].to("cuda")
if cp_enabled:
input_ids, position_ids = setup_cp_params(input_ids, position_ids, cp_rank, cp_size, cp_group)
target_ids = shard_for_cp(target_ids, cp_rank=cp_rank, cp_world_size=cp_size)
loss_mask = shard_for_cp(loss_mask, cp_rank=cp_rank, cp_world_size=cp_size)
if config.model.lora is not None:
set_lora_num_tokens(torch.full((1,), input_ids.numel(), dtype=torch.int32, device="cuda"))
token_count = loss_mask.sum(dtype=torch.int64)
with maybe_activation_offloading(config.model.ac_offloading):
if config.loss_impl == "liger_fused":
masked_target_ids = target_ids.clone()
masked_target_ids[~loss_mask] = FusedCrossEntropyOutputLinear.IGNORE_INDEX
out = forward(model, input_ids, position_ids, labels=masked_target_ids)
loss_sum = out["loss"] * token_count
else:
out = forward(model, input_ids, position_ids)
logits = out["logits"]
B, L, V = logits.shape
token_loss = ce_loss(logits.view(-1, V), target_ids.view(-1)).view(B, L)
loss_sum = token_loss[loss_mask].sum()
del logits
del out
return loss_sum, token_count
maybe_record_function = nullcontext
def run_eval_loop(data_iter):
"""Validation forward loop. Returns token-weighted global mean loss."""
total_loss_sum = torch.tensor(0.0, device="cuda")
total_token_count = torch.tensor(0, dtype=torch.int64, device="cuda")
nan_count = torch.tensor(0, device="cuda")
with torch.no_grad():
for micro_batch in data_iter:
loss_sum, token_count = compute_loss(micro_batch)
if not torch.isnan(loss_sum.detach()):
total_loss_sum += loss_sum.detach()
total_token_count += token_count
else:
nan_count += 1
dist.all_reduce(total_loss_sum, op=dist.ReduceOp.SUM, group=dp_cp_group)
dist.all_reduce(total_token_count, op=dist.ReduceOp.SUM, group=dp_cp_group)
dist.all_reduce(nan_count, op=dist.ReduceOp.SUM)
mean_loss = (total_loss_sum / total_token_count).item() if total_token_count.item() > 0 else float("nan")
return mean_loss, nan_count.item()
def run_validation(step: int) -> None:
val_dataset = setup_dataset(
tokenizer, config.val.data, config.model.cp * config.model.tp, max_epochs=1, raw_dataset=val_raw_dataset
)
val_dataloader = setup_dataloader(val_dataset, config.val.data)
# No train/eval switch: no dropout in these models, and toggling would trigger torch.compile recompilation
mean_loss, nan_count = run_eval_loop(val_dataloader)
if nan_count > 0:
logger.warning(f"Validation at step {step}: {nan_count} batches had NaN loss")
if mean_loss != mean_loss:
logger.warning(f"Validation at step {step} had no valid tokens")
else:
logger.success(f"Validation | Step {step} | Loss: {mean_loss:.4f}")
monitor.log({"val/loss": mean_loss, "step": step}, step=step)
logger.info(f"Starting training loop (max_steps={config.max_steps or 'infinite'})")
max_memory = torch.cuda.mem_get_info()[1] / 1024**3 # GiB
is_first_step = True
maybe_record_function = nullcontext
if config.trace_path:
logger.info(f"Tracing to {config.trace_path}")
prof = profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], record_shapes=True).__enter__()
maybe_record_function = record_function
maybe_record_function = record_function # noqa: F841 – captured by run_forward_loop closure
while True:
# Reset peak memory stats
torch.cuda.reset_peak_memory_stats()
@@ -193,20 +288,23 @@ def train(config: SFTConfig):
and not (is_first_step or is_last_step)
and progress.step % config.ckpt.interval == 0
):
# Save full checkpoint
logger.info(f"Saving checkpoint at step {progress.step}")
save_ckpt_start_time = time.perf_counter()
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
save_ckpt_time = time.perf_counter() - save_ckpt_start_time
save_ckpt_time = 0
if not config.ckpt.weights_only:
# Save full checkpoint
logger.info(f"Saving checkpoint at step {progress.step}")
save_ckpt_start_time = time.perf_counter()
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
# Maybe clean up old checkpoints
ckpt_manager.maybe_clean()
# Save weight checkpoint
if weight_ckpt_manager is not None:
logger.info(f"Saving weight checkpoint at step {progress.step}")
save_ckpt_start_time = time.perf_counter()
weight_ckpt_manager.save(progress.step, model, tokenizer)
# Maybe clean up old weight checkpoint
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
weight_ckpt_manager.maybe_clean()
else:
save_ckpt_time = 0
@@ -222,61 +320,33 @@ def train(config: SFTConfig):
step_start_time = time.perf_counter()
forward_backward_start_time = time.perf_counter()
batch_loss = torch.tensor(0.0).to("cuda")
nan_loss_count = torch.tensor(0).to("cuda")
batch_max_vio, max_vio = torch.tensor(0.0).to("cuda"), None
step_loss_sum = torch.tensor(0.0, device="cuda")
step_local_token_count = torch.tensor(0, dtype=torch.int64, device="cuda")
nan_loss_count = torch.tensor(0, device="cuda")
batch_max_vio = torch.tensor(0.0, device="cuda")
for micro_step in range(grad_accum_steps):
micro_batch = next(dataiter)
input_ids = micro_batch["input_ids"].to("cuda")
position_ids = micro_batch["position_ids"].to("cuda")
target_ids = micro_batch["target_ids"].to("cuda")
loss_mask = micro_batch["loss_mask"].to("cuda")
if cp_enabled:
input_ids, position_ids = setup_cp_params(input_ids, position_ids, cp_rank, cp_size, cp_group)
target_ids = shard_for_cp(target_ids, cp_rank=cp_rank, cp_world_size=cp_size)
loss_mask = shard_for_cp(loss_mask, cp_rank=cp_rank, cp_world_size=cp_size)
assert input_ids.shape == position_ids.shape == target_ids.shape == loss_mask.shape, (
f"input_ids.shape: {input_ids.shape}, position_ids.shape: {position_ids.shape}, target_ids.shape: {target_ids.shape}, loss_mask.shape: {loss_mask.shape}"
)
if config.log.log_data:
logger.debug("Printing samples of the first micro batch")
print_sample(input_ids.flatten().tolist(), loss_mask.flatten().tolist(), tokenizer)
print_sample(
micro_batch["input_ids"].flatten().tolist(), micro_batch["loss_mask"].flatten().tolist(), tokenizer
)
# Forward pass
logger.debug("Starting forward pass")
with maybe_record_function("forward"), maybe_activation_offloading(config.model.ac_offloading):
out = forward(model, input_ids, position_ids)
with maybe_record_function("forward"):
local_loss_sum, local_token_count = compute_loss(micro_batch)
logits = out["logits"]
B, L, V = logits.shape
step_local_token_count += local_token_count
# Compute loss
loss = ce_loss(logits.view(-1, V), target_ids.view(-1)).view(B, L)
# Compute average loss over unmasked tokens
loss = loss[loss_mask].mean()
# Accumulate average loss over gradient accumulation steps
current_loss = loss.detach() / grad_accum_steps
# only add if the loss is not nan
if not torch.isnan(current_loss):
batch_loss += current_loss
else:
if torch.isnan(local_loss_sum.detach()):
nan_loss_count += 1
logger.warning("Loss is nan, not taking into account in the batch loss calculation")
logger.warning("Local loss is nan, excluding this micro step from backward")
scaled_loss = torch.nan_to_num(local_loss_sum, nan=0.0) / grad_accum_steps
else:
step_loss_sum += local_loss_sum.detach()
scaled_loss = local_loss_sum / grad_accum_steps
# Delete logits before backward pass to avoid memory spike
del logits
# Backward pass
logger.debug("Starting backward pass")
with maybe_record_function("backward"):
(loss / grad_accum_steps).backward()
scaled_loss.backward()
if is_tt_moe_model(model):
max_vio = get_load_balance_stats(model)["max_vio"]
@@ -285,11 +355,37 @@ def train(config: SFTConfig):
dist.all_reduce(max_vio, op=dist.ReduceOp.MAX)
batch_max_vio += max_vio / grad_accum_steps
# Debug log with *local, micro step* stats
micro_step_message = f"Micro Step {micro_step}/{grad_accum_steps} | Loss: {loss.item():.4f} | Dataloader Step: {dataloader.state_dict()['dataset_state']['dataset']['step']}"
if is_tt_moe_model(model) and max_vio is not None:
micro_step_message += f" | Max Vio: {max_vio.item():.4f}"
logger.debug(micro_step_message)
forward_backward_time = time.perf_counter() - forward_backward_start_time
# All-reduce token counts and rescale gradients to get a global token-weighted mean.
# FSDP already divided grads by fsdp_gradient_divide_factor, so we undo that and
# divide by the true global token count instead.
global_step_token_count = step_local_token_count.clone()
dist.all_reduce(global_step_token_count, op=dist.ReduceOp.SUM, group=dp_cp_group)
global_token_count_val = global_step_token_count.item()
if global_token_count_val > 0:
grad_scale = parallel_dims.fsdp_gradient_divide_factor * grad_accum_steps / global_token_count_val
for param in model.parameters():
if param.grad is not None:
param.grad.mul_(grad_scale)
# Run validation after forward-backward (so torch.compile sees training graph first) but before
# optimizer step (so eval_on_start evaluates untrained weights)
if config.val is not None and (
(is_first_step and config.val.eval_on_start)
or (not is_first_step and progress.step % config.val.interval == 0)
):
run_validation(progress.step)
# Compute the global mean loss for logging.
dist.all_reduce(step_loss_sum, op=dist.ReduceOp.SUM, group=dp_cp_group)
dist.all_reduce(nan_loss_count, op=dist.ReduceOp.SUM)
if global_token_count_val > 0:
batch_loss = (step_loss_sum / global_token_count_val).item()
else:
batch_loss = 0.0
nan_loss_count = nan_loss_count.item()
logger.debug(f"Clipping gradients with max norm {config.optim.max_norm}")
grad_norm = clip_grad_norm_(
@@ -297,6 +393,7 @@ def train(config: SFTConfig):
)
if grad_norm.device.type == "cpu":
grad_norm = grad_norm.to(torch.device("cuda"))
zero_grad_ratio = get_zero_gradient_ratio(model.parameters(), parallel_dims.dp_replicate)
logger.debug("Optimizer step")
optimizer.step()
@@ -306,17 +403,10 @@ def train(config: SFTConfig):
current_lr = optimizer.param_groups[0]["lr"]
scheduler.step()
forward_backward_time = time.perf_counter() - forward_backward_start_time
# Optionally, dump memory snapshot
if memory_profiler is not None:
memory_profiler.step()
# Synchronize the tensor metrics across all steps and ranks
logger.debug("Synchronizing tensor metrics across all steps and ranks")
dist.all_reduce(batch_loss, op=dist.ReduceOp.AVG)
dist.all_reduce(nan_loss_count, op=dist.ReduceOp.SUM)
# Compute step metrics
# Divide by CP and TP since those ranks process the same data
num_tokens = config.data.batch_size * config.data.seq_len // (config.model.cp * config.model.tp)
@@ -330,8 +420,8 @@ def train(config: SFTConfig):
# Log step metrics
step_time = time.perf_counter() - step_start_time
step_message = f"Step {progress.step} | Time: {step_time:.2f}s | Loss: {batch_loss.item():.4f} | Grad. Norm: {grad_norm:.4f} | LR: {current_lr:.2e} | Throughput: {throughput:.0f} tokens/s | MFU: {mfu:.1f}% | Peak Mem.: {peak_memory:.1f}/{max_memory:.1f} GiB ({peak_memory / max_memory * 100:.1f}%)"
if is_tt_moe_model(model) and max_vio is not None:
step_message = f"Step {progress.step} | Time: {step_time:.2f}s | Loss: {batch_loss:.4f} | Grad. Norm: {grad_norm:.4f} | LR: {current_lr:.2e} | Throughput: {throughput:.0f} tokens/s | MFU: {mfu:.1f}% | Peak Mem.: {peak_memory:.1f}/{max_memory:.1f} GiB ({peak_memory / max_memory * 100:.1f}%)"
if is_tt_moe_model(model) and batch_max_vio.item() > 0:
step_message += f" | Max Vio: {batch_max_vio.item():.4f}"
logger.success(step_message)
@@ -372,13 +462,14 @@ def train(config: SFTConfig):
optim_metrics = {
"optim/lr": current_lr,
"optim/grad_norm": grad_norm.item(),
"optim/zero_grad_ratio": zero_grad_ratio,
"step": progress.step,
}
monitor.log(optim_metrics, step=progress.step)
loss_log_metrics = {
"loss/mean": batch_loss.item(),
"loss/nan_count": nan_loss_count.item(),
"loss/mean": batch_loss,
"loss/nan_count": nan_loss_count,
"step": progress.step,
}
# Log tensor stats
@@ -398,12 +489,8 @@ def train(config: SFTConfig):
disk_metrics["step"] = progress.step
monitor.log(disk_metrics, step=progress.step)
if is_tt_moe_model(model):
max_vio_log_metrics = {
"max_vio/mean": batch_max_vio.item(),
"step": progress.step,
}
monitor.log(max_vio_log_metrics, step=progress.step)
if is_tt_moe_model(model) and batch_max_vio.item() > 0:
monitor.log({"max_vio/mean": batch_max_vio.item(), "step": progress.step}, step=progress.step)
is_first_step = False
progress.step += 1
@@ -422,8 +509,9 @@ def train(config: SFTConfig):
# Write final checkpoint
if ckpt_manager is not None:
logger.info("Writing final checkpoint")
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
if not (config.ckpt and config.ckpt.weights_only):
logger.info("Writing final checkpoint")
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
ckpt_manager.maybe_clean()
# Write final weight checkpoint
+59 -1
View File
@@ -3,6 +3,7 @@ import pickle
import shutil
import time
from collections import defaultdict
from collections.abc import Iterable
from datetime import timedelta
from pathlib import Path
from typing import Any
@@ -14,7 +15,8 @@ from rich import print as rich_print
from rich.console import Console
from rich.table import Table
from rich.text import Text
from torch import Tensor
from torch import Tensor, nn
from torch.distributed.tensor import DTensor
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.trainer.world import get_world
@@ -25,6 +27,62 @@ from prime_rl.utils.utils import format_num, format_time, get_step_path
DEFAULT_TIMEOUT = timedelta(seconds=600)
def _to_local_tensor(tensor: Tensor | DTensor) -> Tensor:
if isinstance(tensor, DTensor):
return tensor.to_local()
return tensor
def count_zero_gradient_elements(parameters: Iterable[nn.Parameter]) -> tuple[Tensor, Tensor]:
"""Count zero-gradient parameter elements on the local distributed shards.
Parameters that require gradients but did not receive one in the current step
are counted as fully zero. This makes inactive MoE experts visible in the
metric instead of silently dropping them from the count.
"""
device = torch.device("cuda", torch.cuda.current_device()) if torch.cuda.is_available() else torch.device("cpu")
num_zeros = torch.zeros((), dtype=torch.long, device=device)
num_tracked = torch.zeros((), dtype=torch.long, device=device)
for param in parameters:
if not param.requires_grad:
continue
local_param = _to_local_tensor(param.detach())
if local_param.numel() == 0:
continue
if local_param.device != num_zeros.device:
num_zeros = num_zeros.to(local_param.device)
num_tracked = num_tracked.to(local_param.device)
local_numel = torch.tensor(local_param.numel(), dtype=torch.long, device=local_param.device)
num_tracked += local_numel
if param.grad is None:
num_zeros += local_numel
continue
local_grad = _to_local_tensor(param.grad.detach())
if local_grad.numel() != local_param.numel():
raise ValueError("Local gradient shape does not match the local parameter shape")
num_zeros += local_numel - torch.count_nonzero(local_grad)
return num_zeros, num_tracked
def get_zero_gradient_ratio(parameters: Iterable[nn.Parameter], dp_replicate: int = 1) -> float:
num_zero_grad, num_grad_elements = count_zero_gradient_elements(parameters)
dist.all_reduce(num_zero_grad, op=dist.ReduceOp.SUM)
dist.all_reduce(num_grad_elements, op=dist.ReduceOp.SUM)
if dp_replicate > 1:
num_zero_grad = torch.div(num_zero_grad, dp_replicate, rounding_mode="floor")
num_grad_elements = torch.div(num_grad_elements, dp_replicate, rounding_mode="floor")
return (num_zero_grad.float() / num_grad_elements.clamp_min(1).float()).item()
def get_ckpt_disk_metrics(output_dir: Path) -> dict[str, float]:
"""
Disk usage metrics for the checkpoint directory (<output_dir>/checkpoints).
+9 -2
View File
@@ -33,9 +33,16 @@ def _strip_pytorch_wrapper_prefix(key: str) -> str:
return key
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
def get_max_layer_num(state_dict: dict[str, Tensor], layer_prefix: str = "model.layers.") -> int:
"""Get the maximum number of layers in the model."""
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
max_num = -1
for key in state_dict:
if not key.startswith(layer_prefix):
continue
layer_num_str = key[len(layer_prefix) :].split(".")[0]
if layer_num_str.isdigit():
max_num = max(max_num, int(layer_num_str))
return max_num + 1
def load_state_dict_keys(save_dir: Path) -> list[str]:
+139
View File
@@ -0,0 +1,139 @@
import json
from typing import Any, Callable
from transformers.tokenization_utils import PreTrainedTokenizer
def common_prefix_len(a: list[int], b: list[int]) -> int:
max_len = min(len(a), len(b))
for idx in range(max_len):
if a[idx] != b[idx]:
return idx
return max_len
def normalize_messages(messages: Any, default_role: str) -> list[dict[str, Any]]:
if messages is None:
return []
if isinstance(messages, str):
return [{"role": default_role, "content": messages}]
if isinstance(messages, dict):
return [dict(messages)]
if isinstance(messages, list):
normalized: list[dict[str, Any]] = []
for message in messages:
if isinstance(message, str):
normalized.append({"role": default_role, "content": message})
elif isinstance(message, dict):
normalized.append(dict(message))
else:
raise TypeError(f"Unsupported message type: {type(message)}")
return normalized
raise TypeError(f"Unsupported messages container type: {type(messages)}")
def deserialize_tool_calls(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
def _deserialize_tool_call(tool_call: dict[str, Any]) -> dict[str, Any]:
function = tool_call.get("function", {})
arguments = function.get("arguments")
if isinstance(arguments, str):
arguments = json.loads(arguments)
return {
**tool_call,
"function": {**function, "arguments": arguments},
}
deserialized_messages: list[dict[str, Any]] = []
for message in messages:
if "tool_calls" not in message:
deserialized_messages.append(dict(message))
continue
tool_calls = message.get("tool_calls") or []
deserialized_messages.append(
{
**message,
"tool_calls": [_deserialize_tool_call(tc) for tc in tool_calls],
}
)
return deserialized_messages
def strip_message_content(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
def _strip(message: dict[str, Any]) -> dict[str, Any]:
content = message.get("content")
if isinstance(content, str):
return {**message, "content": content.strip()}
return message
return [_strip(message) for message in messages]
def should_add_generation_prompt(messages: list[dict[str, Any]], idx: int) -> bool:
role = messages[idx].get("role")
if role not in ("user", "tool"):
return False
if idx + 1 >= len(messages):
return False
return messages[idx + 1].get("role") == "assistant"
def render_messages(
tokenizer: PreTrainedTokenizer,
messages: list[dict[str, Any]],
*,
tools: list[dict[str, Any]] | None = None,
chat_template_kwargs: dict[str, Any] | None = None,
add_generation_prompt: bool = False,
processor=None,
) -> list[int]:
kwargs = dict(chat_template_kwargs or {})
kwargs["add_generation_prompt"] = add_generation_prompt
if tools is not None:
kwargs["tools"] = tools
if processor is not None:
kwargs["tokenize"] = True
kwargs["return_dict"] = True
result = processor.apply_chat_template(messages, **kwargs)
return list(result["input_ids"][0])
kwargs["return_dict"] = False
return list(tokenizer.apply_chat_template(messages, **kwargs))
def build_incremental_token_mask(
tokenizer: PreTrainedTokenizer,
messages: list[dict[str, Any]],
*,
role_to_mask: Callable[[dict[str, Any]], bool],
tools: list[dict[str, Any]] | None = None,
chat_template_kwargs: dict[str, Any] | None = None,
collapse_consecutive_tool_messages: bool = False,
processor=None,
) -> tuple[list[int], list[bool]]:
token_mask: list[bool] = []
prev_ids: list[int] = []
prev_len = 0
for idx, message in enumerate(messages):
role = message.get("role")
if collapse_consecutive_tool_messages and role == "tool" and idx + 1 < len(messages):
if messages[idx + 1].get("role") == "tool":
continue
cur_ids = render_messages(
tokenizer,
messages[: idx + 1],
tools=tools,
chat_template_kwargs=chat_template_kwargs,
add_generation_prompt=should_add_generation_prompt(messages, idx),
processor=processor,
)
assert prev_ids == cur_ids[:prev_len], "Mismatch in incremental tokenization with chat template."
token_mask.extend([role_to_mask(message)] * (len(cur_ids) - prev_len))
prev_ids = cur_ids
prev_len = len(cur_ids)
return prev_ids, token_mask
+32 -15
View File
@@ -109,6 +109,7 @@ async def setup_inference_pool(
logger.info(
f"Initializing static inference pool (base_url={', '.join(client_config.base_url)}, "
f"dp_rank_count={client_config.dp_rank_count}, "
f"api_key_var={client_config.api_key_var}, headers={client_config.headers})"
)
return StaticInferencePool(
@@ -119,20 +120,29 @@ async def setup_inference_pool(
def setup_clients(client_config: ClientConfig, client_type: str = "openai_chat_completions") -> list[vf.ClientConfig]:
def setup_client(client_idx: int, base_url: str) -> vf.ClientConfig:
return vf.ClientConfig(
client_idx=client_idx,
client_type=client_type,
api_base_url=base_url,
api_key_var=client_config.api_key_var,
timeout=client_config.timeout,
max_connections=8192,
max_keepalive_connections=8192,
max_retries=10,
extra_headers=client_config.headers,
)
return [setup_client(client_idx, base_url) for client_idx, base_url in enumerate(client_config.base_url)]
clients = []
client_idx = 0
for base_url in client_config.base_url:
for dp_rank in range(client_config.dp_rank_count):
headers = client_config.headers.copy()
if client_config.dp_rank_count > 1:
headers["X-data-parallel-rank"] = str(dp_rank)
clients.append(
vf.ClientConfig(
client_idx=client_idx,
client_type=client_type,
api_base_url=base_url,
api_key_var=client_config.api_key_var,
timeout=client_config.timeout,
connect_timeout=client_config.connect_timeout,
max_connections=8192,
max_keepalive_connections=8192,
max_retries=10,
extra_headers=headers,
)
)
client_idx += 1
return clients
def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
@@ -301,7 +311,13 @@ async def unload_lora_adapter(admin_clients: list[AsyncClient], lora_name: str)
await asyncio.gather(*[_unload_lora_adapter(admin_client) for admin_client in admin_clients])
async def init_nccl_broadcast(admin_clients: list[AsyncClient], host: str, port: int, timeout: int) -> None:
async def init_nccl_broadcast(
admin_clients: list[AsyncClient],
host: str,
port: int,
timeout: int,
quantize_in_weight_transfer: bool = False,
) -> None:
"""Make a HTTP post request to the vLLM server to initialize the NCCL broadcast."""
logger = get_logger()
@@ -317,6 +333,7 @@ async def init_nccl_broadcast(admin_clients: list[AsyncClient], host: str, port:
"server_rank": client_num,
"num_inference_server": len(admin_clients),
"timeout": timeout,
"quantize_in_weight_transfer": quantize_in_weight_transfer,
},
)
response.raise_for_status()
+14 -1
View File
@@ -108,6 +108,7 @@ class ElasticInferencePool:
port: int = 8000,
sync_interval: float = 5.0,
client_type: str = "openai_chat_completions",
router_url: str | None = None,
):
self.logger = get_logger()
self.hostname = hostname
@@ -117,6 +118,7 @@ class ElasticInferencePool:
self.port = port
self.sync_interval = sync_interval
self.client_type = client_type
self.router_url = router_url
self._servers: dict[str, ServerState] = {}
self._admin_clients: dict[str, AsyncClient] = {}
@@ -143,6 +145,7 @@ class ElasticInferencePool:
port=config.elastic.port,
sync_interval=config.elastic.sync_interval,
client_type=client_type,
router_url=config.router_url,
)
await pool.start()
return pool
@@ -162,7 +165,15 @@ class ElasticInferencePool:
@property
def clients(self) -> list[vf.ClientConfig]:
urls = self.ready_urls
# When a router URL is configured, route inference requests through it
# instead of directly to discovered pods. Admin operations still use
# individual pod IPs via admin_clients.
# Only expose the router when backends are actually ready — otherwise
# the orchestrator would send requests into a router with no healthy backends.
if self.router_url and self.ready_urls:
urls = [self.router_url]
else:
urls = self.ready_urls
if set(urls) != set(self._client_urls):
self._client_urls = urls
self._client_index = 0
@@ -170,9 +181,11 @@ class ElasticInferencePool:
setup_clients(
ClientConfig(
timeout=self.client_config.timeout,
connect_timeout=self.client_config.connect_timeout,
base_url=urls,
api_key_var=self.client_config.api_key_var,
headers=self.client_config.headers,
dp_rank_count=self.client_config.dp_rank_count,
),
client_type=self.client_type,
)
+7
View File
@@ -115,6 +115,11 @@ class MetricsServer(HealthServer):
"trainer_mismatch_kl", "KL divergence between trainer and inference model", registry=self._registry
)
self._kl_ent_ratio = Gauge("trainer_kl_ent_ratio", "Ratio of mismatch KL to entropy", registry=self._registry)
self._zero_grad_ratio = Gauge(
"trainer_zero_grad_ratio",
"Fraction of tracked parameter elements with zero gradient",
registry=self._registry,
)
# Aggregate run metrics
self._runs_discovered = Gauge(
"trainer_runs_discovered", "Number of run folders discovered", registry=self._registry
@@ -196,6 +201,7 @@ class MetricsServer(HealthServer):
mfu: float = 0.0,
entropy: float = 0.0,
mismatch_kl: float = 0.0,
zero_grad_ratio: float = 0.0,
) -> None:
"""Update metrics after a training step."""
self._step.set(step)
@@ -207,6 +213,7 @@ class MetricsServer(HealthServer):
self._mfu.set(mfu)
self._entropy.set(entropy)
self._mismatch_kl.set(mismatch_kl)
self._zero_grad_ratio.set(zero_grad_ratio)
if entropy > 0:
self._kl_ent_ratio.set(mismatch_kl / entropy)
self._last_step_ts.set(time.time())
+2 -6
View File
@@ -12,7 +12,7 @@ class Monitor(ABC):
"""
@abstractmethod
def log(self, metrics: dict[str, Any], step: int | None = None) -> None:
def log(self, metrics: dict[str, Any], step: int) -> None:
pass
@abstractmethod
@@ -31,10 +31,6 @@ class Monitor(ABC):
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
pass
def flush(self, step: int) -> None:
"""Commit all accumulated metrics for the given step."""
pass
def close(self) -> None:
"""Close any resources held by the monitor. Override in subclasses that need cleanup."""
pass
@@ -46,7 +42,7 @@ class NoOpMonitor(Monitor):
def __init__(self):
self.history: list[dict[str, Any]] = []
def log(self, metrics: dict[str, Any], step: int | None = None) -> None:
def log(self, metrics: dict[str, Any], step: int) -> None:
self.history.append(metrics)
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
+1 -8
View File
@@ -19,7 +19,7 @@ class MultiMonitor(Monitor):
return []
return self.monitors[0].history
def log(self, metrics: dict[str, Any], step: int | None = None) -> None:
def log(self, metrics: dict[str, Any], step: int) -> None:
for monitor in self.monitors:
try:
monitor.log(metrics, step=step)
@@ -54,13 +54,6 @@ class MultiMonitor(Monitor):
except Exception as e:
self.logger.warning(f"Failed to log distributions to {monitor.__class__.__name__}: {e}")
def flush(self, step: int) -> None:
for monitor in self.monitors:
try:
monitor.flush(step=step)
except Exception as e:
self.logger.warning(f"Failed to flush {monitor.__class__.__name__}: {e}")
def close(self) -> None:
for monitor in self.monitors:
try:
+141 -11
View File
@@ -2,16 +2,19 @@ import asyncio
import io
import json
import os
import random
import time
from datetime import datetime, timezone
from pathlib import Path
from threading import Thread
from typing import Any
from urllib.parse import urlparse
import httpx
import pyarrow as pa
import pyarrow.parquet as pq
import verifiers as vf
from prime_cli.core.config import Config as PrimeConfig
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.configs.shared import PrimeMonitorConfig
@@ -67,6 +70,10 @@ class PrimeMonitor(Monitor):
self.logger = get_logger()
self.history: list[dict[str, Any]] = []
self.output_dir = output_dir
self._registered = False
self._finalized = False
self._closed = False
self._owner_pid = os.getpid()
rank = int(os.environ.get("RANK", os.environ.get("DP_RANK", "0")))
self.enabled = self.config is not None
@@ -79,24 +86,31 @@ class PrimeMonitor(Monitor):
assert config is not None
self.logger.info(f"Initializing {self.__class__.__name__} ({config})")
# Get API key from environment variable
api_key = os.getenv(config.api_key_var)
if api_key is None:
prime_config = PrimeConfig()
api_key = prime_config.api_key
if not api_key:
self.logger.warning(
f"API key not found. Set {config.api_key_var} environment variable. PrimeMonitor will not be able to upload data."
f"API key not found. Set {config.api_key_var} environment variable or run `prime login`. "
"PrimeMonitor will not be able to upload data."
)
self.enabled = False
return
self.api_key = api_key
self.base_url = config.base_url
self.base_url = config.base_url.rstrip("/")
# Get run_id from environment variable (check before allocating resources)
run_id = os.getenv("RUN_ID")
if not run_id:
self.logger.warning("RUN_ID environment variable not set. PrimeMonitor will not be able to upload data.")
self.enabled = False
return
run_id = self._register_run(config, run_config)
if run_id:
os.environ["RUN_ID"] = run_id
else:
self.enabled = False
return
self.run_id = run_id
# Set up async HTTP client with background event loop.
@@ -117,7 +131,105 @@ class PrimeMonitor(Monitor):
if config.log_extras.distributions:
self.last_log_distributions_step = -1
def log(self, metrics: dict[str, Any], step: int | None = None) -> None:
def _register_run(self, config: PrimeMonitorConfig, run_config: BaseConfig | None) -> str | None:
"""Register an external run with the platform. Returns run_id on success, None on failure."""
registration_api_key = self.api_key
if not registration_api_key:
self.logger.warning(
f"Prime Intellect API key not found. Set {config.api_key_var} environment variable or run `prime login`. "
"PrimeMonitor will not be able to register or upload data."
)
return None
prime_config = None
team_id = config.team_id
frontend_url = config.frontend_url
if team_id is None or frontend_url is None:
prime_config = PrimeConfig()
if team_id is None:
team_id = prime_config.team_id
if frontend_url is None:
frontend_url = prime_config.frontend_url
model = getattr(run_config, "model", None) if run_config else None
environments = getattr(run_config, "env", None) if run_config else None
wandb = getattr(run_config, "wandb", None) if run_config else None
payload: dict = {
"base_model": model.name if model else "unknown",
"max_steps": getattr(run_config, "max_steps", None) or 0,
}
if config.run_name:
payload["name"] = config.run_name
if team_id:
payload["team_id"] = team_id
if environments:
payload["environments"] = [{"id": env.id} for env in environments if hasattr(env, "id")]
if wandb and getattr(wandb, "project", None):
payload["wandb_project"] = wandb.project
parsed = urlparse(config.base_url)
api_base = f"{parsed.scheme}://{parsed.netloc}/api/v1/rft"
try:
response = httpx.post(
f"{api_base}/external-runs",
headers={"Authorization": f"Bearer {registration_api_key}"},
json=payload,
timeout=30,
)
except httpx.HTTPError as e:
self.logger.warning(f"Failed to register platform run: {e}. PrimeMonitor will not be able to upload data.")
return None
if response.status_code != 201:
self.logger.warning(
f"Failed to create platform run (HTTP {response.status_code}): {response.text}. "
"PrimeMonitor will not be able to upload data."
)
return None
run_id = response.json()["run"]["id"]
if frontend_url:
dashboard_url = f"{frontend_url.rstrip('/')}/dashboard/training/{run_id}"
self.logger.success(f"Monitor run at: {dashboard_url}")
else:
self.logger.success(f"Registered platform run {run_id}")
self._registered = True
return run_id
def _finalize_run(self, success: bool) -> None:
"""Mark the run as completed or failed on the platform."""
if not getattr(self, "_registered", False):
return
registration_api_key = self.api_key
payload: dict = {"status": "completed" if success else "failed"}
status_label = "completed" if success else "failed"
self.logger.info(f"Finalizing platform run {self.run_id} as {status_label}")
parsed = urlparse(self.base_url)
finalize_url = f"{parsed.scheme}://{parsed.netloc}/api/v1/rft/external-runs/{self.run_id}/status"
try:
response = httpx.put(
finalize_url,
headers={"Authorization": f"Bearer {registration_api_key}"},
json=payload,
timeout=30,
)
except httpx.HTTPError as e:
self.logger.warning(f"Failed to finalize platform run {self.run_id}: {e}")
return
if response.status_code != 200:
self.logger.warning(
f"Failed to finalize platform run {self.run_id} (HTTP {response.status_code}): {response.text}"
)
return
self.logger.info(f"Platform run {self.run_id} marked as {status_label}")
def log(self, metrics: dict[str, Any], step: int) -> None:
self.history.append(metrics)
if not self.is_master:
return
@@ -143,14 +255,22 @@ class PrimeMonitor(Monitor):
or not self.config.log_extras.samples
or step % self.config.log_extras.interval != 0
):
# Do not log samples if not enabled or not log interval step
return
ratio = self.config.log_extras.sample_ratio
if ratio is not None:
if ratio <= 0.0:
return
if ratio < 1.0:
max_samples = max(1, int(len(rollouts) * ratio))
if len(rollouts) > max_samples:
rollouts = random.sample(rollouts, max_samples)
assert self.last_log_samples_step <= step, "Step must be greater than last logged step"
assert step not in self._pending_sample_steps, f"Step {step} upload already in progress"
assert self.logger is not None, "Logger is required for sample logging"
self.logger.info(f"Logging samples to Prime Intellect API at step {step}")
self.logger.info(f"Logging {len(rollouts)} samples to Prime Intellect API at step {step}")
start_time = time.perf_counter()
parquet_bytes = self._rollouts_to_parquet_bytes(rollouts, step)
@@ -378,12 +498,22 @@ class PrimeMonitor(Monitor):
"summary": self.history[-1] if self.history else {},
},
)
if os.getpid() == self._owner_pid:
self._finalize_run(success=True)
self._finalized = True
def close(self) -> None:
"""Close the HTTP client and stop the background event loop."""
if not hasattr(self, "_client"):
if self._closed or not hasattr(self, "_client"):
return
self._closed = True
should_finalize = self.is_master and self.enabled and not self._finalized and os.getpid() == self._owner_pid
if should_finalize:
self._finalize_run(success=False)
self._finalized = True
self._flush()
# Close the async client within the event loop
+51 -17
View File
@@ -9,6 +9,7 @@ import pandas as pd
import verifiers as vf
import wandb
from transformers.tokenization_utils import PreTrainedTokenizer
from wandb.errors import CommError
from prime_rl.configs.shared import WandbConfig, WandbWithExtrasConfig
from prime_rl.utils.config import BaseConfig
@@ -34,6 +35,7 @@ class WandbMonitor(Monitor):
rank = int(os.environ.get("RANK", os.environ.get("DP_RANK", "0")))
self.enabled = self.config is not None
self.is_master = rank == 0
if not self.enabled or not self.is_master:
if not self.is_master:
self.logger.warning(f"Skipping {self.__class__.__name__} initialization from non-master rank ({rank})")
@@ -42,15 +44,52 @@ class WandbMonitor(Monitor):
assert config is not None
self.logger.info(f"Initializing {self.__class__.__name__} ({config})")
self._maybe_overwrite_wandb_command()
self.wandb = wandb.init(
project=config.project,
name=config.name,
id=config.id,
dir=output_dir,
resume="allow",
config=run_config.model_dump() if run_config else None,
mode="offline" if config.offline else None,
)
shared_mode = os.environ.get("WANDB_SHARED_MODE") == "1"
if shared_mode:
run_id = os.environ.get("WANDB_SHARED_RUN_ID")
label = os.environ.get("WANDB_SHARED_LABEL")
primary = label == "orchestrator"
settings = wandb.Settings(
mode="shared",
x_label=label,
x_primary=primary,
x_update_finish_state=primary,
)
self.logger.info(
f"Using shared W&B mode ({label=}, {primary=}). "
"This is an experimental feature. Disable with --wandb.shared False"
)
else:
run_id = None
primary = False
settings = wandb.Settings(
mode="offline" if config.offline else "online",
)
def init_wandb(max_retries: int):
for attempt in range(max_retries):
try:
return wandb.init(
id=run_id,
project=config.project,
name=config.name,
dir=output_dir,
config=run_config.model_dump() if run_config else None,
settings=settings,
)
except CommError:
if attempt + 1 == max_retries:
raise
self.logger.info(
f"Shared W&B run not yet created by primary, retrying in 10s ({attempt + 1}/{max_retries})"
)
time.sleep(10)
max_retries = 1 if not shared_mode or primary else 30
self.wandb = init_wandb(max_retries)
wandb.define_metric("*", step_metric="step")
# Optionally, initialize sample logging attributes
if config is not None and isinstance(config, WandbWithExtrasConfig) and config.log_extras:
@@ -71,13 +110,13 @@ class WandbMonitor(Monitor):
self.logger.debug(f"Found WANDB_ARGS in environment variables {wandb_args}")
sys.argv = json.loads(wandb_args)
def log(self, metrics: dict[str, Any], step: int | None = None) -> None:
def log(self, metrics: dict[str, Any], step: int) -> None:
self.history.append(metrics)
if not self.is_master:
return
if not self.enabled:
return
wandb.log(metrics, step=step)
wandb.log({**metrics, "step": step})
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
"""Logs rollouts to W&B table."""
@@ -122,7 +161,7 @@ class WandbMonitor(Monitor):
self.samples_table.add_data(*sample.values())
self.samples.append(sample)
wandb.log({"samples": self.samples_table}, step=step)
wandb.log({"samples": self.samples_table, "step": step})
self.last_log_samples_step = step
self.logger.debug(f"Logged samples at step {step} to W&B table in {time.perf_counter() - start_time:.2f}s")
@@ -147,11 +186,6 @@ class WandbMonitor(Monitor):
"""Log distributions (no-op for W&B)."""
pass
def flush(self, step: int) -> None:
if not self.is_master or not self.enabled:
return
wandb.log({}, step=step, commit=True)
def save_final_summary(self, filename: str = "final_summary.json") -> None:
"""Save final summary to W&B table."""
if not self.is_master or not self.enabled:
+20 -12
View File
@@ -69,29 +69,37 @@ def has_checkpoints(output_dir: Path) -> bool:
return ckpt_dir.exists() and any(ckpt_dir.iterdir())
def validate_output_dir(output_dir: Path, *, resuming: bool, clean: bool) -> None:
def validate_output_dir(output_dir: Path, *, resuming: bool, clean: bool, ckpt_output_dir: Path | None = None) -> None:
"""Validate the output directory before training starts.
Raises if the directory contains checkpoints from a previous run, unless
explicitly resuming or opting into cleaning. Other artifacts (logs,
rollouts, configs) are fine and don't trigger the error.
When ckpt_output_dir is set, checkpoints live there instead of under
output_dir, so the guard and clean logic check both locations.
"""
if not output_dir.exists():
return
dirs_to_check = [output_dir]
if ckpt_output_dir is not None and ckpt_output_dir != output_dir:
dirs_to_check.append(ckpt_output_dir)
if resuming:
return
if clean:
logger = get_logger()
logger.warning(f"Cleaning existing output directory: {output_dir}")
shutil.rmtree(output_dir)
for d in dirs_to_check:
if d.exists():
logger.warning(f"Cleaning existing directory: {d}")
shutil.rmtree(d)
return
if has_checkpoints(output_dir):
raise FileExistsError(
f"Output directory '{output_dir}' already contains checkpoints from a previous run. "
f"To resume the latest step of the previous run, set ckpt.resume_step=-1 or --ckpt.resume-step -1 via CLI. "
f"To delete the existing directory and start fresh, set clean_output_dir=true or --clean-output-dir via CLI. "
f"Otherwise use a unique output_dir for this experiment."
)
for d in dirs_to_check:
if has_checkpoints(d):
raise FileExistsError(
f"Directory '{d}' already contains checkpoints from a previous run. "
f"To resume the latest step of the previous run, set ckpt.resume_step=-1 or --ckpt.resume-step -1 via CLI. "
f"To delete the existing directory and start fresh, set clean_output_dir=true or --clean-output-dir via CLI. "
f"Otherwise use a unique output_dir for this experiment."
)
def sync_wait_for_path(path: Path, interval: int = 1, log_interval: int = 10) -> None:
+7 -1
View File
@@ -307,8 +307,14 @@ def install_env(env_id: str) -> None:
logger.info(f"Installing environment {env_id}")
install_cmd = ["uv", "run", "--no-sync", "prime", "env", "install", env_id]
result = subprocess.run(install_cmd, capture_output=True, text=True)
for line in result.stdout.splitlines():
if line.strip():
logger.info(line)
for line in result.stderr.splitlines():
if line.strip():
logger.warning(line)
if result.returncode != 0:
raise RuntimeError(f"Failed to install environment {env_id} (stdout={result.stdout}, stderr={result.stderr})")
raise RuntimeError(f"Failed to install environment {env_id} (exit code {result.returncode})")
logger.info(f"Successfully installed environment {env_id}")
+7 -5
View File
@@ -34,6 +34,13 @@ def validate_shared_model_name(
orchestrator: OrchestratorConfig,
inference: Optional[InferenceConfig] = None,
) -> None:
if inference is not None:
if inference.model.name != orchestrator.model.name:
raise ValueError(
f"Inference model name ({inference.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. Please specify the same model name for both."
)
return
if trainer.model.name.startswith("Jackmin108/"): # The TT MoE models will have a different name on the orchestrator
return
if trainer.model.name != orchestrator.model.name:
@@ -41,11 +48,6 @@ def validate_shared_model_name(
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. Please specify the same model name for both."
)
if inference and inference.model.name != orchestrator.model.name:
raise ValueError(
f"Inference model name ({inference.model.name}) and orchestrator model name ({orchestrator.model.name}. Please specify the same model name for both."
)
def validate_shared_output_dir(
trainer: TrainerConfig,
+38 -1
View File
@@ -5,6 +5,8 @@ This module provides a single source of truth for supported VLM models.
import fnmatch
from transformers.configuration_utils import PretrainedConfig
# Whitelist of supported VLM model patterns (supports wildcards)
# Add new patterns here as they are tested and supported
SUPPORTED_VLM_PATTERNS = [
@@ -12,9 +14,35 @@ SUPPORTED_VLM_PATTERNS = [
"Qwen/Qwen3.5*",
]
DEFAULT_LAYER_PREFIX = "model.layers."
# Per-VLM registry: model_type -> layer key prefix.
# VLM models nest the text decoder under a different prefix
# (e.g. 'model.language_model.layers.' instead of 'model.layers.').
# Add new VLM model types here — this is the single source of truth.
VLM_REGISTRY: dict[str, str] = {
"qwen3_vl": "model.language_model.layers.",
"qwen3_5": "model.language_model.layers.",
"qwen3_5_moe": "model.language_model.layers.",
}
# Derived from the registry — used by is_vlm_config()
SUPPORTED_VLM_MODEL_TYPES = set(VLM_REGISTRY)
def get_layer_prefix(model_config: PretrainedConfig) -> str:
"""Return the layer key prefix for a model config.
VLM models nest their text decoder under a different prefix
(e.g. 'model.language_model.layers.') while standard decoder
models use 'model.layers.'.
"""
model_type = getattr(model_config, "model_type", None)
return VLM_REGISTRY.get(model_type, DEFAULT_LAYER_PREFIX)
def is_vlm_model(model_name: str) -> bool:
"""Check if a model is a supported vision-language model.
"""Check if a model is a supported vision-language model by name pattern.
Args:
model_name: The model name or path (e.g., "Qwen/Qwen3-VL-4B-Instruct")
@@ -24,3 +52,12 @@ def is_vlm_model(model_name: str) -> bool:
"""
model_name_lower = model_name.lower()
return any(fnmatch.fnmatch(model_name_lower, pattern.lower()) for pattern in SUPPORTED_VLM_PATTERNS)
def is_vlm_config(model_config: PretrainedConfig) -> bool:
"""Check if a loaded model config is a VLM by its model_type.
This catches VLMs loaded from local paths where the name doesn't match
the hub patterns.
"""
return getattr(model_config, "model_type", None) in SUPPORTED_VLM_MODEL_TYPES
+13 -14
View File
@@ -22,6 +22,7 @@ TIMEOUT = 15 * 60 # 15 minutes
# Note: I would prefer 5% but massed compute A600s seem to be slower than hyperstack A600s (which is the baseline)
METRIC_TOLERANCE = 0.1 # 10% tolerance for mfu, throughput, step_time
MEMORY_TOLERANCE = 0.01 # 1% tolerance for peak memory
TOKEN_CHUNK_SIZE = "1024"
# Baseline files for the Qwen3-0.6B RL benchmark
BASELINE_FILE_1GPU = Path(
@@ -89,8 +90,8 @@ def benchmark_process_1gpu(
str(benchmark_output_file_1gpu),
"--timeout",
str(TIMEOUT - 5 * 60), # Leave 5 min buffer
"--fused-lm-head-chunk-size",
"8192",
"--fused-lm-head-token-chunk-size",
TOKEN_CHUNK_SIZE,
]
return run_process(cmd, timeout=TIMEOUT, env={"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True"})
@@ -122,8 +123,8 @@ def benchmark_process_4gpu(
str(benchmark_output_file_4gpu),
"--timeout",
str(TIMEOUT - 5 * 60), # Leave 5 min buffer
"--fused-lm-head-chunk-size",
"8192",
"--fused-lm-head-token-chunk-size",
TOKEN_CHUNK_SIZE,
]
return run_process(cmd, timeout=TIMEOUT, env={"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True"})
@@ -168,16 +169,15 @@ def benchmark_metrics_4gpu(benchmark_process_4gpu: ProcessResult, benchmark_outp
def test_peak_memory_within_tolerance_1gpu(benchmark_metrics_1gpu: dict, baseline_metrics_1gpu: dict):
"""Test that peak memory usage is within 1% of the baseline (1-GPU)."""
"""Test that peak memory usage does not exceed the baseline by more than 1% (1-GPU)."""
actual_memory = benchmark_metrics_1gpu["peak_memory"]["gib"]
expected_memory = baseline_metrics_1gpu["peak_memory"]["gib"]
lower_bound = expected_memory * (1 - MEMORY_TOLERANCE)
upper_bound = expected_memory * (1 + MEMORY_TOLERANCE)
assert lower_bound <= actual_memory <= upper_bound, (
f"Peak memory out of tolerance! Expected {expected_memory:.4f} GiB ± 1%, got {actual_memory:.4f} GiB. "
f"Acceptable range: [{lower_bound:.4f}, {upper_bound:.4f}] GiB"
assert actual_memory <= upper_bound, (
f"Peak memory regression! Expected at most {expected_memory:.4f} GiB + 1%, got {actual_memory:.4f} GiB. "
f"Upper bound: {upper_bound:.4f} GiB"
)
@@ -229,16 +229,15 @@ def test_step_time_within_tolerance_1gpu(benchmark_metrics_1gpu: dict, baseline_
def test_peak_memory_within_tolerance_4gpu(benchmark_metrics_4gpu: dict, baseline_metrics_4gpu: dict):
"""Test that peak memory usage is within 1% of the baseline (4-GPU)."""
"""Test that peak memory usage does not exceed the baseline by more than 1% (4-GPU)."""
actual_memory = benchmark_metrics_4gpu["peak_memory"]["gib"]
expected_memory = baseline_metrics_4gpu["peak_memory"]["gib"]
lower_bound = expected_memory * (1 - MEMORY_TOLERANCE)
upper_bound = expected_memory * (1 + MEMORY_TOLERANCE)
assert lower_bound <= actual_memory <= upper_bound, (
f"Peak memory out of tolerance! Expected {expected_memory:.4f} GiB ± 1%, got {actual_memory:.4f} GiB. "
f"Acceptable range: [{lower_bound:.4f}, {upper_bound:.4f}] GiB"
assert actual_memory <= upper_bound, (
f"Peak memory regression! Expected at most {expected_memory:.4f} GiB + 1%, got {actual_memory:.4f} GiB. "
f"Upper bound: {upper_bound:.4f} GiB"
)
+129
View File
@@ -0,0 +1,129 @@
from pathlib import Path
from typing import Callable
import pytest
from prime_rl.trainer.weights import load_state_dict
from tests.conftest import ProcessResult
from tests.utils import check_loss_goes_down, strip_escape_codes
pytestmark = [pytest.mark.slow, pytest.mark.gpu]
TIMEOUT = 300 # 5 minutes
def assert_adapter_checkpoint(adapter_dir: Path) -> None:
assert (adapter_dir / "adapter_config.json").exists()
state_dict = load_state_dict(adapter_dir)
assert state_dict
assert all(".0.weight" not in key for key in state_dict)
assert any(key.endswith("lora_A.weight") for key in state_dict)
assert all(key.startswith("base_model.model.") for key in state_dict)
@pytest.fixture(scope="module")
def wandb_name(branch_name: str) -> str:
"""Fixture for W&B name for SFT LoRA CI integration tests."""
return f"test-sft-lora-{branch_name}"
@pytest.fixture(scope="module")
def sft_lora_process(
run_process: Callable[..., ProcessResult],
wandb_project: str,
wandb_name: str,
output_dir: Path,
) -> ProcessResult:
"""Fixture for running SFT LoRA CI integration test"""
cmd = [
"uv",
"run",
"torchrun",
"--local-ranks-filter",
"0",
"--nproc-per-node",
"2",
"src/prime_rl/trainer/sft/train.py",
"@",
"configs/ci/integration/sft_lora/start.toml",
"--wandb.project",
wandb_project,
"--wandb.name",
wandb_name,
"--output-dir",
output_dir.as_posix(),
]
return run_process(cmd, timeout=TIMEOUT)
@pytest.fixture(scope="module")
def sft_lora_resume_process(
sft_lora_process, # Resume training can only start when regular SFT LoRA process is finished
run_process: Callable[..., ProcessResult],
wandb_project: str,
wandb_name: str,
output_dir: Path,
) -> ProcessResult:
"""Fixture for resuming SFT LoRA CI integration test"""
wandb_name += "-resume"
cmd = [
"uv",
"run",
"torchrun",
"--local-ranks-filter",
"0",
"--nproc-per-node",
"2",
"src/prime_rl/trainer/sft/train.py",
"@",
"configs/ci/integration/sft_lora/resume.toml",
"--wandb.project",
wandb_project,
"--wandb.name",
wandb_name,
"--output-dir",
output_dir.as_posix(),
]
return run_process(cmd, timeout=TIMEOUT)
def test_no_error(sft_lora_process: ProcessResult):
"""Tests that the SFT LoRA process does not fail."""
assert sft_lora_process.returncode == 0, f"Process has non-zero return code ({sft_lora_process})"
def test_loss_goes_down(sft_lora_process: ProcessResult, output_dir: Path):
"""Tests that the loss goes down in the SFT LoRA process"""
trainer_log_path = output_dir / "logs" / "trainer" / "rank_0.log"
print(f"Checking trainer path in {trainer_log_path}")
with open(trainer_log_path, "r") as f:
trainer_stdout = strip_escape_codes(f.read()).splitlines()
check_loss_goes_down(trainer_stdout)
def test_adapter_checkpoint_written(sft_lora_process: ProcessResult, output_dir: Path):
"""Tests that the adapter checkpoint is written with valid PEFT-compatible keys."""
adapter_dir = output_dir / "weights" / "step_10" / "lora_adapters"
assert_adapter_checkpoint(adapter_dir)
def test_no_error_resume(sft_lora_resume_process: ProcessResult):
"""Tests that the SFT LoRA resume process does not fail."""
assert sft_lora_resume_process.returncode == 0, f"Process has non-zero return code ({sft_lora_resume_process})"
def test_loss_goes_down_resume(sft_lora_resume_process: ProcessResult, output_dir: Path):
"""Tests that the loss goes down in the SFT LoRA resume process"""
trainer_log_path = output_dir / "logs" / "trainer" / "rank_0.log"
print(f"Checking trainer path in {trainer_log_path}")
with open(trainer_log_path, "r") as f:
trainer_stdout = strip_escape_codes(f.read()).splitlines()
check_loss_goes_down(trainer_stdout)
def test_adapter_checkpoint_written_resume(sft_lora_resume_process: ProcessResult, output_dir: Path):
"""Tests that the adapter checkpoint is written after resuming with valid PEFT-compatible keys."""
adapter_dir = output_dir / "weights" / "step_20" / "lora_adapters"
assert_adapter_checkpoint(adapter_dir)
+6 -6
View File
@@ -15,24 +15,24 @@ def test_default_advantage_fn_simple_mean():
rewards=torch.tensor([[1.0, 0.5, 0.8], [0.2, 0.9, 0.1]]),
completion_lengths=torch.tensor([[10, 12, 8], [15, 11, 9]]),
)
result = default_advantage_fn(inputs, length_weighted_mean=False)
result = default_advantage_fn(inputs)
assert result.advantages.shape == (2, 3)
# Check that mean is subtracted per row
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(2), atol=1e-6)
def test_default_advantage_fn_length_weighted():
def test_default_advantage_fn_gr3_length_shaping():
inputs = AdvantageInputs(
rewards=torch.tensor([[1.0, 0.5, 0.8]]),
completion_lengths=torch.tensor([[10, 20, 10]]),
)
result = default_advantage_fn(inputs, length_weighted_mean=True)
# Length-weighted mean: (1.0*10 + 0.5*20 + 0.8*10) / (10+20+10) = 28/40 = 0.7
expected_baseline = 0.7
expected = torch.tensor([[1.0 - expected_baseline, 0.5 - expected_baseline, 0.8 - expected_baseline]])
result = default_advantage_fn(inputs, length_shaping_alpha=0.33)
expected = torch.tensor([[0.20915856, -0.25799648, 0.04883792]])
assert torch.allclose(result.advantages, expected, atol=1e-6)
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(1), atol=1e-6)
def test_compute_advantages_with_config():
+103 -3
View File
@@ -1,8 +1,34 @@
import asyncio
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock
from unittest.mock import AsyncMock, MagicMock, patch
from prime_rl.orchestrator.scheduler import InflightRolloutInfo, Scheduler
from prime_rl.utils.async_utils import safe_cancel
def make_scheduler() -> Scheduler:
scheduler = Scheduler.__new__(Scheduler)
scheduler.max_async_level = 1
scheduler.strict_async_level = False
scheduler.step = 9
scheduler.ckpt_step = 7
scheduler.config = SimpleNamespace(output_dir=Path("/tmp/prime-rl-test"))
scheduler.logger = MagicMock()
scheduler.checkpoint_ready = asyncio.Event()
scheduler.checkpoint_ready.set()
scheduler.lora_name = None
scheduler.model_name = "test-model"
scheduler.update_weights_time = 0
scheduler.wait_for_ckpt_time = 0
scheduler.inflight_requests = {}
scheduler.groups = {}
scheduler.max_off_policy_steps = 1
scheduler.cancelled_rollouts_count = 0
scheduler.policy_update_lock = asyncio.Lock()
scheduler.inflight_policy_update_task = None
scheduler.update_policy_task = None
return scheduler
def test_update_off_policy_does_not_increment_interleaved_on_policy_tasks():
@@ -18,8 +44,8 @@ def test_update_off_policy_does_not_increment_interleaved_on_policy_tasks():
interleaved_task = None
scheduler.inflight_requests = {
stale_task: InflightRolloutInfo(off_policy_steps=1, client_config=client, group_id=1),
survivor_task: InflightRolloutInfo(off_policy_steps=0, client_config=client, group_id=2),
stale_task: InflightRolloutInfo(off_policy_steps=1, client_config=client, task="test", group_id=1),
survivor_task: InflightRolloutInfo(off_policy_steps=0, client_config=client, task="test", group_id=2),
}
async def drop_group(group_id: int) -> int:
@@ -38,6 +64,7 @@ def test_update_off_policy_does_not_increment_interleaved_on_policy_tasks():
scheduler.inflight_requests[interleaved_task] = InflightRolloutInfo(
off_policy_steps=0,
client_config=client,
task="test",
group_id=3,
)
return len(tasks_to_remove)
@@ -58,3 +85,76 @@ def test_update_off_policy_does_not_increment_interleaved_on_policy_tasks():
await asyncio.sleep(0)
asyncio.run(run())
def test_maybe_update_policy_reuses_inflight_update_after_cancellation():
async def run() -> None:
scheduler = make_scheduler()
started = asyncio.Event()
release = asyncio.Event()
applied_steps: list[int] = []
async def update_weights(weight_dir, lora_name=None, step=0) -> None:
applied_steps.append(step)
started.set()
await release.wait()
scheduler.inference_pool = SimpleNamespace(
update_weights=update_weights,
update_model_name=MagicMock(),
)
scheduler._update_off_policy = AsyncMock()
with (
patch("prime_rl.orchestrator.scheduler.get_latest_ckpt_step", return_value=8),
patch("prime_rl.orchestrator.scheduler.wait_for_path", new=AsyncMock()),
):
first = asyncio.create_task(scheduler.maybe_update_policy())
await started.wait()
await safe_cancel(first)
second = asyncio.create_task(scheduler.maybe_update_policy())
await asyncio.sleep(0)
assert applied_steps == [8]
release.set()
await second
assert applied_steps == [8]
assert scheduler.ckpt_step == 8
asyncio.run(run())
def test_stop_cancels_inflight_policy_update_task():
async def run() -> None:
scheduler = make_scheduler()
started = asyncio.Event()
cancelled = asyncio.Event()
async def update_weights(weight_dir, lora_name=None, step=0) -> None:
started.set()
try:
await asyncio.Future()
finally:
cancelled.set()
scheduler.inference_pool = SimpleNamespace(
update_weights=update_weights,
update_model_name=MagicMock(),
)
scheduler._update_off_policy = AsyncMock()
with (
patch("prime_rl.orchestrator.scheduler.get_latest_ckpt_step", return_value=8),
patch("prime_rl.orchestrator.scheduler.wait_for_path", new=AsyncMock()),
):
scheduler.update_policy_task = asyncio.create_task(scheduler.maybe_update_policy())
await started.wait()
await asyncio.wait_for(scheduler.stop(), timeout=0.2)
assert cancelled.is_set()
assert scheduler.update_policy_task is None
assert scheduler.inflight_policy_update_task is None
asyncio.run(run())
@@ -0,0 +1,140 @@
from unittest.mock import MagicMock
import verifiers as vf
from prime_rl.orchestrator.trajectories import interleave_rollout, pretokenize_rollout_trajectory
class SimpleChatTokenizer:
def __init__(self):
self._tok2id: dict[str, int] = {}
self._next_id = 1
def _id(self, token: str) -> int:
if token not in self._tok2id:
self._tok2id[token] = self._next_id
self._next_id += 1
return self._tok2id[token]
def apply_chat_template(self, messages, add_generation_prompt=False, return_dict=False):
del return_dict
ids = []
for message in messages:
role = message.get("role", "unknown")
ids.append(self._id(f"<|{role}|>"))
content = message.get("content", "")
if isinstance(content, str):
if content:
ids.append(self._id(content))
else:
ids.append(self._id(str(content)))
if add_generation_prompt:
ids.append(self._id("<|assistant|>"))
return ids
def test_interleave_rollout_missing_tokens_returns_none():
output = vf.RolloutOutput(
example_id=1,
trajectory=[
vf.TrajectoryStep(
prompt=[{"role": "user", "content": "U1"}],
completion=[{"role": "assistant", "content": "A1"}],
response=MagicMock(),
tokens=None,
reward=None,
advantage=None,
is_truncated=False,
trajectory_id="1",
extras={},
)
],
sampling_args={"temperature": 1.0},
error=None,
)
assert interleave_rollout(output) is None
def test_pretokenize_rollout_trajectory_for_sft():
tokenizer = SimpleChatTokenizer()
output = vf.RolloutOutput(
example_id=42,
trajectory=[
vf.TrajectoryStep(
prompt=[{"role": "user", "content": "U1"}],
completion=[{"role": "assistant", "content": "A1"}],
response=MagicMock(),
tokens=None,
reward=None,
advantage=None,
is_truncated=False,
trajectory_id="1",
extras={},
),
vf.TrajectoryStep(
prompt=[
{"role": "user", "content": "U1"},
{"role": "assistant", "content": "A1"},
{"role": "user", "content": "U2"},
],
completion=[{"role": "assistant", "content": "A2"}],
response=MagicMock(),
tokens=None,
reward=None,
advantage=None,
is_truncated=False,
trajectory_id="1",
extras={},
),
],
sampling_args={"temperature": 1.0},
error=None,
)
pretokenize_rollout_trajectory(output, tokenizer)
rollouts = interleave_rollout(output)
assert rollouts is not None
assert len(rollouts) == 1
rollout = rollouts[0]
step1_prompt_ids = tokenizer.apply_chat_template(
[{"role": "user", "content": "U1"}],
add_generation_prompt=True,
)
step1_full_ids = tokenizer.apply_chat_template(
[{"role": "user", "content": "U1"}, {"role": "assistant", "content": "A1"}],
add_generation_prompt=False,
)
step2_prompt_ids = tokenizer.apply_chat_template(
[
{"role": "user", "content": "U1"},
{"role": "assistant", "content": "A1"},
{"role": "user", "content": "U2"},
],
add_generation_prompt=True,
)
step2_full_ids = tokenizer.apply_chat_template(
[
{"role": "user", "content": "U1"},
{"role": "assistant", "content": "A1"},
{"role": "user", "content": "U2"},
{"role": "assistant", "content": "A2"},
],
add_generation_prompt=False,
)
prefix_len_1 = len(step1_prompt_ids)
prefix_len_2 = len(step2_prompt_ids)
step1_completion_ids = step1_full_ids[prefix_len_1:]
step2_completion_ids = step2_full_ids[prefix_len_2:]
step1_prefix = step1_prompt_ids + step1_completion_ids
step2_new_prompt_ids = step2_prompt_ids[len(step1_prefix) :]
assert rollout.prompt_ids == step1_prompt_ids
assert rollout.completion_ids == step1_completion_ids + step2_new_prompt_ids + step2_completion_ids
assert rollout.completion_mask == (
[True] * len(step1_completion_ids) + [False] * len(step2_new_prompt_ids) + [True] * len(step2_completion_ids)
)
assert rollout.completion_logprobs == [0.0] * len(rollout.completion_ids)
@@ -10,6 +10,7 @@ from PIL import Image
from prime_rl.orchestrator.trajectories import (
VLMImageCache,
_align_routed_experts,
_deserialize_tool_calls,
_extract_images_from_examples,
_extract_images_from_messages,
_ImageStore,
@@ -29,6 +30,33 @@ def _decode_pixels(pixel_bytes: bytes, shape: list[int]) -> list[list[float]]:
return np.frombuffer(pixel_bytes, dtype=np.float32).reshape(shape).tolist()
def test_deserialize_tool_calls_does_not_inject_missing_key():
messages = [{"role": "assistant", "content": "hello"}]
deserialized = _deserialize_tool_calls(messages)
assert "tool_calls" not in deserialized[0]
def test_deserialize_tool_calls_parses_arguments_when_present():
messages = [
{
"role": "assistant",
"tool_calls": [
{
"id": "1",
"type": "function",
"function": {"name": "lookup", "arguments": '{"x": 1}'},
}
],
}
]
deserialized = _deserialize_tool_calls(messages)
assert deserialized[0]["tool_calls"][0]["function"]["arguments"] == {"x": 1}
@pytest.fixture
def single_step_trajectory_output():
output = vf.RolloutOutput(
+6
View File
@@ -10,6 +10,7 @@ from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.configs.rl import RLConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.trainer import ModelConfig as TrainerModelConfig
from prime_rl.configs.trainer import TrainerConfig
from prime_rl.utils.config import BaseConfig, cli
@@ -148,3 +149,8 @@ def test_cli_overrides_toml(tmp_path):
assert config.nested.lr == 5e-5
# TOML value not overridden by CLI should still be applied (not reverted to class default)
assert config.nested.weight_decay == 0.01
def test_removed_fused_lm_head_chunk_size_field_is_rejected():
with pytest.raises(ValidationError, match="fused_lm_head_chunk_size"):
TrainerModelConfig.model_validate({"fused_lm_head_chunk_size": "auto"})
@@ -563,7 +563,7 @@ class AfmoeModel(AfmoePreTrainedModel):
class AfmoeForCausalLM(AfmoePreTrainedModel, GenerationMixin):
_tied_weights_keys = ["lm_head.weight"]
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
@@ -0,0 +1,62 @@
import torch
from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import convert_tt_layer_to_vllm_kernel
def _build_prime_layer_state(layer_idx: int = 0) -> dict[str, torch.Tensor]:
prefix = f"model.layers.{layer_idx}"
return {
f"{prefix}.self_attn.q_a_proj.weight": torch.randn(4, 6),
f"{prefix}.self_attn.kv_a_proj_with_mqa.weight": torch.randn(3, 6),
f"{prefix}.self_attn.q_b_proj.weight": torch.randn(5, 6),
f"{prefix}.self_attn.kv_b_proj.weight": torch.randn(7, 6),
f"{prefix}.self_attn.o_proj.weight": torch.randn(6, 5),
f"{prefix}.self_attn.indexer.wq_b.weight": torch.randn(4, 6),
f"{prefix}.self_attn.indexer.wk.weight": torch.randn(4, 6),
f"{prefix}.self_attn.indexer.k_norm.weight": torch.randn(6),
f"{prefix}.self_attn.indexer.k_norm.bias": torch.randn(6),
f"{prefix}.self_attn.indexer.weights_proj.weight": torch.randn(2, 6),
f"{prefix}.mlp.gate_proj.weight": torch.randn(8, 6),
f"{prefix}.mlp.up_proj.weight": torch.randn(8, 6),
f"{prefix}.mlp.down_proj.weight": torch.randn(6, 8),
f"{prefix}.mlp.router.gate.weight": torch.randn(4, 6),
f"{prefix}.mlp.expert_bias": torch.randn(4),
f"{prefix}.mlp.experts.w1": torch.randn(2, 3, 6),
f"{prefix}.mlp.experts.w2": torch.randn(2, 6, 3),
f"{prefix}.mlp.experts.w3": torch.randn(2, 3, 6),
f"{prefix}.mlp.shared_expert.w1": torch.randn(1, 3, 6),
f"{prefix}.mlp.shared_expert.w2": torch.randn(1, 6, 3),
f"{prefix}.mlp.shared_expert.w3": torch.randn(1, 3, 6),
}
def test_convert_tt_layer_to_vllm_kernel_no_fp8():
state = _build_prime_layer_state()
out = convert_tt_layer_to_vllm_kernel(state, layer_idx=0, quantize_fp8=False)
assert "model.layers.0.self_attn.fused_qkv_a_proj.weight" in out
assert out["model.layers.0.self_attn.fused_qkv_a_proj.weight"].shape == (7, 6)
assert "model.layers.0.mlp.gate_up_proj.weight" in out
assert out["model.layers.0.mlp.gate_up_proj.weight"].shape == (16, 6)
assert "model.layers.0.mlp.experts.w13_weight" in out
assert out["model.layers.0.mlp.experts.w13_weight"].shape == (2, 6, 6)
assert "model.layers.0.mlp.experts.w2_weight" in out
assert out["model.layers.0.mlp.experts.w2_weight"].shape == (2, 6, 3)
assert "model.layers.0.mlp.gate.weight" in out
assert "model.layers.0.mlp.gate.e_score_correction_bias" in out
def test_convert_tt_layer_to_vllm_kernel_with_fp8():
state = _build_prime_layer_state()
out = convert_tt_layer_to_vllm_kernel(state, layer_idx=0, quantize_fp8=True)
assert out["model.layers.0.self_attn.fused_qkv_a_proj.weight"].dtype == torch.float8_e4m3fn
assert out["model.layers.0.self_attn.fused_qkv_a_proj.weight_scale_inv"].dtype == torch.float32
assert out["model.layers.0.mlp.experts.w13_weight"].dtype == torch.float8_e4m3fn
assert out["model.layers.0.mlp.experts.w13_weight_scale_inv"].dtype == torch.float32
assert out["model.layers.0.mlp.experts.w2_weight"].dtype == torch.float8_e4m3fn
assert out["model.layers.0.mlp.experts.w2_weight_scale_inv"].dtype == torch.float32
+135
View File
@@ -0,0 +1,135 @@
import pytest
import torch
from transformers import Qwen3_5MoeForCausalLM as HFQwen3_5MoeForCausalLM
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeForCausalLM as PrimeRLQwen3_5MoeForCausalLM
from prime_rl.utils.utils import default_dtype
pytestmark = [pytest.mark.gpu]
def get_model_pairs():
config = Qwen3_5MoeConfig(
vocab_size=256,
hidden_size=256,
num_hidden_layers=4,
num_attention_heads=4,
num_key_value_heads=2,
head_dim=64,
moe_intermediate_size=128,
shared_expert_intermediate_size=128,
num_experts=8,
num_experts_per_tok=2,
max_position_embeddings=512,
rms_norm_eps=1e-6,
linear_conv_kernel_dim=4,
linear_key_head_dim=32,
linear_value_head_dim=32,
linear_num_key_heads=4,
linear_num_value_heads=8,
use_grouped_mm=False,
)
config._attn_implementation = "sdpa"
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFQwen3_5MoeForCausalLM._from_config(config)
prime_model = PrimeRLQwen3_5MoeForCausalLM._from_config(config)
with torch.no_grad():
state_dict = hf_model.state_dict()
prime_state_keys = prime_model.state_dict().keys()
prime_model.convert_to_prime(state_dict)
prime_model.load_state_dict(state_dict)
inject_prime_lm_head(prime_model, chunk_size=None)
assert set(prime_state_keys) - set(state_dict.keys()) == set()
return hf_model, prime_model
def test_qwen3_5_moe():
hf_model, prime_model = get_model_pairs()
with torch.device("cuda"), default_dtype(torch.float32):
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
position_ids = torch.arange(1, 101).unsqueeze(0)
hf_output = hf_model(input_ids, position_ids=position_ids)
prime_output = prime_model(input_ids, position_ids=position_ids)
hf_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
def test_qwen3_5_moe_roundtrip():
"""Verify HF → PrimeRL → HF weight conversion is lossless at the state_dict level."""
hf_model, prime_model = get_model_pairs()
# Get original HF state_dict and the PrimeRL-converted version
original_hf_sd = hf_model.state_dict()
prime_sd = prime_model.state_dict()
# Convert PrimeRL → per-expert HF format
converted_hf_sd = PrimeRLQwen3_5MoeForCausalLM.convert_to_hf(dict(prime_sd))
# Also convert original HF (fused) to per-expert format for comparison
# First convert original HF → PrimeRL, then back to per-expert HF
orig_prime_sd = dict(original_hf_sd)
PrimeRLQwen3_5MoeForCausalLM.convert_to_prime(orig_prime_sd)
orig_roundtripped = dict(orig_prime_sd)
PrimeRLQwen3_5MoeForCausalLM.convert_to_hf(orig_roundtripped)
# All non-expert keys should match exactly, expert keys should match after roundtrip
for key in orig_roundtripped:
assert key in converted_hf_sd, f"Missing key: {key}"
assert torch.equal(orig_roundtripped[key], converted_hf_sd[key]), f"Mismatch at {key}"
def test_qwen3_5_moe_router_replay():
"""When routed_experts are provided, the model uses them instead of computing routing."""
_, prime_model = get_model_pairs()
with torch.device("cuda"), default_dtype(torch.float32):
input_ids = torch.randint(0, prime_model.config.vocab_size, (1, 100))
position_ids = torch.arange(1, 101).unsqueeze(0)
out_normal = prime_model(input_ids, position_ids=position_ids)
num_layers = prime_model.config.num_hidden_layers
topk = prime_model.config.num_experts_per_tok
routed_experts = torch.randint(0, prime_model.config.num_experts, (1, 100, num_layers, topk), device="cuda")
prime_model.zero_grad()
out_replay = prime_model(input_ids, position_ids=position_ids, routed_experts=routed_experts)
assert out_replay["logits"].shape == out_normal["logits"].shape
out_replay["logits"].sum().backward()
assert prime_model.model.embed_tokens.weight.grad is not None
def test_qwen3_5_moe_cp_patching():
"""Verify substitute_ring_attn patches Qwen3_5MoeGatedFlashAttention._compute_attention."""
from unittest.mock import MagicMock
from prime_rl.trainer.models.layers.attn import substitute_ring_attn
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
original_method = Qwen3_5MoeGatedFlashAttention._compute_attention
mock_group = MagicMock()
substitute_ring_attn(process_group=mock_group, heads_k_stride=1)
assert Qwen3_5MoeGatedFlashAttention._compute_attention is not original_method
# Restore to avoid polluting other tests
Qwen3_5MoeGatedFlashAttention._compute_attention = original_method
if __name__ == "__main__":
test_qwen3_5_moe()
@@ -0,0 +1,215 @@
import pytest
import torch
from transformers import AutoConfig
from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import (
Qwen3_5MoeForConditionalGeneration as HFQwen3_5MoeVLM,
)
from prime_rl.trainer.model import can_reinit_empty_buffers
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeForCausalLM
from prime_rl.utils.utils import default_dtype
pytestmark = [pytest.mark.gpu]
def _tiny_vlm_config():
"""HF composite config shrunk for unit testing."""
config = AutoConfig.from_pretrained("Qwen/Qwen3.5-35B-A3B", trust_remote_code=True, attn_implementation="sdpa")
config.use_cache = False
tc = config.text_config
tc.vocab_size = 256
tc.hidden_size = 256
tc.num_hidden_layers = 2
tc.num_attention_heads = 4
tc.num_key_value_heads = 2
tc.head_dim = 64
tc.moe_intermediate_size = 128
tc.shared_expert_intermediate_size = 128
tc.num_experts = 4
tc.num_experts_per_tok = 2
tc.max_position_embeddings = 512
tc.linear_key_head_dim = 32
tc.linear_value_head_dim = 32
tc.linear_num_key_heads = 4
tc.linear_num_value_heads = 8
tc.use_cache = False
vc = config.vision_config
vc.depth = 2
vc.hidden_size = 128
vc.intermediate_size = 256
vc.num_heads = 4
vc.out_hidden_size = tc.hidden_size
# Special token IDs must fit within the tiny vocab
config.image_token_id = 250
config.video_token_id = 251
config.vision_start_token_id = 252
config.vision_end_token_id = 253
return config
def _make_image_inputs(config, device="cuda", dtype=torch.float32):
"""Create minimal image inputs matching the vision config."""
vc = config.vision_config
patch_dim = vc.in_channels * vc.temporal_patch_size * vc.patch_size * vc.patch_size
image_grid_thw = torch.tensor([[1, 2, 2]], device=device)
num_patches = int(image_grid_thw.prod().item())
pixel_values = torch.randn(num_patches, patch_dim, device=device, dtype=dtype)
num_image_tokens = num_patches // (vc.spatial_merge_size**2)
return pixel_values, image_grid_thw, num_image_tokens
def test_vlm_forward():
"""Custom VLM produces logits for both text-only and multimodal inputs."""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.float32):
model = Qwen3_5MoeForCausalLM(config)
inject_prime_lm_head(model)
vocab = config.text_config.vocab_size
# Text-only (avoid special token range 250-253)
input_ids = torch.randint(0, 200, (1, 20), device="cuda")
position_ids = torch.arange(1, 21, device="cuda").unsqueeze(0)
out_text = model(input_ids=input_ids, position_ids=position_ids)
assert out_text["logits"].shape == (1, 20, vocab)
# Multimodal
pixel_values, image_grid_thw, n_img_tokens = _make_image_inputs(config)
text_part = torch.randint(0, 200, (1, 10), device="cuda")
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
input_ids_mm = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
out_mm = model(input_ids=input_ids_mm, pixel_values=pixel_values, image_grid_thw=image_grid_thw)
assert out_mm["logits"].shape == (1, input_ids_mm.shape[1], vocab)
def test_vlm_backward():
"""Gradients flow through both vision scatter and text model."""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.float32):
model = Qwen3_5MoeForCausalLM(config)
inject_prime_lm_head(model)
pixel_values, image_grid_thw, n_img_tokens = _make_image_inputs(config)
text_part = torch.randint(0, 200, (1, 10), device="cuda")
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
input_ids = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
out = model(input_ids=input_ids, pixel_values=pixel_values, image_grid_thw=image_grid_thw)
out["logits"].sum().backward()
assert model.model.language_model.embed_tokens.weight.grad is not None
assert model.model.visual.patch_embed.proj.weight.grad is not None
def test_vlm_weight_load_from_hf():
"""Weights from HF VLM checkpoint load correctly into custom VLM after conversion.
Text model numerical match is already validated by test_qwen3_5_moe.py::test_qwen3_5_moe.
This test verifies that VLM weight conversion + loading produces a working model.
"""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFQwen3_5MoeVLM._from_config(config)
prime_model = Qwen3_5MoeForCausalLM(config)
# Copy weights: HF -> PrimeRL (with MoE conversion)
with torch.no_grad():
hf_sd = hf_model.state_dict()
prime_model.convert_to_prime(hf_sd)
prime_model.load_state_dict(hf_sd)
inject_prime_lm_head(prime_model)
# Verify vision encoder weights match exactly (should be untouched by conversion)
for name, param in hf_model.model.visual.named_parameters():
prime_param = dict(prime_model.model.visual.named_parameters())[name]
assert torch.equal(param, prime_param), f"Vision weight mismatch: {name}"
# Verify model produces output after weight loading
input_ids = torch.randint(0, 200, (1, 20), device="cuda")
position_ids = torch.arange(1, 21, device="cuda").unsqueeze(0)
out = prime_model(input_ids=input_ids, position_ids=position_ids)
assert out["logits"].shape[2] == config.text_config.vocab_size
assert not torch.isnan(out["logits"]).any()
def test_vlm_weight_roundtrip():
"""HF -> PrimeRL -> HF weight conversion is lossless (vision keys untouched, text keys converted)."""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFQwen3_5MoeVLM._from_config(config)
hf_sd = hf_model.state_dict()
original_vision_key = "model.visual.blocks.0.mlp.linear_fc1.weight"
original_vision_weight = hf_sd[original_vision_key].clone()
# HF -> PrimeRL
prime_sd = dict(hf_sd)
Qwen3_5MoeForCausalLM.convert_to_prime(prime_sd)
assert any("language_model" in k and "mlp.experts.w1" in k for k in prime_sd)
assert original_vision_key in prime_sd
# PrimeRL -> HF
roundtripped = dict(prime_sd)
Qwen3_5MoeForCausalLM.convert_to_hf(roundtripped)
# Original HF also needs roundtrip for expert format normalization
orig_rt = dict(hf_sd)
Qwen3_5MoeForCausalLM.convert_to_prime(orig_rt)
Qwen3_5MoeForCausalLM.convert_to_hf(orig_rt)
for key in orig_rt:
assert key in roundtripped, f"Missing key: {key}"
assert torch.equal(orig_rt[key], roundtripped[key]), f"Mismatch at {key}"
# Vision weights preserved through the whole roundtrip
assert torch.equal(roundtripped[original_vision_key], original_vision_weight)
def test_vlm_router_replay():
"""routed_experts bypasses router computation in VLM multimodal forward."""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.float32):
model = Qwen3_5MoeForCausalLM(config)
inject_prime_lm_head(model)
vocab = config.text_config.vocab_size
pixel_values, image_grid_thw, n_img_tokens = _make_image_inputs(config)
text_part = torch.randint(0, 200, (1, 10), device="cuda")
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
input_ids = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
seq_len = input_ids.shape[1]
num_layers = config.text_config.num_hidden_layers
topk = config.text_config.num_experts_per_tok
routed_experts = torch.randint(0, config.text_config.num_experts, (1, seq_len, num_layers, topk), device="cuda")
out = model(
input_ids=input_ids, pixel_values=pixel_values, image_grid_thw=image_grid_thw, routed_experts=routed_experts
)
assert out["logits"].shape == (1, seq_len, vocab)
out["logits"].sum().backward()
assert model.model.language_model.embed_tokens.weight.grad is not None
def test_vlm_meta_device_and_buffer_reinit():
"""Model can be created on meta device and buffers reinitialized."""
config = _tiny_vlm_config()
with torch.device("meta"):
model = Qwen3_5MoeForCausalLM.from_config(config)
assert can_reinit_empty_buffers(model)
model.to_empty(device="cuda")
model.init_buffers_post_meta()
lm_inv = model.model.language_model.rotary_emb.inv_freq
vis_inv = model.model.visual.rotary_pos_emb.inv_freq
assert lm_inv.device.type == "cuda"
assert vis_inv.device.type == "cuda"
assert lm_inv.abs().sum() > 0
assert vis_inv.abs().sum() > 0

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