From dfaae03b009e7001e745ebcefb11d3ce15c6c7f4 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 25 Oct 2026 11:54:42 +0100 Subject: [PATCH 1/9] DeepSeek engine: the RAM store no longer misses the experts the VRAM cache gives back to the CPU lane: the preload fills the slots the lane leaves over (and the 256 reserved ones, evictable first) with the VRAM experts the profile counts least and the lane experts it never saw (DS4_STORE_SPARE=0 off), and an expert leaving VRAM is copied into a store slot from its VRAM blob (put_begin/put_done, DS4_STORE_PUT=0 off) instead of being read from the SSD while the lane waits. r9700 1 card 2.00, store forced (--ssd-cache 140): decode code 23.7 -> 26.2, agent 20.7 -> 24.6 tok/s, misses 1.5/2.6 -> 0.5/0.6 a token; P2003 RTX 3060: no loss, ids identical --- src/dsv41/ds4_model.cu | 35 +++++++++++++++++++++++++++++- src/dsv41/ds4_store.hpp | 48 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 81 insertions(+), 2 deletions(-) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index b8d3991d..650b3ab4 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -4767,8 +4767,28 @@ struct Model::Impl { std::vector> list; list.reserve(cand.size()); for (const auto& c : cand) list.push_back(c.second); + // The slots the CPU lane's experts leave over: the experts the VRAM cache holds that the profile counts least (the cache gives + // up its coldest to the CPU lane, and a store without them reads each from the SSD while the CPU lane waits - 1.8 misses a + // token on the 251 GB R9700 box, 2.9 ms of a 49 ms token), then the lane's experts the profile never saw. Last in the list: they + // take only the slots the likely ones left. DS4_STORE_SPARE=0: off. + if (!(std::getenv("DS4_STORE_SPARE") && std::atoi(std::getenv("DS4_STORE_SPARE")) == 0)) { + std::vector>> vr, zero; + for (const Layer& l : L) { + if (l.il >= g.nl) continue; + const uint32_t* p = prof.data() + (size_t) l.il * g.n_exp; + for (int e = 0; e < l.n_exp; ++e) { + if (l.slot[(size_t) e] >= 0) vr.push_back({(double) p[e] / (double) l.blob, {l.il, e}}); + else if (p[e] == 0) zero.push_back({0.0, {l.il, e}}); + } + } + std::stable_sort(vr.begin(), vr.end(), [](const auto& a, const auto& b) { return a.first < b.first; }); + for (const auto& c : vr) list.push_back(c.second); + for (const auto& c : zero) list.push_back(c.second); + } const double t0 = now_ms(); - const size_t leave = (size_t) (std::getenv("DS4_STORE_RESERVE") ? std::atoi(std::getenv("DS4_STORE_RESERVE")) : 192) + 64; + // (with the spare experts in the list the reserve is theirs: last in the list, so the oldest ticks, so the first a demand read replaces) + const bool spare_on = !(std::getenv("DS4_STORE_SPARE") && std::atoi(std::getenv("DS4_STORE_SPARE")) == 0); + const size_t leave = spare_on ? 0 : (size_t) (std::getenv("DS4_STORE_RESERVE") ? std::atoi(std::getenv("DS4_STORE_RESERVE")) : 192) + 64; // The first 48 GB (what a store held before it could take every expert) are read before the first token; the rest of the // hottest-first list is read after it, in pieces of 128 experts on a thread of its own, behind the model's own reads (a // guess's priority) - the same bytes. Opt-in (DS4_STORE_BG=1): "ready" comes 9 s sooner on the 251 GB R9700 box (24 s against 34), but a prompt sent at @@ -6155,6 +6175,19 @@ struct Model::Impl { } if (got) blob_to_ram(l, sw_b, sw.ram); else sw.ram = -1; // (back to the file's pages then) + } else if (ok && store && l.nm == 1 && l.lay.fmt == gg::kFmtMXFP4 && !(std::getenv("DS4_STORE_PUT") && std::atoi(std::getenv("DS4_STORE_PUT")) == 0)) { + // `out` goes back to the CPU lane: its blob is in VRAM, so it is copied into a store slot now - the lane would otherwise read it from + // the SSD and wait for it (1-2 misses a token on the 251 GB R9700 box). DS4_STORE_PUT=0: off. + uint8_t* dst = store->put_begin(l.il, sw.out); + if (dst != nullptr) { + const Layer& x = member(l, 0); + cudaSetDevice(devs[(size_t) x.dev].id); + cudaStream_t cs = copy_st[(size_t) x.dev]; + const bool got = cudaMemcpyAsync(dst, x.vram_base + (size_t) l.slot[(size_t) sw.out] * unit(l), l.blob, cudaMemcpyDeviceToHost, cs) == + cudaSuccess && + cudaStreamSynchronize(cs) == cudaSuccess; + store->put_done(l.il, sw.out, got); + } } if (check_swaps) { // DS4_CHECK_SWAPS: the slot (and `out`'s RAM copy) against the model file, byte for byte std::vector dev(l.blob), h(unit(l)), file(l.blob); diff --git a/src/dsv41/ds4_store.hpp b/src/dsv41/ds4_store.hpp index ea6b1779..23c01ebf 100644 --- a/src/dsv41/ds4_store.hpp +++ b/src/dsv41/ds4_store.hpp @@ -48,7 +48,7 @@ public: enum Policy { kLru = 0, kLfu = 1 }; struct Stats { std::atomic hits{0}, misses{0}, prefetched{0}, prefetch_used{0}, prefetch_wasted{0}, evictions{0}, fails{0}; - std::atomic bytes_read{0}, wait_ns{0}, no_slot{0}, cancelled{0}; + std::atomic bytes_read{0}, wait_ns{0}, no_slot{0}, cancelled{0}, put{0}; }; struct Vis { // a slot the GPU may read from now on (dev != 0), or no longer (dev == 0) int layer = 0, e = 0; @@ -255,6 +255,52 @@ public: } return n; } + /// A slot for (layer, e) that the caller fills with the expert's blob itself (an expert the VRAM cache gives back to the CPU lane: its bytes + /// are in memory already, so no read from the SSD while the lane waits). Returns the blob's address, or nullptr (it is here already, or + /// no slot can be had). The slot is pinned and not findable until put_done(). + uint8_t* put_begin(int layer, int e) { + if (layer < 0 || layer >= (int) geo_.size() || e < 0 || e >= geo_[(size_t) layer].n_exp) return nullptr; + std::lock_guard lk(mu_); + if (where_[(size_t) layer][(size_t) e] >= 0) return nullptr; + const int s = take_slot(false); + if (s < 0) return nullptr; + Slot& sp = slots_[(size_t) s]; + if (sp.layer >= 0 && sp.expert >= 0) { + where_[(size_t) sp.layer][(size_t) sp.expert] = -1; + if (sp.prefetch) st_.prefetch_wasted.fetch_add(1, std::memory_order_relaxed); + st_.evictions.fetch_add(1, std::memory_order_relaxed); + } + sp.layer = layer; + sp.expert = e; + sp.pin = 1; + sp.prefetch = false; + sp.visible = false; + sp.tick = ++clock_; + sp.bad.store(false); + sp.cancel.store(false); + sp.left.store(1, std::memory_order_release); + sp.state.store(kLoading, std::memory_order_release); + where_[(size_t) layer][(size_t) e] = s; + st_.put.fetch_add(1, std::memory_order_relaxed); + return sp.base; + } + void put_done(int layer, int e, bool ok) { + std::lock_guard lk(mu_); + const int s = where_[(size_t) layer][(size_t) e]; + if (s < 0) return; + Slot& sp = slots_[(size_t) s]; + if (sp.pin > 0) sp.pin--; + if (ok) { + sp.left.store(0, std::memory_order_release); + sp.state.store(kReady, std::memory_order_release); + } else { + where_[(size_t) layer][(size_t) e] = -1; + sp.layer = sp.expert = -1; + sp.left.store(0, std::memory_order_release); + sp.state.store(kFree, std::memory_order_release); + free_hint_ = std::min(free_hint_, (size_t) s); + } + } /// Guesses still waiting in the queue for a layer the token is past: dropped unread (their slots free once the queue has gone by) void cancel_stale(int layer_now) { std::lock_guard lk(mu_); From 4be0a7ce4d3c7f92159752fa6cf07a72324c41ec Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 25 Oct 2026 18:05:54 +0100 Subject: [PATCH 2/9] DeepSeek engine: DS4_COPY_PIN=1 DMAs the prompt's experts from the CPU lane's copies in place (cudaHostRegister, read-only with DS4_COPY_PIN_RO=1), so the flow does not copy each one to the pinned staging first; the pinned chunks are unregistered with the arena. R9700 1 card, 2.25 pack, 8K prompt: the stream's compute wait 5517 -> 0 ms, prompt 28035 -> 27392 ms (292 -> 299 tok/s), ids identical; decode unchanged (16.6 vs 16.8 tok/s). The stream itself stays ~7 GB/s (the DMA issue pattern, not the staging), so the gain is small here; on an SSD-bound box the removed wait is the point. Opt-in: default path unchanged. --- src/dsv41/ds4_model.cu | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index 650b3ab4..ad2cac0b 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -1266,7 +1266,10 @@ struct Model::Impl { for (std::thread& t : cache_ths) if (t.joinable()) t.join(); if (ram_th.joinable()) ram_th.join(); - for (size_t i = 0; i < ram_chunks.size(); ++i) os::anon_free(ram_chunks[i], ram_chunk_bytes[i]); + for (size_t i = 0; i < ram_chunks.size(); ++i) { + if (ram_pinned) (void) cudaHostUnregister(ram_chunks[i]); + os::anon_free(ram_chunks[i], ram_chunk_bytes[i]); + } for (Dev& d : devs) { cudaSetDevice(d.id); for (void* p : d.allocs) cudaFree(p); @@ -3282,8 +3285,10 @@ struct Model::Impl { } } if (in_ram && ram_pinned && store_blob == nullptr) { // (DMA'd from where it lies) - const uint8_t* p = ram_slots[(size_t) l.ram[(size_t) e]]; - for (int r = 0; r < 3; ++r) it.src[r] = p + l.lay.trellis[r] + mx_read_off(l, mi, r); + const uint8_t* p = copy_mode ? ram_part[(size_t) l.ram[(size_t) e]][0] + : ram_slots[(size_t) l.ram[(size_t) e]]; + for (int r = 0; r < 3; ++r) + it.src[r] = p + (copy_mode ? cp_lay[(size_t) l.il][(size_t) r] : l.lay.trellis[r]) + mx_read_off(l, mi, r); ++c.it_ram; return; } @@ -4401,6 +4406,26 @@ struct Model::Impl { std::fprintf(stderr, "ds4: %zu of the CPU lane's %zu experts copied into RAM (%.1f GB, %d NUMA part%s) in %.1f s%s\n", jobs.size(), hot.size(), cb / 1e9, NH, NH > 1 ? "s" : "", (now_ms() - t0) / 1000.0, jobs.size() < hot.size() ? "; the others read in place" : ""); + // DS4_COPY_PIN=1: pin the copies, so the prompt path DMAs each expert from where it lies instead of copying it + // to the pinned staging first (measured on the R9700 box: the 8K pass streams 122 GB at 6.8 GB/s through the + // staging, where the RAM-to-staging and DMA probes are 24 and 28 GB/s). The CPU lane reads the same memory, and + // pinned 4 KB pages can cost its TLB (an earlier registration measured -15% decode), so this stays opt-in. + // DS4_COPY_PIN_RO=1: cudaHostRegisterReadOnly (the GPU only reads it). + if (const char* cp = std::getenv("DS4_COPY_PIN"); cp != nullptr && std::atoi(cp) != 0) { + const bool ro = std::getenv("DS4_COPY_PIN_RO") != nullptr && std::atoi(std::getenv("DS4_COPY_PIN_RO")) != 0; + const double tr = now_ms(); + bool ok = true; + for (size_t i = 0; i < ram_chunks.size() && ok; ++i) + ok = cudaHostRegister(ram_chunks[i], ram_chunk_bytes[i], + ro ? cudaHostRegisterReadOnly : cudaHostRegisterPortable) == cudaSuccess; + if (ok) { + ram_pinned = true; + std::fprintf(stderr, "ds4: the copied experts pinned in %.1f s (%s): the prompt path DMAs them in place\n", + (now_ms() - tr) / 1000.0, ro ? "read-only" : "read-write"); + } else { + std::fprintf(stderr, "ds4: pinning the copied experts failed: the prompt path stages them\n"); + } + } return true; } From 00a1292531575182ca51f898ab037e3e3a4849e7 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 25 Oct 2026 18:45:40 +0100 Subject: [PATCH 3/9] DeepSeek engine: the post-prompt RAM-store preload skips the experts the CPU lane already holds as a RAM copy (copy_mode). In copy-all mode every routed expert is in that copy, so the preload read a second copy of the same bytes: 4152 experts, 40 GB at 6.4 GB/s, 6.2 s of every 8K prompt, with 0.0 store hits in the decode after it; with --mmap-experts off and the experts not all fitting, the in-place ones are still preloaded. R9700 12 GB cell, 2.25 pack, 8K: prompt 27918 -> 21567 ms (293 -> 380 ppts; a repeated prompt 526.6), decode 16.61 -> 16.82 tok/s, ids identical (5705e1164a). With DS4_COPY_PIN=1 the same run is 21347 ms (383.7 ppts, repeat 535.6). --- src/dsv41/ds4_model.cu | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index ad2cac0b..bcb15a8a 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -6263,11 +6263,15 @@ struct Model::Impl { } if (store && env_f("DS4_SETTLE_STORE", 1.0f) != 0.0f) { // the RAM store too: a window prompt fills it through the CPU // lane's picks, a chunked one streams past it - the hottest CPU-lane experts of the prompt into its free slots + // (copy_mode: an expert already in the CPU lane's RAM copy gains nothing from a second copy of the same bytes - + // measured on the R9700 12 GB cell: 4152 such experts, 40 GB read at 6.4 GB/s, 6.2 s of an 8K prompt, 0.0 store + // hits in the decode after it; the VRAM swaps above already read them from the copy) std::vector>> hot; for (const Layer& l : L) { if (l.mtp) continue; for (int e = 0; e < l.n_exp; ++e) - if (l.slot[(size_t) e] < 0 && l.heat[(size_t) e] >= 4.0f) hot.push_back({l.heat[(size_t) e], {l.il, e}}); + if (l.slot[(size_t) e] < 0 && !(copy_mode && !l.ram.empty() && l.ram[(size_t) e] >= 0) && + l.heat[(size_t) e] >= 4.0f) hot.push_back({l.heat[(size_t) e], {l.il, e}}); } std::sort(hot.begin(), hot.end(), [](const auto& a, const auto& b) { return a.first > b.first; }); std::vector> list; From 8abe826f700ed41537b13b7ec1a706e6b93b16b6 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 25 Oct 2026 19:43:51 +0100 Subject: [PATCH 4/9] DeepSeek engine: the chunked prompt's dense dequantizer writes its 32 values a thread through shared memory, coalesced (a warp covers 1024 contiguous values), instead of each thread writing 2 bytes every 64 - a warp's store touched 32 cache lines. Same arithmetic and the same F16/BF16 values (only the store order changes). R9700 12 GB cell, 2.25 pack, 8K warm: prompt 14474 -> 13840 ms (566 -> 591.9 ppts), the q_b+rope stage 4025 -> 3581 ms, ids identical (5705e1164a); the cold first prompt also uses it. DS4_DQ_OLD=1 keeps the old kernel for A/B. --- src/dsv41/ds4_iq.cu | 57 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 55 insertions(+), 2 deletions(-) diff --git a/src/dsv41/ds4_iq.cu b/src/dsv41/ds4_iq.cu index e5f66887..7de79b4e 100644 --- a/src/dsv41/ds4_iq.cu +++ b/src/dsv41/ds4_iq.cu @@ -1278,7 +1278,54 @@ void mv_nc(const Jobs& J, int nj, int max_n, int max_c, cudaStream_t s) { // ---------------------------------------------------------------- whole matrices as 16-bit rows (the chunked prompt's GEMMs) // n rows of k values from `raw` (ld bytes a row): one thread a 32-value sub-block, the sub-block's codes and scales from decode<> -// (value = d s q - m of its half, ggml's dequantize_row_*), rounded to BF16 (bf16) or F16 +// (value = d s q - m of its half, ggml's dequantize_row_*), rounded to BF16 (bf16) or F16. +// The 32 values go through shared memory and are written coalesced (a warp's 32 threads cover 1024 contiguous values): a +// thread writing its own 32 values straight to dst wrote 2 bytes every 64 (a warp's store touches 32 cache lines), which +// measured 0.5 G weights/s on the R9700 - the 8K prompt's q_b stage 4 s. DS4_DQ_OLD=1 keeps the old kernel for A/B. +template +__global__ void __launch_bounds__(kThreads) dq_rows_kernel2(const uint8_t* __restrict__ raw, size_t ld, int k, int n, + uint16_t* __restrict__ dst, bool bf16) { + __shared__ uint32_t tab[Ty::TAB > 0 ? Ty::TAB : 1]; + __shared__ uint16_t sm[kThreads * 32]; + load_tab(tab); + __syncthreads(); + const int nsb = k / 32; + const size_t total = (size_t) n * (size_t) nsb; // 32-value sub-blocks + const size_t vals = (size_t) n * (size_t) k; + for (size_t base = (size_t) blockIdx.x * kThreads; base < total; base += (size_t) gridDim.x * kThreads) { + const size_t i = base + threadIdx.x; + uint16_t* o = sm + threadIdx.x * 32; + if (i < total) { + const size_t r = i / (size_t) nsb; + const int kb = (int) (i - r * (size_t) nsb); + Sub sb; + sb.m0 = sb.m1 = 0.0f; + decode(raw + r * ld, kb, tab, sb); + const float d0 = __fmul_rn(sb.d, (float) sb.s0), d1 = __fmul_rn(sb.d, (float) sb.s1); +#pragma unroll + for (int j = 0; j < 32; ++j) { + const int q = (int) (int8_t) ((uint32_t) sb.q[j >> 2] >> (8 * (j & 3))); + const float v = j < 16 ? __fsub_rn(__fmul_rn(d0, (float) q), sb.m0) : __fsub_rn(__fmul_rn(d1, (float) q), sb.m1); + o[j] = bf16 ? strata::ds4::bf16_rn(v) : __half_as_ushort(__float2half_rn(v)); + } + } else { +#pragma unroll + for (int j = 0; j < 32; ++j) o[j] = 0; + } + __syncthreads(); + // sm[m] is the block's value m (the sub-blocks are contiguous in the row-major output, rows included): write it + // a thread's 32 values apart, so a warp's stores are 512 contiguous bytes each + const size_t go = base * 32; + uint16_t* d = dst + go; +#pragma unroll + for (int j = 0; j < 32; ++j) { + const size_t m = (size_t) j * kThreads + threadIdx.x; + if (go + m < vals) d[m] = sm[m]; + } + __syncthreads(); + } +} + template __global__ void __launch_bounds__(kThreads) dq_rows_kernel(const uint8_t* __restrict__ raw, size_t ld, int k, int n, uint16_t* __restrict__ dst, bool bf16) { @@ -1309,7 +1356,13 @@ __global__ void __launch_bounds__(kThreads) dq_rows_kernel(const uint8_t* __rest bool dequant_rows(int type, const void* raw, size_t ld, int k, int n, uint16_t* dst, bool bf16, cudaStream_t s) { if (raw == nullptr || k % 256 != 0 || n <= 0) return false; const unsigned blocks = (unsigned) std::min(((size_t) n * (size_t) (k / 32) + kThreads - 1) / kThreads, 65535); -#define DS4_DQ(T) dq_rows_kernel<<>>((const uint8_t*) raw, ld, k, n, dst, bf16) + static const bool old = std::getenv("DS4_DQ_OLD") != nullptr && std::atoi(std::getenv("DS4_DQ_OLD")) != 0; +#define DS4_DQ(T) do { \ + if (old) \ + dq_rows_kernel<<>>((const uint8_t*) raw, ld, k, n, dst, bf16); \ + else \ + dq_rows_kernel2<<>>((const uint8_t*) raw, ld, k, n, dst, bf16); \ + } while (0) switch (type) { case kIQ2_XXS: DS4_DQ(kIQ2_XXS); break; case kIQ2_XS: DS4_DQ(kIQ2_XS); break; From 457d8cc7913c3acfd8b1fdd3a608d36be9e84dd2 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 25 Oct 2026 20:45:17 +0100 Subject: [PATCH 5/9] DeepSeek engine: DS4_ATTN_SLAB=N sets the chunked prompt's attention slab rows (default unchanged: 8 MB / HQ rounded to 64). The slab loop runs the dense projections (q_b, wo_a, wo_b) per slab, and each call dequantizes the whole dense matrix: a 256-row slab dequantized the same weights 32 times for an 8K prompt (the dense dequant 916 ms and rocBLAS 867 ms of that prompt). R9700 12 GB cell, 2.25 pack, 8K warm: slab 256 -> 591.9 ppts (with the earlier fixes), slab 2048 + DS4_RING_MB=1600 -> 668.0/666.2 ppts (12.26/12.30 s), the first prompt 429.9 (from 143-402), ids identical (5705e1164a); q_b+rope 3.97 -> 1.15 s. Opt-in: the default slab is unchanged. --- src/dsv41/ds4_model.cu | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index bcb15a8a..d49aee4d 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -2930,6 +2930,14 @@ struct Model::Impl { const size_t C = (size_t) chunk; c.C = chunk; c.A = std::max(64, (int) (((size_t) 8 << 20) / (size_t) HQ) / 64 * 64); + // DS4_ATTN_SLAB=N: the attention slab's rows. The dense projections (q_b, wo_a/b) are dequantized and GEMM'd + // once a slab, so a slab of 256 rows dequantizes the same weights 32 times for an 8K prompt (measured: the + // dense dequant 916 ms of the 8K prompt, rocBLAS 867 ms); a larger slab costs VRAM for c.q/c.o and the oa + // buffers (A * HQ x 4 bytes each). + if (const char* v = std::getenv("DS4_ATTN_SLAB")) { + const int a = std::atoi(v); + if (a > 0) c.A = std::max(64, std::min(chunk, a) / 64 * 64); + } // (the indexer's slab: its scores rows are the context wide - about 64 MB of them) c.AI = std::max(32, std::min(128, (int) (((size_t) 64 << 20) / (((size_t) o.max_context + 64) * 4)) / 32 * 32)); c.w16_elems = (size_t) 8 << 20; From 2dde837d9fd82243e5abcb9e46fe03181522e37d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 25 Oct 2026 22:27:30 +0100 Subject: [PATCH 6/9] DeepSeek engine: DS4_COPY_HUGETLB=1 puts the CPU lane's RAM copy on explicit 2 MB pages (MAP_HUGETLB from the kernel pool; the copy's RAM budget adds the pool, which MemAvailable does not count). With DS4_COPY_PIN=1 the pin then keeps 2 MB pages: on a transparent-huge-page arena the registration pins 4 KB pages and the prompt's DMA from it swings between 11.9 and 30.4 s for the same 140.2 GB stream. R9700 12 GB cell, 2.25 pack, 8K, 3 warm prompts: huge-page arena + pin + DS4_RING_MB=3500 + DS4_ATTN_SLAB=2048 -> 694.2 / 693.0 / 691.2 ppts (11.80-11.82 s), first prompt 435.4 (18.8 s), ids identical (5705e1164a); the THP arena with the pin ran 691/573/270 in one load and 665-691 in another. Copy at load 33.3 s for 156.7 GB; the pool is reserved once per boot (sysctl vm.nr_hugepages=78000). Opt-in: default path unchanged; no-pin staged stays 651. --- src/dsv41/ds4_model.cu | 15 ++++++++++++--- src/dsv41/ds4_os.hpp | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index d49aee4d..02f33a47 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -4283,7 +4283,11 @@ struct Model::Impl { } const uint64_t avail = ram_avail(); // (Windows: the copies are committed memory, within what its commit still has beside the other programs' margin) - const double can = std::min(avail == ~uint64_t{0} ? 1e300 : std::max(0.0, (double) avail - (double) kRamMargin), + // DS4_COPY_HUGETLB: the arena comes from the kernel's huge-page pool, which MemAvailable does not count: add + // its free bytes so the full copy is taken when the pool holds it. + static const bool huge_arena = std::getenv("DS4_COPY_HUGETLB") != nullptr && std::atoi(std::getenv("DS4_COPY_HUGETLB")) != 0; + const double pool = huge_arena ? (double) os::huge_free_bytes() : 0.0; + const double can = std::min(avail == ~uint64_t{0} ? 1e300 : std::max(0.0, (double) avail - (double) kRamMargin) + pool, commit_room()); // (auto: none - copies that all fit were measured no faster than the page cache: the CPU lane's rows are // compute-bound, ~46 GB/s from either on 2 Xeon sockets, NUMA parts included; a part copied cost decode speed @@ -4342,13 +4346,18 @@ struct Model::Impl { if (ns == 0) continue; const size_t part = cp_lay[(size_t) l.il][3], bytes = (size_t) ns * part; std::array base = {nullptr, nullptr}; + // DS4_COPY_HUGETLB=1: the arena on explicit 2 MB pages (the pool must be reserved), so a pin of it keeps + // 2 MB pages and the prompt's DMA reads stay stable (a THP arena pinned by cudaHostRegister runs in 4 KB + // pages: measured 11.9 s one prompt, 30.4 s the next for the same 140 GB) + static const bool huge = std::getenv("DS4_COPY_HUGETLB") != nullptr && std::atoi(std::getenv("DS4_COPY_HUGETLB")) != 0; bool ok = true; for (int X = 0; X < NH && ok; ++X) { - base[(size_t) X] = (uint8_t*) node_map(bytes, X, NH); + size_t got = bytes; + base[(size_t) X] = (uint8_t*) (huge ? os::huge_alloc(bytes, &got) : node_map(bytes, X, NH)); ok = base[(size_t) X] != nullptr; if (ok) { ram_chunks.push_back(base[(size_t) X]); - ram_chunk_bytes.push_back(bytes); + ram_chunk_bytes.push_back(got); } } if (!ok) { diff --git a/src/dsv41/ds4_os.hpp b/src/dsv41/ds4_os.hpp index 916d993f..0e48e9d6 100644 --- a/src/dsv41/ds4_os.hpp +++ b/src/dsv41/ds4_os.hpp @@ -398,6 +398,45 @@ inline bool in_ram(const void* p, size_t n) { #endif } +/// Bytes free in the kernel's explicit huge-page pool (HugePages_Free x Hugepagesize); 0 elsewhere or when unreadable. +/// (MemAvailable does not count a reserved pool, so a budget that must see it - the copy arena on DS4_COPY_HUGETLB - +/// adds this.) +inline uint64_t huge_free_bytes() { +#if defined(_WIN32) + return 0; +#else + std::FILE* f = std::fopen("/proc/meminfo", "r"); + if (f == nullptr) return 0; + char line[256]; + uint64_t pages = 0, size_kb = 0; + while (std::fgets(line, sizeof line, f) != nullptr) { + unsigned long long v = 0; + if (std::sscanf(line, "HugePages_Free: %llu", &v) == 1) pages = v; + else if (std::sscanf(line, "Hugepagesize: %llu kB", &v) == 1) size_kb = v; + } + std::fclose(f); + return pages * size_kb * 1024ull; +#endif +} + +/// Anonymous memory on explicit 2 MB huge pages (MAP_HUGETLB, from the kernel's pool - reserve it first, e.g. +/// `sysctl vm.nr_hugepages=N`): rounded up to a whole number of huge pages, `*got` its size. nullptr: the pool is empty +/// or the kernel cannot. (Unlike THP, a pin of this memory keeps 2 MB pages: a DMA from it does not need 4 KB +/// translations, which is what DS4_COPY_PIN's registered arena wanted.) +inline void* huge_alloc(size_t bytes, size_t* got = nullptr) { +#if defined(_WIN32) + (void) bytes, (void) got; + return nullptr; +#else + const size_t hp = (size_t) 2 << 20; + const size_t hb = (bytes + hp - 1) / hp * hp; + void* m = ::mmap(nullptr, hb, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB, -1, 0); + if (m == MAP_FAILED) return nullptr; + if (got != nullptr) *got = hb; + return m; +#endif +} + /// Anonymous memory on NUMA node `node` of `nodes` (node < 0 or nodes < 2: wherever the first touch puts it), on huge /// pages where the OS gives them; nullptr if it cannot be had. inline void* anon_alloc(size_t bytes, int node, int nodes) { From f05ccd3b54969d36c12a6bb649f74c760bb3dabf Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 25 Oct 2026 23:15:56 +0100 Subject: [PATCH 7/9] DeepSeek engine: DS4_FAST_ATTN=1 runs the chunked prompt's packed-KV attention on the gfx11/gfx12 matrix cores (new sparse_attn_wmma_kernel, opt-in; the decode and verify paths stay on the scalar kernels). The matrix's rows are 16 heads of ONE query, so a block stages a 16-key tile once for all of them: Q (16 heads x 512) is the A operand of the scores, the key tile is B, and the same tile is B of the values' product; the scores' 64-dim slices are computed by the 8 warps and summed in shared, the values by a warp a 64-dim slice, the online softmax a head a thread. R9700 12 GB cell, 2.25 pack, 8K warm: 752.2 / 748.3 ppts (10.89/10.95 s) against 694.2 / 693.0 / 691.2 for the scalar kernel; the sparse attention stage 3750 -> 2516 ms; first prompt 484.8. Quality gate (4995-position score, 2.25 plain, ref_base1): KL 0.10750 / ppl 3.394 / top1 87.83% against the scalar kernel's 0.10746 / 3.395 / 87.81% (delta 0.00004; the gate is 0.006). The ids are the same (5705e1164a) and the 128-token agent decode's ids too (81d895366c); its decode speed unchanged (16.49 vs 16.87 tok/s). The QK/PV sums are the matrix cores' order, hence opt-in (the owner approved the trade for the prefill). --- src/dsv41/ds4_kernels.cu | 167 ++++++++++++++++++++++++++++++++++++++- src/dsv41/ds4_wmma.cuh | 39 +++++++++ 2 files changed, 204 insertions(+), 2 deletions(-) create mode 100644 src/dsv41/ds4_wmma.cuh diff --git a/src/dsv41/ds4_kernels.cu b/src/dsv41/ds4_kernels.cu index f803016b..307c9cbe 100644 --- a/src/dsv41/ds4_kernels.cu +++ b/src/dsv41/ds4_kernels.cu @@ -6,6 +6,7 @@ #include "ds4_numerics.cuh" #include "ds4_q6k.cuh" #include "ds4_attn_split.cuh" +#include "ds4_wmma.cuh" #include @@ -1128,6 +1129,152 @@ __global__ void __launch_bounds__(kThreads) sparse_attn_packed_kernel(const floa } } +// DS4_FAST_ATTN=1: the chunked prompt's packed-KV attention on the matrix cores (gfx11/gfx12 WMMA; the R9700's gfx12). +// The matrix's rows are 16 heads of ONE query, so a block stages a 16-key tile once for all of them: Q (16 heads x 512 +// dims) is the A operand of the scores' product, the key tile is B, and the same tile is B of the values' product (the +// heads' softmaxes and their 512-dim outputs are its rows). The QK and PV sums are the matrix cores' order, not +// sparse_attn_packed_kernel's scalar lanes' - hence opt-in (DS4_FAST_ATTN). +constexpr int kFaHeads = 16; // heads a tile (the matrix's rows) +constexpr int kFaKeys = 16; // keys a tile +constexpr int kFaD = 512; // the head dim +constexpr int kFaLd = 520; // halves a tile row (512 + 8: the pad keeps the 16 rows off one bank) +__global__ void __launch_bounds__(kThreads) sparse_attn_wmma_kernel(const float* __restrict__ q, + const uint16_t* __restrict__ win, + const uint8_t* __restrict__ ckv, + const int* __restrict__ sel, int sel_stride, + AttnRows ar, const float* __restrict__ sink, + int heads, float scale, float* __restrict__ out) { + __shared__ __align__(16) uint16_t qs[kFaHeads * kFaLd]; + __shared__ __align__(16) uint16_t ks[kFaKeys * kFaLd]; + __shared__ float sc[kFaHeads][kFaKeys]; + __shared__ float part[8][kFaHeads][kFaKeys]; // (the 8 warps' 64-dim slices of the scores) + __shared__ uint16_t ps[kFaHeads][kFaKeys]; + __shared__ const uint8_t* rows[kFaKeys]; + __shared__ float m_run[kFaHeads], den[kFaHeads], ts[kFaHeads]; + const int tid = (int) threadIdx.x, wp = tid >> 5, lane = tid & 31, l16 = lane & 15, hi = lane >> 4; + const int t = blockIdx.y, hb = blockIdx.x * kFaHeads; + int n_win, n_sel, w0; + if (ar.gen) { + const long long ta = ar.t0 + t, pa = ar.p0 + ta; + const long long first = max((long long) ar.win - ar.p0, ta + 1); + w0 = (int) first; + n_win = (int) (ar.win + ta - first + 1); + n_sel = ar.R > 0 ? (int) min((long long) ar.kcap, (pa + 1) / ar.R) : 0; + } else { + n_win = ar.nwin[t], n_sel = ar.nsel[t], w0 = ar.win0[t]; + } + const uint16_t* wbase = win + (size_t) w0 * kFaD; + const int* sl = sel + (size_t) t * sel_stride; + const size_t crow = kv_row_bytes(kKvFp4, kFaD); + // the block's 16 heads' queries as FP16 (the matrix's A operand), and their running softmax state + for (int i = tid; i < kFaHeads * kFaD; i += kThreads) { + const int h = i / kFaD, c = i % kFaD; + qs[h * kFaLd + c] = __builtin_bit_cast(uint16_t, (_Float16) q[((size_t) t * heads + hb + h) * kFaD + c]); + } + if (tid < kFaHeads) { + m_run[tid] = -1e30f; + den[tid] = 0.0f; + } + f8v o[4]; +#pragma unroll + for (int f = 0; f < 4; ++f) +#pragma unroll + for (int i = 0; i < 8; ++i) o[f][i] = 0.0f; + __syncthreads(); + auto stage = [&](int t0, int n) { // the tile's n rows into ks (BF16 rows -> FP16) + const int sr = tid >> 4, part = tid & 15; + if (sr >= n) return; + const uint8_t* row = rows[sr]; + uint16_t tmp[32]; + if (t0 + sr < n_win) { + const uint4* src = (const uint4*) (row + part * 64); + const uint4 a = src[0], b = src[1], c = src[2], d = src[3]; + ((uint4*) tmp)[0] = a; + ((uint4*) tmp)[1] = b; + ((uint4*) tmp)[2] = c; + ((uint4*) tmp)[3] = d; + } else { + unpack32(row, part, (uint4*) tmp); + } + uint16_t* dst = ks + sr * kFaLd + part * 32; +#pragma unroll + for (int i = 0; i < 32; ++i) dst[i] = __builtin_bit_cast(uint16_t, (_Float16) bf16f(tmp[i])); + }; + const int total = n_win + n_sel; + for (int t0 = 0; t0 < total; t0 += kFaKeys) { + const int nt = min(kFaKeys, total - t0); + if (tid < nt) { + const int j = t0 + tid; + rows[tid] = j < n_win ? (const uint8_t*) (wbase + (size_t) j * kFaD) : ckv + (size_t) sl[j - n_win] * crow; + } + __syncthreads(); + stage(t0, nt); + __syncthreads(); + { // the scores in 8 slices of 64 dims, a warp a slice, summed in shared + f8v acc = {0, 0, 0, 0, 0, 0, 0, 0}; + const int k0 = wp * 64; + for (int kk = k0; kk < k0 + 64; kk += 16) { + h16v a, b; +#pragma unroll + for (int i = 0; i < 16; ++i) { + a[i] = __builtin_bit_cast(_Float16, qs[l16 * kFaLd + kk + i]); + b[i] = __builtin_bit_cast(_Float16, ks[l16 * kFaLd + kk + i]); + } + acc = set_wmma(a, b, acc); + } +#pragma unroll + for (int i = 0; i < 8; ++i) part[wp][set_wmma_row(i, hi)][l16] = acc[i]; + __syncthreads(); + const int h = tid >> 4, k = tid & 15; + float a = 0.0f; +#pragma unroll + for (int w = 0; w < 8; ++w) a += part[w][h][k]; + sc[h][k] = t0 + k < total ? a * scale : -INFINITY; + } + __syncthreads(); + if (tid < kFaHeads) { // the online softmax, a head a thread + float m = -INFINITY; + for (int j = 0; j < nt; ++j) m = fmaxf(m, sc[tid][j]); + const float mo = m_run[tid], mn = fmaxf(mo, m); + float s = 0.0f; + for (int j = 0; j < nt; ++j) { + const float p = expf(sc[tid][j] - mn); + ps[tid][j] = __builtin_bit_cast(uint16_t, (_Float16) p); + s += p; + } + for (int j = nt; j < kFaKeys; ++j) ps[tid][j] = 0; // (the stale rows: the values' product reads them) + ts[tid] = expf(mo - mn); + den[tid] = den[tid] * ts[tid] + s; + m_run[tid] = mn; + } + __syncthreads(); + const int dim0 = wp * 64; +#pragma unroll + for (int f = 0; f < 4; ++f) +#pragma unroll + for (int i = 0; i < 8; ++i) o[f][i] *= ts[set_wmma_row(i, hi)]; +#pragma unroll + for (int f = 0; f < 4; ++f) { // the values: P (16 heads x 16 keys) x V (16 keys x 64 dims this warp) + h16v a, b; +#pragma unroll + for (int i = 0; i < 16; ++i) { + a[i] = __builtin_bit_cast(_Float16, ps[l16][i]); + b[i] = __builtin_bit_cast(_Float16, ks[i * kFaLd + dim0 + f * 16 + l16]); + } + o[f] = set_wmma(a, b, o[f]); + } + __syncthreads(); + } +#pragma unroll + for (int f = 0; f < 4; ++f) +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int h = set_wmma_row(i, hi), dm = wp * 64 + f * 16 + l16; + const float dv = den[h] + expf(sink[hb + h] - m_run[h]); + out[((size_t) t * heads + hb + h) * kFaD + dm] = o[f][i] / dv; + } +} + // the ring's rows are kKvFp8: E4M3 codes, a UE8M0 scale per 32 (decoded: exactly the BF16 values they were made from) __global__ void ring_to_ext_kernel(const uint8_t* __restrict__ ring, uint16_t* __restrict__ ext, long long p0, int n, int d) { @@ -1839,6 +1986,16 @@ bool split_enabled() { }(); return on; } +// DS4_FAST_ATTN=1: the chunked prompt's packed-KV attention on the matrix cores (sparse_attn_wmma_kernel). Opt-in: the +// QK/PV sums are the matrix cores' order, so the outputs differ from the scalar kernel's in the last places (the owner +// approved the trade for the prefill; the decode path stays on the scalar kernels). +bool fast_attn_enabled() { + static const bool on = [] { + const char* e = std::getenv("DS4_FAST_ATTN"); + return e != nullptr && std::atoi(e) != 0; + }(); + return on; +} attnsplit::AttnSplitScratch split_scratch(cudaStream_t s, int heads) { static std::mutex mu; static std::map, attnsplit::AttnSplitScratch> m; @@ -2094,9 +2251,15 @@ void sparse_attn(const float* q, const uint16_t* win, const void* ckv, const int heads, d, scale, out); return; } + // DS4_FAST_ATTN=1: the chunked prompt's matrix-core path (16 heads a block, a 16-key tile). The decode and the + // verify windows keep the scalar kernels: one query's heads are not the matrix's rows there. + if (fast_attn_enabled() && a.gen != 0 && T >= kFaKeys && heads % kFaHeads == 0) { + sparse_attn_wmma_kernel<<>>(q, win, (const uint8_t*) ckv, sel, sel_stride, + a, sink, heads, scale, out); + return; + } // packed rows: as many heads a block as still leaves two blocks a multiprocessor (a decoded row serves them all) - int G = heads_per_block; - if (G != 1 && G != 2 && G != 4 && G != 8) { + int G = heads_per_block; if (G != 1 && G != 2 && G != 4 && G != 8) { G = 8; while (G > 1 && (heads % G != 0 || (heads / G) * T < 2 * sm_count())) G /= 2; } diff --git a/src/dsv41/ds4_wmma.cuh b/src/dsv41/ds4_wmma.cuh new file mode 100644 index 00000000..569387f9 --- /dev/null +++ b/src/dsv41/ds4_wmma.cuh @@ -0,0 +1,39 @@ +// Strata. The gfx11/gfx12 WMMA fragments one warp's 16x16x16 tile is fed and read through (the expert kernels' +// mx_set_wmma_kernel and the attention kernel's matrix-core path share this form). Each lane gives its row's (or +// column's) 16 values of a k-step - on gfx12 its half of them - and holds 8 of the 16x16 results: row set_wmma_row(i, hi), +// column lane % 16. +#pragma once +#include +#if defined(STRATA_USE_HIP) +#include + +using h16v = _Float16 __attribute__((ext_vector_type(16))); +using f8v = float __attribute__((ext_vector_type(8))); + +inline __device__ __forceinline__ f8v set_wmma(h16v a, h16v b, f8v c) { +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || \ + defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1152__) + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); +#elif defined(__gfx1200__) || defined(__gfx1201__) + using h8 = _Float16 __attribute__((ext_vector_type(8))); + const int k0 = (threadIdx.x & 31) / 16 * 8; + h8 aa, bb; +#pragma unroll + for (int i = 0; i < 8; ++i) { + aa[i] = a[k0 + i]; + bb[i] = b[k0 + i]; + } + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(aa, bb, c); +#else + __builtin_trap(); + return c; +#endif +} +inline __device__ __forceinline__ int set_wmma_row(int i, int hi) { +#if defined(__gfx1200__) || defined(__gfx1201__) + return 8 * hi + i; +#else + return 2 * i + hi; +#endif +} +#endif From 32c686fa67a75a575466b727af3027d4a849f816 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 25 Oct 2026 23:36:23 +0100 Subject: [PATCH 8/9] DeepSeek engine: the matrix-core attention's fragments load two halves a word (the scores' Q/K tiles and the values' P tile), and the online softmax runs a warp per two heads with a lane a key (16-lane shuffle max/sum) instead of a thread a head walking 16 keys. R9700 12 GB cell, 2.25 pack, 8K warm with DS4_FAST_ATTN=1: 767.7 / 765.8 ppts (10.67/10.70 s), the sparse attention stage 2516 -> 2311 ms, first prompt 465.6, with the same ids (5705e1164a, the agent decode's 81d895366c) and the same decode speed (16.49 tok/s). Quality gate on this binary (4995-position score, 2.25 plain, ref_base1): KL 0.10776 / ppl 3.389 / top1 87.89% against the scalar kernel's 0.10746 / 3.395 / 87.81% (delta 0.0003; the gate is 0.006). The softmax's sum order differs from the previous matrix-core build (a shuffle tree, not a key walk). --- src/dsv41/ds4_kernels.cu | 47 ++++++++++++++++++++++++---------------- 1 file changed, 28 insertions(+), 19 deletions(-) diff --git a/src/dsv41/ds4_kernels.cu b/src/dsv41/ds4_kernels.cu index 307c9cbe..218fff20 100644 --- a/src/dsv41/ds4_kernels.cu +++ b/src/dsv41/ds4_kernels.cu @@ -1215,10 +1215,14 @@ __global__ void __launch_bounds__(kThreads) sparse_attn_wmma_kernel(const float* const int k0 = wp * 64; for (int kk = k0; kk < k0 + 64; kk += 16) { h16v a, b; + const uint32_t* qa = (const uint32_t*) (qs + l16 * kFaLd + kk); + const uint32_t* kb = (const uint32_t*) (ks + l16 * kFaLd + kk); #pragma unroll - for (int i = 0; i < 16; ++i) { - a[i] = __builtin_bit_cast(_Float16, qs[l16 * kFaLd + kk + i]); - b[i] = __builtin_bit_cast(_Float16, ks[l16 * kFaLd + kk + i]); + for (int i = 0; i < 8; ++i) { // (two halves a load) + a[2 * i] = __builtin_bit_cast(_Float16, (uint16_t) (qa[i] & 0xffffu)); + a[2 * i + 1] = __builtin_bit_cast(_Float16, (uint16_t) (qa[i] >> 16)); + b[2 * i] = __builtin_bit_cast(_Float16, (uint16_t) (kb[i] & 0xffffu)); + b[2 * i + 1] = __builtin_bit_cast(_Float16, (uint16_t) (kb[i] >> 16)); } acc = set_wmma(a, b, acc); } @@ -1232,20 +1236,22 @@ __global__ void __launch_bounds__(kThreads) sparse_attn_wmma_kernel(const float* sc[h][k] = t0 + k < total ? a * scale : -INFINITY; } __syncthreads(); - if (tid < kFaHeads) { // the online softmax, a head a thread - float m = -INFINITY; - for (int j = 0; j < nt; ++j) m = fmaxf(m, sc[tid][j]); - const float mo = m_run[tid], mn = fmaxf(mo, m); - float s = 0.0f; - for (int j = 0; j < nt; ++j) { - const float p = expf(sc[tid][j] - mn); - ps[tid][j] = __builtin_bit_cast(uint16_t, (_Float16) p); - s += p; + { // the online softmax: a warp per 2 heads, a lane a key (16 lanes a head) + const int h = 2 * wp + (lane >> 4), k = lane & 15; + float m = sc[h][k]; +#pragma unroll + for (int o = 8; o > 0; o >>= 1) m = fmaxf(m, __shfl_xor_sync(0xffffffffu, m, o)); + const float mo = m_run[h], mn = fmaxf(mo, m); + const float p = expf(sc[h][k] - mn); + ps[h][k] = __builtin_bit_cast(uint16_t, (_Float16) p); + float s = p; +#pragma unroll + for (int o = 8; o > 0; o >>= 1) s += __shfl_xor_sync(0xffffffffu, s, o); + if (k == 0) { + ts[h] = expf(mo - mn); + den[h] = den[h] * ts[h] + s; + m_run[h] = mn; } - for (int j = nt; j < kFaKeys; ++j) ps[tid][j] = 0; // (the stale rows: the values' product reads them) - ts[tid] = expf(mo - mn); - den[tid] = den[tid] * ts[tid] + s; - m_run[tid] = mn; } __syncthreads(); const int dim0 = wp * 64; @@ -1256,10 +1262,13 @@ __global__ void __launch_bounds__(kThreads) sparse_attn_wmma_kernel(const float* #pragma unroll for (int f = 0; f < 4; ++f) { // the values: P (16 heads x 16 keys) x V (16 keys x 64 dims this warp) h16v a, b; + const uint32_t* pp = (const uint32_t*) ps[l16]; #pragma unroll - for (int i = 0; i < 16; ++i) { - a[i] = __builtin_bit_cast(_Float16, ps[l16][i]); - b[i] = __builtin_bit_cast(_Float16, ks[i * kFaLd + dim0 + f * 16 + l16]); + for (int i = 0; i < 8; ++i) { + a[2 * i] = __builtin_bit_cast(_Float16, (uint16_t) (pp[i] & 0xffffu)); + a[2 * i + 1] = __builtin_bit_cast(_Float16, (uint16_t) (pp[i] >> 16)); + b[2 * i] = __builtin_bit_cast(_Float16, ks[(2 * i) * kFaLd + dim0 + f * 16 + l16]); + b[2 * i + 1] = __builtin_bit_cast(_Float16, ks[(2 * i + 1) * kFaLd + dim0 + f * 16 + l16]); } o[f] = set_wmma(a, b, o[f]); } From 219beb5736075da289ae74322e97a769896c4f16 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 00:21:01 +0100 Subject: [PATCH 9/9] DeepSeek engine: porting guards for the 12 GB work. The matrix-core attention and its dispatch are now inside #if defined(STRATA_USE_HIP) (a CUDA/sm120 build keeps the scalar path and compiles), and a failed DS4_COPY_HUGETLB allocation falls back to the ordinary arena with a warning instead of leaving that layer's experts in place (the flag is safe on a machine with no huge-page pool). HIP build verified: 8K warm 768.7 / 767.4 / 765.6 ppts with DS4_FAST_ATTN=1, ids 5705e1164a, the agent decode's 81d895366c. --- src/dsv41/ds4_kernels.cu | 5 +++++ src/dsv41/ds4_model.cu | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/src/dsv41/ds4_kernels.cu b/src/dsv41/ds4_kernels.cu index 218fff20..7656f33a 100644 --- a/src/dsv41/ds4_kernels.cu +++ b/src/dsv41/ds4_kernels.cu @@ -1134,6 +1134,8 @@ __global__ void __launch_bounds__(kThreads) sparse_attn_packed_kernel(const floa // dims) is the A operand of the scores' product, the key tile is B, and the same tile is B of the values' product (the // heads' softmaxes and their 512-dim outputs are its rows). The QK and PV sums are the matrix cores' order, not // sparse_attn_packed_kernel's scalar lanes' - hence opt-in (DS4_FAST_ATTN). +// (HIP only: the CUDA build keeps the scalar kernels, so this and the dispatch below compile out there.) +#if defined(STRATA_USE_HIP) constexpr int kFaHeads = 16; // heads a tile (the matrix's rows) constexpr int kFaKeys = 16; // keys a tile constexpr int kFaD = 512; // the head dim @@ -1283,6 +1285,7 @@ __global__ void __launch_bounds__(kThreads) sparse_attn_wmma_kernel(const float* out[((size_t) t * heads + hb + h) * kFaD + dm] = o[f][i] / dv; } } +#endif // STRATA_USE_HIP // the ring's rows are kKvFp8: E4M3 codes, a UE8M0 scale per 32 (decoded: exactly the BF16 values they were made from) __global__ void ring_to_ext_kernel(const uint8_t* __restrict__ ring, uint16_t* __restrict__ ext, long long p0, int n, @@ -2262,11 +2265,13 @@ void sparse_attn(const float* q, const uint16_t* win, const void* ckv, const int } // DS4_FAST_ATTN=1: the chunked prompt's matrix-core path (16 heads a block, a 16-key tile). The decode and the // verify windows keep the scalar kernels: one query's heads are not the matrix's rows there. +#if defined(STRATA_USE_HIP) if (fast_attn_enabled() && a.gen != 0 && T >= kFaKeys && heads % kFaHeads == 0) { sparse_attn_wmma_kernel<<>>(q, win, (const uint8_t*) ckv, sel, sel_stride, a, sink, heads, scale, out); return; } +#endif // packed rows: as many heads a block as still leaves two blocks a multiprocessor (a decoded row serves them all) int G = heads_per_block; if (G != 1 && G != 2 && G != 4 && G != 8) { G = 8; diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index 02f33a47..f7e29e0e 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -4354,6 +4354,16 @@ struct Model::Impl { for (int X = 0; X < NH && ok; ++X) { size_t got = bytes; base[(size_t) X] = (uint8_t*) (huge ? os::huge_alloc(bytes, &got) : node_map(bytes, X, NH)); + if (huge && base[(size_t) X] == nullptr) { // no pool on this machine: the ordinary arena instead + static bool warned = false; + if (!warned) { + std::fprintf(stderr, "ds4: DS4_COPY_HUGETLB=1 but no 2 MB huge pages are free (reserve them: sysctl " + "vm.nr_hugepages=N); using the ordinary arena\n"); + warned = true; + } + got = bytes; + base[(size_t) X] = (uint8_t*) node_map(bytes, X, NH); + } ok = base[(size_t) X] != nullptr; if (ok) { ram_chunks.push_back(base[(size_t) X]);