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"""GatedDeltaNet family selection; backend and communication are independent options."""
16from __future__ import annotations
17
18from typing import Any
19from torch import nn
20
21from hyper_parallel.core.dtensor.placement_types import Replicate, Shard
22from hyper_parallel.distributed.recipe_spec import ModuleShardingSpec
23
24from hyper_parallel.components.modules.module_family import (
25 ModuleFamily, VariantRule, build_family, register_module_family,
26)
27from hyper_parallel.components.modules.attention.linear_attention_utils.parallel_layout import (
28 linear_attention_local_spec, linear_attention_sharding, validate_state_packets,
29)
30from hyper_parallel.components.modules.attention.linear_attention_utils.layer_adapter import validate_backend_options
31from hyper_parallel.models.replacement import module_replacement
32from .gated_delta_net import GatedDeltaNetModule
33
34
35def _validate_gdn_protocol(cp, degree, backend, arguments):
36 """Reject unimplemented combinations before creating communication groups."""
37 if 1 < degree < cp and backend != "ascendc":
38 raise NotImplementedError("GDN hybrid Ulysses/state CP currently requires Ascend C")
39 method = arguments.get("state_cp_method", "p2p")
40 if method not in ("p2p", "allgather"):
41 raise ValueError("GDN state_cp_method must be p2p or allgather")
42 if cp > degree and backend not in ("triton", "ascendc"):
43 raise NotImplementedError("GDN state CP requires Triton or Ascend C")
44 if method == "allgather" and backend != "ascendc":
45 raise NotImplementedError("GDN AllGather currently requires Ascend C")
46
47
48def validate_gdn_family(*, config: Any, module: nn.Module | None, context: Any, member: Any) -> None:
49 """Check this family's supported algorithms before constructing parameters or groups."""
50 del context
51 backend = validate_backend_options(member.arguments)
52 cp = member.axis_sizes["cp"]
53 degree = member.arguments.get("ulysses_degree", 1)
54 degree = cp if degree is None else degree
55 if (not isinstance(degree, int) or isinstance(degree, bool)) or degree < 1 or (cp > 1 and cp % degree):
56 raise ValueError("ulysses_degree must be a positive divisor of CP size")
57 source = config if module is None else module
58 kh = getattr(source, "num_k_heads", None) if module is not None else source.linear_num_key_heads
59 vh = getattr(source, "num_v_heads", None) if module is not None else source.linear_num_value_heads
60 head_degree = member.axis_sizes["tp"] * (degree if cp > 1 else 1)
61 if kh is not None and (kh % head_degree or vh % head_degree):
62 raise ValueError("TP times Ulysses degree must divide both query and value heads")
63 _validate_gdn_protocol(cp, degree, backend, member.arguments)
64 validate_state_packets(member.arguments, cp, degree, backend, None if vh is None else vh // head_degree)
65
66
67def gdn_sharding(*, module: nn.Module, module_fqn: str, member: Any, context: Any) -> ModuleShardingSpec:
68 """Shard complete Q/K/value groups while retaining the shared per-head norm.
69
70 Args:
71 module: GDN family member with grouped QKV and convolution rows.
72 module_fqn: Source path supplied by the common layout planner.
73 member: Resolved family selection.
74 context: Logical TP/CP sizes and SP mode.
75 """
76 del module_fqn, member
77 columns = ("in_proj_qkv", "in_proj_z", "in_proj_a", "in_proj_b", "conv1d")
78 roles = {f"{name}.{suffix}": Shard(0) for name in columns for suffix in ("weight", "bias")}
79 roles.update({"A_log": Shard(0), "dt_bias": Shard(0), "out_proj.weight": Shard(1),
80 "out_proj.bias": Replicate(), "norm.weight": Replicate(), "norm.bias": Replicate()})
81 return linear_attention_sharding(
82 module=module, context=context, roles=roles,
83 tp_divide_attrs=("num_k_heads", "num_v_heads", "key_dim", "value_dim", "conv_dim"))
84
85
86def _build_local(
87 *, config: Any = None, module: nn.Module | None = None, module_fqn: str = "", context: Any = None,
88 backend: str = "eager", conv_backend: str | None = None, chunk_size: int = 64,
89 input_layout: str = "BSH", ulysses_degree: int | None = 1,
90 state_cp_method: str = "p2p", p2p_head_chunks: int = 1, reuse_cp_state_on_recompute: bool = False,
91) -> nn.Module:
92 """Keep CP selection in the family request, outside the standalone algorithm."""
93 del module_fqn, context, ulysses_degree, state_cp_method, p2p_head_chunks, reuse_cp_state_on_recompute
94 return GatedDeltaNetModule(config=config, module=module, backend=backend, conv_backend=conv_backend,
95 chunk_size=chunk_size, input_layout=input_layout)
96
97
98# Public factories follow the ModuleFamily class-style naming convention.
99@module_replacement
100def GatedDeltaNet( # pylint: disable=invalid-name
101 *, config: Any = None, module: nn.Module | None = None, module_fqn: str = "",
102 context: Any = None, mesh: Any = None, backend: str = "eager", conv_backend: str | None = None,
103 chunk_size: int = 64, input_layout: str = "BSH", ulysses_degree: int | None = 1,
104 state_cp_method: str = "p2p", p2p_head_chunks: int = 1, reuse_cp_state_on_recompute: bool = False,
105) -> nn.Module:
106 """Build the complete local or CP training member with source checkpoint names.
107
108 Args:
109 config: Direct model dimensions; mutually exclusive with module.
110 module: Supported source; QKV and convolution rows receive a reversible grouped conversion.
111 module_fqn: Path supplied by model replacement.
112 context: Logical parallel degrees for selection without process groups.
113 mesh: Existing runtime mesh for layout and resource binding.
114 backend: Explicit eager, triton or ascendc attention implementation.
115 conv_backend: Independent convolution implementation; omission preserves scheduling defaults.
116 chunk_size: Local chunk length; fused implementations require 64.
117 input_layout: BSH or TH, determining the external token shard axis.
118 ulysses_degree: Head-exchange degree; None selects pure Ulysses scheduling.
119 state_cp_method: p2p, or allgather for the native state-CP backend.
120 p2p_head_chunks: Number of native state packets, independent of local Prepare.
121 reuse_cp_state_on_recompute: Retain the native CP entry across outer checkpoint replay; default False.
122 """
123 return build_family(GatedDeltaNet, config=config, module=module, module_fqn=module_fqn,
124 context=context, mesh=mesh, backend=backend, conv_backend=conv_backend,
125 chunk_size=chunk_size, input_layout=input_layout, ulysses_degree=ulysses_degree,
126 state_cp_method=state_cp_method,
127 p2p_head_chunks=p2p_head_chunks, reuse_cp_state_on_recompute=reuse_cp_state_on_recompute)
128
129
130register_module_family(ModuleFamily(
131 name="gated_delta_net", baseline=GatedDeltaNet,
132 variants={
133 "local": ("hyper_parallel.components.modules.attention.gated_delta_net."
134 "gated_delta_net_family._build_local"),
135 "cp": ("hyper_parallel.components.modules.attention.gated_delta_net."
136 "cp_gated_delta_net.CPGatedDeltaNetModule"),
137 },
138 default_variant="local", parallel_axis="cp", variant_rules=(VariantRule({"parallel": True}, "cp"),),
139 sharding=gdn_sharding, validate=validate_gdn_family,
140 parallel_spec=linear_attention_local_spec,
141))