Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / functional / linear_attention_convolution.py: 49%

171 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"""Optional NPU kernels for dense and packed depthwise causal convolution.""" 

16 

17from __future__ import annotations 

18 

19from typing import TYPE_CHECKING, Any 

20 

21import torch 

22from torch import nn 

23from torch.nn import functional as F 

24 

25if TYPE_CHECKING: 

26 from hyper_parallel.components.modules.attention.linear_attention_utils.sequence_layout import ( 

27 PackedSequenceInfo, 

28 ) 

29 

30 

31def validate_causal_convolution(convolution: nn.Conv1d, *, require_activation: bool = False) -> None: 

32 """Reject source convolutions whose semantics differ from the supported causal kernel. 

33 

34 Args: 

35 convolution: Source depthwise short convolution. 

36 require_activation: KDA source ShortConv declares its SiLU activation. 

37 """ 

38 if convolution.stride != (1,): 

39 raise ValueError("Linear-attention ShortConv requires stride=1") 

40 if convolution.groups != convolution.in_channels or convolution.out_channels != convolution.in_channels: 

41 raise ValueError("Linear-attention ShortConv requires depthwise equal input/output channels") 

42 padding = (convolution.kernel_size[0] - 1) * convolution.dilation[0] 

43 if convolution.padding != (padding,) or convolution.padding_mode != "zeros": 

44 raise ValueError("Linear-attention ShortConv requires causal zero padding") 

45 if require_activation and getattr(convolution, "activation", None) not in ("silu", "swish"): 

46 raise ValueError("KDA ShortConv requires a declared SiLU/Swish activation") 

47 

48 

49def validate_conv_backend(backend: str) -> str: 

50 """Validate an explicit convolution backend without loading kernels. 

51 

52 Args: 

53 backend: One of ``eager``, ``triton``, or ``ascendc``. 

54 

55 Returns: 

56 The validated backend, without changing its spelling or default. 

57 

58 Raises: 

59 ValueError: If the backend is unsupported. 

60 """ 

61 if backend not in ("eager", "triton", "ascendc"): 

62 raise ValueError(f"Unsupported convolution backend {backend!r}; expected eager, triton, or ascendc.") 

63 return backend 

64 

65 

66class _AscendCConvolution(torch.autograd.Function): 

67 """Shared dense/packed convolution with joint SiLU and convolution backward.""" 

68 

69 @staticmethod 

70 def forward( 

71 ctx: Any, 

72 inputs: torch.Tensor, 

73 weight: torch.Tensor, 

74 bias: torch.Tensor | None, 

75 offsets: tuple[int, ...] | None, 

76 ) -> torch.Tensor: 

77 """Save preactivation and per-call metadata for joint backward. 

78 

79 Args: 

80 ctx: Autograd context owning this call's saved tensors. 

81 inputs: Dense or packed token activations, including any valid history. 

82 weight: Depthwise convolution parameter with shape ``[C,1,W]``. 

83 bias: Optional channel bias. 

84 offsets: Packed document boundaries, or None for independent dense samples. 

85 """ 

86 # Optional native operators must not be loaded by ordinary framework imports. 

87 from fla_npu.ops.ascendc import causal_conv1d_fn # pylint: disable=import-outside-toplevel 

88 

89 op_inputs = inputs if offsets is None else inputs.reshape(-1, inputs.shape[-1]) 

90 op_inputs = op_inputs.contiguous() 

91 op_weight = weight[:, 0].transpose(0, 1).contiguous() 

92 cpu_offsets = None if offsets is None else torch.tensor(offsets, dtype=torch.int64, device="cpu") 

93 preactivation = causal_conv1d_fn( 

94 op_inputs, op_weight, bias, conv_states=None, activation=None, 

95 query_start_loc_cpu=cpu_offsets, head_num=0, 

96 ) 

97 ctx.save_for_backward(op_inputs, op_weight, preactivation, cpu_offsets) 

98 ctx.input_shape = tuple(inputs.shape) 

99 ctx.has_bias = bias is not None 

100 ctx.input_layout = "BSND" if offsets is None else "TND" 

101 return F.silu(preactivation).reshape_as(inputs) 

102 

103 @staticmethod 

