Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / tools / dryrun / ops / fake_kernels.py: 100%

77 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"""Built-in shape-only FakeTensor kernel implementations for dry-run. 

16 

17Every kernel below derives output shapes and dtypes only; gradients mirror the 

18differentiated forward inputs without copying values or launching device work. 

19""" 

20 

21from typing import Any, Optional 

22 

23import torch 

24 

25from hyper_parallel.components.functional import lightning_indexer as lightning_indexer_ops 

26from hyper_parallel.components.functional import sparse_flash_mla as sparse_flash_mla_ops 

27from hyper_parallel.tools.dryrun.ops.registry import ( 

28 register_fake_ops, 

29 register_lazy_op_loader, 

30) 

31 

32 

33# --------------------------------------------------------------------------- 

34# Host memory kernels 

35# --------------------------------------------------------------------------- 

36 

37def pin_memory_fake(self: torch.Tensor, device: Optional[Any] = None) -> torch.Tensor: 

38 """Derive shape for ``aten::_pin_memory`` without touching a live device runtime. 

39 

40 Logically a pinned mirror occupies the same host bytes as a regular CPU tensor. 

41 """ 

42 del device 

43 return torch.empty_like(self) 

44 

45 

46HOST_FAKE_KERNELS = { 

47 "aten::_pin_memory": pin_memory_fake, 

48} 

49 

50 

51# --------------------------------------------------------------------------- 

52# Ascend custom operator kernels 

53# --------------------------------------------------------------------------- 

54 

55def sparse_attention_grad_fake( 

56 query: torch.Tensor, 

57 key: torch.Tensor, 

58 value: torch.Tensor, 

59 sparse_indices: Any, 

60 d_out: Any, 

61 out: Any, 

62 softmax_max: Any, 

63 softmax_sum: Any, 

64 scale_value: float, 

65 sparse_block_size: int, 

66 query_rope: Optional[torch.Tensor] = None, 

67 key_rope: Optional[torch.Tensor] = None, 

68 actual_seq_qlen: Any = None, 

69 actual_seq_kvlen: Any = None, 

70 layout: str = "BSND", 

71 sparse_mode: int = 3, 

72 pre_tokens: int = 9223372036854775807, 

73 next_tokens: int = 9223372036854775807, 

74 attention_mode: int = 0, 

75 deterministic: bool = False, 

76) -> tuple[torch.Tensor, ...]: 

77 """Gradients of query/key/value/rope mirror the forward inputs.""" 

78 del ( 

79 sparse_indices, d_out, out, softmax_max, softmax_sum, scale_value, 

80 sparse_block_size, actual_seq_qlen, actual_seq_kvlen, layout, 

81 sparse_mode, pre_tokens, next_tokens, attention_mode, deterministic, 

82 ) 

83 grad_query_rope = ( 

84 torch.empty_like(query_rope) if query_rope is not None else torch.empty_like(query) 

85 ) 

86 grad_key_rope = ( 

87 torch.empty_like(key_rope) if key_rope is not None else torch.empty_like(key) 

88 ) 

89 return ( 

90 torch.empty_like(query), 

91 torch.empty_like(key), 

92 torch.empty_like(value), 

93 grad_query_rope, 

94 grad_key_rope, 

95 ) 

96 

97 

98def indexer_kl_loss_grad_fake( 

99 query: torch.Tensor, 

100 key: torch.Tensor, 

101 query_index: torch.Tensor, 

102 key_index: torch.Tensor, 

103 weights: torch.Tensor, 

104 sparse_indices: Any, 

105 softmax_max: Any, 

106 softmax_sum: Any, 

107 scale_value: float, 

108 query_rope: Optional[torch.Tensor] = None, 

109 key_rope: Optional[torch.Tensor] = None, 

110 actual_seq_qlen: Any = None, 

111 actual_seq_klen: Any = None, 

112 layout: str = "BSND", 

113 sparse_mode: int = 3, 

114 pre_tokens: int = 2147483647, 

115 next_tokens: int = 2147483647, 

116 deterministic: bool = False, 

117 sparse_block_size: int = 1, 

118) -> tuple[torch.Tensor, ...]: 

119 """Indexer gradients mirror their weights; the inner loss is scalar.""" 

120 del ( 

121 query, key, sparse_indices, softmax_max, softmax_sum, scale_value, 

122 query_rope, key_rope, actual_seq_qlen, actual_seq_klen, layout, 

123 sparse_mode, pre_tokens, next_tokens, deterministic, sparse_block_size, 

124 ) 

