Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / ops / impl / dsa_indexer_kl.py: 87%
171 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
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"""Compressed-key teacher KL loss for the DeepSeek V4.1 DSA Indexer."""
17from __future__ import annotations
19from collections.abc import Callable
20from functools import partial
21from typing import Any, Protocol
23import torch
25from hyper_parallel.components.functional.dsa_dense import dsa_dense_indexer_kl_loss, dsa_dense_indexer_lse
26from hyper_parallel.components.functional.dsa_kl_loss import dsa_kl_loss as fused_packed_kl
27from hyper_parallel.components.functional.sparse_lightning_indexer_kl_loss_grad import (
28 gather_selected_keys, sparse_lightning_indexer_kl_loss, validate_fused_kl_inputs,
29)
31from .._dependency import load_cann, require_package, require_symbol
32from .._dsa_layout import DsaQueryLayout, ReduceSum, packed_segments, selected_packed_keys, selected_packed_scores
33from ..registry import OpRegistry
34from ..spec import OpSpec
35from .dsa_indexer import indexer_native_only
38class DsaIndexerKlFn(Protocol):
39 """Return a scalar KL loss, differentiating only the student."""
41 def __call__(
42 self, x: torch.Tensor, index_key: torch.Tensor, merge_weight: torch.Tensor,
43 attention_query: torch.Tensor, compressed_key: torch.Tensor, topk_indices: torch.Tensor,
44 sinks: torch.Tensor, *, attention_scale: float, loss_coeff: float, query_chunk_size: int = 256,
45 reduce_sum: ReduceSum | None = None, layout: DsaQueryLayout | None = None,
46 ) -> torch.Tensor:
47 """Return the coefficient-scaled loss across all local query rows."""
50DSA_INDEXER_KL = OpSpec[DsaIndexerKlFn](config_key="dsa_indexer_kl", variant="compressed_teacher")
53class PackedDsaKlFn(Protocol):
54 """Distill the packed sparse attention distribution into the DSA indexer."""
56 def __call__(
57 self, x: torch.Tensor, index_key: torch.Tensor, merge_weight: torch.Tensor,
58 query: torch.Tensor, key: torch.Tensor, topk_indices: torch.Tensor,
59 softmax_max: torch.Tensor, softmax_sum: torch.Tensor, query_rope: torch.Tensor, key_rope: torch.Tensor,
60 query_ends: torch.Tensor, key_ends: torch.Tensor, scale: float, loss_coeff: float,
61 ) -> torch.Tensor:
62 """Return a token-mean KL loss with gradients on the three student inputs only."""
65DSA_PACKED_KL = OpSpec[PackedDsaKlFn](config_key="dsa_indexer_kl", variant="packed_sparse_teacher")
68class DenseDsaKlFn(Protocol):
69 """Distill unabsorbed MLA into the indexer over each packed document."""
71 def __call__(
72 self, x: torch.Tensor, index_key: torch.Tensor, weights: torch.Tensor, query: torch.Tensor, key: torch.Tensor,
73 maximum: torch.Tensor, total: torch.Tensor, query_rope: torch.Tensor, key_rope: torch.Tensor,
74 query_ends: torch.Tensor, key_ends: torch.Tensor, *, scale: float, loss_coeff: float,
75 ) -> torch.Tensor:
76 """Return the token-mean KL and differentiate the indexer inputs only."""
79DSA_DENSE_KL = OpSpec[DenseDsaKlFn](config_key="dsa_indexer_kl", variant="packed_dense_teacher")
82def _native_dense_kl(
83 x: torch.Tensor, index_key: torch.Tensor, weights: torch.Tensor, query: torch.Tensor, key: torch.Tensor,
84 maximum: torch.Tensor, total: torch.Tensor, query_rope: torch.Tensor, key_rope: torch.Tensor,
85 query_ends: torch.Tensor, key_ends: torch.Tensor, *, scale: float, loss_coeff: float,
86) -> torch.Tensor:
87 """Compute packed dense-teacher KL while differentiating only student inputs."""
88 del maximum, total
89 loss = x.new_zeros((), dtype=torch.float32)
90 with torch.autocast(device_type=x.device.type, enabled=False):
91 for qs, qe, ks, ke in packed_segments(query_ends, key_ends):
92 key_pos = torch.arange(ke - ks, device=x.device)
93 for start in range(qs, qe, 128):
94 end = min(start + 128, qe)
95 causal = torch.arange(start, end, device=x.device) - qe + ke - ks
96 valid = key_pos[None, :] <= causal[:, None]
97 with torch.no_grad():
98 logits = torch.einsum("thd,khd->thk", query[start:end].float(), key[ks:ke].float())
99 rotary = torch.einsum("thd,khd->thk", query_rope[start:end].float(), key_rope[ks:ke].float())
100 teacher = ((logits + rotary) * scale).masked_fill(~valid[:, None], -1.0e9)
101 target = teacher.softmax(-1).mean(1).masked_fill(~valid, 0.0)
102 student = (x[start:end].float() @ index_key[ks:ke, 0].float().T).relu()
103 student = (student * weights[start:end].float().unsqueeze(-1)).sum(dim=1)
104 student = student.masked_fill(~valid, -1.0e9)
105 loss = loss + (target * (target.clamp_min(1.0e-30).log() - student.log_softmax(-1))).sum()
106 return loss * (loss_coeff / x.shape[0])
109def _cann_dense_kl(
110 x: torch.Tensor, index_key: torch.Tensor, weights: torch.Tensor, query: torch.Tensor, key: torch.Tensor,
111 maximum: torch.Tensor, total: torch.Tensor, query_rope: torch.Tensor, key_rope: torch.Tensor,
112 query_ends: torch.Tensor, key_ends: torch.Tensor, *, scale: float, loss_coeff: float,
113) -> torch.Tensor:
114 indexer_stats = dsa_dense_indexer_lse(x, index_key, weights, query_lengths=query_ends, key_lengths=key_ends)
115 return dsa_dense_indexer_kl_loss(
116 x, index_key, weights, query, key, maximum, total, indexer_stats, scale=scale,
117 query_rope=query_rope, key_rope=key_rope, query_lengths=query_ends, key_lengths=key_ends,
118 loss_coefficient=loss_coeff,
119 )
122def _load_cann_dense_kl() -> DenseDsaKlFn:
123 extension = require_package("torch_npu")
124 require_symbol(extension, "npu_dense_lightning_indexer_softmax_lse")
125 require_symbol(extension, "npu_dense_lightning_indexer_grad_kl_loss")
126 return _cann_dense_kl
129def _native_packed_kl(
130 x: torch.Tensor, index_key: torch.Tensor, merge_weight: torch.Tensor,
131 query: torch.Tensor, key: torch.Tensor, topk_indices: torch.Tensor,
132 softmax_max: torch.Tensor, softmax_sum: torch.Tensor, query_rope: torch.Tensor, key_rope: torch.Tensor,
133 query_ends: torch.Tensor, key_ends: torch.Tensor, scale: float, loss_coeff: float,
134) -> torch.Tensor:
135 """Compute sparse-teacher KL over selected document-local keys."""
136 del softmax_max, softmax_sum
137 loss = x.new_zeros((), dtype=torch.float32)
138 with torch.autocast(device_type=x.device.type, enabled=False):
139 for qs, qe, ks, ke in packed_segments(query_ends, key_ends):
140 for start in range(qs, qe, 32):
141 end = min(start + 32, qe)
142 indices = topk_indices[start:end]
143 causal = torch.arange(start, end, device=x.device) - qe + ke - ks
144 with torch.no_grad():
145 selected, valid = selected_packed_keys(key[ks:ke], indices, causal_end=causal)
146 rotary_keys, _ = selected_packed_keys(key_rope[ks:ke], indices, causal_end=causal)
147 teacher = (selected_packed_scores(query[start:end], selected)
148 + selected_packed_scores(query_rope[start:end], rotary_keys)) * scale
149 teacher = teacher.masked_fill(~valid.unsqueeze(2), -1.0e9).softmax(-1)
150 target = teacher.mean(dim=2).masked_fill(~valid, 0.0)
151 selected, _ = selected_packed_keys(index_key[ks:ke], indices, causal_end=causal)
152 student = selected_packed_scores(x[start:end], selected).relu()
153 weights = merge_weight[start:end].unflatten(-1, (selected.shape[1], -1)).float()
154 student = (student * weights.unsqueeze(-1)).sum(dim=2).masked_fill(~valid, -1.0e9)
155 loss = loss + (target * (target.clamp_min(1.0e-30).log() - student.log_softmax(-1))).sum()
156 return loss * (loss_coeff / x.shape[0])
159def _load_cann_packed_kl() -> PackedDsaKlFn:
160 extension = require_package("torch_npu")
161 require_symbol(extension, "npu_sparse_lightning_indexer_grad_kl_loss")
162 return fused_packed_kl
165class _SharedCompressedIndexerKLLoss(torch.autograd.Function):
166 """PanGu-style precomputed-gradient KL loss for compressed index keys."""
168 @staticmethod
169 def forward(
170 ctx: Any,
171 index_query: torch.Tensor,
172 index_key: torch.Tensor,
173 merge_weight: torch.Tensor,
174 attention_query: torch.Tensor,
175 compressed_key: torch.Tensor,
176 topk_indices: torch.Tensor,
177 sinks: torch.Tensor,
178 attention_scale: float,
179 loss_coeff: float,
180 query_chunk_size: int,
181 reduce_sum: Callable[[torch.Tensor], torch.Tensor] | None,
182 ) -> torch.Tensor:
183 """Compute sparse KL and save only the three Indexer gradients."""
184 batch_size, sequence_length, _, _ = index_query.shape
185 denominator = batch_size * sequence_length
186 total_loss = index_query.new_zeros((), dtype=torch.float32)
187 grad_index_query = torch.zeros_like(index_query, dtype=torch.float32)
188 grad_index_key = torch.zeros_like(index_key, dtype=torch.float32)
189 grad_merge_weight = torch.zeros_like(merge_weight, dtype=torch.float32)
191 with torch.no_grad(), torch.autocast(device_type=index_query.device.type, enabled=False):
192 for start in range(0, sequence_length, query_chunk_size):
193 end = min(start + query_chunk_size, sequence_length)
194 selected = topk_indices[:, start:end]
195 valid = selected >= 0
196 # Graph capture forbids data-dependent control flow, so empty
197 # rows contribute through masks instead of a `torch.any` skip:
198 # their targets are all-zero, their gradients are all-zero, and
199 # eager evaluates exactly the same masked expressions.
200 safe_indices = selected.clamp_min(0).long()
202 query_chunk = index_query[:, start:end].float()
203 weight_chunk = merge_weight[:, start:end].float()
204 selected_index_key = gather_selected_keys(index_key, safe_indices).float()
205 index_dots = torch.einsum(
206 "bcid,bckd->bcik", query_chunk, selected_index_key
207 )
208 index_relu = index_dots.relu()
209 index_scores = (index_relu * weight_chunk.unsqueeze(-1)).sum(dim=2)
210 if reduce_sum is not None:
211 index_scores = reduce_sum(index_scores)
212 index_scores.masked_fill_(~valid, -1.0e9)
214 selected_attention_key = gather_selected_keys(compressed_key, safe_indices).float()
215 attention_scores = torch.einsum(
216 "bhcd,bckd->bhck",
217 attention_query[:, :, start:end].float(),
218 selected_attention_key,
219 ) * attention_scale
220 attention_scores.masked_fill_(~valid.unsqueeze(1), -1.0e9)
221 sink_logits = sinks.float().view(1, -1, 1, 1).expand(
222 batch_size, -1, end - start, -1
223 )
224 target = torch.cat((attention_scores, sink_logits), dim=-1).softmax(dim=-1)
225 target = target[..., :-1].masked_fill(~valid.unsqueeze(1), 0.0).sum(dim=1)
226 if reduce_sum is not None:
227 target = reduce_sum(target)
228 target = target / target.sum(dim=-1, keepdim=True).clamp_min(
229 torch.finfo(torch.float32).tiny
230 )
232 log_prediction = index_scores.log_softmax(dim=-1)
233 target_log = target.clamp_min(torch.finfo(torch.float32).tiny).log()
234 row_loss = (target * (target_log - log_prediction)).sum(dim=-1)
235 # Masked reduction instead of boolean indexing: identical value
236 # in eager and traceable across runtime-dependent row validity.
237 row_mask = valid.any(dim=-1).to(row_loss.dtype)
238 total_loss.add_((row_loss * row_mask).sum() * (loss_coeff / denominator))
240 grad_scores = log_prediction.exp() * target.sum(-1, keepdim=True) - target
241 grad_scores.mul_(loss_coeff / denominator)
242 grad_scores.masked_fill_(~valid, 0.0)
243 grad_dots = (
244 grad_scores.unsqueeze(2)
245 * weight_chunk.unsqueeze(-1)
246 * (index_dots > 0).to(index_dots.dtype)
247 )
248 grad_index_query[:, start:end] = torch.einsum(
249 "bcik,bckd->bcid", grad_dots, selected_index_key
250 )
251 grad_merge_weight[:, start:end] = (
252 grad_scores.unsqueeze(2) * index_relu
253 ).sum(dim=-1)
254 selected_key_grad = torch.einsum(
255 "bcik,bcid->bckd", grad_dots, query_chunk
256 )
257 # Preserve the einsum result if SAC cached its storage.
258 selected_key_grad = selected_key_grad.masked_fill(~valid.unsqueeze(-1), 0.0)
259 # Accumulate complete key rows without expanded-index ScatterAdd.
260 key_indices = safe_indices.reshape(batch_size, -1)
261 key_grad_rows = selected_key_grad.reshape(batch_size, -1, index_key.shape[-1])
262 for batch_idx in range(batch_size):
263 grad_index_key[batch_idx].index_put_(
264 (key_indices[batch_idx],), key_grad_rows[batch_idx], accumulate=True,
265 )
267 ctx.save_for_backward(grad_index_query, grad_index_key, grad_merge_weight)
268 return total_loss
270 @staticmethod
271 def backward(ctx: Any, grad_loss: torch.Tensor) -> tuple:
272 """Return the precomputed Indexer gradients and detach the teacher."""
273 grad_index_query, grad_index_key, grad_merge_weight = ctx.saved_tensors
274 return (
275 grad_index_query * grad_loss,
276 grad_index_key * grad_loss,
277 grad_merge_weight * grad_loss,
278 *((None,) * 8),
279 )
282def native_dsa_indexer_kl(
283 x: torch.Tensor, index_key: torch.Tensor, merge_weight: torch.Tensor,
284 attention_query: torch.Tensor, compressed_key: torch.Tensor, topk_indices: torch.Tensor,
285 sinks: torch.Tensor, *, attention_scale: float, loss_coeff: float, query_chunk_size: int = 256,
286 reduce_sum: ReduceSum | None = None, layout: DsaQueryLayout | None = None,
287) -> torch.Tensor:
288 """Compute the reference KL loss and propagate only the student gradients."""
289 index_query = x
290 if query_chunk_size <= 0:
291 raise ValueError(f"query_chunk_size must be positive, got {query_chunk_size}")
292 if not loss_coeff:
293 return index_query.sum(dtype=torch.float32) * 0.0
294 if index_key.shape[1] == 0:
295 # Keep zero gradients connected even when no document contains a complete block.
296 return (index_query[..., :0].sum(dtype=torch.float32) + index_key.sum(dtype=torch.float32)
297 + merge_weight[..., :0].sum(dtype=torch.float32)) * 0.0
298 if topk_indices.shape[:2] != index_query.shape[:2]:
299 raise ValueError("topk_indices and index_query must share batch/query dimensions")
300 if layout is not None:
301 topk_indices = _mask_compressed_keys(topk_indices, layout, index_query)
302 return _SharedCompressedIndexerKLLoss.apply(
303 x, index_key, merge_weight, attention_query.detach(), compressed_key.detach(),
304 topk_indices, sinks.detach(), attention_scale, loss_coeff, query_chunk_size, reduce_sum,
305 )
308def _mask_compressed_keys(
309 indices: torch.Tensor, layout: DsaQueryLayout, query: torch.Tensor,
310) -> torch.Tensor:
311 upper, lower = layout.compressed_bounds(query)
312 outside = indices >= upper.unsqueeze(-1)
313 if lower is not None:
314 outside = outside | (indices < lower.unsqueeze(-1))
315 return indices.masked_fill(outside, -1)
318def indexer_kl_native_only(
319 x: torch.Tensor, index_key: torch.Tensor, topk_indices: torch.Tensor,
320 layout: DsaQueryLayout | None, reduce_sum: ReduceSum | None,
321) -> str | None:
322 """Explain why the CANN KL candidate cannot represent this call."""
323 if layout is None or indexer_native_only(x, layout, reduce_sum) is not None:
324 return "fused KL requires BF16 D=128, ordinary TopK512, document segments and no TP reduction"
325 if x.shape[2] not in (8, 16, 32, 64) or not min(512, index_key.shape[1]) <= topk_indices.shape[-1] <= 512:
326 return "fused KL requires supported head counts and ordinary TopK512 indices"
327 return None
330def _cann_kl(
331 x: torch.Tensor, index_key: torch.Tensor, merge_weight: torch.Tensor,
332 attention_query: torch.Tensor, compressed_key: torch.Tensor, topk_indices: torch.Tensor,
333 sinks: torch.Tensor, *, attention_scale: float, loss_coeff: float, query_chunk_size: int = 256,
334 reduce_sum: ReduceSum | None = None, layout: DsaQueryLayout | None = None,
335) -> torch.Tensor:
336 """Validate compressed selections and invoke the fused CANN KL adapter."""
337 del reduce_sum
338 if query_chunk_size <= 0:
339 raise ValueError(f"query_chunk_size must be positive, got {query_chunk_size}")
340 indices = _mask_compressed_keys(topk_indices, layout, x)
341 validate_fused_kl_inputs(x, index_key, merge_weight, indices)
342 return sparse_lightning_indexer_kl_loss(
343 x, index_key, merge_weight, attention_query.detach(), compressed_key.detach(),
344 indices, sinks.detach(), attention_scale, loss_coeff, query_chunk_size, layout.compress_ratio, layout.segments,
345 )
348def register_dsa_indexer_kl(registry: OpRegistry) -> None:
349 """Register the compressed-teacher KL contract and its implementations."""
350 registry.register_family("dsa_indexer_kl", specs=(DSA_INDEXER_KL, DSA_PACKED_KL, DSA_DENSE_KL))
351 registry.register_impl(
352 DSA_INDEXER_KL, name="native", devices=("cpu", "cuda", "npu"), load=lambda: native_dsa_indexer_kl,
353 )
354 registry.register_impl(
355 DSA_PACKED_KL, name="native", devices=("cpu", "cuda", "npu"), load=lambda: _native_packed_kl,
356 )
357 registry.register_impl(DSA_PACKED_KL, name="cann", devices=("npu",), load=_load_cann_packed_kl)
358 registry.register_impl(
359 DSA_DENSE_KL, name="native", devices=("cpu", "cuda", "npu"), load=lambda: _native_dense_kl,
360 )
361 registry.register_impl(DSA_DENSE_KL, name="cann", devices=("npu",), load=_load_cann_dense_kl)
362 registry.register_impl(
363 DSA_INDEXER_KL, name="cann", devices=("npu",),
364 load=partial(load_cann, _cann_kl, "sparse_lightning_indexer_kl_loss_grad",
365 "sparse_lightning_indexer_kl_loss_grad_metadata"),
366 )