104 def backward( 

105 ctx: Any, grad_output: torch.Tensor, 

106 ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None, None]: 

107 """Differentiate SiLU once inside the native convolution backward. 

108 

109 Args: 

110 ctx: Autograd context holding this call's forward tensors and layout. 

111 grad_output: Gradient of the activated convolution output. 

112 """ 

113 # Keep the optional native dependency lazy in backward as well as forward. 

114 from fla_npu.ops.ascendc import causal_conv1d_bwd # pylint: disable=import-outside-toplevel 

115 

116 inputs, weight, preactivation, cpu_offsets = ctx.saved_tensors 

117 grad_input, grad_weight, grad_bias, _ = causal_conv1d_bwd( 

118 x=inputs, y=preactivation, weight=weight, 

119 dy=grad_output.reshape_as(inputs).contiguous(), 

120 query_start_loc=cpu_offsets, activation=1, input_layout=ctx.input_layout, 

121 ) 

122 return ( 

123 grad_input.reshape(ctx.input_shape), 

124 grad_weight.transpose(0, 1).unsqueeze(1).contiguous(), 

125 grad_bias if ctx.has_bias else None, 

126 None, 

127 ) 

128 

129 

130def _with_history( 

131 inputs: torch.Tensor, 

132 halo: torch.Tensor | None, 

133 info: PackedSequenceInfo | None, 

134 width: int, 

135) -> tuple[torch.Tensor, tuple[int, ...] | None, int]: 

136 """Prepend valid history while preserving dense samples and packed resets.""" 

137 if info is None: 

138 if halo is None: 

139 return inputs, None, 0 

140 # Dense batch samples are independent; a CP cut is not a document reset. 

141 return torch.cat((halo, inputs), dim=1), None, halo.shape[1] 

142 if halo is None: 

143 return inputs, info.local_offsets, 0 

144 prefix = min(width - 1, info.preceding_sample_tokens) 

145 # The empty slice preserves a zero halo gradient when a real document resets. 

146 extended = torch.cat((halo[:, width - 1 - prefix:], inputs), dim=1) 

147 offsets = (0, *(offset + prefix for offset in info.local_offsets[1:])) 

148 return extended, offsets, prefix 

149 

150 

151def _triton_convolution( 

152 inputs: torch.Tensor, 

153 weight: torch.Tensor, 

154 bias: torch.Tensor | None, 

155 info: PackedSequenceInfo | None, 

156 offsets: tuple[int, ...] | None, 

157 use_plan: bool, 

158) -> torch.Tensor: 

159 """Use one FLA entry for dense batches and immutable packed document plans.""" 

160 # OpSelect imports this adapter during registration; defer its dependency loader. 

161 from hyper_parallel.components.ops._dependency import import_fla_module # pylint: disable=import-outside-toplevel 

162 # FLA is optional and must not be imported for the default eager backend. 

163 causal_conv1d = import_fla_module("fla.modules.conv").causal_conv1d 

164 

165 if info is None: 

166 cu_seqlens, cu_seqlens_cpu, chunk_indices = None, None, None 

167 elif use_plan: 

168 plan = info.materialize(inputs.device, 64) 

169 cu_seqlens, cu_seqlens_cpu = plan.cu_seqlens, plan.cu_seqlens_cpu 

170 chunk_indices = plan.chunk_indices 

171 else: 

172 cu_seqlens_cpu = torch.tensor(offsets, dtype=torch.int64, device="cpu") 

173 cu_seqlens = cu_seqlens_cpu.to(device=inputs.device, dtype=torch.int32) 

174 chunk_indices = None 

175 # Contiguous BTD enables the NPU kernel without its strided fallback workspace. 

176 output, _ = causal_conv1d( 

177 inputs.contiguous(), weight=weight[:, 0], bias=bias, activation=None, backend="triton", 

178 cu_seqlens=cu_seqlens, cu_seqlens_cpu=cu_seqlens_cpu, chunk_indices=chunk_indices, 

179 ) 

180 return F.silu(output) 

181 

182 

183def _validate_fused_inputs( 

184 inputs: torch.Tensor, 

185 weight: torch.Tensor, 

186 bias: torch.Tensor | None, 

187 info: PackedSequenceInfo | None, 

188 halo: torch.Tensor | None, 

189) -> None: 

