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"""CSA2 sparse Indexer KL objective, reference gradients and native dispatch."""
16
17from __future__ import annotations
18
19from collections.abc import Callable
20from typing import Any
21
22import torch
23
24from hyper_parallel.components.functional.sparse_lightning_indexer_kl_loss_grad import (
25 _MAX_FP32_BANK_BYTES, gather_selected_keys, sparse_lightning_indexer_kl_loss, validate_fused_kl_inputs,
26)
27from hyper_parallel.components.quantization.quantizers.csa2 import CSA2CacheQuantizer
28from hyper_parallel.components.quantization.tensor.csa2_cache_tensor import CSA2CacheTensor
29
30
31def _prepare_packed_teacher_bank(cache: torch.Tensor, selected_count: int) -> torch.Tensor | None:
32 """Decode a bounded Main teacher with zero sentinel rows for invalid selections."""
33 if (not isinstance(cache, CSA2CacheTensor) or cache.cache_format != "main_kv"
34 or cache.ndim != 3 or cache.shape[1] == 0 or cache.dtype not in (torch.bfloat16, torch.float16)):
35 return None
36 bank_bytes = cache.shape[0] * (cache.shape[1] + 2) * cache.shape[-1] * 4
37 selected_bytes = selected_count * cache.shape[-1] * cache.element_size()
38 if not 0 < bank_bytes <= _MAX_FP32_BANK_BYTES or bank_bytes >= selected_bytes:
39 return None
40 # Preserve the codec's original low-precision rescale rounding before FP32.
41 # This received bank is local to one no-grad forward, including under CP.
42 # Small sentinel rows avoid masking the much larger gathered teacher tensor.
43 return torch.nn.functional.pad(CSA2CacheQuantizer.dequantize(cache).float(), (0, 0, 1, 1))
44
45
46class _SharedCompressedIndexerKLLoss(torch.autograd.Function):
47 """Sparse KL with forward-computed Indexer gradients applied during backward."""
48
49 @staticmethod
50 def forward(
51 ctx: Any,
52 index_query: torch.Tensor,
53 index_key: torch.Tensor,
54 merge_weight: torch.Tensor,
55 attention_query: torch.Tensor,
56 compressed_key: torch.Tensor,
57 topk_indices: torch.Tensor,
58 sinks: torch.Tensor,
59 attention_scale: float,
60 loss_coeff: float,
61 query_chunk_size: int,
62 reduce_sum: Callable[[torch.Tensor], torch.Tensor] | None,
63 ) -> torch.Tensor:
64 """Compute sparse KL and save only the three Indexer gradients."""
65 batch_size, sequence_length, _, _ = index_query.shape
66 denominator = batch_size * sequence_length
67 total_loss = index_query.new_zeros((), dtype=torch.float32)
68 grad_index_query = torch.zeros_like(index_query, dtype=torch.float32)
69 grad_index_key = torch.zeros_like(index_key, dtype=torch.float32)
70 grad_merge_weight = torch.zeros_like(merge_weight, dtype=torch.float32)
71
72 with torch.no_grad(), torch.autocast(device_type=index_query.device.type, enabled=False):
73 selected_count = batch_size * min(sequence_length, query_chunk_size) * topk_indices.shape[-1]
74 teacher_bank = _prepare_packed_teacher_bank(compressed_key, selected_count)
75 for start in range(0, sequence_length, query_chunk_size):
76 end = min(start + query_chunk_size, sequence_length)
77 selected = topk_indices[:, start:end]
78 valid = selected >= 0
79 # Graph capture forbids data-dependent control flow, so empty
80 # rows contribute through masks instead of a `torch.any` skip:
81 # their targets are all-zero, their gradients are all-zero, and
82 # eager evaluates exactly the same masked expressions.
83 safe_indices = selected.clamp_min(0).long()
84
85 query_chunk = index_query[:, start:end].float()
86 weight_chunk = merge_weight[:, start:end].float()
87 selected_index_key = gather_selected_keys(index_key, safe_indices).float()
88 index_dots = torch.einsum(
89 "bcid,bckd->bcik", query_chunk, selected_index_key
90 )
91 index_relu = index_dots.relu()
92 index_scores = (index_relu * weight_chunk.unsqueeze(-1)).sum(dim=2)
93 if reduce_sum is not None:
94 index_scores = reduce_sum(index_scores)
95 index_scores.masked_fill_(~valid, -1.0e9)
96
97 if isinstance(compressed_key, CSA2CacheTensor):
98 if teacher_bank is None:
99 selected_attention_key = CSA2CacheQuantizer.dequantize_selected(
100 compressed_key, safe_indices
101 ).float()
102 else:
103 teacher_indices = selected.clamp(min=-1, max=compressed_key.shape[1]).long() + 1
104 selected_attention_key = gather_selected_keys(teacher_bank, teacher_indices)
105 else:
106 selected_attention_key = gather_selected_keys(compressed_key, safe_indices).float()
107 attention_scores = torch.einsum(
108 "bhcd,bckd->bhck",
109 attention_query[:, :, start:end].float(),
110 selected_attention_key,
111 ) * attention_scale
112 attention_scores.masked_fill_(~valid.unsqueeze(1), -1.0e9)
113 sink_logits = sinks.float().view(1, -1, 1, 1).expand(
114 batch_size, -1, end - start, -1
115 )
116 target = torch.cat((attention_scores, sink_logits), dim=-1).softmax(dim=-1)
117 target = target[..., :-1].masked_fill(~valid.unsqueeze(1), 0.0).sum(dim=1)
118 if reduce_sum is not None:
119 target = reduce_sum(target)
120 target = target / target.sum(dim=-1, keepdim=True).clamp_min(
121 torch.finfo(torch.float32).tiny
122 )
123
124 log_prediction = index_scores.log_softmax(dim=-1)
125 target_log = target.clamp_min(torch.finfo(torch.float32).tiny).log()
126 row_loss = (target * (target_log - log_prediction)).sum(dim=-1)
127 # Masked reduction instead of boolean indexing: identical value
128 # in eager and traceable across runtime-dependent row validity.
129 row_mask = valid.any(dim=-1).to(row_loss.dtype)
130 total_loss.add_((row_loss * row_mask).sum() * (loss_coeff / denominator))
131
132 grad_scores = log_prediction.exp() * target.sum(-1, keepdim=True) - target
133 grad_scores.mul_(loss_coeff / denominator)
134 grad_scores.masked_fill_(~valid, 0.0)
135 grad_dots = (
136 grad_scores.unsqueeze(2)
137 * weight_chunk.unsqueeze(-1)
138 * (index_dots > 0).to(index_dots.dtype)
139 )
140 grad_index_query[:, start:end] = torch.einsum(
141 "bcik,bckd->bcid", grad_dots, selected_index_key
142 )
143 grad_merge_weight[:, start:end] = (
144 grad_scores.unsqueeze(2) * index_relu
145 ).sum(dim=-1)
146 selected_key_grad = torch.einsum(
147 "bcik,bcid->bckd", grad_dots, query_chunk
148 )
149 # Preserve the einsum result if SAC cached its storage.
150 selected_key_grad = selected_key_grad.masked_fill(~valid.unsqueeze(-1), 0.0)
151 # Each selected key contributes a complete gradient row. Avoid
152 # CANN ScatterAdd's expanded-index host preprocessing path.
153 key_indices = safe_indices.reshape(batch_size, -1)
154 key_grad_rows = selected_key_grad.reshape(batch_size, -1, index_key.shape[-1])
155 for batch_idx in range(batch_size):
156 grad_index_key[batch_idx].index_put_(
157 (key_indices[batch_idx],), key_grad_rows[batch_idx], accumulate=True
158 )
159
160 ctx.save_for_backward(grad_index_query, grad_index_key, grad_merge_weight)
161 return total_loss
162
163 @staticmethod
164 def backward(ctx: Any, grad_loss: torch.Tensor) -> tuple:
165 """Return the precomputed Indexer gradients and detach the teacher."""
166 grad_index_query, grad_index_key, grad_merge_weight = ctx.saved_tensors
167 return (
168 grad_index_query * grad_loss,
169 grad_index_key * grad_loss,
170 grad_merge_weight * grad_loss,
171 *((None,) * 8),
172 )
173
174
175def shared_compressed_indexer_kl_loss(
176 index_query: torch.Tensor,
177 index_key: torch.Tensor,
178 merge_weight: torch.Tensor,
179 attention_query: torch.Tensor,
180 compressed_key: torch.Tensor,
181 topk_indices: torch.Tensor,
182 sinks: torch.Tensor,
183 *,
184 attention_scale: float,
185 loss_coeff: float,
186 query_chunk_size: int = 256,
187 reduce_sum: Callable[[torch.Tensor], torch.Tensor] | None = None,
188 compress_ratio: int = 1,
189 query_segments: tuple[tuple[int, int, int, int, int], ...] | None = None,
190 use_fused: bool = False,
191) -> torch.Tensor:
192 """Compute the sparse-stage DSA KL objective on V4.1 compressed keys.
193
194 The target first softmaxes selected main-attention scores per attention
195 head, then sums and L1-normalizes across heads. Only Indexer query, key,
196 and merge-weight inputs receive gradients; teacher inputs are detached.
197
198 ``use_fused`` is valid only for ordinary causal TopK selections, without
199 candidate-pool holes. ``query_segments`` supplies each document-local K
200 prefix; its ratio and residual encode the CP query offset for the kernel.
201 ``use_fused=True`` raises for unsupported calls when ``loss_coeff != 0``;
202 False explicitly selects the numerical reference. Native errors propagate.
203 """
204 if query_chunk_size <= 0:
205 raise ValueError(f"query_chunk_size must be positive, got {query_chunk_size}")
206 if not loss_coeff:
207 return index_query.sum(dtype=torch.float32) * 0.0
208 if index_key.shape[1] == 0:
209 # Keep zero gradients connected even when no document contains a complete block.
210 return (index_query[..., :0].sum(dtype=torch.float32) + index_key.sum(dtype=torch.float32)
211 + merge_weight[..., :0].sum(dtype=torch.float32)) * 0.0
212 if topk_indices.shape[:2] != index_query.shape[:2]:
213 raise ValueError("topk_indices and index_query must share batch/query dimensions")
214 if use_fused:
215 if reduce_sum is not None:
216 raise NotImplementedError("Fused KL does not support TP score/teacher reduction")
217 if query_segments is None:
218 raise ValueError("Fused KL requires document-local causal query_segments")
219 validate_fused_kl_inputs(index_query, index_key, merge_weight, topk_indices)
220 # The fused kernel consumes the full bank using the codec's original dtype.
221 teacher_key = (
222 CSA2CacheQuantizer.dequantize(compressed_key)
223 if isinstance(compressed_key, CSA2CacheTensor) else compressed_key
224 )
225 return sparse_lightning_indexer_kl_loss(
226 index_query, index_key, merge_weight, attention_query.detach(), teacher_key.detach(),
227 topk_indices, sinks.detach(), attention_scale, loss_coeff, query_chunk_size,
228 compress_ratio, query_segments,
229 )
230 return _SharedCompressedIndexerKLLoss.apply(
231 index_query,
232 index_key,
233 merge_weight,
234 attention_query.detach(),
235 compressed_key.detach(),
236 topk_indices,
237 sinks.detach(),
238 attention_scale,
239 loss_coeff,
240 query_chunk_size,
241 reduce_sum,
242 )