Compare commits

...
Author SHA1 Message Date
56a6c5fea6 fix(trainer): don't resolve Hub envs when parsing orchestrator configs (#3096)
* fix(trainer): don't resolve Hub envs when parsing orchestrator configs

discover_runs() builds OrchestratorConfig to read training-relevant fields, but
constructing a v1 env config eagerly resolves (imports/installs) its taskset/
harness plugins from the Environments Hub. On the trainer that 404s for private
hub envs (taskset.id = owner/name@version) — the trainer has no Hub credentials —
so get_orchestrator_config() returns None and the run is silently skipped.

Parse under verifiers' skip_plugin_install contextvar so the trainer never
touches the Hub; the env server still installs the plugin at runtime.

Depends on verifiers exposing `skip_plugin_install` — bump deps/verifiers to a
commit that includes it before this lands.

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

* chore(trainer): sort imports to satisfy ruff isort (I001)

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 12:51:32 -07:00
HubertandGitHub d69dbb8da4 feat(cp): context parallelism for hybrid + VLM SFT (#3099)
* feat(cp): context parallelism for hybrid + VLM SFT

Unify model CP setup and make packed-boundary metadata CP-aware:

- setup_model_cp replaces setup_hybrid_cp/setup_nemotron_h_cp: models
  owning linear-attention/Mamba layers expose
  set_context_parallel_attributes (dense + MoE Qwen3.5, NemotronH) and
  wire their own layers; hybrid models without the hook are rejected
  instead of silently misconfigured.
- seq_lens stays global under CP: documents can straddle the shard
  cut, so input_ids/position_ids shard per rank while seq_lens keeps
  the full pre-shard boundaries, flagged via seq_lens_are_global
  through forward() / prime_forward_kwargs into both Qwen3.5 models.
  A cu_seqlens_are_global provenance flag rides along to fla's
  GatedDeltaNet instead of reading cu_seqlens back (which cost one
  CPU-GPU sync per linear-attention layer per microbatch); the CP
  conv path switches to fla's causal_conv1d with a CP context so conv
  state passes between ranks with document-boundary resets.
- VLM CP defers sharding to the model: the vision encoder and the
  image-embed merge see the full sequence, then the root forward
  shards embeds/positions (shard_position_ids_for_cp handles 3D
  MRoPE) and updates ulysses attention params from global seq_lens.
  The SFT trainer skips pre-sharding for MRoPE batches; the vision
  encoder is pinned to SDPA under CP.
- shard_for_cp validates divisibility (uneven shards deadlock ulysses
  all-to-all) and CatDataset's seq_len padding guarantees it; the
  LoRA token count follows the sharded loss_mask.
- Qwen3.5 CP requires the custom implementation (the HF impl has no
  set_context_parallel_attributes); rejected in get_model.
2026-07-20 23:53:42 -07:00
samsjaandGitHub 67ba2ff986 fix(ci): increase GPU integration test timeouts to reduce flakiness (#3100)
The GPU integration tests have been failing intermittently on main since
the verifiers re-pin (d085605b) added per-call tracing overhead. The
root cause is tight timeouts that are now occasionally exceeded:

- reverse_text_multi_run: 300s timeout for waiting on Step 11 with 3
  concurrent orchestrators contending for 2 inference GPUs → 600s
- alphabet_sort: 900s for 10 steps that can each take 2+ min on
  contended runners → 1200s
- reverse_text_rl_opd: 600s despite ~8m orchestrator + cleanup → 900s
- reverse_text & reverse_text_rl_sft: 600s → 900s

All remain within the 60-min workflow timeout.
2026-07-21 08:26:55 +02:00
HubertandGitHub 0af5506215 feat(sft): multimodal (VLM) SFT (#3075)
* feat(sft): multimodal (VLM) SFT

Renderer-produced multimodal samples flow end to end through SFT:

- SFTDataset keeps the renderer's MultiModalData: image-safe truncation
  (never cuts inside a placeholder run, drops truncated-out images, and
  skips samples whose EOS was truncated away), mm_token_type_ids kept
  aligned through EOS append and causal shift, video inputs rejected
  explicitly. _flatten_mm_items folds per-image processor outputs into
  model-forward kwargs (pixel_values, image_grid_thw, ...).
- Cat packing concatenates mm_kwargs across samples in a pack and
  represents text-only spans as zeros in mm_token_type_ids; stack
  bucketing emits multimodal samples solo. Collates move mm tensors to
  CUDA and keep packed rows batch-size 1.
- Local data_files normalization wraps string message content into
  typed content blocks under a multimodal flag so Arrow can unify
  text and image rows.
- setup_processor loads the AutoProcessor and attaches it to the
  renderer; VLM SFT fails fast without one; weight checkpoints save
  the processor alongside the tokenizer.
- Dense Qwen3.5 gains the composite VLM body (HF vision encoder +
  custom text model) with MRoPE positions from mm_token_type_ids and
  registers in _CUSTOM_VLM_MAPPING; VLM training requires a custom
  PrimeRL implementation. Both dense and MoE VLM bodies always run
  the vision encoder (dummy input on text-only microbatches, kept in
  the backward graph) for FSDP/EP collective symmetry.
- Config: VLM SFT requires micro_batch_size=1; unfreezing the vision
  encoder is incompatible with LoRA; the renderer-vs-VLM rejection is
  gone (renderers own multimodal tokenization now).
2026-07-20 20:33:51 -07:00
47f97ee1b0 chore: bump verifiers + research-environments to latest main (#3097)
* chore: bump verifiers to latest main

deps/verifiers ab65b6e8d (v0.2.1) -> 1f457da17 (0.2.2.dev6). uv.lock is
unchanged: verifiers is an editable path dep and its dependency set did
not change, so `uv lock` is a no-op.

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

* chore: bump research-environments to latest main

deps/research-environments 85b1527b9 -> e40d32690 (one commit:
refactor(swe): import patch capture from verifiers, #682), pairing with
the verifiers capture_patch/resolve_head utils pulled in by the previous
commit. uv.lock: swelego-v1 / swerebench-v2-v1 / swesmith-v1 0.1.1 ->
0.1.2.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 02:27:55 +02:00
5264eb8984 fix: dp=1 EP replicas launch dense-style (vLLM rejects external-LB args at dp=1) (#3094)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 00:48:45 +02:00
4453922943 chore: bump verifiers to 0.2.1, prime-pydantic-config to 0.4.2, renderers to 0.1.8 (#3095)
* chore: bump verifiers to 0.2.1, prime-pydantic-config to 0.4.2, renderers to 0.1.8

- deps/verifiers -> v0.2.1 (ab65b6e8d), pin verifiers[harbor]>=0.2.1
- deps/pydantic-config -> v0.4.2 (4f5ae37), pin prime-pydantic-config>=0.4.2
- prime-rl-configs: verifiers>=0.2.1, renderers>=0.1.8 (drop dev pins)

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

* chore: bump research-environments to verifiers 0.2.1 pins

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

* fix: drop use_prime_registry from example configs

research-environments#676 removed the field from the swe/terminal
tasksets (the platform now auto-builds images from any docker ref), so
taskset configs no longer accept it.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 14:46:54 -07:00
53 changed files with 1325 additions and 415 deletions
+1 -1
View File
@@ -53,7 +53,7 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
| GLM-5 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8` | yes | ✅ | ✅ |
| Qwen3 MoE (`qwen3_moe`) | `Qwen/Qwen3-30B-A3B`, … | yes | ✅ | ✅ |
| Qwen3.5 MoE (`qwen3_5_moe`) | `Qwen/Qwen3.5-35B-A3B`, … | yes | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#multimodal-training) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#multimodal-training) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ❌ |
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ✅ |
@@ -1,4 +1,4 @@
# Based on configs/multimodal/rl_color_codeword.toml but tuned for CI
# Based on configs/debug/multimodal.toml but tuned for CI.
max_steps = 25
seq_len = 4096
@@ -7,7 +7,7 @@ num_train_gpus = 4
num_infer_gpus = 4
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
name = "Qwen/Qwen3.5-4B"
[model.vlm]
vision_encoder_attr = "model.visual"
@@ -28,6 +28,7 @@ harness = { id = "null", runtime = { type = "subprocess" } }
[trainer]
[trainer.model]
impl = "custom"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
+1 -1
+6 -10
View File
@@ -28,7 +28,7 @@ impl = "custom" # or "hf" to force the HF path
| GLM-5 / GLM-5.2 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8`, `zai-org/GLM-5.2`, `zai-org/GLM-5.2-FP8` | ✅ | ✅ |
| Qwen3 MoE | `Qwen/Qwen3-30B-A3B`, … | ✅ | ✅ |
| Qwen3.5 MoE | `Qwen/Qwen3.5-35B-A3B`, … | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ❌ |
| Laguna | `poolside/Laguna-XS.2` | ✅ | ✅ |
| MiniMax M2 | `MiniMax/MiniMax-M2` | ✅ | ✅ |
| Nemotron H | `nvidia/Nemotron-3-Nano-30B-A3B`, … | ✅ | ❌ |
@@ -72,20 +72,17 @@ The built-in VLM registry covers:
| Family | `model_type` | Vision attr | LM attr |
|---|---|---|---|
| Qwen3-VL | `qwen3_vl` | `model.visual` | `model.language_model` |
| Qwen3-VL MoE | `qwen3_vl_moe` | `model.visual` | `model.language_model` |
| Qwen3.5 | `qwen3_5` | `model.visual` | `model.language_model` |
| Qwen3.5-MoE | `qwen3_5_moe` | `model.visual` | `model.language_model` |
For a model not in the table, look up the attribute paths on the loaded HF model with `model.named_children()` and set them under `[model.vlm]` directly.
### Enabling VLM Mode
Add `[model.vlm]` and bfloat16 dtypes:
```toml
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
name = "Qwen/Qwen3.5-4B"
impl = "custom"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
@@ -97,12 +94,11 @@ language_model_attr = "model.language_model"
The weight-broadcast key prefix is derived as `{language_model_attr}.layers.` automatically.
To add a new model family permanently, append an entry to `VLM_REGISTRY` in `src/prime_rl/utils/vlm.py`.
VLM training requires a registered custom PrimeRL implementation.
### Limitations
- **Vision encoder frozen by default.** Set `freeze_vision_encoder = false` to fine-tune it; in that case it's FSDP-sharded per block. The combination `freeze_vision_encoder = false` + LoRA is rejected by a config validator — LoRA freezes everything non-adapter, so unfreezing the encoder under LoRA would be a silent no-op.
- **No multimodal-safe truncation.** Token sequences are truncated to `seq_len`, but `pixel_values` and `image_grid_thw` pass through unchanged. If a sample's tokens overflow, image tokens may get dropped while image tensors still describe the full image set. Set `seq_len` to cover your longest sample.
- **Vision encoder frozen by default.** The default LoRA targets do not match Qwen3.5 vision modules. Set `freeze_vision_encoder = false` to fine-tune the encoder; this is incompatible with LoRA because LoRA freezes all non-adapter parameters.
- **bfloat16 mandatory.** The trainer config validator refuses any other `optimization_dtype` / `reduce_dtype` for VLMs — vLLM serves VLMs in bfloat16 and a mismatch breaks the importance ratio.
- **Higher KL mismatch with multi-image inputs.** Expect noisier `mismatch_kl` than text-only; this is from minor numerical differences between the trainer's and vLLM's image processing.
- **Images aren't logged to monitors.** Sample logging captures the prompt text but not the actual images.
@@ -160,4 +156,4 @@ salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh'
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
```
The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version. Re-run both commands after every `uv sync`, since the lock pins the wheel.
The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version. Re-run both commands after every `uv sync`, since the lock pins the wheel.
+2 -1
View File
@@ -156,8 +156,9 @@ enable_thinking = false
If a model needs another template control, add it to that model's renderer config in `renderers` (for example a new field on the relevant `*RendererConfig`) and consume it in the renderer implementation.
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `—` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS.
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `<think>` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS, and VLM families such as Qwen3-VL/Qwen3.5.
**VLM training requires a custom PrimeRL implementation.** Training a model with `[model.vlm]` set (SFT or RL) requires `model.impl = "custom"` and only works for models with a registered PrimeRL VLM class (currently Qwen3.5 dense and MoE).
See [Algorithms § Multi-Turn Trajectories](algorithms.md#multi-turn-trajectories) for the full picture.
+2 -2
View File
@@ -99,7 +99,7 @@ thinking_retention = "all"
[[orchestrator.train.env]]
name = "scaleswe"
taskset = { id = "scaleswe-v1", use_prime_registry = true }
taskset = { id = "scaleswe-v1" }
harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
[orchestrator.prime_monitor]
@@ -111,7 +111,7 @@ interval = 20
[[orchestrator.eval.env]]
name = "swebench-verified"
taskset = { id = "swebench-verified-v1", use_prime_registry = true }
taskset = { id = "swebench-verified-v1" }
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
timeout = { rollout = 3600 }
@@ -125,7 +125,6 @@ timeout = { rollout = 3600 }
[orchestrator.eval.env.taskset]
id = "swebench-verified-v1"
use_prime_registry = true
# [[orchestrator.eval.env.taskset.judges]]
# id = "rubric"
+2 -2
View File
@@ -83,7 +83,7 @@ truncate_history_thinking = false
[[orchestrator.train.env]]
name = "scaleswe"
taskset = { id = "scaleswe-v1", use_prime_registry = true }
taskset = { id = "scaleswe-v1" }
harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] } }
[orchestrator.prime_monitor]
@@ -93,7 +93,7 @@ interval = 20
[[orchestrator.eval.env]]
name = "swebench-verified"
taskset = { id = "swebench-verified-v1", use_prime_registry = true }
taskset = { id = "swebench-verified-v1" }
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] } }
timeout = { rollout = 3600 }
+35
View File
@@ -0,0 +1,35 @@
max_steps = 20
[ckpt]
[ckpt.weights]
save_adapter_separately = true
[model]
name = "Qwen/Qwen3.5-0.8B"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
impl = "custom"
[renderer]
name = "auto"
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
freeze_vision_encoder = true
[model.lora]
rank = 16
[model.ac]
freq = 1
[data]
type = "sft"
name = "your-org/your-multimodal-dataset"
batch_size = 1
micro_batch_size = 1
seq_len = 16384
[optim]
lr = 1e-5
+55
View File
@@ -0,0 +1,55 @@
# Multimodal (VLM) SFT on a Mixture-of-Experts model — single 8xH200 node.
max_steps = 1000
dist_timeout_seconds = 3600
[model]
name = "Qwen/Qwen3.6-35B-A3B"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
impl = "custom"
attn = "flash_attention_2"
ep = 8 # keep in sync with deployment.num_gpus
[renderer]
name = "auto"
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
freeze_vision_encoder = true
[model.lora]
rank = 32
alpha = 32
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", "experts"]
# MoE + mode="full" recomputes the router, whose non-deterministic top-k routing
# raises CheckpointError; selective AC excluding routed_experts avoids that.
[model.ac]
mode = "selective"
targets = ["norm", "attn_proj", "linear_attn"]
[data]
type = "sft"
name = "your-org/your-multimodal-dataset"
batch_size = 8
micro_batch_size = 1 # required for VLM SFT
seq_len = 16384
[data.loss_mask]
system = false
user = false
assistant = true
tool = false
[optim]
lr = 1e-5
[ckpt]
interval = 200
[ckpt.weights]
save_adapter_separately = true
[deployment]
type = "single_node"
num_gpus = 8
+3 -3
View File
@@ -6,11 +6,11 @@ readme = "README.md"
requires-python = "~=3.12.0"
dependencies = [
"pydantic>=1.10.13",
"prime-pydantic-config>=0.3.0.dev82",
"renderers>=0.1.8.dev28",
"prime-pydantic-config>=0.4.2",
"renderers>=0.1.8",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.2.0",
"verifiers>=0.2.1",
]
[build-system]
@@ -301,6 +301,31 @@ class SFTConfig(BaseConfig):
raise ValueError("Validation micro batch size must be 1 when CP is enabled")
return self
@model_validator(mode="after")
def vlm_freeze_incompatible_with_lora(self):
if self.model.vlm is not None and not self.model.vlm.freeze_vision_encoder and self.model.lora is not None:
raise ValueError(
"freeze_vision_encoder=false is incompatible with LoRA. "
"LoRA freezes all non-adapter parameters including the vision encoder."
)
return self
@model_validator(mode="after")
def validate_vlm_constraints(self):
if self.model.vlm is None:
return self
if self.model.optimization_dtype != "bfloat16" or self.model.reduce_dtype != "bfloat16":
raise ValueError(
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
)
if self.model.cp > 1 and self.model.cp_style != "ulysses":
raise ValueError("VLM models require cp_style='ulysses' for context parallelism")
if self.data.micro_batch_size != 1:
raise ValueError("VLM SFT requires data.micro_batch_size = 1.")
if self.val is not None and self.val.data.micro_batch_size != 1:
raise ValueError("VLM SFT requires val.data.micro_batch_size = 1.")
return self
@model_validator(mode="after")
def dont_do_massive_traces(self):
if self.trace_path:
@@ -312,15 +337,6 @@ class SFTConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_renderer_vs_vlm(self):
if self.model.vlm is not None:
raise ValueError(
"renderer-only SFT does not support VLMs yet. The renderer tokenizes "
"text-only message dicts client-side and cannot handle image inputs."
)
return self
@model_validator(mode="after")
def validate_lora_adapter_saving(self):
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
@@ -94,7 +94,7 @@ class VLMConfig(BaseConfig):
"""Dotted attribute path to the language model module (e.g. ``model.language_model``)."""
freeze_vision_encoder: bool = True
"""Freeze the vision encoder. When False, it is trainable and FSDP-sharded per-block. No effect with LoRA (LoRA freezes all non-adapter parameters)."""
"""Freeze the vision encoder parameters during training."""
class BaseModelConfig(BaseConfig):
@@ -236,21 +236,19 @@ class ModelConfig(BaseModelConfig):
return self
@model_validator(mode="after")
def cp_only_with_flash_attn(self):
def vlm_only_with_custom_impl(self):
if self.vlm is not None and self.impl != "custom":
raise ValueError("VLM training requires model.impl='custom'")
return self
@model_validator(mode="after")
def validate_cp(self):
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]:
raise ValueError("CP is only supported with flash attention 2, 3, or 4")
if (
self.cp > 1
and self.attn in ("flash_attention_3", "flash_attention_4", "auto")
and self.impl not in ("custom", "auto")
):
# Both ring and ulysses route FA3/FA4 through our custom FlashAttention class:
# ring patches `_compute_attention` with the ring kernel, ulysses patches it with
# the all-to-all wrapper around the FA3/FA4 kernel. The HF path patches
# `_flash_attention_forward` which only wraps FA2.
if self.cp > 1 and self.impl not in ("custom", "auto"):
raise ValueError(
f"CP with {self.attn} requires model.impl='custom' or 'auto' "
"(FA3/FA4 paths are only implemented for the custom model attention class)"
"Context parallelism requires model.impl='custom' or 'auto' "
"(resolved to a custom PrimeRL implementation)"
)
return self
+1 -1
View File
@@ -33,7 +33,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers[harbor]>=0.2.0",
"verifiers[harbor]>=0.2.1",
"renderers",
"dion",
"tilelang>=0.1.8",
@@ -367,12 +367,15 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
for ((d=0; d<INFERENCE_DP_LOCAL; d++)); do
RANK_GPUS=$(seq -s, $((d * INFERENCE_TP)) $((d * INFERENCE_TP + INFERENCE_TP - 1)))
RANK_LOG=$(rank_log "$INFER_NODE_RANK" "$d")
if [ "$INFERENCE_ENABLE_EXPERT_PARALLEL" -eq 1 ]; then
if [ "$INFERENCE_ENABLE_EXPERT_PARALLEL" -eq 1 ] && [ "$INFER_GROUP_DP" -gt 1 ]; then
GLOBAL_DP_RANK=$((RANK_IN_REPLICA * INFERENCE_DP_LOCAL + d))
RANK_EXTRA="{\"data_parallel_rank\": $GLOBAL_DP_RANK, \"data_parallel_address\": \"$DP_ADDR\"}"
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" "$INFER_GROUP_DP" "$INFERENCE_DATA_PARALLEL_RPC_PORT" "$RANK_EXTRA" "" "$RANK_LOG"
else
# Dense: independent single-engine servers (no DP linkage).
# Dense or single-DP-rank EP (dp=1, e.g. EP within one tp=8 group):
# independent single-engine servers. vLLM rejects the external-LB DP
# args when data_parallel_size == 1; enable_expert_parallel in the
# inference config alone shards experts across the TP group.
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" 1 "" "" "" "$RANK_LOG"
fi
done
+8 -1
View File
@@ -18,6 +18,7 @@ from torch.nn import Module
from torch.optim.lr_scheduler import LRScheduler
from torch.optim.optimizer import Optimizer
from torchdata.stateful_dataloader import StatefulDataLoader
from transformers.processing_utils import ProcessorMixin
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.configs.trainer import CheckpointConfig, LoRAConfig, WeightCheckpointConfig
@@ -377,6 +378,7 @@ class WeightCheckpointManager:
lora_state_dict: dict[str, Tensor] | None,
model,
tokenizer: PreTrainedTokenizer,
processor: ProcessorMixin | None = None,
):
"""Save HF-compatible weight checkpoint to a given path."""
if self.world.is_master:
@@ -403,6 +405,10 @@ class WeightCheckpointManager:
gen_config = deepcopy(model.generation_config)
gen_config.use_cache = True
gen_config.save_pretrained(path)
# Processor first: it saves its own (unmodified) tokenizer, which the
# configured tokenizer (pad token, custom chat template) must override.
if processor is not None:
processor.save_pretrained(path)
tokenizer.save_pretrained(path)
if lora_state_dict is not None:
@@ -426,6 +432,7 @@ class WeightCheckpointManager:
step: int,
model: nn.Module,
tokenizer: PreTrainedTokenizer,
processor: ProcessorMixin | None = None,
):
"""Save a HF-compatible weight-only checkpoint for a given step."""
step_path = self.get_step_path(step)
@@ -471,7 +478,7 @@ class WeightCheckpointManager:
self.logger.debug(f"Reverted to HF hub format in {time.perf_counter() - start_time:.2f} seconds")
# Save weight checkpoint on master rank
self.save_to_path(step_path, state_dict, lora_state_dict, model, tokenizer)
self.save_to_path(step_path, state_dict, lora_state_dict, model, tokenizer, processor)
self.mark_stable(step)
bisect.insort(self.ckpt_steps, step)
+1 -2
View File
@@ -162,8 +162,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
)
if not target_modules:
logger.warning("No target modules found for LoRA. Check your target_modules patterns.")
return
raise ValueError(f"No LoRA target modules found for patterns {config.target_modules}.")
for module_name in target_modules:
base_module = _get_module_by_name(model, module_name)
+128 -29
View File
@@ -153,11 +153,38 @@ def _patch_qwen3_5_linear_attn_varlen():
apply_mask_to_padding_states,
)
try:
from fla.modules.convolution import causal_conv1d as fla_causal_conv1d
from fla.ops.cp import build_cp_context
except ImportError:
build_cp_context = None
fla_causal_conv1d = None
if fla_causal_conv1d is not None:
# The CP boundary-state exchange inside fla's conv is not dynamo-traceable;
# graph-break deliberately so the rest of the layer still compiles.
fla_causal_conv1d = torch.compiler.disable(fla_causal_conv1d)
if getattr(Qwen3_5GatedDeltaNet.forward, "_prl_varlen_patched", False):
return
_gdn_orig = Qwen3_5GatedDeltaNet.forward
def _build_cp_context(self, local_seq_len: int, device: torch.device, cu_seqlens=None):
cp_group = getattr(self, "cp_group", None)
if cp_group is None or build_cp_context is None:
return None
global_seq_len = local_seq_len * self.cp_world_size
if cu_seqlens is not None and int(cu_seqlens[-1].item()) == global_seq_len:
global_cu_seqlens = cu_seqlens.to(device=device, dtype=torch.int32)
else:
global_cu_seqlens = torch.tensor([0, global_seq_len], dtype=torch.int32, device=device)
return build_cp_context(
cu_seqlens=global_cu_seqlens,
group=cp_group,
conv1d_kernel_size=self.conv_kernel_size,
)
def _gdn_forward(self, hidden_states, cache_params=None, attention_mask=None, cu_seqlens=None):
if cu_seqlens is None or cache_params is not None:
return _gdn_orig(self, hidden_states, cache_params=cache_params, attention_mask=attention_mask)
@@ -170,7 +197,18 @@ def _patch_qwen3_5_linear_attn_varlen():
b = self.in_proj_b(hidden_states)
a = self.in_proj_a(hidden_states)
if self.causal_conv1d_fn is not None:
cp_context = _build_cp_context(self, seq_len, hidden_states.device, cu_seqlens)
if cp_context is not None and fla_causal_conv1d is not None:
mixed_qkv, _ = fla_causal_conv1d(
x=mixed_qkv.transpose(1, 2),
weight=self.conv1d.weight.squeeze(1),
bias=self.conv1d.bias,
activation=self.activation,
cp_context=cp_context,
)
mixed_qkv = mixed_qkv.transpose(1, 2)
elif self.causal_conv1d_fn is not None:
seg_lens = cu_seqlens[1:] - cu_seqlens[:-1]
seq_idx = torch.repeat_interleave(
torch.arange(seg_lens.numel(), dtype=torch.int32, device=hidden_states.device),
@@ -206,17 +244,29 @@ def _patch_qwen3_5_linear_attn_varlen():
query = query.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
core_attn_out, _ = self.chunk_gated_delta_rule(
query,
key,
value,
g=g,
beta=beta,
initial_state=None,
output_final_state=False,
use_qk_l2norm_in_kernel=True,
cu_seqlens=cu_seqlens,
)
if cp_context is not None:
core_attn_out, _ = self.chunk_gated_delta_rule(
query,
key,
value,
g=g,
beta=beta,
use_qk_l2norm_in_kernel=True,
cu_seqlens=cp_context.cu_seqlens,
cp_context=cp_context,
)
else:
core_attn_out, _ = self.chunk_gated_delta_rule(
query,
key,
value,
g=g,
beta=beta,
initial_state=None,
output_final_state=False,
use_qk_l2norm_in_kernel=True,
cu_seqlens=cu_seqlens,
)
core_attn_out = core_attn_out.reshape(-1, self.head_v_dim)
z = z.reshape(-1, self.head_v_dim)
@@ -348,8 +398,8 @@ def freeze_moe_router(model: nn.Module) -> None:
for param in mlp.router.parameters():
param.requires_grad = False
num_frozen += 1
# HuggingFace implementation: gate attribute (nn.Linear)
elif hasattr(mlp, "gate") and isinstance(mlp.gate, nn.Linear):
# HuggingFace implementation: gate may have been wrapped with LoRA.
elif hasattr(mlp, "gate") and isinstance(mlp.gate, nn.Module):
for param in mlp.gate.parameters():
param.requires_grad = False
num_frozen += 1
@@ -528,6 +578,13 @@ def get_model(
_patch_qwen3_5_text_position_ids()
_patch_qwen3_5_moe_conversion_mapping()
_patch_qwen3_5_linear_attn_varlen()
if is_vlm_arch and config.cp > 1 and config.cp_style == "ulysses":
vision_config = getattr(model_config, "vision_config", None)
if vision_config is not None:
logger.info("Using SDPA for VLM vision encoder under CP")
vision_config._attn_implementation = "sdpa"
if hasattr(vision_config, "_attn_implementation_internal"):
vision_config._attn_implementation_internal = "sdpa"
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"):
@@ -622,6 +679,18 @@ def get_model(
f"but model.impl resolved to 'hf'. Set model.impl='custom' explicitly."
)
if config.cp > 1 and config.impl == "auto" and impl_to_use != "custom":
raise ValueError(
"Context parallelism with model.impl='auto' requires a supported custom PrimeRL implementation, "
"but this architecture resolved to model.impl='hf'."
)
if config.vlm is not None and not (is_vlm_arch and custom_vlm_cls):
raise ValueError(
"VLM training requires a registered custom PrimeRL VLM implementation; "
f"{getattr(model_config, 'model_type', config.name)!r} has none."
)
with device:
if impl_to_use == "custom" and custom_vlm_cls is not None:
model_cls = custom_vlm_cls
@@ -653,10 +722,6 @@ def get_model(
)
logger.debug(f"Loaded model {config.name} in {time.perf_counter() - load_model_start_time:.2f} seconds")
# For VLM models, optionally freeze the vision encoder
if is_vlm_training and config.vlm.freeze_vision_encoder:
freeze_vision_encoder(model, override_attr=config.vlm.vision_encoder_attr)
assert model.lm_head.weight.dtype == dtype, (
f"LM head dtype wasnt loaded correctly {model.lm_head.weight.dtype} != {dtype}"
)
@@ -680,6 +745,23 @@ def setup_tokenizer(config: TokenizerConfig) -> PreTrainedTokenizer:
return tokenizer
def setup_processor(config: ModelConfig):
"""Load an ``AutoProcessor`` for VLM models. Returns ``None`` for text-only models."""
from transformers import AutoProcessor
logger = get_logger()
try:
processor = AutoProcessor.from_pretrained(config.name, trust_remote_code=config.trust_remote_code)
except (ValueError, OSError, KeyError) as e:
logger.debug(f"No AutoProcessor available for {config.name} ({type(e).__name__}); treating as text-only.")
return None
if not (getattr(processor, "image_processor", None) or getattr(processor, "video_processor", None)):
logger.debug(f"AutoProcessor for {config.name} has no image/video processor; treating as text-only.")
return None
logger.info(f"Loaded multimodal processor: {type(processor).__name__}")
return processor
def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims):
mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=DTYPE_MAP[config.reduce_dtype])
offload_policy: OffloadPolicy = CPUOffloadPolicy(pin_memory=True) if config.fsdp_cpu_offload else OffloadPolicy()
@@ -891,7 +973,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
state_dict = model.state_dict()
state_dict = strip_lora_from_state_dict(state_dict)
if model.config.tie_word_embeddings:
del state_dict["lm_head.weight"]
state_dict.pop("lm_head.weight")
dcp_load(
state_dict,
storage_reader=HuggingFaceStorageReader(path=snapshot_path.as_posix()),
@@ -1099,6 +1181,21 @@ def apply_ep(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims)
)
def configure_trainable_parameters(model: nn.Module, config: ModelConfig) -> nn.Module | None:
"""Apply LoRA and identify any vision encoder that must remain frozen."""
frozen_vision_encoder = None
if config.vlm is not None and config.vlm.freeze_vision_encoder:
frozen_vision_encoder = get_vision_encoder(model, override=config.vlm.vision_encoder_attr)
elif config.vlm is None:
frozen_vision_encoder = get_vision_encoder(model)
if frozen_vision_encoder is not None:
get_logger().info("Training a VLM checkpoint on text-only data; freezing the vision encoder")
if config.lora is not None:
apply_lora_to_model(model, config.lora)
return frozen_vision_encoder
def _move_buffers_to_cuda(model: nn.Module, config: ModelConfig) -> None:
"""FSDP CPU offloading only manages parameters, not buffers. Move buffers to CUDA."""
if not config.fsdp_cpu_offload:
@@ -1197,9 +1294,7 @@ def setup_model(
apply_quantization(model, config)
# Apply LoRA before FSDP setup
if config.lora is not None:
apply_lora_to_model(model, config.lora)
frozen_vision_encoder = configure_trainable_parameters(model, config)
if config.freeze_moe_router:
freeze_moe_router(model)
@@ -1222,6 +1317,12 @@ def setup_model(
if config.lora is not None:
freeze_all_except_lora_and_specified(model, config.lora)
if frozen_vision_encoder is not None:
freeze_vision_encoder(
model,
override_attr=config.vlm.vision_encoder_attr if config.vlm is not None else None,
)
# the right order is AC -> Compile -> FSDP
if config.ac is not None:
apply_ac(model, config.ac)
@@ -1273,12 +1374,13 @@ def forward(
# "image_grid_thw": ...} for Qwen3-VL; just {"pixel_values": ...}
# for Gemma3). Passed straight through to ``model(**kwargs)`` so
# the model's HF forward signature is the schema. ``mm_token_type_ids``
# is split out because it's prime-rl-computed (from token ids),
# not a renderer/processor output.
# is split out because it comes from the renderer rather than the processor.
mm_kwargs: dict[str, Tensor] | None = None,
mm_token_type_ids: Int[Tensor, "batch seq"] | None = None,
# True when seq_lens holds the full pre-CP-shard document boundaries
# (kept global because documents can straddle the shard cut).
seq_lens_are_pre_shard: bool = False,
) -> PrimeLmOutput:
# Build kwargs for model forward
kwargs = {
"input_ids": input_ids,
"labels": labels,
@@ -1292,10 +1394,6 @@ def forward(
kwargs.update(mm_kwargs)
if mm_token_type_ids is not None:
kwargs["mm_token_type_ids"] = mm_token_type_ids
# ``position_ids`` for MRoPE families: Qwen3-VL's HF forward
# recomputes 3D positions from ``image_grid_thw`` and breaks if
# given the trainer's pre-computed 1D ``position_ids``. Detect
# via the mm_kwargs shape so we don't enumerate model_types.
if "image_grid_thw" not in mm_kwargs:
kwargs["position_ids"] = position_ids
else:
@@ -1303,6 +1401,7 @@ def forward(
if isinstance(model, PreTrainedModelPrimeRL):
kwargs["seq_lens"] = seq_lens
kwargs["seq_lens_are_pre_shard"] = seq_lens_are_pre_shard
if routed_experts is not None:
kwargs["routed_experts"] = routed_experts
+1
View File
@@ -75,6 +75,7 @@ def supports_custom_impl(model_config: PretrainedConfig) -> bool:
# 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": Qwen3_5ForCausalLM,
"qwen3_5_moe": Qwen3_5MoeForCausalLM,
}
@@ -386,6 +386,7 @@ class AfmoeModel(AfmoePreTrainedModel):
routed_experts: Optional[torch.LongTensor] = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
) -> MoeModelOutputWithPast:
"""
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
@@ -401,7 +402,8 @@ class AfmoeModel(AfmoePreTrainedModel):
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
seq_lens.to(device=inputs_embeds.device),
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
causal_mask_mapping = None
@@ -479,6 +481,7 @@ class AfmoeForCausalLM(AfmoePreTrainedModel, GenerationMixin):
routed_experts: Optional[torch.LongTensor] = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
r"""
@@ -500,6 +503,7 @@ class AfmoeForCausalLM(AfmoePreTrainedModel, GenerationMixin):
inputs_embeds=inputs_embeds,
routed_experts=routed_experts,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
hidden_states = outputs.last_hidden_state
@@ -207,12 +207,15 @@ class Glm4MoeModel(Glm4MoePreTrainedModel):
routed_experts: Optional[torch.LongTensor] = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
) -> BaseModelOutputWithPast:
"""
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
Routed experts for each token in the sequence. Only used for router replay.
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
Per-document lengths of the packed row (PrimeRL packed-batch contract).
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
"""
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
@@ -221,7 +224,8 @@ class Glm4MoeModel(Glm4MoePreTrainedModel):
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
seq_lens.to(device=inputs_embeds.device),
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
@@ -276,11 +280,14 @@ class Glm4MoeForCausalLM(Glm4MoePreTrainedModel, GenerationMixin):
routed_experts: Optional[torch.LongTensor] = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
r"""
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
Per-document lengths of the packed row (PrimeRL packed-batch contract).
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
compatibility — prime-rl asserts `use_cache is None` since training does not
@@ -324,6 +331,7 @@ class Glm4MoeForCausalLM(Glm4MoePreTrainedModel, GenerationMixin):
inputs_embeds=inputs_embeds,
routed_experts=routed_experts,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
hidden_states = outputs.last_hidden_state
@@ -313,11 +313,14 @@ class GlmMoeDsaForCausalLM(GlmMoeDsaPreTrainedModel, GenerationMixin):
# trainer's universal contract.
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
r"""
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
Per-document lengths of the packed row (PrimeRL packed-batch contract).
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
compatibility — prime-rl asserts `use_cache is None` since training does not
@@ -309,11 +309,14 @@ class GptOssForCausalLM(GptOssPreTrainedModel, GenerationMixin):
# seq_lens is accepted to satisfy the trainer's universal contract.
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
r"""
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
Per-document lengths of the packed row (PrimeRL packed-batch contract).
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
temperature (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Per-token temperatures for logprobs/entropy computation when `labels` are provided.
"""
@@ -292,6 +292,7 @@ class LagunaModel(LagunaPreTrainedModel):
routed_experts: torch.LongTensor | None = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
) -> MoeModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
@@ -302,7 +303,8 @@ class LagunaModel(LagunaPreTrainedModel):
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
seq_lens.to(device=inputs_embeds.device),
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
causal_mask_mapping = dict.fromkeys(set(self.config.layer_types), None)
@@ -366,6 +368,7 @@ class LagunaForCausalLM(LagunaPreTrainedModel, GenerationMixin):
routed_experts: torch.LongTensor | None = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
assert use_cache is None, "use_cache is not supported for custom Laguna"
@@ -378,6 +381,7 @@ class LagunaForCausalLM(LagunaPreTrainedModel, GenerationMixin):
inputs_embeds=inputs_embeds,
routed_experts=routed_experts,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
hidden_states = outputs.last_hidden_state
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
@@ -265,12 +265,10 @@ def _patch_model_forward(model: nn.Module) -> None:
if position_ids is None and not is_multimodal:
reference_tensor = input_ids if input_ids is not None else inputs_embeds
position_ids = torch.arange(1, reference_tensor.shape[1] + 1, device=reference_tensor.device).unsqueeze(0)
outputs = self.model(
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
**kwargs,
)
model_kwargs = {"input_ids": input_ids, "position_ids": position_ids, **kwargs}
if inputs_embeds is not None:
model_kwargs["inputs_embeds"] = inputs_embeds
outputs = self.model(**model_kwargs)
hidden_states = outputs.last_hidden_state
# Slice hidden states for logits_to_keep
@@ -183,10 +183,13 @@ class LlamaModel(LlamaPreTrainedModel):
inputs_embeds: Optional[torch.FloatTensor] = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
) -> BaseModelOutputWithPast:
r"""
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
Per-document lengths of the packed row (PrimeRL packed-batch contract).
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
"""
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
@@ -195,7 +198,8 @@ class LlamaModel(LlamaPreTrainedModel):
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
seq_lens.to(device=inputs_embeds.device),
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
@@ -247,11 +251,14 @@ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
temperature: Optional[torch.Tensor] = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
r"""
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
Per-document lengths of the packed row (PrimeRL packed-batch contract).
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
compatibility — prime-rl asserts `use_cache is None` since training does not
@@ -292,6 +299,7 @@ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
position_ids=position_ids,
inputs_embeds=inputs_embeds,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
hidden_states = outputs.last_hidden_state
@@ -168,12 +168,15 @@ class MiniMaxM2Model(MiniMaxM2PreTrainedModel):
routed_experts: Optional[torch.LongTensor] = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
) -> BaseModelOutputWithPast:
"""
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
Routed experts for each token in the sequence. Only used for router replay.
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
Per-document lengths of the packed row (PrimeRL packed-batch contract).
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
"""
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
@@ -182,7 +185,8 @@ class MiniMaxM2Model(MiniMaxM2PreTrainedModel):
inputs_embeds = self.embed_tokens(input_ids)
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
seq_lens.to(device=inputs_embeds.device),
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
@@ -234,11 +238,14 @@ class MiniMaxM2ForCausalLM(MiniMaxM2PreTrainedModel, GenerationMixin):
routed_experts: Optional[torch.LongTensor] = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
r"""
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
Per-document lengths of the packed row (PrimeRL packed-batch contract).
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
compatibility — prime-rl asserts `use_cache is None` since training does not
@@ -265,6 +272,7 @@ class MiniMaxM2ForCausalLM(MiniMaxM2PreTrainedModel, GenerationMixin):
inputs_embeds=inputs_embeds,
routed_experts=routed_experts,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
hidden_states = outputs.last_hidden_state
@@ -225,20 +225,22 @@ class NemotronHMambaLayer(GradientCheckpointingLayer):
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
routed_experts: torch.Tensor | None = None,
cu_seqlens_are_pre_shard: bool = False,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.norm(hidden_states)
if self.cp_enabled:
# The local cu_seqlens cover only this shard; conv/scan need the full
# pre-shard document boundaries published by setup_cp_params.
global_cu_seqlens = (
cu_seqlens if cu_seqlens is not None and cu_seqlens_are_pre_shard else ULYSSES_PARAMS["cu_seqlens"]
)
hidden_states = mamba_cp_forward(
self.mamba,
hidden_states,
self._cp_group,
self._cp_rank,
self._cp_world_size,
ULYSSES_PARAMS["cu_seqlens"],
global_cu_seqlens,
)
else:
hidden_states = self.mamba(hidden_states, cu_seqlens=cu_seqlens)
@@ -275,6 +277,7 @@ class NemotronHMoELayer(GradientCheckpointingLayer):
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
routed_experts: torch.Tensor | None = None,
cu_seqlens_are_pre_shard: bool = False,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.norm(hidden_states)
@@ -308,6 +311,7 @@ class NemotronHAttentionLayer(GradientCheckpointingLayer):
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
routed_experts: torch.Tensor | None = None,
cu_seqlens_are_pre_shard: bool = False,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.norm(hidden_states)
@@ -502,6 +506,11 @@ class NemotronHModel(NemotronHPreTrainedModel):
self.gradient_checkpointing = False
self.post_init()
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
for layer in self.layers.modules():
if isinstance(layer, NemotronHMambaLayer):
layer.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
@auto_docstring
def forward(
self,
@@ -511,6 +520,7 @@ class NemotronHModel(NemotronHPreTrainedModel):
routed_experts: Optional[torch.LongTensor] = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
) -> BaseModelOutputWithPast:
"""
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
@@ -518,6 +528,8 @@ class NemotronHModel(NemotronHPreTrainedModel):
for non-MoE (Mamba/attention) layers are ignored.
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
Per-document lengths of the packed row (PrimeRL packed-batch contract).
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
"""
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
@@ -526,7 +538,8 @@ class NemotronHModel(NemotronHPreTrainedModel):
inputs_embeds = self.embed_tokens(input_ids)
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
seq_lens.to(device=inputs_embeds.device),
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
@@ -542,6 +555,7 @@ class NemotronHModel(NemotronHPreTrainedModel):
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
routed_experts=routed_experts_layer,
cu_seqlens_are_pre_shard=seq_lens_are_pre_shard,
)
hidden_states = self.norm(hidden_states)
@@ -562,6 +576,9 @@ class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
def get_decoder(self):
return self.model
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
self.model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
@@ -573,6 +590,7 @@ class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
routed_experts: Optional[torch.LongTensor] = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
**kwargs,
) -> PrimeLmOutput:
if position_ids is None:
@@ -587,6 +605,7 @@ class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
inputs_embeds=inputs_embeds,
routed_experts=routed_experts,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
hidden_states = outputs.last_hidden_state
@@ -156,10 +156,13 @@ class Qwen3Model(Qwen3PreTrainedModel):
inputs_embeds: Optional[torch.FloatTensor] = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
) -> BaseModelOutputWithPast:
r"""
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
Per-document lengths of the packed row (PrimeRL packed-batch contract).
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
"""
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
@@ -170,7 +173,8 @@ class Qwen3Model(Qwen3PreTrainedModel):
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
seq_lens.to(device=inputs_embeds.device),
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
@@ -225,11 +229,14 @@ class Qwen3ForCausalLM(Qwen3PreTrainedModel, GenerationMixin):
temperature: Optional[torch.Tensor] = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
r"""
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
Per-document lengths of the packed row (PrimeRL packed-batch contract).
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
compatibility; prime-rl asserts `use_cache is None` since training does not
@@ -248,6 +255,7 @@ class Qwen3ForCausalLM(Qwen3PreTrainedModel, GenerationMixin):
position_ids=position_ids,
inputs_embeds=inputs_embeds,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
hidden_states = outputs.last_hidden_state
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
@@ -4,6 +4,7 @@ from typing import Optional, Union
import torch
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 BaseModelOutputWithPast
@@ -11,6 +12,7 @@ from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
from transformers.models.qwen3_5.modeling_qwen3_5 import (
Qwen3_5PreTrainedModel as HFQwen3_5PreTrainedModel,
)
from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5VisionModel
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs
@@ -25,6 +27,8 @@ from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
Qwen3_5MoeRotaryEmbedding,
normalize_qwen3_5_attn_implementation,
)
from prime_rl.trainer.models.qwen3_5_moe.mrope import build_qwen3_5_mrope_position_ids
from prime_rl.utils.cp import setup_cp_attention_params, shard_for_cp, shard_position_ids_for_cp
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
@@ -96,12 +100,15 @@ class Qwen3_5DecoderLayer(GradientCheckpointingLayer):
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
cu_seqlens_are_pre_shard: bool = False,
) -> torch.FloatTensor:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
if self.layer_type == "linear_attention":
hidden_states = self.linear_attn(hidden_states, cu_seqlens=cu_seqlens)
hidden_states = self.linear_attn(
hidden_states, cu_seqlens=cu_seqlens, cu_seqlens_are_pre_shard=cu_seqlens_are_pre_shard
)
else:
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
@@ -185,6 +192,22 @@ class Qwen3_5Model(Qwen3_5PreTrainedModel):
self.post_init()
def get_input_embeddings(self):
return self.embed_tokens
def set_input_embeddings(self, value):
self.embed_tokens = value
def set_context_parallel_attributes(self, cp_group, cp_rank: int, cp_world_size: int) -> None:
self._cp_group = cp_group
self._cp_rank = cp_rank
self._cp_world_size = cp_world_size
for layer in self.layers.modules():
if getattr(layer, "layer_type", None) == "linear_attention":
layer.linear_attn.cp_group = cp_group
layer.linear_attn.cp_rank = cp_rank
layer.linear_attn.cp_world_size = cp_world_size
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
@@ -192,6 +215,7 @@ class Qwen3_5Model(Qwen3_5PreTrainedModel):
inputs_embeds: Optional[torch.FloatTensor] = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
) -> BaseModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
@@ -203,25 +227,138 @@ class Qwen3_5Model(Qwen3_5PreTrainedModel):
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
seq_lens.to(device=inputs_embeds.device),
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids)
cu_seqlens_are_pre_shard = seq_lens_are_pre_shard
for decoder_layer in self.layers:
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
cu_seqlens_are_pre_shard=cu_seqlens_are_pre_shard,
)
hidden_states = self.norm(hidden_states)
return BaseModelOutputWithPast(last_hidden_state=hidden_states)
class Qwen3_5VLMModel(nn.Module):
"""Composite VLM body: HF vision encoder + custom PrimeRL dense text model."""
def __init__(self, config: PretrainedConfig):
super().__init__()
self.config = config
self.visual = Qwen3_5VisionModel._from_config(config.vision_config)
self.language_model = Qwen3_5Model(config.text_config)
def get_input_embeddings(self):
return self.language_model.get_input_embeddings()
def set_input_embeddings(self, value):
self.language_model.set_input_embeddings(value)
def set_context_parallel_attributes(self, cp_group, cp_rank: int, cp_world_size: int) -> None:
self.language_model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
def _dummy_vision_inputs(self, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]:
vcfg = self.config.vision_config
m = vcfg.spatial_merge_size
num_patches = m * m
patch_dim = vcfg.in_channels * vcfg.temporal_patch_size * vcfg.patch_size * vcfg.patch_size
pixel_values = torch.zeros(num_patches, patch_dim, device=device, dtype=self.visual.dtype)
grid_thw = torch.tensor([[1, m, m]], dtype=torch.long, device=device)
return pixel_values, grid_thw
def prepare_inputs_embeds_and_position_ids(
self,
input_ids: torch.LongTensor,
position_ids: torch.LongTensor | None = None,
pixel_values: torch.Tensor | None = None,
image_grid_thw: torch.LongTensor | None = None,
mm_token_type_ids: torch.LongTensor | None = None,
*,
seq_lens: torch.LongTensor,
) -> tuple[torch.FloatTensor, torch.LongTensor]:
inputs_embeds = self.language_model.embed_tokens(input_ids)
has_images = pixel_values is not None
vision_grid_thw = image_grid_thw
if has_images:
pixel_values = pixel_values.type(self.visual.dtype)
else:
pixel_values, vision_grid_thw = self._dummy_vision_inputs(inputs_embeds.device)
vision_output = self.visual(pixel_values, grid_thw=vision_grid_thw, return_dict=True)
image_embeds = vision_output.pooler_output.to(inputs_embeds.device, inputs_embeds.dtype)
if has_images:
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)
else:
inputs_embeds = inputs_embeds + image_embeds.sum() * 0.0
if position_ids is None:
if image_grid_thw is not None:
position_ids = build_qwen3_5_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=image_grid_thw,
spatial_merge_size=self.config.vision_config.spatial_merge_size,
seq_lens=seq_lens,
)
else:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
return inputs_embeds, position_ids
def forward(
self,
input_ids: torch.LongTensor,
position_ids: torch.LongTensor | None = None,
pixel_values: torch.Tensor | None = None,
image_grid_thw: torch.LongTensor | None = None,
mm_token_type_ids: torch.LongTensor | None = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
) -> BaseModelOutputWithPast:
inputs_embeds, position_ids = self.prepare_inputs_embeds_and_position_ids(
input_ids=input_ids,
position_ids=position_ids,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
seq_lens=seq_lens,
)
cp_group = getattr(self.language_model, "_cp_group", None)
if image_grid_thw is not None and cp_group is not None:
cp_rank = self.language_model._cp_rank
cp_world_size = self.language_model._cp_world_size
setup_cp_attention_params(position_ids, cp_group=cp_group, cp_style="ulysses", seq_lens=seq_lens)
inputs_embeds = shard_for_cp(inputs_embeds, cp_rank=cp_rank, cp_world_size=cp_world_size)
position_ids = shard_position_ids_for_cp(position_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
seq_lens_are_pre_shard = True
return self.language_model(
inputs_embeds=inputs_embeds,
position_ids=position_ids,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
"""Unified dense Qwen3.5 model for both text-only and VLM configs."""
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_checkpoint_conversion_mapping = {}
_tp_plan = {"lm_head": "colwise_gather_output"}
@@ -229,16 +366,25 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
def __init__(self, config, **kwargs):
super().__init__(config, **kwargs)
self.model = Qwen3_5Model(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self._is_vlm = hasattr(config, "vision_config")
if self._is_vlm:
self.model = Qwen3_5VLMModel(config)
text_config = config.text_config
self._tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
else:
self.model = Qwen3_5Model(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):
return self.model.embed_tokens
return self.model.get_input_embeddings()
def set_input_embeddings(self, value):
self.model.embed_tokens = value
self.model.set_input_embeddings(value)
def set_decoder(self, decoder):
self.model = decoder
@@ -246,6 +392,9 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
def get_decoder(self):
return self.model
def set_context_parallel_attributes(self, cp_group, cp_rank: int, cp_world_size: int) -> None:
self.model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
@@ -257,25 +406,35 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
use_cache: Optional[bool] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
temperature: Union[torch.Tensor, None] = None,
pixel_values: Optional[torch.Tensor] = None,
image_grid_thw: Optional[torch.LongTensor] = None,
mm_token_type_ids: Optional[torch.LongTensor] = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
assert use_cache is None, "use_cache is not supported for custom qwen3_5 for now"
assert past_key_values is None, "past_key_values is not supported for custom qwen3_5 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)
outputs = self.model(
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
seq_lens=seq_lens,
)
if self._is_vlm:
outputs = self.model(
input_ids=input_ids,
position_ids=position_ids,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
else:
outputs = self.model(
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
hidden_states = outputs.last_hidden_state
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
@@ -286,11 +445,25 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
)
def init_buffers_post_meta(self):
lm_rope = self.model.rotary_emb
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_5ForCausalLM",
@@ -28,7 +28,7 @@ from prime_rl.trainer.models.layers.attn import (
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 apply_rotary_pos_emb
from prime_rl.trainer.models.layers.ulysses_attn import ULYSSES_PARAMS
from prime_rl.utils.cp import setup_cp_attention_params, shard_for_cp, shard_position_ids_for_cp
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
from .configuration_qwen3_5_moe import Qwen3_5MoeConfig
@@ -43,6 +43,24 @@ from .mrope import build_qwen3_5_mrope_position_ids
logger = logging.get_logger(__name__)
@torch.compiler.disable
def _fla_causal_conv1d_cp(
x: torch.Tensor,
weight: torch.Tensor,
bias: torch.Tensor | None,
activation: str,
cp_context: FLACPContext,
) -> torch.Tensor:
output, _ = fla_causal_conv1d(
x=x,
weight=weight,
bias=bias,
activation=activation,
cp_context=cp_context,
)
return output
# ---------------------------------------------------------------------------
# RMSNorm variants
# ---------------------------------------------------------------------------
@@ -113,16 +131,21 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
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)
def _build_cp_context(self) -> "FLACPContext | None":
"""Build fla CP context from the full pre-shard document boundaries."""
def _build_cp_context(
self,
device: torch.device,
cu_seqlens: torch.LongTensor | None = None,
cu_seqlens_are_pre_shard: bool = False,
) -> "FLACPContext | None":
"""Build the FLA CP context from full pre-shard sequence boundaries."""
cp_group = getattr(self, "cp_group", None)
if cp_group is None:
return None
# Local cu_seqlens cannot describe documents straddling shard boundaries;
# use the full (un-sharded) cu_seqlens published by setup_cp_params. fla
# derives per-rank boundaries and document-aware state passing from them.
if cu_seqlens is None or not cu_seqlens_are_pre_shard:
raise ValueError("Qwen3.5 context parallelism requires full pre-shard sequence boundaries")
global_cu_seqlens = cu_seqlens.to(device=device, dtype=torch.int32)
return build_cp_context(
cu_seqlens=ULYSSES_PARAMS["cu_seqlens"],
cu_seqlens=global_cu_seqlens,
group=cp_group,
conv1d_kernel_size=self.conv_kernel_size,
)
@@ -131,6 +154,7 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
self,
hidden_states: torch.Tensor,
cu_seqlens: torch.LongTensor | None = None,
cu_seqlens_are_pre_shard: bool = False,
) -> torch.Tensor:
batch_size, seq_len, _ = hidden_states.shape
@@ -139,18 +163,28 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
b = self.in_proj_b(hidden_states)
a = self.in_proj_a(hidden_states)
cp_context = self._build_cp_context()
cp_context = self._build_cp_context(hidden_states.device, cu_seqlens, cu_seqlens_are_pre_shard)
# Causal conv1d — must reset at sequence boundaries for packed batches,
# otherwise the kernel-1 left pad leaks state across sequences.
mixed_qkv, _ = fla_causal_conv1d(
x=mixed_qkv.transpose(1, 2),
weight=self.conv1d.weight.squeeze(1),
bias=self.conv1d.bias,
activation=self.activation,
cu_seqlens=cu_seqlens if cp_context is None else None,
cp_context=cp_context,
)
conv_input = mixed_qkv.transpose(1, 2)
conv_weight = self.conv1d.weight.squeeze(1)
if cp_context is None:
mixed_qkv, _ = fla_causal_conv1d(
x=conv_input,
weight=conv_weight,
bias=self.conv1d.bias,
activation=self.activation,
cu_seqlens=cu_seqlens,
)
else:
mixed_qkv = _fla_causal_conv1d_cp(
x=conv_input,
weight=conv_weight,
bias=self.conv1d.bias,
activation=self.activation,
cp_context=cp_context,
)
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)
@@ -434,13 +468,16 @@ class Qwen3_5MoeDecoderLayer(GradientCheckpointingLayer):
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
routed_experts: Optional[torch.LongTensor] = None,
cu_seqlens_are_pre_shard: bool = False,
) -> 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, cu_seqlens=cu_seqlens)
hidden_states = self.linear_attn(
hidden_states, cu_seqlens=cu_seqlens, cu_seqlens_are_pre_shard=cu_seqlens_are_pre_shard
)
elif self.layer_type == "full_attention":
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
@@ -656,6 +693,22 @@ class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
self.post_init()
def get_input_embeddings(self):
return self.embed_tokens
def set_input_embeddings(self, value):
self.embed_tokens = value
def set_context_parallel_attributes(self, cp_group, cp_rank: int, cp_world_size: int) -> None:
self._cp_group = cp_group
self._cp_rank = cp_rank
self._cp_world_size = cp_world_size
for layer in self.layers.modules():
if getattr(layer, "layer_type", None) == "linear_attention":
layer.linear_attn.cp_group = cp_group
layer.linear_attn.cp_rank = cp_rank
layer.linear_attn.cp_world_size = cp_world_size
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
@@ -664,6 +717,7 @@ class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
routed_experts: Optional[torch.LongTensor] = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
) -> MoeModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
@@ -674,15 +728,16 @@ class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
if position_ids.ndim == 3 and inputs_embeds.shape[0] != 1:
raise ValueError("3D Qwen3.5 MRoPE positions require batch size 1 for varlen attention")
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
seq_lens.to(device=inputs_embeds.device),
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids)
cu_seqlens_are_pre_shard = seq_lens_are_pre_shard
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(
@@ -691,6 +746,7 @@ class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
routed_experts=routed_experts_layer,
cu_seqlens_are_pre_shard=cu_seqlens_are_pre_shard,
)
hidden_states = self.norm(hidden_states)
@@ -726,10 +782,13 @@ class Qwen3_5MoeVLMModel(nn.Module):
self.language_model = Qwen3_5MoeModel(_build_text_config(config))
def get_input_embeddings(self):
return self.language_model.embed_tokens
return self.language_model.get_input_embeddings()
def set_input_embeddings(self, value):
self.language_model.embed_tokens = value
self.language_model.set_input_embeddings(value)
def set_context_parallel_attributes(self, cp_group, cp_rank: int, cp_world_size: int) -> None:
self.language_model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
def _dummy_vision_inputs(self, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]:
"""Smallest valid vision input: a single merged token (grid [1, m, m])."""
@@ -741,42 +800,26 @@ class Qwen3_5MoeVLMModel(nn.Module):
grid_thw = torch.tensor([[1, m, m]], dtype=torch.long, device=device)
return pixel_values, grid_thw
def forward(
def prepare_inputs_embeds_and_position_ids(
self,
input_ids: torch.LongTensor | None = None,
input_ids: torch.LongTensor,
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,
mm_token_type_ids: torch.LongTensor | None = None,
routed_experts: torch.LongTensor | None = None,
*,
seq_lens: torch.LongTensor,
**kwargs,
) -> MoeModelOutputWithPast:
if inputs_embeds is None:
inputs_embeds = self.language_model.embed_tokens(input_ids)
) -> tuple[torch.FloatTensor, torch.LongTensor]:
inputs_embeds = self.language_model.embed_tokens(input_ids)
if image_grid_thw is not None and input_ids is None:
raise ValueError("input_ids are required to compute Qwen3.5 multimodal MRoPE positions")
if image_grid_thw is not None and mm_token_type_ids is None:
raise ValueError(
"Qwen3.5 multimodal forward requires mm_token_type_ids to compute MRoPE positions correctly"
)
if image_grid_thw is not None and position_ids is not None and position_ids.ndim != 3:
raise ValueError(
f"Qwen3.5 multimodal forward requires 3D MRoPE position_ids; got shape={tuple(position_ids.shape)}"
)
# Keep distributed collectives in the same order when a batch mixes text-only
# and image samples across ranks. The frozen dummy pass is discarded below.
# Always run the vision encoder for collective symmetry: under FSDP + EP
# all ranks share one process group, so every rank must issue the vision
# encoder's collectives in the same order each step. Text-only microbatches
# keep the dummy embeds in the graph with zero contribution so trainable
# vision modules also participate in backward collectives.
has_images = pixel_values is not None
vision_grid_thw = image_grid_thw
if has_images:
if input_ids is None:
raise ValueError("input_ids are required when scattering Qwen3.5 image features")
if image_grid_thw is None:
raise ValueError("image_grid_thw is required when pixel_values are provided")
pixel_values = pixel_values.type(self.visual.dtype)
else:
pixel_values, vision_grid_thw = self._dummy_vision_inputs(inputs_embeds.device)
@@ -786,19 +829,10 @@ class Qwen3_5MoeVLMModel(nn.Module):
if has_images:
image_mask = input_ids == self.config.image_token_id
image_token_count = int(image_mask.sum().item())
image_feature_count = int(image_embeds.shape[0])
if image_token_count != image_feature_count:
raise ValueError(
"Qwen VLM image token/feature mismatch before scatter: "
f"image_token_id={self.config.image_token_id}, "
f"image_tokens={image_token_count}, image_features={image_feature_count}, "
f"input_ids_shape={tuple(input_ids.shape)}, "
f"pixel_values_shape={tuple(pixel_values.shape)}, "
f"image_grid_thw_shape={tuple(image_grid_thw.shape) if image_grid_thw is not None else None}"
)
image_mask = image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
else:
inputs_embeds = inputs_embeds + image_embeds.sum() * 0.0
if position_ids is None:
if image_grid_thw is not None:
@@ -812,11 +846,46 @@ class Qwen3_5MoeVLMModel(nn.Module):
else:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
return inputs_embeds, position_ids
def forward(
self,
input_ids: torch.LongTensor,
position_ids: torch.LongTensor | None = None,
pixel_values: torch.Tensor | None = None,
image_grid_thw: torch.LongTensor | None = None,
mm_token_type_ids: torch.LongTensor | None = None,
routed_experts: torch.LongTensor | None = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
) -> MoeModelOutputWithPast:
inputs_embeds, position_ids = self.prepare_inputs_embeds_and_position_ids(
input_ids=input_ids,
position_ids=position_ids,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
seq_lens=seq_lens,
)
cp_group = getattr(self.language_model, "_cp_group", None)
if image_grid_thw is not None and cp_group is not None:
cp_rank = self.language_model._cp_rank
cp_world_size = self.language_model._cp_world_size
setup_cp_attention_params(position_ids, cp_group=cp_group, cp_style="ulysses", seq_lens=seq_lens)
inputs_embeds = shard_for_cp(inputs_embeds, cp_rank=cp_rank, cp_world_size=cp_world_size)
position_ids = shard_position_ids_for_cp(position_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
if routed_experts is not None:
routed_experts = shard_for_cp(routed_experts, cp_rank=cp_rank, cp_world_size=cp_world_size)
seq_lens_are_pre_shard = True
return self.language_model(
inputs_embeds=inputs_embeds,
position_ids=position_ids,
routed_experts=routed_experts,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
@@ -872,15 +941,10 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
self.post_init()
def get_input_embeddings(self):
if self._is_vlm:
return self.model.get_input_embeddings()
return self.model.embed_tokens
return self.model.get_input_embeddings()
def set_input_embeddings(self, value):
if self._is_vlm:
self.model.set_input_embeddings(value)
else:
self.model.embed_tokens = value
self.model.set_input_embeddings(value)
def set_decoder(self, decoder):
self.model = decoder
@@ -888,6 +952,9 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
def get_decoder(self):
return self.model
def set_context_parallel_attributes(self, cp_group, cp_rank: int, cp_world_size: int) -> None:
self.model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
# ------------------------------------------------------------------
# State dict detection & conversion (handles both text-only and VLM)
# ------------------------------------------------------------------
@@ -966,28 +1033,22 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
mm_token_type_ids: Optional[torch.LongTensor] = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
**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"
has_vlm_image_inputs = self._is_vlm and image_grid_thw is not None
if position_ids is None and not has_vlm_image_inputs:
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,
mm_token_type_ids=mm_token_type_ids,
routed_experts=routed_experts,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
else:
outputs = self.model(
@@ -996,6 +1057,7 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
inputs_embeds=inputs_embeds,
routed_experts=routed_experts,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
hidden_states = outputs.last_hidden_state
@@ -208,12 +208,15 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
routed_experts: Optional[torch.LongTensor] = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
) -> MoeModelOutputWithPast:
"""
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
Routed experts for each token in the sequence. Only used for router replay.
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
Per-document lengths of the packed row (PrimeRL packed-batch contract).
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
"""
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
@@ -222,7 +225,8 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
inputs_embeds = self.embed_tokens(input_ids)
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
seq_lens.to(device=inputs_embeds.device),
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
@@ -286,11 +290,14 @@ class Qwen3MoeForCausalLM(Qwen3MoePreTrainedModel, GenerationMixin):
routed_experts: Optional[torch.LongTensor] = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
r"""
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
Per-document lengths of the packed row (PrimeRL packed-batch contract).
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
compatibility — prime-rl asserts `use_cache is None` since training does not
@@ -339,6 +346,7 @@ class Qwen3MoeForCausalLM(Qwen3MoePreTrainedModel, GenerationMixin):
inputs_embeds=inputs_embeds,
routed_experts=routed_experts,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
hidden_states = outputs.last_hidden_state
+3 -7
View File
@@ -65,7 +65,6 @@ from prime_rl.utils.metrics_server import HealthServer, MetricsServer, RunStats
from prime_rl.utils.monitor import setup_monitor
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
from prime_rl.utils.sequence import get_cp_local_seq_lens
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step, to_col_format
from ring_flash_attn import substitute_hf_flash_attn
from torchtitan.distributed.utils import clip_grad_norm_
@@ -205,8 +204,7 @@ def train(config: TrainerConfig):
substitute_ulysses_attn(cp_group, attn_impl=config.model.attn)
from prime_rl.utils.cp import (
assert_cp_style_supports_model,
setup_hybrid_cp,
setup_nemotron_h_cp,
setup_model_cp,
setup_sparse_mla_cp,
)
@@ -216,8 +214,7 @@ def train(config: TrainerConfig):
# Linear-attn / Mamba layers are only configured under ulysses; with ring
# we'd have already raised above.
if config.model.cp_style == "ulysses":
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
setup_nemotron_h_cp(model, cp_group, cp_rank, parallel_dims.cp)
setup_model_cp(model, cp_group, cp_rank, parallel_dims.cp)
# Optionally, resume training from a checkpoint
progress = Progress()
@@ -379,7 +376,6 @@ def train(config: TrainerConfig):
raise NotImplementedError("Context parallelism is not supported with VLM/multimodal training")
if cp_enabled:
total_tokens = input_ids.shape[1]
input_ids, forward_position_ids = setup_cp_params(
input_ids,
position_ids,
@@ -389,7 +385,6 @@ def train(config: TrainerConfig):
seq_lens=seq_lens,
cp_style=config.model.cp_style,
)
seq_lens = get_cp_local_seq_lens(seq_lens, total_tokens, cp_rank, cp_size)
labels = shard_for_cp(labels, cp_rank=cp_rank, cp_world_size=cp_size)
if routed_experts is not None:
routed_experts = shard_for_cp(routed_experts, cp_rank=cp_rank, cp_world_size=cp_size)
@@ -425,6 +420,7 @@ def train(config: TrainerConfig):
mm_kwargs=mm_kwargs,
mm_token_type_ids=mm_token_type_ids,
seq_lens=seq_lens,
seq_lens_are_pre_shard=cp_enabled,
routed_experts=routed_experts,
)
+12 -1
View File
@@ -236,9 +236,20 @@ class MultiRunManager:
with open(config_path, "rb") as f:
config_dict = tomli.load(f)
from verifiers.v1.loaders import skip_plugin_install
from prime_rl.configs.orchestrator import OrchestratorConfig
config = OrchestratorConfig(**config_dict)
# The trainer only reads training-relevant fields (model, lora, seq_len, buffers,
# env names) and never runs the env, so skip resolving/installing taskset/harness
# plugins from the Environments Hub while parsing. Otherwise a private v1 hub env
# (`taskset.id = owner/name@version`) 404s here — the trainer has no Hub creds — and
# the run is silently skipped. The env server still installs the plugin at runtime.
token = skip_plugin_install.set(True)
try:
config = OrchestratorConfig(**config_dict)
finally:
skip_plugin_install.reset(token)
except Exception as e:
if error_path.parent.exists():
with open(error_path, "w") as f:
+138 -3
View File
@@ -3,10 +3,11 @@ import uuid
from collections import defaultdict
from typing import Any, Literal, TypedDict, cast
import numpy as np
import torch
from datasets import Dataset, interleave_datasets, load_dataset
from jaxtyping import Bool, Int
from renderers.base import Renderer, build_training_sample
from renderers.base import MultiModalData, PlaceholderRange, Renderer, build_training_sample
from torch import Tensor
from torch.distributed.checkpoint.stateful import Stateful
from torch.utils.data import IterableDataset, get_worker_info
@@ -25,6 +26,8 @@ class Sample(TypedDict):
loss_mask: list[bool]
target_ids: list[int]
seq_lens: list[int]
mm_kwargs: dict[str, Tensor] | None
mm_token_type_ids: list[int] | None
class Batch(TypedDict):
@@ -33,6 +36,8 @@ class Batch(TypedDict):
target_ids: Int[Tensor, "batch seq"]
loss_mask: Bool[Tensor, "batch seq"]
seq_lens: Int[Tensor, "packed"]
mm_kwargs: dict[str, Tensor] | None
mm_token_type_ids: Int[Tensor, "batch seq"] | None
class StatefulIterableDataset(Stateful, IterableDataset):
@@ -103,12 +108,27 @@ class FakeDataset(StatefulIterableDataset):
"position_ids": position_ids,
"loss_mask": loss_mask,
"seq_lens": [seq_len],
"mm_kwargs": None,
"mm_token_type_ids": None,
}
self.num_samples["fake"] += 1
self.num_tokens["fake"] += len(input_ids)
yield fake_sample
def _flatten_mm_items(mm_items: dict[str, list[dict[str, Any]]]) -> dict[str, Tensor]:
"""Fold per-item renderer outputs into model-forward tensors."""
out: dict[str, Tensor] = {}
for items in mm_items.values():
for item in items:
for key, value in item.items():
if not isinstance(value, (np.ndarray, Tensor)):
continue
tensor = torch.as_tensor(value)
out[key] = torch.cat([out[key], tensor], dim=0) if key in out else tensor
return out
def _drop_null_fields(value: Any, path: tuple[str, ...] = ()) -> Any:
"""Recursively strip ``None``-valued keys from dict structures.
@@ -129,6 +149,34 @@ def _drop_null_fields(value: Any, path: tuple[str, ...] = ()) -> Any:
return value
def _find_image_safe_cut(budget: int, mm: MultiModalData | None) -> int:
"""Return the largest cut at most ``budget`` outside placeholder runs."""
if mm is None or not mm.mm_placeholders:
return budget
cut = budget
for ranges in mm.mm_placeholders.values():
for placeholder in ranges:
if placeholder.offset < cut < placeholder.offset + placeholder.length:
cut = placeholder.offset
return cut
def _truncate_mm_data(mm: MultiModalData, cut: int) -> MultiModalData:
"""Drop multimodal items whose placeholder ranges extend past ``cut``."""
new_placeholders: dict[str, list[PlaceholderRange]] = {}
new_items: dict[str, list[dict[str, Any]]] = {}
new_hashes: dict[str, list[str]] = {}
for content_type, ranges in mm.mm_placeholders.items():
keep = [index for index, placeholder in enumerate(ranges) if placeholder.offset + placeholder.length <= cut]
if not keep:
continue
new_placeholders[content_type] = [ranges[index] for index in keep]
new_items[content_type] = [mm.mm_items[content_type][index] for index in keep]
if content_type in mm.mm_hashes:
new_hashes[content_type] = [mm.mm_hashes[content_type][index] for index in keep]
return MultiModalData(mm_hashes=new_hashes, mm_placeholders=new_placeholders, mm_items=new_items)
class SFTDataset(StatefulIterableDataset):
"""A dataset wrapping a HF SFT dataset with prompt/completion or raw messages format."""
@@ -143,6 +191,7 @@ class SFTDataset(StatefulIterableDataset):
loss_mask_config: LossMaskConfig = LossMaskConfig(),
max_examples: int | None = None,
max_epochs: int | None = None,
multimodal: bool = False,
):
super().__init__()
self.logger = get_logger()
@@ -155,6 +204,7 @@ class SFTDataset(StatefulIterableDataset):
self.loss_mask_config = loss_mask_config
self.max_examples = max_examples
self.max_epochs = max_epochs
self.multimodal = multimodal
# If specified, select a subset of the dataset
if self.max_examples is not None:
@@ -254,11 +304,39 @@ class SFTDataset(StatefulIterableDataset):
)
input_ids = list(sample.token_ids)
loss_mask = list(sample.loss_mask)
mm = sample.multi_modal_data
mm_token_type_ids = list(sample.mm_token_type_ids) if sample.mm_token_type_ids is not None else None
if mm is not None and mm.mm_items and not self.multimodal:
raise ValueError(
"Renderer produced multimodal data but [model.vlm] is not set. "
"Set [model.vlm] to train on multimodal samples."
)
# Causal shift: model predicts next token from current.
target_ids = input_ids.copy()[1:]
target_ids = input_ids[1:]
loss_mask = loss_mask[1:]
input_ids = input_ids[:-1]
if mm_token_type_ids is not None:
mm_token_type_ids = mm_token_type_ids[:-1]
was_mm_truncated = False
if mm is not None and len(input_ids) > self.seq_len:
was_mm_truncated = True
cut = _find_image_safe_cut(self.seq_len, mm)
self.logger.debug(
f"Truncating example {example.get('__index', '')} from "
f"{len(input_ids)} → {cut} tokens (budget={self.seq_len})"
)
input_ids = input_ids[:cut]
target_ids = target_ids[:cut]
loss_mask = loss_mask[:cut]
if mm_token_type_ids is not None:
mm_token_type_ids = mm_token_type_ids[:cut]
if mm.mm_items:
mm = _truncate_mm_data(mm, cut)
if was_mm_truncated and not set(self.renderer.get_stop_token_ids()) & set(target_ids):
return None
if sum(loss_mask[: self.seq_len]) == 0:
self.logger.warning(
@@ -274,12 +352,22 @@ class SFTDataset(StatefulIterableDataset):
"A renderer stop token must be present in target_ids"
)
mm_kwargs: dict[str, Tensor] | None = None
if mm is not None and mm.mm_items:
mm_kwargs = _flatten_mm_items(mm.mm_items)
if any("video" in key for key in mm_kwargs):
raise ValueError("Video SFT is not supported; sample contains video inputs")
if mm_token_type_ids is not None:
assert len(mm_token_type_ids) == len(input_ids)
return {
"input_ids": input_ids,
"target_ids": target_ids,
"loss_mask": loss_mask,
"position_ids": list(range(len(input_ids))),
"seq_lens": [len(input_ids)],
"mm_kwargs": mm_kwargs,
"mm_token_type_ids": mm_token_type_ids,
}
def __iter__(self):
@@ -327,7 +415,7 @@ class SFTDataset(StatefulIterableDataset):
class CatDataset(StatefulIterableDataset):
"""A dataset that concatenates samples into a single sequence with a fixed length."""
"""Concatenate text and multimodal samples into one fixed-length row."""
def __init__(self, dataset: StatefulIterableDataset, seq_len: int):
self.logger = get_logger()
@@ -347,6 +435,8 @@ class CatDataset(StatefulIterableDataset):
def __iter__(self):
packed_samples = defaultdict(list)
packed_samples["mm_kwargs"] = None
packed_samples["mm_token_type_ids"] = None
seq_len = 0
pending_sample = self.pending_sample
@@ -365,18 +455,48 @@ class CatDataset(StatefulIterableDataset):
yield self._finalize_pack(packed_samples, self.seq_len)
self.pending_sample = None
packed_samples = defaultdict(list)
packed_samples["mm_kwargs"] = None
packed_samples["mm_token_type_ids"] = None
seq_len = 0
existing_len = len(packed_samples["input_ids"])
for key in ("input_ids", "position_ids", "loss_mask", "target_ids"):
value = sample[key]
assert isinstance(value, list)
packed_samples[key].extend(value)
packed_samples["seq_lens"].append(sample_len)
sample_mm_kwargs = sample.get("mm_kwargs")
sample_mm_type_ids = sample.get("mm_token_type_ids")
if sample_mm_kwargs is None:
if packed_samples["mm_token_type_ids"] is not None:
packed_samples["mm_token_type_ids"].extend([0] * sample_len)
else:
if packed_samples["mm_kwargs"] is not None and (
(packed_samples["mm_token_type_ids"] is None) != (sample_mm_type_ids is None)
):
raise ValueError("Cannot pack multimodal samples with mixed mm_token_type_ids")
if packed_samples["mm_kwargs"] is None:
packed_samples["mm_kwargs"] = dict(sample_mm_kwargs)
else:
if packed_samples["mm_kwargs"].keys() != sample_mm_kwargs.keys():
raise ValueError("Cannot pack multimodal samples with different mm_kwargs keys")
for key, value in sample_mm_kwargs.items():
packed_samples["mm_kwargs"][key] = torch.cat([packed_samples["mm_kwargs"][key], value], dim=0)
if packed_samples["mm_token_type_ids"] is None and sample_mm_type_ids is not None:
packed_samples["mm_token_type_ids"] = [0] * existing_len
if packed_samples["mm_token_type_ids"] is not None:
packed_samples["mm_token_type_ids"].extend(sample_mm_type_ids or [0] * sample_len)
seq_len += sample_len
if seq_len >= self.seq_len:
yield self._finalize_pack(packed_samples, self.seq_len)
packed_samples = defaultdict(list)
packed_samples["mm_kwargs"] = None
packed_samples["mm_token_type_ids"] = None
seq_len = 0
if seq_len > 0:
@@ -402,17 +522,30 @@ class CatDataset(StatefulIterableDataset):
result["loss_mask"].extend([False] * pad_len)
result["target_ids"].extend([0] * pad_len)
result["seq_lens"][-1] += pad_len
result["mm_kwargs"] = packed["mm_kwargs"]
if packed["mm_token_type_ids"] is not None:
result["mm_token_type_ids"] = packed["mm_token_type_ids"][:seq_len] + [0] * pad_len
else:
result["mm_token_type_ids"] = None
return result
def cat_collate(samples: list[Sample]) -> Batch:
(sample,) = samples
mm_kwargs = sample.get("mm_kwargs")
mm_token_type_ids = sample.get("mm_token_type_ids")
return {
"input_ids": torch.tensor(sample["input_ids"], dtype=torch.long, device="cuda").unsqueeze(0),
"position_ids": torch.tensor(sample["position_ids"], dtype=torch.long, device="cuda").unsqueeze(0),
"loss_mask": torch.tensor(sample["loss_mask"], dtype=torch.bool, device="cuda").unsqueeze(0),
"target_ids": torch.tensor(sample["target_ids"], dtype=torch.long, device="cuda").unsqueeze(0),
"seq_lens": torch.tensor(sample["seq_lens"], dtype=torch.long, device="cuda"),
"mm_kwargs": {key: value.to("cuda") for key, value in mm_kwargs.items()} if mm_kwargs is not None else None,
"mm_token_type_ids": (
torch.tensor(mm_token_type_ids, dtype=torch.long, device="cuda").unsqueeze(0)
if mm_token_type_ids is not None
else None
),
}
@@ -492,6 +625,7 @@ def setup_dataset(
max_epochs: int | None = None,
raw_dataset: Dataset | None = None,
renderer: Renderer | None = None,
multimodal: bool = False,
) -> StatefulIterableDataset:
if config.type == "fake":
return FakeDataset(
@@ -514,6 +648,7 @@ def setup_dataset(
loss_mask_config=config.loss_mask,
non_dp_size=non_dp_size,
max_epochs=max_epochs,
multimodal=multimodal,
)
else:
raise ValueError(f"Invalid dataset type: {config.type}")
+45 -19
View File
@@ -28,6 +28,7 @@ from prime_rl.trainer.model import (
forward,
get_load_balance_stats,
is_tt_moe_model,
setup_processor,
setup_tokenizer,
resolve_auto_attn,
setup_model,
@@ -50,7 +51,6 @@ from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.monitor import setup_monitor
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
from prime_rl.utils.sequence import get_cp_local_seq_lens
from prime_rl.utils.utils import clean_exit, to_col_format
import torch.distributed as dist
@@ -125,7 +125,7 @@ def train(config: SFTConfig):
substitute_hf_ulysses_attn(cp_group)
substitute_ulysses_attn(cp_group, attn_impl=config.model.attn)
from prime_rl.utils.cp import setup_hybrid_cp, setup_nemotron_h_cp, setup_sparse_mla_cp
from prime_rl.utils.cp import setup_model_cp, setup_sparse_mla_cp
# Set up checkpoint manager
logger.info(f"Initializing checkpoint managers ({config.ckpt})")
@@ -152,8 +152,7 @@ def train(config: SFTConfig):
# Linear-attn / Mamba layers are only configured under ulysses; with ring
# we'd have already raised above.
if config.model.cp_style == "ulysses":
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
setup_nemotron_h_cp(model, cp_group, cp_rank, parallel_dims.cp)
setup_model_cp(model, cp_group, cp_rank, parallel_dims.cp)
if config.model.lora is not None:
multi_run_manager = get_multi_run_manager()
@@ -162,6 +161,9 @@ def train(config: SFTConfig):
logger.info(f"Initializing tokenizer ({config.tokenizer})")
tokenizer = setup_tokenizer(config.tokenizer)
processor = setup_processor(config.model)
if config.model.vlm is not None and processor is None:
raise ValueError(f"[model.vlm] is set but no multimodal processor could be loaded for {config.model.name!r}")
# Fake data never renders messages, so a model without a hand-coded renderer
# can still be used to benchmark step time / memory. Validation data is
@@ -169,6 +171,8 @@ def train(config: SFTConfig):
renderer = None
if config.data.type != "fake" or config.val is not None:
renderer = create_renderer(tokenizer, config.renderer)
if processor is not None and hasattr(renderer, "_processor"):
renderer._processor = processor
logger.info(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}")
# Set up the optimizer
@@ -189,7 +193,8 @@ def train(config: SFTConfig):
# Set up the dataset and dataloader
logger.info(f"Initializing data ({config.data})")
dataset = setup_dataset(tokenizer, config.data, config.model.cp, renderer=renderer)
multimodal = config.model.vlm is not None
dataset = setup_dataset(tokenizer, config.data, config.model.cp, renderer=renderer, multimodal=multimodal)
dataloader = setup_dataloader(dataset, config.data)
dataiter = iter(dataloader)
@@ -234,24 +239,33 @@ def train(config: SFTConfig):
target_ids = micro_batch["target_ids"].to("cuda")
loss_mask = micro_batch["loss_mask"].to("cuda")
seq_lens = micro_batch["seq_lens"].to("cuda")
mm_kwargs = micro_batch.get("mm_kwargs")
mm_type_ids = micro_batch.get("mm_token_type_ids")
seq_lens_are_pre_shard = False
if cp_enabled:
total_tokens = input_ids.shape[1]
input_ids, position_ids = setup_cp_params(
input_ids,
position_ids,
cp_rank,
cp_size,
cp_group,
seq_lens=seq_lens,
cp_style=config.model.cp_style,
# CP requires the sequence length to be divisible by cp_size. CatDataset
# pads every pack to seq_len; shard_for_cp raises on violations.
defer_vlm_cp_to_model = (
mm_kwargs is not None and "image_grid_thw" in mm_kwargs and config.model.cp_style == "ulysses"
)
seq_lens = get_cp_local_seq_lens(seq_lens, total_tokens, cp_rank, cp_size)
if not defer_vlm_cp_to_model:
input_ids, position_ids = setup_cp_params(
input_ids,
position_ids,
cp_rank,
cp_size,
cp_group,
seq_lens=seq_lens,
cp_style=config.model.cp_style,
)
seq_lens_are_pre_shard = True
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"))
set_lora_num_tokens(torch.full((1,), loss_mask.numel(), dtype=torch.int32, device="cuda"))
token_count = loss_mask.sum(dtype=torch.int64)
@@ -268,10 +282,21 @@ def train(config: SFTConfig):
seq_lens=seq_lens,
labels=target_ids,
temperature=temperature,
mm_kwargs=mm_kwargs,
mm_token_type_ids=mm_type_ids,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
loss_sum = -out["logprobs"][loss_mask].sum()
else:
out = forward(model, input_ids, position_ids, seq_lens=seq_lens)
out = forward(
model,
input_ids,
position_ids,
mm_kwargs=mm_kwargs,
mm_token_type_ids=mm_type_ids,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
logits = out["logits"]
B, L, V = logits.shape
token_loss = CrossEntropyLoss(reduction="none")(logits.view(-1, V), target_ids.view(-1)).view(B, L)
@@ -324,6 +349,7 @@ def train(config: SFTConfig):
max_epochs=1,
raw_dataset=val_raw_dataset,
renderer=renderer,
multimodal=multimodal,
)
val_dataloader = setup_dataloader(val_dataset, config.val.data)
@@ -480,7 +506,7 @@ def train(config: SFTConfig):
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)
weight_ckpt_manager.save(progress.step, model, tokenizer, processor)
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
weight_ckpt_manager.maybe_clean()
else:
@@ -616,7 +642,7 @@ def train(config: SFTConfig):
# Write final weight checkpoint
if weight_ckpt_manager is not None:
logger.info("Writing final weight checkpoint")
weight_ckpt_manager.save(progress.step, model, tokenizer)
weight_ckpt_manager.save(progress.step, model, tokenizer, processor)
weight_ckpt_manager.maybe_clean()
logger.info(f"Peak memory: {max(to_col_format(monitor.history)['perf/peak_memory']):.1f} GiB")
+47 -54
View File
@@ -24,7 +24,8 @@ def _has_linear_attn_layer(model: nn.Module) -> bool:
layers = getattr(inner, "layers", None)
if layers is None:
return False
for layer in layers:
layer_modules = layers.modules() if isinstance(layers, nn.Module) else layers
for layer in layer_modules:
# Qwen3.5 hybrid DeltaNet
if getattr(layer, "layer_type", None) == "linear_attention":
return True
@@ -52,54 +53,22 @@ def assert_cp_style_supports_model(cp_style: CPStyle, model: nn.Module) -> None:
)
def setup_hybrid_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
"""Configure DeltaNet modules in Qwen3.5 hybrid models for ulysses-style CP."""
layers = None
if hasattr(model, "model"):
inner = model.model
if hasattr(inner, "language_model"):
inner = inner.language_model
if hasattr(inner, "layers"):
layers = inner.layers
def setup_model_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
"""Hand the CP topology to models whose layers need it (DeltaNet, Mamba).
if layers is None:
return
count = 0
for layer in layers:
if getattr(layer, "layer_type", None) == "linear_attention":
attn = getattr(layer, "linear_attn", None)
if attn is not None:
attn.cp_group = cp_group
attn.cp_rank = cp_rank
attn.cp_world_size = cp_world_size
count += 1
if count > 0:
Such models expose ``set_context_parallel_attributes`` at the top level and
own their layer wiring; softmax-only models don't and need nothing.
"""
if hasattr(model, "set_context_parallel_attributes"):
model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
from prime_rl.utils.logger import get_logger
get_logger().info(f"Configured hybrid CP on {count} DeltaNet modules (fla native state passing)")
def setup_nemotron_h_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
"""Configure NemotronH Mamba layers for ulysses-style all-to-all head partitioning."""
layers = None
if hasattr(model, "model") and hasattr(model.model, "layers"):
layers = model.model.layers
if layers is None:
return
count = 0
for layer in layers:
if hasattr(layer, "mamba") and hasattr(layer, "set_context_parallel_attributes"):
layer.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
count += 1
if count > 0:
from prime_rl.utils.logger import get_logger
get_logger().info(f"Configured NemotronH CP on {count} Mamba layers (all-to-all head partitioning)")
get_logger().info("Configured model CP attributes")
elif _has_linear_attn_layer(model):
raise ValueError(
"Model has linear-attention/Mamba layers but does not implement "
"set_context_parallel_attributes; CP would silently misconfigure them"
)
def setup_sparse_mla_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
@@ -125,7 +94,7 @@ def setup_sparse_mla_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank:
get_logger().info(f"Configured sparse MLA CP on {count} DSA layers")
def shard_for_cp(t: torch.Tensor, cp_rank: int, cp_world_size: int) -> torch.Tensor:
def shard_for_cp(t: torch.Tensor, cp_rank: int, cp_world_size: int, seq_dim: int = 1) -> torch.Tensor:
"""
Shard a tensor for context parallelism.
Args:
@@ -136,13 +105,26 @@ def shard_for_cp(t: torch.Tensor, cp_rank: int, cp_world_size: int) -> torch.Ten
The shard of the tensor for the current rank.
"""
assert t.shape[0] == 1, "For CP, tensor must have batch dimension of 1"
if seq_dim == 1 and t.shape[0] != 1:
raise ValueError(f"For CP, tensor must have batch dimension 1, got shape={tuple(t.shape)}")
if t.shape[seq_dim] % cp_world_size != 0:
raise ValueError(
f"CP requires sequence dimension {seq_dim} to be divisible by cp size: "
f"shape={tuple(t.shape)}, cp_size={cp_world_size}; "
"uneven shards deadlock CP collectives (e.g. ulysses all-to-all)"
)
chunked_t = torch.chunk(t, cp_world_size, dim=1)
chunked_t = torch.chunk(t, cp_world_size, dim=seq_dim)
return chunked_t[cp_rank]
def shard_position_ids_for_cp(position_ids: torch.Tensor, cp_rank: int, cp_world_size: int) -> torch.Tensor:
if position_ids.ndim == 3:
return shard_for_cp(position_ids, cp_rank=cp_rank, cp_world_size=cp_world_size, seq_dim=2)
return shard_for_cp(position_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
def gather_for_cp(t: torch.Tensor, cp_group: dist.ProcessGroup) -> torch.Tensor:
gathered_t = dist_nn.all_gather(t, group=cp_group)
@@ -176,9 +158,24 @@ def setup_cp_params(
Returns the sequence-sharded input_ids and position_ids — the rest of the
model still runs sequence-sharded; only attention sees the full sequence.
"""
setup_cp_attention_params(position_ids, cp_group=cp_group, cp_style=cp_style, seq_lens=seq_lens)
input_ids = shard_for_cp(input_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
position_ids = shard_position_ids_for_cp(position_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
return input_ids, position_ids
def setup_cp_attention_params(
position_ids: torch.Tensor,
cp_group: dist.ProcessGroup,
*,
seq_lens: torch.Tensor,
cp_style: CPStyle = "ring",
) -> None:
total_tokens = position_ids.shape[-1]
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
seq_lens.to(device=position_ids.device),
total_tokens=position_ids.shape[-1],
total_tokens=total_tokens,
)
if cp_style == "ring":
@@ -191,7 +188,3 @@ def setup_cp_params(
update_ulysses_params(cu_seqlens, max_seqlen)
else:
raise ValueError(f"Unknown cp_style: {cp_style}")
input_ids = shard_for_cp(input_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
position_ids = shard_for_cp(position_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
return input_ids, position_ids
-16
View File
@@ -50,19 +50,3 @@ def get_cu_seqlens_from_seq_lens(seq_lens: torch.Tensor, total_tokens: int | Non
cu_seqlens[0] = 0
cu_seqlens[1:] = seq_lens.cumsum(dim=0, dtype=torch.int32)
return cu_seqlens, int(seq_lens.max().item())
def get_cp_local_seq_lens(
seq_lens: torch.Tensor,
total_tokens: int,
cp_rank: int,
cp_world_size: int,
) -> torch.Tensor:
"""Intersect global sequence boundaries with one contiguous CP shard."""
shard_size = total_tokens // cp_world_size
shard_start = seq_lens.new_tensor(cp_rank * shard_size)
shard_end = shard_start + shard_size
seq_ends = seq_lens.cumsum(dim=0)
seq_starts = torch.cat([seq_lens.new_zeros(1), seq_ends[:-1]])
overlaps = torch.minimum(seq_ends, shard_end) - torch.maximum(seq_starts, shard_start)
return overlaps[overlaps > 0]
+2 -1
View File
@@ -15,7 +15,8 @@ from tests.utils import (
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
TIMEOUT = 900 # 15 minutes
TIMEOUT = 1200 # 20 minutes (was 900s — alphabet-sort steps can take 2+ min
# each on contended CI GPU runners, and vLLM warm-up eats ~2 min)
@pytest.fixture(scope="module")
+2 -1
View File
@@ -15,7 +15,8 @@ from tests.utils import (
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
TIMEOUT = 600 # 10 minutes
TIMEOUT = 900 # 15 minutes (was 600s — can be tight on contended CI runners
# after verifiers per-call tracing overhead was added)
@pytest.fixture(scope="module")
@@ -15,13 +15,14 @@ from tests.utils import check_reward_goes_up, check_reward_in_range, strip_escap
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
TIMEOUT = 300 # 5 minutes
TIMEOUT = 600 # 10 minutes (was 300s — too tight when 3 concurrent orchestrators
# contend for 2 inference GPUs; verifiers per-call tracing added overhead)
ORCHESTRATOR_NAMES = ["alpha", "beta", "gamma"]
def wait_for_file(
file_path: Path,
timeout: int = 300,
timeout: int = 600,
poll_interval: float = 1.0,
) -> None:
"""Wait for file to exist.
@@ -46,7 +47,7 @@ def wait_for_log(
log_file: Path,
conditions: list[str],
proc: subprocess.Popen,
timeout: int = 300,
timeout: int = 600,
poll_interval: float = 0.1,
sigterm: bool = False,
kill: bool = False,
@@ -14,7 +14,8 @@ from tests.utils import check_final_eval_reward_above, check_no_error, strip_esc
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
TIMEOUT = 600 # 10 minutes
TIMEOUT = 900 # 15 minutes (was 600s — the OPD orchestrator finishes in ~8m but
# the rl entrypoint cleanup phase can push total wall-clock past the old limit)
REF_PORT = 8001
REF_READY_TIMEOUT_S = 300
@@ -14,7 +14,7 @@ from tests.utils import check_final_eval_reward_above, check_no_error, strip_esc
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
TIMEOUT = 600 # 10 minutes
TIMEOUT = 900 # 15 minutes (was 600s — same overhead as reverse_text)
REF_PORT = 8001
REF_READY_TIMEOUT_S = 300
+25 -1
View File
@@ -1,3 +1,5 @@
from unittest.mock import MagicMock
import pytest
import torch
from transformers.models.nemotron_h.configuration_nemotron_h import NemotronHConfig as HFNemotronHConfig
@@ -10,7 +12,8 @@ from transformers.models.nemotron_h.modeling_nemotron_h import (
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.nemotron_h import NemotronHConfig, NemotronHForCausalLM
from prime_rl.trainer.models.nemotron_h.modeling_nemotron_h import NemotronHAttentionLayer
from prime_rl.trainer.models.nemotron_h.modeling_nemotron_h import NemotronHAttentionLayer, NemotronHMambaLayer
from prime_rl.utils.cp import setup_model_cp
from prime_rl.utils.utils import default_dtype
pytestmark = [pytest.mark.gpu]
@@ -225,6 +228,27 @@ def test_nemotron_h_hybrid_override_pattern():
assert config.num_hidden_layers == 4
def test_nemotron_h_context_parallel_setup_finds_wrapped_mamba_layer():
config = NemotronHConfig(
**(_BASE | {"mamba_n_groups": 2}),
layers_block_type=["mamba", "moe", "attention", "moe"],
use_grouped_mm=False,
)
with torch.device("meta"):
model = NemotronHForCausalLM(config)
mamba_layer = model.model.layers[0]
assert isinstance(mamba_layer, NemotronHMambaLayer)
model.model.layers[0] = torch.nn.Sequential(mamba_layer)
cp_group = MagicMock()
setup_model_cp(model, cp_group, cp_rank=1, cp_world_size=2)
assert mamba_layer._cp_group is cp_group
assert mamba_layer._cp_rank == 1
assert mamba_layer._cp_world_size == 2
def test_nemotron_h_no_latent_projection():
"""Verify model works without latent projections (moe_latent_size=None)."""
prime_config = NemotronHConfig(
+65 -1
View File
@@ -3,13 +3,14 @@ from unittest.mock import MagicMock
import pytest
import torch
from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5Config, Qwen3_5TextConfig, Qwen3_5VisionConfig
from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5ForCausalLM as HFQwen3_5ForCausalLM
from prime_rl.trainer.models.layers.attn import FlashAttention, substitute_ring_attn
from prime_rl.trainer.models.qwen3_5 import Qwen3_5ForCausalLM, Qwen3_5Model
from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAttention
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig
from prime_rl.utils.cp import setup_model_cp
def _tiny_text_config(attn_impl: str = "flash_attention_2") -> Qwen3_5TextConfig:
@@ -33,6 +34,28 @@ def _tiny_text_config(attn_impl: str = "flash_attention_2") -> Qwen3_5TextConfig
return config
def _tiny_vlm_config(attn_impl: str = "flash_attention_2") -> Qwen3_5Config:
text_config = _tiny_text_config(attn_impl)
vision_config = Qwen3_5VisionConfig(
depth=1,
hidden_size=64,
intermediate_size=128,
num_heads=4,
out_hidden_size=text_config.hidden_size,
)
config = Qwen3_5Config(
text_config=text_config,
vision_config=vision_config,
image_token_id=120,
video_token_id=121,
vision_start_token_id=122,
vision_end_token_id=123,
)
config._attn_implementation = attn_impl
config.text_config._attn_implementation = attn_impl
return config
def _tiny_moe_config(attn_impl: str = "flash_attention_2") -> Qwen3_5MoeConfig:
config = Qwen3_5MoeConfig(
vocab_size=128,
@@ -95,6 +118,47 @@ def test_qwen3_5_moe_full_attention_normalizes_fa3_hub_alias():
assert model.config._attn_implementation == "flash_attention_3"
def test_qwen3_5_context_parallel_setup_chain_text_and_vlm():
cp_group = MagicMock()
text_model = Qwen3_5ForCausalLM(_tiny_text_config())
linear_layer = text_model.model.layers[0]
text_model.model.layers[0] = torch.nn.Sequential(linear_layer)
setup_model_cp(text_model, cp_group, cp_rank=1, cp_world_size=2)
assert text_model.model._cp_group is cp_group
assert text_model.model._cp_rank == 1
assert text_model.model._cp_world_size == 2
assert linear_layer.linear_attn.cp_group is cp_group
vlm_config = _tiny_vlm_config()
vlm_config.vision_config._attn_implementation = "sdpa"
vlm_config.vision_config._attn_implementation_internal = "sdpa"
with torch.device("meta"):
vlm_model = Qwen3_5ForCausalLM(vlm_config)
setup_model_cp(vlm_model, cp_group, cp_rank=0, cp_world_size=2)
assert vlm_model.model.language_model._cp_group is cp_group
assert vlm_model.model.language_model.layers[0].linear_attn.cp_world_size == 2
def test_setup_model_cp_requires_hook_only_for_hybrid_models():
class HybridLayer(torch.nn.Module):
layer_type = "linear_attention"
class Inner:
layers = torch.nn.Sequential(torch.nn.Sequential(HybridLayer()))
class HybridNoHookModel:
model = Inner()
with pytest.raises(ValueError, match="set_context_parallel_attributes"):
setup_model_cp(HybridNoHookModel(), MagicMock(), cp_rank=0, cp_world_size=2)
class SoftmaxOnlyModel:
pass
setup_model_cp(SoftmaxOnlyModel(), MagicMock(), cp_rank=0, cp_world_size=2)
def test_qwen3_5_ring_patches_dense_flash_attention():
from prime_rl.trainer.models.afmoe.modeling_afmoe import AfmoeFlashAttention
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
@@ -5,6 +5,7 @@ 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.cp import setup_model_cp
from prime_rl.utils.utils import default_dtype
pytestmark = [pytest.mark.gpu]
@@ -146,5 +147,44 @@ def test_qwen3_5_moe_cp_patching():
cls._compute_attention = method
def test_qwen3_5_moe_context_parallel_setup_hook():
from unittest.mock import MagicMock
config = Qwen3_5MoeConfig(
vocab_size=128,
hidden_size=64,
num_hidden_layers=2,
layer_types=["linear_attention", "full_attention"],
num_attention_heads=4,
num_key_value_heads=2,
head_dim=16,
moe_intermediate_size=64,
shared_expert_intermediate_size=64,
num_experts=4,
num_experts_per_tok=2,
max_position_embeddings=128,
linear_conv_kernel_dim=4,
linear_key_head_dim=8,
linear_value_head_dim=8,
linear_num_key_heads=4,
linear_num_value_heads=8,
use_grouped_mm=False,
)
config._attn_implementation = "flash_attention_2"
with torch.device("meta"):
model = PrimeRLQwen3_5MoeForCausalLM(config)
linear_layer = model.model.layers[0]
model.model.layers[0] = torch.nn.Sequential(linear_layer)
cp_group = MagicMock()
setup_model_cp(model, cp_group, cp_rank=1, cp_world_size=2)
assert model.model._cp_group is cp_group
assert model.model._cp_rank == 1
assert model.model._cp_world_size == 2
assert linear_layer.linear_attn.cp_group is cp_group
assert linear_layer.linear_attn.cp_world_size == 2
if __name__ == "__main__":
test_qwen3_5_moe()
@@ -197,48 +197,6 @@ def test_vlm_weight_roundtrip():
assert torch.equal(roundtripped[original_vision_key], original_vision_weight)
def test_vlm_forward_requires_mm_token_type_ids():
"""Image MRoPE needs renderer-supplied modality token types."""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.bfloat16):
model = Qwen3_5MoeForCausalLM(config)
inject_prime_lm_head(model)
pixel_values, image_grid_thw, n_img_tokens = _make_image_inputs(config)
input_ids = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
with pytest.raises(ValueError, match="mm_token_type_ids"):
model(
input_ids=input_ids,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
seq_lens=_seq_lens(input_ids),
)
def test_vlm_forward_rejects_2d_positions_with_images():
"""Trainer 1D/2D packed positions are not valid image MRoPE coordinates."""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.bfloat16):
model = Qwen3_5MoeForCausalLM(config)
inject_prime_lm_head(model)
pixel_values, image_grid_thw, n_img_tokens = _make_image_inputs(config)
input_ids = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
mm_token_type_ids = _make_mm_token_type_ids(input_ids, config.image_token_id)
position_ids = torch.arange(n_img_tokens, device="cuda").unsqueeze(0)
with pytest.raises(ValueError, match="3D MRoPE position_ids"):
model(
input_ids=input_ids,
position_ids=position_ids,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
seq_lens=_seq_lens(input_ids),
)
def test_vlm_router_replay():
"""routed_experts bypasses router computation in VLM multimodal forward."""
config = _tiny_vlm_config()
+107 -2
View File
@@ -1,12 +1,14 @@
from collections import Counter
import pytest
import torch
from datasets import Dataset, interleave_datasets
from renderers import create_renderer
from renderers.base import RenderedTokens
from renderers.base import MultiModalData, PlaceholderRange, RenderedTokens, RenderedTrainingSample
from transformers import AutoTokenizer
from prime_rl.trainer.sft.data import SFTDataset, _drop_null_fields
import prime_rl.trainer.sft.data as sft_data
from prime_rl.trainer.sft.data import CatDataset, SFTDataset, _drop_null_fields
from prime_rl.trainer.utils import print_sample
_BOS_TOKEN_ID = 0
@@ -399,3 +401,106 @@ def test_null_messages_falls_back_to_prompt_and_completion():
)
assert next(iter(mixed_row_dataset)) == next(iter(expected_dataset))
def test_vlm_truncation_does_not_append_trainable_eos(monkeypatch):
mm = MultiModalData(
mm_placeholders={"image": [PlaceholderRange(offset=1, length=1)]},
mm_items={"image": [{"pixel_values": torch.ones(1, 1), "image_grid_thw": torch.tensor([[1, 1, 1]])}]},
)
def fake_build_training_sample(*args, **kwargs):
return RenderedTrainingSample(
token_ids=[10, 11, 12, _STOP_TOKEN_ID],
loss_mask=[False, False, False, True],
multi_modal_data=mm,
mm_token_type_ids=[0, 1, 0, 0],
)
monkeypatch.setattr(sft_data, "build_training_sample", fake_build_training_sample)
dataset = SFTDataset(Dataset.from_list([]), _DummyRenderer(), seq_len=2, multimodal=True)
assert dataset._process({"messages": [{"role": "assistant", "content": "ignored"}]}) is None
def _sft_sample(
input_ids: list[int],
*,
mm_kwargs: dict[str, torch.Tensor] | None = None,
mm_token_type_ids: list[int] | None = None,
) -> dict:
return {
"input_ids": input_ids,
"position_ids": list(range(len(input_ids))),
"loss_mask": [True] * len(input_ids),
"target_ids": [x + 1 for x in input_ids],
"seq_lens": [len(input_ids)],
"mm_kwargs": mm_kwargs,
"mm_token_type_ids": mm_token_type_ids,
}
def test_cat_dataset_packs_multimodal_samples():
dataset = CatDataset(
[
_sft_sample(
[1, 2],
mm_kwargs={
"pixel_values": torch.ones(2, 3),
"image_grid_thw": torch.tensor([[1, 1, 2]]),
},
mm_token_type_ids=[0, 1],
),
_sft_sample(
[3, 4, 5],
mm_kwargs={
"pixel_values": 2 * torch.ones(3, 3),
"image_grid_thw": torch.tensor([[1, 1, 3]]),
},
mm_token_type_ids=[0, 1, 1],
),
],
seq_len=5,
)
packed = next(iter(dataset))
assert packed["input_ids"] == [1, 2, 3, 4, 5]
assert packed["seq_lens"] == [2, 3]
assert packed["mm_token_type_ids"] == [0, 1, 0, 1, 1]
assert packed["mm_kwargs"]["pixel_values"].shape == (5, 3)
assert packed["mm_kwargs"]["image_grid_thw"].tolist() == [[1, 1, 2], [1, 1, 3]]
def test_cat_dataset_packs_text_and_multimodal_samples_together():
dataset = CatDataset(
[
_sft_sample([1]),
_sft_sample(
[2, 3],
mm_kwargs={
"pixel_values": torch.ones(2, 3),
"image_grid_thw": torch.tensor([[1, 1, 2]]),
},
mm_token_type_ids=[0, 1],
),
_sft_sample([4]),
_sft_sample([5, 6]),
],
seq_len=5,
)
dataiter = iter(dataset)
packed = next(dataiter)
text_pack = next(dataiter)
assert packed["input_ids"] == [1, 2, 3, 4, 0]
assert packed["loss_mask"] == [True, True, True, True, False]
assert packed["seq_lens"] == [1, 2, 2]
assert packed["mm_kwargs"] is not None
assert packed["mm_token_type_ids"] == [0, 0, 1, 0, 0]
assert text_pack["input_ids"] == [5, 6, 0, 0, 0]
assert text_pack["loss_mask"] == [True, True, False, False, False]
assert text_pack["seq_lens"] == [5]
assert text_pack["mm_kwargs"] is None
assert text_pack["mm_token_type_ids"] is None
-8
View File
@@ -2,7 +2,6 @@ import pytest
import torch
from prime_rl.utils.sequence import (
get_cp_local_seq_lens,
get_cu_seqlens_from_position_ids,
get_cu_seqlens_from_seq_lens,
)
@@ -40,10 +39,3 @@ def test_get_cu_seqlens_from_seq_lens():
def test_get_cu_seqlens_from_seq_lens_rejects_wrong_total():
with pytest.raises(ValueError, match="sum must equal"):
get_cu_seqlens_from_seq_lens(torch.tensor([4, 3]), total_tokens=9)
@pytest.mark.parametrize(("cp_rank", "expected"), [(0, [3, 1]), (1, [4])])
def test_get_cp_local_seq_lens(cp_rank: int, expected: list[int]):
local_seq_lens = get_cp_local_seq_lens(torch.tensor([3, 5]), 8, cp_rank, 2)
assert local_seq_lens.tolist() == expected
Generated
+124 -62
View File
@@ -51,6 +51,7 @@ members = [
"compact",
"deepdive-v1",
"deepwiki-v1",
"enterprise-ops-gym-v1",
"forth-lang-v1",
"frontierscience-v1",
"general-agent-v1",
@@ -59,6 +60,7 @@ members = [
"graphwalks-v1",
"gsm8k-v1",
"hle-v1",
"humaneval-v1",
"i3-code-v1",
"i3-logic-v1",
"i3-math-v1",
@@ -75,6 +77,7 @@ members = [
"math500-v1",
"mcp-atlas-v1",
"mmlu-pro-v1",
"mmmu-v1",
"mrcr-v2-v1",
"multiswe-v1",
"nl2repobench-v1",
@@ -101,6 +104,7 @@ members = [
"senior-swe-bench-v1",
"simpleqa-v1",
"simpleqa-verified-v1",
"swebench-multilingual-v1",
"swebench-pro-v1",
"swebench-verified-v1",
"swelego-v1",
@@ -110,6 +114,7 @@ members = [
"terminal-bench-2-v1",
"terminal-lego-v1",
"tmax-v1",
"triviaqa-v1",
"unscramble-v1",
"uuid-ctf-v1",
"verbatim-copy-v1",
@@ -475,7 +480,7 @@ requires-dist = [
{ name = "datasets" },
{ name = "mcp", specifier = "<2" },
{ name = "openai" },
{ name = "verifiers", specifier = ">=0.2.1.dev42" },
{ name = "verifiers", specifier = ">=0.2.1" },
]
[[package]]
@@ -1010,7 +1015,7 @@ dependencies = [
[package.metadata]
requires-dist = [
{ name = "pillow" },
{ name = "pillow", specifier = ">=11.0.0" },
{ name = "verifiers" },
]
@@ -1597,6 +1602,21 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e1/5e/4b5aaaabddfacfe36ba7768817bd1f71a7a810a43705e531f3ae4c690767/emoji-2.15.0-py3-none-any.whl", hash = "sha256:205296793d66a89d88af4688fa57fd6496732eb48917a87175a023c8138995eb", size = 608433, upload-time = "2025-09-21T12:13:01.197Z" },
]
[[package]]
name = "enterprise-ops-gym-v1"
version = "0.1.0"
source = { editable = "deps/research-environments/environments/tool_use/enterprise_ops_gym_v1" }
dependencies = [
{ name = "datasets" },
{ name = "verifiers" },
]
[package.metadata]
requires-dist = [
{ name = "datasets", specifier = ">=4.0.0,<5" },
{ name = "verifiers", specifier = ">=0.2.0" },
]
[[package]]
name = "eval-type-backport"
version = "0.4.0"
@@ -2535,6 +2555,21 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/49/79/621a7dbb80c70974f73a597275351ebe03ce5bc65cb5f8f4acb5859252bc/huggingface_hub-1.16.1-py3-none-any.whl", hash = "sha256:64340de934b9ce37857ef85a82de72f5629e8a270f9119eabb12bf495eb53c22", size = 668176, upload-time = "2026-05-21T18:39:58.596Z" },
]
[[package]]
name = "humaneval-v1"
version = "0.1.0"
source = { editable = "deps/research-environments/environments/code/humaneval_v1" }
dependencies = [
{ name = "datasets" },
{ name = "verifiers" },
]
[package.metadata]
requires-dist = [
{ name = "datasets" },
{ name = "verifiers", specifier = ">=0.2.0" },
]
[[package]]
name = "humming-kernels"
version = "0.1.6"
@@ -3726,6 +3761,23 @@ requires-dist = [
{ name = "verifiers", specifier = ">=0.2.0" },
]
[[package]]
name = "mmmu-v1"
version = "0.1.0"
source = { editable = "deps/research-environments/environments/knowledge/mmmu_v1" }
dependencies = [
{ name = "datasets" },
{ name = "pillow" },
{ name = "verifiers" },
]
[package.metadata]
requires-dist = [
{ name = "datasets" },
{ name = "pillow" },
{ name = "verifiers", specifier = ">=0.2.0" },
]
[[package]]
name = "modal"
version = "1.5.1"
@@ -3908,7 +3960,7 @@ wheels = [
[[package]]
name = "multiswe-v1"
version = "0.1.0"
version = "0.1.2"
source = { editable = "deps/research-environments/environments/swe/multiswe_v1" }
dependencies = [
{ name = "datasets" },
@@ -3920,7 +3972,7 @@ dependencies = [
requires-dist = [
{ name = "datasets" },
{ name = "multi-swe-bench" },
{ name = "verifiers", specifier = ">=0.2.0" },
{ name = "verifiers", specifier = ">=0.2.2.dev5" },
]
[[package]]
@@ -4579,7 +4631,7 @@ requires-dist = [
[[package]]
name = "openswe-v1"
version = "0.1.0"
version = "0.1.2"
source = { editable = "deps/research-environments/environments/swe/openswe_v1" }
dependencies = [
{ name = "datasets" },
@@ -4591,7 +4643,7 @@ dependencies = [
requires-dist = [
{ name = "datasets" },
{ name = "huggingface-hub" },
{ name = "verifiers", specifier = ">=0.2.0" },
{ name = "verifiers", specifier = ">=0.2.2.dev5" },
]
[[package]]
@@ -4728,7 +4780,7 @@ dependencies = [
]
[package.metadata]
requires-dist = [{ name = "verifiers", specifier = ">=0.2.0" }]
requires-dist = [{ name = "verifiers", specifier = ">=0.2.1" }]
[[package]]
name = "orderly-set"
@@ -5038,7 +5090,6 @@ wheels = [
[[package]]
name = "prime-pydantic-config"
version = "0.3.0"
source = { editable = "deps/pydantic-config" }
dependencies = [
{ name = "pydantic" },
@@ -5057,7 +5108,7 @@ requires-dist = [
{ name = "tomli", marker = "extra == 'all'" },
{ name = "tomli", marker = "extra == 'toml'" },
]
provides-extras = ["yaml", "toml", "all"]
provides-extras = ["all", "toml", "yaml"]
[package.metadata.requires-dev]
dev = [
@@ -5265,12 +5316,12 @@ dependencies = [
[package.metadata]
requires-dist = [
{ name = "prime-pydantic-config", specifier = ">=0.3.0.dev82" },
{ name = "prime-pydantic-config", specifier = ">=0.4.2" },
{ name = "pydantic", specifier = ">=1.10.13" },
{ name = "renderers", specifier = ">=0.1.8.dev28" },
{ name = "renderers", specifier = ">=0.1.8" },
{ name = "tomli", specifier = ">=2.2.1" },
{ name = "tomli-w", specifier = ">=1.2.0" },
{ name = "verifiers", specifier = ">=0.2.0" },
{ name = "verifiers", specifier = ">=0.2.1" },
]
[[package]]
@@ -5948,7 +5999,7 @@ wheels = [
[[package]]
name = "r2e-gym-v1"
version = "0.1.0"
version = "0.1.2"
source = { editable = "deps/research-environments/environments/swe/r2e_gym_v1" }
dependencies = [
{ name = "datasets" },
@@ -5958,7 +6009,7 @@ dependencies = [
[package.metadata]
requires-dist = [
{ name = "datasets" },
{ name = "verifiers", specifier = ">=0.2.0" },
{ name = "verifiers", specifier = ">=0.2.2.dev5" },
]
[[package]]
@@ -6263,7 +6314,7 @@ wheels = [
[[package]]
name = "scaleswe-v1"
version = "0.1.0"
version = "0.1.2"
source = { editable = "deps/research-environments/environments/swe/scaleswe_v1" }
dependencies = [
{ name = "datasets" },
@@ -6273,7 +6324,7 @@ dependencies = [
[package.metadata]
requires-dist = [
{ name = "datasets" },
{ name = "verifiers", specifier = ">=0.2.0" },
{ name = "verifiers", specifier = ">=0.2.2.dev5" },
]
[[package]]
@@ -6392,7 +6443,7 @@ dependencies = [
]
[package.metadata]
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.2.1.dev40" }]
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.2.1" }]
[[package]]
name = "sentence-transformers"
@@ -6801,6 +6852,17 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/36/67/981d8b642ac3eac7c8a7b7832ff8b2fb74f96b28b5fcd9a8979879e5c46d/swebench-4.1.0-py3-none-any.whl", hash = "sha256:1243776f720047cc9e20a427f7a52b75c13a07abda6154fb60fe77f82ec8af57", size = 157231, upload-time = "2025-09-11T02:57:58.953Z" },
]
[[package]]
name = "swebench-multilingual-v1"
version = "0.1.0"
source = { editable = "deps/research-environments/environments/swe/swebench_multilingual_v1" }
dependencies = [
{ name = "verifiers", extra = ["harbor"] },
]
[package.metadata]
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.2.1" }]
[[package]]
name = "swebench-pro-v1"
version = "0.1.0"
@@ -6810,7 +6872,7 @@ dependencies = [
]
[package.metadata]
requires-dist = [{ name = "verifiers", specifier = ">=0.2.0" }]
requires-dist = [{ name = "verifiers", specifier = ">=0.2.1" }]
[[package]]
name = "swebench-verified-v1"
@@ -6821,11 +6883,11 @@ dependencies = [
]
[package.metadata]
requires-dist = [{ name = "verifiers", specifier = ">=0.2.0" }]
requires-dist = [{ name = "verifiers", specifier = ">=0.2.1" }]
[[package]]
name = "swelego-v1"
version = "0.1.0"
version = "0.1.2"
source = { editable = "deps/research-environments/environments/swe/swelego_v1" }
dependencies = [
{ name = "datasets" },
@@ -6835,12 +6897,12 @@ dependencies = [
[package.metadata]
requires-dist = [
{ name = "datasets" },
{ name = "verifiers", specifier = ">=0.2.0" },
{ name = "verifiers", specifier = ">=0.2.2.dev5" },
]
[[package]]
name = "swerebench-v2-v1"
version = "0.1.0"
version = "0.1.2"
source = { editable = "deps/research-environments/environments/swe/swerebench_v2_v1" }
dependencies = [
{ name = "datasets" },
@@ -6850,7 +6912,7 @@ dependencies = [
[package.metadata]
requires-dist = [
{ name = "datasets" },
{ name = "verifiers", specifier = ">=0.2.0" },
{ name = "verifiers", specifier = ">=0.2.2.dev5" },
]
[[package]]
@@ -6860,7 +6922,7 @@ source = { git = "https://github.com/SWE-bench/SWE-smith.git?rev=9b74ac0#9b74ac0
[[package]]
name = "swesmith-v1"
version = "0.1.0"
version = "0.1.2"
source = { editable = "deps/research-environments/environments/swe/swesmith_v1" }
dependencies = [
{ name = "datasets" },
@@ -6874,7 +6936,7 @@ requires-dist = [
{ name = "datasets" },
{ name = "swebench" },
{ name = "swesmith", git = "https://github.com/SWE-bench/SWE-smith.git?rev=9b74ac0" },
{ name = "verifiers", specifier = ">=0.2.0" },
{ name = "verifiers", specifier = ">=0.2.2.dev5" },
]
[[package]]
@@ -7015,7 +7077,7 @@ dependencies = [
]
[package.metadata]
requires-dist = [{ name = "verifiers", specifier = ">=0.2.0" }]
requires-dist = [{ name = "verifiers", specifier = ">=0.2.1" }]
[[package]]
name = "terminal-lego-v1"
@@ -7490,6 +7552,21 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/ab/a8/cdf8b3e4c98132f965f88c2313a4b493266832ad47fb52f23d14d4f86bb5/triton-3.6.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:74caf5e34b66d9f3a429af689c1c7128daba1d8208df60e81106b115c00d6fca", size = 188266850, upload-time = "2026-01-20T16:00:43.041Z" },
]
[[package]]
name = "triviaqa-v1"
version = "0.1.0"
source = { editable = "deps/research-environments/environments/knowledge/triviaqa_v1" }
dependencies = [
{ name = "datasets" },
{ name = "verifiers" },
]
[package.metadata]
requires-dist = [
{ name = "datasets" },
{ name = "verifiers", specifier = ">=0.2.0" },
]
[[package]]
name = "typeguard"
version = "4.5.2"
@@ -7735,6 +7812,7 @@ dependencies = [
{ name = "setproctitle" },
{ name = "tenacity" },
{ name = "tomli-w" },
{ name = "typing-extensions" },
{ name = "uvloop", marker = "platform_python_implementation != 'PyPy'" },
]
@@ -7752,73 +7830,57 @@ ta = [
[package.metadata]
requires-dist = [
{ name = "accelerate", marker = "extra == 'rl'", specifier = ">=1.4.0" },
{ name = "aiohttp", specifier = ">=3.9.0" },
{ name = "aiohttp", marker = "extra == 'browser'", specifier = ">=3.9.0" },
{ name = "aiolimiter", specifier = ">=1.2.1" },
{ name = "anthropic", specifier = ">=0.78.0" },
{ name = "certifi", marker = "extra == 'quest'" },
{ name = "datasets", specifier = ">=3.0.0,<4.7.0" },
{ name = "deepspeed", marker = "extra == 'rl'", specifier = ">=0.17.6" },
{ name = "flash-attn", marker = "extra == 'rl'", specifier = ">=2.8.3" },
{ name = "gepa" },
{ name = "datasets", specifier = ">=3.3.0,<6.0.0" },
{ name = "gepa", specifier = ">=0.0.6" },
{ name = "harbor", marker = "python_full_version >= '3.12' and extra == 'harbor'", specifier = "==0.14.0" },
{ name = "httpx", specifier = ">=0.27.0" },
{ name = "liger-kernel", marker = "extra == 'rl'", specifier = ">=0.5.10" },
{ name = "loguru", specifier = ">=0.7.0" },
{ name = "math-verify", specifier = ">=0.8.0" },
{ name = "mcp", specifier = ">=1.14.1" },
{ name = "mcp", specifier = ">=1.24.0,<2" },
{ name = "modal", marker = "extra == 'modal'", specifier = ">=1.4.0" },
{ name = "msgpack", specifier = ">=1.1.2" },
{ name = "nest-asyncio", marker = "extra == 'notebook'", specifier = ">=1.6.0" },
{ name = "nltk", marker = "extra == 'ta'", specifier = ">=3.9.2" },
{ name = "numpy" },
{ name = "openai", specifier = ">=1.108.1" },
{ name = "openai-agents", specifier = ">=0.0.7" },
{ name = "numpy", specifier = ">=2.1.0" },
{ name = "openai", specifier = ">=2.9.0" },
{ name = "openai-agents", specifier = ">=0.8.2" },
{ name = "openenv", marker = "extra == 'openenv'", specifier = ">=0.4.1" },
{ name = "peft", marker = "extra == 'rl'" },
{ name = "pillow", marker = "extra == 'quest'" },
{ name = "prime-pydantic-config", extras = ["toml"], specifier = ">=0.3.0.dev86" },
{ name = "prime-pydantic-config", extras = ["toml"], specifier = ">=0.4.2" },
{ name = "prime-sandboxes", specifier = ">=0.2.31" },
{ name = "prime-tunnel", specifier = ">=0.1.8" },
{ name = "pydantic", specifier = ">=2.11.9" },
{ name = "pymupdf", marker = "extra == 'quest'" },
{ name = "pydantic", specifier = ">=2.12.3" },
{ name = "python-dotenv", marker = "extra == 'browser'", specifier = ">=1.0.0" },
{ name = "pyzmq", specifier = ">=27.1.0" },
{ name = "reasoning-gym", marker = "extra == 'rg'" },
{ name = "reasoning-gym", marker = "extra == 'rg'", specifier = ">=0.1.8" },
{ name = "renderers", specifier = ">=0.1.8" },
{ name = "requests" },
{ name = "requests", marker = "extra == 'rl'" },
{ name = "rich" },
{ name = "rich", specifier = ">=11.0.0" },
{ name = "setproctitle", specifier = ">=1.3.0" },
{ name = "stagehand", marker = "extra == 'browser'", specifier = ">=3.0.0" },
{ name = "stagehand", marker = "extra == 'browser'", specifier = ">=3.4.0" },
{ name = "tenacity", specifier = ">=8.5.0" },
{ name = "textarena", marker = "extra == 'ta'", specifier = "==0.7.4" },
{ name = "tomli-w", specifier = ">=1.0.0" },
{ name = "torch", marker = "extra == 'rl'", specifier = ">=2.8.0,<2.9.0" },
{ name = "transformers", marker = "extra == 'rl'", specifier = ">=4.56.2" },
{ name = "typing-extensions", marker = "python_full_version < '3.12'" },
{ name = "typing-extensions", specifier = ">=4.12.2" },
{ name = "uvloop", marker = "platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32'", specifier = ">=0.21.0" },
{ name = "vllm", marker = "extra == 'rl'", specifier = ">=0.10.0,<0.11.0" },
{ name = "wandb", marker = "extra == 'rl'" },
]
provides-extras = ["browser", "harbor", "modal", "notebook", "openenv", "quest", "rg", "rl", "ta"]
provides-extras = ["browser", "harbor", "modal", "notebook", "openenv", "rg", "ta"]
[package.metadata.requires-dev]
dev = [
{ name = "aiohttp", specifier = ">=3.9.0" },
{ name = "ipykernel" },
{ name = "ipywidgets" },
{ name = "nest-asyncio", specifier = ">=1.6.0" },
{ name = "nltk", specifier = ">=3.9.2" },
{ name = "pre-commit" },
{ name = "pytest", specifier = ">=7.0.0" },
{ name = "pre-commit", specifier = ">=2.19.0" },
{ name = "pytest", specifier = ">=7.0.0,<9.1.0" },
{ name = "pytest-asyncio", specifier = ">=0.21.0" },
{ name = "pytest-cov", specifier = ">=4.0.0" },
{ name = "pytest-xdist", specifier = ">=3.8.0" },
{ name = "python-dotenv", specifier = ">=1.0.0" },
{ name = "reasoning-gym" },
{ name = "ruff" },
{ name = "stagehand", specifier = ">=3.0.0" },
{ name = "reasoning-gym", specifier = ">=0.1.8" },
{ name = "ruff", specifier = ">=0.9.0" },
{ name = "stagehand", specifier = ">=3.4.0" },
{ name = "textarena", specifier = "==0.7.4" },
{ name = "ty", specifier = ">=0.0.1a29,<0.0.22" },
]
@@ -8469,7 +8531,7 @@ dependencies = [
[package.metadata]
requires-dist = [
{ name = "chromadb" },
{ name = "chromadb", specifier = ">=0.4.13" },
{ name = "datasets" },
{ name = "verifiers" },
]