1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Gated GQA: per-query-head gate weights and output math, without CP transport."""
16
17from __future__ import annotations
18
19from typing import Any
20
21import torch
22from torch import nn
23from hyper_parallel.components.checkpoint import InterleaveGateQKV
24from hyper_parallel.components.checkpoint.weight_conversion import WeightConverter
25from ..grouped_query_attention.grouped_query_attention import GroupedQueryAttentionModule, _projections_can_fuse
26
27
28class GatedGroupedQueryAttentionModule(GroupedQueryAttentionModule):
29 """GQA with a sigmoid output gate derived from each query head.
30
31 The source ``q_proj`` is expected to store ``[query, gate]`` rows for each
32 query head. This is the gated-query layout used by Qwen3.5 full attention.
33 """
34
35 def _initialize_dimensions(self, module: nn.Module | None) -> None:
36 """Extend ordinary GQA dimensions by one gate value per query channel."""
37 if not self.fuse_qkv:
38 raise ValueError("Gated GQA currently requires fused Q/K/V/gate projections")
39 super()._initialize_dimensions(module)
40 if self.qk_head_dim != self.v_head_dim:
41 raise ValueError("GatedGroupedQueryAttention requires the gate width to match the attention output width")
42 self.gated_qkv_group_width = self.qkv_group_width + self.num_key_value_groups * self.qk_head_dim
43
44 def _initialize_config_projections(self, config: Any, bias: bool, dtype: torch.dtype | None) -> None:
45 """Allocate native [grouped Q, K, V, grouped gate] rows directly."""
46 self.linear_qkv = nn.Linear(
47 config.hidden_size, self.num_key_value_heads * self.gated_qkv_group_width, bias=bias, dtype=dtype)
48
49 def _validate_source_projections(self, module: nn.Module) -> None:
50 """Validate separate gated-query, key, value, and output projections."""
51 projections = (module.q_proj, module.k_proj, module.v_proj)
52 if any(not isinstance(projection, nn.Linear) for projection in projections):
53 raise TypeError("q_proj, k_proj, and v_proj must be torch.nn.Linear")
54 expected_sizes = (
55 2 * self.num_heads * self.qk_head_dim,
56 self.num_key_value_heads * self.qk_head_dim,
57 self.num_key_value_heads * self.v_head_dim,
58 )
59 if tuple(projection.out_features for projection in projections) != expected_sizes:
60 raise ValueError(
61 "Q/gate, K, and V projection sizes are incompatible with the configured gated GQA dimensions"
62 )
63 if not _projections_can_fuse(projections):
64 raise ValueError("Q/gate, K, and V projections cannot be represented by one fused projection")
65 attention_output_size = self.num_heads * self.v_head_dim
66 if not isinstance(module.o_proj, nn.Linear):
67 raise TypeError("o_proj must be torch.nn.Linear")
68 if module.o_proj.in_features != attention_output_size:
69 raise ValueError("o_proj input size is incompatible with the configured gated GQA dimensions")
70
71 def _initialize_projection(self, module: nn.Module) -> None:
72 """Create the fused gated-QKV projection and attach source output layers."""
73 self.linear_qkv = nn.Linear(
74 module.q_proj.in_features,
75 self.num_key_value_heads * self.gated_qkv_group_width,
76 bias=module.q_proj.bias is not None,
77 device=module.q_proj.weight.device,
78 dtype=module.q_proj.weight.dtype,
79 )
80 self.linear_qkv.weight.requires_grad_(module.q_proj.weight.requires_grad)
81 if self.linear_qkv.bias is not None:
82 self.linear_qkv.bias.requires_grad_(module.q_proj.bias.requires_grad)
83 self.q_norm = getattr(module, "q_norm", None)
84 self.k_norm = getattr(module, "k_norm", None)
85 self.o_proj = module.o_proj
86
87 def _initialize_attention_options(self, module: Any) -> None:
88 """Copy attention options; this representation always computes the query gate."""
89 config = self.config
90 self.scaling = getattr(module, "scaling", self.qk_head_dim**-0.5)
91 self.attention_dropout = getattr(module, "attention_dropout", 0.0)
92 if isinstance(self.attention_dropout, nn.Dropout):
93 self.attention_dropout = self.attention_dropout.p
94 self.is_causal = getattr(module, "is_causal", True)
95 self.sliding_window = getattr(module, "sliding_window", getattr(config, "sliding_window", None))
96 self.rotary_interleaved = getattr(
97 module, "rotary_interleaved",
98 getattr(config, "rope_interleave", getattr(config, "rope_interleaved", False)),
99 )
100
101 def _source_qkv(self, module: nn.Module) -> tuple:
102 """Validate the per-query-head source gate layout before fusion."""
103 if any(not hasattr(module, name) for name in ("q_proj", "k_proj", "v_proj", "o_proj")):
104 raise TypeError("Gated GQA requires separate Q/gate, K, V and output projections")
105 self._validate_source_projections(module)
106 self._source_is_fused = False
107 return module.q_proj, ("q_proj", "k_proj", "v_proj")
108
109 def _initialize_projections(self, module: nn.Module, source_qkv: nn.Linear) -> None:
110 del source_qkv
111 self._initialize_projection(module)
112
113 def make_transforms(self) -> list[WeightConverter]:
114 """Describe reversible gated-query and grouped-QKV conversion."""
115 if self._config_initialization:
116 return []
117 suffixes = ("weight", "bias") if self.linear_qkv.bias is not None else ("weight",)
118 transforms = []
119 for suffix in suffixes:
120 transforms.append(WeightConverter(
121 source_patterns=[f"{name}.{suffix}" for name in ("q_proj", "k_proj", "v_proj")],
122 target_patterns=f"linear_qkv.{suffix}",
123 operations=[InterleaveGateQKV(
124 self.config.num_key_value_heads, self.num_key_value_groups, self.qk_head_dim, self.v_head_dim,
125 )],
126 ))
127 return transforms
128
129 def split_projection(self, hidden_states: torch.Tensor) -> tuple:
130 """Keep the fused per-KV-head Q/K/V/gate checkpoint row ordering."""
131 shape = hidden_states.shape[:-1]
132 projected = self.linear_qkv(hidden_states).view(*shape, self.num_key_value_heads, self.gated_qkv_group_width)
133 query, key, value, gate = projected.split(
134 (*self.qkv_split_sizes, self.num_key_value_groups * self.qk_head_dim), dim=-1)
135 return query.reshape(*shape, self.num_heads, self.qk_head_dim), key, value, gate.reshape(*shape, -1)
136
137 def project_output(self, attention_output: torch.Tensor, output_state: torch.Tensor) -> torch.Tensor:
138 """Apply the mandatory gate before the output projection."""
139 return self.o_proj(attention_output.flatten(-2).contiguous() * torch.sigmoid(output_state))