diff --git a/CMakeLists.txt b/CMakeLists.txt index c7ee9dcf..bd77b562 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -39,6 +39,7 @@ option(STRATA_PREFILL_MMQ "Build the optional GGML MMQ prefill path for HIP" OFF # every kernel when it starts (CUDA_MODULE_LOADING=EAGER), so these took ~5 MB of VRAM - 1-3 expert slots - from every # model, and the UD-Q4_K_XL prompt is SSD-bound with or without them (docs/UNSLOTH_Q4.md) option(STRATA_MMQ_KQUANTS "Build the CUDA MMQ prompt kernels for Q4_K / Q5_K / Q5_1 experts" OFF) +option(STRATA_ORCA_Q4KS_MMQ "Build the GGML Q5_0 MMQ instance for OrcaRouter Q4_K_S" OFF) if(STRATA_PREFILL_MMQ AND NOT STRATA_ENABLE_HIP) message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_ENABLE_HIP=ON") endif() @@ -778,6 +779,9 @@ set(STRATA_GGML_DIR "" CACHE PATH "llama.cpp checkout to take ggml from (empty: if(STRATA_PREFILL_MMQ AND NOT STRATA_NATIVE_EXPERTS) message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_NATIVE_EXPERTS=ON for GGML sources") endif() +if(STRATA_ORCA_Q4KS_MMQ AND NOT STRATA_NATIVE_EXPERTS) + message(FATAL_ERROR "STRATA_ORCA_Q4KS_MMQ requires STRATA_NATIVE_EXPERTS=ON for GGML sources") +endif() if(STRATA_NATIVE_EXPERTS) enable_language(C) set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) @@ -826,6 +830,11 @@ if(STRATA_NATIVE_EXPERTS) endif() target_link_libraries(strata_kernels_cpu PUBLIC ggml-cpu ggml-base) target_compile_definitions(strata_kernels_cpu PUBLIC STRATA_NATIVE_EXPERTS=1) + set(_strata_mmq_types q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0) + # #296: OrcaRouter Q4_K_S's Q5_0 experts (Q4_K and Q5_1 come with STRATA_MMQ_KQUANTS on CUDA, S5's branch) + if(STRATA_ORCA_Q4KS_MMQ) + list(APPEND _strata_mmq_types q5_0) + endif() if(STRATA_ENABLE_CUDA) # prompt-speed plan step 2b: llama.cpp's MMQ kernels (ggml-cuda, MIT) for the prompt path's experts, compiled # from the same checkout as ggml above - only mmq.cuh's instances for the packs' types and the quantizer, with @@ -837,9 +846,10 @@ if(STRATA_NATIVE_EXPERTS) endif() set(_strata_mmq ${_strata_gg}/src/ggml-cuda) add_library(strata_mmq STATIC src/prefill/moe_mmq.cu src/prefill/ggml_cuda_host.cu ${_strata_mmq}/quantize.cu) - # q8_0: the drafter's matrices (E-9); with STRATA_MMQ_KQUANTS q4_k q5_k q5_1, the experts of Unsloth's UD-Q4_K_XL - # (docs/UNSLOTH_Q4.md; the dispatch follows eddoursul/Strata 7706c1b) - set(_strata_mmq_cuda_types q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0) + # q8_0: the drafter's matrices (E-9); STRATA_ORCA_Q4KS_MMQ adds q5_0 (#296, in _strata_mmq_types), and + # STRATA_MMQ_KQUANTS q4_k q5_k q5_1, the experts of Unsloth's UD-Q4_K_XL (docs/UNSLOTH_Q4.md; the dispatch + # follows eddoursul/Strata 7706c1b) + set(_strata_mmq_cuda_types ${_strata_mmq_types}) if(STRATA_MMQ_KQUANTS) list(APPEND _strata_mmq_cuda_types q4_k q5_k q5_1) endif() @@ -856,6 +866,9 @@ if(STRATA_NATIVE_EXPERTS) if(STRATA_MMQ_KQUANTS) target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_KQUANTS=1) endif() + if(STRATA_ORCA_Q4KS_MMQ) + target_compile_definitions(strata_mmq PRIVATE STRATA_ORCA_Q4KS_MMQ=1) + endif() target_link_libraries(strata_prefill PUBLIC strata_mmq) target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1) if(STRATA_BUILD_TESTS AND STRATA_MMQ_KQUANTS) @@ -881,7 +894,7 @@ if(STRATA_NATIVE_EXPERTS) src/prefill/moe_mmq.cu src/prefill/ggml_cuda_host.cu "${_strata_mmq}/quantize.cu") - foreach(_t q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0) + foreach(_t IN LISTS _strata_mmq_types) list(APPEND _strata_mmq_sources "${_strata_mmq}/template-instances/mmq-instance-${_t}.cu") endforeach() set_source_files_properties(${_strata_mmq_sources} PROPERTIES LANGUAGE HIP) @@ -890,6 +903,9 @@ if(STRATA_NATIVE_EXPERTS) PRIVATE "${_strata_gg}/include" "${_strata_gg}/src" "${_strata_mmq}" PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) target_compile_definitions(strata_mmq PRIVATE GGML_USE_HIP=1) + if(STRATA_ORCA_Q4KS_MMQ) + target_compile_definitions(strata_mmq PRIVATE STRATA_ORCA_Q4KS_MMQ=1) + endif() target_link_libraries(strata_mmq PUBLIC ggml-base hip::host roc::hipblas) target_link_libraries(strata_prefill PUBLIC strata_mmq) target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1) @@ -920,11 +936,24 @@ if(STRATA_NATIVE_EXPERTS) set_tests_properties(native_expert_parity_${_name} PROPERTIES TIMEOUT 120) endforeach() add_test(NAME native_expert_parity_q5_1_min COMMAND native_expert_parity --q5_1-min) + # #290: the BF16 token embedding (--embd-gguf) gathered and dequantized bit for bit + add_test(NAME native_expert_parity_bf16_embd COMMAND native_expert_parity --bf16-embd) # a pair without GPU kernels (Q6_K gate/up) is refused by native_expert_supported, not run add_test(NAME native_expert_parity_refuses_q6_K COMMAND native_expert_parity --synthetic q6_K/q8_0) set_tests_properties(native_expert_parity_refuses_q6_K PROPERTIES WILL_FAIL TRUE) endif() endif() + # #296's real-weight checks (OrcaRouter Q4_K_S files; docs/ORCA_Q4_K_S.md) - test programs, not part of a release + if(STRATA_ENABLE_CUDA AND STRATA_BUILD_TESTS) + add_executable(ple_q5_parity src/kernels/ple_q5_parity.cpp) + target_link_libraries(ple_q5_parity PRIVATE strata_kernels strata_artifact ggml-base ${_strata_gpu_runtime_target}) + add_executable(q5_projection_parity src/kernels/q5_projection_parity.cpp) + target_include_directories(q5_projection_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(q5_projection_parity PRIVATE strata_kernels strata_artifact ggml-base ${_strata_gpu_runtime_target}) + # #291: the FP8 PLE table (tools/ple_fp8_pack.py) through PleTable vs the checkpoint's own values + add_executable(ple_fp8_parity src/kernels/ple_fp8_parity.cpp) + target_link_libraries(ple_fp8_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + endif() endif() if(STRATA_ENABLE_CUDA AND STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/hit_cpu_order_parity.cu") diff --git a/bench/results/2026-09-30-tc-gemv-sm75/README.md b/bench/results/2026-09-30-tc-gemv-sm75/README.md new file mode 100644 index 00000000..8eaf9026 --- /dev/null +++ b/bench/results/2026-09-30-tc-gemv-sm75/README.md @@ -0,0 +1,57 @@ +# BF16 GEMV on Turing tensor cores (sm_75): measured negative + +i7-8700K + RTX 2070 8 GB (sm_75, 36 SMs), engine 0.1.27 tree (`bf16_gemv.cu` is unchanged through 0.1.30), +qwen3.8-flash-next (~125.7B MoE, GGUF-verified) Q2_0 in production. Isolated benchmark only - +[`bench_tc_gemv.cu`](bench_tc_gemv.cu) touches nothing in the inference path. Question: the QSA prompt attention +already rides the Turing tensor cores (`mma.sync.m16n8k8`, the #270 path); can the decode GEMVs do the same? + +## Setup + +- Baseline: the production `bf16_gemv` warp kernel, transcribed verbatim +- TC variant: `mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32` on BF16->FP16 (the sm_75 MMA has native f16 only). + BF16->FP16 conversion is exact (0 / 2,000,000 values inexact - bf16's 7-bit mantissa fits in fp16's 10 bits); the + A-fragment packing is the same one #270 validated (`a0` = row `gid`, k columns `2t..2t+1`; broadcast makes + `a0 == a1 == {x[2t], x[2t+1]}`) +- Three TC variants to cover the conversion overhead from every angle: W preconverted to fp16 once at load + (`pc`), W converted in-register every call (`in`), and a fused ks=1 form that writes the output directly and skips + the reduce kernel (`fused`) +- The k-split across blocks (`ks`) is swept over all values that divide n_in, and the best is reported - the TC + kernel gets its best occupancy +- Parity against an fp64 host reference; 2000 iterations x 3 reps, warmed CUDA events + +## Results (best TC config per shape) + +| Shape (decode, n_in = 2560, BF16 W) | Baseline us | Best TC us | Speedup | Config | +| --- | ---: | ---: | ---: | --- | +| ssm_alpha/beta [2560, 48] | 8.73 | 11.32 | 0.77x | pc, ks=16 | +| indexer.k_proj [2560, 128] | 7.14 | 12.09 | 0.59x | pc, ks=16 | +| indexer.q_proj / router [2560, 512] | 9.48 | 15.78 | 0.60x | pc, ks=4 | +| ple_value [2560, 2560] | 35.08 | 77.73 | 0.45x | pc, ks=40 | + +- Numerics pass: TC max error vs fp64 reference 1.7e-6 .. 7.2e-6 (fp16-accumulation level), baseline + 0.7e-6 .. 2.3e-6. The TC variant computes the same thing, it is just slower. +- The warp kernel is already bandwidth-bound at 276-374 GB/s effective W bandwidth (374 GB/s on the 13 MB + [2560, 2560] shape); the TC path reaches only 166-169 GB/s (4-byte lane loads, conversion instructions, in-tile + launch overhead). +- A single-token GEMV broadcasts one token across the whole m16 MMA tile, so 15/16 of the MMA throughput is thrown + away - but the baseline is not compute-bound, so the wasted throughput buys nothing. The k-split sweep and the + fused variant do not recover it. +- One-time W conversion cost is negligible (2 ms for 13 MB), so preconverting W for the TC path does not help. + +## How to rerun + +``` +nvcc -arch=sm_75 -O3 -o bench_tc_gemv.exe bench_tc_gemv.cu +./bench_tc_gemv.exe +``` + +Prints the table above, per-shape latency/parity and the conversion exactness scan. On a newer card, adjust +`-arch`; the packed-A layout comment in the source documents the fragment mapping it relies on. + +## Conclusion + +**Keep the warp kernel. Tensor cores are not a promising direction for the decode GEMVs on sm_75**, and this was a +measured loss (1.3-2.2x slower), not a failed attempt to optimize. The Turing MMA stays worthwhile where the input +really has m16 rows of work: the QSA prompt-attention tiles, which is where #270 uses it. Someone looking to +re-evaluate on future hardware (a card with native bf16 or denser GEMV batching) can rerun this instead of +rebuilding it. \ No newline at end of file diff --git a/bench/results/2026-09-30-tc-gemv-sm75/bench_tc_gemv.cu b/bench/results/2026-09-30-tc-gemv-sm75/bench_tc_gemv.cu new file mode 100644 index 00000000..bead5e33 --- /dev/null +++ b/bench/results/2026-09-30-tc-gemv-sm75/bench_tc_gemv.cu @@ -0,0 +1,305 @@ +// bench_tc_gemv.cu - ISOLATED benchmark: BF16 GEMV baseline vs Tensor Core (mma.m16n8k8, BF16->FP16) on sm_75. +// Nothing in the engine changes. Shapes are the REAL Strata decode GEMVs (BF16 weights, n_in = n_embd = 2560): +// ssm_alpha / ssm_beta [2560, 48] project_bf16(split=true) -> bf16_gemv_split(TPR=32) -> warp kernel +// indexer.k_proj [2560, 128] project_bf16(split=false) -> bf16_gemv -> warp kernel +// indexer.q_proj / ffn_gate_inp / mlp.gate [2560, 512] warp / split(TPR=32) -> warp kernel +// ple_value [2560, 2560] warp +// Baseline = bf16_gemv_warp_kernel transcribed verbatim from src/kernels/cuda/bf16_gemv.cu (production). +// TC variant = same maths; A = x broadcast down m16 (single-token GEMV), k-chunk = 8; +// (a) W preconverted bf16->fp16 once, x converted in-kernel (timed) [tc_preconv] +// (b) fully inline: W read as bf16 and converted in-register [tc_inline] +// Numerics: fp64 host reference; max abs err for baseline and both TC variants; bf16->fp16 exactness scan. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define CHECK(e) do { cudaError_t err_ = (e); if (err_ != cudaSuccess) { \ + fprintf(stderr, "CUDA %s:%d %s\n", __FILE__, __LINE__, cudaGetErrorString(err_)); exit(1); } } while (0) + +__device__ __forceinline__ float bf16_f32(uint16_t v) { return __int_as_float((int) ((unsigned) v << 16)); } +static float bf16_f32_host(uint16_t v) { unsigned u = (unsigned) v << 16; float f; memcpy(&f, &u, 4); return f; } +static uint16_t f32_bf16_host(float f) { + unsigned u, r; memcpy(&u, &f, 4); + r = ((u >> 16) ^ (u >> 15)) & 1; u += 0x7fff + r; + return (uint16_t) (u >> 16); +} + +// ============ baseline: production warp kernel (verbatim semantics from bf16_gemv.cu) ============ +__global__ void gemv_warp(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, + float* __restrict__ y, long long n_in, long long n_out) { + const long long o = (long long) blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5); + if (o >= n_out) return; + const int lane = threadIdx.x & 31; + const uint16_t* row = w + o * n_in; + float acc = 0.0f; + for (long long i = lane; i < n_in; i += 32) + acc += bf16_f32(x[i]) * bf16_f32(row[i]); + for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, off); + if (lane == 0) y[o] = acc; +} + +// ============ TC: A(x) broadcast, k-split over blocks, partial D row 0 -> scratch ============ +// A fragment (m16n8k8, .f16): lane l: a0 = A[m=l>>2][k=2(l&3)], a1 = A[m][k=2(l&3)+1], +// a2/a3 = same cols at row m+8. Broadcast => a2=a0, a3=a1. +// B fragment (.f16, col-major): lane l: b0 = B[k=2(l&3)][n=(l>>2)], b1 = B[k=2(l&3)+1][n]. +// B[k][n] = W[n][k], so lane l loads W[n][2(l&3)], W[n][2(l&3)+1] - coalesced within the row. +// D fragment: c0/c1 = D[m=l>>2][cols 2(l&3), +1], c2/c3 = row m+8. All m rows identical -> row 0. +__global__ void tc_preconv(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_f, + float* __restrict__ partials, long long n_in, long long n_out, int ks) { + const int tile = blockIdx.x, ks_i = blockIdx.y, lane = threadIdx.x & 31; + const long long n_base = (long long) tile * 8; + const long long k_per = n_in / (long long) ks; + const long long k0 = (long long) ks_i * k_per; + const int t2 = 2 * (lane & 3); + float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f; + for (long long kk0 = k0; kk0 < k0 + k_per; kk0 += 8) { + // A (2 x f16x2): a0 = {A[m][2t], A[m+8][2t]}, a1 = {A[m][2t+1], A[m+8][2t+1]} (broadcast -> dup halves) + unsigned xh = (unsigned) x_b[kk0 + t2] | ((unsigned) x_b[kk0 + t2 + 1] << 16); + // fp16 conversion in-register: bf16 -> f32 -> f16 (exact within fp16 range) + __half2 ha = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16))); + __half2 hb = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16))); + unsigned a0 = *reinterpret_cast(&ha); + unsigned a1 = *reinterpret_cast(&hb); + // B is already fp16 here: load as __half2 directly (bf16 path must NOT convert twice) + __half2 wbh = *reinterpret_cast(&w_f[(n_base + (lane >> 2)) * n_in + kk0 + t2]); + unsigned b0 = *reinterpret_cast(&wbh); + asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" + : "+f"(c0), "+f"(c1), "+f"(c2), "+f"(c3) + : "r"(a0), "r"(a1), "r"(b0)); + } + if (lane < 4) { float* p = partials + (size_t) (tile * ks + ks_i) * 8; p[t2] = c0; p[t2 + 1] = c1; } +} + +// same, but W stays bf16 and converts in-register (fully fair per-call cost) +__global__ void tc_inline(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_b, + float* __restrict__ partials, long long n_in, long long n_out, int ks) { + const int tile = blockIdx.x, ks_i = blockIdx.y, lane = threadIdx.x & 31; + const long long n_base = (long long) tile * 8; + const long long k_per = n_in / (long long) ks; + const long long k0 = (long long) ks_i * k_per; + const int t2 = 2 * (lane & 3); + float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f; + for (long long kk0 = k0; kk0 < k0 + k_per; kk0 += 8) { + unsigned xh = (unsigned) x_b[kk0 + t2] | ((unsigned) x_b[kk0 + t2 + 1] << 16); + __half2 ha = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16))); + __half2 hb = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16))); + unsigned a0 = *reinterpret_cast(&ha); + unsigned a1 = *reinterpret_cast(&hb); + const uint16_t* wbv = w_b + (n_base + (lane >> 2)) * n_in + kk0 + t2; + __half2 wbh = __floats2half2_rn(bf16_f32(wbv[0]), bf16_f32(wbv[1])); + unsigned b0 = *reinterpret_cast(&wbh); + asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" + : "+f"(c0), "+f"(c1), "+f"(c2), "+f"(c3) + : "r"(a0), "r"(a1), "r"(b0)); + } + if (lane < 4) { float* p = partials + (size_t) (tile * ks + ks_i) * 8; p[t2] = c0; p[t2 + 1] = c1; } +} + +__global__ void tc_reduce(const float* __restrict__ partials, float* __restrict__ y, long long n_out, int ks) { + const long long o = blockIdx.x * blockDim.x + threadIdx.x; + if (o >= n_out) return; + float s = 0.f; + for (int q = 0; q < ks; ++q) s += partials[(size_t) ((o >> 3) * ks + q) * 8 + (o & 7)]; + y[o] = s; +} + +// variant with the OTHER candidate A layout: a0 = {A[gid][2t], A[gid+8][2t]} (same k-col, two rows), +// a1 = same for col 2t+1. Broadcast => both halves of a0 hold x[2t], both halves of a1 hold x[2t+1]. +__global__ void tc_dupcol(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_b, + float* __restrict__ partials, long long n_in, long long n_out, int ks) { + const int tile = blockIdx.x, ks_i = blockIdx.y, lane = threadIdx.x & 31; + const long long n_base = (long long) tile * 8; + const long long k_per = n_in / (long long) ks; + const long long k0 = (long long) ks_i * k_per; + const int t2 = 2 * (lane & 3); + float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f; + for (long long kk0 = k0; kk0 < k0 + k_per; kk0 += 8) { + __half2 ha = __floats2half2_rn(bf16_f32(x_b[kk0 + t2]), bf16_f32(x_b[kk0 + t2])); + __half2 hb = __floats2half2_rn(bf16_f32(x_b[kk0 + t2 + 1]), bf16_f32(x_b[kk0 + t2 + 1])); + unsigned a0 = *reinterpret_cast(&ha); + unsigned a1 = *reinterpret_cast(&hb); + const uint16_t* wbv = w_b + (n_base + (lane >> 2)) * n_in + kk0 + t2; + __half2 wbh = __floats2half2_rn(bf16_f32(wbv[0]), bf16_f32(wbv[1])); + unsigned b0 = *reinterpret_cast(&wbh); + asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" + : "+f"(c0), "+f"(c1), "+f"(c2), "+f"(c3) + : "r"(a0), "r"(a1), "r"(b0)); + } + if (lane < 4) { float* p = partials + (size_t) (tile * ks + ks_i) * 8; p[t2] = c0; p[t2 + 1] = c1; } +} + +// FUSED, ks=1 only: with a single k-fragment the partial IS the answer -> write y directly, no reduce kernel, +// no scratch. Fully inline bf16 W conversion (fairest per-call TC cost). +__global__ void tc_fused(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_b, + float* __restrict__ y, long long n_in, long long n_out) { + const int tile = blockIdx.x, lane = threadIdx.x & 31; + const long long n_base = (long long) tile * 8; + const int t2 = 2 * (lane & 3); + float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f; + for (long long kk0 = 0; kk0 < n_in; kk0 += 8) { + __half2 ha = __floats2half2_rn(bf16_f32(x_b[kk0 + t2]), bf16_f32(x_b[kk0 + t2 + 1])); + __half2 hb = ha; // broadcast: row gid+8 = row gid (single-token GEMV) + unsigned a0 = *reinterpret_cast(&ha); + unsigned a1 = *reinterpret_cast(&hb); + const uint16_t* wbv = w_b + (n_base + (lane >> 2)) * n_in + kk0 + t2; + __half2 wbh = __floats2half2_rn(bf16_f32(wbv[0]), bf16_f32(wbv[1])); + unsigned b0 = *reinterpret_cast(&wbh); + asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" + : "+f"(c0), "+f"(c1), "+f"(c2), "+f"(c3) + : "r"(a0), "r"(a1), "r"(b0)); + } + if (lane < 4) { y[n_base + t2] = c0; y[n_base + t2 + 1] = c1; } +} + +int main() { + CHECK(cudaSetDevice(0)); + cudaDeviceProp prop; CHECK(cudaGetDeviceProperties(&prop, 0)); + printf("device: %s, SMs %d, capability %d.%d\n", prop.name, prop.multiProcessorCount, prop.major, prop.minor); + + struct Shape { const char* name; long long n_in, n_out; }; + Shape shapes[] = { + {"ssm_alpha/beta [2560,48]", 2560, 48}, + {"indexer.k_proj [2560,128]", 2560, 128}, + {"q_proj/router [2560,512]", 2560, 512}, + {"ple_value [2560,2560]", 2560, 2560}, + }; + auto rng = [](unsigned& s) { s = s * 1664525u + 1013904223u; return (float) ((s >> 8) & 0xFFFF) / 65535.0f - 0.5f; }; + const int ITERS = 2000, WARM = 300; + + printf("\n%-26s %13s | %s\n", "shape", "baseline us", "tc variants (pc = W preconverted, in = inline conversion, fused = no reduce), speedup vs baseline"); + printf("%s\n", std::string(150, '-').c_str()); + + for (auto& sh : shapes) { + const long long n_in = sh.n_in, n_out = sh.n_out; + const size_t wn = (size_t) n_out * n_in; + std::vector hw(wn), hx(n_in), hf(wn); + std::vector hyb(n_out), hypc(n_out), hyin(n_out), hyfu(n_out); + std::vector href(n_out); + unsigned seed = 991u + (unsigned) (n_out & 0xFFF); + for (size_t i = 0; i < wn; ++i) hw[i] = f32_bf16_host(rng(seed) * 0.3f); + for (long long i = 0; i < n_in; ++i) hx[i] = f32_bf16_host(rng(seed) * 3.0f); + for (long long o = 0; o < n_out; ++o) { + double s = 0.0; + for (long long i = 0; i < n_in; ++i) s += (double) bf16_f32_host(hx[i]) * (double) bf16_f32_host(hw[(size_t) o * n_in + i]); + href[o] = s; + } + // preconvert W to fp16 (bf16 -> fp16 is exact within fp16 range) + for (size_t i = 0; i < wn; ++i) { __half h = __float2half_rn(bf16_f32_host(hw[i])); memcpy(&hf[i], &h, 2); } + + uint16_t *dx, *dw, *dwf; float *dy, *dyp; + CHECK(cudaMalloc(&dx, n_in * 2)); + CHECK(cudaMalloc(&dw, wn * 2)); CHECK(cudaMalloc(&dwf, wn * 2)); + CHECK(cudaMalloc(&dy, n_out * 4)); + CHECK(cudaMalloc(&dyp, (size_t)(n_out / 8) * 65 * 8 * 4)); + CHECK(cudaMemcpy(dx, hx.data(), n_in * 2, cudaMemcpyHostToDevice)); + CHECK(cudaMemcpy(dw, hw.data(), wn * 2, cudaMemcpyHostToDevice)); + CHECK(cudaMemcpy(dwf, hf.data(), wn * 2, cudaMemcpyHostToDevice)); + + // one-time W conversion cost (host->device, reported separately; the engine would fold this + // into the weight load exactly like Gemm::bf16 does for sm<80) + { + cudaEvent_t e0, e1; CHECK(cudaEventCreate(&e0)); CHECK(cudaEventCreate(&e1)); + CHECK(cudaEventRecord(e0)); + CHECK(cudaMemcpy(dwf, hf.data(), wn * 2, cudaMemcpyHostToDevice)); + CHECK(cudaEventRecord(e1)); CHECK(cudaEventSynchronize(e1)); + float ms = 0; CHECK(cudaEventElapsedTime(&ms, e0, e1)); + printf("%-26s one-time W convert: %.2f ms (%.1f MB), tiles=%lld\n", sh.name, ms, wn * 2 / 1e6, n_out / 8); + } + + int tiles = (int) (n_out / 8); + // valid ks must divide n_in so each k-chunk is a multiple of 8; sweep ALL of them, report the best + const int cands[11] = {1, 2, 4, 5, 8, 10, 16, 20, 32, 40, 64}; + + auto timeit = [&](const char* tag, const std::function& fn) -> double { + for (int i = 0; i < WARM; ++i) fn(); + CHECK(cudaDeviceSynchronize()); + double best = 1e30; + for (int rep = 0; rep < 3; ++rep) { + cudaEvent_t e0, e1; CHECK(cudaEventCreate(&e0)); CHECK(cudaEventCreate(&e1)); + CHECK(cudaEventRecord(e0)); + for (int i = 0; i < ITERS; ++i) fn(); + CHECK(cudaEventRecord(e1)); CHECK(cudaEventSynchronize(e1)); + float ms = 0; CHECK(cudaEventElapsedTime(&ms, e0, e1)); + double us = ms * 1000.0 / ITERS; + if (us < best) best = us; + } + (void) tag; return best; + }; + + double t_base = timeit("base", [&]{ gemv_warp<<<(unsigned) ((n_out + 7) / 8), 256>>>(dx, dw, dy, n_in, n_out); }); + gemv_warp<<<(unsigned) ((n_out + 7) / 8), 256>>>(dx, dw, dy, n_in, n_out); + CHECK(cudaMemcpy(hyb.data(), dy, n_out * 4, cudaMemcpyDeviceToHost)); + + // occupancy sweep over k-chunk count for the preconverted-W TC kernel + int best_ks = 1; double t_pc = 1e30; + for (int i = 0; i < 11; ++i) { + const int ksv = cands[i]; + if (n_in % ksv != 0) continue; + dim3 g((unsigned) tiles, (unsigned) ksv); + double t = timeit("pcs", [&]{ tc_preconv<<>>(dx, dwf, dyp, n_in, n_out, ksv); + tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, ksv); }); + if (t < t_pc) { t_pc = t; best_ks = ksv; } + } + dim3 gtc((unsigned) tiles, (unsigned) best_ks); + tc_preconv<<>>(dx, dwf, dyp, n_in, n_out, best_ks); + tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, best_ks); + CHECK(cudaMemcpy(hypc.data(), dy, n_out * 4, cudaMemcpyDeviceToHost)); + + double t_ti = timeit("tci", [&]{ tc_inline<<>>(dx, dw, dyp, n_in, n_out, best_ks); + tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, best_ks); }); + tc_inline<<>>(dx, dw, dyp, n_in, n_out, best_ks); + tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, best_ks); + CHECK(cudaMemcpy(hyin.data(), dy, n_out * 4, cudaMemcpyDeviceToHost)); + + double t_fu = timeit("tcf", [&]{ tc_fused<<<(unsigned) tiles, 32>>>(dx, dw, dy, n_in, n_out); }); + tc_fused<<<(unsigned) tiles, 32>>>(dx, dw, dy, n_in, n_out); + CHECK(cudaMemcpy(hyfu.data(), dy, n_out * 4, cudaMemcpyDeviceToHost)); + + double best_tc = t_pc; const char* best_var = "preconv"; + if (t_ti < best_tc) { best_tc = t_ti; best_var = "inline"; } + if (t_fu < best_tc) { best_tc = t_fu; best_var = "fused"; } + + double e_tc = 0, e_base = 0, sc = 0; + if (strcmp(best_var, "preconv") == 0) { + for (long long o = 0; o < n_out; ++o) { e_tc = std::max(e_tc, std::fabs((double) hypc[o] - href[o])); } + } else if (strcmp(best_var, "inline") == 0) { + for (long long o = 0; o < n_out; ++o) { e_tc = std::max(e_tc, std::fabs((double) hyin[o] - href[o])); } + } else { + for (long long o = 0; o < n_out; ++o) { e_tc = std::max(e_tc, std::fabs((double) hyfu[o] - href[o])); } + } + for (long long o = 0; o < n_out; ++o) { + e_base = std::max(e_base, std::fabs((double) hyb[o] - href[o])); + sc = std::max(sc, std::fabs(href[o])); + } + double gb_base = (double) (wn * 2) / t_base / 1e3; + double gb_tc = (double) (wn * 2) / best_tc / 1e3; + printf("%-26s %13.3f | pc %13.3f (ks=%d) | in %13.3f | fused %13.3f | BEST %s %7.3fx | maxerr tc %.2e base %.2e (scale %.1f, BW base %.0f tc %.0f GB/s)\n", + sh.name, t_base, t_pc, best_ks, t_ti, t_fu, best_var, t_base / best_tc, + e_tc, e_base, sc, gb_base, gb_tc); + + CHECK(cudaFree(dx)); CHECK(cudaFree(dw)); CHECK(cudaFree(dwf)); CHECK(cudaFree(dy)); CHECK(cudaFree(dyp)); + } + + { // bf16 -> fp16 exactness scan + unsigned seed = 777u; double worst = 0; int bad = 0, n = 2000000; + for (int i = 0; i < n; ++i) { + float f = (rng(seed) * 2.0f - 1.0f) * 100.0f; + uint16_t b = f32_bf16_host(f); + __half h = __float2half_rn(bf16_f32_host(b)); + if ((double) __half2float(h) != (double) bf16_f32_host(b)) { + bad++; worst = std::max(worst, std::fabs((double) __half2float(h) - (double) bf16_f32_host(b))); + } + } + printf("\nbf16->fp16 conversion exactness: %d / %d inexact, worst %.3g\n", bad, n, worst); + } + printf("BENCH_DONE\n"); + return 0; +} diff --git a/data/draft_vocab_cyrillic.bin b/data/draft_vocab_cyrillic.bin new file mode 100644 index 00000000..06e22cbf Binary files /dev/null and b/data/draft_vocab_cyrillic.bin differ diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 8152179c..08737ec2 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -83,7 +83,10 @@ of the vocabulary (`mtp/rt/draft_vocab.bin`). Since 0.1.27 the subset includes e token (106,299 ids), so answers in those languages are 15-38% faster (Q2_0, RTX 5070). Its head takes ~180 MiB of VRAM, which the expert cache leaves free for it (0.1.28). `START-HERE.bat --setup --draft-vocab en` keeps the English/code subset from before (40,525 ids, ~110 MiB less VRAM, English answers 1-2% faster; CJK answers get -almost no drafts). `tools/draft_vocab.py` builds and inspects subsets. +almost no drafts). `--draft-vocab cyrillic` takes the English/code subset plus the whole Cyrillic script (58,963 +ids): the shipped subsets hold 142 of the vocabulary's 18,580 Cyrillic tokens, so Ukrainian or Russian answers got +1.4 tokens a round; with it 2.1, and 83 -> 109 tokens/s (RTX 5090, the NVFP4 fork), English unchanged. +`tools/draft_vocab.py` builds and inspects subsets. **Low-RAM mode (engine 0.1.26, chosen by setup):** normally all of a model's experts are copied into RAM (23-50 GB, pinned) and the GPU holds a copy of the most-used ones. On a PC whose RAM cannot hold them beside the system (the @@ -424,6 +427,10 @@ print(r.choices[0].message.content) part of the thinking the client sees and counts as output tokens. `"reasoning_budget_tokens": N` in `strata-.json` sets it for every request; a request's own value wins, and `0` means no budget. Off by default; Anthropic's `"thinking": {"budget_tokens": N}` still only chooses the level, as above. +- **Anthropic requests that don't ask for thinking (opt-in, 0.1.32, #278).** By default a `/v1/messages` request + with no `"thinking"`, effort or budget thinks as the model's template does. `"anthropic_thinking": "on_request"` in + `strata-.json` renders such a request without thinking - Anthropic's own rule, and what Claude Code's short + helper calls (a session title in a few dozen tokens) need; its real turns ask for thinking when it is on there. - **Streaming.** With `"stream": true` everything arrives as it is made: the thinking, the answer, and tool calls (the tool's name first, then its arguments piece by piece, like OpenAI and Anthropic do). While the model reads a long prompt the stream sends keep-alives, so agents do not time out; the server window prints progress every @@ -450,7 +457,12 @@ print(r.choices[0].message.content) - **From the internet.** Put a tunnel in front of it, for example [cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/do-more-with-tunnels/trycloudflare/): `cloudflared tunnel --url http://127.0.0.1:8080`. **Set a key first**, or anyone with the link can use your PC: add `"api_key": "some-long-secret"` to `strata-.json` (or set the `STRATA_API_KEY` environment variable); - clients then send it as their API key. + clients then send it as their API key. Streamed answers carry `X-Accel-Buffering: no`, so nginx-style proxies pass + each token on at once. The web app's settings and MCP tools only answer Strata's own page: when you open it through + a proxy or tunnel whose address differs, add that address, e.g. `"trusted_origins": ["https://strata.example.com"]`. +- **From web apps in a browser (CORS).** Off by default. `"cors_origins": ["https://chat.example.com"]` lets pages of + those origins call `/v1/*` from the browser (Open WebUI's direct connections, browser extensions); `["*"]` lets any + page do it - only sensible with an API key. It never opens `/settings`, `/unload` or the MCP tools. **Conversation cache.** A request that continues a chat reads only the part after what the engine already holds: the live session, or one of the checkpoints it keeps in RAM (up to 6, ~118 MB each, taken at the start of each new @@ -776,3 +788,56 @@ Strata itself: [MIT](../LICENSE). The model files are not part of it; their lice `serve/web/fonts/OFL.txt`). Its Monitor tab started from @code-martin's dashboard idea (PR #22). - The experimental speed projection's vector (`data/experimental-speed-projection/`): Qwen Community License 1.0, made from the model's activations (see its README). + +### Start the text API without occupying the GPU + +`serve/server.py --engine strata --config strata-.json --lazy` (or `"lazy_load": true` in that +config) starts the lightweight HTTP API without spawning the native engine. The first generation request +loads it through the existing reload path, including `before_load` and `min_free_vram_mib`. Eager startup +remains the default. This option is text-only: a vision configuration with lazy startup is rejected explicitly. + +`POST /v1/load` and `/v1/unload` are JSON control aliases for integrations, accepting `{}` or +`{"model":""}` and returning model status. They require the configured API key, +`application/json`, and no foreign browser Origin. They return **409** while a request is active or queued, +and **404** for an unknown model. Existing `/load` and `/unload` behavior is preserved. `/api/health` aliases +`/health`; `/v1/status` exposes `loaded` and `auto_load`. The unloaded model remains discoverable. + +Unloading and shutdown close the native engine's stdin after sending `QUIT`, allowing Windows' detached +stdin reader to see EOF. Cleanup waits for process exit before releasing handles; if forced shutdown still +times out, the server keeps ownership and reports an error rather than claiming the model was unloaded. + +### JSON response formats + +`POST /v1/chat/completions` accepts `response_format: {"type":"json_object"}` or +`{"type":"json_schema","json_schema":{"name":"answer","strict":true,"schema":{"type":"object","properties":{"answer":{"type":"integer"}},"required":["answer"],"additionalProperties":false}}}`. +The schema must describe an object at its root. Local `#` references work; remote references are refused. +`json_schema` is checked with the Python package `jsonschema` when it is installed (`python -m pip install +"jsonschema>=4.23,<5"`; setup does not add it); without it the answer is only checked to be one JSON object, and the +server says so once. + +This is **schema prompting followed by server validation**, not grammar-constrained decoding. One generation +is made per request, with no hidden retry. Successful responses contain a validated JSON object. Malformed JSON, +duplicate keys, non-finite numbers, schema violations and incomplete generations return **502** with +`error.code: structured_output_failed`; invalid request schemas return **400**. JSON formats combined with +tools/MCP are refused explicitly. Without `response_format`, ordinary text and tool behavior stays the same. + +Structured SSE buffers the answer while sending keep-alive comments. It emits content only after validation, +then usage/timings and `[DONE]`; failures emit an SSE error and `[DONE]` without invalid content deltas. +`/v1/status.structured_output` advertises the formats, validation method and buffered streaming behavior. + +### API request monitor + +Off by default, since it keeps prompts and answers in memory: turn it on with `"api_monitor": true` in +`strata-.json` (or `serve/server.py --api-monitor`); otherwise nothing is recorded and the two endpoints below +answer 404. +Open `/api-monitor` to inspect API traffic without opening a chat. It shows the model state, safe +load/unload controls, active/queued requests, original request bodies, output, separate reasoning and +non-stream response bodies. Total wall-clock includes FIFO waits and automatic loading; load, queue, +first-token, prompt/output tokens and engine decode timing are shown separately. + +`GET /api/requests` returns compact summaries; `GET /api/requests?id=` returns one retained request. +Both use the existing API-key check. The monitor retains the newest **100 requests in memory** until restart, +with **262,144 characters per input/output/reasoning/response field** and visible truncation flags. The actual API +responses are unaffected. Headers are not recorded, and the monitor key is kept in this tab's session storage. +Treat request history as sensitive input/output when exposing Strata on a network: set an API key as above. +The page uses relative URLs and works through the existing host binding or a reverse proxy. diff --git a/docs/ORCA_Q4_K_S.md b/docs/ORCA_Q4_K_S.md new file mode 100644 index 00000000..25815ff1 --- /dev/null +++ b/docs/ORCA_Q4_K_S.md @@ -0,0 +1,36 @@ +# OrcaRouter Uncensored Q4_K_S (manual setup) + +This path uses the three original `orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF` Q4_K_S shards without rewriting their expert, embedding or PLE table bytes. It is separate from the installer model menu. Keep all three shard filenames together. + +The ordinary GGUF quantizes some small projections which Strata reads as BF16. `--compat-bf16` dequantizes and rounds those projections to BF16 in the separate pack; it does not restore their original precision. The Q5_0 PLE table remains in the source GGUF and currently uses the mapped reader (`--ple-io mmap`). The Q4_K gate/up experts and Q5_0/Q5_1 down experts remain in GGUF form, including layers whose three tensors cross shard boundaries (each role is read from its own shard). The GPU expert kernels take Q4_K with Q5_1 (or Q8_0) downs; Q5_0 downs are not among them yet, and the engine refuses to start on a pack with such a layer (it names the layer). + +## Build and prepare + +Build Strata with CUDA, native experts, `STRATA_ORCA_Q4KS_MMQ=ON` (and `STRATA_BUILD_TESTS=ON` for the two parity programs below). This opt-in compiles the Q5_0 GGML MMQ instance for CUDA or HIP (the Q4_K and Q5_1 instances come with the engine's K-quant MMQ build on CUDA); the usual Q8_0 draft-layer instance remains in both builds. HIP also needs `STRATA_PREFILL_MMQ=ON`. Select your card's compute capability, for example `89` on an L40S. On Windows with Ninja and CUDA 12.6, use the Visual Studio developer environment and `-DCMAKE_CUDA_RUNTIME_LIBRARY=Shared` to keep the CUDA runtime linkage consistent. The default pinned ggml checkout is supported by the project build. + +```sh +cmake -S . -B build -G Ninja -DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_ORCA_Q4KS_MMQ=ON -DCMAKE_CUDA_ARCHITECTURES=89 -DCMAKE_CUDA_RUNTIME_LIBRARY=Shared -DCMAKE_BUILD_TYPE=Release +cmake --build build --target strata native_expert_parity ple_q5_parity +python tools/iq_pack.py --gguf /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf --out packs/orca-q4_k_s --compat-bf16 +``` + +`iq_pack.py` needs NumPy and the `gguf-py` module from the pinned llama.cpp dependency (`STRATA_GGUF_PY` can point to that directory). It writes a roughly 1.43 GiB dense pack and a native-expert manifest. The original 112 GB of model shards are read in place; `experts.bin` is optional and is not written by this command. + +Check the changed kernels against the real files before starting the service: + +```sh +build/native_expert_parity /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00002-of-00003.gguf /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00003-of-00003.gguf 0 5 6 20 47 +build/ple_q5_parity /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf +``` + +## Engine flags + +Pass the same first shard to `--native` and `--ple-gguf`; Strata discovers the other two shards by name. For a first text-only run, use 32K context and a modest cache. Once that passes, increase the context and cache with memory measurements on the target machine. + +```sh +--pack packs/orca-q4_k_s --native /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf --ple-gguf /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf --ple-io mmap --expert-profile data/expert-profile.bin --expert-cache auto --prefill 512 --spec 4 --mtp /path/to/mtp/rt --max-context 32768 --kv int8 +``` + +For two GPUs in persistent server mode, add `--layer-split auto --split-device 1` (with CUDA0 and CUDA1 visible). The usual Strata MTP runtime is built from the original model's draft layer; draft acceptance on the Uncensored fine-tune must be measured. Keep this model's own tokenizer from the pack. Do not combine `--expert-cache-per-layer` with a variable-size native cache: that policy's slot ordering is independent of the pack's per-layer blob sizes. + +This port does not claim that Q4_K_S beats llama.cpp on a given computer. Compare the same model bytes, prompt, context, output length and GPU load; report prefill and decode separately. diff --git a/include/strata/artifact/gguf_reader.hpp b/include/strata/artifact/gguf_reader.hpp index 42e0665e..298dc3bc 100644 --- a/include/strata/artifact/gguf_reader.hpp +++ b/include/strata/artifact/gguf_reader.hpp @@ -96,6 +96,8 @@ inline const char* ggml_type_name(uint32_t t) { return "IQ2_S"; case 23: return "IQ4_XS"; + case 24: + return "I8"; case 30: return "BF16"; case 34: @@ -204,6 +206,10 @@ inline bool block_geometry(uint32_t t, int& elems, int& bytes) { elems = 256; bytes = 56; return true; + case 24: // I8: raw bytes (the FP8 PLE table of tools/ple_fp8_pack.py) + elems = 1; + bytes = 1; + return true; case 42: elems = 64; bytes = 18; diff --git a/include/strata/core/coupled_draft.hpp b/include/strata/core/coupled_draft.hpp index 4758674b..d095e3a0 100644 --- a/include/strata/core/coupled_draft.hpp +++ b/include/strata/core/coupled_draft.hpp @@ -49,15 +49,23 @@ namespace strata::core { /// The longest penalty window the coupled drafter mirrors (serve's kPenaltyWindowCap). inline constexpr int kCoupledHistCap = 4096; -/// STRATA_SPEC_COUPLED=1 (any value but empty or "0"): read once. -inline bool coupled_draft_env() { - static const bool on = [] { +inline bool& coupled_draft_state() { + static bool on = [] { const char* e = std::getenv("STRATA_SPEC_COUPLED"); return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0; }(); return on; } +/// Whether coupled draft sampling is enabled (via STRATA_SPEC_COUPLED=1 or --coupled-draft CLI flag). +inline bool coupled_draft_env() { + return coupled_draft_state(); +} + +inline void set_coupled_draft(bool on) { + coupled_draft_state() = on; +} + /// The MTP cell of chain step j after a window at `p` with `a` drafts accepted (draft() runs step j there). STRATA_COUPLED_HD inline int64_t coupled_draft_cell(int64_t p, int a, int j) { return p + a + j; } diff --git a/include/strata/core/device.hpp b/include/strata/core/device.hpp index 8fb93ad6..2c180263 100644 --- a/include/strata/core/device.hpp +++ b/include/strata/core/device.hpp @@ -43,6 +43,10 @@ const char* compiled_gpu_archs(); // this is the matching check at run time (a binary can be carried to a different machine). DeviceInfo device_info(int ordinal = 0); +/// "" when this build has device code for the current device, else CUDA's error: a build for other GPUs would +/// otherwise fail at its first kernel launch, with nothing that names the cause. +std::string device_code_error(); + class CudaError : public std::runtime_error { public: CudaError(const std::string& what, int code) : std::runtime_error(what), code_(code) {} diff --git a/include/strata/core/emulate.hpp b/include/strata/core/emulate.hpp new file mode 100644 index 00000000..6f28b97f --- /dev/null +++ b/include/strata/core/emulate.hpp @@ -0,0 +1,36 @@ +// strata/core/emulate.hpp - STRATA_EMULATE_CC: another GPU generation's code paths, run on this card (tests only). +// +// A build whose device code is PTX for an older architecture (CMAKE_CUDA_ARCHITECTURES=86-virtual) runs on a newer +// card through the driver's JIT, and every kernel then sees __CUDA_ARCH__ = 860. What the host decides from the +// device must agree with that, or it picks paths and shared-memory sizes the device code was not built for: +// STRATA_EMULATE_CC=75|80|86|89 makes each such query (compute capability, shared memory per block) answer as that +// card would. Speed under it says nothing about the real card; results do - the kernels are the real card's. +#pragma once + +#include + +namespace strata { + +/// the emulated compute capability as 10 * major + minor, or 0 (off) +inline int emulated_cc() { + static const int cc = [] { + const char* e = std::getenv("STRATA_EMULATE_CC"); + const int v = e ? std::atoi(e) : 0; + return v >= 75 && v < 120 ? v : 0; + }(); + return cc; +} +inline int cc_major_of(int real_major) { return emulated_cc() ? emulated_cc() / 10 : real_major; } +inline int cc_minor_of(int real_minor) { return emulated_cc() ? emulated_cc() % 10 : real_minor; } +/// cudaDevAttrMaxSharedMemoryPerBlockOptin as the emulated card reports it: 64 KB on Turing, 163 KB on the A100, +/// 99 KB on the other Ampere and Ada cards +inline int smem_optin_of(int real) { + switch (emulated_cc()) { + case 0: return real; + case 75: return 65536; + case 80: return 166912; + default: return real < 101376 ? real : 101376; + } +} + +} // namespace strata diff --git a/include/strata/core/layer.hpp b/include/strata/core/layer.hpp index 1669256f..a8965da1 100644 --- a/include/strata/core/layer.hpp +++ b/include/strata/core/layer.hpp @@ -217,6 +217,9 @@ struct QsaState { /// Uses k_q/k_scale + v_q4. Mode 0 only (no KV streaming, no ring); under this setting the MTP drafter's /// ring state stays plain INT8, so the block movers never see the hybrid layout. bool kv_hybrid = false; + /// K and V go through kv_q4.hpp's Walsh-Hadamard rotation before they are stored, the queries too, the output + /// back: always for Q4_0, for INT8 by qsa_set_kv_int8_rotate (spreads outlier channels over the scale groups) + bool kv_rot = false; int32_t* page_table = nullptr; ///< (n_pages,) logical page -> physical page (-1: not resident, streamed) int64_t n_pages = 0; int64_t max_cells = 0; @@ -237,6 +240,7 @@ struct QsaState { int32_t* idx_block_pos = nullptr; float* cos_tab = nullptr; ///< (max_cells, n_rot/2), built on the HOST in float64 + bool owns_rope = false; ///< built the table above (not borrowed with share_rope): it releases it float* sin_tab = nullptr; /// THE PER-TOKEN COUNTS, IN DEVICE MEMORY - the whole reason this layer can be a graph. `qsa_step_fill` @@ -278,6 +282,8 @@ uint64_t qsa_kv_host_bytes(); /// Plan v0.3 P7: store K/V as INT8 with FP16 scales per 64 values (half the VRAM of FP16). Set before sizing and /// initializing the session; default off until gate G-C accepts it. void qsa_set_kv_int8(bool enabled); +/// INT8 K/V through the Hadamard rotation (off by default: STRATA_KV_ROT=1) +void qsa_set_kv_int8_rotate(bool enabled); bool qsa_kv_int8(); /// PR #21: store K/V as Q4_0 after a Hadamard rotation (`--kv q4_0`): 576 B per cell, vs 1,056 in INT8. void qsa_set_kv_q4(bool enabled); diff --git a/include/strata/core/session.hpp b/include/strata/core/session.hpp index c05d7e99..6d1becfa 100644 --- a/include/strata/core/session.hpp +++ b/include/strata/core/session.hpp @@ -99,6 +99,9 @@ uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k, int /// Carves `base` (DEVICE memory) into `s`. Returns the bytes used. Same range convention as `session_bytes`. uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void* base, SessionState& s, int64_t layer_lo = 0, int64_t layer_hi = -1); +/// Before the memory `session_init` carved is freed: forgets what points into it from outside the session (the +/// rope kernels' registered angle table, #280), so a later session never rotates by freed memory. +void session_release(SessionState& s); /// Zeroes every layer's state - the residual to `R_init`, everything else to zero, so a fresh sequence starts /// from the reference's own `zeros()`. void session_zero(SessionState& s, const ModelGeometry& g, const float* R_init, void* stream); diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index eec48133..5717eb4f 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -74,6 +74,9 @@ public: /// One window: `tokens[0..T)` at positions pos0.., the pool served per layer; `out[t]` = argmax after token t. /// The PLE rows are gathered here from `ss.ple_prev` and the tokens. Captures the T-token graph on first use. bool run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, void* user, int32_t* out, std::string& err); + /// Diagnostics: row `t` of the last window's head logits (n_vocab floats) to the host. Valid after run(). + bool copy_logits(int t, float* host) const; + int64_t vocab() const { return next_ ? next_->vocab() : n_vocab_; } /// The sampling the verify window's head applies (temperature / top_p / top_k / seed). Set per /// request; greedy by default. The sampling itself runs OUTSIDE the captured graph - its /// parameters would otherwise be baked forever - so this can change between requests freely. @@ -116,6 +119,14 @@ public: /// Keep the first `n_keep` (1..T) tokens of the last window; advances `ss.ple_prev` by them. bool commit(int n_keep, std::string& err); + /// commit() returns without waiting for its graph (a single-GPU session sets it): the next window follows it on + /// the same stream and the drafter reads nothing it writes, so it overlaps the draft. Whoever reads or writes + /// the session from another stream or the host afterwards (a new request, a checkpoint, a snapshot, the prompt + /// path, the end of a run) calls wait_commit() first. STRATA_COMMIT_SYNC=1 keeps the wait. + static void set_commit_async(bool on); + /// Waits for the last commit graph when commit() did not (an event recorded after it, not the whole device); + /// false with `err` when it failed. Free when nothing is pending. + bool wait_commit(std::string& err); /// Measurement hook (STRATA_LOGPOS): after run(), write one line per row t of the last window's head - /// "pos target logprob top top_logprob hit extra_logprob target_logprob_without_extra" - where row t is the @@ -173,7 +184,8 @@ private: bool ple_stage() const { return lb_ <= 1 && 1 < le_; } ///< holds layer 1, where the PLE block runs bool capture_commit(std::string& err); bool record_window(int T, cudaStream_t cs, std::string& err); - static constexpr int kProfPer = 32; // stamps per layer + static constexpr int kProfPer = 33; // stamps per layer (32 left the hc-read second + // half's up-stamp at slot 32 = the next layer's slot 0: D8) bool prof_on_ = false; unsigned long long* prof_ = nullptr; // device: n_layers * kProfPer + 4 stamps std::vector prof_h_; @@ -208,6 +220,8 @@ private: uint32_t* h_flag_ = nullptr; uint32_t* m_flag_ = nullptr; uint32_t* h_flagA_ = nullptr; uint32_t* m_flagA_ = nullptr; // the GPU plan is in place uint32_t* h_flagB_ = nullptr; uint32_t* m_flagB_ = nullptr; // the PCIe share's DMA copies have landed + cudaEvent_t commit_done_ = nullptr; // recorded after an async commit (set_commit_async); see wait_commit + bool commit_pending_ = false; cudaStream_t copy_ = nullptr; // the copy engine's stream (DMA of missed experts) struct FlagSet { uint32_t* flag; uint32_t value; }; FlagSet flag_sets_[2 * 64 * 2] = {}; // host-function arguments, one per (layer, group) diff --git a/include/strata/kernels/cpu/pool.hpp b/include/strata/kernels/cpu/pool.hpp index dce9c2bf..76bda6de 100644 --- a/include/strata/kernels/cpu/pool.hpp +++ b/include/strata/kernels/cpu/pool.hpp @@ -63,13 +63,32 @@ struct ExpertJobMulti { const void* nact[MAXT] = {}; }; +/// How worker threads are allocated across physical/logical CPU cores (#272). `All` is the layout the pool has +/// always used and the default; the hybrid-aware ones are opt-in (--pool-affinity auto|p-cores). +enum class PoolAffinity { + Auto, ///< Hybrid: prioritize physical P-cores, then SMT, then E-cores (defaults to P-core count) + PCores, ///< Restrict workers strictly to Performance cores and their SMT siblings + All, ///< The default: one worker per physical core in the OS's order, without hybrid distinction +}; + +struct CpuTopology { + bool is_hybrid = false; + int p_cores = 0; ///< Physical performance cores + int p_threads = 0; ///< Total logical threads on performance cores + int e_cores = 0; ///< Efficient cores + std::vector worker_cores; ///< Ordered logical core IDs for workers (excluding host if skip_first) + int host_core = -1; ///< Logical core reserved for host thread +}; + +CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity = PoolAffinity::All); + /// One logical processor per PHYSICAL core, so a worker is never scheduled onto an SMT sibling of another /// worker. On the 6-core/12-thread machine this project measures on, `hardware_concurrency()/2` workers on /// logical processors 0..5 would put every worker on a sibling pair and halve the useful bandwidth - which is /// exactly the kind of error that shows up as "the CPU path is slower than the model says" with no clue why. /// /// `skip_first` drops the first core, which P2.S3 reserves for the host loop. -std::vector physical_cores(bool skip_first); +std::vector physical_cores(bool skip_first, PoolAffinity affinity = PoolAffinity::All); /// **THE RESERVATION IS A FICTION UNLESS THE HOST IS ACTUALLY PUT THERE.** /// @@ -101,7 +120,8 @@ public: /// With `host_works`, `run()` claims jobs itself instead of spinning on `done_`, and the pool is six /// threads on six cores. `false` is the A/B arm and exists so the change is measurable rather than /// asserted - the counter it moves is `pool phases ... drain`, which is host-side and needs no profiler. - explicit ExpertPool(int n_workers = 0, bool pin = true, bool host_works = true); + explicit ExpertPool(int n_workers = 0, bool pin = true, bool host_works = true, + PoolAffinity affinity = PoolAffinity::All); /// The watchdog's view of the pool (issue #31): the batch, the counters, every thread's state. void diag(std::FILE* f) const; ~ExpertPool(); @@ -113,6 +133,12 @@ public: /// is on" is only true if the engine says which adaptation it took. bool host_works() const { return host_works_; } + bool is_hybrid() const { return topo_.is_hybrid; } + int p_cores() const { return topo_.p_cores; } + int p_threads() const { return topo_.p_threads; } + int e_cores() const { return topo_.e_cores; } + PoolAffinity affinity() const { return affinity_; } + /// Publish `n` jobs, then block until every one has been claimed AND every worker has parked. /// `jobs` must outlive the call (it does, and the workers never touch it afterwards). void run(ExpertJob* jobs, int n); @@ -239,6 +265,8 @@ private: }; const NativeFmt* nfmt_ = nullptr; std::vector split_multi_; + PoolAffinity affinity_ = PoolAffinity::All; + CpuTopology topo_; }; } // namespace strata::kernels::cpu diff --git a/include/strata/kernels/fused_gr.hpp b/include/strata/kernels/fused_gr.hpp index ba4e7c9d..40eff30f 100644 --- a/include/strata/kernels/fused_gr.hpp +++ b/include/strata/kernels/fused_gr.hpp @@ -49,4 +49,17 @@ constexpr int kFusedGrMaxT = 8; void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf = nullptr, int stamp_i0 = 0); +/// The multi read's variants (#315; not main's opt-in STRATA_GR_V3 read, which sums in another order), all computing +/// every output with the plain read's operations in its order, so bitwise the plain read's and the single-token +/// read's: plain (0.1.31's default: the norm one block per token, the down projection on 41 blocks), split (the norm +/// one block per token and stream, then the plain down projection) and staged (split's norm, and the down +/// projection's activations staged ahead by cp.async, two half-stream tiles in flight, bank-conflict-free). +/// `fused_gr_check` runs all of them and the single-token read on the current card with random weights and inputs +/// (1..8 tokens, with and without the pending write) and from then on uses there the newest one that agrees with the +/// plain read bit for bit; STRATA_HC_SPLIT=0 keeps the plain read, =1 stops at split. It runs once per card +/// (Verifier::init calls it) and prints which one runs. On a card it has not checked, `fused_gr_variant` is the +/// plain read unless STRATA_HC_SPLIT=1 or 2 names a variant. +void fused_gr_check(); +int fused_gr_variant(); + } // namespace strata::kernels diff --git a/include/strata/kernels/iq_kernels.hpp b/include/strata/kernels/iq_kernels.hpp index 1beb9a14..c2bb2b5c 100644 --- a/include/strata/kernels/iq_kernels.hpp +++ b/include/strata/kernels/iq_kernels.hpp @@ -14,6 +14,8 @@ namespace strata::kernels { /// ggml type ids handled here. bool iq_supported(int ggml_type) noexcept; +/// The token-embedding types iq_embed_rows and iq_dequant_f32 read: the i-quants above and BF16 (30). +bool embed_type_supported(int ggml_type) noexcept; /// Bytes of one row of `n` values of `ggml_type` (n a multiple of the type's block). size_t iq_row_bytes(int ggml_type, int64_t n) noexcept; diff --git a/include/strata/kernels/mrope.hpp b/include/strata/kernels/mrope.hpp index fb00bf41..cb1451c4 100644 --- a/include/strata/kernels/mrope.hpp +++ b/include/strata/kernels/mrope.hpp @@ -16,18 +16,46 @@ #include +#include "strata/kernels/rope_scaling.hpp" + namespace strata::kernels { /// The table of the CURRENT device (a layer split sets one per device; null = the identity). void mrope_table_set(const int32_t* device_table); const int32_t* mrope_table(); +/// #280, opt-in (STRATA_ROPE_TABLE=1): the rotation angles, 32 pairs of a 64-wide rotary slice, from the session's +/// float64 table (build_rope_table, [max_pos][32] cos and sin in VRAM, the rope scaling inside) of the CURRENT +/// device. With it the rope kernels rotate by the table's exact angles; without it they compute pos * powf(...) with cosf/sinf, which under +/// --use_fast_math is 0.0014 rad off at 32K and ~0.02 at 262K, and the prompt path (precise libm) and decode +/// (fast-math) disagree with each other. +struct RopeTab { + const float* cos = nullptr; ///< null: no table, the kernels compute the angle as they always did + const float* sin = nullptr; + int max_pos = 0; +}; +/// Registers the table the session just built with `scaling` (the latest one of the device wins). +void rope_table_set(const float* cos_tab, const float* sin_tab, int max_pos, const RopeScaling& scaling); +/// Forgets the table `cos_tab` (on every device) - before the memory that holds it is freed (session_release). +void rope_table_release(const float* cos_tab); +/// The registered table when STRATA_ROPE_TABLE=1 and it was built with `scaling`; otherwise none (the default: the +/// kernels compute the angle exactly as before). +RopeTab rope_table_for(const RopeScaling& scaling); + #if defined(__CUDACC__) || defined(__HIPCC__) /// ggml rope_multi, is_imrope, sections {11, 11, 10, 0}: sector = pair % 32; sector % 3 == 1 -> h (sector < 33), /// == 2 -> w (sector < 30), == 0 -> t (sector < 33). For pairs 0..31 all three bounds hold, so it is pair % 3. __device__ __forceinline__ int mrope_pos(const int32_t* tab, int pos, int pair) { return tab ? __ldg(tab + (size_t) pos * 3 + pair % 3) : pos; } +/// cos and sin of rotary position p, pair `pair` (0..31) from the table (scaling and magnitude included); false +/// when there is no table or p lies past it - then the caller computes the angle as it always did +__device__ __forceinline__ bool rope_tab_cs(const RopeTab& t, int p, int pair, float& c, float& s) { + if (t.cos == nullptr || p < 0 || p >= t.max_pos) return false; + c = __ldg(t.cos + (size_t) p * 32 + pair); + s = __ldg(t.sin + (size_t) p * 32 + pair); + return true; +} #endif } // namespace strata::kernels diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp index 29698422..3c6f8fab 100644 --- a/include/strata/kernels/ngram.hpp +++ b/include/strata/kernels/ngram.hpp @@ -44,7 +44,9 @@ inline constexpr float NG_RMS_EPS = 1e-6f; // The table: [160, 320001536] IQ4_NL. ne0 = 160 is the FAST axis, so one row is 160 contiguous elements = // 5 blocks of 32 at 18 bytes = 90 bytes. The head-slowest flatten then makes 16 rows exactly n_embd = 2560. inline constexpr uint64_t PLE_TABLE_ROWS = 320001536ull; -inline constexpr int PLE_ROW_BYTES = (PLE_HEAD_DIM / 32) * 18; // 90 +inline constexpr int PLE_ROW_BYTES = (PLE_HEAD_DIM / 32) * 18; // 90: an IQ4_NL row +inline constexpr int PLE_ROW_BYTES_FP8 = PLE_HEAD_DIM; // 160: an F8_E4M3 row, one byte a value +inline constexpr int PLE_ROW_BYTES_MAX = PLE_ROW_BYTES_FP8; /// The artifact's own hash constants, transcribed from `docs/gguf-dump-shard1.txt`: /// @@ -96,6 +98,11 @@ int iq4nl_code(int code); /// a perfectly plausible embedding of the wrong 160 values. void iq4nl_dequant_row(const uint8_t* row, float* out160); +/// One FP8 row -> 160 floats: each byte an E4M3 value (the "fn" variant: no infinities, 0x7F/0xFF are NaN), times the +/// table's one scale. This is the table as Qwen3.8-Flash-Next ships it (`...ngram_embedding.shard_k`, F8_E4M3, and +/// `weight_scale`), kept byte for byte by tools/ple_fp8_pack.py; IQ4_NL is 8% off it per row. +void fp8_e4m3_dequant_row(const uint8_t* row, float scale, float* out160); + /// How the table's rows are read (plan v0.3 P2). `Direct` is the default: unbuffered 4 KiB reads from the SSD, /// so the table never occupies RAM or the OS file cache. `Mmap` is the earlier memory-mapped path, kept as the /// A/B arm; it returns the same bytes. @@ -113,6 +120,11 @@ struct PleIoOptions { /// Mmap mode only (`--ple-io ram`): lock the whole mapped table in RAM at open, so no SSD read ever sits on /// the prompt or token path. Needs RAM for the full table. POSIX only (mlock); `locked()` reports the outcome. bool lock = false; + /// Direct mode with the I/O worker only: keep the SSD awake while rows are asked for - one page of the table + /// after this long without a read (0 = off), until `keepalive_window_s` after the last request for rows + /// (see PleReader::set_keepalive). + double keepalive_ms = 0; + double keepalive_window_s = 60; }; /// The PLE table. Held by pointer-to-impl so this header does not drag `` into every @@ -150,6 +162,8 @@ public: /// True when `PleIoOptions::lock` was asked for and mlock succeeded (false: pages only pre-touched). bool locked() const; uint64_t rows() const; + /// "IQ4_NL" or "F8_E4M3" (a GGUF from tools/ple_fp8_pack.py: type I8, strata.ple.format = f8_e4m3). + const char* format() const; /// 16 row indices -> 2560 floats. The gathered rows are flattened HEAD-SLOWEST: row h's 160 values /// occupy `out[h*160, (h+1)*160)`, which is what `ggml_get_rows` does and what makes the result a plain diff --git a/include/strata/ngram/ple_reader.hpp b/include/strata/ngram/ple_reader.hpp index 0552ff1e..2884817e 100644 --- a/include/strata/ngram/ple_reader.hpp +++ b/include/strata/ngram/ple_reader.hpp @@ -1,6 +1,6 @@ // include/strata/ngram/ple_reader.hpp - plan v0.3 P2: the n-gram table read straight from the SSD. // -// The table is 320,001,536 rows of 90 bytes (26.8 GiB) and is never held in RAM: every row comes from an +// The table is 320,001,536 rows of 90 bytes (IQ4_NL, 26.8 GiB) or 160 (FP8 E4M3, 51.2 GB) and is never held in RAM: every row comes from an // unbuffered 4 KiB read (platform::DirectFile). A token needs 16 rows on 16 different pages, and all 16 depend // on the token itself, so the only time to hide them is the embedding plus layer 0. Hence the split API: // @@ -24,7 +24,7 @@ namespace strata::ngram { -inline constexpr uint32_t ROW_BYTES = 90; +inline constexpr uint32_t ROW_BYTES = 90; ///< an IQ4_NL row; `open` takes the table's own size inline constexpr uint32_t PAGE = 4096; struct ReaderStats { @@ -37,6 +37,8 @@ struct ReaderStats { double submit_us = 0; ///< time spent inside the read submission call (non-zero = it blocks) double read_us_sum = 0; ///< sum of per-read latencies (issue to completion) uint64_t late_injected = 0; ///< reads delayed by fault injection + uint64_t keepalive_reads = 0; ///< pages read only to keep the SSD awake (not in `reads`, `bytes` or latencies) + double keepalive_us_max = 0; ///< the slowest of them std::vector read_us; ///< last <= 65,536 read latencies, for percentiles double percentile(double q) const; }; @@ -56,24 +58,36 @@ public: /// validated GGUF parse (PleTable::open checks the table exactly fills the file from there). /// `io_thread` (default): a worker thread submits and reaps reads, so `issue` costs the caller no ReadFile /// calls. false: the caller's thread does it (A/B arm). + /// `row_bytes`: one row's size in the file (90 IQ4_NL, 160 FP8), at most one page. bool open(const std::string& path, uint64_t table_offset, uint64_t n_rows, uint32_t max_inflight, - uint64_t cache_rows, std::string& err, bool io_thread = true); + uint64_t cache_rows, std::string& err, bool io_thread = true, uint32_t row_bytes = ROW_BYTES); + uint32_t row_bytes() const; void close(); bool is_open() const; - /// Start fetching `n` rows; row i's 90 raw bytes land at `out_raw + 90 * i`. `out_raw` must stay valid - /// until `collect` returns. Out-of-range rows produce 90 zero bytes (the mmap path's behaviour). + /// Start fetching `n` rows; row i's raw bytes land at `out_raw + row_bytes * i`. `out_raw` must stay valid + /// until `collect` returns. Out-of-range rows produce zero bytes (the mmap path's behaviour). Ticket issue(const uint32_t* rows, size_t n, uint8_t* out_raw); /// Block until every row of the ticket is in `out_raw`. Returns false on an I/O error (message in `err`). bool collect(Ticket t, std::string& err); + /// Keep the SSD awake while the table is in use (io_thread mode only; call after `open`): when no read has + /// gone out for `period_ms`, the worker reads one page of the table, until `window_s` after the last `issue`. + /// Some SSDs drop into a power state after ~250 ms without a command and stall the next reads 50-150 ms + /// (a WD_BLACK SN7100 on Windows 11; the NVMe idle timeouts of the power plan did not change it), which in + /// decode happens after a few rounds whose rows all came from the row cache. 0 turns it off (the reader's + /// default; generate turns it on, see STRATA_SSD_KEEPALIVE). A keep-alive read that fails turns it off. + void set_keepalive(double period_ms, double window_s); + /// Fault injection for tests and for the plan's P2 exit check: every read completes no earlier than /// `delay_us` after it was issued. 0 disables. void set_injected_delay_us(double delay_us); - /// Read with no ticket in flight (the worker updates these while reads are outstanding). + /// Read with no ticket in flight (the worker updates these while reads are outstanding; with the keep-alive + /// on it may also be counting a keep-alive read - `snapshot` takes a consistent copy). const ReaderStats& stats() const; + ReaderStats snapshot() const; void reset_stats(); uint64_t cache_capacity() const; uint64_t cache_size() const; diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp index 3a4d1ca6..8f6145bf 100644 --- a/include/strata/prefill/kernels.hpp +++ b/include/strata/prefill/kernels.hpp @@ -14,21 +14,24 @@ namespace strata::prefill { // ---- hyper-connection (n_embd 2560, hc 4, hc_lr 320) /// xn[t, c*2560 + d] = R[t,c,d] * rsqrt(mean_d R[t,c,:]^2 + eps) * w_norm[c*2560 + d]; also its BF16 image. -void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream); +/// `xn16_lo` (null: none) takes bf16(x - xn16): W.xn16 + W.xn16_lo is the product with ~16 mantissa bits of x. +void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream, + uint16_t* xn16_lo = nullptr); /// F-1: gr_norm without its FP32 output: the row scales rs[t*4 + c] and the BF16 image; gr_mix_r then reads R. -void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream); +void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream, + uint16_t* xn16_lo = nullptr); /// gr_mix with xn recomputed from R, rs and w_norm exactly as gr_norm computes it (the same bits). void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16, - int64_t T, void* stream, uint16_t* mixed_h = nullptr); + int64_t T, void* stream, uint16_t* mixed_h = nullptr, uint16_t* mixed16_lo = nullptr); /// F-2: gr_write, then gr_norm_rs of the next half (its norm weights) over the rows just written - the same bits as /// the two calls, without reading R back. void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps, - float* rs, uint16_t* xn16, int64_t T, void* stream); + float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr); /// lo16[t, k] = bf16(silu(lo[t, k] / hc)) -void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream); +void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo = nullptr); /// mixed[t, d] = mean_c xn[t, c, d] * sigmoid(gated[t, c, d]); FP32, BF16 and FP16 (either image may be null). void gr_mix(const float* xn, const float* gated, float* mixed, uint16_t* mixed16, int64_t T, void* stream, - uint16_t* mixed_h = nullptr); + uint16_t* mixed_h = nullptr, uint16_t* mixed16_lo = nullptr); /// R[t, c, d] += bo[t, d] * 2 sigmoid(inj[t, c] / hc) (inj has row stride inj_ld) void gr_write(float* R, const float* bo, const float* inj, int64_t inj_ld, int64_t T, void* stream); /// R[t, c, :] = e[t, :] for all four streams (the embedding broadcast). @@ -85,7 +88,7 @@ void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const in /// fp32 -> fp16 bits and fp32 -> bf16, n elements (the two activation images of the prompt GEMMs). void to_f16(const float* x, uint16_t* y, int64_t n, void* stream); -void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream); +void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream, uint16_t* ylo = nullptr); /// y = fp32(fp16(x)): what an FP16 store of x would read back (the FP16 indexer-key experiment) void round_f16(const float* x, float* y, int64_t n, void* stream); /// Expert blob -> FP16 (Q2_0 values are exact in FP16). diff --git a/serve/frontend.py b/serve/frontend.py index 48dc2dbf..e832be99 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -173,8 +173,10 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: return _late_system_to_user(messages), tools, kwargs -def anthropic_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: - """Anthropic Messages -> (template messages, template tools, template kwargs).""" +def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[dict], list[dict] | None, dict]: + """Anthropic Messages -> (template messages, template tools, template kwargs). `think_unasked`: a request + without "thinking", an effort or a budget gets the template's default (it thinks), as through 0.1.31; False + renders it without thinking (#278, the config's "anthropic_thinking": "on_request").""" messages = [] system = req.get("system") if system: @@ -219,6 +221,14 @@ def anthropic_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dic kwargs.update(effort_kwargs(effort)) elif isinstance(thinking, dict) and thinking.get("budget_tokens"): kwargs.update(budget_effort(thinking["budget_tokens"])) + elif thinking is None and not req.get("reasoning_budget_tokens") and not think_unasked: + # Opt-in (the config's "anthropic_thinking": "on_request"; the default thinks as 0.1.31 did, since a + # client that never asks would otherwise lose the thinking on every turn). Anthropic's thinking is + # opt-in there. Claude Code's helper calls (a session title, a topic check) ask for none + # and allow a few dozen tokens, which the model otherwise spent thinking and answered with no text at all. + # A config's reasoning_effort still applies: Service.with_shared sets output_config before this runs. A + # request that gives its own reasoning_budget_tokens (#123) asks for thinking, so it thinks as before. + kwargs["enable_thinking"] = False return _late_system_to_user(messages), tools, kwargs diff --git a/serve/server.py b/serve/server.py index 9642ad45..39271b99 100644 --- a/serve/server.py +++ b/serve/server.py @@ -30,6 +30,7 @@ import ctypes import json import os import queue +import re import signal import subprocess import sys @@ -50,6 +51,7 @@ from serve.frontend import (ChatTemplate, Event, OutputParser, anthropic_to_mess images_of, openai_to_messages) from serve.mcp import McpCancelled, hub_from_config # noqa: E402 from serve.winjob import contain # noqa: E402 +from serve.structured import StructuredOutputError, prepare_format, validated_json # noqa: E402 IM_END = "<|im_end|>" IMAGE_PAD = "<|image_pad|>" @@ -104,11 +106,51 @@ class EngineStarting(RuntimeError): not a 400 about the prompt.""" +class ModelBusy(RuntimeError): + """Explicit model controls must not interrupt active or queued requests.""" + + +class EngineStuck(RuntimeError): + """The engine process did not end after QUIT, terminate and kill: the server keeps it (and says so) rather than + reporting its GPU and RAM as given back.""" + + class GpuBusy(RuntimeError): """The model is unloaded and the GPU has less free VRAM than min_free_vram_mib: something else (a game, another model server) is using it, so the engine is not started into the little that is left.""" +ENGINE_REQUEST = re.compile( + r"prompt (?P\d+) tokens = (?P\d+) reused \+ \d+ read in (?P[\d.]+) ms \((?P[\d.]+) tok/s\), " + r"(?P\d+) generated in (?P[\d.]+) ms \((?P[\d.]+) tok/s\)") + + +_echoing: set[str] = set() # the logs echo_requests already follows (restart() runs StrataEngine.__init__ again) + + +def echo_requests(log_path: str, offset: int) -> None: + """STRATA_REQUEST_LINES=1: one stdout line per finished request, from the engine's own summary in its log. + + The engine's stderr goes to the log file (the start narrator reads it), so a supervisor that only sees this + process's output - a tray, llama-swap - has no per-request numbers. This re-states the engine's line with the + total the two times make: `request prompt P cached C output O prompt_read R ms total S ms prefill X tok/s decode Y + tok/s` (prompt_read: the time the engine spent reading the prompt's new tokens, not a time to first token). + """ + with open(log_path, "r", encoding="utf-8", errors="replace") as f: + f.seek(offset) + while True: + line = f.readline() + if not line: + time.sleep(0.2) + continue + m = ENGINE_REQUEST.search(line) + if m: + read_ms, gen_ms = float(m["read"]), float(m["gen_ms"]) + print("[strata] request prompt %s cached %s output %s prompt_read %.0f ms total %.0f ms prefill %s " + "tok/s decode %s tok/s" % (m["prompt"], m["reused"], m["gen"], read_ms, read_ms + gen_ms, m["pp"], + m["tg"]), flush=True) + + def narrate_start(log_path: str, offset: int, args: list, done: threading.Event, heartbeat=20.0) -> None: """While the engine starts, say in the server window what it is doing, from its log: the start reads tens of GB into RAM and locks part of it for the GPU, and on many PCs everything is slow or frozen for a minute or more - @@ -170,21 +212,14 @@ class StrataEngine: """ def __init__(self, exe: str, args: list[str], cwd: str | None = None, log: str | None = None, - env: dict | None = None): + env: dict | None = None, lazy: bool = False): self.spawn = (exe, list(args), cwd, log, env) # to start it again after it died (issue #27) paths = {k: v for k, v in zip(args, args[1:]) if k in ("--native", "--pack")} self.model_path = paths.get("--native") or paths.get("--pack", "pack/full") self.log_path = log - self.log = open(log, "a", encoding="utf-8") if log else subprocess.DEVNULL - loading = threading.Event() # set once READY: the narrator below stops - if log: - threading.Thread(target=narrate_start, args=(log, os.path.getsize(log), args, loading), - daemon=True).start() - self.proc = subprocess.Popen([exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, - stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env) - contain(self.proc) # ends with the server, however it ends (Windows) - self.max_context = 0 - self.unloaded = False # stopped on purpose (idle unload, POST /unload), not crashed + self.proc, self.pump, self.log = None, None, None + self.ended, self.unloaded = True, True + self.max_context = int(args[args.index("--max-context") + 1]) if "--max-context" in args else 4096 self.can_stop = False # the engine honours a STOP line mid-request (READY stop) self.last = {} self.info = {} # INFO key=value facts (engine 0.1.8+): kv, expert slots, ... (Monitor tab) @@ -194,6 +229,22 @@ class StrataEngine: self.info["version"] = json.loads((Path(exe).parent / "BUILD.json").read_text()).get("version") except (OSError, ValueError): self.info["version"] = None + if lazy: + return + self.ended, self.unloaded = False, False + self.log = open(log, "a", encoding="utf-8") if log else subprocess.DEVNULL + loading = threading.Event() # set once READY: the narrator below stops + if log: + threading.Thread(target=narrate_start, args=(log, os.path.getsize(log), args, loading), + daemon=True).start() + # once per log: the follower keeps reading the same (appended) log across restarts and reloads + if os.environ.get("STRATA_REQUEST_LINES") and os.path.abspath(log) not in _echoing: + _echoing.add(os.path.abspath(log)) + threading.Thread(target=echo_requests, args=(log, os.path.getsize(log)), daemon=True).start() + self.proc = subprocess.Popen([exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env) + contain(self.proc) # ends with the server, however it ends (Windows) + self.max_context = 0 for line in self.proc.stdout: if line.startswith("INFO "): for kv in line.split()[1:]: @@ -214,7 +265,8 @@ class StrataEngine: self.ended = False # READY: alive from here (restart() set it True, #344) # the engine's stdout on a thread, so a request can wait with a timeout (heartbeats, cancel checks) self.lines: queue.Queue = queue.Queue() - threading.Thread(target=self._pump, daemon=True).start() + self.pump = threading.Thread(target=self._pump, daemon=True) + self.pump.start() def _pump(self): proc, lines = self.proc, self.lines # this process's: a restart replaces both (#344) @@ -248,39 +300,24 @@ class StrataEngine: "smaller model (Q2_0 / IQ2_XS).") def alive(self) -> bool: - return not getattr(self, "ended", False) and self.proc.poll() is None + return self.proc is not None and not getattr(self, "ended", False) and self.proc.poll() is None def exit_code(self): + if self.proc is None: + return None try: return self.proc.wait(timeout=5) except subprocess.TimeoutExpired: return None def unload(self): - """Stop the engine process so its VRAM and RAM go back to the system (idle unload, POST /unload); the next - request starts it again with restart(). Only between requests: the caller holds the service's fifo.""" - try: - try: # QUIT first, as close() does: the engine frees its memory - self.proc.stdin.write("QUIT\n") - self.proc.stdin.flush() - self.proc.wait(timeout=20) - except (OSError, ValueError, subprocess.TimeoutExpired): - self.proc.terminate() - self.proc.wait(timeout=20) - except subprocess.TimeoutExpired: - self.proc.kill() - self.proc.wait(timeout=20) - except OSError: - pass - self.ended = True + """Release GPU/RAM between requests, retaining the spawn config for automatic reloading.""" + self.close() self.unloaded = True def restart(self): """Start the engine again (the same command) after it died; the new process has its own line queue.""" - try: - self.proc.kill() - except OSError: - pass + self.close() info = dict(self.info) # #344: not alive until READY - __init__ sets max_context to 0 and blocks until the engine says READY, and a # request that saw alive() in that window skipped load() and failed with "context (0)". __init__ clears @@ -417,12 +454,39 @@ class StrataEngine: break def close(self): + """End the engine process: QUIT first (the engine frees its memory itself - unpinning tens of GB can take + a while), then terminate, then kill, each given 20 s. Raises EngineStuck when it still runs after all three.""" + if self.proc is None: + return try: - self.proc.stdin.write("QUIT\n") - self.proc.stdin.flush() - self.proc.wait(timeout=10) - except Exception: + if self.proc.poll() is None: + try: + self.proc.stdin.write("QUIT\n") + self.proc.stdin.flush() + self.proc.stdin.close() # Windows' detached stdin reader must see EOF before shutdown + self.proc.wait(timeout=20) + except (OSError, ValueError, subprocess.TimeoutExpired): + self.proc.terminate() + self.proc.wait(timeout=20) + except subprocess.TimeoutExpired: self.proc.kill() + try: + self.proc.wait(timeout=20) + except subprocess.TimeoutExpired: + raise EngineStuck("Strata is still releasing GPU/RAM; retry unloading after it exits") from None + except OSError: + pass + finally: + if self.proc.poll() is not None: + if self.pump is not None: + self.pump.join(timeout=2) + self.proc.stdin.close() + self.proc.stdout.close() + if self.log not in (None, subprocess.DEVNULL): + self.log.close() + self.proc = None + self.ended = True + self.progress, self.last = None, {} class Vision: @@ -649,8 +713,19 @@ class Service: self.fifo = threading.Lock() self.embeddings = threading.local() # the current request's image embeddings file (GENI) self.api_key = "" # when set, /v1/* needs it (Bearer or x-api-key) + # #321: browser pages of these origins may call /v1/* (CORS; "*" = any page - only with an api_key that + # matters); empty = no CORS headers at all, as before + self.cors_origins: list[str] = [] + # #321: origins that count as Strata's own page for /settings and MCP tools, e.g. the web app reached through a + # reverse proxy or tunnel whose Host differs ("https://strata.example.com"); never a wildcard + self.trusted_origins: list[str] = [] self.status = {"busy": False, "queued": 0} # GET /status: what the model is doing right now self.rate = collections.deque(maxlen=32) # (time, generated) samples for the live tok/s window + # #332: the API request monitor (/api-monitor) keeps the last 100 requests' prompts and answers in memory, + # so it is off unless the config's "api_monitor" (or --api-monitor) turns it on + self.api_monitor = False + self.api_requests = collections.deque(maxlen=100) # bounded I/O in memory; no headers or API keys + self.request_trace = threading.local() self.history = collections.deque(maxlen=500) # the last finished requests, newest last (GET /metrics) # since the server started (the Monitor's totals, issue #35) self.totals = {"since": time.time(), "requests": 0, "prompt_tokens": 0, "reused": 0, "output_tokens": 0, @@ -667,6 +742,7 @@ class Service: self.min_free_vram_mib = 0 self.before_load = None self.reasoning_budget_tokens = 0 # #123: the config's default thinking budget (0: none) + self.anthropic_think_unasked = True # #278: "anthropic_thinking": "on_request" -> False self.stop_ids = set(tokenizer.encode(IM_END, parse_special=True) + tokenizer.encode("<|endoftext|>", parse_special=True)) @@ -772,8 +848,21 @@ class Service: self.last_request_at = time.time() if self.loaded() and not self._vision_down(): return + trace = getattr(self.request_trace, "record", None) + waiting = time.perf_counter() with self.fifo: - self.ensure_loaded() + loading = time.perf_counter() + if trace is not None: + with self.status_lock: + trace["queue_s"] += round(loading - waiting, 3) + trace["state"] = "loading" + try: + self.ensure_loaded() + finally: + if trace is not None: + with self.status_lock: + trace["load_s"] += round(time.perf_counter() - loading, 3) + trace["state"] = "queued" def unload(self, idle_for: float | None = None) -> str: """Stop the engine between requests: "unloaded", "not loaded", "busy" (a request is running or waiting, or @@ -807,7 +896,10 @@ class Service: def loop(): while True: time.sleep(max(1.0, min(30.0, self.idle_unload_s / 4))) - self.unload(idle_for=self.idle_unload_s) + try: + self.unload(idle_for=self.idle_unload_s) + except EngineStuck as e: # tried again at the next turn; the thread keeps running + print(f"[strata] idle unload: {e}", flush=True) threading.Thread(target=loop, daemon=True).start() def set_shared(self, defaults) -> dict: @@ -883,6 +975,37 @@ class Service: reading = self.status.get("busy") and self.status.get("first_token") is None return getattr(self.engine, "prefill_tok_s_mean", None) if reading else 0.0 + def begin_request(self, path, req): + """#332: a monitor record for this request, or None when the monitor is off (nothing is kept then).""" + if not self.api_monitor: + return None + raw = json.dumps(req, ensure_ascii=False, indent=2) + record = {"id": uuid.uuid4().hex[:12], "path": path, "model": req.get("model") or self.model, + "started_at": time.time(), "state": "queued", "stream": bool(req.get("stream")), + "response_format": (req.get("response_format") or {}).get("type") + if isinstance(req.get("response_format"), dict) else None, + "input": raw[:262144], "input_truncated": len(raw) > 262144, + "output": "", "reasoning": "", "output_truncated": False, "reasoning_truncated": False, + "queue_s": 0.0, "load_s": 0.0, "first_token_s": None, + "_clock": time.perf_counter()} + with self.status_lock: + self.api_requests.append(record) + self.request_trace.record = record + return record + + def request_records(self, request_id=None): + with self.status_lock: + records = list(self.api_requests) + if request_id: + record = next((r for r in records if r["id"] == request_id), None) + if record is None: + return None + return {k: v for k, v in record.items() if not k.startswith("_")} + return [{k: v for k, v in r.items() + if k not in ("input", "output", "reasoning", "response") and not k.startswith("_")} + | {"wallclock_s": r.get("wallclock_s", round(time.perf_counter() - r["_clock"], 3))} + for r in reversed(records)] + def metrics(self, all_requests=False) -> dict: """GET /metrics: what the Monitor tab shows - the engine's facts, what it is doing, the last requests, and the hardware (with a minute of history per series).""" @@ -936,6 +1059,9 @@ class Service: images = self.vision is not None return { "service": "strata", "model": self.model, + "loaded": self.loaded(), "auto_load": hasattr(self.engine, "restart"), + "structured_output": {"formats": ["json_object", "json_schema"], "method": "prompt_and_validate", + "constrained_decoding": False, "stream_buffered": True}, "engine": (getattr(self.engine, "info", {}) or {}).get("version"), "started": int(self.started_at), "uptime_s": int(time.time() - self.started_at), "cache_max_tokens": ctx, @@ -1060,12 +1186,17 @@ class Service: # Identity token: only a DONE line replaces engine.last, so a request that died, errored or was # disconnected must not have the PREVIOUS request's decode figures recorded as its own. engine_last0 = getattr(self.engine, "last", None) + trace = getattr(self.request_trace, "record", None) + waiting = time.perf_counter() with self.status_lock: self.status["queued"] += 1 try: with self.fifo: try: with self.status_lock: + if trace is not None: + trace["queue_s"] += round(time.perf_counter() - waiting, 3) + trace["state"] = "generating" self.status["queued"] -= 1 # issue #27: it died in an earlier request (or was unloaded) - start it again instead of failing self.ensure_loaded() @@ -1089,6 +1220,9 @@ class Service: yield "ping", None continue n += 1 + if trace is not None and trace["first_token_s"] is None: + with self.status_lock: + trace["first_token_s"] = round(time.perf_counter() - trace["_clock"], 3) if t in self.stop_ids: finish = "stop" raw_ids.append(t) @@ -1426,6 +1560,30 @@ def openai_collect(chunks) -> dict: return out +def structured_chunks(chunks, validator): + """Buffer structured streams so a client never receives unvalidated content.""" + buffered = [] + heartbeat = time.monotonic() + try: + for chunk in chunks: + if chunk is not None: + buffered.append(chunk) + if chunk is None or time.monotonic() - heartbeat >= 1: + heartbeat = time.monotonic() + yield None + result = openai_collect(buffered) + choice = result["choices"][0] + content = validated_json(choice["message"]["content"], validator, choice["finish_reason"]) + yield buffered[0] + delta = {"content": content} + if choice["message"].get("reasoning_content"): + delta["reasoning_content"] = choice["message"]["reasoning_content"] + yield {**buffered[0], "choices": [{"index": 0, "delta": delta, "finish_reason": None}]} + yield buffered[-1] + finally: + chunks.close() + + # ------------------------------------------------------------------------------------------------ Anthropic def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, cancel): mid = "msg_" + uuid.uuid4().hex[:24] @@ -1529,13 +1687,58 @@ def make_handler(svc: Service): class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.0" # SSE ends by closing the connection + record = None # #332: this request's monitor record, if kept + def log_message(self, fmt, *args): pass + def _note(self, **values): + """#332: what the monitor shows about this request (nothing when the monitor is off).""" + if self.record is not None: + with svc.status_lock: + self.record.update(values) + + def _cors(self): + """#321: CORS headers for an API path (/v1/*) and an origin the config lists in cors_origins - nothing + otherwise, so a browser keeps every other page away from the API, /settings, /unload and the MCP tools.""" + if not svc.cors_origins or not self.path.split("?")[0].startswith("/v1/"): + return + origin = (self.headers.get("Origin") or "").rstrip("/") + if "*" in svc.cors_origins: + allow = "*" + elif origin and origin in svc.cors_origins: + allow = origin + self.send_header("Vary", "Origin") + else: + return + self.send_header("Access-Control-Allow-Origin", allow) + self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") + # the headers the preflight asks for (SDKs add their own; "*" does not cover Authorization) + asked = self.headers.get("Access-Control-Request-Headers") + self.send_header("Access-Control-Allow-Headers", + asked or "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta") + self.send_header("Access-Control-Max-Age", "600") + + def do_OPTIONS(self): + # a CORS preflight: no credentials come with it, so no API key; the headers only for cors_origins + self.send_response(204) + self._cors() + self.send_header("Content-Length", "0") + self.end_headers() + def _json(self, code, obj): + if self.record is not None: + with svc.status_lock: + self.record["http_status"] = code + raw = json.dumps(obj, ensure_ascii=False, indent=2) + self.record.update(response=raw[:262144], response_truncated=len(raw) > 262144) + for key in ("error", "usage", "timings"): + if key in obj: + self.record[key] = obj[key] body = json.dumps(obj, ensure_ascii=False).encode() self.send_response(code) self.send_header("Content-Type", "application/json") + self._cors() self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) @@ -1590,6 +1793,15 @@ def make_handler(svc: Service): # the last 12 requests; `?requests=all` every one kept (the Monitor's "Show all", issue #35) self._json(200, svc.metrics(all_requests="requests=all" in self.path)) return + if path == "/api/requests" and svc.api_monitor: + if self._authorized(): + request_id = parse_qs(urlsplit(self.path).query).get("id", [None])[0] + records = svc.request_records(request_id) + self._json(404 if records is None else 200, + {"error": {"message": "request no longer retained"}} if records is None else + records if request_id else {"requests": records, "retention": 100, "persistent": False, + "loaded": svc.loaded(), "auto_load": hasattr(svc.engine, "restart")}) + return if path == "/settings": if self._authorized(): self._json(200, {"shared": bool(svc.shared), "defaults": svc.shared}) @@ -1599,17 +1811,17 @@ def make_handler(svc: Service): if self._authorized(): self._json(200, svc.mcp.status() if svc.mcp else {"servers": [], "tools": 0}) return - if path == "": - body = (ROOT / "serve" / "web" / "index.html").read_bytes() + if path == "" or (path == "/api-monitor" and svc.api_monitor): + body = (ROOT / "serve" / "web" / ("monitor.html" if path else "index.html")).read_bytes() self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) - elif path == "/health": + elif path in ("/health", "/api/health"): self._json(200, {"status": "ok", "max_context": svc.engine.max_context, "model": svc.model, "images": svc.vision is not None, "api_key": bool(svc.api_key), - "loaded": svc.loaded()}) + "loaded": svc.loaded(), "service": "strata"}) elif path == "/status": if not self._authorized(): # #212: it shows the end of the last answer return @@ -1662,7 +1874,11 @@ def make_handler(svc: Service): self._settings() return if path == "/unload": # give the GPU back now (between requests) - r = svc.unload() + try: + r = svc.unload() + except EngineStuck as e: + self._json(503, {"error": {"type": "server_error", "message": str(e)}}) + return self._json(409 if r == "busy" else 200, {"status": r}) return if path == "/load": # load now, e.g. ahead of a request @@ -1674,20 +1890,67 @@ def make_handler(svc: Service): return try: req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}") + if not isinstance(req, dict): + raise ValueError("send a JSON object") + if path in ("/v1/load", "/v1/unload"): + if not self._own_page("the model can be loaded or unloaded"): + return + if req.get("model") not in (None, svc.model): + self._json(404, {"error": {"message": "model not found"}}) + return + if path == "/v1/unload": + result = svc.unload() + if result == "busy": + raise ModelBusy("a request is running or queued") + else: + if not svc.fifo.acquire(blocking=False): + raise ModelBusy("a request is running or queued") + try: + with svc.status_lock: + if svc.status.get("busy") or svc.status.get("queued"): + raise ModelBusy("a request is running or queued") + svc.ensure_loaded() + svc.last_request_at = time.time() + finally: + svc.fifo.release() + result = "loaded" + self._json(200, {"status": result, **svc.v1_status()}) + return if path in ("/v1/chat/completions", "/v1/messages"): - svc.load() # unloaded: load first (or 503 while the GPU is busy) + self.record = svc.begin_request(path, req) if path == "/v1/chat/completions": self._openai(req) elif path == "/v1/messages": self._anthropic(req) + elif path == "/v1/messages/count_tokens": + self._count_tokens(req) else: self._json(404, {"error": {"message": "not found"}}) except ValueError as e: self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}}) + except ModelBusy as e: + self._json(409, {"error": {"type": "model_busy", "message": str(e)}}) + except StructuredOutputError as e: + self._json(502, {"error": {"type": "structured_output_failed", "code": "structured_output_failed", + "message": str(e)}}) except (GpuBusy, EngineStarting) as e: self._json(503, {"error": {"type": "server_error", "message": str(e)}}) except EngineDied as e: # before the answer started (not streamed) self._json(503, {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}}) + except EngineStuck as e: # an unload or restart that could not end the engine + self._json(503, {"error": {"type": "server_error", "message": str(e)}}) + + except OSError: + self._note(outcome="disconnected") + raise # as before #332: the server's own handling + finally: + record = self.record + if record is not None: + with svc.status_lock: + record["wallclock_s"] = round(time.perf_counter() - record["_clock"], 3) + record["finished_at"] = time.time() + record["state"] = "error" if record.get("error") else record.get("outcome", "completed") + svc.request_trace.record = None def _props(self): model = parse_qs(urlsplit(self.path).query).get("model", [svc.model])[0] @@ -1705,7 +1968,7 @@ def make_handler(svc: Service): params["n_predict"] = svc.shared.get("max_tokens", -1) props = {"default_generation_settings": {"n_ctx": svc.engine.max_context, "params": params}, "total_slots": 1, "model_alias": svc.model, "chat_template": svc.template.source, - "modalities": {"vision": svc.vision is not None}, "models_autoload": False, + "modalities": {"vision": svc.vision is not None}, "models_autoload": hasattr(svc.engine, "restart"), "is_sleeping": not svc.loaded()} if getattr(svc.engine, "model_path", None): props["model_path"] = svc.engine.model_path @@ -1720,9 +1983,14 @@ def make_handler(svc: Service): if not self.headers.get("Content-Type", "").startswith("application/json"): self._json(415, {"error": {"message": "send application/json"}}) return False - origin = self.headers.get("Origin") - if origin and origin.split("://", 1)[-1] != self.headers.get("Host", ""): - self._json(403, {"error": {"message": f"{what} only from Strata's own page"}}) + # The Origin must be this server's own address (host and port), or an origin the config trusts + # (trusted_origins: the web app behind a reverse proxy or tunnel). Headers a proxy adds (X-Forwarded-*, + # CF-Ray, CF-Connecting-IP) prove nothing about the page that sent the request, so they open nothing. + origin = (self.headers.get("Origin") or "").rstrip("/") + if origin and origin.split("://", 1)[-1] != self.headers.get("Host", "") and \ + origin not in svc.trusted_origins: + self._json(403, {"error": {"message": f"{what} only from Strata's own page (or an origin in the " + f"config's trusted_origins)"}}) return False return True @@ -1742,14 +2010,55 @@ def make_handler(svc: Service): self._json(200, {"shared": bool(shared), "defaults": shared}) def _sse(self): + self._note(http_status=200) self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.send_header("Cache-Control", "no-cache") + self.send_header("X-Accel-Buffering", "no") # nginx and similar proxies pass each event at once + self._cors() self.end_headers() + def _capture(self, items, api): + """Retain bounded input/output for the monitor without changing the API response (the items as they + are when the monitor is off).""" + if self.record is None: + return items + return self._captured(items, api) + + def _captured(self, items, api): + try: + for item in items: + if item is not None: + if api == "openai": + delta = item["choices"][0]["delta"] + content, reasoning = delta.get("content", ""), delta.get("reasoning_content", "") + usage, timings = item.get("usage"), item.get("timings") + else: + _, event = item + delta = event.get("delta", {}) + content, reasoning = delta.get("text", ""), delta.get("thinking", "") + usage, timings = event.get("usage"), None + with svc.status_lock: + for name, value in (("output", content), ("reasoning", reasoning)): + if value: + combined = self.record[name] + value + self.record[name] = combined[:262144] + self.record[name + "_truncated"] |= len(combined) > 262144 + if usage: + self.record["usage"] = usage + if timings: + self.record["timings"] = timings + yield item + finally: + items.close() + def _openai(self, req): req = svc.with_shared(req, "openai") messages, tools, kw = openai_to_messages(req) + messages, validator = prepare_format(req.get("response_format"), messages) + if validator is not None and (tools or req.get("strata_mcp")): + raise ValueError("structured response_format with tools/MCP is not supported") + svc.load() max_req = max_new = int(req.get("max_completion_tokens") or req.get("max_tokens") or 0) # 0/-1: the rest use_mcp = req.get("strata_mcp") is True and svc.mcp is not None # the web app's opt-in (serve/mcp.py) own = {t.get("name") for t in tools or []} @@ -1767,6 +2076,9 @@ def make_handler(svc: Service): run = run_with_mcp(svc, svc.mcp, messages, tools, kw, ids, thinking, max_new, max_req, req, cancel, {t["name"] for t in extra}) if use_mcp else None chunks = openai_chunks(svc, req, ids, thinking, tools, max_new, cancel, run=run) + if validator is not None: + chunks = structured_chunks(chunks, validator) + chunks = self._capture(chunks, "openai") if not req.get("stream"): return self._json(200, openai_collect(chunks)) self._sse() @@ -1779,24 +2091,41 @@ def make_handler(svc: Service): self.wfile.flush() self.wfile.write(b"data: [DONE]\n\n") except OSError: + self._note(outcome="disconnected") cancel.set() # client went away: stop the engine chunks.close() except EngineDied as e: # mid-stream: say so, then end the stream properly err = {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}} + self._note(error=err["error"]) + self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") + except StructuredOutputError as e: + err = {"error": {"type": "structured_output_failed", "code": "structured_output_failed", "message": str(e)}} + self._note(error=err["error"]) self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") except ValueError as e: # the engine's ERR after the stream started: the err = {"error": {"type": "server_error", "message": str(e)}} # headers are sent, so no 400 now + self._note(error=err["error"]) self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") - def _anthropic(self, req): + def _count_tokens(self, req): + """Anthropic's token count, which Claude Code asks for its context figures: the prompt this server would + read for the same request, rendered and tokenized - the model does not run.""" req = svc.with_shared(req, "anthropic") - messages, tools, kw = anthropic_to_messages(req) + messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked) + prompt = svc.template.render(messages, tools=tools, **kw) + self._json(200, {"input_tokens": len(svc.tok.encode(prompt, parse_special=True))}) + + def _anthropic(self, req): + svc.load() + req = svc.with_shared(req, "anthropic") + messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked) max_new = int(req.get("max_tokens") or 0) # 0/-1: the rest of the context svc.reasoning_budget(req) # a bad value is a 400 before anything is sent ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new) _debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids)) cancel = threading.Event() events = anthropic_events(svc, req, ids, thinking, tools, max_new, cancel) + events = self._capture(events, "anthropic") if not req.get("stream"): return self._json(200, anthropic_collect(events)) self._sse() @@ -1810,13 +2139,16 @@ def make_handler(svc: Service): json.dumps(e, ensure_ascii=False).encode() + b"\n\n") self.wfile.flush() except OSError: + self._note(outcome="disconnected") cancel.set() events.close() except EngineDied as e: # mid-stream: Anthropic's error event err = {"type": "error", "error": {"type": "api_error", "message": f"{e}; the next request restarts it"}} + self._note(error=err["error"]) self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n") except ValueError as e: # the engine's ERR after the stream started err = {"type": "error", "error": {"type": "api_error", "message": str(e)}} + self._note(error=err["error"]) self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n") return Handler @@ -1878,6 +2210,28 @@ def serve(svc: Service, host="127.0.0.1", port=8095) -> ThreadingHTTPServer: return httpd +def origins_of(value, key: str, wildcard: bool) -> list[str]: + """#321: a config's origin list ("https://chat.example.com" or a list of them) - scheme://host[:port], no path; + "*" only where `wildcard` allows it. A wrong entry stops the start rather than opening less or more than meant.""" + if value is None or value == "" or value == []: + return [] + items = [value] if isinstance(value, str) else value + if not isinstance(items, list) or not all(isinstance(x, str) for x in items): + raise SystemExit(f"[strata] {key}: expected an origin or a list of origins") + out = [] + for x in items: + x = x.strip().rstrip("/") + if x == "*" and wildcard: + out.append(x) + continue + scheme, sep, rest = x.partition("://") + if scheme not in ("http", "https") or not sep or not rest or "/" in rest or "*" in rest: + raise SystemExit(f"[strata] {key}: {x!r} is not an origin like https://chat.example.com" + + ("" if wildcard else " (no wildcards here)")) + out.append(x) + return out + + SHARED_KEYS = ("reasoning_effort", "temperature", "top_p", "top_k", "seed", "max_tokens", "experimental_speed_projection") @@ -2001,6 +2355,10 @@ def main() -> int: ap.add_argument("--mcp-config", help="a JSON file with MCP servers in Claude Desktop's format ({\"mcpServers\": " "{...}}); the web app's chat can use their tools (also \"mcp_servers\" in " "the config)") + ap.add_argument("--lazy", action="store_true", help="start the text-only API unloaded; load on first request") + ap.add_argument("--api-monitor", action="store_true", + help="the API request monitor at /api-monitor: keeps the last 100 requests' prompts and answers in " + "memory (also \"api_monitor\": true in the config; off by default)") ap.add_argument("--idle-unload", type=float, default=None, metavar="SECONDS", help="unload the model after this many seconds without requests, so other programs (games, other " "model servers) can use the VRAM; the next request loads it again (also \"idle_unload_s\" " @@ -2045,14 +2403,24 @@ def main() -> int: if sampling_defaults: pretty = ", ".join(f"{k}={v}" for k, v in sampling_defaults.items()) print(f"[strata] sampling defaults from the config: {pretty}", flush=True) + lazy = a.lazy or cfg.get("lazy_load") is True + if lazy and cfg.get("vision"): + ap.error("lazy loading is text-only; disable vision in the config") if cfg.get("vision"): print("loading the vision encoder ...", flush=True) - vision = Vision(cfg["vision"], log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None, - env=env) - print("loading the model (the first start takes a minute or two) ...", flush=True) + # relative paths are the config's cwd's, as for the engine below + vcfg = {k: (os.path.abspath(os.path.join(cfg.get("cwd") or ".", v)) + if k in ("exe", "mmproj", "model") and isinstance(v, str) and not os.path.isabs(v) else v) + for k, v in cfg["vision"].items()} + vision = Vision(vcfg, log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None, env=env) + print("model unloaded; the first request loads it ..." if lazy else + "loading the model (the first start takes a minute or two) ...", flush=True) if len(gpu_list(cfg)) > 1: print(f"[strata] layer split across GPUs {gpu_list(cfg)} ({cfg.get('layer_split') or 'auto'})", flush=True) - engine = StrataEngine(cfg["exe"], engine_args(cfg), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env) + # a relative "exe" is the config's cwd's: Windows' CreateProcess resolves "engine/strata.exe" against nothing + # it is told about (WinError 2), so it is made absolute here + exe = cfg["exe"] if os.path.isabs(cfg["exe"]) else os.path.abspath(os.path.join(cfg.get("cwd") or ".", cfg["exe"])) + engine = StrataEngine(exe, engine_args(cfg), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env, lazy=lazy) warn_tight_ram(engine.info.get("arena_mib")) else: engine, vision, sampling_defaults = MockEngine(tok, a.script or [ @@ -2076,10 +2444,25 @@ def main() -> int: file=sys.stderr) return 2 svc.api_key = a.api_key or cfg.get("api_key", "") + svc.cors_origins = origins_of(cfg.get("cors_origins"), "cors_origins", wildcard=True) + svc.trusted_origins = origins_of(cfg.get("trusted_origins"), "trusted_origins", wildcard=False) + svc.api_monitor = a.api_monitor or cfg.get("api_monitor") is True + if svc.api_monitor: + print("[strata] API request monitor on (/api-monitor): the last 100 requests' prompts and answers are kept in " + "memory" + ("" if svc.api_key else "; anyone who can reach this server can read them (no API key)"), + flush=True) + if svc.cors_origins: + print(f"[strata] CORS on /v1/* for {', '.join(svc.cors_origins)}" + + ("" if svc.api_key or "*" not in svc.cors_origins else + " - WARNING: any web page may use the model (no API key)"), flush=True) svc.idle_unload_s = a.idle_unload if a.idle_unload is not None else float(cfg.get("idle_unload_s") or 0) svc.min_free_vram_mib = a.min_free_vram_mib if a.min_free_vram_mib is not None else \ int(cfg.get("min_free_vram_mib") or 0) svc.before_load = a.before_load or cfg.get("before_load") or None + mode = str(cfg.get("anthropic_thinking") or "model") # #278: "on_request" = only when the request asks + if mode not in ("model", "on_request"): + raise SystemExit(f"[strata] config anthropic_thinking must be \"model\" or \"on_request\", not {mode!r}") + svc.anthropic_think_unasked = mode == "model" if cfg.get("reasoning_budget_tokens") is not None: # #123: a default thinking budget for every request try: svc.reasoning_budget_tokens = cfg["reasoning_budget_tokens"] diff --git a/serve/structured.py b/serve/structured.py new file mode 100644 index 00000000..b5f079cc --- /dev/null +++ b/serve/structured.py @@ -0,0 +1,147 @@ +"""JSON response formats at the HTTP boundary: prompt once, validate before delivery. + +The native engine has no grammar decoder. Failed generations are errors, never +silently retried or returned as successful structured output. + +`jsonschema` is optional (no new hard dependency of the server): json_object needs only the standard library, and +json_schema is checked against its schema when the package is installed - without it, only that the answer is one +JSON object, and the server says so once. +""" +import json +import threading + + +class StructuredOutputError(RuntimeError): + pass + + +class _ObjectOnly: + """The validator for json_object, and for json_schema without jsonschema: one JSON object.""" + + def iter_errors(self, value): + if not isinstance(value, dict): + yield _ObjectError() + + +class _ObjectError: + absolute_path = () + message = "the answer is not a JSON object" + + +_jsonschema = None # (validators, SchemaError, Registry, NoSuchResource), False when not installed +_jsonschema_lock = threading.Lock() + + +def jsonschema_modules(): + """jsonschema, imported on first use; None when it is not installed (said once, in the server window).""" + global _jsonschema + with _jsonschema_lock: + if _jsonschema is None: + try: + from jsonschema import validators + from jsonschema.exceptions import SchemaError + from referencing import Registry + from referencing.exceptions import NoSuchResource + _jsonschema = (validators, SchemaError, Registry, NoSuchResource) + except ImportError: + _jsonschema = False + print('[strata] response_format json_schema: the Python package jsonschema is not installed, so ' + 'answers are only checked to be one JSON object (python -m pip install "jsonschema>=4.23,<5")', + flush=True) + return _jsonschema or None + + +def prepare_format(response_format, messages): + if response_format is None: + return messages, None + if not isinstance(response_format, dict): + raise ValueError("response_format must be an object") + kind = response_format.get("type") + if kind == "text": + return messages, None + if kind == "json_object": + schema = {"type": "object"} + modules = None # the standard library is enough for "one JSON object" + elif kind == "json_schema": + spec = response_format.get("json_schema") + if not isinstance(spec, dict) or not isinstance(spec.get("schema"), dict): + raise ValueError("response_format.json_schema needs a schema object") + if not isinstance(spec.get("name"), str) or not spec["name"]: + raise ValueError("response_format.json_schema needs a name") + if "strict" in spec and not isinstance(spec["strict"], bool): + raise ValueError("response_format.json_schema.strict must be boolean") + schema = spec["schema"] + if schema.get("type") != "object": + raise ValueError("response_format schema must have type object at its root") + modules = jsonschema_modules() + else: + raise ValueError("response_format.type must be text, json_object or json_schema") + + def check_refs(node): + if isinstance(node, dict): + for key, value in node.items(): + if key in ("$ref", "$dynamicRef") and isinstance(value, str) and not value.startswith("#"): + raise ValueError("response_format supports only local schema references (#...)") + check_refs(value) + elif isinstance(node, list): + for value in node: + check_refs(value) + check_refs(schema) + if modules is None: + validator = _ObjectOnly() + else: + validators, SchemaError, Registry, NoSuchResource = modules + + def no_remote(uri): + raise NoSuchResource(ref=uri) + + try: + cls = validators.validator_for(schema) + cls.check_schema(schema) + validator = cls(schema, registry=Registry(retrieve=no_remote)) + except SchemaError as exc: + raise ValueError(f"invalid response_format schema: {exc.message}") from exc + directive = ("OUTPUT FORMAT REQUIREMENT: Return exactly one JSON object matching the JSON Schema below. " + "No Markdown, headings, code fences, commentary, or text outside the JSON. " + "Use every required field, correct types, and only allowed fields. " + "Put all requested writing inside the appropriate JSON string fields.\nJSON Schema:\n" + + json.dumps(schema, ensure_ascii=False, allow_nan=False, separators=(",", ":"))) + messages = [dict(message) for message in messages] + if messages and messages[0].get("role") == "system": + content = messages[0].get("content") or "" + if isinstance(content, list): + messages[0]["content"] = content + [{"type": "text", "text": directive}] + else: + messages[0]["content"] = content + "\n\n" + directive + else: + messages.insert(0, {"role": "system", "content": directive}) + return messages, validator + + +def validated_json(text, validator, finish): + def pairs(items): + obj = {} + for key, value in items: + if key in obj: + raise ValueError(f"duplicate JSON key: {key}") + obj[key] = value + return obj + + def constant(value): + raise ValueError(f"invalid JSON constant: {value}") + + if finish != "stop": + raise StructuredOutputError(f"structured output was incomplete (finish_reason={finish}); increase the output budget") + try: + value = json.loads(text or "", object_pairs_hook=pairs, parse_constant=constant) + canonical = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) + except (ValueError, TypeError) as exc: + raise StructuredOutputError(f"model did not return valid JSON: {exc}") from exc + try: + error = next(validator.iter_errors(value), None) + except Exception as exc: + raise StructuredOutputError(f"could not validate structured output: {exc}") from exc + if error is not None: + path = "/" + "/".join(str(part) for part in error.absolute_path) + raise StructuredOutputError(f"model output failed the JSON Schema at {path}: {error.message}") + return canonical diff --git a/serve/test_lifecycle.py b/serve/test_lifecycle.py new file mode 100644 index 00000000..1d9f58c4 --- /dev/null +++ b/serve/test_lifecycle.py @@ -0,0 +1,170 @@ +"""Model discovery, on-demand loading and safe unloading over the actual HTTP API.""" +import json +import io +import subprocess +import time +import unittest +import urllib.error +import urllib.request +from pathlib import Path +from unittest import mock + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, EngineDied, EngineStuck, MockEngine, Service, StrataEngine, serve + + +class ResidentEngine(StrataEngine): + def __init__(self, tok): + self.reply = MockEngine(tok, "Hello.", max_context=4096) + self.max_context, self.info, self.last = 4096, {}, {} + self.loaded, self.starts, self.closes = False, 0, 0 + self.unloaded = True + self.progress = None + + def alive(self): + return self.loaded + + def exit_code(self): + return None + + def restart(self): + self.loaded = True + self.starts += 1 + self.unloaded = False + + def close(self): + self.loaded = False + self.closes += 1 + + def unload(self): + self.close() + self.unloaded = True + + def generate(self, *args, **kwargs): + yield from self.reply.generate(*args, **kwargs) + + +class Lifecycle(unittest.TestCase): + def test_close_sends_eof_before_waiting_for_windows_reader(self): + engine = StrataEngine("missing-executable", [], lazy=True) + proc = mock.Mock() + proc.stdin, proc.stdout = io.StringIO(), io.StringIO() + proc.poll.side_effect = [None, 0] + proc.wait.side_effect = lambda **kwargs: self.assertTrue(proc.stdin.closed) + engine.proc = proc + engine.close() + self.assertIsNone(engine.proc) + proc.kill.assert_not_called() + + def test_close_does_not_forget_a_process_still_exiting(self): + engine = StrataEngine("missing-executable", [], lazy=True) + proc = mock.Mock() + proc.stdin, proc.stdout = io.StringIO(), io.StringIO() + proc.poll.return_value = None + proc.wait.side_effect = subprocess.TimeoutExpired("engine", 2) + engine.proc = proc + with self.assertRaisesRegex(EngineStuck, "still releasing"): + engine.close() + self.assertIs(engine.proc, proc) + proc.terminate.assert_called_once() + proc.kill.assert_called_once() + + def test_close_terminates_before_it_kills(self): + # an engine that does not end on QUIT is terminated first (as the unload always did); kill is the last resort + engine = StrataEngine("missing-executable", [], lazy=True) + proc = mock.Mock() + proc.stdin, proc.stdout = io.StringIO(), io.StringIO() + proc.poll.side_effect = [None, 0] + proc.wait.side_effect = [subprocess.TimeoutExpired("engine", 20), 0] + engine.proc = proc + engine.close() + proc.terminate.assert_called_once() + proc.kill.assert_not_called() + self.assertIsNone(engine.proc) + + def test_native_lazy_constructor_does_not_start_a_process(self): + engine = StrataEngine("missing-executable", ["--max-context", "16384"], lazy=True) + self.assertFalse(engine.alive()) + self.assertEqual(engine.max_context, 16384) + self.assertIsNone(engine.exit_code()) + engine.close() + + def setUp(self): + tok = ByteTokenizer() + self.engine = ResidentEngine(tok) + self.svc = Service(self.engine, tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def request(self, path, body=None, headers=None): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None, + headers={"Content-Type": "application/json", **(headers or {})}) + try: + response = urllib.request.urlopen(req, timeout=10) + except urllib.error.HTTPError as error: + response = error + with response: + data = response.read().decode() + return response.status, data if "event-stream" in response.headers.get("Content-Type", "") else json.loads(data) + + def test_discover_chat_unload_and_stream_reload(self): + self.assertEqual(self.request("/api/health")[1]["service"], "strata") + self.assertFalse(self.request("/v1/status")[1]["loaded"]) + self.assertEqual(self.request("/v1/models")[1]["data"][0]["status"]["value"], "unloaded") + self.assertTrue(self.request("/props")[1]["models_autoload"]) + self.assertEqual(self.engine.starts, 0) + chat = {"messages": [{"role": "user", "content": "Hello"}], "max_tokens": 32, "reasoning_effort": "none"} + for _ in range(2): + code, answer = self.request("/v1/chat/completions", chat) + self.assertEqual(code, 200) + self.assertEqual(answer["choices"][0]["message"]["content"], "Hello.") + self.assertEqual(self.engine.starts, 1) + self.assertFalse(self.request("/v1/unload", {})[1]["loaded"]) + code, stream = self.request("/v1/chat/completions", {**chat, "stream": True}) + self.assertEqual(code, 200) + self.assertIn("data: [DONE]", stream) + self.assertEqual(self.engine.starts, 2) + + def test_busy_auth_and_foreign_origin_cannot_unload(self): + self.engine.loaded = True + with self.svc.fifo: + self.assertEqual(self.request("/v1/unload", {})[0], 409) + self.svc.api_key = "local-secret" + self.assertEqual(self.request("/v1/unload", {})[0], 401) + self.assertEqual(self.request("/v1/unload", {}, {"Authorization": "Bearer local-secret", + "Origin": "https://other.example"})[0], 403) + self.assertEqual(self.engine.closes, 0) + self.assertTrue(self.engine.loaded) + self.assertEqual(self.request("/v1/unload", {}, {"Authorization": "Bearer local-secret"})[0], 200) + + def test_an_engine_that_died_on_load_is_reported_as_such(self): + # EngineDied is a RuntimeError: it keeps its own answer ("the next request restarts it") + def died(): + raise EngineDied("the engine ended while it started") + self.engine.restart = died + code, body = self.request("/v1/chat/completions", {"messages": [{"role": "user", "content": "Hello"}]}) + self.assertEqual(code, 503) + self.assertIn("the next request restarts it", body["error"]["message"]) + + def test_explicit_load_and_model_matching(self): + self.assertEqual(self.request("/v1/load", {"model": "other-model"})[0], 404) + self.assertEqual(self.engine.starts, 0) + before = time.time() + code, status = self.request("/v1/load", {"model": self.svc.model}) + self.assertEqual(code, 200) + self.assertTrue(status["loaded"]) + self.assertEqual(self.engine.starts, 1) + self.assertGreaterEqual(self.svc.last_request_at, before) + self.svc.status["queued"] = 1 + self.assertEqual(self.request("/v1/load", {})[0], 409) + self.assertEqual(self.request("/v1/unload", {})[0], 409) + self.assertEqual(self.engine.closes, 0) + self.assertEqual(self.request("/v1/load", {}, {"Content-Type": "text/plain"})[0], 415) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_monitor.py b/serve/test_monitor.py new file mode 100644 index 00000000..ad554e00 --- /dev/null +++ b/serve/test_monitor.py @@ -0,0 +1,198 @@ +"""Request inspection through HTTP; no native model or GPU is required.""" +import json +import threading +import time +import unittest +import urllib.error +import urllib.request +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from unittest import mock + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, EngineDied, MockEngine, Service, serve + + +class ReloadableEngine(MockEngine): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.running, self.unloaded = True, False + + def alive(self): + return self.running + + def unload(self): + self.running, self.unloaded = False, True + + def restart(self): + self.running, self.unloaded = True, False + + +class MonitorOff(unittest.TestCase): + """#332 is opt-in: by default no prompt or answer is kept, and the monitor's endpoints do not exist.""" + + def test_off_by_default(self): + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "Hello.", max_context=4096), tok, + ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + req = urllib.request.Request(base + "/v1/chat/completions", headers={"Content-Type": "application/json"}, + data=json.dumps({"messages": [{"role": "user", "content": "secret"}]}).encode()) + with urllib.request.urlopen(req, timeout=10) as r: + self.assertEqual(r.status, 200) + self.assertEqual(len(svc.api_requests), 0) + for path in ("/api/requests", "/api-monitor"): + with self.assertRaises(urllib.error.HTTPError) as e: + urllib.request.urlopen(base + path, timeout=10) + self.assertEqual(e.exception.code, 404, path) + e.exception.close() + finally: + httpd.shutdown() + httpd.server_close() + + +class Monitor(unittest.TestCase): + def setUp(self): + self.tok = ByteTokenizer() + self.engine = ReloadableEngine(self.tok, "Thought.\nHello .", max_context=16384) + self.svc = Service(self.engine, self.tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + self.svc.api_monitor = True # opt-in ("api_monitor": true / --api-monitor) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def request(self, path, body=None, headers=None): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None, + headers={"Content-Type": "application/json", **(headers or {})}) + try: + response = urllib.request.urlopen(req, timeout=10) + except urllib.error.HTTPError as error: + response = error + with response: + raw = response.read().decode() + return response.status, json.loads(raw) if "application/json" in response.headers.get("Content-Type", "") else raw + + def chat(self, api="openai", **kwargs): + # Anthropic thinks only when asked (#278): "thinking" there, reasoning_effort for OpenAI + think = {"thinking": {"type": "enabled", "budget_tokens": 1024}} if api == "anthropic" else {"reasoning_effort": "low"} + return self.request("/v1/messages" if api == "anthropic" else "/v1/chat/completions", + {"messages": [{"role": "user", "content": "Say hello."}], + "max_tokens": 256, **think, **kwargs}) + + def latest(self): + summary = self.request("/api/requests")[1]["requests"][0] + return self.request("/api/requests?id=" + summary["id"])[1] + + def test_output_and_reasoning_for_both_dialects_and_stream_modes(self): + for api in ("openai", "anthropic"): + for stream in (False, True): + with self.subTest(api=api, stream=stream): + code, reply = self.chat(api, stream=stream) + self.assertEqual(code, 200) + record = self.latest() + self.assertEqual(record["state"], "completed") + self.assertEqual(record["http_status"], 200) + self.assertIn("Say hello.", record["input"]) + self.assertIn("", record["output"]) + self.assertIn("Thought.", record["reasoning"]) + self.assertGreater(record["usage"].get("completion_tokens", record["usage"].get("output_tokens", 0)), 0) + self.assertGreaterEqual(record["wallclock_s"], record["first_token_s"]) + self.assertNotIn("_clock", record) + if not stream: + self.assertEqual(json.loads(record["response"]), reply) + else: + self.assertNotIn("response", record) + + def test_error_and_engine_death_are_not_successes(self): + self.assertEqual(self.chat(max_tokens=20000)[0], 400) + self.assertEqual(self.latest()["state"], "error") + for api in ("openai", "anthropic"): + for stream in (False, True): + with self.subTest(api=api, stream=stream), mock.patch.object(self.engine, "generate", side_effect=EngineDied("stopped")): + self.chat(api, stream=stream) + record = self.latest() + self.assertEqual(record["state"], "error") + self.assertIn("stopped", record["error"]["message"]) + self.assertEqual(record["output"], "") + self.assertNotIn("timings", record) + + def test_history_is_authorized_and_does_not_capture_headers(self): + self.svc.api_key = "secret" + auth = {"Authorization": "Bearer secret"} + self.assertEqual(self.request("/api/requests")[0], 401) + self.assertEqual(self.request("/api/requests?id=missing")[0], 401) + self.assertEqual(len(self.svc.api_requests), 0) + self.assertEqual(self.request("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}]}, auth)[0], 200) + summary = self.request("/api/requests", headers=auth)[1]["requests"][0] + self.assertNotIn("input", summary) + self.assertNotIn("output", summary) + self.assertEqual(self.request("/api/requests?id=" + summary["id"])[0], 401) + detail = self.request("/api/requests?id=" + summary["id"], headers=auth)[1] + self.assertNotIn("secret", json.dumps(detail)) + + def test_capture_is_bounded_and_eviction_returns_404(self): + huge = "x" * 262200 + first = self.svc.begin_request("/v1/chat/completions", {"messages": [{"content": huge}]}) + self.assertEqual(len(first["input"]), 262144) + self.assertTrue(first["input_truncated"]) + for _ in range(100): + self.svc.begin_request("/v1/chat/completions", {"messages": []}) + self.assertEqual(len(self.request("/api/requests")[1]["requests"]), 100) + self.assertEqual(self.request("/api/requests?id=" + first["id"])[0], 404) + # Exercise output capture without making a mock engine emit 262K tokens. + handler = object.__new__(self.httpd.RequestHandlerClass) + handler.record = self.svc.api_requests[-1] + chunk = {"choices": [{"delta": {"content": huge, "reasoning_content": huge}}]} + list(handler._capture((item for item in [chunk]), "openai")) + for field in ("output", "reasoning"): + self.assertEqual(len(handler.record[field]), 262144) + self.assertTrue(handler.record[field + "_truncated"]) + + def test_queue_wait_and_loading_are_attributed_separately(self): + self.engine.unload() + entered, release = threading.Event(), threading.Event() + original = self.engine.restart + def restart(): + entered.set() + self.assertTrue(release.wait(5)) + original() + with mock.patch.object(self.engine, "restart", side_effect=restart), ThreadPoolExecutor(max_workers=2) as pool: + first = pool.submit(self.chat) + self.assertTrue(entered.wait(5)) + second = pool.submit(self.chat) + deadline = time.monotonic() + 5 + while len(self.svc.api_requests) < 2 and time.monotonic() < deadline: + time.sleep(0.01) + self.assertEqual(len(self.svc.api_requests), 2) + history = self.request("/api/requests")[1] + self.assertEqual({r["state"] for r in history["requests"]}, {"queued", "loading"}) + self.assertFalse(history["loaded"]) + self.assertTrue(history["auto_load"]) + time.sleep(0.03) + release.set() + self.assertEqual(first.result()[0], 200) + self.assertEqual(second.result()[0], 200) + records = list(self.svc.api_requests) + self.assertGreater(records[0]["load_s"], 0.02) + self.assertGreater(records[1]["queue_s"], 0.02) + self.assertLess(records[1]["load_s"], records[0]["load_s"]) + self.assertTrue(all(r["state"] == "completed" for r in records)) + + def test_page_and_relative_assets_are_served(self): + code, html = self.request("/api-monitor") + self.assertEqual(code, 200) + self.assertIn('src="/web/monitor.js"', html) + code, script = self.request("/web/monitor.js") + self.assertEqual(code, 200) + self.assertIn("textContent", script) + self.assertNotIn("innerHTML", script) + self.assertEqual(self.request("/web/../server.py")[0], 404) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_server.py b/serve/test_server.py index 7bcdd73a..90781f7a 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -66,6 +66,36 @@ class MaxTokens(unittest.TestCase): u = b.get("usage", {}) return s, b, u.get("input_tokens"), u.get("output_tokens") + def test_anthropic_thinks_only_when_asked(self): + # #278: Anthropic's thinking is opt-in; "thinking", an effort or a reasoning_budget_tokens (#123) asks for it + from serve.frontend import anthropic_to_messages + msgs = [{"role": "user", "content": "u"}] + kw = lambda **r: anthropic_to_messages({"messages": msgs, **r}, think_unasked=False)[2] # noqa: E731 + # the default ("anthropic_thinking": "model") renders an unasked request as 0.1.31 did + self.assertNotIn("enable_thinking", anthropic_to_messages({"messages": msgs})[2]) + self.assertEqual(kw(), {"enable_thinking": False}) + self.assertEqual(kw(thinking={"type": "disabled"}), {"enable_thinking": False}) + self.assertNotIn("enable_thinking", kw(thinking={"type": "enabled", "budget_tokens": 2048})) + self.assertNotIn("enable_thinking", kw(output_config={"effort": "high"})) + self.assertNotIn("enable_thinking", kw(reasoning_budget_tokens=30)) + + def test_count_tokens_is_the_prompt_messages_reads(self): + # /v1/messages/count_tokens renders and tokenizes the same prompt /v1/messages would read, without running it + msgs = [{"role": "user", "content": "how many tokens is this?"}] + s, b = self.post("/v1/messages/count_tokens", {"model": "m", "messages": msgs}) + self.assertEqual(s, 200) + s2, _, n_in, _ = self.call("anthropic", "how many tokens is this?", max_tokens=8) + self.assertEqual(s2, 200) + self.assertEqual(b["input_tokens"], n_in) + + def test_request_line_parses_the_engine_summary(self): + line = ("strata serve: prompt 1200 tokens = 1000 reused + 200 read in 50 ms (4000.0 tok/s), 30 generated in " + "300 ms (100.0 tok/s), drafts accepted 20 of 28, 2 checkpoints") + from serve.server import ENGINE_REQUEST + m = ENGINE_REQUEST.search(line) + self.assertIsNotNone(m) + self.assertEqual((m["prompt"], m["reused"], m["gen"], m["tg"]), ("1200", "1000", "30", "100.0")) + def test_unset_budget_is_the_rest_of_the_context(self): cases = {"openai": [{"max_tokens": -1}, {"max_tokens": 0}, {}, {"max_tokens": None}, {"max_completion_tokens": -1}, {"max_completion_tokens": None, "max_tokens": None}], @@ -784,6 +814,29 @@ class SharedSettings(unittest.TestCase): finally: self.svc.api_key = "" + def test_proxy_headers_do_not_make_a_page_strata_s_own(self): + # #321: X-Forwarded-*, CF-Ray or CF-Connecting-IP say nothing about the page that sent the request - any web + # page behind any proxy would otherwise change the settings (or run MCP tools) + for extra in ({"X-Forwarded-Host": "proxy.example.com"}, {"CF-Ray": "1234567890"}, + {"X-Forwarded-For": "203.0.113.9"}, {"CF-Connecting-IP": "203.0.113.9"}): + code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, + {"Origin": "https://proxy.example.com", **extra}) + self.assertEqual(code, 403, extra) + # another port on the same host is another site (a local dev server's page) + code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, {"Origin": "http://127.0.0.1:1"}) + self.assertEqual(code, 403) + + def test_a_trusted_origin_is_strata_s_own_page(self): + # the web app behind a reverse proxy or tunnel: the config's trusted_origins + self.svc.trusted_origins = ["https://strata.example.com"] + try: + code, _ = self.req("/settings", {"defaults": {}}, {"Origin": "https://strata.example.com"}) + self.assertEqual(code, 200) + code, _ = self.req("/settings", {"defaults": {}}, {"Origin": "https://evil.example.com"}) + self.assertEqual(code, 403) + finally: + self.svc.trusted_origins = [] + class WebApp(unittest.TestCase): """The web app (PR #22's dashboard idea, rebuilt): its page and files, and GET /metrics.""" @@ -977,6 +1030,58 @@ class UsageAndStatus(unittest.TestCase): return [json.loads(line[6:]) for line in raw.decode().splitlines() if line.startswith("data: {")] + def preflight(self, path, origin="https://chat.example.com"): + req = urllib.request.Request(self.base + path, method="OPTIONS", + headers={"Origin": origin, "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "authorization, content-type"}) + with urllib.request.urlopen(req, timeout=10) as r: + return r.status, r.headers + + def test_cors_is_off_by_default(self): + # #321: OPTIONS is answered, but without cors_origins no page of another origin is let in + status, h = self.preflight("/v1/chat/completions") + self.assertEqual(status, 204) + self.assertIsNone(h.get("Access-Control-Allow-Origin")) + with urllib.request.urlopen(self.base + "/health", timeout=10) as r: + self.assertIsNone(r.headers.get("Access-Control-Allow-Origin")) + + def test_cors_for_the_configured_origins_on_the_api_only(self): + self.svc.cors_origins = ["https://chat.example.com"] + try: + status, h = self.preflight("/v1/chat/completions") + self.assertEqual((status, h.get("Access-Control-Allow-Origin")), (204, "https://chat.example.com")) + self.assertIn("OPTIONS", h.get("Access-Control-Allow-Methods", "")) + self.assertIn("authorization", h.get("Access-Control-Allow-Headers", "")) + self.assertIsNone(self.preflight("/v1/chat/completions", "https://evil.example.com")[1] + .get("Access-Control-Allow-Origin")) + # never on the app's own endpoints (/settings, /unload, ...) + self.assertIsNone(self.preflight("/settings")[1].get("Access-Control-Allow-Origin")) + req = urllib.request.Request(self.base + "/v1/models", headers={"Origin": "https://chat.example.com"}) + with urllib.request.urlopen(req, timeout=10) as r: + self.assertEqual(r.headers.get("Access-Control-Allow-Origin"), "https://chat.example.com") + self.svc.cors_origins = ["*"] + self.assertEqual(self.preflight("/v1/messages", "https://any.example.com")[1] + .get("Access-Control-Allow-Origin"), "*") + finally: + self.svc.cors_origins = [] + + def test_sse_is_not_buffered_by_proxies(self): + req = urllib.request.Request(self.base + "/v1/chat/completions", headers={"Content-Type": "application/json"}, + data=json.dumps({"model": "m", "stream": True, + "messages": [{"role": "user", "content": "hi"}]}).encode()) + with urllib.request.urlopen(req, timeout=30) as r: + self.assertEqual(r.headers.get("X-Accel-Buffering"), "no") + r.read() + + def test_origin_lists_are_checked(self): + from serve.server import origins_of + self.assertEqual(origins_of(None, "k", True), []) + self.assertEqual(origins_of("https://a.example.com/", "k", False), ["https://a.example.com"]) + self.assertEqual(origins_of(["*", "http://localhost:3000"], "k", True), ["*", "http://localhost:3000"]) + for bad in ("*", "a.example.com", "https://a.example.com/path", "https://*.example.com", 5): + with self.assertRaises(SystemExit): + origins_of(bad, "k", False) + def test_openai(self): b = self.chat("/v1/chat/completions") u, t = b["usage"], b["timings"] diff --git a/serve/test_structured.py b/serve/test_structured.py new file mode 100644 index 00000000..cc157a76 --- /dev/null +++ b/serve/test_structured.py @@ -0,0 +1,167 @@ +"""Exercise the JSON contract through HTTP, including H3's strict Story shape.""" +import json +import unittest +import urllib.error +import urllib.request +from pathlib import Path +from unittest import mock + +from serve.frontend import ChatTemplate +from serve import structured +from serve.server import ByteTokenizer, MockEngine, Service, serve + +try: + import jsonschema # noqa: F401 + HAVE_JSONSCHEMA = True +except ImportError: # optional: json_schema answers are then only checked to be one object + HAVE_JSONSCHEMA = False + + +STORY = {"title": "Photobooth", "sheet": "A single continuous shot.", "cast": [], + "boxes": [{"box": 1, "duration_ms": 15000, "new_shot": True, "beat": "Hailee changes poses.", + "on_screen": ["Hailee"], "references": [], "ends": "She smiles."}], "suggestions": []} + + +def object_schema(properties): + return {"type": "object", "properties": properties, "required": list(properties), "additionalProperties": False} + + +TEXT = {"type": "string"} +STORY_SCHEMA = object_schema({ + "title": TEXT, "sheet": TEXT, "cast": {"type": "array", "items": object_schema({"name": TEXT, + "references": {"type": "array", "items": TEXT, "maxItems": 0}})}, + "boxes": {"type": "array", "minItems": 1, "maxItems": 1, "items": object_schema({ + "box": {"type": "integer", "minimum": 1, "maximum": 1}, + "duration_ms": {"type": "integer", "minimum": 1, "maximum": 15000}, "new_shot": {"type": "boolean"}, + "beat": TEXT, "on_screen": {"type": "array", "items": TEXT}, + "references": {"type": "array", "items": TEXT, "maxItems": 0}, "ends": TEXT})}, + "suggestions": {"type": "array", "items": object_schema({"what": TEXT, "why": TEXT, + "boxes": {"type": "array", "items": {"type": "integer"}}, "description": TEXT})}}) +FORMAT = {"type": "json_schema", "json_schema": {"name": "h3_story", "strict": True, "schema": STORY_SCHEMA}} + + +class Structured(unittest.TestCase): + def request(self, path, body=None, headers=None): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None, + headers={"Content-Type": "application/json", **(headers or {})}) + try: + response = urllib.request.urlopen(req, timeout=10) + except urllib.error.HTTPError as error: + response = error + with response: + data = response.read().decode() + return response.status, data if "event-stream" in response.headers.get("Content-Type", "") else json.loads(data) + + def setUp(self): + self.tok = ByteTokenizer() + self.engine = MockEngine(self.tok, json.dumps(STORY), max_context=16384) + self.svc = Service(self.engine, self.tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def chat(self, script=None, **kwargs): + if script is not None: + self.engine = self.svc.engine = MockEngine(self.tok, script, max_context=16384) + req = {"messages": [{"role": "system", "content": "Write a film plan."}, + {"role": "user", "content": "Photobooth. 15 seconds."}], + "response_format": FORMAT, "reasoning_effort": "none", **kwargs} + return self.request("/v1/chat/completions", req) + + def test_h3_schema_success_and_stream_with_reasoning(self): + code, reply = self.chat() + self.assertEqual(code, 200) + self.assertEqual(json.loads(reply["choices"][0]["message"]["content"]), STORY) + prompt = self.tok.decode(self.engine.last_prompt) + self.assertIn("OUTPUT FORMAT REQUIREMENT", prompt) + self.assertIn('"duration_ms"', prompt) + code, raw = self.chat("Consider the shot.\n" + json.dumps(STORY), stream=True, reasoning_effort="low") + self.assertEqual(code, 200) + chunks = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")] + content = "".join(c["choices"][0]["delta"].get("content", "") for c in chunks) + self.assertEqual(json.loads(content), STORY) + self.assertIn("reasoning_content", raw) + self.assertIn("data: [DONE]", raw) + + @unittest.skipUnless(HAVE_JSONSCHEMA, "jsonschema is not installed") + def test_invalid_generation_is_an_error_and_never_streams_content(self): + for script in ("## Film Plan - Photobooth", '{"title":"Only a title"}', + json.dumps({**STORY, "extra": True}), + json.dumps({**STORY, "boxes": [{**STORY["boxes"][0], "duration_ms": "15000"}]})): + with self.subTest(script=script): + code, reply = self.chat(script) + self.assertEqual(code, 502) + self.assertEqual(reply["error"]["code"], "structured_output_failed") + _, raw = self.chat(script, stream=True) + self.assertIn('"structured_output_failed"', raw) + self.assertNotIn('"delta"', raw) + self.assertIn("data: [DONE]", raw) + + def test_object_mode_strict_json_and_truncation(self): + fmt = {"type": "json_object"} + self.assertEqual(self.chat('{"answer":4}', response_format=fmt)[0], 200) + for script in ('[]', '{"x":NaN}', '{"x":1,"x":2}', '{"x":1e999}', '```json\n{}\n```'): + self.assertEqual(self.chat(script, response_format=fmt)[0], 502) + self.assertEqual(self.chat('{"answer":4}', response_format=fmt, max_tokens=5)[0], 502) + # Plain text callers retain normal streaming, without a JSON validation gate. + self.assertEqual(self.chat("Prose.", response_format={"type": "text"})[0], 200) + + def test_rejected_schema_does_not_load_the_engine_or_retry(self): + with mock.patch.object(self.svc, "load") as load: + code, _ = self.chat(response_format={"type": "json_schema"}) + self.assertEqual(code, 400) + load.assert_not_called() + self.engine = self.svc.engine = MockEngine(self.tok, "Markdown is not JSON", max_context=16384) + with mock.patch.object(self.engine, "generate", wraps=self.engine.generate) as generate: + self.assertEqual(self.chat()[0], 502) + self.assertEqual(generate.call_count, 1) + + @unittest.skipUnless(HAVE_JSONSCHEMA, "jsonschema is not installed") + def test_invalid_schema_is_400_and_local_refs_work(self): + for schema in ({"type": "object", "properties": {"x": {"type": "invalid"}}}, + {"type": "object", "$ref": "https://other.example/schema"}): + fmt = {"type": "json_schema", "json_schema": {"name": "test", "strict": True, "schema": schema}} + self.assertEqual(self.chat(response_format=fmt)[0], 400) + schema = object_schema({"answer": {"$ref": "#/$defs/n"}}) + schema["$defs"] = {"n": {"type": "integer"}} + fmt = {"type": "json_schema", "json_schema": {"name": "local", "schema": schema}} + self.assertEqual(self.chat('{"answer":4}', response_format=fmt)[0], 200) + + def test_malformed_formats_and_tools_are_rejected_before_loading(self): + formats = ([], {"type": "unsupported"}, + {"type": "json_schema", "json_schema": {"schema": {"type": "object"}}}, + {"type": "json_schema", "json_schema": {"name": "x", "strict": "true", "schema": {"type": "object"}}}) + with mock.patch.object(self.svc, "load") as load: + for fmt in formats: + with self.subTest(fmt=fmt): + self.assertEqual(self.chat(response_format=fmt)[0], 400) + self.assertEqual(self.chat(tools=[{"type": "function", "function": {"name": "search", "parameters": {"type": "object"}}}])[0], 400) + self.assertEqual(self.chat(strata_mcp=True)[0], 400) + self.assertEqual(self.request("/v1/chat/completions", [])[0], 400) + load.assert_not_called() + + def test_without_jsonschema_an_object_is_still_required(self): + # jsonschema is optional: without it json_schema answers are checked to be one JSON object, json_object + # never needs it, and nothing is imported at server start + with mock.patch.object(structured, "_jsonschema", False): + self.assertEqual(self.chat()[0], 200) + for script in ("## Film Plan - Photobooth", "[1, 2]"): + code, reply = self.chat(script) + self.assertEqual(code, 502, script) + self.assertEqual(reply["error"]["code"], "structured_output_failed") + self.assertEqual(self.chat('{"answer":4}', response_format={"type": "json_object"})[0], 200) + + def test_the_server_does_not_import_jsonschema_at_start(self): + import subprocess + import sys + code = ("import sys; import serve.server; " + "sys.exit(1 if any(m == 'jsonschema' or m.startswith('jsonschema.') for m in sys.modules) else 0)") + r = subprocess.run([sys.executable, "-c", code], cwd=str(Path(__file__).resolve().parents[1])) + self.assertEqual(r.returncode, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/web/monitor.html b/serve/web/monitor.html new file mode 100644 index 00000000..b05b29f8 --- /dev/null +++ b/serve/web/monitor.html @@ -0,0 +1,37 @@ + + + + +Strata API Monitor + + + + + +
Strata Local inference
+
+

API Monitor

Model status and every request, in one place.

+ + +
+
Model
Connecting…
127.0.0.1:5001/v1
+
Requests retained
—
Waiting for server
+
Last wall-clock
—
Includes queue and model loading
+
Last decode speed
—
Engine timing · tokens / second
+
+

Requests

+
+
Inspect a requestSelect a request to see its input, output, and timings.
+ +
+
Last 100 requests kept in memory until restart. Inputs and outputs stay on this machine.Connecting…
+
+ diff --git a/serve/web/monitor.js b/serve/web/monitor.js new file mode 100644 index 00000000..5543b94b --- /dev/null +++ b/serve/web/monitor.js @@ -0,0 +1,111 @@ +"use strict"; +const $ = id => document.getElementById(id); +let selected = null, detail = null, pane = "input", records = [], state = null, operating = false, stamp = "", actionError = ""; +let apiKey = sessionStorage.getItem("strata.monitor.key") || ""; +document.documentElement.dataset.theme = localStorage.getItem("strata.theme") || "dark"; +const seconds = n => typeof n === "number" ? `${n.toFixed(2)} s` : "—"; +const speed = n => typeof n === "number" ? n.toFixed(1) : "—"; +const active = r => !["completed", "error", "disconnected"].includes(r.state); +function text(id, value) { const el = $(id); if (el.textContent !== String(value)) el.textContent = value; } +async function api(path, body) { + const response = await fetch(path, {cache:"no-store", headers:{...(apiKey ? {Authorization:`Bearer ${apiKey}`} : {}), ...(body !== undefined ? {"Content-Type":"application/json"} : {})}, ...(body !== undefined ? {method:"POST", body:JSON.stringify(body)} : {})}); + const value = await response.json(); + if (!response.ok) { + if (response.status === 401) $("auth").hidden = false; + throw new Error(value.error?.message || `HTTP ${response.status}`); + } + return value; +} +function notice(message) { $("error").hidden = !message; text("error", message || ""); } +function list() { + const query = $("search").value.toLowerCase(), filter = $("filter").value; + const visible = records.filter(r => `${r.id} ${r.path} ${r.model}`.toLowerCase().includes(query) && (filter === "all" || (filter === "active" ? active(r) : r.state === filter))); + const nextStamp = JSON.stringify([visible, selected]); + if (stamp === nextStamp) return; + stamp = nextStamp; + const focusId = document.activeElement?.dataset.request; + $("requests").replaceChildren(); + if (!visible.length) { + const empty = document.createElement("div"); empty.className = "empty"; + empty.textContent = records.length ? "No matching requests." : "No requests yet. API calls will appear here automatically."; + $("requests").append(empty); + } + for (const r of visible) { + const button = document.createElement("button"); button.className = `request${selected === r.id ? " selected" : ""}`; + button.dataset.request = r.id; button.setAttribute("aria-label", `Request ${r.id}`); button.setAttribute("aria-pressed", String(selected === r.id)); + const row = document.createElement("div"); row.className = "row"; + const time = document.createElement("span"); time.textContent = new Date(r.started_at * 1000).toLocaleTimeString(); + const tag = document.createElement("span"); tag.className = `tag ${r.state}`; tag.textContent = r.state; + row.append(time, tag); + const endpoint = document.createElement("div"); endpoint.className = "endpoint"; endpoint.textContent = `POST ${r.path}`; + const meta = document.createElement("div"); meta.className = "small"; + meta.textContent = `${r.id} · ${seconds(r.wallclock_s)} · ${r.stream ? "stream" : "JSON response"}${r.http_status ? ` · HTTP ${r.http_status}` : ""}`; + button.append(row, endpoint, meta); + button.onclick = async () => { selected = r.id; detail = null; list(); await showDetail(); }; + $("requests").append(button); + if (focusId === r.id) button.focus({preventScroll:true}); + } +} +function content() { + if (!detail) return; + let value = detail[pane] || (pane === "response" && detail.stream ? "Streaming response: see Output and the request error, if any." : "No content."); + if (pane === "output") { try { value = JSON.stringify(JSON.parse(value), null, 2); } catch (_) {} } + text("content", value); + const note = pane === "output" && detail.error ? "Raw model output retained for diagnosis. The API returned an error." : pane === "input" ? "Original request body." : pane === "output" ? "Model answer. JSON is formatted here for readability." : pane === "reasoning" ? "Separate reasoning content, when enabled." : "API response body."; + text("content-note", note + (detail[`${pane}_truncated`] ? " Monitor capture truncated at 256K characters; the API response was not shortened." : "")); +} +async function showDetail() { + if (!selected) return; + const id = selected; + const value = await api(`/api/requests?id=${encodeURIComponent(id)}`); + if (selected !== id) return; + detail = value; $("selection").hidden = false; $("no-selection").hidden = true; + text("detail-title", `${value.id} · ${value.path}`); + text("detail-status", value.state); $("detail-status").className = `tag ${value.state}`; + text("detail-time", new Date(value.started_at * 1000).toLocaleString()); + text("detail-wall", seconds(value.wallclock_s ?? ((Date.now() / 1000) - value.started_at))); + text("detail-load", seconds(value.load_s)); text("detail-queue", seconds(value.queue_s)); text("detail-first", seconds(value.first_token_s)); + text("detail-prompt", value.usage?.prompt_tokens ?? value.usage?.input_tokens ?? "—"); + text("detail-tokens", value.usage?.completion_tokens ?? value.usage?.output_tokens ?? "—"); + text("detail-speed", speed(value.timings?.predicted_per_second)); text("detail-format", value.response_format || "text"); + $("detail-error").hidden = !value.error; text("detail-error", value.error?.message || ""); content(); +} +async function refresh() { + try { + const [status, history] = await Promise.all([api("/v1/status"), api("/api/requests")]); + state = status; records = history.requests; + status.loaded = history.loaded; status.auto_load = history.auto_load; + if (selected && !records.some(r => r.id === selected)) { + selected = detail = null; $("selection").hidden = true; $("no-selection").hidden = false; + } + const inflight = Math.max(status.activity.in_flight, records.filter(active).length); + const loading = records.some(r => r.state === "loading"); + text("loaded", loading ? "Loading…" : inflight ? "In use" : status.loaded ? "Loaded" : "Unloaded"); + $("model-state").className = `value ${inflight || loading ? "busy" : status.loaded ? "loaded" : ""}`; + text("model", status.model); text("count", records.length); + text("active", inflight ? `${inflight} active / queued` : status.auto_load ? "Loads automatically on the next request" : "No active requests"); + const last = records.find(r => !active(r)); + text("wall", last ? seconds(last.wallclock_s) : "—"); text("speed", speed(last?.timings?.predicted_per_second)); + $("load").disabled = operating || Boolean(inflight) || status.loaded; $("unload").disabled = operating || Boolean(inflight) || !status.loaded; + list(); if (selected) await showDetail(); + text("updated", `Live · updated ${new Date().toLocaleTimeString()}`); + if (!operating) notice(actionError); + } catch (error) { notice(error.message); text("updated", "Disconnected · retrying"); $("load").disabled = $("unload").disabled = true; } +} +async function control(load) { + actionError = ""; + operating = true; $("load").disabled = $("unload").disabled = true; + text("loaded", load ? "Loading…" : "Unloading…"); + try { await api(load ? "/load" : "/unload", {}); notice(""); } + catch (error) { actionError = error.message; notice(actionError); } + finally { operating = false; await refresh(); } +} +$("load").onclick = () => control(true); $("unload").onclick = () => control(false); +$("key").onclick = () => { $("auth").hidden = !$("auth").hidden; if (!$("auth").hidden) $("api-key").focus(); }; +$("auth").onsubmit = async event => { event.preventDefault(); apiKey = $("api-key").value.trim(); sessionStorage.setItem("strata.monitor.key", apiKey); $("auth").hidden = true; await refresh(); }; +$("theme").onclick = () => { const theme = document.documentElement.dataset.theme === "dark" ? "light" : "dark"; document.documentElement.dataset.theme = theme; localStorage.setItem("strata.theme", theme); }; +$("search").oninput = list; $("filter").onchange = list; +document.querySelectorAll("[data-pane]").forEach(button => { button.onclick = () => { pane = button.dataset.pane; document.querySelectorAll("[data-pane]").forEach(b => b.setAttribute("aria-selected", String(b === button))); content(); }; }); +$("copy").onclick = async () => { try { await navigator.clipboard.writeText($("content").textContent); text("copy", "Copied"); setTimeout(() => text("copy", "Copy"), 1500); } catch (_) { notice("Clipboard unavailable; select the text to copy it."); } }; +async function poll() { await refresh(); setTimeout(poll, 2000); } +poll(); diff --git a/setup.py b/setup.py index 77ffe77a..c2d63ed4 100644 --- a/setup.py +++ b/setup.py @@ -1978,7 +1978,17 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ OLD_DRAFT_VOCABS = {"369151522226a5edaa5f12cfd1e2ae7db8f4fbdbd222f3dcf327dced9597fb25"} # to 0.1.26: 27 Han tokens -DRAFT_VOCABS = {"cjk": "draft_vocab.bin", "en": "draft_vocab_en.bin"} +DRAFT_VOCABS = {"cjk": "draft_vocab.bin", "en": "draft_vocab_en.bin", "cyrillic": "draft_vocab_cyrillic.bin"} + + +def saved_draft_vocab(cfg_path: Path) -> str | None: + """The draft subset a model's config chose earlier (--draft-vocab), or None: a setup run again without the flag + rewrites the config, and would otherwise put the default subset back.""" + try: + v = json.loads(cfg_path.read_text(encoding="utf-8-sig")).get("draft_vocab") + except (OSError, ValueError, AttributeError): + return None + return v if v in DRAFT_VOCABS else None def mtp_corrupt(mtp: Path, env=None) -> bool: @@ -1993,8 +2003,10 @@ def mtp_corrupt(mtp: Path, env=None) -> bool: def refresh_draft_vocab(rt: Path, choice: str = "cjk") -> None: - """The draft layer's token subset in the MTP folder: `cjk` (data/draft_vocab.bin, since 0.1.27, #137) or `en` - (data/draft_vocab_en.bin, the English/code subset before it: ~110 MiB less VRAM, English answers 1-2% faster). + """The draft layer's token subset in the MTP folder: `cjk` (data/draft_vocab.bin, since 0.1.27, #137), `en` + (data/draft_vocab_en.bin, the English/code subset before it: ~110 MiB less VRAM, English answers 1-2% faster) or + `cyrillic` (data/draft_vocab_cyrillic.bin: English/code and the whole Cyrillic script, for Ukrainian, Russian, + Bulgarian, Serbian... answers). Copied when missing or when a shipped subset other than the chosen one is there; a subset made by hand is kept.""" new, dst = ROOT / "data" / DRAFT_VOCABS.get(choice, "draft_vocab.bin"), rt / "draft_vocab.bin" if not new.exists() or not rt.is_dir(): @@ -2005,8 +2017,9 @@ def refresh_draft_vocab(rt: Path, choice: str = "cjk") -> None: for f in DRAFT_VOCABS.values() if (ROOT / "data" / f).exists()} if old not in shipped or old == hashlib.sha256(new.read_bytes()).hexdigest(): return - ok("draft layer: the token subset " + ("with Chinese, Japanese and Korean" if choice == "cjk" else - "for English and code (less VRAM)")) + ok("draft layer: the token subset " + {"cjk": "with Chinese, Japanese and Korean", + "cyrillic": "with the Cyrillic script"}.get(choice, + "for English and code (less VRAM)")) shutil.copyfile(new, dst) @@ -2132,7 +2145,8 @@ def main() -> int: help="tune the engine's settings for this PC (about 5-10 minutes), then start the model") ap.add_argument("--draft-vocab", choices=list(DRAFT_VOCABS), help="the draft layer's tokens: cjk = with Chinese, Japanese and Korean (default), en = English " - "and code only (~110 MiB less VRAM, English answers 1-2%% faster)") + "and code only (~110 MiB less VRAM, English answers 1-2%% faster), cyrillic = English, code " + "and the Cyrillic script (Ukrainian, Russian... answers decode ~30%% faster)") ap.add_argument("--low-ram", choices=["auto", "on", "off", "resident", "mmap"], default="auto", help="read the model's experts from one file in its folder instead of copying them all into RAM " "(for a PC with a big GPU and little RAM); auto: when the experts would not fit the RAM. In " @@ -2607,7 +2621,9 @@ def main() -> int: "--out", str(mtp / "mtp-q2_0.gguf")], env=env) run([sys.executable, str(ROOT / "tools" / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(rt)], env=env) - refresh_draft_vocab(rt, a.draft_vocab or "cjk") + # a setup run again without --draft-vocab keeps the subset this model's config chose before (cyrillic, en) + draft_vocab = a.draft_vocab or saved_draft_vocab(ROOT / f"strata-{tag.lower()}.json") + refresh_draft_vocab(rt, draft_vocab or "cjk") ok(f"MTP draft layer: {rt}") # ---- 7. the start script @@ -2682,8 +2698,8 @@ def main() -> int: cfg["host"] = a.host if a.api_key: cfg["api_key"] = a.api_key - if a.draft_vocab: - cfg["draft_vocab"] = a.draft_vocab + if draft_vocab: + cfg["draft_vocab"] = draft_vocab if vision != "none": cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(shards[0]), "gpu": vision == "gpu", "max_tokens": VISION[vision]["max_tokens"]} diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp index f7bc0988..759daa65 100644 --- a/src/core/conversation_snapshot.cpp +++ b/src/core/conversation_snapshot.cpp @@ -43,8 +43,12 @@ bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index // Include the moving spare row, not only completed blocks. The checkpoint // restore reconstructs that row when rewinding to an earlier prefix. const int64_t pooled = index && upto > 0 ? upto / s.idx_block + 1 : 0; - // Format 3 identifies snapshot K8V4 only; never pass it to the block movers. - l = {st.kv_hybrid ? 3 : qsa_kv_format(st), cells, pooled, s.page_size, 0, 0, 0, 0, 0}; + // Format 3 identifies snapshot K8V4 only; never pass it to the block movers. Rotated INT8 K/V (#293, + // STRATA_KV_ROT=1) is another format too (+16): its bytes mean nothing to a state that does not rotate, so a + // snapshot or prompt checkpoint taken with the rotation never restores into one without it, nor the reverse. + // (Q4_0 is always rotated: nothing to tell apart; without the rotation the format is the one it always was.) + const int rotated = st.kv_rot && !st.kv_q4 && !st.kv_hybrid ? 16 : 0; + l = {(st.kv_hybrid ? 3 : qsa_kv_format(st)) + rotated, cells, pooled, s.page_size, 0, 0, 0, 0, 0}; using conversation_detail::product; if (!product(l.data, {(uint64_t) cells, (uint64_t) g.n_head_kv, per}) || !product(l.scales, {(uint64_t) cells, (uint64_t) g.n_head_kv, diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp index bf732f3f..da95113c 100644 --- a/src/core/conversation_snapshot_test.cpp +++ b/src/core/conversation_snapshot_test.cpp @@ -259,6 +259,17 @@ int main() { } auto bad=a; bad.head_dim++; check(!conversation_kv_restore(bad,f.state,f.g,upto,index,err),"reject incompatible geometry"); + if (fmt==kKvInt8) { + // #293: INT8 K/V saved through the Hadamard rotation (STRATA_KV_ROT=1) never restores into a state + // without it, nor the reverse + f.state.kv_rot=true; + ConversationKv rotated; + check(conversation_kv_save(rotated,f.state,f.g,upto,index,err),"save rotated INT8"); + check(!conversation_kv_restore(a,f.state,f.g,upto,index,err),"unrotated image into a rotated state rejected"); + f.state.kv_rot=false; + check(!conversation_kv_restore(rotated,f.state,f.g,upto,index,err),"rotated image into an unrotated state rejected"); + check(conversation_kv_restore(a,f.state,f.g,upto,index,err),"unrotated image still restores"); + } if (!a.k.empty()) { bad=a; bad.k.pop_back(); check(!conversation_kv_restore(bad,f.state,f.g,upto,index,err),"reject malformed payload"); diff --git a/src/core/device.cu b/src/core/device.cu index 010aee0f..814635a6 100644 --- a/src/core/device.cu +++ b/src/core/device.cu @@ -92,6 +92,19 @@ std::string gpu_arch_problem(int ordinal) { #endif } +std::string device_code_error() { +#if defined(STRATA_USE_HIP) + return ""; // gpu_arch_problem() checks the HIP architectures against STRATA_HIP_ARCHS, before this point +#else + // every .cu of the engine is compiled for the same CMAKE_CUDA_ARCHITECTURES, so this kernel stands for all + cudaFuncAttributes a{}; + const cudaError_t e = cudaFuncGetAttributes(&a, poison_kernel); + if (e == cudaSuccess) return {}; + cudaGetLastError(); + return cudaGetErrorString(e); +#endif +} + DeviceInfo device_info(int ordinal) { int count = 0; check(cudaGetDeviceCount(&count), "cudaGetDeviceCount"); diff --git a/src/core/layer.cpp b/src/core/layer.cpp index 8ad9f41a..ff7fc17b 100644 --- a/src/core/layer.cpp +++ b/src/core/layer.cpp @@ -22,6 +22,7 @@ #include "strata/kernels/native_router.hpp" #include "strata/kernels/native_qsa.hpp" #include "strata/kernels/native_qsa_indexer.hpp" +#include "strata/kernels/mrope.hpp" #include "strata/kernels/native_rope.hpp" #include "strata/kernels/native_flash_attn.hpp" #include "strata/kernels/fused_gr.hpp" @@ -172,8 +173,9 @@ if (!w.wants_q8k()) { s_gemv_q8_0_split(x80, p.codes, p.scales, p.offset, // namespace void layer_set_native_bf16(bool enabled) { native_bf16_projections = enabled; } void layer_set_native_flash_attn_short(bool enabled) { native_flash_attn_short = enabled; } -namespace { bool g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false; } +namespace { bool g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false, g_kv_int8_rot = false; } void qsa_set_kv_int8(bool enabled) { g_kv_int8 = enabled; } +void qsa_set_kv_int8_rotate(bool enabled) { g_kv_int8_rot = enabled; } bool qsa_kv_int8() { return g_kv_int8; } void qsa_set_kv_q4(bool enabled) { g_kv_q4 = enabled; } bool qsa_kv_q4() { return g_kv_q4; } @@ -563,6 +565,7 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q st.kv_int8 = false; st.kv_q4 = false; } + st.kv_rot = st.kv_q4 || (st.kv_int8 && g_kv_int8_rot); // K8V4 rotates only V (below) st.kv_mode = p.mode; st.n_slots = p.slots; const uint64_t rows = (uint64_t) p.slots * s.n_head_kv * s.page_size; // VRAM rows: the slots @@ -662,6 +665,9 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q hc.data(), hs.data()); cudaMemcpy(st.cos_tab, hc.data(), hc.size() * 4, cudaMemcpyHostToDevice); cudaMemcpy(st.sin_tab, hs.data(), hs.size() * 4, cudaMemcpyHostToDevice); + st.owns_rope = true; + if (s.n_rot == 64) // the native and prompt-path rope kernels read it (mrope.hpp, STRATA_ROPE_TABLE=1) + strata::kernels::rope_table_set(st.cos_tab, st.sin_tab, (int) max_cells, strata::kernels::rope_scaling()); } // the page table starts as the IDENTITY, which is the simplest legal mapping and what a caller that does // not page at all wants; a streamed state starts with nothing resident, a ring at `block % n_slots`. @@ -899,11 +905,14 @@ if (st.kv_hybrid) { strata::kernels::fwht256_inplace_cuda(b.vcur, g.n_head_kv, stream); kv_append_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, st.step, b.kcur, b.kcur, s, stream, nullptr); // mode 0: no host mirror strata::kernels::kv_append_q4_step(st.v_q4, st.v_q4, st.page_table, st.step, b.vcur, b.vcur, s, stream, nullptr); -} else if (st.kv_q4) { - strata::kernels::fwht256_inplace_cuda(b.kcur, g.n_head_kv, stream); // Q4_0: rotated K and V (kv_q4.hpp) +} else { +if (st.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1 + strata::kernels::fwht256_inplace_cuda(b.kcur, g.n_head_kv, stream); strata::kernels::fwht256_inplace_cuda(b.vcur, g.n_head_kv, stream); +} +if (st.kv_q4) { strata::kernels::kv_append_q4_step(st.k_q4, st.v_q4, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); -} else if (st.kv_int8) kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); else kv_append_step(st.k_pool, st.v_pool, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); { const uint64_t nvk = (uint64_t) g.n_head_kv * g.head_dim; const uint64_t base = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + 2 * nvk + 8; if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.k_pool, base, nvk / 2, stream); if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.v_pool, base + nvk / 2, nvk / 2, stream); dump_slot(dump, g, layer, b.vcur, base + nvk, nvk, stream); dump_slot(dump, g, layer, b.kcur, base + 2 * nvk, nvk, stream); } { const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; if (native_qsa_indexer_enabled()) { +} else if (st.kv_int8) kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); else kv_append_step(st.k_pool, st.v_pool, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); } /* not K8V4 */ { const uint64_t nvk = (uint64_t) g.n_head_kv * g.head_dim; const uint64_t base = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + 2 * nvk + 8; if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.k_pool, base, nvk / 2, stream); if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.v_pool, base + nvk / 2, nvk / 2, stream); dump_slot(dump, g, layer, b.vcur, base + nvk, nvk, stream); dump_slot(dump, g, layer, b.kcur, base + 2 * nvk, nvk, stream); } { const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; if (native_qsa_indexer_enabled()) { try { native_qsa_indexer_append(b.idx_raw, st.step + kStepPos, pos_base, (const float*) w_ikn->data, RMS_EPS, ib, s, st.max_cells, rope_scaling(), stream); @@ -937,7 +946,7 @@ int64_t max_blocks = (st.max_cells / s.idx_block) + 2; } // KV streaming: every block the selection names is made resident before anything reads it qsa_kv_resolve(st, g, b.ids, st.step, 1, cap, stream); - if (st.kv_q4) strata::kernels::fwht256_inplace_cuda(b.qcur, g.n_head, stream); // = + if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(b.qcur, g.n_head, stream); // = if (g_fast_attn && !native_flash_attn_short && dump == nullptr) { const strata::kernels::QsaAttnPools pools = qsa_attn_pools(st); strata::kernels::qsa_decode_attn_step(b.qcur, pools, b.ids, st.step, cap, s, b.attn_scratch, b.attn, stream); @@ -964,7 +973,7 @@ int64_t max_blocks = (st.max_cells / s.idx_block) + 2; } } else qsa_attend_step(b.qcur, b.k_scratch, b.v_scratch, st.step, cap, s, b.attn, nullptr, stream); } - if (st.kv_q4 || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(b.attn, g.n_head, stream); // the output back: H is self-inverse + if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(b.attn, g.n_head, stream); // the output back: H is self-inverse dump_slot(dump, g, layer, b.attn, (uint64_t) 2 * g.n_embd + 2 * g.hc, (uint64_t) g.n_head * g.head_dim, stream); { const uint64_t vs = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + (uint64_t) 2 * g.n_head_kv * g.head_dim; dump_slot(dump, g, layer, (const float*) b.v_scratch, vs, (uint64_t) g.n_head_kv * g.head_dim / 2, stream); dump_slot(dump, g, layer, (const float*) b.ids, vs + (uint64_t) g.n_head_kv * g.head_dim / 2, 4, stream); dump_slot(dump, g, layer, (const float*) st.step, vs + (uint64_t) g.n_head_kv * g.head_dim / 2 + 4, 4, stream); } // ---- 9. Gate the attention output before its projection. Native CUDA keeps F32 // sigmoid/multiply arithmetic and uses Q8_1 for the native quantized projection. diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index 56678374..17e36556 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -471,12 +471,15 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri native_mmvq(GGML_Q8_0, q8("self_attn.v_proj.weight"), xq_, vcur_, (int) N, (int) (NKV * HD), T, cs); for (int t = 0; t < T; ++t) { norm_rope(kcur_ + t * NKV * HD, f32("self_attn.k_norm.weight"), (int) NKV, (int) HD, pos + t * NH); - if (st_.kv_q4) { // Q4_0 KV (kv_q4.hpp): rotated K and V + if (st_.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1 fwht256_inplace_cuda(kcur_ + t * NKV * HD, NKV, cs); fwht256_inplace_cuda(vcur_ + t * NKV * HD, NKV, cs); + } + // stored in the state's own format (#293 appended rotated INT8 K/V as Q4_0, into pools INT8 never has) + if (st_.kv_q4) kv_append_q4_step(st_.k_q4, st_.v_q4, st_.page_table, step + t * 4, kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st_.host); - } else if (st_.kv_int8) + else if (st_.kv_int8) kv_append_q8_step(st_.k_q, st_.v_q, st_.k_scale, st_.v_scale, st_.page_table, step + t * 4, kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st_.host); else @@ -493,12 +496,12 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri return false; } norm_rope(qc, f32("self_attn.q_norm.weight"), (int) NH, (int) HD, pos + t * NH); - if (st_.kv_q4) fwht256_inplace_cuda(qc, NH, cs); + if (st_.kv_rot) fwht256_inplace_cuda(qc, NH, cs); } const QsaAttnPools pools = qsa_attn_pools(st_); if (window_ > 0) window_ids(const_cast(step), T, (int) window_, ident_, cap_, cs); qsa_decode_attn_batch(qcur_, pools, ident_, step, cap_, s, attn_scratch_, attn_, T, cs); - if (st_.kv_q4) fwht256_inplace_cuda(attn_, (int64_t) T * NH, cs); + if (st_.kv_rot) fwht256_inplace_cuda(attn_, (int64_t) T * NH, cs); for (int t = 0; t < T; ++t) native_qsa_gate_apply(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, attn32_ + t * NH * HD, (int) NH, (int) HD, cs); native_quantize_q8_1(attn32_, xq_, (int) (NH * HD), T, cs); diff --git a/src/core/native_head.cpp b/src/core/native_head.cpp index 5eed99d1..e47dfe14 100644 --- a/src/core/native_head.cpp +++ b/src/core/native_head.cpp @@ -108,13 +108,15 @@ NativeEmbed::~NativeEmbed() { bool NativeEmbed::load(const std::vector& shards, int64_t n_embd, int64_t n_vocab, std::string& err) { try { const strata::GgufModel model(shards); - err = strata::check_architecture(model.meta()); + // --embd-gguf's one-tensor file (tools/embd_bf16_pack.py) says "strata-embd": only its tensor is checked + const strata::MetaValue* arch = model.meta().get("general.architecture"); + err = arch != nullptr && arch->s == "strata-embd" ? std::string() : strata::check_architecture(model.meta()); if (!err.empty()) { err = "native embedding: " + err; return false; } size_t at = 0; const strata::TensorInfo* t = model.find("token_embd.weight", &at); const strata::GgufFile& gguf = model.shard(at); if (!t || t->shape.size() != 2 || t->shape[0] != (uint64_t) n_embd || t->shape[1] != (uint64_t) n_vocab || - !strata::kernels::iq_supported((int) t->type) || n_embd % 256) { + !strata::kernels::embed_type_supported((int) t->type) || n_embd % 256) { err = "native embedding: token_embd.weight is absent, of another shape, or of a type without a GPU " "dequantizer"; return false; diff --git a/src/core/session.cpp b/src/core/session.cpp index 2211e9ba..14c61663 100644 --- a/src/core/session.cpp +++ b/src/core/session.cpp @@ -1,5 +1,6 @@ // src/core/session.cpp - one token through all 48 layers. See the header for why the graphs are per-layer. #include "strata/core/session.hpp" +#include "strata/kernels/mrope.hpp" #include "strata/core/progress.hpp" #include "strata/kernels/qsa.hpp" @@ -127,6 +128,14 @@ uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void return used; } +void session_release(SessionState& s) { + for (int64_t j = 0; s.qsa_states != nullptr && j < s.qsa_alloc; ++j) + if (s.qsa_states[j].owns_rope) { + strata::kernels::rope_table_release(s.qsa_states[j].cos_tab); + s.qsa_states[j].owns_rope = false; + } +} + void session_zero(SessionState& s, const ModelGeometry& g, const float* R_init, void* stream) { cudaStream_t cs = (cudaStream_t) stream; // the residual: `hc` copies of the one vector a caller hands in. A real sequence's first token is the diff --git a/src/core/verify.cpp b/src/core/verify.cpp index a798543c..999f85d8 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -177,6 +177,7 @@ Verifier::~Verifier() { if (commit_exec_) cudaGraphExecDestroy(commit_exec_); if (cs_) cudaStreamDestroy(cs_); if (copy_) { cudaStreamSynchronize(copy_); cudaStreamDestroy(copy_); } + if (commit_done_) cudaEventDestroy(commit_done_); if (arena_) cudaFree(arena_); void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_, h_flagA_, h_plan_, h_flagB_}; @@ -194,6 +195,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& } release_gpu_fn().store(&release_live_verifiers); cudaGetDevice(&device_); // a layer split's stage on another GPU: its streams, graphs and buffers live there + strata::kernels::fused_gr_check(); // once per card: which bitwise-equal hyper-connection read runs there wt_ = &wt; g_ = &g; ss_ = &ss; @@ -346,6 +348,10 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& err = "verify: stream create failed"; return false; } + if (cudaEventCreateWithFlags(&commit_done_, cudaEventDisableTiming) != cudaSuccess) { + err = "verify: event create failed"; + return false; + } // E-6: a layer whose routed experts are all resident is planned on the device (STRATA_VERIFY_DEVICE_PLAN=1: on; // exact, but neutral on RIBPC 1-2 GPUs: off by default) { @@ -567,7 +573,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { native_mmvq(wv->native_type, wv->native_data, xq_, vcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs); if (qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV); else for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH); - if (st.kv_q4) { // Q4_0 KV (kv_q4.hpp): K and V rotated before they are stored + if (st.kv_rot) { // K and V rotated before they are stored (kv_q4.hpp) fwht256_inplace_cuda(kcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); } else if (st.kv_hybrid) { // K8V4: only V is rotated @@ -607,6 +613,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { return false; } norm_rope(qcur_ + tb * NH * HD, wqn, (int) (n * NH), (int) HD, pos_ + tb * NH); + if (st.kv_rot) fwht256_inplace_cuda(qcur_ + tb * NH * HD, (int64_t) n * NH, cs); // = bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wiq->data, qidx_ + tb * IQ * ID, IQ * ID, N, IQ * ID, n, cs); norm_rope(qidx_ + tb * IQ * ID, wiqn, (int) (n * IQ), (int) ID, pos_i + tb * IQ); @@ -619,7 +626,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { return false; } norm_rope(qc, wqn, (int) NH, (int) HD, pos_ + t * NH); - if (st.kv_q4) fwht256_inplace_cuda(qc, NH, cs); // = + if (st.kv_rot) fwht256_inplace_cuda(qc, NH, cs); // = } for (int t = tb; t < te; ++t) { float* qx = qidx_ + t * IQ * ID; @@ -640,7 +647,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { qsa_decode_attn_batch(qcur_ + tb * NH * HD, pools, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, cap_, s, attn_scratch_ + (size_t) tb * attn_scratch_floats_, attn_ + tb * NH * HD, n, cs); stamp(l, 13, grp); - if (st.kv_q4 || st.kv_hybrid) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = H + if (st.kv_rot || st.kv_hybrid) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = H if (qb) native_qsa_gate_apply(attn_ + tb * NH * HD, qfull_ + tb * NH * 2 * HD, attn32_ + tb * NH * HD, (int) (n * NH), (int) HD, cs); else @@ -857,7 +864,7 @@ std::string Verifier::profile_report() { "k/v+norm-rope", "kv+idx append", "q+q-idx", "scores+topk", "kv-resolve", "attention", "gate", "", "out-proj", "hc-read1+router", "shared+quant", "waitA", "VRAM hits", "waitB", "PCIe grp", "waitCPU", "copy+combine", - "(gap)", "head", " hc0 norm", " hc0 down", " hc0 up", "", ""}; + "(gap)", "head", " hc0 norm", " hc0 down", " hc0 up", "", "", ""}; std::string out; char b[80]; double total = 0; @@ -1126,6 +1133,13 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, cudaMemcpy(prof_h_.data(), prof_, prof_h_.size() * 8, cudaMemcpyDeviceToHost); const int64_t L = g.n_layers; auto at = [&](int64_t l, int i) { return prof_h_[(size_t) (l * kProfPer + i)]; }; + // D8: the derived columns below read stamps the hc-read kernels write themselves or the next + // layer's first. A slot no kernel stamped is 0 and its unsigned difference wrapped to ~1e19 ns - + // which is why (gap)/head/hc0 printed ~1e14 ms per window. A missing or out-of-order stamp now + // contributes nothing. + const auto gap = [](unsigned long long to, unsigned long long from) { + return (from != 0 && to != 0 && to >= from) ? (double) (to - from) : 0.0; + }; for (int64_t l = 0; l < L; ++l) { const int kind = is_qsa_layer(g, l) ? 1 : 0; unsigned long long prev = at(l, 0); @@ -1135,13 +1149,16 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, prof_sum_[kind][i] += (double) (x - prev); prev = x; } - if (l + 1 < L) prof_sum_[kind][25] += (double) (at(l + 1, 0) - at(l, 24)); - prof_sum_[kind][27] += (double) (at(l, 27) - at(l, 0)); // hc-read0: norm - prof_sum_[kind][28] += (double) (at(l, 28) - at(l, 27)); // down - prof_sum_[kind][29] += (double) (at(l, 1) - at(l, 28)); // up - prof_sum_[kind][1] -= (double) (at(l, 1) - at(l, 0)); // (hc-read0 shown split) + if (l + 1 < L) prof_sum_[kind][25] += gap(at(l + 1, 0), at(l, 24)); + const double dn = gap(at(l, 27), at(l, 0)), dd = gap(at(l, 28), at(l, 27)), du = gap(at(l, 1), at(l, 28)); + if (dn > 0 && dd > 0 && du > 0) { // the split exists: show it split, not twice + prof_sum_[kind][27] += dn; // hc-read0: norm + prof_sum_[kind][28] += dd; // down + prof_sum_[kind][29] += du; // up (through both halves, as before) + prof_sum_[kind][1] -= gap(at(l, 1), at(l, 0)); // (hc-read0 shown split) + } } - prof_sum_[0][26] += (double) (at(L, 1) - at(L, 0)); + prof_sum_[0][26] += gap(at(L, 1), at(L, 0)); ++prof_windows_; } // ---- a sampled or penalized request: the head's sampling again, host-side so its parameters are this call's @@ -1297,6 +1314,9 @@ bool Verifier::window_logprobs(const int32_t* targets, int T, int64_t pos0, int3 return true; } +namespace { bool g_commit_async = false; } +void Verifier::set_commit_async(bool on) { g_commit_async = on && std::getenv("STRATA_COMMIT_SYNC") == nullptr; } + bool Verifier::commit(int n_keep, std::string& err) { const OnDevice on_device(device_); if (n_keep < 1 || n_keep > last_t_) { err = "verify: commit count out of range"; return false; } @@ -1307,8 +1327,17 @@ bool Verifier::commit(int n_keep, std::string& err) { std::atomic_thread_fence(std::memory_order_seq_cst); const cudaError_t le = cudaGraphLaunch(commit_exec_, cs_); if (le != cudaSuccess) { err = std::string("verify: commit launch: ") + cudaGetErrorString(le); return false; } - const cudaError_t se = cudaStreamSynchronize(cs_); - if (se != cudaSuccess) { err = std::string("verify: commit: ") + cudaGetErrorString(se); return false; } + // set_commit_async: no wait here - the next window runs on the same stream after it, and the drafter (its own + // stream) reads only this window's final rows and its own K/V. h_commit_ is next written after the next window's + // results are read, i.e. after this graph has run. Everything else waits on commit_done_ (wait_commit). + if (!g_commit_async || next_ != nullptr) { + const cudaError_t se = cudaStreamSynchronize(cs_); + if (se != cudaSuccess) { err = std::string("verify: commit: ") + cudaGetErrorString(se); return false; } + } else { + const cudaError_t re = cudaEventRecord(commit_done_, cs_); + if (re != cudaSuccess) { err = std::string("verify: commit event: ") + cudaGetErrorString(re); return false; } + commit_pending_ = true; + } if (ple_stage()) // stages that share one session must advance it once for (int t = 0; t < n_keep; ++t) { ss_->ple_prev[0] = ss_->ple_prev[1]; @@ -1318,4 +1347,21 @@ bool Verifier::commit(int n_keep, std::string& err) { return next_ == nullptr || next_->commit(n_keep, err); } +bool Verifier::wait_commit(std::string& err) { + if (commit_pending_) { + const OnDevice on_device(device_); + commit_pending_ = false; + const cudaError_t se = cudaEventSynchronize(commit_done_); + if (se != cudaSuccess) { err = std::string("verify: commit: ") + cudaGetErrorString(se); return false; } + } + return next_ == nullptr || next_->wait_commit(err); +} + +bool Verifier::copy_logits(int t, float* host) const { + if (next_ != nullptr) return next_->copy_logits(t, host); // a layer split: the head is on the last stage + if (head_logits_ == nullptr || host == nullptr || t < 0 || n_vocab_ <= 0) return false; + return cudaMemcpy(host, head_logits_ + (size_t) t * (size_t) n_vocab_, (size_t) n_vocab_ * sizeof(float), + cudaMemcpyDeviceToHost) == cudaSuccess; +} + } // namespace strata::core diff --git a/src/kernels/cpu/pool.cpp b/src/kernels/cpu/pool.cpp index e2e5023e..45e43470 100644 --- a/src/kernels/cpu/pool.cpp +++ b/src/kernels/cpu/pool.cpp @@ -27,8 +27,8 @@ constexpr uint64_t pack_head(uint32_t epoch, uint32_t n, uint32_t i) { } } // namespace -std::vector physical_cores(bool skip_first) { - std::vector cores; +CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity) { + CpuTopology topo; #if defined(_WIN32) // Ask the OS rather than assuming a layout. `hardware_concurrency()` returns LOGICAL processors, and on // every SMT machine half of them are siblings - pinning one worker to each of the first N would put two @@ -36,30 +36,111 @@ std::vector physical_cores(bool skip_first) { DWORD len = 0; GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &len); if (len == 0) { - for (unsigned i = 0; i < std::thread::hardware_concurrency(); ++i) cores.push_back((int) i); - } else { - std::vector buf(len); - if (GetLogicalProcessorInformationEx(RelationProcessorCore, - (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) buf.data(), &len)) { - const char* p = buf.data(); - const char* end = p + len; - while (p < end) { - const auto* e = (const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) p; - if (e->Relationship == RelationProcessorCore) { - const GROUP_AFFINITY& g = e->Processor.GroupMask[0]; - for (int bit = 0; bit < 64; ++bit) - if (g.Mask & (1ull << bit)) { cores.push_back((int) (g.Group * 64 + bit)); break; } + for (unsigned i = 0; i < std::thread::hardware_concurrency(); ++i) topo.worker_cores.push_back((int) i); + if (skip_first && !topo.worker_cores.empty()) { + topo.host_core = topo.worker_cores.front(); + topo.worker_cores.erase(topo.worker_cores.begin()); + } + return topo; + } + std::vector buf(len); + if (GetLogicalProcessorInformationEx(RelationProcessorCore, + (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) buf.data(), &len)) { + const char* p = buf.data(); + const char* end = p + len; + struct CoreDesc { + uint8_t efficiency = 0; + bool has_smt = false; + std::vector lps; + }; + std::vector descs; + while (p < end) { + const auto* e = (const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) p; + if (e->Relationship == RelationProcessorCore) { + CoreDesc cd; + cd.efficiency = e->Processor.EfficiencyClass; + cd.has_smt = (e->Processor.Flags & LTP_PC_SMT) != 0; + const GROUP_AFFINITY& g = e->Processor.GroupMask[0]; + for (int bit = 0; bit < 64; ++bit) { + if (g.Mask & (1ull << bit)) { + cd.lps.push_back((int) (g.Group * 64 + bit)); + } } - p += e->Size; + if (!cd.lps.empty()) { + descs.push_back(std::move(cd)); + } + } + p += e->Size; + } + + uint8_t min_eff = 255, max_eff = 0; + for (const auto& c : descs) { + min_eff = (std::min)(min_eff, c.efficiency); + max_eff = (std::max)(max_eff, c.efficiency); + } + + topo.is_hybrid = (max_eff > min_eff); + if (topo.is_hybrid) { + for (const auto& c : descs) { + if (c.efficiency == max_eff) { + topo.p_cores++; + topo.p_threads += (int) c.lps.size(); + } else { + topo.e_cores++; + } + } + } else { + topo.p_cores = (int) descs.size(); + for (const auto& c : descs) topo.p_threads += (int) c.lps.size(); + } + + if (affinity == PoolAffinity::All || !topo.is_hybrid) { + for (const auto& c : descs) topo.worker_cores.push_back(c.lps[0]); + if (skip_first && !topo.worker_cores.empty()) { + topo.host_core = topo.worker_cores.front(); + topo.worker_cores.erase(topo.worker_cores.begin()); + } + return topo; + } + + // Hybrid CPU with Auto or PCores affinity: + // Prioritize Performance cores: + // 1. Primary logical processor of each P-core (avoids SMT resource contention) + // 2. SMT sibling logical processors of P-cores + // 3. E-cores (only as overflow in Auto mode) + std::vector p_primaries; + std::vector p_siblings; + std::vector e_cores; + + for (const auto& c : descs) { + if (c.efficiency == max_eff) { + p_primaries.push_back(c.lps[0]); + for (size_t s = 1; s < c.lps.size(); ++s) { + p_siblings.push_back(c.lps[s]); + } + } else { + for (int lp : c.lps) e_cores.push_back(lp); } } + + if (skip_first && !p_primaries.empty()) { + topo.host_core = p_primaries.front(); + p_primaries.erase(p_primaries.begin()); + } + + for (int cpu : p_primaries) topo.worker_cores.push_back(cpu); + for (int cpu : p_siblings) topo.worker_cores.push_back(cpu); + if (affinity != PoolAffinity::PCores) { + for (int cpu : e_cores) topo.worker_cores.push_back(cpu); + } + return topo; } #else // The logical CPUs this process may run on, ONE PER PHYSICAL CORE (issue #40): SMT siblings share a core's // load/store bandwidth, so a worker on each would put two workers on one core, as the Windows branch above // explains. sysfs names each CPU's (package, core); the first allowed CPU of each pair is kept, so a taskset // that leaves out the first sibling still gets its core. Without sysfs every allowed CPU counts, as before. - auto topo = [](int cpu, const char* what) -> long { + auto topo_read = [](int cpu, const char* what) -> long { char path[96]; std::snprintf(path, sizeof path, "/sys/devices/system/cpu/cpu%d/topology/%s", cpu, what); long v = -1; @@ -69,6 +150,17 @@ std::vector physical_cores(bool skip_first) { } return v; }; + auto cap_read = [](int cpu) -> long { + char path[96]; + std::snprintf(path, sizeof path, "/sys/devices/system/cpu/cpu%d/cpu_capacity", cpu); + long v = -1; + if (std::FILE* f = std::fopen(path, "r")) { + if (std::fscanf(f, "%ld", &v) != 1) v = -1; + std::fclose(f); + } + return v; + }; + std::vector allowed; cpu_set_t set; CPU_ZERO(&set); @@ -78,19 +170,96 @@ std::vector physical_cores(bool skip_first) { } else { for (unsigned i = 0; i < std::thread::hardware_concurrency(); ++i) allowed.push_back((int) i); } - std::vector> seen; + + struct CoreLinux { + int cpu = -1; + long pkg = -1; + long core = -1; + long cap = -1; + bool is_sibling = false; + }; + std::vector all_cpus; + std::vector> seen_phys; + long max_cap = 0, min_cap = 1000000; + for (int cpu : allowed) { - const long pkg = topo(cpu, "physical_package_id"), core = topo(cpu, "core_id"); - if (pkg >= 0 && core >= 0) { - const std::pair key{pkg, core}; - if (std::find(seen.begin(), seen.end(), key) != seen.end()) continue; // an SMT sibling - seen.push_back(key); + CoreLinux cl; + cl.cpu = cpu; + cl.pkg = topo_read(cpu, "physical_package_id"); + cl.core = topo_read(cpu, "core_id"); + cl.cap = cap_read(cpu); + if (cl.cap > 0) { + max_cap = (std::max)(max_cap, cl.cap); + min_cap = (std::min)(min_cap, cl.cap); } - cores.push_back(cpu); + if (cl.pkg >= 0 && cl.core >= 0) { + const std::pair key{cl.pkg, cl.core}; + if (std::find(seen_phys.begin(), seen_phys.end(), key) != seen_phys.end()) { + cl.is_sibling = true; + } else { + seen_phys.push_back(key); + } + } + all_cpus.push_back(cl); } + + topo.is_hybrid = (max_cap > 0 && max_cap > min_cap); + if (topo.is_hybrid) { + for (const auto& cl : all_cpus) { + if (cl.cap == max_cap) { + if (!cl.is_sibling) topo.p_cores++; + topo.p_threads++; + } else { + if (!cl.is_sibling) topo.e_cores++; + } + } + } else { + topo.p_cores = (int) seen_phys.size(); + topo.p_threads = (int) all_cpus.size(); + } + + if (affinity == PoolAffinity::All || !topo.is_hybrid) { + for (const auto& cl : all_cpus) { + if (!cl.is_sibling) topo.worker_cores.push_back(cl.cpu); + } + if (skip_first && !topo.worker_cores.empty()) { + topo.host_core = topo.worker_cores.front(); + topo.worker_cores.erase(topo.worker_cores.begin()); + } + return topo; + } + + // Hybrid CPU on Linux: + std::vector p_primaries; + std::vector p_siblings; + std::vector e_cores; + + for (const auto& cl : all_cpus) { + if (cl.cap == max_cap) { + if (!cl.is_sibling) p_primaries.push_back(cl.cpu); + else p_siblings.push_back(cl.cpu); + } else { + e_cores.push_back(cl.cpu); + } + } + + if (skip_first && !p_primaries.empty()) { + topo.host_core = p_primaries.front(); + p_primaries.erase(p_primaries.begin()); + } + + for (int cpu : p_primaries) topo.worker_cores.push_back(cpu); + for (int cpu : p_siblings) topo.worker_cores.push_back(cpu); + if (affinity != PoolAffinity::PCores) { + for (int cpu : e_cores) topo.worker_cores.push_back(cpu); + } + return topo; #endif - if (skip_first && !cores.empty()) cores.erase(cores.begin()); - return cores; + return topo; +} + +std::vector physical_cores(bool skip_first, PoolAffinity affinity) { + return detect_cpu_topology(skip_first, affinity).worker_cores; } namespace { @@ -173,11 +342,17 @@ void ExpertPool::diag(std::FILE* f) const { std::fprintf(f, " for %lld ms\n", (long long) (now_ms() - hstate_ms_.load())); } -ExpertPool::ExpertPool(int n_workers, bool pin, bool host_works) : host_works_(host_works) { +ExpertPool::ExpertPool(int n_workers, bool pin, bool host_works, PoolAffinity affinity) + : host_works_(host_works), affinity_(affinity), topo_(detect_cpu_topology(true, affinity)) { if (const char* e = std::getenv("STRATA_POOL_SPIN_US")) // a test knob; see kSpinBeforeSleep spin_before_sleep_ = std::chrono::microseconds((std::max)(0, std::atoi(e))); - const std::vector cores = physical_cores(true); - n_ = n_workers > 0 ? n_workers : (int) cores.size(); + if (n_workers > 0) { + n_ = n_workers; + } else if (topo_.is_hybrid && affinity_ != PoolAffinity::All) { + n_ = (std::max)(1, topo_.p_cores - 1); + } else { + n_ = (int) topo_.worker_cores.size(); + } if (n_ < 1) n_ = 1; scratch_.resize((size_t) n_); wstate_.reset(new std::atomic[(size_t) n_]); @@ -189,7 +364,7 @@ ExpertPool::ExpertPool(int n_workers, bool pin, bool host_works) : host_works_(h split_multi_.resize((size_t) kMaxSplitMulti); threads_.reserve((size_t) n_); for (int i = 0; i < n_; ++i) { - const int core = pin ? (i < (int) cores.size() ? cores[(size_t) i] : -1) : -1; + const int core = pin ? (i < (int) topo_.worker_cores.size() ? topo_.worker_cores[(size_t) i] : -1) : -1; threads_.emplace_back([this, i, core] { pin_this_thread(core); worker(i); diff --git a/src/kernels/cuda/dequant_bf16.cu b/src/kernels/cuda/dequant_bf16.cu index faac2ab4..32601d60 100644 --- a/src/kernels/cuda/dequant_bf16.cu +++ b/src/kernels/cuda/dequant_bf16.cu @@ -67,6 +67,17 @@ __device__ __forceinline__ void group32(const uint8_t* row_blocks, int gi_in_row put(out, j, (float) (((b[6 + j] & 0x0F) | xh0) - 16) * d); put(out, j + 16, (float) (((b[6 + j] >> 4) | xh1) - 16) * d); } + } else if constexpr (TYPE == 7) { // Q5_1 + const uint8_t* b = row_blocks + (size_t) gi_in_row * 24; + const float d = h2f(b), m = h2f(b + 2); + const uint32_t qh = (uint32_t) b[4] | ((uint32_t) b[5] << 8) | + ((uint32_t) b[6] << 16) | ((uint32_t) b[7] << 24); + for (int j = 0; j < 16; ++j) { + const int xh0 = ((qh >> j) & 1) << 4; + const int xh1 = ((qh >> (j + 16)) & 1) << 4; + put(out, j, (float) ((b[8 + j] & 15) | xh0) * d + m); + put(out, j + 16, (float) ((b[8 + j] >> 4) | xh1) * d + m); + } } else if constexpr (TYPE == 8) { // Q8_0 const uint8_t* b = row_blocks + (size_t) gi_in_row * 34; const float d = h2f(b); @@ -167,6 +178,7 @@ bool geometry(int type, int& block_elems, int& block_bytes) { switch (type) { case 2: block_elems = 32; block_bytes = 18; return true; case 6: block_elems = 32; block_bytes = 22; return true; + case 7: block_elems = 32; block_bytes = 24; return true; case 8: block_elems = 32; block_bytes = 34; return true; case 20: block_elems = 32; block_bytes = 18; return true; case 11: block_elems = 256; block_bytes = 110; return true; @@ -195,6 +207,7 @@ void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t co switch (type) { case 2: STRATA_DQ(2); case 6: STRATA_DQ(6); + case 7: STRATA_DQ(7); case 8: STRATA_DQ(8); case 11: STRATA_DQ(11); case 12: STRATA_DQ(12); diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index c022beca..56bb2f57 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -1,12 +1,18 @@ // src/kernels/cuda/fused_gr.cu - see include/strata/kernels/fused_gr.hpp. +#include "strata/core/emulate.hpp" #include "strata/kernels/fused_gr.hpp" #include "strata/kernels/bf16_bits.hpp" #include "strata/kernels/verify_kernels.hpp" #include +#include #include #include +#include +#include +#include +#include namespace strata::kernels { namespace { @@ -489,6 +495,309 @@ __global__ void __launch_bounds__(THREADS) gr_up_v3_kernel(GrMulti m, const floa m.a[k].mixed[d0 + col] = sum / (float) HC; } } +// ================================ #315: split / staged - the same arithmetic, split differently ================== +// The multi read's variants beside the plain read (0.1.31's default; not main's opt-in STRATA_GR_V3 read, which sums +// in another order). Every variant computes each output with exactly the plain read's operations in its order (so +// bitwise the plain read and the single-token read); only who does what, and when, changes. `fused_gr_check` +// compares them on the card before a verify window uses them (STRATA_HC_SPLIT below). +// - the norm (split and staged): one block per token AND stream instead of one per token. Each thread visits +// exactly the elements, in the order, it visited for that stream in the plain read, so every sum of squares and rs +// is the same; then it recomputes its R' * w_norm and writes it times rs (the plain read stored the product and +// scaled it in place: the same two roundings). On an RTX 4080 SUPER, the plain read's norm took 0.58 ms per +// 4-token round (96 launches of 1-4 blocks), this one 0.23 ms. +// - the down projection, split: the plain read's kernel. +// - the down projection, staged: the plain read's 8 rows per block and lane order, but the activations arrive by +// cp.async in half-stream tiles, two in flight, so no thread waits on a chain of loads, and they sit in shared +// memory as two planes (floats 0-3 and 4-7 of every 8), so a warp's reads hit no bank twice. The next tile's +// weights are loaded while the current one is used. A tile is 160 = 5 x 32 chunks of 8, so a lane still +// accumulates its chunks lane + 32 q in ascending order, as in the plain read with either tile. Before sm_80 +// (and on HIP) the staging is a plain copy: the same bits, only not asynchronous. +constexpr int kHcPlain = 1, kHcSplit = 2, kHcStaged = 3; +constexpr int H_TILE = 1280; // staged tile: half a stream = 160 chunks of 8, 5 per lane +constexpr int HQ = H_TILE / 8 / 32; +constexpr int N_HTILES = D / H_TILE; // 8 +static_assert(N % H_TILE == 0, "a staged tile never straddles two streams"); +static_assert(H_TILE % 256 == 0, "a staged tile holds whole rounds of 32 chunks: the plain read's lane order"); + +__global__ void __launch_bounds__(THREADS) gr_norm_split_kernel(GrMulti m) { + __shared__ float part[WARPS]; + __shared__ float s_rs; + const FusedGrArgs& a = m.a[blockIdx.x]; + const int c = blockIdx.y; + float* xn = m.xn + (size_t) blockIdx.x * D; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; + float ss = 0.0f; + for (int i = t * 4; i < D; i += THREADS * 4) { + if (i / N != c) continue; // another stream's element: another block's + const int d = i - c * N; + float4 r = *reinterpret_cast(a.R + i); + if (a.apply) { + const float4 b = *reinterpret_cast(a.bo_prev + d); + r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); + r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); + } + const float sq = r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; + ss += sq; + } + const float v = warp_sum(ss); + if (lane == 0) part[warp] = v; + __syncthreads(); + if (t == 0) { + float s = 0.0f; + for (int w = 0; w < WARPS; ++w) s += part[w]; + s_rs = rsqrtf(s / (float) N + a.eps); + a.rs[c] = s_rs; + } + __syncthreads(); + const float rs = s_rs; + for (int i = t * 4; i < D; i += THREADS * 4) { + if (i / N != c) continue; + const int d = i - c * N; + float4 r = *reinterpret_cast(a.R + i); + if (a.apply) { + const float4 b = *reinterpret_cast(a.bo_prev + d); + r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); + r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); + } + const float4 g = *reinterpret_cast(a.w_norm + i); + const float px = r.x * g.x, py = r.y * g.y, pz = r.z * g.z, pw = r.w * g.w; + *reinterpret_cast(xn + i) = make_float4(px * rs, py * rs, pz * rs, pw * rs); + } +} + +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 && !defined(__HIPCC__) +#define STRATA_GR_CP_ASYNC 1 +#endif +__device__ __forceinline__ void cp_async16(void* smem, const void* gmem) { +#if defined(STRATA_GR_CP_ASYNC) + const unsigned sa = (unsigned) __cvta_generic_to_shared(smem); + asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(sa), "l"(gmem) : "memory"); +#else + *reinterpret_cast(smem) = *reinterpret_cast(gmem); +#endif +} +__device__ __forceinline__ void cp_async_commit() { +#if defined(STRATA_GR_CP_ASYNC) + asm volatile("cp.async.commit_group;\n" ::: "memory"); +#endif +} +__device__ __forceinline__ void cp_async_wait1() { +#if defined(STRATA_GR_CP_ASYNC) + asm volatile("cp.async.wait_group 1;\n" ::: "memory"); +#endif +} +__device__ __forceinline__ void cp_async_wait0() { +#if defined(STRATA_GR_CP_ASYNC) + asm volatile("cp.async.wait_group 0;\n" ::: "memory"); +#endif +} + +// `dot8` with its 8 activations as two float4: the same eight fmaf in the same order +__device__ __forceinline__ float dot8v(const uint4 w, const float4 x0, const float4 x1) { + float acc = 0.0f; + acc = fmaf(__uint_as_float(w.x << 16), x0.x, acc); + acc = fmaf(__uint_as_float(w.x & 0xffff0000u), x0.y, acc); + acc = fmaf(__uint_as_float(w.y << 16), x0.z, acc); + acc = fmaf(__uint_as_float(w.y & 0xffff0000u), x0.w, acc); + acc = fmaf(__uint_as_float(w.z << 16), x1.x, acc); + acc = fmaf(__uint_as_float(w.z & 0xffff0000u), x1.y, acc); + acc = fmaf(__uint_as_float(w.w << 16), x1.z, acc); + acc = fmaf(__uint_as_float(w.w & 0xffff0000u), x1.w, acc); + return acc; +} + +// Stage tile `h` of every token into `buf`: [T][2 planes][160 chunks] float4, plane 0 = floats 0-3 of a chunk. +__device__ __forceinline__ void stage_htile(const GrMulti& m, int T, int h, float4* buf, int t) { + for (int i = t; i < T * (H_TILE / 4); i += THREADS) { + const int k = i / (H_TILE / 4), s4 = i - k * (H_TILE / 4); // s4: float4 of the tile, chunk s4/2, half s4&1 + const float* src = m.xn + (size_t) k * D + (size_t) h * H_TILE + (size_t) s4 * 4; + cp_async16(buf + (size_t) k * (H_TILE / 4) + (s4 & 1) * (H_TILE / 8) + (s4 >> 1), src); + } +} + +__global__ void __launch_bounds__(THREADS) gr_down_staged_kernel(GrMulti m) { + extern __shared__ __align__(16) float4 hbuf[]; // 2 buffers x [T][2][160] float4 + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int T = m.T; + const bool inject_block = blockIdx.x == DOWN_BLOCKS; + const int row = inject_block ? warp : blockIdx.x * WARPS + warp; + const bool active = !(inject_block && (m.a[0].w_inject == nullptr || warp >= HC)); + const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D; + const uint4* w4 = reinterpret_cast(wrow); + const size_t buf_f4 = (size_t) T * (H_TILE / 4); // float4 per buffer (the second one follows the first) + float acc[kFusedGrMaxT]; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f; + uint4 wv[HQ], wnext[HQ]; + if (active) { +#pragma unroll + for (int q = 0; q < HQ; ++q) wv[q] = __ldg(w4 + lane + 32 * q); + } + stage_htile(m, T, 0, hbuf, t); + cp_async_commit(); + stage_htile(m, T, 1, hbuf + buf_f4, t); + cp_async_commit(); +#pragma unroll 1 + for (int h = 0; h < N_HTILES; ++h) { + if (active && h + 1 < N_HTILES) { +#pragma unroll + for (int q = 0; q < HQ; ++q) wnext[q] = __ldg(w4 + (h + 1) * (H_TILE / 8) + lane + 32 * q); + } + if (h + 1 < N_HTILES) cp_async_wait1(); // tile h has landed (h + 1 may still be on its way) + else cp_async_wait0(); + __syncthreads(); + const float4* cur = hbuf + (h & 1) * buf_f4; + if (active) { +#pragma unroll + for (int q = 0; q < HQ; ++q) { + const int j = lane + 32 * q; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) { + if (k < T) { + const float4* pk = cur + (size_t) k * (H_TILE / 4); + acc[k] += dot8v(wv[q], pk[j], pk[H_TILE / 8 + j]); + } + } + } + } + __syncthreads(); // every warp is done with buffer h & 1 + if (h + 2 < N_HTILES) stage_htile(m, T, h + 2, hbuf + (h & 1) * buf_f4, t); + cp_async_commit(); // an empty group at the end keeps the wait counts simple + if (h + 1 < N_HTILES) { +#pragma unroll + for (int q = 0; q < HQ; ++q) wv[q] = wnext[q]; + } + } + if (!active) return; + float s[kFusedGrMaxT]; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) s[k] = k < T ? warp_sum(acc[k]) : 0.0f; + // lane k writes token k (every lane holds every sum after the xor reduction) +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) { + if (k >= T || lane != k) continue; + if (inject_block) { + m.a[k].inject_out[row] = s[k]; + } else { + const float x = s[k] / (float) HC; + m.a[k].lo[row] = x / (1.0f + __expf(-x)); + } + } +} + +// The tokens a down kernel may carry in one launch on the current card, and the plain read's tile: the plain read +// stages n_tok * TILEV floats (1280 on sm_75, 2560 elsewhere), staged two tiles of n_tok * H_TILE. The shared-memory +// opt-in is set here once per device (a per-DEVICE setting: a layer split runs these kernels on two cards). +int down_chunk(bool staged, int* tile_out) { + static bool attr[64] = {}; + static int chunk[64] = {}; // tokens the plain down kernel may carry in one launch on this card + static int chunk_staged[64] = {}; // the same for staged + static int tile[64] = {}; // the plain down kernel's TILEV on this card (1280 on sm_75, 2560 elsewhere) + int dev = 0; + cudaGetDevice(&dev); + if (dev < 0 || dev >= 64) { + *tile_out = 2560; + return kFusedGrMaxT; + } + if (!attr[dev]) { + int optin = 0; + cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev); + optin = strata::smem_optin_of(optin); // STRATA_EMULATE_CC (tests only) + // the down kernel stages n_tok*TILEV floats of dynamic shared memory - 80 KB at the full 8 tokens of the + // CUDA tile. sm_75 gets the smaller tile: all eight tokens fit one 40 KiB launch there (no more slicing), + // the TQ-5 prefetch holds half the registers, and the smaller blocks raise how many of the 41-block grid + // share an SM. Cards whose opt-in is still below that (or that report no opt-in at all) slice the tokens; + // the down kernel's outputs (lo, inject_out) are strictly per-token, so the chunk boundaries are safe, and + // the up kernel below still sees every token of the batch in one launch. +#if defined(__HIPCC__) + const bool small_tile = true; // all eight tokens fit gfx1100's 64 KiB LDS at this tile +#else + int cc_maj = 0, cc_min = 0; + cudaDeviceGetAttribute(&cc_maj, cudaDevAttrComputeCapabilityMajor, dev); + cudaDeviceGetAttribute(&cc_min, cudaDevAttrComputeCapabilityMinor, dev); + const bool small_tile = strata::cc_major_of(cc_maj) * 10 + strata::cc_minor_of(cc_min) == 75; +#endif + const int tv = small_tile ? 1280 : 2560; + tile[dev] = tv; + int want = (int) (kFusedGrMaxT * tv * sizeof(float)); + if (optin > 0 && want > optin) want = optin; + if (small_tile) { + cudaFuncSetAttribute(gr_down_multi_kernel<1280>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); + } else { + cudaFuncSetAttribute(gr_down_multi_kernel<2560>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); + } + int want_staged = (int) (2 * kFusedGrMaxT * H_TILE * sizeof(float)); + if (optin > 0 && want_staged > optin) want_staged = optin; + cudaFuncSetAttribute(gr_down_staged_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, want_staged); + cudaGetLastError(); // drop any error the attempt left behind + // The opt-in is a promise a pre-Volta card does not keep: an sm_60 answers 65536 and accepts the + // cudaFuncSetAttribute for 61440 B, then fails the LAUNCH with "invalid argument". What such a card + // will launch is its per-block limit, so the capacity comes from that below sm_70 - the same tokens + // the "no opt-in" branch assumes, but taken from the attribute that is actually enforced. +#if defined(__HIPCC__) + const int usable = optin > 0 ? optin : 48 * 1024; +#else + int cc = 0, per_block = 0; + cudaDeviceGetAttribute(&cc, cudaDevAttrComputeCapabilityMajor, dev); + cudaDeviceGetAttribute(&per_block, cudaDevAttrMaxSharedMemoryPerBlock, dev); + cc = strata::cc_major_of(cc); + const int usable = (cc >= 7 && optin > 0) ? optin : per_block; +#endif + const int capacity = usable / (int) (tv * sizeof(float)); + chunk[dev] = capacity < 1 ? 1 : (capacity > kFusedGrMaxT ? kFusedGrMaxT : capacity); + const int capacity_staged = usable / (int) (2 * H_TILE * sizeof(float)); + chunk_staged[dev] = capacity_staged < 1 ? 1 : (capacity_staged > kFusedGrMaxT ? kFusedGrMaxT : capacity_staged); + attr[dev] = true; + } + *tile_out = tile[dev] ? tile[dev] : 2560; + return staged ? chunk_staged[dev] : chunk[dev]; +} + +// The multi read as `variant` (kHcPlain, kHcSplit or kHcStaged): the norm, the down projection in launches of as +// many tokens as fit the card, the up projection; the profile's stamps after the norm and after the down projection. +// kHcPlain is the default read exactly as before (never main's opt-in STRATA_GR_V3 path, which fused_gr_read_multi +// takes first). +void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long long* stamp_buf, int stamp_i0) { + const int n_tok = m.T; + if (variant >= kHcSplit) gr_norm_split_kernel<<>>(m); + else gr_norm_multi_kernel<<>>(m); + if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, (void*) st); + const bool staged = variant >= kHcStaged; + int tv = 2560; + const int chunk_tok = down_chunk(staged, &tv); + const size_t per_tok = (staged ? (size_t) 2 * H_TILE : (size_t) tv) * sizeof(float); + for (int c0 = 0; c0 < n_tok; c0 += chunk_tok) { + const int ct = n_tok - c0 < chunk_tok ? n_tok - c0 : chunk_tok; + GrMulti c{}; + if (ct == n_tok) { + c = m; + } else { + c.xn = m.xn + (size_t) c0 * D; + c.T = ct; + for (int k = 0; k < ct; ++k) c.a[k] = m.a[c0 + k]; + } + const size_t smem = (size_t) ct * per_tok; + if (staged) gr_down_staged_kernel<<>>(c); + else if (tv == 1280) gr_down_multi_kernel<1280><<>>(c); + else gr_down_multi_kernel<2560><<>>(c); + } + if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, (void*) st); + gr_up_multi_kernel<<>>(m); +} + +/// STRATA_HC_SPLIT: unset or 2 = the newest the check accepts (staged), 1 = at most split, 0 = the plain read +int env_variant() { + const char* e = std::getenv("STRATA_HC_SPLIT"); + if (e == nullptr || e[0] == '\0') return kHcStaged; + if (e[0] == '0') return kHcPlain; + if (e[0] == '1') return kHcSplit; + return kHcStaged; +} + +// per device: the variant `fused_gr_check` chose (0 = not checked yet) +std::atomic g_variant[64]; + } // namespace void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf, @@ -551,84 +860,8 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi } return; } - gr_norm_multi_kernel<<>>(m); - if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, stream); - // the shared-memory opt-in is a per-DEVICE setting: once per device, not once per process (a layer split - // runs this kernel on two cards) - static bool attr[64] = {}; - static int chunk[64] = {}; // tokens the down kernel may carry in one launch on this card - static int tile[64] = {}; // the down kernel's TILEV on this card (1280 on sm_75, 2560 elsewhere; see above) - int dev = 0; - cudaGetDevice(&dev); - if (dev >= 0 && dev < 64 && !attr[dev]) { - int optin = 0; - cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev); - // the down kernel stages n_tok*TILEV floats of dynamic shared memory - 80 KB at the full 8 tokens of the - // CUDA tile. sm_75 gets the smaller tile: all eight tokens fit one 40 KiB launch there (no more slicing), - // the TQ-5 prefetch holds half the registers, and the smaller blocks raise how many of the 41-block grid - // share an SM. Cards whose opt-in is still below that (or that report no opt-in at all) slice the tokens; - // the down kernel's outputs (lo, inject_out) are strictly per-token, so the chunk boundaries are safe, and - // the up kernel below still sees every token of the batch in one launch. -#if defined(__HIPCC__) - const bool small_tile = true; // all eight tokens fit gfx1100's 64 KiB LDS at this tile -#else - int cc_maj = 0, cc_min = 0; - cudaDeviceGetAttribute(&cc_maj, cudaDevAttrComputeCapabilityMajor, dev); - cudaDeviceGetAttribute(&cc_min, cudaDevAttrComputeCapabilityMinor, dev); - const bool small_tile = cc_maj * 10 + cc_min == 75; -#endif - const int tv = small_tile ? 1280 : 2560; - tile[dev] = tv; - int want = (int) (kFusedGrMaxT * tv * sizeof(float)); - if (optin > 0 && want > optin) want = optin; - if (small_tile) { - cudaFuncSetAttribute(gr_down_multi_kernel<1280>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); - } else { - cudaFuncSetAttribute(gr_down_multi_kernel<2560>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); - } - cudaGetLastError(); // drop any error the attempt left behind - // The opt-in is a promise a pre-Volta card does not keep: an sm_60 answers 65536 and accepts the - // cudaFuncSetAttribute for 61440 B, then fails the LAUNCH with "invalid argument". What such a card - // will launch is its per-block limit, so the capacity comes from that below sm_70 - the same tokens - // the "no opt-in" branch assumes, but taken from the attribute that is actually enforced. -#if defined(__HIPCC__) - const int usable = optin > 0 ? optin : 48 * 1024; -#else - int cc = 0, per_block = 0; - cudaDeviceGetAttribute(&cc, cudaDevAttrComputeCapabilityMajor, dev); - cudaDeviceGetAttribute(&per_block, cudaDevAttrMaxSharedMemoryPerBlock, dev); - const int usable = (cc >= 7 && optin > 0) ? optin : per_block; -#endif - const int capacity = usable / (int) (tv * sizeof(float)); - chunk[dev] = capacity < 1 ? 1 : (capacity > kFusedGrMaxT ? kFusedGrMaxT : capacity); - attr[dev] = true; - } - const int tv = (dev >= 0 && dev < 64 && tile[dev]) ? tile[dev] : 2560; - const int chunk_tok = (dev >= 0 && dev < 64 && chunk[dev]) ? chunk[dev] : kFusedGrMaxT; - if (chunk_tok >= n_tok) { - const size_t smem = (size_t) n_tok * tv * sizeof(float); - if (tv == 1280) { - gr_down_multi_kernel<1280><<>>(m); - } else { - gr_down_multi_kernel<2560><<>>(m); - } - } else { - for (int c0 = 0; c0 < n_tok; c0 += chunk_tok) { - const int ct = n_tok - c0 < chunk_tok ? n_tok - c0 : chunk_tok; - GrMulti c{}; - c.xn = xn_scratch + (size_t) c0 * D; - c.T = ct; - for (int k = 0; k < ct; ++k) c.a[k] = a[c0 + k]; - const size_t smem = (size_t) ct * tv * sizeof(float); - if (tv == 1280) { - gr_down_multi_kernel<1280><<>>(c); - } else { - gr_down_multi_kernel<2560><<>>(c); - } - } - } - if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, stream); - gr_up_multi_kernel<<>>(m); + // the default read (STRATA_GR_V3 unset): v1, or the bitwise-equal v2 / v3 this card's check accepted + launch_multi(m, fused_gr_variant(), st, stamp_buf, stamp_i0); const cudaError_t e = cudaGetLastError(); if (e != cudaSuccess) { std::fprintf(stderr, "fused_gr_read_multi: %s\n", cudaGetErrorString(e)); @@ -657,4 +890,190 @@ void fused_gr_read(const FusedGrArgs& a, void* stream) { } } + +namespace { + +/// The plain read, split, staged and (for one token) the single-token read on random bf16 weights and random inputs, +/// 1..8 tokens, with and without the pending write; every output of split and staged compared with the plain read's +/// bit for bit (and the plain read's with the single-token read's). `why[v]` gets the first difference of variant +/// v; false if the check itself could not run. +bool fused_gr_selftest(bool ok_variant[4], std::string why[4]) { + constexpr int TM = kFusedGrMaxT; + constexpr int NV = 4; // sets: 0 = plain, 1 = split, 2 = staged, 3 = single-token + std::mt19937 rng(20260930u); + std::normal_distribution nd(0.0f, 1.0f); + std::vector h_down((size_t) LR * D), h_up((size_t) D * LR), h_inj((size_t) HC * D); + std::vector h_norm(D), h_R((size_t) TM * D), h_bo((size_t) TM * N), h_ip((size_t) TM * HC); + for (auto& w : h_down) w = bf16_from_f32(0.02f * nd(rng)); + for (auto& w : h_up) w = bf16_from_f32(0.05f * nd(rng)); + for (auto& w : h_inj) w = bf16_from_f32(0.02f * nd(rng)); + for (auto& w : h_norm) w = 1.0f + 0.1f * nd(rng); + for (auto& x : h_R) x = nd(rng); + for (auto& x : h_bo) x = 0.5f * nd(rng); + for (auto& x : h_ip) x = 2.0f * nd(rng); + for (int v = 0; v < 4; ++v) { ok_variant[v] = v == 1; why[v].clear(); } + + const size_t n_set = (size_t) TM * (D + D + LR + HC + HC + N); // R_out, xn, lo, rs, inject, mixed (floats) + const size_t bytes = h_down.size() * 2 + h_up.size() * 2 + h_inj.size() * 2 + + (h_norm.size() + h_R.size() + h_bo.size() + h_ip.size() + NV * n_set) * 4 + 32 * 256; + uint8_t* base = nullptr; + if (cudaMalloc((void**) &base, bytes) != cudaSuccess) { + cudaGetLastError(); + why[0] = "no room for the check (" + std::to_string(bytes >> 20) + " MiB)"; + return false; + } + size_t off = 0; + auto take = [&](size_t b) { void* p = base + off; off += (b + 255) / 256 * 256; return p; }; + uint16_t* d_down = (uint16_t*) take(h_down.size() * 2); + uint16_t* d_up = (uint16_t*) take(h_up.size() * 2); + uint16_t* d_inj = (uint16_t*) take(h_inj.size() * 2); + float* d_norm = (float*) take(h_norm.size() * 4); + float* d_R = (float*) take(h_R.size() * 4); + float* d_bo = (float*) take(h_bo.size() * 4); + float* d_ip = (float*) take(h_ip.size() * 4); + struct Set { float *R_out, *xn, *lo, *rs, *inj, *mixed; } set[NV]; + for (Set& x : set) { + x.R_out = (float*) take((size_t) TM * D * 4); x.xn = (float*) take((size_t) TM * D * 4); + x.lo = (float*) take((size_t) TM * LR * 4); x.rs = (float*) take((size_t) TM * HC * 4); + x.inj = (float*) take((size_t) TM * HC * 4); x.mixed = (float*) take((size_t) TM * N * 4); + } + cudaStream_t st = nullptr; + bool ok = off <= bytes && cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking) == cudaSuccess && + cudaMemcpyAsync(d_down, h_down.data(), h_down.size() * 2, cudaMemcpyHostToDevice, st) == cudaSuccess && + cudaMemcpyAsync(d_up, h_up.data(), h_up.size() * 2, cudaMemcpyHostToDevice, st) == cudaSuccess && + cudaMemcpyAsync(d_inj, h_inj.data(), h_inj.size() * 2, cudaMemcpyHostToDevice, st) == cudaSuccess && + cudaMemcpyAsync(d_norm, h_norm.data(), h_norm.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess && + cudaMemcpyAsync(d_R, h_R.data(), h_R.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess && + cudaMemcpyAsync(d_bo, h_bo.data(), h_bo.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess && + cudaMemcpyAsync(d_ip, h_ip.data(), h_ip.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess; + if (!ok) why[0] = "setting up the check failed"; + std::vector h1, h2; + // true when equal; false with the first difference in `w` (or a read-back failure in `ok`) + auto same = [&](const float* d1, const float* d2, size_t n, const char* what, int T, int apply, std::string& w) { + h1.resize(n); + h2.resize(n); + if (cudaMemcpyAsync(h1.data(), d1, n * 4, cudaMemcpyDeviceToHost, st) != cudaSuccess || + cudaMemcpyAsync(h2.data(), d2, n * 4, cudaMemcpyDeviceToHost, st) != cudaSuccess || + cudaStreamSynchronize(st) != cudaSuccess) { + why[0] = "reading back the check failed"; + ok = false; + return false; + } + for (size_t i = 0; i < n; ++i) { + uint32_t u1, u2; + std::memcpy(&u1, &h1[i], 4); + std::memcpy(&u2, &h2[i], 4); + if (u1 != u2) { + char buf[192]; + std::snprintf(buf, sizeof buf, "%s differs for %d token(s)%s at %zu (%08x, not %08x)", what, T, + apply ? " with the pending write" : "", i, u2, u1); + w = buf; + return false; + } + } + return true; + }; + auto all_same = [&](const Set& s1, const Set& s2, int T, int apply, std::string& w) { + return same(s1.lo, s2.lo, (size_t) T * LR, "lo", T, apply, w) && + same(s1.rs, s2.rs, (size_t) T * HC, "rs", T, apply, w) && + same(s1.inj, s2.inj, (size_t) T * HC, "inject", T, apply, w) && + same(s1.mixed, s2.mixed, (size_t) T * N, "mixed", T, apply, w) && + same(s1.R_out, s2.R_out, (size_t) T * D, "R", T, apply, w); + }; + ok_variant[2] = ok_variant[3] = ok; + bool single_ok = ok; + for (int apply = 0; apply < 2 && ok; ++apply) { + for (int T = 1; T <= TM && ok; ++T) { + FusedGrArgs a[NV][TM]; + for (int v = 0; v < NV; ++v) { + const size_t span = (size_t) ((uint8_t*) (set[v].mixed + (size_t) TM * N) - (uint8_t*) set[v].R_out); + ok = ok && cudaMemsetAsync(set[v].R_out, 0xFF, span, st) == cudaSuccess; // the whole set + for (int k = 0; k < T; ++k) { + FusedGrArgs& x = a[v][k]; + x.R = d_R + (size_t) k * D; x.R_out = set[v].R_out + (size_t) k * D; x.apply = apply != 0; + x.bo_prev = d_bo + (size_t) k * N; x.inj_prev = d_ip + (size_t) k * HC; + x.w_norm = d_norm; x.w_down = d_down; x.w_up = d_up; x.w_inject = d_inj; x.eps = 1e-6f; + x.lo = set[v].lo + (size_t) k * LR; x.rs = set[v].rs + (size_t) k * HC; + x.inject_out = set[v].inj + (size_t) k * HC; x.mixed = set[v].mixed + (size_t) k * N; + } + } + for (int v = 0; v < 3; ++v) { + GrMulti m; + for (int k = 0; k < T; ++k) m.a[k] = a[v][k]; + m.xn = set[v].xn; + m.T = T; + launch_multi(m, v + 1, st, nullptr, 0); + } + if (T == 1) fused_gr_read(a[3][0], st); + if (cudaGetLastError() != cudaSuccess || cudaStreamSynchronize(st) != cudaSuccess) { + why[0] = "a kernel of the check failed"; + ok = false; + break; + } + if (ok_variant[2] && !all_same(set[0], set[1], T, apply, why[2])) ok_variant[2] = false; + if (ok && ok_variant[3] && !all_same(set[0], set[2], T, apply, why[3])) ok_variant[3] = false; + if (ok && T == 1 && single_ok && !all_same(set[3], set[0], T, apply, why[1])) single_ok = false; + } + } + if (!single_ok && ok) { // the plain read itself disagrees with the single-token read + why[2] = why[3] = "the plain read differs from the single-token read: " + why[1]; + ok_variant[2] = ok_variant[3] = false; + } + if (st != nullptr) { + cudaStreamSynchronize(st); + cudaStreamDestroy(st); + } + cudaFree(base); + cudaGetLastError(); + if (!ok) ok_variant[2] = ok_variant[3] = false; + return ok; +} + +} // namespace + +int fused_gr_variant() { + int dev = 0; + cudaGetDevice(&dev); + const int v = dev >= 0 && dev < 64 ? g_variant[dev].load() : 0; + if (v > 0) return v; + // not checked on this card: the plain read, unless STRATA_HC_SPLIT names a variant (a test such as gr_parity) + const char* e = std::getenv("STRATA_HC_SPLIT"); + return e != nullptr && (e[0] == '1' || e[0] == '2') ? env_variant() : kHcPlain; +} + +void fused_gr_check() { + int dev = 0; + cudaGetDevice(&dev); + if (dev < 0 || dev >= 64 || g_variant[dev].load() > 0) return; + const int want = env_variant(); + if (want == kHcPlain) { + g_variant[dev].store(kHcPlain); + std::fprintf(stderr, "strata hc: CUDA%d: the hyper-connection read runs as the plain one (STRATA_HC_SPLIT=0)\n", + dev); + return; + } + bool okv[4]; + std::string why[4]; + const bool ran = fused_gr_selftest(okv, why); + int use = kHcPlain; + if (want >= kHcStaged && okv[kHcStaged]) use = kHcStaged; + else if (okv[kHcSplit]) use = kHcSplit; + g_variant[dev].store(use); + if (!ran) + std::fprintf(stderr, "strata hc: CUDA%d: the check of split/staged could not run (%s)\n", dev, why[0].c_str()); + static const char* const name[4] = {"", "plain", "split", "staged"}; + for (int v = kHcStaged; v >= kHcSplit; --v) + if (v <= want && !okv[v] && ran) + std::fprintf(stderr, "strata hc: CUDA%d: the %s read differs from the plain read on this card - not used: " + "%s\n", dev, name[v], why[v].c_str()); + static const char* const what[4] = { + "", "the plain read (the norm per token, the down projection on 41 blocks)", + "split (the norm per token and stream, then the plain read's down projection)", + "staged (the norm per token and stream, the down projection's activations staged ahead by cp.async)"}; + std::fprintf(stderr, "strata hc: CUDA%d: the hyper-connection read runs as %s%s\n", dev, what[use], + use >= kHcSplit ? "; checked bit for bit against the plain read on this card (STRATA_HC_SPLIT=1 or 0 " + "for the earlier ones)" : ""); +} + + } // namespace strata::kernels diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 61ace84a..3081c82c 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -1218,7 +1218,15 @@ __device__ void dq_q8_0(const void* vx, int64_t ibs, dst_t* yy, int tid) { for (int j = 0; j < 8; ++j) y[j] = cvt((float) x[ib].qs[8 * il + j] * d); } -// Every type below must also be in is_iq(): the host entry points refuse the others, so the default is unreachable. +// BF16 (the token embedding as the checkpoint ships it, tools/embd_bf16_pack.py): 8 values per thread. +template +__device__ void dq_bf16(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const uint16_t* x = (const uint16_t*) vx + ibs * 256 + tid * 8; + for (int j = 0; j < 8; ++j) yy[tid * 8 + j] = cvt(__uint_as_float((uint32_t) x[j] << 16)); +} + +// Every type below must also be in is_iq() (BF16: embed_type_supported): the host entry points refuse the others, +// so the default is unreachable. template __device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs, dst_t* y, int tid) { switch (ty) { @@ -1236,6 +1244,7 @@ __device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs, case 13: dq_q5_k(vx, ibs, y, tid); break; case 7: dq_q5_1(vx, ibs, y, tid); break; case 8: dq_q8_0(vx, ibs, y, tid); break; + case 30: dq_bf16(vx, ibs, y, tid); break; default: break; } } @@ -1321,6 +1330,7 @@ void iq_set_old_kernels(bool old) { g_old_kernels = old; } bool iq_old_kernels() { return g_old_kernels; } bool iq_supported(int t) noexcept { return is_iq(t); } +bool embed_type_supported(int t) noexcept { return is_iq(t) || t == 30; } size_t iq_row_bytes(int t, int64_t n) noexcept { switch (t) { @@ -1338,6 +1348,7 @@ size_t iq_row_bytes(int t, int64_t n) noexcept { case 13: return (size_t) (n / 256) * sizeof(block_q5_K); case 7: return (size_t) (n / 32) * sizeof(block_q5_1); case 8: return (size_t) (n / 32) * sizeof(block_q8_0); + case 30: return (size_t) n * 2; // BF16: the token embedding only (iq_embed_rows, iq_dequant_f32) default: return 0; } } @@ -1382,14 +1393,14 @@ __global__ void embed_rows_kernel(int ty, const uint8_t* __restrict__ table, siz void iq_embed_rows(int t, const void* table, size_t row_bytes, const int32_t* tokens, int64_t n_tok, int64_t n_embd, float* out, void* stream) { if (n_tok <= 0) return; - if (n_embd % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_embed_rows: bad arguments\n"); std::exit(1); } + if (n_embd % 256 != 0 || !embed_type_supported(t)) { std::fprintf(stderr, "iq_embed_rows: bad arguments\n"); std::exit(1); } embed_rows_kernel<<>>( t, (const uint8_t*) table, row_bytes, tokens, n_embd, out); check("iq_embed_rows"); } void iq_dequant_f32(int t, const void* src, int64_t n, float* dst, void* stream) { - if (n % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_f32: bad arguments\n"); std::exit(1); } + if (n % 256 != 0 || !embed_type_supported(t)) { std::fprintf(stderr, "iq_dequant_f32: bad arguments\n"); std::exit(1); } dequant_flat_kernel<<<(unsigned) (n / 256), 32, 0, (cudaStream_t) stream>>>(t, src, dst); check("iq_dequant_f32"); } diff --git a/src/kernels/cuda/native_gdn_preprocess.cu b/src/kernels/cuda/native_gdn_preprocess.cu index 535cb31d..86b10453 100644 --- a/src/kernels/cuda/native_gdn_preprocess.cu +++ b/src/kernels/cuda/native_gdn_preprocess.cu @@ -92,7 +92,7 @@ __global__ void gate_softplus(const float* __restrict__ alpha, const float* __re const int i = blockIdx.x * blockDim.x + threadIdx.x; if (i >= count) return; const float value = __fadd_rn(alpha[i], dt[i]); - const float softplus = value > 20.0f ? value : logf(1.0f + expf(value)); + const float softplus = value > 20.0f ? value : log1pf(expf(value)); // 1 + e^v loses e^v below ~1e-7 gate[i] = softplus * ssm_a[i]; } diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index 219576f7..e0a4c1bd 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -1439,7 +1439,7 @@ void native_iq4_nl_f32(const void* weights, const float* x, void* scratch_q8_1, } bool native_mmvq_supported(int ggml_type) noexcept { - return ggml_type == 2 || ggml_type == 6 || ggml_type == 8 || ggml_type == 11 || + return ggml_type == 2 || ggml_type == 6 || ggml_type == 7 || ggml_type == 8 || ggml_type == 11 || ggml_type == 12 || ggml_type == 13 || ggml_type == 14 || ggml_type == 20 || ggml_type == 23 || ggml_type == 42 || ggml_type == 16 || ggml_type == 17 || ggml_type == 18 || ggml_type == 21 || ggml_type == 22 || ggml_type == 29; @@ -1450,6 +1450,7 @@ std::size_t native_mmvq_weight_bytes(int ggml_type, int n_in, int n_out) { switch (ggml_type) { case 2: block_elems = 32; block_bytes = 18; break; case 6: block_elems = 32; block_bytes = 22; break; + case 7: block_elems = 32; block_bytes = 24; break; case 8: block_elems = 32; block_bytes = 34; break; case 20: block_elems = 32; block_bytes = 18; break; case 11: block_elems = 256; block_bytes = 110; break; @@ -1476,6 +1477,7 @@ void native_mmvq(int ggml_type, const void* weights, const void* x_q8_1, float* switch (ggml_type) { case 2: native_q4_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; case 6: native_q5_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; + case 7: iq_mmvq(ggml_type, weights, x_q8_1, y, n_in, n_out, ncols, stream); break; case 8: native_q8_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; case 20: native_iq4_nl_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; case 11: native_q3_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; diff --git a/src/kernels/cuda/native_qsa_indexer.cu b/src/kernels/cuda/native_qsa_indexer.cu index 299199a9..8147c709 100644 --- a/src/kernels/cuda/native_qsa_indexer.cu +++ b/src/kernels/cuda/native_qsa_indexer.cu @@ -39,13 +39,17 @@ __device__ float warp_sum(float x) { x += __shfl_xor_sync(0xffffffffu, x, offset); return x; } +// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table. The host launches whenever +// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it; +// with it merely skipped at run time, the compiled default path changed its results). +template __global__ void append(const float* __restrict__ raw, const int32_t* __restrict__ pos_dev, int pos_base, const float* __restrict__ gamma, float epsilon, float* __restrict__ tail, float* __restrict__ dead, float* __restrict__ pooled, int32_t* __restrict__ block_pos, int max_cells, float theta_scale, float freq_scale, float corr_low, float corr_high, float ext_factor, float mscale, - const int32_t* __restrict__ mtab) { + const int32_t* __restrict__ mtab, RopeTab rt) { const int pos = *pos_dev, d = threadIdx.x; if (pos < 0 || pos >= max_cells) return; const int slot = pos % R; @@ -87,9 +91,11 @@ __global__ void append(const float* __restrict__ raw, const int32_t* __restrict_ const int pair = d % (ROT / 2); // The spare (pos == 0) keeps its zero angle; under YaRN the mscale magnitude still rides in // through cos(0) - which is exactly what the queries are scaled by, so the top-k is unmoved. - const float theta_extrap = (pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); float c, s; - rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); + if (!(TAB && rope_tab_cs(rt, pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s))) { + const float theta_extrap = (pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); + rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); + } const float a = values[pair], z = values[pair + ROT / 2]; y = d < ROT / 2 ? a * c - z * s : a * s + z * c; } @@ -103,18 +109,22 @@ __global__ void append(const float* __restrict__ raw, const int32_t* __restrict_ // the RMS norm, gamma, the rotation at pos_base + 4b. `k(j)` is the key of the block's cell j: a row of this batch // (cell >= p0) or the tail the previous batch left (cell < p0). Only the batch's last completed block writes the // spare after it (every earlier one's is overwritten by the next block in order). +template __device__ __forceinline__ float pooled_value(const float* values, int d, int rope_pos, float theta_scale, float freq_scale, float corr_low, float corr_high, - float ext_factor, float mscale, const int32_t* mtab, bool zero_pos) { + float ext_factor, float mscale, const int32_t* mtab, bool zero_pos, + const RopeTab& rt) { float y = values[d]; if (d < ROT) { const int pair = d % (ROT / 2); // The same rotation the single append applies, rope_scaling.hpp's helper shared: under none this is // today's cosf/sinf; under linear/YaRN the pooled keys move with the cache's K, and the spare's zero // angle carries the mscale magnitude through cos(0) exactly as the single append's does. - const float theta_extrap = (zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); float c, s; - rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); + if (!(TAB && rope_tab_cs(rt, zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s))) { + const float theta_extrap = (zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); + rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); + } const float a = values[pair], z = values[pair + ROT / 2]; y = d < ROT / 2 ? a * c - z * s : a * s + z * c; } @@ -131,10 +141,11 @@ __device__ __forceinline__ float norm_scale(float mean, float* partials, int d) return square_sum; } // cell 0 of a sequence: the spare (every gather index names cell 0), written to pooled[0] and dead +template __global__ void append_first(const float* __restrict__ raw, const float* __restrict__ gamma, float epsilon, float* __restrict__ dead, float* __restrict__ pooled, float theta_scale, float freq_scale, float corr_low, float corr_high, float ext_factor, float mscale, - const int32_t* __restrict__ mtab) { + const int32_t* __restrict__ mtab, RopeTab rt) { const int d = threadIdx.x; __shared__ float values[D]; __shared__ float partials[32]; @@ -151,17 +162,18 @@ __global__ void append_first(const float* __restrict__ raw, const float* __restr if (d < D) values[d] = scale * mean * gamma[d]; __syncthreads(); if (d >= D) return; - const float y = pooled_value(values, d, 0, theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale, - mtab, true); + const float y = pooled_value(values, d, 0, theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale, + mtab, true, rt); pooled[d] = y; dead[d] = y; } +template __global__ void append_blocks(const float* __restrict__ raw, int64_t n, int64_t p0, int pos_base, const float* __restrict__ gamma, float epsilon, const float* __restrict__ tail, const float* __restrict__ dead, float* __restrict__ pooled, int32_t* __restrict__ block_pos, int64_t first_block, int64_t last_block, float theta_scale, float freq_scale, float corr_low, float corr_high, float ext_factor, float mscale, - const int32_t* __restrict__ mtab) { + const int32_t* __restrict__ mtab, RopeTab rt) { const int64_t b = first_block + blockIdx.x; const int d = threadIdx.x; __shared__ float values[D]; @@ -183,8 +195,8 @@ __global__ void append_blocks(const float* __restrict__ raw, int64_t n, int64_t __syncthreads(); if (d >= D) return; const int rope_pos = pos_base + R * (int) b; - pooled[std::size_t(b) * D + d] = pooled_value(values, d, rope_pos, theta_scale, freq_scale, corr_low, corr_high, - ext_factor, mscale, mtab, false); + pooled[std::size_t(b) * D + d] = pooled_value(values, d, rope_pos, theta_scale, freq_scale, corr_low, corr_high, + ext_factor, mscale, mtab, false, rt); if (b == last_block) { pooled[std::size_t(b + 1) * D + d] = dead[d]; if (d == 0) *block_pos = rope_pos; @@ -228,9 +240,15 @@ void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_dev if (overlaps(spans[i], spans[j])) throw std::invalid_argument("native QSA indexer buffers overlap"); const float theta_scale = powf((float) scaling.freq_base, -2.0f / ROT); const RopeKernelArgs k = scaling.kernel_args(ROT); // none: the identity constants - append<<<1,THREADS,0,static_cast(stream)>>>(raw,relative_pos_device,pos_base,gamma,epsilon, - b.tail,b.dead,b.pooled,b.block_pos,int(max_cells),theta_scale,k.freq_scale, - k.corr_low,k.corr_high,k.ext_factor,k.attn_factor,mrope_table()); + const RopeTab rt = rope_table_for(scaling); + if (rt.cos != nullptr) + append<<<1,THREADS,0,static_cast(stream)>>>(raw,relative_pos_device,pos_base,gamma,epsilon, + b.tail,b.dead,b.pooled,b.block_pos,int(max_cells),theta_scale,k.freq_scale, + k.corr_low,k.corr_high,k.ext_factor,k.attn_factor,mrope_table(),rt); + else + append<<<1,THREADS,0,static_cast(stream)>>>(raw,relative_pos_device,pos_base,gamma,epsilon, + b.tail,b.dead,b.pooled,b.block_pos,int(max_cells),theta_scale,k.freq_scale, + k.corr_low,k.corr_high,k.ext_factor,k.attn_factor,mrope_table(),rt); const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); } @@ -247,15 +265,24 @@ void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, in const float fsf = k.freq_scale, cl = k.corr_low, ch = k.corr_high, ef = k.ext_factor, ms = k.attn_factor; const cudaStream_t st = static_cast(stream); const int32_t* mtab = mrope_table(); - if (p0 == 0) append_first<<<1, THREADS, 0, st>>>(raw, gamma, epsilon, b.dead, b.pooled, theta_scale, - fsf, cl, ch, ef, ms, mtab); + const RopeTab rt = rope_table_for(scaling); + if (p0 == 0) { + if (rt.cos != nullptr) + append_first<<<1, THREADS, 0, st>>>(raw, gamma, epsilon, b.dead, b.pooled, theta_scale, + fsf, cl, ch, ef, ms, mtab, rt); + else + append_first<<<1, THREADS, 0, st>>>(raw, gamma, epsilon, b.dead, b.pooled, theta_scale, + fsf, cl, ch, ef, ms, mtab, rt); + } // completed blocks: those whose last cell (4b+3) lies in [p0, p0 + n) const int64_t first = p0 <= R - 1 ? 0 : (p0 - (R - 1) + R - 1) / R; // the smallest b with 4b+3 >= p0 const int64_t hi = p0 + n - 1 >= R - 1 ? (p0 + n - 1 - (R - 1)) / R : -1; // the largest b with 4b+3 <= p0+n-1 - if (hi >= first) - append_blocks<<<(unsigned) (hi - first + 1), THREADS, 0, st>>>(raw, n, p0, pos_base, gamma, epsilon, b.tail, - b.dead, b.pooled, b.block_pos, first, hi, - theta_scale, fsf, cl, ch, ef, ms, mtab); + if (hi >= first && rt.cos != nullptr) + append_blocks<<<(unsigned) (hi - first + 1), THREADS, 0, st>>>(raw, n, p0, pos_base, gamma, epsilon, + b.tail, b.dead, b.pooled, b.block_pos, first, hi, theta_scale, fsf, cl, ch, ef, ms, mtab, rt); + else if (hi >= first) + append_blocks<<<(unsigned) (hi - first + 1), THREADS, 0, st>>>(raw, n, p0, pos_base, gamma, epsilon, + b.tail, b.dead, b.pooled, b.block_pos, first, hi, theta_scale, fsf, cl, ch, ef, ms, mtab, rt); append_tail<<>>(raw, n, p0, b.tail); const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); diff --git a/src/kernels/cuda/native_rope.cu b/src/kernels/cuda/native_rope.cu index 46311720..57cbe79f 100644 --- a/src/kernels/cuda/native_rope.cu +++ b/src/kernels/cuda/native_rope.cu @@ -28,6 +28,7 @@ #include #include #include +#include #include #include @@ -38,9 +39,13 @@ bool overlaps(const void* a, size_t an, const void* b, size_t bn) { auto x = reinterpret_cast(a), y = reinterpret_cast(b); return x <= y ? y - x < an : x - y < bn; } +// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table. The host launches whenever +// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it; +// with it merely skipped at run time, the compiled default path changed its results). +template __global__ void apply(const float* x, float* out, int rows, int width, int n_rot, float theta_scale, float freq_scale, float corr_low, float corr_high, - float ext_factor, float mscale, const int* positions, const int32_t* mtab) { + float ext_factor, float mscale, const int* positions, const int32_t* mtab, RopeTab rt) { const int row = blockIdx.y; const int pair = blockIdx.x * blockDim.x + threadIdx.x; if (row >= rows || pair >= width / 2) return; @@ -52,9 +57,11 @@ __global__ void apply(const float* x, float* out, int rows, int width, } return; } - const float theta_extrap = mrope_pos(mtab, positions[row], pair) * powf(theta_scale, float(pair)); float c, s; - rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); + if (!(TAB && rope_tab_cs(rt, mrope_pos(mtab, positions[row], pair), pair, c, s))) { + const float theta_extrap = mrope_pos(mtab, positions[row], pair) * powf(theta_scale, float(pair)); + rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); + } const float a = x[start + pair], b = x[start + pair + n_rot / 2]; out[start + pair] = a * c - b * s; out[start + pair + n_rot / 2] = a * s + b * c; @@ -72,6 +79,40 @@ int mrope_dev() { } // namespace void mrope_table_set(const int32_t* device_table) { mrope_tab[mrope_dev()].store(device_table, std::memory_order_relaxed); } const int32_t* mrope_table() { return mrope_tab[mrope_dev()].load(std::memory_order_relaxed); } +namespace { +// #280: the float64 angle table of each device, set at session init (before any graph is captured) +struct RopeReg { + RopeTab tab; + RopeScaling scaling; +}; +RopeReg rope_tab[kMropeDevices] = {}; +bool same_scaling(const RopeScaling& a, const RopeScaling& b) { + return a.type == b.type && a.freq_base == b.freq_base && a.factor == b.factor && a.freq_scale_in == b.freq_scale_in && + a.orig_ctx == b.orig_ctx && a.ext_factor == b.ext_factor && a.attn_factor == b.attn_factor && + a.beta_fast == b.beta_fast && a.beta_slow == b.beta_slow; +} +// opt-in: STRATA_ROPE_TABLE=1 (the table's angles differ from the fast-math ones in the last bits, so outputs move) +bool rope_table_enabled() { + static const bool on = [] { + const char* e = std::getenv("STRATA_ROPE_TABLE"); + return e != nullptr && e[0] == '1'; + }(); + return on; +} +} // namespace +void rope_table_set(const float* cos_tab, const float* sin_tab, int max_pos, const RopeScaling& scaling) { + rope_tab[mrope_dev()] = RopeReg{RopeTab{cos_tab, sin_tab, max_pos}, scaling}; +} +void rope_table_release(const float* cos_tab) { + // every device's entry that points at it (the caller may free it from another current device) + for (RopeReg& r : rope_tab) + if (cos_tab != nullptr && r.tab.cos == cos_tab) r = RopeReg{}; +} +RopeTab rope_table_for(const RopeScaling& scaling) { + if (!rope_table_enabled()) return {}; + const RopeReg& r = rope_tab[mrope_dev()]; + return r.tab.cos != nullptr && same_scaling(r.scaling, scaling) ? r.tab : RopeTab{}; +} void native_rope_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); } bool native_rope_enabled() { return enabled.load(std::memory_order_relaxed); } void native_rope_apply(const float* x, float* out, int rows, int head_dim, @@ -92,10 +133,14 @@ void native_rope_apply(const float* x, float* out, int rows, int head_dim, // Match pinned host-side float powf before device fast powf/trigonometry. const float theta_scale = powf((float) scaling.freq_base, -2.0f / n_rot); const RopeKernelArgs k = scaling.kernel_args(n_rot); // none: the identity constants - apply<<(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale, - k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, - k.attn_factor, positions, mrope_table()); + const RopeTab rt = rope_table_for(scaling); + const dim3 grid((head_dim / 2 + 127) / 128, rows); + if (rt.cos != nullptr) + apply<<(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale, + k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, positions, mrope_table(), rt); + else + apply<<(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale, + k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, positions, mrope_table(), rt); const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); } diff --git a/src/kernels/cuda/qsa.cu b/src/kernels/cuda/qsa.cu index d1338969..a635e81e 100644 --- a/src/kernels/cuda/qsa.cu +++ b/src/kernels/cuda/qsa.cu @@ -40,6 +40,7 @@ // Every comparison still passed at any sane tolerance, the spare key landing 0.4 f32 ulp away; only a // BIT-EXACT assertion plus a full-precision probe of the intermediate found it. That is the strongest // argument in this file for keeping both. +#include "strata/core/emulate.hpp" #include "strata/kernels/qsa.hpp" #include "strata/kernels/f16_bits.hpp" @@ -673,6 +674,7 @@ void qsa_attend_step(const float* q, const uint16_t* k_scratch, const uint16_t* int dev = 0, max_shared = 0; cudaGetDevice(&dev); cudaDeviceGetAttribute(&max_shared, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev); + max_shared = strata::smem_optin_of(max_shared); if ((int) smem > max_shared) { std::fprintf(stderr, "qsa: qsa_attend: max_ids %lld needs %zu B of shared, over the %d B limit\n", (long long) max_ids, smem, max_shared); diff --git a/src/kernels/cuda/qsa_prompt_attn.cu b/src/kernels/cuda/qsa_prompt_attn.cu index 7273eb2f..93a66f03 100644 --- a/src/kernels/cuda/qsa_prompt_attn.cu +++ b/src/kernels/cuda/qsa_prompt_attn.cu @@ -1,4 +1,7 @@ // src/kernels/cuda/qsa_prompt_attn.cu - see include/strata/kernels/qsa_prompt_attn.hpp. +#include "strata/core/emulate.hpp" +#include +#include #include "strata/kernels/qsa_prompt_attn.hpp" #include "strata/kernels/kv_q8.hpp" #include "strata/kernels/kv_q4.hpp" @@ -985,7 +988,9 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3 cudaGetLastError(); return false; } - cc_major[dev] = major; + // STRATA_QSA_WARP=1|attn (an A/B arm): the pre-sm_80 kernels on any card, as RTX 20 runs them + const char* w = std::getenv("STRATA_QSA_WARP"); + cc_major[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "attn")) ? 7 : strata::cc_major_of(major); } if (cc_major[dev] < 7) return false; turing = cc_major[dev] < 8; diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cu index dd3ba537..a780fc87 100644 --- a/src/kernels/cuda/qsa_select.cu +++ b/src/kernels/cuda/qsa_select.cu @@ -1,4 +1,7 @@ // src/kernels/cuda/qsa_select.cu - see include/strata/kernels/qsa_select.hpp. +#include "strata/core/emulate.hpp" +#include +#include #include "strata/kernels/qsa_select.hpp" #include @@ -517,7 +520,9 @@ bool qsa_block_scores_tc(const float* pooled, const float* dead, const float* q_ cudaGetLastError(); return false; } - cc_major[dev] = major; + // STRATA_QSA_WARP=1|select (an A/B arm): the pre-sm_80 kernels on any card, as RTX 20 runs them + const char* w = std::getenv("STRATA_QSA_WARP"); + cc_major[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "select")) ? 7 : strata::cc_major_of(major); } if (cc_major[dev] < 8) return false; } diff --git a/src/kernels/native_expert_parity.cpp b/src/kernels/native_expert_parity.cpp index 2425062e..14232103 100644 --- a/src/kernels/native_expert_parity.cpp +++ b/src/kernels/native_expert_parity.cpp @@ -467,6 +467,59 @@ int check_q5_1_min(cudaStream_t s) { "(largest per-block sum shift %.3g) %s\n", e_q, e_s, shift, ok ? "ok" : "FAIL"); return ok ? 0 : 1; } +// #290: the BF16 token embedding (--embd-gguf) - iq_embed_rows and iq_dequant_f32 on a random BF16 table against +// the exact widening (bits << 16), every bit; rows gathered out of order, with repeats +int check_bf16_embd(cudaStream_t s) { + constexpr int kBf16 = 30; + const int64_t H = 2560, V = 61, NT = 97; + int failures = 0; + if (!strata::kernels::embed_type_supported(kBf16) || strata::kernels::iq_supported(kBf16) || + strata::kernels::iq_row_bytes(kBf16, H) != (size_t) H * 2) { + std::printf("bf16 embedding: type support / row bytes wrong\n"); + return 1; + } + std::mt19937 rng(290); + std::vector table((size_t) (V * H)); + for (auto& v : table) { // any bit pattern but NaN (a NaN's payload is not what the test is about) + do v = (uint16_t) (rng() & 0xffff); while ((v & 0x7f80) == 0x7f80 && (v & 0x7f)); + } + std::vector tok((size_t) NT); + for (auto& t : tok) t = (int32_t) (rng() % V); + void* dt = nullptr; + int32_t* dtok = nullptr; + float* dout = nullptr; + cudaMalloc(&dt, table.size() * 2); + cudaMalloc((void**) &dtok, tok.size() * 4); + const int64_t out_rows = NT > V ? NT : V; // the gathered rows (NT) and the whole table (V) share the buffer + cudaMalloc((void**) &dout, (size_t) (out_rows * H) * 4); + cudaMemcpy(dt, table.data(), table.size() * 2, cudaMemcpyHostToDevice); + cudaMemcpy(dtok, tok.data(), tok.size() * 4, cudaMemcpyHostToDevice); + auto widen = [](uint16_t b) { const uint32_t u = (uint32_t) b << 16; float f; std::memcpy(&f, &u, 4); return f; }; + std::vector got((size_t) (out_rows * H)); + strata::kernels::iq_embed_rows(kBf16, dt, (size_t) H * 2, dtok, NT, H, dout, s); + cudaStreamSynchronize(s); + cudaMemcpy(got.data(), dout, (size_t) (NT * H) * 4, cudaMemcpyDeviceToHost); + size_t rows_differ = 0; + for (int64_t r = 0; r < NT; ++r) + for (int64_t d = 0; d < H; ++d) { + const float want = widen(table[(size_t) (tok[(size_t) r] * H + d)]); + if (std::memcmp(&got[(size_t) (r * H + d)], &want, 4) != 0) { ++rows_differ; break; } + } + strata::kernels::iq_dequant_f32(kBf16, dt, V * H, dout, s); + cudaStreamSynchronize(s); + cudaMemcpy(got.data(), dout, table.size() * 4, cudaMemcpyDeviceToHost); + size_t values_differ = 0; + for (size_t i = 0; i < table.size(); ++i) { + const float want = widen(table[i]); + values_differ += std::memcmp(&got[i], &want, 4) != 0; + } + cudaFree(dt); cudaFree(dtok); cudaFree(dout); + std::printf("bf16 embedding: %lld gathered rows, %zu differ; dequant of %lld values, %zu differ in any bit\n", + (long long) NT, rows_differ, (long long) (V * H), values_differ); + if (rows_differ || values_differ) ++failures; + return failures; +} + } // namespace int main(int argc, char** argv) { @@ -474,7 +527,8 @@ int main(int argc, char** argv) { if (argc < 2) { std::fprintf(stderr, "usage: native_expert_parity [layer ...]\n" " native_expert_parity --synthetic GU/DOWN ... (ggml type names, e.g. q4_K/q5_1)\n" - " native_expert_parity --q5_1-min\n"); + " native_expert_parity --q5_1-min\n" + " native_expert_parity --bf16-embd\n"); return 2; } // #152's width check tests the opt-in rule (the multi-token kernels from one token on) @@ -491,6 +545,8 @@ int main(int argc, char** argv) { const std::string mode = argv[1]; if (mode == "--q5_1-min") { failures += check_q5_1_min(s); + } else if (mode == "--bf16-embd") { + failures += check_bf16_embd(s); } else if (mode == "--synthetic") { for (int i = 2; i < argc; ++i) { const std::string arg = argv[i]; diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp index 9def3309..1a1552bf 100644 --- a/src/kernels/ngram.cpp +++ b/src/kernels/ngram.cpp @@ -3,10 +3,12 @@ // See include/strata/kernels/ngram.hpp for the semantics, the rival readings, and the note on MADV_RANDOM. #include "strata/kernels/ngram.hpp" #include "strata/artifact/gguf_reader.hpp" +#include "strata/artifact/dequant.hpp" #include "strata/kernels/f16_bits.hpp" #include "strata/ngram/ple_reader.hpp" #include +#include #include #include #if !defined(_WIN32) @@ -111,11 +113,33 @@ void iq4nl_dequant_row(const uint8_t* row, float* out160) { } } +namespace { +struct Fp8Table { + float v[256]; + Fp8Table() { + for (int x = 0; x < 256; ++x) { + const int s = x >> 7, e = (x >> 3) & 15, m = x & 7; + float f; + if (e == 15 && m == 7) f = 0.0f; // NaN in e4m3fn; never in a real table, read as 0 + else if (e == 0) f = std::ldexp((float) m / 8.0f, -6); + else f = std::ldexp(1.0f + (float) m / 8.0f, e - 7); + v[x] = s ? -f : f; + } + } +}; +const Fp8Table kFp8; +} // namespace + +void fp8_e4m3_dequant_row(const uint8_t* row, float scale, float* out160) { + for (int j = 0; j < PLE_HEAD_DIM; ++j) out160[j] = kFp8.v[row[j]] * scale; +} + // --------------------------------------------------------------------------------------------------- struct PleTable::Impl { GgufFile* file = nullptr; const uint8_t* data = nullptr; uint64_t n_rows = 0; + bool q5_0 = false; // #296: Q5_0 rows (110 B), the mapped reader only mutable uint64_t bytes_read = 0; // Direct mode (plan v0.3 P2): the mapping above is released after the header parse and every row comes // from an unbuffered SSD read into `raw`. @@ -125,7 +149,16 @@ struct PleTable::Impl { bool pending = false; bool locked = false; uint32_t rows[PLE_N_HEADS] = {}; - uint8_t raw[PLE_N_HEADS * PLE_ROW_BYTES] = {}; + uint8_t raw[PLE_N_HEADS * PLE_ROW_BYTES_MAX] = {}; + bool fp8 = false; // F8_E4M3 rows (tools/ple_fp8_pack.py); else IQ4_NL + float scale = 1.0f; // the FP8 table's one scale + uint32_t rb = PLE_ROW_BYTES; // bytes per row + void decode(const uint8_t* row, float* out160) const { + if (fp8) fp8_e4m3_dequant_row(row, scale, out160); + else if (q5_0) + for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) strata::dequantize_q5_0(row + (size_t) b * 22, out160 + b * 32); + else iq4nl_dequant_row(row, out160); + } }; PleTable::PleTable() : impl_(new Impl) {} @@ -155,8 +188,31 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO close(); return false; } - if (std::strcmp(t->type_name(), "IQ4_NL") != 0) { - err = std::string("per_layer_token_embd.weight is ") + t->type_name() + ", not IQ4_NL"; + // IQ4_NL (ISTA-DASLab's shard 2, the original's own GGUF), Q5_0 (#296: OrcaRouter's GGUF), or the FP8 table as + // shipped: I8 bytes marked strata.ple.format = f8_e4m3 with strata.ple.scale (tools/ple_fp8_pack.py) + impl_->fp8 = false; + impl_->q5_0 = std::strcmp(t->type_name(), "Q5_0") == 0; + impl_->rb = impl_->q5_0 ? (PLE_HEAD_DIM / 32) * 22 : PLE_ROW_BYTES; + if (std::strcmp(t->type_name(), "I8") == 0) { + const MetaValue* f = impl_->file->get("strata.ple.format"); + const MetaValue* s = impl_->file->get("strata.ple.scale"); + if (f == nullptr || f->s != "f8_e4m3" || s == nullptr || !(s->num() > 0.0)) { + err = "per_layer_token_embd.weight is I8 without strata.ple.format = f8_e4m3 and a positive strata.ple.scale"; + close(); + return false; + } + impl_->fp8 = true; + impl_->scale = (float) s->num(); + impl_->rb = PLE_ROW_BYTES_FP8; + } else if (!impl_->q5_0 && std::strcmp(t->type_name(), "IQ4_NL") != 0) { + err = std::string("per_layer_token_embd.weight is ") + t->type_name() + ", not IQ4_NL, Q5_0 or FP8 (I8)"; + close(); + return false; + } + // The direct reader has fixed 90-byte rows. Keep it for IQ4_NL; Q5_0's + // 110-byte rows use the mapped path until that reader supports variable rows. + if (impl_->q5_0 && io.mode == PleIo::Direct) { + err = "Q5_0 PLE requires --ple-io mmap"; close(); return false; } @@ -171,7 +227,7 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO // assumed. A wrong data offset would leave a different remainder. // A shard may hold other tensors too (Swift 1.5's shard 1 holds layers 0-12 and the table): the table must // then fit inside the file at its own offset; alone in its shard (the original's shard 2) it fills it exactly. - const uint64_t need = impl_->n_rows * (uint64_t) PLE_ROW_BYTES; + const uint64_t need = impl_->n_rows * (uint64_t) impl_->rb; const uint64_t have = impl_->file->file_size() - impl_->file->data_start(); const bool alone = impl_->file->tensors().size() == 1; if (alone ? need != have : t->offset + need > have) { @@ -179,7 +235,7 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO std::snprintf(buf, sizeof buf, "PLE table size mismatch: %llu rows x %d B = %llu at offset %llu, but the file holds %llu from " "data_start %llu", - (unsigned long long) impl_->n_rows, PLE_ROW_BYTES, (unsigned long long) need, + (unsigned long long) impl_->n_rows, (int) impl_->rb, (unsigned long long) need, (unsigned long long) t->offset, (unsigned long long) have, (unsigned long long) impl_->file->data_start()); err = buf; @@ -194,10 +250,12 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO delete impl_->file; impl_->file = nullptr; impl_->data = nullptr; - if (!impl_->reader.open(gguf_path, table_offset, n_rows, io.max_inflight, io.cache_rows, err, io.io_thread)) { + if (!impl_->reader.open(gguf_path, table_offset, n_rows, io.max_inflight, io.cache_rows, err, io.io_thread, + impl_->rb)) { close(); return false; } + impl_->reader.set_keepalive(io.keepalive_ms, io.keepalive_window_s); impl_->n_rows = n_rows; } if (io.mode == PleIo::Mmap && io.lock && impl_->data != nullptr) { @@ -230,33 +288,37 @@ void PleTable::close() { impl_->file = nullptr; impl_->data = nullptr; impl_->n_rows = 0; + impl_->rb = PLE_ROW_BYTES; + impl_->q5_0 = false; + impl_->fp8 = false; } bool PleTable::is_open() const { return impl_->data != nullptr || impl_->reader.is_open(); } bool PleTable::locked() const { return impl_->locked; } +const char* PleTable::format() const { return impl_->fp8 ? "F8_E4M3" : impl_->q5_0 ? "Q5_0" : "IQ4_NL"; } PleIo PleTable::mode() const { return impl_->mode; } uint64_t PleTable::rows() const { return impl_->n_rows; } uint64_t PleTable::bytes_read() const { return impl_->bytes_read; } void PleTable::read_row(uint32_t row, float* out160) const { if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) { - uint8_t raw[PLE_ROW_BYTES]; + uint8_t raw[PLE_ROW_BYTES_MAX]; std::string err; const auto t = impl_->reader.issue(&row, 1, raw); if (!impl_->reader.collect(t, err)) { std::memset(out160, 0, (size_t) PLE_HEAD_DIM * sizeof(float)); return; } - iq4nl_dequant_row(raw, out160); - impl_->bytes_read += PLE_ROW_BYTES; + impl_->decode(raw, out160); + impl_->bytes_read += impl_->rb; return; } if (impl_->data == nullptr || row >= impl_->n_rows) { std::memset(out160, 0, (size_t) PLE_HEAD_DIM * sizeof(float)); return; } - iq4nl_dequant_row(impl_->data + (size_t) row * PLE_ROW_BYTES, out160); - impl_->bytes_read += PLE_ROW_BYTES; + impl_->decode(impl_->data + (size_t) row * impl_->rb, out160); + impl_->bytes_read += impl_->rb; } bool PleTable::issue(const uint32_t* rows16) { @@ -273,8 +335,8 @@ bool PleTable::issue(const uint32_t* rows16) { ULONG_PTR n = 0; for (int h = 0; h < PLE_N_HEADS; ++h) { if (rows16[h] >= impl_->n_rows) continue; - ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * PLE_ROW_BYTES); - ranges[n].NumberOfBytes = PLE_ROW_BYTES; + ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * impl_->rb); + ranges[n].NumberOfBytes = impl_->rb; ++n; } if (n > 0) (void) PrefetchVirtualMemory(GetCurrentProcess(), n, ranges, 0); @@ -290,8 +352,8 @@ bool PleTable::collect(float* out2560, std::string& err) { if (impl_->mode == PleIo::Direct) { if (!impl_->reader.collect(impl_->ticket, err)) return false; for (int h = 0; h < PLE_N_HEADS; ++h) - iq4nl_dequant_row(impl_->raw + (size_t) h * PLE_ROW_BYTES, out2560 + (size_t) h * PLE_HEAD_DIM); - impl_->bytes_read += (uint64_t) PLE_N_HEADS * PLE_ROW_BYTES; + impl_->decode(impl_->raw + (size_t) h * impl_->rb, out2560 + (size_t) h * PLE_HEAD_DIM); + impl_->bytes_read += (uint64_t) PLE_N_HEADS * impl_->rb; return true; } for (int h = 0; h < PLE_N_HEADS; ++h) read_row(impl_->rows[h], out2560 + (size_t) h * PLE_HEAD_DIM); @@ -302,11 +364,11 @@ bool PleTable::gather_batch(const uint32_t* rows, size_t n_tokens, float* out, s if (impl_->pending) { err = "PleTable::gather_batch while a token is in flight"; return false; } const size_t n = n_tokens * (size_t) PLE_N_HEADS; if (impl_->mode == PleIo::Direct) { - std::vector raw(n * PLE_ROW_BYTES); + std::vector raw(n * impl_->rb); const auto ticket = impl_->reader.issue(rows, n, raw.data()); if (!impl_->reader.collect(ticket, err)) return false; - for (size_t i = 0; i < n; ++i) iq4nl_dequant_row(raw.data() + i * PLE_ROW_BYTES, out + i * PLE_HEAD_DIM); - impl_->bytes_read += (uint64_t) n * PLE_ROW_BYTES; + for (size_t i = 0; i < n; ++i) impl_->decode(raw.data() + i * impl_->rb, out + i * PLE_HEAD_DIM); + impl_->bytes_read += (uint64_t) n * impl_->rb; return true; } for (size_t i = 0; i < n; ++i) read_row(rows[i], out + i * PLE_HEAD_DIM); @@ -317,15 +379,18 @@ void PleTable::set_injected_delay_us(double us) { impl_->reader.set_injected_del std::string PleTable::io_report() const { if (impl_->mode != PleIo::Direct || !impl_->reader.is_open()) return {}; - const strata::ngram::ReaderStats& s = impl_->reader.stats(); - char buf[320]; - std::snprintf(buf, sizeof buf, + const strata::ngram::ReaderStats s = impl_->reader.snapshot(); + char buf[400]; + int n = std::snprintf(buf, sizeof buf, "ple io: %llu rows, %.1f%% row-cache hits, %llu SSD reads (%.1f MB), read p50 %.0f us p99 %.0f us, " "blocked %.3f ms total (submit %.3f ms), cache %llu/%llu rows", (unsigned long long) s.requests, s.requests ? 100.0 * (double) s.cache_hits / (double) s.requests : 0.0, (unsigned long long) s.reads, (double) s.bytes / 1e6, s.percentile(0.5), s.percentile(0.99), s.wait_us / 1000.0, s.submit_us / 1000.0, (unsigned long long) impl_->reader.cache_size(), (unsigned long long) impl_->reader.cache_capacity()); + if (s.keepalive_reads > 0 && n > 0 && n < (int) sizeof buf) + std::snprintf(buf + n, sizeof buf - (size_t) n, ", SSD kept awake by %llu reads (slowest %.1f ms)", + (unsigned long long) s.keepalive_reads, s.keepalive_us_max / 1000.0); return buf; } @@ -360,8 +425,8 @@ void PleTable::gather(const uint32_t* rows16, float* out2560) const { for (int h = 0; h < PLE_N_HEADS; ++h) { // Out-of-range rows are handled by `read_row` as zeros and have no address to prefetch. if (rows16[h] >= impl_->n_rows) continue; - ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * PLE_ROW_BYTES); - ranges[n].NumberOfBytes = PLE_ROW_BYTES; + ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * impl_->rb); + ranges[n].NumberOfBytes = impl_->rb; ++n; } if (n > 0) (void) PrefetchVirtualMemory(GetCurrentProcess(), n, ranges, 0); diff --git a/src/kernels/ple_fp8_parity.cpp b/src/kernels/ple_fp8_parity.cpp new file mode 100644 index 00000000..09dd199a --- /dev/null +++ b/src/kernels/ple_fp8_parity.cpp @@ -0,0 +1,84 @@ +// src/kernels/ple_fp8_parity.cpp - the FP8 PLE table (tools/ple_fp8_pack.py) read through PleTable, against values +// decoded from the checkpoint itself, and against the IQ4_NL table it replaces. +// +// ple_fp8_parity [] +// +// reference.bin: int32 n, uint32 rows[n], float32 values[n][160] - the rows as torch decodes the checkpoint's +// F8_E4M3 bytes, times its weight_scale (n a multiple of 16 for the gather_batch check). Every row must match BIT FOR BIT through +// both I/O modes (Direct and Mmap) and through the prompt path's gather_batch. With the IQ4_NL shard the same rows +// are compared too: same table, so a correlation near 0.997 - a shifted row order would be ~0. +#include "strata/kernels/ngram.hpp" + +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +int main(int argc, char** argv) { + if (argc < 3) { + std::fprintf(stderr, "usage: ple_fp8_parity []\n"); + return 2; + } + std::ifstream f(argv[2], std::ios::binary); + int32_t n = 0; + f.read((char*) &n, 4); + std::vector rows((size_t) n); + std::vector ref((size_t) n * k::PLE_HEAD_DIM); + f.read((char*) rows.data(), (std::streamsize) rows.size() * 4); + f.read((char*) ref.data(), (std::streamsize) ref.size() * 4); + if (!f || n <= 0) { std::fprintf(stderr, "cannot read %s\n", argv[2]); return 2; } + + int bad = 0; + for (const k::PleIo mode : {k::PleIo::Direct, k::PleIo::Mmap}) { + k::PleTable t; + std::string err; + k::PleIoOptions io; + io.mode = mode; + if (!t.open(argv[1], err, io)) { std::fprintf(stderr, "open: %s\n", err.c_str()); return 1; } + std::vector got((size_t) n * k::PLE_HEAD_DIM); + for (int i = 0; i < n; ++i) t.read_row(rows[(size_t) i], got.data() + (size_t) i * k::PLE_HEAD_DIM); + int diff = 0; + for (size_t j = 0; j < got.size(); ++j) diff += std::memcmp(&got[j], &ref[j], 4) != 0; + std::vector batch((size_t) n * k::PLE_HEAD_DIM); // the prompt path: all rows as one request + const bool ok = t.gather_batch(rows.data(), (size_t) n / k::PLE_N_HEADS, batch.data(), err); + int bdiff = 0; + const size_t nb = (size_t) n / k::PLE_N_HEADS * k::PLE_N_HEADS * k::PLE_HEAD_DIM; + for (size_t j = 0; ok && j < nb; ++j) bdiff += std::memcmp(&batch[j], &ref[j], 4) != 0; + std::printf("%-6s %s, %llu rows: read_row %d/%zu values differ, gather_batch %s %d differ\n", + mode == k::PleIo::Direct ? "Direct" : "Mmap", t.format(), (unsigned long long) t.rows(), diff, + got.size(), ok ? "ok," : "FAILED,", bdiff); + bad += diff + bdiff + (ok ? 0 : 1) + (std::strcmp(t.format(), "F8_E4M3") != 0); + } + if (argc > 3) { + k::PleTable q; + std::string err; + if (!q.open(argv[3], err)) { std::fprintf(stderr, "open %s: %s\n", argv[3], err.c_str()); return 1; } + double cmin = 1, rsum = 0; + int counted = 0; + std::vector v(k::PLE_HEAD_DIM); + for (int i = 0; i < n; ++i) { + q.read_row(rows[(size_t) i], v.data()); + const float* r = ref.data() + (size_t) i * k::PLE_HEAD_DIM; + double sa = 0, sb = 0, sab = 0, sa2 = 0, sb2 = 0, e2 = 0, r2 = 0; + for (int j = 0; j < k::PLE_HEAD_DIM; ++j) { + sa += r[j]; sb += v[j]; sab += (double) r[j] * v[j]; sa2 += (double) r[j] * r[j]; sb2 += (double) v[j] * v[j]; + e2 += ((double) v[j] - r[j]) * ((double) v[j] - r[j]); r2 += (double) r[j] * r[j]; + } + if (r2 == 0) continue; // an all-zero row (the table has some) + const double m = k::PLE_HEAD_DIM; + const double c = (sab - sa * sb / m) / std::sqrt((sa2 - sa * sa / m) * (sb2 - sb * sb / m)); + cmin = std::fmin(cmin, c); + rsum += std::sqrt(e2 / r2); + ++counted; + } + std::printf("IQ4_NL table, same rows: correlation min %.4f, error vs FP8 %.1f%% mean (%d non-zero rows)\n", + cmin, 100 * rsum / (counted ? counted : 1), counted); + if (cmin < 0.98) ++bad; + } + std::printf("RESULT: %s\n", bad ? "MISMATCH" : "FP8 rows exact"); + return bad ? 1 : 0; +} diff --git a/src/kernels/ple_q5_parity.cpp b/src/kernels/ple_q5_parity.cpp new file mode 100644 index 00000000..cd387a8e --- /dev/null +++ b/src/kernels/ple_q5_parity.cpp @@ -0,0 +1,59 @@ +// Real-artifact Q5_0 PLE rows against ggml's reference dequantizer. +#define NOMINMAX +#include "strata/artifact/gguf_reader.hpp" +#include "strata/kernels/ngram.hpp" +#include "ggml.h" + +#include +#include +#include +#include +#include + +int main(int argc, char** argv) { + if (argc != 2) { + std::fprintf(stderr, "usage: ple_q5_parity \n"); + return 2; + } + strata::GgufFile gguf(argv[1]); + const auto* tensor = gguf.find("per_layer_token_embd.weight"); + if (!tensor || tensor->type != 6 || tensor->shape.size() != 2 || tensor->shape[0] != 160) { + std::fprintf(stderr, "expected Q5_0 PLE [160, N]\n"); + return 2; + } + strata::kernels::PleIoOptions options; + options.mode = strata::kernels::PleIo::Mmap; + strata::kernels::PleTable table; + std::string err; + if (!table.open(argv[1], err, options)) { + std::fprintf(stderr, "%s\n", err.c_str()); + return 1; + } + const auto* traits = ggml_get_type_traits(GGML_TYPE_Q5_0); + const uint8_t* bytes = gguf.tensor_data(*tensor); + const uint32_t probes[] = {0, 1, 12345, 20000003, (uint32_t) (table.rows() - 1)}; + double max_abs = 0.0; + for (uint32_t row : probes) { + float got[160], want[160]; + table.read_row(row, got); + traits->to_float(bytes + (size_t) row * 110, want, 160); + for (int i = 0; i < 160; ++i) + max_abs = std::max(max_abs, (double) std::fabs(got[i] - want[i])); + } + uint32_t rows[16]; + for (int i = 0; i < 16; ++i) rows[i] = probes[i % 5]; + float batch[16 * 160]; + if (!table.issue(rows) || !table.collect(batch, err)) { + std::fprintf(stderr, "collect: %s\n", err.c_str()); + return 1; + } + for (int h = 0; h < 16; ++h) { + float want[160]; + traits->to_float(bytes + (size_t) rows[h] * 110, want, 160); + for (int i = 0; i < 160; ++i) + max_abs = std::max(max_abs, (double) std::fabs(batch[h * 160 + i] - want[i])); + } + std::printf("Q5_0 PLE: %zu rows, max_abs %.3e %s\n", (size_t) table.rows(), max_abs, + max_abs <= 1e-6 ? "PASS" : "FAIL"); + return max_abs <= 1e-6 ? 0 : 1; +} diff --git a/src/kernels/q5_projection_parity.cpp b/src/kernels/q5_projection_parity.cpp new file mode 100644 index 00000000..20faf995 --- /dev/null +++ b/src/kernels/q5_projection_parity.cpp @@ -0,0 +1,62 @@ +// Q5_1 shared-expert projection: Strata CUDA dequantization vs ggml. +#define NOMINMAX +#include "strata/artifact/gguf_reader.hpp" +#include "strata/kernels/dequant_bf16.hpp" +#include "ggml.h" + +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char** argv) { + if (argc != 2) { + std::fprintf(stderr, "usage: q5_projection_parity \n"); + return 2; + } + strata::GgufFile gguf(argv[1]); + const auto* t = gguf.find("blk.0.ffn_down_shexp.weight"); + if (!t || t->type != 7 || t->shape.size() != 2) { + std::fprintf(stderr, "expected blk.0.ffn_down_shexp.weight Q5_1\n"); + return 2; + } + const int64_t cols = (int64_t) t->shape[0], rows = std::min(4, (int64_t) t->shape[1]); + const size_t weight_bytes = (size_t) rows * (size_t) (cols / 32) * 24; + const size_t elements = (size_t) rows * (size_t) cols; + const uint8_t* source = gguf.tensor_data(*t); + void *dweight = nullptr, *dfloat = nullptr, *dbf16 = nullptr; + if (cudaMalloc(&dweight, weight_bytes) != cudaSuccess || + cudaMalloc(&dfloat, elements * sizeof(float)) != cudaSuccess || + cudaMalloc(&dbf16, elements * sizeof(uint16_t)) != cudaSuccess) { + std::fprintf(stderr, "CUDA allocation failed\n"); + return 1; + } + cudaMemcpy(dweight, source, weight_bytes, cudaMemcpyHostToDevice); + strata::kernels::dequant_f32(7, dweight, 0, rows, cols, (float*) dfloat, nullptr); + strata::kernels::dequant_bf16(7, dweight, 0, rows, cols, (uint16_t*) dbf16, nullptr); + std::vector got(elements), ref(elements); + std::vector got_bf16(elements); + cudaMemcpy(got.data(), dfloat, elements * sizeof(float), cudaMemcpyDeviceToHost); + cudaMemcpy(got_bf16.data(), dbf16, elements * sizeof(uint16_t), cudaMemcpyDeviceToHost); + cudaFree(dweight); cudaFree(dfloat); cudaFree(dbf16); + const auto* traits = ggml_get_type_traits(GGML_TYPE_Q5_1); + for (int64_t r = 0; r < rows; ++r) + traits->to_float(source + (size_t) r * (size_t) (cols / 32) * 24, + ref.data() + (size_t) r * (size_t) cols, cols); + double max_abs = 0; + size_t bf16_bad = 0; + for (size_t i = 0; i < elements; ++i) { + max_abs = std::max(max_abs, (double) std::fabs(got[i] - ref[i])); + uint32_t bits; + std::memcpy(&bits, &ref[i], sizeof(bits)); + const uint16_t expected = (uint16_t) ((bits + 0x7fffu + ((bits >> 16) & 1u)) >> 16); + if (got_bf16[i] != expected) ++bf16_bad; + } + const bool ok = max_abs <= 1e-6 && bf16_bad == 0; + std::printf("Q5_1 projection: %zu elements, max_abs %.3e, bf16 differences %zu %s\n", + elements, max_abs, bf16_bad, ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/src/ngram/ple_reader.cpp b/src/ngram/ple_reader.cpp index ff6d5139..a03e4c04 100644 --- a/src/ngram/ple_reader.cpp +++ b/src/ngram/ple_reader.cpp @@ -2,6 +2,7 @@ #include "strata/ngram/ple_reader.hpp" #include +#include #include #include #include @@ -33,15 +34,17 @@ constexpr uint32_t EMPTY = 0xFFFFFFFFu; /// Set-associative row cache: 8 ways per set, round-robin replacement inside a set. Bounded by construction. struct RowCache { uint64_t sets = 0; + uint32_t rb = ROW_BYTES; // bytes per row std::vector keys; // sets * WAYS - std::vector data; // sets * WAYS * ROW_BYTES + std::vector data; // sets * WAYS * rb std::vector next; // per-set replacement pointer uint64_t used = 0; - void init(uint64_t rows) { + void init(uint64_t rows, uint32_t row_bytes = ROW_BYTES) { sets = rows / WAYS; + rb = row_bytes; keys.assign(sets * WAYS, EMPTY); - data.assign(sets * WAYS * ROW_BYTES, 0); + data.assign(sets * WAYS * rb, 0); next.assign(sets, 0); used = 0; } @@ -53,7 +56,7 @@ struct RowCache { if (sets == 0) return nullptr; const uint64_t s = mix(row) % sets; for (uint32_t w = 0; w < WAYS; ++w) - if (keys[s * WAYS + w] == row) return &data[(s * WAYS + w) * ROW_BYTES]; + if (keys[s * WAYS + w] == row) return &data[(s * WAYS + w) * rb]; return nullptr; } void insert(uint32_t row, const uint8_t* bytes) { @@ -63,7 +66,7 @@ struct RowCache { next[s] = (uint8_t) ((w + 1) % WAYS); if (keys[s * WAYS + w] == EMPTY) ++used; keys[s * WAYS + w] = row; - std::memcpy(&data[(s * WAYS + w) * ROW_BYTES], bytes, ROW_BYTES); + std::memcpy(&data[(s * WAYS + w) * rb], bytes, rb); } }; @@ -79,6 +82,7 @@ struct Job { uint32_t ticket = 0; std::vector uses; double issued_us = 0; + bool keepalive = false;// no rows and no ticket: it only keeps the SSD awake (`set_keepalive`) }; struct TicketState { @@ -95,6 +99,7 @@ struct PleReader::Impl { DirectFile file; uint64_t table_offset = 0; uint64_t n_rows = 0; + uint32_t row_bytes = ROW_BYTES; uint32_t max_inflight = 0; uint8_t* slab = nullptr; // max_inflight slots of 2 pages std::vector free_slots; @@ -108,6 +113,12 @@ struct PleReader::Impl { size_t ring_pos = 0; double delay_us = 0; std::string error; + // the keep-alive (`set_keepalive`), steady-clock microseconds; `keep_us` 0 = off + double keep_us = 0; + double keep_window_us = 0; + double last_issue_us = 0; // the last `issue` + double last_read_us = 0; // the last read that went out, rows or keep-alive + uint64_t rng = 0x9E3779B97F4A7C15ull; bool threaded = false; bool stop = false; @@ -141,7 +152,14 @@ struct PleReader::Impl { queue.pop_front(); Job& j = inflight[s]; j.issued_us = now_us(); - if (!file.submit(j.offset, slot_buf(s), j.length, s, error)) { + std::string kerr; // a keep-alive read that cannot go out must not fail the reader + if (!file.submit(j.offset, slot_buf(s), j.length, s, j.keepalive ? kerr : error)) { + if (j.keepalive) { // no more of them: the SSD may sleep as before + keep_us = 0; + j.keepalive = false; + free_slots.push_back(s); + continue; + } j.uses.clear(); auto it = tickets.find(j.ticket); if (it != tickets.end() && it->second.pending > 0) --it->second.pending; @@ -149,12 +167,35 @@ struct PleReader::Impl { cancel_queued(); return false; } - stats.submit_us += now_us() - j.issued_us; - ++stats.reads; + last_read_us = j.issued_us; + if (!j.keepalive) { // a keep-alive read counts when it completes (`finish`) + stats.submit_us += now_us() - j.issued_us; + ++stats.reads; + } } return true; } + /// When the next keep-alive read is due, or < 0 when none is: it is off, the reader failed, or no rows + /// were asked for within the window (then the SSD may sleep; the next `issue` re-arms it). + double keepalive_due(double now) const { + if (keep_us <= 0 || !error.empty() || last_issue_us <= 0 || now - last_issue_us > keep_window_us) return -1; + return last_read_us + keep_us; + } + + /// One page of the table, a different one each time, so the SSD really reads (not its controller's buffer). + void queue_keepalive() { + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + const uint64_t first = table_offset / PAGE, end = (table_offset + n_rows * (uint64_t) row_bytes) / PAGE; + Job j; + j.offset = (first + (end > first ? rng % (end - first) : 0)) * PAGE; + j.length = PAGE; + j.keepalive = true; + queue.push_back(std::move(j)); + } + bool finish(const Completion& c) { const uint32_t s = (uint32_t) c.tag; if (s >= inflight.size()) { @@ -163,6 +204,17 @@ struct PleReader::Impl { return false; } Job& j = inflight[s]; + if (j.keepalive) { // no rows: it counts once it is done, with how long it took; + if (c.ok) { // a failed one turns the keep-alive off, not the reader + ++stats.keepalive_reads; + stats.keepalive_us_max = std::max(stats.keepalive_us_max, now_us() - j.issued_us); + } else { + keep_us = 0; + } + j.keepalive = false; + free_slots.push_back(s); + return error.empty() ? pump() : true; + } if (!c.ok) { error = "PleReader: a table read failed"; cancel_queued(); @@ -176,7 +228,7 @@ struct PleReader::Impl { stats.bytes += c.bytes; const uint8_t* buf = slot_buf(s); for (const Use& u : j.uses) { - if (u.in_page + ROW_BYTES > c.bytes) { + if (u.in_page + row_bytes > c.bytes) { error = "PleReader: short read inside the table"; cancel_queued(); j.uses.clear(); @@ -187,7 +239,7 @@ struct PleReader::Impl { } } for (const Use& u : j.uses) { - std::memcpy(u.dst, buf + u.in_page, ROW_BYTES); + std::memcpy(u.dst, buf + u.in_page, row_bytes); cache.insert(u.row, buf + u.in_page); } auto it = tickets.find(j.ticket); @@ -246,7 +298,14 @@ struct PleReader::Impl { void worker_loop() { std::unique_lock lk(mu); for (;;) { - cv_work.wait(lk, [&] { return stop || !queue.empty() || busy(); }); + // Idle: wait for work. While rows are being asked for, the wait ends in time for a keep-alive read. + while (!(stop || !queue.empty() || busy())) { + const double now = now_us(); + const double due = keepalive_due(now); + if (due < 0) cv_work.wait(lk); + else if (now >= due) queue_keepalive(); + else cv_work.wait_for(lk, std::chrono::microseconds(std::max(1000, (int64_t) (due - now)))); + } if (stop && !busy()) break; if (error.empty() && !pump() && error.empty()) error = "PleReader: submit failed"; if (!delayed.empty() && !release_delayed() && error.empty()) error = "PleReader: read failed"; @@ -274,11 +333,13 @@ PleReader::~PleReader() { } bool PleReader::open(const std::string& path, uint64_t table_offset, uint64_t n_rows, uint32_t max_inflight, - uint64_t cache_rows, std::string& err, bool io_thread) { + uint64_t cache_rows, std::string& err, bool io_thread, uint32_t row_bytes) { close(); if (max_inflight == 0 || max_inflight > 1024) { err = "PleReader: max_inflight must be 1..1024"; return false; } + if (row_bytes == 0 || row_bytes > PAGE) { err = "PleReader: row_bytes must be 1..4096"; return false; } if (!impl_->file.open(path, err)) return false; - if (table_offset + n_rows * (uint64_t) ROW_BYTES > impl_->file.size()) { + impl_->row_bytes = row_bytes; + if (table_offset + n_rows * (uint64_t) row_bytes > impl_->file.size()) { err = "PleReader: the table extends past the end of " + path; close(); return false; @@ -291,8 +352,12 @@ bool PleReader::open(const std::string& path, uint64_t table_offset, uint64_t n_ impl_->inflight.assign(max_inflight, Job{}); impl_->free_slots.clear(); for (uint32_t s = max_inflight; s-- > 0;) impl_->free_slots.push_back(s); - impl_->cache.init(cache_rows); + impl_->cache.init(cache_rows, row_bytes); impl_->error.clear(); + impl_->keep_us = 0; + impl_->last_issue_us = impl_->last_read_us = 0; + impl_->rng = 0x9E3779B97F4A7C15ull ^ (uint64_t) now_us(); + if (impl_->rng == 0) impl_->rng = 1; reset_stats(); impl_->stop = false; impl_->threaded = io_thread; @@ -346,9 +411,12 @@ void PleReader::close() { m.cache.init(0); m.threaded = false; m.stop = false; + m.keep_us = 0; + m.last_issue_us = m.last_read_us = 0; } bool PleReader::is_open() const { return impl_->file.is_open(); } +uint32_t PleReader::row_bytes() const { return impl_->row_bytes; } PleReader::Ticket PleReader::issue(const uint32_t* rows, size_t n, uint8_t* out_raw) { Impl& m = *impl_; @@ -356,24 +424,28 @@ PleReader::Ticket PleReader::issue(const uint32_t* rows, size_t n, uint8_t* out_ if (m.threaded) lk.lock(); const uint32_t id = m.next_ticket++; if (m.next_ticket == 0) m.next_ticket = 1; + const double now = now_us(); + const bool rearm = m.keep_us > 0 && (m.last_issue_us <= 0 || now - m.last_issue_us > m.keep_window_us); + m.last_issue_us = now; TicketState& ts = m.tickets[id]; std::unordered_map by_page; // aligned offset -> index in `jobs` std::vector jobs; for (size_t i = 0; i < n; ++i) { - uint8_t* dst = out_raw + i * ROW_BYTES; + const uint32_t rb = m.row_bytes; + uint8_t* dst = out_raw + i * rb; ++m.stats.requests; if (rows[i] >= m.n_rows) { - std::memset(dst, 0, ROW_BYTES); + std::memset(dst, 0, rb); continue; } if (const uint8_t* hit = m.cache.find(rows[i])) { - std::memcpy(dst, hit, ROW_BYTES); + std::memcpy(dst, hit, rb); ++m.stats.cache_hits; continue; } - const uint64_t at = m.table_offset + (uint64_t) rows[i] * ROW_BYTES; + const uint64_t at = m.table_offset + (uint64_t) rows[i] * rb; const uint64_t first = at / PAGE * PAGE; - const uint32_t length = (uint32_t) ((at + ROW_BYTES - 1) / PAGE * PAGE - first + PAGE); + const uint32_t length = (uint32_t) ((at + rb - 1) / PAGE * PAGE - first + PAGE); auto f = by_page.find(first); if (f != by_page.end()) { Job& j = jobs[f->second]; @@ -400,6 +472,8 @@ PleReader::Ticket PleReader::issue(const uint32_t* rows, size_t n, uint8_t* out_ if (has_jobs) { m.cv_work.notify_one(); m.file.wake(); // in case the worker is blocked in the port + } else if (rearm) { + m.cv_work.notify_one(); // the keep-alive had lapsed: start it again } } else if (!m.pump() && m.error.empty()) { m.error = "PleReader: submit failed"; @@ -439,14 +513,33 @@ bool PleReader::collect(Ticket t, std::string& err) { return true; } +void PleReader::set_keepalive(double period_ms, double window_s) { + Impl& m = *impl_; + { + std::lock_guard lk(m.mu); + m.keep_us = m.threaded && period_ms > 0 ? period_ms * 1000.0 : 0.0; + m.keep_window_us = window_s > 0 ? window_s * 1e6 : 0.0; + } + m.cv_work.notify_all(); +} + void PleReader::set_injected_delay_us(double delay_us) { std::lock_guard lk(impl_->mu); impl_->delay_us = delay_us < 0 ? 0 : delay_us; } const ReaderStats& PleReader::stats() const { return impl_->stats; } +ReaderStats PleReader::snapshot() const { + Impl& m = *impl_; + std::unique_lock lk(m.mu, std::defer_lock); + if (m.threaded) lk.lock(); + return m.stats; +} void PleReader::reset_stats() { - impl_->stats = ReaderStats{}; - impl_->ring_pos = 0; + Impl& m = *impl_; + std::unique_lock lk(m.mu, std::defer_lock); + if (m.threaded) lk.lock(); // the worker may be counting a keep-alive read + m.stats = ReaderStats{}; + m.ring_pos = 0; } uint64_t PleReader::cache_capacity() const { return impl_->cache.sets * WAYS; } uint64_t PleReader::cache_size() const { return impl_->cache.used; } diff --git a/src/ngram/ple_reader_test.cpp b/src/ngram/ple_reader_test.cpp index 37e55f3b..86b48624 100644 --- a/src/ngram/ple_reader_test.cpp +++ b/src/ngram/ple_reader_test.cpp @@ -10,6 +10,7 @@ #include "strata/ngram/ple_reader.hpp" #include "strata/platform/direct_file.hpp" +#include #include #include #include @@ -18,6 +19,7 @@ #include #include #include +#include #include namespace ng = strata::ngram; @@ -135,6 +137,56 @@ int selftest(const std::string& dir) { CHECK(now_us() - t0 >= 3000, "injected delay not observed (%.0f us)", now_us() - t0); CHECK(rd.stats().late_injected > 0, "no read was held back"); } + // keep-alive: while rows are asked for, a page goes out after `period` without a read; it stops once the + // window after the last issue has passed, starts again with the next issue (even one the row cache serves), + // and never shows up as a row read or changes a row + { + ng::PleReader rd; + std::string err; + CHECK(rd.open(path, HEADER, N, 16, 4096, err, true), "open: %s", err.c_str()); + rd.set_keepalive(20.0, 0.5); + std::vector rows(16); + for (auto& r : rows) r = rng() % N; + check_rows(rd, rows, N, "keep-alive, first ticket"); + const uint64_t reads0 = rd.snapshot().reads; + const auto nap = [](int ms) { std::this_thread::sleep_for(std::chrono::milliseconds(ms)); }; + nap(300); + const uint64_t k1 = rd.snapshot().keepalive_reads; + CHECK(k1 >= 8 && k1 <= 20, "keep-alive: %llu reads in 300 ms at a 20 ms period", (unsigned long long) k1); + CHECK(rd.snapshot().reads == reads0, "keep-alive reads were counted as row reads"); + nap(600); // the 0.5 s window has passed + const uint64_t k2 = rd.snapshot().keepalive_reads; + nap(300); + const uint64_t k3 = rd.snapshot().keepalive_reads; + CHECK(k3 == k2, "keep-alive went on after the window (%llu -> %llu)", (unsigned long long) k2, + (unsigned long long) k3); + CHECK(k2 <= k1 + 20, "keep-alive: %llu reads by the end of a 0.5 s window", (unsigned long long) k2); + check_rows(rd, rows, N, "keep-alive, cached ticket"); // the row cache serves all 16: no row read + CHECK(rd.snapshot().reads == reads0, "cached rows were read again"); + nap(200); + CHECK(rd.snapshot().keepalive_reads >= k3 + 5, "the keep-alive did not start again (%llu -> %llu)", + (unsigned long long) k3, (unsigned long long) rd.snapshot().keepalive_reads); + std::vector more(2000); + for (auto& r : more) r = rng() % N; + check_rows(rd, more, N, "keep-alive, rows afterwards"); + rd.set_keepalive(0, 0.5); // off + const uint64_t k4 = rd.snapshot().keepalive_reads; + nap(200); + CHECK(rd.snapshot().keepalive_reads <= k4 + 1, "keep-alive went on after it was turned off"); + rd.reset_stats(); + CHECK(rd.snapshot().keepalive_reads == 0 && rd.snapshot().keepalive_us_max == 0, "reset_stats kept keep-alive counts"); + } + { // the caller's thread does the reads: no worker, so no keep-alive + ng::PleReader rd; + std::string err; + CHECK(rd.open(path, HEADER, N, 16, 0, err, false), "open: %s", err.c_str()); + rd.set_keepalive(20.0, 1.0); + std::vector rows(16); + for (auto& r : rows) r = rng() % N; + check_rows(rd, rows, N, "keep-alive, caller thread"); + std::this_thread::sleep_for(std::chrono::milliseconds(150)); + CHECK(rd.snapshot().keepalive_reads == 0, "keep-alive without the worker thread"); + } std::filesystem::remove(path); std::printf("ple_reader selftest: %s\n", g_fail ? "FAILED" : "OK"); return g_fail ? 1 : 0; diff --git a/src/prefill/ggml_cuda_host.cu b/src/prefill/ggml_cuda_host.cu index 12f4c8af..c8f8284b 100644 --- a/src/prefill/ggml_cuda_host.cu +++ b/src/prefill/ggml_cuda_host.cu @@ -1,5 +1,6 @@ // src/prefill/ggml_cuda_host.cu - prompt-speed plan step 2b: the host-side symbols of llama.cpp's ggml-cuda that its MMQ // and quantize code reference, for the MMQ kernels compiled into strata_mmq without the rest of ggml-cuda.cu. +#include "strata/core/emulate.hpp" #include "common.cuh" #include @@ -80,8 +81,8 @@ const ggml_cuda_device_info & ggml_cuda_info() { d.integrated = false; d.supports_cooperative_launch = false; #else - d.cc = 100 * prop.major + 10 * prop.minor; - d.smpbo = prop.sharedMemPerBlockOptin; + d.cc = 100 * strata::cc_major_of(prop.major) + 10 * strata::cc_minor_of(prop.minor); // STRATA_EMULATE_CC + d.smpbo = strata::smem_optin_of((int) prop.sharedMemPerBlockOptin); d.integrated = prop.integrated != 0; d.supports_cooperative_launch = prop.cooperativeLaunch != 0; #endif diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 25226735..de833442 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -32,8 +32,15 @@ __device__ __forceinline__ uint16_t bf(float f) { u += 0x7fffu + ((u >> 16) & 1u); return (uint16_t) (u >> 16); } +// The BF16 GEMMs' second operand (STRATA_PREFILL_BF16X2): what the BF16 image `hi` left out of f, itself in BF16. +// W.hi + W.lo carries ~16 mantissa bits of the activation - the decode path's FP32 x to within ~1e-5. +__device__ __forceinline__ uint16_t bf_lo(float f, uint16_t hi) { return bf(f - __uint_as_float((uint32_t) hi << 16)); } __device__ __forceinline__ float sigm(float x) { return 1.0f / (1.0f + __expf(-x)); } __device__ __forceinline__ uint16_t hf(float f) { return __half_as_ushort(__float2half_rn(f)); } +// A SwiGLU product for an FP16 GEMM: saturated, so a token with a massive activation cannot turn into inf and then +// NaN in the down projection (decode's q8_1 has room to ~8e6; FP16 ends at 65504). A NaN stays NaN (fminf/fmaxf +// would make it -65504 and hide where it came from); finite values below 65504 round exactly as before. +__device__ __forceinline__ uint16_t hf_sat(float f) { return hf(isnan(f) ? f : fminf(fmaxf(f, -65504.0f), 65504.0f)); } // block-wide sum for blockDim.x <= 1024, result broadcast __device__ float block_sum(float v, float* sh) { const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; @@ -56,7 +63,7 @@ unsigned blocks_for(int64_t n, int t = 256) { return (unsigned) ((n + t - 1) / t // ---------------------------------------------------------------- hyper-connection __global__ void gr_norm_kernel(const float* __restrict__ R, const float* __restrict__ w, float eps, - float* __restrict__ xn, uint16_t* __restrict__ xn16) { + float* __restrict__ xn, uint16_t* __restrict__ xn16, uint16_t* __restrict__ xn16_lo) { __shared__ float sh[32]; const int64_t row = blockIdx.x; // t * 4 + c const int c = (int) (row % HC); @@ -67,13 +74,16 @@ __global__ void gr_norm_kernel(const float* __restrict__ R, const float* __restr for (int d = threadIdx.x; d < N; d += blockDim.x) { const float v = r[d] * rs * w[c * N + d]; xn[row * N + d] = v; - xn16[row * N + d] = bf(v); + const uint16_t h = bf(v); + xn16[row * N + d] = h; + if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h); } } // F-1: the row scale only (and the BF16 image); gr_mix_r_kernel recomputes r * rs * w itself, in the same order, // so the FP32 copy of the normalized rows (T x 10240 floats) is neither written nor read __global__ void gr_norm_rs_kernel(const float* __restrict__ R, const float* __restrict__ w, float eps, - float* __restrict__ rs_out, uint16_t* __restrict__ xn16) { + float* __restrict__ rs_out, uint16_t* __restrict__ xn16, + uint16_t* __restrict__ xn16_lo) { __shared__ float sh[32]; const int64_t row = blockIdx.x; // t * 4 + c const int c = (int) (row % HC); @@ -82,11 +92,16 @@ __global__ void gr_norm_rs_kernel(const float* __restrict__ R, const float* __re for (int d = threadIdx.x; d < N; d += blockDim.x) ss += r[d] * r[d]; const float rs = rsqrtf(block_sum(ss, sh) / (float) N + eps); if (threadIdx.x == 0) rs_out[row] = rs; - for (int d = threadIdx.x; d < N; d += blockDim.x) xn16[row * N + d] = bf(r[d] * rs * w[c * N + d]); + for (int d = threadIdx.x; d < N; d += blockDim.x) { + const float v = r[d] * rs * w[c * N + d]; + const uint16_t h = bf(v); + xn16[row * N + d] = h; + if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h); + } } __global__ void gr_mix_r_kernel(const float* __restrict__ R, const float* __restrict__ rs, const float* __restrict__ w, const float* __restrict__ g, float* __restrict__ mixed, uint16_t* __restrict__ mixed16, - int64_t T, uint16_t* __restrict__ mixed_h) { + int64_t T, uint16_t* __restrict__ mixed_h, uint16_t* __restrict__ mixed16_lo) { const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; if (i >= T * N) return; const int64_t t = i / N, d = i % N; @@ -99,7 +114,11 @@ __global__ void gr_mix_r_kernel(const float* __restrict__ R, const float* __rest } s /= (float) HC; mixed[i] = s; - if (mixed16) mixed16[i] = bf(s); + if (mixed16) { + const uint16_t h = bf(s); + mixed16[i] = h; + if (mixed16_lo) mixed16_lo[i] = bf_lo(s, h); + } if (mixed_h) mixed_h[i] = hf(s); } // F-2: gr_write_kernel for one row (t, c), then gr_norm_rs_kernel's reduction over it with the next half's norm @@ -109,7 +128,8 @@ constexpr int GRW_PER = (N + 255) / 256; __global__ void __launch_bounds__(256) gr_write_norm_rs_kernel(float* __restrict__ R, const float* __restrict__ bo, const float* __restrict__ inj, int64_t inj_ld, const float* __restrict__ w, float eps, - float* __restrict__ rs_out, uint16_t* __restrict__ xn16) { + float* __restrict__ rs_out, uint16_t* __restrict__ xn16, + uint16_t* __restrict__ xn16_lo) { __shared__ float sh[32]; const int64_t row = blockIdx.x; // t * 4 + c const int64_t t = row / HC; @@ -130,16 +150,26 @@ __global__ void __launch_bounds__(256) gr_write_norm_rs_kernel(float* __restrict if (threadIdx.x == 0) rs_out[row] = rs; k = 0; #pragma unroll - for (int d = threadIdx.x; d < N; d += 256, ++k) xn16[row * N + d] = bf(v[k] * rs * w[c * N + d]); + for (int d = threadIdx.x; d < N; d += 256, ++k) { + const float x = v[k] * rs * w[c * N + d]; + const uint16_t h = bf(x); + xn16[row * N + d] = h; + if (xn16_lo) xn16_lo[row * N + d] = bf_lo(x, h); + } } -__global__ void gr_silu_kernel(const float* __restrict__ lo, uint16_t* __restrict__ lo16, int64_t n) { +__global__ void gr_silu_kernel(const float* __restrict__ lo, uint16_t* __restrict__ lo16, uint16_t* __restrict__ lo16_lo, + int64_t n) { const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; if (i >= n) return; const float x = lo[i] / (float) HC; - lo16[i] = bf(x / (1.0f + __expf(-x))); + const float v = x / (1.0f + __expf(-x)); + const uint16_t h = bf(v); + lo16[i] = h; + if (lo16_lo) lo16_lo[i] = bf_lo(v, h); } __global__ void gr_mix_kernel(const float* __restrict__ xn, const float* __restrict__ g, float* __restrict__ mixed, - uint16_t* __restrict__ mixed16, int64_t T, uint16_t* __restrict__ mixed_h) { + uint16_t* __restrict__ mixed16, int64_t T, uint16_t* __restrict__ mixed_h, + uint16_t* __restrict__ mixed16_lo) { const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; if (i >= T * N) return; const int64_t t = i / N, d = i % N; @@ -151,7 +181,11 @@ __global__ void gr_mix_kernel(const float* __restrict__ xn, const float* __restr } s /= (float) HC; mixed[i] = s; - if (mixed16) mixed16[i] = bf(s); + if (mixed16) { + const uint16_t h = bf(s); + mixed16[i] = h; + if (mixed16_lo) mixed16_lo[i] = bf_lo(s, h); + } if (mixed_h) mixed_h[i] = hf(s); } __global__ void gr_write_kernel(float* __restrict__ R, const float* __restrict__ bo, const float* __restrict__ inj, @@ -486,14 +520,14 @@ __global__ void swiglu_il_kernel(const float* __restrict__ gu, uint16_t* __restr if (i >= n * 640) return; const int64_t r = i / 640, k = i % 640; const float g = gu[r * 1280 + 2 * k], u = gu[r * 1280 + 2 * k + 1]; - h16[i] = hf(g / (1.0f + __expf(-g)) * u); + h16[i] = hf_sat(g / (1.0f + __expf(-g)) * u); } __global__ void swiglu_pair_kernel(const float* __restrict__ g, const float* __restrict__ u, uint16_t* __restrict__ h16, int64_t n) { const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; if (i >= n * 640) return; const float a = g[i]; - h16[i] = hf(a / (1.0f + __expf(-a)) * u[i]); + h16[i] = hf_sat(a / (1.0f + __expf(-a)) * u[i]); } __global__ void gather_rows16_kernel(const uint16_t* __restrict__ x, const int32_t* __restrict__ src, uint16_t* __restrict__ dst, int64_t n, int64_t width) { @@ -525,18 +559,26 @@ __global__ void rms_rows_kernel(float* __restrict__ x, const float* __restrict__ __syncthreads(); for (int64_t c = threadIdx.x; c < cols; c += blockDim.x) r[c] = s * r[c] * w[c]; } +// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table. The host launches whenever +// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it; +// with it merely skipped at run time, the compiled default path changed its results). +template __global__ void rope_kernel(float* __restrict__ x, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, float theta_scale, float freq_scale, float corr_low, float corr_high, - float ext_factor, float mscale, const int32_t* __restrict__ mtab) { + float ext_factor, float mscale, const int32_t* __restrict__ mtab, + strata::kernels::RopeTab rt) { const int64_t row = blockIdx.x; // t * heads + h const int pair = threadIdx.x; // 0..31 const int64_t t = row / heads, h = row % heads; float* p = x + t * ld + h * dim; - const float theta_extrap = - (float) strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair) * powf(theta_scale, (float) pair); float c, s; - strata::kernels::rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, - pair, c, s); + if (!(TAB && strata::kernels::rope_tab_cs(rt, strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair), pair, c, + s))) { + const float theta_extrap = + (float) strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair) * powf(theta_scale, (float) pair); + strata::kernels::rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, + pair, c, s); + } const float a = p[pair], b = p[pair + 32]; p[pair] = a * c - b * s; p[pair + 32] = a * s + b * c; @@ -608,9 +650,13 @@ __global__ void round_f16_kernel(const float* __restrict__ x, float* __restrict_ for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) y[i] = __half2float(__float2half_rn(x[i])); } -__global__ void to_bf16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, int64_t n) { - for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) - y[i] = bf(x[i]); +__global__ void to_bf16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, uint16_t* __restrict__ ylo, + int64_t n) { + for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) { + const uint16_t h = bf(x[i]); + y[i] = h; + if (ylo) ylo[i] = bf_lo(x[i], h); + } } } // namespace @@ -634,39 +680,41 @@ void round_f16(const float* x, float* y, int64_t n, void* stream) { round_f16_kernel<<<(unsigned) ((n + 255) / 256 < 4096 ? (n + 255) / 256 : 4096), 256, 0, (cudaStream_t) stream>>>(x, y, n); check("round_f16"); } -void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream) { +void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream, uint16_t* ylo) { if (n <= 0) return; - to_bf16_kernel<<<(unsigned) ((n + 255) / 256 < 4096 ? (n + 255) / 256 : 4096), 256, 0, (cudaStream_t) stream>>>(x, y, n); + to_bf16_kernel<<<(unsigned) ((n + 255) / 256 < 4096 ? (n + 255) / 256 : 4096), 256, 0, (cudaStream_t) stream>>>(x, y, ylo, n); check("to_bf16"); } -void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream) { - gr_norm_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, xn, xn16); +void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream, + uint16_t* xn16_lo) { + gr_norm_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, xn, xn16, xn16_lo); check("gr_norm"); } -void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream) { - gr_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, rs, xn16); +void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream, + uint16_t* xn16_lo) { + gr_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, rs, xn16, xn16_lo); check("gr_norm_rs"); } void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16, - int64_t T, void* stream, uint16_t* mixed_h) { + int64_t T, void* stream, uint16_t* mixed_h, uint16_t* mixed16_lo) { gr_mix_r_kernel<<>>(R, rs, w_norm, gated, mixed, mixed16, T, - mixed_h); + mixed_h, mixed16_lo); check("gr_mix_r"); } void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps, - float* rs, uint16_t* xn16, int64_t T, void* stream) { + float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo) { gr_write_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, bo, inj, inj_ld, w_norm_next, eps, - rs, xn16); + rs, xn16, xn16_lo); check("gr_write_norm_rs"); } -void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream) { - gr_silu_kernel<<>>(lo, lo16, T * LR); +void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo) { + gr_silu_kernel<<>>(lo, lo16, lo16_lo, T * LR); check("gr_silu"); } void gr_mix(const float* xn, const float* gated, float* mixed, uint16_t* mixed16, int64_t T, void* stream, - uint16_t* mixed_h) { - gr_mix_kernel<<>>(xn, gated, mixed, mixed16, T, mixed_h); + uint16_t* mixed_h, uint16_t* mixed16_lo) { + gr_mix_kernel<<>>(xn, gated, mixed, mixed16, T, mixed_h, mixed16_lo); check("gr_mix"); } void gr_write(float* R, const float* bo, const float* inj, int64_t inj_ld, int64_t T, void* stream) { @@ -771,9 +819,15 @@ void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t p } const float theta_scale = powf((float) scaling.freq_base, -2.0f / 64.0f); const strata::kernels::RopeKernelArgs k = scaling.kernel_args(64); // none: the identity constants - rope_kernel<<<(unsigned) (T * heads), 32, 0, (cudaStream_t) stream>>>( - x, heads, dim, ld, pos0, theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, - strata::kernels::mrope_table()); + const strata::kernels::RopeTab rt = strata::kernels::rope_table_for(scaling); + if (rt.cos != nullptr) + rope_kernel<<<(unsigned) (T * heads), 32, 0, (cudaStream_t) stream>>>( + x, heads, dim, ld, pos0, theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, + strata::kernels::mrope_table(), rt); + else + rope_kernel<<<(unsigned) (T * heads), 32, 0, (cudaStream_t) stream>>>( + x, heads, dim, ld, pos0, theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, + strata::kernels::mrope_table(), rt); check("rope"); } void split_q(const float* q_full, float* q, int64_t T, void* stream) { diff --git a/src/prefill/moe_mmq.cu b/src/prefill/moe_mmq.cu index 27b52ad5..f1e39874 100644 --- a/src/prefill/moe_mmq.cu +++ b/src/prefill/moe_mmq.cu @@ -91,7 +91,11 @@ bool built() { return true; } bool supported(int t) { switch ((ggml_type) t) { - case GGML_TYPE_Q2_0: case GGML_TYPE_IQ2_XXS: case GGML_TYPE_IQ2_XS: case GGML_TYPE_IQ2_S: + case GGML_TYPE_Q2_0: +#ifdef STRATA_ORCA_Q4KS_MMQ + case GGML_TYPE_Q5_0: // #296 (Q4_K and Q5_1: STRATA_MMQ_KQUANTS) +#endif + case GGML_TYPE_IQ2_XXS: case GGML_TYPE_IQ2_XS: case GGML_TYPE_IQ2_S: case GGML_TYPE_IQ3_XXS: case GGML_TYPE_IQ3_S: case GGML_TYPE_IQ4_NL: case GGML_TYPE_IQ4_XS: case GGML_TYPE_Q8_0: // the draft layer's dense matrices (E-9) #ifdef STRATA_MMQ_KQUANTS @@ -137,6 +141,9 @@ void Context::run(const Product& p, void* stream) { auto& ctx = *(ggml_backend_cuda_context*) ctx_; const cudaStream_t s = (cudaStream_t) stream; switch (t) { +#ifdef STRATA_ORCA_Q4KS_MMQ + case GGML_TYPE_Q5_0: mul_mat_q_case(ctx, a, s); break; +#endif case GGML_TYPE_Q2_0: mul_mat_q_case(ctx, a, s); break; case GGML_TYPE_IQ2_XXS: mul_mat_q_case(ctx, a, s); break; case GGML_TYPE_IQ2_XS: mul_mat_q_case(ctx, a, s); break; diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 017aa9f6..64e9f4af 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -104,6 +104,20 @@ inline int ring_slots(size_t T) { return (int64_t) T >= stream_all_min() ? big : STAGE; } constexpr int DQ = 2; // dequantized-expert ring (FP16 gate/up + down) +// The BF16-weight projections (hyper-connection, SSM alpha/beta, indexer, router, shared gate, PLE key/value) take +// BF16 activations here and FP32 ones in decode. STRATA_PREFILL_BF16X2=1 adds each activation's BF16 remainder as a +// second GEMM (Y = W.hi + W.lo, ~16 mantissa bits): a router that picks its top 10 from the same x decode would. +// 2 = all but the hyper-connection's; 1 = the hyper-connection's too (its activations are 10240 wide and its up +// projection writes as much: slower); 0 (the default: opt-in, it changes the prompt path's numbers) = off. +inline int bf16x2_mode() { + static const int v = [] { + const char* e = std::getenv("STRATA_PREFILL_BF16X2"); + return e != nullptr ? std::atoi(e) : 0; + }(); + return v; +} +inline bool bf16x2() { return bf16x2_mode() != 0; } +inline bool bf16x2_hc() { return bf16x2_mode() == 1; } // F-1: STRATA_GR_UNFUSED=1 keeps the FP32 copy of the normalized rows (gr_norm + gr_mix), the A/B arm inline bool gr_unfused() { @@ -288,6 +302,7 @@ struct Prefill::Impl { uint16_t *xn16 = nullptr, *lo16 = nullptr; float* mixed = nullptr; uint16_t *mixed_bf = nullptr, *mixed_h = nullptr; + uint16_t *xn16_lo = nullptr, *lo16_lo = nullptr, *mixed_bf_lo = nullptr; // bf16x2(): the BF16 GEMMs' low parts float* bo = nullptr; // GDN float *qkv = nullptr, *z = nullptr, *ab = nullptr, *gate = nullptr, *beta = nullptr, *hbuf = nullptr, *y = nullptr; @@ -621,6 +636,8 @@ bool Prefill::carve(size_t T, void* alloc) { m.gated = o.take(T * D, ok); m.inj = o.take(T * HC, ok); m.mixed = o.take(T * N, ok); m.mixed_bf = o.take(T * N, ok); m.mixed_h = o.take(T * N, ok); m.bo = o.take(T * N, ok); + if (bf16x2_hc()) { m.xn16_lo = o.take(T * D, ok); m.lo16_lo = o.take(T * LR, ok); } + if (bf16x2()) m.mixed_bf_lo = o.take(T * N, ok); m.steps_dev = o.take(T * strata::kernels::kStepCount, ok); strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; @@ -843,9 +860,11 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t proj(mixed, mixed_h, w_v, Vc, nb, KV, Nn, 0); rms_rows(Kc, w_kn, nb * g.n_head_kv, g.head_dim, g.head_dim, EPS, m.cs); rope(Kc, nb, g.n_head_kv, g.head_dim, KV, c0, strata::kernels::rope_scaling(), m.cs); - if (st.kv_q4) { + if (st.kv_rot) { // rotated as the drafter's own decode stores them (mtp.cpp) strata::kernels::fwht256_inplace_cuda(Kc, nb * g.n_head_kv, m.cs); strata::kernels::fwht256_inplace_cuda(Vc, nb * g.n_head_kv, m.cs); + } + if (st.kv_q4) { strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, c0, nb, Kc, Vc, s, m.cs, &st.host); } else { kv_append(Kc, Vc, nb, c0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool, @@ -874,6 +893,8 @@ uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::Session auto f = [&](size_t n) { o.take(n, ok); }; f(T * N); f(T * D); f(T * D); o.take(T * D, ok); f(T * LR); o.take(T * LR, ok); f(T * D); f(T * HC); f(T * N); o.take(T * N, ok); o.take(T * N, ok); f(T * N); + if (bf16x2_hc()) { o.take(T * D, ok); o.take(T * LR, ok); } + if (bf16x2()) o.take(T * N, ok); o.take(T * strata::kernels::kStepCount, ok); strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; @@ -912,9 +933,10 @@ bool native_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y return true; } bool bf16_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name, - std::string& err, int64_t ldy = 0) { + std::string& err, int64_t ldy = 0, const uint16_t* X_lo = nullptr) { if (w->kind != core::WeightKind::Bf16InF32 || !w->data) { err = "prefill: " + name + " is not a resident BF16 tensor"; return false; } gm.bf16(X, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy); + if (X_lo) gm.bf16(X_lo, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 1.0f); return true; } @@ -1249,7 +1271,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e const auto tp = Clock::now(); const strata::kernels::PleWeights& pw = ss.ple.w; constexpr int64_t HD = strata::kernels::NG_HC_DIM; - const uint64_t per_token = (uint64_t) (3 * HD + N + 4) * 4 + (uint64_t) N * 2 + 4096; + const uint64_t per_token = (uint64_t) (3 * HD + N + 4) * 4 + (uint64_t) N * (bf16x2() ? 4 : 2) + 4096; const int64_t SB = std::min(T, (int64_t) (m.region_bytes / per_token)); for (int64_t s0 = 0; s0 < T; s0 += SB) { const int64_t nb = std::min(SB, T - s0); @@ -1261,16 +1283,19 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e float* val = carve_f((size_t) nb * N); float* gate = carve_f((size_t) nb * 4); uint16_t* e16 = (uint16_t*) carve_f((size_t) nb * N / 2); + uint16_t* e16_lo = bf16x2() ? (uint16_t*) carve_f((size_t) nb * N / 2) : nullptr; const float* emb = m.ple_emb + s0 * N; if (pw.key_bf16 != nullptr) { - to_bf16(emb, e16, nb * N, m.cs); + to_bf16(emb, e16, nb * N, m.cs, e16_lo); m.gemm.bf16(e16, pw.key_bf16, key, nb, HD, N); + if (e16_lo) m.gemm.bf16(e16_lo, pw.key_bf16, key, nb, HD, N, 0, 1.0f); } else { to_f16(emb, e16, nb * N, m.cs); m.gemm.native(e16, pw.key_native_type, pw.key_native_data, key, nb, HD, N); - to_bf16(emb, e16, nb * N, m.cs); + to_bf16(emb, e16, nb * N, m.cs, e16_lo); } m.gemm.bf16(e16, pw.value_bf16, val, nb, N, N); + if (e16_lo) m.gemm.bf16(e16_lo, pw.value_bf16, val, nb, N, N, 0, 1.0f); try { strata::kernels::native_ple_postops_batch(key, m.R + s0 * D, val, ss.ple.hist, pw, qn, gated, gate, (int) nb, m.cs); @@ -1301,15 +1326,16 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e *wu = need(v, su.c_str(), err), *wi = need(v, si.c_str(), err); if (!wn || !wd || !wu || !wi) return false; pt.mark(kPfHc, cs); - if (gr_unfused()) gr_norm(m.R, (const float*) wn->data, EPS, m.xn, m.xn16, T, m.cs); - else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs); + if (gr_unfused()) gr_norm(m.R, (const float*) wn->data, EPS, m.xn, m.xn16, T, m.cs, m.xn16_lo); + else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs, m.xn16_lo); normed = false; - if (!bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err)) return false; - gr_silu(m.lo, m.lo16, T, m.cs); - if (!bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err)) return false; - if (!bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err)) return false; - if (gr_unfused()) gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h); - else gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h); + if (!bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo)) return false; + gr_silu(m.lo, m.lo16, T, m.cs, m.lo16_lo); + if (!bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo)) return false; + if (!bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo)) return false; + if (gr_unfused()) gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, m.mixed_bf_lo); + else gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, + m.mixed_bf_lo); if (half == 0 && !core::is_qsa_layer(g, l)) { // ======================= GDN ======================= @@ -1324,8 +1350,8 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; if (!native_proj(m.gemm, wqkv, m.mixed_h, m.qkv, T, v.name("attn_qkv.weight"), err)) return false; if (!native_proj(m.gemm, wg, m.mixed_h, m.z, T, v.name("attn_gate.weight"), err)) return false; - if (!bf16_proj(m.gemm, wa, m.mixed_bf, m.ab, T, v.name("ssm_alpha.weight"), err, 2 * HV)) return false; - if (!bf16_proj(m.gemm, wb, m.mixed_bf, m.ab + HV, T, v.name("ssm_beta.weight"), err, 2 * HV)) return false; + if (!bf16_proj(m.gemm, wa, m.mixed_bf, m.ab, T, v.name("ssm_alpha.weight"), err, 2 * HV, m.mixed_bf_lo)) return false; + if (!bf16_proj(m.gemm, wb, m.mixed_bf, m.ab + HV, T, v.name("ssm_beta.weight"), err, 2 * HV, m.mixed_bf_lo)) return false; pt.mark(kPfGdnConv, cs); // "gdn" is the projections in; the rest on their own lines gdn_gates(m.ab, (const float*) wdt->data, (const float*) wsa->data, m.gate, m.beta, T, m.cs); gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, m.cs); @@ -1349,8 +1375,8 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e if (!native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false; if (!native_proj(m.gemm, wv, m.mixed_h, m.Vc, T, v.name("attn_v.weight"), err)) return false; if (!native_proj(m.gemm, wq, m.mixed_h, m.Qf, T, v.name("attn_q.weight"), err)) return false; - if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err)) return false; - if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err)) return false; + if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err, 0, m.mixed_bf_lo)) return false; + if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err, 0, m.mixed_bf_lo)) return false; rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, m.cs); rope(m.Kc, T, 2, 256, 512, p0, strata::kernels::rope_scaling(), m.cs); // KV streaming: this layer's cells [0, p0) come in from the host copy to the staging pool, and the @@ -1370,20 +1396,23 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e staged ? &m.stage : nullptr); strata::kernels::kv_append_q4(st.v_q4, st.v_q4, st.page_table, p0, T, m.Vc, m.Vc, s, m.cs, nullptr, staged ? &m.stage : nullptr); - } else if (st.kv_q4) { // Q4_0 KV (kv_q4.hpp): rotated K and V, the queries below too, the output back - strata::kernels::fwht256_inplace_cuda(m.Kc, T * 2, m.cs); - strata::kernels::fwht256_inplace_cuda(m.Vc, T * 2, m.cs); - strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, p0, T, m.Kc, m.Vc, s, m.cs, - &st.host, staged ? &m.stage : nullptr); } else { - kv_append(m.Kc, m.Vc, T, p0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool, - st.kv_int8 ? nullptr : st.v_pool, st.k_q, st.v_q, st.k_scale, st.v_scale, m.cs, - &st.host, staged ? &m.stage : nullptr); + if (st.kv_rot) { // rotated K and V (kv_q4.hpp), the queries below too, the output back + strata::kernels::fwht256_inplace_cuda(m.Kc, T * 2, m.cs); + strata::kernels::fwht256_inplace_cuda(m.Vc, T * 2, m.cs); + } + if (st.kv_q4) + strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, p0, T, m.Kc, m.Vc, s, m.cs, + &st.host, staged ? &m.stage : nullptr); + else + kv_append(m.Kc, m.Vc, T, p0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool, + st.kv_int8 ? nullptr : st.v_pool, st.k_q, st.v_q, st.k_scale, st.v_scale, m.cs, + &st.host, staged ? &m.stage : nullptr); } split_q(m.Qf, m.q, T, m.cs); rms_rows(m.q, (const float*) wqn->data, T * 24, 256, 256, EPS, m.cs); rope(m.q, T, 24, 256, 6144, p0, strata::kernels::rope_scaling(), m.cs); - if (st.kv_q4) strata::kernels::fwht256_inplace_cuda(m.q, T * 24, m.cs); + if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(m.q, T * 24, m.cs); rms_rows(m.q_idx, (const float*) wiqn->data, T * 4, 128, 128, EPS, m.cs); rope(m.q_idx, T, 4, 128, 512, p0, strata::kernels::rope_scaling(), m.cs); // the indexer appends, token by token; then scores + selection for many queries at once: @@ -1524,7 +1553,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e m.steps_dev + t0 * strata::kernels::kStepCount, m.cap, s, m.attn_scratch, m.attn + t0 * ZV, nb, m.cs); } - if (st.kv_q4 || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(m.attn, T * 24, m.cs); + if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(m.attn, T * 24, m.cs); pt.mark(kPfQsa, cs); gate_attn(m.attn, m.Qf, m.attn_h, T, m.cs); if (!native_proj(m.gemm, wo, m.attn_h, m.bo, T, v.name("attn_output.weight"), err)) return false; @@ -1538,7 +1567,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e *wsd = need(v, "ffn_down_shexp.weight", err); if (!wr || !wgi || !wsg || !wsu || !wsd) return false; pt.mark(kPfRouter, cs); - if (!bf16_proj(m.gemm, wr, m.mixed_bf, m.logits, T, v.name("ffn_gate_inp.weight"), err)) return false; + if (!bf16_proj(m.gemm, wr, m.mixed_bf, m.logits, T, v.name("ffn_gate_inp.weight"), err, 0, m.mixed_bf_lo)) return false; route(m.logits, m.ids, m.w, T, m.g->n_expert, m.cs); // the shared expert and its scalar gate if (!native_proj(m.gemm, wsg, m.mixed_h, m.sgate, T, v.name("ffn_gate_shexp.weight"), err)) return false; @@ -1547,6 +1576,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e if (!native_proj(m.gemm, wsd, m.sh_h, m.shared, T, v.name("ffn_down_shexp.weight"), err)) return false; if (wgi->kind != core::WeightKind::Bf16InF32) { err = "prefill: shared gate is not BF16"; return false; } m.gemm.bf16(m.mixed_bf, (const uint16_t*) wgi->data, m.sg, T, 1, N); + if (m.mixed_bf_lo) m.gemm.bf16(m.mixed_bf_lo, (const uint16_t*) wgi->data, m.sg, T, 1, N, 0, 1.0f); // group the (token, k) pairs by expert on the host pt.mark(kPfHostGroup, cs); // (the sync below also orders this layer's writes of slot/src/bounds after the previous @@ -1814,7 +1844,8 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e if (!wnn) return false; } if (wnn) { - gr_write_norm_rs(m.R, m.bo, m.inj, HC, (const float*) wnn->data, EPS, m.grs, m.xn16, T, m.cs); + gr_write_norm_rs(m.R, m.bo, m.inj, HC, (const float*) wnn->data, EPS, m.grs, m.xn16, T, m.cs, + m.xn16_lo); normed = true; } else { gr_write(m.R, m.bo, m.inj, HC, T, m.cs); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 79da91bb..7f1e3e96 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -18,6 +18,7 @@ #include "strata/core/expert_cache.hpp" #include "strata/core/conversation_snapshot.hpp" #include "strata/core/conversation_memory.hpp" +#include "strata/core/coupled_draft.hpp" #include "strata/core/expert_source.hpp" #include "strata/core/pinned.hpp" #include "strata/core/remote_experts.hpp" @@ -55,6 +56,8 @@ #include "strata/spec/suffix_drafter.hpp" #include "strata/kernels/cvec.hpp" #include "strata/core/progress.hpp" +#include "strata/core/device.hpp" +#include "strata/core/emulate.hpp" #ifndef NOMINMAX #define NOMINMAX // gguf_reader.hpp includes windows.h #endif @@ -213,6 +216,8 @@ struct Options { /// combination recorded in bench/results/2026-09-23-attention-ple plus the native indexer, and never the /// <=256-token attention adapter. It becomes the default once P0 shows it is not slower. std::string native_preset; + /// The token embedding from this GGUF instead of --native's (tools/embd_bf16_pack.py: BF16 as shipped) + std::string embd_gguf; /// Plan v0.3 P2: how the n-gram table is read. Direct (default) = unbuffered SSD reads, table never in RAM. std::string ple_io = "direct"; int64_t ple_row_cache = 1 << 20; ///< bounded row cache (rows of 90 B); 0 disables @@ -251,10 +256,13 @@ struct Options { bool graph_only = false; bool gpu_only_full = false; ///< R0.3: pre + post + head, the true per-token GPU floor int pool_workers = 0; ///< R2.2: 0 = "all physical cores minus the host's"; >0 overrides + /// #272: the pool's core layout; `all` (the default) is the layout it always had, auto / p-cores are opt-in + strata::kernels::cpu::PoolAffinity pool_affinity = strata::kernels::cpu::PoolAffinity::All; /// R2.2's first half, as an A/B arm. **ON by default**, because the measurement that justifies it is the /// pool's own drain: 33.7 GB/s against 5/6 x 44.14 = 36.8 for five workers, on a machine whose sixth core /// is reserved for a host thread that has nothing to do while the drain runs. bool no_host_worker = false; + bool coupled_draft = strata::core::coupled_draft_env(); ///< Coupled draft sampling for MTP drafter under sampling bool mmap_experts = false; ///< R2.1: opt OUT of the resident arena, back to MapViewOfFile std::string shared_expert_arena; ///< Linux: optional file backing for the resident arena shared by processes bool resident_cpu_experts = false; ///< mmap-backed static-cache misses copied into ordinary RAM @@ -318,6 +326,9 @@ struct Options { /// `--prefill auto`: the largest chunk (up to 8192) whose buffers the expert cache can lend. Every expert a chunk /// routes to is streamed once per chunk, so a bigger chunk streams fewer bytes per token (the "ubatch" effect). bool prefill_auto = false; + /// #282, opt-in: the largest chunk `--prefill auto` may take - 8192 by default; `--prefill auto:16384` or + /// `auto:32768` (or STRATA_PREFILL_AUTO_MAX) lets it go further, never past the context + int64_t prefill_auto_max = 8192; bool no_split_rows = false; ///< plan v0.3 P4 A/B: one whole expert per pool thread /// Plan v0.3 P5: the prompt path borrows the top expert-cache slots for its buffers and refills them after /// the prompt (default); `--no-prefill-borrow` reserves the buffers' VRAM for the whole session instead. @@ -449,6 +460,8 @@ void usage() { " indexer, RoPE, PLE postops, and the CPU q8_0 contract unless the\n" " expert cache is on. Individual --native-* flags stay for A/B.\n" " --native-head-gguf PATH native Q5_K head from model shard 1; requires --stream-token\n" + " --embd-gguf PATH the token embedding from this GGUF instead of --native's (tools/embd_bf16_pack.py:\n" + " BF16 as the checkpoint ships it; mapped host memory, no VRAM)\n" " --native-dense-gguf PATH native GDN/QSA/shared projections; repeat for each source model shard\n" " --expert-cache-cpu-order experimental GPU expert reduction matching CPU order\n" " --max-new N tokens to generate (default 16)\n" @@ -497,7 +510,8 @@ void usage() { " --no-token-graph A/B: two graphs per layer (the host launches each) instead of one per token\n" " --no-fused-gr A/B: the six-kernel hyper-connection read and a separate write (native)\n" " --prefill CHUNK batched prompt processing in chunks of CHUNK tokens (needs --native); auto =\n" - " the largest chunk up to 8192 whose buffers the expert cache can lend\n" + " the largest chunk up to 8192 whose buffers the expert cache can lend;\n" + " auto:16384 / auto:32768 (or STRATA_PREFILL_AUTO_MAX) allow bigger ones\n" " --no-pool skip the CPU expert pool (the GPU-only floor)\n" " --sync-every-layer debug: synchronise after every layer\n" " --ple-gguf PATH the n-gram/PLE shard. WITHOUT IT LAYER 1's PLE IS SILENTLY SKIPPED,\n" @@ -538,8 +552,14 @@ void usage() { " pool is six threads on six cores instead of five plus an idle core;\n" " this flag restores the five-worker form for comparison on `pool phases`.\n" " --pool-workers N R2.2: CPU expert pool worker count. Default 0 = every physical core\n" - " except the one the host loop spins on. A sweep is how the pool's\n" + " except the one the host loop spins on (with --pool-affinity auto or\n" + " p-cores on a hybrid CPU: P-cores minus 1). A sweep is how the pool's\n" " deviation from `cpu_s2` is attributed.\n" + " --pool-affinity MODE Worker CPU affinity: all (default: one worker per physical core, as\n" + " always), auto (hybrid CPUs: P-cores first, then their SMT siblings,\n" + " then E-cores) or p-cores (P-cores and their siblings only).\n" + " --coupled-draft enable coupled draft sampling for MTP drafter under sampling (STRATA_SPEC_COUPLED)\n" + " --no-coupled-draft disable coupled draft sampling (propose argmax drafts)\n" " --mmap-experts R2.1: opt OUT of the resident expert arena, back to MapViewOfFile.\n" " The A/B arm: the mmap's rate depends on the OS page cache holding\n" " 34 GB, and measured 71.97 vs 34.78 ms/token cold vs warm.\n" @@ -1058,6 +1078,7 @@ int main(int argc, char** argv) { else if (a == "--cpu-oracle-q8-0") o.cpu_oracle_q8_0 = true; else if (a == "--native") o.native_preset = next("--native"); else if (a == "--native-head-gguf") o.native_head_gguf = next("--native-head-gguf"); + else if (a == "--embd-gguf") o.embd_gguf = next("--embd-gguf"); else if (a == "--native-dense-gguf") o.native_dense_gguf.push_back(next("--native-dense-gguf")); else if (a == "--no-capture") o.no_capture = true; else if (a == "--no-pool") o.no_pool = true; @@ -1066,8 +1087,20 @@ int main(int argc, char** argv) { else if (a == "--graph-only") o.graph_only = true; else if (a == "--gpu-only-full") o.gpu_only_full = true; else if (a == "--pool-workers") o.pool_workers = std::atoi(next("--pool-workers")); + else if (a == "--pool-affinity") { + const std::string v = next("--pool-affinity"); + if (v == "auto") o.pool_affinity = strata::kernels::cpu::PoolAffinity::Auto; + else if (v == "p-cores" || v == "pcores") o.pool_affinity = strata::kernels::cpu::PoolAffinity::PCores; + else if (v == "all") o.pool_affinity = strata::kernels::cpu::PoolAffinity::All; + else { + std::fprintf(stderr, "strata generate: unknown --pool-affinity value '%s' (expected auto, p-cores, or all)\n", v.c_str()); + return 2; + } + } else if (a == "--no-host-worker") o.no_host_worker = true; else if (a == "--no-ple-prefetch") o.no_ple_prefetch = true; + else if (a == "--coupled-draft") o.coupled_draft = true; + else if (a == "--no-coupled-draft") o.coupled_draft = false; else parsed = false; // The chain continues here in a second statement: one chain of 120+ `else if` passed MSVC's limit of 128 // nested blocks (C1061). The order of the tests and what each does are unchanged. @@ -1084,8 +1117,13 @@ int main(int argc, char** argv) { else if (a == "--vram-reserve-mib") o.vram_reserve_mib = std::atoi(next("--vram-reserve-mib")); else if (a == "--prefill") { const std::string v = next("--prefill"); - o.prefill_auto = v == "auto"; - o.prefill_chunk = o.prefill_auto ? 8192 : std::atoll(v.c_str()); + o.prefill_auto = v == "auto" || v.rfind("auto:", 0) == 0; + // #282: auto:N (N = 16384 or 32768) or STRATA_PREFILL_AUTO_MAX lets auto take chunks above 8192 + const char* env_max = std::getenv("STRATA_PREFILL_AUTO_MAX"); + const long long want_max = v.rfind("auto:", 0) == 0 ? std::atoll(v.c_str() + 5) + : (o.prefill_auto && env_max != nullptr ? std::atoll(env_max) : 8192); + o.prefill_auto_max = want_max >= 32768 ? 32768 : want_max >= 16384 ? 16384 : 8192; + o.prefill_chunk = o.prefill_auto ? o.prefill_auto_max : std::atoll(v.c_str()); } else if (a == "--no-split-rows") o.no_split_rows = true; else if (a == "--no-prefill-borrow") o.no_prefill_borrow = true; @@ -1214,6 +1252,7 @@ int main(int argc, char** argv) { } } } + strata::core::set_coupled_draft(o.coupled_draft); if (o.serve && o.conversation_cache_mib > 0 && (o.prompt_cache == 0 || o.conversation_cache_slots == 0)) std::fprintf(stderr, "strata serve: warning: conversation caching is disabled by %s\n", o.prompt_cache == 0 ? "--prompt-cache 0" : "--conversation-cache-slots 0"); @@ -1420,6 +1459,12 @@ int main(int argc, char** argv) { } strata::core::qsa_set_kv_int8(o.kv == "int8"); strata::core::qsa_set_kv_q4(o.kv == "q4_0"); // PR #21: 4-bit codes after a Hadamard rotation (kv_q4.hpp) + // STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation --kv q4_0 already uses. Opt-in: first-token KL to + // fp16 K/V improved on an NVFP4 pack (0.0066 -> 0.0051) but not on IQ2_XS (0.0022 -> 0.0054) + const char* kv_rot = std::getenv("STRATA_KV_ROT"); + strata::core::qsa_set_kv_int8_rotate(kv_rot != nullptr && kv_rot[0] == '1'); + if (kv_rot != nullptr && kv_rot[0] == '1' && o.kv == "int8") + std::fprintf(stderr, "strata generate: STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation (opt-in)\n"); strata::core::qsa_set_kv_hybrid(o.kv == "k8v4"); // K8V4: INT8 K + rotated Q4_0 V, 816 B/cell if (o.kv_resident < 0) { std::fprintf(stderr, "strata generate: --kv-resident must be >= 0\n"); @@ -1469,7 +1514,14 @@ int main(int argc, char** argv) { // every shard of the model (-0000N-of-0000M.gguf beside --native), then the PLE shard: a split // may put any layer in any shard (Swift's GGUFs: layers 13-47 in shard 2, the PLE table in shard 1) o.native_dense_gguf = o.native_shards; - if (std::find(o.native_dense_gguf.begin(), o.native_dense_gguf.end(), o.ple_gguf) == o.native_dense_gguf.end()) + // a PLE-only table (tools/ple_fp8_pack.py: architecture strata-ple) holds no projections + bool ple_only = false; + try { + strata::GgufFile pg(o.ple_gguf); + if (const strata::MetaValue* v = pg.get("general.architecture")) ple_only = v->s == "strata-ple"; + } catch (const std::exception&) {} + if (!ple_only && + std::find(o.native_dense_gguf.begin(), o.native_dense_gguf.end(), o.ple_gguf) == o.native_dense_gguf.end()) o.native_dense_gguf.push_back(o.ple_gguf); } // Plan v0.3 (24 Sep): the CPU experts stay on the VNNI kernel. The llama.cpp-CPU-exact q8_0 contract @@ -1788,15 +1840,16 @@ int main(int argc, char** argv) { return 2; } const strata::core::ModelGeometry g0; - if (!native_embed.load(o.native_shards, g0.n_embd, 248320, err)) { + if (!native_embed.load(o.embd_gguf.empty() ? o.native_shards : std::vector{o.embd_gguf}, g0.n_embd, + 248320, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } strata::core::set_native_embed(&native_embed); std::fprintf(stderr, "strata generate: native pack: %s experts (largest blob %.2f MB), token embedding " - "type %d in mapped host memory (%.0f MiB)\n", + "%s in mapped host memory (%.0f MiB)\n", o.pack.c_str(), (double) strata::kernels::cpu::expert_layout().max_blob / 1e6, - native_embed.type(), (double) native_embed.bytes() / 1048576.0); + strata::ggml_type_name((uint32_t) native_embed.type()), (double) native_embed.bytes() / 1048576.0); } // Plan v0.3 P1: tensors served in native form are not also loaded in canonical form (~2.7 GB of VRAM back // to the expert cache with --native). `--keep-canonical` loads both, as before. @@ -1965,6 +2018,17 @@ int main(int argc, char** argv) { pio.max_inflight = (uint32_t) o.ple_inflight; pio.cache_rows = (uint64_t) o.ple_row_cache; pio.io_thread = !o.ple_sync_submit; + // Keep the SSD awake while rows are being asked for (PleReader::set_keepalive): some SSDs stall the first + // reads 50-150 ms after ~250 ms without a command. STRATA_SSD_KEEPALIVE = ms without a read before one + // page is read anyway (default 100, 0 = off), STRATA_SSD_KEEPALIVE_WINDOW = seconds after the last row + // request that this goes on (default 60; then the SSD may sleep until the next request). + { + const char* ka = std::getenv("STRATA_SSD_KEEPALIVE"); + const char* kw = std::getenv("STRATA_SSD_KEEPALIVE_WINDOW"); + pio.keepalive_ms = ka != nullptr && *ka ? std::clamp(std::atof(ka), 0.0, 10000.0) : 100.0; + pio.keepalive_window_s = kw != nullptr && *kw ? std::clamp(std::atof(kw), 1.0, 86400.0) : 60.0; + if (pio.mode != strata::kernels::PleIo::Direct || !pio.io_thread) pio.keepalive_ms = 0; + } if (!ple_table.open(o.ple_gguf, err, pio)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; @@ -1973,6 +2037,12 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: PLE table %s (--ple-io ram) in %.1f s\n", ple_table.locked() ? "locked in RAM" : "loaded (not locked)", std::chrono::duration(Clock::now() - tpl).count()); + if (pio.keepalive_ms > 0) + std::fprintf(stderr, "strata generate: the SSD is kept awake while rows are read: one page of the table after " + "%.0f ms without a read, until %.0f s after the last request " + "(STRATA_SSD_KEEPALIVE=0 turns it off)\n", pio.keepalive_ms, pio.keepalive_window_s); + else if (pio.mode == strata::kernels::PleIo::Direct) + std::fprintf(stderr, "strata generate: SSD keep-alive off: the SSD may fall asleep between reads\n"); const strata::core::WeightRef* wk = wt.find("blk.1.ple_key.weight"); const strata::core::WeightRef* wv = wt.find("blk.1.ple_value.weight"); const strata::core::WeightRef* wnk = wt.find("blk.1.ple_norm_key.weight"); @@ -2096,6 +2166,7 @@ int main(int argc, char** argv) { } } } + strata::core::Verifier::set_commit_async(!multi_gpu); // see Verifier::set_commit_async // ---- layer split across GPUs: each later stage's own copy of the dense weights, its session and (the last) the // head, made on its device before the host arena is mapped (as the drafter below, for the same WDDM reason) std::vector> stages; @@ -2461,6 +2532,27 @@ int main(int argc, char** argv) { // CUDA error left set by the failed `cudaHostRegister` and read later by `gr_read`'s launch check. See the // note in `pinned.cu`. strata::core::FileExpertSource src; + { // the card, and whether this build has code for it (a binary built for other GPUs fails at its first kernel + // otherwise, after the whole expert arena has loaded) - before the arena starts loading + int dev = 0; + cudaDeviceProp p{}; + const bool named = cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess; + if (!named) cudaGetLastError(); + const char* name = named && p.name[0] ? p.name : "(an unnamed GPU)"; +#if defined(STRATA_USE_HIP) + std::fprintf(stderr, "strata generate: GPU %d: %s (%s)\n", dev, name, named ? p.gcnArchName : "?"); +#else + std::fprintf(stderr, "strata generate: GPU %d: %s, compute capability %d.%d%s\n", dev, name, + strata::cc_major_of(p.major), strata::cc_minor_of(p.minor), + strata::emulated_cc() ? " (STRATA_EMULATE_CC: a test mode, the card is emulated)" : ""); +#endif + const std::string e = strata::core::device_code_error(); + if (!e.empty()) { + std::fprintf(stderr, "strata generate: this engine has no code for %s (sm_%d%d): %s - rebuild it for this " + "card (setup does: START-HERE.bat --setup)\n", name, p.major, p.minor, e.c_str()); + return 1; + } + } strata::core::ArenaExpertSource arena_src; strata::core::ExpertSource* srcp = nullptr; if (o.mmap_experts) { @@ -2522,7 +2614,13 @@ int main(int argc, char** argv) { #endif srcp = &arena_src; } - strata::kernels::cpu::ExpertPool pool(o.pool_workers, /*pin=*/true, /*host_works=*/!o.no_host_worker); + strata::kernels::cpu::ExpertPool pool(o.pool_workers, /*pin=*/true, /*host_works=*/!o.no_host_worker, o.pool_affinity); + if (pool.is_hybrid() && pool.affinity() != strata::kernels::cpu::PoolAffinity::All) { + const char* aff_str = pool.affinity() == strata::kernels::cpu::PoolAffinity::PCores ? "p-cores" : + pool.affinity() == strata::kernels::cpu::PoolAffinity::All ? "all" : "auto"; + std::fprintf(stderr, "strata generate: hybrid CPU detected (%d P-cores / %d threads, %d E-cores), pool workers: %d, affinity: %s\n", + pool.p_cores(), pool.p_threads(), pool.e_cores(), pool.workers(), aff_str); + } if (o.no_ple_prefetch) strata::kernels::ple_prefetch_enable(false); // ---- R4's slot storage. Allocated AFTER the weights and the session, so `cudaMemGetInfo` inside `open` // sees the memory this process actually has left rather than the card's idle figure - and refuses with both @@ -3625,10 +3723,15 @@ int main(int argc, char** argv) { : (int64_t) (strata::prefill::Prefill::pinned_share() >= 0.9 ? 90 : 85); }(); auto plan_lend = [&](int64_t& chunk) -> int64_t { - static constexpr int64_t kAutoChunks[] = {8192, 6144, 4096, 3072, 2048, 1024, 512, 256}; + // 32768 and 16384 (#282, opt-in: --prefill auto:32768): a 32K prompt with IQ2_XS (RTX 5090, 64K context) + // read at 5,624 tok/s in 8192-token chunks and 6,465 in one 32768 chunk (40K -> 18K experts streamed; an + // NVFP4 pack at 262K: 3,535 -> 5,201) + static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256}; auto slots_for = lend_slots; if (o.prefill_auto) { for (const int64_t c : kAutoChunks) { + // above 8192: only when asked for, and only when a prompt of the context can use it + if (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue; const int64_t k = slots_for(c); if (k + 128 <= xcache.slots() && k * 100 <= kAutoLendPct * xcache.slots()) { chunk = c; return k; } } @@ -3763,11 +3866,13 @@ int main(int argc, char** argv) { } return true; }; - static constexpr int64_t kAutoChunks[] = {8192, 6144, 4096, 3072, 2048, 1024, 512, 256}; + static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256}; int64_t chunk = 0; if (o.prefill_auto) { - for (const int64_t c : kAutoChunks) + for (const int64_t c : kAutoChunks) { + if (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue; // #282, as plan_lend if (fits(c, true)) { chunk = c; break; } + } } else { for (int64_t c = o.prefill_chunk; c >= 256; c /= 2) if (fits(c, false)) { chunk = c; break; } @@ -4127,11 +4232,12 @@ int main(int argc, char** argv) { estimate = fresh_estimate; err.clear(); } - if (!reuse.kv.empty() && !conversations.can_fit(estimate, held)) { - // Optional growth capacity must not evict useful conversations. - reuse = {}; - estimate = fresh_estimate; - } + // A park carrying its own retained K/V replaces memory the cache + // already held, so capacity is make_room's call - it runs next either + // way, and put()'s accounting still bounds the budget. The with-reuse + // estimate must stay uncapped: it counts the retained buffers' + // capacity and directories, and put() charges that same true size - + // a capped figure would under-evict and overfill the budget. // #342: before make_room evicts oldest-first, the copies of this conversation a turn back go (they hold // nothing the outgoing chain does not, apart from the tail this conversation rewrote) if (const size_t dropped = conversations.drop_superseded(live, live_imgs, checks, cvec_cached)) @@ -4732,6 +4838,13 @@ int main(int argc, char** argv) { return imgs_below(req_imgs, L) == pre_imgs; }; const bool want_cvec = strata::kernels::cvec().loaded() ? req_cvec != 0 : true; + // the last request's final commit may still be running on the verifier's stream (set_commit_async): + // everything below reads, restores or zeroes the session from other streams and the host (the end of the + // last request waited already; this covers a request that ended on an error path) + if (!ver.wait_commit(err)) { + std::printf("ERR %s\n", err.c_str()); + return 1; + } int64_t resume = 0; bool from_live = false; if (o.prompt_cache > 0 && want_cvec == cvec_cached) { @@ -4923,6 +5036,8 @@ int main(int argc, char** argv) { if (!ver.commit(T, e) || !mtp.prefill(ver.final_R_all(), nxt.data(), T, q, e)) return false; q += T; } + // the batched prompt path (other streams), checkpoints and snapshots may follow: the last commit first + if (!ver.wait_commit(e)) return false; const double ms = std::chrono::duration(Clock::now() - pp_t0).count(); std::printf("PP %lld %lld %.0f %.1f\n", (long long) b, (long long) pp_total, ms, ms > 0.0 ? 1000.0 * (double) (b - pp_from) / ms : 0.0); @@ -5281,6 +5396,11 @@ int main(int argc, char** argv) { p += a + 1; } const double decode_ms = std::chrono::duration(Clock::now() - d0).count(); + // the last commit (set_commit_async): the session is complete before anything reads or copies it + if (!ver.wait_commit(err)) { + std::printf("ERR %s\n", err.c_str()); + return 1; + } if (dec_timing && dec_windows > 0) { const DecSnap d1 = dec_snap(); const double w = (double) dec_windows, L = (double) g.n_layers; @@ -6028,6 +6148,16 @@ int main(int argc, char** argv) { if (first_window) { first_window = false; ttft_ms = std::chrono::duration(Clock::now() - t_start).count(); + // Diagnostics: the first window runs the prompt's last token over the state the prompt path left + // (keys, values, recurrent state), so its logits carry whatever that path did. A native pack never + // runs the per-token loop --dump-logits reads; this is where prompt paths can be compared by output. + if (const char* fl = std::getenv("STRATA_DUMP_FIRST_LOGITS")) { + std::vector row((size_t) ver.vocab()); + std::FILE* f = ver.copy_logits(0, row.data()) ? std::fopen(fl, "wb") : nullptr; + if (f == nullptr || std::fwrite(row.data(), sizeof(float), row.size(), f) != row.size()) + std::fprintf(stderr, "strata generate: STRATA_DUMP_FIRST_LOGITS: cannot write %s\n", fl); + if (f) std::fclose(f); + } } // plan v0.3 P6: the adaptive tier's host work (ranking, copy submission) runs on its own thread while the // GPU commits and drafts; it touches only the residency tables, which nothing reads until the next window @@ -6073,6 +6203,11 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: position %lld, %lld tokens, %lld rounds\n", (long long) p, (long long) produced.size(), (long long) rounds); } + // the last commit (set_commit_async) before anything reads the session again + if (!ver.wait_commit(err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } std::printf("%-24s %lld rounds of %d, drafts accepted %lld of %lld (%.3f), %.2f tokens per round\n", "speculation", (long long) rounds, o.spec, (long long) drafts_ok, (long long) drafts_total, drafts_total > 0 ? (double) drafts_ok / (double) drafts_total : 0.0, diff --git a/tools/draft_vocab.py b/tools/draft_vocab.py index e04ea7b0..77fa6b98 100644 --- a/tools/draft_vocab.py +++ b/tools/draft_vocab.py @@ -8,7 +8,7 @@ Chinese drafted almost nothing (#137). This adds whole scripts to a subset: python tools/draft_vocab.py --gguf -00001-of-0000N.gguf --base data/draft_vocab.bin --add cjk \ --out data/draft_vocab.bin ---add takes han, kana, hangul, cjk_punct, or cjk (all four). The base ids keep their order; the added ones follow in +--add takes han, kana, hangul, cjk_punct, cjk (those four) or cyrillic. The base ids keep their order; the added ones follow in id order. --stats prints what a subset holds. """ from __future__ import annotations @@ -26,6 +26,8 @@ SCRIPTS = { "kana": [(0x3040, 0x30FF), (0x31F0, 0x31FF), (0xFF66, 0xFF9F)], "hangul": [(0x1100, 0x11FF), (0x3130, 0x318F), (0xAC00, 0xD7AF)], "cjk_punct": [(0x3000, 0x303F), (0xFF00, 0xFF65), (0xFFA0, 0xFFEF)], + # Ukrainian, Russian, Bulgarian, Serbian...: the shipped subset held 142 of the vocabulary's 18,580 Cyrillic tokens + "cyrillic": [(0x0400, 0x04FF), (0x0500, 0x052F), (0x1C80, 0x1C8F), (0x2DE0, 0x2DFF), (0xA640, 0xA69F)], } GROUPS = {"cjk": ["han", "kana", "hangul", "cjk_punct"]} @@ -52,7 +54,7 @@ def main() -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--gguf", required=True, help="the model's (first) GGUF file: its vocabulary") ap.add_argument("--base", help="the subset to extend (int32 ids)") - ap.add_argument("--add", default="", help="comma list: han, kana, hangul, cjk_punct, cjk") + ap.add_argument("--add", default="", help="comma list: han, kana, hangul, cjk_punct, cjk, cyrillic") ap.add_argument("--out", help="where to write the new subset") ap.add_argument("--stats", action="store_true", help="print what the base (and the new) subset holds") a = ap.parse_args() diff --git a/tools/embd_bf16_pack.py b/tools/embd_bf16_pack.py new file mode 100644 index 00000000..1ed2d642 --- /dev/null +++ b/tools/embd_bf16_pack.py @@ -0,0 +1,87 @@ +"""tools/embd_bf16_pack.py - the token embedding exactly as the checkpoint ships it (BF16), as a GGUF the engine reads. + + python tools/embd_bf16_pack.py --model --out + +nvfp4_convert.py stores token_embd as Q8_0 (0.56% off per value). The engine keeps the table in mapped host memory +and reads one row per token, so BF16 costs 0.6 GB of RAM more and no VRAM; `--embd-gguf` takes it from this file. + +The output is a one-tensor GGUF: `token_embd.weight`, ne = [n_embd, n_vocab], type BF16, the bytes copied straight +out of the safetensors file - nothing decoded or rounded. +""" +import argparse +import json +import pathlib +import struct +import sys + +GGUF_TYPE_STRING = 8 +GGML_TYPE_BF16 = 30 +ALIGN = 32 +CHUNK = 64 << 20 + + +def safetensors_header(path): + with open(path, "rb") as f: + n = struct.unpack(" int: sidecar = out / "experts.bin.src.json" want = experts_source(model, text, offset) reuse = path.exists() and path.stat().st_size == offset and read_json(sidecar) == want + + def layer_blobs(blob, ts): + chunk = np.concatenate([model.bytes(t.name).reshape(n_expert, -1) for t in ts], axis=1) + assert chunk.shape == (n_expert, blob) # (n_expert, blob): gate | up | down per expert + return chunk + + if reuse: + # the sidecar names the shards by name and size, which a re-quantized or fine-tuned checkpoint of the same + # geometry packed into the same folder can share: compare the first and last blobs of the first, middle and + # last layers with the GGUF too (six blobs, so an unchanged pack is still reused at once) + with open(path, "rb") as f: + for l, gt, dt, off, blob, ts in (layout[0], layout[len(layout) // 2], layout[-1]): + for e in (0, n_expert - 1): + f.seek(off + e * blob) + want_blob = b"".join(model.bytes(t.name).reshape(n_expert, -1)[e].tobytes() for t in ts) + if f.read(blob) != want_blob: + reuse = False + if not reuse: + print("%s matches %s but not this GGUF's expert blobs" % (path, sidecar.name)) if path.exists() and not reuse and not a.experts_bin: if sidecar.exists(): print("%s was cut from another source than this model (%s): the engine would read it instead of " @@ -567,10 +586,7 @@ def main() -> int: part = out / "experts.bin.tmp" with open(part, "wb") as fo: for l, gt, dt, off, blob, ts in layout: - parts = [model.bytes(t.name).reshape(n_expert, -1) for t in ts] - chunk = np.concatenate(parts, axis=1) # (n_expert, blob): gate | up | down per expert - assert chunk.shape == (n_expert, blob) - fo.write(chunk.tobytes()) + fo.write(layer_blobs(blob, ts).tobytes()) if l % 8 == 0: print(" layer %2d %-8s/%-7s blob %8d at %.2f GiB" % (l, ts[0].type_name, ts[2].type_name, blob, off / 2**30), flush=True) diff --git a/tools/ple_fp8_pack.py b/tools/ple_fp8_pack.py new file mode 100644 index 00000000..63132731 --- /dev/null +++ b/tools/ple_fp8_pack.py @@ -0,0 +1,123 @@ +"""tools/ple_fp8_pack.py - the PLE n-gram table exactly as Qwen shipped it (FP8 E4M3), as a GGUF the engine reads. + + python tools/ple_fp8_pack.py --model --out + +Qwen3.8-Flash-Next's checkpoint stores the table as 128 shards `...ngram_embedding.shard_{k}.weight` of +[2500012, 160] F8_E4M3 with one BF16 `weight_scale`: 320,001,536 rows of 160 values, 51.2 GB. The engine used to take +it from ISTA-DASLab's GGUF as IQ4_NL (90 B/row), which is 8% off these values per row; this keeps them bit for bit. + +The output is a one-tensor GGUF: `per_layer_token_embd.weight`, ne = [160, 320001536], type I8 holding the FP8 bytes +(GGUF has no FP8 type), with `strata.ple.format` = "f8_e4m3" and `strata.ple.scale` (F32). The bytes are copied +straight out of the safetensors files in shard order - nothing is decoded or rounded - so memory stays flat. +""" +import argparse +import json +import pathlib +import struct +import sys + +GGUF_TYPE_STRING, GGUF_TYPE_F32 = 8, 6 +GGML_TYPE_I8 = 24 +ALIGN = 32 +CHUNK = 64 << 20 + + +def safetensors_header(path): + with open(path, "rb") as f: + n = struct.unpack(" --model [--gpu] [--threads N] -// [--max-tokens N] +// [--max-tokens N] [--flash-attn on|off|auto] // // Resident: prints "READY ", then per stdin line // ENC -> "OK " or "ERR " @@ -17,6 +17,7 @@ #include "mtmd.h" #include "mtmd-helper.h" +#include #include #include #include @@ -24,6 +25,7 @@ #include #include #include +#include #include namespace { @@ -50,6 +52,7 @@ int main(int argc, char** argv) { std::string mmproj, model; bool gpu = false; int threads = 0, max_tokens = 0; + llama_flash_attn_type fa = LLAMA_FLASH_ATTN_TYPE_AUTO; for (int i = 1; i < argc; ++i) { const std::string a = argv[i]; auto next = [&]() -> std::string { @@ -61,13 +64,27 @@ int main(int argc, char** argv) { else if (a == "--gpu") gpu = true; else if (a == "--threads") threads = std::atoi(next().c_str()); else if (a == "--max-tokens") max_tokens = std::atoi(next().c_str()); + else if (a == "--flash-attn") { // FA keeps K and V in FP16; off = the attention in FP32 + const std::string v = next(); + fa = v == "on" ? LLAMA_FLASH_ATTN_TYPE_ENABLED : v == "off" ? LLAMA_FLASH_ATTN_TYPE_DISABLED + : LLAMA_FLASH_ATTN_TYPE_AUTO; + } else { std::fprintf(stderr, "unknown argument %s\n", a.c_str()); return 2; } } if (mmproj.empty() || model.empty()) { std::fprintf(stderr, "usage: strata-vision --mmproj --model [--gpu] [--threads N] " - "[--max-tokens N]\n"); + "[--max-tokens N] [--flash-attn on|off|auto]\n"); return 2; } + // On the CPU the GPU stays unseen: a CUDA build otherwise opens a context there (measured: 0.4-0.7 GB of VRAM, + // 150-260 expert slots less for the engine beside it). Before anything reaches the CUDA runtime. + if (!gpu) { +#ifdef _WIN32 + _putenv_s("CUDA_VISIBLE_DEVICES", "-1"); +#else + setenv("CUDA_VISIBLE_DEVICES", "-1", 1); +#endif + } llama_log_set(quiet_log, nullptr); mtmd_helper_log_set(quiet_log, nullptr); llama_backend_init(); @@ -81,6 +98,9 @@ int main(int argc, char** argv) { cp.use_gpu = gpu; cp.print_timings = false; cp.warmup = false; + cp.flash_attn_type = fa; + // on the CPU without --threads: one per core (mtmd's own default is 4 threads) + if (threads <= 0 && !gpu) threads = std::max(1u, std::thread::hardware_concurrency() / 2); if (threads > 0) cp.n_threads = threads; if (max_tokens > 0) cp.image_max_tokens = max_tokens; mtmd_context* ctx = mtmd_init_from_file(mmproj.c_str(), text, cp); @@ -103,7 +123,10 @@ int main(int argc, char** argv) { // real picture. The server starts this process before the engine, so the engine sizes its expert cache from // what is really left; allocating ~1 GB later, on a GPU the engine has filled, made Windows page GPU memory and // the engine crawl to a standstill. (A square image well above any cap; mtmd scales it to the token limit.) - { + // On the CPU there is no VRAM to reserve, and the warm-up would only delay the engine's start by one encode + // (~6 s at 1,024 tokens). + if (!gpu) std::fprintf(stderr, "strata-vision: on the CPU, %d threads, no warm-up\n", threads); + else { const uint32_t side = 2048; std::vector rgb((size_t) side * side * 3, 128); mtmd_bitmap* bm = mtmd_bitmap_init(side, side, rgb.data());