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"""DeepSeek sparse-attention implementations and shared projection mathematics."""
16
17from __future__ import annotations
18
19from collections.abc import Mapping, Sequence
20from dataclasses import dataclass
21import math
22from typing import Any
23
24import torch
25import torch.distributed._functional_collectives as funcol
26from torch import nn
27
28from hyper_parallel.components.checkpoint import ConcatenateWithSections
29from hyper_parallel.components.checkpoint.weight_conversion import WeightConverter
30from hyper_parallel.components.losses.aux_loss import aux_loss_auto_scale
31from hyper_parallel.components.functional.dsa_indexer import dsa_indexer
32from hyper_parallel.components.functional.dsa_kl_loss import dsa_kl_loss
33from hyper_parallel.components.functional.dsa_sparse_attention import dsa_sparse_attention
34from hyper_parallel.components.functional.npu_fusion_attention import resolve_packed_sequence_lengths
35from hyper_parallel.distributed.module_binding import ParallelBinding
36
37
38@dataclass(frozen=True)
39class SparseAttentionSequenceMetadata:
40 """Kernel endpoints and the consumed KV prefix for one invocation."""
41
42 kv_prefix_length: int
43 query_ends: torch.Tensor
44 key_ends: torch.Tensor
45
46 @property
47 def sequence_lengths(self) -> tuple[torch.Tensor, torch.Tensor]:
48 """Return cumulative int32 Q/K endpoints for the existing CANN kernels."""
49 return self.query_ends, self.key_ends
50
51 @classmethod
52 def build(
53 cls, *, batch_size: int, local_seq_len: int, device: torch.device,
54 actual_seq_len: torch.Tensor | Sequence[int] | None = None,
55 kwargs: Mapping[str, Any] | None = None,
56 ) -> SparseAttentionSequenceMetadata:
57 """Resolve local cumulative endpoints through the shared packed parser.
58
59 Args:
60 batch_size: Number of batch-major rows.
61 local_seq_len: Token count per row.
62 device: Kernel metadata device.
63 actual_seq_len: Cumulative packed endpoints without leading zero.
64 kwargs: Supported packed aliases, including packed_seq_params.
65 """
66 total = batch_size * local_seq_len
67 packed = dict(kwargs or {})
68 if actual_seq_len is not None:
69 packed["actual_seq_len"] = actual_seq_len
70 queries, keys = resolve_packed_sequence_lengths(packed, total, total)
71 if queries is None:
72 queries = keys = [(row + 1) * local_seq_len for row in range(batch_size)]
73 if len(queries) != len(keys):
74 raise ValueError("Sparse attention requires the same number of packed Q and KV documents")
75 return cls(
76 local_seq_len,
77 torch.tensor(queries, dtype=torch.int32, device=device),
78 torch.tensor(keys, dtype=torch.int32, device=device),
79 )
80
81
82def _apply_attention_rope(
83 query: torch.Tensor,
84 key: torch.Tensor,
85 position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
86 *,
87 interleaved: bool,
88) -> tuple[torch.Tensor, torch.Tensor]:
89 """Apply the configured RoPE convention to an attention query/key pair."""
90 if position_embeddings is None:
91 return query, key
92 # The rotary backend imports torch_npu; defer it until positional math is requested.
93 from hyper_parallel.components.functional import ( # pylint: disable=import-outside-toplevel
94 apply_rotary_pos_emb, apply_rotary_pos_emb_interleave,
95 )
96
97 cos, sin = position_embeddings
98 rotary_op = apply_rotary_pos_emb_interleave if interleaved else apply_rotary_pos_emb
99 return rotary_op(query, key, cos, sin, unsqueeze_dim=2)
100
101
102def _apply_index_rope(
103 query: torch.Tensor,
104 key: torch.Tensor,
105 position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
106 *,
107 rope_head_dim: int,
108 index_head_dim: int,
109 interleaved: bool,
110) -> tuple[torch.Tensor, torch.Tensor]:
111 """Apply RoPE to the rotary portion of an indexer query/key pair."""
112 if position_embeddings is None:
113 return query, key
114 # The rotary backend is optional for construction and CPU metadata/projection tests.
115 from hyper_parallel.components.functional import ( # pylint: disable=import-outside-toplevel
116 apply_rotary_pos_emb, apply_rotary_pos_emb_interleave,
117 )
118
119 cos, sin = position_embeddings
120 split_sizes = (rope_head_dim, index_head_dim - rope_head_dim)
121 query_rot, query_pass = torch.split(query, split_sizes, dim=-1)
122 key_rot, key_pass = torch.split(key, split_sizes, dim=-1)
123 rotary_op = apply_rotary_pos_emb_interleave if interleaved else apply_rotary_pos_emb
124 query_rot, key_rot = rotary_op(query_rot, key_rot, cos, sin, unsqueeze_dim=2)
125 return torch.cat((query_rot, query_pass), dim=-1), torch.cat((key_rot, key_pass), dim=-1)
126
127
128def _absorb_query_projection(
129 query: torch.Tensor,
130 key_up_weight: torch.Tensor,
131 *,
132 num_heads: int,
133 batch_size: int,
134 seq_length: int,
135 input_dim: int,
136 output_dim: int,
137) -> torch.Tensor:
138 """Absorb the key up-projection weight into query states."""
139 query = query.permute(2, 0, 1, 3).reshape(num_heads, batch_size * seq_length, input_dim)
140 query = torch.bmm(query, key_up_weight).view(num_heads, batch_size, seq_length, output_dim)
141 return query.permute(1, 2, 0, 3)
142
143
144def _restore_attention_projection(
145 output: torch.Tensor,
146 value_up_weight: torch.Tensor,
147 *,
148 num_heads: int,
149 batch_size: int,
150 seq_length: int,
151 kv_lora_rank: int,
152 value_head_dim: int,
153) -> torch.Tensor:
154 """Apply the absorbed value up-projection and restore the hidden layout."""
155 output = output[..., :kv_lora_rank]
156 output = output.permute(2, 0, 1, 3).reshape(num_heads, batch_size * seq_length, kv_lora_rank)
157 output = torch.bmm(output, value_up_weight)
158 return output.view(num_heads, batch_size, seq_length, value_head_dim).permute(1, 2, 0, 3).reshape(
159 batch_size, seq_length, -1
160 )
161
162
163def prepare_indexer_teacher(
164 query: torch.Tensor, key: torch.Tensor,
165 query_rope: torch.Tensor, key_rope: torch.Tensor,
166 maximum: torch.Tensor, total: torch.Tensor,
167) -> tuple[torch.Tensor, ...]:
168 """Detach the supplied teacher tensors without changing their local layout.
169
170 Args:
171 query: Main-attention TND query.
172 key: Dense per-head key or sparse shared latent key in TND.
173 query_rope: TND query positional band.
174 key_rope: TND key positional band.
175 maximum: Dense N,T,1 or sparse 1,T,N softmax maximum.
176 total: Corresponding softmax exponential sum.
177
178 Returns:
179 Detached Q, K, Q-rope, K-rope, maximum and sum for the existing KL kernel.
180 """
181 return tuple(tensor.detach() for tensor in (query, key, query_rope, key_rope, maximum, total))
182
183
184@dataclass(frozen=True)
185class SparseAttentionInputs:
186 """Invocation-local operands and the resolved dense/sparse training stage."""
187
188 index_states: tuple[torch.Tensor, ...]
189 attention_states: tuple[torch.Tensor, ...]
190 metadata: SparseAttentionSequenceMetadata
191 use_dense: bool
192
193
194def _dense_flash_attention(
195 module: nn.Module,
196 query: torch.Tensor,
197 key: torch.Tensor,
198 value: torch.Tensor,
199 sequence_lengths: tuple[torch.Tensor, torch.Tensor],
200 *,
201 need_stats: bool,
202) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
203 """Run one TND FA and return dense-indexer statistics."""
204 query_ends, key_ends = (lengths.tolist() for lengths in sequence_lengths)
205 q_flat, k_flat, v_flat = (tensor.flatten(0, 1) for tensor in (query, key, value))
206 num_heads = q_flat.shape[1]
207 causal_mask = torch.ones((2048, 2048), dtype=torch.bool, device=query.device).triu(diagonal=1)
208 import torch_npu # pylint: disable=import-outside-toplevel
209
210 result = torch_npu.npu_fusion_attention(
211 q_flat.contiguous(), k_flat.contiguous(), v_flat.contiguous(), num_heads, "TND",
212 pse=None, padding_mask=None, atten_mask=causal_mask, scale=module.scaling,
213 pre_tockens=getattr(module, "pre_tockens", 1048576),
214 next_tockens=getattr(module, "next_tockens", 0), keep_prob=1.0, inner_precise=0,
215 actual_seq_qlen=query_ends, actual_seq_kvlen=key_ends, sparse_mode=3,
216 )
217 output = result[0].reshape(*query.shape[:3], value.shape[-1])
218 if not need_stats:
219 return output, None, None
220
221 # TND FA stores each packed segment as [head, token, 8], while exposing a
222 # physical [token, head, 8] shape. Dense KL consumes [head, token, 1].
223 statistics = []
224 starts = [0, *query_ends[:-1]]
225 for statistic in result[1:3]:
226 rows = statistic.reshape(-1, statistic.shape[-1])
227 segments = [
228 rows[start * num_heads : end * num_heads].reshape(
229 num_heads, end - start, statistic.shape[-1]
230 )[..., :1]
231 for start, end in zip(starts, query_ends)
232 ]
233 statistics.append(torch.cat(segments, dim=1).detach())
234 return output, statistics[0], statistics[1]
235
236
237def _deepseek_v32_dense_attention(
238 module: nn.Module,
239 index_states: tuple[torch.Tensor, ...],
240 attention_states: tuple[torch.Tensor, ...],
241 sequence_lengths: tuple[torch.Tensor, torch.Tensor],
242) -> torch.Tensor:
243 """Run unabsorbed MLA FA and the fused dense indexer KL on local states."""
244 query, compressed_kv, query_rope, key_rope = attention_states
245 projected_kv = module.kv_b_proj(compressed_kv.squeeze(2)).view(
246 *compressed_kv.shape[:2], query.shape[2], module.qk_nope_head_dim + module.v_head_dim,
247 )
248 key, value = projected_kv.split((module.qk_nope_head_dim, module.v_head_dim), dim=-1)
249 key_rope = key_rope.expand(-1, -1, query.shape[2], -1)
250 need_stats = bool(module.training and not module.freeze_dsa and module.dsa_loss_coeff)
251 output, maximum, total = _dense_flash_attention(
252 module, torch.cat((query, query_rope), dim=-1), torch.cat((key, key_rope), dim=-1),
253 value, sequence_lengths, need_stats=need_stats,
254 )
255 if need_stats:
256 # Dense CANN operators are optional for sparse and Omni execution.
257 # pylint: disable=import-outside-toplevel
258 from hyper_parallel.components.functional.dsa_dense import (
259 dsa_dense_indexer_kl_loss,
260 dsa_dense_indexer_lse,
261 )
262 # pylint: enable=import-outside-toplevel
263
264 query_lengths, key_lengths = sequence_lengths
265 index_query, index_key, weights = (tensor.flatten(0, 1) for tensor in index_states)
266 indexer_stats = dsa_dense_indexer_lse(
267 index_query, index_key, weights, query_lengths=query_lengths, key_lengths=key_lengths,
268 )
269 teacher_query, teacher_key, teacher_qrope, teacher_krope, maximum, total = module.prepare_teacher(
270 query.flatten(0, 1), key.flatten(0, 1),
271 query_rope.flatten(0, 1), key_rope.flatten(0, 1), maximum, total,
272 dense=True,
273 )
274 loss = dsa_dense_indexer_kl_loss(
275 index_query, index_key, weights, teacher_query, teacher_key,
276 maximum, total, indexer_stats, scale=module.scaling,
277 query_rope=teacher_qrope, key_rope=teacher_krope,
278 query_lengths=query_lengths, key_lengths=key_lengths, loss_coefficient=module.dsa_loss_coeff,
279 )
280 output = aux_loss_auto_scale(output, loss)
281 return output
282
283
284class DeepseekSparseAttentionModule(nn.Module):
285 """DeepSeek-V3.2 sparse attention with native configuration and source-module construction.
286
287 It supports causal training and packed sequences. Packed boundaries must
288 be supplied through ``actual_seq_len``. ``attention_mask`` is a compatibility
289 argument whose values are not consumed; causal masking comes from DSA kernels
290 and sequence metadata. Padding/custom masks, dropout, and KV cache are unsupported.
291 """
292
293 def bind_parallel(self, binding: ParallelBinding) -> None:
294 """Borrow the model's existing TP group for teacher assembly."""
295 mesh = binding.mesh_binding.mesh_context.device_mesh
296 names = getattr(mesh, "mesh_dim_names", None)
297 if self._tp_size > 1 or (isinstance(names, (list, tuple)) and "tp" in names):
298 tp = binding.mesh_binding.axis_mesh("tp")
299 bound_size = tp.size()
300 if self._tp_size not in (1, bound_size):
301 raise ValueError(
302 f"Sparse-attention TP size {self._tp_size} does not match bound mesh size {bound_size}"
303 )
304 self._tp_size = bound_size
305 self._tp_group = tp.get_group() if bound_size > 1 else None
306
307 def _gather_tp(self, tensor: torch.Tensor, dim: int) -> torch.Tensor:
308 """Concatenate one head shard across the borrowed TP group."""
309 if self._tp_size == 1:
310 return tensor
311 if self._tp_group is None:
312 raise RuntimeError("parallel DeepSeek sparse attention must be bound before forward")
313 gathered = funcol.all_gather_tensor(tensor.contiguous(), dim, self._tp_group)
314 return funcol.wait_tensor(gathered)
315
316 def gather_teacher_heads(
317 self,
318 query: torch.Tensor,
319 key: torch.Tensor,
320 query_rope: torch.Tensor,
321 key_rope: torch.Tensor,
322 maximum: torch.Tensor,
323 total: torch.Tensor,
324 *,
325 dense: bool,
326 ) -> tuple[torch.Tensor, ...]:
327 """Assemble the global-head detached teacher expected by the fused KL op."""
328 query = self._gather_tp(query, 1)
329 query_rope = self._gather_tp(query_rope, 1)
330 if dense:
331 key = self._gather_tp(key, 1)
332 key_rope = self._gather_tp(key_rope, 1)
333 stats_dim = 0 if dense else 2
334 maximum = self._gather_tp(maximum, stats_dim)
335 total = self._gather_tp(total, stats_dim)
336 return query, key, query_rope, key_rope, maximum, total
337
338 def prepare_teacher(
339 self,
340 query: torch.Tensor,
341 key: torch.Tensor,
342 query_rope: torch.Tensor,
343 key_rope: torch.Tensor,
344 maximum: torch.Tensor,
345 total: torch.Tensor,
346 *,
347 dense: bool,
348 ) -> tuple[torch.Tensor, ...]:
349 """Prepare full-head detached operands for the indexer KL."""
350 teacher = prepare_indexer_teacher(query, key, query_rope, key_rope, maximum, total)
351 return self.gather_teacher_heads(*teacher, dense=dense)
352
353 def _align_tokens(self, tensor: torch.Tensor, dim: int, tokens: int) -> torch.Tensor:
354 """Gather sequence-sharded metadata when attention inputs are TP-gathered."""
355 local = tensor.shape[dim]
356 if local == tokens:
357 return tensor
358 if local * self._tp_size != tokens:
359 raise ValueError("Position length must match local or TP-gathered tokens")
360 return self._gather_tp(tensor, dim % tensor.ndim)
361
362 def prepare_positions(
363 self,
364 hidden_states: torch.Tensor,
365 position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
366 ) -> tuple[torch.Tensor, torch.Tensor] | None:
367 """Align position tables with the tokens consumed by attention."""
368 if position_embeddings is None:
369 return None
370 cosine, sine = position_embeddings
371 return tuple(self._align_tokens(table, -2, hidden_states.shape[1]) for table in (cosine, sine))
372
373 def prepare_position_ids(
374 self,
375 hidden_states: torch.Tensor,
376 position_ids: torch.Tensor | None,
377 ) -> torch.Tensor | None:
378 """Align optional position IDs with TP-gathered attention tokens."""
379 if position_ids is None:
380 return None
381 if position_ids.ndim != 2:
382 raise ValueError("position_ids must have BS layout")
383 return self._align_tokens(position_ids, -1, hidden_states.shape[1])
384
385 def _initialize_dimensions(self, module: nn.Module | None) -> None:
386 """Read main-attention and indexer dimensions from a source or config."""
387 config = self.config
388 indexer = getattr(module, "indexer", None)
389 self.layer_idx = getattr(
390 module, "layer_idx", getattr(module, "layer_number", getattr(config, "layer_idx", None)),
391 )
392 self.num_heads = getattr(module, "num_heads", config.num_attention_heads)
393 self.q_lora_rank = getattr(module, "q_lora_rank", config.q_lora_rank)
394 self.kv_lora_rank = getattr(module, "kv_lora_rank", config.kv_lora_rank)
395 self.qk_rope_head_dim = getattr(module, "qk_rope_head_dim", config.qk_rope_head_dim)
396 self.qk_nope_head_dim = getattr(module, "qk_nope_head_dim", config.qk_nope_head_dim)
397 self.v_head_dim = getattr(module, "v_head_dim", config.v_head_dim)
398 self.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
399 if self.q_lora_rank is None:
400 raise ValueError("DeepseekSparseAttention requires the Q-LoRA projection path")
401 self.index_head_dim = getattr(indexer, "head_dim", config.index_head_dim)
402 self.num_index_heads = getattr(
403 indexer,
404 "n_heads",
405 getattr(config, "index_n_heads", getattr(config, "index_num_attention_heads", None)),
406 )
407 if self.num_index_heads is None:
408 raise ValueError("DeepseekSparseAttention requires the number of indexer heads")
409 self.index_topk = getattr(indexer, "index_topk", config.index_topk)
410
411 def _initialize_options(self, module: nn.Module | None) -> None:
412 """Read sparse attention options while preserving source scaling and RoPE conventions."""
413 config = self.config
414 self.scaling = getattr(module, "scaling", None)
415 if self.scaling is None:
416 self.scaling = self._config_scaling(config)
417 attention_dropout = getattr(module, "attention_dropout", getattr(config, "attention_dropout", 0.0))
418 if isinstance(attention_dropout, nn.Dropout):
419 attention_dropout = attention_dropout.p
420 if attention_dropout != 0.0:
421 raise ValueError(
422 "DeepseekSparseAttention requires attention_dropout=0 because "
423 "the sparse-attention operator does not apply dropout"
424 )
425 source_rotary_interleaved = getattr(module, "rotary_interleaved", getattr(config, "rotary_interleaved", None))
426 if source_rotary_interleaved is None:
427 source_rotary_interleaved = getattr(config, "rope_interleave", None)
428 if source_rotary_interleaved is None:
429 source_rotary_interleaved = getattr(config, "rope_interleaved", None)
430 self.rotary_interleaved = bool(True if source_rotary_interleaved is None else source_rotary_interleaved)
431 self.index_rotary_interleaved = bool(
432 getattr(
433 getattr(module, "indexer", None), "rotary_interleaved",
434 getattr(config, "index_rope_interleaved", False),
435 )
436 )
437 self.dsa_loss_coeff = getattr(config, "dsa_loss_coeff", 0.0)
438 self.freeze_dsa = bool(getattr(config, "freeze_DSA", getattr(config, "freeze_dsa", False)))
439 self.dsa_dense_warm_up = bool(
440 getattr(module, "dsa_dense_warm_up", getattr(config, "dsa_dense_warm_up", False))
441 )
442 if getattr(module, "param_sink_number", getattr(config, "param_sink_number", 0)) > 0:
443 raise ValueError("DeepseekSparseAttention does not support the parameter-sink path")
444 if getattr(module, "use_mome", getattr(config, "use_mome", False)):
445 raise ValueError("DeepseekSparseAttention does not support the MOME path")
446
447 def _config_scaling(self, config: Any) -> float:
448 """Apply the source-compatible YaRN factor for native construction."""
449 scaling = self.qk_head_dim**-0.5
450 rope = getattr(config, "rope_parameters", None) or getattr(config, "rope_scaling", None) or {}
451 if rope.get("rope_type", rope.get("type", "default")) != "default" and rope.get("mscale_all_dim", 0):
452 factor = rope["factor"]
453 mscale = 1.0 if factor <= 1 else 1.0 + 0.1 * rope["mscale_all_dim"] * math.log(factor)
454 scaling *= mscale * mscale
455 return getattr(config, "scaling", scaling)
456
457 def _initialize_config_layers(self, config: Any) -> None:
458 """Allocate the native parameter tree without constructing a Transformers model."""
459 dtype = getattr(config, "dtype", None)
460 if isinstance(dtype, str):
461 dtype = getattr(torch, dtype.removeprefix("torch."))
462 factory_kwargs = {"device": getattr(config, "device", None), "dtype": dtype}
463 bias = getattr(config, "attention_bias", False)
464 self._q_latent_output_size = self.q_lora_rank
465 self._kv_latent_output_size = self.kv_lora_rank + self.qk_rope_head_dim
466 self.linear_qkv = nn.Linear(
467 config.hidden_size, self._q_latent_output_size + self._kv_latent_output_size,
468 bias=bias, **factory_kwargs,
469 )
470 eps = getattr(config, "rms_norm_eps", 1e-6)
471 self.q_a_layernorm = nn.RMSNorm(self.q_lora_rank, eps=eps, **factory_kwargs)
472 self.kv_a_layernorm = nn.RMSNorm(self.kv_lora_rank, eps=eps, **factory_kwargs)
473 self.q_b_proj = nn.Linear(
474 self.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False, **factory_kwargs,
475 )
476 self.kv_b_proj = nn.Linear(
477 self.kv_lora_rank, self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
478 bias=False, **factory_kwargs,
479 )
480 self.o_proj = nn.Linear(
481 self.num_heads * self.v_head_dim, config.hidden_size, bias=bias, **factory_kwargs,
482 )
483 self.indexer = nn.Module()
484 self.indexer.n_heads, self.indexer.head_dim = self.num_index_heads, self.index_head_dim
485 self.indexer.index_topk = self.index_topk
486 self.indexer.wq_b = nn.Linear(
487 self.q_lora_rank, self.num_index_heads * self.index_head_dim, bias=False, **factory_kwargs,
488 )
489 self.indexer.wk = nn.Linear(config.hidden_size, self.index_head_dim, bias=False, **factory_kwargs)
490 self.indexer.k_norm = nn.LayerNorm(self.index_head_dim, eps=1e-6, **factory_kwargs)
491 self.indexer.weights_proj = nn.Linear(config.hidden_size, self.num_index_heads, bias=False, **factory_kwargs)
492
493 def _initialize_source_layers(self, module: nn.Module) -> None:
494 """Fuse loaded down-projection values and retain the remaining Parameters."""
495 q_a, kv_a = module.q_a_proj, module.kv_a_proj_with_mqa
496 self._q_latent_output_size, self._kv_latent_output_size = q_a.out_features, kv_a.out_features
497 can_fuse = (
498 q_a.in_features == kv_a.in_features
499 and q_a.weight.requires_grad == kv_a.weight.requires_grad
500 and q_a.weight.device == kv_a.weight.device
501 and q_a.weight.dtype == kv_a.weight.dtype
502 and (q_a.bias is None) == (kv_a.bias is None)
503 and (q_a.bias is None or q_a.bias.requires_grad == kv_a.bias.requires_grad)
504 )
505 if not can_fuse:
506 raise ValueError("Q and KV latent projections cannot be represented by one fused projection")
507 self.linear_qkv = nn.Linear(
508 q_a.in_features, q_a.out_features + kv_a.out_features, bias=q_a.bias is not None,
509 device=q_a.weight.device, dtype=q_a.weight.dtype,
510 )
511 self.linear_qkv.weight.requires_grad_(q_a.weight.requires_grad)
512 if self.linear_qkv.bias is not None:
513 self.linear_qkv.bias.requires_grad_(q_a.bias.requires_grad)
514 if not q_a.weight.is_meta:
515 with torch.no_grad():
516 self.linear_qkv.weight.copy_(torch.cat((q_a.weight, kv_a.weight), dim=0))
517 if self.linear_qkv.bias is not None:
518 self.linear_qkv.bias.copy_(torch.cat((q_a.bias, kv_a.bias), dim=0))
519 self.linear_qkv._is_hf_initialized = True # pylint: disable=protected-access
520 for name in ("q_a_layernorm", "kv_a_layernorm", "q_b_proj"):
521 setattr(self, name, getattr(module, name))
522 if module.kv_b_proj.bias is not None:
523 raise ValueError("Absorbed KV projection requires a bias-free Linear")
524 self.kv_b_proj = module.kv_b_proj
525 self.o_proj, self.indexer = module.o_proj, module.indexer
526
527 def _reuse_local_member(self, module: DeepseekSparseAttentionModule) -> None:
528 """Promote a loaded unbound member without re-fusing or reinitializing values."""
529 if getattr(module, "_hp_parallel_binding", None) is not None:
530 raise ValueError("DeepSeek-V3.2 promotion must precede parallel binding and FSDP")
531 fields = (
532 "config", "layer_idx", "num_heads", "q_lora_rank", "kv_lora_rank",
533 "qk_rope_head_dim", "qk_nope_head_dim", "v_head_dim", "qk_head_dim", "index_head_dim",
534 "num_index_heads", "index_topk", "scaling", "rotary_interleaved", "index_rotary_interleaved",
535 "dsa_loss_coeff", "freeze_dsa", "dsa_dense_warm_up",
536 "_q_latent_output_size", "_kv_latent_output_size", "_tp_size", "_tp_group",
537 )
538 for name in fields:
539 setattr(self, name, getattr(module, name))
540 for name in ("linear_qkv", "q_a_layernorm", "kv_a_layernorm", "q_b_proj", "kv_b_proj", "o_proj", "indexer"):
541 setattr(self, name, getattr(module, name))
542
543 def __init__(
544 self, *, config: Any = None, module: nn.Module | None = None,
545 module_fqn: str = "", context: Mapping[str, Any] | None = None,
546 kv_cp_size: int = 1, kv_cp_strategy: str = "allgather",
547 cp_comm_overlap: bool = False, dense_warmup: bool | None = None,
548 ) -> None:
549 """Construct native sparse attention parameters, convert a source, or promote a local member.
550
551 Args:
552 config: Native dimensions/options, exclusive with module; optional dtype/device
553 select parameter placement. Otherwise the active Torch defaults apply.
554 module: Source attention or an unbound concrete family member.
555 module_fqn: Source path supplied by replacement.
556 context: Logical construction context, without execution resources.
557 kv_cp_size: KV domain size retained for deferred family promotion.
558 kv_cp_strategy: KV transport, currently allgather.
559 cp_comm_overlap: Submit key-bank gathers asynchronously when enabled.
560 dense_warmup: None follows the mutable training stage; bool pins it.
561 """
562 super().__init__()
563 del module_fqn
564 if (config is None) == (module is None):
565 raise ValueError("DeepSeek-V3.2 sparse attention requires exactly one of config or module")
566 if not isinstance(kv_cp_size, int) or isinstance(kv_cp_size, bool) or kv_cp_size < 1:
567 raise ValueError("kv_cp_size must be a positive integer")
568 if kv_cp_strategy != "allgather":
569 raise ValueError("DeepSeek sparse attention supports only kv_cp_strategy='allgather'")
570 self._config_initialization = module is None or getattr(module, "_config_initialization", False)
571 self._tp_size = (context or {}).get("tp_size", 1)
572 self._tp_group = None
573 self.kv_cp_size, self.kv_cp_strategy = kv_cp_size, kv_cp_strategy
574 self.cp_comm_overlap = cp_comm_overlap
575 self._dense_warmup_override = dense_warmup
576 if isinstance(module, DeepseekSparseAttentionModule):
577 self._reuse_local_member(module)
578 else:
579 self.config = config if module is None else module.config
580 if hasattr(self.config, "indexer_types"):
581 raise TypeError(
582 "DeepSeek-V3.2 sparse attention does not support shared-indexer or three-value output contracts"
583 )
584 self._initialize_dimensions(module)
585 self._initialize_options(module)
586 if module is None:
587 self._initialize_config_layers(config)
588 else:
589 self._initialize_source_layers(module)
590 if module is not None:
591 self.train(module.training)
592
593 def reset_parameters(self) -> None:
594 """Initialize native/meta parameters without resetting converted source weights."""
595 if not self._config_initialization:
596 return
597 for child in (
598 self.linear_qkv, self.q_a_layernorm, self.kv_a_layernorm, self.q_b_proj,
599 self.kv_b_proj, self.o_proj, self.indexer.wq_b, self.indexer.wk,
600 self.indexer.k_norm, self.indexer.weights_proj,
601 ):
602 child.reset_parameters()
603
604 def make_transforms(self) -> list[WeightConverter]:
605 """Describe reversible source-checkpoint to high-performance conversion."""
606 if self._config_initialization:
607 return []
608 transforms: list[WeightConverter] = [
609 WeightConverter(
610 source_patterns=[
611 "q_a_proj.weight",
612 "kv_a_proj_with_mqa.weight",
613 ],
614 target_patterns="linear_qkv.weight",
615 operations=[
616 ConcatenateWithSections(
617 sections=(
618 self._q_latent_output_size,
619 self._kv_latent_output_size,
620 ),
621 dim=0,
622 )
623 ],
624 ),
625 ]
626 if self.linear_qkv.bias is not None:
627 transforms.insert(
628 1,
629 WeightConverter(
630 source_patterns=["q_a_proj.bias", "kv_a_proj_with_mqa.bias"],
631 target_patterns="linear_qkv.bias",
632 operations=[
633 ConcatenateWithSections(
634 sections=(
635 self._q_latent_output_size,
636 self._kv_latent_output_size,
637 ),
638 dim=0,
639 )
640 ],
641 ),
642 )
643 return transforms
644
645 @staticmethod
646 def _invalid_position_ids(
647 position_ids: torch.Tensor | None,
648 batch_size: int,
649 seq_length: int,
650 ) -> bool:
651 """Return whether position IDs violate the supported dense layout."""
652 if position_ids is None:
653 return False
654 if position_ids.ndim != 2:
655 return True
656 return position_ids.shape[0] not in (1, batch_size) or position_ids.shape[1] != seq_length
657
658 def _validate_forward_inputs(
659 self,
660 hidden_states: torch.Tensor,
661 attention_mask: torch.Tensor | None,
662 past_key_values: Any | None,
663 position_ids: torch.Tensor | None,
664 kwargs: dict[str, Any],
665 ) -> None:
666 """Validate inputs supported by the DeepSeek sparse-attention path."""
667 del attention_mask
668 if hidden_states.ndim != 3:
669 raise ValueError("DeepSeek-V3.2 hidden_states must have shape [batch, sequence, hidden]")
670 batch_size, seq_length = hidden_states.shape[:-1]
671 if past_key_values is not None:
672 raise NotImplementedError("DeepseekSparseAttention does not support KV cache")
673 if DeepseekSparseAttentionModule._invalid_position_ids(position_ids, batch_size, seq_length):
674 raise ValueError("position_ids must have shape [1 or batch_size, sequence_length]")
675 if kwargs.pop("output_attentions", False):
676 raise NotImplementedError("DeepseekSparseAttention does not expose attention weights")
677
678 def _project_attention_states(
679 self, hidden_states: torch.Tensor, *, use_dense: bool = False,
680 ) -> tuple[torch.Tensor, tuple[torch.Tensor, ...]]:
681 """Project local states inside the attention/block FSDP boundary."""
682 batch_size, seq_length = hidden_states.shape[:-1]
683 q_latent, latent_kv, key_rope = torch.split(
684 self.linear_qkv(hidden_states),
685 (self.q_lora_rank, self.kv_lora_rank, self.qk_rope_head_dim), dim=-1,
686 )
687 q_resid = self.q_a_layernorm(q_latent)
688 projected = self.q_b_proj(q_resid)
689 heads = projected.shape[-1] // self.qk_head_dim
690 query, query_rope = projected.view(
691 batch_size, seq_length, heads, self.qk_head_dim,
692 ).split((self.qk_nope_head_dim, self.qk_rope_head_dim), dim=-1)
693 if not use_dense:
694 weight = self.kv_b_proj.weight.view(
695 heads, self.qk_nope_head_dim + self.v_head_dim, self.kv_lora_rank,
696 )
697 query = _absorb_query_projection(
698 query, weight[:, :self.qk_nope_head_dim], num_heads=heads,
699 batch_size=batch_size, seq_length=seq_length,
700 input_dim=self.qk_nope_head_dim, output_dim=self.kv_lora_rank,
701 )
702 latent_kv = self.kv_a_layernorm(latent_kv).view(batch_size, seq_length, 1, self.kv_lora_rank)
703 key_rope = key_rope.view(batch_size, seq_length, 1, self.qk_rope_head_dim)
704 return q_resid, (query, latent_kv, query_rope, key_rope)
705
706 def _project_index_states(
707 self,
708 hidden_states: torch.Tensor,
709 q_resid: torch.Tensor,
710 position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
711 ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
712 """Build indexer query, key, and merge-weight states."""
713 batch_size, seq_length = hidden_states.shape[:-1]
714 index_query = self.indexer.wq_b(q_resid.detach()).view(
715 batch_size, seq_length, self.num_index_heads, self.index_head_dim
716 )
717 index_key = self.indexer.k_norm(self.indexer.wk(hidden_states.detach())).unsqueeze(2)
718 merge_weight = self.indexer.weights_proj(hidden_states.detach())
719 # Avoid intermediate low-precision rounding at the TopK boundary.
720 weight_scale = (self.num_index_heads * self.index_head_dim)**-0.5
721 merge_weight = (merge_weight.float() * weight_scale).to(merge_weight.dtype)
722 index_query, index_key = _apply_index_rope(
723 index_query,
724 index_key,
725 position_embeddings,
726 rope_head_dim=self.qk_rope_head_dim,
727 index_head_dim=self.index_head_dim,
728 interleaved=self.index_rotary_interleaved,
729 )
730 return index_query, index_key, merge_weight
731
732 def _apply_auxiliary_loss(
733 self,
734 attn_output: torch.Tensor,
735 index_states: tuple[torch.Tensor, torch.Tensor, torch.Tensor],
736 attention_states: tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor],
737 topk_indices: torch.Tensor,
738 softmax_stats: tuple[torch.Tensor, torch.Tensor],
739 actual_q_len: torch.Tensor,
740 actual_kv_len: torch.Tensor,
741 ) -> torch.Tensor:
742 """Attach the sparse attention KL auxiliary loss when training enables it."""
743 if not (self.training and not self.freeze_dsa and self.dsa_loss_coeff):
744 return attn_output
745 query_tnd, key_tnd, q_rot_tnd, k_rot_tnd = (
746 tensor.reshape(-1, tensor.shape[2], tensor.shape[3])
747 for tensor in attention_states
748 )
749 query_tnd, key_tnd, q_rot_tnd, k_rot_tnd, maximum, total = self.prepare_teacher(
750 query_tnd, key_tnd, q_rot_tnd, k_rot_tnd, *softmax_stats,
751 dense=False,
752 )
753 aux_loss = dsa_kl_loss(
754 *index_states, query_tnd, key_tnd,
755 topk_indices, maximum, total, q_rot_tnd, k_rot_tnd,
756 actual_q_len, actual_kv_len, self.scaling, self.dsa_loss_coeff,
757 backend="cann",
758 )
759 return aux_loss_auto_scale(attn_output, aux_loss)
760
761 def use_dense_attention(self) -> bool:
762 """Read the current training stage unless an explicit override pins it."""
763 return self.dsa_dense_warm_up if self._dense_warmup_override is None else self._dense_warmup_override
764
765 def preflight_attention(
766 self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None,
767 past_key_values: Any | None, position_ids: torch.Tensor | None,
768 actual_seq_len: torch.Tensor | Sequence[int] | None,
769 kwargs: dict[str, Any], *, use_dense: bool,
770 ) -> SparseAttentionSequenceMetadata:
771 """Validate local inputs and construct packed geometry before projection."""
772 del use_dense
773 self._validate_forward_inputs(hidden_states, attention_mask, past_key_values, position_ids, kwargs)
774 return SparseAttentionSequenceMetadata.build(
775 batch_size=hidden_states.shape[0], local_seq_len=hidden_states.shape[1],
776 device=hidden_states.device, actual_seq_len=actual_seq_len, kwargs=kwargs,
777 )
778
779 def prepare_attention(
780 self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
781 *, use_dense: bool,
782 ) -> tuple[tuple[torch.Tensor, ...], tuple[torch.Tensor, ...]]:
783 """Run projections and both independent RoPE conventions on local tokens."""
784 q_resid, states = self._project_attention_states(hidden_states, use_dense=use_dense)
785 query, latent_kv, query_rope, key_rope = states
786 query_rope, key_rope = _apply_attention_rope(
787 query_rope, key_rope, position_embeddings, interleaved=self.rotary_interleaved,
788 )
789 index_states = self._project_index_states(hidden_states, q_resid, position_embeddings)
790 return index_states, (query, latent_kv, query_rope, key_rope)
791
792 def prepare_attention_inputs(
793 self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
794 metadata: SparseAttentionSequenceMetadata, *, use_dense: bool,
795 ) -> SparseAttentionInputs:
796 """Prepare local operands while retaining one invocation's resolved mode."""
797 index_states, attention_states = self.prepare_attention(
798 hidden_states, position_embeddings, use_dense=use_dense,
799 )
800 return SparseAttentionInputs(index_states, attention_states, metadata, use_dense)
801
802 def exchange_attention(self, inputs: SparseAttentionInputs) -> SparseAttentionInputs:
803 """Return ready operands; local attention needs no sequence exchange."""
804 return inputs
805
806 def run_attention(
807 self, index_states: tuple[torch.Tensor, ...], attention_states: tuple[torch.Tensor, ...],
808 sequence_lengths: tuple[torch.Tensor, torch.Tensor], *, use_dense: bool,
809 ) -> torch.Tensor:
810 """Execute the shared dense/sparse kernel and restore local-head output."""
811 if use_dense:
812 return _deepseek_v32_dense_attention(
813 self, index_states, attention_states, sequence_lengths,
814 ).flatten(2)
815 topk, *flattened = dsa_indexer(
816 *index_states, *sequence_lengths, self.index_topk, backend="cann",
817 )
818 output, maximum, total = dsa_sparse_attention(
819 *attention_states, topk, self.scaling, *sequence_lengths, backend="cann",
820 )
821 output = self._apply_auxiliary_loss(
822 output, tuple(flattened), attention_states, topk, (maximum, total), *sequence_lengths,
823 )
824 heads = output.shape[2]
825 weight = self.kv_b_proj.weight.view(
826 heads, self.qk_nope_head_dim + self.v_head_dim, self.kv_lora_rank,
827 )
828 return _restore_attention_projection(
829 output, weight[:, self.qk_nope_head_dim:].transpose(1, 2), num_heads=heads,
830 batch_size=output.shape[0], seq_length=output.shape[1],
831 kv_lora_rank=self.kv_lora_rank, value_head_dim=self.v_head_dim,
832 )
833
834 def project_output(self, output: torch.Tensor) -> torch.Tensor:
835 """Run the output Linear before the shared TP boundary."""
836 return self.o_proj(output)
837
838 def forward(
839 self, hidden_states: torch.Tensor,
840 position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
841 attention_mask: torch.Tensor | None = None, past_key_values: Any | None = None,
842 position_ids: torch.Tensor | None = None,
843 actual_seq_len: torch.Tensor | Sequence[int] | None = None, **kwargs: Any,
844 ) -> tuple[torch.Tensor, None]:
845 """Run causal or packed sparse attention while retaining the Transformers output ABI."""
846 use_dense = self.use_dense_attention()
847 position_ids = self.prepare_position_ids(hidden_states, position_ids)
848 metadata = self.preflight_attention(
849 hidden_states, attention_mask, past_key_values, position_ids, actual_seq_len, kwargs,
850 use_dense=use_dense,
851 )
852 inputs = self.prepare_attention_inputs(
853 hidden_states, self.prepare_positions(hidden_states, position_embeddings), metadata, use_dense=use_dense,
854 )
855 inputs = self.exchange_attention(inputs)
856 output = self.run_attention(
857 inputs.index_states, inputs.attention_states, inputs.metadata.sequence_lengths, use_dense=inputs.use_dense,
858 )
859 del inputs
860 return self.project_output(output), None