125 return ( 

126 torch.empty_like(query_index), 

127 torch.empty_like(key_index), 

128 torch.empty_like(weights), 

129 torch.empty((), dtype=torch.float32, device=weights.device), 

130 ) 

131 

132 

133def aggregate_hidden_grad_fake( 

134 grad_output: torch.Tensor, 

135 input: torch.Tensor, # pylint: disable=redefined-builtin 

136 weight: torch.Tensor, 

137 mask: Any = None, 

138) -> tuple[torch.Tensor, torch.Tensor]: 

139 """Gradients mirror the differentiated forward inputs.""" 

140 del grad_output, mask 

141 return torch.empty_like(input), torch.empty_like(weight) 

142 

143 

144def mhc_pre_grad_fake( 

145 x: torch.Tensor, 

146 phi: torch.Tensor, 

147 alpha: torch.Tensor, 

148 h_in_grad: Any, 

149 h_post_grad: Any, 

150 h_comb_before_grad: Any, 

151 inv_rms: Any, 

152 mm_res: Any, 

153 h_pre: Any, 

154 h_post: Any, 

155 gamma: Optional[torch.Tensor] = None, 

156 hc_eps: float = 1.0e-6, 

157 grad_x_post: Any = None, 

158) -> tuple[torch.Tensor, ...]: 

159 """Gradients follow ``(x, phi, alpha, beta, gamma)`` of the forward.""" 

160 del ( 

161 h_in_grad, h_post_grad, h_comb_before_grad, inv_rms, mm_res, 

162 h_pre, h_post, hc_eps, grad_x_post, 

163 ) 

164 grad_gamma = ( 

165 torch.empty_like(gamma) if gamma is not None else torch.empty_like(alpha) 

166 ) 

167 return ( 

168 torch.empty_like(x), 

169 torch.empty_like(phi), 

170 torch.empty_like(alpha), 

171 torch.empty((phi.shape[0],), dtype=alpha.dtype, device=alpha.device), 

172 grad_gamma, 

173 ) 

174 

175 

176def flash_attention_score_enhance_fake( 

177 query: torch.Tensor, 

178 key: torch.Tensor, 

179 value: torch.Tensor, 

180 head_num: int, 

181 input_layout: str, 

182 pse: Any = None, 

183 padding_mask: Any = None, 

184 atten_mask: Any = None, 

185 sink_tensor: Any = None, 

186 query_rope: Any = None, 

187 key_rope: Any = None, 

188 scale: float = 1.0, 

189 keep_prob: float = 1.0, 

190 pre_tokens: int = 2147483647, 

191 next_tokens: int = 2147483647, 

192 inner_precise: int = 0, 

193 prefix: Any = None, 

194 actual_seq_qlen: Any = None, 

195 actual_seq_kvlen: Any = None, 

196 sparse_mode: int = 0, 

197 sink_num: int = 0, 

198 pse_type: int = 1, 

199 softmaxOutLayout: str = "", # pylint: disable=invalid-name 

200 q_start_idx: Any = None, 

201 kv_start_idx: Any = None, 

202) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

203 """Attention output matches the query; LSE carries per-head scalars.""" 

204 del ( 

205 key, value, pse, padding_mask, atten_mask, sink_tensor, query_rope, 

206 key_rope, scale, keep_prob, pre_tokens, next_tokens, inner_precise, 

207 prefix, actual_seq_qlen, actual_seq_kvlen, sparse_mode, sink_num, 

208 pse_type, softmaxOutLayout, q_start_idx, kv_start_idx, 

209 ) 

210 if input_layout == "TND": 

211 tokens = query.shape[0] 

212 elif input_layout == "BNSD": 

213 tokens = query.shape[0] * query.shape[2] 

214 else: 

215 tokens = query.shape[0] * query.shape[1] 

216 lse_shape = (head_num, int(tokens), 8) 

217 device = query.device 

218 return ( 

219 torch.empty_like(query), 

220 torch.empty(lse_shape, dtype=torch.float32, device=device), 

221 torch.empty(lse_shape, dtype=torch.float32, device=device), 

222 ) 

223 

224 

