diff --git a/tools/vision/CMakeLists.txt b/tools/vision/CMakeLists.txt index 4d810cf21f..b042846b40 100644 --- a/tools/vision/CMakeLists.txt +++ b/tools/vision/CMakeLists.txt @@ -66,6 +66,33 @@ else() endforeach() message(STATUS "strata-vision: native build for this CPU (STRATA_PORTABLE=OFF) - not for other PCs") endif() +# An older-CPU test build (the engine's STRATA_ISA_FLOOR, CMakeLists.txt at the top): ggml-cpu, and the own tower's reference, for that floor instead of this +# machine's, so a newer box builds the program a CPU without AVX2 runs (with -DSTRATA_PORTABLE=OFF). none = SSE4.2 (Nehalem / Westmere), avx = Sandy Bridge +# (AVX, no F16C / FMA), avx_f16c = Ivy Bridge. Empty (the default) changes nothing; on such a CPU setup's native build is this build. +set(STRATA_ISA_FLOOR "" CACHE STRING "older-CPU test build: empty (default), none (SSE4.2), avx or avx_f16c") +set_property(CACHE STRATA_ISA_FLOOR PROPERTY STRINGS "" none avx avx_f16c) +if(STRATA_ISA_FLOOR) + if(NOT STRATA_ISA_FLOOR MATCHES "^(none|avx|avx_f16c)$") + message(FATAL_ERROR "STRATA_ISA_FLOOR must be empty, none, avx or avx_f16c (got '${STRATA_ISA_FLOOR}')") + endif() + if(STRATA_PORTABLE) + message(FATAL_ERROR "STRATA_ISA_FLOOR (an older-CPU build) needs -DSTRATA_PORTABLE=OFF") + endif() + set(GGML_NATIVE OFF CACHE BOOL "" FORCE) + set(GGML_CPU_ALL_VARIANTS OFF CACHE BOOL "" FORCE) + set(GGML_SSE42 ON CACHE BOOL "" FORCE) + foreach(_f GGML_AVX GGML_F16C GGML_AVX2 GGML_FMA GGML_BMI2 GGML_AVX_VNNI GGML_AVX512 GGML_AVX512_VBMI GGML_AVX512_VNNI + GGML_AVX512_BF16 GGML_AMX_TILE GGML_AMX_INT8 GGML_AMX_BF16) + set(${_f} OFF CACHE BOOL "" FORCE) + endforeach() + if(STRATA_ISA_FLOOR MATCHES "^avx") + set(GGML_AVX ON CACHE BOOL "" FORCE) + endif() + if(STRATA_ISA_FLOOR STREQUAL "avx_f16c") + set(GGML_F16C ON CACHE BOOL "" FORCE) + endif() + message(STATUS "strata-vision: ggml-cpu for the floor ${STRATA_ISA_FLOOR} (an older-CPU test build)") +endif() set(GGML_BACKEND_DL OFF CACHE BOOL "" FORCE) set(GGML_CUDA ${STRATA_VISION_CUDA} CACHE BOOL "" FORCE) set(GGML_HIP ${STRATA_VISION_HIP} CACHE BOOL "" FORCE) diff --git a/tools/vision/own/CMakeLists.txt b/tools/vision/own/CMakeLists.txt index 0f7faf5e80..f35454e733 100644 --- a/tools/vision/own/CMakeLists.txt +++ b/tools/vision/own/CMakeLists.txt @@ -80,15 +80,28 @@ if(NOT MSVC) # reference builds on the Linux boxes); the helper's portable build keeps the AVX2 baseline its other code has option(STRATA_VIT_OWN_NATIVE "build the reference for this CPU (-march=native)" ${STRATA_VIT_OWN_STANDALONE}) set_source_files_properties(vit_ref.cpp vit_cpu.cpp cpu_kernels_scalar.cpp cpu_kernels_neon.cpp PROPERTIES COMPILE_OPTIONS "-O3") - if(STRATA_VIT_OWN_NATIVE) + # The reference (VitRef, a test oracle) is the only generic file compiled above the baseline, and only where the whole program has that floor anyway: an + # instruction-set flag on a file that uses the standard library also reaches its inline / template copies (COMDAT), which the linker may keep for the WHOLE + # program, so a wider flag here would put AVX2 code on the path of a CPU without it (RESULTS-OWN-3V.md PART H). + # STRATA_VIT_OWN_NATIVE (standalone test builds) or a native helper build (setup, STRATA_PORTABLE=OFF): -march=native, this CPU; + # the portable helper (STRATA_PORTABLE=ON, an AVX2 baseline for the whole program): -mavx2 -mfma as before; + # an older-CPU test build (STRATA_ISA_FLOOR, tools/vision): that floor. + if(CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64") + if(STRATA_ISA_FLOOR STREQUAL "avx" OR STRATA_ISA_FLOOR STREQUAL "avx_f16c") + set_source_files_properties(vit_ref.cpp PROPERTIES COMPILE_OPTIONS "-O3;-mavx") + elseif(STRATA_ISA_FLOOR) + set_source_files_properties(vit_ref.cpp PROPERTIES COMPILE_OPTIONS "-O3") + elseif(STRATA_VIT_OWN_NATIVE OR (DEFINED STRATA_PORTABLE AND NOT STRATA_PORTABLE)) + set_source_files_properties(vit_ref.cpp PROPERTIES COMPILE_OPTIONS "-O3;-march=native") + elseif(STRATA_PORTABLE) + set_source_files_properties(vit_ref.cpp PROPERTIES COMPILE_OPTIONS "-O3;-mavx2;-mfma") + endif() + elseif(STRATA_VIT_OWN_NATIVE) set_source_files_properties(vit_ref.cpp PROPERTIES COMPILE_OPTIONS "-O3;-march=native") - elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64") - set_source_files_properties(vit_ref.cpp PROPERTIES COMPILE_OPTIONS "-O3;-mavx2;-mfma") endif() - # the CPU tower: the generic part keeps the portable baseline, each kernel tier is compiled for its own instruction set (and only called when the - # CPU has it, cpu_caps.h) + # the CPU tower: the generic part (vit_cpu.cpp) keeps the baseline, each kernel tier is compiled for its own instruction set and only called when the CPU + # has it (cpu_caps.h); the tiers' files include no standard-library code (cpu_tier.h) if(CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64") - set_source_files_properties(vit_cpu.cpp PROPERTIES COMPILE_OPTIONS "-O3;-mavx2;-mfma") set_source_files_properties(cpu_kernels_avx2.cpp PROPERTIES COMPILE_OPTIONS "-O3;-mavx2;-mfma;-mf16c") set_source_files_properties(cpu_kernels_avx512.cpp PROPERTIES COMPILE_OPTIONS "-O3;-mavx2;-mfma;-mf16c;-mavx512f;-mavx512bw;-mavx512dq;-mavx512vl") else() diff --git a/tools/vision/own/check_floor_isa.py b/tools/vision/own/check_floor_isa.py new file mode 100644 index 0000000000..05811e8d4c --- /dev/null +++ b/tools/vision/own/check_floor_isa.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Which code of a linked strata-vision (or strata-vision-own) holds instructions an older CPU lacks (RESULTS-OWN-3V.md PART H). + +The CPU tower compiles each kernel tier in a file of its own with that tier's flags and calls it only after a CPU check (cpu_caps.h); everything else +must stay at the floor of the build. An instruction-set flag on a file that uses the standard library also reaches its inline and template copies +(weak / COMDAT symbols), and the linker may keep such a copy for the whole program, so the check looks at the LINKED binary, function by function: + + floor none (SSE4.2, Nehalem / Westmere): no VEX / EVEX instruction (no AVX of any kind), no BMI1/2, no MOVBE; + floor avx (Sandy Bridge): AVX allowed; no AVX2 (256-bit integer ops, broadcasts / permutes / gathers of AVX2), no FMA, no F16C, no EVEX, no BMI; + floor avx_f16c (Ivy Bridge): as avx, F16C allowed. + +A function with such an instruction passes only if it is a LOCAL symbol of a kernel tier (the anonymous namespace `kn` of cpu_kernels_impl.h) or a tier's +table getter (strata_vit::cpu_ops_), i.e. code reached only behind the CPU check. Anything else is printed, weak / COMDAT copies marked. + + python3 check_floor_isa.py --floor none|avx|avx_f16c exit 0 clean, 1 a violation, 77 no objdump / nm +Linux (GNU binutils) only. +""" +import argparse +import re +import shutil +import subprocess +import sys + +FMA = re.compile(r"^vf(n?m(add|sub)|maddsub|msubadd)") +F16C = re.compile(r"^vcvt(ph2ps|ps2ph)") +AVX2_ONLY = re.compile(r"^(vpbroadcast|vbroadcasti128|vperm2i128|vpermd|vpermq|vpermps|vpermpd|v(p)?gather|vinserti128|vextracti128|vpmaskmov|vps[lr]lv|vpsrav|vpblendd)") +BMI = re.compile(r"^(andn|bextr|blsi|blsmsk|blsr|bzhi|mulx|pdep|pext|rorx|sarx|shlx|shrx|movbe)\b") +AVX1_YMM_INT_OK = ("vptest", "vpermilps", "vpermilpd", "vperm2f128") # AVX (1) instructions whose names start with "vp" and take ymm + + +def bad_reason(mn, ops, floor): + if "zmm" in ops or re.search(r"%k[0-7]|\{%k", ops) or re.search(r"[xy]mm(1[6-9]|2\d|3[01])\b", ops): + return "AVX-512" + if BMI.match(mn): + return "BMI/MOVBE" + if floor == "none": + if mn.startswith("v") and mn not in ("verr", "verw"): + return "AVX" + return None + if FMA.match(mn): + return "FMA" + if F16C.match(mn) and floor != "avx_f16c": + return "F16C" + if AVX2_ONLY.match(mn): + return "AVX2" + if mn.startswith("vp") and "ymm" in ops and not mn.startswith(AVX1_YMM_INT_OK): + return "AVX2" + return None + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("binary") + ap.add_argument("--floor", required=True, choices=["none", "avx", "avx_f16c"]) + ap.add_argument("--show", type=int, default=3, help="instructions shown per function") + a = ap.parse_args() + if not shutil.which("objdump") or not shutil.which("nm"): + print("objdump / nm not found") + return 77 + kind = {} + for line in subprocess.run(["nm", "--defined-only", a.binary], capture_output=True, text=True).stdout.splitlines(): + p = line.split() + if len(p) >= 3: + kind[int(p[0], 16)] = p[1] + names = {} + for line in subprocess.run(["nm", "--defined-only", "-C", a.binary], capture_output=True, text=True).stdout.splitlines(): + p = line.split(None, 2) + if len(p) == 3: + names.setdefault(int(p[0], 16), p[2]) + proc = subprocess.Popen(["objdump", "-d", "-w", "--no-show-raw-insn", a.binary], stdout=subprocess.PIPE, text=True, bufsize=1 << 20) + head = re.compile(r"^([0-9a-f]+) <(.+)>:$") + ins = re.compile(r"^\s*[0-9a-f]+:\s+(\S+)\s*(.*)$") + cur, cur_addr, hits = None, 0, {} + for line in proc.stdout: + m = head.match(line) + if m: + cur_addr = int(m.group(1), 16) + cur = names.get(cur_addr, m.group(2)) + continue + m = ins.match(line) + if not m or cur is None: + continue + mn, ops = m.group(1), m.group(2) + if mn in ("data16", "rex", "lock", "rep", "repz", "repnz", "notrack", "bnd") and ops: + mn, _, ops = ops.partition(" ") + r = bad_reason(mn, ops, a.floor) + if r: + h = hits.setdefault((cur_addr, cur), {"reasons": set(), "ex": []}) + h["reasons"].add(r) + if len(h["ex"]) < a.show: + h["ex"].append(mn + " " + ops.strip()) + proc.wait() + ok_tier, bad = [], [] + for (addr, name), h in sorted(hits.items(), key=lambda x: x[0][1]): + k = kind.get(addr, "?") + local = k in ("t", "d", "b", "r") + tier = ("(anonymous namespace)::kn::" in name and local) or re.match(r"^strata_vit::cpu_ops_(sse41|avx|avx2|avx512)\(\)$", name) + (ok_tier if tier else bad).append((name, k, h)) + print("floor %s: %d functions with instructions above the floor; %d are kernel-tier code behind the CPU check, %d are NOT" % ( + a.floor, len(hits), len(ok_tier), len(bad))) + for name, k, h in bad: + weak = " WEAK/COMDAT" if k in ("W", "w", "V", "v", "u") else "" + print(" NOT GUARDED [%s]%s %s: %s | e.g. %s" % (k, weak, name[:200], ",".join(sorted(h["reasons"])), " ; ".join(h["ex"]))) + return 1 if bad else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/vision/own/cpu_kernels_impl.h b/tools/vision/own/cpu_kernels_impl.h index 67250ad1ad..b1f54d8ded 100644 --- a/tools/vision/own/cpu_kernels_impl.h +++ b/tools/vision/own/cpu_kernels_impl.h @@ -251,11 +251,32 @@ void softmax_update(float* S, size_t lds, int qrows, int nkeys, float* m, float* } } +// The rotary and the position add, written as they were in vit_cpu.cpp (the same expressions in the same order), so a tier compiled with the flags vit_cpu.cpp +// had (-mavx2 -mfma on GCC) contracts them the same way as before: the AVX2 / AVX-512 results stay bit-identical. +void rope_row(float* row, size_t kstride, int heads, int hd, const float* c1, const float* s1, const float* c2, const float* s2) { + const int half = hd / 2, quarter = hd / 4; + for (int part = 0; part < 2; ++part) + for (int hh = 0; hh < heads; ++hh) { + float* v = row + (size_t) part * kstride + (size_t) hh * hd; + for (int j = 0; j < half; ++j) { + const float co = j < quarter ? c1[j] : c2[j - quarter], si = j < quarter ? s1[j] : s2[j - quarter]; + const float a = v[j], b = v[j + half]; + v[j] = a * co - b * si; + v[j + half] = a * si + b * co; + } + } +} + +void pos_add(float* xr, const float* a, const float* b, const float* c, const float* d, float dx, float dy, int D) { + for (int i = 0; i < D; ++i) xr[i] += a[i] * (1 - dx) * (1 - dy) + b[i] * dx * (1 - dy) + c[i] * (1 - dx) * dy + d[i] * dx * dy; +} + } // namespace kn } // namespace const CpuOps& STRATA_KN_GETTER() { - static const CpuOps ops = {STRATA_KN_NAME, kn::MRF, kn::NR, kn::pack_w, kn::conv, kn::gemm, kn::gelu, kn::layernorm, kn::add, kn::round16, kn::softmax_update}; + static const CpuOps ops = {STRATA_KN_NAME, kn::MRF, kn::NR, kn::pack_w, kn::conv, kn::gemm, kn::gelu, kn::layernorm, kn::add, kn::round16, kn::softmax_update, + kn::rope_row, kn::pos_add}; return ops; } diff --git a/tools/vision/own/cpu_tier.h b/tools/vision/own/cpu_tier.h index 82ef7ca3d9..148b3d4e31 100644 --- a/tools/vision/own/cpu_tier.h +++ b/tools/vision/own/cpu_tier.h @@ -39,6 +39,11 @@ struct CpuOps { // One key tile of the online softmax for qrows query rows: S[qrows][nkeys] (row stride lds, already scaled) becomes P = exp(S - m_new) in place, the running // max m[r] and sum l[r] are updated and the context rows O[r][0..hd) (row stride ldo) are rescaled by exp(m_old - m_new) (O's P*V is added afterwards). void (*softmax_update)(float* S, size_t lds, int qrows, int nkeys, float* m, float* l, float* O, size_t ldo, int hd); + // The two loops of the tower whose floating-point result depends on the compiler's multiply-add contraction, so they are compiled with each tier's flags + // (vit_cpu.cpp itself is compiled for the baseline CPU, RESULTS-OWN-3V.md PART H): the rotary of one token row (q at row[0 .. heads*hd), k at + // row[kstride ..); pair j of a head turns by (c1, s1)[j] for j < hd/4, else by (c2, s2)[j - hd/4]), and the position table's bilinear add of one row. + void (*rope_row)(float* row, size_t kstride, int heads, int hd, const float* c1, const float* s1, const float* c2, const float* s2); + void (*pos_add)(float* xr, const float* a, const float* b, const float* c, const float* d, float dx, float dy, int D); }; const CpuOps& cpu_ops_scalar(); diff --git a/tools/vision/own/vit_cpu.cpp b/tools/vision/own/vit_cpu.cpp index 52ba4bbde8..62102a4b3c 100644 --- a/tools/vision/own/vit_cpu.cpp +++ b/tools/vision/own/vit_cpu.cpp @@ -257,8 +257,7 @@ bool VitCpu::encode(const PreparedImage& img, int threads, std::vector& r const float* b = &m.pos[((size_t) y0 * G + x1) * D]; const float* c = &m.pos[((size_t) y1 * G + x0) * D]; const float* d = &m.pos[((size_t) y1 * G + x1) * D]; - float* xr = &x[(size_t) t * D]; - for (int i = 0; i < D; ++i) xr[i] += a[i] * (1 - dx) * (1 - dy) + b[i] * dx * (1 - dy) + c[i] * (1 - dx) * dy + d[i] * dx * dy; + ops.pos_add(&x[(size_t) t * D], a, b, c, d, dx, dy, D); // a tier kernel: its result depends on multiply-add contraction (cpu_tier.h) }); } @@ -310,16 +309,7 @@ bool VitCpu::encode(const PreparedImage& img, int threads, std::vector& r const float* s1 = &rs[(size_t) ty[(size_t) t] * quarter]; const float* c2 = &cc[(size_t) tx[(size_t) t] * quarter]; const float* s2 = &cs[(size_t) tx[(size_t) t] * quarter]; - for (int part = 0; part < 2; ++part) - for (int hh = 0; hh < H; ++hh) { - float* v = row + (size_t) part * D + (size_t) hh * HD; - for (int j = 0; j < half; ++j) { - const float co = j < quarter ? c1[j] : c2[j - quarter], si = j < quarter ? s1[j] : s2[j - quarter]; - const float a = v[j], b = v[j + half]; - v[j] = a * co - b * si; - v[j + half] = a * si + b * co; - } - } + ops.rope_row(row, (size_t) D, H, HD, c1, s1, c2, s2); // a tier kernel, as pos_add if (m.act_round) ops.round16(row, D3, 2); for (int i = 0; i < D; ++i) row[i] *= kq_scale; });