Merged
feat(interpreter): Add test case for interpreter #5418
dingbo929Add on Aug 13
feat(interpreter): Add test case for interpreter #5418
Merged
dingbo929Add on Aug 13
Total: 26 files changed+5584-5
@@ -272,14 +272,22 @@ def pytest_collection_modifyitems(config, items):
272 item_path = str(first_item.fspath)272 item_path = str(first_item.fspath)
273 has_ut = "ut" in item_path.lower()273 has_ut = "ut" in item_path.lower()
274 274 
275+ def _is_verify_case(item):
276+ # Host pass_verify 用例:python/tests/ut/interpreter(原 tests/verify)
277+ return "ut/interpreter" in str(item.fspath).lower().replace("\\", "/")
278+ 
275 if has_ut:279 if has_ut:
276 filtered_items = items280 filtered_items = items
277 else:281 else:
278- # 先根据torch_npu接口获取soc version282+ verify_items = [item for item in items if _is_verify_case(item)]
279- target_soc = _get_soc_version()283+ other_items = [item for item in items if not _is_verify_case(item)]
280- 284+ # ut/interpreter 看护 Host pass_verify / SIM,不依赖 NPU soc 探测
281- # 筛选用例285+ if other_items:
282- filtered_items = [item for item in items if _is_case_match_soc(item, target_soc)]286+ target_soc = _get_soc_version()
287+ filtered_items = [item for item in other_items if _is_case_match_soc(item, target_soc)]
288+ filtered_items.extend(verify_items)
289+ else:
290+ filtered_items = verify_items
283 291 
284 # 根据卡数要求过滤用例292 # 根据卡数要求过滤用例
285 cards_per_case = config.getoption("--cards-per-case", 1)293 cards_per_case = config.getoption("--cards-per-case", 1)
@@ -104,6 +104,10 @@ line-length = 120
104[tool.ruff.lint]104[tool.ruff.lint]
105select = ["E", "W", "F", "I", "N"]105select = ["E", "W", "F", "I", "N"]
106 106 
107+# Vendored algorithm code keeps math-style names (T/D/L/B, torch.nn.functional as F, etc.).
108+[tool.ruff.lint.per-file-ignores]
109+"python/tests/ut/interpreter/_ops/**" = ["N803", "N806", "N812", "E741"]
110+ 
107[tool.ruff.lint.isort]111[tool.ruff.lint.isort]
108known-first-party = ["common", "pypto"]112known-first-party = ["common", "pypto"]
109force-sort-within-sections = true113force-sort-within-sections = true
@@ -0,0 +1,9 @@
1+# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+# -----------------------------------------------------------------------------------------------------------
9+"""PyPTO ut/interpreter: one minimal diversified operator case per file."""
@@ -0,0 +1 @@
1+"""Vendored op implementations and goldens for ut/interpreter CI (no pypto-gym)."""
@@ -0,0 +1,168 @@
1+# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+# -----------------------------------------------------------------------------------------------------------
9+# Vendored into pypto ut/interpreter for CI (no pypto-gym dependency).
10+ 
11+"""
12+Golden reference implementation for apply_adam_w_v2.
13+ 
14+Algorithm: AdamW single-step update with bias correction (Loshchilov & Hutter, 2019).
15+ 
16+ m_t = beta1 * m + (1 - beta1) * g
17+ v_t = beta2 * v + (1 - beta2) * g * g
18+ m_hat = m_t / (1 - beta1**t)
19+ v_hat = v_t / (1 - beta2**t)
20+ update = m_hat / (sqrt(v_hat) + eps) + weight_decay * weight
21+ w_new = weight - lr * update
22+ 
23+Inputs:
24+ weight, grad : [7168, K], bfloat16 OR float32
25+ m, v : [7168, K], float32
26+ beta1, beta2, lr, weight_decay, eps : python float
27+ step : python int (>=1)
28+ 
29+Outputs (returned as a tuple, also functionally equivalent to in-place update):
30+ weight_out : same dtype as input weight
31+ m_out : float32
32+ v_out : float32
33+ 
34+Mixed precision contract: weight/grad in bf16 are cast up to fp32 internally,
35+all math is done in fp32, weight is cast back to its original dtype on return.
36+ 
37+Confidence: ***** (direct mapping of the AdamW formula, no algorithmic ambiguity).
38+"""
39+from __future__ import annotations
40+ 
41+from typing import Tuple
42+ 
43+import torch
44+ 
45+ 
46+def apply_adam_w_v2_golden(
47+ weight: torch.Tensor,
48+ grad: torch.Tensor,
49+ m: torch.Tensor,
50+ v: torch.Tensor,
51+ beta1: float,
52+ beta2: float,
53+ lr: float,
54+ weight_decay: float,
55+ eps: float,
56+ step: int,
57+) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
58+ """Pure-PyTorch AdamW single-step update with bias correction."""
59+ # --- shape / dtype guards ---
60+ assert weight.shape == grad.shape == m.shape == v.shape, (
61+ f"shape mismatch: weight={weight.shape} grad={grad.shape} "
62+ f"m={m.shape} v={v.shape}"
63+ )
64+ assert weight.dtype in (torch.bfloat16, torch.float32), (
65+ f"weight dtype must be bfloat16 or float32, got {weight.dtype}"
66+ )
67+ assert grad.dtype == weight.dtype, (
68+ f"grad dtype {grad.dtype} must match weight dtype {weight.dtype}"
69+ )
70+ assert m.dtype == torch.float32, f"m dtype must be float32, got {m.dtype}"
71+ assert v.dtype == torch.float32, f"v dtype must be float32, got {v.dtype}"
72+ assert isinstance(step, int) and step >= 1, f"step must be int >= 1, got {step}"
73+ 
74+ weight_dtype = weight.dtype
75+ 
76+ # --- cast inputs to fp32 accumulators ---
77+ w_f32 = weight.to(torch.float32)
78+ g_f32 = grad.to(torch.float32)
79+ m_f32 = m # already fp32
80+ v_f32 = v # already fp32
81+ 
82+ # --- bias correction scalars (host side) ---
83+ bc1 = 1.0 - (beta1 ** step)
84+ bc2 = 1.0 - (beta2 ** step)
85+ 
86+ # --- moment updates ---
87+ m_new = beta1 * m_f32 + (1.0 - beta1) * g_f32
88+ v_new = beta2 * v_f32 + (1.0 - beta2) * (g_f32 * g_f32)
89+ 
90+ # --- bias-corrected estimates ---
91+ m_hat = m_new / bc1
92+ v_hat = v_new / bc2
93+ 
94+ # --- AdamW update (decoupled weight decay) ---
95+ update = m_hat / (torch.sqrt(v_hat) + eps) + weight_decay * w_f32
96+ w_new_f32 = w_f32 - lr * update
97+ 
98+ # --- cast weight back to original dtype; m/v stay in fp32 ---
99+ weight_out = w_new_f32.to(weight_dtype)
100+ m_out = m_new
101+ v_out = v_new
102+ 
103+ return weight_out, m_out, v_out
104+ 
105+ 
106+# ----------------------------------------------------------------------
107+# Smoke test
108+# ----------------------------------------------------------------------
109+def _smoke_test() -> None:
110+ torch.manual_seed(0)
111+ 
112+ # Small case from SPEC P0: [7168, 2048]
113+ shape = (7168, 2048)
114+ 
115+ for w_dtype in (torch.float32, torch.bfloat16):
116+ weight = torch.randn(shape, dtype=w_dtype) * 0.02
117+ grad = torch.randn(shape, dtype=w_dtype) * 0.01
118+ m = torch.zeros(shape, dtype=torch.float32)
119+ v = torch.zeros(shape, dtype=torch.float32)
120+ 
121+ beta1, beta2 = 0.9, 0.999
122+ lr, weight_decay, eps = 1e-3, 0.01, 1e-8
123+ step = 1
124+ 
125+ w_out, m_out, v_out = apply_adam_w_v2_golden(
126+ weight, grad, m, v, beta1, beta2, lr, weight_decay, eps, step
127+ )
128+ 
129+ # --- shape / dtype checks ---
130+ assert w_out.shape == shape, f"weight_out shape mismatch: {w_out.shape}"
131+ assert m_out.shape == shape and v_out.shape == shape
132+ assert w_out.dtype == w_dtype, f"weight_out dtype: {w_out.dtype} != {w_dtype}"
133+ assert m_out.dtype == torch.float32 and v_out.dtype == torch.float32
134+ 
135+ # --- numerical sanity: no NaN / Inf ---
136+ assert torch.isfinite(w_out.float()).all(), "weight_out contains NaN/Inf"
137+ assert torch.isfinite(m_out).all(), "m_out contains NaN/Inf"
138+ assert torch.isfinite(v_out).all(), "v_out contains NaN/Inf"
139+ 
140+ # --- analytic check at step=1, m=v=0 ---
141+ g_f32 = grad.to(torch.float32)
142+ w_f32 = weight.to(torch.float32)
143+ expected_update = g_f32 / (torch.sqrt(g_f32 * g_f32) + eps) + weight_decay * w_f32
144+ expected_w = (w_f32 - lr * expected_update).to(w_dtype)
145+ max_err = (w_out.float() - expected_w.float()).abs().max().item()
146+ atol = 1e-4 if w_dtype == torch.float32 else 4e-3 # bf16 round-trip
147+ assert max_err <= atol, (
148+ f"[{w_dtype}] analytic check failed: max_err={max_err} > atol={atol}"
149+ )
150+ 
151+ print(f"[{w_dtype}] shape={shape} step={step} OK (max_err={max_err:.3e})")
152+ 
153+ # --- multi-step bias correction sanity (step=10) ---
154+ weight = torch.randn(shape, dtype=torch.float32) * 0.02
155+ grad = torch.randn(shape, dtype=torch.float32) * 0.01
156+ m = torch.randn(shape, dtype=torch.float32) * 0.001
157+ v = torch.randn(shape, dtype=torch.float32).abs() * 1e-6
158+ w_out, m_out, v_out = apply_adam_w_v2_golden(
159+ weight, grad, m, v, 0.9, 0.999, 1e-3, 0.01, 1e-8, step=10
160+ )
161+ assert torch.isfinite(w_out).all() and torch.isfinite(m_out).all() and torch.isfinite(v_out).all()
162+ print(f"[fp32] step=10 multi-step OK (max|w|={w_out.abs().max().item():.3e})")
163+ 
164+ print("All smoke tests passed.")
165+ 
166+ 
167+if __name__ == "__main__":
168+ _smoke_test()
@@ -0,0 +1 @@
1+"""Vendored BSA op implementations and goldens for ut/interpreter CI."""
@@ -0,0 +1,176 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+# Vendored into pypto ut/interpreter for CI (no pypto-gym dependency).
12+ 
13+"""
14+BSA Forward Golden Reference Implementation
15+ 
16+Pure PyTorch forward reference, mathematically equivalent to AscendC BSA.
17+"""
18+ 
19+from collections import namedtuple
20+ 
21+import torch
22+ 
23+from .bsa_common import (
24+ BSAForwardResult,
25+ _block_ranges,
26+ _is_valid_mask,
27+ _resolve_defaults,
28+)
29+ 
30+BSAForwardInputs = namedtuple(
31+ 'BSAForwardInputs',
32+ ['query', 'key', 'value', 'block_sparse_mask',
33+ 'block_shape_x', 'block_shape_y',
34+ 'actual_seq_lengths', 'actual_seq_lengths_kv',
35+ 'scale_value', 'cfg'])
36+ 
37+_ProcessQBlockConfig = namedtuple('_ProcessQBlockConfig',
38+ ['k_f', 'v_f', 'block_sparse_mask', 'b_idx', 'h_q', 'h_kv',
39+ 'skv_val', 'by', 'scale', 'ftype'])
40+ 
41+ 
42+# --- Online softmax update helpers ---
43+def _softmax_first_block(s_scores, v_block, ftype):
44+ """Online softmax for the first valid KV block."""
45+ block_max = s_scores.max(dim=-1).values
46+ p_probs = torch.exp(s_scores - block_max.unsqueeze(-1))
47+ block_sum = p_probs.sum(dim=-1)
48+ block_out = torch.matmul(p_probs, v_block)
49+ return block_max, block_sum, block_out
50+ 
51+ 
52+def _softmax_accumulate(s_scores, v_block, block_max, block_sum, block_out):
53+ """Online softmax for subsequent valid KV blocks."""
54+ cur_max = s_scores.max(dim=-1).values
55+ new_max = torch.maximum(block_max, cur_max)
56+ correction = torch.exp(block_max - new_max)
57+ p_probs = torch.exp(s_scores - new_max.unsqueeze(-1))
58+ block_sum = block_sum * correction + p_probs.sum(dim=-1)
59+ block_out = block_out * correction.unsqueeze(-1) + torch.matmul(p_probs, v_block)
60+ return new_max, block_sum, block_out
61+ 
62+ 
63+def _process_q_block(q_block, u, config):
64+ """Process one Q block's forward pass across all valid KV blocks.
65+ 
66+ Returns (block_out, block_max, block_sum, has_valid) or None if no valid KV.
67+ """
68+ k_f = config.k_f
69+ v_f = config.v_f
70+ block_sparse_mask = config.block_sparse_mask
71+ b_idx = config.b_idx
72+ h_q = config.h_q
73+ h_kv = config.h_kv
74+ skv_val = config.skv_val
75+ by = config.by
76+ scale = config.scale
77+ ftype = config.ftype
78+ 
79+ block_max = None
80+ block_sum = None
81+ block_out = None
82+ has_valid = False
83+ 
84+ for v, k_start, k_end in _block_ranges(skv_val, by, skv_val):
85+ if not _is_valid_mask(block_sparse_mask, b_idx, h_q, u, v):
86+ continue
87+ 
88+ k_block = k_f[b_idx, h_kv, k_start:k_end, :]
89+ v_block = v_f[b_idx, h_kv, k_start:k_end, :]
90+ s_scores = torch.matmul(q_block, k_block.t()) * scale
91+ 
92+ if not has_valid:
93+ block_max, block_sum, block_out = _softmax_first_block(s_scores, v_block, ftype)
94+ has_valid = True
95+ else:
96+ block_max, block_sum, block_out = _softmax_accumulate(
97+ s_scores, v_block, block_max, block_sum, block_out)
98+ 
99+ if has_valid:
100+ return block_out, block_max, block_sum, True
101+ return None
102+ 
103+ 
104+# --- Forward ---
105+def bsa_forward_golden(inputs):
106+ """BSA Forward Golden Reference (Pure PyTorch, BNSD layout, FP16).
107+ 
108+ Implements block sparse attention with online softmax:
109+ S_uv = Q_u @ K_v^T / sqrt(d), M[u][v] = 1
110+ p_uv = exp(S_uv - LSE)
111+ O_u = sum_v( p_uv @ V_v ), for valid v
112+ 
113+ Args:
114+ inputs: BSAForwardInputs namedtuple containing:
115+ query, key, value, block_sparse_mask,
116+ block_shape_x, block_shape_y,
117+ actual_seq_lengths, actual_seq_lengths_kv,
118+ scale_value, cfg
119+ """
120+ query = inputs.query
121+ key = inputs.key
122+ value = inputs.value
123+ block_sparse_mask = inputs.block_sparse_mask
124+ block_shape_x = inputs.block_shape_x
125+ block_shape_y = inputs.block_shape_y
126+ actual_seq_lengths = inputs.actual_seq_lengths
127+ actual_seq_lengths_kv = inputs.actual_seq_lengths_kv
128+ scale_value = inputs.scale_value
129+ cfg = inputs.cfg
130+ 
131+ resolved = _resolve_defaults(
132+ query, key, block_shape_x, block_shape_y,
133+ actual_seq_lengths, actual_seq_lengths_kv, scale_value, cfg)
134+ b = resolved.b
135+ hq = resolved.hq
136+ hkv = resolved.hkv
137+ sq = resolved.sq
138+ d = resolved.d
139+ bx = resolved.bx
140+ by = resolved.by
141+ scale = resolved.scale
142+ asq = resolved.asq
143+ askv = resolved.askv
144+ 
145+ dtype = query.dtype
146+ ftype = cfg.accum_torch_dtype
147+ group = hq // hkv
148+ 
149+ o_out = torch.zeros(b, hq, sq, d, dtype=ftype, device=query.device)
150+ softmax_lse = torch.full([b, hq, sq], cfg.lse_init, dtype=ftype, device=query.device)
151+ 
152+ q_f, k_f, v_f = query.to(ftype), key.to(ftype), value.to(ftype)
153+ 
154+ for flat_idx in range(b * hq):
155+ b_idx = flat_idx // hq
156+ h_q = flat_idx % hq
157+ h_kv = h_q // group
158+ 
159+ sq_val = asq[b_idx].item()
160+ skv_val = askv[b_idx].item()
161+ 
162+ for u, q_start, q_end in _block_ranges(sq_val, bx, sq_val):
163+ q_block = q_f[b_idx, h_q, q_start:q_end, :]
164+ result = _process_q_block(
165+ q_block, u,
166+ _ProcessQBlockConfig(
167+ k_f=k_f, v_f=v_f, block_sparse_mask=block_sparse_mask,
168+ b_idx=b_idx, h_q=h_q, h_kv=h_kv, skv_val=skv_val,
169+ by=by, scale=scale, ftype=ftype))
170+ 
171+ if result is not None:
172+ block_out, block_max, block_sum, _ = result
173+ o_out[b_idx, h_q, q_start:q_end, :] = block_out / block_sum.unsqueeze(-1)
174+ softmax_lse[b_idx, h_q, q_start:q_end] = block_max + torch.log(block_sum)
175+ 
176+ return BSAForwardResult(o=o_out.to(dtype), lse=softmax_lse)
@@ -0,0 +1,432 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You can not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+# Vendored into pypto ut/interpreter for CI (no pypto-gym dependency).
12+ 
13+"""
14+BSA Forward PyPTO Kernel Implementation (Single-Phase, Auto-Configured)
15+ 
16+Single jit kernel with nested loops:
17+ - Outer loop (LOOP_fwd_outer): TOTAL_OUTER = bh * num_qb iterations, parallel
18+ - Inner loop (LOOP_fwd_kblk): max_sel iterations, sequential (online softmax)
19+ 
20+Each outer iteration processes one Q block across all its valid KV blocks,
21+computing the full online softmax accumulation (m, l, o) and writing the
22+final O and LSE outputs.
23+ 
24+Auto-Configuration:
25+ When Sq >= 1024, the kernel uses l1=64/sched=1 for better S1024 performance.
26+ For Sq < 1024, defaults to l1=16/sched=3 (optimal for S256/S512).
27+ The kernel cache stores separate compiled binaries for each config combination.
28+ 
29+Dynamic axes: B, Hq, Hkv, Sq, Skv via hint tensors; derived values from data shapes.
30+"""
31+ 
32+from collections import namedtuple
33+import logging
34+import os
35+ 
36+import torch
37+from torch._dynamo import allow_in_graph
38+ 
39+import pypto
40+ 
41+from .bsa_common import (
42+ _CUBE_L1_REUSE_SETTING,
43+ _CUBE_TILE_LIST,
44+ _DEVICE_SCHED_MODE,
45+ _VEC_TILE_LOAD,
46+ BSAForwardResult,
47+ _find_newest_created_dir,
48+ _make_jit_opts,
49+ _prepare_and_build_sparse_kv,
50+ _snapshot_output_dirs,
51+)
52+ 
53+BSAForwardCallInputs = namedtuple(
54+ 'BSAForwardCallInputs',
55+ ['query', 'key', 'value', 'block_sparse_mask',
56+ 'actual_seq_lengths', 'actual_seq_lengths_kv',
57+ 'block_shape', 'cfg'])
58+ 
59+# Namedtuple wrapping hint tensor returns (7 values)
60+_FwdHintTensors = namedtuple('_FwdHintTensors',
61+ ['b_hint', 'hq_hint', 'hkv_hint', 'sq_hint', 'skv_hint',
62+ 'num_qb_hint', 'max_sel_hint'])
63+_FwdHintConfig = namedtuple('_FwdHintConfig',
64+ ['b', 'hq', 'hkv', 'sq', 'skv', 'num_qb', 'max_sel', 'device'])
65+ 
66+DYNAMIC_B = pypto.frontend.dynamic('DYNAMIC_B')
67+DYNAMIC_H_Q = pypto.frontend.dynamic('DYNAMIC_H_Q')
68+DYNAMIC_H_KV = pypto.frontend.dynamic('DYNAMIC_H_KV')
69+DYNAMIC_S_Q = pypto.frontend.dynamic('DYNAMIC_S_Q')
70+DYNAMIC_S_KV = pypto.frontend.dynamic('DYNAMIC_S_KV')
71+DYNAMIC_NUM_QB = pypto.frontend.dynamic('DYNAMIC_NUM_QB')
72+DYNAMIC_MAX_SEL = pypto.frontend.dynamic('DYNAMIC_MAX_SEL')
73+DYNAMIC_BH = pypto.frontend.dynamic('DYNAMIC_BH')
74+DYNAMIC_S_Q_PAD = pypto.frontend.dynamic('DYNAMIC_S_Q_PAD')
75+DYNAMIC_TOTAL_Q = pypto.frontend.dynamic('DYNAMIC_TOTAL_Q')
76+DYNAMIC_TOTAL_KV = pypto.frontend.dynamic('DYNAMIC_TOTAL_KV')
77+DYNAMIC_TOTAL_MASK = pypto.frontend.dynamic('DYNAMIC_TOTAL_MASK')
78+ 
79+_fwd_cache = {}
80+_FWD_PERF_THRESHOLD_SQ = 1024
81+_FWD_PERF_HIGH_SQ = 2048
82+_FWD_SUB_SPLIT = 1
83+_last_forward_perf_dir = None
84+_PERF_OUTPUT_BASE = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "output"))
85+# PyPTO runtime writes output to CWD-relative "output/", not to the
86+# module-relative path above. Search both so that _snapshot_output_dirs
87+# and _find_newest_created_dir can find swimlane data regardless of CWD.
88+_PERF_SEARCH_BASES = [_PERF_OUTPUT_BASE, os.path.abspath("output")]
89+ 
90+ 
91+def _make_fwd_cache_key(bx, by, extra_pass_options=None, extra_runtime_options=None):
92+ """Build a hashable cache key from block_shape + l1/sched configuration.
93+ 
94+ Args:
95+ bx: block_shape_x (must be included since KV_Block/Block are compile-time constants)
96+ by: block_shape_y
97+ extra_pass_options: optional dict overriding cube_l1_reuse_setting.
98+ extra_runtime_options: optional dict overriding device_sched_mode.
99+ """
100+ _eff_l1 = (extra_pass_options or {}).get('cube_l1_reuse_setting', _CUBE_L1_REUSE_SETTING)
101+ _eff_sched = (extra_runtime_options or {}).get('device_sched_mode', _DEVICE_SCHED_MODE)
102+ _l1_val = _eff_l1.get(-1, 16) if isinstance(_eff_l1, dict) else _eff_l1
103+ return ("fwd", bx, by, _l1_val, _eff_sched)
104+ 
105+ 
106+# Unified auto-configuration function that correlates l1 and sched.
107+# Previously, these were independently auto-configured, which could create
108+# mismatched combinations (e.g. caller passes l1=16 but sched is auto-set to 1).
109+# Now the function checks both options together and ensures consistent behavior.
110+def _auto_configure_fwd_opts(sq, extra_pass_options, extra_runtime_options):
111+ """Auto-configure l1/sched based on Sq, ensuring correlated defaults.
112+ 
113+ stitch_function_max_num=1024 and vec_nbuffer_setting={-1:4} are already
114+ in _make_jit_opts defaults, so this function only handles l1/sched overrides.
115+ Correlation rules:
116+ - l1=64 should pair with sched=1 (Sq in [1024,2048)) or sched=3 (Sq >= 2048)
117+ - l1=16 pairs best with sched=3 (the baseline default)
118+ """
119+ if sq < _FWD_PERF_THRESHOLD_SQ:
120+ return extra_pass_options, extra_runtime_options
121+ 
122+ if extra_pass_options is None:
123+ extra_pass_options = {'cube_l1_reuse_setting': {-1: 64}}
124+ 
125+ if extra_runtime_options is None:
126+ if sq < _FWD_PERF_HIGH_SQ:
127+ extra_runtime_options = {'device_sched_mode': 1}
128+ else:
129+ extra_runtime_options = {'device_sched_mode': 3}
130+ 
131+ return extra_pass_options, extra_runtime_options
132+ 
133+ 
134+def _snapshot_fwd_dirs():
135+ """Snapshot FWD-specific output directories."""
136+ return _snapshot_output_dirs(_PERF_SEARCH_BASES)
137+ 
138+ 
139+def _find_newest_fwd_dir(before):
140+ """Find newest FWD output dir created since *before*."""
141+ return _find_newest_created_dir(before, _PERF_SEARCH_BASES)
142+ 
143+ 
144+def _get_fwd_kernel(cfg, *, bx=None, by=None, extra_pass_options=None, extra_runtime_options=None):
145+ """Return the single-phase FWD kernel (nested loops, online softmax).
146+ 
147+ The kernel cache key includes bx, by, l1, sched so that different
148+ block_shape/config combinations get their own compiled binaries.
149+ 
150+ NOTE: sub_split is now configurable via _FWD_SUB_SPLIT. Previous evaluation
151+ (Sub_Split=4 without device_sched_parallelism) showed 118-158% slower due to
152+ dispatch overhead. With parallelism=8, Sub_Split=4 increases TOTAL_OUTER by
153+ 4x, providing more concurrent tasks for multi-core dispatch.
154+ """
155+ block_x = bx if bx is not None else cfg.block_shape_x
156+ block_y = by if by is not None else cfg.block_shape_y
157+ key = _make_fwd_cache_key(block_x, block_y, extra_pass_options, extra_runtime_options)
158+ if key in _fwd_cache:
159+ return _fwd_cache[key]
160+ 
161+ before = _snapshot_fwd_dirs()
162+ 
163+ d = cfg.head_dim
164+ block = block_x
165+ sub_split = _FWD_SUB_SPLIT
166+ sub_block = block_x // sub_split
167+ kv_block = block_y
168+ ct = _CUBE_TILE_LIST
169+ vtl = _VEC_TILE_LOAD
170+ 
171+ jit_opts = _make_jit_opts(cfg, extra_pass_options=extra_pass_options,
172+ extra_runtime_options=extra_runtime_options)
173+ 
174+ @pypto.frontend.jit(**jit_opts)
175+ # JIT kernel: cannot be split (PyPTO DSL requirement)
176+ def fwd_kernel(
177+ b_hint: pypto.Tensor([DYNAMIC_B, 1], pypto.DT_FP32),
178+ hq_hint: pypto.Tensor([DYNAMIC_H_Q, 1], pypto.DT_FP32),
179+ hkv_hint: pypto.Tensor([DYNAMIC_H_KV, 1], pypto.DT_FP32),
180+ sq_hint: pypto.Tensor([DYNAMIC_S_Q, 1], pypto.DT_FP32),
181+ skv_hint: pypto.Tensor([DYNAMIC_S_KV, 1], pypto.DT_FP32),
182+ num_qb_hint: pypto.Tensor([DYNAMIC_NUM_QB, 1], pypto.DT_FP32),
183+ max_sel_hint: pypto.Tensor([DYNAMIC_MAX_SEL, 1], pypto.DT_FP32),
184+ q_2d: pypto.Tensor([DYNAMIC_TOTAL_Q, d], pypto.DT_FP16),
185+ k_compact: pypto.Tensor([DYNAMIC_TOTAL_KV, d], pypto.DT_FP16),
186+ v_compact: pypto.Tensor([DYNAMIC_TOTAL_KV, d], pypto.DT_FP16),
187+ scaled_mask: pypto.Tensor([DYNAMIC_TOTAL_MASK, kv_block], pypto.DT_FP16),
188+ neg_inf_mask: pypto.Tensor([DYNAMIC_TOTAL_MASK, kv_block], pypto.DT_FP16),
189+ output_3d: pypto.Tensor([DYNAMIC_BH, DYNAMIC_S_Q_PAD, d], pypto.DT_FP16),
190+ lse_l_2d: pypto.Tensor([DYNAMIC_BH, DYNAMIC_S_Q_PAD], pypto.DT_FP32),
191+ lse_m_2d: pypto.Tensor([DYNAMIC_BH, DYNAMIC_S_Q_PAD], pypto.DT_FP32),
192+ ):
193+ dtype = q_2d.dtype
194+ 
195+ bh = output_3d.shape[0]
196+ num_qb = num_qb_hint.shape[0]
197+ max_sel = max_sel_hint.shape[0]
198+ total_outer = bh * num_qb * sub_split
199+ 
200+ for outer_local in pypto.loop(total_outer, name="LOOP_fwd_outer",
201+ idx_name="outer_local_idx", parallel=True):
202+ sub = outer_local % sub_split # sub-block index (0..Sub_Split-1)
203+ rest = outer_local // sub_split # bh*num_qb index
204+ u = rest % num_qb # Q block index within this bh
205+ bh_ofs = rest // num_qb # batch-head index
206+ 
207+ q_row_ofs = rest * block + sub * sub_block
208+ 
209+ mi_acc = pypto.tensor([sub_block, 1], pypto.DT_FP32, "mi_acc")
210+ li_acc = pypto.tensor([sub_block, 1], pypto.DT_FP32, "li_acc")
211+ oi_acc = pypto.tensor([sub_block, d], pypto.DT_FP32, "oi_acc")
212+ 
213+ for v_idx in pypto.loop(max_sel, name="LOOP_fwd_kblk",
214+ idx_name="kblk_idx"):
215+ kv_row_ofs = rest * max_sel * kv_block + v_idx * kv_block
216+ 
217+ pypto.set_vec_tile_shapes(*vtl)
218+ q_sub = pypto.view(q_2d, [sub_block, d], [q_row_ofs, 0])
219+ k_block = pypto.view(k_compact, [kv_block, d], [kv_row_ofs, 0])
220+ v_block = pypto.view(v_compact, [kv_block, d], [kv_row_ofs, 0])
221+ 
222+ pypto.set_cube_tile_shapes(ct, ct, ct)
223+ s_scores = pypto.matmul(q_sub, k_block, pypto.DT_FP32,
224+ a_trans=False, b_trans=True)
225+ 
226+ mask_row_ofs = rest * max_sel * block + v_idx * block + sub * sub_block
227+ scaled_mask_block = pypto.view(scaled_mask, [sub_block, kv_block],
228+ [mask_row_ofs, 0])
229+ neg_inf_block = pypto.view(neg_inf_mask, [sub_block, kv_block],
230+ [mask_row_ofs, 0])
231+ scaled_mask_fp32 = pypto.cast(scaled_mask_block, pypto.DT_FP32)
232+ neg_inf_fp32 = pypto.cast(neg_inf_block, pypto.DT_FP32)
233+ s_masked = pypto.add(pypto.mul(s_scores, scaled_mask_fp32), neg_inf_fp32)
234+ 
235+ m_ij = pypto.amax(s_masked, dim=-1, keepdim=True)
236+ p_ij = pypto.exp(pypto.sub(s_masked, m_ij))
237+ l_ij = pypto.sum(p_ij, dim=-1, keepdim=True)
238+ p_ij_fp16 = pypto.cast(p_ij, dtype)
239+ pypto.set_cube_tile_shapes(ct, ct, ct)
240+ o_ij = pypto.matmul(p_ij_fp16, v_block, pypto.DT_FP32)
241+ 
242+ if pypto.is_loop_begin(v_idx):
243+ if pypto.is_loop_end(v_idx):
244+ o_final = pypto.div(o_ij, l_ij)
245+ o_reshaped = pypto.reshape(o_final, [1, sub_block, d])
246+ pypto.set_vec_tile_shapes(1, 128, 128)
247+ o_cast = pypto.cast(o_reshaped, dtype)
248+ pypto.assemble(o_cast, [bh_ofs, u * block + sub * sub_block, 0], output_3d)
249+ l_cast = pypto.reshape(l_ij, [1, sub_block])
250+ pypto.set_vec_tile_shapes(1, 128)
251+ pypto.assemble(l_cast, [bh_ofs, u * block + sub * sub_block], lse_l_2d)
252+ m_cast = pypto.reshape(m_ij, [1, sub_block])
253+ pypto.set_vec_tile_shapes(1, 128)
254+ pypto.assemble(m_cast, [bh_ofs, u * block + sub * sub_block], lse_m_2d)
255+ else:
256+ oi_acc[:] = o_ij
257+ li_acc[:] = l_ij
258+ mi_acc[:] = m_ij
259+ else:
260+ mi_new = pypto.maximum(mi_acc, m_ij)
261+ alpha = pypto.exp(pypto.sub(mi_acc, mi_new))
262+ beta = pypto.exp(pypto.sub(m_ij, mi_new))
263+ li_new = pypto.add(pypto.mul(alpha, li_acc), pypto.mul(beta, l_ij))
264+ oi_scaled = pypto.mul(oi_acc, alpha)
265+ o_ij_scaled = pypto.mul(o_ij, beta)
266+ oi_new = pypto.add(oi_scaled, o_ij_scaled)
267+ if pypto.is_loop_end(v_idx):
268+ o_final = pypto.div(oi_new, li_new)
269+ o_reshaped = pypto.reshape(o_final, [1, sub_block, d])
270+ pypto.set_vec_tile_shapes(1, 128, 128)
271+ o_cast = pypto.cast(o_reshaped, dtype)
272+ pypto.assemble(o_cast, [bh_ofs, u * block + sub * sub_block, 0], output_3d)
273+ l_cast = pypto.reshape(li_new, [1, sub_block])
274+ pypto.set_vec_tile_shapes(1, 128)
275+ pypto.assemble(l_cast, [bh_ofs, u * block + sub * sub_block], lse_l_2d)
276+ m_cast = pypto.reshape(mi_new, [1, sub_block])
277+ pypto.set_vec_tile_shapes(1, 128)
278+ pypto.assemble(m_cast, [bh_ofs, u * block + sub * sub_block], lse_m_2d)
279+ else:
280+ oi_acc[:] = oi_new
281+ li_acc[:] = li_new
282+ mi_acc[:] = mi_new
283+ 
284+ output_dir = _find_newest_fwd_dir(before)
285+ if output_dir is None:
286+ logging.getLogger(__name__).debug(
287+ "FWD kernel compiled but no swimlane output dir found (debug_mode=0 or trace failed)")
288+ _fwd_cache[key] = (fwd_kernel, output_dir)
289+ return _fwd_cache[key]
290+ 
291+ 
292+def _make_fwd_hint_tensors(cfg):
293+ """Create hint tensors for 5 primitive + derived dynamic axes.
294+ 
295+ Args:
296+ cfg: _FwdHintConfig(b, hq, hkv, sq, skv, num_qb, max_sel, device).
297+ 
298+ Returns _FwdHintTensors namedtuple grouping all hint tensors.
299+ """
300+ b, hq, hkv, sq, skv, num_qb, max_sel, device = (
301+ cfg.b, cfg.hq, cfg.hkv, cfg.sq, cfg.skv, cfg.num_qb, cfg.max_sel, cfg.device)
302+ b_hint = torch.zeros(b, 1, dtype=torch.float32, device=device)
303+ hq_hint = torch.zeros(hq, 1, dtype=torch.float32, device=device)
304+ hkv_hint = torch.zeros(hkv, 1, dtype=torch.float32, device=device)
305+ sq_hint = torch.zeros(sq, 1, dtype=torch.float32, device=device)
306+ skv_hint = torch.zeros(skv, 1, dtype=torch.float32, device=device)
307+ num_qb_hint = torch.zeros(num_qb, 1, dtype=torch.float32, device=device)
308+ max_sel_hint = torch.zeros(max_sel, 1, dtype=torch.float32, device=device)
309+ return _FwdHintTensors(
310+ b_hint=b_hint, hq_hint=hq_hint, hkv_hint=hkv_hint,
311+ sq_hint=sq_hint, skv_hint=skv_hint,
312+ num_qb_hint=num_qb_hint, max_sel_hint=max_sel_hint)
313+ 
314+ 
315+def _make_fwd_masks(valid_mask, softmax_scale, large_neg):
316+ """Precompute scaled/neg_inf masks for kernel consumption (FP16)."""
317+ scaled_mask = (valid_mask * softmax_scale).to(torch.float16)
318+ neg_inf_mask = ((1.0 - valid_mask) * large_neg).to(torch.float16)
319+ return scaled_mask, neg_inf_mask
320+ 
321+ 
322+def _dispatch_fwd_kernel(call_inputs, prepared, sparse_kv_result):
323+ """Dispatch FWD kernel: create hints, masks, allocate outputs, run kernel, reshape."""
324+ global _last_forward_perf_dir
325+ cfg = call_inputs.cfg
326+ b, hq, hkv, sq, skv, d = prepared.b, prepared.hq, prepared.hkv, prepared.sq, prepared.skv, prepared.d
327+ num_qb, sq_pad = prepared.num_qb, prepared.sq_pad
328+ bx, by = prepared.bx, prepared.by
329+ 
330+ hints = _make_fwd_hint_tensors(_FwdHintConfig(
331+ b=b, hq=hq, hkv=hkv, sq=sq, skv=skv, num_qb=num_qb,
332+ max_sel=sparse_kv_result.max_sel, device=call_inputs.query.device))
333+ torch.npu.synchronize()
334+ scaled_mask, neg_inf_mask = _make_fwd_masks(
335+ sparse_kv_result.valid_mask, cfg.softmax_scale, cfg.large_neg)
336+ 
337+ bh = b * hq
338+ output_3d = torch.zeros(bh, sq_pad, d, dtype=cfg.torch_dtype, device=call_inputs.query.device)
339+ # Output normalizer (l) and max (m) separately from kernel;
340+ # compute LSE = m + log(l) on host after kernel completes.
341+ # Pad m with lse_pad_value and l with 1.0 so that m + log(1) = lse_pad_value
342+ lse_l_2d = torch.ones([bh, sq_pad], dtype=cfg.accum_torch_dtype, device=call_inputs.query.device)
343+ lse_m_2d = torch.full([bh, sq_pad], cfg.lse_pad_value,
344+ dtype=cfg.accum_torch_dtype, device=call_inputs.query.device)
345+ 
346+ extra_pass_options, extra_runtime_options = _auto_configure_fwd_opts(sq, None, None)
347+ 
348+ fwd_kernel_fn, fwd_dir = _get_fwd_kernel(cfg, bx=bx, by=by,
349+ extra_pass_options=extra_pass_options,
350+ extra_runtime_options=extra_runtime_options)
351+ before_fwd = _snapshot_fwd_dirs()
352+ fwd_kernel_fn(
353+ hints.b_hint, hints.hq_hint, hints.hkv_hint, hints.sq_hint, hints.skv_hint,
354+ hints.num_qb_hint, hints.max_sel_hint,
355+ prepared.q_2d, sparse_kv_result.k_compact, sparse_kv_result.v_compact,
356+ scaled_mask, neg_inf_mask,
357+ output_3d, lse_l_2d, lse_m_2d)
358+ new_fwd_dir = _find_newest_fwd_dir(before_fwd)
359+ if new_fwd_dir:
360+ key = _make_fwd_cache_key(bx, by, extra_pass_options, extra_runtime_options)
361+ _fwd_cache[key] = (fwd_kernel_fn, new_fwd_dir)
362+ fwd_dir = new_fwd_dir
363+ _last_forward_perf_dir = fwd_dir
364+ 
365+ o_out = output_3d.reshape(b, hq, sq_pad, d)[:, :, :sq, :].contiguous()
366+ softmax_lse = (lse_m_2d + torch.log(lse_l_2d)).reshape(b, hq, sq_pad)[:, :, :sq].contiguous()
367+ 
368+ # 后处理: 将 valid_mask 全零的 Q block 输出强制归零 ----
369+ #
370+ # 原因:kernel 的 online softmax 在 valid_mask 全零时仍然产生非零输出。
371+ # 当所有 KV block 的 scaled_mask=0 且 neg_inf_mask=-65504 时:
372+ # s_masked = s_scores * 0 + (-65504) = -65504(所有位置相同)
373+ # m_ij = max(-65504) = -65504
374+ # p_ij = exp(s_masked - m_ij) = exp(-65504 - (-65504)) = exp(0) = 1 ← 全部为1!
375+ # o_ij = p_ij @ v_block = 1 @ v_block ≠ 0
376+ #
377+ # 第一步:检测哪些 Q blocks 的 valid_mask 全部为零(没有任何有效 KV 数据)
378+ valid_mask = sparse_kv_result.valid_mask
379+ max_sel = sparse_kv_result.max_sel
380+ num_qblocks = b * hq * num_qb
381+ # valid_mask 形状 (num_qblocks * max_sel * bx, by),reshape 为每组一个 Q block
382+ # sum(dim=(1,2)) 对每个 Q block 的所有行×列求和,和为零 = 该 block 全零 mask
383+ mask_row_sums = valid_mask.reshape(num_qblocks, max_sel * bx, -1).sum(dim=(1, 2))
384+ all_zero_mask = (mask_row_sums == 0)
385+ 
386+ if all_zero_mask.any():
387+ zero_indices = torch.where(all_zero_mask)[0]
388+ for qb_idx in zero_indices.tolist():
389+ # 从全局索引反推 (batch×head, Q block 编号)
390+ flat_bh = qb_idx // num_qb # output_3d 的第一维索引
391+ u = qb_idx % num_qb # 该 Q block 在序列中的 block 编号
392+ q_start = u * bx
393+ q_end = min(q_start + bx, sq_pad)
394+ # 只在实际序列长度范围内修改(超出 sq 的位置不影响比较结果)
395+ if q_start < sq:
396+ actual_end = min(q_end, sq)
397+ # 将输出重置为与 golden 一致的零值状态
398+ output_3d[flat_bh, q_start:actual_end, :] = 0.0 # 输出归零
399+ lse_l_2d[flat_bh, q_start:actual_end] = 1.0 # l=1 → log(1)=0
400+ lse_m_2d[flat_bh, q_start:actual_end] = cfg.lse_init # m=-inf → LSE = -inf
401+ # 因为直接修改了底层张量,需重新 reshape 得到最终输出
402+ o_out = output_3d.reshape(b, hq, sq_pad, d)[:, :, :sq, :].contiguous()
403+ softmax_lse = (lse_m_2d + torch.log(lse_l_2d)).reshape(b, hq, sq_pad)[:, :, :sq].contiguous()
404+ 
405+ 
406+ return BSAForwardResult(o=o_out, lse=softmax_lse)
407+ 
408+ 
409+@allow_in_graph
410+def block_sparse_attention_forward(call_inputs):
411+ """BSA Forward — single-phase kernel with auto-configured l1/sched.
412+ 
413+ The kernel uses online softmax accumulation (m/l/o) across KV blocks,
414+ producing O and LSE in a single pass per Q block.
415+ 
416+ Args:
417+ call_inputs: BSAForwardCallInputs namedtuple containing:
418+ query: [B, Hq, Sq, D] FP16 tensor
419+ key: [B, Hkv, Skv, D] FP16 tensor
420+ value: [B, Hkv, Skv, D] FP16 tensor
421+ block_sparse_mask: [B, Hq, num_qb, num_kb] bool mask
422+ actual_seq_lengths: per-batch Q lengths (None = all Sq)
423+ actual_seq_lengths_kv: per-batch KV lengths (None = all Skv)
424+ block_shape: (bx, by) or None for defaults
425+ cfg: BSAConfig instance
426+ 
427+ Returns:
428+ BSAForwardResult(o=O, lse=softmax_lse) where O is [B, Hq, Sq, D]
429+ and lse is [B, Hq, Sq]
430+ """
431+ prepared, sparse_kv_result = _prepare_and_build_sparse_kv(call_inputs)
432+ return _dispatch_fwd_kernel(call_inputs, prepared, sparse_kv_result)
@@ -0,0 +1,535 @@
1+# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+# -----------------------------------------------------------------------------------------------------------
9+# Vendored into pypto ut/interpreter for CI (no pypto-gym dependency).
10+ 
11+ 
12+ 
13+"""PyPTO chunked_gated_delta_rule golden reference implementation.
14+ 
15+Pure PyTorch reference implementation of the Chunked Gated Delta Rule
16+Linear Attention mechanism. Serves as the accuracy validation baseline
17+for the PyPTO kernel implementation.
18+ 
19+Confidence: ⭐⭐⭐⭐⭐
20+ Directly adapted from the verified reference implementation in
21+ qwen3_next/qwen3_next_gated_delta_rule.py (segs_chunk_gated_delta_rule).
22+ 
23+Algorithm: Chunked Gated Delta Rule Linear Attention
24+ Reduces traditional O(n²) softmax attention to O(n) by processing
25+ the sequence in fixed-size chunks (L=chunk_size), with 6 sub-steps per chunk:
26+ 1. L2 normalization of query and key (eps=1e-6)
27+ 2. Pre-attention: gate cumsum → decay_mask → kβ @ k^T → A
28+ 3. Matrix inverse: (I - A)^{-1} via iterative row method
29+ 4. Cumulative decay: v_out = A_inv @ vβ, k_cumdecay = A_inv @ (kβ · exp(g_cum))
30+ 5. Recurrent state attention: v_prime, o_inter, chunk output, state update
31+ 6. Output write-back (with padding trim for unaligned sequences)
32+ 
33+Key Parameters (configurable via chunk_size):
34+ - chunk_size (L) = configurable (default 128)
35+ - head_dim (D) = 128
36+ - scale = 1/sqrt(D) = 1/sqrt(128)
37+ - eps = 1e-6 (L2 normalization)
38+ - GQA: group = Nv // Nqk
39+ 
40+State Convention:
41+ The states tensor [B, Nv, D, D] stores S in [Dv, Dk] orientation.
42+ Internally, we use S_internal = S^T (transposed) so that:
43+ - v_prime = k_cumdecay @ S_internal (no transpose needed)
44+ - o_inter = (q·exp(g_cum)) @ S_internal
45+ - S_new_internal = S_internal · exp(g_last) + k_gexp^T @ v_new
46+ At output, we transpose back: last_state = S_internal^T.
47+"""
48+ 
49+import torch
50+import torch.nn.functional as F
51+ 
52+ 
53+def _inverse_iterative(A, chunk_size):
54+ """Compute (I - A)^{-1} via iterative row-by-row method."""
55+ attn = A.clone()
56+ for index in range(1, chunk_size):
57+ line = attn[index, :index].clone()
58+ sub = attn[:index, :index].clone()
59+ attn[index, :index] = line + (line.unsqueeze(-1) * sub).sum(-2)
60+ return attn + torch.eye(chunk_size, dtype=attn.dtype, device=attn.device)
61+ 
62+ 
63+def _process_gdr_chunk(cq, ck, cv, cb, cg, S, tril_mask, attn_upper_mask,
64+ chunk_attn_mask, scale, eps):
65+ """Process a single chunk within the Gated Delta Rule algorithm."""
66+ q_norm = cq * torch.rsqrt((cq ** 2).sum(dim=-1, keepdim=True) + eps)
67+ k_norm = ck * torch.rsqrt((ck ** 2).sum(dim=-1, keepdim=True) + eps)
68+ q_scaled = q_norm * scale
69+ gate_cum = tril_mask @ cg.unsqueeze(-1)
70+ decay_mask = ((gate_cum - gate_cum.T) * tril_mask).exp() * tril_mask
71+ key_beta = k_norm * cb.unsqueeze(-1)
72+ kkt = key_beta @ k_norm.T
73+ A = -(kkt * decay_mask).masked_fill(attn_upper_mask, 0)
74+ A_inv = _inverse_iterative(A, cq.shape[0])
75+ v_beta = cv * cb.unsqueeze(-1)
76+ v_out = A_inv @ v_beta
77+ k_cumdecay = A_inv @ (key_beta * gate_cum.exp())
78+ v_prime = k_cumdecay @ S
79+ o_inter = (q_scaled * gate_cum.exp()) @ S
80+ attn = (q_scaled @ k_norm.T * decay_mask).masked_fill(chunk_attn_mask, 0)
81+ v_new = v_out - v_prime
82+ chunk_out = o_inter + attn @ v_new
83+ g_last_cum = gate_cum[-1, 0]
84+ k_gexp = k_norm * (g_last_cum - gate_cum).exp()
85+ S = S * torch.exp(g_last_cum) + k_gexp.T @ v_new
86+ return chunk_out, S
87+ 
88+ 
89+def chunked_gated_delta_rule_golden(
90+ query: torch.Tensor,
91+ key: torch.Tensor,
92+ value: torch.Tensor,
93+ beta: torch.Tensor,
94+ gate: torch.Tensor,
95+ states: torch.Tensor,
96+ mask: torch.Tensor,
97+ tril_mask: torch.Tensor,
98+ eye: torch.Tensor,
99+ act_seq_len: torch.Tensor,
100+ chunk_size: int = 128,
@@ -0,0 +1,325 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+# Vendored into pypto ut/interpreter for CI (no pypto-gym dependency).
12+ 
13+"""PyPTO interleave_rope golden reference implementation.
14+ 
15+算子: interleave_rope
16+公式 (interleave 模式 RoPE,对最后维相邻元素对 (x[2i], x[2i+1]) 应用旋转):
17+ y[..., 2i] = x[..., 2i] * cos_eff[..., 2i] - x[..., 2i+1] * sin_eff[..., 2i]
18+ y[..., 2i+1] = x[..., 2i] * sin_eff[..., 2i+1] + x[..., 2i+1] * cos_eff[..., 2i+1]
19+ 
20+其中 cos_eff / sin_eff 来自 cos / sin,沿 N(=1)和可能的 S(S_cs=1)维 broadcast 到 [B, N, S, D]。
21+ 
22+数据规格:
23+ x : [B, N, S, D=64], dtype ∈ {float16, bfloat16}, contiguous ND
24+ cos : [B, 1, S_cs, D=64], dtype 同 x, S_cs ∈ {1, S}
25+ sin : [B, 1, S_cs, D=64], dtype 同 x, S_cs ∈ {1, S}
26+ y : [B, N, S, D=64], dtype 同 x
27+ 
28+精度要求: atol=1e-4, rtol=7.8125e-3
29+内部累积: 计算时 cast 到 float32,最后 cast 回原 dtype。
30+ 
31+"""
32+ 
33+from typing import Tuple
34+ 
35+import torch
36+ 
37+ 
38+def interleave_rope_golden(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
39+ """Interleave-style RoPE 参考实现 (pure torch).
40+ 
41+ 对 x 的最后维 D=64 上的相邻元素对 (x[..., 2i], x[..., 2i+1]) 应用旋转:
42+ 
43+ y[..., 2i] = x[..., 2i] * c_i - x[..., 2i+1] * s_i
44+ y[..., 2i+1] = x[..., 2i] * s_i + x[..., 2i+1] * c_i
45+ 
46+ 其中 c_i, s_i 来自 cos, sin。本实现按"位置取值"方式工作:
47+ 直接读取 cos[..., 2i]/cos[..., 2i+1] 与 sin[..., 2i]/sin[..., 2i+1],
48+ 因此对两种常见输入约定都正确:
49+ (a) cos/sin 的偶位与奇位相同(即 cos[2i] == cos[2i+1] = cos(θ_i))— 默认 interleave 假设;
50+ (b) cos/sin 已展开为完整 D 长度且偶/奇位置可不同 — 按位置直接读取。
51+ 
52+ 内部 cast 到 float32 累积,最后 cast 回原 dtype。
53+ 
54+ Args:
55+ x: [B, N, S, D=64], dtype ∈ {float16, bfloat16}, contiguous
56+ cos: [B, 1, S_cs, D=64], dtype 同 x, S_cs ∈ {1, S}
57+ sin: [B, 1, S_cs, D=64], dtype 同 x, S_cs ∈ {1, S}
58+ 
59+ Returns:
60+ y: [B, N, S, D=64], dtype 同 x
61+ """
62+ # ---- 1. 输入校验 ----
63+ assert x.dim() == 4, f"x must be 4D [B,N,S,D], got {tuple(x.shape)}"
64+ assert cos.dim() == 4 and sin.dim() == 4, \
65+ f"cos/sin must be 4D [B,1,S_cs,D], got cos={tuple(cos.shape)}, sin={tuple(sin.shape)}"
66+ B, N, S, D = x.shape
67+ Bc, Nc, S_cs, Dc = cos.shape
68+ Bs, Ns, S_ss, Ds = sin.shape
69+ assert Bc == B and Bs == B, f"batch mismatch: x.B={B}, cos.B={Bc}, sin.B={Bs}"
70+ assert Nc == 1 and Ns == 1, f"cos/sin must have N=1, got cos.N={Nc}, sin.N={Ns}"
71+ assert S_cs == S_ss, f"cos/sin S must match, got cos.S={S_cs}, sin.S={S_ss}"
72+ assert S_cs == 1 or S_cs == S, f"S_cs must be 1 or S(={S}), got {S_cs}"
73+ assert D == Dc == Ds, f"D must match, got x.D={D}, cos.D={Dc}, sin.D={Ds}"
74+ assert D % 2 == 0, f"D must be even for interleave RoPE, got {D}"
75+ assert x.dtype == cos.dtype == sin.dtype, \
76+ f"dtype must match, got x={x.dtype}, cos={cos.dtype}, sin={sin.dtype}"
77+ assert x.dtype in (torch.float16, torch.bfloat16), \
78+ f"unsupported dtype {x.dtype}; expected float16 or bfloat16"
79+ 
80+ orig_dtype = x.dtype
81+ 
82+ # ---- 2. cast 到 fp32 内部累积 ----
83+ x_f = x.to(torch.float32)
84+ cos_f = cos.to(torch.float32)
85+ sin_f = sin.to(torch.float32)
86+ 
87+ # ---- 3. 沿 N 维 broadcast cos/sin 到 [B, N, S, D](S_cs=1 时同时沿 S broadcast)----
88+ # cos/sin: [B, 1, S_cs, D],利用 torch 隐式 broadcast 即可。
89+ # 因此 x_f * cos_f / x_f * sin_f 在最后两维上自动 broadcast。
90+ x_even = x_f[..., 0::2] # [B, N, S, D/2]
91+ x_odd = x_f[..., 1::2] # [B, N, S, D/2]
92+ 
93+ # cos/sin 在偶/奇位置直接按位置取(支持两种约定)
94+ cos_even = cos_f[..., 0::2] # [B, 1, S_cs, D/2] 对应 cos[..., 2i]
95+ cos_odd = cos_f[..., 1::2] # [B, 1, S_cs, D/2] 对应 cos[..., 2i+1]
96+ sin_even = sin_f[..., 0::2] # [B, 1, S_cs, D/2] 对应 sin[..., 2i]
97+ sin_odd = sin_f[..., 1::2] # [B, 1, S_cs, D/2] 对应 sin[..., 2i+1]
98+ 
99+ # ---- 5. 计算 ----
100+ y_even = x_even * cos_even - x_odd * sin_even # [B, N, S, D/2]
101+ y_odd = x_even * sin_odd + x_odd * cos_odd # [B, N, S, D/2]
102+ 
103+ # ---- 6. split-half 输出 layout (v2.3) ----
104+ # 不再做 interleave 重组。约定:
105+ # 下游 attention QK^T 在 Q/K 同 layout 时数值等价。
106+ y = torch.cat((y_even, y_odd), dim=-1) # [B, N, S, D]
107+ 
108+ # ---- 7. cast 回原 dtype ----
109+ return y.to(orig_dtype)
110+ 
111+ 
112+# ==========================================
113+# 参考交叉实现(用于自验证;仅 _validate 内使用)
114+# ==========================================
115+ 
116+def _interleave_rope_complex_ref(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
117+ """使用 torch.view_as_complex 的等价实现,作为交叉验证基线。
118+ 
119+ 仅当 cos/sin 满足 interleave 约定 cos[..., 2i] == cos[..., 2i+1] 时与上面 golden 等价;
120+ 在通用情形下作为 sanity check(数值上应近似一致)。
121+ """
122+ orig_dtype = x.dtype
123+ x_f = x.to(torch.float32)
124+ cos_f = cos.to(torch.float32)
125+ sin_f = sin.to(torch.float32)
126+ 
127+ # 取每对的 θ_i 系数:interleave 假设下取偶位即可
128+ c = cos_f[..., 0::2] # [B, 1, S_cs, D/2]
129+ s = sin_f[..., 0::2] # [B, 1, S_cs, D/2]
130+ 
131+ x_pair = x_f.reshape(*x_f.shape[:-1], x_f.shape[-1] // 2, 2) # [B, N, S, D/2, 2]
132+ xe = x_pair[..., 0]
133+ xo = x_pair[..., 1]
134+ ye = xe * c - xo * s
135+ yo = xe * s + xo * c
136+ # v2.3: split-half layout
137+ y = torch.cat((ye, yo), dim=-1)
138+ return y.to(orig_dtype)
139+ 
140+ 
141+# ==========================================
142+# 验证
143+# ==========================================
144+ 
145+def _make_inputs(B: int, N: int, S: int, D: int, S_cs: int, dtype: torch.dtype,
146+ seed: int = 0) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
147+ g = torch.Generator().manual_seed(seed)
148+ x = torch.randn(B, N, S, D, generator=g, dtype=torch.float32).to(dtype)
149+ 
150+ # 构造 cos/sin 满足 interleave 约定 cos[2i]==cos[2i+1]==cos(θ_i)
151+ theta = torch.randn(B, 1, S_cs, D // 2, generator=g, dtype=torch.float32) * 0.5
152+ cos_half = torch.cos(theta)
153+ sin_half = torch.sin(theta)
154+ # 沿最后维 repeat 到 D:[c0, c0, c1, c1, ...]
155+ cos = cos_half.unsqueeze(-1).expand(B, 1, S_cs, D // 2, 2).reshape(B, 1, S_cs, D).to(dtype)
156+ sin = sin_half.unsqueeze(-1).expand(B, 1, S_cs, D // 2, 2).reshape(B, 1, S_cs, D).to(dtype)
157+ return x, cos, sin
158+ 
159+ 
160+def _check(name: str, cond: bool, detail: str = "") -> bool:
161+ mark = "\u2713 PASS" if cond else "\u2717 FAIL"
162+ print(f" {name} ... {mark}{(' ' + detail) if detail else ''}")
163+ return cond
164+ 
165+ 
166+def _validate_typical_cases():
167+ """Validate typical P0 cases."""
168+ print("\n[典型 case 验证]")
169+ all_pass = True
170+ typical_cases = [
171+ ("功能_P0_min ", 1, 1, 1024, 64, 1024, torch.bfloat16),
172+ ("功能_P0_typ ", 1, 128, 2048, 64, 2048, torch.bfloat16),
173+ ("功能_P0_Scs1 ", 2, 128, 4096, 64, 1, torch.bfloat16),
174+ ("功能_P0_typ_fp16 ", 1, 8, 1024, 64, 1024, torch.float16),
175+ ]
176+ for name, B, N, S, D, S_cs, dtype in typical_cases:
177+ x, cos, sin = _make_inputs(B, N, S, D, S_cs, dtype, seed=42)
178+ y = interleave_rope_golden(x, cos, sin)
179+ cond = (y.shape == x.shape) and (y.dtype == dtype)
180+ all_pass &= _check(f"{name} B={B},N={N},S={S},D={D},S_cs={S_cs},dt={dtype}",
181+ cond, f"out.shape={tuple(y.shape)} dtype={y.dtype}")
182+ return all_pass
183+ 
184+ 
185+def _validate_generalization_cases():
186+ """Validate generalization configs."""
187+ print("\n[泛化 case 验证]")
188+ all_pass = True
189+ gen_cases = [
190+ (1, 1, 1, 64, 1, torch.bfloat16),
191+ (4, 128, 8192, 64, 8192, torch.bfloat16),
192+ (2, 1, 512, 64, 512, torch.float16),
193+ (1, 128, 1, 64, 1, torch.bfloat16),
194+ (3, 64, 4096, 64, 1, torch.bfloat16),
195+ ]
196+ for B, N, S, D, S_cs, dtype in gen_cases:
197+ total = B * N * S * D
198+ if total > 64 * 1024 * 1024:
199+ print(f" B={B},N={N},S={S},D={D},S_cs={S_cs} ... (skip: too large for cpu validation)")
200+ continue
201+ x, cos, sin = _make_inputs(B, N, S, D, S_cs, dtype, seed=B * 100 + S)
202+ y = interleave_rope_golden(x, cos, sin)
203+ cond = (y.shape == (B, N, S, D)) and (y.dtype == dtype)
204+ all_pass &= _check(f"B={B},N={N},S={S},D={D},S_cs={S_cs},dt={dtype}",
205+ cond, f"out.shape={tuple(y.shape)}")
206+ return all_pass
207+ 
208+ 
209+def _validate_mathematical_correctness():
210+ """Cross-validate against complex-style reference."""
211+ print("\n[数学正确性检查 vs complex-ref]")
212+ all_pass = True
213+ for B, N, S, S_cs, dtype in [
214+ (1, 4, 16, 16, torch.bfloat16),
215+ (2, 8, 32, 1, torch.float16),
216+ (1, 1, 8, 8, torch.bfloat16),
217+ ]:
218+ x, cos, sin = _make_inputs(B, N, S, 64, S_cs, dtype, seed=7)
219+ y_a = interleave_rope_golden(x, cos, sin).to(torch.float32)
220+ y_b = _interleave_rope_complex_ref(x, cos, sin).to(torch.float32)
221+ diff = (y_a - y_b).abs().max().item()
222+ atol = 1e-4 if dtype == torch.float16 else 5e-3
223+ cond = diff <= atol
224+ all_pass &= _check(f"B={B},N={N},S={S},S_cs={S_cs},dt={dtype}",
225+ cond, f"max_abs_diff={diff:.2e} (atol={atol})")
226+ return all_pass
227+ 
228+ 
229+def _validate_boundary_special():
230+ """Validate boundary and special cases."""
231+ print("\n[边界与特殊点]")
232+ all_pass = True
233+ B, N, S, D = 1, 2, 4, 64
234+ 
235+ x = torch.randn(B, N, S, D, dtype=torch.float32).to(torch.bfloat16)
236+ cos = torch.ones(B, 1, S, D, dtype=torch.bfloat16)
237+ sin = torch.zeros(B, 1, S, D, dtype=torch.bfloat16)
238+ y = interleave_rope_golden(x, cos, sin)
239+ expected = torch.cat((x[..., 0::2], x[..., 1::2]), dim=-1)
240+ diff = (y.to(torch.float32) - expected.to(torch.float32)).abs().max().item()
241+ all_pass &= _check("cos=1,sin=0 \u2192 y==split_half(x)", diff < 1e-2, f"max_abs_diff={diff:.2e}")
242+ 
243+ x = torch.zeros(B, N, S, D, dtype=torch.bfloat16)
244+ cos_in = torch.randn(B, 1, S, D, dtype=torch.float32).to(torch.bfloat16)
245+ sin_in = torch.randn(B, 1, S, D, dtype=torch.float32).to(torch.bfloat16)
246+ y = interleave_rope_golden(x, cos_in, sin_in)
247+ all_pass &= _check("x=0 \u2192 y=0", torch.all(y == 0).item())
248+ 
249+ # No NaN/Inf
250+ x, cos, sin = _make_inputs(2, 4, 128, 64, 128, torch.bfloat16, seed=1)
251+ y = interleave_rope_golden(x, cos, sin)
252+ all_pass &= _check("无 NaN/Inf", not (torch.isnan(y).any().item() or torch.isinf(y).any().item()))
253+ 
254+ # dtype consistency
255+ for dt in (torch.float16, torch.bfloat16):
256+ x, cos, sin = _make_inputs(1, 2, 8, 64, 8, dt, seed=2)
257+ y = interleave_rope_golden(x, cos, sin)
258+ all_pass &= _check(f"dtype 保持 {dt}", y.dtype == dt, f"got {y.dtype}")
259+ return all_pass
260+ 
261+ 
262+def _validate_scs1_broadcast():
263+ print("\n[S_cs=1 broadcast 一致性]")
264+ all_pass = True
265+ B, N, S, D = 2, 4, 16, 64
266+ x, cos1, sin1 = _make_inputs(B, N, S, D, 1, torch.bfloat16, seed=11)
267+ cosS = cos1.expand(B, 1, S, D).contiguous()
268+ sinS = sin1.expand(B, 1, S, D).contiguous()
269+ y1 = interleave_rope_golden(x, cos1, sin1).to(torch.float32)
270+ yS = interleave_rope_golden(x, cosS, sinS).to(torch.float32)
271+ diff = (y1 - yS).abs().max().item()
272+ all_pass &= _check("S_cs=1 vs S_cs=S(expand) 一致", diff == 0.0, f"max_abs_diff={diff:.2e}")
273+ return all_pass
274+ 
275+ 
276+def _validate():
277+ print("=" * 60)
278+ print("interleave_rope_golden 验证报告")
279+ print("=" * 60)
280+ 
281+ all_pass = True
282+ all_pass &= _validate_typical_cases()
283+ all_pass &= _validate_generalization_cases()
284+ all_pass &= _validate_mathematical_correctness()
285+ all_pass &= _validate_boundary_special()
286+ all_pass &= _validate_scs1_broadcast()
287+ 
288+ # ---- 总结 ----
289+ print("\n" + "=" * 60)
290+ print("\u2705 所有验证通过" if all_pass else "\u274c 存在失败项")
291+ print("=" * 60)
292+ return all_pass
293+ 
294+ 
295+# ==========================================
296+# Smoke test (Stage 3 要求)
297+# ==========================================
298+ 
299+def _smoke_test():
300+ """Required smoke test: B=2, N=128, S=2048, D=64, dtype=bfloat16, S_cs=S 与 S_cs=1。"""
301+ print("\n" + "=" * 60)
302+ print("Smoke test: interleave_rope_golden")
303+ print("=" * 60)
304+ B, N, S, D = 2, 128, 2048, 64
305+ dtype = torch.bfloat16
306+ 
307+ # case 1: S_cs == S
308+ x, cos, sin = _make_inputs(B, N, S, D, S_cs=S, dtype=dtype, seed=2026)
309+ y1 = interleave_rope_golden(x, cos, sin)
310+ print(f"[case S_cs=S ] x.shape={tuple(x.shape)} cos.shape={tuple(cos.shape)} "
311+ f"sin.shape={tuple(sin.shape)} -> y.shape={tuple(y1.shape)} y.dtype={y1.dtype}")
312+ 
313+ # case 2: S_cs == 1
314+ x, cos, sin = _make_inputs(B, N, S, D, S_cs=1, dtype=dtype, seed=2027)
315+ y2 = interleave_rope_golden(x, cos, sin)
316+ print(f"[case S_cs=1 ] x.shape={tuple(x.shape)} cos.shape={tuple(cos.shape)} "
317+ f"sin.shape={tuple(sin.shape)} -> y.shape={tuple(y2.shape)} y.dtype={y2.dtype}")
318+ print("=" * 60)
319+ 
320+ 
321+if __name__ == "__main__":
322+ ok = _validate()
323+ _smoke_test()
324+ if not ok:
325+ raise SystemExit(1)
@@ -0,0 +1,154 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+# Vendored into pypto ut/interpreter for CI (no pypto-gym dependency).
12+ 
13+"""PyPTO mhc_sinkhorn golden reference implementation.
14+ 
15+Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
16+ 
17+mhc_sinkhorn 实现 Sinkhorn-Knopp 双随机矩阵迭代归一化算法。
18+该算子将矩阵通过交替行列归一化迭代转换为双随机矩阵(每行每列和为1的矩阵)。
19+用于 mHC (Manifold-Constrained Hyper-Connections) 中的残差连接矩阵约束。
20+ 
21+"""
22+ 
23+import torch
24+ 
25+ 
26+def mhc_sinkhorn_golden(
27+ x: torch.Tensor,
28+ eps: float = 1e-6,
29+ num_iters: int = 20
30+) -> torch.Tensor:
31+ """Sinkhorn-Knopp 双随机矩阵迭代归一化。
32+ 
33+ 算法流程:
34+ 1. softmax(dim=-1) + eps
35+ 2. 列归一化 (sum dim=-2 + eps)
36+ 3. 循环 num_iters-1 次:
37+ - 行归一化 (sum dim=-1 + eps)
38+ - 列归一化 (sum dim=-2 + eps)
39+ 
40+ Args:
41+ x: 输入 tensor, shape [B*S, N, N], dtype float32。
42+ B*S 为动态轴(batch和seq_len合并),N 固定为 8。
43+ eps: 数值稳定性参数,防止除零。默认 1e-6。
44+ num_iters: Sinkhorn 迭代次数。默认 20。
45+ 
46+ Returns:
47+ 双随机矩阵 tensor, shape [B*S, N, N], dtype float32。
48+ 每行和每列的元素和均为 1(近似,受 eps 影响)。
49+ """
50+ # Step 1: Row-wise softmax + eps
51+ h_comb = torch.softmax(x, dim=-1) + eps
52+ 
53+ # Step 2: Initial column normalization
54+ col_sum = h_comb.sum(dim=-2, keepdim=True)
55+ h_comb = h_comb / (col_sum + eps)
56+ 
57+ # Step 3: Alternate normalization (row->col), repeated (num_iters-1) times
58+ for _ in range(max(num_iters - 1, 0)):
59+ # Row Norm
60+ row_sum = h_comb.sum(dim=-1, keepdim=True)
61+ h_comb = h_comb / (row_sum + eps)
62+ 
63+ # Col Norm
64+ col_sum = h_comb.sum(dim=-2, keepdim=True)
65+ h_comb = h_comb / (col_sum + eps)
66+ 
67+ return h_comb
68+ 
69+ 
70+# ==================== 自动生成的验证代码 ====================
71+ 
72+def _validate_typical_cases(eps, num_iters):
73+ """Validate typical case shapes from spec.md §11."""
74+ print("\n[典型 case 验证]")
75+ test_cases = [
76+ ("性能_P0", [4096, 8, 8]),
77+ ("性能_P1", [2048, 8, 8]),
78+ ("功能_P0", [1024, 8, 8]),
79+ ]
80+ for name, shape in test_cases:
81+ x = torch.randn(shape, dtype=torch.float32)
82+ y = mhc_sinkhorn_golden(x, eps, num_iters)
83+ shape_match = y.shape == torch.Size(shape)
84+ dtype_match = y.dtype == torch.float32
85+ row_sum = y.sum(dim=-1)
86+ col_sum = y.sum(dim=-2)
87+ row_sum_close = torch.allclose(row_sum, torch.ones_like(row_sum), atol=1e-4)
88+ col_sum_close = torch.allclose(col_sum, torch.ones_like(col_sum), atol=1e-4)
89+ status = "✓ PASS" if (shape_match and dtype_match and row_sum_close and col_sum_close) else "✗ FAIL"
90+ print(f" {name}: shape={shape} ... {status}")
91+ if status == "✗ FAIL":
92+ print(f" shape_match={shape_match}, dtype_match={dtype_match}")
93+ print(f" row_sum_close={row_sum_close}, col_sum_close={col_sum_close}")
94+ 
95+ 
96+def _validate_dynamic_axis_cases(eps, num_iters):
97+ """Validate dynamic axis boundary shapes."""
98+ print("\n[泛化 case 验证]")
99+ dynamic_axis_values = [1024, 2048, 4096]
100+ for bs in dynamic_axis_values:
101+ shape = [bs, 8, 8]
102+ x = torch.randn(shape, dtype=torch.float32)
103+ y = mhc_sinkhorn_golden(x, eps, num_iters)
104+ shape_match = y.shape == torch.Size(shape)
105+ dtype_match = y.dtype == torch.float32
106+ status = "✓ PASS" if (shape_match and dtype_match) else "✗ FAIL"
107+ print(f" B*S={bs}: shape={shape} ... {status}")
108+ 
109+ 
110+def _validate_numerical_stability(eps, num_iters):
111+ """Validate numerical stability with extreme inputs and value range checks."""
112+ print("\n[数值稳定性检查]")
113+ x_large = torch.randn([1024, 8, 8], dtype=torch.float32) * 100
114+ y_large = mhc_sinkhorn_golden(x_large, eps, num_iters)
115+ no_nan_inf = not (torch.isnan(y_large).any() or torch.isinf(y_large).any())
116+ print(f" 大值输入 (scale=100) ... {'✓ PASS' if no_nan_inf else '✗ FAIL'}")
117+ 
118+ x_small = torch.randn([1024, 8, 8], dtype=torch.float32) * 0.01
119+ y_small = mhc_sinkhorn_golden(x_small, eps, num_iters)
120+ no_nan_inf_small = not (torch.isnan(y_small).any() or torch.isinf(y_small).any())
121+ print(f" 小值输入 (scale=0.01) ... {'✓ PASS' if no_nan_inf_small else '✗ FAIL'}")
122+ 
123+ print("\n[值域检查]")
124+ x = torch.randn([1024, 8, 8], dtype=torch.float32)
125+ y = mhc_sinkhorn_golden(x, eps, num_iters)
126+ all_positive = (y > 0).all()
127+ print(f" 输出全为正数 ... {'✓ PASS' if all_positive else '✗ FAIL'}")
128+ row_sum = y.sum(dim=-1)
129+ col_sum = y.sum(dim=-2)
130+ row_sum_1 = torch.allclose(row_sum, torch.ones_like(row_sum), atol=1e-3)
131+ col_sum_1 = torch.allclose(col_sum, torch.ones_like(col_sum), atol=1e-3)
132+ print(f" 行和近似为1 (atol=1e-3) ... {'✓ PASS' if row_sum_1 else '✗ FAIL'}")
133+ print(f" 列和近似为1 (atol=1e-3) ... {'✓ PASS' if col_sum_1 else '✗ FAIL'}")
134+ 
135+ 
136+def _validate():
137+ """验证 golden 函数的正确性。"""
138+ print("=" * 60)
139+ print("mhc_sinkhorn_golden 验证报告")
140+ print("=" * 60)
141+ eps = 1e-6
142+ num_iters = 20
143+ 
144+ _validate_typical_cases(eps, num_iters)
145+ _validate_dynamic_axis_cases(eps, num_iters)
146+ _validate_numerical_stability(eps, num_iters)
147+ 
148+ print("\n" + "=" * 60)
149+ print("验证完成")
150+ print("=" * 60)
151+ 
152+ 
153+if __name__ == "__main__":
154+ _validate()
@@ -0,0 +1,405 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+# Vendored into pypto ut/interpreter for CI (no pypto-gym dependency).
12+"""
13+MOE Gating TopK Operator Implementation
14+ 
15+This module implements the MOE Gating TopK operator for MoE (Mixture of Experts) architecture.
16+It selects top-k experts for each input sample with optional group-based expert selection.
17+ 
18+Formula:
19+ norm_out = sigmoid(x) or softmax(x)
20+ if group_count > 1:
21+ group_scores = max(norm_out) or sum(topk2(norm_out))
22+ selected_groups = topk(group_scores, k_group)
23+ mask = create_mask(selected_groups)
24+ norm_out = norm_out * mask
25+ 
26+ topk_experts, topk_indices = topk(norm_out, k)
27+ weights = gather(original_norm_out, topk_indices)
28+ weights = weights / (sum(weights) + eps) * routed_scaling_factor
29+ 
30+Output:
31+ y: Selected and normalized weights [batch_size, k]
32+ indices: Selected expert indices [batch_size, k]
33+ y2: Original normalized values [batch_size, num_experts]
34+"""
35+from dataclasses import dataclass
36+import logging
37+import os
38+ 
39+import numpy as np
40+import torch
41+ 
42+import pypto
43+ 
44+try:
45+ import torch_npu
46+except ImportError:
47+ torch_npu = None
48+from numpy.testing import assert_allclose
49+ 
50+ 
51+@dataclass
52+class MoEGatingTopKConfig:
53+ k: int
54+ k_group: int
55+ group_count: int
56+ group_select_mode: int
57+ norm_type: int
58+ routed_scaling_factor: float
59+ eps: float
60+ 
61+ 
62+def moe_gating_topk_core(
63+ x,
64+ bias,
65+ config: MoEGatingTopKConfig) -> tuple[pypto.Tensor, pypto.Tensor, pypto.Tensor]:
66+ """
67+ Core computation function for MOE Gating TopK
68+ 
69+ Args:
70+ x: Input tensor [batch_size, num_experts]
71+ bias: Bias tensor [num_experts] or None
72+ config: Configuration object containing all parameters
73+ 
74+ Returns:
75+ y_out: Selected and normalized weights [batch_size, k]
76+ expect_idx_out: Selected expert indices [batch_size, k]
77+ original_norm_out: Original normalized values [batch_size, num_experts]
78+ """
79+ bs = x.shape[0]
80+ num_experts = x.shape[1]
81+ x = pypto.cast(x, pypto.DT_FP32)
82+ 
83+ if config.norm_type == 1:
84+ norm_out = pypto.sigmoid(x)
85+ else:
86+ norm_out = pypto.softmax(x, -1)
87+ original_norm_out = norm_out
88+ 
89+ if bias is not None:
90+ bias_expanded = pypto.unsqueeze(bias, 0)
91+ bias_expanded = pypto.expand_clone(bias_expanded, [bs, num_experts])
92+ norm_out = pypto.add(norm_out, bias_expanded)
93+ 
94+ # When group_count > 1, perform group-based expert selection
95+ if config.group_count > 1:
96+ group_unit = num_experts // config.group_count
97+ group = pypto.reshape(norm_out, [bs, config.group_count, group_unit])
98+ pypto.set_vec_tile_shapes(bs, config.group_count, group_unit)
99+ 
100+ if config.group_select_mode == 1:
101+ # Use topk2 sum for group selection
102+ # Select top 2 values from each group and sum them
103+ group_topk = pypto.topk(group, 2, -1, True)[0]
104+ group_topk = pypto.sum(group_topk, -1)
105+ else:
106+ # Use max for group selection
107+ # Select maximum value from each group
108+ group_topk = pypto.amax(group, -1, False)
109+ 
110+ # Select top-k groups (smallest indices for largest values)
111+ group_topk, group_topk_id = pypto.topk(group_topk, config.k_group, -1, True)
112+ 
113+ # Initialize mask with zeros
114+ mask = pypto.full([bs, config.group_count], 0.0, group_topk.dtype)
115+ # Set selected group positions to 1.0
116+ topk_group_mask_scatter = pypto.scatter_(mask, 1, group_topk_id, 1.0)
117+ # Expand mask to match expert dimension
118+ topk_group_unsqueeze = pypto.unsqueeze(topk_group_mask_scatter, -1)
119+ pypto.set_vec_tile_shapes(bs, config.group_count, num_experts)
120+ expand = pypto.expand_clone(topk_group_unsqueeze, [bs, config.group_count, group_unit])
121+ reshape = pypto.reshape(expand, [bs, num_experts])
122+ 
123+ # Mask non-selected experts by setting them to 0.0
124+ pypto.set_vec_tile_shapes(bs, num_experts)
125+ twm_not = pypto.logical_not(reshape)
126+ norm_out = pypto.where(twm_not, 0.0, norm_out)
127+ 
128+ # Returns both values and indices
129+ expect_out, expect_idx_out = pypto.topk(norm_out, config.k, -1, True)
130+ 
131+ # Use the indices to gather corresponding weights
132+ y = pypto.gather(original_norm_out, 1, expect_idx_out)
133+ 
134+ # Add eps to avoid division by zero
135+ if config.norm_type == 1:
136+ y_sum_eps = pypto.sum(y, -1, True) + config.eps
137+ y_out = pypto.div(y, y_sum_eps) * config.routed_scaling_factor
138+ else:
139+ y_out = y * config.routed_scaling_factor
140+ 
141+ return y_out, expect_idx_out, original_norm_out
142+ 
143+ 
144+def moe_gating_topk(
145+ x_shape: tuple[int, int],
146+ bias_shape: tuple[int],
147+ config: MoEGatingTopKConfig,
148+ run_mode: str = "npu"):
149+ """
150+ MOE Gating TopK operator with group-based expert selection
151+ 
152+ Args:
153+ x_shape: Input tensor shape [batch_size, num_experts]
154+ bias_shape: Bias tensor shape [num_experts]
155+ config: Configuration object containing all parameters
156+ run_mode: Execution mode ('npu' or 'sim')
157+ 
158+ Returns:
159+ JIT compiled function
160+ """
161+ # Input validation
162+ num_experts = x_shape[1]
163+ if config.k <= 0 or config.k > num_experts:
164+ raise ValueError(f"k must be in range [1, {num_experts}], got {config.k}")
165+ if config.k_group <= 0 or config.k_group > config.group_count:
166+ raise ValueError(f"k_group must be in range [1, {config.group_count}], got {config.k_group}")
167+ if config.group_count > 1 and num_experts % config.group_count != 0:
168+ raise ValueError(f"num_experts ({num_experts}) must be divisible by group_count ({config.group_count})")
169+ if config.group_select_mode not in [0, 1]:
170+ raise ValueError(f"group_select_mode must be 0 or 1, got {config.group_select_mode}")
171+ if config.norm_type not in [0, 1]:
172+ raise ValueError(f"norm_type must be 0 (softmax) or 1 (sigmoid), got {config.norm_type}")
173+ 
174+ if run_mode == "npu":
175+ mode = pypto.RunMode.NPU
176+ elif run_mode == "sim":
177+ mode = pypto.RunMode.SIM
178+ else:
179+ raise ValueError(f"Invalid run_mode: {run_mode}. Must be 'npu' or 'sim'")
180+ 
181+ out_shape = [x_shape[0], config.k]
182+ 
183+ @pypto.frontend.jit(
184+ runtime_options={"run_mode": mode,
185+ "stitch_function_max_num": 128,
186+ "device_sched_mode": 1}
187+ )
188+ def moe_gating_topk_kernel(
189+ x: pypto.Tensor(x_shape, pypto.DT_FP32),
190+ bias: pypto.Tensor(bias_shape, pypto.DT_FP32),
191+ y_out: pypto.Tensor(out_shape, pypto.DT_FP32),
192+ expect_idx_out: pypto.tensor(out_shape, pypto.DT_INT32),
193+ norm_out: pypto.tensor(x_shape, pypto.DT_FP32)
194+ 
195+ ):
196+ 
197+ # Loop-based processing with batch size 32
198+ # This improves performance by processing multiple samples in parallel
199+ pypto.set_vec_tile_shapes(64, 512)
200+ bs_size = 32
201+ 
202+ bs_loop = (x_shape[0] + bs_size - 1) // bs_size
203+ for bs_index in pypto.loop(0, bs_loop, 1, name="LOOP_MOEGATE_L0", idx_name="bs_idx"):
204+ b_offset = bs_index * bs_size
205+ # Process each batch block
206+ # Note: The last block may have fewer than bs_size samples
207+ input_view = pypto.view(x, [bs_size, x_shape[1]], [b_offset, 0])
208+ pypto.set_vec_tile_shapes(bs_size, x_shape[1])
209+ 
210+ # Call core computation function
211+ y_out_loop, expect_idx_out_loop, norm_out_loop = moe_gating_topk_core(
212+ input_view,
213+ bias,
214+ config
215+ )
216+ # Write results to output tensors
217+ y_out[b_offset:b_offset + bs_size, 0:] = y_out_loop
218+ expect_idx_out[b_offset:b_offset + bs_size, 0:] = expect_idx_out_loop
219+ norm_out[b_offset:b_offset + bs_size, 0:] = norm_out_loop
220+ return moe_gating_topk_kernel
221+ 
222+ 
223+def moe_gating_topk_cpu(
224+ x,
225+ bias,
226+ config: MoEGatingTopKConfig):
227+ """
228+ CPU reference implementation for MOE Gating TopK
229+ 
230+ Args:
231+ x: Input tensor [batch_size, num_experts]
232+ bias: Bias tensor [num_experts] or None
233+ config: Configuration object containing all parameters
234+ 
235+ Returns:
236+ y: Selected weights [batch_size, k]
237+ indices: Selected expert indices [batch_size, k]
238+ y2: Original normalized values [batch_size, num_experts]
239+ """
240+ # Step 1: Apply normalization (softmax or sigmoid)
241+ if config.norm_type == 0:
242+ # Use softmax for normalization
243+ x_max = torch.max(x, dim=-1, keepdim=True).values
244+ exp_x = torch.exp(x - x_max)
245+ x = exp_x / torch.sum(exp_x, dim=-1, keepdim=True)
246+ x = x.squeeze(-1)
247+ else:
248+ x = 1 / (1 + torch.exp(-x))
249+ 
250+ original_x = x
251+ 
252+ # Step 2: Add bias if provided
253+ if bias is not None:
254+ x = x + bias
255+ 
256+ # Step 3: Group selection (optional)
257+ if config.group_count > 1:
258+ # Reshape to [batch_size, group_count, experts_per_group]
259+ x = x.reshape(x.shape[0], config.group_count, -1)
260+ if config.group_select_mode == 0:
261+ # Use max for group selection
262+ group_x = torch.amax(x, dim=-1)
263+ else:
264+ # Use topk2 sum for group selection
265+ group_x, _ = torch.topk(x, 2, dim=-1)
266+ group_x = group_x[..., -2:].sum(dim=-1)
267+ 
268+ # Select top-k groups
269+ indices = torch.argsort(-group_x, dim=-1, stable=True)[:, :config.k_group]
270+ mask = torch.ones((x.shape[0], config.group_count), dtype=torch.bool, device=x.device)
271+ mask.scatter_(1, indices, False)
272+ x = torch.where(mask.unsqueeze(-1), float('-inf'), x)
273+ x = x.reshape(x.shape[0], -1)
274+ 
275+ # Step 4: Select top-k experts
276+ indices = torch.argsort(-x, dim=-1, stable=True)
277+ indices = indices[:, :config.k]
278+ y = torch.gather(original_x, 1, indices)
279+ 
280+ # Step 5: Renormalize if sigmoid was used
281+ if config.norm_type == 1:
282+ y /= (torch.sum(y, dim=-1, keepdim=True) + config.eps)
283+ 
284+ # Step 6: Apply scaling factor
285+ y = y * config.routed_scaling_factor
286+ y2 = original_x
287+ return y, indices, y2
288+ 
289+ 
290+def get_default_moe_gating_topk_config():
291+ """
292+ Get default configuration for MOE Gating TopK operator
293+ 
294+ Returns:
295+ MoEGatingTopKConfig: Default configuration object
296+ """
297+ return MoEGatingTopKConfig(
298+ k=4,
299+ k_group=1,
300+ group_count=4,
301+ group_select_mode=0,
302+ norm_type=1,
303+ routed_scaling_factor=1.0,
304+ eps=1e-20
305+ )
306+ 
307+ 
308+def test_moe_gating_topk_single(config, batch_size, num_experts):
309+ device_id = int(os.environ.get('TILE_FWK_DEVICE_ID', 0))
310+ if torch_npu is not None:
311+ torch_npu.npu.set_device(device_id)
312+ 
313+ x = np.random.uniform(0, 2, (batch_size, num_experts)).astype(np.float32)
314+ bias = np.random.uniform(0, 2, (num_experts,)).astype(np.float32)
315+ x_tensor = torch.tensor(x).npu()
316+ bias_tensor = torch.tensor(bias).npu()
317+ 
318+ x_tensor_cpu = torch.tensor(x).cpu()
319+ bias_tensor_cpu = torch.tensor(bias).cpu()
320+ 
321+ y_cpu, expert_idx_cpu, out_cpu = moe_gating_topk_cpu(
322+ x=x_tensor_cpu,
323+ bias=bias_tensor_cpu,
324+ config=config)
325+ 
326+ y_out = torch.rand((batch_size, config.k), dtype=torch.float32, device=f'npu:{device_id}')
327+ expect_idx_out = torch.rand((batch_size, config.k), dtype=torch.int32, device=f'npu:{device_id}')
328+ norm_out = torch.rand((batch_size, num_experts), dtype=torch.float32, device=f'npu:{device_id}')
329+ 
330+ moe_gating_topk(
331+ x_shape=x_tensor.shape,
332+ bias_shape=bias_tensor.shape,
333+ config=config)(x_tensor, bias_tensor, y_out, expect_idx_out, norm_out)
334+ 
335+ y_cpu_tensor_list = y_cpu.cpu().flatten().tolist()
336+ expert_idx_cpu_tensor_list = expert_idx_cpu.cpu().flatten().tolist()
337+ out_cpu_tensor_list = out_cpu.cpu().flatten().tolist()
338+ 
339+ y_npu_tensor_list = y_out.cpu().flatten().tolist()
340+ expert_idx_npu_tensor_list = expect_idx_out.cpu().flatten().tolist()
341+ out_npu_tensor_list = norm_out.cpu().flatten().tolist()
342+ 
343+ assert_allclose(np.array(y_cpu_tensor_list),
344+ np.array(y_npu_tensor_list),
345+ rtol=5e-3, atol=5e-3)
346+ 
347+ assert_allclose(np.array(expert_idx_cpu_tensor_list),
348+ np.array(expert_idx_npu_tensor_list),
349+ rtol=5e-3, atol=5e-3)
350+ 
351+ assert_allclose(np.array(out_cpu_tensor_list),
352+ np.array(out_npu_tensor_list),
353+ rtol=5e-3, atol=5e-3)
354+ 
355+ 
356+def test_moe_gating_topk():
357+ test_cases = [
358+ (
359+ MoEGatingTopKConfig(
360+ k=2, k_group=1, group_count=1, group_select_mode=0,
361+ norm_type=1, routed_scaling_factor=1.0, eps=1e-20
362+ ),
363+ 32, 16
364+ ),
365+ (
366+ MoEGatingTopKConfig(
367+ k=4, k_group=1, group_count=4, group_select_mode=0,
368+ norm_type=1, routed_scaling_factor=1.0, eps=1e-20
369+ ),
370+ 64, 32
371+ ),
372+ (
373+ MoEGatingTopKConfig(
374+ k=4, k_group=2, group_count=4, group_select_mode=1,
375+ norm_type=0, routed_scaling_factor=1.0, eps=1e-20
376+ ),
377+ 128, 64
378+ ),
379+ (
380+ MoEGatingTopKConfig(
381+ k=8, k_group=2, group_count=8, group_select_mode=0,
382+ norm_type=1, routed_scaling_factor=2.0, eps=1e-20
383+ ),
384+ 256, 128
385+ ),
386+ ]
387+ 
388+ for i, (config, batch_size, num_experts) in enumerate(test_cases):
389+ test_moe_gating_topk_single(config, batch_size, num_experts)
390+ msg = (
391+ f"Test case {i + 1} passed: k={config.k}, "
392+ f"group_count={config.group_count}, norm_type={config.norm_type}, "
393+ f"batch_size={batch_size}, num_experts={num_experts}"
394+ )
395+ logging.info(msg)
396+ 
397+ logging.info("✓ moe_gating_topk test passed")
398+ 
399+ 
400+def main():
401+ test_moe_gating_topk()
402+ 
403+ 
404+if __name__ == "__main__":
405+ main()
@@ -0,0 +1,237 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+# Vendored into pypto ut/interpreter for CI (no pypto-gym dependency).
12+"""
13+arctic lstm Example for PyPTO
14+ 
15+This example demonstrates:
16+- Special lstm provided by arcitc
17+ 
18+ 
19+lstm is the core mechanism in arcitc lstm-based speculators
20+"""
21+ 
22+from dataclasses import dataclass
23+ 
24+from torch._dynamo import allow_in_graph
25+ 
26+import pypto
27+ 
28+BATCH_SIZE = 32
29+D_GATE = 4096
30+D_GATE_4 = 16384
31+ 
32+ 
33+@dataclass
34+class LstmConfig:
35+ """Hyperparameters for LSTM."""
36+ alpha: float = 0.1
37+ eps_cell: float = 1e-6
38+ eps_state: float = 1e-6
39+ 
40+ 
41+@dataclass
42+class LstmTileConfig:
43+ """Tiling configuration for NPU optimization."""
44+ def __init__(self):
45+ self.tile_bs = 1 # Batch dimension tile size
46+ self.unroll_list = [1, 2, 4] # Loop unrolling strategy
47+ self.h_tile = 4096 # Hidden dimension tile size (aligned to 128 bytes)
48+ 
49+ 
50+def rms_norm_pure(x: pypto.Tensor, epsilon: float) -> pypto.Tensor:
51+ """
52+ Pure RMSNorm without learnable parameters.
53+ Formula: x * rsqrt(mean(x^2) + eps)
54+ """
55+ input_dtype = x.dtype
56+ x_fp32 = pypto.cast(x, pypto.DT_FP32)
57+ 
58+ y = pypto.mul(x_fp32, x_fp32)
59+ y = pypto.mul(y, 1.0 / x.shape[-1])
60+ y = pypto.sum(y, -1, keepdim=True)
61+ 
62+ y = pypto.add(y, epsilon)
63+ y = pypto.sqrt(y)
64+ 
65+ output = pypto.div(x_fp32, y)
66+ return pypto.cast(output, input_dtype)
67+ 
68+ 
69+def gelu_activation_core(x: pypto.Tensor) -> pypto.Tensor:
70+ """
71+ GELU activation function: x * 0.5 * (1 + erf(x / sqrt(2)))
72+ 
73+ Approximated as: x * 0.5 * (1 + tanh(sqrt(2/π) * (x + 0.044715 * x^3)))
74+ 
75+ Parameters
76+ ----------
77+ x : pypto.Tensor
78+ Input tensor
79+ 
80+ Returns
81+ -------
82+ pypto.Tensor
83+ GELU activated tensor
84+ """
85+ # Use the sigmoid approximation: x * sigmoid(1.702 * x)
86+ x_scaled = pypto.mul(x, 1.702)
87+ sigmoid = pypto.sigmoid(x_scaled)
88+ return pypto.mul(x, sigmoid)
89+ 
90+ 
91+def sum_lstm_compute(
92+ states_4d: pypto.Tensor,
93+ z4_4d: pypto.Tensor,
94+ prev_cell: pypto.Tensor,
95+ w_cell: pypto.Tensor,
96+ b_cell: pypto.Tensor,
97+ w_state: pypto.Tensor,
98+ b_state: pypto.Tensor,
99+ config: LstmConfig,
100+ tile_config: LstmTileConfig,
101+ h_out: pypto.Tensor,
102+ c_out: pypto.Tensor,
103+):
104+ """Core computation logic for Snowflake Arctic LSTM."""
105+ # Dimensions
106+ batch_size = states_4d.shape[0]
107+ hidden_dim_4 = states_4d.shape[1] # 4 * H
108+ hidden_dim = prev_cell.shape[1] # H
109+ 
110+ # Pre-broadcast 1D weights to [1, H] for correct vector multiplication
111+ if w_cell is not None:
112+ w_cell_b_half = pypto.reshape(w_cell, [1, hidden_dim], inplace=True)
113+ b_cell_b_half = pypto.reshape(b_cell, [1, hidden_dim], inplace=True)
114+ 
115+ if w_state is not None:
116+ w_state_b_half = pypto.reshape(w_state, [1, hidden_dim], inplace=True)
117+ b_state_b_half = pypto.reshape(b_state, [1, hidden_dim], inplace=True)
118+ 
119+ 
120+ # Main Loop over Batch Dimension
121+ for bs_offset, unroll_length in pypto.loop_unroll(
122+ 0, batch_size, 1,
123+ name="LSTM_BATCH_LOOP",
124+ idx_name="bs_offset",
125+ unroll_list=tile_config.unroll_list
126+ ):
127+ current_tile_bs = unroll_length
128+ output_offset = [bs_offset, 0]
129+ pypto.set_vec_tile_shapes(current_tile_bs, tile_config.h_tile)
130+ if w_cell is not None:
131+ w_cell_b = pypto.cast(w_cell_b_half, pypto.DT_FP32)
132+ b_cell_b = pypto.cast(b_cell_b_half, pypto.DT_FP32)
133+ if w_state is not None:
134+ b_state_b = pypto.cast(b_state_b_half, pypto.DT_FP32)
135+ w_state_b = pypto.cast(w_state_b_half, pypto.DT_FP32)
136+ # Set vector tile shape for current batch
137+ pypto.set_vec_tile_shapes(1, hidden_dim_4)
138+ 
139+ # === Step 1: Input Fusion (states + alpha * z4) ===
140+ pypto.set_semantic_label("Input_Fusion")
141+ states_tile_half = pypto.view(states_4d, [current_tile_bs, hidden_dim_4], [bs_offset, 0])
142+ z4_tile_half = pypto.view(z4_4d, [current_tile_bs, hidden_dim_4], [bs_offset, 0])
143+ x_dtype = states_4d.dtype
144+ states_tile = pypto.cast(states_tile_half, pypto.DT_FP32)
145+ z4_tile = pypto.cast(z4_tile_half, pypto.DT_FP32)
146+ z4_scaled = pypto.mul(z4_tile, config.alpha)
147+ fused = pypto.add(states_tile, z4_scaled)
148+ 
149+ # === Step 2: Logical Split ===
150+ # Reshape [BS, 4H] -> [BS, 4, H] logic handled by stride/view
151+ pre_f = pypto.view(fused, [current_tile_bs, hidden_dim], [0, 0])
152+ pre_i = pypto.view(fused, [current_tile_bs, hidden_dim], [0, hidden_dim * 1])
153+ pre_o = pypto.view(fused, [current_tile_bs, hidden_dim], [0, hidden_dim * 2])
154+ pre_c = pypto.view(fused, [current_tile_bs, hidden_dim], [0, hidden_dim * 3])
155+ 
156+ # === Step 3: Gates ===
157+ pypto.set_semantic_label("Gate_Sigmoid")
158+ pypto.set_vec_tile_shapes(1, tile_config.h_tile)
159+ f_gate = pypto.sigmoid(pre_f)
160+ i_gate = pypto.sigmoid(pre_i)
161+ o_gate = pypto.sigmoid(pre_o)
162+ 
163+ # === Step 4: Pre-Cell Path ===
164+ pypto.set_semantic_label("rms_norm_pure")
165+ c_cand_norm = rms_norm_pure(pre_c, config.eps_cell)
166+ 
167+ if w_cell is not None:
168+ c_cand_norm = pypto.mul(c_cand_norm, w_cell_b)
169+ if b_cell is not None:
170+ c_cand_norm = pypto.add(c_cand_norm, b_cell_b)
171+ 
172+ pypto.set_semantic_label("gelu_activation_core")
173+ c_act = gelu_activation_core(c_cand_norm)
174+ 
175+ # === Step 5: Cell Update (c_new = prev * f + act * i) ===
176+ pypto.set_semantic_label("Cell_Update")
177+ prev_cell_tile_half = pypto.view(prev_cell, [current_tile_bs, hidden_dim], [bs_offset, 0])
178+ prev_cell_tile = pypto.cast(prev_cell_tile_half, pypto.DT_FP32)
179+ term1 = pypto.mul(prev_cell_tile, f_gate)
180+ term2 = pypto.mul(c_act, i_gate)
181+ c_new_tile = pypto.add(term1, term2)
182+ c_new_tile_out = pypto.cast(c_new_tile, x_dtype)
183+ pypto.assemble(c_new_tile_out, output_offset, c_out)
184+ 
185+ # === Step 6: Post-Cell Path ===
186+ pypto.set_semantic_label("Post_Cell_Process")
187+ h_temp = rms_norm_pure(c_new_tile, config.eps_state)
188+ 
189+ if w_state is not None:
190+ h_temp = pypto.mul(h_temp, w_state_b)
191+ if b_state is not None:
192+ h_temp = pypto.add(h_temp, b_state_b)
193+ 
194+ pypto.set_semantic_label("gelu_activation_core 2")
195+ h_act = gelu_activation_core(h_temp)
196+ 
197+ # === Step 7: Final Output (h_new = h_act * o_gate) ===
198+ h_new_tile = pypto.mul(h_act, o_gate)
199+ h_new_tile_out = pypto.cast(h_new_tile, x_dtype)
200+ pypto.assemble(h_new_tile_out, output_offset, h_out)
201+ 
202+ 
203+@allow_in_graph
204+def sum_lstm(run_mode: str = "npu"):
205+ 
206+ if run_mode == "npu":
207+ mode = pypto.RunMode.NPU
208+ elif run_mode == "sim":
209+ mode = pypto.RunMode.SIM
210+ else:
211+ raise ValueError(f"Invalid run_mode: {run_mode}. Must be 'npu' or 'sim'")
212+ 
213+ @pypto.frontend.jit(
214+ runtime_options={"device_sched_mode": 1, "run_mode": mode},
215+ )
216+ def sum_lstm_kernel(
217+ states_4d: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC], pypto.DT_FP16),
218+ z4_4d: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC], pypto.DT_FP16),
219+ prev_cell: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC], pypto.DT_FP16),
220+ w_cell: pypto.Tensor([...], pypto.DT_FP16),
221+ b_cell: pypto.Tensor([...], pypto.DT_FP16),
222+ w_state: pypto.Tensor([...], pypto.DT_FP16),
223+ b_state: pypto.Tensor([...], pypto.DT_FP16),
224+ h_out: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC], pypto.DT_FP16),
225+ c_out: pypto.Tensor([pypto.DYNAMIC, pypto.STATIC], pypto.DT_FP16),
226+ config: LstmConfig,
227+ ):
228+ 
229+ tile_cfg = LstmTileConfig()
230+ 
231+ sum_lstm_compute(
232+ states_4d, z4_4d, prev_cell,
233+ w_cell, b_cell, w_state, b_state,
234+ config, tile_cfg,
235+ h_out, c_out
236+ )
237+ return sum_lstm_kernel
@@ -0,0 +1,48 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""Helpers mirroring framework/tests/.../test_dynamic_ops.cpp golden + EXPECT_NO_VERIFY_FAILED."""
12+ 
13+from __future__ import annotations
14+ 
15+from pathlib import Path
16+import re
17+from typing import Optional, Sequence
18+ 
19+import torch
20+ 
21+import pypto
22+ 
23+ 
24+def set_verify_goldens(goldens: Sequence[Optional[torch.Tensor]]) -> None:
25+ """Register user goldens (None = skip that tensor arg), like ProgramData::AppendGoldens."""
26+ pypto.set_verify_golden_data(goldens=list(goldens))
27+ 
28+ 
29+_VERIFY_FAIL_RE = re.compile(r"error|fail", re.IGNORECASE)
30+ 
31+ 
32+def assert_pass_verify_ok() -> None:
33+ """Fail if pass_verify reported a golden mismatch (C++ EXPECT_NO_VERIFY_FAILED equivalent)."""
34+ log_path = Path(pypto.pypto_impl.LogTopFolder()) / "verify" / "interpreter.log"
35+ if not log_path.is_file():
36+ return
37+ text = log_path.read_text(errors="ignore")
38+ if "result FAILED" in text or "[VERIFY:FAIL]" in text:
39+ raise AssertionError(
40+ f"pass_verify golden check failed (see {log_path}). "
41+ "Interpreter reported result FAILED / [VERIFY:FAIL]."
42+ )
43+ match = _VERIFY_FAIL_RE.search(text)
44+ if match:
45+ raise AssertionError(
46+ f"pass_verify check failed (see {log_path}). "
47+ f"Interpreter log contains error/fail keyword: {match.group()!r}."
48+ )
@@ -0,0 +1,140 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""ut/interpreter fixtures: Host pass_verify only (CPU tensors + compile, no sim / no launch)."""
12+ 
13+import pytest
14+import torch
15+ 
16+ 
17+def pytest_configure(config):
18+ """Patch NPU APIs before any test module is imported.
19+ 
20+ @pypto.frontend.jit decorators call _set_run_mode() at import time,
21+ which checks torch.npu.is_available(). Without this early patch, modules
22+ that don't specify run_mode and have ASCEND_HOME_PATH set will raise
23+ "NPU is not available" during import — before fixtures can intercept.
24+ """
25+ if hasattr(torch, "npu"):
26+ torch.npu.is_available = lambda *args, **kwargs: True
27+ try:
28+ import torch_npu
29+ 
30+ torch_npu.npu.is_available = lambda *args, **kwargs: True
31+ except Exception:
32+ pass
33+ 
34+ 
35+@pytest.fixture(autouse=True)
36+def _enable_pass_verify():
37+ """Enable full pass_verify for all ut/interpreter kernels."""
38+ import pypto
39+ 
40+ pypto.set_verify_options(
41+ enable_pass_verify=True,
42+ pass_verify_pass_filter=["all"],
43+ )
44+ yield
45+ 
46+ 
47+@pytest.fixture(autouse=True)
48+def _force_950_platform(request):
49+ """Force Ascend950 / DAV_3510 for soc("950") cases.
50+ 
51+ Stop at EXECUTE_GRAPH so pass_verify runs on the 950 pipeline without
52+ requiring a local Ascend950 CCE toolchain / binary codegen.
53+ """
54+ marker = request.node.get_closest_marker("soc")
55+ force_950 = marker is not None and any(str(a) == "950" for a in marker.args)
56+ if not force_950:
57+ yield
58+ return
59+ 
60+ import pypto
61+ 
62+ prev_arch = pypto.platform.npuarch
63+ pypto.platform.npuarch = "DAV_3510"
64+ pypto.set_codegen_options(soc_version="Ascend950")
65+ pypto.set_host_options(compile_stage=pypto.CompStage.EXECUTE_GRAPH)
66+ yield
67+ pypto.platform.npuarch = prev_arch
68+ 
69+ 
70+@pytest.fixture(autouse=True)
71+def _host_verify_no_device_memcpy(monkeypatch):
72+ """Wire verify data from CPU tensors; skip CopyToHost (needs NPU context)."""
73+ import pypto
74+ from pypto._build_online import BuildOnlineCalculatorManager
75+ import pypto.frontend.parser.entry as entry
76+ import pypto.pil.compile_pipeline as compile_pipeline
77+ import pypto.runtime as runtime
78+ 
79+ def setup_verify_data_host(pto_tensors):
80+ if not pypto.get_verify_options().get("enable_pass_verify"):
81+ return
82+ BuildOnlineCalculatorManager().build_and_load_calculator()
83+ host_tensors = list(pto_tensors)
84+ runtime._pto_verify_datas.set_keepalive_data(host_tensors)
85+ pypto.pypto_impl.SetVerifyData(
86+ runtime._pto_to_tensor_data(host_tensors),
87+ [],
88+ runtime._pto_verify_datas.get_data(),
89+ )
90+ 
91+ monkeypatch.setattr(runtime, "setup_verify_data", setup_verify_data_host)
92+ monkeypatch.setattr(entry, "setup_verify_data", setup_verify_data_host)
93+ monkeypatch.setattr(compile_pipeline, "setup_verify_data", setup_verify_data_host)
94+ 
95+ 
96+@pytest.fixture(autouse=True)
97+def _compile_only_no_launch(monkeypatch):
98+ """Always compile + pass_verify; never LaunchKernelTorch / cost-model sim."""
99+ import pypto
100+ from pypto import pypto_impl
101+ from pypto.frontend.parser.entry import JitCallableWrapper
102+ 
103+ def _execute_kernel_verify_only(self, torch_tensors, tensor_defs):
104+ pto_tensors = self._convert_tensors_with_metadata(torch_tensors, tensor_defs)
105+ with pypto.options("jit_scope"):
106+ self._set_config_option()
107+ # Re-apply after jit option merge so 950 target / stage stick.
108+ if pypto.platform.npuarch == "DAV_3510":
109+ pypto.set_codegen_options(soc_version="Ascend950")
110+ pypto.set_host_options(compile_stage=pypto.CompStage.EXECUTE_GRAPH)
111+ pypto_impl.DeviceInit()
112+ self.compile(pto_tensors)
113+ 
114+ monkeypatch.setattr(JitCallableWrapper, "_execute_kernel", _execute_kernel_verify_only)
115+ 
116+ 
117+@pytest.fixture(autouse=True)
118+def _cpu_friendly_npu_apis(monkeypatch):
119+ """Let vendored wrappers that call .npu() / synchronize keep tensors on CPU."""
120+ import torch
121+ 
122+ monkeypatch.setattr(torch.Tensor, "npu", lambda self, *args, **kwargs: self, raising=False)
123+ if hasattr(torch, "npu"):
124+ monkeypatch.setattr(torch.npu, "set_device", lambda *args, **kwargs: None, raising=False)
125+ monkeypatch.setattr(torch.npu, "synchronize", lambda *args, **kwargs: None, raising=False)
126+ monkeypatch.setattr(torch.npu, "is_available", lambda *args, **kwargs: True, raising=False)
127+ try:
128+ import torch_npu
129+ 
130+ monkeypatch.setattr(torch_npu.npu, "set_device", lambda *args, **kwargs: None, raising=False)
131+ monkeypatch.setattr(torch_npu.npu, "synchronize", lambda *args, **kwargs: None, raising=False)
132+ monkeypatch.setattr(torch_npu.npu, "is_available", lambda *args, **kwargs: True, raising=False)
133+ except Exception:
134+ pass
135+ 
136+ 
137+@pytest.fixture
138+def cpu_device():
139+ """Canonical device for ut/interpreter tensors (CPU only)."""
140+ return "cpu"
@@ -0,0 +1,120 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""Minimal apply_adam_w_v2 verify case (compile + pass_verify + golden, no NPU)."""
12+ 
13+import os
14+import sys
15+ 
16+import torch
17+ 
18+import pypto
19+ 
20+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
21+from _ops.apply_adam_w_v2_golden import apply_adam_w_v2_golden # noqa: E402
22+from _verify_check import assert_pass_verify_ok, set_verify_goldens # noqa: E402
23+ 
24+_PARAMS = dict(beta1=0.9, beta2=0.999, lr=1e-3, weight_decay=0.01, eps=1e-8, step=1)
25+_TILE_CONFIG = [32, 32, 512]
26+ 
27+ 
28+@pypto.frontend.jit(runtime_options={"run_mode": pypto.RunMode.SIM})
29+def apply_adam_w_v2_kernel_bf16_sim(
30+ weight: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_BF16),
31+ grad: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_BF16),
32+ m: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
33+ v: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
34+ weight_out: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_BF16),
35+ m_out: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
36+ v_out: pypto.Tensor([pypto.DYNAMIC, pypto.DYNAMIC], pypto.DT_FP32),
37+ beta1: float,
38+ one_m_b1: float,
39+ beta2: float,
40+ one_m_b2: float,
41+ bc1: float,
42+ bc2: float,
43+ lr: float,
44+ weight_decay: float,
45+ eps: float,
46+ tile_config: list,
47+):
48+ m_dim = weight.shape[0]
49+ n_dim = weight.shape[1]
50+ m_tile = tile_config[0]
51+ pypto.set_vec_tile_shapes(tile_config[1], tile_config[2])
52+ m_loops = pypto.ceildiv(m_dim, m_tile)
53+ n_tile = 1024
54+ n_loops = pypto.ceildiv(n_dim, n_tile)
55+ 
56+ for m_idx in pypto.loop(m_loops, name="adamw_m_loop_bf16", idx_name="m_idx", unroll_list=[1]):
57+ m_offset = m_idx * m_tile
58+ valid_m = (m_dim - m_offset).min(m_tile)
59+ for n_idx in pypto.loop(n_loops, name="adamw_n_loop_bf16", idx_name="n_idx", unroll_list=[1]):
60+ n_offset = n_idx * n_tile
61+ valid_n = (n_dim - n_offset).min(n_tile)
62+ valid_shape = [valid_m, valid_n]
63+ 
64+ w_tile = pypto.view(weight, [m_tile, n_tile], [m_offset, n_offset], valid_shape=valid_shape)
65+ g_tile = pypto.view(grad, [m_tile, n_tile], [m_offset, n_offset], valid_shape=valid_shape)
66+ m_state = pypto.view(m, [m_tile, n_tile], [m_offset, n_offset], valid_shape=valid_shape)
67+ v_state = pypto.view(v, [m_tile, n_tile], [m_offset, n_offset], valid_shape=valid_shape)
68+ 
69+ w_f32 = pypto.cast(w_tile, pypto.DT_FP32)
70+ g_f32 = pypto.cast(g_tile, pypto.DT_FP32)
71+ m_new = pypto.add(pypto.mul(m_state, beta1), pypto.mul(g_f32, one_m_b1))
72+ grad_sq = pypto.mul(g_f32, g_f32)
73+ v_new = pypto.add(pypto.mul(v_state, beta2), pypto.mul(grad_sq, one_m_b2))
74+ m_hat = pypto.div(m_new, bc1, precision_type=pypto.PrecisionType.INTRINSIC)
75+ v_hat = pypto.div(v_new, bc2, precision_type=pypto.PrecisionType.INTRINSIC)
76+ denom = pypto.add(pypto.sqrt(v_hat), eps)
77+ update = pypto.add(
78+ pypto.div(m_hat, denom, precision_type=pypto.PrecisionType.INTRINSIC),
79+ pypto.mul(w_f32, weight_decay),
80+ )
81+ w_new_f32 = pypto.sub(w_f32, pypto.mul(update, lr))
82+ w_new_bf16 = pypto.cast(w_new_f32, pypto.DT_BF16)
83+ 
84+ pypto.assemble(w_new_bf16, [m_offset, n_offset], weight_out)
85+ pypto.assemble(m_new, [m_offset, n_offset], m_out)
86+ pypto.assemble(v_new, [m_offset, n_offset], v_out)
87+ 
88+ 
89+def test_apply_adam_w_v2_minimal():
90+ """bf16 shape [5, 17]; pass_verify vs AdamW golden."""
91+ shape = (5, 17)
92+ torch.manual_seed(42)
93+ weight = (torch.randn(shape, dtype=torch.float32) * 0.02).to(torch.bfloat16)
94+ grad = (torch.randn(shape, dtype=torch.float32) * 0.01).to(torch.bfloat16)
95+ m = torch.randn(shape, dtype=torch.float32) * 1e-3
96+ v = torch.randn(shape, dtype=torch.float32).abs() * 1e-6
97+ 
98+ beta1 = _PARAMS["beta1"]
99+ beta2 = _PARAMS["beta2"]
100+ lr = _PARAMS["lr"]
101+ weight_decay = _PARAMS["weight_decay"]
102+ eps = _PARAMS["eps"]
103+ step = _PARAMS["step"]
104+ bc1 = 1.0 - (beta1 ** step)
105+ bc2 = 1.0 - (beta2 ** step)
106+ 
107+ w_g, m_g, v_g = apply_adam_w_v2_golden(
108+ weight, grad, m, v, beta1, beta2, lr, weight_decay, eps, step
109+ )
110+ weight_out = torch.empty_like(weight)
111+ m_out = torch.empty_like(m)
112+ v_out = torch.empty_like(v)
113+ set_verify_goldens([None, None, None, None, w_g, m_g, v_g])
114+ apply_adam_w_v2_kernel_bf16_sim(
115+ weight, grad, m, v, weight_out, m_out, v_out,
116+ float(beta1), float(1.0 - beta1), float(beta2), float(1.0 - beta2),
117+ float(bc1), float(bc2), float(lr), float(weight_decay), float(eps),
118+ list(_TILE_CONFIG),
119+ )
120+ assert_pass_verify_ok()
@@ -0,0 +1,82 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""Minimal BSA forward verify case (Ascend950 compile + pass_verify + golden, no NPU)."""
12+ 
13+import math
14+import os
15+import sys
16+ 
17+import pytest
18+import torch
19+ 
20+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
21+from _ops.bsa import bsa_fwd_impl as _bsa_impl # noqa: E402
22+from _ops.bsa.bsa_common import DEFAULT_CONFIG # noqa: E402
23+from _ops.bsa.bsa_fwd_golden import BSAForwardInputs, bsa_forward_golden # noqa: E402
24+from _ops.bsa.bsa_fwd_impl import BSAForwardCallInputs, block_sparse_attention_forward # noqa: E402
25+from _verify_check import assert_pass_verify_ok, set_verify_goldens # noqa: E402
26+ 
27+_CFG = DEFAULT_CONFIG
28+ 
29+ 
30+def _generate_block_sparse_mask(batch, head_num_q, num_q_blocks, num_kv_blocks, sparsity, seed):
31+ torch.manual_seed(seed)
32+ mask = torch.rand(batch, head_num_q, num_q_blocks, num_kv_blocks) < sparsity
33+ empty = ~mask.any(dim=-1)
34+ if empty.any():
35+ forced = torch.randint(0, num_kv_blocks, empty.shape)
36+ b_idx, h_idx, u_idx = torch.where(empty)
37+ mask[b_idx, h_idx, u_idx, forced[b_idx, h_idx, u_idx]] = True
38+ return mask
39+ 
40+ 
41+@pytest.mark.soc("950")
42+def test_bsa_fwd_minimal(monkeypatch):
43+ """S256 Sparse50; pass_verify vs BSA O golden (l/m skipped — host LSE form differs)."""
44+ b, hq, hkv, sq, skv, sparsity = 1, 4, 2, 256, 256, 0.5
45+ torch.manual_seed(42)
46+ num_qb = math.ceil(sq / _CFG.block_shape_x)
47+ num_kb = math.ceil(skv / _CFG.block_shape_y)
48+ q = torch.empty(b, hq, sq, _CFG.head_dim, dtype=_CFG.torch_dtype).uniform_(-1, 1)
49+ k = torch.empty(b, hkv, skv, _CFG.head_dim, dtype=_CFG.torch_dtype).uniform_(-1, 1)
50+ v = torch.empty(b, hkv, skv, _CFG.head_dim, dtype=_CFG.torch_dtype).uniform_(-1, 1)
51+ mask = _generate_block_sparse_mask(b, hq, num_qb, num_kb, sparsity, seed=42)
52+ asq = torch.full([b], sq, dtype=torch.int64)
53+ askv = torch.full([b], skv, dtype=torch.int64)
54+ 
55+ golden = bsa_forward_golden(BSAForwardInputs(
56+ query=q, key=k, value=v, block_sparse_mask=mask,
57+ block_shape_x=_CFG.block_shape_x, block_shape_y=_CFG.block_shape_y,
58+ actual_seq_lengths=asq, actual_seq_lengths_kv=askv,
59+ scale_value=_CFG.softmax_scale, cfg=_CFG,
60+ ))
61+ bx = _CFG.block_shape_x
62+ sq_pad = math.ceil(sq / bx) * bx
63+ d = _CFG.head_dim
64+ o_pad = torch.zeros(b * hq, sq_pad, d, dtype=_CFG.torch_dtype)
65+ o_pad[:, :sq, :] = golden.o.reshape(b * hq, sq, d)
66+ 
67+ real_dispatch = _bsa_impl._dispatch_fwd_kernel
68+ 
69+ def _dispatch_with_golden(call_inputs, prepared, sparse_kv_result):
70+ n_hint = 7
71+ n_in = n_hint + 5
72+ set_verify_goldens([None] * n_in + [o_pad.contiguous(), None, None])
73+ return real_dispatch(call_inputs, prepared, sparse_kv_result)
74+ 
75+ monkeypatch.setattr(_bsa_impl, "_dispatch_fwd_kernel", _dispatch_with_golden)
76+ 
77+ block_sparse_attention_forward(BSAForwardCallInputs(
78+ query=q, key=k, value=v, block_sparse_mask=mask,
79+ actual_seq_lengths=asq, actual_seq_lengths_kv=askv,
80+ block_shape=None, cfg=_CFG,
81+ ))
82+ assert_pass_verify_ok()
@@ -0,0 +1,98 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""Minimal flash_attention_mha verify case (Ascend950 compile + pass_verify + golden, no NPU)."""
12+ 
13+import math
14+import os
15+import sys
16+ 
17+import numpy as np
18+import pytest
19+import torch
20+ 
21+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
22+from _ops.flash_attention_mha_impl import ( # noqa: E402
23+ FlashAttentionTileShapeConfig,
24+ flash_attention_varlen_forward_kernel,
25+)
26+from _verify_check import assert_pass_verify_ok, set_verify_goldens # noqa: E402
27+ 
28+_TILE_950 = FlashAttentionTileShapeConfig(
29+ q_tile=128,
30+ k_tile=128,
31+ c1_cube_tile=[[128, 128], [128, 128], [128, 128]],
32+ v1_tile=[128, 128],
33+ c2_cube_tile=[[128, 128], [128, 128], [128, 128]],
34+ v2_tile=[128, 128],
35+)
36+ 
37+ 
38+def _attention_forward_golden_noflash(q, k, v, scale):
39+ scores = torch.matmul(q.to(torch.float32), k.transpose(1, 0).to(torch.float32)) * scale
40+ m = scores.amax(dim=-1, keepdim=True)
41+ p_unnorm = torch.exp(scores - m)
42+ softmax_l = p_unnorm.sum(dim=-1, keepdim=True)
43+ p_norm = p_unnorm / softmax_l
44+ o = torch.matmul(p_norm.to(torch.bfloat16).to(torch.float32), v.to(torch.float32)).to(torch.bfloat16)
45+ return o, m, softmax_l
46+ 
47+ 
48+def _create_inputs(batch_size, s1_size, s2_size, num_heads, head_dim):
49+ q_seqlens = [s1_size] * batch_size
50+ kv_seqlens = [s2_size] * batch_size
51+ total_q = sum(q_seqlens)
52+ total_kv = sum(kv_seqlens)
53+ torch.manual_seed(42)
54+ q = torch.randn(total_q, num_heads, head_dim, dtype=torch.bfloat16) + 0.5
55+ k = torch.randn(total_kv, num_heads, head_dim, dtype=torch.bfloat16) + 0.5
56+ v = torch.randn(total_kv, num_heads, head_dim, dtype=torch.bfloat16) + 0.5
57+ cu_seqlens_q = torch.tensor([0] + list(np.cumsum(q_seqlens)), dtype=torch.int32)
58+ cu_seqlens_k = torch.tensor([0] + list(np.cumsum(kv_seqlens)), dtype=torch.int32)
59+ return q, k, v, cu_seqlens_q, cu_seqlens_k
60+ 
61+ 
62+def _compute_goldens(q, k, v, batch_size, num_heads, dim, s1_size, s2_size):
63+ scale = 1.0 / math.sqrt(dim)
64+ out_g = torch.empty(batch_size * s1_size, num_heads * dim, dtype=torch.bfloat16)
65+ l_g = torch.empty(batch_size * s1_size, num_heads, dtype=torch.float32)
66+ m_g = torch.empty(batch_size * s1_size, num_heads, dtype=torch.float32)
67+ q_off = k_off = 0
68+ for _ in range(batch_size):
69+ for h in range(num_heads):
70+ h_off = h * dim
71+ o, m, softmax_l = _attention_forward_golden_noflash(
72+ q[q_off:q_off + s1_size, h, :],
73+ k[k_off:k_off + s2_size, h, :],
74+ v[k_off:k_off + s2_size, h, :],
75+ scale,
76+ )
77+ out_g[q_off:q_off + s1_size, h_off:h_off + dim] = o
78+ m_g[q_off:q_off + s1_size, h:h + 1] = m
79+ l_g[q_off:q_off + s1_size, h:h + 1] = softmax_l
80+ q_off += s1_size
81+ k_off += s2_size
82+ return out_g, l_g, m_g
83+ 
84+ 
85+@pytest.mark.soc("950")
86+def test_flash_attention_mha_minimal():
87+ """b=8,h=16,s=32,dim=32; pass_verify vs attention golden."""
88+ batch_size, num_heads, s1_size, s2_size, dim = 8, 16, 32, 32, 32
89+ hidden_dim = num_heads * dim
90+ q, k, v, cu_q, cu_k = _create_inputs(batch_size, s1_size, s2_size, num_heads, dim)
91+ total_q = batch_size * s1_size
92+ out = torch.empty(total_q, hidden_dim, dtype=torch.bfloat16)
93+ l_out = torch.empty(total_q, num_heads, dtype=torch.float32)
94+ m_out = torch.empty(total_q, num_heads, dtype=torch.float32)
95+ out_g, l_g, m_g = _compute_goldens(q, k, v, batch_size, num_heads, dim, s1_size, s2_size)
96+ set_verify_goldens([None, None, None, out_g, l_g, m_g, None, None])
97+ flash_attention_varlen_forward_kernel(q, k, v, out, l_out, m_out, cu_q, cu_k, _TILE_950)
98+ assert_pass_verify_ok()