diff --git a/docs/INTEL.md b/docs/INTEL.md index af31ac19..2edfaf8e 100644 --- a/docs/INTEL.md +++ b/docs/INTEL.md @@ -715,6 +715,15 @@ Measured on an Arc A750 (8 GB, `i915`, PCIe 4.0) with the Flash-Next IQ3_XXS in `STRATA_SYCL_SPIN_MAX` (CMake; `SPIN_MAX=` for `sycl/tools/build.sh`): 2,000,000 reads (a few seconds) unless the build is an AOT build for a `bmg` card, which keeps 20,000. Before the change 11 of 16 runs of the engine (three requests each, a 26-token prompt) died or gave token 0 in the first request; with 2,000,000 reads 4 of 4 were right in all three requests. +- **Kernels misread memory more than 4 GiB into an allocation (fixed in the build).** On an Arc A770 (16 GB, `xe`, Coder + IQ1_M, `--stream-experts`, a 4.46 GiB expert cache) every prompt answered `!!!!` (token 0): the experts in the cache's + last 0.46 GiB dequantized to NaN in the prompt path. A copy of those slots read back equal to the GGUF + (`STRATA_VERIFY_ALL_SLOTS` passed) and a fresh device copy of the same bytes dequantized clean; only a kernel reading + the slot in place got wrong bytes. In a JIT build IGC addresses a kernel's pointer arguments as a 32-bit offset from + the allocation's base. The JIT build now passes `-ze-opt-greater-than-4GB-buffer-required` (`sycl/CMakeLists.txt`), + which keeps the kernels on 64-bit addresses. After the change, prompts of 73 to 542 tokens had 0 non-finite values + (`STRATA_DBG_NAN=1`) and the 542-token prompt answered right. The speed cost is not measured. The AOT (`bmg-*`) build is + unchanged. oneMKL's own precompiled kernels do not get the option; the GEMM stages an operand past 4 GiB for that. - **Speed.** About 10 to 15 tok/s decode (76 to 92% of the drafts accepted), a 26-token first prompt in 13 s and later short prompts in 0.2 to 1.3 s; the A750's PCIe link probes at 10.6 GB/s. - **A750 and the xe error counters.** The engine segfaults in a worker thread of the CPU pool when it exits (dmesg only, the server diff --git a/include/strata/kernels/elementwise.hpp b/include/strata/kernels/elementwise.hpp index 39a2560a..7c92dcb4 100644 --- a/include/strata/kernels/elementwise.hpp +++ b/include/strata/kernels/elementwise.hpp @@ -121,6 +121,21 @@ void doorbell_publish_value(const float* x, const int32_t* ids, const float* wei void doorbell_publish_res(const float* x, const int32_t* ids, const int32_t* d_res, int n_expert, int64_t n, int64_t k, float* x_out, int32_t* ids_out, uint32_t* d_seq, void* stream); +/// The ring can reach the host before its payload on some GPUs: the payload stores and the ring store are not ordered +/// by the fences alone (measured on an Arc A770: 14 of 2,832 rings in one run were stale, and the CPU pool then +/// computed on a partly stale payload). So the publish kernels also write, next to the sequence number, the ring it +/// belongs to and a checksum of the payload (the wrapping sum of every 32-bit word mixed with its position, murmur3's +/// finalizer - a plain sum missed a reordering, [3,7] -> [7,3], of the expert ids) in a per-ring slot modulo 4: +/// seq[1 + 2 (r % 4)] is the tag, seq[2 + 2 (r % 4)] the checksum (a split verify publishes two rings before the host +/// reads the first). The sequence word therefore needs 9 words of mapped host memory. The two publish shapes +/// differ (doorbell_publish / doorbell_publish_value publish the routing weights, doorbell_publish_res does not), +/// so the wait accepts either. CUDA/HIP: always true (their ordering holds), so callers may skip the wait there. +bool doorbell_payload_ready(const uint32_t* h_seq, const float* h_x, int64_t n, const int32_t* h_ids, + const float* h_weights, int64_t k, uint32_t want); +/// Spins on doorbell_payload_ready for up to `timeout_ms`; false on timeout. +bool doorbell_wait_payload(const uint32_t* h_seq, const float* h_x, int64_t n, const int32_t* h_ids, + const float* h_weights, int64_t k, uint32_t want, int timeout_ms = 2000); + /// Plan v0.3 P3: copy `n` int32 from mapped pinned host memory into device memory with a kernel (the QSA /// per-token step and positions), instead of a host-to-device memcpy node in the middle of a layer. void copy_i32_from_mapped(int32_t* dst, const int32_t* src, int64_t n, void* stream); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index dc8c5d3c..f99b3a26 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -380,6 +380,7 @@ struct Options { std::string embd_gguf; /// Plan v0.3 P2: how the n-gram table is read. Direct (default) = unbuffered SSD reads, table never in RAM. std::string ple_io = "direct"; + bool ple_io_explicit = false; ///< --ple-io was given: the engine only warns when direct measures slow int64_t ple_row_cache = 1 << 20; ///< bounded row cache (rows of 90 B); 0 disables int ple_inflight = 256; // the prompt path reads a chunk's rows at once: 64 left the SSD half idle (32K: 303 -> 189 ms) double ple_delay_us = 0; ///< fault injection: every row read completes no earlier than this @@ -1602,6 +1603,31 @@ double pcie_frac_for_gbps(double gbps, double base) { } // namespace +// #1425 #1549 #1629: --ple-io direct (the default) does unbuffered random reads of the n-gram table; on some drives +// (DRAM-less NVMe, Windows unbuffered I/O) they run at 34 MB/s or 4-8 tok/s and a prompt reads layer 1 for minutes. +// Rows per second of a short cold probe: a few batches of random rows through the same batched reader a prompt chunk +// uses, stopped after ~0.6 s. Returns <= 0 when nothing could be measured. +static double ple_direct_rows_per_s(strata::kernels::PleTable& t) { + const uint64_t n = t.rows(); + if (n < 4096) return -1.0; + constexpr size_t kTok = 4; // 64 rows a batch + std::vector rows(kTok * 16); + std::vector out(kTok * 2560); + uint64_t x = 0x9E3779B97F4A7C15ull ^ n; + const auto t0 = std::chrono::steady_clock::now(); + uint64_t done = 0; + double el = 0; + for (int b = 0; b < 64; ++b) { + for (auto& r : rows) { x ^= x << 13; x ^= x >> 7; x ^= x << 17; r = (uint32_t) (x % n); } + std::string e; + if (!t.gather_batch(rows.data(), kTok, out.data(), e)) return -1.0; + done += rows.size(); + el = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + if (el > 0.6) break; + } + return el > 0 ? (double) done / el : -1.0; +} + int main(int argc, char** argv) { // **UNBUFFERED, BECAUSE THE INTERESTING OUTPUT IS THE OUTPUT BEFORE A CRASH.** `stdout` redirected to a // pipe or a file is block-buffered, so a program that dies loses every line it had already printed - which @@ -1722,7 +1748,7 @@ int main(int argc, char** argv) { else if (a == "--dump-routing") o.dump_routing = next("--dump-routing"); else if (a == "--ple-gguf") o.ple_gguf = next("--ple-gguf"); else if (a == "--no-ple") o.no_ple = true; - else if (a == "--ple-io") o.ple_io = next("--ple-io"); + else if (a == "--ple-io") { o.ple_io = next("--ple-io"); o.ple_io_explicit = true; } else if (a == "--ple-row-cache") o.ple_row_cache = std::atoll(next("--ple-row-cache")); else if (a == "--ple-inflight") o.ple_inflight = std::atoi(next("--ple-inflight")); else if (a == "--ple-delay-us") o.ple_delay_us = std::atof(next("--ple-delay-us")); @@ -2979,6 +3005,34 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } + // Recommend, never force: when the default direct reads measure slow, switch to the mapped reads (40-100x + // faster on the reporters' drives); an explicit --ple-io direct is kept and only warned about. + if (pio.mode == strata::kernels::PleIo::Direct && std::getenv("STRATA_PLE_PROBE") == nullptr) { + constexpr double kSlowRowsPerS = 15000.0; // ~60 MB/s of 4 KiB pages; a healthy NVMe is >100k + const double rps = ple_direct_rows_per_s(ple_table); + if (rps >= kSlowRowsPerS) + std::fprintf(stderr, "strata generate: PLE direct read probe: %.0f rows/s (fine)\n", rps); + if (rps > 0 && rps < kSlowRowsPerS) { + if (!o.ple_io_explicit) { + std::fprintf(stderr, "strata generate: --ple-io direct measures slow here (%.0f rows/s, about %.0f MB/s of " + "random 4 KiB reads): using --ple-io mmap instead (the OS file cache holds the pages; " + "--ple-io direct forces the old mode, --ple-io ram keeps the table in RAM)\n", + rps, rps * 4096.0 / 1e6); + ple_table.close(); + pio.mode = strata::kernels::PleIo::Mmap; + pio.keepalive_ms = 0; + if (!ple_table.open(o.ple_gguf, err, pio)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + } else { + std::fprintf(stderr, "strata generate: WARNING: --ple-io direct measures slow here (%.0f rows/s, about %.0f " + "MB/s of random 4 KiB reads): a prompt can spend minutes reading layer 1 and trip the " + "stall watchdog (#1425, #1629). --ple-io mmap was 40-100x faster on such drives; " + "--ple-io ram needs the RAM for the table\n", rps, rps * 4096.0 / 1e6); + } + } + } #if !defined(_WIN32) if (pio.mode == strata::kernels::PleIo::Direct) { // #605: --ple-io direct's random reads (up to --ple-inflight at once) are for SSDs; a rotational disk diff --git a/sycl/CMakeLists.txt b/sycl/CMakeLists.txt index dd199062..44fa4924 100644 --- a/sycl/CMakeLists.txt +++ b/sycl/CMakeLists.txt @@ -51,7 +51,19 @@ endif() # SYCL_PROGRAM_COMPILE_OPTIONS=-cl-fp32-correctly-rounded-divide-sqrt at run time.) The AOT build passes it to # ocloc above; without that the 303k mismatches came back on 2026-09-30, unnoticed since the AOT switch. if(NOT STRATA_SYCL_AOT) - list(APPEND _sycl_link "-Xsycl-target-backend=spir64" "-cl-fp32-correctly-rounded-divide-sqrt") + # The JIT build is the Alchemist (Arc A-series) build. There IGC turns a kernel's pointer arguments into surface + # accesses with a 32-bit offset from the allocation's base, so a kernel misreads bytes more than 4 GiB into an + # allocation while copies of the same bytes are right. Measured on an Arc A770 (Coder IQ1_M, 4.46 GiB expert cache): + # every expert in the cache's last 0.46 GiB dequantized to NaN in the prompt path, and every prompt answered "!!!!" + # (token 0). This option keeps the kernels on 64-bit (stateless) addresses; with it the same prompts are right. + # (One backend argument for both: CMake drops a repeated -Xsycl-target-backend=spir64.) + option(STRATA_SYCL_JIT_STATELESS "JIT build: keep kernels on 64-bit addresses (-ze-opt-greater-than-4GB-buffer-required)" ON) + if(STRATA_SYCL_JIT_STATELESS) + list(APPEND _sycl_link "-Xsycl-target-backend=spir64" + "-cl-fp32-correctly-rounded-divide-sqrt -ze-opt-greater-than-4GB-buffer-required") + else() + list(APPEND _sycl_link "-Xsycl-target-backend=spir64" "-cl-fp32-correctly-rounded-divide-sqrt") + endif() endif() # Every translation unit gets -fsycl: the migrated host files construct queues and USM, not only the kernels. # icpx defaults to a fast floating-point model (reciprocal approximations, reassociation); the kernels are diff --git a/sycl/include/strata/core/gguf_expert_source.hpp b/sycl/include/strata/core/gguf_expert_source.hpp index 678a754e..2fac7eb7 100644 --- a/sycl/include/strata/core/gguf_expert_source.hpp +++ b/sycl/include/strata/core/gguf_expert_source.hpp @@ -9,7 +9,9 @@ // // It is slow per blob (three reads, ~2.7 MB) and that is fine: the profile fill reads each expert once at start, // the prefill's lent slots are refilled a few hundred at a time, and with every expert resident the pool never -// asks. `pinned()` is false and `device_alias()` null, so nothing tries to DMA from it. +// asks. Before the mirror is built `pinned()` is false and `device_alias()` null, so nothing tries to DMA from it; +// `mirror()` (below) then makes the experts it holds `pinned()` with a device-readable `device_alias()`, built from +// several chunks because an Arc A-series card refuses a single USM host allocation past ~3 GiB. #pragma once #include "strata/core/expert_source.hpp" @@ -69,10 +71,11 @@ private: std::mutex mu_; int64_t n_layers_ = 0, n_expert_ = 0; int64_t reads_ = 0; - uint8_t* mirror_ = nullptr; ///< USM host (pinned, device-readable) + std::vector mirror_chunks_; ///< USM host (pinned, device-readable); several chunks: Alchemist + ///< (Arc A-series) refuses a single host allocation past ~3 GiB uint64_t mirror_bytes_ = 0; - std::vector mirror_off_; ///< per (layer, expert): offset in mirror_, -1 = not mirrored - std::vector layer_first_; ///< per layer: offset of its first mirrored blob, -1 = none + std::vector mirror_ptr_; ///< per (layer, expert): its blob in the chunks, null = not mirrored + std::vector layer_first_; ///< per layer: its first mirrored blob, null = none }; } // namespace strata::core diff --git a/sycl/include/strata/core/verify.hpp b/sycl/include/strata/core/verify.hpp index 2501122d..7d6de96a 100644 --- a/sycl/include/strata/core/verify.hpp +++ b/sycl/include/strata/core/verify.hpp @@ -303,9 +303,9 @@ private: void collect_profile(); ///< STRATA_VERIFY_PROFILE: add the last window's stamps to prof_sum_ void accumulate_profile(const unsigned long long* stamps); ///< one window's stamps (host copy) into prof_sum_ // pipelined windows (pl_launch ...) - dpct::queue_ptr ext_stream_ = - &dpct::get_in_order_queue(); ///< set_stream: the stage's shared stream - ///< (not destroyed here) + dpct::queue_ptr ext_stream_ = nullptr; ///< set_stream: the stage's shared stream (not destroyed here); + ///< nullptr = none until set_stream() (#1555: a queue pointer captured + ///< at construction would be the *constructing* device's) bool always_publish_ = false; void pl_stage(int T, const int32_t* tokens, int64_t pos0, const int32_t ple_prev[2]); dpct::event_ptr ev_done_ = nullptr, ev_commit_ = nullptr; diff --git a/sycl/include/strata/sycl_doorbell.hpp b/sycl/include/strata/sycl_doorbell.hpp index 3ad9f1c8..ec93e210 100644 --- a/sycl/include/strata/sycl_doorbell.hpp +++ b/sycl/include/strata/sycl_doorbell.hpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -39,10 +40,53 @@ inline uint32_t sys_load(const volatile uint32_t* p) { return sys_atomic_u32(*const_cast(p)).load(); } #endif +// The store side of the handshake (device -> host) needs the same hint. A system-scope atomic store, even followed by +// a release fence, is served from the GPU's cache on an Arc (xe) and reaches the host only when the kernel ends +// (measured on an A770: 482 ms into a 482 ms kernel), so a host that polls the ring mid-window never sees it; that is +// why the decode window had to wait for the whole graph (STRATA_VERIFY_NO_HOST) and every expert had to be +// device-resident. The uncached L1+L3 write hint reaches memory at once (44 ms, the launch latency). +// -DSTRATA_DOORBELL_ATOMIC_STORE restores the atomic store. +#ifndef STRATA_DOORBELL_ATOMIC_STORE +using doorbell_uncached_write = decltype(sycl::ext::oneapi::experimental::properties( + sycl::ext::intel::experimental::write_hint>)); +inline void sys_store(volatile uint32_t* p, uint32_t v) { + sycl::ext::oneapi::experimental::annotated_ptr u(const_cast(p)); + u[0] = v; + // Ordering, not visibility: the value is already in memory. The release fence keeps a later payload store (the + // experts' ids the host reads after the ring) after the ring, the same contract the atomic store had. + sycl::atomic_fence(sycl::memory_order::release, sycl::memory_scope::system); +} +// The doorbell's PAYLOAD (activations, expert ids, routing weights) is the other half of the handshake: a plain store +// to host USM reaches the host only when the kernel ends on an Arc (xe), so the host would spin on the ring and then +// read a stale payload. Same uncached L1+L3 hint as sys_store, for float/int32. +template inline void sys_store_mapped(T* p, T v) { + sycl::ext::oneapi::experimental::annotated_ptr u(p); + u[0] = v; +} +#else inline void sys_store(volatile uint32_t* p, uint32_t v) { sys_atomic_u32(*const_cast(p)).store(v); sycl::atomic_fence(sycl::memory_order::release, sycl::memory_scope::system); } +template inline void sys_store_mapped(T* p, T v) { + sycl::atomic_ref(*p).store(v); +} +#endif +// plain = true: an ordinary store. On the i915 driver (Arc A750) a plain store to host USM reaches the host in time +// and the uncached hint only slows the publish (decode -11% on an A750, 4K prompt, 5 rounds); on xe it must be hinted. +// STRATA_DOORBELL_PLAIN=0/1 overrides. The launchers read this on the host and pass it to the kernel. +template inline void sys_store_mapped(bool plain, T* p, T v) { + if (plain) *p = v; else sys_store_mapped(p, v); +} +inline bool doorbell_plain_payload() { + static const bool v = [] { + if (const char* e = std::getenv("STRATA_DOORBELL_PLAIN")) return e[0] == '1'; + return intel_gpu_driver() == "i915"; + }(); + return v; +} // Every device spin is bounded. An unbounded spin that never sees its flag is not a hang of one process: the // xe driver times the queue out, resets the GT node by node (a window graph has 2,366 of them), and the card @@ -50,13 +94,20 @@ inline void sys_store(volatile uint32_t* p, uint32_t v) { // verifier's checks catch. ~2 M host-memory reads is a few seconds at PCIe latency. // The bound is per device, chosen at run time (spin_max below): 20,000 reads on a card under the xe driver (the B-series // on Linux), whose device-plan windows only spin in a failure and where a longer spin is what makes the driver reset the -// GT; 2,000,000 (a few seconds) elsewhere, Windows included (a JIT/OpenCL B-series build measured faster with the long -// bound, #1397). On an Arc A-series (i915) the CPU computes the experts the card does not hold and the GPU waits for it at +// GT; 2,000,000 (a few seconds) elsewhere. A B-series card with no sysfs driver (Windows / OpenCL) gets 20,000 too (#1473, +// measured +46-67% with --mtp), found from the device's architecture or name. On an Arc A-series (i915) the CPU computes the experts the card does not hold and the GPU waits for it at // every layer: 20,000 reads is a few tens of milliseconds, the first request after a start (cold pages, slow CPU // layers) is slower than that, the GPU gave up, went on with the experts' outputs missing, and the answer was token 0 // ("!!!!!") or the engine crashed in the CPU pool on the garbage routing it read next. // STRATA_SPIN_MAX= overrides both; a build's -DSTRATA_SYCL_SPIN_MAX= (CMake) fixes one bound for every // device. The device functions take the bound as an argument: the launchers pass spin_max(queue). +// Without a sysfs driver name (Windows, OpenCL) a B-series card is recognised from the device itself (intel_gpu_gen): +// its window waits are the xe kind (expected to expire, so 20,000 reads), EXCEPT in a run that drafts without the MTP +// layer (--spec N, no --mtp): the suffix drafter's own waits have to complete there, and 20,000 reads left it empty-handed +// (0 drafts, 21.8 vs 68.8 tok/s, #1473). generate calls spin_drafts_need_long_bound(true) for such a run, before any +// launch. A Linux xe card keeps 20,000 in every mode (unchanged). +inline std::atomic& spin_long_drafts_flag() { static std::atomic f{false}; return f; } +inline void spin_drafts_need_long_bound(bool on) { spin_long_drafts_flag() = on; } inline uint32_t spin_max(const sycl::queue& q) { static std::mutex mu; static std::unordered_map cache; @@ -69,7 +120,10 @@ inline uint32_t spin_max(const sycl::queue& q) { #ifdef STRATA_SYCL_SPIN_MAX else v = STRATA_SYCL_SPIN_MAX; #else - else v = intel_gpu_driver() == "xe" ? 20000u : 2000000u; + else if (intel_gpu_driver() == "xe") v = 20000u; + else if (intel_gpu_driver().empty() && intel_gpu_gen(d) == IntelGpuGen::Battlemage) + v = spin_long_drafts_flag().load() ? 2000000u : 20000u; + else v = 2000000u; #endif cache.emplace(d, v); return v; diff --git a/sycl/include/strata/sycl_queue.hpp b/sycl/include/strata/sycl_queue.hpp index 5728e826..3b92cace 100644 --- a/sycl/include/strata/sycl_queue.hpp +++ b/sycl/include/strata/sycl_queue.hpp @@ -116,6 +116,48 @@ inline const std::string& intel_gpu_driver() { } } // namespace strata +namespace strata { +// Which Intel GPU generation a SYCL device is, from the device itself (so it also works on Windows / OpenCL, where +// intel_gpu_driver() has no sysfs to read): the architecture enum when the runtime knows it, else the marketing name +// ("Intel(R) Arc(TM) Pro B70", "... A750 ..."). Battlemage = Arc B-series / Pro B-series (B570 B580 B50 B60 B65 B70). +enum class IntelGpuGen { Unknown, Alchemist, Battlemage }; +inline IntelGpuGen intel_gpu_gen(const sycl::device& d) { + if (!d.is_gpu()) return IntelGpuGen::Unknown; + try { + { + namespace exp = sycl::ext::oneapi::experimental; + const auto a = d.get_info(); + if (a == exp::architecture::intel_gpu_bmg_g21 || a == exp::architecture::intel_gpu_bmg_g31) + return IntelGpuGen::Battlemage; + if (a == exp::architecture::intel_gpu_acm_g10 || a == exp::architecture::intel_gpu_acm_g11 || + a == exp::architecture::intel_gpu_acm_g12) + return IntelGpuGen::Alchemist; + } + } catch (...) { + } + std::string n; + try { n = d.get_info(); } catch (...) { return IntelGpuGen::Unknown; } + if (n.find("Intel") == std::string::npos) return IntelGpuGen::Unknown; + // "Intel(R) Graphics [0xe223]": drivers that print the PCI id instead of a marketing name (the B70 on Linux) + if (const size_t b = n.find("[0x"); b != std::string::npos) { + const unsigned long id = std::strtoul(n.c_str() + b + 1, nullptr, 16); + if (id >= 0xE200 && id <= 0xE2FF) return IntelGpuGen::Battlemage; // BMG-G21 / G31 + if ((id >= 0x5690 && id <= 0x56BF) || id == 0x56C0 || id == 0x56C1) return IntelGpuGen::Alchemist; // DG2 + } + if (n.find("Battlemage") != std::string::npos) return IntelGpuGen::Battlemage; + if (n.find("Alchemist") != std::string::npos) return IntelGpuGen::Alchemist; + // "Arc(TM) Pro B70", "Arc(TM) B580", "Arc(TM) A750": a letter and 2-3 digits, as a whole word + for (size_t i = 0; i + 2 < n.size(); ++i) { + if ((i > 0 && n[i - 1] != ' ') || (n[i] != 'A' && n[i] != 'B')) continue; + size_t j = i + 1; + while (j < n.size() && n[j] >= '0' && n[j] <= '9') ++j; + if (j - i - 1 < 2 || j - i - 1 > 3 || (j < n.size() && n[j] != ' ' && n[j] != '(')) continue; + return n[i] == 'B' ? IntelGpuGen::Battlemage : IntelGpuGen::Alchemist; + } + return IntelGpuGen::Unknown; +} +} // 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 @@ -170,13 +212,56 @@ inline bool arena_alias_guard_enabled() { } // namespace strata #include +#include +#include namespace strata { +// Every big device allocation (base -> size), so device_offset_end can find the allocation that holds an address. The +// CPU expert pool's handshake and oneMKL's GEMM both care where, within its allocation, an operand lies. +inline std::map& device_alloc_map() { + static std::map m; + return m; +} +inline std::mutex& device_alloc_mutex() { + static std::mutex m; + return m; +} +inline void device_alloc_register(const void* p, size_t bytes) { + if (p == nullptr || bytes == 0) return; + std::lock_guard lk(device_alloc_mutex()); + device_alloc_map()[p] = bytes; +} +// Drop a base when its allocation is freed, so a later allocation that reuses the address is not mis-attributed by +// device_offset_end. +inline void device_alloc_unregister(const void* p) { + if (p == nullptr) return; + std::lock_guard lk(device_alloc_mutex()); + device_alloc_map().erase(p); +} +// How far into its device allocation the byte range [p, p + bytes) ends; 0 when p is not in one we know. oneMKL's GEMM +// reads the last, partial tile of an operand from the wrong place when it lies more than 4 GiB in (Arc A770, oneMKL +// 2026.1), so the GEMM stages any operand this reports > 4 GiB for. An operand in an allocation we did not register +// (small cudaMalloc'd buffers) is reported 0: those can never reach 4 GiB. +inline size_t device_offset_end(const void* p, size_t bytes) { + if (p == nullptr) return 0; + std::lock_guard lk(device_alloc_mutex()); + auto& m = device_alloc_map(); + auto it = m.upper_bound(p); + if (it == m.begin()) return 0; + --it; + const uint8_t* base = (const uint8_t*) it->first; + const uint8_t* end = (const uint8_t*) p + bytes; + if (end > base + it->second) return 0; + return (size_t) (end - base); +} // 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; + if (p == nullptr || bytes < ((size_t) 32 << 20) || !arena_alias_guard_enabled()) { + device_alloc_register(p, bytes); + return p; + } std::vector spacers; bool clean = false; for (int attempt = 0; attempt < 8 && p != nullptr; ++attempt) { @@ -199,6 +284,7 @@ inline void* malloc_device_guarded(size_t bytes, sycl::queue& q, const char* wha 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); + device_alloc_register(p, bytes); return p; } } // namespace strata diff --git a/sycl/probe/doorbell_store.cpp b/sycl/probe/doorbell_store.cpp new file mode 100644 index 00000000..433e74fa --- /dev/null +++ b/sycl/probe/doorbell_store.cpp @@ -0,0 +1,43 @@ +// doorbell_store: does the host see a device's store to host USM while the kernel is still running? This is the +// ring publish of Strata's decode handshake (the GPU rings a sequence number the host polls, and the host answers a +// flag the GPU spins on). A `volatile`/atomic store is served from the GPU's cache on an Arc (xe) and reaches the +// host only when the kernel ends; the uncached L1+L3 write hint (strata::sys_store, sycl_doorbell.hpp) reaches memory +// at once. Build twice and compare: +// icpx -fsycl -I sycl/include sycl/probe/doorbell_store.cpp -o /tmp/db # uncached write (the fix) +// icpx -fsycl -DSTRATA_DOORBELL_ATOMIC_STORE -I sycl/include ... -o /tmp/db_atomic # old atomic store +// On an Arc A770 (xe) the first prints "SAW ... at ~0.2 s" with the kernel running to ~2 s; the second prints +// "NEVER SAW" and the value appears only at the kernel's end. Exit 0 when the store was seen mid-kernel. +#include +#include +#include +#include "strata/sycl_doorbell.hpp" + +int main() { + sycl::queue q{sycl::gpu_selector_v}; + uint32_t* flag = (uint32_t*) sycl::malloc_host(sizeof(uint32_t), q); + *flag = 0; + const auto t0 = std::chrono::steady_clock::now(); + q.submit([&](sycl::handler& h) { + h.single_task([=]() { + for (volatile long i = 0; i < 1000000; i++) {} // ~0.2 s before the publish + strata::sys_store(flag, 12345u); + for (volatile long i = 0; i < 10000000; i++) {} // ~2 s more running after the publish + }); + }); + uint32_t v = 0; + double seen_ms = -1.0; + while (std::chrono::steady_clock::now() - t0 < std::chrono::seconds(6)) { + v = *flag; + if (v == 12345u) { seen_ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); break; } + } + q.wait(); + const double end_ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); +#ifdef STRATA_DOORBELL_ATOMIC_STORE + const char* label = "ATOMIC_STORE "; +#else + const char* label = "UNCACHED_WRITE"; +#endif + std::printf("%s: host %s flag=%u at %.1f ms; kernel ended at %.1f ms\n", label, + seen_ms >= 0 ? "SAW" : "NEVER SAW", v, seen_ms, end_ms); + return (seen_ms >= 0 && seen_ms < end_ms - 100.0) ? 0 : 3; // seen well before the kernel ended +} diff --git a/sycl/serve/strata-sycl.sh b/sycl/serve/strata-sycl.sh index 35d670af..f579e79c 100755 --- a/sycl/serve/strata-sycl.sh +++ b/sycl/serve/strata-sycl.sh @@ -35,6 +35,7 @@ for k in "${!setting[@]}"; do case "${setting[$k]}" in 0|"") ;; *) envs+=(-e "$k=${setting[$k]}") ;; esac done exec docker run --rm -i --name "$name" --device /dev/dri --oom-score-adj 1000 --stop-timeout 30 --no-healthcheck \ + --ulimit memlock=-1 \ -v "$root:/work" \ "${envs[@]}" \ "${STRATA_SYCL_IMAGE:-strata-sycl-dev}" \ diff --git a/sycl/setup_intel.py b/sycl/setup_intel.py index 86df7c67..05521ea4 100644 --- a/sycl/setup_intel.py +++ b/sycl/setup_intel.py @@ -47,6 +47,12 @@ INTEL_ARC = {"e223": ("Arc Pro B70", 32.0), "e221": ("Arc Pro B60", 24.0), "e211 "56a0": ("Arc A770", 16.0), "56a1": ("Arc A750", 8.0), "56a2": ("Arc A580", 8.0), "56a5": ("Arc A380", 6.0), "56a6": ("Arc A310", 4.0), "5690": ("Arc A770M", 16.0)} +# Alchemist (DG2, the A-series) has no FP64 hardware and carries the driver's FP64 emulation. On i915 (the A750) a +# single sycl::malloc_host past ~3 GiB also fails, so the experts load into a CPU-computed RAM arena instead of the +# pinned mirror (--mmap-experts + STRATA_VERIFY_NO_HOST=0 - docs/INTEL.md, "Arc A750"). On xe (the A770) the mirror is +# built in chunks past that limit and the A-series uses the ordinary streamed path; see to_sycl(). +ALCHEMIST_IDS = frozenset({"56a0", "56a1", "56a2", "56a5", "56a6", "5690"}) + def intel_gpus(): """Intel discrete GPUs from sysfs: vendor 0x8086 under the xe or i915 driver, named by PCI device id. VRAM comes @@ -75,7 +81,8 @@ def intel_gpus(): vram = (int(end, 16) - int(start, 16) + 1) / 2**30 except (OSError, IndexError, ValueError): vram = 0.0 - found.append({"index": len(found), "name": f"Intel {name}", "vram_gb": vram, "arch": driver, "driver": driver}) + found.append({"index": len(found), "name": f"Intel {name}", "vram_gb": vram, "arch": driver, "driver": driver, + "devid": devid}) return found @@ -124,15 +131,21 @@ def small_card(vram_gb: float, driver: str) -> bool: return 0 < vram_gb < SMALL_CARD_GB or driver == "i915" -def to_sycl(cfg: dict, exe: Path, ram: float, keep: dict, vram_gb: float = 0.0, driver: str = "xe") -> dict: +def to_sycl(cfg: dict, exe: Path, ram: float, keep: dict, vram_gb: float = 0.0, driver: str = "xe", + devid: str = "") -> dict: """setup's config (written for its HIP path) -> the SYCL port's: the container's paths, experts streamed from the GGUF into VRAM (--stream-experts: the engine reads them from the GGUF and keeps what does not fit in a pinned RAM mirror; 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 40+ tok/s with it, 4-9 without). - A reserve the user asked for (--vram-reserve-mib) is kept. An i915 card (Alchemist, the A-series) cannot do that: - a single pinned host allocation above a few GB fails there, so the mirror cannot hold what the card does not, and - the config loads the experts into a RAM arena instead (no --stream-experts, --ple-io ram, and the device-built - verify plan's NO_HOST switch off - docs/INTEL.md, "Arc A750").""" + A reserve the user asked for (--vram-reserve-mib) is kept. + + An Alchemist card (the A-series, i915 or xe) has no FP64 hardware, so its config carries the driver's FP64 + emulation (a kernel on the sampled path declares double). On i915 (the A750) the experts load into a RAM arena + and the CPU computes the ones the card does not hold (--ple-io ram, STRATA_VERIFY_NO_HOST=0 - docs/INTEL.md, + "Arc A750"). On xe (the A770) the experts are streamed into VRAM like any other Arc; the mirror is built in + chunks so DG2's >3 GiB single pinned-host allocation limit is not hit, and the build passes + -ze-opt-greater-than-4GB-buffer-required so the prompt path is correct past the cache's 4 GiB (docs/INTEL.md, + "Kernels misread memory more than 4 GiB into an allocation").""" args = list(cfg["args"]) for f in ("--resident-experts", "--mmap-experts"): # setup's low-RAM mode is the CUDA engine's drop(args, f) @@ -151,8 +164,10 @@ def to_sycl(cfg: dict, exe: Path, ram: float, keep: dict, vram_gb: float = 0.0, drop(args, "--vram-reserve-mib", True) reserve = asked_reserve or (str(SMALL_RESERVE_MIB) if small_card(vram_gb, driver) else "1024" if ctx <= 32768 else "2048") - host_arena = driver == "i915" - if host_arena: + alchemist = driver == "i915" or devid in ALCHEMIST_IDS + if driver == "i915": + # Arc A-series on i915 (the A750): the experts load into an ordinary RAM arena and the CPU computes the ones + # the card does not hold; the n-gram table is kept in RAM (setup's rotational-disk rule) and no mirror is built. if "--ple-io" not in args: args += ["--ple-io", "ram"] args += ["--vram-reserve-mib", reserve] @@ -166,8 +181,11 @@ def to_sycl(cfg: dict, exe: Path, ram: float, keep: dict, vram_gb: float = 0.0, 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 = {} - if host_arena: - env["STRATA_VERIFY_NO_HOST"] = "0" # strata-sycl.sh sets 1 unless told otherwise (xe, every expert in VRAM) + if alchemist: + if driver == "i915": + # on i915 the CPU computes the misses and the GPU waits for them at every layer (NO_HOST=0). On xe the + # experts are streamed and the mirror is used, so strata-sycl.sh's NO_HOST=1 default stands. + env["STRATA_VERIFY_NO_HOST"] = "0" # an Alchemist has no FP64 hardware: a kernel that declares double (one is on the sampled path) is refused at its # first launch - "'double' is not supported in ... device", the engine dies on the first request with a # temperature - unless the driver emulates it (docs/INTEL.md) @@ -208,22 +226,24 @@ def install(argv) -> None: say = S.say fake_ram = max(real_ram, 1024.0) + alch = intel[0]["driver"] == "i915" or intel[0].get("devid") in ALCHEMIST_IDS def say_intel(msg=""): """setup's words for its AMD path and its RAM rule, said for the Intel card.""" msg = str(msg).replace("(AMD, experimental: docs/AMD_HIP.md)", "(Intel Arc: the SYCL port, docs/INTEL.md)") msg = msg.replace("Your AMD GPUs:", "Your Intel GPUs:").replace("just run ./setup.sh", "just run ./setup.sh --backend sycl") msg = re.sub(r"\b(xe|i915) \(AMD: docs/AMD_HIP\.md\)", r"\1 driver (Intel Arc: docs/INTEL.md)", msg) - where = ("the experts are loaded into RAM, the card computes the ones it holds" if intel[0]["driver"] == "i915" + where = ("the experts the card does not hold are computed on the CPU" if alch else "the experts are streamed into VRAM") msg = msg.replace(f"RAM: {fake_ram:.0f} GB", f"RAM: {real_ram:.0f} GB ({where})") if re.match(r"\s+\S+\s+needs ~\d+ GB RAM:", msg): # --check's CUDA verdicts: replaced by the Intel one m = msg.split()[0] d = S.MODELS.get(m, {}) shard1 = d.get("download_gb", 0) - 28.8 # all but the per-layer lookup table (read from disk) - room = intel[0]["vram_gb"] - 3 + max(0.0, real_ram - 10) # VRAM, plus a pinned host mirror + room = intel[0]["vram_gb"] - 3 + max(0.0, real_ram - 10) # VRAM, plus a pinned host mirror (or the CPU) msg = (f" {m:8s} ~{shard1:.0f} GB of weights: " + ("fits in VRAM" if shard1 <= intel[0]["vram_gb"] - 1.5 else + "fits, the experts the card does not hold are computed on the CPU (slower)" if alch and shard1 <= room else "fits with part of its experts mirrored in RAM (slower)" if shard1 <= room else "does not fit")) say(msg) S.say = say_intel @@ -247,11 +267,26 @@ 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, {}), intel[0]["vram_gb"], intel[0]["driver"]) + # the card setup selected (--gpu / the first usable), not intel[0]: on a PC with two Arcs the config must match + # the chosen one (docs/INTEL.md, "Two cards"). intel_gpus() lists them in sysfs card order and cfg["gpu"] is + # that index (setup.py's amd path); a layer split writes a list, and then every listed card is used. + gsel = cfg.get("gpu") + split = isinstance(gsel, list) + idx = gsel if isinstance(gsel, int) and 0 <= gsel < len(intel) else 0 + sel = intel[idx] + cfg = to_sycl(cfg, exe, real_ram, keep.get(Path(cfg_path).name, {}), sel["vram_gb"], sel["driver"], + sel.get("devid", "")) + if len(intel) > 1: # pin the SYCL device(s) + # the Level Zero order followed the sysfs card order on the tested machines; a machine where it does not + # needs an explicit ONEAPI_DEVICE_SELECTOR (kept if the user set one) + selector = "level_zero:*" if split else f"level_zero:{idx}" + cfg.setdefault("env", {}).setdefault("ONEAPI_DEVICE_SELECTOR", selector) need = S.MODELS.get(model, {}).get("ram_gb", 0) - if intel[0]["driver"] == "i915" and need and real_ram < need: - S.warn(f"{model} on this Arc loads its experts into RAM (about {need} GB; this PC has {real_ram:.0f} GB): " - "the start will be slow or fail - a smaller model (--model) fits better (docs/INTEL.md)") + sel_alch = sel["driver"] == "i915" or sel.get("devid") in ALCHEMIST_IDS + if sel_alch and need and real_ram < need: + S.warn(f"{model} on this Arc computes the experts the card does not hold on the CPU (about {need} GB of " + f"weights; this PC has {real_ram:.0f} GB of RAM): the start will be slow or fail - a smaller model " + "(--model) fits better (docs/INTEL.md)") 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/core/expert_cache.cpp b/sycl/src/core/expert_cache.cpp index cc3a7809..da56cd28 100644 --- a/sycl/src/core/expert_cache.cpp +++ b/sycl/src/core/expert_cache.cpp @@ -430,6 +430,9 @@ bool ExpertCache::open_segmented(uint64_t want, std::string &err) try { } mapped_segs_ = (int64_t) i + 1; } + // the reserved VA, so device_offset_end can place a borrowed prompt buffer or a resident expert inside it (the GEMM + // stages an operand that lies more than 4 GiB in; oneMKL misreads such an operand's last partial tile) + strata::device_alloc_register(base_, (size_t) reserved_); return true; #endif } @@ -456,6 +459,7 @@ void ExpertCache::release_segmented() { seg_size_.clear(); mapped_segs_ = 0; reserved_ = 0; + strata::device_alloc_unregister(base_); base_ = nullptr; } @@ -745,8 +749,10 @@ void ExpertCache::close() { release_segmented(); } else if (vmm_) { vmm_.reset(); // unmaps and frees every chunk it still holds + strata::device_alloc_unregister(base_); base_ = nullptr; } else if (base_ != nullptr) { + strata::device_alloc_unregister(base_); sycl::free(base_, dpct::get_in_order_queue()); base_ = nullptr; } diff --git a/sycl/src/core/gguf_expert_source.cpp b/sycl/src/core/gguf_expert_source.cpp index 8c228f3c..af1bda10 100644 --- a/sycl/src/core/gguf_expert_source.cpp +++ b/sycl/src/core/gguf_expert_source.cpp @@ -2,13 +2,15 @@ #include "strata/core/gguf_expert_source.hpp" #include "strata/kernels/cpu/expert_layout.hpp" +#include +#include #include +#include #include #include #include #include #include -#include namespace strata::core { @@ -19,8 +21,9 @@ constexpr size_t kRing = 512; // blobs alive at once: the prompt path holds a GgufExpertSource::~GgufExpertSource() { close(); } void GgufExpertSource::close() { - if (mirror_) { sycl::free(mirror_, dpct::get_in_order_queue()); mirror_ = nullptr; } - mirror_bytes_ = 0; mirror_off_.clear(); layer_first_.clear(); + for (uint8_t* c : mirror_chunks_) if (c) sycl::free(c, dpct::get_in_order_queue()); + mirror_chunks_.clear(); + mirror_bytes_ = 0; mirror_ptr_.clear(); layer_first_.clear(); for (int fd : fds_) if (fd >= 0) ::close(fd); fds_.clear(); names_.clear(); layer_fd_.clear(); ring_.clear(); ring_key_.clear(); where_.clear(); ring_next_ = 0; @@ -75,9 +78,9 @@ int GgufExpertSource::fd_of(int64_t layer, int role, std::string& err) { const uint8_t* GgufExpertSource::blob(int64_t layer, int64_t expert) { if (layer < 0 || layer >= n_layers_ || expert < 0 || expert >= n_expert_ || ring_.empty()) return nullptr; - if (mirror_ != nullptr) { - const int64_t o = mirror_off_[(size_t) (layer * n_expert_ + expert)]; - if (o >= 0) return mirror_ + o; + if (!mirror_ptr_.empty()) { + const uint8_t* p = mirror_ptr_[(size_t) (layer * n_expert_ + expert)]; + if (p != nullptr) return p; } const auto& lay = strata::kernels::cpu::expert_layout(); const auto& fm = lay.fmt[(size_t) layer]; @@ -116,69 +119,100 @@ int64_t GgufExpertSource::mirror(const std::vector>& std::string& err) { const auto& lay = strata::kernels::cpu::expert_layout(); std::vector> take; - std::vector offs; uint64_t total = 0; for (const auto& [l, e] : pairs) { if (l < 0 || l >= n_layers_ || e < 0 || e >= n_expert_) continue; const uint64_t b = (lay.bytes[(size_t) l] + 255) / 256 * 256; if (total + b > cap) break; take.push_back({l, e}); - offs.push_back(total); total += b; } if (take.empty()) return 0; - uint8_t* base = nullptr; - try { - base = (uint8_t*) sycl::malloc_host(total, dpct::get_in_order_queue()); - } catch (const sycl::exception& ex) { - err = std::string("mirror: ") + ex.what(); - } - if (base == nullptr) { - if (err.empty()) err = "mirror: no pinned host memory for " + std::to_string(total >> 20) + " MiB"; - return -1; + // Alchemist (Arc A-series) refuses a single USM host allocation past ~3 GiB (docs/INTEL.md, A750), so the mirror + // is built from chunks under that. Battlemage and the CUDA/HIP builds never hit the limit, but chunking is neutral + // for them. One chunk per (up to) 2 GiB of experts. + constexpr uint64_t kChunk = 2ull << 30; + std::vector chunks; + // Free every chunk unless the mirror is handed over to the object: covers an allocation failure, a failed read and + // any exception (a container allocation, a std::thread that cannot be created) on the way out. + struct ChunkCleanup { + std::vector& v; + bool armed = true; + ~ChunkCleanup() { if (armed) for (uint8_t* c : v) if (c) sycl::free(c, dpct::get_in_order_queue()); } + } cleanup{chunks}; + std::vector ptrs(take.size(), nullptr); + uint64_t placed = 0; + uint8_t* cur = nullptr; + uint64_t cur_off = 0, cur_size = 0; + for (size_t j = 0; j < take.size(); ++j) { + const uint64_t b = (lay.bytes[(size_t) take[j].first] + 255) / 256 * 256; + if (cur == nullptr || cur_off + b > cur_size) { + // never smaller than one blob, so a single blob past kChunk still fits its chunk + const uint64_t want = std::max(b, std::min(kChunk, total - placed)); + uint8_t* nc = nullptr; + try { + nc = (uint8_t*) sycl::malloc_host((size_t) want, dpct::get_in_order_queue()); + } catch (const sycl::exception& ex) { + err = std::string("mirror: ") + ex.what(); + } + if (nc == nullptr) { + if (err.empty()) + err = "mirror: no pinned host memory for " + std::to_string(want >> 20) + " MiB"; + return -1; + } + chunks.push_back(nc); + cur = nc; cur_off = 0; cur_size = want; + } + ptrs[j] = cur + cur_off; + cur_off += b; + placed += b; } std::atomic next{0}; std::atomic bad{false}; std::vector ts; - for (int i = 0; i < std::max(1, threads); ++i) - ts.emplace_back([&] { - for (size_t j; (j = next.fetch_add(1)) < take.size() && !bad.load();) { - const auto [l, e] = take[j]; - if (!read_into(l, e, base + offs[j], (size_t) lay.bytes[(size_t) l])) bad.store(true); - } - }); + try { + for (int i = 0; i < std::max(1, threads); ++i) + ts.emplace_back([&] { + for (size_t j; (j = next.fetch_add(1)) < take.size() && !bad.load();) { + const auto [l, e] = take[j]; + if (!read_into(l, e, ptrs[j], (size_t) lay.bytes[(size_t) l])) bad.store(true); + } + }); + } catch (...) { + for (auto& th : ts) if (th.joinable()) th.join(); // join before the cleanup frees, and before unwinding + throw; + } for (auto& th : ts) th.join(); if (bad.load()) { - sycl::free(base, dpct::get_in_order_queue()); err = "mirror: reading an expert from the GGUF failed"; return -1; } - if (mirror_) sycl::free(mirror_, dpct::get_in_order_queue()); - mirror_ = base; + for (uint8_t* c : mirror_chunks_) if (c) sycl::free(c, dpct::get_in_order_queue()); + mirror_chunks_ = std::move(chunks); + cleanup.armed = false; // the chunks now belong to the object mirror_bytes_ = total; - mirror_off_.assign((size_t) (n_layers_ * n_expert_), -1); - layer_first_.assign((size_t) n_layers_, -1); + mirror_ptr_.assign((size_t) (n_layers_ * n_expert_), nullptr); + layer_first_.assign((size_t) n_layers_, nullptr); for (size_t j = 0; j < take.size(); ++j) { const auto [l, e] = take[j]; - mirror_off_[(size_t) (l * n_expert_ + e)] = (int64_t) offs[j]; - if (layer_first_[(size_t) l] < 0) layer_first_[(size_t) l] = (int64_t) offs[j]; + mirror_ptr_[(size_t) (l * n_expert_ + e)] = ptrs[j]; + if (layer_first_[(size_t) l] == nullptr) layer_first_[(size_t) l] = ptrs[j]; } return (int64_t) take.size(); } bool GgufExpertSource::pinned(int64_t layer, int64_t expert) const { - if (mirror_ == nullptr || layer < 0 || layer >= n_layers_ || expert < 0 || expert >= n_expert_) return false; - return mirror_off_[(size_t) (layer * n_expert_ + expert)] >= 0; + if (mirror_ptr_.empty() || layer < 0 || layer >= n_layers_ || expert < 0 || expert >= n_expert_) return false; + return mirror_ptr_[(size_t) (layer * n_expert_ + expert)] != nullptr; } const uint8_t* GgufExpertSource::device_alias(int64_t layer, int64_t expert) const { - if (mirror_ == nullptr || layer < 0 || layer >= n_layers_) return nullptr; + if (mirror_ptr_.empty() || layer < 0 || layer >= n_layers_) return nullptr; if (expert >= 0 && expert < n_expert_) { - const int64_t o = mirror_off_[(size_t) (layer * n_expert_ + expert)]; - if (o >= 0) return mirror_ + o; + const uint8_t* p = mirror_ptr_[(size_t) (layer * n_expert_ + expert)]; + if (p != nullptr) return p; } - const int64_t f = layer_first_[(size_t) layer]; - return f >= 0 ? mirror_ + f : nullptr; + return layer_first_[(size_t) layer]; } bool GgufExpertSource::read_into(int64_t layer, int64_t expert, uint8_t* dst, size_t bytes) const { diff --git a/sycl/src/core/layer.cpp b/sycl/src/core/layer.cpp index 32a02253..5cb981f8 100644 --- a/sycl/src/core/layer.cpp +++ b/sycl/src/core/layer.cpp @@ -1376,7 +1376,7 @@ catch (sycl::exception const &exc) { << ", line:" << __LINE__ << std::endl; std::exit(1); } -}; if (!alloc((size_t) g.n_embd * 4, (void**) &db.h_x_f, (void**) &db.d_x_f, "x_f")) return 0; if (!alloc((size_t) k * 4, (void**) &db.h_ids, (void**) &db.d_ids, "ids")) return 0; if (!alloc((size_t) k * 4, (void**) &db.h_weights, (void**) &db.d_weights, "weights")) return 0; if (!alloc(4, (void**) &db.h_seq, (void**) &db.d_seq, "seq")) return 0; if (!alloc(4, (void**) &db.h_flag, (void**) &db.d_flag, "flag")) return 0; return bytes;} +}; if (!alloc((size_t) g.n_embd * 4, (void**) &db.h_x_f, (void**) &db.d_x_f, "x_f")) return 0; if (!alloc((size_t) k * 4, (void**) &db.h_ids, (void**) &db.d_ids, "ids")) return 0; if (!alloc((size_t) k * 4, (void**) &db.h_weights, (void**) &db.d_weights, "weights")) return 0; if (!alloc(64, (void**) &db.h_seq, (void**) &db.d_seq, "seq")) return 0; /* + the payload tag and checksum */ if (!alloc(4, (void**) &db.h_flag, (void**) &db.d_flag, "flag")) return 0; return bytes;} void doorbell_free(Doorbell &db) { if (db.h_x_f) sycl::free(db.h_x_f, dpct::get_in_order_queue()); if (db.h_ids) sycl::free(db.h_ids, dpct::get_in_order_queue()); @@ -1386,7 +1386,7 @@ void doorbell_free(Doorbell &db) { db = Doorbell{}; } void doorbell_reset(const Doorbell& db) { - if (db.h_seq) *db.h_seq = 0; + if (db.h_seq) for (int i = 0; i <= 8; ++i) ((volatile uint32_t*) db.h_seq)[i] = 0; /* + the payload tags */ if (db.h_flag) *(volatile uint32_t*) db.h_flag = 0; } // ================================ THE TWO ENDS OF A TOKEN ================================ diff --git a/sycl/src/core/session.cpp b/sycl/src/core/session.cpp index 59fc6c72..9edd8082 100644 --- a/sycl/src/core/session.cpp +++ b/sycl/src/core/session.cpp @@ -1002,6 +1002,14 @@ bool session_loop(const ModelGeometry &g, int64_t pos, int32_t pos_base, return false; } + // the ring can arrive before its payload on some GPUs (elementwise.hpp): wait until it is whole, or the + // pool reads a partly stale payload and the answer is garbage (the A770's "!!!!") + if (!strata::kernels::doorbell_wait_payload(s.db->h_seq, s.db->h_x_f, g.n_embd, s.db->h_ids, + s.db->h_weights, k, (uint32_t) want)) { + err = "session_loop: layer " + std::to_string(l) + " rang but its payload never arrived whole"; + return false; + } + // ---- **THE GPU'S HALF GOES FIRST, SO IT RUNS WHILE THE CPU DOES ITS HALF.** `Launch` only enqueues: // the quantize and the grouped expert kernel land on `main_cs` and the GPU starts on them immediately, // while the host is still inside `pool` below. Nothing here waits. diff --git a/sycl/src/core/verify.cpp b/sycl/src/core/verify.cpp index bae8ecb3..9b3ffca5 100644 --- a/sycl/src/core/verify.cpp +++ b/sycl/src/core/verify.cpp @@ -602,7 +602,7 @@ bool Verifier::init(const WeightTable &wt, const ModelGeometry &g, err = "verify: copy stream create failed"; return false; } - if (ext_stream_ != &dpct::get_in_order_queue()) cs_ = + if (ext_stream_ != nullptr) cs_ = ext_stream_; // set_stream (pipelined windows): the stage's shared // stream /* @@ -1810,6 +1810,7 @@ void Verifier::stage_inputs(int T, const int32_t* tokens, int64_t pos0) { for (int64_t h = 0; h < g.idx_q_heads; ++h) pi[t * g.idx_q_heads + h] = pos_t; } *(volatile uint32_t*) h_seq_ = 0; + for (int _i = 1; _i <= 8; ++_i) ((volatile uint32_t*) h_seq_)[_i] = 0; /* + the payload tags/checksums */ *(volatile uint32_t*) h_flag_ = 0; *(volatile uint32_t*) h_flagA_ = 0; *(volatile uint32_t*) h_flagB_ = 0; @@ -2009,6 +2010,13 @@ bool Verifier::run(int T, const int32_t *tokens, int64_t pos0, PoolMultiFn pool, cur_layer_ = want - 1; set_plan_slot(grp); const int tb = gtb[grp], n = gte[grp] - gtb[grp]; + // the ring can arrive before its payload (elementwise.hpp): the pool must read a whole one + if (!strata::kernels::doorbell_wait_payload(h_seq_, h_x_ + (size_t) tb * g.n_embd, (int64_t) n * g.n_embd, + h_ids_ + (size_t) tb * ss.k, h_w_ + (size_t) tb * ss.k, + (int64_t) n * ss.k, want)) { + err = "verify: layer " + std::to_string(l) + " rang but its payload never arrived whole"; + return false; + } progress_at("verify window: the CPU experts of layer", l); if (remote_opt_) remote_opt_->begin(h_w_ + (size_t) tb * ss.k, tb, n); if (pool != nullptr) @@ -2823,6 +2831,7 @@ bool Verifier::stage_batch(const int *rows, int S, int hbase, c[2 + j] = j < t - first ? (int32_t) pos[first + j] : -1; } *(volatile uint32_t*) h_seq_ = 0; + for (int _i = 1; _i <= 8; ++_i) ((volatile uint32_t*) h_seq_)[_i] = 0; /* + the payload tags/checksums */ *(volatile uint32_t*) h_flag_ = 0; *(volatile uint32_t*) h_flagA_ = 0; *(volatile uint32_t*) h_flagB_ = 0; @@ -3521,6 +3530,13 @@ int Verifier::service(PoolMultiFn pool, void *user, std::string &err) try { cur_layer_ = want - 1; set_plan_slot(grp); const int tb = gtb[grp], n = gte[grp] - gtb[grp]; + // the ring can arrive before its payload (elementwise.hpp): the pool must read a whole one + if (!strata::kernels::doorbell_wait_payload(h_seq_, h_x_ + (size_t) tb * g.n_embd, (int64_t) n * g.n_embd, + h_ids_ + (size_t) tb * ss.k, h_w_ + (size_t) tb * ss.k, + (int64_t) n * ss.k, want)) { + err = "verify: layer " + std::to_string(l) + " rang but its payload never arrived whole"; + return -1; + } progress_at("verify window (pipelined): the CPU experts of layer", l); if (pool != nullptr) pool(user, h_x_ + (size_t) tb * g.n_embd, h_ids_ + (size_t) tb * ss.k, n, ss.k, diff --git a/sycl/src/kernels/cuda/elementwise.dp.cpp b/sycl/src/kernels/cuda/elementwise.dp.cpp index 44815f33..51eab2ab 100644 --- a/sycl/src/kernels/cuda/elementwise.dp.cpp +++ b/sycl/src/kernels/cuda/elementwise.dp.cpp @@ -13,6 +13,8 @@ #include #include #include +#include +#include namespace strata::kernels { namespace { @@ -566,91 +568,124 @@ void copy_from_mapped(float* dst, const float* src, int64_t n, void* stream) { check_launch("copy_from_mapped"); } +namespace { +// The published payload's checksum: the wrapping sum of every 32-bit word mixed with its position (murmur3's +// finalizer). A plain sum of the words missed a reordering ([3, 7] -> [7, 3] in the expert ids) and cancelling +// changes; mixed, a stale payload passes only with a chance near 2^-32 per read. It detects; it does not order - +// the host keeps reading until the payload it sees matches (doorbell_payload_ready). Positions: x 0..n-1, +// ids n..n+k-1, weights n+k..n+2k-1. +inline uint32_t dbx_payload_mix(uint32_t word, uint32_t pos) { + uint32_t h = word ^ (pos * 0x9E3779B9u); + h ^= h >> 16; h *= 0x85EBCA6Bu; h ^= h >> 13; h *= 0xC2B2AE35u; h ^= h >> 16; + return h; +} +inline uint32_t dbx_payload_sum(const float* x, int64_t n, const int32_t* ids, const float* w, int64_t k, + bool has_weights) { + uint32_t s = 0; + for (int64_t j = 0; j < n; ++j) s += dbx_payload_mix(sycl::bit_cast(x[j]), (uint32_t) j); + for (int64_t j = 0; j < k; ++j) s += dbx_payload_mix((uint32_t) ids[j], (uint32_t) (n + j)); + if (has_weights) + for (int64_t j = 0; j < k; ++j) s += dbx_payload_mix(sycl::bit_cast(w[j]), (uint32_t) (n + k + j)); + return s; +} +// The ring, its tag and its checksum, in slot r % 4 of the sequence word (elementwise.hpp). Written last, after a +// system fence over the uncached payload stores. +__dpct_inline__ void dbx_ring_commit(uint32_t* seq, uint32_t part, bool group_ok, uint32_t ring) { +#if defined(__HIPCC__) // #697: HIP only; on RDNA4 the volatile store alone can sit in L2 until the stream syncs + (void) group_ok; +#endif + if (group_ok) { + strata::sys_store(seq + 2 + 2 * (ring % 4), part); + strata::sys_store(seq + 1 + 2 * (ring % 4), ring); + sycl::atomic_fence(sycl::memory_order::seq_cst, sycl::memory_scope::system); + strata::sys_store(seq, ring); + } +} +} // namespace + __dpct_inline__ void doorbell_publish_kernel(const float *__restrict__ x, const int32_t *__restrict__ ids, const float *__restrict__ w, int n, int k, float *x_out, int32_t *ids_out, float *w_out, - uint32_t *seq) { + uint32_t *seq, bool plain) { auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>(); + const int i = (int) item_ct1.get_local_id(2); + const int nt = (int) item_ct1.get_local_range(2); + uint32_t part = 0; #pragma unroll - for (int i = item_ct1.get_local_id(2); i < n; - i += item_ct1.get_local_range(2)) x_out[i] = x[i]; - if ((int)item_ct1.get_local_id(2) < k) { - ids_out[item_ct1.get_local_id(2)] = ids[item_ct1.get_local_id(2)]; - if (w_out != nullptr) w_out[item_ct1.get_local_id(2)] = - w[item_ct1.get_local_id(2)]; + for (int j = i; j < n; j += nt) { + const float v = x[j]; + strata::sys_store_mapped(plain, x_out + j, v); + part += dbx_payload_mix(sycl::bit_cast(v), (uint32_t) j); } - /* - DPCT1078: Consider replacing memory_order::acq_rel with - memory_order::seq_cst for correctness if strong memory order restrictions - are needed. - */ - sycl::atomic_fence(sycl::memory_order::acq_rel, sycl::memory_scope::system); - /* - DPCT1065: Consider replacing sycl::nd_item::barrier() with - sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better - performance if there is no access to global memory. - */ + if (i < k) { + const int32_t id = ids[i]; + strata::sys_store_mapped(plain, ids_out + i, id); + part += dbx_payload_mix((uint32_t) id, (uint32_t) (n + i)); + if (w_out != nullptr) { + const float wv = w[i]; + strata::sys_store_mapped(plain, w_out + i, wv); + part += dbx_payload_mix(sycl::bit_cast(wv), (uint32_t) (n + k + i)); + } + } + const uint32_t sum = sycl::reduce_over_group(item_ct1.get_group(), part, sycl::plus()); + sycl::atomic_fence(sycl::memory_order::seq_cst, sycl::memory_scope::system); item_ct1.barrier(); - if (item_ct1.get_local_id(2) == 0) { - strata::sys_store(seq, strata::sys_load(seq) + 1u); -#if defined(__HIPCC__) // #697: HIP only; on RDNA4 the volatile store alone can sit in L2 until the stream syncs - __threadfence_system(); -#endif + if (i == 0) { + const uint32_t next = strata::sys_load(seq) + 1u; + dbx_ring_commit(seq, sum, true, next); } } __dpct_inline__ void doorbell_publish_res_kernel( const float *__restrict__ x, const int32_t *__restrict__ ids, const int32_t *__restrict__ d_res, int n_expert, int n, int k, float *x_out, - int32_t *ids_out, uint32_t *seq) { + int32_t *ids_out, uint32_t *seq, bool full, bool plain) { + // full (STRATA_DOORBELL_CHECK=1): the payload is published whole and the checksum covers x and the ids (this + // variant publishes no weights). Otherwise d_res/n_expert decide whether x is copied, as before the checksum: + // when every routed expert is resident the host never reads x, and an uncached copy of it costs the A750 ~10% + // of decode. auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>(); - int any_miss = 0; - if ((int)item_ct1.get_local_id(2) < k) { - const int32_t id = ids[item_ct1.get_local_id(2)]; - ids_out[item_ct1.get_local_id(2)] = id; - if (d_res == nullptr || id < 0 || id >= n_expert || d_res[id] < 0) any_miss = 1; + if (!full) { + int any_miss = 0; + if ((int) item_ct1.get_local_id(2) < k) { + const int32_t id = ids[item_ct1.get_local_id(2)]; + strata::sys_store_mapped(plain, ids_out + item_ct1.get_local_id(2), id); + if (d_res == nullptr || id < 0 || id >= n_expert || d_res[id] < 0) any_miss = 1; + } + if ((item_ct1.barrier(), sycl::any_of_group(sycl::ext::oneapi::this_work_item::get_work_group<3>(), any_miss))) { + for (int j = (int) item_ct1.get_local_id(2); j < n; j += (int) item_ct1.get_local_range(2)) + strata::sys_store_mapped(plain, x_out + j, x[j]); + } + sycl::atomic_fence(sycl::memory_order::seq_cst, sycl::memory_scope::system); + item_ct1.barrier(); + if (item_ct1.get_local_id(2) == 0) { + const uint32_t next = strata::sys_load(seq) + 1u; + dbx_ring_commit(seq, 0u, true, next); + } + return; } - /* - DPCT1065: Consider replacing sycl::nd_item::barrier() with - sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better - performance if there is no access to global memory. - */ - if ((item_ct1.barrier(), - sycl::any_of_group( - sycl::ext::oneapi::this_work_item::get_work_group<3>(), - any_miss))) { + const int i = (int) item_ct1.get_local_id(2); + const int nt = (int) item_ct1.get_local_range(2); + uint32_t part = 0; #pragma unroll - for (int i = item_ct1.get_local_id(2); i < n; - i += item_ct1.get_local_range(2)) x_out[i] = x[i]; - /* - DPCT1078: Consider replacing memory_order::acq_rel with - memory_order::seq_cst for correctness if strong memory order - restrictions are needed. - */ - sycl::atomic_fence(sycl::memory_order::acq_rel, - sycl::memory_scope::system); - } else if ((int)item_ct1.get_local_id(2) < k) { - /* - DPCT1078: Consider replacing memory_order::acq_rel with - memory_order::seq_cst for correctness if strong memory order - restrictions are needed. - */ - sycl::atomic_fence(sycl::memory_order::acq_rel, - sycl::memory_scope::system); + for (int j = i; j < n; j += nt) { + const float v = x[j]; + strata::sys_store_mapped(plain, x_out + j, v); + part += dbx_payload_mix(sycl::bit_cast(v), (uint32_t) j); } - /* - DPCT1065: Consider replacing sycl::nd_item::barrier() with - sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better - performance if there is no access to global memory. - */ + if (i < k) { + const int32_t id = ids[i]; + strata::sys_store_mapped(plain, ids_out + i, id); + part += dbx_payload_mix((uint32_t) id, (uint32_t) (n + i)); + } + const uint32_t sum = sycl::reduce_over_group(item_ct1.get_group(), part, sycl::plus()); + sycl::atomic_fence(sycl::memory_order::seq_cst, sycl::memory_scope::system); item_ct1.barrier(); - if (item_ct1.get_local_id(2) == 0) { - strata::sys_store(seq, strata::sys_load(seq) + 1u); -#if defined(__HIPCC__) // #697: HIP only; on RDNA4 the volatile store alone can sit in L2 until the stream syncs - __threadfence_system(); -#endif + if (i == 0) { + const uint32_t next = strata::sys_load(seq) + 1u; + dbx_ring_commit(seq, sum, true, next); } } @@ -659,45 +694,36 @@ __dpct_inline__ void doorbell_publish_res_kernel( __dpct_inline__ void doorbell_publish_value_kernel( const float *__restrict__ x, const int32_t *__restrict__ ids, const float *__restrict__ w, int n, int k, float *x_out, int32_t *ids_out, - float *w_out, uint32_t *seq, uint32_t value) { + float *w_out, uint32_t *seq, uint32_t value, bool plain) { auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>(); + const int i = (int) item_ct1.get_local_id(2); + const int nt = (int) item_ct1.get_local_range(2); + uint32_t part = 0; #pragma unroll - for (int i = item_ct1.get_local_id(2); i < n; - i += item_ct1.get_local_range(2)) x_out[i] = x[i]; - if ((int)item_ct1.get_local_id(2) < k) { - ids_out[item_ct1.get_local_id(2)] = ids[item_ct1.get_local_id(2)]; - w_out[item_ct1.get_local_id(2)] = w[item_ct1.get_local_id(2)]; + for (int j = i; j < n; j += nt) { + const float v = x[j]; + strata::sys_store_mapped(plain, x_out + j, v); + part += dbx_payload_mix(sycl::bit_cast(v), (uint32_t) j); } - /* - DPCT1078: Consider replacing memory_order::acq_rel with - memory_order::seq_cst for correctness if strong memory order restrictions - are needed. - */ - sycl::atomic_fence(sycl::memory_order::acq_rel, sycl::memory_scope::system); - item_ct1.barrier(sycl::access::fence_space::local_space); - if (item_ct1.get_local_id(2) == 0) { - /* - DPCT1078: Consider replacing memory_order::acq_rel with - memory_order::seq_cst for correctness if strong memory order - restrictions are needed. - */ - sycl::atomic_fence(sycl::memory_order::acq_rel, - sycl::memory_scope::system); - *(volatile uint32_t*) seq = value; - /* - DPCT1078: Consider replacing memory_order::acq_rel with - memory_order::seq_cst for correctness if strong memory order - restrictions are needed. - */ - sycl::atomic_fence(sycl::memory_order::acq_rel, - sycl::memory_scope::system); + if (i < k) { + const int32_t id = ids[i]; + strata::sys_store_mapped(plain, ids_out + i, id); + part += dbx_payload_mix((uint32_t) id, (uint32_t) (n + i)); + const float wv = w[i]; + strata::sys_store_mapped(plain, w_out + i, wv); + part += dbx_payload_mix(sycl::bit_cast(wv), (uint32_t) (n + k + i)); } + const uint32_t sum = sycl::reduce_over_group(item_ct1.get_group(), part, sycl::plus()); + sycl::atomic_fence(sycl::memory_order::seq_cst, sycl::memory_scope::system); + item_ct1.barrier(); + if (i == 0) dbx_ring_commit(seq, sum, true, value); } void doorbell_publish_value(const float* x, const int32_t* ids, const float* weights, int64_t n, int64_t k, float* x_out, int32_t* ids_out, float* weights_out, uint32_t* d_seq, uint32_t value, void* stream) { if (k > 1024) { std::fprintf(stderr, "doorbell_publish: k too large\n"); std::exit(1); } + const bool plain = strata::doorbell_plain_payload(); /* DPCT1049: The work-group size passed to the SYCL kernel may exceed the limit. To get the device limit, query info::device::max_work_group_size. @@ -715,7 +741,7 @@ void doorbell_publish_value(const float* x, const int32_t* ids, const float* wei exp_props, [=](sycl::nd_item<3> item_ct1) { doorbell_publish_value_kernel(x, ids, weights, (int)n, (int)k, x_out, ids_out, - weights_out, d_seq, value); + weights_out, d_seq, value, plain); }); } } @@ -723,6 +749,7 @@ void doorbell_publish_value(const float* x, const int32_t* ids, const float* wei void doorbell_publish(const float* x, const int32_t* ids, const float* weights, int64_t n, int64_t k, float* x_out, int32_t* ids_out, float* weights_out, uint32_t* d_seq, void* stream) { if (k > 1024) { std::fprintf(stderr, "doorbell_publish: k too large\n"); std::exit(1); } + const bool plain = strata::doorbell_plain_payload(); /* DPCT1049: The work-group size passed to the SYCL kernel may exceed the limit. To get the device limit, query info::device::max_work_group_size. @@ -739,7 +766,7 @@ void doorbell_publish(const float* x, const int32_t* ids, const float* weights, sycl::range(1, 1, 1024)), exp_props, [=](sycl::nd_item<3> item_ct1) { doorbell_publish_kernel(x, ids, weights, (int)n, (int)k, - x_out, ids_out, weights_out, d_seq); + x_out, ids_out, weights_out, d_seq, plain); }); } check_launch("doorbell_publish"); @@ -748,6 +775,9 @@ void doorbell_publish(const float* x, const int32_t* ids, const float* weights, void doorbell_publish_res(const float* x, const int32_t* ids, const int32_t* d_res, int n_expert, int64_t n, int64_t k, float* x_out, int32_t* ids_out, uint32_t* d_seq, void* stream) { if (k > 1024) { std::fprintf(stderr, "doorbell_publish_res: k too large\n"); std::exit(1); } + static const bool full = [] { const char* v = std::getenv("STRATA_DOORBELL_CHECK"); return v != nullptr && v[0] == '1'; }(); + const bool fl = full; + const bool plain = strata::doorbell_plain_payload(); /* DPCT1049: The work-group size passed to the SYCL kernel may exceed the limit. To get the device limit, query info::device::max_work_group_size. @@ -764,12 +794,38 @@ void doorbell_publish_res(const float* x, const int32_t* ids, const int32_t* d_r sycl::range(1, 1, 1024)), exp_props, [=](sycl::nd_item<3> item_ct1) { doorbell_publish_res_kernel(x, ids, d_res, n_expert, (int)n, - (int)k, x_out, ids_out, d_seq); + (int)k, x_out, ids_out, d_seq, fl, plain); }); } check_launch("doorbell_publish_res"); } +bool doorbell_payload_ready(const uint32_t* h_seq, const float* h_x, int64_t n, const int32_t* h_ids, + const float* h_weights, int64_t k, uint32_t want) { + const volatile uint32_t* w = h_seq + 1 + 2 * (want % 4); // this ring's tag and checksum (elementwise.hpp) + if (w[0] != want) return false; + std::atomic_thread_fence(std::memory_order_acquire); + // the two publish shapes: with the routing weights (doorbell_publish / _value) or without (doorbell_publish_res) + return dbx_payload_sum(h_x, n, h_ids, h_weights, k, true) == w[1] || + dbx_payload_sum(h_x, n, h_ids, h_weights, k, false) == w[1]; +} + +bool doorbell_wait_payload(const uint32_t* h_seq, const float* h_x, int64_t n, const int32_t* h_ids, + const float* h_weights, int64_t k, uint32_t want, int timeout_ms) { + // Opt-in (STRATA_DOORBELL_CHECK=1): on an Arc A750 (i915) the host-side checksum of the whole payload, read from + // uncached host memory twice per CPU-expert layer, cost 15-20% of decode (5 interleaved rounds), and the stale + // payload it guards against was not seen there. The ring tag is still published by the GPU. + static const bool check = [] { const char* v = std::getenv("STRATA_DOORBELL_CHECK"); return v != nullptr && v[0] == '1'; }(); + if (!check) return true; + if (doorbell_payload_ready(h_seq, h_x, n, h_ids, h_weights, k, want)) return true; + const auto t0 = std::chrono::steady_clock::now(); + while (!doorbell_payload_ready(h_seq, h_x, n, h_ids, h_weights, k, want)) { + for (int i = 0; i < 64; ++i) __builtin_ia32_pause(); + if (std::chrono::steady_clock::now() - t0 > std::chrono::milliseconds(timeout_ms)) return false; + } + return true; +} + __dpct_inline__ void copy_i32_from_mapped_kernel(int32_t *__restrict__ dst, const volatile int32_t *src, int n) { diff --git a/sycl/src/kernels/iq_multi_parity.cpp b/sycl/src/kernels/iq_multi_parity.cpp index 0f086958..1b0e02d2 100644 --- a/sycl/src/kernels/iq_multi_parity.cpp +++ b/sycl/src/kernels/iq_multi_parity.cpp @@ -269,6 +269,7 @@ struct Grouped { uint8_t *dxq = nullptr, *dscr = nullptr; float* dout = nullptr; size_t out_floats = 0; + std::vector h_start, h_tok, h_dst; // the host copies, for reference() Grouped(int gu, int dt, int64_t H, int64_t FF, const std::vector& counts, int tokens, std::mt19937& rng) { L = k::native_expert_layout(gu, dt, H, FF); @@ -279,11 +280,14 @@ struct Grouped { for (int c : counts) start.push_back(start.back() + c); n_ent = start.back(); cap_ent = n_ent + 3; + h_start = start; std::uniform_int_distribution tk(0, tokens - 1); for (int e = 0; e < n_ent; ++e) tok.push_back(tk(rng)); dst.resize(n_ent); std::iota(dst.begin(), dst.end(), 0); std::shuffle(dst.begin(), dst.end(), rng); + h_tok = tok; + h_dst = dst; std::vector ptr; for (int g = 0; g < n_groups; ++g) { // one blob per group: gate rows | up rows (format gu, H values) | down rows (format dt, FF values) @@ -385,6 +389,34 @@ struct Grouped { k::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, cap_groups, cap_ent, dxq, dscr, dout, s); k::iq_set_old_kernels(false); } + // An independent reference: every entry through iq_mmvq (itself checked against a double-precision CPU reference + // above), one column at a time - gate and up rows against the token's q8_1 activations, SwiGLU into q8_1, the down + // rows against that. Not bitwise the grouped path (accumulation order), so it is compared with a tolerance. + std::vector reference(dpct::queue_ptr s) { + const int64_t H = L.n_embd, FF = L.n_ff; + float *g = dalloc(FF), *u = dalloc(FF), *y = dalloc(H); + uint8_t* hq = dalloc((size_t) (FF / 32) * 36 + 64); + std::vector out(out_floats, 0.0f); + std::vector ptr(n_groups); + ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()) + .memcpy(ptr.data(), dptr, ptr.size() * 8).wait()), "ptr"); + for (int gi = 0; gi < n_groups; ++gi) { + const uint8_t* blob = (const uint8_t*) ptr[gi]; + for (int e = h_start[gi]; e < h_start[gi + 1]; ++e) { + const uint8_t* xq = dxq + (size_t) h_tok[e] * (H / 32) * 36; + k::iq_mmvq(L.gu_type, blob, xq, g, (int) H, (int) FF, 1, s); + k::iq_mmvq(L.gu_type, blob + L.up_off, xq, u, (int) H, (int) FF, 1, s); + k::native_swiglu_quantize_q8_1(g, u, hq, (int) FF, 1, s); + k::iq_mmvq(L.d_type, blob + L.down_off, hq, y, (int) FF, (int) H, 1, s); + ck(DPCT_CHECK_ERROR(s->wait()), "ref sync"); + ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()) + .memcpy(out.data() + (size_t) h_dst[e] * H, y, (size_t) H * 4).wait()), "ref out"); + } + } + sycl::free(g, dpct::get_in_order_queue()); sycl::free(u, dpct::get_in_order_queue()); + sycl::free(y, dpct::get_in_order_queue()); sycl::free(hq, dpct::get_in_order_queue()); + return out; + } std::vector result(bool old, dpct::queue_ptr s) { ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()) .memset(dout, 0xFF, out_floats * 4) @@ -418,6 +450,22 @@ void check_grouped(int gu, int dt, int64_t H, int64_t FF, dpct::queue_ptr s, diff += std::memcmp(&a[i], &b[i], 4) != 0; if (i < (size_t) G.n_ent * H) { ++written; finite = finite && std::isfinite(b[i]); } } + // against the independent reference: the lane kernels (the default) and the other path, rows that are written + { + const auto r = G.reference(s); + auto bad = [&](const std::vector& v) { + float mx = 0; + for (size_t i = 0; i < (size_t) G.n_ent * H; ++i) mx = std::max(mx, std::fabs(r[i])); + size_t n = 0; + for (size_t i = 0; i < (size_t) G.n_ent * H; ++i) n += !(std::fabs(v[i] - r[i]) <= 0.05f * mx); + return n; + }; + const size_t ba = bad(a), bb = bad(b); + std::printf("%-8s/%-7s %5lld x %4lld vs the mmvq reference: lane kernels %zu, other path %zu of %zu rows-values " + "outside 5%% of the max%s\n", name_of(gu), name_of(dt), (long long) H, (long long) FF, ba, bb, + (size_t) G.n_ent * H, ba || bb ? " <== FAIL" : ""); + if (ba) ++g_fail; + } const bool ok = diff == 0 && finite; std::printf("%-8s/%-7s %5lld x %4lld native_expert_grouped, %d groups, %d entries: %s\n", name_of(gu), name_of(dt), (long long) H, (long long) FF, G.n_groups, G.n_ent, diff --git a/sycl/src/prefill/gemm.dp.cpp b/sycl/src/prefill/gemm.dp.cpp index 110a5f90..b070ec5b 100644 --- a/sycl/src/prefill/gemm.dp.cpp +++ b/sycl/src/prefill/gemm.dp.cpp @@ -686,6 +686,59 @@ bool Gemm::bf16_hcd_exact(const uint16_t* X, int64_t ldx, const uint16_t* W, flo #endif } +namespace { +// oneMKL's GEMM reads the last, partial tile of an operand from the wrong place when it lies more than 4 GiB into its +// allocation (Arc A770, oneMKL 2026.1: a BF16 B placed past 4 GiB of a 10.5 GiB allocation gave its last 21 columns +// wrong, and none below 4 GiB). The prompt path borrows the top of the ~10 GiB expert cache for its buffers, so its +// GEMMs met this and the prompt came out non-finite / garbage. An operand past 4 GiB is copied into a scratch buffer +// of the queue's own - a fresh allocation, so at offset 0 - and the GEMM runs on that. Returns false, so the caller +// runs the direct GEMM, when neither operand needs staging (the common, correct case). +uint8_t* gemm_stage(size_t need, sycl::queue& q) { + static thread_local uint8_t* p = nullptr; + static thread_local size_t cap = 0; + if (need > cap) { + if (p != nullptr) { + q.wait(); // the queue is in-order but asynchronous: a previous staged GEMM may still read p + sycl::free(p, q); + } + p = (uint8_t*) sycl::malloc_device(need, q); + cap = p != nullptr ? need : 0; + } + return p; +} +inline bool staged_gemm(sycl::queue& q, void* handle, const uint16_t* W, int lda, const uint16_t* X, int ldb, + dpct::library_data_t dt, int64_t N, int64_t T, int64_t K, float alpha, float beta, + float* Y, int64_t ldy) { + static const bool no_stage = std::getenv("STRATA_SYCL_GEMM_NO_STAGE") != nullptr; // tests' negative control + constexpr size_t k4G = 4ull << 30; + const size_t es = 2; + const size_t w_bytes = (size_t) lda * (size_t) N * es; // W stored K x N, col-major (lda = K) + const size_t x_bytes = (size_t) ldb * (size_t) T * es; // X stored ldb x T + const bool far_w = strata::device_offset_end(W, w_bytes) > k4G; + const bool far_x = strata::device_offset_end(X, x_bytes) > k4G; + if (no_stage || (!far_w && !far_x)) return false; + uint8_t* s = gemm_stage(w_bytes + x_bytes, q); + if (s == nullptr) { + std::fprintf(stderr, "strata: WARNING: a GEMM operand lies past 4 GiB and the %zu MiB staging buffer could not be " + "allocated; the GEMM runs directly and may be wrong on this card\n", + (w_bytes + x_bytes) >> 20); + return false; + } + uint8_t* sw = s; + uint8_t* sx = s + w_bytes; + if (far_w) q.memcpy(sw, W, w_bytes); + if (far_x) q.memcpy(sx, X, x_bytes); + const uint16_t* Wu = far_w ? (const uint16_t*) sw : W; + const uint16_t* Xu = far_x ? (const uint16_t*) sx : X; + ck(DPCT_CHECK_ERROR(dpct::blas::gemm( + (dpct::blas::descriptor_ptr) handle, oneapi::mkl::transpose::trans, oneapi::mkl::transpose::nontrans, + (int) N, (int) T, (int) K, &alpha, Wu, dt, lda, Xu, dt, ldb, &beta, Y, + dpct::library_data_t::real_float, (int) ldy, dpct::compute_type::f32)), + "cublasGemmEx (staged)"); + return true; +} +} // namespace + void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, int64_t ldx) { if (T <= 0 || N <= 0) return; @@ -758,6 +811,9 @@ void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64 } #endif #endif + if (staged_gemm(*strata::q_of(stream_), handle_, W, (int) K, X, (int) (ldx ? ldx : K), dpct::library_data_t::real_bfloat16, N, T, K, + alpha, beta, Y, ldy)) + return; // Column-major view: Y^T[N, T] = W[N, K] (stored K x N col-major, transposed) . X^T[K, T]. ck(DPCT_CHECK_ERROR(dpct::blas::gemm( (dpct::blas::descriptor_ptr)handle_, oneapi::mkl::transpose::trans, @@ -796,6 +852,8 @@ void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_ return; } #endif + if (staged_gemm(*strata::q_of(stream_), handle_, W, (int) K, X, (int) K, dpct::library_data_t::real_half, N, T, K, alpha, beta, Y, ldy)) + return; ck(DPCT_CHECK_ERROR(dpct::blas::gemm( (dpct::blas::descriptor_ptr)handle_, oneapi::mkl::transpose::trans, oneapi::mkl::transpose::nontrans, (int)N, (int)T, (int)K, &alpha, W, diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index 840880a5..3c3b267d 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -25,6 +25,7 @@ #include #include #include "strata/sycl_queue.hpp" +#include "strata/sycl_doorbell.hpp" #include "strata/core/arch_defaults.hpp" #include "strata/core/dma_batch.hpp" #include "strata/core/device.hpp" @@ -428,6 +429,7 @@ struct Options { std::string embd_gguf; /// Plan v0.3 P2: how the n-gram table is read. Direct (default) = unbuffered SSD reads, table never in RAM. std::string ple_io = "direct"; + bool ple_io_explicit = false; ///< --ple-io was given: the engine only warns when direct measures slow int64_t ple_row_cache = 1 << 20; ///< bounded row cache (rows of 90 B); 0 disables int ple_inflight = 256; // the prompt path reads a chunk's rows at once: 64 left the SSD half idle (32K: 303 -> 189 ms) double ple_delay_us = 0; ///< fault injection: every row read completes no earlier than this @@ -1601,6 +1603,31 @@ double pcie_frac_for_gbps(double gbps, double base) { } // namespace +// #1425 #1549 #1629: --ple-io direct (the default) does unbuffered random reads of the n-gram table; on some drives +// (DRAM-less NVMe, Windows unbuffered I/O) they run at 34 MB/s or 4-8 tok/s and a prompt reads layer 1 for minutes. +// Rows per second of a short cold probe: a few batches of random rows through the same batched reader a prompt chunk +// uses, stopped after ~0.6 s. Returns <= 0 when nothing could be measured. +static double ple_direct_rows_per_s(strata::kernels::PleTable& t) { + const uint64_t n = t.rows(); + if (n < 4096) return -1.0; + constexpr size_t kTok = 4; // 64 rows a batch + std::vector rows(kTok * 16); + std::vector out(kTok * 2560); + uint64_t x = 0x9E3779B97F4A7C15ull ^ n; + const auto t0 = std::chrono::steady_clock::now(); + uint64_t done = 0; + double el = 0; + for (int b = 0; b < 64; ++b) { + for (auto& r : rows) { x ^= x << 13; x ^= x >> 7; x ^= x << 17; r = (uint32_t) (x % n); } + std::string e; + if (!t.gather_batch(rows.data(), kTok, out.data(), e)) return -1.0; + done += rows.size(); + el = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + if (el > 0.6) break; + } + return el > 0 ? (double) done / el : -1.0; +} + int main(int argc, char **argv) try { // **UNBUFFERED, BECAUSE THE INTERESTING OUTPUT IS THE OUTPUT BEFORE A CRASH.** `stdout` redirected to a // pipe or a file is block-buffered, so a program that dies loses every line it had already printed - which @@ -1687,7 +1714,7 @@ int main(int argc, char **argv) try { else if (a == "--dump-routing") o.dump_routing = next("--dump-routing"); else if (a == "--ple-gguf") o.ple_gguf = next("--ple-gguf"); else if (a == "--no-ple") o.no_ple = true; - else if (a == "--ple-io") o.ple_io = next("--ple-io"); + else if (a == "--ple-io") { o.ple_io = next("--ple-io"); o.ple_io_explicit = true; } else if (a == "--ple-row-cache") o.ple_row_cache = std::atoll(next("--ple-row-cache")); else if (a == "--ple-inflight") o.ple_inflight = std::atoi(next("--ple-inflight")); else if (a == "--ple-delay-us") o.ple_delay_us = std::atof(next("--ple-delay-us")); @@ -2143,12 +2170,42 @@ int main(int argc, char **argv) try { // SYCL port (the B70, 2026-09-30): lending cache slots to the prompt path costs ~1 s per prompt (2,184 tokens: // 610 vs 792 tok/s) but is what keeps every expert in VRAM at a long context - 80,000 tokens without it: the // reserve for the KV and the chunk buffers evicts ~1,900 experts, prompt 790 tok/s and decode 2 tok/s after it; - // with it: 1,062 tok/s and 39.5 tok/s. So by default only above a 32K context; the flags still decide. + // with it: 1,062 tok/s and 39.5 tok/s after it. So by default only above a 32K context; the flags still decide. // (0.1.31-0.1.32: borrowing hung in the first chunk of a long prompt; the prompt path's stager waited on the copy // queue's events from its own threads, which the Level Zero v2 adapter did not survive once its ring wrapped - // prefill.cpp, Stager::issued_one. Fixed 2026-10-01: a 40K prompt borrowing reads at 1,144 tok/s and decodes at // 69 tok/s after it, against 1,201 / 65 with its own buffers.) - if (!borrow_explicit) o.no_prefill_borrow = o.max_context <= 32768; + // + // 2026-10-08 (the A770): borrowing is BROKEN on Alchemist. Its prompt buffers are carved from the top of the + // ~10 GiB expert-cache allocation, and oneMKL's BF16 GEMM reads a wrong tile when an operand lies more than 4 GiB + // into its allocation (docs/INTEL.md); the borrowed operands hit that, so from the first full prefill chunk the + // router read garbage and prefill failed ("prefill: routed id out of range") or the engine segfaulted (measured: + // a 236-token prompt, mirrored and mmap configs alike). Keep Alchemist's prompt path on its own buffers (its own + // allocation, reserved exactly by owned_prefill_mib) and keep an automatic chunk under 4 GiB, until the SYCL BLAS + // stages operands as the CUDA/HIP shims do. Battlemage keeps the old default (its long prompts were measured + // correct with borrowing). --prefill-borrow overrides, for testing the staging fix. A layer split keeps its rule. + if (!borrow_explicit) { + static const bool alchemist = [] { + try { + // PCI device ids, the same table setup_intel.py uses: 56a0 A770, 56a1 A750, 56a2 A580, 56a5 A380, + // 56a6 A310, 5690 A770M + const unsigned id = dpct::get_current_device().get_info(); + // Only a card with room for an expert cache past 4 GiB can hit it: on an 8 GB A750 the cache was 0.34 GiB + // and the own-buffers reservation cost experts (prompt 72 -> 52 tok/s, decode -6%, 4K prompt, 4 rounds) + if (dpct::get_current_device().get_info() < (12ull << 30)) return false; + switch (id & 0xffffu) { + case 0x56a0: case 0x56a1: case 0x56a2: case 0x56a5: case 0x56a6: case 0x5690: return true; + default: return false; + } + } catch (...) { return false; } + }(); + if (!multi_gpu && alchemist) { + o.no_prefill_borrow = true; + if (o.prefill_auto && o.prefill_chunk > 2048) o.prefill_chunk = o.prefill_auto_max = 2048; + } else { + o.no_prefill_borrow = o.max_context <= 32768; + } + } #if defined(STRATA_USE_HIP) { // every GPU this run uses must be an architecture the binary has code for (a gfx1100 build on a gfx1201 @@ -2224,6 +2281,7 @@ int main(int argc, char **argv) try { if (o.mtp_max_t == 0) o.mtp_max_t = o.spec; o.spec = std::max(o.spec, std::min(o.mtp_max_t + o.lookup_chain, 8)); // kVerifyMaxT } + strata::spin_drafts_need_long_bound(o.spec >= 2 && o.mtp.empty()); // spin_max: drafting without MTP waits long strata::core::layer_set_shared_early(!o.shared_late); if (!o.native_preset.empty()) { try { @@ -2941,6 +2999,34 @@ int main(int argc, char **argv) try { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } + // Recommend, never force: when the default direct reads measure slow, switch to the mapped reads (40-100x + // faster on the reporters' drives); an explicit --ple-io direct is kept and only warned about. + if (pio.mode == strata::kernels::PleIo::Direct && std::getenv("STRATA_PLE_PROBE") == nullptr) { + constexpr double kSlowRowsPerS = 15000.0; // ~60 MB/s of 4 KiB pages; a healthy NVMe is >100k + const double rps = ple_direct_rows_per_s(ple_table); + if (rps >= kSlowRowsPerS) + std::fprintf(stderr, "strata generate: PLE direct read probe: %.0f rows/s (fine)\n", rps); + if (rps > 0 && rps < kSlowRowsPerS) { + if (!o.ple_io_explicit) { + std::fprintf(stderr, "strata generate: --ple-io direct measures slow here (%.0f rows/s, about %.0f MB/s of " + "random 4 KiB reads): using --ple-io mmap instead (the OS file cache holds the pages; " + "--ple-io direct forces the old mode, --ple-io ram keeps the table in RAM)\n", + rps, rps * 4096.0 / 1e6); + ple_table.close(); + pio.mode = strata::kernels::PleIo::Mmap; + pio.keepalive_ms = 0; + if (!ple_table.open(o.ple_gguf, err, pio)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + } else { + std::fprintf(stderr, "strata generate: WARNING: --ple-io direct measures slow here (%.0f rows/s, about %.0f " + "MB/s of random 4 KiB reads): a prompt can spend minutes reading layer 1 and trip the " + "stall watchdog (#1425, #1629). --ple-io mmap was 40-100x faster on such drives; " + "--ple-io ram needs the RAM for the table\n", rps, rps * 4096.0 / 1e6); + } + } + } #if !defined(_WIN32) if (pio.mode == strata::kernels::PleIo::Direct) { // #605: --ple-io direct's random reads (up to --ple-inflight at once) are for SSDs; a rotational disk