Merged
feat(interpreter): Interpreter python script remove ml_dtypes #5854
dingbo929Add on Sep 2
feat(interpreter): Interpreter python script remove ml_dtypes #5854
Merged
dingbo929Add on Sep 2
Total: 4 files changed+497-39
@@ -0,0 +1,259 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 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 for tools/verifier/dtype_decode.py: packed-dtype decoders (INT4/FP8/FP8E4M3/FP8E5M2/HF8/BF16).
12+ 
13+References:
14+- C++ decoders: framework/src/interface/machine/device/tilefwk/aicore_print_base.h
15+- C++ UT expectations: framework/tests/ut/machine/src/test_aicore_print.cpp (Fp8DecodeTest)
16+- HF8 spec branches: Tiny(D=0000)/Small(D=0001)/Medium(D=001)/Large(D=01)/Huge(D=10)/Max(D=11)
17+"""
18+ 
19+import os
20+import sys
21+ 
22+import numpy as np
23+import pytest
24+import torch
25+ 
26+_TOOLS_VERIFIER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "..", "tools", "verifier")
27+sys.path.insert(0, os.path.abspath(_TOOLS_VERIFIER))
28+ 
29+from dtype_decode import _decode_fp8e5m2_value, _decode_hf8_value, decode_tensor_data # noqa: E402
30+ 
31+ALL_BYTES = np.arange(256, dtype=np.uint8)
32+ 
33+ 
34+def _torch_f8_ref(raw, torch_dtype):
35+ return torch.from_numpy(raw).view(torch_dtype).float().numpy()
36+ 
37+ 
38+def _assert_bitwise_equal(actual, expected):
39+ """NaN-aware bitwise comparison: non-NaN values must match bit-for-bit (keeps -0.0); NaN on both sides passes."""
40+ actual = np.asarray(actual, dtype=np.float32)
41+ expected = np.asarray(expected, dtype=np.float32)
42+ assert actual.dtype == np.float32 and expected.dtype == np.float32
43+ nan_both = np.isnan(actual) & np.isnan(expected)
44+ assert not np.logical_xor(np.isnan(actual), np.isnan(expected)).any(), "NaN/non-NaN mismatch"
45+ diff = actual.view(np.uint32) != expected.view(np.uint32)
46+ assert np.logical_and(diff, ~nan_both).sum() == 0, (
47+ f"bitwise mismatch at: {np.flatnonzero(diff & ~nan_both)[:8]}"
48+ )
49+ 
50+ 
51+# ============================ INT4 ============================
52+class TestDecodeInt4:
53+ """One INT4 value per storage byte (low nibble), sign-extended to int8."""
54+ 
55+ def test_nibble_values(self):
56+ out = decode_tensor_data(np.array([0xAB, 0x12, 0xF8], dtype=np.uint8), "INT4")
57+ assert out.dtype == np.int8
58+ assert list(out) == [-5, 2, -8]
59+ 
60+ def test_boundary_values(self):
61+ out = decode_tensor_data(np.array([0x00, 0x77, 0x88, 0xF7, 0xFF], dtype=np.uint8), "INT4")
62+ # low nibble only: 0, 7, -8, 7, -1
63+ assert list(out) == [0, 7, -8, 7, -1]
64+ 
65+ def test_full_range(self):
66+ raw = np.arange(256, dtype=np.uint8)
67+ out = decode_tensor_data(raw, "INT4")
68+ assert out.shape == (256,)
69+ expected = ((raw.astype(np.int16) & 0xF) ^ 0x8) - 0x8
70+ assert np.array_equal(out.astype(np.int16), expected)
71+ 
72+ 
73+# ============================ FP8 / FP8E4M3 (E4M3FN) ============================
74+class TestDecodeFp8E4M3:
75+ """FP8 and FP8E4M3 are the same E4M3FN format: no inf, only 0x7F/0xFF is NaN."""
76+ 
77+ def test_zero(self):
78+ assert decode_tensor_data(np.array([0x00], dtype=np.uint8), "FP8")[0] == 0.0
79+ assert str(decode_tensor_data(np.array([0x80], dtype=np.uint8), "FP8")[0]) == "-0.0"
80+ 
81+ def test_nan_encoding(self):
82+ for bits in (0x7F, 0xFF):
83+ assert np.isnan(decode_tensor_data(np.array([bits], dtype=np.uint8), "FP8")[0]), hex(bits)
84+ 
85+ def test_max_finite(self):
86+ # exp=0b1111, mant=0b110 -> 448.0 (OCP float8_e4m3fn max)
87+ assert decode_tensor_data(np.array([0x7E], dtype=np.uint8), "FP8")[0] == 448.0
88+ 
89+ def test_normal_values(self):
90+ # 1.0 = 2^0 x 1.0 -> E=7, M=0 -> 0x38; 2.0 -> 0x40; 0.5 -> 0x30
91+ out = decode_tensor_data(np.array([0x38, 0x40, 0x30], dtype=np.uint8), "FP8")
92+ assert out.tolist() == [1.0, 2.0, 0.5]
93+ 
94+ def test_subnormal_values(self):
95+ # exp=0: mant * 2^-9
96+ out = decode_tensor_data(np.array([0x01, 0x07], dtype=np.uint8), "FP8")
97+ assert out.tolist() == [2.0**-9, 7 * 2.0**-9]
98+ 
99+ def test_fp8e4m3_alias_matches_fp8(self):
100+ assert np.array_equal(
101+ decode_tensor_data(ALL_BYTES, "FP8E4M3"), decode_tensor_data(ALL_BYTES, "FP8"), equal_nan=True
102+ )
103+ 
104+ def test_matches_torch_e4m3fn_all_256(self):
105+ if not hasattr(torch, "float8_e4m3fn"):
106+ pytest.skip("torch has no float8_e4m3fn")
107+ _assert_bitwise_equal(decode_tensor_data(ALL_BYTES, "FP8"), _torch_f8_ref(ALL_BYTES, torch.float8_e4m3fn))
108+ 
109+ 
110+# ============================ FP8E5M2 ============================
111+class TestDecodeFp8E5M2:
112+ """IEEE-style E5M2: has inf (0x7C/0xFC) and NaN (mant != 0 with exp=0b11111)."""
113+ 
114+ def test_zero_and_negzero(self):
115+ assert _decode_fp8e5m2_value(0x00) == 0.0
116+ assert str(_decode_fp8e5m2_value(0x80)) == "-0.0"
117+ 
118+ def test_inf(self):
119+ assert np.isinf(_decode_fp8e5m2_value(0x7C)) and _decode_fp8e5m2_value(0x7C) > 0
120+ assert np.isinf(_decode_fp8e5m2_value(0xFC)) and _decode_fp8e5m2_value(0xFC) < 0
121+ 
122+ def test_nan(self):
123+ for bits in (0x7D, 0x7E, 0x7F, 0xFD, 0xFE, 0xFF):
124+ assert np.isnan(_decode_fp8e5m2_value(bits)), hex(bits)
125+ 
126+ def test_subnormal(self):
127+ # exp=0: mant * 2^-16
128+ assert _decode_fp8e5m2_value(0x01) == 2.0**-16
129+ assert _decode_fp8e5m2_value(0x02) == 2 * 2.0**-16
130+ assert _decode_fp8e5m2_value(0x03) == 3 * 2.0**-16
131+ assert _decode_fp8e5m2_value(0x81) == -2.0**-16
132+ assert _decode_fp8e5m2_value(0x83) == -(3 * 2.0**-16)
133+ 
134+ def test_normal_values(self):
135+ # 0x3C=1.0 (E=15,M=0), 0x40=2.0, 0x44=4.0, 0x38=0.5
136+ assert _decode_fp8e5m2_value(0x3C) == 1.0
137+ assert _decode_fp8e5m2_value(0x40) == 2.0
138+ assert _decode_fp8e5m2_value(0x44) == 4.0
139+ assert _decode_fp8e5m2_value(0x38) == 0.5
140+ 
141+ def test_matches_torch_e5m2_all_256(self):
142+ if not hasattr(torch, "float8_e5m2"):
143+ pytest.skip("torch has no float8_e5m2")
144+ _assert_bitwise_equal(decode_tensor_data(ALL_BYTES, "FP8E5M2"), _torch_f8_ref(ALL_BYTES, torch.float8_e5m2))
145+ 
146+ 
147+# ============================ HF8 ============================
148+class TestDecodeHf8:
149+ """HiFloat8: S(1) + D(prefix) + E(variable) + M(variable), 6 decode branches."""
150+ 
151+ def test_tiny_branch(self):
152+ # D=0000: mv=0 -> +0 (sign=0) / NaN (sign=1); mv>0: 2^(mv-23)
153+ assert _decode_hf8_value(0x00) == 0.0
154+ assert np.isnan(_decode_hf8_value(0x80)) and not np.isinf(_decode_hf8_value(0x80))
155+ assert _decode_hf8_value(0x01) == 2.0**-22
156+ assert _decode_hf8_value(0x07) == 2.0**-16
157+ 
158+ def test_small_branch(self):
159+ # D=0001: value = 1 + mv/8, mv in [0,7]
160+ assert _decode_hf8_value(0x08) == 1.0
161+ assert _decode_hf8_value(0x0F) == 1.875
162+ 
163+ def test_medium_branch(self):
164+ # D=001: 1-bit eb, ev=+1/-1, value = 2^ev * (1 + mv/8)
165+ assert _decode_hf8_value(0x18) == 0.5 # ev=-1, mv=0
166+ assert _decode_hf8_value(0x10) == 2.0 # ev=+1, mv=0
167+ 
168+ def test_large_branch(self):
169+ # D=01: 2-bit eb, ev in +-[2,3]
170+ assert _decode_hf8_value(0x20) == 4.0 # ev=+2, mv=0
171+ 
172+ def test_huge_branch(self):
173+ # D=10: 3-bit eb, ev in +-[4,7]
174+ assert _decode_hf8_value(0x40) == 16.0 # ev=+4, mv=0
175+ 
176+ def test_max_branch_and_inf(self):
177+ # D=11: 4-bit eb, ev in +-[8,15], 1-bit mv; S_11_0111_1 is inf
178+ assert np.isinf(_decode_hf8_value(0x6F)) and _decode_hf8_value(0x6F) > 0
179+ assert np.isinf(_decode_hf8_value(0xEF)) and _decode_hf8_value(0xEF) < 0
180+ # 0x6E (ev=15, mv=0) is max normal 32768, not inf
181+ assert not np.isinf(_decode_hf8_value(0x6E))
182+ assert _decode_hf8_value(0x6E) == 32768.0
183+ 
184+ def test_sign_symmetry(self):
185+ # i in [1,128), skip inf(0x6F) / NaN(0x80) / -inf(0xEF)
186+ for i in range(1, 128):
187+ if i == 0x6F:
188+ continue
189+ pos = _decode_hf8_value(i)
190+ neg = _decode_hf8_value(i | 0x80)
191+ if (i | 0x80) in (0x80, 0xEF):
192+ continue
193+ assert pos > 0 and neg < 0, f"sign fail at {i:#04x}"
194+ assert abs(pos) == abs(neg), f"symmetry fail at {i:#04x}"
195+ 
196+ def test_array_decode_uses_lut_consistently(self):
197+ lut = decode_tensor_data(ALL_BYTES, "HF8")
198+ assert lut.dtype == np.float32
199+ per_value = np.array([_decode_hf8_value(i) for i in range(256)], dtype=np.float32)
200+ assert np.array_equal(lut, per_value, equal_nan=True)
201+ 
202+ 
203+# ============================ BF16 ============================
204+class TestDecodeBf16:
205+ """BF16 read as uint16 raw, decode = bit-shift into fp32 exponent/mantissa layout."""
206+ 
207+ def test_roundtrip_of_known_values(self):
208+ raw = np.array([0x0000, 0x3F80, 0xBF80, 0x7F7F, 0x3FC0], dtype=np.uint16)
209+ out = decode_tensor_data(raw, "BF16")
210+ assert out.dtype == np.float32
211+ # 0x7F7F is bf16 max finite, smaller than fp32 max
212+ assert np.allclose(out, [0.0, 1.0, -1.0, 3.3895313892515355e38, 1.5])
213+ 
214+ def test_inf_and_nan(self):
215+ out = decode_tensor_data(np.array([0x7F80, 0xFF80, 0x7FC0], dtype=np.uint16), "BF16")
216+ assert np.isinf(out[0]) and out[0] > 0
217+ assert np.isinf(out[1]) and out[1] < 0
218+ assert np.isnan(out[2])
219+ 
220+ def test_subnormal(self):
221+ # smallest bf16 subnormal = 2^-133
222+ out = decode_tensor_data(np.array([0x0001], dtype=np.uint16), "BF16")
223+ assert out[0] == np.float32(2.0**-133)
224+ 
225+ def test_matches_torch_bf16_all_65536(self):
226+ raw = np.arange(65536, dtype=np.uint16)
227+ out = decode_tensor_data(raw, "BF16")
228+ ref = torch.from_numpy(raw.astype(np.int64)).to(torch.int32).numpy().astype(np.uint32)
229+ ref = (ref << 16).view(np.float32)
230+ _assert_bitwise_equal(out, ref)
231+ 
232+ 
233+# ============================ decode_tensor_data routing ============================
234+class TestDecodeTensorDataRouting:
235+ def test_unknown_dtype_passthrough(self):
236+ for dtype_name in ("INT32", "FP32", "DOUBLE", "UINT8", "BOOL", "UNKNOWN"):
237+ data = np.array([1, 2, 3], dtype=np.int32)
238+ assert decode_tensor_data(data, dtype_name) is data, dtype_name
239+ 
240+ def test_result_dtypes(self):
241+ assert decode_tensor_data(np.array([0], dtype=np.uint8), "INT4").dtype == np.int8
242+ assert decode_tensor_data(np.array([0], dtype=np.uint8), "FP8").dtype == np.float32
243+ assert decode_tensor_data(np.array([0], dtype=np.uint8), "FP8E4M3").dtype == np.float32
244+ assert decode_tensor_data(np.array([0], dtype=np.uint8), "FP8E5M2").dtype == np.float32
245+ assert decode_tensor_data(np.array([0], dtype=np.uint8), "HF8").dtype == np.float32
246+ assert decode_tensor_data(np.array([0], dtype=np.uint16), "BF16").dtype == np.float32
247+ 
248+ def test_empty_input(self):
249+ out = decode_tensor_data(np.array([], dtype=np.uint8), "INT4")
250+ assert out.shape == (0,) and out.dtype == np.int8
251+ for dtype_name in ("FP8", "FP8E4M3", "FP8E5M2", "HF8"):
252+ out = decode_tensor_data(np.array([], dtype=np.uint8), dtype_name)
253+ assert out.shape == (0,) and out.dtype == np.float32, dtype_name
254+ assert decode_tensor_data(np.array([], dtype=np.uint16), "BF16").shape == (0,)
255+ 
256+ def test_shape_preserved(self):
257+ raw = np.arange(24, dtype=np.uint8).reshape(2, 3, 4)
258+ out = decode_tensor_data(raw, "HF8")
259+ assert out.shape == (2, 3, 4)
@@ -0,0 +1,160 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 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+"""Dtype decode utilities: decode packed low-precision dtypes (INT4/FP8/HF8/BF16) to numeric values."""
12+ 
13+import numpy as np
14+ 
15+ 
16+def _build_fp8_e4m3fn_lut():
17+ lut = np.zeros(256, dtype=np.float32)
18+ for i in range(256):
19+ sign = -1.0 if i & 0x80 else 1.0
20+ exp = (i >> 3) & 0xF
21+ mant = i & 0x7
22+ if exp == 0:
23+ val = mant * 2.0**-9
24+ elif exp == 15 and mant == 7:
25+ val = float("nan")
26+ else:
27+ val = (1.0 + mant / 8.0) * 2.0 ** (exp - 7)
28+ lut[i] = sign * val
29+ return lut
30+ 
31+ 
32+_FP8_E4M3FN_LUT = _build_fp8_e4m3fn_lut()
33+ 
34+ 
35+def _decode_fp8e5m2_value(bits):
36+ """Decode one FP8 E5M2 byte to float. Python port of C++ DecodeFp8E5M2 in aicore_print_base.h."""
37+ sign = -1.0 if (bits >> 7) & 0x1 else 1.0
38+ exp = (bits >> 2) & 0x1F
39+ mant = bits & 0x3
40+ if exp == 0:
41+ if mant == 0:
42+ return sign * 0.0
43+ # subnormal: mant/4 * 2^(1-15) = mant * 2^-16
44+ return sign * mant * 2.0**-16
45+ if exp == 0x1F: # E5M2 has infinity
46+ if mant == 0:
47+ return sign * float("inf")
48+ return float("nan")
49+ return sign * (1.0 + mant / 4.0) * 2.0 ** (exp - 15)
50+ 
51+ 
52+def _build_fp8e5m2_lut():
53+ lut = np.zeros(256, dtype=np.float32)
54+ for i in range(256):
55+ lut[i] = _decode_fp8e5m2_value(i)
56+ return lut
57+ 
58+ 
59+_FP8E5M2_LUT = _build_fp8e5m2_lut()
60+ 
61+ 
62+def _decode_hf8_value(bits):
63+ """Decode one HF8 (HiFloat8) byte to float. Python port of C++ DecodeHf8 in aicore_print_base.h."""
64+ sign_bit = (bits >> 7) & 0x1
65+ sign = -1.0 if sign_bit else 1.0
66+ lower7 = bits & 0x7F
67+ top4 = lower7 >> 3
68+ if top4 == 0: # Tiny (D=0000): mv in [0,7], value = 2^(mv-23); mv=0: sign=0 -> +0, sign=1 -> NaN
69+ mv = lower7 & 0x7
70+ if mv == 0:
71+ if sign_bit:
72+ return float("nan")
73+ return 0.0
74+ return sign * 2.0 ** (mv - 23)
75+ if top4 == 1: # Small (D=0001): ev=0, mv in [0,7], value = (1 + mv/8)
76+ mv = lower7 & 0x7
77+ return sign * (1.0 + mv / 8.0)
78+ top3 = lower7 >> 4
79+ if top3 == 1: # Medium (D=001): 1-bit eb, ev = +1/-1, mv in [0,7]
80+ eb = (lower7 >> 3) & 0x1
81+ ev = -1 if eb else 1
82+ mv = lower7 & 0x7
83+ return sign * 2.0**ev * (1.0 + mv / 8.0)
84+ top2 = lower7 >> 5
85+ if top2 == 1: # Large (D=01): 2-bit eb, ev = ±[2,3], mv in [0,7]
86+ eb = (lower7 >> 3) & 0x3
87+ ev_sign = (eb >> 1) & 0x1
88+ ev_abs = 2 + (eb & 0x1)
89+ ev = -ev_abs if ev_sign else ev_abs
90+ mv = lower7 & 0x7
91+ return sign * 2.0**ev * (1.0 + mv / 8.0)
92+ if top2 == 2: # Huge (D=10): 3-bit eb, ev = ±[4,7], mv in [0,3]
93+ eb = (lower7 >> 2) & 0x7
94+ ev_sign = (eb >> 2) & 0x1
95+ ev_abs = 4 + (eb & 0x3)
96+ ev = -ev_abs if ev_sign else ev_abs
97+ mv = lower7 & 0x3
98+ return sign * 2.0**ev * (1.0 + mv / 4.0)
99+ # Max (D=11): 4-bit eb, ev = ±[8,15], mv in [0,1]; S_11_0111_1 (ev=15, mv=1) is infinity
100+ eb = (lower7 >> 1) & 0xF
101+ ev_sign = (eb >> 3) & 0x1
102+ ev_abs = 8 + (eb & 0x7)
103+ ev = -ev_abs if ev_sign else ev_abs
104+ mv = lower7 & 0x1
105+ if ev == 15 and mv == 1:
106+ return sign * float("inf")
107+ return sign * 2.0**ev * (1.0 + mv / 2.0)
108+ 
109+ 
110+def _build_hf8_lut():
111+ lut = np.zeros(256, dtype=np.float32)
112+ for i in range(256):
113+ lut[i] = _decode_hf8_value(i)
114+ return lut
115+ 
116+ 
117+_HF8_LUT = _build_hf8_lut()
118+ 
119+ 
120+def _decode_int4(raw):
121+ v = raw.astype(np.int16) & 0xF
122+ return ((v ^ 0x8) - 0x8).astype(np.int8)
123+ 
124+ 
125+def _decode_fp8(raw):
126+ return _FP8_E4M3FN_LUT[raw.astype(np.uint8)]
127+ 
128+ 
129+def _decode_fp8e5m2(raw):
130+ return _FP8E5M2_LUT[raw.astype(np.uint8)]
131+ 
132+ 
133+def _decode_hf8(raw):
134+ return _HF8_LUT[raw.astype(np.uint8)]
135+ 
136+ 
137+def _decode_bf16(raw):
138+ return (raw.astype(np.uint32) << 16).view(np.float32)
139+ 
140+ 
141+_dtype_decoders = {
142+ "INT4": _decode_int4,
143+ "FP8": _decode_fp8,
144+ "FP8E4M3": _decode_fp8,
145+ "FP8E5M2": _decode_fp8e5m2,
146+ "HF8": _decode_hf8,
147+ "BF16": _decode_bf16,
148+}
149+ 
150+ 
151+def decode_tensor_data(data, dtype_name):
152+ """Decode raw storage bytes (uint8/uint16) to numeric values for packed dtypes.
153+ 
154+ INT4/FP8/FP8E4M3/FP8E5M2/HF8/BF16 are read as raw bytes (uint8/uint16) from files; this decodes
155+ them to int8/float32. Other dtypes are returned unchanged.
156+ """
157+ decoder = _dtype_decoders.get(dtype_name)
158+ if decoder is None:
159+ return data
160+ return decoder(data)
@@ -21,7 +21,7 @@ import struct
21import time21import time
22from typing import Dict22from typing import Dict
23 23 
24-import ml_dtypes24+from dtype_decode import decode_tensor_data
25import numpy as np25import numpy as np
26import pandas as pd26import pandas as pd
27from tensor_diff import IsCloseConfig, compare_tensors_result_dict27from tensor_diff import IsCloseConfig, compare_tensors_result_dict
@@ -31,6 +31,8 @@ import torch
31DEV_SHAPE_DIM_MAX = 6 # 替换为实际值31DEV_SHAPE_DIM_MAX = 6 # 替换为实际值
32BYTE_ORDER = "<" # 小端:< ;大端:> ;本机字节序:=32BYTE_ORDER = "<" # 小端:< ;大端:> ;本机字节序:=
33RESULT_FILE = ""33RESULT_FILE = ""
34+ATOL_OVERRIDE = None
35+RTOL_OVERRIDE = None
34 36 
35# 单个字段的字节数定义(无对齐,纯原始字节)37# 单个字段的字节数定义(无对齐,纯原始字节)
36FIELD_SIZES = {"uint8_t": 1, "uint16_t": 2, "uint32_t": 4, "int32_t": 4, "int64_t": 8, "uint64_t": 8}38FIELD_SIZES = {"uint8_t": 1, "uint16_t": 2, "uint32_t": 4, "int32_t": 4, "int64_t": 8, "uint64_t": 8}
@@ -47,24 +49,26 @@ logging.basicConfig(
47 49 
48 50 
49_data_type_full_mapping = {51_data_type_full_mapping = {
50- 0: ("INT4", ml_dtypes.int4),52+ 0: ("INT4", np.uint8),
51 1: ("INT8", np.int8),53 1: ("INT8", np.int8),
52 2: ("INT16", np.int16),54 2: ("INT16", np.int16),
53 3: ("INT32", np.int32),55 3: ("INT32", np.int32),
54 4: ("INT64", np.int64),56 4: ("INT64", np.int64),
55- 5: ("FP8", ml_dtypes.float8_e4m3fn),57+ 5: ("FP8", np.uint8),
56 6: ("FP16", np.float16),58 6: ("FP16", np.float16),
57 7: ("FP32", np.float32),59 7: ("FP32", np.float32),
58- 8: ("BF16", ml_dtypes.bfloat16),60+ 8: ("BF16", np.uint16),
59 9: ("HF4", None), # 暂不支持解析61 9: ("HF4", None), # 暂不支持解析
60- 10: ("HF8", None), # 暂不支持解析62+ 10: ("HF8", np.uint8),
61 11: ("UINT8", np.uint8),63 11: ("UINT8", np.uint8),
62 12: ("UINT16", np.uint16),64 12: ("UINT16", np.uint16),
63 13: ("UINT32", np.uint32),65 13: ("UINT32", np.uint32),
64 14: ("UINT64", np.uint64),66 14: ("UINT64", np.uint64),
65 15: ("BOOL", np.bool_),67 15: ("BOOL", np.bool_),
66 16: ("DOUBLE", np.float64),68 16: ("DOUBLE", np.float64),
67- 17: ("BOTTOM", None),69+ 17: ("FP8E4M3", np.uint8),
70+ 18: ("FP8E5M2", np.uint8),
71+ 24: ("BOTTOM", None),
68}72}
69 73 
70 74 
@@ -79,29 +83,38 @@ def _get_dtype_from_str(dtype_str: str):
79 return str_to_dtype.get(dtype_str, None)83 return str_to_dtype.get(dtype_str, None)
80 84 
81 85 
82-def _get_compare_config(dtype):86+def _get_compare_config(dtype_name):
83 """87 """
84 根据数据类型返回合适的对比配置88 根据数据类型返回合适的对比配置
85 89 
86 Args:90 Args:
87- dtype: numpy dtype 对象,可能为 None91+ dtype_name: 数据类型名称字符串,可能为 None
88 92 
89 Returns:93 Returns:
90 IsCloseConfig: 对比配置对象,或 None(表示不支持的类型)94 IsCloseConfig: 对比配置对象,或 None(表示不支持的类型)
91 """95 """
92- if dtype is None:96+ if dtype_name is None:
93 return None97 return None
94 98 
95 # 整型数据:精确匹配99 # 整型数据:精确匹配
96- if np.issubdtype(dtype, np.integer):100+ if dtype_name in ("INT4", "INT8", "INT16", "INT32", "INT64", "UINT8", "UINT16", "UINT32", "UINT64"):
97- return IsCloseConfig(rtol=0, atol=0, calc_dtype=torch.float64, is_detail=True)101+ config = IsCloseConfig(rtol=0, atol=0, calc_dtype=torch.float64, is_detail=True)
98 102 
99 # FP32/FP64:标准容差103 # FP32/FP64:标准容差
100- if dtype in [np.float32, np.float64]:104+ elif dtype_name in ("FP32", "DOUBLE"):
101- return IsCloseConfig(rtol=1e-3, atol=1e-3, calc_dtype=torch.float64, is_detail=True)105+ config = IsCloseConfig(rtol=1e-3, atol=1e-3, calc_dtype=torch.float64, is_detail=True)
102 106 
103 # FP16/BF16/FP8 等低精度浮点:放宽容差107 # FP16/BF16/FP8 等低精度浮点:放宽容差
104- return IsCloseConfig(rtol=1e-2, atol=1e-2, calc_dtype=torch.float64, is_detail=True)108+ else:
109+ config = IsCloseConfig(rtol=1e-2, atol=1e-2, calc_dtype=torch.float64, is_detail=True)
110+ 
111+ # 命令行传入的 atol/rtol 优先,覆盖按 dtype 推导的默认值
112+ if ATOL_OVERRIDE is not None or RTOL_OVERRIDE is not None:
113+ config = config._replace(
114+ rtol=config.rtol if RTOL_OVERRIDE is None else RTOL_OVERRIDE,
115+ atol=config.atol if ATOL_OVERRIDE is None else ATOL_OVERRIDE,
116+ )
117+ return config
105 118 
106 119 
107class VerifyRes:120class VerifyRes:
@@ -208,7 +221,8 @@ class VerifyRes:
208 if os.path.exists(verify_tensor_info) and len(verify_tshape) == len(dump_tshape):221 if os.path.exists(verify_tensor_info) and len(verify_tshape) == len(dump_tshape):
209 dtype_result = _get_data_type(tensor_info["datatype"])222 dtype_result = _get_data_type(tensor_info["datatype"])
210 dtype = dtype_result[1]223 dtype = dtype_result[1]
211- verify_data_type = _get_dtype_from_str(tensor_info["A>:datatype"])224+ verify_dtype_name = str(tensor_info["A>:datatype"]).strip().upper()
225+ verify_data_type = _get_dtype_from_str(verify_dtype_name)
212 226 
213 # 不支持的类型,跳过对比227 # 不支持的类型,跳过对比
214 if dtype is None:228 if dtype is None:
@@ -217,9 +231,11 @@ class VerifyRes:
217 continue231 continue
218 232 
219 verify_tensor_data = np.fromfile(verify_tensor_info, verify_data_type)233 verify_tensor_data = np.fromfile(verify_tensor_info, verify_data_type)
234+ verify_tensor_data = decode_tensor_data(verify_tensor_data, verify_dtype_name)
220 verify_tensor_data = verify_tensor_data.reshape(verify_tshape)235 verify_tensor_data = verify_tensor_data.reshape(verify_tshape)
221 236 
222 data = np.fromfile(tensor_info["B>FILENAME"], dtype)237 data = np.fromfile(tensor_info["B>FILENAME"], dtype)
238+ data = decode_tensor_data(data, dtype_result[0])
223 data = data.reshape(dump_tshape)239 data = data.reshape(dump_tshape)
224 240 
225 slices = []241 slices = []
@@ -230,7 +246,7 @@ class VerifyRes:
230 sliced_data = data[tuple(slices)]246 sliced_data = data[tuple(slices)]
231 sliced_verify = verify_tensor_data[tuple(slices)]247 sliced_verify = verify_tensor_data[tuple(slices)]
232 248 
233- config = _get_compare_config(dtype)249+ config = _get_compare_config(dtype_result[0])
234 tensor_a = torch.from_numpy(sliced_data.astype(np.float64)).to(torch.float64)250 tensor_a = torch.from_numpy(sliced_data.astype(np.float64)).to(torch.float64)
235 tensor_b = torch.from_numpy(sliced_verify.astype(np.float64)).to(torch.float64)251 tensor_b = torch.from_numpy(sliced_verify.astype(np.float64)).to(torch.float64)
236 file_name = tensor_info["B>FILENAME"].split('/')[-1]252 file_name = tensor_info["B>FILENAME"].split('/')[-1]
@@ -588,10 +604,13 @@ class CompactDumpTensorInfoParser:
588 return merge_tensor_info604 return merge_tensor_info
589 605 
590 verify_tensor_data = np.fromfile(verify_tensor_info, dtype)606 verify_tensor_data = np.fromfile(verify_tensor_info, dtype)
607+ verify_tensor_data = decode_tensor_data(verify_tensor_data, dtype_result[0])
591 verify_tensor_data = verify_tensor_data.reshape(verify_tshape)608 verify_tensor_data = verify_tensor_data.reshape(verify_tshape)
592 609 
593- config = _get_compare_config(dtype)610+ config = _get_compare_config(dtype_result[0])
594- tensor_a = torch.from_numpy(raw_data.astype(np.float64)).to(torch.float64)611+ tensor_a = torch.from_numpy(decode_tensor_data(raw_data, dtype_result[0]).astype(np.float64)).to(
612+ torch.float64
613+ )
595 tensor_b = torch.from_numpy(verify_tensor_data.astype(np.float64)).to(torch.float64)614 tensor_b = torch.from_numpy(verify_tensor_data.astype(np.float64)).to(torch.float64)
596 file_name = merge_tensor_info["B>FILENAME"].split('/')[-1]615 file_name = merge_tensor_info["B>FILENAME"].split('/')[-1]
597 csv_path = os.path.join(RESULT_FILE[:-4] + ".DETAIL", file_name[:-5] + ".csv")616 csv_path = os.path.join(RESULT_FILE[:-4] + ".DETAIL", file_name[:-5] + ".csv")
@@ -649,7 +668,7 @@ class CompactDumpTensorInfoParser:
649 result["B>:rawshape"] = result["B>:rawshape"][:dims]668 result["B>:rawshape"] = result["B>:rawshape"][:dims]
650 669 
651 # 衍生字段(可选)670 # 衍生字段(可选)
652- result["B>:datatype"] = _get_data_type(result.get("datatype", 17))[0]671+ result["B>:datatype"] = _get_data_type(result.get("datatype", 24))[0]
653 672 
654 return result673 return result
655 674 
@@ -903,6 +922,12 @@ def parse_arguments():
903 help="directory like output/output_2026xxxxx/dump_tensor_device_x",922 help="directory like output/output_2026xxxxx/dump_tensor_device_x",
904 )923 )
905 parser.add_argument("--verify_path", type=str, default="", help="Path to verify_result.csv")924 parser.add_argument("--verify_path", type=str, default="", help="Path to verify_result.csv")
925+ parser.add_argument(
926+ "--atol", type=float, default=None, help="Absolute tolerance override; if not set, use dtype-based default"
927+ )
928+ parser.add_argument(
929+ "--rtol", type=float, default=None, help="Relative tolerance override; if not set, use dtype-based default"
930+ )
906 return parser.parse_args()931 return parser.parse_args()
907 932 
908 933 
@@ -911,8 +936,12 @@ def main():
911 timestamp = int(time.time() * 1_000_000)936 timestamp = int(time.time() * 1_000_000)
912 pass_full_name = get_pass_full_name(args.verify_path, "CodegenPreproc")937 pass_full_name = get_pass_full_name(args.verify_path, "CodegenPreproc")
913 csv_path = os.path.join(args.verify_path, f"verify_task_result_cmp~{pass_full_name}~{timestamp}.csv")938 csv_path = os.path.join(args.verify_path, f"verify_task_result_cmp~{pass_full_name}~{timestamp}.csv")
914- global RESULT_FILE939+ global RESULT_FILE, ATOL_OVERRIDE, RTOL_OVERRIDE
915 RESULT_FILE = csv_path940 RESULT_FILE = csv_path
941+ ATOL_OVERRIDE = args.atol
942+ RTOL_OVERRIDE = args.rtol
943+ if ATOL_OVERRIDE is not None or RTOL_OVERRIDE is not None:
944+ logging.info(f"Compare tolerance override: rtol={RTOL_OVERRIDE}, atol={ATOL_OVERRIDE}")
916 if not os.path.exists(args.dump_tensor_path):945 if not os.path.exists(args.dump_tensor_path):
917 logging.error(f"Directory does not exist: {args.dump_tensor_path}")946 logging.error(f"Directory does not exist: {args.dump_tensor_path}")
918 return947 return
@@ -21,13 +21,35 @@ import time
21import traceback21import traceback
22from typing import Any, Dict, List, Optional, Tuple22from typing import Any, Dict, List, Optional, Tuple
23 23 
24-import ml_dtypes24+from dtype_decode import decode_tensor_data
25import numpy as np25import numpy as np
26import pandas as pd26import pandas as pd
27from parse_dump_tensors import scan_pass_info_from_path27from parse_dump_tensors import scan_pass_info_from_path
28from tensor_diff import IsCloseConfig, compare_tensors_result_dict28from tensor_diff import IsCloseConfig, compare_tensors_result_dict
29import torch29import torch
30 30 
31+# 数据类型 -> 文件原始字节存储 dtype;INT4/FP8/FP8E4M3/FP8E5M2/HF8/BF16 为打包类型,读入后需经 decode_tensor_data 解码
32+_dtype_dict = {
33+ "INT4": np.uint8,
34+ "INT8": np.int8,
35+ "INT16": np.int16,
36+ "INT32": np.int32,
37+ "INT64": np.int64,
38+ "FP8": np.uint8,
39+ "FP8E4M3": np.uint8,
40+ "FP8E5M2": np.uint8,
41+ "HF8": np.uint8,
42+ "FP16": np.float16,
43+ "FP32": np.float32,
44+ "BF16": np.uint16,
45+ "UINT8": np.uint8,
46+ "UINT16": np.uint16,
47+ "UINT32": np.uint32,
48+ "UINT64": np.uint64,
49+ "BOOL": np.bool_,
50+ "DOUBLE": np.float64,
51+}
52+ 
31 53 
32@dataclass54@dataclass
33class ProcessLoopBatchArgs:55class ProcessLoopBatchArgs:
@@ -79,15 +101,7 @@ class PassComparator:
79 self.result_file = ""101 self.result_file = ""
80 self.row_num = 1102 self.row_num = 1
81 self.comparison_records: List[Dict[str, Any]] = []103 self.comparison_records: List[Dict[str, Any]] = []
82- self.dtype_dict = {104+ self.dtype_dict = _dtype_dict
83- "BF16": ml_dtypes.bfloat16,
84- "FP32": np.float32,
85- "FP16": np.float16,
86- "INT32": np.int32,
87- "INT8": np.int8,
88- "INT64": np.int64,
89- "INT16": np.int16,
90- }
91 105 
92 self.pass_dict = {106 self.pass_dict = {
93 "tensor_graph": 0,107 "tensor_graph": 0,
@@ -292,15 +306,7 @@ class PassComparator:
292 csv_data_dict = args.csv_data_dict306 csv_data_dict = args.csv_data_dict
293 result_file = args.result_file307 result_file = args.result_file
294 308 
295- dtype_dict = {309+ dtype_dict = _dtype_dict
296- "BF16": ml_dtypes.bfloat16,
297- "FP32": np.float32,
298- "FP16": np.float16,
299- "INT32": np.int32,
300- "INT8": np.int8,
301- "INT64": np.int64,
302- "INT16": np.int16,
303- }
304 310 
305 opcode_dict = {311 opcode_dict = {
306 "VIEW": ["L1_TO_L0A", "L1_TO_L0B"],312 "VIEW": ["L1_TO_L0A", "L1_TO_L0B"],
@@ -479,6 +485,8 @@ class PassComparator:
479 np_dtype = dtype_dict.get(a[":datatype"])485 np_dtype = dtype_dict.get(a[":datatype"])
480 data_a = np.fromfile(f_a, np_dtype)486 data_a = np.fromfile(f_a, np_dtype)
481 data_b = np.fromfile(f_b, np_dtype)487 data_b = np.fromfile(f_b, np_dtype)
488+ data_a = decode_tensor_data(data_a, a[":datatype"])
489+ data_b = decode_tensor_data(data_b, a[":datatype"])
482 490 
483 data_a = data_a.reshape(a_shape)491 data_a = data_a.reshape(a_shape)
484 data_b = data_b.reshape(b_shape)492 data_b = data_b.reshape(b_shape)
@@ -519,6 +527,8 @@ class PassComparator:
519 np_dtype = dtype_dict.get(a[":datatype"])527 np_dtype = dtype_dict.get(a[":datatype"])
520 data_a = np.fromfile(f_a, np_dtype)528 data_a = np.fromfile(f_a, np_dtype)
521 data_b = np.fromfile(f_b, np_dtype)529 data_b = np.fromfile(f_b, np_dtype)
530+ data_a = decode_tensor_data(data_a, a[":datatype"])
531+ data_b = decode_tensor_data(data_b, a[":datatype"])
522 532 
523 data_a = data_a.reshape(shape)533 data_a = data_a.reshape(shape)
524 data_b = data_b.reshape(shape)534 data_b = data_b.reshape(shape)