diff --git a/docs/BASINKV.md b/docs/BASINKV.md index 9221c73b93..7ccb44de37 100644 --- a/docs/BASINKV.md +++ b/docs/BASINKV.md @@ -9,7 +9,7 @@ step and prefetches the highest-scoring blocks asynchronously over PCIe before t Supported in v1: - **Architectures**: `qwen35moe`, `clover_moe`, `qwen4exp`, and `inkling2` (`Qwen3.6-35B-A3B`, `Qwen4-35B-A3B`, `Groot 19B-A3B`, `Ornith 1.5`, `Tiel Coder`, `Clover`, `Inkling 2 Mini`) on `strata-poly`. -- **Backends**: CUDA (validated on NVIDIA RTX 4070 Laptop 8 GB on Windows and NVIDIA RTX 4090 D 24 GB on Linux) and HIP (shared `hip_compat` code; compiled and linked cleanly under ROCm `10.2.0a20260930` and community-verified on physical AMD Radeon RX 9070 XT 16 GB `gfx1201` with `UD-IQ4_XS` `8/8` exact NIAH `8K–505K` at flat `13.69–14.28 GB` VRAM — see [community RX 9070 XT report](bench-results/2026-12-04-community-rx-9070-xt-qwen4-35b-a3b-ud-iq4-xs/README.md)). Not supported on Metal unified memory (stubbed in `engine/metal/src/poly/unported.cpp`, compiled and passed 8/8 Metal `ctest` parity checks on Apple M5 Ultra). +- **Backends**: CUDA (validated on NVIDIA RTX 4070 Laptop 8 GB on Windows and NVIDIA RTX 4090 D 24 GB on Linux), HIP (shared `hip_compat` code; compiled and linked cleanly under ROCm `10.2.0a20260930` and community-verified on physical AMD Radeon RX 9070 XT 16 GB `gfx1201` with `UD-IQ4_XS` `8/8` exact NIAH `8K–505K` at flat `13.69–14.28 GB` VRAM — see [community RX 9070 XT report](bench-results/2026-12-04-community-rx-9070-xt-qwen4-35b-a3b-ud-iq4-xs/README.md)), and Metal (`engine/metal/src/poly/basinkv.{cpp,metal}`, opt-in via `strata-poly --basinkv`). - **Limits**: single sequence (`--batch 0`), not combined with `--kv-resident` or `--kv` (BasinKV manages its own FP16 hot slab and quantized host tier). - **Speculative decoding**: compatible with embedded MTP (`qwen35moe` and `qwen4exp` `blk.40`) and external DFlash2 (`qwen4exp` `--draft-model`). On `inkling2`, `--draft-model` is not yet combined with `--basinkv`. diff --git a/engine/metal/CMakeLists.txt b/engine/metal/CMakeLists.txt index 14c7f86dc0..4892f46073 100644 --- a/engine/metal/CMakeLists.txt +++ b/engine/metal/CMakeLists.txt @@ -261,7 +261,7 @@ target_link_libraries(window_probe PRIVATE strata_metal_kernels strata_metal_hos # The smaller-family engine keeps the shared line protocol, expert cache, CPU # experts, batching, conversations and speculative decoding. if(STRATA_METAL_POLY) - target_sources(strata_poly_metal_kernels PRIVATE src/poly/quantized.cpp src/poly/inkling.cpp src/poly/qwen4.cpp src/poly/dflash2_poly.cpp src/poly/unported.cpp) + target_sources(strata_poly_metal_kernels PRIVATE src/poly/quantized.cpp src/poly/inkling.cpp src/poly/qwen4.cpp src/poly/dflash2_poly.cpp src/poly/basinkv.cpp src/poly/unported.cpp) if(NOT TARGET strata_quant) message(FATAL_ERROR "strata-poly on Metal needs the Strata quant layer (STRATA_OWN_CPU_QUANT=ON)") endif() @@ -274,7 +274,8 @@ if(STRATA_METAL_POLY) STRATA_POLY_INKLING_SOURCE="${CMAKE_CURRENT_SOURCE_DIR}/src/poly/inkling.metal" STRATA_POLY_INKLING_FLASH_SOURCE="${CMAKE_CURRENT_SOURCE_DIR}/src/poly/inkling_flash.metal" STRATA_POLY_QWEN4_SOURCE="${CMAKE_CURRENT_SOURCE_DIR}/src/poly/qwen4.metal" - STRATA_POLY_DFLASH2_SOURCE="${CMAKE_CURRENT_SOURCE_DIR}/src/poly/dflash2.metal") + STRATA_POLY_DFLASH2_SOURCE="${CMAKE_CURRENT_SOURCE_DIR}/src/poly/dflash2.metal" + STRATA_POLY_BASINKV_SOURCE="${CMAKE_CURRENT_SOURCE_DIR}/src/poly/basinkv.metal") target_link_libraries(strata_poly_metal_kernels PUBLIC strata_quant) add_executable(strata-poly ${S}/poly/main.cpp ${S}/poly/engine.cpp ${S}/poly/basinkv.cpp ${S}/poly/qwen35.cpp ${S}/poly/qwen4.cpp ${S}/poly/gemma4.cpp ${S}/poly/lfm2moe.cpp ${S}/poly/glm5next.cpp ${S}/poly/deepseek4.cpp ${S}/poly/flint.cpp @@ -291,11 +292,16 @@ if(STRATA_METAL_POLY) add_executable(poly_dflash2_metal_test ${S}/poly/dflash2_poly_test.cu) target_include_directories(poly_dflash2_metal_test PRIVATE ${S}/poly) target_link_libraries(poly_dflash2_metal_test PRIVATE strata_poly_metal_kernels strata_quant) + add_executable(poly_basinkv_parity poly_tests/basinkv_parity.cpp ${S}/poly/basinkv.cpp) + target_include_directories(poly_basinkv_parity PRIVATE ${S}/poly) + target_link_libraries(poly_basinkv_parity PRIVATE strata_poly_metal_kernels) if(BUILD_TESTING) add_test(NAME poly_norm_q8_metal_test COMMAND poly_norm_q8_metal_test) set_tests_properties(poly_norm_q8_metal_test PROPERTIES LABELS "metal;gpu;poly" RESOURCE_LOCK metal_gpu TIMEOUT 120) add_test(NAME poly_dflash2_metal_test COMMAND poly_dflash2_metal_test) set_tests_properties(poly_dflash2_metal_test PROPERTIES LABELS "metal;gpu;poly" RESOURCE_LOCK metal_gpu TIMEOUT 180) + add_test(NAME poly_basinkv_parity COMMAND poly_basinkv_parity) + set_tests_properties(poly_basinkv_parity PROPERTIES LABELS "metal;gpu;poly" RESOURCE_LOCK metal_gpu TIMEOUT 180) endif() endif() diff --git a/engine/metal/poly_tests/basinkv_parity.cpp b/engine/metal/poly_tests/basinkv_parity.cpp new file mode 100644 index 0000000000..57ce55e1b6 --- /dev/null +++ b/engine/metal/poly_tests/basinkv_parity.cpp @@ -0,0 +1,1675 @@ +// metal/poly_tests/basinkv_parity.cpp - Comprehensive Apple Silicon Metal GPU parity tests for BasinKV. +// Mirrors engine/src/poly/basinkv_test.cu plus 4096-token (> 2048 resident) steady-state, GQA kMean, and Inkling 2 hot_cap checks. +#include "basinkv.hpp" +#include "inkling2_kernels.hpp" +#include "strata/gpu/metal.hpp" +#include "strata/gpu/runtime.hpp" +#include "strata/poly/kernels.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace strata::poly; +namespace gpu = strata::gpu; + +namespace { + +int g_failures = 0; + +void check_gpu(gpu::Error err, const char* what) { + if (err != gpu::kSuccess) { + std::fprintf(stderr, "METAL ERROR (%s): %s\n", what, gpu::error_string(err)); + std::exit(1); + } +} + +void expect_true(bool cond, const char* msg) { + if (!cond) { + std::fprintf(stderr, "FAIL: %s\n", msg); + ++g_failures; + } +} + +template +void expect_throws(Fn&& fn, const char* msg) { + try { + fn(); + std::fprintf(stderr, "FAIL (did not throw): %s\n", msg); + ++g_failures; + } catch (const std::exception&) { + } +} + +inline float f16_bits_to_f32(uint16_t h) noexcept { + _Float16 f16; + std::memcpy(&f16, &h, sizeof(uint16_t)); + return static_cast(f16); +} + +inline float round_f32_via_f16(float x) noexcept { + const _Float16 f16 = static_cast<_Float16>(x); + return static_cast(f16); +} + +// Reference orthonormal Walsh-Hadamard transform on host (FP64) matching basinkv.metal +void fwht_block_f64(double* v, int n) { + for (int len = 1; len < n; len <<= 1) { + for (int i = 0; i < n; i += (len << 1)) { + for (int j = 0; j < len; ++j) { + double a = v[i + j]; + double b = v[i + j + len]; + v[i + j] = a + b; + v[i + j + len] = a - b; + } + } + } + const double inv = 1.0 / std::sqrt(static_cast(n)); + for (int i = 0; i < n; ++i) v[i] *= inv; +} + +void wht_forward_f64(const std::vector& in, const std::vector& signs, std::vector& out) { + const int D = static_cast(in.size()); + out.resize(D); + for (int i = 0; i < D; ++i) out[i] = in[i] * static_cast(signs[i]); + if (D == 64 || D == 128 || D == 256 || D == 512) { + fwht_block_f64(out.data(), D); + } else { + for (int off = 0; off < D; off += 64) fwht_block_f64(out.data() + off, 64); + } +} + +void verify_page_table_invariants(BasinKvPool& pool, int32_t layer, const char* label) { + const auto& cfg = pool.config(); + const int32_t H = cfg.n_head_kv; + const int32_t W = cfg.resident_blocks(); + const int32_t M = cfg.max_blocks(); + const int32_t sl = pool.seq_len(layer); + std::vector g2c, c2g; + pool.read_page_tables(layer, g2c, c2g); + + for (int32_t h = 0; h < H; ++h) { + const int32_t* g = g2c.data() + static_cast(h) * W; + const int32_t* c = c2g.data() + static_cast(h) * M; + for (int32_t s = 0; s < W; ++s) { + int32_t b = g[s]; + if (b != -1) { + if (b < 0 || b >= M || c[b] != s) { + std::fprintf(stderr, "FAIL [%s]: g2c[%d][%d]=%d but c2g[%d][%d]=%d\n", + label, h, s, b, h, b, (b >= 0 && b < M) ? c[b] : -999); + ++g_failures; + return; + } + } + } + for (int32_t b = 0; b < M; ++b) { + int32_t s = c[b]; + if (s != -1) { + if (s < 0 || s >= W || g[s] != b) { + std::fprintf(stderr, "FAIL [%s]: c2g[%d][%d]=%d but g2c[%d][%d]=%d\n", + label, h, b, s, h, s, (s >= 0 && s < W) ? g[s] : -999); + ++g_failures; + return; + } + } + } + if (sl > cfg.resident_tokens()) { + for (int32_t s = 0; s < W; ++s) { + if (g[s] < 0) { + std::fprintf(stderr, "FAIL [%s]: hole at head=%d slot=%d (seq_len=%d)\n", label, h, s, sl); + ++g_failures; + return; + } + } + for (int32_t s = 0; s < cfg.sink_blocks; ++s) { + if (g[s] != s) { + std::fprintf(stderr, "FAIL [%s]: sink slot %d corrupted (%d)\n", label, s, g[s]); + ++g_failures; + return; + } + } + } + } +} + +// ---- Test 0: Config validation, footprint estimation, GPU availability & UVA flag ---- +void test_config_and_footprint() { + std::printf("Test 0: Config validation, footprint estimation & Metal GPU availability...\n"); + expect_true(basinkv_gpu_available(), "basinkv_gpu_available() == true on Metal"); + + BasinKvConfig cfg; + cfg.n_layers = 10; + cfg.n_head_q = 16; + cfg.n_head_kv = 2; + cfg.head_dim = 256; + cfg.rope_dim = 64; + cfg.max_seq_len = 131072; + basinkv_validate_config(cfg); + expect_true(std::fabs(cfg.effective_alpha() - 0.25f) < 1e-6f, "auto alpha for D=256 is 0.25"); + expect_true(cfg.resident_tokens() == 2048, "default resident_tokens=2048"); + + const BasinKvFootprint fp = basinkv_estimate_footprint(cfg); + expect_true(fp.gpu_hot_kv_bytes == 40ULL * 1024ULL * 1024ULL, "10-layer Qwen4 hot slab == 40 MiB"); + expect_true(fp.gpu_total_bytes < 140ULL * 1024ULL * 1024ULL, "10-layer 128K Quest GPU total < 140 MiB"); + + BasinKvConfig bad = cfg; + bad.n_head_q = 15; + expect_throws([&] { basinkv_validate_config(bad); }, "invalid GQA ratio throws"); + + BasinKvConfig small; + small.n_layers = 1; + small.n_head_q = 8; + small.n_head_kv = 2; + small.head_dim = 64; + small.max_seq_len = 512; + small.sink_blocks = 2; + small.sparse_blocks = 10; + small.local_blocks = 4; + BasinKvPool pool; + pool.init(small); + expect_true(pool.is_initialized(), "pool initialized"); + expect_true(pool.is_using_uva(), "Metal UMA enables zero-copy UVA by default"); + expect_true(pool.footprint().gpu_total_bytes == basinkv_estimate_footprint(small).gpu_total_bytes, + "pool.footprint() matches basinkv_estimate_footprint()"); + pool.destroy(); + expect_true(!pool.is_initialized(), "pool destroyed cleanly"); +} + +// ---- Test 1: Quest INT8 outward rounding exactness + Shrunk-Box scoring parity ---- +void test_quest_index_and_scoring() { + std::printf("Test 1: Quest INT8 outward rounding & Shrunk-Box scoring parity (D=64, 128, 256; kMax & kMean)...\n"); + for (int D : {64, 128, 256}) { + for (float alpha : {0.25f, 1.0f}) { + for (BasinGqaReduce gqa : {BasinGqaReduce::kMax, BasinGqaReduce::kMean}) { + if (D == 64 && alpha == 1.0f && gqa == BasinGqaReduce::kMean) continue; + BasinKvConfig cfg; + cfg.n_layers = 1; + cfg.n_head_q = 16; + cfg.n_head_kv = 2; + cfg.head_dim = D; + cfg.rope_dim = std::min(64, D); + cfg.block_size = 16; + cfg.sink_blocks = 2; + cfg.sparse_blocks = 10; + cfg.local_blocks = 4; + cfg.max_seq_len = 512; + cfg.quest_alpha = alpha; + cfg.gqa_reduce = gqa; + cfg.index_mode = BasinIndexMode::kQuestInt8; + cfg.host_quant = BasinHostQuant::kInt8; + + BasinKvPool pool; + pool.init(cfg); + + std::mt19937 rng(12345 + D * 7 + (alpha < 0.5f ? 1 : 2) + static_cast(gqa) * 100); + std::normal_distribution nd(0.0f, 1.5f); + const int32_t seq_len = 480; // 30 full blocks + const int32_t Hk = cfg.n_head_kv; + const int32_t Hq = cfg.n_head_q; + std::vector h_k(static_cast(seq_len) * Hk * D); + std::vector h_v(static_cast(seq_len) * Hk * D); + for (size_t i = 0; i < h_k.size(); ++i) { + h_k[i] = nd(rng); + h_v[i] = nd(rng); + } + // Adversarial values in block 5: near-zero, identical, large magnitude + for (int t = 0; t < 16; ++t) { + h_k[static_cast(5 * 16 + t) * Hk * D + 0] = 1e-4f; + h_k[static_cast(5 * 16 + t) * Hk * D + 1] = -42.5f; + h_k[static_cast(5 * 16 + t) * Hk * D + 2] = (t == 7) ? 31.25f : -0.001f; + } + + float *d_k = nullptr, *d_v = nullptr, *d_q = nullptr, *d_scores = nullptr; + check_gpu(gpu::malloc_device(&d_k, h_k.size() * sizeof(float)), "t1 dk"); + check_gpu(gpu::malloc_device(&d_v, h_v.size() * sizeof(float)), "t1 dv"); + check_gpu(gpu::malloc_device(&d_q, static_cast(Hq) * D * sizeof(float)), "t1 dq"); + check_gpu(gpu::malloc_device(&d_scores, static_cast(Hk) * cfg.max_blocks() * sizeof(float)), "t1 ds"); + check_gpu(gpu::memcpy_sync(d_k, h_k.data(), h_k.size() * sizeof(float), gpu::kHostToDevice), "t1 h2d k"); + check_gpu(gpu::memcpy_sync(d_v, h_v.data(), h_v.size() * sizeof(float), gpu::kHostToDevice), "t1 h2d v"); + + pool.append_prefill_chunk_f32(0, d_k, d_v, 0, seq_len); + check_gpu(gpu::device_synchronize(), "t1 sync prefill"); + + std::vector qmin, qmax; + std::vector smin, smax; + pool.read_quest_index(0, qmin, qmax, smin, smax); + const int32_t M = cfg.max_blocks(); + const int32_t n_blks = seq_len / cfg.block_size; + int bound_violations = 0; + for (int32_t h = 0; h < Hk; ++h) { + for (int32_t b = 0; b < n_blks; ++b) { + const int64_t bidx = static_cast(h) * M + b; + const float smn = smin[bidx], smx = smax[bidx]; + for (int32_t d = 0; d < D; ++d) { + float mn = std::numeric_limits::infinity(); + float mx = -std::numeric_limits::infinity(); + for (int32_t t = 0; t < cfg.block_size; ++t) { + float orig = h_k[(static_cast(b * cfg.block_size + t) * Hk + h) * D + d]; + float f16 = round_f32_via_f16(orig); + mn = std::min(mn, f16); + mx = std::max(mx, f16); + } + const float rmin = static_cast(qmin[bidx * D + d]) * smn; + const float rmax = static_cast(qmax[bidx * D + d]) * smx; + if (rmin > mn + 1e-6f || rmax < mx - 1e-6f) ++bound_violations; + } + } + } + expect_true(bound_violations == 0, "Quest INT8 outward rounding has zero violations"); + + std::vector h_q(static_cast(Hq) * D); + for (float& x : h_q) x = nd(rng); + check_gpu(gpu::memcpy_sync(d_q, h_q.data(), h_q.size() * sizeof(float), gpu::kHostToDevice), "t1 h2d q"); + pool.score_layer_f32(0, d_q, d_scores); + check_gpu(gpu::device_synchronize(), "t1 score sync"); + + std::vector gpu_scores(static_cast(Hk) * M); + check_gpu(gpu::memcpy_sync(gpu_scores.data(), d_scores, gpu_scores.size() * sizeof(float), gpu::kDeviceToHost), "t1 d2h s"); + + const int32_t elig_start = cfg.sink_blocks; + const int32_t elig_end = n_blks - cfg.local_blocks; + const int32_t G = Hq / Hk; + double max_err = 0.0; + for (int32_t h = 0; h < Hk; ++h) { + for (int32_t b = elig_start; b < elig_end; ++b) { + const int64_t bidx = static_cast(h) * M + b; + double agg = (gqa == BasinGqaReduce::kMax) ? -std::numeric_limits::infinity() : 0.0; + for (int32_t g = 0; g < G; ++g) { + const float* qp = h_q.data() + static_cast(h * G + g) * D; + double acc_max = 0.0, acc_min = 0.0; + for (int32_t d = 0; d < D; ++d) { + double qv = qp[d]; + double qa = std::fabs(qv); + double wp = 0.5 * (qv + static_cast(alpha) * qa); + double wm = 0.5 * (qv - static_cast(alpha) * qa); + acc_max += wp * static_cast(qmax[bidx * D + d]); + acc_min += wm * static_cast(qmin[bidx * D + d]); + } + double sc = acc_max * static_cast(smax[bidx]) + acc_min * static_cast(smin[bidx]); + if (gqa == BasinGqaReduce::kMax) agg = std::max(agg, sc); + else agg += sc; + } + if (gqa == BasinGqaReduce::kMean) agg /= static_cast(G); + max_err = std::max(max_err, std::fabs(static_cast(gpu_scores[bidx]) - agg)); + } + } + expect_true(max_err < 1e-3, "Quest shrunk-box Metal GPU score matches FP64 reference"); + + gpu::free_device(d_scores); + gpu::free_device(d_q); + gpu::free_device(d_v); + gpu::free_device(d_k); + } + } + } +} + +// ---- Test 2: SphereIndex INT4 WHT sealing & scoring parity across ALL WHT head_dims ---- +void test_sphere_index_and_scoring() { + std::printf("Test 2: SphereIndex INT4 WHT sealing & scoring parity (D=64, 128, 192, 256, 320, 512)...\n"); + for (int D : {64, 128, 192, 256, 320, 512}) { + const BasinGqaReduce gqa = (D == 192) ? BasinGqaReduce::kMean : BasinGqaReduce::kMax; + BasinKvConfig cfg; + cfg.n_layers = 1; + cfg.n_head_q = 8; + cfg.n_head_kv = 2; + cfg.head_dim = D; + cfg.rope_dim = std::min(64, D); + cfg.block_size = 16; + cfg.sink_blocks = 2; + cfg.sparse_blocks = 10; + cfg.local_blocks = 4; + cfg.max_seq_len = 512; + cfg.sphere_beta = 0.10f; + cfg.gqa_reduce = gqa; + cfg.index_mode = BasinIndexMode::kSphereInt4; + cfg.host_quant = BasinHostQuant::kWhtInt4; + + BasinKvPool pool; + pool.init(cfg); + + std::mt19937 rng(777 + D); + std::normal_distribution nd(0.0f, 1.0f); + const int32_t seq_len = 480; + const int32_t Hk = cfg.n_head_kv; + const int32_t Hq = cfg.n_head_q; + std::vector h_k(static_cast(seq_len) * Hk * D); + std::vector h_v(static_cast(seq_len) * Hk * D); + for (size_t i = 0; i < h_k.size(); ++i) { + h_k[i] = nd(rng); + h_v[i] = nd(rng); + } + std::vector h_q(static_cast(Hq) * D); + for (float& x : h_q) x = nd(rng); + // Plant an aligned needle block at block 10 + const int32_t G = Hq / Hk; + for (int32_t h = 0; h < Hk; ++h) { + for (int32_t t = 0; t < cfg.block_size; ++t) { + for (int32_t d = 0; d < D; ++d) { + float qsum = 0.0f; + for (int32_t g = 0; g < G; ++g) qsum += h_q[static_cast(h * G + g) * D + d]; + h_k[(static_cast(10 * cfg.block_size + t) * Hk + h) * D + d] = + (gqa == BasinGqaReduce::kMean) ? (2.0f * qsum) : (3.5f * h_q[static_cast(h * G) * D + d]); + } + } + } + + float *d_k = nullptr, *d_v = nullptr, *d_q = nullptr, *d_scores = nullptr; + check_gpu(gpu::malloc_device(&d_k, h_k.size() * sizeof(float)), "t2 dk"); + check_gpu(gpu::malloc_device(&d_v, h_v.size() * sizeof(float)), "t2 dv"); + check_gpu(gpu::malloc_device(&d_q, h_q.size() * sizeof(float)), "t2 dq"); + check_gpu(gpu::malloc_device(&d_scores, static_cast(Hk) * cfg.max_blocks() * sizeof(float)), "t2 ds"); + check_gpu(gpu::memcpy_sync(d_k, h_k.data(), h_k.size() * sizeof(float), gpu::kHostToDevice), "t2 h2d k"); + check_gpu(gpu::memcpy_sync(d_v, h_v.data(), h_v.size() * sizeof(float), gpu::kHostToDevice), "t2 h2d v"); + check_gpu(gpu::memcpy_sync(d_q, h_q.data(), h_q.size() * sizeof(float), gpu::kHostToDevice), "t2 h2d q"); + + pool.append_prefill_chunk_f32(0, d_k, d_v, 0, seq_len); + pool.score_layer_f32(0, d_q, d_scores); + check_gpu(gpu::device_synchronize(), "t2 sync"); + + std::vector packed; + std::vector scales; + std::vector radii_f16; + pool.read_sphere_index(0, packed, scales, radii_f16); + std::vector gpu_scores(static_cast(Hk) * cfg.max_blocks()); + check_gpu(gpu::memcpy_sync(gpu_scores.data(), d_scores, gpu_scores.size() * sizeof(float), gpu::kDeviceToHost), "t2 d2h"); + + const int32_t M = cfg.max_blocks(); + const int32_t elig_start = cfg.sink_blocks; + const int32_t elig_end = (seq_len / cfg.block_size) - cfg.local_blocks; + for (int32_t h = 0; h < Hk; ++h) { + int32_t best_blk = -1; + float best_sc = -std::numeric_limits::infinity(); + for (int32_t b = elig_start; b < elig_end; ++b) { + float sc = gpu_scores[static_cast(h) * M + b]; + if (sc > best_sc) { best_sc = sc; best_blk = b; } + } + expect_true(best_blk == 10, "SphereIndex ranks planted needle block #1"); + } + + std::vector signs; + basinkv_generate_wht_signs(D, cfg.wht_seed, signs); + double max_err = 0.0; + for (int32_t h = 0; h < Hk; ++h) { + std::vector> q_rot(G); + std::vector qn_rope(G, 0.0), qn_nope(G, 0.0); + for (int32_t g = 0; g < G; ++g) { + std::vector qd(D); + for (int32_t d = 0; d < D; ++d) { + qd[d] = h_q[static_cast(h * G + g) * D + d]; + if (d < cfg.effective_rope_dim()) qn_rope[g] += qd[d] * qd[d]; + else qn_nope[g] += qd[d] * qd[d]; + } + qn_rope[g] = std::sqrt(qn_rope[g]); + qn_nope[g] = std::sqrt(qn_nope[g]); + wht_forward_f64(qd, signs, q_rot[g]); + } + for (int32_t b = elig_start; b < elig_end; ++b) { + const int64_t bidx = static_cast(h) * M + b; + const double sc_scale = scales[bidx]; + const double r_rope = f16_bits_to_f32(radii_f16[bidx * 2 + 0]); + const double r_nope = f16_bits_to_f32(radii_f16[bidx * 2 + 1]); + double agg = (gqa == BasinGqaReduce::kMax) ? -std::numeric_limits::infinity() : 0.0; + for (int32_t g = 0; g < G; ++g) { + double dot = 0.0; + for (int32_t p = 0; p < D / 2; ++p) { + uint8_t byte = packed[bidx * (D / 2) + p]; + int lo = static_cast(byte & 0x0Fu) - 8; + int hi = static_cast((byte >> 4) & 0x0Fu) - 8; + dot += q_rot[g][2 * p] * static_cast(lo) + q_rot[g][2 * p + 1] * static_cast(hi); + } + double val = dot * sc_scale + static_cast(cfg.sphere_beta) * (qn_rope[g] * r_rope + qn_nope[g] * r_nope); + if (gqa == BasinGqaReduce::kMax) agg = std::max(agg, val); + else agg += val; + } + if (gqa == BasinGqaReduce::kMean) agg /= static_cast(G); + max_err = std::max(max_err, std::fabs(static_cast(gpu_scores[bidx]) - agg)); + } + } + expect_true(max_err < 1e-2, "SphereIndex Metal GPU score matches FP64 WHT-INT4 reference"); + + gpu::free_device(d_scores); + gpu::free_device(d_q); + gpu::free_device(d_v); + gpu::free_device(d_k); + } +} + +// ---- Test 3: Radix Top-K + 1-hop successor co-fetch + LRS eviction + admitted counter ---- +void test_topk_successor_eviction() { + std::printf("Test 3: Radix Top-K + 1-hop successor co-fetch + LRS eviction + bijection...\n"); + BasinKvConfig cfg; + cfg.n_layers = 1; + cfg.n_head_q = 8; + cfg.n_head_kv = 2; + cfg.head_dim = 64; + cfg.block_size = 16; + cfg.sink_blocks = 2; + cfg.sparse_blocks = 6; + cfg.local_blocks = 4; + cfg.max_seq_len = 1024; + cfg.transfer_cap = 4; + cfg.successor_cofetch = true; + + BasinKvPool pool; + pool.init(cfg); + + const int32_t seq_len = 640; + std::vector zeros(static_cast(seq_len) * cfg.n_head_kv * cfg.head_dim, 0.25f); + float *d_k = nullptr, *d_v = nullptr, *d_scores = nullptr; + check_gpu(gpu::malloc_device(&d_k, zeros.size() * sizeof(float)), "t3 dk"); + check_gpu(gpu::malloc_device(&d_v, zeros.size() * sizeof(float)), "t3 dv"); + check_gpu(gpu::malloc_device(&d_scores, static_cast(cfg.n_head_kv) * cfg.max_blocks() * sizeof(float)), "t3 ds"); + check_gpu(gpu::memcpy_sync(d_k, zeros.data(), zeros.size() * sizeof(float), gpu::kHostToDevice), "t3 h2d k"); + check_gpu(gpu::memcpy_sync(d_v, zeros.data(), zeros.size() * sizeof(float), gpu::kHostToDevice), "t3 h2d v"); + pool.append_prefill_chunk_f32(0, d_k, d_v, 0, seq_len); + check_gpu(gpu::device_synchronize(), "t3 sync"); + verify_page_table_invariants(pool, 0, "t3_after_prefill"); + + const int32_t M = cfg.max_blocks(); + std::vector scores(static_cast(cfg.n_head_kv) * M, 1.0f); + for (int32_t h = 0; h < cfg.n_head_kv; ++h) { + float* row = scores.data() + static_cast(h) * M; + row[5] = std::numeric_limits::quiet_NaN(); + row[6] = -std::numeric_limits::infinity(); + row[10] = 100.0f; + row[11] = -5.0f; // must be boosted by 1-hop successor co-fetch + row[20] = 50.0f; + row[21] = -2.0f; + row[25] = 50.0f; // tied with 20 + } + check_gpu(gpu::memcpy_sync(d_scores, scores.data(), scores.size() * sizeof(float), gpu::kHostToDevice), "t3 h2d sc"); + + pool.run_select_from_scores(0, d_scores, 2, 36, /*step=*/10, /*cap_override=*/4); + check_gpu(gpu::device_synchronize(), "t3 select1"); + verify_page_table_invariants(pool, 0, "t3_after_select1"); + const uint64_t adm1 = pool.read_admitted_count(0); + expect_true(adm1 > 0, "admitted_counter incremented on misses"); + + std::vector g2c, c2g; + pool.read_page_tables(0, g2c, c2g); + for (int32_t h = 0; h < cfg.n_head_kv; ++h) { + const int32_t* c = c2g.data() + static_cast(h) * M; + expect_true(c[10] >= cfg.sink_blocks && c[10] < cfg.local_slot_start(), "block 10 admitted to sparse"); + expect_true(c[11] >= cfg.sink_blocks && c[11] < cfg.local_slot_start(), "successor block 11 co-fetched to sparse"); + expect_true(c[5] == -1 && c[6] == -1, "NaN and -Inf blocks never admitted"); + } + + // Step 2: protect 10 & 11, admit 15 & 16 + std::fill(scores.begin(), scores.end(), 0.0f); + for (int32_t h = 0; h < cfg.n_head_kv; ++h) { + float* row = scores.data() + static_cast(h) * M; + row[10] = 80.0f; + row[15] = 90.0f; + } + check_gpu(gpu::memcpy_sync(d_scores, scores.data(), scores.size() * sizeof(float), gpu::kHostToDevice), "t3 h2d sc2"); + pool.run_select_from_scores(0, d_scores, 2, 36, /*step=*/20, /*cap_override=*/4); + check_gpu(gpu::device_synchronize(), "t3 select2"); + verify_page_table_invariants(pool, 0, "t3_after_select2"); + expect_true(pool.read_admitted_count(0) > adm1, "admitted_counter increased after second selection"); + + pool.read_page_tables(0, g2c, c2g); + for (int32_t h = 0; h < cfg.n_head_kv; ++h) { + const int32_t* c = c2g.data() + static_cast(h) * M; + expect_true(c[10] >= cfg.sink_blocks && c[10] < cfg.local_slot_start(), "block 10 protected"); + expect_true(c[11] >= cfg.sink_blocks && c[11] < cfg.local_slot_start(), "block 11 protected"); + expect_true(c[15] >= cfg.sink_blocks && c[15] < cfg.local_slot_start(), "block 15 admitted"); + expect_true(c[16] >= cfg.sink_blocks && c[16] < cfg.local_slot_start(), "successor block 16 admitted"); + } + + gpu::free_device(d_scores); + gpu::free_device(d_v); + gpu::free_device(d_k); + + // 3b: Multi-iteration Top-K & LRS eviction with sparse_blocks > 256 (s_cnt = 300, P = 512) + { + BasinKvConfig big; + big.n_layers = 1; + big.n_head_q = 4; + big.n_head_kv = 2; + big.head_dim = 64; + big.block_size = 16; + big.sink_blocks = 4; + big.sparse_blocks = 300; + big.local_blocks = 12; + big.max_seq_len = 16384; + big.transfer_cap = 16; + BasinKvPool bpool; + bpool.init(big); + const int32_t bM = big.max_blocks(); + const int32_t b_seq = 12800; // 800 blocks -> elig [4..788), n_elig = 784 > s_cnt = 300 + std::vector bz(static_cast(b_seq) * big.n_head_kv * big.head_dim, 0.1f); + float *bdk = nullptr, *bdv = nullptr, *bds = nullptr; + check_gpu(gpu::malloc_device(&bdk, bz.size() * sizeof(float)), "t3b dk"); + check_gpu(gpu::malloc_device(&bdv, bz.size() * sizeof(float)), "t3b dv"); + check_gpu(gpu::malloc_device(&bds, static_cast(big.n_head_kv) * bM * sizeof(float)), "t3b ds"); + check_gpu(gpu::memcpy_sync(bdk, bz.data(), bz.size() * sizeof(float), gpu::kHostToDevice), "t3b h2d k"); + check_gpu(gpu::memcpy_sync(bdv, bz.data(), bz.size() * sizeof(float), gpu::kHostToDevice), "t3b h2d v"); + bpool.append_prefill_chunk_f32(0, bdk, bdv, 0, b_seq); + + std::vector bsc(static_cast(big.n_head_kv) * bM, 0.5f); + for (int32_t h = 0; h < big.n_head_kv; ++h) { + float* row = bsc.data() + static_cast(h) * bM; + for (int32_t b = 4; b < 788; ++b) row[b] = static_cast((b * 37) % 100) * 0.01f; + row[100] = 200.0f; + row[101] = -10.0f; + row[350] = 150.0f; + } + check_gpu(gpu::memcpy_sync(bds, bsc.data(), bsc.size() * sizeof(float), gpu::kHostToDevice), "t3b h2d s"); + bpool.run_select_from_scores(0, bds, 4, 788, 5, 16); + check_gpu(gpu::device_synchronize(), "t3b sync"); + verify_page_table_invariants(bpool, 0, "t3b_sparse300"); + + std::vector bg2c, bc2g; + bpool.read_page_tables(0, bg2c, bc2g); + for (int32_t h = 0; h < big.n_head_kv; ++h) { + const int32_t* c = bc2g.data() + static_cast(h) * bM; + expect_true(c[100] >= big.sink_blocks && c[100] < big.local_slot_start(), "s_cnt=300: block 100 admitted"); + expect_true(c[101] >= big.sink_blocks && c[101] < big.local_slot_start(), "s_cnt=300: successor 101 co-fetched"); + expect_true(c[350] >= big.sink_blocks && c[350] < big.local_slot_start(), "s_cnt=300: block 350 admitted"); + } + gpu::free_device(bds); + gpu::free_device(bdv); + gpu::free_device(bdk); + } +} + +// ---- Test 4: Short-context (<= resident) 100% BIT-IDENTICAL hot slab & attend() vs dense FP16 ---- +void test_short_context_bit_identical() { + std::printf("Test 4: Short-context 100%% bit-identical parity vs dense FP16 store_f16 + attend()...\n"); + BasinKvConfig cfg; + cfg.n_layers = 1; + cfg.n_head_q = 16; + cfg.n_head_kv = 2; + cfg.head_dim = 256; + cfg.block_size = 16; + cfg.sink_blocks = 2; + cfg.sparse_blocks = 10; + cfg.local_blocks = 4; // W = 16, resident = 256 + cfg.max_seq_len = 1024; + + BasinKvPool pool; + pool.init(cfg); + + const int32_t Hq = cfg.n_head_q, Hk = cfg.n_head_kv, D = cfg.head_dim; + const int32_t kv_stride = Hk * D; + const int32_t prefill_n = 200; + const int32_t decode_n = 56; // total = 256 == resident + const int32_t total_n = prefill_n + decode_n; + + std::mt19937 rng(4242); + std::normal_distribution nd(0.0f, 1.0f); + std::vector h_k(static_cast(total_n) * kv_stride); + std::vector h_v(static_cast(total_n) * kv_stride); + std::vector h_q(static_cast(Hq) * D); + for (float& x : h_k) x = nd(rng); + for (float& x : h_v) x = nd(rng); + for (float& x : h_q) x = nd(rng); + + float *d_k = nullptr, *d_v = nullptr, *d_q = nullptr, *d_out_dense = nullptr, *d_out_basin = nullptr; + uint16_t *d_dense_k = nullptr, *d_dense_v = nullptr; + check_gpu(gpu::malloc_device(&d_k, h_k.size() * sizeof(float)), "t4 dk"); + check_gpu(gpu::malloc_device(&d_v, h_v.size() * sizeof(float)), "t4 dv"); + check_gpu(gpu::malloc_device(&d_q, h_q.size() * sizeof(float)), "t4 dq"); + check_gpu(gpu::malloc_device(&d_out_dense, h_q.size() * sizeof(float)), "t4 od"); + check_gpu(gpu::malloc_device(&d_out_basin, h_q.size() * sizeof(float)), "t4 ob"); + check_gpu(gpu::malloc_device(&d_dense_k, h_k.size() * sizeof(uint16_t)), "t4 ddk"); + check_gpu(gpu::malloc_device(&d_dense_v, h_v.size() * sizeof(uint16_t)), "t4 ddv"); + check_gpu(gpu::memcpy_sync(d_k, h_k.data(), h_k.size() * sizeof(float), gpu::kHostToDevice), "t4 h2d k"); + check_gpu(gpu::memcpy_sync(d_v, h_v.data(), h_v.size() * sizeof(float), gpu::kHostToDevice), "t4 h2d v"); + check_gpu(gpu::memcpy_sync(d_q, h_q.data(), h_q.size() * sizeof(float), gpu::kHostToDevice), "t4 h2d q"); + + store_f16(d_k, d_dense_k, kv_stride, 0, total_n, nullptr); + store_f16(d_v, d_dense_v, kv_stride, 0, total_n, nullptr); + + pool.append_prefill_chunk_f32(0, d_k, d_v, 0, prefill_n); + for (int32_t t = 0; t < decode_n; ++t) { + const size_t off = static_cast(prefill_n + t) * kv_stride; + pool.append_decode_token_f32(0, d_k + off, d_v + off, prefill_n + t); + pool.submit_lookahead_f32(0, d_q); + } + + const float scale = 1.0f / std::sqrt(static_cast(D)); + attend(d_q, d_dense_k, d_dense_v, total_n - 1, 1, nullptr, 1, d_out_dense, D, Hq, Hk, scale, nullptr); + attend(d_q, pool.hot_k(0), pool.hot_v(0), pool.effective_pos(total_n - 1), 1, nullptr, 1, d_out_basin, D, Hq, Hk, + scale, nullptr); + check_gpu(gpu::device_synchronize(), "t4 sync"); + + std::vector dense_k(h_k.size()), basin_k(h_k.size()), dense_v(h_v.size()), basin_v(h_v.size()); + check_gpu(gpu::memcpy_sync(dense_k.data(), d_dense_k, dense_k.size() * sizeof(uint16_t), gpu::kDeviceToHost), "t4 d2h dk"); + check_gpu(gpu::memcpy_sync(basin_k.data(), pool.hot_k(0), basin_k.size() * sizeof(uint16_t), gpu::kDeviceToHost), "t4 d2h bk"); + check_gpu(gpu::memcpy_sync(dense_v.data(), d_dense_v, dense_v.size() * sizeof(uint16_t), gpu::kDeviceToHost), "t4 d2h dv"); + check_gpu(gpu::memcpy_sync(basin_v.data(), pool.hot_v(0), basin_v.size() * sizeof(uint16_t), gpu::kDeviceToHost), "t4 d2h bv"); + expect_true(dense_k == basin_k, "short-context hot_k is 100% bit-identical to store_f16"); + expect_true(dense_v == basin_v, "short-context hot_v is 100% bit-identical to store_f16"); + + std::vector od(h_q.size()), ob(h_q.size()); + check_gpu(gpu::memcpy_sync(od.data(), d_out_dense, od.size() * sizeof(uint32_t), gpu::kDeviceToHost), "t4 d2h od"); + check_gpu(gpu::memcpy_sync(ob.data(), d_out_basin, ob.size() * sizeof(uint32_t), gpu::kDeviceToHost), "t4 d2h ob"); + expect_true(od == ob, "short-context attend() output is 100% bit-identical to dense FP16"); + + gpu::free_device(d_dense_v); + gpu::free_device(d_dense_k); + gpu::free_device(d_out_basin); + gpu::free_device(d_out_dense); + gpu::free_device(d_q); + gpu::free_device(d_v); + gpu::free_device(d_k); +} + +// ---- Test 5: Long-context steady state (seq_len = 4096 > 2048 resident, UVA & staged fallback) ---- +void test_long_context_4096(BasinIndexMode idx_mode, BasinHostQuant hq_mode, bool disable_uva) { + std::printf("Test 5: Long-context 4096 (> 2048 resident) steady-state gather (idx=%s, host=%s, uva=%s)...\n", + basinkv_index_mode_name(idx_mode), basinkv_host_quant_name(hq_mode), disable_uva ? "off" : "on"); + BasinKvConfig cfg; + cfg.n_layers = 1; + cfg.n_head_q = 16; + cfg.n_head_kv = 2; + cfg.head_dim = 256; + cfg.rope_dim = 64; + cfg.block_size = 16; + basinkv_partition_window(2048, cfg.block_size, cfg.sink_blocks, cfg.sparse_blocks, cfg.local_blocks); + cfg.max_seq_len = 4608; + cfg.transfer_cap = 8; + cfg.index_mode = idx_mode; + cfg.host_quant = hq_mode; + cfg.disable_uva = disable_uva; + + BasinKvPool pool; + pool.init(cfg); + if (disable_uva) expect_true(!pool.is_using_uva(), "disable_uva forces staged fallback"); + else expect_true(pool.is_using_uva(), "UMA zero-copy UVA active"); + + const int32_t Hq = cfg.n_head_q, Hk = cfg.n_head_kv, D = cfg.head_dim; + const int32_t kv_stride = Hk * D; + const int32_t prefill_n = 4050; // multi-chunk prefill with non-aligned chunk boundary + const int32_t decode_n = 46; // reaches seq_len = 4096 (> 2048 resident), crosses 3 block boundaries + const int32_t total_n = prefill_n + decode_n; + + std::mt19937 rng(9900 + static_cast(idx_mode) * 10 + static_cast(hq_mode) * 3 + (disable_uva ? 1 : 0)); + std::normal_distribution nd(0.0f, 0.7f); + std::vector h_k(static_cast(total_n) * kv_stride); + std::vector h_v(static_cast(total_n) * kv_stride); + std::vector h_q(static_cast(Hq) * D); + for (float& x : h_k) x = nd(rng); + for (float& x : h_v) x = nd(rng); + for (float& x : h_q) x = nd(rng); + + // Plant a cold needle at block 40 (tokens 640..655) with known distinct V values + const int32_t needle_blk = 40; + for (int32_t t = 0; t < cfg.block_size; ++t) { + for (int32_t h = 0; h < Hk; ++h) { + for (int32_t d = 0; d < D; ++d) { + const size_t idx = (static_cast(needle_blk * cfg.block_size + t) * Hk + h) * D + d; + h_k[idx] = 4.0f * h_q[static_cast(h * (Hq / Hk)) * D + d]; + h_v[idx] = (d % 2 == 0) ? 1.25f : -0.75f; + } + } + } + + float *d_k = nullptr, *d_v = nullptr, *d_q = nullptr; + uint16_t *d_mk = nullptr, *d_mv = nullptr; + check_gpu(gpu::malloc_device(&d_k, h_k.size() * sizeof(float)), "t5 dk"); + check_gpu(gpu::malloc_device(&d_v, h_v.size() * sizeof(float)), "t5 dv"); + check_gpu(gpu::malloc_device(&d_q, h_q.size() * sizeof(float)), "t5 dq"); + check_gpu(gpu::malloc_device(&d_mk, static_cast(256) * kv_stride * sizeof(uint16_t)), "t5 dmk"); + check_gpu(gpu::malloc_device(&d_mv, static_cast(256) * kv_stride * sizeof(uint16_t)), "t5 dmv"); + check_gpu(gpu::memcpy_sync(d_k, h_k.data(), h_k.size() * sizeof(float), gpu::kHostToDevice), "t5 h2d k"); + check_gpu(gpu::memcpy_sync(d_v, h_v.data(), h_v.size() * sizeof(float), gpu::kHostToDevice), "t5 h2d v"); + check_gpu(gpu::memcpy_sync(d_q, h_q.data(), h_q.size() * sizeof(float), gpu::kHostToDevice), "t5 h2d q"); + + // Multi-chunk prefill crossing non-block boundaries (1500 + 1500 + 1050 = 4050) + pool.append_prefill_chunk_f32(0, d_k, d_v, 0, 1500); + pool.append_prefill_chunk_f32(0, d_k + static_cast(1500) * kv_stride, + d_v + static_cast(1500) * kv_stride, 1500, 1500); + pool.append_prefill_chunk_f32(0, d_k + static_cast(3000) * kv_stride, + d_v + static_cast(3000) * kv_stride, 3000, 1050); + verify_page_table_invariants(pool, 0, "t5_after_prefill_4050"); + + // Materialize a slice spanning flushed + open-tail rows (3900..4050) + pool.materialize_range_f16(0, 3900, 150, d_mk, d_mv); + check_gpu(gpu::device_synchronize(), "t5 mat sync"); + std::vector mk(static_cast(150) * kv_stride); + check_gpu(gpu::memcpy_sync(mk.data(), d_mk, mk.size() * sizeof(uint16_t), gpu::kDeviceToHost), "t5 d2h mk"); + const float mat_tol = (hq_mode == BasinHostQuant::kWhtInt4) ? 0.60f : 0.04f; + float max_mat_err = 0.0f; + for (size_t i = 0; i < mk.size(); ++i) { + max_mat_err = std::max(max_mat_err, + std::fabs(f16_bits_to_f32(mk[i]) - h_k[static_cast(3900) * kv_stride + i])); + } + expect_true(max_mat_err < mat_tol, "materialize_range_f16 accurate at 4050 tokens"); + + pool.submit_lookahead_f32(0, d_q); + for (int32_t t = 0; t < decode_n; ++t) { + const size_t off = static_cast(prefill_n + t) * kv_stride; + pool.append_decode_token_f32(0, d_k + off, d_v + off, prefill_n + t); + pool.submit_lookahead_f32(0, d_q); + } + pool.wait_layer_ready(0); + pool.sync_background(); + expect_true(pool.seq_len(0) == 4096, "seq_len reached 4096"); + verify_page_table_invariants(pool, 0, "t5_after_decode_4096"); + + std::vector g2c, c2g; + pool.read_page_tables(0, g2c, c2g); + std::vector hot_v(static_cast(cfg.resident_tokens()) * kv_stride); + check_gpu(gpu::memcpy_sync(hot_v.data(), pool.hot_v(0), hot_v.size() * sizeof(uint16_t), gpu::kDeviceToHost), "t5 hv"); + + const float v_max_tol = (hq_mode == BasinHostQuant::kWhtInt4) ? 0.55f : 0.03f; + const float v_rmse_tol = (hq_mode == BasinHostQuant::kWhtInt4) ? 0.18f : 0.01f; + for (int32_t h = 0; h < Hk; ++h) { + const int32_t s_needle = c2g[static_cast(h) * cfg.max_blocks() + needle_blk]; + const int32_t s_succ = c2g[static_cast(h) * cfg.max_blocks() + needle_blk + 1]; + expect_true(s_needle >= cfg.sink_blocks && s_needle < cfg.local_slot_start(), + "cold needle block 40 gathered to GPU hot slab"); + expect_true(s_succ >= cfg.sink_blocks && s_succ < cfg.local_slot_start(), + "needle successor block 41 co-fetched to GPU hot slab"); + if (s_needle >= 0) { + float max_v_err = 0.0f; + double sq_err = 0.0, dot = 0.0, n_got = 0.0, n_ref = 0.0; + const int64_t total_v = static_cast(cfg.block_size) * D; + for (int32_t t = 0; t < cfg.block_size; ++t) { + for (int32_t d = 0; d < D; ++d) { + const size_t off = (static_cast(s_needle * cfg.block_size + t) * Hk + h) * D + d; + float got = f16_bits_to_f32(hot_v[off]); + float ref = (d % 2 == 0) ? 1.25f : -0.75f; + float diff = got - ref; + max_v_err = std::max(max_v_err, std::fabs(diff)); + sq_err += static_cast(diff) * diff; + dot += static_cast(got) * ref; + n_got += static_cast(got) * got; + n_ref += static_cast(ref) * ref; + } + } + const float rmse = static_cast(std::sqrt(sq_err / static_cast(total_v))); + const float cos_sim = static_cast(dot / (std::sqrt(n_got) * std::sqrt(n_ref))); + expect_true(max_v_err < v_max_tol && rmse < v_rmse_tol && cos_sim > 0.985f, + "gathered needle V matches original within quant tolerance"); + } + } + + gpu::free_device(d_mv); + gpu::free_device(d_mk); + gpu::free_device(d_q); + gpu::free_device(d_v); + gpu::free_device(d_k); +} + +// ---- Test 6: Metal Graph Capture & Multi-Step Replay Across Linear->Sparse & Block Boundaries ---- +void test_metal_graph_replay(BasinIndexMode idx_mode, BasinHostQuant hq_mode, bool use_d_pos_ptr = true) { + std::printf("Test 6: Metal Graph capture & replay across resident + block boundaries (idx=%s, host=%s, d_pos=%s)...\n", + basinkv_index_mode_name(idx_mode), basinkv_host_quant_name(hq_mode), use_d_pos_ptr ? "ext" : "internal"); + BasinKvConfig cfg; + cfg.n_layers = 1; + cfg.n_head_q = 16; + cfg.n_head_kv = 2; + cfg.head_dim = 256; + cfg.rope_dim = 64; + cfg.block_size = 16; + cfg.sink_blocks = 2; + cfg.sparse_blocks = 10; + cfg.local_blocks = 4; // W = 16 (256 hot tokens) + cfg.max_seq_len = 1024; + cfg.transfer_cap = 4; + cfg.index_mode = idx_mode; + cfg.host_quant = hq_mode; + + BasinKvPool eager_pool, graph_pool; + eager_pool.init(cfg); + graph_pool.init(cfg); + expect_true(graph_pool.is_using_uva(), "graph_pool uses UMA zero-copy UVA"); + + const int32_t Hq = cfg.n_head_q, Hk = cfg.n_head_kv, D = cfg.head_dim; + const int32_t kv_stride = Hk * D; + const int32_t prefill_n = 240; // starts BEFORE resident=256 + const int32_t steps = 64; // pos=240..303: crosses 256 (linear->sparse!) + 272 + 288 + + std::mt19937 rng(202604 + static_cast(idx_mode) * 17); + std::normal_distribution nd(0.0f, 0.8f); + std::vector h_k(static_cast(prefill_n + steps) * kv_stride); + std::vector h_v(static_cast(prefill_n + steps) * kv_stride); + std::vector h_q(static_cast(steps) * Hq * D); + for (float& x : h_k) x = nd(rng); + for (float& x : h_v) x = nd(rng); + for (float& x : h_q) x = nd(rng); + + gpu::Stream st = nullptr; + check_gpu(gpu::stream_create(&st, gpu::kStreamNonBlocking), "t6 stream"); + + float *d_k = nullptr, *d_v = nullptr, *d_q = nullptr, *d_cur_k = nullptr, *d_cur_v = nullptr, *d_cur_q = nullptr; + float *d_out_e = nullptr, *d_out_g = nullptr; + long long* d_pos = nullptr; + check_gpu(gpu::malloc_device(&d_k, h_k.size() * sizeof(float)), "t6 dk"); + check_gpu(gpu::malloc_device(&d_v, h_v.size() * sizeof(float)), "t6 dv"); + check_gpu(gpu::malloc_device(&d_q, h_q.size() * sizeof(float)), "t6 dq"); + check_gpu(gpu::malloc_device(&d_cur_k, kv_stride * sizeof(float)), "t6 dck"); + check_gpu(gpu::malloc_device(&d_cur_v, kv_stride * sizeof(float)), "t6 dcv"); + check_gpu(gpu::malloc_device(&d_cur_q, static_cast(Hq) * D * sizeof(float)), "t6 dcq"); + check_gpu(gpu::malloc_device(&d_out_e, static_cast(Hq) * D * sizeof(float)), "t6 oe"); + check_gpu(gpu::malloc_device(&d_out_g, static_cast(Hq) * D * sizeof(float)), "t6 og"); + check_gpu(gpu::malloc_device(&d_pos, sizeof(long long)), "t6 dpos"); + + check_gpu(gpu::memcpy_sync(d_k, h_k.data(), h_k.size() * sizeof(float), gpu::kHostToDevice), "t6 h2d k"); + check_gpu(gpu::memcpy_sync(d_v, h_v.data(), h_v.size() * sizeof(float), gpu::kHostToDevice), "t6 h2d v"); + check_gpu(gpu::memcpy_sync(d_q, h_q.data(), h_q.size() * sizeof(float), gpu::kHostToDevice), "t6 h2d q"); + + eager_pool.append_prefill_chunk_f32(0, d_k, d_v, 0, prefill_n, st); + graph_pool.append_prefill_chunk_f32(0, d_k, d_v, 0, prefill_n, st); + check_gpu(gpu::stream_synchronize(st), "t6 prefill sync"); + + // Capture ONE fixed Metal graph for single-token BasinKV decode + attend + lookahead! + const float scale = 1.0f / std::sqrt(static_cast(D)); + graph_pool.join_all_pending(st); + gpu::Graph graph = nullptr; + gpu::GraphExec exec = nullptr; + check_gpu(gpu::begin_capture(st), "t6 begin capture"); + graph_pool.append_decode_token_graph_f32(0, d_cur_k, d_cur_v, use_d_pos_ptr ? d_pos : nullptr, st); + attend(d_cur_q, graph_pool.hot_k(0), graph_pool.hot_v(0), 0, 1, nullptr, 1, d_out_g, D, Hq, Hk, scale, st, + 0, 0, false, graph_pool.d_eff_pos(0), cfg.resident_tokens()); + graph_pool.submit_lookahead_graph_f32(0, d_cur_q, st); + graph_pool.join_bg_in_capture(st); + check_gpu(gpu::end_capture(st, &graph), "t6 end capture"); + check_gpu(gpu::graph_instantiate(&exec, graph, 0), "t6 instantiate"); + gpu::graph_destroy(graph); + + float max_diff = 0.0f; + bool eff_pos_ok = true; + std::vector oe(static_cast(Hq) * D), og(static_cast(Hq) * D); + for (int32_t s = 0; s < steps; ++s) { + const long long pos = prefill_n + s; + const size_t kv_off = static_cast(pos) * kv_stride; + const size_t q_off = static_cast(s) * Hq * D; + + // Eager step + eager_pool.append_decode_token_f32(0, d_k + kv_off, d_v + kv_off, static_cast(pos), st); + attend(d_q + q_off, eager_pool.hot_k(0), eager_pool.hot_v(0), eager_pool.effective_pos(pos), 1, + nullptr, 1, d_out_e, D, Hq, Hk, scale, st); + eager_pool.submit_lookahead_f32(0, d_q + q_off, st); + + // Graph replay step (same graph across all 64 steps) + check_gpu(gpu::memcpy_async(d_pos, &pos, sizeof(long long), gpu::kHostToDevice, st), "t6 pos"); + check_gpu(gpu::memcpy_async(d_cur_k, d_k + kv_off, kv_stride * sizeof(float), gpu::kDeviceToDevice, st), "t6 ck"); + check_gpu(gpu::memcpy_async(d_cur_v, d_v + kv_off, kv_stride * sizeof(float), gpu::kDeviceToDevice, st), "t6 cv"); + check_gpu(gpu::memcpy_async(d_cur_q, d_q + q_off, static_cast(Hq) * D * sizeof(float), gpu::kDeviceToDevice, st), "t6 cq"); + graph_pool.mark_device_state_dirty(); + check_gpu(gpu::graph_launch(exec, st), "t6 launch"); + + long long got_eff = -1; + check_gpu(gpu::memcpy_async(&got_eff, graph_pool.d_eff_pos(0), sizeof(long long), gpu::kDeviceToHost, st), "t6 eff"); + check_gpu(gpu::memcpy_async(oe.data(), d_out_e, oe.size() * sizeof(float), gpu::kDeviceToHost, st), "t6 d2h oe"); + check_gpu(gpu::memcpy_async(og.data(), d_out_g, og.size() * sizeof(float), gpu::kDeviceToHost, st), "t6 d2h og"); + check_gpu(gpu::stream_synchronize(st), "t6 step sync"); + + if (got_eff != eager_pool.effective_pos(pos)) eff_pos_ok = false; + for (size_t i = 0; i < oe.size(); ++i) max_diff = std::max(max_diff, std::fabs(oe[i] - og[i])); + } + expect_true(eff_pos_ok, "d_eff_pos updated accurately on every graph replay step"); + expect_true(max_diff < 1e-4f, "Metal graph replay matches eager decode across linear->sparse & block boundaries"); + + graph_pool.sync_host_state(st); + expect_true(graph_pool.seq_len(0) == prefill_n + steps, "graph_pool seq_len synced accurately"); + verify_page_table_invariants(graph_pool, 0, "t6_graph_final"); + verify_page_table_invariants(eager_pool, 0, "t6_eager_final"); + + std::vector eg2c, ec2g, gg2c, gc2g; + eager_pool.read_page_tables(0, eg2c, ec2g, st); + graph_pool.read_page_tables(0, gg2c, gc2g, st); + expect_true(eg2c == gg2c && ec2g == gc2g, "graph replay page tables match eager page tables exactly"); + + gpu::graph_exec_destroy(exec); + gpu::stream_destroy(st); + gpu::free_device(d_pos); + gpu::free_device(d_out_g); + gpu::free_device(d_out_e); + gpu::free_device(d_cur_q); + gpu::free_device(d_cur_v); + gpu::free_device(d_cur_k); + gpu::free_device(d_q); + gpu::free_device(d_v); + gpu::free_device(d_k); +} + +// ---- Test 7: Materialize, Truncate (short, intra-tail, cross-block), Reset, Export/Import FP16 ---- +void test_truncate_materialize_export_import() { + std::printf("Test 7: Materialize, truncate, reset, and export/import FP16 rows...\n"); + BasinKvConfig cfg; + cfg.n_layers = 2; + cfg.n_head_q = 8; + cfg.n_head_kv = 2; + cfg.head_dim = 128; + cfg.block_size = 16; + cfg.sink_blocks = 2; + cfg.sparse_blocks = 10; + cfg.local_blocks = 4; // W = 16 (256 hot tokens) + cfg.max_seq_len = 1024; + + BasinKvPool pool; + pool.init(cfg); + + const int32_t Hk = cfg.n_head_kv, D = cfg.head_dim; + const int32_t kv_stride = Hk * D; + const int32_t total_n = 407; // 25 full blocks + 7 open-tail rows + + std::mt19937 rng(55511); + std::uniform_real_distribution ud(-2.0f, 2.0f); + std::vector h_k(static_cast(total_n) * kv_stride); + std::vector h_v(static_cast(total_n) * kv_stride); + for (size_t i = 0; i < h_k.size(); ++i) { + h_k[i] = ud(rng); + h_v[i] = ud(rng); + } + + float *d_k = nullptr, *d_v = nullptr; + uint16_t *d_mk = nullptr, *d_mv = nullptr; + check_gpu(gpu::malloc_device(&d_k, h_k.size() * sizeof(float)), "t7 dk"); + check_gpu(gpu::malloc_device(&d_v, h_v.size() * sizeof(float)), "t7 dv"); + check_gpu(gpu::malloc_device(&d_mk, h_k.size() * sizeof(uint16_t)), "t7 dmk"); + check_gpu(gpu::malloc_device(&d_mv, h_v.size() * sizeof(uint16_t)), "t7 dmv"); + check_gpu(gpu::memcpy_sync(d_k, h_k.data(), h_k.size() * sizeof(float), gpu::kHostToDevice), "t7 h2d k"); + check_gpu(gpu::memcpy_sync(d_v, h_v.data(), h_v.size() * sizeof(float), gpu::kHostToDevice), "t7 h2d v"); + + // 7a: Short-context lossless truncate_layer check + pool.append_prefill_chunk_f32(0, d_k, d_v, 0, 120); + pool.truncate_layer(0, 75); + expect_true(pool.seq_len(0) == 75, "short-context truncate_layer sets seq_len=75"); + pool.reset_layer(0); + expect_true(pool.seq_len(0) == 0, "reset_layer clears seq_len"); + + // 7b: Long-context prefill + materialize + intra-tail truncate + cross-block truncate + for (int32_t l = 0; l < cfg.n_layers; ++l) pool.append_prefill_chunk_f32(l, d_k, d_v, 0, total_n); + pool.materialize_range_f16(0, 0, total_n, d_mk, d_mv); + check_gpu(gpu::device_synchronize(), "t7 mat sync"); + + std::vector mk(h_k.size()), mv(h_v.size()); + check_gpu(gpu::memcpy_sync(mk.data(), d_mk, mk.size() * sizeof(uint16_t), gpu::kDeviceToHost), "t7 d2h mk"); + check_gpu(gpu::memcpy_sync(mv.data(), d_mv, mv.size() * sizeof(uint16_t), gpu::kDeviceToHost), "t7 d2h mv"); + float max_err = 0.0f; + for (size_t i = 0; i < h_k.size(); ++i) { + max_err = std::max(max_err, std::fabs(f16_bits_to_f32(mk[i]) - h_k[i])); + max_err = std::max(max_err, std::fabs(f16_bits_to_f32(mv[i]) - h_v[i])); + } + expect_true(max_err < 0.03f, "materialize_range_f16 reconstructs flushed + open-tail rows accurately"); + + // Intra-tail rollback (407 -> 403, same block 25) + pool.truncate_layer(0, 403); + expect_true(pool.seq_len(0) == 403, "intra-tail truncate sets seq_len=403"); + verify_page_table_invariants(pool, 0, "t7_after_intra_tail_truncate"); + + // Cross-block rollback (403 -> 305) + pool.truncate_all(305); + expect_true(pool.seq_len(0) == 305 && pool.seq_len(1) == 305, "truncate_all sets seq_len=305"); + verify_page_table_invariants(pool, 0, "t7_after_truncate"); + for (int32_t t = 305; t < 330; ++t) { + for (int32_t l = 0; l < cfg.n_layers; ++l) + pool.append_decode_token_f32(l, d_k + static_cast(t) * kv_stride, + d_v + static_cast(t) * kv_stride, t); + } + verify_page_table_invariants(pool, 0, "t7_after_reappend"); + + // Export 330 rows -> reset -> import 330 rows -> verify materialized parity + std::vector exp_k(static_cast(330) * kv_stride); + std::vector exp_v(static_cast(330) * kv_stride); + pool.export_rows_f16(0, 0, 330, exp_k.data(), exp_v.data()); + pool.reset_all(); + expect_true(pool.seq_len(0) == 0, "reset_all clears seq_len"); + pool.import_rows_f16(0, exp_k.data(), exp_v.data(), 0, 330); + expect_true(pool.seq_len(0) == 330, "import_rows_f16 restores seq_len"); + verify_page_table_invariants(pool, 0, "t7_after_import"); + + pool.materialize_range_f16(0, 0, 330, d_mk, d_mv); + check_gpu(gpu::device_synchronize(), "t7 mat2 sync"); + check_gpu(gpu::memcpy_sync(mk.data(), d_mk, static_cast(330) * kv_stride * sizeof(uint16_t), gpu::kDeviceToHost), "t7 d2h mk2"); + float imp_err = 0.0f; + for (size_t i = 0; i < static_cast(330) * kv_stride; ++i) { + imp_err = std::max(imp_err, std::fabs(f16_bits_to_f32(mk[i]) - h_k[i])); + } + expect_true(imp_err < 0.05f, "export -> reset -> import preserves K values accurately"); + + gpu::free_device(d_mv); + gpu::free_device(d_mk); + gpu::free_device(d_v); + gpu::free_device(d_k); +} + +// ---- Test 8: Chunked attend() & attend_batch() with ml_out + merge_attn_piece() ---- +void test_chunked_attention_ml_out() { + std::printf("Test 8: Chunked attend() & attend_batch() with ml_out + merge_attn_piece() (FP16 & Q8_0, D=128 & D=256)...\n"); + struct Shape { int Hq, Hk, D; }; + const Shape shapes[] = { + {8, 2, 128}, + {16, 2, 256}, + }; + constexpr int kTotalRows = 768; + constexpr int kCuts[] = {0, 256, 512, kTotalRows}; + + for (const Shape& sh : shapes) { + const int Hq = sh.Hq, Hk = sh.Hk, D = sh.D; + const float scale = 1.0f / std::sqrt(static_cast(D)); + const size_t kv_row = static_cast(Hk) * D; + const size_t q_row = static_cast(Hq) * D; + const size_t s_row = kv_row / 32; + const int max_n = 128; + + std::mt19937 rng(8800u + static_cast(D)); + std::normal_distribution nd(0.0f, 1.0f); + std::vector h_k(static_cast(kTotalRows) * kv_row); + std::vector h_v(static_cast(kTotalRows) * kv_row); + std::vector h_q(static_cast(max_n) * q_row); + for (float& x : h_k) x = nd(rng); + for (float& x : h_v) x = nd(rng); + for (float& x : h_q) x = 2.0f * nd(rng); + + float *d_kf = nullptr, *d_vf = nullptr, *d_q = nullptr; + uint16_t *d_k16 = nullptr, *d_v16 = nullptr; + int8_t *d_kc = nullptr, *d_vc = nullptr; + uint16_t *d_ks = nullptr, *d_vs = nullptr; + float *d_ref = nullptr, *d_acc = nullptr, *d_piece = nullptr; + float *d_acc_ml = nullptr, *d_piece_ml = nullptr; + + check_gpu(gpu::malloc_device(&d_kf, h_k.size() * sizeof(float)), "t8 dkf"); + check_gpu(gpu::malloc_device(&d_vf, h_v.size() * sizeof(float)), "t8 dvf"); + check_gpu(gpu::malloc_device(&d_q, h_q.size() * sizeof(float)), "t8 dq"); + check_gpu(gpu::malloc_device(&d_k16, h_k.size() * sizeof(uint16_t)), "t8 dk16"); + check_gpu(gpu::malloc_device(&d_v16, h_v.size() * sizeof(uint16_t)), "t8 dv16"); + check_gpu(gpu::malloc_device(&d_kc, h_k.size() * sizeof(int8_t)), "t8 dkc"); + check_gpu(gpu::malloc_device(&d_vc, h_v.size() * sizeof(int8_t)), "t8 dvc"); + check_gpu(gpu::malloc_device(&d_ks, static_cast(kTotalRows) * s_row * sizeof(uint16_t)), "t8 dks"); + check_gpu(gpu::malloc_device(&d_vs, static_cast(kTotalRows) * s_row * sizeof(uint16_t)), "t8 dvs"); + check_gpu(gpu::malloc_device(&d_ref, static_cast(max_n) * q_row * sizeof(float)), "t8 ref"); + check_gpu(gpu::malloc_device(&d_acc, static_cast(max_n) * q_row * sizeof(float)), "t8 acc"); + check_gpu(gpu::malloc_device(&d_piece, static_cast(max_n) * q_row * sizeof(float)), "t8 piece"); + check_gpu(gpu::malloc_device(&d_acc_ml, static_cast(max_n) * Hq * 2 * sizeof(float)), "t8 acc_ml"); + check_gpu(gpu::malloc_device(&d_piece_ml, static_cast(max_n) * Hq * 2 * sizeof(float)), "t8 piece_ml"); + + check_gpu(gpu::memcpy_sync(d_kf, h_k.data(), h_k.size() * sizeof(float), gpu::kHostToDevice), "t8 h2d k"); + check_gpu(gpu::memcpy_sync(d_vf, h_v.data(), h_v.size() * sizeof(float), gpu::kHostToDevice), "t8 h2d v"); + check_gpu(gpu::memcpy_sync(d_q, h_q.data(), h_q.size() * sizeof(float), gpu::kHostToDevice), "t8 h2d q"); + + store_f16(d_kf, d_k16, static_cast(kv_row), 0, kTotalRows, nullptr); + store_f16(d_vf, d_v16, static_cast(kv_row), 0, kTotalRows, nullptr); + store_q8(d_kf, d_kc, d_ks, static_cast(kv_row), 0, kTotalRows, nullptr); + store_q8(d_vf, d_vc, d_vs, static_cast(kv_row), 0, kTotalRows, nullptr); + + for (bool use_q8 : {false, true}) { + auto run_one = [&](bool use_batch, const float* q_ptr, int r0, int64_t pos, int n, bool whole, + float* out_ptr, float* ml_ptr) { + const uint16_t* k16 = use_q8 ? nullptr : (d_k16 + static_cast(r0) * kv_row); + const uint16_t* v16 = use_q8 ? nullptr : (d_v16 + static_cast(r0) * kv_row); + const Kvq8 kq = use_q8 ? Kvq8{d_kc + static_cast(r0) * kv_row, + d_ks + static_cast(r0) * s_row} : Kvq8{}; + const Kvq8 vq = use_q8 ? Kvq8{d_vc + static_cast(r0) * kv_row, + d_vs + static_cast(r0) * s_row} : Kvq8{}; + if (use_batch) { + attend_batch(nullptr, q_ptr, k16, v16, pos, n, nullptr, 0, nullptr, out_ptr, + D, Hq, Hk, scale, nullptr, 0, 0, whole, kq, vq, + nullptr, nullptr, 0, nullptr, ml_ptr); + } else { + attend(q_ptr, k16, v16, pos, n, nullptr, n, out_ptr, + D, Hq, Hk, scale, nullptr, 0, 0, whole, nullptr, 0, 0, + kq, vq, nullptr, 0, ml_ptr); + } + }; + + // (a) Split attend() (n=8 < 32 -> poly_attention + poly_attention_join) + // (b) Non-split attend() (n=40 >= 32 -> poly_attention) + // (c) Flash attend_batch() (n=40, optimize=true -> poly_flash_g_*) + // (d) Flash attend_batch() spanning chunk boundary (n=128 at pos=448 -> [448..576), optimize=true) + // (e) Non-flash attend_batch() fallback (n=40, optimize=false -> attend(..., ml_out)) + struct Case { bool batch; bool opt; int n; int64_t pos; const char* tag; }; + const Case cases[] = { + {false, false, 8, kTotalRows - 8, "attend_split"}, + {false, false, 40, kTotalRows - 40, "attend_nonsplit"}, + {true, true, 40, kTotalRows - 40, "attend_batch_flash"}, + {true, true, 128, 448, "attend_batch_flash_span"}, + {true, false, 40, kTotalRows - 40, "attend_batch_fallback"}, + }; + + const bool prev_opt = gpu::metal::optimize(); + for (const Case& c : cases) { + gpu::metal::set_optimize(c.opt); + const size_t n_vals = static_cast(c.n) * q_row; + run_one(c.batch, d_q, 0, c.pos, c.n, false, d_ref, nullptr); + + const int64_t total = c.pos + c.n; + for (int p = 0; p < 3; ++p) { + const int r0 = kCuts[p]; + if (r0 >= total) break; + const int m = static_cast(std::min(total - r0, kCuts[p + 1] - r0)); + const bool first_piece = (p == 0); + const int t0 = static_cast(std::clamp(r0 - c.pos, 0, c.n)); + const int t1 = static_cast(std::clamp(r0 + m - c.pos, 0, c.n)); + const int n_causal = t1 - t0; + const int n_full = c.n - t1; + if (n_causal > 0) { + float* dst_o = first_piece ? (d_acc + static_cast(t0) * q_row) : d_piece; + float* dst_ml = first_piece ? (d_acc_ml + 2 * static_cast(t0) * Hq) : d_piece_ml; + run_one(c.batch, d_q + static_cast(t0) * q_row, r0, (c.pos + t0) - r0, + n_causal, false, dst_o, dst_ml); + if (!first_piece) { + merge_attn_piece(d_acc + static_cast(t0) * q_row, + d_acc_ml + 2 * static_cast(t0) * Hq, + d_piece, d_piece_ml, n_causal, Hq, D, nullptr); + } + } + if (n_full > 0) { + float* dst_o = first_piece ? (d_acc + static_cast(t1) * q_row) : d_piece; + float* dst_ml = first_piece ? (d_acc_ml + 2 * static_cast(t1) * Hq) : d_piece_ml; + run_one(c.batch, d_q + static_cast(t1) * q_row, r0, + static_cast(m) - n_full, n_full, true, dst_o, dst_ml); + if (!first_piece) { + merge_attn_piece(d_acc + static_cast(t1) * q_row, + d_acc_ml + 2 * static_cast(t1) * Hq, + d_piece, d_piece_ml, n_full, Hq, D, nullptr); + } + } + } + check_gpu(gpu::device_synchronize(), "t8 sync"); + std::vector h_ref(n_vals), h_acc(n_vals); + check_gpu(gpu::memcpy_sync(h_ref.data(), d_ref, n_vals * sizeof(float), gpu::kDeviceToHost), "t8 d2h ref"); + check_gpu(gpu::memcpy_sync(h_acc.data(), d_acc, n_vals * sizeof(float), gpu::kDeviceToHost), "t8 d2h acc"); + + float max_diff = 0.0f; + bool any_nan = false; + for (size_t i = 0; i < n_vals; ++i) { + if (!std::isfinite(h_acc[i])) any_nan = true; + max_diff = std::max(max_diff, std::fabs(h_acc[i] - h_ref[i])); + } + if (any_nan || max_diff >= 1e-3f) { + std::fprintf(stderr, " t8 mismatch D=%d q8=%d case=%s max_diff=%.6e nan=%d\n", + D, use_q8 ? 1 : 0, c.tag, max_diff, any_nan ? 1 : 0); + } + expect_true(!any_nan && max_diff < 1e-3f, "chunked ml_out + merge_attn_piece matches full attention (< 1e-3)"); + } + + // Empty-key piece sentinel check: whole=true with pos=-n -> hi = -1 < lo = 0 -> [-INFINITY, 0.0f], out=0.0f + gpu::metal::set_optimize(true); + for (bool use_batch : {false, true}) { + const int n_emp = 8; + run_one(use_batch, d_q, 0, -n_emp, n_emp, true, d_piece, d_piece_ml); + check_gpu(gpu::device_synchronize(), "t8 empty sync"); + std::vector emp_o(static_cast(n_emp) * q_row); + std::vector emp_ml(static_cast(n_emp) * Hq * 2); + check_gpu(gpu::memcpy_sync(emp_o.data(), d_piece, emp_o.size() * sizeof(float), gpu::kDeviceToHost), "t8 emp o"); + check_gpu(gpu::memcpy_sync(emp_ml.data(), d_piece_ml, emp_ml.size() * sizeof(float), gpu::kDeviceToHost), "t8 emp ml"); + bool emp_ok = true; + for (float v : emp_o) if (v != 0.0f) emp_ok = false; + for (size_t i = 0; i < emp_ml.size(); i += 2) { + if (!(std::isinf(emp_ml[i]) && emp_ml[i] < 0.0f) || emp_ml[i + 1] != 0.0f) emp_ok = false; + } + expect_true(emp_ok, "empty-key attention piece emits out=0 and ml=[-INFINITY, 0]"); + } + gpu::metal::set_optimize(prev_opt); + } + + gpu::free_device(d_piece_ml); + gpu::free_device(d_acc_ml); + gpu::free_device(d_piece); + gpu::free_device(d_acc); + gpu::free_device(d_ref); + gpu::free_device(d_vs); + gpu::free_device(d_ks); + gpu::free_device(d_vc); + gpu::free_device(d_kc); + gpu::free_device(d_v16); + gpu::free_device(d_k16); + gpu::free_device(d_q); + gpu::free_device(d_vf); + gpu::free_device(d_kf); + } +} + +// ---- Test 9: cap_override=64 > cfg.transfer_cap=8 (UVA & non-UVA, eager / select / graph) ---- +void test_cap_override_exceeds_transfer_cap(bool disable_uva) { + std::printf("Test 9: cap_override=64 > cfg.transfer_cap=8 (seq_len=4096, uva=%s)...\n", + disable_uva ? "off" : "on"); + BasinKvConfig cfg; + cfg.n_layers = 1; + cfg.n_head_q = 16; + cfg.n_head_kv = 2; + cfg.head_dim = 256; + cfg.rope_dim = 64; + cfg.block_size = 16; + basinkv_partition_window(2048, cfg.block_size, cfg.sink_blocks, cfg.sparse_blocks, cfg.local_blocks); + cfg.max_seq_len = 4096; + cfg.transfer_cap = 8; + cfg.index_mode = BasinIndexMode::kQuestInt8; + cfg.host_quant = BasinHostQuant::kInt8; + cfg.disable_uva = disable_uva; + + expect_true(cfg.resident_tokens() == 2048 && cfg.sparse_blocks == 112, + "cap_override test uses resident_tokens=2048, sparse_blocks=112"); + + BasinKvPool pool; + pool.init(cfg); + expect_true(pool.is_using_uva() == !disable_uva, "cap_override test UVA mode matches config"); + + const int32_t Hq = cfg.n_head_q, Hk = cfg.n_head_kv, D = cfg.head_dim; + const int32_t kv_stride = Hk * D; + const int32_t seq_len = 4096; // 256 blocks: sink=[0..3], cold=[4..131], initial sparse=[132..243], local=[244..255] + const int32_t M = cfg.max_blocks(); + + std::mt19937 rng(91001 + (disable_uva ? 1 : 0)); + std::normal_distribution nd(0.0f, 0.4f); + std::vector h_k(static_cast(seq_len) * kv_stride); + std::vector h_v(static_cast(seq_len) * kv_stride); + std::vector h_q(static_cast(Hq) * D); + for (float& x : h_k) x = nd(rng); + for (float& x : h_v) x = nd(rng); + for (float& x : h_q) x = nd(rng); + + // Plant 64 strongly aligned cold blocks [4..67] so a single cap_override=64 lookahead admits > 8 blocks/head. + const int32_t G = Hq / Hk; + for (int32_t b = 4; b < 68; ++b) { + const float v_even = 0.5f + 0.01f * static_cast(b); + const float v_odd = -0.25f - 0.01f * static_cast(b); + for (int32_t t = 0; t < cfg.block_size; ++t) { + for (int32_t h = 0; h < Hk; ++h) { + for (int32_t d = 0; d < D; ++d) { + const size_t idx = (static_cast(b * cfg.block_size + t) * Hk + h) * D + d; + h_k[idx] = 5.0f * h_q[static_cast(h * G) * D + d]; + h_v[idx] = (d % 2 == 0) ? v_even : v_odd; + } + } + } + } + + float *d_k = nullptr, *d_v = nullptr, *d_q = nullptr, *d_scores = nullptr; + check_gpu(gpu::malloc_device(&d_k, h_k.size() * sizeof(float)), "t9 dk"); + check_gpu(gpu::malloc_device(&d_v, h_v.size() * sizeof(float)), "t9 dv"); + check_gpu(gpu::malloc_device(&d_q, h_q.size() * sizeof(float)), "t9 dq"); + check_gpu(gpu::malloc_device(&d_scores, static_cast(Hk) * M * sizeof(float)), "t9 ds"); + check_gpu(gpu::memcpy_sync(d_k, h_k.data(), h_k.size() * sizeof(float), gpu::kHostToDevice), "t9 h2d k"); + check_gpu(gpu::memcpy_sync(d_v, h_v.data(), h_v.size() * sizeof(float), gpu::kHostToDevice), "t9 h2d v"); + check_gpu(gpu::memcpy_sync(d_q, h_q.data(), h_q.size() * sizeof(float), gpu::kHostToDevice), "t9 h2d q"); + + auto verify_gathered_cold_v = [&](const char* label) { + std::vector g2c, c2g; + pool.read_page_tables(0, g2c, c2g); + std::vector hot_v(static_cast(cfg.resident_tokens()) * kv_stride); + check_gpu(gpu::memcpy_sync(hot_v.data(), pool.hot_v(0), hot_v.size() * sizeof(uint16_t), gpu::kDeviceToHost), label); + int32_t admitted_planted = 0; + float max_v_err = 0.0f; + for (int32_t h = 0; h < Hk; ++h) { + for (int32_t b = 4; b < 68; ++b) { + const int32_t s = c2g[static_cast(h) * M + b]; + if (s < cfg.sink_blocks || s >= cfg.local_slot_start()) continue; + ++admitted_planted; + const float v_even = 0.5f + 0.01f * static_cast(b); + const float v_odd = -0.25f - 0.01f * static_cast(b); + for (int32_t t = 0; t < cfg.block_size; ++t) { + for (int32_t d = 0; d < D; ++d) { + const size_t off = (static_cast(s * cfg.block_size + t) * Hk + h) * D + d; + const float got = f16_bits_to_f32(hot_v[off]); + const float ref = (d % 2 == 0) ? v_even : v_odd; + max_v_err = std::max(max_v_err, std::fabs(got - ref)); + } + } + } + } + expect_true(admitted_planted > 8 * Hk, "cap_override=64 admitted > 8 planted cold blocks per head"); + expect_true(max_v_err < 0.03f, "cap_override=64 gathered cold V values accurately without corruption"); + }; + + // 9a: submit_lookahead_f32(..., cap_override=64) + pool.append_prefill_chunk_f32(0, d_k, d_v, 0, seq_len); + pool.submit_lookahead_f32(0, d_q, nullptr, /*cap_override=*/64); + check_gpu(gpu::device_synchronize(), "t9a sync"); + verify_page_table_invariants(pool, 0, disable_uva ? "t9a_non_uva" : "t9a_uva"); + const uint64_t adm1 = pool.read_admitted_count(0); + expect_true(adm1 > static_cast(8 * Hk), + "submit_lookahead_f32(cap_override=64) admitted > 8 blocks per head"); + verify_gathered_cold_v("t9a_hv"); + + // 9b: run_select_from_scores(..., cap_override=64) targeting a disjoint set of 64 cold blocks [68..131] + std::vector h_scores(static_cast(Hk) * M, 0.0f); + for (int32_t h = 0; h < Hk; ++h) { + float* row = h_scores.data() + static_cast(h) * M; + for (int32_t b = 68; b < 132; ++b) row[b] = 200.0f - static_cast(b - 68); + } + check_gpu(gpu::memcpy_sync(d_scores, h_scores.data(), h_scores.size() * sizeof(float), gpu::kHostToDevice), "t9b h2d sc"); + pool.run_select_from_scores(0, d_scores, cfg.sink_blocks, 244, /*step=*/50, /*cap_override=*/64); + check_gpu(gpu::device_synchronize(), "t9b sync"); + verify_page_table_invariants(pool, 0, disable_uva ? "t9b_non_uva" : "t9b_uva"); + const uint64_t adm2 = pool.read_admitted_count(0); + expect_true(adm2 - adm1 > static_cast(8 * Hk), + "run_select_from_scores(cap_override=64) admitted > 8 blocks per head"); + + // 9c: submit_lookahead_graph_f32(..., cap_override=64) + if (disable_uva) { + expect_throws([&] { pool.submit_lookahead_graph_f32(0, d_q, nullptr, 64); }, + "submit_lookahead_graph_f32 requires UVA in non-UVA mode"); + } else { + pool.reset_all(); + pool.append_prefill_chunk_f32(0, d_k, d_v, 0, seq_len); + check_gpu(gpu::device_synchronize(), "t9c prefill sync"); + + gpu::Stream st = nullptr; + gpu::Graph graph = nullptr; + gpu::GraphExec exec = nullptr; + check_gpu(gpu::stream_create(&st, gpu::kStreamNonBlocking), "t9c stream"); + check_gpu(gpu::begin_capture(st), "t9c begin capture"); + pool.submit_lookahead_graph_f32(0, d_q, st, /*cap_override=*/64); + pool.join_bg_in_capture(st); + check_gpu(gpu::end_capture(st, &graph), "t9c end capture"); + check_gpu(gpu::graph_instantiate(&exec, graph, 0), "t9c instantiate"); + gpu::graph_destroy(graph); + + pool.mark_device_state_dirty(); + check_gpu(gpu::graph_launch(exec, st), "t9c launch"); + check_gpu(gpu::stream_synchronize(st), "t9c sync"); + pool.sync_host_state(st); + verify_page_table_invariants(pool, 0, "t9c_graph_uva"); + const uint64_t adm_g = pool.read_admitted_count(0, st); + expect_true(adm_g > static_cast(8 * Hk), + "submit_lookahead_graph_f32(cap_override=64) admitted > 8 blocks per head"); + verify_gathered_cold_v("t9c_hv"); + + gpu::graph_exec_destroy(exec); + gpu::stream_destroy(st); + } + + gpu::free_device(d_scores); + gpu::free_device(d_q); + gpu::free_device(d_v); + gpu::free_device(d_k); +} + +// ---- Test 10: Inkling 2 BasinKV Metal support (d_gpu_to_cpu, null-cache ink_qkv/win, hot_cap ink_attend) ---- +void test_inkling2_basinkv_metal() { + std::printf("Test 10: Inkling 2 BasinKV Metal (d_gpu_to_cpu, ink_qkv null cache, ink_attend hot_cap)...\n"); + const int Hq = 6, Hk = 2, D = 128, n_rel = 16, extent = 64; + const int hot_cap = 256; // W = 16 blocks, B = 16 + const int W = hot_cap / 16; + + // 10a. ink_qkv and ink_qkv_win with keys=nullptr, vals=nullptr match non-null cache call on Q/K/V/R/conv-state. + { + const int taps = 4, rows = 3; + std::mt19937 rng(1001); + std::normal_distribution nd(0.f, 0.5f); + auto make_vec = [&](size_t n) { + std::vector v(n); + for (float& x : v) x = nd(rng); + return v; + }; + const auto h_q0 = make_vec(size_t(rows) * Hq * D); + const auto h_r0 = make_vec(size_t(rows) * Hq * n_rel); + const auto h_kr = make_vec(size_t(rows) * Hk * D); + const auto h_vr = make_vec(size_t(rows) * Hk * D); + const auto h_ks0 = make_vec(size_t(taps - 1) * Hk * D); + const auto h_vs0 = make_vec(size_t(taps - 1) * Hk * D); + const auto h_kw = make_vec(size_t(Hk) * D * taps); + const auto h_vw = make_vec(size_t(Hk) * D * taps); + + auto run_qkv = [&](bool win, bool null_cache, std::vector& out_q, std::vector& out_k, + std::vector& out_v, std::vector& out_r, std::vector& out_ks) { + const int nr = win ? rows : 1; + float *dq = nullptr, *dr = nullptr, *dkr = nullptr, *dvr = nullptr; + float *dks = nullptr, *dvs = nullptr, *dkw = nullptr, *dvw = nullptr; + float *dk = nullptr, *dv = nullptr; + uint16_t *dkeys = nullptr, *dvals = nullptr; + check_gpu(gpu::malloc_device(&dq, size_t(nr) * Hq * D * sizeof(float)), "t10 q"); + check_gpu(gpu::malloc_device(&dr, size_t(nr) * Hq * n_rel * sizeof(float)), "t10 r"); + check_gpu(gpu::malloc_device(&dkr, size_t(nr) * Hk * D * sizeof(float)), "t10 kr"); + check_gpu(gpu::malloc_device(&dvr, size_t(nr) * Hk * D * sizeof(float)), "t10 vr"); + check_gpu(gpu::malloc_device(&dks, h_ks0.size() * sizeof(float)), "t10 ks"); + check_gpu(gpu::malloc_device(&dvs, h_vs0.size() * sizeof(float)), "t10 vs"); + check_gpu(gpu::malloc_device(&dkw, h_kw.size() * sizeof(float)), "t10 kw"); + check_gpu(gpu::malloc_device(&dvw, h_vw.size() * sizeof(float)), "t10 vw"); + check_gpu(gpu::malloc_device(&dk, size_t(nr) * Hk * D * sizeof(float)), "t10 k"); + check_gpu(gpu::malloc_device(&dv, size_t(nr) * Hk * D * sizeof(float)), "t10 v"); + if (!null_cache) { + check_gpu(gpu::malloc_device(&dkeys, size_t(32) * Hk * D * sizeof(uint16_t)), "t10 keys"); + check_gpu(gpu::malloc_device(&dvals, size_t(32) * Hk * D * sizeof(uint16_t)), "t10 vals"); + } + check_gpu(gpu::memcpy_sync(dq, h_q0.data(), size_t(nr) * Hq * D * sizeof(float), gpu::kHostToDevice), "t10 h2d q"); + check_gpu(gpu::memcpy_sync(dr, h_r0.data(), size_t(nr) * Hq * n_rel * sizeof(float), gpu::kHostToDevice), "t10 h2d r"); + check_gpu(gpu::memcpy_sync(dkr, h_kr.data(), size_t(nr) * Hk * D * sizeof(float), gpu::kHostToDevice), "t10 h2d kr"); + check_gpu(gpu::memcpy_sync(dvr, h_vr.data(), size_t(nr) * Hk * D * sizeof(float), gpu::kHostToDevice), "t10 h2d vr"); + check_gpu(gpu::memcpy_sync(dks, h_ks0.data(), h_ks0.size() * sizeof(float), gpu::kHostToDevice), "t10 h2d ks"); + check_gpu(gpu::memcpy_sync(dvs, h_vs0.data(), h_vs0.size() * sizeof(float), gpu::kHostToDevice), "t10 h2d vs"); + check_gpu(gpu::memcpy_sync(dkw, h_kw.data(), h_kw.size() * sizeof(float), gpu::kHostToDevice), "t10 h2d kw"); + check_gpu(gpu::memcpy_sync(dvw, h_vw.data(), h_vw.size() * sizeof(float), gpu::kHostToDevice), "t10 h2d vw"); + + InkQkv q{}; + q.q = dq; q.r = dr; q.kraw = dkr; q.vraw = dvr; + q.kstate = dks; q.vstate = dvs; q.kw = dkw; q.vw = dvw; + q.k = dk; q.v = dv; q.keys = dkeys; q.vals = dvals; + q.n_head = Hq; q.n_kv = Hk; q.dim = D; q.n_rel = n_rel; q.taps = taps; + q.pos = 5; q.qk_thr = 4.0f; q.rel_thr = 4.0f; q.alpha = 0.0f; q.floor = 1.0f; q.eps = 1e-6f; + if (win) ink_qkv_win(q, nr, nullptr, nullptr, 0, 0, nullptr); + else ink_qkv(q, nullptr); + check_gpu(gpu::device_synchronize(), "t10 qkv sync"); + + out_q.resize(size_t(nr) * Hq * D); + out_k.resize(size_t(nr) * Hk * D); + out_v.resize(size_t(nr) * Hk * D); + out_r.resize(size_t(nr) * Hq * n_rel); + out_ks.resize(h_ks0.size()); + check_gpu(gpu::memcpy_sync(out_q.data(), dq, out_q.size() * sizeof(float), gpu::kDeviceToHost), "t10 d2h q"); + check_gpu(gpu::memcpy_sync(out_k.data(), dk, out_k.size() * sizeof(float), gpu::kDeviceToHost), "t10 d2h k"); + check_gpu(gpu::memcpy_sync(out_v.data(), dv, out_v.size() * sizeof(float), gpu::kDeviceToHost), "t10 d2h v"); + check_gpu(gpu::memcpy_sync(out_r.data(), dr, out_r.size() * sizeof(float), gpu::kDeviceToHost), "t10 d2h r"); + check_gpu(gpu::memcpy_sync(out_ks.data(), dks, out_ks.size() * sizeof(float), gpu::kDeviceToHost), "t10 d2h ks"); + + if (dvals) gpu::free_device(dvals); + if (dkeys) gpu::free_device(dkeys); + gpu::free_device(dv); gpu::free_device(dk); + gpu::free_device(dvw); gpu::free_device(dkw); + gpu::free_device(dvs); gpu::free_device(dks); + gpu::free_device(dvr); gpu::free_device(dkr); + gpu::free_device(dr); gpu::free_device(dq); + }; + for (bool win : {false, true}) { + std::vector q1, k1, v1, r1, ks1, q2, k2, v2, r2, ks2; + run_qkv(win, false, q1, k1, v1, r1, ks1); + run_qkv(win, true, q2, k2, v2, r2, ks2); + expect_true(q1 == q2 && k1 == k2 && v1 == v2 && r1 == r2 && ks1 == ks2, + win ? "ink_qkv_win(keys=null, vals=null) matches non-null cache bit-identically" + : "ink_qkv(keys=null, vals=null) matches non-null cache bit-identically"); + } + } + + // 10b. End-to-end BasinKvPool (rope_dim=0, D=128) + ink_attend(hot_cap, hot_eff_pos, hot_slot_blk) + // verified against exact CPU FP32 reference in BOTH short-context (empty splits) AND sparse steady-state! + { + BasinKvConfig cfg; + cfg.n_layers = 1; + cfg.n_head_q = Hq; + cfg.n_head_kv = Hk; + cfg.head_dim = D; + cfg.rope_dim = 0; + cfg.block_size = 16; + cfg.sink_blocks = 2; + cfg.sparse_blocks = 8; + cfg.local_blocks = 6; // W = 16 -> resident_tokens = 256 + cfg.max_seq_len = 1024; + cfg.transfer_cap = 4; + cfg.index_mode = BasinIndexMode::kSphereInt4; + cfg.host_quant = BasinHostQuant::kWhtInt4; + + BasinKvPool pool; + pool.init(cfg); + expect_true(pool.d_gpu_to_cpu(0) != nullptr, "BasinKvPool::d_gpu_to_cpu(0) is non-null"); + + std::mt19937 rng(1002); + std::normal_distribution nd(0.f, 0.35f); + auto make_vec = [&](size_t n) { + std::vector v(n); + for (float& x : v) x = nd(rng); + return v; + }; + + const int total_prefill = 512; + const auto h_k_all = make_vec(size_t(total_prefill + 4) * Hk * D); + const auto h_v_all = make_vec(size_t(total_prefill + 4) * Hk * D); + const auto h_q = make_vec(size_t(Hq) * D); + const auto h_r = make_vec(size_t(Hq) * n_rel); + const auto h_sink = make_vec(size_t(Hq)); + const auto h_rel = make_vec(size_t(extent) * n_rel); + const auto h_gate = make_vec(size_t(Hq) * D); + + float *dk = nullptr, *dv = nullptr, *dq = nullptr, *dr = nullptr, *dsink = nullptr, *drel = nullptr, *dgate = nullptr, *dout = nullptr; + check_gpu(gpu::malloc_device(&dk, h_k_all.size() * sizeof(float)), "t10b dk"); + check_gpu(gpu::malloc_device(&dv, h_v_all.size() * sizeof(float)), "t10b dv"); + check_gpu(gpu::malloc_device(&dq, h_q.size() * sizeof(float)), "t10b dq"); + check_gpu(gpu::malloc_device(&dr, h_r.size() * sizeof(float)), "t10b dr"); + check_gpu(gpu::malloc_device(&dsink, h_sink.size() * sizeof(float)), "t10b dsink"); + check_gpu(gpu::malloc_device(&drel, h_rel.size() * sizeof(float)), "t10b drel"); + check_gpu(gpu::malloc_device(&dgate, h_gate.size() * sizeof(float)), "t10b dgate"); + check_gpu(gpu::malloc_device(&dout, size_t(Hq) * D * sizeof(float)), "t10b dout"); + check_gpu(gpu::memcpy_sync(dk, h_k_all.data(), h_k_all.size() * sizeof(float), gpu::kHostToDevice), "t10b h2d k"); + check_gpu(gpu::memcpy_sync(dv, h_v_all.data(), h_v_all.size() * sizeof(float), gpu::kHostToDevice), "t10b h2d v"); + check_gpu(gpu::memcpy_sync(dq, h_q.data(), h_q.size() * sizeof(float), gpu::kHostToDevice), "t10b h2d q"); + check_gpu(gpu::memcpy_sync(dr, h_r.data(), h_r.size() * sizeof(float), gpu::kHostToDevice), "t10b h2d r"); + check_gpu(gpu::memcpy_sync(dsink, h_sink.data(), h_sink.size() * sizeof(float), gpu::kHostToDevice), "t10b h2d sink"); + check_gpu(gpu::memcpy_sync(drel, h_rel.data(), h_rel.size() * sizeof(float), gpu::kHostToDevice), "t10b h2d rel"); + check_gpu(gpu::memcpy_sync(dgate, h_gate.data(), h_gate.size() * sizeof(float), gpu::kHostToDevice), "t10b h2d gate"); + + auto check_ink_hot_parity = [&](int64_t logical_pos, const char* label) { + std::vector g2c, c2g; + pool.read_page_tables(0, g2c, c2g); + std::vector g2c_dev(size_t(Hk) * W); + check_gpu(gpu::memcpy_sync(g2c_dev.data(), pool.d_gpu_to_cpu(0), g2c_dev.size() * sizeof(int32_t), gpu::kDeviceToHost), "t10b g2c"); + expect_true(g2c_dev == g2c, "d_gpu_to_cpu() device table matches read_page_tables()"); + + long long eff_pos = -1; + check_gpu(gpu::memcpy_sync(&eff_pos, pool.d_eff_pos(0), sizeof(long long), gpu::kDeviceToHost), "t10b eff_pos"); + expect_true(eff_pos == pool.effective_pos(logical_pos), "d_eff_pos matches effective_pos"); + + InkAttn a{}; + a.q = dq; a.r = dr; a.sink = dsink; + a.keys = pool.hot_k(0); a.vals = pool.hot_v(0); + a.rel_bias = drel; a.gate = dgate; a.out = dout; + a.pos = logical_pos; a.rows = 1; + a.n_head = Hq; a.n_kv = Hk; a.dim = D; a.n_rel = n_rel; a.extent = extent; + a.scale = 1.0f / std::sqrt(float(D)); + a.hot_cap = hot_cap; + a.hot_eff_pos = pool.d_eff_pos(0); + a.hot_slot_blk = pool.d_gpu_to_cpu(0); + ink_attend(a, nullptr); + check_gpu(gpu::device_synchronize(), "t10b ink_attend sync"); + + std::vector gpu_out(size_t(Hq) * D); + check_gpu(gpu::memcpy_sync(gpu_out.data(), dout, gpu_out.size() * sizeof(float), gpu::kDeviceToHost), "t10b d2h out"); + std::vector hot_k(size_t(hot_cap) * Hk * D), hot_v(size_t(hot_cap) * Hk * D); + check_gpu(gpu::memcpy_sync(hot_k.data(), pool.hot_k(0), hot_k.size() * sizeof(uint16_t), gpu::kDeviceToHost), "t10b hk"); + check_gpu(gpu::memcpy_sync(hot_v.data(), pool.hot_v(0), hot_v.size() * sizeof(uint16_t), gpu::kDeviceToHost), "t10b hv"); + + const int per = Hq / Hk; + const int nk = int(eff_pos + 1); + double max_err = 0.0; + for (int h = 0; h < Hq; ++h) { + const int g = h / per; + std::vector scores(nk); + double m = 0.0; // extra sink term of score 0 + for (int j = 0; j < nk; ++j) { + double dot = 0.0; + for (int d = 0; d < D; ++d) { + const float kv = f16_bits_to_f32(hot_k[(size_t(j) * Hk + g) * D + d]); + dot += double(h_q[size_t(h) * D + d]) * double(a.scale) * double(kv); + } + const int blk = g2c[size_t(g) * W + size_t(j >> 4)]; + const int64_t dist = blk >= 0 ? (logical_pos - (int64_t(blk) * 16 + (j & 15))) : int64_t(extent); + if (dist >= 0 && dist < extent) { + for (int k = 0; k < n_rel; ++k) { + dot += double(h_r[size_t(h) * n_rel + k]) * double(h_rel[size_t(dist) * n_rel + k]); + } + } + dot -= double(h_sink[h]); + scores[j] = dot; + m = std::max(m, dot); + } + double denom = std::exp(-m); + std::vector acc(D, 0.0); + for (int j = 0; j < nk; ++j) { + const double w = std::exp(scores[j] - m); + denom += w; + for (int d = 0; d < D; ++d) { + const float vv = f16_bits_to_f32(hot_v[(size_t(j) * Hk + g) * D + d]); + acc[d] += w * double(vv); + } + } + for (int d = 0; d < D; ++d) { + const double gval = 1.0 / (1.0 + std::exp(-double(h_gate[size_t(h) * D + d]))); + const double ref = (acc[d] / denom) * gval; + max_err = std::max(max_err, std::abs(ref - double(gpu_out[size_t(h) * D + d]))); + } + } + if (max_err > 1e-4) { + std::fprintf(stderr, "FAIL [%s]: ink_attend hot_cap max_err=%.6e\n", label, max_err); + ++g_failures; + } + }; + + // Short context (pos=37 < hot_cap=256): exercises empty splits when keys=256 -> splits > 1 + pool.append_prefill_chunk_f32(0, dk, dv, 0, 37, nullptr); + pool.append_decode_token_f32(0, dk + size_t(37) * Hk * D, dv + size_t(37) * Hk * D, 37, nullptr); + check_ink_hot_parity(37, "t10b_short_37"); + + // Sparse steady-state (pos=513 > hot_cap=256): exercises lookahead + non-monotonic gpu_to_cpu distances + pool.reset_all(nullptr); + pool.append_prefill_chunk_f32(0, dk, dv, 0, total_prefill, nullptr); + pool.submit_lookahead_f32(0, dq, nullptr, 8); + for (int p = total_prefill; p < total_prefill + 3; ++p) { + pool.append_decode_token_f32(0, dk + size_t(p) * Hk * D, dv + size_t(p) * Hk * D, p, nullptr); + check_ink_hot_parity(p, p == total_prefill ? "t10b_sparse_512" : "t10b_sparse_next"); + pool.submit_lookahead_f32(0, dq, nullptr); + } + + gpu::free_device(dout); gpu::free_device(dgate); gpu::free_device(drel); + gpu::free_device(dsink); gpu::free_device(dr); gpu::free_device(dq); + gpu::free_device(dv); gpu::free_device(dk); + } +} + +} // namespace + +int main() { + int count = 0; + if (gpu::device_count(&count) != gpu::kSuccess || count < 1) { + std::printf("poly_basinkv_parity: no Metal GPU available (skipping)\n"); + return 77; + } + gpu::DeviceProp prop{}; + check_gpu(gpu::get_device_properties(&prop, 0), "get_device_properties"); + std::printf("poly_basinkv_parity: running on Metal GPU (%s)\n", prop.name); + + // Enable strict scoped residency to verify every dispatch registers all accessed buffers! + gpu::metal::set_scoped_residency(true); + + test_config_and_footprint(); + test_quest_index_and_scoring(); + test_sphere_index_and_scoring(); + test_topk_successor_eviction(); + test_short_context_bit_identical(); + test_long_context_4096(BasinIndexMode::kQuestInt8, BasinHostQuant::kInt8, false); + test_long_context_4096(BasinIndexMode::kSphereInt4, BasinHostQuant::kWhtInt4, false); + test_long_context_4096(BasinIndexMode::kQuestInt8, BasinHostQuant::kWhtInt4, false); + test_long_context_4096(BasinIndexMode::kSphereInt4, BasinHostQuant::kInt8, false); + test_long_context_4096(BasinIndexMode::kQuestInt8, BasinHostQuant::kInt8, true); + test_long_context_4096(BasinIndexMode::kSphereInt4, BasinHostQuant::kWhtInt4, true); + test_metal_graph_replay(BasinIndexMode::kQuestInt8, BasinHostQuant::kInt8, true); + test_metal_graph_replay(BasinIndexMode::kSphereInt4, BasinHostQuant::kWhtInt4, true); + test_metal_graph_replay(BasinIndexMode::kQuestInt8, BasinHostQuant::kWhtInt4, false); + test_metal_graph_replay(BasinIndexMode::kSphereInt4, BasinHostQuant::kInt8, false); + test_truncate_materialize_export_import(); + test_chunked_attention_ml_out(); + test_cap_override_exceeds_transfer_cap(false); + test_cap_override_exceeds_transfer_cap(true); + test_inkling2_basinkv_metal(); + + if (g_failures > 0) { + std::fprintf(stderr, "poly_basinkv_parity: %d failure(s)\n", g_failures); + return 1; + } + std::printf("poly_basinkv_parity: ALL PASSED\n"); + return 0; +} diff --git a/engine/metal/src/poly/attention.cpp b/engine/metal/src/poly/attention.cpp index 102d7cf054..785237e581 100644 --- a/engine/metal/src/poly/attention.cpp +++ b/engine/metal/src/poly/attention.cpp @@ -4,12 +4,12 @@ namespace strata::poly { namespace { struct Args { - const void* p[10]{}; + const void* p[11]{}; int64_t pos=0; int dim=0,heads=0,kv=0,rows=0,window=0,ring=0,whole=0,stride=0,rot=0,sections=1,kind=0; float scale=0,eps=0; }; -static_assert(sizeof(Args)==144); +static_assert(sizeof(Args)==152); void run(const char* name,const Args& a,void* stream,gpu::metal::Grid groups,gpu::metal::Resources res={},uint32_t threads=32,size_t shared=0) { static const auto source=metal_detail::read_source(STRATA_POLY_ATTENTION_SOURCE); metal_detail::dispatch("poly_attention",source,name,a,stream,groups,threads,res,shared); @@ -101,13 +101,12 @@ void attend(const float* q,const uint16_t* k,const uint16_t* v,int64_t pos,int r int dim,int heads,int kv,float scale,void* s,int window,int ring,bool whole,const long long* at,int room,size_t, Kvq8 kq,Kvq8 vq,const float* sinks,size_t,float* ml_out) { if(dim<=0 || dim>1024 || dim%4 || kv<=0 || heads%kv) throw std::invalid_argument("Metal attention shape"); - if(ml_out) throw std::invalid_argument("Metal attention has no streamed pieces (--kv-resident)"); if((kq.rs && kq.rs!=size_t(kv)*dim) || (vq.rs && vq.rs!=size_t(kv)*dim)) throw std::invalid_argument("Metal q8 cache rows are kv_heads * dim codes apart"); if(sinks) throw std::invalid_argument("Metal attention has no attention sinks (Flint)"); if(rows<=0) return; Args a;a.p[0]=q;a.p[1]=k;a.p[2]=v;a.p[3]=out;a.p[4]=at; - a.p[5]=kq.codes;a.p[6]=kq.scales;a.p[7]=vq.codes;a.p[8]=vq.scales; + a.p[5]=kq.codes;a.p[6]=kq.scales;a.p[7]=vq.codes;a.p[8]=vq.scales;a.p[10]=ml_out; a.dim=dim;a.heads=heads;a.kv=kv;a.pos=pos;a.rows=rows;a.scale=scale;a.window=window;a.ring=ring;a.whole=whole; // The keys a token of the call reads: up to its own, within the window. A recorded launch reads its position on // the card and serves the contexts up to `room` rows: it is sized for the middle of them. Without splits, a SIMD @@ -146,6 +145,7 @@ void attend(const float* q,const uint16_t* k,const uint16_t* v,int64_t pos,int r const size_t q_b=4ULL*size_t(rows)*size_t(heads)*size_t(dim); const size_t at_b=at?16ULL*size_t(rows):0ULL; const size_t scr_b=splits>1?4ULL*size_t(splits)*size_t(rows)*size_t(heads)*size_t(dim+2):0ULL; + const size_t ml_b=ml_out?8ULL*size_t(rows)*size_t(heads):0ULL; if(splits>1) { const void* refs1[10]={q,k,v,nullptr,at,kq.codes,kq.scales,vq.codes,vq.scales,scratch}; const gpu::metal::Access m1[10]={gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R, @@ -154,19 +154,19 @@ void attend(const float* q,const uint16_t* k,const uint16_t* v,int64_t pos,int r const size_t s1[10]={q_b,0,0,0,at_b,0,0,0,0,scr_b}; run(kname,a,s,{uint32_t(kv*n_gqa),uint32_t(rows),uint32_t(splits)}, {refs1,10,true,nullptr,m1,s1},uint32_t(32*groups),shared); - const void* refs2[10]={nullptr,nullptr,nullptr,out,nullptr,nullptr,nullptr,nullptr,nullptr,scratch}; - const gpu::metal::Access m2[10]={gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::W, + const void* refs2[11]={nullptr,nullptr,nullptr,out,nullptr,nullptr,nullptr,nullptr,nullptr,scratch,ml_out}; + const gpu::metal::Access m2[11]={gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::W, gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R, - gpu::metal::Access::R,gpu::metal::Access::R}; - const size_t s2[10]={0,0,0,q_b,0,0,0,0,0,scr_b}; - run("poly_attention_join",a,s,{uint32_t(heads),uint32_t(rows),1},{refs2,10,true,nullptr,m2,s2}); + gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::W}; + const size_t s2[11]={0,0,0,q_b,0,0,0,0,0,scr_b,ml_b}; + run("poly_attention_join",a,s,{uint32_t(heads),uint32_t(rows),1},{refs2,11,true,nullptr,m2,s2}); } else { - const gpu::metal::Access m1[9]={gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::W, - gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R, - gpu::metal::Access::R}; - const size_t s1[9]={q_b,0,0,q_b,at_b,0,0,0,0}; + const gpu::metal::Access m1[11]={gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::W, + gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R, + gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::W}; + const size_t s1[11]={q_b,0,0,q_b,at_b,0,0,0,0,0,ml_b}; run(kname,a,s,{uint32_t(kv*n_gqa),uint32_t(rows),uint32_t(splits)}, - {a.p,9,true,nullptr,m1,s1},uint32_t(32*groups),shared); + {a.p,11,true,nullptr,m1,s1},uint32_t(32*groups),shared); } } size_t attend_split_floats(int,int,int,int) { return 0; } // online softmax has no score workspace @@ -174,7 +174,6 @@ void attend_batch(void*,const float* q,const uint16_t* k,const uint16_t* v,int64 size_t score_n,float*,float* out,int dim,int heads,int kv,float scale,void* s,int window,int ring, bool whole,Kvq8 kq,Kvq8 vq,uint16_t*,uint16_t*,size_t,const float* sinks,float* ml_out, const AttnBias* bias) { - if(ml_out) throw std::invalid_argument("Metal attention has no streamed pieces (--kv-resident)"); if(bias) throw std::invalid_argument("Metal attention has no bias by distance (Inkling 2)"); static const std::string source=metal_detail::read_source(STRATA_POLY_FLASH_SOURCE); static const bool ready=[] { @@ -184,14 +183,14 @@ void attend_batch(void*,const float* q,const uint16_t* k,const uint16_t* v,int64 const bool flash=(dim==64 || dim==128 || dim==256) && !sinks && kv>0 && heads%kv==0 && gpu::metal::optimize() && ready && (!kq.codes || ((!kq.rs || kq.rs==size_t(kv)*dim) && (!vq.rs || vq.rs==size_t(kv)*dim))); if(!flash || rows<=0) { - attend(q,k,v,pos,rows,score,rows,out,dim,heads,kv,scale,s,window,ring,whole,nullptr,0,score_n,kq,vq,sinks,0); + attend(q,k,v,pos,rows,score,rows,out,dim,heads,kv,scale,s,window,ring,whole,nullptr,0,score_n,kq,vq,sinks,0,ml_out); return; } const int per=heads/kv; const int g_tile=(dim==256)?1:std::min(per,4),n_gqa=(per+g_tile-1)/g_tile; const bool is_q8=kq.codes!=nullptr; Args a;a.p[0]=q;a.p[1]=k;a.p[2]=v;a.p[3]=out; - a.p[5]=kq.codes;a.p[6]=kq.scales;a.p[7]=vq.codes;a.p[8]=vq.scales; + a.p[5]=kq.codes;a.p[6]=kq.scales;a.p[7]=vq.codes;a.p[8]=vq.scales;a.p[10]=ml_out; a.dim=dim;a.heads=heads;a.kv=kv;a.pos=pos;a.rows=rows;a.scale=scale;a.window=window;a.ring=ring;a.whole=whole; const int64_t first=window>0?std::max(0,pos-window+1):0; const int64_t keys=pos+rows-first; @@ -202,11 +201,12 @@ void attend_batch(void*,const float* q,const uint16_t* k,const uint16_t* v,int64 gpu::metal::prof_push_hint({gpu::metal::ProfCat::Attention,b,4ULL*uint64_t(rows)*heads*uint64_t(keys)*dim}); } const size_t q_b=4ULL*size_t(rows)*size_t(heads)*size_t(dim); - const gpu::metal::Access mf[9]={gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::W, - gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R, - gpu::metal::Access::R}; - const size_t sf[9]={q_b,0,0,q_b,0,0,0,0,0}; + const size_t ml_b=ml_out?8ULL*size_t(rows)*size_t(heads):0ULL; + const gpu::metal::Access mf[11]={gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::W, + gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R, + gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::W}; + const size_t sf[11]={q_b,0,0,q_b,0,0,0,0,0,0,ml_b}; metal_detail::dispatch("poly_flash",source,name.c_str(),a,s,{uint32_t(kv*n_gqa),uint32_t((rows+15)/16),1}, - uint32_t(g_tile*32),{a.p,9,true,nullptr,mf,sf}); + uint32_t(g_tile*32),{a.p,11,true,nullptr,mf,sf}); } } diff --git a/engine/metal/src/poly/attention.metal b/engine/metal/src/poly/attention.metal index dc888d5acf..19a0588c4e 100644 --- a/engine/metal/src/poly/attention.metal +++ b/engine/metal/src/poly/attention.metal @@ -1,7 +1,7 @@ #include using namespace metal; struct Args { - device void* p[10]; long pos; + device void* p[11]; long pos; int dim,heads,kv,rows,window,ring,whole,stride,rot,sections,kind; float scale,eps; }; @@ -167,12 +167,16 @@ kernel void poly_attention(constant Args& a [[buffer(0)]],threadgroup float* par if(used==1) { if(splits>1) { device float* run=static_cast(a.p[9])+(head0*splits+group.z)*(a.dim+2); - if(!lane) { run[0]=maximum;run[1]=denom; } + if(!lane) { run[0]=denom>0.0f?maximum:-INFINITY;run[1]=denom; } for(int d=lane;d(a.p[3])+head0*a.dim; - const float inv_d=1.0f/denom; + const float inv_d=denom>0.0f?1.0f/denom:0.0f; for(int d=lane;d(a.p[10])+2*head0; + ml[0]=denom>0.0f?maximum:-INFINITY;ml[1]=denom; + } } return; } @@ -188,11 +192,15 @@ kernel void poly_attention(constant Args& a [[buffer(0)]],threadgroup float* par float top=-INFINITY,total=0.0f; float w[16]; for(uint g=0;g0.0f?exp(m[g]-top):0.0f; total+=l[g]*w[g]; } device float* run=splits>1?static_cast(a.p[9])+(head0*splits+group.z)*(a.dim+2):nullptr; device float* out=static_cast(a.p[3])+head0*a.dim; - if(run && !lane) { run[0]=top;run[1]=total; } - const float inv_t=1.0f/total; + if(run && !lane) { run[0]=total>0.0f?top:-INFINITY;run[1]=total; } + else if(!run && a.p[10] && !lane) { + device float* ml=static_cast(a.p[10])+2*head0; + ml[0]=total>0.0f?top:-INFINITY;ml[1]=total; + } + const float inv_t=total>0.0f?1.0f/total:0.0f; for(int d=lane;d1) { device float* run=static_cast(a.p[9])+((head0+hp)*splits+group.z)*(a.dim+2); - if(!lane) { run[0]=maximum[hp];run[1]=denom[hp]; } + if(!lane) { run[0]=denom[hp]>0.0f?maximum[hp]:-INFINITY;run[1]=denom[hp]; } for(int d=lane;d(a.p[3])+(head0+hp)*a.dim; - for(int d=lane;d0.0f?1.0f/denom[hp]:0.0f; + for(int d=lane;d(a.p[10])+2*(head0+hp); + ml[0]=denom[hp]>0.0f?maximum[hp]:-INFINITY;ml[1]=denom[hp]; + } } } return; @@ -266,15 +279,26 @@ kernel void poly_attention(constant Args& a [[buffer(0)]],threadgroup float* par for(int hp=int(sg);hp0.0f) total+=lg*exp(m[ulong(hp)*used+g]-top); + } device float* run=splits>1?static_cast(a.p[9])+((head0+hp)*splits+group.z)*(a.dim+2):nullptr; device float* out=static_cast(a.p[3])+(head0+hp)*a.dim; - if(run && !lane) { run[0]=top;run[1]=total; } + if(run && !lane) { run[0]=total>0.0f?top:-INFINITY;run[1]=total; } + else if(!run && a.p[10] && !lane) { + device float* ml=static_cast(a.p[10])+2*(head0+hp); + ml[0]=total>0.0f?top:-INFINITY;ml[1]=total; + } + const float inv_t=total>0.0f?1.0f/total:0.0f; for(int d=lane;d0.0f) sum+=v[(ulong(hp)*used+g)*a.dim+d]*exp(m[ulong(hp)*used+g]-top); + } if(run) run[2+d]=sum; - else out[d]=sum/total; + else out[d]=sum*inv_t; } } } @@ -294,7 +318,11 @@ kernel void poly_attention_join(constant Args& a [[buffer(0)]],uint2 group [[thr w[s]=ws; total+=den*ws; } - const float inv_total=1.0f/total; + if(a.p[10] && !lane) { + device float* ml=static_cast(a.p[10])+2*(ulong(t)*a.heads+h); + ml[0]=total>0.0f?top:-INFINITY;ml[1]=total; + } + const float inv_total=total>0.0f?1.0f/total:0.0f; for(int d=lane;d +#include +#include +#include +#include +#include +#include + +namespace strata::poly { +namespace { + +constexpr int32_t kMaxSparseSlots = 2048; +constexpr int32_t kMaxTransferCap = 64; +constexpr int32_t kPrefillTile = 256; + +struct BasinArgs { + const void* p[20]{}; + int64_t i64[3]{}; + int32_t n[16]{}; + float f[2]{}; +}; +static_assert(sizeof(BasinArgs) == 256); + +struct ResBuilder { + const void* ptrs[20]{}; + gpu::metal::Access modes[20]{}; + size_t count = 0; + + void add(const void* p, gpu::metal::Access m) { + if (!p) return; + ptrs[count] = p; + modes[count] = m; + ++count; + } + + gpu::metal::Resources build() const noexcept { + return {ptrs, count, true, nullptr, modes, nullptr}; + } +}; + +inline void bck(gpu::Error err, const char* what) { + if (err == gpu::kSuccess) return; + gpu::get_last_error(); + throw std::runtime_error(std::string("BasinKV: ") + what + ": " + gpu::error_string(err)); +} + +struct ScopedDevice { + int prev = -1; + bool switched = false; + explicit ScopedDevice(int target) { + if (target < 0) return; + bck(gpu::get_device(&prev), "get_device"); + if (prev != target) { + bck(gpu::set_device(target), "set_device"); + switched = true; + } + } + ~ScopedDevice() { + if (switched && prev >= 0) (void) gpu::set_device(prev); + } + ScopedDevice(const ScopedDevice&) = delete; + ScopedDevice& operator=(const ScopedDevice&) = delete; +}; + +inline gpu::Stream to_stream(void* s) noexcept { return static_cast(s); } + +inline uint32_t grid_div(int64_t n, uint32_t per) noexcept { + return n > 0 ? static_cast((n + static_cast(per) - 1) / static_cast(per)) : 0u; +} + +inline int32_t canonical_ring_slot(int32_t blk, int32_t lstart, int32_t local_blocks) noexcept { + const int32_t cap = local_blocks - 1; + if (cap <= 0) return -1; + int32_t off = (blk - lstart) % cap; + if (off < 0) off += cap; + return lstart + off; +} + +const std::string& basinkv_source() { + static const std::string src = metal_detail::read_source(STRATA_POLY_BASINKV_SOURCE); + return src; +} + +void run_kernel(const char* name, const BasinArgs& a, gpu::Stream stream, + gpu::metal::Grid groups, uint32_t threads, const ResBuilder& rb, + size_t tg_bytes = 0) { + if (!groups.x || !groups.y || !groups.z) return; + if (tg_bytes > 0) tg_bytes = (tg_bytes + 15u) & ~size_t(15); + metal_detail::dispatch("poly_basinkv", basinkv_source(), name, a, stream, + groups, threads, rb.build(), tg_bytes); +} + +const char* pick_wht_kernel(int32_t D, + const char* k64, const char* k128, const char* k192, + const char* k256, const char* k320, const char* k512) { + switch (D) { + case 64: return k64; + case 128: return k128; + case 192: return k192; + case 256: return k256; + case 320: return k320; + case 512: return k512; + default: throw std::invalid_argument("BasinKV: unsupported WHT head_dim"); + } +} + +void dispatch_set_scalars(int32_t* d_seq_len, int32_t seq_val, + int64_t* d_step, int64_t step_val, + long long* d_eff_pos, long long eff_val, + gpu::Stream stream) { + BasinArgs a; + a.p[0] = d_seq_len; + a.p[1] = d_step; + a.p[2] = d_eff_pos; + a.n[0] = seq_val; + a.i64[0] = step_val; + a.i64[1] = static_cast(eff_val); + ResBuilder rb; + rb.add(d_seq_len, gpu::metal::Access::W); + rb.add(d_step, gpu::metal::Access::W); + rb.add(d_eff_pos, gpu::metal::Access::W); + run_kernel("bkv_set_scalars", a, stream, {1, 1, 1}, 1, rb); +} + +void dispatch_stage_q_inc_step(float* dst_q, const float* src_q, int32_t n_elems, + int64_t* d_step, gpu::Stream stream) { + BasinArgs a; + a.p[0] = dst_q; + a.p[1] = src_q; + a.p[2] = d_step; + a.n[0] = n_elems; + ResBuilder rb; + rb.add(dst_q, gpu::metal::Access::W); + rb.add(src_q, gpu::metal::Access::R); + rb.add(d_step, gpu::metal::Access::RW); + run_kernel("bkv_stage_q_inc_step", a, stream, {1, 1, 1}, 256, rb); +} + +void dispatch_fill_i32(int32_t* dst, int64_t n, int32_t val, gpu::Stream stream) { + if (n <= 0) return; + BasinArgs a; + a.p[0] = dst; + a.i64[0] = n; + a.n[0] = val; + ResBuilder rb; + rb.add(dst, gpu::metal::Access::W); + run_kernel("bkv_fill_i32", a, stream, {grid_div(n, 256), 1, 1}, 256, rb); +} + +void dispatch_copy_f32_to_f16_rows(const float* k_in, const float* v_in, + uint16_t* hot_k, uint16_t* hot_v, + int64_t in_row0, int64_t dst_row0, + int32_t count, int32_t row_elems, gpu::Stream stream) { + const int64_t total = static_cast(count) * row_elems; + if (total <= 0) return; + BasinArgs a; + a.p[0] = k_in; + a.p[1] = v_in; + a.p[2] = hot_k; + a.p[3] = hot_v; + a.i64[0] = in_row0; + a.i64[1] = dst_row0; + a.i64[2] = total; + a.n[0] = row_elems; + ResBuilder rb; + rb.add(k_in, gpu::metal::Access::R); + rb.add(v_in, gpu::metal::Access::R); + rb.add(hot_k, gpu::metal::Access::W); + rb.add(hot_v, gpu::metal::Access::W); + run_kernel("bkv_copy_f32_to_f16_rows", a, stream, {grid_div(total, 256), 1, 1}, 256, rb); +} + +void dispatch_recompute_tail_extrema(const uint16_t* hot_k, float* tail_k_min, float* tail_k_max, + int32_t H_kv, int32_t B, int32_t D, int32_t slot, int32_t valid_toks, + gpu::Stream stream) { + const int64_t total = static_cast(H_kv) * D; + if (total <= 0) return; + BasinArgs a; + a.p[0] = hot_k; + a.p[1] = tail_k_min; + a.p[2] = tail_k_max; + a.n[0] = H_kv; + a.n[1] = B; + a.n[2] = D; + a.n[3] = slot; + a.n[4] = valid_toks; + ResBuilder rb; + rb.add(hot_k, gpu::metal::Access::R); + rb.add(tail_k_min, gpu::metal::Access::W); + rb.add(tail_k_max, gpu::metal::Access::W); + run_kernel("bkv_recompute_tail_extrema", a, stream, {grid_div(total, 256), 1, 1}, 256, rb); +} + +void dispatch_zero_f16_rows(uint16_t* hot_k, uint16_t* hot_v, + int64_t dst_row0, int32_t count, int32_t row_elems, gpu::Stream stream) { + const int64_t total = static_cast(count) * row_elems; + if (total <= 0) return; + BasinArgs a; + a.p[0] = hot_k; + a.p[1] = hot_v; + a.i64[0] = dst_row0; + a.i64[1] = total; + a.n[0] = row_elems; + ResBuilder rb; + rb.add(hot_k, gpu::metal::Access::W); + rb.add(hot_v, gpu::metal::Access::W); + run_kernel("bkv_zero_f16_rows", a, stream, {grid_div(total, 256), 1, 1}, 256, rb); +} + +void dispatch_f16_to_f32(const uint16_t* src, float* dst, int64_t n, gpu::Stream stream) { + if (n <= 0) return; + BasinArgs a; + a.p[0] = src; + a.p[1] = dst; + a.i64[0] = n; + ResBuilder rb; + rb.add(src, gpu::metal::Access::R); + rb.add(dst, gpu::metal::Access::W); + run_kernel("bkv_f16_to_f32", a, stream, {grid_div(n, 256), 1, 1}, 256, rb); +} + +struct LayerState { + // Fixed GPU hot slab (FP16 NHD [W * B, H_kv, D]) + uint16_t* hot_k = nullptr; + uint16_t* hot_v = nullptr; + + // Shared host KV tier + UMA GPU device pointers + int8_t* host_k_i8 = nullptr; + int8_t* host_v_i8 = nullptr; + float* host_k_scale = nullptr; + float* host_v_scale = nullptr; + int8_t* dev_host_k_i8 = nullptr; + int8_t* dev_host_v_i8 = nullptr; + float* dev_host_sk = nullptr; + float* dev_host_sv = nullptr; + + // GPU Quest INT8 index + int8_t* idx_k_min = nullptr; + int8_t* idx_k_max = nullptr; + float* idx_smin = nullptr; + float* idx_smax = nullptr; + float* tail_k_min = nullptr; + float* tail_k_max = nullptr; + + // GPU SphereIndex INT4 + uint8_t* sphere_packed = nullptr; + float* sphere_scale = nullptr; + uint16_t* sphere_radii = nullptr; + + // Device scalars for Metal-graph-safe decode + int32_t* d_seq_len = nullptr; + int64_t* d_step = nullptr; + long long* d_eff_pos = nullptr; + + // Page tables & transfer plan + int32_t* gpu_to_cpu = nullptr; // [H_kv, W] + int32_t* cpu_to_gpu = nullptr; // [H_kv, M] + int64_t* last_selected_step = nullptr; // [H_kv, W] + int32_t* src_cpu_blocks = nullptr; // [H_kv, plan_cap] + int32_t* dst_gpu_slots = nullptr; // [H_kv, plan_cap] + uint8_t* admit_valid = nullptr; // [H_kv, plan_cap] + uint64_t* admitted_counter = nullptr; // [1] + float* q_staging = nullptr; // [H_q, D] + + int32_t seq_len = 0; + int32_t flushed_blks = 0; + int64_t step = 0; + bool device_state_dirty = false; +}; + +} // namespace + +struct BasinKvPool::Impl { + BasinKvConfig cfg{}; + bool initialized = false; + bool use_uva = false; + + float* d_wht_signs = nullptr; // [D] + float* shared_scores = nullptr; // [H_kv, M] + + // Non-UVA staging buffers (only allocated when !use_uva) + int8_t* stage_k_dev = nullptr; + int8_t* stage_v_dev = nullptr; + float* stage_sk_dev = nullptr; + float* stage_sv_dev = nullptr; + int32_t* stage_h_dev = nullptr; + int32_t* stage_s_dev = nullptr; + int32_t stage_cap_blks = 0; + + std::vector layers; + + void validate_layer(int32_t l) const { + if (!initialized) throw std::logic_error("BasinKV: pool not initialized"); + if (l < 0 || l >= cfg.n_layers) throw std::out_of_range("BasinKV: layer index out of range"); + } + + void sync_layer_if_dirty(int32_t l, gpu::Stream stream) { + LayerState& st = layers[static_cast(l)]; + if (!st.device_state_dirty) return; + if (stream) bck(gpu::stream_synchronize(stream), "sync_layer_if_dirty(stream)"); + else bck(gpu::device_synchronize(), "sync_layer_if_dirty(device)"); + bck(gpu::memcpy_sync(&st.seq_len, st.d_seq_len, sizeof(int32_t), gpu::kDeviceToHost), "sync d_seq_len"); + bck(gpu::memcpy_sync(&st.step, st.d_step, sizeof(int64_t), gpu::kDeviceToHost), "sync d_step"); + if (st.seq_len <= 0) { + st.flushed_blks = 0; + } else { + const int32_t lazy_flushed = (st.seq_len - 1) / cfg.block_size; + st.flushed_blks = std::min(st.seq_len / cfg.block_size, std::max(st.flushed_blks, lazy_flushed)); + } + st.device_state_dirty = false; + } + + void ensure_completed_tail_flushed(LayerState& st, gpu::Stream stream) { + const int32_t B = cfg.block_size; + const int32_t W = cfg.resident_blocks(); + if (st.seq_len <= 0 || (st.seq_len % B) != 0) return; + const int32_t full_blks = st.seq_len / B; + if (st.flushed_blks >= full_blks) return; + const int32_t blk = full_blks - 1; + const int32_t slot = (st.seq_len <= W * B) ? blk : cfg.tail_slot(); + launch_seal_hot_slot(st, slot, blk, stream); + st.flushed_blks = full_blks; + } + + void launch_topk_evict_rebind(LayerState& st, const float* scores_dev, + int32_t elig_start, int32_t elig_end, + const int32_t* d_seq_len_ptr, const int64_t* d_step_ptr, + int32_t eff_cap, int64_t step, gpu::Stream stream) { + BasinArgs a; + a.p[0] = scores_dev; + a.p[1] = st.gpu_to_cpu; + a.p[2] = st.cpu_to_gpu; + a.p[3] = st.last_selected_step; + a.p[4] = st.src_cpu_blocks; + a.p[5] = st.dst_gpu_slots; + a.p[6] = st.admit_valid; + a.p[7] = st.admitted_counter; + a.p[8] = d_seq_len_ptr; + a.p[9] = d_step_ptr; + a.n[0] = cfg.n_head_kv; + a.n[1] = cfg.max_blocks(); + a.n[2] = cfg.resident_blocks(); + a.n[3] = cfg.block_size; + a.n[4] = cfg.local_blocks; + a.n[5] = cfg.sink_blocks; + a.n[6] = cfg.local_slot_start(); + a.n[7] = elig_start; + a.n[8] = elig_end; + a.n[9] = eff_cap; + a.n[10] = cfg.successor_cofetch ? 1 : 0; + a.i64[0] = step; + + ResBuilder rb; + rb.add(scores_dev, gpu::metal::Access::R); + rb.add(st.gpu_to_cpu, gpu::metal::Access::RW); + rb.add(st.cpu_to_gpu, gpu::metal::Access::RW); + rb.add(st.last_selected_step, gpu::metal::Access::RW); + rb.add(st.src_cpu_blocks, gpu::metal::Access::W); + rb.add(st.dst_gpu_slots, gpu::metal::Access::W); + rb.add(st.admit_valid, gpu::metal::Access::W); + rb.add(st.admitted_counter, gpu::metal::Access::RW); + rb.add(d_seq_len_ptr, gpu::metal::Access::R); + rb.add(d_step_ptr, gpu::metal::Access::R); + run_kernel("bkv_topk_evict_rebind", a, stream, {static_cast(cfg.n_head_kv), 1, 1}, 256, rb); + } + + void launch_flush_rotate_seal(LayerState& st, int32_t cpu_M, int32_t cpu_dst_blk, + int8_t* ck, int8_t* cv, float* csk, float* csv, + int32_t static_pos, int64_t step, + const long long* d_pos_ptr, const int32_t* d_seq_len_ptr, + const int64_t* d_step_ptr, gpu::Stream stream) { + const bool is_sphere = cfg.index_mode == BasinIndexMode::kSphereInt4; + const bool is_wht4 = cfg.host_quant == BasinHostQuant::kWhtInt4; + BasinArgs a; + a.p[0] = st.hot_k; + a.p[1] = st.hot_v; + a.p[2] = ck; + a.p[3] = cv; + a.p[4] = csk; + a.p[5] = csv; + a.p[6] = st.gpu_to_cpu; + a.p[7] = st.cpu_to_gpu; + a.p[8] = st.last_selected_step; + if (is_sphere) { + a.p[9] = st.sphere_packed; + a.p[10] = st.sphere_scale; + a.p[11] = st.sphere_radii; + } else { + a.p[9] = st.tail_k_min; + a.p[10] = st.tail_k_max; + a.p[11] = st.idx_k_min; + a.p[12] = st.idx_k_max; + a.p[13] = st.idx_smin; + a.p[14] = st.idx_smax; + } + a.p[15] = d_wht_signs; + a.p[16] = d_pos_ptr; + a.p[17] = d_seq_len_ptr; + a.p[18] = d_step_ptr; + a.n[0] = cfg.n_head_kv; + a.n[1] = cfg.resident_blocks(); + a.n[2] = cfg.max_blocks(); + a.n[3] = cfg.block_size; + a.n[4] = cfg.head_dim; + a.n[5] = cfg.effective_rope_dim(); + a.n[6] = cfg.max_seq_len; + a.n[7] = cfg.local_blocks; + a.n[8] = cfg.local_slot_start(); + a.n[9] = cpu_M; + a.n[10] = cpu_dst_blk; + a.n[11] = static_pos; + a.n[12] = is_sphere ? 1 : 0; + a.n[13] = is_wht4 ? 1 : 0; + a.i64[0] = step; + + ResBuilder rb; + rb.add(st.hot_k, gpu::metal::Access::RW); + rb.add(st.hot_v, gpu::metal::Access::RW); + rb.add(ck, gpu::metal::Access::W); + rb.add(cv, gpu::metal::Access::W); + rb.add(csk, gpu::metal::Access::W); + rb.add(csv, gpu::metal::Access::W); + rb.add(st.gpu_to_cpu, gpu::metal::Access::RW); + rb.add(st.cpu_to_gpu, gpu::metal::Access::RW); + rb.add(st.last_selected_step, gpu::metal::Access::RW); + if (is_sphere) { + rb.add(st.sphere_packed, gpu::metal::Access::W); + rb.add(st.sphere_scale, gpu::metal::Access::W); + rb.add(st.sphere_radii, gpu::metal::Access::W); + } else { + rb.add(st.tail_k_min, gpu::metal::Access::R); + rb.add(st.tail_k_max, gpu::metal::Access::R); + rb.add(st.idx_k_min, gpu::metal::Access::W); + rb.add(st.idx_k_max, gpu::metal::Access::W); + rb.add(st.idx_smin, gpu::metal::Access::W); + rb.add(st.idx_smax, gpu::metal::Access::W); + } + rb.add(d_wht_signs, gpu::metal::Access::R); + rb.add(d_pos_ptr, gpu::metal::Access::R); + rb.add(d_seq_len_ptr, gpu::metal::Access::R); + rb.add(d_step_ptr, gpu::metal::Access::R); + + const char* kname = (!is_sphere && !is_wht4) + ? "bkv_flush_rotate_seal_quest_i8" + : pick_wht_kernel(cfg.head_dim, + "bkv_flush_rotate_seal_wht_64", "bkv_flush_rotate_seal_wht_128", + "bkv_flush_rotate_seal_wht_192", "bkv_flush_rotate_seal_wht_256", + "bkv_flush_rotate_seal_wht_320", "bkv_flush_rotate_seal_wht_512"); + run_kernel(kname, a, stream, {static_cast(cfg.n_head_kv), 1, 1}, 256, rb); + } + + void launch_append_decode(LayerState& st, const float* k_f32, const float* v_f32, + const long long* d_pos_ptr, const int64_t* d_step_ptr, + int32_t static_pos, int64_t static_step, gpu::Stream stream) { + BasinArgs a; + a.p[0] = st.hot_k; + a.p[1] = st.hot_v; + a.p[2] = st.tail_k_min; + a.p[3] = st.tail_k_max; + a.p[4] = st.gpu_to_cpu; + a.p[5] = st.cpu_to_gpu; + a.p[6] = st.last_selected_step; + a.p[7] = k_f32; + a.p[8] = v_f32; + a.p[9] = d_pos_ptr; + a.p[10] = st.d_seq_len; + a.p[11] = d_step_ptr; + a.p[12] = st.d_eff_pos; + a.n[0] = static_pos; + a.n[1] = cfg.n_head_kv; + a.n[2] = cfg.resident_blocks(); + a.n[3] = cfg.max_blocks(); + a.n[4] = cfg.block_size; + a.n[5] = cfg.head_dim; + a.n[6] = cfg.max_seq_len; + a.i64[0] = static_step; + + ResBuilder rb; + rb.add(st.hot_k, gpu::metal::Access::W); + rb.add(st.hot_v, gpu::metal::Access::W); + rb.add(st.tail_k_min, gpu::metal::Access::RW); + rb.add(st.tail_k_max, gpu::metal::Access::RW); + rb.add(st.gpu_to_cpu, gpu::metal::Access::RW); + rb.add(st.cpu_to_gpu, gpu::metal::Access::RW); + rb.add(st.last_selected_step, gpu::metal::Access::W); + rb.add(k_f32, gpu::metal::Access::R); + rb.add(v_f32, gpu::metal::Access::R); + rb.add(d_pos_ptr, gpu::metal::Access::R); + rb.add(st.d_seq_len, gpu::metal::Access::RW); + rb.add(d_step_ptr, gpu::metal::Access::R); + rb.add(st.d_eff_pos, gpu::metal::Access::W); + run_kernel("bkv_append_decode_token", a, stream, {1, 1, 1}, 256, rb); + } + + void launch_score(int32_t l, const float* q_dev, float* out_dev, + int32_t elig_start, int32_t elig_end, const int32_t* d_seq_len_ptr, + gpu::Stream stream) { + LayerState& st = layers[static_cast(l)]; + const int32_t M = cfg.max_blocks(); + const int32_t G = cfg.gqa_group(); + const int32_t rm = static_cast(cfg.gqa_reduce); + if (cfg.index_mode == BasinIndexMode::kSphereInt4) { + BasinArgs a; + a.p[0] = q_dev; + a.p[1] = st.sphere_packed; + a.p[2] = st.sphere_scale; + a.p[3] = st.sphere_radii; + a.p[4] = d_wht_signs; + a.p[5] = out_dev; + a.p[6] = d_seq_len_ptr; + a.n[0] = cfg.n_head_q; + a.n[1] = cfg.n_head_kv; + a.n[2] = M; + a.n[3] = cfg.block_size; + a.n[4] = cfg.local_blocks; + a.n[5] = cfg.effective_rope_dim(); + a.n[6] = elig_start; + a.n[7] = elig_end; + a.n[8] = rm; + a.f[0] = cfg.sphere_beta; + + ResBuilder rb; + rb.add(q_dev, gpu::metal::Access::R); + rb.add(st.sphere_packed, gpu::metal::Access::R); + rb.add(st.sphere_scale, gpu::metal::Access::R); + rb.add(st.sphere_radii, gpu::metal::Access::R); + rb.add(d_wht_signs, gpu::metal::Access::R); + rb.add(out_dev, gpu::metal::Access::W); + rb.add(d_seq_len_ptr, gpu::metal::Access::R); + + const char* kname = pick_wht_kernel(cfg.head_dim, + "bkv_sphere_score_64", "bkv_sphere_score_128", "bkv_sphere_score_192", + "bkv_sphere_score_256", "bkv_sphere_score_320", "bkv_sphere_score_512"); + run_kernel(kname, a, stream, {grid_div(M, 64), static_cast(cfg.n_head_kv), 1}, 256, rb); + } else { + BasinArgs a; + a.p[0] = q_dev; + a.p[1] = st.idx_k_min; + a.p[2] = st.idx_k_max; + a.p[3] = st.idx_smin; + a.p[4] = st.idx_smax; + a.p[5] = out_dev; + a.p[6] = d_seq_len_ptr; + a.n[0] = cfg.n_head_q; + a.n[1] = cfg.n_head_kv; + a.n[2] = M; + a.n[3] = cfg.block_size; + a.n[4] = cfg.local_blocks; + a.n[5] = cfg.head_dim; + a.n[6] = elig_start; + a.n[7] = elig_end; + a.n[8] = rm; + a.f[0] = cfg.effective_alpha(); + + ResBuilder rb; + rb.add(q_dev, gpu::metal::Access::R); + rb.add(st.idx_k_min, gpu::metal::Access::R); + rb.add(st.idx_k_max, gpu::metal::Access::R); + rb.add(st.idx_smin, gpu::metal::Access::R); + rb.add(st.idx_smax, gpu::metal::Access::R); + rb.add(out_dev, gpu::metal::Access::W); + rb.add(d_seq_len_ptr, gpu::metal::Access::R); + + const char* kname = "bkv_quest_score_general"; + if (cfg.head_dim == 256 && G * 256 <= 2048) kname = "bkv_quest_score_256"; + else if (cfg.head_dim == 128 && G * 128 <= 2048) kname = "bkv_quest_score_128"; + run_kernel(kname, a, stream, {grid_div(M, 32), static_cast(cfg.n_head_kv), 1}, 256, rb); + } + } + + void launch_uva_gather(LayerState& st, int32_t eff_cap, gpu::Stream stream) { + const uint32_t gx = static_cast(cfg.n_head_kv * eff_cap); + BasinArgs a; + a.p[0] = st.dev_host_k_i8; + a.p[1] = st.dev_host_v_i8; + a.p[2] = st.dev_host_sk; + a.p[3] = st.dev_host_sv; + a.p[4] = st.hot_k; + a.p[5] = st.hot_v; + a.p[6] = st.src_cpu_blocks; + a.p[7] = st.dst_gpu_slots; + a.p[8] = st.admit_valid; + a.p[9] = d_wht_signs; + a.n[0] = cfg.n_head_kv; + a.n[1] = eff_cap; + a.n[2] = cfg.max_blocks(); + a.n[3] = cfg.resident_blocks(); + a.n[4] = cfg.block_size; + a.n[5] = cfg.head_dim; + + ResBuilder rb; + rb.add(st.dev_host_k_i8, gpu::metal::Access::R); + rb.add(st.dev_host_v_i8, gpu::metal::Access::R); + rb.add(st.dev_host_sk, gpu::metal::Access::R); + rb.add(st.dev_host_sv, gpu::metal::Access::R); + rb.add(st.hot_k, gpu::metal::Access::W); + rb.add(st.hot_v, gpu::metal::Access::W); + rb.add(st.src_cpu_blocks, gpu::metal::Access::R); + rb.add(st.dst_gpu_slots, gpu::metal::Access::R); + rb.add(st.admit_valid, gpu::metal::Access::R); + if (cfg.host_quant == BasinHostQuant::kWhtInt4) { + rb.add(d_wht_signs, gpu::metal::Access::R); + const char* kname = pick_wht_kernel(cfg.head_dim, + "bkv_uva_gather_wht4_64", "bkv_uva_gather_wht4_128", "bkv_uva_gather_wht4_192", + "bkv_uva_gather_wht4_256", "bkv_uva_gather_wht4_320", "bkv_uva_gather_wht4_512"); + run_kernel(kname, a, stream, {gx, 1, 1}, 256, rb); + } else { + run_kernel("bkv_uva_gather_i8", a, stream, {gx, 1, 1}, 256, rb); + } + } + + void launch_staged_gather(LayerState& st, int32_t m, gpu::Stream stream) { + BasinArgs a; + a.p[0] = stage_k_dev; + a.p[1] = stage_v_dev; + a.p[2] = stage_sk_dev; + a.p[3] = stage_sv_dev; + a.p[4] = stage_h_dev; + a.p[5] = stage_s_dev; + a.p[6] = st.hot_k; + a.p[7] = st.hot_v; + a.p[8] = d_wht_signs; + a.n[0] = m; + a.n[1] = cfg.n_head_kv; + a.n[2] = cfg.resident_blocks(); + a.n[3] = cfg.block_size; + a.n[4] = cfg.head_dim; + + ResBuilder rb; + rb.add(stage_k_dev, gpu::metal::Access::R); + rb.add(stage_v_dev, gpu::metal::Access::R); + rb.add(stage_sk_dev, gpu::metal::Access::R); + rb.add(stage_sv_dev, gpu::metal::Access::R); + rb.add(stage_h_dev, gpu::metal::Access::R); + rb.add(stage_s_dev, gpu::metal::Access::R); + rb.add(st.hot_k, gpu::metal::Access::W); + rb.add(st.hot_v, gpu::metal::Access::W); + if (cfg.host_quant == BasinHostQuant::kWhtInt4) { + rb.add(d_wht_signs, gpu::metal::Access::R); + const char* kname = pick_wht_kernel(cfg.head_dim, + "bkv_staged_gather_wht4_64", "bkv_staged_gather_wht4_128", "bkv_staged_gather_wht4_192", + "bkv_staged_gather_wht4_256", "bkv_staged_gather_wht4_320", "bkv_staged_gather_wht4_512"); + run_kernel(kname, a, stream, {static_cast(m), 1, 1}, 256, rb); + } else { + run_kernel("bkv_staged_gather_i8", a, stream, {static_cast(m), 1, 1}, 256, rb); + } + } + + void run_non_uva_gather(LayerState& st, int32_t eff_cap, gpu::Stream stream) { + const int32_t total_tasks = cfg.n_head_kv * eff_cap; + std::vector h_src(static_cast(total_tasks)); + std::vector h_dst(static_cast(total_tasks)); + std::vector h_val(static_cast(total_tasks)); + bck(gpu::memcpy_async(h_src.data(), st.src_cpu_blocks, h_src.size() * sizeof(int32_t), gpu::kDeviceToHost, stream), "non-uva src"); + bck(gpu::memcpy_async(h_dst.data(), st.dst_gpu_slots, h_dst.size() * sizeof(int32_t), gpu::kDeviceToHost, stream), "non-uva dst"); + bck(gpu::memcpy_async(h_val.data(), st.admit_valid, h_val.size() * sizeof(uint8_t), gpu::kDeviceToHost, stream), "non-uva val"); + bck(gpu::stream_synchronize(stream), "non-uva plan sync"); + + const int32_t M = cfg.max_blocks(); + const int32_t W = cfg.resident_blocks(); + const int32_t B = cfg.block_size; + const size_t hd = static_cast(cfg.host_kv_dim()); + const size_t be = static_cast(B) * hd; + + std::vector pk, pv; + std::vector psk, psv; + std::vector ph, ps; + for (int32_t t = 0; t < total_tasks; ++t) { + if (!h_val[static_cast(t)]) continue; + const int32_t h = t / eff_cap; + const int32_t sb = h_src[static_cast(t)]; + const int32_t ds = h_dst[static_cast(t)]; + if (h < 0 || h >= cfg.n_head_kv || sb < 0 || sb >= M || ds < 0 || ds >= W) continue; + const size_t idx = static_cast(h) * static_cast(M) + static_cast(sb); + const size_t cur = ph.size(); + pk.resize((cur + 1) * be); + pv.resize((cur + 1) * be); + psk.resize((cur + 1) * static_cast(B)); + psv.resize((cur + 1) * static_cast(B)); + std::memcpy(pk.data() + cur * be, st.host_k_i8 + idx * be, be); + std::memcpy(pv.data() + cur * be, st.host_v_i8 + idx * be, be); + std::memcpy(psk.data() + cur * static_cast(B), st.host_k_scale + idx * static_cast(B), static_cast(B) * sizeof(float)); + std::memcpy(psv.data() + cur * static_cast(B), st.host_v_scale + idx * static_cast(B), static_cast(B) * sizeof(float)); + ph.push_back(h); + ps.push_back(ds); + } + const int32_t n_valid = static_cast(ph.size()); + if (n_valid <= 0) return; + for (int32_t off = 0; off < n_valid; off += stage_cap_blks) { + const int32_t m = std::min(n_valid - off, stage_cap_blks); + bck(gpu::memcpy_async(stage_k_dev, pk.data() + static_cast(off) * be, static_cast(m) * be, gpu::kHostToDevice, stream), "non-uva h2d k"); + bck(gpu::memcpy_async(stage_v_dev, pv.data() + static_cast(off) * be, static_cast(m) * be, gpu::kHostToDevice, stream), "non-uva h2d v"); + bck(gpu::memcpy_async(stage_sk_dev, psk.data() + static_cast(off) * B, static_cast(m) * B * sizeof(float), gpu::kHostToDevice, stream), "non-uva h2d sk"); + bck(gpu::memcpy_async(stage_sv_dev, psv.data() + static_cast(off) * B, static_cast(m) * B * sizeof(float), gpu::kHostToDevice, stream), "non-uva h2d sv"); + bck(gpu::memcpy_async(stage_h_dev, ph.data() + off, static_cast(m) * sizeof(int32_t), gpu::kHostToDevice, stream), "non-uva h2d h"); + bck(gpu::memcpy_async(stage_s_dev, ps.data() + off, static_cast(m) * sizeof(int32_t), gpu::kHostToDevice, stream), "non-uva h2d s"); + launch_staged_gather(st, m, stream); + bck(gpu::stream_synchronize(stream), "non-uva chunk sync"); + } + } + + void launch_seal_prefill_blocks(LayerState& st, const float* k_f32, const float* v_f32, + int32_t blk0, int32_t n_blks, int32_t in_tok_offset, gpu::Stream stream) { + if (n_blks <= 0) return; + const bool is_sphere = cfg.index_mode == BasinIndexMode::kSphereInt4; + const bool is_wht4 = cfg.host_quant == BasinHostQuant::kWhtInt4; + + auto dispatch_one = [&](int8_t* ck, int8_t* cv, float* csk, float* csv, + int32_t cpu_M, int32_t b0, int32_t cb0, int32_t nb, int32_t ito) { + BasinArgs a; + a.p[0] = k_f32; + a.p[1] = v_f32; + a.p[2] = ck; + a.p[3] = cv; + a.p[4] = csk; + a.p[5] = csv; + if (is_sphere) { + a.p[6] = st.sphere_packed; + a.p[7] = st.sphere_scale; + a.p[8] = st.sphere_radii; + } else { + a.p[6] = st.idx_k_min; + a.p[7] = st.idx_k_max; + a.p[8] = st.idx_smin; + a.p[9] = st.idx_smax; + } + a.p[10] = d_wht_signs; + a.n[0] = cfg.n_head_kv; + a.n[1] = cfg.max_blocks(); + a.n[2] = cpu_M; + a.n[3] = cfg.block_size; + a.n[4] = cfg.head_dim; + a.n[5] = cfg.effective_rope_dim(); + a.n[6] = b0; + a.n[7] = cb0; + a.n[8] = nb; + a.n[9] = ito; + a.n[10] = is_sphere ? 1 : 0; + a.n[11] = is_wht4 ? 1 : 0; + + ResBuilder rb; + rb.add(k_f32, gpu::metal::Access::R); + rb.add(v_f32, gpu::metal::Access::R); + rb.add(ck, gpu::metal::Access::W); + rb.add(cv, gpu::metal::Access::W); + rb.add(csk, gpu::metal::Access::W); + rb.add(csv, gpu::metal::Access::W); + if (is_sphere) { + rb.add(st.sphere_packed, gpu::metal::Access::W); + rb.add(st.sphere_scale, gpu::metal::Access::W); + rb.add(st.sphere_radii, gpu::metal::Access::W); + } else { + rb.add(st.idx_k_min, gpu::metal::Access::W); + rb.add(st.idx_k_max, gpu::metal::Access::W); + rb.add(st.idx_smin, gpu::metal::Access::W); + rb.add(st.idx_smax, gpu::metal::Access::W); + } + rb.add(d_wht_signs, gpu::metal::Access::R); + + const gpu::metal::Grid grid{static_cast(nb), static_cast(cfg.n_head_kv), 1}; + if (!is_sphere && !is_wht4) { + const size_t smem = static_cast(2 * cfg.head_dim) * sizeof(float); + run_kernel("bkv_prefill_seal_quest_i8", a, stream, grid, 256, rb, smem); + } else { + const char* kname = pick_wht_kernel(cfg.head_dim, + "bkv_prefill_seal_wht_64", "bkv_prefill_seal_wht_128", "bkv_prefill_seal_wht_192", + "bkv_prefill_seal_wht_256", "bkv_prefill_seal_wht_320", "bkv_prefill_seal_wht_512"); + run_kernel(kname, a, stream, grid, 256, rb); + } + }; + + if (use_uva) { + dispatch_one(st.dev_host_k_i8, st.dev_host_v_i8, st.dev_host_sk, st.dev_host_sv, + cfg.max_blocks(), blk0, blk0, n_blks, in_tok_offset); + } else { + const int32_t M = cfg.max_blocks(); + const int32_t B = cfg.block_size; + const size_t hd = static_cast(cfg.host_kv_dim()); + const size_t be = static_cast(B) * hd; + const int32_t max_tile = std::max(1, stage_cap_blks / cfg.n_head_kv); + for (int32_t off = 0; off < n_blks; off += max_tile) { + const int32_t nb = std::min(n_blks - off, max_tile); + dispatch_one(stage_k_dev, stage_v_dev, stage_sk_dev, stage_sv_dev, + nb, blk0 + off, 0, nb, in_tok_offset + off * B); + for (int32_t h = 0; h < cfg.n_head_kv; ++h) { + const size_t dst_off = static_cast(h) * static_cast(M) + static_cast(blk0 + off); + const size_t src_off = static_cast(h) * static_cast(nb); + bck(gpu::memcpy_async(st.host_k_i8 + dst_off * be, stage_k_dev + src_off * be, static_cast(nb) * be, gpu::kDeviceToHost, stream), "non-uva prefill d2h k"); + bck(gpu::memcpy_async(st.host_v_i8 + dst_off * be, stage_v_dev + src_off * be, static_cast(nb) * be, gpu::kDeviceToHost, stream), "non-uva prefill d2h v"); + bck(gpu::memcpy_async(st.host_k_scale + dst_off * B, stage_sk_dev + src_off * B, static_cast(nb) * B * sizeof(float), gpu::kDeviceToHost, stream), "non-uva prefill d2h sk"); + bck(gpu::memcpy_async(st.host_v_scale + dst_off * B, stage_sv_dev + src_off * B, static_cast(nb) * B * sizeof(float), gpu::kDeviceToHost, stream), "non-uva prefill d2h sv"); + } + bck(gpu::stream_synchronize(stream), "non-uva prefill sync"); + } + } + } + + void launch_seal_hot_slot(LayerState& st, int32_t src_slot, int32_t blk, gpu::Stream stream) { + const bool is_sphere = cfg.index_mode == BasinIndexMode::kSphereInt4; + const bool is_wht4 = cfg.host_quant == BasinHostQuant::kWhtInt4; + + auto dispatch_one = [&](int8_t* ck, int8_t* cv, float* csk, float* csv, int32_t cpu_M, int32_t host_blk) { + BasinArgs a; + a.p[0] = st.hot_k; + a.p[1] = st.hot_v; + a.p[2] = ck; + a.p[3] = cv; + a.p[4] = csk; + a.p[5] = csv; + if (is_sphere) { + a.p[6] = st.sphere_packed; + a.p[7] = st.sphere_scale; + a.p[8] = st.sphere_radii; + } else { + a.p[6] = st.idx_k_min; + a.p[7] = st.idx_k_max; + a.p[8] = st.idx_smin; + a.p[9] = st.idx_smax; + } + a.p[10] = d_wht_signs; + a.n[0] = cfg.n_head_kv; + a.n[1] = cfg.max_blocks(); + a.n[2] = cpu_M; + a.n[3] = cfg.block_size; + a.n[4] = cfg.head_dim; + a.n[5] = cfg.effective_rope_dim(); + a.n[6] = src_slot; + a.n[7] = blk; + a.n[8] = host_blk; + a.n[9] = is_sphere ? 1 : 0; + a.n[10] = is_wht4 ? 1 : 0; + + ResBuilder rb; + rb.add(st.hot_k, gpu::metal::Access::R); + rb.add(st.hot_v, gpu::metal::Access::R); + rb.add(ck, gpu::metal::Access::W); + rb.add(cv, gpu::metal::Access::W); + rb.add(csk, gpu::metal::Access::W); + rb.add(csv, gpu::metal::Access::W); + if (is_sphere) { + rb.add(st.sphere_packed, gpu::metal::Access::W); + rb.add(st.sphere_scale, gpu::metal::Access::W); + rb.add(st.sphere_radii, gpu::metal::Access::W); + } else { + rb.add(st.idx_k_min, gpu::metal::Access::W); + rb.add(st.idx_k_max, gpu::metal::Access::W); + rb.add(st.idx_smin, gpu::metal::Access::W); + rb.add(st.idx_smax, gpu::metal::Access::W); + } + rb.add(d_wht_signs, gpu::metal::Access::R); + + const gpu::metal::Grid grid{static_cast(cfg.n_head_kv), 1, 1}; + if (!is_sphere && !is_wht4) { + const size_t smem = static_cast(2 * cfg.head_dim) * sizeof(float); + run_kernel("bkv_seal_hot_slot_quest_i8", a, stream, grid, 256, rb, smem); + } else { + const char* kname = pick_wht_kernel(cfg.head_dim, + "bkv_seal_hot_slot_wht_64", "bkv_seal_hot_slot_wht_128", "bkv_seal_hot_slot_wht_192", + "bkv_seal_hot_slot_wht_256", "bkv_seal_hot_slot_wht_320", "bkv_seal_hot_slot_wht_512"); + run_kernel(kname, a, stream, grid, 256, rb); + } + }; + + if (use_uva) { + dispatch_one(st.dev_host_k_i8, st.dev_host_v_i8, st.dev_host_sk, st.dev_host_sv, cfg.max_blocks(), blk); + } else { + dispatch_one(stage_k_dev, stage_v_dev, stage_sk_dev, stage_sv_dev, 1, 0); + const int32_t M = cfg.max_blocks(); + const int32_t B = cfg.block_size; + const size_t hd = static_cast(cfg.host_kv_dim()); + const size_t be = static_cast(B) * hd; + for (int32_t h = 0; h < cfg.n_head_kv; ++h) { + const size_t dst_off = static_cast(h) * static_cast(M) + static_cast(blk); + bck(gpu::memcpy_async(st.host_k_i8 + dst_off * be, stage_k_dev + static_cast(h) * be, be, gpu::kDeviceToHost, stream), "non-uva slot d2h k"); + bck(gpu::memcpy_async(st.host_v_i8 + dst_off * be, stage_v_dev + static_cast(h) * be, be, gpu::kDeviceToHost, stream), "non-uva slot d2h v"); + bck(gpu::memcpy_async(st.host_k_scale + dst_off * B, stage_sk_dev + static_cast(h) * B, static_cast(B) * sizeof(float), gpu::kDeviceToHost, stream), "non-uva slot d2h sk"); + bck(gpu::memcpy_async(st.host_v_scale + dst_off * B, stage_sv_dev + static_cast(h) * B, static_cast(B) * sizeof(float), gpu::kDeviceToHost, stream), "non-uva slot d2h sv"); + } + bck(gpu::stream_synchronize(stream), "non-uva slot sync"); + } + } + + void rebuild_hot_slab_for_len(int32_t l, int32_t new_seq_len, bool preserve_sparse, + int32_t preserve_open_tail_from_slot, gpu::Stream stream) { + LayerState& st = layers[static_cast(l)]; + const int32_t H = cfg.n_head_kv; + const int32_t W = cfg.resident_blocks(); + const int32_t M = cfg.max_blocks(); + const int32_t B = cfg.block_size; + const int32_t D = cfg.head_dim; + const int32_t sink = cfg.sink_blocks; + const int32_t local = cfg.local_blocks; + const int32_t lstart = cfg.local_slot_start(); + const int32_t tslot = cfg.tail_slot(); + const int32_t row_elems = H * D; + + std::vector old_g2c; + if (preserve_sparse && new_seq_len > W * B) { + old_g2c.resize(static_cast(H) * static_cast(W), -1); + bck(gpu::memcpy_async(old_g2c.data(), st.gpu_to_cpu, old_g2c.size() * sizeof(int32_t), + gpu::kDeviceToHost, stream), "reseed read g2c"); + bck(gpu::stream_synchronize(stream), "reseed sync g2c"); + } + + const int32_t full_blks = new_seq_len / B; + const int32_t open_valid = new_seq_len % B; + const int32_t n_blks = (new_seq_len + B - 1) / B; + const int32_t last_blk = (new_seq_len > 0) ? ((new_seq_len - 1) / B) : -1; + const int32_t target_tail_slot = (new_seq_len <= W * B) ? last_blk : tslot; + + std::vector saved_tail_k, saved_tail_v; + if (open_valid > 0 && preserve_open_tail_from_slot >= 0) { + const size_t n_h = static_cast(open_valid) * static_cast(row_elems); + saved_tail_k.resize(n_h); + saved_tail_v.resize(n_h); + const size_t src_off = static_cast(preserve_open_tail_from_slot) * static_cast(B) * static_cast(row_elems); + bck(gpu::memcpy_async(saved_tail_k.data(), st.hot_k + src_off, n_h * sizeof(uint16_t), gpu::kDeviceToHost, stream), "save open tail k"); + bck(gpu::memcpy_async(saved_tail_v.data(), st.hot_v + src_off, n_h * sizeof(uint16_t), gpu::kDeviceToHost, stream), "save open tail v"); + bck(gpu::stream_synchronize(stream), "save open tail sync"); + } + + std::vector g2c(static_cast(H) * static_cast(W), -1); + std::vector c2g(static_cast(H) * static_cast(M), -1); + std::vector lrs(static_cast(H) * static_cast(W), st.step); + + if (new_seq_len > 0) { + if (new_seq_len <= W * B) { + for (int32_t h = 0; h < H; ++h) { + for (int32_t b = 0; b < n_blks; ++b) { + g2c[static_cast(h) * W + b] = b; + c2g[static_cast(h) * M + b] = b; + } + } + } else { + const int32_t ring_start_blk = last_blk - (local - 1); + for (int32_t h = 0; h < H; ++h) { + int32_t* g_row = g2c.data() + static_cast(h) * W; + int32_t* c_row = c2g.data() + static_cast(h) * M; + for (int32_t b = 0; b < sink; ++b) { + g_row[b] = b; + c_row[b] = b; + } + for (int32_t b = ring_start_blk; b < last_blk; ++b) { + int32_t rs = canonical_ring_slot(b, lstart, local); + g_row[rs] = b; + c_row[b] = rs; + } + g_row[tslot] = last_blk; + c_row[last_blk] = tslot; + + if (!old_g2c.empty()) { + const int32_t* og = old_g2c.data() + static_cast(h) * W; + for (int32_t s = sink; s < lstart; ++s) { + int32_t b = og[s]; + if (b >= sink && b < ring_start_blk && c_row[b] < 0) { + g_row[s] = b; + c_row[b] = s; + } + } + } + int32_t cand = ring_start_blk - 1; + for (int32_t s = sink; s < lstart; ++s) { + if (g_row[s] >= 0) continue; + while (cand >= sink && c_row[cand] >= 0) --cand; + if (cand >= sink) { + g_row[s] = cand; + c_row[cand] = s; + --cand; + } + } + } + } + } + + bck(gpu::memcpy_async(st.gpu_to_cpu, g2c.data(), g2c.size() * sizeof(int32_t), gpu::kHostToDevice, stream), "reseed g2c"); + bck(gpu::memcpy_async(st.cpu_to_gpu, c2g.data(), c2g.size() * sizeof(int32_t), gpu::kHostToDevice, stream), "reseed c2g"); + bck(gpu::memcpy_async(st.last_selected_step, lrs.data(), lrs.size() * sizeof(int64_t), gpu::kHostToDevice, stream), "reseed lrs"); + + if (full_blks > 0) { + if (use_uva) { + BasinArgs a; + a.p[0] = st.dev_host_k_i8; + a.p[1] = st.dev_host_v_i8; + a.p[2] = st.dev_host_sk; + a.p[3] = st.dev_host_sv; + a.p[4] = st.gpu_to_cpu; + a.p[5] = st.hot_k; + a.p[6] = st.hot_v; + a.p[7] = d_wht_signs; + a.n[0] = H; + a.n[1] = M; + a.n[2] = W; + a.n[3] = B; + a.n[4] = D; + a.n[5] = full_blks; + + ResBuilder rb; + rb.add(st.dev_host_k_i8, gpu::metal::Access::R); + rb.add(st.dev_host_v_i8, gpu::metal::Access::R); + rb.add(st.dev_host_sk, gpu::metal::Access::R); + rb.add(st.dev_host_sv, gpu::metal::Access::R); + rb.add(st.gpu_to_cpu, gpu::metal::Access::R); + rb.add(st.hot_k, gpu::metal::Access::W); + rb.add(st.hot_v, gpu::metal::Access::W); + const gpu::metal::Grid grid{static_cast(W), static_cast(H), 1}; + if (cfg.host_quant == BasinHostQuant::kWhtInt4) { + rb.add(d_wht_signs, gpu::metal::Access::R); + const char* kname = pick_wht_kernel(D, + "bkv_reseed_wht4_64", "bkv_reseed_wht4_128", "bkv_reseed_wht4_192", + "bkv_reseed_wht4_256", "bkv_reseed_wht4_320", "bkv_reseed_wht4_512"); + run_kernel(kname, a, stream, grid, 256, rb); + } else { + run_kernel("bkv_reseed_i8", a, stream, grid, 256, rb); + } + } else { + const size_t hd = static_cast(cfg.host_kv_dim()); + const size_t be = static_cast(B) * hd; + std::vector pk, pv; + std::vector psk, psv; + std::vector ph, ps; + for (int32_t h = 0; h < H; ++h) { + for (int32_t s = 0; s < W; ++s) { + int32_t blk = g2c[static_cast(h) * W + s]; + if (blk < 0 || blk >= full_blks) continue; + const size_t idx = static_cast(h) * M + static_cast(blk); + const size_t cur = ph.size(); + pk.resize((cur + 1) * be); pv.resize((cur + 1) * be); + psk.resize((cur + 1) * B); psv.resize((cur + 1) * B); + std::memcpy(pk.data() + cur * be, st.host_k_i8 + idx * be, be); + std::memcpy(pv.data() + cur * be, st.host_v_i8 + idx * be, be); + std::memcpy(psk.data() + cur * B, st.host_k_scale + idx * B, static_cast(B) * sizeof(float)); + std::memcpy(psv.data() + cur * B, st.host_v_scale + idx * B, static_cast(B) * sizeof(float)); + ph.push_back(h); ps.push_back(s); + } + } + const int32_t nv = static_cast(ph.size()); + for (int32_t off = 0; off < nv; off += stage_cap_blks) { + const int32_t m = std::min(nv - off, stage_cap_blks); + bck(gpu::memcpy_async(stage_k_dev, pk.data() + static_cast(off) * be, static_cast(m) * be, gpu::kHostToDevice, stream), "reseed stage k"); + bck(gpu::memcpy_async(stage_v_dev, pv.data() + static_cast(off) * be, static_cast(m) * be, gpu::kHostToDevice, stream), "reseed stage v"); + bck(gpu::memcpy_async(stage_sk_dev, psk.data() + static_cast(off) * B, static_cast(m) * B * sizeof(float), gpu::kHostToDevice, stream), "reseed stage sk"); + bck(gpu::memcpy_async(stage_sv_dev, psv.data() + static_cast(off) * B, static_cast(m) * B * sizeof(float), gpu::kHostToDevice, stream), "reseed stage sv"); + bck(gpu::memcpy_async(stage_h_dev, ph.data() + off, static_cast(m) * sizeof(int32_t), gpu::kHostToDevice, stream), "reseed stage h"); + bck(gpu::memcpy_async(stage_s_dev, ps.data() + off, static_cast(m) * sizeof(int32_t), gpu::kHostToDevice, stream), "reseed stage s"); + launch_staged_gather(st, m, stream); + bck(gpu::stream_synchronize(stream), "reseed stage sync"); + } + } + } + + if (open_valid > 0 && target_tail_slot >= 0) { + if (!saved_tail_k.empty()) { + const size_t dst_off = static_cast(target_tail_slot) * static_cast(B) * static_cast(row_elems); + bck(gpu::memcpy_async(st.hot_k + dst_off, saved_tail_k.data(), saved_tail_k.size() * sizeof(uint16_t), gpu::kHostToDevice, stream), "restore tail k"); + bck(gpu::memcpy_async(st.hot_v + dst_off, saved_tail_v.data(), saved_tail_v.size() * sizeof(uint16_t), gpu::kHostToDevice, stream), "restore tail v"); + } + const int32_t rem = B - open_valid; + if (rem > 0) { + dispatch_zero_f16_rows(st.hot_k, st.hot_v, + static_cast(target_tail_slot) * B + open_valid, + rem, row_elems, stream); + } + } + + if (st.tail_k_min != nullptr) { + const int32_t valid_in_last = (new_seq_len == 0) ? 0 : (open_valid > 0 ? open_valid : B); + const int32_t last_slot = (target_tail_slot >= 0) ? target_tail_slot : 0; + dispatch_recompute_tail_extrema(st.hot_k, st.tail_k_min, st.tail_k_max, + H, B, D, last_slot, valid_in_last, stream); + } + + st.seq_len = new_seq_len; + st.flushed_blks = full_blks; + const long long eff = new_seq_len > 0 + ? ((new_seq_len - 1 < W * B) ? static_cast(new_seq_len - 1) + : static_cast((W - 1) * B + ((new_seq_len - 1) % B))) + : 0LL; + dispatch_set_scalars(st.d_seq_len, st.seq_len, st.d_step, st.step, st.d_eff_pos, eff, stream); + } + + void launch_materialize(const int8_t* ck, const int8_t* cv, const float* csk, const float* csv, + const uint16_t* hot_k, const uint16_t* hot_v, + uint16_t* dst_k, uint16_t* dst_v, + int32_t M_stride, int32_t row0, int32_t count, + int32_t flushed_rows, int32_t tail_slot, gpu::Stream stream) { + const int32_t H = cfg.n_head_kv; + const int32_t B = cfg.block_size; + const int32_t D = cfg.head_dim; + BasinArgs a; + a.p[0] = ck; + a.p[1] = cv; + a.p[2] = csk; + a.p[3] = csv; + a.p[4] = hot_k; + a.p[5] = hot_v; + a.p[6] = dst_k; + a.p[7] = dst_v; + a.p[8] = d_wht_signs; + a.n[0] = H; + a.n[1] = M_stride; + a.n[2] = B; + a.n[3] = D; + a.n[4] = row0; + a.n[5] = count; + a.n[6] = flushed_rows; + a.n[7] = tail_slot; + + ResBuilder rb; + rb.add(ck, gpu::metal::Access::R); + rb.add(cv, gpu::metal::Access::R); + rb.add(csk, gpu::metal::Access::R); + rb.add(csv, gpu::metal::Access::R); + rb.add(hot_k, gpu::metal::Access::R); + rb.add(hot_v, gpu::metal::Access::R); + rb.add(dst_k, gpu::metal::Access::W); + rb.add(dst_v, gpu::metal::Access::W); + if (cfg.host_quant == BasinHostQuant::kWhtInt4) { + rb.add(d_wht_signs, gpu::metal::Access::R); + const char* kname = pick_wht_kernel(D, + "bkv_materialize_wht4_64", "bkv_materialize_wht4_128", "bkv_materialize_wht4_192", + "bkv_materialize_wht4_256", "bkv_materialize_wht4_320", "bkv_materialize_wht4_512"); + const int64_t items = static_cast(count) * H; + run_kernel(kname, a, stream, {grid_div(items, 8), 1, 1}, 256, rb); + } else { + run_kernel("bkv_materialize_i8", a, stream, + {static_cast(count), static_cast(H), 1}, 128, rb); + } + } +}; + +bool basinkv_gpu_available() noexcept { return true; } + +BasinKvPool::BasinKvPool() : impl_(std::make_unique()) {} +BasinKvPool::~BasinKvPool() { + try { destroy(); } catch (...) {} +} + +void BasinKvPool::init(const BasinKvConfig& cfg) { + destroy(); + basinkv_validate_config(cfg); + ScopedDevice dev(cfg.device_id); + + impl_->cfg = cfg; + const int32_t L = cfg.n_layers; + const int32_t Hq = cfg.n_head_q; + const int32_t Hk = cfg.n_head_kv; + const int32_t D = cfg.head_dim; + const int32_t B = cfg.block_size; + const int32_t W = cfg.resident_blocks(); + const int32_t M = cfg.max_blocks(); + // Size transfer-plan and non-UVA staging buffers for kMaxTransferCap so cap_override up to 64 + // (e.g. post-prefill priming when cfg.transfer_cap < 64) never overflows in UVA or staged modes. + const int32_t plan_cap = std::max(cfg.transfer_cap, kMaxTransferCap); + const int32_t hd = cfg.host_kv_dim(); + + // Apple Silicon uses unified memory (MTLResourceStorageModeShared), so zero-copy UVA is native + // unless explicitly disabled via cfg.disable_uva. + impl_->use_uva = !cfg.disable_uva; + + try { + bck(gpu::malloc_device(&impl_->shared_scores, static_cast(Hk) * M * sizeof(float)), "shared_scores"); + + if (cfg.index_mode == BasinIndexMode::kSphereInt4 || cfg.host_quant == BasinHostQuant::kWhtInt4) { + std::vector signs; + basinkv_generate_wht_signs(D, cfg.wht_seed, signs); + bck(gpu::malloc_device(&impl_->d_wht_signs, static_cast(D) * sizeof(float)), "d_wht_signs"); + bck(gpu::memcpy_sync(impl_->d_wht_signs, signs.data(), static_cast(D) * sizeof(float), + gpu::kHostToDevice), "upload d_wht_signs"); + } + + impl_->layers.resize(static_cast(L)); + const size_t hot_bytes = static_cast(W) * B * Hk * D * sizeof(uint16_t); + const size_t host_kv_bytes = static_cast(Hk) * M * B * static_cast(hd); + const size_t host_sc_bytes = static_cast(Hk) * M * B * sizeof(float); + + for (int32_t l = 0; l < L; ++l) { + LayerState& st = impl_->layers[static_cast(l)]; + bck(gpu::malloc_device(&st.hot_k, hot_bytes), "hot_k"); + bck(gpu::malloc_device(&st.hot_v, hot_bytes), "hot_v"); + bck(gpu::memset_device(st.hot_k, 0, hot_bytes), "zero hot_k"); + bck(gpu::memset_device(st.hot_v, 0, hot_bytes), "zero hot_v"); + + if (impl_->use_uva) { + const unsigned flags = gpu::kHostAllocMapped | gpu::kHostAllocPortable; + gpu::Error ek = gpu::host_alloc(&st.host_k_i8, host_kv_bytes, flags); + gpu::Error ev = (ek == gpu::kSuccess) ? gpu::host_alloc(&st.host_v_i8, host_kv_bytes, flags) : ek; + gpu::Error esk = (ev == gpu::kSuccess) ? gpu::host_alloc(&st.host_k_scale, host_sc_bytes, flags) : ev; + gpu::Error esv = (esk == gpu::kSuccess) ? gpu::host_alloc(&st.host_v_scale, host_sc_bytes, flags) : esk; + if (esv == gpu::kSuccess) { + void *pk = nullptr, *pv = nullptr, *psk = nullptr, *psv = nullptr; + ek = gpu::host_device_pointer_raw(&pk, st.host_k_i8); + ev = (ek == gpu::kSuccess) ? gpu::host_device_pointer_raw(&pv, st.host_v_i8) : ek; + esk = (ev == gpu::kSuccess) ? gpu::host_device_pointer_raw(&psk, st.host_k_scale) : ev; + esv = (esk == gpu::kSuccess) ? gpu::host_device_pointer_raw(&psv, st.host_v_scale) : esk; + if (esv == gpu::kSuccess) { + st.dev_host_k_i8 = static_cast(pk); + st.dev_host_v_i8 = static_cast(pv); + st.dev_host_sk = static_cast(psk); + st.dev_host_sv = static_cast(psv); + } + } + if (esv != gpu::kSuccess) { + gpu::get_last_error(); + if (st.host_k_i8) { gpu::free_host(st.host_k_i8); st.host_k_i8 = nullptr; } + if (st.host_v_i8) { gpu::free_host(st.host_v_i8); st.host_v_i8 = nullptr; } + if (st.host_k_scale) { gpu::free_host(st.host_k_scale); st.host_k_scale = nullptr; } + if (st.host_v_scale) { gpu::free_host(st.host_v_scale); st.host_v_scale = nullptr; } + st.dev_host_k_i8 = st.dev_host_v_i8 = nullptr; + st.dev_host_sk = st.dev_host_sv = nullptr; + impl_->use_uva = false; + } + } + if (!st.host_k_i8) { + bck(gpu::malloc_host(&st.host_k_i8, host_kv_bytes), "host_k_i8"); + bck(gpu::malloc_host(&st.host_v_i8, host_kv_bytes), "host_v_i8"); + bck(gpu::malloc_host(&st.host_k_scale, host_sc_bytes), "host_k_scale"); + bck(gpu::malloc_host(&st.host_v_scale, host_sc_bytes), "host_v_scale"); + } + + if (cfg.index_mode == BasinIndexMode::kSphereInt4) { + bck(gpu::malloc_device(&st.sphere_packed, static_cast(Hk) * M * (D / 2)), "sphere_packed"); + bck(gpu::malloc_device(&st.sphere_scale, static_cast(Hk) * M * sizeof(float)), "sphere_scale"); + bck(gpu::malloc_device(&st.sphere_radii, static_cast(Hk) * M * 2 * sizeof(uint16_t)), "sphere_radii"); + } else { + bck(gpu::malloc_device(&st.idx_k_min, static_cast(Hk) * M * D), "idx_k_min"); + bck(gpu::malloc_device(&st.idx_k_max, static_cast(Hk) * M * D), "idx_k_max"); + bck(gpu::malloc_device(&st.idx_smin, static_cast(Hk) * M * sizeof(float)), "idx_smin"); + bck(gpu::malloc_device(&st.idx_smax, static_cast(Hk) * M * sizeof(float)), "idx_smax"); + bck(gpu::malloc_device(&st.tail_k_min, static_cast(Hk) * D * sizeof(float)), "tail_k_min"); + bck(gpu::malloc_device(&st.tail_k_max, static_cast(Hk) * D * sizeof(float)), "tail_k_max"); + } + + bck(gpu::malloc_device(&st.d_seq_len, sizeof(int32_t)), "d_seq_len"); + bck(gpu::malloc_device(&st.d_step, sizeof(int64_t)), "d_step"); + bck(gpu::malloc_device(&st.d_eff_pos, sizeof(long long)), "d_eff_pos"); + + bck(gpu::malloc_device(&st.gpu_to_cpu, static_cast(Hk) * W * sizeof(int32_t)), "gpu_to_cpu"); + bck(gpu::malloc_device(&st.cpu_to_gpu, static_cast(Hk) * M * sizeof(int32_t)), "cpu_to_gpu"); + bck(gpu::malloc_device(&st.last_selected_step, static_cast(Hk) * W * sizeof(int64_t)), "last_selected_step"); + bck(gpu::malloc_device(&st.src_cpu_blocks, static_cast(Hk) * static_cast(plan_cap) * sizeof(int32_t)), "src_cpu_blocks"); + bck(gpu::malloc_device(&st.dst_gpu_slots, static_cast(Hk) * static_cast(plan_cap) * sizeof(int32_t)), "dst_gpu_slots"); + bck(gpu::malloc_device(&st.admit_valid, static_cast(Hk) * static_cast(plan_cap) * sizeof(uint8_t)), "admit_valid"); + bck(gpu::malloc_device(&st.admitted_counter, sizeof(uint64_t)), "admitted_counter"); + bck(gpu::malloc_device(&st.q_staging, static_cast(Hq) * D * sizeof(float)), "q_staging"); + } + + if (!impl_->use_uva) { + impl_->stage_cap_blks = std::max(Hk * plan_cap, Hk * std::min(kPrefillTile, M)); + const size_t cap = static_cast(impl_->stage_cap_blks); + bck(gpu::malloc_device(&impl_->stage_k_dev, cap * B * static_cast(hd)), "stage_k_dev"); + bck(gpu::malloc_device(&impl_->stage_v_dev, cap * B * static_cast(hd)), "stage_v_dev"); + bck(gpu::malloc_device(&impl_->stage_sk_dev, cap * B * sizeof(float)), "stage_sk_dev"); + bck(gpu::malloc_device(&impl_->stage_sv_dev, cap * B * sizeof(float)), "stage_sv_dev"); + bck(gpu::malloc_device(&impl_->stage_h_dev, cap * sizeof(int32_t)), "stage_h_dev"); + bck(gpu::malloc_device(&impl_->stage_s_dev, cap * sizeof(int32_t)), "stage_s_dev"); + } + + impl_->initialized = true; + reset_all(nullptr); + bck(gpu::device_synchronize(), "BasinKV init sync"); + } catch (...) { + destroy(); + throw; + } +} + +void BasinKvPool::destroy() { + if (!impl_) return; + if (impl_->initialized) (void) gpu::device_synchronize(); + for (auto& st : impl_->layers) { + if (st.hot_k) gpu::free_device(st.hot_k); + if (st.hot_v) gpu::free_device(st.hot_v); + if (st.host_k_i8) gpu::free_host(st.host_k_i8); + if (st.host_v_i8) gpu::free_host(st.host_v_i8); + if (st.host_k_scale) gpu::free_host(st.host_k_scale); + if (st.host_v_scale) gpu::free_host(st.host_v_scale); + if (st.idx_k_min) gpu::free_device(st.idx_k_min); + if (st.idx_k_max) gpu::free_device(st.idx_k_max); + if (st.idx_smin) gpu::free_device(st.idx_smin); + if (st.idx_smax) gpu::free_device(st.idx_smax); + if (st.tail_k_min) gpu::free_device(st.tail_k_min); + if (st.tail_k_max) gpu::free_device(st.tail_k_max); + if (st.sphere_packed) gpu::free_device(st.sphere_packed); + if (st.sphere_scale) gpu::free_device(st.sphere_scale); + if (st.sphere_radii) gpu::free_device(st.sphere_radii); + if (st.d_seq_len) gpu::free_device(st.d_seq_len); + if (st.d_step) gpu::free_device(st.d_step); + if (st.d_eff_pos) gpu::free_device(st.d_eff_pos); + if (st.gpu_to_cpu) gpu::free_device(st.gpu_to_cpu); + if (st.cpu_to_gpu) gpu::free_device(st.cpu_to_gpu); + if (st.last_selected_step) gpu::free_device(st.last_selected_step); + if (st.src_cpu_blocks) gpu::free_device(st.src_cpu_blocks); + if (st.dst_gpu_slots) gpu::free_device(st.dst_gpu_slots); + if (st.admit_valid) gpu::free_device(st.admit_valid); + if (st.admitted_counter) gpu::free_device(st.admitted_counter); + if (st.q_staging) gpu::free_device(st.q_staging); + } + impl_->layers.clear(); + if (impl_->stage_k_dev) { gpu::free_device(impl_->stage_k_dev); impl_->stage_k_dev = nullptr; } + if (impl_->stage_v_dev) { gpu::free_device(impl_->stage_v_dev); impl_->stage_v_dev = nullptr; } + if (impl_->stage_sk_dev) { gpu::free_device(impl_->stage_sk_dev); impl_->stage_sk_dev = nullptr; } + if (impl_->stage_sv_dev) { gpu::free_device(impl_->stage_sv_dev); impl_->stage_sv_dev = nullptr; } + if (impl_->stage_h_dev) { gpu::free_device(impl_->stage_h_dev); impl_->stage_h_dev = nullptr; } + if (impl_->stage_s_dev) { gpu::free_device(impl_->stage_s_dev); impl_->stage_s_dev = nullptr; } + if (impl_->shared_scores) { gpu::free_device(impl_->shared_scores); impl_->shared_scores = nullptr; } + if (impl_->d_wht_signs) { gpu::free_device(impl_->d_wht_signs); impl_->d_wht_signs = nullptr; } + impl_->initialized = false; + impl_->use_uva = false; +} + +bool BasinKvPool::is_initialized() const noexcept { return impl_ && impl_->initialized; } +bool BasinKvPool::is_using_uva() const noexcept { return impl_ && impl_->use_uva; } +const BasinKvConfig& BasinKvPool::config() const noexcept { return impl_->cfg; } +BasinKvFootprint BasinKvPool::footprint() const noexcept { return basinkv_estimate_footprint(impl_->cfg); } + +uint16_t* BasinKvPool::hot_k(int32_t layer) const noexcept { + return impl_->layers[static_cast(layer)].hot_k; +} +uint16_t* BasinKvPool::hot_v(int32_t layer) const noexcept { + return impl_->layers[static_cast(layer)].hot_v; +} +const long long* BasinKvPool::d_eff_pos(int32_t layer) const noexcept { + return impl_->layers[static_cast(layer)].d_eff_pos; +} +const int32_t* BasinKvPool::d_gpu_to_cpu(int32_t layer) const noexcept { + return impl_->layers[static_cast(layer)].gpu_to_cpu; +} +int64_t BasinKvPool::effective_pos(int64_t pos) const noexcept { + const int32_t W = impl_->cfg.resident_blocks(); + const int32_t B = impl_->cfg.block_size; + const int64_t res = static_cast(W) * B; + return (pos < res) ? pos : (static_cast(W - 1) * B + (pos % B)); +} +int32_t BasinKvPool::seq_len(int32_t layer) const noexcept { + return impl_->layers[static_cast(layer)].seq_len; +} +int32_t BasinKvPool::resident_tokens() const noexcept { return impl_->cfg.resident_tokens(); } + +void BasinKvPool::wait_layer_ready(int32_t layer, void*) { + impl_->validate_layer(layer); + // Lookahead runs stream-ordered on main_stream on Metal UMA -> zero cross-stream wait needed. +} + +void BasinKvPool::join_all_pending(void*) { + // Stream-ordered on main_stream. +} + +void BasinKvPool::join_bg_in_capture(void*) { + // Stream-ordered on main_stream inside Metal graph capture. +} + +void BasinKvPool::mark_device_state_dirty() noexcept { + if (!impl_) return; + for (auto& st : impl_->layers) st.device_state_dirty = true; +} + +void BasinKvPool::sync_host_state(void* main_stream) { + if (!impl_->initialized) return; + ScopedDevice dev(impl_->cfg.device_id); + for (int32_t l = 0; l < impl_->cfg.n_layers; ++l) impl_->sync_layer_if_dirty(l, to_stream(main_stream)); +} + +void BasinKvPool::sync_background() { + if (!impl_->initialized) return; + ScopedDevice dev(impl_->cfg.device_id); + bck(gpu::device_synchronize(), "sync_background"); +} + +void BasinKvPool::reset_layer(int32_t layer, void* main_stream) { + impl_->validate_layer(layer); + ScopedDevice dev(impl_->cfg.device_id); + gpu::Stream ms = to_stream(main_stream); + LayerState& st = impl_->layers[static_cast(layer)]; + + const int32_t H = impl_->cfg.n_head_kv; + const int32_t W = impl_->cfg.resident_blocks(); + const int32_t M = impl_->cfg.max_blocks(); + const int32_t B = impl_->cfg.block_size; + const int32_t D = impl_->cfg.head_dim; + + const int64_t g2c_n = static_cast(H) * W; + const int64_t c2g_n = static_cast(H) * M; + dispatch_fill_i32(st.gpu_to_cpu, g2c_n, -1, ms); + dispatch_fill_i32(st.cpu_to_gpu, c2g_n, -1, ms); + bck(gpu::memset_async(st.last_selected_step, 0, static_cast(g2c_n) * sizeof(int64_t), ms), "reset lrs"); + bck(gpu::memset_async(st.admitted_counter, 0, sizeof(uint64_t), ms), "reset admitted"); + if (st.tail_k_min) { + bck(gpu::memset_async(st.tail_k_min, 0, static_cast(H) * D * sizeof(float), ms), "reset tail_min"); + bck(gpu::memset_async(st.tail_k_max, 0, static_cast(H) * D * sizeof(float), ms), "reset tail_max"); + } + bck(gpu::memset_async(st.hot_k, 0, static_cast(W) * B * H * D * sizeof(uint16_t), ms), "reset hot_k"); + bck(gpu::memset_async(st.hot_v, 0, static_cast(W) * B * H * D * sizeof(uint16_t), ms), "reset hot_v"); + dispatch_set_scalars(st.d_seq_len, 0, st.d_step, 0, st.d_eff_pos, 0, ms); + + st.seq_len = 0; + st.flushed_blks = 0; + st.step = 0; + st.device_state_dirty = false; +} + +void BasinKvPool::reset_all(void* main_stream) { + if (!impl_->initialized) return; + for (int32_t l = 0; l < impl_->cfg.n_layers; ++l) reset_layer(l, main_stream); +} + +void BasinKvPool::truncate_layer(int32_t layer, int32_t new_seq_len, void* main_stream) { + impl_->validate_layer(layer); + ScopedDevice dev(impl_->cfg.device_id); + gpu::Stream ms = to_stream(main_stream); + impl_->sync_layer_if_dirty(layer, ms); + LayerState& st = impl_->layers[static_cast(layer)]; + impl_->ensure_completed_tail_flushed(st, ms); + + if (new_seq_len <= 0) { + reset_layer(layer, main_stream); + return; + } + if (new_seq_len >= st.seq_len) return; + + const int32_t B = impl_->cfg.block_size; + const int32_t W = impl_->cfg.resident_blocks(); + const int32_t H = impl_->cfg.n_head_kv; + const int32_t D = impl_->cfg.head_dim; + const int32_t M = impl_->cfg.max_blocks(); + const int32_t row_elems = H * D; + const int32_t new_full_blks = new_seq_len / B; + const int32_t new_open = new_seq_len % B; + const int32_t old_full_blks = st.flushed_blks; + + // Fast path A: lossless short-context rollback (st.seq_len <= W * B) + if (st.seq_len <= W * B) { + if (new_open > 0) { + dispatch_zero_f16_rows(st.hot_k, st.hot_v, + static_cast(new_full_blks) * B + new_open, + B - new_open, row_elems, ms); + } + const int32_t n_blks = (new_seq_len + B - 1) / B; + std::vector g2c(static_cast(H) * W, -1); + std::vector c2g(static_cast(H) * M, -1); + std::vector lrs(static_cast(H) * W, st.step); + for (int32_t h = 0; h < H; ++h) { + for (int32_t b = 0; b < n_blks; ++b) { + g2c[static_cast(h) * W + b] = b; + c2g[static_cast(h) * M + b] = b; + } + } + bck(gpu::memcpy_async(st.gpu_to_cpu, g2c.data(), g2c.size() * sizeof(int32_t), gpu::kHostToDevice, ms), "trunc short g2c"); + bck(gpu::memcpy_async(st.cpu_to_gpu, c2g.data(), c2g.size() * sizeof(int32_t), gpu::kHostToDevice, ms), "trunc short c2g"); + bck(gpu::memcpy_async(st.last_selected_step, lrs.data(), lrs.size() * sizeof(int64_t), gpu::kHostToDevice, ms), "trunc short lrs"); + if (st.tail_k_min != nullptr) { + const int32_t last_blk = (new_seq_len - 1) / B; + const int32_t valid_in_last = new_open > 0 ? new_open : B; + dispatch_recompute_tail_extrema(st.hot_k, st.tail_k_min, st.tail_k_max, + H, B, D, last_blk, valid_in_last, ms); + } + st.seq_len = new_seq_len; + st.flushed_blks = new_full_blks; + dispatch_set_scalars(st.d_seq_len, st.seq_len, st.d_step, st.step, + st.d_eff_pos, static_cast(new_seq_len - 1), ms); + return; + } + + // Fast path B: long-context intra-tail rollback (same open block) + if (new_seq_len > W * B && new_full_blks == old_full_blks && new_open > 0) { + const int32_t tslot = impl_->cfg.tail_slot(); + dispatch_zero_f16_rows(st.hot_k, st.hot_v, + static_cast(tslot) * B + new_open, + B - new_open, row_elems, ms); + if (st.tail_k_min != nullptr) { + dispatch_recompute_tail_extrema(st.hot_k, st.tail_k_min, st.tail_k_max, + H, B, D, tslot, new_open, ms); + } + st.seq_len = new_seq_len; + const long long eff = static_cast(W - 1) * B + (new_open - 1); + dispatch_set_scalars(st.d_seq_len, st.seq_len, st.d_step, st.step, st.d_eff_pos, eff, ms); + return; + } + + int32_t tail_from_slot = -1; + if (new_open > 0) { + if (new_full_blks == old_full_blks) { + tail_from_slot = (st.seq_len <= W * B) ? new_full_blks : impl_->cfg.tail_slot(); + } else { + const int32_t dst_slot = (new_seq_len <= W * B) ? new_full_blks : impl_->cfg.tail_slot(); + const int64_t dst_off = static_cast(dst_slot) * B * row_elems; + materialize_range_f16(layer, new_full_blks * B, new_open, + st.hot_k + dst_off, st.hot_v + dst_off, main_stream); + tail_from_slot = dst_slot; + } + } + impl_->rebuild_hot_slab_for_len(layer, new_seq_len, /*preserve_sparse=*/true, tail_from_slot, ms); +} + +void BasinKvPool::truncate_all(int32_t new_seq_len, void* main_stream) { + if (!impl_->initialized) return; + for (int32_t l = 0; l < impl_->cfg.n_layers; ++l) truncate_layer(l, new_seq_len, main_stream); +} + +void BasinKvPool::append_prefill_chunk_f32(int32_t layer, const float* k_f32, const float* v_f32, + int32_t start_pos, int32_t n_tokens, void* main_stream) { + impl_->validate_layer(layer); + if (n_tokens <= 0) return; + if (!k_f32 || !v_f32) throw std::invalid_argument("BasinKV: null prefill k/v pointer"); + if (start_pos < 0 || start_pos + n_tokens > impl_->cfg.max_seq_len) + throw std::out_of_range("BasinKV: prefill chunk exceeds max_seq_len"); + + ScopedDevice dev(impl_->cfg.device_id); + gpu::Stream ms = to_stream(main_stream); + impl_->sync_layer_if_dirty(layer, ms); + + LayerState& st = impl_->layers[static_cast(layer)]; + if (start_pos < st.seq_len) { + truncate_layer(layer, start_pos, main_stream); + } else if (start_pos > st.seq_len) { + throw std::invalid_argument("BasinKV: non-contiguous prefill chunk (start_pos > seq_len)"); + } else { + impl_->ensure_completed_tail_flushed(st, ms); + } + + const int32_t H = impl_->cfg.n_head_kv; + const int32_t D = impl_->cfg.head_dim; + const int32_t B = impl_->cfg.block_size; + const int32_t W = impl_->cfg.resident_blocks(); + const int32_t row_elems = H * D; + const int32_t end_pos = start_pos + n_tokens; + + int32_t cur_pos = start_pos; + int32_t in_off = 0; + + // 1) Mid-block open tail completion / extension + if (cur_pos % B != 0) { + const int32_t blk = cur_pos / B; + const int32_t off = cur_pos - blk * B; + const int32_t take = std::min(n_tokens, B - off); + const int32_t slot = (blk < W) ? blk : impl_->cfg.tail_slot(); + dispatch_copy_f32_to_f16_rows(k_f32, v_f32, st.hot_k, st.hot_v, + in_off, static_cast(slot) * B + off, take, row_elems, ms); + cur_pos += take; + in_off += take; + if (cur_pos % B == 0) { + impl_->launch_seal_hot_slot(st, slot, blk, ms); + st.flushed_blks = blk + 1; + } + } + + // 2) Bulk-quantize & seal complete blocks wholly inside the chunk + const int32_t rem_full_blks = (end_pos - cur_pos) / B; + if (rem_full_blks > 0) { + const int32_t blk0 = cur_pos / B; + impl_->launch_seal_prefill_blocks(st, k_f32, v_f32, blk0, rem_full_blks, in_off, ms); + if (end_pos <= W * B) { + dispatch_copy_f32_to_f16_rows(k_f32, v_f32, st.hot_k, st.hot_v, + in_off, cur_pos, rem_full_blks * B, row_elems, ms); + } + cur_pos += rem_full_blks * B; + in_off += rem_full_blks * B; + st.flushed_blks = blk0 + rem_full_blks; + } + + // 3) Trailing partial open block + const int32_t tail_rem = end_pos - cur_pos; + int32_t open_slot = -1; + if (tail_rem > 0) { + const int32_t blk = cur_pos / B; + open_slot = (end_pos <= W * B) ? blk : impl_->cfg.tail_slot(); + dispatch_copy_f32_to_f16_rows(k_f32, v_f32, st.hot_k, st.hot_v, + in_off, static_cast(open_slot) * B, tail_rem, row_elems, ms); + } + + // 4) Update page tables & hot slab + if (end_pos <= W * B) { + const int32_t n_blks = (end_pos + B - 1) / B; + const int32_t M = impl_->cfg.max_blocks(); + std::vector g2c(static_cast(H) * W, -1); + std::vector c2g(static_cast(H) * M, -1); + std::vector lrs(static_cast(H) * W, st.step); + for (int32_t h = 0; h < H; ++h) { + for (int32_t b = 0; b < n_blks; ++b) { + g2c[static_cast(h) * W + b] = b; + c2g[static_cast(h) * M + b] = b; + } + } + bck(gpu::memcpy_async(st.gpu_to_cpu, g2c.data(), g2c.size() * sizeof(int32_t), gpu::kHostToDevice, ms), "short g2c"); + bck(gpu::memcpy_async(st.cpu_to_gpu, c2g.data(), c2g.size() * sizeof(int32_t), gpu::kHostToDevice, ms), "short c2g"); + bck(gpu::memcpy_async(st.last_selected_step, lrs.data(), lrs.size() * sizeof(int64_t), gpu::kHostToDevice, ms), "short lrs"); + if (st.tail_k_min != nullptr) { + const int32_t last_blk = (end_pos - 1) / B; + const int32_t valid_in_last = (end_pos % B == 0) ? B : (end_pos % B); + dispatch_recompute_tail_extrema(st.hot_k, st.tail_k_min, st.tail_k_max, + H, B, D, last_blk, valid_in_last, ms); + } + st.seq_len = end_pos; + dispatch_set_scalars(st.d_seq_len, st.seq_len, st.d_step, st.step, + st.d_eff_pos, static_cast(end_pos - 1), ms); + } else { + impl_->rebuild_hot_slab_for_len(layer, end_pos, /*preserve_sparse=*/true, + (tail_rem > 0) ? open_slot : -1, ms); + } +} + +void BasinKvPool::materialize_range_f16(int32_t layer, int32_t row0, int32_t count, + uint16_t* dst_k_f16, uint16_t* dst_v_f16, void* main_stream) { + impl_->validate_layer(layer); + if (count <= 0) return; + if (!dst_k_f16 || !dst_v_f16) throw std::invalid_argument("BasinKV: null materialize destination"); + + ScopedDevice dev(impl_->cfg.device_id); + gpu::Stream ms = to_stream(main_stream); + impl_->sync_layer_if_dirty(layer, ms); + + LayerState& st = impl_->layers[static_cast(layer)]; + impl_->ensure_completed_tail_flushed(st, ms); + if (row0 < 0 || row0 + count > st.seq_len) + throw std::out_of_range("BasinKV: materialize_range_f16 out of seq_len bounds"); + + const int32_t H = impl_->cfg.n_head_kv; + const int32_t M = impl_->cfg.max_blocks(); + const int32_t B = impl_->cfg.block_size; + const int32_t D = impl_->cfg.head_dim; + const int32_t W = impl_->cfg.resident_blocks(); + const int32_t flushed_rows = st.flushed_blks * B; + const int32_t tail_slot = (st.seq_len <= W * B) ? st.flushed_blks : impl_->cfg.tail_slot(); + + if (impl_->use_uva) { + impl_->launch_materialize(st.dev_host_k_i8, st.dev_host_v_i8, st.dev_host_sk, st.dev_host_sv, + st.hot_k, st.hot_v, dst_k_f16, dst_v_f16, + M, row0, count, flushed_rows, tail_slot, ms); + } else { + const int32_t row_end = row0 + count; + const int32_t host_end = std::min(row_end, flushed_rows); + if (row0 < host_end) { + const int32_t b0 = row0 / B; + const int32_t b1 = (host_end + B - 1) / B; + const size_t hd = static_cast(impl_->cfg.host_kv_dim()); + const size_t be = static_cast(B) * hd; + const int32_t max_tile = std::max(1, impl_->stage_cap_blks / H); + for (int32_t blk = b0; blk < b1; blk += max_tile) { + const int32_t nb = std::min(b1 - blk, max_tile); + for (int32_t h = 0; h < H; ++h) { + const size_t src_off = static_cast(h) * M + static_cast(blk); + const size_t dst_off = static_cast(h) * nb; + bck(gpu::memcpy_async(impl_->stage_k_dev + dst_off * be, st.host_k_i8 + src_off * be, static_cast(nb) * be, gpu::kHostToDevice, ms), "non-uva mat k"); + bck(gpu::memcpy_async(impl_->stage_v_dev + dst_off * be, st.host_v_i8 + src_off * be, static_cast(nb) * be, gpu::kHostToDevice, ms), "non-uva mat v"); + bck(gpu::memcpy_async(impl_->stage_sk_dev + dst_off * B, st.host_k_scale + src_off * B, static_cast(nb) * B * sizeof(float), gpu::kHostToDevice, ms), "non-uva mat sk"); + bck(gpu::memcpy_async(impl_->stage_sv_dev + dst_off * B, st.host_v_scale + src_off * B, static_cast(nb) * B * sizeof(float), gpu::kHostToDevice, ms), "non-uva mat sv"); + } + const int32_t tr0 = std::max(row0, blk * B); + const int32_t tr1 = std::min(host_end, (blk + nb) * B); + const int32_t tc = tr1 - tr0; + const int32_t local_row0 = tr0 - blk * B; + const int64_t dst_row_off = static_cast(tr0 - row0) * H * D; + impl_->launch_materialize(impl_->stage_k_dev, impl_->stage_v_dev, + impl_->stage_sk_dev, impl_->stage_sv_dev, + st.hot_k, st.hot_v, + dst_k_f16 + dst_row_off, dst_v_f16 + dst_row_off, + nb, local_row0, tc, nb * B, tail_slot, ms); + bck(gpu::stream_synchronize(ms), "non-uva mat sync"); + } + } + if (row_end > flushed_rows) { + const int32_t tr0 = std::max(row0, flushed_rows); + const int32_t tc = row_end - tr0; + const size_t row_bytes = static_cast(H) * D * sizeof(uint16_t); + const size_t src_off = (static_cast(tail_slot) * B + static_cast(tr0 - flushed_rows)) * H * D; + const size_t dst_off = static_cast(tr0 - row0) * H * D; + bck(gpu::memcpy_async(dst_k_f16 + dst_off, st.hot_k + src_off, static_cast(tc) * row_bytes, gpu::kDeviceToDevice, ms), "mat tail k"); + bck(gpu::memcpy_async(dst_v_f16 + dst_off, st.hot_v + src_off, static_cast(tc) * row_bytes, gpu::kDeviceToDevice, ms), "mat tail v"); + } + } +} + +void BasinKvPool::append_decode_token_f32(int32_t layer, const float* k_f32, const float* v_f32, + int32_t pos, void* main_stream) { + impl_->validate_layer(layer); + if (!k_f32 || !v_f32) throw std::invalid_argument("BasinKV: null decode k/v pointer"); + if (pos < 0 || pos >= impl_->cfg.max_seq_len) + throw std::out_of_range("BasinKV: decode pos out of bounds"); + + ScopedDevice dev(impl_->cfg.device_id); + gpu::Stream ms = to_stream(main_stream); + impl_->sync_layer_if_dirty(layer, ms); + + LayerState& st = impl_->layers[static_cast(layer)]; + if (pos < st.seq_len) { + truncate_layer(layer, pos, main_stream); + } else if (pos > st.seq_len) { + throw std::invalid_argument("BasinKV: non-contiguous decode append (pos > seq_len)"); + } + + const int32_t B = impl_->cfg.block_size; + if (pos > 0 && (pos % B) == 0) { + const int32_t prev_blk = (pos / B) - 1; + if (impl_->use_uva) { + impl_->launch_flush_rotate_seal(st, impl_->cfg.max_blocks(), prev_blk, + st.dev_host_k_i8, st.dev_host_v_i8, st.dev_host_sk, st.dev_host_sv, + pos, st.step, nullptr, nullptr, nullptr, ms); + } else { + impl_->launch_flush_rotate_seal(st, 1, 0, + impl_->stage_k_dev, impl_->stage_v_dev, impl_->stage_sk_dev, impl_->stage_sv_dev, + pos, st.step, nullptr, nullptr, nullptr, ms); + const int32_t M = impl_->cfg.max_blocks(); + const size_t hd = static_cast(impl_->cfg.host_kv_dim()); + const size_t be = static_cast(B) * hd; + for (int32_t h = 0; h < impl_->cfg.n_head_kv; ++h) { + const size_t dst_off = static_cast(h) * M + static_cast(prev_blk); + bck(gpu::memcpy_async(st.host_k_i8 + dst_off * be, impl_->stage_k_dev + static_cast(h) * be, be, gpu::kDeviceToHost, ms), "non-uva flush k"); + bck(gpu::memcpy_async(st.host_v_i8 + dst_off * be, impl_->stage_v_dev + static_cast(h) * be, be, gpu::kDeviceToHost, ms), "non-uva flush v"); + bck(gpu::memcpy_async(st.host_k_scale + dst_off * B, impl_->stage_sk_dev + static_cast(h) * B, static_cast(B) * sizeof(float), gpu::kDeviceToHost, ms), "non-uva flush sk"); + bck(gpu::memcpy_async(st.host_v_scale + dst_off * B, impl_->stage_sv_dev + static_cast(h) * B, static_cast(B) * sizeof(float), gpu::kDeviceToHost, ms), "non-uva flush sv"); + } + bck(gpu::stream_synchronize(ms), "non-uva flush sync"); + } + st.flushed_blks = prev_blk + 1; + } + + impl_->launch_append_decode(st, k_f32, v_f32, nullptr, nullptr, pos, st.step, ms); + st.seq_len = pos + 1; +} + +void BasinKvPool::submit_lookahead_f32(int32_t layer, const float* q_f32, void* main_stream, int32_t cap_override) { + impl_->validate_layer(layer); + if (!q_f32) throw std::invalid_argument("BasinKV: null lookahead q pointer"); + ScopedDevice dev(impl_->cfg.device_id); + gpu::Stream ms = to_stream(main_stream); + impl_->sync_layer_if_dirty(layer, ms); + + LayerState& st = impl_->layers[static_cast(layer)]; + const int32_t eff_cap = (cap_override >= 0) ? std::min(cap_override, kMaxTransferCap) + : std::min(impl_->cfg.transfer_cap, kMaxTransferCap); + const int32_t q_elems = impl_->cfg.n_head_q * impl_->cfg.head_dim; + dispatch_stage_q_inc_step(st.q_staging, q_f32, q_elems, st.d_step, ms); + ++st.step; + + const int32_t W = impl_->cfg.resident_blocks(); + const int32_t B = impl_->cfg.block_size; + if (st.seq_len <= W * B || impl_->cfg.sparse_blocks <= 0 || eff_cap <= 0) return; + + const int32_t nb = (st.seq_len + B - 1) / B; + const int32_t elig_start = impl_->cfg.sink_blocks; + const int32_t elig_end = std::min(impl_->cfg.max_blocks(), std::max(0, nb - impl_->cfg.local_blocks)); + if (elig_end <= elig_start) return; + + // Stream-ordered directly on main_stream (zero cross-stream race on Metal UMA) + impl_->launch_score(layer, st.q_staging, impl_->shared_scores, elig_start, elig_end, nullptr, ms); + impl_->launch_topk_evict_rebind(st, impl_->shared_scores, elig_start, elig_end, + nullptr, nullptr, eff_cap, st.step, ms); + if (impl_->use_uva) { + impl_->launch_uva_gather(st, eff_cap, ms); + } else { + impl_->run_non_uva_gather(st, eff_cap, ms); + } +} + +void BasinKvPool::append_decode_token_graph_f32(int32_t layer, const float* k_f32, const float* v_f32, + const long long* d_pos_ptr, void* main_stream) { + impl_->validate_layer(layer); + if (!impl_->use_uva) throw std::logic_error("BasinKV: graph decode requires UVA"); + if (!k_f32 || !v_f32) throw std::invalid_argument("BasinKV: null graph decode k/v pointer"); + ScopedDevice dev(impl_->cfg.device_id); + gpu::Stream ms = to_stream(main_stream); + LayerState& st = impl_->layers[static_cast(layer)]; + + impl_->launch_flush_rotate_seal(st, impl_->cfg.max_blocks(), -1, + st.dev_host_k_i8, st.dev_host_v_i8, st.dev_host_sk, st.dev_host_sv, + -1, 0, d_pos_ptr, st.d_seq_len, st.d_step, ms); + impl_->launch_append_decode(st, k_f32, v_f32, d_pos_ptr, st.d_step, -1, 0, ms); + st.device_state_dirty = true; +} + +void BasinKvPool::submit_lookahead_graph_f32(int32_t layer, const float* q_f32, void* main_stream, int32_t cap_override) { + impl_->validate_layer(layer); + if (!impl_->use_uva) throw std::logic_error("BasinKV: graph lookahead requires UVA"); + if (!q_f32) throw std::invalid_argument("BasinKV: null graph lookahead q pointer"); + ScopedDevice dev(impl_->cfg.device_id); + gpu::Stream ms = to_stream(main_stream); + LayerState& st = impl_->layers[static_cast(layer)]; + + const int32_t eff_cap = (cap_override >= 0) ? std::min(cap_override, kMaxTransferCap) + : std::min(impl_->cfg.transfer_cap, kMaxTransferCap); + const int32_t q_elems = impl_->cfg.n_head_q * impl_->cfg.head_dim; + dispatch_stage_q_inc_step(st.q_staging, q_f32, q_elems, st.d_step, ms); + st.device_state_dirty = true; + + if (impl_->cfg.sparse_blocks <= 0 || eff_cap <= 0) return; + + // 100% stream-ordered on main_stream inside Metal graph capture (ICB-compatible) + impl_->launch_score(layer, st.q_staging, impl_->shared_scores, + impl_->cfg.sink_blocks, 0, st.d_seq_len, ms); + impl_->launch_topk_evict_rebind(st, impl_->shared_scores, impl_->cfg.sink_blocks, 0, + st.d_seq_len, st.d_step, eff_cap, 0, ms); + impl_->launch_uva_gather(st, eff_cap, ms); +} + +void BasinKvPool::export_rows_f16(int32_t layer, int32_t first, int32_t count, + uint16_t* dst_k_host, uint16_t* dst_v_host, void* main_stream) { + impl_->validate_layer(layer); + if (count <= 0) return; + ScopedDevice dev(impl_->cfg.device_id); + gpu::Stream ms = to_stream(main_stream); + impl_->sync_layer_if_dirty(layer, ms); + + const int32_t row_elems = impl_->cfg.n_head_kv * impl_->cfg.head_dim; + const size_t row_bytes = static_cast(row_elems) * sizeof(uint16_t); + const int32_t chunk_cap = std::min(count, 2048); + + uint16_t *tmp_k = nullptr, *tmp_v = nullptr; + bck(gpu::malloc_device(&tmp_k, static_cast(chunk_cap) * row_bytes), "export tmp_k"); + try { + bck(gpu::malloc_device(&tmp_v, static_cast(chunk_cap) * row_bytes), "export tmp_v"); + for (int32_t off = 0; off < count; off += chunk_cap) { + const int32_t m = std::min(count - off, chunk_cap); + materialize_range_f16(layer, first + off, m, tmp_k, tmp_v, main_stream); + bck(gpu::memcpy_async(dst_k_host + static_cast(off) * row_elems, tmp_k, + static_cast(m) * row_bytes, gpu::kDeviceToHost, ms), "export d2h k"); + bck(gpu::memcpy_async(dst_v_host + static_cast(off) * row_elems, tmp_v, + static_cast(m) * row_bytes, gpu::kDeviceToHost, ms), "export d2h v"); + bck(gpu::stream_synchronize(ms), "export sync"); + } + } catch (...) { + if (tmp_v) gpu::free_device(tmp_v); + if (tmp_k) gpu::free_device(tmp_k); + throw; + } + gpu::free_device(tmp_v); + gpu::free_device(tmp_k); +} + +void BasinKvPool::import_rows_f16(int32_t layer, const uint16_t* src_k_host, const uint16_t* src_v_host, + int32_t first, int32_t count, void* main_stream) { + impl_->validate_layer(layer); + if (count <= 0) return; + ScopedDevice dev(impl_->cfg.device_id); + gpu::Stream ms = to_stream(main_stream); + impl_->sync_layer_if_dirty(layer, ms); + + const int32_t row_elems = impl_->cfg.n_head_kv * impl_->cfg.head_dim; + const size_t row_f16_bytes = static_cast(row_elems) * sizeof(uint16_t); + const size_t row_f32_bytes = static_cast(row_elems) * sizeof(float); + const int32_t chunk_cap = std::min(count, 2048); + + uint16_t *hk = nullptr, *hv = nullptr; + float *fk = nullptr, *fv = nullptr; + try { + bck(gpu::malloc_device(&hk, static_cast(chunk_cap) * row_f16_bytes), "import hk"); + bck(gpu::malloc_device(&hv, static_cast(chunk_cap) * row_f16_bytes), "import hv"); + bck(gpu::malloc_device(&fk, static_cast(chunk_cap) * row_f32_bytes), "import fk"); + bck(gpu::malloc_device(&fv, static_cast(chunk_cap) * row_f32_bytes), "import fv"); + for (int32_t off = 0; off < count; off += chunk_cap) { + const int32_t m = std::min(count - off, chunk_cap); + const int64_t elems = static_cast(m) * row_elems; + bck(gpu::memcpy_async(hk, src_k_host + static_cast(off) * row_elems, + static_cast(m) * row_f16_bytes, gpu::kHostToDevice, ms), "import h2d k"); + bck(gpu::memcpy_async(hv, src_v_host + static_cast(off) * row_elems, + static_cast(m) * row_f16_bytes, gpu::kHostToDevice, ms), "import h2d v"); + dispatch_f16_to_f32(hk, fk, elems, ms); + dispatch_f16_to_f32(hv, fv, elems, ms); + append_prefill_chunk_f32(layer, fk, fv, first + off, m, main_stream); + bck(gpu::stream_synchronize(ms), "import sync"); + } + } catch (...) { + if (fv) gpu::free_device(fv); + if (fk) gpu::free_device(fk); + if (hv) gpu::free_device(hv); + if (hk) gpu::free_device(hk); + throw; + } + gpu::free_device(fv); + gpu::free_device(fk); + gpu::free_device(hv); + gpu::free_device(hk); +} + +// ---- Test & diagnostic helpers ---- + +void BasinKvPool::score_layer_f32(int32_t layer, const float* q_f32, float* scores_out_dev, void* stream) { + impl_->validate_layer(layer); + ScopedDevice dev(impl_->cfg.device_id); + gpu::Stream s = to_stream(stream); + impl_->sync_layer_if_dirty(layer, s); + const LayerState& st = impl_->layers[static_cast(layer)]; + const int32_t nb = (st.seq_len + impl_->cfg.block_size - 1) / impl_->cfg.block_size; + const int32_t elig_end = std::min(impl_->cfg.max_blocks(), std::max(0, nb - impl_->cfg.local_blocks)); + impl_->launch_score(layer, q_f32, scores_out_dev, impl_->cfg.sink_blocks, elig_end, nullptr, s); +} + +void BasinKvPool::run_select_from_scores(int32_t layer, const float* scores_dev, + int32_t elig_start, int32_t elig_end, int64_t step, + int32_t cap_override, void* stream) { + impl_->validate_layer(layer); + ScopedDevice dev(impl_->cfg.device_id); + gpu::Stream s = to_stream(stream); + LayerState& st = impl_->layers[static_cast(layer)]; + const int32_t eff_cap = (cap_override >= 0) ? std::min(cap_override, kMaxTransferCap) + : std::min(impl_->cfg.transfer_cap, kMaxTransferCap); + impl_->launch_topk_evict_rebind(st, scores_dev, elig_start, elig_end, nullptr, nullptr, eff_cap, step, s); +} + +void BasinKvPool::read_page_tables(int32_t layer, std::vector& gpu_to_cpu, + std::vector& cpu_to_gpu, void* stream) { + impl_->validate_layer(layer); + ScopedDevice dev(impl_->cfg.device_id); + gpu::Stream s = to_stream(stream); + const LayerState& st = impl_->layers[static_cast(layer)]; + gpu_to_cpu.resize(static_cast(impl_->cfg.n_head_kv) * impl_->cfg.resident_blocks()); + cpu_to_gpu.resize(static_cast(impl_->cfg.n_head_kv) * impl_->cfg.max_blocks()); + bck(gpu::memcpy_async(gpu_to_cpu.data(), st.gpu_to_cpu, gpu_to_cpu.size() * sizeof(int32_t), gpu::kDeviceToHost, s), "read g2c"); + bck(gpu::memcpy_async(cpu_to_gpu.data(), st.cpu_to_gpu, cpu_to_gpu.size() * sizeof(int32_t), gpu::kDeviceToHost, s), "read c2g"); + bck(gpu::stream_synchronize(s), "read_page_tables sync"); +} + +void BasinKvPool::read_quest_index(int32_t layer, std::vector& k_min, std::vector& k_max, + std::vector& k_min_scale, std::vector& k_max_scale, void* stream) { + impl_->validate_layer(layer); + if (impl_->cfg.index_mode != BasinIndexMode::kQuestInt8) + throw std::logic_error("BasinKV: read_quest_index called in non-Quest mode"); + ScopedDevice dev(impl_->cfg.device_id); + gpu::Stream s = to_stream(stream); + const LayerState& st = impl_->layers[static_cast(layer)]; + const size_t hm = static_cast(impl_->cfg.n_head_kv) * impl_->cfg.max_blocks(); + k_min.resize(hm * impl_->cfg.head_dim); + k_max.resize(hm * impl_->cfg.head_dim); + k_min_scale.resize(hm); + k_max_scale.resize(hm); + bck(gpu::memcpy_async(k_min.data(), st.idx_k_min, k_min.size(), gpu::kDeviceToHost, s), "read idx_k_min"); + bck(gpu::memcpy_async(k_max.data(), st.idx_k_max, k_max.size(), gpu::kDeviceToHost, s), "read idx_k_max"); + bck(gpu::memcpy_async(k_min_scale.data(), st.idx_smin, hm * sizeof(float), gpu::kDeviceToHost, s), "read idx_smin"); + bck(gpu::memcpy_async(k_max_scale.data(), st.idx_smax, hm * sizeof(float), gpu::kDeviceToHost, s), "read idx_smax"); + bck(gpu::stream_synchronize(s), "read_quest_index sync"); +} + +void BasinKvPool::read_sphere_index(int32_t layer, std::vector& packed, std::vector& scale, + std::vector& radii_f16, void* stream) { + impl_->validate_layer(layer); + if (impl_->cfg.index_mode != BasinIndexMode::kSphereInt4) + throw std::logic_error("BasinKV: read_sphere_index called in non-Sphere mode"); + ScopedDevice dev(impl_->cfg.device_id); + gpu::Stream s = to_stream(stream); + const LayerState& st = impl_->layers[static_cast(layer)]; + const size_t hm = static_cast(impl_->cfg.n_head_kv) * impl_->cfg.max_blocks(); + packed.resize(hm * (impl_->cfg.head_dim / 2)); + scale.resize(hm); + radii_f16.resize(hm * 2); + bck(gpu::memcpy_async(packed.data(), st.sphere_packed, packed.size(), gpu::kDeviceToHost, s), "read sphere_packed"); + bck(gpu::memcpy_async(scale.data(), st.sphere_scale, hm * sizeof(float), gpu::kDeviceToHost, s), "read sphere_scale"); + bck(gpu::memcpy_async(radii_f16.data(), st.sphere_radii, hm * 2 * sizeof(uint16_t), gpu::kDeviceToHost, s), "read sphere_radii"); + bck(gpu::stream_synchronize(s), "read_sphere_index sync"); +} + +uint64_t BasinKvPool::read_admitted_count(int32_t layer, void* stream) { + impl_->validate_layer(layer); + ScopedDevice dev(impl_->cfg.device_id); + gpu::Stream s = to_stream(stream); + uint64_t val = 0; + bck(gpu::memcpy_async(&val, impl_->layers[static_cast(layer)].admitted_counter, + sizeof(uint64_t), gpu::kDeviceToHost, s), "read admitted_counter"); + bck(gpu::stream_synchronize(s), "read_admitted_count sync"); + return val; +} + +} // namespace strata::poly diff --git a/engine/metal/src/poly/basinkv.metal b/engine/metal/src/poly/basinkv.metal new file mode 100644 index 0000000000..06cb6d9b3b --- /dev/null +++ b/engine/metal/src/poly/basinkv.metal @@ -0,0 +1,2397 @@ +// metal/src/poly/basinkv.metal - Native Metal kernels for BasinKV sparse KV offload & lookahead prefetch +// for strata-poly on Apple Silicon (UMA). +// +// Mirrors engine/src/poly/basinkv.cu with 100% algorithmic & invariant parity: +// - Shrunk-Box Quest INT8 outward-rounded index (1-ULP IEEE-754 guard) + scorer +// - Fused SphereIndex INT4 randomized WHT index + scorer (D in {64, 128, 192, 256, 320, 512}) +// - Per-token INT8 and WHT-INT4 host KV quantize / dequantize (UVA zero-copy + staged fallback) +// - Fused 1-launch Radix Top-K + Bitonic Sort + 1-hop successor co-fetch + LRS evict + rebind +// (fits in <= 26 KiB threadgroup memory, well under Metal's 32 KiB per-threadgroup limit) +// - Metal-graph-capturable single-token decode append + boundary flush/rotate/seal/zero/rebind +#include +using namespace metal; + +constant int kMaxSparseSlots = 2048; +constant int kMaxTransferCap = 64; +constant int kInvalidSlot = (-2147483647 - 1); +// Exact IEEE-754 float for (1.0 + 2^-20) / 127.0 = 0x1.020418p-7f (0x3c01020c) +constant float kQuestScaleFactor = 0.007874023169279099f; + +// Mirrors BasinArgs in metal/src/poly/basinkv.cpp (256 bytes, inline in runtime Op::args). +struct BasinArgs { + device void* p[20]; + long i64[3]; + int n[16]; + float f[2]; +}; + +// ---- 32-lane SIMD-group primitives ---- + +inline float warp_sum_f32(float v) { + for (ushort off = 16; off > 0; off >>= 1) v += simd_shuffle_down(v, off); + return v; +} + +inline float warp_max_all_f32(float v) { + for (ushort off = 16; off > 0; off >>= 1) { + float o = simd_shuffle_xor(v, off); + if (isnan(o) || o > v) v = o; + } + return v; +} + +inline uint b_ballot_32(bool pred) { + return uint(static_cast(simd_ballot(pred))); +} + +inline long simd_shuffle_down_i64(long v, ushort delta) { + ulong u = as_type(v); + uint lo = simd_shuffle_down(uint(u & 0xfffffffful), delta); + uint hi = simd_shuffle_down(uint(u >> 32), delta); + return as_type((ulong(hi) << 32) | ulong(lo)); +} + +inline void atomic_add_u64(device uint* ctr_u32, uint val) { + device atomic_uint* lo = reinterpret_cast(ctr_u32); + device atomic_uint* hi = reinterpret_cast(ctr_u32 + 1); + uint old_lo = atomic_fetch_add_explicit(lo, val, memory_order_relaxed); + if (old_lo + val < old_lo) { + atomic_fetch_add_explicit(hi, 1u, memory_order_relaxed); + } +} + +template +inline float to_f32(T x); +template <> inline float to_f32(half x) { return float(x); } +template <> inline float to_f32(float x) { return x; } + +template +inline float2 load_pair_f32(device const T* p) { + return float2(to_f32(p[0]), to_f32(p[1])); +} + +// Cross-tile WHT butterflies (specialized per D_CONST so C++14/MSL sees zero OOB array accesses) +template +inline void warp_wht_cross_tiles(thread float* v) { (void) v; } + +template <> +inline void warp_wht_cross_tiles<128>(thread float* v) { + for (int r = 0; r < 2; ++r) { + float a = v[r], b = v[2 + r]; + v[r] = a + b; + v[2 + r] = a - b; + } +} + +template <> +inline void warp_wht_cross_tiles<256>(thread float* v) { + for (int r = 0; r < 2; ++r) { + float a0 = v[r], b0 = v[2 + r]; + v[r] = a0 + b0; v[2 + r] = a0 - b0; + float a1 = v[4 + r], b1 = v[6 + r]; + v[4 + r] = a1 + b1; v[6 + r] = a1 - b1; + } + for (int r = 0; r < 4; ++r) { + float a = v[r], b = v[4 + r]; + v[r] = a + b; v[4 + r] = a - b; + } +} + +template <> +inline void warp_wht_cross_tiles<512>(thread float* v) { + for (int base = 0; base < 16; base += 4) { + for (int r = 0; r < 2; ++r) { + float a = v[base + r], b = v[base + 2 + r]; + v[base + r] = a + b; v[base + 2 + r] = a - b; + } + } + for (int base = 0; base < 16; base += 8) { + for (int r = 0; r < 4; ++r) { + float a = v[base + r], b = v[base + 4 + r]; + v[base + r] = a + b; v[base + 4 + r] = a - b; + } + } + for (int r = 0; r < 8; ++r) { + float a = v[r], b = v[8 + r]; + v[r] = a + b; v[8 + r] = a - b; + } +} + +// ---- In-register orthonormal Walsh-Hadamard Transform across a 32-lane SIMD group ---- +// Full-D orthonormal WHT for power-of-2 D in {64, 128, 256, 512}; +// 64-element block-diagonal orthonormal WHT for D in {192, 320}. +template +inline void warp_wht_inplace(thread float* v, uint lane) { + constexpr int C = D_CONST / 64; + for (int c = 0; c < C; ++c) { + float a = v[2 * c], b = v[2 * c + 1]; + v[2 * c] = a + b; + v[2 * c + 1] = a - b; + } + for (ushort mask = 1; mask < 32; mask <<= 1) { + const bool hi = (lane & uint(mask)) != 0u; + for (int i = 0; i < 2 * C; ++i) { + float x = v[i]; + float o = simd_shuffle_xor(x, mask); + v[i] = hi ? (o - x) : (x + o); + } + } + warp_wht_cross_tiles(v); + constexpr float inv_sqrt = + (D_CONST == 512) ? 0.04419417382415922f : + (D_CONST == 256) ? 0.0625f : + (D_CONST == 128) ? 0.08838834764831845f : + 0.125f; + for (int i = 0; i < 2 * C; ++i) v[i] *= inv_sqrt; +} + +inline void unpack_u32_to_8f(uint w, thread float* dst) { + dst[0] = float(int((w ) & 0xFu) - 8); + dst[1] = float(int((w >> 4) & 0xFu) - 8); + dst[2] = float(int((w >> 8) & 0xFu) - 8); + dst[3] = float(int((w >> 12) & 0xFu) - 8); + dst[4] = float(int((w >> 16) & 0xFu) - 8); + dst[5] = float(int((w >> 20) & 0xFu) - 8); + dst[6] = float(int((w >> 24) & 0xFu) - 8); + dst[7] = float(int((w >> 28) & 0xFu) - 8); +} + +// ---- Per-token INT8 and WHT-INT4 quantize / dequantize (1 SIMD group per token) ---- + +template +inline void quantize_token_int8_warp( + device const IN_T* tk, device const IN_T* tv, + device char* dtk, device char* dtv, + device float* out_sk, device float* out_sv, + int D, uint lane +) { + float mk = 0.0f, mv = 0.0f; + for (int d = int(lane); d < D; d += 32) { + float fk = fabs(to_f32(tk[d])); + float fv = fabs(to_f32(tv[d])); + if (fk > mk) mk = fk; + if (fv > mv) mv = fv; + } + mk = warp_max_all_f32(mk); + mv = warp_max_all_f32(mv); + float sk = fmax(mk / 127.0f, 1e-7f); + float sv = fmax(mv / 127.0f, 1e-7f); + float inv_sk = 1.0f / sk; + float inv_sv = 1.0f / sv; + if (lane == 0u) { + *out_sk = sk; + *out_sv = sv; + } + if ((D & 3) == 0 && ((ulong(dtk) | ulong(dtv)) & 3ul) == 0ul) { + int vecs = D >> 2; + device uint* dk4 = reinterpret_cast(dtk); + device uint* dv4 = reinterpret_cast(dtv); + for (int v = int(lane); v < vecs; v += 32) { + int base = v << 2; + uint pk = 0u, pv = 0u; + for (int i = 0; i < 4; ++i) { + char ck = char(int(fmin(fmax(rint(to_f32(tk[base + i]) * inv_sk), -127.0f), 127.0f))); + char cv = char(int(fmin(fmax(rint(to_f32(tv[base + i]) * inv_sv), -127.0f), 127.0f))); + pk |= uint(uchar(ck)) << uint(i * 8); + pv |= uint(uchar(cv)) << uint(i * 8); + } + dk4[v] = pk; + dv4[v] = pv; + } + } else { + for (int d = int(lane); d < D; d += 32) { + dtk[d] = char(int(fmin(fmax(rint(to_f32(tk[d]) * inv_sk), -127.0f), 127.0f))); + dtv[d] = char(int(fmin(fmax(rint(to_f32(tv[d]) * inv_sv), -127.0f), 127.0f))); + } + } +} + +template +inline void quantize_vec_wht4_warp( + device const IN_T* src, device const float* signs, + device uchar* dst_packed, device float* out_scale, uint lane +) { + constexpr int C = D_CONST / 64; + float v[2 * C]; + for (int c = 0; c < C; ++c) { + int d0 = c * 64 + 2 * int(lane); + float2 p = load_pair_f32(src + d0); + float2 s = load_pair_f32(signs + d0); + v[2 * c] = p.x * s.x; + v[2 * c + 1] = p.y * s.y; + } + warp_wht_inplace(v, lane); + float lm = 0.0f; + for (int i = 0; i < 2 * C; ++i) { + float a = fabs(v[i]); + if (isnan(a) || a > lm) lm = a; + } + float scale = fmax(warp_max_all_f32(lm) / 7.0f, 1e-30f); + if (lane == 0u) *out_scale = scale; + for (int c = 0; c < C; ++c) { + int q0 = int(fmin(fmax(rint(v[2 * c] / scale), -7.0f), 7.0f)); + int q1 = int(fmin(fmax(rint(v[2 * c + 1] / scale), -7.0f), 7.0f)); + dst_packed[c * 32 + int(lane)] = uchar(((q0 + 8) & 0xF) | (((q1 + 8) & 0xF) << 4)); + } +} + +template +inline void dequantize_vec_wht4_to_f16_warp( + device const uchar* src_packed, float scale, device const float* signs, + device half* dst, uint lane +) { + constexpr int C = D_CONST / 64; + float v[2 * C]; + for (int c = 0; c < C; ++c) { + uchar b = src_packed[c * 32 + int(lane)]; + v[2 * c] = float(int(b & 0xFu) - 8) * scale; + v[2 * c + 1] = float(int((b >> 4) & 0xFu) - 8) * scale; + } + warp_wht_inplace(v, lane); + for (int c = 0; c < C; ++c) { + int d0 = c * 64 + 2 * int(lane); + float2 s = load_pair_f32(signs + d0); + dst[d0] = half(v[2 * c] * s.x); + dst[d0 + 1] = half(v[2 * c + 1] * s.y); + } +} + +// ---- Strict outward-rounding Quest INT8 sealer (warp 0 min, warp 1 max) ---- + +inline void seal_quest_int8_head_dev( + device const float* k_min_f32, device const float* k_max_f32, + device char* dst_min, device char* dst_max, + device float* dst_smin, device float* dst_smax, + int D, uint warp_id, uint lane +) { + if (warp_id == 0u) { + float mx = 0.0f; + for (int d = int(lane); d < D; d += 32) { + float a = fabs(k_min_f32[d]); + if (a > mx) mx = a; + } + mx = warp_max_all_f32(mx); + float scale = fmax(mx * kQuestScaleFactor, 1e-30f); + if (lane == 0u) *dst_smin = scale; + for (int d = int(lane); d < D; d += 32) { + float x = k_min_f32[d]; + float q = fmin(fmax(floor(x / scale), -127.0f), 127.0f); + if (q * scale > x && q > -127.0f) q -= 1.0f; + dst_min[d] = char(int(q)); + } + } else if (warp_id == 1u) { + float mx = 0.0f; + for (int d = int(lane); d < D; d += 32) { + float a = fabs(k_max_f32[d]); + if (a > mx) mx = a; + } + mx = warp_max_all_f32(mx); + float scale = fmax(mx * kQuestScaleFactor, 1e-30f); + if (lane == 0u) *dst_smax = scale; + for (int d = int(lane); d < D; d += 32) { + float x = k_max_f32[d]; + float q = fmin(fmax(ceil(x / scale), -127.0f), 127.0f); + if (q * scale < x && q < 127.0f) q += 1.0f; + dst_max[d] = char(int(q)); + } + } +} + +inline void seal_quest_int8_head_tg( + threadgroup const float* k_min_f32, threadgroup const float* k_max_f32, + device char* dst_min, device char* dst_max, + device float* dst_smin, device float* dst_smax, + int D, uint warp_id, uint lane +) { + if (warp_id == 0u) { + float mx = 0.0f; + for (int d = int(lane); d < D; d += 32) { + float a = fabs(k_min_f32[d]); + if (a > mx) mx = a; + } + mx = warp_max_all_f32(mx); + float scale = fmax(mx * kQuestScaleFactor, 1e-30f); + if (lane == 0u) *dst_smin = scale; + for (int d = int(lane); d < D; d += 32) { + float x = k_min_f32[d]; + float q = fmin(fmax(floor(x / scale), -127.0f), 127.0f); + if (q * scale > x && q > -127.0f) q -= 1.0f; + dst_min[d] = char(int(q)); + } + } else if (warp_id == 1u) { + float mx = 0.0f; + for (int d = int(lane); d < D; d += 32) { + float a = fabs(k_max_f32[d]); + if (a > mx) mx = a; + } + mx = warp_max_all_f32(mx); + float scale = fmax(mx * kQuestScaleFactor, 1e-30f); + if (lane == 0u) *dst_smax = scale; + for (int d = int(lane); d < D; d += 32) { + float x = k_max_f32[d]; + float q = fmin(fmax(ceil(x / scale), -127.0f), 127.0f); + if (q * scale < x && q < 127.0f) q += 1.0f; + dst_max[d] = char(int(q)); + } + } +} + +// ---- Warp-level SphereIndex INT4 WHT sealer ---- + +template +inline void seal_sphere_block_warp( + device const T* k_blk, long tok_stride, + device const float* signs, int B, int rope_dim, + device uchar* dst_packed, device float* dst_scale, device half* dst_radii, + uint lane +) { + constexpr int C = D_CONST / 64; + float mu[2 * C]; + for (int i = 0; i < 2 * C; ++i) mu[i] = 0.0f; + + for (int t = 0; t < B; ++t) { + device const T* row = k_blk + long(t) * tok_stride; + for (int c = 0; c < C; ++c) { + int d0 = c * 64 + 2 * int(lane); + float2 p = load_pair_f32(row + d0); + mu[2 * c] += p.x; + mu[2 * c + 1] += p.y; + } + } + const float inv_B = 1.0f / float(B); + for (int i = 0; i < 2 * C; ++i) mu[i] *= inv_B; + + float max_sq_rope = 0.0f, max_sq_nope = 0.0f; + if (B > 1) { + for (int t = 0; t < B; ++t) { + device const T* row = k_blk + long(t) * tok_stride; + float sr = 0.0f, sn = 0.0f; + for (int c = 0; c < C; ++c) { + int d0 = c * 64 + 2 * int(lane); + float2 p = load_pair_f32(row + d0); + float df0 = p.x - mu[2 * c]; + float df1 = p.y - mu[2 * c + 1]; + if (d0 < rope_dim) sr = fma(df0, df0, sr); + else sn = fma(df0, df0, sn); + if (d0 + 1 < rope_dim) sr = fma(df1, df1, sr); + else sn = fma(df1, df1, sn); + } + sr = warp_sum_f32(sr); + sn = warp_sum_f32(sn); + if (lane == 0u) { + if (isnan(sr) || sr > max_sq_rope) max_sq_rope = sr; + if (isnan(sn) || sn > max_sq_nope) max_sq_nope = sn; + } + } + } + if (lane == 0u) { + dst_radii[0] = half(fmin(fmax(sqrt(max_sq_rope), 0.0f), 65504.0f)); + dst_radii[1] = half(fmin(fmax(sqrt(max_sq_nope), 0.0f), 65504.0f)); + } + + for (int c = 0; c < C; ++c) { + int d0 = c * 64 + 2 * int(lane); + float2 s = load_pair_f32(signs + d0); + mu[2 * c] *= s.x; + mu[2 * c + 1] *= s.y; + } + warp_wht_inplace(mu, lane); + float lm = 0.0f; + for (int i = 0; i < 2 * C; ++i) { + float a = fabs(mu[i]); + if (isnan(a) || a > lm) lm = a; + } + float scale = fmax(warp_max_all_f32(lm) / 7.0f, 1e-30f); + if (lane == 0u) *dst_scale = scale; + for (int c = 0; c < C; ++c) { + int q0 = int(fmin(fmax(rint(mu[2 * c] / scale), -7.0f), 7.0f)); + int q1 = int(fmin(fmax(rint(mu[2 * c + 1] / scale), -7.0f), 7.0f)); + dst_packed[c * 32 + int(lane)] = uchar(((q0 + 8) & 0xF) | (((q1 + 8) & 0xF) << 4)); + } +} + +// ---- Bijection-preserving page table rebind (single KV head) ---- + +inline void rebind_slot( + device int* g2c, device int* c2g, + int W, int M, int slot, int new_blk +) { + if (slot < 0 || slot >= W) return; + int old_cpu = g2c[slot]; + if (old_cpu >= 0 && old_cpu < M && c2g[old_cpu] == slot) c2g[old_cpu] = -1; + if (new_blk >= 0 && new_blk < M) { + int prev_slot = c2g[new_blk]; + if (prev_slot >= 0 && prev_slot < W && prev_slot != slot) g2c[prev_slot] = -1; + c2g[new_blk] = slot; + } + g2c[slot] = new_blk; +} + +inline int canonical_ring_slot(int blk, int lstart, int local_blocks) { + const int cap = local_blocks - 1; + if (cap <= 0) return -1; + int off = (blk - lstart) % cap; + if (off < 0) off += cap; + return lstart + off; +} + +// ---- Tiny stream-ordered scalar / q-staging / copy / zero kernels ---- + +kernel void bkv_set_scalars(constant BasinArgs& a [[buffer(0)]], + uint tid [[thread_position_in_grid]]) { + if (tid == 0u) { + if (a.p[0]) *static_cast(a.p[0]) = a.n[0]; + if (a.p[1]) *static_cast(a.p[1]) = a.i64[0]; + if (a.p[2]) *static_cast(a.p[2]) = a.i64[1]; + } +} + +kernel void bkv_stage_q_inc_step(constant BasinArgs& a [[buffer(0)]], + uint tid [[thread_index_in_threadgroup]], + uint nt [[threads_per_threadgroup]]) { + device float* dst_q = static_cast(a.p[0]); + device const float* src_q = static_cast(a.p[1]); + device long* d_step = static_cast(a.p[2]); + const int n_elems = a.n[0]; + for (int i = int(tid); i < n_elems; i += int(nt)) dst_q[i] = src_q[i]; + if (tid == 0u && d_step) *d_step = (*d_step) + 1L; +} + +kernel void bkv_fill_i32(constant BasinArgs& a [[buffer(0)]], + uint gid [[thread_position_in_grid]]) { + const long i = long(gid); + if (i < a.i64[0]) static_cast(a.p[0])[i] = a.n[0]; +} + +kernel void bkv_copy_f32_to_f16_rows(constant BasinArgs& a [[buffer(0)]], + uint gid [[thread_position_in_grid]]) { + const long idx = long(gid); + if (idx >= a.i64[2]) return; + const long row_elems = long(a.n[0]); + const long src_i = a.i64[0] * row_elems + idx; + const long dst_i = a.i64[1] * row_elems + idx; + device const float* k_in = static_cast(a.p[0]); + device const float* v_in = static_cast(a.p[1]); + device half* hot_k = static_cast(a.p[2]); + device half* hot_v = static_cast(a.p[3]); + hot_k[dst_i] = half(k_in[src_i]); + hot_v[dst_i] = half(v_in[src_i]); +} + +kernel void bkv_recompute_tail_extrema(constant BasinArgs& a [[buffer(0)]], + uint gid [[thread_position_in_grid]]) { + const int H_kv = a.n[0]; + const int B = a.n[1]; + const int D = a.n[2]; + const int slot = a.n[3]; + const int valid_toks = a.n[4]; + const long total = long(H_kv) * long(D); + const long idx = long(gid); + if (idx >= total) return; + + device const half* hot_k = static_cast(a.p[0]); + device float* tail_k_min = static_cast(a.p[1]); + device float* tail_k_max = static_cast(a.p[2]); + if (valid_toks <= 0) { + tail_k_min[idx] = 0.0f; + tail_k_max[idx] = 0.0f; + return; + } + const int h = int(idx / long(D)); + const int d = int(idx - long(h) * long(D)); + const long tok_stride = long(H_kv) * long(D); + const long base = long(slot) * long(B) * tok_stride + long(h) * long(D) + long(d); + float mn = float(hot_k[base]); + float mx = mn; + for (int t = 1; t < valid_toks; ++t) { + float f = float(hot_k[base + long(t) * tok_stride]); + mn = fmin(mn, f); + mx = fmax(mx, f); + } + tail_k_min[idx] = mn; + tail_k_max[idx] = mx; +} + +kernel void bkv_zero_f16_rows(constant BasinArgs& a [[buffer(0)]], + uint gid [[thread_position_in_grid]]) { + const long idx = long(gid); + if (idx >= a.i64[1]) return; + const long dst_i = a.i64[0] * long(a.n[0]) + idx; + static_cast(a.p[0])[dst_i] = half(0.0f); + static_cast(a.p[1])[dst_i] = half(0.0f); +} + +kernel void bkv_f16_to_f32(constant BasinArgs& a [[buffer(0)]], + uint gid [[thread_position_in_grid]]) { + const long i = long(gid); + if (i < a.i64[0]) { + static_cast(a.p[1])[i] = float(static_cast(a.p[0])[i]); + } +} + +// ---- 1. Shrunk-Box Quest INT8 Scorer (Fast Path D in {128, 256} + General Fallback) ---- + +template +inline void quest_load_fast(device const char* kmn, device const char* kmx, + float s_min, float s_max, uint lane, + thread float* fn, thread float* fx); + +template <> +inline void quest_load_fast<128>(device const char* kmn, device const char* kmx, + float s_min, float s_max, uint lane, + thread float* fn, thread float* fx) { + uint vn = reinterpret_cast(kmn)[lane]; + uint vx = reinterpret_cast(kmx)[lane]; + for (int k = 0; k < 4; ++k) { + fn[k] = float(char((vn >> uint(k * 8)) & 0xffu)) * s_min; + fx[k] = float(char((vx >> uint(k * 8)) & 0xffu)) * s_max; + } +} + +template <> +inline void quest_load_fast<256>(device const char* kmn, device const char* kmx, + float s_min, float s_max, uint lane, + thread float* fn, thread float* fx) { + uint2 vn = reinterpret_cast(kmn)[lane]; + uint2 vx = reinterpret_cast(kmx)[lane]; + for (int k = 0; k < 4; ++k) { + fn[k] = float(char((vn.x >> uint(k * 8)) & 0xffu)) * s_min; + fx[k] = float(char((vx.x >> uint(k * 8)) & 0xffu)) * s_max; + fn[k + 4] = float(char((vn.y >> uint(k * 8)) & 0xffu)) * s_min; + fx[k + 4] = float(char((vx.y >> uint(k * 8)) & 0xffu)) * s_max; + } +} + +template +kernel void bkv_quest_score_fast_t( + constant BasinArgs& a [[buffer(0)]], + uint2 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]] +) { + constexpr int kWarps = 8; + constexpr int kBlocksPerWarp = 4; + constexpr int kBlocksPerCta = kWarps * kBlocksPerWarp; + constexpr int kKW = D_CONST / 32; + constexpr int kSmemHalf = 2048; + + threadgroup float smem_q_hi[kSmemHalf]; + threadgroup float smem_q_lo[kSmemHalf]; + + const int H_q = a.n[0], H_kv = a.n[1], M = a.n[2], B = a.n[3], local_blocks = a.n[4]; + int elig_start = a.n[6], elig_end = a.n[7]; + const int reduce_mode = a.n[8]; + const float alpha = a.f[0]; + + const int h = int(group.y); + const int tile_start = int(group.x) * kBlocksPerCta; + if (h >= H_kv || tile_start >= M) return; + int tile_end = tile_start + kBlocksPerCta; + if (tile_end > M) tile_end = M; + + device float* out_row = static_cast(a.p[5]) + long(h) * long(M); + device const int* d_seq_len_ptr = static_cast(a.p[6]); + if (d_seq_len_ptr != nullptr) { + int sl = *d_seq_len_ptr; + int nb = sl > 0 ? ((sl + B - 1) / B) : 0; + elig_end = nb - local_blocks; + if (elig_end < 0) elig_end = 0; + if (elig_end > M) elig_end = M; + } + if (tile_start >= elig_end || tile_end <= elig_start) { + for (int b = tile_start + int(tid); b < tile_end; b += 256) out_row[b] = -INFINITY; + return; + } + + const int G = H_q / H_kv; + const float c_hi = 0.5f * (1.0f + alpha); + const float c_lo = 0.5f * (1.0f - alpha); + device const float* q_base = static_cast(a.p[0]) + long(h) * long(G) * long(D_CONST); + + const int q_elems = G * D_CONST; + for (int idx = int(tid); idx < q_elems; idx += 256) { + int g = idx / D_CONST; + int d = idx - g * D_CONST; + int l = d / kKW; + int k = d - l * kKW; + float qf = q_base[idx]; + float qp = isnan(qf) ? qf : (qf > 0.0f ? qf : 0.0f); + float qn = isnan(qf) ? qf : (qf < 0.0f ? qf : 0.0f); + int sidx = (g * kKW + k) * 32 + l; + smem_q_hi[sidx] = c_hi * qp + c_lo * qn; + smem_q_lo[sidx] = c_hi * qn + c_lo * qp; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + const uint warp_id = tid >> 5u; + const uint lane = tid & 31u; + device const char* kmin_base = static_cast(a.p[1]) + long(h) * long(M) * long(D_CONST); + device const char* kmax_base = static_cast(a.p[2]) + long(h) * long(M) * long(D_CONST); + device const float* smin_base = static_cast(a.p[3]) + long(h) * long(M); + device const float* smax_base = static_cast(a.p[4]) + long(h) * long(M); + const float inv_g = 1.0f / float(G); + + for (int it = 0; it < kBlocksPerWarp; ++it) { + int b = tile_start + it * kWarps + int(warp_id); + if (b >= tile_end) continue; + if (b < elig_start || b >= elig_end) { + if (lane == 0u) out_row[b] = -INFINITY; + continue; + } + device const char* kmn = kmin_base + long(b) * long(D_CONST); + device const char* kmx = kmax_base + long(b) * long(D_CONST); + float s_min = smin_base[b], s_max = smax_base[b]; + float fn[kKW], fx[kKW]; + quest_load_fast(kmn, kmx, s_min, s_max, lane, fn, fx); + float best = (reduce_mode == 0) ? -INFINITY : 0.0f; + for (int g = 0; g < G; ++g) { + float acc = 0.0f; + int base_s = g * kKW * 32 + int(lane); + for (int k = 0; k < kKW; ++k) { + acc = fma(smem_q_hi[base_s + k * 32], fx[k], acc); + acc = fma(smem_q_lo[base_s + k * 32], fn[k], acc); + } + acc = warp_sum_f32(acc); + if (lane == 0u) { + if (reduce_mode == 0) { + if (g == 0 || isnan(acc) || acc > best) best = acc; + } else { + best += acc; + } + } + } + if (lane == 0u) out_row[b] = (reduce_mode == 0) ? best : (best * inv_g); + } +} + +template [[host_name("bkv_quest_score_128")]] kernel decltype(bkv_quest_score_fast_t<128>) bkv_quest_score_fast_t<128>; +template [[host_name("bkv_quest_score_256")]] kernel decltype(bkv_quest_score_fast_t<256>) bkv_quest_score_fast_t<256>; + +kernel void bkv_quest_score_general( + constant BasinArgs& a [[buffer(0)]], + uint2 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]] +) { + constexpr int kWarps = 8; + constexpr int kBlocksPerWarp = 4; + constexpr int kBlocksPerCta = kWarps * kBlocksPerWarp; + constexpr int kSmemHalf = 2048; + + threadgroup float smem_q_hi[kSmemHalf]; + threadgroup float smem_q_lo[kSmemHalf]; + + const int H_q = a.n[0], H_kv = a.n[1], M = a.n[2], B = a.n[3], local_blocks = a.n[4], D = a.n[5]; + int elig_start = a.n[6], elig_end = a.n[7]; + const int reduce_mode = a.n[8]; + const float alpha = a.f[0]; + + const int h = int(group.y); + const int tile_start = int(group.x) * kBlocksPerCta; + if (h >= H_kv || tile_start >= M) return; + int tile_end = tile_start + kBlocksPerCta; + if (tile_end > M) tile_end = M; + + device float* out_row = static_cast(a.p[5]) + long(h) * long(M); + device const int* d_seq_len_ptr = static_cast(a.p[6]); + if (d_seq_len_ptr != nullptr) { + int sl = *d_seq_len_ptr; + int nb = sl > 0 ? ((sl + B - 1) / B) : 0; + elig_end = nb - local_blocks; + if (elig_end < 0) elig_end = 0; + if (elig_end > M) elig_end = M; + } + if (tile_start >= elig_end || tile_end <= elig_start) { + for (int b = tile_start + int(tid); b < tile_end; b += 256) out_row[b] = -INFINITY; + return; + } + + const int G = H_q / H_kv; + int g_chunk = kSmemHalf / D; + if (g_chunk > 8) g_chunk = 8; + if (g_chunk < 1) g_chunk = 1; + const float c_hi = 0.5f * (1.0f + alpha); + const float c_lo = 0.5f * (1.0f - alpha); + const uint warp_id = tid >> 5u; + const uint lane = tid & 31u; + + device const char* kmin_base = static_cast(a.p[1]) + long(h) * long(M) * long(D); + device const char* kmax_base = static_cast(a.p[2]) + long(h) * long(M) * long(D); + device const float* smin_base = static_cast(a.p[3]) + long(h) * long(M); + device const float* smax_base = static_cast(a.p[4]) + long(h) * long(M); + device const float* q_base = static_cast(a.p[0]) + long(h) * long(G) * long(D); + + float out_val[kBlocksPerWarp]; + for (int it = 0; it < kBlocksPerWarp; ++it) out_val[it] = (reduce_mode == 0) ? -INFINITY : 0.0f; + + for (int g0 = 0; g0 < G; g0 += g_chunk) { + int gc = G - g0; + if (gc > g_chunk) gc = g_chunk; + int q_elems = gc * D; + for (int idx = int(tid); idx < q_elems; idx += 256) { + float qf = q_base[long(g0) * long(D) + long(idx)]; + float qp = isnan(qf) ? qf : (qf > 0.0f ? qf : 0.0f); + float qn = isnan(qf) ? qf : (qf < 0.0f ? qf : 0.0f); + smem_q_hi[idx] = c_hi * qp + c_lo * qn; + smem_q_lo[idx] = c_hi * qn + c_lo * qp; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int it = 0; it < kBlocksPerWarp; ++it) { + int b = tile_start + it * kWarps + int(warp_id); + if (b >= elig_start && b < elig_end) { + device const char* kmn = kmin_base + long(b) * long(D); + device const char* kmx = kmax_base + long(b) * long(D); + float s_min = smin_base[b], s_max = smax_base[b]; + float acc[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; + for (int d = int(lane); d < D; d += 32) { + float fn = float(kmn[d]) * s_min; + float fx = float(kmx[d]) * s_max; + for (int g = 0; g < 8; ++g) { + if (g < gc) { + float av = acc[g]; + av = fma(smem_q_hi[g * D + d], fx, av); + av = fma(smem_q_lo[g * D + d], fn, av); + acc[g] = av; + } + } + } + for (int g = 0; g < 8; ++g) { + if (g < gc) { + float val = warp_sum_f32(acc[g]); + if (lane == 0u) { + if (reduce_mode == 0) { + if ((g0 == 0 && g == 0) || isnan(val) || val > out_val[it]) out_val[it] = val; + } else { + out_val[it] += val; + } + } + } + } + } + } + if (g0 + g_chunk < G) threadgroup_barrier(mem_flags::mem_threadgroup); + } + if (lane == 0u) { + const float inv_g = 1.0f / float(G); + for (int it = 0; it < kBlocksPerWarp; ++it) { + int b = tile_start + it * kWarps + int(warp_id); + if (b < tile_end) { + out_row[b] = (b < elig_start || b >= elig_end) + ? -INFINITY + : ((reduce_mode == 0) ? out_val[it] : (out_val[it] * inv_g)); + } + } + } +} + +// ---- 1b. Fused SphereIndex INT4 WHT Scorer ---- + +template +inline void sphere_unpack_block(device const uchar* p_blk, int gl, thread float* kv) { + constexpr int C = D_CONST / 64; + device const uint* p_u32 = reinterpret_cast(p_blk); + for (int u = 0; u < C; ++u) { + unpack_u32_to_8f(p_u32[u * 8 + gl], kv + u * 8); + } +} + +template <> +inline void sphere_unpack_block<64>(device const uchar* p_blk, int gl, thread float* kv) { + uint2 raw = reinterpret_cast(p_blk)[gl]; + unpack_u32_to_8f(raw.x, kv + 0); + unpack_u32_to_8f(raw.y, kv + 8); +} + +inline void sphere_unpack_u4(device const uchar* p_blk, int gl, thread float* kv) { + uint4 raw = reinterpret_cast(p_blk)[gl]; + unpack_u32_to_8f(raw.x, kv + 0); + unpack_u32_to_8f(raw.y, kv + 8); + unpack_u32_to_8f(raw.z, kv + 16); + unpack_u32_to_8f(raw.w, kv + 24); +} + +template <> +inline void sphere_unpack_block<128>(device const uchar* p_blk, int gl, thread float* kv) { + sphere_unpack_u4(p_blk, gl, kv); +} +template <> +inline void sphere_unpack_block<256>(device const uchar* p_blk, int gl, thread float* kv) { + sphere_unpack_u4(p_blk, gl, kv); +} +template <> +inline void sphere_unpack_block<512>(device const uchar* p_blk, int gl, thread float* kv) { + sphere_unpack_u4(p_blk, gl, kv); +} + +template +kernel void bkv_sphere_score_t( + constant BasinArgs& a [[buffer(0)]], + uint2 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]] +) { + constexpr int NUM_WARPS = 8; + constexpr int C = D_CONST / 64; + constexpr int SUBWARP = (D_CONST == 64 || D_CONST == 128) ? 4 : (D_CONST == 512 ? 16 : 8); + constexpr int SUBWARPS_PER_CTA = NUM_WARPS * (32 / SUBWARP); + constexpr int BLOCKS_PER_CTA = 64; + constexpr int ITERS = BLOCKS_PER_CTA / SUBWARPS_PER_CTA; + constexpr int ELEMS = D_CONST / SUBWARP; + constexpr int Q_TILE = (D_CONST <= 128) ? 32 : (D_CONST <= 256 ? 16 : (D_CONST == 320 ? 12 : 8)); + + threadgroup float smem_q[Q_TILE * D_CONST]; + threadgroup float smem_qn_rope[Q_TILE]; + threadgroup float smem_qn_nope[Q_TILE]; + + const int H_q = a.n[0], H_kv = a.n[1], M = a.n[2], B = a.n[3], local_blocks = a.n[4], rope_dim = a.n[5]; + int elig_start = a.n[6], elig_end = a.n[7]; + const int reduce_mode = a.n[8]; + const float beta = a.f[0]; + + const int tile_start = int(group.x) * BLOCKS_PER_CTA; + const int h_kv = int(group.y); + if (h_kv >= H_kv || tile_start >= M) return; + int tile_end = tile_start + BLOCKS_PER_CTA; + if (tile_end > M) tile_end = M; + + device float* out_row = static_cast(a.p[5]) + long(h_kv) * long(M); + device const int* d_seq_len_ptr = static_cast(a.p[6]); + if (d_seq_len_ptr != nullptr) { + int sl = *d_seq_len_ptr; + int nb = sl > 0 ? ((sl + B - 1) / B) : 0; + elig_end = nb - local_blocks; + if (elig_end < 0) elig_end = 0; + if (elig_end > M) elig_end = M; + } + if (tile_start >= elig_end || tile_end <= elig_start) { + for (int b = tile_start + int(tid); b < tile_end; b += 256) out_row[b] = -INFINITY; + return; + } + + const uint warp_id = tid >> 5u; + const uint lane = tid & 31u; + const int subwarp_id = int(tid) / SUBWARP; + const int gl = int(tid) & (SUBWARP - 1); + + const int G = H_q / H_kv; + const float inv_g = 1.0f / float(G); + const bool use_beta = (beta != 0.0f); + + device const float* q_all = static_cast(a.p[0]); + device const uchar* packed_base = static_cast(a.p[1]) + (long(h_kv) * long(M)) * long(D_CONST / 2); + device const float* scale_base = static_cast(a.p[2]) + long(h_kv) * long(M); + device const half* radii_base = static_cast(a.p[3]) + (long(h_kv) * long(M)) * 2L; + device const float* signs = static_cast(a.p[4]); + + float best[ITERS]; + for (int it = 0; it < ITERS; ++it) best[it] = (reduce_mode == 0) ? -INFINITY : 0.0f; + + for (int q0 = 0; q0 < G; q0 += Q_TILE) { + int q_n = G - q0; + if (q_n > Q_TILE) q_n = Q_TILE; + + for (int ql = int(warp_id); ql < q_n; ql += NUM_WARPS) { + int g = q0 + ql; + device const float* q_vec = q_all + long(h_kv * G + g) * long(D_CONST); + float v[2 * C]; + float sq_r = 0.0f, sq_n = 0.0f; + for (int c = 0; c < C; ++c) { + int d0 = c * 64 + 2 * int(lane); + float2 pq = load_pair_f32(q_vec + d0); + if (use_beta) { + if (d0 < rope_dim) sq_r = fma(pq.x, pq.x, sq_r); + else sq_n = fma(pq.x, pq.x, sq_n); + if (d0 + 1 < rope_dim) sq_r = fma(pq.y, pq.y, sq_r); + else sq_n = fma(pq.y, pq.y, sq_n); + } + float2 ps = load_pair_f32(signs + d0); + v[2 * c] = pq.x * ps.x; + v[2 * c + 1] = pq.y * ps.y; + } + if (use_beta) { + sq_r = warp_sum_f32(sq_r); + sq_n = warp_sum_f32(sq_n); + if (lane == 0u) { + smem_qn_rope[ql] = sqrt(sq_r); + smem_qn_nope[ql] = sqrt(sq_n); + } + } + warp_wht_inplace(v, lane); + threadgroup float* sq_dst = smem_q + ql * D_CONST; + for (int c = 0; c < C; ++c) { + int d0 = c * 64 + 2 * int(lane); + for (int r = 0; r < 2; ++r) { + int d = d0 + r; + int dst_gl, dst_k; + if (D_CONST == 64) { + dst_gl = d >> 4; dst_k = d & 15; + } else if (D_CONST == 128 || D_CONST == 256 || D_CONST == 512) { + dst_gl = d >> 5; dst_k = d & 31; + } else { + dst_gl = (d >> 3) & 7; dst_k = ((d >> 6) << 3) | (d & 7); + } + sq_dst[dst_k * SUBWARP + dst_gl] = v[2 * c + r]; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + for (int it = 0; it < ITERS; ++it) { + int b = tile_start + it * SUBWARPS_PER_CTA + subwarp_id; + if (b >= tile_end) continue; + if (b < elig_start || b >= elig_end) { + if (q0 == 0 && gl == 0) out_row[b] = -INFINITY; + continue; + } + device const uchar* p_blk = packed_base + long(b) * long(D_CONST / 2); + float kv[ELEMS]; + sphere_unpack_block(p_blk, gl, kv); + float sc = 0.0f, rr = 0.0f, rn = 0.0f; + if (gl == 0) { + sc = scale_base[b]; + if (use_beta) { + device const half* rp = radii_base + long(b) * 2L; + rr = float(rp[0]); + rn = float(rp[1]); + } + } + float cur = best[it]; + for (int ql = 0; ql < q_n; ++ql) { + threadgroup const float* sq_ptr = smem_q + ql * D_CONST + gl; + float acc = 0.0f; + for (int k = 0; k < ELEMS; ++k) acc = fma(sq_ptr[k * SUBWARP], kv[k], acc); + for (ushort off = SUBWARP >> 1; off > 0; off >>= 1) + acc += simd_shuffle_xor(acc, off); + if (gl == 0) { + float s = acc * sc; + if (use_beta) s = fma(beta, fma(smem_qn_rope[ql], rr, smem_qn_nope[ql] * rn), s); + if (reduce_mode == 0) { + if ((q0 == 0 && ql == 0) || isnan(s) || s > cur) cur = s; + } else { + cur += s; + } + } + } + best[it] = cur; + } + if (q0 + Q_TILE < G) threadgroup_barrier(mem_flags::mem_threadgroup); + } + for (int it = 0; it < ITERS; ++it) { + int b = tile_start + it * SUBWARPS_PER_CTA + subwarp_id; + if (b < tile_end && b >= elig_start && b < elig_end && gl == 0) + out_row[b] = (reduce_mode == 0) ? best[it] : (best[it] * inv_g); + } +} + +#define INST_SPHERE_SCORE(D) \ + template [[host_name("bkv_sphere_score_" #D)]] kernel decltype(bkv_sphere_score_t) bkv_sphere_score_t; +INST_SPHERE_SCORE(64) +INST_SPHERE_SCORE(128) +INST_SPHERE_SCORE(192) +INST_SPHERE_SCORE(256) +INST_SPHERE_SCORE(320) +INST_SPHERE_SCORE(512) + +// ---- 2. Fused 1-Launch Radix Top-K + Bitonic Sort + 1-Hop Co-Fetch + LRS Evict + Rebind ---- + +inline bool valid_score(float sc) { + return !isnan(sc) && (sc != -INFINITY); +} + +inline float nextafter_neg_inf(float x) { + if (x == 0.0f) return as_type(0x80000001u); + uint bits = as_type(x); + bits = (x > 0.0f) ? (bits - 1u) : (bits + 1u); + return as_type(bits); +} + +inline float effective_score(device const float* row, int b, int elig_start, bool cofetch) { + float sc = row[b]; + if (!cofetch || b <= elig_start || !valid_score(sc)) return sc; + float prev = row[b - 1]; + if (isfinite(prev)) { + float prop = nextafter_neg_inf(prev); + if (prop > sc) sc = prop; + } + return sc; +} + +inline uint f32_to_ordered_u32(float f) { + if (f == 0.0f) f = 0.0f; + uint bits = as_type(f); + uint mask = (bits & 0x80000000u) ? 0xffffffffu : 0x80000000u; + return bits ^ mask; +} + +inline bool topk_better(uint ua, int ba, uint ub, int bb) { + if (ba < 0) return false; + if (bb < 0) return true; + return (ua > ub) || (ua == ub && ba < bb); +} + +inline bool victim_better(int ar, int ae, long al, int br, int be, long bl) { + if (ar < 0) return false; + if (br < 0) return true; + if (ae != be) return ae > be; + if (ae != 0) return ar < br; + if (al != bl) return al < bl; + return ar < br; +} + +kernel void bkv_topk_evict_rebind( + constant BasinArgs& a [[buffer(0)]], + uint h_u [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]] +) { + // 3-phase aliased threadgroup workspace: 24,576 B + ~1,772 B = ~26.3 KiB (< 32 KiB Metal limit). + // Phase 1 (Radix + Bitonic): top_u[2048] @ 0..8192, top_blk[2048] @ 8192..16384 + // Phase 2 (Protect + Misses): top_slot[2048] @ 0..8192, top_blk[2048] @ 8192..16384 + // Phase 3 (Evict + Rebind): sparse_g2c[2048] @ 0..8192, sparse_lrs[2048] @ 8192..24576 + threadgroup ulong s_buf[3072]; + threadgroup atomic_uint s_hist[256]; + threadgroup atomic_uint s_prot[64]; + threadgroup int s_misses[kMaxTransferCap]; + threadgroup int s_red_rel[8], s_red_empty[8]; + threadgroup long s_red_lrs[8]; + threadgroup int s_warp_gt[8], s_warp_eq[8]; + threadgroup uint s_u[5]; // [0]=prefix, [1]=mask, [2]=remaining, [3]=n_greater, [4]=total_valid + threadgroup int s_i[6]; // [0]=gt_off, [1]=eq_off, [2]=cgt, [3]=ceq, [4]=n_miss, [5]=best_rel + + const int H_kv = a.n[0], M = a.n[1], W = a.n[2], B = a.n[3], local_blocks = a.n[4]; + const int sink = a.n[5], lstart = a.n[6], elig_start = a.n[7]; + int elig_end = a.n[8]; + const int C = a.n[9]; + const bool successor_cofetch = (a.n[10] != 0); + long step = a.i64[0]; + + const int h = int(h_u); + if (h >= H_kv) return; + + device const int* d_seq_len_ptr = static_cast(a.p[8]); + device const long* d_step_ptr = static_cast(a.p[9]); + if (d_seq_len_ptr != nullptr) { + int sl = *d_seq_len_ptr; + int nb = sl > 0 ? ((sl + B - 1) / B) : 0; + elig_end = nb - local_blocks; + if (elig_end < 0) elig_end = 0; + if (elig_end > M) elig_end = M; + } + if (d_step_ptr != nullptr) step = *d_step_ptr; + + const uint warp_id = tid >> 5u; + const uint lane = tid & 31u; + const int s_cnt = lstart - sink; + + device int* src_cpu_blocks = static_cast(a.p[4]); + device int* dst_gpu_slots = static_cast(a.p[5]); + device uchar* admit_valid = static_cast(a.p[6]); + for (int j = int(tid); j < C; j += 256) { + src_cpu_blocks[h * C + j] = -1; + dst_gpu_slots[h * C + j] = -1; + admit_valid[h * C + j] = 0; + } + + const int n_elig = elig_end - elig_start; + if (n_elig <= 0 || s_cnt <= 0) return; + + int K_req = (s_cnt < n_elig) ? s_cnt : n_elig; + if (K_req > kMaxSparseSlots) K_req = kMaxSparseSlots; + + threadgroup uint* s_top_u = reinterpret_cast(s_buf); + threadgroup int* s_top_blk = reinterpret_cast(s_buf + 1024); + + device const float* score_row = static_cast(a.p[0]) + long(h) * long(M); + + // Pass 0 (bits 24..31) + atomic_store_explicit(&s_hist[tid], 0u, memory_order_relaxed); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int b = elig_start + int(tid); b < elig_end; b += 256) { + float sc = effective_score(score_row, b, elig_start, successor_cofetch); + if (valid_score(sc)) { + atomic_fetch_add_explicit(&s_hist[f32_to_ordered_u32(sc) >> 24], 1u, memory_order_relaxed); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (tid == 0u) { + uint tot = 0u; + for (int bin = 255; bin >= 0; --bin) tot += atomic_load_explicit(&s_hist[bin], memory_order_relaxed); + s_u[4] = tot; + s_u[0] = 0u; s_u[1] = 0u; s_u[3] = 0u; + s_u[2] = uint(K_req); + if (tot > uint(K_req)) { + uint acc = 0u; + for (int bin = 255; bin >= 0; --bin) { + uint cnt = atomic_load_explicit(&s_hist[bin], memory_order_relaxed); + if (acc + cnt >= uint(K_req)) { + s_u[3] = acc; + s_u[2] = uint(K_req) - acc; + s_u[0] = uint(bin) << 24; + s_u[1] = 0xff000000u; + break; + } + acc += cnt; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + const uint total_valid = s_u[4]; + if (total_valid == 0u) return; + + int K_eff = 0; + if (total_valid <= uint(K_req)) { + K_eff = int(total_valid); + if (tid == 0u) s_i[0] = 0; + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int base = elig_start; base < elig_end; base += 256) { + int b = base + int(tid); + bool ok = false; + uint u = 0u; + if (b < elig_end) { + float sc = effective_score(score_row, b, elig_start, successor_cofetch); + if (valid_score(sc)) { ok = true; u = f32_to_ordered_u32(sc); } + } + uint wm = b_ballot_32(ok); + int intra = int(popcount(wm & ((1u << lane) - 1u))); + if (lane == 0u) s_warp_gt[warp_id] = int(popcount(wm)); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid == 0u) { + int sum = 0; + for (int w = 0; w < 8; ++w) { int c = s_warp_gt[w]; s_warp_gt[w] = sum; sum += c; } + s_i[2] = s_i[0]; + s_i[0] += sum; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (ok) { + int dst = s_i[2] + s_warp_gt[warp_id] + intra; + if (dst < K_eff) { s_top_u[dst] = u; s_top_blk[dst] = b; } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } else { + K_eff = K_req; + for (int pass = 1; pass < 4; ++pass) { + int shift = 24 - pass * 8; + atomic_store_explicit(&s_hist[tid], 0u, memory_order_relaxed); + threadgroup_barrier(mem_flags::mem_threadgroup); + uint cm = s_u[1], cp = s_u[0]; + for (int b = elig_start + int(tid); b < elig_end; b += 256) { + float sc = effective_score(score_row, b, elig_start, successor_cofetch); + if (valid_score(sc)) { + uint u = f32_to_ordered_u32(sc); + if ((u & cm) == cp) { + atomic_fetch_add_explicit(&s_hist[(u >> uint(shift)) & 0xffu], 1u, memory_order_relaxed); + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid == 0u) { + uint acc = 0u, rem = s_u[2]; + for (int bin = 255; bin >= 0; --bin) { + uint cnt = atomic_load_explicit(&s_hist[bin], memory_order_relaxed); + if (acc + cnt >= rem) { + s_u[3] += acc; + s_u[2] = rem - acc; + s_u[0] |= (uint(bin) << uint(shift)); + s_u[1] |= (0xffu << uint(shift)); + break; + } + acc += cnt; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + const uint thresh = s_u[0]; + const int n_gt = int(s_u[3]); + const int n_eq_need = K_eff - n_gt; + if (tid == 0u) { s_i[0] = 0; s_i[1] = 0; } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int base = elig_start; base < elig_end; base += 256) { + int b = base + int(tid); + bool is_gt = false, is_eq = false; + uint u = 0u; + if (b < elig_end) { + float sc = effective_score(score_row, b, elig_start, successor_cofetch); + if (valid_score(sc)) { + u = f32_to_ordered_u32(sc); + is_gt = (u > thresh); + is_eq = (u == thresh); + } + } + uint mg = b_ballot_32(is_gt), me = b_ballot_32(is_eq); + uint lm = (1u << lane) - 1u; + int ig = int(popcount(mg & lm)), ie = int(popcount(me & lm)); + if (lane == 0u) { s_warp_gt[warp_id] = int(popcount(mg)); s_warp_eq[warp_id] = int(popcount(me)); } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid == 0u) { + int sg = 0, se = 0; + for (int w = 0; w < 8; ++w) { + int cg = s_warp_gt[w], ce = s_warp_eq[w]; + s_warp_gt[w] = sg; s_warp_eq[w] = se; + sg += cg; se += ce; + } + s_i[2] = s_i[0]; s_i[0] += sg; + s_i[3] = s_i[1]; s_i[1] += se; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (is_gt) { + int dst = s_i[2] + s_warp_gt[warp_id] + ig; + if (dst < n_gt) { s_top_u[dst] = u; s_top_blk[dst] = b; } + } + if (is_eq) { + int eqi = s_i[3] + s_warp_eq[warp_id] + ie; + if (eqi < n_eq_need) { int dst = n_gt + eqi; s_top_u[dst] = u; s_top_blk[dst] = b; } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } + + // Parallel Bitonic Sort: descending score, ascending block id tie-break + int P = 1; + while (P < K_eff) P <<= 1; + for (int i = K_eff + int(tid); i < P; i += 256) { s_top_u[i] = 0u; s_top_blk[i] = -1; } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int k = 2; k <= P; k <<= 1) { + for (int j = k >> 1; j > 0; j >>= 1) { + for (int idx = int(tid); idx < P; idx += 256) { + int ixj = idx ^ j; + if (ixj > idx) { + bool asc = ((idx & k) == 0); + uint ua = s_top_u[idx], ub = s_top_u[ixj]; + int ba = s_top_blk[idx], bb = s_top_blk[ixj]; + if (asc ? topk_better(ub, bb, ua, ba) : topk_better(ua, ba, ub, bb)) { + s_top_u[idx] = ub; s_top_blk[idx] = bb; + s_top_u[ixj] = ua; s_top_blk[ixj] = ba; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } + + // Phase 2: Protect hits (via s_prot bitmask) & collect misses into s_misses + device int* g2c = static_cast(a.p[1]) + long(h) * long(W); + device int* c2g = static_cast(a.p[2]) + long(h) * long(M); + device long* lrs_row = static_cast(a.p[3]) + long(h) * long(W); + + int n_words = (s_cnt + 31) >> 5; + if (n_words > 64) n_words = 64; + if (int(tid) < n_words) atomic_store_explicit(&s_prot[tid], 0u, memory_order_relaxed); + threadgroup_barrier(mem_flags::mem_threadgroup); + + threadgroup int* s_top_slot = reinterpret_cast(s_buf); + for (int i = int(tid); i < K_eff; i += 256) { + int blk = s_top_blk[i]; + int slot = (blk >= 0 && blk < M) ? c2g[blk] : kInvalidSlot; + s_top_slot[i] = slot; + if (slot >= sink && slot < lstart) { + int rel = slot - sink; + if (rel < kMaxSparseSlots) { + atomic_fetch_or_explicit(&s_prot[rel >> 5], 1u << uint(rel & 31), memory_order_relaxed); + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (tid == 0u) { + int max_c = (C < kMaxTransferCap) ? C : kMaxTransferCap; + int nm = 0; + for (int i = 0; i < K_eff && nm < max_c; ++i) { + int slot = s_top_slot[i]; + if (slot < 0 && slot != kInvalidSlot) s_misses[nm++] = s_top_blk[i]; + } + s_i[4] = nm; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Phase 3: Stage sparse page table & LRS (refreshing protected hits to `step`), evict LRS victims, rebind + threadgroup int* s_sparse_g2c = reinterpret_cast(s_buf); + threadgroup long* s_sparse_lrs = reinterpret_cast(s_buf + 1024); + for (int rel = int(tid); rel < s_cnt; rel += 256) { + s_sparse_g2c[rel] = g2c[sink + rel]; + bool is_prot = (rel < kMaxSparseSlots) && + ((atomic_load_explicit(&s_prot[rel >> 5], memory_order_relaxed) & (1u << uint(rel & 31))) != 0u); + s_sparse_lrs[rel] = is_prot ? step : lrs_row[sink + rel]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + const int n_miss_total = s_i[4]; + uint admitted_local = 0u; + for (int j = 0; j < n_miss_total; ++j) { + int my_rel = -1, my_empty = 0; + long my_lrs = (1L << 62); + for (int rel = int(tid); rel < s_cnt; rel += 256) { + if (rel < kMaxSparseSlots && + ((atomic_load_explicit(&s_prot[rel >> 5], memory_order_relaxed) & (1u << uint(rel & 31))) != 0u)) { + continue; + } + int cur_cpu = s_sparse_g2c[rel]; + int ce = (cur_cpu < 0) ? 1 : 0; + long cl = (ce != 0) ? 0L : s_sparse_lrs[rel]; + if (victim_better(rel, ce, cl, my_rel, my_empty, my_lrs)) { + my_rel = rel; my_empty = ce; my_lrs = cl; + } + } + for (ushort off = 16; off > 0; off >>= 1) { + int o_rel = simd_shuffle_down(my_rel, off); + int o_emp = simd_shuffle_down(my_empty, off); + long o_lrs = simd_shuffle_down_i64(my_lrs, off); + if (victim_better(o_rel, o_emp, o_lrs, my_rel, my_empty, my_lrs)) { + my_rel = o_rel; my_empty = o_emp; my_lrs = o_lrs; + } + } + if (lane == 0u) { + s_red_rel[warp_id] = my_rel; + s_red_empty[warp_id] = my_empty; + s_red_lrs[warp_id] = my_lrs; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid == 0u) { + int br = -1, be = 0; + long bl = (1L << 62); + for (int w = 0; w < 8; ++w) { + if (victim_better(s_red_rel[w], s_red_empty[w], s_red_lrs[w], br, be, bl)) { + br = s_red_rel[w]; be = s_red_empty[w]; bl = s_red_lrs[w]; + } + } + s_i[5] = br; + if (br >= 0) { + int best_slot = sink + br; + if (br < kMaxSparseSlots) { + atomic_fetch_or_explicit(&s_prot[br >> 5], 1u << uint(br & 31), memory_order_relaxed); + } + int old_cpu = s_sparse_g2c[br]; + if (old_cpu >= 0 && old_cpu < M) c2g[old_cpu] = -1; + int new_cpu = s_misses[j]; + s_sparse_g2c[br] = new_cpu; + c2g[new_cpu] = best_slot; + s_sparse_lrs[br] = step; + src_cpu_blocks[h * C + j] = new_cpu; + dst_gpu_slots[h * C + j] = best_slot; + admit_valid[h * C + j] = 1; + ++admitted_local; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (s_i[5] < 0) break; + } + + if (tid == 0u && admitted_local > 0u && a.p[7] != nullptr) { + atomic_add_u64(static_cast(a.p[7]), admitted_local); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int rel = int(tid); rel < s_cnt; rel += 256) { + g2c[sink + rel] = s_sparse_g2c[rel]; + lrs_row[sink + rel] = s_sparse_lrs[rel]; + } +} + +// ---- 3. Zero-Copy UMA/UVA & Staged Host KV -> GPU Hot Slab Gather (NHD FP16) ---- + +kernel void bkv_uva_gather_i8( + constant BasinArgs& a [[buffer(0)]], + uint task_u [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]], + uint nt [[threads_per_threadgroup]] +) { + const int H_kv = a.n[0], C = a.n[1], M = a.n[2], W = a.n[3], B = a.n[4], D = a.n[5]; + const int task = int(task_u); + device const uchar* valid = static_cast(a.p[8]); + if (task >= H_kv * C || valid[task] == 0) return; + + const int h = task / C; + const int sb = static_cast(a.p[6])[task]; + const int ds = static_cast(a.p[7])[task]; + if (h >= H_kv || sb < 0 || sb >= M || ds < 0 || ds >= W) return; + + const long blk_elems = long(B) * long(D); + const long src_idx = long(h) * long(M) + long(sb); + device const char* sk_src = static_cast(a.p[0]) + src_idx * blk_elems; + device const char* sv_src = static_cast(a.p[1]) + src_idx * blk_elems; + device const float* ks_ptr = static_cast(a.p[2]) + src_idx * long(B); + device const float* vs_ptr = static_cast(a.p[3]) + src_idx * long(B); + + const long tok_stride = long(H_kv) * long(D); + const long dst_base = long(ds) * long(B) * tok_stride + long(h) * long(D); + device half* dk = static_cast(a.p[4]) + dst_base; + device half* dv = static_cast(a.p[5]) + dst_base; + + if ((D & 3) == 0 && ((ulong(sk_src) | ulong(sv_src)) & 3ul) == 0ul) { + const long vecs = blk_elems >> 2; + device const uint* k4 = reinterpret_cast(sk_src); + device const uint* v4 = reinterpret_cast(sv_src); + for (long v = long(tid); v < vecs; v += long(nt)) { + long base = v << 2; + long tok = base / long(D); + long d0 = base - tok * long(D); + float ks = ks_ptr[tok], vs = vs_ptr[tok]; + uint pk = k4[v], pv = v4[v]; + long off = tok * tok_stride + d0; + for (int i = 0; i < 4; ++i) { + dk[off + i] = half(float(char((pk >> uint(i * 8)) & 0xffu)) * ks); + dv[off + i] = half(float(char((pv >> uint(i * 8)) & 0xffu)) * vs); + } + } + } else { + for (long idx = long(tid); idx < blk_elems; idx += long(nt)) { + long tok = idx / long(D), d = idx - tok * long(D); + long off = tok * tok_stride + d; + dk[off] = half(float(sk_src[idx]) * ks_ptr[tok]); + dv[off] = half(float(sv_src[idx]) * vs_ptr[tok]); + } + } +} + +template +kernel void bkv_uva_gather_wht4_t( + constant BasinArgs& a [[buffer(0)]], + uint task_u [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]] +) { + const int H_kv = a.n[0], C = a.n[1], M = a.n[2], W = a.n[3], B = a.n[4]; + const int task = int(task_u); + device const uchar* valid = static_cast(a.p[8]); + if (task >= H_kv * C || valid[task] == 0) return; + + const int h = task / C; + const int sb = static_cast(a.p[6])[task]; + const int ds = static_cast(a.p[7])[task]; + if (h >= H_kv || sb < 0 || sb >= M || ds < 0 || ds >= W) return; + + constexpr int D_HALF = D_CONST / 2; + const long blk_bytes = long(B) * long(D_HALF); + const long src_idx = long(h) * long(M) + long(sb); + device const uchar* sk_src = static_cast(a.p[0]) + src_idx * blk_bytes; + device const uchar* sv_src = static_cast(a.p[1]) + src_idx * blk_bytes; + device const float* ks_ptr = static_cast(a.p[2]) + src_idx * long(B); + device const float* vs_ptr = static_cast(a.p[3]) + src_idx * long(B); + device const float* signs = static_cast(a.p[9]); + + const long tok_stride = long(H_kv) * long(D_CONST); + const long dst_base = long(ds) * long(B) * tok_stride + long(h) * long(D_CONST); + device half* dk = static_cast(a.p[4]) + dst_base; + device half* dv = static_cast(a.p[5]) + dst_base; + + const uint warp_id = tid >> 5u; + const uint lane = tid & 31u; + for (int tok = int(warp_id); tok < B; tok += 8) { + dequantize_vec_wht4_to_f16_warp(sk_src + long(tok) * long(D_HALF), ks_ptr[tok], + signs, dk + long(tok) * tok_stride, lane); + dequantize_vec_wht4_to_f16_warp(sv_src + long(tok) * long(D_HALF), vs_ptr[tok], + signs, dv + long(tok) * tok_stride, lane); + } +} + +#define INST_UVA_GATHER_WHT4(D) \ + template [[host_name("bkv_uva_gather_wht4_" #D)]] kernel decltype(bkv_uva_gather_wht4_t) bkv_uva_gather_wht4_t; +INST_UVA_GATHER_WHT4(64) +INST_UVA_GATHER_WHT4(128) +INST_UVA_GATHER_WHT4(192) +INST_UVA_GATHER_WHT4(256) +INST_UVA_GATHER_WHT4(320) +INST_UVA_GATHER_WHT4(512) + +kernel void bkv_staged_gather_i8( + constant BasinArgs& a [[buffer(0)]], + uint task_u [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]], + uint nt [[threads_per_threadgroup]] +) { + const int n_valid = a.n[0], H_kv = a.n[1], W = a.n[2], B = a.n[3], D = a.n[4]; + const int task = int(task_u); + if (task >= n_valid) return; + const int h = static_cast(a.p[4])[task]; + const int ds = static_cast(a.p[5])[task]; + if (h < 0 || h >= H_kv || ds < 0 || ds >= W) return; + + const long blk_elems = long(B) * long(D); + device const char* sk_src = static_cast(a.p[0]) + long(task) * blk_elems; + device const char* sv_src = static_cast(a.p[1]) + long(task) * blk_elems; + device const float* ks_ptr = static_cast(a.p[2]) + long(task) * long(B); + device const float* vs_ptr = static_cast(a.p[3]) + long(task) * long(B); + + const long tok_stride = long(H_kv) * long(D); + const long dst_base = long(ds) * long(B) * tok_stride + long(h) * long(D); + device half* dk = static_cast(a.p[6]) + dst_base; + device half* dv = static_cast(a.p[7]) + dst_base; + for (long idx = long(tid); idx < blk_elems; idx += long(nt)) { + long tok = idx / long(D), d = idx - tok * long(D); + long off = tok * tok_stride + d; + dk[off] = half(float(sk_src[idx]) * ks_ptr[tok]); + dv[off] = half(float(sv_src[idx]) * vs_ptr[tok]); + } +} + +template +kernel void bkv_staged_gather_wht4_t( + constant BasinArgs& a [[buffer(0)]], + uint task_u [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]] +) { + const int n_valid = a.n[0], H_kv = a.n[1], W = a.n[2], B = a.n[3]; + const int task = int(task_u); + if (task >= n_valid) return; + const int h = static_cast(a.p[4])[task]; + const int ds = static_cast(a.p[5])[task]; + if (h < 0 || h >= H_kv || ds < 0 || ds >= W) return; + + constexpr int D_HALF = D_CONST / 2; + const long blk_bytes = long(B) * long(D_HALF); + device const uchar* sk_src = static_cast(a.p[0]) + long(task) * blk_bytes; + device const uchar* sv_src = static_cast(a.p[1]) + long(task) * blk_bytes; + device const float* ks_ptr = static_cast(a.p[2]) + long(task) * long(B); + device const float* vs_ptr = static_cast(a.p[3]) + long(task) * long(B); + device const float* signs = static_cast(a.p[8]); + + const long tok_stride = long(H_kv) * long(D_CONST); + const long dst_base = long(ds) * long(B) * tok_stride + long(h) * long(D_CONST); + device half* dk = static_cast(a.p[6]) + dst_base; + device half* dv = static_cast(a.p[7]) + dst_base; + + const uint warp_id = tid >> 5u; + const uint lane = tid & 31u; + for (int tok = int(warp_id); tok < B; tok += 8) { + dequantize_vec_wht4_to_f16_warp(sk_src + long(tok) * long(D_HALF), ks_ptr[tok], + signs, dk + long(tok) * tok_stride, lane); + dequantize_vec_wht4_to_f16_warp(sv_src + long(tok) * long(D_HALF), vs_ptr[tok], + signs, dv + long(tok) * tok_stride, lane); + } +} + +#define INST_STAGED_GATHER_WHT4(D) \ + template [[host_name("bkv_staged_gather_wht4_" #D)]] kernel decltype(bkv_staged_gather_wht4_t) bkv_staged_gather_wht4_t; +INST_STAGED_GATHER_WHT4(64) +INST_STAGED_GATHER_WHT4(128) +INST_STAGED_GATHER_WHT4(192) +INST_STAGED_GATHER_WHT4(256) +INST_STAGED_GATHER_WHT4(320) +INST_STAGED_GATHER_WHT4(512) + +// ---- 4. 1-Launch Block-Boundary Flush + Ring Rotate + Seal + Zero + Rebind ---- + +kernel void bkv_flush_rotate_seal_quest_i8( + constant BasinArgs& a [[buffer(0)]], + uint h_u [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]] +) { + const int H_kv = a.n[0], W = a.n[1], M = a.n[2], B = a.n[3], D = a.n[4]; + const int max_seq_len = a.n[6], local_blocks = a.n[7], lstart = a.n[8]; + const int cpu_M = a.n[9], cpu_dst_blk = a.n[10], static_pos = a.n[11]; + long step = a.i64[0]; + + const int h = int(h_u); + if (h >= H_kv) return; + + device const long* d_pos_ptr = static_cast(a.p[16]); + device const int* d_seq_len_ptr = static_cast(a.p[17]); + device const long* d_step_ptr = static_cast(a.p[18]); + + int pos = static_pos; + if (d_pos_ptr != nullptr) pos = int(*d_pos_ptr); + else if (d_seq_len_ptr != nullptr) pos = *d_seq_len_ptr; + if (pos <= 0 || pos >= max_seq_len) return; + const int new_blk = pos / B; + if (pos != new_blk * B) return; + if (d_step_ptr != nullptr) step = *d_step_ptr; + + const int prev_blk = new_blk - 1; + const int prev_slot = (new_blk < W) ? prev_blk : (W - 1); + const int new_slot = (new_blk < W) ? new_blk : (W - 1); + const int ring_slot = (new_blk < W) ? -1 : canonical_ring_slot(prev_blk, lstart, local_blocks); + const int host_blk = (cpu_dst_blk >= 0) ? cpu_dst_blk : prev_blk; + + const uint warp_id = tid >> 5u; + const uint lane = tid & 31u; + const long tok_stride = long(H_kv) * long(D); + const long slot_stride = long(B) * tok_stride; + const long head_off = long(h) * long(D); + const long blk_elems = long(B) * long(D); + + device half* hot_k = static_cast(a.p[0]); + device half* hot_v = static_cast(a.p[1]); + + // 1) Quantize & flush prev_slot -> pinned host (or non-UVA staging) + if (prev_slot >= 0 && prev_slot < W && prev_blk >= 0 && prev_blk < M && host_blk >= 0 && host_blk < cpu_M) { + const long src_base = long(prev_slot) * slot_stride + head_off; + const long dst_blk_idx = long(h) * long(cpu_M) + long(host_blk); + device float* sk_ptr = static_cast(a.p[4]) + dst_blk_idx * long(B); + device float* sv_ptr = static_cast(a.p[5]) + dst_blk_idx * long(B); + device char* dk = static_cast(a.p[2]) + dst_blk_idx * blk_elems; + device char* dv = static_cast(a.p[3]) + dst_blk_idx * blk_elems; + for (int t = int(warp_id); t < B; t += 8) { + device const half* tk = hot_k + src_base + long(t) * tok_stride; + device const half* tv = hot_v + src_base + long(t) * tok_stride; + quantize_token_int8_warp(tk, tv, dk + long(t) * long(D), dv + long(t) * long(D), + sk_ptr + t, sv_ptr + t, D, lane); + } + } + + // 2) Copy prev_slot -> ring_slot when rotating into local ring + if (ring_slot >= 0 && ring_slot < W && ring_slot != prev_slot) { + const long src_base = long(prev_slot) * slot_stride + head_off; + const long dst_base = long(ring_slot) * slot_stride + head_off; + for (long idx = long(tid); idx < blk_elems; idx += 256L) { + long t = idx / long(D), d = idx - t * long(D); + long off = t * tok_stride + d; + hot_k[dst_base + off] = hot_k[src_base + off]; + hot_v[dst_base + off] = hot_v[src_base + off]; + } + } + + // 3) Seal completed block into Quest INT8 GPU index + device const float* tail_k_min = static_cast(a.p[9]); + device const float* tail_k_max = static_cast(a.p[10]); + device char* idx_k_min = static_cast(a.p[11]); + device char* idx_k_max = static_cast(a.p[12]); + device float* idx_smin = static_cast(a.p[13]); + device float* idx_smax = static_cast(a.p[14]); + if (prev_blk >= 0 && prev_blk < M && tail_k_min != nullptr && idx_k_min != nullptr) { + const long bidx = long(h) * long(M) + long(prev_blk); + seal_quest_int8_head_dev( + tail_k_min + long(h) * long(D), tail_k_max + long(h) * long(D), + idx_k_min + bidx * long(D), idx_k_max + bidx * long(D), + idx_smin + bidx, idx_smax + bidx, D, warp_id, lane); + } + + threadgroup_barrier(mem_flags::mem_device | mem_flags::mem_threadgroup); + + // 4) Zero new_slot + if (new_slot >= 0 && new_slot < W) { + const long dst_base = long(new_slot) * slot_stride + head_off; + const half zf = half(0.0f); + for (long idx = long(tid); idx < blk_elems; idx += 256L) { + long t = idx / long(D), d = idx - t * long(D); + long off = t * tok_stride + d; + hot_k[dst_base + off] = zf; + hot_v[dst_base + off] = zf; + } + } + + // 5) Rebind page tables (ring first, then new open slot) + if (tid == 0u) { + device int* g2c = static_cast(a.p[6]) + long(h) * long(W); + device int* c2g = static_cast(a.p[7]) + long(h) * long(M); + device long* lrs = static_cast(a.p[8]) + long(h) * long(W); + if (ring_slot >= 0 && ring_slot < W && prev_blk >= 0 && prev_blk < M) { + rebind_slot(g2c, c2g, W, M, ring_slot, prev_blk); + lrs[ring_slot] = step; + } + if (new_slot >= 0 && new_slot < W && new_blk >= 0 && new_blk < M) { + rebind_slot(g2c, c2g, W, M, new_slot, new_blk); + lrs[new_slot] = step; + } + } +} + +template +kernel void bkv_flush_rotate_seal_wht_t( + constant BasinArgs& a [[buffer(0)]], + uint h_u [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]] +) { + const int H_kv = a.n[0], W = a.n[1], M = a.n[2], B = a.n[3], rope_dim = a.n[5]; + const int max_seq_len = a.n[6], local_blocks = a.n[7], lstart = a.n[8]; + const int cpu_M = a.n[9], cpu_dst_blk = a.n[10], static_pos = a.n[11]; + const bool is_sphere = (a.n[12] != 0); + const bool is_wht4 = (a.n[13] != 0); + long step = a.i64[0]; + + const int h = int(h_u); + if (h >= H_kv) return; + + device const long* d_pos_ptr = static_cast(a.p[16]); + device const int* d_seq_len_ptr = static_cast(a.p[17]); + device const long* d_step_ptr = static_cast(a.p[18]); + + int pos = static_pos; + if (d_pos_ptr != nullptr) pos = int(*d_pos_ptr); + else if (d_seq_len_ptr != nullptr) pos = *d_seq_len_ptr; + if (pos <= 0 || pos >= max_seq_len) return; + const int new_blk = pos / B; + if (pos != new_blk * B) return; + if (d_step_ptr != nullptr) step = *d_step_ptr; + + const int prev_blk = new_blk - 1; + const int prev_slot = (new_blk < W) ? prev_blk : (W - 1); + const int new_slot = (new_blk < W) ? new_blk : (W - 1); + const int ring_slot = (new_blk < W) ? -1 : canonical_ring_slot(prev_blk, lstart, local_blocks); + const int host_blk = (cpu_dst_blk >= 0) ? cpu_dst_blk : prev_blk; + + const uint warp_id = tid >> 5u; + const uint lane = tid & 31u; + const long tok_stride = long(H_kv) * long(D_CONST); + const long slot_stride = long(B) * tok_stride; + const long head_off = long(h) * long(D_CONST); + const long blk_elems = long(B) * long(D_CONST); + + device half* hot_k = static_cast(a.p[0]); + device half* hot_v = static_cast(a.p[1]); + device const float* wht_signs = static_cast(a.p[15]); + + // 1) Quantize & flush prev_slot -> host KV + if (prev_slot >= 0 && prev_slot < W && prev_blk >= 0 && prev_blk < M && host_blk >= 0 && host_blk < cpu_M) { + const long src_base = long(prev_slot) * slot_stride + head_off; + const long dst_blk_idx = long(h) * long(cpu_M) + long(host_blk); + device float* sk_ptr = static_cast(a.p[4]) + dst_blk_idx * long(B); + device float* sv_ptr = static_cast(a.p[5]) + dst_blk_idx * long(B); + if (is_wht4) { + constexpr int DH = D_CONST / 2; + device uchar* dk = static_cast(a.p[2]) + dst_blk_idx * (long(B) * long(DH)); + device uchar* dv = static_cast(a.p[3]) + dst_blk_idx * (long(B) * long(DH)); + for (int t = int(warp_id); t < B; t += 8) { + device const half* tk = hot_k + src_base + long(t) * tok_stride; + device const half* tv = hot_v + src_base + long(t) * tok_stride; + quantize_vec_wht4_warp(tk, wht_signs, dk + long(t) * long(DH), sk_ptr + t, lane); + quantize_vec_wht4_warp(tv, wht_signs, dv + long(t) * long(DH), sv_ptr + t, lane); + } + } else { + device char* dk = static_cast(a.p[2]) + dst_blk_idx * blk_elems; + device char* dv = static_cast(a.p[3]) + dst_blk_idx * blk_elems; + for (int t = int(warp_id); t < B; t += 8) { + device const half* tk = hot_k + src_base + long(t) * tok_stride; + device const half* tv = hot_v + src_base + long(t) * tok_stride; + quantize_token_int8_warp(tk, tv, dk + long(t) * long(D_CONST), dv + long(t) * long(D_CONST), + sk_ptr + t, sv_ptr + t, D_CONST, lane); + } + } + } + + // 2) Copy prev_slot -> ring_slot + if (ring_slot >= 0 && ring_slot < W && ring_slot != prev_slot) { + const long src_base = long(prev_slot) * slot_stride + head_off; + const long dst_base = long(ring_slot) * slot_stride + head_off; + for (long idx = long(tid); idx < blk_elems; idx += 256L) { + long t = idx / long(D_CONST), d = idx - t * long(D_CONST); + long off = t * tok_stride + d; + hot_k[dst_base + off] = hot_k[src_base + off]; + hot_v[dst_base + off] = hot_v[src_base + off]; + } + } + + // 3) Seal completed block into GPU index (BEFORE zeroing new_slot!) + if (is_sphere) { + if (warp_id == 0u && prev_slot >= 0 && prev_blk >= 0 && prev_blk < M) { + const long src_base = long(prev_slot) * slot_stride + head_off; + const long bidx = long(h) * long(M) + long(prev_blk); + device uchar* sp_packed = static_cast(a.p[9]); + device float* sp_scale = static_cast(a.p[10]); + device half* sp_radii = static_cast(a.p[11]); + seal_sphere_block_warp( + hot_k + src_base, tok_stride, wht_signs, B, rope_dim, + sp_packed + bidx * long(D_CONST / 2), sp_scale + bidx, sp_radii + bidx * 2L, lane); + } + } else { + device const float* tail_k_min = static_cast(a.p[9]); + device const float* tail_k_max = static_cast(a.p[10]); + device char* idx_k_min = static_cast(a.p[11]); + device char* idx_k_max = static_cast(a.p[12]); + device float* idx_smin = static_cast(a.p[13]); + device float* idx_smax = static_cast(a.p[14]); + if (prev_blk >= 0 && prev_blk < M && tail_k_min != nullptr && idx_k_min != nullptr) { + const long bidx = long(h) * long(M) + long(prev_blk); + seal_quest_int8_head_dev( + tail_k_min + long(h) * long(D_CONST), tail_k_max + long(h) * long(D_CONST), + idx_k_min + bidx * long(D_CONST), idx_k_max + bidx * long(D_CONST), + idx_smin + bidx, idx_smax + bidx, D_CONST, warp_id, lane); + } + } + + threadgroup_barrier(mem_flags::mem_device | mem_flags::mem_threadgroup); + + // 4) Zero new_slot + if (new_slot >= 0 && new_slot < W) { + const long dst_base = long(new_slot) * slot_stride + head_off; + const half zf = half(0.0f); + for (long idx = long(tid); idx < blk_elems; idx += 256L) { + long t = idx / long(D_CONST), d = idx - t * long(D_CONST); + long off = t * tok_stride + d; + hot_k[dst_base + off] = zf; + hot_v[dst_base + off] = zf; + } + } + + // 5) Rebind page tables + if (tid == 0u) { + device int* g2c = static_cast(a.p[6]) + long(h) * long(W); + device int* c2g = static_cast(a.p[7]) + long(h) * long(M); + device long* lrs = static_cast(a.p[8]) + long(h) * long(W); + if (ring_slot >= 0 && ring_slot < W && prev_blk >= 0 && prev_blk < M) { + rebind_slot(g2c, c2g, W, M, ring_slot, prev_blk); + lrs[ring_slot] = step; + } + if (new_slot >= 0 && new_slot < W && new_blk >= 0 && new_blk < M) { + rebind_slot(g2c, c2g, W, M, new_slot, new_blk); + lrs[new_slot] = step; + } + } +} + +#define INST_FLUSH_ROTATE_WHT(D) \ + template [[host_name("bkv_flush_rotate_seal_wht_" #D)]] kernel decltype(bkv_flush_rotate_seal_wht_t) bkv_flush_rotate_seal_wht_t; +INST_FLUSH_ROTATE_WHT(64) +INST_FLUSH_ROTATE_WHT(128) +INST_FLUSH_ROTATE_WHT(192) +INST_FLUSH_ROTATE_WHT(256) +INST_FLUSH_ROTATE_WHT(320) +INST_FLUSH_ROTATE_WHT(512) + +// ---- 5. Single-Token Decode Append (Dynamic / Graph-Safe & Eager) ---- + +kernel void bkv_append_decode_token( + constant BasinArgs& a [[buffer(0)]], + uint tid [[thread_index_in_threadgroup]], + uint nt [[threads_per_threadgroup]] +) { + const int static_pos = a.n[0]; + const int H_kv = a.n[1]; + const int W = a.n[2]; + const int M = a.n[3]; + const int B = a.n[4]; + const int D = a.n[5]; + const int max_seq_len = a.n[6]; + const long static_step = a.i64[0]; + + device const long* d_pos_ptr = static_cast(a.p[9]); + device int* d_seq_len = static_cast(a.p[10]); + device const long* d_step_ptr = static_cast(a.p[11]); + device long* d_eff_pos = static_cast(a.p[12]); + + int pos = static_pos; + if (d_pos_ptr != nullptr) pos = int(*d_pos_ptr); + else if (static_pos < 0 && d_seq_len != nullptr) pos = *d_seq_len; + if (pos < 0 || pos >= max_seq_len) return; + long step = (d_step_ptr != nullptr) ? (*d_step_ptr) : static_step; + + const int blk = pos / B; + const int off = pos - blk * B; + const int dst_slot = (blk < W) ? blk : (W - 1); + const int dst_row = dst_slot * B + off; + const long total = long(H_kv) * long(D); + const long row_off = long(dst_row) * total; + + device half* hot_k = static_cast(a.p[0]); + device half* hot_v = static_cast(a.p[1]); + device float* tail_k_min = static_cast(a.p[2]); + device float* tail_k_max = static_cast(a.p[3]); + device int* gpu_to_cpu = static_cast(a.p[4]); + device int* cpu_to_gpu = static_cast(a.p[5]); + device long* last_selected_step = static_cast(a.p[6]); + device const float* k_new = static_cast(a.p[7]); + device const float* v_new = static_cast(a.p[8]); + + for (long idx = long(tid); idx < total; idx += long(nt)) { + const half kv = half(k_new[idx]); + const half vv = half(v_new[idx]); + hot_k[row_off + idx] = kv; + hot_v[row_off + idx] = vv; + + if (tail_k_min != nullptr) { + const float f = float(kv); + if (off == 0) { + tail_k_min[idx] = f; + tail_k_max[idx] = f; + } else { + tail_k_min[idx] = fmin(tail_k_min[idx], f); + tail_k_max[idx] = fmax(tail_k_max[idx], f); + } + } + if (off == 0) { + int h = int(idx / long(D)); + int d = int(idx - long(h) * long(D)); + if (d == 0) { + rebind_slot(gpu_to_cpu + long(h) * long(W), + cpu_to_gpu + long(h) * long(M), W, M, dst_slot, blk); + last_selected_step[long(h) * long(W) + dst_slot] = step; + } + } + } + threadgroup_barrier(mem_flags::mem_device | mem_flags::mem_threadgroup); + if (tid == 0u) { + if (d_seq_len) *d_seq_len = pos + 1; + if (d_eff_pos) *d_eff_pos = long(dst_row); + } +} + +// ---- 6. Prefill Block Quantize + Index Seal Kernels ---- + +kernel void bkv_prefill_seal_quest_i8( + constant BasinArgs& a [[buffer(0)]], + threadgroup float* smem_mm [[threadgroup(0)]], + uint2 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]] +) { + const int H_kv = a.n[0], M = a.n[1], cpu_M = a.n[2], B = a.n[3], D = a.n[4]; + const int blk0 = a.n[6], cpu_blk0 = a.n[7], n_blks = a.n[8], in_tok_offset = a.n[9]; + const int bi = int(group.x); + const int h = int(group.y); + if (bi >= n_blks || h >= H_kv) return; + + const int blk = blk0 + bi; + const int cpu_blk = cpu_blk0 + bi; + const uint warp_id = tid >> 5u; + const uint lane = tid & 31u; + const long in_tok_stride = long(H_kv) * long(D); + const long in_blk_base = long(in_tok_offset + bi * B) * in_tok_stride + long(h) * long(D); + const long dst_blk_idx = long(h) * long(cpu_M) + long(cpu_blk); + + device const float* k_in = static_cast(a.p[0]); + device const float* v_in = static_cast(a.p[1]); + device char* dk = static_cast(a.p[2]) + dst_blk_idx * (long(B) * long(D)); + device char* dv = static_cast(a.p[3]) + dst_blk_idx * (long(B) * long(D)); + device float* sk_ptr = static_cast(a.p[4]) + dst_blk_idx * long(B); + device float* sv_ptr = static_cast(a.p[5]) + dst_blk_idx * long(B); + + for (int t = int(warp_id); t < B; t += 8) { + device const float* tk = k_in + in_blk_base + long(t) * in_tok_stride; + device const float* tv = v_in + in_blk_base + long(t) * in_tok_stride; + quantize_token_int8_warp(tk, tv, dk + long(t) * long(D), dv + long(t) * long(D), + sk_ptr + t, sv_ptr + t, D, lane); + } + + threadgroup float* s_min = smem_mm; + threadgroup float* s_max = smem_mm + D; + for (int d = int(tid); d < D; d += 256) { + float mn = float(half(k_in[in_blk_base + d])); + float mx = mn; + for (int t = 1; t < B; ++t) { + float f = float(half(k_in[in_blk_base + long(t) * in_tok_stride + d])); + mn = fmin(mn, f); + mx = fmax(mx, f); + } + s_min[d] = mn; + s_max[d] = mx; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + const long idx_blk = long(h) * long(M) + long(blk); + device char* idx_k_min = static_cast(a.p[6]); + device char* idx_k_max = static_cast(a.p[7]); + device float* idx_smin = static_cast(a.p[8]); + device float* idx_smax = static_cast(a.p[9]); + seal_quest_int8_head_tg(s_min, s_max, idx_k_min + idx_blk * long(D), idx_k_max + idx_blk * long(D), + idx_smin + idx_blk, idx_smax + idx_blk, D, warp_id, lane); +} + +template +kernel void bkv_prefill_seal_wht_t( + constant BasinArgs& a [[buffer(0)]], + uint2 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]] +) { + threadgroup float smem_mm[2 * D_CONST]; + const int H_kv = a.n[0], M = a.n[1], cpu_M = a.n[2], B = a.n[3], rope_dim = a.n[5]; + const int blk0 = a.n[6], cpu_blk0 = a.n[7], n_blks = a.n[8], in_tok_offset = a.n[9]; + const bool is_sphere = (a.n[10] != 0); + const bool is_wht4 = (a.n[11] != 0); + const int bi = int(group.x); + const int h = int(group.y); + if (bi >= n_blks || h >= H_kv) return; + + const int blk = blk0 + bi; + const int cpu_blk = cpu_blk0 + bi; + const uint warp_id = tid >> 5u; + const uint lane = tid & 31u; + const long in_tok_stride = long(H_kv) * long(D_CONST); + const long in_blk_base = long(in_tok_offset + bi * B) * in_tok_stride + long(h) * long(D_CONST); + const long dst_blk_idx = long(h) * long(cpu_M) + long(cpu_blk); + + device const float* k_in = static_cast(a.p[0]); + device const float* v_in = static_cast(a.p[1]); + device float* sk_ptr = static_cast(a.p[4]) + dst_blk_idx * long(B); + device float* sv_ptr = static_cast(a.p[5]) + dst_blk_idx * long(B); + device const float* wht_signs = static_cast(a.p[10]); + + if (is_wht4) { + constexpr int DH = D_CONST / 2; + device uchar* dk = static_cast(a.p[2]) + dst_blk_idx * (long(B) * long(DH)); + device uchar* dv = static_cast(a.p[3]) + dst_blk_idx * (long(B) * long(DH)); + for (int t = int(warp_id); t < B; t += 8) { + device const float* tk = k_in + in_blk_base + long(t) * in_tok_stride; + device const float* tv = v_in + in_blk_base + long(t) * in_tok_stride; + quantize_vec_wht4_warp(tk, wht_signs, dk + long(t) * long(DH), sk_ptr + t, lane); + quantize_vec_wht4_warp(tv, wht_signs, dv + long(t) * long(DH), sv_ptr + t, lane); + } + } else { + device char* dk = static_cast(a.p[2]) + dst_blk_idx * (long(B) * long(D_CONST)); + device char* dv = static_cast(a.p[3]) + dst_blk_idx * (long(B) * long(D_CONST)); + for (int t = int(warp_id); t < B; t += 8) { + device const float* tk = k_in + in_blk_base + long(t) * in_tok_stride; + device const float* tv = v_in + in_blk_base + long(t) * in_tok_stride; + quantize_token_int8_warp(tk, tv, dk + long(t) * long(D_CONST), dv + long(t) * long(D_CONST), + sk_ptr + t, sv_ptr + t, D_CONST, lane); + } + } + + const long idx_blk = long(h) * long(M) + long(blk); + if (is_sphere) { + if (warp_id == 0u) { + device uchar* sp_packed = static_cast(a.p[6]); + device float* sp_scale = static_cast(a.p[7]); + device half* sp_radii = static_cast(a.p[8]); + seal_sphere_block_warp( + k_in + in_blk_base, in_tok_stride, wht_signs, B, rope_dim, + sp_packed + idx_blk * long(D_CONST / 2), sp_scale + idx_blk, sp_radii + idx_blk * 2L, lane); + } + } else { + threadgroup float* s_min = smem_mm; + threadgroup float* s_max = smem_mm + D_CONST; + for (int d = int(tid); d < D_CONST; d += 256) { + float mn = float(half(k_in[in_blk_base + d])); + float mx = mn; + for (int t = 1; t < B; ++t) { + float f = float(half(k_in[in_blk_base + long(t) * in_tok_stride + d])); + mn = fmin(mn, f); + mx = fmax(mx, f); + } + s_min[d] = mn; + s_max[d] = mx; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + device char* idx_k_min = static_cast(a.p[6]); + device char* idx_k_max = static_cast(a.p[7]); + device float* idx_smin = static_cast(a.p[8]); + device float* idx_smax = static_cast(a.p[9]); + seal_quest_int8_head_tg(s_min, s_max, idx_k_min + idx_blk * long(D_CONST), idx_k_max + idx_blk * long(D_CONST), + idx_smin + idx_blk, idx_smax + idx_blk, D_CONST, warp_id, lane); + } +} + +#define INST_PREFILL_SEAL_WHT(D) \ + template [[host_name("bkv_prefill_seal_wht_" #D)]] kernel decltype(bkv_prefill_seal_wht_t) bkv_prefill_seal_wht_t; +INST_PREFILL_SEAL_WHT(64) +INST_PREFILL_SEAL_WHT(128) +INST_PREFILL_SEAL_WHT(192) +INST_PREFILL_SEAL_WHT(256) +INST_PREFILL_SEAL_WHT(320) +INST_PREFILL_SEAL_WHT(512) + +// Seal & quantize ONE full block already in FP16 hot_k/hot_v[src_slot] -> host[host_blk] & index[blk] + +kernel void bkv_seal_hot_slot_quest_i8( + constant BasinArgs& a [[buffer(0)]], + threadgroup float* smem_mm [[threadgroup(0)]], + uint h_u [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]] +) { + const int H_kv = a.n[0], M = a.n[1], cpu_M = a.n[2], B = a.n[3], D = a.n[4]; + const int src_slot = a.n[6], blk = a.n[7], host_blk = a.n[8]; + const int h = int(h_u); + if (h >= H_kv) return; + + const uint warp_id = tid >> 5u; + const uint lane = tid & 31u; + const long tok_stride = long(H_kv) * long(D); + const long src_base = long(src_slot) * long(B) * tok_stride + long(h) * long(D); + const long dst_blk_idx = long(h) * long(cpu_M) + long(host_blk); + + device const half* hot_k = static_cast(a.p[0]); + device const half* hot_v = static_cast(a.p[1]); + device char* dk = static_cast(a.p[2]) + dst_blk_idx * (long(B) * long(D)); + device char* dv = static_cast(a.p[3]) + dst_blk_idx * (long(B) * long(D)); + device float* sk_ptr = static_cast(a.p[4]) + dst_blk_idx * long(B); + device float* sv_ptr = static_cast(a.p[5]) + dst_blk_idx * long(B); + + for (int t = int(warp_id); t < B; t += 8) { + device const half* tk = hot_k + src_base + long(t) * tok_stride; + device const half* tv = hot_v + src_base + long(t) * tok_stride; + quantize_token_int8_warp(tk, tv, dk + long(t) * long(D), dv + long(t) * long(D), + sk_ptr + t, sv_ptr + t, D, lane); + } + + threadgroup float* s_min = smem_mm; + threadgroup float* s_max = smem_mm + D; + for (int d = int(tid); d < D; d += 256) { + float mn = float(hot_k[src_base + d]); + float mx = mn; + for (int t = 1; t < B; ++t) { + float f = float(hot_k[src_base + long(t) * tok_stride + d]); + mn = fmin(mn, f); + mx = fmax(mx, f); + } + s_min[d] = mn; + s_max[d] = mx; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + const long idx_blk = long(h) * long(M) + long(blk); + device char* idx_k_min = static_cast(a.p[6]); + device char* idx_k_max = static_cast(a.p[7]); + device float* idx_smin = static_cast(a.p[8]); + device float* idx_smax = static_cast(a.p[9]); + seal_quest_int8_head_tg(s_min, s_max, idx_k_min + idx_blk * long(D), idx_k_max + idx_blk * long(D), + idx_smin + idx_blk, idx_smax + idx_blk, D, warp_id, lane); +} + +template +kernel void bkv_seal_hot_slot_wht_t( + constant BasinArgs& a [[buffer(0)]], + uint h_u [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]] +) { + threadgroup float smem_mm[2 * D_CONST]; + const int H_kv = a.n[0], M = a.n[1], cpu_M = a.n[2], B = a.n[3], rope_dim = a.n[5]; + const int src_slot = a.n[6], blk = a.n[7], host_blk = a.n[8]; + const bool is_sphere = (a.n[9] != 0); + const bool is_wht4 = (a.n[10] != 0); + const int h = int(h_u); + if (h >= H_kv) return; + + const uint warp_id = tid >> 5u; + const uint lane = tid & 31u; + const long tok_stride = long(H_kv) * long(D_CONST); + const long src_base = long(src_slot) * long(B) * tok_stride + long(h) * long(D_CONST); + const long dst_blk_idx = long(h) * long(cpu_M) + long(host_blk); + + device const half* hot_k = static_cast(a.p[0]); + device const half* hot_v = static_cast(a.p[1]); + device float* sk_ptr = static_cast(a.p[4]) + dst_blk_idx * long(B); + device float* sv_ptr = static_cast(a.p[5]) + dst_blk_idx * long(B); + device const float* wht_signs = static_cast(a.p[10]); + + if (is_wht4) { + constexpr int DH = D_CONST / 2; + device uchar* dk = static_cast(a.p[2]) + dst_blk_idx * (long(B) * long(DH)); + device uchar* dv = static_cast(a.p[3]) + dst_blk_idx * (long(B) * long(DH)); + for (int t = int(warp_id); t < B; t += 8) { + device const half* tk = hot_k + src_base + long(t) * tok_stride; + device const half* tv = hot_v + src_base + long(t) * tok_stride; + quantize_vec_wht4_warp(tk, wht_signs, dk + long(t) * long(DH), sk_ptr + t, lane); + quantize_vec_wht4_warp(tv, wht_signs, dv + long(t) * long(DH), sv_ptr + t, lane); + } + } else { + device char* dk = static_cast(a.p[2]) + dst_blk_idx * (long(B) * long(D_CONST)); + device char* dv = static_cast(a.p[3]) + dst_blk_idx * (long(B) * long(D_CONST)); + for (int t = int(warp_id); t < B; t += 8) { + device const half* tk = hot_k + src_base + long(t) * tok_stride; + device const half* tv = hot_v + src_base + long(t) * tok_stride; + quantize_token_int8_warp(tk, tv, dk + long(t) * long(D_CONST), dv + long(t) * long(D_CONST), + sk_ptr + t, sv_ptr + t, D_CONST, lane); + } + } + + const long idx_blk = long(h) * long(M) + long(blk); + if (is_sphere) { + if (warp_id == 0u) { + device uchar* sp_packed = static_cast(a.p[6]); + device float* sp_scale = static_cast(a.p[7]); + device half* sp_radii = static_cast(a.p[8]); + seal_sphere_block_warp( + hot_k + src_base, tok_stride, wht_signs, B, rope_dim, + sp_packed + idx_blk * long(D_CONST / 2), sp_scale + idx_blk, sp_radii + idx_blk * 2L, lane); + } + } else { + threadgroup float* s_min = smem_mm; + threadgroup float* s_max = smem_mm + D_CONST; + for (int d = int(tid); d < D_CONST; d += 256) { + float mn = float(hot_k[src_base + d]); + float mx = mn; + for (int t = 1; t < B; ++t) { + float f = float(hot_k[src_base + long(t) * tok_stride + d]); + mn = fmin(mn, f); + mx = fmax(mx, f); + } + s_min[d] = mn; + s_max[d] = mx; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + device char* idx_k_min = static_cast(a.p[6]); + device char* idx_k_max = static_cast(a.p[7]); + device float* idx_smin = static_cast(a.p[8]); + device float* idx_smax = static_cast(a.p[9]); + seal_quest_int8_head_tg(s_min, s_max, idx_k_min + idx_blk * long(D_CONST), idx_k_max + idx_blk * long(D_CONST), + idx_smin + idx_blk, idx_smax + idx_blk, D_CONST, warp_id, lane); + } +} + +#define INST_SEAL_HOT_SLOT_WHT(D) \ + template [[host_name("bkv_seal_hot_slot_wht_" #D)]] kernel decltype(bkv_seal_hot_slot_wht_t) bkv_seal_hot_slot_wht_t; +INST_SEAL_HOT_SLOT_WHT(64) +INST_SEAL_HOT_SLOT_WHT(128) +INST_SEAL_HOT_SLOT_WHT(192) +INST_SEAL_HOT_SLOT_WHT(256) +INST_SEAL_HOT_SLOT_WHT(320) +INST_SEAL_HOT_SLOT_WHT(512) + +// ---- 7. Materialize Logical Range [row0, row0 + count) -> Contiguous NHD FP16 ---- + +kernel void bkv_materialize_i8( + constant BasinArgs& a [[buffer(0)]], + uint2 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]], + uint2 shape [[threads_per_threadgroup]] +) { + const uint nt = shape.x; + const int H_kv = a.n[0], M = a.n[1], B = a.n[2], D = a.n[3]; + const int row0 = a.n[4], count = a.n[5], flushed_rows = a.n[6], tail_slot = a.n[7]; + const int r = int(group.x); + const int h = int(group.y); + if (r >= count || h >= H_kv) return; + + const int log_row = row0 + r; + const long dst_off = (long(r) * long(H_kv) + long(h)) * long(D); + device half* dst_k = static_cast(a.p[6]); + device half* dst_v = static_cast(a.p[7]); + + if (log_row < flushed_rows) { + const int blk = log_row / B; + const int off = log_row - blk * B; + const long bidx = long(h) * long(M) + long(blk); + const long src_base = (bidx * long(B) + long(off)) * long(D); + device const char* cpu_k = static_cast(a.p[0]); + device const char* cpu_v = static_cast(a.p[1]); + device const float* cpu_sk = static_cast(a.p[2]); + device const float* cpu_sv = static_cast(a.p[3]); + const float ks = cpu_sk[bidx * long(B) + long(off)]; + const float vs = cpu_sv[bidx * long(B) + long(off)]; + for (int d = int(tid); d < D; d += int(nt)) { + dst_k[dst_off + d] = half(float(cpu_k[src_base + d]) * ks); + dst_v[dst_off + d] = half(float(cpu_v[src_base + d]) * vs); + } + } else { + const int off = log_row - flushed_rows; + const long hot_row = long(tail_slot) * long(B) + long(off); + const long src_off = (hot_row * long(H_kv) + long(h)) * long(D); + device const half* hot_k = static_cast(a.p[4]); + device const half* hot_v = static_cast(a.p[5]); + for (int d = int(tid); d < D; d += int(nt)) { + dst_k[dst_off + d] = hot_k[src_off + d]; + dst_v[dst_off + d] = hot_v[src_off + d]; + } + } +} + +template +kernel void bkv_materialize_wht4_t( + constant BasinArgs& a [[buffer(0)]], + uint gx [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]] +) { + const int H_kv = a.n[0], M = a.n[1], B = a.n[2]; + const int row0 = a.n[4], count = a.n[5], flushed_rows = a.n[6], tail_slot = a.n[7]; + const uint warp_id = tid >> 5u; + const uint lane = tid & 31u; + const int item = int(gx) * 8 + int(warp_id); + const int total_items = count * H_kv; + if (item >= total_items) return; + + const int r = item / H_kv; + const int h = item - r * H_kv; + const int log_row = row0 + r; + const long dst_off = long(item) * long(D_CONST); + device half* dst_k = static_cast(a.p[6]); + device half* dst_v = static_cast(a.p[7]); + + if (log_row < flushed_rows) { + constexpr int DH = D_CONST / 2; + const int blk = log_row / B; + const int off = log_row - blk * B; + const long bidx = long(h) * long(M) + long(blk); + const long src_base = (bidx * long(B) + long(off)) * long(DH); + device const uchar* sk = static_cast(a.p[0]) + src_base; + device const uchar* sv = static_cast(a.p[1]) + src_base; + device const float* cpu_sk = static_cast(a.p[2]); + device const float* cpu_sv = static_cast(a.p[3]); + device const float* signs = static_cast(a.p[8]); + dequantize_vec_wht4_to_f16_warp(sk, cpu_sk[bidx * long(B) + long(off)], signs, dst_k + dst_off, lane); + dequantize_vec_wht4_to_f16_warp(sv, cpu_sv[bidx * long(B) + long(off)], signs, dst_v + dst_off, lane); + } else { + const int off = log_row - flushed_rows; + const long hot_row = long(tail_slot) * long(B) + long(off); + const long src_off = (hot_row * long(H_kv) + long(h)) * long(D_CONST); + device const half* hot_k = static_cast(a.p[4]); + device const half* hot_v = static_cast(a.p[5]); + for (int d = int(lane); d < D_CONST; d += 32) { + dst_k[dst_off + d] = hot_k[src_off + d]; + dst_v[dst_off + d] = hot_v[src_off + d]; + } + } +} + +#define INST_MATERIALIZE_WHT4(D) \ + template [[host_name("bkv_materialize_wht4_" #D)]] kernel decltype(bkv_materialize_wht4_t) bkv_materialize_wht4_t; +INST_MATERIALIZE_WHT4(64) +INST_MATERIALIZE_WHT4(128) +INST_MATERIALIZE_WHT4(192) +INST_MATERIALIZE_WHT4(256) +INST_MATERIALIZE_WHT4(320) +INST_MATERIALIZE_WHT4(512) + +// ---- 8. Re-seed Hot Slab from Host KV According to `gpu_to_cpu[H_kv, W]` ---- + +kernel void bkv_reseed_i8( + constant BasinArgs& a [[buffer(0)]], + uint2 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]], + uint2 shape [[threads_per_threadgroup]] +) { + const uint nt = shape.x; + const int H_kv = a.n[0], M = a.n[1], W = a.n[2], B = a.n[3], D = a.n[4], flushed_blks = a.n[5]; + const int slot = int(group.x); + const int h = int(group.y); + if (slot >= W || h >= H_kv) return; + + const int blk = static_cast(a.p[4])[long(h) * long(W) + long(slot)]; + if (blk < 0 || blk >= flushed_blks) return; + + const long blk_elems = long(B) * long(D); + const long bidx = long(h) * long(M) + long(blk); + device const char* sk_src = static_cast(a.p[0]) + bidx * blk_elems; + device const char* sv_src = static_cast(a.p[1]) + bidx * blk_elems; + device const float* ks_ptr = static_cast(a.p[2]) + bidx * long(B); + device const float* vs_ptr = static_cast(a.p[3]) + bidx * long(B); + + const long tok_stride = long(H_kv) * long(D); + const long dst_base = long(slot) * long(B) * tok_stride + long(h) * long(D); + device half* dk = static_cast(a.p[5]) + dst_base; + device half* dv = static_cast(a.p[6]) + dst_base; + for (long idx = long(tid); idx < blk_elems; idx += long(nt)) { + long tok = idx / long(D), d = idx - tok * long(D); + long off = tok * tok_stride + d; + dk[off] = half(float(sk_src[idx]) * ks_ptr[tok]); + dv[off] = half(float(sv_src[idx]) * vs_ptr[tok]); + } +} + +template +kernel void bkv_reseed_wht4_t( + constant BasinArgs& a [[buffer(0)]], + uint2 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]] +) { + const int H_kv = a.n[0], M = a.n[1], W = a.n[2], B = a.n[3], flushed_blks = a.n[5]; + const int slot = int(group.x); + const int h = int(group.y); + if (slot >= W || h >= H_kv) return; + + const int blk = static_cast(a.p[4])[long(h) * long(W) + long(slot)]; + if (blk < 0 || blk >= flushed_blks) return; + + constexpr int DH = D_CONST / 2; + const long bidx = long(h) * long(M) + long(blk); + device const uchar* sk_src = static_cast(a.p[0]) + bidx * (long(B) * long(DH)); + device const uchar* sv_src = static_cast(a.p[1]) + bidx * (long(B) * long(DH)); + device const float* ks_ptr = static_cast(a.p[2]) + bidx * long(B); + device const float* vs_ptr = static_cast(a.p[3]) + bidx * long(B); + device const float* signs = static_cast(a.p[7]); + + const long tok_stride = long(H_kv) * long(D_CONST); + const long dst_base = long(slot) * long(B) * tok_stride + long(h) * long(D_CONST); + device half* dk = static_cast(a.p[5]) + dst_base; + device half* dv = static_cast(a.p[6]) + dst_base; + + const uint warp_id = tid >> 5u; + const uint lane = tid & 31u; + for (int tok = int(warp_id); tok < B; tok += 8) { + dequantize_vec_wht4_to_f16_warp(sk_src + long(tok) * long(DH), ks_ptr[tok], + signs, dk + long(tok) * tok_stride, lane); + dequantize_vec_wht4_to_f16_warp(sv_src + long(tok) * long(DH), vs_ptr[tok], + signs, dv + long(tok) * tok_stride, lane); + } +} + +#define INST_RESEED_WHT4(D) \ + template [[host_name("bkv_reseed_wht4_" #D)]] kernel decltype(bkv_reseed_wht4_t) bkv_reseed_wht4_t; +INST_RESEED_WHT4(64) +INST_RESEED_WHT4(128) +INST_RESEED_WHT4(192) +INST_RESEED_WHT4(256) +INST_RESEED_WHT4(320) +INST_RESEED_WHT4(512) diff --git a/engine/metal/src/poly/flash.metal b/engine/metal/src/poly/flash.metal index e05d41e460..fe03217f82 100644 --- a/engine/metal/src/poly/flash.metal +++ b/engine/metal/src/poly/flash.metal @@ -7,7 +7,7 @@ using namespace metal; using namespace mpp::tensor_ops; struct Args { // attention.metal's - device void* p[10]; long pos; + device void* p[11]; long pos; int dim,heads,kv,rows,window,ring,whole,stride,rot,sections,kind; float scale,eps; }; @@ -191,28 +191,47 @@ kernel void poly_flash_g(constant Args& a [[buffer(0)]],uint2 tg [[threadgroup_p if(tot0.is_valid_element(i)) { const auto ix=tot0.get_multidimensional_index(i); const int rr=ix[1]; - if(rr0.0f?tot0[i]/ls:0.0f; + } } if(D>=128) for(uint16_t i=0;i0.0f?tot1[i]/ls:0.0f; + } } if(D>=256) { for(uint16_t i=0;i0.0f?tot2[i]/ls:0.0f; + } } for(uint16_t i=0;i0.0f?tot3[i]/ls:0.0f; + } } } + if(a.p[10] && int(lane)(a.p[10])+2*(ulong(t0+rr)*a.heads+ulong(h_sg)); + ml[0]=ls>0.0f?mrun[sg_off+rr]:-INFINITY; + ml[1]=ls; + } } #define PFLASH(D,G,Q8) template [[host_name("poly_flash_g_" #D "_" #G "_" #Q8)]] kernel decltype(poly_flash_g) poly_flash_g; diff --git a/engine/metal/src/poly/inkling.cpp b/engine/metal/src/poly/inkling.cpp index 244a2856c7..a8da14ba0b 100644 --- a/engine/metal/src/poly/inkling.cpp +++ b/engine/metal/src/poly/inkling.cpp @@ -1033,19 +1033,26 @@ void ink_attend(const InkAttn& c, void* stream) { if (c.rows <= 0) return; if (c.n_kv < 1 || c.n_head % c.n_kv != 0 || (c.dim != 64 && c.dim != 128) || c.n_rel < 1 || c.n_rel > 32) throw std::invalid_argument("ink_attend: heads of 64 or 128 values, up to 32 relative values"); - if (c.at && c.room < 1) throw std::invalid_argument("ink_attend: positions on the card need the rows to size for"); + if (c.hot_cap == 0 && c.at && c.room < 1) + throw std::invalid_argument("ink_attend: positions on the card need the rows to size for"); const int fmt = c.kvq4 ? 3 : c.kvq8 ? 2 : c.kv8 ? 1 : 0; + if (c.hot_cap > 0) { + if (fmt != 0) throw std::invalid_argument("ink_attend: BasinKV hot slab requires FP16"); + if ((c.hot_cap & 15) != 0) throw std::invalid_argument("ink_attend: BasinKV hot_cap must be a multiple of 16"); + } Args a; const void* p[9] = {c.q, c.r, c.sink, c.keys, c.vals, c.rel_bias, c.gate, c.out, c.at}; std::copy(p, p + 9, a.p); if (c.q8 && c.rows > kConvFew) throw std::invalid_argument("ink_attend: quantized output supports up to 8 rows"); a.p[10] = c.q8; + a.p[11] = c.hot_eff_pos; + a.p[12] = c.hot_slot_blk; a.n[0] = c.rows, a.n[1] = c.n_head, a.n[2] = c.n_kv, a.n[3] = c.dim, a.n[4] = c.n_rel, a.n[5] = c.extent; - a.n[6] = c.window, a.n[7] = c.ring, a.n[10] = fmt; + a.n[6] = c.window, a.n[7] = c.ring, a.n[10] = fmt, a.n[11] = c.hot_cap; a.f[0] = c.scale; a.pos = c.pos; - int64_t keys = c.at ? std::max(c.room / 2, c.rows) : c.pos + c.rows; - if (c.window > 0) keys = std::min(keys, c.window); + int64_t keys = c.hot_cap > 0 ? (int64_t) c.hot_cap : (c.at ? std::max(c.room / 2, c.rows) : c.pos + c.rows); + if (c.hot_cap == 0 && c.window > 0) keys = std::min(keys, c.window); static void* scratch = nullptr; static bool tried = false; constexpr size_t kRunFloats = size_t(4) << 20; @@ -1083,7 +1090,7 @@ void ink_attend(const InkAttn& c, void* stream) { : ("ink_attn_128_fused_g_" + std::to_string(g_fused) + fsuf); const std::string k_sgr = "ink_attn_128_sg_rows" + gsuf; const std::string k_sg8 = "ink_attn_128_sg8" + gsuf; - const std::string k_attn = (c.dim == 128 ? "ink_attn_128" : "ink_attn_64") + gsuf; + const std::string k_attn = (c.dim == 128 ? "ink_attn_128" : "ink_attn_64") + gsuf + (c.hot_cap > 0 ? "_hot" : ""); const int most = (int) std::min(16, size_t(32768) / ((size_t) nh_tile * (c.dim + 2) * 4)); const int groups = std::max(nh_tile, std::min(most, (int) ((keys + splits * 16 - 1) / (splits * 16)))); const int most_f = (int) std::min(16, size_t(32768) / ((size_t) nh_fused * (c.dim + 2) * 4)); @@ -1104,12 +1111,15 @@ void ink_attend(const InkAttn& c, void* stream) { const size_t r_b = 4ULL * size_t(c.rows) * size_t(c.n_head) * size_t(c.n_rel); const size_t at_b = c.at ? 16ULL * size_t(c.rows) : 0ULL; const size_t q8_b = c.q8 ? kernels::native_q8_1_bytes(c.n_head * c.dim, c.rows) : 0ULL; - const gpu::metal::Access mfused[11] = { + const size_t eff_b = c.hot_eff_pos ? sizeof(long long) : 0ULL; + const size_t blk_b = c.hot_slot_blk ? 4ULL * size_t(c.n_kv) * size_t(c.hot_cap >> 4) : 0ULL; + const gpu::metal::Access mfused[13] = { gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::W, - gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::W}; - const size_t sfused[11] = {q_b, r_b, 0ULL, 0ULL, 0ULL, 0ULL, 0ULL, q_b, at_b, 0ULL, q8_b}; - if (c.rows <= 8 && c.dim == 128 && splits > 1 && splits * groups_f <= 32 && fused_shared <= 32768 && + gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::W, gpu::metal::Access::R, + gpu::metal::Access::R}; + const size_t sfused[13] = {q_b, r_b, 0ULL, 0ULL, 0ULL, 0ULL, 0ULL, q_b, at_b, 0ULL, q8_b, eff_b, blk_b}; + if (c.hot_cap == 0 && c.rows <= 8 && c.dim == 128 && splits > 1 && splits * groups_f <= 32 && fused_shared <= 32768 && fused_th <= pipe_max_threads(k_fused.c_str())) { a.n[9] = groups_f; a.p[9] = nullptr; @@ -1118,12 +1128,13 @@ void ink_attend(const InkAttn& c, void* stream) { {a.p, 11, true, nullptr, mfused, sfused}); return; } - const void* r_p1[10] = {c.q, c.r, c.sink, c.keys, c.vals, c.rel_bias, c.gate, nullptr, c.at, nullptr}; - gpu::metal::Access m_p1[10] = { + const void* r_p1[12] = {c.q, c.r, c.sink, c.keys, c.vals, c.rel_bias, c.gate, nullptr, c.at, nullptr, + c.hot_eff_pos, c.hot_slot_blk}; + gpu::metal::Access m_p1[12] = { gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::R, - gpu::metal::Access::R, gpu::metal::Access::W}; - size_t s_p1[10] = {q_b, r_b, 0ULL, 0ULL, 0ULL, 0ULL, 0ULL, 0ULL, at_b, 0ULL}; + gpu::metal::Access::R, gpu::metal::Access::W, gpu::metal::Access::R, gpu::metal::Access::R}; + size_t s_p1[12] = {q_b, r_b, 0ULL, 0ULL, 0ULL, 0ULL, 0ULL, 0ULL, at_b, 0ULL, eff_b, blk_b}; const void* r_p2[3] = {nullptr, c.out, c.q8}; const gpu::metal::Access m_p2[3] = {gpu::metal::Access::R, gpu::metal::Access::W, gpu::metal::Access::W}; size_t s_p2[3] = {0ULL, q_b, q8_b}; @@ -1131,7 +1142,7 @@ void ink_attend(const InkAttn& c, void* stream) { const char* sgr_kernel = sgr_1h ? "ink_attn_128_sg_rows_1h_0" : k_sgr.c_str(); const uint32_t sgr_th = uint32_t(32 * (sgr_1h ? per : 1) * c.rows), sgr_jth = uint32_t(32 * splits); const int sgr_groups = sgr_1h ? groups_f : groups; - if (c.rows >= 2 && c.rows <= 8 && keys > 2048 && c.dim == 128 && splits > 1 && splits <= 32 && + if (c.hot_cap == 0 && c.rows >= 2 && c.rows <= 8 && keys > 2048 && c.dim == 128 && splits > 1 && splits <= 32 && sgr_th <= pipe_max_threads(sgr_kernel) && sgr_jth <= pipe_max_threads("ink_attn_join_sg_rows")) { static void* sgr_scratch = nullptr; @@ -1165,7 +1176,7 @@ void ink_attend(const InkAttn& c, void* stream) { const uint32_t sg8_th = uint32_t(32 * (sg8_1h ? per : 1) * 8); const int sg8_groups = (keys >= splits * 256) ? 16 : 8; const size_t sg_shared = ((size_t) (sg8_1h ? per : nh_tile) * 8 * 132 * 4 + 15) / 16 * 16; - if (c.rows <= 8 && c.dim == 128 && splits > 1 && splits <= 32 && sg_shared <= 32768 && + if (c.hot_cap == 0 && c.rows <= 8 && c.dim == 128 && splits > 1 && splits <= 32 && sg_shared <= 32768 && sg8_th <= pipe_max_threads(sg8_kernel)) { static void* sg_scratch = nullptr; static bool sg_tried = false; @@ -1199,12 +1210,12 @@ void ink_attend(const InkAttn& c, void* stream) { r_p1[9] = scratch; s_p1[9] = scr_b; r_p2[0] = scratch; s_p2[0] = scr_b; run(k_attn.c_str(), a, stream, {uint32_t(c.n_kv * n_gqa), uint32_t(c.rows), uint32_t(splits)}, - uint32_t(32 * groups), shared, {r_p1, 10, true, nullptr, m_p1, s_p1}); + uint32_t(32 * groups), shared, {r_p1, c.hot_cap > 0 ? size_t(12) : size_t(10), true, nullptr, m_p1, s_p1}); run("ink_attn_join", a, stream, {uint32_t(c.n_head), uint32_t(c.rows), 1}, 32, 0, {r_p2, 3, true, nullptr, m_p2, s_p2}); } else { run(k_attn.c_str(), a, stream, {uint32_t(c.n_kv * n_gqa), uint32_t(c.rows), uint32_t(splits)}, - uint32_t(32 * groups), shared, {a.p, 11, true, nullptr, mfused, sfused}); + uint32_t(32 * groups), shared, {a.p, c.hot_cap > 0 ? size_t(13) : size_t(11), true, nullptr, mfused, sfused}); } } @@ -1217,7 +1228,7 @@ bool ink_attend_batch(const InkAttn& c, void* stream) { gpu::metal::pipeline("poly_inkling_flash", flash_source().c_str(), "ink_flash_128_direct_ring", error) != nullptr && gpu::metal::pipeline("poly_inkling_flash", flash_source().c_str(), "ink_flash_128_g_3_0", error) != nullptr; }(); - if (!(ready && gpu::metal::optimize() && c.dim == 128 && c.n_rel == 16 && !c.at && !c.q8 && c.n_kv > 0 && + if (!(ready && gpu::metal::optimize() && c.dim == 128 && c.n_rel == 16 && !c.at && !c.q8 && !c.hot_cap && c.n_kv > 0 && c.n_head % c.n_kv == 0)) { ink_attend(c, stream); return true; diff --git a/engine/metal/src/poly/inkling.metal b/engine/metal/src/poly/inkling.metal index 3535ebed9d..dee99da9c2 100644 --- a/engine/metal/src/poly/inkling.metal +++ b/engine/metal/src/poly/inkling.metal @@ -1053,7 +1053,8 @@ kernel void ink_qkv(constant Args& a [[buffer(0)]], uint grp [[threadgroup_posit if (is_v) rms_head(head, dim, a.f[4], part, tid, nt); else clip_head(head, nullptr, a.f[0], dim, 0.0f, 1.0f, p, part, tid, nt); threadgroup_barrier(mem_flags::mem_device); - store_kv_head(head, P(a, is_v ? 15 : 14), ring > 0 ? p % ring : p, n_kv, dim, h, part, tid, nt); + device uchar* cache = P(a, is_v ? 15 : 14); + if (cache) store_kv_head(head, cache, ring > 0 ? p % ring : p, n_kv, dim, h, part, tid, nt); return; } b -= 2 * n_kv; @@ -1106,9 +1107,11 @@ kernel void ink_qkv_win(constant Args& a [[buffer(0)]], uint grp [[threadgroup_p v = y * f; out[ulong(t) * channels + c] = v; } - long cell = (at ? at[0] : a.pos) + t; - if (ring > 0) cell %= ring; - store_kv_reg(v, cache, cell, n_kv, dim, h, part, tid, nt); + if (cache) { + long cell = (at ? at[0] : a.pos) + t; + if (ring > 0) cell %= ring; + store_kv_reg(v, cache, cell, n_kv, dim, h, part, tid, nt); + } } if (int(tid) < dim) conv_states(x, state, snap, a.stride, uint(a.n[7]), channels, taps, rows, c); return; @@ -1247,7 +1250,7 @@ inline void ink_kv_load(device const uchar* cache, long cell, int nkv, int dim, } } -template // a lane's values of a head: dim / 8; G = max query heads per GQA tile (1..4) +template // a lane's values of a head: dim / 8; G = max query heads per GQA tile (1..4) kernel void ink_attn(constant Args& a [[buffer(0)]], threadgroup float* sh [[threadgroup(0)]], uint3 grp [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]], uint groups [[simdgroups_per_threadgroup]]) { @@ -1257,7 +1260,8 @@ kernel void ink_attn(constant Args& a [[buffer(0)]], threadgroup float* sh [[thr const int g = int(grp.x) / n_gqa, gt = int(grp.x) % n_gqa, hp0 = gt * G, nh_tile = min(G, per - hp0); const int t = grp.y, z = grp.z; const long p = ink_pos(a, t); - long lo = window > 0 ? max(0L, p - window + 1) : 0, hi = p; + long lo = HOT ? 0L : (window > 0 ? max(0L, p - window + 1) : 0); + long hi = HOT ? (a.p[11] ? *P(a, 11) : a.pos) : p; if (splits > 1) { const long span = (hi - lo + splits) / splits, first = lo + long(z) * span; hi = min(hi, first + span - 1); @@ -1292,10 +1296,18 @@ kernel void ink_attn(constant Args& a [[buffer(0)]], threadgroup float* sh [[thr const long cell = ring > 0 ? (valid ? j : hi) % ring : (valid ? j : hi); ink_kv_load(keys, cell, nkv, dim, g, l8, k); ink_kv_load(vals, cell, nkv, dim, g, l8, v); - const long dist = p - j; + long dist; + if (HOT && a.p[12]) { + const int hot_W = a.n[11] >> 4; + const int slot_idx = int(j >> 4); + const int blk = (valid && slot_idx < hot_W) ? P(a, 12)[g * hot_W + slot_idx] : -1; + dist = blk >= 0 ? (p - (long(blk) * 16 + (j & 15))) : long(extent); + } else { + dist = p - j; + } for (int c = 0; c < 4; ++c) { const int i = l8 * 4 + c; - rb[c] = valid && i < nrel && dist < extent ? rel[ulong(dist) * nrel + i] : 0.0f; + rb[c] = valid && i < nrel && (!HOT || dist >= 0) && dist < extent ? rel[ulong(dist) * nrel + i] : 0.0f; } for (int hp = 0; hp < nh_tile; ++hp) { float d = 0; @@ -1383,10 +1395,14 @@ kernel void ink_attn(constant Args& a [[buffer(0)]], threadgroup float* sh [[thr } } #define INK_ATTN_GF(G, FMT) \ - template [[host_name("ink_attn_128_g_" #G "_" #FMT)]] kernel decltype(ink_attn<16, G, FMT>) ink_attn<16, G, FMT>; \ - template [[host_name("ink_attn_64_g_" #G "_" #FMT)]] kernel decltype(ink_attn<8, G, FMT>) ink_attn<8, G, FMT>; + template [[host_name("ink_attn_128_g_" #G "_" #FMT)]] kernel decltype(ink_attn<16, G, FMT, false>) ink_attn<16, G, FMT, false>; \ + template [[host_name("ink_attn_64_g_" #G "_" #FMT)]] kernel decltype(ink_attn<8, G, FMT, false>) ink_attn<8, G, FMT, false>; #define INK_ATTN_G(G) INK_ATTN_GF(G, 0) INK_ATTN_GF(G, 1) INK_ATTN_GF(G, 2) INK_ATTN_GF(G, 3) INK_ATTN_G(1) INK_ATTN_G(2) INK_ATTN_G(3) INK_ATTN_G(4) +#define INK_ATTN_HOT(G) \ + template [[host_name("ink_attn_128_g_" #G "_0_hot")]] kernel decltype(ink_attn<16, G, 0, true>) ink_attn<16, G, 0, true>; \ + template [[host_name("ink_attn_64_g_" #G "_0_hot")]] kernel decltype(ink_attn<8, G, 0, true>) ink_attn<8, G, 0, true>; +INK_ATTN_HOT(1) INK_ATTN_HOT(2) INK_ATTN_HOT(3) INK_ATTN_HOT(4) // Single- and multi-token (up to 8 rows) fused attention + split join for dim=128 with GQA head grouping: // one threadgroup per (kv_head * gqa_tile, row) (grid n_kv * n_gqa x rows). diff --git a/engine/metal/src/poly/unported.cpp b/engine/metal/src/poly/unported.cpp index a42f574cc1..211b8ad7dd 100644 --- a/engine/metal/src/poly/unported.cpp +++ b/engine/metal/src/poly/unported.cpp @@ -3,7 +3,6 @@ // attend_batch() by its own contract), Gemma 4's opt-in int8 attention caches, Qwen35's opt-in q4_0 cache and cache // streaming, Clover's block guesses and coreset routing, and the half-sum guard of Flint's MMQ. A call that would // need a kernel says what is missing instead of computing something else. -#include "basinkv.hpp" #include "fattn.hpp" #include "mmq.hpp" #include "strata/kernels/native_mmvq.hpp" @@ -73,81 +72,6 @@ void scale_rows(float*, int64_t, int, int, const int32_t*, const float*, bool, v unported("half-sum guard (Flint)"); } -// BasinKV sparse KV offload is CUDA/HIP-only (discrete GPU PCIe offloading); Metal uses unified memory. -struct BasinKvPool::Impl { - BasinKvConfig cfg; -}; -bool basinkv_gpu_available() noexcept { return false; } -BasinKvPool::BasinKvPool() : impl_(std::make_unique()) {} -BasinKvPool::~BasinKvPool() = default; -void BasinKvPool::init(const BasinKvConfig&) { unported("BasinKV sparse KV offload (--basinkv)"); } -void BasinKvPool::destroy() {} -bool BasinKvPool::is_initialized() const noexcept { return false; } -bool BasinKvPool::is_using_uva() const noexcept { return false; } -const BasinKvConfig& BasinKvPool::config() const noexcept { return impl_->cfg; } -BasinKvFootprint BasinKvPool::footprint() const noexcept { return {}; } -void BasinKvPool::reset_all(void*) {} -void BasinKvPool::reset_layer(int32_t, void*) {} -void BasinKvPool::truncate_all(int32_t, void*) {} -void BasinKvPool::truncate_layer(int32_t, int32_t, void*) {} -uint16_t* BasinKvPool::hot_k(int32_t) const noexcept { return nullptr; } -uint16_t* BasinKvPool::hot_v(int32_t) const noexcept { return nullptr; } -const long long* BasinKvPool::d_eff_pos(int32_t) const noexcept { return nullptr; } -const int32_t* BasinKvPool::d_gpu_to_cpu(int32_t) const noexcept { return nullptr; } -int64_t BasinKvPool::effective_pos(int64_t pos) const noexcept { return pos; } -int32_t BasinKvPool::seq_len(int32_t) const noexcept { return 0; } -int32_t BasinKvPool::resident_tokens() const noexcept { return 0; } -void BasinKvPool::wait_layer_ready(int32_t, void*) {} -void BasinKvPool::join_all_pending(void*) {} -void BasinKvPool::join_bg_in_capture(void*) {} -void BasinKvPool::mark_device_state_dirty() noexcept {} -void BasinKvPool::sync_host_state(void*) {} -void BasinKvPool::sync_background() {} -void BasinKvPool::append_prefill_chunk_f32(int32_t, const float*, const float*, int32_t, int32_t, void*) { - unported("BasinKV sparse KV offload (--basinkv)"); -} -void BasinKvPool::materialize_range_f16(int32_t, int32_t, int32_t, uint16_t*, uint16_t*, void*) { - unported("BasinKV sparse KV offload (--basinkv)"); -} -void BasinKvPool::append_decode_token_f32(int32_t, const float*, const float*, int32_t, void*) { - unported("BasinKV sparse KV offload (--basinkv)"); -} -void BasinKvPool::submit_lookahead_f32(int32_t, const float*, void*, int32_t) { - unported("BasinKV sparse KV offload (--basinkv)"); -} -void BasinKvPool::append_decode_token_graph_f32(int32_t, const float*, const float*, const long long*, void*) { - unported("BasinKV sparse KV offload (--basinkv)"); -} -void BasinKvPool::submit_lookahead_graph_f32(int32_t, const float*, void*, int32_t) { - unported("BasinKV sparse KV offload (--basinkv)"); -} -void BasinKvPool::export_rows_f16(int32_t, int32_t, int32_t, uint16_t*, uint16_t*, void*) { - unported("BasinKV sparse KV offload (--basinkv)"); -} -void BasinKvPool::import_rows_f16(int32_t, const uint16_t*, const uint16_t*, int32_t, int32_t, void*) { - unported("BasinKV sparse KV offload (--basinkv)"); -} -void BasinKvPool::score_layer_f32(int32_t, const float*, float*, void*) { - unported("BasinKV sparse KV offload (--basinkv)"); -} -void BasinKvPool::run_select_from_scores(int32_t, const float*, int32_t, int32_t, int64_t, int32_t, void*) { - unported("BasinKV sparse KV offload (--basinkv)"); -} -void BasinKvPool::read_page_tables(int32_t, std::vector&, std::vector&, void*) { - unported("BasinKV sparse KV offload (--basinkv)"); -} -void BasinKvPool::read_quest_index(int32_t, std::vector&, std::vector&, std::vector&, - std::vector&, void*) { - unported("BasinKV sparse KV offload (--basinkv)"); -} -void BasinKvPool::read_sphere_index(int32_t, std::vector&, std::vector&, std::vector&, - void*) { - unported("BasinKV sparse KV offload (--basinkv)"); -} -uint64_t BasinKvPool::read_admitted_count(int32_t, void*) { - unported("BasinKV sparse KV offload (--basinkv)"); -} - } // namespace strata::poly namespace strata::kernels { diff --git a/engine/src/poly/basinkv.cpp b/engine/src/poly/basinkv.cpp index e57b630087..91e568a53b 100644 --- a/engine/src/poly/basinkv.cpp +++ b/engine/src/poly/basinkv.cpp @@ -1,5 +1,5 @@ // src/poly/basinkv.cpp - host-side configuration, partitioning, footprint estimation, -// WHT sign generation, and Metal/CPU stub lifecycle for BasinKV. +// WHT sign generation, and CPU-only stub lifecycle for BasinKV. #include "basinkv.hpp" #include @@ -150,7 +150,7 @@ BasinKvFootprint basinkv_estimate_footprint(const BasinKvConfig& cfg) noexcept { } #if defined(STRATA_BASINKV_HOST_ONLY) -// Host-only stub for CPU-only unit tests (Metal uses engine/metal/src/poly/unported.cpp; +// Host-only stub for CPU-only unit tests (Metal links engine/metal/src/poly/basinkv.cpp; // CUDA and HIP link engine/src/poly/basinkv.cu). struct BasinKvPool::Impl { BasinKvConfig cfg; @@ -162,7 +162,7 @@ BasinKvPool::BasinKvPool() : impl_(std::make_unique()) {} BasinKvPool::~BasinKvPool() = default; void BasinKvPool::init(const BasinKvConfig&) { - throw std::runtime_error("BasinKV requires a CUDA or HIP build (not supported on Metal unified memory)"); + throw std::runtime_error("BasinKV requires a CUDA, HIP, or Metal build"); } void BasinKvPool::destroy() {} bool BasinKvPool::is_initialized() const noexcept { return false; } diff --git a/engine/src/poly/basinkv.hpp b/engine/src/poly/basinkv.hpp index 5d2622f416..6975e26b21 100644 --- a/engine/src/poly/basinkv.hpp +++ b/engine/src/poly/basinkv.hpp @@ -130,7 +130,7 @@ BasinHostQuant basinkv_parse_host_quant(const std::string& name); const char* basinkv_index_mode_name(BasinIndexMode mode) noexcept; const char* basinkv_host_quant_name(BasinHostQuant mode) noexcept; -/// True when this build includes the GPU implementation (CUDA or HIP; false on Metal). +/// True when this build includes the GPU implementation (CUDA, HIP, or Metal). bool basinkv_gpu_available() noexcept; /// Multi-layer BasinKV GPU Hot-Slab + Compressed Block Index + Pinned Host KV Pool. diff --git a/engine/src/poly/engine.cpp b/engine/src/poly/engine.cpp index 0da6fe0bfd..3deb53d9fa 100644 --- a/engine/src/poly/engine.cpp +++ b/engine/src/poly/engine.cpp @@ -2569,7 +2569,7 @@ std::unique_ptr Engine::open(const Options& o) { throw std::runtime_error("--basinkv is supported for qwen35moe / clover_moe / qwen4exp / inkling2 models in v1; this is a '" + name + "' model"); if (!basinkv_gpu_available()) - throw std::runtime_error("--basinkv is not supported on this backend (requires CUDA or HIP)"); + throw std::runtime_error("--basinkv is not supported on this backend (requires CUDA, HIP, or Metal)"); if (o.kv_resident > 0) throw std::runtime_error("--basinkv cannot be combined with --kv-resident"); if (o.kv_format != KvFmt::kFp16 && o.kv_format != KvFmt::kAuto) @@ -4164,8 +4164,8 @@ void Engine::load(const Options& o) { const MetaValue* heads = gg_->get("qwen35moe.attention.head_count_kv"); const MetaValue* key = gg_->get("qwen35moe.attention.key_length"); const MetaValue* value = gg_->get("qwen35moe.attention.value_length"); - // The Q8 attention kernels store a scale for each 32 values within each head. - opt_.kv_format = arch && arch->s == "qwen35moe" && heads && heads->u > 0 && + // The Q8 attention kernels store a scale for each 32 values within each head; BasinKV owns an FP16 hot slab. + opt_.kv_format = !opt_.basinkv && arch && arch->s == "qwen35moe" && heads && heads->u > 0 && key && key->u > 0 && key->u % 32 == 0 && value && value->u == key->u ? KvFmt::kQ8_0 : KvFmt::kFp16; } diff --git a/engine/src/poly/main.cpp b/engine/src/poly/main.cpp index ffd84f260c..9dd87ca477 100644 --- a/engine/src/poly/main.cpp +++ b/engine/src/poly/main.cpp @@ -2199,7 +2199,7 @@ void usage() { " --kv-resident N attention-cache cells kept resident in VRAM, streaming the rest from host\n" " RAM (default: 0 = all of them in VRAM; with --kv-whole, fully resident)\n" " --basinkv opt-in BasinKV sparse KV offload + lookahead prefetch (qwen35moe / clover_moe / qwen4exp /\n" - " inkling2, CUDA/HIP; alias: --kv-sparse). Keeps a fixed FP16 hot slab in VRAM and\n" + " inkling2, CUDA/HIP/Metal; alias: --kv-sparse). Keeps a fixed FP16 hot slab in VRAM and\n" " offloads full history to pinned RAM with GPU block summary index\n" " --basinkv-resident N BasinKV hot-slab tokens per layer, multiple of 256 >= 256 (default 2048)\n" " --basinkv-cap N BasinKV max cold blocks admitted per KV head per step, 1..64 (default 8)\n" diff --git a/engine/src/poly/qwen35.cpp b/engine/src/poly/qwen35.cpp index 2dffc2fc2a..4f05e92344 100644 --- a/engine/src/poly/qwen35.cpp +++ b/engine/src/poly/qwen35.cpp @@ -446,11 +446,11 @@ void Qwen35::assign_scratch() { work_halves_ = kQ8WorkRows * (size_t) n_kv_ * head_dim_; q8w_ = fbuf((2 * work_halves_ + 1) / 2); } - if (kv_ring() > 0 || basinkv_on()) { - // a streamed or BasinKV exact-prefill layer's attention pieces: output and (max, sum) pairs - part_out_ = fbuf(heads); - part_ml_ = fbuf(4 * n * n_head_); - } + } + if (kv_ring() > 0 || basinkv_on()) { + // a streamed or BasinKV exact-prefill layer's attention pieces: output and (max, sum) pairs + part_out_ = fbuf(heads); + part_ml_ = fbuf(4 * n * n_head_); } if (gdn_mma_.initialize([&] { #ifdef STRATA_POLY_GDN_MMA diff --git a/engine/src/poly/qwen4.cpp b/engine/src/poly/qwen4.cpp index 73fb102865..eea5179ae7 100644 --- a/engine/src/poly/qwen4.cpp +++ b/engine/src/poly/qwen4.cpp @@ -778,8 +778,13 @@ void Qwen4::alloc_caches() { basin_stage_v_ = (uint16_t*) dmalloc((size_t) basin_stage_rows_ * row, "BasinKV prefill stage V"); } - // Ensure score_ holds both dense attention scores and QSA split-K partial buffers (<= 16 rows). + // Ensure score_ holds dense attention scores (non-Metal) and QSA split-K partial buffers (<= 16 rows). +#if defined(STRATA_GPU_METAL) + // Metal dense attention uses online softmax (attend_split_floats() == 0) and never reads score_; drop it under BasinKV. + const size_t dense_sf = basinkv_on() ? 0 : (size_t) chunk_ * (size_t) n_head_ * (size_t) opt_.max_context; +#else const size_t dense_sf = (size_t) chunk_ * (size_t) n_head_ * (size_t) opt_.max_context; +#endif const size_t qsa_chunks = (qsa_sel_cap_ > 0 && !basinkv_on()) ? (size_t) ((qsa_sel_cap_ + 63) / 64) : 0; const size_t qsa_part_sf = qsa_chunks > 0 ? size_t(16) * (size_t) n_head_ * qsa_chunks * (size_t) (head_dim_ + 2) : 0; const size_t qsa_score_min = (qsa_sel_cap_ > 0 && !basinkv_on()) ? (size_t) std::max(8, opt_.window) * (size_t) ((opt_.max_context + 3) / 4) : 0; @@ -1013,7 +1018,7 @@ void Qwen4::assign_scratch() { } #if defined(STRATA_GPU_METAL) || defined(STRATA_USE_HIP) - score_ = fbuf(score_floats_); + score_ = score_floats_ > 0 ? fbuf(score_floats_) : nullptr; #endif if (buf_rows_ >= kStageRows && codes_read()) { work_halves_ = kQ8WorkRows * (size_t) n_kv_ * (size_t) head_dim_;