feat(cp): context parallelism for hybrid + VLM SFT (#3099)
* feat(cp): context parallelism for hybrid + VLM SFT Unify model CP setup and make packed-boundary metadata CP-aware: - setup_model_cp replaces setup_hybrid_cp/setup_nemotron_h_cp: models owning linear-attention/Mamba layers expose set_context_parallel_attributes (dense + MoE Qwen3.5, NemotronH) and wire their own layers; hybrid models without the hook are rejected instead of silently misconfigured. - seq_lens stays global under CP: documents can straddle the shard cut, so input_ids/position_ids shard per rank while seq_lens keeps the full pre-shard boundaries, flagged via seq_lens_are_global through forward() / prime_forward_kwargs into both Qwen3.5 models. A cu_seqlens_are_global provenance flag rides along to fla's GatedDeltaNet instead of reading cu_seqlens back (which cost one CPU-GPU sync per linear-attention layer per microbatch); the CP conv path switches to fla's causal_conv1d with a CP context so conv state passes between ranks with document-boundary resets. - VLM CP defers sharding to the model: the vision encoder and the image-embed merge see the full sequence, then the root forward shards embeds/positions (shard_position_ids_for_cp handles 3D MRoPE) and updates ulysses attention params from global seq_lens. The SFT trainer skips pre-sharding for MRoPE batches; the vision encoder is pinned to SDPA under CP. - shard_for_cp validates divisibility (uneven shards deadlock ulysses all-to-all) and CatDataset's seq_len padding guarantees it; the LoRA token count follows the sharded loss_mask. - Qwen3.5 CP requires the custom implementation (the HF impl has no set_context_parallel_attributes); rejected in get_model.
This commit is contained in:
@@ -318,8 +318,8 @@ class SFTConfig(BaseConfig):
|
||||
raise ValueError(
|
||||
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
|
||||
)
|
||||
if self.model.cp > 1:
|
||||
raise ValueError("VLM SFT does not support context parallelism yet.")
|
||||
if self.model.cp > 1 and self.model.cp_style != "ulysses":
|
||||
raise ValueError("VLM models require cp_style='ulysses' for context parallelism")
|
||||
if self.data.micro_batch_size != 1:
|
||||
raise ValueError("VLM SFT requires data.micro_batch_size = 1.")
|
||||
if self.val is not None and self.val.data.micro_batch_size != 1:
|
||||
|
||||
@@ -242,21 +242,13 @@ class ModelConfig(BaseModelConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def cp_only_with_flash_attn(self):
|
||||
def validate_cp(self):
|
||||
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]:
|
||||
raise ValueError("CP is only supported with flash attention 2, 3, or 4")
|
||||
if (
|
||||
self.cp > 1
|
||||
and self.attn in ("flash_attention_3", "flash_attention_4", "auto")
|
||||
and self.impl not in ("custom", "auto")
|
||||
):
|
||||
# Both ring and ulysses route FA3/FA4 through our custom FlashAttention class:
|
||||
# ring patches `_compute_attention` with the ring kernel, ulysses patches it with
|
||||
# the all-to-all wrapper around the FA3/FA4 kernel. The HF path patches
|
||||
# `_flash_attention_forward` which only wraps FA2.
|
||||
if self.cp > 1 and self.impl not in ("custom", "auto"):
|
||||
raise ValueError(
|
||||
f"CP with {self.attn} requires model.impl='custom' or 'auto' "
|
||||
"(FA3/FA4 paths are only implemented for the custom model attention class)"
|
||||
"Context parallelism requires model.impl='custom' or 'auto' "
|
||||
"(resolved to a custom PrimeRL implementation)"
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
@@ -153,11 +153,38 @@ def _patch_qwen3_5_linear_attn_varlen():
|
||||
apply_mask_to_padding_states,
|
||||
)
|
||||
|
||||
try:
|
||||
from fla.modules.convolution import causal_conv1d as fla_causal_conv1d
|
||||
from fla.ops.cp import build_cp_context
|
||||
except ImportError:
|
||||
build_cp_context = None
|
||||
fla_causal_conv1d = None
|
||||
|
||||
if fla_causal_conv1d is not None:
|
||||
# The CP boundary-state exchange inside fla's conv is not dynamo-traceable;
|
||||
# graph-break deliberately so the rest of the layer still compiles.
|
||||
fla_causal_conv1d = torch.compiler.disable(fla_causal_conv1d)
|
||||
|
||||
if getattr(Qwen3_5GatedDeltaNet.forward, "_prl_varlen_patched", False):
|
||||
return
|
||||
|
||||
_gdn_orig = Qwen3_5GatedDeltaNet.forward
|
||||
|
||||
def _build_cp_context(self, local_seq_len: int, device: torch.device, cu_seqlens=None):
|
||||
cp_group = getattr(self, "cp_group", None)
|
||||
if cp_group is None or build_cp_context is None:
|
||||
return None
|
||||
global_seq_len = local_seq_len * self.cp_world_size
|
||||
if cu_seqlens is not None and int(cu_seqlens[-1].item()) == global_seq_len:
|
||||
global_cu_seqlens = cu_seqlens.to(device=device, dtype=torch.int32)
|
||||
else:
|
||||
global_cu_seqlens = torch.tensor([0, global_seq_len], dtype=torch.int32, device=device)
|
||||
return build_cp_context(
|
||||
cu_seqlens=global_cu_seqlens,
|
||||
group=cp_group,
|
||||
conv1d_kernel_size=self.conv_kernel_size,
|
||||
)
|
||||
|
||||
def _gdn_forward(self, hidden_states, cache_params=None, attention_mask=None, cu_seqlens=None):
|
||||
if cu_seqlens is None or cache_params is not None:
|
||||
return _gdn_orig(self, hidden_states, cache_params=cache_params, attention_mask=attention_mask)
|
||||
@@ -170,7 +197,18 @@ def _patch_qwen3_5_linear_attn_varlen():
|
||||
b = self.in_proj_b(hidden_states)
|
||||
a = self.in_proj_a(hidden_states)
|
||||
|
||||
if self.causal_conv1d_fn is not None:
|
||||
cp_context = _build_cp_context(self, seq_len, hidden_states.device, cu_seqlens)
|
||||
|
||||
if cp_context is not None and fla_causal_conv1d is not None:
|
||||
mixed_qkv, _ = fla_causal_conv1d(
|
||||
x=mixed_qkv.transpose(1, 2),
|
||||
weight=self.conv1d.weight.squeeze(1),
|
||||
bias=self.conv1d.bias,
|
||||
activation=self.activation,
|
||||
cp_context=cp_context,
|
||||
)
|
||||
mixed_qkv = mixed_qkv.transpose(1, 2)
|
||||
elif self.causal_conv1d_fn is not None:
|
||||
seg_lens = cu_seqlens[1:] - cu_seqlens[:-1]
|
||||
seq_idx = torch.repeat_interleave(
|
||||
torch.arange(seg_lens.numel(), dtype=torch.int32, device=hidden_states.device),
|
||||
@@ -206,17 +244,29 @@ def _patch_qwen3_5_linear_attn_varlen():
|
||||
query = query.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
|
||||
key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
|
||||
|
||||
core_attn_out, _ = self.chunk_gated_delta_rule(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
g=g,
|
||||
beta=beta,
|
||||
initial_state=None,
|
||||
output_final_state=False,
|
||||
use_qk_l2norm_in_kernel=True,
|
||||
cu_seqlens=cu_seqlens,
|
||||
)
|
||||
if cp_context is not None:
|
||||
core_attn_out, _ = self.chunk_gated_delta_rule(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
g=g,
|
||||
beta=beta,
|
||||
use_qk_l2norm_in_kernel=True,
|
||||
cu_seqlens=cp_context.cu_seqlens,
|
||||
cp_context=cp_context,
|
||||
)
|
||||
else:
|
||||
core_attn_out, _ = self.chunk_gated_delta_rule(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
g=g,
|
||||
beta=beta,
|
||||
initial_state=None,
|
||||
output_final_state=False,
|
||||
use_qk_l2norm_in_kernel=True,
|
||||
cu_seqlens=cu_seqlens,
|
||||
)
|
||||
|
||||
core_attn_out = core_attn_out.reshape(-1, self.head_v_dim)
|
||||
z = z.reshape(-1, self.head_v_dim)
|
||||
@@ -528,6 +578,13 @@ def get_model(
|
||||
_patch_qwen3_5_text_position_ids()
|
||||
_patch_qwen3_5_moe_conversion_mapping()
|
||||
_patch_qwen3_5_linear_attn_varlen()
|
||||
if is_vlm_arch and config.cp > 1 and config.cp_style == "ulysses":
|
||||
vision_config = getattr(model_config, "vision_config", None)
|
||||
if vision_config is not None:
|
||||
logger.info("Using SDPA for VLM vision encoder under CP")
|
||||
vision_config._attn_implementation = "sdpa"
|
||||
if hasattr(vision_config, "_attn_implementation_internal"):
|
||||
vision_config._attn_implementation_internal = "sdpa"
|
||||
for subconfig_key in getattr(model_config, "sub_configs", {}):
|
||||
subconfig = getattr(model_config, subconfig_key, None)
|
||||
if subconfig is not None and hasattr(subconfig, "use_cache"):
|
||||
@@ -622,6 +679,12 @@ def get_model(
|
||||
f"but model.impl resolved to 'hf'. Set model.impl='custom' explicitly."
|
||||
)
|
||||
|
||||
if config.cp > 1 and config.impl == "auto" and impl_to_use != "custom":
|
||||
raise ValueError(
|
||||
"Context parallelism with model.impl='auto' requires a supported custom PrimeRL implementation, "
|
||||
"but this architecture resolved to model.impl='hf'."
|
||||
)
|
||||
|
||||
if config.vlm is not None and not (is_vlm_arch and custom_vlm_cls):
|
||||
raise ValueError(
|
||||
"VLM training requires a registered custom PrimeRL VLM implementation; "
|
||||
@@ -1314,6 +1377,9 @@ def forward(
|
||||
# is split out because it comes from the renderer rather than the processor.
|
||||
mm_kwargs: dict[str, Tensor] | None = None,
|
||||
mm_token_type_ids: Int[Tensor, "batch seq"] | None = None,
|
||||
# True when seq_lens holds the full pre-CP-shard document boundaries
|
||||
# (kept global because documents can straddle the shard cut).
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> PrimeLmOutput:
|
||||
kwargs = {
|
||||
"input_ids": input_ids,
|
||||
@@ -1335,6 +1401,7 @@ def forward(
|
||||
|
||||
if isinstance(model, PreTrainedModelPrimeRL):
|
||||
kwargs["seq_lens"] = seq_lens
|
||||
kwargs["seq_lens_are_pre_shard"] = seq_lens_are_pre_shard
|
||||
|
||||
if routed_experts is not None:
|
||||
kwargs["routed_experts"] = routed_experts
|
||||
|
||||
@@ -386,6 +386,7 @@ class AfmoeModel(AfmoePreTrainedModel):
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> MoeModelOutputWithPast:
|
||||
"""
|
||||
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
|
||||
@@ -401,7 +402,8 @@ class AfmoeModel(AfmoePreTrainedModel):
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
|
||||
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
|
||||
seq_lens.to(device=inputs_embeds.device),
|
||||
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
|
||||
)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
causal_mask_mapping = None
|
||||
@@ -479,6 +481,7 @@ class AfmoeForCausalLM(AfmoePreTrainedModel, GenerationMixin):
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
r"""
|
||||
@@ -500,6 +503,7 @@ class AfmoeForCausalLM(AfmoePreTrainedModel, GenerationMixin):
|
||||
inputs_embeds=inputs_embeds,
|
||||
routed_experts=routed_experts,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
|
||||
@@ -207,12 +207,15 @@ class Glm4MoeModel(Glm4MoePreTrainedModel):
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> BaseModelOutputWithPast:
|
||||
"""
|
||||
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
|
||||
Routed experts for each token in the sequence. Only used for router replay.
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
|
||||
Per-document lengths of the packed row (PrimeRL packed-batch contract).
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
|
||||
"""
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
@@ -221,7 +224,8 @@ class Glm4MoeModel(Glm4MoePreTrainedModel):
|
||||
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
|
||||
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
|
||||
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
|
||||
seq_lens.to(device=inputs_embeds.device),
|
||||
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
|
||||
)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
|
||||
@@ -276,11 +280,14 @@ class Glm4MoeForCausalLM(Glm4MoePreTrainedModel, GenerationMixin):
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
r"""
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
|
||||
Per-document lengths of the packed row (PrimeRL packed-batch contract).
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
|
||||
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
||||
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
|
||||
compatibility — prime-rl asserts `use_cache is None` since training does not
|
||||
@@ -324,6 +331,7 @@ class Glm4MoeForCausalLM(Glm4MoePreTrainedModel, GenerationMixin):
|
||||
inputs_embeds=inputs_embeds,
|
||||
routed_experts=routed_experts,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
|
||||
@@ -313,11 +313,14 @@ class GlmMoeDsaForCausalLM(GlmMoeDsaPreTrainedModel, GenerationMixin):
|
||||
# trainer's universal contract.
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
r"""
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
|
||||
Per-document lengths of the packed row (PrimeRL packed-batch contract).
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
|
||||
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
||||
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
|
||||
compatibility — prime-rl asserts `use_cache is None` since training does not
|
||||
|
||||
@@ -309,11 +309,14 @@ class GptOssForCausalLM(GptOssPreTrainedModel, GenerationMixin):
|
||||
# seq_lens is accepted to satisfy the trainer's universal contract.
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
r"""
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
|
||||
Per-document lengths of the packed row (PrimeRL packed-batch contract).
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
|
||||
temperature (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
||||
Per-token temperatures for logprobs/entropy computation when `labels` are provided.
|
||||
"""
|
||||
|
||||
@@ -292,6 +292,7 @@ class LagunaModel(LagunaPreTrainedModel):
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> MoeModelOutputWithPast:
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
@@ -302,7 +303,8 @@ class LagunaModel(LagunaPreTrainedModel):
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
|
||||
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
|
||||
seq_lens.to(device=inputs_embeds.device),
|
||||
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
|
||||
)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
causal_mask_mapping = dict.fromkeys(set(self.config.layer_types), None)
|
||||
@@ -366,6 +368,7 @@ class LagunaForCausalLM(LagunaPreTrainedModel, GenerationMixin):
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
assert use_cache is None, "use_cache is not supported for custom Laguna"
|
||||
@@ -378,6 +381,7 @@ class LagunaForCausalLM(LagunaPreTrainedModel, GenerationMixin):
|
||||
inputs_embeds=inputs_embeds,
|
||||
routed_experts=routed_experts,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
hidden_states = outputs.last_hidden_state
|
||||
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
||||
|
||||
@@ -183,10 +183,13 @@ class LlamaModel(LlamaPreTrainedModel):
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> BaseModelOutputWithPast:
|
||||
r"""
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
|
||||
Per-document lengths of the packed row (PrimeRL packed-batch contract).
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
|
||||
"""
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
@@ -195,7 +198,8 @@ class LlamaModel(LlamaPreTrainedModel):
|
||||
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
|
||||
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
|
||||
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
|
||||
seq_lens.to(device=inputs_embeds.device),
|
||||
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
|
||||
)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
|
||||
@@ -247,11 +251,14 @@ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
|
||||
temperature: Optional[torch.Tensor] = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
r"""
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
|
||||
Per-document lengths of the packed row (PrimeRL packed-batch contract).
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
|
||||
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
||||
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
|
||||
compatibility — prime-rl asserts `use_cache is None` since training does not
|
||||
@@ -292,6 +299,7 @@ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
|
||||
position_ids=position_ids,
|
||||
inputs_embeds=inputs_embeds,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
|
||||
@@ -168,12 +168,15 @@ class MiniMaxM2Model(MiniMaxM2PreTrainedModel):
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> BaseModelOutputWithPast:
|
||||
"""
|
||||
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
|
||||
Routed experts for each token in the sequence. Only used for router replay.
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
|
||||
Per-document lengths of the packed row (PrimeRL packed-batch contract).
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
|
||||
"""
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
@@ -182,7 +185,8 @@ class MiniMaxM2Model(MiniMaxM2PreTrainedModel):
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
|
||||
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
|
||||
seq_lens.to(device=inputs_embeds.device),
|
||||
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
|
||||
)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
|
||||
@@ -234,11 +238,14 @@ class MiniMaxM2ForCausalLM(MiniMaxM2PreTrainedModel, GenerationMixin):
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
r"""
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
|
||||
Per-document lengths of the packed row (PrimeRL packed-batch contract).
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
|
||||
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
||||
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
|
||||
compatibility — prime-rl asserts `use_cache is None` since training does not
|
||||
@@ -265,6 +272,7 @@ class MiniMaxM2ForCausalLM(MiniMaxM2PreTrainedModel, GenerationMixin):
|
||||
inputs_embeds=inputs_embeds,
|
||||
routed_experts=routed_experts,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
|
||||
@@ -225,20 +225,22 @@ class NemotronHMambaLayer(GradientCheckpointingLayer):
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
cu_seqlens_are_pre_shard: bool = False,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.norm(hidden_states)
|
||||
|
||||
if self.cp_enabled:
|
||||
# The local cu_seqlens cover only this shard; conv/scan need the full
|
||||
# pre-shard document boundaries published by setup_cp_params.
|
||||
global_cu_seqlens = (
|
||||
cu_seqlens if cu_seqlens is not None and cu_seqlens_are_pre_shard else ULYSSES_PARAMS["cu_seqlens"]
|
||||
)
|
||||
hidden_states = mamba_cp_forward(
|
||||
self.mamba,
|
||||
hidden_states,
|
||||
self._cp_group,
|
||||
self._cp_rank,
|
||||
self._cp_world_size,
|
||||
ULYSSES_PARAMS["cu_seqlens"],
|
||||
global_cu_seqlens,
|
||||
)
|
||||
else:
|
||||
hidden_states = self.mamba(hidden_states, cu_seqlens=cu_seqlens)
|
||||
@@ -275,6 +277,7 @@ class NemotronHMoELayer(GradientCheckpointingLayer):
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
cu_seqlens_are_pre_shard: bool = False,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.norm(hidden_states)
|
||||
@@ -308,6 +311,7 @@ class NemotronHAttentionLayer(GradientCheckpointingLayer):
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
cu_seqlens_are_pre_shard: bool = False,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.norm(hidden_states)
|
||||
@@ -502,6 +506,11 @@ class NemotronHModel(NemotronHPreTrainedModel):
|
||||
self.gradient_checkpointing = False
|
||||
self.post_init()
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
for layer in self.layers.modules():
|
||||
if isinstance(layer, NemotronHMambaLayer):
|
||||
layer.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
|
||||
@auto_docstring
|
||||
def forward(
|
||||
self,
|
||||
@@ -511,6 +520,7 @@ class NemotronHModel(NemotronHPreTrainedModel):
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> BaseModelOutputWithPast:
|
||||
"""
|
||||
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
|
||||
@@ -518,6 +528,8 @@ class NemotronHModel(NemotronHPreTrainedModel):
|
||||
for non-MoE (Mamba/attention) layers are ignored.
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
|
||||
Per-document lengths of the packed row (PrimeRL packed-batch contract).
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
|
||||
"""
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
@@ -526,7 +538,8 @@ class NemotronHModel(NemotronHPreTrainedModel):
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
|
||||
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
|
||||
seq_lens.to(device=inputs_embeds.device),
|
||||
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
|
||||
)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
|
||||
@@ -542,6 +555,7 @@ class NemotronHModel(NemotronHPreTrainedModel):
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
routed_experts=routed_experts_layer,
|
||||
cu_seqlens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
@@ -562,6 +576,9 @@ class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
|
||||
def get_decoder(self):
|
||||
return self.model
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
self.model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: Optional[torch.LongTensor] = None,
|
||||
@@ -573,6 +590,7 @@ class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
**kwargs,
|
||||
) -> PrimeLmOutput:
|
||||
if position_ids is None:
|
||||
@@ -587,6 +605,7 @@ class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
|
||||
inputs_embeds=inputs_embeds,
|
||||
routed_experts=routed_experts,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
|
||||
@@ -156,10 +156,13 @@ class Qwen3Model(Qwen3PreTrainedModel):
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> BaseModelOutputWithPast:
|
||||
r"""
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
|
||||
Per-document lengths of the packed row (PrimeRL packed-batch contract).
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
|
||||
"""
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
@@ -170,7 +173,8 @@ class Qwen3Model(Qwen3PreTrainedModel):
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
|
||||
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
|
||||
seq_lens.to(device=inputs_embeds.device),
|
||||
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
|
||||
)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
|
||||
@@ -225,11 +229,14 @@ class Qwen3ForCausalLM(Qwen3PreTrainedModel, GenerationMixin):
|
||||
temperature: Optional[torch.Tensor] = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
r"""
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
|
||||
Per-document lengths of the packed row (PrimeRL packed-batch contract).
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
|
||||
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
||||
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
|
||||
compatibility; prime-rl asserts `use_cache is None` since training does not
|
||||
@@ -248,6 +255,7 @@ class Qwen3ForCausalLM(Qwen3PreTrainedModel, GenerationMixin):
|
||||
position_ids=position_ids,
|
||||
inputs_embeds=inputs_embeds,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
hidden_states = outputs.last_hidden_state
|
||||
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
||||
|
||||
@@ -28,6 +28,7 @@ from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
|
||||
normalize_qwen3_5_attn_implementation,
|
||||
)
|
||||
from prime_rl.trainer.models.qwen3_5_moe.mrope import build_qwen3_5_mrope_position_ids
|
||||
from prime_rl.utils.cp import setup_cp_attention_params, shard_for_cp, shard_position_ids_for_cp
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
|
||||
@@ -99,12 +100,15 @@ class Qwen3_5DecoderLayer(GradientCheckpointingLayer):
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
cu_seqlens_are_pre_shard: bool = False,
|
||||
) -> torch.FloatTensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
|
||||
if self.layer_type == "linear_attention":
|
||||
hidden_states = self.linear_attn(hidden_states, cu_seqlens=cu_seqlens)
|
||||
hidden_states = self.linear_attn(
|
||||
hidden_states, cu_seqlens=cu_seqlens, cu_seqlens_are_pre_shard=cu_seqlens_are_pre_shard
|
||||
)
|
||||
else:
|
||||
hidden_states, _ = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
@@ -194,6 +198,16 @@ class Qwen3_5Model(Qwen3_5PreTrainedModel):
|
||||
def set_input_embeddings(self, value):
|
||||
self.embed_tokens = value
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group, cp_rank: int, cp_world_size: int) -> None:
|
||||
self._cp_group = cp_group
|
||||
self._cp_rank = cp_rank
|
||||
self._cp_world_size = cp_world_size
|
||||
for layer in self.layers.modules():
|
||||
if getattr(layer, "layer_type", None) == "linear_attention":
|
||||
layer.linear_attn.cp_group = cp_group
|
||||
layer.linear_attn.cp_rank = cp_rank
|
||||
layer.linear_attn.cp_world_size = cp_world_size
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: Optional[torch.LongTensor] = None,
|
||||
@@ -201,6 +215,7 @@ class Qwen3_5Model(Qwen3_5PreTrainedModel):
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> BaseModelOutputWithPast:
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
@@ -212,18 +227,22 @@ class Qwen3_5Model(Qwen3_5PreTrainedModel):
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
|
||||
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
|
||||
seq_lens.to(device=inputs_embeds.device),
|
||||
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
|
||||
)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
hidden_states = inputs_embeds
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
|
||||
cu_seqlens_are_pre_shard = seq_lens_are_pre_shard
|
||||
|
||||
for decoder_layer in self.layers:
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
cu_seqlens_are_pre_shard=cu_seqlens_are_pre_shard,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
@@ -245,6 +264,9 @@ class Qwen3_5VLMModel(nn.Module):
|
||||
def set_input_embeddings(self, value):
|
||||
self.language_model.set_input_embeddings(value)
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group, cp_rank: int, cp_world_size: int) -> None:
|
||||
self.language_model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
|
||||
def _dummy_vision_inputs(self, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
vcfg = self.config.vision_config
|
||||
m = vcfg.spatial_merge_size
|
||||
@@ -306,6 +328,7 @@ class Qwen3_5VLMModel(nn.Module):
|
||||
mm_token_type_ids: torch.LongTensor | None = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> BaseModelOutputWithPast:
|
||||
inputs_embeds, position_ids = self.prepare_inputs_embeds_and_position_ids(
|
||||
input_ids=input_ids,
|
||||
@@ -316,10 +339,20 @@ class Qwen3_5VLMModel(nn.Module):
|
||||
seq_lens=seq_lens,
|
||||
)
|
||||
|
||||
cp_group = getattr(self.language_model, "_cp_group", None)
|
||||
if image_grid_thw is not None and cp_group is not None:
|
||||
cp_rank = self.language_model._cp_rank
|
||||
cp_world_size = self.language_model._cp_world_size
|
||||
setup_cp_attention_params(position_ids, cp_group=cp_group, cp_style="ulysses", seq_lens=seq_lens)
|
||||
inputs_embeds = shard_for_cp(inputs_embeds, cp_rank=cp_rank, cp_world_size=cp_world_size)
|
||||
position_ids = shard_position_ids_for_cp(position_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
|
||||
seq_lens_are_pre_shard = True
|
||||
|
||||
return self.language_model(
|
||||
inputs_embeds=inputs_embeds,
|
||||
position_ids=position_ids,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
|
||||
|
||||
@@ -359,6 +392,9 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
|
||||
def get_decoder(self):
|
||||
return self.model
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group, cp_rank: int, cp_world_size: int) -> None:
|
||||
self.model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: Optional[torch.LongTensor] = None,
|
||||
@@ -375,6 +411,7 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
|
||||
mm_token_type_ids: Optional[torch.LongTensor] = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
assert use_cache is None, "use_cache is not supported for custom qwen3_5 for now"
|
||||
@@ -388,6 +425,7 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
|
||||
image_grid_thw=image_grid_thw,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
else:
|
||||
outputs = self.model(
|
||||
@@ -395,6 +433,7 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
|
||||
position_ids=position_ids,
|
||||
inputs_embeds=inputs_embeds,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
|
||||
@@ -28,7 +28,7 @@ from prime_rl.trainer.models.layers.attn import (
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.rotary_emb import apply_rotary_pos_emb
|
||||
from prime_rl.trainer.models.layers.ulysses_attn import ULYSSES_PARAMS
|
||||
from prime_rl.utils.cp import setup_cp_attention_params, shard_for_cp, shard_position_ids_for_cp
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
from .configuration_qwen3_5_moe import Qwen3_5MoeConfig
|
||||
@@ -43,6 +43,24 @@ from .mrope import build_qwen3_5_mrope_position_ids
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
|
||||
@torch.compiler.disable
|
||||
def _fla_causal_conv1d_cp(
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
bias: torch.Tensor | None,
|
||||
activation: str,
|
||||
cp_context: FLACPContext,
|
||||
) -> torch.Tensor:
|
||||
output, _ = fla_causal_conv1d(
|
||||
x=x,
|
||||
weight=weight,
|
||||
bias=bias,
|
||||
activation=activation,
|
||||
cp_context=cp_context,
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# RMSNorm variants
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -113,16 +131,21 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
|
||||
self.in_proj_b = nn.Linear(self.hidden_size, self.num_v_heads, bias=False)
|
||||
self.in_proj_a = nn.Linear(self.hidden_size, self.num_v_heads, bias=False)
|
||||
|
||||
def _build_cp_context(self) -> "FLACPContext | None":
|
||||
"""Build fla CP context from the full pre-shard document boundaries."""
|
||||
def _build_cp_context(
|
||||
self,
|
||||
device: torch.device,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
cu_seqlens_are_pre_shard: bool = False,
|
||||
) -> "FLACPContext | None":
|
||||
"""Build the FLA CP context from full pre-shard sequence boundaries."""
|
||||
cp_group = getattr(self, "cp_group", None)
|
||||
if cp_group is None:
|
||||
return None
|
||||
# Local cu_seqlens cannot describe documents straddling shard boundaries;
|
||||
# use the full (un-sharded) cu_seqlens published by setup_cp_params. fla
|
||||
# derives per-rank boundaries and document-aware state passing from them.
|
||||
if cu_seqlens is None or not cu_seqlens_are_pre_shard:
|
||||
raise ValueError("Qwen3.5 context parallelism requires full pre-shard sequence boundaries")
|
||||
global_cu_seqlens = cu_seqlens.to(device=device, dtype=torch.int32)
|
||||
return build_cp_context(
|
||||
cu_seqlens=ULYSSES_PARAMS["cu_seqlens"],
|
||||
cu_seqlens=global_cu_seqlens,
|
||||
group=cp_group,
|
||||
conv1d_kernel_size=self.conv_kernel_size,
|
||||
)
|
||||
@@ -131,6 +154,7 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
cu_seqlens_are_pre_shard: bool = False,
|
||||
) -> torch.Tensor:
|
||||
batch_size, seq_len, _ = hidden_states.shape
|
||||
|
||||
@@ -139,18 +163,28 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
|
||||
b = self.in_proj_b(hidden_states)
|
||||
a = self.in_proj_a(hidden_states)
|
||||
|
||||
cp_context = self._build_cp_context()
|
||||
cp_context = self._build_cp_context(hidden_states.device, cu_seqlens, cu_seqlens_are_pre_shard)
|
||||
|
||||
# Causal conv1d — must reset at sequence boundaries for packed batches,
|
||||
# otherwise the kernel-1 left pad leaks state across sequences.
|
||||
mixed_qkv, _ = fla_causal_conv1d(
|
||||
x=mixed_qkv.transpose(1, 2),
|
||||
weight=self.conv1d.weight.squeeze(1),
|
||||
bias=self.conv1d.bias,
|
||||
activation=self.activation,
|
||||
cu_seqlens=cu_seqlens if cp_context is None else None,
|
||||
cp_context=cp_context,
|
||||
)
|
||||
conv_input = mixed_qkv.transpose(1, 2)
|
||||
conv_weight = self.conv1d.weight.squeeze(1)
|
||||
if cp_context is None:
|
||||
mixed_qkv, _ = fla_causal_conv1d(
|
||||
x=conv_input,
|
||||
weight=conv_weight,
|
||||
bias=self.conv1d.bias,
|
||||
activation=self.activation,
|
||||
cu_seqlens=cu_seqlens,
|
||||
)
|
||||
else:
|
||||
mixed_qkv = _fla_causal_conv1d_cp(
|
||||
x=conv_input,
|
||||
weight=conv_weight,
|
||||
bias=self.conv1d.bias,
|
||||
activation=self.activation,
|
||||
cp_context=cp_context,
|
||||
)
|
||||
query, key, value = torch.split(mixed_qkv, [self.key_dim, self.key_dim, self.value_dim], dim=-1)
|
||||
|
||||
query = query.reshape(batch_size, seq_len, -1, self.head_k_dim)
|
||||
@@ -434,13 +468,16 @@ class Qwen3_5MoeDecoderLayer(GradientCheckpointingLayer):
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
cu_seqlens_are_pre_shard: bool = False,
|
||||
) -> torch.FloatTensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
|
||||
# Token mixer
|
||||
if self.layer_type == "linear_attention":
|
||||
hidden_states = self.linear_attn(hidden_states, cu_seqlens=cu_seqlens)
|
||||
hidden_states = self.linear_attn(
|
||||
hidden_states, cu_seqlens=cu_seqlens, cu_seqlens_are_pre_shard=cu_seqlens_are_pre_shard
|
||||
)
|
||||
elif self.layer_type == "full_attention":
|
||||
hidden_states, _ = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
@@ -662,6 +699,16 @@ class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
|
||||
def set_input_embeddings(self, value):
|
||||
self.embed_tokens = value
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group, cp_rank: int, cp_world_size: int) -> None:
|
||||
self._cp_group = cp_group
|
||||
self._cp_rank = cp_rank
|
||||
self._cp_world_size = cp_world_size
|
||||
for layer in self.layers.modules():
|
||||
if getattr(layer, "layer_type", None) == "linear_attention":
|
||||
layer.linear_attn.cp_group = cp_group
|
||||
layer.linear_attn.cp_rank = cp_rank
|
||||
layer.linear_attn.cp_world_size = cp_world_size
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: Optional[torch.LongTensor] = None,
|
||||
@@ -670,6 +717,7 @@ class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> MoeModelOutputWithPast:
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
@@ -681,12 +729,15 @@ class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
|
||||
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
|
||||
seq_lens.to(device=inputs_embeds.device),
|
||||
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
|
||||
)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
hidden_states = inputs_embeds
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
|
||||
cu_seqlens_are_pre_shard = seq_lens_are_pre_shard
|
||||
|
||||
for 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(
|
||||
@@ -695,6 +746,7 @@ class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
routed_experts=routed_experts_layer,
|
||||
cu_seqlens_are_pre_shard=cu_seqlens_are_pre_shard,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
@@ -735,6 +787,9 @@ class Qwen3_5MoeVLMModel(nn.Module):
|
||||
def set_input_embeddings(self, value):
|
||||
self.language_model.set_input_embeddings(value)
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group, cp_rank: int, cp_world_size: int) -> None:
|
||||
self.language_model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
|
||||
def _dummy_vision_inputs(self, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Smallest valid vision input: a single merged token (grid [1, m, m])."""
|
||||
vcfg = self.config.vision_config
|
||||
@@ -803,6 +858,7 @@ class Qwen3_5MoeVLMModel(nn.Module):
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> MoeModelOutputWithPast:
|
||||
inputs_embeds, position_ids = self.prepare_inputs_embeds_and_position_ids(
|
||||
input_ids=input_ids,
|
||||
@@ -813,11 +869,23 @@ class Qwen3_5MoeVLMModel(nn.Module):
|
||||
seq_lens=seq_lens,
|
||||
)
|
||||
|
||||
cp_group = getattr(self.language_model, "_cp_group", None)
|
||||
if image_grid_thw is not None and cp_group is not None:
|
||||
cp_rank = self.language_model._cp_rank
|
||||
cp_world_size = self.language_model._cp_world_size
|
||||
setup_cp_attention_params(position_ids, cp_group=cp_group, cp_style="ulysses", seq_lens=seq_lens)
|
||||
inputs_embeds = shard_for_cp(inputs_embeds, cp_rank=cp_rank, cp_world_size=cp_world_size)
|
||||
position_ids = shard_position_ids_for_cp(position_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
|
||||
if routed_experts is not None:
|
||||
routed_experts = shard_for_cp(routed_experts, cp_rank=cp_rank, cp_world_size=cp_world_size)
|
||||
seq_lens_are_pre_shard = True
|
||||
|
||||
return self.language_model(
|
||||
inputs_embeds=inputs_embeds,
|
||||
position_ids=position_ids,
|
||||
routed_experts=routed_experts,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
|
||||
|
||||
@@ -884,6 +952,9 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
|
||||
def get_decoder(self):
|
||||
return self.model
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group, cp_rank: int, cp_world_size: int) -> None:
|
||||
self.model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# State dict detection & conversion (handles both text-only and VLM)
|
||||
# ------------------------------------------------------------------
|
||||
@@ -962,6 +1033,7 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
|
||||
mm_token_type_ids: Optional[torch.LongTensor] = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
assert use_cache is None, "use_cache is not supported for custom qwen3_5_moe for now"
|
||||
@@ -976,6 +1048,7 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
routed_experts=routed_experts,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
else:
|
||||
outputs = self.model(
|
||||
@@ -984,6 +1057,7 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
|
||||
inputs_embeds=inputs_embeds,
|
||||
routed_experts=routed_experts,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
|
||||
@@ -208,12 +208,15 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> MoeModelOutputWithPast:
|
||||
"""
|
||||
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
|
||||
Routed experts for each token in the sequence. Only used for router replay.
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
|
||||
Per-document lengths of the packed row (PrimeRL packed-batch contract).
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
|
||||
"""
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
@@ -222,7 +225,8 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
|
||||
seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1]
|
||||
seq_lens.to(device=inputs_embeds.device),
|
||||
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
|
||||
)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
|
||||
@@ -286,11 +290,14 @@ class Qwen3MoeForCausalLM(Qwen3MoePreTrainedModel, GenerationMixin):
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
r"""
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
|
||||
Per-document lengths of the packed row (PrimeRL packed-batch contract).
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
|
||||
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
||||
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
|
||||
compatibility — prime-rl asserts `use_cache is None` since training does not
|
||||
@@ -339,6 +346,7 @@ class Qwen3MoeForCausalLM(Qwen3MoePreTrainedModel, GenerationMixin):
|
||||
inputs_embeds=inputs_embeds,
|
||||
routed_experts=routed_experts,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
|
||||
@@ -65,7 +65,6 @@ from prime_rl.utils.metrics_server import HealthServer, MetricsServer, RunStats
|
||||
from prime_rl.utils.monitor import setup_monitor
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.utils.sequence import get_cp_local_seq_lens
|
||||
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step, to_col_format
|
||||
from ring_flash_attn import substitute_hf_flash_attn
|
||||
from torchtitan.distributed.utils import clip_grad_norm_
|
||||
@@ -205,8 +204,7 @@ def train(config: TrainerConfig):
|
||||
substitute_ulysses_attn(cp_group, attn_impl=config.model.attn)
|
||||
from prime_rl.utils.cp import (
|
||||
assert_cp_style_supports_model,
|
||||
setup_hybrid_cp,
|
||||
setup_nemotron_h_cp,
|
||||
setup_model_cp,
|
||||
setup_sparse_mla_cp,
|
||||
)
|
||||
|
||||
@@ -216,8 +214,7 @@ def train(config: TrainerConfig):
|
||||
# Linear-attn / Mamba layers are only configured under ulysses; with ring
|
||||
# we'd have already raised above.
|
||||
if config.model.cp_style == "ulysses":
|
||||
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
setup_nemotron_h_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
setup_model_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
|
||||
# Optionally, resume training from a checkpoint
|
||||
progress = Progress()
|
||||
@@ -379,7 +376,6 @@ def train(config: TrainerConfig):
|
||||
raise NotImplementedError("Context parallelism is not supported with VLM/multimodal training")
|
||||
|
||||
if cp_enabled:
|
||||
total_tokens = input_ids.shape[1]
|
||||
input_ids, forward_position_ids = setup_cp_params(
|
||||
input_ids,
|
||||
position_ids,
|
||||
@@ -389,7 +385,6 @@ def train(config: TrainerConfig):
|
||||
seq_lens=seq_lens,
|
||||
cp_style=config.model.cp_style,
|
||||
)
|
||||
seq_lens = get_cp_local_seq_lens(seq_lens, total_tokens, cp_rank, cp_size)
|
||||
labels = shard_for_cp(labels, cp_rank=cp_rank, cp_world_size=cp_size)
|
||||
if routed_experts is not None:
|
||||
routed_experts = shard_for_cp(routed_experts, cp_rank=cp_rank, cp_world_size=cp_size)
|
||||
@@ -425,6 +420,7 @@ def train(config: TrainerConfig):
|
||||
mm_kwargs=mm_kwargs,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=cp_enabled,
|
||||
routed_experts=routed_experts,
|
||||
)
|
||||
|
||||
|
||||
@@ -51,7 +51,6 @@ from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.monitor import setup_monitor
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.utils.sequence import get_cp_local_seq_lens
|
||||
from prime_rl.utils.utils import clean_exit, to_col_format
|
||||
import torch.distributed as dist
|
||||
|
||||
@@ -126,7 +125,7 @@ def train(config: SFTConfig):
|
||||
|
||||
substitute_hf_ulysses_attn(cp_group)
|
||||
substitute_ulysses_attn(cp_group, attn_impl=config.model.attn)
|
||||
from prime_rl.utils.cp import setup_hybrid_cp, setup_nemotron_h_cp, setup_sparse_mla_cp
|
||||
from prime_rl.utils.cp import setup_model_cp, setup_sparse_mla_cp
|
||||
|
||||
# Set up checkpoint manager
|
||||
logger.info(f"Initializing checkpoint managers ({config.ckpt})")
|
||||
@@ -153,8 +152,7 @@ def train(config: SFTConfig):
|
||||
# Linear-attn / Mamba layers are only configured under ulysses; with ring
|
||||
# we'd have already raised above.
|
||||
if config.model.cp_style == "ulysses":
|
||||
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
setup_nemotron_h_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
setup_model_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
|
||||
if config.model.lora is not None:
|
||||
multi_run_manager = get_multi_run_manager()
|
||||
@@ -244,23 +242,30 @@ def train(config: SFTConfig):
|
||||
mm_kwargs = micro_batch.get("mm_kwargs")
|
||||
mm_type_ids = micro_batch.get("mm_token_type_ids")
|
||||
|
||||
seq_lens_are_pre_shard = False
|
||||
|
||||
if cp_enabled:
|
||||
total_tokens = input_ids.shape[1]
|
||||
input_ids, position_ids = setup_cp_params(
|
||||
input_ids,
|
||||
position_ids,
|
||||
cp_rank,
|
||||
cp_size,
|
||||
cp_group,
|
||||
seq_lens=seq_lens,
|
||||
cp_style=config.model.cp_style,
|
||||
# CP requires the sequence length to be divisible by cp_size. CatDataset
|
||||
# pads every pack to seq_len; shard_for_cp raises on violations.
|
||||
defer_vlm_cp_to_model = (
|
||||
mm_kwargs is not None and "image_grid_thw" in mm_kwargs and config.model.cp_style == "ulysses"
|
||||
)
|
||||
seq_lens = get_cp_local_seq_lens(seq_lens, total_tokens, cp_rank, cp_size)
|
||||
if not defer_vlm_cp_to_model:
|
||||
input_ids, position_ids = setup_cp_params(
|
||||
input_ids,
|
||||
position_ids,
|
||||
cp_rank,
|
||||
cp_size,
|
||||
cp_group,
|
||||
seq_lens=seq_lens,
|
||||
cp_style=config.model.cp_style,
|
||||
)
|
||||
seq_lens_are_pre_shard = True
|
||||
target_ids = shard_for_cp(target_ids, cp_rank=cp_rank, cp_world_size=cp_size)
|
||||
loss_mask = shard_for_cp(loss_mask, cp_rank=cp_rank, cp_world_size=cp_size)
|
||||
|
||||
if config.model.lora is not None:
|
||||
set_lora_num_tokens(torch.full((1,), input_ids.numel(), dtype=torch.int32, device="cuda"))
|
||||
set_lora_num_tokens(torch.full((1,), loss_mask.numel(), dtype=torch.int32, device="cuda"))
|
||||
|
||||
token_count = loss_mask.sum(dtype=torch.int64)
|
||||
|
||||
@@ -279,6 +284,7 @@ def train(config: SFTConfig):
|
||||
temperature=temperature,
|
||||
mm_kwargs=mm_kwargs,
|
||||
mm_token_type_ids=mm_type_ids,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
loss_sum = -out["logprobs"][loss_mask].sum()
|
||||
else:
|
||||
@@ -289,6 +295,7 @@ def train(config: SFTConfig):
|
||||
mm_kwargs=mm_kwargs,
|
||||
mm_token_type_ids=mm_type_ids,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
logits = out["logits"]
|
||||
B, L, V = logits.shape
|
||||
|
||||
+47
-54
@@ -24,7 +24,8 @@ def _has_linear_attn_layer(model: nn.Module) -> bool:
|
||||
layers = getattr(inner, "layers", None)
|
||||
if layers is None:
|
||||
return False
|
||||
for layer in layers:
|
||||
layer_modules = layers.modules() if isinstance(layers, nn.Module) else layers
|
||||
for layer in layer_modules:
|
||||
# Qwen3.5 hybrid DeltaNet
|
||||
if getattr(layer, "layer_type", None) == "linear_attention":
|
||||
return True
|
||||
@@ -52,54 +53,22 @@ def assert_cp_style_supports_model(cp_style: CPStyle, model: nn.Module) -> None:
|
||||
)
|
||||
|
||||
|
||||
def setup_hybrid_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
"""Configure DeltaNet modules in Qwen3.5 hybrid models for ulysses-style CP."""
|
||||
layers = None
|
||||
if hasattr(model, "model"):
|
||||
inner = model.model
|
||||
if hasattr(inner, "language_model"):
|
||||
inner = inner.language_model
|
||||
if hasattr(inner, "layers"):
|
||||
layers = inner.layers
|
||||
def setup_model_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
"""Hand the CP topology to models whose layers need it (DeltaNet, Mamba).
|
||||
|
||||
if layers is None:
|
||||
return
|
||||
|
||||
count = 0
|
||||
for layer in layers:
|
||||
if getattr(layer, "layer_type", None) == "linear_attention":
|
||||
attn = getattr(layer, "linear_attn", None)
|
||||
if attn is not None:
|
||||
attn.cp_group = cp_group
|
||||
attn.cp_rank = cp_rank
|
||||
attn.cp_world_size = cp_world_size
|
||||
count += 1
|
||||
|
||||
if count > 0:
|
||||
Such models expose ``set_context_parallel_attributes`` at the top level and
|
||||
own their layer wiring; softmax-only models don't and need nothing.
|
||||
"""
|
||||
if hasattr(model, "set_context_parallel_attributes"):
|
||||
model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
get_logger().info(f"Configured hybrid CP on {count} DeltaNet modules (fla native state passing)")
|
||||
|
||||
|
||||
def setup_nemotron_h_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
"""Configure NemotronH Mamba layers for ulysses-style all-to-all head partitioning."""
|
||||
layers = None
|
||||
if hasattr(model, "model") and hasattr(model.model, "layers"):
|
||||
layers = model.model.layers
|
||||
|
||||
if layers is None:
|
||||
return
|
||||
|
||||
count = 0
|
||||
for layer in layers:
|
||||
if hasattr(layer, "mamba") and hasattr(layer, "set_context_parallel_attributes"):
|
||||
layer.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
count += 1
|
||||
|
||||
if count > 0:
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
get_logger().info(f"Configured NemotronH CP on {count} Mamba layers (all-to-all head partitioning)")
|
||||
get_logger().info("Configured model CP attributes")
|
||||
elif _has_linear_attn_layer(model):
|
||||
raise ValueError(
|
||||
"Model has linear-attention/Mamba layers but does not implement "
|
||||
"set_context_parallel_attributes; CP would silently misconfigure them"
|
||||
)
|
||||
|
||||
|
||||
def setup_sparse_mla_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
@@ -125,7 +94,7 @@ def setup_sparse_mla_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank:
|
||||
get_logger().info(f"Configured sparse MLA CP on {count} DSA layers")
|
||||
|
||||
|
||||
def shard_for_cp(t: torch.Tensor, cp_rank: int, cp_world_size: int) -> torch.Tensor:
|
||||
def shard_for_cp(t: torch.Tensor, cp_rank: int, cp_world_size: int, seq_dim: int = 1) -> torch.Tensor:
|
||||
"""
|
||||
Shard a tensor for context parallelism.
|
||||
Args:
|
||||
@@ -136,13 +105,26 @@ def shard_for_cp(t: torch.Tensor, cp_rank: int, cp_world_size: int) -> torch.Ten
|
||||
The shard of the tensor for the current rank.
|
||||
"""
|
||||
|
||||
assert t.shape[0] == 1, "For CP, tensor must have batch dimension of 1"
|
||||
if seq_dim == 1 and t.shape[0] != 1:
|
||||
raise ValueError(f"For CP, tensor must have batch dimension 1, got shape={tuple(t.shape)}")
|
||||
if t.shape[seq_dim] % cp_world_size != 0:
|
||||
raise ValueError(
|
||||
f"CP requires sequence dimension {seq_dim} to be divisible by cp size: "
|
||||
f"shape={tuple(t.shape)}, cp_size={cp_world_size}; "
|
||||
"uneven shards deadlock CP collectives (e.g. ulysses all-to-all)"
|
||||
)
|
||||
|
||||
chunked_t = torch.chunk(t, cp_world_size, dim=1)
|
||||
chunked_t = torch.chunk(t, cp_world_size, dim=seq_dim)
|
||||
|
||||
return chunked_t[cp_rank]
|
||||
|
||||
|
||||
def shard_position_ids_for_cp(position_ids: torch.Tensor, cp_rank: int, cp_world_size: int) -> torch.Tensor:
|
||||
if position_ids.ndim == 3:
|
||||
return shard_for_cp(position_ids, cp_rank=cp_rank, cp_world_size=cp_world_size, seq_dim=2)
|
||||
return shard_for_cp(position_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
|
||||
|
||||
|
||||
def gather_for_cp(t: torch.Tensor, cp_group: dist.ProcessGroup) -> torch.Tensor:
|
||||
gathered_t = dist_nn.all_gather(t, group=cp_group)
|
||||
|
||||
@@ -176,9 +158,24 @@ def setup_cp_params(
|
||||
Returns the sequence-sharded input_ids and position_ids — the rest of the
|
||||
model still runs sequence-sharded; only attention sees the full sequence.
|
||||
"""
|
||||
setup_cp_attention_params(position_ids, cp_group=cp_group, cp_style=cp_style, seq_lens=seq_lens)
|
||||
|
||||
input_ids = shard_for_cp(input_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
|
||||
position_ids = shard_position_ids_for_cp(position_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
|
||||
return input_ids, position_ids
|
||||
|
||||
|
||||
def setup_cp_attention_params(
|
||||
position_ids: torch.Tensor,
|
||||
cp_group: dist.ProcessGroup,
|
||||
*,
|
||||
seq_lens: torch.Tensor,
|
||||
cp_style: CPStyle = "ring",
|
||||
) -> None:
|
||||
total_tokens = position_ids.shape[-1]
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
|
||||
seq_lens.to(device=position_ids.device),
|
||||
total_tokens=position_ids.shape[-1],
|
||||
total_tokens=total_tokens,
|
||||
)
|
||||
|
||||
if cp_style == "ring":
|
||||
@@ -191,7 +188,3 @@ def setup_cp_params(
|
||||
update_ulysses_params(cu_seqlens, max_seqlen)
|
||||
else:
|
||||
raise ValueError(f"Unknown cp_style: {cp_style}")
|
||||
|
||||
input_ids = shard_for_cp(input_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
|
||||
position_ids = shard_for_cp(position_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
|
||||
return input_ids, position_ids
|
||||
|
||||
@@ -50,19 +50,3 @@ def get_cu_seqlens_from_seq_lens(seq_lens: torch.Tensor, total_tokens: int | Non
|
||||
cu_seqlens[0] = 0
|
||||
cu_seqlens[1:] = seq_lens.cumsum(dim=0, dtype=torch.int32)
|
||||
return cu_seqlens, int(seq_lens.max().item())
|
||||
|
||||
|
||||
def get_cp_local_seq_lens(
|
||||
seq_lens: torch.Tensor,
|
||||
total_tokens: int,
|
||||
cp_rank: int,
|
||||
cp_world_size: int,
|
||||
) -> torch.Tensor:
|
||||
"""Intersect global sequence boundaries with one contiguous CP shard."""
|
||||
shard_size = total_tokens // cp_world_size
|
||||
shard_start = seq_lens.new_tensor(cp_rank * shard_size)
|
||||
shard_end = shard_start + shard_size
|
||||
seq_ends = seq_lens.cumsum(dim=0)
|
||||
seq_starts = torch.cat([seq_lens.new_zeros(1), seq_ends[:-1]])
|
||||
overlaps = torch.minimum(seq_ends, shard_end) - torch.maximum(seq_starts, shard_start)
|
||||
return overlaps[overlaps > 0]
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from transformers.models.nemotron_h.configuration_nemotron_h import NemotronHConfig as HFNemotronHConfig
|
||||
@@ -10,7 +12,8 @@ from transformers.models.nemotron_h.modeling_nemotron_h import (
|
||||
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.nemotron_h import NemotronHConfig, NemotronHForCausalLM
|
||||
from prime_rl.trainer.models.nemotron_h.modeling_nemotron_h import NemotronHAttentionLayer
|
||||
from prime_rl.trainer.models.nemotron_h.modeling_nemotron_h import NemotronHAttentionLayer, NemotronHMambaLayer
|
||||
from prime_rl.utils.cp import setup_model_cp
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
|
||||
pytestmark = [pytest.mark.gpu]
|
||||
@@ -225,6 +228,27 @@ def test_nemotron_h_hybrid_override_pattern():
|
||||
assert config.num_hidden_layers == 4
|
||||
|
||||
|
||||
def test_nemotron_h_context_parallel_setup_finds_wrapped_mamba_layer():
|
||||
config = NemotronHConfig(
|
||||
**(_BASE | {"mamba_n_groups": 2}),
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
use_grouped_mm=False,
|
||||
)
|
||||
with torch.device("meta"):
|
||||
model = NemotronHForCausalLM(config)
|
||||
|
||||
mamba_layer = model.model.layers[0]
|
||||
assert isinstance(mamba_layer, NemotronHMambaLayer)
|
||||
model.model.layers[0] = torch.nn.Sequential(mamba_layer)
|
||||
|
||||
cp_group = MagicMock()
|
||||
setup_model_cp(model, cp_group, cp_rank=1, cp_world_size=2)
|
||||
|
||||
assert mamba_layer._cp_group is cp_group
|
||||
assert mamba_layer._cp_rank == 1
|
||||
assert mamba_layer._cp_world_size == 2
|
||||
|
||||
|
||||
def test_nemotron_h_no_latent_projection():
|
||||
"""Verify model works without latent projections (moe_latent_size=None)."""
|
||||
prime_config = NemotronHConfig(
|
||||
|
||||
@@ -3,13 +3,14 @@ from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
|
||||
from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5Config, Qwen3_5TextConfig, Qwen3_5VisionConfig
|
||||
from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5ForCausalLM as HFQwen3_5ForCausalLM
|
||||
|
||||
from prime_rl.trainer.models.layers.attn import FlashAttention, substitute_ring_attn
|
||||
from prime_rl.trainer.models.qwen3_5 import Qwen3_5ForCausalLM, Qwen3_5Model
|
||||
from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAttention
|
||||
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig
|
||||
from prime_rl.utils.cp import setup_model_cp
|
||||
|
||||
|
||||
def _tiny_text_config(attn_impl: str = "flash_attention_2") -> Qwen3_5TextConfig:
|
||||
@@ -33,6 +34,28 @@ def _tiny_text_config(attn_impl: str = "flash_attention_2") -> Qwen3_5TextConfig
|
||||
return config
|
||||
|
||||
|
||||
def _tiny_vlm_config(attn_impl: str = "flash_attention_2") -> Qwen3_5Config:
|
||||
text_config = _tiny_text_config(attn_impl)
|
||||
vision_config = Qwen3_5VisionConfig(
|
||||
depth=1,
|
||||
hidden_size=64,
|
||||
intermediate_size=128,
|
||||
num_heads=4,
|
||||
out_hidden_size=text_config.hidden_size,
|
||||
)
|
||||
config = Qwen3_5Config(
|
||||
text_config=text_config,
|
||||
vision_config=vision_config,
|
||||
image_token_id=120,
|
||||
video_token_id=121,
|
||||
vision_start_token_id=122,
|
||||
vision_end_token_id=123,
|
||||
)
|
||||
config._attn_implementation = attn_impl
|
||||
config.text_config._attn_implementation = attn_impl
|
||||
return config
|
||||
|
||||
|
||||
def _tiny_moe_config(attn_impl: str = "flash_attention_2") -> Qwen3_5MoeConfig:
|
||||
config = Qwen3_5MoeConfig(
|
||||
vocab_size=128,
|
||||
@@ -95,6 +118,47 @@ def test_qwen3_5_moe_full_attention_normalizes_fa3_hub_alias():
|
||||
assert model.config._attn_implementation == "flash_attention_3"
|
||||
|
||||
|
||||
def test_qwen3_5_context_parallel_setup_chain_text_and_vlm():
|
||||
cp_group = MagicMock()
|
||||
|
||||
text_model = Qwen3_5ForCausalLM(_tiny_text_config())
|
||||
linear_layer = text_model.model.layers[0]
|
||||
text_model.model.layers[0] = torch.nn.Sequential(linear_layer)
|
||||
setup_model_cp(text_model, cp_group, cp_rank=1, cp_world_size=2)
|
||||
assert text_model.model._cp_group is cp_group
|
||||
assert text_model.model._cp_rank == 1
|
||||
assert text_model.model._cp_world_size == 2
|
||||
assert linear_layer.linear_attn.cp_group is cp_group
|
||||
|
||||
vlm_config = _tiny_vlm_config()
|
||||
vlm_config.vision_config._attn_implementation = "sdpa"
|
||||
vlm_config.vision_config._attn_implementation_internal = "sdpa"
|
||||
with torch.device("meta"):
|
||||
vlm_model = Qwen3_5ForCausalLM(vlm_config)
|
||||
setup_model_cp(vlm_model, cp_group, cp_rank=0, cp_world_size=2)
|
||||
assert vlm_model.model.language_model._cp_group is cp_group
|
||||
assert vlm_model.model.language_model.layers[0].linear_attn.cp_world_size == 2
|
||||
|
||||
|
||||
def test_setup_model_cp_requires_hook_only_for_hybrid_models():
|
||||
class HybridLayer(torch.nn.Module):
|
||||
layer_type = "linear_attention"
|
||||
|
||||
class Inner:
|
||||
layers = torch.nn.Sequential(torch.nn.Sequential(HybridLayer()))
|
||||
|
||||
class HybridNoHookModel:
|
||||
model = Inner()
|
||||
|
||||
with pytest.raises(ValueError, match="set_context_parallel_attributes"):
|
||||
setup_model_cp(HybridNoHookModel(), MagicMock(), cp_rank=0, cp_world_size=2)
|
||||
|
||||
class SoftmaxOnlyModel:
|
||||
pass
|
||||
|
||||
setup_model_cp(SoftmaxOnlyModel(), MagicMock(), cp_rank=0, cp_world_size=2)
|
||||
|
||||
|
||||
def test_qwen3_5_ring_patches_dense_flash_attention():
|
||||
from prime_rl.trainer.models.afmoe.modeling_afmoe import AfmoeFlashAttention
|
||||
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
|
||||
|
||||
@@ -5,6 +5,7 @@ from transformers import Qwen3_5MoeForCausalLM as HFQwen3_5MoeForCausalLM
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig
|
||||
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeForCausalLM as PrimeRLQwen3_5MoeForCausalLM
|
||||
from prime_rl.utils.cp import setup_model_cp
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
|
||||
pytestmark = [pytest.mark.gpu]
|
||||
@@ -146,5 +147,44 @@ def test_qwen3_5_moe_cp_patching():
|
||||
cls._compute_attention = method
|
||||
|
||||
|
||||
def test_qwen3_5_moe_context_parallel_setup_hook():
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
config = Qwen3_5MoeConfig(
|
||||
vocab_size=128,
|
||||
hidden_size=64,
|
||||
num_hidden_layers=2,
|
||||
layer_types=["linear_attention", "full_attention"],
|
||||
num_attention_heads=4,
|
||||
num_key_value_heads=2,
|
||||
head_dim=16,
|
||||
moe_intermediate_size=64,
|
||||
shared_expert_intermediate_size=64,
|
||||
num_experts=4,
|
||||
num_experts_per_tok=2,
|
||||
max_position_embeddings=128,
|
||||
linear_conv_kernel_dim=4,
|
||||
linear_key_head_dim=8,
|
||||
linear_value_head_dim=8,
|
||||
linear_num_key_heads=4,
|
||||
linear_num_value_heads=8,
|
||||
use_grouped_mm=False,
|
||||
)
|
||||
config._attn_implementation = "flash_attention_2"
|
||||
with torch.device("meta"):
|
||||
model = PrimeRLQwen3_5MoeForCausalLM(config)
|
||||
|
||||
linear_layer = model.model.layers[0]
|
||||
model.model.layers[0] = torch.nn.Sequential(linear_layer)
|
||||
cp_group = MagicMock()
|
||||
setup_model_cp(model, cp_group, cp_rank=1, cp_world_size=2)
|
||||
|
||||
assert model.model._cp_group is cp_group
|
||||
assert model.model._cp_rank == 1
|
||||
assert model.model._cp_world_size == 2
|
||||
assert linear_layer.linear_attn.cp_group is cp_group
|
||||
assert linear_layer.linear_attn.cp_world_size == 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_qwen3_5_moe()
|
||||
|
||||
@@ -2,7 +2,6 @@ import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.utils.sequence import (
|
||||
get_cp_local_seq_lens,
|
||||
get_cu_seqlens_from_position_ids,
|
||||
get_cu_seqlens_from_seq_lens,
|
||||
)
|
||||
@@ -40,10 +39,3 @@ def test_get_cu_seqlens_from_seq_lens():
|
||||
def test_get_cu_seqlens_from_seq_lens_rejects_wrong_total():
|
||||
with pytest.raises(ValueError, match="sum must equal"):
|
||||
get_cu_seqlens_from_seq_lens(torch.tensor([4, 3]), total_tokens=9)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("cp_rank", "expected"), [(0, [3, 1]), (1, [4])])
|
||||
def test_get_cp_local_seq_lens(cp_rank: int, expected: list[int]):
|
||||
local_seq_lens = get_cp_local_seq_lens(torch.tensor([3, 5]), 8, cp_rank, 2)
|
||||
|
||||
assert local_seq_lens.tolist() == expected
|
||||
|
||||
Reference in New Issue
Block a user