Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / quantization / functional / mxfp8_fused_grouped_swiglu.py: 85%

96 statements  

« 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"""Fused SwiGLU/quantization within one grouped-expert autograd boundary.""" 

16 

17from typing import TYPE_CHECKING, Optional 

18 

19import torch 

20from torch.autograd.function import once_differentiable 

21 

22from hyper_parallel.components.quantization.ops.npu_mxfp8 import mxfp8_grouped_matmul 

23from hyper_parallel.components.quantization.tensor import MXFP8Tensor 

24 

25if TYPE_CHECKING: 

26 from hyper_parallel.components.quantization.quantizers.mxfp8 import MXFP8Quantizer 

27 

28 

29def _save_operands(ctx, counts, projected, operands): 

30 """Expose only needed physical tensors to saved-tensor hooks, never carrier wrappers.""" 

31 metadata = [] 

32 buffers = [] 

33 for operand in operands: 

34 if operand is None: 

35 metadata.append(None) 

36 buffers.extend((None,) * 4) 

37 else: 

38 metadata.append((tuple(operand.shape), operand.dtype, operand.quantizer)) 

39 buffers.extend((operand.row_data, operand.row_scale, operand.col_data, operand.col_scale)) 

40 ctx.operand_metadata = tuple(metadata) 

41 ctx.save_for_backward(counts, projected, *buffers) 

42 

43 

44def _restore_operands(ctx): 

45 """Use the same physical-buffer reconstruction as the upstream Dense/GMM path.""" 

46 counts, projected, *buffers = ctx.saved_tensors 

47 operands = [] 

48 for index, meta in enumerate(ctx.operand_metadata): 

49 if meta is None: 

50 operands.append(None) 

51 continue 

52 shape, dtype, quantizer = meta 

53 row, row_scale, col, col_scale = buffers[4 * index:4 * index + 4] 

54 operands.append(MXFP8Tensor(shape, dtype, quantizer=quantizer, row_data=row, 

55 row_scale=row_scale, col_data=col, col_scale=col_scale)) 

56 return counts, projected, operands 

57 

58 

59def _fused_quant(projected, quantizer, counts, gradient=None, clamp_limit=None): 

60 """Keep prequantized operands internal to this Function's GMM calls.""" 

61 options = { 

62 "quant_dtype": quantizer.quant_dtype, 

63 "group_index": counts.cumsum(0).to(torch.int64), 

64 "clamp_limit": clamp_limit, 

65 } 

66 if gradient is None: 

67 buffers = quantizer.npu_ops.swiglu_mx_quant_dual_axis(projected, **options) 

68 shape = (projected.shape[0], projected.shape[1] // 2) 

69 else: 

70 buffers = quantizer.npu_ops.swiglu_backward_mx_quant_dual_axis( 

71 projected, gradient.contiguous(), **options) 

72 shape = projected.shape 

73 row, row_scale, col, col_scale = buffers 

74 return MXFP8Tensor(shape, projected.dtype, quantizer=quantizer, 

75 row_data=row, row_scale=row_scale, col_data=col, col_scale=col_scale) 

76 

77 

78def _gmm(left, right, counts, dtype, layout="NT"): 

79 """Use the existing MXFP8 adapter and count-based expert partitioning.""" 

80 return mxfp8_grouped_matmul(left, right, layout=layout, group_list=counts, 

81 group_type=2 if layout == "TN" else 0, 

82 group_list_type=1, output_dtype=dtype) 

83 

84 

85class _FusedGroupedSwiGLU(torch.autograd.Function): 

86 """Own both GMMs and fusion directly on canonical [E, O, K] weights without physical transpose copies.""" 

87 

88 @staticmethod 

89 def forward( 

90 ctx: torch.autograd.function.FunctionCtx, inputs: torch.Tensor, 

91 gate_up: torch.Tensor, down: torch.Tensor, counts: torch.Tensor, quantizer: "MXFP8Quantizer", 

92 clamp_limit: Optional[float], 

93 ) -> torch.Tensor: 

94 """Quantize [E, O, K] weights in place, run two NT MXFP8 GMMs, and retain only backward views. 

95 

96 Args: 

97 ctx: Autograd save context. 

98 inputs: Expert-major token matrix ``[R, H]``. 

99 gate_up: Canonical packed gate/up weights ``[E, 2I, H]``. 

100 down: Canonical down weights ``[E, H, I]``. 

101 counts: Per-expert token counts ``[E]``. 

102 quantizer: MXFP8 quantizer. 

103 clamp_limit: Optional positive clipping limit for DeepSeek experts. 

104 """ 

105 ctx.shapes = (inputs.shape, gate_up.shape, down.shape) 

106 ctx.dtype, ctx.device, ctx.quantizer = inputs.dtype, inputs.device, quantizer 

107 ctx.clamp_limit = clamp_limit 

108 if inputs.shape[0] == 0: 

109 ctx.save_for_backward() 

110 return inputs.new_empty((0, down.shape[1])) 

111 needs_input = inputs.requires_grad 

112 needs_gate = gate_up.requires_grad 

113 needs_down = down.requires_grad 

114 needs_swiglu_bwd = needs_input or needs_gate 

115 

116 input_q = quantizer.quantize( 

117 inputs.contiguous(), group_list=counts if needs_gate else None, group_list_type=1, 

118 rowwise=True, colwise=needs_gate, 

119 ) 

120 gate_up_q = quantizer.quantize(gate_up.contiguous(), rowwise=True, colwise=needs_input) 

121 projected = _gmm(input_q, gate_up_q, counts, inputs.dtype, "NT") 

122 input_q.update_usage(rowwise=False, colwise=needs_gate) 

123 gate_up_q.update_usage(rowwise=False, colwise=needs_input) 

124 

125 activated_q = _fused_quant(projected, quantizer, counts, clamp_limit=clamp_limit) 

126 down_q = quantizer.quantize(down.contiguous(), rowwise=True, colwise=needs_swiglu_bwd) 

127 output = _gmm(activated_q, down_q, counts, inputs.dtype, "NT") 

128 activated_q.update_usage(rowwise=False, colwise=needs_down) 

129 down_q.update_usage(rowwise=False, colwise=needs_swiglu_bwd) 

130 

131 _save_operands( 

132 ctx, 

133 counts, 

134 projected if needs_swiglu_bwd else None, 

135 ( 

136 input_q if needs_gate else None, 

137 gate_up_q if needs_input else None, 

138 activated_q if needs_down else None, 

139 down_q if needs_swiglu_bwd else None, 

140 ), 

141 ) 

142 return output 

143 

144 @staticmethod 

145 @once_differentiable 

146 def backward( 

147 ctx: torch.autograd.function.FunctionCtx, gradient: torch.Tensor, 

148 ) -> tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor], None, None, None]: 

