Compare commits

...
Author SHA1 Message Date
8fa0dde0be feat: make max_retries configurable per training env (#2025)
Release / Push CUDA image to Docker (push) Canceled after 0s
Move max_retries from EvalEnvConfig to EnvConfig so it applies to both
training and eval environments. The scheduler now looks up max_retries
per task from the env config instead of hardcoding 0.

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

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

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

* remove vflm warning

* feat: add custom VLM support for Qwen 3.5 MoE

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

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

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

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

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

* fix: support VLM layer key format in weight broadcast

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

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

* use registry-based approach

* run ruff

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

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

---------

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

* fix: cancel inflight scheduler policy update on stop

---------

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

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

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

* fix: print error_chain_repr instead of full error dict

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

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

* simplify: index directly into error dict

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

* feat: make errored_rollouts and empty_rollouts metrics rates per step

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

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

---------

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

* Set default connect_timeout to 30s and add CHANGELOG entry

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

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: rasdani <rasdani@users.noreply.github.com>
2026-03-12 00:29:07 +01:00
21 changed files with 1970 additions and 102 deletions
+1
View File
@@ -2,6 +2,7 @@
Documenting changes which affect configuration usage patterns (added/moved/removed/renamed fields, notable logic changes).
- **`client.connect_timeout`**: Added configurable TCP connect timeout for inference API requests (default: 30.0s). Previously hardcoded to 5.0s. Helps with vLLM or cluster flakiness (2026-03-11)
- **`model.fused_lm_head_token_chunk_size`**: Added as the fused LM-head chunking field for the token-chunked implementation. Unlike the removed `model.fused_lm_head_chunk_size`, this chunks over flattened sequence tokens rather than vocabulary rows. `model.fused_lm_head_chunk_size` is no longer accepted; switch configs to `model.fused_lm_head_token_chunk_size` explicitly. (2026-03-09)
- **`slurm.pre_run_command`**: Added optional shell command to run on the head node before starting the job. Useful for cleanup routines (e.g. killing stale processes, removing lock files). For all-nodes execution, wrap with `srun` in the command string (default: None) (2026-03-08)
- **`slurm.nodelist`**, **`slurm.exclude`**, **`slurm.account`**, **`slurm.time`**: Added common SLURM scheduling options (all default: None) (2026-03-08)
+91 -17
View File
@@ -17,17 +17,60 @@ from pathlib import Path
import torch
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
from transformers import Glm4MoeForCausalLM as HFGlm4MoeForCausalLM
from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import (
Qwen3_5MoeForConditionalGeneration as HFQwen3_5MoeVLM,
)
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig
from prime_rl.trainer.models.glm4_moe import Glm4MoeForCausalLM as PrimeRLGlm4MoeForCausalLM
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2ForCausalLM as PrimeRLMiniMaxM2ForCausalLM
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeForCausalLM as PrimeRLQwen3_5MoeVLM
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.utils import default_dtype
setup_logger("info")
def _qwen3_5_moe_vlm_config():
"""Build a tiny composite VLM config for Qwen3.5 MoE."""
config = AutoConfig.from_pretrained("Qwen/Qwen3.5-35B-A3B", trust_remote_code=True, attn_implementation="sdpa")
config.use_cache = False
tc = config.text_config
tc.vocab_size = 256
tc.hidden_size = 256
tc.num_hidden_layers = 2
tc.num_attention_heads = 4
tc.num_key_value_heads = 2
tc.head_dim = 64
tc.moe_intermediate_size = 128
tc.shared_expert_intermediate_size = 128
tc.num_experts = 4
tc.num_experts_per_tok = 2
tc.max_position_embeddings = 512
tc.linear_key_head_dim = 32
tc.linear_value_head_dim = 32
tc.linear_num_key_heads = 4
tc.linear_num_value_heads = 8
tc.layer_types = ["full_attention", "linear_attention"]
tc.use_cache = False
vc = config.vision_config
vc.depth = 2
vc.hidden_size = 128
vc.intermediate_size = 256
vc.num_heads = 4
vc.out_hidden_size = tc.hidden_size
config.image_token_id = 250
config.video_token_id = 251
config.vision_start_token_id = 252
config.vision_end_token_id = 253
return config
ARCH_PRESETS = {
"glm4_moe": {
"config_class": Glm4MoeConfig,
@@ -87,6 +130,13 @@ ARCH_PRESETS = {
"prime_model_class": PrimeRLMiniMaxM2ForCausalLM,
"tokenizer_source": "MiniMaxAI/MiniMax-M2.1",
},
"qwen3_5_moe_vlm": {
"config_fn": _qwen3_5_moe_vlm_config,
"hf_model_class": HFQwen3_5MoeVLM,
"prime_model_class": PrimeRLQwen3_5MoeVLM,
"tokenizer_source": "Qwen/Qwen3.5-35B-A3B",
"is_vlm": True,
},
# glm_moe_dsa: HF implementation is incorrect, not supported here
}
@@ -115,12 +165,20 @@ def _create_hf_model_from_config(preset, config):
return AutoModelForCausalLM.from_config(config, trust_remote_code=True)
def _build_config(preset):
"""Build model config from preset (handles both config_class and config_fn styles)."""
if "config_fn" in preset:
return preset["config_fn"]()
return preset["config_class"](**preset["config_kwargs"])
def create(arch: str, output_dir: Path) -> None:
preset = ARCH_PRESETS[arch]
config = preset["config_class"](**preset["config_kwargs"])
config = _build_config(preset)
text_config = getattr(config, "text_config", config)
print(f"Creating mini {arch} model...")
print(f" hidden_size={config.hidden_size}, layers={config.num_hidden_layers}")
print(f" hidden_size={text_config.hidden_size}, layers={text_config.num_hidden_layers}")
with torch.device("cpu"):
model = _create_hf_model(preset, config)
@@ -139,14 +197,20 @@ def create(arch: str, output_dir: Path) -> None:
def verify(arch: str, model_dir: Path) -> None:
preset = ARCH_PRESETS[arch]
is_vlm = preset.get("is_vlm", False)
print(f"Verifying HF <-> PrimeRL roundtrip for {model_dir}...")
trust_remote_code = preset["hf_model_class"] is None
config = AutoConfig.from_pretrained(str(model_dir), trust_remote_code=trust_remote_code)
config._attn_implementation = "sdpa"
if hasattr(config, "text_config"):
config.text_config._attn_implementation = "sdpa"
text_config = getattr(config, "text_config", config)
vocab_size = text_config.vocab_size
hf_model = _load_hf_model(preset, model_dir, config).to(device="cuda", dtype=torch.float32)
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = _load_hf_model(preset, model_dir, config)
prime_model = preset["prime_model_class"]._from_config(config)
with torch.no_grad():
@@ -156,29 +220,39 @@ def verify(arch: str, model_dir: Path) -> None:
inject_prime_lm_head(prime_model, chunk_size=None)
# Use tokens in safe range (avoid special VLM token IDs)
max_token = min(vocab_size, 200) if is_vlm else vocab_size
with torch.device("cuda"), default_dtype(torch.float32):
input_ids = torch.randint(0, config.vocab_size, (1, 64))
input_ids = torch.randint(0, max_token, (1, 64))
position_ids = torch.arange(1, 65).unsqueeze(0)
hf_output = hf_model(input_ids=input_ids, position_ids=position_ids)
prime_output = prime_model(input_ids, position_ids)
logits_diff = prime_output["logits"] - hf_output.logits
max_diff = logits_diff.abs().max().item()
print(f" HF vs PrimeRL max logits diff: {max_diff:.6f}")
assert max_diff < 0.1, f"HF vs PrimeRL logits mismatch: max diff {max_diff}"
if is_vlm:
# HF GatedDeltaNet has a dtype bug in float32 mode; just verify non-NaN output
assert not torch.isnan(prime_output["logits"]).any(), "PrimeRL VLM output contains NaN"
assert prime_output["logits"].shape == hf_output.logits.shape
print(" VLM forward pass verified (shape match, no NaN)")
else:
logits_diff = prime_output["logits"] - hf_output.logits
max_diff = logits_diff.abs().max().item()
print(f" HF vs PrimeRL max logits diff: {max_diff:.6f}")
assert max_diff < 0.1, f"HF vs PrimeRL logits mismatch: max diff {max_diff}"
# Roundtrip weight conversion: HF -> PrimeRL -> HF
# Normalize both through the same roundtrip to handle expert format differences
prime_cls = preset["prime_model_class"]
with torch.no_grad():
roundtrip_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
with torch.device("cuda"), default_dtype(torch.float32):
hf_roundtrip = _create_hf_model_from_config(preset, config)
hf_roundtrip.load_state_dict(roundtrip_state_dict)
roundtrip_sd = prime_cls.convert_to_hf(dict(prime_model.state_dict()))
orig_sd = dict(hf_model.state_dict())
prime_cls.convert_to_prime(orig_sd)
prime_cls.convert_to_hf(orig_sd)
hf_roundtrip_output = hf_roundtrip(input_ids=input_ids, position_ids=position_ids)
roundtrip_diff = hf_roundtrip_output.logits - hf_output.logits
max_roundtrip_diff = roundtrip_diff.abs().max().item()
print(f" HF -> PrimeRL -> HF roundtrip max logits diff: {max_roundtrip_diff:.6f}")
assert max_roundtrip_diff < 0.1, f"Roundtrip logits mismatch: max diff {max_roundtrip_diff}"
for key in orig_sd:
assert key in roundtrip_sd, f"Missing key after roundtrip: {key}"
assert torch.equal(orig_sd[key], roundtrip_sd[key]), f"Roundtrip mismatch at {key}"
print(" HF -> PrimeRL -> HF weight roundtrip verified")
print(" Verification passed.")
+7 -11
View File
@@ -287,6 +287,13 @@ class EnvConfig(BaseConfig):
),
),
] = {}
max_retries: Annotated[
int,
Field(
ge=0,
description="Maximum number of times the environment will retry a failed rollout.",
),
] = 0
@property
def resolved_name(self) -> str:
@@ -324,17 +331,6 @@ class EvalEnvConfig(EnvConfig):
),
] = 0
# TODO: should live on the EnvConfig and also apply to training envs but
# this is hard right now because we use the vf.EnvGroup which treats all
# envs as one. for now training envs hardcode no retries, but we should
# probably treat them like environment groups long-term
max_retries: Annotated[
int,
Field(
description="Maximum number of times the environment will try to retry running a rollout.",
),
] = 0
class ValConfig(BaseConfig):
"""Configures the validation of the model."""
+7
View File
@@ -138,6 +138,13 @@ class ClientConfig(BaseConfig):
),
] = 1200
connect_timeout: Annotated[
float,
Field(
description="TCP connect timeout in seconds for inference API requests.",
),
] = 30.0
base_url: Annotated[
list[str],
Field(
+75 -39
View File
@@ -93,6 +93,7 @@ class Scheduler:
# Inference pool - used for admin operations (adapter sync) and metrics
self.inference_pool = inference_pool
self.max_retries_by_task = {env.resolved_name: env.max_retries for env in config.env}
self.deferred_group_scoring_tasks = set(deferred_group_scoring_tasks or ())
if self.deferred_group_scoring_tasks:
task_list = ", ".join(sorted(self.deferred_group_scoring_tasks))
@@ -110,9 +111,12 @@ class Scheduler:
self.checkpoint_ready.set()
self.update_weights_time, self.wait_for_ckpt_time = 0, 0
self.update_policy_task: asyncio.Task | None = None
self.inflight_policy_update_task: asyncio.Task | None = None
self.policy_update_lock = asyncio.Lock()
self.cancelled_rollouts_count = 0
self.empty_rollouts_by_task: dict[str, int] = defaultdict(int)
self.errored_rollouts_by_task: dict[str, int] = defaultdict(int)
self.total_rollouts_by_task: dict[str, int] = defaultdict(int)
self.last_batch_generation_time = 0.0
@property
@@ -200,7 +204,7 @@ class Scheduler:
example=group.example,
model_name=self.model_name,
sampling_args=self.sampling_args,
max_retries=0, # TODO: make configurable
max_retries=self.max_retries_by_task.get(group.example["task"], 0),
)
)
self.inflight_requests[run_rollout_task] = InflightRolloutInfo(
@@ -243,47 +247,71 @@ class Scheduler:
await self.maybe_update_policy()
await asyncio.sleep(1)
async def maybe_update_policy(self):
"""Updates the policy to the latest available checkpoint. Aborts rollout requests that are older than the max retention steps."""
def _compute_next_ckpt_step(self) -> int:
latest_ckpt_step = get_latest_ckpt_step(get_broadcast_dir(self.config.output_dir)) or 0
async_away_ckpt_step = max(self.step - self.max_async_level, 0)
next_ckpt_step = (
async_away_ckpt_step if self.strict_async_level else max(async_away_ckpt_step, latest_ckpt_step)
)
if self.strict_async_level:
return async_away_ckpt_step
return max(async_away_ckpt_step, latest_ckpt_step)
if next_ckpt_step > self.ckpt_step:
if next_ckpt_step == async_away_ckpt_step:
self.logger.info(
f"Orchestrator paused: waiting for trainer process to complete checkpoint {next_ckpt_step} "
f"(>{self.max_async_level} step(s) ahead). Training is progressing normally."
)
self.checkpoint_ready.clear()
wait_for_ckpt_start_time = time.perf_counter()
await wait_for_path(get_step_path(get_broadcast_dir(self.config.output_dir), next_ckpt_step) / "STABLE")
self.wait_for_ckpt_time = time.perf_counter() - wait_for_ckpt_start_time
self.logger.info(
f"Orchestrator resumed: checkpoint {next_ckpt_step} ready (after {self.wait_for_ckpt_time:.2f}s)"
)
self.logger.debug(
f"Got new policy with step {next_ckpt_step}. Updating weights and cancelling old rollout requests."
async def _apply_policy_update(self, next_ckpt_step: int) -> None:
async_away_ckpt_step = max(self.step - self.max_async_level, 0)
if next_ckpt_step == async_away_ckpt_step:
self.logger.info(
f"Orchestrator paused: waiting for trainer process to complete checkpoint {next_ckpt_step} "
f"(>{self.max_async_level} step(s) ahead). Training is progressing normally."
)
self.checkpoint_ready.clear()
wait_for_ckpt_start_time = time.perf_counter()
await wait_for_path(get_step_path(get_broadcast_dir(self.config.output_dir), next_ckpt_step) / "STABLE")
self.wait_for_ckpt_time = time.perf_counter() - wait_for_ckpt_start_time
self.logger.info(
f"Orchestrator resumed: checkpoint {next_ckpt_step} ready (after {self.wait_for_ckpt_time:.2f}s)"
)
# Update weights on inference servers
update_weights_start_time = time.perf_counter()
weights_path = get_step_path(get_broadcast_dir(self.config.output_dir), next_ckpt_step)
await self.inference_pool.update_weights(weights_path, lora_name=self.lora_name, step=next_ckpt_step)
self.update_weights_time = time.perf_counter() - update_weights_start_time
self.logger.debug(f"Updated weights to step {next_ckpt_step} in {self.update_weights_time:.2f}s")
self.logger.debug(
f"Got new policy with step {next_ckpt_step}. Updating weights and cancelling old rollout requests."
)
if self.lora_name is not None:
self.model_name = self.lora_name
self.inference_pool.update_model_name(self.model_name)
update_weights_start_time = time.perf_counter()
weights_path = get_step_path(get_broadcast_dir(self.config.output_dir), next_ckpt_step)
await self.inference_pool.update_weights(weights_path, lora_name=self.lora_name, step=next_ckpt_step)
self.update_weights_time = time.perf_counter() - update_weights_start_time
self.logger.debug(f"Updated weights to step {next_ckpt_step} in {self.update_weights_time:.2f}s")
self.checkpoint_ready.set()
self.ckpt_step = next_ckpt_step
if self.lora_name is not None:
self.model_name = self.lora_name
self.inference_pool.update_model_name(self.model_name)
await self._update_off_policy()
self.ckpt_step = next_ckpt_step
self.checkpoint_ready.set()
await self._update_off_policy()
async def _get_or_start_policy_update_task(self, next_ckpt_step: int) -> asyncio.Task:
async with self.policy_update_lock:
task = self.inflight_policy_update_task
if task is not None and not task.done():
return task
task = asyncio.create_task(self._apply_policy_update(next_ckpt_step))
self.inflight_policy_update_task = task
def _clear_inflight_policy_update(done_task: asyncio.Task) -> None:
if self.inflight_policy_update_task is done_task:
self.inflight_policy_update_task = None
task.add_done_callback(_clear_inflight_policy_update)
return task
async def maybe_update_policy(self):
"""Updates the policy to the latest available checkpoint. Aborts rollout requests that are older than the max retention steps."""
while True:
next_ckpt_step = self._compute_next_ckpt_step()
if next_ckpt_step <= self.ckpt_step:
return
task = await self._get_or_start_policy_update_task(next_ckpt_step)
await asyncio.shield(task)
async def _update_off_policy(self) -> None:
stale_group_ids = {
@@ -375,6 +403,7 @@ class Scheduler:
rollout = finished_task.result()
task = rollout_info.task
self.total_rollouts_by_task[task] += 1
should_reschedule = False
if len(rollout["trajectory"]) == 0:
self.empty_rollouts_by_task[task] += 1
@@ -389,7 +418,7 @@ class Scheduler:
self.logger.warning(
f"Rollout error in group {group_id} ({task}), re-scheduling "
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete): "
f"{rollout['error']}"
f"{rollout['error']['error_chain_repr']}"
)
if should_reschedule:
group.rollouts_to_schedule += 1
@@ -430,6 +459,9 @@ class Scheduler:
if self.update_policy_task is not None:
await safe_cancel(self.update_policy_task)
self.update_policy_task = None
if self.inflight_policy_update_task is not None:
await safe_cancel(self.inflight_policy_update_task)
self.inflight_policy_update_task = None
@property
def max_off_policy_level(self) -> int:
@@ -457,6 +489,7 @@ class Scheduler:
return self.step - self.ckpt_step
def get_metrics(self) -> dict[str, float]:
total_rollouts = sum(self.total_rollouts_by_task.values())
metrics = {
"time/wait_for_ckpt": self.wait_for_ckpt_time,
"time/update_weights": self.update_weights_time,
@@ -464,16 +497,18 @@ class Scheduler:
"scheduler/inflight_rollouts": self.inflight_rollout_count,
"scheduler/inflight_samples": self.inflight_sample_count,
"scheduler/cancelled_rollouts": self.cancelled_rollouts_count,
"empty_rollouts/all": sum(self.empty_rollouts_by_task.values()),
"errored_rollouts/all": sum(self.errored_rollouts_by_task.values()),
"empty_rollouts/all": sum(self.empty_rollouts_by_task.values()) / max(total_rollouts, 1),
"errored_rollouts/all": sum(self.errored_rollouts_by_task.values()) / max(total_rollouts, 1),
"off_policy_level/all/max": self.max_off_policy_level,
"off_policy_level/all/mean": self.mean_off_policy_level,
"off_policy_level/all/min": self.min_off_policy_level,
}
for task, count in self.empty_rollouts_by_task.items():
metrics[f"empty_rollouts/{task}"] = count
task_total = max(self.total_rollouts_by_task[task], 1)
metrics[f"empty_rollouts/{task}"] = count / task_total
for task, count in self.errored_rollouts_by_task.items():
metrics[f"errored_rollouts/{task}"] = count
task_total = max(self.total_rollouts_by_task[task], 1)
metrics[f"errored_rollouts/{task}"] = count / task_total
by_task: dict[str, list[int]] = {}
for info in self.inflight_requests.values():
by_task.setdefault(info.task, []).append(info.off_policy_steps)
@@ -484,6 +519,7 @@ class Scheduler:
self.cancelled_rollouts_count = 0
self.empty_rollouts_by_task.clear()
self.errored_rollouts_by_task.clear()
self.total_rollouts_by_task.clear()
# Add inference pool metrics (e.g. elastic pool server counts)
metrics.update(self.inference_pool.get_metrics())
+33 -19
View File
@@ -28,6 +28,7 @@ from prime_rl.trainer.models import (
PreTrainedModelPrimeRL,
PrimeLmOutput,
cast_float_and_contiguous,
get_custom_vlm_cls,
supports_custom_impl,
)
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
@@ -40,7 +41,7 @@ from prime_rl.trainer.weights import (
)
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.vlm import is_vlm_model
from prime_rl.utils.vlm import is_vlm_config, is_vlm_model
def _patch_qwen3_5_moe_conversion_mapping():
@@ -217,10 +218,8 @@ def get_model(
f"Loading model config (name={config.name}, attn={config.attn}, trust_remote_code={config.trust_remote_code})"
)
# Check if this is a vision-language model
# Check if this is a vision-language model (by name pattern first)
is_vlm = is_vlm_model(config.name)
if is_vlm:
logger.info(f"Detected vision-language model: {config.name}")
if "Qwen3.5" in config.name or "qwen3_5" in config.name.lower():
_patch_qwen3_5_text_position_ids()
@@ -233,6 +232,17 @@ def get_model(
),
)
model_config.use_cache = False
# Fallback VLM detection from loaded config (catches local paths)
if not is_vlm and is_vlm_config(model_config):
is_vlm = True
if is_vlm:
logger.info(f"Detected vision-language model: {config.name}")
# Fallback Qwen3.5 patch detection from loaded config model_type
if getattr(model_config, "model_type", "").startswith("qwen3_5_moe"):
_patch_qwen3_5_text_position_ids()
_patch_qwen3_5_moe_conversion_mapping()
for subconfig_key in getattr(model_config, "sub_configs", {}):
subconfig = getattr(model_config, subconfig_key, None)
if subconfig is not None and hasattr(subconfig, "use_cache"):
@@ -273,25 +283,24 @@ def get_model(
model_config.num_hidden_layers = num_hidden_layers
# Determine the implementation to use
custom_vlm_cls = get_custom_vlm_cls(model_config) if is_vlm else None
if config.impl == "auto":
impl_to_use = "custom" if supports_custom_impl(model_config) else "hf"
logger.info(
f"Auto-selected implementation: {impl_to_use} (custom implementation {'supported' if supports_custom_impl(model_config) else 'not supported'})"
)
if is_vlm:
impl_to_use = "custom" if custom_vlm_cls is not None else "hf"
else:
impl_to_use = "custom" if supports_custom_impl(model_config) else "hf"
logger.info(f"Auto-selected implementation: {impl_to_use}")
else:
impl_to_use = config.impl
if is_vlm and impl_to_use != "hf":
raise ValueError(
f"VLM models only support impl='hf', but got impl='{config.impl}' (resolved to '{impl_to_use}'). "
f"Set impl='hf' or impl='auto' in your model config."
)
with device:
if is_vlm:
from transformers import AutoModelForImageTextToText
if impl_to_use == "custom" and custom_vlm_cls is not None:
model_cls = custom_vlm_cls
else:
from transformers import AutoModelForImageTextToText
model_cls = AutoModelForImageTextToText
model_cls = AutoModelForImageTextToText
else:
match impl_to_use:
case "hf":
@@ -300,8 +309,9 @@ def get_model(
model_cls = AutoModelForCausalLMPrimeRL
load_model_start_time = time.perf_counter()
# VLM models use standard HF API which requires torch_dtype, custom models use dtype
dtype_kwarg = {"torch_dtype": dtype} if is_vlm else {"dtype": dtype}
# HF VLM models require torch_dtype; custom PrimeRL models and text Auto models use dtype
use_torch_dtype = is_vlm and model_cls is not custom_vlm_cls
dtype_kwarg = {"torch_dtype": dtype} if use_torch_dtype else {"dtype": dtype}
if device == torch.device("meta"):
logger.info(f"Loading model {config.name} using {model_cls.__name__} to meta device")
model = model_cls.from_config(model_config, trust_remote_code=config.trust_remote_code, **dtype_kwarg)
@@ -357,7 +367,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
# For VLM models, shard the frozen vision encoder as a single unit
# This allows FSDP to manage the memory while keeping it frozen
is_vlm = is_vlm_model(config.name)
is_vlm = is_vlm_model(config.name) or (hasattr(model, "model") and hasattr(model.model, "visual"))
if is_vlm:
if hasattr(model, "model") and hasattr(model.model, "visual"):
vision_encoder = model.model.visual
@@ -573,6 +583,10 @@ def can_reinit_empty_buffers(model: nn.Module):
The main issue is with anything that is not in the checkpoint.
This is usually any non-persistent buffers.
"""
# Custom PrimeRL models handle buffer reinit via init_buffers_post_meta
if isinstance(model, PreTrainedModelPrimeRL):
return True
buffer_names = [name for name, _ in model.named_buffers()]
# TT MoE buffers
+17
View File
@@ -15,6 +15,7 @@ from prime_rl.trainer.models.glm_moe_dsa import GlmMoeDsaConfig, GlmMoeDsaForCau
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput, cast_float_and_contiguous
from prime_rl.trainer.models.llama import LlamaForCausalLM
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config, MiniMaxM2ForCausalLM
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM
from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalLM
# Make custom config discoverable by AutoConfig
@@ -23,6 +24,7 @@ AutoConfig.register("glm4_moe", Glm4MoeConfig, exist_ok=True)
AutoConfig.register("glm_moe_dsa", GlmMoeDsaConfig, exist_ok=True)
AutoConfig.register("minimax_m2", MiniMaxM2Config, exist_ok=True)
AutoConfig.register("qwen3_moe", Qwen3MoeConfig, exist_ok=True)
AutoConfig.register("qwen3_5_moe_text", Qwen3_5MoeConfig, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, OrderedDict())
_CUSTOM_CAUSAL_LM_MAPPING.register(LlamaConfig, LlamaForCausalLM, exist_ok=True)
@@ -31,6 +33,7 @@ _CUSTOM_CAUSAL_LM_MAPPING.register(Glm4MoeConfig, Glm4MoeForCausalLM, exist_ok=T
_CUSTOM_CAUSAL_LM_MAPPING.register(GlmMoeDsaConfig, GlmMoeDsaForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(MiniMaxM2Config, MiniMaxM2ForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3MoeConfig, Qwen3MoeForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM, exist_ok=True)
class AutoModelForCausalLMPrimeRL(_BaseAutoModelClass):
@@ -52,10 +55,24 @@ def supports_custom_impl(model_config: PretrainedConfig) -> bool:
return type(model_config) in _CUSTOM_CAUSAL_LM_MAPPING
# Mapping from HF composite VLM model_type to custom PrimeRL class.
# Used by get_model() to dispatch VLMs that have a custom text model implementation.
# Points to the same unified class — the config drives text-only vs VLM behavior.
_CUSTOM_VLM_MAPPING: dict[str, type] = {
"qwen3_5_moe": Qwen3_5MoeForCausalLM,
}
def get_custom_vlm_cls(model_config: PretrainedConfig) -> type | None:
"""Return the custom PrimeRL VLM class for this config, or None if unsupported."""
return _CUSTOM_VLM_MAPPING.get(getattr(model_config, "model_type", None))
__all__ = [
"AutoModelForCausalLMPrimeRL",
"PreTrainedModelPrimeRL",
"supports_custom_impl",
"get_custom_vlm_cls",
"PrimeLmOutput",
"cast_float_and_contiguous",
]
+5
View File
@@ -11,6 +11,11 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
after loading with meta device.
"""
@classmethod
def from_config(cls, config, **kwargs):
"""Public from_config that mirrors the Auto class API."""
return cls._from_config(config, **kwargs)
@classmethod
def _can_set_experts_implementation(cls) -> bool:
"""PrimeRL models use custom MoE implementations and don't support dynamic experts implementation."""
+5 -1
View File
@@ -246,7 +246,7 @@ def substitute_ring_attn(
heads_k_stride: int,
attn_impl: str = "flash_attention_2",
) -> None:
"""Patch _compute_attention on FlashAttention (and AfmoeFlashAttention) to use ring attention."""
"""Patch _compute_attention on FlashAttention variants to use ring attention."""
from ring_flash_attn import llama3_flash_attn_varlen_func
from .ring_attn import ring_fa3_varlen_func
@@ -285,3 +285,7 @@ def substitute_ring_attn(
from prime_rl.trainer.models.afmoe.modeling_afmoe import AfmoeFlashAttention
AfmoeFlashAttention._compute_attention = _ring_compute_attention
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
Qwen3_5MoeGatedFlashAttention._compute_attention = _ring_compute_attention
@@ -0,0 +1,13 @@
from prime_rl.trainer.models.qwen3_5_moe.configuration_qwen3_5_moe import Qwen3_5MoeConfig
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
Qwen3_5MoeForCausalLM,
Qwen3_5MoeModel,
Qwen3_5MoePreTrainedModel,
)
__all__ = [
"Qwen3_5MoeConfig",
"Qwen3_5MoeForCausalLM",
"Qwen3_5MoeModel",
"Qwen3_5MoePreTrainedModel",
]
@@ -0,0 +1,108 @@
from transformers.configuration_utils import PretrainedConfig
class Qwen3_5MoeConfig(PretrainedConfig):
r"""
Configuration class for the custom PrimeRL Qwen3.5-MoE model.
This matches the HuggingFace `Qwen3_5MoeTextConfig` architecture:
hybrid attention (GatedDeltaNet linear + gated softmax), MoE with gated shared expert,
and (1+weight) RMSNorm parameterization.
Defaults match Qwen3.5-35B-A3B.
"""
model_type = "qwen3_5_moe_text"
keys_to_ignore_at_inference = ["past_key_values"]
def __init__(
self,
vocab_size=248320,
hidden_size=2048,
num_hidden_layers=40,
num_attention_heads=16,
num_key_value_heads=2,
hidden_act="silu",
max_position_embeddings=32768,
initializer_range=0.02,
rms_norm_eps=1e-6,
use_cache=True,
tie_word_embeddings=False,
rope_theta=10000.0,
rope_scaling=None,
attention_bias=False,
attention_dropout=0.0,
head_dim=256,
# Linear attention (GatedDeltaNet) params
linear_conv_kernel_dim=4,
linear_key_head_dim=128,
linear_value_head_dim=128,
linear_num_key_heads=16,
linear_num_value_heads=32,
# MoE params
moe_intermediate_size=512,
shared_expert_intermediate_size=512,
num_experts_per_tok=8,
num_experts=256,
output_router_logits=False,
router_aux_loss_coef=0.001,
# Layer type configuration
layer_types=None,
# PrimeRL additions
load_balance_coeff=None,
use_grouped_mm=True,
pad_token_id=None,
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.rope_theta = rope_theta
self.rope_scaling = rope_scaling
self.attention_bias = attention_bias
self.attention_dropout = attention_dropout
self.head_dim = head_dim
self.pad_token_id = pad_token_id
# Partial RoPE: only rotate 25% of head_dim
kwargs.setdefault("partial_rotary_factor", 0.25)
# Layer types: default every 4th layer is full_attention, rest linear_attention
self.layer_types = layer_types
if self.layer_types is None:
interval_pattern = kwargs.pop("full_attention_interval", 4)
self.layer_types = [
"linear_attention" if bool((i + 1) % interval_pattern) else "full_attention"
for i in range(self.num_hidden_layers)
]
# Linear attention (GatedDeltaNet) params
self.linear_conv_kernel_dim = linear_conv_kernel_dim
self.linear_key_head_dim = linear_key_head_dim
self.linear_value_head_dim = linear_value_head_dim
self.linear_num_key_heads = linear_num_key_heads
self.linear_num_value_heads = linear_num_value_heads
# MoE params
self.moe_intermediate_size = moe_intermediate_size
self.shared_expert_intermediate_size = shared_expert_intermediate_size
self.num_experts_per_tok = num_experts_per_tok
self.num_experts = num_experts
self.output_router_logits = output_router_logits
self.router_aux_loss_coef = router_aux_loss_coef
# PrimeRL additions
self.load_balance_coeff = load_balance_coeff
self.use_grouped_mm = use_grouped_mm
super().__init__(
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
@@ -0,0 +1,125 @@
import torch
from torch import Tensor
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
"""Get the maximum number of layers in the model."""
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
"""Convert a single layer from HF to PrimeRL format in-place.
Handles:
- Router: mlp.gate.weight -> mlp.router.gate.weight
- Routed experts: fused gate_up_proj/down_proj or per-expert -> w1/w2/w3
- Shared expert: mlp.shared_expert.{gate,up,down}_proj.weight -> shared_expert.{w1,w3,w2}.weight
- Shared expert gate: mlp.shared_expert_gate.weight -> shared_expert_gate.weight
"""
i = layer_idx
# Router: mlp.gate.weight -> mlp.router.gate.weight
gate_key = f"model.layers.{i}.mlp.gate.weight"
if gate_key not in state_dict:
return
state_dict[f"model.layers.{i}.mlp.router.gate.weight"] = state_dict.pop(gate_key)
# Routed experts: convert to fused w1/w2/w3 format
if f"model.layers.{i}.mlp.experts.gate_up_proj" in state_dict:
# New fused format (transformers 5.0+): gate_up_proj shape (num_experts, 2*moe_dim, dim)
gate_up_proj = state_dict.pop(f"model.layers.{i}.mlp.experts.gate_up_proj")
down_proj = state_dict.pop(f"model.layers.{i}.mlp.experts.down_proj")
moe_dim = gate_up_proj.shape[1] // 2
w1 = gate_up_proj[:, :moe_dim, :] # gate
w3 = gate_up_proj[:, moe_dim:, :] # up
w2 = down_proj # down
else:
# Old per-expert format
num_experts = len([k for k in state_dict.keys() if f"model.layers.{i}.mlp.experts" in k and "gate_proj" in k])
if num_experts == 0:
return
dim, moe_dim = state_dict[f"model.layers.{i}.mlp.experts.0.down_proj.weight"].shape
dtype = state_dict[f"model.layers.{i}.mlp.experts.0.down_proj.weight"].dtype
w1 = torch.empty((num_experts, moe_dim, dim), dtype=dtype)
w2 = torch.empty((num_experts, dim, moe_dim), dtype=dtype)
w3 = torch.empty((num_experts, moe_dim, dim), dtype=dtype)
for j in range(num_experts):
w1[j].copy_(state_dict.pop(f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"))
w2[j].copy_(state_dict.pop(f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"))
w3[j].copy_(state_dict.pop(f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"))
state_dict[f"model.layers.{i}.mlp.experts.w1"] = w1
state_dict[f"model.layers.{i}.mlp.experts.w2"] = w2
state_dict[f"model.layers.{i}.mlp.experts.w3"] = w3
# Shared expert: mlp.shared_expert.{gate,up,down}_proj -> shared_expert.{w1,w3,w2}
se_gate_key = f"model.layers.{i}.mlp.shared_expert.gate_proj.weight"
if se_gate_key in state_dict:
state_dict[f"model.layers.{i}.shared_expert.w1.weight"] = state_dict.pop(se_gate_key)
state_dict[f"model.layers.{i}.shared_expert.w2.weight"] = state_dict.pop(
f"model.layers.{i}.mlp.shared_expert.down_proj.weight"
)
state_dict[f"model.layers.{i}.shared_expert.w3.weight"] = state_dict.pop(
f"model.layers.{i}.mlp.shared_expert.up_proj.weight"
)
# Shared expert gate: mlp.shared_expert_gate.weight -> shared_expert_gate.weight
seg_key = f"model.layers.{i}.mlp.shared_expert_gate.weight"
if seg_key in state_dict:
state_dict[f"model.layers.{i}.shared_expert_gate.weight"] = state_dict.pop(seg_key)
def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int):
"""Convert a single layer from PrimeRL to HF format in-place."""
i = layer_idx
# Router
router_key = f"model.layers.{i}.mlp.router.gate.weight"
if router_key not in state_dict:
return
state_dict[f"model.layers.{i}.mlp.gate.weight"] = state_dict.pop(router_key)
# Routed experts: w1/w2/w3 -> per-expert format
w1 = state_dict.pop(f"model.layers.{i}.mlp.experts.w1")
w2 = state_dict.pop(f"model.layers.{i}.mlp.experts.w2")
w3 = state_dict.pop(f"model.layers.{i}.mlp.experts.w3")
num_experts = w1.shape[0]
for j in range(num_experts):
state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"] = w1[j]
state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"] = w2[j]
state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"] = w3[j]
# Shared expert: shared_expert.{w1,w2,w3} -> mlp.shared_expert.{gate,down,up}_proj
se_w1_key = f"model.layers.{i}.shared_expert.w1.weight"
if se_w1_key in state_dict:
state_dict[f"model.layers.{i}.mlp.shared_expert.gate_proj.weight"] = state_dict.pop(se_w1_key)
state_dict[f"model.layers.{i}.mlp.shared_expert.down_proj.weight"] = state_dict.pop(
f"model.layers.{i}.shared_expert.w2.weight"
)
state_dict[f"model.layers.{i}.mlp.shared_expert.up_proj.weight"] = state_dict.pop(
f"model.layers.{i}.shared_expert.w3.weight"
)
# Shared expert gate
seg_key = f"model.layers.{i}.shared_expert_gate.weight"
if seg_key in state_dict:
state_dict[f"model.layers.{i}.mlp.shared_expert_gate.weight"] = state_dict.pop(seg_key)
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]):
"""Convert all MoE weights from HF to PrimeRL format in-place."""
num_layers = get_max_layer_num(state_dict)
for i in range(num_layers):
convert_hf_layer_to_tt(state_dict, i)
def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]):
"""Convert all MoE weights from PrimeRL to HF format in-place."""
num_layers = get_max_layer_num(state_dict)
for i in range(num_layers):
convert_tt_layer_to_hf(state_dict, i)
@@ -0,0 +1,971 @@
import functools
from dataclasses import dataclass
from typing import Optional, Union
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from transformers.cache_utils import Cache
from transformers.configuration_utils import PretrainedConfig
from transformers.generation import GenerationMixin
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import MoeModelOutputWithPast
from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeVisionModel
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs, logging
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig, apply_rotary_pos_emb
from .configuration_qwen3_5_moe import Qwen3_5MoeConfig
from .converting_qwen3_5_moe import (
convert_hf_layer_to_tt,
convert_hf_to_tt_moe,
convert_tt_layer_to_hf,
convert_tt_to_hf_moe,
)
# Flash attention imports
try:
from flash_attn import flash_attn_varlen_func
except ImportError:
flash_attn_varlen_func = None # type: ignore
try:
from flash_attn_interface import flash_attn_varlen_func as flash_attn_3_varlen_func
except ImportError:
flash_attn_3_varlen_func = None # type: ignore
try:
from flash_attn.cute import flash_attn_varlen_func as flash_attn_4_varlen_func
except ImportError:
flash_attn_4_varlen_func = None # type: ignore
# Flash linear attention imports (for GatedDeltaNet fast path)
try:
from causal_conv1d import causal_conv1d_fn
except ImportError:
causal_conv1d_fn = None # type: ignore
try:
from fla.modules import FusedRMSNormGated
from fla.ops.gated_delta_rule import chunk_gated_delta_rule
except ImportError:
chunk_gated_delta_rule = None # type: ignore
FusedRMSNormGated = None # type: ignore
logger = logging.get_logger(__name__)
# ---------------------------------------------------------------------------
# RMSNorm variants
# ---------------------------------------------------------------------------
class Qwen3_5MoeRMSNorm(nn.Module):
"""RMSNorm with (1+weight) parameterization. Weight initialized to zeros."""
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.zeros(dim))
def _norm(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x):
output = self._norm(x.float())
output = output * (1.0 + self.weight.float())
return output.type_as(x)
class Qwen3_5MoeRMSNormGated(nn.Module):
"""RMSNorm with SiLU gating for GatedDeltaNet output."""
def __init__(self, hidden_size, eps=1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states, gate=None):
input_dtype = hidden_states.dtype
hidden_states = hidden_states.to(torch.float32)
variance = hidden_states.pow(2).mean(-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
hidden_states = self.weight * hidden_states.to(input_dtype)
hidden_states = hidden_states * F.silu(gate.to(torch.float32))
return hidden_states.to(input_dtype)
# ---------------------------------------------------------------------------
# GatedDeltaNet linear attention
# ---------------------------------------------------------------------------
def l2norm(x: torch.FloatTensor, dim: int = -1, eps: float = 1e-6):
inv_norm = torch.rsqrt((x * x).sum(dim=dim, keepdim=True) + eps)
return x * inv_norm
def torch_chunk_gated_delta_rule(
query,
key,
value,
g,
beta,
chunk_size=64,
initial_state=None,
output_final_state=False,
use_qk_l2norm_in_kernel=False,
):
"""Pure-PyTorch fallback for chunk_gated_delta_rule."""
initial_dtype = query.dtype
if use_qk_l2norm_in_kernel:
query = l2norm(query, dim=-1, eps=1e-6)
key = l2norm(key, dim=-1, eps=1e-6)
query, key, value, beta, g = [
x.transpose(1, 2).contiguous().to(torch.float32) for x in (query, key, value, beta, g)
]
batch_size, num_heads, sequence_length, k_head_dim = key.shape
v_head_dim = value.shape[-1]
pad_size = (chunk_size - sequence_length % chunk_size) % chunk_size
query = F.pad(query, (0, 0, 0, pad_size))
key = F.pad(key, (0, 0, 0, pad_size))
value = F.pad(value, (0, 0, 0, pad_size))
beta = F.pad(beta, (0, pad_size))
g = F.pad(g, (0, pad_size))
total_sequence_length = sequence_length + pad_size
scale = 1 / (query.shape[-1] ** 0.5)
query = query * scale
v_beta = value * beta.unsqueeze(-1)
k_beta = key * beta.unsqueeze(-1)
query, key, value, k_beta, v_beta = [
x.reshape(x.shape[0], x.shape[1], -1, chunk_size, x.shape[-1]) for x in (query, key, value, k_beta, v_beta)
]
g = g.reshape(g.shape[0], g.shape[1], -1, chunk_size)
mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device), diagonal=0)
g = g.cumsum(dim=-1)
decay_mask = ((g.unsqueeze(-1) - g.unsqueeze(-2)).tril().exp().float()).tril()
attn = -((k_beta @ key.transpose(-1, -2)) * decay_mask).masked_fill(mask, 0)
for i in range(1, chunk_size):
row = attn[..., i, :i].clone()
sub = attn[..., :i, :i].clone()
attn[..., i, :i] = row + (row.unsqueeze(-1) * sub).sum(-2)
attn = attn + torch.eye(chunk_size, dtype=attn.dtype, device=attn.device)
value = attn @ v_beta
k_cumdecay = attn @ (k_beta * g.exp().unsqueeze(-1))
last_recurrent_state = (
torch.zeros(batch_size, num_heads, k_head_dim, v_head_dim).to(value)
if initial_state is None
else initial_state.to(value)
)
core_attn_out = torch.zeros_like(value)
mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device), diagonal=1)
for i in range(0, total_sequence_length // chunk_size):
q_i, k_i, v_i = query[:, :, i], key[:, :, i], value[:, :, i]
attn = (q_i @ k_i.transpose(-1, -2) * decay_mask[:, :, i]).masked_fill_(mask, 0)
v_prime = (k_cumdecay[:, :, i]) @ last_recurrent_state
v_new = v_i - v_prime
attn_inter = (q_i * g[:, :, i, :, None].exp()) @ last_recurrent_state
core_attn_out[:, :, i] = attn_inter + attn @ v_new
last_recurrent_state = (
last_recurrent_state * g[:, :, i, -1, None, None].exp()
+ (k_i * (g[:, :, i, -1, None] - g[:, :, i]).exp()[..., None]).transpose(-1, -2) @ v_new
)
if not output_final_state:
last_recurrent_state = None
core_attn_out = core_attn_out.reshape(core_attn_out.shape[0], core_attn_out.shape[1], -1, core_attn_out.shape[-1])
core_attn_out = core_attn_out[:, :, :sequence_length]
core_attn_out = core_attn_out.transpose(1, 2).contiguous().to(initial_dtype)
return core_attn_out, last_recurrent_state
class Qwen3_5MoeGatedDeltaNet(nn.Module):
"""GatedDeltaNet linear attention with Conv1d, beta/gamma gates, and chunk delta rule."""
def __init__(self, config: Qwen3_5MoeConfig):
super().__init__()
self.hidden_size = config.hidden_size
self.num_v_heads = config.linear_num_value_heads
self.num_k_heads = config.linear_num_key_heads
self.head_k_dim = config.linear_key_head_dim
self.head_v_dim = config.linear_value_head_dim
self.key_dim = self.head_k_dim * self.num_k_heads
self.value_dim = self.head_v_dim * self.num_v_heads
self.conv_kernel_size = config.linear_conv_kernel_dim
self.activation = config.hidden_act
self.layer_norm_epsilon = config.rms_norm_eps
# QKV convolution (depthwise)
self.conv_dim = self.key_dim * 2 + self.value_dim
self.conv1d = nn.Conv1d(
in_channels=self.conv_dim,
out_channels=self.conv_dim,
bias=False,
kernel_size=self.conv_kernel_size,
groups=self.conv_dim,
padding=self.conv_kernel_size - 1,
)
# Time step projection
self.dt_bias = nn.Parameter(torch.ones(self.num_v_heads))
A = torch.empty(self.num_v_heads).uniform_(0, 16)
self.A_log = nn.Parameter(torch.log(A))
# Gated RMSNorm on output (per-head)
if FusedRMSNormGated is not None:
self.norm = FusedRMSNormGated(self.head_v_dim, eps=self.layer_norm_epsilon)
else:
self.norm = Qwen3_5MoeRMSNormGated(self.head_v_dim, eps=self.layer_norm_epsilon)
self.out_proj = nn.Linear(self.value_dim, self.hidden_size, bias=False)
# Input projections
self.in_proj_qkv = nn.Linear(self.hidden_size, self.key_dim * 2 + self.value_dim, bias=False)
self.in_proj_z = nn.Linear(self.hidden_size, self.value_dim, bias=False)
self.in_proj_b = nn.Linear(self.hidden_size, self.num_v_heads, bias=False)
self.in_proj_a = nn.Linear(self.hidden_size, self.num_v_heads, bias=False)
# Select best available kernel
self._causal_conv1d_fn = causal_conv1d_fn
self._chunk_gated_delta_rule = chunk_gated_delta_rule or torch_chunk_gated_delta_rule
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
batch_size, seq_len, _ = hidden_states.shape
mixed_qkv = self.in_proj_qkv(hidden_states).transpose(1, 2)
z = self.in_proj_z(hidden_states).reshape(batch_size, seq_len, -1, self.head_v_dim)
b = self.in_proj_b(hidden_states)
a = self.in_proj_a(hidden_states)
# Causal conv1d
if self._causal_conv1d_fn is not None:
mixed_qkv = self._causal_conv1d_fn(
x=mixed_qkv,
weight=self.conv1d.weight.squeeze(1),
bias=self.conv1d.bias,
activation=self.activation,
seq_idx=None,
)
else:
mixed_qkv = F.silu(self.conv1d(mixed_qkv)[:, :, :seq_len])
mixed_qkv = mixed_qkv.transpose(1, 2)
query, key, value = torch.split(mixed_qkv, [self.key_dim, self.key_dim, self.value_dim], dim=-1)
query = query.reshape(batch_size, seq_len, -1, self.head_k_dim)
key = key.reshape(batch_size, seq_len, -1, self.head_k_dim)
value = value.reshape(batch_size, seq_len, -1, self.head_v_dim)
beta = b.sigmoid()
g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
if self.num_v_heads // self.num_k_heads > 1:
query = query.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
core_attn_out, _ = self._chunk_gated_delta_rule(
query,
key,
value,
g=g,
beta=beta,
initial_state=None,
output_final_state=False,
use_qk_l2norm_in_kernel=True,
)
# Gated RMSNorm
core_attn_out = core_attn_out.reshape(-1, self.head_v_dim)
z = z.reshape(-1, self.head_v_dim)
core_attn_out = self.norm(core_attn_out, z)
core_attn_out = core_attn_out.reshape(batch_size, seq_len, -1)
return self.out_proj(core_attn_out)
# ---------------------------------------------------------------------------
# Gated softmax attention (for full_attention layers)
# ---------------------------------------------------------------------------
@dataclass
class Qwen3_5MoeGatedAttentionConfig:
hidden_size: int
head_dim: int
num_attention_heads: int
num_key_value_heads: int
rms_norm_eps: float
attention_bias: bool = False
attention_dropout: float = 0.0
def _repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
if n_rep == 1:
return hidden_states
batch, num_kv_heads, slen, head_dim = hidden_states.shape
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_kv_heads, n_rep, slen, head_dim)
return hidden_states.reshape(batch, num_kv_heads * n_rep, slen, head_dim)
class Qwen3_5MoeGatedAttentionBase(nn.Module):
"""Base class for gated softmax attention (Q projects 2x: query + gate)."""
def __init__(self, config: Qwen3_5MoeGatedAttentionConfig):
super().__init__()
self.head_dim = config.head_dim
self.num_heads = config.num_attention_heads
self.num_key_value_heads = config.num_key_value_heads
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
self.scaling = self.head_dim**-0.5
self.attention_dropout = config.attention_dropout
# Q projects 2x: query + gate
self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim * 2, bias=config.attention_bias)
self.k_proj = nn.Linear(
config.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.v_proj = nn.Linear(
config.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)
# QK normalization with (1+weight) parameterization
self.q_norm = Qwen3_5MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.k_norm = Qwen3_5MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
class Qwen3_5MoeGatedSDPAAttention(Qwen3_5MoeGatedAttentionBase):
"""Gated softmax attention using PyTorch's scaled_dot_product_attention."""
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, None]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
# Split Q into query + gate
query_states, gate = torch.chunk(
self.q_proj(hidden_states).view(*input_shape, -1, self.head_dim * 2), 2, dim=-1
)
gate = gate.reshape(*input_shape, -1)
query_states = self.q_norm(query_states.view(hidden_shape)).transpose(1, 2)
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
key_states = _repeat_kv(key_states, self.num_key_value_groups)
value_states = _repeat_kv(value_states, self.num_key_value_groups)
attn_output = F.scaled_dot_product_attention(
query_states,
key_states,
value_states,
is_causal=True,
scale=self.scaling,
)
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate)
attn_output = self.o_proj(attn_output)
return attn_output, None
class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
"""Gated softmax attention using Flash Attention varlen functions."""
_funcs = {
2: flash_attn_varlen_func,
3: flash_attn_3_varlen_func,
4: flash_attn_4_varlen_func,
}
def __init__(self, config: Qwen3_5MoeGatedAttentionConfig, flash_attn_version: int = 4):
super().__init__(config)
self._flash_attn_version = flash_attn_version
self.func = self._funcs[flash_attn_version]
self._flash_attn_call = self.func
if self._flash_attn_version == 4:
self._flash_attn_call = torch._dynamo.disable(self.func)
def _compute_attention(self, q, k, v, cu_seqlens, max_seqlen):
args = [q, k, v, cu_seqlens, cu_seqlens]
if self._flash_attn_version != 4:
args.extend([max_seqlen, max_seqlen])
kwargs: dict = {"causal": True}
out = self._flash_attn_call(*args, **kwargs)
if isinstance(out, tuple):
out = out[0]
return out
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, None]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
# Split Q into query + gate
query_states, gate = torch.chunk(
self.q_proj(hidden_states).view(*input_shape, -1, self.head_dim * 2), 2, dim=-1
)
gate = gate.reshape(*input_shape, -1)
query_states = self.q_norm(query_states.view(hidden_shape))
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape))
value_states = self.v_proj(hidden_states).view(hidden_shape)
# Apply RoPE (need transpose for apply_rotary_pos_emb format)
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
attn_output = out.contiguous().view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate)
attn_output = self.o_proj(attn_output)
return attn_output, None
QWEN35MOE_ATTN_IMPL2CLASS = {
"sdpa": Qwen3_5MoeGatedSDPAAttention,
"flash_attention_2": functools.partial(Qwen3_5MoeGatedFlashAttention, flash_attn_version=2),
"flash_attention_3": functools.partial(Qwen3_5MoeGatedFlashAttention, flash_attn_version=3),
"fa4": functools.partial(Qwen3_5MoeGatedFlashAttention, flash_attn_version=4),
}
# ---------------------------------------------------------------------------
# Decoder layer
# ---------------------------------------------------------------------------
def _get_gated_attention(config: Qwen3_5MoeConfig) -> nn.Module:
attn_config = Qwen3_5MoeGatedAttentionConfig(
hidden_size=config.hidden_size,
head_dim=config.head_dim,
num_attention_heads=config.num_attention_heads,
num_key_value_heads=config.num_key_value_heads,
rms_norm_eps=config.rms_norm_eps,
attention_bias=config.attention_bias,
attention_dropout=config.attention_dropout,
)
attn_impl = config._attn_implementation
if attn_impl == "eager":
attn_impl = "sdpa"
if attn_impl not in QWEN35MOE_ATTN_IMPL2CLASS:
supported = list(QWEN35MOE_ATTN_IMPL2CLASS.keys())
raise ValueError(
f"Qwen3.5-MoE attention does not support '{config._attn_implementation}'. "
f"Supported implementations: {supported}."
)
return QWEN35MOE_ATTN_IMPL2CLASS[attn_impl](attn_config)
class Qwen3_5MoeDecoderLayer(GradientCheckpointingLayer):
def __init__(self, config: Qwen3_5MoeConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.layer_type = config.layer_types[layer_idx]
# Token mixer: either GatedDeltaNet or gated softmax attention
if self.layer_type == "linear_attention":
self.linear_attn = Qwen3_5MoeGatedDeltaNet(config)
elif self.layer_type == "full_attention":
self.self_attn = _get_gated_attention(config)
# MoE: routed experts via shared MoE class (no shared experts in MoE itself)
moe_args = MoEArgs(
num_experts=config.num_experts,
num_shared_experts=0,
score_func="softmax",
route_norm=True,
route_scale=1.0,
score_before_experts=False,
top_k=config.num_experts_per_tok,
use_grouped_mm=config.use_grouped_mm,
load_balance_coeff=config.load_balance_coeff,
)
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
# Separate gated shared expert
self.shared_expert = FeedForward(dim=config.hidden_size, hidden_dim=config.shared_expert_intermediate_size)
self.shared_expert_gate = nn.Linear(config.hidden_size, 1, bias=False)
# Layer norms with (1+weight) parameterization
self.input_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
routed_experts: Optional[torch.LongTensor] = None,
) -> torch.FloatTensor:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Token mixer
if self.layer_type == "linear_attention":
hidden_states = self.linear_attn(hidden_states)
elif self.layer_type == "full_attention":
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
position_embeddings=position_embeddings,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
hidden_states = residual + hidden_states
# MLP: routed experts + gated shared expert
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
# Routed experts
routed_output = self.mlp(hidden_states, routed_experts=routed_experts)
# Gated shared expert
bs, slen, dim = hidden_states.shape
hidden_flat = hidden_states.view(-1, dim)
shared_output = self.shared_expert(hidden_flat)
shared_output = F.sigmoid(self.shared_expert_gate(hidden_flat)) * shared_output
shared_output = shared_output.view(bs, slen, dim)
hidden_states = residual + routed_output + shared_output
return hidden_states
# ---------------------------------------------------------------------------
# Model classes
# ---------------------------------------------------------------------------
def _create_rotary_emb(config: Qwen3_5MoeConfig) -> RotaryEmbedding:
if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type", "default"))
else:
rope_type = "default"
rotary_config = RotaryEmbeddingConfig(
max_position_embeddings=config.max_position_embeddings,
rope_type=rope_type,
model_config=config,
)
return RotaryEmbedding(rotary_config)
class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
config_class = Qwen3_5MoeConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["Qwen3_5MoeDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = False
_supports_attention_backend = True
_can_compile_fullgraph = False
_can_record_outputs = {
"hidden_states": Qwen3_5MoeDecoderLayer,
}
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any(
"mlp.experts.1.up_proj" in name
or "mlp.experts.gate_up_proj" in name
or "mlp.shared_expert.gate_proj" in name
for name in state_dict.keys()
)
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any("mlp.experts.w1" in name for name in state_dict.keys())
@classmethod
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
convert_tt_to_hf_moe(state_dict)
return state_dict
@classmethod
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
convert_hf_to_tt_moe(state_dict)
return state_dict
@classmethod
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
convert_tt_layer_to_hf(state_dict, layer_idx)
return state_dict
@classmethod
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
convert_hf_layer_to_tt(state_dict, layer_idx)
return state_dict
class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
def __init__(self, config: Qwen3_5MoeConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.layers = nn.ModuleList(
[Qwen3_5MoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.norm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.rotary_emb = _create_rotary_emb(config)
self.gradient_checkpointing = False
self.post_init()
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
routed_experts: Optional[torch.LongTensor] = None,
) -> MoeModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
flat_position_ids = position_ids.view(-1)
seqlens = torch.cat(
[
flat_position_ids[0:1],
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
flat_position_ids[-1:] + 1,
]
)
max_seqlen = seqlens.max().item()
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
else:
max_seqlen = None
cu_seqlens = None
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for layer_idx, decoder_layer in enumerate(self.layers):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
routed_experts=routed_experts_layer,
)
hidden_states = self.norm(hidden_states)
return MoeModelOutputWithPast(last_hidden_state=hidden_states)
# ---------------------------------------------------------------------------
# VLM composite model body
# ---------------------------------------------------------------------------
def _build_text_config(composite_config: PretrainedConfig) -> Qwen3_5MoeConfig:
"""Build custom PrimeRL text config from HF's composite VLM config."""
text_dict = composite_config.text_config.to_dict()
text_config = Qwen3_5MoeConfig(**text_dict)
attn_impl = getattr(
composite_config.text_config,
"_attn_implementation",
getattr(composite_config, "_attn_implementation", None),
)
if attn_impl is not None:
text_config._attn_implementation = attn_impl
return text_config
class Qwen3_5MoeVLMModel(nn.Module):
"""Composite VLM body: HF vision encoder + custom PrimeRL text model."""
def __init__(self, config: PretrainedConfig):
super().__init__()
self.config = config
self.visual = Qwen3_5MoeVisionModel._from_config(config.vision_config)
self.language_model = Qwen3_5MoeModel(_build_text_config(config))
def get_input_embeddings(self):
return self.language_model.embed_tokens
def set_input_embeddings(self, value):
self.language_model.embed_tokens = value
def forward(
self,
input_ids: torch.LongTensor | None = None,
position_ids: torch.LongTensor | None = None,
inputs_embeds: torch.FloatTensor | None = None,
pixel_values: torch.Tensor | None = None,
image_grid_thw: torch.LongTensor | None = None,
routed_experts: torch.LongTensor | None = None,
**kwargs,
) -> MoeModelOutputWithPast:
if inputs_embeds is None:
inputs_embeds = self.language_model.embed_tokens(input_ids)
if pixel_values is not None:
pixel_values = pixel_values.type(self.visual.dtype)
vision_output = self.visual(pixel_values, grid_thw=image_grid_thw, return_dict=True)
image_embeds = vision_output.pooler_output.to(inputs_embeds.device, inputs_embeds.dtype)
image_mask = input_ids == self.config.image_token_id
image_mask = image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
return self.language_model(
inputs_embeds=inputs_embeds,
position_ids=position_ids,
routed_experts=routed_experts,
)
# ---------------------------------------------------------------------------
# Unified CausalLM / VLM class
# ---------------------------------------------------------------------------
def _has_vlm_keys(state_dict: dict[str, Tensor]) -> bool:
return any(k.startswith("model.language_model.") for k in state_dict)
def _remap_lm_keys(state_dict: dict[str, Tensor], to_flat: bool = True) -> None:
"""Remap language model keys between VLM and flat format for weight conversion.
to_flat=True: model.language_model.* -> model.*
to_flat=False: model.* -> model.language_model.*
Vision keys (model.visual.*) are never touched.
"""
src = "model.language_model." if to_flat else "model."
dst = "model." if to_flat else "model.language_model."
for k in [k for k in list(state_dict.keys()) if k.startswith(src) and not k.startswith("model.visual.")]:
state_dict[dst + k[len(src) :]] = state_dict.pop(k)
class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
"""Unified Qwen3.5 MoE model for both text-only and VLM configs.
When config has a vision_config, creates a composite model with HF's frozen
vision encoder + custom text model. Otherwise creates a text-only model.
"""
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_checkpoint_conversion_mapping = {}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config, **kwargs):
super().__init__(config, **kwargs)
self._is_vlm = hasattr(config, "vision_config")
if self._is_vlm:
self.model = Qwen3_5MoeVLMModel(config)
text_config = config.text_config
self._tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
else:
self.model = Qwen3_5MoeModel(config)
text_config = config
self.vocab_size = text_config.vocab_size
self.lm_head = nn.Linear(text_config.hidden_size, text_config.vocab_size, bias=False)
self.post_init()
def get_input_embeddings(self):
if self._is_vlm:
return self.model.get_input_embeddings()
return self.model.embed_tokens
def set_input_embeddings(self, value):
if self._is_vlm:
self.model.set_input_embeddings(value)
else:
self.model.embed_tokens = value
def set_decoder(self, decoder):
self.model = decoder
def get_decoder(self):
return self.model
# ------------------------------------------------------------------
# State dict detection & conversion (handles both text-only and VLM)
# ------------------------------------------------------------------
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any(
"mlp.experts.gate_up_proj" in name
or "mlp.experts.1.up_proj" in name
or "mlp.shared_expert.gate_proj" in name
for name in state_dict
)
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any("mlp.experts.w1" in name for name in state_dict)
@classmethod
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
vlm = _has_vlm_keys(state_dict)
if vlm:
_remap_lm_keys(state_dict, to_flat=True)
convert_tt_to_hf_moe(state_dict)
if vlm:
_remap_lm_keys(state_dict, to_flat=False)
return state_dict
@classmethod
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
vlm = _has_vlm_keys(state_dict)
if vlm:
_remap_lm_keys(state_dict, to_flat=True)
convert_hf_to_tt_moe(state_dict)
if vlm:
_remap_lm_keys(state_dict, to_flat=False)
return state_dict
@classmethod
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
vlm = _has_vlm_keys(state_dict)
if vlm:
_remap_lm_keys(state_dict, to_flat=True)
convert_tt_layer_to_hf(state_dict, layer_idx)
if vlm:
_remap_lm_keys(state_dict, to_flat=False)
return state_dict
@classmethod
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
vlm = _has_vlm_keys(state_dict)
if vlm:
_remap_lm_keys(state_dict, to_flat=True)
convert_hf_layer_to_tt(state_dict, layer_idx)
if vlm:
_remap_lm_keys(state_dict, to_flat=False)
return state_dict
# ------------------------------------------------------------------
# Forward
# ------------------------------------------------------------------
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
temperature: Union[torch.Tensor, None] = None,
routed_experts: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.Tensor] = None,
image_grid_thw: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
assert use_cache is None, "use_cache is not supported for custom qwen3_5_moe for now"
assert past_key_values is None, "past_key_values is not supported for custom qwen3_5_moe for now"
if position_ids is None:
if inputs_embeds is not None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
elif input_ids is not None:
position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0)
if self._is_vlm:
outputs: MoeModelOutputWithPast = self.model(
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
routed_experts=routed_experts,
)
else:
outputs = self.model(
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
routed_experts=routed_experts,
)
hidden_states = outputs.last_hidden_state
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
return self.lm_head(
hidden_states[:, slice_indices, :],
labels[:, slice_indices] if labels is not None else None,
temperature=temperature,
)
# ------------------------------------------------------------------
# Buffer init after meta-device loading
# ------------------------------------------------------------------
def init_buffers_post_meta(self):
if self._is_vlm:
lm_rope = self.model.language_model.rotary_emb
else:
lm_rope = self.model.rotary_emb
if hasattr(lm_rope, "rope_init_fn"):
inv_freq, lm_rope.attention_scaling = lm_rope.rope_init_fn(lm_rope.config, lm_rope.inv_freq.device)
lm_rope.inv_freq.copy_(inv_freq)
if self._is_vlm:
vis_rope = self.model.visual.rotary_pos_emb
if hasattr(vis_rope, "inv_freq"):
dim = vis_rope.inv_freq.shape[0]
inv_freq = 1.0 / (
10000.0
** (torch.arange(0, dim * 2, 2, dtype=torch.float32, device=vis_rope.inv_freq.device) / (dim * 2))
)
vis_rope.inv_freq.copy_(inv_freq)
__all__ = [
"Qwen3_5MoeForCausalLM",
"Qwen3_5MoeModel",
"Qwen3_5MoePreTrainedModel",
]
+13 -11
View File
@@ -19,6 +19,7 @@ from prime_rl.trainer.weights import get_max_layer_num
from prime_rl.utils.logger import get_logger
from prime_rl.utils.pathing import sync_wait_for_path
from prime_rl.utils.utils import get_broadcast_dir, get_step_path
from prime_rl.utils.vlm import get_layer_prefix
NCCL_READY_MARKER = "NCCL_READY"
@@ -67,19 +68,19 @@ def broadcast_state_dict(state_dict: dict[str, Tensor], communicator: PyNcclComm
def filter_state_dict_by_layers(
state_dict: dict[str, torch.Tensor], num_layers: int
state_dict: dict[str, torch.Tensor], num_layers: int, layer_prefix: str
) -> Generator[tuple[int, dict[str, torch.Tensor]], None, None]:
"""Yield a generator of state dicts for each layer as well as the remaining weights."""
yield 0, {key: value for key, value in state_dict.items() if "model.layers" not in key}
"""Yield non-layer weights first, then each layer's weights.
for i in range(1, num_layers + 1): # +1 because layer indices start from 1
Yields (layer_idx, layer_state_dict) where layer_idx is -1 for the non-layer
dict and the actual layer index (0, 1, ...) for layer dicts.
"""
yield -1, {key: value for key, value in state_dict.items() if not key.startswith(layer_prefix)}
for i in range(num_layers):
yield (
i,
{
key: value
for key, value in state_dict.items()
if key.startswith(f"model.layers.{i}.") or key == f"model.layers.{i}"
},
{key: value for key, value in state_dict.items() if key.startswith(f"{layer_prefix}{i}.")},
)
@@ -112,7 +113,8 @@ class NCCLWeightBroadcastSender:
def broadcast_weights(self, model: nn.Module, step: int) -> None:
"""Broadcast the state dict of a model into the inference pool using NCCL."""
state_dict = model.state_dict()
num_layers = get_max_layer_num(state_dict)
layer_prefix = get_layer_prefix(model.config)
num_layers = get_max_layer_num(state_dict, layer_prefix)
num_state_dict_to_send = num_layers + 1 # we send all layer plus the remaining weights
if self.world.is_master:
@@ -120,7 +122,7 @@ class NCCLWeightBroadcastSender:
self.logger.debug(f"Broadcasting {num_state_dict_to_send} layer state dicts")
for layer_id, state_dict in filter_state_dict_by_layers(state_dict, num_layers):
for layer_id, state_dict in filter_state_dict_by_layers(state_dict, num_layers, layer_prefix):
for key, value in list(state_dict.items()):
if isinstance(value, DTensor):
value = cast(DTensor, value.to(self.dtype)).full_tensor()
+9 -2
View File
@@ -33,9 +33,16 @@ def _strip_pytorch_wrapper_prefix(key: str) -> str:
return key
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
def get_max_layer_num(state_dict: dict[str, Tensor], layer_prefix: str = "model.layers.") -> int:
"""Get the maximum number of layers in the model."""
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
max_num = -1
for key in state_dict:
if not key.startswith(layer_prefix):
continue
layer_num_str = key[len(layer_prefix) :].split(".")[0]
if layer_num_str.isdigit():
max_num = max(max_num, int(layer_num_str))
return max_num + 1
def load_state_dict_keys(save_dir: Path) -> list[str]:
+1
View File
@@ -134,6 +134,7 @@ def setup_clients(client_config: ClientConfig, client_type: str = "openai_chat_c
api_base_url=base_url,
api_key_var=client_config.api_key_var,
timeout=client_config.timeout,
connect_timeout=client_config.connect_timeout,
max_connections=8192,
max_keepalive_connections=8192,
max_retries=10,
+1
View File
@@ -170,6 +170,7 @@ class ElasticInferencePool:
setup_clients(
ClientConfig(
timeout=self.client_config.timeout,
connect_timeout=self.client_config.connect_timeout,
base_url=urls,
api_key_var=self.client_config.api_key_var,
headers=self.client_config.headers,
+38 -1
View File
@@ -5,6 +5,8 @@ This module provides a single source of truth for supported VLM models.
import fnmatch
from transformers.configuration_utils import PretrainedConfig
# Whitelist of supported VLM model patterns (supports wildcards)
# Add new patterns here as they are tested and supported
SUPPORTED_VLM_PATTERNS = [
@@ -12,9 +14,35 @@ SUPPORTED_VLM_PATTERNS = [
"Qwen/Qwen3.5*",
]
DEFAULT_LAYER_PREFIX = "model.layers."
# Per-VLM registry: model_type -> layer key prefix.
# VLM models nest the text decoder under a different prefix
# (e.g. 'model.language_model.layers.' instead of 'model.layers.').
# Add new VLM model types here — this is the single source of truth.
VLM_REGISTRY: dict[str, str] = {
"qwen3_vl": "model.language_model.layers.",
"qwen3_5": "model.language_model.layers.",
"qwen3_5_moe": "model.language_model.layers.",
}
# Derived from the registry — used by is_vlm_config()
SUPPORTED_VLM_MODEL_TYPES = set(VLM_REGISTRY)
def get_layer_prefix(model_config: PretrainedConfig) -> str:
"""Return the layer key prefix for a model config.
VLM models nest their text decoder under a different prefix
(e.g. 'model.language_model.layers.') while standard decoder
models use 'model.layers.'.
"""
model_type = getattr(model_config, "model_type", None)
return VLM_REGISTRY.get(model_type, DEFAULT_LAYER_PREFIX)
def is_vlm_model(model_name: str) -> bool:
"""Check if a model is a supported vision-language model.
"""Check if a model is a supported vision-language model by name pattern.
Args:
model_name: The model name or path (e.g., "Qwen/Qwen3-VL-4B-Instruct")
@@ -24,3 +52,12 @@ def is_vlm_model(model_name: str) -> bool:
"""
model_name_lower = model_name.lower()
return any(fnmatch.fnmatch(model_name_lower, pattern.lower()) for pattern in SUPPORTED_VLM_PATTERNS)
def is_vlm_config(model_config: PretrainedConfig) -> bool:
"""Check if a loaded model config is a VLM by its model_type.
This catches VLMs loaded from local paths where the name doesn't match
the hub patterns.
"""
return getattr(model_config, "model_type", None) in SUPPORTED_VLM_MODEL_TYPES
+100 -1
View File
@@ -1,8 +1,34 @@
import asyncio
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock
from unittest.mock import AsyncMock, MagicMock, patch
from prime_rl.orchestrator.scheduler import InflightRolloutInfo, Scheduler
from prime_rl.utils.async_utils import safe_cancel
def make_scheduler() -> Scheduler:
scheduler = Scheduler.__new__(Scheduler)
scheduler.max_async_level = 1
scheduler.strict_async_level = False
scheduler.step = 9
scheduler.ckpt_step = 7
scheduler.config = SimpleNamespace(output_dir=Path("/tmp/prime-rl-test"))
scheduler.logger = MagicMock()
scheduler.checkpoint_ready = asyncio.Event()
scheduler.checkpoint_ready.set()
scheduler.lora_name = None
scheduler.model_name = "test-model"
scheduler.update_weights_time = 0
scheduler.wait_for_ckpt_time = 0
scheduler.inflight_requests = {}
scheduler.groups = {}
scheduler.max_off_policy_steps = 1
scheduler.cancelled_rollouts_count = 0
scheduler.policy_update_lock = asyncio.Lock()
scheduler.inflight_policy_update_task = None
scheduler.update_policy_task = None
return scheduler
def test_update_off_policy_does_not_increment_interleaved_on_policy_tasks():
@@ -59,3 +85,76 @@ def test_update_off_policy_does_not_increment_interleaved_on_policy_tasks():
await asyncio.sleep(0)
asyncio.run(run())
def test_maybe_update_policy_reuses_inflight_update_after_cancellation():
async def run() -> None:
scheduler = make_scheduler()
started = asyncio.Event()
release = asyncio.Event()
applied_steps: list[int] = []
async def update_weights(weight_dir, lora_name=None, step=0) -> None:
applied_steps.append(step)
started.set()
await release.wait()
scheduler.inference_pool = SimpleNamespace(
update_weights=update_weights,
update_model_name=MagicMock(),
)
scheduler._update_off_policy = AsyncMock()
with (
patch("prime_rl.orchestrator.scheduler.get_latest_ckpt_step", return_value=8),
patch("prime_rl.orchestrator.scheduler.wait_for_path", new=AsyncMock()),
):
first = asyncio.create_task(scheduler.maybe_update_policy())
await started.wait()
await safe_cancel(first)
second = asyncio.create_task(scheduler.maybe_update_policy())
await asyncio.sleep(0)
assert applied_steps == [8]
release.set()
await second
assert applied_steps == [8]
assert scheduler.ckpt_step == 8
asyncio.run(run())
def test_stop_cancels_inflight_policy_update_task():
async def run() -> None:
scheduler = make_scheduler()
started = asyncio.Event()
cancelled = asyncio.Event()
async def update_weights(weight_dir, lora_name=None, step=0) -> None:
started.set()
try:
await asyncio.Future()
finally:
cancelled.set()
scheduler.inference_pool = SimpleNamespace(
update_weights=update_weights,
update_model_name=MagicMock(),
)
scheduler._update_off_policy = AsyncMock()
with (
patch("prime_rl.orchestrator.scheduler.get_latest_ckpt_step", return_value=8),
patch("prime_rl.orchestrator.scheduler.wait_for_path", new=AsyncMock()),
):
scheduler.update_policy_task = asyncio.create_task(scheduler.maybe_update_policy())
await started.wait()
await asyncio.wait_for(scheduler.stop(), timeout=0.2)
assert cancelled.is_set()
assert scheduler.update_policy_task is None
assert scheduler.inflight_policy_update_task is None
asyncio.run(run())
+135
View File
@@ -0,0 +1,135 @@
import pytest
import torch
from transformers import Qwen3_5MoeForCausalLM as HFQwen3_5MoeForCausalLM
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeForCausalLM as PrimeRLQwen3_5MoeForCausalLM
from prime_rl.utils.utils import default_dtype
pytestmark = [pytest.mark.gpu]
def get_model_pairs():
config = Qwen3_5MoeConfig(
vocab_size=256,
hidden_size=256,
num_hidden_layers=4,
num_attention_heads=4,
num_key_value_heads=2,
head_dim=64,
moe_intermediate_size=128,
shared_expert_intermediate_size=128,
num_experts=8,
num_experts_per_tok=2,
max_position_embeddings=512,
rms_norm_eps=1e-6,
linear_conv_kernel_dim=4,
linear_key_head_dim=32,
linear_value_head_dim=32,
linear_num_key_heads=4,
linear_num_value_heads=8,
use_grouped_mm=False,
)
config._attn_implementation = "sdpa"
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFQwen3_5MoeForCausalLM._from_config(config)
prime_model = PrimeRLQwen3_5MoeForCausalLM._from_config(config)
with torch.no_grad():
state_dict = hf_model.state_dict()
prime_state_keys = prime_model.state_dict().keys()
prime_model.convert_to_prime(state_dict)
prime_model.load_state_dict(state_dict)
inject_prime_lm_head(prime_model, chunk_size=None)
assert set(prime_state_keys) - set(state_dict.keys()) == set()
return hf_model, prime_model
def test_qwen3_5_moe():
hf_model, prime_model = get_model_pairs()
with torch.device("cuda"), default_dtype(torch.float32):
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
position_ids = torch.arange(1, 101).unsqueeze(0)
hf_output = hf_model(input_ids, position_ids=position_ids)
prime_output = prime_model(input_ids, position_ids=position_ids)
hf_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
def test_qwen3_5_moe_roundtrip():
"""Verify HF → PrimeRL → HF weight conversion is lossless at the state_dict level."""
hf_model, prime_model = get_model_pairs()
# Get original HF state_dict and the PrimeRL-converted version
original_hf_sd = hf_model.state_dict()
prime_sd = prime_model.state_dict()
# Convert PrimeRL → per-expert HF format
converted_hf_sd = PrimeRLQwen3_5MoeForCausalLM.convert_to_hf(dict(prime_sd))
# Also convert original HF (fused) to per-expert format for comparison
# First convert original HF → PrimeRL, then back to per-expert HF
orig_prime_sd = dict(original_hf_sd)
PrimeRLQwen3_5MoeForCausalLM.convert_to_prime(orig_prime_sd)
orig_roundtripped = dict(orig_prime_sd)
PrimeRLQwen3_5MoeForCausalLM.convert_to_hf(orig_roundtripped)
# All non-expert keys should match exactly, expert keys should match after roundtrip
for key in orig_roundtripped:
assert key in converted_hf_sd, f"Missing key: {key}"
assert torch.equal(orig_roundtripped[key], converted_hf_sd[key]), f"Mismatch at {key}"
def test_qwen3_5_moe_router_replay():
"""When routed_experts are provided, the model uses them instead of computing routing."""
_, prime_model = get_model_pairs()
with torch.device("cuda"), default_dtype(torch.float32):
input_ids = torch.randint(0, prime_model.config.vocab_size, (1, 100))
position_ids = torch.arange(1, 101).unsqueeze(0)
out_normal = prime_model(input_ids, position_ids=position_ids)
num_layers = prime_model.config.num_hidden_layers
topk = prime_model.config.num_experts_per_tok
routed_experts = torch.randint(0, prime_model.config.num_experts, (1, 100, num_layers, topk), device="cuda")
prime_model.zero_grad()
out_replay = prime_model(input_ids, position_ids=position_ids, routed_experts=routed_experts)
assert out_replay["logits"].shape == out_normal["logits"].shape
out_replay["logits"].sum().backward()
assert prime_model.model.embed_tokens.weight.grad is not None
def test_qwen3_5_moe_cp_patching():
"""Verify substitute_ring_attn patches Qwen3_5MoeGatedFlashAttention._compute_attention."""
from unittest.mock import MagicMock
from prime_rl.trainer.models.layers.attn import substitute_ring_attn
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
original_method = Qwen3_5MoeGatedFlashAttention._compute_attention
mock_group = MagicMock()
substitute_ring_attn(process_group=mock_group, heads_k_stride=1)
assert Qwen3_5MoeGatedFlashAttention._compute_attention is not original_method
# Restore to avoid polluting other tests
Qwen3_5MoeGatedFlashAttention._compute_attention = original_method
if __name__ == "__main__":
test_qwen3_5_moe()
@@ -0,0 +1,215 @@
import pytest
import torch
from transformers import AutoConfig
from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import (
Qwen3_5MoeForConditionalGeneration as HFQwen3_5MoeVLM,
)
from prime_rl.trainer.model import can_reinit_empty_buffers
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeForCausalLM
from prime_rl.utils.utils import default_dtype
pytestmark = [pytest.mark.gpu]
def _tiny_vlm_config():
"""HF composite config shrunk for unit testing."""
config = AutoConfig.from_pretrained("Qwen/Qwen3.5-35B-A3B", trust_remote_code=True, attn_implementation="sdpa")
config.use_cache = False
tc = config.text_config
tc.vocab_size = 256
tc.hidden_size = 256
tc.num_hidden_layers = 2
tc.num_attention_heads = 4
tc.num_key_value_heads = 2
tc.head_dim = 64
tc.moe_intermediate_size = 128
tc.shared_expert_intermediate_size = 128
tc.num_experts = 4
tc.num_experts_per_tok = 2
tc.max_position_embeddings = 512
tc.linear_key_head_dim = 32
tc.linear_value_head_dim = 32
tc.linear_num_key_heads = 4
tc.linear_num_value_heads = 8
tc.use_cache = False
vc = config.vision_config
vc.depth = 2
vc.hidden_size = 128
vc.intermediate_size = 256
vc.num_heads = 4
vc.out_hidden_size = tc.hidden_size
# Special token IDs must fit within the tiny vocab
config.image_token_id = 250
config.video_token_id = 251
config.vision_start_token_id = 252
config.vision_end_token_id = 253
return config
def _make_image_inputs(config, device="cuda", dtype=torch.float32):
"""Create minimal image inputs matching the vision config."""
vc = config.vision_config
patch_dim = vc.in_channels * vc.temporal_patch_size * vc.patch_size * vc.patch_size
image_grid_thw = torch.tensor([[1, 2, 2]], device=device)
num_patches = int(image_grid_thw.prod().item())
pixel_values = torch.randn(num_patches, patch_dim, device=device, dtype=dtype)
num_image_tokens = num_patches // (vc.spatial_merge_size**2)
return pixel_values, image_grid_thw, num_image_tokens
def test_vlm_forward():
"""Custom VLM produces logits for both text-only and multimodal inputs."""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.float32):
model = Qwen3_5MoeForCausalLM(config)
inject_prime_lm_head(model)
vocab = config.text_config.vocab_size
# Text-only (avoid special token range 250-253)
input_ids = torch.randint(0, 200, (1, 20), device="cuda")
position_ids = torch.arange(1, 21, device="cuda").unsqueeze(0)
out_text = model(input_ids=input_ids, position_ids=position_ids)
assert out_text["logits"].shape == (1, 20, vocab)
# Multimodal
pixel_values, image_grid_thw, n_img_tokens = _make_image_inputs(config)
text_part = torch.randint(0, 200, (1, 10), device="cuda")
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
input_ids_mm = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
out_mm = model(input_ids=input_ids_mm, pixel_values=pixel_values, image_grid_thw=image_grid_thw)
assert out_mm["logits"].shape == (1, input_ids_mm.shape[1], vocab)
def test_vlm_backward():
"""Gradients flow through both vision scatter and text model."""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.float32):
model = Qwen3_5MoeForCausalLM(config)
inject_prime_lm_head(model)
pixel_values, image_grid_thw, n_img_tokens = _make_image_inputs(config)
text_part = torch.randint(0, 200, (1, 10), device="cuda")
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
input_ids = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
out = model(input_ids=input_ids, pixel_values=pixel_values, image_grid_thw=image_grid_thw)
out["logits"].sum().backward()
assert model.model.language_model.embed_tokens.weight.grad is not None
assert model.model.visual.patch_embed.proj.weight.grad is not None
def test_vlm_weight_load_from_hf():
"""Weights from HF VLM checkpoint load correctly into custom VLM after conversion.
Text model numerical match is already validated by test_qwen3_5_moe.py::test_qwen3_5_moe.
This test verifies that VLM weight conversion + loading produces a working model.
"""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFQwen3_5MoeVLM._from_config(config)
prime_model = Qwen3_5MoeForCausalLM(config)
# Copy weights: HF -> PrimeRL (with MoE conversion)
with torch.no_grad():
hf_sd = hf_model.state_dict()
prime_model.convert_to_prime(hf_sd)
prime_model.load_state_dict(hf_sd)
inject_prime_lm_head(prime_model)
# Verify vision encoder weights match exactly (should be untouched by conversion)
for name, param in hf_model.model.visual.named_parameters():
prime_param = dict(prime_model.model.visual.named_parameters())[name]
assert torch.equal(param, prime_param), f"Vision weight mismatch: {name}"
# Verify model produces output after weight loading
input_ids = torch.randint(0, 200, (1, 20), device="cuda")
position_ids = torch.arange(1, 21, device="cuda").unsqueeze(0)
out = prime_model(input_ids=input_ids, position_ids=position_ids)
assert out["logits"].shape[2] == config.text_config.vocab_size
assert not torch.isnan(out["logits"]).any()
def test_vlm_weight_roundtrip():
"""HF -> PrimeRL -> HF weight conversion is lossless (vision keys untouched, text keys converted)."""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFQwen3_5MoeVLM._from_config(config)
hf_sd = hf_model.state_dict()
original_vision_key = "model.visual.blocks.0.mlp.linear_fc1.weight"
original_vision_weight = hf_sd[original_vision_key].clone()
# HF -> PrimeRL
prime_sd = dict(hf_sd)
Qwen3_5MoeForCausalLM.convert_to_prime(prime_sd)
assert any("language_model" in k and "mlp.experts.w1" in k for k in prime_sd)
assert original_vision_key in prime_sd
# PrimeRL -> HF
roundtripped = dict(prime_sd)
Qwen3_5MoeForCausalLM.convert_to_hf(roundtripped)
# Original HF also needs roundtrip for expert format normalization
orig_rt = dict(hf_sd)
Qwen3_5MoeForCausalLM.convert_to_prime(orig_rt)
Qwen3_5MoeForCausalLM.convert_to_hf(orig_rt)
for key in orig_rt:
assert key in roundtripped, f"Missing key: {key}"
assert torch.equal(orig_rt[key], roundtripped[key]), f"Mismatch at {key}"
# Vision weights preserved through the whole roundtrip
assert torch.equal(roundtripped[original_vision_key], original_vision_weight)
def test_vlm_router_replay():
"""routed_experts bypasses router computation in VLM multimodal forward."""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.float32):
model = Qwen3_5MoeForCausalLM(config)
inject_prime_lm_head(model)
vocab = config.text_config.vocab_size
pixel_values, image_grid_thw, n_img_tokens = _make_image_inputs(config)
text_part = torch.randint(0, 200, (1, 10), device="cuda")
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
input_ids = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
seq_len = input_ids.shape[1]
num_layers = config.text_config.num_hidden_layers
topk = config.text_config.num_experts_per_tok
routed_experts = torch.randint(0, config.text_config.num_experts, (1, seq_len, num_layers, topk), device="cuda")
out = model(
input_ids=input_ids, pixel_values=pixel_values, image_grid_thw=image_grid_thw, routed_experts=routed_experts
)
assert out["logits"].shape == (1, seq_len, vocab)
out["logits"].sum().backward()
assert model.model.language_model.embed_tokens.weight.grad is not None
def test_vlm_meta_device_and_buffer_reinit():
"""Model can be created on meta device and buffers reinitialized."""
config = _tiny_vlm_config()
with torch.device("meta"):
model = Qwen3_5MoeForCausalLM.from_config(config)
assert can_reinit_empty_buffers(model)
model.to_empty(device="cuda")
model.init_buffers_post_meta()
lm_inv = model.model.language_model.rotary_emb.inv_freq
vis_inv = model.model.visual.rotary_pos_emb.inv_freq
assert lm_inv.device.type == "cuda"
assert vis_inv.device.type == "cuda"
assert lm_inv.abs().sum() > 0
assert vis_inv.abs().sum() > 0