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"""Public CSA2 factory and its complete local/CP implementation allowlist."""
16
17from __future__ import annotations
18
19from collections.abc import Mapping
20from functools import partial
21from typing import Any
22
23from torch import nn
24
25from hyper_parallel.components.modules.module_family import (
26 ModuleFamily, SelectorSpec, VariantRule, build_family, register_module_family,
27)
28from hyper_parallel.components.quantization.config import LowPrecisionConfig
29from hyper_parallel.core.dtensor.placement_types import Partial, Replicate, Shard
30from hyper_parallel.distributed._builder.family_layout import validate_tp_boundary
31from hyper_parallel.distributed.context_parallel.indexer_balance import (
32 resolve_indexer_balance_block_size, validate_indexer_hybrid_threshold,
33)
34from hyper_parallel.distributed.module_binding import ParallelModuleSpec
35from hyper_parallel.distributed.recipe_spec import ModuleShardingSpec
36from hyper_parallel.models.replacement import module_replacement
37from .compressed_sparse_attention2 import CompressedSparseAttention2Module
38from .cp_compressed_sparse_attention2 import CPCompressedSparseAttention2, _TPCompressedSparseAttention2
39from .quantize_compressed_sparse_attention2 import QuantizeCompressedSparseAttention2Module
40
41def _sharding(*, module: nn.Module, module_fqn: str, member: Any, context: Any) -> ModuleShardingSpec:
42 """Declare parameter roles and let the framework execute the TP/SP boundary."""
43 del module_fqn, member
44 axes = {axis: Replicate() for axis in context.mesh_dim_names if axis in context.axis_sizes}
45 columns = ("q_b_proj", "indexer.q_b_proj", "indexer.weights_proj", "o_a_proj")
46 replicated = ("q_a_proj", "q_a_norm", "kv_proj", "kv_norm", "compressor.wkv", "compressor.wgate",
47 "compressor.norm", "indexer.wk", "indexer.k_norm")
48 roles = {f"{name}.{suffix}": Shard(0) for name in columns for suffix in ("weight", "bias")}
49 roles.update({f"{name}.{suffix}": Replicate() for name in replicated for suffix in ("weight", "bias")})
50 roles.update({"sinks": Shard(0), "o_b_proj.weight": Shard(1), "o_b_proj.bias": Replicate()})
51 params = {}
52 for name, _ in module.named_parameters():
53 if name not in roles:
54 raise ValueError(f"CSA2 parameter {name!r} has no declared sharding role")
55 params[name] = dict(axes)
56 if context.axis_sizes["tp"] > 1:
57 params[name]["tp"] = roles[name]
58 tokens = dict(axes)
59 if context.axis_sizes["cp"] > 1:
60 tokens["cp"] = Shard(1)
61 if context.axis_sizes["tp"] > 1 and context.sequence_parallel:
62 tokens["tp"] = Shard(1)
63 compute_input, compute_output = dict(tokens), dict(tokens)
64 if context.axis_sizes["tp"] > 1:
65 compute_input["tp"], compute_output["tp"] = Replicate(), Partial()
66 return ModuleShardingSpec(
67 params=params, in_src={"hidden_states": dict(tokens)}, in_dst={"hidden_states": compute_input},
68 out_src={"output": compute_output}, out_dst={"output": dict(tokens)},
69 out_names=("output", "attention_weights"), is_boundary=True,
70 )
71
72
73def _validate_layout(*, module: nn.Module, sharding: Any, context: Any) -> None:
74 """Reject overrides that split heads/groups or bypass the declared TP boundary."""
75 expected = _sharding(module=module, module_fqn="", member=None, context=context)
76 validate_tp_boundary(sharding, expected, name="CSA2")
77 tp_size = context.axis_sizes["tp"]
78 if (module.config.o_groups % tp_size or module.num_heads % tp_size
79 or (module.is_index_source and module.indexer.global_num_heads % tp_size)):
80 raise ValueError("CSA2 main heads, Indexer heads and output groups must be divisible by TP")
81
82
83def _parallel_spec(*, module: nn.Module, member: Any) -> ParallelModuleSpec:
84 """Bind resources only to parallel members; standalone math has no mesh dependency."""
85 del member
86 if isinstance(module, CPCompressedSparseAttention2):
87 return ParallelModuleSpec(
88 "attention.csa2.cp", "cp",
89 {"query_partition": ("sequence_length", "position_ids"),
90 "prepare_attention_inputs": ("hidden_states", "embeddings", "shared_state", "document"),
91 "exchange_attention": ("prepared", "shared_state"),
92 "launch_bank": ("tensor", "sequence_dim")}, validate=_validate_layout,
93 )
94 if isinstance(module, _TPCompressedSparseAttention2):
95 return ParallelModuleSpec(
96 "attention.csa2.tp", "mesh", {"head_reducer": (),
97 "query_partition": ("sequence_length", "position_ids")},
98 validate=_validate_layout,
99 )
100 return ParallelModuleSpec("attention.csa2.local", validate=_validate_layout)
101
102
103def _validate(*, config: Any, module: nn.Module | None, context: Any, member: Any) -> None:
104 """Validate the source contract and supported fusion, balance and communication options."""
105 del context
106 if module is not None and not isinstance(module, CompressedSparseAttention2Module):
107 raise TypeError("CSA2 source conversion requires the shared V4.1 attention parameter contract")
108 if module is None:
109 required = ("v41_compress_ratios", "v41_kv_source_layer_ids", "v41_index_source_layer_ids")
110 if any(not hasattr(config, name) for name in required):
111 raise ValueError("CSA2 config must include compression ratios and Full/Reindex source layers")
112 arguments = member.arguments
113 mode = arguments.get("indexer_load_balance", "none")
114 resolve_indexer_balance_block_size(mode, arguments.get("indexer_balance_block_size"))
115 validate_indexer_hybrid_threshold(mode, arguments.get("indexer_zigzag_min_length"))
116 if arguments.get("main_kv_comm", "all_gather") not in ("all_gather", "all_to_all_v"):
117 raise ValueError("main_kv_comm must be 'all_gather' or 'all_to_all_v'")
118 if member.axis_sizes["tp"] > 1 and (member.selectors["use_fused_ops"] or mode != "none"):
119 raise NotImplementedError("CSA2 fusion and Indexer load balancing currently require TP=1")
120
121
122def _build_local(*, config: Any = None, module: nn.Module | None = None, layer_idx: int = 0,
123 module_fqn: str = "", context: Any = None, use_fused_ops: bool = False,
124 indexer_load_balance: str = "none", main_kv_comm: str = "all_gather",
125 indexer_balance_block_size: int | None = None,
126 indexer_zigzag_min_length: int | None = None) -> nn.Module:
127 """Retain CP options in family provenance without adding them to local math."""
128 del module_fqn, indexer_load_balance, main_kv_comm, indexer_balance_block_size, indexer_zigzag_min_length
129 implementation = (_TPCompressedSparseAttention2 if context is not None and context.get("tp_size", 1) > 1
130 else QuantizeCompressedSparseAttention2Module)
131 return implementation(module, config=config, layer_idx=layer_idx, use_fused_ops=use_fused_ops,
132 low_precision=_active_low_precision_config(context))
133
134
135def _build_cp(*, config: Any = None, module: nn.Module | None = None, layer_idx: int = 0,
136 module_fqn: str = "", context: Any = None, use_fused_ops: bool = False,
137 indexer_load_balance: str = "none", main_kv_comm: str = "all_gather",
138 indexer_balance_block_size: int | None = None,
139 indexer_zigzag_min_length: int | None = None) -> nn.Module:
140 """Build the CP variant with the active low-precision policy."""
141 del module_fqn
142 return CPCompressedSparseAttention2(
143 module, config=config, layer_idx=layer_idx, use_fused_ops=use_fused_ops,
144 indexer_load_balance=indexer_load_balance, main_kv_comm=main_kv_comm,
145 indexer_balance_block_size=indexer_balance_block_size,
146 indexer_zigzag_min_length=indexer_zigzag_min_length,
147 low_precision=_active_low_precision_config(context),
148 )
149
150
151def _active_low_precision_config(context: Any) -> LowPrecisionConfig | None:
152 """Return the enabled low-precision policy from the build context."""
153 policy = context.get("low_precision") if isinstance(context, Mapping) else None
154 return policy if isinstance(policy, LowPrecisionConfig) and policy.enabled else None
155
156
157_reference = partial(_build_local, use_fused_ops=False)
158_fused = partial(_build_local, use_fused_ops=True)
159_cp_reference = partial(_build_cp, use_fused_ops=False)
160_cp_fused = partial(_build_cp, use_fused_ops=True)
161
162
163@module_replacement
164def CompressedSparseAttention2( # pylint: disable=invalid-name
165 *, config: Any = None, module: nn.Module | None = None, layer_idx: int = 0,
166 module_fqn: str = "", context: Any = None, mesh: Any = None,
167 use_fused_ops: bool = False, indexer_load_balance: str = "none",
168 main_kv_comm: str = "all_gather", indexer_balance_block_size: int | None = None,
169 indexer_zigzag_min_length: int | None = None,
170) -> nn.Module:
171 """Build complete CSA2, choosing CP automatically from the job's existing mesh.
172
173 Args:
174 config: V4.1 architecture config for direct parameter construction.
175 module: Compatible source module whose parameters and buffers are retained.
176 layer_idx: Layer whose source relationships are read during direct construction.
177 module_fqn: Model path supplied by the generic replacement executor.
178 context: Job topology and construction facts.
179 mesh: Optional prebuilt mesh for direct construction and layout binding.
180 use_fused_ops: Select all three native entries; unsupported calls raise explicitly.
181 indexer_load_balance: none, zigzag, greedy or hybrid; only selection tasks move.
182 main_kv_comm: all_gather or document-prefix all_to_all_v.
183 indexer_balance_block_size: Greedy/hybrid task size, defaulting to 2048.
184 indexer_zigzag_min_length: Hybrid-only long-document threshold in raw tokens.
185 """
186 return build_family(
187 CompressedSparseAttention2, config=config, module=module, layer_idx=layer_idx,
188 module_fqn=module_fqn, context=context, mesh=mesh, use_fused_ops=use_fused_ops,
189 indexer_load_balance=indexer_load_balance, main_kv_comm=main_kv_comm,
190 indexer_balance_block_size=indexer_balance_block_size,
191 indexer_zigzag_min_length=indexer_zigzag_min_length,
192 )
193
194# Declare direct cache formats separately from W/A quantization.
195CompressedSparseAttention2.low_precision_formats = frozenset(("indexer_qk", "main_kv", "swa_kv"))
196
197_PATH = __name__
198register_module_family(ModuleFamily(
199 name="compressed_sparse_attention2", baseline=CompressedSparseAttention2,
200 variants={"reference": f"{_PATH}._reference", "fused": f"{_PATH}._fused",
201 "cp_reference": f"{_PATH}._cp_reference", "cp_fused": f"{_PATH}._cp_fused"},
202 selector_specs={"use_fused_ops": SelectorSpec(bool, False)},
203 variant_rules=(
204 VariantRule({"use_fused_ops": True, "parallel": False}, "fused"),
205 VariantRule({"use_fused_ops": False, "parallel": True}, "cp_reference"),
206 VariantRule({"use_fused_ops": True, "parallel": True}, "cp_fused"),
207 ),
208 default_variant="reference", parallel_axis="cp", sharding=_sharding, validate=_validate,
209 parallel_spec=_parallel_spec,
210))