From 9d642b9eb963bae4f62faa6519939e3c3839f41d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 2 Nov 2026 00:30:56 +0100 Subject: [PATCH 01/11] split: the expert prompt kernel on Ampere's m16n8k16 tensor-core instruction for sm_80 and later (the Volta m8n8k4 version stays for older cards); first version, to be gated for exactness and speed --- src/split/src/moe_mma.cuh | 59 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/src/split/src/moe_mma.cuh b/src/split/src/moe_mma.cuh index 9695e4554a..9702253374 100644 --- a/src/split/src/moe_mma.cuh +++ b/src/split/src/moe_mma.cuh @@ -253,6 +253,17 @@ __device__ __forceinline__ void mma_884(float (&d)[8], unsigned a0, unsigned a1, : "r"(a0), "r"(a1), "r"(b0), "r"(b1)); } +#if FNX_ARCH >= 80 +// d (16 x 8) += a (16 x 16, row-major) b (16 x 8, col-major): Ampere's HMMA.16816, f16 products with f32 accumulation. Lane (g = lane / 4, +// t = lane % 4) holds a0 = (row g, k 2t..2t+1), a1 = (row g + 8, k 2t..), a2 = (row g, k 2t + 8..), a3 = (row g + 8, k 2t + 8..); +// b0 = (k 2t..2t+1, column g), b1 = (k 2t + 8.., column g); d0 d1 = (row g, columns 2t, 2t + 1), d2 d3 = (row g + 8, same columns) +__device__ __forceinline__ void mma_16816(float (&d)[4], uint32_t a0, uint32_t a1, uint32_t a2, uint32_t a3, uint32_t b0, uint32_t b1) { + asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\n" + : "+f"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3]) + : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1)); +} +#endif + // the output staging's row stride in floats (8 past the tile: fewer conflicts than none or 16) template constexpr int MM_SLD = BM + 8; @@ -282,6 +293,20 @@ __global__ void __launch_bounds__(MM_THREADS) k_moe_mma(MoeW w, const BigJob* __ const int rg = warp % WR, tg = warp / WR; const bool split = WT > 1 && nt <= TT; const int tb = split ? 0 : tg * TT; // the warp's first token tile +#if FNX_ARCH >= 80 + // the warp's 32 rows x 16 TT tokens on HMMA.16816 (mma_16816): 2 row tiles of 16 x 2 TT token tiles of 8; lane (g, t4) loads the + // 32-bit operand pairs of the fragment layout above from the weight tile (rows) and the activation tile (tokens) in shared memory + const int lane = threadIdx.x & 31, g = lane >> 2, t4 = lane & 3; + const __half* arow = sw + (rg * 32 + g) * MM_LD + 2 * t4; + const __half* bcol = sx + (tb * 16 + g) * MM_LD + 2 * t4; + float acc[2][2 * TT][4]; +#pragma unroll + for (int a = 0; a < 2; ++a) +#pragma unroll + for (int b = 0; b < 2 * TT; ++b) +#pragma unroll + for (int j = 0; j < 4; ++j) acc[a][b][j] = 0.f; +#else // the warp's 32 rows x 16 TT tokens on HMMA.884 (mma_884): quad-pair q (lanes 4q..4q+3, 4q+16..4q+19) takes rows // 16 (q >> 1) and tokens 8 TT (q & 1) of them, as 2 x TT tiles of 8 x 8; this lane loads row / token `rl` of a tile const int lane = threadIdx.x & 31, q = (lane >> 2) & 3, rl = (lane & 3) + ((lane >> 4) & 1) * 4; @@ -297,6 +322,7 @@ __global__ void __launch_bounds__(MM_THREADS) k_moe_mma(MoeW w, const BigJob* __ for (int b = 0; b < TT; ++b) #pragma unroll for (int j = 0; j < 8; ++j) acc[a][b][j] = 0.f; +#endif const char* we = moe_expert(w, jb.w); MmTile wt[NP]; MmX xt; @@ -322,6 +348,27 @@ __global__ void __launch_bounds__(MM_THREADS) k_moe_mma(MoeW w, const BigJob* __ for (int i = 0; i < MM_KC / 16; ++i) { const int kt = kt0 + i * kts, kk = kt * 16; if (kt >= kc / 16) break; +#if FNX_ARCH >= 80 + uint32_t fa[2][4], fb[2 * TT][2]; +#pragma unroll + for (int r = 0; r < 2; ++r) { + const __half* ap = arow + r * 16 * MM_LD + kk; + fa[r][0] = *reinterpret_cast(ap); + fa[r][1] = *reinterpret_cast(ap + 8 * MM_LD); + fa[r][2] = *reinterpret_cast(ap + 8); + fa[r][3] = *reinterpret_cast(ap + 8 * MM_LD + 8); + } +#pragma unroll + for (int u = 0; u < 2 * TT; ++u) { + const __half* bp = bcol + u * 8 * MM_LD + kk; + fb[u][0] = *reinterpret_cast(bp); + fb[u][1] = *reinterpret_cast(bp + 8); + } +#pragma unroll + for (int r = 0; r < 2; ++r) +#pragma unroll + for (int u = 0; u < 2 * TT; ++u) mma_16816(acc[r][u], fa[r][0], fa[r][1], fa[r][2], fa[r][3], fb[u][0], fb[u][1]); +#else // 16 k: a 16-byte load per tile row (8 k) twice; each 4 k of it is one HMMA's operand uint4 a[2][2], b[TT][2]; #pragma unroll @@ -342,6 +389,7 @@ __global__ void __launch_bounds__(MM_THREADS) k_moe_mma(MoeW w, const BigJob* __ const uint4& B = b[t][k4 >> 1]; mma_884(acc[r][t], k4 & 1 ? A.z : A.x, k4 & 1 ? A.w : A.y, k4 & 1 ? B.z : B.x, k4 & 1 ? B.w : B.y); } +#endif } } __syncthreads(); @@ -351,6 +399,16 @@ __global__ void __launch_bounds__(MM_THREADS) k_moe_mma(MoeW w, const BigJob* __ float* so = reinterpret_cast(smem); constexpr int SLD = MM_SLD; static_assert(MM_LD % 8 == 0, "16-byte operand loads"); +#if FNX_ARCH >= 80 + // a lane's accumulators of a 16 x 8 tile: rows g and g + 8, columns 2 t4 and 2 t4 + 1 (mma_16816) + float* sob = so + (split ? tg * LO * SLD : tb * 16 * SLD) + rg * 32; // the warp's rows, its first token +#pragma unroll + for (int r = 0; r < 2; ++r) +#pragma unroll + for (int u = 0; u < 2 * TT; ++u) +#pragma unroll + for (int j = 0; j < 4; ++j) sob[(u * 8 + 2 * t4 + (j & 1)) * SLD + r * 16 + g + (j >> 1) * 8] = acc[r][u][j]; +#else // a lane's accumulators in an 8 x 8 tile (measured, tools/m884_probe.cu): rows r0 and r0 + 2, columns cb, cb + 1, // cb + 4, cb + 5, in the order (r0,cb) (r0,cb+1) (r1,cb) (r1,cb+1) (r0,cb+4) (r0,cb+5) (r1,cb+4) (r1,cb+5) const int r0 = (lane & 1) + ((lane >> 4) & 1) * 4, cb = lane & 2; @@ -365,6 +423,7 @@ __global__ void __launch_bounds__(MM_THREADS) k_moe_mma(MoeW w, const BigJob* __ const int tok = (q & 1) * 8 * TT + t * 8 + ((cb + (j & 1) + ((j >> 2) & 1) * 4) ^ sw4); sob[tok * SLD + row] = acc[r][t][j]; } +#endif __syncthreads(); for (int e = threadIdx.x; e < n * BM; e += MM_THREADS) { const int j = e / BM, r = e % BM, row = row0 + r; From 12c2d740c69d4731f95137167a6e459e76f108e0 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 2 Nov 2026 00:40:54 +0100 Subject: [PATCH 02/11] split: the prompt ring's receive and gather steps move data to and from device memory by DMA on the copy engines (the add and output kernels read device memory, not host memory over PCIe) --- src/split/src/pf_common.cuh | 31 ++++++++++++++++++++++++------- src/split/src/prefill.cu | 5 ++++- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/src/split/src/pf_common.cuh b/src/split/src/pf_common.cuh index a1e2916d07..75fa1193a4 100644 --- a/src/split/src/pf_common.cuh +++ b/src/split/src/pf_common.cuh @@ -119,7 +119,7 @@ static __global__ void k_pfr_out(const __half2* __restrict__ ag, float2* __restr template inline void pf_ring_run(const Ring& r, int dev, int g, float* x, int C, unsigned seq, unsigned* err, cudaStream_t s) { if (r.plan.empty() || r.plan.front().part != g) throw std::runtime_error("prefill: the ring's plan is not card " + std::to_string(g) + "'s"); - const int set = (int) (seq & 1u); + const int set = (int) (seq & 1u), fin_part = (g + 1) % NCARD; // the part this card finishes (pf_ring_plan) auto r0 = [&](int k) { return k * C / NCARD; }; auto rows = [&](int k) { return r0(k + 1) - r0(k); }; CUstream cs = (CUstream) s; @@ -146,18 +146,35 @@ inline void pf_ring_run(const Ring& r, int dev, int g, float* x, int C, unsigned k_pfr_pack<<>>((const float2*) (x + (size_t) r0(o.part) * N), rows(o.part) * N / 2, (__half2*) r.send, err); break; - case PfRingOp::ADD: add(r.in[o.hop][set], o.part, o.fin ? r.ag[set] + (size_t) r0(o.part) * N : r.send); break; + case PfRingOp::ADD: + // the slot that arrived in host memory goes to device memory on the copy engine (asynchronous, beside the next chunk's + // compute), and the add reads it there: a kernel reading host memory stalls its SMs at PCIe speed + if (rows(o.part) > 0) + ckc(cudaMemcpyAsync(r.din[o.hop][set], r.in[o.hop][set], (size_t) rows(o.part) * N * sizeof(__half), cudaMemcpyDefault, s), + "ring in"); + add(r.din[o.hop][set], o.part, o.fin ? r.dag[set] + (size_t) r0(o.part) * N : r.send); + break; case PfRingOp::SEND: copy(r.nin[o.hop][set], r.send, rows(o.part)); break; case PfRingOp::PASS: - if (rows(o.part) > 0) - k_pfr_copy<<>>((const uint4*) (r.ag[set] + (size_t) r0(o.part) * N), - (uint4*) (r.nag[set] + (size_t) r0(o.part) * N), - (size_t) rows(o.part) * N / 8); + if (rows(o.part) > 0) { + const size_t off = (size_t) r0(o.part) * N; + if (o.part == fin_part) // the part finished here: device -> the next card's host gather buffer, by DMA + ckc(cudaMemcpyAsync(r.nag[set] + off, r.dag[set] + off, (size_t) rows(o.part) * N * sizeof(__half), cudaMemcpyDefault, s), + "ring gather"); + else // a part that arrived (three or more cards): host -> host by a kernel (a host-to-host memcpy would block the thread) + k_pfr_copy<<>>((const uint4*) (r.ag[set] + off), (uint4*) (r.nag[set] + off), + (size_t) rows(o.part) * N / 8); + } break; case PfRingOp::SIGNAL: signal(o.step); break; case PfRingOp::WAIT: wait(o.step); break; case PfRingOp::OUT: - k_pfr_out<<>>((const __half2*) r.ag[set], (float2*) x, C * N / 2); + // the parts that arrived (everything but the one finished here) go to device memory by DMA, then one kernel reads it all + for (int p = 0; p < NCARD; ++p) + if (p != fin_part && rows(p) > 0) + ckc(cudaMemcpyAsync(r.dag[set] + (size_t) r0(p) * N, r.ag[set] + (size_t) r0(p) * N, (size_t) rows(p) * N * sizeof(__half), + cudaMemcpyDefault, s), "ring out"); + k_pfr_out<<>>((const __half2*) r.dag[set], (float2*) x, C * N / 2); break; default: throw std::runtime_error("prefill: a ring step of unknown kind " + std::to_string((int) o.k)); } diff --git a/src/split/src/prefill.cu b/src/split/src/prefill.cu index 065315726f..4ae9ca6400 100644 --- a/src/split/src/prefill.cu +++ b/src/split/src/prefill.cu @@ -291,7 +291,8 @@ __global__ void k_pf_swiglu(const float* __restrict__ gu, int ffs, int C, __half // a receive slot per reduce hop, flags [2 sets][PF_RING_STEPS] set by the previous card's stream; n*: the next card's; // plan: this card's steps (pf_ring_plan.hpp) struct Engine::PfRing { - __half *send, *in[NCARD - 1][2], *ag[2]; + __half *send, *in[NCARD - 1][2], *ag[2]; // in, ag: host memory, written by the previous card + __half *din[NCARD - 1][2], *dag[2]; // this card's own copies in device memory (the add and the output read these) __half *nin[NCARD - 1][2], *nag[2]; unsigned *flags, *nflags; int next_dev = 0; @@ -688,6 +689,8 @@ void Engine::prefill_alloc() { for (int k = 0; k < 2; ++k) { for (int h = 0; h < NCARD - 1; ++h) r.in[h][k] = hpalloc<__half>(share); // a slot per reduce hop r.ag[k] = hpalloc<__half>((size_t) pf_c_ * N); + for (int h = 0; h < NCARD - 1; ++h) r.din[h][k] = palloc<__half>(share); + r.dag[k] = palloc<__half>((size_t) pf_c_ * N); } r.flags = hpalloc(2 * PF_RING_STEPS); } From 84f16f7a271ec60dbd550b63966e525f2a90d239 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 2 Nov 2026 01:23:25 +0100 Subject: [PATCH 03/11] split: load-time conversion of the dense and small tensors of the IQ3_S set Adds the IQ2_S, IQ3_XXS, IQ3_S, IQ4_XS and Q2_0 types to the GGUF type table and a loader step that, only when a file has routed experts in IQ2_S, IQ3_XXS, IQ3_S or Q2_0, dequantizes its dense matrices, shared experts, projections and embeddings (K-quants, IQ4_XS, IQ4_NL, BF16, F16) and writes them again as Q8_0, and the routers, injections and SSM gates as F32. Other files are not touched. The routed IQ expert kernels are not there yet, so the set still falls back. Checked against gguf-py on the ISTA IQ3_S file: 762 tensors converted, the sampled ones all within the Q8_0 bound (F32 targets exact), every source type covered. --- src/split/CMakeLists.txt | 7 + src/split/src/gguf.cpp | 38 ++++- src/split/src/gguf.hpp | 9 +- src/split/src/tensor_convert.hpp | 264 +++++++++++++++++++++++++++++++ src/split/tools/convert_dump.cpp | 48 ++++++ tests/split/convert_check.py | 71 +++++++++ 6 files changed, 434 insertions(+), 3 deletions(-) create mode 100644 src/split/src/tensor_convert.hpp create mode 100644 src/split/tools/convert_dump.cpp create mode 100644 tests/split/convert_check.py diff --git a/src/split/CMakeLists.txt b/src/split/CMakeLists.txt index b0d7f4c715..4891b03272 100644 --- a/src/split/CMakeLists.txt +++ b/src/split/CMakeLists.txt @@ -75,4 +75,11 @@ if(STRATA_BUILD_TESTS) target_link_libraries(split_${_tt} PRIVATE Threads::Threads) add_test(NAME split_${_tt} COMMAND split_${_tt}) endforeach() + # the load-time conversion's oracle tool (tests/split/convert_check.py compares its output with gguf-py on a real file; not a ctest) + add_executable(split_convert_dump ${_sp}/tools/convert_dump.cpp ${_sp}/src/gguf.cpp) + target_include_directories(split_convert_dump PRIVATE ${_sp}/src ${_sp}/tools) + target_compile_definitions(split_convert_dump PRIVATE FNX_NCARD=${_n0} FNX_27B=0) + target_compile_features(split_convert_dump PRIVATE cxx_std_17) + set_target_properties(split_convert_dump PROPERTIES CUDA_ARCHITECTURES OFF) + target_link_libraries(split_convert_dump PRIVATE Threads::Threads) endif() diff --git a/src/split/src/gguf.cpp b/src/split/src/gguf.cpp index 9ed9fd3f3d..ea7dc4f27d 100644 --- a/src/split/src/gguf.cpp +++ b/src/split/src/gguf.cpp @@ -14,6 +14,8 @@ #include #include +#include "tensor_convert.hpp" + namespace fnx { TypeInfo type_info(uint32_t t) { @@ -33,6 +35,11 @@ TypeInfo type_info(uint32_t t) { case T_Q5_K: return {256, 176}; case T_Q6_K: return {256, 210}; case T_IQ4_NL: return {32, 18}; + case T_IQ3_XXS: return {256, 98}; + case T_IQ3_S: return {256, 110}; + case T_IQ2_S: return {256, 82}; + case T_IQ4_XS: return {256, 136}; + case T_Q2_0: return {64, 18}; } throw std::runtime_error("gguf: unknown ggml type " + std::to_string(t)); } @@ -101,6 +108,27 @@ Gguf::Gguf(const std::string& first) { } else { load_shard(first, true); } + convert_small_tensors(); +} + +// A file with routed experts in the IQ types or Strata's 2-bit type (the ISTA IQ3_S set) also keeps its dense matrices, routers, +// embeddings and projections in K-quants, IQ4_XS and BF16, which the engine does not read. Those are dequantized and written +// again as Q8_0 (F32 for the small ones), once, here; the routed experts are left as they are. A file without such experts +// (UD-Q4_K_XL, Q8_0) is not touched at all: the check below is the only difference for it. +void Gguf::convert_small_tensors() { + bool mixed = false; + for (const auto& kv : tensors_) + mixed |= kv.second.type == T_IQ2_S || kv.second.type == T_IQ3_XXS || kv.second.type == T_IQ3_S || kv.second.type == T_Q2_0; + if (!mixed) return; + for (auto& kv : tensors_) { + Tensor& t = kv.second; + const uint32_t want = conv::wanted_type(t.name); + if (want == 0xFFFFFFFFu || want == t.type) continue; + owned_.emplace_back(); + conv::convert(t, want, owned_.back()); + ++converted_; + } + std::fprintf(stderr, "gguf: %d dense/small tensors converted to Q8_0/F32 at load (the file's routed experts keep their types)\n", converted_); } Gguf::~Gguf() { @@ -281,7 +309,12 @@ Stager::Stager(const Gguf& g, std::vector groups, int consumers, int ahea std::vector ts; for (const std::string& n : gr.spec.names) { const Tensor& t = g.t(n); - if (t.shard < 0) throw std::runtime_error("stager: " + n + " is not in a file"); + if (t.shard < 0) { + if (!t.data) throw std::runtime_error("stager: " + n + " is not in a file"); + gr.t[n] = t; // converted at load: nothing to read + gr.fixed.insert(n); + continue; + } ts.push_back(&t); } std::sort(ts.begin(), ts.end(), [](const Tensor* a, const Tensor* b) { return a->shard != b->shard ? a->shard < b->shard : a->offset < b->offset; }); @@ -406,7 +439,8 @@ void Stager::read_group(G& gr) { for (auto& t : th) t.join(); for (const std::string& e : errs) if (!e.empty()) throw std::runtime_error(e); - for (auto& [name, t] : gr.t) t.data = gr.buf + (uintptr_t) t.data; + for (auto& [name, t] : gr.t) + if (!gr.fixed.count(name)) t.data = gr.buf + (uintptr_t) t.data; read_s_ += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); } diff --git a/src/split/src/gguf.hpp b/src/split/src/gguf.hpp index 543db1a98d..2b458e50de 100644 --- a/src/split/src/gguf.hpp +++ b/src/split/src/gguf.hpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -21,7 +22,8 @@ namespace fnx { enum GgmlType : uint32_t { T_F32 = 0, T_F16 = 1, T_Q4_0 = 2, T_Q4_1 = 3, T_Q5_0 = 6, T_Q5_1 = 7, T_Q8_0 = 8, T_Q8_1 = 9, T_Q2_K = 10, - T_Q3_K = 11, T_Q4_K = 12, T_Q5_K = 13, T_Q6_K = 14, T_Q8_K = 15, T_IQ4_NL = 20, T_BF16 = 30, + T_Q3_K = 11, T_Q4_K = 12, T_Q5_K = 13, T_Q6_K = 14, T_Q8_K = 15, T_IQ3_XXS = 18, T_IQ4_NL = 20, T_IQ3_S = 21, T_IQ2_S = 22, + T_IQ4_XS = 23, T_BF16 = 30, T_Q2_0 = 42, // 42: Strata's 64-value 2-bit blocks (not in llama.cpp) }; struct TypeInfo { @@ -64,6 +66,7 @@ public: #endif const std::map& tensors() const { return tensors_; } int shards() const { return (int) maps_.size(); } + int converted() const { return converted_; } // tensors re-quantized at load (0 for every file the engine reads as it is) const std::string& shard_path(int s) const { return maps_[(size_t) s].path; } size_t shard_size(int s) const { return maps_[(size_t) s].size; } const uint8_t* shard_base(int s) const { return (const uint8_t*) maps_[(size_t) s].base; } @@ -80,7 +83,10 @@ private: std::map> str_arrays_; #endif std::set keys_; + std::deque> owned_; // tensors converted at load (tensor_convert.hpp): their bytes live here, not in a file + int converted_ = 0; void load_shard(const std::string& path, bool meta); + void convert_small_tensors(); }; // Reads groups of tensors (a layer's, say) into host buffers ahead of the threads that slice them, in the order they @@ -116,6 +122,7 @@ private: std::vector spans; size_t bytes = 0; std::map t; + std::set fixed; // converted tensors: their bytes are already in memory (data is a pointer, not an offset into buf) uint8_t* buf = nullptr; int left = 0; // consumers not through with it yet bool ready = false; diff --git a/src/split/src/tensor_convert.hpp b/src/split/src/tensor_convert.hpp new file mode 100644 index 0000000000..78d86e0eb6 --- /dev/null +++ b/src/split/src/tensor_convert.hpp @@ -0,0 +1,264 @@ +// strata-split: load-time conversion of the small tensors of a GGUF whose types the engine does not read, to the types it does +// (what Unsloth's UD-Q4_K_XL file carries: Q8_0 for every dense matrix, the shared experts, the embeddings, the hyper-connection +// and PLE projections; F32 for the routers, the injections and the SSM gates). A set with other types for them (the ISTA-DAS IQ3_S +// set keeps K-quants, IQ4_XS and BF16 there) is dequantized to float and quantized again, once, at load. A tensor that already has the +// target type is never touched, so UD-Q4_K_XL and Q8_0 files load exactly as before. Pure host code, no CUDA. +// +// The dequantizers are ggml's reference ones (ggml-quants.c, dequantize_row_*), written out here because the engine does not link +// ggml's CPU library; tests/split/ check them against gguf-py on real tensors. +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "gguf.hpp" + +namespace fnx { +namespace conv { + +inline float h2f(uint16_t h) { + const uint32_t s = (h >> 15) & 1, e = (h >> 10) & 31, m = h & 1023; + float f; + if (e == 0) f = std::ldexp((float) m, -24); + else if (e == 31) f = m ? NAN : INFINITY; + else f = std::ldexp((float) (m + 1024), (int) e - 25); + return s ? -f : f; +} +inline uint16_t f2h(float x) { // round to nearest even, as ggml's GGML_FP32_TO_FP16 + uint32_t b; + std::memcpy(&b, &x, 4); + const uint32_t s = (b >> 16) & 0x8000, e = (b >> 23) & 0xFF, m = b & 0x7FFFFF; + if (e == 0xFF) return (uint16_t) (s | 0x7C00 | (m ? 0x200 : 0)); + int ne = (int) e - 127 + 15; + if (ne >= 31) return (uint16_t) (s | 0x7C00); + if (ne <= 0) { + if (ne < -10) return (uint16_t) s; + const uint32_t mm = (m | 0x800000) >> (1 - ne); + uint32_t r = mm >> 13; + const uint32_t rem = mm & 0x1FFF; + if (rem > 0x1000 || (rem == 0x1000 && (r & 1))) ++r; + return (uint16_t) (s | r); + } + uint32_t r = ((uint32_t) ne << 10) | (m >> 13); + const uint32_t rem = m & 0x1FFF; + if (rem > 0x1000 || (rem == 0x1000 && (r & 1))) ++r; + return (uint16_t) (s | r); +} +inline float bf2f(uint16_t b) { + const uint32_t u = (uint32_t) b << 16; + float f; + std::memcpy(&f, &u, 4); + return f; +} + +inline const int8_t* kvalues_iq4nl() { + static const int8_t k[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113}; + return k; +} +// the K-quants' 6-bit scale and min of sub-block j (ggml get_scale_min_k4) +inline void scale_min_k4(int j, const uint8_t* q, uint8_t& d, uint8_t& m) { + if (j < 4) { + d = q[j] & 63; + m = q[j + 4] & 63; + } else { + d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4); + m = (q[j + 4] >> 4) | ((q[j] >> 6) << 4); + } +} + +// n values (a whole number of blocks) of `type` at `src`, as floats; throws on a type it has no reader for +inline void dequantize(uint32_t type, const uint8_t* src, size_t n, float* y) { + switch (type) { + case T_F32: std::memcpy(y, src, n * 4); return; + case T_F16: + for (size_t i = 0; i < n; ++i) { uint16_t h; std::memcpy(&h, src + 2 * i, 2); y[i] = h2f(h); } + return; + case T_BF16: + for (size_t i = 0; i < n; ++i) { uint16_t h; std::memcpy(&h, src + 2 * i, 2); y[i] = bf2f(h); } + return; + case T_Q8_0: + for (size_t b = 0; b < n / 32; ++b) { + const uint8_t* p = src + b * 34; + uint16_t dh; + std::memcpy(&dh, p, 2); + const float d = h2f(dh); + for (int j = 0; j < 32; ++j) y[b * 32 + j] = d * (float) (int8_t) p[2 + j]; + } + return; + case T_IQ4_NL: + for (size_t b = 0; b < n / 32; ++b) { + const uint8_t* p = src + b * 18; + uint16_t dh; + std::memcpy(&dh, p, 2); + const float d = h2f(dh); + for (int j = 0; j < 16; ++j) { + y[b * 32 + j] = d * (float) kvalues_iq4nl()[p[2 + j] & 0xF]; + y[b * 32 + j + 16] = d * (float) kvalues_iq4nl()[p[2 + j] >> 4]; + } + } + return; + case T_IQ4_XS: + for (size_t b = 0; b < n / 256; ++b) { + const uint8_t* p = src + b * 136; + uint16_t dh, sh; + std::memcpy(&dh, p, 2); + std::memcpy(&sh, p + 2, 2); + const uint8_t* sl = p + 4; + const uint8_t* qs = p + 8; + const float d = h2f(dh); + float* o = y + b * 256; + for (int ib = 0; ib < 8; ++ib) { + const int ls = ((sl[ib / 2] >> (4 * (ib % 2))) & 0xF) | (((sh >> (2 * ib)) & 3) << 4); + const float dl = d * (float) (ls - 32); + for (int j = 0; j < 16; ++j) { + o[j] = dl * (float) kvalues_iq4nl()[qs[j] & 0xF]; + o[j + 16] = dl * (float) kvalues_iq4nl()[qs[j] >> 4]; + } + o += 32; + qs += 16; + } + } + return; + case T_Q4_K: + for (size_t b = 0; b < n / 256; ++b) { + const uint8_t* p = src + b * 144; + uint16_t dh, mh; + std::memcpy(&dh, p, 2); + std::memcpy(&mh, p + 2, 2); + const float d = h2f(dh), mn = h2f(mh); + const uint8_t* sc = p + 4; + const uint8_t* q = p + 16; + float* o = y + b * 256; + int is = 0; + for (int j = 0; j < 256; j += 64) { + uint8_t s1, m1, s2, m2; + scale_min_k4(is, sc, s1, m1); + scale_min_k4(is + 1, sc, s2, m2); + const float d1 = d * s1, mm1 = mn * m1, d2 = d * s2, mm2 = mn * m2; + for (int l = 0; l < 32; ++l) *o++ = d1 * (float) (q[l] & 0xF) - mm1; + for (int l = 0; l < 32; ++l) *o++ = d2 * (float) (q[l] >> 4) - mm2; + q += 32; + is += 2; + } + } + return; + case T_Q5_K: + for (size_t b = 0; b < n / 256; ++b) { + const uint8_t* p = src + b * 176; + uint16_t dh, mh; + std::memcpy(&dh, p, 2); + std::memcpy(&mh, p + 2, 2); + const float d = h2f(dh), mn = h2f(mh); + const uint8_t* sc = p + 4; + const uint8_t* qh = p + 16; + const uint8_t* ql = p + 48; + float* o = y + b * 256; + int is = 0; + uint8_t u1 = 1, u2 = 2; + for (int j = 0; j < 256; j += 64) { + uint8_t s1, m1, s2, m2; + scale_min_k4(is, sc, s1, m1); + scale_min_k4(is + 1, sc, s2, m2); + const float d1 = d * s1, mm1 = mn * m1, d2 = d * s2, mm2 = mn * m2; + for (int l = 0; l < 32; ++l) *o++ = d1 * (float) ((ql[l] & 0xF) + (qh[l] & u1 ? 16 : 0)) - mm1; + for (int l = 0; l < 32; ++l) *o++ = d2 * (float) ((ql[l] >> 4) + (qh[l] & u2 ? 16 : 0)) - mm2; + ql += 32; + is += 2; + u1 = (uint8_t) (u1 << 2); + u2 = (uint8_t) (u2 << 2); + } + } + return; + case T_Q6_K: + for (size_t b = 0; b < n / 256; ++b) { + const uint8_t* p = src + b * 210; + const uint8_t* ql = p; + const uint8_t* qh = p + 128; + const int8_t* sc = (const int8_t*) (p + 192); + uint16_t dh; + std::memcpy(&dh, p + 208, 2); + const float d = h2f(dh); + float* o = y + b * 256; + for (int h = 0; h < 256; h += 128) { + for (int l = 0; l < 32; ++l) { + const int is = l / 16; + const int q1 = (int) ((ql[l] & 0xF) | (((qh[l] >> 0) & 3) << 4)) - 32; + const int q2 = (int) ((ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4)) - 32; + const int q3 = (int) ((ql[l] >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32; + const int q4 = (int) ((ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32; + o[l] = d * (float) sc[is] * (float) q1; + o[l + 32] = d * (float) sc[is + 2] * (float) q2; + o[l + 64] = d * (float) sc[is + 4] * (float) q3; + o[l + 96] = d * (float) sc[is + 6] * (float) q4; + } + o += 128; + ql += 64; + qh += 32; + sc += 8; + } + } + return; + } + throw std::runtime_error("tensor_convert: no reader for ggml type " + std::to_string(type)); +} + +// Q8_0 as ggml's quantize_row_q8_0_ref: per 32 values d = amax / 127 (stored as f16), q = round(x / d) +inline void quantize_q8_0(const float* x, size_t n, uint8_t* dst) { + for (size_t b = 0; b < n / 32; ++b) { + float amax = 0.f; + for (int j = 0; j < 32; ++j) amax = std::fmax(amax, std::fabs(x[b * 32 + j])); + const float d = amax / 127.0f, id = d != 0.f ? 1.0f / d : 0.f; + const uint16_t dh = f2h(d); + std::memcpy(dst + b * 34, &dh, 2); + for (int j = 0; j < 32; ++j) dst[b * 34 + 2 + j] = (uint8_t) (int8_t) std::lround(x[b * 32 + j] * id); + } +} + +// the type the engine reads a tensor of this name as (what UD-Q4_K_XL carries), or 0xFFFFFFFF for a tensor that is left alone +inline uint32_t wanted_type(const std::string& name) { + auto ends = [&](const char* s) { const size_t l = std::strlen(s); return name.size() >= l && name.compare(name.size() - l, l, s) == 0; }; + static const char* q8[] = {".attn_gate.weight", ".attn_k.weight", ".attn_output.weight", ".attn_q.weight", ".attn_qkv.weight", ".attn_v.weight", + ".ffn_gate_shexp.weight", ".ffn_up_shexp.weight", ".ffn_down_shexp.weight", ".hc_attn_down.weight", + ".hc_attn_up.weight", ".hc_ffn_down.weight", ".hc_ffn_up.weight", ".ple_key.weight", ".ple_value.weight", + ".ssm_out.weight"}; + static const char* f32[] = {".ffn_gate_inp.weight", ".ffn_gate_inp_shexp.weight", ".hc_attn_inject.weight", ".hc_ffn_inject.weight", + ".ssm_alpha.weight", ".ssm_beta.weight", ".ple_conv1d.weight"}; + for (const char* s : q8) + if (ends(s)) return T_Q8_0; + for (const char* s : f32) + if (ends(s)) return T_F32; + if (name == "output.weight" || name == "output_hc_down.weight" || name == "output_hc_up.weight" || name == "token_embd.weight") return T_Q8_0; + return 0xFFFFFFFFu; +} + +// `t` converted to `target` (Q8_0 or F32) into `out`; the Tensor then points at `out` +inline void convert(Tensor& t, uint32_t target, std::vector& out) { + size_t n = 1; + for (int d = 0; d < 4; ++d) n *= (size_t) t.ne[d]; + const TypeInfo from = type_info(t.type); + if (n % (size_t) from.block) throw std::runtime_error(t.name + ": not a whole number of blocks"); + if (target == T_Q8_0 && t.ne[0] % 32) throw std::runtime_error(t.name + ": rows are not a whole number of Q8_0 blocks"); + std::vector f(n); + dequantize(t.type, t.data, n, f.data()); + if (target == T_F32) { + out.resize(n * 4); + std::memcpy(out.data(), f.data(), n * 4); + } else if (target == T_Q8_0) { + out.resize(n / 32 * 34); + quantize_q8_0(f.data(), n, out.data()); + } else { + throw std::runtime_error("tensor_convert: target type " + std::to_string(target)); + } + t.type = target; + t.data = out.data(); + t.nbytes = out.size(); + t.shard = -1; // not in a GGUF file any more: readers that stage from the file by offset must take the bytes at t.data + t.offset = 0; +} + +} // namespace conv +} // namespace fnx diff --git a/src/split/tools/convert_dump.cpp b/src/split/tools/convert_dump.cpp new file mode 100644 index 0000000000..f37c056c8f --- /dev/null +++ b/src/split/tools/convert_dump.cpp @@ -0,0 +1,48 @@ +// Writes what the loader makes of tensors of a GGUF (src/tensor_convert.hpp): for each tensor named on the command line, the +// converted tensor's values as float32 to OUTDIR/.f32 plus a line "name type_after nbytes" on stdout. tests/split/convert_check.py +// compares those with gguf-py's own dequantization of the same tensors in the file. CPU only. +// bin/convert_dump MODEL.gguf OUTDIR name [name ...] (a name of "all" dumps every tensor the loader converted) +#include +#include +#include +#include + +#include "../src/gguf.hpp" +#include "../src/tensor_convert.hpp" + +int main(int argc, char** argv) { + if (argc < 4) { + std::fprintf(stderr, "usage: convert_dump MODEL.gguf OUTDIR name [name ...]\n"); + return 2; + } + try { + fnx::Gguf g(argv[1]); + std::printf("converted %d\n", g.converted()); + std::vector names; + for (int i = 3; i < argc; ++i) { + if (std::string(argv[i]) == "all") { + for (const auto& kv : g.tensors()) + if (fnx::conv::wanted_type(kv.first) != 0xFFFFFFFFu) names.push_back(kv.first); + } else { + names.push_back(argv[i]); + } + } + for (const std::string& n : names) { + const fnx::Tensor& t = g.t(n); + size_t cnt = 1; + for (int d = 0; d < 4; ++d) cnt *= (size_t) t.ne[d]; + std::vector f(cnt); + fnx::conv::dequantize(t.type, t.data, cnt, f.data()); + const std::string path = std::string(argv[2]) + "/" + n + ".f32"; + FILE* fp = std::fopen(path.c_str(), "wb"); + if (!fp) throw std::runtime_error("cannot write " + path); + std::fwrite(f.data(), 4, cnt, fp); + std::fclose(fp); + std::printf("%s %u %zu\n", n.c_str(), t.type, t.nbytes); + } + } catch (const std::exception& e) { + std::fprintf(stderr, "convert_dump: %s\n", e.what()); + return 1; + } + return 0; +} diff --git a/tests/split/convert_check.py b/tests/split/convert_check.py new file mode 100644 index 0000000000..d0c7f7b5b6 --- /dev/null +++ b/tests/split/convert_check.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Check the loader's tensor conversion (src/split/src/tensor_convert.hpp) against gguf-py. + + convert_dump MODEL.gguf OUTDIR name... > dump.txt + convert_check.py MODEL.gguf OUTDIR dump.txt --gguf-py /path/to/llama.cpp/gguf-py + +For each tensor in the dump: the values the loader holds now (read back by convert_dump) must equal gguf-py's dequantization of the +file's original tensor to within what the target type allows: exactly (F32 target), or within half a Q8_0 step per 32 values +(amax/254, plus the f16 rounding of the scale). Prints one line per tensor and exits 1 on any miss. +""" +import argparse +import os +import sys + +import numpy as np + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("model") + ap.add_argument("outdir") + ap.add_argument("dump") + ap.add_argument("--gguf-py", required=True) + a = ap.parse_args() + sys.path.insert(0, a.gguf_py) + import gguf + from gguf import quants + + shards = [a.model] + import re + m = re.match(r"(.*-)(\d{5})(-of-)(\d{5})(\.gguf)$", a.model) + if m: + shards = ["%s%05d%s%s%s" % (m[1], i, m[3], m[4], m[5]) for i in range(1, int(m[4]) + 1)] + tensors = {} + for s in shards: + r = gguf.GGUFReader(s) + for t in r.tensors: + tensors[t.name] = t + + bad = 0 + for line in open(a.dump): + p = line.split() + if len(p) != 3 or p[0] == "converted": + continue + name, ty = p[0], int(p[1]) + t = tensors[name] + ref = quants.dequantize(t.data, t.tensor_type).astype(np.float64).reshape(-1) + got = np.fromfile(os.path.join(a.outdir, name + ".f32"), dtype=np.float32).astype(np.float64) + if ref.shape != got.shape: + print("FAIL %s: %d values, gguf-py %d" % (name, got.size, ref.size)) + bad += 1 + continue + err = np.abs(got - ref) + if ty == 0: # F32: BF16 / F16 / F32 source, exact + lim = np.zeros_like(err) + else: # Q8_0: half a step of its block, the scale stored as f16 + blk = ref.reshape(-1, 32) + amax = np.abs(blk).max(axis=1) + # the scale d = amax/127 is stored as f16 (relative error 2^-11), and the value is q*d with |q| <= 127 + # (a block whose d falls below f16's normal range, 6.1e-5, has an absolute step of 2^-25 in d: 127 * 2^-25 on the value; + # 8 of the 19.9M blocks of token_embd are like that) + lim = np.repeat(amax * (0.5 / 127.0 + 2.0 ** -10) + 127 * 2.0 ** -25 + 1e-12, 32) + ok = bool((err <= lim).all()) + rel = float(np.sqrt((err ** 2).sum() / max((ref ** 2).sum(), 1e-30))) + print("%s %s %s from %s max|d|=%.3g rel_rms=%.3g" % ("ok " if ok else "FAIL", name, "F32" if ty == 0 else "Q8_0", t.tensor_type.name, err.max(), rel)) + bad += not ok + sys.exit(1 if bad else 0) + + +if __name__ == "__main__": + main() From 3d08a095ff6ba4bba9ee593e17d7739a7c6019d0 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 2 Nov 2026 01:30:07 +0100 Subject: [PATCH 04/11] split: routed expert kernels for the IQ3_S set (first version, to be gated) Decode: ggml's vec_dot for IQ4_XS, IQ3_S, IQ3_XXS and IQ2_S added to the mmvq expert launchers beside IQ4_NL and Q4_0. Prompt: weight tiles for Q4_0, IQ4_NL, IQ4_XS, IQ3_S, IQ3_XXS and IQ2_S in moe_mma_iq.cuh (ggml's dequantization rounded once to f16). Loader: Strata's Q2_0 down experts are repacked to Q4_0 blocks (lossless, twice the bytes). --- src/split/src/gguf.cpp | 6 + src/split/src/kernels.cu | 20 ++- src/split/src/moe_mma.cu | 8 ++ src/split/src/moe_mma_iq.cuh | 229 +++++++++++++++++++++++++++++++ src/split/src/tensor_convert.hpp | 46 +++++++ tests/split/convert_check.py | 13 +- 6 files changed, 319 insertions(+), 3 deletions(-) create mode 100644 src/split/src/moe_mma_iq.cuh diff --git a/src/split/src/gguf.cpp b/src/split/src/gguf.cpp index ea7dc4f27d..917c5ffd04 100644 --- a/src/split/src/gguf.cpp +++ b/src/split/src/gguf.cpp @@ -122,6 +122,12 @@ void Gguf::convert_small_tensors() { if (!mixed) return; for (auto& kv : tensors_) { Tensor& t = kv.second; + if (t.type == T_Q2_0) { // the routed down experts of some layers: the same values as Q4_0 blocks + owned_.emplace_back(); + conv::repack_q2_0_to_q4_0(t, owned_.back()); + ++converted_; + continue; + } const uint32_t want = conv::wanted_type(t.name); if (want == 0xFFFFFFFFu || want == t.type) continue; owned_.emplace_back(); diff --git a/src/split/src/kernels.cu b/src/split/src/kernels.cu index 61d50182d0..872ac45037 100644 --- a/src/split/src/kernels.cu +++ b/src/split/src/kernels.cu @@ -121,6 +121,10 @@ template __device__ __forceinline__ float vdot(const void* v, c else if constexpr (type == GGML_TYPE_Q4_0) return vec_dot_q4_0_q8_1(v, y, kbx, iqs); else if constexpr (type == GGML_TYPE_Q6_K) return vec_dot_q6_K_q8_1(v, y, kbx, iqs); else if constexpr (type == GGML_TYPE_IQ4_NL) return vec_dot_iq4_nl_q8_1(v, y, kbx, iqs); + else if constexpr (type == GGML_TYPE_IQ4_XS) return vec_dot_iq4_xs_q8_1(v, y, kbx, iqs); + else if constexpr (type == GGML_TYPE_IQ3_S) return vec_dot_iq3_s_q8_1(v, y, kbx, iqs); + else if constexpr (type == GGML_TYPE_IQ3_XXS) return vec_dot_iq3_xxs_q8_1(v, y, kbx, iqs); + else if constexpr (type == GGML_TYPE_IQ2_S) return vec_dot_iq2_s_q8_1(v, y, kbx, iqs); else return 0.0f; } template constexpr int vdr_of() { @@ -130,7 +134,11 @@ template constexpr int vdr_of() { else if constexpr (type == GGML_TYPE_Q5_1) return VDR_Q5_1_Q8_1_MMVQ; else if constexpr (type == GGML_TYPE_Q4_0) return VDR_Q4_0_Q8_1_MMVQ; else if constexpr (type == GGML_TYPE_Q6_K) return VDR_Q6_K_Q8_1_MMVQ; - else return VDR_IQ4_NL_Q8_1_MMVQ; + else if constexpr (type == GGML_TYPE_IQ4_NL) return VDR_IQ4_NL_Q8_1_MMVQ; + else if constexpr (type == GGML_TYPE_IQ4_XS) return VDR_IQ4_XS_Q8_1_MMVQ; + else if constexpr (type == GGML_TYPE_IQ3_S) return VDR_IQ3_S_Q8_1_MMVQ; + else if constexpr (type == GGML_TYPE_IQ3_XXS) return VDR_IQ3_XXS_Q8_1_MMVQ; + else return VDR_IQ2_S_Q8_1_MMVQ; } constexpr int MMVQ_THREADS = 128; @@ -1940,6 +1948,11 @@ void moe_mm(bool down, const DW& A, size_t sa, const Job* jobs, const int* njobs case T_Q5_1: moe_launch(down, w, jobs, njobs, njobs_max, in, (float*) out, s, T); break; case T_Q4_0: moe_launch(down, w, jobs, njobs, njobs_max, in, (float*) out, s, T); break; case T_Q8_0: moe_launch(down, w, jobs, njobs, njobs_max, in, (float*) out, s, T); break; + case T_IQ4_NL: moe_launch(down, w, jobs, njobs, njobs_max, in, (float*) out, s, T); break; + case T_IQ4_XS: moe_launch(down, w, jobs, njobs, njobs_max, in, (float*) out, s, T); break; + case T_IQ3_S: moe_launch(down, w, jobs, njobs, njobs_max, in, (float*) out, s, T); break; + case T_IQ3_XXS: moe_launch(down, w, jobs, njobs, njobs_max, in, (float*) out, s, T); break; + case T_IQ2_S: moe_launch(down, w, jobs, njobs, njobs_max, in, (float*) out, s, T); break; default: throw std::runtime_error("moe: expert type " + std::to_string(A.type) + " not handled"); } ck_launch(down ? "moe_down" : "moe_gate_up"); @@ -1996,6 +2009,11 @@ void moe_mm_big(bool down, const DW& A, size_t sa, const BigJob* jobs, const int case T_Q5_1: moe_launch_big(down, w, jobs, njobs, njobs_cap, in, (float*) out, s); break; case T_Q4_0: moe_launch_big(down, w, jobs, njobs, njobs_cap, in, (float*) out, s); break; case T_Q8_0: moe_launch_big(down, w, jobs, njobs, njobs_cap, in, (float*) out, s); break; + case T_IQ4_NL: moe_launch_big(down, w, jobs, njobs, njobs_cap, in, (float*) out, s); break; + case T_IQ4_XS: moe_launch_big(down, w, jobs, njobs, njobs_cap, in, (float*) out, s); break; + case T_IQ3_S: moe_launch_big(down, w, jobs, njobs, njobs_cap, in, (float*) out, s); break; + case T_IQ3_XXS: moe_launch_big(down, w, jobs, njobs, njobs_cap, in, (float*) out, s); break; + case T_IQ2_S: moe_launch_big(down, w, jobs, njobs, njobs_cap, in, (float*) out, s); break; default: throw std::runtime_error("moe: expert type " + std::to_string(A.type) + " not handled"); } ck_launch(down ? "moe_down (big jobs)" : "moe_gate_up (big jobs)"); diff --git a/src/split/src/moe_mma.cu b/src/split/src/moe_mma.cu index 126f010ab5..bf6b520728 100644 --- a/src/split/src/moe_mma.cu +++ b/src/split/src/moe_mma.cu @@ -11,6 +11,7 @@ #include #include "ggml.h" +#include "common.cuh" namespace fnx { @@ -24,6 +25,7 @@ __device__ __forceinline__ float silu_(float x) { return x / (1.0f + __expf(-x)) #include "moe_w.cuh" #include "moe_mma.cuh" +#include "moe_mma_iq.cuh" template void mma_launch(const MoeW& w, const BigJob* jobs, const int* njobs, int njobs_cap, const __half* x, float* out, cudaStream_t s) { @@ -41,6 +43,12 @@ void moe_mma(const DW& A, size_t sa, const BigJob* jobs, const int* njobs, int n case T_Q5_K: mma_launch(w, jobs, njobs, njobs_cap, x, out, s); break; case T_Q5_1: mma_launch(w, jobs, njobs, njobs_cap, x, out, s); break; case T_Q8_0: mma_launch(w, jobs, njobs, njobs_cap, x, out, s); break; + case T_Q4_0: mma_launch(w, jobs, njobs, njobs_cap, x, out, s); break; + case T_IQ4_NL: mma_launch(w, jobs, njobs, njobs_cap, x, out, s); break; + case T_IQ4_XS: mma_launch(w, jobs, njobs, njobs_cap, x, out, s); break; + case T_IQ3_S: mma_launch(w, jobs, njobs, njobs_cap, x, out, s); break; + case T_IQ3_XXS: mma_launch(w, jobs, njobs, njobs_cap, x, out, s); break; + case T_IQ2_S: mma_launch(w, jobs, njobs, njobs_cap, x, out, s); break; default: throw std::runtime_error("moe_mma: expert type " + std::to_string(A.type) + " not handled"); } ck_launch("moe_mma"); diff --git a/src/split/src/moe_mma_iq.cuh b/src/split/src/moe_mma_iq.cuh new file mode 100644 index 0000000000..b347274ed6 --- /dev/null +++ b/src/split/src/moe_mma_iq.cuh @@ -0,0 +1,229 @@ +// The prompt path's weight tiles (moe_mma.cuh) for the 4-bit codebook and i-quant routed experts of the IQ3_S set: Q4_0 (what the Q2_0 +// experts are repacked to at load, tensor_convert.hpp), IQ4_NL, IQ4_XS, IQ3_S, IQ3_XXS and IQ2_S. Each value is ggml's own dequantization +// (ggml-cuda/dequantize.cuh dequantize_*: the f32 product d * scale * grid * sign) rounded once to f16, so the f16 operands are the ones +// llama.cpp's cuBLAS path would have made. A thread takes one 32-value sub-block of a row per k-step (MM_TPR = 2 of them side by side +// in the step's 64 columns) like the Q5_1 and Q8_0 tiles; the 256-value types find theirs at (k0 % 256) / 32 + u in the block. +// First version: the raw bytes are read with 16- and 32-bit loads (the blocks of 110, 98 and 82 bytes are only 2-byte aligned) and the +// grids come from ggml's tables in global memory (cached); not yet tuned for speed. + +__device__ __forceinline__ uint32_t mq_ld16(const uint8_t* p) { return *reinterpret_cast(p); } +__device__ __forceinline__ uint32_t mq_ld32(const uint8_t* p) { return mq_ld16(p) | (mq_ld16(p + 2) << 16); } +__device__ __forceinline__ float mq_half(uint32_t h) { return __half2float(__ushort_as_half((uint16_t) h)); } +// 32 f32 values to f16 pairs and into the tile row +__device__ __forceinline__ void mq_put32(__half* dst, const float (&f)[32]) { + __half2 y[16]; +#pragma unroll + for (int i = 0; i < 16; ++i) y[i] = __floats2half2_rn(f[2 * i], f[2 * i + 1]); + mm_store8(dst, y); + mm_store8(dst + 16, y + 8); +} +__device__ __forceinline__ void mq_zero32(__half* dst) { + float z[32]; +#pragma unroll + for (int i = 0; i < 32; ++i) z[i] = 0.f; + mq_put32(dst, z); +} + +// Q4_0 (value (nibble - 8) * d) and IQ4_NL (kvalues_iq4nl[nibble] * d): 18 bytes, low nibbles are values 0..15, high 16..31 +template +struct MmTile4 { + uint16_t v[9]; + bool live, item; + __device__ __forceinline__ void fetch(const char* we, size_t row_a, int nrows, int row0, int k0, int kc) { + const int r = threadIdx.x / MM_TPR, u = threadIdx.x % MM_TPR, row = row0 + r; + item = u * 32 < kc; + live = item && row < nrows; + if (live) { + const uint8_t* b = (const uint8_t*) we + (size_t) row * row_a + (size_t) (k0 / 32 + u) * 18; +#pragma unroll + for (int l = 0; l < 9; ++l) v[l] = (uint16_t) mq_ld16(b + 2 * l); + } + } + __device__ __forceinline__ void put(int, int, __half* sw) const { + if (!item) return; + const int r = threadIdx.x / MM_TPR, u = threadIdx.x % MM_TPR; + if (!live) { + mq_zero32(sw + r * MM_LD + u * 32); + return; + } + const float d = mq_half(v[0]); + float f[32]; +#pragma unroll + for (int w = 0; w < 4; ++w) { + const uint32_t q = (uint32_t) v[1 + 2 * w] | ((uint32_t) v[2 + 2 * w] << 16); +#pragma unroll + for (int k = 0; k < 4; ++k) { + const int lo = (q >> (8 * k)) & 0xF, hi = (q >> (8 * k + 4)) & 0xF; + f[4 * w + k] = d * (float) (NL ? (int) kvalues_iq4nl[lo] : lo - 8); + f[16 + 4 * w + k] = d * (float) (NL ? (int) kvalues_iq4nl[hi] : hi - 8); + } + } + mq_put32(sw + r * MM_LD + u * 32, f); + } +}; +template <> struct MmTile : MmTile4 {}; +template <> struct MmTile : MmTile4 {}; + +// IQ4_XS: 136 bytes = d (f16), scales_h (u16), scales_l[4], qs[128]; sub-block ib has 16 qs bytes at 8 + 16 ib and a 6-bit scale +template <> struct MmTile { + uint32_t hd[2], q[4]; + int ib; + bool live, item; + __device__ __forceinline__ void fetch(const char* we, size_t row_a, int nrows, int row0, int k0, int kc) { + const int r = threadIdx.x / MM_TPR, u = threadIdx.x % MM_TPR, row = row0 + r; + item = u * 32 < kc; + live = item && row < nrows; + ib = (k0 % 256) / 32 + u; + if (live) { + const uint8_t* b = (const uint8_t*) we + (size_t) row * row_a + (size_t) (k0 / 256) * 136; + hd[0] = mq_ld32(b); + hd[1] = mq_ld32(b + 4); +#pragma unroll + for (int l = 0; l < 4; ++l) q[l] = mq_ld32(b + 8 + 16 * ib + 4 * l); + } + } + __device__ __forceinline__ void put(int, int, __half* sw) const { + if (!item) return; + const int r = threadIdx.x / MM_TPR, u = threadIdx.x % MM_TPR; + if (!live) { + mq_zero32(sw + r * MM_LD + u * 32); + return; + } + const uint32_t sh = hd[0] >> 16, sl = (hd[1] >> (8 * (ib / 2))) & 0xFF; + const int ls = (int) (((sl >> (4 * (ib % 2))) & 0xF) | (((sh >> (2 * ib)) & 3) << 4)); + const float d = mq_half(hd[0] & 0xFFFF) * (float) (ls - 32); + float f[32]; +#pragma unroll + for (int l = 0; l < 4; ++l) +#pragma unroll + for (int k = 0; k < 4; ++k) { + const uint32_t byte = (q[l] >> (8 * k)) & 0xFF; + f[4 * l + k] = d * (float) kvalues_iq4nl[byte & 0xF]; + f[16 + 4 * l + k] = d * (float) kvalues_iq4nl[byte >> 4]; + } + mq_put32(sw + r * MM_LD + u * 32, f); + } +}; + +__device__ __forceinline__ void mq_signed4(float* y, uint32_t grid, float d, uint32_t signs, int s0) { +#pragma unroll + for (int j = 0; j < 4; ++j) y[j] = d * (float) ((grid >> (8 * j)) & 0xFF) * ((signs & kmask_iq2xs[s0 + j]) ? -1.f : 1.f); +} + +// IQ3_S: 110 bytes = d, qs[64], qh[8], signs[32], scales[4]; sub-block ib: qs[8 ib..], qh[ib], signs[4 ib..], a 4-bit scale (1 + 2 s) d +template <> struct MmTile { + uint32_t dq, qs[2], sg, qh, sc; // d (low 16 bits of dq), 8 qs bytes, 4 sign bytes, qh byte, scales byte + int ib; + bool live, item; + __device__ __forceinline__ void fetch(const char* we, size_t row_a, int nrows, int row0, int k0, int kc) { + const int r = threadIdx.x / MM_TPR, u = threadIdx.x % MM_TPR, row = row0 + r; + item = u * 32 < kc; + live = item && row < nrows; + ib = (k0 % 256) / 32 + u; + if (live) { + const uint8_t* b = (const uint8_t*) we + (size_t) row * row_a + (size_t) (k0 / 256) * 110; + dq = mq_ld16(b); + qs[0] = mq_ld32(b + 2 + 8 * ib); + qs[1] = mq_ld32(b + 6 + 8 * ib); + qh = b[66 + ib]; + sg = mq_ld32(b + 74 + 4 * ib); + sc = b[106 + ib / 2]; + } + } + __device__ __forceinline__ void put(int, int, __half* sw) const { + if (!item) return; + const int r = threadIdx.x / MM_TPR, u = threadIdx.x % MM_TPR; + if (!live) { + mq_zero32(sw + r * MM_LD + u * 32); + return; + } + const float d = mq_half(dq) * (float) (1 + 2 * ((sc >> (4 * (ib % 2))) & 0xF)); + float f[32]; +#pragma unroll + for (int il = 0; il < 4; ++il) { + const uint32_t q0 = (qs[(2 * il) / 4] >> (8 * ((2 * il) % 4))) & 0xFF, q1 = (qs[(2 * il + 1) / 4] >> (8 * ((2 * il + 1) % 4))) & 0xFF; + const uint32_t g1 = iq3s_grid[q0 | ((qh << (8 - 2 * il)) & 256)], g2 = iq3s_grid[q1 | ((qh << (7 - 2 * il)) & 256)]; + const uint32_t sb = (sg >> (8 * il)) & 0xFF; + mq_signed4(f + 8 * il, g1, d, sb, 0); + mq_signed4(f + 8 * il + 4, g2, d, sb, 4); + } + mq_put32(sw + r * MM_LD + u * 32, f); + } +}; + +// IQ3_XXS: 98 bytes = d, qs[96]: 64 grid indices (8 per sub-block) then per sub-block a u32 of four 7-bit sign codes and a 4-bit scale at the top +template <> struct MmTile { + uint32_t dq, qs[2], aux; + int ib; + bool live, item; + __device__ __forceinline__ void fetch(const char* we, size_t row_a, int nrows, int row0, int k0, int kc) { + const int r = threadIdx.x / MM_TPR, u = threadIdx.x % MM_TPR, row = row0 + r; + item = u * 32 < kc; + live = item && row < nrows; + ib = (k0 % 256) / 32 + u; + if (live) { + const uint8_t* b = (const uint8_t*) we + (size_t) row * row_a + (size_t) (k0 / 256) * 98; + dq = mq_ld16(b); + qs[0] = mq_ld32(b + 2 + 8 * ib); + qs[1] = mq_ld32(b + 6 + 8 * ib); + aux = mq_ld32(b + 66 + 4 * ib); + } + } + __device__ __forceinline__ void put(int, int, __half* sw) const { + if (!item) return; + const int r = threadIdx.x / MM_TPR, u = threadIdx.x % MM_TPR; + if (!live) { + mq_zero32(sw + r * MM_LD + u * 32); + return; + } + const float d = mq_half(dq) * (0.5f + (float) (aux >> 28)) * 0.5f; + float f[32]; +#pragma unroll + for (int il = 0; il < 4; ++il) { + const uint32_t q0 = (qs[(2 * il) / 4] >> (8 * ((2 * il) % 4))) & 0xFF, q1 = (qs[(2 * il + 1) / 4] >> (8 * ((2 * il + 1) % 4))) & 0xFF; + const uint32_t sb = ksigns_iq2xs[(aux >> (7 * il)) & 127]; + mq_signed4(f + 8 * il, iq3xxs_grid[q0], d, sb, 0); + mq_signed4(f + 8 * il + 4, iq3xxs_grid[q1], d, sb, 4); + } + mq_put32(sw + r * MM_LD + u * 32, f); + } +}; + +// IQ2_S: 82 bytes = d, qs[32] (grid index low bytes, 4 per sub-block), signs[32] (4 per sub-block), qh[8], scales[8]; 10-bit grid index of 8 values +template <> struct MmTile { + uint32_t dq, qs, sg, qh, sc; + int ib; + bool live, item; + __device__ __forceinline__ void fetch(const char* we, size_t row_a, int nrows, int row0, int k0, int kc) { + const int r = threadIdx.x / MM_TPR, u = threadIdx.x % MM_TPR, row = row0 + r; + item = u * 32 < kc; + live = item && row < nrows; + ib = (k0 % 256) / 32 + u; + if (live) { + const uint8_t* b = (const uint8_t*) we + (size_t) row * row_a + (size_t) (k0 / 256) * 82; + dq = mq_ld16(b); + qs = mq_ld32(b + 2 + 4 * ib); + sg = mq_ld32(b + 34 + 4 * ib); + qh = b[66 + ib]; + sc = b[74 + ib]; + } + } + __device__ __forceinline__ void put(int, int, __half* sw) const { + if (!item) return; + const int r = threadIdx.x / MM_TPR, u = threadIdx.x % MM_TPR; + if (!live) { + mq_zero32(sw + r * MM_LD + u * 32); + return; + } + float f[32]; +#pragma unroll + for (int il = 0; il < 4; ++il) { + const uint64_t grid = iq2s_grid[((qs >> (8 * il)) & 0xFF) | ((qh << (8 - 2 * il)) & 0x300)]; + const float d = mq_half(dq) * (0.5f + (float) ((sc >> (4 * (il / 2))) & 0xF)) * 0.25f; + const uint32_t sb = (sg >> (8 * il)) & 0xFF; + mq_signed4(f + 8 * il, (uint32_t) grid, d, sb, 0); + mq_signed4(f + 8 * il + 4, (uint32_t) (grid >> 32), d, sb, 4); + } + mq_put32(sw + r * MM_LD + u * 32, f); + } +}; diff --git a/src/split/src/tensor_convert.hpp b/src/split/src/tensor_convert.hpp index 78d86e0eb6..6693c7a676 100644 --- a/src/split/src/tensor_convert.hpp +++ b/src/split/src/tensor_convert.hpp @@ -89,6 +89,27 @@ inline void dequantize(uint32_t type, const uint8_t* src, size_t n, float* y) { for (int j = 0; j < 32; ++j) y[b * 32 + j] = d * (float) (int8_t) p[2 + j]; } return; + case T_Q4_0: + for (size_t b = 0; b < n / 32; ++b) { + const uint8_t* p = src + b * 18; + uint16_t dh; + std::memcpy(&dh, p, 2); + const float d = h2f(dh); + for (int j = 0; j < 16; ++j) { + y[b * 32 + j] = d * (float) ((int) (p[2 + j] & 0xF) - 8); + y[b * 32 + j + 16] = d * (float) ((int) (p[2 + j] >> 4) - 8); + } + } + return; + case T_Q2_0: + for (size_t b = 0; b < n / 64; ++b) { + const uint8_t* p = src + b * 18; + uint16_t dh; + std::memcpy(&dh, p, 2); + const float d = h2f(dh); + for (int j = 0; j < 64; ++j) y[b * 64 + j] = d * (float) ((int) ((p[2 + j / 4] >> (2 * (j % 4))) & 3) - 1); + } + return; case T_IQ4_NL: for (size_t b = 0; b < n / 32; ++b) { const uint8_t* p = src + b * 18; @@ -260,5 +281,30 @@ inline void convert(Tensor& t, uint32_t target, std::vector& out) { t.offset = 0; } +// Strata's Q2_0 (64 values in 18 bytes: f16 d, two bits per value, value j in byte j / 4 at bit 2 (j % 4), meaning (code - 1) * d) as two +// Q4_0 blocks (32 values in 18 bytes: f16 d, nibble i of the low half = value i, of the high half = value i + 16, meaning (nibble - 8) * d). +// Lossless: nibble = code + 7 gives (code + 7 - 8) * d, the same product. The engine's Q4_0 kernels then read it (the draft layer's +// experts.bin goes the same way, model.cpp Mtp::experts). Twice the bytes. +inline void repack_q2_0_to_q4_0(Tensor& t, std::vector& out) { + if (t.ne[0] % 64) throw std::runtime_error(t.name + ": rows are not a whole number of Q2_0 blocks"); + const size_t nb = t.nbytes / 18; + out.resize(nb * 36); + for (size_t b = 0; b < nb; ++b) { + const uint8_t* in = t.data + b * 18; + auto code = [&](int j) { return (in[2 + j / 4] >> (2 * (j % 4))) & 3; }; + for (int h = 0; h < 2; ++h) { + uint8_t* o = out.data() + (2 * b + (size_t) h) * 18; + o[0] = in[0]; + o[1] = in[1]; + for (int i = 0; i < 16; ++i) o[2 + i] = (uint8_t) ((code(32 * h + i) + 7) | ((code(32 * h + 16 + i) + 7) << 4)); + } + } + t.type = T_Q4_0; + t.data = out.data(); + t.nbytes = out.size(); + t.shard = -1; + t.offset = 0; +} + } // namespace conv } // namespace fnx diff --git a/tests/split/convert_check.py b/tests/split/convert_check.py index d0c7f7b5b6..dc5cfcc1c7 100644 --- a/tests/split/convert_check.py +++ b/tests/split/convert_check.py @@ -44,7 +44,14 @@ def main(): continue name, ty = p[0], int(p[1]) t = tensors[name] - ref = quants.dequantize(t.data, t.tensor_type).astype(np.float64).reshape(-1) + if t.tensor_type.name == "Q2_0": # Strata's type 42, not in gguf-py's dequantizers: (code - 1) * d, value j in byte j / 4 at bit 2 (j % 4) + raw = np.ascontiguousarray(t.data).reshape(-1, 18) + d = raw[:, :2].copy().view(np.float16).astype(np.float64).reshape(-1, 1) + qs = raw[:, 2:] + codes = np.stack([(qs >> (2 * k)) & 3 for k in range(4)], axis=2).reshape(-1, 64) + ref = ((codes.astype(np.float64) - 1.0) * d).reshape(-1) + else: + ref = quants.dequantize(t.data, t.tensor_type).astype(np.float64).reshape(-1) got = np.fromfile(os.path.join(a.outdir, name + ".f32"), dtype=np.float32).astype(np.float64) if ref.shape != got.shape: print("FAIL %s: %d values, gguf-py %d" % (name, got.size, ref.size)) @@ -53,6 +60,8 @@ def main(): err = np.abs(got - ref) if ty == 0: # F32: BF16 / F16 / F32 source, exact lim = np.zeros_like(err) + elif ty != 8: # a type the loader keeps or repacks without changing a value (Q2_0 -> Q4_0, IQ4_NL as is): f32 rounding only + lim = np.abs(ref) * 1e-6 + 1e-12 else: # Q8_0: half a step of its block, the scale stored as f16 blk = ref.reshape(-1, 32) amax = np.abs(blk).max(axis=1) @@ -62,7 +71,7 @@ def main(): lim = np.repeat(amax * (0.5 / 127.0 + 2.0 ** -10) + 127 * 2.0 ** -25 + 1e-12, 32) ok = bool((err <= lim).all()) rel = float(np.sqrt((err ** 2).sum() / max((ref ** 2).sum(), 1e-30))) - print("%s %s %s from %s max|d|=%.3g rel_rms=%.3g" % ("ok " if ok else "FAIL", name, "F32" if ty == 0 else "Q8_0", t.tensor_type.name, err.max(), rel)) + print("%s %s %s from %s max|d|=%.3g rel_rms=%.3g" % ("ok " if ok else "FAIL", name, {0: "F32", 8: "Q8_0", 2: "Q4_0", 20: "IQ4_NL"}.get(ty, str(ty)), t.tensor_type.name, err.max(), rel)) bad += not ok sys.exit(1 if bad else 0) From fd3839172c6ac5b1420d33daf4b53d1d8d1a9a4a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 2 Nov 2026 06:27:49 +0100 Subject: [PATCH 05/11] split: tile exactness test and fnx_run (teacher-forced logits) as optional build targets split_moe_tile_test runs the prompt kernel's weight tiles on a GPU for one expert of each routed-expert type and tests/split/tile_check.py compares them with gguf-py. split_fnx_run is sFNX's logits tool on the same engine objects. --- src/split/CMakeLists.txt | 21 + src/split/tools/batch_check.hpp | 173 ++++ src/split/tools/fnx_run.cpp | 1375 ++++++++++++++++++++++++++++++ src/split/tools/moe_tile_test.cu | 135 +++ src/split/tools/ref_tokens.hpp | 42 + tests/split/tile_check.py | 69 ++ 6 files changed, 1815 insertions(+) create mode 100644 src/split/tools/batch_check.hpp create mode 100644 src/split/tools/fnx_run.cpp create mode 100644 src/split/tools/moe_tile_test.cu create mode 100644 src/split/tools/ref_tokens.hpp create mode 100644 tests/split/tile_check.py diff --git a/src/split/CMakeLists.txt b/src/split/CMakeLists.txt index 4891b03272..db753f4ea4 100644 --- a/src/split/CMakeLists.txt +++ b/src/split/CMakeLists.txt @@ -82,4 +82,25 @@ if(STRATA_BUILD_TESTS) target_compile_features(split_convert_dump PRIVATE cxx_std_17) set_target_properties(split_convert_dump PROPERTIES CUDA_ARCHITECTURES OFF) target_link_libraries(split_convert_dump PRIVATE Threads::Threads) + # the weight tiles of the prompt kernel run on a GPU against the file (tests/split/tile_check.py reads its output); not a ctest + add_executable(split_moe_tile_test ${_sp}/tools/moe_tile_test.cu ${_sp}/src/gguf.cpp) + target_include_directories(split_moe_tile_test PRIVATE ${_sp}/src ${_sp}/tools ${STRATA_GGML_DIR}/ggml/src/ggml-cuda ${STRATA_GGML_DIR}/ggml/src + ${STRATA_GGML_DIR}/ggml/include) + target_compile_definitions(split_moe_tile_test PRIVATE FNX_NCARD=${_n0} FNX_ARCH=${STRATA_SPLIT_ARCH} FNX_27B=0) + target_compile_options(split_moe_tile_test PRIVATE $<$:--use_fast_math --expt-relaxed-constexpr -Wno-deprecated-gpu-targets>) + set_target_properties(split_moe_tile_test PROPERTIES CUDA_ARCHITECTURES "${STRATA_SPLIT_ARCH}-real" CUDA_STANDARD 17 CXX_STANDARD 17) + target_link_libraries(split_moe_tile_test PRIVATE Threads::Threads) + # fnx_run: sFNX's test driver (teacher-forced logits to an .lgr file, prompt/decode checks), the same engine objects with its own main + set(_sp_run_src ${_sp_engine}) + list(REMOVE_ITEM _sp_run_src ${_sp}/tools/sfnx.cpp) + add_executable(split_fnx_run ${_sp_run_src} ${_sp}/tools/fnx_run.cpp ${_sp_kparts}) + set_source_files_properties(${_sp}/tools/fnx_run.cpp PROPERTIES LANGUAGE CUDA) + target_include_directories(split_fnx_run PRIVATE ${_sp}/src ${_sp}/tools ${STRATA_GGML_DIR}/ggml/src/ggml-cuda ${STRATA_GGML_DIR}/ggml/src + ${STRATA_GGML_DIR}/ggml/include) + target_compile_definitions(split_fnx_run PRIVATE FNX_NCARD=${_n0} FNX_ARCH=${STRATA_SPLIT_ARCH} FNX_27B=0 FNX_HOSTRING=1 FNX_DIR="${_sp}") + target_compile_options(split_fnx_run PRIVATE $<$:--use_fast_math --expt-relaxed-constexpr -Wno-deprecated-gpu-targets>) + set_target_properties(split_fnx_run PROPERTIES CUDA_ARCHITECTURES "${STRATA_SPLIT_ARCH}-real" CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON CXX_STANDARD 17) + find_package(CUDAToolkit REQUIRED) + target_link_libraries(split_fnx_run PRIVATE CUDA::cublas CUDA::cuda_driver Threads::Threads) + set_target_properties(split_fnx_run PROPERTIES CUDA_RUNTIME_LIBRARY Shared) endif() diff --git a/src/split/tools/batch_check.hpp b/src/split/tools/batch_check.hpp new file mode 100644 index 0000000000..66dbd3fec3 --- /dev/null +++ b/src/split/tools/batch_check.hpp @@ -0,0 +1,173 @@ +// Batched windows (Engine::step) against one sequence at a time: each conversation's GEN greedy tokens alone (one row a +// window, no drafts), then the conversations on lanes decoding together, one row per lane a window; each lane's tokens +// must equal its conversation's alone. For 1, 2, 3 and 6 lanes (prompts reused round-robin): the window time and the +// total tokens a second. With FNX_BATCH_DRAFTS (lookup or 1) the same again with drafts in the batched windows +// (BatchDecoder: several rows a lane, each lane cut back to what it accepts, lanes leaving as they finish), greedy and +// equal to alone; then a sampled run at 3 lanes, which must only run (its tokens differ by chance). bin/batch_test and +// the lab's "batch" command. +#pragma once +#include +#include +#include +#include +#include + +#include "../src/batch.hpp" +#include "../src/engine.hpp" +#include "../src/session.hpp" + +inline int batch_check(const fnx::Model& m, fnx::Engine& e, const fnx::Mtp& mtp, int gen, const std::vector>& prompts) { + e.mtp_attach(mtp); + const std::vector eos{248044, 248046}; + fnx::Sampling greedy; + // alone: one row a window + std::vector> solo(prompts.size()); + { + fnx::Session s(e, 4, 7, eos); + s.speculate = false; + for (size_t i = 0; i < prompts.size(); ++i) { + e.reset(); + fnx::GenStats st; + s.read(prompts[i], st); + s.generate(gen, greedy, [&](int t) { solo[i].push_back(t); }, nullptr, st); + } + } + e.reset(); + std::vector lanes{0}; + while ((int) lanes.size() < 6) lanes.push_back(e.add_lane()); + // a lane's tokens against its conversation's alone: every token of the reference up to its first end-of-reply (past + // it the plain batch keeps decoding), none missing: a lane that ends early or emits nothing does not match + auto matches = [&](const std::vector& got, const std::vector& ref) { + size_t want = ref.size(); + for (size_t j = 0; j < ref.size(); ++j) + if (ref[j] == 248044 || ref[j] == 248046) { + want = j + 1; + break; + } + return got.size() >= want && std::equal(ref.begin(), ref.begin() + (long) want, got.begin()); + }; + bool ok = true; + for (int n : {1, 2, 3, 6}) { + std::vector use(lanes.begin(), lanes.begin() + n), x(n); + std::vector> got(n); + for (int r = 0; r < n; ++r) { + e.use_lane(use[r]); + e.reset(); + fnx::Session s(e, 4, 7, eos, 248045, 0, use[r]); + fnx::GenStats st; + s.read(prompts[r % prompts.size()], st); + x[r] = prompts[r % prompts.size()].back(); + } + double ms = 0; + int windows = 0; + while ((int) got[0].size() < gen) { + const auto t0 = std::chrono::steady_clock::now(); + const std::vector o = e.step(use, x); + ms += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + ++windows; + for (int r = 0; r < n; ++r) { + got[r].push_back(o[r]); + x[r] = o[r]; + } + } + int same = 0; + for (int r = 0; r < n; ++r) same += matches(got[r], solo[r % prompts.size()]); + std::printf("%d lanes: %d windows, %.2f ms a window (first one captures its graph), %.1f tokens/s in all; %d of %d lanes match alone\n", + n, windows, ms / windows, n * windows * 1000.0 / ms, same, n); + ok = ok && same == n; + } + std::printf("%s\n", ok ? "batched windows give each lane its tokens alone" : "MISMATCH"); + if (fnx::batch_drafts() == fnx::BatchDrafts::off) return ok ? 0 : 1; + bool dok = true; + fnx::BatchDecoder dec(e, 4, 15, eos, fnx::batch_drafts()); + // the lanes on their prompts, each lane's next row its prompt's last token + auto start = [&](int n, const fnx::Sampling& s, std::vector& bl) { + bl.assign((size_t) n, fnx::BatchLane{}); + for (int r = 0; r < n; ++r) { + e.use_lane(lanes[(size_t) r]); + e.reset(); + fnx::Session sess(e, 4, 7, eos, 248045, 0, lanes[(size_t) r]); + fnx::GenStats st; + const std::vector& p = prompts[r % prompts.size()]; + sess.read(p, st); + bl[(size_t) r].start(lanes[(size_t) r], s, std::mt19937_64(1000 + r), p); + } + }; + // windows until every lane has gen tokens or ended its reply: the tokens per lane, windows, rows, ms + auto run = [&](std::vector& bl, std::vector>& got, int& windows, int& rows, double& ms) { + const int n = (int) bl.size(); + got.assign((size_t) n, {}); + std::vector ended((size_t) n, false); + windows = rows = 0; + ms = 0; + for (;;) { + std::vector ls; + std::vector idx, limit; + for (int r = 0; r < n; ++r) + if (!ended[(size_t) r] && (int) got[(size_t) r].size() < gen) { + ls.push_back(&bl[(size_t) r]); + idx.push_back(r); + limit.push_back(gen - (int) got[(size_t) r].size()); + } + if (ls.empty()) break; + fnx::BatchDecoder::fit(ls); + const auto t0 = std::chrono::steady_clock::now(); + const auto out = dec.window(ls, limit, [&](int i, int t) { got[(size_t) idx[(size_t) i]].push_back(t); }); + ms += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + ++windows; + rows += dec.last_rows; + for (size_t i = 0; i < out.size(); ++i) + if (out[i].eos) ended[(size_t) idx[i]] = true; + } + }; + const char* mode = fnx::batch_drafts() == fnx::BatchDrafts::lookup ? "lookup drafts" : "lookup drafts and the draft layer's chain"; + for (int n : {1, 2, 3, 6}) { + std::vector bl; + start(n, greedy, bl); + std::vector> got; + int windows = 0, rows = 0; + double ms = 0; + run(bl, got, windows, rows, ms); + int same = 0; + size_t tokens = 0; + long offered = 0, accepted = 0; + for (int r = 0; r < n; ++r) { + same += matches(got[(size_t) r], solo[r % prompts.size()]); + tokens += got[(size_t) r].size(); + offered += bl[(size_t) r].offered; + accepted += bl[(size_t) r].accepted; + } + std::printf("%d lanes with %s: %d windows, %.1f rows and %.2f ms a window, %.1f tokens/s in all, drafts %ld of %ld; %d of %d " + "lanes match alone\n", + n, mode, windows, (double) rows / windows, ms / windows, tokens * 1000.0 / ms, accepted, offered, same, n); + dok = dok && same == n; + } + { // sampled (prod's values): it must run; nothing to compare + fnx::Sampling s; + s.temperature = 0.6f; + s.top_p = 0.95f; + s.pen_present = 1.0f; + std::vector bl; + start(3, s, bl); + std::vector> got; + int windows = 0, rows = 0; + double ms = 0; + run(bl, got, windows, rows, ms); + bool in_vocab = true; + size_t tokens = 0; + for (const auto& g : got) { + tokens += g.size(); + for (int t : g) in_vocab = in_vocab && t >= 0 && t < m.vocab; + } + std::printf("3 lanes sampled (temperature 0.6, top_p 0.95, presence 1.0): %d windows, %.1f rows a window, %.1f tokens/s in all%s\n", + windows, (double) rows / windows, tokens * 1000.0 / ms, in_vocab ? "" : ": A TOKEN OUT OF THE VOCABULARY"); + dok = dok && in_vocab; + } + for (int i : lanes) { + e.use_lane(i); + e.reset(); + } + std::printf("%s\n", dok ? "batched windows with drafts give each lane its tokens alone" : "MISMATCH with drafts"); + ok = ok && dok; + return ok ? 0 : 1; +} diff --git a/src/split/tools/fnx_run.cpp b/src/split/tools/fnx_run.cpp new file mode 100644 index 0000000000..54af935dcc --- /dev/null +++ b/src/split/tools/fnx_run.cpp @@ -0,0 +1,1375 @@ +// fnx_run MODEL.gguf check REF.bin OUT.bin [W] the reference prompt in windows of W rows, per-layer dumps to OUT.bin +// fnx_run MODEL.gguf gen REF.bin N greedy: the reference prompt, then N tokens one row per window +// fnx_run MODEL.gguf rows REF.bin T N N windows of T rows (the reference tokens, cycled): time per window +// fnx_run MODEL.gguf bench REF.bin T N N verify windows of T rows, each committing one: wall and GPU time +// fnx_run MODEL.gguf bench_step REF.bin L N C [step] verify windows of 1..MAXT rows, then batched windows of 1..L lanes, +// at a context of C tokens: medians of N windows each +// fnx_run MODEL.gguf mtp RT_DIR REF.bin N K [VOCAB [LK]] greedy decoding with the draft layer (data/mtp-rt), K drafts +// per round (VOCAB: the draft vocabulary, default RT_DIR's; LK lookup drafts) +// fnx_run MODEL.gguf spec REF.bin GEN.txt K [BAD%] speculative windows of K perfect drafts from gen's output, BAD% of +// windows with one draft corrupted: the output must be gen's +// fnx_run MODEL.gguf logits PROMPT.bin CONT.lgr T OUT.lgr the prompt, then CONT.lgr's steps in windows of T: top-64s +// fnx_run MODEL.gguf exact|read|decode|batch|compare ... the lab's standard checks (lab_check below) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../src/engine.hpp" +#include "batch_check.hpp" +#include "ref_tokens.hpp" +#include "../src/env.hpp" + +// the draft layer's runtime: Flash-Next's files, or the 27B's own layer in its GGUF (Mtp's "nextn") +#if FNX_27B +#define MTP_RT "nextn" +#else +#define MTP_RT FNX_DIR "/data/mtp-rt" +#endif + +// timings: the middle value, and the p-quantile at index p * (n - 1) +static double pct(std::vector v, double p) { + if (v.empty()) throw std::runtime_error("pct: no values"); + std::sort(v.begin(), v.end()); + return v[(size_t) (p * (v.size() - 1))]; +} +static double median(std::vector v) { + if (v.empty()) throw std::runtime_error("median: no values"); + std::sort(v.begin(), v.end()); + return v[v.size() / 2]; +} + +// the reference prompt (through the prompt path when prefill, else in windows of MAXT), then the continuation of +// REF.lgr in windows of T: the top 64 logits of each step to OUT.lgr (fnx_logref's format) +static int run_logits(fnx::Model& m, fnx::Engine& e, const char* prompt_path, const char* ref_path, int T, const char* out_path, + bool prefill) { + const std::vector prompt = ref_tokens(prompt_path); + if (T < 1 || T > fnx::MAXT) { std::fprintf(stderr, "T: 1..%d\n", fnx::MAXT); return 2; } + // the continuation's tokens (fnx_logref's records) + std::vector cont; + { + std::FILE* f = std::fopen(ref_path, "rb"); + char magic[4]; + uint32_t k = 0; + int32_t np = 0, ns = 0; + if (!f || std::fread(magic, 1, 4, f) != 4 || std::memcmp(magic, "LGR1", 4) || std::fread(&k, 4, 1, f) != 1 || + std::fread(&np, 4, 1, f) != 1) { std::fprintf(stderr, "%s: not an .lgr file\n", ref_path); return 1; } + std::vector pr((size_t) np); + if (std::fread(pr.data(), 4, pr.size(), f) != pr.size() || std::fread(&ns, 4, 1, f) != 1) return 1; + if (std::vector(pr.begin(), pr.end()) != prompt) { std::fprintf(stderr, "the .lgr file has another prompt\n"); return 1; } + for (int i = 0; i < ns; ++i) { + int32_t tok; + if (std::fread(&tok, 4, 1, f) != 1) return 1; + cont.push_back(tok); + std::fseek(f, 4 + (long) k * 8, SEEK_CUR); + } + std::fclose(f); + } + constexpr uint32_t K = 64; + std::FILE* out = std::fopen(out_path, "wb"); + if (!out) { std::perror(out_path); return 1; } + const int32_t np = (int32_t) prompt.size(), ns = (int32_t) cont.size(); + std::fwrite("LGR1", 1, 4, out); + std::fwrite(&K, 4, 1, out); + std::fwrite(&np, 4, 1, out); + for (int t : prompt) { + const int32_t v = t; + std::fwrite(&v, 4, 1, out); + } + std::fwrite(&ns, 4, 1, out); + int written = 0; + auto put_rows = [&](const std::vector& lg, int vocab, int r0, int r1) { + for (int r = r0; r < r1 && written < ns; ++r, ++written) { + const float* row = lg.data() + (size_t) r * vocab; + float mx = -INFINITY; + for (int i = 0; i < vocab; ++i) mx = std::max(mx, row[i]); + double s = 0; + for (int i = 0; i < vocab; ++i) s += std::exp((double) row[i] - mx); + const float lse = (float) (mx + std::log(s)); + std::vector idx((size_t) vocab); + std::iota(idx.begin(), idx.end(), 0); + std::partial_sort(idx.begin(), idx.begin() + K, idx.end(), + [&](int a, int b) { return row[a] > row[b] || (row[a] == row[b] && a < b); }); + const int32_t taken = cont[(size_t) written]; + std::fwrite(&taken, 4, 1, out); + std::fwrite(&lse, 4, 1, out); + for (uint32_t k = 0; k < K; ++k) { + const int32_t id = idx[k]; + std::fwrite(&id, 4, 1, out); + std::fwrite(&row[id], 4, 1, out); + } + } + }; + const int vocab = m.cards[fnx::NCARD - 1].v1; + // FNX_IMAGES=FILE.sve (img_logref's): each run of image-pad tokens takes the file's next picture (its cells get + // ids of their own, its rows and grid go to set_images) + std::vector feed = prompt; + std::vector img_rows; + std::vector imgs; + if (const char* sv = std::getenv("FNX_IMAGES")) { + std::FILE* f = std::fopen(sv, "rb"); + if (!f) { std::perror(sv); return 1; } + std::vector> recs; // n, nx, ny, first row + int32_t h[5]; + while (std::fread(h, 4, 5, f) == 5) { + if (h[0] != 0x31455653 || h[4] != fnx::N) { std::fprintf(stderr, "%s: not strata-vision records of width %d\n", sv, fnx::N); return 1; } + const size_t off = img_rows.size(); + img_rows.resize(off + (size_t) h[1] * fnx::N); + if (std::fread(img_rows.data() + off, 4, (size_t) h[1] * fnx::N, f) != (size_t) h[1] * fnx::N) return 1; + recs.push_back({h[1], h[2], h[3], (int) (off / fnx::N)}); + } + std::fclose(f); + size_t k = 0; + for (size_t i = 0; i < feed.size();) { + if (feed[i] != (int) m.ple_image) { ++i; continue; } + if (k >= recs.size()) { std::fprintf(stderr, "more images in the prompt than in %s\n", sv); return 1; } + const auto& r = recs[k]; + for (int j = 0; j < r[0]; ++j) feed[i + j] = fnx::Engine::IMAGE_TOK + (int) k * 65536 + j; + imgs.push_back(fnx::Engine::Image{(int) i, r[0], r[1], r[2], img_rows.data() + (size_t) r[3] * fnx::N}); + i += r[0]; + ++k; + } + e.set_images(imgs); + std::fprintf(stderr, "logits: %zu image(s)\n", imgs.size()); + } + // the prompt: its last window's last row is step 0. FNX_PREFILL=1: all but its last token through the batched path + if (prefill) { + const auto t0 = std::chrono::steady_clock::now(); + e.prefill(std::vector(feed.begin(), feed.end() - 1)); + const double s = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + std::fprintf(stderr, "prefill: %zu tokens in %.2f s (%.0f tok/s)\n", feed.size() - 1, s, (feed.size() - 1) / s); + e.window({feed.back()}); + put_rows(e.last_logits(1), vocab, 0, 1); + } else + for (size_t i = 0; i < feed.size(); i += fnx::MAXT) { + std::vector w(feed.begin() + i, feed.begin() + std::min(feed.size(), i + fnx::MAXT)); + e.window(w); + if (i + w.size() == feed.size()) put_rows(e.last_logits((int) w.size()), vocab, (int) w.size() - 1, (int) w.size()); + } + // the continuation in windows of T: row r of a window starting at step j gives step j + r + 1 + for (int j = 0; j + 1 < ns; j += T) { + std::vector w(cont.begin() + j, cont.begin() + std::min(ns - 1, j + T)); + e.window(w); + put_rows(e.last_logits((int) w.size()), vocab, 0, (int) w.size()); + } + if (std::ferror(out)) { + std::fclose(out); + std::fprintf(stderr, "logits: %s: a write failed\n", out_path); + return 1; + } + if (std::fclose(out) != 0) { + std::fprintf(stderr, "logits: %s: close failed (a buffered write did not reach the disk)\n", out_path); + return 1; + } + std::fprintf(stderr, "logits: %d prompt tokens, %d steps in windows of %d\n", np, written, T); + return 0; +} + +// ---------------------------------------------------------------- the lab's standard checks (fixed inputs, run from fnx/) +// exact [NAME] ref/long64.bin (62,794 tokens), code1 and edit1 each through the prompt path, then their llama.cpp +// continuation steps in windows of 5: the logits to LAB/MODEL-NAME[-PROMPT].lgr (default "try"), +// compared with llama.cpp CUDA's on that model (see below) and, byte for byte and by KL, with +// LAB/MODEL-base[-PROMPT].lgr; "exact base" writes the baselines themselves +// read N [N...] the first N tokens of ref/long64.bin through the prompt path on a fresh engine (after warm_graphs, as +// sfnx starts): the read's time and tok/s +// LAB is FNX_LAB_DIR or /tmp/fnx-lab-UID (tools/lab.sh's directory). +struct Lgr { + uint32_t k = 0; + std::vector prompt; + struct Step { + int32_t tok; + float lse; + std::vector id; + std::vector v; + }; + std::vector steps; +}; +static bool load_lgr(const std::string& path, Lgr& g) { + std::FILE* f = std::fopen(path.c_str(), "rb"); + if (!f) return false; + char magic[4]; + int32_t np = 0, ns = 0; + bool ok = std::fread(magic, 1, 4, f) == 4 && !std::memcmp(magic, "LGR1", 4) && std::fread(&g.k, 4, 1, f) == 1 && + std::fread(&np, 4, 1, f) == 1; + if (ok) { + g.prompt.resize((size_t) np); + ok = std::fread(g.prompt.data(), 4, g.prompt.size(), f) == g.prompt.size() && std::fread(&ns, 4, 1, f) == 1; + } + for (int i = 0; ok && i < ns; ++i) { + Lgr::Step s; + s.id.resize(g.k); + s.v.resize(g.k); + ok = std::fread(&s.tok, 4, 1, f) == 1 && std::fread(&s.lse, 4, 1, f) == 1; + for (uint32_t j = 0; ok && j < g.k; ++j) ok = std::fread(&s.id[j], 4, 1, f) == 1 && std::fread(&s.v[j], 4, 1, f) == 1; + g.steps.push_back(std::move(s)); + } + std::fclose(f); + if (!ok) throw std::runtime_error(path + ": a short or malformed .lgr file"); + return true; +} +// ref/lgrcmp.py's measures: top-1 agreement, the agreeing run from the start, KL(ref || other) over the union of both +// top-Ks (a token outside a side's top-K gets its K-th logit), the top-10 overlap +struct LgrCmp { + int agree = 0, run = 0; + size_t n = 0; + double kl_mean = 0, kl_median = 0, kl_p99 = 0, kl_max = 0, top10 = 0; + double top1_pct() const { return 100.0 * agree / (double) n; } + std::string str() const { + char buf[256]; + std::snprintf(buf, sizeof buf, "top-1 %d/%zu (first %d in a row), KL mean %.2e median %.2e p99 %.2e max %.2e, top-10 overlap %.2f", + agree, n, run, kl_mean, kl_median, kl_p99, kl_max, top10); + return buf; + } +}; +static LgrCmp lgr_compare(const Lgr& r, const Lgr& o) { + if (r.prompt != o.prompt) throw std::runtime_error("lgr_compare: different prompts"); + const size_t n = std::min(r.steps.size(), o.steps.size()); + if (n == 0) throw std::runtime_error("lgr_compare: no steps"); + int agree = 0, run = 0; + bool open = true; + double ov = 0; + std::vector kls; + for (size_t i = 0; i < n; ++i) { + const Lgr::Step &a = r.steps[i], &b = o.steps[i]; + if (a.tok != b.tok) throw std::runtime_error("lgr_compare: step " + std::to_string(i) + " took different tokens"); + if (a.id[0] == b.id[0]) { + ++agree; + run += open; + } else { + open = false; + } + auto logit = [](const Lgr::Step& s, int t) { + for (size_t j = 0; j < s.id.size(); ++j) + if (s.id[j] == t) return s.v[j]; + return s.v.back(); + }; + std::vector u(a.id); + u.insert(u.end(), b.id.begin(), b.id.end()); + std::sort(u.begin(), u.end()); + u.erase(std::unique(u.begin(), u.end()), u.end()); + double kl = 0; + for (int t : u) { + const double p = std::exp((double) logit(a, t) - a.lse), q = std::exp((double) logit(b, t) - b.lse); + if (p > 0 && q > 0) kl += p * std::log(p / q); + } + kls.push_back(std::max(kl, 0.0)); + int o10 = 0; + for (int x = 0; x < 10; ++x) + for (int y = 0; y < 10; ++y) o10 += a.id[x] == b.id[y]; + ov += o10; + } + std::vector sk(kls); + std::sort(sk.begin(), sk.end()); + LgrCmp c; + c.agree = agree, c.run = run, c.n = n; + c.kl_mean = std::accumulate(kls.begin(), kls.end(), 0.0) / n, c.kl_median = sk[n / 2]; + c.kl_p99 = sk[std::min(n - 1, (size_t) (0.99 * n))], c.kl_max = sk.back(), c.top10 = ov / n; + return c; +} +static bool same_bytes(const std::string& a, const std::string& b) { + std::ifstream fa(a, std::ios::binary), fb(b, std::ios::binary); + if (!fa || !fb) return false; + const std::string sa(std::istreambuf_iterator(fa), {}), sb(std::istreambuf_iterator(fb), {}); + return !sa.empty() && sa == sb; +} +static std::string lab_dir() { + if (const char* d = std::getenv("FNX_LAB_DIR")) return d; + return "/tmp/fnx-lab-" + std::to_string(getuid()); +} + +// The exactness bar (README, "Exactness"): llama.cpp's CPU backend against its CUDA one, teacher-forced on the same +// tokens, for code1, edit1 and the picture; for long64, llama.cpp's own q8_0 K/V cache against its f16 one, since +// summation order alone moves long64's KL between 1.8e-3 and 4.3e-3. The Q8_0 model is held to the same bar (its +// references are llama.cpp's CPU backend on Q8_0). A run passes with KL mean <= KL_SLACK x the bar's and top-1 at most +// TOP1_SLACK points under the bar's: sFNX's fp16 ring sums put Q8_0's code1 at 1.10x, while the one precision loss +// caught so far (fast-math decays in the recurrent core) put code1 at 1.44x. The picture (ref/img/sphinx, 200 steps): +// llama.cpp's CPU backend 98.50% / 6.38e-3; sFNX 99.00% / 5.96e-3. +struct Bar { + const char* prompt; + double top1_pct, kl_mean, kl_slack; +}; +constexpr double TOP1_SLACK = 1.5; +#if FNX_27B +// the 27B's (make FNX_MODEL=27b), on Qwen3.8-27B Q8_0 (docs/verification.md, "The 27B"): the widest of llama.cpp's own +// spreads, each teacher-forced on its CUDA run's tokens (the file the check compares against, +// ref/lgr/llama_cuda__.lgr). Its CPU backend against CUDA (llama_cpu_*: code1 8.95e-5, edit1 1.48e-7, +// the picture 99.50% / 4.69e-4), and its CUDA with the int8 products of quantized activations off, cuBLAS for every +// product (ref/llama_cublas_only.patch, llama_cublas_*: code1 1.25e-4, edit1 1.23e-7, the picture 99.00% / 8.91e-4, +// long64 1.04e-4); long64 its q8_0 K/V against its f16 K/V (2.08e-4), as Flash-Next's. Top-1 the CPU backend's (the +// highest), KL the widest; the slack on top is Flash-Next's, for sFNX's own summation orders +constexpr Bar BARS[] = { + {"code1", 100.00, 1.25e-4, 1.25}, + {"edit1", 100.00, 1.48e-7, 1.25}, + {"picture", 99.50, 8.91e-4, 1.25}, + {"long64", 99.50, 2.08e-4, 1.0}, +}; +#else +constexpr Bar BARS[] = { + {"code1", 98.33, 4.85e-4, 1.25}, + {"edit1", 100.00, 4.12e-6, 1.25}, + {"picture", 98.50, 6.38e-3, 1.25}, + {"long64", 97.50, 4.98e-3, 1.0}, +}; +#endif +// empty when c is within prompt's bar, else what is outside it +static std::string breach(const std::string& prompt, const LgrCmp& c) { + for (const Bar& b : BARS) { + if (prompt != b.prompt) continue; + std::string why; + char buf[160]; + if (c.kl_mean > b.kl_mean * b.kl_slack) { + std::snprintf(buf, sizeof buf, "KL mean %.2e over %.2e (%.2fx the bar's %.2e)", c.kl_mean, b.kl_mean * b.kl_slack, b.kl_slack, b.kl_mean); + why = buf; + } + if (c.top1_pct() < b.top1_pct - TOP1_SLACK) { + std::snprintf(buf, sizeof buf, "top-1 %.2f%% under %.2f%% (the bar's %.2f%% less %.1f)", c.top1_pct(), b.top1_pct - TOP1_SLACK, + b.top1_pct, TOP1_SLACK); + why += (why.empty() ? "" : "; ") + std::string(buf); + } + return why; + } + return "no bar for " + prompt; +} + +// What made a run's logits, for the base's identity record (LAB/MODEL-base.id): the model file, the engine code that +// ran (the library or binary holding this function, as loaded: a library rebuilt but not reloaded is still the old +// one), the source tree's revision, and the FNX_ settings. A base is only compared against runs of the same model +// file; the rest is shown so a difference can be traced to its build. +static std::string file_line(const std::string& path) { + struct stat st; + if (stat(path.c_str(), &st) != 0) return path + " (cannot stat)"; + char buf[96]; + std::snprintf(buf, sizeof buf, " %lld bytes, modified %lld", (long long) st.st_size, (long long) st.st_mtime); + return path + buf; +} +static std::string loaded_code() { + Dl_info di; + if (!dladdr((void*) &file_line, &di) || !di.dli_fname) return "unknown (dladdr failed)"; + char real[PATH_MAX]; + const std::string path = realpath(di.dli_fname, real) ? real : di.dli_fname; + // the mapping's inode from /proc/self/maps: the file now at that path may be a newer build + const auto addr = (uintptr_t) di.dli_fbase; + std::ifstream maps("/proc/self/maps"); + for (std::string line; std::getline(maps, line);) { + uintptr_t lo = 0, hi = 0; + unsigned long long ino = 0; + char perms[8], dev[16]; + long long off = 0; + if (std::sscanf(line.c_str(), "%" SCNxPTR "-%" SCNxPTR " %7s %llx %15s %llu", &lo, &hi, perms, &off, dev, &ino) != 6) continue; + if (addr < lo || addr >= hi) continue; + struct stat st; + const bool same = stat(path.c_str(), &st) == 0 && (unsigned long long) st.st_ino == ino; + return same ? file_line(path) : path + " (inode " + std::to_string(ino) + ", replaced on disk since it was loaded)"; + } + return file_line(path); +} +// what the logits depend on besides the model and the code's sums: the card count it was built for, decode's ring and +// rope scaling (named only when on, so an unscaled build's line is the one its bases recorded) +static std::string build_line(int ncard, bool f32, double rope_scale = 0.0) { + std::string l = "build ncard " + std::to_string(ncard) + " ring " + (f32 ? "fp32" : "fp16-pairs"); + if (rope_scale) { + char s[64]; + std::snprintf(s, sizeof s, " rope yarn x%.9g", rope_scale); + l += s; + if (const char* o = std::getenv("FNX_YARN_ORIG_CTX")) l += std::string(" orig ") + o; + } + return l; +} +static std::string run_identity(const char* model) { + std::string id; + char real[PATH_MAX]; + id += "model " + file_line(realpath(model, real) ? real : model) + "\n"; + id += "code " + loaded_code() + "\n"; + std::string rev; + if (std::FILE* p = popen("git -C '" FNX_DIR "' describe --always --dirty --abbrev=12 2>&1", "r")) { + char buf[256]; + while (std::fgets(buf, sizeof buf, p)) rev += buf; + if (pclose(p) != 0) rev = "unknown (git: " + rev + ")"; + } + while (!rev.empty() && (rev.back() == '\n' || rev.back() == ' ')) rev.pop_back(); + id += "tree " FNX_DIR " " + rev + "\n"; + id += build_line(fnx::NCARD, fnx::ring_f32(), fnx::rope_scale()) + "\n"; + std::vector env; + for (char** e = environ; *e; ++e) + if (!std::strncmp(*e, "FNX_", 4)) env.emplace_back(*e); + std::sort(env.begin(), env.end()); + id += "env"; + for (const std::string& e : env) id += " " + e; + return id + "\n"; +} +// the line of an identity record that starts with key + " " +static std::string id_line(const std::string& id, const std::string& key) { + std::istringstream in(id); + for (std::string l; std::getline(in, l);) + if (l.compare(0, key.size() + 1, key + " ") == 0) return l; + return ""; +} +static void sync_cards() { + for (int c = 0; c < fnx::NCARD; ++c) { + if (cudaSetDevice(c) != cudaSuccess || cudaDeviceSynchronize() != cudaSuccess) + throw std::runtime_error(std::string("sync_cards: ") + cudaGetErrorString(cudaGetLastError())); + } +} +static int env_ctx(int need) { + const char* c = std::getenv("FNX_MAX_CTX"); + return std::max(c ? std::atoi(c) : 0, need); +} +static int lab_check(fnx::Model& m, int argc, char** argv) { + const std::string mode = argv[2]; + const char* long64 = "ref/long64.bin"; + const std::vector toks = ref_tokens(long64); + if (mode == "read") { + if (argc < 4) { std::fprintf(stderr, "read needs N [N...]\n"); return 2; } + for (int i = 3; i < argc; ++i) { + const int n = std::atoi(argv[i]); + if (n < 1 || n > (int) toks.size()) { std::fprintf(stderr, "read: N in 1..%zu\n", toks.size()); return 2; } + const auto te = std::chrono::steady_clock::now(); + fnx::Engine e(m, env_ctx(n + 1024), 1); + sync_cards(); + const auto tg = std::chrono::steady_clock::now(); + e.warm_graphs(); + sync_cards(); + const auto t0 = std::chrono::steady_clock::now(); + e.prefill(std::vector(toks.begin(), toks.begin() + n)); + sync_cards(); + const double s = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + std::printf("read %d tokens: %.0f ms, %.0f tok/s (engine made in %.1f s, its graphs warmed in %.1f s)\n", n, s * 1000, n / s, + std::chrono::duration(tg - te).count(), std::chrono::duration(t0 - tg).count()); + } + return 0; + } + if (mode == "decode") { + // one request alone as prod decodes it (Session: MTP drafts up to K=6 (their count follows acceptance), lookup drafts up to 15, prod's draft layer files), + // on an engine made like prod's (262,144 positions, 6 lanes): the code edit (ends at 636 tokens) and new code (N + // tokens, default 1,024), greedy, each once to warm up, then timed; then prose reasoning in the style of thinking + // (N tokens) sampled as prod samples (serve/sfnx.json), since thinking is decoded so: seeds 1-5 summed. SAMPLES: + // which of edit1, code1, prose2 to run (comma separated, default all), or code1s: new code sampled as prose2 is + const int n = argc > 3 ? std::atoi(argv[3]) : 1024, K = argc > 4 ? std::atoi(argv[4]) : 6, LK = argc > 5 ? std::atoi(argv[5]) : 15; + if (n < 1) { std::fprintf(stderr, "decode [N]: N >= 1\n"); return 2; } + const std::string samples = argc > 6 ? argv[6] : "edit1,code1,prose2"; + auto wanted = [&](const std::string& name) { return ("," + samples + ",").find("," + name + ",") != std::string::npos; }; + for (size_t a = 0, b; a <= samples.size(); a = b + 1) { + b = samples.find(',', a); + if (b == std::string::npos) b = samples.size(); + const std::string one = samples.substr(a, b - a); + if (one != "edit1" && one != "code1" && one != "prose2" && one != "code1s") { + std::fprintf(stderr, "decode SAMPLES: edit1, code1, prose2, code1s (comma separated), not '%s'\n", one.c_str()); + return 2; + } + } + const fnx::Mtp mtp(m, MTP_RT, FNX_DIR "/data/draft_vocab_en.bin"); + fnx::Engine e(m, env_ctx(262144), 6); + e.mtp_attach(mtp); + const std::vector eos{248044, 248046}; + fnx::Sampling greedy, served; + served.temperature = 0.6f, served.top_p = 0.95f, served.pen_present = 1.0f; + auto run_one = [&](const std::vector& prompt, const fnx::Sampling& smp) { + e.reset(); + fnx::Session s(e, K, LK, eos); + fnx::GenStats st; + s.read(prompt, st); + s.generate(n, smp, [](int) {}, nullptr, st); + return st; + }; + auto report = [](const std::string& p, const fnx::GenStats& st) { + std::printf("decode %s: %d tokens in %.0f ms, %.1f tok/s, %.2f tokens a round, %.2f ms a round (%d rounds, %d with lookup drafts; drafts %ld of %ld)\n", + p.c_str(), st.generated, st.decode_ms, st.generated * 1000.0 / st.decode_ms, (double) st.generated / st.rounds, + st.decode_ms / st.rounds, st.rounds, st.lookup_rounds, st.drafts_accepted, st.drafts_offered); + std::printf(" a round: verify %.2f ms (GPU %.2f, launch %.2f), drafts %.2f ms in %.1f calls (GPU %.2f), commit %.2f, " + "the session's own %.2f\n", + st.verify_ms / st.rounds, st.verify_gpu_ms / st.rounds, st.launch_ms / st.rounds, st.draft_ms / st.rounds, + (double) st.draft_calls / st.rounds, st.draft_gpu_ms / st.rounds, st.commit_ms / st.rounds, + (st.decode_ms - st.verify_ms - st.draft_ms - st.commit_ms) / st.rounds); + }; + bool warm = false; + for (const char* p : {"edit1", "code1"}) { + if (!wanted(p)) continue; + const std::vector prompt = ref_tokens((std::string("ref/") + p + ".bin").c_str()); + run_one(prompt, greedy); + warm = true; + report(p, run_one(prompt, greedy)); + } + for (const char* p : {"prose2", "code1s"}) { + if (!wanted(p)) continue; + const std::string file = std::string(p) == "code1s" ? "code1" : p; + const std::vector prompt = ref_tokens(("ref/" + file + ".bin").c_str()); + if (!warm) { // the graphs and the first request's costs, out of the timed runs + fnx::Sampling w = served; + w.seed = 0; + fnx::Session s(e, K, LK, eos); + fnx::GenStats st; + e.reset(); + s.read(prompt, st); + s.generate(64, w, [](int) {}, nullptr, st); + warm = true; + } + fnx::GenStats sum; + for (uint64_t seed = 1; seed <= 5; ++seed) { + served.seed = seed; + const fnx::GenStats st = run_one(prompt, served); + sum.generated += st.generated, sum.decode_ms += st.decode_ms, sum.rounds += st.rounds, sum.lookup_rounds += st.lookup_rounds; + sum.drafts_accepted += st.drafts_accepted, sum.drafts_offered += st.drafts_offered; + sum.verify_ms += st.verify_ms, sum.verify_gpu_ms += st.verify_gpu_ms, sum.launch_ms += st.launch_ms; + sum.draft_ms += st.draft_ms, sum.draft_gpu_ms += st.draft_gpu_ms, sum.commit_ms += st.commit_ms, sum.draft_calls += st.draft_calls; + } + report(std::string(p) + " (served sampling, seeds 1-5)", sum); + } + return 0; + } + if (mode == "cache2") { + // the conversation cache where a prompt shares much with what a lane holds (prompts made from long64's tokens, + // message boundaries where a chat template puts them): + // A. X and Y share a 9k system prompt (75% of each) and alternate on one lane: X's next turn reuses all of X + // (Y's read parks X, though it shares more than half) + // B. a 17k system prompt changed at token 16,000: the prompt reuses 12,288 (the first message's last checkpoint + // before the change) instead of nothing + // each cached read against the same prompt read from scratch as cache_test compares them: the first token's top-64 + // (KL(fresh || cached), at most 1.5e-3, the worst measured, and the same top-1), then 16 greedy tokens a row at a + // time (printed, not judged: they may part at a near-tie); exit 1 when a reuse is not what the cache promises or a + // first token is off + constexpr int TURN = 248045, SYS = 8678, USER = 872; + std::vector fill; + for (int t : toks) + if (t != TURN && t != 248044 && t != 248046) fill.push_back(t); + auto span = [&](size_t a, size_t n) { + if (a + n > fill.size()) throw std::runtime_error("cache2: long64 too short"); + return std::vector(fill.begin() + (long) a, fill.begin() + (long) (a + n)); + }; + auto cat = [](std::vector a, const std::vector& b) { + a.insert(a.end(), b.begin(), b.end()); + return a; + }; + auto msg = [&](int role, const std::vector& body) { return cat({TURN, role}, body); }; + const fnx::Mtp mtp(m, MTP_RT, FNX_DIR "/data/draft_vocab_en.bin"); + fnx::Engine e(m, env_ctx(65536), 1); + e.mtp_attach(mtp); + const std::vector eos{248044, 248046}; + int fails = 0; + struct Res { + std::vector> top; + std::vector gen; + }; + // the prompt read, then its last token's window (top-64) and greedy tokens one row a window + auto first16 = [&](fnx::Session& s, const std::vector& p, int& reused) { + fnx::GenStats st; + s.read(p, st); + reused = st.reused; + Res r; + std::vector o = e.verify({p.back()}); + r.top = e.top_tokens(1, {})[0]; + e.commit(1); + r.gen.push_back(o[0]); + while (r.gen.size() < 16) { + o = e.verify({r.gen.back()}); + e.commit(1); + r.gen.push_back(o[0]); + } + return r; + }; + auto fresh16 = [&](const std::vector& p) { + e.reset(); + fnx::Session f(e, 6, 15, eos, TURN, 0, 0); + int r = 0; + return first16(f, p, r); + }; + auto judge = [&](const char* name, int reused, int want, const Res& got, const Res& ref) { + auto lse = [](const std::vector>& t) { + double mx = t[0].first, s = 0; + for (const auto& x : t) s += std::exp(x.first - mx); + return mx + std::log(s); + }; + const double la = lse(got.top), lb = lse(ref.top); + double kl = 0; + for (const auto& x : ref.top) { + double qa = got.top.back().first; + for (const auto& y : got.top) + if (y.second == x.second) qa = y.first; + kl += std::exp(x.first - lb) * ((x.first - lb) - (qa - la)); + } + int same = 0; + while (same < 16 && got.gen[(size_t) same] == ref.gen[(size_t) same]) ++same; + const bool top1 = got.top[0].second == ref.top[0].second, ok = reused == want && top1 && kl <= 1.5e-3; + std::printf("cache2 %s: reused %d (want %d), first token KL %.2e, top-1 %s, %d of 16 greedy tokens as from scratch: %s\n", name, + reused, want, kl, top1 ? "the same" : "DIFFERENT", same, ok ? "ok" : "FAIL"); + if (!ok) ++fails; + }; + { // A + e.reset(); + fnx::Session s(e, 6, 15, eos, TURN, (size_t) 32 << 30, 0); + const std::vector sys = msg(SYS, span(0, 9000)); + const std::vector X = cat(sys, msg(USER, span(20000, 3000))), Y = cat(sys, msg(USER, span(30000, 3000))); + int r = 0; + first16(s, X, r); + const std::vector hx = e.lane_history(0); // X as the lane holds it: its prompt and the reply kept + first16(s, Y, r); + const std::vector X2 = cat(hx, msg(USER, span(40000, 500))); + int reused = 0; + const Res got = first16(s, X2, reused); + judge("A (X's next turn after Y on its lane)", reused, (int) hx.size(), got, fresh16(X2)); + } + { // B + e.reset(); + fnx::Session s(e, 6, 15, eos, TURN, (size_t) 32 << 30, 0); + const std::vector sys1 = msg(SYS, span(0, 17000)); + std::vector sys2 = sys1; + sys2[16000] = sys2[16000] == fill[1] ? fill[2] : fill[1]; + const std::vector P1 = cat(sys1, msg(USER, span(20000, 2000))), P2 = cat(sys2, msg(USER, span(20000, 2000))); + int r = 0; + first16(s, P1, r); + first16(s, msg(USER, span(30000, 3000)), r); // another conversation: P1 parked + int reused = 0; + const Res got = first16(s, P2, reused); + judge("B (the system prompt changed at 16,000)", reused, 12288, got, fresh16(P2)); + } + return fails ? 1 : 0; + } + if (mode == "bdecode") { + // LANES requests decoding together through batched windows with drafts (FNX_BATCH_DRAFTS lookup or 1; the drafts + // a lane: the plan's, or FNX_BATCH_FIXED), prod's sampling, seeds fixed: lanes take PROMPTS in turn (comma + // separated ref/ names, default prose2,code1), N tokens each (default 512); each lane's prompt read first, then + // windows until every lane is done. One warm-up run + const int nl = argc > 3 ? std::atoi(argv[3]) : 2, n = argc > 4 ? std::atoi(argv[4]) : 512; + if (nl < 1 || nl > 6 || n < 1) { std::fprintf(stderr, "bdecode [LANES 1..6] [N >= 1] [PROMPTS]\n"); return 2; } + const std::string names = argc > 5 ? argv[5] : "prose2,code1"; + if (fnx::batch_drafts() == fnx::BatchDrafts::off) { std::fprintf(stderr, "bdecode: set FNX_BATCH_DRAFTS (lookup or 1)\n"); return 2; } + const fnx::Mtp mtp(m, MTP_RT, FNX_DIR "/data/draft_vocab_en.bin"); + fnx::Engine e(m, env_ctx(262144), 6); + e.mtp_attach(mtp); + const std::vector eos{248044, 248046}; + std::vector lanes{0}; + while ((int) lanes.size() < nl) lanes.push_back(e.add_lane()); + std::vector> prompts; + for (size_t a = 0, b; a <= names.size(); a = b + 1) { + b = names.find(',', a); + if (b == std::string::npos) b = names.size(); + prompts.push_back(ref_tokens(("ref/" + names.substr(a, b - a) + ".bin").c_str())); + } + fnx::Sampling s; + s.temperature = 0.6f, s.top_p = 0.95f, s.pen_present = 1.0f; + fnx::BatchDecoder dec(e, 6, 15, eos, fnx::batch_drafts()); + const int seed0 = (int) fnx::env_int("FNX_BDECODE_SEED", 1000); // lane r's sampling seed: seed0 + r + for (int run = 0; run < 2; ++run) { + std::vector bl((size_t) nl); + for (int r = 0; r < nl; ++r) { + e.use_lane(lanes[(size_t) r]); + e.reset(); + fnx::Session sess(e, 6, 15, eos, 248045, 0, lanes[(size_t) r]); + fnx::GenStats st; + const std::vector& p = prompts[(size_t) r % prompts.size()]; + sess.read(p, st); + bl[(size_t) r].start(lanes[(size_t) r], s, std::mt19937_64(seed0 + r), p); + } + std::vector got((size_t) nl, 0); + std::vector ended((size_t) nl, false); + int windows = 0, rows = 0, full = 0, full_rows = 0; + long lane_windows = 0, full_tokens = 0; // the windows each lane was in, summed; the tokens of windows with every lane + double ms = 0, verify_ms = 0, full_ms = 0, full_verify = 0, full_draft = 0, full_capture = 0; + long full_calls = 0, full_captures = 0; + for (;;) { + std::vector ls; + std::vector idx, limit; + for (int r = 0; r < nl; ++r) + if (!ended[(size_t) r] && got[(size_t) r] < n) { + ls.push_back(&bl[(size_t) r]); + idx.push_back(r); + limit.push_back(n - got[(size_t) r]); + } + if (ls.empty()) break; + fnx::BatchDecoder::fit(ls); + long emitted = 0; + const auto out = dec.window(ls, limit, [&](int i, int) { ++got[(size_t) idx[(size_t) i]], ++emitted; }); + ms += dec.last_ms; + verify_ms += dec.last_verify_ms; + ++windows; + rows += dec.last_rows; + lane_windows += (long) ls.size(); + if ((int) ls.size() == nl) { + ++full, full_rows += dec.last_rows, full_tokens += emitted, full_ms += dec.last_ms; + full_verify += dec.last_verify_ms, full_draft += dec.last_draft_ms, full_calls += dec.last_calls; + if (e.last_capture_ms > 0) ++full_captures, full_capture += e.last_capture_ms; + } + for (size_t i = 0; i < out.size(); ++i) + if (out[i].eos) ended[(size_t) idx[i]] = true; + } + if (run == 0) continue; + long tokens = 0, offered = 0, accepted = 0; + for (int r = 0; r < nl; ++r) tokens += got[(size_t) r], offered += bl[(size_t) r].offered, accepted += bl[(size_t) r].accepted; + std::printf("bdecode %d lanes: every lane in: %.1f tok/s, %.2f rows and %.2f ms a window (%d windows); overall %ld tokens, " + "%.1f tok/s, %d windows, %.2f ms a window (verify %.2f), %.2f tokens a lane a window, drafts %ld of %ld\n", + nl, full ? full_tokens * 1000.0 / full_ms : 0.0, full ? (double) full_rows / full : 0.0, full ? full_ms / full : 0.0, + full, tokens, tokens * 1000.0 / ms, windows, ms / windows, verify_ms / windows, (double) tokens / lane_windows, + accepted, offered); + if (full) + std::printf("bdecode %d lanes: every lane in, a window: verify %.2f ms, drafting %.2f ms (%.2f draft-layer calls), the " + "rest %.2f ms; graph captures in %ld of %d windows, %.2f ms each\n", + nl, full_verify / full, full_draft / full, (double) full_calls / full, (full_ms - full_verify - full_draft) / full, + full_captures, full, full_captures ? full_capture / full_captures : 0.0); + } + return 0; + } + if (mode == "compare") { // two .lgr files (ref/lgrcmp.py's measures), the first as the reference + if (argc < 5) { std::fprintf(stderr, "compare REF.lgr OTHER.lgr\n"); return 2; } + Lgr a, b; + if (!load_lgr(argv[3], a) || !load_lgr(argv[4], b)) { std::fprintf(stderr, "compare: cannot open both files\n"); return 1; } + std::printf("%s vs %s: %s\n", argv[3], argv[4], lgr_compare(a, b).str().c_str()); + return 0; + } + if (mode == "batch") { + // tools/batch_check.sh's lanes: two long prompts (past 2,048 positions, so the QSA selection runs) and a short one + const int gen = argc > 3 ? std::atoi(argv[3]) : 64; + if (gen < 1) { std::fprintf(stderr, "batch [GEN]: GEN >= 1\n"); return 2; } + const fnx::Mtp mtp(m, MTP_RT, "data/draft_vocab_en.bin"); + fnx::Engine e(m, env_ctx(100000)); + return batch_check(m, e, mtp, gen, + {ref_tokens("ref/long2.bin"), ref_tokens("ref/code1.bin"), ref_tokens("ref/long2.bin")}); + } + // exact: the model's llama.cpp reference (FNX_EXACT_REF for long64, else by the model's name: Q4's from llama.cpp + // CUDA, Q8_0's from its CPU backend (tools/q8_exact.sh; code1 and edit1 only), any other model's + // ref/lgr/llama_cuda__.lgr, which has no bar), held to the bar above, and its own base + std::string stem = argv[1]; + stem = stem.substr(stem.rfind('/') + 1); + if (const size_t s = stem.find("-00001-of-"); s != std::string::npos) stem = stem.substr(0, s); + else if (stem.size() > 5 && stem.compare(stem.size() - 5, 5, ".gguf") == 0) stem.resize(stem.size() - 5); + // the prompts: long64 (62,794 tokens: long-context drift, where any summation reorder moves KL by ~2e-3), the + // README's code1 and edit1 (61 and 686 tokens: little room for chaos, so a real error shows plainly) and its + // picture (ref/img/sphinx: the logo, the encoder's rows from sphinx.sve; llama.cpp's reference made on Q4 + // only). code1 and edit1 also run in windows of 1, 2, 3, 11 and 16 rows, which must give the 5-row windows' logits + // byte for byte: decode verifies windows of 1..MAXT rows, so a kernel whose sums depend on the row count (or one + // that takes another path for small windows, as FNX_HC1) would move served output while every 5-row check passed. +#if FNX_27B // the 27B's references are its own, named by the model (Flash-Next's Q4 and Q8 files are not its) + const bool q4 = false, q8 = false; + const std::string pic_stem = "ref/img/sphinx_" + stem; +#else + const bool q4 = stem.find("UD-Q4_K_XL") != std::string::npos, q8 = stem.find("Q8_0") != std::string::npos; +#endif + const std::string name = argc > 3 ? argv[3] : "try", dir = lab_dir(); + const bool base_run = name == "base"; + // a base is written only from a run within the bar: its files go to MODEL-base-new*.lgr first and replace the + // base (with its identity record) only when every prompt passed + const std::string id_path = dir + "/" + stem + "-base.id", out_name = base_run ? "base-new" : name; + const std::string me = run_identity(argv[1]); + std::string base_id; + { + std::ifstream f(id_path); + base_id.assign(std::istreambuf_iterator(f), {}); + } + // a base made by another build (card count, ring) is neither compared with nor written over: its logits differ in + // their last bits by design, and a base written over would be lost to the build that owns it. A record from before + // build lines is three cards', its ring as its env set it + if (!base_id.empty()) { + std::string theirs = id_line(base_id, "build"); + if (theirs.empty()) theirs = build_line(3, id_line(base_id, "env").find(" FNX_RING_F32=1") != std::string::npos); + if (theirs != id_line(me, "build")) { + const char* rs = std::getenv("FNX_ROPE_SCALE"); + std::printf("exact: the base in %s is another build's (%s; this one: %s): give this build a lab directory of its own, " + "FNX_LAB_DIR=/tmp/fnx-lab-%u-%dcard%s%s\n", + dir.c_str(), theirs.c_str(), id_line(me, "build").c_str(), (unsigned) getuid(), fnx::NCARD, rs ? "-yarn" : "", + rs ? rs : ""); + return 1; + } + } + if (!base_run) { + if (base_id.empty()) + std::printf("exact: no base identity %s (a base from before identity records, or none): make one with `exact base`\n", + id_path.c_str()); + else if (id_line(base_id, "model") != id_line(me, "model")) + std::printf("exact: the base was made from another model file:\n base: %s\n now: %s\n make a new one with `exact base`\n", + id_line(base_id, "model").c_str(), id_line(me, "model").c_str()); + else { + std::printf("exact: base from %s\n %s\n", id_line(base_id, "tree").c_str(), id_line(base_id, "code").c_str()); + if (id_line(base_id, "env") != id_line(me, "env")) + std::printf(" (other settings: base %s; now %s)\n", id_line(base_id, "env").c_str(), id_line(me, "env").c_str()); + } + } + const bool base_usable = !base_id.empty() && id_line(base_id, "model") == id_line(me, "model"); + int rc = 0; + std::vector> made; // a base run's files: candidate, base + std::string verdicts; + auto fail = [&](const std::string& what) { + std::printf(" FAIL: %s\n", what.c_str()); + rc = 1; + }; + for (const char* p : {"long64", "code1", "edit1", "picture"}) { + const bool pic = std::string(p) == "picture", long64 = std::string(p) == "long64"; +#if !FNX_27B // the 27B has its own picture reference + if (pic && !q4) { + std::printf("exact %s picture: not run (llama.cpp's picture reference is Q4's only)\n", name.c_str()); + continue; + } +#endif + if (long64 && q8 && !std::getenv("FNX_EXACT_REF")) { + std::printf("exact %s long64: not run (no llama.cpp reference on Q8_0 at 62k; FNX_EXACT_REF=FILE.lgr gives one)\n", + name.c_str()); + continue; + } +#if FNX_27B + const std::string prompt = pic ? pic_stem + ".bin" : std::string("ref/") + p + ".bin", +#else + const std::string prompt = pic ? "ref/img/sphinx.bin" : std::string("ref/") + p + ".bin", +#endif + tag = long64 ? "" : std::string("-") + p; + // a scaled build is held to llama.cpp run with the same scaling (ref/fnx_logref and ref/img_logref read the same + // settings), else the comparison measures the rope change itself; the file names the scale, the trained length + // it scales from when set, and the model unless it is Q4's + const double scale = fnx::rope_scale(); + std::string scaled_env, yarn_tag; + if (scale) { + char s[64]; + std::snprintf(s, sizeof s, "%.9g", scale); + scaled_env = std::string("FNX_ROPE_SCALE=") + s + " "; + yarn_tag = std::string("llama_yarn_") + s; + if (const char* oc = std::getenv("FNX_YARN_ORIG_CTX")) { + scaled_env += std::string("FNX_YARN_ORIG_CTX=") + oc + " "; + yarn_tag += std::string("_orig") + oc; + } + if (!q4) yarn_tag += "_" + stem; + } + std::string llama_s = long64 && std::getenv("FNX_EXACT_REF") ? std::getenv("FNX_EXACT_REF") + : scale ? "ref/lgr/" + yarn_tag + "_" + p + ".lgr" +#if FNX_27B + : pic ? pic_stem + ".lgr" +#else + : pic ? "ref/img/sphinx.lgr" +#endif + : q4 ? "ref/lgr/llama_cuda_" + std::string(p) + ".lgr" + : q8 ? "ref/lgr/llama_cpu_q8w_" + std::string(p) + ".lgr" + : "ref/lgr/llama_cuda_" + stem + "_" + p + ".lgr"; + if (std::FILE* f = std::fopen(llama_s.c_str(), "rb")) std::fclose(f); + else { + if (pic) + std::fprintf(stderr, "exact: no llama.cpp reference %s for %s; make it with\n %sref/img_logref %s MMPROJ.gguf " + "ref/img/sphinx.png 'What does this picture show? Answer in two sentences.' 200 %s\n", + llama_s.c_str(), stem.c_str(), scaled_env.c_str(), argv[1], +#if FNX_27B + scale ? llama_s.substr(0, llama_s.size() - 4).c_str() : pic_stem.c_str()); +#else + scale ? llama_s.substr(0, llama_s.size() - 4).c_str() : "ref/img/sphinx"); +#endif + else + std::fprintf(stderr, "exact: no llama.cpp reference %s for %s; make it with\n %sref/fnx_logref %s %s %d %s\n", + llama_s.c_str(), stem.c_str(), scaled_env.c_str(), argv[1], prompt.c_str(), long64 ? 200 : 300, + llama_s.c_str()); + std::printf("exact %s %s: FAIL: no llama.cpp reference %s\n", name.c_str(), p, llama_s.c_str()); + rc = 1; + continue; + } + const int n_prompt = (int) ref_tokens(prompt.c_str()).size(); + // the logits of the prompt and the reference's steps in windows of T rows, on a fresh engine + auto logits = [&](int T, const std::string& out) { + fnx::Engine e(m, env_ctx(n_prompt + 1024), 1); +#if FNX_27B + if (pic) setenv("FNX_IMAGES", (pic_stem + ".sve").c_str(), 1); +#else + if (pic) setenv("FNX_IMAGES", "ref/img/sphinx.sve", 1); +#endif + const int r = run_logits(m, e, prompt.c_str(), llama_s.c_str(), T, out.c_str(), true); + if (pic) unsetenv("FNX_IMAGES"); + return r; + }; + const std::string out = dir + "/" + stem + "-" + out_name + tag + ".lgr", base = dir + "/" + stem + "-base" + tag + ".lgr"; + { + const auto t0 = std::chrono::steady_clock::now(); + if (const int r = logits(5, out)) return r; + std::printf("exact %s %s: logits in %.0f s to %s\n", name.c_str(), p, + std::chrono::duration(std::chrono::steady_clock::now() - t0).count(), out.c_str()); + } + Lgr ref, mine; + load_lgr(llama_s, ref); + load_lgr(out, mine); + const LgrCmp vs_llama = lgr_compare(ref, mine); + std::printf(" vs llama.cpp %s: %s\n", q8 ? "CPU" : "CUDA", vs_llama.str().c_str()); + if (!std::isfinite(vs_llama.kl_mean)) fail("KL is not a number: one side's logits are broken"); +#if !FNX_27B + else if (!q4 && !q8) fail("no documented bar for " + stem + ": the numbers above are not judged"); +#endif + else if (scale) { + // YaRN moves the model's own outputs (docs/verification.md, "Rope scaling"), and llama.cpp's backends part + // differently under it, so the bar is not held here: only a port that is plainly broken fails, at 10x the + // bar's KL or 5 points of top-1 under it. The byte-for-byte base comparison below still judges + std::printf(" scaled: measured against a scaled llama.cpp, not held to the bar\n"); + for (const Bar& b : BARS) + if (p == std::string(b.prompt) && (vs_llama.kl_mean > 10 * b.kl_mean || vs_llama.top1_pct() < b.top1_pct - 5)) + fail("far outside the bar for a scaled build (10x its KL or 5 points of top-1): a broken port, not YaRN's shift"); + } else if (const std::string why = breach(p, vs_llama); !why.empty()) fail("outside the exactness bar: " + why); + verdicts += std::string("llama.cpp ") + p + " " + vs_llama.str() + "\n"; + if (std::string(p) == "code1" || std::string(p) == "edit1") + for (int T : {1, 2, 3, 11, 16}) { + const std::string rows_out = dir + "/" + stem + "-" + out_name + tag + "-rows" + std::to_string(T) + ".lgr"; + if (const int r = logits(T, rows_out)) return r; + if (same_bytes(out, rows_out)) std::printf(" windows of %d: the 5-row windows' logits byte for byte\n", T); + else { + Lgr rows; + load_lgr(rows_out, rows); + fail("windows of " + std::to_string(T) + " give other logits than windows of 5: " + lgr_compare(mine, rows).str()); + } + } + if (base_run) { + made.emplace_back(out, base); + continue; + } + Lgr b; + if (!base_usable) fail("no base to compare with (see above)"); + else if (!load_lgr(base, b)) fail("no " + base + " (exact base writes it)"); + else if (same_bytes(base, out)) std::printf(" vs base: byte for byte identical\n"); + else fail("vs base: DIFFERENT: " + lgr_compare(b, mine).str()); + } + if (base_run) { + if (rc != 0 || made.empty()) { + std::printf("exact base: NOT written (%s); the base stays as it was, this run's files are %s/%s-base-new*.lgr\n", + made.empty() ? "nothing ran" : "a check failed", dir.c_str(), stem.c_str()); + return 1; + } + // the old identity goes first: a base half replaced has no identity, and runs refuse to compare with it + if (std::remove(id_path.c_str()) != 0 && errno != ENOENT) throw std::runtime_error("exact base: cannot remove " + id_path); + for (const auto& [cand, base] : made) + if (std::rename(cand.c_str(), base.c_str()) != 0) throw std::runtime_error("exact base: cannot move " + cand + " to " + base); + const std::string tmp = id_path + ".new"; + std::FILE* f = std::fopen(tmp.c_str(), "w"); + if (!f) throw std::runtime_error("exact base: cannot write " + tmp); + const std::string rec = me + verdicts; + const bool ok = std::fwrite(rec.data(), 1, rec.size(), f) == rec.size(); + if (std::fclose(f) != 0 || !ok || std::rename(tmp.c_str(), id_path.c_str()) != 0) + throw std::runtime_error("exact base: cannot write " + id_path); + std::printf("exact base: written for %zu prompt(s), identity in %s:\n%s", made.size(), id_path.c_str(), me.c_str()); + } + return rc; +} + +// one command on a loaded model, its arguments as fnx_run takes them (argv[1] the model's path, argv[2] the mode); +// bin/fnx_lab calls it from libfnx_lab.so for each command, around a model it keeps loaded +static bool lab_mode(const std::string& mode) { + return mode == "exact" || mode == "read" || mode == "batch" || mode == "compare" || mode == "decode" || mode == "bdecode" || + mode == "cache2"; +} +// a known mode with at least its first argument (each mode checks the rest); else the usage on stderr +static bool args_ok(int argc, char** argv) { + const std::string mode = argc >= 3 ? argv[2] : ""; + const bool plain = mode == "check" || mode == "gen" || mode == "rows" || mode == "bench" || mode == "bench_step" || mode == "mtp" || + mode == "spec" || mode == "logits"; + if (lab_mode(mode) || (plain && argc >= 4)) return true; + std::fputs("usage: fnx_run MODEL.gguf MODE ARGS...\n" + " check REF.bin OUT.bin [W] | gen REF.bin N | rows REF.bin T N | bench REF.bin T N | bench_step REF.bin L N C [step]\n" + " mtp RT_DIR REF.bin N K [VOCAB [LK]] | spec REF.bin GEN.txt K [BAD%] | logits PROMPT.bin CONT.lgr T OUT.lgr\n" + " exact [NAME] | read N [N...] | decode [N] [K] [LK] [SAMPLES] | bdecode [LANES] [N] [PROMPTS] | cache2 | batch [GEN] | compare REF.lgr OTHER.lgr\n", + stderr); + return false; +} + +extern "C" int fnx_run_cmd(fnx::Model* model, int argc, char** argv) { + if (!model || !args_ok(argc, argv)) return 2; + const std::string mode = argv[2]; + if (lab_mode(mode)) return lab_check(*model, argc, argv); + fnx::Model& m = *model; + + // FNX_MAX_CTX: the context the engine allocates for (default 4096); FNX_LANES: lanes the K/V pool has room for + std::optional mtp_mode; // mode mtp's draft layer, made before the engine + if (mode == "mtp" && argc >= 7) mtp_mode.emplace(m, argv[3], argc > 7 ? argv[7] : ""); + fnx::Engine e(m, (int) fnx::env_int("FNX_MAX_CTX", 4096), + (int) fnx::env_int("FNX_LANES", 1)); + if (mode == "logits") { + if (argc < 7) { std::fprintf(stderr, "logits needs PROMPT.bin CONT.lgr T OUT.lgr\n"); return 2; } + return run_logits(m, e, argv[3], argv[4], std::atoi(argv[5]), argv[6], + fnx::env_flag("FNX_PREFILL")); + } + if (mode == "mtp") { + if (argc < 7) { std::fprintf(stderr, "mtp needs RT_DIR REF.bin N K\n"); return 2; } + const fnx::Mtp& mtp = *mtp_mode; + e.mtp_attach(mtp); + const std::vector prompt = ref_tokens(argv[4]); + const int n_gen = std::atoi(argv[5]), K = std::atoi(argv[6]); + if (K < 1 || K + 1 > fnx::MAXT) { std::fprintf(stderr, "K: 1..%d\n", fnx::MAXT - 1); return 2; } + const int LK = argc > 8 ? std::atoi(argv[8]) : 0, LNG = 3; // lookup drafts (0: off), n-gram length + if (LK < 0 || LK + 1 > fnx::MAXT) { std::fprintf(stderr, "LOOKUP_K: 0..%d\n", fnx::MAXT - 1); return 2; } + // the prompt: all but its last token through the prompt path (the draft layer reading each row with the token + // after it), then the last token through a window, the draft layer reading its row with the first generated. + // FNX_PREFILL=0: the whole prompt in windows, each followed by the draft layer over its rows + std::vector out; + int p = 0, T = 0, d = -1; + const bool batched = fnx::env_int("FNX_PREFILL", 1) != 0; + const auto t_read = std::chrono::steady_clock::now(); + if (batched && prompt.size() > 1) { + e.prefill(std::vector(prompt.begin(), prompt.end() - 1), prompt.back()); + p = e.pos(); + T = 1; + out = e.window({prompt.back()}); + d = e.draft(1, true, 0, {out.back()}, p); + } else + for (size_t i = 0; i < prompt.size(); i += fnx::MAXT) { + std::vector w(prompt.begin() + i, prompt.begin() + std::min(prompt.size(), i + fnx::MAXT)); + p = e.pos(); + T = (int) w.size(); + out = e.window(w); + std::vector next(w.begin() + 1, w.end()); + next.push_back(i + T < prompt.size() ? prompt[i + T] : out.back()); + d = e.draft(T, true, 0, next, p); + } + { + const double s = std::chrono::duration(std::chrono::steady_clock::now() - t_read).count(); + std::fprintf(stderr, "prompt: %zu tokens in %.2f s (%.0f tok/s, %s)\n", prompt.size(), s, prompt.size() / s, + batched ? "prompt path" : "windows"); + } + // the chain from the last row: K drafts in all + double dwall = 0, dgpu = 0; + long dcalls = 0; + auto chain = [&](int d1, int src_row, int cell0) { + std::vector drafts{d1}; + for (int j = 1; j < K; ++j) { + drafts.push_back(e.draft(1, false, j == 1 ? src_row : 0, {drafts.back()}, cell0 + j)); + dwall += e.last_draft_ms; + dgpu += e.last_draft_gpu_ms; + ++dcalls; + } + return drafts; + }; + std::vector got{out.back()}; + // the LK tokens after the latest earlier place of the last LNG tokens of prompt + got, if its first is d1 + auto lookup = [&](int d1) { + std::vector ctx(prompt); + ctx.insert(ctx.end(), got.begin(), got.end()); + std::vector r; + if (LK == 0 || (int) ctx.size() <= LNG) return r; + const size_t n0 = ctx.size() - LNG; + for (size_t st = n0; st-- > 0;) + if (std::equal(ctx.begin() + st, ctx.begin() + st + LNG, ctx.begin() + n0)) { + if (st + LNG < ctx.size() && ctx[st + LNG] == d1) + r.assign(ctx.begin() + st + LNG, ctx.begin() + std::min(ctx.size(), st + LNG + LK)); + break; + } + return r; + }; + int lookups = 0; + std::vector round_ms; + std::vector round_tok; + std::vector drafts = lookup(d); + if (drafts.empty()) drafts = chain(d, T - 1, p + T - 1); + int rounds = 0; + long accepted = 0; + std::vector tried(K, 0), hit(K, 0); // draft j: rounds that reached it, rounds that accepted it + double verify_ms = 0, verify_gpu = 0, draft_ms = 0, head_ms = 0; + std::vector rows_hist(fnx::MAXT + 1, 0); // verify windows by their rows + const auto t0 = std::chrono::steady_clock::now(); + while ((int) got.size() <= n_gen) { + std::vector rows{got.back()}; + rows.insert(rows.end(), drafts.begin(), drafts.end()); + p = e.pos(); + const auto r0 = std::chrono::steady_clock::now(); + const std::vector o = e.verify(rows); + int n = 1; + while (n < (int) rows.size() && rows[n] == o[n - 1]) ++n; + e.commit(n); + verify_ms += e.last_ms; + verify_gpu += e.last_gpu_ms; + ++rows_hist[rows.size()]; + ++rounds; + accepted += n - 1; + if ((int) rows.size() - 1 == K) + for (int j = 0; j < K && j < n; ++j) { + ++tried[j]; + if (j < n - 1) ++hit[j]; + } + got.insert(got.end(), o.begin(), o.begin() + n); + const auto d0 = std::chrono::steady_clock::now(); + const int d1 = e.draft(n, true, 0, std::vector(o.begin(), o.begin() + n), p); + head_ms += e.last_draft_ms; + drafts = lookup(d1); + if (!drafts.empty()) ++lookups; + else drafts = chain(d1, n - 1, p + n - 1); + const auto d2 = std::chrono::steady_clock::now(); + draft_ms += std::chrono::duration(d2 - d0).count(); + round_ms.push_back(std::chrono::duration(d2 - r0).count()); + round_tok.push_back(n); + } + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + std::printf("generated:"); + for (int t : got) std::printf(" %d", t); + std::printf("\nmtp K=%d: %d rounds, %zu tokens, %.2f per round (drafts accepted %.1f%%), verify %.2f ms + drafts %.2f ms per round, " + "%.1f tok/s\n", K, rounds, got.size() - 1, (got.size() - 1.0) / rounds, 100.0 * accepted / ((double) rounds * K), + verify_ms / rounds, draft_ms / rounds, (got.size() - 1.0) * 1000.0 / ms); + std::printf("draft step (one row): %.3f ms wall, %.3f ms GPU\n", dwall / (dcalls ? dcalls : 1), dgpu / (dcalls ? dcalls : 1)); + // a round: the verify window, then the draft layer over its accepted rows (the first draft), then the chain's + // further drafts (or a lookup); the rest is the host between them + std::printf("per round: verify %.2f ms wall (%.2f GPU), first draft %.2f ms, chain %.2f ms (%.2f steps), host %.2f ms; " + "verify windows by rows:", verify_ms / rounds, verify_gpu / rounds, head_ms / rounds, dwall / rounds, + (double) dcalls / rounds, (ms - verify_ms - draft_ms) / rounds); + for (int t = 1; t <= fnx::MAXT; ++t) + if (rows_hist[(size_t) t]) std::printf(" %d:%d", t, rows_hist[(size_t) t]); + std::printf("\n"); + { // the best stretch of at least 64 tokens: consecutive rounds, tokens over their wall time + double best = 0; + for (size_t a = 0; a < round_ms.size(); ++a) { + double ms_ = 0; + int tk = 0; + for (size_t b = a; b < round_ms.size(); ++b) { + ms_ += round_ms[b]; + tk += round_tok[b]; + if (tk >= 64) { + best = std::max(best, tk * 1000.0 / ms_); + break; + } + } + } + std::printf("lookup drafts in %d of %d rounds; best 64-token stretch %.1f tok/s\n", lookups, rounds, best); + } + std::printf("per step (given the steps before were accepted):"); + for (int j = 0; j < K; ++j) std::printf(" %.2f", tried[j] ? (double) hit[j] / tried[j] : 0.0); + std::printf("\n"); + if (const std::vector pc = e.probe_counts(); !pc.empty() && pc[3] > 0) { + std::printf("prefetch probe: %llu layer-windows, distinct experts a layer-window: picked %.2f, guessed %.2f, both %.2f " + "(%.1f%% of the picked guessed)\n", + pc[3], (double) pc[0] / pc[3], (double) pc[1] / pc[3], (double) pc[2] / pc[3], 100.0 * pc[2] / pc[0]); + if (pc[4] > 0) + std::printf("prefetch probe, experts in RAM: picked and not in a slot %.2f a layer-window, %.1f%% of them guessed; " + "guessed, not picked, not in a slot (wasted copies) %.2f\n", + (double) pc[4] / pc[3], 100.0 * pc[5] / pc[4], (double) pc[6] / pc[3]); + } + // FNX_ROUTE_COUNT=1 with FNX_ROUTE_FILE=path: the run's expert tallies (sfnx's format) + if (const char* rf = std::getenv("FNX_ROUTE_FILE")) { + const std::vector v = e.route_counts(); + std::FILE* f = std::fopen(rf, "wb"); + if (v.empty() || !f || std::fwrite(v.data(), 4, v.size(), f) != v.size() || std::fclose(f) != 0) { + std::fprintf(stderr, "FNX_ROUTE_FILE %s: no tallies (FNX_ROUTE_COUNT=1?) or not written\n", rf); + return 1; + } + } + // FNX_ROUTE_TRACE=M with FNX_ROUTE_TRACE_FILE=path: decode's picks in order + if (const char* tf = std::getenv("FNX_ROUTE_TRACE_FILE")) { + const std::vector v = e.route_trace(); + std::FILE* f = std::fopen(tf, "wb"); + if (v.empty() || !f || std::fwrite(v.data(), 4, v.size(), f) != v.size() || std::fclose(f) != 0) { + std::fprintf(stderr, "FNX_ROUTE_TRACE_FILE %s: no trace (FNX_ROUTE_TRACE=M?) or not written\n", tf); + return 1; + } + } + std::printf("rounds %d\n", rounds); + return 0; + } + const std::vector toks = ref_tokens(argv[3]); + if (mode == "check") { + if (argc < 5) { std::fprintf(stderr, "check needs REF.bin OUT.bin [W]\n"); return 2; } + long long w_in = 5; + if (argc > 5 && (!fnx::parse_whole(argv[5], w_in) || w_in < 1 || w_in > fnx::MAXT)) + throw std::runtime_error("check: window: want a whole number of rows 1.." + std::to_string(fnx::MAXT) + ", got '" + std::string(argv[5]) + "'"); + const int W = (int) w_in; + std::FILE* out = std::fopen(argv[4], "wb"); + if (!out) { std::perror(argv[4]); return 1; } + const std::string out_path = argv[4]; + e.dump = [&](const std::string& name, int layer, int T, int n, const std::vector& v) { + const std::string full = layer >= 0 ? name + "-" + std::to_string(layer) : name; + const uint32_t nl = (uint32_t) full.size(), nd = 2; + const int64_t ne[2] = {n, T}; + std::fwrite(&nl, 4, 1, out); + std::fwrite(full.data(), 1, nl, out); + std::fwrite(&nd, 4, 1, out); + std::fwrite(ne, 8, 2, out); + std::fwrite(v.data(), 4, v.size(), out); + if (std::ferror(out)) throw std::runtime_error("check: " + out_path + " write failed"); + }; + std::vector next; + for (size_t i = 0; i < toks.size(); i += W) { + std::vector w(toks.begin() + i, toks.begin() + std::min(toks.size(), i + W)); + const std::vector o = e.window(w); + next.insert(next.end(), o.begin(), o.end()); + std::printf("window at %zu: %zu rows in %.1f ms\n", i, w.size(), e.last_ms); + } + if (std::fclose(out) != 0) throw std::runtime_error("check: " + out_path + ": close failed (a buffered write did not reach the disk)"); + std::printf("greedy next token per row:"); + for (int t : next) std::printf(" %d", t); + std::printf("\n"); + } else if (mode == "spec") { + if (argc < 6) { std::fprintf(stderr, "spec needs GEN.txt K\n"); return 2; } + std::vector ref; + { + std::ifstream f(argv[4]); + std::string word; + if (!(f >> word) || word != "generated:") { std::fprintf(stderr, "%s: not gen's output\n", argv[4]); return 2; } + for (int t; f >> t;) ref.push_back(t); + } + const int K = std::atoi(argv[5]); + const double bad = argc > 6 ? std::atof(argv[6]) / 100.0 : 0.0; + if (K < 0 || K + 1 > fnx::MAXT) { std::fprintf(stderr, "K: 0..%d\n", fnx::MAXT - 1); return 2; } + std::vector o; + for (size_t i = 0; i < toks.size(); i += fnx::MAXT) { + std::vector w(toks.begin() + i, toks.begin() + std::min(toks.size(), i + fnx::MAXT)); + o = e.window(w); + } + std::vector got{o.back()}; + std::mt19937 rng(7); + std::uniform_real_distribution u(0.0, 1.0); + int windows = 0; + double ms = 0; + while (got.size() + K + 1 <= ref.size()) { + const size_t i = got.size() - 1; // got[i] = ref[i]: this window's row 0 + std::vector rows{got.back()}; + for (int j = 1; j <= K; ++j) rows.push_back(ref[i + j]); + if (K > 0 && u(rng) < bad) rows[1 + (int) (u(rng) * K)] ^= 1; + const std::vector out = e.verify(rows); + int n = 1; + while (n < (int) rows.size() && rows[n] == out[n - 1]) ++n; + e.commit(n); + ms += e.last_ms; + ++windows; + for (int j = 0; j < n; ++j) got.push_back(out[j]); + } + size_t same = 0; + while (same < got.size() && same < ref.size() && got[same] == ref[same]) ++same; + std::printf("spec K=%d bad=%.0f%%: %d windows, %zu tokens (%.2f per window), %.2f ms per window, %.1f tok/s; " + "%zu of %zu tokens match the reference\n", K, bad * 100, windows, got.size() - 1, + (got.size() - 1.0) / windows, ms / windows, (got.size() - 1.0) * 1000.0 / ms, same, got.size()); + return same == got.size() ? 0 : 1; + } else if (mode == "bench_step") { + // what a window costs by its rows, at a context of C tokens of the prompt (read through the prompt path) on every + // lane: verify windows of 1..MAXT rows on one lane, then batched windows (step: one row per lane) on 1..L lanes + // (FNX_LANES >= L); medians of N windows each + if (argc < 7) { std::fprintf(stderr, "bench_step needs L N C [step]\n"); return 2; } + const bool step_only = argc > 7 && std::string(argv[7]) == "step"; // only batched windows of all L lanes + const int L = std::atoi(argv[4]), n = std::atoi(argv[5]), nc = std::atoi(argv[6]); + std::vector lanes{0}; + while ((int) lanes.size() < L) lanes.push_back(e.add_lane()); + e.warm_graphs(); // every lane's rotary table, as sfnx does after adding its lanes + std::vector x(L); + for (int r = 0; r < L; ++r) { + e.use_lane(lanes[r]); + std::vector ctx(nc); + for (int i = 0; i < nc; ++i) ctx[i] = toks[(i + 97 * r) % toks.size()]; + e.prefill(ctx); + x[r] = toks[(nc + 97 * r) % toks.size()]; + } + if (n < 2) { std::fprintf(stderr, "bench_step: N 2 or more (the first window captures the graph and is not timed)\n"); return 2; } + e.use_lane(0); + for (int T = 1; T <= (step_only ? 0 : fnx::MAXT); ++T) { + std::vector wall, gpu; + for (int i = 0; i < n; ++i) { + std::vector w; + for (int t = 0; t < T; ++t) w.push_back(toks[(i + t) % toks.size()]); + e.verify(w); + if (i > 0) wall.push_back(e.last_ms), gpu.push_back(e.last_gpu_ms); // the first captures the graph + e.commit(1); + } + std::fprintf(stderr, "verify, 1 lane, %d rows: wall %.3f ms, gpu %.3f ms\n", T, median(wall), median(gpu)); + } + for (int k = step_only ? L : 1; k <= L; ++k) { + const std::vector use(lanes.begin(), lanes.begin() + k); + std::vector xk(x.begin(), x.begin() + k); + std::vector wall, gpu; + for (int i = 0; i < n; ++i) { + xk = e.step(use, xk); + if (i > 0) wall.push_back(e.last_ms), gpu.push_back(e.last_gpu_ms); + } + std::fprintf(stderr, "step, %d lanes, 1 row each: wall %.3f ms, gpu %.3f ms\n", k, median(wall), median(gpu)); + } + } else if (mode == "bench") { + if (argc < 6) { std::fprintf(stderr, "bench needs T N\n"); return 2; } + const int T = std::atoi(argv[4]), n = std::atoi(argv[5]); + // FNX_BENCH_CTX=N: the windows at a context of N tokens (the prompt repeated, read through the prompt path) + if (std::getenv("FNX_BENCH_CTX")) { + const int nc = (int) fnx::env_int("FNX_BENCH_CTX", 0); + std::vector ctx(nc); + for (int i = 0; i < nc; ++i) ctx[i] = toks[i % toks.size()]; + e.prefill(ctx); + } + std::vector wall, gpu; + for (int i = 0; i < n; ++i) { + std::vector w; + for (int t = 0; t < T; ++t) w.push_back(toks[(i + t) % toks.size()]); + e.verify(w); + if (i > 0) { // the first window of a T captures its graph + wall.push_back(e.last_ms); + gpu.push_back(e.last_gpu_ms); + } + e.commit(1); + } + auto stats = [](std::vector v, double& med, double& trim) { + med = median(v); + std::sort(v.begin(), v.end()); + const size_t a = v.size() / 10, b = v.size() - a; + trim = 0; + for (size_t i = a; i < b; ++i) trim += v[i]; + trim /= (double) (b - a); + }; + double wm, wt, gm, gt; + stats(wall, wm, wt); + stats(gpu, gm, gt); + std::printf("bench %d windows of %d rows: wall median %.3f trimmed %.3f ms, gpu median %.3f trimmed %.3f ms\n", n - 1, T, wm, wt, + gm, gt); + } else if (mode == "rows") { + if (argc < 6) { std::fprintf(stderr, "rows needs T N\n"); return 2; } + const int T = std::atoi(argv[4]), n = std::atoi(argv[5]); + if (n < 2) { std::fprintf(stderr, "rows: N 2 or more (the first window captures the graph and is not timed)\n"); return 2; } + std::vector wall, gpu, launch, card[fnx::NCARD]; + size_t k = 0; + for (int i = 0; i < n; ++i) { + std::vector w; + for (int t = 0; t < T; ++t) w.push_back(toks[k++ % toks.size()]); + e.window(w); + if (i > 0) { // the first window of a T captures its graph + wall.push_back(e.last_ms); + gpu.push_back(e.last_gpu_ms); + launch.push_back(e.last_launch_ms); + for (int c = 0; c < fnx::NCARD; ++c) card[c].push_back(e.last_card_ms[c]); + } + } + std::printf("%d windows of %d rows: median wall %.2f ms, gpu %.2f ms (p90 wall %.2f), graph launches %.3f ms; " + "each card's gpu %.2f / %.2f / %.2f ms\n", + n - 1, T, median(wall), median(gpu), pct(wall, 0.9), median(launch), median(card[0]), median(card[1]), median(card[2])); + } else { // gen + const int n = std::atoi(argv[4]); + if (n < 2) { std::fprintf(stderr, "gen: N 2 or more\n"); return 2; } + std::vector o; + for (size_t i = 0; i < toks.size(); i += fnx::MAXT) { + std::vector w(toks.begin() + i, toks.begin() + std::min(toks.size(), i + fnx::MAXT)); + o = e.window(w); + } + int cur = o.back(); + std::vector gen{cur}; + double ms = 0; + std::vector wall, emb, gpu; + for (int i = 1; i < n; ++i) { + cur = e.window({cur})[0]; + ms += e.last_ms; + wall.push_back(e.last_ms); + emb.push_back(e.last_embed_ms); + gpu.push_back(e.last_gpu_ms); + gen.push_back(cur); + } + std::printf("generated:"); + for (int t : gen) std::printf(" %d", t); + std::printf("\n%d single-row windows: %.2f ms each, %.1f tok/s\n", n - 1, ms / (n - 1), (n - 1) * 1000.0 / ms); + std::printf(" p10/p50/p90 ms: wall %.2f/%.2f/%.2f embed %.2f/%.2f/%.2f gpu %.2f/%.2f/%.2f\n", pct(wall, .1), + pct(wall, .5), pct(wall, .9), pct(emb, .1), pct(emb, .5), pct(emb, .9), pct(gpu, .1), pct(gpu, .5), + pct(gpu, .9)); + } + return 0; +} + +#ifndef FNX_LAB_LIB +int main(int argc, char** argv) { + try { + if (!args_ok(argc, argv)) return 2; // before the model's minutes of loading + fnx::Model m(argv[1]); + return fnx_run_cmd(&m, argc, argv); + } catch (const std::exception& e) { + std::fprintf(stderr, "fnx_run: %s\n", e.what()); + return 1; + } +} +#endif diff --git a/src/split/tools/moe_tile_test.cu b/src/split/tools/moe_tile_test.cu new file mode 100644 index 0000000000..3941a65ada --- /dev/null +++ b/src/split/tools/moe_tile_test.cu @@ -0,0 +1,135 @@ +// The prompt kernel's weight tiles (src/moe_mma.cuh, src/moe_mma_iq.cuh) against the file: for one expert of each routed-expert type a +// GGUF holds, runs the tiles' fetch() and put() over the whole matrix on the GPU and writes the f16 values they put into shared memory. +// tests/split/tile_check.py compares those with gguf-py's dequantization of the same expert (rounded once to f16). +// bin/moe_tile_test MODEL.gguf OUTDIR [expert ...] writes OUTDIR/.e.f16 and prints "name type nrows ncols expert" +#include "kernels.hpp" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common.cuh" +#include "ggml.h" +#include "gguf.hpp" + +namespace fnx { +namespace { + +__device__ __forceinline__ float silu_(float x) { return x / (1.0f + __expf(-x)); } + +#include "moe_w.cuh" +#include "moe_mma.cuh" +#include "moe_mma_iq.cuh" + +template +__global__ void __launch_bounds__(MM_THREADS) k_tiles(const char* __restrict__ we, size_t row_a, int nrows, int ncols, __half* __restrict__ out) { + extern __shared__ __align__(32) __half smem[]; + constexpr int NP = MM_BM / MM_PASS; + const int row0 = blockIdx.x * MM_BM; + for (int k0 = 0; k0 < ncols; k0 += MM_KC) { + const int kc = min(MM_KC, ncols - k0); + MmTile wt[NP]; +#pragma unroll + for (int p = 0; p < NP; ++p) wt[p].fetch(we, row_a, nrows, row0 + p * MM_PASS, k0, kc); +#pragma unroll + for (int p = 0; p < NP; ++p) wt[p].put(k0, kc, smem + p * MM_PASS * MM_LD); + __syncthreads(); + for (int e = threadIdx.x; e < MM_BM * kc; e += MM_THREADS) { + const int r = e / kc, c = e % kc, row = row0 + r; + if (row < nrows) out[(size_t) row * ncols + k0 + c] = smem[r * MM_LD + c]; + } + __syncthreads(); + } +} + +template +void run(const char* d_we, size_t row_a, int nrows, int ncols, __half* d_out) { + k_tiles<<<(nrows + MM_BM - 1) / MM_BM, MM_THREADS, MM_BM * MM_LD * sizeof(__half)>>>(d_we, row_a, nrows, ncols, d_out); +} + +} // namespace +} // namespace fnx + +using namespace fnx; + +int main(int argc, char** argv) { + if (argc < 3) { + std::fprintf(stderr, "usage: moe_tile_test MODEL.gguf OUTDIR [expert ...]\n"); + return 2; + } + try { + Gguf g(argv[1]); + std::vector experts; + for (int i = 3; i < argc; ++i) experts.push_back(std::atoi(argv[i])); + if (experts.empty()) experts = {5, 511}; + std::map pick; // the first routed-expert tensor of each type, gate/up first + for (const auto& kv : g.tensors()) { + const std::string& n = kv.first; + if (n.find("_exps.weight") == std::string::npos) continue; + const uint32_t ty = kv.second.type; + if (!pick.count(ty)) pick[ty] = n; + } + // also a down matrix of each type that has both, as its K (640) is not a multiple of 256 + for (const auto& kv : g.tensors()) { + const std::string& n = kv.first; + if (n.find("ffn_down_exps.weight") == std::string::npos) continue; + const std::string key = "down:" + std::to_string(kv.second.type); + static std::map seen; + if (!seen[key]) { + seen[key] = true; + pick[1000 + kv.second.type] = n; + } + } + for (const auto& pk : pick) { + const Tensor& t = g.t(pk.second); + const int ncols = (int) t.ne[0], nrows = (int) t.ne[1]; + const size_t row_a = t.row_bytes(); + for (int e : experts) { + if (e >= t.ne[2]) continue; + const char* we = (const char*) t.data + (size_t) e * row_a * nrows; + char* d_we; + __half* d_out; + if (cudaMalloc(&d_we, row_a * nrows) || cudaMalloc(&d_out, (size_t) nrows * ncols * 2)) throw std::runtime_error("cudaMalloc"); + cudaMemcpy(d_we, we, row_a * nrows, cudaMemcpyHostToDevice); + cudaMemset(d_out, 0xFF, (size_t) nrows * ncols * 2); + switch (t.type) { + case T_Q4_0: run(d_we, row_a, nrows, ncols, d_out); break; + case T_IQ4_NL: run(d_we, row_a, nrows, ncols, d_out); break; + case T_IQ4_XS: run(d_we, row_a, nrows, ncols, d_out); break; + case T_IQ3_S: run(d_we, row_a, nrows, ncols, d_out); break; + case T_IQ3_XXS: run(d_we, row_a, nrows, ncols, d_out); break; + case T_IQ2_S: run(d_we, row_a, nrows, ncols, d_out); break; + case T_Q4_K: run(d_we, row_a, nrows, ncols, d_out); break; + case T_Q5_K: run(d_we, row_a, nrows, ncols, d_out); break; + case T_Q5_1: run(d_we, row_a, nrows, ncols, d_out); break; + case T_Q8_0: run(d_we, row_a, nrows, ncols, d_out); break; + default: std::printf("skip %s type %u\n", t.name.c_str(), t.type); cudaFree(d_we); cudaFree(d_out); continue; + } + if (cudaDeviceSynchronize() != cudaSuccess) throw std::runtime_error(std::string("kernel: ") + cudaGetErrorString(cudaGetLastError())); + std::vector<__half> h((size_t) nrows * ncols); + cudaMemcpy(h.data(), d_out, h.size() * 2, cudaMemcpyDeviceToHost); + cudaFree(d_we); + cudaFree(d_out); + const std::string path = std::string(argv[2]) + "/" + t.name + ".e" + std::to_string(e) + ".f16"; + FILE* fp = std::fopen(path.c_str(), "wb"); + if (!fp) throw std::runtime_error("cannot write " + path); + std::fwrite(h.data(), 2, h.size(), fp); + std::fclose(fp); + std::printf("%s %u %d %d %d\n", t.name.c_str(), t.type, nrows, ncols, e); + } + } + } catch (const std::exception& e) { + std::fprintf(stderr, "moe_tile_test: %s\n", e.what()); + return 1; + } + return 0; +} diff --git a/src/split/tools/ref_tokens.hpp b/src/split/tools/ref_tokens.hpp new file mode 100644 index 0000000000..2d4908a4bd --- /dev/null +++ b/src/split/tools/ref_tokens.hpp @@ -0,0 +1,42 @@ +// A prompt file's token ids: ref/*.bin (fnx_ref's dump format, ref/refio.py), whose first record is one named +// "tokens" holding the ids as float32 (later records, per-layer dumps, are not read). Every read is checked and the +// ids must be whole numbers in [0, 2^24): a short or foreign file is an error here, never a run on a truncated or +// zero-padded prompt. It throws rather than exits, so a lab worker (bin/fnx_lab) survives a wrong path. +#pragma once +#include +#include +#include +#include +#include + +inline std::vector ref_tokens(const char* path) { + std::FILE* f = std::fopen(path, "rb"); + if (!f) throw std::runtime_error(std::string(path) + ": cannot open"); + auto bad = [&](const std::string& why) { + std::fclose(f); + return std::runtime_error(std::string(path) + ": " + why); + }; + uint32_t nl = 0, nd = 0; + if (std::fread(&nl, 4, 1, f) != 1) throw bad("empty file"); + if (nl == 0 || nl > 256) throw bad("not a prompt file (record name length " + std::to_string(nl) + ")"); + std::string name(nl, '\0'); + if (std::fread(name.data(), 1, nl, f) != nl) throw bad("short record name"); + if (name != "tokens") throw bad("the first record is '" + name + "', not tokens"); + if (std::fread(&nd, 4, 1, f) != 1 || nd != 1) throw bad("the tokens record is not one-dimensional"); + int64_t ne = 0; + if (std::fread(&ne, 8, 1, f) != 1 || ne < 1 || ne > 0x7fffffffLL) throw bad("no valid token count"); + std::vector v((size_t) ne); + if (std::fread(v.data(), 4, v.size(), f) != v.size()) throw bad("short file: fewer tokens than its header says"); + std::fclose(f); + std::vector ids; + ids.reserve(v.size()); + for (size_t i = 0; i < v.size(); ++i) { + const float x = v[i]; + // float32 holds every integer below 2^24 exactly (the vocabulary is ~248k) + if (!(x >= 0.f && x < 16777216.f) || x != (float) (int) x) + throw std::runtime_error(std::string(path) + ": value " + std::to_string(x) + " at " + std::to_string(i) + + " is not a token id"); + ids.push_back((int) x); + } + return ids; +} diff --git a/tests/split/tile_check.py b/tests/split/tile_check.py new file mode 100644 index 0000000000..d5e850f838 --- /dev/null +++ b/tests/split/tile_check.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Check the prompt kernel's weight tiles against gguf-py. + + moe_tile_test MODEL.gguf OUTDIR > tiles.txt + tile_check.py MODEL.gguf OUTDIR tiles.txt --gguf-py /path/to/gguf-py + +For each line of the dump (tensor, loader type, rows, columns, expert): the f16 values the tile put in shared memory must equal gguf-py's +dequantization of the file's expert, rounded once to f16 (a tile value may differ by one f16 step where the two compute the f32 product in +another order). Strata's Q2_0 (type 42; the loader repacks it to Q4_0 blocks, type 2) is checked against (code - 1) * d read from the +file. Prints one line per tensor and expert; exit 1 on any miss. +""" +import argparse +import os +import re +import sys + +import numpy as np + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("model") + ap.add_argument("outdir") + ap.add_argument("dump") + ap.add_argument("--gguf-py", required=True) + a = ap.parse_args() + sys.path.insert(0, a.gguf_py) + import gguf + from gguf import quants + + m = re.match(r"(.*-)(\d{5})(-of-)(\d{5})(\.gguf)$", a.model) + shards = ["%s%05d%s%s%s" % (m[1], i, m[3], m[4], m[5]) for i in range(1, int(m[4]) + 1)] if m else [a.model] + tensors = {} + for s in shards: + for t in gguf.GGUFReader(s).tensors: + tensors[t.name] = t + + bad = 0 + for line in open(a.dump): + p = line.split() + if len(p) != 5 or not p[1].isdigit(): + continue + name, ty, nrows, ncols, e = p[0], int(p[1]), int(p[2]), int(p[3]), int(p[4]) + t = tensors[name] + raw = np.asarray(t.data)[e] + if t.tensor_type.name == "Q2_0": + raw = np.ascontiguousarray(raw).reshape(-1, 18) + d = raw[:, :2].copy().view(np.float16).astype(np.float32).reshape(-1, 1) + codes = np.stack([(raw[:, 2:] >> (2 * k)) & 3 for k in range(4)], axis=2).reshape(-1, 64) + ref = ((codes.astype(np.float32) - 1.0) * d).reshape(nrows, ncols) + else: + ref = quants.dequantize(raw, t.tensor_type).astype(np.float32).reshape(nrows, ncols) + ref16 = ref.astype(np.float16) + got = np.fromfile(os.path.join(a.outdir, "%s.e%d.f16" % (name, e)), dtype=np.float16).reshape(nrows, ncols) + gi, ri = got.view(np.int16).astype(np.int32), ref16.view(np.int16).astype(np.int32) + # f16 ordering: compare as sign-magnitude steps + def key(x): + return np.where(x < 0, -(x & 0x7FFF), x) + step = np.abs(key(gi) - key(ri)) + exact = float((step == 0).mean()) + ok = bool(step.max() <= 1 and exact >= 0.999 and not np.isnan(got.astype(np.float32)).any()) + print("%s %-44s %-8s e%-3d exact %.5f max step %d max|d| %.3g" % ("ok " if ok else "FAIL", name, t.tensor_type.name, e, exact, step.max(), + float(np.abs(got.astype(np.float32) - ref).max()))) + bad += not ok + sys.exit(1 if bad else 0) + + +if __name__ == "__main__": + main() From aaa7a8e4948a5e68df93d98b5f169f100c316717 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 2 Nov 2026 08:41:19 +0100 Subject: [PATCH 06/11] split: the selection rule accepts the i-quant and Q2_0 expert sets the engine now runs EXPERT_TYPES gains IQ2_S, IQ3_XXS, IQ3_S, IQ4_XS, IQ4_NL and Q2_0; a set with such experts may have embeddings, shared experts and an output head in any type the loader converts to Q8_0; the memory estimate counts the Q2_0 to Q4_0 repack twice; the per-layer embedding table type is checked. Tests for the supported sets (the IQ3_S set, UD-IQ4_XS), the plain refusal lines and the scan. --- strata_control/split_engine.py | 42 +++++++++++++++++++------- tests/split/test_split_engine.py | 51 ++++++++++++++++++++++++++++++-- 2 files changed, 81 insertions(+), 12 deletions(-) diff --git a/strata_control/split_engine.py b/strata_control/split_engine.py index 8495c07c45..5458e0d2f7 100644 --- a/strata_control/split_engine.py +++ b/strata_control/split_engine.py @@ -12,8 +12,10 @@ has actually been run: - Linux, NVIDIA cards, 2 to 4 of them, all the same model of card and memory size; - a card architecture and card count that have been run (TESTED): sm_86 on 2 cards today. Others build but stay off unless the caller says allow_untested (testers); the Decision says which part is untested in plain words; - - the GGUF is UD-Q4_K_XL type: routed experts Q4_K/Q5_K/Q5_1/Q8_0, token embeddings and the shared expert Q8_0 (checked from the - file's tensor types, not its name), the Qwen3.8-Flash-Next shapes (48 layers, 512 experts); + - the GGUF is a set the engine reads (checked from the file's tensor types, not its name), the Qwen3.8-Flash-Next shapes (48 layers, + 512 experts): routed experts Q4_K/Q5_K/Q5_1/Q8_0/Q4_0 (UD-Q4_K_XL, Q8_0) or the i-quants IQ2_S/IQ3_XXS/IQ3_S/IQ4_XS/IQ4_NL and Strata's + Q2_0 (UD-IQ4_XS, the IQ3_S set); token embeddings, shared expert, output head Q8_0, or, in a set with i-quant or Q2_0 experts, + any type the loader converts to Q8_0/F32 when it reads the file (src/split/src/tensor_convert.hpp); - ALL routed experts fit in the cards' memory (the expert cache is off: with it the engine keeps a 74 GiB pinned copy of the experts in RAM) and the RAM that stays (the 27.5 GiB locked embedding table, a few GiB of buffers and the conversation cache) is available with room to spare; @@ -34,8 +36,14 @@ TESTED_ARCHS = (86,) # compute capability: sm_86 only TESTED_CONTEXT = 131072 MAX_CARDS = 4 LAYERS, EXPERTS = 48, 512 # Qwen3.8-Flash-Next -EXPERT_TYPES = {"Q4_K", "Q5_K", "Q5_1", "Q8_0", "Q4_0"} # the routed-expert kernels -Q8_ROLES = ("token_embd.weight",) +EXPERT_TYPES = {"Q4_K", "Q5_K", "Q5_1", "Q8_0", "Q4_0", # the routed-expert kernels (decode and prompt) + "IQ2_S", "IQ3_XXS", "IQ3_S", "IQ4_XS", "IQ4_NL", # ggml's i-quant vec_dots; prompt tiles in src/moe_mma_iq.cuh + "Q2_0"} # Strata's 2-bit type: the loader repacks it to Q4_0 blocks (twice the bytes) +# the loader (Gguf::convert_small_tensors) converts the dense tensors to Q8_0/F32 only when the file has one of these routed types +CONVERT_TRIGGERS = {"IQ2_S", "IQ3_XXS", "IQ3_S", "Q2_0"} +# and can read these types to do it +CONVERTED_FROM = {"Q8_0", "Q4_K", "Q5_K", "Q6_K", "IQ4_XS", "IQ4_NL", "BF16", "F16", "F32"} +PLE_TYPES = {"IQ4_NL", "Q8_0"} # per_layer_token_embd.weight as the host's row reader takes it # measured on 2x RTX A6000 48 GB at 128K context, 6 lanes (phaseA-tests/sfnx/RESULTS.md section 8): a card held half the experts plus # 8.4 GiB of dense weights, buffers and the K/V pool, with 3.6 GiB left free. 9 GiB per card is that plus a little. CARD_OVERHEAD_GIB = 9.0 @@ -62,6 +70,8 @@ class ModelFacts: embd_ram_bytes: int # token_embd + per_layer_token_embd: locked in RAM layers: int experts: int + ple_type: str | None = "IQ4_NL" # per_layer_token_embd.weight + output_type: str | None = "Q8_0" # output.weight @dataclasses.dataclass @@ -98,6 +108,8 @@ def scan_model(first_shard: str | pathlib.Path) -> ModelFacts: routed_bytes = 0 shexp: dict[str, int] = {} embd_type = None + ple_type = None + output_type = None embd_ram = 0 layers = 0 experts = 0 @@ -108,7 +120,7 @@ def scan_model(first_shard: str | pathlib.Path) -> ModelFacts: b = t.expected_bytes() or 0 if "_exps" in n and n.endswith(".weight") and "shexp" not in n: routed_types[t.type_name] = routed_types.get(t.type_name, 0) + 1 - routed_bytes += b + routed_bytes += b * 2 if t.type_name == "Q2_0" else b # the loader repacks Q2_0 to Q4_0: twice the bytes in the cards if len(t.shape) >= 3: experts = max(experts, t.shape[-1]) mm = re.search(r"blk\.(\d+)\.", n) @@ -120,8 +132,11 @@ def scan_model(first_shard: str | pathlib.Path) -> ModelFacts: embd_type = t.type_name embd_ram += b elif n == "per_layer_token_embd.weight": + ple_type = t.type_name embd_ram += b - return ModelFacts(routed_types, routed_bytes, embd_type, shexp, embd_ram, layers, experts) + elif n == "output.weight": + output_type = t.type_name + return ModelFacts(routed_types, routed_bytes, embd_type, shexp, embd_ram, layers, experts, ple_type, output_type) def decide(*, enabled: bool, system: str, cards: list[Card], ram_total_gib: float, ram_available_gib: float, model: ModelFacts, @@ -163,10 +178,17 @@ def decide(*, enabled: bool, system: str, cards: list[Card], ram_total_gib: floa why.append("this is not a model it knows (no routed experts)") elif bad: why.append("the model's routed experts use " + "/".join(bad) + ", which it does not read") - if model.embd_type != "Q8_0": - why.append(f"the token embeddings are {model.embd_type}, it needs Q8_0") - if model.shexp_types and set(model.shexp_types) != {"Q8_0"}: - why.append("the shared expert is not Q8_0") + converts = bool(CONVERT_TRIGGERS & set(model.routed_types)) # the loader then converts the dense tensors it does not read + readable = CONVERTED_FROM if converts else {"Q8_0"} + if model.embd_type not in readable: + why.append(f"the token embeddings are {model.embd_type}, it needs Q8_0" if not converts else + f"the token embeddings are {model.embd_type}, which it cannot convert to Q8_0") + if model.shexp_types and not set(model.shexp_types) <= readable: + why.append("the shared expert is " + "/".join(sorted(set(model.shexp_types) - readable)) + ", which it cannot read" + ("" if converts else " (it needs Q8_0)")) + if model.output_type is not None and model.output_type not in readable: + why.append(f"the output head is {model.output_type}, which it cannot read" + ("" if converts else " (it needs Q8_0)")) + if model.ple_type is not None and model.ple_type not in PLE_TYPES: + why.append(f"the per-layer embedding table is {model.ple_type}, it needs IQ4_NL or Q8_0") if (model.layers, model.experts) != (LAYERS, EXPERTS): why.append("it only knows Qwen3.8-Flash-Next (48 layers, 512 experts)") need_vram = model.routed_bytes / GIB / max(n, 1) + CARD_OVERHEAD_GIB diff --git a/tests/split/test_split_engine.py b/tests/split/test_split_engine.py index bf9ba6185b..fdf8a42781 100644 --- a/tests/split/test_split_engine.py +++ b/tests/split/test_split_engine.py @@ -84,12 +84,59 @@ class Rule(unittest.TestCase): self.assertIn("RAM", d.line) def test_only_the_quant_types_it_reads(self): - for model in (udq4(routed_types={"IQ3_S": 10, "IQ2_S": 20, "IQ4_NL": 39}), udq4(embd_type="IQ4_XS"), - udq4(shexp_types={"BF16": 48, "IQ4_NL": 47}), udq4(layers=64), udq4(routed_types={})): + for model in (udq4(layers=64), udq4(routed_types={}), + udq4(routed_types={"Q6_K": 48}), # UD-Q6_K_XL-like experts: no kernel + udq4(embd_type="IQ4_XS"), # a K-quant set is not converted at load + udq4(shexp_types={"BF16": 48, "IQ4_NL": 47}), + udq4(output_type="Q6_K"), + udq4(ple_type="Q6_K")): d = decide(model=model) self.assertFalse(d.use_split, model) self.assertTrue(d.line.startswith("Using the normal layer split")) + def test_the_iq3_s_set_and_ud_iq4_xs_run(self): + iq3s = S.ModelFacts(routed_types={"IQ2_S": 40, "IQ3_XXS": 34, "IQ3_S": 20, "IQ4_XS": 2, "IQ4_NL": 39, "Q2_0": 9}, + routed_bytes=int(49 * GIB), embd_type="IQ4_XS", shexp_types={"IQ4_XS": 60, "Q4_K": 40, "Q5_K": 20, "IQ4_NL": 24}, + embd_ram_bytes=int(27.2 * GIB), layers=48, experts=512, ple_type="IQ4_NL", output_type="Q6_K") + d = decide(model=iq3s) + self.assertTrue(d.use_split, d.reasons) + ud_iq4_xs = S.ModelFacts(routed_types={"IQ3_S": 94, "IQ4_XS": 2, "IQ4_NL": 43, "Q8_0": 5}, routed_bytes=int(59.5e9), + embd_type="Q8_0", shexp_types={"Q8_0": 144}, embd_ram_bytes=int(27.5 * GIB), layers=48, experts=512, + ple_type="IQ4_NL", output_type="Q6_K") + d = decide(model=ud_iq4_xs) + self.assertTrue(d.use_split, d.reasons) + self.assertTrue(d.need_vram_gib < 48, d.need_vram_gib) + + def test_a_type_the_loader_cannot_convert_is_a_plain_refusal(self): + for model, word in ((udq4(routed_types={"IQ3_S": 94}, embd_type="Q3_K"), "cannot convert"), + (udq4(routed_types={"IQ3_S": 94}, shexp_types={"Q3_K": 5}), "cannot read"), + (udq4(routed_types={"IQ3_S": 94}, ple_type="Q6_K"), "per-layer"), + (udq4(routed_types={"IQ3_S": 94, "TQ2_0": 2}), "TQ2_0")): + d = decide(model=model) + self.assertFalse(d.use_split) + self.assertIn(word, d.line) + self.assertNotIn(chr(10), d.line) # one plain line + + def test_scan_counts_the_q2_0_repack_twice(self): + from unittest import mock + + class T: + def __init__(self, name, type_name, shape, nbytes): + self.name, self.type_name, self.shape, self._n = name, type_name, shape, nbytes + def expected_bytes(self): + return self._n + + class F: + def __init__(self, path): + self.tensors = [T("blk.0.ffn_down_exps.weight", "Q2_0", (640, 2560, 512), 1000), T("blk.1.ffn_gate_exps.weight", "IQ3_S", (2560, 640, 512), 5000), + T("token_embd.weight", "IQ4_XS", (2560, 248320), 10), T("per_layer_token_embd.weight", "IQ4_NL", (1, 2), 20), + T("output.weight", "Q6_K", (2560, 248320), 30)] + with mock.patch("tools.gguf_reader.GGUFFile", F): + m = S.scan_model("/x/model-00001-of-00001.gguf") + self.assertEqual(m.routed_bytes, 2 * 1000 + 5000) + self.assertEqual((m.embd_type, m.ple_type, m.output_type), ("IQ4_XS", "IQ4_NL", "Q6_K")) + self.assertEqual(m.embd_ram_bytes, 30) + def test_the_reasons_are_all_reported(self): d = decide(system="windows", cards=cards(1), model=udq4(embd_type="Q6_K")) self.assertGreaterEqual(len(d.reasons), 3) From 1ba2312176750ec8a8ce7189ab646ba4dc4a5fed Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 2 Nov 2026 09:29:42 +0100 Subject: [PATCH 07/11] split: refuse a model whose routed experts it has no kernel for at once, in one plain line Before this, a start with such a file (UD-Q6_K_XL) read 55 GB of embeddings and spent more than 25 minutes loading before it gave up, so the server's fallback to the normal layer split came very late. The check runs when the file is opened, before anything is read or placed. --- src/split/src/model.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/split/src/model.cpp b/src/split/src/model.cpp index a9267c8a8b..0c147f99eb 100644 --- a/src/split/src/model.cpp +++ b/src/split/src/model.cpp @@ -1182,6 +1182,20 @@ Mtp::Mtp(const Model& m, const std::string& dir, const std::string& vocab_file) Mtp::~Mtp() { free_mtp_cards(cards); } +// A file whose routed experts the engine has no kernel for is refused here, in one plain line, before anything is read into RAM or placed on +// the cards (the app's rule, strata_control/split_engine.py, refuses it earlier; this is the same check for a start that skipped the rule). The +// server then starts the normal layer split. Q2_0 is not listed: the Gguf has already repacked it to Q4_0. +static void check_supported(const Gguf& g) { + const uint32_t ok[] = {T_Q4_K, T_Q5_K, T_Q5_1, T_Q8_0, T_Q4_0, T_IQ4_NL, T_IQ4_XS, T_IQ3_S, T_IQ3_XXS, T_IQ2_S}; + for (const auto& kv : g.tensors()) { + const std::string& n = kv.first; + if (n.find("_exps.weight") == std::string::npos || n.find("shexp") != std::string::npos) continue; + if (std::find(std::begin(ok), std::end(ok), kv.second.type) == std::end(ok)) + throw std::runtime_error("the all-cards split engine does not read this model's routed experts (" + n + " is ggml type " + + std::to_string(kv.second.type) + "); use the normal layer split"); + } +} + Model::Model(const std::string& path, Load how, Store* store, const std::string* image) : g(path) { // the cards first: reading the embeddings into RAM below takes seconds on a cold cache { @@ -1195,6 +1209,7 @@ Model::Model(const std::string& path, Load how, Store* store, const std::string* " of them, or build for " + std::to_string(ndev) + " (make FNX_NCARD=" + std::to_string(ndev) + ")"); check_cards(); } + check_supported(g); #if FNX_27B const std::string p = "qwen35."; // block_count holds the draft (nextn) layer too From 575caededc6b8369090512556b6c736bfbb1020e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 2 Nov 2026 10:15:30 +0100 Subject: [PATCH 08/11] split: the fallback line carries the engine's own reason and keeps its log; FNX_DUMP_FIRST_LOGITS diagnostic serve/server.py: when the split engine fails to start, the one line now says why in the engine's words (its 'sfnx: failed:' line) and the split engine's log is kept beside the normal engine's (it wrote the same file). src/split/src/session.cpp: FNX_DUMP_FIRST_LOGITS=PATH writes each request's first-token full-vocabulary logits to PATH., for comparing the prompt path with another engine's. --- serve/server.py | 13 ++++++++++++- serve/test_split_fallback.py | 22 ++++++++++++++++++++++ src/split/src/session.cpp | 12 ++++++++++++ 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/serve/server.py b/serve/server.py index 097c9ab282..57a93dfbd0 100644 --- a/serve/server.py +++ b/serve/server.py @@ -8938,7 +8938,18 @@ def start_engine_or_fallback(cfg: dict, exe: str, effort_end: list[str] | None, except Exception as e: if not isinstance(fb, dict) or not fb.get("exe"): raise - why = str(e).strip().splitlines()[0][:200] if str(e).strip() else type(e).__name__ + msg = str(e).strip() + why = msg.splitlines()[0][:200] if msg else type(e).__name__ + # the engine's own reason ("sfnx: failed: ..." in its log tail, which the exception carries) is what a person needs to read + own = next((ln.split("sfnx: failed: ", 1)[1].strip() for ln in reversed(msg.splitlines()) if "sfnx: failed: " in ln), "") + if own: + why = own[:300] + log = cfg.get("log") + if log: # the normal engine writes the same log file: keep the split engine's + try: + os.replace(log, str(log) + ".split-engine") + except OSError: + pass print(f"[strata] The all-cards split engine could not start ({why}). Starting the normal layer split instead.", flush=True) cfg2 = {k: v for k, v in cfg.items() if k not in SPLIT_KEYS + ("exe", "args", "env", "layer_split", "replicas", "user_args", "drafting")} cfg2.update(fb) diff --git a/serve/test_split_fallback.py b/serve/test_split_fallback.py index 7e1ee1439a..62219d0aba 100644 --- a/serve/test_split_fallback.py +++ b/serve/test_split_fallback.py @@ -75,6 +75,28 @@ class Fallback(unittest.TestCase): self.assertIn("all-cards split engine could not start", lines[0]) self.assertIn("normal layer split", lines[0]) + def test_the_engines_own_reason_is_in_the_line_and_its_log_is_kept(self): + import tempfile + log = os.path.join(tempfile.mkdtemp(), "engine.log") + Path(log).write_text("sfnx: failed: the all-cards split engine does not read this model's routed experts (blk.0.ffn_gate_exps.weight is ggml type 14); use the normal layer split\n") + cfg = split_cfg() + cfg["log"] = log + + class Refusing(FakeEngine): + def __init__(self, exe, args, cwd=None, log=None, env=None, lazy=False, **kw): + FakeEngine.started.append((exe, list(args), cwd, dict(env or {}))) + if exe == "/e/strata-split-2": + raise S.EngineDied("the engine exited before it was ready (see x)\n" + Path(log).read_text()) + self.info = {} + with mock.patch.object(S, "StrataEngine", Refusing): + engine, out = self.run_start(cfg) + lines = [ln for ln in out.splitlines() if ln.strip()] + self.assertEqual(len(lines), 1) + self.assertIn("does not read this model's routed experts", lines[0]) + self.assertNotIn("exited before it was ready", lines[0]) + self.assertTrue(os.path.exists(log + ".split-engine")) # the normal engine will overwrite the log; the refusal stays readable + self.assertEqual([s[0] for s in FakeEngine.started], ["/e/strata-split-2", NORMAL]) + def test_without_a_fallback_the_failure_stays_a_failure(self): cfg = split_cfg() del cfg["split_fallback"] diff --git a/src/split/src/session.cpp b/src/split/src/session.cpp index fdc0aaa402..8e429c761f 100644 --- a/src/split/src/session.cpp +++ b/src/split/src/session.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include @@ -463,6 +464,17 @@ Finish Session::generate(int max_new, const Sampling& s, const std::function o = e_.verify(rows); + if (produced == 0) { // FNX_DUMP_FIRST_LOGITS=PATH (diagnostics): the full-vocabulary logits of each request's first token to PATH. (float32) + static const char* dump = std::getenv("FNX_DUMP_FIRST_LOGITS"); + static int dump_n = 0; + if (dump) { + const std::vector row = e_.last_logits(1); + const std::string path = std::string(dump) + "." + std::to_string(dump_n++); + std::FILE* f = std::fopen(path.c_str(), "wb"); + if (!f || std::fwrite(row.data(), 4, row.size(), f) != row.size()) std::fprintf(stderr, "session: FNX_DUMP_FIRST_LOGITS: cannot write %s\n", path.c_str()); + if (f) std::fclose(f); + } + } st.verify_ms += ms_since(tv); st.verify_gpu_ms += e_.last_gpu_ms; st.launch_ms += e_.last_launch_ms; From ac1965edeadda2703838ca46e9a90db491023a62 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 2 Nov 2026 10:44:43 +0100 Subject: [PATCH 09/11] split: the all-cards split engine is automatic by default, with an off switch strata launch --split-engine auto|on|off (settings field, saved in the preset and written to the launch config, so an off survives updates); STRATA_SPLIT_ENGINE=0/1 for testers. auto (the default) uses the split engine where the rule says yes and says nothing where it says no; on says why it cannot run; off never. The rule also leaves the layer split for choices the split engine does not honour (DFlash2, custom engine arguments, replicas, a conversation memory format other than int8). The engine is looked up per card count and architecture (strata-split-N-smCC, then strata-split-N); sm_120 joins sm_86 as a tested architecture. Tests: modes, auto/on/off, silent refusals, the flag, a saved off. --- strata_cli/launch/cmd.py | 8 +- strata_cli/launch/runner.py | 33 +++++--- strata_cli/launch/settings.py | 5 ++ strata_control/split_engine.py | 66 +++++++++++---- tests/split/test_split_engine.py | 100 +++++++++++++++++++++-- tests/terminal/test_split_engine_flag.py | 46 +++++++++++ 6 files changed, 223 insertions(+), 35 deletions(-) create mode 100644 tests/terminal/test_split_engine_flag.py diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 7d1b4540d1..df3c8e1d64 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -105,6 +105,10 @@ def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser] help="which drafter guesses words ahead to make answers faster: auto (recommended: Strata picks from what it measured on cards like yours; " "that is the MTP today), mtp, dflash2 (Qwen3.8-Flash-Next only; downloads a 1.2 GB drafter once) or off. If DFlash2 cannot run " "(not enough graphics memory, or a model it is not for) the MTP is used and the start says why") + g.add_argument("--split-engine", type=_choice("a split-engine setting", S.SPLIT_MODES), metavar="auto|on|off", + help="NVIDIA, two or more cards: the engine that splits every layer across the cards (faster answers). auto (the default) uses it by itself " + "where it is supported and starts the normal layer split everywhere else; on asks for it and says in one line why it cannot run; " + "off never uses it. Your choice is saved with the preset") g.add_argument("--speed", type=_choice("a speed", S.SPEED_MODES), metavar="faster|full", help="DeepSeek: faster uses 5 of 6 experts per word (a small quality change, usually not noticeable; the default on a PC with 16 GB " "of graphics memory or less, and on a single Radeon RX 9000 / AI PRO R9700 card, or several that hold half of the experts), full uses all 6") @@ -244,6 +248,8 @@ def settings_from_args(a: argparse.Namespace, catalog=None) -> tuple[S.LaunchSet s.mtp = a.mtp if a.drafting: s.drafting = a.drafting + if getattr(a, "split_engine", None): + s.split_engine = a.split_engine if getattr(a, "full_quality", False): if getattr(a, "speed", None) == "faster": notices.append(S.Notice("warn", "--full-quality and --speed faster were both given; full quality is used.", "")) @@ -865,7 +871,7 @@ def run_launch(a: argparse.Namespace) -> int: notices.append(S.Notice("warn", backend_note, "")) if not machine: _interrupted_move_notice() - have_choices = bool(a.preset or a.model or a.model_path or a.context or a.vision or a.parallel or a.access or a.tune or a.drafting or getattr(a, "speed", None) or getattr(a, "full_quality", False)) + have_choices = bool(a.preset or a.model or a.model_path or a.context or a.vision or a.parallel or a.access or a.tune or a.drafting or getattr(a, "split_engine", None) or getattr(a, "speed", None) or getattr(a, "full_quality", False)) interactive = sys.stdin.isatty() and sys.stdout.isatty() and not a.no_tui and not machine and not a.plan plain_questions = False no_screens_package = None diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index bab8b2d0b1..03a463bcb6 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -545,6 +545,8 @@ def derive_config(base: dict, s: S.LaunchSettings, *, bool_flags: frozenset[str] cfg.pop("api_key", None) if s.drafting: # strata_control/drafting.py: serve/server.py applies it at every start cfg["drafting"] = s.drafting + if s.split_engine: # strata_control/split_engine.py: read by apply_split_engine; "off" survives every update + cfg["split_engine"] = s.split_engine cfg.setdefault("exe", "component:strata-engine") cfg["open_browser"] = False # strata launch never opens a browser by itself (only `--open` does, after the start) if isinstance(cfg.get("args"), list): @@ -1529,32 +1531,39 @@ class Runner: return out def apply_split_engine(self, cfg: dict) -> None: - """The opt-in all-cards split engine (docs/SPLIT_ENGINE.md): only when the run config says "split_engine": true (or a tester sets - STRATA_SPLIT_ENGINE=1), only for a Qwen model on this PC's NVIDIA cards that passes strata_control/split_engine.py's rule. Anything - else leaves the config as it is, with one plain line when the person had asked for it. It never stops a launch.""" + """The all-cards split engine (docs/SPLIT_ENGINE.md): by itself ("auto", the default) for a Qwen model on this PC's NVIDIA cards that passes + strata_control/split_engine.py's rule, never when the run config says "split_engine": "off" (`--split-engine off`, STRATA_SPLIT_ENGINE=0). + In auto a "no" is silent and the config stays as it is; with "on" it gets one plain line. It never stops a launch.""" from strata_control import split_engine as SE - if cfg.get("arch") == "deepseek41" or not SE.wanted(cfg): + if cfg.get("arch") == "deepseek41" or SE.mode(cfg) == "off": return from strata_control import engine_component as EC - def exe_for(n: int): + def exe_for(n: int, cc: int | None = None): exe = cfg.get("exe") try: real = EC.expand(exe, cfg, full=False) if EC.is_reference(exe) else exe except Exception: # noqa: BLE001 - no engine to look beside: no split return None - p = Path(str(real)).parent / f"strata-split-{n}" - return str(p) if p.is_file() else None + for name in ((f"strata-split-{n}-sm{cc}",) if cc else ()) + (f"strata-split-{n}",): # one build per architecture (FNX_ARCH is compile time) + p = Path(str(real)).parent / name + if p.is_file(): + return str(p) + return None try: decision = SE.apply_to_config(cfg, exe_for_cards=exe_for, allow_untested=os.environ.get("STRATA_SPLIT_ALLOW_UNTESTED") == "1") except Exception as e: # noqa: BLE001 - never stop a launch over an option - text = f"The all-cards split engine was left out ({type(e).__name__}). Using the normal layer split." - self.notices.append(text) - self.emit("config", text, None, level="warn") + if SE.mode(cfg) == "on": + text = f"The all-cards split engine was left out ({type(e).__name__}). Using the normal layer split." + self.notices.append(text) + self.emit("config", text, None, level="warn") return - self.notices.append(decision.line) - self.emit("config", decision.line, None) + if decision.quiet: + return + line = decision.line + (" Turn it off with: strata launch --split-engine off." if decision.use_split else "") + self.notices.append(line) + self.emit("config", line, None) def say_remembered_cards(self, base: dict) -> None: """A launch that names no cards keeps the cards the person chose earlier (`--gpu 0` is remembered by the model's settings). On a PC with more diff --git a/strata_cli/launch/settings.py b/strata_cli/launch/settings.py index d73ad98b0e..fd1e603950 100644 --- a/strata_cli/launch/settings.py +++ b/strata_cli/launch/settings.py @@ -26,6 +26,8 @@ ACCESS_WORDS = {"local": "This computer only", "lan": "My local network", "cloud TUNE_MODES = ("quick", "thorough", "skip") VISION_MODES = ("off", "on", "gpu", "cpu") MTP_MODES = ("on", "off") +#: strata_control/split_engine.py MODES: the all-cards split engine on NVIDIA cards (auto = by itself where it is supported, the default) +SPLIT_MODES = ("auto", "on", "off") #: strata_control/drafting.py MODES (tests/terminal/test_drafting.py keeps the two the same) DRAFTING_MODES = ("auto", "mtp", "dflash2", "off") SPEED_MODES = ("faster", "full") # DeepSeek: 5 experts per word (Faster) or all 6 (Full quality) @@ -123,6 +125,7 @@ class LaunchSettings: parallel: int | None = None # None = fit to the card speed: str | None = None # DeepSeek only: None = the default for this PC (faster up to 16 GB of graphics memory); faster | full drafting: str | None = None # None = Auto (recommended): the table in strata_control/drafting.py; mtp | dflash2 | off choose one. Saved in the launch config + split_engine: str | None = None # None = auto (the all-cards split engine runs by itself where it is supported); on | off. Saved in the preset and the launch config mtp: str | None = None # None = as installed (draft layer on); "off" starts without it (less graphics memory and RAM, slower); "on" overrides an installed "off" tune: str = "skip" # quick | thorough | skip tune_allow_small: bool = False # the "answer-changing" tick, off by default, as in the app @@ -345,6 +348,8 @@ def flags_text(s: LaunchSettings, *, preset: str | None = None) -> str: parts.append(f"--mtp {s.mtp}") if s.drafting: parts.append(f"--drafting {s.drafting}") + if s.split_engine: + parts.append(f"--split-engine {s.split_engine}") if s.speed == "full": parts.append("--full-quality") elif s.speed == "faster": diff --git a/strata_control/split_engine.py b/strata_control/split_engine.py index 5458e0d2f7..e13ee9bea8 100644 --- a/strata_control/split_engine.py +++ b/strata_control/split_engine.py @@ -1,14 +1,16 @@ -"""strata-split: when the all-cards split engine may run, and the run config for it. OFF by default, opt-in. +"""strata-split: when the all-cards split engine may run, and the run config for it. AUTOMATIC by default (mode "auto"), with an off switch. `strata-split-N` (src/split, from sFNX, MIT, Copyright (c) 2026 John Fink) gives every card a share of EVERY layer instead of some layers, and the cards exchange the layer sums through page-locked host memory (no peer access anywhere). On two RTX A6000 with -UD-Q4_K_XL it decodes 40-95% faster than the normal layer split and reads prompts 1.7-2.8x slower (phaseA-tests/sfnx/RESULTS.md, -section 8), so it is an option, never the default, until the owner has chosen. +UD-Q4_K_XL it decodes 40-95% faster than the normal layer split (phaseA-tests/sfnx/RESULTS.md). The owner's decision: it runs by itself whenever the +rule below says yes ("auto", the default), and `strata launch --split-engine off` (or "split_engine": "off" in the run config, or +STRATA_SPLIT_ENGINE=0) turns it off; "on" asks for it and says why in one line when it cannot run. In auto a "no" is silent: the normal +layer split starts, as before. This module is pure (no I/O besides reading GGUF directories): the launcher passes it facts and gets a Decision. The rule, from what has actually been run: - - the person turned it on (config key "split_engine": true, or `strata launch --split-engine on`); never otherwise; + - not turned off (mode(): "auto" by default; "on" is the same rule but a refusal is reported; "off" never); - Linux, NVIDIA cards, 2 to 4 of them, all the same model of card and memory size; - a card architecture and card count that have been run (TESTED): sm_86 on 2 cards today. Others build but stay off unless the caller says allow_untested (testers); the Decision says which part is untested in plain words; @@ -31,8 +33,10 @@ import pathlib import re from typing import Any -TESTED_CARD_COUNTS = (2,) # run with the host exchange: 2 cards (boston, 2x RTX A6000) -TESTED_ARCHS = (86,) # compute capability: sm_86 only +TESTED_CARD_COUNTS = (2,) # run with the host exchange: 2 cards (boston, 2x RTX A6000; srv118, 2x RTX PRO 6000) +TESTED_ARCHS = (86, 120) # compute capability: sm_86 (the 61-task suite, pictures, hashes) and sm_120 (decode, prompts, parallel, hashes, + # pictures; no suite there) +MODES = ("auto", "on", "off") TESTED_CONTEXT = 131072 MAX_CARDS = 4 LAYERS, EXPERTS = 48, 512 # Qwen3.8-Flash-Next @@ -82,6 +86,7 @@ class Decision: untested: list[str] = dataclasses.field(default_factory=list) # what about this setup nobody has run need_vram_gib: float = 0.0 need_ram_gib: float = 0.0 + quiet: bool = False # auto mode and a "no": the launch says nothing and starts the normal layer split @property def line(self) -> str: @@ -264,18 +269,43 @@ def _flag(args: list, name: str) -> str | None: return str(args[args.index(name) + 1]) if name in args and args.index(name) + 1 < len(args) else None -def wanted(cfg: dict, environ: dict | None = None) -> bool: - """The person turned the option on: "split_engine": true in the run config, or STRATA_SPLIT_ENGINE=1 in the environment (testers).""" +def mode(cfg: dict, environ: dict | None = None) -> str: + """"auto" (the default), "on" or "off". The run config's "split_engine" (true/false or the word; `strata launch --split-engine X` writes it) + and, over it, STRATA_SPLIT_ENGINE in the environment (testers). Anything it does not know is auto.""" import os - return cfg.get("split_engine") is True or (environ if environ is not None else os.environ).get("STRATA_SPLIT_ENGINE") == "1" + env = environ if environ is not None else os.environ + raw = env.get("STRATA_SPLIT_ENGINE") + if raw is None or not str(raw).strip(): + raw = cfg.get("split_engine") + if raw is True: + return "on" + if raw is False: + return "off" + return {"on": "on", "1": "on", "true": "on", "yes": "on", "off": "off", "0": "off", "false": "off", "no": "off"}.get(str(raw).strip().lower(), "auto") + + +def wanted(cfg: dict, environ: dict | None = None) -> bool: + """The split engine may be tried for this launch (anything but off).""" + return mode(cfg, environ) != "off" def apply_to_config(cfg: dict, *, exe_for_cards, system: str | None = None, allow_untested: bool = False, probe=None, ram=None, - scan=None, data_dir: str | None = None) -> Decision: - """Turn a normal run config into the split engine's config IN PLACE when the rule says yes, and say what was decided. - exe_for_cards(n) -> the path of strata-split-n or None (the engine package has none); probe(indexes) -> [Card]; ram() -> (total, - available) GiB; scan(first_shard) -> ModelFacts: the facts of this PC and model, replaceable for tests.""" + scan=None, data_dir: str | None = None, mode_: str | None = None) -> Decision: + """Turn a normal run config into the split engine's config IN PLACE when the mode and the rule say yes, and say what was decided. + exe_for_cards(n, cc) -> the path of the strata-split-n built for compute capability cc, or None (the engine package has none); + probe(indexes) -> [Card]; ram() -> (total, available) GiB; scan(first_shard) -> ModelFacts: the facts of this PC and model, replaceable + for tests. Mode "off": nothing happens, silently. Mode "auto": a refusal is `quiet` (the normal layer split starts without a word).""" + m = mode_ or mode(cfg) + if m == "off": + return Decision(False, ["the all-cards split engine is turned off"], quiet=True) + d = _apply(cfg, exe_for_cards=exe_for_cards, system=system, allow_untested=allow_untested, probe=probe, ram=ram, scan=scan, data_dir=data_dir) + if m == "auto" and not d.use_split: + d.quiet = True + return d + + +def _apply(cfg: dict, *, exe_for_cards, system, allow_untested, probe, ram, scan, data_dir) -> Decision: import os import pathlib import sys @@ -285,6 +315,14 @@ def apply_to_config(cfg: dict, *, exe_for_cards, system: str | None = None, allo native = _flag(args, "--native") if not native: return Decision(False, ["this model is not a single GGUF file set"]) + # choices the split engine does not honour: the normal layer split keeps them + if str(cfg.get("drafting") or "").lower() == "dflash2": + return Decision(False, ["DFlash2 drafting was chosen, which the all-cards split engine does not run"]) + if cfg.get("user_args") or cfg.get("replicas"): + return Decision(False, ["this run config has engine arguments of its own or replicas, which the all-cards split engine does not take"]) + kv = _flag(args, "--kv") + if kv not in (None, "int8"): + return Decision(False, [f"the conversation memory format is {kv}, the all-cards split engine keeps int8"]) gpus = cfg.get("gpu") indexes = [int(g) for g in gpus] if isinstance(gpus, list) else ([int(gpus)] if isinstance(gpus, int) else None) cards = (probe or probe_cards)(indexes) if system == "linux" else [] @@ -298,7 +336,7 @@ def apply_to_config(cfg: dict, *, exe_for_cards, system: str | None = None, allo allow_untested=allow_untested) if not d.use_split: return d - exe = exe_for_cards(d.cards) + exe = exe_for_cards(d.cards, cards[0].cc) if not exe: return Decision(False, [f"this engine package has no strata-split-{d.cards}"], d.cards) mtp = _flag(args, "--mtp") diff --git a/tests/split/test_split_engine.py b/tests/split/test_split_engine.py index fdf8a42781..a0efb4daa7 100644 --- a/tests/split/test_split_engine.py +++ b/tests/split/test_split_engine.py @@ -59,7 +59,7 @@ class Rule(unittest.TestCase): self.assertIn("same model", d.line) def test_untested_counts_archs_and_contexts_stay_off_unless_a_tester_allows_them(self): - for c in (cards(3), cards(2, cc=89), cards(2, cc=120)): + for c in (cards(3), cards(2, cc=89), cards(2, cc=90)): d = decide(cards=c) self.assertFalse(d.use_split) self.assertIn("only been run", d.line) @@ -184,7 +184,7 @@ class Apply(unittest.TestCase): "cwd": tmp, "tokenizer": "tok", "port": 8080, "gpu": [0, 1], "env": {}, "split_engine": True} def run_apply(self, cfg, *, cards_=None, avail=80.0, model=None, exe="/e/strata-split-2", **kw): - return S.apply_to_config(cfg, exe_for_cards=lambda n: exe, system=kw.pop("system", "linux"), probe=lambda idx: cards_ or cards(), + return S.apply_to_config(cfg, exe_for_cards=lambda n, cc=None: exe, system=kw.pop("system", "linux"), probe=lambda idx: cards_ or cards(), ram=lambda: (125.0, avail), scan=lambda path: model or udq4(), **kw) def test_a_good_pc_gets_the_split_config(self): @@ -222,15 +222,99 @@ class Apply(unittest.TestCase): with tempfile.TemporaryDirectory() as tmp: cfg = self.cfg(tmp) - d = S.apply_to_config(cfg, exe_for_cards=lambda n: "/e/x", system="linux", probe=lambda i: cards(), ram=lambda: (125.0, 80.0), scan=boom) + d = S.apply_to_config(cfg, exe_for_cards=lambda n, cc=None: "/e/x", system="linux", probe=lambda i: cards(), ram=lambda: (125.0, 80.0), scan=boom) self.assertFalse(d.use_split) self.assertIn("could not be read", d.line) - def test_wanted_is_opt_in(self): - self.assertFalse(S.wanted({}, {})) - self.assertFalse(S.wanted({"split_engine": False}, {})) - self.assertTrue(S.wanted({"split_engine": True}, {})) - self.assertTrue(S.wanted({}, {"STRATA_SPLIT_ENGINE": "1"})) + def test_modes_auto_is_the_default_and_off_is_the_switch(self): + self.assertEqual(S.mode({}, {}), "auto") + for raw, want in ((True, "on"), (False, "off"), ("on", "on"), ("off", "off"), ("auto", "auto"), ("OFF", "off"), ("nonsense", "auto"), (None, "auto")): + self.assertEqual(S.mode({"split_engine": raw}, {}), want, raw) + self.assertEqual(S.mode({"split_engine": "on"}, {"STRATA_SPLIT_ENGINE": "0"}), "off") # the environment wins (testers) + self.assertEqual(S.mode({"split_engine": "off"}, {"STRATA_SPLIT_ENGINE": "1"}), "on") + self.assertEqual(S.mode({}, {"STRATA_SPLIT_ENGINE": "off"}), "off") + self.assertEqual(S.mode({"split_engine": "off"}, {"STRATA_SPLIT_ENGINE": ""}), "off") # an empty variable is no variable + self.assertTrue(S.wanted({}, {})) + self.assertFalse(S.wanted({"split_engine": "off"}, {})) + + def test_auto_uses_the_split_where_it_is_supported_and_says_nothing_otherwise(self): + import copy + import tempfile + + with tempfile.TemporaryDirectory() as tmp: + cfg = self.cfg(tmp) + del cfg["split_engine"] # nothing asked: auto + d = self.run_apply(cfg) + self.assertTrue(d.use_split, d.reasons) + self.assertFalse(d.quiet) + self.assertEqual(cfg["exe"], "/e/strata-split-2") + for kw in (dict(cards_=cards(1)), dict(avail=20.0), dict(exe=None), dict(system="windows"), dict(model=udq4(routed_types={"Q6_K": 48})), + dict(cards_=cards(3)), dict(cards_=cards(2, cc=89))): + cfg = self.cfg(tmp) + del cfg["split_engine"] + before = copy.deepcopy(cfg) + d = self.run_apply(cfg, **kw) + self.assertFalse(d.use_split, kw) + self.assertTrue(d.quiet, kw) # silent: the launch goes on with the layer split + self.assertEqual(cfg, before, kw) + + def test_on_says_why_it_cannot_run(self): + import tempfile + + with tempfile.TemporaryDirectory() as tmp: + cfg = self.cfg(tmp) + cfg["split_engine"] = "on" + d = self.run_apply(cfg, cards_=cards(1)) + self.assertFalse(d.use_split) + self.assertFalse(d.quiet) + self.assertIn("two or more cards", d.line) + + def test_off_never_runs_and_changes_nothing(self): + import copy + import tempfile + + with tempfile.TemporaryDirectory() as tmp: + for off in ("off", False): + cfg = self.cfg(tmp) + cfg["split_engine"] = off + before = copy.deepcopy(cfg) + d = self.run_apply(cfg) + self.assertFalse(d.use_split) + self.assertTrue(d.quiet) + self.assertEqual(cfg, before) + + def test_choices_the_split_engine_does_not_honour_keep_the_layer_split(self): + import tempfile + + with tempfile.TemporaryDirectory() as tmp: + for change in (lambda c: c.update(drafting="dflash2"), lambda c: c.update(user_args=["--x"]), lambda c: c.update(replicas=2), + lambda c: c["args"].extend(["--kv", "q4_0"])): + cfg = self.cfg(tmp) + del cfg["split_engine"] + change(cfg) + d = self.run_apply(cfg) + self.assertFalse(d.use_split) + self.assertTrue(d.quiet) + cfg = self.cfg(tmp) + cfg["args"].extend(["--kv", "int8"]) + self.assertTrue(self.run_apply(cfg).use_split) + + def test_the_engine_is_picked_by_card_count_and_architecture(self): + import tempfile + + seen = [] + + def exe_for(n, cc=None): + seen.append((n, cc)) + return "/e/strata-split-2-sm120" + + with tempfile.TemporaryDirectory() as tmp: + cfg = self.cfg(tmp) + d = S.apply_to_config(cfg, exe_for_cards=exe_for, system="linux", probe=lambda i: cards(2, cc=120, name="NVIDIA RTX PRO 6000", vram_mib=97887), + ram=lambda: (125.0, 80.0), scan=lambda path: udq4()) + self.assertTrue(d.use_split, d.reasons) + self.assertEqual(seen, [(2, 120)]) + self.assertEqual(cfg["exe"], "/e/strata-split-2-sm120") class NoPeerAccess(unittest.TestCase): diff --git a/tests/terminal/test_split_engine_flag.py b/tests/terminal/test_split_engine_flag.py new file mode 100644 index 0000000000..a302666fd8 --- /dev/null +++ b/tests/terminal/test_split_engine_flag.py @@ -0,0 +1,46 @@ +"""`strata launch --split-engine auto|on|off`: the owner's switch for the all-cards split engine (strata_control/split_engine.py). +auto (nothing written) is the default; the choice is listed in --help, in the copyable flags, in the launch config and in a saved preset, so an +"off" survives updates and restarts; the launcher's apply_split_engine honours it (off: nothing, auto: silent on a refusal, on: one line).""" + +from __future__ import annotations + +import unittest + +from strata_cli.launch import settings as S +from strata_cli.launch.runner import derive_config +from strata_control import split_engine as SE +from tests.terminal.launch_support import run_cli + + +class Flag(unittest.TestCase): + BASE = {"exe": "component:strata-engine", "args": ["--pack", "/d/packs/x", "--mtp", "/d/mtp/rt"], "port": 8080, "model_name": "m"} + + def test_the_flag_is_listed_checked_copyable_and_saved_in_the_launch_config(self): + code, out, _ = run_cli(["launch", "--help"]) + self.assertIn("--split-engine", out) + self.assertIn("auto|on|off", out) + for mode in S.SPLIT_MODES: + cfg = derive_config(self.BASE, S.LaunchSettings(split_engine=mode), bool_flags=frozenset()) + self.assertEqual(cfg["split_engine"], mode) + self.assertEqual(SE.mode(cfg, {}), mode) + self.assertNotIn("split_engine", derive_config(self.BASE, S.LaunchSettings(), bool_flags=frozenset()), "nobody chose: auto writes nothing") + self.assertEqual(SE.mode(derive_config(self.BASE, S.LaunchSettings(), bool_flags=frozenset()), {}), "auto") + self.assertIn("--split-engine off", S.flags_text(S.LaunchSettings(split_engine="off"))) + self.assertNotIn("--split-engine", S.flags_text(S.LaunchSettings())) + code, out, err = run_cli(["launch", "--plan", "--split-engine", "sometimes"]) + self.assertNotEqual(code, 0) + + def test_a_saved_off_survives_a_new_launch_config_and_a_preset_round_trip(self): + s = S.LaunchSettings.from_dict(S.LaunchSettings(split_engine="off").to_dict()) + self.assertEqual(s.split_engine, "off") + self.assertIsNone(S.LaunchSettings.from_dict({}).split_engine) + # a config written earlier with "off" is kept when this launch names nothing + cfg = derive_config({**self.BASE, "split_engine": "off"}, S.LaunchSettings(), bool_flags=frozenset()) + self.assertEqual(cfg["split_engine"], "off") + # and the person's flag of this launch wins over the old file + cfg = derive_config({**self.BASE, "split_engine": "off"}, S.LaunchSettings(split_engine="on"), bool_flags=frozenset()) + self.assertEqual(cfg["split_engine"], "on") + + +if __name__ == "__main__": + unittest.main() From 15fb6ffe3f75ca4f71d87925aef073975001c9ac Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 2 Nov 2026 10:53:28 +0100 Subject: [PATCH 10/11] split: Auto drafting on a setup the split accepts runs the split with its MTP; DFlash2 or off chosen by the person keeps the layer split split_config writes "drafting": "mtp" (what the split engine runs), so serve/server.py's drafter step, which resolves Auto to DFlash2 where the engine has it, cannot add DFlash2 flags to the split engine's arguments; the fallback keeps the person's own drafting word (or none: Auto), so the layer split that starts instead gets DFlash2 as usual. The rule refuses (quietly in auto) for an explicit dflash2 or off, and for Auto on a card where the split has not been measured to decode faster than the layer split with DFlash2. Tests: all four cases, the card rule, the server's drafter step on a split config. --- serve/test_split_fallback.py | 23 ++++++++++++++++++++++ strata_control/split_engine.py | 18 ++++++++++++++++- tests/split/test_split_engine.py | 33 ++++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 1 deletion(-) diff --git a/serve/test_split_fallback.py b/serve/test_split_fallback.py index 62219d0aba..5eee16056f 100644 --- a/serve/test_split_fallback.py +++ b/serve/test_split_fallback.py @@ -97,6 +97,29 @@ class Fallback(unittest.TestCase): self.assertTrue(os.path.exists(log + ".split-engine")) # the normal engine will overwrite the log; the refusal stays readable self.assertEqual([s[0] for s in FakeEngine.started], ["/e/strata-split-2", NORMAL]) + def test_a_split_config_keeps_its_arguments_through_the_drafter_step(self): + """strata_control/split_engine.split_config writes "drafting": "mtp" (what the split engine runs), so the drafter step, which resolves Auto to + DFlash2 where the engine has it, adds no DFlash2 flag to the split engine's arguments (it would refuse them and every start would fall back).""" + from strata_control import split_engine as SE + + base = {"exe": NORMAL, "args": ["--pack", "/p", "--native", "/m/a.gguf", "--mtp", "/d/mtp/rt", "--layer-split", "auto"], "cwd": "/x", + "tokenizer": "/t", "port": 8080} + decision = SE.Decision(True, [], 2) + cfg = SE.split_config(base, decision, exe="/e/strata-split-2", native="/m/a.gguf", mtp_dir="/d/mtp/rt", draft_vocab="/d/v.bin", context=131072) + args = S.engine_args(cfg) + self.assertEqual(args[:2], ["--native", "/m/a.gguf"]) + self.assertNotIn("--draft", args) + self.assertNotIn("--draft-model", args) + self.assertEqual(args[args.index("--mtp") + 1], "/d/mtp/rt") + self.assertEqual(args[args.index("--spec") + 1], "6") + self.assertNotIn("--layer-split", args) + # the layer split that starts instead keeps the person's drafting word, or none (Auto) + self.assertNotIn("drafting", cfg["split_fallback"]) + cfg = SE.split_config({**base, "drafting": "auto"}, decision, exe="/e/strata-split-2", native="/m/a.gguf", mtp_dir="/d/mtp/rt", + draft_vocab="/d/v.bin", context=131072) + self.assertEqual(cfg["split_fallback"]["drafting"], "auto") + self.assertEqual(cfg["drafting"], "mtp") + def test_without_a_fallback_the_failure_stays_a_failure(self): cfg = split_cfg() del cfg["split_fallback"] diff --git a/strata_control/split_engine.py b/strata_control/split_engine.py index e13ee9bea8..6c546cda13 100644 --- a/strata_control/split_engine.py +++ b/strata_control/split_engine.py @@ -37,6 +37,9 @@ TESTED_CARD_COUNTS = (2,) # run with the host exchange: 2 cards (boston TESTED_ARCHS = (86, 120) # compute capability: sm_86 (the 61-task suite, pictures, hashes) and sm_120 (decode, prompts, parallel, hashes, # pictures; no suite there) MODES = ("auto", "on", "off") +#: cards (compute capability) on which Auto drafting resolves to split + MTP rather than layer split + DFlash2: the split decodes faster there +#: (phaseA-tests/sfnx/RESULTS.md section 17). Another card is not auto-split at all (TESTED_ARCHS), so it keeps Auto = layer split + DFlash2. +AUTO_SPLIT_BEATS_DFLASH2 = (86, 120) TESTED_CONTEXT = 131072 MAX_CARDS = 4 LAYERS, EXPERTS = 48, 512 # Qwen3.8-Flash-Next @@ -223,6 +226,11 @@ def split_config(base: dict, decision: Decision, *, exe: str, native: str, mtp_d # every expert in the cards' memory, no expert cache, no arena: the engine reads these two at start cfg["env"] = {**(base.get("env") or {}), "FNX_ARENA": "0", "FNX_EXPERT_RAM_GIB": "off"} cfg["split_fallback"] = {k: base[k] for k in ("exe", "args", "env", "layer_split", "replicas", "user_args", "drafting", "cwd") if k in base} + # The split engine runs the model's own draft layer (the MTP) and nothing else. Saying so in the config ("drafting": "mtp") keeps serve/server.py's + # drafter step, which resolves Auto to DFlash2 where the engine has it, from adding DFlash2 flags to the split engine's arguments (it would refuse them + # and every start would fall back to the layer split). The fallback keeps the person's own choice (or none: Auto), so the layer split that starts + # instead gets DFlash2 as usual. + cfg["drafting"] = "mtp" cfg["split_engine_note"] = decision.line return cfg @@ -316,8 +324,14 @@ def _apply(cfg: dict, *, exe_for_cards, system, allow_untested, probe, ram, scan if not native: return Decision(False, ["this model is not a single GGUF file set"]) # choices the split engine does not honour: the normal layer split keeps them - if str(cfg.get("drafting") or "").lower() == "dflash2": + # Drafting: Auto (nothing written, or "auto") on a setup the split accepts runs the split with its MTP: measured faster to decode than the layer + # split with DFlash2 on both tested cards (AUTO_SPLIT_BEATS_DFLASH2, numbers in docs/SPLIT_ENGINE.md). The person's own "dflash2" (or "off", which the + # split cannot do: it needs the draft layer) keeps the layer split; "mtp" is what the split runs. + chosen = str(cfg.get("drafting") or "auto").lower() + if chosen == "dflash2": return Decision(False, ["DFlash2 drafting was chosen, which the all-cards split engine does not run"]) + if chosen == "off": + return Decision(False, ["drafting is off, and the all-cards split engine needs the draft layer"]) if cfg.get("user_args") or cfg.get("replicas"): return Decision(False, ["this run config has engine arguments of its own or replicas, which the all-cards split engine does not take"]) kv = _flag(args, "--kv") @@ -336,6 +350,8 @@ def _apply(cfg: dict, *, exe_for_cards, system, allow_untested, probe, ram, scan allow_untested=allow_untested) if not d.use_split: return d + if chosen == "auto" and not all(c.cc in AUTO_SPLIT_BEATS_DFLASH2 for c in cards): + return Decision(False, ["on this card the layer split with DFlash2 has not been measured slower than the all-cards split engine"], d.cards) exe = exe_for_cards(d.cards, cards[0].cc) if not exe: return Decision(False, [f"this engine package has no strata-split-{d.cards}"], d.cards) diff --git a/tests/split/test_split_engine.py b/tests/split/test_split_engine.py index a0efb4daa7..8c6b8ed70b 100644 --- a/tests/split/test_split_engine.py +++ b/tests/split/test_split_engine.py @@ -299,6 +299,39 @@ class Apply(unittest.TestCase): cfg["args"].extend(["--kv", "int8"]) self.assertTrue(self.run_apply(cfg).use_split) + def test_drafting_auto_resolves_to_the_split_with_its_mtp_and_the_fallback_keeps_the_layer_split_choice(self): + import tempfile + + with tempfile.TemporaryDirectory() as tmp: + for chosen, split in ((None, True), ("auto", True), ("mtp", True), ("dflash2", False), ("off", False)): + cfg = self.cfg(tmp) + del cfg["split_engine"] + if chosen: + cfg["drafting"] = chosen + before_fallback = {k: v for k, v in cfg.items() if k == "drafting"} + d = self.run_apply(cfg) + self.assertEqual(d.use_split, split, chosen) + if split: + # Auto/MTP: the split engine runs its MTP; the config says so, so serve/server.py's drafter step (Auto = DFlash2) leaves its arguments alone + self.assertEqual(cfg["drafting"], "mtp", chosen) + self.assertEqual(cfg["split_fallback"].get("drafting"), before_fallback.get("drafting"), chosen) # the layer split keeps the person's word, or Auto + self.assertNotIn("--draft", cfg["args"]) + else: + self.assertEqual(cfg.get("drafting"), chosen) # untouched: the layer split gets DFlash2 as chosen + self.assertNotIn("split_fallback", cfg) + + def test_auto_needs_a_card_where_the_split_decodes_faster_than_the_layer_split_with_dflash2(self): + import tempfile + + with tempfile.TemporaryDirectory() as tmp: + cfg = self.cfg(tmp) + del cfg["split_engine"] + d = self.run_apply(cfg, cards_=cards(2, cc=89), allow_untested=True) # a tester allowed it, but nobody measured it there + self.assertFalse(d.use_split) + self.assertIn("DFlash2", d.line) + cfg["drafting"] = "mtp" # the person asked for the MTP: no comparison to win + self.assertTrue(self.run_apply(cfg, cards_=cards(2, cc=89), allow_untested=True).use_split) + def test_the_engine_is_picked_by_card_count_and_architecture(self): import tempfile From ea2aed12cdf71b1abbbb335ede41a9dd14b69f06 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 2 Nov 2026 11:13:09 +0100 Subject: [PATCH 11/11] split: build option STRATA_SPLIT_PF_JOB (64 default, 128): rows of one expert per prompt-path job, so a weight tile is dequantized once for twice the tokens Default unchanged (64). The expert prompt kernel's token-tile count follows PF_JOB (it was fixed at four). --- src/split/CMakeLists.txt | 3 ++- src/split/src/kernels.hpp | 9 +++++++-- src/split/src/moe_mma.cuh | 8 ++++++-- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/split/CMakeLists.txt b/src/split/CMakeLists.txt index db753f4ea4..7100944dd9 100644 --- a/src/split/CMakeLists.txt +++ b/src/split/CMakeLists.txt @@ -12,6 +12,7 @@ # the engine refuses a card of any other architecture set(STRATA_SPLIT_CARDS "2" CACHE STRING "card counts strata-split is built for (2, 3, 4)") set(STRATA_SPLIT_ARCH "" CACHE STRING "compute capability strata-split is built for (e.g. 86)") +set(STRATA_SPLIT_PF_JOB "64" CACHE STRING "rows of one expert per prompt-path job: 64 (default) or 128") if(NOT STRATA_ENABLE_CUDA OR WIN32 OR APPLE) message(STATUS "STRATA_BUILD_SPLIT: needs a Linux CUDA build, skipped") @@ -50,7 +51,7 @@ foreach(_n ${STRATA_SPLIT_CARDS}) add_executable(${_t} ${_sp_engine} ${_sp_kparts}) target_include_directories(${_t} PRIVATE ${_sp}/src ${_sp}/tools ${STRATA_GGML_DIR}/ggml/src/ggml-cuda ${STRATA_GGML_DIR}/ggml/src ${STRATA_GGML_DIR}/ggml/include) - target_compile_definitions(${_t} PRIVATE FNX_NCARD=${_n} FNX_ARCH=${STRATA_SPLIT_ARCH} FNX_27B=0 FNX_HOSTRING=1 + target_compile_definitions(${_t} PRIVATE FNX_NCARD=${_n} FNX_ARCH=${STRATA_SPLIT_ARCH} FNX_27B=0 FNX_HOSTRING=1 FNX_PF_JOB=${STRATA_SPLIT_PF_JOB} FNX_DIR="${_sp}") target_compile_options(${_t} PRIVATE $<$:--use_fast_math --expt-relaxed-constexpr -Wno-deprecated-gpu-targets>) set_target_properties(${_t} PROPERTIES CUDA_ARCHITECTURES "${STRATA_SPLIT_ARCH}-real" CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON diff --git a/src/split/src/kernels.hpp b/src/split/src/kernels.hpp index c344e5f3c3..b821631254 100644 --- a/src/split/src/kernels.hpp +++ b/src/split/src/kernels.hpp @@ -22,8 +22,13 @@ struct Job { int out[MAXT]; // output rows }; -// the prompt path's expert jobs: up to PF_JOB rows of one expert -constexpr int PF_JOB = 64; +// the prompt path's expert jobs: up to PF_JOB rows of one expert (64: four 16-token tiles per job; 128: eight, the expert's weight tile is then +// dequantized once for twice the tokens; a build option, STRATA_SPLIT_PF_JOB) +#ifndef FNX_PF_JOB +#define FNX_PF_JOB 64 +#endif +constexpr int PF_JOB = FNX_PF_JOB; +static_assert(PF_JOB == 64 || PF_JOB == 128, "PF_JOB: 64 or 128"); struct BigJob { int w; int n; diff --git a/src/split/src/moe_mma.cuh b/src/split/src/moe_mma.cuh index 9702253374..ea489067f0 100644 --- a/src/split/src/moe_mma.cuh +++ b/src/split/src/moe_mma.cuh @@ -280,8 +280,12 @@ template __global__ void __launch_bounds__(MM_THREADS) k_moe_mma(MoeW w, const BigJob* __restrict__ jobs, const int* __restrict__ njobs, const __half* __restrict__ x, int ldx, float* __restrict__ out) { using namespace nvcuda; - constexpr int WR = BM / 32, WT = MM_THREADS / 32 / WR, TT = 4 / WT, NP = BM / MM_PASS, LO = 16 * TT; - static_assert(WR * WT == MM_THREADS / 32 && TT * WT == 4 && NP * MM_PASS == BM, "warp layout"); + constexpr int MM_NT = PF_JOB / 16; // token tiles of a job + constexpr int WR = BM / 32, WT = MM_THREADS / 32 / WR, TT = MM_NT / WT, NP = BM / MM_PASS, LO = 16 * TT; + static_assert(WR * WT == MM_THREADS / 32 && TT * WT == MM_NT && NP * MM_PASS == BM, "warp layout"); +#if FNX_ARCH < 80 + static_assert(PF_JOB == 64, "the m8n8k4 path is laid out for 64-row jobs"); +#endif const int ji = blockIdx.y; if (ji >= *njobs) return; __shared__ BigJob jb;