Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
tests: AVX2 dispatch never enters wider code (#795)
Niko122190dd021a70a8
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 995765af9..e1bcbd34f 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -1478,6 +1478,41 @@ if(STRATA_BUILD_TESTS)target_link_libraries(pool_stress PRIVATE strata_kernels_cpu)add_test(NAME pool_stress COMMAND pool_stress 20)+ # #795: nothing an AVX2-only CPU can reach may hold AVX-512 / AVX-VNNI-class instructions. (1) the linked test binary+ # (every CPU kernel file plus ggml-cpu; on Linux, the kernel library) is disassembled and any function with such instructions must be a kernel of+ # a wide-ISA file, not a weak / COMDAT copy and not a probe or helper that every CPU runs; (2) with -DSTRATA_SDE=<sde>+ # (Intel SDE) the CPU tests run on an emulated AVX2-only Haswell and on an Alder Lake (AVX-VNNI, no AVX-512): SDE stops+ # at the first instruction the chip does not have.+ if(TARGET iq_avx2_parity)+ find_package(Python3 QUIET COMPONENTS Interpreter)+ if(Python3_Interpreter_FOUND)+ if(MSVC)+ target_link_options(iq_avx2_parity PRIVATE /MAP)+ add_test(NAME isa_guard_check COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/check_isa_guard.py+ $<TARGET_FILE:iq_avx2_parity> --map $<TARGET_FILE_DIR:iq_avx2_parity>/iq_avx2_parity.map)+ else()+ # the library, not the binary: a Linux source build compiles ggml-cpu for the build machine on purpose+ add_test(NAME isa_guard_check COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/check_isa_guard.py+ $<TARGET_FILE:strata_kernels_cpu>)+ endif()+ set_tests_properties(isa_guard_check PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600)+ endif()+ endif()+ set(STRATA_SDE "" CACHE FILEPATH "Intel SDE (sde / sde64): also run the CPU tests on an emulated AVX2-only and an AVX-VNNI-only CPU")+ if(STRATA_SDE AND TARGET iq_avx2_parity)+ foreach(_chip hsw adl)+ foreach(_t iq_avx2_parity q8k_quant_parity router_dot_parity pool_tasks_test q2_bitplane_parity)+ if(TARGET ${_t})+ add_test(NAME sde_${_chip}_${_t} COMMAND ${STRATA_SDE} -${_chip} -- $<TARGET_FILE:${_t}>)+ set_tests_properties(sde_${_chip}_${_t} PROPERTIES TIMEOUT 900)+ endif()+ endforeach()+ if(TARGET q2_bitplane_parity)+ set_tests_properties(sde_${_chip}_q2_bitplane_parity PROPERTIES ENVIRONMENT "STRATA_Q2_BITPLANE=1")+ endif()+ endforeach()+ endif()+if(UNIX AND NOT APPLE)add_executable(direct_file_async_test tests/platform/direct_file_async.cpp src/platform/direct_file.cpp)target_include_directories(direct_file_async_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)diff --git a/tools/check_isa_guard.py b/tools/check_isa_guard.pynew file mode 100644index 000000000..384e8a358--- /dev/null+++ b/tools/check_isa_guard.py@@ -0,0 +1,208 @@+#!/usr/bin/env python3+"""Check that no code reachable on an AVX2-only CPU can contain wider-ISA instructions (#795).++Strata compiles a few translation units for AVX-512 (expert.cpp, iq_avx512.cpp) and some for AVX2 + AVX-VNNI+(q2_avx2.cpp, iq_avx2.cpp); the engine picks them at run time. Two things go wrong when that is done carelessly,+and both end in an illegal instruction on the CPU that lacks the feature:++ * a function that every CPU runs (a probe, a "supported?" helper, a startup flag) sits in a wide-ISA file, so the+ compiler may use the wide ISA in it;+ * an inline function or template instantiation (std::, a shared header) compiled in a wide-ISA file is emitted as a+ COMDAT / weak symbol, and the linker keeps THAT copy for every caller in the program.++The check disassembles a linked binary, finds every function that holds an AVX-512 (EVEX) or AVX-VNNI / VAES /+GFNI / SHA instruction, and fails unless the function is one of the kernels meant to be reached only behind a CPU+check: internal linkage (anonymous namespace) or a named public kernel entry point below, defined in a wide-ISA+object file, and not a weak / COMDAT symbol. MSVC's own auto-vectorizer guard (`cmp [__isa_available], 6`) is accepted.++ Linux : check_isa_guard.py libstrata_kernels_cpu.a (needs objdump and nm from binutils)+ Windows: check_isa_guard.py EXE --map EXE.map (link with /MAP; needs `pip install capstone pefile`)++Exit 0 = clean, 1 = a violation, 77 = cannot run here (tools missing; ctest SKIP_RETURN_CODE).+"""+import argparse+import bisect+import re+import shutil+import subprocess+import sys++# Public functions of the wide-ISA files that are wide on purpose: every caller tests the CPU first+# (cpu_avx512_ok / cpu_avxvnni_ok), or reaches them only after cpu_require_expert_support().+WIDE_PUBLIC = {+ "act_quant_q8_1", "q2_0_gguf_rows_multi", "s2_expert_vnni", "s2_expert_vnni_q", "s2_expert_gu_rows",+ "s2_expert_down_rows", "s2_expert_gu_rows_multi", "s2_expert_down_rows_multi", "s2_expert_vnni_multi",+ "s2_expert_scalar", "iq512_gu_rows", "iq512_rows", "iq256_gu_rows", "iq256_rows", "iq256_gu_rows_v",+ "iq256_rows_v", "iq4nl256_down_rows", "iq4nl256_down_rows_v", "q2_0_gguf_rows_multi_avx2",+ "q2_0_gguf_rows_multi_avx2_v", "q2_0_gguf_rows_multi_avx2_legacy", "q2_0_gguf_rows_multi_avx2_bitplane",+ "act_quant_q8_1_avx2", "q8k_quant_avx2", "kq256_gu_rows", "kq256_rows", "bf16_rows_dot_multi",+}+WIDE_OBJECTS = ("expert.cpp", "iq_avx512.cpp", "iq_avx2.cpp", "q2_avx2.cpp", "kq_avx2.cpp")++# An instruction is "wide" if it is EVEX encoded (first byte 0x62 in 64-bit mode), or one of these VEX / legacy+# extensions that an AVX2 CPU may lack. AVX-VNNI is VEX encoded (vpdpbusd, vpdpwssd ...).+WIDE_MNEMONIC = re.compile(r"^(vpdp|vgf2p8|vaes|vpclmul|sha(1|256)|vp2intersect|vpmadd52|vcvtne|vbcstnebf16|vsha512|vsm[34]|tdp|ldtilecfg)")+WIDE_OPERAND = re.compile(r"\bzmm|\bk[0-7]\b|[xy]mm(1[6-9]|2\d|3[01])\b|\{k[0-7]\}")+++def is_wide(raw0, mnemonic, ops):+ return raw0 == 0x62 or WIDE_MNEMONIC.match(mnemonic) is not None or WIDE_OPERAND.search(ops) is not None+++def judge(name, obj, wide_text, guarded, weak, is_elf):+ """Returns None if this wide function is allowed, else the reason."""+ if guarded:+ return None+ if name.startswith("?"): # MSVC decorated: ?name@scope@...+ base = re.match(r"\?+(?:\$)?([^@$?]+)", name).group(1) if re.match(r"\?+(?:\$)?([^@$?]+)", name) else name+ else: # demangled ELF names carry the argument list+ base = re.sub(r"\(.*$", "", name)+ base = re.sub(r"<.*$", "", base).split("::")[-1]+ anon = ("(anonymous namespace)" in name) or ("?A0x" in name)+ if weak:+ return "weak / COMDAT symbol: the linker may pick this wide copy for every caller (ODR)"+ if obj is not None and not any(obj.endswith(o + ".obj") or obj.endswith(o + ".o") or o in obj for o in WIDE_OBJECTS):+ return "wide-ISA code outside the wide-ISA translation units (object %s)" % obj+ if anon or base in WIDE_PUBLIC:+ return None+ return "wide-ISA code in an unlisted public function"+++# ---------------------------------------------------------------- ELF+def run_elf(path):+ """An archive (libstrata_kernels_cpu.a), an object or a linked binary. Give it the archive: a linked binary also+ holds ggml-cpu, which a Linux source build compiles for the build machine (-march=native) on purpose."""+ for tool in ("objdump", "nm"):+ if shutil.which(tool) is None:+ print("check_isa_guard: %s not found" % tool)+ return 77+ nm = subprocess.run(["nm", "-C", "--defined-only", path], capture_output=True, text=True, check=True).stdout+ weak, obj = set(), None+ for line in nm.splitlines():+ m = re.match(r"^(\S+\.o):$", line)+ if m:+ obj = m.group(1)+ continue+ m = re.match(r"^[0-9a-f]+ ([A-Za-z]) (.*)$", line)+ if m and m.group(2) and m.group(1) in "WVwu":+ weak.add((obj, m.group(2)))+ dis = subprocess.run(["objdump", "-d", "-C", "-w", "--no-addresses", path], capture_output=True, text=True,+ check=True).stdout+ obj, cur, wide, funcs = None, None, {}, 0+ for line in dis.splitlines():+ m = re.match(r"^(\S+\.o):\s+file format", line)+ if m:+ obj = m.group(1)+ continue+ m = re.match(r"^(?:[0-9a-f]+ )?<(.*)>:$", line.strip())+ if m:+ cur = m.group(1)+ funcs += 1+ continue+ if cur is None or "\t" not in line:+ continue+ parts = line.split("\t")+ if len(parts) < 3:+ continue+ raw = parts[1].split()+ text = parts[2].strip().split(None, 1)+ if not raw or not text:+ continue+ ops = text[1] if len(text) > 1 else ""+ if is_wide(int(raw[0], 16), text[0], ops):+ e = wide.setdefault((obj, cur), [0, text[0]])+ e[0] += 1+ bad = []+ for (obj, name), (n, first) in sorted(wide.items(), key=lambda kv: (kv[0][0] or "", kv[0][1])):+ # .isra / .part / .cold clones belong to the function they were split from+ root = re.sub(r"( \[clone [^\]]*\])+$", "", name)+ is_weak = (obj, name) in weak or (obj, root) in weak+ why = judge(root, obj, "", False, is_weak, True)+ if why:+ bad.append((name, n, first, why + (" [%s]" % obj if obj else "")))+ return report(path, funcs, {k[1]: v for k, v in wide.items()}, bad)+++# ---------------------------------------------------------------- PE+def run_pe(path, mapf):+ try:+ import pefile+ from capstone import Cs, CS_ARCH_X86, CS_MODE_64+ except ImportError:+ print("check_isa_guard: pip install capstone pefile to check a PE binary")+ return 77+ base_sym, isa_rva = {}, None+ pe = pefile.PE(path)+ image_base = pe.OPTIONAL_HEADER.ImageBase+ for line in open(mapf, errors="replace"):+ m = re.match(r"\s*0001:[0-9a-f]+\s+(\S+)\s+([0-9a-f]{16})\s+(?:f i|f)?\s*(\S+)\s*$", line)+ if m:+ rva = int(m.group(2), 16) - image_base+ base_sym[rva] = (m.group(1), m.group(3))+ for line in open(mapf, errors="replace"):+ m = re.match(r"\s*0003:[0-9a-f]+\s+__isa_available\s+([0-9a-f]{16})", line)+ if m:+ isa_rva = int(m.group(1), 16) - image_base+ starts = sorted(base_sym)+ text = [s for s in pe.sections if s.Name.startswith(b".text")][0]+ funcs = sorted((e.struct.BeginAddress, e.struct.EndAddress) for e in pe.DIRECTORY_ENTRY_EXCEPTION)+ md = Cs(CS_ARCH_X86, CS_MODE_64)+ wide, nfun = {}, 0+ for b, e in funcs:+ if not (text.VirtualAddress <= b < text.VirtualAddress + text.Misc_VirtualSize):+ continue+ nfun += 1+ n, first, guarded = 0, None, False+ for ins in md.disasm(pe.get_data(b, e - b), b):+ if isa_rva is not None and "[rip" in ins.op_str:+ m = re.search(r"\[rip ([+-]) 0x([0-9a-f]+)\]", ins.op_str)+ if m: # the function reads __isa_available: MSVC's own run-time guard for its vectorizer+ disp = int(m.group(2), 16) * (1 if m.group(1) == "+" else -1)+ guarded = guarded or ins.address + ins.size + disp == isa_rva+ if is_wide(ins.bytes[0], ins.mnemonic, ins.op_str):+ n += 1+ first = first or ins.mnemonic+ if n:+ # a cold chunk or funclet has no map entry: it belongs to the nearest symbol before it+ i = bisect.bisect_right(starts, b) - 1+ sym, obj = base_sym[starts[i]] if i >= 0 else ("?", "?")+ wide[(b, sym, obj)] = (n, first, guarded)+ bad = []+ for (b, sym, obj), (n, first, guarded) in sorted(wide.items()):+ why = judge(sym, obj.split(":")[-1], "", guarded, False, False)+ # an inline function defined in a header comes out of the map as `f i`; the wide-ISA files must have none+ if why is None and re.search(r"std@@|\?\$", sym) and not ("?A0x" in sym):+ why = "template / std:: instantiation inside a wide-ISA object (COMDAT: the linker may share it)"+ if why:+ bad.append((sym, n, first, why + " [rva %x, %s]" % (b, obj)))+ return report(path, nfun, {k[1]: v for k, v in wide.items()}, bad)+++def report(path, nfun, wide, bad):+ print("check_isa_guard: %s: %s functions, %d hold wide-ISA instructions, %d not allowed"+ % (path, nfun, len(wide), len(bad)))+ for name, n, first, why in bad:+ print(" VIOLATION %s (%d wide instructions, first %s): %s" % (name[:160], n, first, why))+ return 1 if bad else 0+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("binary")+ ap.add_argument("--map", help="MSVC linker map (PE)")+ a = ap.parse_args()+ with open(a.binary, "rb") as f:+ magic = f.read(4)+ if magic[:2] == b"MZ":+ if not a.map:+ print("check_isa_guard: a PE binary needs --map (link with /MAP)")+ return 77+ return run_pe(a.binary, a.map)+ if magic == b"\x7fELF" or magic == b"!<ar":+ return run_elf(a.binary)+ print("check_isa_guard: not a PE or ELF file")+ return 77+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/test_check_isa_guard.py b/tools/test_check_isa_guard.pynew file mode 100644index 000000000..c92810d43--- /dev/null+++ b/tools/test_check_isa_guard.py@@ -0,0 +1,60 @@+"""Tests for tools/check_isa_guard.py's policy (#795): which functions may hold wider-ISA instructions. No binary, no GPU.++ python -m unittest tools.test_check_isa_guard+"""+from __future__ import annotations++import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+import check_isa_guard as G # noqa: E402+++class WideInstruction(unittest.TestCase):+ def test_evex_prefix_is_wide(self):+ self.assertTrue(G.is_wide(0x62, "vmovups", "zmm0, zmmword ptr [rcx]"))+ self.assertTrue(G.is_wide(0x62, "vpmullq", "xmm0, xmm0, xmm6")) # EVEX with xmm0-15 operands only++ def test_vex_avx2_is_not(self):+ self.assertFalse(G.is_wide(0xC4, "vpinsrd", "xmm1, xmm1, dword ptr [r13 + r9*4 + 0x405fc0], 3"))+ self.assertFalse(G.is_wide(0xC5, "vmovdqu", "ymm0, ymmword ptr [r14]"))++ def test_avx_vnni_and_registers_above_15(self):+ self.assertTrue(G.is_wide(0xC4, "vpdpbusd", "ymm0, ymm1, ymm2"))+ self.assertTrue(G.is_wide(0xC5, "vpxor", "ymm17, ymm17, ymm17"))+ self.assertTrue(G.is_wide(0xC5, "kmovb", "k1, eax"))+++class Policy(unittest.TestCase):+ def test_kernel_in_an_anonymous_namespace_of_a_wide_file_is_fine(self):+ self.assertIsNone(G.judge("??$gu_rows@$0BA@$00@?A0xa1d599f5@cpu@kernels@strata@@YAXXZ",+ "strata_kernels_cpu:iq_avx512.cpp.obj", "", False, False, False))+ self.assertIsNone(G.judge("strata::kernels::cpu::(anonymous namespace)::gu_rows<18, 1>(int)", None, "", False,+ False, True))++ def test_listed_public_entry_point_is_fine(self):+ self.assertIsNone(G.judge("?act_quant_q8_1@cpu@kernels@strata@@YAXPEBMHAEAUActQ@123@@Z",+ "strata_kernels_cpu:expert.cpp.obj", "", False, False, False))++ def test_the_probe_must_not_be_wide(self):+ self.assertIsNotNone(G.judge("?cpu_features@cpu@kernels@strata@@YA?AUCpuFeatures@123@XZ",+ "strata_kernels_cpu:expert.cpp.obj", "", False, False, False))+ self.assertIsNotNone(G.judge("strata::kernels::cpu::cpu_features()", None, "", False, False, True))+ self.assertIsNotNone(G.judge("strata::kernels::cpu::iq512_supported(int)", None, "", False, False, True))++ def test_weak_symbol_is_a_violation_even_in_a_wide_file(self):+ why = G.judge("std::vector<float, std::allocator<float> >::_M_realloc_insert(float const&)", None, "", False,+ True, True)+ self.assertIn("weak", why)++ def test_wide_code_in_another_object_is_a_violation(self):+ self.assertIsNotNone(G.judge("?f@@YAXXZ", "strata_kernels_cpu:pool.cpp.obj", "", False, False, False))++ def test_msvc_vectorizer_guard_is_accepted(self):+ self.assertIsNone(G.judge("?bench@@YAHXZ", "iq_avx2_parity.cpp.obj", "", True, False, False))+++if __name__ == "__main__":+ unittest.main()