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"""Shared grouped-linear autograd flow for native and fake-QAT strategies.
16
17The lifecycle prepares forward operands, executes GMM, retains only the views
18required by backward, prepares ``grad_output``, and executes dgrad/wgrad.
19Format-specific strategies provide quantization, their forward weight
20direction, group normalization, and backend calls. The shared template derives
21the dgrad direction and owns weight-view cleanup.
22"""
23
24from abc import ABC, abstractmethod
25from typing import Optional
26
27import torch
28
29from hyper_parallel.components.quantization.tensor import QuantizedTensor
30from hyper_parallel.components.quantization.config import (
31 GMM_GROUP_K,
32 GMM_GROUP_M,
33 GROUPED_NDIM,
34 GROUP_LIST_COUNTS,
35 GROUP_LIST_OFFSETS,
36 MATRIX_NDIM,
37)
38from hyper_parallel.components.quantization.functional._saved_quantized import (
39 restore_quantized_operands,
40 save_quantized_operands,
41)
42
43class GroupedLinear(ABC):
44 """Own the common grouped-linear flow and expose format-specific hooks.
45
46 The weight contract is fixed to the HuggingFace live layout ``[E, O, K]``
47 (contracting ``K`` at ``-1``): strategies quantize ``[E, O, K]`` directly
48 in place, ``forward`` runs ``layout="NT"``, ``dgrad`` runs ``layout="NN"``,
49 and ``wgrad`` runs ``grad_output^T @ inputs`` (``layout="TN"``) to emit
50 contiguous ``[E, O, K]`` gradients directly without physical transpose copies.
51 """
52
53 FORMAT_NAME: str
54
55 def _validate_inputs(
56 self,
57 inputs: torch.Tensor,
58 weight: torch.Tensor,
59 group_list: torch.Tensor,
60 group_list_type: int,
61 ) -> None:
62 """Validate the common live-weight and group metadata contract."""
63
64 validate_grouped_linear_inputs(
65 inputs,
66 weight,
67 group_list,
68 group_list_type,
69 weight_input_dim=-1,
70 name=self.FORMAT_NAME,
71 )
72
73 @abstractmethod
74 def normalize_group_list(
75 self,
76 group_list: torch.Tensor,
77 group_list_type: int,
78 ) -> tuple[torch.Tensor, int]:
79 """Adapt grouped metadata to this backend's fixed contract.
80
81 ``group_list_type=1`` means ``group_list`` contains per-expert token
82 counts; ``group_list_type=0`` means it contains cumulative expert
83 offsets. The returned tensor and type must describe the same
84 representation. MXFP8 and HiFloat8 preserve either representation,
85 while W4A8 strategies convert counts to cumulative offsets and return
86 type 0 because their grouped-matmul path uses the offsets contract.
87 The shared lifecycle passes this pair through forward and saves it for
88 backward, so callers must not assume the returned type is always 0.
89 """
90
91 @abstractmethod
92 def output_features(self, weight: torch.Tensor) -> int:
93 """Return the output width ``O`` in the live ``[E, O, K]`` layout."""
94
95 @property
96 @abstractmethod
97 def weight_forward_is_rowwise(self) -> bool:
98 """Declare the weight view required by this strategy's forward NT GMM.
99
100 Return ``True`` when the forward kernel consumes the row-wise ``[E, O, K]``
101 weight view, or ``False`` when it consumes the column-wise view. The shared
102 lifecycle builds the forward view and, when an input gradient is needed,
103 the opposite view for the dgrad NN GMM, then releases the forward view
104 immediately after the forward call.
105
106 Returns:
107 Whether the forward NT GMM consumes the row-wise weight view.
108 """
109
110 @abstractmethod
111 def quantize_input(
112 self,
113 inputs: torch.Tensor,
114 *,
115 rowwise: bool,
116 colwise: bool,
117 group_list: torch.Tensor,
118 group_list_type: int,
119 ) -> QuantizedTensor:
120 """Create the format-specific activation representation."""
121
122 @abstractmethod
123 def quantize_weight(
124 self,
125 weight: torch.Tensor,
126 *,
127 rowwise: bool,
128 colwise: bool,
129 ) -> QuantizedTensor:
130 """Create the format-specific weight representation."""
131
132 @abstractmethod
133 def quantize_grad_output(
134 self,
135 grad_output: torch.Tensor,
136 *,
137 rowwise: bool,
138 colwise: bool,
139 group_list: torch.Tensor,
140 group_list_type: int,
141 ) -> QuantizedTensor:
142 """Create the format-specific gradient-output representation."""
143
144 @abstractmethod
145 def grouped_matmul(
146 self,
147 left: QuantizedTensor,
148 right: QuantizedTensor,
149 *,
150 layout: str,
151 group_list: torch.Tensor,
152 group_type: int,
153 group_list_type: int,
154 output_dtype: torch.dtype,
155 ) -> torch.Tensor:
156 """Execute one format-specific grouped matrix multiplication."""
157
158 def forward(
159 self,
160 ctx: torch.autograd.function.FunctionCtx,
161 inputs: torch.Tensor,
162 weight: torch.Tensor,
163 group_list: torch.Tensor,
164 group_list_type: int,
165 ) -> torch.Tensor:
166 """Run the complete forward lifecycle using this strategy's hooks."""
167
168 # Shared validation gate for live [E, O, K] geometry and group
169 # invariants. Errors use FORMAT_NAME as their prefix.
170 self._validate_inputs(
171 inputs,
172 weight,
173 group_list,
174 group_list_type,
175 )
176 # Prepare the strategy-specific representation once. Keep the tensor
177 # and its type paired: W4A8 converts counts to offsets/type 0, whereas
178 # MXFP8 and HiFloat8 can preserve counts/type 1.
179 effective_group_list, effective_group_list_type = self.normalize_group_list(
180 group_list,
181 group_list_type,
182 )
183 ctx.input_shape = inputs.shape
184 ctx.input_dtype = inputs.dtype
185 ctx.input_device = inputs.device
186 ctx.weight_shape = weight.shape
187 ctx.weight_dtype = weight.dtype
188 ctx.weight_device = weight.device
189 # Backward must interpret the saved group list exactly as forward did.
190 ctx.group_list_type = effective_group_list_type
191 ctx.strategy = self
192 ctx.empty_input = inputs.shape[0] == 0
193 if ctx.empty_input:
194 # Return the output width O even when the input is empty.
195 ctx.save_for_backward(effective_group_list)
196 return inputs.new_empty((0, self.output_features(weight)))
197
198 needs_grad_input = inputs.requires_grad
199 needs_grad_weight = weight.requires_grad
200 # Quantize activations: rowwise for forward and colwise for wgrad.
201 input_quant = self.quantize_input(
202 inputs,
203 rowwise=True,
204 colwise=needs_grad_weight,
205 group_list=effective_group_list,
206 group_list_type=effective_group_list_type,
207 )
208 # The forward NT and dgrad NN kernels consume opposite weight views.
209 forward_rowwise = self.weight_forward_is_rowwise
210 # Always build the forward view; build the opposite dgrad view only
211 # when the input gradient needs the weight.
212 if forward_rowwise:
213 weight_rowwise, weight_colwise = True, needs_grad_input
214 else:
215 weight_rowwise, weight_colwise = needs_grad_input, True
216 # Quantize the live HuggingFace [E, O, K] weight directly without copying.
217 weight_quant = self.quantize_weight(
218 weight,
219 rowwise=weight_rowwise,
220 colwise=weight_colwise,
221 )
222 # Run the forward NT GMM (inputs [R, K] @ weight^T [E, K, O] -> [R, O]).
223 output = self.grouped_matmul(
224 input_quant,
225 weight_quant,
226 layout="NT",
227 group_list=effective_group_list,
228 group_type=GMM_GROUP_M,
229 group_list_type=effective_group_list_type,
230 output_dtype=inputs.dtype,
231 )
232 # Some CANN grouped-matmul kernels promote their result to float32
233 # even when ``output_dtype`` is supplied. The routed expert contract
234 # is the input activation dtype; enforce it here so the next model
235 # operator (for example BF16 RMSNorm) receives a supported pair.
236 if output.dtype != inputs.dtype:
237 output = output.to(dtype=inputs.dtype)
238
239 # The forward view is spent; keep only the direction backward needs.
240 input_quant.update_usage(rowwise=False, colwise=needs_grad_weight)
241 # Dgrad consumes the opposite view. Release both views when it is unused.
242 if not needs_grad_input:
243 weight_quant.update_usage(rowwise=False, colwise=False)
244 elif forward_rowwise:
245 weight_quant.update_usage(rowwise=False, colwise=True)
246 else:
247 weight_quant.update_usage(rowwise=True, colwise=False)
248 operands = (
249 input_quant if needs_grad_weight else None,
250 weight_quant if needs_grad_input else None,
251 )
252 ctx.quantized_operands_saved = all(
253 operand is None or isinstance(operand, QuantizedTensor)
254 for operand in operands
255 )
256 if ctx.quantized_operands_saved:
257 save_quantized_operands(ctx, *operands, effective_group_list)
258 ctx.input_quant = None
259 ctx.weight_quant = None
260 else:
261 ctx.save_for_backward(effective_group_list)
262 ctx.input_quant, ctx.weight_quant = operands
263 return output
264
265 def backward(
266 self,
267 ctx: torch.autograd.function.FunctionCtx,
268 grad_output: torch.Tensor,
269 ) -> tuple[Optional[torch.Tensor], Optional[torch.Tensor]]:
270 """Run the complete dgrad/wgrad lifecycle using this strategy's hooks."""
271
272 needs_grad_input = ctx.needs_input_grad[0]
273 needs_grad_weight = ctx.needs_input_grad[1]
274 if ctx.empty_input:
275 (group_list,) = ctx.saved_tensors
276 grad_input = (
277 torch.zeros(
278 ctx.input_shape,
279 dtype=ctx.input_dtype,
280 device=ctx.input_device,
281 )
282 if needs_grad_input
283 else None
284 )
285 grad_weight = (
286 torch.zeros(
287 ctx.weight_shape,
288 dtype=ctx.weight_dtype,
289 device=ctx.weight_device,
290 )
291 if needs_grad_weight
292 else None
293 )
294 return grad_input, grad_weight
295
296 if ctx.quantized_operands_saved:
297 group_list, input_quant, weight_quant = restore_quantized_operands(ctx)
298 else:
299 (group_list,) = ctx.saved_tensors
300 input_quant = ctx.input_quant
301 weight_quant = ctx.weight_quant
302 # Quantize grad_output with the views required by backward.
303 grad_quant = self.quantize_grad_output(
304 grad_output,
305 rowwise=needs_grad_input,
306 colwise=needs_grad_weight,
307 group_list=group_list,
308 group_list_type=ctx.group_list_type,
309 )
310 grad_input = None
311 grad_weight = None
312 if needs_grad_input:
313 # dgrad: grad_output [R, O] @ retained weight [E, O, K] (NN) -> [R, K].
314 grad_input = self.grouped_matmul(
315 grad_quant,
316 weight_quant,
317 layout="NN",
318 group_list=group_list,
319 group_type=GMM_GROUP_M,
320 group_list_type=ctx.group_list_type,
321 output_dtype=ctx.input_dtype,
322 )
323 if needs_grad_weight:
324 # wgrad: grad_output^T [O, M_e] @ retained input [M_e, K] (TN) -> [E, O, K].
325 grad_weight = self.grouped_matmul(
326 grad_quant,
327 input_quant,
328 layout="TN",
329 group_list=group_list,
330 group_type=GMM_GROUP_K,
331 group_list_type=ctx.group_list_type,
332 output_dtype=ctx.weight_dtype,
333 )
334
335 grad_quant.update_usage(rowwise=False, colwise=False)
336 ctx.input_quant = None
337 ctx.weight_quant = None
338 return grad_input, grad_weight
339
340
341def validate_grouped_linear_inputs(
342 inputs: torch.Tensor,
343 weight: torch.Tensor,
344 group_list: torch.Tensor,
345 group_list_type: int,
346 *,
347 weight_input_dim: int,
348 name: str,
349) -> None:
350 """Validate shape and grouping invariants shared by native formats."""
351
352 if inputs.ndim != MATRIX_NDIM:
353 raise ValueError(
354 f"{name} grouped linear inputs must be two-dimensional, "
355 f"got shape {tuple(inputs.shape)}."
356 )
357 if weight.ndim != GROUPED_NDIM:
358 raise ValueError(
359 f"{name} grouped linear weight must be three-dimensional, "
360 f"got shape {tuple(weight.shape)}."
361 )
362 if inputs.shape[-1] != weight.shape[weight_input_dim]:
363 raise ValueError(
364 f"{name} grouped linear contracting dimensions differ: "
365 f"inputs={inputs.shape[-1]}, weight={weight.shape[weight_input_dim]}."
366 )
367 if not isinstance(group_list, torch.Tensor) or group_list.ndim != 1:
368 raise ValueError(f"{name} grouped linear group_list must be one-dimensional.")
369 if group_list.shape[0] != weight.shape[0]:
370 raise ValueError(
371 f"{name} grouped linear requires one group per expert: "
372 f"groups={group_list.shape[0]}, experts={weight.shape[0]}."
373 )
374 if group_list_type not in (GROUP_LIST_OFFSETS, GROUP_LIST_COUNTS):
375 raise ValueError(
376 f"{name} grouped linear group_list_type must be "
377 f"{GROUP_LIST_OFFSETS} or {GROUP_LIST_COUNTS}, "
378 f"but got {group_list_type}."
379 )
380
381
382# PyTorch's Function base exposes variadic callbacks; this bridge intentionally
383# specializes them for the grouped-linear ``apply`` contract.
384class _GroupedLinearFunction(torch.autograd.Function): # pylint: disable=abstract-method,arguments-differ
385 """Bridge PyTorch autograd callbacks to the strategy selected for the call.
386
387 Model adapters pass the strategy instance into ``apply`` as an argument;
388 inside the bridge the strategy's own forward/backward lifecycle runs.
389 Because ``Function`` forward/backward are static methods, instance state
390 (quantizer, tile size, ...) can only reach the flow through the ``apply``
391 arguments, so the strategy is carried on ``ctx`` for backward.
392 """
393
394 @staticmethod
395 def forward( # pylint: disable=arguments-differ
396 ctx: torch.autograd.function.FunctionCtx,
397 inputs: torch.Tensor,
398 weight: torch.Tensor,
399 group_list: torch.Tensor,
400 strategy: GroupedLinear,
401 group_list_type: int,
402 ) -> torch.Tensor:
403 """Delegate the complete forward lifecycle to the strategy."""
404
405 return strategy.forward(
406 ctx,
407 inputs,
408 weight,
409 group_list,
410 group_list_type,
411 )
412
413 @staticmethod
414 def backward( # pylint: disable=arguments-differ
415 ctx: torch.autograd.function.FunctionCtx,
416 grad_output: torch.Tensor,
417 ) -> tuple[
418 Optional[torch.Tensor],
419 Optional[torch.Tensor],
420 None,
421 None,
422 None,
423 ]:
424 """Delegate the complete backward lifecycle to the strategy."""
425
426 grad_input, grad_weight = ctx.strategy.backward(ctx, grad_output)
427 return grad_input, grad_weight, None, None, None
428
429
430__all__ = [
431 "GroupedLinear",
432 "_GroupedLinearFunction",
433 "validate_grouped_linear_inputs",
434]