Merge f-clean-p2i into next-0224: clean-room P2 files wired in (dp4a, rope scaling, dequant, image resize, CPU expert oracle parts, GGUF core, x86 and NEON tiers, kq dots, split HIP iqdot)

The derived regions of 14 files are replaced by the clean-room files written from the interface spec; the allowlist entries of the replaced files are removed.
Gates (12-01) on the tree with #7310 on top: z440 CUDA release build (checks clean, strata --help unchanged, rope device test), owner PC MSVC + CUDA build and the 8 unit tests incl. AVX-512,
boston cpu-check-native (only pool_tasks_test differs, as on main); on the tree before #7310 also p1004, HIP compile (rx9070, rdna2, gfx906, gfx1010, gfx1012) and NEON on an M4.
This commit is contained in:
Niko1221 committed 2026-12-01 09:10:29 +01:00
commit addfdb1618
156 files changed
+30898 -2708

No files matched your search

+2
View File
@@ -17,6 +17,8 @@ include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/strata_geometry.cmake) # -DSTRATA_GE
include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/strata_ggml.cmake) # which ggml: the vendored third_party/strata-ggml, or -DSTRATA_ORACLE_GGML_DIR (tests only)
include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/backends/cpu.cmake) # strata_kernels_cpu, the native (ggml-cpu) expert rows, the CPU tests
include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/backends/quant.cmake) # strata_quant: the Strata quant layer (no ggml) and its oracle tests
include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/backends/clean_p2.cmake) # the clean-room round: unit tests of the rewritten pieces (tests/clean_p2)
include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/backends/clean_p2_neon.cmake) # arm64: the NEON tier tests
include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/backends/cuda.cmake) # NVIDIA: toolchain, Strata's prompt kernels (strata_pf_own)
include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/backends/hip.cmake) # AMD: gfx906 compat, Strata's prompt kernels on HIP
include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/strata_gpu_engine.cmake) # the GPU engine both of them build
+53
View File
@@ -0,0 +1,53 @@
# The clean-room round (P2): unit tests of the rewritten pieces, built from the spec vectors in tests/data/clean_p2.
# Every test here is CPU-only and needs no model.
if(STRATA_BUILD_TESTS)
set(_cp2_dir ${CMAKE_CURRENT_SOURCE_DIR}/tests/clean_p2)
set(_cp2_data ${CMAKE_CURRENT_SOURCE_DIR}/tests/data/clean_p2)
function(strata_clean_p2_test name)
add_executable(${name} ${ARGN})
target_compile_features(${name} PRIVATE cxx_std_20)
target_include_directories(${name} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_cp2_dir})
target_compile_definitions(${name} PRIVATE STRATA_CLEAN_P2_DATA="${_cp2_data}")
if(NOT MSVC)
target_compile_options(${name} PRIVATE -ffp-contract=off)
else()
target_compile_options(${name} PRIVATE /fp:precise)
endif()
add_test(NAME ${name} COMMAND ${name})
endfunction()
# P-3: artifact/dequant.hpp
strata_clean_p2_test(dequant_vectors_test ${_cp2_dir}/dequant_vectors_test.cpp)
# P-2: kernels/rope_yarn_math.hpp
strata_clean_p2_test(rope_yarn_golden_test ${_cp2_dir}/rope_yarn_golden_test.cpp)
# P-1: hip_compat/dp4a_rdna1.hpp, host emulation of the RDNA1 form
if(NOT MSVC) # the host emulation uses GNU inline asm
strata_clean_p2_test(dp4a_rdna1_host_test ${_cp2_dir}/dp4a_rdna1_host_test.cpp)
endif()
# P-5: src/kernels/cpu/expert_oracle_parts.hpp
strata_clean_p2_test(expert_oracle_parts_test ${_cp2_dir}/expert_oracle_parts_test.cpp)
# P-7: the x86 tier (dot_avx2.cpp, act_avx512.cpp, kq_dots_avx2): against the plain / Avx2 kernels of the quant layer, bit for bit. strata_quant is created
# later in CMakeLists.txt, so the registration is deferred to the end of the directory scope.
function(strata_clean_p2_quant_tests)
if(TARGET strata_quant AND STRATA_CPU_X86)
strata_clean_p2_test(dot_avx2_verify ${_cp2_dir}/dot_avx2_verify.cpp)
target_include_directories(dot_avx2_verify PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/quant)
target_link_libraries(dot_avx2_verify PRIVATE strata_quant)
set_tests_properties(dot_avx2_verify PROPERTIES ENVIRONMENT "STRATA_FORMAT_TABLES=${CMAKE_CURRENT_SOURCE_DIR}/../terminal/tools/format_tables" TIMEOUT 600)
strata_clean_p2_test(act_avx512_verify ${_cp2_dir}/act_avx512_verify.cpp)
target_include_directories(act_avx512_verify PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/quant)
target_link_libraries(act_avx512_verify PRIVATE strata_quant)
set_tests_properties(act_avx512_verify PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) # needs an AVX-512 CPU: 77 = skipped
strata_clean_p2_test(kq_dots_avx2_test ${_cp2_dir}/kq_dots_avx2_test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cpu/kq_dots_avx2.cpp)
target_include_directories(kq_dots_avx2_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/quant ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml)
target_link_libraries(kq_dots_avx2_test PRIVATE strata_quant)
if(MSVC)
set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cpu/kq_dots_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2")
else()
set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cpu/kq_dots_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")
endif()
endif()
endfunction()
cmake_language(DEFER DIRECTORY ${CMAKE_SOURCE_DIR} CALL strata_clean_p2_quant_tests)
endif()
+20
View File
@@ -0,0 +1,20 @@
# The clean-room round (P2), packet P-8: unit tests of the NEON tier (arm/dot_neon.cpp, arm/arm_act.inc).
# arm64 only; they link strata_quant, so they test whatever tier files the build has.
if(STRATA_BUILD_TESTS AND NOT STRATA_CPU_X86 AND CMAKE_SYSTEM_PROCESSOR MATCHES "^(aarch64|arm64|ARM64)$")
set(_cp2_dir ${CMAKE_CURRENT_SOURCE_DIR}/tests/clean_p2)
# the four optimised dots against their in-TU oracles, bit for bit (1.2 million random rows each, edge rows included), and the dispatcher's pick
add_executable(neon_dot_cmp ${_cp2_dir}/neon_dot_cmp.cpp)
target_include_directories(neon_dot_cmp PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(neon_dot_cmp PRIVATE strata_quant)
add_test(NAME neon_dot_cmp COMMAND neon_dot_cmp)
add_test(NAME neon_dot_cmp_nonfinite COMMAND neon_dot_cmp 300000 --nonfinite)
# the activation quantisers against a scalar model of the spec (Q8_0, Q8_1) and quantize_q8_K_ref (Q8_K)
add_executable(neon_act_test ${_cp2_dir}/neon_act_test.cpp)
target_include_directories(neon_act_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(neon_act_test PRIVATE strata_quant)
add_test(NAME neon_act_test COMMAND neon_act_test)
# speed of oracle vs optimised kernel (interleaved rounds); not a test
add_executable(neon_dot_bench ${_cp2_dir}/neon_dot_bench.cpp)
target_link_libraries(neon_dot_bench PRIVATE strata_quant)
set_tests_properties(neon_dot_cmp neon_dot_cmp_nonfinite PROPERTIES TIMEOUT 600)
endif()
+3 -3
View File
@@ -307,7 +307,7 @@ macro(strata_cpu_native_experts)
target_sources(strata_kernels_cpu PRIVATE src/kernels/cpu/native_expert.cpp)
if(STRATA_CPU_X86)
target_sources(strata_kernels_cpu PRIVATE src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/iq_avx2.cpp
src/kernels/cpu/kq_avx2.cpp src/kernels/cpu/kq_avx512.cpp src/kernels/cpu/kq_avx1.cpp src/kernels/cpu/q2_avx1.cpp
src/kernels/cpu/kq_avx2.cpp src/kernels/cpu/kq_dots_avx2.cpp src/kernels/cpu/kq_avx512.cpp src/kernels/cpu/kq_avx1.cpp src/kernels/cpu/q2_avx1.cpp
src/kernels/cpu/iq_avx1.cpp src/kernels/cpu/nvfp4_avx512.cpp src/kernels/cpu/nvfp4_avx2.cpp
src/kernels/cpu/tq_cpu.cpp src/kernels/cpu/tq_avx2.cpp src/kernels/cpu/tq_avx512.cpp)
else()
@@ -320,7 +320,7 @@ macro(strata_cpu_native_experts)
set_source_files_properties(src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/nvfp4_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")
set_source_files_properties(src/kernels/cpu/kq_avx2.cpp src/kernels/cpu/kq_dots_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2")
set_source_files_properties(src/kernels/cpu/kq_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512")
set_source_files_properties(src/kernels/cpu/nvfp4_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2")
set_source_files_properties(src/kernels/cpu/tq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2")
@@ -336,7 +336,7 @@ macro(strata_cpu_native_experts)
set_source_files_properties(src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/nvfp4_avx512.cpp PROPERTIES COMPILE_OPTIONS
"-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mavx512vpopcntdq;-mbmi2;-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_avx2.cpp src/kernels/cpu/kq_dots_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")
set_source_files_properties(src/kernels/cpu/nvfp4_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")
set_source_files_properties(src/kernels/cpu/kq_avx512.cpp PROPERTIES COMPILE_OPTIONS
"-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mavx2;-mfma;-mf16c")
+232 -263
View File
@@ -1,308 +1,277 @@
#pragma once
// src/artifact/dequant.cpp - P1.S3: scalar reference dequantizers, transcribed from ggml.
// Scalar float32 reference dequantisers for the GGUF block formats Strata reads.
//
// P1.S3 asks for every encoding present in the Q2_0 file. This starts with the ones on the critical
// path (the routed experts are all Q2_0) plus the trivial element types, and is structured so the
// rest drop in. Source of truth per encoding is quoted in each function.
// Written from the block-format tables of phaseA-tests/hy4gguf/FORMAT-SPEC.md (sections 2-5, 9, 12-16) only.
// Every function takes one block and writes that block's elements in element order. Rounding rule: each
// operator rounds to float32 on its own, left to right as written in the formulas below, and no product may
// be fused into a following add or subtract (keep the translation unit's -ffp-contract setting as it is;
// the clang pragma below only makes that explicit where the compiler honours it).
//
// Q2_0 is the one that matters, and its contract is settled from source in docs/q2_0-contract.md:
// block = { fp16 d; uint8 qs[16] } = 64 elements, 18 bytes
// code {0,1,2,3} -> symbol {-1,0,+1,+2}; v = (code - 1) * d
// 4 codes per byte, LSB-first: byte j/4, bits (j%4)*2
// QK2_0 = 64 is PROVEN from the artifact's own offset brackets, not assumed (the llama.cpp PR that
// introduced the type used 128; this artifact is 64).
//
// Validation: `--check <file.gguf>` dequantizes real blocks and asserts the STRUCTURAL invariant that
// every output value is one of {-d, 0, +d, +2d} for that block's own scale. That catches bit-order,
// sign and stride bugs, which are the failure modes a dequantizer actually has. It is deliberately
// not a correctness-vs-ggml test - that needs ggml linked, which is P1.S3's next step.
#ifndef STRATA_ARTIFACT_DEQUANT_HPP
#define STRATA_ARTIFACT_DEQUANT_HPP
#ifndef STRATA_GGUF_MAIN_DISABLED
#define STRATA_GGUF_MAIN_DISABLED
#endif
#include "strata/artifact/gguf_reader.hpp"
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#define STRATA_GGUF_MAIN_DISABLED 1
#include "strata/artifact/gguf_reader.hpp"
#if defined(__clang__)
#pragma STDC FP_CONTRACT OFF
#endif
namespace strata {
// ---- fp16/bf16 -> fp32. Both handle subnormals and infinities; naive shifts do not.
// ---- scalar conversions ---------------------------------------------------------------------------------
// little-endian 16-bit word at p (no alignment assumed)
inline uint16_t read_u16(const uint8_t* p) { return (uint16_t)(p[0] | (p[1] << 8)); }
namespace dq_detail {
inline uint32_t read_u32(const uint8_t* p) {
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
inline float bits_to_float(uint32_t u) {
float f;
std::memcpy(&f, &u, sizeof f);
return f;
}
} // namespace dq_detail
// IEEE binary16 -> binary32. Exact for every finite half; subnormal halves stay subnormal-derived values
// (never flushed), infinities map to infinities, a NaN keeps its payload shifted left by 13.
inline float fp16_to_fp32(uint16_t h) {
const uint32_t sign = (uint32_t)(h >> 15) & 1u;
uint32_t exp = (h >> 10) & 0x1Fu, man = h & 0x3FFu, f;
if (exp == 0) {
if (man == 0)
f = sign << 31;
else {
exp = 127 - 15 + 1;
while (!(man & 0x400u)) {
man <<= 1;
--exp;
}
man &= 0x3FFu;
f = (sign << 31) | (exp << 23) | (man << 13);
}
} else if (exp == 31)
f = (sign << 31) | 0x7F800000u | (man << 13);
else
f = (sign << 31) | ((exp - 15 + 127) << 23) | (man << 13);
float out;
std::memcpy(&out, &f, 4);
return out;
}
inline float bf16_to_fp32(uint16_t h) {
const uint32_t f = (uint32_t)h << 16;
float out;
std::memcpy(&out, &f, 4);
return out;
}
inline uint16_t read_u16(const uint8_t* p) {
return (uint16_t)(p[0] | (p[1] << 8));
}
// ---- Q2_0: 64 elements from an 18-byte block. Mirrors dequantize_row_q2_0 (ggml master 3cf03257).
inline void dequantize_q2_0(const uint8_t* block, float* out) {
const float d = fp16_to_fp32(read_u16(block));
const uint8_t* qs = block + 2;
for (int j = 0; j < 64; ++j) {
const int byte_index = j / 4;
const int bit_offset = (j % 4) * 2;
const int code = (qs[byte_index] >> bit_offset) & 0x03;
out[j] = (float)(code - 1) * d; // code {0,1,2,3} -> symbol {-1,0,+1,+2}
const uint32_t sign = (uint32_t)(h & 0x8000u) << 16;
const uint32_t exp5 = (h >> 10) & 0x1Fu;
const uint32_t man = h & 0x3FFu;
if (exp5 == 0x1Fu) return dq_detail::bits_to_float(sign | 0x7F800000u | (man << 13));
if (exp5 == 0) {
// a subnormal half is man * 2^-24: man (< 1024) is exact in float32 and a power-of-two scale is exact
const float mag = (float)man * dq_detail::bits_to_float(0x33800000u); // 2^-24
return sign ? -mag : mag;
}
return dq_detail::bits_to_float(sign | ((exp5 + 112u) << 23) | (man << 13));
}
// ---- Q8_0: 32 elements from a 34-byte block.
inline void dequantize_q8_0(const uint8_t* block, float* out) {
const float d = fp16_to_fp32(read_u16(block));
const int8_t* qs = (const int8_t*)(block + 2);
for (int j = 0; j < 32; ++j) out[j] = (float)qs[j] * d;
}
// bfloat16 -> binary32: the 16 bits become the high half of the float.
inline float bf16_to_fp32(uint16_t b) { return dq_detail::bits_to_float((uint32_t)b << 16); }
// ---- Q4_0: 32 elements from an 18-byte block. Low nibble is element j, high nibble is j+16.
inline void dequantize_q4_0(const uint8_t* block, float* out) {
const float d = fp16_to_fp32(read_u16(block));
const uint8_t* qs = block + 2;
for (int j = 0; j < 16; ++j) {
out[j] = (float)((int)(qs[j] & 0x0F) - 8) * d;
out[j + 16] = (float)((int)(qs[j] >> 4) - 8) * d;
}
}
// ---- tables ---------------------------------------------------------------------------------------------
// ---- Q5_0: 32 elements from a 22-byte block. Same nibble layout as Q4_0 plus a 5th bit per element
// packed in qh[4]; the 32 bits of qh are the high bits of elements 0..31 in order.
inline void dequantize_q5_0(const uint8_t* block, float* out) {
const float d = fp16_to_fp32(read_u16(block));
const uint8_t* qh = block + 2;
const uint8_t* qs = block + 6;
const uint32_t h =
(uint32_t)qh[0] | ((uint32_t)qh[1] << 8) | ((uint32_t)qh[2] << 16) | ((uint32_t)qh[3] << 24);
for (int j = 0; j < 16; ++j) {
const int x0 = (int)(qs[j] & 0x0F) | (int)(((h >> j) & 1u) << 4);
const int x1 = (int)(qs[j] >> 4) | (int)(((h >> (j + 16)) & 1u) << 4);
out[j] = (float)(x0 - 16) * d;
out[j + 16] = (float)(x1 - 16) * d;
}
}
// ---- Q5_1: 32 elements from a 24-byte block: fp16 d, fp16 m, then Q5_0's qh[4] and qs[16]. The 5-bit codes are
// unsigned and the block's minimum m is added instead of Q5_0's fixed -16 offset (dequantize_row_q5_1).
inline void dequantize_q5_1(const uint8_t* block, float* out) {
const float d = fp16_to_fp32(read_u16(block));
const float m = fp16_to_fp32(read_u16(block + 2));
const uint8_t* qh = block + 4;
const uint8_t* qs = block + 8;
const uint32_t h =
(uint32_t)qh[0] | ((uint32_t)qh[1] << 8) | ((uint32_t)qh[2] << 16) | ((uint32_t)qh[3] << 24);
for (int j = 0; j < 16; ++j) {
const int x0 = (int)(qs[j] & 0x0F) | (int)(((h >> j) & 1u) << 4);
const int x1 = (int)(qs[j] >> 4) | (int)(((h >> (j + 16)) & 1u) << 4);
out[j] = (float)x0 * d + m;
out[j + 16] = (float)x1 * d + m;
}
}
// ---- IQ4_NL: 32 elements from an 18-byte block. Non-linear 4-bit codebook, NOT a linear grid, so
// the table must be exact. Copied verbatim from ggml-common.h `kvalues_iq4nl` at 3cf03257:
// -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113
// Layout matches dequantize_row_iq4_nl (ggml-quants.c): low nibble is element j, high nibble j+16.
static const int8_t kvalues_iq4nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10,
1, 13, 25, 38, 53, 69, 89, 113};
// the 4-bit non-linear codebook of IQ4_NL / IQ4_XS (FORMAT-SPEC section 14)
static const int8_t kvalues_iq4nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113};
inline void dequantize_iq4_nl(const uint8_t* block, float* out) {
const float d = fp16_to_fp32(read_u16(block));
const uint8_t* qs = block + 2;
for (int j = 0; j < 16; ++j) {
out[j] = d * (float)kvalues_iq4nl[qs[j] & 0x0F];
out[j + 16] = d * (float)kvalues_iq4nl[qs[j] >> 4];
}
}
// ---- Q6_K: 256 elements from a 210-byte super-block, transcribed from dequantize_row_q6_K
// (ggml-quants.c at 3cf03257). Layout: ql[128] low nibbles, qh[64] high 2 bits, scales[16] int8,
// fp16 d LAST. Processed in two 128-element halves, each advancing ql by 64, qh by 32, sc by 8.
// The `sc` indices are is+{0,2,4,6} with is = l/16 - so each 32-element group draws from 8 of the 16
// scales, and the four output positions within a 32-group use different scales. Easy to get subtly
// wrong, which is why it is transcribed rather than recalled.
inline void dequantize_q6_K(const uint8_t* block, float* out) {
const uint8_t* ql = block; // 128 bytes
const uint8_t* qh = block + 128; // 64
const int8_t* sc = (const int8_t*)(block + 192); // 16
const float d = fp16_to_fp32(read_u16(block + 208));
float* y = out;
for (int n = 0; n < 256; n += 128) {
for (int l = 0; l < 32; ++l) {
const int is = l / 16;
const int q1 = (int)((ql[l + 0] & 0x0F) | (((qh[l] >> 0) & 3) << 4)) - 32;
const int q2 = (int)((ql[l + 32] & 0x0F) | (((qh[l] >> 2) & 3) << 4)) - 32;
const int q3 = (int)((ql[l + 0] >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32;
const int q4 = (int)((ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32;
y[l + 0] = d * (float)sc[is + 0] * (float)q1;
y[l + 32] = d * (float)sc[is + 2] * (float)q2;
y[l + 64] = d * (float)sc[is + 4] * (float)q3;
y[l + 96] = d * (float)sc[is + 6] * (float)q4;
}
y += 128;
ql += 64;
qh += 32;
sc += 8;
}
}
// ---- Q4_K: 256 elements from a 144-byte super-block. Layout is `fp16 d`, `fp16 dmin` (so the FIRST
// four bytes are the scale pair, unlike Q6_K where d is last), `scales[12]`, `qs[128]`.
// Both functions transcribed from ggml-quants.c at 3cf03257. The 6-bit scale/min unpacking in
// get_scale_min_k4 is the part that is impossible to recall reliably: the low 4 bits of the second
// half come from q[j+4], and the high 2 bits from the low halves' top bits (q[j-4] and q[j]).
// The 6-bit scale d and 6-bit minimum m of sub-block j (0..7) of a Q4_K / Q5_K block; q = the block's
// scales[12] bytes (FORMAT-SPEC section 3).
static inline void get_scale_min_k4(int j, const uint8_t* q, uint8_t& d, uint8_t& m) {
if (j < 4) {
d = q[j] & 63;
m = q[j + 4] & 63;
} else {
d = (q[j + 4] & 0x0F) | ((q[j - 4] >> 6) << 4);
m = (q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4);
d = (uint8_t)((q[j + 4] & 15) | ((q[j - 4] >> 6) << 4));
m = (uint8_t)((q[j + 4] >> 4) | ((q[j] >> 6) << 4));
}
}
inline void dequantize_q4_K(const uint8_t* block, float* out) {
const float d = fp16_to_fp32(read_u16(block)); // d
const float mn = fp16_to_fp32(read_u16(block + 2)); // dmin
const uint8_t* scales = block + 4; // 12 bytes
const uint8_t* q = block + 16; // 128 bytes
float* y = out;
int is = 0;
for (int j = 0; j < 256; j += 64) {
uint8_t sc, m;
get_scale_min_k4(is + 0, scales, sc, m);
const float d1 = d * (float)sc, m1 = mn * (float)m;
get_scale_min_k4(is + 1, scales, sc, m);
const float d2 = d * (float)sc, m2 = mn * (float)m;
for (int l = 0; l < 32; ++l) *y++ = d1 * (float)(q[l] & 0x0F) - m1;
for (int l = 0; l < 32; ++l) *y++ = d2 * (float)(q[l] >> 4) - m2;
q += 32;
is += 2;
// ---- 32 / 64-element formats (FORMAT-SPEC sections 2 and 12) ---------------------------------------------
// Q2_0: 64 elements, 18 bytes: d (half), qs[16] with four 2-bit codes per byte, first code in the low bits.
// A code c stands for c - 1.
inline void dequantize_q2_0(const uint8_t* b, float* out) {
const float d = fp16_to_fp32(read_u16(b));
for (int j = 0; j < 64; ++j) {
const int c = (b[2 + (j >> 2)] >> (2 * (j & 3))) & 3;
out[j] = (float)(c - 1) * d;
}
}
// ---- Q5_K: 256 elements from a 176-byte super-block: `fp16 d`, `fp16 dmin`, `scales[12]`,
// `qh[32]`, `qs[128]`. Same shape as Q4_K plus the 5th bit plane. Transcribed from
// dequantize_row_q5_K (ggml-quants.c, 3cf03257). The 5th bits are selected by a mask that SHIFTS LEFT
// BY 2 each 64-element group (u1 = 1,4,16,64; u2 = 2,8,32,128) - a recalled version would very likely
// have used a fixed mask or a shift by 1.
inline void dequantize_q5_K(const uint8_t* block, float* out) {
const float d = fp16_to_fp32(read_u16(block));
const float mn = fp16_to_fp32(read_u16(block + 2));
const uint8_t* scales = block + 4; // 12
const uint8_t* qh = block + 16; // 32
const uint8_t* ql = block + 48; // 128
float* y = out;
int is = 0;
uint8_t u1 = 1, u2 = 2;
for (int j = 0; j < 256; j += 64) {
uint8_t sc, m;
get_scale_min_k4(is + 0, scales, sc, m);
const float d1 = d * (float)sc, m1 = mn * (float)m;
get_scale_min_k4(is + 1, scales, sc, m);
const float d2 = d * (float)sc, m2 = mn * (float)m;
for (int l = 0; l < 32; ++l) *y++ = d1 * (float)((ql[l] & 0x0F) + ((qh[l] & u1) ? 16 : 0)) - m1;
for (int l = 0; l < 32; ++l) *y++ = d2 * (float)((ql[l] >> 4) + ((qh[l] & u2) ? 16 : 0)) - m2;
ql += 32;
is += 2;
u1 = (uint8_t)(u1 << 2);
u2 = (uint8_t)(u2 << 2);
// Q8_0: 32 elements, 34 bytes: d (half), qs[32] int8.
inline void dequantize_q8_0(const uint8_t* b, float* out) {
const float d = fp16_to_fp32(read_u16(b));
for (int j = 0; j < 32; ++j) out[j] = (float)(int8_t)b[2 + j] * d;
}
// Q4_0: 32 elements, 18 bytes: d, qs[16]; low nibble of qs[j] is element j, high nibble element j + 16.
inline void dequantize_q4_0(const uint8_t* b, float* out) {
const float d = fp16_to_fp32(read_u16(b));
for (int j = 0; j < 16; ++j) {
out[j] = (float)((b[2 + j] & 15) - 8) * d;
out[j + 16] = (float)((b[2 + j] >> 4) - 8) * d;
}
}
// ---- Q3_K: 256 elements from a 110-byte super-block: `hmask[32]`, `qs[64]`, `scales[12]`, `fp16 d`
// LAST. Transcribed from dequantize_row_q3_K (ggml-quants.c, 3cf03257). This type has NO `dmin` - its
// scales are SIGNED 6-bit with a `- 32` bias - so it does not follow the Q4_K/Q5_K pattern at all.
// Two details that cannot be recalled:
// * the 12 scale bytes are bit-repacked through three 32-bit masks before use (kmask1/2 below),
// because 16 six-bit scales do not fit in 12 bytes linearly;
// * the low 2 bits are offset by -4 when the high bit is CLEAR, i.e. the correction is NEGATIVE.
inline void dequantize_q3_K(const uint8_t* block, float* out) {
const uint8_t* hm = block; // 32
const uint8_t* q = block + 32; // 64
const float d_all = fp16_to_fp32(read_u16(block + 108));
const uint32_t kmask1 = 0x03030303u, kmask2 = 0x0f0f0f0fu;
uint32_t aux[4] = {0, 0, 0, 0};
std::memcpy(aux, block + 96, 12);
const uint32_t tmp = aux[2];
aux[2] = ((aux[0] >> 4) & kmask2) | (((tmp >> 4) & kmask1) << 4);
aux[3] = ((aux[1] >> 4) & kmask2) | (((tmp >> 6) & kmask1) << 4);
aux[0] = (aux[0] & kmask2) | (((tmp >> 0) & kmask1) << 4);
aux[1] = (aux[1] & kmask2) | (((tmp >> 2) & kmask1) << 4);
const int8_t* scales = (const int8_t*)aux;
// Q5_0: 32 elements, 22 bytes: d, qh[4] (32 fifth bits, bit i for element i), qs[16].
inline void dequantize_q5_0(const uint8_t* b, float* out) {
const float d = fp16_to_fp32(read_u16(b));
const uint32_t qh = dq_detail::read_u32(b + 2);
for (int j = 0; j < 16; ++j) {
const int lo = (b[6 + j] & 15) | (int)(((qh >> j) & 1u) << 4);
const int hi = (b[6 + j] >> 4) | (int)(((qh >> (j + 16)) & 1u) << 4);
out[j] = (float)(lo - 16) * d;
out[j + 16] = (float)(hi - 16) * d;
}
}
float* y = out;
int is = 0;
uint8_t m = 1; // hoisted: ggml declares this BEFORE the n loop, so it does not reset between halves
for (int n = 0; n < 256; n += 128) {
int shift = 0;
for (int j = 0; j < 4; ++j) {
float dl = d_all * (float)(scales[is++] - 32);
for (int l = 0; l < 16; ++l)
*y++ = dl * (float)((int8_t)((q[l + 0] >> shift) & 3) - ((hm[l + 0] & m) ? 0 : 4));
dl = d_all * (float)(scales[is++] - 32);
for (int l = 0; l < 16; ++l)
*y++ = dl * (float)((int8_t)((q[l + 16] >> shift) & 3) - ((hm[l + 16] & m) ? 0 : 4));
shift += 2;
m = (uint8_t)(m << 1);
// Q5_1: 32 elements, 24 bytes: d, m (halves), qh[4], qs[16]. y = q5 * d + m (product first, then the sum:
// the two roundings must stay separate).
inline void dequantize_q5_1(const uint8_t* b, float* out) {
const float d = fp16_to_fp32(read_u16(b));
const float m = fp16_to_fp32(read_u16(b + 2));
const uint32_t qh = dq_detail::read_u32(b + 4);
for (int j = 0; j < 16; ++j) {
const int lo = (b[8 + j] & 15) | (int)(((qh >> j) & 1u) << 4);
const int hi = (b[8 + j] >> 4) | (int)(((qh >> (j + 16)) & 1u) << 4);
const float pl = (float)lo * d;
const float ph = (float)hi * d;
out[j] = pl + m;
out[j + 16] = ph + m;
}
}
// IQ4_NL: 32 elements, 18 bytes: d, qs[16]; y = d * kvalues_iq4nl[nibble].
inline void dequantize_iq4_nl(const uint8_t* b, float* out) {
const float d = fp16_to_fp32(read_u16(b));
for (int j = 0; j < 16; ++j) {
out[j] = d * (float)kvalues_iq4nl[b[2 + j] & 15];
out[j + 16] = d * (float)kvalues_iq4nl[b[2 + j] >> 4];
}
}
// ---- 256-element K-quants (FORMAT-SPEC sections 3, 4, 9, 13, 14) -----------------------------------------
// Q6_K: 210 bytes: ql[128], qh[64], scales[16] int8, d (half). y = (d * scale) * q, q = (low4 + 16*high2) - 32.
inline void dequantize_q6_K(const uint8_t* b, float* out) {
const uint8_t* ql = b;
const uint8_t* qh = b + 128;
const int8_t* sc = (const int8_t*)(b + 192);
const float d = fp16_to_fp32(read_u16(b + 208));
for (int n = 0; n < 2; ++n) {
for (int l = 0; l < 32; ++l) {
const uint8_t h = qh[32 * n + l];
const uint8_t a = ql[64 * n + l];
const uint8_t c = ql[64 * n + 32 + l];
const int q0 = ((a & 15) | (((h >> 0) & 3) << 4)) - 32;
const int q1 = ((c & 15) | (((h >> 2) & 3) << 4)) - 32;
const int q2 = ((a >> 4) | (((h >> 4) & 3) << 4)) - 32;
const int q3 = ((c >> 4) | (((h >> 6) & 3) << 4)) - 32;
const int s = 8 * n + (l >> 4);
float* o = out + 128 * n + l;
o[0] = (d * (float)sc[s + 0]) * (float)q0;
o[32] = (d * (float)sc[s + 2]) * (float)q1;
o[64] = (d * (float)sc[s + 4]) * (float)q2;
o[96] = (d * (float)sc[s + 6]) * (float)q3;
}
q += 32;
}
}
// ---- IQ4_XS: 256 elements from a 136-byte super-block: `fp16 d`, `uint16 scales_h`, `scales_l[4]`,
// `qs[128]`. Transcribed from dequantize_row_iq4_xs (ggml-quants.c, 3cf03257). Reuses the IQ4_NL
// codebook. Eight 32-element groups; each group's scale is 6 bits assembled from the LOW nibble of
// `scales_l[ib/2]` (selected by ib%2) and TWO bits of `scales_h` at shift 2*ib - so the high bits come
// from a 16-bit field indexed by group, not from a byte array. Then `- 32`, as in Q3_K.
inline void dequantize_iq4_xs(const uint8_t* block, float* out) {
const float d = fp16_to_fp32(read_u16(block));
const uint16_t scales_h = read_u16(block + 2);
const uint8_t* scales_l = block + 4; // 4
const uint8_t* qs = block + 8; // 128
float* y = out;
// Q4_K: 144 bytes: d, dmin, scales[12], qs[128]. y = ((d * sc) * q) - (dmin * m).
inline void dequantize_q4_K(const uint8_t* b, float* out) {
const float d = fp16_to_fp32(read_u16(b));
const float dmin = fp16_to_fp32(read_u16(b + 2));
const uint8_t* scales = b + 4;
const uint8_t* qs = b + 16;
for (int g = 0; g < 4; ++g) {
uint8_t sc0, m0, sc1, m1;
get_scale_min_k4(2 * g, scales, sc0, m0);
get_scale_min_k4(2 * g + 1, scales, sc1, m1);
const float d0 = d * (float)sc0, n0 = dmin * (float)m0;
const float d1 = d * (float)sc1, n1 = dmin * (float)m1;
for (int l = 0; l < 32; ++l) {
const uint8_t byte = qs[32 * g + l];
const float lo = d0 * (float)(byte & 15);
const float hi = d1 * (float)(byte >> 4);
out[64 * g + l] = lo - n0;
out[64 * g + 32 + l] = hi - n1;
}
}
}
// Q5_K: 176 bytes: d, dmin, scales[12], qh[32], qs[128]. q = nibble + 16 * (bit j of qh[l]).
inline void dequantize_q5_K(const uint8_t* b, float* out) {
const float d = fp16_to_fp32(read_u16(b));
const float dmin = fp16_to_fp32(read_u16(b + 2));
const uint8_t* scales = b + 4;
const uint8_t* qh = b + 16;
const uint8_t* qs = b + 48;
for (int g = 0; g < 4; ++g) {
uint8_t sc0, m0, sc1, m1;
get_scale_min_k4(2 * g, scales, sc0, m0);
get_scale_min_k4(2 * g + 1, scales, sc1, m1);
const float d0 = d * (float)sc0, n0 = dmin * (float)m0;
const float d1 = d * (float)sc1, n1 = dmin * (float)m1;
for (int l = 0; l < 32; ++l) {
const uint8_t byte = qs[32 * g + l];
const int q0 = (byte & 15) | (((qh[l] >> (2 * g)) & 1) << 4);
const int q1 = (byte >> 4) | (((qh[l] >> (2 * g + 1)) & 1) << 4);
const float lo = d0 * (float)q0;
const float hi = d1 * (float)q1;
out[64 * g + l] = lo - n0;
out[64 * g + 32 + l] = hi - n1;
}
}
}
// Q3_K: 110 bytes: hmask[32], qs[64], scales[12], d (half, may be negative).
// y = (d * (u_t - 32)) * q, q = lo if the element's hmask bit is set else lo - 4.
inline void dequantize_q3_K(const uint8_t* b, float* out) {
const uint8_t* hmask = b;
const uint8_t* qs = b + 32;
const uint8_t* sc = b + 96;
const float d = fp16_to_fp32(read_u16(b + 108));
int u[16];
for (int t = 0; t < 16; ++t) {
const int low4 = (t < 8) ? (sc[t] & 15) : (sc[t - 8] >> 4);
const int high2 = (sc[8 + (t & 3)] >> (2 * (t >> 2))) & 3;
u[t] = low4 + 16 * high2;
}
for (int h = 0; h < 2; ++h) {
for (int s = 0; s < 4; ++s) {
for (int l = 0; l < 32; ++l) {
const int e = 128 * h + 32 * s + l;
const int lo = (qs[32 * h + l] >> (2 * s)) & 3;
const int hb = (hmask[l] >> (4 * h + s)) & 1;
const int q = hb ? lo : lo - 4;
const float dl = d * (float)(u[e >> 4] - 32);
out[e] = dl * (float)q;
}
}
}
}
// IQ4_XS: 136 bytes: d, scales_h (u16), scales_l[4], qs[128]. y = (d * (ls - 32)) * kvalue.
inline void dequantize_iq4_xs(const uint8_t* b, float* out) {
const float d = fp16_to_fp32(read_u16(b));
const uint16_t sh = read_u16(b + 2);
const uint8_t* sl = b + 4;
const uint8_t* qs = b + 8;
for (int ib = 0; ib < 8; ++ib) {
const int ls = ((scales_l[ib / 2] >> (4 * (ib % 2))) & 0x0F) | (((scales_h >> (2 * ib)) & 3) << 4);
const int ls = ((sl[ib >> 1] >> (4 * (ib & 1))) & 15) | (((sh >> (2 * ib)) & 3) << 4);
const float dl = d * (float)(ls - 32);
for (int j = 0; j < 16; ++j) {
y[j + 0] = dl * (float)kvalues_iq4nl[qs[j] & 0x0F];
y[j + 16] = dl * (float)kvalues_iq4nl[qs[j] >> 4];
const uint8_t q = qs[16 * ib + j];
out[32 * ib + j] = dl * (float)kvalues_iq4nl[q & 15];
out[32 * ib + 16 + j] = dl * (float)kvalues_iq4nl[q >> 4];
}
y += 32;
qs += 16;
}
}
// ---- element types
inline void dequantize_f32(const uint8_t* p, float* out, int n) {
std::memcpy(out, p, (size_t)n * 4);
}
// ---- whole-array copies / conversions ---------------------------------------------------------------------
inline void dequantize_f32(const uint8_t* p, float* out, int n) { std::memcpy(out, p, (size_t)n * sizeof(float)); }
inline void dequantize_f16(const uint8_t* p, float* out, int n) {
for (int i = 0; i < n; ++i) out[i] = fp16_to_fp32(read_u16(p + 2 * i));
}
inline void dequantize_bf16(const uint8_t* p, float* out, int n) {
for (int i = 0; i < n; ++i) out[i] = bf16_to_fp32(read_u16(p + 2 * i));
for (int i = 0; i < n; ++i) out[i] = fp16_to_fp32(read_u16(p + 2 * (size_t)i));
}
} // namespace strata
inline void dequantize_bf16(const uint8_t* p, float* out, int n) {
for (int i = 0; i < n; ++i) out[i] = bf16_to_fp32(read_u16(p + 2 * (size_t)i));
}
} // namespace strata
#endif
@@ -0,0 +1,35 @@
// dp4a for RDNA1 (gfx1010 / gfx1012): the signed four-lane byte dot product, c + sum_k (signed byte k of a) * (signed byte k of b),
// accumulated modulo 2^32, with the same semantics as STRATA_DP4A in kernels/dp4a.hpp. These chips have no dot instruction.
//
// The body is plain integer C++ (plus empty asm statements as fusion barriers). The AMDGPU back end turns the byte extractions into
// sub-dword (SDWA) operand selects of the 24-bit integer multiply and adds the products with three-input adds; a and b may be the
// same register and c is only an input. No dot instruction is used. The function exists only when compiling for gfx1010 or gfx1012.
//
// intrinsics.hpp calls this from its gfx1010 / gfx1012 branch.
#pragma once
#include <cstdint>
#if defined(__gfx1010__) || defined(__gfx1012__)
namespace strata::hip_compat {
__device__ __forceinline__ int dp4a_rdna1(int a, int b, int c) {
const uint32_t ua = (uint32_t)a, ub = (uint32_t)b;
int p0 = (int)(int8_t)(ua) * (int)(int8_t)(ub);
int p1 = (int)(int8_t)(ua >> 8) * (int)(int8_t)(ub >> 8);
int p2 = (int)(int8_t)(ua >> 16) * (int)(int8_t)(ub >> 16);
int p3 = (int)(int8_t)(ua >> 24) * (int)(int8_t)(ub >> 24);
// An empty asm on each product keeps the back end from fusing the four products into a dot instruction (gfx1012 would
// otherwise get one): the byte multiplies stay SDWA multiplies and the sum stays three-input adds.
asm("" : "+v"(p0));
asm("" : "+v"(p1));
asm("" : "+v"(p2));
asm("" : "+v"(p3));
// unsigned adds keep the wrap-around defined
return (int)((uint32_t)c + (uint32_t)p0 + (uint32_t)p1 + (uint32_t)p2 + (uint32_t)p3);
}
} // namespace strata::hip_compat
#endif
@@ -7,6 +7,8 @@
#include <cstdint>
#include "dp4a_rdna1.hpp"
namespace strata::hip_compat {
__device__ __forceinline__ int signed_byte(uint32_t word, int lane) {
@@ -33,18 +35,8 @@ __device__ __forceinline__ int dp4a(int a, int b, int c) {
// operands directly, avoiding separate shift/mask/sign-extension work. gfx1010 takes this since #4855 (Keoian; no card here
// runs it): the community switch, cmake -DSTRATA_AMD_COMMUNITY_TUNING=OFF, defines STRATA_AMD_COMMUNITY_DOT_OFF and
// gfx1010 gets the portable loop again (strata/core/amd_community.hpp).
// Adapted from pinned llama.cpp ggml-cuda/common.cuh (MIT; see
// third_party/ggml/LICENSE), same modulo-2^32 accumulation contract.
int lo, hi;
asm("v_mul_i32_i24 %1, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0 src1_sel:BYTE_0\n"
"v_mul_i32_i24 %2, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1 src1_sel:BYTE_1\n"
"v_add3_u32 %0, %1, %2, %0\n"
"v_mul_i32_i24 %1, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_2 src1_sel:BYTE_2\n"
"v_mul_i32_i24 %2, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_3 src1_sel:BYTE_3\n"
"v_add3_u32 %0, %1, %2, %0\n"
// c changes before the high-byte reads; it must not alias a or b.
: "+&v"(c), "=&v"(lo), "=&v"(hi) : "v"(a), "v"(b));
return c;
// same modulo-2^32 accumulation contract as the other branches (hip_compat/dp4a_rdna1.hpp, no dot instruction).
return strata::hip_compat::dp4a_rdna1(a, b, c);
#else
const uint32_t ua = static_cast<uint32_t>(a);
const uint32_t ub = static_cast<uint32_t>(b);
+23 -35
View File
@@ -1,55 +1,43 @@
// include/strata/kernels/dp4a.hpp - the two instructions the kernels use that Pascal (sm_60) does not have.
// STRATA_DP4A(a, b, c): the signed four-lane byte dot product with an int32 accumulator, for device code, plus strata_spin_pause().
//
// The engine is written for compute capability 7.5 and newer and refuses older cards at CMake configure time
// (a Pascal build passes -DSTRATA_EXPERIMENTAL_SM60=ON). A GP100-class card is compute capability 6.0, which is
// missing exactly two things the i-quant kernels rely on:
// STRATA_DP4A(a, b, c) == c + sum over k = 0..3 of (signed byte k of a) * (signed byte k of b), modulo 2^32.
//
// * `__dp4a`, a byte-wise dot product, available from 6.1 (Pascal GP10x/GV11x). The reference for its
// fallback is llama.cpp's own (`ggml/src/ggml-cuda/common.cuh`), since the kernels in this directory are
// transcribed from llama.cpp's vecdotq.cuh and that wrapper's operands are the same sites: it reinterprets
// the operands as SIGNED bytes and accumulates in int32, which is what `__dp4a` does for these calls. The
// fallback below computes exactly that with four PTX `vmad` byte-select instructions, so it is bit-exact
// rather than merely close (tools/sm60_dp4a_check.cu checks it against the byte-wise form).
// * `__nanosleep`, available from 7.0 (Volta). It only paces single-thread doorbell waits, so a loop that
// spins without it is correct, merely busier.
// Where the hardware has the instruction (CUDA compute capability >= 6.1, and HIP through hip_compat) it is __dp4a. Below 6.1 the
// same value is formed in registers: each operand byte is sign-extended, multiplied, and the four products are added to c. The
// operands are plain values, so a and b may be the same register and c may share a register with either of them.
//
// Both are compile-time selections on `__CUDA_ARCH__`, so one source tree builds for Pascal and for RTX
// 20/30/40/50 without a #define at the call sites. A HIP build never takes either fallback: `__CUDA_ARCH__` is
// undefined there, so `STRATA_DP4A` is `__dp4a` (which `hip_compat/intrinsics.hpp` provides) and the pause is
// HIP's own `__nanosleep`.
#pragma once
#include <cstdint>
#if defined(STRATA_HIP_GFX906)
#include <cuda_runtime.h> // gfx906: the compat layer (__forceinline__, __nanosleep, __dp4a)
#include <cuda_runtime.h> // the HIP compat layer: __dp4a, __nanosleep
#endif
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 610
#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 610)
// Software form for sm_60 and older: four chained PTX `vmad` instructions, one per byte lane. vmad with the .s32 types and a byte
// selector (.b0 .. .b3) sign-extends the selected bytes of both sources, multiplies, and adds the third operand modulo 2^32 (no .sat).
// Each lane is its own single-instruction asm statement, so an output register may share a register with any input without harm.
__device__ __forceinline__ int strata_dp4a(const int a, const int b, const int c) {
// PTX vmad with byte selectors: compiles to four VMAD.S8.S8 (cuobjdump -sass), no byte extraction.
// Bit-exact with the byte-wise form it replaces: 1.07e9 cases (edge bytes, every per-lane byte pair, random),
// 0 mismatches, ~2.2x faster in isolation on a Tesla P100 (tools/sm60_dp4a_check.cu).
int r = c;
asm("vmad.s32.s32.s32 %0, %1.b0, %2.b0, %0;\n\t"
"vmad.s32.s32.s32 %0, %1.b1, %2.b1, %0;\n\t"
"vmad.s32.s32.s32 %0, %1.b2, %2.b2, %0;\n\t"
"vmad.s32.s32.s32 %0, %1.b3, %2.b3, %0;"
// The first instruction writes r before the remaining instructions
// have read a/b. Equal-valued operands must not share its register.
: "+&r"(r) : "r"(a), "r"(b));
int r;
asm("vmad.s32.s32.s32 %0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(c));
asm("vmad.s32.s32.s32 %0, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r));
asm("vmad.s32.s32.s32 %0, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r));
asm("vmad.s32.s32.s32 %0, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r));
return r;
}
#define STRATA_DP4A(a, b, c) strata_dp4a((a), (b), (c))
#else
#define STRATA_DP4A(a, b, c) __dp4a((a), (b), (c))
#endif
/// Yield the thread while a doorbell flag is being polled. The length of the pause is a backoff hint, not a
/// contract, and only pre-Volta CUDA has no `__nanosleep` at all.
// Yield the thread while a flag is polled. Below compute capability 7.0 there is no sleep instruction and a plain spin is correct.
__device__ __forceinline__ void strata_spin_pause() {
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 700
// sm_6x: the loop spins. Every call site is a single-thread doorbell wait, so nothing else is delayed.
#else
__nanosleep(100);
#if !(defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 700))
__nanosleep(100); // every target but CUDA below 7.0 (HIP's compat layer has __nanosleep too)
#endif
}
+26 -79
View File
@@ -2,7 +2,7 @@
//
// WHAT IT IS. The artifact's RoPE is trained over `orig_ctx` positions (the artifact ships no
// `rope.scaling` keys, so this is a pure runtime feature). Scaling re-uses positions past that by
// rescaling the rotation angles. Three types, the llama.cpp set:
// rescaling the rotation angles. Three types:
//
// none freq_scale 1, no correction - today's behaviour, exactly
// linear Position Interpolation: angles shrunk by 1/factor - every position fits again, all
@@ -11,13 +11,10 @@
// pairs are interpolated, and the pairs in between blend - plus a magnitude correction
// `mscale` that keeps the attention temperature where training put it
//
// THE MATH IS GGML'S, TRANSCRIBED, NOT RE-DERIVED. `third_party/llama.cpp` is vendored and is the
// numerical contract (the same standing `native_rope.cu` declares): ramp, correction dims, the
// interpolation mix and the mscale formula below are line-for-line that source, with the MIT
// attribution at each helper. The one deliberate deviation is bookkeeping: ggml's device kernel
// speaks in even dim indices (`i0`) and halves them inside the ramp, while every Strata rope kernel
// speaks in PAIR indices - so `rope_yarn_ramp` here takes the pair index and compares it against
// `corr_dims` directly. Same numbers, one less division per call site.
// THE MATH is the YaRN paper's (Peng et al., arXiv 2309.00071), written once in rope_yarn_math.hpp (namespace strata::kernels::yarn): the
// correction window, the ramp, the interpolation mix and the magnitude correction. This header keeps the configuration, its validity rule and
// the process constant, and calls those functions. Every Strata rope kernel speaks in PAIR indices, so the ramp takes the pair index and
// compares it against the correction window directly.
//
// HOW IT REACHES THE ROPE. Two forms, one config:
//
@@ -37,16 +34,11 @@
#include <cmath>
#if defined(__CUDACC__) || defined(__HIPCC__)
#define STRATA_ROPE_SCALING_HD __host__ __device__
#else
#define STRATA_ROPE_SCALING_HD
#endif
#include "strata/kernels/rope_scaling_type.hpp" // RopeScalingType, STRATA_ROPE_SCALING_HD
#include "strata/kernels/rope_yarn_math.hpp"
namespace strata::kernels {
enum class RopeScalingType { None, Linear, YaRN };
/// The float32 constants the ANALYTIC rotation kernels take (`rope_scaled_angle`'s arguments). The defaults are
/// the identity: freq_scale 1, no correction, magnitude 1 - with them the helper computes `cosf(theta) * 1.0f`
/// on `1.0f * theta`, which is exactly today's unscaled `cosf(theta)` bit for bit.
@@ -67,42 +59,28 @@ struct RopeScaling {
RopeScalingType type = RopeScalingType::None;
double freq_base = 1e7; ///< `rope.freq_base` (the value pinned by `qsa_freq_base()`)
double factor = 1.0; ///< `--rope-scale`: how far past the trained context the run goes
double freq_scale_in = 0; ///< `--rope-freq-scale`: the raw ggml knob; 0 = 1/factor
double freq_scale_in = 0; ///< `--rope-freq-scale`: the raw knob; 0 = 1/factor
double orig_ctx = 262144; ///< `--yarn-orig-ctx`: the context the model was trained over
double ext_factor = 0; ///< `--yarn-ext-factor`: correction depth; 0 = off, 1 = full YaRN
double attn_factor = 1.0; ///< `--yarn-attn-factor`: extra magnitude scale (ggml's attn_factor)
double attn_factor = 1.0; ///< `--yarn-attn-factor`: extra magnitude scale
double beta_fast = 32.0; ///< `--yarn-beta-fast`
double beta_slow = 1.0; ///< `--yarn-beta-slow`
/// The angle shrink. ggml's `freq_scale`: 1 means "the trained angles", 1/factor squeezes
/// `factor` positions into the trained range.
double freq_scale() const {
if (type == RopeScalingType::None) return 1.0;
return freq_scale_in > 0 ? freq_scale_in : 1.0 / factor;
}
/// The angle shrink: 1 means "the trained angles", 1/factor squeezes `factor` positions into the trained range.
double freq_scale() const { return yarn::freq_scale(type, freq_scale_in, factor); }
/// The magnitude correction. ggml's `rope_yarn` multiplies cos and sin by this; the log term
/// rides on `ext_factor != 0` (not on the type), exactly as that source has it. With the
/// The magnitude correction cos and sin are multiplied by; the log term rides on `ext_factor != 0` (not on the type). With the
/// default knobs YaRN factor F gives `1 + 0.1*ln(F)` - YaRN's temperature correction.
double mscale() const {
if (ext_factor == 0) return attn_factor;
return attn_factor * (1.0 + 0.1 * std::log(1.0 / freq_scale()));
}
double mscale() const { return yarn::mscale(ext_factor, attn_factor, freq_scale()); }
/// The correction window, in PAIR indices: below `out[0]` pairs extrapolate (keep the trained
/// angles), above `out[1]` they interpolate, in between they blend. Transcribed from ggml's
/// `ggml_rope_yarn_corr_dims` (see the derivation comment at `rope_yarn_corr_dim` below).
void corr_dims(int n_rot, double out[2]) const {
const double start = std::floor(rope_yarn_corr_dim(n_rot, orig_ctx, beta_fast, freq_base));
const double end = std::ceil(rope_yarn_corr_dim(n_rot, orig_ctx, beta_slow, freq_base));
out[0] = start < 0 ? 0 : start;
out[1] = end > (double) (n_rot - 1) ? (double) (n_rot - 1) : end;
}
/// angles), above `out[1]` they interpolate, in between they blend.
void corr_dims(int n_rot, double out[2]) const { yarn::corr_dims(n_rot, orig_ctx, beta_fast, beta_slow, freq_base, out); }
/// The analytic kernels' constants. `none` returns the identity constants WHATEVER the other knobs hold -
/// the table builder ignores them for `none` too, so the two rotation forms cannot disagree there, and an
/// unscaled run computes exactly what it computed before scaling existed. Linear/YaRN: ggml's `rope_yarn`
/// arguments (`attn_factor` is the raw knob; the helper applies the log term when correcting).
/// unscaled run computes exactly what it computed before scaling existed. Linear/YaRN: the
/// arguments of the YaRN rotation (`attn_factor` is the raw knob; `rope_scaled_angle` applies the log term when correcting).
RopeKernelArgs kernel_args(int n_rot) const {
RopeKernelArgs a;
if (type == RopeScalingType::None) return a;
@@ -115,50 +93,19 @@ struct RopeScaling {
a.attn_factor = (float) attn_factor;
return a;
}
private:
/// ggml/src/ggml.c: "Apparently solving `n_rot = 2pi * x * base^((2 * max_pos_emb) / n_dims)`
/// for x, we get `corr_dim(n_rot) = n_dims * log(max_pos_emb / (n_rot * 2pi)) / (2 * log(base))`".
/// float64 rather than ggml's float32: the table path computes in float64 and is held to a
/// bit-exact float64 reference, so its inputs are float64 too.
static double rope_yarn_corr_dim(int n_dims, double n_ctx_orig, double n_rot, double base) {
return (double) n_dims * std::log(n_ctx_orig / (n_rot * 2.0 * 3.14159265358979323846)) /
(2.0 * std::log(base));
}
};
/// The ramp between extrapolation (1) and interpolation (0).
///
/// ggml/src/ggml-cuda/rope.cu `rope_yarn_ramp`: `1 - clamp(y, 0, 1)` with
/// `y = (i0 / 2 - low) / max(0.001, high - low)`. ggml passes the even dim index `i0`; this takes
/// the pair index (ggml's `i0/2`) so Strata's pair-indexed kernels don't re-derive the mapping. The
/// 0.001 floor on the denominator is ggml's, kept verbatim: `corr_dims` can produce low == high.
STRATA_ROPE_SCALING_HD inline float rope_yarn_ramp(float low, float high, int pair) {
const float y = ((float) pair - low) / (high - low > 0.001f ? high - low : 0.001f);
const float clamped = y < 0.0f ? 0.0f : (y > 1.0f ? 1.0f : y);
return 1.0f - clamped;
}
/// The ramp between extrapolation (1) and interpolation (0), in float32: `1 - clamp((pair - low) / max(0.001, high - low), 0, 1)`. The 0.001
/// floor on the denominator is part of the contract: `corr_dims` can produce low == high.
STRATA_ROPE_SCALING_HD inline float rope_yarn_ramp(float low, float high, int pair) { return yarn::ramp(low, high, pair); }
/// The scaled angle for one pair, float32, the ANALYTIC paths' contract (pinned ggml arithmetic).
/// The scaled angle for one pair, float32, the ANALYTIC paths' contract.
///
/// Takes `theta_extrap` - the position times that pair's trained `inv_freq` - and returns the angle
/// to take cos/sin of, with ggml's mscale already folded in. `mscale_in` must be `attn_factor`
/// (ggml's kernels receive the raw knob and apply the log term here, where it is per-pair constant;
/// this helper keeps that shape so the native path reads against ggml line by line).
STRATA_ROPE_SCALING_HD inline void rope_scaled_angle(float theta_extrap, float freq_scale, float corr_low,
float corr_high, float ext_factor, float mscale_in,
int pair, float& cos_out, float& sin_out) {
// The interpolation, always applied; the correction mixed in on top (ggml-cuda/rope.cu rope_yarn).
float theta = freq_scale * theta_extrap;
float mscale = mscale_in;
if (ext_factor != 0.0f) {
const float ramp_mix = rope_yarn_ramp(corr_low, corr_high, pair) * ext_factor;
theta = theta * (1.0f - ramp_mix) + theta_extrap * ramp_mix;
// "Get n-d magnitude scaling corrected for interpolation" - the log term only when correcting.
mscale *= 1.0f + 0.1f * logf(1.0f / freq_scale);
}
cos_out = cosf(theta) * mscale;
sin_out = sinf(theta) * mscale;
/// Takes `theta_extrap` - the position times that pair's trained `inv_freq` - and returns cos and sin of the angle to rotate by, with the
/// magnitude correction folded in. `mscale_in` must be `attn_factor` (the log term is applied inside, where it is per-pair constant).
STRATA_ROPE_SCALING_HD inline void rope_scaled_angle(float theta_extrap, float freq_scale, float corr_low, float corr_high, float ext_factor,
float mscale_in, int pair, float& cos_out, float& sin_out) {
yarn::scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale_in, pair, cos_out, sin_out);
}
/// The ONE validity rule for a resolved configuration, shared by the engine's startup check and every rotation
@@ -0,0 +1,16 @@
// The rope scaling kind and the host/device qualifier of the rope-scaling maths (shared by rope_scaling.hpp and rope_yarn_math.hpp).
#pragma once
#ifndef STRATA_ROPE_SCALING_HD
#if defined(__CUDACC__) || defined(__HIPCC__)
#define STRATA_ROPE_SCALING_HD __host__ __device__
#else
#define STRATA_ROPE_SCALING_HD
#endif
#endif
namespace strata::kernels {
enum class RopeScalingType { None, Linear, YaRN };
} // namespace strata::kernels
@@ -0,0 +1,84 @@
// The maths of rope scaling (linear position interpolation and YaRN), written from the YaRN paper (Peng et al., arXiv 2309.00071)
// with Strata's pair-index convention.
//
// n_rot number of rotated dimensions; pair = 0 .. n_rot/2 - 1 the index of a rotated pair
// base the rope base theta; L (orig_ctx) the context length the model was trained for
//
// Everything here is header-only and usable from host and device code. The functions are small pieces on purpose: rope_scaling.hpp
// (struct RopeScaling, validation) calls them, and so do the kernels through scaled_angle / ramp.
#pragma once
#include <math.h>
// SYCL: the kernels use sycl::cos / sycl::sin / sycl::log (found by comparing with the previous SYCL kernel's outputs: those are the functions it calls;
// the plain C names compile to a different, less accurate sequence on the Intel GPU). Everywhere else the C float functions.
#if defined(SYCL_LANGUAGE_VERSION)
#include <sycl/sycl.hpp>
#define STRATA_YARN_COSF(x) sycl::cos((float)(x))
#define STRATA_YARN_SINF(x) sycl::sin((float)(x))
#define STRATA_YARN_LOGF(x) sycl::log((float)(x))
#else
#define STRATA_YARN_COSF(x) cosf(x)
#define STRATA_YARN_SINF(x) sinf(x)
#define STRATA_YARN_LOGF(x) logf(x)
#endif
#include "strata/kernels/rope_scaling_type.hpp"
namespace strata::kernels::yarn {
// Dimension index at which a rotation count `beta` is reached (float64): n_dims * ln(L / (beta * 2 pi)) / (2 ln base).
STRATA_ROPE_SCALING_HD inline double corr_dim(int n_dims, double n_ctx_orig, double n_rot, double base) {
const double two_pi = 2.0 * 3.14159265358979323846;
const double numerator = (double)n_dims * log(n_ctx_orig / (n_rot * two_pi));
return numerator / (2.0 * log(base));
}
// The factor the rotation angle is shrunk by: 1 for None, freq_scale_in when it is positive, else 1 / factor.
STRATA_ROPE_SCALING_HD inline double freq_scale(RopeScalingType type, double freq_scale_in, double factor) {
if (type == RopeScalingType::None) return 1.0;
return freq_scale_in > 0.0 ? freq_scale_in : 1.0 / factor;
}
// The attention magnitude scale: attn_factor when ext_factor is 0, else attn_factor * (1 + 0.1 ln(1 / freq_scale)).
STRATA_ROPE_SCALING_HD inline double mscale(double ext_factor, double attn_factor, double freq_scale) {
if (ext_factor == 0.0) return attn_factor;
return attn_factor * (1.0 + 0.1 * log(1.0 / freq_scale));
}
// Low and high correction dimensions, in pair units: low = max(0, floor(corr_dim(beta_fast))), high = min(n_rot - 1, ceil(corr_dim(beta_slow))).
STRATA_ROPE_SCALING_HD inline void corr_dims(int n_rot, double orig_ctx, double beta_fast, double beta_slow, double base, double out[2]) {
const double lo = floor(corr_dim(n_rot, orig_ctx, beta_fast, base));
const double hi = ceil(corr_dim(n_rot, orig_ctx, beta_slow, base));
out[0] = lo > 0.0 ? lo : 0.0;
const double top = (double)(n_rot - 1);
out[1] = hi < top ? hi : top;
}
// Ramp over the pair index: 1 (extrapolate) below `low` falling linearly to 0 (interpolate) at `high`. float32; the 0.001 floor on
// the span keeps the division finite when low == high.
STRATA_ROPE_SCALING_HD inline float ramp(float low, float high, int pair) {
const float span = high - low;
const float denom = span > 0.001f ? span : 0.001f;
const float y = ((float)pair - low) / denom;
const float c = y < 0.0f ? 0.0f : (y > 1.0f ? 1.0f : y);
return 1.0f - c;
}
// cos / sin of the angle of one pair, already multiplied by the magnitude scale. theta_extrap is the unscaled angle;
// mscale_in is the raw attn_factor. float32 throughout (cosf / sinf / logf of the device's libm).
STRATA_ROPE_SCALING_HD inline void scaled_angle(float theta_extrap, float freq_scale, float corr_low, float corr_high, float ext_factor,
float mscale_in, int pair, float& cos_out, float& sin_out) {
const float theta_interp = freq_scale * theta_extrap;
float theta = theta_interp;
float mag = mscale_in;
if (ext_factor != 0.0f) {
const float mix = ramp(corr_low, corr_high, pair) * ext_factor;
theta = theta_interp * (1.0f - mix) + theta_extrap * mix;
mag = mag * (1.0f + 0.1f * STRATA_YARN_LOGF(1.0f / freq_scale));
}
cos_out = STRATA_YARN_COSF(theta) * mag;
sin_out = STRATA_YARN_SINF(theta) * mag;
}
} // namespace strata::kernels::yarn
+3 -87
View File
@@ -5,6 +5,7 @@
// include/strata/kernels/cpu/expert.hpp. Read that header first; it says why each piece is shaped this way.
#include "strata/kernels/cpu/expert.hpp"
#include "strata/kernels/cpu/expert_layout.hpp"
#include "expert_oracle_parts.hpp" // quantize_oracle_q8_0, chunk_dot_oracle, row_dot_oracle (the oracle path's helpers)
#include <immintrin.h>
#if defined(_MSC_VER)
@@ -48,68 +49,7 @@ inline float h2f(const uint8_t* p) {
return out;
}
// The x86 Q8_0 quantization and generic Q2_0 dot sequences are adapted from llama.cpp
// 3cf03257f219afbe7334045ff7c6a06ac68c627d,
// ggml/src/ggml-cpu/arch/x86/quants.c: quantize_row_q8_0 and
// ggml/src/ggml-cpu/quants.c: ggml_vec_dot_q2_0_q8_0_generic.
//
// MIT License
// Copyright (c) 2023-2026 The ggml authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
void quantize_oracle_q8_0(const float* x, int n, ActQ& a) {
a.nchunks = n / QKA;
for (int chunk = 0; chunk < a.nchunks; ++chunk) {
const float* xb = x + chunk * QKA;
__m256 v0 = _mm256_loadu_ps(xb);
__m256 v1 = _mm256_loadu_ps(xb + 8);
__m256 v2 = _mm256_loadu_ps(xb + 16);
__m256 v3 = _mm256_loadu_ps(xb + 24);
const __m256 sign = _mm256_set1_ps(-0.0f);
__m256 maximum = _mm256_andnot_ps(sign, v0);
maximum = _mm256_max_ps(maximum, _mm256_andnot_ps(sign, v1));
maximum = _mm256_max_ps(maximum, _mm256_andnot_ps(sign, v2));
maximum = _mm256_max_ps(maximum, _mm256_andnot_ps(sign, v3));
__m128 max4 = _mm_max_ps(_mm256_extractf128_ps(maximum, 1), _mm256_castps256_ps128(maximum));
max4 = _mm_max_ps(max4, _mm_movehl_ps(max4, max4));
max4 = _mm_max_ss(max4, _mm_movehdup_ps(max4));
const float amax = _mm_cvtss_f32(max4);
const float d = amax / 127.0f;
const uint16_t half_d = (uint16_t) _mm_cvtsi128_si32(_mm_cvtps_ph(_mm_set_ss(d), 0));
const __m256 inverse = _mm256_set1_ps(amax != 0.0f ? 127.0f / amax : 0.0f);
v0 = _mm256_round_ps(_mm256_mul_ps(v0, inverse), _MM_FROUND_TO_NEAREST_INT);
v1 = _mm256_round_ps(_mm256_mul_ps(v1, inverse), _MM_FROUND_TO_NEAREST_INT);
v2 = _mm256_round_ps(_mm256_mul_ps(v2, inverse), _MM_FROUND_TO_NEAREST_INT);
v3 = _mm256_round_ps(_mm256_mul_ps(v3, inverse), _MM_FROUND_TO_NEAREST_INT);
__m256i i0 = _mm256_packs_epi32(_mm256_cvtps_epi32(v0), _mm256_cvtps_epi32(v1));
const __m256i i2 = _mm256_packs_epi32(_mm256_cvtps_epi32(v2), _mm256_cvtps_epi32(v3));
i0 = _mm256_packs_epi16(i0, i2);
i0 = _mm256_permutevar8x32_epi32(i0, _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7));
int8_t* q = a.q + chunk * QKA;
_mm256_storeu_si256((__m256i*) q, i0);
int32_t sum = 0;
for (int j = 0; j < QKA; ++j) sum += q[j];
a.scale[chunk] = h2f((const uint8_t*) &half_d);
a.sum[chunk] = sum;
a.hx[chunk] = a.scale[chunk] * float(sum);
}
}
// quantize_oracle_q8_0 (the oracle path's activation quantiser) is in expert_oracle_parts.hpp.
/// 2-bit unpack via VPMULTISHIFTQB.
///
@@ -285,31 +225,7 @@ inline float row_dot(const uint8_t* codes, const uint8_t* scales, const ActQ& a,
return hsum_ps(acc) - corr;
}
// VNNI's integer partial sums are exact. Remove the Q2_0 code offset BEFORE
// conversion to float, then follow the pinned generic CPU dot's two-chunk and
// per-64-block reduction. Its x86 type trait selects this generic reduction even
// in the AVX-512 oracle build. The legacy eight-lane FP32 reduction above has a
// different rounding order and remains the default.
inline int chunk_dot_oracle(const uint8_t* codes, const int8_t* q, int sum) {
const __m256i lanes = block_dot(codes, q);
const __m128i halves = _mm_add_epi32(_mm256_castsi256_si128(lanes), _mm256_extracti128_si256(lanes, 1));
const __m128i pairs = _mm_hadd_epi32(halves, halves);
return _mm_cvtsi128_si32(_mm_hadd_epi32(pairs, pairs)) - sum;
}
inline float row_dot_oracle(const uint8_t* codes, const uint8_t* scales, const ActQ& a, int nblocks) {
float result = 0.0f;
for (int b = 0; b < nblocks; ++b) {
float block = 0.0f;
for (int half = 0; half < 2; ++half) {
const int chunk = 2 * b + half;
const int dot = chunk_dot_oracle(codes + b * 16 + half * 8, a.q + chunk * QKA, a.sum[chunk]);
block += a.scale[chunk] * float(dot);
}
result += h2f(scales + 2 * b) * block;
}
return result;
}
// chunk_dot_oracle and row_dot_oracle (the oracle path's Q2_0 row dot, with its fixed float order) are in expert_oracle_parts.hpp.
/// `row_dot` for NT activations at once: the codes of each block are unpacked once, and each token's
/// accumulator sees exactly the operations `row_dot` would apply to it, in the same order.
@@ -0,0 +1,149 @@
// expert_oracle_parts.hpp - the two helper pieces of the CPU expert path's ORACLE mode (expert_oracle_q8_0), a test device that
// reproduces the 8-bit activation quantiser and the Q2_0 row dot of the reference CPU build so the VNNI path can be checked against it.
//
// quantize_oracle_q8_0 activation floats -> Q8_0 chunks of 32 (stored scale = half(amax / 127), codes by half-even of x * (127 / amax))
// chunk_dot_oracle one chunk of 32 two-bit weight codes against 32 int8 activations, as an exact integer
// row_dot_oracle a Q2_0 row (64-weight blocks, two chunks each) against a quantised activation, float32 in a fixed order
//
// Written from the packet spec (phaseA-tests/clean/P2-INTERFACES.md, 2.5) and FORMAT-SPEC sections 12 and 19. Included by expert.cpp inside
// the strata::kernels::cpu namespace scope (it opens that namespace itself).
//
// Float contract: every float operation below is a separate float32 operation, none may be fused (build this TU without -ffp-contract=fast;
// the clang pragma and the GCC attribute below make that explicit where the compiler honours them).
#pragma once
#include <cmath>
#include <cstdint>
#include <cstring>
#include "strata/kernels/cpu/expert.hpp"
#if defined(__clang__)
#pragma STDC FP_CONTRACT OFF
#endif
namespace strata::kernels::cpu {
namespace { // internal linkage: expert.cpp is built with AVX-512 flags, so no weak (COMDAT) copy of this code may reach the linker (isa_guard_check)
namespace oracle_detail {
// half (IEEE binary16) -> float, exact
inline float half_to_float(uint16_t h) {
const uint32_t sign = (uint32_t)(h & 0x8000u) << 16;
const uint32_t e = (h >> 10) & 0x1Fu;
const uint32_t m = h & 0x3FFu;
uint32_t u;
if (e == 0x1Fu) {
u = sign | 0x7F800000u | (m << 13);
} else if (e == 0) {
// subnormal half: m * 2^-24, exact in float32
const float mag = (float)m * 5.9604644775390625e-08f;
float f = sign ? -mag : mag;
std::memcpy(&u, &f, 4);
} else {
u = sign | ((e + 112u) << 23) | (m << 13);
}
float f;
std::memcpy(&f, &u, 4);
return f;
}
// float -> half, round to nearest even (overflow gives infinity, subnormal results are kept, NaN stays NaN)
inline uint16_t float_to_half(float f) {
uint32_t u;
std::memcpy(&u, &f, 4);
const uint32_t sign = (u >> 16) & 0x8000u;
const uint32_t abs_bits = u & 0x7FFFFFFFu;
if (abs_bits > 0x7F800000u) return (uint16_t)(sign | 0x7E00u | ((abs_bits >> 13) & 0x3FFu)); // NaN
if (abs_bits >= 0x477FF000u) return (uint16_t)(sign | 0x7C00u); // rounds to or beyond 65536: infinity
if (abs_bits < 0x33000001u) return (uint16_t)sign; // below half of the smallest subnormal
const int exp = (int)(abs_bits >> 23) - 127; // unbiased exponent of the float
uint32_t man = (abs_bits & 0x7FFFFFu) | 0x800000u; // 24-bit significand
int shift;
uint32_t base;
if (exp >= -14) { // normal half: keep 10 mantissa bits
shift = 13;
base = (uint32_t)(exp + 15) << 10;
man &= 0x7FFFFFu;
} else { // subnormal half: the significand moves right until the weight of its last bit is 2^-24
shift = 13 + (-14 - exp);
base = 0;
}
const uint32_t kept = man >> shift;
const uint32_t rest = man & ((1u << shift) - 1u);
const uint32_t halfway = 1u << (shift - 1);
uint32_t r = base + kept;
if (rest > halfway || (rest == halfway && (r & 1u))) ++r; // may carry into the exponent, which is correct
return (uint16_t)(sign | r);
}
} // namespace oracle_detail
#if defined(__GNUC__) && !defined(__clang__)
#define STRATA_ORACLE_NO_CONTRACT __attribute__((optimize("fp-contract=off")))
#else
#define STRATA_ORACLE_NO_CONTRACT
#endif
// n must be a multiple of QKA (32). Per chunk: amax = max |x|; d = amax / 127 (float32); scale[c] = float(half(d)); id = 127 / amax (0 for
// amax == 0); q = half-even(x * id); sum[c] = sum of q; hx[c] = scale[c] * (float)sum[c].
STRATA_ORACLE_NO_CONTRACT inline void quantize_oracle_q8_0(const float* x, int n, ActQ& a) {
const int nchunks = n / QKA;
for (int c = 0; c < nchunks; ++c) {
const float* xc = x + (size_t)c * QKA;
float amax = 0.0f;
for (int i = 0; i < QKA; ++i) {
const float v = std::fabs(xc[i]);
if (v > amax) amax = v;
}
const float d = amax / 127.0f;
const float id = amax != 0.0f ? 127.0f / amax : 0.0f;
a.scale[c] = oracle_detail::half_to_float(oracle_detail::float_to_half(d));
int32_t sum = 0;
for (int i = 0; i < QKA; ++i) {
const float p = xc[i] * id;
const int q = (int)std::nearbyint(p);
a.q[(size_t)c * QKA + i] = (int8_t)q;
sum += q;
}
a.sum[c] = sum;
a.hx[c] = a.scale[c] * (float)sum;
}
a.nchunks = nchunks;
a.bp_pairs = 0;
}
// One chunk: `codes` holds 32 two-bit codes (8 bytes, code j in bits 2 (j mod 4) of byte j / 4); a code c stands for c - 1.
// The value is sum_i (code_i - 1) * q_i = sum_i code_i * q_i - sum, with sum = the chunk's sum of q. Exact integer.
inline int chunk_dot_oracle(const uint8_t* codes, const int8_t* q, int sum) {
int acc = 0;
for (int j = 0; j < QKA; ++j) {
const int code = (codes[j >> 2] >> (2 * (j & 3))) & 3;
acc += code * (int)q[j];
}
return acc - sum;
}
// A Q2_0 row of nblocks 64-weight blocks: codes + 16 b are the 16 code bytes of block b, scales + 2 b its half scale.
// block_b = scale[2b] * (float)dot_2b, then + scale[2b+1] * (float)dot_2b+1 (starting from 0); result += h(b) * block_b in block order.
STRATA_ORACLE_NO_CONTRACT inline float row_dot_oracle(const uint8_t* codes, const uint8_t* scales, const ActQ& a, int nblocks) {
float result = 0.0f;
for (int b = 0; b < nblocks; ++b) {
const uint8_t* cb = codes + (size_t)b * 16;
const int8_t* qb = a.q + (size_t)b * 64;
const int d0 = chunk_dot_oracle(cb, qb, a.sum[2 * b]);
const int d1 = chunk_dot_oracle(cb + 8, qb + 32, a.sum[2 * b + 1]);
float block = 0.0f;
const float t0 = a.scale[2 * b] * (float)d0;
block = block + t0;
const float t1 = a.scale[2 * b + 1] * (float)d1;
block = block + t1;
const uint16_t hs = (uint16_t)(scales[2 * b] | (scales[2 * b + 1] << 8));
const float t2 = oracle_detail::half_to_float(hs) * block;
result = result + t2;
}
return result;
}
} // namespace
} // namespace strata::kernels::cpu
+21 -214
View File
@@ -1,27 +1,13 @@
// Portions of this file are derived from ggml / llama.cpp (https://github.com/ggml-org/llama.cpp, pin 3cf03257f219afbe7334045ff7c6a06ac68c627d), MIT
// licence, Copyright (c) 2023-2026 The ggml authors (licence text: engine/third_party/ggml/LICENSE). Derived: hsum_float_8, bytes_from_nibbles_32,
// bytes_from_bits_32 and the per-block Q4_K / Q5_1 / Q8_0 integer chains of the AVX2 branches of ggml-cpu/arch/x86/quants.c (about 50 of 300 lines). The
// loop over several tokens inside the loop over blocks is ours.
// The rest is Copyright (c) 2026 Niko1221 and the Strata contributors, MIT.
// src/kernels/cpu/kq_avx2.cpp - Unsloth UD-Q4_K_XL's expert rows (Q4_K gate/up, Q5_1 and Q8_0 down) for several tokens at once, and the BF16
// router dots of the routing-aware prefetch.
//
// src/kernels/cpu/kq_avx2.cpp - Unsloth UD-Q4_K_XL's expert rows (Q4_K gate/up, Q5_1 and Q8_0 down) for several
// tokens at once, BIT-EXACT against ggml-cpu's own dot products.
// The dot kernels themselves (one weight row against up to 8 tokens' quantised activations, every token's result bit-identical to the
// single-token Avx2 dot of the quant layer) are in kq_dots_avx2.cpp; this file is the glue: the token-group loop, the SwiGLU of the gate / up
// rows and the BF16 router dots (an estimate only: no bit contract).
//
// ggml-cpu is built for AVX2 here (STRATA_PORTABLE: GGML_AVX2=ON, GGML_AVX512=OFF), so its vec_dot for these formats
// is the __AVX2__ branch of ggml-cpu/arch/x86/quants.c: ggml_vec_dot_q4_K_q8_K, ggml_vec_dot_q5_1_q8_1,
// ggml_vec_dot_q8_0_q8_0. The functions below are those branches with the loop over tokens moved inside the loop
// over blocks: everything that depends only on the weights (the 4-bit unpacking, the 6-bit scales and mins, the
// fifth bits, the absolute values of the Q8_0 weights, the fp16 scales) is done once per block, and every token then
// runs exactly ggml's integer chain and ggml's float operations in ggml's order - so each token's result is ggml's
// to the bit (native_expert_parity checks it), whatever the number of tokens. Unlike the i-quant kernels (#152)
// the group size therefore never changes an answer.
//
// The gain is the weight-side work and the weight bytes, read once per verify window instead of once per token.
// The gain over one-token dots is the weight-side work and the weight bytes, read once per verify window instead of once per token.
#include "strata/kernels/cpu/kq_avx2.hpp"
#define GGML_COMMON_DECL_CPP
#define GGML_COMMON_IMPL_CPP
#include "ggml-common.h"
#include "kq_dots_avx2.hpp" // kqd::q4k_dot, q5_1_dot_nt, q8_0_dot_nt (and the block types)
#include <immintrin.h>
@@ -33,198 +19,19 @@ namespace {
constexpr int MAXT = 8; // the verify window's tokens per group (kVerifyMaxT)
inline float h2f(ggml_half h) {
uint16_t u;
std::memcpy(&u, &h, 2);
return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128((int) u)));
}
// the fp16 pair {d, dmin} / {d, m} / {d, s} a block starts with (a union in ggml-common.h's C++ declarations)
inline float half_at(const void* block, int i) {
ggml_half h;
std::memcpy(&h, (const uint8_t*) block + 2 * i, 2);
return h2f(h);
}
// ---- ggml's helpers (ggml-cpu/arch/x86/quants.c, the AVX2 / non-VNNI forms), verbatim
inline float hsum_float_8(const __m256 x) {
__m128 res = _mm256_extractf128_ps(x, 1);
res = _mm_add_ps(res, _mm256_castps256_ps128(x));
res = _mm_add_ps(res, _mm_movehl_ps(res, res));
res = _mm_add_ss(res, _mm_movehdup_ps(res));
return _mm_cvtss_f32(res);
}
inline __m256i bytes_from_bits_32(const uint8_t* x) {
uint32_t x32;
std::memcpy(&x32, x, sizeof(uint32_t));
const __m256i shuf_mask = _mm256_set_epi64x(0x0303030303030303, 0x0202020202020202, 0x0101010101010101,
0x0000000000000000);
__m256i bytes = _mm256_shuffle_epi8(_mm256_set1_epi32((int) x32), shuf_mask);
const __m256i bit_mask = _mm256_set1_epi64x(0x7fbfdfeff7fbfdfe);
bytes = _mm256_or_si256(bytes, bit_mask);
return _mm256_cmpeq_epi8(bytes, _mm256_set1_epi64x(-1));
}
inline __m256i bytes_from_nibbles_32(const uint8_t* rsi) {
const __m128i tmp = _mm_loadu_si128((const __m128i*) rsi);
const __m256i bytes = _mm256_insertf128_si256(_mm256_castsi128_si256(tmp), _mm_srli_epi16(tmp, 4), 1);
const __m256i lowMask = _mm256_set1_epi8(0xF);
return _mm256_and_si256(lowMask, bytes);
}
inline __m256 sum_i16_pairs_float(const __m256i x) {
const __m256i ones = _mm256_set1_epi16(1);
return _mm256_cvtepi32_ps(_mm256_madd_epi16(ones, x));
}
inline __m256 mul_sum_us8_pairs_float(const __m256i ax, const __m256i sy) {
return sum_i16_pairs_float(_mm256_maddubs_epi16(ax, sy));
}
alignas(32) const uint8_t k_shuffle[256] = {
0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3,
4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5,
6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7,
8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9,
10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,
12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,
14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15};
inline __m256i get_scale_shuffle_k4(int i) { return _mm256_loadu_si256((const __m256i*) k_shuffle + i); }
// ---- Q4_K x Q8_K (ggml_vec_dot_q4_K_q8_K, __AVX2__)
void q4k_dot(const block_q4_K* x, int nb, const void* const* act, int nt, float* res) {
static const uint32_t kmask1 = 0x3f3f3f3f, kmask2 = 0x0f0f0f0f, kmask3 = 0x03030303;
const __m256i m4 = _mm256_set1_epi8(0xF);
__m256 acc[MAXT];
__m128 acc_m[MAXT];
for (int t = 0; t < nt; ++t) { acc[t] = _mm256_setzero_ps(); acc_m[t] = _mm_setzero_ps(); }
for (int i = 0; i < nb; ++i) {
const float xd = half_at(&x[i], 0), xdmin = half_at(&x[i], 1);
uint32_t utmp[4];
std::memcpy(utmp, x[i].scales, 12);
utmp[3] = ((utmp[2] >> 4) & kmask2) | (((utmp[1] >> 6) & kmask3) << 4);
const uint32_t uaux = utmp[1] & kmask1;
utmp[1] = (utmp[2] & kmask2) | (((utmp[0] >> 6) & kmask3) << 4);
utmp[2] = uaux;
utmp[0] &= kmask1;
const __m256i mins_and_scales = _mm256_cvtepu8_epi16(_mm_set_epi32((int) utmp[3], (int) utmp[2],
(int) utmp[1], (int) utmp[0]));
const __m128i mins = _mm256_extracti128_si256(mins_and_scales, 1);
const __m128i sc128 = _mm256_extracti128_si256(mins_and_scales, 0);
const __m256i scales = _mm256_insertf128_si256(_mm256_castsi128_si256(sc128), sc128, 1);
__m256i scale_l[4], scale_h[4], q4l[4], q4h[4];
const uint8_t* q4 = x[i].qs;
for (int j = 0; j < QK_K / 64; ++j) {
scale_l[j] = _mm256_shuffle_epi8(scales, get_scale_shuffle_k4(2 * j + 0));
scale_h[j] = _mm256_shuffle_epi8(scales, get_scale_shuffle_k4(2 * j + 1));
const __m256i q4bits = _mm256_loadu_si256((const __m256i*) q4);
q4 += 32;
q4l[j] = _mm256_and_si256(q4bits, m4);
q4h[j] = _mm256_and_si256(_mm256_srli_epi16(q4bits, 4), m4);
}
for (int t = 0; t < nt; ++t) {
const block_q8_K* y = (const block_q8_K*) act[t] + i;
const float d = y->d * xd;
const float dmin = -y->d * xdmin;
const int8_t* q8 = y->qs;
const __m256i q8sums = _mm256_loadu_si256((const __m256i*) y->bsums);
const __m128i q8s = _mm_hadd_epi16(_mm256_extracti128_si256(q8sums, 0), _mm256_extracti128_si256(q8sums, 1));
const __m128i prod = _mm_madd_epi16(mins, q8s);
acc_m[t] = _mm_fmadd_ps(_mm_set1_ps(dmin), _mm_cvtepi32_ps(prod), acc_m[t]);
__m256i sumi = _mm256_setzero_si256();
for (int j = 0; j < QK_K / 64; ++j) {
const __m256i q8l = _mm256_loadu_si256((const __m256i*) q8);
q8 += 32;
__m256i p16l = _mm256_maddubs_epi16(q4l[j], q8l);
p16l = _mm256_madd_epi16(scale_l[j], p16l);
const __m256i q8h = _mm256_loadu_si256((const __m256i*) q8);
q8 += 32;
__m256i p16h = _mm256_maddubs_epi16(q4h[j], q8h);
p16h = _mm256_madd_epi16(scale_h[j], p16h);
sumi = _mm256_add_epi32(sumi, _mm256_add_epi32(p16l, p16h));
}
acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(sumi), acc[t]);
}
}
for (int t = 0; t < nt; ++t) {
__m128 m = acc_m[t];
m = _mm_add_ps(m, _mm_movehl_ps(m, m));
m = _mm_add_ss(m, _mm_movehdup_ps(m));
res[t] = hsum_float_8(acc[t]) + _mm_cvtss_f32(m);
}
}
// ---- Q5_1 x Q8_1 (ggml_vec_dot_q5_1_q8_1, __AVX2__)
template <int NT>
void q5_1_dot(const block_q5_1* x, int nb, const void* const* act, float* res) {
__m256 acc[NT];
float summs[NT];
for (int t = 0; t < NT; ++t) { acc[t] = _mm256_setzero_ps(); summs[t] = 0.0f; }
for (int ib = 0; ib < nb; ++ib) {
const __m256 dx = _mm256_set1_ps(half_at(&x[ib], 0));
const float xm = half_at(&x[ib], 1);
__m256i qx = bytes_from_nibbles_32(x[ib].qs);
__m256i bxhi = bytes_from_bits_32(x[ib].qh);
bxhi = _mm256_and_si256(bxhi, _mm256_set1_epi8(0x10));
qx = _mm256_or_si256(qx, bxhi);
for (int t = 0; t < NT; ++t) {
const block_q8_1* y = (const block_q8_1*) act[t] + ib;
summs[t] += xm * half_at(y, 1);
const __m256 dy = _mm256_set1_ps(half_at(y, 0));
const __m256i qy = _mm256_loadu_si256((const __m256i*) y->qs);
const __m256 q = mul_sum_us8_pairs_float(qx, qy);
acc[t] = _mm256_fmadd_ps(q, _mm256_mul_ps(dx, dy), acc[t]);
}
}
for (int t = 0; t < NT; ++t) res[t] = hsum_float_8(acc[t]) + summs[t];
}
// ---- Q8_0 x Q8_0 (ggml_vec_dot_q8_0_q8_0, __AVX2__; mul_sum_i8_pairs_float without AVX-VNNI-INT8)
template <int NT>
void q8_0_dot(const block_q8_0* x, int nb, const void* const* act, float* res) {
__m256 acc[NT];
for (int t = 0; t < NT; ++t) acc[t] = _mm256_setzero_ps();
for (int ib = 0; ib < nb; ++ib) {
const float xd = h2f(x[ib].d);
const __m256i qx = _mm256_loadu_si256((const __m256i*) x[ib].qs);
const __m256i ax = _mm256_sign_epi8(qx, qx);
for (int t = 0; t < NT; ++t) {
const block_q8_0* y = (const block_q8_0*) act[t] + ib;
const __m256 d = _mm256_set1_ps(xd * h2f(y->d));
const __m256i qy = _mm256_loadu_si256((const __m256i*) y->qs);
const __m256i sy = _mm256_sign_epi8(qy, qx);
const __m256 q = mul_sum_us8_pairs_float(ax, sy);
acc[t] = _mm256_fmadd_ps(d, q, acc[t]);
}
}
for (int t = 0; t < NT; ++t) res[t] = hsum_float_8(acc[t]);
}
void q5_1_dot_nt(const block_q5_1* x, int nb, const void* const* act, int nt, float* res) {
for (int t0 = 0; t0 < nt; t0 += 4) {
const int k = nt - t0 < 4 ? nt - t0 : 4;
switch (k) {
case 1: q5_1_dot<1>(x, nb, act + t0, res + t0); break;
case 2: q5_1_dot<2>(x, nb, act + t0, res + t0); break;
case 3: q5_1_dot<3>(x, nb, act + t0, res + t0); break;
default: q5_1_dot<4>(x, nb, act + t0, res + t0); break;
}
}
}
void q8_0_dot_nt(const block_q8_0* x, int nb, const void* const* act, int nt, float* res) {
for (int t0 = 0; t0 < nt; t0 += 4) {
const int k = nt - t0 < 4 ? nt - t0 : 4;
switch (k) {
case 1: q8_0_dot<1>(x, nb, act + t0, res + t0); break;
case 2: q8_0_dot<2>(x, nb, act + t0, res + t0); break;
case 3: q8_0_dot<3>(x, nb, act + t0, res + t0); break;
default: q8_0_dot<4>(x, nb, act + t0, res + t0); break;
}
}
// sum of the 8 lanes: (high half + low half), then the two 64-bit halves, then the two lanes
inline float bf16_hsum8(const __m256 x) {
__m128 r = _mm_add_ps(_mm256_extractf128_ps(x, 1), _mm256_castps256_ps128(x));
r = _mm_add_ps(r, _mm_movehl_ps(r, r));
r = _mm_add_ss(r, _mm_movehdup_ps(r));
return _mm_cvtss_f32(r);
}
void dot_rows(int type, const uint8_t* row, int n, const void* const* act, int nt, float* res) {
switch (type) {
case 12: q4k_dot((const block_q4_K*) row, n / QK_K, act, nt, res); break;
case 7: q5_1_dot_nt((const block_q5_1*) row, n / QK5_1, act, nt, res); break;
case 8: q8_0_dot_nt((const block_q8_0*) row, n / QK8_0, act, nt, res); break;
case 12: kqd::q4k_dot((const block_q4_K*) row, n / QK_K, act, nt, res); break;
case 7: kqd::q5_1_dot_nt((const block_q5_1*) row, n / QK5_1, act, nt, res); break;
case 8: kqd::q8_0_dot_nt((const block_q8_0*) row, n / QK8_0, act, nt, res); break;
default: break;
}
}
@@ -250,10 +57,10 @@ void bf16_rows_dot_multi(const uint16_t* w, int rows, int cols, const float* x,
if (m > 2) a2 = _mm256_fmadd_ps(wf, _mm256_loadu_ps(x2 + c), a2);
if (m > 3) a3 = _mm256_fmadd_ps(wf, _mm256_loadu_ps(x3 + c), a3);
}
out[(size_t) t0 * rows + r] = hsum_float_8(a0);
if (m > 1) out[(size_t) (t0 + 1) * rows + r] = hsum_float_8(a1);
if (m > 2) out[(size_t) (t0 + 2) * rows + r] = hsum_float_8(a2);
if (m > 3) out[(size_t) (t0 + 3) * rows + r] = hsum_float_8(a3);
out[(size_t) t0 * rows + r] = bf16_hsum8(a0);
if (m > 1) out[(size_t) (t0 + 1) * rows + r] = bf16_hsum8(a1);
if (m > 2) out[(size_t) (t0 + 2) * rows + r] = bf16_hsum8(a2);
if (m > 3) out[(size_t) (t0 + 3) * rows + r] = bf16_hsum8(a3);
}
}
}
@@ -267,7 +74,7 @@ void bf16_rows_dot(const uint16_t* w, int rows, int cols, const float* x, float*
const __m256i h = _mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*) (wr + c)));
acc = _mm256_fmadd_ps(_mm256_castsi256_ps(_mm256_slli_epi32(h, 16)), _mm256_loadu_ps(x + c), acc);
}
float s = hsum_float_8(acc);
float s = bf16_hsum8(acc);
for (; c < cols; ++c) {
const uint32_t b = (uint32_t) wr[c] << 16;
float f;
+153
View File
@@ -0,0 +1,153 @@
// kq_dots_avx2.cpp - see kq_dots_avx2.hpp. Written from FORMAT-SPEC (Q4_K, Q5_1, Q8_0, Q8_K, Q8_1 layouts) and the float composition measured on the
// single-token Avx2 dots of the quant layer (tests/clean_p2/probe_*.cpp, model_*.cpp):
// * the integer part of a block is exact, in 8 int32 lanes (lane l = elements 4l .. 4l+3 of each 32-element group, scales applied inside the lane);
// * acc[l] += fma(D, float(lane l)) per block with D = float(d_w) * d_a, blocks in order; the 8 lanes are added as ((l0+l4)+(l2+l6)) + ((l1+l5)+(l3+l7));
// * Q4_K: min lanes (sub-block pairs) accumulated the same way with dm = float(dmin) * d_a, and the result is the sum minus their tree (k0+k2)+(k1+k3);
// * Q5_1: the min part sum_b m_w * s_a (sequential float), added to the lane sum; Q8_0: the sign of a weight moves onto the activation (-128 wraps).
#include "kq_dots_avx2.hpp"
#include <immintrin.h>
#include <cstdint>
#include <cstring>
namespace strata::kernels::cpu::kqd {
static_assert(sizeof(block_q4_K) == 144 && sizeof(block_q5_1) == 24 && sizeof(block_q8_0) == 34 && sizeof(block_q8_K) == 292 && sizeof(block_q8_1) == 36,
"block layouts of the format spec");
namespace {
#if defined(_MSC_VER)
inline float h2f(uint16_t h) { return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128((int)h))); }
#else
inline float h2f(uint16_t h) { return _cvtsh_ss(h); }
#endif
inline uint32_t ld32(const uint8_t* p) { uint32_t v; std::memcpy(&v, p, 4); return v; }
inline uint16_t ld16(const uint8_t* p) { return (uint16_t)(p[0] | (p[1] << 8)); }
inline float ldf(const uint8_t* p) { float v; std::memcpy(&v, p, 4); return v; }
inline __m256i ld256(const uint8_t* p) { return _mm256_loadu_si256((const __m256i*)p); }
inline float tree8(__m256 v) {
const __m128 a = _mm_add_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps(v, 1));
const __m128 b = _mm_add_ps(a, _mm_movehl_ps(a, a));
return _mm_cvtss_f32(_mm_add_ss(b, _mm_shuffle_ps(b, b, 1)));
}
// the four min lanes sit in the even lanes: (k0 + k2) + (k1 + k3)
inline float tree4_even(__m256 v) {
const __m128 a = _mm_add_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps(v, 1));
return _mm_cvtss_f32(_mm_add_ss(a, _mm_movehl_ps(a, a)));
}
inline __m256i madd_group(__m256i u8, __m256i s8, __m256i scale16) { return _mm256_madd_epi16(_mm256_maddubs_epi16(u8, s8), scale16); }
inline __m256 acc_step(__m256 acc, float D, __m256i lanes) { return _mm256_fmadd_ps(_mm256_set1_ps(D), _mm256_cvtepi32_ps(lanes), acc); }
} // namespace
// ============================================================================================================================================
// Q4_K x Q8_K
// ============================================================================================================================================
void q4k_dot(const block_q4_K* x, int nb, const void* const* act, int nt, float* res) {
const uint8_t* xr = (const uint8_t*)x;
const __m256i lowmask = _mm256_set1_epi8(0x0f);
__m256 acc[8], accm[8];
for (int t = 0; t < nt; ++t) acc[t] = accm[t] = _mm256_setzero_ps();
for (int i = 0; i < nb; ++i) {
const uint8_t* xb = xr + (size_t)i * 144;
// 6-bit scales and mins (12 bytes): sc32[j] = scale j in both halves of a 32-bit word, mm = the mins as 32-bit words
const uint32_t u0 = ld32(xb + 4), u1 = ld32(xb + 8), u2 = ld32(xb + 12);
const uint32_t sc_lo = u0 & 0x3f3f3f3fu, m_lo = u1 & 0x3f3f3f3fu;
const uint32_t sc_hi = (u2 & 0x0f0f0f0fu) | (((u0 >> 6) & 0x03030303u) << 4);
const uint32_t m_hi = ((u2 >> 4) & 0x0f0f0f0fu) | (((u1 >> 6) & 0x03030303u) << 4);
const __m256i scd = _mm256_cvtepu8_epi32(_mm_cvtsi64_si128((long long)((uint64_t)sc_lo | ((uint64_t)sc_hi << 32))));
alignas(32) uint32_t sc32[8];
_mm256_store_si256((__m256i*)sc32, _mm256_or_si256(scd, _mm256_slli_epi32(scd, 16)));
const __m256i mm = _mm256_cvtepu8_epi32(_mm_cvtsi64_si128((long long)((uint64_t)m_lo | ((uint64_t)m_hi << 32))));
// the weights' nibbles, unpacked once for all tokens: sub-block 2g from the low and 2g + 1 from the high nibbles of qs[32g .. 32g+31]
__m256i w[8];
for (int g = 0; g < 4; ++g) {
const __m256i q = ld256(xb + 16 + 32 * g);
w[2 * g] = _mm256_and_si256(q, lowmask);
w[2 * g + 1] = _mm256_and_si256(_mm256_srli_epi16(q, 4), lowmask);
}
const float dw = h2f(ld16(xb)), dmin = h2f(ld16(xb + 2));
for (int t = 0; t < nt; ++t) {
const uint8_t* yb = (const uint8_t*)act[t] + (size_t)i * 292;
const float da = ldf(yb);
__m256i s0 = _mm256_setzero_si256(), s1 = _mm256_setzero_si256();
for (int g = 0; g < 4; ++g) {
s0 = _mm256_add_epi32(s0, madd_group(w[2 * g], ld256(yb + 4 + 64 * g), _mm256_set1_epi32((int)sc32[2 * g])));
s1 = _mm256_add_epi32(s1, madd_group(w[2 * g + 1], ld256(yb + 4 + 64 * g + 32), _mm256_set1_epi32((int)sc32[2 * g + 1])));
}
acc[t] = acc_step(acc[t], dw * da, _mm256_add_epi32(s0, s1));
// min lanes: m_j * (bsums[2j] + bsums[2j+1]) with the pair added as 16-bit integers; lane k = j = 2k and 2k + 1 added
const __m256i bs = ld256(yb + 260);
const __m256i p = _mm256_madd_epi16(_mm256_add_epi16(bs, _mm256_srli_epi32(bs, 16)), mm);
const __m256i v = _mm256_add_epi32(p, _mm256_srli_epi64(p, 32));
accm[t] = _mm256_fmadd_ps(_mm256_set1_ps(dmin * da), _mm256_cvtepi32_ps(v), accm[t]);
}
}
for (int t = 0; t < nt; ++t) res[t] = tree8(acc[t]) - tree4_even(accm[t]);
}
// ============================================================================================================================================
// Q5_1 x Q8_1 : 24-byte weight blocks (d, m, qh[4], qs[16]) against 36-byte activation blocks (d, s, qs[32])
// ============================================================================================================================================
void q5_1_dot_nt(const block_q5_1* x, int nb, const void* const* act, int nt, float* res) {
const uint8_t* xr = (const uint8_t*)x;
const __m256i lowmask = _mm256_set1_epi8(0x0f);
const __m256i bitsel = _mm256_set1_epi64x((long long)0x8040201008040201ull); // bit (k mod 8) in byte k
const __m256i pick = _mm256_set_epi64x(0x0303030303030303ll, 0x0202020202020202ll, 0x0101010101010101ll, 0x0000000000000000ll); // byte k of the 32-bit mask -> element k
const __m256i ones = _mm256_set1_epi16(1);
// the mask expansion needs, per element e, byte e / 8 of qh: lane 0 (elements 0..15) uses qh bytes 0, 1 and lane 1 (elements 16..31) bytes 2, 3
const __m256i sel = _mm256_set_epi8(3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0);
(void)pick;
for (int t0 = 0; t0 < nt; t0 += 4) {
const int n = (nt - t0) < 4 ? (nt - t0) : 4;
__m256 acc[4] = {_mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps()};
float summs[4] = {0.f, 0.f, 0.f, 0.f};
for (int i = 0; i < nb; ++i) {
const uint8_t* xb = xr + (size_t)i * 24;
// element e (0..31): nibble of qs[e % 16] (low for e < 16, high otherwise) plus 16 * bit e of qh
const __m128i raw = _mm_loadu_si128((const __m128i*)(xb + 8));
const __m256i nib = _mm256_and_si256(_mm256_set_m128i(_mm_srli_epi16(raw, 4), raw), lowmask);
const __m256i bits = _mm256_shuffle_epi8(_mm256_set1_epi32((int)ld32(xb + 4)), sel);
const __m256i fifth = _mm256_and_si256(_mm256_cmpeq_epi8(_mm256_and_si256(bits, bitsel), bitsel), _mm256_set1_epi8(0x10));
const __m256i q5 = _mm256_or_si256(nib, fifth);
const float dw = h2f(ld16(xb)), mw = h2f(ld16(xb + 2));
for (int t = 0; t < n; ++t) {
const uint8_t* yb = (const uint8_t*)act[t0 + t] + (size_t)i * 36;
const __m256i lanes = _mm256_madd_epi16(_mm256_maddubs_epi16(q5, ld256(yb + 4)), ones);
acc[t] = acc_step(acc[t], dw * h2f(ld16(yb)), lanes);
summs[t] += mw * h2f(ld16(yb + 2));
}
}
for (int t = 0; t < n; ++t) res[t0 + t] = tree8(acc[t]) + summs[t];
}
}
// ============================================================================================================================================
// Q8_0 x Q8_0
// ============================================================================================================================================
void q8_0_dot_nt(const block_q8_0* x, int nb, const void* const* act, int nt, float* res) {
const uint8_t* xr = (const uint8_t*)x;
const __m256i ones = _mm256_set1_epi16(1);
for (int t0 = 0; t0 < nt; t0 += 4) {
const int n = (nt - t0) < 4 ? (nt - t0) : 4;
__m256 acc[4] = {_mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps()};
for (int i = 0; i < nb; ++i) {
const uint8_t* xb = xr + (size_t)i * 34;
const __m256i w = ld256(xb + 2);
const __m256i aw = _mm256_sign_epi8(w, w); // |w| (128 for -128, read as unsigned)
const float dw = h2f(ld16(xb));
for (int t = 0; t < n; ++t) {
const uint8_t* yb = (const uint8_t*)act[t0 + t] + (size_t)i * 34;
const __m256i sy = _mm256_sign_epi8(ld256(yb + 2), w); // y with the sign of w (-128 under a negative w wraps)
acc[t] = acc_step(acc[t], dw * h2f(ld16(yb)), _mm256_madd_epi16(_mm256_maddubs_epi16(aw, sy), ones));
}
}
for (int t = 0; t < n; ++t) res[t0 + t] = tree8(acc[t]);
}
}
} // namespace strata::kernels::cpu::kqd
+25
View File
@@ -0,0 +1,25 @@
// kq_dots_avx2.hpp - multi-token CPU expert dots for Unsloth UD-Q4_K_XL rows in 256-bit lanes (clean-room round P-7).
//
// One weight row against several tokens' quantised activations: the weights of a block are unpacked once and every token's dot is formed from them.
// Each result is bit-identical, token by token, to the single-token Avx2 dot of the quant layer for the same row and activation
// Q4_K x Q8_K dot_kernel(Type::Q4_K, Arith::Avx2, Isa::Avx2)->fn
// Q5_1 x Q8_1 dot_kernel(Type::Q5_1, Arith::Avx2, Isa::Avx2)->fn
// Q8_0 x Q8_0 dot_kernel(Type::Q8_0, Arith::Avx2, Isa::Avx2)->fn
// whatever nt and however the tokens are grouped inside. Compiled with AVX2 + FMA + F16C (MSVC /arch:AVX2).
#pragma once
#define GGML_COMMON_DECL_CPP
#include "ggml-common.h" // the forwarder to strata-quant-common.h: block_q4_K, block_q5_1, block_q8_0, block_q8_K, block_q8_1
namespace strata::kernels::cpu::kqd {
/// x = one weight row of nb Q4_K blocks; act[t] (t < nt, 1 <= nt <= 8) = a row of nb Q8_K blocks; res[t] = dot of the row with token t.
void q4k_dot(const block_q4_K* x, int nb, const void* const* act, int nt, float* res);
/// x = one row of nb Q5_1 blocks (32 elements each); act[t] = a row of nb Q8_1 blocks; nt >= 1 (processed in groups of up to 4); res[0..nt).
void q5_1_dot_nt(const block_q5_1* x, int nb, const void* const* act, int nt, float* res);
/// x = one row of nb Q8_0 blocks; act[t] = a row of nb Q8_0 blocks; nt >= 1; res[0..nt).
void q8_0_dot_nt(const block_q8_0* x, int nb, const void* const* act, int nt, float* res);
} // namespace strata::kernels::cpu::kqd
+187 -149
View File
@@ -1,178 +1,216 @@
// Copyright (c) 2026 Niko1221 and the Strata contributors
// SPDX-License-Identifier: MIT
// src/quant/arm/arm_act.inc - the Neon contract's activation quantizers: Q8_0, Q8_1 (float rows -> blocks of 32) and Q8_K (blocks of 256).
//
// Portions of this file are derived from ggml / llama.cpp (https://github.com/ggml-org/llama.cpp, pin 3cf03257f219afbe7334045ff7c6a06ac68c627d), MIT
// licence, Copyright (c) 2023-2026 The ggml authors (licence text: engine/third_party/ggml/LICENSE). Derived: the NEON Q8_0, Q8_1 and Q8_K activation
// quantizers (quantize_row_q8_0 / q8_1 / q8_K of ggml-cpu/arch/arm/quants.c and ggml-quants.c), whose rounding, scales and block layout they keep (about
// 40 of 170 lines).
// The rest is Copyright (c) 2026 Niko1221 and the Strata contributors, MIT.
// Included into namespace strata::quant::neon by arm/act_neon.cpp (which includes arm_helpers.inc first and registers the three functions below);
// every helper here is named an_* so nothing can collide with that file. Written from phaseA-tests/hy4gguf/FORMAT-SPEC.md Part II section 19
// (row Neon) and section 6; block layouts are written as byte offsets (Q8_0: d half @0, qs[32] @2; Q8_1: d half @0, s half @2, qs[32] @4;
// Q8_K: d float @0, qs[256] @4, bsums[16] int16 @260).
//
// arm_act.inc - ARM64 NEON activation quantizers for Q8_0, Q8_1, and Q8_K.
// Q8_0 / Q8_1 round half to even (vcvtnq_s32_f32) with vectorized narrow-and-store.
// Q8_K matches quantize_q8_K_ref byte-for-byte on both GCC (-ffp-contract=fast) and Clang (unfused mul+add)
// using 4-way unrolled max-abs, exact first-occurrence sign scan, narrow-store, and single-instruction vaddlvq_s8 bsums.
// Q8_0 amax = max |x|, d = amax / 127, id = 1 / d (0 when d is 0), q = half-even(x * id), d stored as half(d)
// Q8_1 the same q and d, plus s = half(d * sum q) with d the float32 value before the half rounding
// Q8_K mx = the first element of largest magnitude (sign kept), iscale = -127 / mx, q = min(127, nearest_int(iscale * x)) half-even,
// bsums[t] = sum of q over 16, d = 1 / iscale; an all-zero block gives zeros and d = 0.
// The product iscale * x is rounded to float32 before the rounding to an integer (Clang, Apple Clang); a GCC build fuses it into the
// rounding step (what its contraction does to the reference), kept here as a separate code path so the bits stay those of each build.
//
// Without __ARM_NEON the same three functions are plain scalar code with the same results.
void quantize_q8_0(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT vy, int64_t k) {
assert(QK8_0 == 32);
assert(k % QK8_0 == 0);
const int nb = (int) (k / QK8_0);
block_q8_0* STRATA_RESTRICT y = (block_q8_0*) vy;
#include <cstring>
#if defined(__ARM_NEON)
for (int i = 0; i < nb; i++) {
float32x4_t srcv[8];
float32x4_t asrcv[8];
float32x4_t amaxv[8];
for (int j = 0; j < 8; j++) srcv[j] = vld1q_f32(x + i * 32 + 4 * j);
for (int j = 0; j < 8; j++) asrcv[j] = vabsq_f32(srcv[j]);
static inline float an_h2f(uint16_t h) {
__fp16 t;
std::memcpy(&t, &h, sizeof t);
return (float) t;
}
static inline uint16_t an_f2h(float f) {
const __fp16 t = (__fp16) f;
uint16_t r;
std::memcpy(&r, &t, sizeof r);
return r;
}
for (int j = 0; j < 4; j++) amaxv[2 * j] = vmaxq_f32(asrcv[2 * j], asrcv[2 * j + 1]);
for (int j = 0; j < 2; j++) amaxv[4 * j] = vmaxq_f32(amaxv[4 * j], amaxv[4 * j + 2]);
amaxv[0] = vmaxq_f32(amaxv[0], amaxv[4]);
// the 32 floats of one Q8_0 / Q8_1 block as 8 quads; returns amax
static inline float an_amax32(const float* x, float32x4_t* v) {
float32x4_t m = vdupq_n_f32(0.0f);
for (int i = 0; i < 8; ++i) {
v[i] = vld1q_f32(x + 4 * i);
m = vmaxq_f32(m, vabsq_f32(v[i]));
}
return vmaxvq_f32(m);
}
const float amax = vmaxvq_f32(amaxv[0]);
const float d = amax / ((1 << 7) - 1);
const float id = d ? 1.0f / d : 0.0f;
y[i].d = f2h(d);
// quantize 32 floats with the scale factor id into q (int8), returns the sum of the codes
static inline int an_quant32(const float32x4_t* v, float id, int8_t* q) {
int32x4_t acc = vdupq_n_s32(0);
for (int i = 0; i < 4; ++i) {
const int32x4_t a = vcvtnq_s32_f32(vmulq_n_f32(v[2 * i], id));
const int32x4_t b = vcvtnq_s32_f32(vmulq_n_f32(v[2 * i + 1], id));
acc = vaddq_s32(acc, vaddq_s32(a, b));
const int16x8_t h = vcombine_s16(vmovn_s32(a), vmovn_s32(b));
vst1_s8(q + 8 * i, vmovn_s16(h));
}
return vaddvq_s32(acc);
}
int16x8_t n[4];
for (int j = 0; j < 4; j++) {
const int32x4_t vi0 = vcvtnq_s32_f32(vmulq_n_f32(srcv[2 * j + 0], id));
const int32x4_t vi1 = vcvtnq_s32_f32(vmulq_n_f32(srcv[2 * j + 1], id));
n[j] = vcombine_s16(vmovn_s32(vi0), vmovn_s32(vi1));
}
vst1q_s8(y[i].qs + 0, vcombine_s8(vmovn_s16(n[0]), vmovn_s16(n[1])));
vst1q_s8(y[i].qs + 16, vcombine_s8(vmovn_s16(n[2]), vmovn_s16(n[3])));
void quantize_q8_0(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT vy, int64_t k) {
uint8_t* y = (uint8_t*) vy;
const int64_t nb = k / 32;
for (int64_t b = 0; b < nb; ++b) {
float32x4_t v[8];
const float amax = an_amax32(x + 32 * b, v);
const float d = amax / 127.0f;
const float id = d != 0.0f ? 1.0f / d : 0.0f;
const uint16_t dh = an_f2h(d);
std::memcpy(y + 34 * b, &dh, 2);
(void) an_quant32(v, id, (int8_t*) (y + 34 * b + 2));
}
#else
UNUSED(nb);
quantize_q8_0_ref(x, y, k);
#endif
}
void quantize_q8_1(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT vy, int64_t k) {
assert(k % QK8_1 == 0);
const int nb = (int) (k / QK8_1);
block_q8_1* STRATA_RESTRICT y = (block_q8_1*) vy;
#if defined(__ARM_NEON)
for (int i = 0; i < nb; i++) {
float32x4_t srcv[8];
float32x4_t asrcv[8];
float32x4_t amaxv[8];
for (int j = 0; j < 8; j++) srcv[j] = vld1q_f32(x + i * 32 + 4 * j);
for (int j = 0; j < 8; j++) asrcv[j] = vabsq_f32(srcv[j]);
for (int j = 0; j < 4; j++) amaxv[2 * j] = vmaxq_f32(asrcv[2 * j], asrcv[2 * j + 1]);
for (int j = 0; j < 2; j++) amaxv[4 * j] = vmaxq_f32(amaxv[4 * j], amaxv[4 * j + 2]);
amaxv[0] = vmaxq_f32(amaxv[0], amaxv[4]);
const float amax = vmaxvq_f32(amaxv[0]);
const float d = amax / ((1 << 7) - 1);
const float id = d ? 1.0f / d : 0.0f;
y[i].d = f2h(d);
int32x4_t accv = vdupq_n_s32(0);
int16x8_t n[4];
for (int j = 0; j < 4; j++) {
const int32x4_t vi0 = vcvtnq_s32_f32(vmulq_n_f32(srcv[2 * j + 0], id));
const int32x4_t vi1 = vcvtnq_s32_f32(vmulq_n_f32(srcv[2 * j + 1], id));
accv = vaddq_s32(accv, vaddq_s32(vi0, vi1));
n[j] = vcombine_s16(vmovn_s32(vi0), vmovn_s32(vi1));
}
vst1q_s8(y[i].qs + 0, vcombine_s8(vmovn_s16(n[0]), vmovn_s16(n[1])));
vst1q_s8(y[i].qs + 16, vcombine_s8(vmovn_s16(n[2]), vmovn_s16(n[3])));
y[i].s = f2h(d * vaddvq_s32(accv));
uint8_t* y = (uint8_t*) vy;
const int64_t nb = k / 32;
for (int64_t b = 0; b < nb; ++b) {
float32x4_t v[8];
const float amax = an_amax32(x + 32 * b, v);
const float d = amax / 127.0f;
const float id = d != 0.0f ? 1.0f / d : 0.0f;
const int sum = an_quant32(v, id, (int8_t*) (y + 36 * b + 4));
const uint16_t dh = an_f2h(d);
const uint16_t sh = an_f2h(d * (float) sum);
std::memcpy(y + 36 * b, &dh, 2);
std::memcpy(y + 36 * b + 2, &sh, 2);
}
}
// nearest_int of the product iscale * x as an integer quad, clamped above at 127: the magic-number rounding (add 1.5 * 2^23, then the low 23 bits
// of the float pattern minus 2^22), which equals round-half-even for |product| < 2^22 and gives the same wrapped values as the scalar reference
// for the huge or non-finite products a subnormal block maximum produces (iscale = -inf).
static inline int32x4_t an_q8k_code(float32x4_t xv, float iscale) {
const float32x4_t magic = vdupq_n_f32(12582912.0f);
#if defined(__clang__)
const float32x4_t p = vmulq_n_f32(xv, iscale); // the product is rounded to float32 first (a separate statement: no contraction)
const float32x4_t t = vaddq_f32(p, magic);
#else
UNUSED(nb);
quantize_q8_1_ref(x, y, k);
const float32x4_t t = vfmaq_n_f32(magic, xv, iscale); // fused: one rounding of iscale * x + 2^23 + 2^22 (what GCC's contraction gives the reference)
#endif
const int32x4_t q = vsubq_s32(vandq_s32(vreinterpretq_s32_f32(t), vdupq_n_s32(0x007fffff)), vdupq_n_s32(0x00400000));
return vminq_s32(q, vdupq_n_s32(127));
}
void quantize_q8_K(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT vy, int64_t k) {
assert(k % QK_K == 0);
const int64_t nb = k / QK_K;
block_q8_K* STRATA_RESTRICT y = (block_q8_K*) vy;
#if defined(__ARM_NEON)
const float32x4_t magic = vdupq_n_f32(12582912.f);
const int32x4_t mant = vdupq_n_s32(0x007fffff);
const int32x4_t off = vdupq_n_s32(0x00400000);
const int32x4_t c127 = vdupq_n_s32(127);
for (int64_t i = 0; i < nb; ++i, x += QK_K) {
if (i + 1 < nb) {
__builtin_prefetch(x + QK_K, 0, 0);
__builtin_prefetch(x + QK_K + 64, 0, 0);
}
// 4-way unrolled max(abs(x)) across all 256 floats
float32x4_t m0 = vdupq_n_f32(0.0f);
float32x4_t m1 = vdupq_n_f32(0.0f);
float32x4_t m2 = vdupq_n_f32(0.0f);
float32x4_t m3 = vdupq_n_f32(0.0f);
for (int j = 0; j < QK_K; j += 16) {
m0 = vmaxq_f32(m0, vabsq_f32(vld1q_f32(x + j + 0)));
m1 = vmaxq_f32(m1, vabsq_f32(vld1q_f32(x + j + 4)));
m2 = vmaxq_f32(m2, vabsq_f32(vld1q_f32(x + j + 8)));
m3 = vmaxq_f32(m3, vabsq_f32(vld1q_f32(x + j + 12)));
}
const float amax = vmaxvq_f32(vmaxq_f32(vmaxq_f32(m0, m1), vmaxq_f32(m2, m3)));
if (!amax) {
y[i].d = 0.0f;
std::memset(y[i].qs, 0, QK_K);
uint8_t* y = (uint8_t*) vy;
const int64_t nb = k / 256;
for (int64_t b = 0; b < nb; ++b) {
const float* xb = x + 256 * b;
uint8_t* yb = y + 292 * b;
int8_t* qs = (int8_t*) (yb + 4);
int16_t bs[16];
float32x4_t m = vdupq_n_f32(0.0f);
for (int i = 0; i < 64; ++i) m = vmaxq_f32(m, vabsq_f32(vld1q_f32(xb + 4 * i)));
const float amax = vmaxvq_f32(m);
if (amax == 0.0f) { // an all-zero block: d = 0 and zero codes; bsums is left as it is (the reference does not write it; callers hand in zeroed blocks)
const float zero = 0.0f;
std::memcpy(yb, &zero, 4);
std::memset(yb + 4, 0, 256);
continue;
}
// Exact first-occurrence sign scan matching q8_K_ref (`if (ax > amax)`)
// the first element of largest magnitude keeps its sign
float mx = 0.0f;
const float32x4_t vamax = vdupq_n_f32(amax);
for (int j = 0; j < QK_K; j += 4) {
const uint32x4_t eq = vceqq_f32(vabsq_f32(vld1q_f32(x + j)), vamax);
if (vmaxvq_u32(eq)) {
if (vgetq_lane_u32(eq, 0)) mx = x[j + 0];
else if (vgetq_lane_u32(eq, 1)) mx = x[j + 1];
else if (vgetq_lane_u32(eq, 2)) mx = x[j + 2];
else mx = x[j + 3];
const float32x4_t am = vdupq_n_f32(amax);
for (int i = 0; i < 64; ++i) {
const uint32x4_t eq = vceqq_f32(vabsq_f32(vld1q_f32(xb + 4 * i)), am);
if (vmaxvq_u32(eq) != 0) {
for (int l = 0; l < 4; ++l)
if (std::fabs(xb[4 * i + l]) == amax) { mx = xb[4 * i + l]; break; }
break;
}
}
const float iscale = -127.f / mx;
const float32x4_t vis = vdupq_n_f32(iscale);
// Quantize 16 floats per iteration (1 bsums sub-block)
for (int j = 0; j < QK_K; j += 16) {
int32x4_t v[4];
for (int q = 0; q < 4; ++q) {
const float32x4_t vx = vld1q_f32(x + j + 4 * q);
#if defined(__GNUC__) && !defined(__clang__)
// Matches GCC ggml-base (-ffp-contract=fast), which fuses nearest_int(iscale * x) into FMA
const float32x4_t t = vfmaq_f32(magic, vis, vx);
#else
// Matches Clang ggml-base (-ffp-contract=on), which rounds iscale * x before adding magic
float32x4_t p = vmulq_f32(vis, vx);
#if defined(__clang__)
__asm__("" : "+w"(p));
#endif
const float32x4_t t = vaddq_f32(p, magic);
#endif
v[q] = vminq_s32(vsubq_s32(vandq_s32(vreinterpretq_s32_f32(t), mant), off), c127);
const float iscale = -127.0f / mx;
for (int t = 0; t < 16; ++t) {
int32x4_t acc = vdupq_n_s32(0);
int16x8_t h[2];
for (int j = 0; j < 2; ++j) {
const int32x4_t a = an_q8k_code(vld1q_f32(xb + 16 * t + 8 * j), iscale);
const int32x4_t c = an_q8k_code(vld1q_f32(xb + 16 * t + 8 * j + 4), iscale);
acc = vaddq_s32(acc, vaddq_s32(a, c));
h[j] = vcombine_s16(vmovn_s32(a), vmovn_s32(c));
}
const int16x8_t n01 = vcombine_s16(vmovn_s32(v[0]), vmovn_s32(v[1]));
const int16x8_t n23 = vcombine_s16(vmovn_s32(v[2]), vmovn_s32(v[3]));
const int8x16_t b = vcombine_s8(vmovn_s16(n01), vmovn_s16(n23));
vst1q_s8(y[i].qs + j, b);
y[i].bsums[j / 16] = (int16_t) vaddlvq_s8(b);
vst1q_s8(qs + 16 * t, vcombine_s8(vmovn_s16(h[0]), vmovn_s16(h[1])));
bs[t] = (int16_t) vaddvq_s32(acc);
}
y[i].d = 1.0f / iscale;
const float d = 1.0f / iscale;
std::memcpy(yb, &d, 4);
std::memcpy(yb + 260, bs, 32);
}
#else
UNUSED(nb);
quantize_q8_K_ref(x, y, k);
#endif
}
#else // portable scalar versions (same results)
static inline float an_h2f(uint16_t h) { return fp16_to_fp32(h); }
static inline uint16_t an_f2h(float f) { return fp32_to_fp16(f); }
static inline int an_rne(float v) { return (int) std::nearbyintf(v); }
void quantize_q8_0(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT vy, int64_t k) {
uint8_t* y = (uint8_t*) vy;
for (int64_t b = 0; b < k / 32; ++b) {
const float* xb = x + 32 * b;
float amax = 0.0f;
for (int i = 0; i < 32; ++i) amax = std::fmax(amax, std::fabs(xb[i]));
const float d = amax / 127.0f;
const float id = d != 0.0f ? 1.0f / d : 0.0f;
const uint16_t dh = an_f2h(d);
std::memcpy(y + 34 * b, &dh, 2);
for (int i = 0; i < 32; ++i) y[34 * b + 2 + i] = (uint8_t) (int8_t) an_rne(xb[i] * id);
}
}
void quantize_q8_1(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT vy, int64_t k) {
uint8_t* y = (uint8_t*) vy;
for (int64_t b = 0; b < k / 32; ++b) {
const float* xb = x + 32 * b;
float amax = 0.0f;
for (int i = 0; i < 32; ++i) amax = std::fmax(amax, std::fabs(xb[i]));
const float d = amax / 127.0f;
const float id = d != 0.0f ? 1.0f / d : 0.0f;
int sum = 0;
for (int i = 0; i < 32; ++i) {
const int q = an_rne(xb[i] * id);
y[36 * b + 4 + i] = (uint8_t) (int8_t) q;
sum += q;
}
const uint16_t dh = an_f2h(d), sh = an_f2h(d * (float) sum);
std::memcpy(y + 36 * b, &dh, 2);
std::memcpy(y + 36 * b + 2, &sh, 2);
}
}
void quantize_q8_K(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT vy, int64_t k) {
uint8_t* y = (uint8_t*) vy;
for (int64_t b = 0; b < k / 256; ++b) {
const float* xb = x + 256 * b;
uint8_t* yb = y + 292 * b;
float amax = 0.0f, mx = 0.0f;
for (int i = 0; i < 256; ++i)
if (std::fabs(xb[i]) > amax) { amax = std::fabs(xb[i]); mx = xb[i]; }
if (amax == 0.0f) {
std::memset(yb, 0, 260);
continue;
}
const float iscale = -127.0f / mx;
int16_t bs[16] = {0};
for (int i = 0; i < 256; ++i) {
volatile float p = iscale * xb[i]; // rounded to float32 before the integer rounding
int q = an_rne(p);
if (q > 127) q = 127;
yb[4 + i] = (uint8_t) (int8_t) q;
bs[i / 16] = (int16_t) (bs[i / 16] + q);
}
const float d = 1.0f / iscale;
std::memcpy(yb, &d, 4);
std::memcpy(yb + 260, bs, 32);
}
}
#endif
+264 -238
View File
@@ -1,15 +1,20 @@
// Copyright (c) 2026 Niko1221 and the Strata contributors
// SPDX-License-Identifier: MIT
// src/quant/arm/dot_neon.cpp - the NEON tier's dot-kernel table and Strata's optimised kernels for Q8_0, Q4_K, Q5_K and IQ4_XS.
//
// Portions of this file are derived from ggml / llama.cpp (https://github.com/ggml-org/llama.cpp, pin 3cf03257f219afbe7334045ff7c6a06ac68c627d), MIT
// licence, Copyright (c) 2023-2026 The ggml authors (licence text: engine/third_party/ggml/LICENSE). Derived: the per-block unpack, scale and integer-
// chain code of dot_q4_K / q5_K / iq4_xs / q8_0 _opt, which keep the integer steps, constants and float order of ggml-cpu/arch/arm/quants.c (about 90 of
// 280 lines). The vector accumulation and the prefetching are ours.
// The rest is Copyright (c) 2026 Niko1221 and the Strata contributors, MIT.
// Compiled with -march=armv8.2-a+dotprod+fp16+i8mm (no SVE), GCC or Apple Clang (cmake/backends/quant.cmake). The namespace neon holds the
// reference kernels dot_<N> (arm_dots.inc, with arm_helpers.inc and arm_tables.inc: included here, not part of this file) which are the bit oracles
// of the four optimised kernels below. The optimised kernels give the oracle's bits exactly: the integer sums are exact, and the float steps are
// the oracle's, found by probing it (tests/clean_p2/neon_probe_*.cpp, neon_model_*.cpp):
//
// src/quant/arm/dot_neon.cpp - the Neon contract: ggml-cpu's dot products + ARM64 NEON dotprod vector-accumulated
// and L1-prefetched optimizations for Q4_K, Q5_K, Q6_K, Q8_0, IQ4_XS, and IQ3_XXS (DGX Spark GB10 & Apple Silicon).
// Compiled with the flags of cmake/backends/quant.cmake (armv8.2-a+dotprod+fp16+i8mm, no SVE).
// Q8_0 x Q8_0 blocks are taken in pairs, the even block into accumulator A0 and the odd block into A1, each a float32x4 over the four int32
// lanes of the block (lane l: elements 4l..4l+3 and 16+4l..16+4l+3): A_k[l] = fma(d, float(I_l), A_k[l]) with d = dw * da;
// result = (A0[0]+A0[1])+(A0[2]+A0[3]) + the same for A1; a last odd block is one scalar step s = fma(d, float(whole block sum), s).
// Q4_K x Q8_K one scalar chain over the blocks: s = fma(-dmin_b, float(summin), s); then s = fma(d_b, float(sumi), s), with d_b = yd * dx,
// dmin_b = yd * dxmin, sumi = sum sc_j I_j and summin = sum m_j (bsums[2j] + bsums[2j+1]) in exact int32.
// Q5_K x Q8_K per block q = fma(d_b, float(sumi), -(dmin_b * float(summin))), then s = s + q along one chain.
// IQ4_XS x Q8_K one scalar chain: s = fma(d_b, float(sumi), s), sumi = sum (ls_ib - 32) * sum kvalues[nibble] qa.
//
// Layouts (FORMAT-SPEC): Q8_0 34 bytes (d half, qs[32]); Q8_K 292 bytes (d float, qs[256], bsums[16] int16 at 260); Q4_K 144 (d, dmin, scales[12], qs[128]);
// Q5_K 176 (d, dmin, scales[12], qh[32], qs[128]); IQ4_XS 136 (d, scales_h u16, scales_l[4], qs[128]).
#include "tier_common.hpp"
#include "../generic.hpp"
@@ -25,238 +30,239 @@ namespace neon {
#if defined(__ARM_NEON) && defined(__ARM_FEATURE_DOTPROD)
// Vector-accumulated NEON dotprod Q4_K x Q8_K: eliminates 7 inner-loop vaddvq_s32 stalls per superblock (bit-exact).
void dot_q4_K_q8_K_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
assert(n % QK_K == 0);
const block_q4_K* STRATA_RESTRICT x = (const block_q4_K*) vx;
const block_q8_K* STRATA_RESTRICT y = (const block_q8_K*) vy;
const int nb = n / QK_K;
namespace {
static constexpr uint32_t kmask1 = 0x3f3f3f3f;
static constexpr uint32_t kmask2 = 0x0f0f0f0f;
static constexpr uint32_t kmask3 = 0x03030303;
uint32_t utmp[4];
const uint8x16_t m4b = vdupq_n_u8(0x0f);
const int32x4_t mzero = vdupq_n_s32(0);
float sumf = 0.0f;
for (int i = 0; i < nb; ++i) {
if (i + 2 < nb) {
__builtin_prefetch(&x[i + 2], 0, 0);
__builtin_prefetch(&y[i + 2], 0, 0);
}
const float d = y[i].d * h2f(x[i].d);
const float dmin = y[i].d * h2f(x[i].dmin);
const int16x8_t q8sums = vpaddq_s16(vld1q_s16(y[i].bsums), vld1q_s16(y[i].bsums + 8));
std::memcpy(utmp, x[i].scales, 12);
uint32x2_t mins8 = {0, 0};
mins8 = vset_lane_u32(utmp[1] & kmask1, mins8, 0);
mins8 = vset_lane_u32(((utmp[2] >> 4) & kmask2) | (((utmp[1] >> 6) & kmask3) << 4), mins8, 1);
utmp[1] = (utmp[2] & kmask2) | (((utmp[0] >> 6) & kmask3) << 4);
utmp[0] &= kmask1;
const int16x8_t mins = vreinterpretq_s16_u16(vmovl_u8(vreinterpret_u8_u32(mins8)));
const int32x4_t prod = vaddq_s32(vmull_s16(vget_low_s16(q8sums), vget_low_s16(mins)),
vmull_s16(vget_high_s16(q8sums), vget_high_s16(mins)));
sumf -= dmin * vaddvq_s32(prod);
const uint8_t* scales = (const uint8_t*) utmp;
const uint8_t* STRATA_RESTRICT q4 = x[i].qs;
const int8_t* STRATA_RESTRICT q8 = y[i].qs;
int32x4_t vsum1 = mzero;
int32x4_t vsum2 = mzero;
for (int j = 0; j < QK_K / 64; ++j) {
const uint8x16x2_t q4bits = vld1q_u8_x2(q4);
q4 += 32;
const int8x16x4_t q8b = vld1q_s8_x4(q8);
q8 += 64;
const int8x16_t q4l0 = vreinterpretq_s8_u8(vandq_u8(q4bits.val[0], m4b));
const int8x16_t q4l1 = vreinterpretq_s8_u8(vandq_u8(q4bits.val[1], m4b));
const int8x16_t q4h0 = vreinterpretq_s8_u8(vshrq_n_u8(q4bits.val[0], 4));
const int8x16_t q4h1 = vreinterpretq_s8_u8(vshrq_n_u8(q4bits.val[1], 4));
const int32x4_t p1 = vdotq_s32(vdotq_s32(mzero, q4l0, q8b.val[0]), q4l1, q8b.val[1]);
const int32x4_t p2 = vdotq_s32(vdotq_s32(mzero, q4h0, q8b.val[2]), q4h1, q8b.val[3]);
vsum1 = vmlaq_n_s32(vsum1, p1, (int32_t) scales[2 * j + 0]);
vsum2 = vmlaq_n_s32(vsum2, p2, (int32_t) scales[2 * j + 1]);
}
sumf += d * (float) (vaddvq_s32(vsum1) + vaddvq_s32(vsum2));
}
*s = sumf;
inline uint16_t dn_u16(const uint8_t* p) {
uint16_t t;
std::memcpy(&t, p, sizeof t);
return t;
}
inline float dn_h2f(const uint8_t* p) {
__fp16 t;
std::memcpy(&t, p, sizeof t);
return (float) t;
}
inline float dn_f32(const uint8_t* p) {
float f;
std::memcpy(&f, p, sizeof f);
return f;
}
// (x0 + x1) + (x2 + x3)
inline float dn_hsum(float32x4_t x) {
const float32x2_t p = vpadd_f32(vget_low_f32(x), vget_high_f32(x));
return vget_lane_f32(p, 0) + vget_lane_f32(p, 1);
}
// exact int32 dot of 32 signed bytes: one int32x4 whose lane l sums the products of bytes 4l..4l+3 of both halves
inline int32x4_t dn_dot32(const int8_t* w, const int8_t* a) {
const int8x16x2_t wv = vld1q_s8_x2(w), av = vld1q_s8_x2(a);
return vdotq_s32(vdotq_s32(vdupq_n_s32(0), wv.val[0], av.val[0]), wv.val[1], av.val[1]);
}
// the same for two 16-byte halves already loaded
inline int32x4_t dn_dot32v(int8x16_t w0, int8x16_t w1, const int8_t* a) {
return vdotq_s32(vdotq_s32(vdupq_n_s32(0), w0, vld1q_s8(a)), w1, vld1q_s8(a + 16));
}
// Vector-accumulated NEON dotprod Q5_K x Q8_K (bit-exact).
void dot_q5_K_q8_K_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
assert(n % QK_K == 0);
const block_q5_K* STRATA_RESTRICT x = (const block_q5_K*) vx;
const block_q8_K* STRATA_RESTRICT y = (const block_q8_K*) vy;
const int nb = n / QK_K;
const int8_t dn_kvalues[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113};
static constexpr uint32_t kmask1 = 0x3f3f3f3f;
static constexpr uint32_t kmask2 = 0x0f0f0f0f;
static constexpr uint32_t kmask3 = 0x03030303;
uint32_t utmp[4];
// the eight 6-bit scales and minimums of a Q4_K / Q5_K block (scales[12] at s; 12 bytes are read):
// scl = int32 sc[0..3], sch = int32 sc[4..7], mn = int16 m[0..7]. The bit shuffling is done on 32-bit integers (scalar pipes), the widening
// is three table lookups.
const uint8_t dn_idx_scl[16] = {0, 255, 255, 255, 1, 255, 255, 255, 2, 255, 255, 255, 3, 255, 255, 255};
const uint8_t dn_idx_sch[16] = {8, 255, 255, 255, 9, 255, 255, 255, 10, 255, 255, 255, 11, 255, 255, 255};
const uint8_t dn_idx_mn[16] = {4, 255, 5, 255, 6, 255, 7, 255, 12, 255, 13, 255, 14, 255, 15, 255};
const uint8x16_t m4b = vdupq_n_u8(0x0f);
const uint8x16_t mone = vdupq_n_u8(1);
const uint8x16_t mtwo = vdupq_n_u8(2);
const int32x4_t mzero = vdupq_n_s32(0);
float sumf = 0.0f;
for (int i = 0; i < nb; ++i) {
if (i + 2 < nb) {
__builtin_prefetch(&x[i + 2], 0, 0);
__builtin_prefetch(&y[i + 2], 0, 0);
}
const float d = y[i].d * h2f(x[i].d);
const float dmin = y[i].d * h2f(x[i].dmin);
const int16x8_t q8sums = vpaddq_s16(vld1q_s16(y[i].bsums), vld1q_s16(y[i].bsums + 8));
std::memcpy(utmp, x[i].scales, 12);
utmp[3] = ((utmp[2] >> 4) & kmask2) | (((utmp[1] >> 6) & kmask3) << 4);
const uint32_t uaux = utmp[1] & kmask1;
utmp[1] = (utmp[2] & kmask2) | (((utmp[0] >> 6) & kmask3) << 4);
utmp[2] = uaux;
utmp[0] &= kmask1;
const uint8x8_t mins8 = vld1_u8((const uint8_t*) utmp + 8);
const int16x8_t mins = vreinterpretq_s16_u16(vmovl_u8(mins8));
const int32x4_t prod = vaddq_s32(vmull_s16(vget_low_s16(q8sums), vget_low_s16(mins)),
vmull_s16(vget_high_s16(q8sums), vget_high_s16(mins)));
const int32_t sumi_mins = vaddvq_s32(prod);
const uint8_t* scales = (const uint8_t*) utmp;
const uint8_t* STRATA_RESTRICT q5 = x[i].qs;
const int8_t* STRATA_RESTRICT q8 = y[i].qs;
uint8x16x2_t qhbits = vld1q_u8_x2(x[i].qh);
int32x4_t vsum1 = mzero;
int32x4_t vsum2 = mzero;
for (int j = 0; j < QK_K / 64; ++j) {
const uint8x16x2_t q5bits = vld1q_u8_x2(q5);
q5 += 32;
const int8x16x4_t q8b = vld1q_s8_x4(q8);
q8 += 64;
const uint8x16_t h0 = vshlq_n_u8(vandq_u8(mone, qhbits.val[0]), 4);
const uint8x16_t h1 = vshlq_n_u8(vandq_u8(mone, qhbits.val[1]), 4);
const uint8x16_t h2 = vshlq_n_u8(vandq_u8(mtwo, qhbits.val[0]), 3);
const uint8x16_t h3 = vshlq_n_u8(vandq_u8(mtwo, qhbits.val[1]), 3);
qhbits.val[0] = vshrq_n_u8(qhbits.val[0], 2);
qhbits.val[1] = vshrq_n_u8(qhbits.val[1], 2);
const int8x16_t q5_0 = vreinterpretq_s8_u8(vorrq_u8(vandq_u8(q5bits.val[0], m4b), h0));
const int8x16_t q5_1 = vreinterpretq_s8_u8(vorrq_u8(vandq_u8(q5bits.val[1], m4b), h1));
const int8x16_t q5_2 = vreinterpretq_s8_u8(vorrq_u8(vshrq_n_u8(q5bits.val[0], 4), h2));
const int8x16_t q5_3 = vreinterpretq_s8_u8(vorrq_u8(vshrq_n_u8(q5bits.val[1], 4), h3));
const int32x4_t p1 = vdotq_s32(vdotq_s32(mzero, q5_0, q8b.val[0]), q5_1, q8b.val[1]);
const int32x4_t p2 = vdotq_s32(vdotq_s32(mzero, q5_2, q8b.val[2]), q5_3, q8b.val[3]);
vsum1 = vmlaq_n_s32(vsum1, p1, (int32_t) scales[2 * j + 0]);
vsum2 = vmlaq_n_s32(vsum2, p2, (int32_t) scales[2 * j + 1]);
}
const int32_t sumi = vaddvq_s32(vaddq_s32(vsum1, vsum2));
sumf += d * (float) sumi - dmin * (float) sumi_mins;
}
*s = sumf;
inline void dn_scales_k(const uint8_t* s, int32x4_t& scl, int32x4_t& sch, int16x8_t& mn) {
uint32_t u0, u1, u2;
std::memcpy(&u0, s, 4);
std::memcpy(&u1, s + 4, 4);
std::memcpy(&u2, s + 8, 4);
const uint32_t k6 = 0x3f3f3f3fu, k4 = 0x0f0f0f0fu, k2 = 0x03030303u;
const uint32_t sc_lo = u0 & k6, mn_lo = u1 & k6;
const uint32_t sc_hi = (u2 & k4) | (((u0 >> 6) & k2) << 4);
const uint32_t mn_hi = ((u2 >> 4) & k4) | (((u1 >> 6) & k2) << 4);
// bytes [sc0..3 | m0..3 | sc4..7 | m4..7]
const uint8x16_t v = vreinterpretq_u8_u64(vcombine_u64(vcreate_u64((uint64_t) sc_lo | ((uint64_t) mn_lo << 32)), vcreate_u64((uint64_t) sc_hi | ((uint64_t) mn_hi << 32))));
scl = vreinterpretq_s32_u8(vqtbl1q_u8(v, vld1q_u8(dn_idx_scl)));
sch = vreinterpretq_s32_u8(vqtbl1q_u8(v, vld1q_u8(dn_idx_sch)));
mn = vreinterpretq_s16_u8(vqtbl1q_u8(v, vld1q_u8(dn_idx_mn)));
}
// Vector-accumulated NEON dotprod IQ4_XS x Q8_K (bit-exact).
void dot_iq4_xs_q8_K_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
assert(n % QK_K == 0);
const block_iq4_xs* STRATA_RESTRICT x = (const block_iq4_xs*) vx;
const block_q8_K* STRATA_RESTRICT y = (const block_q8_K*) vy;
const int nb = n / QK_K;
const int8x16_t values = vld1q_s8(kvalues_iq4nl);
const uint8x16_t m4b = vdupq_n_u8(0x0f);
const int32x4_t mzero = vdupq_n_s32(0);
float sumf = 0.0f;
for (int ibl = 0; ibl < nb; ++ibl) {
if (ibl + 2 < nb) {
__builtin_prefetch(&x[ibl + 2], 0, 0);
__builtin_prefetch(&y[ibl + 2], 0, 0);
}
const int8_t* STRATA_RESTRICT q8 = y[ibl].qs;
const uint8_t* STRATA_RESTRICT q4 = x[ibl].qs;
uint16_t h = x[ibl].scales_h;
int32x4_t vsum1 = mzero;
int32x4_t vsum2 = mzero;
for (int ib = 0; ib < QK_K / 64; ++ib) {
const uint8x16x2_t q4bits = vld1q_u8_x2(q4);
q4 += 32;
const int8x16x4_t q8b = vld1q_s8_x4(q8);
q8 += 64;
const int8x16_t q4_0 = vqtbl1q_s8(values, vandq_u8(q4bits.val[0], m4b));
const int8x16_t q4_1 = vqtbl1q_s8(values, vshrq_n_u8(q4bits.val[0], 4));
const int8x16_t q4_2 = vqtbl1q_s8(values, vandq_u8(q4bits.val[1], m4b));
const int8x16_t q4_3 = vqtbl1q_s8(values, vshrq_n_u8(q4bits.val[1], 4));
const int32x4_t p1 = vdotq_s32(vdotq_s32(mzero, q4_0, q8b.val[0]), q4_1, q8b.val[1]);
const int32x4_t p2 = vdotq_s32(vdotq_s32(mzero, q4_2, q8b.val[2]), q4_3, q8b.val[3]);
const int32_t ls1 = ((x[ibl].scales_l[ib] & 0xf) | ((h << 4) & 0x30)) - 32;
const int32_t ls2 = ((x[ibl].scales_l[ib] >> 4) | ((h << 2) & 0x30)) - 32;
h >>= 4;
vsum1 = vmlaq_n_s32(vsum1, p1, ls1);
vsum2 = vmlaq_n_s32(vsum2, p2, ls2);
}
sumf += h2f(x[ibl].d) * y[ibl].d * (float) (vaddvq_s32(vsum1) + vaddvq_s32(vsum2));
}
*s = sumf;
// sum_j m_j * (bsums[2j] + bsums[2j+1]), exact, as four int32 partial sums
inline int32x4_t dn_summin(int16x8_t mn, const uint8_t* ybsums) {
const int16x8_t lo = vreinterpretq_s16_u8(vld1q_u8(ybsums));
const int16x8_t hi = vreinterpretq_s16_u8(vld1q_u8(ybsums + 16));
const int16x8_t pair = vpaddq_s16(lo, hi); // 8 sums of two bsums (|value| <= 4064)
return vmlal_s16(vmull_s16(vget_low_s16(pair), vget_low_s16(mn)), vget_high_s16(pair), vget_high_s16(mn));
}
// (sum of a, sum of b) of two int32x4 as a float pair
inline float32x2_t dn_sums2f(int32x4_t a, int32x4_t b) {
const int32x4_t r = vpaddq_s32(a, b);
return vcvt_f32_s32(vpadd_s32(vget_low_s32(r), vget_high_s32(r)));
}
// Prefetched NEON dotprod Q8_0 x Q8_0 (bit-exact).
} // namespace
// one pair of blocks (even block at index ib, odd block at ib + 1): the four half scales are loaded as lanes of one vector and converted together,
// d = (dw0 * da0, dw1 * da1), then each block's four int32 lane sums are fused into its accumulator
#define DN_Q80_PAIR(IB) \
{ \
const uint8_t* w0 = w + 34 * (IB); \
const uint8_t* a0 = a + 34 * (IB); \
const uint8_t* w1 = w0 + 34; \
const uint8_t* a1 = a0 + 34; \
uint16x4_t hs = vld1_lane_u16((const uint16_t*) w0, vdup_n_u16(0), 0); \
hs = vld1_lane_u16((const uint16_t*) w1, hs, 1); \
hs = vld1_lane_u16((const uint16_t*) a0, hs, 2); \
hs = vld1_lane_u16((const uint16_t*) a1, hs, 3); \
const float32x4_t f = vcvt_f32_f16(vreinterpret_f16_u16(hs)); \
const float32x2_t d = vmul_f32(vget_low_f32(f), vget_high_f32(f)); \
const int32x4_t p0 = dn_dot32((const int8_t*) (w0 + 2), (const int8_t*) (a0 + 2)); \
const int32x4_t p1 = dn_dot32((const int8_t*) (w1 + 2), (const int8_t*) (a1 + 2)); \
acc0 = vfmaq_lane_f32(acc0, vcvtq_f32_s32(p0), d, 0); \
acc1 = vfmaq_lane_f32(acc1, vcvtq_f32_s32(p1), d, 1); \
}
void dot_q8_0_q8_0_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
assert(n % QK8_0 == 0);
const int nb = n / QK8_0;
const block_q8_0* STRATA_RESTRICT x = (const block_q8_0*) vx;
const block_q8_0* STRATA_RESTRICT y = (const block_q8_0*) vy;
float32x4_t sumv0 = vdupq_n_f32(0.0f);
float32x4_t sumv1 = vdupq_n_f32(0.0f);
const int32x4_t mzero = vdupq_n_s32(0);
const uint8_t* w = (const uint8_t*) vx;
const uint8_t* a = (const uint8_t*) vy;
const int nb = n / 32;
float32x4_t acc0 = vdupq_n_f32(0.0f), acc1 = vdupq_n_f32(0.0f);
int ib = 0;
for (; ib + 1 < nb; ib += 2) {
if (ib + 4 < nb) {
__builtin_prefetch(&x[ib + 4], 0, 0);
__builtin_prefetch(&y[ib + 4], 0, 0);
}
const block_q8_0* STRATA_RESTRICT x0 = &x[ib + 0];
const block_q8_0* STRATA_RESTRICT x1 = &x[ib + 1];
const block_q8_0* STRATA_RESTRICT y0 = &y[ib + 0];
const block_q8_0* STRATA_RESTRICT y1 = &y[ib + 1];
const int8x16_t x0_0 = vld1q_s8(x0->qs);
const int8x16_t x0_1 = vld1q_s8(x0->qs + 16);
const int8x16_t x1_0 = vld1q_s8(x1->qs);
const int8x16_t x1_1 = vld1q_s8(x1->qs + 16);
const int8x16_t y0_0 = vld1q_s8(y0->qs);
const int8x16_t y0_1 = vld1q_s8(y0->qs + 16);
const int8x16_t y1_0 = vld1q_s8(y1->qs);
const int8x16_t y1_1 = vld1q_s8(y1->qs + 16);
sumv0 = vmlaq_n_f32(sumv0, vcvtq_f32_s32(vaddq_s32(vdotq_s32(mzero, x0_0, y0_0), vdotq_s32(mzero, x0_1, y0_1))),
h2f(x0->d) * h2f(y0->d));
sumv1 = vmlaq_n_f32(sumv1, vcvtq_f32_s32(vaddq_s32(vdotq_s32(mzero, x1_0, y1_0), vdotq_s32(mzero, x1_1, y1_1))),
h2f(x1->d) * h2f(y1->d));
for (; ib + 7 < nb; ib += 8) { // four pairs per turn (the accumulators still see the blocks in order)
DN_Q80_PAIR(ib)
DN_Q80_PAIR(ib + 2)
DN_Q80_PAIR(ib + 4)
DN_Q80_PAIR(ib + 6)
}
float sumf = vaddvq_f32(sumv0) + vaddvq_f32(sumv1);
for (; ib + 3 < nb; ib += 4) {
DN_Q80_PAIR(ib)
DN_Q80_PAIR(ib + 2)
}
for (; ib + 1 < nb; ib += 2) DN_Q80_PAIR(ib)
float sum = dn_hsum(acc0) + dn_hsum(acc1);
for (; ib < nb; ++ib) {
int sumi = 0;
for (int j = 0; j < QK8_0; ++j) sumi += x[ib].qs[j] * y[ib].qs[j];
sumf += sumi * (h2f(x[ib].d) * h2f(y[ib].d));
const uint8_t* w0 = w + 34 * ib;
const uint8_t* a0 = a + 34 * ib;
const int32_t i = vaddvq_s32(dn_dot32((const int8_t*) (w0 + 2), (const int8_t*) (a0 + 2)));
sum = std::fmaf(dn_h2f(w0) * dn_h2f(a0), (float) i, sum);
}
*s = sumf;
*s = sum;
}
// weights of one 64-element group g of a Q4_K block: low nibbles are sub-block 2g, high nibbles 2g+1
#define DN_Q4K_GROUP(G, SCV, LA, LB) \
{ \
const uint8x16_t b0 = vld1q_u8(qs + 32 * (G)), b1 = vld1q_u8(qs + 32 * (G) + 16); \
const int8_t* qg = qa + 64 * (G); \
const int32x4_t d_lo = dn_dot32v(vreinterpretq_s8_u8(vandq_u8(b0, m4)), vreinterpretq_s8_u8(vandq_u8(b1, m4)), qg); \
const int32x4_t d_hi = dn_dot32v(vreinterpretq_s8_u8(vshrq_n_u8(b0, 4)), vreinterpretq_s8_u8(vshrq_n_u8(b1, 4)), qg + 32); \
isum = vmlaq_laneq_s32(isum, d_lo, SCV, LA); \
isum = vmlaq_laneq_s32(isum, d_hi, SCV, LB); \
}
void dot_q4_K_q8_K_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
const uint8_t* w = (const uint8_t*) vx;
const uint8_t* y = (const uint8_t*) vy;
const int nb = n / 256;
const uint8x16_t m4 = vdupq_n_u8(0x0f);
float sum = 0.0f;
for (int ib = 0; ib < nb; ++ib) {
const uint8_t* wb = w + 144 * ib;
const uint8_t* yb = y + 292 * ib;
int32x4_t scl, sch;
int16x8_t mn;
dn_scales_k(wb + 4, scl, sch, mn);
const int8_t* qa = (const int8_t*) (yb + 4);
const uint8_t* qs = wb + 16;
int32x4_t isum = vdupq_n_s32(0);
DN_Q4K_GROUP(0, scl, 0, 1)
DN_Q4K_GROUP(1, scl, 2, 3)
DN_Q4K_GROUP(2, sch, 0, 1)
DN_Q4K_GROUP(3, sch, 2, 3)
const float32x2_t fs = dn_sums2f(isum, dn_summin(mn, yb + 260)); // (sumi, summin) as floats
const float yd = dn_f32(yb);
const float d = yd * dn_h2f(wb);
const float dm = yd * dn_h2f(wb + 2);
sum = std::fmaf(-dm, vget_lane_f32(fs, 1), sum);
sum = std::fmaf(d, vget_lane_f32(fs, 0), sum);
}
*s = sum;
}
// the fifth bit of sub-block J moved to bit 4 of each byte of qh, merged into the nibbles with a bit select
#define DN_Q5K_GROUP(G, SCV, LA, LB) \
{ \
const uint8x16_t b0 = vld1q_u8(qs + 32 * (G)), b1 = vld1q_u8(qs + 32 * (G) + 16); \
const int8x16_t sa = vdupq_n_s8((int8_t) (4 - 2 * (G))), sb = vdupq_n_s8((int8_t) (3 - 2 * (G))); \
const int8x16_t lo0 = vreinterpretq_s8_u8(vbslq_u8(m10, vshlq_u8(qh0, sa), vandq_u8(b0, m4))); \
const int8x16_t lo1 = vreinterpretq_s8_u8(vbslq_u8(m10, vshlq_u8(qh1, sa), vandq_u8(b1, m4))); \
const int8x16_t hi0 = vreinterpretq_s8_u8(vbslq_u8(m10, vshlq_u8(qh0, sb), vshrq_n_u8(b0, 4))); \
const int8x16_t hi1 = vreinterpretq_s8_u8(vbslq_u8(m10, vshlq_u8(qh1, sb), vshrq_n_u8(b1, 4))); \
const int8_t* qg = qa + 64 * (G); \
const int32x4_t d_lo = dn_dot32v(lo0, lo1, qg); \
const int32x4_t d_hi = dn_dot32v(hi0, hi1, qg + 32); \
isum = vmlaq_laneq_s32(isum, d_lo, SCV, LA); \
isum = vmlaq_laneq_s32(isum, d_hi, SCV, LB); \
}
void dot_q5_K_q8_K_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
const uint8_t* w = (const uint8_t*) vx;
const uint8_t* y = (const uint8_t*) vy;
const int nb = n / 256;
const uint8x16_t m4 = vdupq_n_u8(0x0f);
const uint8x16_t m10 = vdupq_n_u8(0x10);
float sum = 0.0f;
for (int ib = 0; ib < nb; ++ib) {
const uint8_t* wb = w + 176 * ib;
const uint8_t* yb = y + 292 * ib;
int32x4_t scl, sch;
int16x8_t mn;
dn_scales_k(wb + 4, scl, sch, mn);
const int8_t* qa = (const int8_t*) (yb + 4);
const uint8x16_t qh0 = vld1q_u8(wb + 16), qh1 = vld1q_u8(wb + 32);
const uint8_t* qs = wb + 48;
int32x4_t isum = vdupq_n_s32(0);
DN_Q5K_GROUP(0, scl, 0, 1)
DN_Q5K_GROUP(1, scl, 2, 3)
DN_Q5K_GROUP(2, sch, 0, 1)
DN_Q5K_GROUP(3, sch, 2, 3)
const float32x2_t fs = dn_sums2f(isum, dn_summin(mn, yb + 260)); // (sumi, summin) as floats
const float yd = dn_f32(yb);
const float d = yd * dn_h2f(wb);
const float dm = yd * dn_h2f(wb + 2);
const float pm = dm * vget_lane_f32(fs, 1); // rounded first
sum = sum + std::fmaf(d, vget_lane_f32(fs, 0), -pm);
}
*s = sum;
}
void dot_iq4_xs_q8_K_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
const uint8_t* w = (const uint8_t*) vx;
const uint8_t* y = (const uint8_t*) vy;
const int nb = n / 256;
const uint8x16_t m4 = vdupq_n_u8(0x0f);
const int8x16_t kv = vld1q_s8(dn_kvalues);
float sum = 0.0f;
for (int ib = 0; ib < nb; ++ib) {
const uint8_t* wb = w + 136 * ib;
const uint8_t* yb = y + 292 * ib;
const uint16_t sh = (uint16_t) (wb[2] | (wb[3] << 8));
const uint8_t* sl = wb + 4;
const uint8_t* qs = wb + 8;
const int8_t* qa = (const int8_t*) (yb + 4);
int32x4_t isum = vdupq_n_s32(0);
for (int g = 0; g < 8; ++g) {
const int ls = ((sl[g >> 1] >> (4 * (g & 1))) & 15) | (((sh >> (2 * g)) & 3) << 4);
const uint8x16_t q = vld1q_u8(qs + 16 * g);
const int8x16_t lo = vqtbl1q_s8(kv, vandq_u8(q, m4));
const int8x16_t hi = vqtbl1q_s8(kv, vshrq_n_u8(q, 4));
isum = vmlaq_n_s32(isum, dn_dot32v(lo, hi, qa + 32 * g), ls - 32);
}
const int32_t sumi = vaddvq_s32(isum);
const float d = dn_f32(yb) * dn_h2f(wb);
sum = std::fmaf(d, (float) sumi, sum);
}
*s = sum;
}
#endif // __ARM_NEON && __ARM_FEATURE_DOTPROD
@@ -264,22 +270,42 @@ void dot_q8_0_q8_0_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTR
} // namespace neon
namespace {
#define ENTRY(T, ACT, NAME) {neon::dot_##NAME, Type::T, Type::ACT, Arith::Neon, Isa::Neon, "neon_" #NAME}
#define ENTRY(W, A, N) {neon::dot_##N, Type::W, Type::A, Arith::Neon, Isa::Neon, "neon_" #N}
#if defined(__ARM_NEON) && defined(__ARM_FEATURE_DOTPROD)
#define ENTRY_OPT(T, ACT, NAME) {neon::dot_##NAME##_opt, Type::T, Type::ACT, Arith::Neon, Isa::Neon, "neon_" #NAME}
#define ENTRY_OPT(W, A, N) {neon::dot_##N##_opt, Type::W, Type::A, Arith::Neon, Isa::Neon, "neon_" #N}
#else
#define ENTRY_OPT(T, ACT, NAME) ENTRY(T, ACT, NAME)
#define ENTRY_OPT(W, A, N) ENTRY(W, A, N)
#endif
const DotKernel kTable[] = {
ENTRY(Q2_0, Q8_0, q2_0_q8_0), ENTRY(Q4_0, Q8_0, q4_0_q8_0), ENTRY(Q4_1, Q8_1, q4_1_q8_1), ENTRY(Q5_0, Q8_0, q5_0_q8_0),
ENTRY(Q5_1, Q8_1, q5_1_q8_1), ENTRY_OPT(Q8_0, Q8_0, q8_0_q8_0), ENTRY(IQ4_NL, Q8_0, iq4_nl_q8_0), ENTRY(MXFP4, Q8_0, mxfp4_q8_0),
ENTRY(NVFP4, Q8_0, nvfp4_q8_0), ENTRY(Q2_K, Q8_K, q2_K_q8_K), ENTRY(Q3_K, Q8_K, q3_K_q8_K), ENTRY_OPT(Q4_K, Q8_K, q4_K_q8_K),
ENTRY_OPT(Q5_K, Q8_K, q5_K_q8_K), ENTRY(Q6_K, Q8_K, q6_K_q8_K), ENTRY(IQ1_S, Q8_K, iq1_s_q8_K), ENTRY(IQ1_M, Q8_K, iq1_m_q8_K),
ENTRY(IQ2_XXS, Q8_K, iq2_xxs_q8_K), ENTRY(IQ2_XS, Q8_K, iq2_xs_q8_K), ENTRY(IQ2_S, Q8_K, iq2_s_q8_K),
ENTRY(IQ3_XXS, Q8_K, iq3_xxs_q8_K), ENTRY(IQ3_S, Q8_K, iq3_s_q8_K), ENTRY_OPT(IQ4_XS, Q8_K, iq4_xs_q8_K),
ENTRY(Q2_0, Q8_0, q2_0_q8_0),
ENTRY(Q4_0, Q8_0, q4_0_q8_0),
ENTRY(Q4_1, Q8_1, q4_1_q8_1),
ENTRY(Q5_0, Q8_0, q5_0_q8_0),
ENTRY(Q5_1, Q8_1, q5_1_q8_1),
ENTRY(Q8_0, Q8_0, q8_0_q8_0), // the oracle: the optimised kernel measured 2 to 4 % slower than it on an M4
ENTRY(IQ4_NL, Q8_0, iq4_nl_q8_0),
ENTRY(MXFP4, Q8_0, mxfp4_q8_0),
ENTRY(NVFP4, Q8_0, nvfp4_q8_0),
ENTRY(Q2_K, Q8_K, q2_K_q8_K),
ENTRY(Q3_K, Q8_K, q3_K_q8_K),
ENTRY_OPT(Q4_K, Q8_K, q4_K_q8_K),
ENTRY_OPT(Q5_K, Q8_K, q5_K_q8_K),
ENTRY(Q6_K, Q8_K, q6_K_q8_K),
ENTRY(IQ1_S, Q8_K, iq1_s_q8_K),
ENTRY(IQ1_M, Q8_K, iq1_m_q8_K),
ENTRY(IQ2_XXS, Q8_K, iq2_xxs_q8_K),
ENTRY(IQ2_XS, Q8_K, iq2_xs_q8_K),
ENTRY(IQ2_S, Q8_K, iq2_s_q8_K),
ENTRY(IQ3_XXS, Q8_K, iq3_xxs_q8_K),
ENTRY(IQ3_S, Q8_K, iq3_s_q8_K),
ENTRY_OPT(IQ4_XS, Q8_K, iq4_xs_q8_K),
};
#undef ENTRY_OPT
#undef ENTRY
#undef ENTRY_OPT
} // namespace
DotTable neon_dot_table() noexcept { return {kTable, (int) (sizeof kTable / sizeof kTable[0])}; }
+106 -158
View File
@@ -1,194 +1,142 @@
// Copyright (c) 2026 Niko1221 and the Strata contributors
// SPDX-License-Identifier: MIT
// src/quant/x86/act_avx512.cpp - AVX-512 activation quantisers of the Avx2 contract.
//
// Portions of this file are derived from ggml / llama.cpp (https://github.com/ggml-org/llama.cpp, pin 3cf03257f219afbe7334045ff7c6a06ac68c627d), MIT
// licence, Copyright (c) 2023-2026 The ggml authors (licence text: engine/third_party/ggml/LICENSE). Derived: the block steps of the Q8_0, Q8_1 and Q8_K
// activation quantizers (max-abs reduction, scale, sub-block sums) of ggml-cpu/arch/x86/quants.c and ggml-quants.c (about 25 of 200 lines). The AVX-512
// vectorisation is ours.
// The rest is Copyright (c) 2026 Niko1221 and the Strata contributors, MIT.
//
// src/quant/x86/act_avx512.cpp - isolated AVX-512 activation quantizers for the Avx2 contract (Q8_0, Q8_1, Q8_K).
// Compiled strictly in this AVX-512 TU so act_avx2.cpp emits 0 EVEX/ZMM instructions (safe for Alder/Raptor Lake).
// Runtime-gated behind Isa::Avx512 (F/DQ/BW/VL + VNNI); bit-exact to act_avx2.cpp / quantize_q8_K_ref.
// Q8_0, Q8_1 and Q8_K from floats, byte for byte what the AVX2 / reference quantisers write (FORMAT-SPEC part II section 19, row "Avx / Avx2", and
// section 6 for Q8_K):
// Q8_0 d = amax / 127 (float32), id = 127 / amax (0 when amax = 0), q = round-half-even(x * id), stored d = half(d);
// Q8_1 the same q and d, plus s = half(d * sum q) with d the float32 value before the half rounding;
// Q8_K mx = the first element of largest magnitude (sign kept), iscale = -127 / mx, q = min(127, nearest_int(iscale * x)) with the product rounded
// to float32 BEFORE the rounding to an integer (never a fused multiply-add into the rounding step), bsums = sums of 16, d = 1 / iscale;
// an all-zero block gives d = 0 and zero quants.
// Compiled with AVX-512 F / BW / VL (+ DQ, VNNI where the flags give them); the dispatcher calls these only behind Isa::Avx512.
#if defined(_MSC_VER) && defined(__AVX512VL__) && !defined(__AVX512VNNI__)
#define __AVX512VNNI__ 1 // an existing MSVC workaround: the intrinsics header wants the macro with /arch:AVX512
#endif
#include "tier_common.hpp"
#include "../registry.hpp"
#include "strata/quant/act.hpp"
#if defined(_MSC_VER) && !defined(__clang__) && defined(__AVX512VL__) && !defined(__AVX512VNNI__)
#define __AVX512VNNI__ 1
#if !defined(_MSC_VER) && !(defined(__AVX512F__) && defined(__AVX512BW__) && defined(__AVX512VL__))
#error "act_avx512.cpp needs AVX-512 F, BW and VL"
#endif
#if !defined(_MSC_VER) && (!defined(__AVX512F__) || !defined(__AVX512BW__) || !defined(__AVX512VL__))
#error "act_avx512.cpp needs AVX-512 F, BW, and VL"
// keeps a float vector value as it is, so that a following add cannot be fused with the multiply that produced it
#if defined(__GNUC__) || defined(__clang__)
#define A5_NOFUSE(v) __asm__("" : "+v"(v))
#else
#define A5_NOFUSE(v) (void)(v)
#endif
namespace strata::quant {
namespace avx512 {
static inline int q8k_ctz32_avx512(unsigned int m) {
namespace {
#if defined(_MSC_VER)
unsigned long idx = 0;
_BitScanForward(&idx, m);
return (int) idx;
inline int ctz32(unsigned v) { unsigned long i; _BitScanForward(&i, v); return (int)i; }
#else
return __builtin_ctz(m);
inline int ctz32(unsigned v) { return __builtin_ctz(v); }
#endif
inline __m512 abs512(__m512 v) { return _mm512_castsi512_ps(_mm512_and_si512(_mm512_castps_si512(v), _mm512_set1_epi32(0x7fffffff))); }
// 32 floats -> 32 int8 (signed saturation, like the packs of the AVX2 code), amax, and the integer sum of the quants
struct Q8Block {
float amax;
float d;
int sum;
__m256i q;
};
inline Q8Block quantize32(const float* x) {
const __m512 a = _mm512_loadu_ps(x);
const __m512 b = _mm512_loadu_ps(x + 16);
Q8Block r;
r.amax = _mm512_reduce_max_ps(_mm512_max_ps(abs512(a), abs512(b)));
r.d = r.amax / 127.0f;
const float id = r.amax != 0.0f ? 127.0f / r.amax : 0.0f;
const __m512 vid = _mm512_set1_ps(id);
const __m512i qa = _mm512_cvtps_epi32(_mm512_mul_ps(a, vid)); // current rounding mode: to nearest, ties to even
const __m512i qb = _mm512_cvtps_epi32(_mm512_mul_ps(b, vid));
r.q = _mm256_set_m128i(_mm512_cvtsepi32_epi8(qb), _mm512_cvtsepi32_epi8(qa));
r.sum = _mm512_reduce_add_epi32(_mm512_add_epi32(qa, qb));
return r;
}
} // namespace
void quantize_q8_0_avx512(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT vy, int64_t k) {
assert(QK8_0 == 32);
assert(k % QK8_0 == 0);
const int64_t nb = k / QK8_0;
block_q8_0* STRATA_RESTRICT y = (block_q8_0*) vy;
const __m512 absm = _mm512_castsi512_ps(_mm512_set1_epi32(0x7fffffff));
for (int64_t i = 0; i < nb; ++i, x += 32) {
if (i + 4 < nb) _mm_prefetch((const char*) (x + 128), _MM_HINT_T0);
const __m512 v0 = _mm512_loadu_ps(x);
const __m512 v1 = _mm512_loadu_ps(x + 16);
const __m512 maxAbs = _mm512_max_ps(_mm512_and_ps(v0, absm), _mm512_and_ps(v1, absm));
const __m256 m8 = _mm256_max_ps(_mm512_castps512_ps256(maxAbs), _mm512_extractf32x8_ps(maxAbs, 1));
__m128 m4 = _mm_max_ps(_mm256_extractf128_ps(m8, 1), _mm256_castps256_ps128(m8));
m4 = _mm_max_ps(m4, _mm_movehl_ps(m4, m4));
m4 = _mm_max_ss(m4, _mm_movehdup_ps(m4));
const float maxScalar = _mm_cvtss_f32(m4);
const float d = maxScalar / 127.f;
y[i].d = f2h(d);
const float id = (maxScalar != 0.0f) ? 127.f / maxScalar : 0.0f;
const __m512 mul = _mm512_set1_ps(id);
const __m512 r0 = _mm512_roundscale_ps(_mm512_mul_ps(v0, mul), _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC);
const __m512 r1 = _mm512_roundscale_ps(_mm512_mul_ps(v1, mul), _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC);
const __m128i b0 = _mm512_cvtsepi32_epi8(_mm512_cvtps_epi32(r0));
const __m128i b1 = _mm512_cvtsepi32_epi8(_mm512_cvtps_epi32(r1));
_mm_storeu_si128((__m128i*) (y[i].qs + 0), b0);
_mm_storeu_si128((__m128i*) (y[i].qs + 16), b1);
uint8_t* y = (uint8_t*)vy;
const int64_t nb = k / 32;
for (int64_t i = 0; i < nb; ++i) {
const Q8Block r = quantize32(x + 32 * i);
const uint16_t dh = f2h(r.d);
std::memcpy(y + 34 * i, &dh, 2);
_mm256_storeu_si256((__m256i*)(y + 34 * i + 2), r.q);
}
}
void quantize_q8_1_avx512(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT vy, int64_t k) {
assert(QK8_1 == 32);
assert(k % QK8_1 == 0);
const int64_t nb = k / QK8_1;
block_q8_1* STRATA_RESTRICT y = (block_q8_1*) vy;
const __m512 absm = _mm512_castsi512_ps(_mm512_set1_epi32(0x7fffffff));
for (int64_t i = 0; i < nb; ++i, x += 32) {
if (i + 4 < nb) _mm_prefetch((const char*) (x + 128), _MM_HINT_T0);
const __m512 v0 = _mm512_loadu_ps(x);
const __m512 v1 = _mm512_loadu_ps(x + 16);
const __m512 maxAbs = _mm512_max_ps(_mm512_and_ps(v0, absm), _mm512_and_ps(v1, absm));
const __m256 m8 = _mm256_max_ps(_mm512_castps512_ps256(maxAbs), _mm512_extractf32x8_ps(maxAbs, 1));
__m128 m4 = _mm_max_ps(_mm256_extractf128_ps(m8, 1), _mm256_castps256_ps128(m8));
m4 = _mm_max_ps(m4, _mm_movehl_ps(m4, m4));
m4 = _mm_max_ss(m4, _mm_movehdup_ps(m4));
const float maxScalar = _mm_cvtss_f32(m4);
const float d = maxScalar / 127.f;
y[i].d = f2h(d);
const float id = (maxScalar != 0.0f) ? 127.f / maxScalar : 0.0f;
const __m512 mul = _mm512_set1_ps(id);
const __m512i i0 = _mm512_cvtps_epi32(_mm512_roundscale_ps(_mm512_mul_ps(v0, mul), _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC));
const __m512i i1 = _mm512_cvtps_epi32(_mm512_roundscale_ps(_mm512_mul_ps(v1, mul), _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC));
const int sumi = _mm512_reduce_add_epi32(_mm512_add_epi32(i0, i1));
y[i].s = f2h(d * (float) sumi);
_mm_storeu_si128((__m128i*) (y[i].qs + 0), _mm512_cvtsepi32_epi8(i0));
_mm_storeu_si128((__m128i*) (y[i].qs + 16), _mm512_cvtsepi32_epi8(i1));
uint8_t* y = (uint8_t*)vy;
const int64_t nb = k / 32;
for (int64_t i = 0; i < nb; ++i) {
const Q8Block r = quantize32(x + 32 * i);
const uint16_t dh = f2h(r.d);
const uint16_t sh = f2h(r.d * (float)r.sum);
std::memcpy(y + 36 * i, &dh, 2);
std::memcpy(y + 36 * i + 2, &sh, 2);
_mm256_storeu_si256((__m256i*)(y + 36 * i + 4), r.q);
}
}
void quantize_q8_K_avx512(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT vy, int64_t k) {
assert(k % QK_K == 0);
block_q8_K* STRATA_RESTRICT y = (block_q8_K*) vy;
const int64_t nb = k / QK_K;
const __m512 absm = _mm512_castsi512_ps(_mm512_set1_epi32(0x7fffffff));
const __m512 magic = _mm512_set1_ps(12582912.f);
const __m512i mant = _mm512_set1_epi32(0x007fffff);
const __m512i off = _mm512_set1_epi32(0x00400000);
const __m512i c127 = _mm512_set1_epi32(127);
const __m512i sign80 = _mm512_set1_epi8((char) 0x80);
const __m512i zero = _mm512_setzero_si512();
for (int64_t i = 0; i < nb; ++i, x += QK_K) {
if (i + 1 < nb) {
_mm_prefetch((const char*) (x + QK_K), _MM_HINT_T0);
_mm_prefetch((const char*) (x + QK_K + 64), _MM_HINT_T0);
_mm_prefetch((const char*) (x + QK_K + 128), _MM_HINT_T0);
_mm_prefetch((const char*) (x + QK_K + 192), _MM_HINT_T0);
uint8_t* y = (uint8_t*)vy;
const int64_t nb = k / 256;
const __m512i low_mask = _mm512_set1_epi32(0x007fffff);
const __m512i bias = _mm512_set1_epi32(0x00400000);
const __m512 magic = _mm512_set1_ps(12582912.0f); // 2^23 + 2^22: adding it rounds to an integer, ties to even
const __m512i cap = _mm512_set1_epi32(127);
for (int64_t i = 0; i < nb; ++i) {
const float* xb = x + 256 * i;
uint8_t* yb = y + 292 * i;
__m512 v[16];
__m512 vmax = _mm512_setzero_ps();
for (int j = 0; j < 16; ++j) {
v[j] = _mm512_loadu_ps(xb + 16 * j);
vmax = _mm512_max_ps(vmax, abs512(v[j]));
}
// 4x ZMM max(abs(x)): 4 iterations cover all 256 floats
__m512 m0 = _mm512_setzero_ps();
__m512 m1 = _mm512_setzero_ps();
__m512 m2 = _mm512_setzero_ps();
__m512 m3 = _mm512_setzero_ps();
for (int j = 0; j < QK_K; j += 64) {
m0 = _mm512_max_ps(m0, _mm512_and_ps(_mm512_loadu_ps(x + j + 0), absm));
m1 = _mm512_max_ps(m1, _mm512_and_ps(_mm512_loadu_ps(x + j + 16), absm));
m2 = _mm512_max_ps(m2, _mm512_and_ps(_mm512_loadu_ps(x + j + 32), absm));
m3 = _mm512_max_ps(m3, _mm512_and_ps(_mm512_loadu_ps(x + j + 48), absm));
}
const __m512 m = _mm512_max_ps(_mm512_max_ps(m0, m1), _mm512_max_ps(m2, m3));
const float amax = _mm512_reduce_max_ps(m);
if (!amax) {
y[i].d = 0;
std::memset(y[i].qs, 0, QK_K);
const float amax = _mm512_reduce_max_ps(vmax);
if (amax == 0.0f) {
const float zero = 0.0f;
std::memcpy(yb, &zero, 4);
std::memset(yb + 4, 0, 256 + 32);
continue;
}
// Exact first-occurrence sign scan matching q8_K_ref (`if (ax > amax)`)
float mx = 0.f;
const __m512 va = _mm512_set1_ps(amax);
for (int j = 0; j < QK_K; j += 32) {
const unsigned int m0k = (unsigned int) _mm512_cmp_ps_mask(_mm512_and_ps(_mm512_loadu_ps(x + j + 0), absm), va, _CMP_EQ_OQ);
const unsigned int m1k = (unsigned int) _mm512_cmp_ps_mask(_mm512_and_ps(_mm512_loadu_ps(x + j + 16), absm), va, _CMP_EQ_OQ);
const unsigned int msk = m0k | (m1k << 16);
if (msk) {
mx = x[j + q8k_ctz32_avx512(msk)];
// the first element of largest magnitude, with its sign
float mx = 0.0f;
for (int j = 0; j < 16; ++j) {
const __mmask16 m = _mm512_cmp_ps_mask(abs512(v[j]), _mm512_set1_ps(amax), _CMP_EQ_OQ);
if (m) {
mx = xb[16 * j + ctz32((unsigned)m)];
break;
}
}
const float iscale = -127.f / mx;
const __m512 vis = _mm512_set1_ps(iscale);
for (int j = 0; j < QK_K; j += 64) {
__m128i b[4];
for (int q = 0; q < 4; ++q) {
__m512 p = _mm512_mul_ps(vis, _mm512_loadu_ps(x + j + 16 * q));
#if defined(__GNUC__)
// Keep multiply rounded before add to match scalar nearest_int(iscale * x) bit-for-bit
__asm__("" : "+v"(p));
#endif
const __m512 t = _mm512_add_ps(p, magic);
const __m512i vi = _mm512_min_epi32(_mm512_sub_epi32(_mm512_and_si512(_mm512_castps_si512(t), mant), off), c127);
// VPMOVDB truncates each int32 to its low 8 bits in exact order (matches int8_t qs = MIN(127, v))
b[q] = _mm512_cvtepi32_epi8(vi);
}
const __m256i p256_lo = _mm256_inserti128_si256(_mm256_castsi128_si256(b[0]), b[1], 1);
const __m256i p256_hi = _mm256_inserti128_si256(_mm256_castsi128_si256(b[2]), b[3], 1);
const __m512i p512 = _mm512_inserti64x4(_mm512_castsi256_si512(p256_lo), p256_hi, 1);
_mm512_storeu_si512((__m512i*) (y[i].qs + j), p512);
// Compute all 4 16-byte signed sub-block sums in one ZMM VPSADBW
const __m512i sad = _mm512_sad_epu8(_mm512_xor_si512(p512, sign80), zero);
const __m256i slo = _mm512_castsi512_si256(sad);
const __m256i shi = _mm512_extracti64x4_epi64(sad, 1);
const __m128i s0 = _mm256_castsi256_si128(slo);
const __m128i s1 = _mm256_extracti128_si256(slo, 1);
const __m128i s2 = _mm256_castsi256_si128(shi);
const __m128i s3 = _mm256_extracti128_si256(shi, 1);
y[i].bsums[j / 16 + 0] = (int16_t) (_mm_cvtsi128_si32(s0) + _mm_extract_epi32(s0, 2) - 2048);
y[i].bsums[j / 16 + 1] = (int16_t) (_mm_cvtsi128_si32(s1) + _mm_extract_epi32(s1, 2) - 2048);
y[i].bsums[j / 16 + 2] = (int16_t) (_mm_cvtsi128_si32(s2) + _mm_extract_epi32(s2, 2) - 2048);
y[i].bsums[j / 16 + 3] = (int16_t) (_mm_cvtsi128_si32(s3) + _mm_extract_epi32(s3, 2) - 2048);
const float iscale = -127.0f / mx;
const __m512 viscale = _mm512_set1_ps(iscale);
for (int j = 0; j < 16; ++j) {
__m512 p = _mm512_mul_ps(viscale, v[j]); // rounded to float32 first ...
A5_NOFUSE(p);
const __m512 t = _mm512_add_ps(p, magic); // ... then to an integer: the low mantissa bits of the sum
__m512i q = _mm512_sub_epi32(_mm512_and_si512(_mm512_castps_si512(t), low_mask), bias);
q = _mm512_min_epi32(q, cap);
const __m128i q8 = _mm512_cvtepi32_epi8(q); // truncation, like the cast of the scalar code
_mm_storeu_si128((__m128i*)(yb + 4 + 16 * j), q8);
const int16_t bs = (int16_t)_mm512_reduce_add_epi32(_mm512_cvtepi8_epi32(q8)); // the sum of the stored quants
std::memcpy(yb + 260 + 2 * j, &bs, 2);
}
y[i].d = 1 / iscale;
const float d = 1.0f / iscale;
std::memcpy(yb, &d, 4);
}
}
@@ -202,6 +150,6 @@ const ActKernel kTable[] = {
};
} // namespace
ActTable avx512_act_table() noexcept { return {kTable, (int) (sizeof kTable / sizeof kTable[0])}; }
ActTable avx512_act_table() noexcept { return {kTable, (int)(sizeof kTable / sizeof kTable[0])}; }
} // namespace strata::quant
File diff suppressed because it is too large. Load diff
+92 -85
View File
@@ -1,104 +1,111 @@
// Portions of this file are derived from ggml / llama.cpp (https://github.com/ggml-org/llama.cpp, pin 3cf03257f219afbe7334045ff7c6a06ac68c627d), MIT
// licence, Copyright (c) 2023-2026 The ggml authors (licence text: engine/third_party/ggml/LICENSE). Derived: the arithmetic and block access of
// vec_dot_iq3_s_q8_1, vec_dot_iq3_xxs_q8_1 and vec_dot_iq2_s_q8_1 of ggml-cuda/vecdotq.cuh (about 50 of 100 lines). Only the sign expansion
// (iq_sign_bytes, iq_negate) is ours.
// The rest is Copyright (c) 2026 Niko1221 and the Strata contributors, MIT.
// src/iqdot_hip.cuh - HIP decode dots of IQ3_S, IQ3_XXS and IQ2_S weights against Q8_1 activations (split engine, AMD multi-GPU).
//
// The i-quant routed experts' decode dots for HIP (included by kernels.cu after qdot.cuh, ggml vecdotq.cuh's arithmetic): ggml's vec_dot_iq3_s / iq3_xxs / iq2_s_q8_1 with the sign
// expansion done in a few integer operations instead of ggml's HIP __vcmpne4 / __vsub4 (a loop of four byte compares and a saturating byte subtract each).
// The same integers come out, so the answers are bit for bit the ggml dot's (checked on every grid entry by tools/iqdot_test.cu and by the engine's identity runs).
// Written from the packet spec (phaseA-tests/clean/P2-INTERFACES.md 2.13) and FORMAT-SPEC Part II sections 15 and 16. Replaces iqdot_hip.cuh.
//
// A sign byte's four low bits become 0x00 / 0xff in the four bytes of a word: ((s & 0xF) * 0x00204081) & 0x01010101 puts bit i in byte i's low bit (the four
// shifted copies 0, 7, 14, 21 do not overlap, so no carries), * 0xff widens it. A negated byte is (g ^ 0xff) + 1: the word-wide add of the 0/1 bytes cannot
// carry into the next byte as long as no grid byte is 0; the IQ3_S (odd 1..15), IQ3_XXS (4..62) and IQ2_S (8..43) grid bytes never are.
// One call returns the partial dot of ONE sub-block (32 weights, s = iqs / 2) with bq8_1[s]:
// result = ((float) d_w * (float) d_a) * (float) sumi
// d_w the weight block's half scale, d_a the low half of bq8_1[s].ds, sumi an int built from P, the exact integer sum over the 32 elements
// of (grid value x sign) x q_i, with the sub-block scale applied IN INTEGERS (C truncating division; this is the bit contract):
// IQ3_S sumi = P * (1 + 2 * nibble)
// IQ3_XXS sumi = (ls * P + P / 2) / 2 ls = the sub-block word >> 28
// IQ2_S sumi = (P0 * ls0 + P1 * ls1 + (P0 + P1) / 2) / 4 P0 elements 0..15, P1 elements 16..31
//
// Signs: the four (or eight) sign bits of a run are spread to one byte each, and a grid byte g (never 0: the grids hold 1..62) becomes
// -g by (g ^ 0xFF) + 1, so the signed grid word is (g ^ m) + u with u = 0x01 in the bytes to negate and m = 0xFF there: no compare, no
// per-byte subtract, no carry between bytes. The products then run through qd_dp4a.
#pragma once
#if FNX_HIP
namespace fnx {
namespace {
__device__ __forceinline__ uint32_t iq_sign_bytes(uint32_t s4) { return ((s4 & 0xFu) * 0x00204081u) & 0x01010101u; } // 0 / 1 in byte i for bit i of s4
// grid bytes negated where the sign byte of the same index is set (t: 0 / 1 per byte)
__device__ __forceinline__ int iq_negate(uint32_t grid, uint32_t t) { return (int) ((grid ^ (t * 0xFFu)) + t); }
// bit j (0..3) of `bits` -> byte j = 0x01 (the multiplier puts bit j at bit 8 j; no two partial products meet, so nothing carries)
static __device__ __forceinline__ unsigned sgn_ones(unsigned bits) { return (bits * 0x00204081u) & 0x01010101u; }
static __device__ __forceinline__ float fnx_vec_dot_iq3_s_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, const int& kbx, const int& iqs) {
const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;
const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1));
const uint8_t* qs = (const uint8_t*) &qs_packed;
const int qh = bq3->qh[iqs / 2];
const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2);
const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
int sumi = 0;
#pragma unroll
for (int l0 = 0; l0 < 8; l0 += 2) {
const uint32_t g0 = iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)];
const uint32_t g1 = iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)];
const uint32_t s = signs_packed_8[l0 / 2];
const int grid_l = iq_negate(g0, iq_sign_bytes(s));
const int grid_h = iq_negate(g1, iq_sign_bytes(s >> 4));
const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
sumi = qd_dp4a(grid_l, u0, sumi);
sumi = qd_dp4a(grid_h, u1, sumi);
}
sumi *= 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F);
const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds);
return d * sumi;
// the signed grid word: bytes of g negated where u has 0x01
static __device__ __forceinline__ int sgn_apply(unsigned g, unsigned u) { return (int) ((g ^ (u * 0xFFu)) + u); }
// sign byte of a 7-bit sign index: bit 7 makes the byte's one-bits even (FORMAT-SPEC section 15)
static __device__ __forceinline__ unsigned sgn_byte7(unsigned v) { return v | ((__popc(v) & 1u) << 7); }
static __device__ __forceinline__ float sub_scale(const unsigned char* blk, const block_q8_1* y, int s, int sumi) {
const float dw = __half2float(__ushort_as_half((unsigned short) (blk[0] | (blk[1] << 8))));
const float da = __half2float(__low2half(y[s].ds));
const float dd = dw * da;
return dd * (float) sumi;
}
static __device__ __forceinline__ float fnx_vec_dot_iq3_xxs_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, const int& kbx, const int& iqs) {
const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx;
const int2 q3_packed = make_int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1));
const uint8_t* q3 = (const uint8_t*) &q3_packed;
const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2);
int sumi = 0;
static __device__ __forceinline__ float fnx_vec_dot_iq3_s_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, const int& kbx,
const int& iqs) {
const unsigned char* blk = (const unsigned char*) vbq + (size_t) kbx * sizeof(block_iq3_s);
const int s = iqs >> 1;
const unsigned char* qs = blk + 2;
const unsigned qlo = (unsigned) get_int_b2(qs, 2 * s), qhi = (unsigned) get_int_b2(qs, 2 * s + 1); // grid index low bytes of the 8 runs
const unsigned qh = blk[66 + s]; // their ninth bits
const unsigned sg = (unsigned) get_int_b2(blk + 74, s); // 32 sign bits, 4 per run
const int* q8 = (const int*) bq8_1[s].qs;
int p = 0;
#pragma unroll
for (int l0 = 0; l0 < 8; l0 += 2) {
const uint32_t g0 = iq3xxs_grid[q3[l0 + 0]], g1 = iq3xxs_grid[q3[l0 + 1]];
const uint32_t s = unpack_ksigns(aux32 >> (7 * l0 / 2)) & 0xFFu; // the 8-bit sign pattern (ggml's helper repeats it in all four bytes)
const int grid_l = iq_negate(g0, iq_sign_bytes(s));
const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
const int grid_h = iq_negate(g1, iq_sign_bytes(s >> 4));
const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
sumi = qd_dp4a(grid_l, u0, sumi);
sumi = qd_dp4a(grid_h, u1, sumi);
for (int l = 0; l < 8; ++l) {
const unsigned lowbyte = ((l < 4 ? qlo : qhi) >> (8 * (l & 3))) & 0xFFu;
const unsigned idx = lowbyte | (((qh >> l) & 1u) << 8);
const int w = sgn_apply(iq3s_grid[idx], sgn_ones((sg >> (4 * l)) & 0xFu));
p = qd_dp4a(w, get_int_b4(q8, l), p);
}
const int ls = aux32 >> 28;
sumi = (ls * sumi + sumi / 2) / 2;
const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds);
return d * sumi;
const unsigned sc = blk[106 + (s >> 1)];
const int nib = (int) ((s & 1) ? (sc >> 4) : (sc & 0xFu));
return sub_scale(blk, bq8_1, s, p * (1 + 2 * nib));
}
static __device__ __forceinline__ float fnx_vec_dot_iq2_s_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, const int& kbx, const int& iqs) {
const block_iq2_s* bq2 = (const block_iq2_s*) vbq + kbx;
const int qs_packed = get_int_b2(bq2->qs, iqs / 2);
const uint8_t* qs = (const uint8_t*) &qs_packed;
const int qh = bq2->qh[iqs / 2];
const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2);
const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
const int ls0 = bq2->scales[iqs / 2] & 0x0F;
const int ls1 = bq2->scales[iqs / 2] >> 4;
int sumi0 = 0;
int sumi1 = 0;
static __device__ __forceinline__ float fnx_vec_dot_iq3_xxs_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, const int& kbx,
const int& iqs) {
const unsigned char* blk = (const unsigned char*) vbq + (size_t) kbx * sizeof(block_iq3_xxs);
const int s = iqs >> 1;
const unsigned char* qs = blk + 2;
const unsigned g0 = (unsigned) get_int_b2(qs, 2 * s), g1 = (unsigned) get_int_b2(qs, 2 * s + 1); // 8 grid indices: byte 2 l + h
const unsigned w = (unsigned) get_int_b2(blk + 66, s); // four 7-bit sign indices, scale in the top 4 bits
const int* q8 = (const int*) bq8_1[s].qs;
int p = 0;
#pragma unroll
for (int l0 = 0; l0 < 8; l0 += 2) {
const uint2 grid_pos = *(const uint2*) (iq2s_grid + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300)));
const uint32_t s = signs_packed_8[l0 / 2];
const int grid_l = iq_negate(grid_pos.x, iq_sign_bytes(s));
const int grid_h = iq_negate(grid_pos.y, iq_sign_bytes(s >> 4));
const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
if (l0 < 4) {
sumi0 = qd_dp4a(grid_l, u0, sumi0);
sumi0 = qd_dp4a(grid_h, u1, sumi0);
} else {
sumi1 = qd_dp4a(grid_l, u0, sumi1);
sumi1 = qd_dp4a(grid_h, u1, sumi1);
}
for (int l = 0; l < 4; ++l) {
const unsigned sb = sgn_byte7((w >> (7 * l)) & 127u);
const unsigned gw = l < 2 ? g0 : g1;
const unsigned i0 = (gw >> (16 * (l & 1))) & 0xFFu, i1 = (gw >> (16 * (l & 1) + 8)) & 0xFFu;
p = qd_dp4a(sgn_apply(iq3xxs_grid[i0], sgn_ones(sb & 0xFu)), get_int_b4(q8, 2 * l), p);
p = qd_dp4a(sgn_apply(iq3xxs_grid[i1], sgn_ones(sb >> 4)), get_int_b4(q8, 2 * l + 1), p);
}
const int sumi = (sumi0 * ls0 + sumi1 * ls1 + (sumi0 + sumi1) / 2) / 4;
const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds);
return d * sumi;
const int ls = (int) (w >> 28);
return sub_scale(blk, bq8_1, s, (ls * p + p / 2) / 2);
}
static __device__ __forceinline__ float fnx_vec_dot_iq2_s_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, const int& kbx,
const int& iqs) {
const unsigned char* blk = (const unsigned char*) vbq + (size_t) kbx * sizeof(block_iq2_s);
const int s = iqs >> 1;
const unsigned char* qs = blk + 2;
const unsigned lo = (unsigned) get_int_b2(qs, s); // grid index low bytes of the 4 runs
const unsigned sg = (unsigned) get_int_b2(qs + 32, s); // their sign bytes, stored as they are
const unsigned qh = blk[66 + s]; // two more index bits per run
const int* q8 = (const int*) bq8_1[s].qs;
int p01[2] = {0, 0}; // [0]: runs 0 and 1 (elements 0..15), [1]: runs 2 and 3
#pragma unroll
for (int l = 0; l < 4; ++l) {
const unsigned idx = ((lo >> (8 * l)) & 0xFFu) | (((qh >> (2 * l)) & 3u) << 8);
const unsigned long long g = iq2s_grid[idx];
const unsigned sb = (sg >> (8 * l)) & 0xFFu;
int a = p01[l >> 1];
a = qd_dp4a(sgn_apply((unsigned) g, sgn_ones(sb & 0xFu)), get_int_b4(q8, 2 * l), a);
a = qd_dp4a(sgn_apply((unsigned) (g >> 32), sgn_ones(sb >> 4)), get_int_b4(q8, 2 * l + 1), a);
p01[l >> 1] = a;
}
const unsigned sc = blk[74 + s];
const int p0 = p01[0], p1 = p01[1];
const int sumi = (p0 * (int) (sc & 0xFu) + p1 * (int) (sc >> 4) + (p0 + p1) / 2) / 4;
return sub_scale(blk, bq8_1, s, sumi);
}
} // namespace
} // namespace fnx
#endif
#endif // FNX_HIP
+106
View File
@@ -0,0 +1,106 @@
// HIP micro-benchmark of the three i-quant decode dots (fnx_vec_dot_iq3_s / iq3_xxs / iq2_s_q8_1) from whichever iqdot header is first on the include path
// (the current iqdot_hip.cuh, or the clean one through a shim). L2-resident working set, each thread sums many dots. Prints "<type> <median ms>" lines.
// build: as tools/iqdot_test.cu (see engine/tests/clean_p2 / the p9 scripts), run: iqdot_clean_bench [reps] [runs]
#include "kernels.hpp"
#include "env.hpp"
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <vector>
#include "qdot.cuh"
#include "iqdot_hip.cuh"
namespace {
template <int T> struct Dots;
template <> struct Dots<0> {
static constexpr int BYTES = sizeof(block_iq3_s);
__device__ static float f(const void* v, const block_q8_1* y, int k, int i) { return fnx::fnx_vec_dot_iq3_s_q8_1(v, y, k, i); }
};
template <> struct Dots<1> {
static constexpr int BYTES = sizeof(block_iq3_xxs);
__device__ static float f(const void* v, const block_q8_1* y, int k, int i) { return fnx::fnx_vec_dot_iq3_xxs_q8_1(v, y, k, i); }
};
template <> struct Dots<2> {
static constexpr int BYTES = sizeof(block_iq2_s);
__device__ static float f(const void* v, const block_q8_1* y, int k, int i) { return fnx::fnx_vec_dot_iq2_s_q8_1(v, y, k, i); }
};
template <int T>
__global__ void k_bench(const char* w, const block_q8_1* y, int nblocks, int reps, float* out) {
const int t = blockIdx.x * blockDim.x + threadIdx.x;
const int n = nblocks * 8;
float acc = 0.f;
int e = (t * 7) % n;
for (int r = 0; r < reps; ++r) {
const int kbx = e >> 3, iqs = (e & 7) * 2;
acc += Dots<T>::f(w, y + (size_t) kbx * 8, kbx, iqs);
e += 13;
if (e >= n) e -= n;
}
out[t] = acc;
}
template <int T>
void run(const char* name, int reps, int runs) {
constexpr int B = Dots<T>::BYTES;
const int nblocks = 4096;
std::mt19937 rng(7 + T);
std::vector<unsigned char> w((size_t) nblocks * B);
for (auto& c : w) c = (unsigned char) rng();
for (int k = 0; k < nblocks; ++k) {
const __half h = __float2half((float) ((int) (rng() % 2001) - 1000) / 400.0f);
std::memcpy(&w[(size_t) k * B], &h, 2);
}
std::vector<block_q8_1> y((size_t) nblocks * 8);
for (auto& b : y) {
for (int i = 0; i < 32; ++i) b.qs[i] = (int8_t) (int) (rng() % 255 - 127);
b.ds = make_half2(__float2half((float) (rng() % 1000) / 500.0f), __float2half(1.f));
}
char* dw;
block_q8_1* dy;
float* dout;
const int threads = 256, blocks = 2048;
cudaMalloc(&dw, w.size());
cudaMalloc(&dy, y.size() * sizeof(block_q8_1));
cudaMalloc(&dout, sizeof(float) * threads * blocks);
cudaMemcpy(dw, w.data(), w.size(), cudaMemcpyHostToDevice);
cudaMemcpy(dy, y.data(), y.size() * sizeof(block_q8_1), cudaMemcpyHostToDevice);
k_bench<T><<<blocks, threads>>>(dw, dy, nblocks, reps / 8, dout);
cudaDeviceSynchronize();
std::vector<float> ms;
cudaEvent_t a, b;
cudaEventCreate(&a);
cudaEventCreate(&b);
for (int i = 0; i < runs; ++i) {
cudaEventRecord(a);
k_bench<T><<<blocks, threads>>>(dw, dy, nblocks, reps, dout);
cudaEventRecord(b);
cudaEventSynchronize(b);
float m;
cudaEventElapsedTime(&m, a, b);
ms.push_back(m);
}
std::sort(ms.begin(), ms.end());
std::printf("%s %.3f\n", name, ms[ms.size() / 2]);
cudaFree(dw); cudaFree(dy); cudaFree(dout);
}
} // namespace
int main(int argc, char** argv) {
const int reps = argc > 1 ? std::atoi(argv[1]) : 4096;
const int runs = argc > 2 ? std::atoi(argv[2]) : 9;
run<0>("IQ3_S", reps, runs);
run<1>("IQ3_XXS", reps, runs);
run<2>("IQ2_S", reps, runs);
return 0;
}
+2 -2
View File
@@ -227,7 +227,7 @@ if(STRATA_NATIVE_EXPERTS)
message(STATUS "Strata SYCL: no ggml in this build (own CPU pool, parity tests off)")
endif()
strata_resolve(_cpu_native 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/kq_avx512.cpp src/kernels/cpu/kq_avx1.cpp # 0.1.31: the Q4_K/Q5_K/Q5_1/Q8_0 expert rows
src/kernels/cpu/kq_avx2.cpp src/kernels/cpu/kq_dots_avx2.cpp src/kernels/cpu/kq_avx512.cpp src/kernels/cpu/kq_avx1.cpp # 0.1.31: the Q4_K/Q5_K/Q5_1/Q8_0 expert rows
src/kernels/cpu/q2_avx1.cpp src/kernels/cpu/iq_avx1.cpp # 0.1.42: AVX1 (no AVX2) Q2_0 / i-quant rows
src/kernels/cpu/nvfp4_avx512.cpp src/kernels/cpu/nvfp4_avx2.cpp # NVFP4 expert rows (native_expert.cpp calls them)
src/kernels/cpu/tq_cpu.cpp src/kernels/cpu/tq_avx2.cpp src/kernels/cpu/tq_avx512.cpp) # Gyro trellis CPU rows (native_expert.cpp calls them; the SYCL GPU path does not run these types)
@@ -240,7 +240,7 @@ if(STRATA_NATIVE_EXPERTS)
set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/tq_avx512.cpp PROPERTIES COMPILE_OPTIONS
"-mavx512f;-mavx512bw;-mavx512vl;-mavx512vnni;-mavx512vbmi;-mavx2;-mfma;-mf16c")
set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")
set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")
set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/kq_avx2.cpp ${STRATA_ROOT}/src/kernels/cpu/kq_dots_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")
set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/kq_avx512.cpp PROPERTIES COMPILE_OPTIONS
"-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mavx2;-mfma;-mf16c")
set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "-mavx")
+19 -38
View File
@@ -1,55 +1,36 @@
// include/strata/kernels/dp4a.hpp - the two instructions the kernels use that Pascal (sm_60) does not have.
// STRATA_DP4A(a, b, c): the signed four-lane byte dot product with an int32 accumulator (SYCL spelling), plus strata_spin_pause().
//
// The engine is written for compute capability 7.5 and newer and refuses older cards at CMake configure time
// (a Pascal build passes -DSTRATA_EXPERIMENTAL_SM60=ON). A GP100-class card is compute capability 6.0, which is
// missing exactly two things the i-quant kernels rely on:
// STRATA_DP4A(a, b, c) == c + sum over k = 0..3 of (signed byte k of a) * (signed byte k of b), modulo 2^32.
//
// * `__dp4a`, a byte-wise dot product, available from 6.1 (Pascal GP10x/GV11x). Its fallback below is
// llama.cpp's own (`ggml/src/ggml-cuda/common.cuh`), which is the reference for the kernels in this
// directory: they are transcribed from llama.cpp's vecdotq.cuh, and that wrapper's operands are the same
// sites. It reinterprets the operands as SIGNED bytes and accumulates in int32, which is what `__dp4a`
// does for these calls, so the fallback is bit-exact rather than merely close.
// * `__nanosleep`, available from 7.0 (Volta). It only paces single-thread doorbell waits, so a loop that
// spins without it is correct, merely busier.
// With dpct compatibility level 610 or higher it is dpct::dp4a; below that the same value is formed in registers (each operand byte is
// sign-extended, multiplied, and the four products are added to c). The operands are plain values, so a and b may be the same register.
// SYCL has no nanosleep: strata_spin_pause() is empty (every wait is bounded elsewhere by strata::kSpinMax).
//
// Both are compile-time selections on `__CUDA_ARCH__`, so one source tree builds for Pascal and for RTX
// 20/30/40/50 without a #define at the call sites. A HIP build never takes either fallback: `__CUDA_ARCH__` is
// undefined there, so `STRATA_DP4A` is `__dp4a` (which `hip_compat/intrinsics.hpp` provides) and the pause is
// HIP's own `__nanosleep`.
#pragma once
#define DPCT_PROFILING_ENABLED
#include <sycl/sycl.hpp>
#include <dpct/dpct.hpp>
#include <cstdint>
#include <time.h>
#if defined(STRATA_HIP_GFX906)
#include <cuda_runtime.h> // gfx906: the compat layer (__forceinline__, __nanosleep, __dp4a)
#endif
#if defined(DPCT_COMPATIBILITY_TEMP) && (DPCT_COMPATIBILITY_TEMP < 610)
#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP < 610
__device__ __forceinline__ int strata_dp4a(const int a, const int b, const int c) {
const int8_t* a8 = (const int8_t*) &a;
const int8_t* b8 = (const int8_t*) &b;
return c + a8[0] * b8[0] + a8[1] * b8[1] + a8[2] * b8[2] + a8[3] * b8[3];
__dpct_inline__ int strata_dp4a(const int a, const int b, const int c) {
const uint32_t ua = (uint32_t)a, ub = (uint32_t)b;
uint32_t acc = (uint32_t)c;
acc += (uint32_t)((int)(int8_t)(ua) * (int)(int8_t)(ub));
acc += (uint32_t)((int)(int8_t)(ua >> 8) * (int)(int8_t)(ub >> 8));
acc += (uint32_t)((int)(int8_t)(ua >> 16) * (int)(int8_t)(ub >> 16));
acc += (uint32_t)((int)(int8_t)(ua >> 24) * (int)(int8_t)(ub >> 24));
return (int)acc;
}
#define STRATA_DP4A(a, b, c) strata_dp4a((a), (b), (c))
#else
#define STRATA_DP4A(a, b, c) dpct::dp4a((a), (b), (c))
#endif
/// Yield the thread while a doorbell flag is being polled. The length of the pause is a backoff hint, not a
/// contract, and only pre-Volta CUDA has no `__nanosleep` at all.
__dpct_inline__ void strata_spin_pause() {
#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP < 700
// sm_6x: the loop spins. Every call site is a single-thread doorbell wait, so nothing else is delayed.
#else
/*
DPCT1008: __nanosleep function is not defined in SYCL. This is a
hardware-specific feature. Consult with your hardware vendor to find a
replacement.
*/
// SYCL port: no __nanosleep; the doorbell waits are bounded by strata::kSpinMax instead
#endif
}
__dpct_inline__ void strata_spin_pause() {}
@@ -2,7 +2,7 @@
//
// WHAT IT IS. The artifact's RoPE is trained over `orig_ctx` positions (the artifact ships no
// `rope.scaling` keys, so this is a pure runtime feature). Scaling re-uses positions past that by
// rescaling the rotation angles. Three types, the llama.cpp set:
// rescaling the rotation angles. Three types:
//
// none freq_scale 1, no correction - today's behaviour, exactly
// linear Position Interpolation: angles shrunk by 1/factor - every position fits again, all
@@ -11,13 +11,10 @@
// pairs are interpolated, and the pairs in between blend - plus a magnitude correction
// `mscale` that keeps the attention temperature where training put it
//
// THE MATH IS GGML'S, TRANSCRIBED, NOT RE-DERIVED. `third_party/llama.cpp` is vendored and is the
// numerical contract (the same standing `native_rope.cu` declares): ramp, correction dims, the
// interpolation mix and the mscale formula below are line-for-line that source, with the MIT
// attribution at each helper. The one deliberate deviation is bookkeeping: ggml's device kernel
// speaks in even dim indices (`i0`) and halves them inside the ramp, while every Strata rope kernel
// speaks in PAIR indices - so `rope_yarn_ramp` here takes the pair index and compares it against
// `corr_dims` directly. Same numbers, one less division per call site.
// THE MATH is the YaRN paper's (Peng et al., arXiv 2309.00071), written once in rope_yarn_math.hpp (namespace strata::kernels::yarn): the
// correction window, the ramp, the interpolation mix and the magnitude correction. This header keeps the configuration, its validity rule and
// the process constant, and calls those functions. Every Strata rope kernel speaks in PAIR indices, so the ramp takes the pair index and
// compares it against the correction window directly.
//
// HOW IT REACHES THE ROPE. Two forms, one config:
//
@@ -40,16 +37,11 @@
#include <dpct/dpct.hpp>
#include <cmath>
#if defined(SYCL_LANGUAGE_VERSION) || defined(__HIPCC__)
#define STRATA_ROPE_SCALING_HD
#else
#define STRATA_ROPE_SCALING_HD
#endif
#include "strata/kernels/rope_scaling_type.hpp" // RopeScalingType, STRATA_ROPE_SCALING_HD
#include "strata/kernels/rope_yarn_math.hpp"
namespace strata::kernels {
enum class RopeScalingType { None, Linear, YaRN };
/// The float32 constants the ANALYTIC rotation kernels take (`rope_scaled_angle`'s arguments). The defaults are
/// the identity: freq_scale 1, no correction, magnitude 1 - with them the helper computes `cosf(theta) * 1.0f`
/// on `1.0f * theta`, which is exactly today's unscaled `cosf(theta)` bit for bit.
@@ -70,42 +62,28 @@ struct RopeScaling {
RopeScalingType type = RopeScalingType::None;
double freq_base = 1e7; ///< `rope.freq_base` (the value pinned by `qsa_freq_base()`)
double factor = 1.0; ///< `--rope-scale`: how far past the trained context the run goes
double freq_scale_in = 0; ///< `--rope-freq-scale`: the raw ggml knob; 0 = 1/factor
double freq_scale_in = 0; ///< `--rope-freq-scale`: the raw knob; 0 = 1/factor
double orig_ctx = 262144; ///< `--yarn-orig-ctx`: the context the model was trained over
double ext_factor = 0; ///< `--yarn-ext-factor`: correction depth; 0 = off, 1 = full YaRN
double attn_factor = 1.0; ///< `--yarn-attn-factor`: extra magnitude scale (ggml's attn_factor)
double attn_factor = 1.0; ///< `--yarn-attn-factor`: extra magnitude scale
double beta_fast = 32.0; ///< `--yarn-beta-fast`
double beta_slow = 1.0; ///< `--yarn-beta-slow`
/// The angle shrink. ggml's `freq_scale`: 1 means "the trained angles", 1/factor squeezes
/// `factor` positions into the trained range.
double freq_scale() const {
if (type == RopeScalingType::None) return 1.0;
return freq_scale_in > 0 ? freq_scale_in : 1.0 / factor;
}
/// The angle shrink: 1 means "the trained angles", 1/factor squeezes `factor` positions into the trained range.
double freq_scale() const { return yarn::freq_scale(type, freq_scale_in, factor); }
/// The magnitude correction. ggml's `rope_yarn` multiplies cos and sin by this; the log term
/// rides on `ext_factor != 0` (not on the type), exactly as that source has it. With the
/// The magnitude correction cos and sin are multiplied by; the log term rides on `ext_factor != 0` (not on the type). With the
/// default knobs YaRN factor F gives `1 + 0.1*ln(F)` - YaRN's temperature correction.
double mscale() const {
if (ext_factor == 0) return attn_factor;
return attn_factor * (1.0 + 0.1 * std::log(1.0 / freq_scale()));
}
double mscale() const { return yarn::mscale(ext_factor, attn_factor, freq_scale()); }
/// The correction window, in PAIR indices: below `out[0]` pairs extrapolate (keep the trained
/// angles), above `out[1]` they interpolate, in between they blend. Transcribed from ggml's
/// `ggml_rope_yarn_corr_dims` (see the derivation comment at `rope_yarn_corr_dim` below).
void corr_dims(int n_rot, double out[2]) const {
const double start = std::floor(rope_yarn_corr_dim(n_rot, orig_ctx, beta_fast, freq_base));
const double end = std::ceil(rope_yarn_corr_dim(n_rot, orig_ctx, beta_slow, freq_base));
out[0] = start < 0 ? 0 : start;
out[1] = end > (double) (n_rot - 1) ? (double) (n_rot - 1) : end;
}
/// angles), above `out[1]` they interpolate, in between they blend.
void corr_dims(int n_rot, double out[2]) const { yarn::corr_dims(n_rot, orig_ctx, beta_fast, beta_slow, freq_base, out); }
/// The analytic kernels' constants. `none` returns the identity constants WHATEVER the other knobs hold -
/// the table builder ignores them for `none` too, so the two rotation forms cannot disagree there, and an
/// unscaled run computes exactly what it computed before scaling existed. Linear/YaRN: ggml's `rope_yarn`
/// arguments (`attn_factor` is the raw knob; the helper applies the log term when correcting).
/// unscaled run computes exactly what it computed before scaling existed. Linear/YaRN: the
/// arguments of the YaRN rotation (`attn_factor` is the raw knob; `rope_scaled_angle` applies the log term when correcting).
RopeKernelArgs kernel_args(int n_rot) const {
RopeKernelArgs a;
if (type == RopeScalingType::None) return a;
@@ -118,50 +96,19 @@ struct RopeScaling {
a.attn_factor = (float) attn_factor;
return a;
}
private:
/// ggml/src/ggml.c: "Apparently solving `n_rot = 2pi * x * base^((2 * max_pos_emb) / n_dims)`
/// for x, we get `corr_dim(n_rot) = n_dims * log(max_pos_emb / (n_rot * 2pi)) / (2 * log(base))`".
/// float64 rather than ggml's float32: the table path computes in float64 and is held to a
/// bit-exact float64 reference, so its inputs are float64 too.
static double rope_yarn_corr_dim(int n_dims, double n_ctx_orig, double n_rot, double base) {
return (double) n_dims * std::log(n_ctx_orig / (n_rot * 2.0 * 3.14159265358979323846)) /
(2.0 * std::log(base));
}
};
/// The ramp between extrapolation (1) and interpolation (0).
///
/// ggml/src/ggml-cuda/rope.cu `rope_yarn_ramp`: `1 - clamp(y, 0, 1)` with
/// `y = (i0 / 2 - low) / max(0.001, high - low)`. ggml passes the even dim index `i0`; this takes
/// the pair index (ggml's `i0/2`) so Strata's pair-indexed kernels don't re-derive the mapping. The
/// 0.001 floor on the denominator is ggml's, kept verbatim: `corr_dims` can produce low == high.
STRATA_ROPE_SCALING_HD inline float rope_yarn_ramp(float low, float high, int pair) {
const float y = ((float) pair - low) / (high - low > 0.001f ? high - low : 0.001f);
const float clamped = y < 0.0f ? 0.0f : (y > 1.0f ? 1.0f : y);
return 1.0f - clamped;
}
/// The ramp between extrapolation (1) and interpolation (0), in float32: `1 - clamp((pair - low) / max(0.001, high - low), 0, 1)`. The 0.001
/// floor on the denominator is part of the contract: `corr_dims` can produce low == high.
STRATA_ROPE_SCALING_HD inline float rope_yarn_ramp(float low, float high, int pair) { return yarn::ramp(low, high, pair); }
/// The scaled angle for one pair, float32, the ANALYTIC paths' contract (pinned ggml arithmetic).
/// The scaled angle for one pair, float32, the ANALYTIC paths' contract.
///
/// Takes `theta_extrap` - the position times that pair's trained `inv_freq` - and returns the angle
/// to take cos/sin of, with ggml's mscale already folded in. `mscale_in` must be `attn_factor`
/// (ggml's kernels receive the raw knob and apply the log term here, where it is per-pair constant;
/// this helper keeps that shape so the native path reads against ggml line by line).
STRATA_ROPE_SCALING_HD inline void rope_scaled_angle(float theta_extrap, float freq_scale, float corr_low,
float corr_high, float ext_factor, float mscale_in,
int pair, float& cos_out, float& sin_out) {
// The interpolation, always applied; the correction mixed in on top (ggml-cuda/rope.cu rope_yarn).
float theta = freq_scale * theta_extrap;
float mscale = mscale_in;
if (ext_factor != 0.0f) {
const float ramp_mix = rope_yarn_ramp(corr_low, corr_high, pair) * ext_factor;
theta = theta * (1.0f - ramp_mix) + theta_extrap * ramp_mix;
// "Get n-d magnitude scaling corrected for interpolation" - the log term only when correcting.
mscale *= 1.0f + 0.1f * sycl::log(1.0f / freq_scale);
}
cos_out = sycl::cos(theta) * mscale;
sin_out = sycl::sin(theta) * mscale;
/// Takes `theta_extrap` - the position times that pair's trained `inv_freq` - and returns cos and sin of the angle to rotate by, with the
/// magnitude correction folded in. `mscale_in` must be `attn_factor` (the log term is applied inside, where it is per-pair constant).
STRATA_ROPE_SCALING_HD inline void rope_scaled_angle(float theta_extrap, float freq_scale, float corr_low, float corr_high, float ext_factor,
float mscale_in, int pair, float& cos_out, float& sin_out) {
yarn::scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale_in, pair, cos_out, sin_out);
}
/// The ONE validity rule for a resolved configuration, shared by the engine's startup check and every rotation
@@ -1,143 +0,0 @@
// Portions of this file are derived from ggml / llama.cpp (https://github.com/ggml-org/llama.cpp, pin 3cf03257f219afbe7334045ff7c6a06ac68c627d), MIT
// licence, Copyright (c) 2023-2026 The ggml authors (licence text: engine/third_party/ggml/LICENSE). Derived: the IQ2_XS grid table (iq2xs_grid), copied
// from ggml/src/ggml-common.h (about 135 of 139 lines); the file format's codebook is not ours to change.
// The rest is Copyright (c) 2026 Niko1221 and the Strata contributors, MIT.
//
// iq2xs_host_tables.inc - IQ2_XS's grid and sign tables as plain host arrays (from ggml-common.h, MIT), for the
// CPU decode in iq_multi_parity (the SYCL ggml-common.h holds them as device globals only)
static const uint64_t host_iq2xs_grid[512] = {0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08,
0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x080808080819192b,
0x0808080808192b19, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b1919,
0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908, 0x080808081908192b,
0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919,
0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x080808082b080808,
0x080808082b08082b, 0x080808082b081919, 0x080808082b082b08, 0x080808082b190819,
0x080808082b191908, 0x080808082b192b19, 0x080808082b2b0808, 0x0808081908080819,
0x0808081908081908, 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808,
0x080808190819082b, 0x0808081908191919, 0x0808081908192b08, 0x0808081908192b2b,
0x08080819082b0819, 0x08080819082b1908, 0x0808081919080808, 0x080808191908082b,
0x0808081919081919, 0x0808081919082b08, 0x0808081919190819, 0x0808081919191908,
0x08080819192b0808, 0x08080819192b2b08, 0x080808192b080819, 0x080808192b081908,
0x080808192b190808, 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b08081919,
0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, 0x0808082b082b0808,
0x0808082b19080819, 0x0808082b19081908, 0x0808082b19190808, 0x0808082b19191919,
0x0808082b2b080808, 0x0808082b2b082b2b, 0x0808190808080819, 0x0808190808081908,
0x080819080808192b, 0x0808190808082b19, 0x0808190808190808, 0x080819080819082b,
0x0808190808191919, 0x0808190808192b08, 0x08081908082b0819, 0x08081908082b1908,
0x0808190819080808, 0x080819081908082b, 0x0808190819081919, 0x0808190819082b08,
0x0808190819190819, 0x0808190819191908, 0x080819081919192b, 0x08081908192b0808,
0x080819082b080819, 0x080819082b081908, 0x080819082b190808, 0x0808191908080808,
0x080819190808082b, 0x0808191908081919, 0x0808191908082b08, 0x0808191908190819,
0x0808191908191908, 0x08081919082b0808, 0x0808191919080819, 0x0808191919081908,
0x0808191919190808, 0x08081919192b0819, 0x080819192b080808, 0x0808192b08080819,
0x0808192b08081908, 0x0808192b08190808, 0x0808192b082b192b, 0x0808192b19080808,
0x0808192b1908082b, 0x0808192b2b081908, 0x08082b0808080808, 0x08082b080808082b,
0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808082b2b, 0x08082b0808190819,
0x08082b0808191908, 0x08082b08082b0808, 0x08082b08082b1919, 0x08082b0819080819,
0x08082b0819081908, 0x08082b0819190808, 0x08082b0819192b08, 0x08082b082b080808,
0x08082b082b2b0808, 0x08082b082b2b2b2b, 0x08082b1908080819, 0x08082b1908081908,
0x08082b1908190808, 0x08082b1919080808, 0x08082b192b080819, 0x08082b192b082b19,
0x08082b2b08080808, 0x08082b2b082b0808, 0x08082b2b082b2b08, 0x08082b2b2b19192b,
0x08082b2b2b2b0808, 0x0819080808080819, 0x0819080808081908, 0x081908080808192b,
0x0819080808082b19, 0x0819080808190808, 0x081908080819082b, 0x0819080808191919,
0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908, 0x0819080819080808,
0x081908081908082b, 0x0819080819081919, 0x0819080819082b08, 0x0819080819190819,
0x0819080819191908, 0x08190808192b0808, 0x08190808192b2b2b, 0x081908082b080819,
0x081908082b081908, 0x081908082b190808, 0x0819081908080808, 0x081908190808082b,
0x0819081908081919, 0x0819081908082b08, 0x0819081908190819, 0x0819081908191908,
0x08190819082b0808, 0x0819081919080819, 0x0819081919081908, 0x0819081919190808,
0x081908192b080808, 0x081908192b191908, 0x081908192b19192b, 0x0819082b08080819,
0x0819082b08081908, 0x0819082b0808192b, 0x0819082b08190808, 0x0819082b19080808,
0x0819082b192b0808, 0x0819190808080808, 0x081919080808082b, 0x0819190808081919,
0x0819190808082b08, 0x0819190808190819, 0x0819190808191908, 0x08191908082b0808,
0x0819190819080819, 0x0819190819081908, 0x0819190819082b19, 0x0819190819190808,
0x08191908192b1908, 0x081919082b080808, 0x0819191908080819, 0x0819191908081908,
0x0819191908190808, 0x0819191919080808, 0x0819192b08080808, 0x0819192b08191908,
0x0819192b19082b19, 0x08192b0808080819, 0x08192b0808081908, 0x08192b0808190808,
0x08192b080819082b, 0x08192b0819080808, 0x08192b0819191908, 0x08192b082b08192b,
0x08192b1908080808, 0x08192b1908081919, 0x08192b19192b192b, 0x08192b2b19190819,
0x08192b2b2b2b2b19, 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919,
0x082b080808082b08, 0x082b080808082b2b, 0x082b080808190819, 0x082b080808191908,
0x082b0808082b0808, 0x082b080819080819, 0x082b080819081908, 0x082b080819190808,
0x082b08082b080808, 0x082b08082b2b0808, 0x082b081908080819, 0x082b081908081908,
0x082b081908190808, 0x082b081919080808, 0x082b081919082b08, 0x082b0819192b1919,
0x082b082b08080808, 0x082b082b082b082b, 0x082b082b2b080808, 0x082b082b2b2b2b08,
0x082b190808080819, 0x082b190808081908, 0x082b190808190808, 0x082b1908082b2b19,
0x082b190819080808, 0x082b191908080808, 0x082b191919080819, 0x082b19191919082b,
0x082b19192b192b19, 0x082b192b08080819, 0x082b192b08192b2b, 0x082b192b2b2b192b,
0x082b2b0808080808, 0x082b2b0808082b08, 0x082b2b0808082b2b, 0x082b2b08082b0808,
0x082b2b0819191919, 0x082b2b082b082b08, 0x082b2b082b2b082b, 0x082b2b19192b2b08,
0x082b2b192b190808, 0x082b2b2b08082b08, 0x082b2b2b082b0808, 0x082b2b2b2b08082b,
0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819, 0x1908080808081908,
0x190808080808192b, 0x1908080808082b19, 0x1908080808190808, 0x190808080819082b,
0x1908080808191919, 0x1908080808192b08, 0x19080808082b0819, 0x19080808082b1908,
0x1908080819080808, 0x190808081908082b, 0x1908080819081919, 0x1908080819082b08,
0x1908080819082b2b, 0x1908080819190819, 0x1908080819191908, 0x19080808192b0808,
0x19080808192b1919, 0x190808082b080819, 0x190808082b081908, 0x190808082b190808,
0x1908081908080808, 0x190808190808082b, 0x1908081908081919, 0x1908081908082b08,
0x1908081908190819, 0x1908081908191908, 0x19080819082b0808, 0x1908081919080819,
0x1908081919081908, 0x1908081919190808, 0x190808192b080808, 0x190808192b081919,
0x190808192b2b082b, 0x1908082b08080819, 0x1908082b08081908, 0x1908082b08190808,
0x1908082b0819082b, 0x1908082b082b2b19, 0x1908082b19080808, 0x1908190808080808,
0x190819080808082b, 0x1908190808081919, 0x1908190808082b08, 0x1908190808190819,
0x1908190808191908, 0x1908190808192b19, 0x19081908082b0808, 0x1908190819080819,
0x1908190819081908, 0x1908190819190808, 0x190819082b080808, 0x190819082b191908,
0x1908191908080819, 0x1908191908081908, 0x1908191908190808, 0x19081919082b1908,
0x1908191919080808, 0x190819192b192b2b, 0x1908192b08080808, 0x1908192b08082b2b,
0x1908192b19081908, 0x1908192b19190808, 0x19082b0808080819, 0x19082b0808081908,
0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919, 0x19082b0819191908,
0x19082b08192b082b, 0x19082b1908080808, 0x19082b1908190819, 0x19082b1919081908,
0x19082b1919190808, 0x19082b19192b2b19, 0x19082b2b08081908, 0x1919080808080808,
0x191908080808082b, 0x1919080808081919, 0x1919080808082b08, 0x1919080808190819,
0x1919080808191908, 0x19190808082b0808, 0x19190808082b2b08, 0x1919080819080819,
0x1919080819081908, 0x1919080819190808, 0x191908082b080808, 0x1919081908080819,
0x1919081908081908, 0x1919081908190808, 0x1919081908191919, 0x1919081919080808,
0x191908191908082b, 0x1919082b08080808, 0x1919082b19081908, 0x1919082b2b2b2b2b,
0x1919190808080819, 0x1919190808081908, 0x1919190808190808, 0x19191908082b0819,
0x1919190819080808, 0x19191908192b0808, 0x191919082b080819, 0x191919082b2b0819,
0x1919191908080808, 0x1919191908082b08, 0x191919192b080808, 0x191919192b082b08,
0x1919192b082b0819, 0x1919192b192b2b08, 0x1919192b2b2b0819, 0x19192b0808080808,
0x19192b0808191908, 0x19192b0819080819, 0x19192b0819190808, 0x19192b082b192b19,
0x19192b1908192b2b, 0x19192b1919080808, 0x19192b191908082b, 0x19192b2b2b081919,
0x192b080808080819, 0x192b080808081908, 0x192b080808190808, 0x192b080819080808,
0x192b080819191908, 0x192b0808192b082b, 0x192b08082b08192b, 0x192b08082b2b2b19,
0x192b081908080808, 0x192b082b082b1908, 0x192b082b19082b2b, 0x192b082b2b19082b,
0x192b190808080808, 0x192b19080819192b, 0x192b191908190808, 0x192b191919080808,
0x192b191919081919, 0x192b19192b2b1908, 0x192b2b0808080819, 0x192b2b08192b2b2b,
0x192b2b19082b1919, 0x192b2b2b0808192b, 0x192b2b2b19191908, 0x192b2b2b192b082b,
0x2b08080808080808, 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08,
0x2b08080808190819, 0x2b08080808191908, 0x2b080808082b0808, 0x2b080808082b2b2b,
0x2b08080819080819, 0x2b08080819081908, 0x2b08080819190808, 0x2b0808082b080808,
0x2b0808082b08082b, 0x2b0808082b2b2b08, 0x2b0808082b2b2b2b, 0x2b08081908080819,
0x2b08081908081908, 0x2b0808190808192b, 0x2b08081908190808, 0x2b08081919080808,
0x2b08081919190819, 0x2b08081919192b19, 0x2b08082b08080808, 0x2b08082b082b0808,
0x2b08082b2b080808, 0x2b08082b2b08082b, 0x2b08082b2b2b0808, 0x2b08082b2b2b2b08,
0x2b08190808080819, 0x2b08190808081908, 0x2b08190808190808, 0x2b0819080819082b,
0x2b08190808191919, 0x2b08190819080808, 0x2b081908192b0808, 0x2b0819082b082b19,
0x2b08191908080808, 0x2b08191919081908, 0x2b0819192b2b1919, 0x2b08192b08192b08,
0x2b08192b192b2b2b, 0x2b082b0808080808, 0x2b082b0808082b08, 0x2b082b08082b1919,
0x2b082b0819192b2b, 0x2b082b082b080808, 0x2b082b082b08082b, 0x2b082b082b2b2b08,
0x2b082b190808192b, 0x2b082b2b082b082b, 0x2b082b2b2b080808, 0x2b082b2b2b082b08,
0x2b082b2b2b19192b, 0x2b082b2b2b2b2b08, 0x2b19080808080819, 0x2b19080808081908,
0x2b19080808190808, 0x2b19080819080808, 0x2b1908081919192b, 0x2b1908082b081908,
0x2b19081908080808, 0x2b190819082b082b, 0x2b190819192b1908, 0x2b19082b1919192b,
0x2b19082b2b082b19, 0x2b19190808080808, 0x2b19190808081919, 0x2b19190819081908,
0x2b19190819190808, 0x2b19190819192b08, 0x2b191919082b2b19, 0x2b1919192b190808,
0x2b1919192b19082b, 0x2b19192b19080819, 0x2b192b0819190819, 0x2b192b082b2b192b,
0x2b192b1919082b19, 0x2b192b2b08191919, 0x2b192b2b192b0808, 0x2b2b080808080808,
0x2b2b08080808082b, 0x2b2b080808082b08, 0x2b2b080808082b2b, 0x2b2b0808082b0808,
0x2b2b0808082b2b2b, 0x2b2b08082b2b0808, 0x2b2b081919190819, 0x2b2b081919192b19,
0x2b2b08192b2b192b, 0x2b2b082b08080808, 0x2b2b082b0808082b, 0x2b2b082b08082b08,
0x2b2b082b082b2b2b, 0x2b2b082b2b080808, 0x2b2b082b2b2b0808, 0x2b2b190819080808,
0x2b2b19082b191919, 0x2b2b192b192b1919, 0x2b2b192b2b192b08, 0x2b2b2b0808082b2b,
0x2b2b2b08082b0808, 0x2b2b2b08082b082b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b0808,
0x2b2b2b082b2b2b08, 0x2b2b2b1908081908, 0x2b2b2b192b081908, 0x2b2b2b192b08192b,
0x2b2b2b2b082b2b08, 0x2b2b2b2b082b2b2b, 0x2b2b2b2b2b190819, 0x2b2b2b2b2b2b2b2b};
static const uint8_t host_ksigns_iq2xs[128] = {0, 129, 130, 3, 132, 5, 6, 135, 136, 9, 10, 139, 12, 141, 142, 15,
144, 17, 18, 147, 20, 149, 150, 23, 24, 153, 154, 27, 156, 29, 30, 159,
160, 33, 34, 163, 36, 165, 166, 39, 40, 169, 170, 43, 172, 45, 46, 175,
48, 177, 178, 51, 180, 53, 54, 183, 184, 57, 58, 187, 60, 189, 190, 63,
192, 65, 66, 195, 68, 197, 198, 71, 72, 201, 202, 75, 204, 77, 78, 207,
80, 209, 210, 83, 212, 85, 86, 215, 216, 89, 90, 219, 92, 221, 222, 95,
96, 225, 226, 99, 228, 101, 102, 231, 232, 105, 106, 235, 108, 237, 238, 111,
240, 113, 114, 243, 116, 245, 246, 119, 120, 249, 250, 123, 252, 125, 126, 255};
@@ -0,0 +1,142 @@
// GENERATED by tools/gen_iq2xs_host_tables.py from tools/format_tables (iq2xs_grid.txt, small_tables.txt). Do not edit.
// host_iq2xs_grid[i]: row i of the IQ2_XS grid, value j in byte j (little endian); host_ksigns_iq2xs[v]: the sign byte of the 7-bit index v.
static const uint64_t host_iq2xs_grid[512] = {
0x0808080808080808ull, 0x080808080808082bull, 0x0808080808081919ull, 0x0808080808082b08ull,
0x0808080808082b2bull, 0x0808080808190819ull, 0x0808080808191908ull, 0x080808080819192bull,
0x0808080808192b19ull, 0x08080808082b0808ull, 0x08080808082b082bull, 0x08080808082b1919ull,
0x08080808082b2b08ull, 0x0808080819080819ull, 0x0808080819081908ull, 0x080808081908192bull,
0x0808080819082b19ull, 0x0808080819190808ull, 0x080808081919082bull, 0x0808080819191919ull,
0x0808080819192b08ull, 0x08080808192b0819ull, 0x08080808192b1908ull, 0x080808082b080808ull,
0x080808082b08082bull, 0x080808082b081919ull, 0x080808082b082b08ull, 0x080808082b190819ull,
0x080808082b191908ull, 0x080808082b192b19ull, 0x080808082b2b0808ull, 0x0808081908080819ull,
0x0808081908081908ull, 0x080808190808192bull, 0x0808081908082b19ull, 0x0808081908190808ull,
0x080808190819082bull, 0x0808081908191919ull, 0x0808081908192b08ull, 0x0808081908192b2bull,
0x08080819082b0819ull, 0x08080819082b1908ull, 0x0808081919080808ull, 0x080808191908082bull,
0x0808081919081919ull, 0x0808081919082b08ull, 0x0808081919190819ull, 0x0808081919191908ull,
0x08080819192b0808ull, 0x08080819192b2b08ull, 0x080808192b080819ull, 0x080808192b081908ull,
0x080808192b190808ull, 0x0808082b08080808ull, 0x0808082b0808082bull, 0x0808082b08081919ull,
0x0808082b08082b08ull, 0x0808082b08190819ull, 0x0808082b08191908ull, 0x0808082b082b0808ull,
0x0808082b19080819ull, 0x0808082b19081908ull, 0x0808082b19190808ull, 0x0808082b19191919ull,
0x0808082b2b080808ull, 0x0808082b2b082b2bull, 0x0808190808080819ull, 0x0808190808081908ull,
0x080819080808192bull, 0x0808190808082b19ull, 0x0808190808190808ull, 0x080819080819082bull,
0x0808190808191919ull, 0x0808190808192b08ull, 0x08081908082b0819ull, 0x08081908082b1908ull,
0x0808190819080808ull, 0x080819081908082bull, 0x0808190819081919ull, 0x0808190819082b08ull,
0x0808190819190819ull, 0x0808190819191908ull, 0x080819081919192bull, 0x08081908192b0808ull,
0x080819082b080819ull, 0x080819082b081908ull, 0x080819082b190808ull, 0x0808191908080808ull,
0x080819190808082bull, 0x0808191908081919ull, 0x0808191908082b08ull, 0x0808191908190819ull,
0x0808191908191908ull, 0x08081919082b0808ull, 0x0808191919080819ull, 0x0808191919081908ull,
0x0808191919190808ull, 0x08081919192b0819ull, 0x080819192b080808ull, 0x0808192b08080819ull,
0x0808192b08081908ull, 0x0808192b08190808ull, 0x0808192b082b192bull, 0x0808192b19080808ull,
0x0808192b1908082bull, 0x0808192b2b081908ull, 0x08082b0808080808ull, 0x08082b080808082bull,
0x08082b0808081919ull, 0x08082b0808082b08ull, 0x08082b0808082b2bull, 0x08082b0808190819ull,
0x08082b0808191908ull, 0x08082b08082b0808ull, 0x08082b08082b1919ull, 0x08082b0819080819ull,
0x08082b0819081908ull, 0x08082b0819190808ull, 0x08082b0819192b08ull, 0x08082b082b080808ull,
0x08082b082b2b0808ull, 0x08082b082b2b2b2bull, 0x08082b1908080819ull, 0x08082b1908081908ull,
0x08082b1908190808ull, 0x08082b1919080808ull, 0x08082b192b080819ull, 0x08082b192b082b19ull,
0x08082b2b08080808ull, 0x08082b2b082b0808ull, 0x08082b2b082b2b08ull, 0x08082b2b2b19192bull,
0x08082b2b2b2b0808ull, 0x0819080808080819ull, 0x0819080808081908ull, 0x081908080808192bull,
0x0819080808082b19ull, 0x0819080808190808ull, 0x081908080819082bull, 0x0819080808191919ull,
0x0819080808192b08ull, 0x08190808082b0819ull, 0x08190808082b1908ull, 0x0819080819080808ull,
0x081908081908082bull, 0x0819080819081919ull, 0x0819080819082b08ull, 0x0819080819190819ull,
0x0819080819191908ull, 0x08190808192b0808ull, 0x08190808192b2b2bull, 0x081908082b080819ull,
0x081908082b081908ull, 0x081908082b190808ull, 0x0819081908080808ull, 0x081908190808082bull,
0x0819081908081919ull, 0x0819081908082b08ull, 0x0819081908190819ull, 0x0819081908191908ull,
0x08190819082b0808ull, 0x0819081919080819ull, 0x0819081919081908ull, 0x0819081919190808ull,
0x081908192b080808ull, 0x081908192b191908ull, 0x081908192b19192bull, 0x0819082b08080819ull,
0x0819082b08081908ull, 0x0819082b0808192bull, 0x0819082b08190808ull, 0x0819082b19080808ull,
0x0819082b192b0808ull, 0x0819190808080808ull, 0x081919080808082bull, 0x0819190808081919ull,
0x0819190808082b08ull, 0x0819190808190819ull, 0x0819190808191908ull, 0x08191908082b0808ull,
0x0819190819080819ull, 0x0819190819081908ull, 0x0819190819082b19ull, 0x0819190819190808ull,
0x08191908192b1908ull, 0x081919082b080808ull, 0x0819191908080819ull, 0x0819191908081908ull,
0x0819191908190808ull, 0x0819191919080808ull, 0x0819192b08080808ull, 0x0819192b08191908ull,
0x0819192b19082b19ull, 0x08192b0808080819ull, 0x08192b0808081908ull, 0x08192b0808190808ull,
0x08192b080819082bull, 0x08192b0819080808ull, 0x08192b0819191908ull, 0x08192b082b08192bull,
0x08192b1908080808ull, 0x08192b1908081919ull, 0x08192b19192b192bull, 0x08192b2b19190819ull,
0x08192b2b2b2b2b19ull, 0x082b080808080808ull, 0x082b08080808082bull, 0x082b080808081919ull,
0x082b080808082b08ull, 0x082b080808082b2bull, 0x082b080808190819ull, 0x082b080808191908ull,
0x082b0808082b0808ull, 0x082b080819080819ull, 0x082b080819081908ull, 0x082b080819190808ull,
0x082b08082b080808ull, 0x082b08082b2b0808ull, 0x082b081908080819ull, 0x082b081908081908ull,
0x082b081908190808ull, 0x082b081919080808ull, 0x082b081919082b08ull, 0x082b0819192b1919ull,
0x082b082b08080808ull, 0x082b082b082b082bull, 0x082b082b2b080808ull, 0x082b082b2b2b2b08ull,
0x082b190808080819ull, 0x082b190808081908ull, 0x082b190808190808ull, 0x082b1908082b2b19ull,
0x082b190819080808ull, 0x082b191908080808ull, 0x082b191919080819ull, 0x082b19191919082bull,
0x082b19192b192b19ull, 0x082b192b08080819ull, 0x082b192b08192b2bull, 0x082b192b2b2b192bull,
0x082b2b0808080808ull, 0x082b2b0808082b08ull, 0x082b2b0808082b2bull, 0x082b2b08082b0808ull,
0x082b2b0819191919ull, 0x082b2b082b082b08ull, 0x082b2b082b2b082bull, 0x082b2b19192b2b08ull,
0x082b2b192b190808ull, 0x082b2b2b08082b08ull, 0x082b2b2b082b0808ull, 0x082b2b2b2b08082bull,
0x082b2b2b2b082b08ull, 0x082b2b2b2b082b2bull, 0x1908080808080819ull, 0x1908080808081908ull,
0x190808080808192bull, 0x1908080808082b19ull, 0x1908080808190808ull, 0x190808080819082bull,
0x1908080808191919ull, 0x1908080808192b08ull, 0x19080808082b0819ull, 0x19080808082b1908ull,
0x1908080819080808ull, 0x190808081908082bull, 0x1908080819081919ull, 0x1908080819082b08ull,
0x1908080819082b2bull, 0x1908080819190819ull, 0x1908080819191908ull, 0x19080808192b0808ull,
0x19080808192b1919ull, 0x190808082b080819ull, 0x190808082b081908ull, 0x190808082b190808ull,
0x1908081908080808ull, 0x190808190808082bull, 0x1908081908081919ull, 0x1908081908082b08ull,
0x1908081908190819ull, 0x1908081908191908ull, 0x19080819082b0808ull, 0x1908081919080819ull,
0x1908081919081908ull, 0x1908081919190808ull, 0x190808192b080808ull, 0x190808192b081919ull,
0x190808192b2b082bull, 0x1908082b08080819ull, 0x1908082b08081908ull, 0x1908082b08190808ull,
0x1908082b0819082bull, 0x1908082b082b2b19ull, 0x1908082b19080808ull, 0x1908190808080808ull,
0x190819080808082bull, 0x1908190808081919ull, 0x1908190808082b08ull, 0x1908190808190819ull,
0x1908190808191908ull, 0x1908190808192b19ull, 0x19081908082b0808ull, 0x1908190819080819ull,
0x1908190819081908ull, 0x1908190819190808ull, 0x190819082b080808ull, 0x190819082b191908ull,
0x1908191908080819ull, 0x1908191908081908ull, 0x1908191908190808ull, 0x19081919082b1908ull,
0x1908191919080808ull, 0x190819192b192b2bull, 0x1908192b08080808ull, 0x1908192b08082b2bull,
0x1908192b19081908ull, 0x1908192b19190808ull, 0x19082b0808080819ull, 0x19082b0808081908ull,
0x19082b0808190808ull, 0x19082b0819080808ull, 0x19082b0819081919ull, 0x19082b0819191908ull,
0x19082b08192b082bull, 0x19082b1908080808ull, 0x19082b1908190819ull, 0x19082b1919081908ull,
0x19082b1919190808ull, 0x19082b19192b2b19ull, 0x19082b2b08081908ull, 0x1919080808080808ull,
0x191908080808082bull, 0x1919080808081919ull, 0x1919080808082b08ull, 0x1919080808190819ull,
0x1919080808191908ull, 0x19190808082b0808ull, 0x19190808082b2b08ull, 0x1919080819080819ull,
0x1919080819081908ull, 0x1919080819190808ull, 0x191908082b080808ull, 0x1919081908080819ull,
0x1919081908081908ull, 0x1919081908190808ull, 0x1919081908191919ull, 0x1919081919080808ull,
0x191908191908082bull, 0x1919082b08080808ull, 0x1919082b19081908ull, 0x1919082b2b2b2b2bull,
0x1919190808080819ull, 0x1919190808081908ull, 0x1919190808190808ull, 0x19191908082b0819ull,
0x1919190819080808ull, 0x19191908192b0808ull, 0x191919082b080819ull, 0x191919082b2b0819ull,
0x1919191908080808ull, 0x1919191908082b08ull, 0x191919192b080808ull, 0x191919192b082b08ull,
0x1919192b082b0819ull, 0x1919192b192b2b08ull, 0x1919192b2b2b0819ull, 0x19192b0808080808ull,
0x19192b0808191908ull, 0x19192b0819080819ull, 0x19192b0819190808ull, 0x19192b082b192b19ull,
0x19192b1908192b2bull, 0x19192b1919080808ull, 0x19192b191908082bull, 0x19192b2b2b081919ull,
0x192b080808080819ull, 0x192b080808081908ull, 0x192b080808190808ull, 0x192b080819080808ull,
0x192b080819191908ull, 0x192b0808192b082bull, 0x192b08082b08192bull, 0x192b08082b2b2b19ull,
0x192b081908080808ull, 0x192b082b082b1908ull, 0x192b082b19082b2bull, 0x192b082b2b19082bull,
0x192b190808080808ull, 0x192b19080819192bull, 0x192b191908190808ull, 0x192b191919080808ull,
0x192b191919081919ull, 0x192b19192b2b1908ull, 0x192b2b0808080819ull, 0x192b2b08192b2b2bull,
0x192b2b19082b1919ull, 0x192b2b2b0808192bull, 0x192b2b2b19191908ull, 0x192b2b2b192b082bull,
0x2b08080808080808ull, 0x2b0808080808082bull, 0x2b08080808081919ull, 0x2b08080808082b08ull,
0x2b08080808190819ull, 0x2b08080808191908ull, 0x2b080808082b0808ull, 0x2b080808082b2b2bull,
0x2b08080819080819ull, 0x2b08080819081908ull, 0x2b08080819190808ull, 0x2b0808082b080808ull,
0x2b0808082b08082bull, 0x2b0808082b2b2b08ull, 0x2b0808082b2b2b2bull, 0x2b08081908080819ull,
0x2b08081908081908ull, 0x2b0808190808192bull, 0x2b08081908190808ull, 0x2b08081919080808ull,
0x2b08081919190819ull, 0x2b08081919192b19ull, 0x2b08082b08080808ull, 0x2b08082b082b0808ull,
0x2b08082b2b080808ull, 0x2b08082b2b08082bull, 0x2b08082b2b2b0808ull, 0x2b08082b2b2b2b08ull,
0x2b08190808080819ull, 0x2b08190808081908ull, 0x2b08190808190808ull, 0x2b0819080819082bull,
0x2b08190808191919ull, 0x2b08190819080808ull, 0x2b081908192b0808ull, 0x2b0819082b082b19ull,
0x2b08191908080808ull, 0x2b08191919081908ull, 0x2b0819192b2b1919ull, 0x2b08192b08192b08ull,
0x2b08192b192b2b2bull, 0x2b082b0808080808ull, 0x2b082b0808082b08ull, 0x2b082b08082b1919ull,
0x2b082b0819192b2bull, 0x2b082b082b080808ull, 0x2b082b082b08082bull, 0x2b082b082b2b2b08ull,
0x2b082b190808192bull, 0x2b082b2b082b082bull, 0x2b082b2b2b080808ull, 0x2b082b2b2b082b08ull,
0x2b082b2b2b19192bull, 0x2b082b2b2b2b2b08ull, 0x2b19080808080819ull, 0x2b19080808081908ull,
0x2b19080808190808ull, 0x2b19080819080808ull, 0x2b1908081919192bull, 0x2b1908082b081908ull,
0x2b19081908080808ull, 0x2b190819082b082bull, 0x2b190819192b1908ull, 0x2b19082b1919192bull,
0x2b19082b2b082b19ull, 0x2b19190808080808ull, 0x2b19190808081919ull, 0x2b19190819081908ull,
0x2b19190819190808ull, 0x2b19190819192b08ull, 0x2b191919082b2b19ull, 0x2b1919192b190808ull,
0x2b1919192b19082bull, 0x2b19192b19080819ull, 0x2b192b0819190819ull, 0x2b192b082b2b192bull,
0x2b192b1919082b19ull, 0x2b192b2b08191919ull, 0x2b192b2b192b0808ull, 0x2b2b080808080808ull,
0x2b2b08080808082bull, 0x2b2b080808082b08ull, 0x2b2b080808082b2bull, 0x2b2b0808082b0808ull,
0x2b2b0808082b2b2bull, 0x2b2b08082b2b0808ull, 0x2b2b081919190819ull, 0x2b2b081919192b19ull,
0x2b2b08192b2b192bull, 0x2b2b082b08080808ull, 0x2b2b082b0808082bull, 0x2b2b082b08082b08ull,
0x2b2b082b082b2b2bull, 0x2b2b082b2b080808ull, 0x2b2b082b2b2b0808ull, 0x2b2b190819080808ull,
0x2b2b19082b191919ull, 0x2b2b192b192b1919ull, 0x2b2b192b2b192b08ull, 0x2b2b2b0808082b2bull,
0x2b2b2b08082b0808ull, 0x2b2b2b08082b082bull, 0x2b2b2b08082b2b08ull, 0x2b2b2b082b2b0808ull,
0x2b2b2b082b2b2b08ull, 0x2b2b2b1908081908ull, 0x2b2b2b192b081908ull, 0x2b2b2b192b08192bull,
0x2b2b2b2b082b2b08ull, 0x2b2b2b2b082b2b2bull, 0x2b2b2b2b2b190819ull, 0x2b2b2b2b2b2b2b2bull,
};
static const uint8_t host_ksigns_iq2xs[128] = {
0x00, 0x81, 0x82, 0x03, 0x84, 0x05, 0x06, 0x87, 0x88, 0x09, 0x0a, 0x8b, 0x0c, 0x8d, 0x8e, 0x0f,
0x90, 0x11, 0x12, 0x93, 0x14, 0x95, 0x96, 0x17, 0x18, 0x99, 0x9a, 0x1b, 0x9c, 0x1d, 0x1e, 0x9f,
0xa0, 0x21, 0x22, 0xa3, 0x24, 0xa5, 0xa6, 0x27, 0x28, 0xa9, 0xaa, 0x2b, 0xac, 0x2d, 0x2e, 0xaf,
0x30, 0xb1, 0xb2, 0x33, 0xb4, 0x35, 0x36, 0xb7, 0xb8, 0x39, 0x3a, 0xbb, 0x3c, 0xbd, 0xbe, 0x3f,
0xc0, 0x41, 0x42, 0xc3, 0x44, 0xc5, 0xc6, 0x47, 0x48, 0xc9, 0xca, 0x4b, 0xcc, 0x4d, 0x4e, 0xcf,
0x50, 0xd1, 0xd2, 0x53, 0xd4, 0x55, 0x56, 0xd7, 0xd8, 0x59, 0x5a, 0xdb, 0x5c, 0xdd, 0xde, 0x5f,
0x60, 0xe1, 0xe2, 0x63, 0xe4, 0x65, 0x66, 0xe7, 0xe8, 0x69, 0x6a, 0xeb, 0x6c, 0xed, 0xee, 0x6f,
0xf0, 0x71, 0x72, 0xf3, 0x74, 0xf5, 0xf6, 0x77, 0x78, 0xf9, 0xfa, 0x7b, 0xfc, 0x7d, 0x7e, 0xff,
};
+1 -1
View File
@@ -123,7 +123,7 @@ std::vector<double> dequant_q8_1(const std::vector<uint8_t>& q, size_t n) {
return v;
}
#include "iq2xs_host_tables.inc"
#include "iq2xs_host_tables_gen.inc"
// IQ2_XS decoded on the CPU from ggml's tables (dequantize_row_iq2_xs), a reference independent of the GPU dequantizer
std::vector<float> host_iq2_xs(const std::vector<uint8_t>& w, size_t n) {
std::vector<float> y(n);
+124
View File
@@ -0,0 +1,124 @@
// act_avx512_verify: the AVX-512 activation quantisers (act_avx512.cpp) against the Avx2-contract quantisers (avx2:: in act_avx2.cpp, and
// quantize_q8_K_ref) byte for byte, over random floats, exact ties, zeros, negative zero, subnormals, equal / doubled maxima and raw random finite
// bit patterns. Output buffers are pre-filled with a marker so an unwritten byte shows. Needs an AVX-512 (F/BW/VL) CPU.
// usage: act_avx512_verify [blocks per case]
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <vector>
#include "strata/quant/act.hpp"
#include "strata/quant/isa.hpp"
#if defined(_MSC_VER)
#define STRATA_RESTRICT __restrict // MSVC mangles it into the symbol name
#else
#define STRATA_RESTRICT __restrict__
#endif
namespace strata::quant::avx2 {
void quantize_q8_0(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT y, int64_t k);
void quantize_q8_1(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT y, int64_t k);
void quantize_q8_K_avx2(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT y, int64_t k);
} // namespace strata::quant::avx2
namespace strata::quant::avx512 {
void quantize_q8_0_avx512(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT y, int64_t k);
void quantize_q8_1_avx512(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT y, int64_t k);
void quantize_q8_K_avx512(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT y, int64_t k);
} // namespace strata::quant::avx512
using namespace strata::quant;
static float bits_to_f(uint32_t u) { float f; std::memcpy(&f, &u, 4); return f; }
int main(int argc, char** argv) {
if (!strata::quant::caps().avx512) {
std::printf("skip: this CPU has no AVX-512 (F, DQ, BW, VL)\n");
return 77;
}
const int blocks = argc > 1 ? atoi(argv[1]) : 20000;
struct K { const char* name; int blk, bytes; void (*oracle)(const float* STRATA_RESTRICT, void* STRATA_RESTRICT, int64_t); void (*ref)(const float*, void*, int64_t); void (*test)(const float* STRATA_RESTRICT, void* STRATA_RESTRICT, int64_t); } ks[] = {
{"q8_0", 32, 34, avx2::quantize_q8_0, quantize_q8_0_ref, avx512::quantize_q8_0_avx512},
{"q8_1", 32, 36, avx2::quantize_q8_1, quantize_q8_1_ref, avx512::quantize_q8_1_avx512},
{"q8_K", 256, 292, avx2::quantize_q8_K_avx2, quantize_q8_K_ref, avx512::quantize_q8_K_avx512},
};
std::mt19937_64 rng(2112);
int fail = 0;
for (const K& k : ks) {
long bad = 0, bad_ref = 0, total = 0, differ_from_ref = 0, zero_blocks = 0;
for (int mode = 0; mode < 12; ++mode) {
const int nblk = blocks;
const int n = nblk * k.blk;
std::vector<float> x(n);
for (int b = 0; b < nblk; ++b) {
float* xb = &x[(size_t)b * k.blk];
std::normal_distribution<float> nd(0.f, 1.f);
const float scale = std::ldexp(1.0f, (int)(rng() % 40) - 20);
switch (mode) {
case 0: for (int i = 0; i < k.blk; ++i) xb[i] = nd(rng) * scale; break;
case 1: for (int i = 0; i < k.blk; ++i) xb[i] = nd(rng) * 1e-3f * scale; break;
case 2: { // exact ties: the largest is 127 * s, the others odd multiples of s / 2 (x * id is then k + 0.5 exactly when id * s == 1)
const float s = std::ldexp(1.0f, (int)(rng() % 20) - 10);
for (int i = 0; i < k.blk; ++i) xb[i] = ((int)(rng() % 255) - 127) * s + ((rng() & 1) ? 0.5f * s : 0.f);
xb[rng() % k.blk] = (rng() & 1) ? 127 * s : -127 * s;
break;
}
case 3: for (int i = 0; i < k.blk; ++i) xb[i] = (rng() % 4 == 0) ? nd(rng) : 0.0f; break;
case 4: for (int i = 0; i < k.blk; ++i) xb[i] = 0.0f; break;
case 5: for (int i = 0; i < k.blk; ++i) xb[i] = (rng() & 1) ? -0.0f : 0.0f; break;
case 6: for (int i = 0; i < k.blk; ++i) xb[i] = bits_to_f((uint32_t)(rng() % 0x007fffffu) | ((rng() & 1) ? 0x80000000u : 0u)); break; // subnormals
case 7: { const float v = nd(rng) * scale; for (int i = 0; i < k.blk; ++i) xb[i] = v; break; } // all equal
case 8: { // the largest magnitude occurs twice with different signs
for (int i = 0; i < k.blk; ++i) xb[i] = nd(rng) * scale * 0.5f;
const float m = 3.0f * scale;
const int a = (int)(rng() % k.blk), b2 = (int)(rng() % k.blk);
xb[a] = m;
xb[b2 == a ? (a + 1) % k.blk : b2] = -m;
break;
}
case 9: for (int i = 0; i < k.blk; ++i) { uint32_t u; do { u = (uint32_t)rng(); } while (((u >> 23) & 255) == 255); xb[i] = bits_to_f(u); if (!std::isfinite(xb[i]) || std::fabs(xb[i]) > 1e37f) xb[i] = nd(rng); } break; // raw bit patterns
case 10: for (int i = 0; i < k.blk; ++i) xb[i] = std::ldexp(nd(rng), (int)(rng() % 60) - 30); break; // wide dynamic range
default: for (int i = 0; i < k.blk; ++i) xb[i] = (float)((int)(rng() % 255) - 127) * scale; break; // integers: ties after scaling
}
}
std::vector<uint8_t> a((size_t)nblk * k.bytes, 0xA5), b((size_t)nblk * k.bytes, 0xA5), c((size_t)nblk * k.bytes, 0xA5);
k.oracle(x.data(), a.data(), n);
k.test(x.data(), b.data(), n);
k.ref(x.data(), c.data(), n);
for (int blk = 0; blk < nblk; ++blk) {
++total;
const uint8_t* pa = &a[(size_t)blk * k.bytes];
const uint8_t* pb = &b[(size_t)blk * k.bytes];
// the one intended difference: an all-zero Q8_K block (d == 0, qs == 0) leaves bsums untouched in the Avx2 quantiser, the new one writes zeros
bool zero_block = false;
if (k.blk == 256 && std::memcmp(pa, pb, 260) == 0) {
zero_block = true;
for (int o = 0; o < 260; ++o) zero_block = zero_block && pa[o] == 0;
for (int o = 260; o < 292; ++o) zero_block = zero_block && pb[o] == 0;
if (zero_block) ++zero_blocks;
}
if (!zero_block && std::memcmp(pa, pb, k.bytes)) {
if (++bad <= 3) {
printf(" %s MISMATCH mode %d block %d, differing byte offsets (oracle/new):", k.name, mode, blk);
int shown = 0;
for (int o = 0; o < k.bytes && shown < 6; ++o)
if (a[(size_t)blk * k.bytes + o] != b[(size_t)blk * k.bytes + o]) {
printf(" %d:%02x/%02x", o, a[(size_t)blk * k.bytes + o], b[(size_t)blk * k.bytes + o]);
++shown;
}
printf("\n");
}
}
if (std::memcmp(&a[(size_t)blk * k.bytes], &c[(size_t)blk * k.bytes], k.bytes)) ++differ_from_ref; // (information: the ties rule differs between contracts)
}
}
(void)bad_ref;
const bool ok = bad == 0;
printf("%s %-5s %ld blocks: avx512 vs avx2 mismatches %ld (info: avx2 vs generic reference differ in %ld blocks)\n", ok ? "ok " : "FAIL", k.name, total, bad, differ_from_ref);
if (!ok) ++fail;
}
printf("%s\n", fail ? "FAILED" : "PASSED");
return fail ? 1 : 0;
}
@@ -0,0 +1,210 @@
// dequant_vectors_test: the dequantisers (artifact/dequant.hpp) against the format-spec vectors.
// - phaseA-tests/clean/p2 vectors (random blocks, float32 expected, %.9g): compared EXACTLY (bits; +0 and -0 count equal)
// - hy4gguf vectors (real blocks, float64 expected): compared within 4 float32 ulps (the float32 chain rounds at each step)
// Plus synthetic edge blocks (subnormal / maximal halves, extreme quants) checked against an independent float64 evaluation.
#include "strata/artifact/dequant.hpp"
#include <cmath>
#include <cstdio>
#include <cstring>
#include <functional>
#include <string>
#include <vector>
#include "vec_util.hpp"
using namespace strata;
namespace {
int g_fail = 0;
struct Case {
const char* dir;
const char* name;
int block_bytes;
int block_elems;
std::function<void(const uint8_t*, float*)> fn;
bool exact;
};
void run_case(const std::string& root, const Case& c) {
std::vector<uint8_t> bin;
std::vector<double> exp;
const std::string base = root + "/" + c.dir + "/" + c.name;
if (!cp2::read_file(base + ".bin", bin) || !cp2::read_values(base + ".expected.txt", exp)) {
std::printf("FAIL %s: cannot read vectors at %s\n", c.name, base.c_str());
++g_fail;
return;
}
const size_t nb = bin.size() / c.block_bytes;
if (bin.size() % c.block_bytes || exp.size() != nb * c.block_elems) {
std::printf("FAIL %s: size mismatch (bin %zu, expected %zu values)\n", c.name, bin.size(), exp.size());
++g_fail;
return;
}
std::vector<float> out(c.block_elems);
int64_t worst = 0;
size_t bad = 0;
for (size_t b = 0; b < nb; ++b) {
c.fn(bin.data() + b * c.block_bytes, out.data());
for (int i = 0; i < c.block_elems; ++i) {
const float want = (float)exp[b * c.block_elems + i];
const int64_t d = cp2::ulp_diff(out[i], want);
if (d > worst) worst = d;
if (c.exact ? d != 0 : d > 4) ++bad;
}
}
std::printf("%s %-12s %zu blocks, max ulp diff %lld\n", bad ? "FAIL" : "ok ", c.name, nb, (long long)worst);
if (bad) ++g_fail;
}
// ---- independent float64 check of edge blocks -------------------------------------------------------------
void put_half(uint8_t* p, uint16_t h) {
p[0] = (uint8_t)(h & 255);
p[1] = (uint8_t)(h >> 8);
}
double half64(uint16_t h) {
const int s = h >> 15, e = (h >> 10) & 31, m = h & 1023;
double v = e == 0 ? std::ldexp((double)m, -24) : std::ldexp((double)(1024 + m), e - 25);
return s ? -v : v;
}
void check_close(const char* what, const float* got, const double* want, int n) {
for (int i = 0; i < n; ++i) {
const float w = (float)want[i];
if (cp2::ulp_diff(got[i], w) > 3 && std::fabs((double)got[i] - want[i]) > 1e-30) {
std::printf("FAIL %s: elem %d got %.9g want %.9g\n", what, i, got[i], want[i]);
++g_fail;
return;
}
}
std::printf("ok %s\n", what);
}
void edge_blocks() {
const uint16_t halves[] = {0x0001, 0x03FF, 0x0400, 0x3C00, 0x7BFF, 0x8001, 0xFBFF, 0x0000};
// Q8_0: every half scale x extreme quants
for (uint16_t h : halves) {
uint8_t blk[34];
put_half(blk, h);
for (int i = 0; i < 32; ++i) blk[2 + i] = (uint8_t)(i == 0 ? 0x80 : i == 1 ? 0x7F : i * 8 + 3);
float out[32];
double want[32];
dequantize_q8_0(blk, out);
for (int i = 0; i < 32; ++i) want[i] = half64(h) * (int8_t)blk[2 + i];
check_close("q8_0 edge", out, want, 32);
}
// Q6_K: scales -128 / 127, q extremes -32 / 31
for (uint16_t h : halves) {
uint8_t blk[210];
std::memset(blk, 0, sizeof blk);
for (int i = 0; i < 128; ++i) blk[i] = (i & 1) ? 0xFF : 0x00;
for (int i = 0; i < 64; ++i) blk[128 + i] = (i & 2) ? 0xFF : 0x00;
for (int s = 0; s < 16; ++s) blk[192 + s] = (uint8_t)((s & 1) ? 127 : 0x80);
put_half(blk + 208, h);
float out[256];
dequantize_q6_K(blk, out);
double want[256];
for (int n = 0; n < 2; ++n)
for (int p = 0; p < 4; ++p)
for (int l = 0; l < 32; ++l) {
const int a = blk[64 * n + (p & 1) * 32 + l];
const int low4 = p < 2 ? (a & 15) : (a >> 4);
const int high2 = (blk[128 + 32 * n + l] >> (2 * p)) & 3;
const int q = low4 + 16 * high2 - 32;
const int s = 8 * n + 2 * p + (l >> 4);
want[128 * n + 32 * p + l] = half64(h) * (int8_t)blk[192 + s] * q;
}
check_close("q6_K edge", out, want, 256);
}
// Q4_K: sc = m = 63 and nibbles 0 / 15
for (uint16_t h : halves) {
uint8_t blk[144];
std::memset(blk, 0xFF, sizeof blk);
put_half(blk, h);
put_half(blk + 2, 0x7BFF);
for (int i = 0; i < 128; ++i) blk[16 + i] = (i & 1) ? 0x0F : 0xF0;
float out[256];
dequantize_q4_K(blk, out);
double want[256];
for (int g = 0; g < 4; ++g)
for (int hh = 0; hh < 2; ++hh)
for (int l = 0; l < 32; ++l) {
const int byte = blk[16 + 32 * g + l];
const int q = hh ? (byte >> 4) : (byte & 15);
want[64 * g + 32 * hh + l] = half64(h) * 63 * q - half64(0x7BFF) * 63;
}
check_close("q4_K edge", out, want, 256);
}
// fp16 conversion: every half pattern against the float64 value (finite) and class for inf / nan
int bad = 0;
for (uint32_t h = 0; h < 65536; ++h) {
const float f = fp16_to_fp32((uint16_t)h);
const int e = (h >> 10) & 31;
if (e == 31) {
const uint32_t u = cp2::f2u(f);
const uint32_t want = ((h & 0x8000u) << 16) | 0x7F800000u | ((h & 0x3FFu) << 13);
if (u != want) ++bad;
} else if ((double)f != half64((uint16_t)h) || std::signbit(f) != (bool)(h >> 15)) {
++bad;
}
// bf16
if (cp2::f2u(bf16_to_fp32((uint16_t)h)) != ((uint32_t)h << 16)) ++bad;
}
std::printf("%s fp16/bf16 conversion over all 65536 patterns\n", bad ? "FAIL" : "ok ");
if (bad) ++g_fail;
uint8_t le[2] = {0x34, 0x12};
if (read_u16(le) != 0x1234) { std::printf("FAIL read_u16\n"); ++g_fail; }
}
} // namespace
int main(int argc, char** argv) {
const std::string root = argc > 1 ? argv[1] : cp2::data_dir();
const Case cases[] = {
{"format-vectors", "q2_0", 18, 64, dequantize_q2_0, true},
{"format-vectors", "q4_0", 18, 32, dequantize_q4_0, true},
{"format-vectors", "q5_0", 22, 32, dequantize_q5_0, true},
{"format-vectors", "q5_1", 24, 32, dequantize_q5_1, true},
{"format-vectors", "q5_k", 176, 256, dequantize_q5_K, true},
{"format-vectors", "iq4_nl", 18, 32, dequantize_iq4_nl, true},
{"format-vectors", "iq4_xs", 136, 256, dequantize_iq4_xs, true},
{"hy4-vectors", "q8_0_ffn", 34, 32, dequantize_q8_0, false},
{"hy4-vectors", "q8_0_embd", 34, 32, dequantize_q8_0, false},
{"hy4-vectors", "q4k_gate", 144, 256, dequantize_q4_K, false},
{"hy4-vectors", "q4k_down", 144, 256, dequantize_q4_K, false},
{"hy4-vectors", "q6k_down", 210, 256, dequantize_q6_K, false},
{"hy4-vectors", "q3k_gate", 110, 256, dequantize_q3_K, false},
};
for (const Case& c : cases) run_case(root, c);
// BF16 vector
{
std::vector<uint8_t> bin;
std::vector<double> exp;
if (!cp2::read_file(root + "/hy4-vectors/bf16_out.bin", bin) || !cp2::read_values(root + "/hy4-vectors/bf16_out.expected.txt", exp)) {
std::printf("FAIL bf16 vectors unreadable\n");
++g_fail;
} else {
std::vector<float> out(exp.size());
dequantize_bf16(bin.data(), out.data(), (int)exp.size());
size_t bad = 0;
for (size_t i = 0; i < exp.size(); ++i) bad += (out[i] != (float)exp[i]);
std::printf("%s bf16_out %zu values\n", bad ? "FAIL" : "ok ", exp.size());
if (bad) ++g_fail;
// f32 copy and f16 path
std::vector<float> c(exp.size());
dequantize_f32((const uint8_t*)out.data(), c.data(), (int)out.size());
if (std::memcmp(c.data(), out.data(), out.size() * 4)) { std::printf("FAIL f32 copy\n"); ++g_fail; }
const uint8_t h16[4] = {0x00, 0x3C, 0x01, 0x00};
float f2[2];
dequantize_f16(h16, f2, 2);
if (f2[0] != 1.0f || f2[1] != std::ldexp(1.0f, -24)) { std::printf("FAIL f16 path\n"); ++g_fail; }
}
}
edge_blocks();
std::printf("%s (%d failure(s))\n", g_fail ? "FAILED" : "PASSED", g_fail);
return g_fail ? 1 : 0;
}
+102
View File
@@ -0,0 +1,102 @@
// dot_avx2_bench: ns per row-dot of the optimised Avx2 kernels and of the plain kernel of the same translation unit, plus the 4-row kernels.
// Built twice (against the old library and against the new one) and run interleaved by tests/clean_p2/run_dot_bench.sh.
// output lines: "<type> opt <ns> plain <ns> [x4 <ns per row>]" (best of several repetitions, one thread)
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <vector>
#include "probe_blocks.hpp"
#include "strata/quant/act.hpp"
#include "strata/quant/dot.hpp"
#if defined(_MSC_VER)
#define STRATA_RESTRICT __restrict // MSVC mangles it into the symbol name
#else
#define STRATA_RESTRICT __restrict__
#endif
namespace strata::quant::avx2 {
#define DECL(N) \
void dot_##N(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT x, const void* STRATA_RESTRICT y); \
void dot_##N##_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT x, const void* STRATA_RESTRICT y);
DECL(q8_0_q8_0) DECL(q4_K_q8_K) DECL(q5_K_q8_K) DECL(q6_K_q8_K) DECL(iq3_xxs_q8_K) DECL(iq4_xs_q8_K)
void dot_q8_0_q8_0_x4_avx2(int n, float out[4], const void* STRATA_RESTRICT w, size_t rb, const void* STRATA_RESTRICT a);
void dot_q4_K_q8_K_x4_avx2(int n, float out[4], const void* STRATA_RESTRICT w, size_t rb, const void* STRATA_RESTRICT a);
void dot_iq4_xs_q8_K_x4_avx2(int n, float out[4], const void* STRATA_RESTRICT w, size_t rb, const void* STRATA_RESTRICT a);
} // namespace strata::quant::avx2
using namespace strata::quant;
typedef void (*Fn)(int, float* STRATA_RESTRICT, const void* STRATA_RESTRICT, const void* STRATA_RESTRICT);
typedef void (*Fn4)(int, float*, const void* STRATA_RESTRICT, size_t, const void* STRATA_RESTRICT);
static double now() { return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count(); }
int main(int argc, char** argv) {
const int reps = argc > 1 ? atoi(argv[1]) : 15;
const int rowsN = argc > 2 ? atoi(argv[2]) : 1024;
using namespace strata::quant::avx2;
struct T { const char* name; int wb, ab, elems; Fn plain, opt; Fn4 x4; bool k; } types[] = {
{"q8_0", 34, 34, 32, dot_q8_0_q8_0, dot_q8_0_q8_0_opt, dot_q8_0_q8_0_x4_avx2, false},
{"q4_K", 144, 292, 256, dot_q4_K_q8_K, dot_q4_K_q8_K_opt, dot_q4_K_q8_K_x4_avx2, true},
{"q5_K", 176, 292, 256, dot_q5_K_q8_K, dot_q5_K_q8_K_opt, nullptr, true},
{"q6_K", 210, 292, 256, dot_q6_K_q8_K, dot_q6_K_q8_K_opt, nullptr, true},
{"iq3_xxs", 98, 292, 256, dot_iq3_xxs_q8_K, dot_iq3_xxs_q8_K_opt, nullptr, true},
{"iq4_xs", 136, 292, 256, dot_iq4_xs_q8_K, dot_iq4_xs_q8_K_opt, dot_iq4_xs_q8_K_x4_avx2, true},
};
std::mt19937_64 rng(1);
const int K = 4096;
for (const T& t : types) {
const int nb = K / t.elems;
std::vector<uint8_t> w((size_t)rowsN * nb * t.wb), a((size_t)nb * t.ab);
for (auto& b : w) b = (uint8_t)rng();
for (int r = 0; r < rowsN; ++r)
for (int b = 0; b < nb; ++b) {
uint8_t* p = &w[((size_t)r * nb + b) * t.wb];
put_half(p + (t.wb == 210 ? 208 : 0), rand_half(rng));
if (t.wb == 144 || t.wb == 176) put_half(p + 2, rand_half(rng));
}
if (t.k) {
std::vector<float> x(K);
std::normal_distribution<float> nd(0.f, 1.f);
for (auto& v : x) v = nd(rng);
quantize_q8_K_ref(x.data(), a.data(), K);
} else {
for (int b = 0; b < nb; ++b) {
put_half(&a[(size_t)b * 34], rand_half(rng));
for (int i = 0; i < 32; ++i) a[(size_t)b * 34 + 2 + i] = (uint8_t)(int8_t)((int)(rng() % 255) - 127);
}
}
const size_t rb = (size_t)nb * t.wb;
volatile float sink = 0;
auto time_one = [&](Fn f) {
double best = 1e30;
for (int rep = 0; rep < reps; ++rep) {
const double t0 = now();
float s = 0, acc = 0;
for (int r = 0; r < rowsN; ++r) { f(K, &s, &w[r * rb], a.data()); acc += s; }
best = std::min(best, now() - t0);
sink = acc;
}
return best / rowsN * 1e9;
};
const double opt = time_one(t.opt), plain = time_one(t.plain);
double x4 = -1;
if (t.x4) {
double best = 1e30;
for (int rep = 0; rep < reps; ++rep) {
const double t0 = now();
float o[4], acc = 0;
for (int r = 0; r + 3 < rowsN; r += 4) { t.x4(K, o, &w[r * rb], rb, a.data()); acc += o[0]; }
best = std::min(best, now() - t0);
sink = acc;
}
x4 = best / rowsN * 1e9;
}
(void)sink;
printf("%s opt %.1f plain %.1f x4 %.1f\n", t.name, opt, plain, x4);
}
return 0;
}
+170
View File
@@ -0,0 +1,170 @@
// dot_avx2_verify: the optimised Avx2 kernels of dot_avx2.cpp against the plain kernels of the same translation unit (bit identical), and the 4-row
// kernels against the one-row kernels (bit identical per row). Weights and activations are random bytes (all quants, -128 activations, subnormal /
// negative / zero scales), plus real Q8_K activations made by the reference quantiser. Also a float64 sanity bound against the exact value.
// Built against the library of the *new* dot_avx2 (tests/clean_p2/build_quant_manual.sh with USE_CLEAN=1); the plain kernels are called by their
// namespace-qualified names.
// usage: dot_avx2_verify [rows per type]
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <string>
#include <vector>
#include "model_ref.hpp"
#include "probe_blocks.hpp"
#include "strata/quant/act.hpp"
#include "strata/quant/dot.hpp"
#if defined(_MSC_VER)
#define STRATA_RESTRICT __restrict // MSVC mangles it into the symbol name
#else
#define STRATA_RESTRICT __restrict__
#endif
namespace strata::quant::avx2 {
#define DECL(N) \
void dot_##N(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT x, const void* STRATA_RESTRICT y); \
void dot_##N##_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT x, const void* STRATA_RESTRICT y);
DECL(q8_0_q8_0) DECL(q4_K_q8_K) DECL(q5_K_q8_K) DECL(q6_K_q8_K) DECL(iq3_xxs_q8_K) DECL(iq4_xs_q8_K)
void dot_q8_0_q8_0_x4_avx2(int n, float out[4], const void* STRATA_RESTRICT w, size_t rb, const void* STRATA_RESTRICT a);
void dot_q4_K_q8_K_x4_avx2(int n, float out[4], const void* STRATA_RESTRICT w, size_t rb, const void* STRATA_RESTRICT a);
void dot_iq4_xs_q8_K_x4_avx2(int n, float out[4], const void* STRATA_RESTRICT w, size_t rb, const void* STRATA_RESTRICT a);
} // namespace strata::quant::avx2
using namespace strata::quant;
typedef void (*Fn)(int, float* STRATA_RESTRICT, const void* STRATA_RESTRICT, const void* STRATA_RESTRICT);
typedef void (*Fn4)(int, float*, const void* STRATA_RESTRICT, size_t, const void* STRATA_RESTRICT);
struct T {
const char* name;
PT pt;
int wb, ab, elems;
Fn plain, opt;
Fn4 x4;
};
static uint16_t special_half(std::mt19937_64& rng) {
static const uint16_t sp[] = {0x0000, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x7bff, 0xfbff, 0x3c00, 0xbc00, 0x2e66, 0x5640};
return (rng() % 3 == 0) ? sp[rng() % (sizeof sp / sizeof sp[0])] : rand_half(rng, -14, 8);
}
int main(int argc, char** argv) {
const long rows = argc > 1 ? atol(argv[1]) : 100000;
using namespace strata::quant::avx2;
const T types[] = {
{"q8_0", PQ8_0, 34, 34, 32, dot_q8_0_q8_0, dot_q8_0_q8_0_opt, dot_q8_0_q8_0_x4_avx2},
{"q4_K", PQ4_K, 144, 292, 256, dot_q4_K_q8_K, dot_q4_K_q8_K_opt, dot_q4_K_q8_K_x4_avx2},
{"q5_K", PQ5_K, 176, 292, 256, dot_q5_K_q8_K, dot_q5_K_q8_K_opt, nullptr},
{"q6_K", PQ6_K, 210, 292, 256, dot_q6_K_q8_K, dot_q6_K_q8_K_opt, nullptr},
{"iq3_xxs", PIQ3_XXS, 98, 292, 256, dot_iq3_xxs_q8_K, dot_iq3_xxs_q8_K_opt, nullptr},
{"iq4_xs", PIQ4_XS, 136, 292, 256, dot_iq4_xs_q8_K, dot_iq4_xs_q8_K_opt, dot_iq4_xs_q8_K_x4_avx2},
};
std::mt19937_64 rng(424242);
int fail = 0;
for (const T& t : types) {
long bad = 0, bad_x4 = 0, bad_val = 0, nx4 = 0;
double worst_rel = 0;
for (long it = 0; it < rows; ++it) {
const int nb = 1 + (int)(rng() % 9);
const int n = nb * t.elems;
const int nrow = t.x4 ? 4 : 1;
std::vector<uint8_t> w((size_t)nrow * nb * t.wb), a((size_t)nb * t.ab);
const int style = (int)(rng() % 6);
for (auto& b : w) b = (uint8_t)rng();
if (style == 1) for (auto& b : w) b = (rng() & 1) ? 0xff : 0x00; // extreme quants
if (style == 2) for (auto& b : w) b = (rng() & 3) ? 0 : (uint8_t)rng();
// scales
for (int r = 0; r < nrow; ++r)
for (int b = 0; b < nb; ++b) {
uint8_t* p = &w[((size_t)r * nb + b) * t.wb];
put_half(p + (t.pt == PQ6_K ? 208 : 0), special_half(rng));
if (t.pt == PQ4_K || t.pt == PQ5_K) put_half(p + 2, special_half(rng));
}
// activation
const bool real = (it & 1) == 0 && t.pt != PQ8_0;
if (real) {
std::vector<float> x(n);
std::normal_distribution<float> nd(0.f, (rng() % 4 == 0) ? 1e-3f : 1.f);
for (auto& v : x) v = nd(rng);
quantize_q8_K_ref(x.data(), a.data(), n);
} else {
for (int b = 0; b < nb; ++b) {
uint8_t* p = &a[(size_t)b * t.ab];
if (t.pt == PQ8_0) {
put_half(p, special_half(rng));
for (int i = 0; i < 32; ++i) p[2 + i] = (style == 3) ? 0x80 : (uint8_t)rng();
} else {
const float d = (rng() % 8 == 0) ? 0.f : std::ldexp(0.5f + (float)(rng() % 1000) / 1000.f, (int)(rng() % 20) - 14) * ((rng() & 1) ? 1.f : -1.f);
std::memcpy(p, &d, 4);
for (int i = 0; i < 256; ++i) p[4 + i] = (style == 3) ? 0x80 : (style == 4 ? 0x7f : (uint8_t)rng());
for (int k = 0; k < 16; ++k) { // consistent bsums
int16_t s = 0;
for (int i = 0; i < 16; ++i) s = (int16_t)(s + (int8_t)p[4 + 16 * k + i]);
std::memcpy(p + 260 + 2 * k, &s, 2);
}
if (style == 5) for (int k = 0; k < 16; ++k) { int16_t s = (int16_t)rng(); std::memcpy(p + 260 + 2 * k, &s, 2); } // bsums not tied to qs
}
}
}
float rp = 0, ro = 0;
t.plain(n, &rp, w.data(), a.data());
t.opt(n, &ro, w.data(), a.data());
if (std::memcmp(&rp, &ro, 4) && !(rp != rp && ro != ro)) {
if (++bad <= 3) printf(" %s MISMATCH n=%d style=%d plain %.9g (%08x) opt %.9g (%08x)\n", t.name, n, style, rp, *(uint32_t*)&rp, ro, *(uint32_t*)&ro);
}
if (t.x4) {
float o4[4];
t.x4(n, o4, w.data(), (size_t)nb * t.wb, a.data());
for (int r = 0; r < 4; ++r) {
float one = 0;
t.plain(n, &one, &w[(size_t)r * nb * t.wb], a.data());
++nx4;
if (std::memcmp(&one, &o4[r], 4) && !(one != one && o4[r] != o4[r])) ++bad_x4;
}
}
// float64 sanity: |opt - V| <= 2^-20 * sum |terms|, V from the exact integer lanes (types with a lane model)
if (t.pt != PQ8_0 && real) {
ProbeType pt{t.name, t.pt, strata::quant::Type::Q8_0, t.elems, t.wb, t.ab};
ProbeRow row(pt, nb);
std::memcpy(row.w.data(), w.data(), (size_t)nb * t.wb);
std::memcpy(row.a.data(), a.data(), (size_t)nb * t.ab);
double V = 0, S = 0;
for (int b = 0; b < nb; ++b) {
int lane[8];
lane_ints(t.pt, row.wb(b), row.ab(b), lane);
int tot = 0;
for (int l = 0; l < 8; ++l) tot += lane[l];
const double term = (double)row.D(b) * (double)tot;
V += term;
for (int l = 0; l < 8; ++l) S += std::fabs((double)row.D(b) * (double)lane[l]); // the error scale is the lane magnitudes, not their cancelling sum
if (t.pt == PQ4_K || t.pt == PQ5_K) {
const uint8_t* s12 = row.wb(b) + 4;
const int16_t* bs = (const int16_t*)(row.ab(b) + 260);
long M = 0, Mk[4] = {0, 0, 0, 0};
for (int j = 0; j < 8; ++j) {
const int mj = j < 4 ? (s12[j + 4] & 63) : ((s12[j + 4] >> 4) | ((s12[j] >> 6) << 4));
M += (long)mj * (bs[2 * j] + bs[2 * j + 1]);
Mk[j / 2] += (long)mj * (bs[2 * j] + bs[2 * j + 1]);
}
const double dmv = (double)fp16_to_fp32(get_half(row.wb(b) + 2)) * (double)row.act_d(b);
V -= dmv * (double)M;
if (t.pt == PQ4_K) for (int k = 0; k < 4; ++k) S += std::fabs(dmv * (double)Mk[k]); // four min lanes
else S += std::fabs(dmv * (double)M);
}
}
if (S > 1e-20 && S < 1e30 && std::isfinite(ro)) { // outside the subnormal / overflow ranges the relative bound is meaningful
const double rel = std::fabs((double)ro - V) / S;
if (rel > worst_rel) worst_rel = rel;
if (rel > std::ldexp(1.0, -20)) ++bad_val;
}
}
}
const bool ok = bad == 0 && bad_x4 == 0 && bad_val == 0;
printf("%s %-8s rows %ld: opt vs plain mismatches %ld, x4 vs one-row %ld/%ld, float64 bound violations %ld (worst %.3g of 2^-20)\n", ok ? "ok " : "FAIL", t.name, rows, bad,
bad_x4, nx4, bad_val, worst_rel / std::ldexp(1.0, -20));
if (!ok) ++fail;
}
printf("%s\n", fail ? "FAILED" : "PASSED");
return fail ? 1 : 0;
}
@@ -0,0 +1,56 @@
// Host emulation of hip_compat/dp4a_rdna1.hpp: the device function is compiled as plain host code (the gfx1010 macro and an empty
// __device__ are defined here) and compared with the byte-wise definition on every (lane, a byte, b byte) with other lanes and c varied,
// plus a random sweep. build: g++ -O2 -std=c++17 -Iengine/include dp4a_rdna1_host_test.cpp
#define __gfx1010__ 1
#define __device__
#define __forceinline__ inline __attribute__((always_inline))
#include "strata/hip_compat/dp4a_rdna1.hpp"
#include <cstdint>
#include <cstdio>
static int ref_dp4a(int a, int b, int c) {
int64_t s = c;
for (int k = 0; k < 4; ++k) s += (int64_t)(int8_t)((uint32_t)a >> (8 * k)) * (int64_t)(int8_t)((uint32_t)b >> (8 * k));
return (int)(uint32_t)(uint64_t)s; // wrap modulo 2^32
}
static uint64_t g_state = 0x9E3779B97F4A7C15ull;
static uint32_t rnd() {
g_state ^= g_state << 13;
g_state ^= g_state >> 7;
g_state ^= g_state << 17;
return (uint32_t)(g_state >> 16);
}
int main() {
const int cvals[16] = {0, 1, -1, 0x7fffffff, (int)0x80000000, 0x12345678, (int)0xdeadbeef, 127 * 127 * 4, -128 * -128 * 4, -128 * 127 * 4, 255, -255, 65536, -65536, (int)0x7ffffc00, (int)0x80000400};
uint64_t cases = 0, bad = 0;
for (int lane = 0; lane < 4; ++lane)
for (uint32_t xa = 0; xa < 256; ++xa)
for (uint32_t xb = 0; xb < 256; ++xb)
for (int r = 0; r < 16; ++r) {
uint32_t a = rnd(), b = rnd();
a = (a & ~(0xffu << (8 * lane))) | (xa << (8 * lane));
b = (b & ~(0xffu << (8 * lane))) | (xb << (8 * lane));
for (int c : cvals) {
++cases;
bad += strata::hip_compat::dp4a_rdna1((int)a, (int)b, c) != ref_dp4a((int)a, (int)b, c);
}
}
// a and b the same register
for (uint32_t i = 0; i < (1u << 22); ++i) {
const uint32_t a = rnd();
++cases;
bad += strata::hip_compat::dp4a_rdna1((int)a, (int)a, (int)i) != ref_dp4a((int)a, (int)a, (int)i);
}
// random words
for (uint32_t i = 0; i < (1u << 27); ++i) {
const int a = (int)rnd(), b = (int)rnd(), c = (int)rnd();
++cases;
bad += strata::hip_compat::dp4a_rdna1(a, b, c) != ref_dp4a(a, b, c);
}
std::printf("dp4a_rdna1 host emulation: %llu cases, %llu mismatches\n", (unsigned long long)cases, (unsigned long long)bad);
std::printf("%s\n", bad ? "FAILED" : "PASSED");
return bad ? 1 : 0;
}
+61
View File
@@ -0,0 +1,61 @@
// SYCL check of the clean dp4a header (engine/sycl/include/strata/kernels/dp4a_clean.hpp installed as strata/kernels/dp4a.hpp):
// STRATA_DP4A on the GPU against the byte-wise definition, over every (lane, a byte, b byte) and a random sweep, including a == b.
// build: icpx -fsycl -O2 -I<engine/sycl/include dir holding strata/kernels/dp4a.hpp> dp4a_sycl_test.cpp
// add -DDPCT_COMPATIBILITY_TEMP=600 to exercise the software form.
#include "strata/kernels/dp4a.hpp"
#include <cstdint>
#include <cstdio>
#include <vector>
static int ref_dp4a(int a, int b, int c) {
int64_t s = c;
for (int k = 0; k < 4; ++k) s += (int64_t)(int8_t)((uint32_t)a >> (8 * k)) * (int64_t)(int8_t)((uint32_t)b >> (8 * k));
return (int)(uint32_t)(uint64_t)s;
}
int main() {
sycl::queue q{sycl::gpu_selector_v};
std::printf("device: %s DPCT_COMPATIBILITY_TEMP=%d\n", q.get_device().get_info<sycl::info::device::name>().c_str(), (int)DPCT_COMPATIBILITY_TEMP);
const size_t N = (size_t)1 << 24;
std::vector<int> A(N), B(N), C(N), R(N);
uint64_t st = 0x9E3779B97F4A7C15ull;
auto rnd = [&]() { st ^= st << 13; st ^= st >> 7; st ^= st << 17; return (uint32_t)(st >> 16); };
uint64_t bad = 0, cases = 0;
int* dA = sycl::malloc_device<int>(N, q);
int* dB = sycl::malloc_device<int>(N, q);
int* dC = sycl::malloc_device<int>(N, q);
int* dR = sycl::malloc_device<int>(N, q);
auto run = [&]() {
q.memcpy(dA, A.data(), N * 4).wait();
q.memcpy(dB, B.data(), N * 4).wait();
q.memcpy(dC, C.data(), N * 4).wait();
q.parallel_for(sycl::range<1>(N), [=](sycl::id<1> i) {
strata_spin_pause();
dR[i] = STRATA_DP4A(dA[i], dB[i], dC[i]);
}).wait();
q.memcpy(R.data(), dR, N * 4).wait();
for (size_t i = 0; i < N; ++i) {
++cases;
bad += R[i] != ref_dp4a(A[i], B[i], C[i]);
}
};
// (lane, a byte, b byte): 4 * 65536 combinations x 64 repetitions with random other lanes and c
for (int rep = 0; rep < 64; ++rep) {
size_t i = 0;
for (int lane = 0; lane < 4; ++lane)
for (uint32_t xa = 0; xa < 256; ++xa)
for (uint32_t xb = 0; xb < 256; ++xb, ++i) {
uint32_t a = rnd(), b = rnd();
a = (a & ~(0xffu << (8 * lane))) | (xa << (8 * lane));
b = (b & ~(0xffu << (8 * lane))) | (xb << (8 * lane));
A[i] = (int)a; B[i] = (int)b; C[i] = (int)rnd();
}
for (; i < N; ++i) { A[i] = (int)rnd(); B[i] = (int)rnd(); C[i] = (int)rnd(); if ((i & 7) == 0) B[i] = A[i]; if ((i & 15) == 1) C[i] = A[i]; }
run();
}
std::printf("dp4a sycl: %llu cases, %llu mismatches\n", (unsigned long long)cases, (unsigned long long)bad);
std::printf("%s\n", bad ? "FAILED" : "PASSED");
sycl::free(dA, q); sycl::free(dB, q); sycl::free(dC, q); sycl::free(dR, q);
return bad ? 1 : 0;
}
@@ -0,0 +1,146 @@
// expert_oracle_parts_test: src/kernels/cpu/expert_oracle_parts.hpp
// 1. half conversions: exhaustive round trip, and float -> half against the hardware conversion (F16C) on x86 for random floats
// including ties, subnormals, overflow
// 2. quantize_oracle_q8_0 against an independent double-precision-assisted reference (codes, stored scale, sums, hx)
// 3. chunk_dot_oracle / row_dot_oracle against a straightforward reference built from the spec formulas
#include "../../src/kernels/cpu/expert_oracle_parts.hpp"
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <vector>
#if defined(__F16C__)
#include <immintrin.h>
#endif
using namespace strata::kernels::cpu;
using namespace strata::kernels::cpu::oracle_detail;
static int g_fail = 0;
#define CHECK(cond, ...) \
do { \
if (!(cond)) { \
++g_fail; \
std::printf("FAIL %s:%d ", __FILE__, __LINE__); \
std::printf(__VA_ARGS__); \
std::printf("\n"); \
if (g_fail > 20) return 1; \
} \
} while (0)
static uint32_t f2u(float f) { uint32_t u; std::memcpy(&u, &f, 4); return u; }
int main() {
std::mt19937_64 rng(5150);
// 1. halves
for (uint32_t h = 0; h < 65536; ++h) {
const float f = half_to_float((uint16_t)h);
const int e = (h >> 10) & 31;
if (e == 31 && (h & 1023)) { CHECK(f != f, "nan half %04x", h); continue; }
const uint16_t back = float_to_half(f);
CHECK(back == h, "round trip %04x -> %08x -> %04x", h, f2u(f), back);
}
#if defined(__F16C__)
long n_f16c = 0;
for (long it = 0; it < 30000000; ++it) {
uint32_t u = (uint32_t)rng();
if (it & 1) u = (u & 0x80000000u) | (0x30000000u + (u & 0x0FFFFFFFu)); // near the half range
if ((it & 7) == 2) u &= ~0x1FFFu; // exact ties after the shift
if ((it & 7) == 3) u = (u & ~0x1FFFu) | 0x1000u;
float f;
std::memcpy(&f, &u, 4);
if (f != f) continue;
const uint16_t a = float_to_half(f);
const uint16_t b = _cvtss_sh(f, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC);
++n_f16c;
CHECK(a == b, "float_to_half(%08x) = %04x, hardware %04x", u, a, b);
}
std::printf("float_to_half vs F16C: %ld values\n", n_f16c);
#else
std::printf("(no F16C in this build: hardware comparison skipped)\n");
#endif
// 2. quantiser
const int N = 2560;
std::vector<float> x(N);
ActQ a;
long nq = 0;
for (int it = 0; it < 4000; ++it) {
std::normal_distribution<float> nd(0.f, (it % 5 == 0) ? 1e-3f : (it % 7 == 0 ? 300.f : 1.f));
for (int i = 0; i < N; ++i) x[i] = nd(rng);
if (it % 11 == 0) for (int c = 0; c < 80; ++c) if (c % 3 == 0) for (int i = 0; i < 32; ++i) x[c * 32 + i] = 0.f; // all-zero chunks
if (it % 13 == 0) for (int i = 0; i < N; ++i) x[i] = std::ldexp(x[i], -20); // tiny scales
if (it % 17 == 0) for (int i = 0; i < N; i += 5) x[i] = (float)((int)(rng() % 255) - 127) * 0.5f; // many exact products
quantize_oracle_q8_0(x.data(), N, a);
CHECK(a.nchunks == 80, "nchunks");
for (int c = 0; c < 80; ++c) {
float amax = 0;
for (int i = 0; i < 32; ++i) amax = std::fmax(amax, std::fabs(x[c * 32 + i]));
const float d = amax / 127.0f;
const float id = amax ? 127.0f / amax : 0.f;
const float scale = half_to_float(float_to_half(d));
CHECK(f2u(a.scale[c]) == f2u(scale), "scale c=%d", c);
int sum = 0;
for (int i = 0; i < 32; ++i) {
const float p = x[c * 32 + i] * id;
double dp = (double)p;
double r = std::floor(dp + 0.5);
if (dp + 0.5 == r && std::fmod(r, 2.0) != 0.0) r -= 1.0; // ties to even
CHECK((int)a.q[c * 32 + i] == (int)r, "code c=%d i=%d p=%.9g got %d want %d", c, i, p, (int)a.q[c * 32 + i], (int)r);
sum += (int)r;
++nq;
}
CHECK(a.sum[c] == sum, "sum");
CHECK(f2u(a.hx[c]) == f2u(a.scale[c] * (float)sum), "hx");
}
}
std::printf("quantize_oracle_q8_0: %ld codes checked\n", nq);
// 3. dots
long nd2 = 0;
for (int it = 0; it < 3000; ++it) {
const int nblocks = 1 + (int)(rng() % 40);
std::vector<float> xx(nblocks * 64);
for (auto& v : xx) v = (float)((int)(rng() % 2001) - 1000) / 311.0f;
ActQ q;
quantize_oracle_q8_0(xx.data(), nblocks * 64, q);
std::vector<uint8_t> codes(nblocks * 16), scales(nblocks * 2);
for (auto& c : codes) c = (uint8_t)rng();
for (int b = 0; b < nblocks; ++b) {
const uint16_t h = float_to_half((float)((int)(rng() % 2001) - 1000) / 20000.0f);
scales[2 * b] = h & 255;
scales[2 * b + 1] = h >> 8;
}
const float got = row_dot_oracle(codes.data(), scales.data(), q, nblocks);
// reference: the formula of the spec with explicit float32 temporaries
float res = 0.f;
for (int b = 0; b < nblocks; ++b) {
int dot[2] = {0, 0};
for (int ch = 0; ch < 2; ++ch) {
int s = 0;
for (int j = 0; j < 32; ++j) {
const int bit = (b * 64 + ch * 32 + j);
const int code = (codes[bit / 4] >> (2 * (bit % 4))) & 3;
s += (code - 1) * (int)q.q[bit];
}
dot[ch] = s;
CHECK(chunk_dot_oracle(&codes[b * 16 + ch * 8], &q.q[b * 64 + ch * 32], q.sum[2 * b + ch]) == s, "chunk dot");
}
volatile float t0 = q.scale[2 * b] * (float)dot[0];
volatile float blk = 0.f;
blk = blk + t0;
volatile float t1 = q.scale[2 * b + 1] * (float)dot[1];
blk = blk + t1;
volatile float t2 = half_to_float((uint16_t)(scales[2 * b] | (scales[2 * b + 1] << 8))) * blk;
res = res + t2;
}
CHECK(f2u(got) == f2u(res), "row dot %.9g vs %.9g", got, res);
++nd2;
}
std::printf("row_dot_oracle: %ld rows checked\n", nd2);
std::printf("%s (%d failure(s))\n", g_fail ? "FAILED" : "PASSED", g_fail);
return g_fail ? 1 : 0;
}
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env python3
"""hip_rdna1_isa.py - compile-check hip_compat/dp4a_rdna1.hpp for gfx1010 and gfx1012 and compare its ISA size with the portable
__dp4a of the current hip_compat/intrinsics.hpp (device-only, nothing is run: no gfx1010 card exists on any box).
usage: python -I hip_rdna1_isa.py <worktree> <out dir>
Run through jobq on the owner PC (heavy lock): TheRock ROCm venv C:\\r0222\\rocm-venv (read-only) + the MSVC environment for the host headers.
"""
import os
import re
import subprocess
import sys
from pathlib import Path
wt, out = Path(sys.argv[1]), Path(sys.argv[2])
out.mkdir(parents=True, exist_ok=True)
ROCM_VENV = Path(r"C:\r0222\rocm-venv")
rocm = Path(subprocess.check_output([str(ROCM_VENV / "Scripts" / "rocm-sdk.exe"), "path", "--root"], text=True).strip())
def find_vs():
vswhere = Path(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")) / r"Microsoft Visual Studio\Installer\vswhere.exe"
o = subprocess.check_output([str(vswhere), "-latest", "-products", "*", "-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath"], text=True).strip()
return Path(o)
def msvc_env(vs):
bat = vs / r"VC\Auxiliary\Build\vcvars64.bat"
r = subprocess.run(f'cmd /d /s /c ""{bat}" >nul && set"', capture_output=True, text=True, errors="replace", check=True)
env = {}
for line in r.stdout.splitlines():
k, sep, v = line.partition("=")
if sep and k:
env[k.upper()] = v
return env
env = msvc_env(find_vs())
env["HIP_PLATFORM"] = "amd"
env["HIP_PATH"] = str(rocm)
env["ROCM_PATH"] = str(rocm)
env["PATH"] = f"{rocm / 'bin'};{rocm / 'lib' / 'llvm' / 'bin'};{env.get('PATH', '')}"
NEW = """#include <hip/hip_runtime.h>
#include "strata/hip_compat/dp4a_rdna1.hpp"
extern "C" __global__ void k_new(const int* a, const int* b, const int* c, int* o) {
const int i = threadIdx.x;
o[i] = strata::hip_compat::dp4a_rdna1(a[i], b[i], c[i]);
}
"""
OLD = """#include <hip/hip_runtime.h>
#include "strata/hip_compat/intrinsics.hpp"
extern "C" __global__ void k_old(const int* a, const int* b, const int* c, int* o) {
const int i = threadIdx.x;
o[i] = __dp4a(a[i], b[i], c[i]);
}
"""
LOOP = """#include <hip/hip_runtime.h>
#include <cstdint>
extern "C" __global__ void k_loop(const int* a, const int* b, const int* c, int* o) {
const int i = threadIdx.x;
int r = c[i];
for (int k = 0; k < 4; ++k) r += (int)(int8_t)((uint32_t)a[i] >> (8 * k)) * (int)(int8_t)((uint32_t)b[i] >> (8 * k));
o[i] = r;
}
"""
(out / "k_loop.hip.cpp").write_text(LOOP)
(out / "k_new.hip.cpp").write_text(NEW)
(out / "k_old.hip.cpp").write_text(OLD)
clang = None
for cand in (rocm / "lib" / "llvm" / "bin" / "clang++.exe", rocm / "lib" / "llvm" / "bin" / "amdclang++.exe"):
if cand.exists():
clang = cand
break
if clang is None:
raise SystemExit("no clang++ in the ROCm SDK")
def count(asm):
global mn
mn = {}
n = 0
in_fn = False
for ln in asm.splitlines():
s = ln.strip()
if s.startswith("k_new:") or s.startswith("k_old:") or s.startswith("k_loop:"):
in_fn = True
continue
if in_fn and s.startswith(".Lfunc_end"):
break
if in_fn and s.startswith("v_"):
n += 1
mn[s.split()[0]] = mn.get(s.split()[0], 0) + 1
return n
bad = 0
for arch in ("gfx1010", "gfx1012"):
res = {}
for name in ("new", "old", "loop"):
src = out / f"k_{name}.hip.cpp"
asm = out / f"k_{name}.{arch}.s"
cmd = [str(clang), "-x", "hip", f"--offload-arch={arch}", "--cuda-device-only", "-O3", "-S", f"--rocm-path={rocm}", f"--rocm-device-lib-path={rocm.as_posix()}/lib/llvm/amdgcn/bitcode", "-I", str(wt / "engine" / "include"), str(src), "-o", str(asm)]
r = subprocess.run(cmd, env=env, capture_output=True, text=True)
print(arch, name, "rc", r.returncode)
if r.returncode:
print(r.stderr[-1500:])
bad += 1
continue
res[name] = count(asm.read_text())
print(arch, name, "VALU instructions in the kernel:", res[name], dict(sorted(mn.items())))
if name == "new" and any("dot" in k for k in mn):
print("FAIL: a dot instruction in the new kernel")
bad += 1
if len(res) == 3:
print(arch, "new <= old:", res["new"] <= res["old"], " new <= loop:", res["new"] <= res["loop"])
if res["new"] > res["old"] or res["new"] > res["loop"]:
bad += 1
print("RESULT", "FAIL" if bad else "OK")
sys.exit(1 if bad else 0)
@@ -0,0 +1,10 @@
// Prints host_iq2xs_grid and host_ksigns_iq2xs of the .inc named by -DTABLES_INC="..."; two builds (old and generated .inc) must print the same text.
#include <cstdint>
#include <cstdio>
#include TABLES_INC
int main() {
for (int i = 0; i < 512; ++i) std::printf("%016llx\n", (unsigned long long)host_iq2xs_grid[i]);
for (int i = 0; i < 128; ++i) std::printf("%02x\n", (unsigned)host_ksigns_iq2xs[i]);
return 0;
}
@@ -0,0 +1,86 @@
// kq_dots_avx2_test: every token of the multi-token kernels (src/kernels/cpu/kq_dots_avx2.cpp) against the single-token Avx2 dot of the quant layer, bit for bit,
// for n = 1, 2, 5, 8 tokens (and 3, 4, 6, 7, 9, 13 for the two groupable kernels) and nb = 1, 2, 7, 12 blocks, random rows and activations
// (real quantiser output and raw random bytes, -128 included).
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <vector>
#include "../../src/kernels/cpu/kq_dots_avx2.hpp"
#include "probe_blocks.hpp"
#include "strata/quant/act.hpp"
#include "strata/quant/dot.hpp"
using namespace strata::quant;
namespace kq = strata::kernels::cpu::kqd;
int main(int argc, char** argv) {
const long iters = argc > 1 ? atol(argv[1]) : 2000;
std::mt19937_64 rng(777);
int fail = 0;
struct K { const char* name; Type w; int wb, ab, elems; int maxnt; } ks[] = {
{"q4_K x q8_K", Type::Q4_K, 144, 292, 256, 8},
{"q5_1 x q8_1", Type::Q5_1, 24, 36, 32, 13},
{"q8_0 x q8_0", Type::Q8_0, 34, 34, 32, 13},
};
const int nts[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 13};
const int nbs[] = {1, 2, 7, 12};
for (const K& k : ks) {
const DotKernel* single = dot_kernel(k.w, Arith::Avx2, Isa::Avx2);
long bad = 0, total = 0;
for (long it = 0; it < iters; ++it) {
const int nt = nts[rng() % 10];
if (nt > k.maxnt) continue;
const int nb = nbs[rng() % 4];
const int n = nb * k.elems;
std::vector<uint8_t> w((size_t)nb * k.wb);
for (auto& b : w) b = (uint8_t)rng();
for (int b = 0; b < nb; ++b) {
put_half(&w[(size_t)b * k.wb], rand_half(rng, -10, 4));
if (k.w == Type::Q4_K) put_half(&w[(size_t)b * k.wb + 2], rand_half(rng, -10, 4));
if (k.w == Type::Q5_1) put_half(&w[(size_t)b * k.wb + 2], rand_half(rng, -10, 4));
}
std::vector<std::vector<uint8_t>> acts(nt, std::vector<uint8_t>((size_t)nb * k.ab));
std::vector<const void*> ap(nt);
for (int t = 0; t < nt; ++t) {
if (it & 1) {
std::vector<float> x(n);
std::normal_distribution<float> nd(0.f, 1.f);
for (auto& v : x) v = nd(rng);
act_kernel(k.w == Type::Q4_K ? Type::Q8_K : (k.w == Type::Q5_1 ? Type::Q8_1 : Type::Q8_0), Arith::Avx2)->fn(x.data(), acts[t].data(), n);
} else {
for (auto& b : acts[t]) b = (uint8_t)rng();
for (int b = 0; b < nb; ++b) {
uint8_t* p = &acts[t][(size_t)b * k.ab];
if (k.w == Type::Q4_K) {
const float d = std::ldexp(0.5f + (float)(rng() % 1000) / 1000.f, (int)(rng() % 12) - 12);
std::memcpy(p, &d, 4);
for (int g = 0; g < 16; ++g) { int16_t s = 0; for (int i = 0; i < 16; ++i) s = (int16_t)(s + (int8_t)p[4 + 16 * g + i]); std::memcpy(p + 260 + 2 * g, &s, 2); }
} else {
put_half(p, rand_half(rng, -10, 4));
if (k.w == Type::Q5_1) put_half(p + 2, rand_half(rng, -10, 4));
}
}
}
ap[t] = acts[t].data();
}
std::vector<float> res(nt, 0.f);
if (k.w == Type::Q4_K) kq::q4k_dot((const block_q4_K*)w.data(), nb, ap.data(), nt, res.data());
else if (k.w == Type::Q5_1) kq::q5_1_dot_nt((const block_q5_1*)w.data(), nb, ap.data(), nt, res.data());
else kq::q8_0_dot_nt((const block_q8_0*)w.data(), nb, ap.data(), nt, res.data());
for (int t = 0; t < nt; ++t) {
float one = 0;
single->fn(n, &one, w.data(), ap[t]);
++total;
if (std::memcmp(&one, &res[t], 4) && !(one != one && res[t] != res[t])) {
if (++bad <= 3) printf(" %s MISMATCH nt=%d nb=%d token %d: single %.9g (%08x) multi %.9g (%08x)\n", k.name, nt, nb, t, one, *(uint32_t*)&one, res[t], *(uint32_t*)&res[t]);
}
}
}
printf("%s %-12s %ld token results: %ld mismatches\n", bad ? "FAIL" : "ok ", k.name, total, bad);
if (bad) ++fail;
}
printf("%s\n", fail ? "FAILED" : "PASSED");
return fail ? 1 : 0;
}
+89
View File
@@ -0,0 +1,89 @@
// model_mins: the dmin term of the Avx2 Q4_K / Q5_K dots. Rows with dmin != 0; the A part (scales x quants) follows the model of model_scan; the
// min part is -dmin*da*sum_j m_j*(bsums[2j] + bsums[2j+1]). Options scanned: how the integer min sums are laid out (scalar / 4 lanes of sub-block pairs /
// 8 lanes), the float scale (fl(dmin*da)), accumulate fused / unfused, the 4-lane or 8-lane final tree, and how it joins the A result.
#include "model_ref.hpp"
#include "probe_core.hpp"
static float tree8(const float* v) { return ((v[0] + v[4]) + (v[2] + v[6])) + ((v[1] + v[5]) + (v[3] + v[7])); }
int main(int argc, char** argv) {
const std::string name = argc > 1 ? argv[1] : "q4_K";
const long rows = argc > 2 ? atol(argv[2]) : 30000;
ProbeType* t = find_probe_type(name);
const DotKernel* k = dot_kernel(t->type, Arith::Avx2, Isa::Avx2);
std::mt19937_64 rng(99);
const int NOPT = 2 * 3 * 2 * 3; // layout(S,L4,L8) x fused x tree(L4: movehl+shuf / adjacent) x join(A-m, A+(-m), m first)
std::vector<long> bad(NOPT, 0);
long cnt = 0;
for (long it = 0; it < rows; ++it) {
const int nb = 1 + (int)(rng() % 5);
ProbeRow r(*t, nb);
for (int b = 0; b < nb; ++b) {
for (int i = 0; i < t->wbytes; ++i) r.wb(b)[i] = (uint8_t)rng();
put_half(r.wb(b), rand_half(rng));
put_half(r.wb(b) + 2, rand_half(rng));
const float d = std::ldexp(0.5f + (float)(rng() % 1000) / 1000.0f, (int)(rng() % 7) - 9) * ((rng() & 1) ? 1.f : -1.f);
std::memcpy(r.ab(b), &d, 4);
const int mode = (int)(rng() % 4); // mode 3: no products at all, only bsums (isolates the min term)
for (int i = 0; i < 256; ++i) {
int v = mode == 0 ? (int)(rng() % 255) - 127 : mode == 1 ? (int)(rng() % 31) - 15 : mode == 2 ? (rng() % 4 == 0 ? (int)(rng() % 255) - 127 : 0) : 0;
r.set_act(b, i, (int8_t)v);
}
if (mode == 3)
for (int t2 = 0; t2 < 16; ++t2) {
const int16_t s = (int16_t)((int)(rng() % 4001) - 2000);
std::memcpy(r.ab(b) + 260 + 2 * t2, &s, 2);
}
}
float oracle = 0;
k->fn(nb * 256, &oracle, r.w.data(), r.a.data());
++cnt;
float accA[8] = {};
std::vector<int> m8(nb * 8);
for (int b = 0; b < nb; ++b) {
int lane[8];
lane_ints(t->pt, r.wb(b), r.ab(b), lane);
const float D = r.wd(b) * r.act_d(b);
for (int l = 0; l < 8; ++l) accA[l] = std::fmaf(D, (float)lane[l], accA[l]);
const uint8_t* s12 = r.wb(b) + 4;
const int16_t* bs = (const int16_t*)(r.ab(b) + 260);
for (int j = 0; j < 8; ++j) {
const int mj = j < 4 ? (s12[j + 4] & 63) : ((s12[j + 4] >> 4) | ((s12[j] >> 6) << 4));
m8[b * 8 + j] = mj * ((int)bs[2 * j] + (int)bs[2 * j + 1]);
}
}
const float A = tree8(accA);
int o = 0;
for (int layout = 0; layout < 3; ++layout)
for (int fused = 0; fused < 2; ++fused)
for (int tr = 0; tr < 2; ++tr)
for (int join = 0; join < 3; ++join, ++o) {
// scalar: one lane; L4: lane k = pair (2k, 2k+1); L8: lane j
float acc[8] = {};
for (int b = 0; b < nb; ++b) {
const float dm = fp16_to_fp32(get_half(r.wb(b) + 2)) * r.act_d(b);
int v[8] = {};
if (layout == 0) { int s = 0; for (int j = 0; j < 8; ++j) s += m8[b * 8 + j]; v[0] = s; }
else if (layout == 1) for (int j = 0; j < 8; ++j) v[j / 2] += m8[b * 8 + j];
else for (int j = 0; j < 8; ++j) v[j] = m8[b * 8 + j];
for (int l = 0; l < 8; ++l) acc[l] = fused ? std::fmaf(dm, (float)v[l], acc[l]) : acc[l] + dm * (float)v[l];
}
float mt;
if (layout == 0) mt = acc[0];
else if (layout == 1) mt = tr == 0 ? (acc[0] + acc[2]) + (acc[1] + acc[3]) : (acc[0] + acc[1]) + (acc[2] + acc[3]);
else mt = tr == 0 ? tree8(acc) : ((acc[0] + acc[1]) + (acc[2] + acc[3])) + ((acc[4] + acc[5]) + (acc[6] + acc[7]));
float res;
if (join == 0) res = A - mt;
else if (join == 1) res = A + (-mt);
else res = (-mt) + A;
if (std::memcmp(&res, &oracle, 4)) ++bad[o];
}
}
int o = 0;
for (int layout = 0; layout < 3; ++layout)
for (int fused = 0; fused < 2; ++fused)
for (int tr = 0; tr < 2; ++tr)
for (int join = 0; join < 3; ++join, ++o)
if (bad[o] < cnt / 3) printf("layout %s %s tree%d join%d: mismatches %ld / %ld\n", layout == 0 ? "scalar" : layout == 1 ? "L4" : "L8", fused ? "fma" : "mul+add", tr, join, bad[o], cnt);
return 0;
}
+54
View File
@@ -0,0 +1,54 @@
// model_q51: float composition of the Avx2 Q5_1 x Q8_1 dot: lanes (4 adjacent products), acc[l] = fma(D, lane, acc[l]), the min part m_w * s_a, and how they join.
#include "probe_core.hpp"
static float tree8(const float* v) { return ((v[0] + v[4]) + (v[2] + v[6])) + ((v[1] + v[5]) + (v[3] + v[7])); }
int main(int argc, char** argv) {
const long rows = argc > 1 ? atol(argv[1]) : 50000;
ProbeType* t = find_probe_type("q5_1");
const DotKernel* k = dot_kernel(t->type, Arith::Avx2, Isa::Avx2);
std::mt19937_64 rng(51);
long bad[2][2][2] = {}; // acc fused, min fused, join order (A + m, m + A is the same in IEEE; second slot: A - (-m) irrelevant) -> kept for symmetry
long cnt = 0;
for (long it = 0; it < rows; ++it) {
const int nb = 1 + (int)(rng() % 9);
ProbeRow r(*t, nb);
for (int b = 0; b < nb; ++b) {
for (int i = 0; i < 24; ++i) r.wb(b)[i] = (uint8_t)rng();
put_half(r.wb(b), rand_half(rng));
put_half(r.wb(b) + 2, rand_half(rng));
put_half(r.ab(b), rand_half(rng));
put_half(r.ab(b) + 2, rand_half(rng));
const int mode = (int)(rng() % 3);
for (int i = 0; i < 32; ++i) r.ab(b)[4 + i] = (uint8_t)(int8_t)(mode == 0 ? (int)(rng() % 256) - 128 : mode == 1 ? (int)(rng() % 31) - 15 : (rng() % 4 == 0 ? (int)(rng() % 255) - 127 : 0));
}
float oracle = 0;
k->fn(nb * 32, &oracle, r.w.data(), r.a.data());
++cnt;
for (int af = 0; af < 2; ++af)
for (int mf = 0; mf < 2; ++mf) {
float acc[8] = {};
float summs = 0.f;
for (int b = 0; b < nb; ++b) {
const uint8_t* w = r.wb(b);
const uint8_t* a = r.ab(b);
const uint32_t qh = (uint32_t)(w[4] | (w[5] << 8) | (w[6] << 16) | ((uint32_t)w[7] << 24));
int lane[8] = {};
for (int i = 0; i < 32; ++i) {
const int j = i % 16;
const int q5 = ((i >= 16 ? (w[8 + j] >> 4) : (w[8 + j] & 15))) | (int)(((qh >> i) & 1) << 4);
lane[i / 4] += q5 * (int)(int8_t)a[4 + i];
}
const float D = fp16_to_fp32(get_half(w)) * fp16_to_fp32(get_half(a));
for (int l = 0; l < 8; ++l) acc[l] = af ? std::fmaf(D, (float)lane[l], acc[l]) : acc[l] + D * (float)lane[l];
const float mw = fp16_to_fp32(get_half(w + 2)), sa = fp16_to_fp32(get_half(a + 2));
summs = mf ? std::fmaf(mw, sa, summs) : summs + mw * sa;
}
const float res = tree8(acc) + summs;
if (std::memcmp(&res, &oracle, 4)) ++bad[af][mf][0];
}
}
for (int af = 0; af < 2; ++af)
for (int mf = 0; mf < 2; ++mf) printf("acc %s, min %s: mismatches %ld / %ld\n", af ? "fma" : "mul+add", mf ? "fma" : "mul+add", bad[af][mf][0], cnt);
return 0;
}
+77
View File
@@ -0,0 +1,77 @@
// model_ref.hpp - scalar models of the integer lane structure of the Avx2 K-quant dots, found by the probes (probe_lanes / probe_q6k / probe_tree).
// lane_ints(type, wblock, ablock, lane[8]) gives, for one 256-element block, the 8 integer lane sums the Avx2 kernels convert to float; the model of the
// float composition (fused multiply-add per block, then a fixed tree) is tested in model_scan.cpp.
#pragma once
#include <cstdint>
#include <cstring>
#include "probe_blocks.hpp"
inline int lane_of(int i) { return (i % 32) / 4; }
// returns false if the type is not modelled
inline bool lane_ints(PT pt, const uint8_t* w, const uint8_t* a, int lane[8]) {
const int8_t* qa = (const int8_t*)(a + 4);
const int16_t* bs = (const int16_t*)(a + 260);
for (int l = 0; l < 8; ++l) lane[l] = 0;
switch (pt) {
case PQ6_K: {
const uint8_t* ql = w;
const uint8_t* qh = w + 128;
const int8_t* sc = (const int8_t*)(w + 192);
for (int i = 0; i < 256; ++i) {
const int n = i / 128, p = (i % 128) / 32, l = i % 32;
const int lo = (p < 2) ? (ql[64 * n + 32 * (p & 1) + l] & 15) : (ql[64 * n + 32 * (p & 1) + l] >> 4);
const int hi = (qh[32 * n + l] >> (2 * p)) & 3;
const int qu = lo | (hi << 4);
const int s = 8 * n + 2 * p + l / 16;
lane[lane_of(i)] += sc[s] * qu * qa[i];
}
for (int t = 0; t < 16; ++t) lane[t / 2] -= 32 * sc[t] * (int)bs[t];
return true;
}
case PQ4_K:
case PQ5_K: {
const uint8_t* s12 = w + 4;
const uint8_t* qh = w + 16;
const uint8_t* qs = w + (pt == PQ4_K ? 16 : 48);
int sc[8];
for (int j = 0; j < 8; ++j) sc[j] = j < 4 ? (s12[j] & 63) : ((s12[j + 4] & 15) | ((s12[j - 4] >> 6) << 4));
for (int i = 0; i < 256; ++i) {
const int g = i / 64, h = (i / 32) % 2, l = i % 32, j = 2 * g + h;
int q = h ? (qs[32 * g + l] >> 4) : (qs[32 * g + l] & 15);
if (pt == PQ5_K) q |= ((qh[l] >> j) & 1) << 4;
lane[lane_of(i)] += sc[j] * q * qa[i];
}
return true;
}
case PIQ4_XS: {
const uint16_t sh = (uint16_t)(w[2] | (w[3] << 8));
for (int i = 0; i < 256; ++i) {
const int ib = i / 32, r = i % 32, j = r % 16;
const int ls = ((w[4 + ib / 2] >> (4 * (ib % 2))) & 15) | (((sh >> (2 * ib)) & 3) << 4);
const uint8_t byte = w[8 + 16 * ib + j];
const int nib = r >= 16 ? (byte >> 4) : (byte & 15);
// weights are signed here: the kernel takes |kv| and moves the sign to the activation (wrap-around at -128 included)
int sy = kKV[nib] < 0 ? -(int)qa[i] : (int)qa[i];
sy = (int8_t)sy;
const int ax = kKV[nib] < 0 ? -kKV[nib] : kKV[nib];
lane[lane_of(i)] += (ls - 32) * ax * sy;
}
return true;
}
case PIQ3_XXS: {
const auto& G = iq3xxs_grid();
for (int i = 0; i < 256; ++i) {
const int g = i / 32, l = (i % 32) / 8, pos = i % 8, half = pos / 4, j = pos % 4;
const uint32_t wg = (uint32_t)(w[66 + 4 * g] | (w[67 + 4 * g] << 8) | (w[68 + 4 * g] << 16) | ((uint32_t)w[69 + 4 * g] << 24));
const int v = (int)((wg >> (7 * l)) & 127), ls = (int)(wg >> 28);
const int gv = G[w[2 + 8 * g + 2 * l + half]][j];
const int sign = ksign(v, half * 4 + j) ? -1 : 1;
const int sy = (int8_t)(sign < 0 ? -(int)qa[i] : (int)qa[i]); // the sign moves to the activation; -128 wraps
lane[lane_of(i)] += (2 * ls + 1) * gv * sy;
}
return true;
}
default: return false;
}
}
+58
View File
@@ -0,0 +1,58 @@
// model_scan: random full rows of a K-quant type against the lane model of model_ref.hpp + float composition options; counts mismatches with the oracle kernel.
// usage: model_scan <q6_K|q4_K|q5_K|iq4_xs> [rows] [mins 0/1]
#include "model_ref.hpp"
#include "probe_core.hpp"
static float tree8(const float* v) {
return ((v[0] + v[4]) + (v[2] + v[6])) + ((v[1] + v[5]) + (v[3] + v[7]));
}
int main(int argc, char** argv) {
const std::string name = argc > 1 ? argv[1] : "q6_K";
const long rows = argc > 2 ? atol(argv[2]) : 50000;
const int mins = argc > 3 ? atoi(argv[3]) : 0;
ProbeType* t = find_probe_type(name);
const DotKernel* k = dot_kernel(t->type, Arith::Avx2, Isa::Avx2);
std::mt19937_64 rng(2026);
long bad[2][2] = {}; // fused, NA(1,2)
long cnt = 0;
for (long it = 0; it < rows; ++it) {
const int nb = 1 + (int)(rng() % 6);
ProbeRow r(*t, nb);
for (int b = 0; b < nb; ++b) {
for (auto& x : std::vector<uint8_t*>{r.wb(b)}) for (int i = 0; i < t->wbytes; ++i) x[i] = (uint8_t)rng();
// halves finite and moderate
const int dpos = (t->pt == PQ6_K) ? 208 : 0;
put_half(r.wb(b) + dpos, rand_half(rng));
if (t->pt == PQ4_K || t->pt == PQ5_K) put_half(r.wb(b) + 2, mins ? rand_half(rng) : 0);
const float d = std::ldexp(0.5f + (float)(rng() % 1000) / 1000.0f, (int)(rng() % 7) - 9) * ((rng() & 1) ? 1.f : -1.f);
std::memcpy(r.ab(b), &d, 4);
const int mode = (int)(rng() % 3);
for (int i = 0; i < 256; ++i) {
int v = mode == 0 ? (int)(rng() % 256) - 128 : mode == 1 ? (int)(rng() % 31) - 15 : (rng() % 4 == 0 ? (int)(rng() % 255) - 127 : 0);
r.set_act(b, i, (int8_t)v);
}
if ((rng() % 4) == 0) for (int t2 = 0; t2 < 16; ++t2) { int16_t s = (int16_t)((int)(rng() % 4001) - 2000); if (rng() % 2) s = 0; std::memcpy(r.ab(b) + 260 + 2 * t2, &s, 2); if (!mins && t->pt != PQ6_K) {} }
}
float oracle = 0;
k->fn(nb * 256, &oracle, r.w.data(), r.a.data());
++cnt;
for (int fused = 0; fused < 2; ++fused)
for (int na = 0; na < 2; ++na) {
float acc[2][8] = {};
for (int b = 0; b < nb; ++b) {
int lane[8];
lane_ints(t->pt, r.wb(b), r.ab(b), lane);
const float D = r.D(b);
float* ac = acc[na ? b % 2 : 0];
for (int l = 0; l < 8; ++l) ac[l] = fused ? std::fmaf(D, (float)lane[l], ac[l]) : ac[l] + D * (float)lane[l];
}
float tot[8];
for (int l = 0; l < 8; ++l) tot[l] = na ? acc[0][l] + acc[1][l] : acc[0][l];
const float res = tree8(tot);
if (std::memcmp(&res, &oracle, 4)) ++bad[fused][na];
}
}
printf("%s (mins %d): rows %ld; mismatches: fused NA1 %ld, fused NA2 %ld, unfused NA1 %ld, unfused NA2 %ld\n", name.c_str(), mins, cnt, bad[1][0], bad[1][1], bad[0][0], bad[0][1]);
return 0;
}
+63
View File
@@ -0,0 +1,63 @@
// neon_act_dump: deterministic activation-quantiser cases through strata::quant::neon::quantize_q8_{0,1,K}; prints one FNV-1a line per case.
// Build it against the old library and the new one and diff the outputs: they must be identical (byte-exact quantisers).
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <random>
#include <vector>
namespace strata::quant::neon {
void quantize_q8_0(const float*, void*, int64_t);
void quantize_q8_1(const float*, void*, int64_t);
void quantize_q8_K(const float*, void*, int64_t);
} // namespace strata::quant::neon
static uint64_t fnv(const uint8_t* p, size_t n, uint64_t h = 1469598103934665603ull) {
for (size_t i = 0; i < n; ++i) { h ^= p[i]; h *= 1099511628211ull; }
return h;
}
int main(int argc, char** argv) {
const long N = argc > 1 ? std::atol(argv[1]) : 200000;
std::mt19937_64 rng(4242);
std::normal_distribution<float> nd(0.f, 1.f);
uint64_t total = 1469598103934665603ull;
for (long it = 0; it < N; ++it) {
const int kind = (int)(rng() % 3);
const int bs = kind == 2 ? 256 : 32;
const int nblk = 1 + (int)(rng() % 3);
std::vector<float> x((size_t)bs * nblk);
const int mode = (int)(rng() % 15);
for (int b = 0; b < nblk; ++b) {
float* xb = &x[(size_t)bs * b];
const float scale = std::ldexp(1.0f, (int)(rng() % 40) - 25) * (1.0f + (float)(rng() % 1000) / 777.0f);
switch (mode) {
case 0: for (int i = 0; i < bs; ++i) xb[i] = nd(rng) * scale; break;
case 1: for (int i = 0; i < bs; ++i) xb[i] = 0.0f; break; // all zero
case 2: for (int i = 0; i < bs; ++i) xb[i] = (i & 1) ? -0.0f : 0.0f; break; // signed zeros
case 3: for (int i = 0; i < bs; ++i) xb[i] = ((float)((int)(rng() % 255) - 127) + 0.5f * (float)(rng() % 2)) * scale; break; // near ties
case 4: for (int i = 0; i < bs; ++i) xb[i] = scale; break; // all equal
case 5: for (int i = 0; i < bs; ++i) xb[i] = nd(rng) * scale; xb[3] = 5.0f * scale; xb[bs - 2] = -5.0f * scale; break; // max twice, opposite signs
case 6: for (int i = 0; i < bs; ++i) xb[i] = std::ldexp(nd(rng), -140); break; // subnormals
case 7: for (int i = 0; i < bs; ++i) xb[i] = nd(rng) * 1e30f; break; // huge
case 8: for (int i = 0; i < bs; ++i) xb[i] = ((float)((int)(rng() % 255) - 127)) * scale + 0.5f * scale; break; // exact half steps of the scale
case 9: for (int i = 0; i < bs; ++i) xb[i] = (rng() % 8 == 0) ? nd(rng) * scale : 0.0f; break; // sparse
case 10: { for (int i = 0; i < bs; ++i) xb[i] = nd(rng) * scale; xb[(int)(rng() % bs)] = -9.0f * scale; break; }
case 11: for (int i = 0; i < bs; ++i) xb[i] = nd(rng) * scale; xb[(int)(rng() % bs)] = INFINITY; break; // an infinity
case 12: for (int i = 0; i < bs; ++i) xb[i] = nd(rng) * scale; xb[(int)(rng() % bs)] = -INFINITY; break;
case 13: for (int i = 0; i < bs; ++i) xb[i] = nd(rng) * scale; xb[(int)(rng() % bs)] = NAN; break; // a NaN
default: for (int i = 0; i < bs; ++i) xb[i] = (float)((int)(rng() % 255) - 127) * 0.37f * scale; break;
}
}
std::vector<uint8_t> y((size_t)(kind == 0 ? 34 : kind == 1 ? 36 : 292) * nblk, 0xA5);
if (kind == 0) strata::quant::neon::quantize_q8_0(x.data(), y.data(), (int64_t)x.size());
else if (kind == 1) strata::quant::neon::quantize_q8_1(x.data(), y.data(), (int64_t)x.size());
else strata::quant::neon::quantize_q8_K(x.data(), y.data(), (int64_t)x.size());
const uint64_t h = fnv(y.data(), y.size());
total = fnv((const uint8_t*)&h, 8, total);
if (argc > 2) std::printf("%ld %d %d %016llx\n", it, kind, mode, (unsigned long long)h);
}
std::printf("total %016llx over %ld cases\n", (unsigned long long)total, N);
return 0;
}
+118
View File
@@ -0,0 +1,118 @@
// neon_act_test: the NEON activation quantisers (arm_act_clean.inc, as strata::quant::neon::quantize_q8_{0,1,K}) against
// Q8_0 / Q8_1 : a scalar model of FORMAT-SPEC Part II section 19 (row Neon): d = amax / 127, id = 1 / d (0 for d = 0), q = half-even(x * id), d stored as half(d),
// Q8_1 adds s = half(d * sum q)
// Q8_K : quantize_q8_K_ref of the layer (the Generic reference; the NEON code is bit-exact to it for the build's compiler)
// on random blocks with ties, zeros, signed zeros, subnormals, equal maxima of both signs, huge values and infinities. Buffers are zero-filled so a block whose
// bsums the all-zero case leaves alone compares equal. Exit 0 = every byte of every case equal.
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <random>
#include <vector>
#include "strata/quant/act.hpp"
namespace strata::quant::neon {
void quantize_q8_0(const float*, void*, int64_t);
void quantize_q8_1(const float*, void*, int64_t);
void quantize_q8_K(const float*, void*, int64_t);
} // namespace strata::quant::neon
using namespace strata::quant;
static uint16_t f2h(float f) { __fp16 t = (__fp16)f; uint16_t u; std::memcpy(&u, &t, 2); return u; }
static void model_q8_0_1(const float* x, uint8_t* y, int64_t k, bool q81) {
const int bytes = q81 ? 36 : 34;
for (int64_t b = 0; b < k / 32; ++b) {
const float* xb = x + 32 * b;
float amax = 0;
for (int i = 0; i < 32; ++i) amax = std::fmax(amax, std::fabs(xb[i]));
const float d = amax / 127.0f;
const float id = d != 0.0f ? 1.0f / d : 0.0f;
uint8_t* yb = y + bytes * b;
const uint16_t dh = f2h(d);
std::memcpy(yb, &dh, 2);
int sum = 0;
for (int i = 0; i < 32; ++i) {
const int q = (int)std::nearbyintf(xb[i] * id);
yb[(q81 ? 4 : 2) + i] = (uint8_t)(int8_t)q;
sum += q;
}
if (q81) { const uint16_t sh = f2h(d * (float)sum); std::memcpy(yb + 2, &sh, 2); }
}
}
int main(int argc, char** argv) {
const long N = argc > 1 ? std::atol(argv[1]) : 300000;
std::mt19937_64 rng(99);
std::normal_distribution<float> nd(0.f, 1.f);
long bad[3] = {0, 0, 0}, cnt[3] = {0, 0, 0};
const ActKernel* k0 = act_kernel(Type::Q8_0, Arith::Neon, Isa::Neon);
const ActKernel* k1 = act_kernel(Type::Q8_1, Arith::Neon, Isa::Neon);
const ActKernel* kK = act_kernel(Type::Q8_K, Arith::Neon, Isa::Neon);
if (!k0 || !k1 || !kK) { std::printf("FAIL: the dispatcher has no Neon activation kernel\n"); return 1; }
for (long it = 0; it < N; ++it) {
const int kind = (int)(rng() % 3);
const int bs = kind == 2 ? 256 : 32;
const int nblk = 1 + (int)(rng() % 3);
std::vector<float> x((size_t)bs * nblk);
const int mode = (int)(rng() % 14);
for (int b = 0; b < nblk; ++b) {
float* xb = &x[(size_t)bs * b];
const float scale = std::ldexp(1.0f, (int)(rng() % 40) - 25) * (1.0f + (float)(rng() % 1000) / 777.0f);
for (int i = 0; i < bs; ++i) {
switch (mode) {
case 0: xb[i] = nd(rng) * scale; break;
case 1: xb[i] = 0.0f; break;
case 2: xb[i] = (i & 1) ? -0.0f : 0.0f; break;
case 3: xb[i] = ((float)((int)(rng() % 255) - 127) + 0.5f * (float)(rng() % 2)) * scale; break;
case 4: xb[i] = scale; break;
case 5: xb[i] = nd(rng) * scale; break;
case 6: xb[i] = std::ldexp(nd(rng), -140); break;
case 7: xb[i] = nd(rng) * 1e30f; break;
case 8: xb[i] = ((float)((int)(rng() % 255) - 127)) * scale + 0.5f * scale; break;
case 9: xb[i] = (rng() % 8 == 0) ? nd(rng) * scale : 0.0f; break;
case 10: xb[i] = nd(rng) * scale; break;
case 11: xb[i] = nd(rng) * scale; break;
case 12: xb[i] = nd(rng) * scale; break;
default: xb[i] = (float)((int)(rng() % 255) - 127) * 0.37f * scale; break;
}
}
if (mode == 5) { xb[3] = 5.0f * scale; xb[bs - 2] = -5.0f * scale; } // maximum twice, opposite signs
if (mode == 10) xb[(int)(rng() % bs)] = -9.0f * scale;
if (mode == 11) xb[(int)(rng() % bs)] = INFINITY;
if (mode == 12) xb[(int)(rng() % bs)] = -INFINITY;
}
const size_t ybytes = (size_t)(kind == 0 ? 34 : kind == 1 ? 36 : 292) * nblk;
std::vector<uint8_t> got(ybytes, 0), want(ybytes, 0);
if (kind == 0) { k0->fn(x.data(), got.data(), (int64_t)x.size()); model_q8_0_1(x.data(), want.data(), (int64_t)x.size(), false); }
else if (kind == 1) { k1->fn(x.data(), got.data(), (int64_t)x.size()); model_q8_0_1(x.data(), want.data(), (int64_t)x.size(), true); }
else { kK->fn(x.data(), got.data(), (int64_t)x.size()); quantize_q8_K_ref(x.data(), want.data(), (int64_t)x.size()); }
++cnt[kind];
if (got != want && ++bad[kind] <= 2) std::printf(" MISMATCH kind %d mode %d case %ld\n", kind, mode, it);
}
const char* nm[3] = {"Q8_0", "Q8_1", "Q8_K"};
int fail = 0;
for (int i = 0; i < 3; ++i) {
std::printf("%s %s: %ld cases, %ld differ\n", bad[i] ? "FAIL" : "ok ", nm[i], cnt[i], bad[i]);
fail += bad[i] != 0;
}
// the SIMD Q8_K quantiser itself (not only the dispatcher's pick) against the reference
{
long b2 = 0;
for (int t = 0; t < 20000; ++t) {
std::vector<float> x(256);
for (auto& v : x) v = nd(rng) * std::ldexp(1.0f, (int)(rng() % 20) - 10);
std::vector<uint8_t> a(292, 0), b(292, 0);
neon::quantize_q8_K(x.data(), a.data(), 256);
quantize_q8_K_ref(x.data(), b.data(), 256);
b2 += a != b;
}
std::printf("%s neon::quantize_q8_K vs quantize_q8_K_ref: %ld / 20000 differ\n", b2 ? "FAIL" : "ok ", b2);
fail += b2 != 0;
}
std::printf("%s\n", fail ? "FAILED" : "PASSED");
return fail ? 1 : 0;
}
+49
View File
@@ -0,0 +1,49 @@
// debugging aid for the Q8_0 probe: which element positions of a block share an integer lane (nb = 2, block 0 live)
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <random>
#include <vector>
namespace strata::quant::neon {
void dot_q8_0_q8_0(int, float*, const void*, const void*);
}
static float h2f(uint16_t h) { __fp16 t; std::memcpy(&t, &h, 2); return (float)t; }
static uint16_t f2h(float f) { __fp16 t = f; uint16_t u; std::memcpy(&u, &t, 2); return u; }
static float run(int nb, const uint8_t* W, const uint8_t* A) { float s = 0; strata::quant::neon::dot_q8_0_q8_0(32 * nb, &s, W, A); return s; }
int main() {
std::mt19937_64 rng(5);
int nb = 2;
// same[i][j]: 1 = single rounding (same lane), 0 = two roundings, -1 undecided
int vote_s[32][32] = {{0}}, vote_d[32][32] = {{0}};
for (int i = 0; i < 32; ++i)
for (int j = i + 1; j < 32; ++j)
for (int trial = 0; trial < 60; ++trial) {
uint8_t W[68] = {0}, A[68] = {0};
uint16_t h = f2h(0.5f + (float)(rng() % 1000) / 1000.f);
std::memcpy(W, &h, 2);
h = f2h(0.5f + (float)(rng() % 1000) / 1000.f);
std::memcpy(A, &h, 2);
int pi = 1 + (int)(rng() % 127), pj = 1 + (int)(rng() % 127);
W[2 + i] = (uint8_t)pi; A[2 + i] = (uint8_t)(int8_t)(1 + (int)(rng() % 120)); const int ai = (int8_t)A[2 + i];
W[2 + j] = (uint8_t)pj; A[2 + j] = (uint8_t)(int8_t)(1 + (int)(rng() % 120)); const int aj = (int8_t)A[2 + j];
const float D = h2f(*(uint16_t*)W) * h2f(*(uint16_t*)A);
const float r = run(nb, W, A);
const float Hs = D * (float)(pi * ai + pj * aj);
const float Hd = D * (float)(pi * ai) + D * (float)(pj * aj);
if (Hs != Hd) { vote_s[i][j] += r == Hs; vote_d[i][j] += r == Hd; }
}
// print the classes: for each i the set of j in the same lane
for (int i = 0; i < 32; ++i) {
std::printf("pos %2d same-lane with:", i);
for (int j = 0; j < 32; ++j) {
if (j == i) continue;
int a = i < j ? i : j, b = i < j ? j : i;
if (vote_s[a][b] > 0 && vote_d[a][b] == 0) std::printf(" %d", j);
else if (vote_s[a][b] == 0 && vote_d[a][b] == 0) std::printf(" ?%d", j);
else if (vote_s[a][b] > 0 && vote_d[a][b] > 0) std::printf(" !%d", j);
}
std::printf("\n");
}
return 0;
}
+87
View File
@@ -0,0 +1,87 @@
// neon_dot_bench: one-thread speed of the oracle dot_<N> and dot_<N>_opt of the four optimised NEON kernels, interleaved rounds.
// neon_dot_bench [rounds] [rows] [k_elems] prints one line per kernel: median GB/s (weights) of oracle and opt over the rounds, pairs where opt was faster
// Build it against two libraries (old / new tier file) and compare the opt columns: run the two executables alternately.
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <random>
#include <vector>
namespace strata::quant::neon {
#define DECL(N) void dot_##N(int, float*, const void*, const void*); void dot_##N##_opt(int, float*, const void*, const void*);
DECL(q8_0_q8_0) DECL(q4_K_q8_K) DECL(q5_K_q8_K) DECL(iq4_xs_q8_K)
} // namespace strata::quant::neon
using namespace strata::quant;
struct K {
const char* name;
int wbytes, abytes, wblock;
void (*oracle)(int, float*, const void*, const void*);
void (*opt)(int, float*, const void*, const void*);
};
static double run(void (*fn)(int, float*, const void*, const void*), int k, int rows, size_t rowb, const uint8_t* W, const uint8_t* A, int reps, float& sink) {
const auto t0 = std::chrono::steady_clock::now();
for (int r = 0; r < reps; ++r)
for (int i = 0; i < rows; ++i) {
float s;
fn(k, &s, W + (size_t)i * rowb, A);
sink += s;
}
const auto t1 = std::chrono::steady_clock::now();
return std::chrono::duration<double>(t1 - t0).count();
}
int main(int argc, char** argv) {
const int rounds = argc > 1 ? std::atoi(argv[1]) : 9;
const int rows = argc > 2 ? std::atoi(argv[2]) : 1024;
const int kel = argc > 3 ? std::atoi(argv[3]) : 4096;
const K ks[] = {
{"q8_0_q8_0", 34, 34, 32, neon::dot_q8_0_q8_0, neon::dot_q8_0_q8_0_opt},
{"q4_K_q8_K", 144, 292, 256, neon::dot_q4_K_q8_K, neon::dot_q4_K_q8_K_opt},
{"q5_K_q8_K", 176, 292, 256, neon::dot_q5_K_q8_K, neon::dot_q5_K_q8_K_opt},
{"iq4_xs_q8_K", 136, 292, 256, neon::dot_iq4_xs_q8_K, neon::dot_iq4_xs_q8_K_opt},
};
std::mt19937_64 rng(3);
float sink = 0;
for (const K& k : ks) {
const int nb = kel / k.wblock;
const size_t rowb = (size_t)nb * k.wbytes;
std::vector<uint8_t> W(rowb * rows), A((size_t)nb * k.abytes);
for (auto& b : W) b = (uint8_t)rng();
for (auto& b : A) b = (uint8_t)rng();
// finite scales
for (int i = 0; i < rows; ++i)
for (int b = 0; b < nb; ++b) {
uint8_t* w = &W[(size_t)i * rowb + (size_t)b * k.wbytes];
const uint16_t h = (uint16_t)(0x2c00 + (rng() & 0x3ff));
std::memcpy(w, &h, 2);
if (k.wbytes == 144 || k.wbytes == 176) std::memcpy(w + 2, &h, 2);
}
for (int b = 0; b < nb; ++b) {
uint8_t* a = &A[(size_t)b * k.abytes];
if (k.abytes == 34) { const uint16_t h = 0x2c00; std::memcpy(a, &h, 2); }
else { const float f = 0.01f; std::memcpy(a, &f, 4); int16_t* bs = (int16_t*)(a + 260); for (int t = 0; t < 16; ++t) bs[t] = (int16_t)(rng() % 400); }
}
const int reps = std::max(1, (int)(2.0e8 / ((double)rowb * rows))); // ~200 MB of weights per timing
std::vector<double> to, tn;
int faster = 0;
run(k.oracle, nb * k.wblock, rows, rowb, W.data(), A.data(), 1, sink); // warm up
for (int r = 0; r < rounds; ++r) {
const double a = run(k.oracle, nb * k.wblock, rows, rowb, W.data(), A.data(), reps, sink);
const double b = run(k.opt, nb * k.wblock, rows, rowb, W.data(), A.data(), reps, sink);
to.push_back(a);
tn.push_back(b);
faster += b < a;
}
std::sort(to.begin(), to.end());
std::sort(tn.begin(), tn.end());
const double bytes = (double)rowb * rows * reps;
std::printf("%-12s oracle %6.2f GB/s opt %6.2f GB/s opt/oracle %.2fx pairs faster %d/%d\n", k.name, bytes / to[to.size() / 2] / 1e9, bytes / tn[tn.size() / 2] / 1e9,
to[to.size() / 2] / tn[tn.size() / 2], faster, rounds);
}
std::fprintf(stderr, "(sink %g)\n", sink);
return 0;
}
+152
View File
@@ -0,0 +1,152 @@
// neon_dot_cmp: the optimised NEON kernels dot_<N>_opt against the in-TU reference kernels dot_<N> (the bit oracles), bit for bit, on random and edge rows.
// neon_dot_cmp [rows_per_kernel] exit 0 only when every row of every kernel is identical
// Also checks that the dispatcher's table (dot_kernel) hands out kernels that equal the oracle.
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <random>
#include <vector>
#include "strata/quant/dot.hpp"
namespace strata::quant::neon {
#define DECL(N) void dot_##N(int, float*, const void*, const void*); void dot_##N##_opt(int, float*, const void*, const void*);
DECL(q8_0_q8_0) DECL(q4_K_q8_K) DECL(q5_K_q8_K) DECL(iq4_xs_q8_K)
} // namespace strata::quant::neon
using namespace strata::quant;
static std::mt19937_64 rng(20261201);
static bool g_nonfinite = false; // --nonfinite: half scales / float scales may be inf or NaN
static uint16_t rand_half(int kind) {
if (g_nonfinite && rng() % 5 == 0) { static const uint16_t nf[] = {0x7c00, 0xfc00, 0x7e00, 0xfe00, 0x7d55}; return nf[rng() % 5]; }
switch (kind) {
case 0: return (uint16_t)(((rng() % 30 + 1) << 10) | (rng() & 1023)) | (uint16_t)((rng() & 1) << 15); // any finite normal
case 1: return (uint16_t)((rng() & 1023) | ((rng() & 1) << 15)); // subnormal or zero
case 2: return (uint16_t)(0x2800 + (rng() % 0x1400)); // moderate positive
case 3: return (uint16_t)(0xA800 + (rng() % 0x1400)); // moderate negative
case 4: return (rng() & 1) ? 0x7bff : 0xfbff; // largest finite
default: return 0;
}
}
static float rand_float(int kind) {
if (g_nonfinite && rng() % 5 == 0) { static const float nf[] = {INFINITY, -INFINITY, NAN, -NAN}; return nf[rng() % 4]; }
switch (kind) {
case 0: return std::ldexp((float)((int)(rng() % 2001) - 1000) / 997.f, (int)(rng() % 20) - 14);
case 1: return std::ldexp(1.0f, -140) * (float)(rng() % 100); // subnormal
case 2: return 0.0f;
case 3: return -std::ldexp((float)(rng() % 1000 + 1) / 700.f, (int)(rng() % 10) - 5);
default: return std::ldexp((float)(rng() % 1000 + 1) / 700.f, (int)(rng() % 40) - 20);
}
}
struct Kernel {
const char* name;
int wbytes, abytes, wblock;
void (*oracle)(int, float*, const void*, const void*);
void (*opt)(int, float*, const void*, const void*);
int nhalf; // half fields at offset 0 and 2
bool q8k;
};
static void fill(const Kernel& k, uint8_t* W, uint8_t* A, int nb, int wmode, int amode, bool bs_consistent) {
for (int b = 0; b < nb; ++b) {
uint8_t* w = W + (size_t)k.wbytes * b;
uint8_t* a = A + (size_t)k.abytes * b;
for (int i = 0; i < k.wbytes; ++i) w[i] = (uint8_t)rng();
if (wmode == 1) std::memset(w, 0xFF, k.wbytes);
if (wmode == 2) std::memset(w, 0x00, k.wbytes);
if (wmode == 3) for (int i = 0; i < k.wbytes; ++i) w[i] = (rng() & 1) ? 0xFF : 0x00;
for (int h = 0; h < k.nhalf; ++h) {
const uint16_t v = rand_half((int)(rng() % 6));
std::memcpy(w + 2 * h, &v, 2);
}
if (k.q8k) {
const float yd = rand_float((int)(rng() % 6));
std::memcpy(a, &yd, 4);
int8_t* qa = (int8_t*)(a + 4);
for (int i = 0; i < 256; ++i) {
switch (amode) {
case 0: qa[i] = (int8_t)((int)(rng() % 255) - 127); break;
case 1: qa[i] = (rng() & 1) ? 127 : -127; break;
case 2: qa[i] = (int8_t)(rng() & 1 ? -128 : 127); break;
case 3: qa[i] = 0; break;
default: qa[i] = (int8_t)(rng() % 3 - 1); break;
}
}
int16_t* bs = (int16_t*)(a + 260);
for (int t = 0; t < 16; ++t) {
int s = 0;
for (int i = 0; i < 16; ++i) s += qa[16 * t + i];
bs[t] = bs_consistent ? (int16_t)s : (int16_t)(rng() % 4001 - 2000);
}
} else {
const uint16_t d = rand_half((int)(rng() % 6));
std::memcpy(a, &d, 2);
int8_t* qa = (int8_t*)(a + 2);
for (int i = 0; i < 32; ++i) {
switch (amode) {
case 0: qa[i] = (int8_t)((int)(rng() % 255) - 127); break;
case 1: qa[i] = (rng() & 1) ? 127 : -127; break;
case 2: qa[i] = (int8_t)(rng() & 1 ? -128 : 127); break;
case 3: qa[i] = 0; break;
default: qa[i] = (int8_t)(rng() % 3 - 1); break;
}
}
}
}
}
int main(int argc, char** argv) {
const long rows = argc > 1 ? std::atol(argv[1]) : 1200000;
for (int i = 2; i < argc; ++i) if (!std::strcmp(argv[i], "--nonfinite")) g_nonfinite = true;
const Kernel ks[] = {
{"q8_0_q8_0", 34, 34, 32, neon::dot_q8_0_q8_0, neon::dot_q8_0_q8_0_opt, 1, false},
{"q4_K_q8_K", 144, 292, 256, neon::dot_q4_K_q8_K, neon::dot_q4_K_q8_K_opt, 2, true},
{"q5_K_q8_K", 176, 292, 256, neon::dot_q5_K_q8_K, neon::dot_q5_K_q8_K_opt, 2, true},
{"iq4_xs_q8_K", 136, 292, 256, neon::dot_iq4_xs_q8_K, neon::dot_iq4_xs_q8_K_opt, 1, true},
};
int failures = 0;
for (const Kernel& k : ks) {
long bad = 0, nan_both = 0, n_total = 0;
for (long it = 0; it < rows; ++it) {
const int nb = (it % 50 == 0) ? 1 + (int)(rng() % 64) : 1 + (int)(rng() % 8);
std::vector<uint8_t> W((size_t)k.wbytes * nb), A((size_t)k.abytes * nb);
const int wmode = (it % 20 == 7) ? 1 + (int)(rng() % 3) : 0;
fill(k, W.data(), A.data(), nb, wmode, (int)(rng() % 5), (it % 9) != 4);
float a = 1234.5f, b = 5432.1f;
k.oracle(nb * k.wblock, &a, W.data(), A.data());
k.opt(nb * k.wblock, &b, W.data(), A.data());
uint32_t ua, ub;
std::memcpy(&ua, &a, 4);
std::memcpy(&ub, &b, 4);
++n_total;
if (ua != ub) {
if (a != a && b != b) { ++nan_both; continue; } // both NaN (payload may differ)
if (++bad <= 3) std::printf(" MISMATCH %s nb=%d wmode=%d: oracle %a (%08x) opt %a (%08x)\n", k.name, nb, wmode, a, ua, b, ub);
}
}
std::printf("%s %-12s %ld rows: %ld mismatches (%ld NaN-vs-NaN)\n", bad ? "FAIL" : "ok ", k.name, n_total, bad, nan_both);
if (bad) ++failures;
// the dispatcher hands out kernels that equal the oracle
const DotKernel* dk = nullptr;
const Type wt = k.name[0] == 'q' && k.name[1] == '8' ? Type::Q8_0 : (k.name[1] == '4' ? Type::Q4_K : (k.name[1] == '5' ? Type::Q5_K : Type::IQ4_XS));
dk = dot_kernel(wt, Arith::Neon, Isa::Neon);
if (!dk || !dk->fn) { std::printf("FAIL dispatcher gives no NEON kernel for %s\n", k.name); ++failures; continue; }
std::vector<uint8_t> W((size_t)k.wbytes * 3), A((size_t)k.abytes * 3);
long dbad = 0;
for (int t = 0; t < 2000; ++t) {
fill(k, W.data(), A.data(), 3, 0, (int)(rng() % 5), true);
float a = 0, b = 0;
k.oracle(3 * k.wblock, &a, W.data(), A.data());
dk->fn(3 * k.wblock, &b, W.data(), A.data());
dbad += std::memcmp(&a, &b, 4) != 0 && !(a != a && b != b);
}
std::printf("%s dispatcher kernel \"%s\" equals the oracle (%ld / 2000 differ)\n", dbad ? "FAIL" : "ok ", dk->name, dbad);
if (dbad) ++failures;
}
std::printf("%s\n", failures ? "FAILED" : "PASSED");
return failures ? 1 : 0;
}
+76
View File
@@ -0,0 +1,76 @@
// neon_fprev.hpp - discover the float summation tree of a black-box dot kernel (clean-room probing, P-8).
//
// Method (reveal the order of a floating point reduction from its outputs): a kernel adds n "leaf" terms t_0..t_{n-1} (one per weight block, each
// an integer-exact block sum times scales). Give leaf i the value +M, leaf j the value -M and every other leaf the value 1 with M so large that
// M + k == M for the few ones that can meet it. The result is then the number of ones that were added AFTER +M and -M had cancelled, so
// n - 2 - result ones were absorbed and the subtree below the last common ancestor of i and j has size L(i,j) = n - result.
// The matrix L determines the tree. A node with more than two children (a fused multi-way add) shows up as equal L values.
#pragma once
#include <cstdint>
#include <cstdio>
#include <functional>
#include <string>
#include <vector>
namespace fprev {
// run(values) -> kernel result, where values[b] is the wanted float term of leaf b (each is 0, +-1 or +-2^30 here)
using Runner = std::function<float(const std::vector<float>&)>;
inline std::vector<std::vector<int>> matrix(int n, const Runner& run, float M = 1073741824.0f) {
std::vector<std::vector<int>> L(n, std::vector<int>(n, 0));
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j) {
std::vector<float> v(n, 1.0f);
v[i] = M;
v[j] = -M;
const float r = run(v);
L[i][j] = L[j][i] = n - (int)r;
}
return L;
}
// the tree as a nested string, e.g. ((0 1) (2 3)); children of an n-ary node are listed in order of first leaf
inline std::string tree(const std::vector<std::vector<int>>& L, std::vector<int> set) {
if (set.size() == 1) return std::to_string(set[0]);
const int sz = (int)set.size();
// leaves belong to the same child of the root iff L(i,j) < sz
std::vector<std::vector<int>> groups;
std::vector<bool> used(set.size(), false);
for (size_t a = 0; a < set.size(); ++a) {
if (used[a]) continue;
std::vector<int> g{set[a]};
used[a] = true;
bool grew = true;
while (grew) {
grew = false;
for (size_t b = 0; b < set.size(); ++b) {
if (used[b]) continue;
for (int m : g)
if (L[m][set[b]] < sz) {
g.push_back(set[b]);
used[b] = true;
grew = true;
break;
}
}
}
groups.push_back(g);
}
if (groups.size() == 1) return "?" + std::to_string(sz); // inconsistent matrix
std::string s = "(";
for (size_t k = 0; k < groups.size(); ++k) {
if (k) s += " ";
s += tree(L, groups[k]);
}
return s + ")";
}
inline std::string tree_of(int n, const Runner& run) {
auto L = matrix(n, run);
std::vector<int> all(n);
for (int i = 0; i < n; ++i) all[i] = i;
return tree(L, all);
}
} // namespace fprev
+173
View File
@@ -0,0 +1,173 @@
// neon_model_k: candidate float orders for the K-quant style dots (q4_K, q5_K, iq4_xs against q8_K) against the oracles (P-8 probing).
// Tree facts (neon_probe_k): q4_K: one sequential float chain; per block the minimum term first, then the main term. q5_K: per block the two terms
// are combined first, then added to one sequential chain. iq4_xs: one sequential chain. Unknown: fused or separately rounded products.
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <random>
#include <vector>
namespace strata::quant::neon {
void dot_q4_K_q8_K(int, float*, const void*, const void*);
void dot_q5_K_q8_K(int, float*, const void*, const void*);
void dot_iq4_xs_q8_K(int, float*, const void*, const void*);
} // namespace strata::quant::neon
static float h2f(uint16_t h) { __fp16 t; std::memcpy(&t, &h, 2); return (float)t; }
static const int8_t KV[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113};
struct Blk { // the integer facts of one block
float yd, dx, dmin;
int32_t sumi, summin;
};
static void sc_min(const uint8_t* s, int* sc, int* mn) {
for (int j = 0; j < 8; ++j) {
if (j < 4) { sc[j] = s[j] & 63; mn[j] = s[j + 4] & 63; }
else { sc[j] = (s[j + 4] & 15) | ((s[j - 4] >> 6) << 4); mn[j] = (s[j + 4] >> 4) | ((s[j] >> 6) << 4); }
}
}
static Blk facts_q45(bool q5, const uint8_t* W, const uint8_t* A) {
Blk r;
std::memcpy(&r.yd, A, 4);
uint16_t d, dm;
std::memcpy(&d, W, 2);
std::memcpy(&dm, W + 2, 2);
r.dx = h2f(d);
r.dmin = h2f(dm);
const int8_t* qa = (const int8_t*)(A + 4);
const int16_t* bs = (const int16_t*)(A + 260);
int sc[8], mn[8];
sc_min(W + 4, sc, mn);
const uint8_t* qh = W + 16;
const uint8_t* qs = W + (q5 ? 48 : 16);
r.sumi = 0;
r.summin = 0;
for (int j = 0; j < 8; ++j) {
int I = 0;
for (int l = 0; l < 32; ++l) {
const int g = j / 2, h = j % 2;
const uint8_t byte = qs[32 * g + l];
int q = h ? (byte >> 4) : (byte & 15);
if (q5) q += 16 * ((qh[l] >> j) & 1);
I += q * qa[32 * j + l];
}
r.sumi += sc[j] * I;
r.summin += mn[j] * (bs[2 * j] + bs[2 * j + 1]);
}
return r;
}
static Blk facts_iq4xs(const uint8_t* W, const uint8_t* A) {
Blk r;
std::memcpy(&r.yd, A, 4);
uint16_t d, sh;
std::memcpy(&d, W, 2);
std::memcpy(&sh, W + 2, 2);
r.dx = h2f(d);
r.dmin = 0;
const int8_t* qa = (const int8_t*)(A + 4);
r.sumi = 0;
r.summin = 0;
for (int ib = 0; ib < 8; ++ib) {
const int ls = ((W[4 + ib / 2] >> (4 * (ib % 2))) & 15) | (((sh >> (2 * ib)) & 3) << 4);
int I = 0;
for (int j = 0; j < 16; ++j) {
const uint8_t q = W[8 + 16 * ib + j];
I += KV[q & 15] * qa[32 * ib + j] + KV[q >> 4] * qa[32 * ib + 16 + j];
}
r.sumi += (ls - 32) * I;
}
return r;
}
int main() {
std::mt19937_64 rng(77);
// q4_K: min form (0 sep, 1 fused) x main form (0 sep, 1 fused) x order (0 min first, 1 main first)
static long bad4[2][2][2], bad5[4][2], badx[2];
long N = 40000;
for (long it = 0; it < N; ++it) {
int nb = 1 + (int)(rng() % 10);
for (int kind = 0; kind < 3; ++kind) {
const int wb = kind == 0 ? 144 : (kind == 1 ? 176 : 136);
std::vector<uint8_t> W((size_t)wb * nb), A((size_t)292 * nb);
for (int b = 0; b < nb; ++b) {
uint8_t* w = &W[(size_t)wb * b];
uint8_t* a = &A[(size_t)292 * b];
for (int i = 0; i < wb; ++i) w[i] = (uint8_t)rng();
for (int h = 0; h < 2; ++h) { // d / dmin (or d only) : moderate finite halves
if (kind == 2 && h) break;
float f = std::ldexp((float)((int)(rng() % 2001) - 1000) / 997.f, (int)(rng() % 10) - 12);
__fp16 hh = f;
std::memcpy(w + 2 * h, &hh, 2);
}
float yd = std::ldexp((float)((int)(rng() % 2001) - 1000) / 997.f, (int)(rng() % 6) - 4);
std::memcpy(a, &yd, 4);
int8_t* qa = (int8_t*)(a + 4);
for (int i = 0; i < 256; ++i) qa[i] = (int8_t)((int)(rng() % 255) - 127);
int16_t* bs = (int16_t*)(a + 260);
for (int t = 0; t < 16; ++t) { int s = 0; for (int i = 0; i < 16; ++i) s += qa[16 * t + i]; bs[t] = (int16_t)s; }
}
float s = 0;
if (kind == 0) strata::quant::neon::dot_q4_K_q8_K(256 * nb, &s, W.data(), A.data());
else if (kind == 1) strata::quant::neon::dot_q5_K_q8_K(256 * nb, &s, W.data(), A.data());
else strata::quant::neon::dot_iq4_xs_q8_K(256 * nb, &s, W.data(), A.data());
uint32_t us;
std::memcpy(&us, &s, 4);
auto eq = [&](float m) { uint32_t um; std::memcpy(&um, &m, 4); return um == us; };
std::vector<Blk> bl;
for (int b = 0; b < nb; ++b)
bl.push_back(kind == 2 ? facts_iq4xs(&W[(size_t)wb * b], &A[(size_t)292 * b]) : facts_q45(kind == 1, &W[(size_t)wb * b], &A[(size_t)292 * b]));
if (kind == 0) {
for (int mf = 0; mf < 2; ++mf)
for (int nf = 0; nf < 2; ++nf)
for (int ord = 0; ord < 2; ++ord) {
float m = 0;
for (const Blk& b : bl) {
const float d = b.yd * b.dx, dm = b.yd * b.dmin;
auto minstep = [&]() { m = mf ? fmaf(-dm, (float)b.summin, m) : m - dm * (float)b.summin; };
auto mainstep = [&]() { m = nf ? fmaf(d, (float)b.sumi, m) : m + d * (float)b.sumi; };
if (ord == 0) { minstep(); mainstep(); } else { mainstep(); minstep(); }
}
bad4[mf][nf][ord] += !eq(m);
}
} else if (kind == 1) {
for (int form = 0; form < 4; ++form)
for (int fs = 0; fs < 2; ++fs) {
float m = 0;
for (const Blk& b : bl) {
const float d = b.yd * b.dx, dm = b.yd * b.dmin;
float q;
const float pm = dm * (float)b.summin;
switch (form) {
case 0: q = d * (float)b.sumi - pm; break;
case 1: q = fmaf(d, (float)b.sumi, -pm); break;
case 2: q = fmaf(-dm, (float)b.summin, d * (float)b.sumi); break;
default: q = d * (float)b.sumi + (-dm) * (float)b.summin; break;
}
m = m + q;
(void)fs;
}
bad5[form][fs] += !eq(m);
}
} else {
for (int f = 0; f < 2; ++f) {
float m = 0;
for (const Blk& b : bl) {
const float d = b.yd * b.dx;
m = f ? fmaf(d, (float)b.sumi, m) : m + d * (float)b.sumi;
}
badx[f] += !eq(m);
}
}
}
}
std::printf("rows per kind: %ld\n", N);
for (int mf = 0; mf < 2; ++mf) for (int nf = 0; nf < 2; ++nf) for (int ord = 0; ord < 2; ++ord)
std::printf("q4_K min_fused=%d main_fused=%d order=%s : %ld differ\n", mf, nf, ord ? "main,min" : "min,main", bad4[mf][nf][ord]);
for (int form = 0; form < 4; ++form) std::printf("q5_K block form %d : %ld differ\n", form, bad5[form][0]);
for (int f = 0; f < 2; ++f) std::printf("iq4_xs fused=%d : %ld differ\n", f, badx[f]);
return 0;
}
+93
View File
@@ -0,0 +1,93 @@
// neon_model_q80: candidate float orders for the Q8_0 x Q8_0 dot against the oracle strata::quant::neon::dot_q8_0_q8_0 on random rows (P-8 probing).
// The summation tree (found with neon_probe_q80): blocks in pairs into two accumulators (even / odd block), acc0 + acc1, then a last odd block.
// Unknown: how one term (dw, da, I) is formed and whether it is fused into the accumulator. form 0: (dw*da)*I, 1: (I*dw)*da, 2: (I*da)*dw.
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <random>
#include <vector>
namespace strata::quant::neon {
void dot_q8_0_q8_0(int, float*, const void*, const void*);
}
static float h2f(uint16_t h) {
__fp16 t;
std::memcpy(&t, &h, 2);
return (float)t;
}
static float step(float acc, float dw, float da, float fI, int form, int fused) {
switch (form) {
case 0: { const float d = dw * da; return fused ? fmaf(d, fI, acc) : acc + d * fI; }
case 1: { const float u = fI * dw; return fused ? fmaf(u, da, acc) : acc + u * da; }
default: { const float u = fI * da; return fused ? fmaf(u, dw, acc) : acc + u * dw; }
}
}
static float model(const uint8_t* W, const uint8_t* A, int nb, int pf, int pu, int tf, int tu) {
float acc[2] = {0, 0};
auto get = [&](int b, float& dw, float& da, float& fI) {
uint16_t a, c;
std::memcpy(&a, W + 34 * b, 2);
std::memcpy(&c, A + 34 * b, 2);
dw = h2f(a);
da = h2f(c);
int I = 0;
for (int i = 0; i < 32; ++i) I += (int)(int8_t)W[34 * b + 2 + i] * (int)(int8_t)A[34 * b + 2 + i];
fI = (float)I;
};
int b = 0;
for (; b + 1 < nb; b += 2)
for (int k = 0; k < 2; ++k) {
float dw, da, fI;
get(b + k, dw, da, fI);
acc[k] = step(acc[k], dw, da, fI, pf, pu);
}
float s = acc[0] + acc[1];
for (; b < nb; ++b) {
float dw, da, fI;
get(b, dw, da, fI);
s = step(s, dw, da, fI, tf, tu);
}
return s;
}
int main() {
std::mt19937_64 rng(11);
static long bad[3][2][3][2];
long N = 100000;
for (long it = 0; it < N; ++it) {
int nb = 1 + (int)(rng() % 40);
std::vector<uint8_t> W(34 * nb), A(34 * nb);
for (auto* p : {&W, &A})
for (int b = 0; b < nb; ++b) {
for (int i = 0; i < 32; ++i) (*p)[34 * b + 2 + i] = (uint8_t)rng();
float f = std::ldexp((float)((int)(rng() % 2001) - 1000) / 997.f, (int)(rng() % 12) - 8);
__fp16 h = f;
std::memcpy(&(*p)[34 * b], &h, 2);
}
float s = 0;
strata::quant::neon::dot_q8_0_q8_0(32 * nb, &s, W.data(), A.data());
uint32_t us;
std::memcpy(&us, &s, 4);
for (int pf = 0; pf < 3; ++pf)
for (int pu = 0; pu < 2; ++pu)
for (int tf = 0; tf < 3; ++tf)
for (int tu = 0; tu < 2; ++tu) {
float m = model(W.data(), A.data(), nb, pf, pu, tf, tu);
uint32_t um;
std::memcpy(&um, &m, 4);
bad[pf][pu][tf][tu] += um != us;
}
}
for (int pf = 0; pf < 3; ++pf)
for (int pu = 0; pu < 2; ++pu)
for (int tf = 0; tf < 3; ++tf)
for (int tu = 0; tu < 2; ++tu)
if (bad[pf][pu][tf][tu] < N / 20)
std::printf("pair form %d fused %d, tail form %d fused %d : %ld / %ld rows differ\n", pf, pu, tf, tu, bad[pf][pu][tf][tu], N);
std::printf("(only variants with < 5%% differing rows are listed)\n");
return 0;
}
+88
View File
@@ -0,0 +1,88 @@
// neon_probe_k: block-level float summation tree of the oracle K-quant style dots (q4_K, q5_K, iq4_xs against q8_K) by probing, P-8.
// Leaves: the main term of each block (d * sum scale_j * I_j), and for q4_K / q5_K the minimum term of each block (dmin * sum m_j * bsums_j).
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include "neon_fprev.hpp"
namespace strata::quant::neon {
void dot_q4_K_q8_K(int, float*, const void*, const void*);
void dot_q5_K_q8_K(int, float*, const void*, const void*);
void dot_iq4_xs_q8_K(int, float*, const void*, const void*);
} // namespace strata::quant::neon
static uint16_t half_pow2(int k) { return (uint16_t)((k + 15) << 10); } // 2^k, k in -14..15
static uint16_t half_of(double v) { // v = +-2^k, k in -24..15 (subnormal halves for k < -14)
uint16_t sign = v < 0 ? 0x8000 : 0;
double a = std::fabs(v);
int k = (int)std::lround(std::log2(a));
if (k >= -14) return sign | half_pow2(k);
return sign | (uint16_t)(1u << (k + 24));
}
enum Kind { Q4K, Q5K, IQ4XS };
struct Geo { int wbytes; };
static const int ABYTES = 292;
// write block b's leaves: main value vm, min value vn (0 = none)
static void set_leaf(Kind k, uint8_t* W, uint8_t* A, double vm, double vn) {
const int wbytes = k == Q4K ? 144 : (k == Q5K ? 176 : 136);
std::memset(W, 0, wbytes);
std::memset(A, 0, ABYTES);
const double am = std::fabs(vm), an = std::fabs(vn);
const bool big = am > 2.0 || an > 2.0;
const float yd = big ? 32768.0f : 1.0f;
std::memcpy(A, &yd, 4);
int8_t* qa = (int8_t*)(A + 4);
int16_t* bs = (int16_t*)(A + 260);
if (am > 0) { // main: act q[0] = sign, weight element 0 = 1, scale 1
qa[0] = vm < 0 ? -1 : 1;
const uint16_t d = half_of(am / yd);
if (k == IQ4XS) {
std::memcpy(W, &d, 2);
W[4] = 1; // scales_l[0] low nibble = 1
const uint16_t sh = 2; // scales_h bits 0..1 = 2 -> ls = 33, dl = d * 1
std::memcpy(W + 2, &sh, 2);
W[8] = 8; // qs[0] low nibble 8 -> kvalue 1 (element 0)
} else {
std::memcpy(W, &d, 2);
W[4] = 1; // sc_0 = 1
if (k == Q4K) W[16] = 1; // element 0 = 1
else W[48] = 1;
}
}
if (an > 0 && k != IQ4XS) { // min: -dmin * m_0 * (bsums[0]) with m_0 = 1 ; wanted +-an
const uint16_t dm = half_of(an / yd);
std::memcpy(W + 2, &dm, 2);
W[8] = (uint8_t)(W[8] | 1); // m_0 = low 6 bits of scales[4] (byte 8 of the block)
bs[0] = vn < 0 ? 1 : -1; // the term is -dmin*m*bsum
}
}
int main() {
using namespace strata::quant::neon;
struct K { const char* name; Kind kind; void (*fn)(int, float*, const void*, const void*); int wbytes; bool has_min; };
const K ks[] = {{"q4_K", Q4K, dot_q4_K_q8_K, 144, true}, {"q5_K", Q5K, dot_q5_K_q8_K, 176, true}, {"iq4_xs", IQ4XS, dot_iq4_xs_q8_K, 136, false}};
for (const K& k : ks) {
for (int nb : {1, 2, 3, 4, 5, 6}) {
for (int with_min = 0; with_min < (k.has_min ? 2 : 1); ++with_min) {
// leaves: main of every block, then (with_min) min of every block
const int n = nb * (with_min ? 2 : 1);
fprev::Runner run = [&](const std::vector<float>& v) {
std::vector<uint8_t> W((size_t)k.wbytes * nb), A((size_t)ABYTES * nb);
for (int b = 0; b < nb; ++b) set_leaf(k.kind, &W[(size_t)k.wbytes * b], &A[(size_t)ABYTES * b], v[b], with_min ? v[nb + b] : 0.0);
float s = 0;
k.fn(256 * nb, &s, W.data(), A.data());
return s;
};
std::string t = n >= 2 ? fprev::tree_of(n, run) : std::string("0");
std::printf("%-7s nb=%d %s: %s%s\n", k.name, nb, with_min ? "main+min" : "main ", t.c_str(), with_min ? " (leaves nb..2nb-1 are the min terms)" : "");
}
}
}
return 0;
}
+124
View File
@@ -0,0 +1,124 @@
// neon_probe_q80: lane-level float order of the oracle strata::quant::neon::dot_q8_0_q8_0 (P-8 probing).
// Facts found so far (neon_dbg_q80 / FPRev): a pair of blocks is processed together, 4 int32 lanes per block (lane l = element positions 4l..4l+3 and
// 16+4l..16+4l+3); one trailing odd block is a scalar term with the whole block summed as an integer first. This program scans candidate float orders.
// term form T: lane value = (dw*da) * float(I_l) (T0) or (float(I_l) * dw) * da (T1)
// accumulate across pairs: acc[k] = acc[k] + term (unfused) or fma(...) (fused)
// reduction R: 0 = vaddv(acc0) + vaddv(acc1) with vaddv = (x0+x1)+(x2+x3); 1 = vaddv(acc0 + acc1); 2 = sequential x0+x1+x2+x3 on each then add
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <random>
#include <vector>
namespace strata::quant::neon {
void dot_q8_0_q8_0(int, float*, const void*, const void*);
}
static float h2f(uint16_t h) {
__fp16 t;
std::memcpy(&t, &h, 2);
return (float)t;
}
static float lane_step(float acc, float dw, float da, int I, int T, int fused) {
const float fI = (float)I;
if (T == 0) {
const float d = dw * da;
return fused ? fmaf(d, fI, acc) : acc + d * fI;
}
const float u = fI * dw;
return fused ? fmaf(u, da, acc) : acc + u * da;
}
static float vaddv(const float* x, int R) {
if (R == 2) return ((x[0] + x[1]) + x[2]) + x[3];
return (x[0] + x[1]) + (x[2] + x[3]);
}
static float model(const uint8_t* W, const uint8_t* A, int nb, int T, int fused, int R, int tailT, int tailFused) {
float acc[2][4] = {{0, 0, 0, 0}, {0, 0, 0, 0}};
auto blk = [&](int b, float& dw, float& da, int* I4, int& Itot) {
uint16_t a, c;
std::memcpy(&a, W + 34 * b, 2);
std::memcpy(&c, A + 34 * b, 2);
dw = h2f(a);
da = h2f(c);
Itot = 0;
for (int l = 0; l < 4; ++l) {
I4[l] = 0;
for (int k = 0; k < 4; ++k)
for (int half = 0; half < 2; ++half) {
const int i = 16 * half + 4 * l + k;
I4[l] += (int)(int8_t)W[34 * b + 2 + i] * (int)(int8_t)A[34 * b + 2 + i];
}
Itot += I4[l];
}
};
int b = 0;
for (; b + 1 < nb; b += 2)
for (int k = 0; k < 2; ++k) {
float dw, da;
int I4[4], It;
blk(b + k, dw, da, I4, It);
for (int l = 0; l < 4; ++l) acc[k][l] = lane_step(acc[k][l], dw, da, I4[l], T, fused);
}
float s;
if (R == 1) {
float sum[4];
for (int l = 0; l < 4; ++l) sum[l] = acc[0][l] + acc[1][l];
s = vaddv(sum, 0);
} else {
s = vaddv(acc[0], R) + vaddv(acc[1], R);
}
for (; b < nb; ++b) {
float dw, da;
int I4[4], It;
blk(b, dw, da, I4, It);
s = lane_step(s, dw, da, It, tailT, tailFused);
}
return s;
}
int main() {
std::mt19937_64 rng(11);
static long bad[2][2][3][2][2];
long N = 60000;
for (long it = 0; it < N; ++it) {
int nb = 1 + (int)(rng() % 12);
std::vector<uint8_t> W(34 * nb), A(34 * nb);
for (auto* p : {&W, &A})
for (int b = 0; b < nb; ++b) {
for (int i = 0; i < 32; ++i) (*p)[34 * b + 2 + i] = (uint8_t)rng();
float f = std::ldexp((float)((int)(rng() % 2001) - 1000) / 997.f, (int)(rng() % 12) - 8);
__fp16 h = f;
std::memcpy(&(*p)[34 * b], &h, 2);
}
float s = 0;
strata::quant::neon::dot_q8_0_q8_0(32 * nb, &s, W.data(), A.data());
uint32_t us;
std::memcpy(&us, &s, 4);
for (int T = 0; T < 2; ++T)
for (int f = 0; f < 2; ++f)
for (int R = 0; R < 3; ++R)
for (int tt = 0; tt < 2; ++tt)
for (int tf = 0; tf < 2; ++tf) {
float m = model(W.data(), A.data(), nb, T, f, R, tt, tf);
uint32_t um;
std::memcpy(&um, &m, 4);
bad[T][f][R][tt][tf] += um != us;
}
}
int shown = 0;
for (int T = 0; T < 2; ++T)
for (int f = 0; f < 2; ++f)
for (int R = 0; R < 3; ++R)
for (int tt = 0; tt < 2; ++tt)
for (int tf = 0; tf < 2; ++tf)
if (bad[T][f][R][tt][tf] < N / 20) {
++shown;
std::printf("T%d fused%d R%d tailT%d tailF%d : %ld / %ld differ\n", T, f, R, tt, tf, bad[T][f][R][tt][tf], N);
}
std::printf("%d variants with < 5%% differing rows\n", shown);
return 0;
}
+236
View File
@@ -0,0 +1,236 @@
// probe_blocks.hpp - raw block builders for the black-box probes of the dot kernels (clean-room round P-7 / P-8).
// A ProbeRow holds nb weight blocks and nb activation blocks as raw bytes (FORMAT-SPEC layouts). set_product(b, i, rng) makes element i of block b
// contribute a random non-zero integer to the kernel's integer sum (all other activation entries stay 0) and returns that integer; the sub-block scale
// of the element is chosen at the first use and kept. D(b) is the float the block's integer sum is scaled by.
#pragma once
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <random>
#include <sstream>
#include <string>
#include <vector>
#include "strata/quant/dot.hpp"
#include "strata/quant/fp16.hpp"
enum PT { PQ8_0, PQ4_K, PQ5_K, PQ6_K, PIQ4_XS, PIQ3_XXS, PQ5_1 };
struct ProbeType {
std::string name;
PT pt;
strata::quant::Type type;
int elems, wbytes, abytes;
};
inline void put_half(uint8_t* p, uint16_t h) { p[0] = h & 255; p[1] = h >> 8; }
inline uint16_t get_half(const uint8_t* p) { return (uint16_t)(p[0] | (p[1] << 8)); }
inline uint16_t rand_half(std::mt19937_64& rng, int lo = -6, int hi = 2) {
const float m = 0.5f + (float)(rng() % 1000) / 1000.0f;
return strata::quant::fp32_to_fp16(std::ldexp(m, lo + (int)(rng() % (unsigned)(hi - lo + 1))) * ((rng() & 1) ? 1.f : -1.f));
}
inline const std::vector<std::vector<int>>& iq3xxs_grid() {
static std::vector<std::vector<int>> g;
if (g.empty()) {
const char* dir = std::getenv("STRATA_FORMAT_TABLES");
std::ifstream f(std::string(dir ? dir : "terminal/tools/format_tables") + "/iq3xxs_grid.txt");
std::string ln;
while (std::getline(f, ln)) {
if (ln.empty() || ln[0] == '#') continue;
std::istringstream ss(ln.substr(ln.find(':') + 1));
std::vector<int> r;
int v;
while (ss >> v) r.push_back(v);
g.push_back(r);
}
}
return g;
}
inline int ksign(int v7, int j) { int p = 0; for (int b = 0; b < 7; ++b) p ^= (v7 >> b) & 1; return ((v7 | (p << 7)) >> j) & 1; }
static const int kKV[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113};
struct ProbeRow {
const ProbeType& t;
int nb;
std::vector<uint8_t> w, a;
std::vector<int> sub_scale; // per block x 16: chosen sub-block scale, 0 = unset
ProbeRow(const ProbeType& ty, int n) : t(ty), nb(n), w((size_t)n * ty.wbytes, 0), a((size_t)n * ty.abytes, 0), sub_scale((size_t)n * 16, 0) {}
uint8_t* wb(int b) { return &w[(size_t)b * t.wbytes]; }
uint8_t* ab(int b) { return &a[(size_t)b * t.abytes]; }
bool is_k() const { return t.pt != PQ8_0 && t.pt != PQ5_1; }
bool zero_bsums = false; // keep the bsums field at 0 (the kernel reads it separately from qs): isolates the products from the bias / min terms
float act_d(int b) {
if (!is_k()) return strata::quant::fp16_to_fp32(get_half(ab(b)));
float f;
std::memcpy(&f, ab(b), 4);
return f;
}
void randomize_scales(std::mt19937_64& rng) {
for (int b = 0; b < nb; ++b) {
put_half(wb(b), rand_half(rng)); // weight d is the first half of every block type used here, Q6_K's is at 208
if (t.pt == PQ6_K) { put_half(wb(b), 0); put_half(wb(b) + 208, rand_half(rng)); }
if (!is_k()) put_half(ab(b), rand_half(rng));
else {
const float d = std::ldexp(0.5f + (float)(rng() % 1000) / 1000.0f, (int)(rng() % 7) - 9) * ((rng() & 1) ? 1.f : -1.f);
std::memcpy(ab(b), &d, 4);
}
}
}
float wd(int b) { return strata::quant::fp16_to_fp32(get_half(t.pt == PQ6_K ? wb(b) + 208 : wb(b))); }
float D(int b) {
float d = wd(b) * act_d(b);
if (t.pt == PIQ3_XXS) d = d * 0.25f; // the 0.25 is a power of two: exact wherever it is applied
return d;
}
void set_act(int b, int i, int8_t v) {
uint8_t* p = ab(b);
if (!is_k()) { p[(t.pt == PQ5_1 ? 4 : 2) + i] = (uint8_t)v; return; }
p[4 + i] = (uint8_t)v;
int16_t s = 0;
for (int k = 0; k < 16; ++k) s = (int16_t)(s + (int8_t)p[4 + (i / 16) * 16 + k]);
if (!zero_bsums) std::memcpy(p + 260 + 2 * (i / 16), &s, 2);
}
// 6-bit scale / min packing of Q4_K / Q5_K
void set_sc6(uint8_t* s12, int j, int v, bool is_min) {
if (j < 4) {
uint8_t& b = s12[is_min ? j + 4 : j];
b = (uint8_t)((b & 0xC0) | (v & 63));
} else {
uint8_t& lo = s12[j + 4];
lo = is_min ? (uint8_t)((lo & 0x0F) | ((v & 15) << 4)) : (uint8_t)((lo & 0xF0) | (v & 15));
uint8_t& hi = s12[is_min ? j : j - 4];
hi = (uint8_t)((hi & 0x3F) | (((v >> 4) & 3) << 6));
}
}
int pick_scale(int b, int sub, std::mt19937_64& rng, int lo, int hi) {
int& s = sub_scale[(size_t)b * 16 + sub];
if (!s) {
do { s = lo + (int)(rng() % (unsigned)(hi - lo + 1)); } while (s == 0);
}
return s;
}
int set_product(int b, int i, std::mt19937_64& rng) {
uint8_t* q = wb(b);
int8_t av = (int8_t)((int)(rng() % 255) - 127);
if (av == 0) av = 5;
switch (t.pt) {
case PQ8_0: {
int8_t x = (int8_t)((int)(rng() % 255) - 127);
if (x == 0) x = 3;
q[2 + i] = (uint8_t)x;
set_act(b, i, av);
return (int)x * (int)av;
}
case PQ5_1: {
const int j = i % 16;
int q5 = 1 + (int)(rng() % 31);
uint8_t& byte = q[8 + j];
byte = (i >= 16) ? (uint8_t)((byte & 0x0F) | ((q5 & 15) << 4)) : (uint8_t)((byte & 0xF0) | (q5 & 15));
uint32_t qh = (uint32_t)(q[4] | (q[5] << 8) | (q[6] << 16) | ((uint32_t)q[7] << 24));
qh = (qh & ~(1u << i)) | ((uint32_t)((q5 >> 4) & 1) << i);
q[4] = qh & 255; q[5] = (qh >> 8) & 255; q[6] = (qh >> 16) & 255; q[7] = qh >> 24;
set_act(b, i, av);
return q5 * (int)av;
}
case PQ4_K:
case PQ5_K: {
const int g = i / 64, h = (i / 32) % 2, l = i % 32, j = 2 * g + h;
const int sc = pick_scale(b, j, rng, 1, 63);
set_sc6(q + 4, j, sc, false);
const int maxq = t.pt == PQ4_K ? 15 : 31;
int nib = 1 + (int)(rng() % (unsigned)maxq);
uint8_t* qs = q + (t.pt == PQ4_K ? 16 : 48);
uint8_t& byte = qs[32 * g + l];
const int low = nib & 15;
byte = h ? (uint8_t)((byte & 0x0F) | (low << 4)) : (uint8_t)((byte & 0xF0) | low);
if (t.pt == PQ5_K) {
uint8_t& qh = q[16 + l];
qh = (uint8_t)((qh & ~(1 << j)) | (((nib >> 4) & 1) << j));
}
set_act(b, i, av);
return sc * nib * (int)av;
}
case PQ6_K: {
const int n = i / 128, p = (i % 128) / 32, l = i % 32;
const int s = 8 * n + 2 * p + l / 16;
const int sc = pick_scale(b, s, rng, -100, 100);
q[192 + s] = (uint8_t)(int8_t)sc;
int qv = (int)(rng() % 63) - 31;
if (qv == 0) qv = 7;
const int qu = qv + 32;
uint8_t& lo = q[64 * n + 32 * (p & 1) + l];
lo = (p < 2) ? (uint8_t)((lo & 0xF0) | (qu & 15)) : (uint8_t)((lo & 0x0F) | ((qu & 15) << 4));
uint8_t& hi = q[128 + 32 * n + l];
hi = (uint8_t)((hi & ~(3 << (2 * p))) | (((qu >> 4) & 3) << (2 * p)));
set_act(b, i, av);
return zero_bsums ? sc * qu * (int)av : sc * qv * (int)av; // with bsums 0 only the unsigned part is seen
}
case PIQ4_XS: {
const int ib = i / 32, r = i % 32;
const int j = r % 16;
const int ls = pick_scale(b, ib, rng, 1, 63);
uint16_t sh = (uint16_t)(q[2] | (q[3] << 8));
sh = (uint16_t)((sh & ~(3 << (2 * ib))) | (((ls >> 4) & 3) << (2 * ib)));
q[2] = sh & 255; q[3] = sh >> 8;
uint8_t& sl = q[4 + ib / 2];
sl = (ib & 1) ? (uint8_t)((sl & 0x0F) | ((ls & 15) << 4)) : (uint8_t)((sl & 0xF0) | (ls & 15));
const int nib = 1 + (int)(rng() % 15);
uint8_t& byte = q[8 + 16 * ib + j];
byte = (r >= 16) ? (uint8_t)((byte & 0x0F) | (nib << 4)) : (uint8_t)((byte & 0xF0) | nib);
set_act(b, i, av);
return (ls - 32) * kKV[nib] * (int)av;
}
case PIQ3_XXS: {
const auto& G = iq3xxs_grid();
const int g = i / 32, l = (i % 32) / 8, pos = i % 8, half = pos / 4, j = pos % 4;
const int ls = pick_scale(b, g, rng, 0, 15) ; // 0 is excluded by pick_scale; 2*ls+1 is the factor
// the sub-block "scale" here is s_g in 1..15
uint32_t wg = (uint32_t)(q[66 + 4 * g] | (q[67 + 4 * g] << 8) | (q[68 + 4 * g] << 16) | (q[69 + 4 * g] << 24));
wg = (wg & 0x0FFFFFFFu) | ((uint32_t)ls << 28);
// sign index of run l: the first use picks it, later uses of the same run keep it
int v = (int)((wg >> (7 * l)) & 127);
if (v == 0) { v = 1 + (int)(rng() % 127); wg = (wg & ~(127u << (7 * l))) | ((uint32_t)v << (7 * l)); }
q[66 + 4 * g] = wg & 255; q[67 + 4 * g] = (wg >> 8) & 255; q[68 + 4 * g] = (wg >> 16) & 255; q[69 + 4 * g] = wg >> 24;
const int k = 8 * g + 2 * l + half;
if (q[2 + k] == 0 && (half == 0 || true)) q[2 + k] = (uint8_t)(1 + (rng() % 255));
const int gv = G[q[2 + k]][j];
const int sign = ksign(v, half * 4 + j) ? -1 : 1;
set_act(b, i, av);
return (2 * ls + 1) * gv * sign * (int)av;
}
}
return 0;
}
// Q6_K bias item: sub-block t gets a scale and a bsums entry v (qs stays 0): the kernel's contribution is -32 * scale * v
int set_bias_q6(int b, int tsub, std::mt19937_64& rng) {
const int sc = pick_scale(b, tsub, rng, -100, 100);
wb(b)[192 + tsub] = (uint8_t)(int8_t)sc;
int v = (int)(rng() % 4001) - 2000;
if (v == 0) v = 17;
const int16_t s = (int16_t)v;
std::memcpy(ab(b) + 260 + 2 * tsub, &s, 2);
return -32 * sc * v;
}
float finish(float x) { return x; }
float finish_lane(float x) { return x; }
};
inline ProbeType* find_probe_type(const std::string& n) {
static ProbeType types[] = {
{"q8_0", PQ8_0, strata::quant::Type::Q8_0, 32, 34, 34},
{"q4_K", PQ4_K, strata::quant::Type::Q4_K, 256, 144, 292},
{"q5_K", PQ5_K, strata::quant::Type::Q5_K, 256, 176, 292},
{"q6_K", PQ6_K, strata::quant::Type::Q6_K, 256, 210, 292},
{"iq4_xs", PIQ4_XS, strata::quant::Type::IQ4_XS, 256, 136, 292},
{"iq3_xxs", PIQ3_XXS, strata::quant::Type::IQ3_XXS, 256, 98, 292},
{"q5_1", PQ5_1, strata::quant::Type::Q5_1, 32, 24, 36},
};
for (auto& t : types)
if (t.name == n) return &t;
return nullptr;
}
+63
View File
@@ -0,0 +1,63 @@
// probe_core.hpp - shared pieces of the dot-kernel probes: the lane partition of a block's elements.
#pragma once
#include "probe_blocks.hpp"
using namespace strata::quant;
struct LanePartition {
int nclasses = 0;
int anomalies = 0;
std::vector<int> cls; // class id per element (classes numbered by first element)
};
// Two elements (i, j) with all other products zero: the result is fl(D*float(p_i + p_j)) when they share an integer lane, fl(fl(D*p_i) + fl(D*p_j)) otherwise.
inline LanePartition lane_partition(const ProbeType& t, const DotKernel* k, std::mt19937_64& rng, int trials, int only_first = -1) {
const int n = t.elems;
std::vector<std::vector<int>> same(n, std::vector<int>(n, 0)), diff(n, std::vector<int>(n, 0)), neither(n, std::vector<int>(n, 0));
for (int i = 0; i < n; ++i) {
if (only_first >= 0 && i != only_first) continue;
for (int j = i + 1; j < n; ++j)
for (int tr = 0; tr < trials; ++tr) {
ProbeRow r(t, 1);
r.zero_bsums = true;
r.randomize_scales(rng);
const int p1 = r.set_product(0, i, rng), p2 = r.set_product(0, j, rng);
float oracle = 0;
k->fn(n, &oracle, r.w.data(), r.a.data());
const float D = r.D(0);
const float hs = D * (float)(p1 + p2);
const float hd = D * (float)p1 + D * (float)p2;
const bool es = std::memcmp(&oracle, &hs, 4) == 0, ed = std::memcmp(&oracle, &hd, 4) == 0;
if (es && !ed) ++same[i][j];
else if (ed && !es) ++diff[i][j];
else if (!es && !ed) ++neither[i][j];
}
}
LanePartition lp;
lp.cls.assign(n, -1);
for (int i = 0; i < n; ++i) {
if (lp.cls[i] < 0) lp.cls[i] = lp.nclasses++;
if (only_first >= 0 && i != only_first) continue;
for (int j = i + 1; j < n; ++j) {
if (neither[i][j] > 0 || (same[i][j] > 0 && diff[i][j] > 0)) ++lp.anomalies;
if (same[i][j] > 0 && diff[i][j] == 0 && neither[i][j] == 0) lp.cls[j] = lp.cls[i];
}
}
return lp;
}
inline void print_partition(const LanePartition& lp, int n) {
printf("classes: %d, anomalous pairs: %d\n", lp.nclasses, lp.anomalies);
for (int c = 0; c < lp.nclasses; ++c) {
printf("lane %d:", c);
int run0 = -1, prev = -2;
auto flush = [&]() { if (run0 >= 0) { if (prev == run0) printf(" %d", run0); else printf(" %d-%d", run0, prev); } };
for (int i = 0; i < n; ++i)
if (lp.cls[i] == c) {
if (i == prev + 1 && run0 >= 0) prev = i;
else { flush(); run0 = prev = i; }
}
flush();
printf("\n");
}
}
+16
View File
@@ -0,0 +1,16 @@
// probe_lanes: which elements of one block share an accumulator lane in a dot kernel (Q8 activation, one block); see probe_core.hpp.
// usage: probe_lanes <q8_0|q4_K|q5_K|q6_K|iq4_xs|iq3_xxs> [trials]
#include "probe_core.hpp"
int main(int argc, char** argv) {
const std::string name = argc > 1 ? argv[1] : "q8_0";
const int trials = argc > 2 ? atoi(argv[2]) : 40;
ProbeType* t = find_probe_type(name);
if (!t) { printf("unknown type\n"); return 1; }
const DotKernel* k = dot_kernel(t->type, Arith::Avx2, Isa::Avx2);
printf("kernel %s, block %d elements\n", k->name, t->elems);
std::mt19937_64 rng(5);
LanePartition lp = lane_partition(*t, k, rng, trials);
print_partition(lp, t->elems);
return 0;
}
+48
View File
@@ -0,0 +1,48 @@
// probe_mins: layout of the integer min terms of the Avx2 Q4_K / Q5_K dots. Item j (0..7) = the min m_j of sub-block j with bsums[2j] = v and every
// product zero: the contribution is -dmin*da*m_j*v. Two items in one integer lane give -fl(Dm*float(M1+M2)), different lanes -(fl(Dm*M1)+fl(Dm*M2)).
#include "probe_core.hpp"
int main(int argc, char** argv) {
const std::string name = argc > 1 ? argv[1] : "q4_K";
const int trials = argc > 2 ? atoi(argv[2]) : 200;
ProbeType* t = find_probe_type(name);
const DotKernel* k = dot_kernel(t->type, Arith::Avx2, Isa::Avx2);
std::mt19937_64 rng(3);
auto setitem = [&](ProbeRow& r, int j, int& M) {
int m = 1 + (int)(rng() % 63);
r.set_sc6(r.wb(0) + 4, j, m, true);
int v = (int)(rng() % 4001) - 2000;
if (v == 0) v = 9;
const int16_t s = (int16_t)v;
std::memcpy(r.ab(0) + 260 + 2 * (2 * j), &s, 2);
M = m * v;
};
int same[8][8] = {}, diff[8][8] = {}, none[8][8] = {};
for (int a = 0; a < 8; ++a)
for (int b = a + 1; b < 8; ++b)
for (int tr = 0; tr < trials; ++tr) {
ProbeRow r(*t, 1);
put_half(r.wb(0), rand_half(rng));
put_half(r.wb(0) + 2, rand_half(rng));
const float da = std::ldexp(0.5f + (float)(rng() % 1000) / 1000.0f, (int)(rng() % 7) - 9);
std::memcpy(r.ab(0), &da, 4);
int M1, M2;
setitem(r, a, M1);
setitem(r, b, M2);
float o = 0;
k->fn(256, &o, r.w.data(), r.a.data());
const float Dm = fp16_to_fp32(get_half(r.wb(0) + 2)) * da;
const float hs = -(Dm * (float)(M1 + M2)), hd = -(Dm * (float)M1) + -(Dm * (float)M2);
const bool es = std::memcmp(&o, &hs, 4) == 0, ed = std::memcmp(&o, &hd, 4) == 0;
if (es && !ed) ++same[a][b]; else if (ed && !es) ++diff[a][b]; else if (!es && !ed) ++none[a][b];
}
printf("%s: pairs of min items (j1,j2): S = same lane, D = different lane, ? = matched neither at least once\n", name.c_str());
for (int a = 0; a < 8; ++a) {
for (int b = 0; b < 8; ++b) {
if (b <= a) { printf(" ."); continue; }
printf(" %c", none[a][b] ? '?' : (same[a][b] && !diff[a][b]) ? 'S' : (diff[a][b] && !same[a][b]) ? 'D' : '-');
}
printf("\n");
}
return 0;
}
+27
View File
@@ -0,0 +1,27 @@
// probe_one: single-element rows (one non-zero product): does the kernel give fl(D * p)? Prints a few raw cases when not.
#include "probe_core.hpp"
int main(int argc, char** argv) {
const std::string name = argc > 1 ? argv[1] : "q6_K";
ProbeType* t = find_probe_type(name);
const DotKernel* k = dot_kernel(t->type, Arith::Avx2, Isa::Avx2);
std::mt19937_64 rng(1);
int bad = 0, shown = 0;
const int N = 2000;
for (int tr = 0; tr < N; ++tr) {
const int i = (int)(rng() % t->elems);
ProbeRow r(*t, 1);
r.zero_bsums = true;
r.randomize_scales(rng);
const int p = r.set_product(0, i, rng);
float o = 0;
k->fn(t->elems, &o, r.w.data(), r.a.data());
const float e = r.D(0) * (float)p;
if (std::memcmp(&o, &e, 4)) {
++bad;
if (shown++ < 5) printf("elem %d p=%d D=%.9g oracle=%.9g expected=%.9g ratio=%.6g\n", i, p, r.D(0), o, e, e != 0 ? o / e : 0);
}
}
printf("%s: %d of %d single-element rows differ from fl(D*p)\n", name.c_str(), bad, N);
return 0;
}
+56
View File
@@ -0,0 +1,56 @@
// probe_q6k: lane structure of the Avx2 Q6_K x Q8_K dot. Items 0..255 are product elements (bsums kept 0), items 256..271 the bias entries of the
// 16 sub-blocks (qs kept 0). Two items share an integer lane when the result is fl(D*(p1+p2)), different lanes when it is fl(D*p1)+fl(D*p2).
#include "probe_core.hpp"
static int apply(ProbeRow& r, int item, std::mt19937_64& rng) {
if (item < 256) return r.set_product(0, item, rng);
return r.set_bias_q6(0, item - 256, rng);
}
int main(int argc, char** argv) {
const int trials = argc > 1 ? atoi(argv[1]) : 30;
ProbeType* t = find_probe_type("q6_K");
const DotKernel* k = dot_kernel(t->type, Arith::Avx2, Isa::Avx2);
std::mt19937_64 rng(5);
const int n = 272;
std::vector<int> cls(n, -1);
int nc = 0, anomalies = 0;
std::vector<std::vector<char>> same(n, std::vector<char>(n, 0));
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j) {
int s = 0, d = 0, x = 0;
for (int tr = 0; tr < trials; ++tr) {
ProbeRow r(*t, 1);
r.zero_bsums = true;
r.randomize_scales(rng);
const int p1 = apply(r, i, rng), p2 = apply(r, j, rng);
float o = 0;
k->fn(256, &o, r.w.data(), r.a.data());
const float D = r.D(0);
const float hs = D * (float)(p1 + p2), hd = D * (float)p1 + D * (float)p2;
const bool es = std::memcmp(&o, &hs, 4) == 0, ed = std::memcmp(&o, &hd, 4) == 0;
if (es && !ed) ++s; else if (ed && !es) ++d; else if (!es && !ed) ++x;
}
if (x > 0 || (s > 0 && d > 0)) ++anomalies;
same[i][j] = (s > 0 && d == 0 && x == 0);
}
for (int i = 0; i < n; ++i) {
if (cls[i] < 0) cls[i] = nc++;
for (int j = i + 1; j < n; ++j) if (same[i][j]) cls[j] = cls[i];
}
printf("kernel %s: %d classes, %d anomalous pairs\n", k->name, nc, anomalies);
for (int c = 0; c < nc; ++c) {
printf("lane %d: elements", c);
int run0 = -1, prev = -2;
bool in_bias = false;
for (int i = 0; i < n; ++i)
if (cls[i] == c) {
if (i >= 256 && !in_bias) { if (run0 >= 0) printf(" %d-%d", run0, prev); run0 = -1; printf(" | bias subblocks"); in_bias = true; prev = -2; }
if (i == prev + 1 && run0 >= 0) prev = i;
else { if (run0 >= 0) printf(" %d-%d", run0, prev); run0 = prev = i; }
}
if (run0 >= 0) printf(" %d-%d", run0, prev);
printf("\n");
}
return 0;
}
+92
View File
@@ -0,0 +1,92 @@
// probe_q8_0: black-box scan of the float composition of the Avx2 Q8_0 x Q8_0 dot (dot_kernel(Q8_0, Avx2, Avx2)).
// Candidate models = lane partition x accumulate (fused / unfused) x number of accumulators x combine order x horizontal-sum tree.
// Mismatch counts are listed per block count nb, so a structure that only shows from nb = 2 or nb = 4 on is visible.
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <random>
#include <string>
#include <vector>
#include "strata/quant/dot.hpp"
#include "strata/quant/fp16.hpp"
using namespace strata::quant;
static void put16(uint8_t* p, uint16_t h) { p[0] = h & 255; p[1] = h >> 8; }
typedef std::function<float(const float*)> Tree;
int main(int argc, char** argv) {
const long iters = argc > 1 ? atol(argv[1]) : 20000;
const int NBMAX = 9;
const DotKernel* k = dot_kernel(Type::Q8_0, Arith::Avx2, Isa::Avx2);
printf("kernel %s\n", k->name);
std::vector<std::pair<std::string, Tree>> trees = {
{"lohi,movehl,shuf", [](const float* v) { float a[4]; for (int i = 0; i < 4; ++i) a[i] = v[i] + v[i + 4]; float b0 = a[0] + a[2], b1 = a[1] + a[3]; return b0 + b1; }},
{"lohi,adj", [](const float* v) { float a[4]; for (int i = 0; i < 4; ++i) a[i] = v[i] + v[i + 4]; return (a[0] + a[1]) + (a[2] + a[3]); }},
{"sequential", [](const float* v) { float s = v[0]; for (int i = 1; i < 8; ++i) s += v[i]; return s; }},
};
// acc count NA in {1,2,4}; combine: 0 sequential lane-wise, 1 pairwise; fused 0/1
const int NAs[3] = {1, 2, 4};
std::mt19937_64 rng(77);
static long bad[3][2][2][3][10]; // NA, comb, fused, tree, nb
static long cnt[10];
for (long it = 0; it < iters; ++it) {
int nb = 1 + (int)(rng() % NBMAX);
std::vector<uint8_t> w(nb * 34), a(nb * 34);
std::vector<float> dw(nb), da(nb);
for (int b = 0; b < nb; ++b) {
uint16_t hw = fp32_to_fp16((float)std::ldexp(0.5 + (rng() % 1000) / 1000.0, (int)(rng() % 9) - 6) * ((rng() & 1) ? 1 : -1));
uint16_t ha = fp32_to_fp16((float)std::ldexp(0.5 + (rng() % 1000) / 1000.0, (int)(rng() % 9) - 6) * ((rng() & 1) ? 1 : -1));
put16(&w[b * 34], hw);
put16(&a[b * 34], ha);
dw[b] = fp16_to_fp32(hw);
da[b] = fp16_to_fp32(ha);
for (int i = 0; i < 32; ++i) {
int mode = it % 3;
w[b * 34 + 2 + i] = (uint8_t)(int8_t)(mode == 0 ? (int)(rng() % 256) - 128 : (int)(rng() % 41) - 20);
a[b * 34 + 2 + i] = (uint8_t)(int8_t)(mode == 0 ? (int)(rng() % 256) - 128 : (int)(rng() % 41) - 20);
}
}
float oracle = 0;
k->fn(nb * 32, &oracle, w.data(), a.data());
++cnt[nb];
for (int na = 0; na < 3; ++na)
for (int comb = 0; comb < 2; ++comb)
for (int fused = 0; fused < 2; ++fused) {
float acc[4][8] = {};
const int NA = NAs[na];
for (int b = 0; b < nb; ++b) {
int lane[8] = {};
for (int i = 0; i < 32; i += 2) { int pr = 0; for (int h = 0; h < 2; ++h) { const int wv = (int8_t)w[b * 34 + 2 + i + h], av = (int8_t)a[b * 34 + 2 + i + h]; const int ax = wv < 0 ? -wv : wv; int sy = wv < 0 ? -av : (wv == 0 ? 0 : av); sy = (int8_t)sy; pr += ax * sy; } if (pr > 32767) pr = 32767; if (pr < -32768) pr = -32768; lane[i / 4] += pr; }
const float D = dw[b] * da[b];
float* ac = acc[b % NA];
for (int l = 0; l < 8; ++l) ac[l] = fused ? std::fmaf(D, (float)lane[l], ac[l]) : ac[l] + D * (float)lane[l];
}
float tot[8];
for (int l = 0; l < 8; ++l) {
if (NA == 1) tot[l] = acc[0][l];
else if (NA == 2) tot[l] = acc[0][l] + acc[1][l];
else tot[l] = comb == 0 ? ((acc[0][l] + acc[1][l]) + acc[2][l]) + acc[3][l] : (acc[0][l] + acc[1][l]) + (acc[2][l] + acc[3][l]);
}
for (size_t t = 0; t < trees.size(); ++t) {
float r = trees[t].second(tot);
if (memcmp(&r, &oracle, 4) != 0) ++bad[na][comb][fused][t][nb];
}
}
}
for (int na = 0; na < 3; ++na)
for (int comb = 0; comb < 2; ++comb)
for (int fused = 0; fused < 2; ++fused)
for (size_t t = 0; t < trees.size(); ++t) {
long tot = 0;
for (int nb = 1; nb <= NBMAX; ++nb) tot += bad[na][comb][fused][t][nb];
if (tot > (long)iters / 4) continue;
printf("NA=%d comb=%d %-5s %-18s total %5ld by nb:", NAs[na], comb, fused ? "fma" : "mul+add", trees[t].first.c_str(), tot);
for (int nb = 1; nb <= NBMAX; ++nb) printf(" %ld/%ld", bad[na][comb][fused][t][nb], cnt[nb]);
printf("\n");
}
return 0;
}
+88
View File
@@ -0,0 +1,88 @@
// probe_tree: the shape of the horizontal reduction of the lane accumulators of a dot kernel (one block, Q8 activation).
// Three lanes carry non-zero float values, the rest are zero: the result is fl(fl(x_a + x_b) + x_c) when a and b merge before c, and so on.
// Every triple of lanes with random values tells which pair merges first, which fixes the tree (up to operand order). The lanes are found by
// probe_core.hpp's partition first (one representative element per lane).
// usage: probe_tree <type> [trials]
#include "probe_core.hpp"
int main(int argc, char** argv) {
const std::string name = argc > 1 ? argv[1] : "q8_0";
const int trials = argc > 2 ? atoi(argv[2]) : 200;
ProbeType* t = find_probe_type(name);
const DotKernel* k = dot_kernel(t->type, Arith::Avx2, Isa::Avx2);
std::mt19937_64 rng(11);
LanePartition lp = lane_partition(*t, k, rng, 24);
const int L = lp.nclasses;
printf("kernel %s: %d lanes, %d anomalous pairs\n", k->name, L, lp.anomalies);
std::vector<int> rep(L, -1);
for (int i = 0; i < t->elems; ++i) if (rep[lp.cls[i]] < 0) rep[lp.cls[i]] = i;
std::vector<int> merge((size_t)L * L * L, -1);
auto M = [&](int a, int b, int c) -> int& { return merge[((size_t)a * L + b) * L + c]; };
int unresolved = 0;
for (int a = 0; a < L; ++a)
for (int b = a + 1; b < L; ++b)
for (int c = b + 1; c < L; ++c) {
int votes[3] = {0, 0, 0}, none = 0, informative = 0;
for (int tr = 0; tr < trials; ++tr) {
ProbeRow r(*t, 1);
r.zero_bsums = true;
r.randomize_scales(rng);
const float D = r.D(0);
const int lanes[3] = {a, b, c};
float x[3];
for (int q = 0; q < 3; ++q) x[q] = D * (float)r.set_product(0, rep[lanes[q]], rng);
float oracle = 0;
k->fn(t->elems, &oracle, r.w.data(), r.a.data());
const float h[3] = {(x[0] + x[1]) + x[2], (x[0] + x[2]) + x[1], (x[1] + x[2]) + x[0]};
const bool m[3] = {memcmp(&oracle, &h[0], 4) == 0, memcmp(&oracle, &h[1], 4) == 0, memcmp(&oracle, &h[2], 4) == 0};
const int nm = m[0] + m[1] + m[2];
if (nm == 0) { ++none; continue; }
if (nm == 3) continue;
++informative;
for (int q = 0; q < 3; ++q) if (m[q]) votes[q] += 1;
}
int cand = -1, ncand = 0;
for (int q = 0; q < 3; ++q) if (votes[q] == informative && none == 0) { cand = q; ++ncand; }
M(a, b, c) = (ncand == 1) ? cand : -1;
if (ncand != 1) { ++unresolved; if (unresolved < 10) printf("triple %d %d %d unresolved: votes %d %d %d of %d informative, %d matching none\n", a, b, c, votes[0], votes[1], votes[2], informative, none); }
}
printf("unresolved triples: %d of %d\n", unresolved, L * (L - 1) * (L - 2) / 6);
// closest pairs: for a pair (a,b), the number of third lanes c for which (a,b) merge first
auto first_pair = [&](int a, int b, int c, int& p0, int& p1) {
int s[3] = {a, b, c};
std::sort(s, s + 3);
const int mm = M(s[0], s[1], s[2]);
if (mm == 0) { p0 = s[0]; p1 = s[1]; } else if (mm == 1) { p0 = s[0]; p1 = s[2]; } else if (mm == 2) { p0 = s[1]; p1 = s[2]; } else { p0 = p1 = -1; }
};
// build the tree by repeated merging: clusters; two clusters X, Y merge first if for all x in X, y in Y and every other lane c outside X u Y, (x,y) beats c
std::vector<std::vector<int>> cl;
std::vector<std::string> txt;
for (int i = 0; i < L; ++i) { cl.push_back({i}); txt.push_back(std::to_string(i)); }
while (cl.size() > 1) {
bool did = false;
for (size_t x = 0; x < cl.size() && !did; ++x)
for (size_t y = x + 1; y < cl.size() && !did; ++y) {
bool ok = true;
for (size_t z = 0; z < cl.size() && ok; ++z) {
if (z == x || z == y) continue;
for (int p : cl[x]) for (int q : cl[y]) for (int c : cl[z]) {
int p0, p1;
first_pair(p, q, c, p0, p1);
if (!((p0 == p && p1 == q) || (p0 == q && p1 == p))) ok = false;
}
}
if (ok && cl.size() >= 2) {
// also the sibling must not be beaten inside: both sides are already complete clusters
std::vector<int> u = cl[x];
u.insert(u.end(), cl[y].begin(), cl[y].end());
std::string s = "(" + txt[x] + "+" + txt[y] + ")";
cl[x] = u; txt[x] = s;
cl.erase(cl.begin() + y); txt.erase(txt.begin() + y);
did = true;
}
}
if (!did) { printf("could not build a complete binary tree (a non-binary or non-tree structure); clusters left: %zu\n", cl.size()); for (auto& s : txt) printf(" %s\n", s.c_str()); return 0; }
}
printf("tree: %s\n", txt[0].c_str());
return 0;
}
+36
View File
@@ -0,0 +1,36 @@
// rope_inputs.hpp - the same deterministic input set for the old / new rope kernels on a device (rope_old_new_dev.cu, rope_old_new_sycl.cpp).
#pragma once
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <random>
#include <vector>
struct RopeItem { float theta, fs, lo, hi, ext, attn; int pair; };
inline std::vector<RopeItem> make_rope_inputs(int n) {
std::mt19937_64 rng(4242);
const float fss[] = {1.0f, 0.5f, 0.25f, 0.125f, 0.4f, 1.0f / 3.0f};
const float exts[] = {0.0f, 1.0f, 0.5f, 2.0f};
const float attns[] = {1.0f, 1.2f, 0.9f, 1.4f};
const double bases[] = {1e4, 1e6, 1e7, 5e5};
const int nrots[] = {64, 128, 8, 256};
std::vector<RopeItem> v;
v.reserve(n);
for (int i = 0; i < n; ++i) {
const int nr = nrots[rng() % 4];
const int pair = (int)(rng() % (nr / 2));
const double base = bases[rng() % 4];
const double pos = (i % 5 == 0) ? (double)(rng() % 100) : (double)(rng() % (1u << 21));
RopeItem it;
it.theta = (float)(pos * std::pow(base, -2.0 * pair / nr));
it.fs = fss[rng() % 6];
it.lo = (float)(rng() % 20);
it.hi = it.lo + (float)(rng() % 24) - (rng() % 7 == 0 ? 3.0f : 0.0f); // includes high <= low (the 0.001 floor)
it.ext = exts[rng() % 4];
it.attn = attns[rng() % 4];
it.pair = pair;
v.push_back(it);
}
return v;
}
@@ -0,0 +1,97 @@
// rope_yarn_device_test: kernels/rope_yarn_math.hpp ramp() and scaled_angle() on the GPU (CUDA: nvcc -x cu; HIP: hipcc) against the golden file rope_current.txt
// (ramp bit-exact, cos / sin within 1e-6 absolute: the device libm is not the host's). The double-precision functions of the header (corr_dim, corr_dims, mscale,
// freq_scale) run on the host only in the engine, so the kernel arguments are formed here exactly as the golden test forms them.
// build: nvcc -O2 -std=c++17 -Iengine/include rope_yarn_device_test.cu -o rope_dev usage: rope_dev <rope_current.txt>
#include "strata/kernels/rope_yarn_math.hpp"
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#if defined(__HIPCC__)
#include <hip/hip_runtime.h>
#define cudaMalloc hipMalloc
#define cudaMemcpy hipMemcpy
#define cudaMemcpyHostToDevice hipMemcpyHostToDevice
#define cudaMemcpyDeviceToHost hipMemcpyDeviceToHost
#define cudaDeviceSynchronize hipDeviceSynchronize
#define cudaFree hipFree
#endif
using namespace strata::kernels;
struct Item { float theta, fs, lo, hi, ext, attn; int pair; };
__global__ void kernel(const Item* in, float* out, int n) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= n) return;
const Item& it = in[i];
out[3 * i] = yarn::ramp(it.lo, it.hi, it.pair);
float c, s;
yarn::scaled_angle(it.theta, it.fs, it.lo, it.hi, it.ext, it.attn, it.pair, c, s);
out[3 * i + 1] = c;
out[3 * i + 2] = s;
}
static float from_hex(const std::string& s) { uint32_t u = (uint32_t)std::strtoul(s.c_str(), nullptr, 16); float f; std::memcpy(&f, &u, 4); return f; }
static uint32_t f2u(float f) { uint32_t u; std::memcpy(&u, &f, 4); return u; }
static long ulp(float a, float b) {
if (a == b) return 0;
auto key = [](float f) -> long { const uint32_t u = f2u(f); return (u & 0x80000000u) ? -(long)(u & 0x7fffffffu) : (long)u; };
return std::labs(key(a) - key(b));
}
int main(int argc, char** argv) {
std::ifstream f(argc > 1 ? argv[1] : "rope_current.txt");
if (!f) { std::printf("cannot open golden file\n"); return 1; }
std::map<std::string, std::vector<float>> args; // name -> 5 kernel arguments
std::vector<Item> items;
std::vector<float> want_ramp, want_c, want_s;
std::map<std::string, float> ramp_of;
std::string ln;
std::vector<std::pair<std::string, int>> ramp_keys;
while (std::getline(f, ln)) {
std::istringstream ss(ln);
std::vector<std::string> p;
for (std::string t; ss >> t;) p.push_back(t);
if (p.empty()) continue;
if (p[0] == "args") args[p[1]] = {from_hex(p[2]), from_hex(p[3]), from_hex(p[4]), from_hex(p[5]), from_hex(p[6])};
else if (p[0] == "ramp") ramp_of[p[1] + ":" + p[2]] = from_hex(p[3]);
else if (p[0] == "angle") {
const auto& a = args[p[1]];
items.push_back({from_hex(p[4]), a[0], a[1], a[2], a[3], a[4], std::atoi(p[2].c_str())});
want_ramp.push_back(ramp_of[p[1] + ":" + p[2]]);
want_c.push_back(from_hex(p[5]));
want_s.push_back(from_hex(p[6]));
}
}
const int n = (int)items.size();
Item* d_in;
float* d_out;
cudaMalloc((void**)&d_in, n * sizeof(Item));
cudaMalloc((void**)&d_out, 3 * n * sizeof(float));
cudaMemcpy(d_in, items.data(), n * sizeof(Item), cudaMemcpyHostToDevice);
kernel<<<(n + 255) / 256, 256>>>(d_in, d_out, n);
cudaDeviceSynchronize();
std::vector<float> out(3 * n);
cudaMemcpy(out.data(), d_out, 3 * n * sizeof(float), cudaMemcpyDeviceToHost);
int bad = 0;
double worst_abs = 0, worst_big = 0;
for (int i = 0; i < n; ++i) {
if (f2u(out[3 * i]) != f2u(want_ramp[i])) ++bad;
const double e = std::max(std::fabs((double)out[3 * i + 1] - want_c[i]), std::fabs((double)out[3 * i + 2] - want_s[i]));
if (std::fabs(items[i].theta) <= 64.0f) { worst_abs = std::max(worst_abs, e); if (e > 1e-6 + 8.0 * 1.1920929e-7 * std::max(std::fabs((double)items[i].theta), 1.0)) ++bad; } // the device may fuse the float steps of scaled_angle: allow 8 ulp of theta; large angles: information only
else worst_big = std::max(worst_big, e); // the device libm differs from the host's; near a zero of cos / sin that is many ulp but a tiny absolute error
}
std::printf("%d angles on the device: ramp bit-exact, cos / sin worst absolute error %.3g for |theta| <= 64 (limit 1e-6 + 8 ulp of theta), %.3g above (information), %d failures\n%s\n", n, worst_abs, worst_big, bad, bad ? "FAILED" : "PASSED");
cudaFree(d_in);
cudaFree(d_out);
return bad ? 1 : 0;
}
@@ -0,0 +1,136 @@
// rope_yarn_golden_test: kernels/rope_yarn_math.hpp against the recorded golden file rope_current.txt
// (8 configurations x all pairs x 3 positions; written from the pre-rewrite build):
// cfg freq_scale / mscale / corr dims as %.17g text -> bit-identical (compared as the same text)
// args the five float32 kernel arguments -> bit-identical
// ramp float32 ramp per pair -> bit-identical
// angle theta, cos, sin float32 bits -> within 2 ulp (cos / sin come from the host libm)
// The RopeScaling members are mirrored here with the same one-line calls rope_scaling.hpp makes.
#include "strata/kernels/rope_yarn_math.hpp"
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include "vec_util.hpp"
using namespace strata::kernels;
namespace {
struct Cfg {
const char* name;
RopeScalingType type;
double base, factor, fs_in, orig, ext, attn, bf, bs;
int n_rot;
};
const Cfg kCfgs[] = {
{"none", RopeScalingType::None, 1e7, 1.0, 0, 262144, 0, 1.0, 32, 1, 64},
{"linear2", RopeScalingType::Linear, 1e7, 2.0, 0, 262144, 0, 1.0, 32, 1, 64},
{"yarn4_big", RopeScalingType::YaRN, 1e7, 4.0, 0, 262144, 1.0, 1.0, 32, 1, 64},
{"yarn4_small", RopeScalingType::YaRN, 1e4, 4.0, 0, 4096, 1.0, 1.0, 32, 1, 64},
{"yarn8_128", RopeScalingType::YaRN, 1e6, 8.0, 0, 8192, 1.0, 1.0, 32, 1, 128},
{"yarn4_ext05", RopeScalingType::YaRN, 1e7, 4.0, 0, 262144, 0.5, 1.2, 32, 1, 64},
{"yarn2_fsin", RopeScalingType::YaRN, 1e7, 2.0, 0.4, 32768, 1.0, 1.0, 16, 2, 64},
{"yarn_degenerate", RopeScalingType::YaRN, 1e4, 2.0, 0, 64, 1.0, 1.0, 32, 1, 8},
};
struct Args {
float freq_scale, corr_low, corr_high, ext_factor, attn_factor;
};
const Cfg* find(const std::string& n) {
for (const Cfg& c : kCfgs)
if (n == c.name) return &c;
return nullptr;
}
Args kernel_args(const Cfg& c) {
if (c.type == RopeScalingType::None) return Args{1.f, 0.f, 0.f, 0.f, 1.f};
double cd[2];
yarn::corr_dims(c.n_rot, c.orig, c.bf, c.bs, c.base, cd);
return Args{(float)yarn::freq_scale(c.type, c.fs_in, c.factor), (float)cd[0], (float)cd[1], (float)c.ext, (float)c.attn};
}
std::string fmt17(double v) {
char b[64];
std::snprintf(b, sizeof b, "%.17g", v);
return b;
}
float from_hex(const std::string& s) {
const uint32_t u = (uint32_t)std::strtoul(s.c_str(), nullptr, 16);
float f;
std::memcpy(&f, &u, 4);
return f;
}
} // namespace
int main(int argc, char** argv) {
const std::string path = argc > 1 ? argv[1] : cp2::data_dir() + "/rope-vectors/rope_current.txt";
std::ifstream f(path);
if (!f) {
std::printf("FAIL: cannot open %s\n", path.c_str());
return 1;
}
int bad = 0, ncfg = 0, nargs = 0, nramp = 0, nang = 0;
int64_t worst = 0;
std::string ln;
while (std::getline(f, ln)) {
std::istringstream ss(ln);
std::vector<std::string> p;
for (std::string t; ss >> t;) p.push_back(t);
if (p.empty()) continue;
const Cfg* c = p.size() > 1 ? find(p[1]) : nullptr;
if (!c) { std::printf("FAIL unknown config in line: %s\n", ln.c_str()); ++bad; continue; }
if (p[0] == "cfg") {
// cfg <name> n_rot N invalid X freq_scale F mscale M corr LO HI
double cd[2];
yarn::corr_dims(c->n_rot, c->orig, c->bf, c->bs, c->base, cd);
const double fs = yarn::freq_scale(c->type, c->fs_in, c->factor);
const double ms = yarn::mscale(c->ext, c->attn, fs);
const bool ok = p[7] == fmt17(fs) && p[9] == fmt17(ms) && p[11] == fmt17(cd[0]) && p[12] == fmt17(cd[1]);
if (!ok) {
++bad;
std::printf("FAIL cfg %s: got %s %s %s %s want %s %s %s %s\n", c->name, fmt17(fs).c_str(), fmt17(ms).c_str(), fmt17(cd[0]).c_str(), fmt17(cd[1]).c_str(),
p[7].c_str(), p[9].c_str(), p[11].c_str(), p[12].c_str());
}
++ncfg;
} else if (p[0] == "args") {
const Args a = kernel_args(*c);
const float w[5] = {from_hex(p[2]), from_hex(p[3]), from_hex(p[4]), from_hex(p[5]), from_hex(p[6])};
const float g[5] = {a.freq_scale, a.corr_low, a.corr_high, a.ext_factor, a.attn_factor};
for (int i = 0; i < 5; ++i)
if (cp2::f2u(g[i]) != cp2::f2u(w[i])) { ++bad; std::printf("FAIL args %s field %d\n", c->name, i); }
++nargs;
} else if (p[0] == "ramp") {
const Args a = kernel_args(*c);
const int pair = std::atoi(p[2].c_str());
const float r = yarn::ramp(a.corr_low, a.corr_high, pair);
if (cp2::f2u(r) != cp2::f2u(from_hex(p[3]))) { ++bad; std::printf("FAIL ramp %s pair %d\n", c->name, pair); }
++nramp;
} else if (p[0] == "angle") {
const Args a = kernel_args(*c);
const int pair = std::atoi(p[2].c_str());
const float theta = from_hex(p[4]);
float co, si;
yarn::scaled_angle(theta, a.freq_scale, a.corr_low, a.corr_high, a.ext_factor, a.attn_factor, pair, co, si);
const int64_t u = std::max(cp2::ulp_diff(co, from_hex(p[5])), cp2::ulp_diff(si, from_hex(p[6])));
if (u > worst) worst = u;
if (u > 2) { ++bad; std::printf("FAIL angle %s pair %d pos %s: %lld ulp\n", c->name, pair, p[3].c_str(), (long long)u); }
++nang;
}
}
std::printf("cfg %d args %d ramp %d (bit-exact) angle %d (worst %lld ulp) failures %d\n", ncfg, nargs, nramp, nang, (long long)worst, bad);
if (ncfg != 8 || nargs != 8 || nramp == 0 || nang == 0) { std::printf("FAIL: golden file incomplete\n"); return 1; }
std::printf("%s\n", bad ? "FAILED" : "PASSED");
return bad ? 1 : 0;
}
@@ -0,0 +1,76 @@
// rope_yarn_sycl_test: kernels/rope_yarn_math.hpp ramp() / scaled_angle() inside a SYCL kernel against the host evaluation of the same header
// (ramp bit-exact, cos / sin within 1e-6 absolute). build: icpx -fsycl -O2 -Iengine/include rope_yarn_sycl_test.cpp
#include <sycl/sycl.hpp>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <vector>
#include "strata/kernels/rope_yarn_math.hpp"
using namespace strata::kernels;
int main() {
sycl::queue q{sycl::gpu_selector_v};
std::printf("device: %s\n", q.get_device().get_info<sycl::info::device::name>().c_str());
const int n = 1 << 16;
std::vector<float> theta(n), fs(n), lo(n), hi(n), ext(n), attn(n);
std::vector<int> pair(n);
for (int i = 0; i < n; ++i) {
pair[i] = i % 32;
theta[i] = (float)(1.0 + (i % 977) * 31.37) * std::pow(1e7f, -2.0f * pair[i] / 64.0f);
fs[i] = 0.25f + (i % 7) * 0.1f;
lo[i] = (float)(i % 5);
hi[i] = lo[i] + (float)(i % 9);
ext[i] = (i % 3 == 0) ? 0.0f : 1.0f;
attn[i] = 1.0f + (i % 4) * 0.05f;
}
std::vector<float> out(3 * n, 0.f);
float* d_t = sycl::malloc_device<float>(n, q);
float* d_f = sycl::malloc_device<float>(n, q);
float* d_l = sycl::malloc_device<float>(n, q);
float* d_h = sycl::malloc_device<float>(n, q);
float* d_e = sycl::malloc_device<float>(n, q);
float* d_a = sycl::malloc_device<float>(n, q);
int* d_p = sycl::malloc_device<int>(n, q);
float* d_o = sycl::malloc_device<float>(3 * n, q);
q.memcpy(d_t, theta.data(), n * 4).wait();
q.memcpy(d_f, fs.data(), n * 4).wait();
q.memcpy(d_l, lo.data(), n * 4).wait();
q.memcpy(d_h, hi.data(), n * 4).wait();
q.memcpy(d_e, ext.data(), n * 4).wait();
q.memcpy(d_a, attn.data(), n * 4).wait();
q.memcpy(d_p, pair.data(), n * 4).wait();
q.parallel_for(sycl::range<1>(n), [=](sycl::id<1> id) {
const int i = (int)id[0];
d_o[3 * i] = yarn::ramp(d_l[i], d_h[i], d_p[i]);
float c, s;
yarn::scaled_angle(d_t[i], d_f[i], d_l[i], d_h[i], d_e[i], d_a[i], d_p[i], c, s);
d_o[3 * i + 1] = c;
d_o[3 * i + 2] = s;
}).wait();
q.memcpy(out.data(), d_o, 3 * n * 4).wait();
int bad = 0;
double worst = 0, worst_big = 0;
int ramp_inexact = 0;
double ramp_worst = 0;
for (int i = 0; i < n; ++i) {
const float r = yarn::ramp(lo[i], hi[i], pair[i]);
float c, s;
yarn::scaled_angle(theta[i], fs[i], lo[i], hi[i], ext[i], attn[i], pair[i], c, s);
{ // ramp: bit-exact only when the device divides with correct rounding (not the default of every SYCL device); 1 - y cancels, so the bound is absolute
const double d = std::fabs((double)r - out[3 * i]);
if (std::memcmp(&r, &out[3 * i], 4)) ++ramp_inexact;
ramp_worst = std::fmax(ramp_worst, d);
if (d > 1e-5) ++bad;
}
const double e = std::fmax(std::fabs((double)c - out[3 * i + 1]), std::fabs((double)s - out[3 * i + 2]));
if (std::fabs(theta[i]) <= 64.0f) { worst = std::fmax(worst, e); if (e > 1e-4) ++bad; } // smoke bound: the Intel device cos / sin (and fused float steps) are not IEEE-exact; ramp is the exact part
else worst_big = std::fmax(worst_big, e);
}
std::printf("%d angles in a SYCL kernel: ramp not bit-exact in %d (worst absolute %.3g, limit 1e-5), cos / sin worst absolute error %.3g for |theta| <= 64 (smoke limit 1e-4), %.3g above (information), %d failures\n%s\n", n, ramp_inexact, ramp_worst, worst, worst_big, bad, bad ? "FAILED" : "PASSED");
return bad ? 1 : 0;
}
+27
View File
@@ -0,0 +1,27 @@
#!/bin/bash
# Interleaved speed pairs of the old and the new dot_avx2 (libraries qb = old, qbn = new, see build_quant_manual.sh), one core, from the directory holding engine/.
# usage: bash engine/tests/clean_p2/run_dot_bench.sh [pairs] [cpu] [rows: 1024 = from L3/RAM, 96 = from L2]
PAIRS=${1:-7}
CPU=${2:-3}
ROWS=${3:-1024}
OPTS="-std=c++20 -O2 -mfma -ffp-contract=off -Iengine/include -Iengine/src/quant -Iengine/tests/clean_p2"
g++ $OPTS engine/tests/clean_p2/dot_avx2_bench.cpp qb/libstrata_quant.a -o bench_old
g++ $OPTS engine/tests/clean_p2/dot_avx2_bench.cpp qbn/libstrata_quant.a -o bench_new
rm -f bench_old.txt bench_new.txt
for i in $(seq 1 $PAIRS); do
if [ $((i % 2)) -eq 1 ]; then
taskset -c $CPU ./bench_old 12 $ROWS >> bench_old.txt
taskset -c $CPU ./bench_new 12 $ROWS >> bench_new.txt
else
taskset -c $CPU ./bench_new 12 $ROWS >> bench_new.txt
taskset -c $CPU ./bench_old 12 $ROWS >> bench_old.txt
fi
done
# per type: median over pairs; "pairs faster" = how often the new one-row kernel was faster than the old one in the same pair
for ty in q8_0 q4_K q5_K q6_K iq3_xxs iq4_xs; do
grep "^$ty " bench_old.txt | awk '{print $3, $5, $7}' > o.tmp
grep "^$ty " bench_new.txt | awk '{print $3, $5, $7}' > n.tmp
paste o.tmp n.tmp | awk -v ty=$ty '{o[NR]=$1; op[NR]=$2; ox[NR]=$3; n[NR]=$4; np[NR]=$5; nx[NR]=$6; if ($4 <= $1) f++; if ($4 <= $2) fp++; N=NR}
function med(a,N, i,j,t,b){for(i=1;i<=N;i++)b[i]=a[i]; for(i=1;i<=N;i++)for(j=i+1;j<=N;j++)if(b[j]<b[i]){t=b[i];b[i]=b[j];b[j]=t}; return b[int((N+1)/2)]}
END{printf "%-8s old_opt %.1f new_opt %.1f plain(old tu) %.1f plain(new tu) %.1f ns/row-dot ; new faster than old in %d/%d pairs, not slower than its plain kernel in %d/%d; x4 old %.1f new %.1f\n", ty, med(o,N), med(n,N), med(op,N), med(np,N), f, N, fp, N, med(ox,N), med(nx,N)}'
done
+68
View File
@@ -0,0 +1,68 @@
// Shared helpers of the clean-room round tests (P2): load the spec vectors from tests/data/clean_p2.
#pragma once
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
namespace cp2 {
#ifndef STRATA_CLEAN_P2_DATA
#define STRATA_CLEAN_P2_DATA "tests/data/clean_p2"
#endif
inline std::string data_dir() {
const char* e = std::getenv("STRATA_CLEAN_P2_DATA");
return e && *e ? std::string(e) : std::string(STRATA_CLEAN_P2_DATA);
}
inline bool read_file(const std::string& path, std::vector<uint8_t>& out) {
FILE* f = std::fopen(path.c_str(), "rb");
if (!f) return false;
std::fseek(f, 0, SEEK_END);
const long n = std::ftell(f);
std::fseek(f, 0, SEEK_SET);
out.resize((size_t)n);
const size_t got = n ? std::fread(out.data(), 1, (size_t)n, f) : 0;
std::fclose(f);
return got == (size_t)n;
}
// one decimal value per line
inline bool read_values(const std::string& path, std::vector<double>& out) {
std::vector<uint8_t> raw;
if (!read_file(path, raw)) return false;
std::string s((const char*)raw.data(), raw.size());
out.clear();
size_t i = 0;
while (i < s.size()) {
size_t j = s.find('\n', i);
if (j == std::string::npos) j = s.size();
std::string ln = s.substr(i, j - i);
i = j + 1;
if (ln.empty() || ln[0] == '#') continue;
out.push_back(std::strtod(ln.c_str(), nullptr));
}
return true;
}
inline uint32_t f2u(float f) {
uint32_t u;
std::memcpy(&u, &f, 4);
return u;
}
// float32 distance in units in the last place (monotone integer mapping); 0 for equal incl. +0/-0
inline int64_t ulp_diff(float a, float b) {
if (a == b) return 0;
auto key = [](float f) -> int64_t {
const uint32_t u = f2u(f);
return (u & 0x80000000u) ? -(int64_t)(u & 0x7FFFFFFFu) : (int64_t)u;
};
const int64_t d = key(a) - key(b);
return d < 0 ? -d : d;
}
} // namespace cp2
@@ -0,0 +1,13 @@
Random-byte blocks (seed 20261201; every half field finite) and the float32 values of FORMAT-SPEC.md sections 11-17.
Q2_0: q2_0.bin = 4 blocks (72 bytes), q2_0.expected.txt = 256 float32 values (%.9g)
Q4_0: q4_0.bin = 4 blocks (72 bytes), q4_0.expected.txt = 128 float32 values (%.9g)
Q4_1: q4_1.bin = 4 blocks (80 bytes), q4_1.expected.txt = 128 float32 values (%.9g)
Q5_0: q5_0.bin = 4 blocks (88 bytes), q5_0.expected.txt = 128 float32 values (%.9g)
Q5_1: q5_1.bin = 4 blocks (96 bytes), q5_1.expected.txt = 128 float32 values (%.9g)
Q5_K: q5_k.bin = 4 blocks (704 bytes), q5_k.expected.txt = 1024 float32 values (%.9g)
IQ4_NL: iq4_nl.bin = 4 blocks (72 bytes), iq4_nl.expected.txt = 128 float32 values (%.9g)
IQ4_XS: iq4_xs.bin = 4 blocks (544 bytes), iq4_xs.expected.txt = 1024 float32 values (%.9g)
IQ2_XS: iq2_xs.bin = 4 blocks (296 bytes), iq2_xs.expected.txt = 1024 float32 values (%.9g)
IQ2_S: iq2_s.bin = 4 blocks (328 bytes), iq2_s.expected.txt = 1024 float32 values (%.9g)
IQ3_XXS: iq3_xxs.bin = 4 blocks (392 bytes), iq3_xxs.expected.txt = 1024 float32 values (%.9g)
IQ3_S: iq3_s.bin = 4 blocks (440 bytes), iq3_s.expected.txt = 1024 float32 values (%.9g)
Binary file not shown.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,2 @@
Д╨Lюa│ш└ц▐]
w ЧЕм?y╦║з√╬,Тm▄╔`чSйнP┼N╥Ьз·╓UP╒Эья4 Ъ\jT2$VчFЬHc╬┬▀h2Q©│6eшD&uйд%6h"╖Q┐┬\Z|EВт~`ц"÷jDИН▄k╡цТ&| Шk9в┼tw2b(гмI(·ЕЦ∙▒║тТ{NЙ╩╥У╖Ё═x╗Ljh\╨⌡ёHяQ 8OZв╩}G'вг┼ш═з▌URИoИкНVBвC█Ф╞(T╨r╓ vЩ=╫к+\5 ~U╟В-&[╧<⌠w`ъ╚ф╗2зroП▒╠■]еу⌡6оп▒F:ол▄ф┼жh'╨й?P╛·п⌡еЗB╧╜)Не■╒ау_юwчwm-╩Я&═≥ЮS
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,3 @@
Ê¿�Róéo»¢Êc1CÎ-I{¹á¯»ù91å×e%AJAwgÌn;á /Œ=ÇjP«5•'^ ^�êY‚~eƒèÇ´”––’”Tè}:’ˆ ·D ,«Ë>…áÛáÊh•BLó�ó,µ—O -$å^zöÝ�ßvd¸Ø2Hﲓ9�ÄãÒÂKݘVbgy1÷VæzOž1p„¨²…ðOK7Ø_Tó
6¬<Ï‹UcGéòɼ­¬çÎÝ€<ªQÑl-½jgêQÜÕ¿X“ΓÿR’;iq*[ö�¯mÃø<áO¼Æçü–øÏƒ–ò6J„ ?)W ­$& L–«�ÛêƒGW*«ÒvÙ¤‘ôœûýŒ»‚—&Dƒ,¬È’Ù†)�íéó}î7 iìš)�nôd½Ši%’U¤ËJ|/=§ÅPÐ atvSàçÞÂÌÕ°ó‘¦/\
Ø?Ã'Ó”ZºOÍn ö†|æZ—Ó¿õ«Ã†�B{$ CNÝÇDôj•ƒSƒ‹ä«¯~ËðåÈ@$6)#—ùN”¨I³˜Hƒ�y ¥Q¡�¾
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,2 @@
é¾\Õ7ŒØÁ—Ë/´2pt‹¼VÎ
q`Mú¿ŽUE0|ß¹«‡¤<Û±a¡�3=‘¿Yæc PÈKZï.ÆÎν
@@ -0,0 +1,128 @@
-91.5595703
60.4638672
17.2753906
38.0058594
-91.5595703
-1.72753906
179.664062
17.2753906
112.290039
38.0058594
-65.6464844
-195.211914
84.6494141
143.385742
219.397461
84.6494141
60.4638672
-119.200195
112.290039
179.664062
-1.72753906
-119.200195
-91.5595703
-22.4580078
-91.5595703
219.397461
-1.72753906
143.385742
-65.6464844
112.290039
17.2753906
17.2753906
24.9863281
-101.081055
-28.3935547
118.117188
11.3574219
144.239258
-78.3662109
-28.3935547
-78.3662109
-78.3662109
-128.338867
-101.081055
39.7509766
39.7509766
144.239258
-60.1943359
39.7509766
-60.1943359
144.239258
11.3574219
118.117188
24.9863281
55.6513672
-128.338867
118.117188
118.117188
-43.1582031
-1.13574219
39.7509766
55.6513672
73.8232422
11.3574219
47.7026367
-27.8876953
7.33886719
35.9604492
-38.8959961
-27.8876953
76.3242188
76.3242188
16.1455078
76.3242188
16.1455078
76.3242188
16.1455078
47.7026367
47.7026367
-50.6381836
93.2036133
-18.347168
-0.733886719
-18.347168
47.7026367
-50.6381836
-27.8876953
16.1455078
76.3242188
-18.347168
76.3242188
-0.733886719
-27.8876953
76.3242188
47.7026367
47.7026367
-24.5908203
41.6152344
122.954102
-100.254883
240.233398
-1.89160156
92.6884766
66.2060547
-71.8808594
-47.2900391
-213.750977
-168.352539
41.6152344
-168.352539
-168.352539
-130.520508
66.2060547
-168.352539
41.6152344
240.233398
66.2060547
-100.254883
196.726562
240.233398
92.6884766
66.2060547
-168.352539
157.00293
-100.254883
-100.254883
-100.254883
-71.8808594
Binary file not shown.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
�=bm-��|;��a(���GUxc��gU�rZ�t�����l�j{��'��m��83�ab�CX�~��a9-0
@@ -0,0 +1,256 @@
1.4375
-1.4375
1.4375
0
0
2.875
1.4375
0
1.4375
0
0
-1.4375
0
2.875
1.4375
-1.4375
0
1.4375
1.4375
1.4375
1.4375
1.4375
1.4375
1.4375
2.875
0
0
-1.4375
-1.4375
2.875
2.875
0
-1.4375
-1.4375
0
-1.4375
2.875
1.4375
2.875
-1.4375
2.875
-1.4375
-1.4375
2.875
0
0
-1.4375
2.875
0
-1.4375
1.4375
0
1.4375
2.875
-1.4375
-1.4375
-1.4375
1.4375
1.4375
-1.4375
1.4375
0
-1.4375
1.4375
-3.36914062
-0
1.68457031
-0
-0
-0
-0
-0
1.68457031
-1.68457031
-3.36914062
-0
-3.36914062
1.68457031
-1.68457031
-0
-3.36914062
-1.68457031
-1.68457031
-3.36914062
-3.36914062
-0
1.68457031
-1.68457031
-3.36914062
-0
-1.68457031
-0
-0
-0
-0
-0
-1.68457031
1.68457031
-0
1.68457031
-1.68457031
-1.68457031
-1.68457031
-3.36914062
-1.68457031
1.68457031
-3.36914062
-0
-1.68457031
-1.68457031
-0
-0
-3.36914062
1.68457031
-1.68457031
-3.36914062
-0
-0
1.68457031
1.68457031
1.68457031
-0
-3.36914062
-0
-0
-0
-0
-3.36914062
-1.03027344
1.03027344
1.03027344
-1.03027344
-2.06054688
-2.06054688
-0
-1.03027344
-0
-2.06054688
-2.06054688
-2.06054688
1.03027344
-2.06054688
-1.03027344
-0
-2.06054688
-2.06054688
1.03027344
-1.03027344
-1.03027344
-1.03027344
-1.03027344
-0
-2.06054688
-1.03027344
-2.06054688
-0
-1.03027344
-2.06054688
-1.03027344
-1.03027344
1.03027344
-1.03027344
-1.03027344
-1.03027344
-2.06054688
-0
-1.03027344
1.03027344
-0
1.03027344
-0
1.03027344
-1.03027344
-2.06054688
-2.06054688
-2.06054688
1.03027344
-2.06054688
-1.03027344
-1.03027344
-0
-2.06054688
-1.03027344
-0
1.03027344
-2.06054688
1.03027344
-1.03027344
-1.03027344
-1.03027344
-1.03027344
-1.03027344
-0.225585938
0.225585938
0.451171875
0.225585938
0
-0.225585938
0.225585938
0
0.225585938
-0.225585938
0.225585938
0
0.225585938
0
0
0.451171875
0.451171875
-0.225585938
-0.225585938
0
-0.225585938
0.225585938
0
0
0.451171875
0.451171875
0
0.451171875
0.225585938
0.451171875
0.451171875
0
0
-0.225585938
-0.225585938
0.225585938
0
0.225585938
-0.225585938
0.451171875
0
-0.225585938
0.225585938
0
-0.225585938
-0.225585938
0
-0.225585938
0
0.225585938
0.451171875
-0.225585938
0
0.451171875
0.225585938
-0.225585938
0.225585938
0.451171875
0
-0.225585938
-0.225585938
-0.225585938
0.451171875
-0.225585938
@@ -0,0 +1 @@
~4ÎÖϤ–:ÌÖsðº¿@‚a«¸†2 H°©–¼g2Òí^"qµbùM‚É­g4�ZGÄ3#²4õ>ƒ!®KÑà¤0¥!¨…†$
@@ -0,0 +1,128 @@
1.68457031
-0.561523438
1.96533203
-1.12304688
-0.561523438
0.561523438
1.12304688
-0.561523438
-1.12304688
-1.40380859
-2.24609375
0.561523438
1.96533203
-2.24609375
-1.68457031
-1.96533203
1.12304688
1.40380859
1.12304688
0.561523438
0.280761719
-1.40380859
1.12304688
1.40380859
-1.96533203
-0.280761719
1.96533203
0.842285156
0.842285156
-1.12304688
0
-0.561523438
1.16699219
3.50097656
4.66796875
-0
4.66796875
-0.583496094
1.16699219
1.75048828
-2.33398438
0.583496094
3.50097656
3.50097656
-2.91748047
-3.50097656
3.50097656
-1.75048828
-0
2.91748047
3.50097656
2.33398438
-1.75048828
-1.16699219
-0.583496094
4.66796875
-1.75048828
1.16699219
2.91748047
-2.91748047
-3.50097656
1.75048828
3.50097656
4.08447266
2.04052734
-0.340087891
-1.70043945
2.04052734
-0.340087891
-1.70043945
0.340087891
1.36035156
-2.38061523
-0.680175781
0.340087891
1.36035156
1.70043945
1.70043945
2.04052734
1.36035156
0.680175781
-2.38061523
1.36035156
-0
-1.36035156
-0.680175781
0.680175781
1.70043945
-0
1.02026367
1.36035156
-1.36035156
1.70043945
2.04052734
-1.02026367
1.70043945
-8.69628906
-12.1748047
10.4355469
10.4355469
5.21777344
-12.1748047
-13.9140625
-6.95703125
-13.9140625
-5.21777344
-12.1748047
12.1748047
0
-5.21777344
-3.47851562
-6.95703125
0
-10.4355469
3.47851562
-13.9140625
-6.95703125
8.69628906
10.4355469
3.47851562
-8.69628906
3.47851562
-10.4355469
-12.1748047
3.47851562
0
0
-10.4355469
@@ -0,0 +1 @@
™=R¿¶ca,|¥ÃÚyb¦yç]þÕ®€½*а �X©FzBžn'�wßd>‘¿K©J¨_ Ž7S˜2V,h—ð=Œ>úP’ÍtOQµÛ&ˆN¥Í�ß
@@ -0,0 +1,128 @@
6.56640625
2.36816406
-0.430664062
14.9628906
14.9628906
5.16699219
2.36816406
12.1640625
10.7646484
0.96875
14.9628906
6.56640625
10.7646484
7.96582031
16.3623047
17.7617188
13.5634766
6.56640625
6.56640625
0.96875
7.96582031
12.1640625
14.9628906
16.3623047
7.96582031
6.56640625
-0.430664062
12.1640625
7.96582031
17.7617188
5.16699219
19.1611328
-2.44250488
-1.375
-1.375
-2.54925537
-1.48175049
-2.22900391
-2.33575439
-2.01550293
-2.44250488
-1.58850098
-2.86950684
-2.86950684
-2.12225342
-2.97625732
-2.12225342
-2.97625732
-1.58850098
-2.76275635
-2.54925537
-1.375
-2.22900391
-1.90875244
-2.44250488
-1.80200195
-2.12225342
-1.80200195
-2.33575439
-2.01550293
-1.58850098
-2.22900391
-2.12225342
-2.76275635
15.6826172
12.4873047
14.0849609
10.8896484
22.0732422
17.2802734
20.4755859
9.29199219
6.09667969
2.90136719
10.8896484
1.30371094
7.69433594
17.2802734
10.8896484
9.29199219
4.49902344
14.0849609
4.49902344
14.0849609
6.09667969
-1.89160156
10.8896484
2.90136719
-1.89160156
6.09667969
12.4873047
2.90136719
6.09667969
1.30371094
7.69433594
12.4873047
16.4804688
1.63671875
4.60546875
20.9335938
7.57421875
23.9023438
3.12109375
9.05859375
17.9648438
10.5429688
13.5117188
22.4179688
9.05859375
20.9335938
20.9335938
23.9023438
23.9023438
9.05859375
14.9960938
19.4492188
12.0273438
7.57421875
9.05859375
17.9648438
20.9335938
4.60546875
13.5117188
7.57421875
16.4804688
19.4492188
14.9960938
20.9335938
Binary file not shown.
@@ -0,0 +1,128 @@
-0.396484375
-0
5.15429688
-3.171875
6.34375
-5.55078125
1.98242188
-1.98242188
-1.18945312
-4.7578125
-2.77539062
-0
-1.5859375
-3.171875
-5.15429688
-5.15429688
-1.5859375
6.34375
5.15429688
-1.18945312
-5.55078125
1.98242188
6.34375
-0.396484375
3.56835938
3.56835938
-1.5859375
5.94726562
1.98242188
-1.5859375
-0.396484375
1.98242188
-0.763671875
0.763671875
-6.87304688
11.4550781
6.87304688
-9.1640625
4.58203125
-11.4550781
7.63671875
6.87304688
10.6914062
4.58203125
9.1640625
-0.763671875
3.0546875
-11.4550781
-6.109375
-0.763671875
-12.21875
-3.0546875
-8.40039062
-12.21875
4.58203125
-5.34570312
9.92773438
-2.29101562
-2.29101562
-2.29101562
0
9.1640625
1.52734375
7.63671875
-6.1015625
12.203125
-7.62695312
-4.57617188
18.3046875
-15.2539062
16.7792969
1.52539062
-6.1015625
21.3554688
-21.3554688
-21.3554688
19.8300781
-16.7792969
-18.3046875
4.57617188
1.52539062
4.57617188
22.8808594
16.7792969
16.7792969
-9.15234375
-9.15234375
12.203125
22.8808594
4.57617188
24.40625
-19.8300781
-1.52539062
-9.15234375
21.3554688
-15.2539062
0
4.24853516
-1.51733398
3.64160156
-0.606933594
-1.51733398
-2.12426758
-3.64160156
3.64160156
3.03466797
0.606933594
0.303466797
0.910400391
-3.03466797
-0.910400391
-2.42773438
4.24853516
0.606933594
2.73120117
-0.910400391
-0.910400391
-3.03466797
3.64160156
-0.303466797
0
-3.64160156
-3.03466797
-0.606933594
1.51733398
-4.24853516
-4.24853516
-2.12426758
Binary file not shown.
@@ -0,0 +1,128 @@
59.3544922
21.7255859
21.7255859
11.8232422
55.3935547
53.4130859
19.7451172
3.90136719
3.90136719
35.5888672
5.88183594
59.3544922
17.7646484
31.6279297
31.6279297
25.6865234
41.5302734
5.88183594
55.3935547
11.8232422
21.7255859
11.8232422
47.4716797
49.4521484
45.4912109
15.7841797
27.6669922
39.5498047
33.6083984
7.86230469
35.5888672
21.7255859
-52.3378906
-18.4707031
-25.2441406
-6.6171875
-33.7109375
-28.6308594
-37.0976562
-47.2578125
-6.6171875
-4.92382812
-26.9375
-38.7910156
-16.7773438
-33.7109375
-42.1777344
-10.0039062
-11.6972656
-11.6972656
-8.31054688
-6.6171875
-40.484375
-21.8574219
-33.7109375
-30.3242188
-28.6308594
-1.53710938
-8.31054688
-15.0839844
-1.53710938
-6.6171875
-21.8574219
-21.8574219
-42.4667969
-22.1816406
-27.2529297
-30.6337891
-1.89648438
-42.4667969
-13.7294922
-32.3242188
-8.65820312
-42.4667969
-1.89648438
-3.58691406
-34.0146484
-23.8720703
-52.609375
-32.3242188
-50.9189453
-45.8476562
-20.4912109
-39.0859375
-39.0859375
-47.5380859
-1.89648438
-17.1103516
-45.8476562
-17.1103516
-1.89648438
-6.96777344
-50.9189453
-47.5380859
-45.8476562
-15.4199219
6.42797852
11.9562988
4.58520508
12.8776855
5.04589844
5.5065918
4.58520508
7.34936523
11.4956055
5.5065918
5.5065918
13.7990723
10.1135254
3.66381836
10.5742188
3.66381836
7.34936523
8.27075195
2.28173828
10.5742188
12.8776855
-0.482421875
7.81005859
7.81005859
13.3383789
10.1135254
1.82104492
5.04589844
1.36035156
5.5065918
13.7990723
0.899658203
Binary file not shown.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,9 @@
q4k_gate.bin Q4_K 8 blocks of 144 bytes 2048 values from blk.1.ffn_gate_exps.weight, expert 0, the first 8 blocks of the tensor = row 0 (6 blocks of its 1536 columns) then the first 2 blocks of row 1 -> q4k_gate.expected.txt (one float64 per line, element order)
q4k_down.bin Q4_K 8 blocks of 144 bytes 2048 values from blk.5.ffn_down_exps.weight, expert 0, the first 8 blocks of the tensor = row 0 (6 blocks of its 1536 columns) then the first 2 blocks of row 1 -> q4k_down.expected.txt (one float64 per line, element order)
q6k_down.bin Q6_K 8 blocks of 210 bytes 2048 values from blk.1.ffn_down_exps.weight, expert 0, the first 8 blocks of the tensor = row 0 (6 blocks of its 1536 columns) then the first 2 blocks of row 1 -> q6k_down.expected.txt (one float64 per line, element order)
q8_0_ffn.bin Q8_0 8 blocks of 34 bytes 256 values from blk.0.ffn_gate.weight, row 0, columns 0..255 (8 blocks) -> q8_0_ffn.expected.txt (one float64 per line, element order)
q8_0_embd.bin Q8_0 8 blocks of 34 bytes 256 values from token_embd.weight, row 0, columns 0..255 (8 blocks) -> q8_0_embd.expected.txt (one float64 per line, element order)
bf16_out.bin BF16 32 values from output.weight, row 0, columns 0..31 -> bf16_out.expected.txt
q3k_gate.bin Q3_K 8 blocks of 110 bytes 2048 values from Hy4-flash-Q3_K file blk.6.ffn_gate_exps.weight, expert 0, first 8 blocks -> q3k_gate.expected.txt
iq2xxs_gate.bin IQ2_XXS 8 blocks of 66 bytes 2048 values from Hy4-flash-IQ2_AH file blk.1.ffn_gate_exps.weight, expert 0, first 8 blocks -> iq2xxs_gate.expected.txt
iq2xxs_grid.txt the 256-row IQ2_XXS grid (index, 8 digits: 0=8 1=25 2=43), Appendix A of FORMAT-SPEC.md
@@ -0,0 +1 @@
¦<z¼¢¼ =`½&»³=O<„<�½9½š¼¥:ûŒ¼’;µ¼P¼½�¼—»`½ƒ¼d:¼N»Ö¼6¼¼P½½,=
@@ -0,0 +1,32 @@
0.020263671875
-0.0152587890625
-0.019775390625
0.033935546875
-0.0546875
-0.002532958984375
0.08740234375
0.01263427734375
0.01611328125
-0.06298828125
-0.045166015625
-0.018798828125
0.00125885009765625
-0.005950927734375
-0.01708984375
0.00445556640625
-0.0220947265625
-0.0126953125
-0.033203125
-0.0172119140625
-0.004608154296875
-0.0546875
-0.0159912109375
0.0008697509765625
-0.00811767578125
-0.003143310546875
-0.026123046875
-0.0111083984375
-0.00927734375
-0.05078125
-0.0322265625
0.0419921875
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,256 @@
0 00000000
1 20000000
2 11000000
3 02000000
4 22000000
5 10100000
6 01100000
7 00200000
8 20200000
9 02200000
10 22200000
11 10010000
12 01010000
13 00110000
14 02110000
15 10210000
16 01210000
17 00020000
18 20020000
19 22020000
20 20220000
21 10001000
22 01001000
23 00101000
24 11101000
25 00011000
26 01021000
27 02121000
28 00002000
29 20002000
30 20202000
31 20022000
32 10000100
33 01000100
34 00100100
35 10200100
36 01200100
37 00010100
38 20010100
39 02010100
40 00210100
41 10020100
42 01020100
43 00120100
44 01220100
45 00001100
46 20001100
47 02001100
48 00201100
49 21011100
50 12211100
51 00021100
52 10121100
53 12002100
54 00102100
55 00012100
56 01022100
57 01222100
58 00000200
59 11000200
60 02000200
61 01100200
62 02200200
63 10010200
64 01010200
65 00110200
66 20110200
67 02020200
68 01001200
69 00011200
70 20002200
71 01102200
72 10000010
73 01000010
74 00100010
75 10200010
76 00010010
77 00210010
78 01020010
79 00120010
80 11120010
81 00001010
82 02001010
83 00201010
84 00111010
85 22111010
86 00021010
87 01202010
88 11012010
89 00000110
90 02000110
91 00200110
92 11200110
93 12010110
94 00020110
95 02101110
96 20211110
97 00002110
98 21102110
99 10000210
100 01000210
101 00100210
102 00010210
103 10020210
104 00001210
105 11001210
106 00221210
107 10112210
108 00000020
109 20000020
110 22000020
111 01010020
112 10210020
113 00020020
114 20020020
115 12201020
116 02011020
117 00002020
118 20002020
119 10000120
120 01000120
121 00100120
122 00010120
123 21110120
124 00001120
125 10011120
126 01211120
127 00122120
128 02000220
129 00200220
130 01120220
131 01012220
132 10000001
133 01000001
134 00100001
135 02100001
136 10200001
137 01200001
138 00010001
139 02010001
140 21110001
141 00210001
142 10020001
143 01020001
144 00120001
145 00001001
146 00201001
147 10211001
148 00021001
149 11021001
150 10002001
151 00102001
152 02012001
153 21112001
154 02212001
155 00000101
156 02000101
157 00200101
158 00020101
159 12120101
160 20101101
161 01201101
162 00002101
163 10000201
164 01000201
165 00100201
166 00010201
167 11010201
168 00001201
169 02111201
170 10211201
171 20021201
172 11012201
173 00122201
174 00000011
175 02000011
176 10100011
177 12100011
178 00200011
179 00020011
180 02020011
181 01001011
182 20011011
183 01221011
184 10122011
185 00120111
186 20120111
187 22001111
188 10002111
189 01112111
190 00000211
191 10100211
192 12100211
193 01210211
194 00011211
195 02002211
196 01000021
197 00100021
198 00010021
199 02210021
200 00001021
201 11111021
202 02102021
203 00212021
204 00000121
205 11000121
206 00101121
207 20101121
208 01021121
209 20010221
210 00000002
211 20000002
212 22000002
213 10010002
214 20020002
215 01001002
216 02101002
217 00011002
218 10102002
219 10000102
220 01000102
221 00100102
222 11100102
223 00010102
224 00210102
225 00001102
226 21011102
227 01121102
228 12002102
229 00012102
230 00212102
231 20000202
232 01001202
233 10102202
234 01000012
235 00100012
236 01200012
237 00010012
238 10220012
239 21101012
240 00021012
241 11012012
242 00000112
243 20200112
244 01010112
245 10111112
246 10020212
247 00201212
248 20000022
249 00110022
250 11020022
251 12001022
252 00002022
253 02100122
254 00110222
255 01001222
Binary file not shown.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,6 @@
�Hüòÿô­¥ÿï¢÷{é8fWY–‰fOEpxtŠKT"´Yˆó8¨8Q|¶¦F´h¤
[ŠË‰i‹É]™Xu]ƈçm<W™¹`Jžuljˆ8ÇȘÚzp]yœãÊjŒH:›mnŠkH| •6e~‹Io©dcׄ¨É‰€i¹¹¬ŒÉs¸y ¦ÚÇ—|Èi—ú™t×¹·—I�¥­ÿð§k²SYÁwhªÇ¶˜…xÕÈÖª “°�ÑÌ€¯ÝEšËÉ…›£Ì³ÆªíÝG GœŠHAê šJnxúH5¢ H:9�µ¼Çœž§k*…?ƒ55t„&� •ç::8bqWWuœ3hX˜‰‰S‡Ù¶æU ˜Wht:Y,™4˜÷�¯‹s{�ˆ–mWkzþ¾÷ÿö¾ú¶P®ùYF?hw†$÷fÇd—‰¥„–Wg¹%hksˆu�·vE‡ufHgF¹‡%‰Ie0ãu»d¾MF¤†Y¶ujvCRsÛ#Št{eDi™û@gM&Ì
~ dÛxê“*,xNxyI©|a†| sdg<e€l'Tx˘$2|
MX éxV/|AèêøöïéýÿðÉ�†$¬œd|¥vf9?)îL«wm+“»d´×°ð»¬}§œ»U7˜¾ø¼Y¥‹yIzÏwH  –Ÿù¦Κ•¨(ˆ{£8GTh_[(›yU¨;O{˜é�kµ(¯)‰K¢4Z~]5hl—†uè)iŒ§rGe·t§Ž‚ƒx€R¦Iz—$fi†¦·_"í÷ï«äüÿ³òQ_ºŒw`•¤lZ‘£æª©©Z¸C¶bÃØNS;!J¤¦’€ÀT6‹™Á/`Æå˜}n—oš\ÉÜ(o™g{xKv+w{HºnÚcZèÂ'4¨ÚwåJmvbš|¬šE~µúk$h@rW‡¥åÇV¶g:b§ ÄU²¡ø'TUbÅÎ'vóª[‰MÉÖÿø÷öèüô¬x,ýù†8}Ió”¹´’ªn[—ŠHÉÿŠ—”¡c†VU(š«ÅuUzeÄK«‘n°5g?¶æ›Q‘À¥É`¢W§wV(ÆK ¡k›ˆÂ»ybhÛ6˜%=Ne´¤j"9Ÿž^�CºNIòùq•Ë6È(f}X^êVtVkªÄ‰YqxY<ð—o`QÞb®ú¾óíÿ°ø‹V‹_²Óirs‰†TD…ºˆ¬
‡=@› fe‡‹[™ùXo°Lig�H¦óg™‡@ÅfPgd“…1‰‰G‰Ç¾—zÄI©tÔiYk|KN{xm9'æz9C
Q®h0]—¸w�OJš-�{žï…@ƒas¬j�Cwqt'"†eZ‚bnuxQdA�iƒt󿦱éÿêvÿyC[�qr·fw\wuf¹…^y6g÷ªp‰dc’F‡‡“‡�tcbw7Kׇӈɗ¨˜›<Ëw~|”ªö”‰]iZ0 Ùg:ƒd·h(ésö؈RwãgŠzh˜˜™¨Ë•étÌ�€xwb~pƒ”&[«†K6f;í:>I[«IU[9Ö5¬«\;
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff. Show more