From 78f6174474e8e75d7ff3882060560f4586d7d9d3 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 7 Oct 2026 10:53:07 +0200 Subject: [PATCH 1/3] sycl: guard big device allocations against aliased pages on the xe driver (Arc Pro B70) An Arc Pro B70 (xe) returned the 22 GiB expert-cache arena with two of its 2 MiB pages mapped onto the same memory: a write to the page at +2 MiB showed at +1022 MiB, so cache slots there held other experts' bytes and the prompt came out NaN at the first layer that routed to one of them (layer 4, expert 249). Which pages alias depends on the allocation history (the context size, the MTP window), so it comes and goes between runs. strata::arena_alias_check tags every 64 KiB of a fresh range and reads the tags back in a second kernel; strata::malloc_device_guarded allocates again behind a growing spacer until the range is clean (and warns if it never is). It guards the expert cache arena and every device allocation of 32 MiB or more (session arena, weights, MTP, verify, head, prefill). STRATA_ARENA_ALIAS_CHECK=0 skips it. Two debug aids: STRATA_VERIFY_ALL_SLOTS=1 (with STRATA_VERIFY_FIND=1, STRATA_VERIFY_DUMP=dir) reads every filled slot back and compares it with the GGUF, and the probes sycl/probe/arena_rw.cpp and alias_scan.cpp. --- sycl/include/strata/sycl_queue.hpp | 87 ++++++++++++++++++++++++++++++ sycl/probe/alias_scan.cpp | 38 +++++++++++++ sycl/probe/arena_rw.cpp | 63 ++++++++++++++++++++++ sycl/src/core/device.dp.cpp | 3 +- sycl/src/core/expert_cache.cpp | 4 +- sycl/src/core/mtp.cpp | 12 ++--- sycl/src/core/native_dense.cpp | 9 ++-- sycl/src/core/native_head.cpp | 7 +-- sycl/src/core/verify.cpp | 2 +- sycl/src/prefill/prefill.cpp | 4 +- sycl/src/program/generate.cpp | 51 +++++++++++++++++- 11 files changed, 259 insertions(+), 21 deletions(-) create mode 100644 sycl/probe/alias_scan.cpp create mode 100644 sycl/probe/arena_rw.cpp diff --git a/sycl/include/strata/sycl_queue.hpp b/sycl/include/strata/sycl_queue.hpp index e9986d82..5728e826 100644 --- a/sycl/include/strata/sycl_queue.hpp +++ b/sycl/include/strata/sycl_queue.hpp @@ -115,3 +115,90 @@ inline const std::string& intel_gpu_driver() { return drv; } } // namespace strata + +#include +namespace strata { +// Does every page of a big device allocation keep its own bytes? On an Arc Pro B70 (xe) a 22 GiB expert-cache arena came +// back with two of its 2 MiB pages mapped onto the same memory (a write to the page at +2 MiB showed up at +1022 MiB; the +// cache slots there then held other experts' bytes and the prompt came out NaN). The check writes a tag per 64 KiB of +// the range, then reads them back in a second kernel: it returns the number of 64 KiB blocks that do not hold their own tag +// (0 = clean) and the first such block's offset. The range's contents are destroyed. +inline uint64_t arena_alias_check(sycl::queue& q, void* base, size_t bytes, size_t* first_bad = nullptr) { + constexpr size_t kBlock = 64 << 10; + const size_t n = bytes / kBlock; + if (n == 0) return 0; + uint8_t* b = (uint8_t*) base; + uint64_t* res = sycl::malloc_device(2, q); + uint64_t init[2] = {0, ~0ull}; + q.memcpy(res, init, sizeof init).wait(); + // chunked so that no single launch is huge (an xe job past a few seconds is timed out) + const size_t chunk = (size_t) 1 << 20; + for (size_t c0 = 0; c0 < n; c0 += chunk) { + const size_t cn = n - c0 < chunk ? n - c0 : chunk; + q.parallel_for(sycl::range<1>(cn), [=](sycl::id<1> i) { + const size_t blk = c0 + i[0]; + *(volatile uint64_t*) (b + blk * kBlock) = (blk + 1) * 0x9E3779B97F4A7C15ull; + }); + q.wait(); + } + for (size_t c0 = 0; c0 < n; c0 += chunk) { + const size_t cn = n - c0 < chunk ? n - c0 : chunk; + q.parallel_for(sycl::range<1>(cn), [=](sycl::id<1> i) { + const size_t blk = c0 + i[0]; + if (*(volatile uint64_t*) (b + blk * kBlock) != (blk + 1) * 0x9E3779B97F4A7C15ull) { + sycl::atomic_ref bad(res[0]); + sycl::atomic_ref lo(res[1]); + bad.fetch_add(1); + lo.fetch_min((uint64_t) blk * kBlock); + } + }); + q.wait(); + } + uint64_t out[2] = {0, 0}; + q.memcpy(out, res, sizeof out).wait(); + sycl::free(res, q); + if (first_bad) *first_bad = (size_t) out[1]; + return out[0]; +} +} // namespace strata + +namespace strata { +inline bool arena_alias_guard_enabled() { + static const bool on = [] { const char* v = std::getenv("STRATA_ARENA_ALIAS_CHECK"); return v == nullptr || v[0] != '0'; }(); + return on; +} +} // namespace strata + +#include +namespace strata { +// sycl::malloc_device for a big allocation, checked for aliased pages (arena_alias_check) and, when it has some, allocated +// again behind a growing spacer that moves it. Small allocations and STRATA_ARENA_ALIAS_CHECK=0 go straight to +// sycl::malloc_device. The memory comes back uninitialised, as from sycl::malloc_device. +inline void* malloc_device_guarded(size_t bytes, sycl::queue& q, const char* what = "device buffer") { + void* p = sycl::malloc_device(bytes, q); + if (p == nullptr || bytes < ((size_t) 32 << 20) || !arena_alias_guard_enabled()) return p; + std::vector spacers; + bool clean = false; + for (int attempt = 0; attempt < 8 && p != nullptr; ++attempt) { + size_t first = 0; + const uint64_t bad = arena_alias_check(q, p, bytes, &first); + if (bad == 0) { + clean = true; + if (attempt > 0) + std::fprintf(stderr, "strata: %s (%.2f GiB) is clean after %d move(s)\n", what, (double) bytes / 1073741824.0, attempt); + break; + } + std::fprintf(stderr, + "strata: WARNING: %llu 64-KiB blocks of the %s (%.2f GiB) do not keep their own bytes (first at +%zu MiB): the GPU's " + "page table maps them onto other pages; allocating it again behind a %d MiB spacer\n", + (unsigned long long) bad, what, (double) bytes / 1073741824.0, first >> 20, 2 * (attempt + 1)); + sycl::free(p, q); + spacers.push_back(sycl::malloc_device((size_t) (2 * (attempt + 1)) << 20, q)); + p = sycl::malloc_device(bytes, q); + } + for (void* sp : spacers) if (sp != nullptr) sycl::free(sp, q); + if (p != nullptr && !clean) + std::fprintf(stderr, "strata: WARNING: the %s still has aliased pages after 8 tries (STRATA_ARENA_ALIAS_CHECK=0 skips the check)\n", what); + return p; +} +} // namespace strata diff --git a/sycl/probe/alias_scan.cpp b/sycl/probe/alias_scan.cpp new file mode 100644 index 00000000..19a5d4ab --- /dev/null +++ b/sycl/probe/alias_scan.cpp @@ -0,0 +1,38 @@ +// alias_scan: allocate device buffers of assorted sizes, keep them, and run strata::arena_alias_check on each: where does +// the xe page table alias pages (a write to one 2 MiB page showing at another)? Prints each buffer's address mod 1 GiB. +// alias_scan [n=40] [seed=1] [max_mib=6000] +#include +#include +#include +#include +#include +#include "strata/sycl_queue.hpp" + +int main(int argc, char** argv) { + const int n = argc > 1 ? std::atoi(argv[1]) : 40; + const unsigned seed = argc > 2 ? (unsigned) std::atoi(argv[2]) : 1; + const size_t max_mib = argc > 3 ? (size_t) std::atoll(argv[3]) : 6000; + sycl::queue q{sycl::gpu_selector_v, sycl::property::queue::in_order{}}; + std::mt19937_64 rng(seed); + std::vector keep; + size_t total = 0; + int bad_bufs = 0; + for (int i = 0; i < n; ++i) { + size_t mib = (rng() % 4 == 0) ? 1 + rng() % 8 : 1 + rng() % max_mib; + if (total + mib > 24000) break; + const size_t bytes = mib << 20; + void* p = sycl::malloc_device(bytes, q); + if (!p) { std::printf("alloc %zu MiB failed\n", mib); break; } + keep.push_back(p); + total += mib; + size_t first = 0; + const uint64_t bad = strata::arena_alias_check(q, p, bytes, &first); + std::printf("#%02d %6zu MiB at %p (mod 1GiB %5zu MiB, mod 2MiB %zu): %s", i, mib, p, (size_t) (((uintptr_t) p & ((1u << 30) - 1)) >> 20), + (size_t) ((uintptr_t) p & ((2u << 20) - 1)), bad ? "ALIAS" : "ok"); + if (bad) { ++bad_bufs; std::printf(" %llu blocks, first at +%zu MiB", (unsigned long long) bad, first >> 20); } + std::printf("\n"); + } + std::printf("%d of %zu buffers aliased\n", bad_bufs, keep.size()); + for (void* p : keep) sycl::free(p, q); + return bad_bufs ? 3 : 0; +} diff --git a/sycl/probe/arena_rw.cpp b/sycl/probe/arena_rw.cpp new file mode 100644 index 00000000..072e2bd2 --- /dev/null +++ b/sycl/probe/arena_rw.cpp @@ -0,0 +1,63 @@ +// arena_rw: does a big device arena keep what is copied into it? The engine's expert-cache fill (pinned host batches of +// 64 blobs, queue.memcpy into odd-sized slots, the arena zeroed by chunked kernels first) read back with 2 MiB pages of the +// arena holding wrong bytes on an Arc Pro B70 (xe). This reproduces the shape without the engine. +// arena_rw GIB [slot_bytes=1971200] [batch=64] [zero=1] [verify_after_fill=1] +#include +#include +#include +#include +#include +#include +#include +#include "strata/sycl_queue.hpp" + +static inline uint8_t pat(uint64_t off) { + uint64_t x = off * 0x9E3779B97F4A7C15ull; + x ^= x >> 29; + return (uint8_t) (x >> 11); +} + +int main(int argc, char** argv) { + const double gib = argc > 1 ? std::atof(argv[1]) : 4.0; + const size_t slot = argc > 2 ? (size_t) std::atoll(argv[2]) : 1971200; + const size_t batch = argc > 3 ? (size_t) std::atoll(argv[3]) : 64; + const int zero = argc > 4 ? std::atoi(argv[4]) : 1; + const size_t total = (size_t) (gib * 1073741824.0); + const size_t n_slots = total / ((slot + 255) / 256 * 256); + const size_t stride = (slot + 255) / 256 * 256; + sycl::queue q{sycl::gpu_selector_v, sycl::property::queue::in_order{}}; + std::printf("device %s\n", q.get_device().get_info().c_str()); + uint8_t* arena = (uint8_t*) sycl::malloc_device(n_slots * stride + (2 << 20), q); + if (!arena) { std::printf("alloc failed\n"); return 1; } + arena = (uint8_t*) (((uintptr_t) arena + (2 << 20) - 1) & ~(uintptr_t) ((2 << 20) - 1)); // as the engine's: 2 MiB aligned + std::printf("arena %p, %zu slots of %zu (stride %zu)\n", (void*) arena, n_slots, slot, stride); + if (zero) strata::big_fill_zero(q, arena, n_slots * stride); + uint8_t* pin = sycl::malloc_host(2 * batch * stride, q); + sycl::event done[2]; + size_t k = 0; + for (size_t b0 = 0; b0 < n_slots; b0 += batch, ++k) { + const size_t n = std::min(batch, n_slots - b0); + uint8_t* set = pin + (k % 2) * batch * stride; + done[k % 2].wait(); + for (size_t j = 0; j < n; ++j) + for (size_t x = 0; x < slot; ++x) set[j * stride + x] = pat((b0 + j) * stride + x); + for (size_t j = 0; j < n; ++j) done[k % 2] = q.memcpy(arena + (b0 + j) * stride, set + j * stride, slot); + } + q.wait(); + std::vector got(stride); + size_t bad = 0; + for (size_t i = 0; i < n_slots; ++i) { + q.memcpy(got.data(), arena + i * stride, slot).wait(); + size_t nd = 0, fd = slot; + for (size_t x = 0; x < slot; ++x) + if (got[x] != pat(i * stride + x)) { ++nd; if (fd == slot) fd = x; } + if (nd) { + ++bad; + if (bad <= 10) + std::printf("slot %zu at %p (offset %zu MiB): %zu of %zu bytes differ, first at %zu\n", i, (void*) (arena + i * stride), + (i * stride) >> 20, nd, slot, fd); + } + } + std::printf("%zu of %zu slots differ\n", bad, n_slots); + return bad ? 3 : 0; +} diff --git a/sycl/src/core/device.dp.cpp b/sycl/src/core/device.dp.cpp index 45645f7a..5905b306 100644 --- a/sycl/src/core/device.dp.cpp +++ b/sycl/src/core/device.dp.cpp @@ -2,6 +2,7 @@ #define DPCT_PROFILING_ENABLED #include #include +#include "strata/sycl_queue.hpp" #include "strata/core/device.hpp" #include @@ -411,7 +412,7 @@ DeviceArena::DeviceArena(uint64_t bytes, int ordinal, bool poison) check(DPCT_CHECK_ERROR(dpct::select_device(ordinal)), "cudaSetDevice"); // One allocation for the whole region. cudaMalloc of a large block is the thing that can fail late, so it // happens once, here, before anything depends on it. - check(DPCT_CHECK_ERROR(base_ = (void *)sycl::malloc_device( + check(DPCT_CHECK_ERROR(base_ = (void *)strata::malloc_device_guarded( (size_t)bytes, dpct::get_in_order_queue())), "cudaMalloc"); if (poison_) { diff --git a/sycl/src/core/expert_cache.cpp b/sycl/src/core/expert_cache.cpp index fb8b519f..ed1c8740 100644 --- a/sycl/src/core/expert_cache.cpp +++ b/sycl/src/core/expert_cache.cpp @@ -638,8 +638,8 @@ bool ExpertCache::open(int64_t n_slots, int64_t n_layers, int64_t n_expert, int6 base_ = r->base(); vmm_ = std::move(r); } else if (DPCT_CHECK_ERROR( - base_ = (uint8_t *)sycl::malloc_device( - (size_t)want, dpct::get_in_order_queue())) != 0 || + base_ = (uint8_t *)strata::malloc_device_guarded( + (size_t)want, dpct::get_in_order_queue(), "expert cache arena")) != 0 || base_ == nullptr) { // Level Zero answers a too-large allocation with null, not an exception // (an Arc A750 caps one allocation at 4 GiB unless UR_L0_ENABLE_RELAXED_ALLOCATION_LIMITS=1) base_ = nullptr; diff --git a/sycl/src/core/mtp.cpp b/sycl/src/core/mtp.cpp index a5c4af8a..3c021574 100644 --- a/sycl/src/core/mtp.cpp +++ b/sycl/src/core/mtp.cpp @@ -222,7 +222,7 @@ bool MtpDrafter::make_q4_dense(const std::vector& blob, std::string& er } q4_off_.push_back({t->name, off}); } - dense4_ = (uint8_t*) sycl::malloc_device((size_t) total, dpct::get_in_order_queue()); // SYCL port: cudaMalloc/cudaMemcpy + dense4_ = (uint8_t*) strata::malloc_device_guarded((size_t) total, dpct::get_in_order_queue()); // SYCL port: cudaMalloc/cudaMemcpy if (dense4_ == nullptr) { err = "mtp: the Q4_0 projections do not fit"; return false; } dpct::get_in_order_queue().memcpy(dense4_, host.data(), (size_t) total).wait(); vram_ += total; @@ -306,7 +306,7 @@ bool MtpDrafter::load(const std::string &rt_dir, const ModelGeometry &g, std::vector blob; if (!read_file(rt_dir + "/dense.bin", blob)) { err = "mtp: cannot read dense.bin"; return false; } const dpct::err0 alloc = - DPCT_CHECK_ERROR(dense_ = (uint8_t *)sycl::malloc_device( + DPCT_CHECK_ERROR(dense_ = (uint8_t *)strata::malloc_device_guarded( blob.size(), dpct::get_in_order_queue())); /* DPCT1000: Error handling if-stmt was detected but could not be @@ -353,7 +353,7 @@ bool MtpDrafter::load(const std::string &rt_dir, const ModelGeometry &g, FILE* f; ~Closer() { if (f != nullptr) std::fclose(f); } } closer{f}; - if (DPCT_CHECK_ERROR(experts_ = (uint8_t *)sycl::malloc_device( + if (DPCT_CHECK_ERROR(experts_ = (uint8_t *)strata::malloc_device_guarded( bytes, dpct::get_in_order_queue())) != 0) { err = "mtp: the 512 experts do not fit in VRAM"; return false; } @@ -390,7 +390,7 @@ bool MtpDrafter::load(const std::string &rt_dir, const ModelGeometry &g, qsa_set_kv_hybrid(false); if (kv_hybrid_was) qsa_set_kv_int8(true); // the drafter under --kv k8v4: plain INT8 uint64_t sb = qsa_state_bytes(g, max_cells, false, ring); - if (DPCT_CHECK_ERROR(state_arena_ = (void *)sycl::malloc_device( + if (DPCT_CHECK_ERROR(state_arena_ = (void *)strata::malloc_device_guarded( sb, dpct::get_in_order_queue())) != 0) { err = "mtp: the K/V state does not fit"; return false; } @@ -405,7 +405,7 @@ bool MtpDrafter::load(const std::string &rt_dir, const ModelGeometry &g, st_ = QsaState{}; ring = -1; // fully resident sb = qsa_state_bytes(g, max_cells, false, ring); - if (DPCT_CHECK_ERROR(state_arena_ = (void *)sycl::malloc_device( + if (DPCT_CHECK_ERROR(state_arena_ = (void *)strata::malloc_device_guarded( sb, dpct::get_in_order_queue())) != 0) { err = "mtp: the K/V state does not fit"; return false; } @@ -465,7 +465,7 @@ bool MtpDrafter::load(const std::string &rt_dir, const ModelGeometry &g, }; Bump count; carve(count); - if (DPCT_CHECK_ERROR(arena_ = (void *)sycl::malloc_device( + if (DPCT_CHECK_ERROR(arena_ = (void *)strata::malloc_device_guarded( count.used, dpct::get_in_order_queue())) != 0) { err = "mtp: buffers do not fit"; return false; } diff --git a/sycl/src/core/native_dense.cpp b/sycl/src/core/native_dense.cpp index 4c938108..3d6beca1 100644 --- a/sycl/src/core/native_dense.cpp +++ b/sycl/src/core/native_dense.cpp @@ -1,6 +1,7 @@ #define DPCT_PROFILING_ENABLED #include #include +#include "strata/sycl_queue.hpp" #include "strata/core/native_dense.hpp" #include #include "strata/core/weights.hpp" @@ -245,7 +246,7 @@ bool NativeDense::load(const std::vector &shards, tensor.type, (int) ref.ne0, (int) ref.ne1); void* allocation = nullptr; auto status = - DPCT_CHECK_ERROR(allocation = (void *)sycl::malloc_device( + DPCT_CHECK_ERROR(allocation = (void *)strata::malloc_device_guarded( bytes, dpct::get_in_order_queue())); DevicePtr data(allocation); if (status == 0) @@ -284,7 +285,7 @@ bool NativeDense::load(const std::vector &shards, (int) ref.ne1); void* packed_allocation = nullptr; auto packed_status = DPCT_CHECK_ERROR( - packed_allocation = (void *)sycl::malloc_device( + packed_allocation = (void *)strata::malloc_device_guarded( bytes, dpct::get_in_order_queue())); packed.reset(packed_allocation); if (packed_status == 0) @@ -332,7 +333,7 @@ bool NativeDense::load(const std::vector &shards, std::vector q8; if (f32_inject) q8 = q8_0_of((const float*) gguf.tensor_data(tensor), (uint64_t) ref.ne0 * (uint64_t) ref.ne1); if (DPCT_CHECK_ERROR( - p = (void *)sycl::malloc_device( + p = (void *)strata::malloc_device_guarded( bytes, dpct::get_in_order_queue())) != 0 || /* DPCT1114: cudaMemcpy is migrated to @@ -356,7 +357,7 @@ bool NativeDense::load(const std::vector &shards, if (pending.empty()) { err = "native dense: no supported GDN/QSA matrices in supplied shards"; return false; } void* allocation = nullptr; const auto status = - DPCT_CHECK_ERROR(allocation = (void *)sycl::malloc_device( + DPCT_CHECK_ERROR(allocation = (void *)strata::malloc_device_guarded( strata::kernels::native_q8_1_bytes(max_in), dpct::get_in_order_queue())); DevicePtr scratch(allocation); diff --git a/sycl/src/core/native_head.cpp b/sycl/src/core/native_head.cpp index 9f4b270f..9afd2199 100644 --- a/sycl/src/core/native_head.cpp +++ b/sycl/src/core/native_head.cpp @@ -1,6 +1,7 @@ #define DPCT_PROFILING_ENABLED #include #include +#include "strata/sycl_queue.hpp" #include "strata/core/native_head.hpp" #include "strata/artifact/gguf_reader.hpp" #include "strata/kernels/iq_kernels.hpp" @@ -50,11 +51,11 @@ bool NativeHead::load(const std::vector &shards, int64_t n_in, void* weights = nullptr; void* scratch = nullptr; dpct::err0 status = - DPCT_CHECK_ERROR(weights = (void *)sycl::malloc_device( + DPCT_CHECK_ERROR(weights = (void *)strata::malloc_device_guarded( bytes, dpct::get_in_order_queue())); if (status == 0) status = DPCT_CHECK_ERROR( - scratch = (void *)sycl::malloc_device( + scratch = (void *)strata::malloc_device_guarded( strata::kernels::native_q8_1_bytes((int)n_in, 1), dpct::get_in_order_queue())); strata::platform::advise_willneed(gguf.tensor_data(*tensor), bytes); @@ -212,7 +213,7 @@ bool NativeEmbed::load(const std::vector &shards, int64_t n_embd, */ host_ = nullptr; void* d = nullptr; - if (DPCT_CHECK_ERROR(d = (void *)sycl::malloc_device( + if (DPCT_CHECK_ERROR(d = (void *)strata::malloc_device_guarded( bytes_, dpct::get_in_order_queue())) != 0 || /* diff --git a/sycl/src/core/verify.cpp b/sycl/src/core/verify.cpp index 8e27634a..9d26b880 100644 --- a/sycl/src/core/verify.cpp +++ b/sycl/src/core/verify.cpp @@ -541,7 +541,7 @@ bool Verifier::init(const WeightTable &wt, const ModelGeometry &g, }; Bump count; carve(count); - if (DPCT_CHECK_ERROR(arena_ = (void *)sycl::malloc_device( + if (DPCT_CHECK_ERROR(arena_ = (void *)strata::malloc_device_guarded( count.used, dpct::get_in_order_queue())) != 0) { err = "verify: the device arena (" + std::to_string(count.used >> 20) + " MiB) does not fit"; return false; diff --git a/sycl/src/prefill/prefill.cpp b/sycl/src/prefill/prefill.cpp index ae244c85..edb08989 100644 --- a/sycl/src/prefill/prefill.cpp +++ b/sycl/src/prefill/prefill.cpp @@ -316,7 +316,7 @@ struct Alloc { return p; } void* p = nullptr; - if (DPCT_CHECK_ERROR(p = (void *)sycl::malloc_device( + if (DPCT_CHECK_ERROR(p = (void *)strata::malloc_device_guarded( bytes, dpct::get_in_order_queue())) != 0) { ok = false; failed_bytes = bytes; return nullptr; } @@ -1706,7 +1706,7 @@ bool Prefill::set_peer(core::PeerExperts *peer, int64_t cap_rows, try { void *p = nullptr; if (!ok || - DPCT_CHECK_ERROR(p = (void *)sycl::malloc_device( + DPCT_CHECK_ERROR(p = (void *)strata::malloc_device_guarded( bytes, dpct::get_in_order_queue())) != 0) { ok = false; return nullptr; } diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index eec2dc49..17cb2995 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -2723,7 +2723,7 @@ int main(int argc, char **argv) try { rewritten. */ if (const dpct::err0 ce = - DPCT_CHECK_ERROR(arena = (void *)sycl::malloc_device( + DPCT_CHECK_ERROR(arena = (void *)strata::malloc_device_guarded( pool_bytes, dpct::get_in_order_queue())); ce != 0) { // #486: the arena is the first large allocation and its size does not depend on the context, so what is @@ -3154,7 +3154,7 @@ int main(int argc, char **argv) try { skip_s = skip; } void* arena_s = nullptr; - if (DPCT_CHECK_ERROR(arena_s = (void *)sycl::malloc_device( + if (DPCT_CHECK_ERROR(arena_s = (void *)strata::malloc_device_guarded( pool_s, dpct::get_in_order_queue())) != 0 || !st.wt.load(o.pack, arena_s, pool_s, err, skip_s.empty() ? nullptr : &skip_s)) { @@ -4511,6 +4511,7 @@ int main(int argc, char **argv) try { // admission finds no room and every non-profiled expert stays a CPU miss. That is what makes the profile // the policy rather than a hint. int64_t prefilled = 0; + std::function verify_all_slots; // STRATA_VERIFY_ALL_SLOTS (debug), set by the pipelined fill if (!profile.empty() && srcp != nullptr) { // #369 (dag08): per layer, a full layer skips only its own pairs - each layer takes its hottest experts until // its range is full (one full layer used to end the whole fill, leaving most layers empty) @@ -4580,6 +4581,51 @@ int main(int argc, char **argv) try { return 1; } prefilled = (int64_t) fills.size(); + if (std::getenv("STRATA_VERIFY_ALL_SLOTS") != nullptr) { // debug: every filled slot read back and compared with the GGUF + auto fl = std::make_shared>(fills); + verify_all_slots = [&, fl, blob_cap](const char* when) { + sycl::queue& vq = dpct::get_in_order_queue(); + vq.wait(); + std::vector want_b(blob_cap), got_b(blob_cap); + int64_t bad = 0, first_bad = -1; + for (size_t i = 0; i < fl->size(); ++i) { + const Fill& f = (*fl)[i]; + const size_t nb = (size_t) lay.blob_bytes(f.l); + if (!gguf_src.read_into(f.l, f.e, want_b.data(), blob_cap)) { ++bad; continue; } + vq.memcpy(got_b.data(), xcache.device_slot(f.slot), nb).wait(); + if (std::memcmp(want_b.data(), got_b.data(), nb) != 0) { + if (first_bad < 0) first_bad = (int64_t) i; + ++bad; + size_t nd = 0, fd = nb, ld = 0; + for (size_t x = 0; x < nb; ++x) + if (want_b[x] != got_b[x]) { ++nd; if (fd == nb) fd = x; ld = x; } + if (std::getenv("STRATA_VERIFY_FIND") != nullptr && bad <= 2 && fd + 4160 < nb) { // whose blob is the wrong data? + const uint8_t* probe = got_b.data() + fd + 4096; + std::vector other(blob_cap); + for (size_t j = 0; j < fl->size(); ++j) { + const Fill& g2 = (*fl)[j]; + if (!gguf_src.read_into(g2.l, g2.e, other.data(), blob_cap)) continue; + const size_t nb2 = (size_t) lay.blob_bytes(g2.l); + const void* hit = memmem(other.data(), nb2, probe, 64); + if (hit != nullptr) + std::fprintf(stderr, " the wrong data at byte %zu is expert (layer %d, expert %d), slot %d (fill %zu), byte %zu of its blob\n", + fd + 4096, (int) g2.l, (int) g2.e, (int) g2.slot, j, (size_t) ((const uint8_t*) hit - other.data())); + } + } + if (const char* dd = std::getenv("STRATA_VERIFY_DUMP"); dd != nullptr && bad == 1) { + const std::string base = std::string(dd) + "/slot" + std::to_string(f.slot); + if (FILE* fo = std::fopen((base + ".got").c_str(), "wb")) { std::fwrite(got_b.data(), 1, nb, fo); std::fclose(fo); } + if (FILE* fo = std::fopen((base + ".want").c_str(), "wb")) { std::fwrite(want_b.data(), 1, nb, fo); std::fclose(fo); } + } + std::fprintf(stderr, "strata generate: STRATA_VERIFY_ALL_SLOTS (%s): fill %zu (layer %d expert %d) slot %d at %p: %zu of %zu bytes differ, first at %zu, last at %zu\n", + when, i, (int) f.l, (int) f.e, (int) f.slot, (const void*) xcache.device_slot(f.slot), nd, nb, fd, ld); + } + } + std::fprintf(stderr, "strata generate: STRATA_VERIFY_ALL_SLOTS (%s): %lld of %zu slots differ from the GGUF (first at fill %lld)\n", + when, (long long) bad, fl->size(), (long long) first_bad); + }; + verify_all_slots("after the fill"); + } } // #286: an unbuffered file tier reads the pairs in batches of 64, the next batch while this one is copied std::future ahead; @@ -5113,6 +5159,7 @@ int main(int argc, char **argv) try { mem_mark("the expert cache and the graphs"); std::fprintf(stderr, "strata generate: session is up (engine %s)\n", STRATA_VERSION); + if (verify_all_slots) verify_all_slots("session up"); auto run_head = [&](void* stream) -> bool { if (!native_head.loaded()) return strata::core::lm_head(wt, g, ss.block, d_logits, stream, err); From 6fd12038b11f7269fe3e9b172635aa3764c517eb Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 7 Oct 2026 11:31:11 +0200 Subject: [PATCH 2/3] sycl: no short first prompt chunk while part of the experts is in the host mirror; setup asks a 24 GB+ card for 4096-token chunks Every prompt chunk streams the experts the VRAM cache does not hold, over PCIe, and a 4K prompt touches nearly all 512 experts of a layer. The short first chunk (STRATA_PREFILL_FIRST, 256 tokens, there to start the GPU while PLE rows are read) therefore cost a whole extra pass of that stream whenever the cache holds only part of the model. Its default is now 256 only when the cache holds every expert, else 0 (an explicit STRATA_PREFILL_FIRST still decides). Arc Pro B70 32 GB, IQ3_S (11.5k of 24.6k experts in VRAM, the rest in the pinned mirror at 13 GB/s), a 4,095-token prompt, MTP on, interleaved runs, medians of 3: 2048-token chunks 618 -> 730 tok/s, 4096-token chunks 784 -> 980. sycl/setup_intel.py now writes --prefill 4096 for a card with 24 GB or more (it costs ~700 expert cache slots, about 3% of decode on the 200-token story). --- sycl/probe/gemm_launch.cpp | 44 +++++++++++++++++++++++++++++++++++ sycl/probe/launch_cost.cpp | 45 ++++++++++++++++++++++++++++++++++++ sycl/setup_intel.py | 12 ++++++---- sycl/src/prefill/prefill.cpp | 8 ++++++- 4 files changed, 103 insertions(+), 6 deletions(-) create mode 100644 sycl/probe/gemm_launch.cpp create mode 100644 sycl/probe/launch_cost.cpp diff --git a/sycl/probe/gemm_launch.cpp b/sycl/probe/gemm_launch.cpp new file mode 100644 index 00000000..88af0dce --- /dev/null +++ b/sycl/probe/gemm_launch.cpp @@ -0,0 +1,44 @@ +// gemm_launch: what does one expert-sized FP16 GEMM (oneMKL, half in, float out) cost back to back, by row count? +// The prompt path issues one gate/up and one down GEMM per routed expert (~25k experts per 4K prompt on the 48 layers); if the +// per-call time barely moves with the rows, the path is bound by launches, not by the XMX units. +// gemm_launch [calls=2000] +#include +#include +#include +#include +#include +#include + +int main(int argc, char** argv) { + const int calls = argc > 1 ? std::atoi(argv[1]) : 2000; + sycl::queue q{sycl::gpu_selector_v, sycl::property::queue::in_order{}}; + const int64_t N = 2560; + struct Shape { const char* name; int64_t n, k; }; + const Shape shapes[] = {{"gate/up 1280x2560", 1280, N}, {"down 2560x640", N, 640}}; + const int64_t Ts[] = {8, 32, 80, 160, 320, 640, 1280}; + const int64_t maxT = 1280; + using half = sycl::half; + half* X = sycl::malloc_device(maxT * N, q); + half* W = sycl::malloc_device(N * 1280 * 4, q); + float* Y = sycl::malloc_device(maxT * N, q); + q.memset(X, 0, maxT * N * sizeof(half)); + q.memset(W, 0, N * 1280 * 4 * sizeof(half)); + q.wait(); + for (const Shape& s : shapes) { + for (int64_t T : Ts) { + auto run = [&](int n) { + for (int i = 0; i < n; ++i) + oneapi::mkl::blas::column_major::gemm(q, oneapi::mkl::transpose::trans, oneapi::mkl::transpose::nontrans, s.n, T, s.k, 1.0f, + W, s.k, X, s.k, 0.0f, Y, s.n); + q.wait(); + }; + run(50); + const auto t0 = std::chrono::steady_clock::now(); + run(calls); + const double us = std::chrono::duration(std::chrono::steady_clock::now() - t0).count() / calls; + const double gflop = 2.0 * (double) s.n * (double) T * (double) s.k * 1e-9; + std::printf("%-20s T=%5lld: %7.1f us/call (%6.1f TFLOP/s)\n", s.name, (long long) T, us, gflop / us * 1e-3 * 1e3 / 1e3); + } + } + return 0; +} diff --git a/sycl/probe/launch_cost.cpp b/sycl/probe/launch_cost.cpp new file mode 100644 index 00000000..cef1cd04 --- /dev/null +++ b/sycl/probe/launch_cost.cpp @@ -0,0 +1,45 @@ +// launch_cost: host time per submission on an in-order queue (empty-ish kernel), with and without queue profiling, and with +// an event per submission. If the prompt path's ~6 submissions per expert cost this much each, the 25k experts of a 4K +// prompt are launch-bound. +#include +#include +#include +#include +#include + +template +static double per_call_us(sycl::queue& q, int n, F&& f) { + for (int i = 0; i < 100; ++i) f(i); + q.wait(); + const auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < n; ++i) f(i); + const double submit_us = std::chrono::duration(std::chrono::steady_clock::now() - t0).count() / n; + q.wait(); + const double total_us = std::chrono::duration(std::chrono::steady_clock::now() - t0).count() / n; + std::printf(" host submit %.2f us/call, until done %.2f us/call\n", submit_us, total_us); + return submit_us; +} + +int main(int argc, char** argv) { + const int n = argc > 1 ? std::atoi(argv[1]) : 20000; + for (int prof = 0; prof < 2; ++prof) { + sycl::queue q = prof ? sycl::queue{sycl::gpu_selector_v, {sycl::property::queue::in_order(), sycl::property::queue::enable_profiling()}} + : sycl::queue{sycl::gpu_selector_v, {sycl::property::queue::in_order()}}; + float* d = sycl::malloc_device(1 << 20, q); + std::printf("queue profiling %s\n", prof ? "on" : "off"); + std::printf(" tiny kernel, 1 work-group:\n"); + per_call_us(q, n, [&](int) { q.parallel_for(sycl::nd_range<1>(256, 256), [=](sycl::nd_item<1> it) { d[it.get_global_id(0)] = 1.f; }); }); + std::printf(" kernel of 4096 work-groups (1M items):\n"); + per_call_us(q, n / 4, [&](int) { q.parallel_for(sycl::nd_range<1>(1 << 20, 256), [=](sycl::nd_item<1> it) { d[it.get_global_id(0)] += 1.f; }); }); + std::printf(" tiny kernel, event kept:\n"); + sycl::event e; + per_call_us(q, n, [&](int) { e = q.parallel_for(sycl::nd_range<1>(256, 256), [=](sycl::nd_item<1> it) { d[it.get_global_id(0)] = 1.f; }); }); + std::printf(" submit_barrier(event) + tiny kernel:\n"); + per_call_us(q, n, [&](int) { + q.ext_oneapi_submit_barrier({e}); + e = q.parallel_for(sycl::nd_range<1>(256, 256), [=](sycl::nd_item<1> it) { d[it.get_global_id(0)] = 1.f; }); + }); + sycl::free(d, q); + } + return 0; +} diff --git a/sycl/setup_intel.py b/sycl/setup_intel.py index 5e01db41..900b1de7 100644 --- a/sycl/setup_intel.py +++ b/sycl/setup_intel.py @@ -115,7 +115,7 @@ def drop(args, name, value=False): del args[i:i + 1 + int(value)] -def to_sycl(cfg: dict, exe: Path, ram: float, keep: dict) -> dict: +def to_sycl(cfg: dict, exe: Path, ram: float, keep: dict, vram_gb: float = 0.0) -> dict: """setup's config (written for its HIP path) -> the SYCL port's: the container's paths, experts streamed from the GGUF into VRAM (every expert must fit, so the VRAM reserve is the smallest that leaves the KV and the prompt buffers room - docs/INTEL.md), KV streaming from 64K up when the RAM holds the KV (the B70 at 256K decodes at @@ -137,9 +137,11 @@ def to_sycl(cfg: dict, exe: Path, ram: float, keep: dict) -> dict: S.ok(f"KV streaming on: the context's KV cache lives in RAM ({kv_ram:.1f} GB), every expert stays in VRAM") drop(args, "--vram-reserve-mib", True) args += ["--stream-experts", "--vram-reserve-mib", "1024" if ctx <= 32768 else "2048"] - if ctx > 32768: # long contexts: 4096-token chunks keep the prompt buffers small - drop(args, "--prefill", True) - args += ["--prefill", "4096"] + if ctx > 32768 or vram_gb >= 24: # long contexts: 4096-token chunks keep the prompt buffers small; a + drop(args, "--prefill", True) # 24 GB+ card with part of the experts in the RAM mirror streams those + args += ["--prefill", "4096"] # over PCIe once per chunk, so fewer, bigger chunks read the prompt + # faster (Arc Pro B70, IQ3_S, a 4,095-token prompt: 2,048-token + # chunks 618 tok/s, 4,096: 1,002; docs/INTEL.md); it costs ~700 cache slots out = {k: v for k, v in cfg.items() if k not in ("lib_dirs", "env", "vision", "gpus")} out.update({"backend": "sycl", "exe": str(SYCL_WRAPPER), "args": args, "sycl_root": str(MOUNT)}) env = {} @@ -207,7 +209,7 @@ def install(argv) -> None: def write_run_script(model, cfg_path, port, open_browser=True): # setup.write_run_script's signature (#870) cfg = json.loads(Path(cfg_path).read_text(encoding="utf-8")) - cfg = to_sycl(cfg, exe, real_ram, keep.get(Path(cfg_path).name, {})) + cfg = to_sycl(cfg, exe, real_ram, keep.get(Path(cfg_path).name, {}), intel[0]["vram_gb"]) Path(cfg_path).write_text(json.dumps(cfg, indent=1), encoding="utf-8") script = write(model, cfg_path, port, open_browser) script.write_text(script.read_text().replace(str(ROOT / "serve" / "server.py"), str(SERVER))) diff --git a/sycl/src/prefill/prefill.cpp b/sycl/src/prefill/prefill.cpp index edb08989..08fe3fc2 100644 --- a/sycl/src/prefill/prefill.cpp +++ b/sycl/src/prefill/prefill.cpp @@ -2156,7 +2156,13 @@ bool Prefill::run_impl(const int64_t *tokens, int64_t n, int64_t pos0, // SYCL port: a short first chunk so the GPU starts while the rest of the prompt's PLE rows are still being read // (27k random 4 KB reads per 2k tokens, 330 ms at the drive's ~85k IOPS, otherwise all before the first kernel). // STRATA_PREFILL_FIRST= (0: off), default 256 when the prompt is longer than twice that. - static const int64_t first_chunk = [] { const char* v = std::getenv("STRATA_PREFILL_FIRST"); return v ? std::atoll(v) : 256; }(); + // Every chunk streams the experts the cache does not hold (a 4K prompt touches nearly all 512 per layer), over PCIe: with + // part of the model in the host mirror a short first chunk costs a whole extra pass of that stream (an Arc Pro B70 on + // IQ3_S: a 4,095-token prompt 784 -> 1,002 tok/s without it). So the default is 256 only when the cache holds every + // expert; STRATA_PREFILL_FIRST= decides explicitly. + const bool all_cached = m.cache != nullptr && m.g != nullptr && m.cache->slots() >= m.g->n_layers * m.g->n_expert; + static const char* const first_env = std::getenv("STRATA_PREFILL_FIRST"); + const int64_t first_chunk = first_env ? std::atoll(first_env) : (all_cached ? 256 : 0); auto chunk_len = [&](int64_t c0) { if (c0 == 0 && first_chunk > 0 && first_chunk < m.T && n > 2 * first_chunk) return first_chunk; return std::min(m.T, n - c0); From 3838a40a0c791391f5f412c372318df1bafcaac2 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 7 Oct 2026 12:22:00 +0200 Subject: [PATCH 3/3] sycl: the sampler's top_p/temperature tail accumulates in float (FP64 is emulated on Arc Alchemist); B70 IQ3_S findings in docs/INTEL.md samp_acc_t is float by default (-DSTRATA_SYCL_SAMPLER_FP64=1 keeps the reference's double). On an Arc A750 one row of the tail cost 451 us in double and 20 us in float; a sampled decode ran at 7.62 -> 8.10 tok/s (medians of 5 interleaved pairs, runs 7.1-9.2). sampler_parity: 0 failures on the A750 (JIT build) and on the B70; both cards' 10-prompt gates pass 10 of 10, and the B70 gate's sampled cases pick the same tokens as before. Of the kernels that use double, only the sampler runs on a native pack (the router, combine, gate and norm kernels there are float). Probes: sycl/probe/fp64_cost.cpp (FP64 against float in the small reduction kernels), gemm_vary.cpp. docs/INTEL.md: the aliased-pages bug, NO_HOST, the prompt-chunking numbers, draft-length sweep, FP64 and XMX findings; docs/INTEL_ARC.md: a row for the B70/A750 runs. --- docs/INTEL.md | 65 +++++++++++++++++ docs/INTEL_ARC.md | 1 + sycl/include/strata/sycl_math.hpp | 12 +++ sycl/probe/fp64_cost.cpp | 105 +++++++++++++++++++++++++++ sycl/probe/gemm_launch.cpp | 20 ++++- sycl/probe/gemm_vary.cpp | 47 ++++++++++++ sycl/src/kernels/cuda/sampler.dp.cpp | 45 ++++++------ 7 files changed, 271 insertions(+), 24 deletions(-) create mode 100644 sycl/probe/fp64_cost.cpp create mode 100644 sycl/probe/gemm_vary.cpp diff --git a/docs/INTEL.md b/docs/INTEL.md index 38b331ee..edafe0ec 100644 --- a/docs/INTEL.md +++ b/docs/INTEL.md @@ -631,6 +631,71 @@ test an SM-holding NVIDIA bench (not built). Outputs identical to 0.1.33 (Coder - Speculative decoding on the llama.cpp path (the GGUF carries no draft layer llama.cpp can use). The SYCL port has it (MTP draft layer, `--mtp`). +## Arc Pro B70 with a model that does not fit: Flash-Next IQ3_S (2026-10-07, branch f-141-intel) + +The earlier B70 rows are for models whose experts all fit in VRAM. IQ3_S has 24,576 experts of 1.97 MB (46 GB): the 32 GB +card holds 11.5k of them (22 GiB of cache) and the rest sit in a pinned host mirror that the GPU reads over PCIe. Tested on +the B70 VM (xe driver, kernel 7.0, oneAPI 2026.1, PCIe measured at 13.3 GB/s host to device), engine 0.1.40-sycl. + +**Two things made it produce garbage, both fixed or documented here.** + +- **Aliased pages in big allocations (fixed in the engine).** The xe driver returned the 22 GiB expert-cache arena with two + of its 2 MiB pages mapped onto the same memory: a write at +2 MiB showed at +1022 MiB. Cache slots there held other + experts' bytes, and the prompt came out NaN at the first layer that routed to one (layer 4, expert 249); the same run + with another `--max-context`, or with an MTP window of 4 instead of 6, was clean. `STRATA_VERIFY_ALL_SLOTS=1` + (`STRATA_VERIFY_FIND=1`, `STRATA_VERIFY_DUMP=dir`) reads every filled slot back and compares it with the GGUF; that is how + the aliasing was found (the wrong bytes were slot 0's blob). Every allocation of 32 MiB or more now goes through + `strata::malloc_device_guarded`: it tags every 64 KiB, reads the tags back in a second kernel, and allocates again behind a + growing spacer until the range is clean (a warning names each retry; the check costs under 0.5 s at startup; + `STRATA_ARENA_ALIAS_CHECK=0` skips it). `sycl/probe/arena_rw.cpp` and `alias_scan.cpp` do not reproduce it on their own: it + needs the engine's allocation history. +- **`STRATA_VERIFY_NO_HOST=1` is required whenever part of the experts is not in VRAM.** `sycl/serve/strata-sycl.sh` sets + it; a by-hand run must too. Without it the per-layer host/GPU handshake is not visible across the bus on xe and the logits + turn NaN a few tokens into the answer, differently on every run. With it (and the mirror covering every miss) the run is + deterministic: two runs gave identical tokens. + +**Numbers** (greedy, `--spec 4 --spec-min-p 0.5 --mtp`, INT8 KV, 32K context, `--stream-experts --vram-reserve-mib 1024 +--ple-io ram`, 11.5k experts resident; the 10-prompt `mg_norepeat` gate passes 10 of 10, the xe error counters did not move): + +| | before | after | +|---|---|---| +| 4,095-token prompt, `--prefill auto` (2,048-token chunks) | 618 tok/s | 730 | +| 4,095-token prompt, `--prefill 4096` | 784 | **980-1,002** | +| 8,169-token prompt: auto / 4096 / 8192 lending cache slots / 8192 own buffers | 676 | 953 / 1,037 / 1,117 (9.4k slots) | +| decode, 200-token story (66% of drafts accepted, 1.98 tokens per round) | 31.4 tok/s | 30.5 with 4096-token chunks (700 fewer cache slots) | +| decode, 200-token code answer (90% accepted, 3.65 tokens per round) | not measured | 40.8 with 4096-token chunks | + +(Interleaved A/B pairs, medians of 3-5. "Before" is the same build with the old short first chunk; the decode figures are +the old default and `--prefill 4096`.) + +**Why the prompt is slow here, and the two changes.** Every prompt chunk streams the experts the cache does not hold over +PCIe, and a 4K prompt touches nearly all 512 experts of every layer: 13.5k missing experts x 1.97 MB = 26 GB, 2 s of the +bus per chunk. So the prompt reads faster in fewer, bigger chunks, and the short first chunk (`STRATA_PREFILL_FIRST`, 256 +tokens, there to start the GPU while the PLE rows are read) cost a whole extra pass of that stream. It is now 256 only when +the cache holds every expert, else 0. `setup_intel.py` writes `--prefill 4096` for a card with 24 GB or more (the chunk's +buffers take ~700 cache slots; `--prefill 8192 --prefill-borrow` lends cache slots instead and keeps all of them for decode, +at ~1 s of refill per prompt). Where the 4K prompt's GPU time goes now (GPU timeline, timing on): expert dequant 20%, the two +expert GEMMs 34%, QSA attention 14%, host grouping 6.5%, GDN 9%, hyper-connection reads 4.6%. + +**Draft length** (200 tokens, medians of 5 interleaved pairs, `--spec-min-p 0.5`): `--spec 6` against `--spec 4` is +6.5% on +code (43.4 against 40.8 tok/s, 84% accepted against 90%) and -1.5% on prose (29.9 against 30.4). A 2-run sweep of the rest +(`--spec 2/3/5`, min-p 0.3/0.7) was within the run-to-run noise of ~1 tok/s; the setup default (4, 0.5) stays. + +**FP64.** Arc Alchemist emulates it (`IGC_EnableDPEmulation=1`); on the A750 one row of the sampler's top_p/temperature tail +costs 451 us in double and 20 us in float (`sycl/probe/fp64_cost.cpp`), and a sampled decode ran at 7.6 tok/s against 12 for +a greedy one. On the B70 the same kernels cost 3.4 against 2.1 us, so FP64 is not a B70 problem. Of the kernels that use +double, the native-pack path (the packs setup builds) runs only the sampler (a 16-token greedy run created 173 kernels, the +double ones among them: `sample_tokens` only; the native router, combine, gate and norm kernels are float). The sampler's tail +now accumulates in `strata::samp_acc_t`, float by default (`-DSTRATA_SYCL_SAMPLER_FP64=1` keeps double): A750 sampled decode +7.62 -> 8.10 tok/s (medians of 5 interleaved pairs, runs 7.1-9.2), `sampler_parity` 0 failures on both cards, and the B70 gate's +sampled cases picked the same tokens. + +**XMX.** oneMKL's FP16 GEMMs already run on the matrix engines; per expert the dequant (42 us for a gate/up matrix) costs +twice the GEMM (20 us), and the fused dequant+XMX kernel (`xmx_gemm_bench`) is 0.22x of the pair on this card. The speed left +on this card for this model is the dequant kernels (at ~200 GB/s against a 600 GB/s card), the host grouping, and the QSA +prompt attention (14%); the multi-column int8 DPAS decode kernels of llama.cpp PR 29864 target K-quant and Q8_0 weights, not +the IQ-quant experts, and were not ported. + ## Measured, 2026-10-01, Arc Pro B70, Coder IQ1_M, 32K context, INT8 KV: the SYCL port (engine 0.1.31-sycl) | | | diff --git a/docs/INTEL_ARC.md b/docs/INTEL_ARC.md index 2f65b3bd..462bb5c4 100644 --- a/docs/INTEL_ARC.md +++ b/docs/INTEL_ARC.md @@ -22,6 +22,7 @@ There is **no ready-made Intel engine** in the release zips. You build it from s | Community | 2x Arc Pro B60 24 GB, `--layer-split` | Coder IQ1_M: 56.6 tok/s decode, 428 tok/s prompt (2,129 tokens); Flash-Next IQ2_XS: 58.6-61.3 tok/s decode, 436 tok/s prompt; all experts in VRAM; 8K context | [bench/results/2026-10-04-community-2x-arc-pro-b60](../bench/results/2026-10-04-community-2x-arc-pro-b60/README.md) | | Community | one Arc Pro B60 24 GB | Coder IQ1_M with 4,042 of 12,288 experts mirrored in RAM: 11.9 tok/s decode (needs the ring-wait fix from the same report) | same | | Strata maintainers | no Arc | compile check and kernel tests on a CPU device only (below) | this release | +| Strata maintainers (0.1.41 work) | Arc Pro B70 32 GB (xe) and Arc A750 8 GB (i915), test machines | Flash-Next IQ3_S on the B70 with 11.5k of 24.6k experts resident: 10-prompt gate passes, prompt 980-1,000 tok/s on 4K tokens, decode 30 (prose) to 41 (code) tok/s; the xe aliased-pages fix and the `NO_HOST` requirement are in [INTEL.md](INTEL.md) | INTEL.md, "Arc Pro B70 with a model that does not fit" | The 0.1.39 port re-migrates 0.1.38's port onto the 0.1.39 engine sources (the #606 NaN fix, the #649 verify trace, the new prompt paths). 0.1.39's `sycl/` did not compile against 0.1.39's own engine sources (#784: the diff --git a/sycl/include/strata/sycl_math.hpp b/sycl/include/strata/sycl_math.hpp index 58ccd2ca..38e4170d 100644 --- a/sycl/include/strata/sycl_math.hpp +++ b/sycl/include/strata/sycl_math.hpp @@ -13,3 +13,15 @@ inline int32_t dp4a(A a, B b, C c) { return dpct::dp4a((int32_t) a, (int32_t) b, (int32_t) c); } } // namespace strata + +namespace strata { +// The accumulator of the sampler's top_p / temperature tail (exp, sum, cumulative scan over the <= 64 kept logits). FP64 is +// emulated on an Arc Alchemist (an A750: the tail of one row costs ~450 us against 20 us in float, which made sampled +// decode ~40% slower than greedy) and is not hardware on any Arc. Float is the default; -DSTRATA_SYCL_SAMPLER_FP64=1 +// keeps the reference's double. +#if defined(STRATA_SYCL_SAMPLER_FP64) && STRATA_SYCL_SAMPLER_FP64 +using samp_acc_t = double; +#else +using samp_acc_t = float; +#endif +} // namespace strata diff --git a/sycl/probe/fp64_cost.cpp b/sycl/probe/fp64_cost.cpp new file mode 100644 index 00000000..96f43fe5 --- /dev/null +++ b/sycl/probe/fp64_cost.cpp @@ -0,0 +1,105 @@ +// fp64_cost: what does FP64 (emulated on Arc Alchemist and Battlemage) cost in the engine's small reduction kernels? +// Same one-warp-per-row sum of squares + 1/sqrt as gdn_l2_norm / gdn_out_norm / the PLE rms norm, once with a double +// accumulator (the engine today) and once in float, plus a silu over n values the way silu_inplace does it. +// fp64_cost [launches=4000] (the A750 needs IGC_EnableDPEmulation=1 OverrideDefaultFP64Settings=1 for the double kernels) +#include +#include +#include +#include +#include +#include + +template +static double us_per_launch(sycl::queue& q, int n, F&& f) { + for (int i = 0; i < 50; ++i) f(); + q.wait(); + const auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < n; ++i) f(); + q.wait(); + return std::chrono::duration(std::chrono::steady_clock::now() - t0).count() / n; +} + +template +static void l2norm(sycl::queue& q, float* x, int rows, int cols, float eps) { + q.parallel_for(sycl::nd_range<1>(rows * 32, 32), [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(32)]] { + const int row = it.get_group(0); + float* p = x + (size_t) row * cols; + auto sg = it.get_sub_group(); + Acc acc = 0; + for (int i = it.get_local_id(0); i < cols; i += 32) acc += (Acc) p[i] * (Acc) p[i]; + for (int off = 16; off > 0; off >>= 1) acc += sycl::shift_group_left(sg, acc, off); + acc = sycl::group_broadcast(sg, acc, 0); + const float inv = (float) ((Acc) 1 / sycl::sqrt(acc + (Acc) eps)); + for (int i = it.get_local_id(0); i < cols; i += 32) p[i] *= inv; + }); +} + +template +static void silu(sycl::queue& q, float* x, int n) { + q.parallel_for(sycl::nd_range<1>((n + 255) / 256 * 256, 256), [=](sycl::nd_item<1> it) { + const int i = it.get_global_id(0); + if (i >= n) return; + const Acc v = (Acc) x[i]; + x[i] = (float) (v / ((Acc) 1 + sycl::exp(-v))); + }); +} + + +// the sampler's tail: top_p cut and temperature draw over k kept logits, one warp (like sampled_tail_warp), 3 exps per element +template +static void sampler_tail(sycl::queue& q, const float* sel, int* out, int k, float top_p, float u) { + q.parallel_for(sycl::nd_range<1>(32, 32), [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(32)]] { + const int lane = it.get_local_id(0); + Acc sum = 0; + float mx = sel[0]; + for (int i = lane; i < k; i += 32) sum += sycl::exp((Acc) sel[i] - (Acc) mx); + sum = sycl::reduce_over_group(it.get_sub_group(), sum, sycl::plus()); + Acc cum = 0; + int cut = k; + if (lane == 0) { + for (int i = 0; i < k; ++i) { cum += sycl::exp((Acc) sel[i] - (Acc) mx) / sum; if (cum >= (Acc) top_p) { cut = i + 1; break; } } + Acc c2 = 0; int pick = cut - 1; + for (int i = 0; i < cut; ++i) { c2 += sycl::exp((Acc) sel[i] - (Acc) mx) / sum; if ((Acc) u < c2) { pick = i; break; } } + out[0] = pick; + } + }); +} + +int main(int argc, char** argv) { + const int n = argc > 1 ? std::atoi(argv[1]) : 4000; + sycl::queue q{sycl::gpu_selector_v, sycl::property::queue::in_order{}}; + std::printf("device %s, fp64 %s\n", q.get_device().get_info().c_str(), + q.get_device().has(sycl::aspect::fp64) ? "yes" : "NO (double kernels skipped)"); + const bool fp64 = q.get_device().has(sycl::aspect::fp64); + float* x = sycl::malloc_device(1 << 20, q); + q.fill(x, 0.5f, 1 << 20).wait(); + struct Shape { const char* what; int rows, cols; }; + const Shape shapes[] = {{"gdn l2 norm (rows 48, cols 128)", 48, 128}, {"gdn out norm (rows 48, cols 128)", 48, 128}, + {"ple rms (rows 8, cols 2560)", 8, 2560}, {"wide (rows 6, cols 2560)", 6, 2560}}; + for (const Shape& s : shapes) { + const double f = us_per_launch(q, n, [&] { l2norm(q, x, s.rows, s.cols, 1e-6f); }); + double d = -1; + if (fp64) d = us_per_launch(q, n, [&] { l2norm(q, x, s.rows, s.cols, 1e-6f); }); + std::printf("%-34s float %6.2f us double %6.2f us\n", s.what, f, d); + } + for (int cnt : {2560, 10240, 61440}) { + const double f = us_per_launch(q, n, [&] { silu(q, x, cnt); }); + double d = -1; + if (fp64) d = us_per_launch(q, n, [&] { silu(q, x, cnt); }); + std::printf("silu over %-24d float %6.2f us double %6.2f us\n", cnt, f, d); + } + { + float* sel = sycl::malloc_device(64, q); + int* o = sycl::malloc_device(1, q); + std::vector h(64); + for (int i = 0; i < 64; ++i) h[i] = 10.f - 0.3f * i; + q.memcpy(sel, h.data(), 64 * 4).wait(); + for (int k : {20, 64}) { + const double f = us_per_launch(q, n, [&] { sampler_tail(q, sel, o, k, 0.95f, 0.5f); }); + double d = -1; + if (fp64) d = us_per_launch(q, n, [&] { sampler_tail(q, sel, o, k, 0.95f, 0.5f); }); + std::printf("sampler tail, k=%-21d float %6.2f us double %6.2f us\n", k, f, d); + } + } + return 0; +} diff --git a/sycl/probe/gemm_launch.cpp b/sycl/probe/gemm_launch.cpp index 88af0dce..4879b30d 100644 --- a/sycl/probe/gemm_launch.cpp +++ b/sycl/probe/gemm_launch.cpp @@ -4,6 +4,8 @@ // gemm_launch [calls=2000] #include #include +#include +#include #include #include #include @@ -36,8 +38,22 @@ int main(int argc, char** argv) { const auto t0 = std::chrono::steady_clock::now(); run(calls); const double us = std::chrono::duration(std::chrono::steady_clock::now() - t0).count() / calls; - const double gflop = 2.0 * (double) s.n * (double) T * (double) s.k * 1e-9; - std::printf("%-20s T=%5lld: %7.1f us/call (%6.1f TFLOP/s)\n", s.name, (long long) T, us, gflop / us * 1e-3 * 1e3 / 1e3); + auto* h = new dpct::blas::descriptor(); + h->set_queue(&q); + const float alpha = 1.0f, beta = 0.0f; + auto run2 = [&](int cnt) { + for (int i = 0; i < cnt; ++i) + dpct::blas::gemm(h, oneapi::mkl::transpose::trans, oneapi::mkl::transpose::nontrans, (int) s.n, (int) T, (int) s.k, &alpha, W, + dpct::library_data_t::real_half, (int) s.k, X, dpct::library_data_t::real_half, (int) s.k, &beta, Y, + dpct::library_data_t::real_float, (int) s.n, dpct::compute_type::f32); + q.wait(); + }; + run2(50); + const auto t1 = std::chrono::steady_clock::now(); + run2(calls); + const double us2 = std::chrono::duration(std::chrono::steady_clock::now() - t1).count() / calls; + delete h; + std::printf("%-20s T=%5lld: mkl %7.1f us/call dpct::blas::gemm %7.1f us/call\n", s.name, (long long) T, us, us2); } } return 0; diff --git a/sycl/probe/gemm_vary.cpp b/sycl/probe/gemm_vary.cpp new file mode 100644 index 00000000..ab647a76 --- /dev/null +++ b/sycl/probe/gemm_vary.cpp @@ -0,0 +1,47 @@ +// gemm_vary: the expert GEMMs of a prompt see a different row count every call. Does oneMKL pay per distinct M (kernel +// generation / lookup), and how much do rows that are not a multiple of 8, 16 or 32 cost? +// gemm_vary [calls=3000] +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char** argv) { + const int calls = argc > 1 ? std::atoi(argv[1]) : 3000; + sycl::queue q{sycl::gpu_selector_v, sycl::property::queue::in_order{}}; + using half = sycl::half; + const int64_t N = 2560, maxT = 1536; + half* X = sycl::malloc_device(maxT * N, q); + half* W = sycl::malloc_device(N * 1280, q); + float* Y = sycl::malloc_device(maxT * N, q); + q.memset(X, 0, maxT * N * 2); q.memset(W, 0, N * 1280 * 2); q.wait(); + struct Shape { const char* name; int64_t n, k; }; + const Shape shapes[] = {{"gate/up", 1280, N}, {"down", N, 640}}; + std::mt19937 rng(7); + std::vector ts(calls); + // skewed like a prompt's per-expert row counts: many small, a few large + for (int& t : ts) { const double u = std::generate_canonical(rng); t = 1 + (int) (400.0 * u * u * u * u * 3.8); if (t > 1500) t = 1500; } + double mean_t = 0; for (int t : ts) mean_t += t; mean_t /= calls; + std::printf("rows per call: mean %.0f\n", mean_t); + for (const Shape& s : shapes) { + auto pass = [&](bool round8) { + const auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < calls; ++i) { + int64_t T = ts[i]; + if (round8) T = (T + 15) / 16 * 16; + oneapi::mkl::blas::column_major::gemm(q, oneapi::mkl::transpose::trans, oneapi::mkl::transpose::nontrans, s.n, T, s.k, 1.0f, W, s.k, X, s.k, + 0.0f, Y, s.n); + } + q.wait(); + return std::chrono::duration(std::chrono::steady_clock::now() - t0).count() / calls; + }; + const double first = pass(false); + const double second = pass(false); + const double rounded = pass(true); + std::printf("%-8s first pass %7.1f us/call, second %7.1f, rows rounded up to 16: %7.1f\n", s.name, first, second, rounded); + } + return 0; +} diff --git a/sycl/src/kernels/cuda/sampler.dp.cpp b/sycl/src/kernels/cuda/sampler.dp.cpp index 6c86dfae..e9206fdb 100644 --- a/sycl/src/kernels/cuda/sampler.dp.cpp +++ b/sycl/src/kernels/cuda/sampler.dp.cpp @@ -23,6 +23,7 @@ #include #include #include "strata/sycl_queue.hpp" +#include "strata/sycl_math.hpp" #include "strata/kernels/sampler.hpp" #include "strata/core/coupled_draft.hpp" #include "strata/core/emulate.hpp" @@ -583,16 +584,16 @@ __dpct_inline__ void sampler_kernel(const float *__restrict__ logits, #pragma unroll for (int i = 1; i < k; ++i) mx = sycl::fmax(mx, sel_logit[i]); if (p.top_p < 1.0f) { - double sum = 0.0; + strata::samp_acc_t sum = 0.0; #pragma unroll for (int i = 0; i < k; ++i) sum += - sycl::exp((double)sel_logit[i] - (double)mx); - double cum = 0.0; + sycl::exp((strata::samp_acc_t)sel_logit[i] - (strata::samp_acc_t)mx); + strata::samp_acc_t cum = 0.0; int cut = k; #pragma unroll for (int i = 0; i < k; ++i) { - cum += sycl::exp((double)sel_logit[i] - (double)mx) / sum; - if (cum >= (double) p.top_p) { cut = i + 1; break; } + cum += sycl::exp((strata::samp_acc_t)sel_logit[i] - (strata::samp_acc_t)mx) / sum; + if (cum >= (strata::samp_acc_t) p.top_p) { cut = i + 1; break; } } if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k; n_keep = cut; @@ -613,17 +614,17 @@ __dpct_inline__ void sampler_kernel(const float *__restrict__ logits, float smx = scaled(0); #pragma unroll for (int i = 1; i < n_keep; ++i) smx = sycl::fmax(smx, scaled(i)); - double sum = 0.0; + strata::samp_acc_t sum = 0.0; #pragma unroll for (int i = 0; i < n_keep; ++i) sum += - sycl::exp((double)scaled(i) - (double)smx); + sycl::exp((strata::samp_acc_t)scaled(i) - (strata::samp_acc_t)smx); const float u = philox_uniform(p.seed, p.counter + (uint64_t) t); - double cum = 0.0; + strata::samp_acc_t cum = 0.0; int pick = sel_ids[n_keep - 1]; #pragma unroll for (int i = 0; i < n_keep; ++i) { - cum += sycl::exp((double)scaled(i) - (double)smx) / sum; - if ((double) u < cum) { pick = sel_ids[i]; break; } + cum += sycl::exp((strata::samp_acc_t)scaled(i) - (strata::samp_acc_t)smx) / sum; + if ((strata::samp_acc_t) u < cum) { pick = sel_ids[i]; break; } } if (item_ct1.get_local_id(2) == 0) out[t] = pick; } @@ -689,7 +690,7 @@ __dpct_inline__ void warp_first(float &bv, int &bi) { template inline void sampled_tail_warp(const int *sel_ids, const float *sel_logit, int k, const SamplerParams &p, int t, - int *__restrict__ out, double *ex, + int *__restrict__ out, strata::samp_acc_t *ex, float *prob_out = nullptr) { const int lane = (int)(sycl::ext::oneapi::this_work_item::get_nd_item<3>().get_local_id( @@ -703,9 +704,9 @@ inline void sampled_tail_warp(const int *sel_ids, const float *sel_logit, int k, if (p.top_p < 1.0f) { #pragma unroll for (int i = lane; i < k; i += 32) - ex[i] = sycl::exp((double)sel_logit[i] - (double)mx); + ex[i] = sycl::exp((strata::samp_acc_t)sel_logit[i] - (strata::samp_acc_t)mx); sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group()); - double sum = 0.0; + strata::samp_acc_t sum = 0.0; if (lane == 0) #pragma unroll for (int i = 0; i < k; ++i) sum += ex[i]; @@ -725,11 +726,11 @@ inline void sampled_tail_warp(const int *sel_ids, const float *sel_logit, int k, sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group()); int cut = k; if (lane == 0) { - double cum = 0.0; + strata::samp_acc_t cum = 0.0; #pragma unroll for (int i = 0; i < k; ++i) { cum += ex[i]; - if (cum >= (double) p.top_p) { cut = i + 1; break; } + if (cum >= (strata::samp_acc_t) p.top_p) { cut = i + 1; break; } } } /* @@ -759,9 +760,9 @@ inline void sampled_tail_warp(const int *sel_ids, const float *sel_logit, int k, smx = sycl::fmax(smx, sel_logit[i] * inv_t); #pragma unroll for (int i = lane; i < n_keep; i += 32) - ex[i] = sycl::exp((double)(sel_logit[i] * inv_t) - (double)smx); + ex[i] = sycl::exp((strata::samp_acc_t)(sel_logit[i] * inv_t) - (strata::samp_acc_t)smx); sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group()); - double sum = 0.0; + strata::samp_acc_t sum = 0.0; if (lane == 0) #pragma unroll for (int i = 0; i < n_keep; ++i) sum += ex[i]; @@ -778,13 +779,13 @@ inline void sampled_tail_warp(const int *sel_ids, const float *sel_logit, int k, sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group()); if (lane == 0) { const float u = philox_uniform(p.seed, p.counter + (uint64_t) t); - double cum = 0.0; + strata::samp_acc_t cum = 0.0; int pi = n_keep > 0 ? n_keep - 1 : 0; int pick = sel_ids[pi]; #pragma unroll for (int i = 0; i < n_keep; ++i) { cum += ex[i]; - if ((double) u < cum) { pick = sel_ids[i]; pi = i; break; } + if ((strata::samp_acc_t) u < cum) { pick = sel_ids[i]; pi = i; break; } } out[t] = pick; if constexpr (kProb) *prob_out = n_keep > 0 ? (float) ex[pi] : 1.0f; @@ -859,7 +860,7 @@ sampler_one_block_kernel(const float *__restrict__ logits, int n_vocab, *sycl::ext::oneapi::group_local_memory_for_overwrite( sycl::ext::oneapi::this_work_item::get_work_group<3>()); auto &ex = - *sycl::ext::oneapi::group_local_memory_for_overwrite( + *sycl::ext::oneapi::group_local_memory_for_overwrite( sycl::ext::oneapi::this_work_item::get_work_group<3>()); auto &sv = *sycl::ext::oneapi::group_local_memory_for_overwrite( sycl::ext::oneapi::this_work_item::get_work_group<3>()); @@ -1146,7 +1147,7 @@ sampler_split_merge_kernel(const sycl::int2 *__restrict__ cand, int n_blocks, *sycl::ext::oneapi::group_local_memory_for_overwrite( sycl::ext::oneapi::this_work_item::get_work_group<3>()); auto &ex = - *sycl::ext::oneapi::group_local_memory_for_overwrite( + *sycl::ext::oneapi::group_local_memory_for_overwrite( sycl::ext::oneapi::this_work_item::get_work_group<3>()); const sycl::int2 *src = cand + (size_t)t * n_blocks * k; #pragma unroll @@ -1247,7 +1248,7 @@ __dpct_inline__ void coupled_merge_kernel( *sycl::ext::oneapi::group_local_memory_for_overwrite( sycl::ext::oneapi::this_work_item::get_work_group<3>()); auto &ex = - *sycl::ext::oneapi::group_local_memory_for_overwrite( + *sycl::ext::oneapi::group_local_memory_for_overwrite( sycl::ext::oneapi::this_work_item::get_work_group<3>()); auto &pick = *sycl::ext::oneapi::group_local_memory_for_overwrite( sycl::ext::oneapi::this_work_item::get_work_group<3>());