190 """Check layouts before a selected backend is allowed to launch kernels.""" 

191 if inputs.ndim != 3 or any(size < 1 for size in inputs.shape): 

192 raise ValueError("Fused convolution expects nonempty [B,S,C] or packed [1,T,C] inputs.") 

193 if weight.ndim != 3 or weight.shape[:2] != (inputs.shape[-1], 1): 

194 raise ValueError("Fused convolution weight must have shape [C,1,W] matching input channels.") 

195 if bias is not None and bias.shape != (inputs.shape[-1],): 

196 raise ValueError("Fused convolution bias must have shape [C] matching input channels.") 

197 if weight.device != inputs.device or (bias is not None and bias.device != inputs.device): 

198 raise ValueError("Fused convolution input, weight and bias must be on the same device.") 

199 if info is not None and inputs.shape[:2] != (1, info.length): 

200 raise ValueError("Packed convolution expects [1,T,C] matching its token interval.") 

201 if halo is not None: 

202 _validate_fused_history(inputs, halo, weight.shape[-1]) 

203 

204 

205def _validate_fused_history( 

206 inputs: torch.Tensor, 

207 halo: torch.Tensor, 

208 width: int, 

209) -> None: 

210 """Check the received history layout for dense and packed inputs.""" 

211 if halo.shape != (inputs.shape[0], width - 1, inputs.shape[-1]): 

212 raise ValueError("Fused convolution halo has an incompatible shape.") 

213 if halo.dtype != inputs.dtype or halo.device != inputs.device: 

214 raise ValueError("Fused convolution halo must match the input dtype and device.") 

215 

216 

217def fused_causal_conv1d( 

218 inputs: torch.Tensor, 

219 weight: torch.Tensor, 

220 bias: torch.Tensor | None, 

221 info: PackedSequenceInfo | None = None, 

222 halo: torch.Tensor | None = None, 

223 *, 

224 backend: str, 

225 dilation: int = 1, 

226) -> torch.Tensor: 

227 """Apply fused depthwise causal convolution and SiLU to dense or packed tokens. 

228 

229 Args: 

230 inputs: Dense ``[B,S,C]`` or packed ``[1,T,C]`` projected tokens. 

231 weight: The original parameter's local view with shape ``[C,1,W]``. 

232 bias: Optional local bias with shape ``[C]``. 

233 info: Packed document boundaries, or None for independent dense batch samples. 

234 halo: Already exchanged ``[B,W-1,C]`` history for dense batches, or 

235 ``[1,W-1,C]`` history whose valid prefix is selected by packed metadata. 

236 This helper adds no communication. 

237 backend: Explicit ``triton`` or ``ascendc`` selection, with no fallback. 

238 dilation: Source convolution dilation; fused kernels require one. 

239 

240 Returns: 

241 Local SiLU output with the input shape and dtype. 

242 

243 Raises: 

244 ValueError: If the backend, device, dilation, or native dtype/shape is unsupported. 

245 ImportError: If the selected optional kernel package is missing. 

246 

247 Note: 

248 AscendC jointly differentiates SiLU and convolution using a saved low-precision 

249 preactivation. Unlike eager or Triton, its backward does not round the SiLU 

250 gradient to the input dtype before convolution backward. Dense batch samples 

251 remain separate; only packed inputs with explicit metadata are flattened. 

252 """ 

253 if backend not in ("triton", "ascendc"): 

254 raise ValueError(f"Fused convolution requires triton or ascendc, got {backend!r}.") 

255 if dilation != 1: 

256 raise ValueError("Fused convolution requires dilation=1.") 

257 if inputs.device.type != "npu": 

258 raise ValueError("Fused convolution currently supports NPU tensors only.") 

259 _validate_fused_inputs(inputs, weight, bias, info, halo) 

260 width = weight.shape[-1] 

261 if backend == "ascendc": 

262 if width not in (2, 3, 4) or inputs.shape[-1] % 16: 

263 raise ValueError("AscendC convolution requires width 2/3/4 and channels divisible by 16.") 

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

265 raise ValueError("AscendC convolution requires BF16 or FP16 activations.") 

266 if weight.dtype != inputs.dtype or (bias is not None and bias.dtype != inputs.dtype): 

