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"""GQA families: fixed parameter representations and complete TP/SP layout ownership."""
16
17from __future__ import annotations
18
19from typing import Any
20
21from torch import nn
22
23from hyper_parallel.components.modules.module_family import (
24 ModuleFamily, VariantRule, build_family, register_module_family,
25)
26from hyper_parallel.core.dtensor.placement_types import Partial, Replicate, Shard
27from hyper_parallel.distributed.recipe_spec import ModuleShardingSpec
28from hyper_parallel.distributed._builder.family_layout import validate_tp_boundary
29from hyper_parallel.distributed.module_binding import ParallelModuleSpec
30from hyper_parallel.models.replacement import module_replacement
31from .grouped_query_attention import GroupedQueryAttentionModule
32
33
34_DEFAULT_GQA_CP_OPTIONS = {
35 "ulysses_cp_size": 1,
36 "ulysses_cp_strategy": "alltoall",
37 "kv_cp_size": 1,
38 "kv_cp_strategy": "allgather",
39 "ring_cp_size": 1,
40 "ring_cp_strategy": "p2p",
41 "ring_cp_load_balance": False,
42 "cp_comm_overlap": False,
43 "prune_documents": True,
44}
45
46
47def _normalize_load_balance(value: bool | str, name: str) -> str:
48 """Normalize the public disabled/zigzag values to an internal name."""
49 if value is False or value in ("none", "false"):
50 return "none"
51 if value == "zigzag":
52 return value
53 raise ValueError(f"{name} must be false or 'zigzag'")
54
55
56def _gqa_cp_options(config: Any) -> dict[str, Any]:
57 """Read and validate the GQA CP options stored on attention config."""
58 options = {name: getattr(config, name, default)
59 for name, default in _DEFAULT_GQA_CP_OPTIONS.items()}
60 for name in ("ulysses_cp_size", "kv_cp_size", "ring_cp_size"):
61 value = options[name]
62 if not isinstance(value, int) or isinstance(value, bool) or value < 1:
63 raise ValueError(f"{name} must be a positive integer")
64 if options["ulysses_cp_strategy"] != "alltoall":
65 raise ValueError("GQA currently supports ulysses_cp_strategy='alltoall'")
66 if options["kv_cp_strategy"] != "allgather":
67 raise ValueError("GQA currently supports kv_cp_strategy='allgather'")
68 if options["ring_cp_strategy"] != "p2p":
69 raise ValueError("GQA currently supports ring_cp_strategy='p2p'")
70 if not isinstance(options["cp_comm_overlap"], bool):
71 raise TypeError("cp_comm_overlap must be boolean")
72 if not isinstance(options["prune_documents"], bool):
73 raise TypeError("prune_documents must be boolean")
74 options["ring_cp_load_balance"] = _normalize_load_balance(
75 options["ring_cp_load_balance"], "ring_cp_load_balance")
76 if options["kv_cp_size"] > 1 and options["ring_cp_size"] > 1:
77 raise ValueError("GQA does not support combining KV AllGather with Ring")
78 if options["ring_cp_load_balance"] != "none" and options["ring_cp_size"] == 1:
79 raise ValueError("ring_cp_load_balance requires ring_cp_size > 1")
80 return options
81
82
83def _store_gqa_cp_options(config: Any, module: nn.Module | None, options: dict[str, Any]) -> None:
84 """Store module-level CP overrides on the config consumed by the CP member."""
85 attention_config = config if config is not None else getattr(module, "config", None)
86 if attention_config is None:
87 raise ValueError("GQA CP options require an attention config")
88 for name, value in options.items():
89 if value is not None:
90 setattr(attention_config, name, value)
91
92
93def validate_gqa_family(*, config: Any, module: nn.Module | None, context: Any, member: Any) -> None:
94 """Reject TP degrees that split KV groups before constructing parameters."""
95 del context
96 config = config if module is None else module.config
97 if config is None:
98 raise ValueError("GQA requires configuration")
99 heads = (config.num_attention_heads, config.num_key_value_heads)
100 if any(not isinstance(value, int) or isinstance(value, bool) or value <= 0 for value in heads):
101 raise ValueError("GQA head counts must be positive integers")
102 if not isinstance(member.arguments.get("fuse_qkv", True), bool):
103 raise TypeError("GQA fuse_qkv must be boolean")
104 options = _gqa_cp_options(config)
105 if options["ulysses_cp_size"] * options["kv_cp_size"] * options["ring_cp_size"] != member.axis_sizes["cp"]:
106 raise ValueError(
107 "GQA CP factors must multiply to accelerator.cp_size: "
108 f"{options['ulysses_cp_size']} × {options['kv_cp_size']} × {options['ring_cp_size']} "
109 f"!= {member.axis_sizes['cp']}"
110 )
111 _validate_gqa_degrees(config, member, options)
112
113
114def _validate_gqa_degrees(config, member, options):
115 """Check TP/CP factors against whole Q and KV groups."""
116 degree = options["ulysses_cp_size"]
117 tp = member.axis_sizes["tp"]
118 if config.num_attention_heads % tp:
119 raise ValueError("GQA query heads must be divisible by TP degree")
120 if config.num_key_value_heads % tp:
121 raise ValueError(
122 "GQA KV heads must be divisible by TP degree for the current whole-KV-group layout; "
123 "TP KV replication is not implemented"
124 )
125
126 if degree > 1 and (config.num_attention_heads // tp % degree or config.num_key_value_heads // tp % degree):
127 raise ValueError("GQA ulysses_cp_size must divide TP-local Q and KV heads")
128
129
130def gqa_sharding(*, module: nn.Module, module_fqn: str, member: Any, context: Any) -> ModuleShardingSpec:
131 """Own all GQA parameters and declare the actual external token layout."""
132 del module_fqn, member
133 placements = {axis: Replicate() for axis in context.mesh_dim_names if axis in context.axis_sizes}
134 # Every supported parameter has an explicit role. A new/quantized projection
135 # must declare its layout instead of silently inheriting Replicate.
136 columns = {f"{name}.{suffix}" for name in ('linear_qkv', 'q_proj', 'k_proj', 'v_proj')
137 for suffix in ("weight", "bias")}
138 replicated = {f"{name}.{suffix}" for name in ('q_norm', 'k_norm')
139 for suffix in ("weight", "bias")}
140 roles = {**dict.fromkeys(columns, Shard(0)), **dict.fromkeys(replicated, Replicate()),
141 "o_proj.weight": Shard(1), "o_proj.bias": Replicate()}
142 params = {}
143 for name, _ in module.named_parameters():
144 if name not in roles:
145 raise ValueError(f"GQA parameter {name!r} has no declared sharding role")
146 params[name] = dict(placements)
147 if context.axis_sizes["tp"] > 1:
148 params[name]["tp"] = roles[name]
149 tokens = dict(placements)
150 if context.axis_sizes["cp"] > 1:
151 tokens["cp"] = Shard(1)
152 if context.axis_sizes["tp"] > 1 and context.sequence_parallel:
153 tokens["tp"] = Shard(1)
154 # CP ownership describes the external token shard. Ulysses changes head /
155 # sequence ownership internally and restores this same shard before return.
156 compute_input, compute_output = dict(tokens), dict(tokens)
157 if context.axis_sizes["tp"] > 1:
158 compute_input["tp"], compute_output["tp"] = Replicate(), Partial()
159 return ModuleShardingSpec(
160 params=params, in_src={"hidden_states": dict(tokens)}, in_dst={"hidden_states": compute_input},
161 out_src={"output": compute_output}, out_dst={"output": dict(tokens)},
162 out_names=("output", "attention_weights"), is_boundary=True,
163 )
164
165
166def validate_gqa_layout(*, module: nn.Module, sharding: Any, context: Any) -> None:
167 """Reject incompatible parameter overrides before any collectives can be bound."""
168 expected = gqa_sharding(module=module, module_fqn="", member=None, context=context)
169 validate_tp_boundary(sharding, expected, name="GQA")
170
171
172
173def gqa_local_parallel_spec(*, module: nn.Module, member: Any) -> ParallelModuleSpec:
174 """Retain final layout validation without binding resources to standalone math."""
175 del module, member
176 return ParallelModuleSpec("attention.gqa.local", validate=validate_gqa_layout)
177
178
179def _build_local(
180 *, config: Any = None, module: nn.Module | None = None, fuse_qkv: bool = True,
181) -> nn.Module:
182 """Build standalone GQA math without receiving family-owned CP controls."""
183 return GroupedQueryAttentionModule(config=config, module=module, fuse_qkv=fuse_qkv)
184
185
186@module_replacement
187def GroupedQueryAttention( # pylint: disable=invalid-name
188 *, config: Any = None, module: nn.Module | None = None, module_fqn: str = "",
189 context: Any = None, mesh: Any = None, fuse_qkv: bool = True,
190 ulysses_cp_size: int | None = None, ulysses_cp_strategy: str | None = None,
191 kv_cp_size: int | None = None, kv_cp_strategy: str | None = None,
192 ring_cp_size: int | None = None, ring_cp_strategy: str | None = None,
193 ring_cp_load_balance: bool | str | None = None,
194 cp_comm_overlap: bool | None = None, prune_documents: bool | None = None,
195) -> nn.Module:
196 """Build GQA; module-level CP overrides are stored on its attention config.
197
198 Args:
199 config: Native dimensions/options; mutually exclusive with module. Q/K RMSNorm is opt-in via qk_norm.
200 module: Source attention with the supported projection and checkpoint layout.
201 module_fqn: Source module path supplied by replacement.
202 context: Logical parallel configuration, independent of concrete process groups.
203 mesh: Existing job mesh, borrowed by the shared execution binder.
204 fuse_qkv: Use grouped linear_qkv (True) or independent Q/K/V Parameters (False); fixed at construction.
205 ulysses_cp_size: Number of ranks exchanging sequence for heads.
206 ulysses_cp_strategy: Currently only ``alltoall`` is supported.
207 kv_cp_size: Number of ranks in the original KV AllGather domain.
208 kv_cp_strategy: Currently only ``allgather`` is supported.
209 ring_cp_size: Number of ranks in Ring; may combine with Ulysses.
210 ring_cp_strategy: Currently only ``p2p`` is supported.
211 ring_cp_load_balance: Optional ``zigzag`` balancing for Ring query work.
212 cp_comm_overlap: Submit supported CP communications asynchronously.
213 prune_documents: Prune unused packed-document KV routes in Ring mode.
214
215 Returns:
216 The local or CP member with fixed parameter names and family provenance.
217 """
218 _store_gqa_cp_options(config, module, {
219 "ulysses_cp_size": ulysses_cp_size,
220 "ulysses_cp_strategy": ulysses_cp_strategy,
221 "kv_cp_size": kv_cp_size,
222 "kv_cp_strategy": kv_cp_strategy,
223 "ring_cp_size": ring_cp_size,
224 "ring_cp_strategy": ring_cp_strategy,
225 "ring_cp_load_balance": ring_cp_load_balance,
226 "cp_comm_overlap": cp_comm_overlap,
227 "prune_documents": prune_documents,
228 })
229 return build_family(GroupedQueryAttention, config=config, module=module, module_fqn=module_fqn,
230 context=context, mesh=mesh, fuse_qkv=fuse_qkv)
231
232
233register_module_family(ModuleFamily(
234 name="grouped_query_attention", baseline=GroupedQueryAttention,
235 variants={"local": (
236 "hyper_parallel.components.modules.attention.grouped_query_attention."
237 "grouped_query_attention_family._build_local"
238 ),
239 "cp": (
240 "hyper_parallel.components.modules.attention.grouped_query_attention."
241 "cp_grouped_query_attention.build_cp_grouped_query_attention"
242 )},
243 default_variant="local", parallel_axis="cp",
244 variant_rules=(VariantRule({"parallel": True}, "cp"),),
245 sharding=gqa_sharding, validate=validate_gqa_family, parallel_spec=gqa_local_parallel_spec,
246))