149 """Fuse SwiGLU derivative/quantization and emit contiguous [E, O, K] weight gradients directly. 

150 

151 Args: 

152 ctx: Saved forward context. 

153 gradient: Output gradient ``[R, H]``. 

154 """ 

155 needs_input, needs_gate, needs_down = ctx.needs_input_grad[:3] 

156 if ctx.shapes[0][0] == 0: 

157 grads = [torch.zeros(shape, device=ctx.device, dtype=ctx.dtype) if needed else None 

158 for shape, needed in zip(ctx.shapes, (needs_input, needs_gate, needs_down))] 

159 return *grads, None, None, None 

160 if not (needs_input or needs_gate or needs_down): 

161 return None, None, None, None, None, None 

162 counts, projected, (input_q, gate_up_q, activated_q, down_q) = _restore_operands(ctx) 

163 grad_q = ctx.quantizer.quantize( 

164 gradient.contiguous(), group_list=counts if needs_down else None, group_list_type=1, 

165 rowwise=needs_input or needs_gate, colwise=needs_down, 

166 ) 

167 grad_down = _gmm(grad_q, activated_q, counts, ctx.dtype, "TN") if needs_down else None 

168 grad_input = grad_gate = None 

169 if needs_input or needs_gate: 

170 grad_activated = _gmm(grad_q, down_q, counts, ctx.dtype, "NN") 

171 grad_projected_q = _fused_quant(projected, ctx.quantizer, counts, grad_activated, ctx.clamp_limit) 

172 if needs_input: 

173 grad_input = _gmm(grad_projected_q, gate_up_q, counts, ctx.dtype, "NN") 

174 if needs_gate: 

175 grad_gate = _gmm(grad_projected_q, input_q, counts, ctx.dtype, "TN") 

176 return grad_input, grad_gate, grad_down, None, None, None 

177 

178 

179def fused_grouped_swiglu( 

180 inputs: torch.Tensor, gate_up: torch.Tensor, down: torch.Tensor, 

181 counts: torch.Tensor, quantizer: "MXFP8Quantizer", 

182 *, clamp_limit: Optional[float] = None, 

183) -> torch.Tensor: 

184 """Compute expert-major outputs with canonical HuggingFace [E, 2I, H] / [E, H, I] weights. 

185 

186 Args: 

187 inputs: BF16/FP16 expert-major token matrix ``[R, H]``. 

188 gate_up: Canonical packed gate/up weights ``[E, 2I, H]``. 

189 down: Canonical down weights ``[E, H, I]``. 

190 counts: Per-local-expert token counts, including zero-token experts. 

191 quantizer: MXFP8 recipe with both fused NPU kernels available. 

192 clamp_limit: Optional positive clipping limit for gate and up projections. 

193 

194 Returns: 

195 Ordinary BF16/FP16 outputs before outer routing weights are applied. 

196 """ 

197 if inputs.dtype not in (torch.bfloat16, torch.float16): 

198 raise ValueError("Fused MXFP8 SwiGLU requires BF16 or FP16 inputs") 

199 if gate_up.dtype != inputs.dtype or down.dtype != inputs.dtype: 

200 raise ValueError("Fused MXFP8 SwiGLU requires matching input and weight dtypes") 

201 if inputs.ndim != 2 or gate_up.ndim != 3 or down.ndim != 3: 

202 raise ValueError("Fused MXFP8 SwiGLU requires 2D inputs and 3D expert weights") 

203 if (gate_up.shape[0] != down.shape[0] or gate_up.shape[2] != inputs.shape[1] 

204 or gate_up.shape[1] != 2 * down.shape[2] or down.shape[1] != inputs.shape[1]): 

205 raise ValueError("Fused MXFP8 SwiGLU weight dimensions do not match inputs") 

206 if counts.ndim != 1 or counts.numel() != gate_up.shape[0] or counts.dtype not in (torch.int32, torch.int64): 

207 raise ValueError("Fused MXFP8 SwiGLU requires one integer count per expert") 

208 return _FusedGroupedSwiGLU.apply(inputs, gate_up, down, counts, quantizer, clamp_limit)