Merge branch 'f-139b-cpu' into f-139-rel

This commit is contained in:
Niko1221 committed 2026-10-04 10:11:54 +02:00
commit 0918cba0a5
18 files changed
+590 -39

No files matched your search

+45 -1
View File
@@ -21,6 +21,18 @@ endif()
# instead of this machine's (Strata's own AVX-512 kernels are per-file and chosen at run time either way), and
# the MSVC runtime linked in, so no Visual C++ redistributable is needed.
option(STRATA_PORTABLE "build for other PCs: AVX2 baseline, static MSVC runtime" OFF)
# EXPERIMENTAL, opt-in: an engine for CPUs without AVX2 (#394, #595, #623), compiled on that PC. ggml-cpu, which then
# computes every CPU expert row, is built for this floor instead of AVX2 or the build host: "avx" (Sandy/Ivy Bridge:
# AVX, no FMA/F16C/AVX2) or "none" (SSE4.2 + POPCNT: Nehalem/Westmere). Strata's own AVX2/AVX-512 kernels stay in the
# binary behind their CPU checks; the router lookahead gets an AVX1 kernel. Empty (the default) changes nothing.
set(STRATA_ISA_FLOOR "" CACHE STRING "experimental older-CPU build: empty (default, AVX2 floor), avx, or none (SSE4.2)")
set_property(CACHE STRATA_ISA_FLOOR PROPERTY STRINGS "" avx none)
if(NOT STRATA_ISA_FLOOR STREQUAL "" AND NOT STRATA_ISA_FLOOR STREQUAL "avx" AND NOT STRATA_ISA_FLOOR STREQUAL "none")
message(FATAL_ERROR "STRATA_ISA_FLOOR must be empty, avx or none (got '${STRATA_ISA_FLOOR}')")
endif()
if(STRATA_ISA_FLOOR AND STRATA_PORTABLE)
message(FATAL_ERROR "STRATA_ISA_FLOOR (an older-CPU build) and STRATA_PORTABLE (the AVX2 release build) exclude each other")
endif()
if(STRATA_PORTABLE AND MSVC)
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded")
endif()
@@ -868,6 +880,22 @@ if(STRATA_NATIVE_EXPERTS)
foreach(_f GGML_AVX GGML_AVX2 GGML_FMA GGML_F16C GGML_BMI2)
set(${_f} ON CACHE BOOL "" FORCE)
endforeach()
elseif(STRATA_ISA_FLOOR)
# the experimental older-CPU build (STRATA_ISA_FLOOR above): one ggml-cpu for the floor, ggml's "sandybridge"
# feature set (SSE4.2 + AVX) or SSE4.2 alone - not the build host's, which may be newer than the PC it runs on.
# From the Strata_Dirigo fork (rwkeyes). ggml's defaults turn the rest on when GGML_NATIVE is off: all off here.
set(GGML_NATIVE OFF CACHE BOOL "" FORCE)
set(GGML_CPU_ALL_VARIANTS OFF CACHE BOOL "" FORCE)
set(GGML_SSE42 ON CACHE BOOL "" FORCE)
if(STRATA_ISA_FLOOR STREQUAL "avx")
set(GGML_AVX ON CACHE BOOL "" FORCE)
else()
set(GGML_AVX OFF CACHE BOOL "" FORCE)
endif()
foreach(_f GGML_AVX2 GGML_FMA GGML_F16C 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()
else()
set(GGML_NATIVE ON CACHE BOOL "" FORCE)
endif()
@@ -888,20 +916,36 @@ if(STRATA_NATIVE_EXPERTS)
# part of strata_kernels_cpu (the pool calls these and they call its CPU probe: one library, so GNU ld's
# one-pass static linking has no cycle to resolve)
target_sources(strata_kernels_cpu PRIVATE src/kernels/cpu/native_expert.cpp src/kernels/cpu/iq_avx512.cpp
src/kernels/cpu/iq_avx2.cpp src/kernels/cpu/kq_avx2.cpp)
src/kernels/cpu/iq_avx2.cpp src/kernels/cpu/kq_avx2.cpp
src/kernels/cpu/kq_avx1.cpp)
target_include_directories(strata_kernels_cpu PRIVATE third_party/ggml)
if(MSVC)
set_source_files_properties(src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512")
set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2")
set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2")
# the router lookahead's AVX1 dot (older CPUs; called behind cpu_avx1_ok): no FMA, no 256-bit integer ops
set_source_files_properties(src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX")
else()
set_source_files_properties(src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS
"-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma")
set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")
set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")
set_source_files_properties(src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "-mavx")
endif()
if(STRATA_ISA_FLOOR STREQUAL "avx")
target_compile_definitions(strata_kernels_cpu PRIVATE STRATA_ISA_FLOOR_AVX=1)
elseif(STRATA_ISA_FLOOR STREQUAL "none")
target_compile_definitions(strata_kernels_cpu PRIVATE STRATA_ISA_FLOOR_NONE=1)
endif()
target_link_libraries(strata_kernels_cpu PUBLIC ggml-cpu ggml-base)
target_compile_definitions(strata_kernels_cpu PUBLIC STRATA_NATIVE_EXPERTS=1)
# the router lookahead's dot on each rung this CPU has (AVX2, the older CPUs' AVX1) against a double reference
add_executable(router_dot_parity src/kernels/cpu/router_dot_parity.cpp)
target_link_libraries(router_dot_parity PRIVATE strata_kernels_cpu)
if(STRATA_BUILD_TESTS)
add_test(NAME router_dot_parity COMMAND router_dot_parity)
add_test(NAME router_dot_parity_avx COMMAND ${CMAKE_COMMAND} -E env STRATA_FORCE_ISA=avx $<TARGET_FILE:router_dot_parity>)
endif()
set(_strata_mmq_types q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0)
# #296: OrcaRouter Q4_K_S's Q5_0 experts (Q4_K and Q5_1 come with STRATA_MMQ_KQUANTS on CUDA, S5's branch)
if(STRATA_ORCA_Q4KS_MMQ)
+1 -1
View File
@@ -48,7 +48,7 @@ Requirements (details: [INSTALL.md](INSTALL.md#what-you-need)):
- **Driver:** NVIDIA 580 or newer. AMD on Linux: the kernel's amdgpu driver; on Windows: a current AMD Adrenalin
driver. If the driver is missing or too old, tell the user to update it (NVIDIA App / nvidia.com/drivers, or AMD
Software) and restart; do not install drivers yourself unless they ask.
- **RAM:** 32 GB or more (see step 3). **Disk:** ~80 GB free, ideally on an NVMe SSD. **CPU:** x86-64 with AVX2.
- **RAM:** 32 GB or more (see step 3). **Disk:** ~80 GB free, ideally on an NVMe SSD. **CPU:** x86-64 with AVX2. Without AVX2 (Xeon E5 v1/v2 and older) setup still installs, as an experimental and slow build it compiles on the PC (10-20 minutes): tell the user that before starting ([INSTALL.md](INSTALL.md#older-cpus-experimental)).
- **OS:** Windows 10/11 or Linux (Ubuntu 22.04/24.04 are fully automatic).
If the PC does not meet them, say which part is missing and stop.
+1 -1
View File
@@ -303,7 +303,7 @@ Everything else is installed for you the first time.
| --- | --- |
| GPU | NVIDIA **RTX 20, 30, 40 or 50 series**, **12 GB VRAM or more** (8 GB runs, slowly). Measured on an RTX 5070 and an RTX 3090; RTX 20 (Turing, since 0.1.27) was tested by a contributor on an RTX 2070. Or AMD **Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT, Radeon AI PRO R9700, RX 6800 / 6900 series**: [AMD_HIP.md](AMD_HIP.md). |
| RAM | **64 GB** recommended (see the table above). |
| CPU | x86-64 with AVX2 (any Intel/AMD desktop CPU from the last ~8 years). AVX-512 (Ryzen 7000/9000) is a bit faster. |
| CPU | x86-64 with AVX2 (any Intel/AMD desktop CPU from the last ~8 years). AVX-512 (Ryzen 7000/9000) is a bit faster. Older CPUs without AVX2 are experimental and slow: [Older CPUs](INSTALL.md#older-cpus-experimental). |
| Disk | ~70-80 GB free for the model, ~6 GB for the MTP layer (+1 GB with images). **Q2_0 on an AVX-512 CPU** also writes a one-time ~40 GB pack for the fast CPU kernel (34 GB of experts in its layout, plus the dense weights). An NVMe SSD is strongly recommended. |
| OS | Windows 10/11, or Linux (Ubuntu 22.04/24.04 get everything installed automatically). |
+33 -4
View File
@@ -5,9 +5,9 @@ AMD graphics card. The short version is in the [README](../README.md#install); a
this for you with [AI_SETUP.md](AI_SETUP.md).
> **On this page:** [What you need](#what-you-need) · [Windows](#windows) · [Linux](#linux) ·
> [AMD cards](#amd-cards) · [Several cards](#two-or-three-cards) · [Docker](#docker-linux) · [Updating](#updating) ·
> [Where things are stored](#where-things-are-stored) · [Setup's questions](#setups-questions) ·
> [Tuning](#tuning-for-your-pc) · [All options](#options-without-questions)
> [AMD cards](#amd-cards) · [Several cards](#two-or-three-cards) · [Docker](#docker-linux) ·
> [Older CPUs](#older-cpus-experimental) · [Updating](#updating) · [Where things are stored](#where-things-are-stored) ·
> [Setup's questions](#setups-questions) · [Tuning](#tuning-for-your-pc) · [All options](#options-without-questions)
## What you need
@@ -15,7 +15,7 @@ this for you with [AI_SETUP.md](AI_SETUP.md).
| --- | --- |
| **GPU** | **NVIDIA** RTX 20, 30, 40 or 50 series, **12 GB VRAM or more** (8 GB runs, slowly). Measured on an RTX 5070 and an RTX 3090; RTX 20 (Turing, since 0.1.27) was tested by a contributor on an RTX 2070. **AMD** Radeon RX 7900 XT / XTX, RX 9070 / 9070 XT and Radeon AI PRO R9700 (validated), RX 7800 XT / 7700 XT and RX 9060 XT (validated by their owners), RX 6800 / 6900 series (community-reported), with 12 GB of VRAM or more. See [AMD cards](#amd-cards). |
| **RAM** | Enough for the size you pick ([which model](MODELS.md#pick-by-ram)); **64 GB** runs every size. A big GPU makes up for less RAM - the [low-RAM mode](MODELS.md#a-big-graphics-card-and-little-ram). |
| **CPU** | x86-64 with AVX2 (any Intel/AMD desktop CPU from the last ~8 years). AVX-512 (Ryzen 7000/9000) is a bit faster. |
| **CPU** | x86-64 with AVX2 (any Intel/AMD desktop CPU from the last ~8 years). AVX-512 (Ryzen 7000/9000) is a bit faster. Older CPUs without AVX2 are experimental and slow: [Older CPUs](#older-cpus-experimental). |
| **Disk** | ~70-80 GB free for the model, ~6 GB for the MTP layer (+1 GB with images). **Q2_0 on an AVX-512 CPU** also writes a one-time ~40 GB copy of its experts for the fast CPU kernel. On Linux with an AMD card, ROCm takes ~10 GB more when setup installs it. An NVMe SSD is strongly recommended: it makes the first start much faster. |
| **OS** | Windows 10/11, or Linux (Ubuntu 22.04/24.04 get everything installed automatically). |
| **Driver** | **NVIDIA:** a current driver, version 580 or newer ([nvidia.com/drivers](https://www.nvidia.com/drivers) or the NVIDIA App). **AMD:** on Linux the kernel's amdgpu driver (no ROCm install needed); on Windows a current AMD Software: Adrenalin Edition driver ([amd.com/support](https://www.amd.com/en/support)). |
@@ -121,6 +121,35 @@ The same idea, in a container (NVIDIA cards).
to a network. The image has a `HEALTHCHECK` on `/health`, so `docker ps` shows the container
healthy once the model is loaded, and `GET /v1/status` says what it is running.
## Older CPUs (experimental)
Strata's ready-made engine needs AVX2 (Intel Haswell 2013, AMD Zen 2017 or newer). Since 0.1.39 an older CPU - AVX
only (Sandy Bridge / Ivy Bridge, Xeon E5 v1/v2, AMD Bulldozer) or SSE4.2 only (Nehalem / Westmere, Xeon X5600) - runs
as an **experimental** build that setup compiles on that PC. Run setup as usual: it says the CPU has no AVX2, warns
that this is experimental and slow, and compiles the engine (10-20 minutes, once; Windows needs the Visual Studio Build
Tools and the CUDA Toolkit, which setup offers to install). It does not stop. The ready-made engine still refuses such
a CPU, and says so.
What differs in that build (`STRATA_ISA_FLOOR=avx` or `none`, chosen from the CPU):
- ggml-cpu is compiled for AVX or SSE4.2 instead of AVX2, and the CPU's share of the experts runs on its kernels.
Strata's own AVX2 / AVX-512 kernels stay in the program but are used only on a CPU that has them.
- Only the i-quant models' packs run (every model setup installs on such a CPU); the AVX-512 Q2_0 pack does not.
- Speed: the GPU part is unchanged and the CPU part is slower, so a GPU with more VRAM (more experts cached there)
helps most. With the older paths forced on a Ryzen 5 7600 + RTX 5070 and the expert cache held at 1500 slots, greedy
decode went from 26 to 11-17 tok/s with the AVX build and to 3.5-3.8 tok/s with the SSE4.2 build (Coder and IQ3_XXS,
10 prompts each, one run). An old Xeon with DDR3 will be slower than these.
- Untested on a real old CPU by us. It was checked here by forcing the older paths on a Ryzen 5 7600
(`STRATA_FORCE_ISA=avx` or `sse`): the answers were sane and passed the engine's checks, but not the same token for
token as the normal build (ggml-cpu rounds the CPU experts differently, as the AVX2 kernel does from the AVX-512
one). Contributors ran earlier versions of the same approach on a Xeon E5-2680 (2.87 tok/s with a GTX 1080 Ti)
and on Xeon E5-2687W / X5690 machines.
- AMD cards: Linux only (setup compiles the AMD engine there anyway); NVIDIA on Windows and Linux.
- Two-socket Xeons: memory on the other socket is slow; keep the RAM on one CPU if you can.
By hand: `cmake ... -DSTRATA_ISA_FLOOR=avx` (or `none`) builds it; `STRATA_ISA_FLOOR=avx` set for setup builds it on
any PC (to try it). Problems and results on real hardware are welcome as GitHub issues.
## Updating
**`UPDATE.bat`** (Linux: `./update.sh`) updates Strata without starting the model - for when the GPU is busy with
@@ -47,6 +47,20 @@ bool cpu_avx512_ok();
/// Whether this CPU (and its OS) runs the AVX2 kernels (AVX, AVX2, FMA, F16C): the floor of every expert kernel
/// (q2_avx2.cpp, iq_avx2.cpp, and ggml-cpu in the portable build). STRATA_FORCE_AVX2 does not change it.
bool cpu_avx2_ok();
/// Whether this CPU (and its OS) runs AVX (Sandy Bridge and newer): the AVX1 router dot (kq_avx1.cpp) and ggml-cpu in
/// a STRATA_ISA_FLOOR=avx build. The other expert rows then run on ggml-cpu (experimental, slow).
bool cpu_avx1_ok();
/// SSE4.2 + POPCNT: ggml-cpu in a STRATA_ISA_FLOOR=none build.
bool cpu_sse42_ok();
/// STRATA_FORCE_ISA=avx2|avx|sse caps the probes above (3 = no cap, 2 = AVX2, 1 = AVX, 0 = SSE4.2), so the older-CPU
/// paths run on any PC: tests and the experimental builds' checks. ggml-cpu keeps what it was compiled for.
int cpu_isa_cap();
/// The experimental older-CPU build this engine is ("avx", "sse4.2"), or "" for the normal build (AVX2 floor).
const char* isa_floor_build();
/// Whether a native pack's layer of this ggml type runs on Strata's own Q2_0 kernels (AVX2 / AVX-512). On a
/// CPU without AVX2 (a native, non-portable build: ggml-cpu compiled for this CPU's SSE) a Q2_0 layer takes
/// ggml-cpu's own Q2_0 vec_dot like every other native type: slower, but it runs.
inline bool q2_native_kernels(int type) { return type == 42 && cpu_avx2_ok(); }
/// The CPU's brand string (CPUID 0x80000002..4), for messages; "unknown" when it has none.
std::string cpu_name();
/// Q2_0 GGUF rows / activation quantizer on the kernels this CPU has.
+18
View File
@@ -0,0 +1,18 @@
// include/strata/kernels/cpu/kq_avx1.hpp - the AVX1 router dot for older CPUs (from the Strata_Dirigo fork).
//
// bf16_rows_dot_multi (kq_avx2.cpp) is compiled with -mavx2 and uses instructions an AVX-only CPU does
// not have (`vpmovzxwd`, `vfmadd`), so an AVX-only host cannot call it at all. This is the same
// arithmetic on AVX1 instructions: 8 float lanes per token, one weight stream per row shared by all
// `nt` tokens, one horizontal sum per (row, token). AVX1 has no FMA, so the multiply and the add stay
// separate; it has no 256-bit integer ops, so the bf16 -> f32 widening runs in 128-bit halves.
#pragma once
#include <cstdint>
namespace strata::kernels::cpu {
/// Mirrors bf16_rows_dot_multi's arithmetic (same accumulation shape, mul+add instead of FMA).
/// Requires cols % 8 == 0 and nt <= 8, exactly like the AVX2 kernel it stands in for.
void bf16_rows_dot_multi_avx1(const uint16_t* w, int rows, int cols, const float* x, int nt, float* out);
} // namespace strata::kernels::cpu
+76 -7
View File
@@ -407,6 +407,48 @@ def cpu_info():
return name, avx2, avx512
def _cpuid_floor() -> str:
"""Below AVX2 (Windows): "avx" when the CPU has AVX and the OS saves the YMM registers, "sse4.2" with SSE4.2 and
POPCNT, else ""."""
try:
regs = (ctypes.c_uint32 * 4)()
_run_stub(bytes([0x53, 0x49, 0x89, 0xC8, 0x89, 0xD0, 0x31, 0xC9, 0x0F, 0xA2, # push rbx; r8=rcx; eax=edx; ecx=0; cpuid
0x41, 0x89, 0x00, 0x41, 0x89, 0x58, 0x04, 0x41, 0x89, 0x48, 0x08, # [r8]=eax, [r8+4]=ebx, [r8+8]=ecx
0x41, 0x89, 0x50, 0x0C, 0x5B, 0xC3]), # [r8+12]=edx; pop rbx
ctypes.addressof(regs), 1)
ecx1 = regs[2]
if (ecx1 >> 27) & 1 and (ecx1 >> 28) & 1: # OSXSAVE, AVX
xcr0 = (ctypes.c_uint32 * 2)()
_run_stub(bytes([0x49, 0x89, 0xC8, 0x31, 0xC9, 0x0F, 0x01, 0xD0, # r8=rcx; ecx=0; xgetbv
0x41, 0x89, 0x00, 0x41, 0x89, 0x50, 0x04, 0xC3]), ctypes.addressof(xcr0))
if xcr0[0] & 6 == 6:
return "avx"
return "sse4.2" if (ecx1 >> 20) & 1 and (ecx1 >> 23) & 1 else ""
except Exception:
return ""
def cpu_floor(avx2: bool) -> str:
"""The experimental older-CPU build this PC needs (#394 #595 #623): "" with AVX2 (the normal engine), "avx" (Sandy /
Ivy Bridge, AMD Bulldozer), "none" (SSE4.2 + POPCNT: Nehalem, Westmere), or "unsupported". STRATA_ISA_FLOOR=avx|
none asks for that build on any PC (testing it on a newer one)."""
forced = os.environ.get("STRATA_ISA_FLOOR", "").strip().lower()
if forced in ("avx", "none"):
return forced
if avx2:
return ""
if WIN:
f = _cpuid_floor()
else:
try:
txt = open("/proc/cpuinfo").read()
flags = set(re.search(r"^flags\s*:\s*(.*)$", txt, re.M).group(1).split())
except (OSError, AttributeError):
flags = set()
f = "avx" if "avx" in flags else "sse4.2" if {"sse4_2", "popcnt"} <= flags else ""
return {"avx": "avx", "sse4.2": "none"}.get(f, "unsupported")
def _cpuid_avx512_full() -> bool:
"""Windows has no feature bit for VNNI / VBMI: ask the CPU (CPUID leaf 7) through a tiny machine-code stub."""
try:
@@ -1708,7 +1750,9 @@ def build_engine_hip(gpu, llama, vision="none") -> Path:
src, vsrc = source_hash(ENGINE_SOURCES), source_hash(VISION_SOURCES)
archs = sorted(set(gpu.get("archs") or [gpu["arch"]]))
has_archs = set(archs) <= set(meta.get("archs", []))
engine_ok = meta.get("backend") == "hip" and (eng / EXE).exists() and meta.get("src") == src and has_archs
floor = cpu_floor(cpu_info()[1]) # "" on an AVX2 CPU: the normal engine
engine_ok = meta.get("backend") == "hip" and (eng / EXE).exists() and meta.get("src") == src and has_archs and \
(meta.get("isa_floor") or "") == floor
vision_ok = vision == "none" or ((eng / VEXE).exists() and meta.get("vision_src") == vsrc)
if engine_ok and vision_ok:
ok("engine already built for this PC")
@@ -1736,10 +1780,10 @@ def build_engine_hip(gpu, llama, vision="none") -> Path:
f"-DCMAKE_HIP_COMPILER={root / 'llvm' / 'bin' / 'clang++'}", f"-DCMAKE_HIP_COMPILER_ROCM_ROOT={root}",
"-DCMAKE_PREFIX_PATH=" + ";".join([str(root), *libs]),
f"-DCMAKE_HIP_FLAGS=--rocm-path={root} --rocm-device-lib-path={bitcode}",
f"-DSTRATA_GGML_DIR={llama}"], None, "")
f"-DSTRATA_GGML_DIR={llama}", *isa_floor_defs(floor, ROOT / "build-hip", meta)], None, "")
shutil.copy2(ROOT / "build-hip" / EXE, eng / EXE)
meta = {"source": "local-hip", "backend": "hip", "version": source_version(), "archs": archs, "vision": "none",
"lib_dirs": dirs, "src": src}
"lib_dirs": dirs, "src": src, **({"isa_floor": floor} if floor else {})}
if vision != "none":
return build_vision_cpu(eng, stamp, meta, llama, vsrc)
stamp.write_text(json.dumps(meta, indent=1))
@@ -2064,6 +2108,14 @@ def source_hash(parts) -> str:
return h.hexdigest()[:16]
def isa_floor_defs(floor: str, bdir: Path, meta: dict) -> list:
"""The experimental older-CPU build's CMake definition (STRATA_ISA_FLOOR, CMakeLists.txt), none for the normal
build. A build folder configured for another floor is configured afresh: ggml's CPU options are cached there."""
if (meta.get("isa_floor") or "") != floor and (bdir / "CMakeCache.txt").exists():
(bdir / "CMakeCache.txt").unlink()
return [f"-DSTRATA_ISA_FLOOR={floor}"] if floor else []
def engine_defs(archs) -> list:
"""Extra CMake definitions for the engine: the experimental Pascal/Volta build (#295) for cards below sm_75."""
return ["-DSTRATA_EXPERIMENTAL_SM60=ON"] if min(int(x) for x in archs) < 75 else []
@@ -2098,7 +2150,9 @@ def build_engine(gpu, vision, yes, llama) -> Path:
# a card the engine has no code for (a GPU added with --gpus, #128) needs a compile even when the source is the
# same; the compile keeps the generations it was built for
new_arch = local and not set(archs) <= built
engine_ok = local and (eng / EXE).exists() and meta.get("src") == src and not new_arch
floor = cpu_floor(cpu_info()[1]) # "" on an AVX2 CPU: the normal engine
engine_ok = local and (eng / EXE).exists() and meta.get("src") == src and not new_arch and \
(meta.get("isa_floor") or "") == floor
vision_ok = not want_vision or ((eng / VEXE).exists() and (not local or meta.get("vision_src") == vsrc))
if engine_ok and vision_ok:
ok("engine already built for this PC")
@@ -2114,7 +2168,8 @@ def build_engine(gpu, vision, yes, llama) -> Path:
if local and (eng / EXE).exists() else " Compiling the Strata engine for your GPU (10-20 minutes, once) ...")
cmake_build(ROOT, ROOT / "build", "strata",
["-DSTRATA_ENABLE_CUDA=ON", "-DSTRATA_BUILD_TESTS=OFF", f"-DCMAKE_CUDA_ARCHITECTURES={cuda_archs}",
f"-DCMAKE_CUDA_COMPILER={nvcc}", f"-DSTRATA_GGML_DIR={llama}", *engine_defs(archs)],
f"-DCMAKE_CUDA_COMPILER={nvcc}", f"-DSTRATA_GGML_DIR={llama}", *engine_defs(archs),
*isa_floor_defs(floor, ROOT / "build", meta)],
vcvars, "build-strata.bat")
shutil.copy2(ROOT / "build" / EXE, eng / EXE)
if not vision_ok:
@@ -2128,7 +2183,8 @@ def build_engine(gpu, vision, yes, llama) -> Path:
dirs = [str(d) for d in (bindir, bindir / "x64", bindir.parent / "lib64") if d.is_dir()]
stamp.write_text(json.dumps({"source": "local", "version": source_version(), "archs": archs,
"vision": vision,
"cuda_dirs": dirs, "src": src, "vision_src": vsrc if want_vision else None}, indent=1))
"cuda_dirs": dirs, "src": src, "vision_src": vsrc if want_vision else None,
**({"isa_floor": floor} if floor else {})}, indent=1))
ok(f"engine compiled: {eng / EXE}")
return eng
@@ -3466,8 +3522,21 @@ def main() -> int:
"the model may not start or may use less VRAM. Set it to \"System managed\": System > About > "
"Advanced system settings > Performance > Advanced > Virtual memory")
ok(f"CPU: {cpu} ({'AVX-512' if avx512 else 'AVX2' if avx2 else 'no AVX2'})")
floor = cpu_floor(avx2)
if floor == "unsupported":
fail("this CPU has neither AVX2 nor SSE4.2; Strata needs at least SSE4.2 (Intel Nehalem, 2008, or newer)")
if not avx2:
fail("this CPU has no AVX2; Strata needs at least AVX2")
# #394 #595 #623: the ready-made engine is AVX2; an older CPU gets one compiled here, whose CPU experts run on
# ggml-cpu's kernels for this CPU. Experimental: measured only on newer CPUs with the older path forced, and by
# users on a few Xeons. A warning, not a stop.
warn(f"this CPU has no AVX2: Strata support for it is EXPERIMENTAL and slow. Setup compiles the engine on this "
f"PC for {'AVX' if floor == 'avx' else 'SSE4.2'} (STRATA_ISA_FLOOR={floor}; 10-20 minutes, once), and the "
"CPU's share of the experts runs on ggml-cpu's kernels, a few times slower than on an AVX2 CPU. "
"See \"Older CPUs\" in docs/INSTALL.md")
if hip and WIN:
fail("the older-CPU engine is compiled from source, and setup compiles the AMD engine on Linux only",
"use Linux for an AMD card on this CPU, or an NVIDIA card")
a.build = True
if a.check:
say()
for m, d in MODELS.items():
+31 -3
View File
@@ -10,6 +10,7 @@
#include "strata/kernels/elementwise.hpp"
#include "strata/kernels/quantize_act.hpp"
#include "strata/kernels/s2_expert_grouped.hpp"
#include "strata/kernels/cpu/kq_avx1.hpp"
#include "strata/kernels/cpu/kq_avx2.hpp"
#include <cuda_runtime.h>
@@ -1219,8 +1220,35 @@ void RouterLookahead::run() {
}
const auto t0 = std::chrono::steady_clock::now();
want.clear();
strata::kernels::cpu::bf16_rows_dot_multi(routers_[(size_t) layer].data(), (int) n_expert_, (int) n_embd_,
x_.data(), (int) nt, logits.data());
// The router dot is AVX2 (kq_avx2.cpp); a CPU without AVX2 (the experimental older-CPU builds) takes the AVX1
// one (kq_avx1.cpp) or, without AVX, the same sums in plain C++. From the Strata_Dirigo fork (rwkeyes): an
// AVX-only Xeon E5-2687W died here (vpmovzxwd) on its first request. An estimate only (which experts to
// prefetch); the order of the additions differs between the three, the output does not depend on it.
if (strata::kernels::cpu::cpu_avx2_ok()) {
strata::kernels::cpu::bf16_rows_dot_multi(routers_[(size_t) layer].data(), (int) n_expert_, (int) n_embd_,
x_.data(), (int) nt, logits.data());
} else if (strata::kernels::cpu::cpu_avx1_ok()) {
strata::kernels::cpu::bf16_rows_dot_multi_avx1(routers_[(size_t) layer].data(), (int) n_expert_,
(int) n_embd_, x_.data(), (int) nt, logits.data());
} else {
// a mul and an add, not std::fma: without an FMA instruction that is a libm call per element (74x
// slower on a Xeon E5-2665, measured by the fork)
const uint16_t* rw = routers_[(size_t) layer].data();
for (int64_t r = 0; r < n_expert_; ++r) {
const uint16_t* wr = rw + (size_t) r * (size_t) n_embd_;
for (int64_t t = 0; t < nt; ++t) {
const float* xr = x_.data() + (size_t) t * (size_t) n_embd_;
float acc = 0.0f;
for (int64_t c = 0; c < n_embd_; ++c) {
const uint32_t bits = (uint32_t) wr[c] << 16;
float wf;
std::memcpy(&wf, &bits, sizeof wf);
acc += wf * xr[c];
}
logits[(size_t) t * (size_t) n_expert_ + (size_t) r] = acc;
}
}
}
for (int64_t t = 0; t < nt; ++t) {
const float* lt = logits.data() + (size_t) (t * n_expert_);
for (int64_t e = 0; e < n_expert_; ++e) order[(size_t) e] = (int32_t) e;
@@ -2100,7 +2128,7 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
}
}
const auto c1 = std::chrono::steady_clock::now();
if (native && lay.fmt[(size_t) d.layers].gu_type == 42) // a native Q2_0 pack: the Q2_0 kernels' activations
if (native && strata::kernels::cpu::q2_native_kernels(lay.fmt[(size_t) d.layers].gu_type)) // a native Q2_0 pack: the Q2_0 kernels' activations
for (int64_t t = 0; t < n_tok; ++t) act_quant_any(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]);
else if (native)
for (int64_t t = 0; t < n_tok; ++t)
+69
View File
@@ -21,9 +21,26 @@ ExpertLayout g_layout;
const ExpertLayout& expert_layout() { return g_layout; }
int cpu_isa_cap() {
// STRATA_FORCE_ISA (tests, the experimental older-CPU builds): the engine's own dispatch acts as if this CPU
// stopped at that level. ggml-cpu is not affected: it runs what the build compiled it for.
static const int cap = [] {
const char* f = std::getenv("STRATA_FORCE_ISA");
if (f == nullptr || f[0] == '\0') return 3;
const std::string v(f);
if (v == "avx2") return 2;
if (v == "avx") return 1;
if (v == "sse" || v == "sse4.2" || v == "none") return 0;
std::fprintf(stderr, "strata: STRATA_FORCE_ISA=%s is not avx2, avx or sse; ignored\n", f);
return 3;
}();
return cap;
}
bool cpu_avx512_ok() {
static const bool ok = [] {
if (const char* f = std::getenv("STRATA_FORCE_AVX2"); f != nullptr && f[0] == '1') return false;
if (cpu_isa_cap() < 3) return false;
unsigned r[4] = {0, 0, 0, 0};
auto cpuid = [&](unsigned leaf, unsigned sub) {
#if defined(_MSC_VER)
@@ -55,6 +72,7 @@ bool cpu_avx512_ok() {
bool cpu_avx2_ok() {
static const bool ok = [] {
if (cpu_isa_cap() < 2) return false;
unsigned r[4] = {0, 0, 0, 0};
auto cpuid = [&](unsigned leaf, unsigned sub) {
#if defined(_MSC_VER)
@@ -85,6 +103,57 @@ bool cpu_avx2_ok() {
return ok;
}
bool cpu_avx1_ok() {
// AVX (Sandy Bridge, 2011): AVX + OSXSAVE with the OS saving the YMM state; FMA, F16C and AVX2 not needed.
// From the Strata_Dirigo fork (rwkeyes).
static const bool ok = [] {
if (cpu_isa_cap() < 1) return false;
unsigned r[4] = {0, 0, 0, 0};
#if defined(_MSC_VER)
int x[4];
__cpuidex(x, 1, 0);
for (int i = 0; i < 4; ++i) r[i] = (unsigned) x[i];
#else
__cpuid_count(1, 0, r[0], r[1], r[2], r[3]);
#endif
if (!((r[2] >> 27) & 1u) || !((r[2] >> 28) & 1u)) return false; // OSXSAVE, AVX
#if defined(_MSC_VER)
const unsigned long long xcr0 = _xgetbv(0);
#else
unsigned lo = 0, hi = 0;
__asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0));
const unsigned long long xcr0 = ((unsigned long long) hi << 32) | lo;
#endif
return (xcr0 & 0x6) == 0x6;
}();
return ok;
}
bool cpu_sse42_ok() {
static const bool ok = [] {
unsigned r[4] = {0, 0, 0, 0};
#if defined(_MSC_VER)
int x[4];
__cpuidex(x, 1, 0);
for (int i = 0; i < 4; ++i) r[i] = (unsigned) x[i];
#else
__cpuid_count(1, 0, r[0], r[1], r[2], r[3]);
#endif
return ((r[2] >> 20) & 1u) && ((r[2] >> 23) & 1u); // SSE4.2, POPCNT
}();
return ok;
}
const char* isa_floor_build() {
#if defined(STRATA_ISA_FLOOR_AVX)
return "avx";
#elif defined(STRATA_ISA_FLOOR_NONE)
return "sse4.2";
#else
return "";
#endif
}
std::string cpu_name() {
unsigned r[12] = {};
#if defined(_MSC_VER)
+16 -5
View File
@@ -56,19 +56,30 @@ inline __m256i sc32(int s) { return _mm256_set1_epi16(s); }
// keven_signs_q2xs (ggml keeps it static in arch/x86/quants.c): one u64 per 7-bit sign index, byte k
// = 0xFF when bit k of ksigns_iq2xs[i] is set, 0x01 otherwise. With this a whole 32-value sign vector
// is four scalar loads and a set_epi64x - no ksigns byte packing chain and no bit_selector expansion.
// Built once at load time from the shared ggml-common table so it can never drift from it.
//
// Computed at COMPILE time (constexpr), so this file has no static constructor at all. This TU is compiled
// for AVX2, and a runtime constructor here runs before main() on every CPU: MSVC turned its variable shift
// into BMI2 `shlx` (#391, demetree: strata.exe exited 0xC000001D before printing anything on a Sandy Bridge
// Xeon) and GCC vectorised the loop into AVX2 (`vpbroadcastb`, found on an AVX-only Xeon E5 by the
// Strata_Dirigo fork). ksigns_iq2xs[i] is i's 7 bits plus an even-parity bit 7 (ggml-common.h); a const
// array is not usable in a constant expression, so the byte is derived the same way here, and
// native_expert_parity checks these kernels against ggml-cpu's.
struct EvenSigns {
uint64_t v[128];
EvenSigns() {
constexpr EvenSigns() : v{} {
for (int i = 0; i < 128; ++i) {
int par = 0;
for (int k = 0; k < 7; ++k) par ^= (i >> k) & 1;
const int s = i | (par << 7); // == ksigns_iq2xs[i]
uint64_t r = 0;
for (int k = 0; k < 8; ++k)
r |= (uint64_t) (((ksigns_iq2xs[i] >> k) & 1) ? 0xFF : 0x01) << (8 * k);
for (int k = 0; k < 8; ++k) r |= (uint64_t) (((s >> k) & 1) ? 0xFF : 0x01) << (8 * k);
v[i] = r;
}
}
};
static const EvenSigns even_signs;
static constexpr EvenSigns even_signs{};
static_assert(even_signs.v[0] == 0x0101010101010101ull && even_signs.v[1] == 0xFF010101010101FFull,
"keven_signs_q2xs: byte k = 0xFF when bit k of ksigns_iq2xs[i] is set");
inline float hsum8(__m256 v) {
const __m128 lo = _mm256_castps256_ps128(v), hi = _mm256_extractf128_ps(v, 1);
+71
View File
@@ -0,0 +1,71 @@
// src/kernels/cpu/kq_avx1.cpp - the AVX1 router dot for older CPUs (see kq_avx1.hpp). From rwkeyes' Strata_Dirigo
// fork (MIT), its AVX1 floor.
//
// Measured on the hardware this exists for (Xeon E5-2665, 2x8 cores, AVX only) for one layer's router
// [512 experts x 5120 embeddings]: the scalar std::fma fallback it replaces took 362 ms/layer, a scalar
// mul+add 4.9 ms, and this kernel 2.6 ms - 137x, with no extra memory (the weights stay bf16).
//
// Compiled for AVX (/arch:AVX, -mavx; CMakeLists.txt sets that per source); it is only ever called behind
// cpu_avx1_ok(), so no CPU that lacks AVX can reach it.
#include "strata/kernels/cpu/kq_avx1.hpp"
#include <immintrin.h>
#include <cstring>
#if !defined(__AVX__)
#error "kq_avx1.cpp must be compiled with AVX enabled (see the per-source flags in CMakeLists.txt)"
#endif
namespace strata::kernels::cpu {
namespace {
// 8 floats -> one float, the same reduction order the AVX2 kernel's hsum_float_8 uses.
inline float hsum_float_8_avx1(__m256 v) {
__m128 lo = _mm256_castps256_ps128(v);
__m128 hi = _mm256_extractf128_ps(v, 1);
lo = _mm_add_ps(lo, hi);
lo = _mm_add_ps(lo, _mm_movehl_ps(lo, lo));
lo = _mm_add_ss(lo, _mm_shuffle_ps(lo, lo, 0x55));
return _mm_cvtss_f32(lo);
}
// 8 bf16 -> 8 f32: a bf16 is the top half of its f32, so widen in 128-bit halves (AVX1 has no
// 256-bit integer ops) and shift each 32-bit lane into the high half.
inline __m256 bf16x8_to_f32x8_avx1(const uint16_t* p) {
const __m128i v = _mm_loadu_si128((const __m128i*) p);
const __m128i z = _mm_setzero_si128();
const __m128 lo = _mm_castsi128_ps(_mm_slli_epi32(_mm_unpacklo_epi16(v, z), 16));
const __m128 hi = _mm_castsi128_ps(_mm_slli_epi32(_mm_unpackhi_epi16(v, z), 16));
return _mm256_insertf128_ps(_mm256_castps128_ps256(lo), hi, 1);
}
} // namespace
void bf16_rows_dot_multi_avx1(const uint16_t* w, int rows, int cols, const float* x, int nt, float* out) {
// each row is read once for all `nt` (<= 8) tokens, exactly as the AVX2 kernel does
for (int r = 0; r < rows; ++r) {
const uint16_t* wr = w + (size_t) r * (size_t) cols;
__m256 acc[8];
for (int t = 0; t < nt; ++t) acc[t] = _mm256_setzero_ps();
int c = 0;
for (; c + 8 <= cols; c += 8) {
const __m256 wf = bf16x8_to_f32x8_avx1(wr + c);
for (int t = 0; t < nt; ++t) {
const __m256 xv = _mm256_loadu_ps(x + (size_t) t * (size_t) cols + c);
acc[t] = _mm256_add_ps(acc[t], _mm256_mul_ps(wf, xv)); // no FMA on AVX1: mul, then add
}
}
for (int t = 0; t < nt; ++t) {
float s = hsum_float_8_avx1(acc[t]);
for (; c < cols; ++c) { // cols % 8 != 0 tail (cols % 8 == 0 today)
const uint32_t bits = (uint32_t) wr[c] << 16;
float wf; std::memcpy(&wf, &bits, sizeof wf);
s += wf * x[(size_t) t * (size_t) cols + c];
}
out[(size_t) t * (size_t) rows + r] = s;
}
}
}
} // namespace strata::kernels::cpu
+14 -4
View File
@@ -84,7 +84,14 @@ void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const*
// AVX-2 kernel, STRATA_NO_IQ256 drops the AVX-2 kernel; ggml-cpu's single-token vec_dot is reached only with
// both set (and on a CPU without AVX-512, STRATA_NO_IQ512 changes nothing).
static const bool avx512 = cpu_avx512_ok() && std::getenv("STRATA_NO_IQ512") == nullptr;
static const bool avx2 = std::getenv("STRATA_NO_IQ256") == nullptr;
// STRATA_NO_IQ256 drops the AVX-2 kernel. cpu_avx2_ok() is ALSO required: iq_avx2.cpp and kq_avx2.cpp
// are compiled /arch:AVX2 and use AVX2 and FMA3, so calling them on a CPU without either is an
// illegal instruction, not a slow path. The gate sat next to `avx512` above, which does test
// cpu_avx512_ok(), and that asymmetry is what let a pre-Haswell CPU reach iq256_gu_rows.
// Without it this falls through to ggml-cpu's vec_dot below, which is compiled for whatever
// baseline the build selected (AVX1 here) and covers the same types - IQ2_XXS and IQ2_S among
// them. That path loops over tokens itself, so it is correct for any `nt`, not just one.
static const bool avx2 = cpu_avx2_ok() && std::getenv("STRATA_NO_IQ256") == nullptr;
// #152: from how many tokens the multi-token kernels run (ggml's vec_dot below that). The default 2 is the
// measured-fastest rule, but a token's expert rows then round differently alone than in a group, so greedy output
// can depend on how many drafts a verify window held. STRATA_IQ_MT_MIN=1 (opt-in, 0.1.30) uses the multi-token
@@ -93,7 +100,7 @@ void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const*
// Unsloth UD-Q4_K_XL's Q4_K gate/up: the multi-token kernel is bit-exact against ggml's per-token dot (any group
// size, no #152 rule). Opt-in, STRATA_KQ256=1: measured no faster in the engine (a window's expert groups hold
// ~1.4 tokens and the weights stay in L1 across ggml's per-token calls; 1.01-1.13x in native_expert_parity).
static const bool kq = [] { const char* v = std::getenv("STRATA_KQ256"); return v != nullptr && std::atoi(v) != 0; }();
static const bool kq = [] { const char* v = std::getenv("STRATA_KQ256"); return cpu_avx2_ok() && v != nullptr && std::atoi(v) != 0; }();
if (kq && f.gu_type == 12 && nt >= 2) { // one token: ggml's own dot below (the same bits, less overhead)
kq256_gu_rows(f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act, nt, ff, r0, r1);
return;
@@ -133,11 +140,14 @@ void native_down_rows(const NativeFmt& f, const uint8_t* blob, const void* const
static const bool iq4nl_mt = std::getenv("STRATA_NO_IQ4NL") == nullptr;
static const int mt_min = [] { const char* e = std::getenv("STRATA_IQ_MT_MIN"); return e ? std::atoi(e) : 2; }();
static const bool kq = [] { const char* v = std::getenv("STRATA_KQ256"); return v != nullptr && std::atoi(v) != 0; }();
if (kq && nt >= 2 && (f.d_type == 7 || f.d_type == 8)) { // Q5_1 / Q8_0 down: bit-exact, any group size
// Both multi-token kernels below are /arch:AVX2 translation units (kq_avx2.cpp and iq_avx2.cpp),
// so a CPU without AVX2 has to reach ggml-cpu's vec_dot instead - same reasoning as the gate/up
// rows above, where `avx512` tested cpu_avx512_ok() and `avx2` did not.
if (cpu_avx2_ok() && kq && nt >= 2 && (f.d_type == 7 || f.d_type == 8)) { // Q5_1 / Q8_0 down: bit-exact, any group size
kq256_rows(f.d_type, blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1);
return;
}
if (nt >= mt_min && f.d_type == 20 && iq4nl_mt) { // #152: the same rule as the gate/up rows
if (cpu_avx2_ok() && nt >= mt_min && f.d_type == 20 && iq4nl_mt) { // #152: the same rule as the gate/up rows
iq4nl256_down_rows(blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1);
return;
}
+3 -3
View File
@@ -549,7 +549,7 @@ void ExpertPool::drain(int id, ExpertScratch& scratch, uint32_t epoch) {
const int e = (int) (r / per), r0 = (int) (r % per);
const int r1 = (int) std::min<int64_t>(per, r0 + (g1 - r));
SplitBufMulti& sb = split_multi_[(size_t) e];
if (mode_ == 5 && nfmt_->gu_type == 42) {
if (mode_ == 5 && q2_native_kernels(nfmt_->gu_type)) {
// a native Q2_0 pack: gate and up rows on the Q2_0 kernels, then SwiGLU
thread_local float gbuf[MAXT][FF], ubuf[MAXT][FF];
float* gp[MAXT];
@@ -565,7 +565,7 @@ void ExpertPool::drain(int id, ExpertScratch& scratch, uint32_t epoch) {
float* ff[MAXT];
for (int t = 0; t < mjobs_[e].nt; ++t) ff[t] = sb.ff[t];
native_gu_rows(*nfmt_, mjobs_[e].blob, mjobs_[e].nact, mjobs_[e].nt, ff, r0, r1);
} else if (nfmt_->d_type == 42) {
} else if (q2_native_kernels(nfmt_->d_type)) {
// Q2_0 down (most IQ layers): the AVX-512 kernel, ggml-cpu has only a scalar one on x86
const ActQ* a2[MAXT];
for (int t = 0; t < mjobs_[e].nt; ++t) a2[t] = &sb.a2[t];
@@ -685,7 +685,7 @@ void ExpertPool::run_split_multi_native(const NativeFmt& f, ExpertJobMulti* jobs
const auto b = std::chrono::steady_clock::now();
for (int e = 0; e < nb; ++e)
for (int t = 0; t < mjobs_[e].nt; ++t)
if (f.d_type == 42) act_quant_any(split_multi_[(size_t) e].ff[t], FF, split_multi_[(size_t) e].a2[t]);
if (q2_native_kernels(f.d_type)) act_quant_any(split_multi_[(size_t) e].ff[t], FF, split_multi_[(size_t) e].a2[t]);
else native_quant_h(f, split_multi_[(size_t) e].ff[t], split_multi_[(size_t) e].hq[t]);
const auto c = std::chrono::steady_clock::now();
mrows_ = (int64_t) nb * H;
+70
View File
@@ -0,0 +1,70 @@
// src/kernels/cpu/router_dot_parity.cpp - the router lookahead's BF16 dot on each rung this CPU has: the AVX2 kernel
// (kq_avx2.cpp) and the AVX1 one for older CPUs (kq_avx1.cpp), against a double-precision reference, plus the time
// of one layer's router. No GPU, no model: random BF16 rows of the model's router shape [512 x 2560], 1..8 tokens.
//
// router_dot_parity (STRATA_FORCE_ISA=avx leaves out the AVX2 kernel, as on an AVX-only CPU)
#include "strata/kernels/cpu/expert_layout.hpp"
#include "strata/kernels/cpu/kq_avx1.hpp"
#include "strata/kernels/cpu/kq_avx2.hpp"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <random>
#include <vector>
namespace cpu = strata::kernels::cpu;
int main() {
constexpr int R = 512, C = 2560, MAXT = 8;
std::mt19937 rng(7);
std::normal_distribution<float> nd(0.f, 0.05f);
std::vector<uint16_t> w((size_t) R * C);
for (auto& v : w) {
const float f = nd(rng);
uint32_t b;
std::memcpy(&b, &f, 4);
v = (uint16_t) (b >> 16);
}
std::vector<float> x((size_t) MAXT * C);
for (auto& v : x) v = nd(rng) * 20.f;
std::vector<double> ref((size_t) MAXT * R);
for (int t = 0; t < MAXT; ++t)
for (int r = 0; r < R; ++r) {
double s = 0;
for (int c = 0; c < C; ++c) {
const uint32_t b = (uint32_t) w[(size_t) r * C + c] << 16;
float f;
std::memcpy(&f, &b, 4);
s += (double) f * x[(size_t) t * C + c];
}
ref[(size_t) t * R + r] = s;
}
int failures = 0;
auto run = [&](const char* tag, void (*fn)(const uint16_t*, int, int, const float*, int, float*)) {
std::vector<float> out((size_t) MAXT * R);
for (int nt = 1; nt <= MAXT; ++nt) {
std::fill(out.begin(), out.end(), 0.f);
fn(w.data(), R, C, x.data(), nt, out.data());
double num = 0, den = 0;
for (int i = 0; i < nt * R; ++i) { num += std::fabs(out[(size_t) i] - ref[(size_t) i]); den += std::fabs(ref[(size_t) i]); }
const double rel = num / (den + 1e-30);
if (nt == 1 || nt == MAXT) std::printf(" %-5s nt=%d rel %.2e vs the double reference\n", tag, nt, rel);
if (!(rel < 1e-5)) { std::printf(" %-5s nt=%d MISMATCH\n", tag, nt); ++failures; }
}
const int it = 20;
const auto t0 = std::chrono::steady_clock::now();
for (int i = 0; i < it; ++i) fn(w.data(), R, C, x.data(), 4, out.data());
const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count() / it;
std::printf(" %-5s one layer's router, 4 tokens: %.3f ms\n", tag, ms);
};
std::printf("router_dot_parity: %s (avx2 %d, avx %d)\n", cpu::cpu_name().c_str(), (int) cpu::cpu_avx2_ok(),
(int) cpu::cpu_avx1_ok());
if (cpu::cpu_avx2_ok()) run("avx2", cpu::bf16_rows_dot_multi);
if (cpu::cpu_avx1_ok()) run("avx", cpu::bf16_rows_dot_multi_avx1);
std::printf("router_dot_parity: %d failures\n", failures);
return failures == 0 ? 0 : 1;
}
+4 -4
View File
@@ -147,7 +147,7 @@ int check_blob(const cpu::NativeFmt& f, const std::vector<uint8_t>& blob, int se
};
// guarded: the binary runs on AVX-2 CPUs too, and IQ4_XS has no AVX-512 kernel (an empty switch)
if (cpu::cpu_avx512_ok() && cpu::iq512_supported(f.gu_type)) check("avx512", true);
if (cpu::iq256_supported(f.gu_type)) check("avx2", false);
if (cpu::cpu_avx2_ok() && cpu::iq256_supported(f.gu_type)) check("avx2", false); // no AVX2: ggml-cpu only
}
for (int k = 0; k < NT; ++k) {
cpu::native_quant_h(f, ff[k].data(), hq[k].data());
@@ -180,7 +180,7 @@ int check_blob(const cpu::NativeFmt& f, const std::vector<uint8_t>& blob, int se
// BIT FOR BIT, for 1..8 tokens; then the time of 4 tokens (a verify window) both ways
for (int role = 0; role < 2; ++role) {
const int type = role == 0 ? f.gu_type : f.d_type;
if (!cpu::kq256_supported(type) || (role == 0 && type != 12)) continue;
if (!cpu::cpu_avx2_ok() || !cpu::kq256_supported(type) || (role == 0 && type != 12)) continue;
const int n = role == 0 ? (int) H : (int) FF, rows = role == 0 ? (int) FF : (int) H;
const size_t rb = role == 0 ? f.gu_row : f.d_row;
const uint8_t* w = blob.data() + (role == 0 ? 0 : f.down_off);
@@ -223,7 +223,7 @@ int check_blob(const cpu::NativeFmt& f, const std::vector<uint8_t>& blob, int se
role == 0 ? "gate" : "down", differ, us_k, us_g, us_g / us_k);
if (differ) ++failures;
}
if (f.d_type == 42) {
if (cpu::q2_native_kernels(f.d_type)) {
// (b2) the GGUF-layout Q2_0 kernel the pool uses for Q2_0 down projections - the AVX-512 one
// where the CPU has it, the AVX-2 one (q2_avx2.cpp) where it does not. Calling the AVX-512
// kernel unconditionally faults on a Zen 2/3 CPU.
@@ -240,7 +240,7 @@ int check_blob(const cpu::NativeFmt& f, const std::vector<uint8_t>& blob, int se
std::printf(" q2_0 %s down vs ggml down: rel %.2e\n",
cpu::cpu_avx512_ok() ? "AVX-512" : "AVX-2", rel(alt, got_c));
}
if (f.d_type == 20) {
if (f.d_type == 20 && cpu::cpu_avx2_ok()) {
// (b3) the IQ4_NL multi-token AVX-2 kernel the pool now uses for IQ4_NL down projections,
// against ggml-cpu's single-token vec_dot on the SAME Q8_0 activations (h), plus timing.
std::vector<float> alt((size_t) NT * H), refd((size_t) NT * H);
+26 -4
View File
@@ -1923,12 +1923,33 @@ int main(int argc, char** argv) {
// ... and nothing runs on a CPU without AVX2: every CPU expert kernel is AVX2 at least (the AVX-512 ones are
// chosen above it), and so is ggml-cpu in the release build, which the native pack's layout load initializes
// next. Refused here, by name, rather than an illegal instruction in the first expert.
if (!strata::kernels::cpu::cpu_avx2_ok()) {
std::fprintf(stderr, "strata generate: this CPU (%s) does not support AVX2 with FMA and F16C, which every CPU "
"expert kernel needs; Strata runs on Intel Haswell (2013), AMD Zen (2017) or newer\n",
// The experimental older-CPU build (STRATA_ISA_FLOOR=avx|none, compiled on that PC; #394 #595 #623) has ggml-cpu
// for that floor, so a native pack's experts run there on ggml-cpu (every AVX2 kernel is behind cpu_avx2_ok).
const char* isa_floor = strata::kernels::cpu::isa_floor_build();
if (!strata::kernels::cpu::cpu_avx2_ok() && isa_floor[0] == '\0') {
std::fprintf(stderr, "strata generate: this CPU (%s) does not support AVX2 with FMA and F16C, which this engine's "
"CPU expert kernels need; Strata runs on Intel Haswell (2013), AMD Zen (2017) or newer. "
"Older CPUs are EXPERIMENTAL and slow: setup compiles an engine for them on this PC "
"(STRATA_ISA_FLOOR, see \"Older CPUs\" in docs/INSTALL.md)\n",
strata::kernels::cpu::cpu_name().c_str());
return 2;
}
if (isa_floor[0] != '\0') {
const bool avx_floor = std::strcmp(isa_floor, "avx") == 0;
if (avx_floor ? !strata::kernels::cpu::cpu_avx1_ok() : !strata::kernels::cpu::cpu_sse42_ok()) {
std::fprintf(stderr, "strata generate: this engine is the older-CPU build for %s, which this CPU (%s) does "
"not have%s\n", avx_floor ? "AVX" : "SSE4.2 with POPCNT",
strata::kernels::cpu::cpu_name().c_str(),
avx_floor ? "; compile it with STRATA_ISA_FLOOR=none" : "");
return 2;
}
if (!strata::kernels::cpu::cpu_avx2_ok())
std::fprintf(stderr, "strata generate: EXPERIMENTAL older-CPU build (ggml-cpu for %s): this CPU has no AVX2, "
"so the CPU's experts run on ggml-cpu's kernels - expect it to be slow\n", isa_floor);
else
std::fprintf(stderr, "strata generate: this is the older-CPU build (ggml-cpu for %s); this CPU has AVX2, "
"and the normal build is faster on it\n", isa_floor);
}
std::string err;
if (!o.native_head_gguf.empty() && !o.stream_token) {
@@ -2001,7 +2022,8 @@ int main(int argc, char** argv) {
else if (!strata::kernels::cpu::cpu_avx512_ok())
std::fprintf(stderr, "strata generate: this CPU has no AVX-512: the expert kernels run on %s "
"(multi-token for the i-quant gate/up rows)\n",
std::getenv("STRATA_NO_IQ256") == nullptr ? "AVX-2" : "ggml-cpu vec_dot (STRATA_NO_IQ256 set)");
!strata::kernels::cpu::cpu_avx2_ok() ? "ggml-cpu vec_dot (no AVX2: the older-CPU build)"
: std::getenv("STRATA_NO_IQ256") == nullptr ? "AVX-2" : "ggml-cpu vec_dot (STRATA_NO_IQ256 set)");
strata::core::ModelGeometry g; // canonical defaults; the model file overrides the MoE shape below
int64_t K = 10;
// THE ROPE CONFIG RESOLVES HERE, BEFORE ANY WEIGHT MOVES - the CLI and the model file have both spoken,
+3 -2
View File
@@ -680,8 +680,9 @@ class Strata:
ctx = 32768 if vram < 14 else 65536 if vram < 20 else 131072
if vram < 11:
notes.append("less than 12 GB of VRAM: it runs, but slowly (most experts stay on the CPU)")
if hw.get("cpu", {}).get("avx2") is False:
return {"family": None, "model": None, "why": "this CPU has no AVX2; Strata needs at least AVX2"}
if hw.get("cpu", {}).get("avx2") is False: # #623: a warning, not a stop (setup compiles for it)
notes.append("this CPU has no AVX2: EXPERIMENTAL and slow - setup compiles the engine on this PC for the "
"older CPU (10-20 minutes), and the CPU's share of the experts runs a few times slower")
if backend == "hip":
notes.append("AMD (experimental, Linux): the engine is compiled during setup; no images")
cmd = (("START-HERE.bat --setup" if WIN else "./setup.sh --setup") +
+95
View File
@@ -0,0 +1,95 @@
"""Tests for setup.py's experimental older-CPU build (#394 #595 #623): which floor a CPU without AVX2 gets, the CMake
definition, a build folder configured afresh when the floor changes, and the MCP server's note instead of a refusal.
No compiler, no GPU.
python -m unittest tools.test_setup_oldcpu
"""
from __future__ import annotations
import io
import os
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "tools"))
import setup # noqa: E402
def cpuinfo(flags: str):
return mock.patch("builtins.open", lambda *a, **k: io.StringIO(f"model name\t: Old Xeon\nflags\t\t: {flags}\n"))
class FloorTest(unittest.TestCase):
def setUp(self):
self.env = mock.patch.dict(os.environ, {"STRATA_ISA_FLOOR": ""})
self.env.start()
def tearDown(self):
self.env.stop()
def test_avx2_cpu_gets_the_normal_engine(self):
self.assertEqual(setup.cpu_floor(True), "")
def test_linux_flags(self):
with mock.patch.object(setup, "WIN", False):
with cpuinfo("fpu sse4_1 sse4_2 popcnt avx xsave"):
self.assertEqual(setup.cpu_floor(False), "avx")
with cpuinfo("fpu sse4_1 sse4_2 popcnt"):
self.assertEqual(setup.cpu_floor(False), "none")
with cpuinfo("fpu sse3 ssse3"):
self.assertEqual(setup.cpu_floor(False), "unsupported")
def test_windows_probe(self):
with mock.patch.object(setup, "WIN", True):
for probe, want in (("avx", "avx"), ("sse4.2", "none"), ("", "unsupported")):
with mock.patch.object(setup, "_cpuid_floor", lambda p=probe: p):
self.assertEqual(setup.cpu_floor(False), want)
def test_env_asks_for_a_floor_build_on_any_cpu(self):
for v in ("avx", "none", "AVX"):
with mock.patch.dict(os.environ, {"STRATA_ISA_FLOOR": v}):
self.assertEqual(setup.cpu_floor(True), v.lower())
with mock.patch.dict(os.environ, {"STRATA_ISA_FLOOR": "bogus"}):
self.assertEqual(setup.cpu_floor(True), "")
@unittest.skipUnless(os.name == "nt", "the CPUID stub runs on Windows")
def test_this_pc_probe(self):
self.assertIn(setup._cpuid_floor(), ("avx", "sse4.2")) # any x86-64 PC that runs the tests
class DefsTest(unittest.TestCase):
def test_defs_and_fresh_configure(self):
with tempfile.TemporaryDirectory() as d:
b = Path(d)
cache = b / "CMakeCache.txt"
self.assertEqual(setup.isa_floor_defs("", b, {}), []) # the normal build: nothing added
cache.write_text("x")
self.assertEqual(setup.isa_floor_defs("avx", b, {"isa_floor": "avx"}), ["-DSTRATA_ISA_FLOOR=avx"])
self.assertTrue(cache.exists()) # same floor: the folder is kept
self.assertEqual(setup.isa_floor_defs("none", b, {"isa_floor": "avx"}), ["-DSTRATA_ISA_FLOOR=none"])
self.assertFalse(cache.exists()) # another floor: configured afresh
cache.write_text("x")
self.assertEqual(setup.isa_floor_defs("", b, {"isa_floor": "none"}), [])
self.assertFalse(cache.exists()) # back to the normal build
cache.write_text("x")
setup.isa_floor_defs("", b, {})
self.assertTrue(cache.exists()) # the normal build's folder untouched
class McpTest(unittest.TestCase):
def test_no_avx2_is_a_note_not_a_refusal(self):
import strata_mcp as M
s = M.Strata(ROOT)
gpu = [{"index": 0, "name": "x", "vram_gb": 24.0, "usable": True, "vendor": "nvidia"}]
r = s.recommend({"ram_gb": 64, "gpus": gpu, "cpu": {"avx2": False}})
self.assertIsNotNone(r["model"])
self.assertTrue(any("no AVX2" in n and "EXPERIMENTAL" in n for n in r["notes"]))
if __name__ == "__main__":
unittest.main()