Merged
test(pro): 随 QLI 测试提供独立的 CPU golden 和精度判据 #1127
test(pro): 随 QLI 测试提供独立的 CPU golden 和精度判据 #1127
Merged
xuzhenghao8Add on 6 days ago
Total: 4 files changed+1034-20
@@ -133,7 +133,7 @@ host 通过本轮生成的 `GET_TPL_TILING_KEY` 选 key,通过生成的 Tiling
133 133 
134## 验证134## 验证
135 135 
136-测试复用原算子的独立 CPU golden、合法同分集合检查和 Scheme A,未复制或放宽精度策略;候选长度与 padding 精确检查。136+JIT 和 ACLNN 测试共用本算子 `tests/assets/` 下的 CPU golden 和精度判据。索引检查合法同分集合,分数使用 Scheme A,候选长度与 padding 要求精确匹配。
137 137 
138```bash138```bash
139python -m pytest -q --mode=torch \139python -m pytest -q --mode=torch \
@@ -0,0 +1,641 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2024-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+ 
12+"""quant_lightning_indexer CPU Golden for the exact SPEC output ABI.
13+ 
14+Pure-torch CPU reference; no PyPTO and no NPU import, so the golden stays
15+independent from the implementation it validates. Four parts, top to bottom:
16+ 
17+1. reference math: ``decode`` / ``scores`` / ``visible_keys`` /
18+ ``candidate_scores`` - the four SPEC primitives;
19+2. ``CASES`` - the twelve delivered on-board cases (PA128 / PA64 / TND, ragged
20+ and causal-compressed visibility, candidates on and off, short sequences,
21+ empty query / empty key, two B=12 long-context cases), the single source the
22+ NPU test and the self-check share;
23+3. ``make_inputs`` - deterministic inputs plus the reference rows, and
24+ ``expected_scores`` - the expected score tensor for a given selection;
25+4. a CPU self-check (``python quant_lightning_indexer_golden_cpu.py``) that
26+ cross-validates the math against an independent FP64 / E2M1-bit-field oracle.
27+ 
28+The score chain is a numeric contract, not an optimization target: QK is rounded
29+to BF16 once, then heads 0..31 are folded with a multiply-add that is rounded to
30+BF16 after every step. It must not be replaced by a single FP32 reduction.
31+"""
32+ 
33+import logging
34+from itertools import accumulate
35+from typing import NamedTuple
36+ 
37+import torch
38+ 
39+_LOG = logging.getLogger(__name__)
40+ 
41+# SPEC 公式(数值契约,自检输出用它)
42+_SPEC_FORMULA = (
43+ 'q_f = decode_mxfp4(q, descale_q); k_f = decode_mxfp4(k, descale_k); '
44+ 'qk = bf16(q_f @ k_f^T).float(); w_b = bf16(w).float(); '
45+ 'acc_0 = 0; acc_{h+1} = bf16(acc_h + relu(qk[:, h]) * w_b[:, h]).float(), '
46+ 'h = 0..31; score = acc_32; '
47+ 'visible(t) = 0 if t >= Lq, else Lk if mask_mode == 0, else '
48+ 'min(Lk, max(0, (cmp_ratio * Lk + residual - Lq + t + 1) // cmp_ratio)); '
49+ 'candidate block score = max over the 8 tokens of the block, and the '
50+ 'trailing partial block of a query whose visible count is not a multiple '
51+ 'of 8 is +inf'
52+)
53+ 
54+HEADS = 32
55+CANDIDATE_CAPACITY = 2048
56+TOPK = 512
57+SEED = 20260929
58+_HEAD_DIM = 128
59+_PACKED_DIM = _HEAD_DIM // 2
60+_SCALES_PER_HEAD = 4
61+_SCALE_GROUP = _HEAD_DIM // _SCALES_PER_HEAD
62+_SCALE_BIAS = 127
63+# Above this many key rows the FP64 oracle is skipped (host memory / runtime);
64+# the two long-context typical cases are contract-checked without it.
65+_ORACLE_KEY_LIMIT = 200000
66+ 
67+# ===== 交付算例定义(测试与自检共用的唯一来源)=====
68+# name -> spec; keys see _SPEC_DEFAULTS. Only these twelve are delivered.
69+CASES = {
70+ "pa128_ragged": {"layout": "PA_BBND", "page_size": 128, "mask": 0},
71+ "pa64_causal_candidates": {
72+ "layout": "PA_BBND", "page_size": 64, "mask": 3, "candidates": True},
73+ "tnd_causal": {"layout": "TND", "page_size": 128, "mask": 3},
74+ "candidate16_ld_tail": {
75+ "layout": "PA_BBND", "page_size": 64, "mask": 3, "candidates": True,
76+ "candidate_capacity": 16},
77+ "invalid_values_PA_BBND": {
78+ "layout": "PA_BBND", "page_size": 128, "mask": 0,
79+ "key_lengths": (19, 73)},
80+ "invalid_values_TND": {
81+ "layout": "TND", "page_size": 128, "mask": 0, "key_lengths": (19, 73)},
82+ "empty_query_PA_BBND": {
83+ "layout": "PA_BBND", "page_size": 128, "mask": 0,
84+ "key_lengths": (19, 73), "empty": "query"},
85+ "empty_key_PA_BBND": {
86+ "layout": "PA_BBND", "page_size": 128, "mask": 0,
87+ "key_lengths": (19, 73), "empty": "key"},
88+ "empty_query_TND": {
89+ "layout": "TND", "page_size": 128, "mask": 0, "key_lengths": (19, 73),
90+ "empty": "query"},
91+ "empty_key_TND": {
92+ "layout": "TND", "page_size": 128, "mask": 0, "key_lengths": (19, 73),
93+ "empty": "key"},
94+ "b12_s1_6_n32_s2_64k": {
95+ "layout": "PA_BBND", "page_size": 128, "mask": 3,
96+ "query_lengths": (6,) * 12, "key_lengths": (65536,) * 12,
97+ "signed_weights": True, "uniform_scale": True},
98+ "b12_s1_6_n32_s2_128k": {
99+ "layout": "PA_BBND", "page_size": 128, "mask": 3,
100+ "query_lengths": (6,) * 12, "key_lengths": (131072,) * 12,
@@ -0,0 +1,375 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2024-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+ 
12+"""精度对比引擎 — 当前工作流固定的方案A混合容差策略。
13+ 
14+以下阈值和判定逻辑以本文件为当前可执行事实源:
15+ - 逐元素通过条件: |actual - golden| <= atol + rtol * |golden|
16+ - 整体通过条件: matched_ratio >= required_matched_ratio AND max_abs_error <= max_abs_error_limit
17+ AND mean_abs_error <= atol AND mean_rel_error <= rtol
18+ - max_abs_error_limit = max(fixed_limit, 32 * ULP) ('or' 语义取较大者)
19+ 
20+阈值表硬编码,不接受外部参数(防作弊)。
21+纯 CPU + torch 实现,不依赖 torch_npu。
22+"""
23+ 
24+from typing import List, Optional, Tuple, Union
25+ 
26+import torch
27+ 
28+# ============================================================================
29+# 当前工作流固定阈值表(可执行事实源)
30+# ============================================================================
31+ 
32+_REQUIRED_MATCHED_RATIO = 0.99
33+ 
34+# 每种 dtype 的阈值元组含义: (rtol, atol, fixed_max_abs_limit)
35+_THRESHOLDS = {
36+ torch.float16: (2.0**-9, 2.0**-9, 1e-1), # 1.95e-3, 1.95e-3, 0.1
37+ torch.bfloat16: (2.0**-6, 2.0**-6, 1e-0), # 1.56e-2, 1.56e-2, 1.0
38+ torch.float32: (2.0**-10, 2.0**-16, 1e-2), # 9.77e-4, 1.53e-5, 0.01
39+ torch.float64: (2.0**-10, 2.0**-16, 1e-2), # 同 float32
40+}
41+ 
42+# 对外接受的 dtype 名称及常用别名;未列出的名称显式拒绝
43+_DTYPE_NAME_MAP = {
44+ "float16": torch.float16,
45+ "bfloat16": torch.bfloat16,
46+ "float32": torch.float32,
47+ "float64": torch.float64,
48+ "half": torch.float16,
49+ "float": torch.float32,
50+ "double": torch.float64,
51+}
52+ 
53+ 
54+def _get_threshold(dtype):
55+ """查表返回 (rtol, atol, required_matched_ratio, max_abs_error_limit)。
56+ 
57+ 对已登记浮点类型返回阈值;其他 dtype 返回 None,由调用方再区分整数精确匹配
58+ 与不支持类型,避免把未知浮点、复数或量化类型误当作整数。
59+ """
60+ if dtype in _THRESHOLDS:
61+ rtol, atol, fixed_limit = _THRESHOLDS[dtype]
62+ ulp = _compute_ulp(dtype)
63+ max_abs_limit = max(fixed_limit, 32.0 * ulp)
64+ return rtol, atol, _REQUIRED_MATCHED_RATIO, max_abs_limit
65+ # 整数类型 → 精确匹配
66+ return None
67+ 
68+ 
69+def _compute_ulp(dtype):
70+ """计算给定 dtype 的 ULP (Unit in the Last Place)。
71+ 
72+ ULP = 2^(exponent - mantissa_bits),取 1.0 附近的 ULP 值。
73+ """
74+ try:
75+ one = torch.tensor(1.0, dtype=dtype)
76+ nxt = torch.nextafter(one, torch.tensor(2.0, dtype=dtype))
77+ return (nxt - one).item()
78+ except (TypeError, RuntimeError):
79+ # 降级:用 finfo 推算
80+ fi = torch.finfo(dtype)
81+ return fi.eps
82+ 
83+ 
84+def _to_cpu(tensor):
85+ """转到 CPU,不改变 dtype。"""
86+ if isinstance(tensor, torch.Tensor):
87+ return tensor.cpu() if tensor.is_cuda or "npu" in str(tensor.device) else tensor
88+ return tensor
89+ 
90+ 
91+# ============================================================================
92+# 核心对比逻辑
93+# ============================================================================
94+ 
95+def _compare_integer(actual, golden, total):
96+ passed = torch.equal(actual, golden)
97+ if passed:
98+ return True, "exact match (integer)", {"matched_ratio": 1.0, "max_abs_error": 0.0}
99+ mismatch = (actual != golden).sum().item()
100+ metrics = {"matched_ratio": 1 - mismatch / total}
101+ return False, f"integer mismatch: {mismatch}/{total} elements differ", metrics
102+ 
103+ 
104+def _prepare_float_tensors(actual, golden, comparison_dtype):
105+ actual_float = actual.to(torch.float64)
106+ golden_float = golden.to(torch.float64)
107+ actual_nan = torch.isnan(actual_float)
108+ golden_nan = torch.isnan(golden_float)
109+ nan_mismatch = (actual_nan != golden_nan).sum().item()
110+ if nan_mismatch:
111+ return None, f"NaN position mismatch: {nan_mismatch} positions differ"
112+ 
113+ actual_inf = torch.isinf(actual_float)
114+ golden_inf = torch.isinf(golden_float)
115+ both_inf = actual_inf & golden_inf
116+ inf_diff_sign = both_inf & (torch.sign(actual_float) != torch.sign(golden_float))
117+ if inf_diff_sign.any().item():
118+ return None, f"Inf sign mismatch: {inf_diff_sign.sum().item()} positions"
119+ 
120+ actual_clean = actual_float.clone()
121+ golden_clean = golden_float.clone()
122+ finfo = torch.finfo(comparison_dtype)
123+ actual_only_inf = actual_inf & ~golden_inf
124+ golden_only_inf = golden_inf & ~actual_inf
125+ actual_clean[actual_only_inf & (actual_float > 0)] = finfo.max
126+ actual_clean[actual_only_inf & (actual_float < 0)] = finfo.min
127+ golden_clean[golden_only_inf & (golden_float > 0)] = finfo.max
128+ golden_clean[golden_only_inf & (golden_float < 0)] = finfo.min
129+ same_inf = both_inf & (torch.sign(actual_float) == torch.sign(golden_float))
130+ match_mask = same_inf | actual_nan | golden_nan
131+ return (actual_clean, golden_clean, match_mask), None
132+ 
133+ 
134+def _calculate_float_metrics(prepared, threshold, total):
135+ actual, golden, match_mask = prepared
136+ rtol, atol, required_ratio, max_abs_limit = threshold
137+ compare_mask = ~match_mask
138+ if not compare_mask.any().item():
139+ matched_ratio = 1.0
140+ max_abs_error = 0.0
141+ mean_abs_error = 0.0
142+ mean_rel_error = 0.0
143+ else:
144+ diff = (actual - golden).abs()
145+ element_pass = diff <= atol + rtol * golden.abs()
146+ pass_count = (element_pass & compare_mask).sum().item() + match_mask.sum().item()
147+ matched_ratio = pass_count / total
148+ max_abs_error = diff[compare_mask].max().item()
149+ mean_abs_error = diff[compare_mask].mean().item()
150+ golden_abs = golden.abs()[compare_mask]
151+ rel_valid = golden_abs > 0
152+ if rel_valid.any().item():
153+ mean_rel_error = (diff[compare_mask][rel_valid] / golden_abs[rel_valid]).mean().item()
154+ else:
155+ mean_rel_error = 0.0
156+ return {
157+ "matched_ratio": matched_ratio,
158+ "max_abs_error": max_abs_error,
159+ "mean_abs_error": mean_abs_error,
160+ "mean_rel_error": mean_rel_error,
161+ "required_matched_ratio": required_ratio,
162+ "max_abs_error_limit": max_abs_limit,
163+ "rtol": rtol,
164+ "atol": atol,
165+ }
166+ 
167+ 
168+def _format_float_result(metrics):
169+ checks = [
170+ ("atol", metrics["mean_abs_error"], metrics["atol"], "GT"),
171+ ("rtol", metrics["mean_rel_error"], metrics["rtol"], "GT"),
172+ ("matched_ratio", metrics["matched_ratio"], metrics["required_matched_ratio"], "LT"),
173+ ("max_abs_error", metrics["max_abs_error"], metrics["max_abs_error_limit"], "GT"),
174+ ]
175+ failed = {
176+ name
177+ for name, value, thresh, op in checks
178+ if (value > thresh if op == "GT" else value < thresh)
179+ }
180+ passed = not failed
181+ lines = [f"precision {'PASS' if passed else 'FAIL'}"]
182+ for name, value, thresh, op in checks:
183+ if name == "matched_ratio":
184+ val_s, thr_s = f"{value:.4f}", f"{thresh:.4f}"
185+ else:
186+ val_s, thr_s = f"{value:.3e}", f"{thresh:.3e}"
187+ lines.append(
188+ f" {name:<16}: {val_s:<10}thresh={thr_s:<10}check={op}"
189+ + (" [CHECK_FAILED]" if name in failed else "")
190+ )
191+ lines.append("-" * 100)
192+ summary = "\n".join(lines)
193+ return passed, summary, metrics
194+ 
195+ 
196+def _compare_single_tensor(actual: torch.Tensor, golden: torch.Tensor, threshold_dtype=None) -> Tuple[bool, str, dict]:
197+ """对比单个 tensor,返回 (passed, summary, metrics)。
198+ 
199+ 按本文件固定策略:
200+ - 浮点: 混合容差 + matched_ratio + max_abs_error_limit
201+ - 整数: torch.equal 精确匹配
202+ - NaN 位置必须一致
203+ - Inf: 同号视为匹配;异号 FAIL;一方 Inf 一方有限值→替换为 finfo.max 后正常判定
204+ """
205+ actual = _to_cpu(actual)
206+ golden = _to_cpu(golden)
207+ if actual.shape != golden.shape:
208+ return False, f"shape mismatch: actual={tuple(actual.shape)} vs golden={tuple(golden.shape)}", {}
209+ total = actual.numel()
210+ if actual.is_quantized or golden.is_quantized:
211+ return False, f"unsupported quantized dtype pair: actual={actual.dtype}, golden={golden.dtype}", {}
212+ if actual.is_complex() or golden.is_complex():
213+ return False, f"unsupported complex dtype pair: actual={actual.dtype}, golden={golden.dtype}", {}
214+ 
215+ comparison_dtype = threshold_dtype or actual.dtype
216+ threshold = _get_threshold(comparison_dtype)
217+ if threshold is None:
218+ if actual.dtype != golden.dtype:
219+ return False, f"dtype mismatch for exact comparison: actual={actual.dtype}, golden={golden.dtype}", {}
220+ if actual.is_floating_point() or golden.is_floating_point():
221+ return False, f"unsupported floating dtype: {comparison_dtype}", {}
222+ if actual.dtype != torch.bool:
223+ try:
224+ torch.iinfo(actual.dtype)
225+ except (TypeError, RuntimeError):
226+ return False, f"unsupported exact-comparison dtype: {actual.dtype}", {}
227+ if total == 0:
228+ return True, "empty tensor", {}
229+ return _compare_integer(actual, golden, total)
230+ if not actual.is_floating_point() or not golden.is_floating_point():
231+ return (
232+ False,
233+ f"unsupported dtype pair for floating comparison: actual={actual.dtype}, golden={golden.dtype}",
234+ {},
235+ )
236+ if total == 0:
237+ return True, "empty tensor", {}
238+ prepared, error = _prepare_float_tensors(actual, golden, comparison_dtype)
239+ if error is not None:
240+ return False, error, {}
241+ metrics = _calculate_float_metrics(prepared, threshold, total)
242+ return _format_float_result(metrics)
243+ 
244+ 
245+def _normalize_outputs(output) -> List[Optional[torch.Tensor]]:
246+ """将输出标准化为 tensor 列表。
247+ 
248+ 支持: 单个 tensor / tuple / list / None 占位。None 只能作为多输出对齐占位;
249+ 顶层 None 或全 None 会由 check_precision 判定为失败。
250+ """
251+ if output is None:
252+ return [None]
253+ if isinstance(output, torch.Tensor):
254+ return [output]
255+ if isinstance(output, (tuple, list)):
256+ normalized = []
257+ for index, item in enumerate(output):
258+ if item is None or isinstance(item, torch.Tensor):
259+ normalized.append(item)
260+ else:
261+ raise TypeError(
262+ f"unsupported output leaf at index {index}: {type(item).__name__}"
263+ )
264+ return normalized
265+ raise TypeError(f"unsupported output type: {type(output).__name__}")
266+ 
267+ 
268+def check_precision(
269+ actual: Union[torch.Tensor, tuple, list],
270+ golden: Union[torch.Tensor, tuple, list],
271+ dtype_str: Optional[str] = None,
272+) -> Tuple[bool, str]:
273+ """精度对比主入口(方案A混合容差标准)。
274+ 
275+ Args:
276+ actual: 算子输出(NPU tensor 或 CPU tensor,单输出或多输出)
277+ golden: golden 参考输出(CPU FP32 更高精度)
278+ dtype_str: 可选,指定 dtype 名称字符串(默认从 actual 推断)
279+ 
280+ Returns:
281+ (passed, summary): passed=True/False, summary=人类可读的精度指标摘要
282+ 
283+ 本文件固定策略:
284+ - 逐元素: |actual - golden| <= atol + rtol * |golden|
285+ - 整体: matched_ratio >= 0.99 AND max_abs_error <= max_abs_error_limit
286+ - max_abs_error_limit = max(fixed_limit, 32 * ULP)
287+ - 整数: 精确匹配 (torch.equal)
288+ - NaN 位置必须一致
289+ - Inf: 同号匹配, 异号 FAIL, 一方Inf→替换为 finfo.max
290+ """
291+ try:
292+ actuals = _normalize_outputs(actual)
293+ goldens = _normalize_outputs(golden)
294+ except TypeError as error:
295+ return False, str(error)
296+ 
297+ if len(actuals) != len(goldens):
298+ return False, f"output count mismatch: actual={len(actuals)} vs golden={len(goldens)}"
299+ if dtype_str is not None and dtype_str not in _DTYPE_NAME_MAP:
300+ return False, f"unsupported dtype: {dtype_str}"
301+ threshold_dtype = _DTYPE_NAME_MAP.get(dtype_str)
302+ 
303+ all_passed = True
304+ summaries = []
305+ compared_tensors = 0
306+ 
307+ for i, (a, g) in enumerate(zip(actuals, goldens)):
308+ if a is None and g is None:
309+ continue
310+ if a is None or g is None:
311+ all_passed = False
312+ summaries.append(f"output[{i}]: one side is None")
313+ continue
314+ 
315+ compared_tensors += 1
316+ passed, summary, _ = _compare_single_tensor(a, g, threshold_dtype)
317+ if not passed:
318+ all_passed = False
319+ prefix = "" if len(actuals) == 1 else f"output[{i}]: "
320+ summaries.append(f"{prefix}{summary}")
321+ 
322+ if compared_tensors == 0:
323+ all_passed = False
324+ summaries.append("no tensor output was compared")
325+ 
326+ return all_passed, "; ".join(summaries)
327+ 
328+ 
329+# ============================================================================
330+# quant_lightning_indexer 专用:索引类输出的精确 Top-K 集合判定
331+# ============================================================================
332+# 本算子契约允许任意输出顺序与同分的任意合法集合(实测多数行的分数并不按分值排序、
333+# 部分行边界存在同分),golden 只产分数、不产索引集合,因此索引无法逐元素比较——
334+# 方案 A 对 int32 走 torch.equal,会把合法的同分排列判为失败。这部分按「集合」判定;
335+# 逐元素可比的输出(返回分数、candidate_lengths)仍走上面的方案 A 引擎。
336+# 与方案 A 一致:阈值硬编码、不接收外部容差,纯 CPU + torch,不依赖 torch_npu。
337+ 
338+ 
339+def check_topk(indices, expected, allowed, offset=0):
340+ """Tie-aware exact Top-K membership check for one query row's indices.
341+ 
342+ Args:
343+ indices: [topk] int32 实际输出;``-1`` 表示无效槽。
344+ expected: [n] float32 独立 CPU 参考分数(可见与不可见 key 都在内)。
345+ allowed: [n] bool 可见性掩码;只有可见 key 才允许被选中。
346+ offset: 加在有效 token 索引上的 ``output_idx_offset`` 标量。
347+ 
348+ 判定项(任何一项不满足即 AssertionError):
349+ - 选中数量 == min(topk, 可见 key 数)
350+ - 索引唯一、落在 ``[0, n)``、且全部可见
351+ - 选中集合不越过精确 Top-K 边界(同分并列时只要求边界,不要求具体排列;
352+ 边界为 +inf 时必须选中全部 +inf 块)
353+ """
354+ present = indices != -1
355+ selected = indices[present].long() - offset
356+ wanted = min(indices.numel(), int(allowed.sum()))
357+ if selected.numel() != wanted:
358+ raise AssertionError(
359+ f"selected {selected.numel()} indices, expected {wanted}")
360+ if selected.unique().numel() != selected.numel():
361+ raise AssertionError("selected indices are not unique")
362+ if not bool(((selected >= 0) & (selected < expected.numel())).all()):
363+ raise AssertionError("selected index out of the reference range")
364+ if not bool(allowed[selected].all()):
365+ raise AssertionError("an invisible key was selected")
366+ if not selected.numel():
367+ return
368+ got = expected[selected]
369+ boundary = expected[allowed].topk(selected.numel()).values[-1]
370+ if torch.isposinf(boundary):
371+ if not bool(torch.isposinf(got).all()):
372+ raise AssertionError("mandatory partial block was not selected as +inf")
373+ elif got.min() < boundary:
374+ raise AssertionError(
375+ f"selection crosses the exact TopK boundary ({got.min()} < {boundary})")
@@ -6,11 +6,7 @@
6# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.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.7# See LICENSE in the root of the software repository for the full text of the License.
8# -----------------------------------------------------------------------------------------------------------8# -----------------------------------------------------------------------------------------------------------
9-"""Replay the existing QLI golden through JIT or both formal Torch entries.9+"""Check the JIT and Torch entries against the CPU golden in tests/assets."""
10- 
11-The original golden and precision policy are shared instead of copied. Binary
12-mode imports no PyPTO kernel; all device work enters the installed Torch binding.
13-"""
14from functools import lru_cache10from functools import lru_cache
15import importlib.util11import importlib.util
16import inspect12import inspect
@@ -24,11 +20,18 @@ import torch
24import torch_npu # noqa: F40120import torch_npu # noqa: F401
25 21 
26HERE = Path(__file__).resolve().parent22HERE = Path(__file__).resolve().parent
27-GYM = HERE.parents[4]23+ 
28-BASE = GYM / "ops/pypto_pro/deepseek_v4_1/quant_lightning_indexer"24+ 
29-sys.path.insert(0, str(BASE / "tests/assets"))25+def _load_module(name, path):
30-import quant_lightning_indexer_golden_cpu as golden # noqa: E40226+ spec = importlib.util.spec_from_file_location(name, path)
31-from quant_lightning_indexer_precision import check_precision, check_topk # noqa: E40227+ module = importlib.util.module_from_spec(spec)
28+ sys.modules[name] = module
29+ spec.loader.exec_module(module)
30+ return module
31+ 
32+ 
33+golden = _load_module("gym_pro_qli_golden", HERE / "assets/quant_lightning_indexer_golden_cpu.py")
34+precision = _load_module("gym_pro_qli_precision", HERE / "assets/quant_lightning_indexer_precision.py")
32 35 
33pytestmark = pytest.mark.soc("950")36pytestmark = pytest.mark.soc("950")
34_ENTRY_CYCLE = itertools.cycle(("python", "torch"))37_ENTRY_CYCLE = itertools.cycle(("python", "torch"))
@@ -46,12 +49,7 @@ def _torch_entry(*args, **kwargs):
46 49 
47@lru_cache(maxsize=1)50@lru_cache(maxsize=1)
48def _jit_module():51def _jit_module():
49- path = HERE.parent / "op_kernel/quant_lightning_indexer.py"52+ return _load_module("gym_pro_quant_lightning_indexer", HERE.parent / "op_kernel/quant_lightning_indexer.py")
50- spec = importlib.util.spec_from_file_location("gym_pro_quant_lightning_indexer", path)
51- module = importlib.util.module_from_spec(spec)
52- sys.modules[spec.name] = module
53- spec.loader.exec_module(module)
54- return module
55 53 
56 54 
57def runner():55def runner():
@@ -75,9 +73,9 @@ def verify(outputs, kwargs, refs, allowed, return_value, offsets=True):
75 idx, val, cand, length = [t.cpu() for t in outputs]73 idx, val, cand, length = [t.cpu() for t in outputs]
76 assert idx.dtype == torch.int32 and idx.shape == (len(refs), 1, kwargs["topk"])74 assert idx.dtype == torch.int32 and idx.shape == (len(refs), 1, kwargs["topk"])
77 for row, (ref, valid) in enumerate(zip(refs, allowed)):75 for row, (ref, valid) in enumerate(zip(refs, allowed)):
78- check_topk(idx[row, 0], ref, valid, row * 10000 if offsets else 0)76+ precision.check_topk(idx[row, 0], ref, valid, row * 10000 if offsets else 0)
79 if return_value:77 if return_value:
80- passed, summary = check_precision(val, golden.expected_scores(idx, refs))78+ passed, summary = precision.check_precision(val, golden.expected_scores(idx, refs))
81 assert passed, summary79 assert passed, summary
82 else:80 else:
83 assert val.shape == (0,) and val.dtype == torch.bfloat1681 assert val.shape == (0,) and val.dtype == torch.bfloat16
@@ -90,7 +88,7 @@ def verify(outputs, kwargs, refs, allowed, return_value, offsets=True):
90 score, active = golden.candidate_scores(ref, valid)88 score, active = golden.candidate_scores(ref, valid)
91 count = min(capacity, int(active.sum()))89 count = min(capacity, int(active.sum()))
92 counts.append(count)90 counts.append(count)
93- check_topk(cand[row, 0, :count], score, active)91+ precision.check_topk(cand[row, 0, :count], score, active)
94 assert bool((cand[row, 0, count:] == -1).all())92 assert bool((cand[row, 0, count:] == -1).all())
95 assert torch.equal(length, torch.tensor(counts, dtype=torch.int32).view_as(length))93 assert torch.equal(length, torch.tensor(counts, dtype=torch.int32).view_as(length))
96 94