267 raise ValueError("AscendC convolution requires matching input/weight/bias dtypes; no implicit cast.") 

268 extended, offsets, prefix = _with_history(inputs, halo, info, width) 

269 if backend == "triton": 

270 output = _triton_convolution(extended, weight, bias, info, offsets, halo is None) 

271 else: 

272 output = _AscendCConvolution.apply(extended, weight, bias, offsets) 

273 return output[:, prefix:] 

274 

275 

276class _PackedConvTap(torch.autograd.Function): 

277 """Recreate a masked tap in backward instead of retaining its FP32 copy.""" 

278 

279 @staticmethod 

280 def forward( 

281 ctx: Any, extended: torch.Tensor, weight: torch.Tensor, valid: torch.Tensor, offset: int, length: int, 

282 ) -> torch.Tensor: 

283 """Save shared input storage while preserving the eager product precision. 

284 

285 Args: 

286 ctx: Autograd context owning tensors and communication metadata for this invocation. 

287 extended: Input tokens extended by the predecessor halo. 

288 weight: Depthwise convolution weights. 

289 valid: Mask excluding taps that cross document boundaries. 

290 offset: Start of the local output within the extended input. 

291 length: Number of local output tokens. 

292 """ 

293 ctx.save_for_backward(extended, weight, valid) 

294 ctx.offset, ctx.length = offset, length 

295 values = extended[:, offset : offset + length].to(weight.dtype) 

296 values = torch.where(valid[None, :, None], values, 0.0) 

297 return values * weight[None, None, :] 

298 

299 @staticmethod 

300 def backward( 

301 ctx: Any, grad_output: torch.Tensor, 

302 ) -> tuple[torch.Tensor | None, torch.Tensor | None, None, None, None]: 

303 """Rebuild only this tap; differentiable autograd operations retain higher derivatives. 

304 

305 Args: 

306 ctx: Autograd context owning tensors and communication metadata for this invocation. 

307 grad_output: Gradient of the local operator output. 

308 """ 

309 extended, weight, valid = ctx.saved_tensors 

310 grad_extended = grad_weight = None 

311 if ctx.needs_input_grad[0]: 

312 grad_values = grad_output * weight[None, None, :] 

313 grad_values = torch.where(valid[None, :, None], grad_values, 0.0).to(extended.dtype) 

314 grad_extended = F.pad(grad_values, (0, 0, ctx.offset, extended.shape[1] - ctx.offset - ctx.length)) 

315 if ctx.needs_input_grad[1]: 

316 values = extended[:, ctx.offset : ctx.offset + ctx.length].to(weight.dtype) 

317 values = torch.where(valid[None, :, None], values, 0.0) 

318 grad_weight = (grad_output * values).sum(dim=(0, 1)) 

319 return grad_extended, grad_weight, None, None, None 

320 

321 

322def packed_causal_conv1d( 

323 inputs: torch.Tensor, 

324 convolution: nn.Conv1d, 

325 info: PackedSequenceInfo, 

326 halo: torch.Tensor | None = None, 

327 *, 

328 weight: torch.Tensor | None = None, 

329 bias: torch.Tensor | None = None, 

330 backend: str = "eager", 

331) -> torch.Tensor: 

332 """Apply depthwise causal SiLU convolution with exact sample isolation. 

333 

334 Vectorize over tokens rather than loop over samples. Accumulate low-precision 

335 products in FP32; keep FP32/FP64 reference inputs at their original precision. 

336 Masking taps also masks their autograd contribution to an exchanged halo. 

337 Backward reconstructs each masked tap from the shared input rather than 

338 retaining a full accumulation-precision input for every window position. 

339 

340 Args: 

341 inputs: Local projected tokens with shape ``[1, T, C]``. 

342 convolution: Source depthwise, stride-one convolution attributes and parameters. 

343 info: True document boundaries and the current local token interval. 

344 halo: Optional already exchanged causal history; this function adds no communication. 

345 weight: Optional local parameter view with shape ``[C, 1, W]``. 

346 bias: Optional local bias; used with an explicit weight override. 

347 backend: ``eager`` by default, or explicitly ``triton`` / ``ascendc`` 

348 for optional NPU kernels. The selected backend never silently falls back. 

349 

350 Returns: 

351 SiLU output with the input shape and dtype. 

352 

353 Raises: 

354 ValueError: If metadata, depthwise shape, or the selected kernel contract is invalid. 

355 ImportError: If an explicitly selected optional kernel package is unavailable. 

356 """ 