225def flash_attention_score_grad_enhance_fake( 

226 query: torch.Tensor, 

227 key: torch.Tensor, 

228 value: torch.Tensor, 

229 dy: torch.Tensor, 

230 head_num: int, 

231 input_layout: str, 

232 pse: Optional[torch.Tensor] = None, 

233 padding_mask: Any = None, 

234 atten_mask: Any = None, 

235 softmax_max: Any = None, 

236 softmax_sum: Any = None, 

237 softmax_in: Any = None, 

238 attention_in: Any = None, 

239 sink_tensor: Optional[torch.Tensor] = None, 

240 query_rope: Any = None, 

241 key_rope: Any = None, 

242 scale_value: float = 1.0, 

243 keep_prob: float = 1.0, 

244 pre_tokens: int = 2147483647, 

245 next_tokens: int = 2147483647, 

246 inner_precise: int = 0, 

247 prefix: Any = None, 

248 actual_seq_qlen: Any = None, 

249 actual_seq_kvlen: Any = None, 

250 sparse_mode: int = 0, 

251 sink_num: int = 0, 

252 pse_type: int = 1, 

253 softmaxInLayout: str = "", # pylint: disable=invalid-name 

254 q_start_idx: Any = None, 

255 kv_start_idx: Any = None, 

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

257 """Attention backward mirrors query, key, value, and optional pse/sink.""" 

258 del ( 

259 dy, head_num, input_layout, padding_mask, atten_mask, softmax_max, 

260 softmax_sum, softmax_in, attention_in, query_rope, key_rope, 

261 scale_value, keep_prob, pre_tokens, next_tokens, inner_precise, 

262 prefix, actual_seq_qlen, actual_seq_kvlen, sparse_mode, sink_num, 

263 pse_type, softmaxInLayout, q_start_idx, kv_start_idx, 

264 ) 

265 grad_pse = torch.empty_like(pse) if pse is not None else None 

266 grad_sink = torch.empty_like(sink_tensor) if sink_tensor is not None else None 

267 return ( 

268 torch.empty_like(query), 

269 torch.empty_like(key), 

270 torch.empty_like(value), 

271 grad_pse, 

272 grad_sink, 

273 ) 

274 

275 

276CUSTOM_FAKE_KERNELS = { 

277 "custom::npu_sparse_flash_attention_grad_enhance": sparse_attention_grad_fake, 

278 "custom::npu_sparse_lightning_indexer_grad_kl_loss_enhance": indexer_kl_loss_grad_fake, 

279 "custom::npu_aggregate_hidden_grad": aggregate_hidden_grad_fake, 

280 "custom::npu_manifold_constrained_hyper_connection_pre_grad": mhc_pre_grad_fake, 

281 "custom::npu_flash_attention_score_enhance": flash_attention_score_enhance_fake, 

282 "custom::npu_flash_attention_score_grad_enhance": flash_attention_score_grad_enhance_fake, 

283} 

284 

285 

286# --------------------------------------------------------------------------- 

287# CANN transformer operator kernels 

288# --------------------------------------------------------------------------- 

289 

290def cann_sparse_mla_metadata_fake( 

291 num_heads_q: int, 

292 num_heads_kv: int, 

293 head_dim: int, 

294 **kwargs: Any, 

295) -> torch.Tensor: 

296 """Derive shape for ``cann_ops_transformer::sparse_flash_mla_metadata``.""" 

297 del num_heads_q, num_heads_kv, head_dim, kwargs 

298 return torch.empty((1,), device="meta", dtype=torch.int64) 

299 

300 

301def cann_sparse_mla_forward_fake( 

302 q: torch.Tensor, 

303 *, 

304 return_softmax_lse: bool = False, 

305 layout_q: str = "BSND", 

306 **kwargs: Any, 

307) -> tuple[torch.Tensor, torch.Tensor]: 

308 """Derive output and LSE shapes for ``cann_ops_transformer::sparse_flash_mla``.""" 

309 del return_softmax_lse, kwargs 

310 if layout_q == "TND": 

311 length, heads = q.shape[:2] 

312 lse_shape = (heads, length) 

313 else: 

314 batch, length, heads = q.shape[:3] 

315 lse_shape = (batch, heads, length) 

316 return torch.empty_like(q), q.new_empty(lse_shape, dtype=torch.float32) 

317 

318 

319def cann_sparse_mla_backward_fake( 

320 q: torch.Tensor, 

321 dout: torch.Tensor, 

322 attn_out: torch.Tensor, 

323 softmax_lse: torch.Tensor, 

324 *, 

325 ori_kv: Optional[torch.Tensor] = None, 

326 cmp_kv: Optional[torch.Tensor] = None, 

327 sinks: Optional[torch.Tensor] = None, 

328 **kwargs: Any, 

329) -> tuple[torch.Tensor, ...]: 

330 """Derive gradient shapes for ``cann_ops_transformer::sparse_flash_mla_grad``.""" 

331 del dout, attn_out, softmax_lse, kwargs 

332 empty = q.new_empty((0,)) 

333 return ( 

334 torch.empty_like(q), 

335 torch.empty_like(ori_kv) if ori_kv is not None else empty, 

336 torch.empty_like(cmp_kv) if cmp_kv is not None else empty, 

337 torch.empty_like(sinks) if sinks is not None else empty, 

338 empty, 

339 empty, 

340 ) 

341 

342 

343def cann_lightning_indexer_metadata_fake( 

344 num_heads_q: int, 

345 num_heads_k: int, 

346 head_dim: int, 

347 topk: int, 

348 **kwargs: Any, 

349) -> torch.Tensor: 

350 """Derive shape for ``cann_ops_transformer::lightning_indexer_metadata``.""" 

351 del num_heads_q, num_heads_k, head_dim, topk, kwargs 

352 return torch.empty((1,), device="meta", dtype=torch.int64) 

353 

354 

355def cann_lightning_indexer_fake( 

356 q: torch.Tensor, 

357 k: torch.Tensor, 

358 weights: torch.Tensor, 

359 topk: int, 

360 *, 

361 layout_q: str = "BSND", 

362 **kwargs: Any, 

363) -> tuple[torch.Tensor, torch.Tensor]: 

364 """Derive index and auxiliary shapes for ``cann_ops_transformer::lightning_indexer``.""" 

365 del k, weights, kwargs 

366 if layout_q == "TND": 

367 indices_shape = (q.shape[0], 1, topk) 

368 else: 

369 indices_shape = (q.shape[0], q.shape[1], 1, topk) 

370 indices = torch.empty(indices_shape, device=q.device, dtype=torch.int32) 

371 auxiliary = torch.empty(indices_shape, device=q.device, dtype=torch.float32) 

372 return indices, auxiliary 

373 

374 

375CANN_FAKE_KERNELS = { 

376 "cann_ops_transformer::sparse_flash_mla_metadata": cann_sparse_mla_metadata_fake, 

377 "cann_ops_transformer::sparse_flash_mla": cann_sparse_mla_forward_fake, 

378 "cann_ops_transformer::sparse_flash_mla_grad": cann_sparse_mla_backward_fake, 

379 "cann_ops_transformer::lightning_indexer_metadata": cann_lightning_indexer_metadata_fake, 

380 "cann_ops_transformer::lightning_indexer": cann_lightning_indexer_fake, 

381} 

382 

383_CANN_LAZY_LOADERS = ( 

384 (sparse_flash_mla_ops, "_load_attention_ops"), 

385 (lightning_indexer_ops, "_load_indexer_op"), 

386 (lightning_indexer_ops, "_load_indexer_metadata_op"), 

387) 

388 

389 

390def register_cann_fake_ops() -> None: 

391 """Register shape-only fake kernels for loaded CANN sparse-attention operators.""" 

392 register_fake_ops(CANN_FAKE_KERNELS, allow_missing=True, allow_existing=True) 

393 

394 

395def register_builtin_fake_ops() -> None: 

396 """Register all built-in host, Ascend custom, and CANN fake kernels.""" 

397 for module, attr_name in _CANN_LAZY_LOADERS: 

398 register_lazy_op_loader(module, attr_name, register_cann_fake_ops) 

399 register_fake_ops(HOST_FAKE_KERNELS, allow_missing=False, allow_existing=True) 

400 register_fake_ops(CUSTOM_FAKE_KERNELS, allow_missing=True, allow_existing=True) 

401 register_cann_fake_ops() 

402 

403 

404__all__ = [ 

405 "CANN_FAKE_KERNELS", 

406 "CUSTOM_FAKE_KERNELS", 

407 "HOST_FAKE_KERNELS", 

408 "aggregate_hidden_grad_fake", 

409 "cann_lightning_indexer_fake", 

410 "cann_lightning_indexer_metadata_fake", 

411 "cann_sparse_mla_backward_fake", 

412 "cann_sparse_mla_forward_fake", 

413 "cann_sparse_mla_metadata_fake", 

414 "flash_attention_score_enhance_fake", 

415 "flash_attention_score_grad_enhance_fake", 

416 "indexer_kl_loss_grad_fake", 

417 "mhc_pre_grad_fake", 

418 "pin_memory_fake", 

419 "register_builtin_fake_ops", 

420 "register_cann_fake_ops", 

421 "sparse_attention_grad_fake", 

422]