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"""Explicit local-query KV-AllGather scheduling for DeepSeek sparse attention."""
16
17from __future__ import annotations
18
19from collections.abc import Mapping, Sequence
20from dataclasses import dataclass
21from typing import Any
22
23import torch
24
25from hyper_parallel.components.functional.npu_fusion_attention import resolve_packed_sequence_lengths
26from hyper_parallel.components.modules.attention.deepseek_sparse_attention.deepseek_sparse_attention import (
27 DeepseekSparseAttentionModule,
28 SparseAttentionInputs, SparseAttentionSequenceMetadata,
29)
30from hyper_parallel.components.modules.attention.deepseek_sparse_attention.deepseek_sparse_attention_family import (
31 sparse_attention_parallel_spec, validate_sparse_attention_layout,
32)
33from hyper_parallel.distributed.context_parallel.cp_context import CPContext
34from hyper_parallel.distributed.module_binding import ParallelBinding, ParallelModuleSpec
35
36
37@dataclass(frozen=True)
38class CPSparseAttentionSequenceMetadata(SparseAttentionSequenceMetadata):
39 """CP kernel segments and optional ranges into the flattened global key bank."""
40
41 key_ranges: tuple[tuple[int, int], ...] = ()
42
43
44def _split_packed_prefixes(
45 queries: Sequence[int], keys: Sequence[int], *, global_seq_len: int, local_seq_len: int, rank: int,
46) -> tuple[tuple[int, ...], tuple[int, ...], tuple[tuple[int, int], ...]]:
47 """Pair each contiguous local Q segment with its complete document KV prefix."""
48 query_ends, key_ends, key_ranges = [], [], []
49 query_start = key_start = query_total = key_total = 0
50 for query_end, key_end in zip(queries, keys):
51 for row in range(query_start // global_seq_len, (query_end - 1) // global_seq_len + 1):
52 shard_start = row * global_seq_len + rank * local_seq_len
53 begin, end = max(query_start, shard_start), min(query_end, shard_start + local_seq_len)
54 if begin >= end:
55 continue
56 prefix_end = key_end - (query_end - end)
57 query_total += end - begin
58 key_total += prefix_end - key_start
59 query_ends.append(query_total)
60 key_ends.append(key_total)
61 key_ranges.append((key_start, prefix_end))
62 query_start, key_start = query_end, key_end
63 return tuple(query_ends), tuple(key_ends), tuple(key_ranges)
64
65
66def _project_ends(
67 boundaries: Sequence[int], *, global_seq_len: int, local_seq_len: int, rank: int, query: bool,
68) -> tuple[int, ...]:
69 """Intersect every document with the Q shard or causal KV prefix in each row."""
70 previous = total = 0
71 result = []
72 for end in boundaries:
73 length = 0
74 for row in range(previous // global_seq_len, (end - 1) // global_seq_len + 1):
75 row_start = row * global_seq_len
76 begin = row_start + rank * local_seq_len if query else row_start
77 stop = row_start + (rank + 1) * local_seq_len
78 length += max(0, min(end, stop) - max(previous, begin))
79 total += length
80 result.append(total)
81 previous = end
82 return tuple(result)
83
84
85def _project_rank_metadata(
86 queries: Sequence[int], keys: Sequence[int], *, global_length: int, local_seq_len: int,
87 rank: int, compact: bool,
88) -> tuple[tuple[int, ...], tuple[int, ...], tuple[tuple[int, int], ...]]:
89 """Project one rank's sequence metadata and causal KV prefixes."""
90 if compact:
91 return _split_packed_prefixes(
92 queries, keys, global_seq_len=global_length, local_seq_len=local_seq_len, rank=rank,
93 )
94 query = _project_ends(
95 queries, global_seq_len=global_length, local_seq_len=local_seq_len, rank=rank, query=True,
96 )
97 key = _project_ends(
98 keys, global_seq_len=global_length, local_seq_len=local_seq_len, rank=rank, query=False,
99 )
100 return query, key, ()
101
102
103def build_cp_sequence_metadata(
104 *, batch_size: int, local_seq_len: int, device: torch.device, cp_size: int, cp_rank: int,
105 actual_seq_len: torch.Tensor | Sequence[int] | None = None, kwargs: Mapping[str, Any] | None = None,
106) -> CPSparseAttentionSequenceMetadata:
107 """Project each rank's non-empty query fragments and causal KV prefixes.
108
109 Args:
110 batch_size: Number of batch-major rows.
111 local_seq_len: Equal contiguous token count per row and CP rank.
112 device: Kernel metadata device.
113 cp_size: Context-parallel degree.
114 cp_rank: Rank within the borrowed CP group.
115 actual_seq_len: Global cumulative packed endpoints without leading zero.
116 kwargs: Supported packed aliases, including packed_seq_params.
117
118 Returns:
119 This rank's cumulative Q/K endpoints and the consumed key-bank ranges.
120 """
121 global_length = local_seq_len * cp_size
122 total = batch_size * global_length
123 packed = dict(kwargs or {})
124 if actual_seq_len is not None:
125 packed["actual_seq_len"] = actual_seq_len
126 queries, keys = resolve_packed_sequence_lengths(packed, total, total)
127 compact = cp_size > 1 and queries is not None
128 if queries is None:
129 queries = keys = [(row + 1) * global_length for row in range(batch_size)]
130 if len(queries) != len(keys):
131 raise ValueError("Sparse attention requires the same number of packed Q and KV documents")
132 if cp_size > 1 and queries != keys:
133 raise ValueError("Sparse attention CP requires matching packed Q and KV document boundaries")
134 projected = tuple(
135 _project_rank_metadata(
136 queries, keys, global_length=global_length, local_seq_len=local_seq_len,
137 rank=rank, compact=compact,
138 )
139 for rank in range(cp_size)
140 )
141 local_query, local_key, key_ranges = projected[cp_rank]
142 return CPSparseAttentionSequenceMetadata(
143 local_key[-1] if key_ranges else (cp_rank + 1) * local_seq_len,
144 torch.tensor(local_query, dtype=torch.int32, device=device),
145 torch.tensor(local_key, dtype=torch.int32, device=device),
146 key_ranges,
147 )
148
149
150def _gather_key_banks(
151 context: CPContext, overlap: bool,
152 index_states: tuple[torch.Tensor, ...], attention_states: tuple[torch.Tensor, ...],
153 metadata: CPSparseAttentionSequenceMetadata,
154) -> tuple[tuple[torch.Tensor, ...], tuple[torch.Tensor, ...]]:
155 """Gather the three key banks, then select complete causal prefixes."""
156 index_query, index_key, weights = index_states
157 query, latent_kv, query_rope, key_rope = attention_states
158 tensors = (index_key, latent_kv, key_rope)
159 if overlap:
160 pending = tuple(context.launch_gather_sequence(tensor, dim=1) for tensor in tensors)
161 gathered = tuple(receipt.wait()[0] for receipt in pending)
162 else:
163 gathered = tuple(context.gather_sequence(tensor, dim=1)[0] for tensor in tensors)
164 if metadata.key_ranges:
165 # Repeated prefixes remain in autograd so their key gradients accumulate
166 # before the existing gather adjoint reduces them to the source shards.
167 index_key, latent_kv, key_rope = (
168 torch.cat([tensor.flatten(0, 1)[begin:end] for begin, end in metadata.key_ranges]).unsqueeze(0)
169 for tensor in gathered
170 )
171 else:
172 index_key, latent_kv, key_rope = (
173 tensor[:, :metadata.kv_prefix_length].contiguous() for tensor in gathered
174 )
175 return (index_query, index_key, weights), (query, latent_kv, query_rope, key_rope)
176
177
178class CPDeepseekSparseAttentionModule(DeepseekSparseAttentionModule):
179 """Borrow CP transport while reusing the local constructor and kernel stages.
180
181 Binding installs the borrowed context on each instance; construction needs no mesh.
182 """
183
184 _cp_context: CPContext | None = None
185
186 @staticmethod
187 def parallel_module_spec() -> ParallelModuleSpec:
188 """Declare operand exchange while the local algorithm owns mathematical dispatch."""
189 local_spec = sparse_attention_parallel_spec(module=None, member=None)
190 return ParallelModuleSpec(
191 "attention.deepseek_sparse_attention.cp", binding_kind="cp",
192 stages=local_spec.stages,
193 validate=validate_sparse_attention_layout,
194 )
195
196 def bind_parallel(self, binding: ParallelBinding) -> None:
197 """Borrow an existing CPContext before FSDP installs projection hooks.
198
199 Args:
200 binding: Existing CP context and mesh resources owned by the job.
201 """
202 context = binding.cp_context
203 if context is None or context.size <= 1:
204 raise ValueError("DeepSeek sparse-attention CP member requires an active CPContext")
205 if self.kv_cp_size != context.size:
206 raise ValueError("kv_cp_size must equal the bound CPContext size")
207 if self._cp_context is not None and self._cp_context.mesh is not context.mesh:
208 raise ValueError("DeepSeek sparse-attention CP member already belongs to another mesh")
209 super().bind_parallel(binding)
210 self._cp_context = context
211
212 def prepare_key_bank(
213 self, index_states: tuple[torch.Tensor, ...], attention_states: tuple[torch.Tensor, ...],
214 metadata: CPSparseAttentionSequenceMetadata,
215 ) -> tuple[tuple[torch.Tensor, ...], tuple[torch.Tensor, ...]]:
216 """Gather three banks in fixed order and consume their causal prefixes.
217
218 All readiness receipts belong to this invocation. The existing gather
219 adjoint sums consumers into each source shard, including the zero
220 gradients from unused suffix tokens.
221
222 Args:
223 index_states: Local indexer query, key and weight tensors.
224 attention_states: Local attention query, latent KV and rotary tensors.
225 metadata: Compact Q/K endpoints and ranges for this CP rank.
226
227 Returns:
228 Indexer and attention operands with compacted global key banks.
229 """
230 return _gather_key_banks(self._cp_context, self.cp_comm_overlap, index_states, attention_states, metadata)
231
232 def exchange_attention(self, inputs: SparseAttentionInputs) -> SparseAttentionInputs:
233 """Return ready key banks without taking ownership of the attention algorithm.
234
235 Args:
236 inputs: Invocation-local DSA states and compact sequence metadata.
237
238 Returns:
239 The same states with gathered and selected key banks.
240 """
241 index_states, attention_states = self.prepare_key_bank(
242 inputs.index_states, inputs.attention_states, inputs.metadata,
243 )
244 return SparseAttentionInputs(index_states, attention_states, inputs.metadata, inputs.use_dense)
245
246 def preflight_attention(
247 self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None,
248 past_key_values: Any | None, position_ids: torch.Tensor | None,
249 actual_seq_len: torch.Tensor | Sequence[int] | None,
250 kwargs: dict[str, Any], *, use_dense: bool,
251 ) -> SparseAttentionSequenceMetadata:
252 """Validate every rank's packed geometry before any operand collective.
253
254 Args:
255 hidden_states: Local batch-major activation shard.
256 attention_mask: Optional Transformers causal-mask carrier.
257 past_key_values: Unsupported KV cache input.
258 position_ids: Optional local or global position IDs.
259 actual_seq_len: Global cumulative TND document endpoints.
260 kwargs: Other supported packed-sequence aliases.
261 use_dense: Whether the current training stage uses dense warm-up.
262
263 Returns:
264 This rank's compact local Q/K endpoints and key ranges.
265 """
266 del use_dense
267 if self._cp_context is None:
268 raise ValueError("DeepSeek sparse-attention CP member must be bound before execution")
269 self._validate_forward_inputs(hidden_states, attention_mask, past_key_values, position_ids, kwargs)
270 return build_cp_sequence_metadata(
271 batch_size=hidden_states.shape[0], local_seq_len=hidden_states.shape[1],
272 device=hidden_states.device, cp_size=self._cp_context.size, cp_rank=self._cp_context.rank,
273 actual_seq_len=actual_seq_len, kwargs=kwargs,
274 )