357 validate_conv_backend(backend) 

358 if inputs.ndim != 3 or inputs.shape[:2] != (1, info.length): 

359 raise ValueError("Packed convolution expects [1,T,C] matching its token interval.") 

360 channels = inputs.shape[-1] 

361 if ( 

362 convolution.groups != convolution.in_channels 

363 or convolution.out_channels != convolution.in_channels 

364 or convolution.stride != (1,) 

365 ): 

366 raise ValueError("Packed convolution requires a stride-one depthwise Conv1d.") 

367 if weight is None: 

368 weight, bias = convolution.weight, convolution.bias 

369 width, dilation = convolution.kernel_size[0], convolution.dilation[0] 

370 if weight.shape != (channels, 1, width): 

371 raise ValueError("Packed convolution weight must match the local head channels.") 

372 halo_width = (width - 1) * dilation 

373 if halo is not None and halo.shape != (1, halo_width, channels): 

374 raise ValueError("Packed convolution halo has an incompatible shape.") 

375 if backend != "eager": 

376 return fused_causal_conv1d( 

377 inputs, weight, bias, info, halo, backend=backend, dilation=dilation, 

378 ) 

379 if halo is None: 

380 halo = inputs.new_zeros((1, halo_width, channels)) 

381 extended = torch.cat((halo, inputs), dim=1) 

382 positions = torch.arange(info.start, info.end, device=inputs.device) 

383 boundaries = torch.tensor(info.global_offsets, device=inputs.device) 

384 sample_indices = torch.bucketize(positions, boundaries[1:], right=True) 

385 starts = boundaries[sample_indices] 

386 dtype = torch.float32 if inputs.dtype in (torch.bfloat16, torch.float16) else inputs.dtype 

387 output = torch.zeros_like(inputs, dtype=dtype) 

388 weights = weight[:, 0].to(dtype) 

389 for tap in range(width): 

390 valid = positions - (width - 1 - tap) * dilation >= starts 

391 output = output + _PackedConvTap.apply(extended, weights[:, tap], valid, tap * dilation, info.length) 

392 if bias is not None: 

393 output = output + bias.to(dtype) 

394 return F.silu(output.to(inputs.dtype)) 

395 

396 

397def run_causal_short_conv( 

398 tensor: torch.Tensor, 

399 convolution: nn.Conv1d, 

400 halo: torch.Tensor | None = None, 

401 sequence_info: PackedSequenceInfo | None = None, 

402 backend: str = "eager", 

403) -> torch.Tensor: 

404 """Apply one local ShortConv, optionally with a preceding-rank halo. 

405 

406 Args: 

407 tensor: Tensor to reshape or redistribute without changing token order. 

408 convolution: Depthwise causal convolution module providing weights and activation. 

409 halo: Optional predecessor tokens required by the convolution. 

410 sequence_info: Immutable document metadata for this local token interval. 

411 backend: Explicit local operator implementation to dispatch. 

412 """ 

413 if backend != "eager": 

414 return fused_causal_conv1d( 

415 tensor, convolution.weight, convolution.bias, sequence_info, halo, 

416 backend=backend, dilation=convolution.dilation[0]) 

417 if sequence_info is not None: 

418 return packed_causal_conv1d(tensor, convolution, sequence_info, halo) 

419 if halo is None: 

420 conv_input = tensor.transpose(1, 2) 

421 padding = convolution.padding 

422 else: 

423 conv_input = torch.cat((halo, tensor), dim=1).transpose(1, 2) 

424 padding = 0 

425 output = F.conv1d( # pylint: disable=not-callable 

426 input=conv_input, 

427 weight=convolution.weight, 

428 bias=convolution.bias, 

429 stride=convolution.stride, 

430 padding=padding, 

431 dilation=convolution.dilation, 

432 groups=tensor.shape[-1], 

433 ) 

434 if halo is None: 

435 output = output[:, :, : tensor.shape[1]] 

436 return F.silu(output).transpose(1, 2)