feat: use FA3 as default, rename fa4 to flash_attention_4, remove eager (#3057)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: use FA3 as default, rename fa4 to flash_attention_4, remove eager Three changes: 1. Default attention implementation changed from flash_attention_2 to flash_attention_3. 2. Renamed internal 'fa4' alias to 'flash_attention_4' everywhere for consistency. The _ATTN_ALIASES mapping and _normalize_attn_alias validator are removed since flash_attention_4 is now the canonical name. The _register_fa4_attention_interface noop is also removed since transformers already registers flash_attention_4 in AttentionInterface._global_mapping. 3. Removed 'eager' from AttnImplementation Literal. GPT-OSS non-Hopper fallback updated to suggest 'sdpa' instead of 'eager'. * fix: allow impl='auto' with FA3/FA4 + CP, fix ruff format - Update CP+FA3/FA4 validator to also accept impl='auto' (which resolves to 'custom' at runtime for supported models). This fixes the config test for rl_qwen3_30b_a3b.toml which uses cp=2 with the new FA3 default. - Apply ruff format to qwen3_5 and qwen3_5_moe model files (multi-line tuple formatting for long in-check). * feat: remove sdpa and eager attention support Remove 'sdpa' and 'eager' from AttnImplementation. Only flash_attention_2, flash_attention_3, and flash_attention_4 are now supported. Changes: - Remove 'sdpa' from AttnImplementation Literal in trainer config - Remove SDPAAttention class from layers/attn.py - Remove all SDPA attention classes from custom models (AfmoeSDPAAttention, LagunaSDPAAttention, Qwen3_5MoeGatedSDPAAttention, Qwen3_5GatedSDPAAttention) - Remove 'sdpa' entries from all ATTN_IMPL2CLASS dispatch dicts - Remove eager->sdpa fallback logic in afmoe, laguna, qwen3_5_moe - Set _supports_sdpa = False on all custom model configs - Remove GPT-OSS non-Hopper SDPA fallback (now errors on non-Hopper) - Update normalize_qwen3_5_attn_implementation to drop eager alias - Update default attn_impl in qwen3_5/qwen3_5_moe _check_and_adjust - Update configs and tests to use flash_attention_2 instead of sdpa - Mark test_qwen3_5_dense_matches_hf_state_keys_on_meta as GPU test (HF model validates flash attn availability at init, requires GPU) * fix: accept impl='auto' for flash_attention_4 validator Same pattern as the CP+FA3/FA4 validator fix: 'auto' resolves to 'custom' at runtime for supported models, so it should be accepted at config validation time. Also improve error message to match. * fix: bypass flash attention availability check for custom models Override _check_and_adjust_attn_implementation on PreTrainedModelPrimeRL to skip transformers' flash attention package/device validation. This restores the behavior of the old _register_fa4_attention_interface() noop that was removed when fa4 was renamed to flash_attention_4. Without this override, instantiating a custom model with _from_config fails on machines where flash_attn_3 or flash_attn_cute is not installed, because transformers recognizes flash_attention_3/4 as flash attention and tries to validate availability before our own ATTN_IMPL2CLASS dispatch runs. Custom models use their own attention dispatch (ATTN_IMPL2CLASS) and never call transformers' ALL_ATTENTION_FUNCTIONS, so the availability check is unnecessary. qwen3_5 and qwen3_5_moe already override this method with their own validation; those overrides take precedence via MRO.
This commit is contained in:
@@ -4,7 +4,7 @@ max_steps = 5
|
||||
name = "PrimeIntellect/GLM-0.5B"
|
||||
moe_use_grouped_mm = false
|
||||
impl = "custom"
|
||||
attn = "sdpa"
|
||||
attn = "flash_attention_2"
|
||||
|
||||
[model.compile]
|
||||
|
||||
|
||||
@@ -18,15 +18,9 @@ from prime_rl.utils.config import BaseConfig
|
||||
|
||||
# -- Shared trainer configs (used by both SFT and RL trainers) --
|
||||
|
||||
AttnImplementation: TypeAlias = Literal["eager", "sdpa", "flash_attention_2", "flash_attention_3", "fa4"]
|
||||
AttnImplementation: TypeAlias = Literal["flash_attention_2", "flash_attention_3", "flash_attention_4"]
|
||||
EPCommBackend: TypeAlias = Literal["torch", "deepep"]
|
||||
|
||||
# User-facing name -> internal name. Users set `flash_attention_4` in configs,
|
||||
# which gets rewritten to `fa4` before pydantic validation.
|
||||
# We use `fa4` internally because `flash_attention_*` triggers transformers
|
||||
# to attempt installing a kernel from hub.
|
||||
_ATTN_ALIASES = {"flash_attention_4": "fa4"}
|
||||
|
||||
|
||||
class GCConfig(BaseConfig):
|
||||
interval: int = Field(50, ge=1)
|
||||
@@ -159,7 +153,7 @@ class ModelConfig(BaseModelConfig):
|
||||
seq_len: int = 2048
|
||||
"""Sequence length the model is trained on."""
|
||||
|
||||
attn: AttnImplementation = "flash_attention_2"
|
||||
attn: AttnImplementation = "flash_attention_3"
|
||||
"""Attention implementation. With CP enabled, ring attention uses the matching kernel family (FA2/FA3/FA4)."""
|
||||
|
||||
compile: CompileConfig | None = CompileConfig()
|
||||
@@ -233,14 +227,6 @@ class ModelConfig(BaseModelConfig):
|
||||
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 1024
|
||||
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. SFT training silently disables this (not supported yet)."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _normalize_attn_alias(cls, data):
|
||||
"""Rewrite user-facing `flash_attention_4` to internal `fa4` before validation."""
|
||||
if isinstance(data, dict) and data.get("attn") in _ATTN_ALIASES:
|
||||
data["attn"] = _ATTN_ALIASES[data["attn"]]
|
||||
return data
|
||||
|
||||
@model_validator(mode="after")
|
||||
def trust_remote_code_only_with_hf(self):
|
||||
"""Trust remote code only if the model is from HF."""
|
||||
@@ -251,15 +237,19 @@ class ModelConfig(BaseModelConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def cp_only_with_flash_attn(self):
|
||||
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "fa4"]:
|
||||
raise ValueError("CP is only supported with flash attention 2, flash attention 3, or fa4")
|
||||
if self.cp > 1 and self.attn in ("flash_attention_3", "fa4") and self.impl != "custom":
|
||||
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "flash_attention_4"]:
|
||||
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")
|
||||
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.
|
||||
raise ValueError(
|
||||
f"CP with {self.attn} requires model.impl='custom' "
|
||||
f"CP with {self.attn} requires model.impl='custom' or 'auto' "
|
||||
"(FA3/FA4 paths are only implemented for the custom model attention class)"
|
||||
)
|
||||
return self
|
||||
@@ -285,8 +275,8 @@ class ModelConfig(BaseModelConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def flash_attention_4_only_with_custom_impl(self):
|
||||
if self.attn == "fa4" and self.impl != "custom":
|
||||
raise ValueError("Flash attention 4 is only supported with the custom implementation")
|
||||
if self.attn == "flash_attention_4" and self.impl not in ("custom", "auto"):
|
||||
raise ValueError("Flash attention 4 is only supported with model.impl='custom' or 'auto'")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -282,7 +282,7 @@ def _patch_qwen3_5_linear_attn_varlen():
|
||||
):
|
||||
attn_impl = getattr(self.config, "_attn_implementation", None)
|
||||
cu_seqlens = None
|
||||
if attn_impl in ("flash_attention_2", "flash_attention_3", "fa4") and position_ids is not None:
|
||||
if attn_impl in ("flash_attention_2", "flash_attention_3", "flash_attention_4") and position_ids is not None:
|
||||
pids = position_ids
|
||||
if pids.ndim == 3:
|
||||
pids = pids[0]
|
||||
@@ -510,17 +510,14 @@ def get_model(
|
||||
)
|
||||
|
||||
# GPT-OSS only supports FlashAttention via kernels-community/vllm-flash-attn3, which requires Hopper (SM 90).
|
||||
# On other architectures (e.g. Blackwell), users must fall back to eager attention.
|
||||
HOPPER_MAJOR = 9
|
||||
if getattr(model_config, "model_type", "") == "gpt_oss":
|
||||
if config.attn != "eager":
|
||||
major, minor = torch.cuda.get_device_capability()
|
||||
if major != HOPPER_MAJOR:
|
||||
raise ValueError(
|
||||
f"GPT-OSS requires 'attn = \"eager\"' on non-Hopper GPUs (detected SM {major}{minor}). "
|
||||
f"The only flash attention kernel supported by GPT-OSS (kernels-community/vllm-flash-attn3) is Hopper-only. "
|
||||
f'Set [trainer.model] attn = "eager" in your config.'
|
||||
)
|
||||
major, minor = torch.cuda.get_device_capability()
|
||||
if major != HOPPER_MAJOR:
|
||||
raise ValueError(
|
||||
f"GPT-OSS requires Hopper (SM 90) for flash attention, detected SM {major}{minor}. "
|
||||
f"GPT-OSS is not supported on non-Hopper GPUs."
|
||||
)
|
||||
# Enable hub kernels for GPT-OSS (disabled by default to avoid interfering with other models).
|
||||
import transformers.integrations.hub_kernels as _hub_kernels
|
||||
|
||||
@@ -1131,22 +1128,6 @@ def _validate_flash_attn_4_installed() -> None:
|
||||
)
|
||||
|
||||
|
||||
def _register_fa4_attention_interface() -> None:
|
||||
"""Register a dummy `fa4` attention with transformers so AutoConfig accepts it.
|
||||
|
||||
The `flash_attention_*` naming pattern triggers transformers to attempt
|
||||
installing a kernel from the hub, so we use the short name `fa4` internally.
|
||||
This dummy is never called because fa4 is only supported with our custom
|
||||
model implementation.
|
||||
"""
|
||||
from transformers import AttentionInterface
|
||||
|
||||
def _noop(*args, **kwargs) -> None:
|
||||
pass
|
||||
|
||||
AttentionInterface.register("fa4", _noop)
|
||||
|
||||
|
||||
def setup_model(
|
||||
config: ModelConfig,
|
||||
parallel_dims: ParallelDims,
|
||||
@@ -1157,9 +1138,8 @@ def setup_model(
|
||||
"Flash attention 3 is only supported if the flash_attn_3 package is installed. Install with `uv pip install 'flash-attn-3 @ git+https://github.com/Dao-AILab/flash-attention.git@main#subdirectory=hopper' --no-build-isolation`"
|
||||
)
|
||||
|
||||
if config.attn == "fa4":
|
||||
if config.attn == "flash_attention_4":
|
||||
_validate_flash_attn_4_installed()
|
||||
_register_fa4_attention_interface()
|
||||
|
||||
logger = get_logger()
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ from dataclasses import dataclass
|
||||
from typing import Optional, Union
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
from transformers.cache_utils import Cache
|
||||
from transformers.generation import GenerationMixin
|
||||
@@ -105,78 +104,6 @@ class AfmoeAttentionBase(nn.Module):
|
||||
return self.o_proj(attn_output)
|
||||
|
||||
|
||||
class AfmoeSDPAAttention(AfmoeAttentionBase):
|
||||
"""AFMoE attention using PyTorch's scaled_dot_product_attention."""
|
||||
|
||||
def attn_projections(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
query_states = self.q_proj(hidden_states).view(hidden_shape)
|
||||
key_states = self.k_proj(hidden_states).view(hidden_shape)
|
||||
value_states = self.v_proj(hidden_states).view(hidden_shape)
|
||||
gate_states = self.gate_proj(hidden_states)
|
||||
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
query_states = query_states.transpose(1, 2)
|
||||
key_states = key_states.transpose(1, 2)
|
||||
value_states = value_states.transpose(1, 2)
|
||||
|
||||
if self.is_local_attention:
|
||||
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)
|
||||
|
||||
return query_states, key_states, value_states, gate_states
|
||||
|
||||
def _attention_core(
|
||||
self,
|
||||
query_states: torch.Tensor,
|
||||
key_states: torch.Tensor,
|
||||
value_states: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
dropout_p: float = 0.0,
|
||||
) -> torch.Tensor:
|
||||
return F.scaled_dot_product_attention(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
attn_mask=attention_mask,
|
||||
dropout_p=dropout_p,
|
||||
is_causal=attention_mask is None,
|
||||
scale=self.scaling,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, None]:
|
||||
query_states, key_states, value_states, gate_states = self.attn_projections(hidden_states, position_embeddings)
|
||||
|
||||
dropout_p = self.attention_dropout if self.training else 0.0
|
||||
attn_output = self._attention_core(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
attention_mask=attention_mask,
|
||||
dropout_p=dropout_p,
|
||||
)
|
||||
|
||||
return self.output_proj(attn_output, gate_states), None
|
||||
|
||||
|
||||
class AfmoeFlashAttention(AfmoeAttentionBase):
|
||||
"""AFMoE attention using Flash Attention varlen functions."""
|
||||
|
||||
@@ -263,10 +190,9 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
|
||||
|
||||
|
||||
AFMOE_ATTN_IMPL2CLASS = {
|
||||
"sdpa": AfmoeSDPAAttention,
|
||||
"flash_attention_2": functools.partial(AfmoeFlashAttention, flash_attn_version=2),
|
||||
"flash_attention_3": functools.partial(AfmoeFlashAttention, flash_attn_version=3),
|
||||
"fa4": functools.partial(AfmoeFlashAttention, flash_attn_version=4),
|
||||
"flash_attention_4": functools.partial(AfmoeFlashAttention, flash_attn_version=4),
|
||||
}
|
||||
|
||||
|
||||
@@ -299,8 +225,6 @@ def _get_afmoe_attention(config: AfmoeConfig, layer_idx: int) -> nn.Module:
|
||||
)
|
||||
|
||||
attn_impl = config._attn_implementation
|
||||
if attn_impl == "eager":
|
||||
attn_impl = "sdpa"
|
||||
|
||||
if attn_impl not in AFMOE_ATTN_IMPL2CLASS:
|
||||
supported = list(AFMOE_ATTN_IMPL2CLASS.keys())
|
||||
@@ -394,7 +318,7 @@ class AfmoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
"k_norm",
|
||||
"norm",
|
||||
]
|
||||
_supports_sdpa = True
|
||||
_supports_sdpa = False
|
||||
_supports_flash_attn = True
|
||||
_supports_flex_attn = False
|
||||
_supports_attention_backend = True
|
||||
@@ -478,7 +402,7 @@ class AfmoeModel(AfmoePreTrainedModel):
|
||||
if position_ids is None:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
|
||||
use_flash = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4")
|
||||
use_flash = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4")
|
||||
|
||||
if use_flash:
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
|
||||
@@ -21,6 +21,22 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
|
||||
"""PrimeRL models use custom MoE implementations and don't support dynamic experts implementation."""
|
||||
return False
|
||||
|
||||
def _check_and_adjust_attn_implementation(
|
||||
self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
|
||||
) -> str:
|
||||
"""Bypass transformers' flash attention availability checks.
|
||||
|
||||
PrimeRL custom models dispatch attention through their own ``ATTN_IMPL2CLASS``
|
||||
dictionaries, not through transformers' ``ALL_ATTENTION_FUNCTIONS``. The default
|
||||
``_check_and_adjust_attn_implementation`` validates that the requested flash
|
||||
attention package is installed and the device is supported, which fails on
|
||||
CPU-only machines and is unnecessary because we never call transformers'
|
||||
attention dispatch for custom models.
|
||||
"""
|
||||
if attn_implementation is None:
|
||||
attn_implementation = "flash_attention_3"
|
||||
return attn_implementation
|
||||
|
||||
def get_correct_experts_implementation(self, requested_experts: str | None) -> str:
|
||||
"""PrimeRL models always use eager experts implementation."""
|
||||
return "eager"
|
||||
|
||||
@@ -121,7 +121,7 @@ class Glm4MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
_no_split_modules = ["Glm4MoeDecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = True
|
||||
_supports_sdpa = False
|
||||
_supports_flex_attn = True
|
||||
_can_compile_fullgraph = False
|
||||
_supports_attention_backend = True
|
||||
@@ -216,7 +216,7 @@ class Glm4MoeModel(Glm4MoePreTrainedModel):
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
|
||||
@@ -126,7 +126,7 @@ class GlmMoeDsaPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
_no_split_modules = ["GlmMoeDsaDecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = True
|
||||
_supports_sdpa = False
|
||||
_supports_flex_attn = True
|
||||
_can_compile_fullgraph = False
|
||||
_supports_attention_backend = True
|
||||
|
||||
@@ -22,7 +22,7 @@ from prime_rl.trainer.models.laguna.converting_laguna import (
|
||||
convert_prime_layer_to_hf,
|
||||
convert_prime_to_hf,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.attn import AttentionConfig, FlashAttention, SDPAAttention
|
||||
from prime_rl.trainer.models.layers.attn import AttentionConfig, FlashAttention
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
|
||||
@@ -138,70 +138,16 @@ class LagunaFlashAttention(FlashAttention):
|
||||
return self.o_proj(attn_output), None
|
||||
|
||||
|
||||
class LagunaSDPAAttention(SDPAAttention):
|
||||
def __init__(self, config: LagunaConfig, layer_idx: int, num_heads: int):
|
||||
super().__init__(_laguna_attention_config(config, num_heads))
|
||||
self.num_heads = num_heads
|
||||
self.config = config
|
||||
self.layer_idx = layer_idx
|
||||
self.attention_dropout = config.attention_dropout
|
||||
self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
|
||||
self.sliding_window = config.sliding_window if self.is_local_attention else None
|
||||
self.g_proj = nn.Linear(config.hidden_size, num_heads, bias=False)
|
||||
self.o_proj = nn.Linear(num_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)
|
||||
|
||||
def _attention_core(
|
||||
self,
|
||||
query_states: torch.Tensor,
|
||||
key_states: torch.Tensor,
|
||||
value_states: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
key_states = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
||||
value_states = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
||||
dropout_p = 0.0 if not self.training else self.attention_dropout
|
||||
out = F.scaled_dot_product_attention(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
attn_mask=attention_mask,
|
||||
dropout_p=dropout_p,
|
||||
is_causal=attention_mask is None,
|
||||
)
|
||||
out = out.transpose(1, 2).contiguous()
|
||||
return out.view(out.shape[0], out.shape[1], -1)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
query_states, key_states, value_states = self.attn_projections(hidden_states, position_embeddings)
|
||||
attn_output = self._attention_core(query_states, key_states, value_states, attention_mask=attention_mask)
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
attn_output = attn_output.view(*input_shape, self.num_heads, self.head_dim)
|
||||
gate = F.softplus(self.g_proj(hidden_states).float()).to(attn_output.dtype)
|
||||
attn_output = (attn_output * gate.unsqueeze(-1)).view(*input_shape, -1)
|
||||
return self.o_proj(attn_output), None
|
||||
|
||||
|
||||
def _get_laguna_attention(config: LagunaConfig, layer_idx: int):
|
||||
attn_impl = config._attn_implementation
|
||||
if attn_impl == "eager":
|
||||
attn_impl = "sdpa"
|
||||
num_heads = config.num_attention_heads_per_layer[layer_idx]
|
||||
match attn_impl:
|
||||
case "flash_attention_2":
|
||||
return LagunaFlashAttention(config, layer_idx, num_heads, flash_attn_version=2)
|
||||
case "flash_attention_3":
|
||||
return LagunaFlashAttention(config, layer_idx, num_heads, flash_attn_version=3)
|
||||
case "fa4":
|
||||
case "flash_attention_4":
|
||||
return LagunaFlashAttention(config, layer_idx, num_heads, flash_attn_version=4)
|
||||
case "sdpa":
|
||||
return LagunaSDPAAttention(config, layer_idx, num_heads)
|
||||
case _:
|
||||
raise ValueError(f"Laguna attention does not support '{config._attn_implementation}'.")
|
||||
|
||||
@@ -286,7 +232,7 @@ class LagunaPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
_no_split_modules = ["LagunaDecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = True
|
||||
_supports_sdpa = False
|
||||
_supports_flex_attn = False
|
||||
_can_compile_fullgraph = False
|
||||
_supports_attention_backend = True
|
||||
@@ -354,7 +300,7 @@ class LagunaModel(LagunaPreTrainedModel):
|
||||
if position_ids is None:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
causal_mask_mapping = dict.fromkeys(set(self.config.layer_types), None)
|
||||
|
||||
@@ -3,7 +3,6 @@ from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
|
||||
from .norms import RMSNorm, RMSNormConfig
|
||||
@@ -42,7 +41,7 @@ class AttentionConfig:
|
||||
|
||||
|
||||
# TODO: Does torch compile support config._attn_implementation forking?
|
||||
# If so, we can combine FlashAttention and SDPAAttention into one class
|
||||
# If so, we can combine FlashAttention variants into one class
|
||||
# Otherwise, do ABC or something to make the signatures match
|
||||
|
||||
|
||||
@@ -183,108 +182,10 @@ class FlashAttention(nn.Module):
|
||||
return attn_output, None
|
||||
|
||||
|
||||
class SDPAAttention(nn.Module):
|
||||
"""SDPA Attention"""
|
||||
|
||||
def __init__(self, config: AttentionConfig):
|
||||
super().__init__()
|
||||
self.head_dim = config.head_dim
|
||||
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
||||
self.scaling = self.head_dim**-0.5
|
||||
self.is_causal = config.is_causal
|
||||
|
||||
self.q_proj = nn.Linear(
|
||||
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
||||
)
|
||||
self.k_proj = nn.Linear(
|
||||
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
||||
)
|
||||
self.v_proj = nn.Linear(
|
||||
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
||||
)
|
||||
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.output_bias)
|
||||
self.use_qk_norm = config.use_qk_norm
|
||||
self.qk_norm_type = config.qk_norm_type
|
||||
if self.use_qk_norm:
|
||||
if self.qk_norm_type == "per_layer":
|
||||
self.q_norm = RMSNorm(
|
||||
RMSNormConfig(hidden_size=config.num_attention_heads * self.head_dim, eps=config.rms_norm_eps)
|
||||
)
|
||||
self.k_norm = RMSNorm(
|
||||
RMSNormConfig(hidden_size=config.num_key_value_heads * self.head_dim, eps=config.rms_norm_eps)
|
||||
)
|
||||
else:
|
||||
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
|
||||
def attn_projections(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
query_states = self.q_proj(hidden_states)
|
||||
key_states = self.k_proj(hidden_states)
|
||||
value_states = self.v_proj(hidden_states)
|
||||
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_layer":
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
query_states = query_states.view(hidden_shape)
|
||||
key_states = key_states.view(hidden_shape)
|
||||
value_states = value_states.view(hidden_shape)
|
||||
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_head":
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
query_states = query_states.transpose(1, 2)
|
||||
key_states = key_states.transpose(1, 2)
|
||||
value_states = value_states.transpose(1, 2)
|
||||
|
||||
if position_embeddings is not None:
|
||||
cos, sin = position_embeddings
|
||||
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
||||
|
||||
return query_states, key_states, value_states
|
||||
|
||||
def _attention_core(
|
||||
self,
|
||||
query_states: torch.Tensor,
|
||||
key_states: torch.Tensor,
|
||||
value_states: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
key_states = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
||||
value_states = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
||||
out = F.scaled_dot_product_attention(query_states, key_states, value_states, is_causal=True)
|
||||
out = out.transpose(1, 2).contiguous()
|
||||
return out.view(out.shape[0], out.shape[1], -1)
|
||||
|
||||
def output_proj(self, attn_output: torch.Tensor) -> torch.Tensor:
|
||||
return self.o_proj(attn_output)
|
||||
|
||||
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,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
query_states, key_states, value_states = self.attn_projections(hidden_states, position_embeddings)
|
||||
|
||||
attn_output = self._attention_core(query_states, key_states, value_states)
|
||||
attn_output = self.output_proj(attn_output)
|
||||
return attn_output, None
|
||||
|
||||
|
||||
ATTN_IMPL2CLASS = {
|
||||
"flash_attention_2": functools.partial(FlashAttention, flash_attn_version=2),
|
||||
"sdpa": SDPAAttention,
|
||||
"flash_attention_3": functools.partial(FlashAttention, flash_attn_version=3),
|
||||
"fa4": functools.partial(FlashAttention, flash_attn_version=4),
|
||||
"flash_attention_4": functools.partial(FlashAttention, flash_attn_version=4),
|
||||
}
|
||||
|
||||
|
||||
@@ -298,7 +199,7 @@ def substitute_ring_attn(
|
||||
|
||||
from .ring_attn import ring_fa3_varlen_func, ring_fa4_varlen_func
|
||||
|
||||
if attn_impl == "fa4":
|
||||
if attn_impl == "flash_attention_4":
|
||||
ring_func = ring_fa4_varlen_func
|
||||
elif attn_impl == "flash_attention_3":
|
||||
ring_func = ring_fa3_varlen_func
|
||||
|
||||
@@ -173,7 +173,7 @@ def substitute_ulysses_attn(
|
||||
cp_size = dist.get_world_size(group=process_group)
|
||||
|
||||
# Resolve flash kernel + version from attn_impl.
|
||||
if attn_impl == "fa4":
|
||||
if attn_impl == "flash_attention_4":
|
||||
from flash_attn.cute import flash_attn_varlen_func as flash_fn
|
||||
|
||||
flash_attn_version = 4
|
||||
|
||||
@@ -107,7 +107,7 @@ class LlamaPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
_no_split_modules = ["LlamaDecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = True
|
||||
_supports_sdpa = False
|
||||
_supports_flex_attn = True
|
||||
|
||||
_can_compile_fullgraph = True
|
||||
@@ -188,7 +188,7 @@ class LlamaModel(LlamaPreTrainedModel):
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
|
||||
@@ -95,7 +95,7 @@ class MiniMaxM2PreTrainedModel(PreTrainedModelPrimeRL):
|
||||
_no_split_modules = ["MiniMaxM2DecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = True
|
||||
_supports_sdpa = False
|
||||
_supports_flex_attn = True
|
||||
_can_compile_fullgraph = False
|
||||
_supports_attention_backend = True
|
||||
@@ -177,7 +177,7 @@ class MiniMaxM2Model(MiniMaxM2PreTrainedModel):
|
||||
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"):
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
|
||||
@@ -342,7 +342,7 @@ class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
supports_gradient_checkpointing = True
|
||||
_no_split_modules = ["NemotronHMambaLayer", "NemotronHMoELayer", "NemotronHAttentionLayer"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = True
|
||||
_supports_sdpa = False
|
||||
_can_compile_fullgraph = False
|
||||
|
||||
def _init_weights(self, module):
|
||||
@@ -522,7 +522,7 @@ class NemotronHModel(NemotronHPreTrainedModel):
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
# Compute cu_seqlens and max_seqlen for flash attention
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
|
||||
@@ -50,8 +50,6 @@ class Qwen3DecoderLayer(GradientCheckpointingLayer):
|
||||
)
|
||||
self.self_attn = ATTN_IMPL2CLASS[config._attn_implementation](attn_config)
|
||||
if self.layer_type == "sliding_attention":
|
||||
if config._attn_implementation == "sdpa":
|
||||
raise ValueError("Qwen3 sliding attention is only supported by the custom model with flash attention.")
|
||||
self.self_attn.sliding_window = config.sliding_window
|
||||
|
||||
mlp_config = MLPConfig(
|
||||
@@ -95,7 +93,7 @@ class Qwen3PreTrainedModel(PreTrainedModelPrimeRL):
|
||||
_no_split_modules = ["Qwen3DecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = True
|
||||
_supports_sdpa = False
|
||||
_supports_flex_attn = True
|
||||
_can_compile_fullgraph = True
|
||||
_supports_attention_backend = True
|
||||
@@ -165,7 +163,7 @@ class Qwen3Model(Qwen3PreTrainedModel):
|
||||
if position_ids is None:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
|
||||
@@ -21,7 +21,6 @@ from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
|
||||
Qwen3_5MoeGatedAttentionConfig,
|
||||
Qwen3_5MoeGatedDeltaNet,
|
||||
Qwen3_5MoeGatedFlashAttention,
|
||||
Qwen3_5MoeGatedSDPAAttention,
|
||||
Qwen3_5MoeRMSNorm,
|
||||
Qwen3_5MoeRotaryEmbedding,
|
||||
normalize_qwen3_5_attn_implementation,
|
||||
@@ -29,19 +28,14 @@ from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
|
||||
class Qwen3_5GatedSDPAAttention(Qwen3_5MoeGatedSDPAAttention):
|
||||
pass
|
||||
|
||||
|
||||
class Qwen3_5GatedFlashAttention(Qwen3_5MoeGatedFlashAttention):
|
||||
pass
|
||||
|
||||
|
||||
QWEN35_ATTN_IMPL2CLASS = {
|
||||
"sdpa": Qwen3_5GatedSDPAAttention,
|
||||
"flash_attention_2": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=2),
|
||||
"flash_attention_3": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=3),
|
||||
"fa4": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=4),
|
||||
"flash_attention_4": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=4),
|
||||
}
|
||||
|
||||
|
||||
@@ -130,7 +124,7 @@ class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
|
||||
_no_split_modules = ["Qwen3_5DecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = True
|
||||
_supports_sdpa = False
|
||||
_supports_flex_attn = False
|
||||
_supports_attention_backend = True
|
||||
_can_compile_fullgraph = False
|
||||
@@ -141,7 +135,7 @@ class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
|
||||
def _check_and_adjust_attn_implementation(
|
||||
self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
|
||||
) -> str:
|
||||
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "sdpa")
|
||||
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "flash_attention_3")
|
||||
if attn_impl not in QWEN35_ATTN_IMPL2CLASS:
|
||||
supported = list(QWEN35_ATTN_IMPL2CLASS.keys())
|
||||
raise ValueError(
|
||||
@@ -206,7 +200,11 @@ class Qwen3_5Model(Qwen3_5PreTrainedModel):
|
||||
if position_ids is None:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
|
||||
flash_attn_enabled = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4")
|
||||
flash_attn_enabled = self.config._attn_implementation in (
|
||||
"flash_attention_2",
|
||||
"flash_attention_3",
|
||||
"flash_attention_4",
|
||||
)
|
||||
if flash_attn_enabled:
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
|
||||
@@ -417,59 +417,6 @@ class Qwen3_5MoeGatedAttentionBase(nn.Module):
|
||||
return self.o_proj(attn_output)
|
||||
|
||||
|
||||
class Qwen3_5MoeGatedSDPAAttention(Qwen3_5MoeGatedAttentionBase):
|
||||
"""Gated softmax attention using PyTorch's scaled_dot_product_attention."""
|
||||
|
||||
def attn_projections(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
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)
|
||||
|
||||
return query_states, key_states, value_states, gate
|
||||
|
||||
def _attention_core(
|
||||
self,
|
||||
query_states: torch.Tensor,
|
||||
key_states: torch.Tensor,
|
||||
value_states: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
key_states = _repeat_kv(key_states, self.num_key_value_groups)
|
||||
value_states = _repeat_kv(value_states, self.num_key_value_groups)
|
||||
return F.scaled_dot_product_attention(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
is_causal=True,
|
||||
scale=self.scaling,
|
||||
)
|
||||
|
||||
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]:
|
||||
query_states, key_states, value_states, gate = self.attn_projections(hidden_states, position_embeddings)
|
||||
attn_output = self._attention_core(query_states, key_states, value_states)
|
||||
return self.output_proj(attn_output, gate), None
|
||||
|
||||
|
||||
class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
|
||||
"""Gated softmax attention using Flash Attention varlen functions."""
|
||||
|
||||
@@ -560,16 +507,13 @@ class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
|
||||
|
||||
|
||||
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),
|
||||
"flash_attention_4": functools.partial(Qwen3_5MoeGatedFlashAttention, flash_attn_version=4),
|
||||
}
|
||||
|
||||
|
||||
def normalize_qwen3_5_attn_implementation(attn_impl: str) -> str:
|
||||
if attn_impl == "eager":
|
||||
return "sdpa"
|
||||
if attn_impl == "kernels-community/vllm-flash-attn3":
|
||||
return "flash_attention_3"
|
||||
return attn_impl
|
||||
@@ -798,7 +742,7 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
_no_split_modules = ["Qwen3_5MoeDecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = True
|
||||
_supports_sdpa = False
|
||||
_supports_flex_attn = False
|
||||
_supports_attention_backend = True
|
||||
_can_compile_fullgraph = False
|
||||
@@ -809,7 +753,7 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
def _check_and_adjust_attn_implementation(
|
||||
self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
|
||||
) -> str:
|
||||
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "sdpa")
|
||||
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "flash_attention_3")
|
||||
if attn_impl not in QWEN35MOE_ATTN_IMPL2CLASS:
|
||||
supported = list(QWEN35MOE_ATTN_IMPL2CLASS.keys())
|
||||
raise ValueError(
|
||||
@@ -885,7 +829,11 @@ class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
|
||||
if position_ids is None:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
|
||||
flash_attn_enabled = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4")
|
||||
flash_attn_enabled = self.config._attn_implementation in (
|
||||
"flash_attention_2",
|
||||
"flash_attention_3",
|
||||
"flash_attention_4",
|
||||
)
|
||||
if flash_attn_enabled:
|
||||
if position_ids.ndim == 3:
|
||||
if inputs_embeds.shape[0] != 1:
|
||||
|
||||
@@ -127,7 +127,7 @@ class Qwen3MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
_no_split_modules = ["Qwen3MoeDecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = True
|
||||
_supports_sdpa = False
|
||||
_supports_flex_attn = True
|
||||
_can_compile_fullgraph = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
|
||||
_supports_attention_backend = True
|
||||
@@ -217,7 +217,7 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
|
||||
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"):
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "flash_attention_4"):
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
|
||||
@@ -56,7 +56,7 @@ def get_model_pairs():
|
||||
use_grouped_mm=False,
|
||||
vocab_size=256,
|
||||
)
|
||||
hf_config._attn_implementation = "sdpa"
|
||||
hf_config._attn_implementation = "flash_attention_2"
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_model = HFAfmoeForCausalLM._from_config(hf_config)
|
||||
prime_model = PrimeRLAfmoeForCausalLM._from_config(hf_config)
|
||||
|
||||
@@ -32,7 +32,7 @@ def get_model_pairs() -> tuple[HFGlm4MoeForCausalLM, PrimeRLGlm4MoeForCausalLM]:
|
||||
# TODO: We should test this path because it's the most performant
|
||||
# But the grad seems to be off in attn because of precision
|
||||
# hf_config._attn_implementation = "flash_attention_2"
|
||||
hf_config._attn_implementation = "sdpa"
|
||||
hf_config._attn_implementation = "flash_attention_2"
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_model = HFGlm4MoeForCausalLM._from_config(hf_config)
|
||||
prime_model = PrimeRLGlm4MoeForCausalLM._from_config(hf_config)
|
||||
|
||||
@@ -25,7 +25,7 @@ def get_model_pairs():
|
||||
attention_bias=False,
|
||||
mlp_bias=False,
|
||||
)
|
||||
hf_config._attn_implementation = "sdpa"
|
||||
hf_config._attn_implementation = "flash_attention_2"
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_model = HFLlamaForCausalLM._from_config(hf_config)
|
||||
prime_model = PrimeRLLlamaForCausalLM._from_config(hf_config)
|
||||
|
||||
@@ -47,14 +47,14 @@ _BASE = dict(
|
||||
def get_model_pairs():
|
||||
"""Create an HF model and a PrimeRL model with shared weights."""
|
||||
hf_config = HFNemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
hf_config._attn_implementation = "sdpa"
|
||||
hf_config._attn_implementation = "flash_attention_2"
|
||||
|
||||
prime_config = NemotronHConfig(
|
||||
**_BASE,
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
use_grouped_mm=False,
|
||||
)
|
||||
prime_config._attn_implementation = "sdpa"
|
||||
prime_config._attn_implementation = "flash_attention_2"
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_model = HFNemotronHForCausalLM._from_config(hf_config)
|
||||
@@ -110,10 +110,10 @@ def test_nemotron_h_reverse():
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
use_grouped_mm=False,
|
||||
)
|
||||
prime_config._attn_implementation = "sdpa"
|
||||
prime_config._attn_implementation = "flash_attention_2"
|
||||
|
||||
hf_config = HFNemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
hf_config._attn_implementation = "sdpa"
|
||||
hf_config._attn_implementation = "flash_attention_2"
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
prime_model = NemotronHForCausalLM._from_config(prime_config)
|
||||
|
||||
@@ -55,7 +55,7 @@ def _make_model(device="cuda"):
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
use_grouped_mm=False,
|
||||
)
|
||||
config._attn_implementation = "sdpa"
|
||||
config._attn_implementation = "flash_attention_2"
|
||||
with torch.device(device), default_dtype(torch.float32):
|
||||
model = NemotronHForCausalLM._from_config(config)
|
||||
inject_prime_lm_head(model, chunk_size=None)
|
||||
@@ -186,7 +186,7 @@ def test_kl_with_fused_lm_head():
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
use_grouped_mm=False,
|
||||
)
|
||||
config._attn_implementation = "sdpa"
|
||||
config._attn_implementation = "flash_attention_2"
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
model = NemotronHForCausalLM._from_config(config)
|
||||
|
||||
@@ -12,7 +12,7 @@ from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAt
|
||||
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig
|
||||
|
||||
|
||||
def _tiny_text_config(attn_impl: str = "sdpa") -> Qwen3_5TextConfig:
|
||||
def _tiny_text_config(attn_impl: str = "flash_attention_2") -> Qwen3_5TextConfig:
|
||||
config = Qwen3_5TextConfig(
|
||||
vocab_size=128,
|
||||
hidden_size=64,
|
||||
@@ -33,7 +33,7 @@ def _tiny_text_config(attn_impl: str = "sdpa") -> Qwen3_5TextConfig:
|
||||
return config
|
||||
|
||||
|
||||
def _tiny_moe_config(attn_impl: str = "sdpa") -> Qwen3_5MoeConfig:
|
||||
def _tiny_moe_config(attn_impl: str = "flash_attention_2") -> Qwen3_5MoeConfig:
|
||||
config = Qwen3_5MoeConfig(
|
||||
vocab_size=128,
|
||||
hidden_size=64,
|
||||
@@ -58,6 +58,7 @@ def _tiny_moe_config(attn_impl: str = "sdpa") -> Qwen3_5MoeConfig:
|
||||
return config
|
||||
|
||||
|
||||
@pytest.mark.gpu
|
||||
def test_qwen3_5_dense_matches_hf_state_keys_on_meta():
|
||||
config = _tiny_text_config()
|
||||
with torch.device("meta"):
|
||||
|
||||
@@ -31,7 +31,7 @@ def get_model_pairs():
|
||||
linear_num_value_heads=8,
|
||||
use_grouped_mm=False,
|
||||
)
|
||||
config._attn_implementation = "sdpa"
|
||||
config._attn_implementation = "flash_attention_2"
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_model = HFQwen3_5MoeForCausalLM._from_config(config)
|
||||
prime_model = PrimeRLQwen3_5MoeForCausalLM._from_config(config)
|
||||
|
||||
@@ -15,7 +15,9 @@ 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 = AutoConfig.from_pretrained(
|
||||
"Qwen/Qwen3.5-35B-A3B", trust_remote_code=True, attn_implementation="flash_attention_2"
|
||||
)
|
||||
config.use_cache = False
|
||||
tc = config.text_config
|
||||
tc.vocab_size = 256
|
||||
|
||||
@@ -31,7 +31,7 @@ def get_model_pairs():
|
||||
# TODO: We should test this path because it's the most performant
|
||||
# But the grad seems to be off in attn because of precision
|
||||
# hf_config._attn_implementation = "flash_attention_2"
|
||||
hf_config._attn_implementation = "sdpa"
|
||||
hf_config._attn_implementation = "flash_attention_2"
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_model = HFQwen3MoeForCausalLM._from_config(hf_config)
|
||||
prime_model = PrimeRLQwen3MoeForCausalLM._from_config(hf_config)
|
||||
|
||||
@@ -14,7 +14,7 @@ pytestmark = [
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(params=["sdpa", "flash_attention_2"])
|
||||
@pytest.fixture(params=["flash_attention_2"])
|
||||
def attn(request) -> AttnImplementation:
|
||||
"""
|
||||
Fixture to test different attention implementations.
|
||||
@@ -117,7 +117,9 @@ def test_model_with_sequence_packing(model, correct_position_ids):
|
||||
|
||||
|
||||
def test_moe_custom_impl():
|
||||
config = ModelConfig(name="PrimeIntellect/GLM-0.5B", attn="sdpa", impl="custom", moe_use_grouped_mm=False)
|
||||
config = ModelConfig(
|
||||
name="PrimeIntellect/GLM-0.5B", attn="flash_attention_2", impl="custom", moe_use_grouped_mm=False
|
||||
)
|
||||
model = get_model(config)
|
||||
model = model.to("cuda")
|
||||
# we need to wrap the lm head as custom forward only works with it, this is done in setup_model
|
||||
@@ -133,7 +135,7 @@ def test_moe_custom_impl():
|
||||
@pytest.mark.skip(reason="need special token for meta stuff in ci")
|
||||
@pytest.mark.parametrize("model_name", ["meta-llama/Llama-3.2-1B-Instruct"])
|
||||
def test_model_forward_custom_impl(model_name):
|
||||
config = ModelConfig(name=model_name, impl="custom", attn="sdpa")
|
||||
config = ModelConfig(name=model_name, impl="custom", attn="flash_attention_2")
|
||||
model = get_model(config)
|
||||
# we need to wrap the lm head as custom forward only works with it, this is done in setup_model
|
||||
inject_prime_lm_head(model, chunk_size=None)
|
||||
|
||||
Reference in New Issue
Block a user