diff --git a/CMakeLists.txt b/CMakeLists.txt index f54244b0..d4f34778 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -239,6 +239,9 @@ target_link_libraries(strata-dequant PRIVATE strata_artifact) # this file is now nothing but the CLI entry point, and its inherited guard spells that as a "selftest" target_compile_definitions(strata-dequant PRIVATE STRATA_DEQUANT_SELFTEST) if(STRATA_BUILD_TESTS) + add_executable(logit_bias_test src/core/logit_bias_test.cpp) + target_include_directories(logit_bias_test PRIVATE include) + add_test(NAME logit_bias_test COMMAND logit_bias_test) # the reader refuses a duplicate tensor name at open, naming it (a synthetic GGUF: no model, no GPU) add_executable(gguf_reader_test src/artifact/gguf_reader_test.cpp) target_link_libraries(gguf_reader_test PRIVATE strata_artifact) @@ -351,6 +354,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) src/kernels/cuda/native_gdn.cu src/kernels/cuda/native_gr_postops.cu src/kernels/cuda/native_router.cu + src/kernels/cuda/route_prior.cu src/kernels/cuda/native_gdn_preprocess.cu src/kernels/cuda/native_qsa.cu src/kernels/cuda/native_rope.cu @@ -1241,7 +1245,7 @@ if(STRATA_NATIVE_EXPERTS) # one-pass static linking has no cycle to resolve) target_sources(strata_kernels_cpu PRIVATE src/kernels/cpu/native_expert.cpp src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/iq_avx2.cpp src/kernels/cpu/kq_avx2.cpp - src/kernels/cpu/kq_avx1.cpp) + src/kernels/cpu/kq_avx1.cpp src/kernels/cpu/q2_avx1.cpp src/kernels/cpu/iq_avx1.cpp) target_include_directories(strata_kernels_cpu PRIVATE third_party/ggml) if(MSVC) set_source_files_properties(src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512") @@ -1249,12 +1253,26 @@ if(STRATA_NATIVE_EXPERTS) set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") # the router lookahead's AVX1 dot (older CPUs; called behind cpu_avx1_ok): no FMA, no 256-bit integer ops set_source_files_properties(src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX") + # the older CPUs' Q2_0 rows and activation quantizer (q2_avx1.cpp, issue #1699): 128-bit integer lanes, + # no FMA/F16C, its own #error guard; called only behind cpu_avx1_ok() && !cpu_avx2_ok() + set_source_files_properties(src/kernels/cpu/q2_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX") + # the older CPUs' i-quant expert rows (iq_avx1.hpp): 128-bit SSSE3/SSE2 integer, SSE2 float, no FMA/F16C + set_source_files_properties(src/kernels/cpu/iq_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX") else() set_source_files_properties(src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma") set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") set_source_files_properties(src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "-mavx") + # the older CPUs' Q2_0 rows and activation quantizer (q2_avx1.cpp, issue #1699): SSE4.2 + AVX with + # AVX2/FMA/F16C explicitly off, so a -march=native build host cannot leak AVX2 code into the file that + # runs on a Sandy Bridge Xeon + set_source_files_properties(src/kernels/cpu/q2_avx1.cpp PROPERTIES COMPILE_OPTIONS + "-msse4.2;-mavx;-mno-avx2;-mno-fma;-mno-f16c") + # the older CPUs' i-quant expert rows (iq_avx1.hpp): SSE4.2 + AVX with AVX2/FMA/F16C explicitly off, so a + # -march=native build host cannot leak AVX2 code into the file that runs on a Sandy Bridge Xeon + set_source_files_properties(src/kernels/cpu/iq_avx1.cpp PROPERTIES COMPILE_OPTIONS + "-msse4.2;-mavx;-mno-avx2;-mno-fma;-mno-f16c") endif() set_property(SOURCE src/kernels/cpu/iq_avx2.cpp APPEND PROPERTY COMPILE_DEFINITIONS ${_strata_avxvnni}) if(STRATA_ISA_FLOOR STREQUAL "avx") @@ -1289,6 +1307,14 @@ if(STRATA_NATIVE_EXPERTS) add_test(NAME iq_avx2_parity COMMAND iq_avx2_parity) add_test(NAME iq_avx2_parity_iq3s_mt1 COMMAND ${CMAKE_COMMAND} -E env STRATA_IQ3S_MT1=1 $) endif() + # the older CPUs' AVX1 expert rows (iq_avx1.cpp) against ggml-cpu's dots and against their own one-token + # rows at every width; --bench: ms per expert, the weights streamed from DRAM. Runs on any AVX CPU: + # on an AVX2 machine it checks the older-CPU path as an AVX-only machine would run it. + add_executable(iq_avx1_parity src/kernels/cpu/iq_avx1_parity.cpp) + target_link_libraries(iq_avx1_parity PRIVATE strata_kernels_cpu) + if(STRATA_BUILD_TESTS) + add_test(NAME iq_avx1_parity COMMAND iq_avx1_parity) + endif() # the AVX-2 Q8_K activation quantizer against ggml's, byte for byte (--bench: its time) add_executable(q8k_quant_parity src/kernels/cpu/q8k_quant_parity.cpp) target_link_libraries(q8k_quant_parity PRIVATE strata_kernels_cpu) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index c1739f2e..331d1611 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1194,6 +1194,8 @@ the speculative decoding checks at once, exactly as if it decoded one token at a each batch got them). That makes requests with penalties 1-11% slower than in 0.1.18: the draft layer guesses without penalties, so more of its guesses are now rejected. Requests without penalties are unchanged. `top_k` keeps at most 64 candidates: `0` ("off") or anything above 64 uses all 64. +**Token biases (opt-in).** The chat API supports request-scoped `logit_bias` objects and token/bias pair lists on supporting CUDA/HIP engines without continuous batching. A value of -100 (or `false` in a pair list) excludes a token. Unsupported engines return an error. See [LOGIT_BIAS.md](LOGIT_BIAS.md) for formats, limits and validation. + **Sampled drafting (opt-in, 0.1.40.2).** With temperature above 0 the engine keeps a draft only when it equals the token the model sampled for that position, and the draft layer proposes its best guess. Two opt-in switches change how the draft layer drafts a sampled request; greedy requests (temperature 0) are never touched and stay byte-identical. `STRATA_SPEC_COUPLED=1` (or `--coupled-draft`) drafts by sampling with the request's own settings and the random number the checking row will use; the text for a seed does not change. `STRATA_SPEC_PROB=1` is speculative rejection sampling: the draft layer samples its guess from its own distribution q, the check accepts it with probability min(1, p/q) (p is the model's distribution after penalties, top_k, top_p, min_p and temperature) and otherwise samples the replacement from the leftover distribution, so every token is distributed exactly as without drafts (the text for a seed then depends on the drafts, so it is reproducible only for the same engine, flags and prompt). Guesses without a distribution (prompt lookup, suffix drafts) keep the exact-match rule, which is already exact. Neither is faster in a way that holds up: on an RTX 3060 (IQ3_XXS, 200-token story and code answers, 10 interleaved pairs) the default's median output speed was 42.4 / 43.2 / 43.3 tok/s at temperature 0.3 / 0.7 / 1.0, coupled drafting 40.6 / 42.4 / 43.3 and rejection sampling 41.0 / 42.6 / 42.6, with run-to-run differences of up to 5% between repeats; drafts kept per round fell at 0.3 and rose by about 5 points at 1.0, which the cost of the longer sampled windows ate. `STRATA_SPEC_DEPTH=1` prints the acceptance by draft depth for each request; `STRATA_SPEC_MIN_TEMP=0.9` limits sampled drafting to hotter requests. Proof that the rejection rule keeps the distribution: `spec_prob_test` (chi-square, 2 million trials per case) and `spec_verify_parity` (GPU against the host reference). --- diff --git a/docs/LOGIT_BIAS.md b/docs/LOGIT_BIAS.md new file mode 100644 index 00000000..58bf5d4b --- /dev/null +++ b/docs/LOGIT_BIAS.md @@ -0,0 +1,76 @@ +# Per-request token biases + +`POST /v1/chat/completions` accepts `logit_bias` with a supporting CUDA or HIP +engine, without continuous batching. The same bias applies to every generated +token in the request, including tokens checked together during speculative +decoding. It does not force single-token verification windows. + +## Example: Hello becomes Hi + +We use `Hello` because it is a familiar word, it is exactly one token in the +tested tokenizer, and the unbiased model naturally chooses it for this prompt. +The tokenizer maps `Hello` to **token ID 9419**. That number identifies the token; +it is not its logit or probability. The value **-100** is the requested bias, +which this implementation treats as a hard exclusion. + +Before: send this request without a bias. The measured response was **Hello**. + +```json +{ + "model": "bias-validation", + "messages": [{"role": "user", "content": "Reply with one English greeting, one word only."}], + "max_tokens": 8, + "temperature": 0, + "reasoning_effort": "none" +} +``` + +After: add only `logit_bias`. The measured response was **Hi** (token 12675). + +```json +{ + "model": "bias-validation", + "messages": [{"role": "user", "content": "Reply with one English greeting, one word only."}], + "max_tokens": 8, + "temperature": 0, + "reasoning_effort": "none", + "logit_bias": {"9419": -100} +} +``` + +The equivalent llama.cpp-style pair list is `"logit_bias": [[9419, false]]`; +it also produced **Hi**. Removing the field on the next request restored **Hello**. +Nothing is banned by default. This is a per-request example, not a built-in list. +The `model` value above is the test server's alias; use your server's model name. +Numeric pair values are also supported, for example `[[42, 2.5]]`. +Token IDs belong to the loaded model's tokenizer; the example ID is not portable +between arbitrary models. Leading spaces and letter case can also change token IDs. +The four English requests were measured on ISTA IQ3_XXS; a +[reproduction script](../tools/logit_bias_english_example.py) is included. + +## Semantics and limits + +Biases must be finite numbers in `[-100, 100]`. Negative values discourage a +token, positive values encourage it, and **-100 excludes it** (`false` in a +pair list has the same meaning). The bias is added before repetition/frequency/ +presence penalties, temperature, and candidate filtering. Raw model logits +are not overwritten. Banning a token does not ban a word or language: other +token sequences may produce the same text. + +Omitting the field, `null`, `{}`, or `[]` clears the previous request's bias. +Biases are request sampling state; they are not stored in a conversation cache. +They do not change the model weights or prompt KV. A fixed dense vocabulary +vector is uploaded when the bias changes and reused within the request. + +Malformed entries, duplicate IDs in pair lists, IDs outside the vocabulary, +out-of-range biases, or banning the entire vocabulary return HTTP 400. Validation +on the chat route occurs before SSE streaming headers are sent. Nonempty biases +also return HTTP 400 with older engines, the current SYCL engine, or continuous +batching (`--batch`), rather than being silently ignored. The engine advertises +`logit_bias=1` in its `INFO` response when this implementation is present. + +MTP target verification applies the bias; the draft model is not biased, so a +restrictive list may reduce draft acceptance. Ordinary MTP was tested. The +experimental coupled/rejection-sampling combinations and multi-GPU execution +were not validated in this campaign. There is no startup bias-file option in +this change: send the field with each request. diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 030ee3cc..861d9e82 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -429,6 +429,10 @@ struct ExpertDispatch { /// #588: routed (token, expert) entries the GPU computed from outside its cache in verify windows: read over PCIe /// (--pcie-frac, kind 1) or on another GPU (kind 2). In neither cache_hits nor cache_refused. int64_t offload_entries = 0; + /// STRATA_ROUTE_TAIL_SKIP=R: entries skipped (a missed expert every token of the window routes only at rank >= R) + /// and the distinct experts behind them (neither copied nor computed) + int64_t tail_skipped = 0; + int64_t tail_experts = 0; double ms_plan = 0, ms_actq = 0, ms_jobs = 0, ms_run = 0; ///< verify-window dispatch sections /// Plan v0.3 P6: decayed routing counts per (layer, expert) during decode (sized by the caller; empty = off), /// which the driver uses to swap the most-routed missing experts into the VRAM tier between rounds. @@ -617,6 +621,16 @@ public: /// 32 measured 2.35 GB/s with experts.bin mapped and 3.57 GB/s without. After this every file read goes through /// read_direct (mapped_blob answers nullptr). Returns whether the view was closed; `why` says why not. bool drop_mapping(std::string& why); + /// Windows, experts.bin, a file tier that reads through the file cache (--resident-experts): the startup reads - + /// the GPU cache's fill from the profile and the RAM copy (pin_cache_complement) - go unbuffered (read_direct) + /// with the view closed meanwhile. Through the mapping they put the file's pages in the working set beside the + /// RAM copy, and on a PC short of RAM that pages other memory out. The bytes and their places are the same. + /// end_startup_unbuffered maps the view again and closes the unbuffered handles and the stage buffers, as before + /// the startup. STRATA_STARTUP_UNBUFFERED=0: the mapped copy (A/B). False (and `why`) when it does not apply. + bool begin_startup_unbuffered(std::string& why); + /// False when the view could not be mapped again: then the file tier stays unbuffered, `why` says so. + bool end_startup_unbuffered(std::string& why); + bool startup_unbuffered() const { return startup_ub_; } /// Every expert's bytes (n_layers x n_expert blobs). uint64_t expert_bytes() const; /// #286, unbuffered: assembles the blobs of these pairs ahead of the `blob` calls that will ask for them (the @@ -704,6 +718,8 @@ private: /// Windows, io_submit on Linux) into this thread's aligned buffer, then copied into place. False when a read fails. bool read_direct(const Fill* fills, size_t n) const; bool open_direct(std::string& why); + /// Windows: experts.bin mapped again as `open` maps it (begin/end_startup_unbuffered). + bool map_view(std::string& why); std::vector paths_; ///< the mapped files, as maps_ std::vector direct_; ///< #286: per file, an unbuffered handle (Windows) or O_DIRECT fd (Linux) std::vector role_file_; ///< 3 x n_layers: index into maps_ / direct_ @@ -828,6 +844,8 @@ private: int fd_ = -1; #endif bool unmapped_ = false; ///< pp-opt: drop_mapping closed the view (base_ stays as the "opened" mark only) + bool startup_ub_ = false; ///< begin_startup_unbuffered: until end_startup_unbuffered + uint64_t startup_blob_bytes_ = 0, startup_us_ = 0; ///< the staged reads' counters at its begin (put back at the end) }; // ================================ THE RESIDENT ARENA (R2.1) ================================ diff --git a/include/strata/core/logit_bias.hpp b/include/strata/core/logit_bias.hpp new file mode 100644 index 00000000..cbf096cb --- /dev/null +++ b/include/strata/core/logit_bias.hpp @@ -0,0 +1,39 @@ +#pragma once +#include +#include +#include +#include +#include + +namespace strata::core { +// Native protocol: logit_bias=id:value,id:value. -100 is a hard exclusion, not a finite penalty. +inline bool parse_logit_bias(const std::string& text, int vocab, std::vector& out, std::string& error) { + out.clear(); + if (text.empty() || vocab <= 0) { error = "empty logit_bias or invalid vocabulary"; return false; } + std::vector bias((size_t) vocab, 0.0f); + std::vector seen((size_t) vocab, false); + const char* p = text.c_str(); + int banned = 0; + for (;;) { + if (*p < '0' || *p > '9') { error = "invalid logit_bias token ID"; return false; } + char* end = nullptr; + const unsigned long id = std::strtoul(p, &end, 10); + if (*end != ':' || id >= (unsigned long) vocab || seen[id]) { + error = "logit_bias ID outside vocabulary, duplicated, or missing ':'"; return false; + } + p = end + 1; + const float value = std::strtof(p, &end); + if (end == p || !std::isfinite(value) || value < -100 || value > 100 || (*end && *end != ',')) { + error = "invalid logit_bias value (expected -100..100)"; return false; + } + seen[id] = true; + bias[id] = value == -100 ? -std::numeric_limits::infinity() : value; + banned += value == -100; + if (!*end) break; + p = end + 1; + } + if (banned == vocab) { error = "logit_bias bans the entire vocabulary"; return false; } + out = std::move(bias); + return true; +} +} // namespace strata::core diff --git a/include/strata/core/remote_experts.hpp b/include/strata/core/remote_experts.hpp index 218ff55b..d499c031 100644 --- a/include/strata/core/remote_experts.hpp +++ b/include/strata/core/remote_experts.hpp @@ -5,7 +5,9 @@ #include +#include #include +#include #include #include #include @@ -51,6 +53,15 @@ public: double ms_begin() const { return ms_begin_; } double ms_wait() const { return ms_wait_; } + /// STRATA_PREFILL_HELPER_SOURCE (opt-in): copy up to `n` cached blobs into the host buffers `dst[i]` + /// on this helper's own stream and wait. `hit[i]` is set where this helper held (layer, expert); the + /// bytes are the ones open() filled from the same source, so the prompt path gets identical bytes. + /// Misses are left to the caller. False with `err` on a CUDA failure; the hits copied so far are + /// complete (the stream is drained), so the caller falls back for the rest. Safe from several threads + /// (one stream, one lock): the prompt path's stager is threaded. + bool copy_cached_blobs(const int32_t* layers, const int32_t* experts, uint8_t* const* dst, size_t n, + uint8_t* hit, std::string& err); + private: friend class RemoteExpertOpt; RemoteExpertOpt* remote_opt_ = nullptr; @@ -64,6 +75,8 @@ private: double ms_begin_ = 0, ms_wait_ = 0; ExpertCache cache_; cudaStream_t stream_ = nullptr; + cudaStream_t read_stream_ = nullptr; ///< STRATA_PREFILL_HELPER_SOURCE: cache -> host copies + std::mutex read_mu_; ///< one cache reader at a time (the stager is threaded) float* h_x_ = nullptr; float* h_out_ = nullptr; void* h_meta_ = nullptr; @@ -88,4 +101,72 @@ private: std::vector ptr_; }; +/// STRATA_PREFILL_HELPER_SOURCE (opt-in): the prompt path's view of the expert tiers, where a blob a helper +/// GPU already holds in its VRAM cache is copied from that cache instead of being read from the files again. +/// Everything else is forwarded to `fallback` unchanged, so its batched unbuffered reads, its pinned RAM copy +/// and the prompt path's own decisions keep their meaning. Nothing is cached here: every call asks the +/// helpers, so an entry an adaptive tier moves between requests is a miss (a file read), never a wrong blob. +/// +/// The serve loop builds this only for a serial request path (no batch slots, no layer split), while the +/// helpers are idle: during a prompt read the helper GPUs compute nothing, so their caches can be read +/// without ordering the copies against their kernel streams. +class RemotePrefillSource final : public ExpertSource { +public: + RemotePrefillSource(ExpertSource& fallback, const std::vector& helpers) + : fallback_(fallback), helpers_(helpers) {} + + /// Whether any helper's VRAM cache holds (layer, expert) right now. + bool from_helper(int64_t layer, int64_t expert) const { + for (const RemoteExperts* h : helpers_) if (h->holds(layer, (int32_t) expert)) return true; + return false; + } + /// Blobs / bytes this source has taken from the helpers so far (the per-request evidence line). + uint64_t helper_blobs() const { return helper_blobs_.load(std::memory_order_relaxed); } + uint64_t helper_bytes() const { return helper_bytes_.load(std::memory_order_relaxed); } + + const uint8_t* blob(int64_t layer, int64_t expert) override { return fallback_.blob(layer, expert); } + const uint8_t* blob_stable(int64_t layer, int64_t expert) override { + return fallback_.blob_stable(layer, expert); + } + int64_t reads() const override { return fallback_.reads(); } + bool pinned(int64_t layer, int64_t expert) const override { + return from_helper(layer, expert) ? false : fallback_.pinned(layer, expert); + } + void begin_layer(int64_t layer, const int32_t* ids, int64_t k) override { + fallback_.begin_layer(layer, ids, k); + } + const uint8_t* device_alias(int64_t layer, int64_t expert) const override { + return from_helper(layer, expert) ? nullptr : fallback_.device_alias(layer, expert); + } + void prefetch(int64_t layer, int64_t expert) override { fallback_.prefetch(layer, expert); } + uint64_t release(int64_t layer, int64_t expert) override { + return from_helper(layer, expert) ? 0 : fallback_.release(layer, expert); + } + bool pcie_layer(int64_t layer) const override { return fallback_.pcie_layer(layer); } + /// True where a helper holds the blob: the prompt path's stager must then take the copy_blob(s) route, + /// which is where the cache-to-host copy happens. Everywhere else the fallback answers as it always did. + bool transient(int64_t layer, int64_t expert) const override { + return from_helper(layer, expert) ? true : fallback_.transient(layer, expert); + } + double cached_share(int64_t samples) const override { return fallback_.cached_share(samples); } + bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst) override; + bool copy_blobs(const int32_t* layers, const int32_t* experts, uint8_t* const* dst, size_t n) override; + void prefetch(int64_t layer, const int64_t* experts, int64_t n) override { + fallback_.prefetch(layer, experts, n); + } + void warm(int64_t layer, const int64_t* experts, int64_t n) override { + fallback_.warm(layer, experts, n); + } + bool warms() const override { return fallback_.warms(); } + bool advise_pairs(const std::pair* pairs, int64_t n) const override { + return fallback_.advise_pairs(pairs, n); + } + +private: + void warn(const std::string& err); + ExpertSource& fallback_; + std::vector helpers_; + std::atomic helper_blobs_{0}, helper_bytes_{0}; + std::atomic warned_{false}; +}; } // namespace strata::core diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index 16849810..519fd43b 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -90,8 +90,11 @@ public: /// parameters would otherwise be baked forever - so this can change between requests freely. void set_sampling(const strata::kernels::SamplerParams& sp) { sampling_ = sp; // row t of a window at pos0 draws Philox(seed, pos0 + t): see run() + sampling_.logit_bias = logit_bias_host_.empty() ? nullptr : logit_bias_device_; if (next_) next_->set_sampling(sp); } + // One request's fixed vocabulary bias. Empty clears it; copied only when changed, on the final stage's device. + bool set_logit_bias(const std::vector& bias, std::string& err); /// The penalty histories for `sampling_.penalty_last_n`: ONE ROW PER WINDOW ROW, T rows of `history_len` /// int32 slots at that stride (`strata::kernels::penalty_rows` builds them), most recent token LAST, unused @@ -341,6 +344,8 @@ private: int32_t* d_spec_ = nullptr; ///< device: kVerifyMaxT draft ids, then kVerifyMaxT q rows int hist_len_ = 0; bool head_sampling_ = true; ///< set_head_sampling + std::vector logit_bias_host_; + float* logit_bias_device_ = nullptr; int device_ = -1; ///< the device `init` ran on: run/commit switch to it (layer split) unsigned long long* rr_stats_ = nullptr; ///< STRATA_ROUTE_RESIDENT's counters on device_ (#1578); null: none std::atomic released_{false}; ///< #267: release_gpu_waits ran (maybe on the watchdog thread): no more windows diff --git a/include/strata/kernels/cpu/expert.hpp b/include/strata/kernels/cpu/expert.hpp index 8510598b..441dfac0 100644 --- a/include/strata/kernels/cpu/expert.hpp +++ b/include/strata/kernels/cpu/expert.hpp @@ -189,6 +189,14 @@ void q2_0_gguf_rows_multi_avx2_legacy(const uint8_t* w, size_t row_bytes, int nb void q2_0_gguf_rows_multi_avx2_v(bool vnni, const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, float* const* out, int r0, int r1); void act_quant_q8_1_avx2(const float* x, int n, ActQ& a); +/// The same for CPUs with AVX but no AVX2 (src/kernels/cpu/q2_avx1.cpp, the third rung of q2_rows_any / +/// act_quant_any, issue #1699): same arithmetic, 128-bit integer lanes, mul+add instead of FMA (last bits), +/// software fp16 conversion. Called only behind cpu_avx1_ok() && !cpu_avx2_ok(). +void q2_0_gguf_rows_multi_avx1(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, + float* const* out, int r0, int r1); +void q2_0_gguf_rows_multi_avx1_legacy(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, + float* const* out, int r0, int r1); +void act_quant_q8_1_avx1(const float* x, int n, ActQ& a); void s2_expert_scalar(const uint8_t* blob, const float* x, float* out, bool quant_acts); diff --git a/include/strata/kernels/cpu/expert_layout.hpp b/include/strata/kernels/cpu/expert_layout.hpp index 615afa19..6b3fddb6 100644 --- a/include/strata/kernels/cpu/expert_layout.hpp +++ b/include/strata/kernels/cpu/expert_layout.hpp @@ -85,6 +85,9 @@ std::string cpu_name(); void q2_rows_any(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, float* const* out, int r0, int r1); void act_quant_any(const float* x, int n, ActQ& a); +/// The same dispatch, always the pre-bit-plane kernel (tests and A/B; the bit-plane switch off by construction). +void q2_rows_any_legacy(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, float* const* out, + int r0, int r1); /// The process-wide layout (canonical Q2_0 until `expert_layout_load` finds a native pack). const ExpertLayout& expert_layout(); diff --git a/include/strata/kernels/cpu/iq_avx1.hpp b/include/strata/kernels/cpu/iq_avx1.hpp new file mode 100644 index 00000000..c160acc2 --- /dev/null +++ b/include/strata/kernels/cpu/iq_avx1.hpp @@ -0,0 +1,37 @@ +// include/strata/kernels/cpu/iq_avx1.hpp - AVX1 (SSE4.2 + AVX, no AVX2/FMA) multi-token expert rows +// for the older-CPU builds (STRATA_ISA_FLOOR=avx: Sandy/Ivy Bridge, Xeon E5 v1/v2, Bulldozer). +// +// The sibling of kq_avx1.cpp for the expert kernels: without these, every CPU expert on such a CPU runs on +// ggml-cpu's scalar `_generic` dots (every x86 i-quant dot is #if defined(__AVX2__)). Everything these +// kernels need exists in 128-bit on that ISA: pshufb, sign_epi8 and maddubs are SSSE3, madd_epi16 is SSE2; +// the float accumulation is 128-bit SSE2 (no FMA). No gathered variants: the non-gather Fmt32 decode of +// iq_avx2.cpp is the template and it is 128-bit-portable. +// +// Compiled for AVX (-mavx / /arch:AVX, see CMakeLists.txt) and called only behind cpu_avx1_ok(), so a CPU +// without AVX never reaches it. The arithmetic is ggml's (the `_generic` references): a multi-token row is +// bit for bit the same kernel's single-token row for that token (#152), and rows match ggml-cpu's dot to +// rel <= 1e-5 (iq_avx1_parity checks both). +#pragma once + +#include +#include + +namespace strata::kernels::cpu { + +/// gate/up formats with an AVX1 kernel: IQ3_XXS (18), IQ3_S (21), IQ2_S (22), IQ4_XS (23). +bool iq128_supported(int ggml_type) noexcept; +/// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]), rows [r0, r1); gate rows at blob, up rows at blob + up_off. +/// Activations are ggml's quantized form for the format (Q8_K for every format here), as in native_gu_rows. +void iq128_gu_rows(int ggml_type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, + int nt, float* const* ff, int r0, int r1); + +/// down formats with an AVX1 kernel: IQ4_NL (20), Q2_0 (42, the fork's type). Activations: Q8_0 for both. +bool iq128_down_supported(int ggml_type) noexcept; +void iq128_down_rows(int ggml_type, const uint8_t* w, size_t row_bytes, int n, const void* const* hq, int nt, + float* const* out, int r0, int r1); + +/// ggml's quantize_row_q8_K (x86 runs the scalar reference), byte-identical, in SSE4.2/AVX1: the older CPUs' +/// copy of q8k_quant_avx2 (no 256-bit integer ops, no FMA). q8k_quant_parity checks the bytes. +void q8k_quant_avx1(const float* x, void* y, int64_t n); + +} // namespace strata::kernels::cpu diff --git a/include/strata/kernels/route_prior.hpp b/include/strata/kernels/route_prior.hpp new file mode 100644 index 00000000..c00e3b24 --- /dev/null +++ b/include/strata/kernels/route_prior.hpp @@ -0,0 +1,15 @@ +// include/strata/kernels/route_prior.hpp - STRATA_ROUTE_PRIOR=lambda (opt-in, changes the output): cache-conditioned +// routing in verify windows. See src/kernels/cuda/route_prior.cu. +#pragma once + +#include + +namespace strata::kernels { + +/// Top-10 per token over `logits` (n_tok x 512) where a resident expert (`res_layer[e] >= 0`, the layer's residency +/// table) gets `lambda` added to its logit for the SELECTION; the weights are the router's own probabilities +/// (softmax over the 512 unbiased logits) renormalised over the 10 picked, as the native router does. +void route_prior_top10(const float* logits, const int32_t* res_layer, float lambda, int32_t* ids, float* weights, + int n_tok, void* stream); + +} // namespace strata::kernels diff --git a/include/strata/kernels/sampler.hpp b/include/strata/kernels/sampler.hpp index f8d6bfe3..a3121ba1 100644 --- a/include/strata/kernels/sampler.hpp +++ b/include/strata/kernels/sampler.hpp @@ -25,6 +25,7 @@ struct SamplerParams { uint64_t seed = 0; // drives Philox, which is counter-based on (seed, token index) uint64_t counter = 0; // absolute draw index of row 0; advance across decode calls bool greedy = false; + const float* logit_bias = nullptr; // optional device array [n_vocab], added BEFORE penalties/filters; -inf bans bool gumbel = false; // STRATA_SPEC_GUMBEL=1: Gumbel-max pick keyed by (seed, counter, token id) - see sampler.cu }; diff --git a/include/strata/prefill/gemm.hpp b/include/strata/prefill/gemm.hpp index 1eae68b4..935f1a9a 100644 --- a/include/strata/prefill/gemm.hpp +++ b/include/strata/prefill/gemm.hpp @@ -68,6 +68,13 @@ private: bool external_ = false; void* hipblaslt_state_ = nullptr; bool f16_io_ = false; + /// cuBLAS 12 answers the default FP16 algorithm of a few (N, K) shapes with CUBLAS_STATUS_INTERNAL_ERROR once + /// another CUDA device in the process has initialized its context (issue #1650, Turing + Pascal). A fixed + /// algorithm (ALGO2) survives that state, but is markedly slower for the wide shapes, so only the shapes that + /// fail move, and they are remembered here ((K << 32) | N, up to kF16AlgoSlots). CUDA only. + static constexpr int kF16AlgoSlots = 32; + int64_t f16_algo_shape_[kF16AlgoSlots] = {}; + int f16_algo_n_ = 0; // below sm_80: FP16 (Pascal: fp32) copies of a BF16 product's weight and activation slice (Gemm::bf16) uint16_t* tc_w_ = nullptr; int64_t tc_w_elems_ = 0; diff --git a/serve/logit_bias.py b/serve/logit_bias.py new file mode 100644 index 00000000..59873a77 --- /dev/null +++ b/serve/logit_bias.py @@ -0,0 +1,52 @@ +"""Request-scoped token biases. Normalize before HTTP streaming starts.""" +import math +import re + + +def normalize(value, vocab_size=None): + if value is None: + return {} + if isinstance(value, dict): + entries = value.items() + pairs = False + elif isinstance(value, list): + entries = value + pairs = True + else: + raise ValueError("logit_bias: expected an object or a list of [token_id, bias] pairs") + out = {} + for entry in entries: + if not isinstance(entry, (list, tuple)) or len(entry) != 2: + raise ValueError("logit_bias: each entry must be [token_id, bias]") + token, bias = entry + if isinstance(token, bool) or not isinstance(token, (str, int)) or not re.fullmatch(r"[0-9]+", str(token)): + raise ValueError("logit_bias: token IDs must be non-negative integers") + token = int(token) + if token > 2147483647 or (vocab_size is not None and token >= vocab_size): + raise ValueError("logit_bias: token ID outside the model vocabulary") + if token in out: + raise ValueError("logit_bias: duplicate token ID") + if pairs and bias is False: + bias = -100.0 + if isinstance(bias, bool) or not isinstance(bias, (int, float)) or not -100 <= bias <= 100 or not math.isfinite(bias): + raise ValueError("logit_bias: biases must be finite numbers between -100 and 100; false is a pair-list ban") + out[token] = float(bias) + if vocab_size is not None and sum(b == -100 for b in out.values()) == vocab_size: + raise ValueError("logit_bias: cannot ban the entire vocabulary") + return out + + +def engine_key(value): + entries = normalize(value) + return " logit_bias=" + ",".join(f"{i}:{b:g}" for i, b in sorted(entries.items())) if entries else "" + + +def validate_request(req, engine, vocab_size): + """Fail closed for old engines, unsupported backends and continuous batching.""" + normalized = normalize(req.get("logit_bias"), vocab_size) + if normalized: + if getattr(engine, "info", {}).get("logit_bias") != 1: + raise ValueError("logit_bias: this engine does not support token biases; use a supporting CUDA/HIP build") + if getattr(engine, "batch", 0): + raise ValueError("logit_bias: continuous batching is not supported; run without --batch") + return normalized diff --git a/serve/server.py b/serve/server.py index cde9073a..f6134f68 100644 --- a/serve/server.py +++ b/serve/server.py @@ -59,6 +59,7 @@ from serve.frontend import (THINK_END, ChatTemplate, Event, OutputParser, anthro tool_choice_of, unmark_think_literals) from serve.mcp import McpCancelled, hub_from_config # noqa: E402 from serve import runconfig # noqa: E402 +from serve import logit_bias as bias_api # noqa: E402 from serve.winjob import contain # noqa: E402 from serve.structured import StructuredOutputError, prepare_format, validated_json # noqa: E402 from serve import responses as responses_api # noqa: E402 @@ -1001,7 +1002,7 @@ class StrataEngine: pn = prefix.get("tokens") if isinstance(pn, int) and not isinstance(pn, bool) and pn > 0: keys += f" pin={pn}" - return keys + StrataEngine.projection_key(sampling) + return keys + StrataEngine.projection_key(sampling) + bias_api.engine_key(sampling.get("logit_bias")) @staticmethod def projection_key(sampling: dict) -> str: @@ -1554,6 +1555,7 @@ class StrataEngine: has gone. A consumer that stops early (or `cancel`) makes the engine STOP, so it does not run to max_new.""" if not self.alive(): raise EngineDied("the engine is unavailable; this request was not sent") + bias_api.validate_request(sampling or {}, self, None) if getattr(self, "batch", 0): yield from self.generate_batched(ids, max_new, sampling, cancel, embeddings) return @@ -5185,6 +5187,7 @@ def make_handler(svc: Service): def _openai(self, req): req = svc.with_shared(req, "openai") + bias_api.normalize(req.get("logit_bias"), len(getattr(svc.tok, "tokens", ())) or None) messages, tools, kw = openai_to_messages(req) self._no_local_images(messages) if tool_choice_of(req.get("tool_choice"))[0] == "none": # as the Responses route: no tools are offered @@ -5195,6 +5198,7 @@ def make_handler(svc: Service): 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 + bias_api.validate_request(req, svc.engine, len(getattr(svc.tok, "tokens", ())) or None) 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 [] if isinstance(t, dict)} # #592: a second line of defence if use_mcp: diff --git a/serve/test_logit_bias.py b/serve/test_logit_bias.py new file mode 100644 index 00000000..ee3751b1 --- /dev/null +++ b/serve/test_logit_bias.py @@ -0,0 +1,61 @@ +import json +from pathlib import Path +from types import SimpleNamespace +import unittest +import urllib.error +import urllib.request + +from serve.logit_bias import engine_key, normalize, validate_request +from serve.server import ByteTokenizer, MockEngine, Service, StrataEngine, serve +from serve.frontend import ChatTemplate + + +class LogitBias(unittest.TestCase): + def test_forms_and_transport(self): + self.assertEqual(normalize({"7": -100, "9": 2.5}, 10), normalize([[7, False], [9, 2.5]], 10)) + self.assertEqual(engine_key([[9, 2.5], [7, False]]), " logit_bias=7:-100,9:2.5") + self.assertEqual(StrataEngine.sampling_keys({"logit_bias": {"7": -100}}), " logit_bias=7:-100") + for value in [None, {}, []]: + self.assertEqual(engine_key(value), "") + + def test_invalid(self): + bad = [True, 1, "x", [1], [[1]], [[1, 0, 2]], {"-1": 0}, {"1.0": 0}, {"10": 0}, + {"1": False}, [[1, True]], [[1.0, 0]], [[True, 0]], [[1, 0], ["1", 2]], + {"1": 101}, {"1": -101}, {"1": float('nan')}, {"1": float('inf')}, {"1": 10**1000}] + for value in bad: + with self.subTest(value=str(value)[:50]), self.assertRaises(ValueError): + normalize(value, 10) + with self.assertRaises(ValueError): + normalize({str(i): -100 for i in range(10)}, 10) + + def test_large_list(self): + entries = [[i, False] for i in range(103215)] + self.assertEqual(len(normalize(entries, 248320)), 103215) + self.assertEqual(engine_key(entries).count(':-100'), 103215) + + def test_capability_and_batch(self): + for engine in [SimpleNamespace(info={}), SimpleNamespace(info={'logit_bias': 1}, batch=2)]: + with self.assertRaises(ValueError): + validate_request({'logit_bias': {'1': -100}}, engine, 10) + self.assertEqual(validate_request({}, engine, 10), {}) + self.assertEqual(validate_request({'logit_bias': {'1': -100}}, SimpleNamespace(info={'logit_bias': 1}), 10), {1: -100}) + + def test_http_rejects_before_stream(self): + tok = ByteTokenizer() + engine = MockEngine(tok, 'ok', max_context=4096) + service = Service(engine, tok, ChatTemplate(Path(__file__).parent/'chat_template.jinja')) + httpd = serve(service, port=0) + try: + for bias in [True, {'1': -100}, [[1, True]]]: + data = json.dumps({'messages': [{'role': 'user', 'content': 'hi'}], 'max_tokens': 2, + 'stream': True, 'logit_bias': bias}).encode() + req = urllib.request.Request(f'http://127.0.0.1:{httpd.server_address[1]}/v1/chat/completions', + data=data, headers={'Content-Type': 'application/json'}) + with self.assertRaises(urllib.error.HTTPError) as caught: + urllib.request.urlopen(req, timeout=10) + with caught.exception as response: + self.assertEqual(response.code, 400) + self.assertIn('logit_bias', json.loads(response.read())['error']['message']) + finally: + httpd.shutdown() + httpd.server_close() diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index 3ba41e87..add047d0 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -1666,6 +1666,120 @@ bool FileExpertSource::drop_mapping(std::string& why) { #endif } +bool FileExpertSource::begin_startup_unbuffered(std::string& why) { +#if defined(_WIN32) + if (const char* v = std::getenv("STRATA_STARTUP_UNBUFFERED"); v != nullptr && v[0] != '\0' && std::atoi(v) == 0) { + why = "STRATA_STARTUP_UNBUFFERED=0"; + return false; + } + if (base_ == nullptr || unmapped_ || startup_ub_ || !role_ptr_.empty() || !maps_.empty() || paths_.size() != 1 || + layer_blob_bytes_.empty()) { + why = "experts.bin only"; + return false; + } + if (!direct_.empty()) { why = "the file tier reads unbuffered already"; return false; } + const auto t0 = std::chrono::steady_clock::now(); + const uint8_t* m = mapped_blob(0, 0); // the first blob as the mapping reads it, for the check below + if (m == nullptr) { why = "the first blob is not mapped"; return false; } + const std::vector ref(m, m + (size_t) layer_blob_bytes_[0]); + // NTFS runs the unbuffered reads of a file one at a time while it is mapped or open buffered (drop_mapping), so + // the view, the section and the handle all go. The first unbuffered open with no buffered handle left purges the + // file's cached pages: 1.2-2.5 s after a mapped start had left IQ2_XS's 33 GiB experts.bin on the standby list, + // 3 ms after an unbuffered start. A buffered handle held open instead keeps the cache and serializes the reads + UnmapViewOfFile((LPCVOID) base_); + unmapped_ = true; + if (mapping_ != nullptr) CloseHandle((HANDLE) mapping_); + mapping_ = nullptr; + if (file_ != nullptr) CloseHandle((HANDLE) file_); + file_ = nullptr; + std::string fail; + if (open_direct(fail)) { + // the first blob both ways: a drive that does not read it unbuffered keeps the mapped copy + std::vector probe(ref.size()); + const Fill f{0, 0, 0, probe.data()}; + if (read_direct(&f, 1) && std::memcmp(probe.data(), ref.data(), ref.size()) == 0) { + startup_ub_ = true; + startup_blob_bytes_ = file_blob_bytes_.load(); + startup_us_ = file_us_.load(); + char note[96]; + std::snprintf(note, sizeof note, "the view closed until the RAM copy is built; %.0f ms", + std::chrono::duration(std::chrono::steady_clock::now() - t0).count()); + why = note; + return true; + } + fail = "an unbuffered read of the first blob failed or differed from the mapping"; + for (void* d : direct_) close_direct(d); + direct_.clear(); + std::lock_guard lk(stage_mu_); + stage_blob_ = 0; + } + std::string again; + why = map_view(again) ? fail : fail + "; " + again; + return false; +#else + why = "Windows only"; + return false; +#endif +} + +bool FileExpertSource::end_startup_unbuffered(std::string& why) { + if (!startup_ub_) return true; + startup_ub_ = false; + // the view first: closing the unbuffered handles beside a buffered one purges nothing + if (!map_view(why)) { + why += ": the file tier reads it unbuffered"; + return false; // as after drop_mapping: every read goes through read_direct + } + for (void* d : direct_) close_direct(d); + direct_.clear(); + { // the mapped tier hands out the mapping: the startup's stage buffers go + std::lock_guard lk(stage_mu_); + stage_buf_.clear(); + stage_key_.clear(); + stage_epoch_.clear(); + stage_used_.clear(); + stage_busy_.clear(); + stage_pf_.clear(); + stage_of_.clear(); + stage_blob_ = 0; + } + file_blob_bytes_.store(startup_blob_bytes_); + file_us_.store(startup_us_); + return true; +} + +bool FileExpertSource::map_view(std::string& why) { +#if defined(_WIN32) + // open's mapping of experts.bin, again + const std::string& path = paths_.front(); + const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0); + std::vector wpath((size_t) (wide > 0 ? wide : 1), L'\0'); + if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide); + HANDLE f = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, + nullptr); + LARGE_INTEGER sz{}; + const bool same = f != INVALID_HANDLE_VALUE && GetFileSizeEx(f, &sz) && (uint64_t) sz.QuadPart == mapped_bytes_; + HANDLE m = same ? CreateFileMappingW(f, nullptr, PAGE_READONLY, 0, 0, nullptr) : nullptr; + void* view = m != nullptr ? MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0) : nullptr; + if (view == nullptr) { + why = f != INVALID_HANDLE_VALUE && !same + ? std::string("experts.bin changed size since it was opened") + : "experts.bin could not be mapped again (error " + std::to_string((unsigned long long) GetLastError()) + ")"; + if (m != nullptr) CloseHandle(m); + if (f != INVALID_HANDLE_VALUE) CloseHandle(f); + return false; + } + file_ = f; + mapping_ = m; + base_ = (const uint8_t*) view; + unmapped_ = false; + return true; +#else + why = "Windows only"; + return false; +#endif +} + bool FileExpertSource::read_direct(const Fill* fills, size_t n) const { #if defined(_WIN32) // NTFS runs the unbuffered reads of a file one at a time while the file is mapped or cached anywhere (the engine @@ -2809,9 +2923,29 @@ bool FileExpertSource::pin_cache_complement( #if defined(_WIN32) // The mapped pages this process touched (the GPU cache's fill and this copy) leave its working set for the // standby list: VirtualUnlock on pages that are not locked does exactly that (it then reports ERROR_NOT_LOCKED). - if (maps_.empty()) (void) VirtualUnlock((LPVOID) base_, (SIZE_T) mapped_bytes_); + // Not with the view closed (begin_startup_unbuffered): its range may hold other memory by now. + if (maps_.empty() && !unmapped_) (void) VirtualUnlock((LPVOID) base_, (SIZE_T) mapped_bytes_); for (const Map& m : maps_) (void) VirtualUnlock((LPVOID) m.base, (SIZE_T) m.bytes); #endif + if (std::getenv("STRATA_VERIFY_COMPLEMENT") != nullptr && host != nullptr && bytes > 0) { + // tests: the copy's checksum (FNV-1a of each 1 GiB piece on its own thread, then of those), any reader + constexpr uint64_t kPiece = 1ull << 30; + const size_t pieces = (size_t) ((bytes + kPiece - 1) / kPiece); + std::vector ph(pieces, 0); + std::atomic next_piece{0}; + auto hash_work = [&] { + for (size_t i; (i = next_piece.fetch_add(1)) < pieces;) + ph[i] = fnv1a64(host + (size_t) (i * kPiece), std::min(kPiece, bytes - i * kPiece)); + }; + std::vector hth; + for (int t = 1; t < 8; ++t) hth.emplace_back(hash_work); + hash_work(); + for (auto& t : hth) t.join(); + uint64_t h = fnv1a64((const uint8_t*) offsets.data(), (uint64_t) (offsets.size() * sizeof(uint64_t))); + h = fnv1a64((const uint8_t*) ph.data(), (uint64_t) (ph.size() * sizeof(uint64_t)), h); + std::fprintf(stderr, "FileExpertSource: cache complement checksum %016llx (%.2f GiB, its offsets included)\n", + (unsigned long long) h, (double) bytes / 1073741824.0); + } complement_arena_ = arena; complement_host_ = host; @@ -3297,6 +3431,33 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 !(d.peer != nullptr && d.peer->has(d.layers, e)) && !helper_holds(e)) ++nmiss; } } + // STRATA_ROUTE_TAIL_SKIP=R (opt-in, changes the output): a missed expert that EVERY token of the window routes + // only at rank >= R (the smallest weights of the top-10) is neither copied nor computed; its contribution is + // zero, without renormalisation (the others keep the weight the router gave them). Less PCIe and CPU work. + static const int tail_rank = [] { + const char* v = std::getenv("STRATA_ROUTE_TAIL_SKIP"); + const int r = v != nullptr ? std::atoi(v) : 0; + return r > 0 && r < 10 ? r : 0; + }(); + bool skip_d[kMaxWindowEntries]; + for (int q = 0; q < nd; ++q) skip_d[q] = false; + if (tail_rank > 0 && d.peer == nullptr && d.remote_count == 0) { + int minr[kMaxWindowEntries]; + for (int q = 0; q < nd; ++q) minr[q] = 99; + for (int64_t i = 0; i < n; ++i) { + int q = 0; + while (q < nd && distinct[q] != first_of[i]) ++q; + if (q < nd) minr[q] = std::min(minr[q], (int) (i % k)); + } + for (int q = 0; q < nd; ++q) { + const int32_t e = ids[distinct[q]]; + if (e < 0 || e >= d.n_expert || minr[q] < tail_rank) continue; + if (d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] >= 0) continue; // resident + skip_d[q] = true; + --nmiss; + ++d.tail_experts; + } + } const bool pcie_ok = d.pcie_num > 0 && d.src->pcie_layer(d.layers); const int m = pcie_ok ? (nmiss * d.pcie_num) >> 8 : 0; int miss_rank = 0, groups = 0, entries = 0, fetches = 0; @@ -3308,6 +3469,11 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 const int32_t e = ids[i0]; int kd = -1; unsigned long long ptr = 0; + if (skip_d[q]) { // STRATA_ROUTE_TAIL_SKIP: neither copied nor computed + for (int64_t i = i0; i < n; ++i) + if (first_of[i] == i0) kind[i] = -2; + continue; + } if (e >= 0 && e < d.n_expert) { const int32_t slot = d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e]; if (slot >= 0) { @@ -3405,7 +3571,7 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 const bool gpu_zeroes_hits = (d.plan != nullptr && n <= kMaxWindowEntries && n <= d.plan->cap && dec_batch && !device_plan); bool any_cpu = false; for (int64_t i = 0; i < n; ++i) - if (kind[i] < 0) { any_cpu = true; break; } + if (kind[i] == -1) { any_cpu = true; break; } // -2: skipped (STRATA_ROUTE_TAIL_SKIP), no work const auto c1 = std::chrono::steady_clock::now(); if (any_cpu) { // #578 --remote-expert-opt: a token whose experts all run on a GPU (CUDA0 or a helper) needs no CPU activation @@ -3425,7 +3591,7 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 static thread_local std::vector miss; miss.clear(); for (int64_t i = 0; i < n_tok * k; ++i) - if (kind[i] < 0 && ids[i] >= 0 && ids[i] < d.n_expert && + if (kind[i] == -1 && ids[i] >= 0 && ids[i] < d.n_expert && std::find(miss.begin(), miss.end(), (int64_t) ids[i]) == miss.end()) miss.push_back(ids[i]); d.src->prefetch(d.layers, miss.data(), (int64_t) miss.size()); @@ -3443,6 +3609,11 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 d.fail_expert = e; return; } + if (kind[i] == -2) { // STRATA_ROUTE_TAIL_SKIP: a skipped tail expert contributes zero + std::memset(row, 0, (size_t) H * sizeof(float)); + ++d.tail_skipped; + continue; + } if (kind[i] >= 0) { // CUDA0, PCIe, or a remote/peer result staged into this row below if (kind[i] == 0) ++d.cache_hits; else ++d.offload_entries; // #588: PCIe or another GPU diff --git a/src/core/logit_bias_test.cpp b/src/core/logit_bias_test.cpp new file mode 100644 index 00000000..0d60c88e --- /dev/null +++ b/src/core/logit_bias_test.cpp @@ -0,0 +1,21 @@ +#include "strata/core/logit_bias.hpp" +#include +#include + +int main() { + std::vector b; + std::string err; + auto check = [](bool ok) { if (!ok) { std::fprintf(stderr, "logit_bias parser regression\n"); std::exit(1); } }; + check(strata::core::parse_logit_bias("0:-100,2:1.25,3:-0.5", 4, b, err)); + check(b.size() == 4 && std::isinf(b[0]) && b[0] < 0 && b[1] == 0 && b[2] == 1.25f && b[3] == -0.5f); + for (const char* text : {"", "0:", "0:NaN", "0:inf", "0:-101", "0:101", "4:0", "-1:0", "x:1", + "0:1,", "0:1,0:2", "0:1x", "0:-100,1:-100,2:-100,3:-100", "999999999999999999999:0"}) { + check(!strata::core::parse_logit_bias(text, 4, b, err)); + check(b.empty()); + } + std::string large; + for (int i = 0; i < 103215; ++i) { if (i) large += ','; large += std::to_string(i) + ":-100"; } + check(strata::core::parse_logit_bias(large, 248320, b, err)); + check(std::isinf(b[103214]) && b[103215] == 0 && b.size() == 248320); + std::puts("logit_bias_test: passed, including 103215 bans"); +} diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index 7d46389d..afd1ef72 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -1257,7 +1257,9 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* if (!mtp_catchup_all()) T = a + 1; const bool cp = coupled_active_; // coupled draft sampling for this request: its own graphs if (!capture_round(T, cp, err)) return false; - const int max_steps = std::min(max_t_ - 1, max_drafts_); + // Draft j writes its K/V at cell p + a + j, and the K/V ends at max_cells (its page table has no page past it): + // near the context's end the round drafts only the cells that exist + const int max_steps = (int) std::min(std::min(max_t_ - 1, max_drafts_), st_.max_cells - (p + a)); for (int j = 1; j < max_steps; ++j) if (!capture_step(j, cp, err)) return false; const Clock::time_point t0 = Clock::now(); diff --git a/src/core/remote_experts.cpp b/src/core/remote_experts.cpp index 1b6969e8..9af13abf 100644 --- a/src/core/remote_experts.cpp +++ b/src/core/remote_experts.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -93,6 +94,7 @@ void RemoteExperts::close() { DeviceScope scope(device_); if (scope.ok) { if (stream_) cudaStreamSynchronize(stream_); + if (read_stream_) cudaStreamSynchronize(read_stream_); cache_.close(); if (d_x_) cudaFree(d_x_); if (d_out_) cudaFree(d_out_); @@ -104,9 +106,11 @@ void RemoteExperts::close() { if (h_out_) cudaFreeHost(h_out_); if (h_meta_) cudaFreeHost(h_meta_); if (stream_) cudaStreamDestroy(stream_); + if (read_stream_) cudaStreamDestroy(read_stream_); } device_ = -1; stream_ = nullptr; + read_stream_ = nullptr; h_x_ = h_out_ = d_x_ = d_out_ = nullptr; h_meta_ = d_meta_ = nullptr; d_q8_ = nullptr; @@ -204,6 +208,10 @@ bool RemoteExperts::open(int device, int slots, int64_t layers, int64_t experts, check(cudaMalloc(&d_scratch_, scratch), "scratch", err, device) && check(cudaMalloc(&d_meta_, meta_bytes), "group metadata", err, device); if (!allocated) { close(); return false; } + if (!check(cudaStreamCreateWithFlags(&read_stream_, cudaStreamNonBlocking), "cache read stream", err, device)) { + close(); + return false; + } // Zero-copy: the helper reads its input from, and writes its compact rows into, the pinned host buffers // directly - two copies fewer per layer, each of which is a PCIe round trip. STRATA_REMOTE_ZEROCOPY=0 copies. const char* zc = std::getenv("STRATA_REMOTE_ZEROCOPY"); @@ -338,4 +346,111 @@ bool RemoteExperts::finish(float* out, std::string& err) { return true; } +bool RemoteExperts::copy_cached_blobs(const int32_t* layers, const int32_t* experts, uint8_t* const* dst, + size_t n, uint8_t* hit, std::string& err) { + std::fill(hit, hit + n, 0); + if (device_ < 0 || read_stream_ == nullptr || n == 0) return true; + const auto& lay = strata::kernels::cpu::expert_layout(); + DeviceScope scope(device_); + if (!scope.ok) { err = scope.error(device_); return false; } + std::lock_guard lock(read_mu_); + bool queued = false; + for (size_t i = 0; i < n; ++i) { + if (dst[i] == nullptr) continue; + const int32_t slot = cache_.slot_of(layers[i], experts[i]); + if (slot < 0) continue; + const size_t bytes = (size_t) lay.blob_bytes(layers[i]); + if (!check(cudaMemcpyAsync(dst[i], cache_.device_slot(slot), bytes, cudaMemcpyDeviceToHost, read_stream_), + "cache read", err, device_)) { + // Nothing may still be writing a caller's buffer when this returns. If the drain succeeds, the + // hits queued before the failure are complete and the caller may keep them; if it does not, + // forget every hit and let the caller refill all of them from its fallback. + if (cudaStreamSynchronize(read_stream_) != cudaSuccess) std::fill(hit, hit + n, 0); + return false; + } + hit[i] = 1; + queued = true; + } + if (queued && !check(cudaStreamSynchronize(read_stream_), "cache read wait", err, device_)) { + std::fill(hit, hit + n, 0); // a failed wait means no copied buffer may be trusted + return false; + } + return true; +} + +bool RemotePrefillSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) { + if (dst != nullptr && from_helper(layer, expert)) { + const int32_t l = (int32_t) layer, e = (int32_t) expert; + uint8_t* d = dst; + std::string err; + for (RemoteExperts* h : helpers_) { + uint8_t got = 0; + const bool ok = h->copy_cached_blobs(&l, &e, &d, 1, &got, err); + if (got) { + helper_blobs_.fetch_add(1, std::memory_order_relaxed); + helper_bytes_.fetch_add(strata::kernels::cpu::expert_layout().blob_bytes(layer), + std::memory_order_relaxed); + return true; + } + if (!ok) break; + } + warn(err); + } + return fallback_.copy_blob(layer, expert, dst); +} + +bool RemotePrefillSource::copy_blobs(const int32_t* layers, const int32_t* experts, uint8_t* const* dst, size_t n) { + if (helpers_.empty() || n == 0) return fallback_.copy_blobs(layers, experts, dst, n); + thread_local std::vector hl, he; + thread_local std::vector hd; + thread_local std::vector idx; + thread_local std::vector got; + thread_local std::vector served; + thread_local std::vector ml, me; + thread_local std::vector md; + thread_local std::vector which; + which.assign(n, -1); + served.assign(n, 0); + for (size_t i = 0; i < n; ++i) { + if (dst[i] == nullptr) continue; + for (size_t k = 0; k < helpers_.size(); ++k) + if (helpers_[k]->holds(layers[i], experts[i])) { which[i] = (int) k; break; } + } + // One stream batch per helper, so several hits pay one wait; the misses go to the file source in one + // call, which keeps its own batched-read merging for them. + uint64_t blobs = 0, bytes = 0; + const auto& lay = strata::kernels::cpu::expert_layout(); + for (size_t k = 0; k < helpers_.size(); ++k) { + hl.clear(); he.clear(); hd.clear(); idx.clear(); + for (size_t i = 0; i < n; ++i) + if (which[i] == (int) k) { + hl.push_back(layers[i]); he.push_back(experts[i]); hd.push_back(dst[i]); idx.push_back(i); + } + if (hl.empty()) continue; + got.assign(hl.size(), 0); + std::string err; + if (!helpers_[k]->copy_cached_blobs(hl.data(), he.data(), hd.data(), hl.size(), got.data(), err)) warn(err); + for (size_t j = 0; j < got.size(); ++j) + if (got[j]) { + served[idx[j]] = 1; + ++blobs; + bytes += lay.blob_bytes(hl[j]); + } + } + if (blobs != 0) { + helper_blobs_.fetch_add(blobs, std::memory_order_relaxed); + helper_bytes_.fetch_add(bytes, std::memory_order_relaxed); + } + ml.clear(); me.clear(); md.clear(); + for (size_t i = 0; i < n; ++i) + if (!served[i]) { ml.push_back(layers[i]); me.push_back(experts[i]); md.push_back(dst[i]); } + if (ml.empty()) return true; + return fallback_.copy_blobs(ml.data(), me.data(), md.data(), ml.size()); +} + +void RemotePrefillSource::warn(const std::string& err) { + if (err.empty() || warned_.exchange(true)) return; + std::fprintf(stderr, "prefill: a helper cache read failed (%s); the file source fills that blob instead\n", + err.c_str()); +} } // namespace strata::core diff --git a/src/core/verify.cpp b/src/core/verify.cpp index bc84c361..a6e36289 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -18,6 +18,7 @@ #include "strata/kernels/cpu/expert.hpp" #include "strata/kernels/elementwise.hpp" #include "strata/kernels/fused_gr.hpp" +#include "strata/kernels/route_prior.hpp" #include "strata/kernels/cvec.hpp" #include "strata/kernels/gr.hpp" #include "strata/kernels/kv_q4.hpp" @@ -417,6 +418,7 @@ Verifier::~Verifier() { if (h_commitb_) cudaFreeHost(h_commitb_); if (qcnt_) cudaFree(qcnt_); if (d_spec_) cudaFree(d_spec_); + if (logit_bias_device_) cudaFree(logit_bias_device_); if (cs_ && cs_ != ext_stream_) cudaStreamDestroy(cs_); // set_stream: the stage's stream, shared, not ours if (sh_cs_) cudaStreamDestroy(sh_cs_); if (copy_) { cudaStreamSynchronize(copy_); cudaStreamDestroy(copy_); } @@ -438,6 +440,25 @@ Verifier::~Verifier() { if (h) cudaFreeHost(h); } +bool Verifier::set_logit_bias(const std::vector& bias, std::string& err) { + if (next_ && !next_->set_logit_bias(bias, err)) return false; + if (le_ < g_->n_layers) return true; + const OnDevice on_device(device_); + if (!bias.empty() && bias.size() != (size_t) n_vocab_) { + err = "logit_bias vocabulary size mismatch"; return false; + } + if (bias != logit_bias_host_ && !bias.empty()) { + const size_t bytes = bias.size() * sizeof(float); + if ((!logit_bias_device_ && cudaMalloc((void**) &logit_bias_device_, bytes) != cudaSuccess) || + cudaMemcpy(logit_bias_device_, bias.data(), bytes, cudaMemcpyHostToDevice) != cudaSuccess) { + err = "cannot upload logit_bias"; return false; + } + } + logit_bias_host_ = bias; + sampling_.logit_bias = bias.empty() ? nullptr : logit_bias_device_; + return true; +} + bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& ss, const VerifyHits& hits, const NativeHead* head, int max_t, std::string& err) { g_diag_verifier.store(this); @@ -739,7 +760,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { const bool ple_on = ss.ple.ready() && ple_stage(); auto Rt = [&](int t) { return R_ + (size_t) t * HC * N; }; const int G = (split_ && T >= 2 && !batch_rec_) ? 2 : 1; // a batch window is one group - const bool self_commit = T == 1 && !batch_rec_ && !g_qfuse() && one_token_self_commit(); // see Verifier::commit + // Pipelined windows must wait for the host verdict/snapshot fence before mutating state. + const bool self_commit = T == 1 && !always_publish_ && !batch_rec_ && !g_qfuse() && one_token_self_commit(); // see Verifier::commit static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }(); auto stamp = [&](int64_t l, int i, int grp) { if (prof_on_ && grp == 0) gpu_stamp(prof_, (int) (l * kProfPer + i), cs); @@ -1346,6 +1368,11 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { mb.logits = logits_ + t * NE; mb.ids = ids_ + t * K; mb.weights = w_ + t * K; if (!moe_route(wt, g, l, K, mb, mixed_ + t * N, cs, err, nullptr)) return false; } + // STRATA_ROUTE_PRIOR=lambda (opt-in, changes the output): the top-10 picked again with a logit bonus for the + // resident experts; the weights stay the router's (route_prior.cu) + static const float route_prior = [] { const char* v = std::getenv("STRATA_ROUTE_PRIOR"); return v ? (float) std::atof(v) : 0.0f; }(); + if (route_prior > 0.0f && NE == 512 && K == 10 && hits_.d_res != nullptr) + route_prior_top10(logits_ + tb * NE, hits_.d_res + l * g.n_expert, route_prior, ids_ + tb * K, w_ + tb * K, n, cs); if (route_resident_cfg().margin > 0.0f && NE == 512 && K == 10 && hits_.d_res != nullptr) { // STRATA_ROUTE_RESIDENT: after the router, before the plan/doorbell read ids_/w_ (opt-in, changes the output) try { @@ -2101,7 +2128,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, return next_ == nullptr || next_->run(T, tokens, pos0, pool, next_user_, out, err); } const bool sampled = !sampling_.greedy && sampling_.temperature > 0.0f; - if (head_sampling_ && (sampled || hist_d_ != nullptr)) { + if (head_sampling_ && (sampled || hist_d_ != nullptr || sampling_.logit_bias != nullptr)) { SamplerParams sp = sampling_; sp.counter = (uint64_t) pos0; // STRATA_SPEC_PROB: the drafter's q lists for this window, judged by rejection sampling (spec_prob.hpp) @@ -2294,7 +2321,7 @@ bool Verifier::commit(int n_keep, std::string& err) { h_commit_[0] = n_keep; h_commit_[1] = n_keep - 1; for (int t = 0; t < max_t_; ++t) h_commit_[2 + t] = t < n_keep ? (int32_t) (last_pos0_ + t) : -1; - if (last_t_ == 1 && one_token_self_commit()) { + if (last_t_ == 1 && !always_publish_ && one_token_self_commit()) { // a one-token window has advanced the state itself (record_window): no commit graph } else { std::atomic_thread_fence(std::memory_order_seq_cst); @@ -2717,7 +2744,11 @@ bool Verifier::run_slot_rows(const int* rows, int S, const int32_t* tokens, cons cur_layer_ = want - 1; set_plan_slot(0); progress_at("verify batch: the CPU experts of layer", l); + // The recorded graph consumes the helper mask and weighted sum just as + // the solo graph does. Reset both and supply this layer's routing weights. + if (remote_opt_) remote_opt_->begin(h_w_, 0, S); if (pool != nullptr) pool(user, h_x_, h_ids_, S, ss_->k, h_ymiss_, l); + if (remote_opt_) remote_opt_->end(); progress_tick(); std::atomic_thread_fence(std::memory_order_seq_cst); _mm_sfence(); @@ -2869,7 +2900,9 @@ int Verifier::batch_poll(PoolMultiFn pool, void* user, std::string& err) { const Clock::time_point b = Clock::now(); cur_layer_ = want - 1; set_plan_slot(0); + if (remote_opt_) remote_opt_->begin(h_w_, 0, S); if (pool != nullptr) pool(user, h_x_, h_ids_, S, ss_->k, h_ymiss_, lb_ + b_k_); + if (remote_opt_) remote_opt_->end(); progress_tick(); std::atomic_thread_fence(std::memory_order_seq_cst); _mm_sfence(); @@ -3143,7 +3176,7 @@ bool Verifier::pl_finish(int32_t* out, std::string& err) { if (le_ < g.n_layers) return true; // an earlier stage: the hand-off is written const int T = fl_T_; const bool sampled = !sampling_.greedy && sampling_.temperature > 0.0f; - if (head_sampling_ && (sampled || hist_d_ != nullptr)) { // run()'s host-side sampling, Philox(seed, pos0 + t) + if (head_sampling_ && (sampled || hist_d_ != nullptr || sampling_.logit_bias != nullptr)) { // run()'s host-side sampling, Philox(seed, pos0 + t) SamplerParams sp = sampling_; sp.counter = (uint64_t) last_pos0_; sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_); diff --git a/src/kernels/cpu/expert_layout.cpp b/src/kernels/cpu/expert_layout.cpp index 4e13167a..d8adb260 100644 --- a/src/kernels/cpu/expert_layout.cpp +++ b/src/kernels/cpu/expert_layout.cpp @@ -348,12 +348,21 @@ void cpu_require_expert_support() { void q2_rows_any(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, float* const* out, int r0, int r1) { if (cpu_avx512_ok()) q2_0_gguf_rows_multi(w, row_bytes, nblocks, a, nt, out, r0, r1); - else q2_0_gguf_rows_multi_avx2(w, row_bytes, nblocks, a, nt, out, r0, r1); + else if (cpu_avx2_ok()) q2_0_gguf_rows_multi_avx2(w, row_bytes, nblocks, a, nt, out, r0, r1); + else q2_0_gguf_rows_multi_avx1(w, row_bytes, nblocks, a, nt, out, r0, r1); // issue #1699: the third rung +} + +void q2_rows_any_legacy(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, float* const* out, + int r0, int r1) { + if (cpu_avx512_ok()) q2_0_gguf_rows_multi(w, row_bytes, nblocks, a, nt, out, r0, r1); + else if (cpu_avx2_ok()) q2_0_gguf_rows_multi_avx2_legacy(w, row_bytes, nblocks, a, nt, out, r0, r1); + else q2_0_gguf_rows_multi_avx1_legacy(w, row_bytes, nblocks, a, nt, out, r0, r1); } void act_quant_any(const float* x, int n, ActQ& a) { if (cpu_avx512_ok()) act_quant_q8_1(x, n, a); - else act_quant_q8_1_avx2(x, n, a); + else if (cpu_avx2_ok()) act_quant_q8_1_avx2(x, n, a); + else act_quant_q8_1_avx1(x, n, a); // issue #1699 } #if !defined(STRATA_NATIVE_EXPERTS) diff --git a/src/kernels/cpu/iq_avx1.cpp b/src/kernels/cpu/iq_avx1.cpp new file mode 100644 index 00000000..f80cc652 --- /dev/null +++ b/src/kernels/cpu/iq_avx1.cpp @@ -0,0 +1,511 @@ +// src/kernels/cpu/iq_avx1.cpp - the i-quant expert rows for CPUs without AVX2 (STRATA_ISA_FLOOR=avx: +// Sandy/Ivy Bridge, Xeon E5 v1/v2, Bulldozer). See iq_avx1.hpp. +// +// iq_avx2.cpp's multi-token scheme in 128-bit lanes: each 32-value chunk is decoded once per verify window +// (grid lookups, one sign vector, one scale vector) and every token applies it with a load, a sign, a +// maddubs, a madd and an add - all SSSE3/SSE2, all available since Core 2. The 256-bit integer ops of the +// AVX2 kernel (pshufb/maddubs/sign_epi8 in __m256i, vpgather, vpdpbusd) have no AVX1 form and no FMA exists +// there, so the float accumulation is a plain SSE2 mul+add. Without these kernels such a CPU runs every +// expert on ggml-cpu's scalar `_generic` dots (every x86 i-quant dot is #if defined(__AVX2__)). +// +// The arithmetic is ggml's (ggml-cpu/quants.c, the `_generic` references) - only the order of the float +// additions differs; the integer sums are exact. iq_avx1_parity checks: rows vs ggml-cpu's dot rel <= 1e-5, +// and a multi-token row bit for bit the same kernel's single-token row for that token (#152). +// +// Formats: gate/up IQ3_XXS (18), IQ3_S (21), IQ2_S (22), IQ4_XS (23); down IQ4_NL (20) and Q2_0 (42, the +// fork's type). IQ2_XXS/IQ2_XS have no layer in the packs that need this and stay on ggml-cpu's dot. +// +// This file is compiled for SSE4.2 + AVX with AVX2/FMA/F16C explicitly off (CMakeLists.txt), and the engine +// calls it only behind cpu_avx1_ok(). No static constructors at namespace scope (#391): the tables below +// are constexpr, like iq_avx2.cpp's. +#include "strata/kernels/cpu/iq_avx1.hpp" + +#include "ggml.h" + +#define GGML_COMMON_DECL_CPP +#define GGML_COMMON_IMPL_CPP +#include "ggml-common.h" + +#include + +#include +#include +#include + +#if !defined(__AVX__) +#error "iq_avx1.cpp must be compiled with AVX enabled (see the per-source flags in CMakeLists.txt)" +#endif +#if defined(__FMA__) || defined(__F16C__) +#error "iq_avx1.cpp must be compiled without FMA/F16C: it runs on CPUs (Sandy/Ivy Bridge) that lack them" +#endif + +namespace strata::kernels::cpu { +namespace { + +// fp16 -> fp32 without F16C (expert.cpp's h2f: the conversion written out, subnormals included). +inline float h2f(uint16_t h) { + const uint32_t sign = (uint32_t) (h >> 15) & 1u; + uint32_t exp = (h >> 10) & 0x1Fu, man = h & 0x3FFu, f; + if (exp == 0) { + if (man == 0) { + f = sign << 31; + } else { + exp = 127 - 15 + 1; + while (!(man & 0x400u)) { man <<= 1; --exp; } + man &= 0x3FFu; + f = (sign << 31) | (exp << 23) | (man << 13); + } + } else if (exp == 31) { + f = (sign << 31) | 0x7F800000u | (man << 13); + } else { + f = (sign << 31) | ((exp - 15 + 127) << 23) | (man << 13); + } + float out; + std::memcpy(&out, &f, 4); + return out; +} + +inline uint32_t u32(const uint8_t* p) { uint32_t v; std::memcpy(&v, p, 4); return v; } +inline uint16_t u16(const uint8_t* p) { uint16_t v; std::memcpy(&v, p, 2); return v; } +inline uint64_t u64(const uint8_t* p) { uint64_t v; std::memcpy(&v, p, 8); return v; } + +// The sign-vector pattern of iq_avx2.cpp's sgn_vec_at in 128-bit: 16 values from two sign bytes. +// bits = the two bytes broadcast over the 16 lanes, sel = bit k of each byte per lane, -> 16 bytes of +// -1 (bit set) / +1. ggml's bit_selector pattern, same bits. +inline __m128i sgn16(uint32_t w, int byte_pair) { // byte_pair 0: bytes 0-1 (values 0-15), 1: bytes 2-3 + const __m128i bits = _mm_shuffle_epi8(_mm_set1_epi32((int) w), + byte_pair ? _mm_setr_epi8(2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3) + : _mm_setr_epi8(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1)); + const __m128i sel = _mm_setr_epi8(1, 2, 4, 8, 16, 32, 64, (char) 0x80, 1, 2, 4, 8, 16, 32, 64, (char) 0x80); + return _mm_or_si128(_mm_cmpeq_epi8(_mm_and_si128(bits, sel), sel), _mm_set1_epi8(1)); +} + +// keven_signs_q2xs as a constexpr table (iq_avx2.cpp's EvenSigns; byte k = 0xFF when bit k of +// ksigns_iq2xs[i] is set, 0x01 otherwise). constexpr, not a runtime constructor (#391). +struct EvenSigns { + uint64_t v[128]; + constexpr EvenSigns() : v{} { + for (int i = 0; i < 128; ++i) { + int par = 0; + for (int k = 0; k < 7; ++k) par ^= (i >> k) & 1; + const int s = i | (par << 7); // == ksigns_iq2xs[i] + uint64_t r = 0; + for (int k = 0; k < 8; ++k) r |= (uint64_t) (((s >> k) & 1) ? 0xFF : 0x01) << (8 * k); + v[i] = r; + } + } +}; +static constexpr EvenSigns even_signs{}; +static_assert(even_signs.v[0] == 0x0101010101010101ull && even_signs.v[1] == 0xFF010101010101FFull, + "keven_signs_q2xs: byte k = 0xFF when bit k of ksigns_iq2xs[i] is set"); + +// The high index bits of a 32-value half spread one per byte (iq_avx2.cpp's HiSpread): punpcklbw puts them +// next to the low index bytes, so every grid index is a 16-bit load. IQ3_S: byte k = bit k (the 9th bit of +// index k). IQ2_S: byte k = bits 2k,2k+1 (bits 8-9 of index k), k < 4. +struct HiSpread { + uint64_t iq3s[256]; + uint64_t iq2s[256]; + constexpr HiSpread() : iq3s{}, iq2s{} { + for (int h = 0; h < 256; ++h) { + uint64_t r3 = 0, r2 = 0; + for (int k = 0; k < 8; ++k) r3 |= (uint64_t) ((h >> k) & 1) << (8 * k); + for (int k = 0; k < 4; ++k) r2 |= (uint64_t) ((h >> (2 * k)) & 3) << (8 * k); + iq3s[h] = r3; + iq2s[h] = r2; + } + } +}; +static constexpr HiSpread hi_spread{}; +static_assert(hi_spread.iq3s[0x81] == 0x0100000000000001ull && hi_spread.iq2s[0xE4] == 0x0000000003020100ull, + "hi_spread: one high-bit group per index byte"); + +// The low index bytes interleaved with the spread high bits: eight 16-bit grid indices in one register. +// (iq_avx2.cpp's grid_indices stores them to memory; on Ivy Bridge that store -> narrow-load round trip +// costs a forwarding stall per index, so the decoders below read the lanes with _mm_extract_epi16 instead.) +inline __m128i grid_idx(const uint8_t* q, uint64_t hi) { + return _mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i*) q), _mm_cvtsi64_si128((long long) hi)); +} + +inline float hsum4(__m128 v) { + __m128 s = _mm_add_ps(v, _mm_movehl_ps(v, v)); + s = _mm_add_ss(s, _mm_movehdup_ps(s)); + return _mm_cvtss_f32(s); +} + +// E-2 prefetching, the same knob as the AVX-2/512 kernels: STRATA_IQ_PREFETCH is the distance in bytes. +int prefetch_distance() { + static const int d = [] { + const char* v = std::getenv("STRATA_IQ_PREFETCH"); + return v ? std::atoi(v) : 2048; + }(); + return d; +} + +inline void rows_ahead(const uint8_t* blk, int pf) { + if (pf <= 0) return; + _mm_prefetch((const char*) blk + pf, _MM_HINT_T0); + _mm_prefetch((const char*) blk + pf + 64, _MM_HINT_T0); +} + +// ---- per format: one 32-value half (values 64*j + 32*half .. +31) -> grid magnitudes, sign vector and +// scales as TWO 16-value halves (g0/g1, s0/s1, c0/c1). +template struct Fmt128; + +template <> struct Fmt128<18> { // IQ3_XXS: d, qs[64] grid bytes, 8 x u32 (4 x 7-bit sign index + 4-bit scale) + static constexpr int bytes = 98; + static constexpr float K = 0.25f; + static inline void decode(const uint8_t* b, int j, int half, + __m128i& g0, __m128i& g1, __m128i& s0, __m128i& s1, __m128i& c0, __m128i& c1) { + const uint8_t* q = b + 2 + 16 * j + 8 * half; + g0 = _mm_set_epi32((int) iq3xxs_grid[q[3]], (int) iq3xxs_grid[q[2]], + (int) iq3xxs_grid[q[1]], (int) iq3xxs_grid[q[0]]); + g1 = _mm_set_epi32((int) iq3xxs_grid[q[7]], (int) iq3xxs_grid[q[6]], + (int) iq3xxs_grid[q[5]], (int) iq3xxs_grid[q[4]]); + const uint32_t w = u32(b + 2 + 64 + 8 * j + 4 * half); + s0 = _mm_set_epi64x((long long) even_signs.v[(w >> 7) & 127], (long long) even_signs.v[w & 127]); + s1 = _mm_set_epi64x((long long) even_signs.v[(w >> 21) & 127], (long long) even_signs.v[(w >> 14) & 127]); + c0 = c1 = _mm_set1_epi16((short) (2 * (int) (w >> 28) + 1)); + } +}; + +template <> struct Fmt128<21> { // IQ3_S: d, qs[64], qh[8], signs[32], scales[4] + static constexpr int bytes = 110; + static constexpr float K = 1.0f; + static inline void decode(const uint8_t* b, int j, int half, + __m128i& g0, __m128i& g1, __m128i& s0, __m128i& s1, __m128i& c0, __m128i& c1) { + const uint8_t* q = b + 2 + 16 * j + 8 * half; + const __m128i idx = grid_idx(q, hi_spread.iq3s[b[66 + 2 * j + half]]); +#define G3(k) (int) iq3s_grid[_mm_extract_epi16(idx, k)] + g0 = _mm_set_epi32(G3(3), G3(2), G3(1), G3(0)); + g1 = _mm_set_epi32(G3(7), G3(6), G3(5), G3(4)); +#undef G3 + const uint32_t sg = u32(b + 74 + 8 * j + 4 * half); + s0 = sgn16(sg, 0); + s1 = sgn16(sg, 1); + const uint8_t s = b[106 + j]; + c0 = c1 = _mm_set1_epi16((short) (2 * (int) (half ? s >> 4 : s & 15) + 1)); + } +}; + +template <> struct Fmt128<22> { // IQ2_S: d, qs[64] (32 grid bytes, 32 sign bytes), qh[8], scales[8] + static constexpr int bytes = 82; + static constexpr float K = 0.125f; + static inline void decode(const uint8_t* b, int j, int half, + __m128i& g0, __m128i& g1, __m128i& s0, __m128i& s1, __m128i& c0, __m128i& c1) { + // only the first 4 index bytes are this half's (the load's rest stays inside the block) + const __m128i idx = grid_idx(b + 2 + 8 * j + 4 * half, hi_spread.iq2s[b[66 + 2 * j + half]]); + g0 = _mm_set_epi64x((long long) iq2s_grid[_mm_extract_epi16(idx, 1)], + (long long) iq2s_grid[_mm_extract_epi16(idx, 0)]); + g1 = _mm_set_epi64x((long long) iq2s_grid[_mm_extract_epi16(idx, 3)], + (long long) iq2s_grid[_mm_extract_epi16(idx, 2)]); + const uint32_t sg = u32(b + 2 + 32 + 8 * j + 4 * half); + s0 = sgn16(sg, 0); + s1 = sgn16(sg, 1); + const uint8_t sb = b[74 + 2 * j + half]; + c0 = _mm_set1_epi16((short) (2 * (sb & 15) + 1)); + c1 = _mm_set1_epi16((short) (2 * (sb >> 4) + 1)); + } +}; + +template <> struct Fmt128<23> { // IQ4_XS: d, scales_h, scales_l[4], qs[128] - 136 B, 8 signed sub-scales + // ggml's ggml_vec_dot_iq4_xs_q8_K: the same 16-value codebook as IQ4_NL, one 6-bit scale per 32-value + // sub-block read as two nibbles of scales_l plus two bits of scales_h, used SIGNED as (ls - 32): the + // scale folds into the int16 operand of madd_epi16. The codebook sign rides on sign_epi8, |w| is the + // unsigned maddubs operand (a pair is at most 2 * 127 * 128, no saturation). + static constexpr int bytes = 136; + static constexpr float K = 1.0f; + static inline void decode(const uint8_t* b, int j, int half, + __m128i& g0, __m128i& g1, __m128i& s0, __m128i& s1, __m128i& c0, __m128i& c1) { + const int H = 2 * j + half; + const __m128i values = _mm_loadu_si128((const __m128i*) kvalues_iq4nl); + const __m128i bits = _mm_loadu_si128((const __m128i*) (b + 8 + 16 * H)); + const __m128i m4 = _mm_set1_epi8(0x0f); + const __m128i v0 = _mm_shuffle_epi8(values, _mm_and_si128(bits, m4)); + const __m128i v1 = _mm_shuffle_epi8(values, _mm_and_si128(_mm_srli_epi16(bits, 4), m4)); + g0 = _mm_sign_epi8(v0, v0); + g1 = _mm_sign_epi8(v1, v1); + s0 = _mm_sign_epi8(_mm_set1_epi8(1), v0); + s1 = _mm_sign_epi8(_mm_set1_epi8(1), v1); + const int ls = ((b[4 + (H >> 1)] >> (4 * (H & 1))) & 0xf) | (((u16(b + 2) >> (2 * H)) & 3) << 4); + c0 = c1 = _mm_set1_epi16((short) (ls - 32)); + } +}; + +// acc + madd(maddubs(g, sign(y, sgn)), sc): the AVX2 kernel's per-token application in 128-bit. +inline __m128i madd_add(__m128i acc, __m128i g, __m128i sgn, __m128i yv, __m128i sc) { + return _mm_add_epi32(acc, _mm_madd_epi16(_mm_maddubs_epi16(g, _mm_sign_epi8(yv, sgn)), sc)); +} + +// ---- the row kernels (iq_avx2_rows.inl's row_dot in 128-bit lanes) +template +inline void row_dot(const uint8_t* row, int nblocks, const block_q8_K* const* y, float* res) { + const int pf = prefetch_distance(); + __m128 accf[NT]; + for (int t = 0; t < NT; ++t) accf[t] = _mm_setzero_ps(); + for (int i = 0; i < nblocks; ++i) { + const uint8_t* blk = row + (size_t) i * Fmt128::bytes; + rows_ahead(blk, pf); + __m128i acci[NT][2]; + for (int t = 0; t < NT; ++t) acci[t][0] = acci[t][1] = _mm_setzero_si128(); + for (int j = 0; j < 4; ++j) { + for (int half = 0; half < 2; ++half) { + __m128i g0, g1, s0, s1, c0, c1; + Fmt128::decode(blk, j, half, g0, g1, s0, s1, c0, c1); + const int off = 64 * j + 32 * half; + for (int t = 0; t < NT; ++t) { + const uint8_t* q8 = (const uint8_t*) (y[t][i].qs + off); + acci[t][0] = madd_add(acci[t][0], g0, s0, _mm_loadu_si128((const __m128i*) q8), c0); + acci[t][1] = madd_add(acci[t][1], g1, s1, _mm_loadu_si128((const __m128i*) (q8 + 16)), c1); + } + } + } + const float dx = h2f(u16(blk)) * Fmt128::K; + for (int t = 0; t < NT; ++t) { + const __m128 f = _mm_add_ps(_mm_cvtepi32_ps(acci[t][0]), _mm_cvtepi32_ps(acci[t][1])); + accf[t] = _mm_add_ps(accf[t], _mm_mul_ps(_mm_set1_ps(dx * y[t][i].d), f)); + } + } + for (int t = 0; t < NT; ++t) res[t] = hsum4(accf[t]); +} + +template +inline void gu_rows(const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, + float* const* ff, int r0, int r1) { + const block_q8_K* y[NT]; + for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t]; + const int nb = n / QK_K; + float g[NT], u[NT]; + for (int r = r0; r < r1; ++r) { + row_dot(blob + (size_t) r * gu_row, nb, y, g); + row_dot(blob + up_off + (size_t) r * gu_row, nb, y, u); + for (int t = 0; t < NT; ++t) ff[t][r] = (g[t] / (1.f + std::exp(-g[t]))) * u[t]; + } +} + +template +inline void dot_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out, + int r0, int r1) { + const block_q8_K* y[NT]; + for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t]; + float res[NT]; + for (int r = r0; r < r1; ++r) { + row_dot(w + (size_t) r * row_bytes, n / QK_K, y, res); + for (int t = 0; t < NT; ++t) out[t][r] = res[t]; + } +} + +template +void gu_rows_nt(int nt, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, + float* const* ff, int r0, int r1) { + switch (nt) { + case 1: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 2: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 3: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 4: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 5: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 6: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 7: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + default: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + } +} + +// ---- IQ4_NL (20) down rows against Q8_0: ggml's dot is single-token even where it is vectorized (and +// scalar here); decode the nibbles once, every token pays a sign, a maddubs, a madd and an fmadd-equivalent. +template +void iq4nl_rows(const uint8_t* w, size_t row_bytes, int n, const block_q8_0* const* y, float* const* out, + int r0, int r1) { + const __m128i values = _mm_loadu_si128((const __m128i*) kvalues_iq4nl); + const __m128i m4b = _mm_set1_epi8(0x0f); + const __m128i ones = _mm_set1_epi16(1); + const int nb = n / QK4_NL; + const int pf = prefetch_distance(); + for (int r = r0; r < r1; ++r) { + const uint8_t* row = w + (size_t) r * row_bytes; + __m128 accf[NT]; + for (int t = 0; t < NT; ++t) accf[t] = _mm_setzero_ps(); + for (int ib = 0; ib < nb; ++ib) { + const uint8_t* blk = row + (size_t) ib * sizeof(block_iq4_nl); + rows_ahead(blk, pf); + const __m128i bits = _mm_loadu_si128((const __m128i*) (blk + 2)); + const __m128i v0 = _mm_shuffle_epi8(values, _mm_and_si128(bits, m4b)); + const __m128i v1 = _mm_shuffle_epi8(values, _mm_and_si128(_mm_srli_epi16(bits, 4), m4b)); + const __m128i aq0 = _mm_sign_epi8(v0, v0); // |w|: the unsigned maddubs operand + const __m128i aq1 = _mm_sign_epi8(v1, v1); + const float dx = h2f(u16(blk)); + for (int t = 0; t < NT; ++t) { + const uint8_t* q8 = (const uint8_t*) y[t][ib].qs; + const __m128i p0 = _mm_madd_epi16(_mm_maddubs_epi16(aq0, _mm_sign_epi8(_mm_loadu_si128((const __m128i*) q8), v0)), ones); + const __m128i p1 = _mm_madd_epi16(_mm_maddubs_epi16(aq1, _mm_sign_epi8(_mm_loadu_si128((const __m128i*) (q8 + 16)), v1)), ones); + const __m128 f = _mm_add_ps(_mm_cvtepi32_ps(p0), _mm_cvtepi32_ps(p1)); + accf[t] = _mm_add_ps(accf[t], _mm_mul_ps(_mm_set1_ps(dx * h2f(y[t][ib].d)), f)); + } + } + for (int t = 0; t < NT; ++t) out[t][r] = hsum4(accf[t]); + } +} + +// ---- Q2_0 (42) down rows against Q8_0: ggml-cpu has only the scalar generic dot for this type on x86. +// Codes {0,1,2,3} map to {c-1}: unpack to unsigned code bytes, dot them with maddubs, and subtract the +// activation's pair sums - all integer, so the per-block sum is EXACTLY the generic dot's sumi_block. +template +void q2_0_rows(const uint8_t* w, size_t row_bytes, int n, const block_q8_0* const* y, float* const* out, + int r0, int r1) { + const __m128i m3 = _mm_set1_epi8(3); + const __m128i ones = _mm_set1_epi16(1); + const int nb = n / QK2_0; + const int pf = prefetch_distance(); + for (int r = r0; r < r1; ++r) { + const uint8_t* row = w + (size_t) r * row_bytes; + __m128 accf[NT]; + for (int t = 0; t < NT; ++t) accf[t] = _mm_setzero_ps(); + for (int i = 0; i < nb; ++i) { + const uint8_t* blk = row + (size_t) i * sizeof(block_q2_0); + rows_ahead(blk, pf); + const float dx = h2f(u16(blk)); + const uint8_t* qs = blk + 2; + for (int k = 0; k < 2; ++k) { + // 8 code bytes -> 32 unsigned codes in order (c0..c3 = the four 2-bit groups of each byte) + const __m128i q = _mm_cvtsi64_si128((long long) u64(qs + 8 * k)); + const __m128i c0 = _mm_and_si128(q, m3); + const __m128i c1 = _mm_and_si128(_mm_srli_epi16(q, 2), m3); + const __m128i c2 = _mm_and_si128(_mm_srli_epi16(q, 4), m3); + const __m128i c3 = _mm_and_si128(_mm_srli_epi32(q, 6), m3); + const __m128i t01 = _mm_unpacklo_epi8(c0, c1); + const __m128i t23 = _mm_unpacklo_epi8(c2, c3); + const __m128i k0 = _mm_unpacklo_epi16(t01, t23); // codes 0..15 + const __m128i k1 = _mm_unpackhi_epi16(t01, t23); // codes 16..31 + for (int t = 0; t < NT; ++t) { + const uint8_t* q8 = (const uint8_t*) y[t][i * 2 + k].qs; + const __m128i y0 = _mm_loadu_si128((const __m128i*) q8); + const __m128i y1 = _mm_loadu_si128((const __m128i*) (q8 + 16)); + // (c-1)*qy per pair: c*qy - qy, both at int16 level (|result| <= 508, no saturation) + const __m128i d0 = _mm_sub_epi16(_mm_maddubs_epi16(k0, y0), _mm_maddubs_epi16(_mm_set1_epi8(1), y0)); + const __m128i d1 = _mm_sub_epi16(_mm_maddubs_epi16(k1, y1), _mm_maddubs_epi16(_mm_set1_epi8(1), y1)); + const __m128 f = _mm_add_ps(_mm_cvtepi32_ps(_mm_madd_epi16(d0, ones)), + _mm_cvtepi32_ps(_mm_madd_epi16(d1, ones))); + accf[t] = _mm_add_ps(accf[t], _mm_mul_ps(_mm_set1_ps(dx * h2f(y[t][i * 2 + k].d)), f)); + } + } + } + for (int t = 0; t < NT; ++t) out[t][r] = hsum4(accf[t]); + } +} + +} // namespace + +bool iq128_supported(int type) noexcept { + // IQ4_XS (23) is deliberately NOT here: its ggml generic dot auto-vectorizes well and beats the 128-bit + // grid kernel (0.7-1.0x in iq_avx1_parity --bench on an E5-2470 v2); the generic stays for that format's + // gate/up rows. Its down rows (IQ4_NL/Q2_0) still take iq128_down_rows. The kernel itself stays built + // and parity-tested. + return type == 18 || type == 21 || type == 22; +} + +bool iq128_down_supported(int type) noexcept { + return type == 20 || type == 42; +} + +void iq128_gu_rows(int type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, + int nt, float* const* ff, int r0, int r1) { + switch (type) { + case 18: gu_rows_nt<18>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 21: gu_rows_nt<21>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 22: gu_rows_nt<22>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 23: gu_rows_nt<23>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; + default: break; + } +} + +void iq128_down_rows(int type, const uint8_t* w, size_t row_bytes, int n, const void* const* hq, int nt, + float* const* out, int r0, int r1) { + const block_q8_0* y[8]; + for (int t = 0; t < nt && t < 8; ++t) y[t] = (const block_q8_0*) hq[t]; + if (type == 20) { + for (int t0 = 0; t0 < nt; t0 += 4) { + const int k = nt - t0 < 4 ? nt - t0 : 4; + switch (k) { + case 1: iq4nl_rows<1>(w, row_bytes, n, y + t0, out + t0, r0, r1); break; + case 2: iq4nl_rows<2>(w, row_bytes, n, y + t0, out + t0, r0, r1); break; + case 3: iq4nl_rows<3>(w, row_bytes, n, y + t0, out + t0, r0, r1); break; + default: iq4nl_rows<4>(w, row_bytes, n, y + t0, out + t0, r0, r1); break; + } + } + return; + } + // Q2_0: the same 4-at-a-time chunking (NT is capped at 8 by the pool; prefill chunks larger than 8 + // loop here, the per-token rows identical either way). + for (int t0 = 0; t0 < nt; t0 += 4) { + const int k = nt - t0 < 4 ? nt - t0 : 4; + switch (k) { + case 1: q2_0_rows<1>(w, row_bytes, n, y + t0, out + t0, r0, r1); break; + case 2: q2_0_rows<2>(w, row_bytes, n, y + t0, out + t0, r0, r1); break; + case 3: q2_0_rows<3>(w, row_bytes, n, y + t0, out + t0, r0, r1); break; + default: q2_0_rows<4>(w, row_bytes, n, y + t0, out + t0, r0, r1); break; + } + } +} + +// ggml's quantize_row_q8_K_ref in SSE4.2/AVX1: q8k_quant_avx2's arithmetic, 128-bit lanes (its packs need no +// lane-crossing permute at 128-bit). The same per-value operations as the scalar reference - one IEEE multiply +// by the same iscale, the same 1.5*2^23 rounding add, the same clamp - so the bytes are identical +// (q8k_quant_parity checks it), including the NaN and degenerate-block behavior: `ax > amax` is false for a NaN +// and max_ps returns its second operand for a NaN first one, and a zero block leaves bsums as the reference does. +void q8k_quant_avx1(const float* x, void* vy, int64_t k) { + block_q8_K* y = (block_q8_K*) vy; + const int64_t nb = k / QK_K; + const __m128 absm = _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff)); + const __m128 magic = _mm_set1_ps(12582912.f); + const __m128i mant = _mm_set1_epi32(0x007fffff), off = _mm_set1_epi32(0x00400000); + const __m128i c127 = _mm_set1_epi32(127); + for (int64_t i = 0; i < nb; ++i, x += QK_K) { + __m128 m = _mm_setzero_ps(); + for (int j = 0; j < QK_K; j += 4) m = _mm_max_ps(_mm_and_ps(_mm_loadu_ps(x + j), absm), m); + __m128 h = _mm_max_ps(m, _mm_movehl_ps(m, m)); + h = _mm_max_ss(h, _mm_movehdup_ps(h)); + const float amax = _mm_cvtss_f32(h); + if (!amax) { + y[i].d = 0; + std::memset(y[i].qs, 0, QK_K); + continue; + } + float mx = 0.f; + const __m128 va = _mm_set1_ps(amax); + for (int j = 0; j < QK_K; j += 4) { + const int msk = _mm_movemask_ps(_mm_cmpeq_ps(_mm_and_ps(_mm_loadu_ps(x + j), absm), va)); + if (msk) { + int b = 0; + while (!((msk >> b) & 1)) ++b; + mx = x[j + b]; + break; + } + } + const float iscale = -127.f / mx; + const __m128 vis = _mm_set1_ps(iscale); + for (int j = 0; j < QK_K; j += 16) { + __m128i v[4]; + for (int q = 0; q < 4; ++q) { + __m128 p = _mm_mul_ps(vis, _mm_loadu_ps(x + j + 4 * q)); +#if defined(__GNUC__) && !defined(__clang__) + // GCC fuses a multiply and an add into an FMA by default (-ffp-contract=fast); the reference + // rounds the product before the add, so the product must stay a separate value (no FMA under + // -mavx, but the barrier keeps the contract if the file is ever built with a newer floor) + __asm__("" : "+x"(p)); +#endif + const __m128 t = _mm_add_ps(p, magic); + v[q] = _mm_min_epi32(_mm_sub_epi32(_mm_and_si128(_mm_castps_si128(t), mant), off), c127); + // the reference stores MIN(127, v) into an int8 (keeps the low byte), and its bsums add those + // bytes: the same here, so even a degenerate block (iscale overflowing to inf) gives the same bytes + v[q] = _mm_srai_epi32(_mm_slli_epi32(v[q], 24), 24); + } + __m128i s = _mm_add_epi32(_mm_add_epi32(v[0], v[1]), _mm_add_epi32(v[2], v[3])); + s = _mm_add_epi32(s, _mm_shuffle_epi32(s, 0x4E)); + s = _mm_add_epi32(s, _mm_shuffle_epi32(s, 0xB1)); + y[i].bsums[j / 16] = (int16_t) _mm_cvtsi128_si32(s); + _mm_storeu_si128((__m128i*) (y[i].qs + j), + _mm_packs_epi16(_mm_packs_epi32(v[0], v[1]), _mm_packs_epi32(v[2], v[3]))); + } + y[i].d = 1 / iscale; + } +} + +} // namespace strata::kernels::cpu diff --git a/src/kernels/cpu/iq_avx1_parity.cpp b/src/kernels/cpu/iq_avx1_parity.cpp new file mode 100644 index 00000000..2f83251f --- /dev/null +++ b/src/kernels/cpu/iq_avx1_parity.cpp @@ -0,0 +1,291 @@ +// src/kernels/cpu/iq_avx1_parity.cpp - the AVX1 expert kernels (iq_avx1.cpp) against ggml-cpu's dots and +// against themselves at every token count. No GPU, no model: random blocks (every grid index and sign +// pattern occurs) and random activations quantized the way the engine quantizes them. +// +// iq_avx1_parity IQ3_XXS/IQ3_S/IQ2_S/IQ4_XS gate/up rows and IQ4_NL/Q2_0 down rows: +// every row bit for bit the same kernel's one-token row (#152), and rel <= 1e-5 +// against ggml-cpu's vec_dot (the scalar _generic the engine runs without these). +// iq_avx1_parity --bench [--mb 128] [--nt 1,2,4] [--cpu N] +// ms per expert on one thread: ggml-cpu's per-token dot vs the iq128 kernel over +// --mb MB of expert blobs (more than any L3: the weights stream from DRAM as in +// decode), for the nt in --nt. +// +// Runs on any CPU with AVX (the kernels are compiled for SSE4.2 + AVX); on an AVX2 machine it checks the +// older-CPU path exactly as an AVX-only machine runs it (the engine's dispatch gate is separate: this calls +// the kernels directly). +#include "strata/kernels/cpu/iq_avx1.hpp" +#include "strata/kernels/cpu/native_expert.hpp" +#include "strata/kernels/cpu/expert_layout.hpp" + +#include "ggml.h" +#include "ggml-cpu.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if !defined(_WIN32) +#include +#endif + +namespace cpu = strata::kernels::cpu; +using Clock = std::chrono::steady_clock; + +namespace { + +constexpr int kH = 2560, kFF = 640; // the experts' geometry: n_embd, expert width (as iq_avx2_parity) +constexpr int kMaxT = 8; + +uint64_t mix(uint64_t& s) { // splitmix64 + uint64_t z = (s += 0x9E3779B97F4A7C15ull); + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBull; + return z ^ (z >> 31); +} + +const ggml_type_traits_cpu* traits_cpu(int type) { return ggml_get_type_traits_cpu((ggml_type) type); } + +// random bytes, then a sane fp16 scale at the front of every block (iq_avx2_parity's) +void fill_blocks(uint8_t* p, size_t bytes, int type, uint64_t& seed) { + for (size_t i = 0; i < bytes; i += 8) { + const uint64_t v = mix(seed); + std::memcpy(p + i, &v, std::min(8, bytes - i)); + } + const size_t bs = ggml_type_size((ggml_type) type); + for (size_t o = 0; o + bs <= bytes; o += bs) { + const float d = (0.5f + (float) (mix(seed) >> 40) * (1.f / 16777216.f)) * 1e-3f; + const ggml_fp16_t h = ggml_fp32_to_fp16(d); + std::memcpy(p + o, &h, 2); + } +} + +void fill_blob(uint8_t* blob, const cpu::NativeFmt& f, uint64_t& seed) { + fill_blocks(blob, f.down_off, f.gu_type, seed); // the gate and up rows + fill_blocks(blob + f.down_off, f.bytes - f.down_off, f.d_type, seed); // the down rows +} + +struct Case { + int gu, dn; + const char* name; +}; + +const Case kCases[] = { + {18, 20, "iq3_xxs/iq4_nl"}, {21, 20, "iq3_s/iq4_nl"}, {22, 20, "iq2_s/iq4_nl"}, {23, 20, "iq4_xs/iq4_nl"}, + {18, 42, "iq3_xxs/q2_0"}, {21, 42, "iq3_s/q2_0"}, {22, 42, "iq2_s/q2_0"}, {23, 42, "iq4_xs/q2_0"}, +}; + +// one expert, nt tokens of quantized activations, and the reference rows +struct Fixture { + cpu::NativeFmt f; + std::vector blob; + std::vector> act, hq; // per token + std::vector> x, h; + std::vector ff_ref, out_ref; // [t][row] +}; + +void make_fixture(Fixture& fx, int gu, int dn, int nt, uint64_t& seed) { + std::string err; + if (!cpu::native_fmt(gu, dn, kH, kFF, fx.f, err)) { std::fprintf(stderr, "native_fmt: %s\n", err.c_str()); std::exit(1); } + fx.blob.resize(fx.f.bytes); + fill_blob(fx.blob.data(), fx.f, seed); + fx.act.resize(nt); fx.hq.resize(nt); fx.x.resize(nt); fx.h.resize(nt); + for (int t = 0; t < nt; ++t) { + fx.act[t].resize(fx.f.act_bytes); fx.hq[t].resize(fx.f.h_bytes); + fx.x[t].resize(kH); fx.h[t].resize(kFF); + for (int i = 0; i < kH; ++i) fx.x[t][i] = (float) ((mix(seed) >> 40) * 0x1p-24 * 2.0 - 1.0); + for (int i = 0; i < kFF; ++i) fx.h[t][i] = (float) ((mix(seed) >> 40) * 0x1p-24 * 2.0 - 1.0); + cpu::native_quant_act(fx.f, fx.x[t].data(), fx.act[t].data()); + cpu::native_quant_h(fx.f, fx.h[t].data(), fx.hq[t].data()); + } + // reference rows: ggml-cpu's own dots, per token (what the engine runs without the iq128 kernels) + const ggml_vec_dot_t gu_dot = traits_cpu(gu)->vec_dot; + const ggml_vec_dot_t dn_dot = traits_cpu(dn)->vec_dot; + fx.ff_ref.resize((size_t) nt * kFF); fx.out_ref.resize((size_t) nt * kH); + for (int t = 0; t < nt; ++t) { + for (int r = 0; r < kFF; ++r) { + float g = 0.f, u = 0.f; + gu_dot(kH, &g, 0, fx.blob.data() + (size_t) r * fx.f.gu_row, 0, fx.act[t].data(), 0, 1); + gu_dot(kH, &u, 0, fx.blob.data() + fx.f.up_off + (size_t) r * fx.f.gu_row, 0, fx.act[t].data(), 0, 1); + fx.ff_ref[(size_t) t * kFF + r] = (g / (1.f + std::exp(-g))) * u; + } + for (int r = 0; r < kH; ++r) { + float s = 0.f; + dn_dot(kFF, &s, 0, fx.blob.data() + fx.f.down_off + (size_t) r * fx.f.d_row, 0, fx.hq[t].data(), 0, 1); + fx.out_ref[(size_t) t * kH + r] = s; + } + } +} + +int failures = 0; + +void check(const char* what, const std::vector& got, const std::vector& ref, bool exact) { + if (exact) { // bit-exact (iq_avx2_parity's rows_differ) + size_t d = 0; + for (size_t i = 0; i < ref.size(); ++i) d += std::memcmp(&got[i], &ref[i], sizeof(float)) != 0; + if (d) { std::printf(" FAIL %s: %zu of %zu rows differ\n", what, d, ref.size()); ++failures; } + return; + } + // the repo's bar (iq_avx2_parity's rel): aggregate sum|diff| / sum|ref| <= 1e-5 + double num = 0, den = 0; + for (size_t i = 0; i < ref.size(); ++i) { + num += std::fabs((double) got[i] - (double) ref[i]); + den += std::fabs((double) ref[i]); + } + const double r = num / (den + 1e-30); + if (!(r <= 1e-5)) { std::printf(" FAIL %s: rel %.3e > 1e-5 vs ggml-cpu\n", what, r); ++failures; } +} + +// ---- the checks +void run_checks() { + for (const Case& c : kCases) { + uint64_t seed = 0x5EED1234u + (uint64_t) c.gu * 1000 + (uint64_t) c.dn; + Fixture fx; + make_fixture(fx, c.gu, c.dn, kMaxT, seed); + const void* actp[kMaxT]; const void* hqp[kMaxT]; + std::vector ff[kMaxT], out[kMaxT]; + float* ffp[kMaxT]; float* outp[kMaxT]; + for (int t = 0; t < kMaxT; ++t) { + actp[t] = fx.act[t].data(); hqp[t] = fx.hq[t].data(); + ff[t].resize(kFF); out[t].resize(kH); + ffp[t] = ff[t].data(); outp[t] = out[t].data(); + } + // gate/up: nt = 1..8, every width bit-identical to that token's nt = 1 row (#152), all rel <= 1e-5 vs ggml + std::vector> ff1(kMaxT), out1(kMaxT); + for (int nt = 1; nt <= kMaxT; ++nt) { + cpu::iq128_gu_rows(c.gu, fx.blob.data(), fx.f.gu_row, fx.f.up_off, kH, actp, nt, ffp, 0, kFF); + for (int t = 0; t < nt; ++t) { + char what[96]; + std::snprintf(what, sizeof what, "%s gu nt=%d vs ggml", c.name, nt); + check(what, ff[t], std::vector(fx.ff_ref.begin() + (size_t) t * kFF, + fx.ff_ref.begin() + (size_t) (t + 1) * kFF), false); + if (nt == 1) ff1[t] = ff[t]; + else { + std::snprintf(what, sizeof what, "%s gu nt=%d token %d vs its nt=1 row", c.name, nt, t); + check(what, ff[t], ff1[t], true); + } + } + } + // down + for (int nt = 1; nt <= kMaxT; ++nt) { + cpu::iq128_down_rows(c.dn, fx.blob.data() + fx.f.down_off, fx.f.d_row, kFF, hqp, nt, outp, 0, kH); + for (int t = 0; t < nt; ++t) { + char what[96]; + std::snprintf(what, sizeof what, "%s down nt=%d vs ggml", c.name, nt); + check(what, out[t], std::vector(fx.out_ref.begin() + (size_t) t * kH, + fx.out_ref.begin() + (size_t) (t + 1) * kH), false); + if (nt == 1) out1[t] = out[t]; + else { + std::snprintf(what, sizeof what, "%s down nt=%d token %d vs its nt=1 row", c.name, nt, t); + check(what, out[t], out1[t], true); + } + } + } + std::printf(" %-16s checked (gu %d, down %d)\n", c.name, c.gu, c.dn); + } +} + +// ---- the bench: ms per expert, the weights streamed from DRAM +void run_bench(int mb, const std::vector& nts) { + for (const Case& c : kCases) { + uint64_t seed = 0xBEEF0000u + (uint64_t) c.gu * 1000 + (uint64_t) c.dn; + Fixture fx; + make_fixture(fx, c.gu, c.dn, 1, seed); + const size_t per = fx.f.bytes; + const int nexp = (int) ((size_t) mb * 1024 * 1024 / per); + std::vector blob((size_t) nexp * per); + for (int e = 0; e < nexp; ++e) std::memcpy(blob.data() + (size_t) e * per, fx.blob.data(), per); + // vary the blocks a little so the run is not one blob repeated (the same bytes hit the same caches) + for (int e = 1; e < nexp; ++e) { + uint64_t s2 = seed + (uint64_t) e * 7919; + const size_t o = (size_t) e * per; + for (size_t i = 0; i + 8 <= per; i += 128) { + const uint64_t v = mix(s2); + std::memcpy(blob.data() + o + i, &v, 8); // keep block scales (first 2 bytes of each block) + } + } + for (int nt : nts) { + if (nt > kMaxT) continue; + const void* actp[kMaxT]; const void* hqp[kMaxT]; + float* ffp[kMaxT]; float* outp[kMaxT]; + std::vector> ff(kMaxT, std::vector(kFF)), out(kMaxT, std::vector(kH)); + Fixture fx8; // nt tokens of activations + uint64_t s8 = seed + 0x1234; + make_fixture(fx8, c.gu, c.dn, nt, s8); + for (int t = 0; t < nt; ++t) { + actp[t] = fx8.act[t].data(); hqp[t] = fx8.hq[t].data(); + ffp[t] = ff[t].data(); outp[t] = out[t].data(); + } + const ggml_vec_dot_t gu_dot = traits_cpu(c.gu)->vec_dot, dn_dot = traits_cpu(c.dn)->vec_dot; + // ggml-cpu's path (what the engine runs today on this CPU): per-token dots over every row + auto t0 = Clock::now(); + for (int e = 0; e < nexp; ++e) { + for (int r = 0; r < kFF; ++r) { + for (int t = 0; t < nt; ++t) { + float g = 0.f, u = 0.f; + gu_dot(kH, &g, 0, blob.data() + (size_t) e * per + (size_t) r * fx.f.gu_row, 0, (const uint8_t*) actp[t], 0, 1); + gu_dot(kH, &u, 0, blob.data() + (size_t) e * per + fx.f.up_off + (size_t) r * fx.f.gu_row, 0, (const uint8_t*) actp[t], 0, 1); + ff[t][r] = (g / (1.f + std::exp(-g))) * u; + } + } + for (int r = 0; r < kH; ++r) { + for (int t = 0; t < nt; ++t) { + float s = 0.f; + dn_dot(kFF, &s, 0, blob.data() + (size_t) e * per + fx.f.down_off + (size_t) r * fx.f.d_row, 0, (const uint8_t*) hqp[t], 0, 1); + out[t][r] = s; + } + } + } + const double ms_ggml = std::chrono::duration(Clock::now() - t0).count(); + t0 = Clock::now(); + for (int e = 0; e < nexp; ++e) { + cpu::iq128_gu_rows(c.gu, blob.data() + (size_t) e * per, fx.f.gu_row, fx.f.up_off, kH, actp, nt, ffp, 0, kFF); + cpu::iq128_down_rows(c.dn, blob.data() + (size_t) e * per + fx.f.down_off, fx.f.d_row, kFF, hqp, nt, outp, 0, kH); + } + const double ms_iq = std::chrono::duration(Clock::now() - t0).count(); + std::printf(" %-16s nt=%d ggml %8.2f ms/expert iq128 %6.2f ms/expert %.1fx\n", + c.name, nt, ms_ggml / nexp, ms_iq / nexp, ms_ggml / ms_iq); + } + } +} + +} // namespace + +int main(int argc, char** argv) { + bool bench = false; + int mb = 128, cpu_pin = -1; + std::vector nts = {1, 2, 4}; + for (int i = 1; i < argc; ++i) { + std::string a = argv[i]; + if (a == "--bench") bench = true; + else if (a == "--mb" && i + 1 < argc) mb = std::atoi(argv[++i]); + else if (a == "--cpu" && i + 1 < argc) cpu_pin = std::atoi(argv[++i]); + else if (a == "--nt" && i + 1 < argc) { + nts.clear(); + const char* p = argv[++i]; + while (*p) { nts.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p == ',') ++p; } + } else { + std::printf("usage: iq_avx1_parity [--bench [--mb N] [--nt 1,2,4] [--cpu N]]\n"); + return 2; + } + } +#if !defined(_WIN32) + if (cpu_pin >= 0) { + cpu_set_t set; + CPU_ZERO(&set); + CPU_SET(cpu_pin, &set); + if (sched_setaffinity(0, sizeof set, &set) != 0) std::fprintf(stderr, "pinning to CPU %d failed\n", cpu_pin); + } +#endif + if (!cpu::cpu_avx1_ok()) { std::printf("iq_avx1_parity: no AVX here, the kernels would not run\n"); return 0; } + std::printf("iq_avx1_parity: %s\n", cpu::cpu_avx1_ok() ? "AVX1 kernels checked (128-bit lanes)" : ""); + if (bench) { run_bench(mb, nts); return failures != 0; } + run_checks(); + std::printf(failures ? "iq_avx1_parity: %d FAILURES\n" : "iq_avx1_parity: all rows match\n", failures); + return failures != 0; +} diff --git a/src/kernels/cpu/native_expert.cpp b/src/kernels/cpu/native_expert.cpp index 8baead06..78e3cbaa 100644 --- a/src/kernels/cpu/native_expert.cpp +++ b/src/kernels/cpu/native_expert.cpp @@ -5,6 +5,7 @@ #include "strata/kernels/cpu/expert.hpp" #include "strata/kernels/cpu/iq_avx512.hpp" #include "strata/kernels/cpu/iq_avx2.hpp" +#include "strata/kernels/cpu/iq_avx1.hpp" #include "strata/kernels/cpu/kq_avx2.hpp" #include "strata/kernels/cpu/expert_layout.hpp" @@ -91,15 +92,23 @@ bool q8k_avx2(int type) { static const bool on = cpu_avx2_ok() && std::getenv("STRATA_NO_Q8K_AVX2") == nullptr; return on && type == (int) GGML_TYPE_Q8_K; } +// the older CPUs' copy (iq_avx1.cpp): byte-identical like the AVX-2 one, and only where AVX2 is absent (same +// policy as STRATA_NO_IQ128 above; STRATA_NO_Q8K_AVX1=1 keeps ggml's scalar reference on those CPUs). +bool q8k_avx1(int type) { + static const bool on = !cpu_avx2_ok() && cpu_avx1_ok() && std::getenv("STRATA_NO_Q8K_AVX1") == nullptr; + return on && type == (int) GGML_TYPE_Q8_K; +} } // namespace void native_quant_act(const NativeFmt& f, const float* x, void* dst) { if (q8k_avx2(f.gu_act)) { q8k_quant_avx2(x, dst, f.n_embd); return; } + if (q8k_avx1(f.gu_act)) { q8k_quant_avx1(x, dst, f.n_embd); return; } traits(f.gu_act)->from_float(x, dst, f.n_embd); } void native_quant_h(const NativeFmt& f, const float* h, void* dst) { if (q8k_avx2(f.d_act)) { q8k_quant_avx2(h, dst, f.n_ff); return; } + if (q8k_avx1(f.d_act)) { q8k_quant_avx1(h, dst, f.n_ff); return; } traits(f.d_act)->from_float(h, dst, f.n_ff); } @@ -138,6 +147,14 @@ void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const* // baseline the build selected (AVX1 here) and covers the same types - IQ2_XXS and IQ2_S among // them. That path loops over tokens itself, so it is correct for any `nt`, not just one. static const bool avx2 = cpu_avx2_ok() && std::getenv("STRATA_NO_IQ256") == nullptr; + // The older-CPU tier (STRATA_ISA_FLOOR=avx builds): without it every expert on such a CPU runs on ggml-cpu's + // scalar _generic dots. Only where AVX2 is absent, so a modern CPU's rounding never moves (and + // STRATA_NO_IQ256=1 there still means ggml, as before). iq_avx1.cpp is compiled for AVX and gated on + // cpu_avx1_ok(). Measured on an E5-2470 v2 (iq_avx1_parity --bench): 1.2-3.1x ggml's dot from two tokens on, + // at one token ggml's auto-vectorized generic loop matches the 128-bit kernel - so the same #152 mt_min rule + // as the AVX-2 kernels, and STRATA_IQ_MT_MIN=1 takes the kernel for one token too (its rows are then + // independent of the drafting: iq_avx1_parity checks every width bit for bit). + static const bool avx1 = !cpu_avx2_ok() && cpu_avx1_ok() && std::getenv("STRATA_NO_IQ128") == nullptr; const int mt_min = native_gu_mt_min(f.gu_type); // #152 // Unsloth UD-Q4_K_XL's Q4_K gate/up: the multi-token kernel is bit-exact against ggml's per-token dot (any group // size, no #152 rule). Opt-in, STRATA_KQ256=1: measured no faster in the engine (a window's expert groups hold @@ -161,6 +178,10 @@ void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const* return; } } + if (avx1 && nt >= mt_min && iq128_supported(f.gu_type)) { + iq128_gu_rows(f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act, nt, ff, r0, r1); + return; + } const ggml_vec_dot_t dot = traits(f.gu_type)->vec_dot; const int n = (int) f.n_embd; for (int r = r0; r < r1; ++r) { @@ -193,6 +214,12 @@ void native_down_rows(const NativeFmt& f, const uint8_t* blob, const void* const iq4nl256_down_rows(blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1); return; } + // the older-CPU tier: IQ4_NL and Q2_0 down rows in 128-bit (ggml-cpu's dots for both are scalar here) + static const bool avx1 = !cpu_avx2_ok() && cpu_avx1_ok() && std::getenv("STRATA_NO_IQ128") == nullptr; + if (avx1 && iq128_down_supported(f.d_type)) { + iq128_down_rows(f.d_type, blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1); + return; + } const ggml_vec_dot_t dot = traits(f.d_type)->vec_dot; const int n = (int) f.n_ff; for (int r = r0; r < r1; ++r) { diff --git a/src/kernels/cpu/q2_avx1.cpp b/src/kernels/cpu/q2_avx1.cpp new file mode 100644 index 00000000..6d5b9699 --- /dev/null +++ b/src/kernels/cpu/q2_avx1.cpp @@ -0,0 +1,294 @@ +// src/kernels/cpu/q2_avx1.cpp - the Q2_0 expert rows and the activation quantizer for CPUs that have AVX but +// no AVX2 (Sandy Bridge through Ivy Bridge Xeons; issue #623, #1375), the third rung of q2_rows_any / +// act_quant_any below the AVX-2 one (issue #1699: those dispatchers used to hand AVX2 code to an AVX1 CPU). +// +// The arithmetic is q2_avx2.cpp's: codes 0..3 against the int8 activation per 32-value chunk, times the weight +// scale and the chunk scale, minus the weight scale times the chunk's `hx`. 128-bit integer lanes (maddubs and +// madd are SSSE3/SSE2), 256-bit float accumulation with mul+add (no FMA), fp16 scales converted in software (no +// F16C). The legacy row kernel keeps q2_avx2.cpp's lane pairing and reduction tree exactly, so the only +// difference from an AVX2 CPU is its FMA becoming mul+add (last bits, unavoidable without FMA); the bit-plane +// kernel's float summation order is its own (last bits, as documented for the AVX-2 one), and every token's +// operations are the same whatever the window width (#152). +// +// Compiled with -msse4.2 -mavx -mno-avx2 -mno-fma -mno-f16c (CMakeLists.txt, the iq_avx1.cpp pattern) and called +// only behind cpu_avx1_ok() && !cpu_avx2_ok(), so no CPU that lacks those features can reach it - and no CPU that +// has AVX2 changes what it runs. +#include "strata/kernels/cpu/expert.hpp" +#include "strata/kernels/cpu/expert_layout.hpp" + +#include + +#include +#include +#include +#include + +#if defined(__AVX2__) || defined(__FMA__) || defined(__F16C__) +#error "q2_avx1.cpp must be compiled without AVX2, FMA and F16C (see the per-source flags in CMakeLists.txt)" +#endif + +namespace strata::kernels::cpu { +namespace { + +// fp16 -> fp32 without F16C (the written-out conversion, subnormals included; iq_avx1.cpp's copy). +inline float h2f(uint16_t h) { + const uint32_t sign = (uint32_t) (h >> 15) & 1u; + uint32_t exp = (h >> 10) & 0x1Fu, man = h & 0x3FFu, f; + if (exp == 0) { + if (man == 0) { + f = sign << 31; + } else { + exp = 127 - 15 + 1; + while (!(man & 0x400u)) { man <<= 1; --exp; } + man &= 0x3FFu; + f = (sign << 31) | (exp << 23) | (man << 13); + } + } else if (exp == 31) { + f = (sign << 31) | 0x7F800000u | (man << 13); + } else { + f = (sign << 31) | ((exp - 15 + 127) << 23) | (man << 13); + } + float out; + std::memcpy(&out, &f, 4); + return out; +} + +// 16 bytes of 2-bit codes -> 64 codes in value order, four 16-byte vectors: v0 values 0..15, v1 16..31, +// v2 32..47, v3 48..63 (q2_avx2.cpp's unpack64 cut to 128-bit lanes; the same interleave). +inline void unpack64(const uint8_t* codes, __m128i& v0, __m128i& v1, __m128i& v2, __m128i& v3) { + const __m128i b = _mm_loadu_si128((const __m128i*) codes); + const __m128i m3 = _mm_set1_epi8(3); + const __m128i c0 = _mm_and_si128(b, m3); + const __m128i c1 = _mm_and_si128(_mm_srli_epi16(b, 2), m3); + const __m128i c2 = _mm_and_si128(_mm_srli_epi16(b, 4), m3); + const __m128i c3 = _mm_and_si128(_mm_srli_epi16(b, 6), m3); + const __m128i a0 = _mm_unpacklo_epi8(c0, c1), a1 = _mm_unpacklo_epi8(c2, c3); // bytes 0..7 + const __m128i b0 = _mm_unpackhi_epi8(c0, c1), b1 = _mm_unpackhi_epi8(c2, c3); // bytes 8..15 + v0 = _mm_unpacklo_epi16(a0, a1); // values 0..15 + v1 = _mm_unpackhi_epi16(a0, a1); // values 16..31 + v2 = _mm_unpacklo_epi16(b0, b1); // values 32..47 + v3 = _mm_unpackhi_epi16(b0, b1); // values 48..63 +} + +// 16 codes against 16 activations, four products per int32 lane (q2_avx2_rows.inl's dot4 at 128-bit; +// maddubs cannot saturate: a pair is at most 2 * 3 * 128). +inline __m128i dot4(__m128i codes, __m128i act) { + return _mm_madd_epi16(_mm_maddubs_epi16(codes, act), _mm_set1_epi16(1)); +} + +// The legacy row kernel. The accumulator pairing matches q2_avx2.cpp's lane pairing: each 256-bit lane takes +// the s0 contribution (values 0..31) and the s1 contribution (values 32..63) into the SAME lanes, block by +// block, and the reduction tree is the same one ((L0+L4)+(L2+L6)) + ((L1+L5)+(L3+L7)) - the only difference +// from an AVX2 CPU is that kernel's FMA being a mul+add here (last bits). +template +inline void row_multi(const uint8_t* row, const ActQ* const* a, int nblocks, float* res) { + __m256 acc[NT]; + float corr[NT]; + for (int t = 0; t < NT; ++t) { acc[t] = _mm256_setzero_ps(); corr[t] = 0.f; } + for (int b = 0; b < nblocks; ++b) { + const uint8_t* blk = row + (size_t) b * 18; + const float d = h2f((uint16_t) (blk[0] | (blk[1] << 8))); + __m128i v0, v1, v2, v3; + unpack64(blk + 2, v0, v1, v2, v3); + for (int t = 0; t < NT; ++t) { + const int8_t* q = a[t]->q + b * 64; + // s0 = values 0..31: lanes 0..3 of accA's 128-bit halves; s1 = values 32..63 into the SAME lanes + const __m128i s0a = dot4(v0, _mm_loadu_si128((const __m128i*) q)); // values 0..15 + const __m128i s0b = dot4(v1, _mm_loadu_si128((const __m128i*) (q + 16))); // values 16..31 + const __m128i s1a = dot4(v2, _mm_loadu_si128((const __m128i*) (q + 32))); // values 32..47 + const __m128i s1b = dot4(v3, _mm_loadu_si128((const __m128i*) (q + 48))); // values 48..63 + const __m256 s0 = _mm256_insertf128_ps(_mm256_castps128_ps256(_mm_cvtepi32_ps(s0a)), _mm_cvtepi32_ps(s0b), 1); + const __m256 s1 = _mm256_insertf128_ps(_mm256_castps128_ps256(_mm_cvtepi32_ps(s1a)), _mm_cvtepi32_ps(s1b), 1); + // exactly the AVX-2 kernel's two fmadds: the whole s0 (values 0..31) by scale[2b], the whole s1 + // (values 32..63) by scale[2b+1], into the same lanes - lane pairing and reduce tree follow suit + acc[t] = _mm256_add_ps(acc[t], _mm256_mul_ps(_mm256_set1_ps(d * a[t]->scale[2 * b]), s0)); + acc[t] = _mm256_add_ps(acc[t], _mm256_mul_ps(_mm256_set1_ps(d * a[t]->scale[2 * b + 1]), s1)); + corr[t] += d * (a[t]->hx[2 * b] + a[t]->hx[2 * b + 1]); + } + } + for (int t = 0; t < NT; ++t) { + const __m128 h = _mm_add_ps(_mm256_castps256_ps128(acc[t]), _mm256_extractf128_ps(acc[t], 1)); + const __m128 s = _mm_add_ps(h, _mm_movehl_ps(h, h)); + res[t] = _mm_cvtss_f32(_mm_add_ss(s, _mm_movehdup_ps(s))) - corr[t]; + } +} + +template +void rows(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, float* const* out, int r0, int r1) { + float res[NT]; + for (int r = r0; r < r1; ++r) { + row_multi(w + (size_t) r * row_bytes, a, nblocks, res); + for (int t = 0; t < NT; ++t) out[t][r] = res[t]; + } +} + +// ---- the bit-plane row kernel (STRATA_Q2_BITPLANE=1), 128-bit lanes: one 64-value block at a time instead of +// a pair per 256-bit register. The integer part is exact; the float summation order is this kernel's own (the +// same statement as for the AVX-2 one), and every row reduces with the same tree alone or in a group (#152). +template +inline void row_bp_acc(const uint8_t* row, const ActQ* const* a, int npairs, __m128* acc) { + for (int t = 0; t < NT; ++t) { acc[2 * t] = _mm_setzero_ps(); acc[2 * t + 1] = _mm_setzero_ps(); } + const __m128i m3 = _mm_set1_epi8(3); + const __m128i ones = _mm_set1_epi16(1); + for (int p = 0; p < npairs; ++p) { + const uint8_t* blk = row + (size_t) p * 36; + for (int h = 0; h < 2; ++h) { + uint16_t dh; + std::memcpy(&dh, blk + h * 18, 2); // the block's fp16 scale: bytes 0..1 (block 1 at +18) + const __m128 d = _mm_set1_ps(h2f(dh)); + const __m128i c = _mm_loadu_si128((const __m128i*) (blk + 2 + h * 18)); // its 16 code bytes + const __m128i c0 = _mm_and_si128(c, m3); + const __m128i c1 = _mm_and_si128(_mm_srli_epi16(c, 2), m3); + const __m128i c2 = _mm_and_si128(_mm_srli_epi16(c, 4), m3); + const __m128i c3 = _mm_and_si128(_mm_srli_epi16(c, 6), m3); + for (int t = 0; t < NT; ++t) { + const int8_t* q = a[t]->qp + (size_t) p * 128 + h * 16; + __m128i s = _mm_maddubs_epi16(c0, _mm_load_si128((const __m128i*) q)); + s = _mm_add_epi16(s, _mm_maddubs_epi16(c1, _mm_load_si128((const __m128i*) (q + 32)))); + s = _mm_add_epi16(s, _mm_maddubs_epi16(c2, _mm_load_si128((const __m128i*) (q + 64)))); + s = _mm_add_epi16(s, _mm_maddubs_epi16(c3, _mm_load_si128((const __m128i*) (q + 96)))); + const __m128i i32 = _mm_sub_epi32(_mm_madd_epi16(s, ones), + _mm_load_si128((const __m128i*) (a[t]->psum + p * 8 + h * 4))); + const __m128 v = _mm_mul_ps(_mm_cvtepi32_ps(i32), + _mm_load_ps(a[t]->pscale + p * 8 + h * 4)); + __m128& x = acc[2 * t + h]; + x = _mm_add_ps(x, _mm_mul_ps(d, v)); + } + } + } +} + +inline float reduce1(__m128 a, __m128 b) { // ((v0+v1)+(v2+v3)) + ((v4+v5)+(v6+v7)), the AVX-2 kernel's tree + __m128 ha = _mm_hadd_ps(a, a); // [a0+a1, a2+a3, a0+a1, a2+a3] + ha = _mm_add_ss(ha, _mm_movehdup_ps(ha)); // (v0+v1)+(v2+v3) + __m128 hb = _mm_hadd_ps(b, b); + hb = _mm_add_ss(hb, _mm_movehdup_ps(hb)); // (v4+v5)+(v6+v7) + return _mm_cvtss_f32(_mm_add_ss(ha, hb)); +} + +template +void rows_bp(const uint8_t* w, size_t row_bytes, int npairs, const ActQ* const* a, float* const* out, int r0, int r1) { + for (int r = r0; r < r1; ++r) { + __m128 acc[2 * NT]; + row_bp_acc(w + (size_t) r * row_bytes, a, npairs, acc); + for (int t = 0; t < NT; ++t) out[t][r] = reduce1(acc[2 * t], acc[2 * t + 1]); + } +} + +const bool kBitplane = [] { + const char* e = std::getenv("STRATA_Q2_BITPLANE"); + return e != nullptr && e[0] == '1'; +}(); + +// ActQ::qp / psum / pscale from q and scale: q2_avx2.cpp's bitplane_image, which is already pure SSE2/SSSE3 +// (shuffle_epi8, sad, unpack) - copied rather than shared so q2_avx2.cpp stays untouched. +void bitplane_image(ActQ& a) { + if (a.nchunks % 4 != 0) { a.bp_pairs = 0; return; } + const int nblk = a.nchunks / 2; + const __m128i shuf = _mm_setr_epi8(0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15); + const __m128i bias = _mm_set1_epi8((char) 0x80); + for (int b = 0; b < nblk; ++b) { + const int8_t* q = a.q + b * 64; + __m128i s[4]; + for (int g = 0; g < 4; ++g) { + const __m128i v = _mm_loadu_si128((const __m128i*) (q + 16 * g)); + s[g] = _mm_shuffle_epi8(v, shuf); + const __m128i sad = _mm_sad_epu8(_mm_xor_si128(v, bias), _mm_setzero_si128()); + a.psum[(b >> 1) * 8 + (b & 1) * 4 + g] = + _mm_cvtsi128_si32(sad) + _mm_extract_epi16(sad, 4) - 16 * 128; + } + const __m128i t0 = _mm_unpacklo_epi32(s[0], s[1]), t1 = _mm_unpacklo_epi32(s[2], s[3]); + const __m128i t2 = _mm_unpackhi_epi32(s[0], s[1]), t3 = _mm_unpackhi_epi32(s[2], s[3]); + int8_t* dst = a.qp + (b >> 1) * 128 + (b & 1) * 16; + _mm_store_si128((__m128i*) (dst), _mm_unpacklo_epi64(t0, t1)); + _mm_store_si128((__m128i*) (dst + 32), _mm_unpackhi_epi64(t0, t1)); + _mm_store_si128((__m128i*) (dst + 64), _mm_unpacklo_epi64(t2, t3)); + _mm_store_si128((__m128i*) (dst + 96), _mm_unpackhi_epi64(t2, t3)); + } + for (int c = 0; c < a.nchunks; ++c) { + a.pscale[2 * c] = a.scale[c]; + a.pscale[2 * c + 1] = a.scale[c]; + } + a.bp_pairs = nblk / 2; +} + +} // namespace + +void q2_0_gguf_rows_multi_avx1_legacy(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, + float* const* out, int r0, int r1) { + switch (nt) { + case 1: rows<1>(w, row_bytes, nblocks, a, out, r0, r1); break; + case 2: rows<2>(w, row_bytes, nblocks, a, out, r0, r1); break; + case 3: rows<3>(w, row_bytes, nblocks, a, out, r0, r1); break; + case 4: rows<4>(w, row_bytes, nblocks, a, out, r0, r1); break; + default: + for (int t0 = 0; t0 < nt; t0 += 4) { + const int k = nt - t0 < 4 ? nt - t0 : 4; + q2_0_gguf_rows_multi_avx1_legacy(w, row_bytes, nblocks, a + t0, k, out + t0, r0, r1); + } + } +} + +void q2_0_gguf_rows_multi_avx1(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, + float* const* out, int r0, int r1) { + bool bp = kBitplane && nblocks % 2 == 0; + for (int t = 0; t < nt && bp; ++t) bp = a[t]->bp_pairs == nblocks / 2; + if (!bp) { + q2_0_gguf_rows_multi_avx1_legacy(w, row_bytes, nblocks, a, nt, out, r0, r1); + return; + } + const int np = nblocks / 2; + switch (nt) { + case 1: rows_bp<1>(w, row_bytes, np, a, out, r0, r1); break; + case 2: rows_bp<2>(w, row_bytes, np, a, out, r0, r1); break; + case 3: rows_bp<3>(w, row_bytes, np, a, out, r0, r1); break; + case 4: rows_bp<4>(w, row_bytes, np, a, out, r0, r1); break; + default: + for (int t0 = 0; t0 < nt; t0 += 4) { + const int k = nt - t0 < 4 ? nt - t0 : 4; + q2_0_gguf_rows_multi_avx1(w, row_bytes, nblocks, a + t0, k, out + t0, r0, r1); + } + } +} + +void act_quant_q8_1_avx1(const float* x, int n, ActQ& a) { + a.nchunks = n / QKA; + const __m128 absmask = _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff)); + const __m128 half = _mm_set1_ps(0.5f), mhalf = _mm_set1_ps(-0.5f), zero = _mm_setzero_ps(); + const __m128i lo = _mm_set1_epi32(-127), hi = _mm_set1_epi32(127); + for (int k = 0; k < a.nchunks; ++k) { + const float* xb = x + k * QKA; + __m128 v[8]; + __m128 m = _mm_setzero_ps(); + for (int i = 0; i < 8; ++i) { + v[i] = _mm_loadu_ps(xb + 4 * i); + m = _mm_max_ps(m, _mm_and_ps(v[i], absmask)); + } + m = _mm_max_ps(m, _mm_movehl_ps(m, m)); + const float amax = _mm_cvtss_f32(_mm_max_ss(m, _mm_movehdup_ps(m))); + const float s = amax > 0.f ? amax / 127.f : 0.f; + const float inv = s > 0.f ? 1.f / s : 0.f; + const __m128 vinv = _mm_set1_ps(inv); + __m128i sum = _mm_setzero_si128(); + alignas(16) int32_t qi[QKA]; + for (int i = 0; i < 8; ++i) { + const __m128 t = _mm_mul_ps(v[i], vinv); + const __m128 r = _mm_add_ps(t, _mm_blendv_ps(mhalf, half, _mm_cmp_ps(t, zero, _CMP_GE_OQ))); + __m128i q = _mm_cvttps_epi32(r); + q = _mm_min_epi32(_mm_max_epi32(q, lo), hi); + sum = _mm_add_epi32(sum, q); + _mm_store_si128((__m128i*) (qi + 4 * i), q); + } + for (int j = 0; j < QKA; ++j) a.q[k * QKA + j] = (int8_t) qi[j]; + __m128i s4 = _mm_add_epi32(sum, _mm_shuffle_epi32(sum, 0x4E)); + s4 = _mm_add_epi32(s4, _mm_shuffle_epi32(s4, 0xB1)); + const int32_t total = _mm_cvtsi128_si32(s4); + a.scale[k] = s; + a.sum[k] = total; + a.hx[k] = s * (float) total; + } + if (kBitplane) bitplane_image(a); + else a.bp_pairs = 0; +} + +} // namespace strata::kernels::cpu diff --git a/src/kernels/cpu/q2_bitplane_parity.cpp b/src/kernels/cpu/q2_bitplane_parity.cpp index cefa81f8..65c1c1dc 100644 --- a/src/kernels/cpu/q2_bitplane_parity.cpp +++ b/src/kernels/cpu/q2_bitplane_parity.cpp @@ -1,13 +1,15 @@ -// src/kernels/cpu/q2_bitplane_parity.cpp - the opt-in AVX-2 Q2_0 bit-plane kernel (STRATA_Q2_BITPLANE=1, PR #706). +// src/kernels/cpu/q2_bitplane_parity.cpp - the opt-in Q2_0 bit-plane kernel (STRATA_Q2_BITPLANE=1, PR #706), +// on the AVX-2 pair where the CPU has AVX2 and on the AVX1 pair below it (issue #1699) - the bit-plane is an +// AVX2/AVX1 feature, the AVX-512 kernel does not read the image. // -// 1. against the legacy AVX-2 kernel: the integer part is exact, only the float summation order differs, so the -// two agree to a few ulps of the largest term (a relative bound on the row's magnitude); +// 1. against the legacy kernel of the same rung: the integer part is exact, only the float summation order +// differs, so the two agree to a few ulps of the largest term (a relative bound on the row's magnitude); // 2. bitwise: a token's rows are the same alone, in a window of any width, and cut into any row ranges // (the engine's pool splits rows between workers, a verify window changes the width); // 3. the legacy path is untouched when the switch is off (this test only runs with the switch on: ctest sets it). -// Synthetic data, CPU only; skipped (pass) on a CPU without AVX2. +// Synthetic data, CPU only; skipped (pass) on a CPU without AVX. #include "strata/kernels/cpu/expert.hpp" - +#include "strata/kernels/cpu/expert_layout.hpp" #include #include #include @@ -23,6 +25,16 @@ int main() { std::printf("q2_bitplane_parity: STRATA_Q2_BITPLANE=1 is not set\n"); return 1; } + if (!c::cpu_avx1_ok()) { std::printf("q2_bitplane_parity: no AVX on this CPU, skipped\n"); return 0; } + const bool avx2 = c::cpu_avx2_ok(); // the pair under test: AVX-2 where present, AVX1 below it + auto quant = [&](const float* x, int n, c::ActQ& q) { avx2 ? c::act_quant_q8_1_avx2(x, n, q) + : c::act_quant_q8_1_avx1(x, n, q); }; + auto rows_bp_k = [&](const uint8_t* w, size_t rb, int nb, const c::ActQ* const* a, int nt, float* const* o, + int r0, int r1) { avx2 ? c::q2_0_gguf_rows_multi_avx2(w, rb, nb, a, nt, o, r0, r1) + : c::q2_0_gguf_rows_multi_avx1(w, rb, nb, a, nt, o, r0, r1); }; + auto rows_lg = [&](const uint8_t* w, size_t rb, int nb, const c::ActQ* const* a, int nt, float* const* o, + int r0, int r1) { avx2 ? c::q2_0_gguf_rows_multi_avx2_legacy(w, rb, nb, a, nt, o, r0, r1) + : c::q2_0_gguf_rows_multi_avx1_legacy(w, rb, nb, a, nt, o, r0, r1); }; std::mt19937 rng(706); std::normal_distribution nd(0.f, 1.f); int fail = 0; @@ -43,7 +55,7 @@ int main() { std::vector> xs(NT, std::vector((size_t) n)); for (int t = 0; t < NT; ++t) { for (float& v : xs[(size_t) t]) v = nd(rng) * (t % 3 == 0 ? 8.f : 1.f); - c::act_quant_q8_1_avx2(xs[(size_t) t].data(), n, acts[t]); + quant(xs[(size_t) t].data(), n, acts[t]); if (acts[t].bp_pairs != nblocks / 2) { std::printf("FAIL n=%d: no bit-plane image\n", n); ++fail; } } const c::ActQ* ap[8]; @@ -53,13 +65,13 @@ int main() { float* wo[8]; float* ro[8]; float* ao[8]; float* co[8]; for (int t = 0; t < NT; ++t) { wo[t] = win[(size_t) t].data(); ro[t] = ref[(size_t) t].data(); ao[t] = alone[(size_t) t].data(); co[t] = cut[(size_t) t].data(); } - c::q2_0_gguf_rows_multi_avx2(w.data(), row_bytes, nblocks, ap, NT, wo, 0, rows); - c::q2_0_gguf_rows_multi_avx2_legacy(w.data(), row_bytes, nblocks, ap, NT, ro, 0, rows); + rows_bp_k(w.data(), row_bytes, nblocks, ap, NT, wo, 0, rows); + rows_lg(w.data(), row_bytes, nblocks, ap, NT, ro, 0, rows); for (int t = 0; t < NT; ++t) { // one token at a time - c::q2_0_gguf_rows_multi_avx2(w.data(), row_bytes, nblocks, ap + t, 1, ao + t, 0, rows); + rows_bp_k(w.data(), row_bytes, nblocks, ap + t, 1, ao + t, 0, rows); } for (int r0 = 0; r0 < rows; r0 += 5) // rows cut into ranges of five - c::q2_0_gguf_rows_multi_avx2(w.data(), row_bytes, nblocks, ap, 3, co, r0, r0 + 5 < rows ? r0 + 5 : rows); + rows_bp_k(w.data(), row_bytes, nblocks, ap, 3, co, r0, r0 + 5 < rows ? r0 + 5 : rows); for (int t = 0; t < NT; ++t) for (int r = 0; r < rows; ++r) { const float a = win[(size_t) t][(size_t) r], b = ref[(size_t) t][(size_t) r]; @@ -82,7 +94,7 @@ int main() { static c::ActQ a; std::vector x((size_t) n); for (float& v : x) v = nd(rng); - c::act_quant_q8_1_avx2(x.data(), n, a); + quant(x.data(), n, a); if (a.bp_pairs != 0) { std::printf("FAIL: an odd block count got an image\n"); ++fail; } } std::printf(fail ? "FAIL (%d)\n" : "PASS\n", fail); diff --git a/src/kernels/cpu/q8k_quant_parity.cpp b/src/kernels/cpu/q8k_quant_parity.cpp index 535b1881..dc24e652 100644 --- a/src/kernels/cpu/q8k_quant_parity.cpp +++ b/src/kernels/cpu/q8k_quant_parity.cpp @@ -7,6 +7,7 @@ // q8k_quant_parity --bench ns per 2560-value row, ggml-cpu's and the AVX-2 copy #include "strata/kernels/cpu/expert_layout.hpp" #include "strata/kernels/cpu/iq_avx2.hpp" +#include "strata/kernels/cpu/iq_avx1.hpp" #include "strata/kernels/cpu/native_expert.hpp" #include "ggml.h" @@ -93,6 +94,7 @@ int main(int argc, char** argv) { const ggml_from_float_t ref = quantize_row_q8_K_ref; const ggml_from_float_t gcpu = ggml_get_type_traits_cpu(GGML_TYPE_Q8_K)->from_float; const bool avx2 = cpu::cpu_avx2_ok(); + const bool avx1 = !avx2 && cpu::cpu_avx1_ok(); // the older CPUs' copy (checked wherever AVX exists) int failures = 0, checked = 0; for (const int n : {256, 512, 2560, 6144}) { const size_t bytes = ggml_row_size(GGML_TYPE_Q8_K, n); @@ -100,6 +102,7 @@ int main(int argc, char** argv) { for (int ci = 0; ci < (int) cs.size(); ++ci) { failures += !same("ggml-cpu vs reference", n, ci, ref, gcpu, cs[(size_t) ci], bytes); if (avx2) failures += !same("AVX-2 vs reference", n, ci, ref, cpu::q8k_quant_avx2, cs[(size_t) ci], bytes); + if (avx1) failures += !same("AVX1 vs reference", n, ci, ref, cpu::q8k_quant_avx1, cs[(size_t) ci], bytes); ++checked; } } @@ -115,9 +118,10 @@ int main(int argc, char** argv) { failures += !same("native_quant_act", 2560, 0, ref, via_act, x, ggml_row_size(GGML_TYPE_Q8_K, 2560)); for (const auto& x : cases(512)) failures += !same("native_quant_h", 512, 0, ref, via_h, x, ggml_row_size(GGML_TYPE_Q8_K, 512)); - std::printf("q8k_quant_parity: %d rows x 4 sizes, AVX-2 copy %s: %s\n", checked / 4, - avx2 ? "checked" : "skipped (no AVX2, or STRATA_FORCE_ISA)", failures ? "FAILED" : "identical"); - if (bench && avx2) { + std::printf("q8k_quant_parity: %d rows x 4 sizes, AVX-2 copy %s, AVX1 copy %s: %s\n", checked / 4, + avx2 ? "checked" : "skipped (no AVX2, or STRATA_FORCE_ISA)", + avx1 ? "checked" : "skipped (AVX2 present, no AVX, or STRATA_FORCE_ISA)", failures ? "FAILED" : "identical"); + if (bench && (avx2 || avx1)) { std::mt19937 rng(3); std::normal_distribution nd(0.f, 1.f); const int n = 2560, rows = 4096; @@ -137,7 +141,7 @@ int main(int argc, char** argv) { return best; }; const double a = time("ggml-cpu", gcpu); - const double b = time("AVX-2", cpu::q8k_quant_avx2); + const double b = avx2 ? time("AVX-2", cpu::q8k_quant_avx2) : time("AVX1", cpu::q8k_quant_avx1); std::printf(" %.1fx\n", a / b); } return failures ? 1 : 0; diff --git a/src/kernels/cuda/dequant_bf16.cu b/src/kernels/cuda/dequant_bf16.cu index e159a96c..a6fe910e 100644 --- a/src/kernels/cuda/dequant_bf16.cu +++ b/src/kernels/cuda/dequant_bf16.cu @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -174,6 +175,30 @@ __global__ void dequant_kernel(const uint8_t* __restrict__ blocks, int64_t row_b group32(blocks + (row0 + r) * row_bytes, (int) gi, out + r * ld + gi * 32); } +// Q8_0 with four threads per block, 8 values each: the warp reads 8 consecutive blocks and writes 512 consecutive +// bytes (a thread per block wrote 2-byte values 64 bytes apart: ~110 GB/s, a quarter of a prompt projection's time) +template +__global__ void dequant_q8_0_kernel(const uint8_t* __restrict__ blocks, int64_t row_bytes, int64_t row0, int64_t rows, + int64_t groups_per_row, T* __restrict__ out) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rows * groups_per_row * 4) return; + const int64_t g = i >> 2, r = g / groups_per_row, gi = g % groups_per_row; + const int piece = (int) (i & 3); + const uint8_t* b = blocks + (row0 + r) * row_bytes + gi * 34; + const float d = h2f(b); + const uint16_t* q = (const uint16_t*) (b + 2 + 8 * piece); // blocks are 2-byte aligned + __align__(16) T v[8]; +#pragma unroll + for (int k = 0; k < 4; ++k) { + const uint16_t w = q[k]; + put(v, 2 * k, (float) (int8_t) (w & 0xFF) * d); + put(v, 2 * k + 1, (float) (int8_t) (w >> 8) * d); + } + uint4* o = (uint4*) (out + g * 32 + 8 * piece); +#pragma unroll + for (int k = 0; k < (int) (8 * sizeof(T) / 16); ++k) o[k] = ((const uint4*) v)[k]; +} + bool geometry(int type, int& block_elems, int& block_bytes) { switch (type) { case 2: block_elems = 32; block_bytes = 18; return true; @@ -205,6 +230,13 @@ void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t co const unsigned grid = (unsigned) ((total + 255) / 256); const uint8_t* p = (const uint8_t*) blocks; cudaStream_t st = (cudaStream_t) stream; + if (type == 8 && ld == cols && (reinterpret_cast(blocks) & 1) == 0 && + (reinterpret_cast(out) & 15) == 0) { // contiguous rows only (the kernel writes out + g * 32) + dequant_q8_0_kernel<<<(unsigned) ((4 * total + 255) / 256), 256, 0, st>>>(p, row_bytes, row0, rows, gpr, out); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "dequant launch: %s\n", cudaGetErrorString(e)); std::exit(1); } + return; + } #define STRATA_DQ(TY) dequant_kernel<<>>(p, row_bytes, row0, rows, gpr, ld, out); break switch (type) { case 2: STRATA_DQ(2); diff --git a/src/kernels/cuda/route_prior.cu b/src/kernels/cuda/route_prior.cu new file mode 100644 index 00000000..79a7581d --- /dev/null +++ b/src/kernels/cuda/route_prior.cu @@ -0,0 +1,79 @@ +// src/kernels/cuda/route_prior.cu - STRATA_ROUTE_PRIOR=lambda: cache-conditioned routing (opt-in, changes the output). +// +// "Mixture of Cache-Conditional Experts" (arXiv 2412.00099), without training: when a token's 10 experts are picked, +// an expert already in VRAM gets a `lambda` bonus on its logit. The SELECTION uses the biased logits; the WEIGHTS stay +// the router's (softmax over the 512 unbiased logits), renormalised over the 10 picked like the native router. Fewer +// missed experts to copy over PCIe or compute on the CPU. Unlike STRATA_ROUTE_RESIDENT (a missed tail expert swapped +// for the best resident one within a logit margin), every rank can move, by an amount the logits decide. +#include "strata/kernels/route_prior.hpp" + +#include + +#include +#include + +namespace strata::kernels { +namespace { + +__device__ __forceinline__ float wmax(float v) { +#pragma unroll + for (int m = 16; m; m >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, m, 32)); + return v; +} +__device__ __forceinline__ float wsum(float v) { +#pragma unroll + for (int m = 16; m; m >>= 1) v += __shfl_xor_sync(0xffffffffu, v, m, 32); + return v; +} + +// one warp per token; 512 experts = 16 values per lane (as the native router) +__global__ void route_prior_k(const float* __restrict__ logits, const int32_t* __restrict__ res, float lambda, + int32_t* __restrict__ ids, float* __restrict__ weights) { + const float* lg = logits + (size_t) blockIdx.x * 512; + int32_t* id = ids + (size_t) blockIdx.x * 10; + float* w = weights + (size_t) blockIdx.x * 10; + const int lane = threadIdx.x; + float p[16], s[16]; + float mx = -INFINITY; +#pragma unroll + for (int i = 0; i < 16; ++i) { p[i] = lg[lane + 32 * i]; mx = fmaxf(mx, p[i]); } + mx = wmax(mx); + float sum = 0.0f; +#pragma unroll + for (int i = 0; i < 16; ++i) { + const int e = lane + 32 * i; + s[i] = p[i] + (res[e] >= 0 ? lambda : 0.0f); // the selection score + p[i] = expf(p[i] - mx); // the router's probability (unnormalised) + sum += p[i]; + } + (void) wsum(sum); + float sel_p = 0.0f, sel_sum = 0.0f; + for (int rank = 0; rank < 10; ++rank) { + float best = -FLT_MAX, bp = 0.0f; + int be = 1 << 30; +#pragma unroll + for (int i = 0; i < 16; ++i) + if (s[i] > best) { best = s[i]; be = lane + 32 * i; bp = p[i]; } +#pragma unroll + for (int m = 16; m; m >>= 1) { + const float ob = __shfl_xor_sync(0xffffffffu, best, m, 32); + const int oe = __shfl_xor_sync(0xffffffffu, be, m, 32); + const float op = __shfl_xor_sync(0xffffffffu, bp, m, 32); + if (ob > best || (ob == best && oe < be)) { best = ob; be = oe; bp = op; } + } + if ((be & 31) == lane) s[be >> 5] = -FLT_MAX; + if (lane == rank) { id[rank] = be; sel_p = bp; } + sel_sum += bp; // the same on every lane + } + if (lane < 10) w[lane] = sel_p / fmaxf(sel_sum, 1e-30f); +} + +} // namespace + +void route_prior_top10(const float* logits, const int32_t* res_layer, float lambda, int32_t* ids, float* weights, + int n_tok, void* stream) { + if (n_tok <= 0) return; + route_prior_k<<>>(logits, res_layer, lambda, ids, weights); +} + +} // namespace strata::kernels diff --git a/src/kernels/cuda/sampler.cu b/src/kernels/cuda/sampler.cu index fb40668f..b9e04318 100644 --- a/src/kernels/cuda/sampler.cu +++ b/src/kernels/cuda/sampler.cu @@ -158,7 +158,7 @@ __global__ void sampler_greedy_kernel(const float* __restrict__ logits, int n_vo float bv = __int_as_float(0xff800000); // -inf int best = n_vocab; for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) { - const float s = apply_penalties(l[v], hit_count(v), p); + const float s = apply_penalties(p.logit_bias ? l[v] + p.logit_bias[v] : l[v], hit_count(v), p); if (s > bv) { bv = s; best = v; } } for (int off = 16; off > 0; off >>= 1) { @@ -355,7 +355,7 @@ __global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, in bool taken = false; for (int j = 0; j < i; ++j) if (sel_ids[j] == v) { taken = true; break; } if (taken) continue; - const float s = apply_penalties(l[v], hit_count(v), p); + const float s = apply_penalties(p.logit_bias ? l[v] + p.logit_bias[v] : l[v], hit_count(v), p); if (s > bv) { bv = s; best = v; } } for (int off = 16; off > 0; off >>= 1) { @@ -601,7 +601,7 @@ sampler_one_block_kernel(const float* __restrict__ logits, int n_vocab, const in float bv = __int_as_float(0xff800000); // -inf int best = n_vocab; for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) { - const float s = apply_penalties(l[v], hit_count(v), p); + const float s = apply_penalties(p.logit_bias ? l[v] + p.logit_bias[v] : l[v], hit_count(v), p); if ((s < prev_v || (s == prev_v && v > prev_i)) && s > bv) { bv = s; best = v; } } for (int off = 16; off > 0; off >>= 1) { @@ -730,7 +730,7 @@ sampler_split_part_kernel(const float* __restrict__ logits, int n_vocab, const i #pragma unroll for (int j = 0; j < kSplitPerLane; ++j) { const int v = lo + 32 * j + lane; - s[j] = v < n_vocab ? l[v] : __int_as_float(0xff800000); + s[j] = v < n_vocab ? (p.logit_bias ? l[v] + p.logit_bias[v] : l[v]) : __int_as_float(0xff800000); } if (use_bits) { #pragma unroll @@ -1258,7 +1258,7 @@ void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* hi }(); // One block per token, 1,024 threads over the vocabulary. See `sampler_greedy_kernel`. const int gthreads = 1024; - if (!(multi && shmem == 0 && sample_greedy_cluster(logits, n_tokens, n_vocab, out, stream))) + if (!(multi && shmem == 0 && !p.logit_bias && sample_greedy_cluster(logits, n_tokens, n_vocab, out, stream))) sampler_greedy_kernel<<<(unsigned) n_tokens, gthreads, shmem, (cudaStream_t) stream>>>( logits, n_vocab, history, history_len, p, p.penalty_last_n, p.penalty_last_n, out); } else if (sampled_path() == SampledPath::Old) { diff --git a/src/kernels/sampler_parity.cpp b/src/kernels/sampler_parity.cpp index 1c1cf88b..744800c8 100644 --- a/src/kernels/sampler_parity.cpp +++ b/src/kernels/sampler_parity.cpp @@ -484,6 +484,54 @@ int main(int argc, char** argv) { int bad = 0; const int NV = 512, NT = 4; + // Request bias affects every target row, including greedy; omission leaves logits and the default pick intact. + // Compare against an independently pre-biased input through each ctest sampler implementation. + { + std::vector l(NV * NT), bias(NV, 0.0f), adjusted; + for (int t = 0; t < NT; ++t) + for (int v = 0; v < NV; ++v) l[t * NV + v] = float(v % 17) / 4; + l[0] = 50; + bias[0] = -std::numeric_limits::infinity(); + bias[7] = 20; + bias[16] = -9; + adjusted = l; + for (int t = 0; t < NT; ++t) + for (int v = 0; v < NV; ++v) adjusted[t * NV + v] += bias[v]; + float* db = nullptr; + check(cudaMalloc(&db, NV * sizeof(float)), "bias malloc"); + check(cudaMemcpy(db, bias.data(), NV * sizeof(float), cudaMemcpyHostToDevice), "bias upload"); + std::vector hist(NT * 4, 7); + DeviceRows raw(l, NT, hist, 4), expected(adjusted, NT, hist, 4); + for (bool greedy : {true, false}) for (bool penalty : {false, true}) { + strata::kernels::SamplerParams p; + p.greedy = greedy; p.temperature = greedy ? 0 : 0.8f; p.seed = 71; p.top_k = 16; + if (penalty) { p.penalty_last_n = 4; p.penalty_freq = 3; p.penalty_repeat = 1.1f; } + const auto want = expected.sample(p, nullptr); + p.logit_bias = db; + const auto got = raw.sample(p, nullptr); + if (got != want || std::find(got.begin(), got.end(), 0) != got.end()) ++bad; + p.logit_bias = nullptr; + DeviceRows plain(l, NT, hist, 4); + if (raw.sample(p, nullptr) != plain.sample(p, nullptr)) ++bad; + } + std::vector unchanged(l.size()); + check(cudaMemcpy(unchanged.data(), raw.l, l.size() * sizeof(float), cudaMemcpyDeviceToHost), "raw logits"); + if (unchanged != l) ++bad; + // The reporter's vocabulary scale, with only one permitted token: masked entries cannot win top-k tails. + const int vocab = 248320; + std::vector large(vocab, 100), bans(vocab, -std::numeric_limits::infinity()); + bans[109266] = 0; large[109266] = -50; + cudaFree(db); + check(cudaMalloc(&db, vocab * sizeof(float)), "large bias malloc"); + check(cudaMemcpy(db, bans.data(), bans.size() * sizeof(float), cudaMemcpyHostToDevice), "large bias upload"); + DeviceRows many(large, 1, {}, 0); + for (bool greedy : {true, false}) { + strata::kernels::SamplerParams p; p.greedy = greedy; p.logit_bias = db; + if (many.sample(p, nullptr) != std::vector{109266}) ++bad; + } + cudaFree(db); + } + // ---- fixture 1: plain greedy. top_k = 0 (disabled), top_p = 1 (disabled), T = 1 -> argmax. { strata::kernels::SamplerParams p; p.top_k = 0; p.top_p = 1.0f; p.temperature = 1.0f; p.greedy = true; diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu index 2c1db6de..29d9292a 100644 --- a/src/prefill/gemm.cu +++ b/src/prefill/gemm.cu @@ -674,10 +674,32 @@ void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_ return; } #endif +#if !defined(__HIPCC__) + const auto f16_gemm = [&](cublasGemmAlgo_t algo) { + return cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &alpha, + W, CUDA_R_16F, (int) K, X, CUDA_R_16F, (int) K, &beta, Y, CUDA_R_32F, (int) ldy, + CUBLAS_COMPUTE_32F, algo); + }; + // Issue #1650: with a second CUDA device initialized in the process, cuBLAS 12 answers the default algorithm of a + // few shapes - narrow ones, and the set moves with K - with CUBLAS_STATUS_INTERNAL_ERROR; a fixed algorithm keeps + // a kernel that state does not break. Only the shapes that fail are moved (the failing call itself is harmless); + // the wide shapes, for which the fixed algorithms are markedly slower, stay on the default. + const int64_t shape = ((int64_t) K << 32) | (uint32_t) N; + cublasGemmAlgo_t algo = CUBLAS_GEMM_DEFAULT; + for (int i = 0; i < f16_algo_n_; ++i) + if (f16_algo_shape_[i] == shape) { algo = CUBLAS_GEMM_ALGO2; break; } + cublasStatus_t st = f16_gemm(algo); + if (st == CUBLAS_STATUS_INTERNAL_ERROR && algo == CUBLAS_GEMM_DEFAULT) { + if (f16_algo_n_ < kF16AlgoSlots) f16_algo_shape_[f16_algo_n_++] = shape; + st = f16_gemm(CUBLAS_GEMM_ALGO2); + } + ck(st, "cublasGemmEx f16"); +#else ck(cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &alpha, W, CUDA_R_16F, (int) K, X, CUDA_R_16F, (int) K, &beta, Y, CUDA_R_32F, (int) ldy, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT), "cublasGemmEx f16"); +#endif STRATA_ABSORB_HIPBLAS_STICKY("cublasGemmEx f16"); } diff --git a/src/prefill/mmq_resident_sort.hpp b/src/prefill/mmq_resident_sort.hpp index 2e03856b..c81b4562 100644 --- a/src/prefill/mmq_resident_sort.hpp +++ b/src/prefill/mmq_resident_sort.hpp @@ -21,7 +21,10 @@ inline bool mmq_resident_sort_requested() { inline bool mmq_resident_sort_eligible(bool requested, bool use_mmq, bool native_layout, bool has_cache, const int32_t* layer_resident, int64_t n_expert, bool stream_all, bool layer_stream_empty) { - if (!requested || !use_mmq || native_layout || !has_cache || !layer_resident || n_expert <= 0) return false; + // native-layout packs too: slot/src/off are built the same way for both layouts, and nothing reads off[e + 1] as a + // count (4x GP100, sm_60: 1.2K prompt 7.27 -> 5.32 s, 35K 63.3 -> 54.1 s, the same bits) + (void) native_layout; + if (!requested || !use_mmq || !has_cache || !layer_resident || n_expert <= 0) return false; // All experts, including unselected ones: leave every partial/streamed layer in ID order. if (stream_all && !layer_stream_empty) return false; for (int64_t e = 0; e < n_expert; ++e) if (layer_resident[e] < 0) return false; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 3248acb1..7f76ca12 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1,3 +1,4 @@ +#include "strata/core/logit_bias.hpp" // src/program/generate.cpp - P2.S6: `strata generate`. // // THE DRIVER, and the first program in this project that answers a question. Everything below it is a @@ -2617,7 +2618,10 @@ int main(int argc, char** argv) { else if (!strata::kernels::cpu::cpu_avx512_ok()) std::fprintf(stderr, "strata generate: this CPU has no AVX-512: the expert kernels run on %s " "(multi-token for the i-quant gate/up rows)\n", - !strata::kernels::cpu::cpu_avx2_ok() ? "ggml-cpu vec_dot (no AVX2: the older-CPU build)" + !strata::kernels::cpu::cpu_avx2_ok() + ? (strata::kernels::cpu::cpu_avx1_ok() && std::getenv("STRATA_NO_IQ128") == nullptr + ? "AVX1 128-bit (iq_avx1, the older-CPU build)" + : "ggml-cpu vec_dot (no AVX2: the older-CPU build)") : std::getenv("STRATA_NO_IQ256") == nullptr ? "AVX-2" : "ggml-cpu vec_dot (STRATA_NO_IQ256 set)"); strata::core::ModelGeometry g; // canonical defaults; the model file overrides the MoE shape below int64_t K = 10; @@ -4419,6 +4423,19 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: the file tier reads through the file cache (STRATA_UNBUFFERED_LOAD=%s " "ignored: without --resident-budget-gib the file cache holds the experts)\n", env); } +#if defined(_WIN32) + // the GPU cache's fill and the RAM copy read unbuffered even so: through the mapping their pages sat in the + // working set beside the copy (end_startup_unbuffered below, once the copy is built). Windows, experts.bin + if (o.resident_cpu_experts && !src.unbuffered()) { + std::string why; + if (src.begin_startup_unbuffered(why)) + std::fprintf(stderr, "strata generate: the GPU cache's fill and the RAM copy read unbuffered (%s)\n", + why.c_str()); + else if (why.find("STRATA_STARTUP_UNBUFFERED") == std::string::npos) + std::fprintf(stderr, "strata generate: the GPU cache's fill and the RAM copy read through the mapping " + "(%s)\n", why.c_str()); + } +#endif // Linux I/O path (opt in): whole-blob preads instead of page faults, and the predicted experts of the next // layers read ahead on I/O threads while the current layer computes (see FileExpertSource::set_io_prefetch) if (const char* v = std::getenv("STRATA_IO_PREFETCH"); v != nullptr && std::atoi(v) != 0) { @@ -4952,6 +4969,39 @@ int main(int argc, char** argv) { "slot 0 verified\n", (long long) prefilled, (long long) (per_layer ? xcache.slots() : want), fill_s, fill_s > 0 ? (double) fill_bytes / 1e6 / fill_s : 0.0); + if (std::getenv("STRATA_VERIFY_COMPLEMENT") != nullptr) { + // tests: the filled slots' checksum (each slot's blob read back and hashed, then the hashes in slot order) + std::vector> sl; // (slot, blob bytes) + for (int64_t l = 0; l < g.n_layers; ++l) + for (int64_t e = 0; e < g.n_expert; ++e) + if (const int32_t s = xcache.slot_of(l, e); s >= 0) + sl.emplace_back(s, (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(l)); + std::sort(sl.begin(), sl.end()); + std::vector sh(sl.size(), 0); + std::atomic next_slot{0}; + std::atomic copy_ok{true}; + auto hash_work = [&] { + std::vector hb; + for (size_t i; (i = next_slot.fetch_add(1)) < sl.size();) { + hb.resize((size_t) sl[i].second); + if (cudaMemcpy(hb.data(), xcache.device_slot(sl[i].first), hb.size(), cudaMemcpyDeviceToHost) != + cudaSuccess) copy_ok = false; + sh[i] = strata::core::fnv1a64(hb.data(), (uint64_t) hb.size()); + } + }; + std::vector hth; + for (int t = 1; t < 8; ++t) hth.emplace_back(hash_work); + hash_work(); + for (auto& t : hth) t.join(); + uint64_t h = strata::core::fnv1a64(nullptr, 0); + for (size_t i = 0; i < sl.size(); ++i) { // field by field: a pair's padding is not part of it + const int64_t v[2] = {(int64_t) sl[i].first, sl[i].second}; + h = strata::core::fnv1a64((const uint8_t*) v, sizeof v, h); + h = strata::core::fnv1a64((const uint8_t*) &sh[i], sizeof sh[i], h); + } + std::fprintf(stderr, "strata generate: expert cache checksum %016llx (%zu slots%s)\n", (unsigned long long) h, + sl.size(), copy_ok ? "" : ", A READ-BACK FAILED"); + } } for (auto& stp : stages) { @@ -6299,8 +6349,8 @@ int main(int argc, char** argv) { } for (const auto& [i, s] : filled) host_res[i] = s; kvg.refilled += (int64_t) filled.size(); - if (cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice) != cudaSuccess) - return false; + // res_put waits for its copy: the next reader can be a verify window (a non-blocking stream) right away + if (res_put(d_res) != cudaSuccess) return false; for (const strata::core::VmmChunk h : kvg.spare) strata::core::vmm_chunk_free(h); // new ones, if any kvg.spare.clear(); ++kvg.trims; @@ -6451,6 +6501,17 @@ int main(int argc, char** argv) { else err = whole_err + "; " + err; } + // the startup reads are done: the view of experts.bin back, the file tier as chosen above + bool startup_kept = false; + if (src.startup_unbuffered()) { + std::string why; + const auto end_t0 = std::chrono::steady_clock::now(); + startup_kept = !src.end_startup_unbuffered(why); + if (startup_kept) std::fprintf(stderr, "strata generate: WARNING: %s\n", why.c_str()); + else + std::fprintf(stderr, "strata generate: the startup reads are done: experts.bin mapped again (%.0f ms)\n", + std::chrono::duration(std::chrono::steady_clock::now() - end_t0).count()); + } // #669 / #765: a big chunk lends many cache slots to the prompt path, and each lent slot's expert is read back // from the SSD whenever the RAM could not keep its copy (31 GB: auto:32768 read prompts ~3x slower than auto). // Said, never capped: --prefill is the user's, and with the RAM for them it is the faster one (+21-35%). @@ -6503,7 +6564,7 @@ int main(int argc, char** argv) { // the file cache keeps those, and every refill after a prompt read the drive instead). Windows and Linux: the // unbuffered reads exist there #if defined(_WIN32) || defined(__linux__) - if (o.mmap_experts && o.resident_budget > 0) { + if (o.mmap_experts && o.resident_budget > 0 && !startup_kept) { std::string why; const bool was = src.unbuffered(); const bool ub = src.recheck_unbuffered(why); @@ -6563,6 +6624,23 @@ int main(int argc, char** argv) { // neither fires, plain one-token-per-round decoding - slower, never wrong: the verify window still // confirms every emitted token against the real model regardless of where the draft came from. const bool use_mtp = !o.mtp.empty(); + // STRATA_PREFILL_HELPER_SOURCE (opt-in): the prompt path may take a blob a helper's VRAM cache already + // holds from that cache instead of reading the files again. The helpers are idle while a prompt is read + // (the serve path is serial: no batch slots), so the copy needs no ordering against their kernel streams. + // Everything else - the fallback's batched unbuffered reads, its pinned RAM copy, the prompt path's own + // decisions - is forwarded unchanged. Default off: the prompt path's source is srcp, exactly as before. + std::vector prefill_helpers; + for (int r = 0; r < drive.d.remote_count; ++r) prefill_helpers.push_back(drive.d.remote[r]); + std::unique_ptr prefill_helper_src; + strata::core::ExpertSource* prefill_src = srcp; + uint64_t helper_blobs_before = 0, helper_bytes_before = 0; + if (const char* hv = std::getenv("STRATA_PREFILL_HELPER_SOURCE"); hv != nullptr && std::atoi(hv) != 0 && + srcp != nullptr && !multi_gpu && stages.empty() && o.batch <= 0 && !prefill_helpers.empty()) { + prefill_helper_src = std::make_unique(*srcp, prefill_helpers); + prefill_src = prefill_helper_src.get(); + std::fprintf(stderr, "strata serve: the prompt path reads the experts a helper cache holds from that " + "cache (STRATA_PREFILL_HELPER_SOURCE)\n"); + } strata::prefill::Prefill sp; // the pool is idle while a prompt is read unless batch slots decode between its parts; with // STRATA_PREFILL_CPU_SHARE the staged-chunk limit before the chunk below sizes the loans (bytes_needed reads it) @@ -6891,7 +6969,7 @@ int main(int argc, char** argv) { } if (multi_gpu) sp.set_stage(0, split_at[0], &stages[0]->sp); if (share_pool) sp.set_cpu_pool(&pool); - if (!sp.init(wt, g, ss, srcp, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes)) + if (!sp.init(wt, g, ss, prefill_src, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes)) return err.find("do not fit") != std::string::npos ? 2 : 1; return 0; }; @@ -8481,7 +8559,7 @@ int main(int argc, char** argv) { slots_all += remote_experts[(size_t) r].resident(); mib_all += (int64_t) (remote_experts[(size_t) r].gib() * 1024.0); } - std::printf("INFO context=%lld kv=%s kv_resident=%lld expert_slots=%lld expert_cache_mib=%lld " + std::printf("INFO logit_bias=1 context=%lld kv=%s kv_resident=%lld expert_slots=%lld expert_cache_mib=%lld " "expert_slots_primary=%lld expert_cache_primary_mib=%lld spec=%d " "mtp_max=%d lookup=%d vram_free_mib=%lld cvec=%s arena_mib=%lld pool_workers=%d pcie_frac=%.2f " "spec_min_p=%.2f conversation_cache_mib=%lld conversation_cache_slots=%d " @@ -9382,6 +9460,8 @@ int main(int argc, char** argv) { unsigned long long req_seed = 0; float req_min_p = 0.0f, req_penalty_repeat = 1.0f, req_penalty_freq = 0.0f, req_penalty_present = 0.0f; int req_penalty_last_n = 0; + std::string req_bias_text; + bool req_bias_present = false; int req_cvec = 1; // cvec=0|1: a loaded control vector for this request (on when absent) // ckpt=0: a one-shot call whose turn no later request extends. No checkpoint at its last turn boundary // (so no split there) nor every --prompt-cache-every tokens, and its session is neither continued nor @@ -9409,7 +9489,8 @@ int main(int argc, char** argv) { if (eq == std::string::npos) { endp = const_cast(start); break; } const std::string key = tok.substr(0, eq); const float fv = std::strtof(tok.c_str() + eq + 1, nullptr); - if (key == "cvec") req_cvec = std::atoi(tok.c_str() + eq + 1); + if (key == "logit_bias") { req_bias_text = tok.substr(eq + 1); req_bias_present = true; } + else if (key == "cvec") req_cvec = std::atoi(tok.c_str() + eq + 1); else if (key == "ckpt") req_ckpt = std::atoi(tok.c_str() + eq + 1) != 0; else if (key == "pin") req_pin = std::max(0, std::atoll(tok.c_str() + eq + 1)); else if (key == "temperature") req_temperature = fv; @@ -9427,6 +9508,13 @@ int main(int argc, char** argv) { // unknown keys are skipped: the ids start at the first token without '=' } } + std::vector req_bias; + std::string bias_error; + if (req_bias_present && (o.batch > 0 || + !strata::core::parse_logit_bias(req_bias_text, (int) n_vocab, req_bias, bias_error))) { + std::printf("ERR logit_bias: %s\n", o.batch > 0 ? "continuous batching is not supported" : bias_error.c_str()); + continue; + } std::string emb_path; if (geni && endp != nullptr) { while (*endp == ' ') ++endp; @@ -10268,6 +10356,10 @@ int main(int argc, char** argv) { req_sp.penalty_freq = req_penalty_freq; req_sp.penalty_present = req_penalty_present; req_sp.counter = 0; + if (!ver.set_logit_bias(req_bias, err) || (pipe && !ver_b.set_logit_bias(req_bias, err))) { + std::printf("ERR %s\n", err.c_str()); + return 1; + } ver.set_sampling(req_sp); if (pipe) ver_b.set_sampling(req_sp); // (reaches the later stage's odd verifier) if (use_mtp) mtp.set_draft_sampling(req_sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise) @@ -11507,6 +11599,9 @@ int main(int argc, char** argv) { 100.0 * (double) req_hits / (double) req_look, (long long) req_hits, (long long) req_look, off); } + if (drive.d.tail_experts > 0) // STRATA_ROUTE_TAIL_SKIP, cumulative + std::fprintf(stderr, "strata serve: route tail skip: %lld missed experts skipped (%lld entries) since the " + "start\n", (long long) drive.d.tail_experts, (long long) drive.d.tail_skipped); // the resident RAM mode, cumulative: experts read from experts.bin since the copy was made (what the plain // mmap mode reads through the OS file cache, from the SSD when the RAM could not keep it) if (src.complement_ready()) @@ -11612,6 +11707,14 @@ int main(int argc, char** argv) { (double) (remote_experts[(size_t) r].full_row_bytes() - full_before[(size_t) r]) / 1048576.0, remote_experts[(size_t) r].ms_begin() - begin_before[(size_t) r], remote_experts[(size_t) r].ms_wait() - wait_before[(size_t) r]); + if (prefill_helper_src) { + const uint64_t blobs = prefill_helper_src->helper_blobs(), bytes = prefill_helper_src->helper_bytes(); + std::fprintf(stderr, "strata serve: prefill helper source: %lld blobs / %.1f MiB taken from a helper's " + "cache in this request\n", + (long long) (blobs - helper_blobs_before), (double) (bytes - helper_bytes_before) / 1048576.0); + helper_blobs_before = blobs; + helper_bytes_before = bytes; + } } save_profile("exit"); // #477: QUIT, or the server closed stdin return 0; @@ -12237,13 +12340,18 @@ int main(int argc, char** argv) { if (pk.lookup) { T = pk.t; from_sfx = true; } } } + // The window's rows sit at p .. p + T - 1, and past the context there is no cell to verify them in: near + // its end the window takes only the rows that fit (the admission checked the prompt and max_new, which a + // full window can overrun) + const int room = (int) std::min(o.spec, o.max_context - p); + T = std::min(T, room); // --lookup-chain: what followed an earlier occurrence of the context + the MTP's drafts, after them int chain_n = 0, cm = 0; - if (o.lookup_chain > 0 && use_mtp && !first_window && !from_sfx && T < o.spec) { + if (o.lookup_chain > 0 && use_mtp && !first_window && !from_sfx && T < room) { int csrc = -1; const int nt = chain_tail(sfx, drafts.data(), T - 1, ctail); chain_n = strata::spec::propose_from_sources(lookup_src, ctail.data(), nt, T - 1, - std::min(o.lookup_chain, o.spec - T), o.lookup_chain_min, + std::min(o.lookup_chain, room - T), o.lookup_chain_min, cbuf.data(), &cm, &csrc); if (chain_n > 0 && std::getenv("STRATA_LOOKUP_CHAIN_FIXED") == nullptr) { double p_mtp = 1.0; diff --git a/tools/agent_turns_bench.py b/tools/agent_turns_bench.py new file mode 100644 index 00000000..198ebcc8 --- /dev/null +++ b/tools/agent_turns_bench.py @@ -0,0 +1,216 @@ +"""Decode A/B on coding-agent turns over this repository: arms restarted per round, per-turn ratios. + + python tools/agent_turns_bench.py strata-iq2_xs.json base: hcq8:STRATA_HC_Q8=2 [--rounds 2] + +The workload is five simulated coding-agent sessions over this repository's own files (README, serve/, setup.py, the +expert cache, the hyper-connection kernels, the tokenizer): a system prompt, four tools, a task (three in English, two +in French), then tool calls whose results are the real files, at most 2,000 lines per read as agents' read tools +return them. Every point right after a tool result is one turn the model continues - 23 turns from ~2.5K to ~100K +tokens with the repository as of 0.1.41, consecutive turns sharing their prefix as in a real session. Nothing +personal and nothing downloaded: anyone with this checkout gets the same requests. + +Arms are given as ab_engine.py takes them (NAME:key=value,...; `exe` replaces the engine, `xargs` appends +';'-separated engine arguments, any other key goes to the engine's environment). The rounds mirror the arm order +(A B, B A, ...), each arm on a fresh server. Sampling is the agent's (temperature 1, top-p 0.95, top-k 20, a fixed +seed), 256 new tokens per turn. The result is the server's own decode tok/s per turn and, per arm, the median of the +per-turn ratios to the first arm with the number of turns it won: a whole-session median hides which turns moved. +""" +from __future__ import annotations + +import argparse +import json +import os +import statistics +import subprocess +import sys +import tempfile +import time +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from ab_engine import wait_ready # noqa: E402 + +SYSTEM = ("You are an autonomous coding agent working in the user's repository. You can read files, search the code, " + "edit files and run commands with the tools below. Work step by step: read the code you need before changing " + "it, make small and correct edits, keep the existing style, and explain briefly what you did. Never invent " + "file contents: read them. When the task is done, give a short summary of the changes and how to test them.") + +TOOLS = [ + {"type": "function", "function": { + "name": "read_file", "description": "Read a file of the repository (UTF-8 text).", + "parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "path from the repository root"}}, + "required": ["path"]}}}, + {"type": "function", "function": { + "name": "grep", "description": "Search the repository for a regular expression; returns matching lines.", + "parameters": {"type": "object", "properties": {"pattern": {"type": "string"}, "path": {"type": "string"}}, + "required": ["pattern"]}}}, + {"type": "function", "function": { + "name": "edit_file", "description": "Replace an exact string in a file with a new one.", + "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "old": {"type": "string"}, + "new": {"type": "string"}}, "required": ["path", "old", "new"]}}}, + {"type": "function", "function": { + "name": "run", "description": "Run a shell command in the repository and return its output.", + "parameters": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}}}, +] + +# (name, task, [(tool, argument, what the assistant says before the call)]) +SESSIONS = [ + ("server-option", + "Add a `--max-queue N` option to the HTTP server that rejects new chat requests with HTTP 503 when N requests are " + "already waiting, document it in the README's settings section, and add a test.", + [("read_file", "README.md", "I'll start with the README to see how settings are documented."), + ("grep", "add_argument", "Now let me find where the server parses its options."), + ("read_file", "serve/server.py", "The options are in serve/server.py; reading it."), + ("read_file", "serve/frontend.py", "Requests go through the frontend; let me read it too."), + ("read_file", "docs/DETAILS.md", "Checking DETAILS.md for the existing API documentation style.")]), + ("expert-cache", + "Explain precisely how the expert cache decides which experts stay in VRAM during decode, then propose and " + "implement a small improvement to its eviction policy with a measurement plan.", + [("read_file", "docs/HOW_IT_WORKS.md", "Let me read the design overview first."), + ("read_file", "include/strata/core/expert_cache.hpp", "Now the cache's interface."), + ("read_file", "src/core/expert_cache.cpp", "And its implementation."), + ("grep", "adapt_every", "Searching for the adaptive swap logic."), + ("read_file", "src/core/expert_source.cpp", "The dispatch that consults the cache is in expert_source.cpp.")]), + ("installer-fr", + "Dans l'installateur, la détection de la RAM disponible se trompe parfois sous Windows quand un autre programme " + "réserve beaucoup de mémoire. Trouve où elle est faite, corrige-la, ajoute un test et explique la correction en " + "français.", + [("read_file", "setup.py", "Je commence par lire l'installateur."), + ("grep", "def .*ram", "Je cherche les fonctions qui mesurent la RAM."), + ("read_file", "docs/INSTALL.md", "Je vérifie ce que la documentation promet sur la RAM."), + ("read_file", "docs/MODELS.md", "Le choix du modèle dépend de la RAM ; je lis cette page aussi.")]), + ("cuda-kernel", + "The hyper-connection read kernels are latency bound on small batches. Read them, explain where the time goes, " + "and write a faster variant for 1-4 tokens that keeps the same results bit for bit.", + [("read_file", "include/strata/kernels/fused_gr.hpp", "First the kernel interface."), + ("read_file", "src/kernels/cuda/fused_gr.cu", "Now the kernels themselves."), + ("grep", "fused_gr_read_multi", "Where are they called from?"), + ("read_file", "src/core/verify.cpp", "The verify window calls them; reading it.")]), + ("tokenizer-fr", + "Écris une suite de tests pytest pour le tokenizer Python (encodage, décodage, tokens spéciaux, texte multilingue, " + "cas limites), puis corrige les bugs que les tests révèlent. Réponds en français.", + [("read_file", "tools/strata_tokenizer.py", "Je lis d'abord le tokenizer."), + ("grep", "strata_tokenizer", "Je cherche qui l'utilise."), + ("read_file", "serve/frontend.py", "Le frontend l'appelle ; je le lis pour voir les usages réels."), + ("read_file", "serve/chat_template.jinja", "Je regarde aussi le modèle de conversation."), + ("read_file", "chat.py", "Et le client en ligne de commande.")]), +] + + +def tool_result(tool: str, arg: str) -> str: + if tool == "read_file": + lines = (ROOT / arg).read_text(encoding="utf-8", errors="replace").splitlines() + text = "\n".join(lines[:2000]) + return text + (f"\n... (truncated: lines 1-2000 of {len(lines)})" if len(lines) > 2000 else "") + if tool == "grep": + r = subprocess.run(["git", "-C", str(ROOT), "grep", "-n", "-I", "-E", arg], capture_output=True, text=True, + encoding="utf-8", errors="replace") + lines = r.stdout.splitlines() + return "\n".join(lines[:200]) + (f"\n... ({len(lines) - 200} more lines)" if len(lines) > 200 else "") + raise ValueError(tool) + + +def turns() -> list[tuple[str, list[dict]]]: + """[(tag, messages)]: one entry per point right after a tool result.""" + out = [] + for name, task, steps in SESSIONS: + msgs = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": task}] + for i, (tool, arg, before) in enumerate(steps): + cid = f"call_{name}_{i}" + args = {"path": arg} if tool == "read_file" else {"pattern": arg} + msgs.append({"role": "assistant", "content": before, + "tool_calls": [{"id": cid, "type": "function", + "function": {"name": tool, "arguments": json.dumps(args)}}]}) + msgs.append({"role": "tool", "tool_call_id": cid, "content": tool_result(tool, arg)}) + out.append((f"{name}.{i}", [dict(m) for m in msgs])) + return out + + +def post(port: int, messages: list[dict], max_tokens: int, seed: int) -> dict: + body = {"messages": messages, "tools": TOOLS, "max_tokens": max_tokens, "temperature": 1.0, "top_p": 0.95, + "top_k": 20, "seed": seed, "reasoning_effort": "high"} + req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=3600) as r: + return json.loads(r.read()) + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("config") + ap.add_argument("arms", nargs="+") + ap.add_argument("--rounds", type=int, default=2) + ap.add_argument("--port", type=int, default=8090) + ap.add_argument("--max-new", type=int, default=256) + ap.add_argument("--max-turns", type=int, default=0, help="only the first N turns (0: all)") + ap.add_argument("--seed", type=int, default=1234) + ap.add_argument("--log", default="agent_turns_bench.jsonl") + a = ap.parse_args() + base = json.loads(Path(a.config).read_text()) + arms = [] + for s in a.arms: + name, _, kv = s.partition(":") + arms.append((name, dict(x.split("=", 1) for x in kv.split(",") if x))) + work = turns() + if a.max_turns: + work = work[:a.max_turns] + out = open(a.log, "a") + res: dict = {n: {} for n, _ in arms} + for rnd in range(a.rounds): + for name, env in (arms if rnd % 2 == 0 else arms[::-1]): + cfg = dict(base) + e = dict(env) + if "exe" in e: + cfg["exe"] = e.pop("exe") + if "xargs" in e: + cfg["args"] = list(base["args"]) + e.pop("xargs").split(";") + cfg["port"] = a.port + cfg["log"] = str(Path(tempfile.gettempdir()) / f"agent_turns_{name}_r{rnd}.log") + cpath = Path(tempfile.gettempdir()) / f"agent_turns_{name}.json" + cpath.write_text(json.dumps(cfg, indent=1)) + proc = subprocess.Popen([sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", + str(cpath), "--port", str(a.port)], cwd=str(ROOT), env=dict(os.environ, **e), + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + t0 = time.time() + wait_ready(a.port, proc) + print(f"round {rnd} {name}: ready in {time.time() - t0:.0f} s", flush=True) + for tag, msgs in work: + r = post(a.port, msgs, a.max_new, a.seed) + t = r.get("timings", {}) + row = {"round": rnd, "arm": name, "turn": tag, "decode": t.get("predicted_per_second"), + "prompt_n": t.get("prompt_n"), "prompt": t.get("prompt_per_second"), + "n": r.get("usage", {}).get("completion_tokens")} + out.write(json.dumps(row) + "\n") + out.flush() + res[name].setdefault(tag, []).append(row) + print(f" {tag:16s} decode {row['decode']} tok/s prompt {row['prompt_n']} tokens", flush=True) + finally: + proc.terminate() + try: + proc.wait(60) + except subprocess.TimeoutExpired: + proc.kill() + time.sleep(5) + first = arms[0][0] + + def per_turn(name: str, tag: str) -> float: + v = [x["decode"] for x in res[name].get(tag, []) if x["decode"]] + return statistics.mean(v) if v else float("nan") + + print(f"\nper-turn decode ratio to {first} (mean over rounds per turn, then the median over turns):") + for name, _ in arms: + med = statistics.median([per_turn(name, t) for t, _ in work]) + if name == first: + print(f" {name:10s} median decode {med:6.1f} tok/s") + continue + r = [per_turn(name, t) / per_turn(first, t) for t, _ in work] + print(f" {name:10s} median decode {med:6.1f} tok/s x{statistics.median(r):.3f} (x{min(r):.2f} to " + f"x{max(r):.2f}), {sum(x > 1 for x in r)}/{len(r)} turns faster") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/logit_bias_english_example.py b/tools/logit_bias_english_example.py new file mode 100644 index 00000000..f9f710eb --- /dev/null +++ b/tools/logit_bias_english_example.py @@ -0,0 +1,81 @@ +"""Record the same English greeting request before and after a token ban.""" +import argparse +import json +from pathlib import Path +import sys +import urllib.request + +ap = argparse.ArgumentParser(description=__doc__) +for name in ['source', 'config', 'candidate', 'output']: + ap.add_argument('--' + name, type=Path, required=True) +a = ap.parse_args() +source = a.source.resolve() +sys.path[:0] = [str(source), str(source / 'tools')] +from serve.server import StrataEngine, Service, engine_args, child_env, serve +from serve.frontend import ChatTemplate +import strata_tokenizer as ST + +cfg = json.loads(a.config.read_text()) +cfg = {k: v for k, v in cfg.items() if k in ['args', 'tokenizer', 'gpu', 'lib_dirs', 'env']} +args = list(cfg['args']) +for flag in ['--conversation-cache-spill-dir', '--conversation-cache-disk-mib', '--mtp']: + if flag in args: + i = args.index(flag) + del args[i:i+2] +args = [x for x in args if x != '--conversation-cache-disk-only'] +cfg['args'] = args +tp = Path(cfg['tokenizer']) +vocab = json.loads((tp / 'vocab.json').read_text()) +tokens = [None] * len(vocab) +for token, index in vocab.items(): + tokens[index] = token +tok = ST.Tokenizer(tokens, (tp / 'merges.txt').read_text().split('\n'), + json.loads((tp / 'token_type.json').read_text())) +a.output.mkdir(parents=True, exist_ok=True) + +class AuditEngine(StrataEngine): + def generate(self, *args, **kwargs): + self.emitted = [] + for token in super().generate(*args, **kwargs): + if token is not None: + self.emitted.append(token) + yield token + +engine = AuditEngine(str(a.candidate.resolve()), engine_args(cfg), cwd=str(source), + log=str(a.output / 'engine.txt'), env=child_env(cfg)) +server = serve(Service(engine, tok, ChatTemplate(tp / 'chat_template.jinja'), + model_name='bias-validation'), port=0) +base = dict(model='bias-validation', messages=[dict(role='user', content= + 'Reply with one English greeting, one word only.')], max_tokens=8, + temperature=0, reasoning_effort='none') +rows = [] +def call(label, **extra): + request = dict(base, **extra) + req = urllib.request.Request(f'http://127.0.0.1:{server.server_address[1]}/v1/chat/completions', + data=json.dumps(request).encode(), headers={'Content-Type': 'application/json'}) + with urllib.request.urlopen(req, timeout=180) as response: + result = json.loads(response.read()) + row = dict(label=label, request=request, response=result, token_ids=list(engine.emitted)) + rows.append(row) + (a.output / 'rows.json').write_text(json.dumps(rows, indent=2, ensure_ascii=False)) + print(label, row['token_ids'], result['choices'][0]['message']['content'], flush=True) + return row + +try: + hello = tok.encode('Hello', parse_special=False) + print('Hello tokenizer IDs:', hello, flush=True) + before = call('before') + assert len(hello) == 1 and hello[0] in before['token_ids'], 'Choose a prompt whose baseline emits Hello' + banned = hello[0] + after = call('after-object', logit_bias={str(banned): -100}) + pairs = call('after-pairs', logit_bias=[[banned, False]]) + cleared = call('cleared') + assert banned not in after['token_ids'] and banned not in pairs['token_ids'] + assert after['token_ids'] == pairs['token_ids'] + assert cleared['token_ids'] == before['token_ids'] + (a.output / 'complete.json').write_text(json.dumps(dict(status='passed', requests=len(rows), + token_id=banned, token_text=tok.decode([banned])), indent=2)) +finally: + server.shutdown() + server.server_close() + engine.close() diff --git a/tools/logit_bias_http_probe.py b/tools/logit_bias_http_probe.py new file mode 100644 index 00000000..312cda14 --- /dev/null +++ b/tools/logit_bias_http_probe.py @@ -0,0 +1,91 @@ +"""Real HTTP chat validation, with emitted token IDs captured at the engine boundary.""" +import argparse, json, sys, time, urllib.error, urllib.request +from pathlib import Path +ap=argparse.ArgumentParser(description=__doc__) +for name in ['source','config','baseline','candidate','mtp','output']: + ap.add_argument('--'+name,type=Path,required=True) +a=ap.parse_args() +source=a.source.resolve() +sys.path[:0]=[str(source),str(source/'tools')] +from serve.server import StrataEngine, Service, engine_args, child_env, serve +from serve.frontend import ChatTemplate +import strata_tokenizer as ST + +cfg=json.loads(a.config.read_text()) +cfg={k:v for k,v in cfg.items() if k in ['args','tokenizer','gpu','lib_dirs','env']} +args=list(cfg['args']) +for flag in ['--conversation-cache-spill-dir','--conversation-cache-disk-mib','--mtp']: + if flag in args:i=args.index(flag);del args[i:i+2] +args=[a for a in args if a!='--conversation-cache-disk-only'] +tp=Path(cfg['tokenizer']);vocab=json.loads((tp/'vocab.json').read_text());tokens=[None]*len(vocab) +for t,i in vocab.items():tokens[i]=t +tok=ST.Tokenizer(tokens,(tp/'merges.txt').read_text().split('\n'),json.loads((tp/'token_type.json').read_text())) +template=ChatTemplate(tp/'chat_template.jinja') +rows=[] +out=a.output;out.mkdir(parents=True,exist_ok=True) +class AuditEngine(StrataEngine): + def generate(self,*a,**kw): + self.emitted=[] + for token in super().generate(*a,**kw): + if token is not None:self.emitted.append(token) + yield token + +for mode in ['baseline','off','mtp']: + exe=(a.baseline if mode=='baseline' else a.candidate).resolve() + current=list(args) + if mode=='mtp':current+=['--mtp',str(a.mtp.resolve())];current[current.index('--spec')+1]='4' + local=dict(cfg,args=current,exe=str(exe),cwd=str(source),log=str(out/(mode+'.log'))) + engine=AuditEngine(local['exe'],engine_args(local),cwd=local['cwd'],log=local['log'],env=child_env(local)) + service=Service(engine,tok,template,model_name='bias-validation') + server=serve(service,port=0) + def call(label,prompt='Write the Chinese word for hello. Only the word.',expect=200,**kw): + req={'model':'bias-validation','messages':[{'role':'user','content':prompt}],'max_tokens':8,'temperature':0,'reasoning_effort':'none',**kw} + data=json.dumps(req).encode();started=time.perf_counter() + http=urllib.request.Request(f'http://127.0.0.1:{server.server_address[1]}/v1/chat/completions',data=data,headers={'Content-Type':'application/json'}) + try: + with urllib.request.urlopen(http,timeout=180) as response:status=response.status;raw=response.read().decode() + except urllib.error.HTTPError as e: + with e:status=e.code;raw=e.read().decode() + row={'mode':mode,'label':label,'status':status,'seconds':time.perf_counter()-started,'request_bytes':len(data), + 'token_ids':list(engine.emitted) if status==200 else [],'response':raw,'engine':dict(engine.last) if status==200 else {}} + rows.append(row);(out/'rows.json').write_text(json.dumps(rows,indent=2,ensure_ascii=False)) + print(mode,label,status,row['token_ids'],flush=True) + assert status==expect,(label,status,raw) + return row + try: + first=call('unchanged-greedy') + sampled=call('unchanged-sampled',prompt='Write one sentence about Python.',temperature=0.7,top_k=20,seed=42) + if mode=='baseline':continue + assert engine.info.get('logit_bias')==1 + banned=first['token_ids'][0] + one=call('ban-object',logit_bias={str(banned):-100}) + two=call('ban-pairs',logit_bias=[[banned,False]]) + assert banned not in one['token_ids'] and banned not in two['token_ids'] + assert one['token_ids']==two['token_ids'] + boosted=tok.encode(' banana',parse_special=False)[0] + positive=call('positive-bias',logit_bias={str(boosted):100},max_tokens=3) + assert positive['token_ids'][0]==boosted + # Changing requests must not inherit a prior mask, including after a rejected request. + call('invalid-id',expect=400,logit_bias={str(len(tokens)):1},stream=True) + call('invalid-value',expect=400,logit_bias={'0':101},stream=True) + again=call('cleared-bias') + assert again['token_ids']==first['token_ids'] + empty=call('empty-bias',logit_bias={}) + assert empty['token_ids']==first['token_ids'] + large=set(range(103214));large.add(banned) + if len(large)<103215:large.add(103214) + bulk=call('103215-bans',logit_bias=[[i,False] for i in sorted(large)],max_tokens=8) + assert not set(bulk['token_ids']) & large + streamed=call('stream-ban',logit_bias={str(banned):-100},stream=True) + assert banned not in streamed['token_ids'] + sampled_ban=call('sampled-ban',logit_bias={str(banned):-100},temperature=0.8,seed=123) + assert banned not in sampled_ban['token_ids'] + finally: + server.shutdown();server.server_close();engine.close() + +for label in ['unchanged-greedy','unchanged-sampled']: + before=next(x for x in rows if x['mode']=='baseline' and x['label']==label) + after=next(x for x in rows if x['mode']=='off' and x['label']==label) + assert before['token_ids']==after['token_ids'],('default-output-changed',label) +(out/'complete.json').write_text(json.dumps({'status':'passed','requests':len(rows),'token_109266':tok.decode([109266]), + 'baseline':str(a.baseline),'candidate':str(a.candidate),'config':str(a.config)},indent=2,ensure_ascii=False))