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"""Head ownership and shared TP/SP token boundaries for linear attention."""
16from __future__ import annotations
17
18from typing import Any
19
20from torch import nn
21import torch.distributed as dist
22
23from hyper_parallel.components.modules.module_family import get_family_build_info
24from hyper_parallel.core.dtensor.device_mesh import DeviceMesh
25from hyper_parallel.core.dtensor.placement_types import Partial, Replicate, Shard
26from hyper_parallel.distributed._builder.family_layout import validate_tp_boundary
27from hyper_parallel.distributed.recipe_spec import ModuleShardingSpec
28from hyper_parallel.distributed.module_binding import ParallelModuleSpec
29
30
31def split_linear_attention_mesh(mesh: DeviceMesh, degree: int, names: tuple[str, str]) -> DeviceMesh:
32 """Split chronological CP ranks into outer state and inner head-exchange groups.
33
34 Args:
35 mesh: One-dimensional CP mesh retaining its complete root rank map.
36 degree: Number of consecutive sequence ranks in each Ulysses group.
37 names: Names for the outer state axis and inner Ulysses axis.
38 """
39 if mesh.ndim != 1 or not isinstance(degree, int) or isinstance(degree, bool):
40 raise ValueError("Linear-attention mesh splitting requires a 1-D mesh and integer degree.")
41 if degree < 1 or mesh.size() % degree:
42 raise ValueError("The split degree must be positive and divide the CP size.")
43 ranks = tuple(mesh.rank_list)
44 if ranks != tuple(dist.get_process_group_ranks(mesh.get_group())):
45 raise ValueError("The CP mesh rank order must match the communication group order.")
46 # Group creation must derive the same sibling groups on every root rank.
47 root = mesh._get_root_mesh() # pylint: disable=protected-access
48 if root.size() != dist.get_world_size():
49 raise ValueError("Hybrid linear attention requires a CP submesh retaining its WORLD root mesh.")
50 return mesh._unflatten(0, (mesh.size() // degree, degree), names) # pylint: disable=protected-access
51
52
53def validate_state_packets(options: Any, cp_size: int, degree: int, backend: str,
54 local_heads: int | None = None) -> None:
55 """Check explicit state packet ownership before creating communication groups.
56
57 Args:
58 options: Module-family arguments containing the packet count and protocol.
59 cp_size: Total context-parallel degree.
60 degree: Ulysses degree within the CP axis.
61 backend: Selected local attention backend.
62 local_heads: Value heads after TP and Ulysses, when dimensions are known.
63 """
64 packets = options.get("p2p_head_chunks", 1)
65 if isinstance(packets, bool) or not isinstance(packets, int) or packets < 1:
66 raise ValueError("p2p_head_chunks must be a positive integer")
67 if packets > 1 and (backend != "ascendc" or options.get("state_cp_method", "p2p") != "p2p" or cp_size <= degree):
68 raise ValueError("p2p_head_chunks requires Ascend C state P2P")
69 if local_heads is not None and packets > local_heads:
70 raise ValueError("p2p_head_chunks must not exceed the local value-head count")
71
72
73def linear_attention_sharding(*, module: nn.Module, context: Any,
74 roles: dict, tp_divide_attrs: tuple[str, ...]) -> ModuleShardingSpec:
75 """Declare head-sharded parameters and reuse the framework's TP/SP token boundary.
76
77 Args:
78 module: Complete local or CP attention member.
79 context: Logical mesh sizes and the external SP layout.
80 roles: Explicit TP placement for each supported parameter name.
81 tp_divide_attrs: Cached dimensions not covered by automatic head-count adjustment.
82 """
83 placements = {axis: Replicate() for axis in context.mesh_dim_names if axis in context.axis_sizes}
84 params = {}
85 for name, _ in module.named_parameters():
86 params[name] = dict(placements)
87 if context.axis_sizes["tp"] > 1:
88 if name not in roles:
89 raise ValueError(f"Linear-attention parameter {name!r} has no declared TP role")
90 params[name]["tp"] = roles[name]
91 tokens = dict(placements)
92 token_axis = 0 if module.input_layout == "TH" else 1
93 if context.axis_sizes["cp"] > 1:
94 tokens["cp"] = Shard(token_axis)
95 if context.axis_sizes["tp"] > 1 and context.sequence_parallel:
96 tokens["tp"] = Shard(token_axis)
97 compute_input, compute_output = dict(tokens), dict(tokens)
98 if context.axis_sizes["tp"] > 1:
99 compute_input["tp"], compute_output["tp"] = Replicate(), Partial()
100 names = ("output", "attention_weights", "cache") if getattr(module, "_returns_tuple", False) else ("output",)
101 return ModuleShardingSpec(params=params, tp_divide_attrs=list(tp_divide_attrs),
102 in_src={"hidden_states": dict(tokens)}, in_dst={"hidden_states": compute_input},
103 out_src={"output": compute_output}, out_dst={"output": dict(tokens)},
104 out_names=names, is_boundary=True)
105
106
107def validate_linear_attention_layout(*, module: nn.Module, sharding: Any, context: Any) -> None:
108 """Reject a user override that changes ownership without an implemented algorithm.
109
110 Args:
111 module: Existing source module or resolved family member.
112 sharding: Proposed input, output and parameter placements.
113 context: Logical parallel sizes or the resolved sharding context.
114 """
115 member = get_family_build_info(module).resolved
116 expected = member.family.sharding(module=module, module_fqn="", member=member, context=context)
117 validate_tp_boundary(sharding, expected, name=type(module).__name__,
118 sequence_dim=0 if module.input_layout == "TH" else 1)
119
120
121def linear_attention_local_spec(*, module: nn.Module, member: Any) -> ParallelModuleSpec:
122 """Validate local layouts without borrowing CP resources.
123
124 Args:
125 module: Existing source module or resolved family member.
126 member: Resolved family member and its implementation arguments.
127 """
128 del module, member
129 return ParallelModuleSpec("attention.linear.local", validate=validate_linear_attention_layout)