Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Merge f-140 (3f8f333e) into the Aurora port

Niko1221d215016f401a
diff --cc CMakeLists.txt
index 86b90ec1e,e69ece0ce..4a6dd9da2
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@@ -420,10 -420,17 +420,18 @@@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_
add_library(strata_engine STATIC src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cpp
src/core/remote_expert_opt.cu
src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp
- src/core/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp src/core/peer_experts.cpp)
+ src/core/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp src/core/peer_experts.cpp
+ src/core/arch_defaults.cpp)
target_include_directories(strata_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu ${_strata_gpu_runtime_target})
+ if(STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/exchange_storage_test.cpp")
+ add_executable(exchange_storage_test tests/core/exchange_storage_test.cpp)
+ target_include_directories(exchange_storage_test PRIVATE include)
+ target_link_libraries(exchange_storage_test PRIVATE Threads::Threads)
+ add_test(NAME exchange_storage_test COMMAND exchange_storage_test)
+ set_tests_properties(exchange_storage_test PROPERTIES TIMEOUT 60)
+ endif()
+
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/file_expert_source_test.cpp")
enable_testing()
add_executable(file_expert_source_test tests/core/file_expert_source_test.cpp)
diff --cc docs/STRIX_HALO.md
index 000000000,000000000..e8f9c63db
new file mode 100644
--- /dev/null
+++ b/docs/STRIX_HALO.md
@@@ -1,0 -1,0 +1,116 @@@
++# Strix Halo (Ryzen AI Max, gfx1151): build from source on Linux
++
++Strata runs on the Ryzen AI Max "Strix Halo" APUs (Radeon 8060S / 8050S, RDNA3.5, `gfx1151`, one pool of LPDDR5X shared by the
++CPU and the GPU) through the same HIP backend as the Radeon cards in [AMD_HIP.md](AMD_HIP.md). **Status: experimental.**
++Everything here was built and measured on one machine, the maintainers' Strix Halo box (Ryzen AI Max+ 395, 128 GB,
++Ubuntu 26.04, kernel 7.0, ROCm 7.14.1). There is no ready-made engine for it and setup (`setup.sh`) does not offer it:
++it lists integrated Radeon GPUs as not supported. You build the engine yourself, as below.
++
++What the engine does differently on this chip:
++
++- **Unified memory.** The GPU's "VRAM" is the GTT pool of the same RAM. `device_free_bytes()` (the figure `--expert-cache auto` and
++ the memory plan use) counts what Linux can give back (`MemAvailable` less 6 GiB for the system, `STRATA_UMA_HEADROOM_GIB`
++ changes the 6) instead of only `MemFree`, per device, for any integrated GPU on Linux (this applies to a DGX Spark too).
++- **gfx11 matrix cores.** The prompt attention, the block scorer, the prompt GEMMs and the prompt experts have WMMA kernels for
++ gfx1100 / 1101 / 1102 / 1150 / 1151. A gfx11 part outside that list (gfx1103, gfx1152) is not given them: it takes the portable path.
++- **The hipBLASLt table** `tools/hip/gfx1151-hipblaslt-100401.txt` (ROCm 7.14.1's hipBLASLt 1.x `100401`), including the prompt shapes
++ at `--prefill 16384` (T 16383 / 16384).
++
++## 1. The toolchain (no root needed)
++
++ROCm 7.14.1 for gfx1151 from AMD's TheRock builds, extracted into a folder of your own:
++
++```sh
++mkdir -p ~/rocm && cd ~/rocm
++curl -LO https://repo.amd.com/rocm/tarball-multi-arch/therock-dist-linux-gfx1151-7.14.1.tar.gz # 1.7 GB
++sha256sum therock-dist-linux-gfx1151-7.14.1.tar.gz # c40e8f2bd6630a7d11557c762b99c6fa8afb04c9bd0e51ed1675ee1ca24afb00
++mkdir install && tar -xzf therock-dist-linux-gfx1151-7.14.1.tar.gz -C install
++export SDK=$HOME/rocm/install
++export ROCM_PATH=$SDK HIP_PATH=$SDK HIP_PLATFORM=amd
++export PATH=$SDK/bin:$SDK/lib/llvm/bin:$PATH
++export LD_LIBRARY_PATH=$SDK/lib:$SDK/lib/rocm_sysdeps/lib:$SDK/lib/llvm/lib:${LD_LIBRARY_PATH:-}
++```
++
++You also need CMake 3.24+, Ninja, git and a C++ host toolchain with libstdc++ headers (`sudo apt install build-essential cmake ninja-build git`).
++The maintainers' box has no system compiler: they point ROCm's clang at a user-space copy of gcc 15 with
++`--gcc-toolchain=<dir>/usr` (added to `CMAKE_HIP_FLAGS` below; leave it out when the system has one).
++
++The kernel's amdgpu driver and `/dev/kfd` access (your user in the `render` and `video` groups) are all the GPU side needs.
++To let the GPU use most of a 128 GB machine the maintainers' box boots with `ttm.pages_limit=29360128 ttm.page_pool_size=29360128`
++(a 112 GiB GTT; the default is about half of the RAM) and `amd_iommu=off`; both are host settings the engine does not need to run,
++only to have the room.
++
++## 2. The engine
++
++llama.cpp's `ggml` sources are pinned by this repository: CMake fetches the revision it needs. For an offline build, point
++`STRATA_GGML_DIR` at a checkout of exactly that revision.
++
++```sh
++git clone https://github.com/Niko1221/Strata.git && cd Strata
++cmake -S . -B build-halo -G Ninja -DCMAKE_BUILD_TYPE=Release \
++ -DSTRATA_ENABLE_HIP=ON -DSTRATA_ENABLE_CUDA=OFF -DSTRATA_PREFILL_MMQ=ON \
++ -DCMAKE_HIP_ARCHITECTURES=gfx1151 \
++ -DCMAKE_HIP_COMPILER=$SDK/lib/llvm/bin/clang++ -DCMAKE_HIP_COMPILER_ROCM_ROOT=$SDK \
++ "-DCMAKE_PREFIX_PATH=$SDK;$SDK/lib/rocm_sysdeps;$SDK/lib/llvm" \
++ "-DCMAKE_HIP_FLAGS=--rocm-path=$SDK --rocm-device-lib-path=$SDK/lib/llvm/amdgcn/bitcode"
++cmake --build build-halo --target strata -j 8 # about 25 minutes the first time
++```
++
++`gfx1151` is "unvalidated" in the build's own wording (it warns). `STRATA_PREFILL_MMQ=ON` builds ggml's MMQ kernels the prompt
++experts need. The tests: `cmake --build build-halo -j 8` builds them all, `ctest --test-dir build-halo` runs them;
++`hip_prefill_hcd_exact_parity` and `hip_prefill_hipblaslt_gemm` need the table (next section) and skip without it.
++
++## 3. The prompt table, and running
++
++Hand the engine the table (`setup` does it for the supported cards; for gfx1151 you do it): without it the prompt's dense matrix
++products use plain hipBLAS and are slower.
++
++```sh
++export STRATA_HIPBLASLT_TUNING=$PWD/tools/hip/gfx1151-hipblaslt-100401.txt
++```
++
++The engine accepts it only for the architecture and the hipBLASLt version named on the table's second line
++(`STRATA_HIPBLASLT_TUNING_V1 gfx1151 100401`: ROCm 7.14.1) and says so at start-up (`prefill gemm: hipBLASLt tuning enabled (90 rows,
++gfx1151, version 100401)`). Then run `strata` with the same arguments as on any other card (the model packs, `--serve`, the
++settings of [DETAILS.md](DETAILS.md)); a pack of the Unsloth UD-IQ4_XS or UD-Q4_K_XL GGUFs is what the numbers below used.
++
++## 4. What is on by default on gfx1151
++
++At start the engine looks at GPU 0; on a gfx1151 it sets the switches below unless you set them yourself
++(`STRATA_GFX1151_DEFAULTS=0` turns the whole table off, and the start-up line names what was set). **Every one of them gave
++byte-identical output on the maintainers' box** (the same token ids, 4K / 32K / 64K and four models, and a bitwise harness per kernel):
++they change speed, not answers. Nothing here applies to CUDA or to another AMD architecture.
++
++| Switch | What it does |
++|---|---|
++| `STRATA_GDN_HEAD`, `STRATA_GDN_PP=2`, `STRATA_GDN_CONVL2`, `STRATA_GDN_NOY` | the prompt's gated-delta-net recurrence: four lanes per column, two columns per lane, the convolution and the norms fused |
++| `STRATA_HCD_EXACT` | the hyper-connection down projection (N 320, K 10240) in a WMMA kernel that reproduces hipBLASLt solution 1176 / 1177's summation order (`hip_prefill_hcd_exact_parity` checks it bit for bit); it runs only where the table makes hipBLASLt pick one of those two, and says once if it cannot |
++| `STRATA_CVEC_FUSE`, `STRATA_PF_PAD` | a steered layer's write, control vector and next norm in one pass; padded GEMM row strides |
++| `STRATA_Q8_PACKED`, `STRATA_Q6_PACKED`, `STRATA_MMVF_ROWS`, `STRATA_ATTN_LANECELL` | decode layouts and kernels (packed Q8_0 / Q6_K weights, 4-row BF16 GEMV, one-cell-per-thread attention scores) |
++| `STRATA_EXPERT_V2`, `STRATA_TSUM`, `STRATA_LFUSE` | the grouped decode experts (IQ3_S / IQ4_NL), single-butterfly warp sums, fewer launches around the shared expert and the KV append |
++| `STRATA_GDN_SPLIT`, `STRATA_QFUSE`, `STRATA_PLE_BATCH` | the GDN step over four blocks per head, activation images written by their producers, the PLE key / value projections of a verify window at once |
++
++## 5. What is not on by default (it changes bits)
++
++These are faster on gfx1151 and **round differently** from the default path (a different summation order or a half-precision
++intermediate), so they are opt-in and the maintainers gate them with KL against the default (`STRATA_PF_SWITCH_MIN_T=4096` keeps
++the short prompts on the default numerics, since these pay on long ones). The maintainers' fast configuration sets all of
++them:
++
++```sh
++export STRATA_PF_FUSED=1 # the prompt experts on the matrix cores (IQ2 / IQ3 / IQ4_XS gate/up, Q2_0 / IQ4_NL / Q8_0 down)
++export STRATA_PF_GEMM=1 # the prompt's FP16 projections on the 128 x 256 WMMA GEMM
++export STRATA_HC_UPMIX=1 # the hyper-connection up projection with its epilogue
++export STRATA_PA_FAST=1 # the prompt attention with single FP16 q and p
++export STRATA_HIP_WMMA=1 # the prompt attention on matrix cores
++export STRATA_SELECT_WMMA=1 # the block scorer on matrix cores
++export STRATA_HC_Q8=1 # the hyper-connection read from the GGUF's own Q8_0 projections
++export STRATA_PF_SWITCH_MIN_T=4096
++```
++
++Two engine flags help on long contexts and are not Strix-specific: `--mtp-window 8192` (the draft layer attends to the last 8,192
++cells: 64K output +3.5%, 32K -0.4%) and `--spec`, `--lookup-chain`, `--mtp-q4` (see [DETAILS.md](DETAILS.md)).
++
++## 6. Measured
++
++(see the end of this page for the table of this build's measurements)
diff --cc include/strata/core/mtp.hpp
index 97da1e890,e43e2ac57..e4b1d6223
--- a/include/strata/core/mtp.hpp
+++ b/include/strata/core/mtp.hpp
@@@ -48,20 -48,7 +48,21 @@@ public
void set_prompt_len(int64_t n) { prompt_len_ = n; }
/// At most this many drafts per round (below max_t - 1): a window longer than the MTP's comes from elsewhere.
void set_max_drafts(int k) { max_drafts_ = k; }
+ /// --mtp-hnorm stream (opt-in; before the first draft or prefill): pre_fc_norm_hidden normalizes each
+ /// hyper-connection stream on its own, as llama.cpp's qwen4exp MTP graph does, instead of one RMS over all four.
+ void set_hnorm_per_stream(bool on) { hnorm_stream_ = on; }
+ bool hnorm_per_stream() const { return hnorm_stream_; }
+ /// --mtp-q4 (opt-in; before load): the draft layer's Q8_0 projections and its draft head run from 4-bit (Q4_0)
+ /// copies made at load/bind - fewer bytes per draft step; drafts only, the verify window decides every token.
+ /// (The prompt path's batched K/V pass keeps the Q8_0 originals.)
+ void set_q4(bool proj, bool head) { q4_ = proj; q4_head_ = head; }
+ /// --mtp-draft-vocab FILE (opt-in; before bind): the draft head's token subset from FILE instead of
+ /// rt/draft_vocab.bin (e.g. data/draft_vocab_en.bin, 40K tokens)
+ void set_draft_vocab(const std::string& path) { dvocab_path_ = path; }
+ /// STRATA_MTP_TOP2=1 (diagnostic): draft j's runner-up token in the last draft() (-1 = unknown)
+ static bool top2_env();
+ int32_t top2(int j) const { return j >= 0 && j < (int) top2_.size() ? top2_[(size_t) j] : -1; }
+ int max_t() const { return max_t_; }
uint64_t vram_bytes() const { return vram_; }
/// The draft layer's K/V state (read-only: --serve's STRATA_STATE_HASH check hashes it)
const QsaState& kv_state() const { return st_; }
@@@ -146,20 -165,16 +179,30 @@@ private
int max_t_ = 0;
int device_ = -1; ///< the device `load` ran on: the public calls switch to it (layer split)
int max_drafts_ = 1 << 30;
+ bool hnorm_stream_ = false;
+ bool q4_ = false, q4_head_ = false;
+ uint8_t* dense4_ = nullptr; ///< --mtp-q4: Q4_0 copies of the Q8_0 tensors
+ std::vector<std::pair<std::string, uint64_t>> q4_off_;
+ int dhead_type_ = -1; ///< the draft head subset's ggml type (the main head's, or Q4_0)
+ std::string dvocab_path_;
+ std::string vocab_file() const { return dvocab_path_.empty() ? rt_dir_ + "/draft_vocab.bin" : dvocab_path_; }
+ /// a projection's weights for the draft layer's own pass: the Q4_0 copy under --mtp-q4, else the Q8_0 original
+ const void* wq(const char* name, int& type) const;
+ bool make_q4_dense(const std::vector<uint8_t>& blob, std::string& err);
+ bool make_q4_head(std::string& err);
+ void record_top2(int j);
+ std::vector<int32_t> top2_, dvocab_host_;
+ std::vector<float> lg_host_;
+ // --pipeline-windows 2 (chain_launch)
+ bool stage_source_R(int T, std::string& err); ///< set_source_R's rows into the bound buffer
+ bool force_on_ = false, chain_live_ = false;
+ const float* src_R_ = nullptr;
+ int32_t *h_force_ = nullptr, *m_force_ = nullptr; ///< the forced tokens (mapped), -1 = the step's own pick
+ cudaEvent_t ev_chain_ = nullptr;
+ cudaEvent_t ev_step_[8] = {}; ///< after each of the first n_early outputs
+ int steps_seen_ = 0, chain_n_ = 0, chain_early_ = 0;
+ int32_t chain_tok_[8] = {};
+ float chain_prob_[8] = {};
int64_t n_vocab_ = 0;
uint64_t vram_ = 0;
cudaStream_t cs_ = nullptr;
diff --cc src/core/mtp.cpp
index 130dc275e,285b45f4e..da0cbacdb
--- a/src/core/mtp.cpp
+++ b/src/core/mtp.cpp
@@@ -134,9 -128,11 +134,11 @@@ MtpDrafter::~MtpDrafter()
if (state_arena_) cudaFree(state_arena_);
if (arena_) cudaFree(arena_);
if (head_logits_) cudaFree(head_logits_);
- if (dhead_) { strata::kernels::native_q6_k_unpack(dhead_); cudaFree(dhead_); }
- if (dvocab_) cudaFree(dvocab_);
- void* hosts[] = {h_tok_, h_step_, h_pos_, h_row_, h_out_, h_prob_};
- if (owns_draft_head_ && dhead_) cudaFree(dhead_);
++ if (owns_draft_head_ && dhead_) { strata::kernels::native_q6_k_unpack(dhead_); cudaFree(dhead_); }
+ if (owns_draft_head_ && dvocab_) cudaFree(dvocab_);
+ if (ev_chain_) cudaEventDestroy(ev_chain_);
+ for (cudaEvent_t e : ev_step_) if (e) cudaEventDestroy(e);
+ void* hosts[] = {h_tok_, h_step_, h_pos_, h_row_, h_out_, h_prob_, h_force_};
for (void* h : hosts) if (h) cudaFreeHost(h);
}
@@@ -152,77 -148,9 +154,77 @@@ const void* MtpDrafter::q8(const char*
for (const auto& t : tensors_) if (t.name == name && t.kind == "q8_0") return dense_ + t.off;
return nullptr;
}
+const void* MtpDrafter::wq(const char* name, int& type) const {
+ if (dense4_ != nullptr)
+ for (const auto& e : q4_off_)
+ if (e.first == name) { type = GGML_Q4_0; return dense4_ + e.second; }
+ type = GGML_Q8_0;
+ return q8(name);
+}
+
+// --mtp-q4: every Q8_0 tensor of dense.bin as Q4_0 (ggml's reference quantizer), in one device buffer
+bool MtpDrafter::make_q4_dense(const std::vector<uint8_t>& blob, std::string& err) {
+#ifdef STRATA_NATIVE_EXPERTS
+ uint64_t total = 0;
+ std::vector<std::pair<const Tensor*, uint64_t>> plan;
+ for (const auto& t : tensors_) {
+ if (t.kind != "q8_0" || t.cols % 32 != 0) continue;
+ plan.push_back({&t, total});
+ total += ((uint64_t) t.rows * (uint64_t) (t.cols / 32) * 18 + 255) & ~255ull;
+ }
+ std::vector<uint8_t> host((size_t) total);
+ std::vector<float> row;
+ const auto* q8t = ggml_get_type_traits(GGML_TYPE_Q8_0);
+ for (const auto& [t, off] : plan) {
+ row.resize((size_t) t->cols);
+ const uint64_t in_row = (uint64_t) (t->cols / 32) * 34, out_row = (uint64_t) (t->cols / 32) * 18;
+ for (int64_t r = 0; r < t->rows; ++r) {
+ q8t->to_float(blob.data() + t->off + (uint64_t) r * in_row, row.data(), t->cols);
+ ggml_quantize_chunk(GGML_TYPE_Q4_0, row.data(), host.data() + off + (uint64_t) r * out_row, 0, 1, t->cols,
+ nullptr);
+ }
+ q4_off_.push_back({t->name, off});
+ }
+ if (cudaMalloc((void**) &dense4_, (size_t) total) != cudaSuccess) { err = "mtp: the Q4_0 projections do not fit"; return false; }
+ cudaMemcpy(dense4_, host.data(), (size_t) total, cudaMemcpyHostToDevice);
+ vram_ += total;
+ std::fprintf(stderr, "strata mtp: --mtp-q4: %zu projections as Q4_0 (%.1f MiB)\n", plan.size(), (double) total / 1048576.0);
+ return true;
+#else
+ (void) blob;
+ err = "mtp: --mtp-q4 needs a build with native experts (ggml)";
+ return false;
+#endif
+}
+
+// --mtp-q4: the draft head's subset rows as Q4_0 (dequantized from the main head's format)
+bool MtpDrafter::make_q4_head(std::string& err) {
+#ifdef STRATA_NATIVE_EXPERTS
+ const int64_t N = g_->n_embd;
+ const auto* tt = ggml_get_type_traits((ggml_type) head_->type());
+ if (tt == nullptr || tt->to_float == nullptr || N % 32 != 0) { err = "mtp: --mtp-q4 cannot read the head's format"; return false; }
+ const size_t in_row = head_->row_bytes(), out_row = (size_t) (N / 32) * 18;
+ std::vector<uint8_t> src((size_t) n_dvocab_ * in_row), dst((size_t) n_dvocab_ * out_row);
+ if (cudaMemcpy(src.data(), dhead_, src.size(), cudaMemcpyDeviceToHost) != cudaSuccess) { err = "mtp: reading the draft head"; return false; }
+ std::vector<float> row((size_t) N);
+ for (int64_t r = 0; r < n_dvocab_; ++r) {
+ tt->to_float(src.data() + (size_t) r * in_row, row.data(), N);
+ ggml_quantize_chunk(GGML_TYPE_Q4_0, row.data(), dst.data() + (size_t) r * out_row, 0, 1, N, nullptr);
+ }
+ // the Q4_0 rows replace the subset in place (they are smaller)
+ if (cudaMemcpy(dhead_, dst.data(), dst.size(), cudaMemcpyHostToDevice) != cudaSuccess) { err = "mtp: writing the draft head"; return false; }
+ dhead_type_ = GGML_Q4_0;
+ std::fprintf(stderr, "strata mtp: --mtp-q4: draft head over %lld tokens as Q4_0 (%.1f MiB read per step, was %.1f)\n",
+ (long long) n_dvocab_, (double) dst.size() / 1048576.0, (double) src.size() / 1048576.0);
+ return true;
+#else
+ err = "mtp: --mtp-q4 needs a build with native experts (ggml)";
+ return false;
+#endif
+}
bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, SessionState& ss, int max_t, std::string& err,
- int64_t window) {
+ int64_t window, const MtpDrafter* shared) {
cudaGetDevice(&device_); // a layer split's last stage on another GPU: the drafter lives there
g_ = &g;
ss_ = &ss;
@@@ -259,10 -199,9 +273,10 @@@
}
cudaMemcpy(dense_, blob.data(), blob.size(), cudaMemcpyHostToDevice);
vram_ += blob.size();
+ if (q4_ && !make_q4_dense(blob, err)) return false;
}
// ---- the 512 routed experts, one blob each
- {
+ if (shared == nullptr) {
const uint64_t bytes = (uint64_t) g.n_expert * strata::kernels::cpu::BLOB;
// Loader fix (0.1.15+loaderfix.2): each 64 MiB read below reached the disk as ~16k 4095-byte reads under
// MSVC's `basic_filebuf::xsgetn`, which is what made 675 MiB of drafter experts take minutes.
@@@ -385,44 -341,10 +416,44 @@@
return true;
}
+namespace {
+// STRATA_MTP_FULL_HEAD=1 (a diagnostic): draft over the whole vocabulary (the main head itself) instead of
+// rt/draft_vocab.bin's subset - the reference head, to measure what the subset costs in acceptance
+bool full_head_env() {
+ static const bool on = [] { const char* v = std::getenv("STRATA_MTP_FULL_HEAD"); return v && v[0] == '1'; }();
+ return on;
+}
+} // namespace
+
+bool MtpDrafter::top2_env() {
+ static const bool on = [] { const char* v = std::getenv("STRATA_MTP_TOP2"); return v && v[0] == '1'; }();
+ return on;
+}
+
+// STRATA_MTP_TOP2=1 (a diagnostic for tree drafts): draft j's runner-up under the draft layer, from the head logits
+// the step just wrote (row 0), on the host. Slow; only for measuring what a second branch would have caught.
+void MtpDrafter::record_top2(int j) {
+ const int64_t nv = dhead_ != nullptr ? n_dvocab_ : n_vocab_;
+ if ((int64_t) lg_host_.size() < nv) lg_host_.resize((size_t) nv);
+ if ((int) top2_.size() < max_t_) top2_.assign((size_t) max_t_, -1);
+ if (j < 0 || j >= max_t_) return;
+ if (cudaMemcpy(lg_host_.data(), head_logits_, (size_t) nv * sizeof(float), cudaMemcpyDeviceToHost) != cudaSuccess) {
+ top2_[(size_t) j] = -1;
+ return;
+ }
+ int64_t b1 = -1, b2 = -1;
+ for (int64_t i = 0; i < nv; ++i) {
+ const float v = lg_host_[(size_t) i];
+ if (b1 < 0 || v > lg_host_[(size_t) b1]) { b2 = b1; b1 = i; }
+ else if (b2 < 0 || v > lg_host_[(size_t) b2]) b2 = i;
+ }
+ top2_[(size_t) j] = b2 < 0 ? -1 : dhead_ != nullptr ? dvocab_host_[(size_t) b2] : (int32_t) b2;
+}
+
uint64_t MtpDrafter::bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const {
uint64_t bytes = head_logits_ ? 0 : (uint64_t) max_t_ * (uint64_t) n_vocab * sizeof(float);
- if (dhead_ == nullptr && !full_head_env()) {
- if (dhead_ == nullptr && owns_draft_head_) {
- if (FILE* f = std::fopen((rt_dir_ + "/draft_vocab.bin").c_str(), "rb")) {
++ if (dhead_ == nullptr && owns_draft_head_ && !full_head_env()) {
+ if (FILE* f = std::fopen(vocab_file().c_str(), "rb")) {
std::fseek(f, 0, SEEK_END);
const long size = std::ftell(f);
std::fclose(f);
@@@ -543,10 -466,21 +575,21 @@@ bool MtpDrafter::bind(const WeightTable
err = "mtp: the draft logits do not fit";
return false;
}
+ if (shared != nullptr) {
+ if (shared->head_ != head || shared->device_ != device_ ||
+ shared->n_vocab_ != n_vocab_) {
+ err = "mtp: incompatible shared draft head";
+ return false;
+ }
+ dhead_ = shared->dhead_;
+ dvocab_ = shared->dvocab_;
+ n_dvocab_ = shared->n_dvocab_;
+ owns_draft_head_ = false;
+ }
// the draft head's token subset, when tools/draft_vocab.py wrote one
- if (dhead_ == nullptr && !full_head_env()) {
- if (dhead_ == nullptr && shared == nullptr) {
++ if (dhead_ == nullptr && shared == nullptr && !full_head_env()) {
std::vector<uint8_t> raw;
- if (read_file(rt_dir_ + "/draft_vocab.bin", raw) && raw.size() >= 4 && raw.size() % 4 == 0) {
+ if (read_file(vocab_file(), raw) && raw.size() >= 4 && raw.size() % 4 == 0) {
n_dvocab_ = (int64_t) (raw.size() / 4);
const int64_t row_bytes = (int64_t) head->row_bytes(); // a vocabulary row of the native head
if (cudaMalloc((void**) &dvocab_, raw.size()) != cudaSuccess ||
diff --cc src/core/verify.cpp
index 33f0a601e,bc63ba3f6..d6bd65d03
--- a/src/core/verify.cpp
+++ b/src/core/verify.cpp
@@@ -293,8 -287,7 +293,8 @@@ Verifier::~Verifier()
if (kv.second) cudaGraphExecDestroy(kv.second);
if (arena_b_) cudaFree(arena_b_);
if (h_commitb_) cudaFreeHost(h_commitb_);
+ if (qcnt_) cudaFree(qcnt_);
- if (cs_) cudaStreamDestroy(cs_);
+ 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_); }
if (commit_done_) cudaEventDestroy(commit_done_);
@@@ -525,17 -521,9 +529,18 @@@ bool Verifier::init(const WeightTable&
// exact, but neutral on RIBPC 1-2 GPUs: off by default)
{
const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN");
- device_plan_ = !all_resident_ && (v != nullptr && std::atoi(v) != 0);
+ // (not with set_always_publish: the device table may lag the host's while windows are in flight)
+ device_plan_ = !all_resident_ && !always_publish_ && (v != nullptr && std::atoi(v) != 0);
}
+ // (halo's STRATA_VERIFY_RESIDENT=1 is this window's all_resident_ graph above, which 0.1.39 has on by default)
+ if (g_qfuse()) { // S26: the HC read's q8_1 group counters, zeroed once (each launch leaves them zero)
+ if (cudaMalloc((void**) &qcnt_, sizeof(unsigned) * (size_t) (g.n_embd / 32)) != cudaSuccess ||
+ cudaMemset(qcnt_, 0, sizeof(unsigned) * (size_t) (g.n_embd / 32)) != cudaSuccess) {
+ cudaGetLastError();
+ if (qcnt_) cudaFree(qcnt_);
+ qcnt_ = nullptr;
+ }
+ }
if (all_resident_ || device_plan_) {
bool ok2 = true;
if (device_plan_)
@@@ -774,16 -726,18 +779,18 @@@ bool Verifier::record_window(int T, cud
float* hb = h_L_ + (size_t) gi * MT * C;
float* gate = gate_L_ + (size_t) gi * MT * HV;
float* beta = beta_L_ + (size_t) gi * MT * HV;
- native_quantize_q8_1(xm, xq_, (int) N, n, cs);
+ if (!q8_attn) native_quantize_q8_1(xm, xq_, (int) N, n, cs);
native_mmvq(wqkv->native_type, wqkv->native_data, xq_, qkv + (size_t) tb * C, (int) N, (int) C, n, cs);
stamp(l, 2, grp);
- if (batch_rec_) { // each row from its own slot's conv history, one row each
- for (int t = tb; t < te; ++t) {
- SessionState& sx = slot_ss(t);
+ if (batch_rec_) { // contiguous rows may be proposals for the same slot
+ for (int t = tb; t < te;) {
+ const int first = t;
+ while (t < te && brow_[t] == brow_[first]) ++t;
+ SessionState& sx = slot_ss(first);
const float* cx = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats +
(uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
- gdn_conv_l2_multi(cx, qkv + (size_t) t * C, (const float*) wc->data, hb + (size_t) t * C, (int) C,
- (int) (2 * HK), EPS, 1, cs, 0);
+ gdn_conv_l2_multi(cx, qkv + (size_t) first * C, (const float*) wc->data,
+ hb + (size_t) first * C, (int) C, (int) (2 * HK), EPS, t - first, cs, 0);
}
} else
gdn_conv_l2_multi(conv, qkv, (const float*) wc->data, hb, (int) C, (int) (2 * HK), EPS, n, cs, tb);
@@@ -848,18 -805,13 +858,19 @@@
fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);
}
stamp(l, 8, grp);
- if (batch_rec_) { // every slot's indexer tail, restored by its commit
+ if (batch_rec_) { // snapshot each slot's indexer tail before its first proposed row
for (int t = tb; t < te; ++t)
- copy_from_mapped(tail_snap_b_ + ((size_t) brow_[t] * nQall + qi) * TS, slot_ss(t).qsa_states[qi].idx_tail,
- TS, cs);
+ if (t == tb || brow_[t] != brow_[t - 1])
+ copy_from_mapped(tail_snap_b_ + ((size_t) brow_[t] * nQall + qi) * TS,
+ slot_ss(t).qsa_states[qi].idx_tail, TS, cs);
} else
if (grp == 0) copy_from_mapped(tail_snap_ + (size_t) qi * TS, st.idx_tail, TS, cs);
+ const bool kv_multi = g_lfuse() && !st.kv_hybrid && !st.kv_q4 && st.kv_int8 && n > 1; // S26 STRATA_LFUSE
+ if (kv_multi)
+ kv_append_q8_steps(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, step_ + tb * kStepCount,
+ (int) kStepCount, kcur_ + tb * NKV * HD, vcur_ + tb * NKV * HD, (int) (NKV * HD), n,
+ s, cs, &st.host);
+ else
for (int t = tb; t < te; ++t) {
const QsaState& st = slot_ss(t).qsa_states[qi]; // the row's own K/V (ss's outside a batch)
const int32_t* step_t = step_ + t * kStepCount;
diff --cc src/program/generate.cpp
index d37fdecbb,7be73397a..af31325d6
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@@ -767,26 -770,12 +791,29 @@@ void usage()
" RAM allows); adaptive swaps exchange them, so none is read from the file again.\n"
" --resident-experts the low-RAM PC's resident mode (setup): --mmap-experts --resident-cpu-experts\n"
" with the copy page-locked when possible, 4 GiB headroom, plain mmap if it\n"
- " does not fit. Same answers as --mmap-experts for the same placement.\n");
+ " does not fit. Same answers as --mmap-experts for the same placement.\n"
+ " --adapt-async 1 --serve with the resident RAM mode (opt-in): the adaptive tier's swaps\n"
+ " advance between verify windows instead of a window waiting for a whole\n"
+ " round. Not bit-exact run to run. 0 (default) = the blocking tier.\n");
}
+// --lookup-chain: the context's last tokens for the draft sources (at most 64), the MTP's pending drafts last
+int chain_tail(const strata::spec::SuffixDrafter& sfx, const int32_t* pending, int n_pending, std::vector<int32_t>& tail) {
+ const std::vector<int32_t>& h = sfx.history();
+ const int keep = std::max(0, std::min((int) h.size(), 64 - n_pending));
+ tail.assign(h.end() - keep, h.end());
+ tail.insert(tail.end(), pending, pending + n_pending);
+ return (int) tail.size();
+}
+
+// --lookup-chain: the registered extra draft sources (strata/spec/draft_source.hpp) see the committed context too
+void extra_sources_reset() {
+ for (auto& src : strata::spec::extra_draft_sources()) src->reset();
+}
+void extra_sources_append(const int32_t* t, size_t n) {
+ for (auto& src : strata::spec::extra_draft_sources()) src->append(t, n);
+}
+
bool parse_i64_list(const char* s, std::vector<int64_t>& out, std::string& err) {
out.clear();
std::string text(s);
@@@ -1504,26 -1598,9 +1636,27 @@@ int main(int argc, char** argv)
else if (a == "--turn-token") o.turn_token = std::atoll(next("--turn-token"));
else if (a == "--tail-role-token") o.tail_role_token = std::atoll(next("--tail-role-token"));
else if (a == "--short-read") o.short_read = std::max(0LL, std::atoll(next("--short-read")));
+ else if (a == "--pipeline-windows") o.pipeline_windows = std::max(0, std::min(2, std::atoi(next("--pipeline-windows"))));
else if (a == "--suffix-draft") o.suffix_draft = std::max(0, std::atoi(next("--suffix-draft")));
else if (a == "--mtp-max-t") o.mtp_max_t = std::max(0, std::atoi(next("--mtp-max-t")));
+ else if (a == "--lookup-chain") o.lookup_chain = std::clamp(std::atoi(next("--lookup-chain")), 0, 7);
+ else if (a == "--lookup-chain-min") o.lookup_chain_min = std::max(3, std::atoi(next("--lookup-chain-min")));
+ else if (a == "--mtp-hnorm") {
+ const std::string v = next("--mtp-hnorm");
+ if (v != "pooled" && v != "stream") {
+ std::fprintf(stderr, "strata generate: --mtp-hnorm takes pooled or stream\n");
+ return 2;
+ }
+ o.mtp_hnorm_stream = v == "stream";
+ }
+ else if (a == "--mtp-q4") {
+ o.mtp_q4 = next("--mtp-q4");
+ if (o.mtp_q4 != "all" && o.mtp_q4 != "proj" && o.mtp_q4 != "head") {
+ std::fprintf(stderr, "strata generate: --mtp-q4 takes all, proj or head\n");
+ return 2;
+ }
+ }
+ else if (a == "--mtp-draft-vocab") o.mtp_draft_vocab = next("--mtp-draft-vocab");
else if (a == "--control-vector") o.cvec_files.push_back({next("--control-vector"), 1.0f});
else if (a == "--control-vector-scaled") {
// FILE:SCALE, comma-separated; the LAST colon splits, so a Windows path (C:\...) keeps its drive
@@@ -3108,16 -3264,29 +3333,32 @@@
o.mtp.clear();
}
if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size());
+ mtp.set_hnorm_per_stream(o.mtp_hnorm_stream); // --mtp-hnorm stream (opt-in), before any capture
+ mtp.set_q4(o.mtp_q4 == "all" || o.mtp_q4 == "proj", o.mtp_q4 == "all" || o.mtp_q4 == "head"); // before load
+ if (!o.mtp_draft_vocab.empty()) mtp.set_draft_vocab(o.mtp_draft_vocab);
// the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned,
// so it always sees the canonical geometry; `static` because MtpDrafter keeps a reference
- static const strata::core::ModelGeometry draft_geometry{};
// with a layer split across GPUs the drafter reads the last stage's residual: it lives on that device
const strata::core::OnDevice on_mtp(last_st ? last_st->dev : -1);
- if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st ? last_st->ss : ss, o.spec, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), vram_free_note().c_str()); return 1; }
+ // --pipeline-windows 2: 8 rows (the chain runs on past the window in flight: its drafts, its bonus token and
+ // the next window's drafts), and the round/step graphs carry the forcing kernel
+ const int mtp_t = o.pipeline_windows >= 2 ? strata::kernels::kVerifyMaxT : o.spec;
+ if (o.pipeline_windows >= 2) mtp.set_force_capture(true);
+ if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st ? last_st->ss : ss, mtp_t, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), vram_free_note().c_str()); return 1; }
mtp.set_ple_session(&ss);
+ if (batch_mtp) {
+ for (int b = 0; b < o.batch; ++b) {
+ auto d = std::make_unique<strata::core::MtpDrafter>();
+ if (!d->load(o.mtp, draft_geometry, *bslot_ss[0][(size_t) b], o.spec, err, o.mtp_window, &mtp)) {
+ std::fprintf(stderr, "strata generate: batch MTP slot %d: %s%s\n", b, err.c_str(),
+ vram_free_note().c_str());
+ return 1;
+ }
+ d->set_max_drafts(1); // the first candidate verifies one proposal per slot
+ d->set_ple_session(bslot_ss[0][(size_t) b].get());
+ slot_mtp.push_back(std::move(d));
+ }
+ }
}
// THE HEAD BEFORE THE CACHE, AND BEFORE THE ARENA. The expert cache takes what is free minus the reserve, so
// everything allocated after it comes out of the reserve. The native head (~0.5 GB with IQ3_S) was loaded after
@@@ -3306,9 -3475,16 +3547,16 @@@
// THE HEAD BEFORE THE CACHE: the native head and the logits are allocated above, before the expert arena (#620)
const bool auto_cache = o.expert_cache < 0;
bool reserve_adapted = false; // #496: the auto sizing lowered the reserve so a small card's cache fits
+ // --pipeline-windows: what it allocates on CUDA0 after the cache (see kPipeWindowMib)
+ const int64_t pipe_first = o.pipeline_windows <= 0 ? 0
+ : (kPipeWindowMib << 20) + (o.pipeline_windows >= 2 ? 2 * (int64_t) gdn_snapshot_bytes(ss) : 0);
+ if (pipe_first > 0)
+ std::fprintf(stderr, "strata generate: --pipeline-windows %d: %lld MiB of CUDA0 kept out of the expert cache "
+ "(the second verifier%s)\n", o.pipeline_windows, (long long) (pipe_first >> 20),
+ o.pipeline_windows >= 2 ? ", the GDN snapshots" : "");
if (o.expert_cache < 0) {
size_t free_b = 0, total_b = 0;
- cudaMemGetInfo(&free_b, &total_b);
+ free_b = strata::core::device_free_bytes(); (void) total_b;
// Plan v0.3 P5: the batched prompt path's chunk buffers are allocated later, so they are reserved here -
// under WDDM an over-subscribed allocation does not fail, it pages to system memory and crawls.
// (with borrowing - the default with a profile - the prompt path lends cache slots instead; `pf_borrow` is
@@@ -3381,9 -3559,9 +3631,9 @@@
// fails with "device buffers ... do not fit" (with borrowing - the default with a profile - the path lends
// slots instead and `prefill_mib` is 0, so only the reserve is checked)
size_t free_b = 0, total_b = 0;
- cudaMemGetInfo(&free_b, &total_b);
+ free_b = strata::core::device_free_bytes(); (void) total_b;
const int64_t prefill_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0;
- const int64_t reserve = ((int64_t) o.vram_reserve_mib + prefill_mib) << 20;
+ const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + pipe_first;
const int64_t fit = std::max<int64_t>(((int64_t) free_b - reserve) / (int64_t) strata::kernels::cpu::expert_layout().max_blob, 0);
if (o.expert_cache > fit) {
// a WARNING that names the knob: the user asked for this size, and gets fewer slots
@@@ -3505,8 -3684,8 +3756,8 @@@
cudaMemset(xcache.device_slot(0), 0, (size_t) xcache.bytes());
cudaDeviceSynchronize();
size_t free_b = 0, total_b = 0;
- cudaMemGetInfo(&free_b, &total_b);
+ free_b = strata::core::device_free_bytes(); (void) total_b;
- const int64_t want = (int64_t) o.vram_reserve_mib << 20;
+ const int64_t want = ((int64_t) o.vram_reserve_mib << 20) + pipe_first;
if ((int64_t) free_b >= want - (64ll << 20)) break;
// short by (want - free); a figure of 0 only says "at least": the first two such reads give back 1 GiB
// each (under WDDM the free figure read before the allocation runs ~0.7 GiB high), later ones a quarter
@@@ -7191,11 -8011,12 +8083,13 @@@
// the verify windows: the first holds the last prompt token alone
int64_t p = n - 1;
int32_t x = (int32_t) ids[(size_t) (n - 1)];
- std::vector<int32_t> drafts((size_t) S, 0), window((size_t) S), outv((size_t) S);
- std::vector<float> dprob((size_t) S, 0.0f);
+ // (the drafter writes max_t - 1 drafts: 8 rows with --pipeline-windows 2)
+ const size_t DS = (size_t) std::max(S, use_mtp ? mtp.max_t() : 0);
+ std::vector<int32_t> drafts(DS, 0), window((size_t) S), outv((size_t) S);
+ std::vector<float> dprob(DS, 0.0f);
std::vector<int32_t> sbuf((size_t) S, 0);
- if (o.suffix_draft > 0) {
+ const bool sfx_on = o.suffix_draft > 0 || o.lookup_chain > 0;
+ if (sfx_on) {
sfx.reset();
for (int64_t t : ids) sfx.append((int32_t) t);
}