Compare commits

...
Author SHA1 Message Date
a30d417f25 Add new selective AC targets (#2120)
Release / Push CUDA image to Docker (push) Canceled after 0s
* selective-ac-update

* address comments

* add docs

* fix: remove redundant selective target normalization

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

* docs: note selective ac target rename

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

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>
2026-03-31 10:50:03 +01:00
rasdaniandGitHub 07411f392f fix: log chat templated messages to eval/samples Table (#2143)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-31 09:21:04 +02:00
9 changed files with 173 additions and 105 deletions
+1
View File
@@ -3,6 +3,7 @@
Documenting changes which affect configuration usage patterns (added/moved/removed/renamed fields, notable logic changes).
- **`loss_impl = "quack_fused"` (SFT)**: Added `quack_fused` option for the SFT `loss_impl` field. Uses quack-kernels for chunked linear + cross-entropy with CuTe DSL CUDA kernels, avoiding full logits materialization. Requires `quack-kernels` package. Does not support Gemma logit softcapping. Custom model impl (`model.impl = "custom"`) also gains quack RMSNorm acceleration on CUDA automatically. (2026-03-26)
- **`model.ac.targets`**: Removed the `mamba` selective activation checkpoint target and folded that behavior into the broader `linear_attn` target. Existing configs using `targets = ["mamba"]` will now fail validation at runtime with `ValueError`; switch them to `targets = ["linear_attn"]`. The `linear_attn` target description now covers supported token mixers outside the standard softmax-attention path, including NemotronH Mamba layers, Qwen3.5-MoE GatedDeltaNet layers, and AFMoE sliding-window attention layers. (2026-03-28)
- **`model.tp` (trainer `ModelConfig`)**: Removed from the trainer model config. Existing trainer configs must delete this field; it is no longer accepted. (2026-03-26)
- **`orchestrator.env[].num_workers`**: Added configurable env server worker count (`int | "auto"`, default: `"auto"`). When `"auto"`, scales based on concurrency (1 worker per 256 concurrent rollouts). Only used when the orchestrator spawns the env server (i.e. `address` is not set). (2026-03-25)
- **`[model.vlm]` (NEW — replaces auto-detection)**: VLM mode is now opt-in via a `[model.vlm]` sub-config with required `vision_encoder_attr` and `language_model_attr` fields. There is no auto-detection — if you train a VLM, you must add `[model.vlm]`. Existing multimodal configs need the new section. See `docs/multimodal.md` for the table of known model attrs. (2026-03-24)
+2 -1
View File
@@ -46,12 +46,13 @@ class ActivationCheckpointConfig(BaseConfig):
targets: Annotated[
list[str],
Field(
description="Selective checkpoint targets. `norm` checkpoints every norm module inside selected layers (decoder, attention, MLA, etc.). `attn_proj` checkpoints QKV projections, QK norms, RoPE, and output projection — everything in the attention layer except the kernel. `mlp` checkpoints the entire dense MLP forward (not applicable to MoE layers). `mla_up_proj` checkpoints MLA Q/KV up-projection work where supported. `routed_experts` checkpoints routed expert compute in MoE layers (including LatentMoE). `mamba` checkpoints the Mamba mixer forward in NemotronH Mamba layers. `linear_attn` checkpoints the GatedDeltaNet forward in Qwen3.5-MoE linear attention layers.",
description="Selective checkpoint targets. `norm` checkpoints every norm module inside selected layers (decoder, attention, MLA, etc.). `attn_proj` checkpoints projection-side attention work outside the kernel, including input/output projections, attention-local norms, RoPE, gating, and model-specific MLA projection helpers where exposed. `mlp` checkpoints the entire dense MLP forward (not applicable to MoE layers). `mla_up_proj` checkpoints MLA Q/KV up-projection work where supported. `routed_experts` checkpoints routed expert compute in MoE layers (including LatentMoE). `linear_attn` checkpoints supported token mixers outside the standard softmax-attention path, including NemotronH Mamba layers, Qwen3.5-MoE GatedDeltaNet layers, and AFMoE sliding-window attention layers.",
),
] = ["norm"]
@model_validator(mode="after")
def validate_selective_targets(self):
self.targets = list(dict.fromkeys(self.targets))
if self.mode == "selective" and not self.targets:
raise ValueError("Selective activation checkpointing requires at least one target.")
return self
+4 -3
View File
@@ -607,6 +607,7 @@ def reshard_module(model: nn.Module):
def apply_ac(model: nn.Module, ac_config: ActivationCheckpointConfig):
logger = get_logger()
language_model = get_language_model(model)
target_list = sorted(frozenset(ac_config.targets))
selective_layers = 0
full_layers = 0
fallback_layer_types: set[str] = set()
@@ -618,7 +619,7 @@ def apply_ac(model: nn.Module, ac_config: ActivationCheckpointConfig):
if ac_config.mode == "selective" and supports_selective_activation_checkpointing(transformer_block):
model_supported_targets.update(get_supported_targets(transformer_block))
set_selective_activation_checkpointing(transformer_block, ac_config.targets)
set_selective_activation_checkpointing(transformer_block, target_list)
selective_layers += 1
else:
if ac_config.mode == "selective":
@@ -629,7 +630,7 @@ def apply_ac(model: nn.Module, ac_config: ActivationCheckpointConfig):
language_model.layers.register_module(layer_name, transformer_block)
if ac_config.mode == "selective":
unsupported_targets = frozenset(ac_config.targets) - model_supported_targets
unsupported_targets = frozenset(target_list) - model_supported_targets
if unsupported_targets:
raise ValueError(
f"Selective activation checkpoint targets {sorted(unsupported_targets)} are not supported "
@@ -642,7 +643,7 @@ def apply_ac(model: nn.Module, ac_config: ActivationCheckpointConfig):
)
logger.info(
"Applied selective activation checkpointing "
f"(freq={ac_config.freq}, targets={ac_config.targets}, selective_layers={selective_layers}, "
f"(freq={ac_config.freq}, targets={target_list}, selective_layers={selective_layers}, "
f"full_fallback_layers={full_layers})"
)
return
@@ -101,11 +101,27 @@ class AfmoeAttentionBase(nn.Module):
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 _project_states(
def output_proj(
self,
attn_output: torch.Tensor,
gate_states: torch.Tensor,
) -> torch.Tensor:
input_shape = gate_states.shape[:-1]
if attn_output.dim() == 4:
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.contiguous().view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate_states)
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, tuple[int, ...]]:
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
@@ -128,23 +144,7 @@ class AfmoeAttentionBase(nn.Module):
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, input_shape
def _finalize_output(
self,
attn_output: torch.Tensor,
gate_states: torch.Tensor,
input_shape: tuple[int, ...],
) -> tuple[torch.Tensor, None]:
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate_states)
attn_output = self.o_proj(attn_output)
return attn_output, None
class AfmoeSDPAAttention(AfmoeAttentionBase):
"""AFMoE attention using PyTorch's scaled_dot_product_attention."""
return query_states, key_states, value_states, gate_states
def _attention_core(
self,
@@ -172,9 +172,7 @@ class AfmoeSDPAAttention(AfmoeAttentionBase):
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, None]:
query_states, key_states, value_states, gate_states, input_shape = self._project_states(
hidden_states, position_embeddings
)
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(
@@ -185,7 +183,7 @@ class AfmoeSDPAAttention(AfmoeAttentionBase):
dropout_p=dropout_p,
)
return self._finalize_output(attn_output, gate_states, input_shape)
return self.output_proj(attn_output, gate_states), None
class AfmoeFlashAttention(AfmoeAttentionBase):
@@ -228,14 +226,11 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
) -> torch.Tensor:
return self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
def forward(
def attn_projections(
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]:
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
@@ -255,6 +250,17 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
return query_states, key_states, value_states, gate_states
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)
attn_output = self._attention_core(
query_states,
key_states,
@@ -262,10 +268,7 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
attn_output = attn_output.contiguous().view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate_states)
attn_output = self.o_proj(attn_output)
return attn_output, None
return self.output_proj(attn_output, gate_states), None
AFMOE_ATTN_IMPL2CLASS = {
@@ -128,13 +128,13 @@ class GlmMoeDsaAttention(nn.Module):
self.indexer = Indexer(args)
self.scaling = self.qk_head_dim ** (-0.5)
def _mla_latents(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
def attn_projections(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
q_latent = self.q_a_layernorm(self.q_a_proj(hidden_states))
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
k_compressed, k_rope = compressed_kv.split([self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
return q_latent, self.kv_a_layernorm(k_compressed), k_rope
def _mla_up_proj(
def mla_up_proj(
self,
q_latent: torch.Tensor,
k_compressed_normed: torch.Tensor,
@@ -167,6 +167,12 @@ class GlmMoeDsaAttention(nn.Module):
def _mla_unabsorb(self, out: torch.Tensor, w_v: torch.Tensor) -> torch.Tensor:
return torch.einsum("bshk,hdk->bshd", out, w_v)
def output_proj(self, attn_output: torch.Tensor, w_v: torch.Tensor) -> torch.Tensor:
attn_output = self._mla_unabsorb(attn_output, w_v)
batch_size, total_tokens = attn_output.shape[:2]
attn_output = attn_output.reshape(batch_size, total_tokens, -1)
return self.o_proj(attn_output)
def forward(
self,
hidden_states: torch.Tensor,
@@ -174,15 +180,13 @@ class GlmMoeDsaAttention(nn.Module):
ks: torch.Tensor | None = None,
ke: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
batch_size, total_tokens, _ = hidden_states.shape
q_latent, k_compressed_normed, k_rope = self._mla_latents(hidden_states)
q_latent, k_compressed_normed, k_rope = self.attn_projections(hidden_states)
indices = self.indexer.compute_sparse_indices(
hidden_states, q_latent, ks, ke, self.args.index_topk, position_embeddings
)
sparse_q, sparse_kv, w_v = self._mla_up_proj(
sparse_q, sparse_kv, w_v = self.mla_up_proj(
q_latent,
k_compressed_normed,
k_rope,
@@ -190,7 +194,4 @@ class GlmMoeDsaAttention(nn.Module):
)
out = _SparseMLA.apply(sparse_q, sparse_kv, indices, self.scaling)
out = self._mla_unabsorb(out, w_v)
out = out.reshape(batch_size, total_tokens, -1)
return self.o_proj(out), None
return self.output_proj(out, w_v), None
+8 -8
View File
@@ -116,7 +116,7 @@ class FlashAttention(nn.Module):
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
return out.contiguous().view(1, out.shape[0], -1)
def _attn_projections(
def attn_projections(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
@@ -155,7 +155,7 @@ class FlashAttention(nn.Module):
return query_states, key_states, value_states
def _output_proj(self, attn_output: torch.Tensor) -> torch.Tensor:
def output_proj(self, attn_output: torch.Tensor) -> torch.Tensor:
return self.o_proj(attn_output)
def forward(
@@ -165,7 +165,7 @@ class FlashAttention(nn.Module):
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)
query_states, key_states, value_states = self.attn_projections(hidden_states, position_embeddings)
attn_output = self._attention_core(
query_states,
@@ -174,7 +174,7 @@ class FlashAttention(nn.Module):
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
attn_output = self._output_proj(attn_output)
attn_output = self.output_proj(attn_output)
return attn_output, None
@@ -212,7 +212,7 @@ class SDPAAttention(nn.Module):
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(
def attn_projections(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
@@ -258,7 +258,7 @@ class SDPAAttention(nn.Module):
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:
def output_proj(self, attn_output: torch.Tensor) -> torch.Tensor:
return self.o_proj(attn_output)
def forward(
@@ -268,10 +268,10 @@ class SDPAAttention(nn.Module):
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)
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)
attn_output = self.output_proj(attn_output)
return attn_output, None
@@ -1,3 +1,30 @@
"""Selective activation checkpointing hooks for custom decoder layers.
New model integration contract:
- `norm`: no explicit hook is required. Every child module whose type name
contains `norm` is checkpointed through `forward()`.
- `attn_proj`: expose `layer.self_attn.attn_projections(...)` for
projection-side attention work before the core kernel, plus
`layer.self_attn.output_proj(...)` for the post-attention output projection.
This target is meant for attention-local work outside the main attention
kernel, such as q/k/v projections, attention-local norms, RoPE, gating, and
similar model-specific helpers.
- `mla_up_proj`: expose `layer.self_attn.mla_up_proj(...)` when MLA-style
up-projection work should be checkpointed separately from
`attn_projections(...)`.
- `mlp`: expose a dense `layer.mlp.forward(...)`. A module is treated as dense
when it does not define `_run_routed_experts` or `tokens_per_expert`.
- `routed_experts`: expose `layer.mlp._run_routed_experts(...)` for the MoE
expert path.
- `linear_attn`: expose a token-mixer module on `layer.linear_attn` or
`layer.mamba`, or reuse `layer.self_attn` when
`layer.attention_type == "sliding_attention"`.
These hook names are an intentional public interface for custom model support,
so new models should follow them directly rather than adding private aliases.
"""
from collections.abc import Iterable
from functools import wraps
@@ -5,7 +32,7 @@ import torch
import torch.nn as nn
from torch.utils.checkpoint import checkpoint
SELECTIVE_AC_TARGETS = frozenset({"norm", "attn_proj", "mlp", "mla_up_proj", "routed_experts", "mamba", "linear_attn"})
SELECTIVE_AC_TARGETS = frozenset({"norm", "attn_proj", "mlp", "mla_up_proj", "routed_experts", "linear_attn"})
_PATCHED_METHODS_ATTR = "_prime_rl_selective_ac_patched_methods"
@@ -49,23 +76,40 @@ def _is_dense_mlp(mlp: nn.Module) -> bool:
return not hasattr(mlp, "_run_routed_experts") and not hasattr(mlp, "tokens_per_expert")
def _supports_attn_proj(self_attn: nn.Module | None) -> bool:
return self_attn is not None and hasattr(self_attn, "attn_projections") and hasattr(self_attn, "output_proj")
def _get_linear_attn_module(layer: nn.Module) -> nn.Module | None:
linear_attn = getattr(layer, "linear_attn", None)
if linear_attn is not None:
return linear_attn
mamba = getattr(layer, "mamba", None)
if mamba is not None:
return mamba
if getattr(layer, "attention_type", None) == "sliding_attention":
return getattr(layer, "self_attn", None)
return None
def get_supported_targets(layer: nn.Module) -> frozenset[str]:
"""Infer which selective activation checkpoint targets a decoder layer supports."""
supported_targets = {"norm"}
self_attn = getattr(layer, "self_attn", None)
mlp = getattr(layer, "mlp", None)
mamba = getattr(layer, "mamba", None)
linear_attn = getattr(layer, "linear_attn", None)
linear_attn = _get_linear_attn_module(layer)
if self_attn is not None and hasattr(self_attn, "_attn_projections"):
if _supports_attn_proj(self_attn):
supported_targets.add("attn_proj")
if self_attn is not None and hasattr(self_attn, "_mla_up_proj"):
if self_attn is not None and hasattr(self_attn, "mla_up_proj"):
supported_targets.add("mla_up_proj")
if mlp is not None and _is_dense_mlp(mlp):
supported_targets.add("mlp")
if mlp is not None and hasattr(mlp, "_run_routed_experts"):
supported_targets.add("routed_experts")
if mamba is not None:
supported_targets.add("mamba")
if linear_attn is not None:
supported_targets.add("linear_attn")
@@ -73,29 +117,26 @@ def get_supported_targets(layer: nn.Module) -> frozenset[str]:
def set_selective_activation_checkpointing(layer: nn.Module, targets: Iterable[str]) -> None:
normalized_targets = frozenset(targets)
invalid_targets = normalized_targets - SELECTIVE_AC_TARGETS
target_set = frozenset(targets)
invalid_targets = target_set - SELECTIVE_AC_TARGETS
if invalid_targets:
raise ValueError(f"Unsupported selective activation checkpoint targets: {sorted(invalid_targets)}")
enabled_targets = normalized_targets & get_supported_targets(layer)
enabled_targets = target_set & get_supported_targets(layer)
self_attn = getattr(layer, "self_attn", None)
mlp = getattr(layer, "mlp", None)
linear_attn = _get_linear_attn_module(layer)
attn_proj_is_subsumed = "linear_attn" in enabled_targets and linear_attn is self_attn
mamba = getattr(layer, "mamba", None)
linear_attn = getattr(layer, "linear_attn", None)
if self_attn is not None and "attn_proj" in enabled_targets:
checkpoint_method(self_attn, "_attn_projections")
checkpoint_method(self_attn, "_output_proj")
if self_attn is not None and "attn_proj" in enabled_targets and not attn_proj_is_subsumed:
checkpoint_method(self_attn, "attn_projections")
checkpoint_method(self_attn, "output_proj")
if self_attn is not None and "mla_up_proj" in enabled_targets:
checkpoint_method(self_attn, "_mla_up_proj")
checkpoint_method(self_attn, "mla_up_proj")
if mlp is not None and "mlp" in enabled_targets:
checkpoint_method(mlp, "forward")
if mlp is not None and "routed_experts" in enabled_targets:
checkpoint_method(mlp, "_run_routed_experts")
if mamba is not None and "mamba" in enabled_targets:
checkpoint_method(mamba, "forward")
if linear_attn is not None and "linear_attn" in enabled_targets:
checkpoint_method(linear_attn, "forward")
if "norm" in enabled_targets:
@@ -374,10 +374,44 @@ class Qwen3_5MoeGatedAttentionBase(nn.Module):
self.q_norm = Qwen3_5MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.k_norm = Qwen3_5MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
def output_proj(
self,
attn_output: torch.Tensor,
gate: torch.Tensor,
) -> torch.Tensor:
input_shape = gate.shape[:-1]
if attn_output.dim() == 4:
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.contiguous().view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate)
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,
@@ -401,28 +435,9 @@ class Qwen3_5MoeGatedSDPAAttention(Qwen3_5MoeGatedAttentionBase):
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, None]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
# Split Q into query + gate
query_states, gate = torch.chunk(
self.q_proj(hidden_states).view(*input_shape, -1, self.head_dim * 2), 2, dim=-1
)
gate = gate.reshape(*input_shape, -1)
query_states = self.q_norm(query_states.view(hidden_shape)).transpose(1, 2)
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
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)
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate)
attn_output = self.o_proj(attn_output)
return attn_output, None
return self.output_proj(attn_output, gate), None
class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
@@ -462,17 +477,14 @@ class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
) -> torch.Tensor:
return self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
def forward(
def attn_projections(
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]:
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
# Split Q into query + gate
query_states, gate = torch.chunk(
self.q_proj(hidden_states).view(*input_shape, -1, self.head_dim * 2), 2, dim=-1
)
@@ -482,7 +494,6 @@ class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape))
value_states = self.v_proj(hidden_states).view(hidden_shape)
# Apply RoPE (need transpose for apply_rotary_pos_emb format)
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
cos, sin = position_embeddings
@@ -490,6 +501,16 @@ class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
return query_states, key_states, value_states, gate
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,
@@ -497,10 +518,7 @@ class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
attn_output = attn_output.contiguous().view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate)
attn_output = self.o_proj(attn_output)
return attn_output, None
return self.output_proj(attn_output, gate), None
QWEN35MOE_ATTN_IMPL2CLASS = {
+3 -1
View File
@@ -183,9 +183,11 @@ class WandbMonitor(Monitor):
return
for rollout in rollouts:
completion = rollout.get("completion", "")
completion = rollout.get("completion")
if not completion:
continue
if isinstance(completion, list):
completion = self.tokenizer.apply_chat_template(completion, tokenize=False)
sample = {
"step": step,
"env": env_name,