Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
sycl: re-migrate the port to 0.1.40.1 (dpct 2025.3, 3-way merge per docs/INTEL.md)
Niko122123a38a0bb75c
diff --git a/sycl/CMakeLists.txt b/sycl/CMakeLists.txtindex 1b6094afc..bee31fe40 100644--- a/sycl/CMakeLists.txt+++ b/sycl/CMakeLists.txt@@ -10,7 +10,7 @@## Device code is JIT-compiled from SPIR-V unless STRATA_SYCL_AOT names a device (bmg-g31 for the Arc Pro B70).cmake_minimum_required(VERSION 3.24)-project(strata_sycl VERSION 0.1.39 LANGUAGES C CXX) # the upstream engine version this port tracks+project(strata_sycl VERSION 0.1.40 LANGUAGES C CXX) # the upstream engine version this port tracksset(STRATA_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/..)set(CMAKE_CXX_STANDARD 20)set(CMAKE_CXX_STANDARD_REQUIRED ON)@@ -81,7 +81,8 @@ target_include_directories(strata_includes INTERFACEtarget_compile_options(strata_includes INTERFACE -Wall -Wextra)# --- CPU-side pieces, identical to the top-level build -------------------------------------------------------------strata_resolve(_spec src/spec/suffix_drafter.cpp src/spec/controller.cpp src/spec/draft_policy.cpp)+strata_resolve(_spec src/spec/suffix_drafter.cpp src/spec/controller.cpp src/spec/draft_policy.cpp+ src/spec/draft_source.cpp)add_library(strata_spec STATIC ${_spec})target_link_libraries(strata_spec PUBLIC strata_includes)@@ -91,6 +92,27 @@ add_library(strata_kernels_cpu STATIC ${_cpu})set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/expert.cpp PROPERTIES COMPILE_OPTIONS"-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma")set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/q2_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")+# AVX-VNNI copies of the AVX-2 expert kernels (q2_avx2.cpp, iq_avx2.cpp), taken at run time where the CPU has them+include(CheckCXXSourceCompiles)+set(CMAKE_REQUIRED_FLAGS "-mavx2 -mfma -mf16c")+check_cxx_source_compiles([=[+#include <immintrin.h>+#if defined(__GNUC__) || defined(__clang__)+__attribute__((target("avxvnni")))+#endif+static __m256i dots(__m256i a, __m256i b) { return _mm256_dpbusd_avx_epi32(_mm256_dpwssd_avx_epi32(a, a, b), a, b); }+int main() {+ volatile int x = 1;+ return _mm256_extract_epi32(dots(_mm256_set1_epi32(x), _mm256_set1_epi32(x)), 0) == 0;+}+]=] STRATA_HAVE_AVXVNNI_INTRINSICS)+unset(CMAKE_REQUIRED_FLAGS)+if(STRATA_HAVE_AVXVNNI_INTRINSICS)+ set(_strata_avxvnni STRATA_AVXVNNI=1)+else()+ set(_strata_avxvnni STRATA_AVXVNNI=0)+endif()+set_property(SOURCE ${STRATA_ROOT}/src/kernels/cpu/q2_avx2.cpp APPEND PROPERTY COMPILE_DEFINITIONS ${_strata_avxvnni})find_package(Threads REQUIRED)target_link_libraries(strata_kernels_cpu PUBLIC strata_includes Threads::Threads)@@ -121,13 +143,15 @@ if(STRATA_NATIVE_EXPERTS)add_subdirectory(${strata_llamacpp_SOURCE_DIR}/ggml ${CMAKE_BINARY_DIR}/ggml EXCLUDE_FROM_ALL)endif()strata_resolve(_cpu_native src/kernels/cpu/native_expert.cpp src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/iq_avx2.cpp- src/kernels/cpu/kq_avx2.cpp) # 0.1.31: the Q4_K/Q5_K/Q5_1/Q8_0 expert rows+ src/kernels/cpu/kq_avx2.cpp src/kernels/cpu/kq_avx1.cpp) # 0.1.31: the Q4_K/Q5_K/Q5_1/Q8_0 expert rowstarget_sources(strata_kernels_cpu PRIVATE ${_cpu_native})target_include_directories(strata_kernels_cpu PRIVATE ${STRATA_ROOT}/third_party/ggml)set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS"-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma")set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")+ set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "-mavx")+ set_property(SOURCE ${STRATA_ROOT}/src/kernels/cpu/iq_avx2.cpp APPEND PROPERTY COMPILE_DEFINITIONS ${_strata_avxvnni})target_link_libraries(strata_kernels_cpu PUBLIC ggml-cpu ggml-base)target_compile_definitions(strata_kernels_cpu PUBLIC STRATA_NATIVE_EXPERTS=1)endif()@@ -157,7 +181,9 @@ strata_resolve(_engine src/core/layer.cpp src/core/session.cpp src/core/expert_ssrc/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cppsrc/core/mtp.cpp src/core/conversation_snapshot.cpp src/core/conversation_state.cppsrc/core/conversation_memory.cpp # 0.1.31: the conversation snapshots (#216)- src/core/peer_experts.cpp) # 0.1.36+: --peer-device (a stub in the port: no second GPU tier yet)+ src/core/arch_defaults.cpp src/core/vmm.cpp # vmm.cpp is the port's stub: no driver VMM on Level Zero+ src/core/conversation_file.cpp+ src/core/peer_experts.cpp src/core/remote_expert_opt_stub.cpp) # 0.1.36+: --peer-device (a stub in the port: no second GPU tier yet)add_library(strata_engine STATIC ${_engine} ${CMAKE_CURRENT_SOURCE_DIR}/src/core/gguf_expert_source.cpp)target_include_directories(strata_engine PRIVATE ${STRATA_ROOT}/src/core) # conversation_checked.hpp (#include "...")target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu)@@ -202,6 +228,16 @@ if(STRATA_SYCL_PARITY)add_executable(native_grouped_parity ${_src})target_link_libraries(native_grouped_parity PRIVATE strata_kernels)add_test(NAME native_grouped_parity COMMAND native_grouped_parity)+ # 0.1.40 (#783): the batched verify-window kernels against the ones they replace, bitwise (synthetic, no model)+ foreach(p IN ITEMS verify native_multi kv_steps resident_plan gr_multi)+ strata_resolve(_src src/kernels/${p}_parity.cpp)+ add_executable(${p}_parity ${_src})+ target_include_directories(${p}_parity PRIVATE ${STRATA_ROOT}/src/kernels)+ target_link_libraries(${p}_parity PRIVATE strata_kernels)+ add_test(NAME ${p}_parity COMMAND ${p}_parity)+ endforeach()+ # not built here: qsa_topk_parity / qsa_topk_active_parity (the sm_90 thread-block-cluster QSA top-k has no SYCL+ # counterpart: the callers take the plain kernels), route_window_parity and fused_gr_bench (no migrated copy yet)# (upstream PR #413's gdn_rec_parity is an SM-holding NVIDIA bench - PTX timers, __nanosleep - not built here; the# key-head kernel is checked through the engine: output hashes with STRATA_GDN_KEYHEAD=1 and without)# the conversation snapshots (#216) against the engine, as upstream's STRATA_BUILD_CONVERSATION_TESTSdiff --git a/sycl/include/strata/core/dma_batch.hpp b/sycl/include/strata/core/dma_batch.hppnew file mode 100644index 000000000..a0bc413a1--- /dev/null+++ b/sycl/include/strata/core/dma_batch.hpp@@ -0,0 +1,182 @@+#define DPCT_COMPAT_RT_VERSION 12080+#pragma once+// dma_batch.hpp - independent host-to-device blob copies as one submission: copy_blobs.+//+// The batched path is midhatn's (PR #807, MIT-compatible contribution): cudaMemcpyBatchAsync for independent+// pinned expert uploads on CUDA 13+, with the Windows alias lookup it found necessary. eddoursul's fork (F12) uses+// the same call for the adaptive tier's and the prefetch's copies: under WDDM a copy submitted alone raises an+// interrupt when it lands, on the processor its GPU's interrupts go to; a batch raises one.+//+// Modes (STRATA_DMA_BATCH, read once; `dma_batch_mode()`):+// 0 one cudaMemcpyAsync per blob: exactly the loop the engine always ran+// 1 cudaMemcpyBatchAsync (CUDA 13+, groups of 2..128), the copies in any order, the batch in the stream's+// 2 as 1, plus CUDA 13.4's cudaMemcpyFlagPreferOverlapWithCompute (a hint)+// Every other build (HIP, CUDA before 13) and every single copy or group over 128 takes the loop. A batch the+// runtime refuses is redone as the loop (with one warning), never dropped: readiness is signalled only for+// uploads that were submitted.+#define DPCT_PROFILING_ENABLED+#include <sycl/sycl.hpp>+#include <dpct/dpct.hpp>++#include <array>+#include <cstddef>+#include <cstdint>+#include <cstdio>+#include <cstdlib>+#include <mutex>+#include <unordered_map>++namespace strata::core {++/// The mode: STRATA_DMA_BATCH (0, 1, 2); unset = the engine's default (`default_mode`, set at the call site's first+/// use; 0 until a measured win makes it 1).+inline int dma_batch_mode(int default_mode = 0) {+ static const int mode = [default_mode] {+ const char* e = std::getenv("STRATA_DMA_BATCH");+ return e != nullptr && e[0] != '\0' ? std::atoi(e) : default_mode;+ }();+ return mode;+}++namespace detail {++// A registered Windows host pointer may differ from its device-visible alias; the batch API needs the alias+// (cudaMemcpyAsync(kind=HostToDevice) resolves it itself). The experts' blobs are fixed, so each is looked up once.+inline dpct::err0 host_alias(const void *p, const void **out) try {+ static std::mutex mu;+ static std::unordered_map<const void*, const void*> cache;+ {+ std::lock_guard<std::mutex> lk(mu);+ const auto it = cache.find(p);+ if (it != cache.end()) { *out = it->second; return 0; }+ }+ void* alias = nullptr;+ const dpct::err0 e =+ DPCT_CHECK_ERROR(alias = (void *)const_cast<void *>(p));+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (e != 0) return e;+ std::lock_guard<std::mutex> lk(mu);+ cache.emplace(p, alias);+ *out = alias;+ return 0;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++} // namespace detail++/// `n` independent copies, dst[i] <- src[i] (bytes[i] each), on `stream`. The sources are immutable pinned host+/// blobs and the destinations disjoint; the caller keeps them alive until the stream completes. Ordering with+/// earlier and later work on the stream is that of the copies one by one. Returns the first error (the loop+/// continues past none: the first failing copy ends it).+inline dpct::err0 copy_blobs(void *const *dst, const void *const *src,+ const size_t *bytes, size_t n,+ dpct::queue_ptr stream, int batch_mode) try {+ if (n == 0) return 0;+#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && \+ defined(DPCT_COMPAT_RT_VERSION) && DPCT_COMPAT_RT_VERSION >= 13000+ constexpr size_t cap = 128;+ if (batch_mode != 0 && n > 1 && n <= cap) {+ std::array<const void*, cap> srcs{};+ bool aliased = true;+ for (size_t i = 0; i < n; ++i)+ if (detail::host_alias(src[i], &srcs[i]) != cudaSuccess) { aliased = false; break; }+ if (aliased) {+ cudaMemcpyAttributes attr{};+ attr.srcAccessOrder = cudaMemcpySrcAccessOrderStream;+#if CUDART_VERSION >= 13040+ if (batch_mode == 2) attr.flags = cudaMemcpyFlagPreferOverlapWithCompute;+#endif+ size_t first = 0;+ std::array<void*, cap> dsts{};+ std::array<size_t, cap> sizes{};+ for (size_t i = 0; i < n; ++i) { dsts[i] = dst[i]; sizes[i] = bytes[i]; }+ const cudaError_t e = cudaMemcpyBatchAsync(dsts.data(), srcs.data(), sizes.data(), n, &attr, &first, 1, stream);+ if (e == cudaSuccess) return cudaSuccess;+ static bool warned = false;+ if (!warned) {+ warned = true;+ std::fprintf(stderr, "strata: cudaMemcpyBatchAsync failed (%s); the uploads go one copy at a time\n",+ cudaGetErrorString(e));+ }+ (void) cudaGetLastError();+ }+ }+#else+ (void) batch_mode;+#endif+ for (size_t i = 0; i < n; ++i) {+ /*+ DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.+ While the origin API might be synchronous, it depends on the type of+ operand memory, so you may need to call wait() on event return by memcpy+ API to ensure synchronization behavior.+ */+ const dpct::err0 e =+ DPCT_CHECK_ERROR(stream->memcpy(dst[i], src[i], bytes[i]));+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (e != 0) return e;+ }+ return 0;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++/// The verifier's form: `n` blobs of `bytes` each into consecutive slots of `dst`.+inline dpct::err0 copy_expert_blobs(uint8_t *dst, const uint8_t *const *src,+ int n, size_t bytes, dpct::queue_ptr stream,+ int batch_mode) try {+ if (n <= 0) return 0;+ constexpr size_t cap = 128;+ if (batch_mode == 0 || (size_t) n > cap) { // the old loop, with no staging of its own+ for (int i = 0; i < n; ++i) {+ /*+ DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy+ API. While the origin API might be synchronous, it depends on the+ type of operand memory, so you may need to call wait() on event+ return by memcpy API to ensure synchronization behavior.+ */+ const dpct::err0 e = DPCT_CHECK_ERROR(+ stream->memcpy(dst + (size_t)i * bytes, src[i], bytes));+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (e != 0) return e;+ }+ return 0;+ }+ void* d[cap] = {}; // plain arrays: nvcc on Linux (13.0, g++) rejects std::array<T, cap> here ("template argument 2 is invalid")+ const void* s[cap] = {};+ size_t b[cap] = {};+ for (int i = 0; i < n; ++i) { d[i] = dst + (size_t) i * bytes; s[i] = src[i]; b[i] = bytes; }+ return copy_blobs(d, s, b, (size_t) n, stream, batch_mode);+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++} // namespace strata::corediff --git a/sycl/include/strata/core/exchange_storage.hpp b/sycl/include/strata/core/exchange_storage.hppnew file mode 100644index 000000000..c4ba22084--- /dev/null+++ b/sycl/include/strata/core/exchange_storage.hpp@@ -0,0 +1,115 @@+#pragma once++#include <atomic>+#include <cstddef>+#include <memory>+#include <utility>+#include <cstdint>+#include <limits>+#include <string>+#include <vector>+#include <cmath>++namespace strata::core::detail {++// Non-owning views: the complement and exchange allocations retain their original+// owners until FileExpertSource::close(). Ownership changes via slot IDs; the+// physical buffer addresses, bytes and CUDA aliases stay in place. This first path requires uniform, fully mapped/pinned expert slots.+class ExchangeStorage {+public:+ struct View {+ uint8_t* host = nullptr;+ const uint8_t* device = nullptr;+ };++ bool initialize(const std::vector<uint64_t>& offsets, uint8_t* resident_host,+ const uint8_t* resident_device, uint64_t resident_bytes,+ uint8_t* exchange_host, const uint8_t* exchange_device,+ size_t count, size_t blob_bytes, std::string& error) {+ error.clear();+ if (active()) { error = "exchange storage already initialized"; return false; }+ if (!resident_host || !resident_device || !exchange_host || !exchange_device ||+ !blob_bytes || !count || !resident_bytes || resident_bytes % blob_bytes ||+ count > std::numeric_limits<size_t>::max() / blob_bytes) {+ error = "invalid uniform mapped exchange geometry"; return false;+ }+ const size_t resident_slots = (size_t)(resident_bytes / blob_bytes);+ if (resident_slots > std::numeric_limits<size_t>::max() - count) {+ error = "exchange slot count overflow"; return false;+ }+ auto experts = std::make_unique<std::atomic<size_t>[]>(offsets.size());+ std::vector<size_t> spares(count);+ std::vector<View> buffers(resident_slots + count);+ for (size_t slot = 0; slot < resident_slots; ++slot)+ buffers[slot] = {resident_host + slot * blob_bytes, resident_device + slot * blob_bytes};+ std::vector<bool> used(resident_slots, false);+ for (size_t i = 0; i < offsets.size(); ++i) {+ const uint64_t at = offsets[i];+ experts[i].store(kAbsent, std::memory_order_relaxed);+ if (at == ~uint64_t{0}) continue;+ if (at >= resident_bytes || at % blob_bytes || used[(size_t)(at / blob_bytes)]) {+ error = "invalid or duplicate resident slot"; return false;+ }+ used[(size_t)(at / blob_bytes)] = true;+ experts[i].store((size_t)(at / blob_bytes), std::memory_order_relaxed);+ }+ for (bool present : used) if (!present) {+ error = "unassigned resident slot"; return false;+ }+ for (size_t q = 0; q < count; ++q) {+ spares[q] = resident_slots + q;+ buffers[spares[q]] = {exchange_host + q * blob_bytes, exchange_device + q * blob_bytes};+ }+ experts_ = std::move(experts);+ expert_count_ = offsets.size();+ spares_.swap(spares);+ buffers_.swap(buffers);+ blob_bytes_ = blob_bytes;+ return true;+ }++ bool active() const { return blob_bytes_ != 0; }+ View resident(size_t expert) const {+ if (expert >= expert_count_) return {};+ const size_t slot = experts_[expert].load(std::memory_order_acquire);+ return slot != kAbsent ? buffers_[slot] : View{};+ }+ View spare(size_t q) const { return q < spares_.size() ? buffers_[spares_[q]] : View{}; }++ // Only after every CPU reader and H2D copy of `in` has completed, and `out`+ // has landed in spare(q). No allocation, memcpy, or CUDA operation here.+ bool commit(size_t in, size_t out, size_t q, const uint8_t* staged, size_t bytes) {+ if (in >= expert_count_ || out >= expert_count_ || q >= spares_.size() ||+ !staged || bytes != blob_bytes_) return false;+ const size_t incoming_slot = experts_[in].load(std::memory_order_acquire);+ if (incoming_slot == kAbsent || experts_[out].load(std::memory_order_acquire) != kAbsent ||+ buffers_[spares_[q]].host != staged) return false;+ // A background router lookahead can query residency to skip redundant+ // file prefetches. Publish one atomic slot ID; the pointer/alias pair is+ // immutable. Actual compute readers still obey the completion contract.+ experts_[out].store(spares_[q], std::memory_order_release);+ spares_[q] = incoming_slot;+ experts_[in].store(kAbsent, std::memory_order_release);+ ++exchanges_;+ avoided_bytes_ += bytes;+ return true;+ }++ uint64_t exchanges() const { return exchanges_; }+ uint64_t avoided_bytes() const { return avoided_bytes_; } // memcpy payload, not read+write total+ void clear() {+ experts_.reset(); expert_count_ = 0; buffers_.clear(); spares_.clear();+ blob_bytes_ = 0; exchanges_ = avoided_bytes_ = 0;+ }++private:+ static constexpr size_t kAbsent = std::numeric_limits<size_t>::max();+ std::unique_ptr<std::atomic<size_t>[]> experts_;+ size_t expert_count_ = 0;+ std::vector<View> buffers_; // immutable physical addresses after initialize+ std::vector<size_t> spares_; // touched only by the serialized cache manager+ size_t blob_bytes_ = 0;+ uint64_t exchanges_ = 0, avoided_bytes_ = 0;+};++} // namespace strata::core::detaildiff --git a/sycl/include/strata/core/expert_source.hpp b/sycl/include/strata/core/expert_source.hppnew file mode 100644index 000000000..2a8731aec--- /dev/null+++ b/sycl/include/strata/core/expert_source.hpp@@ -0,0 +1,774 @@+// include/strata/core/expert_source.hpp - P2.S3/P2.S5: the expert pool's adapter to the host loop.+//+// `session_loop` publishes, per layer, the NORMED activation `x_f`, the ten routed expert ids and their router+// weights, and expects `k x n_embd` floats back. This is the piece that turns those four things into an+// `ExpertPool::run` call. Nothing here is clever, and that is the point: the pool, the kernel and the loop are+// each already verified, so this file has exactly one job - get the CONTRACT between them right.+//+// THE CONTRACT, and each clause is a way to be wrong:+//+// 1. **`x_f` IS THE SAME PINNED BUFFER EVERY LAYER.** Its ADDRESS never changes, so the `ActQ` cannot be+// cached by pointer - a cache keyed on `x_f` would quantize layer 0 and reuse it for all 47 remaining+// layers, which is a finite, plausible, completely wrong token. There is no cache here at all: the+// conversion is one 2560-element pass against a 0.3 ms/layer budget, and a correct answer is worth more+// than the microseconds.+// 2. **THE POOL DOES NOT APPLY THE ROUTER WEIGHT.** `moe_combine` (`src/core/layer.cpp:479`) sums+// `w[i] * parts[i]` on the device. `ExpertJob::weight` is a diagnostic field; setting it here would+// apply the weight twice, which is invisible in a single layer and compounds over 48.+// 3. **THE KERNEL'S GEOMETRY IS FIXED BY THE ARTIFACT** (`H = 2560`, `FF = 640`, `BLOB = 1,382,400`). A+// different `n_embd` or a different expert width is REFUSED rather than mis-indexed, because the blob's+// internal offsets are compile-time constants and reading a 640-wide expert as a 2560-wide one walks off+// the end into the next expert's bytes without faulting.+#pragma once++#include "strata/core/expert_cache.hpp"+#include "strata/core/exchange_storage.hpp"+#include "strata/core/hit_hook.hpp"+#include "strata/kernels/cpu/pool.hpp"++#include <atomic>+#include <cstdint>+#include <cstddef>+#include <condition_variable>+#include <memory>+#include <mutex>+#include <thread>+#include <unordered_map>+#include <utility>+#include <string>+#include <vector>++namespace strata::kernels::cpu {+struct ExpertLayout;+}++namespace strata::core {++class PeerExperts; // multi-GPU: the second GPU's expert tier (peer_experts.hpp)+class RemoteExperts;+struct LoadStats;++namespace detail {++/// Sentinel used by the pure complement planner for a blob that remains in the mmap fallback.+inline constexpr uint64_t kNoCacheComplement = ~uint64_t{0};++/// Required cgroup-v2 usage counters for the conservative cache-reclaim allowance.+struct CgroupMemoryStat {+ uint64_t current = 0;+ uint64_t inactive_file = 0;+ uint64_t file_dirty = 0;+ uint64_t file_writeback = 0;+ bool valid = false;+};++/// Calculate additional bytes under a finite cgroup limit after reclaiming only clean inactive file cache.+/// Returns false when the required memory.stat counters were unavailable.+bool cgroup_available_bytes(uint64_t limit, const CgroupMemoryStat& stat, uint64_t& bytes);++/// #633: the RAM this process can get. `available`: MemAvailable (Windows: the available physical memory), lowered+/// to the room under the tightest cgroup limit; `cgroup_limit`: that tightest limit itself (v2 memory.max of the group+/// and its ancestors, or v1 memory.limit_in_bytes), ~0 when there is none - what a container can never exceed.+struct HostMemory {+ uint64_t available = 0;+ uint64_t cgroup_limit = ~uint64_t{0};+ uint64_t commit = ~uint64_t{0}; ///< available Windows commit capacity; ~0 when not reported+};++/// Linux reads `meminfo`, `self_cgroup` and the cgroup tree under `cgroup_root` (the parameters are for tests; the+/// defaults are the real files). cgroup v2 as before (an unreadable limit of a group that has one fails); cgroup v1's+/// memory controller (`<root>/memory/<path>`: memory.limit_in_bytes - memory.usage_in_bytes); no cgroup line at all is+/// MemAvailable alone. False when the RAM cannot be determined.+bool host_available_memory(HostMemory& m, const std::string& meminfo = "/proc/meminfo",+ const std::string& self_cgroup = "/proc/self/cgroup",+ const std::string& cgroup_root = "/sys/fs/cgroup");++/// Bound a resident budget by RAM and commit capacity after headroom; leave 256 MiB more when clamping.+/// Pass UINT64_MAX for commit when the platform does not report it.+uint64_t clamp_resident_budget(uint64_t requested, uint64_t physical, uint64_t commit, uint64_t headroom);++/// Build compact offsets for experts absent from both the primary GPU cache and an optional second GPU tier.+/// Kept CPU-only so selection and byte accounting can be tested without initializing a GPU.+bool make_cache_complement_plan(+ int64_t n_layers, int64_t n_expert, const std::vector<uint64_t>& layer_blob_bytes,+ const std::vector<std::pair<int32_t, int32_t>>& primary_gpu_pairs,+ const std::vector<std::pair<int32_t, int32_t>>& additional_gpu_pairs,+ std::vector<uint64_t>& offsets, uint64_t& bytes, std::string& err);++/// Resolve one blob through the compact copy when present, otherwise preserve its exact mapped-file fallback.+const uint8_t* cache_complement_blob_or_fallback(+ size_t index, const std::vector<uint64_t>& offsets, const uint8_t* complement_host,+ const uint8_t* mapped_fallback);++/// The resident RAM mode: which GPU-cache slots' experts are kept in RAM too. The prompt path lends the cache's+/// LAST slots (from `lend_from` on; a short prompt lends only the last few), and a lent slot's expert is streamed+/// from RAM during the prompt and copied back into its slot after it. `base_bytes` (every expert no slot holds)+/// must fit `budget`; slots are then added from the end down to `lend_from` while they still fit. Returns the+/// first slot kept in RAM (`slot_bytes.size()` = none), or -1 when `base_bytes` alone exceeds `budget`.+int64_t choose_resident_keep_from(const std::vector<uint64_t>& slot_bytes, uint64_t base_bytes, uint64_t budget,+ int64_t lend_from);++/// The adaptive tier swapped `in` into a GPU slot and `out` out of it: `out` takes `in`'s place in the compact copy+/// (the caller copies out's bytes there). False, and nothing changed, unless `in` is in the copy and `out` is not.+bool exchange_cache_complement(std::vector<uint64_t>& offsets, size_t in, size_t out);++} // namespace detail++++/// Where one routed expert's bytes come from.+///+/// Phase 2 has NO cache (`phase-2-correct-engine.md`: hit rate `h = 0`), so the only implementation is a+/// file-backed reader. The interface exists anyway because Phase 3 replaces exactly this object with the VRAM+/// cache, and because a test can supply an in-memory source without a 34 GB artifact.+class ExpertSource {+public:+ /*+ DPCT1109: Virtual functions cannot be called in SYCL device code. You+ need to adjust the code.+ */+ virtual ~ExpertSource() = default;++ /// The expert-layout blob for `(layer, expert)`, or nullptr if it cannot be produced.+ ///+ /// The pointer only has to stay valid until the next `blob()` call: with `h = 0` every expert is computed+ /// immediately and nothing is retained. A CACHING source must return pointers into the cache, not into a+ /// reused staging buffer - otherwise the pool would read the next expert's bytes while computing this one.+ virtual const uint8_t* blob(int64_t layer, int64_t expert) = 0;++ /// Blobs touched, for the driver to report. A source that does not count returns 0.+ virtual int64_t reads() const { return 0; }++ /// Plan v0.3 P5: whether `blob(layer, expert)` lies in page-locked, CUDA-registered memory, so an+ /// asynchronous host-to-device copy can DMA it directly (no staging copy on the CPU).+ virtual bool pinned(int64_t layer, int64_t expert) const { (void) layer; (void) expert; return false; }++ /// Called once before the first expert of a layer. A source that reads from disk wants to start the read+ /// here so it overlaps the quantisation, and a prefetching source in Phase 3 wants the ids.+ virtual void begin_layer(int64_t layer, const int32_t* ids, int64_t k) { (void) layer; (void) ids; (void) k; }+ /// Plan v0.3 P6: the DEVICE address of a pinned, mapped blob (the GPU can read it over PCIe), or null.+ virtual const uint8_t* device_alias(int64_t layer, int64_t expert) const { (void) layer; (void) expert; return nullptr; }+ /// A file-backed source: start reading this expert's pages now (it will be needed by the CPU); no-op elsewhere.+ virtual void prefetch(int64_t layer, int64_t expert) { (void) layer; (void) expert; }+ /// A file-backed source: this expert lives in VRAM, so its pages need not stay in RAM - hand them back to the+ /// kernel (a later read re-reads the file; no result depends on it). Returns the bytes released; 0 elsewhere.+ virtual uint64_t release(int64_t layer, int64_t expert) { (void) layer; (void) expert; return 0; }+ /// Whether the verify window may give the GPU a PCIe share of this layer's misses at all (each expert is still+ /// checked with `pinned`). The arena answers per layer through its expert 0; the resident RAM mode's compact+ /// copy has no expert 0 when the GPU cache holds it, so it answers for the whole copy.+ virtual bool pcie_layer(int64_t layer) const { return device_alias(layer, 0) != nullptr; }++ /// CS-T: whether `blob(layer, expert)` would be assembled into a short-lived buffer (a native pack read from its+ /// GGUF shards in place, where an expert's gate, up and down rows are three separate slices). Such a pointer+ /// stays valid for the layer it was asked in and the next one or two; a consumer that keeps a blob longer (the+ /// prompt path's stager queues a whole chunk) copies it with `copy_blob` instead.+ virtual bool transient(int64_t layer, int64_t expert) const { (void) layer; (void) expert; return false; }+ /// Disk sessions: the files this source read its experts from, as (role, path), resolved by the loader itself+ /// - the pack's experts.bin, or every GGUF tensor native_experts.txt named, per layer and role+ /// ("expert blk.L.ffn_up"). Filled by open(); empty before.+ const std::vector<std::pair<std::string, std::string>>& model_inputs() const { return inputs_; }+ /// The blob's bytes into `dst` (blob_bytes(layer) of them). Safe from several threads for a source whose+ /// `transient` can be true.+ virtual bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst);+ /// Asks the OS for these pairs' bytes ahead of the `blob` calls that read them. False (nothing asked) by default.+ virtual bool advise_pairs(const std::pair<int32_t, int32_t>* pairs, int64_t n) const {+ (void) pairs; (void) n; return false;+ }+ /// The `n` experts of `layer` the CPU is about to ask `blob` for, all at once: a source that reads a file may+ /// fetch them in parallel. The bytes `blob` then returns are the same. Default: nothing.+ virtual void prefetch(int64_t layer, const int64_t* experts, int64_t n) { (void) layer; (void) experts; (void) n; }+ /// CS-T: the experts of `layer` a predictor expects next - a source that reads a file may start reading their+ /// pages now, in the background. Only warms: what `blob` returns is unchanged. Default: nothing.+ virtual void warm(int64_t layer, const int64_t* experts, int64_t n) { (void) layer; (void) experts; (void) n; }+ /// Whether `warm` does anything (the predictor is not run otherwise).+ virtual bool warms() const { return false; }+protected:+ /// What model_inputs() returns; set by a source's open().+ void record_inputs(const std::string& pack_experts, const std::string& gguf,+ const strata::kernels::cpu::ExpertLayout& lay, bool from_gguf);+ std::vector<std::pair<std::string, std::string>> inputs_;+};++/// CS-T, routing-aware prefetch of the file tier: when the CPU pool starts layer `l`, a worker thread applies layer+/// l+1's router (BF16, host copy) to layer l's MoE input - the residual stream changes little from one layer to the+/// next - takes each token's top `k` experts, drops the ones the GPU cache or the RAM copy holds, and asks the+/// source to `warm` the rest, so their pages are on the way while layer l computes. A prediction only warms pages:+/// it never changes which experts are computed or how.+class RouterLookahead {+public:+ RouterLookahead() = default;+ ~RouterLookahead();+ RouterLookahead(const RouterLookahead&) = delete;+ RouterLookahead& operator=(const RouterLookahead&) = delete;+ /// `routers[l]`: layer l's ffn_gate_inp as BF16 bits, n_expert rows of n_embd.+ bool start(std::vector<std::vector<uint16_t>> routers, int64_t n_embd, int64_t n_expert, int k, ExpertSource* src,+ std::string& err);+ /// Layer `layer`'s MoE input for `n_tok` tokens (host floats): predict and warm layer + 1. Never waits: a+ /// prediction still running for an earlier layer makes this one skip.+ void submit(int64_t layer, const float* x, int64_t n_tok, const int32_t* host_res);+ int64_t predicted() const { return predicted_.load(std::memory_order_relaxed); }+ int64_t skipped() const { return skipped_.load(std::memory_order_relaxed); }+ double busy_ms() const { return (double) busy_us_.load(std::memory_order_relaxed) / 1000.0; }++private:+ void run();+ std::vector<std::vector<uint16_t>> routers_;+ int64_t n_embd_ = 0, n_expert_ = 0;+ int k_ = 10;+ ExpertSource* src_ = nullptr;+ std::thread thread_;+ std::mutex mu_;+ std::condition_variable cv_;+ bool quit_ = false, pending_ = false, busy_ = false;+ int64_t layer_ = -1, n_tok_ = 0;+ const int32_t* host_res_ = nullptr;+ std::vector<float> x_;+ std::atomic<int64_t> predicted_{0}, skipped_{0};+ std::atomic<uint64_t> busy_us_{0};+};++/// Plan v0.3 P6: what the GPU computes in a verify window's layer, written by the pool (mapped host memory) right+/// after the ring and published before the CPU starts its own share. Groups of entries that share a blob; the+/// blob is a VRAM slot or a pinned host blob read over PCIe.+struct GpuPlanSink {+ int32_t* counts = nullptr; ///< [0] groups, [1] entries+ int32_t* start = nullptr; ///< cap + 1+ int32_t* dst = nullptr; ///< cap: the entry's row of parts (token * k + j)+ int32_t* tok = nullptr; ///< cap: the entry's token+ unsigned long long* ptr = nullptr; ///< cap: the group's blob, device address+ /// Plan v0.3 P6 (DMA): the PCIe share is a second list of groups - `ptr2[q]` is staging slot q, `start2` indexes+ /// the same dst/tok entries - computed by the GPU after `fetch` has copied their blobs into staging with the+ /// copy engine. counts[0] = VRAM groups, counts[1] = all entries, counts[2] = PCIe groups.+ unsigned long long* ptr2 = nullptr;+ int32_t* start2 = nullptr;+ unsigned long long staging = 0;+ int64_t staging_cap = 0;+ int64_t cap = 0;+ void (*publish)(void* ctx) = nullptr;+ /// Starts the DMA copies of `n` host blobs (pinned) into staging slots 0..n-1 and signals the GPU when they land.+ void (*fetch)(void* ctx, const uint8_t* const* src, int n, size_t bytes) = nullptr;+ void* ctx = nullptr;+ /// Plan v0.3 P6: how a PCIe group reaches the GPU. 0 = the copy engine stages it (DMA, `fetch`); 1 = the grouped+ /// kernel reads the mapped arena directly; 2 = a copy kernel stages it inside the graph. For 1 and 2 `ptr2`+ /// holds the arena's device alias.+ int pcie_mode = 0;+};++/// The adapter's own state. One per session, reused every layer so the token path allocates nothing (P2.T10).+struct ExpertDispatch {+ strata::kernels::cpu::ExpertPool* pool = nullptr;+ ExpertSource* src = nullptr;+ RouterLookahead* lookahead = nullptr; ///< CS-T: warms the next layer's predicted file-tier experts+ RemoteExperts* remote[3] = {}; ///< optional CUDA1..3 tiers for otherwise CPU-served rows+ int remote_count = 0;+ int64_t n_expert = strata::kernels::cpu::NE;++ /// Counters, for the driver to report rather than for control flow.+ int64_t layers = 0;+ int64_t experts = 0;+ int64_t missing = 0;++ // ================================ R4: THE VRAM TIER, MEASURED BEFORE IT IS USED ================================+ //+ // **THE CACHE IS CONSULTED AND FILLED HERE, AND NOTHING IS COMPUTED FROM IT YET.** That is deliberate and+ // it is `R4-design-note.md` §7 step 2: the *dispatch* is measured on its own before any kernel is written,+ // because a hit rate measured after the kernel exists cannot say whether a disappointing result was the+ // policy, the split or the kernel.+ //+ // So every expert is still computed by the CPU, exactly as before, and the run is numerically identical+ // with the cache on or off. What changes is that the engine now reports **h on its own routing, on a real+ // workload** - which is the number `R4.1` asks for and which until now existed only from offline traces.+ //+ // The policy is compulsory-miss: the first time `(layer, expert)` is routed, if a slot is free it is+ // admitted and filled from the arena. No eviction, because eviction policy is the measured question+ // (`R4.1`'s LFU-decay vs LRU sweep) and a placeholder would set the hit rate everything is sized against.+ ExpertCache* cache = nullptr;+ int64_t cache_hits = 0; ///< lookups already resident+ int64_t cache_admitted = 0; ///< lookups that took a slot+ int64_t cache_refused = 0; ///< lookups with no slot free (the cache is full)+ void* cache_stream = nullptr;+ const char* cache_fail = nullptr;++ // ================================ R4.2c: THE HITS GO TO THE GPU ================================+ //+ // **THE SPLIT IS BY ROUTER INDEX, AND THAT IS THE WHOLE TRICK.** A layer routes ten experts; the resident+ // ones are computed on the GPU and the rest on the CPU, and both answers have to end up in `parts` at the+ // index the ROUTER gave them, because that is the order `moe_combine` weights against. So the CPU's `out`+ // rows are zeroed for the hits, and each hit carries its routed index to the kernel as `dst`.+ //+ // Everything below is per-session state rather than per-call, so the token path allocates nothing (P2.T10).+ const uint8_t* cache_base = nullptr; ///< the slot arena on the DEVICE+ int64_t cache_blob = 0; ///< bytes per slot+ const uint64_t* cache_slot_off = nullptr; ///< plan v0.3 P6: per-slot offsets when the slots differ in size+ void* hit_scratch = nullptr; ///< `moe_hit_grouped_scratch_bytes(K, ...)`+ float* parts_out = nullptr; ///< the graph's `parts` buffer, on the device+ /// Where the GPU's hits land, `K x n_embd`, DEVICE and separate from `parts_out` on purpose: see+ /// `HitPhase`. Zeroed by the hit path each layer before the kernel writes it.+ float* hit_out = nullptr;+ int64_t parts_elems = 0; ///< `K * n_embd`, the length of both buffers+ const float* mixed = nullptr; ///< the layer's normed activation, for the hit kernel's Q8_0+ uint8_t* x_q8_0_hit = nullptr; ///< `(n_embd/32) * 34` bytes, its own buffer+ /// **R4.2h: THE CPU's fp32 ACTIVATION SCALES, `(n_embd/32)` FLOATS.** Without them the GPU's hits are+ /// computed with the `block_q8_0`'s fp16 `d` while the CPU's misses use the fp32 `ActQ::scale`+ /// (`cpu/expert.cpp:92`) - **4.761e-04 relative on 80 of 80 chunks**, measured with both real+ /// implementations linked in `bench/micro/act_quant_parity.cu`. That disagreement is why turning the+ /// cache on changed the generated tokens. Required whenever the hit path runs.+ float* x_q8_0_hit_scale = nullptr;+ int32_t* d_slot = nullptr; ///< device, K entries+ int32_t* d_dst = nullptr; ///< device, K entries+ std::vector<int32_t> h_slot, h_dst; ///< host staging, sized at session setup+ /// **PER ROUTER INDEX, DECIDED IN `Launch` AND CONSUMED BY THE POOL.** The two callbacks share it+ /// so the decision is made exactly once, on this layer's ids, and neither side can re-decide it.+ std::vector<uint8_t> is_hit;+ bool decided = false;+ /// Plan v0.3 P4 token graph: the STATIC residency table (`n_layers x n_expert`, slot or -1), the host's copy+ /// of what the device hit path reads. When set, the pool leaves a resident expert's row at zero (the GPU+ /// computes it) without any `Launch` callback.+ const int32_t* host_res = nullptr;+ /// Plan v0.3 P4: split every expert by rows across the pool's threads (default on; A/B `--no-split-rows`).+ bool split_rows = true;++ // ================================ R4.2d: DID THE GPU ACTUALLY START? ================================+ //+ // **THE HIT PATH IS 0.91 ms SLOWER AND THE ONLY EXPLANATION LEFT IS THAT IT NEVER OVERLAPS.** The kernel+ // is 159 GB/s against the CPU's 35, the CPU's half of the drain falls 6 ms, and none of it reaches the+ // token - which is what it would look like if the enqueued hit kernels did not BEGIN until the host next+ // entered the driver, i.e. after `pool()` returned. That is the third sighting of this driver behaving+ // that way (rounds 195/287 on the doorbell, round 36 on the head and sampler) and it decides whether R4 can+ // pay at all, so it gets measured rather than argued.+ //+ // `hit_done` is recorded on the stream straight after the hit kernel. `Combine` - which runs after the+ // pool - queries it: SUCCESS means the GPU finished while the CPU was working, NOT-READY means it had not.+ // Same shape as the doorbell's `rings_mid_graph`, and for the same reason.+ void* hit_done = nullptr; ///< cudaEvent_t, created at session setup+ int64_t hit_ready = 0; ///< layers where the hit work was DONE by the time the pool returned+ int64_t hit_late = 0; ///< layers where it was not+ /// The candidate fix, as an A/B arm: enter the driver once right after the hit launch. If submission is+ /// lazy, this starts the GPU work before the pool instead of after it.+ bool hit_poke = false;+ bool hit_cpu_order = false; ///< experimental CPU-order GPU expert arithmetic; opt-in only+ int64_t n_hits = 0; ///< this layer's hits+ /// Set by `Launch` and consumed by `Combine`, so a `Combine` with no `Launch` in front of it cannot+ /// add a stale buffer into `parts`.+ bool hit_pending = false;+ const char* hit_fail = nullptr;++ /// Whether the hit path is wired up. All of it or none of it: a half-configured hit path would compute+ /// some experts twice and others not at all, which is a wrong token rather than an error.+ bool hits_ready() const {+ return cache != nullptr && cache_base != nullptr && parts_out != nullptr && hit_out != nullptr &&+ mixed != nullptr &&+ hit_scratch != nullptr && x_q8_0_hit != nullptr && x_q8_0_hit_scale != nullptr && d_slot != nullptr && d_dst != nullptr;+ }++ std::vector<strata::kernels::cpu::ExpertJob> jobs;+ strata::kernels::cpu::ActQ act;+ /// Plan v0.3 P6 verify window: one quantized activation per token, the multi-token jobs, and the expert ->+ /// job map (reset after every layer).+ std::vector<strata::kernels::cpu::ActQ> act_multi;+ /// Plan v0.3 P6: a native pack's per-token activations (MAXT x kNativeActBytes).+ std::vector<uint8_t> nact_multi;+ std::vector<strata::kernels::cpu::ExpertJobMulti> jobs_multi;+ std::vector<int16_t> job_of;+ /// Plan v0.3 P6: the verify window's GPU plan (VRAM hits + the PCIe share of the misses); `pcie_num`/256 of+ /// each layer's distinct missed experts (the last ones in routing order) are read by the GPU over PCIe.+ GpuPlanSink* plan = nullptr;+ int pcie_num = 0;+ int64_t pcie_experts = 0; ///< distinct experts the GPU read over PCIe in verify windows+ /// #588: routed (token, expert) entries the GPU computed from outside its cache in verify windows: read over PCIe+ /// (--pcie-frac, kind 1) or on another GPU (kind 2). In neither cache_hits nor cache_refused.+ int64_t offload_entries = 0;+ double ms_plan = 0, ms_actq = 0, ms_jobs = 0, ms_run = 0; ///< verify-window dispatch sections+ /// Plan v0.3 P6: decayed routing counts per (layer, expert) during decode (sized by the caller; empty = off),+ /// which the driver uses to swap the most-routed missing experts into the VRAM tier between rounds.+ std::vector<float> usage;+ int64_t multi_misses = 0; ///< distinct (layer, expert) pairs the CPU computed in verify windows+ int64_t multi_entries = 0; ///< routed (token, expert) entries the CPU served in verify windows+ /// Multi-GPU: the second GPU's tier. Its experts are computed there instead of on the CPU (kind 2).+ PeerExperts* peer = nullptr;+ int64_t peer_entries = 0; ///< routed entries the peer served in verify windows+ /// Set when `dispatch` could not produce an answer. The loop itself has no error channel, so this is+ /// where a source failure surfaces: the driver checks it after `session_loop` returns rather than the+ /// engine computing from a half-filled `parts`.+ ///+ /// **`failed` LATCHES AND `fail` IS ONLY THE MESSAGE.** Clearing the message must not re-arm the adapter:+ /// a session that failed at layer 5 has already fed `moe_combine` whatever `parts` held, so every layer+ /// after it is built on a hole - and resuming into a plausible-looking token is the exact outcome this+ /// whole mechanism exists to prevent. `failed` is what the short-circuit reads.+ bool failed = false;+ const char* fail = nullptr;+ int64_t fail_layer = -1;+ int64_t fail_expert = -1;+};++/// `strata::core::PoolFn`, exactly. Silent on failure BY SIGNATURE - see `ExpertDispatch::fail`.+void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, const float* weights, int64_t n_embd,+ int64_t k, float* out);++/// Plan v0.3 P6: the pool for a verify window of `n_tok` tokens. `x_f` is (n_tok, n_embd), `ids` (n_tok, k) and+/// `out` (n_tok * k, n_embd). Each distinct missed expert is computed once for all the tokens routed to it;+/// resident experts' rows are zeroed (the GPU adds them). Requires `host_res` (the token-graph residency).+void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k,+ float* out);++/// **THE HITS, LAUNCHED AFTER THE MISSES ARE STAGED AND BEFORE `post[l]`.** Same shape as `PoolFn` and for the+/// same reason: `session_loop` owns the ORDER and this owns the work, so the loop needs to know nothing about+/// expert caches. Returns immediately when there are no hits, which is every layer until the cache is warm.+///+/// It must run AFTER the host has copied the misses into `parts_dev` (it writes into the same buffer, on rows+/// the CPU zeroed) and BEFORE `post[l]` (which reads it). Both are stream-ordered on the loop's own stream.+void expert_hit_run(void* user, void* stream, HitPhase phase, const int32_t* ids, int64_t k);+/// The pool half of the same decision; see `ExpertDispatch::is_hit`.++/// **PHASE 2'S ONLY SOURCE: `experts.bin`, memory-mapped, no cache.**+///+/// `experts.bin` is 33,973,862,400 B and `BLOB` is 1,382,400, so it holds exactly `48 x 512 = 24,576` blobs and+/// the index is `layer * 512 + expert` with NO padding. A mapping is therefore the whole implementation: the+/// blob pointer is base plus a multiply, and the page fault that follows is the read.+///+/// **AND THAT IS NOT AS SLOW AS IT SOUNDS, WHICH IS THE POINT.** The expert set is 34 GB and this machine has+/// 64 GB of DDR5, so a warm OS page cache holds ALL of it - the second token onward is a DRAM read at the+/// measured 44.14 GB/s, not a disk read. The first token's 663.6 MB comes off the disk and is the cold-path+/// number; `benches` should report the two separately rather than blending them.+///+/// IT IS NOT AN LRU, AN LFU OR A PREFETCHER. Phase 3 replaces this object with those. Phase 2 is hit rate+/// `h = 0` on purpose, so that the CPU path and the host round trip are exercised on every layer of every+/// token - which is the only way they get debugged before speed matters.+class FileExpertSource : public ExpertSource {+public:+ FileExpertSource() = default;+ ~FileExpertSource() override;+ FileExpertSource(const FileExpertSource&) = delete;+ FileExpertSource& operator=(const FileExpertSource&) = delete;++ /// Maps `<pack_dir>/experts.bin` and checks its size against the loaded expert layout. Canonical packs use+ /// `n_layers * n_expert * BLOB`; native packs use their variable per-layer blob sizes and offsets.+ ///+ /// The size check is not a formality: a short file would fault at the END of a long sequence, and an+ /// over-long one means the pack is not the one the geometry came from. Refuses with the two numbers.+ ///+ /// CS-T: a native pack WITHOUT experts.bin, after `set_gguf`, maps the model's GGUF shards instead (every file+ /// native_experts.txt names, after `check_experts_gguf`), and assembles a blob from its three role slices when+ /// it is asked for: the SSD tier, read in place through the OS file cache, with no 30-77 GB experts.bin copy.+ /// With experts.bin present nothing changes.+ bool open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err);+ /// CS-T: the --native shard (native_experts.txt names the other files beside it); see `open`.+ void set_gguf(const std::string& native) { gguf_ = native; }+ /// Whether the experts are read from the GGUF shards in place (no experts.bin).+ bool gguf_mode() const { return !role_ptr_.empty(); }+ /// Pin a compact host mirror of experts absent from a fully filled static GPU cache. The mmap remains open+ /// as a fallback for later cache reloads. This is opt-in because the complement may still be a large allocation.+ ///+ /// The resident RAM mode (`--resident-experts`, `--resident-cpu-experts`):+ /// - `pin`: page-locked and mapped (`cudaHostAlloc`), so the prompt path copies it by DMA and the verify+ /// window may read a share of the misses over PCIe; when the driver refuses, ordinary memory locked in the+ /// working set instead. `pin = false` is ordinary pageable memory (the ROCm arm: large pinned allocations+ /// can fail there, and it is what the HIP measurements used).+ /// - `lend_from_slot` >= 0: the GPU-cache slots from there to the end are the prompt path's lend region; their+ /// experts are kept in RAM too, from the last slot down, as far as available memory minus headroom allows+ /// (a lent slot's expert is streamed during the prompt and copied back after it).+ /// - the rest (the experts no slot holds) must fit that budget, or nothing is allocated and this returns false.+ ///+ /// CS-T, `budget_bytes` > 0 (`--resident-budget-gib`): only as many of those experts as fit `budget_bytes`, taken+ /// in `rank` order (the expert profile: the hottest after the GPU cache's), are copied; the rest stay on the+ /// mapped files (the SSD tier). No lend region then (a lent slot's expert is read from the files).+ /// Available memory is limited by both RAM and commit capacity on Windows.+ /// #467: `budget_bytes` = `kResidentWhatFits` sizes that path from available memory minus headroom and the #403+ /// margin - the soft --resident-experts mode's second try when the whole complement does not fit;+ /// false when not even one expert fits. On Windows the mapped experts leave the working set before any reading.+ static constexpr uint64_t kResidentWhatFits = ~0ull;+ bool pin_cache_complement(+ const ExpertCache& cache, std::string& err, bool pin = true,+ const std::vector<std::pair<int32_t, int32_t>>& additional_gpu_pairs = {}, int64_t lend_from_slot = -1,+ uint64_t headroom_bytes = 8ull << 30, uint64_t budget_bytes = 0,+ const std::vector<std::pair<int32_t, int32_t>>* rank = nullptr);+ void close();++ bool mapped() const { return base_ != nullptr; }+ int64_t blobs() const { return blobs_; }+ uint64_t pinned_bytes() const { return complement_pinned_ ? complement_pin_limit_ : 0; }+ uint64_t resident_bytes() const { return complement_bytes_; }+ bool complement_pinned() const { return complement_pinned_; }+ bool complement_ready() const { return complement_ready_; }+ uint64_t locked_bytes() const { return complement_locked_; }+ /// Lend-region slots whose experts the compact copy holds (the last ones of the cache).+ int64_t resident_lent_slots() const { return complement_lent_slots_; }++ // ---- the resident RAM mode and the adaptive tier. A swap puts `in` (held here) into a GPU slot and evicts+ // `out` (held only by that slot). Before the slot is overwritten the caller copies it back into an exchange+ // buffer and calls `stage_exchange`: `out` is then read from that buffer, and `in` still from here (the CPU+ // computes both until the swap lands). Once the slot copy has landed, `commit_exchanges` moves `out` into+ // `in`'s place, so the copy keeps holding exactly the experts the GPU does not - with no read of the file.+ // STRATA_EXCHANGE_ROTATE=1 can instead transfer buffer ownership (uniform, fully pinned/mapped slots).+ /// Whether the compact copy holds `(layer, expert)`.+ bool has_resident(int64_t layer, int64_t expert) const;+ /// Host room for `n` evicted blobs (page-locked when possible). Idempotent for the same or a smaller `n`.+ bool reserve_exchanges(int64_t n, std::string& err);+ int64_t exchange_capacity() const { return xstage_cap_; }+ /// The exchange buffers are page-locked (cudaHostAlloc): copies to and from them are asynchronous.+ bool exchange_pinned() const { return xstage_pinned_; }+ uint8_t* exchange_buffer(int64_t q) const;+ /// Requires `has_resident(layer, in)`, `!has_resident(layer, out)` and `exchange_buffer(q)` holding out's blob.+ bool stage_exchange(int64_t layer, int64_t in, int64_t out, int64_t q);+ /// --pipeline-windows: size the exchange table now, so a `stage_exchange` on the adaptive tier's thread never+ /// reallocates it under a concurrent `blob` (the pool reads it while windows are in flight).+ void prepare_overrides() { if (override_.empty()) override_.assign((size_t) blobs_, nullptr); }+ /// After the GPU copies of every staged swap have landed. Returns how many exchanges were applied.+ int64_t commit_exchanges();+ /// `commit_exchanges` in two halves, for the asynchronous adaptive tier (--adapt-async): `commit_copies` moves+ /// every staged evicted blob into its `in`'s place in the copy (on another thread: safe once nothing computes `in`+ /// from RAM - it is resident on the GPU - while `out` is still read from its exchange buffer), then `commit_flip`+ /// (the caller's thread, between windows) points `out` there and drops the staging. Returns how many were applied.+ void commit_copies();+ int64_t commit_flip();+ /// The compact copy's blob of `(layer, expert)`, or null; not counted as a read (any thread).+ const uint8_t* resident_blob(int64_t layer, int64_t expert) const;+ int64_t exchanges() const { return exchanges_; }+ bool exchange_rotation() const { return exchange_storage_.active(); }+ uint64_t rotated_exchanges() const { return exchange_storage_.exchanges(); }+ uint64_t avoided_exchange_copy_bytes() const { return exchange_storage_.avoided_bytes(); }+ /// With the compact copy ready: blobs read from the mapped file since (what the plain mmap mode may read from+ /// the SSD). 0 in a steady resident mode; lend-region experts that did not fit the RAM count here.+ int64_t file_reads() const { return file_reads_.load(std::memory_order_relaxed); }+ /// CS-T per-tier counters: blobs served from the RAM copy, and the bytes read from the mapped files (the blobs+ /// `file_reads` counts, plus the prompt path's copies of them).+ int64_t ram_reads() const { return ram_reads_.load(std::memory_order_relaxed); }+ uint64_t file_read_bytes() const { return file_read_bytes_.load(std::memory_order_relaxed); }+ /// Of those, the bytes `blob` read (decode windows, adaptive swaps; the rest are the prompt path's copies), and+ /// the time spent reading the files, summed over threads.+ uint64_t file_blob_bytes() const { return file_blob_bytes_.load(std::memory_order_relaxed); }+ double file_ms() const { return (double) file_us_.load(std::memory_order_relaxed) / 1000.0; }+ /// Threads `prefetch` reads the GGUF with (STRATA_FETCH_THREADS, default 8).+ void set_fetch_threads(int n) { fetch_threads_ = n < 1 ? 1 : n; }+ /// #286: read the experts straight from the drive (Windows: FILE_FLAG_NO_BUFFERING, overlapped; Linux: O_DIRECT and+ /// the kernel's asynchronous reads) instead of+ /// through the mapped files - the GGUF in place, or a pack's experts.bin - when the file cache could not keep them+ /// beside `ram_bytes` (the RAM budget), cached now or not (their mapped pages would land in the working set); see+ /// experts_unbuffered. The mapped reads' page faults are one small request each, and the pages they bring in+ /// take the RAM the budget was sized for. `why` says what decided.+ /// #577: `ram_bytes` counts up to every expert, and only the experts outside it are what the cache must keep.+ bool set_unbuffered(uint64_t ram_bytes, std::string& why);+ /// #577: the same decision once the RAM copy is built (pin_cache_complement), from the RAM it really holds and the+ /// expert bytes outside it; switches either way (startup only, nothing reading). Returns whether unbuffered.+ bool recheck_unbuffered(std::string& why);+ bool unbuffered() const { return !direct_.empty(); }+ /// Every expert's bytes (n_layers x n_expert blobs).+ uint64_t expert_bytes() const;+ /// #286, unbuffered: assembles the blobs of these pairs ahead of the `blob` calls that will ask for them (the+ /// GPU cache's fill from the profile) - one batch of reads instead of one blob at a time. At most 64 pairs.+ void prefetch_pairs(const std::pair<int32_t, int32_t>* pairs, int64_t n);+ /// Mapped reads: asks the OS for these pairs' blobs ahead (platform::advise_willneed). False when unbuffered,+ /// when read-ahead is off, or before `open`.+ bool advise_pairs(const std::pair<int32_t, int32_t>* pairs, int64_t n) const override;++ const uint8_t* blob(int64_t layer, int64_t expert) override;+ /// Windows, opt-in with STRATA_FILE_RELEASE=1: trim the file mapping's full pages after their expert reaches+ /// VRAM. Never touches the resident complement or staging buffers. Disabled by default.+ uint64_t release(int64_t layer, int64_t expert) override;+ bool pinned(int64_t layer, int64_t expert) const override;+ const uint8_t* device_alias(int64_t layer, int64_t expert) const override;+ bool pcie_layer(int64_t layer) const override;+ bool transient(int64_t layer, int64_t expert) const override;+ bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst) override;+ /// CS-T: advances the assembled blobs' age (see staged_blob).+ void begin_layer(int64_t layer, const int32_t* ids, int64_t k) override;+ /// CS-T: the GGUF in place assembles the missed experts on `fetch_threads_` threads.+ void prefetch(int64_t layer, const int64_t* experts, int64_t n) override;+ /// CS-T: the GGUF in place asks the OS for the predicted experts' pages (PrefetchVirtualMemory on Windows,+ /// madvise(WILLNEED) elsewhere), skipping the RAM copy's.+ void warm(int64_t layer, const int64_t* experts, int64_t n) override;+ /// Not when the reads are unbuffered: the warmed pages would be read through the file cache, a second time.+ bool warms() const override { return !role_ptr_.empty() && direct_.empty(); }+ /// Of the blobs the file tier read for the decode, how many had been warmed for their layer beforehand.+ int64_t warmed_hits() const { return warm_hits_.load(std::memory_order_relaxed); }+ int64_t warmed() const { return warm_count_.load(std::memory_order_relaxed); }+ /// #286: blobs an unbuffered read could not deliver, read through the mapping instead (0 when all went direct).+ int64_t direct_fallbacks() const { return direct_fallbacks_.load(std::memory_order_relaxed); }++ /// Blobs touched, for the driver to report. With `h = 0` this is `48 * k` per token and the number is only+ /// interesting once Phase 3 makes it not so.+ int64_t reads() const override { return reads_; }++private:+ const uint8_t* resident_blob(size_t index) const;+ const uint8_t* mapped_blob(int64_t layer, int64_t expert) const;+ /// The blob's bytes from the mapped file(s) - experts.bin, or the three GGUF role slices - into `dst`.+ bool copy_from_files(int64_t layer, int64_t expert, uint8_t* dst) const;+ bool open_gguf(std::string& err);+ const uint8_t* staged_blob(int64_t layer, int64_t expert);+ bool claim_stage(int64_t key, size_t& v, bool& fill);+ bool fill_stage(size_t v, int64_t layer, int64_t expert, uint8_t* dst);+ void publish_stage(size_t v, int64_t layer, bool ok, double us);+ struct Fill { size_t v; int64_t layer, e; uint8_t* dst; };+ /// The claimed buffers' blobs: one overlapped batch when unbuffered, else the fetch threads' mapped copies.+ void fill_many(const std::vector<Fill>& todo);+ /// #286: the blobs from the drive, unbuffered: every role's 4 KiB-aligned window is read at once (overlapped on+ /// Windows, io_submit on Linux) into this thread's aligned buffer, then copied into place. False when a read fails.+ bool read_direct(const Fill* fills, size_t n) const;+ bool open_direct(std::string& why);+ std::vector<std::string> paths_; ///< the mapped files, as maps_+ std::vector<void*> direct_; ///< #286: per file, an unbuffered handle (Windows) or O_DIRECT fd (Linux)+ std::vector<int> role_file_; ///< 3 x n_layers: index into maps_ / direct_+ /// blobs assembled in the stage buffers (`blob` hands those out): the GGUF in place, or any unbuffered source+ bool staged() const { return !role_ptr_.empty() || !direct_.empty(); }+ static constexpr uint64_t kNoComplement = detail::kNoCacheComplement;+ // ---- CS-T: the GGUF shards in place+ std::string gguf_;+ struct Map {+ const uint8_t* base = nullptr;+ uint64_t bytes = 0;+#if defined(_WIN32)+ void* file = nullptr;+ void* mapping = nullptr;+#else+ int fd = -1;+#endif+ };+ std::vector<Map> maps_;+ std::vector<const uint8_t*> role_ptr_; ///< 3 x n_layers: gate / up / down of the layer's expert 0+ std::vector<uint64_t> role_bytes_; ///< 3 x n_layers: bytes per expert of that role+ // the blobs assembled for `blob()`: a small pool of buffers, one per recent (layer, expert). A buffer is+ // reused only once `kStageAge` layer changes have passed since its blob was last asked for, so a pointer holds+ // through the layer it was asked in and the next ones (the pool computes a layer's misses before the next).+ static constexpr uint64_t kStageAge = 3;+ std::mutex stage_mu_;+ std::vector<std::unique_ptr<uint8_t[]>> stage_buf_;+ std::vector<int64_t> stage_key_;+ std::vector<uint64_t> stage_epoch_, stage_used_;+ std::vector<char> stage_busy_; ///< being filled (outside stage_mu_): never a victim+ std::condition_variable stage_cv_;+ int fetch_threads_ = 8;+ std::atomic<uint64_t> file_blob_bytes_{0}, file_us_{0};+ std::unique_ptr<std::atomic<uint32_t>[]> warm_stamp_; ///< per (layer, expert): epoch_ + 1 when warmed+ std::atomic<int64_t> warm_hits_{0}, warm_count_{0};+ mutable std::atomic<int64_t> direct_fallbacks_{0};+ std::unordered_map<int64_t, size_t> stage_of_;+ uint64_t stage_blob_ = 0;+ uint64_t stage_seq_ = 0;+ uint64_t epoch_ = 0;+ int64_t last_layer_ = -1;+ bool stage_grew_ = false;+ std::atomic<int64_t> ram_reads_{0};+ std::atomic<uint64_t> file_read_bytes_{0};+ const uint8_t* base_ = nullptr;+ int64_t blobs_ = 0;+ int64_t n_layers_ = 0;+ int64_t n_expert_ = 0;+ uint64_t mapped_bytes_ = 0;+ std::vector<uint64_t> layer_offsets_, layer_blob_bytes_;+ void* complement_arena_ = nullptr;+ const uint8_t* complement_host_ = nullptr;+ const uint8_t* complement_device_ = nullptr;+ uint64_t complement_bytes_ = 0;+ std::vector<uint64_t> complement_offsets_;+ detail::ExchangeStorage exchange_storage_; // authoritative when active; original arenas still own memory+ bool complement_pinned_ = false;+ bool complement_partial_ = false; ///< CS-T: only the first complement_pin_limit_ bytes are registered+ uint64_t complement_pin_limit_ = 0;+ uint64_t complement_lock_off_ = 0; ///< the working-set lock covers [lock_off, lock_off + locked)+ bool complement_ready_ = false;+ uint64_t complement_locked_ = 0; ///< bytes held in the working set (pin refused)+ int64_t complement_lent_slots_ = 0;+ std::vector<const uint8_t*> override_; ///< staged exchanges: an evicted expert read from its exchange buffer+ struct Exchange { size_t in, out; int64_t q; uint64_t bytes; };+ std::vector<Exchange> staged_;+ uint8_t* xstage_ = nullptr; ///< exchange buffers, `xstage_cap_ x xstage_blob_`+ bool xstage_pinned_ = false;+ int64_t xstage_cap_ = 0;+ uint64_t xstage_blob_ = 0;+ int64_t exchanges_ = 0;+ std::atomic<int64_t> file_reads_{0};+ int64_t reads_ = 0;+#if defined(_WIN32)+ void* file_ = nullptr;+ void* mapping_ = nullptr;+#else+ int fd_ = -1;+#endif+};++// ================================ THE RESIDENT ARENA (R2.1) ================================+//+// **THE MMAP ABOVE IS THE REVIEW'S FINDING C1 AND IT IS WORTH 2.2x.** Read the comment on `FileExpertSource`+// about the page cache holding all 34 GB: that is true of the expert file ALONE, and it is not what this engine+// does. The PLE/n-gram shard is a 26.8 GB file that the engine also maps, so 34 GB of experts plus 26.8 GB of+// n-gram is 60.8 GB of mapped, file-backed pages on a 63 GB machine - and file-backed pages are exactly the ones+// the OS drops from the standby list when it wants memory. The expert stream then re-faults from disk.+//+// Measured, this round: the pool runs at **~19 GB/s in the engine against 42.8 GB/s in `bench/micro/cpu_s2.cpp`+// on the same machine, reading the same 34 GB**. The micro does `std::fread` into a heap arena and reads+// ordinary (anonymous, resident) memory; the engine reads `MapViewOfFile`. That is the whole difference, and it+// is why this class exists.+//+// It reads `experts.bin` into a `PinnedArena` once at startup, so the expert stream comes from anonymous memory+// the OS has no cheaper reason to evict. `PinnedArena` also tries `cudaHostRegister`, which the GPU needs for+// Phase 3's cache fills and the CPU/PCIe miss split - but registration is best-effort and reported, not assumed.+class ArenaExpertSource : public ExpertSource {+public:+ ArenaExpertSource() = default;+ ~ArenaExpertSource() override;+ ArenaExpertSource(const ArenaExpertSource&) = delete;+ ArenaExpertSource& operator=(const ArenaExpertSource&) = delete;++ /// Allocates and loads `<pack_dir>/experts.bin`. Prints nothing; the caller reports `note()` and the load+ /// rate, because those are the two numbers that say whether the arena is the one that was asked for.+ bool open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int threads, std::string& err,+ uint64_t max_pinned_bytes = 0, const std::string& shared_arena_file = {});+ /// Plan v0.3 P6: a native pack without experts.bin takes its experts from the model's GGUF: `native` is the+ /// --native shard, and native_experts.txt names the other shards beside it (per layer, or per role in v4).+ void set_gguf(const std::string& native) { gguf_ = native; }+ void close();++ bool mapped() const { return base_ != nullptr; }+ int64_t blobs() const { return blobs_; }+ const uint8_t* blob(int64_t layer, int64_t expert) override;+ int64_t reads() const { return reads_; }+ bool pinned(int64_t layer, int64_t expert) const override;+ const uint8_t* device_alias(int64_t layer, int64_t expert) const override;+ void prefetch(int64_t layer, int64_t expert) override;+ uint64_t release(int64_t layer, int64_t expert) override;++ /// What backing was obtained and why, for the startup print. "The engine adapts to the machine it is on" is+ /// only true if the engine says what it got.+ const std::string& note() const { return note_; }+ /// #633: set by `open` when the RAM available is less than the arena needs (a recommendation; it still loads)+ const std::string& ram_warning() const { return ram_warning_; }+ double load_gib_per_second() const { return gib_per_s_; }+ // Loader fix: the load, split. `load_seconds()` is the wall clock of the load loop; the other two are+ // sums over the reader threads (see LoadStats), so on their own they say how much of that wall was spent+ // waiting for the disk and how much in memcpy + FNV-1a.+ double load_seconds() const { return load_seconds_; }+ double load_read_seconds() const { return load_read_s_; }+ double load_copy_seconds() const { return load_copy_s_; }++private:+ void* arena_ = nullptr; ///< the PinnedArena, owned+ void* map_ = nullptr; ///< STRATA_ARENA_MMAP: the arena file, mapped read-only (not the PinnedArena)+ uint64_t map_bytes_ = 0;+ std::vector<const uint8_t*> dev_slice_; ///< device alias of each registered slice (or of the whole range)+ uint64_t slice_bytes_ = 0;+ const uint8_t* base_ = nullptr;+ int64_t blobs_ = 0;+ int64_t n_expert_ = 0;+ int64_t reads_ = 0;+ std::string note_;+ std::string ram_warning_;+ double gib_per_s_ = 0.0;+ double load_seconds_ = 0.0;+ double load_read_s_ = 0.0;+ double load_copy_s_ = 0.0;+ uint64_t pinned_bytes_ = 0;+ std::string gguf_;+};++/// Plan v0.3 P6: checks native_experts.txt's GGUF spans against the files, before anything is read: each layer's+/// gate/up/down at its recorded (file, offset) must be that tensor (`blk.L.ffn_<role>_exps.weight`), of the+/// layout's type and dimensions, and inside the file. `native` is the --native shard (see set_gguf).+bool check_experts_gguf(const std::string& native, const strata::kernels::cpu::ExpertLayout& lay, std::string& err);+/// Fills `dst` (lay.total bytes, the experts.bin layout) from the GGUF files, one role at a time.+/// `unbuffered`: each chunk read past the file cache (Windows); `ready`: layer l is written only once+/// *ready > l + 1 (an arena that is still being registered).+LoadStats load_experts_gguf(const std::string& native, uint8_t* dst, const strata::kernels::cpu::ExpertLayout& lay,+ int threads, bool unbuffered = false, const std::atomic<int>* ready = nullptr);++} // namespace strata::corediff --git a/sycl/include/strata/core/mtp.hpp b/sycl/include/strata/core/mtp.hppindex c5726b461..dc515ad58 100644--- a/sycl/include/strata/core/mtp.hpp+++ b/sycl/include/strata/core/mtp.hpp@@ -44,7 +44,7 @@ public:/// Loads `rt_dir` (from tools/mtp_rt.py) and allocates the layer's K/V and buffers for up to `max_t` rows./// Call before the VRAM expert tier is sized: this takes ~0.9 GB.bool load(const std::string& rt_dir, const ModelGeometry& g, SessionState& ss, int max_t, std::string& err,- int64_t window = 32768);+ int64_t window = 32768, const MtpDrafter* shared = nullptr);/// The prompt's length: prefill() skips the cells the attention window can never reach again.void set_prompt_len(int64_t n) { prompt_len_ = n; }/// At most this many drafts per round (below max_t - 1): a window longer than the MTP's comes from elsewhere.@@ -57,6 +57,21 @@ public:if (!capture_step(j, false, err)) return false;return true;}+ /// --mtp-hnorm stream (opt-in; before the first draft or prefill): pre_fc_norm_hidden normalizes each+ /// hyper-connection stream on its own, as llama.cpp's qwen4exp MTP graph does, instead of one RMS over all four.+ void set_hnorm_per_stream(bool on) { hnorm_stream_ = on; }+ bool hnorm_per_stream() const { return hnorm_stream_; }+ /// --mtp-q4 (opt-in; before load): the draft layer's Q8_0 projections and its draft head run from 4-bit (Q4_0)+ /// copies made at load/bind - fewer bytes per draft step; drafts only, the verify window decides every token.+ /// (The prompt path's batched K/V pass keeps the Q8_0 originals.)+ void set_q4(bool proj, bool head) { q4_ = proj; q4_head_ = head; }+ /// --mtp-draft-vocab FILE (opt-in; before bind): the draft head's token subset from FILE instead of+ /// rt/draft_vocab.bin (e.g. data/draft_vocab_en.bin, 40K tokens)+ void set_draft_vocab(const std::string& path) { dvocab_path_ = path; }+ /// STRATA_MTP_TOP2=1 (diagnostic): draft j's runner-up token in the last draft() (-1 = unknown)+ static bool top2_env();+ int32_t top2(int j) const { return j >= 0 && j < (int) top2_.size() ? top2_[(size_t) j] : -1; }+ int max_t() const { return max_t_; }uint64_t vram_bytes() const { return vram_; }/// The draft layer's K/V state (read-only: --serve's STRATA_STATE_HASH check hashes it)const QsaState& kv_state() const { return st_; }@@ -67,11 +82,18 @@ public:/// the draft head over rt/draft_vocab.bin's subset. The expert cache is sized before bind(), so it reserves this.uint64_t bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const;/// The main model's embedding and head, and the verify window's final residuals (T rows, hc*n_embd each).- bool bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err);+ bool bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err,+ const MtpDrafter* shared = nullptr);/// Prompt cells [cell0, cell0 + n): residual rows `R_rows` (device, hc*n_embd each) and `next_tokens` (host,- /// the token at position cell+1). Runs in batches of up to max_t rows.- bool prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err);+ /// the token at position cell+1). Runs in batches of up to max_t rows. `sync` false: returns without waiting+ /// for the drafter's stream (the caller orders on it: `stream()`).+ bool prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err,+ bool sync = true);+ /// --pipeline-windows: capture the prefill graphs and size its input records for windows of up to max_t rows now,+ /// so a later prefill(sync = false) of a window neither captures nor allocates (both wait for the device).+ bool prepare_prefill(std::string& err);+ dpct::queue_ptr stream() const { return cs_; }/// One round: catch-up over T cells from `p` (rows = the window's final residuals, `tokens` = the window's/// argmaxes: row t pairs R_{p+t} with the token at p+t+1), then the draft chain from row `a` (the last@@ -91,8 +113,34 @@ public:/// Coupled mode with penalties: the history the next draft() chain starts from - what the session holds after the/// window's commit (`tail`) and the window's pick at its last accepted row (`next`, the next window's row 0).void set_draft_history(const int32_t* tail, int64_t n_tail, int32_t next);+ void set_ple_session(SessionState* s) { ple_ss_ = s; }bool coupled() const { return coupled_active_; }+ // ---- --pipeline-windows 2: the chain as one asynchronous launch (the round and its steps back to back, no host+ // wait), its first `n_force` steps fed the given tokens instead of their own picks (teacher forcing: the drafts of+ // a window already in flight), each output read once the event after its step has completed.+ /// Before `load`: the round/step graphs get the forcing kernel (a no-op while its token is -1), and the drafter's+ /// stream the highest priority (STRATA_MTP_PRIORITY=0: the default priority).+ void set_force_capture(bool on) { force_on_ = on; }+ /// The rows the next round reads (null: the bound `window_R`), copied into the bound buffer before the round.+ void set_source_R(const float* rows) { src_R_ = rows; }+ /// Capture the round graphs for T = 1..max_t and every step graph now (a capture syncs the drafter's stream).+ bool prepare_chain(std::string& err);+ /// The catch-up over T cells from `p` (as draft()), then `n_out` outputs from row `a`: output j is the chain's+ /// own pick, and step j (1 <= j <= n_force) takes force[j - 1] as its input token instead of output j - 1.+ /// `n_early`: an event after each of the first `n_early` outputs (chain_outputs_ready).+ bool chain_launch(int T, const int32_t* tokens, int64_t p, int a, const int32_t* force, int n_force, int n_out,+ int n_early, std::string& err);+ /// 1: every output is in chain_tok()/chain_prob(); 0: still running; -1: an error.+ int chain_poll(std::string& err);+ /// How many of the chain's first outputs (up to `n_early`; all of them once the chain is done) have landed in+ /// chain_tok()/chain_prob(); -1: an error. A window's size is often decided by its first outputs (a draft below+ /// spec_min_p ends it), so the next launch need not wait for all of them.+ int chain_outputs_ready(std::string& err);+ bool chain_live() const { return chain_live_; }+ const int32_t* chain_tok() const { return chain_tok_; }+ const float* chain_prob() const { return chain_prob_; }+double ms_draft = 0, ms_prefill = 0;int64_t rounds = 0;@@ -119,6 +167,14 @@ public:private:bool record_forward(int T, int step_row0, dpct::queue_ptr cs,std::string &err);+ /// The layer's front for T rows at step rows [row0, +T): the embedding, the fc projections, the attention+ /// hyper-connection read (R_, inj_, mixed_) and the K/V appended.+ bool record_front(int T, int row0, dpct::queue_ptr cs, std::string &err);+ /// The rest for row 0 at step row `step_row`: the attention from the q projection, the MLP, the final mixer,+ /// the head, the draft and its probability. Needs row 0's R_, inj_ and mixed_ (its q8_1 rows in xq_).+ bool record_rest(int step_row, dpct::queue_ptr cs, std::string &err);+ void norm_rope(float *data, const float *gamma, int rows, int cols,+ const int32_t *p, dpct::queue_ptr cs);bool capture_prefill(int T, std::string& err);bool capture_prefill_dev(int T, std::string& err); ///< E-4: without the mapped staging (inputs copied on device)bool capture_round(int T, bool coupled, std::string& err);@@ -141,12 +197,38 @@ private:const ModelGeometry* g_ = nullptr;SessionState* ss_ = nullptr;+ SessionState* ple_ss_ = nullptr;const WeightTable* wt_ = nullptr;const NativeHead* head_ = nullptr;const float* window_R_ = nullptr;int max_t_ = 0;int device_ = -1; ///< the device `load` ran on: the public calls switch to it (layer split)int max_drafts_ = 1 << 30;+ bool hnorm_stream_ = false;+ bool q4_ = false, q4_head_ = false;+ uint8_t* dense4_ = nullptr; ///< --mtp-q4: Q4_0 copies of the Q8_0 tensors+ std::vector<std::pair<std::string, uint64_t>> q4_off_;+ int dhead_type_ = -1; ///< the draft head subset's ggml type (the main head's, or Q4_0)+ std::string dvocab_path_;+ std::string vocab_file() const { return dvocab_path_.empty() ? rt_dir_ + "/draft_vocab.bin" : dvocab_path_; }+ /// a projection's weights for the draft layer's own pass: the Q4_0 copy under --mtp-q4, else the Q8_0 original+ const void* wq(const char* name, int& type) const;+ bool make_q4_dense(const std::vector<uint8_t>& blob, std::string& err);+ bool make_q4_head(std::string& err);+ void record_top2(int j);+ std::vector<int32_t> top2_, dvocab_host_;+ std::vector<float> lg_host_;+ // --pipeline-windows 2 (chain_launch)+ bool stage_source_R(int T, std::string& err); ///< set_source_R's rows into the bound buffer+ bool force_on_ = false, chain_live_ = false;+ const float* src_R_ = nullptr;+ int32_t *h_force_ = nullptr, *m_force_ = nullptr; ///< the forced tokens (mapped), -1 = the step's own pick+ dpct::event_ptr ev_chain_ = nullptr;+ dpct::event_ptr ev_step_[8] =+ {}; ///< after each of the first n_early outputs+ int steps_seen_ = 0, chain_n_ = 0, chain_early_ = 0;+ int32_t chain_tok_[8] = {};+ float chain_prob_[8] = {};int64_t n_vocab_ = 0;uint64_t vram_ = 0;dpct::queue_ptr cs_ = &dpct::get_in_order_queue();@@ -154,12 +236,19 @@ private:dpct::experimental::command_graph_exec_ptr prefill_dev_exec_[9] = {};int32_t* pf_dev_ = nullptr; ///< E-4: a prompt's rows' token / step / position records, uploaded at onceint64_t pf_cap_ = 0; ///< its capacity in ints+ dpct::queue_ptr side_ =+ &dpct::get_in_order_queue(); // the shared expert's branch of the draft+ // graphs (CUDA)+ dpct::event_ptr sh_fork_ = nullptr, sh_join_ = nullptr;dpct::experimental::command_graph_exec_ptr round_exec_[9] = {};struct Tensor { std::string name, kind; int64_t rows = 0, cols = 0; uint64_t off = 0, bytes = 0; };std::vector<Tensor> tensors_;uint8_t* dense_ = nullptr;uint8_t* experts_ = nullptr;+ // Slot drafters borrow immutable weights and head; each still owns its state and scratch.+ bool owns_weights_ = true;+ bool owns_draft_head_ = true;void* state_arena_ = nullptr;QsaState st_;void* arena_ = nullptr;@@ -178,6 +267,8 @@ private:int64_t window_ = 0; // attention over the last window_ cells (0 = every cell)int64_t prompt_len_ = 0;float* probs_ = nullptr;+ uint8_t* arg_scratch_ = nullptr; ///< argmax_rows' and row_top_prob_split's partials and counters+ uint8_t* top_scratch_ = nullptr;// deviceint32_t *tok_ = nullptr, *step_ = nullptr, *pos_ = nullptr, *row_ = nullptr, *ident_ = nullptr;float *Rin_ = nullptr, *R_ = nullptr, *emb_ = nullptr, *en_ = nullptr, *e2_ = nullptr, *hn_ = nullptr, *h2_ = nullptr;diff --git a/sycl/include/strata/core/remote_experts.hpp b/sycl/include/strata/core/remote_experts.hppindex 097d82d99..b1e424f84 100644--- a/sycl/include/strata/core/remote_experts.hpp+++ b/sycl/include/strata/core/remote_experts.hpp@@ -27,7 +27,7 @@ public:bool open(int device, int slots, int64_t layers, int64_t experts,const std::vector<std::pair<int32_t, int32_t>>& ranked,const ExpertCache& primary, ExpertSource& source,- std::vector<uint8_t>& claimed, std::string& err);+ std::vector<uint8_t>& claimed, std::string& err, bool auto_size = false);void close();/// `kind` is the primary verifier's classification (-1 = CPU candidate),@@ -35,6 +35,9 @@ public:bool begin(int64_t layer, const float* x, const int32_t* ids, int64_t n_tok,int64_t k, const int32_t* kind, const int32_t* primary_res,std::string& err);+ /// This helper's cache holds (layer, expert): begin() will take its rows unless the plan gave them away.+ bool holds(int64_t layer, int32_t expert) const { return cache_.slot_of(layer, expert) >= 0; }+ bool optimized_decode() const { return false; } // SYCL port: no RemoteExpertOptbool owns(int64_t index) const { return owned_[(size_t) index] != 0; }bool finish(float* out, std::string& err);int64_t resident() const { return cache_.resident(); }diff --git a/sycl/include/strata/core/verify.hpp b/sycl/include/strata/core/verify.hppindex 0db24e25f..2501122db 100644--- a/sycl/include/strata/core/verify.hpp+++ b/sycl/include/strata/core/verify.hpp@@ -31,6 +31,8 @@#include "strata/kernels/sampler.hpp"#include <atomic>+#include <chrono>+#include <map>#include <cstdint>#include <chrono>#include <string>@@ -39,6 +41,7 @@namespace strata::core {class NativeHead;+class RemoteExpertOpt;/// The CPU pool for a window: x_f (n_tok, n_embd), ids (n_tok, k) -> out (n_tok * k, n_embd), hit rows zeroed.using PoolMultiFn = void (*)(void* user, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k, float* out,@@ -46,6 +49,7 @@ using PoolMultiFn = void (*)(void* user, const float* x_f, const int32_t* ids, istruct VerifyHits {const int32_t* d_res = nullptr; ///< device [n_layers * n_expert] slot or -1+ const int32_t* h_res = nullptr; ///< host [n_layers * n_expert] slot or -1 (when all >= 0 in stage: zero-doorbell)const uint8_t* cache_base = nullptr; ///< slot 0 of the VRAM expert arenaconst uint64_t* slot_off = nullptr; ///< E-6: host per-slot offsets when slots differ in size (null: slot * blob)int64_t n_slots = 0; ///< E-6: how many (for the device copy)@@ -58,6 +62,7 @@ public:~Verifier();Verifier(const Verifier&) = delete;Verifier& operator=(const Verifier&) = delete;+ void set_remote_expert_opt(RemoteExpertOpt* opt) { remote_opt_ = opt; } // before init/capture/// The watchdog's view of the window in flight (issue #31): the layer, the GPU's sequence, the flags.void diag(std::FILE* f) const;@@ -122,14 +127,60 @@ public:static int64_t handoff_floats(const ModelGeometry& g) { return (int64_t) g.hc * g.n_embd + g.n_embd + g.hc; }/// Keep the first `n_keep` (1..T) tokens of the last window; advances `ss.ple_prev` by them.- /// `wait = false` (SYCL port, single stage only): the commit graph is launched and left running so the drafter's- /// round (its own queue, reads only the window's residuals) overlaps it; `commit_finish()` before the next run.- bool commit(int n_keep, std::string& err, bool wait = true);- bool commit_finish(std::string& err);/// SYCL port: capture every window graph now (one per window size) instead of on first use, so the first/// request does not pay for them (a 2,400-node graph takes tens of ms to finalize on this backend).bool warm(std::string& err);- /// (upstream 0.1.32; the port maps it onto commit_finish, verify.cpp) commit() returns without waiting for its graph (a single-GPU session sets it): the next window follows it on+ bool commit(int n_keep, std::string& err);++ // ================================ SEVERAL SEQUENCES IN ONE WINDOW ================================+ //+ // A batch window holds S INDEPENDENT sequences, one token each: row s is slot s, at slot s's own position,+ // reading and writing slot s's own state (GDN recurrence and conv history, QSA K/V and indexer, PLE history),+ // which lives in `slots[s]` - a session carved like this verifier's own (same layer range, same max_cells).+ // Everything that is per row already (hyper-connections, dense projections, router, shared expert, the+ // routed experts on the GPU and the CPU, the head) runs once over the S rows, so the weights are read once+ // per window for all the sequences. Row s's arithmetic is the single-token window's, so a slot's greedy+ // tokens are its solo greedy tokens (modulo the multi-token CPU kernel choice: STRATA_IQ_MT_MIN=1).+ //+ // Greedy only, no drafts (MTP) in a batch window. `init_slots` once after `init` (S <= max_t); a layer+ // split's stages each get their own sessions, and run_slots/commit_slots continue into the next stage.+ bool init_slots(const std::vector<SessionState*>& slots, std::string& err);+ int n_slots() const { return (int) slots_.size(); }+ /// One batch window over slots [0, S): tokens[s] at positions pos[s]; out[s] = the greedy pick after it.+ bool run_slots(int S, const int32_t* tokens, const int64_t* pos, PoolMultiFn pool, void* user, int32_t* out,+ std::string& err);+ /// The same over the S slots `rows` (row t is slot rows[t], any distinct slots in any order): the slots not+ /// listed are not touched, so an idle slot keeps its state (a finished conversation it may continue later).+ bool run_slot_rows(const int* rows, int S, const int32_t* tokens, const int64_t* pos, PoolMultiFn pool, void* user,+ int32_t* out, std::string& err);+ /// Keep every row of the last batch window.+ bool commit_slots(std::string& err);+ /// Commit an accepted prefix in each contiguous slot group of the last window. `keep` has+ /// one entry per slot (indexed by slot ID), each in 1..that slot's group length.+ bool commit_slot_prefixes(const int* keep, std::string& err);+ /// --batch-mtp: slot rotation makes many row layouts, so bound the captured batch graph pairs (LRU). 0 = unbounded.+ void set_batch_graph_limit(size_t n) { batch_graph_limit_ = n; }++ // ---- The stages of a layer split as a PIPELINE. A batch window over the slot GROUP+ // [base, base + S) is launched on ONE stage with its commit right behind it on the stage's stream (a batch window+ // keeps every row, so the commit needs no host decision), and the host serves the rings of every stage that has+ // a window in flight from one thread (batch_poll does not block). Stage k can then run group g while stage k+1+ // runs group g-1. Rows of group `base` use hand-off rows [base, base + S), so groups never share a hand-off row.+ bool batch_launch(int base, int S, const int32_t* tokens, const int64_t* pos, std::string& err);+ /// 1 = this stage's window and commit are done (the last stage's picks are in batch_out), 0 = still running,+ /// -1 = an error (err). Serves every layer that has rung so far.+ int batch_poll(PoolMultiFn pool, void* user, std::string& err);+ bool batch_busy() const { return b_running_; }+ /// A slot's sampling (temperature / top_p / top_k / min_p / seed; penalties are not applied in batch windows):+ /// its row is drawn again on the last stage with Philox(seed, position), as a solo window draws it. Greedy by+ /// default. Set on the first stage, it reaches the last.+ void set_slot_sampling(int slot, const strata::kernels::SamplerParams& sp) {+ if (slot >= 0 && slot < (int) slot_sp_.size()) slot_sp_[(size_t) slot] = sp;+ if (next_) next_->set_slot_sampling(slot, sp);+ }+ const int32_t* batch_out() const { return b_out_; }+ bool last_stage() const { return g_ != nullptr && le_ == g_->n_layers; }+ /// commit() returns without waiting for its graph (a single-GPU session sets it): the next window follows it on/// the same stream and the drafter reads nothing it writes, so it overlaps the draft. Whoever reads or writes/// the session from another stream or the host afterwards (a new request, a checkpoint, a snapshot, the prompt/// path, the end of a run) calls wait_commit() first. STRATA_COMMIT_SYNC=1 keeps the wait.@@ -138,6 +189,45 @@ public:/// false with `err` when it failed. Free when nothing is pending.bool wait_commit(std::string& err);+ // ---- PIPELINED WINDOWS (--pipeline-windows, a layer split on two GPUs). One conversation's windows with the+ // stages overlapped: stage 0 runs window K+1 while stage 1 still runs window K. The same window as `run`, driven+ // without blocking the host, so one host thread keeps a window in flight on each stage (the batch pipeline's+ // pattern, batch_launch / batch_poll, for one sequence with drafts). Two verifiers per stage (one per window+ // parity) share the stage's stream and each has its own hand-off. `pl_launch` stages and launches (it never+ // captures: `capture_all` first, with nothing in flight), `service` serves the layers whose doorbells have rung+ // and returns at once, `done` polls the window's completion, `pl_finish` reads the picks, `pl_commit_async`+ // queues the commit. Nothing chains to `next_`: the caller drives every stage.+ /// The compute stream to use instead of a private one (the two verifiers of one stage share it). Before `init`.+ void set_stream(dpct::queue_ptr s) { ext_stream_ = s; }+ /// Every layer copies the token rows to the host (doorbell_publish), not only the layers with a routed expert+ /// outside the VRAM tier by the device's residency table: with windows in flight the adaptive tier marks an+ /// expert evicted on the host (the pool then computes it on the CPU) before the device table follows. Also turns+ /// the device-planned layers (E-6) off. Before `init`.+ void set_always_publish(bool on) { always_publish_ = on; }+ dpct::queue_ptr stream() const { return cs_; }+ int device() const { return device_; }+ /// Capture every window size and the commit graph now (a capture syncs the stream: never with a window in flight).+ bool capture_all(std::string& err);+ bool pl_launch(int T, const int32_t* tokens, int64_t pos0, std::string& err);+ /// Stage a window ahead of its launch (positions, and the PLE rows from `ple_prev` = the two tokens before the+ /// window as they WILL be, their pages prefetched). A later `pl_launch` of the same window (T, pos0, tokens, and+ /// `ss.ple_prev` equal to `ple_prev` by then) skips the staging; anything else stages again.+ bool prestage(int T, const int32_t* tokens, int64_t pos0, const int32_t ple_prev[2], std::string& err);+ /// 1: every layer served; 0: the GPU has not reached the next layer yet; -1: an error (`err`).+ int service(PoolMultiFn pool, void* user, std::string& err);+ bool in_flight() const { return fl_active_; }+ /// The window's graph (and its profile copy) completed; false while it runs. An error sets `err`.+ bool done(std::string& err);+ /// After `done`: the profile, the last stage's host sampling and picks (`out` may be null on an earlier stage).+ bool pl_finish(int32_t* out, std::string& err);+ /// The commit without a host sync; `ss.ple_prev` advances now (host side). A second call for the same window+ /// (after its state was restored) replays it with another count.+ bool pl_commit_async(int n_keep, std::string& err);+ /// Fold another verifier's counters and GPU profile into this one's (the two verifiers of one stage report once).+ void absorb_stats(Verifier& o);+ /// The watchdog's line for a pipelined verifier: in flight, layers served, the GPU's ring and flags, its events.+ void diag_pipelined(std::FILE* f, const char* name) const;+/// Measurement hook (STRATA_LOGPOS): after run(), write one line per row t of the last window's head -/// "pos target logprob top top_logprob hit extra_logprob target_logprob_without_extra" - where row t is the/// distribution at pos0 + t, targets[t] is the token at pos0 + t + 1, extra_logprob is the log-probability of@@ -171,7 +261,63 @@ public:std::string profile_report();private:+ RemoteExpertOpt* remote_opt_ = nullptr;bool capture(int T, std::string& err);+ // batch windows (see init_slots)+ std::vector<SessionState*> slots_;+ bool batch_rec_ = false; ///< record_window is capturing a batch window+ int row_base_ = 0; ///< ... its hand-off rows start here (a pipeline group's own rows)+ int brow_[8] = {}; ///< ... and row t is slot brow_[t]+ bool last_batch_ = false; ///< the last run was a batch window (set_plan_slot: one group)+ std::map<std::vector<int>, dpct::experimental::command_graph_exec_ptr>+ exec_bm_, commit_bm_; ///< full row layout avoids slot-ID collisions+ std::map<std::vector<int>, uint64_t> bm_used_; ///< last use of each captured layout (LRU, only with a graph limit)+ uint64_t bm_tick_ = 0;+ size_t batch_graph_limit_ = 0; ///< 0: keep every captured batch graph (0.1.39); N: LRU-evict beyond N layouts+ int last_rows_[8] = {}; ///< the slots of the last batch window's rows+ std::vector<int> bkey(const int* rows, int S, int hbase) const { // #871: the doorbell variant has its own graphs+ std::vector<int> k = batch_key(rows, S, hbase);+ k.push_back(ar_off_ ? 1 : 0);+ return k;+ }+ static std::vector<int> batch_key(const int* rows, int S, int hbase) {+ std::vector<int> k;+ k.reserve((size_t) S + 1);+ k.push_back(hbase);+ for (int t = 0; t < S; ++t) k.push_back(rows[t]);+ return k;+ }+ // batch_launch / batch_poll+ bool b_running_ = false;+ int64_t b_k_ = 0, b_steps_ = 0;+ std::chrono::steady_clock::time_point b_last_;+ int32_t b_out_[8] = {};+ std::vector<strata::kernels::SamplerParams> slot_sp_;+ bool sample_rows(int S, std::string& err); ///< the sampled slots' rows of the last batch window+ int32_t* h_commitb_ = nullptr; int32_t* m_commitb_ = nullptr; // per slot [1, 0, pos, -1 ..], stride 2 + max_t+ int32_t* commitb_ = nullptr;+ float* tail_snap_b_ = nullptr; ///< per (slot, QSA layer) indexer tail snapshot+ void* arena_b_ = nullptr;+ int64_t last_pos_b_[8] = {};+ bool capture_batch(const int* rows, int S, int hbase, std::string& err);+ 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)+ 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;+ unsigned long long* prof_pin_ = nullptr; ///< pinned host copy of the stamps (pipelined windows)+ bool fl_active_ = false, fl_prof_ = false, fl_ple_ = false, commit_live_ = false, pl_prestaged_ = false;+ int fl_T_ = 0;+ int64_t fl_k_ = 0, fl_total_ = 0;+ double fl_since_ms_ = 0, fl_flush_ms_ = 0, fl_launch_ms_ = 0;+ int32_t pl_prev_[2] = {-1, -1};+ std::vector<uint32_t> pl_ple_rows_; ///< the window's PLE rows (T x PLE_N_HEADS), gathered when layer 0 is served+ bool capture_commit_batch(const int* rows, int S, int hbase, std::string& err);+ bool stage_batch(const int* rows, int S, int hbase, const int32_t* tokens, const int64_t* pos, std::string& err);strata::kernels::SamplerParams sampling_ = [] {strata::kernels::SamplerParams s;s.greedy = true;@@ -183,8 +329,19 @@ private:bool head_sampling_ = true; ///< set_head_samplingint device_ = -1; ///< the device `init` ran on: run/commit switch to it (layer split)std::atomic<bool> released_{false}; ///< #267: release_gpu_waits ran (maybe on the watchdog thread): no more windows+ bool all_resident_ = false; ///< 100% of experts in [lb_, le_) resident in VRAM: zero-doorbell graph+ /// #871: the zero-doorbell graph plans from the device residency table alone, so it is only right while every+ /// expert of the stage is in VRAM. A prompt loan, a VRAM shrink or an adaptive swap marks some -1 for a while:+ /// every window then runs the doorbell graph (exec_nr_ / the batch key's top bit), the same as a stage that never+ /// was all-resident. refresh_ar() looks at the host table before each window.+ bool ar_off_ = false;+ bool ar_on() const { return all_resident_ && !ar_off_; }+ void refresh_ar();+ uint32_t* h_plan_err_ = nullptr; uint32_t* m_plan_err_ = nullptr; // set by resident_plan on a -1 (all-resident graph)+ const int32_t* h_res_ = nullptr; ///< the host residency table (VerifyHits::h_res)bool device_plan_ = false; ///< E-6: resident-only layers planned on the device (STRATA_VERIFY_DEVICE_PLAN)uint32_t* skip_ = nullptr; ///< E-6: per group, the ring whose plan the device built (0: the host's)+ unsigned* qcnt_ = nullptr; ///< S26 STRATA_QFUSE: the HC read's q8_1 group counters (n_embd / 32)unsigned long long* slot_off_d_ = nullptr; ///< E-6: the slot offsets on the deviceint64_t lb_ = 0, le_ = -1; ///< set_stage: the layers this verifier runs (-1: to the last)const float* hand_in_ = nullptr;@@ -192,9 +349,10 @@ private:Verifier* next_ = nullptr;void* next_user_ = nullptr;bool ple_stage() const { return lb_ <= 1 && 1 < le_; } ///< holds layer 1, where the PLE block runs+ void stage_inputs(int T, const int32_t* tokens, int64_t pos0);+ bool staged_ = false;+ bool copy_used_ = false;bool capture_commit(std::string& err);- int pending_commit_ = 0; ///< n_keep of a launched, unfinished commit (0: none)- std::chrono::steady_clock::time_point pending_commit_t0_{};bool record_window(int T, dpct::queue_ptr cs, std::string &err);// #649: STRATA_VERIFY_TRACE=1 - a host event ring (trace_ev) and GPU breadcrumbs: the profiler's stamp points,// per layer and token group, written to mapped memory (null when the trace is off)@@ -216,6 +374,8 @@ private:VerifyHits hits_;const NativeHead* head_ = nullptr;int max_t_ = 0;+ float* ple_key_ = nullptr; ///< STRATA_PLE_BATCH: the window rows' PLE key / value projections+ float* ple_val_ = nullptr;int last_t_ = 0;int64_t last_pos0_ = 0;int32_t last_tokens_[8] = {};@@ -223,7 +383,12 @@ private:dpct::queue_ptr cs_ = &dpct::get_in_order_queue();float* dbgR_ = nullptr; ///< SYCL port debug: R (token 0) after every layer, n_layers x n_embdfloat* dbgM_ = nullptr; ///< SYCL port debug: mixed_ (token 0) after every layer+ dpct::queue_ptr sh_cs_ = &dpct::get_in_order_queue();+ dpct::event_ptr ev_fork_ = nullptr, ev_join_ = nullptr;dpct::experimental::command_graph_exec_ptr exec_[9] = {};+ dpct::experimental::command_graph_exec_ptr exec_nr_[9] =+ {}; // #871: the doorbell variant of a stage that is all-resident+ // otherwisedpct::experimental::command_graph_exec_ptr commit_exec_ = nullptr;// mapped staging (host pointer, device alias)@@ -267,6 +432,7 @@ private:float *ple_ = nullptr, *emb_ = nullptr, *R_ = nullptr, *mixed_ = nullptr, *bo_ = nullptr;float *inj_ = nullptr, *inj2_ = nullptr, *lo_ = nullptr, *rs_ = nullptr, *xn_ = nullptr;uint8_t* xq_ = nullptr; // T columns of q8_1+ uint8_t* sh_xq_ = nullptr; // T columns of q8_1 for shared expert branchfloat *qkv_L_ = nullptr, *h_L_ = nullptr, *gate_L_ = nullptr, *beta_L_ = nullptr; // per GDN layerfloat *z_ = nullptr, *y_ = nullptr, *y_dummy_ = nullptr;float *qfull_ = nullptr, *qcur_ = nullptr, *kcur_ = nullptr, *vcur_ = nullptr, *idx_raw_L_ = nullptr;@@ -285,6 +451,8 @@ private:void* hit_scratch_ = nullptr;float *head_mixed_ = nullptr, *head_inj_ = nullptr, *head_logits_ = nullptr;uint16_t* sh_bf16_ = nullptr;+ uint8_t* arg_scratch_ = nullptr; ///< argmax_rows' partials and counters+ int32_t* one_ = nullptr; ///< device {1}: the n_keep of a one-token window, which commits itselffloat *sh_gate_ = nullptr, *sh_up_ = nullptr, *sh_g_ = nullptr;float* hist_snap_ = nullptr; // T * NG_HIST * NG_HC_DIMint64_t cap_ = 0, max_blocks_ = 0, attn_scratch_floats_ = 0;diff --git a/sycl/include/strata/kernels/dp4a.hpp b/sycl/include/strata/kernels/dp4a.hppindex 89f7ba86a..7084bcb5d 100644--- a/sycl/include/strata/kernels/dp4a.hpp+++ b/sycl/include/strata/kernels/dp4a.hpp@@ -24,6 +24,10 @@#include <cstdint>#include <time.h>+#if defined(STRATA_HIP_GFX906)+#include <cuda_runtime.h> // gfx906: the compat layer (__forceinline__, __nanosleep, __dp4a)+#endif+#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP < 610__device__ __forceinline__ int strata_dp4a(const int a, const int b, const int c) {const int8_t* a8 = (const int8_t*) &a;diff --git a/sycl/include/strata/kernels/mrope.hpp b/sycl/include/strata/kernels/mrope.hppindex ed27cf809..ab659ffaa 100644--- a/sycl/include/strata/kernels/mrope.hpp+++ b/sycl/include/strata/kernels/mrope.hpp@@ -18,6 +18,9 @@#include <sycl/sycl.hpp>#include <dpct/dpct.hpp>#include <cstdint>+#if defined(__HIPCC__) && defined(STRATA_HIP_GFX906) // PR #638: the gfx906 compat build only+#include <hip/hip_runtime.h>+#endif#include "strata/kernels/rope_scaling.hpp"diff --git a/sycl/include/strata/kernels/native_mmvq.hpp b/sycl/include/strata/kernels/native_mmvq.hppindex 4b3e82a6f..370a90393 100644--- a/sycl/include/strata/kernels/native_mmvq.hpp+++ b/sycl/include/strata/kernels/native_mmvq.hpp@@ -41,6 +41,9 @@ bool native_mmvq_multi_exact();void native_quantize_q8_1(const float* x, void* x_q8_1, int n_in, int ncols,void* stream);+void native_swiglu_quantize_q8_1(const float* gate, const float* up, void* x_q8_1,+ int n_in, int ncols, void* stream);+void native_q5_k_mmvq(const void* weights, const void* x_q8_1, float* y,int n_in, int n_out, int ncols, void* stream);@@ -93,6 +96,24 @@ void native_q5_0_f32(const void* weights, const float* x, void* scratch_q8_1,void native_q8_0_mmvq(const void* weights, const void* x_q8_1, float* y,int n_in, int n_out, int ncols, void* stream);+/// STRATA_Q8_PACKED=1 (opt-in): a lossless load-time repack of a Q8_0 matrix into a qs plane (n_out x n_in int8)+/// followed by a d plane (n_out x n_in / 32 fp16), the same bytes (34 per 32 values). A registered matrix's+/// native_q8_0_mmvq calls (keyed by its GGUF-layout device pointer, which stays valid for the prompt path) read the+/// packed copy instead; every output is bitwise equal to the GGUF-layout kernels.+bool native_q8_0_packed_enabled();+bool native_q8_0_packed_eligible(int n_in, int n_out);+void native_q8_0_pack_host(const void* gguf_blocks, void* out, int n_in, int n_out);+void native_q8_0_packed_register(const void* gguf_weights, const void* packed, int n_in, int n_out);+void native_q8_0_packed_unregister(const void* gguf_weights);++/// STRATA_Q6_PACKED=1 (opt-in): a packed copy of a Q6_K matrix (the output heads) - the same bytes as ql / qh /+/// scales / d planes - that native_q6_k_mmvq calls on `weights` read instead (bitwise equal outputs). The copy is+/// owned here: native_q6_k_pack builds it from the device matrix (false: not eligible or failed; nothing changes),+/// native_q6_k_unpack frees it. STRATA_Q6P_SELFTEST=1 checks it bitwise and times it at load.+bool native_q6_k_packed_enabled();+bool native_q6_k_pack(const void* weights, int n_in, int n_out, const char* what);+void native_q6_k_unpack(const void* weights);+void native_q8_0_f32(const void* weights, const float* x, void* scratch_q8_1,float* y, int n_in, int n_out, int ncols, void* stream);@@ -111,5 +132,9 @@ bool native_mmvq_supported(int ggml_type) noexcept;std::size_t native_mmvq_weight_bytes(int ggml_type, int n_in, int n_out);void native_mmvq(int ggml_type, const void* weights, const void* x_q8_1, float* y,int n_in, int n_out, int ncols, void* stream);+/// S26 STRATA_LFUSE: native_mmvq(w1 -> y1) and native_mmvq(w2 -> y2), same type / shape / input, in ONE launch,+/// bitwise the two calls. Returns false (nothing launched) where that is not the case (Q8_0, 2-8 columns only).+bool native_mmvq_pair(int ggml_type, const void* w1, const void* w2, const void* x_q8_1, float* y1, float* y2,+ int n_in, int n_out, int ncols, void* stream);} // namespace strata::kernelsdiff --git a/sycl/setup_intel.py b/sycl/setup_intel.pyindex 0174248ec..5e01db413 100644--- a/sycl/setup_intel.py+++ b/sycl/setup_intel.py@@ -86,10 +86,6 @@ def sycl_engine():exe = next((b for b in (ROOT / "build-sycl-aot" / "strata", ROOT / "build-sycl" / "strata") if b.exists()), None)if exe is None:return None, "it is not built (sycl/tools/build.sh; docs/INTEL.md)"- if not shutil.which("docker"):- return None, "docker is not installed (the engine runs in the oneAPI image)"- if subprocess.run(["docker", "image", "inspect", SYCL_IMAGE], capture_output=True).returncode != 0:- return None, f"the runtime image {SYCL_IMAGE} is missing (sycl/tools/Dockerfile)"return exe, Nonediff --git a/sycl/src/core/conversation_snapshot.cpp b/sycl/src/core/conversation_snapshot.cppindex 92664a7b3..17b8cd504 100644--- a/sycl/src/core/conversation_snapshot.cpp+++ b/sycl/src/core/conversation_snapshot.cpp@@ -8,6 +8,7 @@#include <array>#include <cstring>#include <limits>+#include <memory>namespace strata::core {namespace {@@ -28,8 +29,8 @@ bool valid_extent(const QsaState& st, int64_t upto, std::string& error) {bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index, Layout& l, std::string& error) {if (!valid_extent(st, upto, error)) return false;- if (st.kv_hybrid && (st.kv_mode != 0 || st.kv_q4 || st.kv_int8)) {- error = "conversation snapshot: hybrid K8V4 requires an identity layout and distinct format flags";+ if (st.kv_hybrid && (st.kv_mode == 2 || st.kv_q4 || st.kv_int8)) { // a streamed one reads its host copy+ error = "conversation snapshot: hybrid K8V4 cannot be a ring and needs distinct format flags";return false;}const auto s = strata::kernels::qsa_real_shapes();@@ -74,7 +75,9 @@ bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool indexstd::array<void*, 5> pools(const QsaState& st, bool resident = false) {const bool host = st.kv_mode != 0 && !resident;- if (st.kv_hybrid) return {st.k_q, st.v_q4, st.k_scale, nullptr, st.idx_pooled};+ if (st.kv_hybrid)+ return {host ? st.host.k_q : st.k_q, host ? st.host.v_q4 : st.v_q4, host ? st.host.k_scale : st.k_scale,+ nullptr, st.idx_pooled};if (st.kv_q4)return {host ? st.host.k_q4 : st.k_q4, host ? st.host.v_q4 : st.v_q4, nullptr, nullptr, st.idx_pooled};if (st.kv_int8)@@ -247,6 +250,34 @@ bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, coreturn false;}+bool conversation_kv_part_sizes(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index,+ std::array<uint64_t, 5>& sizes, std::string& error) {+ Layout l{};+ if (!layout(st, g, upto, index, l, error)) return false;+ sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};+ return true;+}++bool conversation_kv_source(SessionKvSource& out, const QsaState& st, const ModelGeometry& g,+ int64_t upto, bool index, std::string& error) {+ Layout l{};+ if (!layout(st, g, upto, index, l, error) || !valid(st, l, upto, error)) return false;+ SessionKvSource s;+ s.format = l.format; s.cells = l.cells; s.heads = g.n_head_kv; s.head_dim = g.head_dim;+ s.page_size = l.page_size; s.pooled_rows = l.pooled_rows; s.idx_dim = g.idx_key_dim;+ s.sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};+ const auto src = pools(st);+ const auto sizes = s.sizes;+ auto why = std::make_shared<std::string>();+ s.read = [src, sizes, why](size_t part, size_t offset, void* dst, size_t n) {+ if (part >= 5 || offset > sizes[part] || n > sizes[part] - offset) { *why = "K/V read out of range"; return false; }+ return transfer(dst, src[part] ? static_cast<const uint8_t*>(src[part]) + offset : nullptr, n, *why);+ };+ s.error = [why] { return *why; };+ out = std::move(s);+ return true;+}+bool conversation_kv_verify(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,int64_t upto, bool index, uint64_t& fingerprint, std::string& error) {if (!conversation_kv_validate(image, st, g, upto, index, error)) return false;diff --git a/sycl/src/core/conversation_snapshot_test.cpp b/sycl/src/core/conversation_snapshot_test.cppindex ba5bdbc5e..c7e70951d 100644--- a/sycl/src/core/conversation_snapshot_test.cpp+++ b/sycl/src/core/conversation_snapshot_test.cpp@@ -2,10 +2,16 @@#include <sycl/sycl.hpp>#include <dpct/dpct.hpp>#include "strata/core/conversation_snapshot.hpp"+#include "strata/core/conversation_file.hpp"#include "strata/kernels/kv_q4.hpp"#include <array>+#include <chrono>#include <cstdio>+#include <filesystem>+#include <fstream>+#include <iterator>+#include <string>#include <cstdlib>#include <limits>#include <vector>@@ -180,6 +186,35 @@ void full_session(int fmt, int mode, int experts) {check(a.checkpoints[0].used == 17,"upstream checkpoint LRU stamp survives capture");fill(177);check(conversation_snapshot_save(b,view,ss,g,draft.state,err),"capture complete B");+ {+ // disk save path: metadata + streamed K/V give the same file as the captured image+ SavedConversation meta;+ std::vector<SessionKvSource> sources;+ check(conversation_snapshot_sources(meta,sources,view,ss,g,draft.state,err),"disk-save sources");+ check(meta.kv.empty() && sources.size()==b.kv.size(),"one source per K/V layer, none captured");+ const SessionFileIdentity id{1,2};+ namespace fs=std::filesystem;+ const fs::path dir=fs::temp_directory_path()/("strata-snap-test-"+std::to_string(experts)+"-"++ std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));+ fs::create_directories(dir);+ const std::string p1=(dir/"streamed.bin").string(), p2=(dir/"captured.bin").string();+ auto slurp=[](const std::string& p){ std::ifstream f(p,std::ios::binary);+ return std::vector<char>((std::istreambuf_iterator<char>(f)),std::istreambuf_iterator<char>()); };+ size_t n1=0,n2=0;+ check(session_file_write(p1,meta,sources,id,n1,err),"streamed session write");+ check(session_file_write(p2,b,id,n2,err),"captured session write");+ SavedConversation x,y;+ check(session_file_read(p1,id,x,n1,err) && session_file_read(p2,id,y,n2,err) && n1==n2,"both files read");+ check(x.live.gdn==y.live.gdn && x.live.dead==y.live.dead && x.live.ids==y.live.ids &&+ x.checkpoints.size()==y.checkpoints.size() && equal(x.kv[0],y.kv[0]) && equal(x.kv.back(),y.kv.back()),+ "streamed file equals captured file");+ check(slurp(p1)==slurp(p2),"streamed file is byte-identical to the captured file");+ std::error_code ec;+ fs::remove_all(dir,ec);+ auto empty_ids=std::vector<int32_t>{};+ const ConversationView none{empty_ids,images,checkpoints,true};+ check(!conversation_snapshot_sources(meta,sources,none,ss,g,draft.state,err),"empty session refused");+ }check(a.live.dead!=b.live.dead,"different opening-state spare keys in regression fixture");auto bad=a; bad.kv.back().k.pop_back();check(conversation_snapshot_restore(bad,ss,g,draft.state,err)==ConversationRestore::invalid,@@ -225,6 +260,47 @@ void full_session(int fmt, int mode, int experts) {check(conversation_kv_verify(incremental.kv.back(),draft.state,g,70,false,fingerprint,err),"incremental draft authoritative and ring read-back");ids.resize(65);}+ {+ // a layer split's later stage: the same image WITHOUT the draft layer's K/V (draft == nullptr)+ check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore A before stage images");+ size_t with_draft=0,without=0;+ check(conversation_snapshot_bytes(view,ss,g,draft.state,with_draft,err) &&+ conversation_snapshot_bytes(view,ss,g,nullptr,without,err) && without<with_draft,+ "a stage image's estimate leaves the draft out");+ SavedConversation stage,stage_b,stage_back;+ check(conversation_snapshot_save(stage,view,ss,g,nullptr,err),"capture a stage image");+ check(stage.kv.size()==a.kv.size()-1 && equal(stage.kv[0],a.kv[0]) && stage.live.gdn==a.live.gdn,+ "a stage image holds the session's own layers, no draft");+ check(stage.bytes()<a.bytes(),"a stage image is smaller by the draft ring");+ check(conversation_snapshot_validate(stage,ss,g,nullptr,err),"validate a stage image without a draft");+ check(!conversation_snapshot_validate(stage,ss,g,draft.state,err),"a stage image is refused where a draft is expected");+ check(!conversation_snapshot_validate(a,ss,g,nullptr,err),"an image with a draft is refused where none is expected");+ fill(201);+ check(conversation_snapshot_save(stage_b,view,ss,g,nullptr,err),"capture another stage state");+ check(conversation_snapshot_restore(a,ss,g,nullptr,err)==ConversationRestore::invalid,+ "restoring a draft image as a stage image is refused before any write");+ check(conversation_snapshot_save(stage_back,view,ss,g,nullptr,err) && stage_back.live.gdn==stage_b.live.gdn &&+ equal(stage_back.kv[0],stage_b.kv[0]),"the refusal left the stage untouched");+ check(conversation_snapshot_restore(stage,ss,g,nullptr,err)==ConversationRestore::restored,"restore a stage image");+ check(conversation_snapshot_save(stage_back,view,ss,g,nullptr,err) && stage_back.live.gdn==stage.live.gdn &&+ stage_back.live.dead==stage.live.dead && equal(stage_back.kv[0],stage.kv[0]),"stage A/B/A exactness");+ // its retained K/V: the next park copies only what changed, and equals a full capture+ ConversationKvReuse reuse{stage.kv,65,65,{}};+ SavedConversation fresh,incremental;+ size_t peak=0,reused=0;+ check(conversation_snapshot_save(fresh,view,ss,g,nullptr,err),"full stage capture reference");+ check(conversation_snapshot_capture_bytes(reuse,view,ss,g,nullptr,peak,err),"admit an incremental stage capture");+ check(conversation_snapshot_save(incremental,view,ss,g,nullptr,err,std::move(reuse),&reused),"incremental stage capture");+ check(reused>0 && incremental.bytes()<=peak && equal(incremental.kv[0],fresh.kv[0]) &&+ incremental.live.gdn==fresh.live.gdn,"an incremental stage capture reuses pages and equals a full one");+ SavedConversation split_image=stage;+ split_image.stage_images.push_back(stage);+ check(!conversation_snapshot_validate(split_image,ss,g,draft.state,err),+ "a layer split's image is refused by the whole-session form");+ ConversationKvReuse wrong{a.kv,65,65,{}};+ check(!conversation_snapshot_capture_bytes(wrong,view,ss,g,nullptr,peak,err),"a draft image's K/V is not a stage's reuse");+ }+ check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore A after stage images");check(conversation_checkpoint_restore(a.checkpoints[0],ss,g,err),"restore early running checkpoint");std::vector<uint8_t> spare(sizes.dead);cuda_check(DPCT_CHECK_ERROR(@@ -281,6 +357,25 @@ int main() {check(equal(a,restored),"A/B/A byte-exact K/V and indexer state");uint64_t fingerprint = 0;check(conversation_kv_verify(a,f.state,f.g,upto,index,fingerprint,err),"verify restored authoritative and resident bytes without rewriting them");+ {+ // disk save streams the same bytes as a captured image, without the host copy+ SessionKvSource src;+ check(conversation_kv_source(src,f.state,f.g,upto,index,err),"K/V source for a disk save");+ check(src.format==a.format && src.cells==a.cells && src.heads==a.heads && src.head_dim==a.head_dim &&+ src.page_size==a.page_size && src.pooled_rows==a.pooled_rows && src.idx_dim==a.idx_dim,+ "K/V source metadata equals the captured image");+ const std::array<const ConversationBuffer*,5> parts={&a.k,&a.v,&a.k_scale,&a.v_scale,&a.pooled};+ for (size_t i=0;i<5;++i) {+ check(src.sizes[i]==parts[i]->size(),"K/V source part size");+ std::vector<uint8_t> got(src.sizes[i]), want(src.sizes[i]);+ const size_t half=src.sizes[i]/2; // two reads: offsets are honoured+ check(src.read(i,0,got.data(),half) && src.read(i,half,got.data()+half,src.sizes[i]-half),+ "K/V source reads");+ check(parts[i]->read(want.data(),0,want.size()) && got==want,"K/V source bytes equal the image");+ }+ SessionKvSource none;+ check(!conversation_kv_source(none,f.state,f.g,-1,index,err),"K/V source rejects an invalid extent");+ }if (mode==1) {std::vector<int32_t> table((size_t)f.state.n_pages);cuda_check(DPCT_CHECK_ERROR(dpct::get_in_order_queue()diff --git a/sycl/src/core/conversation_state.cpp b/sycl/src/core/conversation_state.cppindex 584fc3ab2..f6bd041dc 100644--- a/sycl/src/core/conversation_state.cpp+++ b/sycl/src/core/conversation_state.cpp@@ -204,7 +204,7 @@ bool conversation_checkpoint_restore(const ConversationCheckpoint& c, SessionSta}bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& ss,- const ModelGeometry& g, const QsaState& draft, size_t& bytes, std::string& error) {+ const ModelGeometry& g, const QsaState* draft, size_t& bytes, std::string& error) {bytes = 0;if (!view_validate(view, ss, g, error)) return false;ConversationStateSizes z;@@ -214,7 +214,7 @@ bool conversation_snapshot_bytes(const ConversationView& view, const SessionStatif (!product(ids, {view.ids.size(), sizeof(int32_t)}) ||!product(images, {view.images.size(), sizeof(ConversationImageKey)}) ||!product(checkpoints, {view.checkpoints.size(), sizeof(ConversationCheckpoint)}) ||- !product(layers, {qsa + 1, sizeof(ConversationKv)}) ||+ !product(layers, {qsa + (draft ? 1 : 0), sizeof(ConversationKv)}) ||!product(tails, {qsa, z.tail}) || !product(dead, {qsa, z.dead}) ||!product(positions, {qsa, z.block_pos})) return fail(error, "snapshot metadata byte count overflow");for (size_t n : {ids, images, checkpoints, layers, tails, dead, positions, z.gdn, ss.ple_hist ? z.ple : 0})@@ -222,8 +222,8 @@ bool conversation_snapshot_bytes(const ConversationView& view, const SessionStatfor (const auto& c : view.checkpoints)if (!metadata_bytes(c, bytes)) return fail(error, "checkpoint byte count overflow");const int64_t upto = (int64_t) view.ids.size(); // view_validate bounds this by signed max_cells- for (uint64_t i = 0; i <= qsa; ++i) {- const auto& st = i == qsa ? draft : owned(ss, (size_t) i);+ for (uint64_t i = 0; i < qsa + (draft ? 1 : 0); ++i) {+ const auto& st = i == qsa ? *draft : owned(ss, (size_t) i);const size_t n = conversation_kv_bytes(st, g, upto, i != qsa);if (!n || !add(bytes, n)) return fail(error, "invalid or overflowing K/V byte estimate");}@@ -232,16 +232,16 @@ bool conversation_snapshot_bytes(const ConversationView& view, const SessionStatbool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view,const SessionState& ss, const ModelGeometry& g,- const QsaState& draft, size_t& bytes, std::string& error) {+ const QsaState* draft, size_t& bytes, std::string& error) {if (!conversation_snapshot_bytes(view, ss, g, draft, bytes, error)) return false;if (reuse.kv.empty()) return true;- const size_t layers = owned_qsa(ss) + 1;+ const size_t layers = owned_qsa(ss) + (draft ? 1 : 0);if (reuse.kv.size() != layers || reuse.unchanged_tokens < 0 ||reuse.unchanged_tokens > reuse.captured_tokens || reuse.unchanged_tokens > int64_t(view.ids.size()))return fail(error, "invalid retained K/V prefix");for (size_t i = 0; i < layers; ++i) {- const bool index = i + 1 != layers;- const auto& st = index ? owned(ss, i) : draft;+ const bool index = i < owned_qsa(ss);+ const auto& st = index ? owned(ss, i) : *draft;if (!conversation_kv_validate(reuse.kv[i], st, g, reuse.captured_tokens, index, error)) return false;const size_t fresh = conversation_kv_bytes(st, g, int64_t(view.ids.size()), index);size_t retained = 0;@@ -257,7 +257,7 @@ bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, constbool conversation_snapshot_save(SavedConversation& image, const ConversationView& view,const SessionState& ss, const ModelGeometry& g,- const QsaState& draft, std::string& error,+ const QsaState* draft, std::string& error,ConversationKvReuse reuse, size_t* reused_bytes) {size_t estimate = 0;if (!conversation_snapshot_capture_bytes(reuse, view, ss, g, draft, estimate, error) || !sync(error)) return false;@@ -270,7 +270,7 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationViewconst int64_t unchanged = reuse.kv.empty() ? 0 : reuse.unchanged_tokens;captured.kv = std::move(reuse.kv);const size_t layers = owned_qsa(ss);- captured.kv.resize(layers + 1);+ captured.kv.resize(layers + (draft ? 1 : 0));if (!conversation_checkpoint_save(captured.live, ss, g, error)) return false;const int64_t upto = (int64_t) view.ids.size();for (size_t j = 0; j < layers; ++j)@@ -278,15 +278,68 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationViewunchanged, reused_bytes)) return false;// The draft's final cell may not have been computed when the output cap was// reached. Refresh that page even when the main prefix continued unchanged.- if (!conversation_kv_save(captured.kv.back(), draft, g, upto, false, error,- std::max<int64_t>(0, unchanged - 1), reused_bytes)) return false;+ if (draft && !conversation_kv_save(captured.kv.back(), *draft, g, upto, false, error,+ std::max<int64_t>(0, unchanged - 1), reused_bytes)) return false;image = std::move(captured);return true;}+bool conversation_snapshot_sources(SavedConversation& meta, std::vector<SessionKvSource>& sources,+ const ConversationView& view, const SessionState& ss, const ModelGeometry& g,+ const QsaState& draft, std::string& error) {+ if (!view_validate(view, ss, g, error) || !sync(error)) return false;+ SavedConversation captured;+ captured.geometry = geometry_key(g);+ captured.layer_lo = ss.layer_lo; captured.layer_hi = ss.layer_hi;+ captured.live.ids = view.ids; captured.live.imgs = view.images;+ captured.cvec = view.cvec; captured.checkpoints = view.checkpoints;+ if (!conversation_checkpoint_save(captured.live, ss, g, error)) return false;+ const int64_t upto = (int64_t) view.ids.size();+ const size_t layers = owned_qsa(ss);+ std::vector<SessionKvSource> out(layers + 1);+ for (size_t j = 0; j < layers; ++j)+ if (!conversation_kv_source(out[j], owned(ss, j), g, upto, true, error)) return false;+ if (!conversation_kv_source(out.back(), draft, g, upto, false, error)) return false;+ meta = std::move(captured);+ sources = std::move(out);+ return true;+}++bool conversation_session_read_limits(SessionReadLimits& limits, const SessionState& ss, const ModelGeometry& g,+ const QsaState& draft, uint64_t max_tokens, uint64_t max_checkpoints,+ std::string& error) {+ ConversationStateSizes z;+ if (!conversation_session_sizes(g, ss, z, error)) return false;+ if (ss.max_cells < 0) return fail(error, "invalid session cells");+ const uint64_t tokens = std::min<uint64_t>(max_tokens, (uint64_t) ss.max_cells);+ const size_t layers = owned_qsa(ss);+ if ((owned_qsa(ss) && !ss.qsa_states)) return fail(error, "invalid session running-state targets");+ size_t tails = 0, dead = 0, block_pos = 0;+ if (!product(tails, {layers, z.tail}) || !product(dead, {layers, z.dead}) ||+ !product(block_pos, {layers, z.block_pos})) return fail(error, "indexer byte count overflow");+ SessionReadLimits l = limits; // keeps the caller's admit / progress / max_file_bytes+ l.max_tokens = tokens;+ l.max_checkpoints = max_checkpoints;+ l.max_kv_layers = layers + 1;+ l.geometry = geometry_key(g);+ l.layer_range = std::make_pair(ss.layer_lo, ss.layer_hi);+ l.max_state_bytes = {z.gdn, ss.ple_hist ? z.ple : 0, tails, dead, block_pos};+ l.max_kv_bytes.assign(layers + 1, {});+ for (size_t j = 0; j < layers; ++j) {+ const auto& st = owned(ss, j);+ const int64_t upto = (int64_t) std::min<uint64_t>(tokens, (uint64_t) std::max<int64_t>(st.max_cells, 0));+ if (!conversation_kv_part_sizes(st, g, upto, true, l.max_kv_bytes[j], error)) return false;+ }+ const int64_t dupto = (int64_t) std::min<uint64_t>(tokens, (uint64_t) std::max<int64_t>(draft.max_cells, 0));+ if (!conversation_kv_part_sizes(draft, g, dupto, false, l.max_kv_bytes.back(), error)) return false;+ limits = std::move(l);+ return true;+}+bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& ss,- const ModelGeometry& g, const QsaState& draft, std::string& error) {- if (!image.live.stage_parts.empty()) return fail(error, "layer-split parking is not supported");+ const ModelGeometry& g, const QsaState* draft, std::string& error) {+ if (!image.live.stage_parts.empty())+ return fail(error, "a running checkpoint's stage parts belong in the stage images, not in live.stage_parts");if (image.geometry != geometry_key(g)) return fail(error, "incompatible runtime geometry");// an image holds exactly one carve's running state and K/V: same layer range or nothingif (image.layer_lo != ss.layer_lo || image.layer_hi != ss.layer_hi)@@ -294,23 +347,49 @@ bool conversation_snapshot_validate(const SavedConversation& image, const Sessioconst ConversationView view{image.live.ids, image.live.imgs, image.checkpoints, image.cvec};if (!view_validate(view, ss, g, error) || !conversation_checkpoint_validate(image.live, ss, g, error)) return false;const size_t layers = owned_qsa(ss);- if (image.kv.size() != layers + 1) return fail(error, "invalid K/V layer count");+ if (image.kv.size() != layers + (draft ? 1 : 0)) return fail(error, "invalid K/V layer count");const int64_t upto = (int64_t) image.live.ids.size();for (size_t j = 0; j < layers; ++j)if (!conversation_kv_validate(image.kv[j], owned(ss, j), g, upto, true, error)) return false;- return conversation_kv_validate(image.kv.back(), draft, g, upto, false, error);+ return !draft || conversation_kv_validate(image.kv.back(), *draft, g, upto, false, error);}ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& ss,- const ModelGeometry& g, const QsaState& draft, std::string& error) {+ const ModelGeometry& g, const QsaState* draft, std::string& error) {if (!conversation_snapshot_validate(image, ss, g, draft, error)) return ConversationRestore::invalid;if (!sync(error)) return ConversationRestore::transfer_failed;const int64_t upto = (int64_t) image.live.ids.size();for (size_t j = 0; j < owned_qsa(ss); ++j)if (!conversation_kv_restore(image.kv[j], owned(ss, j), g, upto, true, error))return ConversationRestore::transfer_failed;- if (!conversation_kv_restore(image.kv.back(), draft, g, upto, false, error) ||+ if ((draft && !conversation_kv_restore(image.kv.back(), *draft, g, upto, false, error)) ||!conversation_checkpoint_restore(image.live, ss, g, error)) return ConversationRestore::transfer_failed;return ConversationRestore::restored;}++// the draft layer's K/V included (the stage that owns the draft head, or no layer split)+bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& ss, const ModelGeometry& g,+ const QsaState& draft, size_t& bytes, std::string& error) {+ return conversation_snapshot_bytes(view, ss, g, &draft, bytes, error);+}+bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view,+ const SessionState& ss, const ModelGeometry& g, const QsaState& draft,+ size_t& bytes, std::string& error) {+ return conversation_snapshot_capture_bytes(reuse, view, ss, g, &draft, bytes, error);+}+bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, const SessionState& ss,+ const ModelGeometry& g, const QsaState& draft, std::string& error,+ ConversationKvReuse reuse, size_t* reused_bytes) {+ return conversation_snapshot_save(image, view, ss, g, &draft, error, std::move(reuse), reused_bytes);+}+bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& ss, const ModelGeometry& g,+ const QsaState& draft, std::string& error) {+ // the whole-session form: a layer split's image (stage images) is restored stage by stage, never through here+ if (!image.stage_images.empty()) return fail(error, "a layer split's image restored as a single session");+ return conversation_snapshot_validate(image, ss, g, &draft, error);+}+ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& ss,+ const ModelGeometry& g, const QsaState& draft, std::string& error) {+ return conversation_snapshot_restore(image, ss, g, &draft, error);+}} // namespace strata::corediff --git a/sycl/src/core/device.dp.cpp b/sycl/src/core/device.dp.cppindex 09485d574..45645f7a5 100644--- a/sycl/src/core/device.dp.cpp+++ b/sycl/src/core/device.dp.cpp@@ -200,8 +200,28 @@ IDXGIAdapter3* budget_adapter(int device) {}} // namespace+// #873 / #654: on some Windows setups the first hipMemGetInfo of a process fails with hipErrorInvalidValue because the ROCm+// runtime has not finished initialising against the Adrenalin WDDM driver, and the first kernel launch after that+// crashes (0xC0000005 in amdhip64_7.dll). A hipFree(0) before the first query initialises the context, and one+// failed query gets one retry after 250 ms. Both happen once per process, before the DXGI budget below; any other+// error, and a failure of the retry, are returned as they are (a real failure is never retried).+static hipError_t first_mem_get_info(size_t* free_bytes, size_t* total_bytes) {+ static std::atomic<bool> warmed{false}, retried{false};+ if (!warmed.exchange(true)) (void) hipFree(nullptr);+ hipError_t e = hipMemGetInfo(free_bytes, total_bytes);+ if (e == hipErrorInvalidValue && !retried.exchange(true)) {+ (void) hipGetLastError();+ std::fprintf(stderr, "strata: hipMemGetInfo failed (%s); retrying once after 250 ms\n", hipGetErrorString(e));+ Sleep(250);+ e = hipMemGetInfo(free_bytes, total_bytes);+ std::fprintf(stderr, "strata: hipMemGetInfo retry: %s\n", e == hipSuccess ? "ok" : hipGetErrorString(e));+ }+ return e;+}+hipError_t mem_get_info(size_t* free_bytes, size_t* total_bytes) {- const hipError_t e = hipMemGetInfo(free_bytes, total_bytes);+ if (free_bytes == nullptr || total_bytes == nullptr) return hipMemGetInfo(free_bytes, total_bytes);+ const hipError_t e = first_mem_get_info(free_bytes, total_bytes);static const bool off = [] {const char* v = std::getenv("STRATA_WDDM_BUDGET");return v != nullptr && std::atoi(v) == 0;@@ -252,7 +272,7 @@ std::string gpu_arch_problem(int ordinal) {}std::string device_code_error() try {-#if defined(STRATA_USE_HIP)+#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)return ""; // gpu_arch_problem() checks the HIP architectures against STRATA_HIP_ARCHS, before this point#else// every .cu of the engine is compiled for the same CMAKE_CUDA_ARCHITECTURES, so this kernel stands for all@@ -349,7 +369,17 @@ DeviceInfo device_info(int ordinal) {// supported arch is enforced by CMake; RUNNING on an older card is caught here, because a binary can be carried// to a machine with an older card and would otherwise silently take whatever path the driver chose. The HIP// backend checks the card against the architectures the binary was compiled for (and wave32).-#if defined(STRATA_USE_HIP)+#if defined(STRATA_HIP_GFX906)+ // AMD gfx906 (the STRATA_HIP_GFX906 compat build, not STRATA_USE_HIP): the build targets one gfx arch+ // (CMAKE_HIP_ARCHITECTURES, wave64); a card of another arch fails at the first kernel launch with+ // hipErrorInvalidDeviceFunction. gcnArchName says which it is.+ {+ std::string arch(p.gcnArchName);+ if (const size_t colon = arch.find(':'); colon != std::string::npos) arch.resize(colon);+ d.arch = arch;+ }+ if (p.gcnArchName[0] != 0) d.name += std::string(" (") + p.gcnArchName + ")";+#elif defined(STRATA_USE_HIP)d.arch = base_arch(p.gcnArchName);if (const std::string why = arch_problem(p, ordinal); !why.empty()) throw CudaError(why, -1);#elsediff --git a/sycl/src/core/expert_cache.cpp b/sycl/src/core/expert_cache.cppindex 56cd011a5..fe5c7d0a4 100644--- a/sycl/src/core/expert_cache.cpp+++ b/sycl/src/core/expert_cache.cpp@@ -7,19 +7,87 @@#include "strata/sycl_queue.hpp"#include "strata/core/expert_cache.hpp"-#if !defined(STRATA_USE_HIP)+// #533's segmented cache uses CUDA's virtual memory management (cuMem*): not on HIP, neither the RDNA backend nor+// the gfx906 compat build (PR #638), which compiles this file as HIP without STRATA_USE_HIP+#define STRATA_EC_NO_VMM 1 // SYCL port: no driver virtual memory management on Level Zero (--vram-elastic is CUDA-only, #533)++#if !defined(STRATA_EC_NO_VMM)// #533: the virtual memory management types (the functions come through the// runtime's entry points)#endif#include <algorithm>+#include <atomic>#include <cstdio>#include <filesystem>+#include <cstdlib>#include <utility>#include <cstring>namespace strata::core {+// See the header. NVIDIA's DGX Spark Porting Guide (section 5.5, "Memory reporting on UMA systems") recommends the same:+// not to rely on cudaMemGetInfo alone but to count the memory the OS can reclaim. Swap is not counted here (unlike+// NVIDIA's reference snippet): an expert cache that pushes the system into swap would be far slower than a smaller one.+size_t device_free_bytes() try {+ size_t free_b = 0, total_b = 0;+ /*+ DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions for+ device information which may not be supported by all compilers or runtimes.+ You may need to adjust the code.+ */+ dpct::get_current_device().get_memory_info(free_b, total_b);+#if defined(__linux__) && !defined(STRATA_HIP_GFX906) // (the gfx906 compat layer has no cudaDevAttrIntegrated; that GPU is discrete)+ // per device: a box can mix an integrated GPU (an APU) with a discrete one, and the answer is the CURRENT device's+ static std::atomic<int> uma_cache[64]; // 0 unknown, 1 integrated (unified memory), 2 discrete+ bool unified_memory = false;+ {+ int dev = 0, v = 0;+ if (DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()) == 0 &&+ dev >= 0 && dev < 64) {+ int c = uma_cache[dev].load(std::memory_order_acquire);+ if (c == 0) {+ c = DPCT_CHECK_ERROR(+ v = dpct::get_device(dev).get_integrated()) == 0 &&+ v+ ? 1+ : 2;+ uma_cache[dev].store(c, std::memory_order_release);+ }+ unified_memory = c == 1;+ }+ }+ if (unified_memory) {+ if (FILE* m = std::fopen("/proc/meminfo", "r")) {+ char line[256];+ unsigned long long kb = 0;+ while (std::fgets(line, sizeof line, m))+ if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) break;+ std::fclose(m);+ // STRATA_UMA_HEADROOM_GIB: a whole number of GiB, 0..1024; anything else keeps the default 6 (said once)+ static const long gib = [] {+ const char* h = std::getenv("STRATA_UMA_HEADROOM_GIB");+ if (h == nullptr) return 6L;+ char* end = nullptr;+ const long v = std::strtol(h, &end, 10);+ if (end != h && *end == '\0' && v >= 0 && v <= 1024) return v;+ std::fprintf(stderr, "strata: STRATA_UMA_HEADROOM_GIB=%s is not a whole number of GiB (0-1024): using 6\n", h);+ return 6L;+ }();+ const unsigned long long head = (unsigned long long) gib << 30;+ const unsigned long long avail = kb << 10;+ if (avail > head && avail - head > free_b) free_b = (size_t) (avail - head);+ }+ }+#endif+ return free_b;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}+bool read_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert,std::vector<std::pair<int32_t, int32_t>>& ranked, int64_t& slots, std::string& err) {std::FILE* f = std::fopen(path.c_str(), "rb");@@ -154,7 +222,7 @@ ExpertCache::~ExpertCache() { close(); }// ---- #533: the segmented arena (--vram-elastic). The driver API's virtual memory functions, looked up through the// runtime (no link against the driver library): one address range for the whole arena, backed by physical segments,// and the tail's segments unmapped / mapped again later. Nothing here runs unless a segment size was set.-#if 0 // SYCL port: no driver virtual memory management (--vram-elastic is CUDA-only, #533)+#if !defined(STRATA_EC_NO_VMM)namespace {struct Vmm {int(CUDAAPI *device_get)(int *, int) = nullptr;@@ -258,7 +326,7 @@ bool map_segment(const Vmm &v, int dev, dpct::device_ptr va, size_t bytes,#endifbool ExpertCache::open_segmented(uint64_t want, std::string &err) try {-#if 1 // SYCL port: --vram-elastic is CUDA-only (#533)+#if defined(STRATA_EC_NO_VMM)(void) want;err = "ExpertCache: --vram-elastic (a segmented expert cache) is CUDA-only for now";return false;@@ -324,7 +392,7 @@ catch (sycl::exception const &exc) {}void ExpertCache::release_segmented() {-#if 0 // SYCL port: no segmented arena (#533)+#if !defined(STRATA_EC_NO_VMM)const Vmm& v = vmm();if (base_ != nullptr) dpct::get_current_device().queues_wait_and_throw();const dpct::device_ptr va = reinterpret_cast<dpct::device_ptr>(base_);@@ -363,7 +431,7 @@ bool ExpertCache::shrink(int64_t keep_bytes, std::string &err) try {err = "the expert cache is not segmented (the engine needs --vram-elastic)";return false;}-#if 1 // SYCL port: --vram-elastic is CUDA-only (#533)+#if defined(STRATA_EC_NO_VMM)(void) keep_bytes;return false;#else@@ -416,7 +484,7 @@ bool ExpertCache::grow(int64_t want_bytes, std::string& err) {err = "the expert cache is not segmented (the engine needs --vram-elastic)";return false;}-#if 1 // SYCL port: --vram-elastic is CUDA-only (#533)+#if defined(STRATA_EC_NO_VMM)(void) want_bytes;return false;#else@@ -464,8 +532,14 @@ bool ExpertCache::ensure_blocking_staging(std::size_t bytes, std::string& err) {}#endif-bool ExpertCache::open(int64_t n_slots, int64_t n_layers, int64_t n_expert,- int64_t blob_bytes, std::string &err) try {+namespace {+bool g_cache_vmm = false; // set_vmm+} // namespace++void ExpertCache::set_vmm(bool enabled) { g_cache_vmm = enabled; }++bool ExpertCache::open(int64_t n_slots, int64_t n_layers, int64_t n_expert, int64_t blob_bytes,+ std::string& err) {close();if (n_slots <= 0) {err = "ExpertCache: n_slots must be positive";@@ -492,6 +566,7 @@ bool ExpertCache::open(int64_t n_slots, int64_t n_layers, int64_t n_expert,*/if (DPCT_CHECK_ERROR(dpct::get_current_device().get_memory_info(free_b, total_b)) == 0) {+ free_b = device_free_bytes(); // unified memory: what the OS can give back counts (see the header)if ((uint64_t) free_b < want) {char buf[320];std::snprintf(buf, sizeof buf,@@ -507,6 +582,18 @@ bool ExpertCache::open(int64_t n_slots, int64_t n_layers, int64_t n_expert,if (seg_req_ > 0) { // #533: --vram-elastic: physical segments behind one address range (zeroed below)if (!open_segmented(want, err)) return false;+ } else if (g_cache_vmm && vmm_available()) {+ // the elastic K/V: every chunk mapped now; the K/V may later take some of them (and give them back)+ auto r = std::make_unique<VmmRange>();+ if (!r->reserve(want) || !r->map_range(0, r->chunks(), [] { return (VmmChunk) 0; })) {+ char buf[256];+ std::snprintf(buf, sizeof buf, "ExpertCache: mapping %.2f GiB of VRAM failed: out of memory",+ (double) want / 1073741824.0);+ err = buf;+ return false;+ }+ 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) {@@ -563,11 +650,6 @@ bool ExpertCache::open(int64_t n_slots, int64_t n_layers, int64_t n_expert,}return true;}-catch (sycl::exception const &exc) {- std::cerr << exc.what() << "Exception caught at file:" << __FILE__- << ", line:" << __LINE__ << std::endl;- std::exit(1);-}bool ExpertCache::open_sized(const std::vector<int64_t>& slot_bytes, int64_t n_layers, int64_t n_expert,std::string& err) {@@ -611,6 +693,9 @@ void ExpertCache::close() {off_.clear();if (!segs_.empty()) {release_segmented();+ } else if (vmm_) {+ vmm_.reset(); // unmaps and frees every chunk it still holds+ base_ = nullptr;} else if (base_ != nullptr) {sycl::free(base_, dpct::get_in_order_queue());base_ = nullptr;diff --git a/sycl/src/core/expert_source.cpp b/sycl/src/core/expert_source.cppindex e1177d8eb..6103866fd 100644--- a/sycl/src/core/expert_source.cpp+++ b/sycl/src/core/expert_source.cpp@@ -14,10 +14,12 @@#include "strata/kernels/elementwise.hpp"#include "strata/kernels/quantize_act.hpp"#include "strata/kernels/s2_expert_grouped.hpp"+#include "strata/kernels/cpu/kq_avx1.hpp"#include "strata/kernels/cpu/kq_avx2.hpp"#include <algorithm>#include <atomic>+#include <cerrno>#include <chrono>#include <cstdio>#include <cstdlib>@@ -45,6 +47,11 @@#include <sys/stat.h>#include <unistd.h>#endif+#if defined(__linux__)+#include <cerrno>+#include <linux/aio_abi.h> // the kernel's own asynchronous reads (io_submit): no library, allowed by Docker's seccomp+#include <sys/syscall.h>+#endif// a 64-bit seek (as in pinned.cu): the 32-bit `fseek` wraps past 4 GiB, and the spelling differs per platform#ifndef STRATA_FSEEK64@@ -74,6 +81,14 @@ bool cgroup_available_bytes(uint64_t limit, const CgroupMemoryStat& stat, uint64return true;}+uint64_t clamp_resident_budget(uint64_t requested, uint64_t physical, uint64_t commit, uint64_t headroom) {+ const uint64_t available = std::min(physical, commit);+ const uint64_t room = available > headroom ? available - headroom : 0;+ if (requested <= room) return requested;+ const uint64_t margin = 256ull << 20;+ return room > margin ? room - margin : 0;+}+bool make_cache_complement_plan(int64_t n_layers, int64_t n_expert, const std::vector<uint64_t>& layer_blob_bytes,const std::vector<std::pair<int32_t, int32_t>>& primary_gpu_pairs,@@ -232,6 +247,7 @@ bool host_available_memory(HostMemory& m, const std::string& meminfo, const std:status.dwLength = sizeof(status);if (!GlobalMemoryStatusEx(&status)) return false;m.available = (uint64_t) status.ullAvailPhys;+ m.commit = (uint64_t) status.ullAvailPageFile;return m.available > 0;#elif defined(__linux__)// MemAvailable includes reclaimable page cache, unlike _SC_AVPHYS_PAGES.@@ -325,13 +341,76 @@ bool host_available_memory(HostMemory& m, const std::string& meminfo, const std:namespace {-bool available_memory_bytes(uint64_t& bytes) {+bool available_memory_bytes(uint64_t& bytes, uint64_t* commit = nullptr) {detail::HostMemory m;if (!detail::host_available_memory(m)) return false;bytes = m.available;+ if (commit != nullptr) *commit = m.commit;return bytes > 0;}+void log_complement_memory(const char* stage, uint64_t requested) {+#if defined(_WIN32)+ MEMORYSTATUSEX status{};+ status.dwLength = sizeof(status);+ if (!GlobalMemoryStatusEx(&status)) {+ std::fprintf(stderr, "FileExpertSource: %s: GlobalMemoryStatusEx failed (error %lu)\n", stage, GetLastError());+ return;+ }+ std::fprintf(stderr, "FileExpertSource: %s: requested %.2f GiB, available RAM %.2f GiB, available commit %.2f GiB "+ "(limit %.2f GiB), available virtual address space %.2f GiB\n",+ stage, (double) requested / 1073741824.0, (double) status.ullAvailPhys / 1073741824.0,+ (double) status.ullAvailPageFile / 1073741824.0, (double) status.ullTotalPageFile / 1073741824.0,+ (double) status.ullAvailVirtual / 1073741824.0);+#else+ (void) stage;+ (void) requested;+#endif+}++/// #286: an unbuffered file handle - a HANDLE on Windows, an O_DIRECT descriptor (as a pointer-sized integer) on Linux.+void close_direct(void* h) {+#if defined(_WIN32)+ CloseHandle((HANDLE) h);+#else+ ::close((int) (intptr_t) h);+#endif+}++/// #286/#577: whether the file tier reads its `read_bytes` unbuffered, beside `arena_bytes` of RAM copy still to be+/// taken. Windows times probe reads too (experts_unbuffered); on Linux the same rule as its `cache_counts = false`+/// arm decides: whether the file cache could keep those bytes at all, from MemAvailable and the tightest cgroup+/// limit (host_available_memory). STRATA_UNBUFFERED_LOAD=1 / 0 forces it either way, as on Windows.+bool file_tier_unbuffered(const std::vector<std::string>& paths, uint64_t arena_bytes, uint64_t read_bytes,+ std::string& why) {+#if defined(_WIN32)+ return experts_unbuffered(paths, arena_bytes, why, /*cache_counts=*/false, read_bytes);+#elif defined(__linux__)+ (void) paths;+ if (const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); env != nullptr && env[0] != '\0') {+ why = std::string("STRATA_UNBUFFERED_LOAD=") + env;+ return env[0] != '0';+ }+ uint64_t avail = 0;+ if (!available_memory_bytes(avail)) {+ why = "the available RAM is unknown";+ return false;+ }+ const bool keepable = strata::platform::file_cache_keeps(avail, arena_bytes, read_bytes);+ char msg[256];+ std::snprintf(msg, sizeof msg, "%.1f GiB available, %.1f GiB of it still to be taken by the RAM copy, %.1f GiB "+ "of experts read from the files: the file cache %s keep them",+ (double) avail / (1ull << 30), (double) arena_bytes / (1ull << 30), (double) read_bytes / (1ull << 30),+ keepable ? "can" : "cannot");+ why = msg;+ return !keepable;+#else+ (void) paths; (void) arena_bytes; (void) read_bytes;+ why = "through the file cache (no unbuffered reads on this platform)";+ return false;+#endif+}+} // namespace// ================================ THE FILE-BACKED SOURCE ================================@@ -418,6 +497,7 @@ bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64layer_offsets_ = std::move(layer_offsets);layer_blob_bytes_ = std::move(layer_blob_bytes);if (!open_gguf(err)) { close(); return false; }+ record_inputs(path, gguf_, layout, true);return true;}@@ -497,6 +577,7 @@ bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64if (view == MAP_FAILED) { ::close(fd); err = "FileExpertSource: mmap failed on " + path; return false; }fd_ = fd;base_ = (const uint8_t*) view;+ paths_.assign(1, path); // #286: open_direct opens it again with O_DIRECT#endifblobs_ = (int64_t) blob_count;n_layers_ = n_layers;@@ -504,10 +585,12 @@ bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64mapped_bytes_ = want;layer_offsets_ = std::move(layer_offsets);layer_blob_bytes_ = std::move(layer_blob_bytes);+ record_inputs(path, gguf_, layout, false);return true;}void FileExpertSource::close() {+ inputs_.clear();if (complement_arena_ != nullptr) {if (complement_pinned_ && !complement_partial_)(void) DPCT_CHECK_ERROR(sycl::free(complement_arena_, dpct::get_in_order_queue()));@@ -535,6 +618,7 @@ void FileExpertSource::close() {xstage_blob_ = 0;override_.clear();staged_.clear();+ exchange_storage_.clear();exchanges_ = 0;file_reads_.store(0);complement_arena_ = nullptr;@@ -567,9 +651,7 @@ void FileExpertSource::close() {role_bytes_.clear();role_file_.clear();paths_.clear();-#if defined(_WIN32)- for (void* h : direct_) CloseHandle((HANDLE) h);-#endif+ for (void* h : direct_) close_direct(h);direct_.clear();{std::lock_guard<std::mutex> lk(stage_mu_);@@ -711,6 +793,7 @@ bool FileExpertSource::copy_from_files(int64_t layer, int64_t expert, uint8_t* dif (!direct_.empty()) { // #286: from the drive; a failed read falls back to the mapping belowconst Fill f{0, layer, expert, dst};if (read_direct(&f, 1)) return true;+ direct_fallbacks_.fetch_add(1, std::memory_order_relaxed);}if (!role_ptr_.empty()) {uint64_t at = 0;@@ -832,7 +915,7 @@ void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t nconst int64_t e = experts[i];if (e < 0 || e >= n_expert_) continue;const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e;- if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement)+ if (complement_ready_ && resident_blob(index) != nullptr)continue; // in the RAM copyif (!override_.empty() && override_[index] != nullptr) continue;size_t v = 0;@@ -865,6 +948,23 @@ void FileExpertSource::prefetch_pairs(const std::pair<int32_t, int32_t>* pairs,fill_many(todo);}+bool FileExpertSource::advise_pairs(const std::pair<int32_t, int32_t>* pairs, int64_t n) const {+ if (base_ == nullptr || !direct_.empty() || !strata::platform::read_ahead_enabled()) return false;+ for (int64_t i = 0; pairs != nullptr && i < n; ++i) {+ const int64_t l = pairs[i].first, e = pairs[i].second;+ if (l < 0 || e < 0 || l >= n_layers_ || e >= n_expert_) continue;+ if (role_ptr_.empty()) { // experts.bin: the blob is one contiguous range+ if (const uint8_t* b = mapped_blob(l, e)) strata::platform::advise_willneed(b, layer_blob_bytes_[(size_t) l]);+ continue;+ }+ for (int r = 0; r < 3; ++r) {+ const size_t k = (size_t) (3 * l + r);+ strata::platform::advise_willneed(role_ptr_[k] + (size_t) ((uint64_t) e * role_bytes_[k]), role_bytes_[k]);+ }+ }+ return true;+}+void FileExpertSource::fill_many(const std::vector<Fill>& todo) {if (todo.empty()) return;if (!direct_.empty()) {@@ -957,6 +1057,23 @@ bool FileExpertSource::open_direct(std::string& why) {for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b);}return true;+#elif defined(__linux__)+ // O_DIRECT: the reads bypass the page cache, as FILE_FLAG_NO_BUFFERING does (4 KiB-aligned windows, read_direct)+ for (const std::string& path : paths_) {+ const int fd = ::open(path.c_str(), O_RDONLY | O_DIRECT | O_CLOEXEC);+ if (fd < 0) {+ why += "; cannot open " + path + " with O_DIRECT (" + std::strerror(errno) + "), read through the file cache";+ for (void* d : direct_) close_direct(d);+ direct_.clear();+ return false;+ }+ direct_.push_back((void*) (intptr_t) fd);+ }+ if (role_ptr_.empty()) { // experts.bin: blob() now assembles into the stage buffers, sized for the largest blob+ std::lock_guard<std::mutex> lk(stage_mu_);+ for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b);+ }+ return true;#else(void) why;return false;@@ -964,7 +1081,7 @@ bool FileExpertSource::open_direct(std::string& why) {}bool FileExpertSource::set_unbuffered(uint64_t ram_bytes, std::string& why) {-#if defined(_WIN32)+#if defined(_WIN32) || defined(__linux__)if (base_ == nullptr || paths_.empty() || !direct_.empty()) {why = !direct_.empty() ? "already unbuffered" : "no expert files open";return !direct_.empty();@@ -973,17 +1090,17 @@ bool FileExpertSource::set_unbuffered(uint64_t ram_bytes, std::string& why) {// PLE table), and the copy holds at most every expert - the budget asked for can be more than thatconst uint64_t experts = expert_bytes();const uint64_t arena = std::min(ram_bytes, experts);- if (!experts_unbuffered(paths_, arena, why, /*cache_counts=*/false, experts - arena)) return false;+ if (!file_tier_unbuffered(paths_, arena, experts - arena, why)) return false;return open_direct(why);#else(void) ram_bytes;- why = "through the file cache (not Windows)";+ why = "through the file cache (no unbuffered reads on this platform)";return false;#endif}bool FileExpertSource::recheck_unbuffered(std::string& why) {-#if defined(_WIN32)+#if defined(_WIN32) || defined(__linux__)if (const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); env != nullptr && env[0] != '\0') {why = std::string("STRATA_UNBUFFERED_LOAD=") + env;return !direct_.empty();@@ -998,7 +1115,7 @@ bool FileExpertSource::recheck_unbuffered(std::string& why) {const uint64_t experts = expert_bytes();const uint64_t read = experts > complement_bytes_ ? experts - complement_bytes_ : 0;std::string w;- const bool ub = experts_unbuffered(paths_, 0, w, /*cache_counts=*/false, read);+ const bool ub = file_tier_unbuffered(paths_, 0, read, w);char head[96];std::snprintf(head, sizeof head, "re-checked with the RAM copy built (%.2f GiB): ",(double) complement_bytes_ / 1073741824.0);@@ -1006,11 +1123,11 @@ bool FileExpertSource::recheck_unbuffered(std::string& why) {if (ub == !direct_.empty()) return ub;if (ub) return open_direct(why);// through the file cache after all: the mapped reads take over (staged() stays true for the GGUF in place)- for (void* d : direct_) CloseHandle((HANDLE) d);+ for (void* d : direct_) close_direct(d);direct_.clear();return false;#else- why = "through the file cache (not Windows)";+ why = "through the file cache (no unbuffered reads on this platform)";return false;#endif}@@ -1129,6 +1246,148 @@ bool FileExpertSource::read_direct(const Fill* fills, size_t n) const {std::memcpy(x.dst + x.at, sc.buf + sc.req[x.req].pos + x.in_req + x.skip, (size_t) x.n);}return true;+#elif defined(__linux__)+ // Linux: O_DIRECT descriptors (open_direct) and the kernel's asynchronous reads - every window of the batch is+ // queued with one io_submit before the first wait, so the drive sees the batch as one queue, as the overlapped+ // ReadFiles above do. No NTFS here: windows are merged only where they touch (the 4 KiB rounding of adjacent+ // slices, consecutive experts of a role), never across a gap that would be read for nothing. Each thread has its+ // own context and aligned buffer, kept for its next batch, so concurrent batches never see each other's events.+ constexpr uint64_t kSector = 4096, kMerge = 32ull << 20;+ constexpr long kDepth = 256; // requests in flight per thread; a larger batch is read in waves of this many+ struct Window { int file; uint64_t a0, size, skip, n, at; uint8_t* dst; size_t req; uint64_t in_req; };+ struct Req { int fd; uint64_t a0, size, pos; };+ struct Scratch {+ uint8_t* buf = nullptr;+ size_t cap = 0;+ aio_context_t ctx = 0;+ std::vector<Window> win;+ std::vector<size_t> order;+ std::vector<Req> req;+ std::vector<int64_t> got;+ std::vector<iocb> cb;+ std::vector<iocb*> cbp;+ std::vector<io_event> ev;+ ~Scratch() {+ std::free(buf);+ if (ctx != 0) (void) syscall(SYS_io_destroy, ctx);+ }+ };+ thread_local Scratch sc;+ if (sc.ctx == 0 && syscall(SYS_io_setup, kDepth, &sc.ctx) != 0) {+ sc.ctx = 0;+ return false; // no AIO (a seccomp profile, aio-max-nr): the caller falls back to the mapped copy+ }+ sc.win.clear();+ for (size_t k = 0; k < n; ++k) {+ const Fill& f = fills[k];+ if (f.dst == nullptr || f.layer < 0 || f.e < 0 || f.layer >= n_layers_ || f.e >= n_expert_) return false;+ if (role_ptr_.empty()) { // experts.bin: the blob is one contiguous range+ const uint64_t per = layer_blob_bytes_[(size_t) f.layer];+ const uint64_t off = layer_offsets_[(size_t) f.layer] + (uint64_t) f.e * per;+ const uint64_t a0 = off / kSector * kSector, a1 = (off + per + kSector - 1) / kSector * kSector;+ sc.win.push_back({0, a0, a1 - a0, off - a0, per, 0, f.dst, 0, 0});+ continue;+ }+ uint64_t at = 0;+ for (int r = 0; r < 3; ++r) {+ const size_t i = (size_t) (3 * f.layer + r);+ const uint64_t per = role_bytes_[i];+ const Map& m = maps_[(size_t) role_file_[i]];+ const uint64_t off = (uint64_t) (role_ptr_[i] - m.base) + (uint64_t) f.e * per;+ const uint64_t a0 = off / kSector * kSector, a1 = (off + per + kSector - 1) / kSector * kSector;+ sc.win.push_back({role_file_[i], a0, a1 - a0, off - a0, per, at, f.dst, 0, 0});+ at += per;+ }+ }+ sc.order.resize(sc.win.size());+ for (size_t w = 0; w < sc.win.size(); ++w) sc.order[w] = w;+ std::sort(sc.order.begin(), sc.order.end(), [&](size_t a, size_t b) {+ return sc.win[a].file != sc.win[b].file ? sc.win[a].file < sc.win[b].file : sc.win[a].a0 < sc.win[b].a0;+ });+ sc.req.clear();+ uint64_t total = 0;+ int last_file = -1;+ for (size_t w : sc.order) {+ Window& x = sc.win[w];+ if (!sc.req.empty() && x.file == last_file) {+ Req& q = sc.req.back();+ const uint64_t end = q.a0 + q.size, xend = x.a0 + x.size;+ if (x.a0 <= end && std::max(end, xend) - q.a0 <= kMerge) {+ if (xend > end) {+ total += xend - end;+ q.size = xend - q.a0;+ }+ x.req = sc.req.size() - 1;+ x.in_req = x.a0 - q.a0;+ continue;+ }+ }+ sc.req.push_back({(int) (intptr_t) direct_[(size_t) x.file], x.a0, x.size, total});+ total += x.size;+ last_file = x.file;+ x.req = sc.req.size() - 1;+ x.in_req = 0;+ }+ if (total > sc.cap) {+ std::free(sc.buf);+ sc.cap = (size_t) ((total + (1u << 20) - 1) >> 20 << 20);+ void* p = nullptr;+ sc.buf = posix_memalign(&p, (size_t) kSector, sc.cap) == 0 ? (uint8_t*) p : nullptr;+ if (sc.buf == nullptr) { sc.cap = 0; return false; }+ }+ sc.got.assign(sc.req.size(), -1);+ sc.cb.resize(std::min<size_t>(sc.req.size(), (size_t) kDepth));+ sc.cbp.resize(sc.cb.size());+ sc.ev.resize(sc.cb.size());+ bool ok = true;+ for (size_t w0 = 0; ok && w0 < sc.req.size(); w0 += (size_t) kDepth) {+ const size_t wn = std::min<size_t>((size_t) kDepth, sc.req.size() - w0);+ for (size_t j = 0; j < wn; ++j) {+ const Req& r = sc.req[w0 + j];+ iocb& c = sc.cb[j];+ std::memset(&c, 0, sizeof c);+ c.aio_lio_opcode = IOCB_CMD_PREAD;+ c.aio_fildes = (uint32_t) r.fd;+ c.aio_buf = (uint64_t) (uintptr_t) (sc.buf + r.pos);+ c.aio_nbytes = r.size;+ c.aio_offset = (int64_t) r.a0;+ c.aio_data = (uint64_t) (w0 + j);+ sc.cbp[j] = &c;+ }+ // every request of the wave queued; a refused submit ends the batch once what was queued has completed+ // (the kernel still writes into the buffer until then)+ size_t queued = 0;+ while (queued < wn) {+ const long r = syscall(SYS_io_submit, sc.ctx, (long) (wn - queued), sc.cbp.data() + queued);+ if (r > 0) { queued += (size_t) r; continue; }+ if (r < 0 && errno == EINTR) continue;+ ok = false;+ break;+ }+ for (size_t done = 0; done < queued;) {+ const long r = syscall(SYS_io_getevents, sc.ctx, 1L, (long) (queued - done), sc.ev.data(), nullptr);+ if (r < 0) {+ if (errno == EINTR) continue;+ // the context is in an unknown state: drop it (io_destroy waits for what is still in flight)+ (void) syscall(SYS_io_destroy, sc.ctx);+ sc.ctx = 0;+ return false;+ }+ for (long j = 0; j < r; ++j) {+ const io_event& e = sc.ev[(size_t) j];+ sc.got[(size_t) e.data] = e.res;+ if (e.res < 0) ok = false;+ }+ done += (size_t) r;+ }+ }+ if (!ok) return false;+ for (const Window& x : sc.win) {+ // a request may run past the end of the file: only the role's own bytes have to arrive+ if (sc.got[x.req] < 0 || (uint64_t) sc.got[x.req] < x.in_req + x.skip + x.n) return false;+ std::memcpy(x.dst + x.at, sc.buf + sc.req[x.req].pos + x.in_req + x.skip, (size_t) x.n);+ }+ return true;#else(void) fills; (void) n;return false;@@ -1151,7 +1410,7 @@ void FileExpertSource::warm(int64_t layer, const int64_t* experts, int64_t n) {const int64_t e = experts[j];if (e < 0 || e >= n_expert_) continue;const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e;- if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement)+ if (complement_ready_ && resident_blob(index) != nullptr)continue; // in the RAM copyif (warm_stamp_) warm_stamp_[index].store(stamp, std::memory_order_relaxed);warm_count_.fetch_add(1, std::memory_order_relaxed);@@ -1229,8 +1488,35 @@ void RouterLookahead::run() {}const auto t0 = std::chrono::steady_clock::now();want.clear();- strata::kernels::cpu::bf16_rows_dot_multi(routers_[(size_t) layer].data(), (int) n_expert_, (int) n_embd_,- x_.data(), (int) nt, logits.data());+ // The router dot is AVX2 (kq_avx2.cpp); a CPU without AVX2 (the experimental older-CPU builds) takes the AVX1+ // one (kq_avx1.cpp) or, without AVX, the same sums in plain C++. From the Strata_Dirigo fork (rwkeyes): an+ // AVX-only Xeon E5-2687W died here (vpmovzxwd) on its first request. An estimate only (which experts to+ // prefetch); the order of the additions differs between the three, the output does not depend on it.+ if (strata::kernels::cpu::cpu_avx2_ok()) {+ strata::kernels::cpu::bf16_rows_dot_multi(routers_[(size_t) layer].data(), (int) n_expert_, (int) n_embd_,+ x_.data(), (int) nt, logits.data());+ } else if (strata::kernels::cpu::cpu_avx1_ok()) {+ strata::kernels::cpu::bf16_rows_dot_multi_avx1(routers_[(size_t) layer].data(), (int) n_expert_,+ (int) n_embd_, x_.data(), (int) nt, logits.data());+ } else {+ // a mul and an add, not std::fma: without an FMA instruction that is a libm call per element (74x+ // slower on a Xeon E5-2665, measured by the fork)+ const uint16_t* rw = routers_[(size_t) layer].data();+ for (int64_t r = 0; r < n_expert_; ++r) {+ const uint16_t* wr = rw + (size_t) r * (size_t) n_embd_;+ for (int64_t t = 0; t < nt; ++t) {+ const float* xr = x_.data() + (size_t) t * (size_t) n_embd_;+ float acc = 0.0f;+ for (int64_t c = 0; c < n_embd_; ++c) {+ const uint32_t bits = (uint32_t) wr[c] << 16;+ float wf;+ std::memcpy(&wf, &bits, sizeof wf);+ acc += wf * xr[c];+ }+ logits[(size_t) t * (size_t) n_expert_ + (size_t) r] = acc;+ }+ }+ }for (int64_t t = 0; t < nt; ++t) {const float* lt = logits.data() + (size_t) (t * n_expert_);for (int64_t e = 0; e < n_expert_; ++e) order[(size_t) e] = (int32_t) e;@@ -1267,7 +1553,7 @@ void FileExpertSource::begin_layer(int64_t layer, const int32_t* ids, int64_t k)bool FileExpertSource::transient(int64_t layer, int64_t expert) const {if (!staged() || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false;const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;- if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement)+ if (complement_ready_ && resident_blob(index) != nullptr)return false;return override_.empty() || override_[index] == nullptr;}@@ -1279,7 +1565,7 @@ bool FileExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) {const uint64_t bytes = layer_blob_bytes_[(size_t) layer];if (complement_ready_) {const uint8_t* held =- detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr);+ resident_blob(index);if (held == nullptr && !override_.empty()) held = override_[index];if (held != nullptr) {std::memcpy(dst, held, (size_t) bytes);@@ -1309,12 +1595,65 @@ const uint8_t* FileExpertSource::mapped_blob(int64_t layer, int64_t expert) consreturn base_ + (size_t) offset;}+uint64_t FileExpertSource::release(int64_t layer, int64_t expert) {+#if defined(_WIN32)+ static const bool enabled = [] {+ const char* v = std::getenv("STRATA_FILE_RELEASE");+ return v != nullptr && std::strcmp(v, "1") == 0;+ }();+ if (!enabled || base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_)+ return 0;+ static const uint64_t page = [] {+ SYSTEM_INFO info{};+ GetSystemInfo(&info);+ return (uint64_t) info.dwPageSize;+ }();+ // These read-only file views are not CUDA-registered. blob() may instead return pinned RAM or an exchange+ // buffer, so resolve the file spans directly. A shared boundary page stays for the neighboring expert.+ auto trim = [&](const uint8_t* p, uint64_t bytes) -> uint64_t {+ const uint64_t misalignment = (uintptr_t) p % page;+ const uint64_t skip = misalignment == 0 ? 0 : page - misalignment;+ if (bytes <= skip) return 0;+ const uint64_t whole = (bytes - skip) / page * page;+ if (whole == 0) return 0;+ SetLastError(ERROR_SUCCESS);+ if (!VirtualUnlock((LPVOID) (p + (size_t) skip), (SIZE_T) whole)) {+ const DWORD error = GetLastError();+ // VirtualUnlock trims an unlocked range and reports FALSE / ERROR_NOT_LOCKED for that success.+ if (error != ERROR_NOT_LOCKED) {+ std::fprintf(stderr, "FileExpertSource: cannot trim mapped pages for layer %lld expert %lld "+ "(%llu bytes, Windows error %lu)\n",+ (long long) layer, (long long) expert, (unsigned long long) whole,+ (unsigned long) error);+ std::fflush(stderr);+ return 0;+ }+ }+ return whole; // bytes advised, not a measurement of physical RAM reclaimed+ };+ if (role_ptr_.empty()) {+ const uint8_t* p = mapped_blob(layer, expert);+ return p == nullptr ? 0 : trim(p, layer_blob_bytes_[(size_t) layer]);+ }+ uint64_t bytes = 0;+ for (int r = 0; r < 3; ++r) {+ const size_t i = (size_t) (3 * layer + r);+ bytes += trim(role_ptr_[i] + (size_t) ((uint64_t) expert * role_bytes_[i]), role_bytes_[i]);+ }+ return bytes;+#else+ (void) layer; (void) expert;+ return 0;+#endif+}+bool FileExpertSource::pin_cache_complement(const ExpertCache &cache, std::string &err, bool pin,const std::vector<std::pair<int32_t, int32_t>> &additional_gpu_pairs,int64_t lend_from_slot, uint64_t headroom_bytes, uint64_t budget_bytes,const std::vector<std::pair<int32_t, int32_t>> *rank) try {err.clear();+ const auto pin_t0 = std::chrono::steady_clock::now();if (base_ == nullptr) { err = "FileExpertSource: open the mapped experts before pinning a complement"; return false; }if (complement_ready_) { err = "FileExpertSource: the cache complement is already pinned"; return false; }if (!cache.valid()) { err = "FileExpertSource: the GPU expert cache is not open"; return false; }@@ -1384,32 +1723,33 @@ bool FileExpertSource::pin_cache_complement(}#endifconst bool what_fits = budget_bytes == kResidentWhatFits; // #467: the soft mode's second try- uint64_t budget_physical = 0; // #403: the RAM reading a budget was sized from (0: no budget)+ uint64_t budget_physical = 0; // #403: reuse the memory snapshot a budget was sized from+ uint64_t budget_commit = std::numeric_limits<uint64_t>::max();if (budget_bytes > 0) {// CS-T: a RAM budget. The complement's experts in `rank` order (the expert profile, hottest first) while- // they fit, the rest left on the mapped files; clamped to what the RAM has room for.+ // they fit, the rest left on the mapped files; Windows commit capacity also limits the allocation (#730).uint64_t physical = 0;- if (!available_memory_bytes(physical)) {- err = "FileExpertSource: cannot determine available RAM for --resident-budget-gib";+ if (!available_memory_bytes(physical, &budget_commit)) {+ err = "FileExpertSource: cannot determine available memory for --resident-budget-gib";return false;}budget_physical = physical;- const uint64_t room = physical > headroom_bytes ? physical - headroom_bytes : 0;- if (budget_bytes > room) {+ const uint64_t available = std::min(physical, budget_commit);+ const char* limit = budget_commit < physical ? "commit" : "RAM";+ const uint64_t clamped = detail::clamp_resident_budget(budget_bytes, physical, budget_commit, headroom_bytes);+ if (budget_bytes > clamped) {// #403: 256 MiB under the room, so the engine's own allocations after this reading still leave the// headroom (a budget clamped to exactly the room failed the safety check below on a reading a few MB// lower). An unclamped budget is unchanged.- const uint64_t margin = 256ull << 20;- const uint64_t clamped = room > margin ? room - margin : 0;if (what_fits)- std::fprintf(stderr, "FileExpertSource: RAM room for the complement: %.2f GiB (%.2f GiB available "+ std::fprintf(stderr, "FileExpertSource: room for the complement: %.2f GiB (%.2f GiB available %s ""minus %.0f GiB headroom and a 0.25 GiB margin)\n",- (double) clamped / 1073741824.0, (double) physical / 1073741824.0,+ (double) clamped / 1073741824.0, (double) available / 1073741824.0, limit,(double) headroom_bytes / 1073741824.0);else- std::fprintf(stderr, "FileExpertSource: --resident-budget-gib %.2f is more than the RAM has room for "- "(%.2f GiB available minus %.0f GiB headroom and a 0.25 GiB margin): %.2f GiB\n",- (double) budget_bytes / 1073741824.0, (double) physical / 1073741824.0,+ std::fprintf(stderr, "FileExpertSource: --resident-budget-gib %.2f exceeds available %s "+ "(%.2f GiB minus %.0f GiB headroom and a 0.25 GiB margin): %.2f GiB\n",+ (double) budget_bytes / 1073741824.0, limit, (double) available / 1073741824.0,(double) headroom_bytes / 1073741824.0, (double) clamped / 1073741824.0);budget_bytes = clamped;}@@ -1428,7 +1768,7 @@ bool FileExpertSource::pin_cache_complement(++held;}if (what_fits && held == 0) { // #467: nothing to keep - the caller's plain mmap fallback, not an empty copy- err = "FileExpertSource: the RAM has no room for any expert of the complement";+ err = "FileExpertSource: available memory cannot hold any expert of the complement";return false;}std::fprintf(stderr, "FileExpertSource: RAM budget %.2f GiB: %lld of the %.2f GiB of experts the GPU cache does "@@ -1445,18 +1785,20 @@ bool FileExpertSource::pin_cache_complement(// #403: with a budget, the reading it was sized from - a second reading a few MB lower (the engine's own// allocations, the file cache) failed a budget the first one had clamped. (A budget turns `lend` off.)uint64_t physical = budget_physical;- if (physical == 0 && !available_memory_bytes(physical)) {- err = "FileExpertSource: cannot determine available RAM for the resident-memory safety check";+ uint64_t commit = budget_commit;+ if (physical == 0 && !available_memory_bytes(physical, &commit)) {+ err = "FileExpertSource: cannot determine available memory for the resident-memory safety check";return false;}- budget = physical > headroom_bytes ? physical - headroom_bytes : 0;+ const uint64_t available = std::min(physical, commit);+ budget = available > headroom_bytes ? available - headroom_bytes : 0;if (bytes > budget) {char message[320];std::snprintf(message, sizeof message,- "FileExpertSource: resident complement %.2f GiB exceeds available RAM (%.2f GiB) minus the "+ "FileExpertSource: resident complement %.2f GiB exceeds available %s (%.2f GiB) minus the ""%.0f GiB safety headroom",- (double) bytes / 1073741824.0, (double) physical / 1073741824.0,- (double) headroom_bytes / 1073741824.0);+ (double) bytes / 1073741824.0, commit < physical ? "commit" : "RAM",+ (double) available / 1073741824.0, (double) headroom_bytes / 1073741824.0);err = message;return false;}@@ -1513,6 +1855,7 @@ bool FileExpertSource::pin_cache_complement(if (bytes > 0) {std::fprintf(stderr, "FileExpertSource: allocating %.2f GiB %s cache complement\n",(double) bytes / 1073741824.0, pin ? "page-locked" : "pageable resident");+ log_complement_memory("before complement allocation", bytes);std::fflush(stderr);if (pin) {const dpct::err0 allocated = DPCT_CHECK_ERROR(@@ -1566,9 +1909,19 @@ bool FileExpertSource::pin_cache_complement(}}if (arena == nullptr) {+ if (!note.empty()) {+ std::fprintf(stderr, "FileExpertSource: %s; trying pageable memory\n", note.c_str());+ log_complement_memory("before pageable allocation", bytes);+ std::fflush(stderr);+ }+ errno = 0;arena = std::malloc((size_t) bytes);if (arena == nullptr) {- err = "FileExpertSource: pageable resident complement allocation failed";+ const int allocation_errno = errno;+ err = "FileExpertSource: pageable resident complement allocation failed (malloc errno " ++ std::to_string(allocation_errno) + ": " + std::strerror(allocation_errno) + ")";+ if (!note.empty()) err += "; " + note;+ log_complement_memory("after pageable allocation failure", bytes);return false;}if (pin) {@@ -1670,6 +2023,7 @@ bool FileExpertSource::pin_cache_complement(std::atomic<uint64_t> copied{0};std::atomic<bool> failed{false};std::mutex fail_mu;+ const auto copy_t0 = std::chrono::steady_clock::now();std::string fail_msg;auto fail = [&](const std::string& m) {std::lock_guard<std::mutex> lock(fail_mu);@@ -1691,6 +2045,13 @@ bool FileExpertSource::pin_cache_complement(batch.clear();return true;};+ if (direct_.empty()) { // mapped reads: ask for the layer's blobs before copying them+ std::vector<std::pair<int32_t, int32_t>> ahead;+ for (int64_t expert = 0; expert < n_expert_; ++expert)+ if (offsets[(size_t) layer * (size_t) n_expert_ + (size_t) expert] != kNoComplement)+ ahead.emplace_back((int32_t) layer, (int32_t) expert);+ (void) advise_pairs(ahead.data(), (int64_t) ahead.size());+ }for (int64_t expert = 0; expert < n_expert_; ++expert) {const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;const uint64_t offset = offsets[index];@@ -1741,8 +2102,9 @@ bool FileExpertSource::pin_cache_complement(#endifconst int64_t done = layers_done.fetch_add(1) + 1;if (done % 8 == 0 || done == n_layers_)- std::fprintf(stderr, "FileExpertSource: copied cache complement through layer %lld/%lld (%.2f GiB)\n",- (long long) done, (long long) n_layers_, (double) copied.load() / 1073741824.0);+ std::fprintf(stderr, "FileExpertSource: copied cache complement through layer %lld/%lld (%.2f GiB, %.0f s)\n",+ (long long) done, (long long) n_layers_, (double) copied.load() / 1073741824.0,+ std::chrono::duration<double>(std::chrono::steady_clock::now() - copy_t0).count());}};{@@ -1777,9 +2139,10 @@ bool FileExpertSource::pin_cache_complement(complement_lock_off_ = lock_off;complement_lent_slots_ = lend ? n_slots - keep_from : 0;complement_ready_ = true;- std::fprintf(stderr, "FileExpertSource: %s cache complement ready: resident %.2f GiB, pinned %.2f GiB%s%s\n",+ std::fprintf(stderr, "FileExpertSource: %s cache complement ready: resident %.2f GiB, pinned %.2f GiB in %.0f s%s%s\n",complement_pinned_ ? "mapped pinned" : pin ? "locked resident" : "pageable resident",(double) resident_bytes() / 1073741824.0, (double) pinned_bytes() / 1073741824.0,+ std::chrono::duration<double>(std::chrono::steady_clock::now() - pin_t0).count(),note.empty() ? "" : "; ", note.c_str());if (lend)std::fprintf(stderr, "FileExpertSource: %lld of the prompt path's %lld lendable slots keep their experts in RAM "@@ -1799,16 +2162,25 @@ catch (sycl::exception const &exc) {std::exit(1);}+const uint8_t* FileExpertSource::resident_blob(size_t index) const {+ if (exchange_storage_.active()) return exchange_storage_.resident(index).host;+ return detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr);+}+bool FileExpertSource::has_resident(int64_t layer, int64_t expert) const {if (!complement_ready_ || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false;const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;- return index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement;+ return resident_blob(index) != nullptr;}-bool FileExpertSource::reserve_exchanges(int64_t n, std::string &err) try {+bool FileExpertSource::reserve_exchanges(int64_t n, std::string& err) {err.clear();if (n <= xstage_cap_) return true;if (!staged_.empty()) { err = "FileExpertSource: exchange buffers are in use"; return false; }+ if (exchange_storage_.active()) {+ err = "FileExpertSource: reserve maximum exchange capacity before enabling rotation";+ return false; // the original exchange allocation can now contain live resident experts+ }uint64_t blob = 0;for (const uint64_t b : layer_blob_bytes_) blob = std::max(blob, b);if (blob == 0 || n <= 0) { err = "FileExpertSource: no expert geometry for the exchange buffers"; return false; }@@ -1819,9 +2191,23 @@ bool FileExpertSource::reserve_exchanges(int64_t n, std::string &err) try {xstage_ = nullptr;xstage_cap_ = 0;}+ if ((uint64_t)n > std::numeric_limits<size_t>::max() / blob) {+ err = "FileExpertSource: exchange allocation size overflow"; return false;+ }+ const char* rotate_env = std::getenv("STRATA_EXCHANGE_ROTATE");+ const bool requested = rotate_env && std::strcmp(rotate_env, "1") == 0;+ const bool uniform = std::all_of(layer_blob_bytes_.begin(), layer_blob_bytes_.end(),+ [blob](uint64_t b) { return b == blob; });+ const bool eligible = requested && uniform && complement_pinned_ && !complement_partial_ &&+ complement_host_ && complement_device_ && complement_bytes_ > 0;const size_t total = (size_t) n * (size_t) blob;void* p = nullptr;/*+ DPCT1048: The original value cudaHostAllocMapped is not meaningful in the+ migrated code and was removed or replaced with 0. You may need to check the+ migrated code.+ */+ /*DPCT1048: The original value cudaHostAllocDefault is not meaningful in themigrated code and was removed or replaced with 0. You may need to check themigrated code.@@ -1844,21 +2230,42 @@ bool FileExpertSource::reserve_exchanges(int64_t n, std::string &err) try {xstage_ = (uint8_t*) p;xstage_cap_ = n;xstage_blob_ = blob;+ if (requested) {+ std::string reason = "requires equal-size expert blocks and a fully mapped/pinned RAM complement";+ void* device = nullptr;+ if (eligible && xstage_pinned_ &&+ DPCT_CHECK_ERROR(device = (void *)p) == 0 && device) {+ try {+ if (exchange_storage_.initialize(complement_offsets_, (uint8_t*)complement_host_, complement_device_,+ complement_bytes_, xstage_, (const uint8_t*)device, (size_t)n, (size_t)blob, reason)) {+ std::fprintf(stderr, "FileExpertSource: exchange buffer rotation enabled: %lld buffers, %llu bytes each; no host commit memcpy\n",+ (long long)n, (unsigned long long)blob);+ }+ } catch (const std::bad_alloc&) { reason = "buffer metadata allocation failed"; }+ } else if (eligible) {+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use+ the error codes. The cudaGetLastError function call was replaced+ with 0. You need to rewrite this code.+ */+ (void)0;+ reason = "exchange buffers could not be pinned and mapped";+ }+ if (!exchange_storage_.active())+ std::fprintf(stderr, "FileExpertSource: exchange rotation unavailable; retaining copy path: %s\n", reason.c_str());+ }return true;}-catch (sycl::exception const &exc) {- std::cerr << exc.what() << "Exception caught at file:" << __FILE__- << ", line:" << __LINE__ << std::endl;- std::exit(1);-}uint8_t* FileExpertSource::exchange_buffer(int64_t q) const {if (xstage_ == nullptr || q < 0 || q >= xstage_cap_) return nullptr;+ if (exchange_storage_.active()) return exchange_storage_.spare((size_t)q).host;return xstage_ + (size_t) q * (size_t) xstage_blob_;}bool FileExpertSource::stage_exchange(int64_t layer, int64_t in, int64_t out, int64_t q) {- if (!has_resident(layer, in) || has_resident(layer, out) || exchange_buffer(q) == nullptr) return false;+ if (out < 0 || out >= n_expert_ || !has_resident(layer, in) || has_resident(layer, out) ||+ exchange_buffer(q) == nullptr) return false;const size_t i_in = (size_t) layer * (size_t) n_expert_ + (size_t) in;const size_t i_out = (size_t) layer * (size_t) n_expert_ + (size_t) out;if (override_.empty()) override_.assign((size_t) blobs_, nullptr);@@ -1874,6 +2281,16 @@ int64_t FileExpertSource::commit_exchanges() {int64_t n = 0;for (const Exchange& x : staged_) {const uint8_t* src = override_[x.out];+ if (exchange_storage_.active()) {+ if (!exchange_storage_.commit(x.in, x.out, (size_t)x.q, src, (size_t)x.bytes)) {+ // Admitting the GPU swap after a failed RAM ownership update would lose an expert.+ std::fprintf(stderr, "FileExpertSource: invalid exchange rotation commit; refusing corrupt residency\n");+ std::abort();+ }+ ++n;+ override_[x.out] = nullptr;+ continue;+ }const uint64_t at = complement_offsets_[x.in];if (src != nullptr && at != kNoComplement && at <= complement_bytes_ && x.bytes <= complement_bytes_ - at &&complement_host_ != nullptr) {@@ -1887,13 +2304,57 @@ int64_t FileExpertSource::commit_exchanges() {return n;}+void FileExpertSource::commit_copies() {+ if (exchange_storage_.active()) return; // STRATA_EXCHANGE_ROTATE: ownership moves in commit_flip, nothing to copy+ for (const Exchange& x : staged_) {+ const uint8_t* src = override_.empty() ? nullptr : override_[x.out];+ const uint64_t at = complement_offsets_[x.in];+ if (src != nullptr && at != kNoComplement && at <= complement_bytes_ && x.bytes <= complement_bytes_ - at &&+ complement_host_ != nullptr)+ std::memcpy((uint8_t*) complement_host_ + (size_t) at, src, (size_t) x.bytes);+ }+}++int64_t FileExpertSource::commit_flip() {+ int64_t n = 0;+ for (const Exchange& x : staged_) {+ const uint8_t* src = override_[x.out];+ if (exchange_storage_.active()) { // STRATA_EXCHANGE_ROTATE: the same ownership transfer as commit_exchanges+ if (!exchange_storage_.commit(x.in, x.out, (size_t) x.q, src, (size_t) x.bytes)) {+ std::fprintf(stderr, "FileExpertSource: invalid exchange rotation commit; refusing corrupt residency\n");+ std::abort();+ }+ ++n;+ override_[x.out] = nullptr;+ continue;+ }+ const uint64_t at = complement_offsets_[x.in];+ // the same test as commit_copies: an exchange whose bytes were copied is the one that flips+ if (src != nullptr && at != kNoComplement && at <= complement_bytes_ && x.bytes <= complement_bytes_ - at &&+ complement_host_ != nullptr && detail::exchange_cache_complement(complement_offsets_, x.in, x.out))+ ++n;+ override_[x.out] = nullptr;+ }+ staged_.clear();+ exchanges_ += n;+ return n;+}++const uint8_t* FileExpertSource::resident_blob(int64_t layer, int64_t expert) const {+ if (!complement_ready_ || complement_host_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ ||+ expert >= n_expert_) return nullptr;+ const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;+ if (index >= complement_offsets_.size()) return nullptr;+ return resident_blob(index); // through the rotation's ownership table when STRATA_EXCHANGE_ROTATE is on+}+const uint8_t* FileExpertSource::blob(int64_t layer, int64_t expert) {if (base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return nullptr;const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;const uint8_t* result = nullptr;bool from_files = true;if (complement_ready_) {- result = detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr);+ result = resident_blob(index);if (result != nullptr) {ram_reads_.fetch_add(1, std::memory_order_relaxed);from_files = false;@@ -1920,6 +2381,7 @@ bool FileExpertSource::pinned(int64_t layer, int64_t expert) const {if (!complement_ready_ || !complement_pinned_ || complement_host_ == nullptr || layer < 0 || expert < 0 ||layer >= n_layers_ || expert >= n_expert_) return false;const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;+ if (exchange_storage_.active()) return exchange_storage_.resident(index).host != nullptr;if (index >= complement_offsets_.size() || complement_offsets_[index] == kNoComplement) return false;// a partial pin (CS-T): only the registered prefixreturn !complement_partial_ ||@@ -1929,6 +2391,7 @@ bool FileExpertSource::pinned(int64_t layer, int64_t expert) const {const uint8_t* FileExpertSource::device_alias(int64_t layer, int64_t expert) const {if (!pinned(layer, expert) || complement_device_ == nullptr) return nullptr;const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;+ if (exchange_storage_.active()) return exchange_storage_.resident(index).device;return complement_device_ + (size_t) complement_offsets_[index];}@@ -2111,6 +2574,15 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32if (d.plan != nullptr && n <= kMaxWindowEntries && n <= d.plan->cap) {int64_t distinct[kMaxWindowEntries], first_of[kMaxWindowEntries];int nd = 0, nmiss = 0;+ // a helper GPU (RemoteExperts) holding the expert computes it in its own VRAM once begin() claims the row: like+ // the peer tier's, such an expert is no miss of this plan and never part of the PCIe share, which would read it+ // over the primary's link instead (2x RX 6900 XT, IQ3_S, --remote-expert-opt with the probed share 0.39: ~4+ // helper experts per layer-window moved to PCIe, 59 ms per window against 34 ms)+ auto helper_holds = [&](int32_t e) {+ for (int r = 0; r < d.remote_count; ++r)+ if (d.remote[r]->holds(d.layers, e)) return true;+ return false;+ };for (int64_t i = 0; i < n; ++i) {first_of[i] = i;for (int64_t j = 0; j < i; ++j)@@ -2119,7 +2591,7 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32distinct[nd++] = i;const int32_t e = ids[i];if (e >= 0 && e < d.n_expert && d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] < 0 &&- !(d.peer != nullptr && d.peer->has(d.layers, e))) ++nmiss;+ !(d.peer != nullptr && d.peer->has(d.layers, e)) && !helper_holds(e)) ++nmiss;}}const bool pcie_ok = d.pcie_num > 0 && d.src->pcie_layer(d.layers);@@ -2141,6 +2613,8 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32: (size_t) slot * (size_t) d.cache_blob));} else if (d.peer != nullptr && d.peer->has(d.layers, e)) {kd = 2; // multi-GPU: the second GPU computes it+ } else if (helper_holds(e)) {+ // left to the helper: kind -1 until RemoteExperts::begin() claims the row (see above)} else {if (miss_rank >= nmiss - m && fetches < P.staging_cap && fetches < 64) {const uint8_t* src = d.src->pinned(d.layers, e) ? d.src->blob(d.layers, e) : nullptr;@@ -2218,16 +2692,30 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32for (int64_t i = 0; i < n; ++i) if (d.remote[r]->owns(i)) kind[i] = 2;}}+ static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }();+ // the GPU's copy_rows_from_mapped zeroes the rows it computed itself (dec_batch); STRATA_VERIFY_DEVICE_PLAN's+ // copy_or_zero_from_mapped copies every row, so there the host still zeroes them+ static const bool device_plan = [] { const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN"); return v != nullptr && std::atoi(v) != 0; }();+ const bool gpu_zeroes_hits = (d.plan != nullptr && n <= kMaxWindowEntries && n <= d.plan->cap && dec_batch && !device_plan);+ bool any_cpu = false;+ for (int64_t i = 0; i < n; ++i)+ if (kind[i] < 0) { any_cpu = true; break; }const auto c1 = std::chrono::steady_clock::now();- if (native && lay.fmt[(size_t) d.layers].gu_type == 42) // a native Q2_0 pack: the Q2_0 kernels' activations- for (int64_t t = 0; t < n_tok; ++t) act_quant_any(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]);- else if (native)- for (int64_t t = 0; t < n_tok; ++t)- native_quant_act(lay.fmt[(size_t) d.layers], x_f + (size_t) t * H, d.nact_multi.data() + (size_t) t * kNativeActBytes);- else- for (int64_t t = 0; t < n_tok; ++t) act_quant_q8_1(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]);+ if (any_cpu) {+ // #578 --remote-expert-opt: a token whose experts all run on a GPU (CUDA0 or a helper) needs no CPU activation+ const bool ep = d.remote_count > 0 && d.remote[0]->optimized_decode();+ for (int64_t t = 0; t < n_tok; ++t) {+ if (ep && std::all_of(kind + t * k, kind + (t + 1) * k, [](int32_t v) { return v >= 0; })) continue;+ if (native && strata::kernels::cpu::q2_native_kernels(lay.fmt[(size_t) d.layers].gu_type)) // a native Q2_0 pack: the Q2_0 kernels' activations+ act_quant_any(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]);+ else if (native)+ native_quant_act(lay.fmt[(size_t) d.layers], x_f + (size_t) t * H, d.nact_multi.data() + (size_t) t * kNativeActBytes);+ else+ act_quant_q8_1(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]);+ }+ }const auto c2 = std::chrono::steady_clock::now();- { // CS-T: the experts the CPU computes, fetched together (the GGUF in place reads them on several threads)+ if (any_cpu) { // CS-T: the experts the CPU computes, fetched together (the GGUF in place reads them on several threads)static thread_local std::vector<int64_t> miss;miss.clear();for (int64_t i = 0; i < n_tok * k; ++i)@@ -2253,8 +2741,10 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32if (kind[i] == 0) ++d.cache_hits;else ++d.offload_entries; // #588: PCIe or another GPUif (kind[i] == 2 && d.peer != nullptr) ++d.peer_entries;- // multi-GPU: a direct peer launch is writing this row right now - zeroing it would race it- if (!(kind[i] == 2 && d.peer != nullptr && d.peer->launched_direct()))+ // multi-GPU: a direct peer launch is writing this row right now - zeroing it would race it;+ // dec_batch: copy_rows_from_mapped_kernel already zeroes kind 0/1 rows on the GPU+ if (!((kind[i] == 2 && d.peer != nullptr && d.peer->launched_direct()) ||+ (gpu_zeroes_hits && (kind[i] == 0 || kind[i] == 1))))std::memset(row, 0, (size_t) H * sizeof(float));continue;}@@ -2284,8 +2774,10 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32}const auto c3 = std::chrono::steady_clock::now();pt("run", njobs);- if (native) d.pool->run_split_multi_native(lay.fmt[(size_t) d.layers], d.jobs_multi.data(), njobs);- else d.pool->run_split_multi(d.jobs_multi.data(), njobs);+ if (njobs > 0) {+ if (native) d.pool->run_split_multi_native(lay.fmt[(size_t) d.layers], d.jobs_multi.data(), njobs);+ else d.pool->run_split_multi(d.jobs_multi.data(), njobs);+ }if (d.remote_count > 0) {static thread_local std::string remote_error;for (int r = 0; r < d.remote_count; ++r)@@ -2569,6 +3061,17 @@ std::string expert_gguf_file(const std::string& gguf, const strata::kernels::cpu}} // namespace+void ExpertSource::record_inputs(const std::string& pack_experts, const std::string& gguf,+ const strata::kernels::cpu::ExpertLayout& lay, bool from_gguf) {+ static const char* roles[3] = {"gate", "up", "down"};+ inputs_.clear();+ if (!from_gguf) { inputs_.push_back({"pack experts.bin", pack_experts}); return; }+ // the same resolution open_gguf / load_experts_gguf use: every (layer, role) tensor and the file it is read from+ for (int64_t l = 0; l < lay.n_layers; ++l)+ for (int r = 0; r < 3; ++r)+ inputs_.push_back({"expert blk." + std::to_string(l) + ".ffn_" + roles[r], expert_gguf_file(gguf, lay, l, r)});+}+bool check_experts_gguf(const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay, std::string& err) {static const char* roles[3] = {"gate", "up", "down"};if (lay.gguf_off.size() != (size_t) (3 * lay.n_layers)) {@@ -2630,7 +3133,13 @@ bool check_experts_gguf(const std::string& gguf, const strata::kernels::cpu::Exp// `unbuffered` (Windows, experts_unbuffered): each chunk's 4 KiB-aligned window is read with FILE_FLAG_NO_BUFFERING into// an aligned buffer and scattered into the blobs - no copy through the file cache when the drive is read anyway.LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata::kernels::cpu::ExpertLayout& lay,- int threads, bool unbuffered) {+ int threads, bool unbuffered, const std::atomic<int>* ready) {+ // `ready`: layer l is written only once *ready > l + 1 (a PinnedArena registering its slices meanwhile; the next+ // slice too, since its registration starts on the page that may hold this layer's tail)+ auto wait_ready = [ready](int64_t l) {+ if (ready != nullptr)+ while (ready->load(std::memory_order_acquire) <= l + 1) std::this_thread::yield();+ };LoadStats st;st.layers = (uint64_t) lay.n_layers;const auto t0 = std::chrono::steady_clock::now();@@ -2660,6 +3169,7 @@ LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata:for (;;) {const int64_t l = next.fetch_add(1);if (l >= lay.n_layers || bad) break;+ wait_ready(l);const auto& fm = lay.fmt[(size_t) l];const uint64_t blob = lay.bytes[(size_t) l];const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off};@@ -2738,6 +3248,7 @@ LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata:for (;;) {const int64_t l = next.fetch_add(1);if (l >= lay.n_layers || bad) break;+ wait_ready(l);const auto& fm = lay.fmt[(size_t) l];const uint64_t blob = lay.bytes[(size_t) l];const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off};@@ -2859,6 +3370,7 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6note_ = "mapped read-only from " + path + " (STRATA_ARENA_MMAP: not locked, not pinned)";gib_per_s_ = 0.0;load_seconds_ = load_read_s_ = load_copy_s_ = 0.0;+ record_inputs(path, gguf_, lay, from_gguf); // session files: the mapped experts.bin is a model inputreturn true;}}@@ -2908,8 +3420,22 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6lbytes.push_back(lay.blob_bytes(l) * (uint64_t) n_expert);}bounds.push_back(want);- PinnedArena* a = new PinnedArena(want + (uint64_t) blob, bounds, max_pinned_bytes,- shared_arena_file, pack_hash);+ // #285: on Windows the per-layer registration runs on a thread ahead of the readers, which wait for their+ // layer's slice (the whole arena registered before the load cost ~2.5 s at 33 GiB of 4 KB pages, not hidden).+ // Only where the whole arena would be registered: no cap (STRATA_ARENA_PIN_GIB, multi-GPU), no shared arena.+ // Linux keeps the whole-arena pin (#253). OPT-IN (STRATA_DEFERRED_REGISTER=1): on the RTX 5070 / Windows the+ // arena registered per layer before it is filled decoded ~10% slower than the old order (whole-arena try, sliced+ // fallback after the load) with identical output; the start-time gain does not pay for that.+#ifdef _WIN32+ const char* defer_env = std::getenv("STRATA_DEFERRED_REGISTER");+ const bool deferred = max_pinned_bytes == 0 && arena_pin_cap_gib() == -1 && shared_arena_file.empty() &&+ (defer_env != nullptr && defer_env[0] != 0 && defer_env[0] != '0');+#else+ const bool deferred = false;+#endif+ PinnedArena* a = deferred ? new PinnedArena(want + (uint64_t) blob, bounds, PinnedArena::Deferred{})+ : new PinnedArena(want + (uint64_t) blob, bounds, max_pinned_bytes,+ shared_arena_file, pack_hash);if (!a->valid()) {const std::string why = a->note;delete a;@@ -2934,13 +3460,29 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6const bool unbuffered = experts_unbuffered(files, want + (uint64_t) blob, why);const int readers = unbuffered ? std::max(threads, 16) : threads; // 16 keep a PCIe 5 drive's queue fullLoadStats st;+ std::atomic<int> ready{0};+ std::thread reg;+ if (deferred) {+ int dev = 0;+ dev = dpct::get_current_device_id();+ reg = std::thread([a, &ready, dev] {+ /*+ DPCT1093: The "dev" device may be not the one intended for use.+ Adjust the selected device if needed.+ */+ dpct::select_device(dev);+ a->register_slices(ready);+ });+ }+ const std::atomic<int>* rp = deferred ? &ready : nullptr;if (from_gguf) {- st = load_experts_gguf(gguf_, a->data(), lay, readers, unbuffered);+ st = load_experts_gguf(gguf_, a->data(), lay, readers, unbuffered, rp);} else {- if (unbuffered) st = load_experts_direct(path, a->data(), loff, lbytes, readers, /*chunk=*/8u << 20);+ if (unbuffered) st = load_experts_direct(path, a->data(), loff, lbytes, readers, /*chunk=*/8u << 20, rp);if (!unbuffered || (!st.ok && st.error.empty())) // unaligned ranges: the buffered reader- st = load_experts_ranges(path, a->data(), loff, lbytes, threads, /*chunk=*/8u << 20);+ st = load_experts_ranges(path, a->data(), loff, lbytes, threads, /*chunk=*/8u << 20, rp);}+ if (reg.joinable()) reg.join();std::fprintf(stderr, "strata generate: expert arena read %s (%s)\n", unbuffered ? "unbuffered" : "through the file cache",why.c_str());if (!st.ok) {@@ -2953,6 +3495,10 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6err = "ArenaExpertSource: the load read " + std::to_string(st.bytes) + " B of " + std::to_string(want);return false;}+ if (std::getenv("STRATA_VERIFY_ARENA") != nullptr) { // tests: the loaded arena's checksum, any loader+ std::fprintf(stderr, "strata generate: expert arena checksum %016llx (%.2f GiB)\n",+ (unsigned long long) fnv1a64(a->data(), want), (double) want / (1ull << 30));+ }// the first start: write experts.bin for the mapped starts after this one - only when the drive has room for it// and 2 GiB more (a full drive fails other writes too); otherwise this start says so and runs pinned as beforestd::error_code space_ec;@@ -3008,6 +3554,7 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6load_seconds_ = st.seconds;load_read_s_ = st.read_seconds;load_copy_s_ = st.copy_seconds;+ record_inputs(path, gguf_, lay, from_gguf);return true;}@@ -3017,6 +3564,7 @@ void ArenaExpertSource::close() {#endifmap_ = nullptr;map_bytes_ = 0;+ inputs_.clear();if (arena_ != nullptr) {delete (PinnedArena*) arena_;arena_ = nullptr;diff --git a/sycl/src/core/layer.cpp b/sycl/src/core/layer.cppindex 54da32fd5..2ce1aa479 100644--- a/sycl/src/core/layer.cpp+++ b/sycl/src/core/layer.cpp@@ -40,6 +40,8 @@#include <cmath>#include <cstdio>#include <cstring>+#include <limits>+#include <memory>#include <vector>namespace strata::core {namespace { bool g_shared_early = true; bool g_fused_gr = false; bool g_fast_attn = true; bool g_publish_kernel = true; bool g_fused_gdn = true; bool g_fast_select = true; }@@ -448,6 +450,34 @@ catch (sycl::exception const &exc) {<< ", line:" << __LINE__ << std::endl;std::exit(1);}+// The verify window's routing: n tokens' logits in one BF16 projection and their top-k in one launch, each token+// bitwise what `moe_route` gives it (the projection is the same kernel per column, the top-k kernel is per token).+// Anything else (a native router, the canonical BF16 GEMVs, a doorbell) takes the per-token `moe_route`.+bool moe_route_window(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b,+ const float* x, float* logits, int32_t* ids, float* weights, int n, void* stream, std::string& err) {+ using namespace strata::kernels;+ const bool batched = native_bf16_projections && !(native_router_enabled() && g.n_expert == 512 && k == 10) &&+ !std::getenv("STRATA_ROUTE_PER_TOKEN");+ if (!batched || n == 1) {+ for (int t = 0; t < n; ++t) {+ MoEBuffers mb = b;+ mb.logits = logits + t * g.n_expert; mb.ids = ids + t * k; mb.weights = weights + t * k;+ if (!moe_route(tables, g, layer, k, mb, x + t * g.n_embd, stream, err, nullptr)) return false;+ }+ return true;+ }+ const LayerView v(tables, layer);+ const WeightRef* w_router = v.get("ffn_gate_inp.weight");+ if (w_router == nullptr) { err = v.name("ffn_gate_inp.weight") + " is missing"; return false; }+ if (std::getenv("STRATA_ROUTE_PROJ_PER_TOKEN"))+ for (int t = 0; t < n; ++t)+ bf16_gemv_fp32_mmvf(x + t * g.n_embd, (const uint16_t*) w_router->data, logits + t * g.n_expert, g.n_embd,+ g.n_expert, stream);+ else+ bf16_gemv_fp32_mmvf_cols(x, (const uint16_t*) w_router->data, logits, g.n_embd, g.n_expert, n, stream);+ router_top10(logits, n, (int) g.n_expert, (int) k, ids, weights, stream);+ return true;+}bool moe_shared(const WeightTable& tables, const ModelGeometry& g, int64_t layer, const MoEBuffers& b, const float* x, void* stream, std::string& err) { using namespace strata::kernels; const LayerView v(tables, layer); const WeightRef* w_ginp = v.get("ffn_gate_inp_shexp.weight"); const WeightRef* w_sgate = v.get("ffn_gate_shexp.weight"); const WeightRef* w_sup = v.get("ffn_up_shexp.weight"); const WeightRef* w_sdown = v.get("ffn_down_shexp.weight"); const char* missing = !w_ginp ? "ffn_gate_inp_shexp.weight" : !w_sgate ? "ffn_gate_shexp.weight" : !w_sup ? "ffn_up_shexp.weight" : !w_sdown ? "ffn_down_shexp.weight" : nullptr; if (missing) { err = v.name(missing) + " is missing"; return false; }// ---- the shared expert. Its three weights are quantized, so they need their planes.SForm f_gate, f_up, f_down; if (!sform_of(*w_sgate, f_gate, v.name("ffn_gate_shexp.weight"), err)) return false; if (!sform_of(*w_sup, f_up, v.name("ffn_up_shexp.weight"), err)) return false; if (!sform_of(*w_sdown, f_down, v.name("ffn_down_shexp.weight"), err)) return false; Planes p_gate, p_up, p_down; if (!plane_ptrs(*w_sgate, v.name("ffn_gate_shexp.weight"), p_gate, err)) return false; if (!plane_ptrs(*w_sup, v.name("ffn_up_shexp.weight"), p_up, err)) return false; if (!plane_ptrs(*w_sdown, v.name("ffn_down_shexp.weight"), p_down, err)) return false;@@ -548,6 +578,144 @@ namespace {int64_t g_kv_resident = 0;uint64_t g_kv_host_bytes = 0;+// ---- the elastic K/V (--kv-grow): one VMM range per state, each pool array at a chunk boundary in it+bool g_kv_elastic = false;+int64_t g_kv_elastic_init = 16384;+struct ElasticPool {+ strata::core::VmmRange range;+ std::vector<uint64_t> off, per_slot; // each array's offset in the range (whole chunks) and bytes per page slot+ int64_t n_slots = 0, page_size = 0;+};+std::vector<std::unique_ptr<ElasticPool>> g_pools;++int64_t pool_chunks(const ElasticPool& p, size_t a, int64_t slots) {+ const uint64_t G = strata::core::vmm_granularity();+ return (int64_t) (((uint64_t) slots * p.per_slot[a] + G - 1) / G);+}+int64_t pool_slots(const ElasticPool& p, int64_t cells) {+ return std::min<int64_t>(p.n_slots, std::max<int64_t>((cells + p.page_size - 1) / p.page_size, 1));+}+/// Whole page slots every array of the pool has mapped.+int64_t pool_slots_mapped(const ElasticPool& p) {+ const uint64_t G = strata::core::vmm_granularity();+ int64_t slots = p.n_slots;+ for (size_t a = 0; a < p.off.size(); ++a) {+ const int64_t c0 = (int64_t) (p.off[a] / G);+ const int64_t end = a + 1 < p.off.size() ? (int64_t) (p.off[a + 1] / G) : p.range.chunks();+ int64_t c = 0;+ while (c0 + c < end && p.range.mapped(c0 + c)) ++c;+ slots = std::min<int64_t>(slots, (int64_t) ((uint64_t) c * G / p.per_slot[a]));+ }+ return slots;+}+bool pool_grow(ElasticPool &p, int64_t cells,+ const std::function<strata::core::VmmChunk()> &take) try {+ const uint64_t G = strata::core::vmm_granularity();+ const int64_t slots = pool_slots(p, cells);+ for (size_t a = 0; a < p.off.size(); ++a) {+ const int64_t c0 = (int64_t) (p.off[a] / G), c1 = c0 + pool_chunks(p, a, slots);+ std::vector<int64_t> fresh;+ for (int64_t c = c0; c < c1; ++c)+ if (!p.range.mapped(c)) fresh.push_back(c);+ if (fresh.empty()) continue;+ if (!p.range.map_range(c0, c1, take)) {+ std::fprintf(stderr, "strata: the elastic K/V could not map %zu chunks (the driver has no VRAM left)\n",+ fresh.size());+ return false;+ }+ // what the chunk held before (another pool's cells, an expert) is not K/V: zeroed, as a new session is+ for (const int64_t c : fresh)+ if (DPCT_CHECK_ERROR(+ dpct::get_in_order_queue()+ .memset(p.range.base() + (uint64_t)c * G, 0, (size_t)G)+ .wait()) != 0) {+ std::fprintf(+ stderr,+ "strata: the elastic K/V could not clear a chunk: %s\n",+ /*+ DPCT1009: SYCL reports errors using exceptions and does+ not use error codes. Please replace the+ "get_error_string_dummy(...)" with a real error-handling+ function.+ */+ /*+ DPCT1010: SYCL uses exceptions to report errors and+ does not use the error codes. The cudaGetLastError function+ call was replaced with 0. You need to rewrite this code.+ */+ dpct::get_error_string_dummy(0));+ return false;+ }+ }+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}+} // namespace++void qsa_set_kv_elastic(bool enabled, int64_t init_cells) {+ g_kv_elastic = enabled && strata::core::vmm_available();+ if (init_cells > 0) g_kv_elastic_init = init_cells;+}+bool qsa_kv_elastic() { return g_kv_elastic; }+int64_t qsa_kv_elastic_cells() {+ int64_t cells = std::numeric_limits<int64_t>::max();+ for (const auto& p : g_pools) cells = std::min<int64_t>(cells, pool_slots_mapped(*p) * p->page_size);+ return cells;+}+int64_t qsa_kv_elastic_need(int64_t cells) {+ const uint64_t G = strata::core::vmm_granularity();+ int64_t n = 0;+ for (const auto& p : g_pools) {+ const int64_t slots = pool_slots(*p, cells);+ for (size_t a = 0; a < p->off.size(); ++a) {+ const int64_t c0 = (int64_t) (p->off[a] / G), c1 = c0 + pool_chunks(*p, a, slots);+ for (int64_t c = c0; c < c1; ++c) n += !p->range.mapped(c);+ }+ }+ return n;+}+bool qsa_kv_elastic_grow(+ int64_t cells, const std::function<strata::core::VmmChunk()> &take) try {+ for (auto& p : g_pools)+ if (!pool_grow(*p, cells, take)) return false;+ return DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()) == 0;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}+int64_t qsa_kv_elastic_shrink(int64_t cells, const std::function<void(strata::core::VmmChunk)>& give) {+ const uint64_t G = strata::core::vmm_granularity();+ int64_t n = 0;+ for (auto& p : g_pools) {+ const int64_t slots = pool_slots(*p, cells);+ for (size_t a = 0; a < p->off.size(); ++a) {+ const int64_t c0 = (int64_t) (p->off[a] / G), c1 = c0 + pool_chunks(*p, a, slots);+ const int64_t end = a + 1 < p->off.size() ? (int64_t) (p->off[a + 1] / G) : p->range.chunks();+ for (int64_t c = c1; c < end; ++c)+ if (const strata::core::VmmChunk h = p->range.unmap(c)) { give(h); ++n; }+ }+ }+ return n;+}+uint64_t qsa_kv_elastic_mapped_bytes() {+ uint64_t n = 0;+ for (const auto& p : g_pools) n += (uint64_t) p->range.mapped_count() * strata::core::vmm_granularity();+ return n;+}+uint64_t qsa_kv_elastic_full_bytes() {+ uint64_t n = 0;+ for (const auto& p : g_pools) n += (uint64_t) p->range.chunks() * strata::core::vmm_granularity();+ return n;+}+namespace {+/// How one state holds its K/V: `mode` as in QsaState::kv_mode, `slots` VRAM pages of `pages` logical ones.struct KvPlan {int mode = 0;@@ -593,8 +761,9 @@ uint64_t qsa_state_bytes(const ModelGeometry& g, int64_t max_cells, bool with_roconst QsaShapes s = qsa_shapes(g);const KvPlan p = kv_plan(s, max_cells, ring_cells);uint64_t n = 0;- n += kv_pool_bytes(s, p.slots, g_kv_hybrid && ring_cells <= 0,- g_kv_int8 || g_kv_hybrid) + 4 * 16; // K/V pools (the VRAM slots)+ if (!(g_kv_elastic && p.mode == 0)) // the elastic K/V's pools are in their own VMM range+ n += kv_pool_bytes(s, p.slots, g_kv_hybrid && ring_cells <= 0,+ g_kv_int8 || g_kv_hybrid) + 4 * 16; // K/V pools (the VRAM slots)n += (uint64_t) p.pages * 4; // page_tableif (p.mode == 1) n += strata::kernels::kv_stream_map_bytes(p.slots) + 6 * 16; // the residency mapn += (uint64_t) (s.idx_block - 1) * s.idx_dim * 4; // tail@@ -607,9 +776,8 @@ uint64_t qsa_state_bytes(const ModelGeometry& g, int64_t max_cells, bool with_roreturn align_up16(n) + 256;}-uint64_t qsa_state_init(const ModelGeometry &g, int64_t max_cells, void *base,- QsaState &st, const QsaState *share_rope,- int64_t ring_cells) try {+uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaState& st,+ const QsaState* share_rope, int64_t ring_cells) {const QsaShapes s = qsa_shapes(g);const KvPlan p = kv_plan(s, max_cells, ring_cells);const int64_t pages = p.pages;@@ -617,12 +785,8 @@ uint64_t qsa_state_init(const ModelGeometry &g, int64_t max_cells, void *base,st.kv_int8 = g_kv_int8 && !g_kv_q4;st.kv_q4 = g_kv_q4;// Hybrid K8V4, main layers only (the drafter's state is created with the globals toggled to INT8 -- // mtp.cpp). Streamed mode is refused outright; generate.cpp validates it too, this is the backstop.+ // mtp.cpp). A streamed one keeps its host copy in the same three runs (kv_stream.cu, kKvHybrid).if (g_kv_hybrid && ring_cells <= 0) {- if (p.mode == 1) {- std::fprintf(stderr, "strata: hybrid K8V4 KV does not support --kv-resident streaming\n");- return 0;- }st.kv_hybrid = true;st.kv_int8 = false;st.kv_q4 = false;@@ -632,7 +796,43 @@ uint64_t qsa_state_init(const ModelGeometry &g, int64_t max_cells, void *base,st.n_slots = p.slots;const uint64_t rows = (uint64_t) p.slots * s.n_head_kv * s.page_size; // VRAM rows: the slotsconst uint64_t q4_row = strata::kernels::kv_q4_bytes_per_head((int) s.head_dim);- if (st.kv_hybrid) {+ st.kv_elastic = -1;+ if (g_kv_elastic && p.mode == 0) {+ // the elastic K/V: each array at a chunk boundary of the state's own range, the first cells mapped+ const uint64_t slot_rows = (uint64_t) s.n_head_kv * s.page_size;+ const uint64_t scale_row = (uint64_t) (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2;+ std::vector<uint64_t> per; // bytes per page slot of each array, in the order they are assigned below+ if (st.kv_hybrid) per = {slot_rows * s.head_dim, slot_rows * scale_row, slot_rows * q4_row};+ else if (st.kv_q4) per = {slot_rows * q4_row, slot_rows * q4_row};+ else if (st.kv_int8) per = {slot_rows * s.head_dim, slot_rows * s.head_dim, slot_rows * scale_row, slot_rows * scale_row};+ else per = {slot_rows * s.head_dim * 2, slot_rows * s.head_dim * 2};+ auto pool = std::make_unique<ElasticPool>();+ const uint64_t G = strata::core::vmm_granularity();+ uint64_t at = 0;+ for (const uint64_t b : per) {+ pool->off.push_back(at);+ at += ((uint64_t) p.slots * b + G - 1) / G * G;+ }+ pool->per_slot = per;+ pool->n_slots = p.slots;+ pool->page_size = s.page_size;+ if (!pool->range.reserve(at) || !pool_grow(*pool, g_kv_elastic_init, [] { return (strata::core::VmmChunk) 0; })) {+ std::fprintf(stderr, "strata: the elastic K/V could not reserve or map its pools\n");+ return 0;+ }+ uint8_t* b = pool->range.base();+ const uint64_t* o = pool->off.data();+ if (st.kv_hybrid) { st.k_q = (int8_t*) (b + o[0]); st.k_scale = (uint16_t*) (b + o[1]); st.v_q4 = b + o[2]; }+ else if (st.kv_q4) { st.k_q4 = b + o[0]; st.v_q4 = b + o[1]; }+ else if (st.kv_int8) {+ st.k_q = (int8_t*) (b + o[0]);+ st.v_q = (int8_t*) (b + o[1]);+ st.k_scale = (uint16_t*) (b + o[2]);+ st.v_scale = (uint16_t*) (b + o[3]);+ } else { st.k_pool = (uint16_t*) (b + o[0]); st.v_pool = (uint16_t*) (b + o[1]); }+ st.kv_elastic = (int32_t) g_pools.size();+ g_pools.push_back(std::move(pool));+ } else if (st.kv_hybrid) {st.k_q = c.take<int8_t>(rows * s.head_dim);st.k_scale = c.take<uint16_t>(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP));st.v_q4 = c.take<uint8_t>(rows * q4_row);@@ -728,7 +928,11 @@ uint64_t qsa_state_init(const ModelGeometry &g, int64_t max_cells, void *base,}g_kv_host_bytes += bytes;Cursor hc{d};- if (st.kv_q4) {+ if (st.kv_hybrid) {+ st.host.k_q = hc.take<int8_t>(hrows * s.head_dim);+ st.host.k_scale = hc.take<uint16_t>(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP));+ st.host.v_q4 = hc.take<uint8_t>(hrows * q4_row);+ } else if (st.kv_q4) {st.host.k_q4 = hc.take<uint8_t>(hrows * q4_row);st.host.v_q4 = hc.take<uint8_t>(hrows * q4_row);} else if (st.kv_int8) {@@ -775,16 +979,13 @@ uint64_t qsa_state_init(const ModelGeometry &g, int64_t max_cells, void *base,dpct::get_current_device().queues_wait_and_throw();return c.used;}-catch (sycl::exception const &exc) {- std::cerr << exc.what() << "Exception caught at file:" << __FILE__- << ", line:" << __LINE__ << std::endl;- std::exit(1);-}void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream) {const QsaShapes s = qsa_shapes(g);dpct::queue_ptr cs = strata::q_of(stream);- const size_t rows = (size_t) st.n_slots * s.n_head_kv * s.page_size;+ // an elastic state zeroes what is mapped (the rest is zeroed when it is mapped)+ const int64_t live_slots = st.kv_elastic >= 0 ? pool_slots_mapped(*g_pools[(size_t) st.kv_elastic]) : st.n_slots;+ const size_t rows = (size_t) live_slots * s.n_head_kv * s.page_size;if (st.kv_hybrid) {cs->memset(st.k_q, 0, rows * s.head_dim);cs->memset(st.k_scale, 0,@@ -1044,9 +1245,15 @@ if (st.kv_hybrid) {// K8V4: only V is rotated (kv_q4.hpp's H); the scores pair unrotated q with unrotated INT8 K, and the// output - a mix of rotated values - is rotated back after attention. Each append/gather call folds the// unused half's lanes onto the used pool (a bit-identical duplicate write), so no kernel variants exist.+ // Streamed (--kv-resident), each half also writes its part of the host copy (kv_hybrid_*_half).strata::kernels::fwht256_inplace_cuda(b.vcur, g.n_head_kv, stream);- kv_append_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, st.step, b.kcur, b.kcur, s, stream, nullptr); // mode 0: no host mirror- strata::kernels::kv_append_q4_step(st.v_q4, st.v_q4, st.page_table, st.step, b.vcur, b.vcur, s, stream, nullptr);+ const strata::kernels::KvHostPools hk = strata::kernels::kv_hybrid_k_half(st.host),+ hv = strata::kernels::kv_hybrid_v_half(st.host);+ const bool mirror = st.host.present();+ kv_append_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, st.step, b.kcur, b.kcur, s, stream,+ mirror ? &hk : nullptr);+ strata::kernels::kv_append_q4_step(st.v_q4, st.v_q4, st.page_table, st.step, b.vcur, b.vcur, s, stream,+ mirror ? &hv : nullptr);} else {if (st.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1strata::kernels::fwht256_inplace_cuda(b.kcur, g.n_head_kv, stream);@@ -1386,9 +1593,9 @@ bool block_layer_pre(const WeightTable &tables, const ModelGeometry &g,// would be the natural reading and would scramble the channels.strata::kernels::ple_history_advance(ple->hist, po.normalized, stream);/*- DPCT1010: SYCL uses exceptions to report errors and does not use the- error codes. The cudaPeekAtLastError function call was replaced with 0.- You need to rewrite this code.+ DPCT1010: SYCL uses exceptions to report errors and does not use+ the error codes. The cudaPeekAtLastError function call was replaced with+ 0. You need to rewrite this code.*/if (0 != 0) {err = "block_layer_pre: the PLE history shift failed";diff --git a/sycl/src/core/mtp.cpp b/sycl/src/core/mtp.cppindex 554afd47e..aa2fa6703 100644--- a/sycl/src/core/mtp.cpp+++ b/sycl/src/core/mtp.cpp@@ -1,4 +1,5 @@// src/core/mtp.cpp - see include/strata/core/mtp.hpp.+#define DPCT_PROFILING_ENABLED#include <sycl/sycl.hpp>#include <dpct/dpct.hpp>#include "strata/core/mtp.hpp"@@ -7,6 +8,7 @@#include "strata/core/native_head.hpp"#include "strata/core/peer_experts.hpp"+#include "strata/platform/memory.hpp"#include "strata/kernels/bf16_gemv.hpp"#include "strata/kernels/cpu/expert.hpp"#include "strata/kernels/elementwise.hpp"@@ -28,6 +30,7 @@#include "strata/kernels/sampler.hpp"#include "strata/kernels/shared_expert.hpp"#include "strata/kernels/verify_kernels.hpp"+#include "strata/kernels/ngram.hpp"#include <algorithm>#include <atomic>@@ -39,12 +42,31 @@#include <fstream>#include <sstream>#include <vector>+#if defined(_WIN32)+#include <intrin.h>+#elif defined(__x86_64__)+#include <immintrin.h>+#endif++#ifdef STRATA_NATIVE_EXPERTS+#include "ggml.h" // --mtp-q4: the head rows' and projections' formats, dequantized and requantized at load+#endifnamespace strata::core {namespace {constexpr float EPS = 1e-6f;++// #783 PR-i: STRATA_MTP_CATCHUP_ALL=1 catches the drafter's K/V up for the whole verified window, rejected rows included+bool mtp_catchup_all() {+ static const bool on = [] {+ const char* v = std::getenv("STRATA_MTP_CATCHUP_ALL");+ return v != nullptr && v[0] != '\0' && v[0] != '0';+ }();+ return on;+}constexpr int GGML_Q8_0 = 8;+constexpr int GGML_Q4_0 = 2;using Clock = std::chrono::steady_clock;double ms_since(Clock::time_point t) { return std::chrono::duration<double, std::milli>(Clock::now() - t).count(); }@@ -109,6 +131,9 @@ bool read_file(const std::string& path, std::vector<uint8_t>& out) {if (STRATA_FILE_SEEK64(f, 0, SEEK_END) != 0) return false;const long long n = (long long) STRATA_FILE_TELL64(f);if (n < 0 || STRATA_FILE_SEEK64(f, 0, SEEK_SET) != 0) return false;+#if !defined(_WIN32)+ strata::platform::advise_willneed(fileno(f), 0, (uint64_t) n);+#endifout.resize((size_t) n);return n == 0 || std::fread(out.data(), 1, (size_t) n, f) == (size_t) n;}@@ -120,6 +145,7 @@ MtpDrafter::~MtpDrafter() {for (auto &e : prefill_exec_) if (e) delete (e);for (auto &e : prefill_dev_exec_) if (e) delete (e);if (pf_dev_) sycl::free(pf_dev_, dpct::get_in_order_queue());+ if (dense4_) sycl::free(dense4_, dpct::get_in_order_queue());for (auto &e : round_exec_) if (e) delete (e);for (auto &e : step_exec_) if (e) delete (e);for (auto &e : round_exec_c_) if (e) delete (e);@@ -131,14 +157,24 @@ MtpDrafter::~MtpDrafter() {if (h_cparams_) sycl::free(h_cparams_, dpct::get_in_order_queue());if (h_chist_) sycl::free(h_chist_, dpct::get_in_order_queue());if (cs_) dpct::get_current_device().destroy_queue(cs_);- if (dense_) sycl::free(dense_, dpct::get_in_order_queue());- if (experts_) sycl::free(experts_, dpct::get_in_order_queue());+ if (side_) dpct::get_current_device().destroy_queue(side_);+ if (sh_fork_) dpct::destroy_event(sh_fork_);+ if (sh_join_) dpct::destroy_event(sh_join_);+ if (owns_weights_ && dense_) sycl::free(dense_, dpct::get_in_order_queue());+ if (owns_weights_ && experts_)+ sycl::free(experts_, dpct::get_in_order_queue());if (state_arena_) sycl::free(state_arena_, dpct::get_in_order_queue());if (arena_) sycl::free(arena_, dpct::get_in_order_queue());if (head_logits_) sycl::free(head_logits_, dpct::get_in_order_queue());- if (dhead_) sycl::free(dhead_, dpct::get_in_order_queue());- if (dvocab_) sycl::free(dvocab_, dpct::get_in_order_queue());- void* hosts[] = {h_tok_, h_step_, h_pos_, h_row_, h_out_, h_prob_};+ if (owns_draft_head_ && dhead_) {+ strata::kernels::native_q6_k_unpack(dhead_);+ sycl::free(dhead_, dpct::get_in_order_queue());+ }+ if (owns_draft_head_ && dvocab_)+ sycl::free(dvocab_, dpct::get_in_order_queue());+ if (ev_chain_) dpct::destroy_event(ev_chain_);+ for (dpct::event_ptr e : ev_step_) if (e) dpct::destroy_event(e);+ void* hosts[] = {h_tok_, h_step_, h_pos_, h_row_, h_out_, h_prob_, h_force_};for (void *h : hosts) if (h) sycl::free(h, dpct::get_in_order_queue());}@@ -154,23 +190,107 @@ const void* MtpDrafter::q8(const char* name) const {for (const auto& t : tensors_) if (t.name == name && t.kind == "q8_0") return dense_ + t.off;return nullptr;}+const void* MtpDrafter::wq(const char* name, int& type) const {+ if (dense4_ != nullptr)+ for (const auto& e : q4_off_)+ if (e.first == name) { type = GGML_Q4_0; return dense4_ + e.second; }+ type = GGML_Q8_0;+ return q8(name);+}++// --mtp-q4: every Q8_0 tensor of dense.bin as Q4_0 (ggml's reference quantizer), in one device buffer+bool MtpDrafter::make_q4_dense(const std::vector<uint8_t>& blob, std::string& err) {+#ifdef STRATA_NATIVE_EXPERTS+ uint64_t total = 0;+ std::vector<std::pair<const Tensor*, uint64_t>> plan;+ for (const auto& t : tensors_) {+ if (t.kind != "q8_0" || t.cols % 32 != 0) continue;+ plan.push_back({&t, total});+ total += ((uint64_t) t.rows * (uint64_t) (t.cols / 32) * 18 + 255) & ~255ull;+ }+ std::vector<uint8_t> host((size_t) total);+ std::vector<float> row;+ const auto* q8t = ggml_get_type_traits(GGML_TYPE_Q8_0);+ for (const auto& [t, off] : plan) {+ row.resize((size_t) t->cols);+ const uint64_t in_row = (uint64_t) (t->cols / 32) * 34, out_row = (uint64_t) (t->cols / 32) * 18;+ for (int64_t r = 0; r < t->rows; ++r) {+ q8t->to_float(blob.data() + t->off + (uint64_t) r * in_row, row.data(), t->cols);+ ggml_quantize_chunk(GGML_TYPE_Q4_0, row.data(), host.data() + off + (uint64_t) r * out_row, 0, 1, t->cols,+ nullptr);+ }+ q4_off_.push_back({t->name, off});+ }+ dense4_ = (uint8_t*) sycl::malloc_device((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;+ std::fprintf(stderr, "strata mtp: --mtp-q4: %zu projections as Q4_0 (%.1f MiB)\n", plan.size(), (double) total / 1048576.0);+ return true;+#else+ (void) blob;+ err = "mtp: --mtp-q4 needs a build with native experts (ggml)";+ return false;+#endif+}++// --mtp-q4: the draft head's subset rows as Q4_0 (dequantized from the main head's format)+bool MtpDrafter::make_q4_head(std::string& err) {+#ifdef STRATA_NATIVE_EXPERTS+ const int64_t N = g_->n_embd;+ const auto* tt = ggml_get_type_traits((ggml_type) head_->type());+ if (tt == nullptr || tt->to_float == nullptr || N % 32 != 0) { err = "mtp: --mtp-q4 cannot read the head's format"; return false; }+ const size_t in_row = head_->row_bytes(), out_row = (size_t) (N / 32) * 18;+ std::vector<uint8_t> src((size_t) n_dvocab_ * in_row), dst((size_t) n_dvocab_ * out_row);+ try { dpct::get_in_order_queue().memcpy(src.data(), dhead_, src.size()).wait(); } // SYCL port: cudaMemcpy+ catch (sycl::exception const&) { err = "mtp: reading the draft head"; return false; }+ std::vector<float> row((size_t) N);+ for (int64_t r = 0; r < n_dvocab_; ++r) {+ tt->to_float(src.data() + (size_t) r * in_row, row.data(), N);+ ggml_quantize_chunk(GGML_TYPE_Q4_0, row.data(), dst.data() + (size_t) r * out_row, 0, 1, N, nullptr);+ }+ // the Q4_0 rows replace the subset in place (they are smaller)+ try { dpct::get_in_order_queue().memcpy(dhead_, dst.data(), dst.size()).wait(); }+ catch (sycl::exception const&) { err = "mtp: writing the draft head"; return false; }+ dhead_type_ = GGML_Q4_0;+ std::fprintf(stderr, "strata mtp: --mtp-q4: draft head over %lld tokens as Q4_0 (%.1f MiB read per step, was %.1f)\n",+ (long long) n_dvocab_, (double) dst.size() / 1048576.0, (double) src.size() / 1048576.0);+ return true;+#else+ err = "mtp: --mtp-q4 needs a build with native experts (ggml)";+ return false;+#endif+}bool MtpDrafter::load(const std::string &rt_dir, const ModelGeometry &g,SessionState &ss, int max_t, std::string &err,- int64_t window) try {+ int64_t window, const MtpDrafter *shared) try {device_ =dpct::get_current_device_id(); // a layer split's last stage on another// GPU: the drafter lives thereg_ = &g;ss_ = &ss;+ if (ple_ss_ == nullptr) ple_ss_ = &ss;max_t_ = max_t;rt_dir_ = rt_dir;if (max_t < 1 || max_t > strata::kernels::kVerifyMaxT) { err = "mtp: max_t out of range"; return false; }+ if (shared != nullptr) {+ if (shared->device_ != device_ || shared->g_ != &g || shared->dense_ == nullptr ||+ shared->experts_ == nullptr || shared->rt_dir_ != rt_dir) {+ err = "mtp: incompatible shared weights";+ return false;+ }+ dense_ = shared->dense_;+ experts_ = shared->experts_;+ tensors_ = shared->tensors_;+ owns_weights_ = false;+ owns_draft_head_ = false;+ }// Loader fix (0.1.15+loaderfix.2): the two reads below are the whole “drafter files” cost; reporting// them apart from the rest of the stage is what makes the next regression visible.const auto t_files = std::chrono::steady_clock::now();// ---- the index and the dense weights- {+ if (shared == nullptr) {std::ifstream idx(rt_dir + "/dense.txt");if (!idx) { err = "mtp: cannot open " + rt_dir + "/dense.txt (run tools/mtp_rt.py)"; return false; }std::string line;@@ -194,9 +314,9 @@ bool MtpDrafter::load(const std::string &rt_dir, const ModelGeometry &g,if (alloc != 0) {size_t free_bytes = 0, total_bytes = 0;/*- DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions- for device information which may not be supported by all compilers- or runtimes. You may need to adjust the code.+ DPCT1106: 'cudaMemGetInfo' was migrated with the Intel+ extensions for device information which may not be supported by all+ compilers or runtimes. You may need to adjust the code.*/const dpct::err0 info =DPCT_CHECK_ERROR(dpct::get_current_device().get_memory_info(@@ -217,17 +337,12 @@ bool MtpDrafter::load(const std::string &rt_dir, const ModelGeometry &g,: "unknown");return false;}- /*- DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming- in the original code the source host memory is pageable memory. If the- memory is not pageable, call wait() on event return by memcpy API to- ensure synchronization behavior.- */dpct::get_in_order_queue().memcpy(dense_, blob.data(), blob.size()).wait();vram_ += blob.size();+ if (q4_ && !make_q4_dense(blob, err)) return false;}// ---- the 512 routed experts, one blob each- {+ if (shared == nullptr) {const uint64_t bytes = (uint64_t) g.n_expert * strata::kernels::cpu::BLOB;// Loader fix (0.1.15+loaderfix.2): each 64 MiB read below reached the disk as ~16k 4095-byte reads under// MSVC's `basic_filebuf::xsgetn`, which is what made 675 MiB of drafter experts take minutes.@@ -241,6 +356,9 @@ bool MtpDrafter::load(const std::string &rt_dir, const ModelGeometry &g,bytes, dpct::get_in_order_queue())) != 0) {err = "mtp: the 512 experts do not fit in VRAM"; return false;}+#if !defined(_WIN32)+ strata::platform::advise_willneed(fileno(f), 0, bytes);+#endifstd::vector<uint8_t> chunk(64u << 20);for (uint64_t off = 0; off < bytes;) {const uint64_t n = std::min<uint64_t>(chunk.size(), bytes - off);@@ -310,8 +428,10 @@ bool MtpDrafter::load(const std::string &rt_dir, const ModelGeometry &g,mapped(R2 * NH * 4 + 64, (void**) &h_pos_, (void**) &m_pos_) &&mapped(64, (void**) &h_row_, (void**) &m_row_) &&mapped(T * 4 + 64, (void**) &h_out_, (void**) &m_out_) &&- mapped(T * 4 + 64, (void**) &h_prob_, (void**) &m_prob_);+ mapped(T * 4 + 64, (void**) &h_prob_, (void**) &m_prob_) &&+ (!force_on_ || mapped(64, (void**) &h_force_, (void**) &m_force_));if (!ok) { err = "mtp: mapped staging failed"; return false; }+ if (h_force_ != nullptr) for (int j = 0; j < 16; ++j) h_force_[j] = -1;auto carve = [&](Bump& b) {tok_ = b.take<int32_t>(T); step_ = b.take<int32_t>(R2 * 4); pos_ = b.take<int32_t>(R2 * NH); row_ = b.take<int32_t>(4);ident_ = b.take<int32_t>(T * (uint64_t) cap_);@@ -338,6 +458,8 @@ bool MtpDrafter::load(const std::string &rt_dir, const ModelGeometry &g,x_bf16_ = b.take<uint16_t>(N);out_ids_ = b.take<int32_t>(T + 4);probs_ = b.take<float>(T + 4);+ arg_scratch_ = b.take<uint8_t>(strata::kernels::argmax_rows_scratch_bytes((int) T));+ top_scratch_ = b.take<uint8_t>(strata::kernels::row_top_prob_scratch_bytes((int) T));dummy_inj_ = b.take<float>(HC);};Bump count;@@ -356,27 +478,65 @@ bool MtpDrafter::load(const std::string &rt_dir, const ModelGeometry &g,for (uint64_t t = 0; t < T; ++t)for (int64_t i = 0; i < cap_; ++i) id[(size_t) (t * (uint64_t) cap_ + (uint64_t) i)] = (int32_t) i;/*- DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming- in the original code the source host memory is pageable memory. If the- memory is not pageable, call wait() on event return by memcpy API to- ensure synchronization behavior.+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable memory.+ If the memory is not pageable, call wait() on event return by memcpy API+ to ensure synchronization behavior.*/dpct::get_in_order_queue().memcpy(ident_, id.data(), id.size() * 4).wait();}+ // --pipeline-windows 2 (the forcing graphs): the chain shares its card with stage 1's windows and the next launch+ // on stage 0 waits for it, so its stream gets the highest priority there (STRATA_MTP_PRIORITY=0: the default)+ bool prio = false;+#if !defined(STRATA_USE_HIP) // (HIP: the default priority)+ static const bool hi_prio = [] { const char* v = std::getenv("STRATA_MTP_PRIORITY"); return v == nullptr || std::atoi(v) != 0; }();+ int prio_lo = 0, prio_hi = 0;+ /*+ DPCT1027: The call to cudaDeviceGetStreamPriorityRange was replaced with+ 0 because SYCL currently does not support get queue priority range.+ */+ if (force_on_ && hi_prio && 0 == 0)+ /*+ DPCT1025: The SYCL queue is created ignoring the flag and priority+ options.+ */+ prio = DPCT_CHECK_ERROR(+ cs_ = dpct::get_current_device().create_queue(true)) == 0;+ /*+ DPCT1026: The call to cudaGetLastError was removed because this+ functionality is redundant in SYCL.+ */+#endif+ /*+ DPCT1025: The SYCL queue is created ignoring the flag and priority+ options.+ */+ if (!prio && DPCT_CHECK_ERROR(cs_ = dpct::get_current_device().create_queue(+ true)) != 0) {+ err = "mtp: stream"; return false;+ }/*DPCT1025: The SYCL queue is created ignoring the flag and priorityoptions.*/- if (DPCT_CHECK_ERROR(cs_ = dpct::get_current_device().create_queue(true)) !=- 0) {- err = "mtp: stream"; return false;+ if (DPCT_CHECK_ERROR(+ side_ = dpct::get_current_device().create_queue(true)) != 0 ||+ DPCT_CHECK_ERROR(sh_fork_ = new sycl::event()) != 0 ||+ DPCT_CHECK_ERROR(sh_join_ = new sycl::event()) != 0) {+ err = "mtp: streams";+ return false;}const double files_s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t_files).count();- std::fprintf(stderr, "strata mtp: draft layer loaded, %.0f MiB of VRAM (experts %.0f, dense %.0f), files read in %.2f s (%.0f MiB/s)\n",- (double) vram_ / 1048576.0, (double) g.n_expert * strata::kernels::cpu::BLOB / 1048576.0,- (double) tensors_.back().off / 1048576.0, files_s,- files_s > 0 ? ((double) g.n_expert * strata::kernels::cpu::BLOB + (double) tensors_.back().off) /- 1048576.0 / files_s : 0.0);+ if (shared != nullptr) {+ std::fprintf(stderr, "strata mtp: shared draft weights, %.0f MiB of private state and buffers\n",+ (double) vram_ / 1048576.0);+ } else {+ std::fprintf(stderr, "strata mtp: draft layer loaded, %.0f MiB of VRAM (experts %.0f, dense %.0f), files read in %.2f s (%.0f MiB/s)\n",+ (double) vram_ / 1048576.0, (double) g.n_expert * strata::kernels::cpu::BLOB / 1048576.0,+ (double) tensors_.back().off / 1048576.0, files_s,+ files_s > 0 ? ((double) g.n_expert * strata::kernels::cpu::BLOB + (double) tensors_.back().off) /+ 1048576.0 / files_s : 0.0);+ }return true;}catch (sycl::exception const &exc) {@@ -385,10 +545,52 @@ catch (sycl::exception const &exc) {std::exit(1);}+namespace {+// STRATA_MTP_FULL_HEAD=1 (a diagnostic): draft over the whole vocabulary (the main head itself) instead of+// rt/draft_vocab.bin's subset - the reference head, to measure what the subset costs in acceptance+bool full_head_env() {+ static const bool on = [] { const char* v = std::getenv("STRATA_MTP_FULL_HEAD"); return v && v[0] == '1'; }();+ return on;+}+} // namespace++bool MtpDrafter::top2_env() {+ static const bool on = [] { const char* v = std::getenv("STRATA_MTP_TOP2"); return v && v[0] == '1'; }();+ return on;+}++// STRATA_MTP_TOP2=1 (a diagnostic for tree drafts): draft j's runner-up under the draft layer, from the head logits+// the step just wrote (row 0), on the host. Slow; only for measuring what a second branch would have caught.+void MtpDrafter::record_top2(int j) try {+ const int64_t nv = dhead_ != nullptr ? n_dvocab_ : n_vocab_;+ if ((int64_t) lg_host_.size() < nv) lg_host_.resize((size_t) nv);+ if ((int) top2_.size() < max_t_) top2_.assign((size_t) max_t_, -1);+ if (j < 0 || j >= max_t_) return;+ if (DPCT_CHECK_ERROR(dpct::get_in_order_queue()+ .memcpy(lg_host_.data(), head_logits_,+ (size_t)nv * sizeof(float))+ .wait()) != 0) {+ top2_[(size_t) j] = -1;+ return;+ }+ int64_t b1 = -1, b2 = -1;+ for (int64_t i = 0; i < nv; ++i) {+ const float v = lg_host_[(size_t) i];+ if (b1 < 0 || v > lg_host_[(size_t) b1]) { b2 = b1; b1 = i; }+ else if (b2 < 0 || v > lg_host_[(size_t) b2]) b2 = i;+ }+ top2_[(size_t) j] = b2 < 0 ? -1 : dhead_ != nullptr ? dvocab_host_[(size_t) b2] : (int32_t) b2;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}+uint64_t MtpDrafter::bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const {uint64_t bytes = head_logits_ ? 0 : (uint64_t) max_t_ * (uint64_t) n_vocab * sizeof(float);- if (dhead_ == nullptr) {- if (FILE* f = std::fopen((rt_dir_ + "/draft_vocab.bin").c_str(), "rb")) {+ if (dhead_ == nullptr && owns_draft_head_ && !full_head_env()) {+ if (FILE* f = std::fopen(vocab_file().c_str(), "rb")) {std::fseek(f, 0, SEEK_END);const long size = std::ftell(f);std::fclose(f);@@ -437,7 +639,21 @@ bool MtpDrafter::setup_coupled(std::string& err) try {q.memcpy(dinv_, inv.data(), inv.size() * sizeof(int32_t)).wait();vram_ += inv.size() * sizeof(int32_t);}- dpct::get_current_device().queues_wait_and_throw();+ if (DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()) !=+ 0) {+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use+ error codes. Please replace the "get_error_string_dummy(...)" with a+ real error-handling function.+ */+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use the+ error codes. The cudaGetLastError function call was replaced with 0. You+ need to rewrite this code.+ */+ err = std::string("mtp: coupled setup: ") + dpct::get_error_string_dummy(0);+ return false;+ }coupled_ok_ = true;std::fprintf(stderr, "strata mtp: coupled draft sampling on (STRATA_SPEC_COUPLED): sampled requests draft with the ""target's chain and Philox draw over %lld tokens\n", (long long) nv);@@ -501,7 +717,8 @@ void draft_head_hint(int64_t n_tokens, int64_t row_bytes) {} // namespacebool MtpDrafter::bind(const WeightTable &wt, const NativeHead *head,- const float *window_R, std::string &err) try {+ const float *window_R, std::string &err,+ const MtpDrafter *shared) try {const OnDevice on_device(device_);wt_ = &wt;head_ = head;@@ -517,10 +734,21 @@ bool MtpDrafter::bind(const WeightTable &wt, const NativeHead *head,err = "mtp: the draft logits do not fit";return false;}+ if (shared != nullptr) {+ if (shared->head_ != head || shared->device_ != device_ ||+ shared->n_vocab_ != n_vocab_) {+ err = "mtp: incompatible shared draft head";+ return false;+ }+ dhead_ = shared->dhead_;+ dvocab_ = shared->dvocab_;+ n_dvocab_ = shared->n_dvocab_;+ owns_draft_head_ = false;+ }// the draft head's token subset, when tools/draft_vocab.py wrote one- if (dhead_ == nullptr) {+ if (dhead_ == nullptr && shared == nullptr && !full_head_env()) {std::vector<uint8_t> raw;- if (read_file(rt_dir_ + "/draft_vocab.bin", raw) && raw.size() >= 4 && raw.size() % 4 == 0) {+ if (read_file(vocab_file(), raw) && raw.size() >= 4 && raw.size() % 4 == 0) {n_dvocab_ = (int64_t) (raw.size() / 4);const int64_t row_bytes = (int64_t) head->row_bytes(); // a vocabulary row of the native headif (DPCT_CHECK_ERROR(dvocab_ = (int32_t *)sycl::malloc_device(@@ -533,14 +761,19 @@ bool MtpDrafter::bind(const WeightTable &wt, const NativeHead *head,draft_head_hint(n_dvocab_, row_bytes);return false;}- dpct::get_in_order_queue()- .memcpy(dvocab_, raw.data(), raw.size())- .wait();+ dpct::get_in_order_queue().memcpy(dvocab_, raw.data(), raw.size()).wait();+ dvocab_host_.resize((size_t) n_dvocab_);+ std::memcpy(dvocab_host_.data(), raw.data(), raw.size());strata::kernels::gather_rows((const uint8_t*) head->weights(), row_bytes, dvocab_, n_dvocab_, dhead_, nullptr);dpct::get_current_device().queues_wait_and_throw();vram_ += (uint64_t) (n_dvocab_ * row_bytes) + raw.size();std::fprintf(stderr, "strata mtp: draft head over %lld tokens (%.1f MiB)\n", (long long) n_dvocab_,(double) (n_dvocab_ * row_bytes) / 1048576.0);+ dhead_type_ = head->type();+ if (q4_head_ && !make_q4_head(err)) return false;+ if (dhead_type_ == 14 && strata::kernels::native_q6_k_packed_enabled()) // STRATA_Q6_PACKED=1+ strata::kernels::native_q6_k_pack(dhead_, (int) (row_bytes / 210) * 256, (int) n_dvocab_,+ "MTP draft head");}}if (coupled_draft_env() && cparams_ == nullptr && !setup_coupled(err)) return false;@@ -555,18 +788,27 @@ catch (sycl::exception const &exc) {// The layer for T rows. full = false stops after the K/V append (the prompt only needs the cache).bool MtpDrafter::record_forward(int T, int step_row0, dpct::queue_ptr cs,std::string &err) {- using namespace strata::kernels;- const ModelGeometry& g = *g_;- SessionState& ss = *ss_;// step_row0 >= 0: the full layer on step rows [step_row0, +T); step_row0 < 0: K/V only on rows [-1 - step_row0, +T)const bool full = step_row0 >= 0;- const int row0 = full ? step_row0 : -1 - step_row0;if (full && T != 1) { err = "mtp: the full layer runs one row at a time (its attention scratch is sized for one)"; return false; }- const int64_t N = g.n_embd, HC = g.hc, K = ss.k, NH = g.n_head, HD = g.head_dim, NKV = g.n_head_kv;+ if (!record_front(T, full ? step_row0 : -1 - step_row0, cs, err)) return false;+ return !full || record_rest(step_row0, cs, err);+}++bool MtpDrafter::record_front(int T, int row0, dpct::queue_ptr cs,+ std::string &err) {+ using namespace strata::kernels;+ const ModelGeometry& g = *g_;+ const int64_t N = g.n_embd, HC = g.hc, NH = g.n_head, HD = g.head_dim, NKV = g.n_head_kv;const QsaShapes s = shapes_of(g);- const GrShapes gs{g.n_embd, g.hc, g.hc_lr};const int32_t* step = step_ + row0 * 4;const int32_t* pos = pos_ + row0 * NH;+ // --mtp-q4: each projection's format and weights for this pass (Q8_0 unless the Q4_0 copies exist)+ int wt_fc_embedding, wt_fc_hidden, wt_k_proj, wt_v_proj;+ const void* wp_fc_embedding = wq("fc_embedding.weight", wt_fc_embedding);+ const void* wp_fc_hidden = wq("fc_hidden.weight", wt_fc_hidden);+ const void* wp_k_proj = wq("self_attn.k_proj.weight", wt_k_proj);+ const void* wp_v_proj = wq("self_attn.v_proj.weight", wt_v_proj);try {// ---- the two input branchesconst WeightRef* we = wt_->find("token_embd.weight");@@ -582,12 +824,15 @@ bool MtpDrafter::record_forward(int T, int step_row0, dpct::queue_ptr cs,}native_qsa_rms_norm_weighted(emb_, f32("pre_fc_norm_embedding.weight"), en_, (int) N, T, EPS, cs);native_quantize_q8_1(en_, xq_, (int) N, T, cs);- native_mmvq(GGML_Q8_0, q8("fc_embedding.weight"), xq_, e2_, (int) N, (int) N, T, cs);- native_qsa_rms_norm_weighted(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) (HC * N), T, EPS, cs);+ native_mmvq(wt_fc_embedding, wp_fc_embedding, xq_, e2_, (int) N, (int) N, T, cs);+ if (hnorm_stream_) // --mtp-hnorm stream: one RMS per stream, each scaled by its slice of the weight+ native_qsa_rms_norm_grouped(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) N, (int) HC, (int) (T * HC), EPS, cs);+ else+ native_qsa_rms_norm_weighted(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) (HC * N), T, EPS, cs);for (int c0 = 0; c0 < T * HC; c0 += 8) {const int nc = (int) std::min<int64_t>(8, T * HC - c0);native_quantize_q8_1(hn_ + (size_t) c0 * N, xq_, (int) N, nc, cs);- native_mmvq(GGML_Q8_0, q8("fc_hidden.weight"), xq_, h2_ + (size_t) c0 * N, (int) N, (int) N, nc, cs);+ native_mmvq(wt_fc_hidden, wp_fc_hidden, xq_, h2_ + (size_t) c0 * N, (int) N, (int) N, nc, cs);}add_streams_broadcast(h2_, e2_, R_, N, (int) HC, T, cs);// ---- the attention hyper-connection@@ -604,36 +849,93 @@ bool MtpDrafter::record_forward(int T, int step_row0, dpct::queue_ptr cs,}fused_gr_read_multi(fa, T, xn_, cs);}- // ---- attention: K/V into the layer's own cache, then (full) dense attention over every cell- auto norm_rope = [&](float* data, const float* gamma, int rows, int cols, const int32_t* p) {- native_qsa_rms_norm_weighted(data, gamma, data, cols, rows, EPS, cs);- if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), p, cs);- else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st_.cos_tab, st_.sin_tab, p, cs);- };+ // ---- attention: K/V into the layer's own cachenative_quantize_q8_1(mixed_, xq_, (int) N, T, cs);- native_mmvq(GGML_Q8_0, q8("self_attn.k_proj.weight"), xq_, kcur_, (int) N, (int) (NKV * HD), T, cs);- native_mmvq(GGML_Q8_0, q8("self_attn.v_proj.weight"), xq_, vcur_, (int) N, (int) (NKV * HD), T, cs);- for (int t = 0; t < T; ++t) {- norm_rope(kcur_ + t * NKV * HD, f32("self_attn.k_norm.weight"), (int) NKV, (int) HD, pos + t * NH);- if (st_.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1- fwht256_inplace_cuda(kcur_ + t * NKV * HD, NKV, cs);- fwht256_inplace_cuda(vcur_ + t * NKV * HD, NKV, cs);+ native_mmvq(wt_k_proj, wp_k_proj, xq_, kcur_, (int) N, (int) (NKV * HD), T, cs);+ native_mmvq(wt_v_proj, wp_v_proj, xq_, vcur_, (int) N, (int) (NKV * HD), T, cs);+ // #783 PR-d (stuchapin909): the T tokens' K norm, K/V rotation and K/V append each run once over all T rows+ // (every row is independent; the rope keeps its per-token positions). STRATA_NO_BATCH_KV_STEP=1 appends per token.+ static const bool no_batch_kv = [] {+ const char* v = std::getenv("STRATA_NO_BATCH_KV_STEP");+ return v != nullptr && v[0] != '\0' && v[0] != '0';+ }();+ // #783 PR-f (stuchapin909): the per-head RMSNorm and the rope fused (bit-identical to the pair, rope_parity+ // check 6; STRATA_NO_NORM_ROPE=1 keeps the two; off on HIP until its parity check passes). K rows of one token+ // are consecutive in `pos`, tokens are NH apart, so a one-token window is the fusable case.+ const bool fuse_nr = native_rope_enabled() && native_norm_rope_usable((int) HD, (int) s.n_rot);+ if (T == 1 && fuse_nr) {+ native_qsa_rms_norm_rope(kcur_, (int) HD, f32("self_attn.k_norm.weight"), kcur_, (int) NKV, (int) HD,+ (int) s.n_rot, EPS, rope_scaling(), pos, cs);+ } else {+ native_qsa_rms_norm_weighted(kcur_, f32("self_attn.k_norm.weight"), kcur_, (int) HD, (int) (T * NKV), EPS, cs);+ for (int t = 0; t < T; ++t) {+ float* kc = kcur_ + t * NKV * HD;+ if (native_rope_enabled()) native_rope_apply(kc, kc, (int) NKV, (int) HD, (int) s.n_rot, rope_scaling(), pos + t * NH, cs);+ else rope_neox_apply(kc, kc, (int) NKV, (int) HD, (int) s.n_rot, st_.cos_tab, st_.sin_tab, pos + t * NH, cs);}- // stored in the state's own format (#293 appended rotated INT8 K/V as Q4_0, into pools INT8 never has)- if (st_.kv_q4)- kv_append_q4_step(st_.k_q4, st_.v_q4, st_.page_table, step + t * 4, kcur_ + t * NKV * HD,- vcur_ + t * NKV * HD, s, cs, &st_.host);- else if (st_.kv_int8)- kv_append_q8_step(st_.k_q, st_.v_q, st_.k_scale, st_.v_scale, st_.page_table, step + t * 4,- kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st_.host);- else- kv_append_step(st_.k_pool, st_.v_pool, st_.page_table, step + t * 4, kcur_ + t * NKV * HD,- vcur_ + t * NKV * HD, s, cs, &st_.host);}- if (!full) return true;- native_mmvq(GGML_Q8_0, q8("self_attn.q_proj.weight"), xq_, qfull_, (int) N, (int) (NH * 2 * HD), T, cs);- for (int t = 0; t < T; ++t) {- float* qc = qcur_ + t * NH * HD;+ if (st_.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1+ fwht256_inplace_cuda(kcur_, (int64_t) T * NKV, cs);+ fwht256_inplace_cuda(vcur_, (int64_t) T * NKV, cs);+ }+ // stored in the state's own format (#293 appended rotated INT8 K/V as Q4_0, into pools INT8 never has)+ if (!no_batch_kv && st_.kv_q4)+ kv_append_q4_steps(st_.k_q4, st_.v_q4, st_.page_table, step, 4, T, kcur_, vcur_, s, cs, &st_.host);+ else if (!no_batch_kv && st_.kv_int8)+ kv_append_q8_steps(st_.k_q, st_.v_q, st_.k_scale, st_.v_scale, st_.page_table, step, 4, kcur_, vcur_,+ (int) (NKV * HD), T, s, cs, &st_.host);+ else+ for (int t = 0; t < T; ++t) {+ if (st_.kv_q4)+ kv_append_q4_step(st_.k_q4, st_.v_q4, st_.page_table, step + t * 4, kcur_ + t * NKV * HD,+ vcur_ + t * NKV * HD, s, cs, &st_.host);+ else if (st_.kv_int8)+ kv_append_q8_step(st_.k_q, st_.v_q, st_.k_scale, st_.v_scale, st_.page_table, step + t * 4,+ kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st_.host);+ else+ kv_append_step(st_.k_pool, st_.v_pool, st_.page_table, step + t * 4, kcur_ + t * NKV * HD,+ vcur_ + t * NKV * HD, s, cs, &st_.host);+ }+ } catch (const std::exception& e) {+ err = std::string("mtp: ") + e.what();+ return false;+ }+ return true;+}++void MtpDrafter::norm_rope(float *data, const float *gamma, int rows, int cols,+ const int32_t *p, dpct::queue_ptr cs) {+ using namespace strata::kernels;+ const QsaShapes s = shapes_of(*g_);+ native_qsa_rms_norm_weighted(data, gamma, data, cols, rows, EPS, cs);+ if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), p, cs);+ else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st_.cos_tab, st_.sin_tab, p, cs);+}++bool MtpDrafter::record_rest(int step_row, dpct::queue_ptr cs,+ std::string &err) {+ using namespace strata::kernels;+ const ModelGeometry& g = *g_;+ SessionState& ss = *ss_;+ const int T = 1;+ const int64_t N = g.n_embd, HC = g.hc, K = ss.k, NH = g.n_head, HD = g.head_dim;+ const QsaShapes s = shapes_of(g);+ const GrShapes gs{g.n_embd, g.hc, g.hc_lr};+ const int32_t* step = step_ + step_row * 4;+ const int32_t* pos = pos_ + step_row * NH;+ // --mtp-q4: the q and o projections' format and weights (Q8_0 unless the Q4_0 copies exist)+ int wt_q_proj, wt_o_proj;+ const void* wp_q_proj = wq("self_attn.q_proj.weight", wt_q_proj);+ const void* wp_o_proj = wq("self_attn.o_proj.weight", wt_o_proj);+ const bool fuse_nr = native_rope_enabled() && native_norm_rope_usable((int) HD, (int) s.n_rot); // #783 PR-f+ try {+ // ---- dense attention over every cell+ native_mmvq(wt_q_proj, wp_q_proj, xq_, qfull_, (int) N, (int) (NH * 2 * HD), T, cs);+ // all T tokens' q rows at once (the rows of token t sit at pos[t * NH ..], so row r reads pos[r])+ if (fuse_nr) {+ native_qsa_rms_norm_rope(qfull_, (int) (2 * HD), f32("self_attn.q_norm.weight"), qcur_, (int) (T * NH),+ (int) HD, (int) s.n_rot, EPS, rope_scaling(), pos, cs);+ } else {/*DPCT1124: cudaMemcpy2DAsync is migrated to asynchronous memcpyAPI. While the origin API might be synchronous, it depends on the@@ -641,23 +943,22 @@ bool MtpDrafter::record_forward(int T, int step_row0, dpct::queue_ptr cs,return by memcpy API to ensure synchronization behavior.*/if (DPCT_CHECK_ERROR(dpct::async_dpct_memcpy(- qc, (size_t)HD * 4, qfull_ + t * NH * 2 * HD,- (size_t)HD * 2 * 4, (size_t)HD * 4, (size_t)NH,- dpct::device_to_device, *cs)) != 0) {+ qcur_, (size_t)HD * 4, qfull_, (size_t)HD * 2 * 4,+ (size_t)HD * 4, (size_t)(T * NH), dpct::device_to_device,+ *cs)) != 0) {err = "mtp: q split failed";return false;}- norm_rope(qc, f32("self_attn.q_norm.weight"), (int) NH, (int) HD, pos + t * NH);- if (st_.kv_rot) fwht256_inplace_cuda(qc, NH, cs);+ norm_rope(qcur_, f32("self_attn.q_norm.weight"), (int) (T * NH), (int) HD, pos, cs);}+ if (st_.kv_rot) fwht256_inplace_cuda(qcur_, (int64_t) T * NH, cs);const QsaAttnPools pools = qsa_attn_pools(st_);if (window_ > 0) window_ids(const_cast<int32_t*>(step), T, (int) window_, ident_, cap_, cs);qsa_decode_attn_batch(qcur_, pools, ident_, step, cap_, s, attn_scratch_, attn_, T, cs);if (st_.kv_rot) fwht256_inplace_cuda(attn_, (int64_t) T * NH, cs);- for (int t = 0; t < T; ++t)- native_qsa_gate_apply(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, attn32_ + t * NH * HD, (int) NH, (int) HD, cs);+ native_qsa_gate_apply(attn_, qfull_, attn32_, (int) (T * NH), (int) HD, cs);native_quantize_q8_1(attn32_, xq_, (int) (NH * HD), T, cs);- native_mmvq(GGML_Q8_0, q8("self_attn.o_proj.weight"), xq_, bo_, (int) (NH * HD), (int) N, T, cs);+ native_mmvq(wt_o_proj, wp_o_proj, xq_, bo_, (int) (NH * HD), (int) N, T, cs);// ---- the MLP hyper-connection (the attention write folded in){FusedGrArgs fa[kFusedGrMaxT];@@ -673,44 +974,155 @@ bool MtpDrafter::record_forward(int T, int step_row0, dpct::queue_ptr cs,}fused_gr_read_multi(fa, T, xn_, cs);}- // ---- MoE: router, the 512 resident experts, the shared expert, the combine, the write+ // ---- MoE: router, the 512 resident experts, the shared expert (on a branch beside them on CUDA), the+ // combine, the write+ NativeSharedWeights nsw;+ nsw.gate_data = wq("mlp.shared_expert.gate_proj.weight", nsw.gate_type);+ nsw.up_data = wq("mlp.shared_expert.up_proj.weight", nsw.up_type);+ nsw.down_data = wq("mlp.shared_expert.down_proj.weight", nsw.down_type);+ nsw.q8_1 = xq_; // the routed experts read hit_xq_+ const SForm none{};+ const bool need_bf16_x = !shared_expert_native_bf16_enabled();+ static const bool fuse_head_gr = [] {+ const char* v = std::getenv("STRATA_FUSE_HEAD_GR");+ return v != nullptr && std::atoi(v) != 0;+ }();+ static const bool head_mix_multi_on = [] {+#if defined(STRATA_USE_HIP)+ return false;+#else+ const char* v = std::getenv("STRATA_HEAD_MIX_MULTI");+ return v == nullptr || std::atoi(v) != 0;+#endif+ }();+ // the shared expert only reads mixed_ / xq_ and writes shared_: a branch beside the router and the routed+ // experts, joined before the combine (CUDA; HIP keeps one stream: STRATA_MTP_SHARED_BRANCH=0 does too)+ static const bool branch_on = [] {+#if defined(STRATA_USE_HIP)+ return false;+#else+ const char* v = std::getenv("STRATA_MTP_SHARED_BRANCH");+ return v == nullptr || std::atoi(v) != 0;+#endif+ }();+ dpct::queue_ptr sh_cs = cs;+ if (branch_on) {+ /*+ DPCT1024: The original code returned the error code that was+ further consumed by the program logic. This original code was+ replaced with 0. You may need to rewrite the program logic consuming+ the error code.+ */+ if (DPCT_CHECK_ERROR(dpct::sync_barrier(sh_fork_, cs)) != 0 ||+ DPCT_CHECK_ERROR(+ (side_)->ext_oneapi_submit_barrier({*sh_fork_})) != 0) {+ err = "mtp: the shared expert's branch";+ return false;+ }+ sh_cs = side_;+ }+ auto shared_rows = [&]() {+ for (int t = 0; t < T; ++t) {+ if (need_bf16_x) f32_to_bf16_bulk(mixed_ + t * N, x_bf16_, N, sh_cs);+ shared_expert(nullptr, nullptr, x_bf16_, none, nullptr, nullptr, nullptr, none, nullptr, nullptr, nullptr,+ none, nullptr, nullptr, nullptr, bf16("mlp.shared_expert_gate.weight"), sh_scratch_,+ shared_ + t * N, N, g.n_ff, 32, sh_cs, mixed_ + t * N, &nsw);+ }+ };+ if (branch_on) {+ shared_rows();+ /*+ DPCT1024: The original code returned the error code that was+ further consumed by the program logic. This original code was+ replaced with 0. You may need to rewrite the program logic consuming+ the error code.+ */+ if (DPCT_CHECK_ERROR(dpct::sync_barrier(sh_join_, side_)) != 0) {+ err = "mtp: the shared expert's branch"; return false;+ }+ }+ // #783 PR-c (stuchapin909): a multi-token window routes in two launches (one router GEMV reading the weight once,+ // one top-10 over all rows - each row bitwise the single-token call) and combines in one+ if (T > 1 && native_router_enabled() && g.n_expert == 512 && K == 10) {+ bf16_gemv_fp32_mmvf_multi(mixed_, N, bf16("mlp.gate.weight"), logits_, g.n_expert, (int) N, (int) g.n_expert, T, cs);+ native_router_top10_multi(logits_, ids_, w_, T, cs);+ } else {for (int t = 0; t < T; ++t) {bf16_gemv_fp32_mmvf(mixed_ + t * N, bf16("mlp.gate.weight"), logits_ + t * g.n_expert, (int) N, (int) g.n_expert, cs);if (native_router_enabled()) native_router_top10(logits_ + t * g.n_expert, ids_ + t * K, w_ + t * K, cs);else router_top10(logits_ + t * g.n_expert, 1, (int) g.n_expert, (int) K, ids_ + t * K, w_ + t * K, cs);}+ }moe_group_resident(ids_, (int) (T * K), (int) K, experts_, (int64_t) strata::kernels::cpu::BLOB, grp_ptr_,grp_start_, grp_counts_, hit_dst_, hit_slot_, cs);quantize_q8_0_scaled(mixed_, hit_xq_, hit_xs_, (int64_t) T * N, cs);moe_grouped_s2(grp_ptr_, grp_start_, grp_counts_, hit_dst_, hit_slot_, (int64_t) T * K, (int64_t) T * K, hit_xq_,hit_xs_, hit_scratch_, parts_, cs);- NativeSharedWeights nsw;- nsw.gate_type = GGML_Q8_0; nsw.gate_data = q8("mlp.shared_expert.gate_proj.weight");- nsw.up_type = GGML_Q8_0; nsw.up_data = q8("mlp.shared_expert.up_proj.weight");- nsw.down_type = GGML_Q8_0; nsw.down_data = q8("mlp.shared_expert.down_proj.weight");- nsw.q8_1 = xq_;- const SForm none{};+ if (branch_on) {+ if (DPCT_CHECK_ERROR(cs->ext_oneapi_submit_barrier({*sh_join_})) !=+ 0) {+ err = "mtp: the shared expert's join"; return false;+ }+ } else {+ shared_rows();+ }+ static const bool no_multi_gr = [] { // #783 PR-g: STRATA_NO_MULTI_GR=1 keeps the per-token GR calls+ const char* v = std::getenv("STRATA_NO_MULTI_GR");+ return v != nullptr && v[0] != '\0' && v[0] != '0';+ }();for (int t = 0; t < T; ++t) {- f32_to_bf16_bulk(mixed_ + t * N, x_bf16_, N, cs);- shared_expert(nullptr, nullptr, x_bf16_, none, nullptr, nullptr, nullptr, none, nullptr, nullptr, nullptr, none,- nullptr, nullptr, nullptr, bf16("mlp.shared_expert_gate.weight"), sh_scratch_, shared_ + t * N,- N, g.n_ff, 32, cs, mixed_ + t * N, &nsw);- if (native_moe_combine_enabled())- native_moe_combine(parts_ + (size_t) t * K * N, w_ + t * K, shared_ + t * N, y_ + t * N, N, K, cs);- else- moe_combine(parts_ + (size_t) t * K * N, w_ + t * K, shared_ + t * N, y_ + t * N, N, K, cs);- gr_write(R_ + (size_t) t * HC * N, y_ + t * N, inj2_ + t * HC, gs, R_ + (size_t) t * HC * N, cs);+ if (!(T > 1 && native_moe_combine_enabled())) {+ if (native_moe_combine_enabled())+ native_moe_combine(parts_ + (size_t) t * K * N, w_ + t * K, shared_ + t * N, y_ + t * N, N, K, cs);+ else+ moe_combine(parts_ + (size_t) t * K * N, w_ + t * K, shared_ + t * N, y_ + t * N, N, K, cs);+ }+ if (!fuse_head_gr && no_multi_gr)+ gr_write(R_ + (size_t) t * HC * N, y_ + t * N, inj2_ + t * HC, gs, R_ + (size_t) t * HC * N, cs);}+ if (T > 1 && native_moe_combine_enabled())+ native_moe_combine_multi(parts_, w_, shared_, y_, N, K, T, cs);+ // #783 PR-g (stuchapin909): the T residual writes in one launch (each token's R, block output and injection are+ // its own, so doing them after the loop changes nothing)+ if (!fuse_head_gr && !no_multi_gr)+ gr_write_multi(R_, y_, inj2_, gs, R_, T, cs);// ---- the final mixer and the main model's head- for (int t = 0; t < T; ++t)- gr_read(R_ + (size_t) t * HC * N, f32("hyper_connection_mixer.hc_norm.weight"),- bf16("hyper_connection_mixer.input_mix_weight_down.weight"),- bf16("hyper_connection_mixer.input_mix_weight_up.weight"), nullptr, EPS, gs, ss.block.gr,- sample_ + t * N, dummy_inj_, cs);+ if (fuse_head_gr) {+ FusedGrArgs fa[kFusedGrMaxT];+ for (int t = 0; t < T; ++t) {+ fa[t].R = R_ + (size_t) t * HC * N; fa[t].R_out = R_ + (size_t) t * HC * N; fa[t].apply = true;+ fa[t].bo_prev = y_ + t * N; fa[t].inj_prev = inj2_ + t * HC;+ fa[t].w_norm = f32("hyper_connection_mixer.hc_norm.weight");+ fa[t].w_down = bf16("hyper_connection_mixer.input_mix_weight_down.weight");+ fa[t].w_up = bf16("hyper_connection_mixer.input_mix_weight_up.weight");+ fa[t].w_inject = nullptr;+ fa[t].eps = EPS; fa[t].lo = lo_ + t * g.hc_lr; fa[t].rs = rs_ + t * HC;+ fa[t].inject_out = dummy_inj_; fa[t].mixed = sample_ + t * N;+ }+ fused_gr_read_multi(fa, T, xn_, cs);+ } else if (head_mix_multi_on) {+ // the window's rows in one read (CUDA; HIP keeps gr_read per row): bitwise the same sums+ FusedGrArgs fa[kFusedGrMaxT];+ for (int t = 0; t < T; ++t) {+ fa[t].R = R_ + (size_t) t * HC * N; fa[t].R_out = R_ + (size_t) t * HC * N; fa[t].apply = false;+ fa[t].w_norm = f32("hyper_connection_mixer.hc_norm.weight");+ fa[t].w_down = bf16("hyper_connection_mixer.input_mix_weight_down.weight");+ fa[t].w_up = bf16("hyper_connection_mixer.input_mix_weight_up.weight");+ fa[t].eps = EPS; fa[t].lo = lo_ + t * g.hc_lr; fa[t].rs = rs_ + t * HC; fa[t].mixed = sample_ + t * N;+ }+ fused_gr_read_multi(fa, T, xn_, cs);+ } else {+ for (int t = 0; t < T; ++t)+ gr_read(R_ + (size_t) t * HC * N, f32("hyper_connection_mixer.hc_norm.weight"),+ bf16("hyper_connection_mixer.input_mix_weight_down.weight"),+ bf16("hyper_connection_mixer.input_mix_weight_up.weight"), nullptr, EPS, gs, ss.block.gr,+ sample_ + t * N, dummy_inj_, cs);+ }native_quantize_q8_1(sample_, xq_, (int) N, T, cs);const bool sub = dhead_ != nullptr;const int64_t nv = sub ? n_dvocab_ : n_vocab_;- native_mmvq(head_->type(), sub ? dhead_ : head_->weights(), xq_, head_logits_, (int) N, (int) nv, T, cs);+ native_mmvq(sub ? dhead_type_ : head_->type(), sub ? dhead_ : head_->weights(), xq_, head_logits_, (int) N,+ (int) nv, T, cs);if (coupled_rec_) {// coupled draft sampling: the target's chain and Philox draw for the row that will verify this draft// (counter = this cell + 1, from its step record), penalties over the ring; T == 1 (full layer)@@ -718,11 +1130,16 @@ bool MtpDrafter::record_forward(int T, int step_row0, dpct::queue_ptr cs,cparams_, cring_, kCoupledHistCap, coupled_j_, step, cscratch_, out_ids_, probs_, cs);return true;}- SamplerParams sp;- sp.greedy = true;- sp.temperature = 0.0f;- sample_tokens(head_logits_, T, (int) nv, nullptr, 0, sp, out_ids_, cs);- row_top_prob(head_logits_, T, (int) nv, out_ids_, probs_, cs);+ if (argmax_rows_wanted()) {+ argmax_rows(head_logits_, T, (int) nv, arg_scratch_, out_ids_, cs);+ } else {+ SamplerParams sp;+ sp.greedy = true;+ sp.temperature = 0.0f;+ sample_tokens(head_logits_, T, (int) nv, nullptr, 0, sp, out_ids_, cs);+ }+ if (multi_block_head_ops()) row_top_prob_split(head_logits_, T, (int) nv, out_ids_, probs_, top_scratch_, cs);+ else row_top_prob(head_logits_, T, (int) nv, out_ids_, probs_, cs);if (sub) map_ids(out_ids_, dvocab_, T, cs);} catch (const std::exception& e) {err = std::string("mtp: ") + e.what();@@ -749,9 +1166,9 @@ bool finish_capture(dpct::queue_ptr cs, bool ok,graph->finalize())) != 0) {if (graph) delete (graph);/*- DPCT1009: SYCL reports errors using exceptions and does not use error- codes. Please replace the "get_error_string_dummy(...)" with a real- error-handling function.+ DPCT1009: SYCL reports errors using exceptions and does not use+ error codes. Please replace the "get_error_string_dummy(...)" with a+ real error-handling function.*/err = std::string("mtp: ") + what +" capture: " + dpct::get_error_string_dummy(ce);@@ -816,26 +1233,38 @@ bool MtpDrafter::capture_round(int T, bool coupled, std::string &err) try {bool ok = true;// coupled: the request's chain and the penalty history's base, for this round's draftsif (coupled) coupled_draft_stage(m_cparams_, m_chist_, cparams_, cring_, kCoupledHistCap, cs_);+ // the catch-up: the layer's front for the window's T cells (their K/V), then its rest for row a only, on row+ // a's intermediates copied to row 0, at the cell the host staged in step row 2*max_t - 1; the draft chain is+ // one graph per step (`capture_step`) so the host can stop it when a draft is unlikely+ const int ra = 2 * max_t_ - 1;+ const int64_t N = g_->n_embd, NH = g_->n_head;+#if defined(STRATA_USE_HIP) // AMD keeps its separate copiescopy_i32_from_mapped(tok_, m_tok_, T, cs_);copy_i32_from_mapped(step_, m_step_, (int64_t) 2 * T * 4, cs_);- copy_i32_from_mapped(pos_, m_pos_, (int64_t) 2 * T * g_->n_head, cs_);+ copy_i32_from_mapped(pos_, m_pos_, (int64_t) 2 * T * NH, cs_);copy_i32_from_mapped(row_, m_row_, 2, cs_);copy_from_mapped(Rin_, window_R_, (int64_t) T * HCN, cs_);- // the catch-up: K/V for the window's T cells, then the full layer for row a only (its cell's K/V is written- // again, identically), staged by the host in step row 2*max_t - 1; the draft chain is one graph per step- // (`capture_step`) so the host can stop it when a draft is unlikely- const int ra = 2 * max_t_ - 1;- ok = record_forward(T, -1, cs_, err);- if (ok) mtp_select(Rin_, HCN, tok_, row_, Rin_, tok_, nullptr, 0, cs_);+ copy_i32_from_mapped(step_ + ra * 4, m_step_ + ra * 4, 4, cs_);+ copy_i32_from_mapped(pos_ + ra * NH, m_pos_ + ra * NH, NH, cs_);+#else // the draft round's seven inputs in one launch+ const MappedCopy in[7] = {{tok_, m_tok_, T}, {step_, m_step_, (int64_t) 2 * T * 4}, {pos_, m_pos_, 2 * T * NH},+ {row_, m_row_, 2}, {Rin_, window_R_, T * HCN}, {step_ + ra * 4, m_step_ + ra * 4, 4},+ {pos_ + ra * NH, m_pos_ + ra * NH, NH}};+ copy_from_mapped_multi(in, 7, cs_);+#endif+ ok = record_front(T, 0, cs_, err);if (ok) {- copy_i32_from_mapped(step_ + ra * 4, m_step_ + ra * 4, 4, cs_);- copy_i32_from_mapped(pos_ + ra * g_->n_head, m_pos_ + ra * g_->n_head, g_->n_head, cs_);+ if (T > 1) {+ copy_row_to_first(row_, R_, HCN, inj_, g_->hc, mixed_, N, cs_);+ native_quantize_q8_1(mixed_, xq_, (int) N, 1, cs_);+ }coupled_rec_ = coupled;coupled_j_ = 0;- ok = record_forward(1, ra, cs_, err);+ ok = record_rest(ra, cs_, err);coupled_rec_ = false;}if (ok) mtp_select(R_, HCN, out_ids_, row_ + 1, Rin_, tok_, m_out_, 0, cs_, probs_, m_prob_);+ if (ok && force_on_ && !coupled) force_token(tok_, m_force_, 0, cs_); // chain_launch: step 1's inputreturn finish_capture(cs_, ok, exec, coupled ? "round (coupled)" : "round", err);}catch (sycl::exception const &exc) {@@ -855,13 +1284,20 @@ bool MtpDrafter::capture_step(int j, bool coupled, std::string &err) try {if (DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs_)) != 0) {err = "mtp: begin capture"; return false;}+#if defined(STRATA_USE_HIP)copy_i32_from_mapped(step_ + row * 4, m_step_ + row * 4, 4, cs_);copy_i32_from_mapped(pos_ + row * g_->n_head, m_pos_ + row * g_->n_head, g_->n_head, cs_);+#else+ const MappedCopy in[2] = {{step_ + row * 4, m_step_ + row * 4, 4},+ {pos_ + row * g_->n_head, m_pos_ + row * g_->n_head, g_->n_head}};+ copy_from_mapped_multi(in, 2, cs_);+#endifcoupled_rec_ = coupled;coupled_j_ = j;bool ok = record_forward(1, row, cs_, err);coupled_rec_ = false;if (ok) mtp_select(R_, HCN, out_ids_, row_ + 1, Rin_, tok_, m_out_, j, cs_, probs_, m_prob_);+ if (ok && force_on_ && !coupled) force_token(tok_, m_force_, j, cs_); // chain_launch: step j+1's inputreturn finish_capture(cs_, ok, exec, coupled ? "step (coupled)" : "step", err);}catch (sycl::exception const &exc) {@@ -880,8 +1316,33 @@ void MtpDrafter::kv_restore(int64_t upto) {cs_->wait();}-bool MtpDrafter::prefill(const float *R_rows, const int32_t *next_tokens,- int64_t n, int64_t cell0, std::string &err) try {+bool MtpDrafter::prepare_prefill(std::string &err) try {+ const OnDevice on_device(device_);+ const int64_t per_row = 1 + 4 + g_->n_head;+ if (pf_cap_ < (int64_t) max_t_ * per_row) {+ if (pf_dev_) sycl::free(pf_dev_, dpct::get_in_order_queue());+ pf_dev_ = nullptr;+ pf_cap_ = 0;+ if (DPCT_CHECK_ERROR(pf_dev_ = sycl::malloc_device<int32_t>(+ (size_t)(max_t_ * per_row),+ dpct::get_in_order_queue())) != 0) {+ err = "mtp prefill: the input records do not fit";+ return false;+ }+ pf_cap_ = max_t_ * per_row;+ }+ for (int T = 1; T <= max_t_; ++T)+ if (!capture_prefill_dev(T, err)) return false; // (STRATA_MTP_PREFILL_SYNC's loop syncs anyway)+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err,+ bool sync) {const OnDevice on_device(device_);const Clock::time_point t0 = Clock::now();const int64_t HCN = g_->hc * g_->n_embd;@@ -951,10 +1412,10 @@ bool MtpDrafter::prefill(const float *R_rows, const int32_t *next_tokens,if (cell0 + c + T <= first_needed) continue;if (!capture_prefill_dev(T, err)) return false;/*- DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.- While the origin API might be synchronous, it depends on the type of- operand memory, so you may need to call wait() on event return by- memcpy API to ensure synchronization behavior.+ DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy+ API. While the origin API might be synchronous, it depends on the+ type of operand memory, so you may need to call wait() on event+ return by memcpy API to ensure synchronization behavior.*/if (DPCT_CHECK_ERROR(cs_->memcpy(tok_, d_tk + c, (size_t)T * 4)) !=0 ||@@ -1001,6 +1462,11 @@ bool MtpDrafter::prefill(const float *R_rows, const int32_t *next_tokens,return false;}}+ if (!sync) { // the caller orders on stream(); the records are staged (a pageable copy returns once taken)+ (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));+ ms_prefill += ms_since(t0);+ return true;+ }if (DPCT_CHECK_ERROR(cs_->wait()) != 0) {/*DPCT1009: SYCL reports errors using exceptions and does not use@@ -1061,18 +1527,20 @@ bool MtpDrafter::prefill(const float *R_rows, const int32_t *next_tokens,ms_prefill += ms_since(t0);return true;}-catch (sycl::exception const &exc) {- std::cerr << exc.what() << "Exception caught at file:" << __FILE__- << ", line:" << __LINE__ << std::endl;- std::exit(1);-}bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* drafts, std::string& err,float* probs, float min_p, int* n_drafts) {const OnDevice on_device(device_);if (T < 1 || T > max_t_ || a < 0 || a >= T) { err = "mtp: draft arguments out of range"; return false; }+ if (chain_live_) { err = "mtp: a pipelined chain is still in flight"; return false; }+ // #783 PR-i (stuchapin909): the round runs for the cells up to the accepted row a (T = a + 1): the K/V of the rejected+ // rows is not caught up - no later read reaches a cell past the one being drafted and the next round writes it first+ if (!mtp_catchup_all()) T = a + 1;const bool cp = coupled_active_; // coupled draft sampling for this request: its own graphsif (!capture_round(T, cp, err)) return false;+ const int max_steps = std::min(max_t_ - 1, max_drafts_);+ for (int j = 1; j < max_steps; ++j)+ if (!capture_step(j, cp, err)) return false;const Clock::time_point t0 = Clock::now();const int64_t NH = g_->n_head;auto put = [&](int row, int64_t cell) {@@ -1087,35 +1555,99 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t*put(t, p + t);}put(2 * max_t_ - 1, coupled_draft_cell(p, a, 0)); // p + a: draft 0's cell+ for (int j = 1; j < max_steps; ++j)+ put(max_t_ + j - 1, coupled_draft_cell(p, a, j));+ for (int j = 0; j < max_steps; ++j) ((volatile int32_t*) h_out_)[j] = -1;h_row_[0] = a;h_row_[1] = 0;+ if (h_force_ != nullptr) for (int j = 0; j < 16; ++j) h_force_[j] = -1; // the forcing kernels: no-ops herestd::atomic_thread_fence(std::memory_order_seq_cst);- if (DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*(cp ? round_exec_c_[T] : round_exec_[T]))) != 0 ||- DPCT_CHECK_ERROR(cs_->wait()) != 0) {- /*- DPCT1009: SYCL reports errors using exceptions and does not use error- codes. Please replace the "get_error_string_dummy(...)" with a real- error-handling function.- */- /*- DPCT1010: SYCL uses exceptions to report errors and does not use the- error codes. The cudaGetLastError function call was replaced with 0. You- need to rewrite this code.- */- err = std::string("mtp draft: ") + dpct::get_error_string_dummy(0);- return false;- }- drafts[0] = ((volatile int32_t*) h_out_)[0];- float pj = ((volatile float*) h_prob_)[0];- if (probs) probs[0] = pj;- int n = 1;- // the chain continues while the last draft is likely enough to be verified- for (int j = 1; j < std::min(max_t_ - 1, max_drafts_) && pj >= min_p; ++j) {- if (!capture_step(j, cp, err)) return false;- put(max_t_ + j - 1, coupled_draft_cell(p, a, j)); // p + a + j; coupled: drawn at counter cell + 1- std::atomic_thread_fence(std::memory_order_seq_cst);- if (DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*(cp ? step_exec_c_[j] : step_exec_[j]))) != 0 ||- DPCT_CHECK_ERROR(cs_->wait()) != 0) {+ if (!stage_source_R(T, err)) return false;++ SessionState* const pss = ple_ss_ ? ple_ss_ : ss_;+ const bool do_ple = pss != nullptr && pss->ple.ready() && pss->ple.table != nullptr;+ int32_t ple_prev[2] = {do_ple ? pss->ple_prev[0] : 0, do_ple ? pss->ple_prev[1] : 0};+ auto prefetch_ple = [&](int32_t tok) {+ if (!do_ple || tok < 0) return;+ uint32_t rows16[strata::kernels::PLE_N_HEADS];+ strata::kernels::ngram_rows(&tok, ple_prev, 1, pss->ple.consts, rows16);+ ple_prev[0] = ple_prev[1];+ ple_prev[1] = tok;+ pss->ple.table->prefetch_rows(rows16);+ };++ int n = 0;+ if (min_p <= 0.0f && max_steps > 0) {+ if (DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(+ *(cp ? round_exec_c_[T] : round_exec_[T]))) != 0) {+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use+ error codes. Please replace the "get_error_string_dummy(...)" with a+ real error-handling function.+ */+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use+ the error codes. The cudaGetLastError function call was replaced+ with 0. You need to rewrite this code.+ */+ err = std::string("mtp draft: ") + dpct::get_error_string_dummy(0);+ return false;+ }+ for (int j = 1; j < max_steps; ++j) {+ if (DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(+ *(cp ? step_exec_c_[j] : step_exec_[j]))) != 0) {+ /*+ DPCT1009: SYCL reports errors using exceptions and does not+ use error codes. Please replace the+ "get_error_string_dummy(...)" with a real error-handling+ function.+ */+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not+ use the error codes. The cudaGetLastError function call was+ replaced with 0. You need to rewrite this code.+ */+ err = std::string("mtp draft step: ") + dpct::get_error_string_dummy(0);+ return false;+ }+ }+ (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));+ prefetch_ple(tokens[a]);+ for (int j = 0; j + 1 < max_steps; ++j) {+ uint32_t spins = 0;+ while (((volatile int32_t*) h_out_)[j] < 0) {+#if defined(_WIN32) || defined(__x86_64__)+ _mm_pause();+#endif+ if ((++spins & 1023u) == 0 &&+ DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty())) != 1) break;+ }+ drafts[j] = ((volatile int32_t*) h_out_)[j];+ if (probs) probs[j] = ((volatile float*) h_prob_)[j];+ prefetch_ple(drafts[j]);+ }+ if (DPCT_CHECK_ERROR(cs_->wait()) != 0) {+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use+ error codes. Please replace the "get_error_string_dummy(...)" with a+ real error-handling function.+ */+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use+ the error codes. The cudaGetLastError function call was replaced+ with 0. You need to rewrite this code.+ */+ err = std::string("mtp draft: ") + dpct::get_error_string_dummy(0);+ return false;+ }+ const int last = max_steps - 1;+ drafts[last] = ((volatile int32_t*) h_out_)[last];+ if (probs) probs[last] = ((volatile float*) h_prob_)[last];+ prefetch_ple(drafts[last]);+ n = max_steps;+ } else if (max_steps > 0) {+ if (DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(+ *(cp ? round_exec_c_[T] : round_exec_[T]))) != 0) {/*DPCT1009: SYCL reports errors using exceptions and does not useerror codes. Please replace the "get_error_string_dummy(...)" with a@@ -1126,14 +1658,73 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t*the error codes. The cudaGetLastError function call was replacedwith 0. You need to rewrite this code.*/- err = std::string("mtp draft step: ") +- dpct::get_error_string_dummy(0);+ err = std::string("mtp draft: ") + dpct::get_error_string_dummy(0);+ return false;+ }+ (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));+ prefetch_ple(tokens[a]);+ auto wait_step = [&](int j) {+ try {+ uint32_t spins = 0;+ while (((volatile int32_t*) h_out_)[j] < 0) {+#if defined(_WIN32) || defined(__x86_64__)+ _mm_pause();+#endif+ if ((++spins & 1023u) == 0 &&+ DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty())) != 1) break;+ }+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ wait_step(0);+ drafts[0] = ((volatile int32_t*) h_out_)[0];+ float pj = ((volatile float*) h_prob_)[0];+ if (probs) probs[0] = pj;+ n = 1;+ for (int j = 1; j < max_steps && pj >= min_p; ++j) {+ if (DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(+ *(cp ? step_exec_c_[j] : step_exec_[j]))) != 0) {+ /*+ DPCT1009: SYCL reports errors using exceptions and does not+ use error codes. Please replace the+ "get_error_string_dummy(...)" with a real error-handling+ function.+ */+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not+ use the error codes. The cudaGetLastError function call was+ replaced with 0. You need to rewrite this code.+ */+ err = std::string("mtp draft step: ") + dpct::get_error_string_dummy(0);+ return false;+ }+ (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));+ prefetch_ple(drafts[j - 1]);+ wait_step(j);+ drafts[j] = ((volatile int32_t*) h_out_)[j];+ pj = ((volatile float*) h_prob_)[j];+ if (probs) probs[j] = pj;+ ++n;+ }+ prefetch_ple(drafts[n - 1]);+ if (DPCT_CHECK_ERROR(cs_->wait()) != 0) {+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use+ error codes. Please replace the "get_error_string_dummy(...)" with a+ real error-handling function.+ */+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use+ the error codes. The cudaGetLastError function call was replaced+ with 0. You need to rewrite this code.+ */+ err = std::string("mtp draft: ") + dpct::get_error_string_dummy(0);return false;}- drafts[j] = ((volatile int32_t*) h_out_)[j];- pj = ((volatile float*) h_prob_)[j];- if (probs) probs[j] = pj;- ++n;}for (int j = n; j < max_t_ - 1; ++j) { drafts[j] = 0; if (probs) probs[j] = 0.0f; }if (n_drafts) *n_drafts = n;@@ -1142,6 +1733,222 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t*return true;}+bool MtpDrafter::stage_source_R(int T, std::string &err) try {+ if (src_R_ == nullptr || src_R_ == window_R_) return true;+ /*+ DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While+ the origin API might be synchronous, it depends on the type of operand+ memory, so you may need to call wait() on event return by memcpy API to+ ensure synchronization behavior.+ */+ if (DPCT_CHECK_ERROR(cs_->memcpy((void *)window_R_, src_R_,+ (size_t)T * (size_t)(g_->hc * g_->n_embd) *+ sizeof(float))) != 0) {+ err = "mtp: staging the window's residual rows failed";+ return false;+ }+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++bool MtpDrafter::prepare_chain(std::string &err) try {+ const OnDevice on_device(device_);+ if (!force_on_ || h_force_ == nullptr) { err = "mtp: chains need set_force_capture before load"; return false; }+ for (int T = 1; T <= max_t_; ++T)+ if (!capture_round(T, false, err)) return false;+ for (int j = 1; j <= max_t_ - 2; ++j)+ if (!capture_step(j, false, err)) return false;+ if (ev_chain_ == nullptr &&+ DPCT_CHECK_ERROR(ev_chain_ = new sycl::event()) != 0) {+ err = "mtp: event creation failed";+ return false;+ }+ for (dpct::event_ptr &e : ev_step_)+ if (e == nullptr && DPCT_CHECK_ERROR(e = new sycl::event()) != 0) {+ err = "mtp: event creation failed";+ return false;+ }+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++bool MtpDrafter::chain_launch(int T, const int32_t *tokens, int64_t p, int a,+ const int32_t *force, int n_force, int n_out,+ int n_early, std::string &err) try {+ const OnDevice on_device(device_);+ if (chain_live_) { err = "mtp: a chain is already in flight"; return false; }+ if (!force_on_ || ev_chain_ == nullptr) { err = "mtp: chains need prepare_chain"; return false; }+ if (T < 1 || T > max_t_ || a < 0 || a >= T || n_out < 1 || n_out > max_t_ - 1 || n_force < 0 || n_force > n_out ||+ n_force > 16) {+ err = "mtp: chain arguments out of range";+ return false;+ }+ if (round_exec_[T] == nullptr) { err = "mtp: chain graphs not prepared"; return false; }+ for (int j = 1; j < n_out; ++j)+ if (step_exec_[j] == nullptr) { err = "mtp: chain graphs not prepared"; return false; }+ const Clock::time_point t0 = Clock::now();+ const int64_t NH = g_->n_head;+ auto put = [&](int row, int64_t cell) {+ h_step_[row * 4 + 0] = (int32_t) cell;+ h_step_[row * 4 + 1] = (int32_t) (cell + 1);+ h_step_[row * 4 + 2] = (int32_t) ((cell + 1) / 4);+ h_step_[row * 4 + 3] = (int32_t) (cell + 1);+ for (int64_t h = 0; h < NH; ++h) h_pos_[row * NH + h] = (int32_t) cell;+ };+ for (int t = 0; t < T; ++t) {+ h_tok_[t] = tokens[t];+ put(t, p + t);+ }+ put(2 * max_t_ - 1, p + a); // output 0's cell+ for (int j = 1; j < n_out; ++j) put(max_t_ + j - 1, p + a + j); // every step's cell, staged at once+ for (int j = 0; j < 16; ++j) h_force_[j] = j < n_force ? force[j] : -1;+ h_row_[0] = a;+ h_row_[1] = 0;+ std::atomic_thread_fence(std::memory_order_seq_cst);+ if (!stage_source_R(T, err)) return false;+ chain_early_ = std::max(0, std::min(n_early, n_out));+ bool ok = DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*round_exec_[T])) == 0;+ /*+ DPCT1024: The original code returned the error code that was further+ consumed by the program logic. This original code was replaced with 0. You+ may need to rewrite the program logic consuming the error code.+ */+ if (ok && chain_early_ >= 1) ok =+ DPCT_CHECK_ERROR(dpct::sync_barrier(ev_step_[0], cs_)) == 0;+ for (int j = 1; ok && j < n_out; ++j) {+ ok = DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*step_exec_[j])) == 0;+ /*+ DPCT1024: The original code returned the error code that was further+ consumed by the program logic. This original code was replaced with 0.+ You may need to rewrite the program logic consuming the error code.+ */+ if (ok && j < chain_early_) ok =+ DPCT_CHECK_ERROR(dpct::sync_barrier(ev_step_[j], cs_)) == 0;+ }+ /*+ DPCT1024: The original code returned the error code that was further+ consumed by the program logic. This original code was replaced with 0. You+ may need to rewrite the program logic consuming the error code.+ */+ if (!ok || DPCT_CHECK_ERROR(dpct::sync_barrier(ev_chain_, cs_)) != 0) {+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use+ error codes. Please replace the "get_error_string_dummy(...)" with a+ real error-handling function.+ */+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use the+ error codes. The cudaGetLastError function call was replaced with 0. You+ need to rewrite this code.+ */+ err = std::string("mtp chain: ") + dpct::get_error_string_dummy(0);+ return false;+ }+ (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty())); // WDDM: submit now+ steps_seen_ = 0;+ chain_live_ = true;+ chain_n_ = n_out;+ ms_draft += ms_since(t0);+ ++rounds;+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++int MtpDrafter::chain_outputs_ready(std::string &err) try {+ if (!chain_live_) return chain_n_;+ const OnDevice on_device(device_);+ while (steps_seen_ < chain_early_) {+ const dpct::err0 q = dpct::sycl_event_query(ev_step_[steps_seen_]);+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1002: Special case error handling if-stmt was detected. You may+ need to rewrite this code.+ */+ if (q == 1) break;+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use+ error codes. Please replace the "get_error_string_dummy(...)" with a+ real error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (q != 0) {+ err = std::string("mtp chain: ") + dpct::get_error_string_dummy(q);+ return -1;+ }+ chain_tok_[steps_seen_] = ((volatile int32_t*) h_out_)[steps_seen_];+ chain_prob_[steps_seen_] = ((volatile float*) h_prob_)[steps_seen_];+ ++steps_seen_;+ }+ return steps_seen_;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++int MtpDrafter::chain_poll(std::string &err) try {+ if (!chain_live_) return 1;+ const OnDevice on_device(device_);+ const dpct::err0 q = dpct::sycl_event_query(ev_chain_);+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1002: Special case error handling if-stmt was detected. You may need+ to rewrite this code.+ */+ if (q == 1) return 0;+ chain_live_ = false;+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (q != 0) {+ err = std::string("mtp chain: ") + dpct::get_error_string_dummy(q);+ return -1;+ }+ for (int j = 0; j < chain_n_; ++j) {+ chain_tok_[j] = ((volatile int32_t*) h_out_)[j];+ chain_prob_[j] = ((volatile float*) h_prob_)[j];+ }+ for (int j = chain_n_; j < 8; ++j) { chain_tok_[j] = 0; chain_prob_[j] = 0.0f; }+ return 1;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}+bool MtpDrafter::draft_first(int T, const float *R_row, int32_t token,int64_t cell, int32_t *drafts, std::string &err,float *probs, float min_p, int *n_drafts) try {diff --git a/sycl/src/core/native_dense.cpp b/sycl/src/core/native_dense.cppindex af95caaff..4c9381085 100644--- a/sycl/src/core/native_dense.cpp+++ b/sycl/src/core/native_dense.cpp@@ -2,17 +2,23 @@#include <sycl/sycl.hpp>#include <dpct/dpct.hpp>#include "strata/core/native_dense.hpp"+#include <cstdlib>#include "strata/core/weights.hpp"#include "strata/artifact/gguf_reader.hpp"#include "strata/kernels/native_mmvq.hpp"+#include "strata/platform/memory.hpp"#include <algorithm>#include <climits>+#include <cstdio>#include <cstdlib>#include <exception>#include <limits>#include <memory>#include <set>+#include <cmath>+#include <cstring>+#include <vector>namespace strata::core {namespace {@@ -22,6 +28,55 @@ bool in_range(const std::string& name) {const int l = std::atoi(name.c_str() + 4);return l >= g_layer_lb && l < g_layer_le;}+// S23 experiment (STRATA_HC_Q8=1): the hyper-connection projections' Q8_0 bytes for the verify read+bool hc_q8_requested() {+ static const bool on = [] { const char* v = std::getenv("STRATA_HC_Q8"); return v != nullptr && v[0] == '1'; }();+ return on;+}+bool hc_q8_name(const std::string& name) {+ if (name == "output_hc_down.weight" || name == "output_hc_up.weight") return true; // S25: the final mixer too+ if (name.rfind("blk.", 0) != 0) return false;+ static const char* suffixes[] = {".hc_attn_down.weight", ".hc_attn_up.weight", ".hc_attn_inject.weight",+ ".hc_ffn_down.weight", ".hc_ffn_up.weight", ".hc_ffn_inject.weight"};+ for (const char* suffix : suffixes) if (name.ends_with(suffix)) return true;+ return false;+}+// S25: the GGUF keeps the inject rows as F32 - quantized here to Q8_0 (ggml's reference rounding) so the Q8_0 read+// covers every hc projection+uint16_t half_bits(float f) {+ uint32_t x;+ std::memcpy(&x, &f, 4);+ const uint32_t sign = (x >> 16) & 0x8000u;+ int32_t e = (int32_t) ((x >> 23) & 0xff) - 127 + 15;+ uint32_t m = x & 0x7fffffu;+ if (e <= 0) { // subnormal or zero+ if (e < -10) return (uint16_t) sign;+ m |= 0x800000u;+ const uint32_t shift = (uint32_t) (14 - e);+ uint32_t h = m >> shift;+ const uint32_t rem = m & ((1u << shift) - 1), half = 1u << (shift - 1);+ if (rem > half || (rem == half && (h & 1u))) ++h;+ return (uint16_t) (sign | h);+ }+ if (e >= 31) return (uint16_t) (sign | 0x7c00u);+ uint32_t h = ((uint32_t) e << 10) | (m >> 13);+ const uint32_t rem = m & 0x1fffu;+ if (rem > 0x1000u || (rem == 0x1000u && (h & 1u))) ++h;+ return (uint16_t) (sign | h);+}+std::vector<uint8_t> q8_0_of(const float* x, uint64_t n) {+ std::vector<uint8_t> out((size_t) (n / 32 * 34));+ for (uint64_t b = 0; b < n / 32; ++b) {+ float amax = 0.0f;+ for (int j = 0; j < 32; ++j) amax = (std::max)(amax, std::fabs(x[b * 32 + j]));+ const float d = amax / 127.0f, id = d != 0.0f ? 1.0f / d : 0.0f;+ uint8_t* o = out.data() + b * 34;+ const uint16_t hb = half_bits(d);+ std::memcpy(o, &hb, 2);+ for (int j = 0; j < 32; ++j) o[2 + j] = (uint8_t) (int8_t) std::lround(x[b * 32 + j] * id);+ }+ return out;+}bool eligible(const strata::TensorInfo& tensor, bool include_ple_key) {const auto& name = tensor.name;if (name.rfind("blk.", 0) != 0) return false;@@ -47,6 +102,7 @@ struct Pending {int type;uint64_t bytes;DevicePtr data;+ DevicePtr packed; // STRATA_Q8_PACKED=1 copy, or null};}@@ -79,6 +135,7 @@ bool NativeDense::keep_unquantized_ple_key(const std::string& pack_dir, std::set}NativeDense::~NativeDense() {+ for (const void* p : packed_keys_) strata::kernels::native_q8_0_packed_unregister(p);if (scratch_) sycl::free(scratch_, dpct::get_in_order_queue());for (void *p : weights_)DPCT_CHECK_ERROR(sycl::free(p, dpct::get_in_order_queue()));@@ -86,8 +143,9 @@ NativeDense::~NativeDense() {bool NativeDense::load(const std::vector<std::string> &shards,WeightTable &table, std::string &err,- bool include_ple_key, int64_t layer_lo, int64_t layer_hi) try {- auto outside = [&](const std::string &name) { // a blk.<l>. tensor of another stage's layers+ bool include_ple_key, int64_t layer_lo,+ int64_t layer_hi) try {+ auto outside = [&](const std::string& name) { // a blk.<l>. tensor of another stage's layersif (layer_hi < 0 || name.rfind("blk.", 0) != 0) return false;const long l = std::strtol(name.c_str() + 4, nullptr, 10);return l < layer_lo || l >= layer_hi;@@ -98,7 +156,7 @@ bool NativeDense::load(const std::vector<std::string> &shards,std::vector<Pending> pending;std::set<std::string> seen;int max_in = 0;- uint64_t total = 0;+ uint64_t total = 0, hc_q8_bytes = 0;uint64_t split_count = 0, split_tensors = 0;std::set<uint64_t> split_numbers;bool have_architecture = false;@@ -158,6 +216,10 @@ bool NativeDense::load(const std::vector<std::string> &shards,if (next != offsets.end() && bytes > *next - tensor.offset) {err = "native dense: overlapping payload " + tensor.name; return false;}+ // the uploads below read these: ask for them now so the reads overlap+ if (eligible(tensor, include_ple_key) && !outside(tensor.name) &&+ strata::kernels::native_mmvq_supported(tensor.type))+ strata::platform::advise_willneed(gguf.tensor_data(tensor), bytes);}for (const auto& tensor : gguf.tensors()) {if (!eligible(tensor, include_ple_key) || outside(tensor.name)) continue;@@ -211,8 +273,85 @@ bool NativeDense::load(const std::vector<std::string> &shards,}max_in = (std::max)(max_in, (int) ref.ne0);total += bytes;- pending.push_back(Pending{&ref, (int) tensor.type, bytes, std::move(data)});+ // STRATA_Q8_PACKED=1: a second, packed copy of an eligible Q8_0 matrix for the decode MMVQ (the GGUF+ // copy stays: the prompt path's GEMMs read it).+ DevicePtr packed;+ if (tensor.type == 8 && tensor.name != "blk.1.ple_key.weight" && // the PLE has its own kernel+ strata::kernels::native_q8_0_packed_enabled() &&+ strata::kernels::native_q8_0_packed_eligible((int) ref.ne0, (int) ref.ne1)) {+ std::vector<uint8_t> host(bytes);+ strata::kernels::native_q8_0_pack_host(gguf.tensor_data(tensor), host.data(), (int) ref.ne0,+ (int) ref.ne1);+ void* packed_allocation = nullptr;+ auto packed_status = DPCT_CHECK_ERROR(+ packed_allocation = (void *)sycl::malloc_device(+ bytes, dpct::get_in_order_queue()));+ packed.reset(packed_allocation);+ if (packed_status == 0)+ packed_status = DPCT_CHECK_ERROR(+ dpct::get_in_order_queue()+ .memcpy(packed.get(), host.data(), bytes)+ .wait());+ /*+ DPCT1000: Error handling if-stmt was detected but could+ not be rewritten.+ */+ if (packed_status != 0) {+ /*+ DPCT1009: SYCL reports errors using exceptions and+ does not use error codes. Please replace the+ "get_error_string_dummy(...)" with a real error-handling+ function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ err = "native dense packed upload " + tensor.name ++ ": " ++ dpct::get_error_string_dummy(packed_status);+ return false;+ }+ }+ pending.push_back(Pending{&ref, (int) tensor.type, bytes, std::move(data), std::move(packed)});}+ if (hc_q8_requested())+ for (const auto& tensor : gguf.tensors()) {+ // S25: the F32 inject rows hold BF16-exact values: the read takes the pack's BF16 rows unless+ // STRATA_HC_Q8_INJECT=1 asks for a Q8_0 copy+ static const bool q8_inject = [] { const char* v = std::getenv("STRATA_HC_Q8_INJECT"); return v && v[0] == '1'; }();+ const bool f32_inject = q8_inject && tensor.type == 0 && tensor.name.ends_with("_inject.weight");+ if ((tensor.type != 8 && !f32_inject) || !hc_q8_name(tensor.name) || tensor.shape.size() != 2) continue;+ auto found = table.table_.find(tensor.name);+ if (found == table.table_.end() || found->second.hc_q8 != nullptr) continue;+ auto& ref = found->second;+ if (tensor.shape[0] != (uint64_t) ref.ne0 || tensor.shape[1] != (uint64_t) ref.ne1 || ref.ne0 % 32 != 0) {+ err = "native dense (STRATA_HC_Q8): incompatible matrix " + tensor.name; return false;+ }+ const uint64_t bytes = (uint64_t) ref.ne0 / 32 * 34 * (uint64_t) ref.ne1;+ void* p = nullptr;+ std::vector<uint8_t> 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(+ bytes, dpct::get_in_order_queue())) != 0 ||+ /*+ DPCT1114: cudaMemcpy is migrated to+ asynchronization memcpy, assuming in the original code+ the source host memory is pageable memory. If the memory+ is not pageable, call wait() on event return by memcpy+ API to ensure synchronization behavior.+ */+ DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(+ p,+ f32_inject ? (const void *)q8.data()+ : gguf.tensor_data(tensor),+ bytes).wait()) != 0) {+ err = "native dense (STRATA_HC_Q8) upload " + tensor.name; return false;+ }+ ref.hc_q8 = p;+ weights_.push_back(p);+ hc_q8_bytes += bytes;+ }}if (pending.empty()) { err = "native dense: no supported GDN/QSA matrices in supplied shards"; return false; }void* allocation = nullptr;@@ -240,14 +379,30 @@ bool NativeDense::load(const std::vector<std::string> &shards,}// All checks and allocations finish before publishing any reference.weights_.reserve(pending.size());+ uint64_t packed_bytes = 0;+ size_t packed_count = 0;for (auto& item : pending) {item.ref->native_data = item.data.get();item.ref->native_type = item.type;item.ref->native_q8_1 = scratch.get();+ if (item.packed) {+ strata::kernels::native_q8_0_packed_register(item.data.get(), item.packed.get(), (int) item.ref->ne0,+ (int) item.ref->ne1);+ packed_keys_.push_back(item.data.get());+ packed_bytes += item.bytes;+ ++packed_count;+ weights_.push_back(item.packed.release());+ }weights_.push_back(item.data.release());}+ if (packed_count)+ std::fprintf(stderr, "native dense: STRATA_Q8_PACKED=1 packed %zu Q8_0 matrices for decode (+%.1f MiB)\n",+ packed_count, packed_bytes / 1048576.0);scratch_ = scratch.release();- bytes_ = total;+ bytes_ = total + hc_q8_bytes;+ if (hc_q8_requested())+ std::fprintf(stderr, "strata: STRATA_HC_Q8=1: %.2f GiB of Q8_0 hyper-connection projections for the verify read\n",+ (double) hc_q8_bytes / 1073741824.0);return true;} catch (const std::exception& error) {err = std::string("native dense: ") + error.what();diff --git a/sycl/src/core/native_head.cpp b/sycl/src/core/native_head.cppindex 6b5a938f5..9f4b270fd 100644--- a/sycl/src/core/native_head.cpp+++ b/sycl/src/core/native_head.cpp@@ -5,6 +5,7 @@#include "strata/artifact/gguf_reader.hpp"#include "strata/kernels/iq_kernels.hpp"#include "strata/kernels/native_mmvq.hpp"+#include "strata/platform/memory.hpp"#include <climits>#include <cstdio>@@ -14,6 +15,7 @@namespace strata::core {NativeHead::~NativeHead() {+ if (weights_) strata::kernels::native_q6_k_unpack(weights_);if (scratch_) sycl::free(scratch_, dpct::get_in_order_queue());if (weights_) sycl::free(weights_, dpct::get_in_order_queue());}@@ -55,6 +57,7 @@ bool NativeHead::load(const std::vector<std::string> &shards, int64_t n_in,scratch = (void *)sycl::malloc_device(strata::kernels::native_q8_1_bytes((int)n_in, 1),dpct::get_in_order_queue()));+ strata::platform::advise_willneed(gguf.tensor_data(*tensor), bytes);if (status == 0)status = DPCT_CHECK_ERROR(dpct::get_in_order_queue()@@ -85,6 +88,8 @@ bool NativeHead::load(const std::vector<std::string> &shards, int64_t n_in,n_in_ = (int) n_in;n_out_ = (int) n_out;type_ = (int) tensor->type;+ if (type_ == 14 && strata::kernels::native_q6_k_packed_enabled()) // STRATA_Q6_PACKED=1+ strata::kernels::native_q6_k_pack(weights_, n_in_, n_out_, "output head");return true;} catch (const std::exception& error) {err = std::string("native head: ") + error.what();@@ -185,6 +190,7 @@ bool NativeEmbed::load(const std::vector<std::string> &shards, int64_t n_embd,bytes_ = 0;return false;}+ strata::platform::advise_willneed(gguf.tensor_data(*t), bytes_); // copied out of the mapping below/*DPCT1048: The original value cudaHostAllocMapped is not meaningful inthe migrated code and was removed or replaced with 0. You may need todiff --git a/sycl/src/core/pinned.dp.cpp b/sycl/src/core/pinned.dp.cppindex 6fdd17ce6..57fc68e4a 100644--- a/sycl/src/core/pinned.dp.cpp+++ b/sycl/src/core/pinned.dp.cpp@@ -6,6 +6,7 @@#include "strata/platform/memory.hpp"#include <atomic>+#include <climits>#include <cerrno>#include <cstdlib>#include <cstdio>@@ -225,9 +226,49 @@ void* reserve(uint64_t bytes, PageBacking& got, std::string& note, const std::stnote = "MAP_HUGETLB unavailable (needed " + std::to_string(need) + " 2 MiB pages, vm.nr_hugepages=" +(have_pool ? std::to_string(pool) : std::string("?")) + "); using 4 KB pages";}- void* p = mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);+ // No hugetlb mapping: a 2 MiB-aligned anonymous mapping with MADV_HUGEPAGE, so transparent huge pages back+ // it where THP is "madvise" (the common distro default). The CPU expert pool streams whole experts out of+ // this arena; with 4 KB pages every 3 MB expert costs ~750 TLB misses.+ constexpr uint64_t kAlign = 2ull << 20;+ const uint64_t padded = bytes + kAlign;+ void* raw = mmap(nullptr, padded, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);got = PageBacking::NormalPages;- return p == MAP_FAILED ? nullptr : p;+ if (raw == MAP_FAILED) return nullptr;+ const uintptr_t start = (uintptr_t) raw;+ const uintptr_t aligned = (start + kAlign - 1) & ~(uintptr_t) (kAlign - 1);+ if (aligned > start) munmap(raw, aligned - start);+ const uintptr_t end = aligned + bytes, raw_end = start + padded;+ if (raw_end > end) munmap((void*) end, raw_end - end);+ void* p = (void*) aligned;+ // #771: with THP "always" the kernel already backs this mapping with huge pages where it can; the extra+ // MADV_HUGEPAGE only adds direct reclaim and compaction on every fault (defrag=madvise), which on a fragmented+ // machine stretched a 25 s start to 432 s. So it is not asked for there. STRATA_NO_ARENA_THP=1 skips it+ // anywhere (the request alone; STRATA_NO_LARGEPAGES also skips the hugetlb try).+ std::string thp_mode;+ if (std::FILE* f = std::fopen("/sys/kernel/mm/transparent_hugepage/enabled", "r")) {+ char line[128] = {0};+ if (std::fgets(line, sizeof line, f) != nullptr) {+ const char* open = std::strchr(line, '[');+ const char* close = open ? std::strchr(open, ']') : nullptr;+ if (open && close) thp_mode.assign(open + 1, close);+ }+ std::fclose(f);+ }+ const bool skip_thp_request = std::getenv("STRATA_NO_ARENA_THP") != nullptr || thp_mode == "always";+ if (std::getenv("STRATA_NO_LARGEPAGES") == nullptr && skip_thp_request) {+ const std::string four_k = "; using 4 KB pages";+ if (note.size() >= four_k.size() && note.compare(note.size() - four_k.size(), four_k.size(), four_k) == 0)+ note.resize(note.size() - four_k.size());+ note += std::getenv("STRATA_NO_ARENA_THP") != nullptr+ ? "; transparent huge pages skipped (STRATA_NO_ARENA_THP)"+ : "; transparent huge pages are on for every mapping (THP always): MADV_HUGEPAGE not requested";+ } else if (std::getenv("STRATA_NO_LARGEPAGES") == nullptr && madvise(p, bytes, MADV_HUGEPAGE) == 0) {+ const std::string four_k = "; using 4 KB pages";+ if (note.size() >= four_k.size() && note.compare(note.size() - four_k.size(), four_k.size(), four_k) == 0)+ note.resize(note.size() - four_k.size());+ note += "; transparent huge pages requested (MADV_HUGEPAGE)";+ }+ return p;#endif}@@ -411,7 +452,9 @@ PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t> &bounds,std::to_string(registered_bytes >> 30) + " GiB); " + note;if (registered_bytes < bytes) {const char* env = std::getenv("STRATA_ARENA_LOCK");- if (env == nullptr || std::string(env) != "0") {+ if (backing == PageBacking::LargePages) { // #779: large pages cannot be paged out: nothing to lock+ note = "large pages are resident without a lock; " + note;+ } else if (env == nullptr || std::string(env) != "0") {const strata::platform::LockResult lr =strata::platform::lock_resident((uint8_t*) base + registered_bytes, bytes - registered_bytes);locked_bytes = lr.locked_bytes;@@ -449,7 +492,9 @@ PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t> &bounds,// and the CPU pool's rate then depends on the OS; locking it through the working set needs no// special privilege. STRATA_ARENA_LOCK=0 is the A/B arm.const char* env = std::getenv("STRATA_ARENA_LOCK");- if (env == nullptr || std::string(env) != "0") {+ if (backing == PageBacking::LargePages) { // #779: large pages cannot be paged out: nothing to lock+ note = "large pages are resident without a lock; " + note;+ } else if (env == nullptr || std::string(env) != "0") {const strata::platform::LockResult lr = strata::platform::lock_resident(base, bytes);locked_bytes = lr.locked_bytes;note = lr.note + "; " + note;@@ -465,6 +510,62 @@ catch (sycl::exception const &exc) {std::exit(1);}+PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t>& bounds, Deferred)+ : capacity(bytes), bounds_(bounds) {+ if (bytes == 0 || bounds.size() < 2) return;+ base = reserve(bytes, backing, note, std::string{}, 0, mapping_base, mapping_bytes);+ if (base != nullptr && mapping_base == nullptr) {+ mapping_base = base;+ mapping_bytes = bytes;+ }+ slice_bytes = 1; // sliced: one registration per layer+}++void PinnedArena::register_slices(std::atomic<int> &ready) try {+ const int n = (int) bounds_.size() - 1;+ int i = 0;+ for (; base != nullptr && i < n; ++i) {+ const uint64_t off = bounds_[(size_t) i], len = bounds_[(size_t) i + 1] - off;+ /*+ DPCT1027: The call to cudaHostRegister was replaced with 0 because+ SYCL currently does not support registering of existing host memory for+ use by device. Use USM to allocate memory for use by host and device.+ */+ if (0 != 0) {+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use+ the error codes. The cudaGetLastError function call was replaced+ with 0. You need to rewrite this code.+ */+ (void)0;+ break;+ }+ slice_starts.push_back(off);+ registered_bytes = off + len;+ ++registered_slices;+ ready.store(i + 1, std::memory_order_release);+ }+ note = "cudaHostRegister per layer, pipelined with the load: " + std::to_string(registered_slices) + " of " ++ std::to_string(n) + " slices pinned; " + note;+ if (i < n && base != nullptr) { // the rest stays resident through the working-set lock, as the sliced fallback does+ const char* env = std::getenv("STRATA_ARENA_LOCK");+ if (backing == PageBacking::LargePages) { // #779: large pages cannot be paged out: nothing to lock+ note = "large pages are resident without a lock; " + note;+ } else if (env == nullptr || std::string(env) != "0") {+ const strata::platform::LockResult lr =+ strata::platform::lock_resident((uint8_t*) base + registered_bytes, capacity - registered_bytes);+ locked_bytes = lr.locked_bytes;+ note = lr.note + "; " + note;+ }+ }+ ready.store(INT_MAX, std::memory_order_release); // every slice done (or given up on)+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}+PinnedArena::~PinnedArena() {if (base) {if (locked_bytes) strata::platform::unlock_resident((uint8_t*) base + (slice_bytes ? registered_bytes : 0), locked_bytes);@@ -499,19 +600,20 @@ LoadStats load_experts(const std::string& path, uint8_t* dst, uint64_t blob_byte}LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std::vector<uint64_t>& layer_off,- const std::vector<uint64_t>& layer_bytes, int threads, uint64_t chunk) {+ const std::vector<uint64_t>& layer_bytes, int threads, uint64_t chunk,+ const std::atomic<int>* ready) {LoadStats st;st.ok = false;#ifdef _WIN32constexpr uint64_t kAlign = 4096;if (((uintptr_t) dst % kAlign) != 0 || chunk == 0 || chunk % kAlign != 0) return st;- struct Piece { uint64_t off, n; };+ struct Piece { uint64_t off, n; int layer; };std::vector<Piece> pieces;uint64_t bytes = 0;for (size_t L = 0; L < layer_off.size(); ++L) {if (layer_off[L] % kAlign != 0 || layer_bytes[L] % kAlign != 0) return st;for (uint64_t p = 0; p < layer_bytes[L]; p += chunk)- pieces.push_back({layer_off[L] + p, std::min<uint64_t>(chunk, layer_bytes[L] - p)});+ pieces.push_back({layer_off[L] + p, std::min<uint64_t>(chunk, layer_bytes[L] - p), (int) L});bytes += layer_bytes[L];}if (threads < 1) threads = 1;@@ -520,7 +622,7 @@ LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std::std::mutex err_mu;std::string err;const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);- std::vector<wchar_t> wpath((size_t) std::max(wide, 1), L'\0');+ std::vector<wchar_t> wpath((size_t) (std::max)(wide, 1), L'\0');if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide);auto worker = [&]() {HANDLE h = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,@@ -535,6 +637,8 @@ LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std::for (;;) {const size_t i = next.fetch_add(1);if (i >= pieces.size()) break;+ if (ready != nullptr) // the slice must be registered before its pages are touched+ while (ready->load(std::memory_order_acquire) <= pieces[i].layer + 1) std::this_thread::yield();OVERLAPPED ov{};ov.Offset = (DWORD) pieces[i].off;ov.OffsetHigh = (DWORD) (pieces[i].off >> 32);@@ -565,7 +669,7 @@ LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std::st.bytes = bytes;st.seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();#else- (void) path; (void) dst; (void) layer_off; (void) layer_bytes; (void) threads; (void) chunk;+ (void) path; (void) dst; (void) layer_off; (void) layer_bytes; (void) threads; (void) chunk; (void) ready;#endifreturn st;}@@ -588,7 +692,7 @@ bool experts_unbuffered(const std::vector<std::string>& files, uint64_t arena_byuint64_t seed = (uint64_t) GetTickCount64() * 6364136223846793005ull + 1442695040888963407ull;for (const std::string& f : files) {const int wide = MultiByteToWideChar(CP_UTF8, 0, f.c_str(), -1, nullptr, 0);- std::vector<wchar_t> w((size_t) std::max(wide, 1), L'\0');+ std::vector<wchar_t> w((size_t) (std::max)(wide, 1), L'\0');if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, f.c_str(), -1, w.data(), wide);HANDLE h = CreateFileW(w.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS,nullptr);@@ -640,7 +744,8 @@ bool experts_unbuffered(const std::vector<std::string>& files, uint64_t arena_by}LoadStats load_experts_ranges(const std::string& path, uint8_t* dst, const std::vector<uint64_t>& layer_off,- const std::vector<uint64_t>& layer_bytes, int threads, uint64_t chunk) {+ const std::vector<uint64_t>& layer_bytes, int threads, uint64_t chunk,+ const std::atomic<int>* ready) {LoadStats st;const uint64_t layers = (uint64_t) layer_off.size();st.layers = layers;@@ -681,6 +786,8 @@ LoadStats load_experts_ranges(const std::string& path, uint8_t* dst, const std::for (;;) {const uint64_t L = next_layer.fetch_add(1);if (L >= layers) break;+ if (ready != nullptr) // the slice must be registered before its pages are touched+ while (ready->load(std::memory_order_acquire) <= (int) L + 1) std::this_thread::yield();const uint64_t off = layer_off[(size_t) L];uint64_t remaining = layer_bytes[(size_t) L];uint64_t pos = 0;diff --git a/sycl/src/core/remote_expert_opt_stub.cpp b/sycl/src/core/remote_expert_opt_stub.cppnew file mode 100644index 000000000..a34f7835b--- /dev/null+++ b/sycl/src/core/remote_expert_opt_stub.cpp@@ -0,0 +1,38 @@+// --remote-expert-opt (Remote Expert Decode Optimization) needs a second CUDA device as an expert tier; the SYCL port+// has no such tier (the peer-expert and remote-expert helpers are single-device stubs). The class exists so the shared+// headers and generate.cpp build; init() refuses with a message, so the option reports itself unsupported.+#include "strata/core/remote_expert_opt.hpp"++namespace strata::core {++RemoteExpertOpt::~RemoteExpertOpt() = default;++void RemoteExpertOpt::attach(RemoteExperts&) {}++bool RemoteExpertOpt::init(std::string& err) {+ err = "--remote-expert-opt is not supported by the SYCL engine (no second-device expert tier)";+ return false;+}++bool RemoteExpertOpt::owns(int64_t, int32_t) const { return false; }++bool RemoteExpertOpt::adapt(const std::vector<float>&, const std::vector<int32_t>&,+ const std::vector<std::pair<int32_t, int32_t>>&, int, ExpertSource&) {+ return false;+}++void RemoteExpertOpt::begin(const float*, int, int) {}++void RemoteExpertOpt::copy_rows(float*, const float*, int, int, const int32_t*, const int32_t*, void*) const {}++void RemoteExpertOpt::combine(float*, float*, int, int, const uint32_t*, uint32_t, void*) const {}++size_t RemoteExpertOpt::metadata_bytes() { return 0; }++void RemoteExpertOpt::prepare(const RemoteExperts&, void*) const {}++bool RemoteExpertOpt::reduce(RemoteExperts&, const void*, std::string&) { return true; }++void RemoteExpertOpt::accumulate(const RemoteExperts&) {}++} // namespace strata::corediff --git a/sycl/src/core/remote_experts.cpp b/sycl/src/core/remote_experts.cppindex 5d198b0fb..2473463bb 100644--- a/sycl/src/core/remote_experts.cpp+++ b/sycl/src/core/remote_experts.cpp@@ -160,7 +160,7 @@ void RemoteExperts::close() {bool RemoteExperts::open(int device, int slots, int64_t layers, int64_t experts,const std::vector<std::pair<int32_t, int32_t>> &ranked,const ExpertCache &primary, ExpertSource &source,- std::vector<uint8_t> &claimed, std::string &err) try {+ std::vector<uint8_t> &claimed, std::string &err, bool /*auto_size*/) try {close();int count = 0;if (!check(DPCT_CHECK_ERROR(count = dpct::device_count()),diff --git a/sycl/src/core/session.cpp b/sycl/src/core/session.cppindex e3bc11676..ecb690441 100644--- a/sycl/src/core/session.cpp+++ b/sycl/src/core/session.cpp@@ -781,10 +781,17 @@ bool SessionLoopScratch::init(size_t parts_bytes_in, std::string &err) try {// core or its SMT sibling. The symptom is not an error: it is a CPU path at 26.9 GB/s where the same pool// runs at 36.32. It was being done and undone on EVERY token, which is a syscall pair on the critical path// for a property that wants to hold for the whole session.- const std::vector<int> cores = strata::kernels::cpu::physical_cores(false);- if (!cores.empty()) {- pinned_core = strata::kernels::cpu::pin_current_thread(cores[0]);+ // The host's core is the pool's reserved one: the first physical core, or the last with --host-core last (F12).+ const int host_core = strata::kernels::cpu::planned_host_core();+ if (host_core >= 0) {+ pinned_core = strata::kernels::cpu::pin_current_thread(host_core);pinned = pinned_core.valid;+ } else {+ const std::vector<int> cores = strata::kernels::cpu::physical_cores(false);+ if (!cores.empty()) {+ pinned_core = strata::kernels::cpu::pin_current_thread(cores[0]);+ pinned = pinned_core.valid;+ }}return true;}@@ -1375,8 +1382,8 @@ bool session_run_token(const ModelGeometry &g, int64_t pos, int32_t pos_base,err = "session_run_token: layer " + std::to_string(l) +" never rang (" +/*- DPCT1009: SYCL reports errors using exceptions- and does not use error codes. Please replace the+ DPCT1009: SYCL reports errors using exceptions and+ does not use error codes. Please replace the"get_error_string_dummy(...)" with a realerror-handling function.*/diff --git a/sycl/src/core/verify.cpp b/sycl/src/core/verify.cppindex 27aa6fb40..5ad44bd2e 100644--- a/sycl/src/core/verify.cpp+++ b/sycl/src/core/verify.cpp@@ -1,7 +1,10 @@// src/core/verify.cpp - see include/strata/core/verify.hpp.+#define DPCT_PROFILING_ENABLED#include <sycl/sycl.hpp>#include <dpct/dpct.hpp>#include "strata/core/verify.hpp"+#include "strata/core/remote_expert_opt.hpp"+#include "strata/core/dma_batch.hpp"#if defined(_WIN32)#include <intrin.h>#endif@@ -59,6 +62,12 @@ constexpr float EPS = 1e-6f;using Clock = std::chrono::steady_clock;double ms_since(Clock::time_point t) { return std::chrono::duration<double, std::milli>(Clock::now() - t).count(); }const bool g_dbg = std::getenv("STRATA_VERIFY_DEBUG") != nullptr;+inline bool g_lfuse() { static const bool on = [] { const char* v = std::getenv("STRATA_LFUSE"); return v != nullptr && v[0] == '1'; }(); return on; }+inline bool g_lfuse_gate() { static const bool on = [] { const char* v = std::getenv("STRATA_LFUSE_GATE"); return v == nullptr || v[0] != '0'; }(); return on; }+inline bool g_lfuse_pair() { static const bool on = [] { const char* v = std::getenv("STRATA_LFUSE_PAIR"); return v == nullptr || v[0] != '0'; }(); return on; }+inline bool g_qdedup() { static const bool on = [] { const char* v = std::getenv("STRATA_VERIFY_QDEDUP"); return v != nullptr && std::atoi(v) != 0; }(); return on; }+// S26 STRATA_QFUSE=1: activation q8_1 images written by their producers (the GDN output norm) - the same bytes+inline bool g_qfuse() { static const bool on = [] { const char* v = std::getenv("STRATA_QFUSE"); return v != nullptr && std::atoi(v) != 0; }(); return on; }#define VDBG(...) do { if (g_dbg) { std::fprintf(stderr, "verify dbg: " __VA_ARGS__); std::fflush(stderr); } } while (0)struct Bump {@@ -83,6 +92,57 @@ const bool g_coherent = env_on("STRATA_VERIFY_COHERENT");const bool g_doorbell_store = env_on("STRATA_DOORBELL_STORE");#endifconst bool g_trace = env_on("STRATA_VERIFY_TRACE");+const bool g_no_multi_gr = env_on("STRATA_NO_MULTI_GR"); // #783 PR-g: per-token GR reads/writes and generic-T kernels again+const bool g_no_batch_kv = env_on("STRATA_NO_BATCH_KV_STEP"); // #783 PR-d: per-token K/V and indexer appends again++// The shared expert runs on its own stream, forked off and joined back per layer (`sh_fork` in record_window). The+// overlap pays off on CUDA, where it was added (cfd3b72). On HIP a cross-stream event dependency costs more than the+// shared expert takes to run, so there the fork starts off: same binary, same 48,067-token prompt, three runs each on a+// Radeon AI PRO R9700 (gfx1201, ROCm 6.4.3), the fork off decodes at 62.9 t/s against 43.4 t/s with it on. The+// profiler turns the fork off to time the stages, so a profiled run never showed that. #816 reports the same fall on a+// gfx1030 (RX 6800, Windows, 42.5 -> 56.4 t/s). STRATA_SH_STREAM overrides either default: `=1` forks, `=0` does not.+// Strix Halo (gfx1151, unified memory) is the exception: the fork pays there (+1.8% UD-IQ4_XS, +6.7% UD-Q4_K_XL decode+// at 8K, ids identical), so the gfx1151 arch table sets STRATA_SH_STREAM=1. Read on first use, after that table ran.+bool sh_stream_on() {+ static const bool on = [] {+ if (const char* v = std::getenv("STRATA_SH_STREAM")) return v[0] != '0';+#if defined(STRATA_USE_HIP)+ return false;+#else+ return true;+#endif+ }();+ return on;+}++// A one-token window always keeps its token, so its graph advances the sequence state itself (the GDN conv history+// and recurrence state) and Verifier::commit launches no commit graph after it (eddoursul's fork, F7). CUDA only:+// HIP keeps the commit graph after every window (STRATA_ONE_TOKEN_COMMIT=0 does too).+// The head's hyper-connection read for the window's tokens in one launch set (CUDA; HIP keeps gr_read per token;+// STRATA_HEAD_MIX_MULTI=0 does too): bitwise the same sums.+bool head_mix_multi_enabled() {+#if defined(STRATA_USE_HIP)+ return false;+#else+ static const bool on = [] {+ const char* v = std::getenv("STRATA_HEAD_MIX_MULTI");+ return v == nullptr || std::atoi(v) != 0;+ }();+ return on;+#endif+}++bool one_token_self_commit() {+#if defined(STRATA_USE_HIP)+ return false;+#else+ static const bool on = [] {+ const char* v = std::getenv("STRATA_ONE_TOKEN_COMMIT");+ return v == nullptr || std::atoi(v) != 0;+ }();+ return on;+#endif+}bool mapped(size_t bytes, void **h, void **d) try {/*@@ -284,16 +344,32 @@ Verifier::~Verifier() try {slot.compare_exchange_strong(me, nullptr);}if (cs_) cs_->wait();+ if (sh_cs_) sh_cs_->wait();for (auto& e : exec_)if (e) delete (e);+ for (auto& e : exec_nr_)+ if (e) delete (e);if (commit_exec_) delete (commit_exec_);- if (cs_) dpct::get_current_device().destroy_queue(cs_);- if (copy_) {- copy_->wait(); dpct::get_current_device().destroy_queue(copy_);- }+ for (auto& kv : exec_bm_)+ if (kv.second) delete (kv.second);+ for (auto& kv : commit_bm_)+ if (kv.second) delete (kv.second);+ if (arena_b_) sycl::free(arena_b_, dpct::get_in_order_queue());+ if (h_commitb_) sycl::free(h_commitb_, dpct::get_in_order_queue());+ if (qcnt_) sycl::free(qcnt_, dpct::get_in_order_queue());+ if (cs_ && cs_ != ext_stream_) dpct::get_current_device().destroy_queue(+ cs_); // set_stream: the stage's stream, shared, not ours+ if (sh_cs_) dpct::get_current_device().destroy_queue(sh_cs_);+ if (copy_) { copy_->wait(); dpct::get_current_device().destroy_queue(copy_); }+ if (commit_done_) dpct::destroy_event(commit_done_);+ if (ev_done_) dpct::destroy_event(ev_done_);+ if (ev_commit_) dpct::destroy_event(ev_commit_);+ if (prof_pin_) sycl::free(prof_pin_, dpct::get_in_order_queue());+ if (ev_fork_) dpct::destroy_event(ev_fork_);+ if (ev_join_) dpct::destroy_event(ev_join_);if (arena_) sycl::free(arena_, dpct::get_in_order_queue());void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_,- h_flagA_, h_plan_, h_flagB_};+ h_flagA_, h_plan_, h_flagB_, h_plan_err_};for (void* h : hosts)if (h) sycl::free(h, dpct::get_in_order_queue());} catch (...) {@@ -381,6 +457,7 @@ bool Verifier::init(const WeightTable &wt, const ModelGeometry &g,mapped(64, (void**) &h_flag_, (void**) &m_flag_) &&mapped(64, (void**) &h_flagA_, (void**) &m_flagA_) &&mapped(64, (void**) &h_flagB_, (void**) &m_flagB_) &&+ mapped(64, (void**) &h_plan_err_, (void**) &m_plan_err_) &&mapped(T * K * N * 4, (void**) &h_ymiss_, (void**) &m_ymiss_);if (!ok) { err = "verify: mapped staging allocation failed"; return false; }// the GPU plan: counts(4) | start(cap+1) | dst(cap) | tok(cap) | pad | ptr(cap u64) | ptr2(cap u64) | start2(cap+1)@@ -415,6 +492,7 @@ bool Verifier::init(const WeightTable &wt, const ModelGeometry &g,inj_ = b.take<float>(T * HC); inj2_ = b.take<float>(T * HC);lo_ = b.take<float>(T * (uint64_t) g.hc_lr); rs_ = b.take<float>(T * HC); xn_ = b.take<float>(T * HC * N);xq_ = b.take<uint8_t>(strata::kernels::native_q8_1_bytes(max_in, (int) T));+ sh_xq_ = b.take<uint8_t>(strata::kernels::native_q8_1_bytes(max_in, (int) T));qkv_L_ = b.take<float>(nG * T * C); h_L_ = b.take<float>(nG * T * C);gate_L_ = b.take<float>(nG * T * HV); beta_L_ = b.take<float>(nG * T * HV);z_ = b.take<float>(T * ZV); y_ = b.take<float>(T * ZV); y_dummy_ = b.take<float>(T * ZV);@@ -439,7 +517,10 @@ bool Verifier::init(const WeightTable &wt, const ModelGeometry &g,sh_bf16_ = b.take<uint16_t>(T * N); sh_gate_ = b.take<float>(T * (uint64_t) g.n_ff);sh_up_ = b.take<float>(T * (uint64_t) g.n_ff); sh_g_ = b.take<float>(T + 4);head_logits_ = b.take<float>(T * (uint64_t) n_vocab_);+ arg_scratch_ = b.take<uint8_t>(strata::kernels::argmax_rows_scratch_bytes((int) T));+ one_ = b.take<int32_t>(4);hist_snap_ = b.take<float>(T * HS);+ ple_key_ = b.take<float>(T * (uint64_t) strata::kernels::NG_HC_DIM); ple_val_ = b.take<float>(T * N);};Bump count;carve(count);@@ -483,6 +564,15 @@ bool Verifier::init(const WeightTable &wt, const ModelGeometry &g,Bump real;real.base = (uint8_t*) arena_;carve(real);+ {+ const int32_t one = 1;+ if (DPCT_CHECK_ERROR(dpct::get_in_order_queue()+ .memcpy(one_, &one, sizeof one)+ .wait()) != 0) {+ err = "verify: the arena could not be set";+ return false;+ }+ }sink_.staging = (unsigned long long) staging_;sink_.staging_cap = kStagingBlobs;(void) TS;@@ -495,27 +585,87 @@ 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_ =+ ext_stream_; // set_stream (pipelined windows): the stage's shared+ // stream+ /*+ DPCT1025: The SYCL queue is created ignoring the flag and priority+ options.+ */+ else if (DPCT_CHECK_ERROR(+ cs_ = dpct::get_current_device().create_queue(true)) != 0)+ cs_ = &dpct::get_in_order_queue();/*DPCT1025: The SYCL queue is created ignoring the flag and priorityoptions.*/- if (DPCT_CHECK_ERROR(cs_ = dpct::get_current_device().create_queue(true)) !=- 0) {+ if (cs_ == &dpct::get_in_order_queue() ||+ DPCT_CHECK_ERROR(+ sh_cs_ = dpct::get_current_device().create_queue(true)) != 0) {err = "verify: stream create failed";return false;}+ if (DPCT_CHECK_ERROR(commit_done_ = new sycl::event()) != 0 ||+ DPCT_CHECK_ERROR(ev_fork_ = new sycl::event()) != 0 ||+ DPCT_CHECK_ERROR(ev_join_ = new sycl::event()) != 0) {+ err = "verify: event create failed";+ return false;+ }+ // Check whether 100% of experts across [lb_, le_) are resident in this stage's VRAM cache.+ // When true, every layer plans on device and writes directly into parts_ without any CPU doorbells,+ // wait_flag_ge spins, PCIe empty launches, or moe_hit_add copies.+ all_resident_ = false;+ ar_off_ = false;+ h_res_ = hits.h_res;+ if (h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0;+ if (hits.h_res != nullptr && hits.d_res != nullptr && hits.cache_base != nullptr) {+ const char* v_ar = std::getenv("STRATA_VERIFY_ALL_RESIDENT");+ if (v_ar == nullptr || std::atoi(v_ar) != 0) {+ bool all_ok = true;+ for (int64_t l = lb_; l < le_ && all_ok; ++l) {+ for (int64_t e = 0; e < g.n_expert; ++e) {+ if (hits.h_res[l * g.n_expert + e] < 0) {+ all_ok = false;+ break;+ }+ }+ }+ all_resident_ = all_ok;+ }+ }// E-6: a layer whose routed experts are all resident is planned on the device (STRATA_VERIFY_DEVICE_PLAN=1: on;// exact, but neutral on RIBPC 1-2 GPUs: off by default){const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN");- device_plan_ = v != nullptr && std::atoi(v) != 0;+ // (not with set_always_publish: the device table may lag the host's while windows are in flight)+ device_plan_ = !all_resident_ && !always_publish_ && (v != nullptr && std::atoi(v) != 0);}- if (device_plan_) {- bool ok2 =- DPCT_CHECK_ERROR(skip_ = (uint32_t *)sycl::malloc_device(- 64, dpct::get_in_order_queue())) == 0 &&+ // (halo's STRATA_VERIFY_RESIDENT=1 is this window's all_resident_ graph above, which 0.1.39 has on by default)+ if (g_qfuse()) { // S26: the HC read's q8_1 group counters, zeroed once (each launch leaves them zero)+ if (DPCT_CHECK_ERROR(qcnt_ = sycl::malloc_device<unsigned int>(+ (size_t)(g.n_embd / 32),+ dpct::get_in_order_queue())) != 0 ||DPCT_CHECK_ERROR(- dpct::get_in_order_queue().memset(skip_, 0, 64).wait()) == 0;+ dpct::get_in_order_queue()+ .memset(qcnt_, 0,+ sizeof(unsigned) * (size_t)(g.n_embd / 32))+ .wait()) != 0) {+ /*+ DPCT1026: The call to cudaGetLastError was removed because this+ functionality is redundant in SYCL.+ */+ if (qcnt_) sycl::free(qcnt_, dpct::get_in_order_queue());+ qcnt_ = nullptr;+ }+ }+ if (all_resident_ || device_plan_) {+ bool ok2 = true;+ if (device_plan_)+ ok2 = DPCT_CHECK_ERROR(skip_ = (uint32_t *)sycl::malloc_device(+ 64, dpct::get_in_order_queue())) == 0 &&+ DPCT_CHECK_ERROR(+ dpct::get_in_order_queue().memset(skip_, 0, 64).wait()) ==+ 0;if (ok2 && hits.slot_off != nullptr && hits.n_slots > 0) {ok2 = DPCT_CHECK_ERROR(slot_off_d_ = sycl::malloc_device<unsigned long long>(@@ -531,14 +681,15 @@ bool Verifier::init(const WeightTable &wt, const ModelGeometry &g,DPCT1026: The call to cudaGetLastError was removed because thisfunctionality is redundant in SYCL.*/- if (!ok2) {; device_plan_ = false; }+ if (!ok2) {; all_resident_ = false; device_plan_ = false; }}if (std::getenv("STRATA_VERIFY_DEBUG") != nullptr) { // SYCL port: the per-layer residual ladder (token 0)dbgR_ = (float*) sycl::malloc_device((size_t) g.n_layers * g.n_embd * 4, dpct::get_in_order_queue());dbgM_ = (float*) sycl::malloc_device((size_t) g.n_layers * g.n_embd * 4, dpct::get_in_order_queue());}- std::fprintf(stderr, "strata verify: window up to %d tokens, %.1f MiB of device buffers\n", max_t,- (double) count.used / 1048576.0);+ std::fprintf(stderr, "strata verify: window up to %d tokens, %.1f MiB of device buffers%s\n", max_t,+ (double) count.used / 1048576.0,+ all_resident_ ? " (100% VRAM resident: zero-doorbell graph)" : "");return true;}catch (sycl::exception const &exc) {@@ -575,7 +726,8 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {const int64_t TS = (s.idx_block - 1) * ID;const bool ple_on = ss.ple.ready() && ple_stage();auto Rt = [&](int t) { return R_ + (size_t) t * HC * N; };- const int G = (split_ && T >= 2) ? 2 : 1;+ const int G = (split_ && T >= 2 && !batch_rec_) ? 2 : 1; // a batch window is one group+ const bool self_commit = T == 1 && !batch_rec_ && !g_qfuse() && one_token_self_commit(); // see Verifier::commitstatic const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }();// SYCL port, STRATA_VERIFY_EAGER=1: the window runs on the queue instead of as a graph, and each stage stamp is// a host-side wait + clock (there is no %globaltimer here), so the existing stage profiler reports ms per stage.@@ -587,7 +739,17 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {else gpu_stamp(prof_, (int) (l * kProfPer + i), cs);};const int tb_[2] = {0, (T + 1) / 2}, te_[2] = {G == 2 ? (T + 1) / 2 : T, T};- groups_[T] = G;+ // S26 STRATA_LFUSE=1: where the shared expert's gate / scale fusions apply (the paths they replace are the ones taken)+ auto lfuse_on = [&](int n) {+ return g_lfuse() && ar_on() && native_moe_combine_enabled() && dec_batch && n > 1 && n <= 8 &&+ shared_expert_native_bf16_enabled();+ };+ bool sg_gated_[2] = {false, false}; // per group: the combine applies the shared gate+ if (!batch_rec_) groups_[T] = G;+ const int64_t nQall = g.n_qsa_layers();+ // a batch window: row t is slot t, whose state lives in its own session+ auto slot_ss = [&](int t) -> SessionState& { return batch_rec_ ? *slots_[(size_t) brow_[t]] : ss; };+ const int hrow0 = batch_rec_ ? row_base_ : 0; // a slot group's own hand-off rows// ---- the window's inputs, from mapped stagingcopy_i32_from_mapped(tok_, m_tok_, T, cs);@@ -596,17 +758,15 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {// per-ROW positions of the K rows [t][NKV] and the indexer query rows [t][IQ] (for batched RoPE)const int32_t* pos_k = pos_ + MT * NH;const int32_t* pos_i = pos_ + MT * (NH + NKV);- if (ple_on) copy_from_mapped(ple_, m_ple_, (int64_t) T * N, cs);// ---- the embeddings, broadcast to the hc streams - or, in a later stage of a layer split, the previous stage's// residual, pending write and inject (see set_stage)const int64_t HB = Verifier::handoff_floats(g);if (lb_ > 0) {- for (int t = 0; t < T; ++t) {- copy_from_mapped(Rt(t), hand_in_ + (size_t) t * HB, HC * N, cs);- copy_from_mapped(bo_ + (size_t) t * N, hand_in_ + (size_t) t * HB + HC * N, N, cs);- copy_from_mapped(inj2_ + (size_t) t * HC, hand_in_ + (size_t) t * HB + HC * N + N, HC, cs);- }+ const float* hin = hand_in_ + (size_t) hrow0 * HB; // the group's rows: [R][bo][inj] contiguous+ copy_from_mapped(R_, hin, (int64_t) T * HC * N, cs);+ copy_from_mapped(bo_, hin + (size_t) T * HC * N, (int64_t) T * N, cs);+ copy_from_mapped(inj2_, hin + (size_t) T * (HC + 1) * N, (int64_t) T * HC, cs);} else if (const NativeEmbed* ne = native_embed()) { // plan v0.3 P6: the GGUF-form tablene->gather_dev(tok_, T, emb_, cs);broadcast_streams(emb_, R_, N, (int) HC, T, cs);@@ -654,20 +814,74 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {// already applied it)bool pending = l > 0 && !cvec().covers(l - 1);if (l == 1 && ple_on) {+ if (grp == 0) {+ if (ar_on()) wait_flag_ge(m_flag_, 1, cs);+ copy_from_mapped(ple_, m_ple_, (int64_t) T * N, cs);+ }float* normalized = (float*) ((uint8_t*) ss.ple.scratch + ple_block_scratch_bytes());+ static const bool ple_batch_env = [] {+ const char* e = std::getenv("STRATA_PLE_BATCH");+ return !e || e[0] != '0';+ }();+ const bool ple_batch_kv = ple_batch_env && dec_batch && n > 1 && ss.ple.w.key_bf16 != nullptr &&+ ss.ple.w.value_bf16 != nullptr && ple_native_bf16_enabled() &&+ ple_native_postops_enabled();+ // S25 (STRATA_PLE_BATCH=1): the key and value projections depend only on each row's n-gram embedding, so+ // the group's rows run through the multi-row forms of the same kernels (the weights read once); every+ // row's arithmetic is the single-row call's. The history-dependent rest stays row by row.+ static const bool ple_batch = [] { const char* e = std::getenv("STRATA_PLE_BATCH"); return e && e[0] == '1'; }();+ PleWeights pw = ss.ple.w;+ const bool nkey = pw.key_native_data != nullptr && pw.key_bf16 == nullptr;+ const bool batched = !ple_batch_kv && ple_batch && n > 1 && (pw.key_bf16 != nullptr || nkey) && ple_native_bf16_enabled();+ if (ple_batch_kv) {+ try {+ bf16_gemv_fp32_mmvf_multi(ple_ + (size_t) tb * N, N, ss.ple.w.key_bf16,+ xn_ + (size_t) tb * HC * N, HC * N, N, HC * N, n, cs);+ bf16_gemv_fp32_mmvf_multi(ple_ + (size_t) tb * N, N, ss.ple.w.value_bf16,+ z_ + (size_t) tb * N, N, N, N, n, cs);+ } catch (const std::exception& e) {+ err = std::string("verify PLE multi: ") + e.what();+ return false;+ }+ } else if (batched) {+ try {+ if (pw.key_bf16 != nullptr)+ bf16_gemv_fp32_mmvf_multi(ple_ + tb * N, N, pw.key_bf16, ple_key_ + (size_t) tb * NG_HC_DIM,+ NG_HC_DIM, N, NG_HC_DIM, n, cs);+ else {+ native_quantize_q8_1(ple_ + tb * N, xq_, (int) N, n, cs);+ native_mmvq(pw.key_native_type, pw.key_native_data, xq_, ple_key_ + (size_t) tb * NG_HC_DIM,+ (int) N, NG_HC_DIM, n, cs);+ }+ bf16_gemv_fp32_mmvf_multi(ple_ + tb * N, N, pw.value_bf16, ple_val_ + tb * N, N, N, N, n, cs);+ } catch (const std::exception& e) {+ err = std::string("verify PLE batch: ") + e.what();+ return false;+ }+ }+ // #783 PR-g (stuchapin909): the window's residual writes in one launch (STRATA_NO_MULTI_GR=1: per token)+ const bool multi_write = dec_batch && !g_no_multi_gr && n > 1;+ if (multi_write) gr_write_multi(Rt(tb), bo_ + tb * N, inj2_ + tb * HC, gs, Rt(tb), n, cs);for (int t = tb; t < te; ++t) {- gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs);+ if (batched) { pw.pre_key = ple_key_ + (size_t) t * NG_HC_DIM; pw.pre_value = ple_val_ + t * N; }+ if (!multi_write) gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs);PleOut po;po.normalized = normalized;po.result = Rt(t);+ float* hist = batch_rec_ ? slot_ss(t).ple_hist : ss.ple.hist; // the row's own historytry {- ple_block(ple_ + t * N, Rt(t), ss.ple.hist, ss.ple.w, po, ss.ple.scratch, cs);- ple_history_advance(ss.ple.hist, normalized, cs);+ if (ple_batch_kv) {+ ple_block_projected(xn_ + (size_t) t * HC * N, z_ + (size_t) t * N, Rt(t), hist,+ ss.ple.w, po, ss.ple.scratch, cs);+ } else {+ ple_block(ple_ + t * N, Rt(t), hist, pw, po, ss.ple.scratch, cs);+ }+ ple_history_advance(hist, normalized, cs);} catch (const std::exception& e) {err = std::string("verify PLE: ") + e.what();return false;}- copy_from_mapped(hist_snap_ + (size_t) t * HS, ss.ple.hist, HS, cs);+ copy_from_mapped(hist_snap_ + (size_t) t * HS, hist, HS, cs);}pending = false;}@@ -679,13 +893,20 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {a.bo_prev = bo_ + t * N; a.inj_prev = inj_prev + t * HC;a.w_norm = (const float*) wn[half]->data; a.w_down = (const uint16_t*) wd[half]->data;a.w_up = (const uint16_t*) wu[half]->data; a.w_inject = (const uint16_t*) wi[half]->data;+ a.q8_down = (const uint8_t*) wd[half]->hc_q8; a.q8_up = (const uint8_t*) wu[half]->hc_q8;+ a.q8_inject = (const uint8_t*) wi[half]->hc_q8;a.eps = EPS; a.lo = lo_ + t * g.hc_lr; a.rs = rs_ + t * HC;a.inject_out = inj_out + t * HC; a.mixed = mixed_ + t * N;+ if (qcnt_ != nullptr) { // S26 STRATA_QFUSE: the consumer's q8_1 image written by the read itself+ a.q8_cnt = qcnt_;+ if (half == 0) a.q8_mixed = xq_ + (size_t) (t - tb) * (N / 32) * 36;+ else if (strata::kernels::cpu::expert_layout().native) a.q8_mixed = nat_xq_ + (size_t) t * (N / 32) * 36;+ }}- fused_gr_read_multi(fa, n, xn_ + (size_t) tb * HC * N, cs, (prof_on_ && grp == 0) ? prof_ : nullptr,+ return fused_gr_read_multi(fa, n, xn_ + (size_t) tb * HC * N, cs, (prof_on_ && grp == 0) ? prof_ : nullptr,(int) (l * kProfPer + (half == 0 ? 27 : 30)));};- gr_read_group(0, pending, inj2_, inj_);+ const bool q8_attn = gr_read_group(0, pending, inj2_, inj_); // true: xq_ holds mixed's q8_1 (STRATA_QFUSE)stamp(l, 1, grp);float* xm = mixed_ + tb * N;try {@@ -707,10 +928,23 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {float* hb = h_L_ + (size_t) gi * MT * C;float* gate = gate_L_ + (size_t) gi * MT * HV;float* beta = beta_L_ + (size_t) gi * MT * HV;- native_quantize_q8_1(xm, xq_, (int) N, n, cs);+ if (!q8_attn) native_quantize_q8_1(xm, xq_, (int) N, n, cs);native_mmvq(wqkv->native_type, wqkv->native_data, xq_, qkv + (size_t) tb * C, (int) N, (int) C, n, cs);stamp(l, 2, grp);- gdn_conv_l2_multi(conv, qkv, (const float*) wc->data, hb, (int) C, (int) (2 * HK), EPS, n, cs, tb);+ if (batch_rec_) { // contiguous rows may be proposals for the same slot+ for (int t = tb; t < te;) {+ const int first = t;+ while (t < te && brow_[t] == brow_[first]) ++t;+ SessionState& sx = slot_ss(first);+ const float* cx = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats ++ (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;+ gdn_conv_l2_multi(cx, qkv + (size_t) first * C, (const float*) wc->data,+ hb + (size_t) first * C, (int) C, (int) (2 * HK), EPS, t - first, cs, 0);+ }+ } else+ // a one-token window keeps its token: it advances the conv history and the state itself (commit)+ gdn_conv_l2_multi(conv, qkv, (const float*) wc->data, hb, (int) C, (int) (2 * HK), EPS, n, cs, tb,+ self_commit);stamp(l, 3, grp);gdn_ab_multi(xm, (const uint16_t*) wa->data, (const uint16_t*) wb->data, (const float*) wdt->data,(const float*) wsa->data, gate + (size_t) tb * HV, beta + (size_t) tb * HV, (int) N, (int) HV,@@ -719,10 +953,22 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {native_mmvq(wg->native_type, wg->native_data, xq_, z_ + (size_t) tb * ZV, (int) N, (int) ZV, n, cs);stamp(l, 5, grp);// the recurrence from the untouched state over tokens [0, te); outputs only for this group's+ if (batch_rec_) { // each slot's recurrence over its own proposed-token group+ for (int t = tb; t < te;) {+ const int first = t;+ while (t < te && brow_[t] == brow_[first]) ++t;+ SessionState& sx = slot_ss(first);+ float* stx = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats;+ gdn_step_norm_multi(stx, hb + (size_t) first * C, (int) C, gate + (size_t) first * HV,+ beta + (size_t) first * HV, z_ + (size_t) first * ZV,+ (const float*) wnm->data, EPS, y_ + (size_t) first * ZV,+ (int) HK, (int) HV, t - first, nullptr, cs, 0);+ }+ } elsegdn_step_norm_multi(state, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, y_, (int) HK,- (int) HV, te, nullptr, cs, tb);+ (int) HV, te, self_commit ? one_ : nullptr, cs, tb, g_qfuse() ? (void*) xq_ : nullptr);stamp(l, 6, grp);- native_quantize_q8_1(y_ + (size_t) tb * ZV, xq_, (int) ZV, n, cs);+ if (!g_qfuse()) native_quantize_q8_1(y_ + (size_t) tb * ZV, xq_, (int) ZV, n, cs); // STRATA_QFUSE: done abovenative_mmvq(wout->native_type, wout->native_data, xq_, bo_ + tb * N, (int) ZV, (int) N, n, cs);} else {// ======================= QSA =======================@@ -737,7 +983,15 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {if (!native_of(wq, v.name("attn_q.weight"), err) || !native_of(wk, v.name("attn_k.weight"), err) ||!native_of(wv, v.name("attn_v.weight"), err) || !native_of(wo, v.name("attn_output.weight"), err))return false;+ // #783 PR-f (stuchapin909): the per-head RMSNorm and the rope in one launch, bit-identical to the pair+ // (rope_parity check 6); STRATA_NO_NORM_ROPE=1 keeps the two; off on HIP until its parity check passes+ const bool fuse_nr = native_qsa_enabled() && native_rope_enabled() && native_norm_rope_usable((int) HD, (int) s.n_rot);auto norm_rope = [&](float* data, const WeightRef* norm, int rows, int cols, const int32_t* pos) {+ if (fuse_nr && native_norm_rope_usable(cols, (int) s.n_rot)) {+ native_qsa_rms_norm_rope(data, cols, (const float*) norm->data, data, rows, cols, (int) s.n_rot, EPS,+ rope_scaling(), pos, cs);+ return;+ }if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, EPS, cs);else rms_norm_weighted(data, (const float*) norm->data, rows, cols, EPS, cs);if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), pos, cs);@@ -747,7 +1001,7 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {// the per-token GEMVs / norms / RoPEs / copies of this layer as one launch over the// window's rows each - row-wise identical arithmetic (STRATA_DEC_BATCH=0: token by token)const bool qb = dec_batch && n > 1 && native_qsa_enabled() && native_rope_enabled() && !st.kv_q4;- native_quantize_q8_1(xm, xq_, (int) N, n, cs);+ if (!q8_attn) native_quantize_q8_1(xm, xq_, (int) N, n, cs);if (qb) bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wik->data, idx_raw + tb * ID, ID, N, ID, n, cs);else for (int t = tb; t < te; ++t)bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wik->data, idx_raw + t * ID, (int) N, (int) ID, cs);@@ -763,14 +1017,45 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);}stamp(l, 8, grp);+ if (batch_rec_) { // snapshot each slot's indexer tail before its first proposed row+ for (int t = tb; t < te; ++t)+ if (t == tb || brow_[t] != brow_[t - 1])+ copy_from_mapped(tail_snap_b_ + ((size_t) brow_[t] * nQall + qi) * TS,+ slot_ss(t).qsa_states[qi].idx_tail, TS, cs);+ } elseif (grp == 0) copy_from_mapped(tail_snap_ + (size_t) qi * TS, st.idx_tail, TS, cs);+ // #783 PR-d (stuchapin909): the window's K/V cells in one launch per pool instead of one per token (a+ // batch's rows each have their own K/V, so that case keeps the loop)+ if (dec_batch && !g_no_batch_kv && !batch_rec_) {+ const int32_t* step_b = step_ + tb * kStepCount;+ const float* kc_b = kcur_ + tb * NKV * HD;+ const float* vc_b = vcur_ + tb * NKV * HD;+ if (st.kv_hybrid) { // K8V4: the unused half's lanes folded onto the used pool (layer.cpp)+ kv_append_q8_steps(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, step_b, kStepCount,+ kc_b, kc_b, (int) (NKV * HD), n, s, cs, nullptr);+ kv_append_q4_steps(st.v_q4, st.v_q4, st.page_table, step_b, kStepCount, n, vc_b, vc_b, s, cs,+ nullptr);+ } else if (st.kv_q4)+ kv_append_q4_steps(st.k_q4, st.v_q4, st.page_table, step_b, kStepCount, n, kc_b, vc_b, s, cs,+ &st.host);+ else if (st.kv_int8)+ kv_append_q8_steps(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, step_b, kStepCount,+ kc_b, vc_b, (int) (NKV * HD), n, s, cs, &st.host);+ else+ for (int t = tb; t < te; ++t)+ kv_append_step(st.k_pool, st.v_pool, st.page_table, step_ + t * kStepCount,+ kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st.host);+ } elsefor (int t = tb; t < te; ++t) {+ const QsaState& st = slot_ss(t).qsa_states[qi]; // the row's own K/V (ss's outside a batch)const int32_t* step_t = step_ + t * kStepCount;if (st.kv_hybrid) { // K8V4: the unused half's lanes folded onto the used pool (layer.cpp)+ const KvHostPools hk = kv_hybrid_k_half(st.host), hv = kv_hybrid_v_half(st.host);+ const bool mirror = st.host.present(); // streamed: the host copy tookv_append_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, step_t,- kcur_ + t * NKV * HD, kcur_ + t * NKV * HD, s, cs, nullptr);+ kcur_ + t * NKV * HD, kcur_ + t * NKV * HD, s, cs, mirror ? &hk : nullptr);kv_append_q4_step(st.v_q4, st.v_q4, st.page_table, step_t, vcur_ + t * NKV * HD,- vcur_ + t * NKV * HD, s, cs, nullptr);+ vcur_ + t * NKV * HD, s, cs, mirror ? &hv : nullptr);} else if (st.kv_q4)kv_append_q4_step(st.k_q4, st.v_q4, st.page_table, step_t, kcur_ + t * NKV * HD,vcur_ + t * NKV * HD, s, cs, &st.host);@@ -781,15 +1066,29 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {kv_append_step(st.k_pool, st.v_pool, st.page_table, step_t, kcur_ + t * NKV * HD,vcur_ + t * NKV * HD, s, cs, &st.host);}- const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};- for (int t = tb; t < te; ++t)- native_qsa_indexer_append(idx_raw + t * ID, step_ + t * kStepCount + kStepPos, 0,- (const float*) wikn->data, EPS, ib, s, st.max_cells,- rope_scaling(), cs);+ if (dec_batch && !g_no_batch_kv && !batch_rec_) {+ const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};+ native_qsa_indexer_append_steps(idx_raw + tb * ID, step_ + tb * kStepCount + kStepPos, kStepCount,+ n, 0, (const float*) wikn->data, EPS, ib, s, st.max_cells,+ rope_scaling(), cs);+ } else {+ for (int t = tb; t < te; ++t) {+ const QsaState& sx = slot_ss(t).qsa_states[qi];+ const QsaIndexerBuffers ib{sx.idx_tail, sx.idx_dead, sx.idx_pooled, sx.idx_block_pos};+ native_qsa_indexer_append(idx_raw + t * ID, step_ + t * kStepCount + kStepPos, 0,+ (const float*) wikn->data, EPS, ib, s, sx.max_cells,+ rope_scaling(), cs);+ }+ }stamp(l, 9, grp);native_mmvq(wq->native_type, wq->native_data, xq_, qfull_ + tb * NH * 2 * HD, (int) N, (int) (NH * 2 * HD),n, cs);if (qb) {+ if (fuse_nr) { // the q/gate split reads q straight out of the q|gate rows (stride 2 * HD)+ native_qsa_rms_norm_rope(qfull_ + tb * NH * 2 * HD, (int) (2 * HD), (const float*) wqn->data,+ qcur_ + tb * NH * HD, (int) (n * NH), (int) HD, (int) s.n_rot, EPS,+ rope_scaling(), pos_ + tb * NH, cs);+ } else {/*DPCT1124: cudaMemcpy2DAsync is migrated to asynchronousmemcpy API. While the origin API might be synchronous, it@@ -806,6 +1105,7 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {return false;}norm_rope(qcur_ + tb * NH * HD, wqn, (int) (n * NH), (int) HD, pos_ + tb * NH);+ }if (st.kv_rot) fwht256_inplace_cuda(qcur_ + tb * NH * HD, (int64_t) n * NH, cs); // <Hq, Hk> = <q, k>bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wiq->data, qidx_ + tb * IQ * ID, IQ * ID,N, IQ * ID, n, cs);@@ -813,6 +1113,10 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {} else {for (int t = tb; t < te; ++t) {float* qc = qcur_ + t * NH * HD;+ if (fuse_nr) {+ native_qsa_rms_norm_rope(qfull_ + t * NH * 2 * HD, (int) (2 * HD), (const float*) wqn->data, qc,+ (int) NH, (int) HD, (int) s.n_rot, EPS, rope_scaling(), pos_ + t * NH, cs);+ } else {/*DPCT1124: cudaMemcpy2DAsync is migrated to asynchronousmemcpy API. While the origin API might be synchronous, it@@ -828,6 +1132,7 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {return false;}norm_rope(qc, wqn, (int) NH, (int) HD, pos_ + t * NH);+ }if (st.kv_rot) fwht256_inplace_cuda(qc, NH, cs); // <Hq, Hk> = <q, k>}for (int t = tb; t < te; ++t) {@@ -837,6 +1142,20 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {}}stamp(l, 10, grp);+ if (batch_rec_) { // each row selects and attends over its own slot's K/V+ for (int t = tb; t < te; ++t) {+ const QsaState& sx = slot_ss(t).qsa_states[qi];+ qsa_block_scores(sx.idx_pooled, sx.idx_dead, qidx_ + t * IQ * ID, step_ + t * kStepCount, 1,+ max_blocks_, s, scores_ + (size_t) t * max_blocks_, cs);+ qsa_block_topk(scores_ + (size_t) t * max_blocks_, step_ + t * kStepCount, 1, max_blocks_, cap_, s,+ sel_ + (size_t) t * cap_, cs);+ qsa_kv_resolve(sx, *g_, sel_ + (size_t) t * cap_, step_ + t * kStepCount, 1, cap_, cs);+ const QsaAttnPools px = qsa_attn_pools(sx);+ qsa_decode_attn_batch(qcur_ + t * NH * HD, px, sel_ + (size_t) t * cap_, step_ + t * kStepCount,+ cap_, s, attn_scratch_ + (size_t) t * attn_scratch_floats_,+ attn_ + t * NH * HD, 1, cs);+ }+ } else {qsa_block_scores(st.idx_pooled, st.idx_dead, qidx_ + tb * IQ * ID, step_ + tb * kStepCount, n, max_blocks_,s, scores_ + (size_t) tb * max_blocks_, cs);qsa_block_topk(scores_ + (size_t) tb * max_blocks_, step_ + tb * kStepCount, n, max_blocks_, cap_, s,@@ -848,6 +1167,7 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {const QsaAttnPools pools = qsa_attn_pools(st);qsa_decode_attn_batch(qcur_ + tb * NH * HD, pools, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, cap_,s, attn_scratch_ + (size_t) tb * attn_scratch_floats_, attn_ + tb * NH * HD, n, cs);+ }stamp(l, 13, grp);if (st.kv_rot || st.kv_hybrid) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = Hif (qb) native_qsa_gate_apply(attn_ + tb * NH * HD, qfull_ + tb * NH * 2 * HD, attn32_ + tb * NH * HD,@@ -869,36 +1189,88 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {return false;}stamp(l, 16, grp);- gr_read_group(1, true, inj_, inj2_);+ const bool q8_ffn = gr_read_group(1, true, inj_, inj2_); // true: nat_xq_ holds the MoE input's q8_1 (STRATA_QFUSE)+ // with CPU experts in the window the shared expert forks off once the doorbell is published (it no longer+ // competes with it for the GPU's first microseconds); STRATA_SH_FORK_LATE=0 forks at the top as before+ static const bool sh_fork_late_env = [] {+ const char* e = std::getenv("STRATA_SH_FORK_LATE");+ return !e || e[0] != '0';+ }();+ const bool sh_fork = sh_stream_on() && !prof_on_ &&+ sh_cs_ != &dpct::get_in_order_queue() &&+ ev_fork_ != nullptr && ev_join_ != nullptr;+ const bool sh_fork_late = sh_fork && sh_fork_late_env && !ar_on();+ dpct::queue_ptr sh_stream = sh_fork ? sh_cs_ : cs;+ if (sh_fork && !sh_fork_late) {+ dpct::sync_barrier(ev_fork_, cs);+ (sh_cs_)->ext_oneapi_submit_barrier({*ev_fork_});+ }// the window's rows routed in 2 launches (one router GEMV reading the weight once, one// top-10) instead of 2 per token; every row's arithmetic is the single-token call's (STRATA_DEC_BATCH=0: old)const WeightRef* w_router = v.get("ffn_gate_inp.weight");+ // S26 STRATA_LFUSE=1: the shared expert's gate row rides in the router GEMV launch, its sigmoid + row scale+ // move into the combine, gate + up share one launch (all bitwise; resident combine path, 2-8 rows only)+ const WeightRef* w_sgi = lfuse_on(n) && g_lfuse_gate() ? v.get("ffn_gate_inp_shexp.weight") : nullptr;+ bool sg_ready = false;if (dec_batch && n > 1 && w_router != nullptr && native_router_enabled() && (NE == 512 || NE == 256) && K == 10) {try { // SYCL port: the fused multi-token router for 256 experts as well (it was 512-only)+ if (w_sgi != nullptr)+ sg_ready = bf16_gemv_fp32_mmvf_multi_aux(mixed_ + tb * N, N, (const uint16_t*) w_router->data,+ logits_ + tb * NE, NE, N, NE, n,+ (const uint16_t*) w_sgi->data, sh_g_ + tb, 1, cs);+ if (!sg_ready)bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) w_router->data, logits_ + tb * NE, NE, N,NE, n, cs);native_router_top10_multi_ne(logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, n, (int) NE, cs);} catch (const std::exception& e) { err = "verify router: " + std::string(e.what()); return false; }+#if defined(STRATA_HIP_GFX906)+ } else if (dec_batch) {+ // gfx906: the Coder's 256-expert router (the native router is 512 x 10 only) for the whole window in one+ // multi-column BF16 projection and one top-k, bitwise the per-token calls (route_window_parity); ~3 ms+ // of a ~55 ms verify window on 2x MI50. STRATA_ROUTE_PER_TOKEN=1: the per-token calls.+ if (!moe_route_window(wt, g, l, K, ss.moe, mixed_ + tb * N, logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, n,+ cs, err))+ return false;+#endif} elsefor (int t = tb; t < te; ++t) {MoEBuffers mb = ss.moe;mb.logits = logits_ + t * NE; mb.ids = ids_ + t * K; mb.weights = w_ + t * K;if (!moe_route(wt, g, l, K, mb, mixed_ + t * N, cs, err, nullptr)) return false;}- if (device_plan_) // E-6: every routed expert resident: this group's plan without the host+ if (ar_on()) {resident_plan(ids_ + tb * K, n * (int) K, (int) K, hits_.d_res + l * g.n_expert, (int) g.n_expert,hits_.cache_base, slot_off_d_, (long long) hits_.blob,- plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, skip_ + grp,- (uint32_t) ((l - lb_) * G + grp + 1), cs);+ plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, nullptr, 0, cs, m_plan_err_);+ } else {+ if (device_plan_) // E-6: every routed expert resident: this group's plan without the host+ resident_plan(ids_ + tb * K, n * (int) K, (int) K, hits_.d_res + l * g.n_expert, (int) g.n_expert,+ hits_.cache_base, slot_off_d_, (long long) hits_.blob,+ plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, skip_ + grp,+ (uint32_t) ((l - lb_) * G + grp + 1), cs);#if defined(STRATA_USE_HIP)- if (g_doorbell_store) // #649 A/B: the step's ring stored, not incremented over PCIe- doorbell_publish_value(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N,- m_ids_ + tb * K, m_w_ + tb * K, m_seq_, (uint32_t) ((l - lb_) * G + grp + 1), cs);- else+ if (g_doorbell_store) // #649 A/B: the step's ring stored, not incremented over PCIe+ doorbell_publish_value(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N,+ m_ids_ + tb * K, m_w_ + tb * K, m_seq_, (uint32_t) ((l - lb_) * G + grp + 1), cs);+ else#endif- doorbell_publish(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N,- m_ids_ + tb * K, m_w_ + tb * K, m_seq_, cs);+ // #578: the helper GPUs reduce with the routing weights - publish them; set_always_publish: the rows+ // whatever the device's residency table says (pipelined windows)+ if (remote_opt_ || always_publish_)+ doorbell_publish(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N,+ m_ids_ + tb * K, m_w_ + tb * K, m_seq_, cs);+ else {+ const int32_t* layer_res = hits_.d_res != nullptr ? (hits_.d_res + l * g.n_expert) : nullptr;+ doorbell_publish_res(xm, ids_ + tb * K, layer_res, (int) g.n_expert, (int64_t) n * N, (int64_t) n * K,+ m_x_ + tb * N, m_ids_ + tb * K, m_seq_, cs);+ }+ if (sh_fork_late) {+ dpct::sync_barrier(ev_fork_, cs);+ (sh_cs_)->ext_oneapi_submit_barrier({*ev_fork_});+ }+ }stamp(l, 17, grp);+ bool qdedup = false; // STRATA_VERIFY_QDEDUP took effect: the experts' q8_1 image of xm is already made{const WeightRef *wgi = need(v, "ffn_gate_inp_shexp.weight", err), *wsg = need(v, "ffn_gate_shexp.weight", err),*wsu = need(v, "ffn_up_shexp.weight", err), *wsd = need(v, "ffn_down_shexp.weight", err);@@ -910,39 +1282,49 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {nsw.gate_type = wsg->native_type; nsw.gate_data = wsg->native_data;nsw.up_type = wsu->native_type; nsw.up_data = wsu->native_data;nsw.down_type = wsd->native_type; nsw.down_data = wsd->native_data;- nsw.q8_1 = xq_;- if (dec_batch) f32_to_bf16_bulk(mixed_ + tb * N, sh_bf16_ + tb * N, (int64_t) n * N, cs); // contiguous rows- else for (int t = tb; t < te; ++t) f32_to_bf16_bulk(mixed_ + t * N, sh_bf16_ + t * N, N, cs);+ nsw.q8_1 = sh_fork ? sh_xq_ : xq_;+ // STRATA_VERIFY_QDEDUP=1 (not with the forked shared-expert stream, which quantizes into its own buffer): the+ // experts' q8_1 image of xm is made first and the shared expert's gate/up read it (quantize_q8_1_rows and+ // native_quantize_q8_1 write the same bytes)+ qdedup = g_qdedup() && !sh_fork && strata::kernels::cpu::expert_layout().native;+ if (qdedup && !q8_ffn) quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs);+ if (!shared_expert_native_bf16_enabled()) {+ if (dec_batch) f32_to_bf16_bulk(mixed_ + tb * N, sh_bf16_ + tb * N, (int64_t) n * N, sh_stream); // contiguous rows+ else for (int t = tb; t < te; ++t) f32_to_bf16_bulk(mixed_ + t * N, sh_bf16_ + t * N, N, sh_stream);+ }try {shared_expert_multi(n, xm, sh_bf16_ + tb * N, nsw, (const uint16_t*) wgi->data, sh_gate_ + (size_t) tb * g.n_ff,- sh_up_ + (size_t) tb * g.n_ff, sh_g_ + tb, shared_ + tb * N, N, g.n_ff, cs);+ sh_up_ + (size_t) tb * g.n_ff, sh_g_ + tb, shared_ + tb * N, N, g.n_ff, sh_stream,+ qdedup ? (const void*) (nat_xq_ + (size_t) tb * (N / 32) * 36) : nullptr,+ (sg_ready ? 1 : 0) | (lfuse_on(n) && g_lfuse_pair() ? 2 : 0));+ sg_gated_[grp] = sg_ready;} catch (const std::exception& e) {err = std::string("verify shared expert: ") + e.what();return false;}+ if (sh_fork) dpct::sync_barrier(ev_join_, sh_cs_);}- if (strata::kernels::cpu::expert_layout().native)- quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs);- else+ if (strata::kernels::cpu::expert_layout().native) {+ if (!qdedup)+ if (!q8_ffn) quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs);+ } elsequantize_q8_0_scaled(xm, hit_xq_ + (size_t) tb * (N / 32) * 34, hit_xs_ + (size_t) tb * (N / 32), (int64_t) n * N, cs);stamp(l, 18, grp);return true;};// ---------------------------------------------------------------- post(l, group): experts, combine+ static const bool fuse_head_gr_env = [] {+ const char* e = std::getenv("STRATA_FUSE_HEAD_GR");+ return e && e[0] == '1';+ }();+ const bool fuse_head_gr = fuse_head_gr_env && (le_ == g.n_layers) && (head_ != nullptr && head_->loaded()) &&+ !cvec().covers(g.n_layers - 1);auto post = [&](int64_t l, int grp) -> bool {const int tb = tb_[grp], te = te_[grp], n = te - tb;const uint32_t ring = (uint32_t) ((l - lb_) * G + grp + 1);const int64_t cap = (int64_t) n * K, capx = (int64_t) max_t_ * K;int32_t* pl = plan_ + (size_t) grp * (size_t) (plan_i32_ + 16);- if (device_plan_) { // E-6: skipped when the device planned this group (all its experts resident)- wait_flag_ge_or(m_flagA_, ring, skip_ + grp, cs);- copy_i32_from_mapped_unless(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, skip_ + grp, ring, cs);- } else {- wait_flag_ge(m_flagA_, ring, cs); // the pool published this group's GPU plan- copy_i32_from_mapped(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, cs);- }- stamp(l, 19, grp);const int32_t* p_counts = pl;const int32_t* p_start = pl + 4;const int32_t* p_dst = p_start + capx + 1;@@ -952,50 +1334,79 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {const unsigned long long* p_ptr2 = p_ptr + capx;const int32_t* p_start2 = pl + ptr_off + 4 * capx;float* hit_out = hit_out_ + (size_t) tb * K * N;+ float* parts_out = parts_ + (size_t) tb * K * N;const auto& lay = strata::kernels::cpu::expert_layout();// plan v0.3 P6: the VRAM groups now; the PCIe groups once the copy engine has landed them in staging.// `gy`: the native launch's groups side by side (0: cap, one block row per possible group).- auto grouped = [&](const unsigned long long* gp, const int32_t* gs, const int32_t* gn, int64_t gy) {+ auto grouped = [&](const unsigned long long* gp, const int32_t* gs, const int32_t* gn, int64_t gy, float* dst_buf) {if (lay.native) {// the layer's GGUF formats (i-quant gate/up, Q2_0 / IQ4_NL down)const auto& f = lay.fmt[(size_t) l];const NativeExpertLayout L = native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff);native_expert_grouped(L, gp, gs, gn, p_dst, p_tok, cap, cap,- nat_xq_ + (size_t) tb * (N / 32) * 36, hit_scratch_, hit_out, cs, gy);+ nat_xq_ + (size_t) tb * (N / 32) * 36, hit_scratch_, dst_buf, cs, gy);} else {moe_grouped_s2(gp, gs, gn, p_dst, p_tok, cap, cap, hit_xq_ + (size_t) tb * (N / 32) * 34,- hit_xs_ + (size_t) tb * (N / 32), hit_scratch_, hit_out, cs);+ hit_xs_ + (size_t) tb * (N / 32), hit_scratch_, dst_buf, cs);}};- grouped(p_ptr, p_start, p_counts, 0);- stamp(l, 20, grp);- if (device_plan_) wait_flag_ge_or(m_flagB_, ring, skip_ + grp, cs);- else wait_flag_ge(m_flagB_, ring, cs); // the PCIe share is in staging (DMA) or mapped- if (sink_.pcie_mode == 2) { // stage it with a copy kernel, then point at staging- const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs;- uint8_t* stage = staging_ + (size_t) (grp * per) * lay.max_blob;- fetch_blobs(p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), (int) per, cs);- rebase_ptrs((unsigned long long*) p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), cs);- }- stamp(l, 21, grp);- // the PCIe share is pcie_frac of the misses: a few groups when the cache is cold, usually none (always none at- // pcie_frac 0), so its launch is kPcieGroupRows block rows striding over the groups, not cap of them- grouped(p_ptr2, p_start2, p_counts + 2, kPcieGroupRows);- stamp(l, 22, grp);- if (device_plan_) { // no CPU share when the device planned the group: its rows are zeros- wait_flag_ge_or(m_flag_, ring, skip_ + grp, cs);- copy_or_zero_from_mapped(parts_ + (size_t) tb * K * N, m_ymiss_ + (size_t) tb * K * N, (long long) n * K * N,- skip_ + grp, ring, cs);+ if (ar_on()) {+ stamp(l, 19, grp);+ grouped(p_ptr, p_start, p_counts, 0, parts_out);+ stamp(l, 20, grp);} else {- wait_flag_ge(m_flag_, ring, cs); // the CPU's share is in the mapped rows- stamp(l, 23, grp);- if (dec_batch) // only the CPU rows cross PCIe (p_dst[0, counts[1]) = the GPU's own rows)- copy_rows_from_mapped(parts_ + (size_t) tb * K * N, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K, N,- p_dst, p_counts + 1, cs);- else- copy_from_mapped(parts_ + (size_t) tb * K * N, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K * N, cs);+ if (device_plan_) { // E-6: skipped when the device planned this group (all its experts resident)+ wait_flag_ge_or(m_flagA_, ring, skip_ + grp, cs);+ copy_i32_from_mapped_unless(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, skip_ + grp, ring, cs);+ } else {+ wait_flag_ge(m_flagA_, ring, cs); // the pool published this group's GPU plan+ copy_i32_from_mapped(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, cs);+ }+ stamp(l, 19, grp);+ grouped(p_ptr, p_start, p_counts, 0, hit_out);+ stamp(l, 20, grp);+ if (device_plan_) wait_flag_ge_or(m_flagB_, ring, skip_ + grp, cs);+ else wait_flag_ge(m_flagB_, ring, cs); // the PCIe share is in staging (DMA) or mapped+ if (sink_.pcie_mode == 2) { // stage it with a copy kernel, then point at staging+ const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs;+ uint8_t* stage = staging_ + (size_t) (grp * per) * lay.max_blob;+ fetch_blobs(p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), (int) per, cs);+ rebase_ptrs((unsigned long long*) p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), cs);+ }+ stamp(l, 21, grp);+ // the PCIe share is pcie_frac of the misses: a few groups when the cache is cold, usually none (always none at+ // pcie_frac 0), so its launch is kPcieGroupRows block rows striding over the groups, not cap of them+ grouped(p_ptr2, p_start2, p_counts + 2, kPcieGroupRows, hit_out);+ stamp(l, 22, grp);+ if (device_plan_) { // no CPU share when the device planned the group: its rows are zeros+ wait_flag_ge_or(m_flag_, ring, skip_ + grp, cs);+ copy_or_zero_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (long long) n * K * N,+ skip_ + grp, ring, cs);+ } else {+ wait_flag_ge(m_flag_, ring, cs); // the CPU's share is in the mapped rows+ stamp(l, 23, grp);+ if (remote_opt_) // #578: the helper's rows come back reduced; skip them as well+ remote_opt_->copy_rows(parts_out, m_ymiss_ + (size_t) tb * K * N, tb, n, p_dst, p_counts + 1, cs);+ else if (dec_batch) // only the CPU rows cross PCIe (p_dst[0, counts[1]) = the GPU's own rows)+ copy_rows_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K, N,+ p_dst, p_counts + 1, cs);+ else+ copy_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K * N, cs);+ }+ moe_hit_add(parts_out, hit_out, p_dst, p_counts + 1, cap, N, cs);+ }+ // Same condition as `sh_fork` above, which is per group and out of scope here: wait only when the fork+ // actually ran (a wait on an event never recorded is a no-op, but saying it outright reads better).+ if (sh_stream_on() && !prof_on_ &&+ sh_cs_ != &dpct::get_in_order_queue() && ev_fork_ != nullptr &&+ ev_join_ != nullptr) {+ cs->ext_oneapi_submit_barrier({*ev_join_});}- moe_hit_add(parts_ + (size_t) tb * K * N, hit_out, p_dst, p_counts + 1, cap, N, cs);+ if (sg_gated_[grp]) { // STRATA_LFUSE: the shared expert's gate was not applied: the combine applies it (all rows are hits)+ try {+ native_moe_combine_multi_hits_gated(parts_out, w_ + tb * K, shared_ + tb * N, sh_g_ + tb, bo_ + tb * N, N, K, n, cs);+ } catch (const std::exception& e) { err = "verify combine: " + std::string(e.what()); return false; }+ } elseif (dec_batch && n > 1 && native_moe_combine_enabled()) { // one launch for the window's rowstry {native_moe_combine_multi(parts_ + (size_t) tb * K * N, w_ + tb * K, shared_ + tb * N, bo_ + tb * N, N, K, n, cs);@@ -1006,10 +1417,15 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {mb.weights = w_ + t * K; mb.shared = shared_ + t * N;if (!moe_combine_parts(g, l, K, mb, parts_ + (size_t) t * K * N, bo_ + t * N, cs, err)) return false;}+ if (remote_opt_) remote_opt_->combine(bo_ + tb * N, y_dummy_ + tb * N, tb, n,+ device_plan_ ? skip_ + grp : nullptr, ring, cs);stamp(l, 24, grp);if (l == g.n_layers - 1) {- for (int t = tb; t < te; ++t) gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs);- if (cvec().covers(l)) cvec_apply(Rt(tb), l, n, HC * N, nullptr, 0, nullptr, 0, false, cs);+ if (!fuse_head_gr) {+ if (dec_batch && !g_no_multi_gr) gr_write_multi(Rt(tb), bo_ + tb * N, inj2_ + tb * HC, gs, Rt(tb), n, cs);+ else for (int t = tb; t < te; ++t) gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs);+ if (cvec().covers(l)) cvec_apply(Rt(tb), l, n, HC * N, nullptr, 0, nullptr, 0, false, cs);+ }} else if (cvec().covers(l)) {cvec_apply(Rt(tb), l, n, HC * N, bo_ + tb * N, N, inj2_ + tb * HC, HC, true, cs);}@@ -1028,11 +1444,10 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {if (l + 1 < le_ && !pre(l + 1, grp)) return false;}if (le_ < g.n_layers) { // a layer split's earlier stage: hand the residual on, no head- for (int t = 0; t < T; ++t) {- copy_from_mapped(hand_out_ + (size_t) t * HB, Rt(t), HC * N, cs);- copy_from_mapped(hand_out_ + (size_t) t * HB + HC * N, bo_ + (size_t) t * N, N, cs);- copy_from_mapped(hand_out_ + (size_t) t * HB + HC * N + N, inj2_ + (size_t) t * HC, HC, cs);- }+ float* hout = hand_out_ + (size_t) hrow0 * HB;+ copy_from_mapped(hout, R_, (int64_t) T * HC * N, cs);+ copy_from_mapped(hout + (size_t) T * HC * N, bo_, (int64_t) T * N, cs);+ copy_from_mapped(hout + (size_t) T * (HC + 1) * N, inj2_, (int64_t) T * HC, cs);return true;}@@ -1042,15 +1457,65 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {const WeightRef *hn = wt.find("output_hc_norm.weight"), *hd = wt.find("output_hc_down.weight"),*hu = wt.find("output_hc_up.weight");if (!hn || !hd || !hu) { err = "verify: an output_hc_* weight is missing"; return false; }- for (int t = 0; t < T; ++t) {- BlockBuffers bb = ss.block;- bb.R = Rt(t);- bb.mixed = head_mixed_ + t * N;- if (head_ != nullptr && head_->loaded()) {- if (!lm_head_mix(wt, g, bb, cs, err)) return false;- } else if (!lm_head(wt, g, bb, head_logits_ + (size_t) t * n_vocab_, cs, err)) {+ // S25 (STRATA_HC_Q8=1): the final mixer from the GGUF's Q8_0 projections too, through the same multi read+ // (no pending write, no inject)+ const bool mix_q8 = hd->hc_q8 != nullptr && hu->hc_q8 != nullptr && head_ != nullptr && head_->loaded();+ if (mix_q8) {+ FusedGrArgs fa[kFusedGrMaxT];+ for (int t = 0; t < T; ++t) {+ FusedGrArgs& a = fa[t];+ a.R = Rt(t); a.R_out = Rt(t); a.apply = false;+ a.w_norm = (const float*) hn->data; a.w_down = (const uint16_t*) hd->data;+ a.w_up = (const uint16_t*) hu->data; a.w_inject = nullptr;+ a.q8_down = (const uint8_t*) hd->hc_q8; a.q8_up = (const uint8_t*) hu->hc_q8;+ a.eps = EPS; a.lo = lo_ + t * g.hc_lr; a.rs = rs_ + t * HC;+ a.mixed = head_mixed_ + t * N;+ }+ fused_gr_read_multi(fa, T, xn_, cs);+ }+ else if (fuse_head_gr) {+ FusedGrArgs fa[kFusedGrMaxT];+ for (int t = 0; t < T; ++t) {+ FusedGrArgs& a = fa[t];+ a.R = Rt(t); a.R_out = Rt(t); a.apply = true;+ a.bo_prev = bo_ + t * N; a.inj_prev = inj2_ + t * HC;+ a.w_norm = (const float*) hn->data;+ a.w_down = (const uint16_t*) hd->data;+ a.w_up = (const uint16_t*) hu->data;+ a.w_inject = nullptr;+ a.eps = EPS;+ a.lo = lo_ + t * g.hc_lr;+ a.rs = rs_ + t * HC;+ a.inject_out = head_inj_;+ a.mixed = head_mixed_ + t * N;+ }+ fused_gr_read_multi(fa, T, xn_, cs);+ } else if (head_mix_multi_enabled() && head_ != nullptr && head_->loaded()) {+ // the final mixer, the window's tokens in one read (fused_gr_read_multi without the pending write: the+ // last layer's write was done above; its sums are gr_read's)+ if (hn->kind != WeightKind::F32 || hd->kind != WeightKind::Bf16InF32 || hu->kind != WeightKind::Bf16InF32) {+ err = "verify: the output_hc_* weights have the wrong engine forms";return false;}+ FusedGrArgs fa[kFusedGrMaxT];+ for (int t = 0; t < T; ++t) {+ fa[t].R = Rt(t); fa[t].R_out = Rt(t); fa[t].apply = false;+ fa[t].w_norm = (const float*) hn->data; fa[t].w_down = (const uint16_t*) hd->data;+ fa[t].w_up = (const uint16_t*) hu->data; fa[t].eps = EPS;+ fa[t].lo = lo_ + t * g.hc_lr; fa[t].rs = rs_ + t * HC; fa[t].mixed = head_mixed_ + t * N;+ }+ fused_gr_read_multi(fa, T, xn_, cs);+ } else {+ for (int t = 0; t < T; ++t) {+ BlockBuffers bb = ss.block;+ bb.R = Rt(t);+ bb.mixed = head_mixed_ + t * N;+ if (head_ != nullptr && head_->loaded()) {+ if (!lm_head_mix(wt, g, bb, cs, err)) return false;+ } else if (!lm_head(wt, g, bb, head_logits_ + (size_t) t * n_vocab_, cs, err)) {+ return false;+ }+ }}if (head_ != nullptr && head_->loaded()) {try {@@ -1064,10 +1529,14 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {// Greedy, the default, is recorded here as before (no extra launch or sync per window). A request that// samples or penalizes is sampled again host-side after the replay (run()) with its own parameters and a// fresh draw counter: a captured sampler would bake them in and replay the same draws forever.- SamplerParams sp;- sp.greedy = true;- sp.temperature = 0.0f;- sample_tokens(head_logits_, T, (int) n_vocab_, nullptr, 0, sp, m_out_, cs);+ if (argmax_rows_wanted()) { // sm_80 to sm_89: the pick over many blocks a row (bitwise the one-block kernel's)+ argmax_rows(head_logits_, T, (int) n_vocab_, arg_scratch_, m_out_, cs);+ } else {+ SamplerParams sp;+ sp.greedy = true;+ sp.temperature = 0.0f;+ sample_tokens(head_logits_, T, (int) n_vocab_, nullptr, 0, sp, m_out_, cs);+ }}stamp(g.n_layers, 1, 0);return true;@@ -1099,8 +1568,29 @@ std::string Verifier::profile_report() {return out;}+// #871: is the zero-doorbell graph right for the next window? Only while every expert of [lb_, le_) is in VRAM now+// (the host table is the one the device copy was uploaded from; a loan, a VRAM shrink or a swap in flight has+// marked some -1). Not: the doorbell graph, which asks the pool for what the device does not hold.+void Verifier::refresh_ar() {+ if (!all_resident_ || h_res_ == nullptr || g_ == nullptr) return;+ const int64_t ne = g_->n_expert;+ const int32_t* r = h_res_ + lb_ * ne;+ const int64_t n = (le_ < 0 ? g_->n_layers : le_) * ne - lb_ * ne;+ int32_t lo = 0;+ for (int64_t i = 0; i < n; ++i) lo = std::min(lo, r[i]);+ const bool off = lo < 0;+ if (off != ar_off_) {+ ar_off_ = off;+ std::fprintf(stderr, "strata verify: layers [%lld, %lld) %s\n", (long long) lb_, (long long) (le_ < 0 ? g_->n_layers : le_),+ off ? "have experts out of VRAM (a prompt loan, a shrink or a swap): the doorbell graph runs the windows"+ : "are 100% VRAM resident again: the zero-doorbell graph");+ }+}+bool Verifier::capture(int T, std::string &err) try {- if (exec_[T] != nullptr) return true;+ dpct::experimental::command_graph_exec_ptr &exec_t =+ ar_off_ ? exec_nr_[T] : exec_[T];+ if (exec_t != nullptr) return true;if (std::getenv("STRATA_VERIFY_EAGER") != nullptr) return true; // SYCL port: no graph, run() replays the bodyif (DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs_)) != 0) {err = "verify: begin capture failed";@@ -1158,7 +1648,7 @@ bool Verifier::capture(int T, std::string &err) try {std::fprintf(stderr, "\n");}const dpct::err0 ie = DPCT_CHECK_ERROR(- exec_[T] = new sycl::ext::oneapi::experimental::command_graph<+ exec_t = new sycl::ext::oneapi::experimental::command_graph<sycl::ext::oneapi::experimental::graph_state::executable>(graph->finalize()));delete (graph);@@ -1231,7 +1721,8 @@ bool Verifier::capture_commit(std::string &err) try {gdn_conv_commit(conv, qkv, (int) C, commit_, cs_);gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C, (int) C, gate_L_ + (size_t) gdn_index * MT * HV,beta_L_ + (size_t) gdn_index * MT * HV, z_, (const float*) wnm->data, EPS, y_dummy_,- (int) g.ssm_k_heads, (int) HV, (int) MT, commit_, cs_);+ (int) g.ssm_k_heads, (int) HV, (int) MT, commit_, cs_,+ (int) MT); // S26: t_out_begin = MT - the replay's outputs (y_dummy_) are never read++gdn_index;} else {const QsaState& st = ss.qsa_states[qsa_index];@@ -1239,10 +1730,15 @@ bool Verifier::capture_commit(std::string &err) try {if (!wikn) { ok = false; break; }copy_from_mapped(st.idx_tail, tail_snap_ + (size_t) qsa_index * TS, TS, cs_);const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};- for (int64_t t = 0; t < MT; ++t)- native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + t) * ID, commit_ + 2 + t, 0,- (const float*) wikn->data, EPS, ib, s, st.max_cells,- rope_scaling(), cs_);+ if (!g_no_batch_kv) {+ native_qsa_indexer_append_steps(idx_raw_L_ + (size_t) qsa_index * MT * ID, commit_ + 2, 1, (int) MT, 0,+ (const float*) wikn->data, EPS, ib, s, st.max_cells, rope_scaling(), cs_);+ } else {+ for (int64_t t = 0; t < MT; ++t)+ native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + t) * ID, commit_ + 2 + t, 0,+ (const float*) wikn->data, EPS, ib, s, st.max_cells,+ rope_scaling(), cs_);+ }++qsa_index;}}@@ -1282,55 +1778,111 @@ catch (sycl::exception const &exc) {std::exit(1);}+void Verifier::stage_inputs(int T, const int32_t* tokens, int64_t pos0) {+ using namespace strata::kernels;+ const ModelGeometry& g = *g_;+ const QsaShapes s = shapes_of(g);+ int32_t* const pk = h_pos_ + (size_t) max_t_ * g.n_head;+ int32_t* const pi = pk + (size_t) max_t_ * g.n_head_kv;+ for (int t = 0; t < T; ++t) {+ h_tok_[t] = tokens[t];+ qsa_step_fill(h_step_ + t * kStepCount, pos0 + t, s);+ const int32_t pos_t = (int32_t) (pos0 + t);+ for (int64_t h = 0; h < g.n_head; ++h) h_pos_[t * g.n_head + h] = pos_t;+ for (int64_t h = 0; h < g.n_head_kv; ++h) pk[t * g.n_head_kv + h] = pos_t;+ 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;+ *(volatile uint32_t*) h_flag_ = 0;+ *(volatile uint32_t*) h_flagA_ = 0;+ *(volatile uint32_t*) h_flagB_ = 0;+ std::atomic_thread_fence(std::memory_order_seq_cst);+ last_t_ = T;+ last_pos0_ = pos0;+ for (int t = 0; t < T; ++t) last_tokens_[t] = tokens[t];+ staged_ = true;+}++void Verifier::collect_profile() {+ if (std::getenv("STRATA_VERIFY_EAGER") == nullptr) // eager (SYCL port): prof_h_ already holds the host clocks+ dpct::get_in_order_queue()+ .memcpy(prof_h_.data(), prof_, prof_h_.size() * 8)+ .wait();+ accumulate_profile(prof_h_.data());+}++void Verifier::accumulate_profile(const unsigned long long* stamps) {+ const ModelGeometry& g = *g_;+ const int64_t L = g.n_layers;+ auto at = [&](int64_t l, int i) { return stamps[(size_t) (l * kProfPer + i)]; };+ // D8: the derived columns below read stamps the hc-read kernels write themselves or the next+ // layer's first. A slot no kernel stamped is 0 and its unsigned difference wrapped to ~1e19 ns -+ // which is why (gap)/head/hc0 printed ~1e14 ms per window. A missing or out-of-order stamp now+ // contributes nothing.+ const auto gap = [](unsigned long long to, unsigned long long from) {+ return (from != 0 && to != 0 && to >= from) ? (double) (to - from) : 0.0;+ };+ // only this stage's layers [lb_, le_) are ever stamped (a layer split); the head only on the last stage+ for (int64_t l = lb_; l < le_; ++l) {+ const int kind = is_qsa_layer(g, l) ? 1 : 0;+ unsigned long long prev = at(l, 0);+ for (int i = 1; i <= 24; ++i) {+ const unsigned long long x = at(l, i);+ if (x == 0 || x < prev) continue;+ prof_sum_[kind][i] += (double) (x - prev);+ prev = x;+ }+ if (l + 1 < le_) prof_sum_[kind][25] += gap(at(l + 1, 0), at(l, 24));+ const double dn = gap(at(l, 27), at(l, 0)), dd = gap(at(l, 28), at(l, 27)), du = gap(at(l, 1), at(l, 28));+ if (dn > 0 && dd > 0 && du > 0) { // the split exists: show it split, not twice+ prof_sum_[kind][27] += dn; // hc-read0: norm+ prof_sum_[kind][28] += dd; // down+ prof_sum_[kind][29] += du; // up (through both halves, as before)+ prof_sum_[kind][1] -= gap(at(l, 1), at(l, 0)); // (hc-read0 shown split)+ }+ }+ if (le_ == L) prof_sum_[0][26] += gap(at(L, 1), at(L, 0));+ ++prof_windows_;+}+bool Verifier::run(int T, const int32_t *tokens, int64_t pos0, PoolMultiFn pool,void *user, int32_t *out, std::string &err) try {using namespace strata::kernels;const OnDevice on_device(device_);+ last_batch_ = false;if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; }const ModelGeometry& g = *g_;SessionState& ss = *ss_;if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }if (pos0 + T > ss.qsa_states[ss.qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; }+ refresh_ar();if (!capture(T, err) || !capture_commit(err)) return false;VDBG("captured; staging\n");const Clock::time_point t0 = Clock::now();- const QsaShapes s = shapes_of(g);- for (int t = 0; t < T; ++t) {- h_tok_[t] = tokens[t];- qsa_step_fill(h_step_ + t * kStepCount, pos0 + t, s);- for (int64_t h = 0; h < g.n_head; ++h) h_pos_[t * g.n_head + h] = (int32_t) (pos0 + t);- int32_t* pk = h_pos_ + (size_t) max_t_ * g.n_head;- int32_t* pi = pk + (size_t) max_t_ * g.n_head_kv;- for (int64_t h = 0; h < g.n_head_kv; ++h) pk[t * g.n_head_kv + h] = (int32_t) (pos0 + t);- for (int64_t h = 0; h < g.idx_q_heads; ++h) pi[t * g.idx_q_heads + h] = (int32_t) (pos0 + t);- }- if (ss.ple.ready() && ple_stage()) {- uint32_t rows[kVerifyMaxT * PLE_N_HEADS];+ if (!staged_) stage_inputs(T, tokens, pos0);+ staged_ = false;+ const bool do_ple = ss.ple.ready() && ple_stage();+ uint32_t ple_rows[kVerifyMaxT * PLE_N_HEADS];+ if (do_ple) {int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]};for (int t = 0; t < T; ++t) {- ngram_rows(&tokens[t], prev, 1, ss.ple.consts, rows + t * PLE_N_HEADS);+ ngram_rows(&tokens[t], prev, 1, ss.ple.consts, ple_rows + t * PLE_N_HEADS);prev[0] = prev[1];prev[1] = tokens[t];+ ss.ple.table->prefetch_rows(ple_rows + t * PLE_N_HEADS);}- if (!ss.ple.table->gather_batch(rows, (size_t) T, h_ple_, err)) return false;}- *(volatile uint32_t*) h_seq_ = 0;- *(volatile uint32_t*) h_flag_ = 0;- *(volatile uint32_t*) h_flagA_ = 0;- *(volatile uint32_t*) h_flagB_ = 0;if (trace_h_ != nullptr) std::memset(trace_h_, 0, trace_n_ * 8); // #649: this window's breadcrumbs onlystd::atomic_thread_fence(std::memory_order_seq_cst);trace_ev("WINDOW", -1, -1, pos0 * 16 + T);- last_t_ = T;- last_pos0_ = pos0;- for (int t = 0; t < T; ++t) last_tokens_[t] = tokens[t];ms_host += ms_since(t0);VDBG("staged; launching\n");static Clock::time_point t_prev_end; // SYCL port timing: where does a round's wall clock go?const Clock::time_point t_launch = Clock::now();+ if (ar_on() && h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0;const dpct::err0 le = (std::getenv("STRATA_VERIFY_EAGER") != nullptr)? (record_window(T, cs_, err) ? 0 : 1) // SYCL port: eager replay of the window body- : DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*exec_[T]));+ : DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*(ar_off_ ? exec_nr_[T] : exec_[T])));/*DPCT1009: SYCL reports errors using exceptions and does not use errorcodes. Please replace the "get_error_string_dummy(...)" with a real@@ -1362,6 +1914,18 @@ bool Verifier::run(int T, const int32_t *tokens, int64_t pos0, PoolMultiFn pool,static const bool no_host = std::getenv("STRATA_VERIFY_NO_HOST") != nullptr;const int64_t steps = (le_ - lb_) * G;const bool test_stall = g_test_stall > 0 && windows + 1 == g_test_stall; // #267 test hook (off: false)+ if (ar_on() && !test_stall) {+ if (do_ple) {+ const Clock::time_point tp = Clock::now();+ if (!ss.ple.table->gather_batch(ple_rows, (size_t) T, h_ple_, err)) return false;+ std::atomic_thread_fence(std::memory_order_seq_cst);+ _mm_sfence();+ *flag = 1;+ ms_host += ms_since(tp);+ } else {+ *flag = 1;+ }+ } elsefor (int64_t k = 0; !no_host && k < steps; ++k) {const int64_t l = lb_ + k / G;const int grp = (int) (k % G);@@ -1419,9 +1983,11 @@ bool Verifier::run(int T, const int32_t *tokens, int64_t pos0, PoolMultiFn pool,set_plan_slot(grp);const int tb = gtb[grp], n = gte[grp] - gtb[grp];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)pool(user, h_x_ + (size_t) tb * g.n_embd, h_ids_ + (size_t) tb * ss.k, n, ss.k,h_ymiss_ + (size_t) tb * ss.k * g.n_embd, l);+ if (remote_opt_) remote_opt_->end();VDBG("layer %lld served\n", (long long) l);if (g_trace) trace_ev(*(volatile uint32_t*) h_flagA_ == want ? "SERVED" : "SERVED-NO-PLAN-YET", k, l,(int64_t) ms_since(b)); // aux: ms the CPU experts took@@ -1438,10 +2004,22 @@ bool Verifier::run(int T, const int32_t *tokens, int64_t pos0, PoolMultiFn pool,*(volatile uint32_t*) h_flagA_ = want;raise_flag(h_flagB_, want);}+ // Layer 1's pre(1, 0) copies h_ple_ -> ple_ after Layer 0's wait_flag_ge(m_flag_, 1).+ // By collecting PLE here at k == 0 (after publishing flagA/flagB for Layer 0 so the GPU can run+ // Layer 0's VRAM experts, and before raising *flag = 1), the NVMe PLE reads overlap with both+ // MtpDrafter::draft and Layer 0's attention + router + expert execution!+ if (k == 0 && do_ple) {+ const Clock::time_point tp = Clock::now();+ if (!ss.ple.table->gather_batch(ple_rows, (size_t) T, h_ple_, err)) return false;+ std::atomic_thread_fence(std::memory_order_seq_cst);+ _mm_sfence();+ ms_host += ms_since(tp);+ }if (!(test_stall && k + 1 == steps)) *flag = want;ms_wait += std::chrono::duration<double, std::milli>(b - a).count();ms_pool += ms_since(b);}+ // (#646 staged the next stage's inputs here; 0.1.39b keeps the layer split's order: each stage stages its own)progress_at("verify window: waiting for the GPU to finish the window (flags A/B/M raised)", (int64_t) T);// #267: a window the GPU never finishes (a spin kernel that never sees its flag) holds the host here; the stall// watchdog then releases every verifier's GPU waits (release_live_verifiers) before it ends the engine, so no@@ -1530,43 +2108,20 @@ bool Verifier::run(int T, const int32_t *tokens, int64_t pos0, PoolMultiFn pool,stat("R_", R_, (size_t) g.n_embd);stat("mixed_", mixed_, (size_t) g.n_embd);}+ if (ar_on() && h_plan_err_ != nullptr && *(volatile uint32_t*) h_plan_err_ != 0) { // #871: refresh_ar saw the table whole+ *(volatile uint32_t*) h_plan_err_ = 0;+ err = "verify: the all-resident plan met an expert that is not in VRAM (the residency table changed during the window)";+ return false;+ }+ commit_pending_ = false;progress_at("verify window: waiting for the expert copies", (int64_t) T);- copy_->wait(); // no host function of this window may raise flag B in the- // next one- if (prof_on_ && G == 1) { // the window's GPU stage stamps- if (std::getenv("STRATA_VERIFY_EAGER") == nullptr) // eager: prof_h_ already holds the host clocks- dpct::get_in_order_queue()- .memcpy(prof_h_.data(), prof_, prof_h_.size() * 8)- .wait();- const int64_t L = g.n_layers;- auto at = [&](int64_t l, int i) { return prof_h_[(size_t) (l * kProfPer + i)]; };- // D8: the derived columns below read stamps the hc-read kernels write themselves or the next- // layer's first. A slot no kernel stamped is 0 and its unsigned difference wrapped to ~1e19 ns -- // which is why (gap)/head/hc0 printed ~1e14 ms per window. A missing or out-of-order stamp now- // contributes nothing.- const auto gap = [](unsigned long long to, unsigned long long from) {- return (from != 0 && to != 0 && to >= from) ? (double) (to - from) : 0.0;- };- for (int64_t l = 0; l < L; ++l) {- const int kind = is_qsa_layer(g, l) ? 1 : 0;- unsigned long long prev = at(l, 0);- for (int i = 1; i <= 24; ++i) {- const unsigned long long x = at(l, i);- if (x == 0 || x < prev) continue;- prof_sum_[kind][i] += (double) (x - prev);- prev = x;- }- if (l + 1 < L) prof_sum_[kind][25] += gap(at(l + 1, 0), at(l, 24));- const double dn = gap(at(l, 27), at(l, 0)), dd = gap(at(l, 28), at(l, 27)), du = gap(at(l, 1), at(l, 28));- if (dn > 0 && dd > 0 && du > 0) { // the split exists: show it split, not twice- prof_sum_[kind][27] += dn; // hc-read0: norm- prof_sum_[kind][28] += dd; // down- prof_sum_[kind][29] += du; // up (through both halves, as before)- prof_sum_[kind][1] -= gap(at(l, 1), at(l, 0)); // (hc-read0 shown split)- }- }- prof_sum_[0][26] += gap(at(L, 1), at(L, 0));- ++prof_windows_;+ if (copy_used_) {+ copy_->wait(); // no host function of this window may raise flag B in+ // the next one+ copy_used_ = false;+ }+ if (prof_on_ && G == 1) { // the window's GPU stage stamps+ collect_profile();if (std::getenv("STRATA_VERIFY_EAGER") != nullptr) // SYCL port: the stage table per window, host-clockedstd::fprintf(stderr, "verify stages T=%d (ms/window):%s\n", T, profile_report().c_str());}@@ -1632,7 +2187,7 @@ void Verifier::set_plan_slot(int grp) {sink_.ptr = (unsigned long long*) (base + ptr_off);sink_.ptr2 = sink_.ptr + cap;sink_.start2 = base + ptr_off + 4 * cap;- const int G = groups_[last_t_] > 0 ? groups_[last_t_] : 1;+ const int G = last_batch_ ? 1 : (groups_[last_t_] > 0 ? groups_[last_t_] : 1);const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs;sink_.staging = (unsigned long long) (staging_ + (size_t) (grp * per) * strata::kernels::cpu::expert_layout().max_blob);sink_.staging_cap = per;@@ -1657,19 +2212,49 @@ void Verifier::raise_flag(uint32_t* flag, uint32_t value) {// Plan v0.3 P6: the PCIe share by DMA. The copy engine moves the blobs while the CPU computes its own share and the// GPU its VRAM experts; a host function raises flag B when they have landed (the graph waits for it before the PCIe// groups). Staging is split between the two token groups of a split window.-void Verifier::fetch_dma(void* ctx, const uint8_t* const* src, int n, size_t bytes) {+void Verifier::fetch_dma(void *ctx, const uint8_t *const *src, int n,+ size_t bytes) try {Verifier* v = (Verifier*) ctx;const uint32_t want = v->cur_layer_ + 1;if (n <= 0) { raise_flag(v->h_flagB_, want); return; }+ v->copy_used_ = true;uint8_t* stage = (uint8_t*) v->sink_.staging; // this group's half in a split window- /*- DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While- the origin API might be synchronous, it depends on the type of operand- memory, so you may need to call wait() on event return by memcpy API to- ensure synchronization behavior.- */- for (int i = 0; i < n; ++i)- v->copy_->memcpy(stage + (size_t)i * bytes, src[i], bytes);+ // STRATA_DMA_BATCH (midhatn's #807, F12): the group's independent uploads as one cudaMemcpyBatchAsync. Mode 0 is+ // the loop the engine always ran, errors unchecked (it never stops the engine). A batch mode whose uploads+ // cannot be submitted stops the engine: flag B must not release the consumers to expert weights that were never+ // copied.+ const int batch_mode = strata::core::dma_batch_mode();+ if (batch_mode == 0) {+ /*+ DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.+ While the origin API might be synchronous, it depends on the type of+ operand memory, so you may need to call wait() on event return by memcpy+ API to ensure synchronization behavior.+ */+ for (int i = 0; i < n; ++i)+ v->copy_->memcpy(stage + (size_t)i * bytes, src[i], bytes);+ } else {+ const auto copied = strata::core::copy_expert_blobs(stage, src, n, bytes, v->copy_, batch_mode);+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (copied != 0) {+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use+ error codes. Please replace the "get_error_string_dummy(...)" with a+ real error-handling function.+ */+ std::fprintf(stderr, "strata DMA: expert upload failed: %s\n",+ dpct::get_error_string_dummy(copied));+ /*+ DPCT1001: The statement could not be removed.+ */+ std::fflush(stderr);+ v->release_gpu_waits(5000);+ std::abort();+ }+ }FlagSet& fs = v->flag_sets_[v->cur_layer_ % (sizeof v->flag_sets_ / sizeof v->flag_sets_[0])];fs.flag = v->h_flagB_;fs.value = want;@@ -1678,6 +2263,11 @@ void Verifier::fetch_dma(void* ctx, const uint8_t* const* src, int n, size_t bytcgh.host_task([=]() { raise_flag(fsp->flag, fsp->value); });});}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}void Verifier::publish_plan(void* ctx) {Verifier* v = (Verifier*) ctx;@@ -1741,47 +2331,97 @@ bool Verifier::window_logprobs(const int32_t* targets, int T, int64_t pos0, int3return false;}-// Upstream's set_commit_async/wait_commit (0.1.32) on the port's own deferred commit: commit(n, err, false) leaves-// the graph running and commit_finish() collects it (it also advances ss.ple_prev, so a pending commit must be-// finished before the next window). The flag is kept for the API; the port decides per call site (generate.cpp).namespace { bool g_commit_async = false; }void Verifier::set_commit_async(bool on) { g_commit_async = on && std::getenv("STRATA_COMMIT_SYNC") == nullptr; }-bool Verifier::commit(int n_keep, std::string &err, bool wait) try {+bool Verifier::commit(int n_keep, std::string &err) try {const OnDevice on_device(device_);if (n_keep < 1 || n_keep > last_t_) { err = "verify: commit count out of range"; return false; }- if (pending_commit_ != 0 && !commit_finish(err)) return false;const Clock::time_point t0 = Clock::now();h_commit_[0] = n_keep;h_commit_[1] = n_keep - 1;for (int t = 0; t < max_t_; ++t) h_commit_[2 + t] = t < n_keep ? (int32_t) (last_pos0_ + t) : -1;- std::atomic_thread_fence(std::memory_order_seq_cst);- const dpct::err0 le =- DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*commit_exec_));- /*- DPCT1009: SYCL reports errors using exceptions and does not use error- codes. Please replace the "get_error_string_dummy(...)" with a real- error-handling function.- */- /*- DPCT1001: The statement could not be removed.- */- /*- DPCT1000: Error handling if-stmt was detected but could not be rewritten.- */- if (le != 0) {- err = std::string("verify: commit launch: ") +- dpct::get_error_string_dummy(le);- return false;- }- if (!wait && next_ == nullptr) { // left running: commit_finish() collects it (the drafter overlaps it)- pending_commit_ = n_keep;- pending_commit_t0_ = t0;- return true;+ if (last_t_ == 1 && one_token_self_commit()) {+ // a one-token window has advanced the state itself (record_window): no commit graph+ } else {+ std::atomic_thread_fence(std::memory_order_seq_cst);+ const dpct::err0 le =+ DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*commit_exec_));+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (le != 0) {+ err = std::string("verify: commit launch: ") ++ dpct::get_error_string_dummy(le);+ return false;+ }+ // set_commit_async: no wait here - the next window runs on the same stream after it, and the drafter (its own+ // stream) reads only this window's final rows and its own K/V. h_commit_ is next written after the next window's+ // results are read, i.e. after this graph has run. Everything else waits on commit_done_ (wait_commit).+ if (!g_commit_async || next_ != nullptr) {+ const dpct::err0 se = DPCT_CHECK_ERROR(cs_->wait());+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use+ error codes. Please replace the "get_error_string_dummy(...)" with a+ real error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (se != 0) {+ err = std::string("verify: commit: ") ++ dpct::get_error_string_dummy(se);+ return false;+ }+ } else {+ /*+ DPCT1024: The original code returned the error code that was+ further consumed by the program logic. This original code was+ replaced with 0. You may need to rewrite the program logic consuming+ the error code.+ */+ const dpct::err0 re =+ DPCT_CHECK_ERROR(dpct::sync_barrier(commit_done_, cs_));+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use+ error codes. Please replace the "get_error_string_dummy(...)" with a+ real error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (re != 0) {+ err = std::string("verify: commit event: ") ++ dpct::get_error_string_dummy(re);+ return false;+ }+ (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));+ commit_pending_ = true;+ }}- pending_commit_ = n_keep;- pending_commit_t0_ = t0;- if (!commit_finish(err)) return false;+ if (ple_stage()) // stages that share one session must advance it once+ for (int t = 0; t < n_keep; ++t) {+ ss_->ple_prev[0] = ss_->ple_prev[1];+ ss_->ple_prev[1] = last_tokens_[t];+ }+ ms_commit += ms_since(t0);return next_ == nullptr || next_->commit(n_keep, err);}catch (sycl::exception const &exc) {@@ -1790,28 +2430,696 @@ catch (sycl::exception const &exc) {std::exit(1);}+bool Verifier::wait_commit(std::string &err) try {+ if (commit_pending_) {+ const OnDevice on_device(device_);+ commit_pending_ = false;+ const dpct::err0 se = DPCT_CHECK_ERROR(commit_done_->wait_and_throw());+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (se != 0) {+ err = std::string("verify: commit: ") ++ dpct::get_error_string_dummy(se);+ return false;+ }+ }+ return next_ == nullptr || next_->wait_commit(err);+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++// SYCL port: capture every window graph now (one per window size) instead of on first use, so the first request+// does not pay for them (a 2,400-node graph takes tens of ms to finalize on this backend).bool Verifier::warm(std::string &err) {for (int T = 1; T <= max_t_; ++T)if (!capture(T, err)) return false;return true;}-bool Verifier::commit_finish(std::string &err) try {- if (pending_commit_ == 0) return true;+// ================================ BATCH WINDOWS (see init_slots) ================================++bool Verifier::init_slots(const std::vector<SessionState *> &slots,+ std::string &err) try {const OnDevice on_device(device_);- const int n_keep = pending_commit_;- pending_commit_ = 0;- const dpct::err0 se = DPCT_CHECK_ERROR(cs_->wait());- if (se != 0) {- err = std::string("verify: commit: ") + dpct::get_error_string_dummy(se);+ if (g_ == nullptr || ss_ == nullptr) { err = "verify: init_slots before init"; return false; }+ if (slots.empty()) {+ err = "verify: init_slots needs at least one session";return false;}- if (ple_stage()) // stages that share one session must advance it once- for (int t = 0; t < n_keep; ++t) {- ss_->ple_prev[0] = ss_->ple_prev[1];- ss_->ple_prev[1] = last_tokens_[t];+ for (SessionState* x : slots) {+ if (x == nullptr || x->layer_lo != ss_->layer_lo || x->layer_hi != ss_->layer_hi ||+ x->max_cells != ss_->max_cells || x->gdn_ord0 != ss_->gdn_ord0 || x->qsa_ord0 != ss_->qsa_ord0) {+ err = "verify: a slot's session is not carved like the stage's own (layer range, context)";+ return false;+ }+ }+ const strata::kernels::QsaShapes s = shapes_of(*g_);+ const int64_t S = (int64_t) slots.size(), CB = 2 + max_t_;+ const int64_t TS = (s.idx_block - 1) * g_->idx_key_dim, nQ = g_->n_qsa_layers();+ void* d = nullptr;+ if (!mapped((size_t) (S * CB * 4 + 16), (void**) &h_commitb_, (void**) &m_commitb_)) {+ err = "verify: the batch commit staging failed";+ return false;+ }+ const uint64_t a = ((uint64_t) S * CB * 4 + 255) & ~255ull;+ if (DPCT_CHECK_ERROR(+ d = (void *)sycl::malloc_device(+ a + (uint64_t)S * std::max<int64_t>(nQ, 1) * TS * 4,+ dpct::get_in_order_queue())) != 0) {+ err = "verify: the batch buffers do not fit";+ return false;+ }+ arena_b_ = d;+ commitb_ = (int32_t*) d;+ tail_snap_b_ = (float*) ((uint8_t*) d + a);+ slots_ = slots;+ slot_sp_.assign(slots.size(), sampling_); // greedy until set_slot_sampling+ std::fprintf(stderr, "strata verify: batch windows of up to %lld sequences (layers [%lld, %lld))\n", (long long) S,+ (long long) lb_, (long long) le_);+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++bool Verifier::capture_batch(const int *rows, int S, int hbase,+ std::string &err) try {+ dpct::experimental::command_graph_exec_ptr &ex =+ exec_bm_[bkey(rows, S, hbase)];+ if (ex != nullptr) return true;+ if (DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs_)) != 0) {+ err = "verify: begin batch capture failed";+ return false;+ }+ batch_rec_ = true;+ row_base_ = hbase;+ for (int t = 0; t < S; ++t) brow_[t] = rows[t];+ std::string rerr;+ const bool ok = record_window(S, cs_, rerr);+ batch_rec_ = false;+ row_base_ = 0;+ dpct::experimental::command_graph_ptr graph = nullptr;+ const dpct::err0 ce =+ DPCT_CHECK_ERROR(dpct::experimental::end_recording(cs_, &graph));+ if (!ok || ce != 0) {+ if (graph) delete (graph);+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ err = !ok ? rerr+ : std::string("verify: end batch capture: ") ++ dpct::get_error_string_dummy(ce);+ return false;+ }+ const dpct::err0 ie = DPCT_CHECK_ERROR(+ ex = new sycl::ext::oneapi::experimental::command_graph<+ sycl::ext::oneapi::experimental::graph_state::executable>(+ graph->finalize()));+ delete (graph);+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be rewritten.+ */+ if (ie != 0) {+ err = std::string("verify: batch instantiate: ") ++ dpct::get_error_string_dummy(ie);+ return false;+ }+ /*+ DPCT1007: Migration of cudaGraphUpload is not supported.+ */+ // no cudaGraphUpload on SYCL: a finalized command_graph is already resident+ cs_->wait();+ std::string list;+ for (int t = 0; t < S; ++t) list += (t ? "," : "") + std::to_string(rows[t]);+ std::fprintf(stderr, "strata verify: captured the batch window over slots %s\n", list.c_str());+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++bool Verifier::capture_commit_batch(const int *rows, int S, int hbase,+ std::string &err) try {+ dpct::experimental::command_graph_exec_ptr &cex =+ commit_bm_[bkey(rows, S, hbase)];+ if (cex != nullptr) return true;+ using namespace strata::kernels;+ const ModelGeometry& g = *g_;+ const QsaShapes s = shapes_of(g);+ const int64_t C = g.ssm_conv_channels, HV = g.ssm_v_heads, ZV = g.ssm_value_dim, ID = g.idx_key_dim, MT = max_t_;+ const int64_t CB = 2 + MT, nQ = g.n_qsa_layers();+ const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size ++ (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);+ const int64_t TS = (s.idx_block - 1) * ID;+ const int64_t HS = (int64_t) NG_HIST * NG_HC_DIM;+ if (DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs_)) != 0) {+ err = "verify: begin batch commit capture failed";+ return false;+ }+ bool ok = true;+ try {+ for (int t = 0; t < S; ++t)+ if (t == 0 || rows[t] != rows[t - 1])+ copy_i32_from_mapped(commitb_ + (size_t) rows[t] * CB, m_commitb_ + (size_t) rows[t] * CB, CB, cs_);+ int64_t qsa_index = 0, gdn_index = 0;+ for (int64_t l = 0; l < lb_; ++l) (is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1;+ for (int64_t l = lb_; l < le_ && ok; ++l) {+ const LayerView v(*wt_, l);+ if (!is_qsa_layer(g, l)) {+ const WeightRef* wnm = need(v, "ssm_norm.weight", err);+ if (!wnm) { ok = false; break; }+ for (int t = 0; t < S;) {+ const int first = t;+ while (t < S && rows[t] == rows[first]) ++t;+ SessionState& sx = *slots_[(size_t) rows[first]];+ const int32_t* keep = commitb_ + (size_t) rows[first] * CB;+ float* state = sx.gdn_state + (size_t) (gdn_index - sx.gdn_ord0) * gdn_floats;+ float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;+ gdn_conv_commit(conv, qkv_L_ + (size_t) gdn_index * MT * C + (size_t) first * C,+ (int) C, keep, cs_);+ gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C + (size_t) first * C, (int) C,+ gate_L_ + (size_t) gdn_index * MT * HV + (size_t) first * HV,+ beta_L_ + (size_t) gdn_index * MT * HV + (size_t) first * HV,+ z_ + (size_t) first * ZV, (const float*) wnm->data, EPS,+ y_dummy_ + (size_t) first * ZV, (int) g.ssm_k_heads,+ (int) HV, t - first, keep, cs_,+ t - first > 1 ? t - first : 0); // a 1-row group keeps the 0.1.39 kernel+ }+ ++gdn_index;+ } else {+ const WeightRef* wikn = need(v, "indexer.k_norm.weight", err);+ if (!wikn) { ok = false; break; }+ for (int t = 0; t < S;) {+ const int first = t;+ while (t < S && rows[t] == rows[first]) ++t;+ const QsaState& st = slots_[(size_t) rows[first]]->qsa_states[qsa_index];+ copy_from_mapped(st.idx_tail, tail_snap_b_ + ((size_t) rows[first] * nQ + qsa_index) * TS,+ TS, cs_);+ const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};+ for (int u = first; u < t; ++u)+ native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + u) * ID,+ commitb_ + (size_t) rows[first] * CB + 2 + (u - first),+ 0, (const float*) wikn->data, EPS, ib, s, st.max_cells,+ rope_scaling(), cs_);+ }+ ++qsa_index;+ }+ }+ if (ok && ss_->ple.ready() && ple_stage())+ for (int t = 0; t < S;) {+ const int first = t;+ while (t < S && rows[t] == rows[first]) ++t;+ copy_indexed(slots_[(size_t) rows[first]]->ple_hist, hist_snap_ + (size_t) first * HS,+ HS, commitb_ + (size_t) rows[first] * CB + 1, HS, cs_);+ }+ } catch (const std::exception& e) {+ err = std::string("verify batch commit: ") + e.what();+ ok = false;+ }+ dpct::experimental::command_graph_ptr graph = nullptr;+ const dpct::err0 ce =+ DPCT_CHECK_ERROR(dpct::experimental::end_recording(cs_, &graph));+ if (!ok) {+ if (graph) delete (graph);+ return false;+ }+ if (ce != 0 ||+ DPCT_CHECK_ERROR(+ cex = new sycl::ext::oneapi::experimental::command_graph<+ sycl::ext::oneapi::experimental::graph_state::executable>(+ graph->finalize())) != 0) {+ if (graph) delete (graph);+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ err = std::string("verify: batch commit capture: ") ++ dpct::get_error_string_dummy(ce);+ return false;+ }+ delete (graph);+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++bool Verifier::stage_batch(const int *rows, int S, int hbase,+ const int32_t *tokens, const int64_t *pos,+ std::string &err) try {+ using namespace strata::kernels;+ if (S < 1 || S > max_t_ || hbase < 0 ||+ (next_ != nullptr && hbase + S > (int) slots_.size())) {+ err = "verify: batch rows out of range (init_slots)";+ return false;+ }+ for (int t = 0; t < S; ++t) {+ if (rows[t] < 0 || rows[t] >= (int) slots_.size()) {+ err = "verify: a batch row's slot is out of range";+ return false;+ }+ for (int u = 0; u < t - 1; ++u)+ if (rows[u] == rows[t] && rows[t - 1] != rows[t]) {+ err = "verify: a slot's proposed rows must be contiguous";+ return false;+ }+ if (t > 0 && rows[t] == rows[t - 1] && pos[t] != pos[t - 1] + 1) {+ err = "verify: proposed rows must have consecutive positions";+ return false;+ }+ if (t > 0 && rows[t] == rows[t - 1] && next_ != nullptr) {+ err = "verify: grouped slot rows do not support a layer split yet";+ return false;+ }+ }+ if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }+ const ModelGeometry& g = *g_;+ for (int t = 0; t < S; ++t)+ if (pos[t] < 0 || pos[t] + 1 > slots_[(size_t) rows[t]]->max_cells) {+ err = "verify: slot " + std::to_string(rows[t]) + " runs past its context";+ return false;+ }+ refresh_ar();+ // --batch-mtp only (limit 0 = 0.1.39: no eviction): slot rotation creates new layouts; bound the captured graph+ // pairs, evicting the least recently used layout.+ if (batch_graph_limit_ > 0) {+ const auto key = bkey(rows, S, hbase);+ if (exec_bm_.find(key) == exec_bm_.end() && exec_bm_.size() >= batch_graph_limit_) {+ if (DPCT_CHECK_ERROR(cs_->wait()) != 0) {+ err = "verify: synchronizing before batch graph eviction failed";+ return false;+ }+ auto old = exec_bm_.begin();+ uint64_t oldest = UINT64_MAX;+ for (auto it = exec_bm_.begin(); it != exec_bm_.end(); ++it) {+ const auto u = bm_used_.find(it->first);+ const uint64_t t = u == bm_used_.end() ? 0 : u->second;+ if (t < oldest) { oldest = t; old = it; }+ }+ const auto old_key = old->first;+ if (old->second) delete (old->second);+ exec_bm_.erase(old);+ bm_used_.erase(old_key);+ auto commit_old = commit_bm_.find(old_key);+ if (commit_old != commit_bm_.end()) {+ if (commit_old->second) delete (commit_old->second);+ commit_bm_.erase(commit_old);+ }+ }+ bm_used_[key] = ++bm_tick_;+ }+ if (!capture_batch(rows, S, hbase, err) || !capture_commit_batch(rows, S, hbase, err)) return false;+ const Clock::time_point t0 = Clock::now();+ const QsaShapes s = shapes_of(g);+ for (int t = 0; t < S; ++t) {+ h_tok_[t] = tokens[t];+ qsa_step_fill(h_step_ + t * kStepCount, pos[t], s);+ for (int64_t h = 0; h < g.n_head; ++h) h_pos_[t * g.n_head + h] = (int32_t) pos[t];+ int32_t* pk = h_pos_ + (size_t) max_t_ * g.n_head;+ int32_t* pi = pk + (size_t) max_t_ * g.n_head_kv;+ for (int64_t h = 0; h < g.n_head_kv; ++h) pk[t * g.n_head_kv + h] = (int32_t) pos[t];+ for (int64_t h = 0; h < g.idx_q_heads; ++h) pi[t * g.idx_q_heads + h] = (int32_t) pos[t];+ }+ if (ss_->ple.ready() && ple_stage()) {+ uint32_t ple_rows[kVerifyMaxT * PLE_N_HEADS]; // (not `rows`: that is the slots of the window's rows)+ for (int t = 0; t < S; ++t) {+ const SessionState& sx = *slots_[(size_t) rows[t]];+ int32_t prev[2] = {sx.ple_prev[0], sx.ple_prev[1]};+ if (t > 0 && rows[t] == rows[t - 1]) {+ prev[0] = t > 1 && rows[t - 2] == rows[t] ? tokens[t - 2] : sx.ple_prev[1];+ prev[1] = tokens[t - 1];+ }+ ngram_rows(&tokens[t], prev, 1, ss_->ple.consts, ple_rows + t * PLE_N_HEADS);+ }+ if (!ss_->ple.table->gather_batch(ple_rows, (size_t) S, h_ple_, err)) return false;+ }+ // Each slot owns a contiguous group. The default commit keeps all its rows; speculative+ // decoding may change the prefix length after comparing the draft with these picks.+ const int64_t CB = 2 + max_t_;+ for (int t = 0; t < S;) {+ const int first = t;+ while (t < S && rows[t] == rows[first]) ++t;+ int32_t* c = h_commitb_ + (size_t) rows[first] * CB;+ c[0] = t - first;+ c[1] = t - first - 1;+ for (int64_t j = 0; j < max_t_; ++j)+ c[2 + j] = j < t - first ? (int32_t) pos[first + j] : -1;+ }+ *(volatile uint32_t*) h_seq_ = 0;+ *(volatile uint32_t*) h_flag_ = 0;+ *(volatile uint32_t*) h_flagA_ = 0;+ *(volatile uint32_t*) h_flagB_ = 0;+ std::atomic_thread_fence(std::memory_order_seq_cst);+ last_t_ = S;+ for (int t = 0; t < S; ++t) last_rows_[t] = rows[t];+ row_base_ = hbase; // the graphs' key (and nothing else) reads it until the next stage_batch+ last_batch_ = true;+ for (int t = 0; t < S; ++t) { last_tokens_[t] = tokens[t]; last_pos_b_[t] = pos[t]; }+ ms_host += ms_since(t0);+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++bool Verifier::run_slots(int S, const int32_t* tokens, const int64_t* pos, PoolMultiFn pool, void* user, int32_t* out,+ std::string& err) {+ int rows[8] = {};+ for (int t = 0; t < S && t < 8; ++t) rows[t] = t;+ return run_slot_rows(rows, S, tokens, pos, pool, user, out, err);+}++bool Verifier::run_slot_rows(const int *rows, int S, const int32_t *tokens,+ const int64_t *pos, PoolMultiFn pool, void *user,+ int32_t *out, std::string &err) try {+ using namespace strata::kernels;+ const OnDevice on_device(device_);+ const ModelGeometry& g = *g_;+ if (!stage_batch(rows, S, 0, tokens, pos, err)) return false;+ const dpct::err0 le =+ DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*exec_bm_[bkey(rows, S, 0)]));+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be rewritten.+ */+ if (le != 0) {+ err = std::string("verify: batch launch: ") ++ dpct::get_error_string_dummy(le);+ return false;+ }+ (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));+ volatile uint32_t* const seq = h_seq_;+ volatile uint32_t* const flag = h_flag_;+ const int64_t steps = le_ - lb_;+ // #646: a stage whose every expert is resident plans on the device and raises no host doorbells, so the+ // per-layer spin below has nothing to wait for: without the PLE flag the graph finishes with the ring silent+ // ("verify batch: layer K never rang (graph finished)" - K is that stage's first layer), and with it the graph+ // sits on the PLE wait until the 20 s timeout. As run() does: raise the PLE flag the graph's first wait reads,+ // let the graph run to the end, and skip the host's per-layer service (there is nothing to serve).+ if (all_resident_) {+ if (ss_->ple.ready() && ple_stage()) {+ std::atomic_thread_fence(std::memory_order_seq_cst);+ _mm_sfence();+ *flag = 1;+ }+ const dpct::err0 se = DPCT_CHECK_ERROR(cs_->wait());+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (se != 0) {+ err =+ std::string("verify batch: ") + dpct::get_error_string_dummy(se);+ return false;+ }+ copy_->wait();+ if (prof_on_) collect_profile();+ ++windows;+ if (le_ < g.n_layers) return next_ == nullptr || next_->run_slot_rows(rows, S, tokens, pos, pool, next_user_, out, err);+ if (!sample_rows(S, err)) return false;+ for (int t = 0; t < S; ++t) out[t] = ((volatile int32_t*) h_out_)[t];+ progress_at("decode");+ progress_beat();+ return true;+ }+ for (int64_t k = 0; k < steps; ++k) {+ const int64_t l = lb_ + k;+ const uint32_t want = (uint32_t) (k + 1);+ const Clock::time_point a = Clock::now();+ auto last_flush = a;+ uint32_t spins = 0;+ progress_at("verify batch: waiting for the GPU to reach layer", l);+ while (*seq < want) {+ _mm_pause();+ if ((++spins & 1023u) != 0) continue;+ const auto now = Clock::now();+ if (now - last_flush > std::chrono::microseconds(2000)) {+ last_flush = now;+ const dpct::err0 q = cs_->ext_oneapi_empty() ? 0 : 1;+ if (q != 1 && *seq < want) {+ err = "verify batch: layer " + std::to_string(l) ++ " never rang (" ++ /*+ DPCT1009: SYCL reports errors using exceptions and+ does not use error codes. Please replace the+ "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ (q == 0+ ? std::string("graph finished")+ : std::string(dpct::get_error_string_dummy(q))) ++ ")";+ return false;+ }+ }+ if (now - a > std::chrono::seconds(20)) {+ err = "verify batch: timed out at layer " + std::to_string(l) + released_note(release_gpu_waits(5000));+ return false;+ }+ }+ const Clock::time_point b = Clock::now();+ cur_layer_ = want - 1;+ set_plan_slot(0);+ progress_at("verify batch: the CPU experts of layer", l);+ if (pool != nullptr) pool(user, h_x_, h_ids_, S, ss_->k, h_ymiss_, l);+ progress_tick();+ std::atomic_thread_fence(std::memory_order_seq_cst);+ _mm_sfence();+ if (*(volatile uint32_t*) h_flagA_ != want) { // the pool did not publish a plan: an empty one+ sink_.counts[0] = 0;+ sink_.counts[1] = 0;+ sink_.counts[2] = 0;+ sink_.start[0] = 0;+ sink_.start2[0] = 0;+ std::atomic_thread_fence(std::memory_order_seq_cst);+ *(volatile uint32_t*) h_flagA_ = want;+ raise_flag(h_flagB_, want);+ }+ *flag = want;+ ms_wait += std::chrono::duration<double, std::milli>(b - a).count();+ ms_pool += ms_since(b);+ }+ const dpct::err0 se = DPCT_CHECK_ERROR(cs_->wait());+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be rewritten.+ */+ if (se != 0) {+ err = std::string("verify batch: ") + dpct::get_error_string_dummy(se);+ return false;+ }+ copy_->wait();+ if (prof_on_) collect_profile();+ ++windows;+ if (le_ < g.n_layers) return next_ == nullptr || next_->run_slot_rows(rows, S, tokens, pos, pool, next_user_, out, err);+ if (!sample_rows(S, err)) return false;+ for (int t = 0; t < S; ++t) out[t] = ((volatile int32_t*) h_out_)[t];+ progress_at("decode");+ progress_beat();+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++bool Verifier::commit_slots(std::string& err) {+ std::vector<int> keep(slots_.size(), 0);+ for (int t = 0; t < last_t_; ++t) ++keep[(size_t) last_rows_[t]];+ return commit_slot_prefixes(keep.data(), err);+}++bool Verifier::commit_slot_prefixes(const int *keep, std::string &err) try {+ const OnDevice on_device(device_);+ if (!last_batch_ || last_t_ < 1) { err = "verify: commit_slots without a batch window"; return false; }+ const int S = last_t_;+ const Clock::time_point t0 = Clock::now();+ const int64_t CB = 2 + max_t_;+ // One prefix per slot: rejected draft rows must not enter recurrent state.+ for (int t = 0; t < S;) {+ const int first = t;+ while (t < S && last_rows_[t] == last_rows_[first]) ++t;+ const int n = keep[last_rows_[first]];+ if (n < 1 || n > t - first) {+ err = "verify: accepted prefix is outside its slot group";+ return false;+ }+ int32_t* c = h_commitb_ + (size_t) last_rows_[first] * CB;+ c[0] = n;+ c[1] = n - 1;+ for (int j = 0; j < max_t_; ++j)+ c[2 + j] = j < n ? (int32_t) last_pos_b_[first + j] : -1;+ }+ std::atomic_thread_fence(std::memory_order_seq_cst);+ const dpct::err0 le = DPCT_CHECK_ERROR(+ (cs_)->ext_oneapi_graph(*commit_bm_[bkey(last_rows_, S, row_base_)]));+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be rewritten.+ */+ if (le != 0) {+ err = std::string("verify: batch commit launch: ") ++ dpct::get_error_string_dummy(le);+ return false;+ }+ const dpct::err0 se = DPCT_CHECK_ERROR(cs_->wait());+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be rewritten.+ */+ if (se != 0) {+ err = std::string("verify: batch commit: ") ++ dpct::get_error_string_dummy(se);+ return false;+ }+ if (ple_stage())+ for (int t = 0; t < S;) {+ const int first = t;+ while (t < S && last_rows_[t] == last_rows_[first]) ++t;+ SessionState& sx = *slots_[(size_t) last_rows_[first]];+ for (int u = first; u < first + keep[last_rows_[first]]; ++u) {+ sx.ple_prev[0] = sx.ple_prev[1];+ sx.ple_prev[1] = last_tokens_[u];+ }+ }+ ms_commit += ms_since(t0);+ return next_ == nullptr || next_->commit_slot_prefixes(keep, err);+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++bool Verifier::sample_rows(int S, std::string &err) try {+ bool any = false;+ for (int t = 0; t < S; ++t) {+ strata::kernels::SamplerParams sp = slot_sp_[(size_t) last_rows_[t]];+ if (sp.greedy || sp.temperature <= 0.0f) continue;+ sp.counter = (uint64_t) last_pos_b_[t]; // Philox(seed, position): the solo window's draw for this position+ sp.penalty_last_n = 0;+ strata::kernels::sample_tokens(head_logits_ + (size_t) t * (size_t) n_vocab_, 1, (int) n_vocab_, nullptr, 0, sp,+ m_out_ + t, cs_);+ any = true;+ }+ if (any && DPCT_CHECK_ERROR(cs_->wait()) != 0) {+ err = "verify batch: the row sampling failed"; return false;+ }+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++bool Verifier::batch_launch(int base, int S, const int32_t *tokens,+ const int64_t *pos, std::string &err) try {+ const OnDevice on_device(device_);+ if (b_running_) { err = "verify: batch_launch while this stage is busy"; return false; }+ int rows[8] = {};+ for (int t = 0; t < S && t < 8; ++t) rows[t] = base + t;+ if (!stage_batch(rows, S, base, tokens, pos, err)) return false;+ dpct::err0 le = DPCT_CHECK_ERROR(+ (cs_)->ext_oneapi_graph(*exec_bm_[bkey(rows, S, base)]));+ if (le == 0) le = DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*commit_bm_[bkey(+ rows, S, base)])); // right behind it: every row is kept+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be rewritten.+ */+ if (le != 0) {+ err = std::string("verify: batch launch: ") ++ dpct::get_error_string_dummy(le);+ return false;+ }+ (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));+ if (ple_stage()) // the host's side of the commit (the hash's last two tokens)+ for (int t = 0; t < S; ++t) {+ SessionState& sx = *slots_[(size_t) rows[t]];+ sx.ple_prev[0] = sx.ple_prev[1];+ sx.ple_prev[1] = tokens[t];}- ms_commit += ms_since(pending_commit_t0_);+ b_running_ = true;+ b_k_ = 0;+ b_steps_ = le_ - lb_;+ b_last_ = Clock::now();return true;}catch (sycl::exception const &exc) {@@ -1820,11 +3128,123 @@ catch (sycl::exception const &exc) {std::exit(1);}-bool Verifier::wait_commit(std::string& err) {- if (!commit_finish(err)) return false;- return next_ == nullptr || next_->wait_commit(err);-}-+int Verifier::batch_poll(PoolMultiFn pool, void *user, std::string &err) try {+ if (!b_running_) return 1;+ const OnDevice on_device(device_);+ volatile uint32_t* const seq = h_seq_;+ const int S = last_t_;+ // #646: an all-resident stage's graph raises no host doorbells (see run_slot_rows): nothing to serve per layer,+ // so the poll is just "has the graph finished" - except the PLE flag, which the graph's first wait reads and+ // only the host can raise (the same raise run_slot_rows makes).+ if (all_resident_ && ss_->ple.ready() && ple_stage()) {+ std::atomic_thread_fence(std::memory_order_seq_cst);+ _mm_sfence();+ *h_flag_ = 1;+ }+ while (!all_resident_ && b_k_ < b_steps_) {+ const uint32_t want = (uint32_t) (b_k_ + 1);+ if (*seq < want) {+ const auto now = Clock::now();+ if (now - b_last_ > std::chrono::milliseconds(2)) {+ const dpct::err0 q = cs_->ext_oneapi_empty() ? 0 : 1;+ if (q != 1 && *seq < want) {+ err = "verify batch: layer " + std::to_string(lb_ + b_k_) ++ " never rang (" ++ /*+ DPCT1009: SYCL reports errors using exceptions and+ does not use error codes. Please replace the+ "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ (q == 0+ ? std::string("graph finished")+ : std::string(dpct::get_error_string_dummy(q))) ++ ")";+ b_running_ = false;+ return -1;+ }+ if (now - b_last_ > std::chrono::seconds(20)) {+ err = "verify batch: timed out at layer " + std::to_string(lb_ + b_k_) + released_note(release_gpu_waits(5000));+ b_running_ = false;+ return -1;+ }+ }+ return 0;+ }+ const Clock::time_point b = Clock::now();+ cur_layer_ = want - 1;+ set_plan_slot(0);+ if (pool != nullptr) pool(user, h_x_, h_ids_, S, ss_->k, h_ymiss_, lb_ + b_k_);+ progress_tick();+ std::atomic_thread_fence(std::memory_order_seq_cst);+ _mm_sfence();+ if (*(volatile uint32_t*) h_flagA_ != want) { // the pool did not publish a plan: an empty one+ sink_.counts[0] = 0;+ sink_.counts[1] = 0;+ sink_.counts[2] = 0;+ sink_.start[0] = 0;+ sink_.start2[0] = 0;+ std::atomic_thread_fence(std::memory_order_seq_cst);+ *(volatile uint32_t*) h_flagA_ = want;+ raise_flag(h_flagB_, want);+ }+ *(volatile uint32_t*) h_flag_ = want;+ ms_pool += ms_since(b);+ b_last_ = Clock::now();+ ++b_k_;+ }+ const dpct::err0 q = cs_->ext_oneapi_empty() ? 0 : 1;+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1002: Special case error handling if-stmt was detected. You may need+ to rewrite this code.+ */+ if (q == 1) return 0;+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be rewritten.+ */+ if (q != 0) {+ err = std::string("verify batch: ") + dpct::get_error_string_dummy(q);+ b_running_ = false;+ return -1;+ }+ const dpct::err0 qc = DPCT_CHECK_ERROR(+ ((copy_)->ext_oneapi_empty())); // no host function of this window may+ // raise flag B in the next+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1002: Special case error handling if-stmt was detected. You may need+ to rewrite this code.+ */+ if (qc == 1) return 0;+ if (prof_on_) collect_profile();+ if (last_stage()) {+ if (!sample_rows(S, err)) { b_running_ = false; return -1; }+ for (int t = 0; t < S; ++t) b_out_[t] = ((volatile int32_t*) h_out_)[t];+ }+ ++windows;+ b_running_ = false;+ progress_beat();+ return 1;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}+bool Verifier::copy_logits(int t, float* host) const {if (next_ != nullptr) return next_->copy_logits(t, host); // a layer split: the head is on the last stageif (head_logits_ == nullptr || host == nullptr || t < 0 || n_vocab_ <= 0) return false;@@ -1836,4 +3256,423 @@ bool Verifier::copy_logits(int t, float* host) const {return true;}+// ================================ PIPELINED WINDOWS (see verify.hpp) ================================+//+// The window is run()'s, step for step: the same graph, the same staging, the same per-layer service (the PLE rows+// gathered while layer 0 is served, the zero-doorbell graph's one flag), the same commit graph. Only the waits are+// split up: the host polls instead of spinning, so it can serve the other stage's window in between.++namespace {+double now_ms() { return std::chrono::duration<double, std::milli>(Clock::now().time_since_epoch()).count(); }+} // namespace++void Verifier::diag_pipelined(std::FILE* f, const char* name) const {+ auto rd = [](const uint32_t* p) { return p ? *(const volatile uint32_t*) p : 0u; };+ auto ev = [](dpct::event_ptr e) {+ try {+ if (e == nullptr) return "none";+ const dpct::err0 q = dpct::sycl_event_query(e);+ return q == 0 ? "done" : q == 1 ? "PENDING" : "error";+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ std::fprintf(f, " %s: %s T=%d pos %lld served %lld/%lld; GPU rang %u, flags served %u A %u B %u; window event %s, "+ "commit event %s (commit launched %d)\n", name, fl_active_ ? "IN FLIGHT" : "idle", last_t_,+ (long long) last_pos0_, (long long) fl_k_, (long long) fl_total_, rd(h_seq_), rd(h_flag_), rd(h_flagA_),+ rd(h_flagB_), ev(ev_done_), ev(ev_commit_), (int) commit_live_);+}++bool Verifier::capture_all(std::string &err) try {+ const OnDevice on_device(device_);+ if (g_ == nullptr) { err = "verify: capture_all before init"; return false; }+ if (remote_opt_ != nullptr) { err = "verify: pipelined windows do not serve --remote-expert-opt"; return false; }+ if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }+ for (int T = 1; T <= max_t_; ++T)+ if (!capture(T, err)) return false;+ if (!capture_commit(err)) return false;+ if ((ev_done_ == nullptr &&+ DPCT_CHECK_ERROR(ev_done_ = new sycl::event()) != 0) ||+ (ev_commit_ == nullptr &&+ DPCT_CHECK_ERROR(ev_commit_ = new sycl::event()) != 0)) {+ err = "verify: event create failed";+ return false;+ }+ if (prof_on_ && prof_pin_ == nullptr &&+ /*+ DPCT1048: The original value cudaHostAllocDefault is not meaningful in+ the migrated code and was removed or replaced with 0. You may need to+ check the migrated code.+ */+ DPCT_CHECK_ERROR(prof_pin_ = (unsigned long long *)sycl::malloc_host(+ prof_h_.size() * 8, dpct::get_in_order_queue())) !=+ 0) {+ prof_pin_ = nullptr; // the pipelined windows go unprofiled+ /*+ DPCT1026: The call to cudaGetLastError was removed because this+ functionality is redundant in SYCL.+ */+ }+ pl_ple_rows_.assign((size_t) strata::kernels::kVerifyMaxT * strata::kernels::PLE_N_HEADS, 0u);+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++// The host staging of a pipelined window: run()'s (stage_inputs), and its PLE rows from `ple_prev` with their pages+// prefetched (they are gathered into the mapped rows when layer 0 is served, as run() does).+void Verifier::pl_stage(int T, const int32_t* tokens, int64_t pos0, const int32_t ple_prev[2]) {+ using namespace strata::kernels;+ stage_inputs(T, tokens, pos0);+ staged_ = false; // a later run() stages its own window+ SessionState& ss = *ss_;+ fl_ple_ = ss.ple.ready() && ple_stage();+ if (fl_ple_) {+ int32_t prev[2] = {ple_prev[0], ple_prev[1]};+ for (int t = 0; t < T; ++t) {+ ngram_rows(&tokens[t], prev, 1, ss.ple.consts, pl_ple_rows_.data() + t * PLE_N_HEADS);+ prev[0] = prev[1];+ prev[1] = tokens[t];+ ss.ple.table->prefetch_rows(pl_ple_rows_.data() + t * PLE_N_HEADS);+ }+ }+ pl_prev_[0] = ple_prev[0];+ pl_prev_[1] = ple_prev[1];+}++bool Verifier::prestage(int T, const int32_t* tokens, int64_t pos0, const int32_t ple_prev[2], std::string& err) {+ if (fl_active_) { err = "verify: a window is in flight on this verifier"; return false; }+ if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; }+ if (pl_ple_rows_.empty()) { err = "verify: pipelined window not prepared (capture_all)"; return false; }+ const Clock::time_point t0 = Clock::now();+ pl_stage(T, tokens, pos0, ple_prev);+ pl_prestaged_ = true;+ ms_host += ms_since(t0);+ return true;+}++bool Verifier::pl_launch(int T, const int32_t *tokens, int64_t pos0,+ std::string &err) try {+ const OnDevice on_device(device_);+ if (fl_active_) { err = "verify: a window is already in flight on this verifier"; return false; }+ if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }+ if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; }+ SessionState& ss = *ss_;+ if (pos0 + T > ss.qsa_states[ss.qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; }+ if (exec_[T] == nullptr || commit_exec_ == nullptr || ev_done_ == nullptr || pl_ple_rows_.empty()) {+ err = "verify: pipelined window not prepared (capture_all)";+ return false;+ }+ const Clock::time_point t0 = Clock::now();+ last_batch_ = false;+ bool staged = pl_prestaged_ && last_t_ == T && last_pos0_ == pos0;+ for (int t = 0; staged && t < T; ++t) staged = last_tokens_[t] == tokens[t];+ if (staged && ss.ple.ready() && ple_stage())+ staged = pl_prev_[0] == ss.ple_prev[0] && pl_prev_[1] == ss.ple_prev[1];+ pl_prestaged_ = false;+ if (!staged) pl_stage(T, tokens, pos0, ss.ple_prev);+ const int G = groups_[T] > 0 ? groups_[T] : 1;+ fl_T_ = T;+ fl_k_ = 0;+ fl_total_ = (le_ - lb_) * G;+ fl_prof_ = prof_on_ && G == 1 && prof_pin_ != nullptr;+ if (trace_h_ != nullptr) std::memset(trace_h_, 0, trace_n_ * 8); // #649: this window's breadcrumbs only+ std::atomic_thread_fence(std::memory_order_seq_cst);+ trace_ev("WINDOW (pipelined)", -1, -1, pos0 * 16 + T);+ ms_host += ms_since(t0);+ const dpct::err0 le = DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*exec_[T]));+ trace_ev("LAUNCHED", -1, -1, (int64_t) le);+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be rewritten.+ */+ if (le != 0) {+ err = std::string("verify: launch: ") + dpct::get_error_string_dummy(le);+ return false;+ }+ /*+ DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While+ the origin API might be synchronous, it depends on the type of operand+ memory, so you may need to call wait() on event return by memcpy API to+ ensure synchronization behavior.+ */+ if (fl_prof_) cs_->memcpy(prof_pin_, prof_, prof_h_.size() * 8);+ /*+ DPCT1024: The original code returned the error code that was further+ consumed by the program logic. This original code was replaced with 0. You+ may need to rewrite the program logic consuming the error code.+ */+ if (DPCT_CHECK_ERROR(dpct::sync_barrier(ev_done_, cs_)) != 0) {+ err = "verify: event record failed"; return false;+ }+ (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty())); // WDDM: submit now+ fl_active_ = true;+ fl_since_ms_ = fl_flush_ms_ = fl_launch_ms_ = now_ms();+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++int Verifier::service(PoolMultiFn pool, void *user, std::string &err) try {+ if (!fl_active_) return 1;+ if (fl_k_ >= fl_total_) return 1;+ const OnDevice on_device(device_);+ const ModelGeometry& g = *g_;+ SessionState& ss = *ss_;+ const int T = fl_T_;+ // the PLE rows into the mapped staging (layer 1's pre() copies them once flag 1 is up), as run() does at k == 0+ auto gather_ple = [&]() -> bool {+ if (!fl_ple_) return true;+ const Clock::time_point tp = Clock::now();+ if (!ss.ple.table->gather_batch(pl_ple_rows_.data(), (size_t) T, h_ple_, err)) return false;+ std::atomic_thread_fence(std::memory_order_seq_cst);+ _mm_sfence();+ ms_host += ms_since(tp);+ return true;+ };+ if (all_resident_) { // the zero-doorbell graph never rings: it waits only for flag 1 (stage 0's PLE rows)+ if (!gather_ple()) return -1;+ *(volatile uint32_t*) h_flag_ = 1;+ fl_k_ = fl_total_;+ progress_tick();+ return 1;+ }+ const int G = groups_[T] > 0 ? groups_[T] : 1;+ const int gtb[2] = {0, (T + 1) / 2}, gte[2] = {G == 2 ? (T + 1) / 2 : T, T};+ while (fl_k_ < fl_total_) {+ const int64_t l = lb_ + fl_k_ / G;+ const uint32_t want = (uint32_t) (fl_k_ + 1);+ if (*(volatile uint32_t*) h_seq_ < want) {+ const double now = now_ms();+ if (now - fl_flush_ms_ > 2.0) { // flush WDDM and notice a dead graph, as run() does+ fl_flush_ms_ = now;+ const dpct::err0 q = dpct::sycl_event_query(ev_done_);+ if (q != 1 && *(volatile uint32_t *)h_seq_ < want) {+ trace_ev("NEVER-RANG", fl_k_, l, (int64_t) q);+ err = "verify: layer " + std::to_string(l) ++ " never rang (" ++ /*+ DPCT1009: SYCL reports errors using exceptions and+ does not use error codes. Please replace the+ "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ (q == 0+ ? std::string("graph finished")+ : std::string(dpct::get_error_string_dummy(q))) ++ ")";+ return -1;+ }+ (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));+ }+ if (now - fl_since_ms_ > 20000.0) { // #267: no spin kernel may outlive the engine+ trace_ev("TIMEOUT", fl_k_, l, 0);+ err = "verify: timed out at layer " + std::to_string(l) + released_note(release_gpu_waits(5000));+ return -1;+ }+ return 0;+ }+ const Clock::time_point b = Clock::now();+ ms_wait += now_ms() - fl_since_ms_;+ const int grp = (int) (fl_k_ % G);+ cur_layer_ = want - 1;+ set_plan_slot(grp);+ const int tb = gtb[grp], n = gte[grp] - gtb[grp];+ 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,+ h_ymiss_ + (size_t) tb * ss.k * g.n_embd, l);+ if (g_trace) trace_ev(*(volatile uint32_t*) h_flagA_ == want ? "SERVED" : "SERVED-NO-PLAN-YET", fl_k_, l,+ (int64_t) ms_since(b));+ progress_tick();+ std::atomic_thread_fence(std::memory_order_seq_cst);+ _mm_sfence();+ if (*(volatile uint32_t*) h_flagA_ != want) { // the pool did not publish a plan: an empty one+ sink_.counts[0] = 0;+ sink_.counts[1] = 0;+ sink_.counts[2] = 0;+ sink_.start[0] = 0;+ sink_.start2[0] = 0;+ std::atomic_thread_fence(std::memory_order_seq_cst);+ *(volatile uint32_t*) h_flagA_ = want;+ raise_flag(h_flagB_, want);+ }+ if (fl_k_ == 0 && !gather_ple()) return -1;+ *(volatile uint32_t*) h_flag_ = want;+ ++fl_k_;+ ms_pool += ms_since(b);+ fl_since_ms_ = fl_flush_ms_ = now_ms();+ }+ return 1;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++bool Verifier::done(std::string &err) try {+ if (!fl_active_ || fl_k_ < fl_total_) return false;+ const OnDevice on_device(device_);+ const dpct::err0 q = dpct::sycl_event_query(ev_done_);++ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (q != 0) {+ err = std::string("verify: ") + dpct::get_error_string_dummy(q);+ return false;+ }+ if (copy_used_) { // no host function of this window may raise flag B in the next one+ if (DPCT_CHECK_ERROR(((copy_)->ext_oneapi_empty())) == 1) return false;+ copy_used_ = false;+ }+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++bool Verifier::pl_finish(int32_t *out, std::string &err) try {+ using namespace strata::kernels;+ const OnDevice on_device(device_);+ const ModelGeometry& g = *g_;+ fl_active_ = false;+ if (fl_prof_) accumulate_profile(prof_pin_);+ ++windows;+ trace_ev("DONE (pipelined)", -1, -1, (int64_t) (now_ms() - fl_launch_ms_));+ if (le_ < g.n_layers) return true; // an earlier stage: the hand-off is written+ const int T = fl_T_;+ const bool sampled = !sampling_.greedy && sampling_.temperature > 0.0f;+ if (head_sampling_ && (sampled || hist_d_ != nullptr)) { // run()'s host-side sampling, Philox(seed, pos0 + t)+ SamplerParams sp = sampling_;+ sp.counter = (uint64_t) last_pos0_;+ sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_);+ if (DPCT_CHECK_ERROR(cs_->wait()) != 0) {+ err = "verify: the head sampling failed";+ return false;+ }+ }+ if (out != nullptr)+ for (int t = 0; t < T; ++t) out[t] = ((volatile int32_t*) h_out_)[t];+ progress_beat();+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++bool Verifier::pl_commit_async(int n_keep, std::string &err) try {+ const OnDevice on_device(device_);+ if (n_keep < 1 || n_keep > last_t_) { err = "verify: commit count out of range"; return false; }+ if (commit_exec_ == nullptr || ev_commit_ == nullptr) { err = "verify: pipelined commit not prepared"; return false; }+ const Clock::time_point t0 = Clock::now();+ if (commit_live_) { // its graph reads the words below when it starts: the previous one has (a window ago)+ dpct::err0 q;+ while ((q = dpct::sycl_event_query(ev_commit_)) == 1) _mm_pause();+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use+ error codes. Please replace the "get_error_string_dummy(...)" with a+ real error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (q != 0) {+ err =+ std::string("verify: commit: ") + dpct::get_error_string_dummy(q);+ return false;+ }+ }+ h_commit_[0] = n_keep;+ h_commit_[1] = n_keep - 1;+ for (int t = 0; t < max_t_; ++t) h_commit_[2 + t] = t < n_keep ? (int32_t) (last_pos0_ + t) : -1;+ std::atomic_thread_fence(std::memory_order_seq_cst);+ const dpct::err0 le =+ DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*commit_exec_));+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (le != 0) {+ err = std::string("verify: commit launch: ") ++ dpct::get_error_string_dummy(le);+ return false;+ }+ /*+ DPCT1024: The original code returned the error code that was further+ consumed by the program logic. This original code was replaced with 0. You+ may need to rewrite the program logic consuming the error code.+ */+ if (DPCT_CHECK_ERROR(dpct::sync_barrier(ev_commit_, cs_)) != 0) {+ err = "verify: event record failed"; return false;+ }+ (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));+ commit_live_ = true;+ if (ple_stage())+ for (int t = 0; t < n_keep; ++t) {+ ss_->ple_prev[0] = ss_->ple_prev[1];+ ss_->ple_prev[1] = last_tokens_[t];+ }+ ms_commit += ms_since(t0);+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++void Verifier::absorb_stats(Verifier& o) {+ ms_wait += o.ms_wait; ms_pool += o.ms_pool; ms_host += o.ms_host; ms_commit += o.ms_commit;+ windows += o.windows;+ o.ms_wait = o.ms_pool = o.ms_host = o.ms_commit = 0;+ o.windows = 0;+ for (int k = 0; k < 2; ++k)+ for (int i = 0; i < kProfPer; ++i) { prof_sum_[k][i] += o.prof_sum_[k][i]; o.prof_sum_[k][i] = 0; }+ prof_windows_ += o.prof_windows_;+ o.prof_windows_ = 0;+}+} // namespace strata::corediff --git a/sycl/src/core/vmm.cpp b/sycl/src/core/vmm.cppnew file mode 100644index 000000000..7ec6acf52--- /dev/null+++ b/sycl/src/core/vmm.cpp@@ -0,0 +1,27 @@+// src/core/vmm.cpp - SYCL port: no virtual memory management.+//+// Upstream's vmm.cpp reaches the CUDA driver's cuMem* functions through cudaGetDriverEntryPointByVersion; Level Zero+// has no equivalent through dpct. Every entry point therefore reports "not available", the same answer a GPU+// without virtual memory management gives, so --vram-elastic and the elastic K/V (--kv-grow) refuse with their+// usual message and nothing else changes.+#include "strata/core/vmm.hpp"++namespace strata::core {++bool vmm_available() { return false; }+uint64_t vmm_granularity() { return 0; }+VmmChunk vmm_chunk_new() { return 0; }+void vmm_chunk_free(VmmChunk) {}++bool VmmRange::reserve(uint64_t) { return false; }+void VmmRange::release() {+ h_.clear();+ base_ = 0;+}+int64_t VmmRange::mapped_count() const { return 0; }+VmmChunk VmmRange::unmap(int64_t) { return 0; }+bool VmmRange::map_one(int64_t, VmmChunk) { return false; }+bool VmmRange::set_access(int64_t, int64_t) { return false; }+bool VmmRange::commit_run(int64_t, int64_t) { return false; }++} // namespace strata::corediff --git a/sycl/src/core/weights.cpp b/sycl/src/core/weights.cppindex 7a7ed123c..5741893ce 100644--- a/sycl/src/core/weights.cpp+++ b/sycl/src/core/weights.cpp@@ -5,6 +5,7 @@#include "strata/core/weights.hpp"#include "strata/kernels/f16_bits.hpp"+#include "strata/platform/memory.hpp"#include <chrono>#include <algorithm>@@ -225,15 +226,15 @@ bool WeightTable::load(const std::string &pack_dir, void *arena_base,void* stage_in = nullptr;void* stage_out = nullptr;/*- DPCT1048: The original value cudaHostAllocDefault is not meaningful in- the migrated code and was removed or replaced with 0. You may need to check- the migrated code.+ DPCT1048: The original value cudaHostAllocDefault is not meaningful in the+ migrated code and was removed or replaced with 0. You may need to check the+ migrated code.*/if (DPCT_CHECK_ERROR(stage_in = (void *)sycl::malloc_host(CHUNK, dpct::get_in_order_queue())) != 0 ||/*- DPCT1048: The original value cudaHostAllocDefault is not meaningful- in the migrated code and was removed or replaced with 0. You may need to+ DPCT1048: The original value cudaHostAllocDefault is not meaningful in+ the migrated code and was removed or replaced with 0. You may need tocheck the migrated code.*/DPCT_CHECK_ERROR(stage_out = (void *)sycl::malloc_host(@@ -299,6 +300,12 @@ bool WeightTable::load(const std::string &pack_dir, void *arena_base,return false;}cur_file = r.file;+#if !defined(_WIN32)+ // ask for this file's remaining rows up front so their reads overlap+ for (size_t j = row_i; j < rows.size(); ++j)+ if (rows[j].file == r.file && !skipped[j])+ strata::platform::advise_willneed(fileno(cur), rows[j].src_off, rows[j].src_bytes);+#endif}// ---- the segment list: what this tensor's bytes are, plane by plane, in both formsdiff --git a/sycl/src/kernels/cuda/cvec.dp.cpp b/sycl/src/kernels/cuda/cvec.dp.cppindex c118d5171..35b9c2348 100644--- a/sycl/src/kernels/cuda/cvec.dp.cpp+++ b/sycl/src/kernels/cuda/cvec.dp.cpp@@ -256,6 +256,14 @@ void cvec_set_enabled(bool on) {bool cvec_enabled() { return g_cvec.loaded() && g_on_host; }+bool cvec_tables(const float** dir, const float** s, const int** on) {+ if (!g_cvec.loaded()) return false;+ const DevTables& t = g_dev[cur_device()];+ if (t.dir == nullptr) return false;+ *dir = t.dir; *s = t.s; *on = t.on;+ return true;+}+void cvec_apply(float *R, int64_t layer, int64_t T, int64_t r_ld,const float *bo, int64_t bo_ld, const float *inj,int64_t inj_ld, bool write, void *stream) try {diff --git a/sycl/src/kernels/cuda/dequant_bf16.dp.cpp b/sycl/src/kernels/cuda/dequant_bf16.dp.cppindex 272e95425..668bf088c 100644--- a/sycl/src/kernels/cuda/dequant_bf16.dp.cpp+++ b/sycl/src/kernels/cuda/dequant_bf16.dp.cpp@@ -189,14 +189,14 @@ template <int TYPE, typename T>__dpct_inline__ void dequant_kernel(const uint8_t *__restrict__ blocks,int64_t row_bytes, int64_t row0,int64_t rows, int64_t groups_per_row,- T *__restrict__ out) {+ int64_t ld, T *__restrict__ out) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();const int64_t g =(int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +item_ct1.get_local_id(2);if (g >= rows * groups_per_row) return;const int64_t r = g / groups_per_row, gi = g % groups_per_row;- group32<TYPE>(blocks + (row0 + r) * row_bytes, (int) gi, out + r * groups_per_row * 32 + gi * 32);+ group32<TYPE>(blocks + (row0 + r) * row_bytes, (int) gi, out + r * ld + gi * 32);}bool geometry(int type, int& block_elems, int& block_bytes) {@@ -217,7 +217,8 @@ bool geometry(int type, int& block_elems, int& block_bytes) {}template <typename T>-void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, T* out, void* stream) {+void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, T* out, void* stream,+ int64_t ld = 0) {int be = 0, bb = 0;if (!geometry(type, be, bb) || cols % be != 0 || rows <= 0) {std::fprintf(stderr, "dequant: unsupported type %d or shape %lld x %lld\n", type, (long long) rows,@@ -225,6 +226,7 @@ void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t costd::exit(1);}const int64_t row_bytes = cols / be * bb, gpr = cols / 32, total = rows * gpr;+ if (ld <= 0) ld = cols;const unsigned grid = (unsigned) ((total + 255) / 256);const uint8_t* p = (const uint8_t*) blocks;dpct::queue_ptr st = strata::q_of(stream);@@ -239,7 +241,8 @@ void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t coauto row0_ct2 = row0; \auto rows_ct3 = rows; \auto gpr_ct4 = gpr; \- auto out_ct5 = out; \+ auto ld_ct5 = ld; \+ auto out_ct6 = out; \\cgh.parallel_for<dpct_kernel_name<class dequant_kernel_ec9311, \dpct_kernel_scalar<TY>, T>>( \@@ -248,7 +251,7 @@ void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t cosycl::range(1, 1, 256)), \exp_props, [=](sycl::nd_item<3> item_ct1) { \dequant_kernel<TY, T>(p_ct0, row_bytes_ct1, row0_ct2, \- rows_ct3, gpr_ct4, out_ct5); \+ rows_ct3, gpr_ct4, ld_ct5, out_ct6); \}); \}); \} break@@ -306,6 +309,15 @@ void dequant_f16(int ggml_type, const void* blocks, int64_t row0, int64_t rows,launch<H16>(ggml_type, blocks, row0, rows, cols, reinterpret_cast<H16*>(out), stream);}+bool dequant_f16_ld(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, int64_t ld,+ uint16_t* out, void* stream) {+ int be = 0, bb = 0;+ if (iq_only(ggml_type) || !geometry(ggml_type, be, bb) || cols % be != 0 || rows <= 0 || ld < cols || ld % 8 != 0)+ return false;+ launch<H16>(ggml_type, blocks, row0, rows, cols, reinterpret_cast<H16*>(out), stream, ld);+ return true;+}+void dequant_f32(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, float* out, void* stream) {if (iq_only(ggml_type)) {iq_dequant_f32(ggml_type, (const uint8_t*) blocks + (size_t) row0 * iq_row_bytes(ggml_type, cols), rows * cols,diff --git a/sycl/src/kernels/cuda/elementwise.dp.cpp b/sycl/src/kernels/cuda/elementwise.dp.cppindex 6f0168323..38ef29ef4 100644--- a/sycl/src/kernels/cuda/elementwise.dp.cpp+++ b/sycl/src/kernels/cuda/elementwise.dp.cpp@@ -166,9 +166,9 @@ runtimes. You may need to adjust the code.float inv = 0.0f;if (lane == 0) inv = sycl::rsqrt(acc / (float)cols + eps);/*- DPCT1108: '__shfl_sync' was migrated with the experimental feature- masked sub_group function which may not be supported by all compilers or- runtimes. You may need to adjust the code.+ DPCT1108: '__shfl_sync' was migrated with the experimental feature masked+ sub_group function which may not be supported by all compilers or runtimes.+ You may need to adjust the code.*/inv = dpct::experimental::select_from_sub_group(0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(), inv,@@ -375,6 +375,9 @@ __dpct_inline__ void doorbell_ring_kernel(uint32_t *seq) {*/sycl::atomic_fence(sycl::memory_order::acq_rel, sycl::memory_scope::system);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}__dpct_inline__ void doorbell_wait_kernel(const volatile uint32_t *flag,@@ -574,7 +577,8 @@ __dpct_inline__ void doorbell_publish_kernel(const float *__restrict__ x,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)];+ if (w_out != nullptr) w_out[item_ct1.get_local_id(2)] =+ w[item_ct1.get_local_id(2)];}/*DPCT1078: Consider replacing memory_order::acq_rel with@@ -589,6 +593,36 @@ __dpct_inline__ void doorbell_publish_kernel(const float *__restrict__ x,*/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+ }+}++__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) {+ 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;+ }+ /*+ 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))) {+#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 withmemory_order::seq_cst for correctness if strong memory order@@ -596,7 +630,26 @@ __dpct_inline__ void doorbell_publish_kernel(const float *__restrict__ x,*/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);+ }+ /*+ 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.+ */+ 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}}@@ -691,6 +744,31 @@ void doorbell_publish(const float* x, const int32_t* ids, const float* weights,check_launch("doorbell_publish");}+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); }+ /*+ 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.+ Adjust the work-group size if needed.+ */+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<+ dpct_kernel_name<class doorbell_publish_res_kernel_85b9b3>>(+ sycl::nd_range<3>(sycl::range(1, 1, 1024),+ 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);+ });+ }+ check_launch("doorbell_publish_res");+}+__dpct_inline__ void copy_i32_from_mapped_kernel(int32_t *__restrict__ dst,const volatile int32_t *src,int n) {@@ -700,6 +778,65 @@ __dpct_inline__ void copy_i32_from_mapped_kernel(int32_t *__restrict__ dst,i += item_ct1.get_local_range(2)) dst[i] = src[i];}+#if !defined(__HIPCC__)+struct MappedCopies {+ MappedCopy c[8];+};++__dpct_inline__ void copy_from_mapped_multi_kernel(MappedCopies a) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const MappedCopy c = a.c[item_ct1.get_group(1)];+ const int64_t i0 = (int64_t)item_ct1.get_group(2) *+ item_ct1.get_local_range(2) ++ item_ct1.get_local_id(2),+ st = (int64_t)item_ct1.get_group_range(2) *+ item_ct1.get_local_range(2);+ if ((c.words & 3) == 0 && ((uintptr_t) c.dst & 15) == 0 && ((uintptr_t) c.src & 15) == 0) {+ /*+ DPCT1052: SYCL does not support the member access for a volatile+ qualified vector type. The volatile qualifier was removed. You may need+ to rewrite the code.+ */+ const sycl::float4 *s = (const sycl::float4 *)c.src;+#pragma unroll+ for (int64_t i = i0; i < c.words / 4; i += st)(+ (sycl::float4 *)c.dst)[i] = const_cast<const sycl::float4 *>(s)[i];+ } else {+ const volatile int32_t* s = (const volatile int32_t*) c.src;+#pragma unroll+ for (int64_t i = i0; i < c.words; i += st)((int32_t *)c.dst)[i] = s[i];+ }+}++void copy_from_mapped_multi(const MappedCopy* copies, int n, void* stream) {+ if (n <= 0) return;+ if (n > 8) { std::fprintf(stderr, "copy_from_mapped_multi: at most 8 copies\n"); std::exit(1); }+ MappedCopies a;+ int64_t most = 0;+ for (int i = 0; i < n; ++i) {+ a.c[i] = copies[i];+ most = copies[i].words > most ? copies[i].words : most;+ }+ const int64_t units = (most + 3) / 4;+ const unsigned bx = (unsigned) ((units + 255) / 256 < 32 ? (units + 255) / 256 : 32);+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<+ dpct_kernel_name<class copy_from_mapped_multi_kernel_66c71e>>(+ sycl::nd_range<3>(sycl::range(1, (unsigned)n, bx < 1 ? 1 : bx) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ copy_from_mapped_multi_kernel(a);+ });+ }+ check_launch("copy_from_mapped_multi");+}+#endif+void copy_i32_from_mapped(int32_t* dst, const int32_t* src, int64_t n, void* stream) {if (n <= 0) return;{@@ -719,6 +856,13 @@ void copy_i32_from_mapped(int32_t* dst, const int32_t* src, int64_t n, void* strcheck_launch("copy_i32_from_mapped");}+#if defined(__HIPCC__) // AMD keeps one copy a launch+void copy_from_mapped_multi(const MappedCopy* copies, int n, void* stream) {+ for (int i = 0; i < n; ++i)+ copy_i32_from_mapped((int32_t*) copies[i].dst, (const int32_t*) copies[i].src, copies[i].words, stream);+}+#endif+void doorbell_ring(uint32_t* d_seq, void* stream) {if (d_seq == nullptr) return;{diff --git a/sycl/src/kernels/cuda/fused_gdn.dp.cpp b/sycl/src/kernels/cuda/fused_gdn.dp.cppindex eca2bab0e..ba5499529 100644--- a/sycl/src/kernels/cuda/fused_gdn.dp.cpp+++ b/sycl/src/kernels/cuda/fused_gdn.dp.cpp@@ -32,7 +32,10 @@ auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(sycl::ext::oneapi::this_work_item::get_work_group<3>());auto &sq = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(sycl::ext::oneapi::this_work_item::get_work_group<3>());- auto &red =+ auto &red_kv =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][S]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &red_o =*sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][S]>(sycl::ext::oneapi::this_work_item::get_work_group<3>());auto &wsum = *sycl::ext::oneapi::group_local_memory_for_overwrite<@@ -59,14 +62,14 @@ auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(float kv = 0.0f;#pragma unrollfor (int r = 0; r < RPG; ++r) kv = sycl::fma(s[r], sk[rg * RPG + r], kv);- red[rg][col] = kv;+ red_kv[rg][col] = kv;/*DPCT1065: Consider replacing sycl::nd_item::barrier() withsycl::nd_item::barrier(sycl::access::fence_space::local_space) for betterperformance if there is no access to global memory.*/item_ct1.barrier();- const float kv_col = red[0][col] + red[1][col] + red[2][col] + red[3][col];+ const float kv_col = red_kv[0][col] + red_kv[1][col] + red_kv[2][col] + red_kv[3][col];const float delta = (v[head * S + col] - g * kv_col) * beta[head];float o = 0.0f;#pragma unroll@@ -75,13 +78,7 @@ auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(o = sycl::fma(s[r], sq[rg * RPG + r], o);base[r * row_stride] = s[r];}- /*- 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.- */- item_ct1.barrier(); // every thread has read red[] for kv_col- red[rg][col] = o;+ red_o[rg][col] = o;/*DPCT1065: Consider replacing sycl::nd_item::barrier() withsycl::nd_item::barrier(sycl::access::fence_space::local_space) for better@@ -90,15 +87,15 @@ auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(item_ct1.barrier();float oc = 0.0f, sq_part = 0.0f;if (rg == 0) {- oc = (red[0][col] + red[1][col] + red[2][col] + red[3][col]) *+ oc = (red_o[0][col] + red_o[1][col] + red_o[2][col] + red_o[3][col]) *sycl::rsqrt((float)S);sq_part = oc * oc;}// RMS over the head's 128 outputs: warps of row group 0 are threads 0..127./*-DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature-masked sub_group function which may not be supported by all compilers or-runtimes. You may need to adjust the code.+DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature masked+sub_group function which may not be supported by all compilers or runtimes. You+may need to adjust the code.*/#pragma unrollfor (int o2 = 16; o2 > 0; o2 >>= 1) sq_part +=@@ -140,9 +137,9 @@ auto &part =if ((int)item_ct1.get_group(2) < qk_heads) {float sq = y * y;/*-DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature-masked sub_group function which may not be supported by all compilers or-runtimes. You may need to adjust the code.+DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature masked+sub_group function which may not be supported by all compilers or runtimes. You+may need to adjust the code.*/#pragma unrollfor (int o = 16; o > 0; o >>= 1) sq +=@@ -210,9 +207,9 @@ gdn_ab_kernel(const float *__restrict__ x, const uint16_t *__restrict__ wa,(float)(xb.w()), acc);}/*-DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature-masked sub_group function which may not be supported by all compilers or-runtimes. You may need to adjust the code.+DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature masked+sub_group function which may not be supported by all compilers or runtimes. You+may need to adjust the code.*/#pragma unrollfor (int o = 16; o > 0; o >>= 1) acc +=diff --git a/sycl/src/kernels/cuda/fused_gr.dp.cpp b/sycl/src/kernels/cuda/fused_gr.dp.cppindex d5aa4cb91..2c8d12469 100644--- a/sycl/src/kernels/cuda/fused_gr.dp.cpp+++ b/sycl/src/kernels/cuda/fused_gr.dp.cpp@@ -1604,7 +1604,7 @@ static float* down_partials(sycl::queue* q) {return p;}-void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf,+bool fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf,int stamp_i0) {if (n_tok < 1 || n_tok > kFusedGrMaxT || xn_scratch == nullptr) {std::fprintf(stderr, "fused_gr_read_multi: invalid arguments\n");@@ -1752,7 +1752,7 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi*/const dpct::err0 e3 = 0;- return;+ return false; // SYCL port: never writes the q8_1 images (STRATA_QFUSE is not supported here)}m.part = down_partials(st);{@@ -1879,8 +1879,12 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voineed to rewrite this code.*/const dpct::err0 e = 0;+ return false; // SYCL port: the q8_1 images (S26 STRATA_QFUSE) and the Q8_0 reads (S23 STRATA_HC_Q8) are not built; the caller quantizes}+// the bench only (AMD latency-hidden kernels): nothing to switch on the SYCL port+void fused_gr_set_fast(int) {}+bool fused_gr_supported(int64_t n_embd, int64_t hc, int64_t hc_lr) {return n_embd == N && hc == HC && hc_lr == LR;}diff --git a/sycl/src/kernels/cuda/gr.dp.cpp b/sycl/src/kernels/cuda/gr.dp.cppindex fd8f809b1..c7c6a692d 100644--- a/sycl/src/kernels/cuda/gr.dp.cpp+++ b/sycl/src/kernels/cuda/gr.dp.cpp@@ -504,7 +504,7 @@ void gr_read(const float *R, const float *w_norm, const uint16_t *w_down,dpct::has_capability_or_fail(st->get_device(),{sycl::aspect::fp64});- st->parallel_for<dpct_kernel_name<class gr_norm_kernel_8a2029,+ st->parallel_for<dpct_kernel_name<class gr_norm_kernel_588e81,dpct_kernel_scalar<true>>>(sycl::nd_range<3>(sycl::range(1, 1, hc) *sycl::range(1, 1, THREADS),@@ -521,7 +521,7 @@ void gr_read(const float *R, const float *w_norm, const uint16_t *w_down,sycl::ext::oneapi::experimental::use_root_sync};st->parallel_for<- dpct_kernel_name<class gr_down_kernel_f016b0, float>>(+ dpct_kernel_name<class gr_down_kernel_6ff92b, float>>(sycl::nd_range<3>(sycl::range(1, 1, hc_lr) *sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),@@ -537,7 +537,7 @@ void gr_read(const float *R, const float *w_norm, const uint16_t *w_down,sycl::ext::oneapi::experimental::use_root_sync};st->parallel_for<- dpct_kernel_name<class gr_gate_kernel_4b823d, float>>(+ dpct_kernel_name<class gr_gate_kernel_abf73c, float>>(sycl::nd_range<3>(sycl::range(1, 1, (hc_dim + WARPS - 1) / WARPS) *sycl::range(1, 1, THREADS),@@ -556,7 +556,7 @@ void gr_read(const float *R, const float *w_norm, const uint16_t *w_down,dpct::has_capability_or_fail(st->get_device(),{sycl::aspect::fp64});- st->parallel_for<dpct_kernel_name<class gr_norm_kernel_f7b23c,+ st->parallel_for<dpct_kernel_name<class gr_norm_kernel_70bea5,dpct_kernel_scalar<false>>>(sycl::nd_range<3>(sycl::range(1, 1, hc) *sycl::range(1, 1, THREADS),@@ -573,7 +573,7 @@ void gr_read(const float *R, const float *w_norm, const uint16_t *w_down,sycl::ext::oneapi::experimental::use_root_sync};st->parallel_for<- dpct_kernel_name<class gr_down_kernel_cbf49c, uint16_t>>(+ dpct_kernel_name<class gr_down_kernel_518fbb, uint16_t>>(sycl::nd_range<3>(sycl::range(1, 1, hc_lr) *sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),@@ -589,7 +589,7 @@ void gr_read(const float *R, const float *w_norm, const uint16_t *w_down,sycl::ext::oneapi::experimental::use_root_sync};st->parallel_for<- dpct_kernel_name<class gr_gate_kernel_75fce5, uint16_t>>(+ dpct_kernel_name<class gr_gate_kernel_feafeb, uint16_t>>(sycl::nd_range<3>(sycl::range(1, 1, (hc_dim + WARPS - 1) / WARPS) *sycl::range(1, 1, THREADS),@@ -634,7 +634,7 @@ void gr_read(const float *R, const float *w_norm, const uint16_t *w_down,sycl::ext::oneapi::experimental::use_root_sync};st->parallel_for<- dpct_kernel_name<class gr_inject_kernel_182d54, float>>(+ dpct_kernel_name<class gr_inject_kernel_569ce0, float>>(sycl::nd_range<3>(sycl::range(1, 1, nthreads),sycl::range(1, 1, nthreads)),exp_props,@@ -655,7 +655,7 @@ void gr_read(const float *R, const float *w_norm, const uint16_t *w_down,sycl::ext::oneapi::experimental::use_root_sync};st->parallel_for<- dpct_kernel_name<class gr_inject_kernel_500b2a, uint16_t>>(+ dpct_kernel_name<class gr_inject_kernel_d9aa02, uint16_t>>(sycl::nd_range<3>(sycl::range(1, 1, nthreads),sycl::range(1, 1, nthreads)),exp_props,@@ -685,6 +685,57 @@ catch (sycl::exception const &exc) {std::exit(1);}+static bool no_multi_gr() {+ static const bool off = [] {+ const char* v = std::getenv("STRATA_NO_MULTI_GR");+ return v != nullptr && v[0] != '\0' && v[0] != '0';+ }();+ return off;+}++void gr_read_multi(const float *R, const float *w_norm, const uint16_t *w_down,+ const uint16_t *w_up, const uint16_t *w_inject, float eps,+ const GrShapes &s, const GrWorkspace &ws, float *xn_multi,+ float *lo_multi, float *gated_multi, float *mixed,+ float *inject, int n_tok, void *stream) try {+ if (n_tok <= 0 || s.n_embd <= 0 || s.hc <= 0 || s.hc_lr <= 0) return;+ if (!no_multi_gr() && native_mmvf && n_tok > 1 && xn_multi != nullptr && lo_multi != nullptr && gated_multi != nullptr) {+ const int n_embd = (int) s.n_embd, hc = (int) s.hc, hc_lr = (int) s.hc_lr;+ const int hc_dim = (int) (s.hc * s.n_embd);+ if ((hc_dim & 1) != 0 || (hc_lr & 1) != 0)+ throw std::invalid_argument("gr_read native MMVF requires even hc*n_embd and hc_lr");+ native_gr_rms_norm_weighted_multi(R, w_norm, xn_multi, n_embd, hc, n_tok, eps, stream);+ bf16_gemv_fp32_mmvf_multi(xn_multi, hc_dim, w_down, lo_multi, hc_lr, hc_dim, hc_lr, n_tok, stream);+ native_gr_down_silu(lo_multi, hc_lr * n_tok, hc, stream);+ bf16_gemv_fp32_mmvf_multi(lo_multi, hc_lr, w_up, gated_multi, hc_dim, hc_lr, hc_dim, n_tok, stream);+ native_gr_pre_gated_multi(xn_multi, gated_multi, mixed, n_embd, hc, n_tok, w_inject != nullptr, stream);+ if (w_inject != nullptr)+ bf16_gemv_fp32_mmvf_multi(xn_multi, hc_dim, w_inject, inject, hc, hc_dim, hc, n_tok, stream);+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use+ the error codes. The cudaGetLastError function call was replaced with 0.+ You need to rewrite this code.+ */+ const dpct::err0 e = 0;++ if (stream == nullptr) {+ const dpct::err0 se = DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw());+ }+ return;+ }+ const size_t hc_dim = (size_t) s.hc * (size_t) s.n_embd;+ for (int t = 0; t < n_tok; ++t) {+ gr_read(R + (size_t) t * hc_dim, w_norm, w_down, w_up, w_inject, eps, s, ws,+ mixed + (size_t) t * s.n_embd, inject ? inject + (size_t) t * s.hc : nullptr, stream);+ }+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}+void gr_write(const float *R, const float *block_out, const float *inject,const GrShapes &s, float *R_out, void *stream) try {if (s.n_embd <= 0 || s.hc <= 0) return;@@ -732,4 +783,28 @@ catch (sycl::exception const &exc) {std::exit(1);}+void gr_write_multi(const float *R, const float *block_out, const float *inject,+ const GrShapes &s, float *R_out, int n_tok,+ void *stream) try {+ if (n_tok <= 0 || s.n_embd <= 0 || s.hc <= 0) return;+ if (!no_multi_gr() && native_mmvf && n_tok > 1) {+ native_gr_post_multi(R, block_out, inject, R_out, (int) s.n_embd, (int) s.hc, n_tok, stream);+ if (stream == nullptr) {+ const dpct::err0 e = DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw());+ }+ return;+ }+ const size_t hc_dim = (size_t) s.hc * (size_t) s.n_embd;+ for (int t = 0; t < n_tok; ++t) {+ gr_write(R + (size_t) t * hc_dim, block_out + (size_t) t * s.n_embd, inject + (size_t) t * s.hc, s,+ R_out + (size_t) t * hc_dim, stream);+ }+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}+} // namespace strata::kernelsdiff --git a/sycl/src/kernels/cuda/iq_kernels.dp.cpp b/sycl/src/kernels/cuda/iq_kernels.dp.cppindex cecfcd81f..324bc9ed2 100644--- a/sycl/src/kernels/cuda/iq_kernels.dp.cpp+++ b/sycl/src/kernels/cuda/iq_kernels.dp.cpp@@ -12,6 +12,7 @@#include "strata/kernels/iq_kernels.hpp"#include "strata/kernels/dp4a.hpp"#include "strata/kernels/q8_1_finite.hpp"+#include "s26_tsum.dp.hpp"#define GGML_COMMON_DECL_SYCL#define GGML_COMMON_IMPL_SYCL@@ -21,7 +22,9 @@#include <algorithm>#include <type_traits>#include <cstdio>+#include <utility>#include <cstdlib>+#include <type_traits>namespace strata::kernels {namespace {@@ -57,6 +60,18 @@ __dpct_inline__ uint32_t unpack_ksigns(const uint8_t v) {}__dpct_inline__ sycl::int2 get_int_from_table_16(const int &q4,const int8_t *table) {+#if defined(STRATA_HIP_GFX906)+ // AMD: llama.cpp's HIP lookup (vecdotq.cuh) - v_perm_b32 takes 3-bit byte indices, so the low and high halves+ // of the table are looked up and the index MSB picks between them: 4 perms per 8 values.+ const uint32_t* v32 = reinterpret_cast<const uint32_t*>(table);+ const uint32_t q_even = (uint32_t) q4, q_odd = (uint32_t) q4 >> 4;+ const uint32_t el = __builtin_amdgcn_perm(v32[1], v32[0], q_even & 0x07070707u);+ const uint32_t ol = __builtin_amdgcn_perm(v32[1], v32[0], q_odd & 0x07070707u);+ const uint32_t eh = __builtin_amdgcn_perm(v32[3], v32[2], q_even & 0x07070707u);+ const uint32_t oh = __builtin_amdgcn_perm(v32[3], v32[2], q_odd & 0x07070707u);+ return make_int2((int) __builtin_amdgcn_perm(eh, el, 0x03020100u | ((q_even & 0x08080808u) >> 1)),+ (int) __builtin_amdgcn_perm(oh, ol, 0x03020100u | ((q_odd & 0x08080808u) >> 1)));+#elseconst uint32_t* table32 = (const uint32_t*) table;uint32_t tmp[2];const uint32_t low_high_selection_indices = (0x32103210 | ((q4 & 0x88888888) >> 1));@@ -72,6 +87,7 @@ __dpct_inline__ sycl::int2 get_int_from_table_16(const int &q4,}return sycl::int2(dpct::byte_level_permute(tmp[0], tmp[1], 0x6420),dpct::byte_level_permute(tmp[0], tmp[1], 0x7531));+#endif}#define ggml_cuda_dp4a(a, b, c) strata::dp4a((a), (b), (c)) // SYCL port: the one dp4a (strata/sycl_math.hpp)@@ -428,7 +444,7 @@ __dpct_inline__ float vec_dot_iq4_xs_q8_1(const void *__restrict__ vbq,// Q4_K / Q5_K gate/up and Q5_1 / Q8_0 down: llama.cpp's vec_dot_*_q8_1 (vecdotq.cuh, VDR 2 each), transcribed; the// Q5_1 min term is the one departure (below). Via eddoursul/Strata 8029fa9 (iq_dot.cuh) and #255 (Q8_0,// gopinath87607), which agree with llama.cpp and with each other.-constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q5_0 = 2, VDR_Q8_0 = 2;+constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q5_0 = 2, VDR_Q4_1 = 2, VDR_Q4_0 = 2, VDR_Q8_0 = 2, VDR_Q6_K = 1;__dpct_inline__ float vec_dot_q4_K_q8_1_impl_vmmq(const int *__restrict__ v, const int *__restrict__ u,@@ -577,6 +593,53 @@ __dpct_inline__ float vec_dot_q5_0_q8_1(const void *__restrict__ vbq,const float s8 = bq8_1->ds[1];return d5 * (sumi * d8 - (16.0f * VDR_Q5_0 / QI5_0) * s8);}+// Q4_0 (plain llama-quantize Q4_0 files, e.g. bartowski's: gate/up and most down projections): the codes are centred+// (q - 8 as signed bytes) before the dot, the exact integer form ggml-cpu's q4_0 x q8_0 dot uses, rather than+// llama.cpp's CUDA chain (uncentred codes minus 8 x the q8_1 block's float sum `ds.y`). On a real Q4_0 expert+// (2560 x 640) the CUDA chain measured 1.4e-2 relative error against the float product, the centred form 5.3e-3;+// with the CUDA chain native_expert_parity failed its 3e-2 limit on two layers of a Q4_0 Flash-Next file. The+// centring is the same idea as the Q5_1 min term above: the offset is applied to the activations' own int8 codes.+__dpct_inline__ int q4_0_centred(const int v) {+ // Unsigned: (b & 0x08080808) * 0x1E reaches 0xF0F0F0F0, which overflows a signed int - undefined behaviour the+ // sm_60 build (no __dp4a, strata_dp4a fallback) optimised into a wrong value (native_expert_parity gpu rel 1.7e4).+ const uint32_t b = (uint32_t) v ^ 0x08080808u; // per byte: 0..15 -> (q - 8) as a 4-bit two's complement value+ return (int) (b | ((b & 0x08080808u) * 0x1Eu)); // sign-extend each nibble into its byte (0x08 * 0x1E = 0xF0)+}+__dpct_inline__ float vec_dot_q4_0_q8_1(const void *__restrict__ vbq,+ const block_q8_1 *__restrict__ bq8_1,+ const int &kbx, const int &iqs) {+ const block_q4_0* bq4 = (const block_q4_0*) vbq + kbx;+ int sumi = 0;+#pragma unroll+ for (int i = 0; i < VDR_Q4_0; ++i) {+ const int v = get_int_b2(bq4->qs, iqs + i);+ sumi = ggml_cuda_dp4a(q4_0_centred((v >> 0) & 0x0F0F0F0F), get_int_b4(bq8_1->qs, iqs + i), sumi);+ sumi = ggml_cuda_dp4a(q4_0_centred((v >> 4) & 0x0F0F0F0F), get_int_b4(bq8_1->qs, iqs + i + QI4_0), sumi);+ }+ return sycl::vec<sycl::half, 1>(bq4->d)+ .convert<float, sycl::rounding_mode::automatic>()[0] *+ bq8_1->ds[0] * sumi;+}+// Q4_1 (llama-quantize puts it on a few down projections of its Q4_0 files): the Q5_1 chain above without the fifth+// bit, the same min-term choice (the activations' own int8 codes): sumi * (d4 * d8) + sumu * (m4 * d8).+__dpct_inline__ float vec_dot_q4_1_q8_1(const void *__restrict__ vbq,+ const block_q8_1 *__restrict__ bq8_1,+ const int &kbx, const int &iqs) {+ const block_q4_1* bq4_1 = (const block_q4_1*) vbq + kbx;+ int sumi = 0, sumu = 0;+#pragma unroll+ for (int i = 0; i < VDR_Q4_1; ++i) {+ const int v = get_int_b4(bq4_1->qs, iqs + i);+ const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI4_1);+ sumi = ggml_cuda_dp4a((v >> 0) & 0x0F0F0F0F, u0, sumi);+ sumi = ggml_cuda_dp4a((v >> 4) & 0x0F0F0F0F, u1, sumi);+ sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu));+ }+ const sycl::float2 dm4 =+ (bq4_1->dm).template convert<float, sycl::rounding_mode::automatic>();+ const float d8 = bq8_1->ds[0];+ return sumi * (dm4.x() * d8) + sumu * (dm4.y() * d8);+}__dpct_inline__ float vec_dot_q5_1_q8_1(const void *__restrict__ vbq,const block_q8_1 *__restrict__ bq8_1,const int &kbx, const int &iqs) {@@ -606,6 +669,49 @@ __dpct_inline__ float vec_dot_q5_1_q8_1(const void *__restrict__ vbq,const float d8 = bq8_1->ds[0];return sumi * (dm5.x() * d8) + sumu * (dm5.y() * d8);}+// Q6_K: llama.cpp's integer chain verbatim (vecdotq.cuh vec_dot_q6_K_q8_1_impl_mmvq / vec_dot_q6_K_q8_1) -- signed+// per-16-element scales, the -32 offset folded into the per-byte value, the q8_1 block's ds.low for the scales,+// upstream exactly as pulled (no min-term choice exists: Q6_K has no learned min).+__dpct_inline__ float+vec_dot_q6_K_q8_1_impl_mmvq(const int vl, const int vh,+ const int *__restrict__ u,+ const int8_t *__restrict__ scales, const float d,+ const float *__restrict__ d8) {+ float sumf = 0.0f;+#pragma unroll+ for (int i = 0; i < QR6_K; ++i) {+ const int sc = scales[4 * i];+ const int vil = (vl >> (4 * i)) & 0x0F0F0F0F;+ const int vih = ((vh >> (4 * i)) << 4) & 0x30303030;+ const int vi = dpct::vectorized_binary<sycl::char4>(+ vil | vih, 0x20202020, dpct::sub_sat()); // vi = (vil | vih) - 32+ sumf += d8[i] * (STRATA_DP4A(vi, u[i], 0) * sc);+ }+ return d * sumf;+}+__dpct_inline__ float vec_dot_q6_K_q8_1(const void *__restrict__ vbq,+ const block_q8_1 *__restrict__ bq8_1,+ const int &kbx, const int &iqs) {+ const block_q6_K* bq6_K = (const block_q6_K*) vbq + kbx;+ const int bq8_offset = 2 * QR6_K * (iqs / (QI6_K / 2)) + (iqs % (QI6_K / 2)) / (QI6_K / 4);+ const int scale_offset = (QI6_K / 4) * (iqs / (QI6_K / 2)) + (iqs % (QI6_K / 2)) / (QI6_K / 8);+ const int vh_shift = 2 * ((iqs % (QI6_K / 2)) / (QI6_K / 4));+ const int vl = get_int_b2(bq6_K->ql, iqs);+ const int vh = get_int_b2(bq6_K->qh, (QI6_K / 4) * (iqs / (QI6_K / 2)) + iqs % (QI6_K / 4)) >> vh_shift;+ const int8_t* scales = bq6_K->scales + scale_offset;+ int u[QR6_K];+ float d8[QR6_K];+#pragma unroll+ for (int i = 0; i < QR6_K; ++i) {+ u[i] = get_int_b4(bq8_1[bq8_offset + 2 * i].qs, iqs % QI8_1);+ d8[i] = bq8_1[bq8_offset + 2 * i].ds[0];+ }+ return vec_dot_q6_K_q8_1_impl_mmvq(+ vl, vh, u, scales,+ sycl::vec<sycl::half, 1>(bq6_K->d)+ .convert<float, sycl::rounding_mode::automatic>()[0],+ d8);+}__dpct_inline__ float vec_dot_q8_0_q8_1(const void *__restrict__ vbq,const block_q8_1 *__restrict__ bq8_1,const int &kbx, const int &iqs) {@@ -646,8 +752,14 @@ template<> struct Fmt<12> { static constexpr int qk = 256, ipb = QI4_K / VDR_Q4_static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_K_q8_1(v, y, kbx, iqs); } };template<> struct Fmt<13> { static constexpr int qk = 256, ipb = QI5_K / VDR_Q5_K, step = VDR_Q5_K;static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_K_q8_1(v, y, kbx, iqs); } };+template<> struct Fmt<14> { static constexpr int qk = 256, ipb = QI6_K / VDR_Q6_K, step = VDR_Q6_K;+ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q6_K_q8_1(v, y, kbx, iqs); } };template<> struct Fmt<7> { static constexpr int qk = 32, ipb = QI5_1 / VDR_Q5_1, step = VDR_Q5_1;static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_1_q8_1(v, y, kbx, iqs); } };+template<> struct Fmt<2> { static constexpr int qk = 32, ipb = QI4_0 / VDR_Q4_0, step = VDR_Q4_0;+ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_0_q8_1(v, y, kbx, iqs); } };+template<> struct Fmt<3> { static constexpr int qk = 32, ipb = QI4_1 / VDR_Q4_1, step = VDR_Q4_1;+ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_1_q8_1(v, y, kbx, iqs); } };template<> struct Fmt<6> { static constexpr int qk = 32, ipb = QI5_0 / VDR_Q5_0, step = VDR_Q5_0;static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_0_q8_1(v, y, kbx, iqs); } };template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0, step = VDR_Q8_0;@@ -655,9 +767,13 @@ template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0,// The formats of each role, one list each so a type cannot be in one switch and missing from another. Every// entry is a kernel template for each CUDA architecture of the build, hence two lists rather than one.-#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(8)-#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(8)-#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(8)+#ifdef STRATA_Q6K_EXPERTS // opt-in build (-DSTRATA_Q6K_EXPERTS=ON): one more instance per kernel, loaded at start+#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(14) X(6) X(2) X(3) X(8)+#else+#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(2) X(3) X(8)+#endif+#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8)+#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(2) X(3) X(8)__dpct_inline__ float warp_sum(float v) {#pragma unroll@@ -748,19 +864,24 @@ template<int TY> struct Split;// per-entry ones, which call Fmt<TY>::dot per column exactly as before #242 (the launchers test kSplit at compile// time, so the multi kernels are never instantiated for a type without a Split).template<int TY> inline constexpr bool kSplit = false;+template<int TY> inline constexpr bool kStageIqGrid = (TY == 16 || TY == 17 || TY == 22 || TY == 29);+template<> inline constexpr bool kSplit<16> = true;template<> struct Split<16> { // IQ2_XXSstruct W { int g[8]; int ls; float dw; };- static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ template<bool STAGE_GRID = false>+ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) {const block_iq2_xxs* bq2 = (const block_iq2_xxs*) vbq + kbx;const int q2 = get_int_b2(bq2->qs, iqs);const uint8_t* aux8 = (const uint8_t*) &q2;const uint32_t aux32 = get_int_b2(bq2->qs, iqs + 1);+ const sycl::uint2 *grid_lut;+ if constexpr (STAGE_GRID) grid_lut = (const sycl::uint2 *)s_grid;+ else grid_lut = (const sycl::uint2 *)iq2xxs_grid;W r;#pragma unrollfor (int k0 = 0; k0 < 8; k0 += 2) {- const sycl::uint2 grid_pos =- ((const sycl::uint2 *)iq2xxs_grid)[aux8[k0 / 2]];+ const sycl::uint2 grid_pos = grid_lut[aux8[k0 / 2]];const uint32_t signs = unpack_ksigns(aux32 >> (7 * k0 / 2));const int signs0 = dpct::vectorized_binary<sycl::uchar4>(signs & 0x08040201, 0, std::not_equal_to<>());@@ -801,18 +922,21 @@ struct SplitLs2 {};template<> inline constexpr bool kSplit<17> = true;template<> struct Split<17> : SplitLs2 { // IQ2_XS- static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ template<bool STAGE_GRID = false>+ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) {const block_iq2_xs* bq2 = (const block_iq2_xs*) vbq + kbx;// SYCL port: the codes by shifts, not through a uint16_t* to an int2 (see vec_dot_iq2_xs_q8_1)const uint32_t q2_lo = (uint32_t) get_int_b2(bq2->qs, iqs + 0), q2_hi = (uint32_t) get_int_b2(bq2->qs, iqs + 1);const uint16_t q2[4] = {(uint16_t) q2_lo, (uint16_t) (q2_lo >> 16), (uint16_t) q2_hi, (uint16_t) (q2_hi >> 16)};+ const sycl::uint2 *grid_lut;+ if constexpr (STAGE_GRID) grid_lut = (const sycl::uint2 *)s_grid;+ else grid_lut = (const sycl::uint2 *)iq2xs_grid;W r;r.ls0 = bq2->scales[iqs / 2] & 0x0F;r.ls1 = bq2->scales[iqs / 2] >> 4;#pragma unrollfor (int l0 = 0; l0 < 8; l0 += 2) {- const sycl::uint2 grid_pos =- ((const sycl::uint2 *)iq2xs_grid)[q2[l0 / 2] & 0x1FF];+ const sycl::uint2 grid_pos = grid_lut[q2[l0 / 2] & 0x1FF];const uint32_t signs = unpack_ksigns(q2[l0 / 2] >> 9);const int signs0 = dpct::vectorized_binary<sycl::uchar4>(signs & 0x08040201, 0, std::not_equal_to<>());@@ -830,19 +954,23 @@ template<> struct Split<17> : SplitLs2 { // IQ2_XS};template<> inline constexpr bool kSplit<22> = true;template<> struct Split<22> : SplitLs2 { // IQ2_S- static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ template<bool STAGE_GRID = false>+ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) {const block_iq2_s* bq2 = (const block_iq2_s*) vbq + kbx;const int qs_packed = get_int_b2(bq2->qs, iqs / 2);const uint8_t* qs = (const uint8_t*) &qs_packed;const int qh = bq2->qh[iqs / 2];const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2);const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;+ const uint64_t* grid_lut;+ if constexpr (STAGE_GRID) grid_lut = (const uint64_t*) s_grid;+ else grid_lut = iq2s_grid;W r;r.ls0 = bq2->scales[iqs / 2] & 0x0F;r.ls1 = bq2->scales[iqs / 2] >> 4;#pragma unrollfor (int l0 = 0; l0 < 8; l0 += 2) {- const int* grid_pos = (const int*) (iq2s_grid + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300)));+ const int* grid_pos = (const int*) (grid_lut + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300)));const int signs0 = dpct::vectorized_binary<sycl::uchar4>(((signs_packed_8[l0 / 2] & 0x03) << 7) |((signs_packed_8[l0 / 2] & 0x0C) << 21),@@ -864,7 +992,8 @@ template<> struct Split<22> : SplitLs2 { // IQ2_Stemplate<> inline constexpr bool kSplit<18> = true;template<> struct Split<18> { // IQ3_XXSstruct W { int g[8]; int ls; float dw; };- static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ template<bool STAGE_GRID = false>+ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx;const sycl::int2 q3_packed =sycl::int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1));@@ -902,7 +1031,8 @@ template<> struct Split<18> { // IQ3_XXStemplate<> inline constexpr bool kSplit<21> = true;template<> struct Split<21> { // IQ3_Sstruct W { int g[8]; int ls; float dw; };- static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ template<bool STAGE_GRID = false>+ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;const sycl::int2 qs_packed = sycl::int2(get_int_b2(bq3->qs, iqs + 0),get_int_b2(bq3->qs, iqs + 1));@@ -946,15 +1076,19 @@ template<> struct Split<21> { // IQ3_Stemplate<> inline constexpr bool kSplit<29> = true;template<> struct Split<29> { // IQ1_Mstruct W { int g[8]; float delta[4]; int sc0, sc1; float dw; };- static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ template<bool STAGE_GRID = false>+ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) {const block_iq1_m* bq1 = (const block_iq1_m*) vbq + kbx;const int qs_packed = get_int_b4(bq1->qs, iqs);const uint8_t* qs = (const uint8_t*) &qs_packed;+ const uint32_t* grid_lut;+ if constexpr (STAGE_GRID) grid_lut = s_grid;+ else grid_lut = iq1s_grid_gpu;W r;#pragma unrollfor (int l0 = 0; l0 < 8; l0 += 2) {const int qhl = bq1->qh[2 * iqs + l0 / 4] >> (4 * ((l0 / 2) % 2));- const int grid = iq1s_grid_gpu[qs[l0 / 2] | ((qhl & 0x07) << 8)];+ const int grid = grid_lut[qs[l0 / 2] | ((qhl & 0x07) << 8)];r.g[l0 + 0] = (grid >> 0) & 0x0F0F0F0F;r.g[l0 + 1] = (grid >> 4) & 0x0F0F0F0F;r.delta[l0 / 2] = -1.0f + IQ1M_DELTA - (qhl & 0x08) * (2.0f * IQ1M_DELTA / 0x08);@@ -990,7 +1124,8 @@ template<> struct Split<29> { // IQ1_Mtemplate<> inline constexpr bool kSplit<20> = true;template<> struct Split<20> { // IQ4_NLstruct W { sycl::int2 v[2]; float dw; };- static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ template<bool STAGE_GRID = false>+ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx;W r;#pragma unroll@@ -1014,7 +1149,8 @@ template<> struct Split<20> { // IQ4_NLtemplate<> inline constexpr bool kSplit<23> = true;template<> struct Split<23> { // IQ4_XSstruct W { sycl::int2 v[4]; int ls; float dw; };- static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ template<bool STAGE_GRID = false>+ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {const block_iq4_xs* bq4 = (const block_iq4_xs*) vbq + kbx;W r;#pragma unroll@@ -1041,7 +1177,8 @@ template<> struct Split<23> { // IQ4_XStemplate<> inline constexpr bool kSplit<42> = true;template<> struct Split<42> { // Q2_0struct W { int qx[4], qy[4]; float d2; };- static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ template<bool STAGE_GRID = false>+ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {const block_q2_0* bq2_0 = (const block_q2_0*) vbq + kbx;W r;r.d2 = bq2_0->d;@@ -1076,10 +1213,11 @@ template<> struct Split<42> { // Q2_0// One row against the n <= NC activations x + off[0..n) (n >= 1, warp-uniform; offsets in q8_1 blocks, 32-bit to// spare registers), the whole warp. Per activation this is row_dot: the same calls k, lane-strided the same way,// summed in the same order, then the same warp_sum. Only the weight side moves out of the per-activation loop.-template <int TY, int NC>-__dpct_inline__ void row_dot_multi(const uint8_t *row, const block_q8_1 *x,- const int (&off)[NC], int n, int nb,- int lane, float (&s)[NC]) {+template <int TY, int NC, bool EXACT_N = false, bool STAGE_GRID = false>+__dpct_inline__ void+row_dot_multi(const uint8_t *row, const block_q8_1 *x, const int (&off)[NC],+ int n, int nb, int lane, float (&s)[NC],+ const uint32_t *__restrict__ s_grid = nullptr) {using F = Fmt<TY>;using S = Split<TY>;#pragma unroll@@ -1091,39 +1229,346 @@ __dpct_inline__ void row_dot_multi(const uint8_t *row, const block_q8_1 *x,results in different template instantiations that could not be unified.You may need to adjust the code.*/- const typename S::W w = S::load(row, kbx, iqs);+ const typename S::W w =+ S::template load<STAGE_GRID>(row, kbx, iqs, s_grid);#pragma unrollfor (int c = 0; c < NC; ++c)- if (c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);+ if (EXACT_N || c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);}#pragma unrollfor (int c = 0; c < NC; ++c)- if (c < n) s[c] = warp_sum(s[c]);+ if (EXACT_N || c < n) s[c] = warp_sum(s[c]);+}++// 8-lane sub-warp row dot for K = nb * ipb == 40 (TD == 20, IQ4_NL with n_ff == 640):+// 4 rows per warp (32 rows per 256-thread block), 100% active lanes, bitwise identical addition tree to row_dot_multi.+template <int TY, int NC, bool EXACT_N = false>+/*+DPCT1110: The total declared local variable size in device function+row_dot_40_sub8 exceeds 128 bytes and may cause high register pressure. Consult+with your hardware vendor to find the total register size available and adjust+the code, or use smaller sub-group size to avoid high register pressure.+*/+__dpct_inline__ void row_dot_40_sub8(const uint8_t *row, const block_q8_1 *x,+ const int (&off)[NC], int n, int t,+ float (&s)[NC]) {+ using F = Fmt<TY>;+ using S = Split<TY>;+#pragma unroll+ for (int c = 0; c < NC; ++c) s[c] = 0.0f;+ for (int k = t; k < 40; k += 32) {+ const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+ const typename S::W w = S::load(row, kbx, iqs);+#pragma unroll+ for (int c = 0; c < NC; ++c)+ if (EXACT_N || c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);+ }+ {+ const int k = t + 16, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+ const typename S::W w = S::load(row, kbx, iqs);+#pragma unroll+ for (int c = 0; c < NC; ++c) {+ if (EXACT_N || c < n) {+ float s16 = 0.0f;+ s16 += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);+ /*+ DPCT1013: The rounding mode could not be specified and the+ generated code may have different accuracy than the original+ code. Verify the correctness. SYCL math built-in function+ rounding mode is aligned with OpenCL C 1.2 standard.+ */+ s[c] = s[c] + s16;+ }+ }+ }+ float s8[NC];+#pragma unroll+ for (int c = 0; c < NC; ++c) s8[c] = 0.0f;+ {+ const int k = t + 8, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+ const typename S::W w = S::load(row, kbx, iqs);+#pragma unroll+ for (int c = 0; c < NC; ++c)+ if (EXACT_N || c < n) s8[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);+ }+ {+ const int k = t + 24, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+ const typename S::W w = S::load(row, kbx, iqs);+#pragma unroll+ for (int c = 0; c < NC; ++c) {+ if (EXACT_N || c < n) {+ float s24 = 0.0f;+ s24 += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);+ /*+ DPCT1013: The rounding mode could not be specified and the+ generated code may have different accuracy than the original+ code. Verify the correctness. SYCL math built-in function+ rounding mode is aligned with OpenCL C 1.2 standard.+ */+ s[c] = s[c] + s8[c] + s24;+ }+ }+ }+#pragma unroll+ for (int c = 0; c < NC; ++c) {+ if (EXACT_N || c < n) {+#pragma unroll+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ for (int o = 4; o > 0; o >>= 1) s[c] +=+ dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu,+ sycl::ext::oneapi::this_work_item::get_sub_group(), s[c],+ o);+ }+ }+}++// 16-lane sub-warp row dot for K = nb * ipb == 20 (TD == 42, Q2_0 with n_ff == 640):+// 2 rows per warp (16 rows per 256-thread block), bitwise identical addition tree to row_dot_multi.+template <int TY, int NC, bool EXACT_N = false>+/*+DPCT1110: The total declared local variable size in device function+row_dot_20_sub16 exceeds 128 bytes and may cause high register pressure. Consult+with your hardware vendor to find the total register size available and adjust+the code, or use smaller sub-group size to avoid high register pressure.+*/+__dpct_inline__ void row_dot_20_sub16(const uint8_t *row, const block_q8_1 *x,+ const int (&off)[NC], int n, int t,+ float (&s)[NC]) {+ using F = Fmt<TY>;+ using S = Split<TY>;+#pragma unroll+ for (int c = 0; c < NC; ++c) s[c] = 0.0f;+ {+ const int k = t, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+ const typename S::W w = S::load(row, kbx, iqs);+#pragma unroll+ for (int c = 0; c < NC; ++c)+ if (EXACT_N || c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);+ }+ float s16[NC];+#pragma unroll+ for (int c = 0; c < NC; ++c) s16[c] = 0.0f;+ if (t < 4) {+ const int k = t + 16, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+ const typename S::W w = S::load(row, kbx, iqs);+#pragma unroll+ for (int c = 0; c < NC; ++c)+ if (EXACT_N || c < n) s16[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);+ }+#pragma unroll+ for (int c = 0; c < NC; ++c) {+ if (EXACT_N || c < n) {+ /*+ DPCT1013: The rounding mode could not be specified and the+ generated code may have different accuracy than the original code.+ Verify the correctness. SYCL math built-in function rounding mode is+ aligned with OpenCL C 1.2 standard.+ */+ s[c] = s[c] + s16[c];+#pragma unroll+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ for (int o = 8; o > 0; o >>= 1) s[c] +=+ dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu,+ sycl::ext::oneapi::this_work_item::get_sub_group(), s[c],+ o);+ }+ }+}++// 16-lane sub-warp row dot for K = nb * ipb == 80 (all kSplit gate/up formats with n_embd == 2560):+// 2 rows per warp (16 rows per 256-thread block), 100% active lanes, bitwise identical addition tree to row_dot_multi.+template <int TY, int NC, bool EXACT_N = false, bool STAGE_GRID = false>+/*+DPCT1110: The total declared local variable size in device function+row_dot_80_sub16 exceeds 128 bytes and may cause high register pressure. Consult+with your hardware vendor to find the total register size available and adjust+the code, or use smaller sub-group size to avoid high register pressure.+*/+__dpct_inline__ void+row_dot_80_sub16(const uint8_t *row, const block_q8_1 *x, const int (&off)[NC],+ int n, int t, float (&s)[NC],+ const uint32_t *__restrict__ s_grid = nullptr) {+ using F = Fmt<TY>;+ using S = Split<TY>;+#pragma unroll+ for (int c = 0; c < NC; ++c) s[c] = 0.0f;+ for (int k = t; k < 80; k += 32) {+ const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+ /*+ DPCT1084: The function call "Split::load" has multiple migration+ results in different template instantiations that could not be unified.+ You may need to adjust the code.+ */+ const typename S::W w =+ S::template load<STAGE_GRID>(row, kbx, iqs, s_grid);+#pragma unroll+ for (int c = 0; c < NC; ++c)+ if (EXACT_N || c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);+ }+ float s16[NC];+#pragma unroll+ for (int c = 0; c < NC; ++c) s16[c] = 0.0f;+ for (int k = t + 16; k < 64; k += 32) {+ const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+ /*+ DPCT1084: The function call "Split::load" has multiple migration+ results in different template instantiations that could not be unified.+ You may need to adjust the code.+ */+ const typename S::W w =+ S::template load<STAGE_GRID>(row, kbx, iqs, s_grid);+#pragma unroll+ for (int c = 0; c < NC; ++c)+ if (EXACT_N || c < n) s16[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);+ }+#pragma unroll+ for (int c = 0; c < NC; ++c) {+ if (EXACT_N || c < n) {+ /*+ DPCT1013: The rounding mode could not be specified and the+ generated code may have different accuracy than the original code.+ Verify the correctness. SYCL math built-in function rounding mode is+ aligned with OpenCL C 1.2 standard.+ */+ s[c] = s[c] + s16[c];+#pragma unroll+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ for (int o = 8; o > 0; o >>= 1) s[c] +=+ dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu,+ sycl::ext::oneapi::this_work_item::get_sub_group(), s[c],+ o);+ }+ }+}++template <int TY, bool STAGE_GRID = kStageIqGrid<TY>>+__dpct_inline__ const uint32_t *+stage_iq_grid(uint32_t *s_buf, int tid, int nthreads) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ if constexpr (!STAGE_GRID) {+ return nullptr;+ } else if constexpr (TY == 16) {+ sycl::uint2 *dst = (sycl::uint2 *)s_buf;+ const sycl::uint2 *src = (const sycl::uint2 *)iq2xxs_grid;+#pragma unroll+ for (int i = tid; i < 256; i += nthreads) dst[i] = src[i];+ /*+ 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.+ */+ item_ct1.barrier();+ return s_buf;+ } else if constexpr (TY == 17) {+ sycl::uint2 *dst = (sycl::uint2 *)s_buf;+ const sycl::uint2 *src = (const sycl::uint2 *)iq2xs_grid;+#pragma unroll+ for (int i = tid; i < 512; i += nthreads) dst[i] = src[i];+ /*+ 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.+ */+ item_ct1.barrier();+ return s_buf;+ } else if constexpr (TY == 22) {+ sycl::uint2 *dst = (sycl::uint2 *)s_buf;+ const sycl::uint2 *src = (const sycl::uint2 *)iq2s_grid;+#pragma unroll+ for (int i = tid; i < 1024; i += nthreads) dst[i] = src[i];+ /*+ 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.+ */+ item_ct1.barrier();+ return s_buf;+ } else if constexpr (TY == 29) {+ sycl::uint2 *dst = (sycl::uint2 *)s_buf;+ const sycl::uint2 *src = (const sycl::uint2 *)iq1s_grid_gpu;+#pragma unroll+ for (int i = tid; i < 1024; i += nthreads) dst[i] = src[i];+ /*+ 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.+ */+ item_ct1.barrier();+ return s_buf;+ } else {+ return nullptr;+ }}+template<int TY, bool STAGE_GRID = kStageIqGrid<TY>>+struct IqGridWords {+ static constexpr int value = !STAGE_GRID ? 4 : (TY == 22 || TY == 29) ? 2048 : (TY == 17) ? 1024 : (TY == 16) ? 512 : 4;+};+// mmvq_kernel with the columns taken NC at a time. After warp_sum every lane holds the same sum, so lane c stores// column c.-template <int TY, int NC>+// #778: `__shared__ alignas(16)` does not compile for gfx1030 (HIP); the attribute after the declarator does, but nvcc+// with MSVC as host does not take it. Same layout either way.+#if defined(__HIPCC__)+#define STRATA_SHARED_ALIGN16_U32(name, ...) __shared__ uint32_t name[__VA_ARGS__] __attribute__((aligned(16)))+#else+#define STRATA_SHARED_ALIGN16_U32(name, ...) alignas(16) uint32_t name[__VA_ARGS__]+#endif+template <int TY, int NC, bool STAGE_GRID = kStageIqGrid<TY>,+ bool EXACT_N = false>__dpct_inline__ voidmmvq_multi_kernel(const uint8_t *__restrict__ w, size_t row_bytes,const block_q8_1 *__restrict__ x, float *__restrict__ y,int n_in, int n_out, int ncols) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+auto &s_grid_buf = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ uint32_t[IqGridWords<TY, STAGE_GRID>::value]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const uint32_t *s_grid = stage_iq_grid<TY, STAGE_GRID>(+ s_grid_buf, item_ct1.get_local_id(1) * 32 + item_ct1.get_local_id(2),+ 128);const int row = item_ct1.get_group(2) * 4 + item_ct1.get_local_id(1);if (row >= n_out) return;const int lane = item_ct1.get_local_id(2);const int nb = n_in / Fmt<TY>::qk, xb = n_in / 32;const uint8_t* wr = w + (size_t) row * row_bytes;- for (int c0 = 0; c0 < ncols; c0 += NC) {- const int n = sycl::min(NC, ncols - c0);+ if constexpr (EXACT_N) {int off[NC];#pragma unroll- for (int c = 0; c < NC; ++c) off[c] = (c0 + sycl::min(c, n - 1)) * xb;+ for (int c = 0; c < NC; ++c) off[c] = c * xb;float s[NC];- row_dot_multi<TY, NC>(wr, x, off, n, nb, lane, s);+ row_dot_multi<TY, NC, true, STAGE_GRID>(wr, x, off, NC, nb, lane, s, s_grid);#pragma unrollfor (int c = 0; c < NC; ++c)- if (c < n && lane == c) y[(size_t) (c0 + c) * n_out + row] = s[c];+ if (lane == c) y[(size_t) c * n_out + row] = s[c];+ } else {+ for (int c0 = 0; c0 < ncols; c0 += NC) {+ const int n = sycl::min(NC, ncols - c0);+ int off[NC];+#pragma unroll+ for (int c = 0; c < NC; ++c)+ off[c] = (c0 + sycl::min(c, n - 1)) * xb;+ float s[NC];+ row_dot_multi<TY, NC, false, STAGE_GRID>(wr, x, off, n, nb, lane, s, s_grid);+#pragma unroll+ for (int c = 0; c < NC; ++c)+ if (c < n && lane == c) y[(size_t) (c0 + c) * n_out + row] = s[c];+ }}}@@ -1412,13 +1857,73 @@ __dpct_inline__ void native_gu_kernel(// has halves of <= 4), so 4 takes such windows in one pass; 8 would take ~64-80 registers against ~48 (ptxas -v).constexpr int GRP_NC = 4;-template <int TG>+template <int TG, bool STAGE_GRID = kStageIqGrid<TG>, bool SUB16 = true>+/*+DPCT1110: The total declared local variable size in device function+native_gu_multi_kernel exceeds 128 bytes and may cause high register pressure.+Consult with your hardware vendor to find the total register size available and+adjust the code, or use smaller sub-group size to avoid high register pressure.+*/__dpct_inline__ void native_gu_multi_kernel(const unsigned long long *__restrict__ grp_ptr,const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,const int32_t *__restrict__ ent_tok, const block_q8_1 *__restrict__ xq,NativeExpertLayout L, float *__restrict__ gate, float *__restrict__ up) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int ng = *n_groups;+ if (item_ct1.get_group(1) >= ng) return;+ auto &s_grid_buf = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ uint32_t[IqGridWords<TG, STAGE_GRID>::value]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const uint32_t *s_grid = stage_iq_grid<TG, STAGE_GRID>(+ s_grid_buf, item_ct1.get_local_id(2), 256);+ const int nb = (int) (L.n_embd / Fmt<TG>::qk), xb = (int) (L.n_embd / 32);+ if constexpr (SUB16) {+ if (xb == 80) {+ const int subwarp = item_ct1.get_local_id(2) >> 4,+ t = item_ct1.get_local_id(2) & 15;+ const int row = item_ct1.get_group(2) * 16 + subwarp; // 0 .. 2*n_ff+ if (row >= 2 * L.n_ff) return;+ const bool is_up = row >= L.n_ff;+ const int r = is_up ? row - (int) L.n_ff : row;+ const size_t w_off = (is_up ? L.up_off : 0) + (size_t) r * L.gu_row;+ float* dst = is_up ? up : gate;+ for (int g = item_ct1.get_group(1); g < ng;+ g += item_ct1.get_group_range(1)) {+ const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ for (int e = e0; e < e1; e += GRP_NC) {+ const int n = sycl::min(GRP_NC, e1 - e);+ if (n == 1) {+ const int off1[1] = { ent_tok[e] * 80 };+ float s1[1];+ row_dot_80_sub16<TG, 1, true, STAGE_GRID>(+ wr, xq, off1, 1, t, s1, s_grid);+ if (t == 0) dst[(size_t) e * L.n_ff + r] = s1[0];+ } else if (n == 2) {+ const int off2[2] = { ent_tok[e] * 80, ent_tok[e + 1] * 80 };+ float s2[2];+ row_dot_80_sub16<TG, 2, true, STAGE_GRID>(+ wr, xq, off2, 2, t, s2, s_grid);+ if (t < 2) dst[(size_t) (e + t) * L.n_ff + r] = s2[t];+ } else if (n == 3) {+ const int off3[3] = { ent_tok[e] * 80, ent_tok[e + 1] * 80, ent_tok[e + 2] * 80 };+ float s3[3];+ row_dot_80_sub16<TG, 3, true, STAGE_GRID>(+ wr, xq, off3, 3, t, s3, s_grid);+ if (t < 3) dst[(size_t) (e + t) * L.n_ff + r] = s3[t];+ } else {+ const int off4[4] = { ent_tok[e] * 80, ent_tok[e + 1] * 80, ent_tok[e + 2] * 80, ent_tok[e + 3] * 80 };+ float s4[4];+ row_dot_80_sub16<TG, 4, true, STAGE_GRID>(+ wr, xq, off4, 4, t, s4, s_grid);+ if (t < 4) dst[(size_t) (e + t) * L.n_ff + r] = s4[t];+ }+ }+ }+ return;+ }+ }const int warp = item_ct1.get_local_id(2) >> 5,lane = item_ct1.get_local_id(2) & 31;const int row = item_ct1.get_group(2) * GU_ROWS + warp; // 0 .. 2*n_ff@@ -1426,9 +1931,7 @@ __dpct_inline__ void native_gu_multi_kernel(const bool is_up = row >= L.n_ff;const int r = is_up ? row - (int) L.n_ff : row;const size_t w_off = (is_up ? L.up_off : 0) + (size_t) r * L.gu_row;- const int nb = (int) (L.n_embd / Fmt<TG>::qk), xb = (int) (L.n_embd / 32);float* dst = is_up ? up : gate;- const int ng = *n_groups;for (int g = item_ct1.get_group(1); g < ng;g +=item_ct1.get_group_range(1)) { // the group stride, as native_gu_kernel@@ -1436,15 +1939,31 @@ __dpct_inline__ void native_gu_multi_kernel(const int e0 = grp_start[g], e1 = grp_start[g + 1];for (int e = e0; e < e1; e += GRP_NC) {const int n = sycl::min(GRP_NC, e1 - e);- int off[GRP_NC];-#pragma unroll- for (int c = 0; c < GRP_NC; ++c)- off[c] = ent_tok[e + sycl::min(c, n - 1)] * xb;- float s[GRP_NC];- row_dot_multi<TG, GRP_NC>(wr, xq, off, n, nb, lane, s);-#pragma unroll- for (int c = 0; c < GRP_NC; ++c)- if (c < n && lane == c) dst[(size_t) (e + c) * L.n_ff + r] = s[c];+ if (n == 1) {+ const int off1[1] = { ent_tok[e] * xb };+ float s1[1];+ row_dot_multi<TG, 1, true, STAGE_GRID>(+ wr, xq, off1, 1, nb, lane, s1, s_grid);+ if (lane == 0) dst[(size_t) e * L.n_ff + r] = s1[0];+ } else if (n == 2) {+ const int off2[2] = { ent_tok[e] * xb, ent_tok[e + 1] * xb };+ float s2[2];+ row_dot_multi<TG, 2, true, STAGE_GRID>(+ wr, xq, off2, 2, nb, lane, s2, s_grid);+ if (lane < 2) dst[(size_t) (e + lane) * L.n_ff + r] = s2[lane];+ } else if (n == 3) {+ const int off3[3] = { ent_tok[e] * xb, ent_tok[e + 1] * xb, ent_tok[e + 2] * xb };+ float s3[3];+ row_dot_multi<TG, 3, true, STAGE_GRID>(+ wr, xq, off3, 3, nb, lane, s3, s_grid);+ if (lane < 3) dst[(size_t) (e + lane) * L.n_ff + r] = s3[lane];+ } else {+ const int off4[4] = { ent_tok[e] * xb, ent_tok[e + 1] * xb, ent_tok[e + 2] * xb, ent_tok[e + 3] * xb };+ float s4[4];+ row_dot_multi<TG, 4, true, STAGE_GRID>(+ wr, xq, off4, 4, nb, lane, s4, s_grid);+ if (lane < 4) dst[(size_t) (e + lane) * L.n_ff + r] = s4[lane];+ }}}}@@ -1505,36 +2024,254 @@ __dpct_inline__ void native_down_kernel(}// native_down_kernel with the entries taken GRP_NC at a time-template <int TD>+template <int TD, bool SUB_DOWN = true>+/*+DPCT1110: The total declared local variable size in device function+native_down_multi_kernel exceeds 128 bytes and may cause high register pressure.+Consult with your hardware vendor to find the total register size available and+adjust the code, or use smaller sub-group size to avoid high register pressure.+*/__dpct_inline__ void native_down_multi_kernel(const unsigned long long *__restrict__ grp_ptr,const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,const int32_t *__restrict__ ent_dst, const block_q8_1 *__restrict__ hq,NativeExpertLayout L, float *__restrict__ out) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int ng = *n_groups;+ if (item_ct1.get_group(1) >= ng) return;+ auto &s_hq_buf = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ uint32_t[GRP_NC * 20 * 9]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const int nb = (int) (L.n_ff / Fmt<TD>::qk), hb = (int) (L.n_ff / 32);+ if constexpr (SUB_DOWN && TD == 20) {+ if (hb == 20) {+ const int r =+ item_ct1.get_group(2) * 32 + (item_ct1.get_local_id(2) >> 3);+ const int t = item_ct1.get_local_id(2) & 7;+ const bool valid_r = (r < L.n_embd);+ const size_t w_off = L.down_off + (size_t) (valid_r ? r : 0) * L.d_row;+ const block_q8_1* s_hq = reinterpret_cast<const block_q8_1*>(s_hq_buf);+ for (int g = item_ct1.get_group(1); g < ng;+ g += item_ct1.get_group_range(1)) {+ const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ for (int e = e0; e < e1; e += GRP_NC) {+ const int n = sycl::min(GRP_NC, e1 - e);+ const uint32_t* src = reinterpret_cast<const uint32_t*>(hq + (size_t) e * 20);+ const int words = n * (20 * 9);+ /*+ DPCT1118: SYCL group functions and algorithms must be+ encountered in converged control flow. You may need to+ adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+#pragma unroll+ for (int i = item_ct1.get_local_id(2); i < words; i += 256)+ s_hq_buf[i] = src[i];+ /*+ DPCT1118: SYCL group functions and algorithms must be+ encountered in converged control flow. You may need to+ adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ if (valid_r) {+ if (n == 1) {+ const int off1[1] = { 0 };+ float s1[1];+ row_dot_40_sub8<TD, 1, true>(wr, s_hq, off1, 1, t,+ s1);+ if (t == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0];+ } else if (n == 2) {+ const int off2[2] = { 0, 20 };+ float s2[2];+ row_dot_40_sub8<TD, 2, true>(wr, s_hq, off2, 2, t,+ s2);+ if (t < 2) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s2[t];+ } else if (n == 3) {+ const int off3[3] = { 0, 20, 40 };+ float s3[3];+ row_dot_40_sub8<TD, 3, true>(wr, s_hq, off3, 3, t,+ s3);+ if (t < 3) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s3[t];+ } else {+ const int off4[4] = { 0, 20, 40, 60 };+ float s4[4];+ row_dot_40_sub8<TD, 4, true>(wr, s_hq, off4, 4, t,+ s4);+ if (t < 4) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s4[t];+ }+ }+ }+ }+ return;+ }+ } else if constexpr (SUB_DOWN && TD == 42) {+ if (hb == 20) {+ const int r =+ item_ct1.get_group(2) * 16 + (item_ct1.get_local_id(2) >> 4);+ const int t = item_ct1.get_local_id(2) & 15;+ const bool valid_r = (r < L.n_embd);+ const size_t w_off = L.down_off + (size_t) (valid_r ? r : 0) * L.d_row;+ const block_q8_1* s_hq = reinterpret_cast<const block_q8_1*>(s_hq_buf);+ for (int g = item_ct1.get_group(1); g < ng;+ g += item_ct1.get_group_range(1)) {+ const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ for (int e = e0; e < e1; e += GRP_NC) {+ const int n = sycl::min(GRP_NC, e1 - e);+ const uint32_t* src = reinterpret_cast<const uint32_t*>(hq + (size_t) e * 20);+ const int words = n * (20 * 9);+ /*+ DPCT1118: SYCL group functions and algorithms must be+ encountered in converged control flow. You may need to+ adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+#pragma unroll+ for (int i = item_ct1.get_local_id(2); i < words; i += 256)+ s_hq_buf[i] = src[i];+ /*+ DPCT1118: SYCL group functions and algorithms must be+ encountered in converged control flow. You may need to+ adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ if (valid_r) {+ if (n == 1) {+ const int off1[1] = { 0 };+ float s1[1];+ row_dot_20_sub16<TD, 1, true>(wr, s_hq, off1, 1, t, s1);+ if (t == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0];+ } else if (n == 2) {+ const int off2[2] = { 0, 20 };+ float s2[2];+ row_dot_20_sub16<TD, 2, true>(wr, s_hq, off2, 2, t, s2);+ if (t < 2) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s2[t];+ } else if (n == 3) {+ const int off3[3] = { 0, 20, 40 };+ float s3[3];+ row_dot_20_sub16<TD, 3, true>(wr, s_hq, off3, 3, t, s3);+ if (t < 3) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s3[t];+ } else {+ const int off4[4] = { 0, 20, 40, 60 };+ float s4[4];+ row_dot_20_sub16<TD, 4, true>(wr, s_hq, off4, 4, t, s4);+ if (t < 4) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s4[t];+ }+ }+ }+ }+ return;+ }+ }const int warp = item_ct1.get_local_id(2) >> 5,lane = item_ct1.get_local_id(2) & 31;const int r = item_ct1.get_group(2) * 8 + warp;- if (r >= L.n_embd) return;- const size_t w_off = L.down_off + (size_t) r * L.d_row;- const int nb = (int) (L.n_ff / Fmt<TD>::qk), hb = (int) (L.n_ff / 32);- const int ng = *n_groups;+ const bool valid_r = (r < L.n_embd);+ const size_t w_off = L.down_off + (size_t) (valid_r ? r : 0) * L.d_row;for (int g = item_ct1.get_group(1); g < ng;g +=item_ct1.get_group_range(1)) { // the group stride, as native_gu_kernelconst uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;const int e0 = grp_start[g], e1 = grp_start[g + 1];- for (int e = e0; e < e1; e += GRP_NC) {- const int n = sycl::min(GRP_NC, e1 - e);- int off[GRP_NC];+ if (hb == 20) {+ const block_q8_1* s_hq = reinterpret_cast<const block_q8_1*>(s_hq_buf);+ for (int e = e0; e < e1; e += GRP_NC) {+ const int n = sycl::min(GRP_NC, e1 - e);+ const uint32_t* src = reinterpret_cast<const uint32_t*>(hq + (size_t) e * 20);+ const int words = n * (20 * 9);+ /*+ DPCT1118: SYCL group functions and algorithms must be+ encountered in converged control flow. You may need to adjust+ the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();#pragma unroll- for (int c = 0; c < GRP_NC; ++c)- off[c] = (e + sycl::min(c, n - 1)) * hb;- float s[GRP_NC];- row_dot_multi<TD, GRP_NC>(wr, hq, off, n, nb, lane, s);+ for (int i = item_ct1.get_local_id(2); i < words; i += 256)+ s_hq_buf[i] = src[i];+ /*+ DPCT1118: SYCL group functions and algorithms must be+ encountered in converged control flow. You may need to adjust+ the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ if (valid_r) {+ if (n == 1) {+ const int off1[1] = { 0 };+ float s1[1];+ row_dot_multi<TD, 1, true>(wr, s_hq, off1, 1, nb, lane,+ s1);+ if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0];+ } else if (n == 2) {+ const int off2[2] = { 0, 20 };+ float s2[2];+ row_dot_multi<TD, 2, true>(wr, s_hq, off2, 2, nb, lane,+ s2);+ if (lane < 2) out[(size_t) ent_dst[e + lane] * L.n_embd + r] = s2[lane];+ } else {+ int off[GRP_NC];#pragma unroll- for (int c = 0; c < GRP_NC; ++c)- if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c];+ for (int c = 0; c < GRP_NC; ++c)+ off[c] = sycl::min(c, n - 1) * 20;+ float s[GRP_NC];+ row_dot_multi<TD, GRP_NC>(wr, s_hq, off, n, nb, lane, s);+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c];+ }+ }+ }+ } else if (valid_r) {+ for (int e = e0; e < e1; e += GRP_NC) {+ const int n = sycl::min(GRP_NC, e1 - e);+ int off[GRP_NC];+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ off[c] = (e + sycl::min(c, n - 1)) * hb;+ float s[GRP_NC];+ row_dot_multi<TD, GRP_NC>(wr, hq, off, n, nb, lane, s);+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c];+ }}}}@@ -1611,10 +2348,10 @@ __dpct_inline__ void swiglu_q8_1_entries_kernel(const float h = (g / (1.0f + __expf(-g))) * up[i];#else/*- DPCT1013: The rounding mode could not be specified and the- generated code may have different accuracy than the original code.- Verify the correctness. SYCL math built-in function rounding mode is- aligned with OpenCL C 1.2 standard.+ DPCT1013: The rounding mode could not be specified and the generated+ code may have different accuracy than the original code. Verify the+ correctness. SYCL math built-in function rounding mode is aligned with+ OpenCL C 1.2 standard.*/const float h = (g / (1.0f + sycl::native::exp(-g))) * up[i];#endif@@ -1894,6 +2631,32 @@ inline void dq_q5_0(const void *vx, int64_t ibs, dst_t *yy, int tid) {}}template <typename dst_t>+inline void dq_q4_0(const void *vx, int64_t ibs, dst_t *yy, int tid) {+ const block_q4_0* x = (const block_q4_0*) vx + ibs * (QK_K / QK4_0);+ const int ib = tid % 8, il = tid / 8;+ const float d = sycl::vec<sycl::half, 1>(x[ib].d)+ .convert<float, sycl::rounding_mode::automatic>()[0];+ dst_t* y = yy + 32 * ib;+ for (int j = 0; j < 4; ++j) {+ const int iqs = 4 * il + j; // llama.cpp's dequantize_q4_0 for value pairs iqs, iqs + 16+ y[iqs] = cvt<dst_t>(((float) (x[ib].qs[iqs] & 0xf) - 8.0f) * d);+ y[iqs + 16] = cvt<dst_t>(((float) (x[ib].qs[iqs] >> 4) - 8.0f) * d);+ }+}+template <typename dst_t>+inline void dq_q4_1(const void *vx, int64_t ibs, dst_t *yy, int tid) {+ const block_q4_1* x = (const block_q4_1*) vx + ibs * (QK_K / QK4_1);+ const int ib = tid % 8, il = tid / 8;+ const sycl::float2 dm =+ (x[ib].dm).template convert<float, sycl::rounding_mode::automatic>();+ dst_t* y = yy + 32 * ib;+ for (int j = 0; j < 4; ++j) {+ const int iqs = 4 * il + j; // llama.cpp's dequantize_q4_1 for value pairs iqs, iqs + 16+ y[iqs] = cvt<dst_t>((float)(x[ib].qs[iqs] & 0xf) * dm.x() + dm.y());+ y[iqs + 16] = cvt<dst_t>((float)(x[ib].qs[iqs] >> 4) * dm.x() + dm.y());+ }+}+template <typename dst_t>inline void dq_q5_1(const void *vx, int64_t ibs, dst_t *yy, int tid) {const block_q5_1* x = (const block_q5_1*) vx + ibs * (QK_K / QK5_1);const int ib = tid % 8, il = tid / 8;@@ -1912,6 +2675,28 @@ inline void dq_q5_1(const void *vx, int64_t ibs, dst_t *yy, int tid) {cvt<dst_t>((float)((x[ib].qs[iqs] >> 4) | xh_1) * dm.x() + dm.y());}}+template<typename dst_t>+void dq_q6_k(const void* vx, int64_t ibs, dst_t* yy, int tid) {+ // llama.cpp's dequantize_q6_K (dequantize.cuh, written for 64 threads) folded onto the kernel's 32: each of the+ // 64 thread roles runs at tid and tid + 32.+ const block_q6_K* x = (const block_q6_K*) vx;+ for (int tt = tid; tt < 64; tt += 32) {+ const int64_t ip = tt / 32; // 0 or 1+ const int64_t il = tt - 32 * ip; // 0...31+ const int64_t is = 8 * ip + il / 16;+ dst_t* y = yy + 128 * ip + il;+ const float d =+ sycl::vec<sycl::half, 1>(x[ibs].d)+ .convert<float, sycl::rounding_mode::automatic>()[0];+ const uint8_t* ql = x[ibs].ql + 64 * ip + il;+ const uint8_t qh = x[ibs].qh[32 * ip + il];+ const int8_t* sc = x[ibs].scales + is;+ y[0] = cvt<dst_t>(d * sc[0] * ((int8_t) ((ql[0] & 0xF) | (((qh >> 0) & 3) << 4)) - 32));+ y[32] = cvt<dst_t>(d * sc[2] * ((int8_t) ((ql[32] & 0xF) | (((qh >> 2) & 3) << 4)) - 32));+ y[64] = cvt<dst_t>(d * sc[4] * ((int8_t) ((ql[0] >> 4) | (((qh >> 4) & 3) << 4)) - 32));+ y[96] = cvt<dst_t>(d * sc[6] * ((int8_t) ((ql[32] >> 4) | (((qh >> 6) & 3) << 4)) - 32));+ }+}template <typename dst_t>inline void dq_q8_0(const void *vx, int64_t ibs, dst_t *yy, int tid) {const block_q8_0* x = (const block_q8_0*) vx + ibs * (QK_K / QK8_0);@@ -1954,8 +2739,13 @@ dq_dispatch(int ty, const void *vx, int64_t ibs, dst_t *y, int tid) {case 42: dq_q2_0(vx, ibs, y, tid); break;case 12: dq_q4_k(vx, ibs, y, tid); break;case 13: dq_q5_k(vx, ibs, y, tid); break;+#ifdef STRATA_Q6K_EXPERTS+ case 14: dq_q6_k(vx, ibs, y, tid); break;+#endifcase 7: dq_q5_1(vx, ibs, y, tid); break;case 6: dq_q5_0(vx, ibs, y, tid); break;+ case 2: dq_q4_0(vx, ibs, y, tid); break;+ case 3: dq_q4_1(vx, ibs, y, tid); break;case 8: dq_q8_0(vx, ibs, y, tid); break;case 30: dq_bf16(vx, ibs, y, tid); break;default: break;@@ -1986,7 +2776,11 @@ __dpct_inline__ void dequant_gu_kernel(// the types dq_dispatch dequantizesbool is_iq(int t) {return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11 ||- t == 12 || t == 13 || t == 7 || t == 6 || t == 8;+#ifdef STRATA_Q6K_EXPERTS+ t == 12 || t == 13 || t == 14 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8;+#else+ t == 12 || t == 13 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8;+#endif}// values per block of the types the grouped expert kernels take (0 = none)int gu_qk(int t) {@@ -2005,6 +2799,14 @@ int d_qk(int t) {default: return 0;}}+bool gu_split(int t) {+ switch (t) {+#define STRATA_SP(T) case T: return kSplit<T>;+ STRATA_GU_FMTS(STRATA_SP)+#undef STRATA_SP+ default: return false;+ }+}bool env_on(const char* name) {const char* v = std::getenv(name);@@ -2017,96 +2819,246 @@ bool g_old_kernels = env_on("STRATA_OLD_IQ_MMVQ");// dots with aligned loads and the IQ4 codebook in registers) are the measured ones, so they stay the default for// every format; STRATA_EXPERT_SPLIT=1 takes upstream's multi kernels, launched with their own grid (GU_ROWS rows).bool g_split_multi = env_on("STRATA_EXPERT_SPLIT");+bool g_no_sub16_gu = env_on("STRATA_NO_SUB16_GU");+// STRATA_IQ_STAGE_GRID=0 disables staging 64-bit i-quant codebook tables into shared memory+bool g_stage_grid = [] {+ const char* v = std::getenv("STRATA_IQ_STAGE_GRID");+ return v == nullptr || v[0] == '\0' || v[0] != '0';+}();+// The single-matrix mmvq (128-thread blocks, one per 4 rows) pays the 2-8 KB staging per block: on the RTX 5070 its+// IQ2_XS / IQ2_S / IQ1_M calls were 10-20% slower staged at 3-8 columns (iq_multi_parity --bench), while the grouped+// expert kernels gain. So mmvq stages only with STRATA_IQ_STAGE_GRID_MMVQ=1 (bitwise the same either way).+bool g_stage_grid_mmvq = g_stage_grid && [] {+ const char* v = std::getenv("STRATA_IQ_STAGE_GRID_MMVQ");+ return v != nullptr && v[0] == '1';+}();-template <int TY>-void launch_mmvq(const uint8_t *W, size_t rb, const block_q8_1 *X, float *y,- int n_in, int n_out, int ncols, dpct::queue_ptr s) {- const dpct::dim3 grid((unsigned)((n_out + 3) / 4)), block(32, 4);- /*- 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.- Adjust the work-group size if needed.- */- if constexpr (!kSplit<TY>) {+template <int TY, bool STAGE_GRID = kStageIqGrid<TY>>+void launch_mmvq_multi_nc(dpct::dim3 grid, dpct::dim3 block, dpct::queue_ptr s,+ const uint8_t *W, size_t rb, const block_q8_1 *X,+ float *y, int n_in, int n_out, int ncols) {+ switch (ncols) {+ /*+ 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. Adjust the work-group size if needed.+ */+ case 1: {auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};s->submit([&](sycl::handler &cgh) {- cgh.parallel_for<dpct_kernel_name<class mmvq_kernel_87549a,- dpct_kernel_scalar<TY>>>(+ cgh.parallel_for<dpct_kernel_name<+ class mmvq_multi_kernel_8df6c9, dpct_kernel_scalar<TY>,+ dpct_kernel_scalar<1>, dpct_kernel_scalar<STAGE_GRID>,+ dpct_kernel_scalar<true>>>(sycl::nd_range<3>(grid * block, block), exp_props,[=](sycl::nd_item<3> item_ct1)[[sycl::reqd_sub_group_size(32)]] {- mmvq_kernel<TY>(W, rb, X, y, n_in, n_out, ncols);+ mmvq_multi_kernel<TY, 1, STAGE_GRID, true>(+ W, rb, X, y, n_in, n_out, 1);});});- }- /*- 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.- Adjust the work-group size if needed.- */- else if (g_old_kernels) {+ } break;+ /*+ 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. Adjust the work-group size if needed.+ */+ case 2: {auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};s->submit([&](sycl::handler &cgh) {- cgh.parallel_for<dpct_kernel_name<class mmvq_kernel_f617b1,- dpct_kernel_scalar<TY>>>(+ cgh.parallel_for<dpct_kernel_name<+ class mmvq_multi_kernel_9c43f2, dpct_kernel_scalar<TY>,+ dpct_kernel_scalar<2>, dpct_kernel_scalar<STAGE_GRID>,+ dpct_kernel_scalar<true>>>(sycl::nd_range<3>(grid * block, block), exp_props,[=](sycl::nd_item<3> item_ct1)[[sycl::reqd_sub_group_size(32)]] {- mmvq_kernel<TY>(W, rb, X, y, n_in, n_out, ncols);+ mmvq_multi_kernel<TY, 2, STAGE_GRID, true>(+ W, rb, X, y, n_in, n_out, 2);});});- }- /*- 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.- Adjust the work-group size if needed.- */- else if (ncols <= 1) {-+ } break;+ /*+ 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. Adjust the work-group size if needed.+ */+ case 3: {++ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ s->submit([&](sycl::handler &cgh) {++ cgh.parallel_for<dpct_kernel_name<+ class mmvq_multi_kernel_f8d14a, dpct_kernel_scalar<TY>,+ dpct_kernel_scalar<3>, dpct_kernel_scalar<STAGE_GRID>,+ dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(grid * block, block), exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ mmvq_multi_kernel<TY, 3, STAGE_GRID, true>(+ W, rb, X, y, n_in, n_out, 3);+ });+ });+ } break;+ /*+ 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. Adjust the work-group size if needed.+ */+ case 4: {+auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};s->submit([&](sycl::handler &cgh) {- cgh.parallel_for<dpct_kernel_name<class mmvq_multi_kernel_77d6d0,- dpct_kernel_scalar<TY>,- dpct_kernel_scalar<1>>>(+ cgh.parallel_for<dpct_kernel_name<+ class mmvq_multi_kernel_88cd9a, dpct_kernel_scalar<TY>,+ dpct_kernel_scalar<4>, dpct_kernel_scalar<STAGE_GRID>,+ dpct_kernel_scalar<true>>>(sycl::nd_range<3>(grid * block, block), exp_props,[=](sycl::nd_item<3> item_ct1)[[sycl::reqd_sub_group_size(32)]] {- mmvq_multi_kernel<TY, 1>(W, rb, X, y, n_in, n_out,- ncols);+ mmvq_multi_kernel<TY, 4, STAGE_GRID, true>(+ W, rb, X, y, n_in, n_out, 4);});});+ } break;+ /*+ 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. Adjust the work-group size if needed.+ */+ case 5: {++ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ s->submit([&](sycl::handler &cgh) {++ cgh.parallel_for<dpct_kernel_name<+ class mmvq_multi_kernel_d55b02, dpct_kernel_scalar<TY>,+ dpct_kernel_scalar<5>, dpct_kernel_scalar<STAGE_GRID>,+ dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(grid * block, block), exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ mmvq_multi_kernel<TY, 5, STAGE_GRID, true>(+ W, rb, X, y, n_in, n_out, 5);+ });+ });+ } break;+ /*+ 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. Adjust the work-group size if needed.+ */+ case 6: {++ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ s->submit([&](sycl::handler &cgh) {++ cgh.parallel_for<dpct_kernel_name<+ class mmvq_multi_kernel_3404b2, dpct_kernel_scalar<TY>,+ dpct_kernel_scalar<6>, dpct_kernel_scalar<STAGE_GRID>,+ dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(grid * block, block), exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ mmvq_multi_kernel<TY, 6, STAGE_GRID, true>(+ W, rb, X, y, n_in, n_out, 6);+ });+ });+ } break;+ default:+ /*+ 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. Adjust the work-group size if+ needed.+ */+ if (ncols <= 1) {++ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ s->submit([&](sycl::handler &cgh) {++ cgh.parallel_for<dpct_kernel_name<+ class mmvq_multi_kernel_1f7e16, dpct_kernel_scalar<TY>,+ dpct_kernel_scalar<1>, dpct_kernel_scalar<STAGE_GRID>,+ dpct_kernel_scalar<false>>>(+ sycl::nd_range<3>(grid * block, block), exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ mmvq_multi_kernel<TY, 1, STAGE_GRID, false>(+ W, rb, X, y, n_in, n_out, ncols);+ });+ });+ }+ /*+ 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. Adjust the work-group size if+ needed.+ */+ else {++ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ s->submit([&](sycl::handler &cgh) {++ cgh.parallel_for<dpct_kernel_name<+ class mmvq_multi_kernel_95b544, dpct_kernel_scalar<TY>,+ dpct_kernel_scalar<8>, dpct_kernel_scalar<STAGE_GRID>,+ dpct_kernel_scalar<false>>>(+ sycl::nd_range<3>(grid * block, block), exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ mmvq_multi_kernel<TY, 8, STAGE_GRID, false>(+ W, rb, X, y, n_in, n_out, ncols);+ });+ });+ }+ break;}+}++template <int TY>+void launch_mmvq(const uint8_t *W, size_t rb, const block_q8_1 *X, float *y,+ int n_in, int n_out, int ncols, dpct::queue_ptr s) {+ const dpct::dim3 grid((unsigned)((n_out + 3) / 4)), block(32, 4);/*DPCT1049: The work-group size passed to the SYCL kernel may exceed thelimit. To get the device limit, query info::device::max_work_group_size.Adjust the work-group size if needed.*/- else if (ncols == 2) {+ if constexpr (!kSplit<TY>) {auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};s->submit([&](sycl::handler &cgh) {- cgh.parallel_for<dpct_kernel_name<class mmvq_multi_kernel_7ba01c,- dpct_kernel_scalar<TY>,- dpct_kernel_scalar<2>>>(+ cgh.parallel_for<dpct_kernel_name<class mmvq_kernel_c04bb8,+ dpct_kernel_scalar<TY>>>(sycl::nd_range<3>(grid * block, block), exp_props,[=](sycl::nd_item<3> item_ct1)[[sycl::reqd_sub_group_size(32)]] {- mmvq_multi_kernel<TY, 2>(W, rb, X, y, n_in, n_out,- ncols);+ mmvq_kernel<TY>(W, rb, X, y, n_in, n_out, ncols);});});}@@ -2115,49 +3067,1034 @@ void launch_mmvq(const uint8_t *W, size_t rb, const block_q8_1 *X, float *y,limit. To get the device limit, query info::device::max_work_group_size.Adjust the work-group size if needed.*/- else if (ncols <= 4) {+ else if (g_old_kernels) {auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};s->submit([&](sycl::handler &cgh) {- cgh.parallel_for<dpct_kernel_name<class mmvq_multi_kernel_6fd6d9,- dpct_kernel_scalar<TY>,- dpct_kernel_scalar<4>>>(+ cgh.parallel_for<dpct_kernel_name<class mmvq_kernel_18057f,+ dpct_kernel_scalar<TY>>>(sycl::nd_range<3>(grid * block, block), exp_props,[=](sycl::nd_item<3> item_ct1)[[sycl::reqd_sub_group_size(32)]] {- mmvq_multi_kernel<TY, 4>(W, rb, X, y, n_in, n_out,- ncols);+ mmvq_kernel<TY>(W, rb, X, y, n_in, n_out, ncols);});});+ } else if constexpr (kStageIqGrid<TY>) {+ if (!g_stage_grid_mmvq) {+ launch_mmvq_multi_nc<TY, false>(grid, block, s, W, rb, X, y, n_in, n_out, ncols);+ return;+ }+ launch_mmvq_multi_nc<TY, true>(grid, block, s, W, rb, X, y, n_in, n_out, ncols);+ } else {+ launch_mmvq_multi_nc<TY, false>(grid, block, s, W, rb, X, y, n_in, n_out, ncols);}- /*- 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.- Adjust the work-group size if needed.- */- else {+}+++// SYCL port: upstream's opt-in AMD-tuned S26 (STRATA_EXPERT_V2) and S27 (STRATA_EXPERT_V2K) grouped-expert kernels are+// not migrated: dpct cannot name their instantiations and they are tuned for gfx1151. The port's lane kernels below are+// the measured ones for every format; the two switches only print a note.+#if 0+// ---------------------------------------------------------------- S26 STRATA_EXPERT_V2=1 (opt-in): IQ3_S gate/up + IQ4_NL down+// Bitwise equal to native_gu_multi_kernel / native_down_multi_kernel (S26 harness, real UD-IQ4_XS expert blobs, T 1-3,+// memcmp of every output): each row's lane sums and warp_sum are the same; a warp interleaves RPW rows (more loads in+// flight) and reads the chunk's activation rows from LDS and, for IQ3_S, the grid table from LDS (the same values).+#if defined(__HIPCC__)+#define STRATA_NT_LOAD(p) __builtin_nontemporal_load(p)+#else // (opt-in S26 kernels, AMD-tuned: a CUDA build compiles them with plain loads)+#define STRATA_NT_LOAD(p) (*(p))+#endif+template <bool NT> __dpct_inline__ int ld16i(const uint16_t *p) {+ if constexpr (NT) return (int) STRATA_NT_LOAD(p); else return (int) *p;+}+template <bool NT> __dpct_inline__ int ldb2(const void *x, int i32) {+ const uint16_t* x16 = (const uint16_t*) x;+ int x32 = ld16i<NT>(x16 + 2 * i32 + 0) << 0;+ x32 |= ld16i<NT>(x16 + 2 * i32 + 1) << 16;+ return x32;+}+template <bool NT> __dpct_inline__ int ld8i(const uint8_t *p) {+ if constexpr (NT) return (int) STRATA_NT_LOAD(p); else return (int) *p;+}+template <bool NT> __dpct_inline__ float ldhalf(const sycl::half *p) {+ return sycl::vec<sycl::half, 1>(+ sycl::bit_cast<sycl::half, unsigned short>(+ (unsigned short)ld16i<NT>(+ reinterpret_cast<const uint16_t *>(p))))+ .convert<float, sycl::rounding_mode::automatic>()[0];+}+template<int TY, bool NT> struct S26Split;+template<bool NT> struct S26Split<21, NT> { // IQ3_S: Split<21>::load with the loads made explicit+ using W = Split<21>::W;+ static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;+ const sycl::int2 qs_packed =+ make_int2(ldb2<NT>(bq3->qs, iqs + 0), ldb2<NT>(bq3->qs, iqs + 1));+ const uint8_t* qs = (const uint8_t*) &qs_packed;+ const int qh = ld8i<NT>(bq3->qh + iqs / 2);+ const int signs_packed_32 = ldb2<NT>(bq3->signs, iqs / 2);+ const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;+ W r;+#pragma unroll+ for (int l0 = 0; l0 < 8; l0 += 2) {+ const sycl::int2 grid_pos =+ sycl::int2(iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)],+ iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]);+ const int signs0 = dpct::vectorized_binary<sycl::uchar4>(+ ((signs_packed_8[l0 / 2] & 0x03) << 7) |+ ((signs_packed_8[l0 / 2] & 0x0C) << 21),+ 0x00000000, std::not_equal_to<>());+ const int signs1 = dpct::vectorized_binary<sycl::uchar4>(+ ((signs_packed_8[l0 / 2] & 0x30) << 3) |+ ((signs_packed_8[l0 / 2] & 0xC0) << 17),+ 0x00000000, std::not_equal_to<>());+ r.g[l0 + 0] = dpct::vectorized_binary<sycl::uchar4>(+ grid_pos.x() ^ signs0, signs0, std::minus<>());+ r.g[l0 + 1] = dpct::vectorized_binary<sycl::uchar4>(+ grid_pos.y() ^ signs1, signs1, std::minus<>());+ }+ r.ls = 1 + 2 * ((ld8i<NT>(bq3->scales + iqs / 4) >> ((iqs << 1) & 0x04)) & 0x0F);+ r.dw = ldhalf<NT>(&bq3->d);+ return r;+ }+ static float apply(const W& r, const block_q8_1* __restrict__ b, int iqs) { return Split<21>::apply(r, b, iqs); }+};+template<bool NT> struct S26Split<20, NT> { // IQ4_NL+ using W = Split<20>::W;+ static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx;+ W r;+#pragma unroll+ for (int l = 0; l < 2; ++l) r.v[l] = get_int_from_table_16(ldb2<NT>(bq4->qs, iqs + l), kvalues_iq4nl);+ r.dw = ldhalf<NT>(&bq4->d);+ return r;+ }+ static float apply(const W& r, const block_q8_1* __restrict__ b, int iqs) { return Split<20>::apply(r, b, iqs); }+};++// S26 v13+: v6 (4 interleaved rows per warp) with the IQ3_S grid table (LT) and / or the chunk's activation rows (LX)+// read from LDS: the same table values and the same q8_1 bytes, so the same arithmetic and bits.+struct S26IQ3S { // Split<21>::load with the grid from `grid` (LT) or iq3s_grid itself+ using W = Split<21>::W;+ template<bool LT = true>+ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* grid) {+ const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;+ const sycl::int2 qs_packed = sycl::int2(get_int_b2(bq3->qs, iqs + 0),+ get_int_b2(bq3->qs, iqs + 1));+ const uint8_t* qs = (const uint8_t*) &qs_packed;+ const int qh = bq3->qh[iqs / 2];+ const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2);+ const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;+ W r;+#pragma unroll+ for (int l0 = 0; l0 < 8; l0 += 2) {+ const int i0 = qs[l0 + 0] | ((qh << (8 - l0)) & 0x100), i1 = qs[l0 + 1] | ((qh << (7 - l0)) & 0x100);+ const sycl::int2 grid_pos =+ LT ? sycl::int2(grid[i0], grid[i1])+ : sycl::int2(iq3s_grid[i0], iq3s_grid[i1]);+ const int signs0 = dpct::vectorized_binary<sycl::uchar4>(+ ((signs_packed_8[l0 / 2] & 0x03) << 7) |+ ((signs_packed_8[l0 / 2] & 0x0C) << 21),+ 0x00000000, std::not_equal_to<>());+ const int signs1 = dpct::vectorized_binary<sycl::uchar4>(+ ((signs_packed_8[l0 / 2] & 0x30) << 3) |+ ((signs_packed_8[l0 / 2] & 0xC0) << 17),+ 0x00000000, std::not_equal_to<>());+ r.g[l0 + 0] = dpct::vectorized_binary<sycl::uchar4>(+ grid_pos.x() ^ signs0, signs0, std::minus<>());+ r.g[l0 + 1] = dpct::vectorized_binary<sycl::uchar4>(+ grid_pos.y() ^ signs1, signs1, std::minus<>());+ }+ r.ls = 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F);+ r.dw = sycl::vec<sycl::half, 1>(bq3->d)+ .convert<float, sycl::rounding_mode::automatic>()[0];+ return r;+ }+};++constexpr int S26_XMAX = 2560 / 32; // q8_1 blocks of one activation row (n_embd 2560)++// S26 BAL: step I of a warp's RPW x NI items (item p = 32 I + lane): rows QA / QB (lanes >= THR take QB)+template<int I, int NI, int RPW> struct S26Bal {+ static constexpr int P0 = 32 * I, QA = P0 / NI, QB0 = (P0 + 31) / NI, QB = QB0 < RPW ? QB0 : RPW - 1;+ static constexpr int THR = (QA + 1) * NI - P0;+ static_assert(NI >= 32, "a step spans at most two rows");+};++template <bool LT, bool LX, int RPW, bool SL = false, bool TS = false>+/*+DPCT1110: The total declared local variable size in device function+s26_gu_l_kernel exceeds 128 bytes and may cause high register pressure. Consult+with your hardware vendor to find the total register size available and adjust+the code, or use smaller sub-group size to avoid high register pressure.+*/+__dpct_inline__ void s26_gu_l_kernel(+ const unsigned long long *__restrict__ grp_ptr,+ const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,+ const int32_t *__restrict__ ent_tok, const block_q8_1 *__restrict__ xq,+ NativeExpertLayout L, float *__restrict__ gate, float *__restrict__ up) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+auto &s_grid = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ uint32_t[LT ? 512 : 1]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &s_x = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ block_q8_1[LX ? GRP_NC * S26_XMAX : 1]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const int g = item_ct1.get_group(1);+ if (g >= *n_groups) return;+ if constexpr (LT)+#pragma unroll+ for (int i = item_ct1.get_local_id(2); i < 512; i += 256)+ s_grid[i] = iq3s_grid[i];+ const int warp = item_ct1.get_local_id(2) >> 5,+ lane = item_ct1.get_local_id(2) & 31;+ const int row0 = item_ct1.get_group(2) * GU_ROWS * RPW + warp;+ const bool live = row0 + GU_ROWS * (RPW - 1) < 2 * L.n_ff;+ const uint8_t* blob = (const uint8_t*) grp_ptr[g];+ const uint8_t* wr[RPW];+ int rr[RPW];+ bool upq[RPW];+#pragma unroll+ for (int q = 0; q < RPW; ++q) {+ const int row = row0 + q * GU_ROWS;+ upq[q] = row >= L.n_ff;+ rr[q] = upq[q] ? row - (int) L.n_ff : row;+ wr[q] = blob + (upq[q] ? L.up_off : 0) + (size_t) rr[q] * L.gu_row;+ }+ const uint32_t* grid = LT ? s_grid : reinterpret_cast<const uint32_t*>(iq3s_grid);+ const int nb = (int) (L.n_embd / 256), xb = (int) (L.n_embd / 32);+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ for (int e = e0; e < e1; e += GRP_NC) {+ const int n = sycl::min(GRP_NC, e1 - e);+ const block_q8_1* xbase = xq;+ int off[GRP_NC];+ if constexpr (LX) {+ /*+ DPCT1118: SYCL group functions and algorithms must be+ encountered in converged control flow. You may need to adjust the+ code.+ */+ /*+ 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.+ */+ item_ct1.barrier(); // the previous chunk is done with s_x+ for (int i = item_ct1.get_local_id(2); i < n * xb; i += 256) {+ const int c = i / xb, j = i - c * xb;+ memcpy(&s_x[c * S26_XMAX + j], &xq[(size_t) ent_tok[e + c] * xb + j], sizeof(s_x[0]));+ }+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ off[c] = sycl::min(c, n - 1) * S26_XMAX;+ xbase = s_x;+ } else {+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ off[c] = ent_tok[e + sycl::min(c, n - 1)] * xb;+ }+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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 constexpr (LT || LX) item_ct1.barrier(); // s_grid / s_x ready+ if (!live) continue;+ float s[RPW][GRP_NC];+#pragma unroll+ for (int q = 0; q < RPW; ++q)+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f;+ for (int k = lane; k < nb * 8; k += 32) {+ const int kbx = k / 8, iqs = 2 * (k % 8);+ Split<21>::W w[RPW];+#pragma unroll+ for (int q = 0; q < RPW; ++q) {+ if constexpr (SL && !LT) w[q] =+ S26Split<21, false>::load(wr[q], kbx, iqs);+ else w[q] = S26IQ3S::load<LT>(wr[q], kbx, iqs, grid);+ }+#pragma unroll+ for (int q = 0; q < RPW; ++q)+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n) s[q][c] += Split<21>::apply(w[q], xbase + off[c] + kbx * 8, iqs);+ }+ if constexpr (TS) { // S26: all RPW x GRP_NC sums in one transposed butterfly (bitwise the same sums)+ constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC);+ float v[P];+#pragma unroll+ for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f;+ const float sum = s26ts::tsum<P>(v, lane);+ const int j = s26ts::tsum_token<P>(lane);+ if (lane == s26ts::tsum_lane<P>(j) && j < RPW * GRP_NC) {+ const int c = j % GRP_NC;+#pragma unroll+ for (int q = 0; q < RPW; ++q)+ if (j / GRP_NC == q && c < n) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = sum;+ }+ continue;+ }+#pragma unroll+ for (int q = 0; q < RPW; ++q)+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n) s[q][c] = warp_sum(s[q][c]);+#pragma unroll+ for (int q = 0; q < RPW; ++q)+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n && lane == c) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = s[q][c];+ }+}++constexpr int S26_HMAX = 640 / 32; // q8_1 blocks of one SwiGLU row (n_ff 640)++template <bool LX, int RPW, bool SL = false, bool TS = false, int BAL = 0>+/*+DPCT1110: The total declared local variable size in device function+s26_down_l_kernel exceeds 128 bytes and may cause high register pressure.+Consult with your hardware vendor to find the total register size available and+adjust the code, or use smaller sub-group size to avoid high register pressure.+*/+__dpct_inline__ void+s26_down_l_kernel(const unsigned long long *__restrict__ grp_ptr,+ const int32_t *__restrict__ grp_start,+ const int32_t *__restrict__ n_groups,+ const int32_t *__restrict__ ent_dst,+ const block_q8_1 *__restrict__ hq, NativeExpertLayout L,+ float *__restrict__ out) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+auto &s_h = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ block_q8_1[LX ? GRP_NC * S26_HMAX : 1]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const int g = item_ct1.get_group(1);+ if (g >= *n_groups) return;+ const int warp = item_ct1.get_local_id(2) >> 5,+ lane = item_ct1.get_local_id(2) & 31;+ const int r0 = item_ct1.get_group(2) * 8 * RPW + warp;+ const bool live = r0 + 8 * (RPW - 1) < L.n_embd;+ const uint8_t* blob = (const uint8_t*) grp_ptr[g];+ const uint8_t* wr[RPW];+#pragma unroll+ for (int q = 0; q < RPW; ++q) wr[q] = blob + L.down_off + (size_t) (r0 + 8 * q) * L.d_row;+ const int nb = (int) (L.n_ff / 32), hb = (int) (L.n_ff / 32);+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ for (int e = e0; e < e1; e += GRP_NC) {+ const int n = sycl::min(GRP_NC, e1 - e);+ const block_q8_1* hbase = hq;+ int off[GRP_NC];+ if constexpr (LX) {+ /*+ DPCT1118: SYCL group functions and algorithms must be+ encountered in converged control flow. You may need to adjust the+ code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ for (int i = item_ct1.get_local_id(2); i < n * hb; i += 256) {+ const int c = i / hb, j = i - c * hb;+ memcpy(&s_h[c * S26_HMAX + j], &hq[(size_t) (e + c) * hb + j], sizeof(s_h[0]));+ }+ /*+ DPCT1118: SYCL group functions and algorithms must be+ encountered in converged control flow. You may need to adjust the+ code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ off[c] = sycl::min(c, n - 1) * S26_HMAX;+ hbase = s_h;+ } else {+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ off[c] = (e + sycl::min(c, n - 1)) * hb;+ }+ if (!live) continue;+ float s[RPW][GRP_NC];+#pragma unroll+ for (int q = 0; q < RPW; ++q)+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f;+ if constexpr (BAL > 0) { // S26: 5 items per lane instead of 8 / 4, in BAL groups (loads first)+ constexpr int NI = 2 * S26_HMAX, IT = RPW * NI / 32;+ static_assert(RPW * NI % 32 == 0, "whole steps");+ /*+ DPCT1110: The total declared local variable size in device+ function operator() exceeds 128 bytes and may cause high register+ pressure. Consult with your hardware vendor to find the total+ register size available and adjust the code, or use smaller+ sub-group size to avoid high register pressure.+ */+ auto group = [&]<int G0, int... J>(std::integer_sequence<int, J...>) {+ Split<20>::W w[sizeof...(J)];+ int kk[sizeof...(J)];+ bool hh[sizeof...(J)];+ (+ [&] {+ using B = S26Bal<G0 + J, NI, RPW>;+ hh[J] = B::QB != B::QA && lane >= B::THR;+ kk[J] = B::P0 + lane - (hh[J] ? B::QB : B::QA) * NI;+ const uint8_t* rp = hh[J] ? wr[B::QB] : wr[B::QA];+ if constexpr (SL) w[J] = S26Split<20, false>::load(+ rp, kk[J] / 2, 2 * (kk[J] % 2));+ else w[J] = Split<20>::load(rp, kk[J] / 2, 2 * (kk[J] % 2));+ }(),+ ...);+ (+ [&] {+ using B = S26Bal<G0 + J, NI, RPW>;+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n) {+ const float v = Split<20>::apply(w[J], hbase + off[c] + kk[J] / 2, 2 * (kk[J] % 2));+ if (hh[J]) s[B::QB][c] += v; else s[B::QA][c] += v;+ }+ }(),+ ...);+ };+ constexpr int G = (IT + BAL - 1) / BAL;+ [&]<int... Q>(std::integer_sequence<int, Q...>) {+ (group.template operator()<Q * G>(std::make_integer_sequence<int, (IT - Q * G < G ? IT - Q * G : G)>{}), ...);+ }(std::make_integer_sequence<int, BAL>{});+ } else+ for (int k = lane; k < nb * 2; k += 32) {+ const int kbx = k / 2, iqs = 2 * (k % 2);+ Split<20>::W w[RPW];+#pragma unroll+ for (int q = 0; q < RPW; ++q) {+ if constexpr (SL) w[q] =+ S26Split<20, false>::load(wr[q], kbx, iqs);+ else w[q] = Split<20>::load(wr[q], kbx, iqs);+ }+#pragma unroll+ for (int q = 0; q < RPW; ++q)+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n) s[q][c] += Split<20>::apply(w[q], hbase + off[c] + kbx, iqs);+ }+ if constexpr (TS) { // S26: all RPW x GRP_NC sums in one transposed butterfly (bitwise the same sums)+ constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC);+ float v[P];+#pragma unroll+ for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f;+ const float sum = s26ts::tsum<P>(v, lane);+ const int j = s26ts::tsum_token<P>(lane);+ const int q = j / GRP_NC, c = j % GRP_NC;+ if (lane == s26ts::tsum_lane<P>(j) && j < RPW * GRP_NC && c < n)+ out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = sum;+ continue;+ }+#pragma unroll+ for (int q = 0; q < RPW; ++q)+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n) s[q][c] = warp_sum(s[q][c]);+#pragma unroll+ for (int q = 0; q < RPW; ++q)+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = s[q][c];+ }+}+++// S26: swiglu_entries_kernel + quantize_q8_1_kernel in one launch (the same h expression, then the same block quantizer,+// contraction off so the product cannot fuse into the first sum); h is still written (it is the scratch the old pair used)+__dpct_inline__ void s26_swiglu_q8_1_kernel(const float *__restrict__ gate,+ const float *__restrict__ up,+ float *__restrict__ h,+ block_q8_1 *__restrict__ y,+ long long n) {+#pragma clang fp contract(off)+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const long long i =+ (long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) ++ item_ct1.get_local_id(2);+ if (i >= n) return; // n is a multiple of 32: whole warps only+ const float g = gate[i];+ const float xi = (g / (1.0f + sycl::native::exp(-g))) * up[i];+ h[i] = xi;+ float amax = sycl::fabs(xi), sum = xi;+#pragma unroll+ for (int o = 16; o > 0; o >>= 1) {+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ amax = sycl::fmax(+ amax,+ dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),+ amax, o));+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ sum += dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),+ sum, o);+ }+ const float d = amax / 127.0f;+ const int8_t q = amax == 0.0f ? 0 : sycl::round(xi / d);+ const long long ib = i / 32, iqs = i % 32;+ y[ib].qs[iqs] = q;+ if (iqs == 0) y[ib].ds = sycl::half2(d, sum);+}+template <bool LT, bool LX, int RG, int RD, bool SL = false, bool FQ = false,+ bool TS = false, int BD = 0>+void s26_launch_l(const NativeExpertLayout &L, int64_t cap_groups,+ dpct::queue_ptr s, const unsigned long long *grp_ptr,+ const int32_t *grp_start, const int32_t *n_groups,+ const int32_t *ent_dst, const int32_t *ent_tok,+ const block_q8_1 *X, float *gate, float *up, float *h,+ block_q8_1 *hq, float *out, long long nh) {+ const dpct::dim3 ggu((unsigned)(2 * L.n_ff / (GU_ROWS * RG)),+ (unsigned)cap_groups);+ {++ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});++ s->submit([&](sycl::handler &cgh) {++ cgh.parallel_for<dpct_kernel_name<+ class s26_gu_l_kernel_46f2dc, dpct_kernel_scalar<LT>,+ dpct_kernel_scalar<LX>, dpct_kernel_scalar<RG>,+ dpct_kernel_scalar<SL>, dpct_kernel_scalar<TS>>>(+ sycl::nd_range<3>(ggu * sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ s26_gu_l_kernel<LT, LX, RG, SL, TS>(+ grp_ptr, grp_start, n_groups, ent_tok, X, L, gate,+ up);+ });+ });+ }+ if (FQ) {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ s->parallel_for<dpct_kernel_name<class s26_swiglu_q8_1_kernel_a7b554>>(+ sycl::nd_range<3>(sycl::range(1, 1, (unsigned)((nh + 255) / 256)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ s26_swiglu_q8_1_kernel(gate, up, h, hq, nh);+ });+ } else {+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ s->parallel_for<+ dpct_kernel_name<class swiglu_entries_kernel_a4959c>>(+ sycl::nd_range<3>(+ sycl::range(1, 1, (unsigned)((nh + 255) / 256)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ swiglu_entries_kernel(gate, up, h, nh);+ });+ }+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});++ s->parallel_for<+ dpct_kernel_name<class quantize_q8_1_kernel_6b0f01>>(+ sycl::nd_range<3>(+ sycl::range(1, 1, (unsigned)((nh + 255) / 256)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ quantize_q8_1_kernel(h, hq, nh);+ });+ }+ }+ const dpct::dim3 gd((unsigned)(L.n_embd / (8 * RD)), (unsigned)cap_groups);+ {auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});s->submit([&](sycl::handler &cgh) {- cgh.parallel_for<dpct_kernel_name<class mmvq_multi_kernel_6e0f6e,- dpct_kernel_scalar<TY>,- dpct_kernel_scalar<8>>>(- sycl::nd_range<3>(grid * block, block), exp_props,- [=](sycl::nd_item<3> item_ct1)- [[sycl::reqd_sub_group_size(32)]] {- mmvq_multi_kernel<TY, 8>(W, rb, X, y, n_in, n_out,- ncols);- });- });- } // 8 at a time past 8+ cgh.parallel_for<dpct_kernel_name<+ class s26_down_l_kernel_669590, dpct_kernel_scalar<LX>,+ dpct_kernel_scalar<RD>, dpct_kernel_scalar<SL>,+ dpct_kernel_scalar<TS>, dpct_kernel_scalar<BD>>>(+ sycl::nd_range<3>(gd * sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ s26_down_l_kernel<LX, RD, SL, TS, BD>(+ grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);+ });+ });+ }+}+// ---------------------------------------------------------------- stream B: UD-Q4_K_XL grouped decode experts+// STRATA_EXPERT_V2K=1: s26_gu_l_kernel / s26_down_l_kernel's structure (4 interleaved rows per warp, the chunk's q8_1+// activation rows in LDS, SwiGLU + q8_1 fused, optionally STRATA_TSUM's transposed butterfly) for Q4_K / Q5_K gate/up+// and Q5_1 / Q8_0 down, which otherwise run native_gu_kernel / native_down_kernel (one entry at a time, the weight+// words re-read per column). Each Fmt<TY>::dot is split into S27<TY>::load (everything that depends on the weight) and+// apply (the activation words and the same integer / float expression), the same impl functions, so a row's lane-strided+// k order, its terms and warp_sum are the old kernels': every output is bitwise the old one's (iq harness, memcmp).+template<int TY> struct S27;+template<> struct S27<12> { // Q4_K+ struct W { int v[2]; uint16_t aux[2]; sycl::half2 dm; };+ static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ const block_q4_K* b = (const block_q4_K*) vbq + kbx;+ W r;+ const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2));+ const int* q4 = (const int*) (b->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));+ r.v[0] = q4[0];+ r.v[1] = q4[4];+ k_scale_min(b->scales, bq8_offset, r.aux);+ r.dm = b->dm;+ return r;+ }+ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {+ const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2));+ int u[2 * QR4_K];+ float d8[QR4_K];+#pragma unroll+ for (int i = 0; i < QR4_K; ++i) {+ const block_q8_1* bq8i = bq8_1 + bq8_offset + i;+ d8[i] = bq8i->ds[0];+ const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4);+ u[2 * i + 0] = q8[0];+ u[2 * i + 1] = q8[4];+ }+ const uint8_t* sc = (const uint8_t*) r.aux;+ const uint8_t* m = sc + 2;+ return vec_dot_q4_K_q8_1_impl_vmmq(r.v, u, sc, m, r.dm, d8);+ }+};+template<> struct S27<13> { // Q5_K+ struct W { int vl[2]; int vh[2]; uint16_t aux[2]; sycl::half2 dm; };+ static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ const block_q5_K* b = (const block_q5_K*) vbq + kbx;+ W r;+ const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2));+ const int* ql = (const int*) (b->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));+ const int* qh = (const int*) (b->qh + 4 * ((iqs / 2) % 4));+ r.vl[0] = ql[0];+ r.vl[1] = ql[4];+ r.vh[0] = qh[0] >> bq8_offset;+ r.vh[1] = qh[4] >> bq8_offset;+ k_scale_min(b->scales, bq8_offset, r.aux);+ r.dm = b->dm;+ return r;+ }+ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {+ const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2));+ int u[2 * QR5_K];+ float d8[QR5_K];+#pragma unroll+ for (int i = 0; i < QR5_K; ++i) {+ const block_q8_1* bq8i = bq8_1 + bq8_offset + i;+ d8[i] = bq8i->ds[0];+ const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4);+ u[2 * i + 0] = q8[0];+ u[2 * i + 1] = q8[4];+ }+ const uint8_t* sc = (const uint8_t*) r.aux;+ const uint8_t* m = sc + 2;+ return vec_dot_q5_K_q8_1_impl_vmmq(r.vl, r.vh, u, sc, m, r.dm, d8);+ }+};+template<> struct S27<7> { // Q5_1+ struct W { int vl[VDR_Q5_1]; int qh; sycl::half2 dm; };+ static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ const block_q5_1* b = (const block_q5_1*) vbq + kbx;+ W r;+#pragma unroll+ for (int i = 0; i < VDR_Q5_1; ++i) r.vl[i] = get_int_b4(b->qs, iqs + i);+ r.qh = get_int_b4(b->qh, 0);+ r.dm = b->dm;+ return r;+ }+ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {+ int sumi = 0, sumu = 0;+#pragma unroll+ for (int i = 0; i < VDR_Q5_1; ++i) {+ const int vl = r.vl[i];+ const int vh = r.qh >> (4 * (iqs + i));+ const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI5_1);+ int vi0 = (vl >> 0) & 0x0F0F0F0F;+ vi0 |= (vh << 4) & 0x00000010;+ vi0 |= (vh << 11) & 0x00001000;+ vi0 |= (vh << 18) & 0x00100000;+ vi0 |= (vh << 25) & 0x10000000;+ sumi = ggml_cuda_dp4a(vi0, u0, sumi);+ int vi1 = (vl >> 4) & 0x0F0F0F0F;+ vi1 |= (vh >> 12) & 0x00000010;+ vi1 |= (vh >> 5) & 0x00001000;+ vi1 |= (vh << 2) & 0x00100000;+ vi1 |= (vh << 9) & 0x10000000;+ sumi = ggml_cuda_dp4a(vi1, u1, sumi);+ sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu));+ }+ const sycl::float2 dm5 =+ (r.dm).template convert<float, sycl::rounding_mode::automatic>();+ const float d8 = bq8_1->ds[0];+ return sumi * (dm5.x() * d8) + sumu * (dm5.y() * d8);+ }+};+template<> struct S27<8> { // Q8_0+ struct W { int q[VDR_Q8_0]; float d; };+ static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ const block_q8_0* b = (const block_q8_0*) vbq + kbx;+ W r;+#pragma unroll+ for (int i = 0; i < VDR_Q8_0; ++i) r.q[i] = get_int_b2(b->qs, iqs + i);+ r.d = sycl::vec<sycl::half, 1>(b->d)+ .convert<float, sycl::rounding_mode::automatic>()[0];+ return r;+ }+ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {+ int sumi = 0;+#pragma unroll+ for (int i = 0; i < VDR_Q8_0; ++i) sumi = ggml_cuda_dp4a(r.q[i], get_int_b4(bq8_1->qs, iqs + i), sumi);+ const float d8_1 = bq8_1->ds[0];+ return r.d * d8_1 * ((float) sumi);+ }+};++template <int TG, bool LX, int RPW, bool TS>+/*+DPCT1110: The total declared local variable size in device function+s27_gu_kernel exceeds 128 bytes and may cause high register pressure. Consult+with your hardware vendor to find the total register size available and adjust+the code, or use smaller sub-group size to avoid high register pressure.+*/+__dpct_inline__ void s27_gu_kernel(+ const unsigned long long *__restrict__ grp_ptr,+ const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,+ const int32_t *__restrict__ ent_tok, const block_q8_1 *__restrict__ xq,+ NativeExpertLayout L, float *__restrict__ gate, float *__restrict__ up) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ using F = Fmt<TG>;+ using S = S27<TG>;+ auto &s_x = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ block_q8_1[LX ? GRP_NC * S26_XMAX : 1]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const int g = item_ct1.get_group(1);+ if (g >= *n_groups) return;+ const int warp = item_ct1.get_local_id(2) >> 5,+ lane = item_ct1.get_local_id(2) & 31;+ const int row0 = item_ct1.get_group(2) * GU_ROWS * RPW + warp;+ const bool live = row0 + GU_ROWS * (RPW - 1) < 2 * L.n_ff;+ const uint8_t* blob = (const uint8_t*) grp_ptr[g];+ const uint8_t* wr[RPW];+ int rr[RPW];+ bool upq[RPW];+#pragma unroll+ for (int q = 0; q < RPW; ++q) {+ const int row = row0 + q * GU_ROWS;+ upq[q] = row >= L.n_ff;+ rr[q] = upq[q] ? row - (int) L.n_ff : row;+ wr[q] = blob + (upq[q] ? L.up_off : 0) + (size_t) rr[q] * L.gu_row;+ }+ const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32);+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ for (int e = e0; e < e1; e += GRP_NC) {+ const int n = sycl::min(GRP_NC, e1 - e);+ const block_q8_1* xbase = xq;+ int off[GRP_NC];+ if constexpr (LX) {+ /*+ DPCT1118: SYCL group functions and algorithms must be+ encountered in converged control flow. You may need to adjust the+ code.+ */+ /*+ 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.+ */+ item_ct1.barrier(); // the previous chunk is done with s_x+ for (int i = item_ct1.get_local_id(2); i < n * xb; i += 256) {+ const int c = i / xb, j = i - c * xb;+ memcpy(&s_x[c * S26_XMAX + j], &xq[(size_t) ent_tok[e + c] * xb + j], sizeof(s_x[0]));+ }+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ off[c] = sycl::min(c, n - 1) * S26_XMAX;+ xbase = s_x;+ /*+ DPCT1118: SYCL group functions and algorithms must be+ encountered in converged control flow. You may need to adjust the+ code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ } else {+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ off[c] = ent_tok[e + sycl::min(c, n - 1)] * xb;+ }+ if (!live) continue;+ float s[RPW][GRP_NC];+#pragma unroll+ for (int q = 0; q < RPW; ++q)+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f;+ for (int k = lane; k < nb * F::ipb; k += 32) {+ const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+ typename S::W w[RPW];+#pragma unroll+ for (int q = 0; q < RPW; ++q) w[q] = S::load(wr[q], kbx, iqs);+#pragma unroll+ for (int q = 0; q < RPW; ++q)+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n) s[q][c] += S::apply(w[q], xbase + off[c] + kbx * (F::qk / 32), iqs);+ }+ if constexpr (TS) {+ constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC);+ float v[P];+#pragma unroll+ for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f;+ const float sum = s26ts::tsum<P>(v, lane);+ const int j = s26ts::tsum_token<P>(lane);+ if (lane == s26ts::tsum_lane<P>(j) && j < RPW * GRP_NC) {+ const int c = j % GRP_NC;+#pragma unroll+ for (int q = 0; q < RPW; ++q)+ if (j / GRP_NC == q && c < n) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = sum;+ }+ continue;+ }+#pragma unroll+ for (int q = 0; q < RPW; ++q)+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n) s[q][c] = warp_sum(s[q][c]);+#pragma unroll+ for (int q = 0; q < RPW; ++q)+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n && lane == c) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = s[q][c];+ }+}++template <int TD, bool LX, int RPW, bool TS>+/*+DPCT1110: The total declared local variable size in device function+s27_down_kernel exceeds 128 bytes and may cause high register pressure. Consult+with your hardware vendor to find the total register size available and adjust+the code, or use smaller sub-group size to avoid high register pressure.+*/+__dpct_inline__ void s27_down_kernel(+ const unsigned long long *__restrict__ grp_ptr,+ const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,+ const int32_t *__restrict__ ent_dst, const block_q8_1 *__restrict__ hq,+ NativeExpertLayout L, float *__restrict__ out) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ using F = Fmt<TD>;+ using S = S27<TD>;+ auto &s_h = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ block_q8_1[LX ? GRP_NC * S26_HMAX : 1]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const int g = item_ct1.get_group(1);+ if (g >= *n_groups) return;+ const int warp = item_ct1.get_local_id(2) >> 5,+ lane = item_ct1.get_local_id(2) & 31;+ const int r0 = item_ct1.get_group(2) * 8 * RPW + warp;+ const bool live = r0 + 8 * (RPW - 1) < L.n_embd;+ const uint8_t* blob = (const uint8_t*) grp_ptr[g];+ const uint8_t* wr[RPW];+#pragma unroll+ for (int q = 0; q < RPW; ++q) wr[q] = blob + L.down_off + (size_t) (r0 + 8 * q) * L.d_row;+ const int nb = (int) (L.n_ff / F::qk), hb = (int) (L.n_ff / 32);+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ for (int e = e0; e < e1; e += GRP_NC) {+ const int n = sycl::min(GRP_NC, e1 - e);+ const block_q8_1* hbase = hq;+ int off[GRP_NC];+ if constexpr (LX) {+ /*+ DPCT1118: SYCL group functions and algorithms must be+ encountered in converged control flow. You may need to adjust the+ code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ for (int i = item_ct1.get_local_id(2); i < n * hb; i += 256) {+ const int c = i / hb, j = i - c * hb;+ memcpy(&s_h[c * S26_HMAX + j], &hq[(size_t) (e + c) * hb + j], sizeof(s_h[0]));+ }+ /*+ DPCT1118: SYCL group functions and algorithms must be+ encountered in converged control flow. You may need to adjust the+ code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ off[c] = sycl::min(c, n - 1) * S26_HMAX;+ hbase = s_h;+ } else {+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ off[c] = (e + sycl::min(c, n - 1)) * hb;+ }+ if (!live) continue;+ float s[RPW][GRP_NC];+#pragma unroll+ for (int q = 0; q < RPW; ++q)+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f;+ for (int k = lane; k < nb * F::ipb; k += 32) {+ const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+ typename S::W w[RPW];+#pragma unroll+ for (int q = 0; q < RPW; ++q) w[q] = S::load(wr[q], kbx, iqs);+#pragma unroll+ for (int q = 0; q < RPW; ++q)+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n) s[q][c] += S::apply(w[q], hbase + off[c] + kbx * (F::qk / 32), iqs);+ }+ if constexpr (TS) {+ constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC);+ float v[P];+#pragma unroll+ for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f;+ const float sum = s26ts::tsum<P>(v, lane);+ const int j = s26ts::tsum_token<P>(lane);+ const int q = j / GRP_NC, c = j % GRP_NC;+ if (lane == s26ts::tsum_lane<P>(j) && j < RPW * GRP_NC && c < n)+ out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = sum;+ continue;+ }+#pragma unroll+ for (int q = 0; q < RPW; ++q)+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n) s[q][c] = warp_sum(s[q][c]);+#pragma unroll+ for (int q = 0; q < RPW; ++q)+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = s[q][c];+ }+}++template <int TG, int TD, bool LX, int RG, int RD, bool TS>+void s27_launch(const NativeExpertLayout &L, int64_t cap_groups,+ dpct::queue_ptr s, const unsigned long long *grp_ptr,+ const int32_t *grp_start, const int32_t *n_groups,+ const int32_t *ent_dst, const int32_t *ent_tok,+ const block_q8_1 *X, float *gate, float *up, float *h,+ block_q8_1 *hq, float *out, long long nh) {+ const dpct::dim3 ggu((unsigned)(2 * L.n_ff / (GU_ROWS * RG)),+ (unsigned)cap_groups);+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});++ s->parallel_for<+ dpct_kernel_name<class s27_gu_kernel_7906c8, dpct_kernel_scalar<TG>,+ dpct_kernel_scalar<LX>, dpct_kernel_scalar<RG>,+ dpct_kernel_scalar<TS>>>(+ sycl::nd_range<3>(ggu * sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ s27_gu_kernel<TG, LX, RG, TS>(grp_ptr, grp_start, n_groups,+ ent_tok, X, L, gate, up);+ });+ }+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ s->parallel_for<dpct_kernel_name<class s26_swiglu_q8_1_kernel_a7f255>>(+ sycl::nd_range<3>(sycl::range(1, 1, (unsigned)((nh + 255) / 256)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ s26_swiglu_q8_1_kernel(gate, up, h, hq, nh);+ });+ }+ const dpct::dim3 gd((unsigned)(L.n_embd / (8 * RD)), (unsigned)cap_groups);+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ s->parallel_for<+ dpct_kernel_name<class s27_down_kernel_d38356,+ dpct_kernel_scalar<TD>, dpct_kernel_scalar<LX>,+ dpct_kernel_scalar<RD>, dpct_kernel_scalar<TS>>>(+ sycl::nd_range<3>(gd * sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ s27_down_kernel<TD, LX, RD, TS>(grp_ptr, grp_start, n_groups,+ ent_dst, hq, L, out);+ });+ }+}+template <int TG, int TD>+void s27_launch_ts(bool ts, const NativeExpertLayout &L, int64_t cap_groups,+ dpct::queue_ptr s, const unsigned long long *grp_ptr,+ const int32_t *grp_start, const int32_t *n_groups,+ const int32_t *ent_dst, const int32_t *ent_tok,+ const block_q8_1 *X, float *gate, float *up, float *h,+ block_q8_1 *hq, float *out, long long nh) {+ if (ts) s27_launch<TG, TD, true, 4, 4, true>(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, hq, out, nh);+ else s27_launch<TG, TD, true, 4, 4, false>(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, hq, out, nh);}+#endif+// SYCL port: lanes per row of the port's grouped expert kernels at run time (STRATA_GU_LANES / STRATA_DOWN_LANES:// 4, 8, 16 or 32; default STRATA_EXPERT_LANES), 256 / lanes rows per work-group. Gate/up rows are 80 dot calls// (2560 wide), the IQ4_NL down rows 40 (640 wide), so the best split can differ by role.@@ -2217,6 +4154,23 @@ void launch_down_lanes(dpct::dim3 grid, dpct::queue_ptr s, const unsigned long l}}+// STRATA_EXPERT_SPLIT=1 (opt-in): upstream's multi-entry kernels, one warp per row, GU_ROWS rows a group, launched with+// their own grid. The sub-warp variants (SUB16 / SUB_DOWN) are not launched here: they are bitwise equal to the+// generic path and need their own row counts; the port's lane kernels are the default for every format.+template <int TG, bool STAGE_GRID>+void launch_gu_multi(dpct::dim3 grid, dpct::queue_ptr s, const unsigned long long *grp_ptr, const int32_t *grp_start,+ const int32_t *n_groups, const int32_t *ent_tok, const block_q8_1 *X,+ const NativeExpertLayout &L, float *gate, float *up) {+ auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};+ const sycl::range<3> g(1, grid.y, (size_t) ((2 * L.n_ff + GU_ROWS - 1) / GU_ROWS));+ s->parallel_for<dpct_kernel_name<class native_gu_multi_split, dpct_kernel_scalar<TG>,+ dpct_kernel_scalar<STAGE_GRID>>>(+ sycl::nd_range<3>(sycl::range<3>(1, g[1], g[2] * 256), sycl::range<3>(1, 1, 256)), exp_props,+ [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {+ native_gu_multi_kernel<TG, STAGE_GRID, false>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);+ });+}+template <int TG>void launch_gu(dpct::dim3 grid, dpct::queue_ptr s,const unsigned long long *grp_ptr, const int32_t *grp_start,@@ -2224,30 +4178,31 @@ void launch_gu(dpct::dim3 grid, dpct::queue_ptr s,const block_q8_1 *X, const NativeExpertLayout &L, float *gate,float *up) {if constexpr (!kSplit<TG>) {-launch_gu_lanes<TG>(grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);} else if (g_old_kernels || !g_split_multi) {-launch_gu_lanes<TG>(grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);} else {+ if constexpr (kStageIqGrid<TG>) {+ if (g_stage_grid) {+ launch_gu_multi<TG, true>(grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);+ return;+ }+ }+ launch_gu_multi<TG, false>(grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);+ }+}- auto exp_props = sycl::ext::oneapi::experimental::properties{- sycl::ext::oneapi::experimental::use_root_sync};-- s->submit([&](sycl::handler &cgh) {-- cgh.parallel_for<dpct_kernel_name<- class native_gu_multi_kernel_37f479, dpct_kernel_scalar<TG>>>(- sycl::nd_range<3>(dpct::dim3((unsigned) ((2 * L.n_ff + GU_ROWS - 1) / GU_ROWS), grid.y) * sycl::range(1, 1, 256),- sycl::range(1, 1, 256)),- exp_props,- [=](sycl::nd_item<3> item_ct1)- [[sycl::reqd_sub_group_size(32)]] {- native_gu_multi_kernel<TG>(grp_ptr, grp_start, n_groups,- ent_tok, X, L, gate, up);- });+template <int TD>+void launch_down_multi(dpct::dim3 grid, dpct::queue_ptr s, const unsigned long long *grp_ptr,+ const int32_t *grp_start, const int32_t *n_groups, const int32_t *ent_dst,+ const block_q8_1 *hq, const NativeExpertLayout &L, float *out) {+ auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};+ const size_t gx = (size_t) ((L.n_embd + GU_ROWS - 1) / GU_ROWS);+ s->parallel_for<dpct_kernel_name<class native_down_multi_split, dpct_kernel_scalar<TD>>>(+ sycl::nd_range<3>(sycl::range<3>(1, grid.y, gx * 256), sycl::range<3>(1, 1, 256)), exp_props,+ [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {+ native_down_multi_kernel<TD, false>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);});- }}template <int TD>@@ -2257,30 +4212,11 @@ void launch_down(dpct::dim3 grid, dpct::queue_ptr s,const block_q8_1 *hq, const NativeExpertLayout &L,float *out) {if constexpr (!kSplit<TD>) {-launch_down_lanes<TD>(grid, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);} else if (g_old_kernels || !g_split_multi) {-launch_down_lanes<TD>(grid, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);} else {-- auto exp_props = sycl::ext::oneapi::experimental::properties{- sycl::ext::oneapi::experimental::use_root_sync};-- s->submit([&](sycl::handler &cgh) {-- cgh.parallel_for<dpct_kernel_name<- class native_down_multi_kernel_490cef, dpct_kernel_scalar<TD>>>(- sycl::nd_range<3>(dpct::dim3((unsigned) ((L.n_embd + GU_ROWS - 1) / GU_ROWS), grid.y) * sycl::range(1, 1, 256),- sycl::range(1, 1, 256)),- exp_props,- [=](sycl::nd_item<3> item_ct1)- [[sycl::reqd_sub_group_size(32)]] {- native_down_multi_kernel<TD>(grp_ptr, grp_start,- n_groups, ent_dst, hq, L,- out);- });- });+ launch_down_multi<TD>(grid, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);}}@@ -2306,8 +4242,11 @@ size_t iq_row_bytes(int t, int64_t n) noexcept {case 42: return (size_t) (n / 64) * sizeof(block_q2_0);case 12: return (size_t) (n / 256) * sizeof(block_q4_K);case 13: return (size_t) (n / 256) * sizeof(block_q5_K);+ case 14: return (size_t) (n / 256) * sizeof(block_q6_K);case 7: return (size_t) (n / 32) * sizeof(block_q5_1);case 6: return (size_t) (n / 32) * sizeof(block_q5_0);+ case 2: return (size_t) (n / 32) * sizeof(block_q4_0);+ case 3: return (size_t) (n / 32) * sizeof(block_q4_1);case 8: return (size_t) (n / 32) * sizeof(block_q8_0);case 30: return (size_t) n * 2; // BF16: the token embedding only (iq_embed_rows, iq_dequant_f32)default: return 0;@@ -2322,7 +4261,7 @@ void quantize_q8_1_rows(const float* x, int64_t n_rows, int64_t n_cols, void* y,sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class quantize_q8_1_kernel_9d62b4>>(+ ->parallel_for<dpct_kernel_name<class quantize_q8_1_kernel_422964>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)((n + 255) / 256)) *sycl::range(1, 1, 256),@@ -2364,7 +4303,7 @@ void iq_dequant_f16(int t, const void* src, int64_t n, uint16_t* dst, void* stre->submit([&](sycl::handler &cgh) {cgh.parallel_for<dpct_kernel_name<- class dequant_flat_kernel_d891c8, sycl::half>>(+ class dequant_flat_kernel_c7cec2, sycl::half>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(n / 256)) *sycl::range(1, 1, 32),sycl::range(1, 1, 32)),@@ -2435,7 +4374,7 @@ void iq_dequant_f32(int t, const void* src, int64_t n, float* dst, void* stream)->submit([&](sycl::handler &cgh) {cgh.parallel_for<- dpct_kernel_name<class dequant_flat_kernel_d7b5ca, float>>(+ dpct_kernel_name<class dequant_flat_kernel_9052bc, float>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(n / 256)) *sycl::range(1, 1, 32),sycl::range(1, 1, 32)),@@ -2503,6 +4442,560 @@ size_t native_expert_scratch_bytes(int64_t cap, int64_t n_ff) {return 3 * ((f + 255) & ~(size_t) 255) + (((size_t) cap * (size_t) (n_ff / 32) * sizeof(block_q8_1) + 255) & ~(size_t) 255);}++#if defined(STRATA_HIP_GFX906)+// ---- AMD layouts for the grouped native experts (STRATA_EXP_MODE; 0 = the CUDA one above).+// 1 (W64): a row per 64-lane wavefront - 4x the wavefronts, ~1-2 calls per lane, a 64-lane butterfly.+// 2 (R2): a 32-lane logical warp computes TWO rows in one loop - two independent load chains in flight.+// Either way a (row, entry) sum does not depend on the window size.+template<int TY>+__device__ __forceinline__ float row_dot64(const uint8_t* row, const block_q8_1* x, int nb, int lane) {+ using F = Fmt<TY>;+ float s = 0.0f;+ for (int k = lane; k < nb * F::ipb; k += 64) {+ const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+ s += F::dot(row, x + kbx * (F::qk / 32), kbx, iqs);+ }+#pragma unroll+ for (int o = 32; o > 0; o >>= 1) s += __shfl_xor(s, o, 64);+ return s;+}+template<int TY>+__device__ __forceinline__ void row_dot2(const uint8_t* r0, const uint8_t* r1, const block_q8_1* x, int nb, int lane,+ float& o0, float& o1) {+ using F = Fmt<TY>;+ float s0 = 0.0f, s1 = 0.0f;+ for (int k = lane; k < nb * F::ipb; k += 32) {+ const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+ const block_q8_1* xk = x + kbx * (F::qk / 32);+ const float a = F::dot(r0, xk, kbx, iqs);+ const float b = F::dot(r1, xk, kbx, iqs);+ s0 += a;+ s1 += b;+ }+ o0 = warp_sum(s0);+ o1 = warp_sum(s1);+}+template<int TY, int NR>+__device__ __forceinline__ void row_dotn(const uint8_t* const* r, const block_q8_1* x, int nb, int lane, float* o) {+ using F = Fmt<TY>;+ float acc[NR];+#pragma unroll+ for (int i = 0; i < NR; ++i) acc[i] = 0.0f;+ for (int k = lane; k < nb * F::ipb; k += 32) {+ const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+ const block_q8_1* xk = x + kbx * (F::qk / 32);+ float d[NR];+#pragma unroll+ for (int i = 0; i < NR; ++i) d[i] = F::dot(r[i], xk, kbx, iqs);+#pragma unroll+ for (int i = 0; i < NR; ++i) acc[i] += d[i];+ }+#pragma unroll+ for (int i = 0; i < NR; ++i) o[i] = warp_sum(acc[i]);+}+template<int TG, int MODE>+__global__ void __launch_bounds__(256) native_gu_amd_kernel(const unsigned long long* __restrict__ grp_ptr,+ const int32_t* __restrict__ grp_start,+ const int32_t* __restrict__ n_groups,+ const int32_t* __restrict__ ent_tok,+ const block_q8_1* __restrict__ xq, NativeExpertLayout L,+ float* __restrict__ gate, float* __restrict__ up) {+ const int g = blockIdx.y;+ if (g >= *n_groups) return;+ const uint8_t* blob = (const uint8_t*) grp_ptr[g];+ const int nb = (int) (L.n_embd / Fmt<TG>::qk), xb = (int) (L.n_embd / 32);+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ const int nrow = 2 * (int) L.n_ff;+ auto wrow = [&](int row) -> const uint8_t* {+ const bool is_up = row >= L.n_ff;+ return blob + (is_up ? L.up_off : 0) + (size_t) (is_up ? row - (int) L.n_ff : row) * L.gu_row;+ };+ auto put = [&](int row, int e, float v) {+ const bool is_up = row >= L.n_ff;+ (is_up ? up : gate)[(size_t) e * L.n_ff + (is_up ? row - (int) L.n_ff : row)] = v;+ };+ if constexpr (MODE == 1) {+ const int lane = threadIdx.x & 63, row = blockIdx.x * 4 + (threadIdx.x >> 6);+ if (row >= nrow) return;+ const uint8_t* wr = wrow(row);+ for (int e = e0; e < e1; ++e) {+ const float v = row_dot64<TG>(wr, xq + (size_t) ent_tok[e] * xb, nb, lane);+ if (lane == 0) put(row, e, v);+ }+ } else if constexpr (MODE == 4) {+ const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;+ const int row0 = blockIdx.x * 32 + warp;+ if (row0 >= nrow) return;+ const uint8_t* w[4];+#pragma unroll+ for (int i = 0; i < 4; ++i) w[i] = wrow(row0 + 8 * i < nrow ? row0 + 8 * i : row0);+ for (int e = e0; e < e1; ++e) {+ float o[4];+ row_dotn<TG, 4>(w, xq + (size_t) ent_tok[e] * xb, nb, lane, o);+ if (lane == 0)+#pragma unroll+ for (int i = 0; i < 4; ++i) if (row0 + 8 * i < nrow) put(row0 + 8 * i, e, o[i]);+ }+ } else {+ const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;+ const int row0 = blockIdx.x * 16 + warp, row1 = row0 + 8;+ if (row0 >= nrow) return;+ const bool two = row1 < nrow;+ const uint8_t* w0 = wrow(row0);+ const uint8_t* w1 = wrow(two ? row1 : row0);+ for (int e = e0; e < e1; ++e) {+ float a, b;+ row_dot2<TG>(w0, w1, xq + (size_t) ent_tok[e] * xb, nb, lane, a, b);+ if (lane == 0) { put(row0, e, a); if (two) put(row1, e, b); }+ }+ }+}+template<int TD, int MODE>+__global__ void __launch_bounds__(256) native_down_amd_kernel(const unsigned long long* __restrict__ grp_ptr,+ const int32_t* __restrict__ grp_start,+ const int32_t* __restrict__ n_groups,+ const int32_t* __restrict__ ent_dst,+ const block_q8_1* __restrict__ hq, NativeExpertLayout L,+ float* __restrict__ out) {+ const int g = blockIdx.y;+ if (g >= *n_groups) return;+ const uint8_t* blob = (const uint8_t*) grp_ptr[g];+ const int nb = (int) (L.n_ff / Fmt<TD>::qk), hb = (int) (L.n_ff / 32);+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ const int nrow = (int) L.n_embd;+ if constexpr (MODE == 1) {+ const int lane = threadIdx.x & 63, r = blockIdx.x * 4 + (threadIdx.x >> 6);+ if (r >= nrow) return;+ const uint8_t* wr = blob + L.down_off + (size_t) r * L.d_row;+ for (int e = e0; e < e1; ++e) {+ const float v = row_dot64<TD>(wr, hq + (size_t) e * hb, nb, lane);+ if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = v;+ }+ } else if constexpr (MODE == 4) {+ const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;+ const int r0 = blockIdx.x * 32 + warp;+ if (r0 >= nrow) return;+ const uint8_t* w[4];+#pragma unroll+ for (int i = 0; i < 4; ++i) w[i] = blob + L.down_off + (size_t) (r0 + 8 * i < nrow ? r0 + 8 * i : r0) * L.d_row;+ for (int e = e0; e < e1; ++e) {+ float o[4];+ row_dotn<TD, 4>(w, hq + (size_t) e * hb, nb, lane, o);+ if (lane == 0)+#pragma unroll+ for (int i = 0; i < 4; ++i) if (r0 + 8 * i < nrow) out[(size_t) ent_dst[e] * L.n_embd + r0 + 8 * i] = o[i];+ }+ } else {+ const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;+ const int r0 = blockIdx.x * 16 + warp, r1 = r0 + 8;+ if (r0 >= nrow) return;+ const bool two = r1 < nrow;+ const uint8_t* w0 = blob + L.down_off + (size_t) r0 * L.d_row;+ const uint8_t* w1 = blob + L.down_off + (size_t) (two ? r1 : r0) * L.d_row;+ for (int e = e0; e < e1; ++e) {+ float a, b;+ row_dot2<TD>(w0, w1, hq + (size_t) e * hb, nb, lane, a, b);+ if (lane == 0) {+ out[(size_t) ent_dst[e] * L.n_embd + r0] = a;+ if (two) out[(size_t) ent_dst[e] * L.n_embd + r1] = b;+ }+ }+ }+}+// ---- 5 (LDS): gate/up of the grid formats (IQ2_S, IQ3_XXS, IQ3_S) with the codebook grid and the group's q8_1+// activations in LDS. The bench showed gate/up compute-bound, not bandwidth-bound (T = 2 costs ~1.8x T = 1 on the+// same weights, 110-130 GB/s): each call issues its grid lookups and eight activation loads through the vector+// memory path after the weight load. Same calls, same lane-strided k, same R2 row pairs, same warp_sum: the+// output is bitwise the mode-2 one.+template<int TY> struct GridOf;+template<> struct GridOf<22> { using T = uint64_t; static constexpr int N = 1024; __device__ static const T* src() { return iq2s_grid; } };+template<> struct GridOf<18> { using T = uint32_t; static constexpr int N = 256; __device__ static const T* src() { return iq3xxs_grid; } };+template<> struct GridOf<21> { using T = uint32_t; static constexpr int N = 512; __device__ static const T* src() { return iq3s_grid; } };+template<> struct GridOf<23> { using T = uint32_t; static constexpr int N = 1; __device__ static const T* src() { return iq3s_grid; } }; // IQ4_XS: no grid++// SG = 1 (mode 6): the signs without byte-SIMD ops, which gfx906 lacks (strata_vcmpne4 / strata_vsub4 unpack to+// ~12 word ops each). m = the sign nibble as 0x00/0xff bytes; (g ^ m) is g or -g-1 per byte, so+// dp4a(g ^ m, u) - dp4a(m, u) = sum(s g u) exactly - the same integers, the same floats.+__device__ __forceinline__ int nib_mask(uint32_t n) {+ const uint32_t b = __umul24(n & 0xFu, 0x204081u) & 0x01010101u;+ return (int) ((b << 8) - b);+}+template<int TY, int SG> struct DotG;+template<int SG> struct DotG<22, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,+ const uint64_t* grid) {+ const block_iq2_s* bq2 = (const block_iq2_s*) vbq + kbx;+ const int qs_packed = get_int_b2(bq2->qs, iqs / 2);+ const uint8_t* qs = (const uint8_t*) &qs_packed;+ const int qh = bq2->qh[iqs / 2];+ const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2);+ const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;+ const int ls0 = bq2->scales[iqs / 2] & 0x0F;+ const int ls1 = bq2->scales[iqs / 2] >> 4;+ int sumi0 = 0, sumi1 = 0;+#pragma unroll+ for (int l0 = 0; l0 < 8; l0 += 2) {+ const int* grid_pos = (const int*) (grid + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300)));+ const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);+ const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);+ int& acc = l0 < 4 ? sumi0 : sumi1;+ if constexpr (SG == 1) {+ const int m0 = nib_mask(signs_packed_8[l0 / 2]), m1 = nib_mask(signs_packed_8[l0 / 2] >> 4);+ acc = ggml_cuda_dp4a(grid_pos[0] ^ m0, u0, acc);+ acc = ggml_cuda_dp4a(grid_pos[1] ^ m1, u1, acc);+ acc -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0));+ } else {+ const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);+ const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);+ const int grid_l = __vsub4(grid_pos[0] ^ signs0, signs0);+ const int grid_h = __vsub4(grid_pos[1] ^ signs1, signs1);+ acc = ggml_cuda_dp4a(grid_l, u0, acc);+ acc = ggml_cuda_dp4a(grid_h, u1, acc);+ }+ }+ const int sumi = (sumi0 * ls0 + sumi1 * ls1 + (sumi0 + sumi1) / 2) / 4;+ const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds);+ return d * sumi;+} };+template<int SG> struct DotG<18, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,+ const uint32_t* grid) {+ const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx;+ const int2 q3_packed = make_int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1));+ const uint8_t* q3 = (const uint8_t*) &q3_packed;+ const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2);+ int sumi = 0;+#pragma unroll+ for (int l0 = 0; l0 < 8; l0 += 2) {+ const int2 grid_pos = make_int2(grid[q3[l0 + 0]], grid[q3[l0 + 1]]);+ const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2));+ const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);+ const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);+ if constexpr (SG == 1) {+ const int m0 = nib_mask(signs), m1 = nib_mask(signs >> 4);+ sumi = ggml_cuda_dp4a(grid_pos.x ^ m0, u0, sumi);+ sumi = ggml_cuda_dp4a(grid_pos.y ^ m1, u1, sumi);+ sumi -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0));+ } else {+ const int signs0 = __vcmpne4(signs & 0x08040201, 0);+ const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0);+ const int signs1 = __vcmpne4(signs & 0x80402010, 0);+ const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1);+ sumi = ggml_cuda_dp4a(grid_l, u0, sumi);+ sumi = ggml_cuda_dp4a(grid_h, u1, sumi);+ }+ }+ const int ls = aux32 >> 28;+ sumi = (ls * sumi + sumi / 2) / 2;+ const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds);+ return d * sumi;+} };+template<int SG> struct DotG<21, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,+ const uint32_t* grid) {+ const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;+ const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1));+ const uint8_t* qs = (const uint8_t*) &qs_packed;+ const int qh = bq3->qh[iqs / 2];+ const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2);+ const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;+ int sumi = 0;+#pragma unroll+ for (int l0 = 0; l0 < 8; l0 += 2) {+ const int2 grid_pos = make_int2(grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)],+ grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]);+ const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);+ const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);+ if constexpr (SG == 1) {+ const int m0 = nib_mask(signs_packed_8[l0 / 2]), m1 = nib_mask(signs_packed_8[l0 / 2] >> 4);+ sumi = ggml_cuda_dp4a(grid_pos.x ^ m0, u0, sumi);+ sumi = ggml_cuda_dp4a(grid_pos.y ^ m1, u1, sumi);+ sumi -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0));+ } else {+ const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);+ const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);+ const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0);+ const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1);+ sumi = ggml_cuda_dp4a(grid_l, u0, sumi);+ sumi = ggml_cuda_dp4a(grid_h, u1, sumi);+ }+ }+ sumi *= 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F);+ const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds);+ return d * sumi;+} };++template<int SG> struct DotG<23, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,+ const uint32_t*) { return vec_dot_iq4_xs_q8_1(vbq, bq8_1, kbx, iqs); } };++constexpr int LDS_RB = 64; // gate/up rows per block (4 R2 passes of 16)+constexpr int LDS_NT = 4; // entries whose activations sit in LDS at once++template<int TG, int SG, bool TI = false>+__global__ void __launch_bounds__(256) native_gu_lds_kernel(const unsigned long long* __restrict__ grp_ptr,+ const int32_t* __restrict__ grp_start,+ const int32_t* __restrict__ n_groups,+ const int32_t* __restrict__ ent_tok,+ const block_q8_1* __restrict__ xq, NativeExpertLayout L,+ float* __restrict__ gate, float* __restrict__ up) {+ using GT = typename GridOf<TG>::T;+ using F = Fmt<TG>;+ __shared__ GT sgrid[GridOf<TG>::N];+ extern __shared__ int sx_raw[]; // LDS_NT tokens x xb blocks of q8_1 (36 bytes = 9 ints each)+ const int g = blockIdx.y;+ if (g >= *n_groups) return; // uniform over the block+ const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;+ const GT* gsrc = GridOf<TG>::src();+ for (int i = tid; i < GridOf<TG>::N; i += 256) sgrid[i] = gsrc[i];+ const uint8_t* blob = (const uint8_t*) grp_ptr[g];+ const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32);+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ const int nrow = 2 * (int) L.n_ff;+ const block_q8_1* sx = (const block_q8_1*) sx_raw;+ auto wrow = [&](int row) -> const uint8_t* {+ const bool is_up = row >= L.n_ff;+ return blob + (is_up ? L.up_off : 0) + (size_t) (is_up ? row - (int) L.n_ff : row) * L.gu_row;+ };+ auto put = [&](int row, int e, float v) {+ const bool is_up = row >= L.n_ff;+ (is_up ? up : gate)[(size_t) e * L.n_ff + (is_up ? row - (int) L.n_ff : row)] = v;+ };+ for (int c0 = e0; c0 < e1; c0 += LDS_NT) {+ const int cn = min(LDS_NT, e1 - c0);+ __syncthreads();+ for (int j = 0; j < cn; ++j) {+ const int* src = (const int*) (xq + (size_t) ent_tok[c0 + j] * xb);+ for (int i = tid; i < xb * 9; i += 256) sx_raw[j * xb * 9 + i] = src[i];+ }+ __syncthreads();+ for (int p = 0; p < LDS_RB / 16; ++p) {+ const int row0 = blockIdx.x * LDS_RB + p * 16 + warp, row1 = row0 + 8;+ if (row0 >= nrow) break;+ const bool two = row1 < nrow;+ const uint8_t* w0 = wrow(row0);+ const uint8_t* w1 = wrow(two ? row1 : row0);+ if constexpr (TI) { // mode 7: the tokens inside the k loop - one weight load per k for all of them+ auto pass = [&](auto ntc) {+ constexpr int NTC = decltype(ntc)::value;+ float s0[NTC], s1[NTC];+#pragma unroll+ for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; }+ for (int k = lane; k < nb * F::ipb; k += 32) {+ const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+#pragma unroll+ for (int j = 0; j < NTC; ++j) {+ const block_q8_1* xk = sx + (size_t) j * xb + kbx * (F::qk / 32);+ const float a = DotG<TG, SG>::f(w0, xk, kbx, iqs, sgrid);+ const float b = DotG<TG, SG>::f(w1, xk, kbx, iqs, sgrid);+ s0[j] += a;+ s1[j] += b;+ }+ }+#pragma unroll+ for (int j = 0; j < NTC; ++j) {+ const float a = warp_sum(s0[j]), b = warp_sum(s1[j]);+ if (lane == 0) { put(row0, c0 + j, a); if (two) put(row1, c0 + j, b); }+ }+ };+ switch (cn) {+ case 1: pass(std::integral_constant<int, 1>{}); break;+ case 2: pass(std::integral_constant<int, 2>{}); break;+ case 3: pass(std::integral_constant<int, 3>{}); break;+ default: pass(std::integral_constant<int, 4>{}); break;+ }+ continue;+ }+ for (int j = 0; j < cn; ++j) {+ const block_q8_1* x = sx + (size_t) j * xb;+ float s0 = 0.0f, s1 = 0.0f;+ for (int k = lane; k < nb * F::ipb; k += 32) {+ const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+ const block_q8_1* xk = x + kbx * (F::qk / 32);+ const float a = DotG<TG, SG>::f(w0, xk, kbx, iqs, sgrid);+ const float b = DotG<TG, SG>::f(w1, xk, kbx, iqs, sgrid);+ s0 += a;+ s1 += b;+ }+ s0 = warp_sum(s0);+ s1 = warp_sum(s1);+ if (lane == 0) { put(row0, c0 + j, s0); if (two) put(row1, c0 + j, s1); }+ }+ }+ }+}++// ---- 7 (down): the group's q8_1 h rows in LDS, the tokens inside the k loop, the R2 row pairs of mode 2 -+// the same per-(row, entry) sums in the same order: bitwise the mode-2 output.+template<int TD>+__global__ void __launch_bounds__(256) native_down_lds_kernel(const unsigned long long* __restrict__ grp_ptr,+ const int32_t* __restrict__ grp_start,+ const int32_t* __restrict__ n_groups,+ const int32_t* __restrict__ ent_dst,+ const block_q8_1* __restrict__ hq, NativeExpertLayout L,+ float* __restrict__ out) {+ using F = Fmt<TD>;+ extern __shared__ int sh_raw[]; // LDS_NT entries x hb blocks of q8_1+ const int g = blockIdx.y;+ if (g >= *n_groups) return;+ const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;+ const uint8_t* blob = (const uint8_t*) grp_ptr[g];+ const int nb = (int) (L.n_ff / F::qk), hb = (int) (L.n_ff / 32);+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ const int nrow = (int) L.n_embd;+ const block_q8_1* sh = (const block_q8_1*) sh_raw;+ for (int c0 = e0; c0 < e1; c0 += LDS_NT) {+ const int cn = min(LDS_NT, e1 - c0);+ __syncthreads();+ {+ const int* src = (const int*) (hq + (size_t) c0 * hb); // the chunk's entries are contiguous+ for (int i = tid; i < cn * hb * 9; i += 256) sh_raw[i] = src[i];+ }+ __syncthreads();+ for (int p = 0; p < LDS_RB / 16; ++p) {+ const int r0 = blockIdx.x * LDS_RB + p * 16 + warp, r1 = r0 + 8;+ if (r0 >= nrow) break;+ const bool two = r1 < nrow;+ const uint8_t* w0 = blob + L.down_off + (size_t) r0 * L.d_row;+ const uint8_t* w1 = blob + L.down_off + (size_t) (two ? r1 : r0) * L.d_row;+ auto pass = [&](auto ntc) {+ constexpr int NTC = decltype(ntc)::value;+ float s0[NTC], s1[NTC];+#pragma unroll+ for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; }+ for (int k = lane; k < nb * F::ipb; k += 32) {+ const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+#pragma unroll+ for (int j = 0; j < NTC; ++j) {+ const block_q8_1* xk = sh + (size_t) j * hb + kbx * (F::qk / 32);+ const float a = F::dot(w0, xk, kbx, iqs);+ const float b = F::dot(w1, xk, kbx, iqs);+ s0[j] += a;+ s1[j] += b;+ }+ }+#pragma unroll+ for (int j = 0; j < NTC; ++j) {+ const float a = warp_sum(s0[j]), b = warp_sum(s1[j]);+ if (lane == 0) {+ out[(size_t) ent_dst[c0 + j] * L.n_embd + r0] = a;+ if (two) out[(size_t) ent_dst[c0 + j] * L.n_embd + r1] = b;+ }+ }+ };+ switch (cn) {+ case 1: pass(std::integral_constant<int, 1>{}); break;+ case 2: pass(std::integral_constant<int, 2>{}); break;+ case 3: pass(std::integral_constant<int, 3>{}); break;+ default: pass(std::integral_constant<int, 4>{}); break;+ }+ }+ }+}++// ---- 8: mode 7's gate/up with SwiGLU and the q8_1 quantization in the epilogue. A block takes h rows+// [r0, r0 + 32): gate rows r0.. and up rows r0.. (64 weight rows, the same per-(row, entry) sums as mode 7), so+// one 32-lane warp per entry holds exactly one q8_1 block of h and runs quantize_q8_1_kernel's own code on it -+// bitwise the separate kernels' hq, two launches fewer per call.+template<int TG>+__global__ void __launch_bounds__(256) native_gu_fused_kernel(const unsigned long long* __restrict__ grp_ptr,+ const int32_t* __restrict__ grp_start,+ const int32_t* __restrict__ n_groups,+ const int32_t* __restrict__ ent_tok,+ const block_q8_1* __restrict__ xq, NativeExpertLayout L,+ block_q8_1* __restrict__ hq) {+ using GT = typename GridOf<TG>::T;+ using F = Fmt<TG>;+ __shared__ GT sgrid[GridOf<TG>::N];+ __shared__ float res[LDS_NT][64];+ extern __shared__ int sx_raw[];+ const int g = blockIdx.y;+ if (g >= *n_groups) return;+ const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;+ const GT* gsrc = GridOf<TG>::src();+ for (int i = tid; i < GridOf<TG>::N; i += 256) sgrid[i] = gsrc[i];+ const uint8_t* blob = (const uint8_t*) grp_ptr[g];+ const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32), hb = (int) (L.n_ff / 32);+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ const int r0 = blockIdx.x * 32;+ const block_q8_1* sx = (const block_q8_1*) sx_raw;+ auto wrow = [&](int i) -> const uint8_t* { // i < 32: gate row r0 + i, else up row r0 + i - 32+ return blob + (i < 32 ? (size_t) 0 : L.up_off) + (size_t) (r0 + (i & 31)) * L.gu_row;+ };+ for (int c0 = e0; c0 < e1; c0 += LDS_NT) {+ const int cn = min(LDS_NT, e1 - c0);+ __syncthreads();+ for (int j = 0; j < cn; ++j) {+ const int* src = (const int*) (xq + (size_t) ent_tok[c0 + j] * xb);+ for (int i = tid; i < xb * 9; i += 256) sx_raw[j * xb * 9 + i] = src[i];+ }+ __syncthreads();+ for (int p = 0; p < 4; ++p) {+ const int i0 = p * 16 + warp, i1 = i0 + 8;+ const uint8_t* w0 = wrow(i0);+ const uint8_t* w1 = wrow(i1);+ auto pass = [&](auto ntc) {+ constexpr int NTC = decltype(ntc)::value;+ float s0[NTC], s1[NTC];+#pragma unroll+ for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; }+ for (int k = lane; k < nb * F::ipb; k += 32) {+ const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+#pragma unroll+ for (int j = 0; j < NTC; ++j) {+ const block_q8_1* xk = sx + (size_t) j * xb + kbx * (F::qk / 32);+ const float a = DotG<TG, 1>::f(w0, xk, kbx, iqs, sgrid);+ const float b = DotG<TG, 1>::f(w1, xk, kbx, iqs, sgrid);+ s0[j] += a;+ s1[j] += b;+ }+ }+#pragma unroll+ for (int j = 0; j < NTC; ++j) {+ const float a = warp_sum(s0[j]), b = warp_sum(s1[j]);+ if (lane == 0) { res[j][i0] = a; res[j][i1] = b; }+ }+ };+ switch (cn) {+ case 1: pass(std::integral_constant<int, 1>{}); break;+ case 2: pass(std::integral_constant<int, 2>{}); break;+ case 3: pass(std::integral_constant<int, 3>{}); break;+ default: pass(std::integral_constant<int, 4>{}); break;+ }+ }+ __syncthreads();+ if (warp < cn) { // swiglu_entries_kernel + quantize_q8_1_kernel, one block of 32 h values per entry+ const float gg = res[warp][lane], uu = res[warp][32 + lane];+ const float xi = (gg / (1.0f + __expf(-gg))) * uu;+ float amax = fabsf(xi), sum = xi;+#pragma unroll+ for (int o = 16; o > 0; o >>= 1) {+ amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));+ sum += __shfl_xor_sync(0xffffffffu, sum, o);+ }+ const float d = q8_1_finite(amax / 127.0f); // #606, as q8_1_store: finite blocks bit for bit+ const int8_t q = q8_1_quant(xi, d, amax);+ block_q8_1* y = hq + (size_t) (c0 + warp) * hb + blockIdx.x;+ y->qs[lane] = q;+ if (lane == 0) y->ds = q8_1_ds(d, sum);+ }+ }+}++int g_exp_mode = -1; // native_expert_set_mode (the bench); -1 = STRATA_EXP_MODE, default 7+int exp_mode() {+ static const int m = [] { const char* v = std::getenv("STRATA_EXP_MODE"); return v ? std::atoi(v) : 7; }();+ return g_exp_mode >= 0 ? g_exp_mode : m;+}+#endif+int g_exp_phase = 0; // the bench: 0 all, 1 gate/up + swiglu + quantize only, 2 down only++void native_expert_set_mode(int mode, int phase) {+#if defined(STRATA_HIP_GFX906)+ g_exp_mode = mode;+#else+ (void) mode;+#endif+ g_exp_phase = phase;+}+namespace {bool g_grouped_v1 = env_on("STRATA_GROUPED_V1");} // namespace@@ -2522,41 +5015,129 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long longfloat* h = (float*) ((uint8_t*) scratch + 2 * fa);block_q8_1* hq = (block_q8_1*) ((uint8_t*) scratch + 3 * fa);const auto* X = (const block_q8_1*) x_q8_1;+ // SYCL port: STRATA_EXPERT_V2 / STRATA_EXPERT_V2K (upstream's AMD-tuned S26 / S27 kernels) are not built here+ static const bool v2_note = [] {+ const char* a = std::getenv("STRATA_EXPERT_V2");+ const char* b = std::getenv("STRATA_EXPERT_V2K");+ if ((a && a[0] == '1') || (b && b[0] == '1'))+ std::fprintf(stderr, "note: STRATA_EXPERT_V2 / STRATA_EXPERT_V2K are AMD-only experiments, ignored on SYCL\n");+ return true;+ }();+ (void) v2_note;const bool v1 = g_grouped_v1;// #363: a verify window's PCIe call usually has no group: `grid_groups` block rows stride over the groups instead// of one row per possible group (the results do not depend on it)const int64_t gy = (v1 || grid_groups <= 0 || grid_groups > cap_groups) ? cap_groups : grid_groups;const dpct::dim3 ggu((unsigned)((2 * L.n_ff + kExpertRows - 1) / kExpertRows),(unsigned)gy);+#if defined(STRATA_HIP_GFX906)+ const int em0 = exp_mode();+#endif+#if defined(STRATA_HIP_GFX906)+ const bool fused_gu = em0 == 8 && (L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23) &&+ L.n_ff % 32 == 0;+ if (fused_gu && g_exp_phase != 2) {+ const dim3 gl((unsigned) (L.n_ff / 32), (unsigned) cap_groups);+ const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1);+ switch (L.gu_type) {+ case 18: native_gu_fused_kernel<18><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;+ case 21: native_gu_fused_kernel<21><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;+ case 23: native_gu_fused_kernel<23><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;+ default: native_gu_fused_kernel<22><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;+ }+ check("native_expert_grouped/gu fused");+ }+ if (g_exp_phase != 2 && !fused_gu) {+#else+ if (g_exp_phase != 2) {+#endif+#if defined(STRATA_HIP_GFX906)+ const bool lds_gu = (em0 == 5 || em0 == 6 || em0 == 7 || em0 == 8) && (L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23);+ if (lds_gu) {+ const dim3 gl((unsigned) ((2 * L.n_ff + LDS_RB - 1) / LDS_RB), (unsigned) cap_groups);+ const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1);+ switch (L.gu_type) {+ case 18: if (em0 >= 7) native_gu_lds_kernel<18, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<18, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<18, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;+ case 21: if (em0 >= 7) native_gu_lds_kernel<21, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<21, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<21, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;+ case 23: if (em0 >= 7) native_gu_lds_kernel<23, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<23, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;+ default: if (em0 >= 7) native_gu_lds_kernel<22, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<22, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<22, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;+ }+ } else {+ const int em = exp_mode() >= 5 ? 2 : exp_mode();+ const dim3 ggu_amd((unsigned) ((2 * L.n_ff + (em == 1 ? 3 : em == 4 ? 31 : 15)) / (em == 1 ? 4 : em == 4 ? 32 : 16)), (unsigned) cap_groups);+#define STRATA_GU_AMD(T) \+ case T: if (em == 1) native_gu_amd_kernel<T, 1><<<ggu_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); \+ else if (em == 4) native_gu_amd_kernel<T, 4><<<ggu_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); \+ else native_gu_amd_kernel<T, 2><<<ggu_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;+ // the AMD layouts cover the IQ packs' gate/up types; Unsloth's Q4_K / Q5_K take the CUDA layout below+ const bool amd_gu = L.gu_type == 16 || L.gu_type == 17 || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 ||+ L.gu_type == 23 || L.gu_type == 29 || L.gu_type == 42;+ if ((em == 1 || em == 2 || em == 4) && amd_gu) {+ switch (L.gu_type) {+ STRATA_GU_AMD(16) STRATA_GU_AMD(17) STRATA_GU_AMD(18) STRATA_GU_AMD(21) STRATA_GU_AMD(22) STRATA_GU_AMD(23)+ STRATA_GU_AMD(29) STRATA_GU_AMD(42)+ }+ } else+#undef STRATA_GU_AMD+#endifswitch (L.gu_type) {#define STRATA_GU(T) case T: launch_gu<T>(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;STRATA_GU_FMTS(STRATA_GU)#undef STRATA_GUdefault: std::fprintf(stderr, "native_expert_grouped: gate/up type %d\n", L.gu_type); std::exit(1);}+#if defined(STRATA_HIP_GFX906)+ }+#endifcheck("native_expert_grouped/gu");const long long nh = (long long) cap_entries * L.n_ff;- if (v1) {- {- auto exp_props = sycl::ext::oneapi::experimental::properties{- sycl::ext::oneapi::experimental::use_root_sync};+#if defined(STRATA_HIP_GFX906)+ // gfx906: the separate SwiGLU and q8_1 passes stay the default (the A/B baseline); the RDNA one-pass+ // kernel (bitwise the same) with STRATA_HIP_SWIGLU_FUSED=1+ static const bool sw_fused = env_on("STRATA_HIP_SWIGLU_FUSED");+ const bool sw_v1 = v1 || !sw_fused;+#else+ const bool sw_v1 = v1;+#endif+ if (sw_v1) {+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};- s->parallel_for<- dpct_kernel_name<class swiglu_entries_kernel_a4959c>>(- sycl::nd_range<3>(- sycl::range(1, 1, (unsigned)((nh + 255) / 256)) *- sycl::range(1, 1, 256),- sycl::range(1, 1, 256)),- exp_props, [=](sycl::nd_item<3> item_ct1) {- swiglu_entries_kernel(gate, up, h, nh);- });- }- {+ s->parallel_for<+ dpct_kernel_name<class swiglu_entries_kernel_a4959c>>(+ sycl::nd_range<3>(+ sycl::range(1, 1, (unsigned)((nh + 255) / 256)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ swiglu_entries_kernel(gate, up, h, nh);+ });+ }+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(s->get_device(),+ {sycl::aspect::fp16});++ s->parallel_for<+ dpct_kernel_name<class quantize_q8_1_kernel_f68c59>>(+ sycl::nd_range<3>(+ sycl::range(1, 1, (unsigned)((nh + 255) / 256)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ quantize_q8_1_kernel(h, hq, nh);+ });+ }+ } else {auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};s->parallel_for<- dpct_kernel_name<class quantize_q8_1_kernel_cfb6c5>>(+ dpct_kernel_name<class swiglu_q8_1_entries_kernel_115291>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)((nh + 255) / 256)) *sycl::range(1, 1, 256),@@ -2564,26 +5145,40 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long longexp_props,[=](sycl::nd_item<3> item_ct1)[[sycl::reqd_sub_group_size(32)]] {- quantize_q8_1_kernel(h, hq, nh);+ swiglu_q8_1_entries_kernel(gate, up, grp_start,+ n_groups, (int)L.n_ff, hq);});- }- } else {- auto exp_props = sycl::ext::oneapi::experimental::properties{- sycl::ext::oneapi::experimental::use_root_sync};-- s->parallel_for<- dpct_kernel_name<class swiglu_q8_1_entries_kernel_115291>>(- sycl::nd_range<3>(sycl::range(1, 1, (unsigned)((nh + 255) / 256)) *- sycl::range(1, 1, 256),- sycl::range(1, 1, 256)),- exp_props,- [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {- swiglu_q8_1_entries_kernel(gate, up, grp_start, n_groups,- (int)L.n_ff, hq);- });}check("native_expert_grouped/swiglu");- const dpct::dim3 gd((unsigned)((L.n_embd + kExpertRows - 1) / kExpertRows), (unsigned)gy);+ }+ if (g_exp_phase == 1) return;+ const int d_rows = (!g_old_kernels && !g_no_sub16_gu && L.n_ff == 640) ? (L.d_type == 20 ? 32 : (L.d_type == 42 ? 16 : 8)) : 8;+ const dpct::dim3 gd((unsigned)((L.n_embd + d_rows - 1) / d_rows),+ (unsigned)gy);+#if defined(STRATA_HIP_GFX906)+ if ((em0 == 7 || em0 == 8) && (L.d_type == 20 || L.d_type == 42)) {+ const dim3 gl((unsigned) ((L.n_embd + LDS_RB - 1) / LDS_RB), (unsigned) cap_groups);+ const size_t sh = (size_t) LDS_NT * (size_t) (L.n_ff / 32) * sizeof(block_q8_1);+ if (L.d_type == 20) native_down_lds_kernel<20><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);+ else native_down_lds_kernel<42><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);+ check("native_expert_grouped/down");+ return;+ }+ const int em = exp_mode() >= 5 ? 2 : exp_mode();+ const dim3 gd_amd((unsigned) ((L.n_embd + (em == 1 ? 3 : em == 4 ? 31 : 15)) / (em == 1 ? 4 : em == 4 ? 32 : 16)), (unsigned) cap_groups);+#define STRATA_D_AMD(T) \+ case T: if (em == 1) native_down_amd_kernel<T, 1><<<gd_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); \+ else if (em == 4) native_down_amd_kernel<T, 4><<<gd_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); \+ else native_down_amd_kernel<T, 2><<<gd_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;+ // the AMD layouts cover the IQ packs' down types; the others (Unsloth's Q4_K / Q5_K / Q5_1 / Q8_0) take the+ // CUDA layout below+ if ((em == 1 || em == 2 || em == 4) && (L.d_type == 20 || L.d_type == 23 || L.d_type == 42)) {+ switch (L.d_type) {+ STRATA_D_AMD(20) STRATA_D_AMD(23) STRATA_D_AMD(42)+ }+ } else+#undef STRATA_D_AMD+#endifswitch (L.d_type) {#define STRATA_DOWN(T) case T: launch_down<T>(gd, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;STRATA_D_FMTS(STRATA_DOWN)diff --git a/sycl/src/kernels/cuda/kv_q4.dp.cpp b/sycl/src/kernels/cuda/kv_q4.dp.cppindex 630fe2e9f..a0fcf8f78 100644--- a/sycl/src/kernels/cuda/kv_q4.dp.cpp+++ b/sycl/src/kernels/cuda/kv_q4.dp.cpp@@ -134,24 +134,28 @@ __dpct_inline__ void q4_store(uint8_t *pool, long long row, int b, int lane,if (lane < 16) blk->qs[lane] = byte;}-// One block = one 32-value group of one KV head of K (blockIdx.z = 0) or V (1); 32 threads. KV streaming: the VRAM-// page only if the block is resident (table >= 0), the host copy always (identity layout) when there is one.-__dpct_inline__ void kv_append_q4_kernel(- uint8_t *__restrict__ k_q4, uint8_t *__restrict__ v_q4,- const int32_t *__restrict__ table, const int32_t *__restrict__ step,- const float *__restrict__ kcur, const float *__restrict__ vcur,- int kv_heads, int head_dim, int page_size, KvHostPools host) {+// One block = one 32-value group of one KV head of K (plane 0) or V (plane 1) for token step_idx; 32 threads.+__dpct_inline__ void+kv_append_q4_kernel(uint8_t *__restrict__ k_q4, uint8_t *__restrict__ v_q4,+ const int32_t *__restrict__ table,+ const int32_t *__restrict__ step, int step_stride,+ int planes, const float *__restrict__ kcur,+ const float *__restrict__ vcur, int kv_heads, int head_dim,+ int page_size, KvHostPools host) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int step_idx = (int)(item_ct1.get_group(0) / (unsigned)planes);+ const bool is_v = (item_ct1.get_group(0) % (unsigned)planes) == 1u;/*DPCT1098: The '*' expression is used instead of the __ldg call. Thesetwo expressions do not provide the exact same functionality. Check thegenerated code for potential precision and/or performance issues.*/- auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();- const long long pos = (long long)*(step + kStepPos);+ const long long pos =+ (long long)*(step + (long long)step_idx * step_stride + kStepPos);const int h = item_ct1.get_group(2), b = item_ct1.get_group(1),t = item_ct1.get_local_id(2);- const bool is_v = item_ct1.get_group(0) == 1;- const float x = (is_v ? vcur : kcur)[h * head_dim + b * QK4_0 + t];+ const long long step_off = (long long) step_idx * kv_heads * head_dim;+ const float x = (is_v ? vcur : kcur)[step_off + h * head_dim + b * QK4_0 + t];uint8_t byte;const uint16_t d = q4_group(x, t, byte);const long long page = (long long) table[pos / page_size];@@ -265,19 +269,21 @@ void fwht256_cuda(const float* src, float* dst, int64_t n_rows, void* stream) {check("fwht256 launch");}-void kv_append_q4_step(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, const int32_t* step,- const float* kcur, const float* vcur, const QsaShapes& s, void* stream,- const KvHostPools* host) {+void kv_append_q4_steps(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, const int32_t* step,+ int step_stride, int n_steps, const float* kcur, const float* vcur, const QsaShapes& s,+ void* stream, const KvHostPools* host) {+ if (n_steps <= 0) return;need_256(s, "kv_append_q4");+ const int planes = (v_q4 == nullptr || (v_q4 == k_q4 && vcur == kcur)) ? 1 : 2;const dpct::dim3 grid((unsigned)s.n_head_kv, (unsigned)(s.head_dim / QK4_0),- 2);+ (unsigned)(n_steps * planes));{auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)->submit([&](sycl::handler &cgh) {- KvHostPools host_host_KvHostPools_ct9 =+ KvHostPools host_host_KvHostPools_ct11 =host ? *host : KvHostPools{};cgh.parallel_for<@@ -288,15 +294,22 @@ void kv_append_q4_step(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table,[=](sycl::nd_item<3> item_ct1)[[sycl::reqd_sub_group_size(32)]] {kv_append_q4_kernel(- k_q4, v_q4, page_table, step, kcur, vcur,- (int)s.n_head_kv, (int)s.head_dim,- (int)s.page_size, host_host_KvHostPools_ct9);+ k_q4, v_q4, page_table, step, step_stride,+ planes, kcur, vcur, (int)s.n_head_kv,+ (int)s.head_dim, (int)s.page_size,+ host_host_KvHostPools_ct11);});});}check("kv_append_q4 launch");}+void kv_append_q4_step(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, const int32_t* step,+ const float* kcur, const float* vcur, const QsaShapes& s, void* stream,+ const KvHostPools* host) {+ kv_append_q4_steps(k_q4, v_q4, page_table, step, 0, 1, kcur, vcur, s, stream, host);+}+void kv_append_q4(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, int64_t pos0, int64_t T, const float* K,const float* V, const QsaShapes& s, void* stream, const KvHostPools* host, const KvHostPools* stage) {if (T <= 0) return;diff --git a/sycl/src/kernels/cuda/kv_q8.dp.cpp b/sycl/src/kernels/cuda/kv_q8.dp.cppindex 215ea943f..15faa9cd3 100644--- a/sycl/src/kernels/cuda/kv_q8.dp.cpp+++ b/sycl/src/kernels/cuda/kv_q8.dp.cpp@@ -30,22 +30,31 @@ void validate(const QsaShapes& s, const char* what) {}// One block = one 64-value group of one KV head of K (blockIdx.z = 0) or V (1); 64 threads, one value each.+// MULTI (S26 STRATA_LFUSE): blockIdx.z = 2 * token + (K / V); token j reads step + j * step_stride and its rows at+// kcur / vcur + j * cur_stride - every token's code is the single launch's+template <bool MULTI = false>__dpct_inline__ void kv_append_q8_kernel(int8_t *__restrict__ k_q, int8_t *__restrict__ v_q,uint16_t *__restrict__ k_scale, uint16_t *__restrict__ v_scale,const int32_t *__restrict__ table, const int32_t *__restrict__ step,const float *__restrict__ kcur, const float *__restrict__ vcur,- int kv_heads, int head_dim, int page_size, KvHostPools host) {+ int kv_heads, int head_dim, int page_size, KvHostPools host,+ int step_stride = 0, int cur_stride = 0) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ if constexpr (MULTI) {+ const int j = item_ct1.get_group(0) >> 1;+ step += (size_t) j * step_stride; kcur += (size_t) j * cur_stride; vcur += (size_t) j * cur_stride;+ }/*DPCT1098: The '*' expression is used instead of the __ldg call. Thesetwo expressions do not provide the exact same functionality. Check thegenerated code for potential precision and/or performance issues.*/- auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();const long long pos = (long long)*(step + kStepPos);const int h = item_ct1.get_group(2), g = item_ct1.get_group(1),t = item_ct1.get_local_id(2);- const bool is_v = item_ct1.get_group(0) == 1;+ const bool is_v =+ MULTI ? (item_ct1.get_group(0) & 1) == 1 : item_ct1.get_group(0) == 1;const int groups = head_dim / KV_Q8_GROUP;const float x = (is_v ? vcur : kcur)[h * head_dim + g * KV_Q8_GROUP + t];// max |x| over the 64 values: two warps, then combine through shared memory in a fixed order@@ -158,8 +167,13 @@ void kv_append_q8_step(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_KvHostPools host_host_KvHostPools_ct11 =host ? *host : KvHostPools{};- cgh.parallel_for<- dpct_kernel_name<class kv_append_q8_kernel_b60fdc>>(+ /*+ DPCT1050: The template argument of the dpct_kernel_name+ could not be deduced. You need to update this code.+ */+ cgh.parallel_for<dpct_kernel_name<+ class kv_append_q8_kernel_b60fdc,+ dpct_kernel_scalar<false>>>(sycl::nd_range<3>(grid * sycl::range(1, 1, KV_Q8_GROUP),sycl::range(1, 1, KV_Q8_GROUP)),exp_props,@@ -168,13 +182,50 @@ void kv_append_q8_step(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_kv_append_q8_kernel(k_q, v_q, k_scale, v_scale, page_table, step,kcur, vcur, (int)s.n_head_kv, (int)s.head_dim,- (int)s.page_size, host_host_KvHostPools_ct11);+ (int)s.page_size, host_host_KvHostPools_ct11, 0,+ 0);});});}check("kv_append_q8 launch");}+void kv_append_q8_steps(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, const int32_t* page_table,+ const int32_t* step, int step_stride, const float* kcur, const float* vcur, int cur_stride,+ int n_tok, const QsaShapes& s, void* stream, const KvHostPools* host) {+ validate(s, "kv_append_q8 (steps)");+ if (n_tok < 1) return;+ const dpct::dim3 grid((unsigned)s.n_head_kv,+ (unsigned)(s.head_dim / KV_Q8_GROUP),+ (unsigned)(2 * n_tok));+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->submit([&](sycl::handler &cgh) {+ KvHostPools host_host_KvHostPools_ct11 =+ host ? *host : KvHostPools{};++ cgh.parallel_for<+ dpct_kernel_name<class kv_append_q8_kernel_b60fdc,+ dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(grid * sycl::range(1, 1, KV_Q8_GROUP),+ sycl::range(1, 1, KV_Q8_GROUP)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ kv_append_q8_kernel<true>(+ k_q, v_q, k_scale, v_scale, page_table, step,+ kcur, vcur, (int)s.n_head_kv, (int)s.head_dim,+ (int)s.page_size, host_host_KvHostPools_ct11,+ step_stride, cur_stride);+ });+ });+ }+ check("kv_append_q8 (steps) launch");+}+void kv_gather_q8_step(const int8_t* k_q, const int8_t* v_q, const uint16_t* k_scale, const uint16_t* v_scale,const int32_t* page_table, const int32_t* ids, const int32_t* step, int64_t max_ids,const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream) {diff --git a/sycl/src/kernels/cuda/kv_stream.dp.cpp b/sycl/src/kernels/cuda/kv_stream.dp.cppindex 5c8566e32..c713f7a62 100644--- a/sycl/src/kernels/cuda/kv_stream.dp.cpp+++ b/sycl/src/kernels/cuda/kv_stream.dp.cpp@@ -37,7 +37,14 @@ struct Runs {Runs runs_of(const QsaAttnPools& slots, const KvHostPools& host, int fmt, const QsaShapes& s) {const int rows = (int) (s.n_head_kv * s.page_size);Runs r{};- if (fmt == kKvQ4) {+ if (fmt == kKvHybrid) { // K8V4: int8 K codes, their scales, rotated q4_0 V+ const int codes = rows * (int) s.head_dim, scales = rows * (int) (s.head_dim / KV_Q8_GROUP) * 2;+ const int v = rows * (int) kv_q4_bytes_per_head((int) s.head_dim);+ r.src[0] = (const uint8_t*) host.k_q; r.dst[0] = (uint8_t*) slots.k_q; r.len[0] = codes;+ r.src[1] = (const uint8_t*) host.k_scale; r.dst[1] = (uint8_t*) slots.k_scale; r.len[1] = scales;+ r.src[2] = (const uint8_t*) host.v_q4; r.dst[2] = (uint8_t*) slots.v_q4; r.len[2] = v;+ r.n = 3;+ } else if (fmt == kKvQ4) {const int bytes = rows * (int) kv_q4_bytes_per_head((int) s.head_dim);r.src[0] = (const uint8_t*) host.k_q4; r.dst[0] = (uint8_t*) slots.k_q4; r.len[0] = bytes;r.src[1] = (const uint8_t*) host.v_q4; r.dst[1] = (uint8_t*) slots.v_q4; r.len[1] = bytes;@@ -159,8 +166,10 @@ auto &s_nmiss = *sycl::ext::oneapi::group_local_memory_for_overwrite<int>(}}}- dpct::atomic_fetch_add<sycl::access::address_space::generic_space>(- &s_lookups, lookups);+ if (lookups > 0)+ dpct::atomic_fetch_add<sycl::access::address_space::generic_space>(+ &s_lookups, lookups); // (#783, stuchapin909) most threads see none:+ // skip the shared atomic/*DPCT1065: Consider replacing sycl::nd_item::barrier() withsycl::nd_item::barrier(sycl::access::fence_space::local_space) for better@@ -300,6 +309,9 @@ __dpct_inline__ void ring_kernel(int32_t *table, long long n_blocks,uint64_t kv_block_bytes(const QsaShapes& s, int fmt) {const uint64_t rows = (uint64_t) (s.n_head_kv * s.page_size);+ if (fmt == kKvHybrid)+ return rows * (uint64_t) s.head_dim + rows * (uint64_t) (s.head_dim / KV_Q8_GROUP) * 2 ++ rows * kv_q4_bytes_per_head((int) s.head_dim);if (fmt == kKvQ4) return rows * kv_q4_bytes_per_head((int) s.head_dim) * 2;return fmt == kKvInt8 ? rows * (uint64_t) s.head_dim * 2 + rows * (uint64_t) (s.head_dim / KV_Q8_GROUP) * 2 * 2: rows * (uint64_t) s.head_dim * 2 * 2;diff --git a/sycl/src/kernels/cuda/native_bf16.dp.cpp b/sycl/src/kernels/cuda/native_bf16.dp.cppindex 61f059015..28f8db8e0 100644--- a/sycl/src/kernels/cuda/native_bf16.dp.cpp+++ b/sycl/src/kernels/cuda/native_bf16.dp.cpp@@ -3,8 +3,10 @@#include <dpct/dpct.hpp>#include "strata/sycl_queue.hpp"#include "strata/kernels/bf16_gemv.hpp"+#include "s26_tsum.dp.hpp"#include "strata/kernels/bf16_bits.hpp"+#include <cstdlib>#include <limits>#include <stdexcept>#include <string>@@ -63,10 +65,8 @@ __dpct_inline__ void bf16_f32_mmvf_kernel(const float *__restrict__ x,auto &partials =*sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(sycl::ext::oneapi::this_work_item::get_work_group<3>());- if constexpr (BLOCK_SIZE > 32) {- if (t < 32) partials[t] = 0.0f;- item_ct1.barrier(sycl::access::fence_space::local_space);- }+ if (t < 32) partials[t] = 0.0f;+ item_ct1.barrier(sycl::access::fence_space::local_space);float acc = 0.0f;for (int pair = t; pair < n_in / 2; pair += BLOCK_SIZE) {const uint32_t weight = weights2[pair];@@ -101,7 +101,7 @@ __dpct_inline__ void bf16_f32_mmvf_kernel(const float *__restrict__ x,// the same kernel for up to 8 activation rows - the weight row is read ONCE and every// token keeps its own accumulator with exactly the single-row kernel's order (pairs, two ordered FMAs, the same warp// and block reductions), so each output is bit-identical to a bf16_f32_mmvf_kernel launch of its own.-template <int BLOCK_SIZE, int NT>+template <int BLOCK_SIZE, int NT, bool EXACT_T = true>__dpct_inline__ void bf16_f32_mmvf_multi_kernel(const float *__restrict__ x, int64_t ldx, const uint16_t *__restrict__ w,float *__restrict__ y, int64_t ldy, int n_in, int n_tok) {@@ -112,24 +112,35 @@ __dpct_inline__ void bf16_f32_mmvf_multi_kernel(auto &partials =*sycl::ext::oneapi::group_local_memory_for_overwrite<float[NT][32]>(sycl::ext::oneapi::this_work_item::get_work_group<3>());- if constexpr (BLOCK_SIZE > 32) {- if (t < 32)+ if (t < 32) {#pragma unroll- for (int k = 0; k < NT; ++k) partials[k][t] = 0.0f;- item_ct1.barrier(sycl::access::fence_space::local_space);+ for (int k = 0; k < NT; ++k) partials[k][t] = 0.0f;}+ item_ct1.barrier(sycl::access::fence_space::local_space);float acc[NT];#pragma unrollfor (int k = 0; k < NT; ++k) acc[k] = 0.0f;for (int pair = t; pair < n_in / 2; pair += BLOCK_SIZE) {- const uint32_t weight = weights2[pair];+ /*+ DPCT1098: The '*' expression is used instead of the __ldg call.+ These two expressions do not provide the exact same functionality. Check+ the generated code for potential precision and/or performance issues.+ */+ const uint32_t weight = *(weights2 + pair);const float w0 = f32_from_bf16((uint16_t) weight), w1 = f32_from_bf16((uint16_t) (weight >> 16));#pragma unrollfor (int k = 0; k < NT; ++k) {- if (k < n_tok) {+ if (EXACT_T || k < n_tok) {+ /*+ DPCT1098: The '*' expression is used instead of the __ldg+ call. These two expressions do not provide the exact same+ functionality. Check the generated code for potential precision+ and/or performance issues.+ */const sycl::float2 input =- reinterpret_cast<const sycl::float2 *>(x + (size_t)k *- ldx)[pair];+ *(reinterpret_cast<const sycl::float2 *>(x ++ (size_t)k * ldx) ++ pair);/*DPCT1013: The rounding mode could not be specified and thegenerated code may have different accuracy than the original@@ -148,20 +159,363 @@ __dpct_inline__ void bf16_f32_mmvf_multi_kernel(}}#pragma unroll- for (int k = 0; k < NT; ++k) acc[k] = mmvf_warp_sum(acc[k]);+ for (int k = 0; k < NT; ++k)+ if (EXACT_T || k < n_tok) acc[k] = mmvf_warp_sum(acc[k]);if constexpr (BLOCK_SIZE > 32) {if ((t & 31) == 0)#pragma unroll- for (int k = 0; k < NT; ++k) partials[k][t / 32] = acc[k];+ for (int k = 0; k < NT; ++k)+ if (EXACT_T || k < n_tok) partials[k][t / 32] = acc[k];item_ct1.barrier(sycl::access::fence_space::local_space);if (t < 32)#pragma unroll- for (int k = 0; k < NT; ++k) acc[k] = mmvf_warp_sum(partials[k][t]);+ for (int k = 0; k < NT; ++k)+ if (EXACT_T || k < n_tok) acc[k] = mmvf_warp_sum(partials[k][t]);}if (t == 0)#pragma unrollfor (int k = 0; k < NT; ++k)- if (k < n_tok) y[(size_t)k * ldy + item_ct1.get_group(2)] = acc[k];+ if (EXACT_T || k < n_tok)+ y[(size_t)k * ldy + item_ct1.get_group(2)] = acc[k];+}++// S25 (STRATA_MMVF_ROWS=1): RPB output rows per block. Each block read its row's weights once but all T activation+// rows again (n_out blocks x T x n_in floats through L2 - the part that grew with T); here a block reads the+// activations once for RPB rows. Per output, thread t still walks pairs t, t + BLOCK_SIZE, ... with the same two+// ordered FMAs and the same warp and block reductions: bit-identical to bf16_f32_mmvf_multi_kernel.+// S26 STRATA_LFUSE=1 (AUX): one more block computes row 0 of w_aux into y_aux[k * ldy_aux] - the same per-output+// code, so each aux output is bitwise what its own bf16_f32_mmvf_multi_kernel launch gave (the shared expert's gate)+template <int BLOCK_SIZE, int NT, int RPB, bool TS = false, bool AUX = false>+/*+DPCT1110: The total declared local variable size in device function+bf16_f32_mmvf_rows_kernel exceeds 128 bytes and may cause high register+pressure. Consult with your hardware vendor to find the total register size+available and adjust the code, or use smaller sub-group size to avoid high+register pressure.+*/+__dpct_inline__ void bf16_f32_mmvf_rows_kernel(+ const float *__restrict__ x, int64_t ldx, const uint16_t *__restrict__ w,+ float *__restrict__ y, int64_t ldy, int n_in, int n_out, int n_tok,+ const uint16_t *__restrict__ w_aux = nullptr,+ float *__restrict__ y_aux = nullptr, int64_t ldy_aux = 0) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int t = item_ct1.get_local_id(2);+ int o0 = item_ct1.get_group(2) * RPB;+ if constexpr (AUX) {+ if (item_ct1.get_group(2) == item_ct1.get_group_range(2) - 1) {+ w = w_aux; y = y_aux; ldy = ldy_aux; n_out = 1; o0 = 0;+ }+ }+ auto &partials = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ float[RPB][NT][32]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ if constexpr (BLOCK_SIZE > 32) {+ if (t < 32)+#pragma unroll+ for (int r = 0; r < RPB; ++r)+#pragma unroll+ for (int k = 0; k < NT; ++k) partials[r][k][t] = 0.0f;+ item_ct1.barrier(sycl::access::fence_space::local_space);+ }+ float acc[RPB][NT];+#pragma unroll+ for (int r = 0; r < RPB; ++r)+#pragma unroll+ for (int k = 0; k < NT; ++k) acc[r][k] = 0.0f;+ for (int pair = t; pair < n_in / 2; pair += BLOCK_SIZE) {+ sycl::float2 in[NT];+#pragma unroll+ for (int k = 0; k < NT; ++k)+ if (k < n_tok) in[k] = reinterpret_cast<const sycl::float2 *>(+ x + (size_t)k * ldx)[pair];+#pragma unroll+ for (int r = 0; r < RPB; ++r) {+ if (o0 + r >= n_out) break;+ const uint32_t weight = reinterpret_cast<const uint32_t*>(w + (size_t) (o0 + r) * n_in)[pair];+ const float w0 = f32_from_bf16((uint16_t) weight), w1 = f32_from_bf16((uint16_t) (weight >> 16));+#pragma unroll+ for (int k = 0; k < NT; ++k) {+ if (k < n_tok) {+ /*+ DPCT1013: The rounding mode could not be specified and+ the generated code may have different accuracy than the+ original code. Verify the correctness. SYCL math built-in+ function rounding mode is aligned with OpenCL C 1.2+ standard.+ */+ acc[r][k] = sycl::fma(w0, in[k].x(), acc[r][k]);+ /*+ DPCT1013: The rounding mode could not be specified and+ the generated code may have different accuracy than the+ original code. Verify the correctness. SYCL math built-in+ function rounding mode is aligned with OpenCL C 1.2+ standard.+ */+ acc[r][k] = sycl::fma(w1, in[k].y(), acc[r][k]);+ }+ }+ }+ }+ if constexpr (TS) { // S26 STRATA_TSUM=1: the RPB x NT warp sums (both stages) as transposed butterflies, bitwise the same+ constexpr int V = RPB * NT, P = s26ts::pow2_ceil(V);+ const int lane = t & 31, j = s26ts::tsum_token<P>(lane);+ const bool own = lane == s26ts::tsum_lane<P>(j) && j < V;+ float v[P];+#pragma unroll+ for (int q = 0; q < P; ++q) v[q] = q < V ? acc[q / NT][q % NT] : 0.0f;+ float sum = s26ts::tsum<P>(v, lane);+ if constexpr (BLOCK_SIZE > 32) {+ if (own) partials[j / NT][j % NT][t / 32] = sum;+ item_ct1.barrier(sycl::access::fence_space::local_space);+ if (t >= 32) return;+#pragma unroll+ for (int q = 0; q < P; ++q) v[q] = q < V ? partials[q / NT][q % NT][t] : 0.0f;+ sum = s26ts::tsum<P>(v, lane);+ }+ const int r = j / NT, k = j % NT;+ if (own && o0 + r < n_out && k < n_tok) y[(size_t) k * ldy + o0 + r] = sum;+ return;+ }+#pragma unroll+ for (int r = 0; r < RPB; ++r)+#pragma unroll+ for (int k = 0; k < NT; ++k) acc[r][k] = mmvf_warp_sum(acc[r][k]);+ if constexpr (BLOCK_SIZE > 32) {+ if ((t & 31) == 0)+#pragma unroll+ for (int r = 0; r < RPB; ++r)+#pragma unroll+ for (int k = 0; k < NT; ++k) partials[r][k][t / 32] = acc[r][k];+ /*+ DPCT1064: Migrated __syncthreads call is used in a macro/template+ definition and may not be valid for all macro/template uses. Adjust the+ code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ if (t < 32)+#pragma unroll+ for (int r = 0; r < RPB; ++r)+#pragma unroll+ for (int k = 0; k < NT; ++k) acc[r][k] = mmvf_warp_sum(partials[r][k][t]);+ }+ if (t == 0)+#pragma unroll+ for (int r = 0; r < RPB; ++r)+ if (o0 + r < n_out)+#pragma unroll+ for (int k = 0; k < NT; ++k)+ if (k < n_tok) y[(size_t) k * ldy + o0 + r] = acc[r][k];+}++template <int B>+void launch_rows(const float *x, int64_t ldx, const uint16_t *w, float *y,+ int64_t ldy, int n_in, int n_out, int n_tok,+ dpct::queue_ptr st, const uint16_t *w_aux = nullptr,+ float *y_aux = nullptr, int64_t ldy_aux = 0) {+ constexpr int RPB = 4;+ const unsigned nb = (unsigned) ((n_out + RPB - 1) / RPB);+ static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }();+ if (w_aux != nullptr) { // S26 STRATA_LFUSE: + one aux row block+/*+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. Adjust+the work-group size if needed.+*/+/*+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. Adjust+the work-group size if needed.+*/+#define S26_AUX(TSV) \+ if (n_tok <= 4) { \+ auto exp_props = sycl::ext::oneapi::experimental::properties{ \+ sycl::ext::oneapi::experimental::use_root_sync}; \+ \+ st->submit([&](sycl::handler &cgh) { \+ auto x_ct0 = x; \+ auto ldx_ct1 = ldx; \+ auto w_ct2 = w; \+ auto y_ct3 = y; \+ auto ldy_ct4 = ldy; \+ auto n_in_ct5 = n_in; \+ auto n_out_ct6 = n_out; \+ auto n_tok_ct7 = n_tok; \+ auto w_aux_ct8 = w_aux; \+ auto y_aux_ct9 = y_aux; \+ auto ldy_aux_ct10 = ldy_aux; \+ \+ cgh.parallel_for<dpct_kernel_name< \+ class bf16_f32_mmvf_rows_kernel_7c05e5, dpct_kernel_scalar<B>, \+ dpct_kernel_scalar<4>, dpct_kernel_scalar<RPB>, \+ dpct_kernel_scalar<TSV>, dpct_kernel_scalar<true>>>( \+ sycl::nd_range<3>(sycl::range(1, 1, nb + 1) * \+ sycl::range(1, 1, B), \+ sycl::range(1, 1, B)), \+ exp_props, \+ [=](sycl::nd_item<3> item_ct1) \+ [[sycl::reqd_sub_group_size(32)]] { \+ bf16_f32_mmvf_rows_kernel<B, 4, RPB, TSV, true>( \+ x_ct0, ldx_ct1, w_ct2, y_ct3, ldy_ct4, n_in_ct5, \+ n_out_ct6, n_tok_ct7, w_aux_ct8, y_aux_ct9, \+ ldy_aux_ct10); \+ }); \+ }); \+ } else { \+ auto exp_props = sycl::ext::oneapi::experimental::properties{ \+ sycl::ext::oneapi::experimental::use_root_sync}; \+ \+ st->submit([&](sycl::handler &cgh) { \+ auto x_ct0 = x; \+ auto ldx_ct1 = ldx; \+ auto w_ct2 = w; \+ auto y_ct3 = y; \+ auto ldy_ct4 = ldy; \+ auto n_in_ct5 = n_in; \+ auto n_out_ct6 = n_out; \+ auto n_tok_ct7 = n_tok; \+ auto w_aux_ct8 = w_aux; \+ auto y_aux_ct9 = y_aux; \+ auto ldy_aux_ct10 = ldy_aux; \+ \+ cgh.parallel_for<dpct_kernel_name< \+ class bf16_f32_mmvf_rows_kernel_681929, dpct_kernel_scalar<B>, \+ dpct_kernel_scalar<8>, dpct_kernel_scalar<RPB>, \+ dpct_kernel_scalar<TSV>, dpct_kernel_scalar<true>>>( \+ sycl::nd_range<3>(sycl::range(1, 1, nb + 1) * \+ sycl::range(1, 1, B), \+ sycl::range(1, 1, B)), \+ exp_props, \+ [=](sycl::nd_item<3> item_ct1) \+ [[sycl::reqd_sub_group_size(32)]] { \+ bf16_f32_mmvf_rows_kernel<B, 8, RPB, TSV, true>( \+ x_ct0, ldx_ct1, w_ct2, y_ct3, ldy_ct4, n_in_ct5, \+ n_out_ct6, n_tok_ct7, w_aux_ct8, y_aux_ct9, \+ ldy_aux_ct10); \+ }); \+ }); \+ }+ if (ts) { S26_AUX(true) } else { S26_AUX(false) }+#undef S26_AUX+ return;+ }+ if (ts) {+ /*+ 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. Adjust the work-group size if needed.+ */+ if (n_tok <= 4) {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ st->/*+ DPCT1050: The template argument of the dpct_kernel_name could not be+ deduced. You need to update this code.+ */+ parallel_for<dpct_kernel_name<+ class bf16_f32_mmvf_rows_kernel_ff3610,+ dpct_kernel_scalar<B>, dpct_kernel_scalar<4>,+ dpct_kernel_scalar<RPB>, dpct_kernel_scalar<true>,+ dpct_kernel_scalar<false>>>(+ sycl::nd_range<3>(sycl::range(1, 1, nb) *+ sycl::range(1, 1, B),+ sycl::range(1, 1, B)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ bf16_f32_mmvf_rows_kernel<B, 4, RPB, true>(+ x, ldx, w, y, ldy, n_in, n_out, n_tok);+ });+ }+ /*+ 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. Adjust the work-group size if needed.+ */+ else {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ st->/*+ DPCT1050: The template argument of the dpct_kernel_name could not be+ deduced. You need to update this code.+ */+ parallel_for<dpct_kernel_name<+ class bf16_f32_mmvf_rows_kernel_1b1bb5,+ dpct_kernel_scalar<B>, dpct_kernel_scalar<8>,+ dpct_kernel_scalar<RPB>, dpct_kernel_scalar<true>,+ dpct_kernel_scalar<false>>>(+ sycl::nd_range<3>(sycl::range(1, 1, nb) *+ sycl::range(1, 1, B),+ sycl::range(1, 1, B)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ bf16_f32_mmvf_rows_kernel<B, 8, RPB, true>(+ x, ldx, w, y, ldy, n_in, n_out, n_tok);+ });+ }+ return;+ }+ /*+ 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.+ Adjust the work-group size if needed.+ */+ if (n_tok <= 4) {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ st->/*+ DPCT1050: The template argument of the dpct_kernel_name could not be+ deduced. You need to update this code.+ */+ parallel_for<dpct_kernel_name<+ class bf16_f32_mmvf_rows_kernel_7ff80d, dpct_kernel_scalar<B>,+ dpct_kernel_scalar<4>, dpct_kernel_scalar<RPB>,+ dpct_kernel_scalar<false>,+ dpct_kernel_scalar<false>>>(+ sycl::nd_range<3>(sycl::range(1, 1, nb) * sycl::range(1, 1, B),+ sycl::range(1, 1, B)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ bf16_f32_mmvf_rows_kernel<B, 4, RPB>(+ x, ldx, w, y, ldy, n_in, n_out, n_tok);+ });+ }+ /*+ 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.+ Adjust the work-group size if needed.+ */+ else {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ st->/*+ DPCT1050: The template argument of the dpct_kernel_name could not be+ deduced. You need to update this code.+ */+ parallel_for<dpct_kernel_name<+ class bf16_f32_mmvf_rows_kernel_13db68, dpct_kernel_scalar<B>,+ dpct_kernel_scalar<8>, dpct_kernel_scalar<RPB>,+ dpct_kernel_scalar<false>,+ dpct_kernel_scalar<false>>>(+ sycl::nd_range<3>(sycl::range(1, 1, nb) * sycl::range(1, 1, B),+ sycl::range(1, 1, B)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ bf16_f32_mmvf_rows_kernel<B, 8, RPB>(+ x, ldx, w, y, ldy, n_in, n_out, n_tok);+ });+ }}int mmvf_block_size(int64_t n_in) {@@ -179,6 +533,51 @@ int mmvf_block_size(int64_t n_in) {} // namespace+bool bf16_gemv_fp32_mmvf_multi_aux(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy,+ int64_t n_in, int64_t n_out, int n_tok, const uint16_t* w_aux, float* y_aux,+ int64_t ldy_aux, void* stream) {+ static const bool rows = [] { const char* v = std::getenv("STRATA_MMVF_ROWS"); return v && v[0] == '1'; }();+ // exactly the conditions under which both calls would take the rows / multi kernels at the same block size+ if (!rows || n_out < 64 || n_tok < 2 || n_tok > 8 || n_in <= 0 || (n_in & 1) != 0 || (ldx & 1) != 0 || x == nullptr ||+ w == nullptr || y == nullptr || w_aux == nullptr || y_aux == nullptr || (reinterpret_cast<uintptr_t>(x) & 7u) != 0)+ return false;+ const dpct::queue_ptr st = strata::q_of(stream);+ const int ni = (int) n_in, no = (int) n_out;+ switch (mmvf_block_size(n_in)) {+ case 32: launch_rows<32>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break;+ case 64: launch_rows<64>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break;+ case 96: launch_rows<96>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break;+ case 128: launch_rows<128>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break;+ case 160: launch_rows<160>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break;+ case 192: launch_rows<192>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break;+ case 224: launch_rows<224>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break;+ default: launch_rows<256>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break;+ }+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use the+ error codes. The cudaGetLastError function call was replaced with 0. You+ need to rewrite this code.+ */+ const dpct::err0 result = 0;+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (result != 0)+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use+ error codes. Please replace the "get_error_string_dummy(...)" with a+ real error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ throw std::runtime_error(+ std::string("bf16_gemv_fp32_mmvf_multi_aux launch: ") ++ dpct::get_error_string_dummy(result));+ return true;+}+void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy,int64_t n_in, int64_t n_out, int n_tok, void* stream) {if (n_tok == 1 && ldy >= n_out) { bf16_gemv_fp32_mmvf(x, w, y, n_in, n_out, stream); return; }@@ -186,9 +585,76 @@ void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, fw == nullptr || y == nullptr || (reinterpret_cast<uintptr_t>(x) & 7u) != 0)throw std::invalid_argument("bf16_gemv_fp32_mmvf_multi: 1..8 rows, even n_in/ldx, aligned pointers");const dpct::queue_ptr st = strata::q_of(stream);+ static const bool rows = [] { const char* v = std::getenv("STRATA_MMVF_ROWS"); return v && v[0] == '1'; }();+ if (rows && n_out >= 64) {+ const int ni = (int) n_in, no = (int) n_out;+ switch (mmvf_block_size(n_in)) {+ case 32: launch_rows<32>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;+ case 64: launch_rows<64>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;+ case 96: launch_rows<96>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;+ case 128: launch_rows<128>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;+ case 160: launch_rows<160>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;+ case 192: launch_rows<192>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;+ case 224: launch_rows<224>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;+ default: launch_rows<256>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;+ }+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use+ the error codes. The cudaGetLastError function call was replaced with 0.+ You need to rewrite this code.+ */+ const dpct::err0 result = 0;+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (result != 0)+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use+ error codes. Please replace the "get_error_string_dummy(...)" with a+ real error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ throw std::runtime_error(+ std::string("bf16_gemv_fp32_mmvf_multi launch: ") ++ dpct::get_error_string_dummy(result));+ return;+ }#define STRATA_MMVF_M(N) \case N: \- if (n_tok <= 4) { \+ switch (n_tok) { \+ case 1: { \+ auto exp_props = sycl::ext::oneapi::experimental::properties{ \+ sycl::ext::oneapi::experimental::use_root_sync}; \+ \+ st->submit([&](sycl::handler &cgh) { \+ auto x_ct0 = x; \+ auto ldx_ct1 = ldx; \+ auto w_ct2 = w; \+ auto y_ct3 = y; \+ auto ldy_ct4 = ldy; \+ auto n_in_ct5 = (int)n_in; \+ auto n_tok_ct6 = n_tok; \+ \+ cgh.parallel_for<dpct_kernel_name< \+ class bf16_f32_mmvf_multi_kernel_27194f, \+ dpct_kernel_scalar<N>, dpct_kernel_scalar<1>, \+ dpct_kernel_scalar<true>>>( \+ sycl::nd_range<3>(sycl::range(1, 1, (unsigned)n_out) * \+ sycl::range(1, 1, N), \+ sycl::range(1, 1, N)), \+ exp_props, \+ [=](sycl::nd_item<3> item_ct1) \+ [[sycl::reqd_sub_group_size(32)]] { \+ bf16_f32_mmvf_multi_kernel<N, 1, true>( \+ x_ct0, ldx_ct1, w_ct2, y_ct3, ldy_ct4, \+ n_in_ct5, n_tok_ct6); \+ }); \+ }); \+ } break; \+ case 2: { \auto exp_props = sycl::ext::oneapi::experimental::properties{ \sycl::ext::oneapi::experimental::use_root_sync}; \\@@ -202,20 +668,22 @@ void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, fauto n_tok_ct6 = n_tok; \\cgh.parallel_for<dpct_kernel_name< \- class bf16_f32_mmvf_multi_kernel_c4da69, \- dpct_kernel_scalar<N>, dpct_kernel_scalar<4>>>( \+ class bf16_f32_mmvf_multi_kernel_ded48c, \+ dpct_kernel_scalar<N>, dpct_kernel_scalar<2>, \+ dpct_kernel_scalar<true>>>( \sycl::nd_range<3>(sycl::range(1, 1, (unsigned)n_out) * \sycl::range(1, 1, N), \sycl::range(1, 1, N)), \exp_props, \[=](sycl::nd_item<3> item_ct1) \[[sycl::reqd_sub_group_size(32)]] { \- bf16_f32_mmvf_multi_kernel<N, 4>( \+ bf16_f32_mmvf_multi_kernel<N, 2, true>( \x_ct0, ldx_ct1, w_ct2, y_ct3, ldy_ct4, \n_in_ct5, n_tok_ct6); \}); \}); \- } else { \+ } break; \+ case 3: { \auto exp_props = sycl::ext::oneapi::experimental::properties{ \sycl::ext::oneapi::experimental::use_root_sync}; \\@@ -229,19 +697,137 @@ void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, fauto n_tok_ct6 = n_tok; \\cgh.parallel_for<dpct_kernel_name< \- class bf16_f32_mmvf_multi_kernel_e8550d, \- dpct_kernel_scalar<N>, dpct_kernel_scalar<8>>>( \+ class bf16_f32_mmvf_multi_kernel_a6c94f, \+ dpct_kernel_scalar<N>, dpct_kernel_scalar<3>, \+ dpct_kernel_scalar<true>>>( \sycl::nd_range<3>(sycl::range(1, 1, (unsigned)n_out) * \sycl::range(1, 1, N), \sycl::range(1, 1, N)), \exp_props, \[=](sycl::nd_item<3> item_ct1) \[[sycl::reqd_sub_group_size(32)]] { \- bf16_f32_mmvf_multi_kernel<N, 8>( \+ bf16_f32_mmvf_multi_kernel<N, 3, true>( \x_ct0, ldx_ct1, w_ct2, y_ct3, ldy_ct4, \n_in_ct5, n_tok_ct6); \}); \}); \+ } break; \+ case 4: { \+ auto exp_props = sycl::ext::oneapi::experimental::properties{ \+ sycl::ext::oneapi::experimental::use_root_sync}; \+ \+ st->submit([&](sycl::handler &cgh) { \+ auto x_ct0 = x; \+ auto ldx_ct1 = ldx; \+ auto w_ct2 = w; \+ auto y_ct3 = y; \+ auto ldy_ct4 = ldy; \+ auto n_in_ct5 = (int)n_in; \+ auto n_tok_ct6 = n_tok; \+ \+ cgh.parallel_for<dpct_kernel_name< \+ class bf16_f32_mmvf_multi_kernel_eba2ed, \+ dpct_kernel_scalar<N>, dpct_kernel_scalar<4>, \+ dpct_kernel_scalar<true>>>( \+ sycl::nd_range<3>(sycl::range(1, 1, (unsigned)n_out) * \+ sycl::range(1, 1, N), \+ sycl::range(1, 1, N)), \+ exp_props, \+ [=](sycl::nd_item<3> item_ct1) \+ [[sycl::reqd_sub_group_size(32)]] { \+ bf16_f32_mmvf_multi_kernel<N, 4, true>( \+ x_ct0, ldx_ct1, w_ct2, y_ct3, ldy_ct4, \+ n_in_ct5, n_tok_ct6); \+ }); \+ }); \+ } break; \+ case 5: { \+ auto exp_props = sycl::ext::oneapi::experimental::properties{ \+ sycl::ext::oneapi::experimental::use_root_sync}; \+ \+ st->submit([&](sycl::handler &cgh) { \+ auto x_ct0 = x; \+ auto ldx_ct1 = ldx; \+ auto w_ct2 = w; \+ auto y_ct3 = y; \+ auto ldy_ct4 = ldy; \+ auto n_in_ct5 = (int)n_in; \+ auto n_tok_ct6 = n_tok; \+ \+ cgh.parallel_for<dpct_kernel_name< \+ class bf16_f32_mmvf_multi_kernel_3318a1, \+ dpct_kernel_scalar<N>, dpct_kernel_scalar<5>, \+ dpct_kernel_scalar<true>>>( \+ sycl::nd_range<3>(sycl::range(1, 1, (unsigned)n_out) * \+ sycl::range(1, 1, N), \+ sycl::range(1, 1, N)), \+ exp_props, \+ [=](sycl::nd_item<3> item_ct1) \+ [[sycl::reqd_sub_group_size(32)]] { \+ bf16_f32_mmvf_multi_kernel<N, 5, true>( \+ x_ct0, ldx_ct1, w_ct2, y_ct3, ldy_ct4, \+ n_in_ct5, n_tok_ct6); \+ }); \+ }); \+ } break; \+ case 6: { \+ auto exp_props = sycl::ext::oneapi::experimental::properties{ \+ sycl::ext::oneapi::experimental::use_root_sync}; \+ \+ st->submit([&](sycl::handler &cgh) { \+ auto x_ct0 = x; \+ auto ldx_ct1 = ldx; \+ auto w_ct2 = w; \+ auto y_ct3 = y; \+ auto ldy_ct4 = ldy; \+ auto n_in_ct5 = (int)n_in; \+ auto n_tok_ct6 = n_tok; \+ \+ cgh.parallel_for<dpct_kernel_name< \+ class bf16_f32_mmvf_multi_kernel_eddebc, \+ dpct_kernel_scalar<N>, dpct_kernel_scalar<6>, \+ dpct_kernel_scalar<true>>>( \+ sycl::nd_range<3>(sycl::range(1, 1, (unsigned)n_out) * \+ sycl::range(1, 1, N), \+ sycl::range(1, 1, N)), \+ exp_props, \+ [=](sycl::nd_item<3> item_ct1) \+ [[sycl::reqd_sub_group_size(32)]] { \+ bf16_f32_mmvf_multi_kernel<N, 6, true>( \+ x_ct0, ldx_ct1, w_ct2, y_ct3, ldy_ct4, \+ n_in_ct5, n_tok_ct6); \+ }); \+ }); \+ } break; \+ default: { \+ auto exp_props = sycl::ext::oneapi::experimental::properties{ \+ sycl::ext::oneapi::experimental::use_root_sync}; \+ \+ st->submit([&](sycl::handler &cgh) { \+ auto x_ct0 = x; \+ auto ldx_ct1 = ldx; \+ auto w_ct2 = w; \+ auto y_ct3 = y; \+ auto ldy_ct4 = ldy; \+ auto n_in_ct5 = (int)n_in; \+ auto n_tok_ct6 = n_tok; \+ \+ cgh.parallel_for<dpct_kernel_name< \+ class bf16_f32_mmvf_multi_kernel_b73f0b, \+ dpct_kernel_scalar<N>, dpct_kernel_scalar<8>, \+ dpct_kernel_scalar<false>>>( \+ sycl::nd_range<3>(sycl::range(1, 1, (unsigned)n_out) * \+ sycl::range(1, 1, N), \+ sycl::range(1, 1, N)), \+ exp_props, \+ [=](sycl::nd_item<3> item_ct1) \+ [[sycl::reqd_sub_group_size(32)]] { \+ bf16_f32_mmvf_multi_kernel<N, 8, false>( \+ x_ct0, ldx_ct1, w_ct2, y_ct3, ldy_ct4, \+ n_in_ct5, n_tok_ct6); \+ }); \+ }); \+ } break; \} breakswitch (mmvf_block_size(n_in)) {STRATA_MMVF_M(32); STRATA_MMVF_M(64); STRATA_MMVF_M(96); STRATA_MMVF_M(128);@@ -342,4 +928,17 @@ void bf16_gemv_fp32_mmvf(const float* x, const uint16_t* w, float* y,}++void bf16_gemv_fp32_mmvf_cols(const float* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, int ncols,+ void* stream) {+ // columns contiguous: the existing multi-row kernel (weight read once, each output bitwise its one-row call),+ // up to 8 rows per launch+ for (int c0 = 0; c0 < ncols; c0 += 8) {+ const int nc = ncols - c0 < 8 ? ncols - c0 : 8;+ if (nc == 1) bf16_gemv_fp32_mmvf(x + (size_t) c0 * n_in, w, y + (size_t) c0 * n_out, n_in, n_out, stream);+ else bf16_gemv_fp32_mmvf_multi(x + (size_t) c0 * n_in, n_in, w, y + (size_t) c0 * n_out, n_out, n_in, n_out, nc,+ stream);+ }+}+} // namespace strata::kernelsdiff --git a/sycl/src/kernels/cuda/native_gr_norm.dp.cpp b/sycl/src/kernels/cuda/native_gr_norm.dp.cppindex 63258c375..8c7eb9eca 100644--- a/sycl/src/kernels/cuda/native_gr_norm.dp.cpp+++ b/sycl/src/kernels/cuda/native_gr_norm.dp.cpp@@ -59,9 +59,12 @@ __dpct_inline__ void weighted_rms_norm(const float *__restrict__ input,float epsilon) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();const int tid = item_ct1.get_local_id(2);- const std::size_t row_offset = std::size_t(item_ct1.get_group(2)) * n_cols;+ const std::size_t row =+ std::size_t(item_ct1.get_group(1)) * item_ct1.get_group_range(2) ++ item_ct1.get_group(2);+ const std::size_t row_offset = row * n_cols;input += row_offset;- gamma += row_offset;+ gamma += std::size_t(item_ct1.get_group(2)) * n_cols;output += row_offset;float partial = 0.0f;for (int col = tid; col < n_cols; col += BlockSize) {@@ -99,21 +102,26 @@ void check_pointer(const void* p) {void native_gr_rms_norm_weighted(const float* input, const float* gamma, float* output,int n_cols, int n_rows, float epsilon, void* stream) {- if (n_cols <= 0 || n_rows <= 0 || !std::isfinite(epsilon) || epsilon < 0.0f)+ native_gr_rms_norm_weighted_multi(input, gamma, output, n_cols, n_rows, 1, epsilon, stream);+}++void native_gr_rms_norm_weighted_multi(const float* input, const float* gamma, float* output,+ int n_cols, int n_rows, int n_tok, float epsilon, void* stream) {+ if (n_cols <= 0 || n_rows <= 0 || n_tok <= 0 || !std::isfinite(epsilon) || epsilon < 0.0f)throw std::invalid_argument("native GR RMSNorm requires positive dimensions and finite nonnegative epsilon");check_pointer(input);check_pointer(gamma);check_pointer(output);const auto cuda_stream = strata::q_of(stream);+ const dpct::dim3 grid{unsigned(n_rows), unsigned(n_tok), 1u};if (n_cols < 1024){auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};cuda_stream->parallel_for<dpct_kernel_name<- class weighted_rms_norm_46d94c, dpct_kernel_scalar<256>>>(- sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_rows)) *- sycl::range(1, 1, 256),+ class weighted_rms_norm_60b509, dpct_kernel_scalar<256>>>(+ sycl::nd_range<3>(grid * sycl::range(1, 1, 256),sycl::range(1, 1, 256)),exp_props,[=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {@@ -130,9 +138,8 @@ void native_gr_rms_norm_weighted(const float* input, const float* gamma, float*sycl::ext::oneapi::experimental::use_root_sync};cuda_stream->parallel_for<dpct_kernel_name<- class weighted_rms_norm_11a6fe, dpct_kernel_scalar<1024>>>(- sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_rows)) *- sycl::range(1, 1, 1024),+ class weighted_rms_norm_9382c8, dpct_kernel_scalar<1024>>>(+ sycl::nd_range<3>(grid * sycl::range(1, 1, 1024),sycl::range(1, 1, 1024)),exp_props,[=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {diff --git a/sycl/src/kernels/cuda/native_gr_postops.dp.cpp b/sycl/src/kernels/cuda/native_gr_postops.dp.cppindex 436af20f3..a8f1c9c44 100644--- a/sycl/src/kernels/cuda/native_gr_postops.dp.cpp+++ b/sycl/src/kernels/cuda/native_gr_postops.dp.cpp@@ -69,6 +69,10 @@ pre_gated(const float *__restrict__ xn, float *__restrict__ gate,std::size_t(item_ct1.get_group(2)) * item_ct1.get_local_range(2) +item_ct1.get_local_id(2);if (d >= std::size_t(n_embd)) return;+ const std::size_t t = item_ct1.get_group(1);+ xn += t * std::size_t(n_embd) * hc;+ gate += t * std::size_t(n_embd) * hc;+ mixed += t * std::size_t(n_embd);float sum = 0.0f;for (int c = 0; c < hc; ++c) {const std::size_t i = std::size_t(c) * n_embd + d;@@ -108,6 +112,11 @@ __dpct_inline__ void post(const float *residual,std::size_t(item_ct1.get_group(2)) * item_ct1.get_local_range(2) +item_ct1.get_local_id(2);if (i >= std::size_t(n_embd) * hc) return;+ const std::size_t t = item_ct1.get_group(1);+ residual += t * std::size_t(n_embd) * hc;+ block_out += t * std::size_t(n_embd);+ inject += t * std::size_t(hc);+ output += t * std::size_t(n_embd) * hc;const int c = int(i / n_embd), d = int(i % n_embd);const float weight = scale_zero_bias(sigmoid(scale_zero_bias(inject[c], scale)), 2.0f);// Exact residual/output alias is supported; no other thread reads residual[i].@@ -177,8 +186,15 @@ void native_gr_down_silu(float* lo, int hc_lr, int hc, void* stream) {}void native_gr_pre_gated(const float* xn, float* gate, float* mixed,int n_embd, int hc, bool fused_layer, void* stream) {+ native_gr_pre_gated_multi(xn, gate, mixed, n_embd, hc, 1, fused_layer, stream);+}+void native_gr_pre_gated_multi(const float* xn, float* gate, float* mixed,+ int n_embd, int hc, int n_tok, bool fused_layer, void* stream) {+ if (n_tok <= 0)+ throw std::invalid_argument("native GR postops require positive n_tok");check_shape(n_embd, hc);check_pointer(xn); check_pointer(gate); check_pointer(mixed);+ const dpct::dim3 grid{blocks(n_embd), unsigned(n_tok), 1u};if (fused_layer){auto exp_props = sycl::ext::oneapi::experimental::properties{@@ -188,10 +204,9 @@ void native_gr_pre_gated(const float* xn, float* gate, float* mixed,->submit([&](sycl::handler &cgh) {auto float_hc_ct5 = 1.0f / float(hc);- cgh.parallel_for<dpct_kernel_name<class pre_gated_7b64ea,+ cgh.parallel_for<dpct_kernel_name<class pre_gated_e6e3d1,dpct_kernel_scalar<true>>>(- sycl::nd_range<3>(sycl::range(1, 1, blocks(n_embd)) *- sycl::range(1, 1, THREADS),+ sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),exp_props, [=](sycl::nd_item<3> item_ct1) {pre_gated<true>(xn, gate, mixed, n_embd, hc,@@ -206,10 +221,9 @@ void native_gr_pre_gated(const float* xn, float* gate, float* mixed,->submit([&](sycl::handler &cgh) {auto float_hc_ct5 = 1.0f / float(hc);- cgh.parallel_for<dpct_kernel_name<class pre_gated_4a043d,+ cgh.parallel_for<dpct_kernel_name<class pre_gated_10bc88,dpct_kernel_scalar<false>>>(- sycl::nd_range<3>(sycl::range(1, 1, blocks(n_embd)) *- sycl::range(1, 1, THREADS),+ sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),exp_props, [=](sycl::nd_item<3> item_ct1) {pre_gated<false>(xn, gate, mixed, n_embd, hc,@@ -221,8 +235,16 @@ void native_gr_pre_gated(const float* xn, float* gate, float* mixed,}void native_gr_post(const float* residual, const float* block_out, const float* inject,float* output, int n_embd, int hc, void* stream) {+ native_gr_post_multi(residual, block_out, inject, output, n_embd, hc, 1, stream);+}+void native_gr_post_multi(const float* residual, const float* block_out, const float* inject,+ float* output, int n_embd, int hc, int n_tok, void* stream) {+ if (n_tok <= 0)+ throw std::invalid_argument("native GR postops require positive n_tok");check_shape(n_embd, hc);check_pointer(residual); check_pointer(block_out); check_pointer(inject); check_pointer(output);+ const dpct::dim3 grid{blocks(std::size_t(n_embd) * hc), unsigned(n_tok),+ 1u};{auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};@@ -232,10 +254,8 @@ void native_gr_post(const float* residual, const float* block_out, const float*auto float_hc_ct6 = 1.0f / float(hc);cgh.parallel_for<dpct_kernel_name<class post_a7f844>>(- sycl::nd_range<3>(- sycl::range(1, 1, blocks(std::size_t(n_embd) * hc)) *- sycl::range(1, 1, THREADS),- sycl::range(1, 1, THREADS)),+ sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),+ sycl::range(1, 1, THREADS)),exp_props, [=](sycl::nd_item<3> item_ct1) {post(residual, block_out, inject, output, n_embd, hc,float_hc_ct6);diff --git a/sycl/src/kernels/cuda/native_mmvq.dp.cpp b/sycl/src/kernels/cuda/native_mmvq.dp.cppindex d44715a62..ea02af521 100644--- a/sycl/src/kernels/cuda/native_mmvq.dp.cpp+++ b/sycl/src/kernels/cuda/native_mmvq.dp.cpp@@ -32,13 +32,19 @@#include "strata/kernels/dp4a.hpp"#include "strata/kernels/q8_1_finite.hpp"#include "strata/kernels/iq_kernels.hpp"+#include "s26_tsum.dp.hpp"+#include <algorithm>#include <cstdint>#include <cstdlib>+#include <cstring>#include <limits>#include <stdexcept>#include <type_traits>#include <string>+#include <unordered_map>+#include <cstdio>+#include <vector>#include <cmath>namespace strata::kernels {@@ -197,6 +203,30 @@ __dpct_inline__ void native_quantize_q8_1_kernel(const float *__restrict__ x,if (i % Q8K == 0) y[i / Q8K].ds = q8_1_ds(d, sum);}+__dpct_inline__ void+native_swiglu_quantize_q8_1_kernel(const float *__restrict__ gate,+ const float *__restrict__ up,+ Q81Block *__restrict__ y, int n_in) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int i = int(item_ct1.get_group(2)) * QUANT_THREADS ++ int(item_ct1.get_local_id(2));+ if (i >= n_in) return; // n_in is a multiple of 32: only whole warps return.+ const float gi = gate[i];+ /*+ DPCT1013: The rounding mode could not be specified and the generated+ code may have different accuracy than the original code. Verify the+ correctness. SYCL math built-in function rounding mode is aligned with+ OpenCL C 1.2 standard.+ */+ const float xi = gi / (1.0f + sycl::native::exp(-gi)) * up[i];+ const float amax = warp_max(sycl::fabs(xi));+ const float sum = warp_sum(xi);+ const float d = q8_1_finite(amax / 127.0f); // #606, as native_quantize_q8_1_kernel: finite blocks bit for bit+ const int8_t q = q8_1_quant(xi, d, amax);+ y[i / Q8K].qs[i % Q8K] = q;+ if (i % Q8K == 0) y[i / Q8K].ds = q8_1_ds(d, sum);+}+// Exact pinned vec_dot_q5_K_q8_1_impl_vmmq expression and integer dot order.__dpct_inline__ floatq5_q8_dot_impl(const int *__restrict__ vl, const int *__restrict__ vh,@@ -511,6 +541,17 @@ inline dpct::global_memory<int8_t, 1>& iq4nl_values = *new dpct::global_memory<istatic constexpr int8_t kIq4nlTable[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113};__dpct_inline__ sycl::int2 iq4_table_lookup(int q4, int8_t *iq4nl_values) {+#if defined(STRATA_HIP_GFX906)+ // AMD: llama.cpp's HIP lookup (see iq_kernels.cu get_int_from_table_16): 4 v_perm_b32 per 8 values+ const uint32_t* v32 = reinterpret_cast<const uint32_t*>(iq4nl_values);+ const uint32_t q_even = (uint32_t) q4, q_odd = (uint32_t) q4 >> 4;+ const uint32_t el = __builtin_amdgcn_perm(v32[1], v32[0], q_even & 0x07070707u);+ const uint32_t ol = __builtin_amdgcn_perm(v32[1], v32[0], q_odd & 0x07070707u);+ const uint32_t eh = __builtin_amdgcn_perm(v32[3], v32[2], q_even & 0x07070707u);+ const uint32_t oh = __builtin_amdgcn_perm(v32[3], v32[2], q_odd & 0x07070707u);+ return make_int2((int) __builtin_amdgcn_perm(eh, el, 0x03020100u | ((q_even & 0x08080808u) >> 1)),+ (int) __builtin_amdgcn_perm(oh, ol, 0x03020100u | ((q_odd & 0x08080808u) >> 1)));+#elseconst uint32_t* table32 = reinterpret_cast<const uint32_t*>(iq4nl_values);uint32_t tmp[2];const uint32_t low_high_selection_indices = 0x32103210 | ((q4 & 0x88888888) >> 1);@@ -526,6 +567,7 @@ __dpct_inline__ sycl::int2 iq4_table_lookup(int q4, int8_t *iq4nl_values) {}return sycl::int2(dpct::byte_level_permute(tmp[0], tmp[1], 0x6420),dpct::byte_level_permute(tmp[0], tmp[1], 0x7531));+#endif}// Exact pinned vec_dot_iq4_xs_q8_1: a lane consumes one 32-element subblock,@@ -1173,19 +1215,134 @@ struct IQ4XSTraits {return d * sumi;}};-// The four 32-element formats: `load` keeps the block pointer (their decode is a few integer ops) and `apply` is-// the unchanged small_q8_dot. Their per-column cost is small; the win above is for the K and IQ formats.+// The four 32-element formats: `load` decodes the two 32-bit weight chunks and block scale once per (row, block),+// and `apply` runs the exact same STRATA_DP4A and scale arithmetic per activation column as `small_q8_dot`.template<typename Weight, int Qi>-struct SmallTraits {- using Block = Weight;- static constexpr int DIV = 32, T = Qi / 2, KBY = 1, BPI = 2 * WARPS * WARP / Qi;- static int kqs(int tid) { return 2 * (tid % (Qi / 2)); }- struct W { const Weight* w; };- static W load(const Block* __restrict__ w, int) { return W{w}; }- static float apply(const W &r, const Q81Block *__restrict__ x, int k) { return apply(r, x, k, const_cast<int8_t*>(kIq4nlTable)); }- static float apply(const W &r, const Q81Block *__restrict__ x, int k,- int8_t *iq4nl_values) {- return small_q8_dot(r.w, x, k, iq4nl_values);+struct SmallTraits;++template<>+struct SmallTraits<Q40Block, 4> {+ using Block = Q40Block;+ static constexpr int DIV = 32, T = 2, KBY = 1, BPI = 2 * WARPS * WARP / 4;+ static int kqs(int tid) { return 2 * (tid % 2); }+ struct W { int vi0[2], vi1[2]; float d; };+ static W load(const Block* __restrict__ w, int iqs) {+ W r;+#pragma unroll+ for (int i = 0; i < 2; ++i) {+ const int v = load_int_b2(w->qs, iqs + i);+ r.vi0[i] = (v >> 0) & 0x0f0f0f0f;+ r.vi1[i] = (v >> 4) & 0x0f0f0f0f;+ }+ r.d = w->d;+ return r;+ }+ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {+ int sumi = 0;+#pragma unroll+ for (int i = 0; i < 2; ++i) {+ sumi = STRATA_DP4A(r.vi0[i], reinterpret_cast<const int*>(x->qs)[iqs + i], sumi);+ sumi = STRATA_DP4A(r.vi1[i], reinterpret_cast<const int*>(x->qs)[iqs + i + 4], sumi);+ }+ const sycl::float2 ds =+ (x->ds).template convert<float, sycl::rounding_mode::automatic>();+ return r.d * (sumi * ds.x() - 4 * ds.y());+ }+};++template<>+struct SmallTraits<Q50Block, 4> {+ using Block = Q50Block;+ static constexpr int DIV = 32, T = 2, KBY = 1, BPI = 2 * WARPS * WARP / 4;+ static int kqs(int tid) { return 2 * (tid % 2); }+ struct W { int vi0[2], vi1[2]; float d; };+ static W load(const Block* __restrict__ w, int iqs) {+ W r;+ const int qh = load_int_b2(w->qh, 0);+#pragma unroll+ for (int i = 0; i < 2; ++i) {+ const int vl = load_int_b2(w->qs, iqs + i);+ const int vh = qh >> (4 * (iqs + i));+ int vi0 = (vl >> 0) & 0x0f0f0f0f;+ vi0 |= (vh << 4) & 0x00000010;+ vi0 |= (vh << 11) & 0x00001000;+ vi0 |= (vh << 18) & 0x00100000;+ vi0 |= (vh << 25) & 0x10000000;+ r.vi0[i] = vi0;+ int vi1 = (vl >> 4) & 0x0f0f0f0f;+ vi1 |= (vh >> 12) & 0x00000010;+ vi1 |= (vh >> 5) & 0x00001000;+ vi1 |= (vh << 2) & 0x00100000;+ vi1 |= (vh << 9) & 0x10000000;+ r.vi1[i] = vi1;+ }+ r.d = w->d;+ return r;+ }+ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {+ int sumi = 0;+#pragma unroll+ for (int i = 0; i < 2; ++i) {+ sumi = STRATA_DP4A(r.vi0[i], reinterpret_cast<const int*>(x->qs)[iqs + i], sumi);+ sumi = STRATA_DP4A(r.vi1[i], reinterpret_cast<const int*>(x->qs)[iqs + i + 4], sumi);+ }+ const sycl::float2 ds =+ (x->ds).template convert<float, sycl::rounding_mode::automatic>();+ return r.d * (sumi * ds.x() - 8 * ds.y());+ }+};++template<>+struct SmallTraits<Q80Block, 8> {+ using Block = Q80Block;+ static constexpr int DIV = 32, T = 4, KBY = 1, BPI = 2 * WARPS * WARP / 8;+ static int kqs(int tid) { return 2 * (tid % 4); }+ struct W { int v[2]; float d0; };+ static W load(const Block* __restrict__ w, int iqs) {+ W r;+#pragma unroll+ for (int i = 0; i < 2; ++i) r.v[i] = load_int_b2(w->qs, iqs + i);+ r.d0 = w->d;+ return r;+ }+ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {+ int sumi = 0;+#pragma unroll+ for (int i = 0; i < 2; ++i) {+ const int u = reinterpret_cast<const int*>(x->qs)[iqs + i];+ sumi = STRATA_DP4A(r.v[i], u, sumi);+ }+ const float d1 = x->ds[0];+ return r.d0 * d1 * float(sumi);+ }+};++template<>+struct SmallTraits<IQ4NLBlock, 4> {+ using Block = IQ4NLBlock;+ static constexpr int DIV = 32, T = 2, KBY = 1, BPI = 2 * WARPS * WARP / 4;+ static int kqs(int tid) { return 2 * (tid % 2); }+ struct W { sycl::int2 v[2]; float dw; };+ static W load(const Block* __restrict__ w, int iqs) { return load(w, iqs, const_cast<int8_t*>(kIq4nlTable)); }+ static W load(const Block* __restrict__ w, int iqs, int8_t *iq4nl_values) {+ W r;+#pragma unroll+ for (int i = 0; i < 2; ++i) r.v[i] =+ iq4_table_lookup(load_int_b2(w->qs, iqs + i), iq4nl_values);+ r.dw = sycl::vec<sycl::half, 1>(w->d)+ .convert<float, sycl::rounding_mode::automatic>()[0];+ return r;+ }+ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {+ const int* q8 = reinterpret_cast<const int*>(x->qs) + iqs;+ int sumi = 0;+#pragma unroll+ for (int i = 0; i < 2; ++i) {+ sumi = STRATA_DP4A(r.v[i].x(), q8[i], sumi);+ sumi = STRATA_DP4A(r.v[i].y(), q8[i + 4], sumi);+ }+ const float d = r.dw * x->ds[0];+ return d * sumi;}};@@ -1195,7 +1352,16 @@ struct SmallTraits {// equal to ncols = 1 only to float rounding (the cross-warp reduction groups partial sums differently).bool g_multi_exact = true; // until the upstream layout is timed on an idle GPU (plan rule: default only what is measured)-template <typename F, int NCOLS, int NW, int ROWS, int SG = WARP>+// S26 STRATA_TSUM=1 (TS): warp 0's NCOLS x ROWS sums as one transposed butterfly (s26_tsum.cuh), bitwise the same+static bool s26_tsum_on() {+ static const bool on = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }();+ return on;+}++// S26 STRATA_LFUSE (PAIR): blocks n_out.. compute the same rows of w2 into y2 (two matrices of one shape on one+// input in one launch; each output's code is the single matrix's)+template <typename F, int NCOLS, int NW, int ROWS, bool TS = false,+ bool PAIR = false, int SG = WARP>/*DPCT1110: The total declared local variable size in device functionnative_mmvq_multi_kernel exceeds 128 bytes and may cause high register pressure.@@ -1205,13 +1371,19 @@ adjust the code, or use smaller sub-group size to avoid high register pressure.__dpct_inline__ voidnative_mmvq_multi_kernel(const typename F::Block *__restrict__ w,const Q81Block *__restrict__ x, float *__restrict__ y,- int n_in, int n_out) {+ int n_in, int n_out,+ const typename F::Block *__restrict__ w2 = nullptr,+ float *__restrict__ y2 = nullptr) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();constexpr int BPI =F::BPI * NW * SG / (WARPS * WARP); // blocks per iteration scale with the thread countconst int tid =SG * int(item_ct1.get_local_id(1)) + int(item_ct1.get_local_id(2));- const int row0 = ROWS * int(item_ct1.get_group(2));+ int bxi = int(item_ct1.get_group(2));+ if constexpr (PAIR) {+ if (bxi >= n_out / ROWS) { bxi -= n_out / ROWS; w = w2; y = y2; }+ }+ const int row0 = ROWS * bxi;const int blocks_per_row = n_in / F::DIV;const int x_stride = n_in / Q8K; // Q8_1 blocks per activation columnfloat tmp[NCOLS][ROWS] = {};@@ -1232,14 +1404,7 @@ native_mmvq_multi_kernel(const typename F::Block *__restrict__ w,F::load(w + block, kqs); // once per (row, block)#pragma unrollfor (int j = 0; j < NCOLS; ++j) // then per column- /*- DPCT1084: The function call "Q5KTraits::apply" has- multiple migration results in different template- instantiations that could not be unified. You may need to- adjust the code.- */- tmp[j][i] +=- F::apply(wv, x + std::size_t(j) * x_stride + kby, kqs);+ tmp[j][i] += F::apply(wv, x + std::size_t(j) * x_stride + kby, kqs);}}}@@ -1261,6 +1426,27 @@ native_mmvq_multi_kernel(const typename F::Block *__restrict__ w,*/item_ct1.barrier();if (item_ct1.get_local_id(1) > 0) return;+ if constexpr (TS) {+ constexpr int V = NCOLS * ROWS, P = s26ts::pow2_ceil(V);+ float v[P];+#pragma unroll+ for (int j = 0; j < NCOLS; ++j)+#pragma unroll+ for (int i = 0; i < ROWS; ++i) {+#pragma unroll+ for (int l = 0; l < NW - 1; ++l) tmp[j][i] +=+ partial[l][j][i][item_ct1.get_local_id(2)];+ v[j * ROWS + i] = tmp[j][i];+ }+#pragma unroll+ for (int k = V; k < P; ++k) v[k] = 0.0f;+ const float sum = s26ts::tsum<P>(v, int(item_ct1.get_local_id(2)));+ const int k = s26ts::tsum_token<P>(int(item_ct1.get_local_id(2)));+ const int j = k / ROWS, i = k % ROWS;+ if (int(item_ct1.get_local_id(2)) == s26ts::tsum_lane<P>(k) && k < V &&+ row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = sum;+ return;+ }#pragma unrollfor (int j = 0; j < NCOLS; ++j) {#pragma unroll@@ -1821,34 +2007,23 @@ void launch_multi_n(const void *weights, const void *x_q8_1, float *y, int n_in,int n_out, dpct::queue_ptr s) {const auto* w = static_cast<const typename F::Block*>(weights);const auto* x = static_cast<const Q81Block*>(x_q8_1);+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});if (!g_multi_exact) {constexpr int NW = NCOLS <= 4 ? 4 : 2;constexpr int ROWS = 1; // SYCL port: one row per work-group (more groups: the kernel is latency-bound here)const unsigned blocks = unsigned((std::size_t(n_out) + ROWS - 1) / ROWS);- /*- 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. Adjust the work-group size if needed.- */- {- auto exp_props = sycl::ext::oneapi::experimental::properties{- sycl::ext::oneapi::experimental::use_root_sync};- dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});-- s->parallel_for<dpct_kernel_name<- class native_mmvq_multi_kernel_646c3d, F,- dpct_kernel_scalar<NCOLS>, dpct_kernel_scalar<NW>,- dpct_kernel_scalar<2>>>(- sycl::nd_range<3>(sycl::range(1, 1, blocks) *- sycl::range(1, NW, WARP),- sycl::range(1, NW, WARP)),- exp_props,- [=](sycl::nd_item<3> item_ct1)- [[sycl::reqd_sub_group_size(32)]] {- native_mmvq_multi_kernel<F, NCOLS, NW, ROWS>(w, x, y, n_in,- n_out);- });- }+ s->parallel_for<dpct_kernel_name<+ class native_mmvq_multi_kernel_646c3d, F,+ dpct_kernel_scalar<NCOLS>, dpct_kernel_scalar<NW>,+ dpct_kernel_scalar<2>>>(+ sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, NW, WARP),+ sycl::range(1, NW, WARP)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ native_mmvq_multi_kernel<F, NCOLS, NW, ROWS>(w, x, y, n_in, n_out);+ });return;}if (mmvq_sg16(std::is_same_v<F, IQ4XSTraits>, n_out)) { // same 128 threads as 8 SIMD16 sub-groups@@ -1859,61 +2034,69 @@ void launch_multi_n(const void *weights, const void *x_q8_1, float *y, int n_in,s->parallel_for<dpct_kernel_name<class native_mmvq_multi16_small, F, dpct_kernel_scalar<NCOLS>>>(sycl::nd_range<3>(sycl::range(1, 1, blocks) * t16, t16),[=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(16)]] {- native_mmvq_multi_kernel<F, NCOLS, NW16, WARPS, 16>(w, x, y, n_in, n_out);+ native_mmvq_multi_kernel<F, NCOLS, NW16, WARPS, false, false, 16>(w, x, y, n_in, n_out);});} else {s->parallel_for<dpct_kernel_name<class native_mmvq_multi16, F, dpct_kernel_scalar<NCOLS>>>(sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * t16, t16),[=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(16)]] {- native_mmvq_multi_kernel<F, NCOLS, NW16, 1, 16>(w, x, y, n_in, n_out);+ native_mmvq_multi_kernel<F, NCOLS, NW16, 1, false, false, 16>(w, x, y, n_in, n_out);});}return;}const dpct::dim3 threads(WARP, WARPS);- if (n_in / F::DIV < F::BPI) {- const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);- /*- 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. Adjust the work-group size if needed.- */- {- auto exp_props = sycl::ext::oneapi::experimental::properties{- sycl::ext::oneapi::experimental::use_root_sync};- dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});-+ // #783 PR-h (stuchapin909): two rows per block for every K, not only small K - each row keeps its own partial sums and+ // reduction, so a row's result does not depend on its neighbour; STRATA_NO_MMVQ_ROWS2=1 keeps one row for large K+ static const bool rows1 = [] {+ const char* v = std::getenv("STRATA_NO_MMVQ_ROWS2");+ return v != nullptr && v[0] != '\0' && v[0] != '0';+ }();+ if (rows1 && n_in / F::DIV >= F::BPI) {+ if (s26_tsum_on()) {+ s->parallel_for<dpct_kernel_name<+ class native_mmvq_multi_kernel_2a7dda, F,+ dpct_kernel_scalar<NCOLS>, dpct_kernel_scalar<WARPS>,+ dpct_kernel_scalar<1>, dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads, threads),+ exp_props,+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ native_mmvq_multi_kernel<F, NCOLS, WARPS, 1, true>(w, x, y, n_in, n_out);+ });+ } else {s->parallel_for<dpct_kernel_name<class native_mmvq_multi_kernel_23124e, F,dpct_kernel_scalar<NCOLS>, dpct_kernel_scalar<WARPS>,- dpct_kernel_scalar<WARPS>>>(- sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads, threads),+ dpct_kernel_scalar<1>, dpct_kernel_scalar<false>>>(+ sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads, threads),exp_props,- [=](sycl::nd_item<3> item_ct1)- [[sycl::reqd_sub_group_size(32)]] {- native_mmvq_multi_kernel<F, NCOLS, WARPS, WARPS>(- w, x, y, n_in, n_out);- });+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ native_mmvq_multi_kernel<F, NCOLS, WARPS, 1>(w, x, y, n_in, n_out);+ });}+ return;+ }+ constexpr int ROWS = 2;+ const unsigned blocks = unsigned((std::size_t(n_out) + ROWS - 1) / ROWS);+ if (s26_tsum_on()) {+ s->parallel_for<dpct_kernel_name<+ class native_mmvq_multi_kernel_279861, F,+ dpct_kernel_scalar<NCOLS>, dpct_kernel_scalar<WARPS>,+ dpct_kernel_scalar<ROWS>, dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads, threads),+ exp_props,+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ native_mmvq_multi_kernel<F, NCOLS, WARPS, ROWS, true>(w, x, y, n_in, n_out);+ });} else {- /*- 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. Adjust the work-group size if needed.- */- auto exp_props = sycl::ext::oneapi::experimental::properties{- sycl::ext::oneapi::experimental::use_root_sync};- dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});-s->parallel_for<dpct_kernel_name<class native_mmvq_multi_kernel_75e8ad, F, dpct_kernel_scalar<NCOLS>,- dpct_kernel_scalar<WARPS>, dpct_kernel_scalar<1>>>(- sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads,- threads),+ dpct_kernel_scalar<WARPS>, dpct_kernel_scalar<ROWS>,+ dpct_kernel_scalar<false>>>(+ sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads, threads),exp_props,[=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {- native_mmvq_multi_kernel<F, NCOLS, WARPS, 1>(w, x, y, n_in,- n_out);+ native_mmvq_multi_kernel<F, NCOLS, WARPS, ROWS>(w, x, y, n_in, n_out);});}}@@ -1973,6 +2156,77 @@ void launch_check() {}}++#if defined(STRATA_HIP_GFX906)+// ---- AMD (wave64) layout: one wavefront per R rows, four wavefronts per block, the row's blocks strided over the+// 64 lanes exactly as the CUDA kernels stride them over a block (kbx = lane / T, stride 64 / T), and a 64-lane+// butterfly instead of the LDS partials and __syncthreads of the one-block-per-row layout: on gfx906 a block per+// 2 KB row spent most of its time being launched and joined. The SAME kernel serves every column count 1..8, so a+// column's sums do not depend on how many columns (verify tokens) ride along. STRATA_MMVQ_WAVE=0: the CUDA layout.+bool g_wave_off = std::getenv("STRATA_MMVQ_WAVE") && std::string(std::getenv("STRATA_MMVQ_WAVE")) == "0";+template<typename F, int NCOLS, int R>+__launch_bounds__(256)+__global__ void native_mmvq_wave_kernel(const typename F::Block* __restrict__ w, const Q81Block* __restrict__ x,+ float* __restrict__ y, int n_in, int n_out) {+ constexpr int BPIW = 64 / F::T;+ static_assert(64 % F::T == 0, "a block's threads must tile the wavefront");+ const int lane = int(threadIdx.x) & 63;+ const int row0 = (int(blockIdx.x) * 4 + (int(threadIdx.x) >> 6)) * R;+ if (row0 >= n_out) return;+ const int blocks_per_row = n_in / F::DIV;+ const int x_stride = n_in / Q8K;+ const int kqs = F::kqs(lane);+ float tmp[NCOLS][R] = {};+ for (int kbx = lane / F::T; kbx < blocks_per_row; kbx += BPIW) {+ const int kby = kbx * F::KBY;+#pragma unroll+ for (int i = 0; i < R; ++i) {+ if (row0 + i < n_out) {+ const typename F::W wv = F::load(w + std::size_t(row0 + i) * blocks_per_row + kbx, kqs);+#pragma unroll+ for (int j = 0; j < NCOLS; ++j) tmp[j][i] += F::apply(wv, x + std::size_t(j) * x_stride + kby, kqs);+ }+ }+ }+#pragma unroll+ for (int j = 0; j < NCOLS; ++j)+#pragma unroll+ for (int i = 0; i < R; ++i) {+ float v = tmp[j][i];+#pragma unroll+ for (int off = 32; off > 0; off >>= 1) v += __shfl_xor(v, off, 64);+ if (lane == 0 && row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = v;+ }+}+template<typename F, int NCOLS>+void wave_launch_n(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, cudaStream_t s) {+ const auto* w = static_cast<const typename F::Block*>(weights);+ const auto* x = static_cast<const Q81Block*>(x_q8_1);+ constexpr int R = 1;+ const unsigned blocks = unsigned((std::size_t(n_out) + 4 * R - 1) / (4 * R));+ native_mmvq_wave_kernel<F, NCOLS, R><<<blocks, 256, 0, s>>>(w, x, y, n_in, n_out);+}+template<typename F>+void wave_launch(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {+ const auto s = static_cast<cudaStream_t>(stream);+ switch (ncols) {+ case 1: wave_launch_n<F, 1>(weights, x_q8_1, y, n_in, n_out, s); break;+ case 2: wave_launch_n<F, 2>(weights, x_q8_1, y, n_in, n_out, s); break;+ case 3: wave_launch_n<F, 3>(weights, x_q8_1, y, n_in, n_out, s); break;+ case 4: wave_launch_n<F, 4>(weights, x_q8_1, y, n_in, n_out, s); break;+ case 5: wave_launch_n<F, 5>(weights, x_q8_1, y, n_in, n_out, s); break;+ case 6: wave_launch_n<F, 6>(weights, x_q8_1, y, n_in, n_out, s); break;+ case 7: wave_launch_n<F, 7>(weights, x_q8_1, y, n_in, n_out, s); break;+ case 8: wave_launch_n<F, 8>(weights, x_q8_1, y, n_in, n_out, s); break;+ default: throw std::invalid_argument("native MMVQ (wave) requires 1 <= ncols <= 8");+ }+}+#define STRATA_WAVE_MMVQ(...) \+ if (!g_wave_off) { wave_launch<__VA_ARGS__>(weights, x_q8_1, y, n_in, n_out, ncols, stream); launch_check(); return; }+#else+#define STRATA_WAVE_MMVQ(...)+#endif+template<typename Weight, int Qi>void small_mmvq(const void* weights, const void* x_q8_1, float* y,int n_in, int n_out, int ncols, void* stream) {@@ -1982,6 +2236,7 @@ void small_mmvq(const void* weights, const void* x_q8_1, float* y,validate_pointer(x_q8_1);validate_pointer(y);validate_stream(stream);+ STRATA_WAVE_MMVQ(SmallTraits<Weight, Qi>)if (ncols > 1) {launch_multi<SmallTraits<Weight, Qi>>(weights, x_q8_1, y, n_in, n_out, ncols, stream);launch_check();@@ -2008,7 +2263,7 @@ void small_mmvq(const void* weights, const void* x_q8_1, float* y,auto iq4nl_values_ptr_ct1 = iq4nl_values.get_ptr();cgh.parallel_for<dpct_kernel_name<- class native_small_mmvq_kernel_75ea67, Weight,+ class native_small_mmvq_kernel_95f41f, Weight,dpct_kernel_scalar<Qi>, dpct_kernel_scalar<true>>>(sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads,threads),@@ -2035,7 +2290,7 @@ void small_mmvq(const void* weights, const void* x_q8_1, float* y,auto iq4nl_values_ptr_ct1 = iq4nl_values.get_ptr();cgh.parallel_for<dpct_kernel_name<- class native_small_mmvq_kernel_7408e4, Weight,+ class native_small_mmvq_kernel_d00fb9, Weight,dpct_kernel_scalar<Qi>, dpct_kernel_scalar<false>>>(sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads,threads),@@ -2064,8 +2319,638 @@ void small_f32(const void* weights, const float* x, void* scratch_q8_1,small_mmvq<Weight, Qi>(weights, scratch_q8_1, y, n_in, n_out, ncols, stream);}+// ============================ STRATA_Q8_PACKED=1: the packed Q8_0 decode layout (opt-in) ============================+//+// A lossless load-time repack of a Q8_0 matrix: the SAME int8 values in a qs plane (row-major, n_in bytes per row)+// followed by the SAME fp16 scales in a d plane (row-major, n_in / 32 per row) - no requantization, same bytes.+// The GGUF's 34-byte blocks leave every int 2-byte aligned (load_int_b2 = two 16-bit loads); the planes give each+// thread one aligned 8-byte run, read with streaming (non-temporal) loads. Every thread owns exactly the bytes of+// the ncols = 1 / multi-column EXACT layout (block kbx = tid / 4 + 32 i, ints 2 (tid % 4) and +1), accumulates them+// in the same order with the same expression, and the cross-warp sum and XOR tree are the same: every output is+// BITWISE equal to native_small_mmvq_kernel / native_mmvq_multi_kernel<SmallTraits<Q80Block, 8>, NC, 4, 1>.+// Eligible: 1024 <= n_in <= 4096 and n_out >= 2048, run as 640 persistent workgroups (a grid-stride over rows, two+// partial buffers). Measured on gfx1151 (S26, 8 real UD-IQ4_XS layers per shape, paired, 1-5 columns): 2560 ->+// 6144/10240/12288 +10-12% per call (engine trace: -10.7% on those calls). 6144 -> 2560 (one workgroup per row)+// was +2-4% standalone but -3% in the engine, and rows < 2048 lose: neither is packed.+#if defined(__HIPCC__)+#define STRATA_Q8P_LOAD(p) __builtin_nontemporal_load(p)+#else+/*+DPCT1098: The '*' expression is used instead of the __ldcs call. These two+expressions do not provide the exact same functionality. Check the generated+code for potential precision and/or performance issues.+*/+/*+DPCT1064: Migrated __ldcs call is used in a macro/template definition and+may not be valid for all macro/template uses. Adjust the code.+*/+#define STRATA_Q8P_LOAD(p) (*(p))+#endif+constexpr int Q8P_PERSIST_GRID = 640;+constexpr int Q8P_PERSIST_MAX_IN = 4096;++template <int NCOLS, bool TS = false>+/*+DPCT1110: The total declared local variable size in device function+native_q8_0_packed_kernel exceeds 128 bytes and may cause high register+pressure. Consult with your hardware vendor to find the total register size+available and adjust the code, or use smaller sub-group size to avoid high+register pressure.+*/+__dpct_inline__ void+native_q8_0_packed_kernel(const int8_t *__restrict__ qs,+ const sycl::half *__restrict__ dpl,+ const Q81Block *__restrict__ x, float *__restrict__ y,+ int n_in, int n_out, int row_step) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int tid =+ WARP * int(item_ct1.get_local_id(1)) + int(item_ct1.get_local_id(2));+ const int nb = n_in / 32;+ const int kqs = 2 * (tid % 4);+ auto &partial = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ float[2][WARPS - 1][NCOLS][WARP]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ int buf = 0;+ for (int row = int(item_ct1.get_group(2)); row < n_out;+ row += row_step, buf ^= 1) {+ float tmp[NCOLS] = {};+ for (int kbx = tid / 4; kbx < nb; kbx += 2 * WARPS * WARP / 8) {+ const std::size_t block = std::size_t(row) * nb + kbx;+ const int* p = reinterpret_cast<const int*>(qs + block * 32) + kqs;+ const int v0 = STRATA_Q8P_LOAD(p);+ const int v1 = STRATA_Q8P_LOAD(p + 1);+ const float d0 = dpl[block];+#pragma unroll+ for (int j = 0; j < NCOLS; ++j) {+ const Q81Block* xb = x + std::size_t(j) * nb + kbx;+ const int* u = reinterpret_cast<const int*>(xb->qs);+ int sumi = 0;+ sumi = STRATA_DP4A(v0, u[kqs], sumi);+ sumi = STRATA_DP4A(v1, u[kqs + 1], sumi);+ const float d1 = xb->ds[0];+ tmp[j] += d0 * d1 * float(sumi);+ }+ }+ if (item_ct1.get_local_id(1) > 0) {+#pragma unroll+ for (int j = 0; j < NCOLS; ++j)+ partial[buf][item_ct1.get_local_id(1) - 1][j]+ [item_ct1.get_local_id(2)] = tmp[j];+ }+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ if (TS && item_ct1.get_local_id(1) ==+ 0) { // S26 STRATA_TSUM=1: one transposed butterfly,+ // bitwise the same sums+ constexpr int P = s26ts::pow2_ceil(NCOLS);+ float v[P];+#pragma unroll+ for (int j = 0; j < NCOLS; ++j) {+#pragma unroll+ for (int l = 0; l < WARPS - 1; ++l) tmp[j] +=+ partial[buf][l][j][item_ct1.get_local_id(2)];+ v[j] = tmp[j];+ }+#pragma unroll+ for (int j = NCOLS; j < P; ++j) v[j] = 0.0f;+ const float sum = s26ts::tsum<P>(v, int(item_ct1.get_local_id(2)));+ const int j = s26ts::tsum_token<P>(int(item_ct1.get_local_id(2)));+ if (int(item_ct1.get_local_id(2)) == s26ts::tsum_lane<P>(j) &&+ j < NCOLS) y[std::size_t(j) * n_out + row] = sum;+ } else if (item_ct1.get_local_id(1) == 0) {+#pragma unroll+ for (int j = 0; j < NCOLS; ++j) {+#pragma unroll+ for (int l = 0; l < WARPS - 1; ++l) tmp[j] +=+ partial[buf][l][j][item_ct1.get_local_id(2)];+ tmp[j] = warp_sum(tmp[j]);+ if (item_ct1.get_local_id(2) == 0)+ y[std::size_t(j) * n_out + row] = tmp[j];+ }+ }+ }+}++struct Q8Packed { const int8_t *qs; const sycl::half * d; int n_in, n_out; };+std::unordered_map<const void*, Q8Packed>& q8_packed_registry() {+ static std::unordered_map<const void*, Q8Packed> registry;+ return registry;+}++template <int NCOLS>+void q8_packed_launch(const Q8Packed &w, const Q81Block *x, float *y,+ dpct::queue_ptr s) {+ const bool persist = w.n_in <= Q8P_PERSIST_MAX_IN;+ const int grid = persist ? (std::min)(w.n_out, Q8P_PERSIST_GRID) : w.n_out;+ if (s26_tsum_on())+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});++ s->parallel_for<dpct_kernel_name<class native_q8_0_packed_kernel_851f07,+ dpct_kernel_scalar<NCOLS>,+ dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(sycl::range(1, 1, unsigned(grid)) *+ sycl::range(1, WARPS, WARP),+ sycl::range(1, WARPS, WARP)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ native_q8_0_packed_kernel<NCOLS, true>(+ w.qs, w.d, x, y, w.n_in, w.n_out, persist ? grid : w.n_out);+ });+ } else {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});++ s->/*+DPCT1050: The template argument of the dpct_kernel_name could not be+deduced. You need to update this code.+*/+ parallel_for<+ dpct_kernel_name<class native_q8_0_packed_kernel_56c826,+ dpct_kernel_scalar<NCOLS>,+ dpct_kernel_scalar<false>>>(+ sycl::nd_range<3>(sycl::range(1, 1, unsigned(grid)) *+ sycl::range(1, WARPS, WARP),+ sycl::range(1, WARPS, WARP)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ native_q8_0_packed_kernel<NCOLS>(+ w.qs, w.d, x, y, w.n_in, w.n_out,+ persist ? grid : w.n_out);+ });+ }+}++bool q8_packed_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {+ auto& registry = q8_packed_registry();+ if (registry.empty() || (ncols > 1 && !g_multi_exact)) return false; // packed = the EXACT layout only+ const auto found = registry.find(weights);+ if (found == registry.end() || found->second.n_in != n_in || found->second.n_out != n_out) return false;+ validate_shape(n_in, ncols, 32);+ validate_pointer(x_q8_1);+ validate_pointer(y);+ validate_stream(stream);+ const auto* x = static_cast<const Q81Block*>(x_q8_1);+ const auto s = strata::q_of(stream);+ switch (ncols) {+ case 1: q8_packed_launch<1>(found->second, x, y, s); break;+ case 2: q8_packed_launch<2>(found->second, x, y, s); break;+ case 3: q8_packed_launch<3>(found->second, x, y, s); break;+ case 4: q8_packed_launch<4>(found->second, x, y, s); break;+ case 5: q8_packed_launch<5>(found->second, x, y, s); break;+ case 6: q8_packed_launch<6>(found->second, x, y, s); break;+ case 7: q8_packed_launch<7>(found->second, x, y, s); break;+ case 8: q8_packed_launch<8>(found->second, x, y, s); break;+ default: throw std::invalid_argument("native MMVQ requires 1 <= ncols <= 8");+ }+ launch_check();+ return true;+}+++// ============================ STRATA_Q6_PACKED=1: the packed Q6_K head layout (opt-in) ============================+//+// The output heads (the main head, 248320 rows, and the MTP draft head's row subset) are Q6_K matrices of 2560-wide+// rows: 10 blocks of 210 bytes each, so every int load is 2-byte aligned and a row is 2100 bytes. The packed copy+// holds the SAME bytes as four planes - ql (128 B per block), qh (64 B), scales (16 B), d (2 B) - so a thread's+// two words are aligned dword loads (non-temporal). Thread ownership (block tid / 32 + 4 i, word tid % 32), the+// q6_q8_dot_impl expression, the per-thread order and the reduction are those of native_q6_k_mmvq_kernel<false> /+// native_mmvq_multi_kernel<Q6KTraits, NC, 4, 1>: every output is bitwise equal. Persistent workgroups.+int g_q6p_grid_override = 0; // the self-test's grid sweep (STRATA_Q6P_SELFTEST=2)+int q6p_grid() {+ if (g_q6p_grid_override > 0) return g_q6p_grid_override;+ static const int grid = [] {+ const char* v = std::getenv("STRATA_Q6P_GRID");+ const int g = v ? std::atoi(v) : 0;+ return g > 0 ? g : 640;+ }();+ return grid;+}++template <int NCOLS, bool TS = false>+/*+DPCT1110: The total declared local variable size in device function+native_q6_k_packed_kernel exceeds 128 bytes and may cause high register+pressure. Consult with your hardware vendor to find the total register size+available and adjust the code, or use smaller sub-group size to avoid high+register pressure.+*/+__dpct_inline__ void native_q6_k_packed_kernel(+ const int *__restrict__ ql, const int *__restrict__ qh,+ const int8_t *__restrict__ sc, const sycl::half *__restrict__ dpl,+ const Q81Block *__restrict__ x, float *__restrict__ y, int n_in, int n_out,+ int row_step) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int tid =+ WARP * int(item_ct1.get_local_id(1)) + int(item_ct1.get_local_id(2));+ const int nb = n_in / 256;+ const int x_stride = n_in / Q8K;+ const int iqs = tid % 32;+ const int bq8_offset = 4 * (iqs / 16) + (iqs % 16) / 8;+ const int scale_offset = 8 * (iqs / 16) + (iqs % 16) / 4;+ const int vh_shift = 2 * ((iqs % 16) / 8);+ const int qh_word = 8 * (iqs / 16) + iqs % 8;+ auto &partial = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ float[2][WARPS - 1][NCOLS][WARP]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ int buf = 0;+ for (int row = int(item_ct1.get_group(2)); row < n_out;+ row += row_step, buf ^= 1) {+ float tmp[NCOLS] = {};+ for (int kbx = tid / 32; kbx < nb; kbx += WARPS * WARP / 32) {+ const std::size_t block = std::size_t(row) * nb + kbx;+ const int vl = STRATA_Q8P_LOAD(ql + block * 32 + iqs);+ const int vh = STRATA_Q8P_LOAD(qh + block * 16 + qh_word) >> vh_shift;+ const int8_t* scales = sc + block * 16 + scale_offset;+ const float d = dpl[block];+ const int kby = kbx * 8;+#pragma unroll+ for (int j = 0; j < NCOLS; ++j) {+ const Q81Block* xb = x + std::size_t(j) * x_stride + kby;+ int u[2];+ float d8[2];+#pragma unroll+ for (int i = 0; i < 2; ++i) {+ u[i] = reinterpret_cast<const int*>(xb[bq8_offset + 2 * i].qs)[iqs % 8];+ d8[i] = xb[bq8_offset + 2 * i].ds[0];+ }+ tmp[j] += q6_q8_dot_impl(vl, vh, u, scales, d, d8);+ }+ }+ if (item_ct1.get_local_id(1) > 0) {+#pragma unroll+ for (int j = 0; j < NCOLS; ++j)+ partial[buf][item_ct1.get_local_id(1) - 1][j]+ [item_ct1.get_local_id(2)] = tmp[j];+ }+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ if (TS && item_ct1.get_local_id(1) ==+ 0) { // S26 STRATA_TSUM=1: one transposed butterfly,+ // bitwise the same sums+ constexpr int P = s26ts::pow2_ceil(NCOLS);+ float v[P];+#pragma unroll+ for (int j = 0; j < NCOLS; ++j) {+#pragma unroll+ for (int l = 0; l < WARPS - 1; ++l) tmp[j] +=+ partial[buf][l][j][item_ct1.get_local_id(2)];+ v[j] = tmp[j];+ }+#pragma unroll+ for (int j = NCOLS; j < P; ++j) v[j] = 0.0f;+ const float sum = s26ts::tsum<P>(v, int(item_ct1.get_local_id(2)));+ const int j = s26ts::tsum_token<P>(int(item_ct1.get_local_id(2)));+ if (int(item_ct1.get_local_id(2)) == s26ts::tsum_lane<P>(j) &&+ j < NCOLS) y[std::size_t(j) * n_out + row] = sum;+ } else if (item_ct1.get_local_id(1) == 0) {+#pragma unroll+ for (int j = 0; j < NCOLS; ++j) {+#pragma unroll+ for (int l = 0; l < WARPS - 1; ++l) tmp[j] +=+ partial[buf][l][j][item_ct1.get_local_id(2)];+ tmp[j] = warp_sum(tmp[j]);+ if (item_ct1.get_local_id(2) == 0)+ y[std::size_t(j) * n_out + row] = tmp[j];+ }+ }+ }+}++bool g_q6_bypass = false; // the load-time self-test times the GGUF-layout kernels with the copy registered++// the packed planes of one Q6_K matrix (owned: allocated by native_q6_k_pack, freed by native_q6_k_unpack)+struct Q6Packed {+ void *base; const int * ql; const int * qh; const int8_t * sc;+ const sycl::half * d;+ int n_in, n_out;+};+std::unordered_map<const void*, Q6Packed>& q6_packed_registry() {+ static std::unordered_map<const void*, Q6Packed> registry;+ return registry;+}++template <int NCOLS>+void q6_packed_launch(const Q6Packed &w, const Q81Block *x, float *y,+ dpct::queue_ptr s) {+ const int grid = (std::min)(w.n_out, q6p_grid());+ if (s26_tsum_on())+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});++ s->parallel_for<dpct_kernel_name<class native_q6_k_packed_kernel_ee650b,+ dpct_kernel_scalar<NCOLS>,+ dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(sycl::range(1, 1, unsigned(grid)) *+ sycl::range(1, WARPS, WARP),+ sycl::range(1, WARPS, WARP)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ native_q6_k_packed_kernel<NCOLS, true>(+ w.ql, w.qh, w.sc, w.d, x, y, w.n_in, w.n_out, grid);+ });+ } else {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});++ s->/*+DPCT1050: The template argument of the dpct_kernel_name could not be+deduced. You need to update this code.+*/+ parallel_for<+ dpct_kernel_name<class native_q6_k_packed_kernel_ca2554,+ dpct_kernel_scalar<NCOLS>,+ dpct_kernel_scalar<false>>>(+ sycl::nd_range<3>(sycl::range(1, 1, unsigned(grid)) *+ sycl::range(1, WARPS, WARP),+ sycl::range(1, WARPS, WARP)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ native_q6_k_packed_kernel<NCOLS>(+ w.ql, w.qh, w.sc, w.d, x, y, w.n_in, w.n_out, grid);+ });+ }+}++bool q6_packed_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {+ auto& registry = q6_packed_registry();+ if (registry.empty() || g_q6_bypass || (ncols > 1 && !g_multi_exact)) return false;+ const auto found = registry.find(weights);+ if (found == registry.end() || found->second.n_in != n_in || found->second.n_out != n_out) return false;+ validate_shape(n_in, ncols, 256);+ validate_pointer(x_q8_1);+ validate_pointer(y);+ validate_stream(stream);+ const auto* x = static_cast<const Q81Block*>(x_q8_1);+ const auto s = strata::q_of(stream);+ switch (ncols) {+ case 1: q6_packed_launch<1>(found->second, x, y, s); break;+ case 2: q6_packed_launch<2>(found->second, x, y, s); break;+ case 3: q6_packed_launch<3>(found->second, x, y, s); break;+ case 4: q6_packed_launch<4>(found->second, x, y, s); break;+ case 5: q6_packed_launch<5>(found->second, x, y, s); break;+ case 6: q6_packed_launch<6>(found->second, x, y, s); break;+ case 7: q6_packed_launch<7>(found->second, x, y, s); break;+ case 8: q6_packed_launch<8>(found->second, x, y, s); break;+ default: throw std::invalid_argument("native MMVQ requires 1 <= ncols <= 8");+ }+ launch_check();+ return true;+}} // namespace+bool native_q8_0_packed_enabled() {+ static const bool enabled = [] {+ const char* v = std::getenv("STRATA_Q8_PACKED");+ return v && v[0] == '1' && v[1] == '\0';+ }();+ return enabled;+}++bool native_q8_0_packed_eligible(int n_in, int n_out) {+ return n_in > 0 && n_in % 32 == 0 && n_in / 32 >= 2 * WARPS * WARP / 8 && n_in <= Q8P_PERSIST_MAX_IN &&+ n_out >= 2048;+}++void native_q8_0_pack_host(const void* gguf_blocks, void* out, int n_in, int n_out) {+ const auto* blocks = static_cast<const Q80Block*>(gguf_blocks);+ auto* qs = static_cast<int8_t*>(out);+ auto *d = reinterpret_cast<sycl::half *>(qs + std::size_t(n_in) * n_out);+ const std::size_t count = std::size_t(n_in / 32) * n_out;+ for (std::size_t b = 0; b < count; ++b) {+ std::memcpy(qs + b * 32, blocks[b].qs, 32);+ std::memcpy(d + b, &blocks[b].d, sizeof(sycl::half));+ }+}++void native_q8_0_packed_register(const void* gguf_weights, const void* packed, int n_in, int n_out) {+ validate_pointer(gguf_weights);+ validate_pointer(packed);+ if (!native_q8_0_packed_eligible(n_in, n_out)) throw std::invalid_argument("Q8_0 packed: ineligible shape");+ const auto* qs = static_cast<const int8_t*>(packed);+ q8_packed_registry()[gguf_weights] = Q8Packed{+ qs,+ reinterpret_cast<const sycl::half *>(qs + std::size_t(n_in) * n_out),+ n_in, n_out};+}++void native_q8_0_packed_unregister(const void* gguf_weights) { q8_packed_registry().erase(gguf_weights); }++bool native_q6_k_packed_enabled() {+ static const bool enabled = [] {+ const char* v = std::getenv("STRATA_Q6_PACKED");+ return v && v[0] == '1' && v[1] == '\0';+ }();+ return enabled;+}++bool native_q6_k_pack(const void *weights, int n_in, int n_out,+ const char *what) try {+ if (!weights || n_in <= 0 || n_in % 256 || n_in / 256 < WARPS * WARP / 32 || n_out < 2048) return false;+ if (q6_packed_registry().count(weights)) return true;+ const std::size_t nb = std::size_t(n_in / 256) * std::size_t(n_out);+ const std::size_t bytes = nb * sizeof(Q6KBlock);+ std::vector<Q6KBlock> host(nb);+ /*+ DPCT1026: The call to cudaGetLastError was removed because this+ functionality is redundant in SYCL.+ */+ if (DPCT_CHECK_ERROR(dpct::get_in_order_queue()+ .memcpy(host.data(), weights, bytes)+ .wait()) != 0) {+ ; return false;+ }+ // planes: ql | qh | scales | d, each 256-byte aligned+ const std::size_t o_qh = (nb * 128 + 255) & ~std::size_t(255);+ const std::size_t o_sc = (o_qh + nb * 64 + 255) & ~std::size_t(255);+ const std::size_t o_d = (o_sc + nb * 16 + 255) & ~std::size_t(255);+ const std::size_t total = o_d + nb * 2;+ std::vector<uint8_t> packed(total, 0);+ for (std::size_t b = 0; b < nb; ++b) {+ std::memcpy(packed.data() + b * 128, host[b].ql, 128);+ std::memcpy(packed.data() + o_qh + b * 64, host[b].qh, 64);+ std::memcpy(packed.data() + o_sc + b * 16, host[b].scales, 16);+ std::memcpy(packed.data() + o_d + b * 2, &host[b].d, 2);+ }+ void* dev = nullptr;+ /*+ DPCT1026: The call to cudaGetLastError was removed because this+ functionality is redundant in SYCL.+ */+ if (DPCT_CHECK_ERROR(dev = (void *)sycl::malloc_device(+ total, dpct::get_in_order_queue())) != 0) {+ ; return false;+ }+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in+ the original code the source host memory is pageable memory. If the memory+ is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ if (DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(dev, packed.data(),+ total).wait()) != 0) {+ /*+ DPCT1026: The call to cudaGetLastError was removed because this+ functionality is redundant in SYCL.+ */+ sycl::free(dev, dpct::get_in_order_queue());; return false;+ }+ auto* base = static_cast<uint8_t*>(dev);+ q6_packed_registry()[weights] =+ Q6Packed{dev,+ reinterpret_cast<const int *>(base),+ reinterpret_cast<const int *>(base + o_qh),+ reinterpret_cast<const int8_t *>(base + o_sc),+ reinterpret_cast<const sycl::half *>(base + o_d),+ n_in,+ n_out};+ std::fprintf(stderr, "strata: STRATA_Q6_PACKED=1 packed the %s (%d x %d, +%.1f MiB)\n", what, n_out, n_in,+ total / 1048576.0);+ // STRATA_Q6P_SELFTEST=1: bitwise check against the GGUF-layout kernels (1..4 columns) and paired timings+ if (const char* v = std::getenv("STRATA_Q6P_SELFTEST"); v && (v[0] == '1' || v[0] == '2')) {+ dpct::queue_ptr s = &dpct::get_in_order_queue();+ /*+ DPCT1025: The SYCL queue is created ignoring the flag and priority+ options.+ */+ s = dpct::get_current_device().create_queue(true);+ const int nq = n_in / Q8K;+ std::vector<Q81Block> hx(std::size_t(4) * nq);+ uint32_t r = 12345u;+ for (auto& blk : hx) {+ for (auto& q : blk.qs) { r = r * 1664525u + 1013904223u; q = int8_t(int((r >> 24) & 255u) - 128); }+ r = r * 1664525u + 1013904223u;+ blk.ds = sycl::float2(0.001f + float(r >> 8) * 1e-9f, 0.0f)+ .convert<sycl::half, sycl::rounding_mode::rte>();+ }+ void *dx = nullptr, *ya = nullptr, *yb = nullptr;+ dx = (void *)sycl::malloc_device(hx.size() * sizeof(Q81Block),+ dpct::get_in_order_queue());+ ya = (void *)sycl::malloc_device(std::size_t(4) * n_out * 4,+ dpct::get_in_order_queue());+ yb = (void *)sycl::malloc_device(std::size_t(4) * n_out * 4,+ dpct::get_in_order_queue());+ dpct::get_in_order_queue()+ .memcpy(dx, hx.data(), hx.size() * sizeof(Q81Block))+ .wait();+ std::vector<float> a(std::size_t(4) * n_out), c(std::size_t(4) * n_out);+ bool same = true;+ for (int nc = 1; nc <= 4; ++nc) {+ g_q6_bypass = true;+ native_q6_k_mmvq(weights, dx, (float*) ya, n_in, n_out, nc, s);+ g_q6_bypass = false;+ native_q6_k_mmvq(weights, dx, (float*) yb, n_in, n_out, nc, s);+ s->wait();+ dpct::get_in_order_queue()+ .memcpy(a.data(), ya, std::size_t(nc) * n_out * 4)+ .wait();+ dpct::get_in_order_queue()+ .memcpy(c.data(), yb, std::size_t(nc) * n_out * 4)+ .wait();+ same = same && std::memcmp(a.data(), c.data(), std::size_t(nc) * n_out * 4) == 0;+ }+ dpct::event_ptr e0, e1;+ e0 = new sycl::event(); e1 = new sycl::event();+ for (int nc : {1, 2, 4}) {+ std::vector<float> tb, tc;+ for (int k = 0; k < 11; ++k) {+ for (int pass = 0; pass < 2; ++pass) {+ const bool cand = (pass == 0) == (k % 2 == 1);+ g_q6_bypass = !cand;+ dpct::sync_barrier(e0, s);+ for (int it = 0; it < 5; ++it) native_q6_k_mmvq(weights, dx, (float*) (cand ? yb : ya), n_in, n_out, nc, s);+ dpct::sync_barrier(e1, s);+ e1->wait_and_throw();+ float ms = 0;+ ms = (e1->get_profiling_info<+ sycl::info::event_profiling::command_end>() -+ e0->get_profiling_info<+ sycl::info::event_profiling::+ command_start>()) /+ 1000000.0f;+ (cand ? tc : tb).push_back(ms * 1000.0f / 5);+ }+ }+ g_q6_bypass = false;+ std::sort(tb.begin(), tb.end()); std::sort(tc.begin(), tc.end());+ std::fprintf(stderr, "strata: Q6_K packed self-test %s ncols %d: GGUF %.1f us (%.1f-%.1f), packed %.1f us "+ "(%.1f-%.1f), 11 paired samples\n", what, nc, tb[5], tb[0], tb[10], tc[5], tc[0], tc[10]);+ }+ std::fprintf(stderr, "strata: Q6_K packed self-test %s: outputs %s (1-4 columns)\n", what,+ same ? "BITWISE EQUAL" : "DIFFER");+ if (v[0] == '2') { // grid sweep of the packed kernel+ for (int grid : {160, 320, 640, 1280, 2560, 5120, 20480}) {+ g_q6p_grid_override = grid;+ for (int nc : {1, 2, 4}) {+ std::vector<float> tc;+ for (int k = 0; k < 7; ++k) {+ dpct::sync_barrier(e0, s);+ for (int it = 0; it < 5; ++it) native_q6_k_mmvq(weights, dx, (float*) yb, n_in, n_out, nc, s);+ dpct::sync_barrier(e1, s);+ e1->wait_and_throw();+ float ms = 0; ms = (e1->get_profiling_info<+ sycl::info::event_profiling::+ command_end>() -+ e0->get_profiling_info<+ sycl::info::event_profiling::+ command_start>()) /+ 1000000.0f;+ tc.push_back(ms * 1000.0f / 5);+ }+ std::sort(tc.begin(), tc.end());+ std::fprintf(stderr, "strata: Q6_K packed grid sweep %s grid %d ncols %d: %.1f us (%.1f-%.1f)\n",+ what, grid, nc, tc[3], tc[0], tc[6]);+ }+ }+ g_q6p_grid_override = 0;+ }+ dpct::destroy_event(e0); dpct::destroy_event(e1);+ sycl::free(dx, dpct::get_in_order_queue());+ sycl::free(ya, dpct::get_in_order_queue());+ sycl::free(yb, dpct::get_in_order_queue());+ dpct::get_current_device().destroy_queue(s);+ if (!same) { native_q6_k_unpack(weights); return false; }+ }+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++void native_q6_k_unpack(const void* weights) {+ auto& registry = q6_packed_registry();+ const auto found = registry.find(weights);+ if (found == registry.end()) return;+ sycl::free(found->second.base, dpct::get_in_order_queue());+ registry.erase(found);+}+void native_mmvq_set_multi_exact(bool exact) { g_multi_exact = exact; }void native_mmvq_set_q6k_wide(bool on) { g_q6k_wide = on; }void native_q6_k_mmvq_stride224(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols,@@ -2115,6 +3000,39 @@ void native_quantize_q8_1(const float* x, void* x_q8_1, int n_in, int ncols, voilaunch_check();}+void native_swiglu_quantize_q8_1(const float* gate, const float* up, void* x_q8_1,+ int n_in, int ncols, void* stream) {+ validate_shape(n_in, ncols);+ validate_pointer(gate);+ validate_pointer(up);+ validate_pointer(x_q8_1);+ validate_stream(stream);+ const int n_total = n_in * ncols;+ const unsigned blocks = unsigned((std::size_t(n_total) + QUANT_THREADS - 1) / QUANT_THREADS);+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(+ ((sycl::queue *)(strata::q_of(stream)))+ ->get_device(),+ {sycl::aspect::fp16});++ ((sycl::queue *)(strata::q_of(stream)))+ ->parallel_for<dpct_kernel_name<+ class native_swiglu_quantize_q8_1_kernel_85e13e>>(+ sycl::nd_range<3>(sycl::range(1, 1, blocks) *+ sycl::range(1, 1, QUANT_THREADS),+ sycl::range(1, 1, QUANT_THREADS)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ native_swiglu_quantize_q8_1_kernel(+ gate, up, static_cast<Q81Block *>(x_q8_1), n_total);+ });+ }+ launch_check();+}+void native_q5_k_mmvq(const void* weights, const void* x_q8_1, float* y,int n_in, int n_out, int ncols, void* stream) {validate_shape(n_in, ncols, QK);@@ -2124,6 +3042,7 @@ void native_q5_k_mmvq(const void* weights, const void* x_q8_1, float* y,validate_pointer(y);validate_stream(stream);if (try_wide<WideQ5K>(weights, x_q8_1, y, n_in, n_out, ncols, stream)) { launch_check(); return; }+ STRATA_WAVE_MMVQ(Q5KTraits)if (ncols > 1) {launch_multi<Q5KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);launch_check();@@ -2146,7 +3065,7 @@ void native_q5_k_mmvq(const void* weights, const void* x_q8_1, float* y,dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});s->parallel_for<- dpct_kernel_name<class native_q5_k_mmvq_kernel_cee99f,+ dpct_kernel_name<class native_q5_k_mmvq_kernel_b1d5a2,dpct_kernel_scalar<true>>>(sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads, threads),exp_props,@@ -2165,7 +3084,7 @@ void native_q5_k_mmvq(const void* weights, const void* x_q8_1, float* y,sycl::ext::oneapi::experimental::use_root_sync};dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});- s->parallel_for<dpct_kernel_name<class native_q5_k_mmvq_kernel_4061e4,+ s->parallel_for<dpct_kernel_name<class native_q5_k_mmvq_kernel_938b09,dpct_kernel_scalar<false>>>(sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads,threads),@@ -2199,6 +3118,7 @@ void native_q2_0_mmvq(const void* weights, const void* x_q8_1, float* y,validate_pointer(x_q8_1);validate_pointer(y);validate_stream(stream);+ STRATA_WAVE_MMVQ(Q20Traits)if (ncols > 1) {launch_multi<Q20Traits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);launch_check();@@ -2220,7 +3140,7 @@ void native_q2_0_mmvq(const void* weights, const void* x_q8_1, float* y,sycl::ext::oneapi::experimental::use_root_sync};s->parallel_for<- dpct_kernel_name<class native_q2_0_mmvq_kernel_b58485,+ dpct_kernel_name<class native_q2_0_mmvq_kernel_dec305,dpct_kernel_scalar<true>>>(sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads, threads),exp_props,@@ -2238,7 +3158,7 @@ void native_q2_0_mmvq(const void* weights, const void* x_q8_1, float* y,auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- s->parallel_for<dpct_kernel_name<class native_q2_0_mmvq_kernel_42f157,+ s->parallel_for<dpct_kernel_name<class native_q2_0_mmvq_kernel_ef5f5c,dpct_kernel_scalar<false>>>(sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads,threads),@@ -2271,6 +3191,7 @@ void native_q3_k_mmvq(const void* weights, const void* x_q8_1, float* y,validate_pointer(x_q8_1);validate_pointer(y);validate_stream(stream);+ STRATA_WAVE_MMVQ(Q3KTraits)if (ncols > 1) {launch_multi<Q3KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);launch_check();@@ -2292,7 +3213,7 @@ void native_q3_k_mmvq(const void* weights, const void* x_q8_1, float* y,sycl::ext::oneapi::experimental::use_root_sync};s->parallel_for<- dpct_kernel_name<class native_q3_k_mmvq_kernel_616146,+ dpct_kernel_name<class native_q3_k_mmvq_kernel_208be9,dpct_kernel_scalar<true>>>(sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads, threads),exp_props,@@ -2310,7 +3231,7 @@ void native_q3_k_mmvq(const void* weights, const void* x_q8_1, float* y,auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- s->parallel_for<dpct_kernel_name<class native_q3_k_mmvq_kernel_72056c,+ s->parallel_for<dpct_kernel_name<class native_q3_k_mmvq_kernel_926817,dpct_kernel_scalar<false>>>(sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads,threads),@@ -2344,6 +3265,7 @@ void native_iq4_xs_mmvq(const void* weights, const void* x_q8_1, float* y,validate_pointer(y);validate_stream(stream);if (try_wide<WideIQ4XS>(weights, x_q8_1, y, n_in, n_out, ncols, stream)) { launch_check(); return; }+ STRATA_WAVE_MMVQ(IQ4XSTraits)if (ncols > 1) {launch_multi<IQ4XSTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);launch_check();@@ -2370,7 +3292,7 @@ void native_iq4_xs_mmvq(const void* weights, const void* x_q8_1, float* y,auto iq4nl_values_ptr_ct1 = iq4nl_values.get_ptr();cgh.parallel_for<- dpct_kernel_name<class native_iq4_xs_mmvq_kernel_4d1d70,+ dpct_kernel_name<class native_iq4_xs_mmvq_kernel_22a688,dpct_kernel_scalar<true>>>(sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads,threads),@@ -2397,7 +3319,7 @@ void native_iq4_xs_mmvq(const void* weights, const void* x_q8_1, float* y,auto iq4nl_values_ptr_ct1 = iq4nl_values.get_ptr();cgh.parallel_for<- dpct_kernel_name<class native_iq4_xs_mmvq_kernel_e6ab3b,+ dpct_kernel_name<class native_iq4_xs_mmvq_kernel_3ba00d,dpct_kernel_scalar<false>>>(sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads,threads),@@ -2434,6 +3356,7 @@ void native_q4_k_mmvq(const void* weights, const void* x_q8_1, float* y,validate_pointer(y);validate_stream(stream);if (try_wide<WideQ4K>(weights, x_q8_1, y, n_in, n_out, ncols, stream)) { launch_check(); return; }+ STRATA_WAVE_MMVQ(Q4KTraits)if (ncols > 1) {launch_multi<Q4KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);launch_check();@@ -2456,7 +3379,7 @@ void native_q4_k_mmvq(const void* weights, const void* x_q8_1, float* y,dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});s->parallel_for<- dpct_kernel_name<class native_q4_k_mmvq_kernel_e486cb,+ dpct_kernel_name<class native_q4_k_mmvq_kernel_da128d,dpct_kernel_scalar<true>>>(sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads, threads),exp_props,@@ -2475,7 +3398,7 @@ void native_q4_k_mmvq(const void* weights, const void* x_q8_1, float* y,sycl::ext::oneapi::experimental::use_root_sync};dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});- s->parallel_for<dpct_kernel_name<class native_q4_k_mmvq_kernel_1ca3b8,+ s->parallel_for<dpct_kernel_name<class native_q4_k_mmvq_kernel_b29f4f,dpct_kernel_scalar<false>>>(sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads,threads),@@ -2502,6 +3425,7 @@ void native_q4_k_f32(const void* weights, const float* x, void* scratch_q8_1,void native_q6_k_mmvq(const void* weights, const void* x_q8_1, float* y,int n_in, int n_out, int ncols, void* stream) {+ if (q6_packed_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream)) return; // STRATA_Q6_PACKED=1 heads// SYCL port: 16-byte-load kernel for the decode shapes (ncols <= 4)// With the aligned loads (load16_a2) the wide kernel wins on every Q6_K shape and window width: 2.6-3.4x the// misaligned-load kernels in q6k_align_bench, decode 44.9 -> 54 tok/s on the Coder, output tokens identical.@@ -2537,6 +3461,7 @@ void native_q6_k_mmvq(const void* weights, const void* x_q8_1, float* y,validate_pointer(x_q8_1);validate_pointer(y);validate_stream(stream);+ STRATA_WAVE_MMVQ(Q6KTraits)if (ncols > 1) {launch_multi<Q6KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);launch_check();@@ -2558,7 +3483,7 @@ void native_q6_k_mmvq(const void* weights, const void* x_q8_1, float* y,sycl::ext::oneapi::experimental::use_root_sync};s->parallel_for<- dpct_kernel_name<class native_q6_k_mmvq_kernel_902936,+ dpct_kernel_name<class native_q6_k_mmvq_kernel_4d887f,dpct_kernel_scalar<true>>>(sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads, threads),exp_props,@@ -2576,7 +3501,7 @@ void native_q6_k_mmvq(const void* weights, const void* x_q8_1, float* y,auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- s->parallel_for<dpct_kernel_name<class native_q6_k_mmvq_kernel_239e8f,+ s->parallel_for<dpct_kernel_name<class native_q6_k_mmvq_kernel_19484e,dpct_kernel_scalar<false>>>(sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads,threads),@@ -2621,8 +3546,88 @@ void native_q5_0_f32(const void* weights, const float* x, void* scratch_q8_1,small_f32<Q50Block, 4>(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream);}+template <int NCOLS>+void q8_0_pair_launch(const Q80Block *w1, const Q80Block *w2, const Q81Block *x,+ float *y1, float *y2, int n_in, int n_out,+ dpct::queue_ptr s) {+ using F = SmallTraits<Q80Block, 8>;+ const dpct::dim3 threads(WARP, WARPS);+ if (s26_tsum_on())+ /*+ 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. Adjust the work-group size if needed.+ */+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});++ s->parallel_for<dpct_kernel_name<+ class native_mmvq_multi_kernel_ab153b, F, dpct_kernel_scalar<NCOLS>,+ dpct_kernel_scalar<WARPS>, dpct_kernel_scalar<1>,+ dpct_kernel_scalar<true>, dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(sycl::range(1, 1, unsigned(2 * n_out)) * threads,+ threads),+ exp_props,+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ native_mmvq_multi_kernel<F, NCOLS, WARPS, 1, true, true>(+ w1, x, y1, n_in, n_out, w2, y2);+ });+ } else+ /*+ 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. Adjust the work-group size if needed.+ */+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});++ s->parallel_for<dpct_kernel_name<+ class native_mmvq_multi_kernel_50d9c5, F, dpct_kernel_scalar<NCOLS>,+ dpct_kernel_scalar<WARPS>, dpct_kernel_scalar<1>,+ dpct_kernel_scalar<false>, dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(sycl::range(1, 1, unsigned(2 * n_out)) * threads,+ threads),+ exp_props,+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ native_mmvq_multi_kernel<F, NCOLS, WARPS, 1, false, true>(+ w1, x, y1, n_in, n_out, w2, y2);+ });+ }+}++bool native_mmvq_pair(int ggml_type, const void* w1, const void* w2, const void* x_q8_1, float* y1, float* y2,+ int n_in, int n_out, int ncols, void* stream) {+ using F = SmallTraits<Q80Block, 8>;+ // only where both calls would run native_mmvq_multi_kernel<F, ncols, WARPS, 1> (exact layout, not packed)+ if (ggml_type != 8 || !g_multi_exact || ncols < 2 || ncols > 8 || n_out <= 0 || n_in <= 0 || n_in % 32 != 0 ||+ n_in / F::DIV < F::BPI || !w1 || !w2 || !x_q8_1 || !y1 || !y2 || !stream)+ return false;+ const auto& reg = q8_packed_registry();+ if (reg.count(w1) || reg.count(w2)) return false;+ const auto* a = static_cast<const Q80Block*>(w1);+ const auto* b = static_cast<const Q80Block*>(w2);+ const auto* x = static_cast<const Q81Block*>(x_q8_1);+ const auto s = strata::q_of(stream);+ switch (ncols) {+ case 2: q8_0_pair_launch<2>(a, b, x, y1, y2, n_in, n_out, s); break;+ case 3: q8_0_pair_launch<3>(a, b, x, y1, y2, n_in, n_out, s); break;+ case 4: q8_0_pair_launch<4>(a, b, x, y1, y2, n_in, n_out, s); break;+ case 5: q8_0_pair_launch<5>(a, b, x, y1, y2, n_in, n_out, s); break;+ case 6: q8_0_pair_launch<6>(a, b, x, y1, y2, n_in, n_out, s); break;+ case 7: q8_0_pair_launch<7>(a, b, x, y1, y2, n_in, n_out, s); break;+ default: q8_0_pair_launch<8>(a, b, x, y1, y2, n_in, n_out, s); break;+ }+ launch_check();+ return true;+}+void native_q8_0_mmvq(const void* weights, const void* x_q8_1, float* y,int n_in, int n_out, int ncols, void* stream) {+ if (q8_packed_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream)) return; // STRATA_Q8_PACKED=1 tensorsif (try_wide32<Wide32Q8>(weights, x_q8_1, y, n_in, n_out, ncols, stream)) { launch_check(); return; }small_mmvq<Q80Block, 8>(weights, x_q8_1, y, n_in, n_out, ncols, stream);}diff --git a/sycl/src/kernels/cuda/native_moe.dp.cpp b/sycl/src/kernels/cuda/native_moe.dp.cppindex 3212e3ced..6c951ba77 100644--- a/sycl/src/kernels/cuda/native_moe.dp.cpp+++ b/sycl/src/kernels/cuda/native_moe.dp.cpp@@ -35,11 +35,14 @@namespace strata::kernels {namespace {std::atomic<bool> enabled{false};-__dpct_inline__ void combine(const float *__restrict__ parts,- const float *__restrict__ weights,- const float *__restrict__ shared,- float *__restrict__ output, int64_t n_embd,- int k) {+// GATED (S26 STRATA_LFUSE): `shared` is the shared expert's unscaled output and sg its raw gate logit per token;+// the row is scaled here as shared_expert_multi did (native_scalar_sigmoid_multi_kernel's expression, then one+// rounded multiply = scale_rows_kernel's `out *= g`), then added as before+template <bool ZADD = false, bool GATED = false>+__dpct_inline__ void+combine(const float *__restrict__ parts, const float *__restrict__ weights,+ const float *__restrict__ shared, float *__restrict__ output,+ int64_t n_embd, int k, const float *__restrict__ sg = nullptr) {// blockIdx.y = the token of a multi-token launch (0 for the single one)auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();const int64_t tk = item_ct1.get_group(1);@@ -48,14 +51,74 @@ __dpct_inline__ void combine(const float *__restrict__ parts,int64_t(item_ct1.get_group(2)) * item_ct1.get_local_range(2) +item_ct1.get_local_id(2);if (col >= n_embd) return;- float sum = parts[col] * weights[0];-#pragma unroll+ // ZADD: a part is 0.0f + hit (the zeroed row plus moe_hit_add of the verify window), rounded as that add+ float p0 = parts[col];+ if (ZADD) p0 = 0.0f + p0;+ float sum = p0 * weights[0];for (int expert = 1; expert < k; ++expert) {- sum += parts[int64_t(expert) * n_embd + col] * weights[expert];+ float p = parts[int64_t(expert) * n_embd + col];+ if (ZADD) p = 0.0f + p;+ sum += p * weights[expert];+ }+ if constexpr (GATED) {+ // contraction off in this block only: the product is rounded on its own (scale_rows' store), then added+#pragma clang fp contract(off)+ const float g = 1.0f / (1.0f + sycl::native::exp(-sg[tk]));+ const float sh = shared[col] * g;+ sum += sh;+ } else {+ if (shared) sum += shared[col];}- if (shared) sum += shared[col];output[col] = sum;}+__dpct_inline__ void combine_k10_vec4(const sycl::float4 *__restrict__ parts4,+ const float *__restrict__ weights,+ const sycl::float4 *__restrict__ shared4,+ sycl::float4 *__restrict__ output4,+ int64_t n4) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int64_t tk = item_ct1.get_group(1);+ parts4 += tk * 10 * n4;+ weights += tk * 10;+ shared4 += tk * n4;+ output4 += tk * n4;+ const int64_t c4 =+ int64_t(item_ct1.get_group(2)) * item_ct1.get_local_range(2) ++ item_ct1.get_local_id(2);+ if (c4 >= n4) return;+ /*+ DPCT1098: The '*' expression is used instead of the __ldg call. These+ two expressions do not provide the exact same functionality. Check the+ generated code for potential precision and/or performance issues.+ */+ const float w0 = *(weights + 0);+ const sycl::float4 p0 = parts4[c4];+ sycl::float4 sum =+ sycl::float4(p0.x() * w0, p0.y() * w0, p0.z() * w0, p0.w() * w0);+#pragma unroll+ for (int expert = 1; expert < 10; ++expert) {+ /*+ DPCT1098: The '*' expression is used instead of the __ldg call.+ These two expressions do not provide the exact same functionality. Check+ the generated code for potential precision and/or performance issues.+ */+ const float w = *(weights + expert);+ const sycl::float4 p = parts4[int64_t(expert) * n4 + c4];+ // the documented contract spelled out: the first product rounded, then one FMA per expert in order. Left to the+ // compiler's contraction, a build may fuse a different product (gfx1151: the float4 kernel then differed from the+ // scalar one, native_multi_parity)+ sum.x() = sycl::fma((float)(p.x()), (float)w, sum.x());+ sum.y() = sycl::fma((float)(p.y()), (float)w, sum.y());+ sum.z() = sycl::fma((float)(p.z()), (float)w, sum.z());+ sum.w() = sycl::fma((float)(p.w()), (float)w, sum.w());+ }+ const sycl::float4 sh = shared4[c4];+ sum.x() += sh.x();+ sum.y() += sh.y();+ sum.z() += sh.z();+ sum.w() += sh.w();+ output4[c4] = sum;+}bool valid_span(const void* p, size_t bytes) {const auto address = reinterpret_cast<uintptr_t>(p);return p && address % alignof(float) == 0 && bytes <= UINTPTR_MAX - address;@@ -79,18 +142,47 @@ void native_moe_combine(const float* parts, const float* weights, const float* s|| overlap(output, row_bytes, weights, weight_bytes)|| (shared && overlap(output, row_bytes, shared, row_bytes)))throw std::invalid_argument("native MoE combine requires aligned spans and disjoint output");- {+ if (k == 10 && shared != nullptr && (n_embd & 3) == 0 &&+ (((uintptr_t) parts | (uintptr_t) shared | (uintptr_t) output) & 15u) == 0) {+ const int64_t n4 = n_embd >> 2;+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ ((sycl::queue *)(strata::q_of(stream)))+ ->parallel_for<dpct_kernel_name<class combine_k10_vec4_503ec2>>(+ sycl::nd_range<3>(+ sycl::range(1, 1, unsigned((n4 + 127) / 128)) *+ sycl::range(1, 1, 128),+ sycl::range(1, 1, 128)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ combine_k10_vec4(+ reinterpret_cast<const sycl::float4 *>(parts),+ weights,+ reinterpret_cast<const sycl::float4 *>(shared),+ reinterpret_cast<sycl::float4 *>(output), n4);+ });+ }+ } else {auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};((sycl::queue *)(strata::q_of(stream)))- ->parallel_for<dpct_kernel_name<class combine_d6d46b>>(+ ->/*+DPCT1050: The template argument of the dpct_kernel_name could not be+deduced. You need to update this code.+*/+ parallel_for<+ dpct_kernel_name<class combine_f74f36,+ dpct_kernel_scalar<false>,+ dpct_kernel_scalar<false>>>(sycl::nd_range<3>(sycl::range(1, 1, unsigned((n_embd + 255) / 256)) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),exp_props, [=](sycl::nd_item<3> item_ct1) {- combine(parts, weights, shared, output, n_embd, int(k));+ combine(parts, weights, shared, output, n_embd, int(k),+ nullptr);});}/*@@ -118,18 +210,136 @@ void native_moe_combine_multi(const float* parts, const float* weights, const flint64_t n_embd, int64_t k, int n_tok, void* stream) {if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1)throw std::invalid_argument("native MoE combine (multi) requires a stream, width, 1..15 experts, tokens");+ if (k == 10 && shared != nullptr && (n_embd & 3) == 0 &&+ (((uintptr_t) parts | (uintptr_t) shared | (uintptr_t) output) & 15u) == 0) {+ const int64_t n4 = n_embd >> 2;+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ ((sycl::queue *)(strata::q_of(stream)))+ ->parallel_for<dpct_kernel_name<class combine_k10_vec4_44a528>>(+ sycl::nd_range<3>(sycl::range(1, (unsigned)n_tok,+ unsigned((n4 + 127) / 128)) *+ sycl::range(1, 1, 128),+ sycl::range(1, 1, 128)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ combine_k10_vec4(+ reinterpret_cast<const sycl::float4 *>(parts),+ weights,+ reinterpret_cast<const sycl::float4 *>(shared),+ reinterpret_cast<sycl::float4 *>(output), n4);+ });+ }+ } else {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ ((sycl::queue *)(strata::q_of(stream)))+ ->/*+DPCT1050: The template argument of the dpct_kernel_name could not be+deduced. You need to update this code.+*/+ parallel_for<+ dpct_kernel_name<class combine_d78bb3,+ dpct_kernel_scalar<false>,+ dpct_kernel_scalar<false>>>(+ sycl::nd_range<3>(sycl::range(1, (unsigned)n_tok,+ unsigned((n_embd + 255) / 256)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ combine(parts, weights, shared, output, n_embd, int(k),+ nullptr);+ });+ }+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use the+ error codes. The cudaGetLastError function call was replaced with 0. You+ need to rewrite this code.+ */+ const auto error = 0;+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (error !=+ 0) throw std::runtime_error(dpct::get_error_string_dummy(error));+}+void native_moe_combine_multi_hits_gated(const float* hits, const float* weights, const float* shared,+ const float* shared_gate, float* output, int64_t n_embd, int64_t k, int n_tok,+ void* stream) {+ if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1 || !shared || !shared_gate)+ throw std::invalid_argument("native MoE combine (hits, gated) requires a stream, width, 1..15 experts, tokens");+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ ((sycl::queue *)(strata::q_of(stream)))+ ->parallel_for<+ dpct_kernel_name<class combine_deb31a, dpct_kernel_scalar<true>,+ dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(sycl::range(1, (unsigned)n_tok,+ unsigned((n_embd + 255) / 256)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ combine<true, true>(hits, weights, shared, output, n_embd,+ int(k), shared_gate);+ });+ }+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use the+ error codes. The cudaGetLastError function call was replaced with 0. You+ need to rewrite this code.+ */+ const auto error = 0;+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (error !=+ 0) throw std::runtime_error(dpct::get_error_string_dummy(error));+}+void native_moe_combine_multi_hits(const float* hits, const float* weights, const float* shared, float* output,+ int64_t n_embd, int64_t k, int n_tok, void* stream) {+ if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1)+ throw std::invalid_argument("native MoE combine (hits) requires a stream, width, 1..15 experts, tokens");{auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};((sycl::queue *)(strata::q_of(stream)))- ->parallel_for<dpct_kernel_name<class combine_eee9de>>(+ ->/*+ DPCT1050: The template argument of the dpct_kernel_name could not be+ deduced. You need to update this code.+ */+ parallel_for<+ dpct_kernel_name<class combine_772c4f, dpct_kernel_scalar<true>,+ dpct_kernel_scalar<false>>>(sycl::nd_range<3>(sycl::range(1, (unsigned)n_tok,unsigned((n_embd + 255) / 256)) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),exp_props, [=](sycl::nd_item<3> item_ct1) {- combine(parts, weights, shared, output, n_embd, int(k));+ combine<true>(hits, weights, shared, output, n_embd, int(k),+ nullptr);});}/*diff --git a/sycl/src/kernels/cuda/native_qsa.dp.cpp b/sycl/src/kernels/cuda/native_qsa.dp.cppindex 221831459..62370a7b7 100644--- a/sycl/src/kernels/cuda/native_qsa.dp.cpp+++ b/sycl/src/kernels/cuda/native_qsa.dp.cpp@@ -80,6 +80,36 @@ __dpct_inline__ void norm(const float *input, const float *__restrict__ gamma,for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize)output[col] = scale * input[col] * gamma[col];}+// As norm, with gamma[groups * n_cols]: row r is group r % groups and reads its own slice of gamma.+template <int BlockSize>+__dpct_inline__ void+norm_grouped(const float *input, const float *__restrict__ gamma, float *output,+ int n_cols, int groups, float epsilon) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int tid = item_ct1.get_local_id(2);+ const std::size_t row_offset = std::size_t(item_ct1.get_group(2)) * n_cols;+ input += row_offset; output += row_offset;+ gamma += std::size_t(item_ct1.get_group(2) % unsigned(groups)) * n_cols;+ float partial = 0.0f;+ for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) {+ const float x = input[col];+ partial += x * x;+ }+ auto &sums =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ partial = warp_sum(partial);+ const int lane = tid % 32;+ if (lane == 0) sums[tid / 32] = partial;+ item_ct1.barrier(sycl::access::fence_space::local_space);+ partial = lane < BlockSize / 32 ? sums[lane] : 0.0f;+ partial = warp_sum(partial);+ const float mean = partial / n_cols;+ const float scale = sycl::rsqrt(mean + epsilon);+#pragma unroll+ for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize)+ output[col] = scale * input[col] * gamma[col];+}__dpct_inline__ void gate(const float *attn, const float *__restrict__ q_full,float *output, int n_head, int head_dim) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();@@ -153,7 +183,7 @@ void native_qsa_rms_norm_weighted(const float* input, const float* gamma, float*((sycl::queue *)(strata::q_of(stream)))->parallel_for<- dpct_kernel_name<class norm_bffbae, dpct_kernel_scalar<256>>>(+ dpct_kernel_name<class norm_5d08bf, dpct_kernel_scalar<256>>>(sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_rows)) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),@@ -174,7 +204,7 @@ void native_qsa_rms_norm_weighted(const float* input, const float* gamma, float*((sycl::queue *)(strata::q_of(stream)))->parallel_for<- dpct_kernel_name<class norm_de4c8c, dpct_kernel_scalar<1024>>>(+ dpct_kernel_name<class norm_127936, dpct_kernel_scalar<1024>>>(sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_rows)) *sycl::range(1, 1, 1024),sycl::range(1, 1, 1024)),@@ -186,6 +216,55 @@ void native_qsa_rms_norm_weighted(const float* input, const float* gamma, float*}check_launch();}+void native_qsa_rms_norm_grouped(const float* input, const float* gamma, float* output,+ int n_cols, int groups, int n_rows, float epsilon, void* stream) {+ if (groups < 1) throw std::invalid_argument("native QSA requires positive bounded dimensions");+ const auto count = elements(n_cols, n_rows);+ if (!std::isfinite(epsilon) || epsilon < 0.0f)+ throw std::invalid_argument("native QSA requires finite nonnegative epsilon");+ buffers(input, count * 4, gamma, std::size_t(n_cols) * groups * 4, output, stream);+ if (n_cols < 1024)+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ ((sycl::queue *)(strata::q_of(stream)))+ ->parallel_for<dpct_kernel_name<class norm_grouped_b5907a,+ dpct_kernel_scalar<256>>>(+ sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_rows)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ norm_grouped<256>(input, gamma, output, n_cols, groups,+ epsilon);+ });+ } else+ /*+ 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. Adjust the work-group size if needed.+ */+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ ((sycl::queue *)(strata::q_of(stream)))+ ->parallel_for<dpct_kernel_name<class norm_grouped_927e80,+ dpct_kernel_scalar<1024>>>(+ sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_rows)) *+ sycl::range(1, 1, 1024),+ sycl::range(1, 1, 1024)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ norm_grouped<1024>(input, gamma, output, n_cols, groups,+ epsilon);+ });+ }+ check_launch();+}void native_qsa_gate_apply(const float* attn, const float* q_full, float* output,int n_head, int head_dim, void* stream) {const auto count = elements(head_dim, n_head);diff --git a/sycl/src/kernels/cuda/native_qsa_indexer.dp.cpp b/sycl/src/kernels/cuda/native_qsa_indexer.dp.cppindex 52f01ccba..c1d89635e 100644--- a/sycl/src/kernels/cuda/native_qsa_indexer.dp.cpp+++ b/sycl/src/kernels/cuda/native_qsa_indexer.dp.cpp@@ -54,97 +54,129 @@ inline float warp_sum(float x) {template <bool TAB>__dpct_inline__ voidappend(const float *__restrict__ raw, const int32_t *__restrict__ pos_dev,- int pos_base, const float *__restrict__ gamma, float epsilon,- float *__restrict__ tail, float *__restrict__ dead,- float *__restrict__ pooled, int32_t *__restrict__ block_pos,- int max_cells, float theta_scale, float freq_scale, float corr_low,- float corr_high, float ext_factor, float mscale,- const int32_t *__restrict__ mtab, RopeTab rt) {+ int pos_stride, int n_steps, int pos_base,+ const float *__restrict__ gamma, float epsilon, float *__restrict__ tail,+ float *__restrict__ dead, float *__restrict__ pooled,+ int32_t *__restrict__ block_pos, int max_cells, float theta_scale,+ float freq_scale, float corr_low, float corr_high, float ext_factor,+ float mscale, const int32_t *__restrict__ mtab, RopeTab rt) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();- const int pos = *pos_dev, d = item_ct1.get_local_id(2);- if (pos < 0 || pos >= max_cells) return;- const int slot = pos % R;- float incoming = 0.0f;- if (d < D) {- // SET_ROWS stores F16; GET_ROWS expands those exact values to F32.- incoming = sycl::vec<sycl::half, 1>(- sycl::vec<float, 1>(raw[d])- .convert<sycl::half, sycl::rounding_mode::rte>()[0])- .convert<float, sycl::rounding_mode::automatic>()[0];- if (slot < R - 1) tail[slot * D + d] = incoming;- }- if (pos != 0 && slot != R - 1) return;- auto &values =- *sycl::ext::oneapi::group_local_memory_for_overwrite<float[D]>(- sycl::ext::oneapi::this_work_item::get_work_group<3>());+auto &values = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[D]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());auto &partials =*sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(sycl::ext::oneapi::this_work_item::get_work_group<3>());- float mean = 0.0f;- if (d < D) {- // The spare's four gather indices all name cell zero. Completed blocks- // use chronological slices; each graph ADD materializes an F32 sum.- float sum = pos == 0 ? incoming : tail[d];+ const int d = item_ct1.get_local_id(2);+ for (int step_idx = 0; step_idx < n_steps; ++step_idx) {+ const int pos = pos_dev[(std::size_t) step_idx * pos_stride];+ if (pos >= 0 && pos < max_cells) {+ const float* raw_step = raw + (std::size_t) step_idx * D;+ const int slot = pos % R;+ float incoming = 0.0f;+ if (d < D) {+ // SET_ROWS stores F16; GET_ROWS expands those exact values to F32.+ incoming =+ sycl::vec<sycl::half, 1>(+ sycl::vec<float, 1>(raw_step[d])+ .convert<sycl::half, sycl::rounding_mode::rte>()[0])+ .convert<float, sycl::rounding_mode::automatic>()[0];+ if (slot < R - 1) tail[slot * D + d] = incoming;+ }+ if (pos == 0 || slot == R - 1) {+ float mean = 0.0f;+ if (d < D) {+ // The spare's four gather indices all name cell zero. Completed blocks+ // use chronological slices; each graph ADD materializes an F32 sum.+ float sum = pos == 0 ? incoming : tail[d];#pragma unroll- for (int j = 1; j < R; ++j)- /*- DPCT1013: The rounding mode could not be specified and the- generated code may have different accuracy than the original code.- Verify the correctness. SYCL math built-in function rounding mode is- aligned with OpenCL C 1.2 standard.- */- sum = sum + (pos == 0 || j == R - 1 ? incoming : tail[j * D + d]);+ for (int j = 1; j < R; ++j)+ /*+ DPCT1013: The rounding mode could not be specified+ and the generated code may have different accuracy than+ the original code. Verify the correctness. SYCL math+ built-in function rounding mode is aligned with OpenCL+ C 1.2 standard.+ */+ sum = sum + (pos == 0 || j == R - 1 ? incoming+ : tail[j * D + d]);+ /*+ DPCT1013: The rounding mode could not be specified and+ the generated code may have different accuracy than the+ original code. Verify the correctness. SYCL math built-in+ function rounding mode is aligned with OpenCL C 1.2+ standard.+ */+ mean = sycl::fma(0.25f, sum,+ 0.0f); // SCALE includes a zero bias.+ }+ float square_sum = 0.0f;+ if (d < D) square_sum += mean * mean;+ square_sum = warp_sum(square_sum);+ const int lane = d % 32;+ if (lane == 0) partials[d / 32] = square_sum;+ /*+ DPCT1118: SYCL group functions and algorithms must be+ encountered in converged control flow. You may need to adjust+ the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ square_sum = lane < THREADS / 32 ? partials[lane] : 0.0f;+ square_sum = warp_sum(square_sum);+ const float scale = sycl::rsqrt(square_sum / D + epsilon);+ if (d < D) values[d] = scale * mean * gamma[d];+ /*+ DPCT1118: SYCL group functions and algorithms must be+ encountered in converged control flow. You may need to adjust+ the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ if (d < D) {+ const int b = pos / R;+ const int rope_pos = pos == 0 ? 0 : pos_base + R * b;+ float y = values[d];+ if (d < ROT) {+ const int pair = d % (ROT / 2);+ // The spare (pos == 0) keeps its zero angle; under YaRN the mscale magnitude still rides in+ // through cos(0) - which is exactly what the queries are scaled by, so the top-k is unmoved.+ float c, s;+ if (!(TAB && rope_tab_cs(rt, pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s))) {+ const float theta_extrap =+ (pos == 0 ? 0+ : mrope_pos(mtab, rope_pos, pair)) *+ dpct::pow(theta_scale, float(pair));+ rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s);+ }+ const float a = values[pair], z = values[pair + ROT / 2];+ y = d < ROT / 2 ? a * c - z * s : a * s + z * c;+ }+ pooled[std::size_t(b) * D + d] = y;+ if (pos == 0) dead[d] = y;+ else pooled[std::size_t(b + 1) * D + d] = dead[d];+ if (d == 0 && pos != 0) *block_pos = rope_pos;+ }+ }+ }/*- DPCT1013: The rounding mode could not be specified and the generated- code may have different accuracy than the original code. Verify the- correctness. SYCL math built-in function rounding mode is aligned with- OpenCL C 1.2 standard.+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.*/- mean = sycl::fma(0.25f, sum, 0.0f); // SCALE includes a zero bias.- }- float square_sum = 0.0f;- if (d < D) square_sum += mean * mean;- square_sum = warp_sum(square_sum);- const int lane = d % 32;- if (lane == 0) partials[d / 32] = square_sum;- /*- 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.- */- item_ct1.barrier();- square_sum = lane < THREADS / 32 ? partials[lane] : 0.0f;- square_sum = warp_sum(square_sum);- const float scale = sycl::rsqrt(square_sum / D + epsilon);- if (d < D) values[d] = scale * mean * gamma[d];- /*- 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.- */- item_ct1.barrier();- if (d >= D) return;- const int b = pos / R;- const int rope_pos = pos == 0 ? 0 : pos_base + R * b;- float y = values[d];- if (d < ROT) {- const int pair = d % (ROT / 2);- // The spare (pos == 0) keeps its zero angle; under YaRN the mscale magnitude still rides in- // through cos(0) - which is exactly what the queries are scaled by, so the top-k is unmoved.- float c, s;- if (!(TAB && rope_tab_cs(rt, pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s))) {- const float theta_extrap =- (pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair)) *- dpct::pow(theta_scale, float(pair));- rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s);- }- const float a = values[pair], z = values[pair + ROT / 2];- y = d < ROT / 2 ? a * c - z * s : a * s + z * c;+ /*+ 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 (n_steps > 1) item_ct1.barrier();}- pooled[std::size_t(b) * D + d] = y;- if (pos == 0) dead[d] = y;- else pooled[std::size_t(b + 1) * D + d] = dead[d];- if (d == 0 && pos != 0) *block_pos = rope_pos;}// ---- C-2: the batched append. The pooled key of a completed block b (its last cell pos = 4b+3), computed with// the single append's arithmetic: keys rounded through F16, summed tail[0]+tail[1]+tail[2]+incoming in that order,@@ -341,15 +373,18 @@ bool overlaps(Span a, Span b) {void native_qsa_indexer_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); }bool native_qsa_indexer_enabled() { return enabled.load(std::memory_order_relaxed); }-void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_device, int32_t pos_base,- const float* gamma, float epsilon, const QsaIndexerBuffers& b,- const QsaShapes& s, int64_t max_cells, const RopeScaling& scaling, void* stream) {+void native_qsa_indexer_append_steps(const float* raw, const int32_t* relative_pos_device,+ int pos_stride, int n_steps, int32_t pos_base,+ const float* gamma, float epsilon, const QsaIndexerBuffers& b,+ const QsaShapes& s, int64_t max_cells, const RopeScaling& scaling, void* stream) {+ if (n_steps <= 0) return;if (!stream || s.idx_dim != D || s.idx_block != R || s.n_rot != ROT ||max_cells < 1 || max_cells > INT32_MAX || pos_base < 0 || pos_base % R ||int64_t(pos_base) + max_cells > INT32_MAX || !std::isfinite(epsilon) || epsilon <= 0.0f ||rope_scaling_invalid(scaling) != nullptr)throw std::invalid_argument("native QSA indexer requires fixed geometry, aligned position base, positive capacity/epsilon, valid frequency/scaling and explicit stream");- const Span spans[] = {{raw,D*4},{relative_pos_device,4},{gamma,D*4},{b.tail,(R-1)*D*4},+ const std::size_t pos_span = (n_steps == 1 || pos_stride <= 0) ? 4 : (std::size_t(n_steps - 1) * pos_stride + 1) * 4;+ const Span spans[] = {{raw,std::size_t(n_steps)*D*4},{relative_pos_device,pos_span},{gamma,D*4},{b.tail,(R-1)*D*4},{b.dead,D*4},{b.pooled,std::size_t(max_cells/R+1)*D*4},{b.block_pos,4}};for (const auto& span : spans) validate(span);for (int i = 0; i < 7; ++i) for (int j = i + 1; j < 7; ++j)@@ -364,7 +399,7 @@ void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_dev((sycl::queue *)(strata::q_of(stream)))->submit([&](sycl::handler &cgh) {- auto mrope_table_ct16 = mrope_table();+ auto mrope_table_ct18 = mrope_table();cgh.parallel_for<dpct_kernel_name<class append_182f95,dpct_kernel_scalar<true>>>(@@ -373,12 +408,13 @@ void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_devexp_props,[=](sycl::nd_item<3> item_ct1)[[sycl::reqd_sub_group_size(32)]] {- append<true>(raw, relative_pos_device, pos_base,- gamma, epsilon, b.tail, b.dead,- b.pooled, b.block_pos, int(max_cells),- theta_scale, k.freq_scale, k.corr_low,- k.corr_high, k.ext_factor,- k.attn_factor, mrope_table_ct16, rt);+ append<true>(raw, relative_pos_device, pos_stride,+ n_steps, pos_base, gamma, epsilon,+ b.tail, b.dead, b.pooled, b.block_pos,+ int(max_cells), theta_scale,+ k.freq_scale, k.corr_low, k.corr_high,+ k.ext_factor, k.attn_factor,+ mrope_table_ct18, rt);});});} else {@@ -387,7 +423,7 @@ void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_dev((sycl::queue *)(strata::q_of(stream)))->submit([&](sycl::handler &cgh) {- auto mrope_table_ct16 = mrope_table();+ auto mrope_table_ct18 = mrope_table();cgh.parallel_for<dpct_kernel_name<class append_182f95,dpct_kernel_scalar<false>>>(@@ -396,12 +432,13 @@ void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_devexp_props,[=](sycl::nd_item<3> item_ct1)[[sycl::reqd_sub_group_size(32)]] {- append<false>(raw, relative_pos_device, pos_base,- gamma, epsilon, b.tail, b.dead,- b.pooled, b.block_pos, int(max_cells),- theta_scale, k.freq_scale, k.corr_low,- k.corr_high, k.ext_factor,- k.attn_factor, mrope_table_ct16, rt);+ append<false>(raw, relative_pos_device, pos_stride,+ n_steps, pos_base, gamma, epsilon,+ b.tail, b.dead, b.pooled, b.block_pos,+ int(max_cells), theta_scale,+ k.freq_scale, k.corr_low, k.corr_high,+ k.ext_factor, k.attn_factor,+ mrope_table_ct18, rt);});});}@@ -426,6 +463,12 @@ void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_devif (error !=0) throw std::runtime_error(dpct::get_error_string_dummy(error));}++void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_device, int32_t pos_base,+ const float* gamma, float epsilon, const QsaIndexerBuffers& b,+ const QsaShapes& s, int64_t max_cells, const RopeScaling& scaling, void* stream) {+ native_qsa_indexer_append_steps(raw, relative_pos_device, 0, 1, pos_base, gamma, epsilon, b, s, max_cells, scaling, stream);+}void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, int32_t pos_base, const float* gamma,float epsilon, const QsaIndexerBuffers& b, const QsaShapes& s, int64_t max_cells,const RopeScaling& scaling, void* stream) {diff --git a/sycl/src/kernels/cuda/native_rope.dp.cpp b/sycl/src/kernels/cuda/native_rope.dp.cppindex 9f67374c5..07110dbae 100644--- a/sycl/src/kernels/cuda/native_rope.dp.cpp+++ b/sycl/src/kernels/cuda/native_rope.dp.cpp@@ -74,6 +74,103 @@ __dpct_inline__ void apply(const float *x, float *out, int rows, int width,out[start + pair] = a * c - b * s;out[start + pair + n_rot / 2] = a * s + b * c;}++template <bool TAB>+__dpct_inline__ void+norm_rope_kernel(const float *x, int in_stride, const float *__restrict__ gamma,+ float *out, int n_cols, int n_rot, float epsilon,+ float theta_scale, float freq_scale, float corr_low,+ float corr_high, float ext_factor, float mscale,+ const int *positions, const int32_t *mtab, RopeTab rt) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int tid = item_ct1.get_local_id(2);+ const int row = item_ct1.get_group(2);+ const float* in_row = x + size_t(row) * in_stride;+ float* out_row = out + size_t(row) * n_cols;+ float partial = 0.0f;+ for (size_t col = tid; col < size_t(n_cols); col += 256) {+ const float xv = in_row[col];+ partial += xv * xv;+ }+ const int half_rot = n_rot / 2;+ const float x_tid = tid < n_cols ? in_row[tid] : 0.0f;+ const float x_hi = tid < half_rot ? in_row[tid + half_rot] : 0.0f;+ auto &sums =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+#pragma unroll+ for (int offset = 16; offset; offset >>= 1)+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ partial += dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),+ partial, offset);+ const int lane = tid % 32;+ if (lane == 0) sums[tid / 32] = partial;+ /*+ 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.+ */+ item_ct1.barrier();+ partial = lane < 256 / 32 ? sums[lane] : 0.0f;+#pragma unroll+ for (int offset = 16; offset; offset >>= 1)+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ partial += dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),+ partial, offset);+ const float mean = partial / n_cols;+ const float scale = sycl::rsqrt(mean + epsilon);+ if (tid >= n_rot && tid < n_cols) {+ out_row[tid] = (scale * x_tid) * gamma[tid];+ } else if (tid < half_rot) {+ const int pair = tid;+ float a = (scale * x_tid) * gamma[pair];+ float b = (scale * x_hi) * gamma[pair + half_rot];+#if defined(DPCT_COMPATIBILITY_TEMP) && !defined(__HIP_DEVICE_COMPILE__)+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)+ asm volatile("mov.f32 %0, %1;" : "=f"(a) : "f"(a));+#else+ a = a;+#endif+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)+ asm volatile("mov.f32 %0, %1;" : "=f"(b) : "f"(b));+#else+ b = b;+#endif+#endif+ float c, s;+ if (!(TAB && rope_tab_cs(rt, mrope_pos(mtab, positions[row], pair), pair, c, s))) {+ const float theta_extrap = mrope_pos(mtab, positions[row], pair) *+ dpct::pow(theta_scale, float(pair));+ rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s);+ }+ float bs = b * s;+ float bc = b * c;+#if defined(DPCT_COMPATIBILITY_TEMP) && !defined(__HIP_DEVICE_COMPILE__)+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)+ asm volatile("mov.f32 %0, %1;" : "=f"(bs) : "f"(bs));+#else+ bs = bs;+#endif+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)+ asm volatile("mov.f32 %0, %1;" : "=f"(bc) : "f"(bc));+#else+ bc = bc;+#endif+#endif+ out_row[pair] = sycl::fma(a, c, -bs);+ out_row[pair + half_rot] = sycl::fma(a, s, bc);+ }+}}// one table per device (a layer split runs the rope kernels on several): set and read for the current devicenamespace {@@ -129,6 +226,20 @@ RopeTab rope_table_for(const RopeScaling& scaling) {}void native_rope_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); }bool native_rope_enabled() { return enabled.load(std::memory_order_relaxed); }+bool native_norm_rope_usable(int head_dim, int n_rot) {+ static const bool on = [] {+ const char* off = std::getenv("STRATA_NO_NORM_ROPE");+ if (off != nullptr && off[0] != '\0' && off[0] != '0') return false;+#if defined(__HIPCC__)+ const char* v = std::getenv("STRATA_NORM_ROPE"); // AMD: opt in until rope_parity check 6 passes there+ return v != nullptr && v[0] != '\0' && v[0] != '0';+#else+ return true;+#endif+ }();+ return on && (head_dim == 128 || head_dim == 256) && n_rot == 64;+}+void native_rope_apply(const float* x, float* out, int rows, int head_dim,int n_rot, const RopeScaling& scaling, const int* positions, void* stream) {if (!x || !out || !positions || !stream || rows < 1 || rows > 65535 ||@@ -148,8 +259,15 @@ void native_rope_apply(const float* x, float* out, int rows, int head_dim,const float theta_scale = powf((float) scaling.freq_base, -2.0f / n_rot);const RopeKernelArgs k = scaling.kernel_args(n_rot); // none: the identity constantsconst RopeTab rt = rope_table_for(scaling);- const dpct::dim3 grid((head_dim / 2 + 127) / 128, rows);+ const unsigned threads = (x == out && n_rot == 64 && native_norm_rope_usable(head_dim, n_rot)) ? 32u : 128u;+ const dpct::dim3 grid(+ threads == 32u ? 1u : unsigned((head_dim / 2 + 127) / 128), rows);if (rt.cos != nullptr)+ /*+ 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. Adjust the work-group size if needed.+ */{auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};@@ -160,8 +278,8 @@ void native_rope_apply(const float* x, float* out, int rows, int head_dim,cgh.parallel_for<dpct_kernel_name<class apply_b955ef,dpct_kernel_scalar<true>>>(- sycl::nd_range<3>(grid * sycl::range(1, 1, 128),- sycl::range(1, 1, 128)),+ sycl::nd_range<3>(grid * sycl::range(1, 1, threads),+ sycl::range(1, 1, threads)),exp_props, [=](sycl::nd_item<3> item_ct1) {apply<true>(x, out, rows, head_dim, n_rot, theta_scale,k.freq_scale, k.corr_low, k.corr_high,@@ -169,7 +287,13 @@ void native_rope_apply(const float* x, float* out, int rows, int head_dim,mrope_table_ct12, rt);});});- } else {+ } else+ /*+ 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. Adjust the work-group size if needed.+ */+ {auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};@@ -179,8 +303,8 @@ void native_rope_apply(const float* x, float* out, int rows, int head_dim,cgh.parallel_for<dpct_kernel_name<class apply_b955ef,dpct_kernel_scalar<false>>>(- sycl::nd_range<3>(grid * sycl::range(1, 1, 128),- sycl::range(1, 1, 128)),+ sycl::nd_range<3>(grid * sycl::range(1, 1, threads),+ sycl::range(1, 1, threads)),exp_props, [=](sycl::nd_item<3> item_ct1) {apply<false>(x, out, rows, head_dim, n_rot, theta_scale,k.freq_scale, k.corr_low, k.corr_high,@@ -210,4 +334,88 @@ void native_rope_apply(const float* x, float* out, int rows, int head_dim,if (error !=0) throw std::runtime_error(dpct::get_error_string_dummy(error));}++void native_qsa_rms_norm_rope(const float* x, int in_stride, const float* gamma, float* out,+ int rows, int head_dim, int n_rot, float epsilon,+ const RopeScaling& scaling, const int* positions, void* stream) {+ if (!x || !gamma || !out || !positions || !stream || rows < 1 || rows > 65535 ||+ (head_dim != 128 && head_dim != 256) || in_stride < head_dim || n_rot != 64 ||+ !std::isfinite(epsilon) || epsilon < 0.0f ||+ rope_scaling_invalid(scaling) != nullptr ||+ reinterpret_cast<uintptr_t>(x) % 4 || reinterpret_cast<uintptr_t>(gamma) % 4 ||+ reinterpret_cast<uintptr_t>(out) % 4 || reinterpret_cast<uintptr_t>(positions) % 4) {+ throw std::invalid_argument("native_qsa_rms_norm_rope: invalid arguments");+ }+ const float theta_scale = powf((float) scaling.freq_base, -2.0f / n_rot);+ const RopeKernelArgs k = scaling.kernel_args(n_rot);+ const RopeTab rt = rope_table_for(scaling);+ if (rt.cos != nullptr)+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ ((sycl::queue *)(strata::q_of(stream)))+ ->submit([&](sycl::handler &cgh) {+ auto mrope_table_ct14 = mrope_table();++ cgh.parallel_for<dpct_kernel_name<class norm_rope_kernel_c8b2b8,+ dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(sycl::range(1, 1, unsigned(rows)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ norm_rope_kernel<true>(+ x, in_stride, gamma, out, head_dim, n_rot,+ epsilon, theta_scale, k.freq_scale, k.corr_low,+ k.corr_high, k.ext_factor, k.attn_factor,+ positions, mrope_table_ct14, rt);+ });+ });+ } else {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ ((sycl::queue *)(strata::q_of(stream)))+ ->submit([&](sycl::handler &cgh) {+ auto mrope_table_ct14 = mrope_table();++ cgh.parallel_for<dpct_kernel_name<class norm_rope_kernel_f9c8ef,+ dpct_kernel_scalar<false>>>(+ sycl::nd_range<3>(sycl::range(1, 1, unsigned(rows)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ norm_rope_kernel<false>(+ x, in_stride, gamma, out, head_dim, n_rot,+ epsilon, theta_scale, k.freq_scale, k.corr_low,+ k.corr_high, k.ext_factor, k.attn_factor,+ positions, mrope_table_ct14, rt);+ });+ });+ }+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use the+ error codes. The cudaGetLastError function call was replaced with 0. You+ need to rewrite this code.+ */+ const auto error = 0;+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (error !=+ 0) throw std::runtime_error(dpct::get_error_string_dummy(error));+}}diff --git a/sycl/src/kernels/cuda/native_router.dp.cpp b/sycl/src/kernels/cuda/native_router.dp.cppindex b0af7d0bc..9bbb52d0d 100644--- a/sycl/src/kernels/cuda/native_router.dp.cpp+++ b/sycl/src/kernels/cuda/native_router.dp.cpp@@ -142,6 +142,80 @@ __dpct_inline__ void route(const float *__restrict__ logits,const float inverse_selected_sum = 1.0f / selected_sum;if (lane < 10) weights[lane] = selected * inverse_selected_sum;}+/*+DPCT1110: The total declared local variable size in device function+route_multi exceeds 128 bytes and may cause high register pressure. Consult with+your hardware vendor to find the total register size available and adjust the+code, or use smaller sub-group size to avoid high register pressure.+*/+__dpct_inline__ void route_multi(const float *__restrict__ logits,+ int32_t *__restrict__ ids,+ float *__restrict__ weights, int n_tok) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int tk =+ (int)item_ct1.get_group(2) * 8 + (int)item_ct1.get_local_id(1);+ if (tk >= n_tok) return;+ logits += (size_t) tk * 512; ids += (size_t) tk * 10; weights += (size_t) tk * 10;+ const int lane = item_ct1.get_local_id(2);+ float values[16];+#pragma unroll+ for (int i = 0; i < 16; ++i) values[i] = logits[lane + i * 32];+ sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());+ float maximum = -INFINITY;+#pragma unroll+ for (int i = 0; i < 16; ++i) maximum = sycl::max(maximum, values[i]);+ maximum = warp_max(maximum);+ float sum = 0.0f;+#pragma unroll+ for (int i = 0; i < 16; ++i) {+ values[i] = sycl::native::exp(values[i] - maximum);+ sum += values[i];+ }+ const float reciprocal = 1.0f / warp_sum(sum);+#pragma unroll+ for (int i = 0; i < 16; ++i) {+ values[i] *= reciprocal;+ if (sycl::isnan(values[i])) values[i] = -FLT_MAX;+ }+ float selected = 0.0f, selected_sum = 0.0f;+ for (int rank = 0; rank < 10; ++rank) {+ float best = values[0];+ int expert = lane;+#pragma unroll+ for (int i = 1; i < 16; ++i) {+ if (values[i] > best) { best = values[i]; expert = lane + i * 32; }+ }+#pragma unroll+ for (int mask = 16; mask; mask >>= 1) {+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ const float other = dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),+ best, mask);+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ const int other_id = dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),+ expert, mask);+ if (other > best || (other == best && other_id < expert)) { best = other; expert = other_id; }+ }+ if ((expert & 31) == lane) {+ values[expert / 32] = -INFINITY;+ ids[rank] = expert;+ selected_sum += best;+ }+ if (rank == lane) selected = best;+ }+ selected_sum = sycl::max(warp_sum(selected_sum), 6.103515625e-5f);+ const float inverse_selected_sum = 1.0f / selected_sum;+ if (lane < 10) weights[lane] = selected * inverse_selected_sum;+}bool valid(const void* p, size_t bytes) {const auto address = reinterpret_cast<uintptr_t>(p);return p && address % 4 == 0 && bytes <= UINTPTR_MAX - address;@@ -163,7 +237,7 @@ void native_router_top10(const float* logits, int32_t* ids, float* weights, voidsycl::ext::oneapi::experimental::use_root_sync};((sycl::queue *)(strata::q_of(stream)))- ->parallel_for<dpct_kernel_name<class route_60b296>>(+ ->parallel_for<dpct_kernel_name<class route_96e6fb>>(sycl::nd_range<3>(sycl::range(1, 8, 32), sycl::range(1, 8, 32)),exp_props,[=](sycl::nd_item<3> item_ct1)@@ -201,14 +275,15 @@ void native_router_top10_multi(const float* logits, int32_t* ids, float* weightssycl::ext::oneapi::experimental::use_root_sync};((sycl::queue *)(strata::q_of(stream)))- ->parallel_for<dpct_kernel_name<class route_64c24f>>(- sycl::nd_range<3>(sycl::range(1, 1, (unsigned)n_tok) *- sycl::range(1, 8, 32),- sycl::range(1, 8, 32)),+ ->parallel_for<dpct_kernel_name<class route_multi_a3bff6>>(+ sycl::nd_range<3>(+ sycl::range(1, 1, (unsigned)((n_tok + 7) / 8)) *+ sycl::range(1, 8, 32),+ sycl::range(1, 8, 32)),exp_props,[=](sycl::nd_item<3> item_ct1)[[sycl::reqd_sub_group_size(32)]] {- route<512>(logits, ids, weights);+ route_multi(logits, ids, weights, n_tok);});}/*diff --git a/sycl/src/kernels/cuda/ple.dp.cpp b/sycl/src/kernels/cuda/ple.dp.cppindex 1d430071c..48939e5e0 100644--- a/sycl/src/kernels/cuda/ple.dp.cpp+++ b/sycl/src/kernels/cuda/ple.dp.cpp@@ -281,6 +281,7 @@ void ck(dpct::err0 e, const char *what) {} // namespacevoid ple_set_native_bf16(bool enabled) { native_bf16 = enabled; }+bool ple_native_bf16_enabled() { return native_bf16; }void ple_set_native_postops(bool enabled) { native_postops = enabled; }bool ple_native_postops_enabled() { return native_postops; }@@ -411,7 +412,15 @@ void ple_block(const float* emb, const float* hidden, const float* hist_rows, co// ---- key = grouped_norm(ple_key @ emb). The optional native projection// follows pinned CUDA Q8_1 MMVQ; the default retains its canonical Q8_0 path.- if (w.key_bf16 != nullptr) {+ if (w.pre_key != nullptr) {+ /*+ DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.+ While the origin API might be synchronous, it depends on the type of+ operand memory, so you may need to call wait() on event return by memcpy+ API to ensure synchronization behavior.+ */+ st->memcpy(d_key, w.pre_key, (size_t)hc_dim * sizeof(float));+ } else if (w.key_bf16 != nullptr) {bf16_gemv_fp32_mmvf(emb, w.key_bf16, d_key, n_embd, hc_dim, stream);} else if (native_key) {native_quantize_q8_1(emb, w.key_native_q8_1, n_embd, 1, stream);@@ -431,7 +440,7 @@ void ple_block(const float* emb, const float* hidden, const float* hist_rows, cost->submit([&](sycl::handler &cgh) {auto NG_RMS_EPS_ct4 = NG_RMS_EPS;- cgh.parallel_for<dpct_kernel_name<class gnorm_kernel_2584bb>>(+ cgh.parallel_for<dpct_kernel_name<class gnorm_kernel_e2f600>>(sycl::nd_range<3>(sycl::range(1, 1, hc) *sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),@@ -452,7 +461,7 @@ void ple_block(const float* emb, const float* hidden, const float* hist_rows, cost->submit([&](sycl::handler &cgh) {auto NG_RMS_EPS_ct4 = NG_RMS_EPS;- cgh.parallel_for<dpct_kernel_name<class gnorm_kernel_e3be1c>>(+ cgh.parallel_for<dpct_kernel_name<class gnorm_kernel_92a6ef>>(sycl::nd_range<3>(sycl::range(1, 1, hc) *sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),@@ -467,7 +476,15 @@ void ple_block(const float* emb, const float* hidden, const float* hist_rows, co}// The value projection's independent option leaves the nonlinear PLE operations unchanged.- if (native_bf16) {+ if (w.pre_value != nullptr) {+ /*+ DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.+ While the origin API might be synchronous, it depends on the type of+ operand memory, so you may need to call wait() on event return by memcpy+ API to ensure synchronization behavior.+ */+ st->memcpy(d_value, w.pre_value, (size_t)n_embd * sizeof(float));+ } else if (native_bf16) {bf16_gemv_fp32_mmvf(emb, w.value_bf16, d_value, n_embd, n_embd, stream);} else {{@@ -552,7 +569,7 @@ void ple_block(const float* emb, const float* hidden, const float* hist_rows, cost->submit([&](sycl::handler &cgh) {auto NG_RMS_EPS_ct4 = NG_RMS_EPS;- cgh.parallel_for<dpct_kernel_name<class gnorm_kernel_cb94da>>(+ cgh.parallel_for<dpct_kernel_name<class gnorm_kernel_dda9b4>>(sycl::nd_range<3>(sycl::range(1, 1, hc) *sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),@@ -673,4 +690,21 @@ void ple_block(const float* emb, const float* hidden, const float* hist_rows, co// itself, and the engine's caller does not want that at all.}+void ple_block_projected(const float* projected_key, const float* projected_value, const float* hidden,+ const float* hist_rows, const PleWeights& w, PleOut& out, void* scratch, void* stream) {+ if (!projected_key || !projected_value || !hidden || !hist_rows || !out.result || !scratch) return;+ const int n_embd = NG_N_EMBD, hc = NG_HC, hc_dim = NG_HC_DIM;+ float* d_scratch = (float*) scratch;+ float* d_key = d_scratch;+ float* d_query = d_key + hc_dim;+ float* d_norm = d_query + hc_dim;+ float* d_gated = d_norm + hc_dim;+ float* d_conv = d_gated + hc_dim;+ float* d_value = d_conv + hc_dim;+ float* d_gate = d_value + n_embd;+ float* norm_dst = out.normalized ? out.normalized : d_norm;+ NativePlePostopsBuffers buffers{d_query, norm_dst, d_gate, d_gated, norm_dst, d_conv, out.result};+ native_ple_postops(projected_key, hidden, projected_value, hist_rows, w, buffers, stream);+}+} // namespace strata::kernelsdiff --git a/sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp b/sycl/src/kernels/cuda/qsa_decode_attn.dp.cppindex 39981a32c..552c4a7db 100644--- a/sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp+++ b/sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp@@ -107,7 +107,7 @@ __dpct_inline__ void load8(const QsaAttnPools &p, bool value, long long row,} else load8_q4(p, value, row, d0, out);}-template <int KV_MODE>+template <int KV_MODE, bool LANE_CELL = false>/*DPCT1110: The total declared local variable size in device functionattn_chunk_kernel exceeds 128 bytes and may cause high register pressure.@@ -176,6 +176,46 @@ attn_chunk_kernel(const float *__restrict__ q, QsaAttnPools p,performance if there is no access to global memory.*/item_ct1.barrier();+ if constexpr (LANE_CELL) {+ // S25 (STRATA_ATTN_LANECELL=1): thread t scores cell t % 64 for heads 3 (t / 64) .. +2 by itself - the same+ // 8-dimension partial per former lane (the identical expression), then the former warp_sum's butterfly as+ // lane 0 ran it (a[l] += a[l + o] for o = 16 .. 1), so every score is bit-identical without 12 shuffle+ // reductions per cell+ constexpr int HPT = G * CHUNK / THREADS; // heads per thread (3)+ const int c = t % CHUNK, h0 = (t / CHUNK) * HPT;+ if (c >= n_here || srow[c] < 0) {+#pragma unroll+ for (int j = 0; j < HPT; ++j) sp[h0 + j][c] = -FLT_MAX;+ } else {+ float a[HPT][32];+#pragma unroll+ for (int l = 0; l < 32; ++l) {+ float k8[8];+ load8<KV_MODE>(p, false, srow[c], l * 8, k8);+#pragma unroll+ for (int j = 0; j < HPT; ++j) {+ const sycl::float4 qa =+ *reinterpret_cast<const sycl::float4 *>(+ &sq[h0 + j][l * 8]);+ const sycl::float4 qb =+ *reinterpret_cast<const sycl::float4 *>(+ &sq[h0 + j][l * 8 + 4]);+ float s = k8[0] * qa.x() + k8[1] * qa.y() + k8[2] * qa.z() ++ k8[3] * qa.w() + k8[4] * qb.x() + k8[5] * qb.y() ++ k8[6] * qb.z() + k8[7] * qb.w();+ a[j][l] = s;+ }+ }+#pragma unroll+ for (int j = 0; j < HPT; ++j) {+#pragma unroll+ for (int o = 16; o > 0; o >>= 1)+#pragma unroll+ for (int l = 0; l < o; ++l) a[j][l] = a[j][l] + a[j][l + o];+ sp[h0 + j][c] = a[j][0] * scale;+ }+ }+ } else// scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions.for (int c = warp; c < CHUNK; c += WARPS) {if (c >= n_here || srow[c] < 0) {@@ -265,6 +305,217 @@ attn_chunk_kernel(const float *__restrict__ q, QsaAttnPools p,for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];}+// PR #540 (sskver): the same attention with fewer shuffles and less shared-memory traffic, bit for bit the kernel+// above (same operands, same order); +7% prompt speed on a V100, where this kernel reads every prompt chunk. It+// uses more registers (80 vs 38 on sm_70), so it runs on cards below sm_75 only, and exists only in the experimental+// build (-DSTRATA_EXPERIMENTAL_SM60=ON): the ready-made engine keeps exactly the kernel above.+#if defined(STRATA_EXPERIMENTAL_SM60)+// The 12 heads' lane sums (`part[12..15]` zero), reduce-scattered with warp_sum's pairing order (xor 16, 8, 4, 2, 1):+// every output adds the same two operands at every level, so each sum is bit for bit warp_sum's (float add commutes),+// for 16 shuffles instead of 12 x 5. Lane l ends holding head head_of_lane(l); lanes l and l^1 agree.+__device__ __forceinline__ float reduce12(const float (&part)[16], int lane) {+ float r8[8];+#pragma unroll+ for (int i = 0; i < 8; ++i) {+ const bool hi = (lane & 16) != 0;+ r8[i] = (hi ? part[i + 8] : part[i]) + __shfl_xor_sync(0xffffffffu, hi ? part[i] : part[i + 8], 16);+ }+ float r4[4];+#pragma unroll+ for (int i = 0; i < 4; ++i) {+ const bool hi = (lane & 8) != 0;+ r4[i] = (hi ? r8[i + 4] : r8[i]) + __shfl_xor_sync(0xffffffffu, hi ? r8[i] : r8[i + 4], 8);+ }+ float r2[2];+#pragma unroll+ for (int i = 0; i < 2; ++i) {+ const bool hi = (lane & 4) != 0;+ r2[i] = (hi ? r4[i + 2] : r4[i]) + __shfl_xor_sync(0xffffffffu, hi ? r4[i] : r4[i + 2], 4);+ }+ const bool hi2 = (lane & 2) != 0;+ const float r1 = (hi2 ? r2[1] : r2[0]) + __shfl_xor_sync(0xffffffffu, hi2 ? r2[0] : r2[1], 2);+ return r1 + __shfl_xor_sync(0xffffffffu, r1, 1);+}+__device__ __forceinline__ int head_of_lane(int lane) {+ return ((lane >> 4) & 1) * 8 + ((lane >> 3) & 1) * 4 + ((lane >> 2) & 1) * 2 + ((lane >> 1) & 1);+}++// One V element of pool row `row`, dimension `d` (the value loop's own thread index), per KV format.+template <int KV_MODE>+__device__ __forceinline__ float load_v1(const QsaAttnPools& p, long long row, int d) {+ if constexpr (KV_MODE == 0) {+ return __half2float(__ushort_as_half(p.v_pool[row * HD + d]));+ } else if constexpr (KV_MODE == 1) {+ const float sc = __half2float(__ushort_as_half(p.v_scale[row * (HD / KV_Q8_GROUP) + d / KV_Q8_GROUP]));+ return (float) p.v_q[row * HD + d] * sc;+ } else { // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back+ constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);+ const int b = d / QK4_0;+ const int rem = d % QK4_0;+ const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + row * bytes_per_head) + b;+ const float dd = __half2float(__ushort_as_half(blk->d));+ const int j = rem < 16 ? rem : (rem - 16);+ const uint8_t byte = blk->qs[j];+ const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);+ return (float) nibble * dd;+ }+}++template <int KV_MODE>+__global__ void __launch_bounds__(THREADS) attn_chunk_kernel_pre75(const float* __restrict__ q, QsaAttnPools p,+ const int32_t* __restrict__ ids,+ const int32_t* __restrict__ step, int n_kv_heads,+ int page_size, float scale, float* __restrict__ part_acc,+ float* __restrict__ part_m, float* __restrict__ part_l,+ int n_chunks, int cap = 0, long long scratch_stride = 0) {+ // batched form: query blockIdx.z, with its own q row, selection, step and scratch+ q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD;+ ids += (size_t) blockIdx.z * (size_t) cap;+ step += (size_t) blockIdx.z * kStepCount;+ part_acc += (size_t) blockIdx.z * (size_t) scratch_stride;+ part_m += (size_t) blockIdx.z * (size_t) scratch_stride;+ part_l += (size_t) blockIdx.z * (size_t) scratch_stride;+ __shared__ __align__(16) float sq[G][HD]; // 12 KB: this KV head's query heads (dead once the scores are done)+ __shared__ float sp[G][CHUNK]; // scores+ __shared__ long long srow[CHUNK]; // pool row of each cell (page, kv head, slot)+ // probabilities, cell-major: the value loop reads one cell's 12 as three float4. They are first written after the+ // __syncthreads that ends the score phase, the last reader of sq, so they share its storage (64 x 12 of its 256 x 12+ // floats) and the block's shared memory stays what it was before the cell-major layout.+ float (*const spt)[G] = reinterpret_cast<float (*)[G]>(&sq[0][0]);+ static_assert(CHUNK * G <= G * HD, "spt must fit in sq");+ const int n_ids = __ldg(step + kStepWidth);+ const int chunk = blockIdx.x, kvh = blockIdx.y;+ const int t = threadIdx.x, lane = t & 31, warp = t >> 5;+ const int c0 = chunk * CHUNK;+ const int n_here = min(CHUNK, n_ids - c0);+ const int slot = kvh * n_chunks + chunk;+ if (n_here <= 0) {+ if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }+ return;+ }+ for (int i = t; i < G * HD; i += THREADS) sq[i / HD][i % HD] = q[(size_t) (kvh * G) * HD + i];+ if (t < CHUNK) {+ long long r = -1;+ if (t < n_here) {+ const int cell = ids[c0 + t];+ const long long page = (long long) p.page_table[cell / page_size];+ // a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked+ // (score -FLT_MAX, weight 0) instead of being read from before the pool.+ if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);+ }+ srow[t] = r;+ }+ __syncthreads();+ // scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions. NC cells per step+ // (warp + 8 * (i + j)): a lane's q slice comes out of shared memory once for all of them, which cuts the traffic+ // that bounds this phase (24 x 16 B per lane per cell, against the FMAs) by NC; every dot product is the same+ // expression as for a single cell, so the scores are unchanged.+ constexpr int NC = 2; // 4 measured slower on a V100 (the registers cost occupancy)+ const int hd = head_of_lane(lane);+ for (int i = 0; i < CHUNK / WARPS; i += NC) {+ int cc[NC];+ bool all_ok = true;+#pragma unroll+ for (int j = 0; j < NC; ++j) {+ cc[j] = warp + WARPS * (i + j);+ all_ok = all_ok && cc[j] < n_here && srow[cc[j]] >= 0;+ }+ if (all_ok) {+ float kk[NC][8];+#pragma unroll+ for (int j = 0; j < NC; ++j) load8<KV_MODE>(p, false, srow[cc[j]], lane * 8, kk[j]);+ float pp[NC][16];+#pragma unroll+ for (int h = 0; h < G; ++h) {+ const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);+ const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);+#pragma unroll+ for (int j = 0; j < NC; ++j)+ pp[j][h] = kk[j][0] * qa.x + kk[j][1] * qa.y + kk[j][2] * qa.z + kk[j][3] * qa.w ++ kk[j][4] * qb.x + kk[j][5] * qb.y + kk[j][6] * qb.z + kk[j][7] * qb.w;+ }+#pragma unroll+ for (int j = 0; j < NC; ++j) {+#pragma unroll+ for (int h = G; h < 16; ++h) pp[j][h] = 0.0f;+ const float sj = reduce12(pp[j], lane);+ if ((lane & 1) == 0 && hd < G) sp[hd][cc[j]] = sj * scale;+ }+ } else {+ for (int k = 0; k < NC; ++k) { // a masked or out-of-range cell in the group: one cell at a time+ const int c = cc[k];+ if (c >= n_here || srow[c] < 0) {+ if (lane < G) sp[lane][c] = -FLT_MAX;+ continue;+ }+ float k8[8];+ load8<KV_MODE>(p, false, srow[c], lane * 8, k8);+ float part[16];+#pragma unroll+ for (int h = 0; h < G; ++h) {+ const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);+ const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);+ part[h] = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w ++ k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w;+ }+#pragma unroll+ for (int h = G; h < 16; ++h) part[h] = 0.0f;+ const float s = reduce12(part, lane);+ if ((lane & 1) == 0 && hd < G) sp[hd][c] = s * scale;+ }+ }+ }+ __syncthreads();+ // per-head chunk max and exp-sum: warp w handles heads w and w+8.+ for (int h = warp; h < G; h += WARPS) {+ const float a = sp[h][lane], b = sp[h][lane + 32];+ const float m = warp_max(fmaxf(a, b));+ const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f;+ const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f;+ spt[lane][h] = ea;+ spt[lane + 32][h] = eb;+ const float l = warp_sum(ea + eb);+ if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; }+ }+ __syncthreads();+ // values: thread t owns dimension t for all 12 heads.+ float acc[G];+#pragma unroll+ for (int h = 0; h < G; ++h) acc[h] = 0.0f;+ // One cell's 12 weights (three broadcast float4 loads) into the 12 accumulators; the cells are folded in+ // ascending order, so the sums are the plain loop's, bit for bit.+ const auto fold = [&](int c, float v) {+ const float4* w4 = reinterpret_cast<const float4*>(spt[c]);+ const float4 w0 = w4[0], w1 = w4[1], w2 = w4[2];+ acc[0] = fmaf(w0.x, v, acc[0]); acc[1] = fmaf(w0.y, v, acc[1]);+ acc[2] = fmaf(w0.z, v, acc[2]); acc[3] = fmaf(w0.w, v, acc[3]);+ acc[4] = fmaf(w1.x, v, acc[4]); acc[5] = fmaf(w1.y, v, acc[5]);+ acc[6] = fmaf(w1.z, v, acc[6]); acc[7] = fmaf(w1.w, v, acc[7]);+ acc[8] = fmaf(w2.x, v, acc[8]); acc[9] = fmaf(w2.y, v, acc[9]);+ acc[10] = fmaf(w2.z, v, acc[10]); acc[11] = fmaf(w2.w, v, acc[11]);+ };+ int c = 0;+ // four cells at a time with their V loads issued together (the loop was one dependent load chain per cell);+ // a group holding a masked cell (page -1, rare) leaves this loop and the scalar one below finishes the chunk.+ for (; c + 4 <= n_here; c += 4) {+ const long long r0 = srow[c], r1 = srow[c + 1], r2 = srow[c + 2], r3 = srow[c + 3];+ if ((r0 | r1 | r2 | r3) < 0) break;+ const float v0 = load_v1<KV_MODE>(p, r0, t), v1 = load_v1<KV_MODE>(p, r1, t);+ const float v2 = load_v1<KV_MODE>(p, r2, t), v3 = load_v1<KV_MODE>(p, r3, t);+ fold(c, v0);+ fold(c + 1, v1);+ fold(c + 2, v2);+ fold(c + 3, v3);+ }+ for (; c < n_here; ++c) {+ if (srow[c] < 0) continue; // masked above, weight 0+ fold(c, load_v1<KV_MODE>(p, srow[c], t));+ }+#pragma unroll+ for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];+}+#endif // STRATA_EXPERIMENTAL_SM60+__dpct_inline__ void attn_merge_kernel(const float *__restrict__ part_acc,const float *__restrict__ part_m,const float *__restrict__ part_l,@@ -296,6 +547,34 @@ __dpct_inline__ void attn_merge_kernel(const float *__restrict__ part_acc,attn[(size_t) h * HD + d] = L > 0.0f ? acc / L : 0.0f;}+#if defined(STRATA_EXPERIMENTAL_SM60)+// the current device is below sm_75 (per device: a layer split can mix cards); STRATA_ATTN_PRE75=0 turns PR #540's+// kernel off (A/B)+bool pre75_attn() {+ static const bool off = [] {+ const char* e = std::getenv("STRATA_ATTN_PRE75");+ return e != nullptr && e[0] == '0';+ }();+ static int cc[64] = {};+ int dev = 0;+ if (off) return false;+ if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }+ if (cc[dev] == 0) {+ int major = 0, minor = 0;+ if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess ||+ cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) {+ cudaGetLastError();+ return false;+ }+ cc[dev] = 10 * major + minor;+ }+ return cc[dev] < 75;+}+#define STRATA_ATTN_CHUNK(M) (pre75_attn() ? attn_chunk_kernel_pre75<M> : attn_chunk_kernel<M>)+#else+#define STRATA_ATTN_CHUNK(M) attn_chunk_kernel<M>+#endif+} // namespacevoid qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,@@ -318,6 +597,52 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3const dpct::dim3 grid((unsigned)n_chunks, (unsigned)s.n_head_kv,(unsigned)n_q);dpct::queue_ptr st = strata::q_of(stream);+ // S25: STRATA_ATTN_LANECELL=1 - the score phase one cell per thread (bit-identical scores, no shuffle reductions)+ static const bool lane_cell = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }();+#define STRATA_ATTN_LC(M) \+ { \+ auto exp_props = sycl::ext::oneapi::experimental::properties{ \+ sycl::ext::oneapi::experimental::use_root_sync}; \+ dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16}); \+ \+ st->submit([&](sycl::handler &cgh) { \+ auto q_ct0 = q; \+ QsaAttnPools pools_ct1 = pools; \+ auto ids_ct2 = ids; \+ auto steps_ct3 = steps; \+ auto s_n_head_kv_ct4 = (int)s.n_head_kv; \+ auto s_page_size_ct5 = (int)s.page_size; \+ auto scale_ct6 = scale; \+ auto part_acc_ct7 = part_acc; \+ auto part_m_ct8 = part_m; \+ auto part_l_ct9 = part_l; \+ auto n_chunks_ct10 = n_chunks; \+ auto cap_ct11 = (int)cap; \+ auto stride_ct12 = stride; \+ \+ cgh.parallel_for<dpct_kernel_name<class attn_chunk_kernel_6e87d5, \+ dpct_kernel_scalar<M>, \+ dpct_kernel_scalar<true>>>( \+ sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS), \+ sycl::range(1, 1, THREADS)), \+ exp_props, \+ [=](sycl::nd_item<3> item_ct1) \+ [[sycl::reqd_sub_group_size(32)]] { \+ attn_chunk_kernel<M, true>( \+ q_ct0, pools_ct1, ids_ct2, steps_ct3, \+ s_n_head_kv_ct4, s_page_size_ct5, scale_ct6, \+ part_acc_ct7, part_m_ct8, part_l_ct9, \+ n_chunks_ct10, cap_ct11, stride_ct12); \+ }); \+ }); \+ }+ if (lane_cell) {+ if (kv_mode == 3) { STRATA_ATTN_LC(3); }+ else if (kv_mode == 2) { STRATA_ATTN_LC(2); }+ else if (kv_mode == 1) { STRATA_ATTN_LC(1); }+ else { STRATA_ATTN_LC(0); }+ } else+#undef STRATA_ATTN_LCif (kv_mode == 3){auto exp_props = sycl::ext::oneapi::experimental::properties{@@ -386,7 +711,7 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- st->parallel_for<dpct_kernel_name<class attn_merge_kernel_2cdaf7>>(+ st->parallel_for<dpct_kernel_name<class attn_merge_kernel_338175>>(sycl::nd_range<3>(sycl::range(1, (unsigned)n_q, (unsigned)s.n_head) *sycl::range(1, 1, HD),@@ -499,7 +824,7 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- st->parallel_for<dpct_kernel_name<class attn_merge_kernel_4bb902>>(+ st->parallel_for<dpct_kernel_name<class attn_merge_kernel_c055e7>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)s.n_head) *sycl::range(1, 1, HD),sycl::range(1, 1, HD)),diff --git a/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp b/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cppindex 0744998e1..f4a6533be 100644--- a/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp+++ b/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp@@ -8,6 +8,7 @@#include <cstring>#include "strata/kernels/qsa_prompt_attn.hpp"#include "strata/kernels/qsa_prompt_attn_xmx.hpp"+#include "strata/kernels/gfx_arch.hpp"#include "strata/kernels/kv_q8.hpp"#include "strata/kernels/kv_q4.hpp"@@ -186,9 +187,9 @@ prompt_attn_kernel(const float *__restrict__ q, QsaAttnPools p,sycl::fmax(S.qmax[2], S.qmax[3]));int qe = 0;/*- DPCT1017: The sycl::frexp call is used instead of the frexpf call. These- two calls do not provide exactly the same functionality. Check the potential- precision and/or performance issues for the generated code.+ DPCT1017: The sycl::frexp call is used instead of the frexpf call.+ These two calls do not provide exactly the same functionality. Check the+ potential precision and/or performance issues for the generated code.*/if (qm > 0.0f) sycl::frexp(qm, sycl::address_space_cast<sycl::access::address_space::generic_space,@@ -784,9 +785,9 @@ prompt_attn_i8_kernel(const float *__restrict__ q, QsaAttnPools p,sycl::fmax(S.qmax[2], S.qmax[3]));int qe = 0;/*- DPCT1017: The sycl::frexp call is used instead of the frexpf call. These- two calls do not provide exactly the same functionality. Check the potential- precision and/or performance issues for the generated code.+ DPCT1017: The sycl::frexp call is used instead of the frexpf call.+ These two calls do not provide exactly the same functionality. Check the+ potential precision and/or performance issues for the generated code.*/if (qm > 0.0f) sycl::frexp(qm, sycl::address_space_cast<sycl::access::address_space::generic_space,@@ -1254,6 +1255,391 @@ catch (sycl::exception const &exc) {std::exit(1);}+// PR #600: compiled only into the experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON), the one build that runs on a+// Volta card; the ready-made engine has none of it (no extra kernels to load, the same code as before).+#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60)+// ---- sm_70 (Volta): v1's structure on mma.m8n8k4 ------------------------------------------------------------------+// Volta's tensor cores only have m8n8k4 (FP16 in, FP32 accumulate): per warp FOUR independent 8x8x4 products, one per+// quad-pair (QP q = lanes 4q..4q+3 and 4q+16..4q+19; thread j = (lane & 3) + 4 * (lane >> 4) within it). Layout, measured on+// a V100 (tools-free microtest, and equal to turbomind's SM70_MMA_884): the thread holds row j of A (k 0..3 as two+// registers) and column j of B (k 0..3); C register i is row (lane & 1) + 4 * (lane >> 4) + 2 * ((i >> 1) & 1),+// column (lane & 2) + 4 * (i >> 2) + (i & 1) of its QP's 8x8 tile.+// q.k: warp w owns dims [64w, 64w+64) = int8 scale group w; QP q takes cells 8q..8q+7 of the 32-cell chunk; 16 k-steps+// of 4 dims, two 8-row blocks (12 heads + 4 zero rows), q as hi + lo halves. The warp's partial (times the+// cells' K scale) goes to S.part[w]; the softmax adds the four groups in a fixed order (deterministic).+// p.v: warp w owns dims [64w, 64w+64) again; QP q takes the 16 dims 64w+16q.. (two n-tiles of 8); k = the 32 cells in+// steps of 4; p carries the V scale (as v1) and is split into hi + lo halves.+#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 && __CUDA_ARCH__ < 750+#define STRATA_PA_VOLTA 1+#else+#define STRATA_PA_VOLTA 0+#endif++__device__ __forceinline__ void mma884(float* c, uint32_t a0, uint32_t a1, uint32_t b0, uint32_t b1) {+#if STRATA_PA_VOLTA+ asm volatile("mma.sync.aligned.m8n8k4.row.col.f32.f16.f16.f32 {%0,%1,%2,%3,%4,%5,%6,%7}, {%8,%9}, {%10,%11}, "+ "{%0,%1,%2,%3,%4,%5,%6,%7};\n"+ : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]), "+f"(c[4]), "+f"(c[5]), "+f"(c[6]), "+f"(c[7])+ : "r"(a0), "r"(a1), "r"(b0), "r"(b1));+#else+ /* unreachable on SYCL: the launcher refuses this device */ // m8n8k4 is a Volta instruction; the host only launches this kernel on sm_70+#endif+}++template <int KV_MODE>+struct Smem70 {+ using KElem = typename std::conditional<KV_MODE == 0, __half, int8_t>::type;+ using VElem = typename std::conditional<KV_MODE == 1, int8_t, __half>::type;+ static constexpr int KROW = KV_MODE == 0 ? HD + 8 : HD + 16;+ static constexpr int VROW = KV_MODE == 1 ? HD + 16 : HD + 8;+ __half qh[16][QS];+ __half ql[16][QS];+ KElem k[CH][KROW];+ VElem v[CH][VROW];+ float ks[CH][4];+ float vs[CH][4];+ float part[4][16][CH + 4]; // q.k per dim group (scaled by the cell's K scale)+ float s[16][CH + 4]; // the chunk's probabilities+ float qmax[THREADS / 32];+ float alpha[16];+ float lsum[16];+ float mrow[16];+ long long row[CH];+};++template <int KV_MODE>+__global__ void __launch_bounds__(THREADS) prompt_attn_v70_kernel(const float* __restrict__ q, QsaAttnPools p,+ const int32_t* __restrict__ ids,+ const int32_t* __restrict__ steps, int n_kv_heads,+ int page_size, float scale_log2,+ float* __restrict__ attn, int cap) {+ extern __shared__ __align__(16) unsigned char smem_raw[];+ Smem70<KV_MODE>& S = *reinterpret_cast<Smem70<KV_MODE>*>(smem_raw);+ const int qi = blockIdx.x, kvh = blockIdx.y;+ const int n_head = n_kv_heads * G;+ q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;+ attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;+ ids += (size_t) qi * cap;+ const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);+ const int t = threadIdx.x, lane = t & 31, warp = t >> 5;+ const int qp = (lane >> 2) & 3, jj = (lane & 3) + 4 * (lane >> 4); // quad-pair, thread within it+ const int crow = (lane & 1) + 4 * (lane >> 4); // C row of register 0 (+2 per register pair)+ const int ccol = lane & 2; // C column of register 0 (+4 per half, +1 per reg)++ // q: 12 heads + 4 zero rows, scaled by a power of two that puts its largest value near 2^14 (exact, and the+ // lo halves stay out of FP16's subnormal range), then split into hi + lo halves+ float qm = 0.0f;+ for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i]));+#pragma unroll+ for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o));+ if (lane == 0) S.qmax[warp] = qm;+ __syncthreads();+ qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3]));+ int qe = 0;+ if (qm > 0.0f) frexpf(qm, &qe); // qm < 2^qe+ const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14);+ for (int i = t; i < 16 * HD; i += THREADS) {+ const int h = i / HD, d = i % HD;+ const float x = h < G ? q[(size_t) h * HD + d] * qup : 0.0f;+ const __half hi = __float2half_rn(x);+ S.qh[h][d] = hi;+ S.ql[h][d] = __float2half_rn(x - __half2float(hi));+ }+ if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; }++ float acc[2][2][8];+#pragma unroll+ for (int rb = 0; rb < 2; ++rb)+#pragma unroll+ for (int nt = 0; nt < 2; ++nt)+#pragma unroll+ for (int i = 0; i < 8; ++i) acc[rb][nt][i] = 0.0f;++ for (int c0 = 0; c0 < n; c0 += CH) {+ const int nh = min(CH, n - c0);+ if (t < CH) {+ long long r = -1;+ if (t < nh) {+ const int cell = ids[c0 + t];+ const long long page = (long long) p.page_table[cell / page_size];+ r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);+ }+ S.row[t] = r;+ }+ __syncthreads(); // rows ready; the previous chunk's p.v is done with k, v, s+ // gather the chunk's K and V rows (16-byte pieces; K8V4's V as q4_0 blocks dequantized to fp16)+ // and their scales+ {+ constexpr int KPIECES = HD * (int) sizeof(typename Smem<KV_MODE>::KElem) / 16; // per K row+ for (int i = t; i < CH * KPIECES; i += THREADS) {+ const int c = i / KPIECES, pc = i % KPIECES;+ const long long r = S.row[c];+ uint4 kx = make_uint4(0, 0, 0, 0);+ if (r >= 0) {+ if constexpr (KV_MODE == 0)+ kx = __ldg(reinterpret_cast<const uint4*>(p.k_pool + r * HD) + pc);+ else // modes 1 and 3: the K side is INT8+ kx = __ldg(reinterpret_cast<const uint4*>(p.k_q + r * HD) + pc);+ }+ *reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.k[c][0]) + pc * 16) = kx;+ }+ if constexpr (KV_MODE == 3) { // V: dequantize the row's q4_0 blocks straight into the fp16 V row+ constexpr int BLKS = HD / QK4_0;+ constexpr int BYTES = BLKS * (int) sizeof(block_q4_0);+ for (int i = t; i < CH * BLKS; i += THREADS) {+ const int c = i / BLKS, b = i % BLKS;+ const long long r = S.row[c];+#pragma unroll+ for (int j = 0; j < QK4_0; ++j) S.v[c][b * QK4_0 + j] = __half(0);+ if (r >= 0) {+ const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + r * BYTES) + b;+ const float d = __half2float(__ushort_as_half(blk->d));+#pragma unroll+ for (int j = 0; j < QK4_0 / 2; ++j) {+ S.v[c][b * QK4_0 + j] = __float2half_rn((float) ((int)(blk->qs[j] & 0x0F) - 8) * d);+ S.v[c][b * QK4_0 + j + QK4_0 / 2] =+ __float2half_rn((float) ((int)(blk->qs[j] >> 4) - 8) * d);+ }+ }+ }+ } else {+ constexpr int VPIECES = HD * (int) sizeof(typename Smem<KV_MODE>::VElem) / 16; // per V row+ for (int i = t; i < CH * VPIECES; i += THREADS) {+ const int c = i / VPIECES, pc = i % VPIECES;+ const long long r = S.row[c];+ uint4 vx = make_uint4(0, 0, 0, 0);+ if (r >= 0) {+ if constexpr (KV_MODE == 1)+ vx = __ldg(reinterpret_cast<const uint4*>(p.v_q + r * HD) + pc);+ else+ vx = __ldg(reinterpret_cast<const uint4*>(p.v_pool + r * HD) + pc);+ }+ *reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.v[c][0]) + pc * 16) = vx;+ }+ }+ for (int i = t; i < CH * 4; i += THREADS) {+ const int c = i / 4, g = i % 4;+ const long long r = S.row[c];+ float a = 0.0f, b = 0.0f;+ if (r >= 0) {+ if constexpr (KV_MODE == 1) {+ a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g]));+ b = __half2float(__ushort_as_half(p.v_scale[r * (HD / KV_Q8_GROUP) + g]));+ } else if constexpr (KV_MODE == 3) { // K as int8, V dequantized to fp16 (scale 1)+ a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g]));+ b = 1.0f;+ } else {+ a = b = 1.0f;+ }+ }+ S.ks[c][g] = a;+ S.vs[c][g] = b;+ }+ }+ __syncthreads();+ // scores: warp w = dim group w (64 dims), QP q = cells 8q..8q+7+ {+ float tg[2][8];+#pragma unroll+ for (int rb = 0; rb < 2; ++rb)+#pragma unroll+ for (int i = 0; i < 8; ++i) tg[rb][i] = 0.0f;+ const int cell_b = qp * 8 + jj;+#pragma unroll+ for (int ks = 0; ks < 16; ++ks) {+ const int d0 = warp * 64 + ks * 4;+ uint32_t b0, b1;+ if constexpr (KV_MODE != 0) { // modes 1 and 3: the K side is INT8 codes, exact in FP16+ const uint32_t raw = *reinterpret_cast<const uint32_t*>(&S.k[cell_b][d0]);+ b0 = i8x2_to_h2(raw & 0xffffu);+ b1 = i8x2_to_h2(raw >> 16);+ } else {+ const uint2 raw = *reinterpret_cast<const uint2*>(&S.k[cell_b][d0]);+ b0 = raw.x;+ b1 = raw.y;+ }+#pragma unroll+ for (int rb = 0; rb < 2; ++rb) {+ const uint2 ah = *reinterpret_cast<const uint2*>(&S.qh[rb * 8 + jj][d0]);+ const uint2 al = *reinterpret_cast<const uint2*>(&S.ql[rb * 8 + jj][d0]);+ mma884(tg[rb], ah.x, ah.y, b0, b1);+ mma884(tg[rb], al.x, al.y, b0, b1);+ }+ }+#pragma unroll+ for (int rb = 0; rb < 2; ++rb)+#pragma unroll+ for (int i = 0; i < 8; ++i) {+ const int row = rb * 8 + crow + 2 * ((i >> 1) & 1);+ const int cell = qp * 8 + ccol + 4 * (i >> 2) + (i & 1);+ S.part[warp][row][cell] = tg[rb][i] * S.ks[cell][warp];+ }+ }+ __syncthreads();+ // online softmax: row t/8, 4 cells per thread, 8 threads per row (lanes 8r..8r+7 of a warp)+ {+ constexpr int PER = CH / 8;+ const int r = t >> 3, sub = t & 7;+ float x[PER], mx = -INFINITY;+#pragma unroll+ for (int j = 0; j < PER; ++j) {+ const int c = sub * PER + j;+ const float sum4 = ((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c];+ x[j] = c < nh ? sum4 * qdown : -INFINITY;+ mx = fmaxf(mx, x[j]);+ }+#pragma unroll+ for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o));+ const float m_old = S.mrow[r];+ const float m_new = fmaxf(m_old, mx);+ float sum = 0.0f;+#pragma unroll+ for (int j = 0; j < PER; ++j) {+ const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new);+ S.s[r][sub * PER + j] = e;+ sum += e;+ }+#pragma unroll+ for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);+ __syncwarp();+ if (sub == 0) {+ const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new);+ S.alpha[r] = a;+ S.lsum[r] = fmaf(S.lsum[r], a, sum);+ S.mrow[r] = m_new;+ }+ }+ __syncthreads();+ __syncthreads();+ // p.v: warp w owns dims [64w, 64w+64) (int8 scale group w), QP q its 16 dims 64w+16q..; the V scale is folded+ // into p relative to the chunk's largest, times 2^14 (as v1)+ {+ float vmax = 0.0f;+#pragma unroll+ for (int c = lane; c < CH; c += 32) vmax = fmaxf(vmax, S.vs[c][warp]);+#pragma unroll+ for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o));+ const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f);+ float tmp[2][2][8];+#pragma unroll+ for (int rb = 0; rb < 2; ++rb)+#pragma unroll+ for (int nt = 0; nt < 2; ++nt)+#pragma unroll+ for (int i = 0; i < 8; ++i) tmp[rb][nt][i] = 0.0f;+#pragma unroll+ for (int ks = 0; ks < CH / 4; ++ks) {+ const int c0 = ks * 4;+ float w[4];+#pragma unroll+ for (int e = 0; e < 4; ++e) w[e] = S.vs[c0 + e][warp] * vup;+ uint2 ah[2], al[2];+#pragma unroll+ for (int rb = 0; rb < 2; ++rb) {+ const float4 pv = *reinterpret_cast<const float4*>(&S.s[rb * 8 + jj][c0]);+ const float p0 = pv.x * w[0], p1 = pv.y * w[1], p2 = pv.z * w[2], p3 = pv.w * w[3];+ ah[rb].x = pack_h2(p0, p1);+ ah[rb].y = pack_h2(p2, p3);+ const float2 f01 = __half22float2(*reinterpret_cast<const __half2*>(&ah[rb].x));+ const float2 f23 = __half22float2(*reinterpret_cast<const __half2*>(&ah[rb].y));+ al[rb].x = pack_h2(p0 - f01.x, p1 - f01.y);+ al[rb].y = pack_h2(p2 - f23.x, p3 - f23.y);+ }+#pragma unroll+ for (int nt = 0; nt < 2; ++nt) {+ const int d = warp * 64 + qp * 16 + nt * 8 + jj;+ uint32_t b0, b1;+ if constexpr (KV_MODE == 1) {+ const uint32_t x0 = (uint8_t) S.v[c0][d] | ((uint32_t) (uint8_t) S.v[c0 + 1][d] << 8);+ const uint32_t x1 = (uint8_t) S.v[c0 + 2][d] | ((uint32_t) (uint8_t) S.v[c0 + 3][d] << 8);+ b0 = i8x2_to_h2(x0);+ b1 = i8x2_to_h2(x1);+ } else {+ const __half2 h0 = __halves2half2(S.v[c0][d], S.v[c0 + 1][d]);+ const __half2 h1 = __halves2half2(S.v[c0 + 2][d], S.v[c0 + 3][d]);+ b0 = *reinterpret_cast<const uint32_t*>(&h0);+ b1 = *reinterpret_cast<const uint32_t*>(&h1);+ }+#pragma unroll+ for (int rb = 0; rb < 2; ++rb) {+ mma884(tmp[rb][nt], ah[rb].x, ah[rb].y, b0, b1);+ mma884(tmp[rb][nt], al[rb].x, al[rb].y, b0, b1);+ }+ }+ }+#pragma unroll+ for (int rb = 0; rb < 2; ++rb) {+ float a_[2];+ a_[0] = S.alpha[rb * 8 + crow];+ a_[1] = S.alpha[rb * 8 + crow + 2];+#pragma unroll+ for (int nt = 0; nt < 2; ++nt)+#pragma unroll+ for (int i = 0; i < 8; ++i)+ acc[rb][nt][i] = fmaf(acc[rb][nt][i], a_[(i >> 1) & 1], tmp[rb][nt][i] * vdown);+ }+ }+ }+ __syncthreads();+#pragma unroll+ for (int rb = 0; rb < 2; ++rb)+#pragma unroll+ for (int h = 0; h < 2; ++h) {+ const int row = rb * 8 + crow + 2 * h;+ if (row >= G) continue;+ const float l = S.lsum[row];+ const float inv = l > 0.0f ? 1.0f / l : 0.0f;+#pragma unroll+ for (int nt = 0; nt < 2; ++nt)+#pragma unroll+ for (int hh = 0; hh < 2; ++hh) {+ const int i = hh * 4 + h * 2; // registers i, i+1: row h, columns ccol + 4 * hh + {0, 1}+ const int d = warp * 64 + qp * 16 + nt * 8 + ccol + 4 * hh;+ *reinterpret_cast<float2*>(attn + (size_t) row * HD + d) =+ make_float2(acc[rb][nt][i] * inv, acc[rb][nt][i + 1] * inv);+ }+ }+}++template <int KV_MODE>+bool launch70(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,+ const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) {+ static bool attr[64] = {};+ int dev = 0;+ cudaGetDevice(&dev);+ const int bytes = (int) sizeof(Smem70<KV_MODE>);+ if (dev < 0 || dev >= 64) return false;+ if (!attr[dev]) {+ if (cudaFuncSetAttribute(prompt_attn_v70_kernel<KV_MODE>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=+ cudaSuccess) {+ cudaGetLastError();+ return false;+ }+ attr[dev] = true;+ }+ const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);+ for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {+ const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;+ prompt_attn_v70_kernel<KV_MODE><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(+ q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,+ (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);+ }+ const cudaError_t e = cudaGetLastError();+ if (e != cudaSuccess) {+ std::fprintf(stderr, "qsa_prompt_attn_batch (sm_70): %s\n", cudaGetErrorString(e));+ std::exit(1);+ }+ return true;+}+#else // AMD, or a build without STRATA_EXPERIMENTAL_SM60: no m8n8k4 kernel (the caller keeps the old one)+template <int KV_MODE>+bool launch70(const float *, const QsaAttnPools &, const int32_t *,+ const int32_t *, int64_t, const QsaShapes &, float *, int64_t,+ dpct::queue_ptr) {+ return false;+}+#endif // !__HIPCC__ && STRATA_EXPERIMENTAL_SM60+#if defined(__HIPCC__)// ---- S6: the int8-KV prompt attention on RDNA4 matrix cores (opt-in: STRATA_HIP_WMMA=1, gfx12 only). The design of// the v2 kernel above with gfx12's v_wmma_f32_16x16x16_f16 (wave32) in place of m16n8k16: wave w owns dims@@ -1262,12 +1648,30 @@ catch (sycl::exception const &exc) {// FP32-level accuracy, deterministic, but not bitwise equal to qsa_decode_attn_batch (another summation order).// Fragment layout (16x16x16, wave32, checked on gfx1201): A lane l holds A[l % 16][(l / 16) * 8 + i], B lane l holds// B[(l / 16) * 8 + i][l % 16], C/D lane l holds D[(l / 16) * 8 + i][l % 16], i = 0..7.+// gfx11 (RDNA3 / RDNA3.5: gfx110x, gfx115x) has the same instruction with another layout: A lane l holds all 16 k of+// row l % 16 (lanes 16..31 repeat lanes 0..15), B lane l all 16 k of column l % 16, and C/D lane l holds+// D[2 * i + l / 16][l % 16]. PA_KL is the k values per lane (8 or 16), PA_KOFF(half) the first one, PA_ROW the C row.#if defined(__gfx1200__) || defined(__gfx1201__)#define STRATA_PA_WMMA 1+#define STRATA_PA_GFX11 0+#elif defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || \+ defined(__gfx1151__)+#define STRATA_PA_WMMA 1+#define STRATA_PA_GFX11 1#else#define STRATA_PA_WMMA 0+#define STRATA_PA_GFX11 0#endif-typedef _Float16 wh8 __attribute__((ext_vector_type(8)));+#if STRATA_PA_GFX11+constexpr int PA_KL = 16;+#define PA_KOFF(half) 0+#define PA_ROW(i, half) (2 * (i) + (half))+#else+constexpr int PA_KL = 8;+#define PA_KOFF(half) ((half) * 8)+#define PA_ROW(i, half) ((half) * 8 + (i))+#endif+typedef _Float16 wh8 __attribute__((ext_vector_type(PA_KL)));typedef float wf8 __attribute__((ext_vector_type(8)));constexpr int WCH = 32; // cells per chunk (two 16-cell tiles)constexpr int WVS = 80; // staged V row stride in bytes (64 codes, 16-byte aligned, banks spread)@@ -1284,7 +1688,9 @@ struct alignas(16) SmemW {};__device__ __forceinline__ wf8 wmma_f16(wh8 a, wh8 b, wf8 c) {-#if STRATA_PA_WMMA+#if STRATA_PA_WMMA && STRATA_PA_GFX11+ return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c);+#elif STRATA_PA_WMMAreturn __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c);#else__builtin_trap();@@ -1292,16 +1698,17 @@ __device__ __forceinline__ wf8 wmma_f16(wh8 a, wh8 b, wf8 c) {#endif}-__device__ __forceinline__ wh8 i8x8_to_h8(uint2 x) { // exact: |code| <= 128+__device__ __forceinline__ wh8 i8_to_h(const uint32_t* x) { // PA_KL codes, exact: |code| <= 128wh8 h;#pragma unroll- for (int i = 0; i < 4; ++i) {- h[i] = (_Float16) (int) (int8_t) (x.x >> (8 * i));- h[4 + i] = (_Float16) (int) (int8_t) (x.y >> (8 * i));- }+ for (int i = 0; i < PA_KL; ++i) h[i] = (_Float16) (int) (int8_t) (x[i / 4] >> (8 * (i % 4)));return h;}+// SPLIT = true (default): q and p carried as FP16 hi + lo pairs (two WMMAs each: FP32-level). S23 (opt-in+// STRATA_PA_FAST=1): SPLIT = false, one FP16 image each - half the matrix work, rounding-level (FP16 attention as the+// usual flash-attention kernels), quality-gated+template <bool SPLIT>__global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* __restrict__ q, QsaAttnPools p,const int32_t* __restrict__ ids,const int32_t* __restrict__ steps, int n_kv_heads,@@ -1330,21 +1737,24 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float*int qe = 0;if (qm > 0.0f) frexpf(qm, &qe);const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14);- // q A fragments of this wave's 64 dims: row = col (heads 12..15 zero), k = dim0 + kk*16 + half*8 + i+ // q A fragments of this wave's 64 dims: row = col (heads 12..15 zero), k = dim0 + kk*16 + PA_KOFF(half) + iwh8 qh[4], ql[4];#pragma unrollfor (int kk = 0; kk < 4; ++kk) {- float x[8];+ float x[PA_KL];if (col < G) {- const float4* src = reinterpret_cast<const float4*>(q + (size_t) col * HD + dim0 + kk * 16 + half * 8);- const float4 a = src[0], b = src[1];- x[0] = a.x; x[1] = a.y; x[2] = a.z; x[3] = a.w; x[4] = b.x; x[5] = b.y; x[6] = b.z; x[7] = b.w;+ const float4* src = reinterpret_cast<const float4*>(q + (size_t) col * HD + dim0 + kk * 16 + PA_KOFF(half));+#pragma unroll+ for (int j = 0; j < PA_KL / 4; ++j) {+ const float4 a = src[j];+ x[4 * j] = a.x; x[4 * j + 1] = a.y; x[4 * j + 2] = a.z; x[4 * j + 3] = a.w;+ }} else {#pragma unroll- for (int i = 0; i < 8; ++i) x[i] = 0.0f;+ for (int i = 0; i < PA_KL; ++i) x[i] = 0.0f;}#pragma unroll- for (int i = 0; i < 8; ++i) {+ for (int i = 0; i < PA_KL; ++i) {const float v = x[i] * qup;const _Float16 hi = (_Float16) v;qh[kk][i] = hi;@@ -1391,14 +1801,23 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float*if (rr >= 0) ksc = __half2float(__ushort_as_half(__ldg(p.k_scale + rr * (HD / KV_Q8_GROUP) + warp)));#pragma unrollfor (int kk = 0; kk < 4; ++kk) {- uint2 kx = make_uint2(0, 0);- if (rr >= 0) kx = __ldg(reinterpret_cast<const uint2*>(p.k_q + rr * HD + dim0 + kk * 16 + half * 8));- const wh8 b = i8x8_to_h8(kx);+ uint32_t kx[PA_KL / 4] = {};+ if (rr >= 0) {+ const uint32_t* src = reinterpret_cast<const uint32_t*>(p.k_q + rr * HD + dim0 + kk * 16 + PA_KOFF(half));+#if STRATA_PA_GFX11+ const uint4 v = __ldg(reinterpret_cast<const uint4*>(src));+ kx[0] = v.x; kx[1] = v.y; kx[2] = v.z; kx[3] = v.w;+#else+ const uint2 v = __ldg(reinterpret_cast<const uint2*>(src));+ kx[0] = v.x; kx[1] = v.y;+#endif+ }+ const wh8 b = i8_to_h(kx);s = wmma_f16(qh[kk], b, s);- s = wmma_f16(ql[kk], b, s);+ if constexpr (SPLIT) s = wmma_f16(ql[kk], b, s);}#pragma unroll- for (int i = 0; i < 8; ++i) S.part[warp][half * 8 + i][nt * 16 + col] = s[i] * ksc;+ for (int i = 0; i < 8; ++i) S.part[warp][PA_ROW(i, half)][nt * 16 + col] = s[i] * ksc;}__syncthreads();// online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread@@ -1445,10 +1864,10 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float*for (int j = 0; j < 4; ++j) tmp[j] = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};#pragma unrollfor (int ks = 0; ks < 2; ++ks) {- const int cb = ks * 16 + half * 8; // this lane's 8 cells+ const int cb = ks * 16 + PA_KOFF(half); // this lane's PA_KL cellswh8 ah, al;#pragma unroll- for (int i = 0; i < 8; ++i) {+ for (int i = 0; i < PA_KL; ++i) {const float pv = S.p[col][cb + i] * (S.vs[warp][cb + i] * vup);const _Float16 hi = (_Float16) pv;ah[i] = hi;@@ -1459,14 +1878,14 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float*const int d = j * 16 + col;wh8 b;#pragma unroll- for (int i = 0; i < 8; ++i) b[i] = (_Float16) (int) (int8_t) S.v[warp][cb + i][d];+ for (int i = 0; i < PA_KL; ++i) b[i] = (_Float16) (int) (int8_t) S.v[warp][cb + i][d];tmp[j] = wmma_f16(ah, b, tmp[j]);- tmp[j] = wmma_f16(al, b, tmp[j]);+ if constexpr (SPLIT) tmp[j] = wmma_f16(al, b, tmp[j]);}}float a[8];#pragma unroll- for (int i = 0; i < 8; ++i) a[i] = S.alpha[half * 8 + i];+ for (int i = 0; i < 8; ++i) a[i] = S.alpha[PA_ROW(i, half)];#pragma unrollfor (int j = 0; j < 4; ++j)#pragma unroll@@ -1478,14 +1897,14 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float*float inv[8];#pragma unrollfor (int i = 0; i < 8; ++i) {- const float l = S.lsum[half * 8 + i];+ const float l = S.lsum[PA_ROW(i, half)];inv[i] = l > 0.0f ? 1.0f / l : 0.0f;}#pragma unrollfor (int j = 0; j < 4; ++j)#pragma unrollfor (int i = 0; i < 8; ++i) {- const int row = half * 8 + i;+ const int row = PA_ROW(i, half);if (row < G) attn[(size_t) row * HD + dim0 + j * 16 + col] = acc[j][i] * inv[i];}#else@@ -1493,20 +1912,22 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float*#endif}-// gfx12 (RDNA4) only, and only on request: the output differs from the default kernel's in its last bits+// gfx12 (RDNA4) and gfx11 (RDNA3 / RDNA3.5), only on request: the output differs from the default kernel's in its+// last bitsbool hip_wmma_usable() {static const bool want = [] {const char* e = std::getenv("STRATA_HIP_WMMA");return e != nullptr && e[0] == '1';}();if (!want) return false;- static int arch[64] = {}; // 0 unknown, 1 gfx12, 2 other+ static int arch[64] = {}; // 0 unknown, 1 gfx11 / gfx12, 2 otherint dev = 0;if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= 64) { (void) hipGetLastError(); return false; }if (arch[dev] == 0) {hipDeviceProp_t prop{};if (hipGetDeviceProperties(&prop, dev) != hipSuccess) { (void) hipGetLastError(); return false; }- arch[dev] = std::strncmp(prop.gcnArchName, "gfx12", 5) == 0 ? 1 : 2;+ arch[dev] = std::strncmp(prop.gcnArchName, "gfx12", 5) == 0 || strata::kernels::gfx_arch_is_gfx11_wmma(prop.gcnArchName)+ ? 1 : 2;static bool told = false;if (!told) {told = true;@@ -1522,9 +1943,16 @@ bool launch_wmma(const float* q, const QsaAttnPools& pools, const int32_t* ids,const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;- prompt_attn_wmma_kernel<<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, 0, st>>>(- q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,- (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);+ static const bool fast = [] { const char* e = std::getenv("STRATA_PA_FAST"); return e != nullptr && e[0] == '1'; }();+ static const int64_t min_t = [] { const char* e = std::getenv("STRATA_PF_SWITCH_MIN_T"); return e ? (int64_t) std::atoll(e) : (int64_t) 0; }();+ if (fast && n_q >= min_t)+ prompt_attn_wmma_kernel<false><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, 0, st>>>(+ q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,+ (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);+ else+ prompt_attn_wmma_kernel<true><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, 0, st>>>(+ q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,+ (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);}const cudaError_t e = cudaGetLastError();if (e != cudaSuccess) {@@ -1540,11 +1968,14 @@ bool launch_wmma(const float* q, const QsaAttnPools& pools, const int32_t* ids,bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, void* stream) {if (n_q <= 0) return true;- bool turing = false; // per call, from the CURRENT device (a layer split can mix Turing with newer cards)+ bool volta = false, turing = false; // per call, from the CURRENT device (a layer split can mix Turing with newer cards){ // sm_75 or newer: the MMA above compiles for both. sm_80+ runs the cp.async kernel (launch_i8); Turing has// no cp.async, so it runs the v1 kernel (launch<1>, same accuracy, another summation order). An older card// keeps the old kernel.// #371: the compute capability with its minor - sm_70 (V100) has no m16n8k8 (the kernels trap below sm_75)+#if defined(STRATA_HIP_GFX906)+ return false; // gfx906: the tensor-core and WMMA kernels are not for it; the FP32 kernel runs+#endifstatic int cc[64] = {};int dev = 0;/*@@ -1581,7 +2012,7 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3#if defined(__HIPCC__)// the tensor-core kernels are compiled out on AMD (its major version is not a CUDA sm); RDNA4 has its own int8-KV// matrix-core kernel, opt-in (STRATA_HIP_WMMA=1); everything else keeps the old kernel- (void) turing;+ (void) turing; (void) volta;if (pools.k_q != nullptr && pools.v_q != nullptr && pools.k_scale != nullptr && pools.v_scale != nullptr &&pools.k_q4 == nullptr && pools.v_q4 == nullptr && s.head_dim == HD && s.n_head == (int64_t) G * s.n_head_kv &&cap > 0 && ids && steps && pools.page_table && hip_wmma_usable())@@ -1602,6 +2033,7 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3}if (pools.k_q != nullptr && pools.v_q4 != nullptr) { // hybrid K8V4: int8 K + dequantized-q4 Vif (!pools.k_scale) return false;+ if (volta) return launch70<3>(q, pools, ids, steps, cap, s, attn, n_q, st);return launch<3>(q, pools, ids, steps, cap, s, attn, n_q, st);}if (pools.k_q != nullptr) {@@ -1610,10 +2042,12 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3// for how far the model amplifies an FP32-level change. Turing always takes it: v2's cp.async does not// exist before sm_80.static const bool v1 = std::getenv("STRATA_PROMPT_ATTN_V1") != nullptr;+ if (volta) return launch70<1>(q, pools, ids, steps, cap, s, attn, n_q, st);if (v1 || turing) return launch<1>(q, pools, ids, steps, cap, s, attn, n_q, st);return launch_i8(q, pools, ids, steps, cap, s, attn, n_q, st);}if (!pools.k_pool || !pools.v_pool) return false;+ if (volta) return launch70<0>(q, pools, ids, steps, cap, s, attn, n_q, st);return launch<0>(q, pools, ids, steps, cap, s, attn, n_q, st);}diff --git a/sycl/src/kernels/cuda/qsa_select.dp.cpp b/sycl/src/kernels/cuda/qsa_select.dp.cppindex a4ed9bf8d..481963bfe 100644--- a/sycl/src/kernels/cuda/qsa_select.dp.cpp+++ b/sycl/src/kernels/cuda/qsa_select.dp.cpp@@ -7,6 +7,7 @@#include <cstdlib>#include <cstring>#include "strata/kernels/qsa_select.hpp"+#include "strata/kernels/gfx_arch.hpp"#include <cfloat>#include <cstdio>@@ -432,14 +433,32 @@ __dpct_inline__ void block_scores_tc_kernel(// a lane ends up with 8 consecutive blocks of ONE query, written as one run. No LDS for keys: a lane reads its// 32-byte slice of the key row from global (the 16 query tiles of a launch re-read them from L2); the queries are// split once per CTA into LDS.+// gfx11 (RDNA3 / RDNA3.5) has the same instruction with another fragment layout: a lane holds all 16 k of its row+// (A) or column (B) - lanes 16..31 repeat lanes 0..15 - and D[2i + l/16][l%16]; SEL_KL is the k per lane, SEL_KOFF(g)+// the first, SEL_ROW(i, g) the D row of element i. Same products, same order per element as on gfx12.#if defined(__gfx1200__) || defined(__gfx1201__)#define STRATA_SEL_GFX12 1+#define STRATA_SEL_GFX11 0+#elif defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || \+ defined(__gfx1151__)+#define STRATA_SEL_GFX12 0+#define STRATA_SEL_GFX11 1#else#define STRATA_SEL_GFX12 0+#define STRATA_SEL_GFX11 0+#endif+#if STRATA_SEL_GFX11+constexpr int SEL_KL = 16;+#define SEL_KOFF(g) 0+#define SEL_ROW(i, g) (2 * (i) + (g))+#else+constexpr int SEL_KL = 8;+#define SEL_KOFF(g) ((g) * 8)+#define SEL_ROW(i, g) ((g) * 8 + (i))#endif-typedef short sel_s8 __attribute__((ext_vector_type(8)));+typedef short sel_s8 __attribute__((ext_vector_type(SEL_KL)));typedef float sel_f8 __attribute__((ext_vector_type(8)));-typedef uint32_t sel_u4 __attribute__((ext_vector_type(4)));+typedef uint32_t sel_u4 __attribute__((ext_vector_type(SEL_KL / 2)));constexpr int WQT = 16; // queries per CTA (the N of one WMMA)constexpr int WITER = 4; // key tiles per warp (the CTA covers 4 warps * WITER * 16 blocks)constexpr int WQS = IDX_DIM + 8; // bf16 elements per LDS row: 272 bytes, conflict-free 16-byte reads@@ -447,6 +466,8 @@ constexpr int WQS = IDX_DIM + 8; // bf16 elements per LDS row: 272 byt__device__ __forceinline__ sel_f8 wmma_bf16(const sel_s8& a, const sel_s8& b, const sel_f8& c) {#if STRATA_SEL_GFX12return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c);+#elif STRATA_SEL_GFX11+ return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c);#else/* unreachable on SYCL: the launcher refuses this device */return c;@@ -460,7 +481,7 @@ __device__ __forceinline__ void split3(float x, uint32_t& hi, uint32_t& mid, uinlo = sycl::bit_cast<uint32_t>(r1 - __uint_as_float(mid)) & 0xffff0000u; // exact: at most 8 significant bits left}__device__ __forceinline__ uint32_t pack_bf16x2(uint32_t a, uint32_t b) { // low half = a's bf16, high half = b's-#if STRATA_SEL_GFX12+#if STRATA_SEL_GFX12 || STRATA_SEL_GFX11return __builtin_amdgcn_perm(b, a, 0x07060302u);#elsereturn (a >> 16) | (b & 0xffff0000u);@@ -501,7 +522,7 @@ __global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __rif (b0 >= reach || b0 >= hi_nbid) break; // warp-uniform; later tiles start higherconst int64_t row = b0 + l16;const bool rv = row < hi_nbid && row < max_blocks;- const float* kp = pooled + (rv ? row : 0) * IDX_DIM + g * 8;+ const float* kp = pooled + (rv ? row : 0) * IDX_DIM + SEL_KOFF(g);// acc: the hi*hi products; cor: the five smaller ones (<= 2^-8 of it). Kept apart and added once at the end: a// correction summed into the big accumulator is rounded to ITS ulp at every one of the 48 steps (measured: 8e-7// of the score scale; apart, near the warp kernel's)@@ -510,18 +531,19 @@ __global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __rfor (int h = 0; h < IDX_HEADS; ++h) acc[h] = cor[h] = sel_f8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};#pragma unroll 2for (int kk = 0; kk < IDX_DIM / 16; ++kk) {- float4 k0 = make_float4(0.f, 0.f, 0.f, 0.f), k1 = k0;- if (rv) {- k0 = *reinterpret_cast<const float4*>(kp + kk * 16);- k1 = *reinterpret_cast<const float4*>(kp + kk * 16 + 4);+ float x[SEL_KL];+#pragma unroll+ for (int j = 0; j < SEL_KL / 4; ++j) {+ float4 kv = make_float4(0.f, 0.f, 0.f, 0.f);+ if (rv) kv = *reinterpret_cast<const float4*>(kp + kk * 16 + 4 * j);+ x[4 * j] = kv.x; x[4 * j + 1] = kv.y; x[4 * j + 2] = kv.z; x[4 * j + 3] = kv.w;}- const float x[8] = {k0.x, k0.y, k0.z, k0.w, k1.x, k1.y, k1.z, k1.w};- uint32_t hb[8], mb[8], lb[8];+ uint32_t hb[SEL_KL], mb[SEL_KL], lb[SEL_KL];#pragma unroll- for (int j = 0; j < 8; ++j) split3(x[j], hb[j], mb[j], lb[j]);+ for (int j = 0; j < SEL_KL; ++j) split3(x[j], hb[j], mb[j], lb[j]);sel_u4 ah, am, al;#pragma unroll- for (int j = 0; j < 4; ++j) {+ for (int j = 0; j < SEL_KL / 2; ++j) {ah[j] = pack_bf16x2(hb[2 * j], hb[2 * j + 1]);am[j] = pack_bf16x2(mb[2 * j], mb[2 * j + 1]);al[j] = pack_bf16x2(lb[2 * j], lb[2 * j + 1]);@@ -530,9 +552,9 @@ __global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __rAl = __builtin_bit_cast(sel_s8, al);#pragma unrollfor (int h = 0; h < IDX_HEADS; ++h) {- const sel_s8 Bh = *reinterpret_cast<const sel_s8*>(&sq[0][h][l16][kk * 16 + g * 8]);- const sel_s8 Bm = *reinterpret_cast<const sel_s8*>(&sq[1][h][l16][kk * 16 + g * 8]);- const sel_s8 Bl = *reinterpret_cast<const sel_s8*>(&sq[2][h][l16][kk * 16 + g * 8]);+ const sel_s8 Bh = *reinterpret_cast<const sel_s8*>(&sq[0][h][l16][kk * 16 + SEL_KOFF(g)]);+ const sel_s8 Bm = *reinterpret_cast<const sel_s8*>(&sq[1][h][l16][kk * 16 + SEL_KOFF(g)]);+ const sel_s8 Bl = *reinterpret_cast<const sel_s8*>(&sq[2][h][l16][kk * 16 + SEL_KOFF(g)]);cor[h] = wmma_bf16(Al, Bh, cor[h]);cor[h] = wmma_bf16(Ah, Bl, cor[h]);cor[h] = wmma_bf16(Am, Bm, cor[h]);@@ -541,11 +563,11 @@ __global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __racc[h] = wmma_bf16(Ah, Bh, acc[h]);}}- // relu per head, heads added in order (as the warp kernel); this lane: query qi, blocks b0 + 8g .. 8g+7+ // relu per head, heads added in order (as the warp kernel); this lane: query qi, blocks b0 + SEL_ROW(i, g)if (qi < nq) {#pragma unrollfor (int i = 0; i < 8; ++i) {- const int64_t b = b0 + g * 8 + i;+ const int64_t b = b0 + SEL_ROW(i, g);if (b >= nb_q || b >= max_blocks) continue;float score = 0.0f;#pragma unroll@@ -559,7 +581,7 @@ __global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __r}}-// the gfx12 kernel needs gfx1200/gfx1201 code objects and a gfx12 device (gfx1100 has WMMA too, with another layout)+// the WMMA kernel needs gfx12 (gfx1200/gfx1201) or gfx11 (gfx110x/gfx115x: the other fragment layout) code objectsbool sel_gfx12_device() {static int ok[64] = {}; // per device: 0 unknown, 1 yes, 2 noint dev = 0;@@ -567,7 +589,8 @@ bool sel_gfx12_device() {if (ok[dev] == 0) {cudaDeviceProp prop;ok[dev] = (cudaGetDeviceProperties(&prop, dev) == cudaSuccess &&- (std::strncmp(prop.gcnArchName, "gfx1200", 7) == 0 || std::strncmp(prop.gcnArchName, "gfx1201", 7) == 0))+ (std::strncmp(prop.gcnArchName, "gfx1200", 7) == 0 || std::strncmp(prop.gcnArchName, "gfx1201", 7) == 0 ||+ strata::kernels::gfx_arch_is_gfx11_wmma(prop.gcnArchName)))? 1 : 2;cudaGetLastError();}@@ -842,6 +865,248 @@ auto &hist =}}+#if !defined(__HIPCC__)+// ---- a query with more blocks than the register kernel holds (contexts past 4 * 1024 * TK_PER cells): the register+// kernel's threads, per-warp histograms and warp scans, with each key read from memory again on every pass. A+// histogram has no order, so on the four radix passes thread t reads blocks t, t + 1024, ...: a warp reads 32+// neighbours at a time. The cells are emitted ascending in the order (warp, row, lane): warp w holds the `per` rows+// of 32 consecutive blocks from block w * 32 * per. block_topk_kernel's selection rule (radix threshold, ties to the+// lowest index): identical ids.+/*+DPCT1110: The total declared local variable size in device function+block_topk_wide_kernel exceeds 128 bytes and may cause high register pressure.+Consult with your hardware vendor to find the total register size available and+adjust the code, or use smaller sub-group size to avoid high register pressure.+*/+__dpct_inline__ void block_topk_wide_kernel(const float *__restrict__ scores,+ const int32_t *__restrict__ steps,+ int64_t max_blocks, int64_t cap,+ int32_t *__restrict__ ids) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+auto &hist =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<int[TK_T / 32][256]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &s_gt =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<int[TK_T / 32]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &s_eq =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<int[TK_T / 32]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &s_digit = *sycl::ext::oneapi::group_local_memory_for_overwrite<int>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &s_above = *sycl::ext::oneapi::group_local_memory_for_overwrite<int>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const int64_t qi = item_ct1.get_group(2);+ const int32_t* st = steps + qi * kStepCount;+ const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];+ int32_t* out = ids + qi * cap;+ const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;+ if (n_kv <= width) {+#pragma unroll+ for (int64_t j = t; j < n_kv; j += TK_T) out[j] = (int32_t)j;+ return;+ }+ const float* sc = scores + qi * max_blocks;+ const int64_t nb = n_bid + 1;+ const int64_t per = (nb + TK_T - 1) / TK_T; // rows of 32 blocks per warp+ auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); };+ uint32_t prefix = 0;+ int above = 0;+ for (int shift = 24; shift >= 0; shift -= 8) {+#pragma unroll+ for (int i = lane; i < 256; i += 32) hist[warp][i] = 0;+ sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());+ const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8));+ for (int64_t b = t; b < nb; b += TK_T) {+ const int w = weight(b);+ if (w == 0) continue;+ const uint32_t k = order_key(sc[b]);+ if ((k & hi_mask) == (prefix & hi_mask)) dpct::atomic_fetch_add<+ sycl::access::address_space::generic_space>(+ &hist[warp][(k >> shift) & 255], w);+ }+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ if (t < 256) { // fold the warps' histograms into warp 0's+ int sum = 0;+#pragma unroll+ for (int w2 = 0; w2 < TK_T / 32; ++w2) sum += hist[w2][t];+ hist[0][t] = sum;+ }+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ if (t == 0) {+ int cum = above, d = 255;+#pragma unroll+ for (; d > 0; --d) {+ if (cum + hist[0][d] >= width) break;+ cum += hist[0][d];+ }+ s_digit = d;+ s_above = cum;+ }+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ prefix |= (uint32_t) s_digit << shift;+ above = s_above;+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ }+ const uint32_t thr = prefix;+ const int eq_budget = (int) (width - above); // cells equal to thr that fit, lowest index first+ const int64_t w0 = (int64_t) warp * 32 * per;+ int gt = 0, eq = 0;+ for (int64_t b = w0 + lane; b < nb && b < w0 + 32 * per; b += 32) {+ const int w = weight(b);+ if (w == 0) continue;+ const uint32_t k = order_key(sc[b]);+ if (k > thr) gt += w;+ else if (k == thr) eq += w;+ }+#pragma unroll+ for (int o = 16; o > 0; o >>= 1) {+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ gt += dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), gt,+ o);+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ eq += dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), eq,+ o);+ }+ if (lane == 0) { s_gt[warp] = gt; s_eq[warp] = eq; }+ /*+ 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.+ */+ item_ct1.barrier();+ if (t == 0) { // per warp: the selected cells and the tied cells before it+ int eb = 0, sb = 0;+ for (int w2 = 0; w2 < TK_T / 32; ++w2) {+ const int g2 = s_gt[w2], e2 = s_eq[w2];+ const int take = eq_budget - eb < 0 ? 0 : (eq_budget - eb > e2 ? e2 : eq_budget - eb);+ s_gt[w2] = sb;+ s_eq[w2] = eb;+ sb += g2 + take;+ eb += e2;+ }+ }+ /*+ 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.+ */+ item_ct1.barrier();+ int run_sel = s_gt[warp], run_eq = s_eq[warp];+ for (int64_t r0 = w0; r0 < nb && r0 < w0 + 32 * per; r0 += 32) {+ const int64_t b = r0 + lane;+ const int w = b < nb ? weight(b) : 0;+ const uint32_t k = w ? order_key(sc[b]) : 0u;+ const int my_gt = (w && k > thr) ? w : 0, my_eq = (w && k == thr) ? w : 0;+ if (sycl::reduce_over_group(+ sycl::ext::oneapi::this_work_item::get_sub_group(),+ (0xffffffffu &+ (0x1 << sycl::ext::oneapi::this_work_item::get_sub_group()+ .get_local_linear_id())) &&+ (my_gt | my_eq) != 0+ ? (0x1 << sycl::ext::oneapi::this_work_item::get_sub_group()+ .get_local_linear_id())+ : 0,+ sycl::ext::oneapi::plus<>()) ==+ 0u) continue; // a row without a selected block+ int pe = my_eq; // tied cells up to and with this lane+#pragma unroll+ for (int o = 1; o < 32; o <<= 1) {+ /*+ DPCT1108: '__shfl_up_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ const int y = dpct::experimental::shift_sub_group_right(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),+ pe, o);+ if (lane >= o) pe += y;+ }+ const int left = eq_budget - (run_eq + pe - my_eq);+ const int take = left < 0 ? 0 : (left > my_eq ? my_eq : left);+ const int my_sel = my_gt + take;+ int ps = my_sel;+#pragma unroll+ for (int o = 1; o < 32; o <<= 1) {+ /*+ DPCT1108: '__shfl_up_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ const int y = dpct::experimental::shift_sub_group_right(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),+ ps, o);+ if (lane >= o) ps += y;+ }+ int32_t* dst = out + run_sel + ps - my_sel;+#pragma unroll+ for (int c = 0; c < my_sel; ++c) dst[c] = (int32_t)(b * R + c);+ /*+ DPCT1108: '__shfl_sync' was migrated with the experimental feature+ masked sub_group function which may not be supported by all compilers or+ runtimes. You may need to adjust the code.+ */+ run_eq += dpct::experimental::select_from_sub_group(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), pe,+ 31);+ /*+ DPCT1108: '__shfl_sync' was migrated with the experimental feature+ masked sub_group function which may not be supported by all compilers or+ runtimes. You may need to adjust the code.+ */+ run_sel += dpct::experimental::select_from_sub_group(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), ps,+ 31);+ }+}+#endif+// Block scores with every key block read ONCE for all of a call's queries (block_scores_kernel's grid is// (max_blocks / 8) x nq: ~24,600 mostly-idle blocks per layer at a decode window, each key re-read per query). A fixed@@ -859,7 +1124,7 @@ register pressure.__dpct_inline__ void block_scores_multi_kernel(const float *__restrict__ pooled, const float *__restrict__ dead,const float *__restrict__ q_idx, const int32_t *__restrict__ steps, int nq,- int64_t max_blocks, float *__restrict__ out) {+ int64_t max_blocks, float *__restrict__ out, bool early_exit) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();auto &qs = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[MQ * IDX_HEADS * IDX_DIM]>(@@ -870,9 +1135,10 @@ auto &qs = *sycl::ext::oneapi::group_local_memory_for_overwrite<auto &s_nbid =*sycl::ext::oneapi::group_local_memory_for_overwrite<int64_t[MQ]>(sycl::ext::oneapi::this_work_item::get_work_group<3>());+ if (!early_exit)#pragma unroll- for (int i = item_ct1.get_local_id(2); i < nq * IDX_HEADS * IDX_DIM;- i += item_ct1.get_local_range(2)) qs[i] = q_idx[i];+ for (int i = item_ct1.get_local_id(2); i < nq * IDX_HEADS * IDX_DIM;+ i += item_ct1.get_local_range(2)) qs[i] = q_idx[i];if (item_ct1.get_local_id(2) < nq) {s_nkv[item_ct1.get_local_id(2)] =steps[item_ct1.get_local_id(2) * kStepCount + kStepNKv];@@ -883,6 +1149,20 @@ auto &qs = *sycl::ext::oneapi::group_local_memory_for_overwrite<int64_t top = 0;#pragma unrollfor (int q = 0; q < nq; ++q) top = s_nbid[q] > top ? s_nbid[q] : top;+ if (early_exit) {+ // (#783, stuchapin909) a CTA whose first block is past the batch's largest n_bid has no work: the grid is a+ // fixed 256 CTAs and a decode window reaches only a few of them, so those return before staging the queries.+ // Every thread of the CTA takes the same branch (top and blockIdx are CTA-uniform), so the barrier is safe.+ if ((int64_t)item_ct1.get_group(2) * SCORE_WARPS > top) return;+#pragma unroll+ for (int i = item_ct1.get_local_id(2); i < nq * IDX_HEADS * IDX_DIM;+ i += item_ct1.get_local_range(2)) qs[i] = q_idx[i];+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ item_ct1.barrier(sycl::access::fence_space::local_space);+ }const int lane = item_ct1.get_local_id(2) & 31;const int64_t wstride = (int64_t)item_ct1.get_group_range(2) * SCORE_WARPS;for (int64_t b = (int64_t)item_ct1.get_group(2) * SCORE_WARPS +@@ -1293,28 +1573,35 @@ void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx// a block past a query's n_bid returns at once: the grid need only reach the batch's largest n_bid (C-1)static const bool multi = [] { const char* v = std::getenv("STRATA_SCORES_MULTI"); return v == nullptr || std::atoi(v) != 0; }();if (multi && nq <= MQ && active_blocks <= 0) { // no active count: decode (captured or not) and prefill's pooled16+ // STRATA_QSA_EARLY_EXIT=0 keeps the old staging (every CTA loads the queries first); the scores are the same bits+ static const bool early = [] { const char* v = std::getenv("STRATA_QSA_EARLY_EXIT"); return v == nullptr || std::atoi(v) != 0; }();{auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<- dpct_kernel_name<class block_scores_multi_kernel_dea7d4>>(- sycl::nd_range<3>(sycl::range(1, 1, 256) *- sycl::range(1, 1, SCORE_WARPS * 32),- sycl::range(1, 1, SCORE_WARPS * 32)),- exp_props,- [=](sycl::nd_item<3> item_ct1)- [[sycl::reqd_sub_group_size(32)]] {- block_scores_multi_kernel(pooled, dead, q_idx,- steps, (int)nq,- max_blocks, scores);- });+ ->submit([&](sycl::handler &cgh) {+ auto early_ct7 = early;++ cgh.parallel_for<dpct_kernel_name<+ class block_scores_multi_kernel_dea7d4>>(+ sycl::nd_range<3>(+ sycl::range(1, 1, 256) *+ sycl::range(1, 1, SCORE_WARPS * 32),+ sycl::range(1, 1, SCORE_WARPS * 32)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ block_scores_multi_kernel(+ pooled, dead, q_idx, steps, (int)nq,+ max_blocks, scores, early_ct7);+ });+ });}/*- DPCT1010: SYCL uses exceptions to report errors and does not use the- error codes. The cudaGetLastError function call was replaced with 0. You- need to rewrite this code.+ DPCT1010: SYCL uses exceptions to report errors and does not use+ the error codes. The cudaGetLastError function call was replaced with 0.+ You need to rewrite this code.*/const dpct::err0 e = 0;/*@@ -1665,8 +1952,8 @@ catch (sycl::exception const &exc) {void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,const QsaShapes& s, int32_t* ids, void* stream, int64_t active_blocks) {- // keys in registers when every query's blocks fit (contexts up to ~135K cells); the same ids. STRATA_TOPK_OLD=1:- // the kernel that reads them from memory on every pass+ // keys in registers when every query's blocks fit (contexts up to ~135K cells), else (CUDA) the same threads+ // reading them from memory; the same ids. STRATA_TOPK_OLD=1: the original kernelstatic const bool old = std::getenv("STRATA_TOPK_OLD") != nullptr;if (nq <= 0) return;#if !defined(__HIPCC__)@@ -1700,10 +1987,12 @@ void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64#if defined(__HIPCC__)constexpr int64_t kRegMinBlocks = 7168; // gfx1201: below ~28K cells the 1,024-thread kernel's fixed cost loses to the refconst bool too_small = counted && reach < kRegMinBlocks;+ if (old || too_small || reach > fit) {#else- const bool too_small = false;+ constexpr int64_t kWideMinBlocks = 4608; // RTX 3060: a prompt batch below ~18K cells is faster on the ref+ const bool too_small = reach > fit && active_blocks > 0 && active_blocks < kWideMinBlocks;+ if (old || too_small) {#endif- if (old || too_small || reach > fit) {qsa_block_topk_ref(scores, steps, nq, max_blocks, cap, s, ids, stream);return;}@@ -1711,7 +2000,39 @@ void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64std::fprintf(stderr, "qsa_block_topk: unsupported geometry or cap\n");std::exit(1);}- if (reach <= (int64_t) TK_T * TK_PER)+#if !defined(__HIPCC__)+ // Turing prefill (the `counted` bound) above ~90K cells (22,528 blocks): the wide kernel, which reads the keys+ // coalesced, instead of the register kernel's uncoalesced per-thread runs (PR #743: 131K, 1.03 -> 0.75 ms); the+ // same ids. STRATA_TOPK_STREAM=0 restores the register kernel there.+ static const bool turing_wide = [] {+ const char* v = std::getenv("STRATA_TOPK_STREAM");+ return v == nullptr || v[0] != '0';+ }();+ if (reach > fit || (turing_wide && counted && reach > 22528)) // past the register kernel's reach, or Turing's band+ /*+ 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. Adjust the work-group size if needed.+ */+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<+ dpct_kernel_name<class block_topk_wide_kernel_5162c4>>(+ sycl::nd_range<3>(sycl::range(1, 1, (unsigned)nq) *+ sycl::range(1, 1, TK_T),+ sycl::range(1, 1, TK_T)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ block_topk_wide_kernel(scores, steps, max_blocks, cap,+ ids);+ });+ } else+#endif+ if (reach <= (int64_t)TK_T * TK_PER)/*DPCT1049: The work-group size passed to the SYCL kernel may exceedthe limit. To get the device limit, query@@ -1722,7 +2043,7 @@ void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class block_topk_reg_kernel_652097,+ ->parallel_for<dpct_kernel_name<class block_topk_reg_kernel_6ae5f0,dpct_kernel_scalar<TK_PER>>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)nq) *sycl::range(1, 1, TK_T),@@ -1744,7 +2065,7 @@ void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class block_topk_reg_kernel_652098,+ ->parallel_for<dpct_kernel_name<class block_topk_reg_kernel_10a848,dpct_kernel_scalar<TK_PER_MAX>>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)nq) *sycl::range(1, 1, TK_T),diff --git a/sycl/src/kernels/cuda/quantize_act.dp.cpp b/sycl/src/kernels/cuda/quantize_act.dp.cppindex ac4d0fdb1..180d37c2b 100644--- a/sycl/src/kernels/cuda/quantize_act.dp.cpp+++ b/sycl/src/kernels/cuda/quantize_act.dp.cpp@@ -104,21 +104,16 @@ __dpct_inline__ void quantize_q8_0_kernel(const float *__restrict__ x,/// `moe_hit_parity`. This function's job is different: it must match **this engine's own CPU reference**,/// because a hit and a miss for the same expert on the same layer have to produce the same number. The CPU/// path is the reference - C1 passes on it - so the hit path is brought to it, not the reverse.-__dpct_inline__ void quantize_q8_0_scaled_kernel(const float *__restrict__ x,- uint8_t *__restrict__ blocks,- float *__restrict__ scales,- long long n_blocks) {- auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();- const long long b =- (long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) +- item_ct1.get_local_id(2);+#if defined(__HIPCC__) // AMD keeps the thread-a-block kernel+__global__ void quantize_q8_0_scaled_kernel(const float* __restrict__ x, uint8_t* __restrict__ blocks,+ float* __restrict__ scales, long long n_blocks) {+ const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x;if (b >= n_blocks) return;const float* xb = x + b * QK8_0;uint8_t* out = blocks + b * 34;float amax = 0.0f;-#pragma unroll- for (int i = 0; i < QK8_0; ++i) amax = sycl::fmax(amax, sycl::fabs(xb[i]));+ for (int i = 0; i < QK8_0; ++i) amax = fmaxf(amax, fabsf(xb[i]));// VERBATIM from `cpu/expert.cpp:144-145`, including the `amax > 0` guard, so the fp32 value written here// is bit-identical to the `s` the CPU path used.const float s = amax > 0.f ? amax / 127.f : 0.f;@@ -139,6 +134,55 @@ __dpct_inline__ void quantize_q8_0_scaled_kernel(const float *__restrict__ x,}}+#else+// A warp a block, lane i on value i: the block's |max| is a max over the same values (0 for none above it, as the+// serial scan from 0 through fmaxf), so every byte is the per-thread loop's.+__dpct_inline__ void quantize_q8_0_scaled_kernel(const float *__restrict__ x,+ uint8_t *__restrict__ blocks,+ float *__restrict__ scales,+ long long n_blocks) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const long long b =+ ((long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) ++ item_ct1.get_local_id(2)) >>+ 5;+ const int i = (int)(item_ct1.get_local_id(2) & 31);+ if (b >= n_blocks) return;+ const float xi = x[b * QK8_0 + i];+ uint8_t* out = blocks + b * 34;++ float amax = sycl::fmax(0.0f, sycl::fabs(xi));+ /*+DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature+masked sub_group function which may not be supported by all compilers or+runtimes. You may need to adjust the code.+*/+#pragma unroll+ for (int o = 16; o > 0; o >>= 1) amax = sycl::fmax(+ amax, dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu,+ sycl::ext::oneapi::this_work_item::get_sub_group(), amax, o));+ // VERBATIM from `cpu/expert.cpp:144-145`, including the `amax > 0` guard, so the fp32 value written here+ // is bit-identical to the `s` the CPU path used.+ const float s = amax > 0.f ? amax / 127.f : 0.f;+ const float inv = s > 0.f ? 1.f / s : 0.f;+ if (i == 0) {+ scales[b] = s;+ const uint16_t d16bits = f16_from_f32(s);+ out[0] = (uint8_t) (d16bits & 0xFF);+ out[1] = (uint8_t) (d16bits >> 8);+ }+ // VERBATIM from `cpu/expert.cpp:159-162`: reciprocal multiply, then `t + copysign(0.5, t)` truncated+ // toward zero, which is `lround`'s rule - round half away from zero.+ const float t = xi * inv;+ const float r = t + (t >= 0.f ? 0.5f : -0.5f);+ int v = (int) r;+ v = v < -127 ? -127 : (v > 127 ? 127 : v);+ out[2 + i] = (uint8_t) (int8_t) v;+}++#endif+__dpct_inline__ void dequant_q8_0_kernel(const uint8_t *__restrict__ blocks,float *__restrict__ x,long long n_blocks) {@@ -308,7 +352,11 @@ void quantize_q8_0_scaled(const float* x, uint8_t* blocks, float* scales, int64_}const long long nb = n / QK8_0;const int threads = 128;+#if defined(__HIPCC__)const unsigned grid = (unsigned) ((nb + threads - 1) / threads);+#else+ const unsigned grid = (unsigned) ((nb + threads / 32 - 1) / (threads / 32)); // a warp a block+#endif{auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};@@ -319,9 +367,11 @@ void quantize_q8_0_scaled(const float* x, uint8_t* blocks, float* scales, int64_sycl::nd_range<3>(sycl::range(1, 1, grid) *sycl::range(1, 1, threads),sycl::range(1, 1, threads)),- exp_props, [=](sycl::nd_item<3> item_ct1) {- quantize_q8_0_scaled_kernel(x, blocks, scales, nb);- });+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ quantize_q8_0_scaled_kernel(x, blocks, scales, nb);+ });}/*DPCT1010: SYCL uses exceptions to report errors and does not use thediff --git a/sycl/src/kernels/cuda/router_top10.dp.cpp b/sycl/src/kernels/cuda/router_top10.dp.cppindex 1a602e5de..73d5b14a4 100644--- a/sycl/src/kernels/cuda/router_top10.dp.cpp+++ b/sycl/src/kernels/cuda/router_top10.dp.cpp@@ -313,6 +313,83 @@ runtimes. You may need to adjust the code.}}++#if defined(STRATA_HIP_GFX906)+// AMD (wave64): the same routing in ONE wavefront per token. The block-wide kernel above spends its time in+// barriers - 10 selection passes with two __syncthreads each over 8 logical warps - not in arithmetic (43 us per+// token on gfx906). Here every lane holds up to RW_PER probabilities in registers and each pass is a 64-lane+// butterfly argmax: no LDS round trip, no block barrier. Bit-identical to the kernel above: fmaxf trees are+// exact, the exponentials and the (float) products are the same expressions, the sum stays one serial ascending+// scan, and the argmax keeps the lowest index on a tie (a total order, so the butterfly's association is free).+constexpr int RW_PER = 8; // n_expert <= 64 * 8+__global__ void __launch_bounds__(64) router_top10_wave_kernel(const float* __restrict__ logits, int n_tokens,+ int n_expert, int k, int* __restrict__ ids,+ float* __restrict__ weights) {+ __shared__ double s_ex[64 * RW_PER];+ __shared__ double s_sum;+ const int t = blockIdx.x;+ if (t >= n_tokens) return;+ const int lane = threadIdx.x;+ const float* l = logits + (size_t) t * n_expert;+ float lv[RW_PER];+ float mx = -INFINITY;+#pragma unroll+ for (int j = 0; j < RW_PER; ++j) {+ const int e = lane + 64 * j;+ lv[j] = e < n_expert ? l[e] : -INFINITY;+ mx = fmaxf(mx, lv[j]);+ }+#pragma unroll+ for (int off = 32; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_xor(mx, off, 64));+#pragma unroll+ for (int j = 0; j < RW_PER; ++j) {+ const int e = lane + 64 * j;+ if (e < n_expert) s_ex[e] = exp((double) lv[j] - (double) mx);+ }+ __syncthreads();+ if (lane == 0) {+ double sum = 0.0;+ for (int e = 0; e < n_expert; ++e) sum += s_ex[e];+ s_sum = sum;+ }+ __syncthreads();+ const float inv = (float) (1.0 / s_sum);+ float p[RW_PER];+#pragma unroll+ for (int j = 0; j < RW_PER; ++j) {+ const int e = lane + 64 * j;+ p[j] = e < n_expert ? (float) (s_ex[e] * inv) : -INFINITY;+ }+ unsigned taken = 0;+ for (int i = 0; i < k; ++i) {+ float bv = -INFINITY;+ int bi = n_expert;+#pragma unroll+ for (int j = 0; j < RW_PER; ++j) {+ const int e = lane + 64 * j;+ if (e >= n_expert || (taken >> j & 1u)) continue;+ if (p[j] > bv || (p[j] == bv && e < bi)) { bv = p[j]; bi = e; }+ }+#pragma unroll+ for (int off = 32; off > 0; off >>= 1) {+ const float ov = __shfl_xor(bv, off, 64);+ const int oi = __shfl_xor(bi, off, 64);+ if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }+ }+ if (bi >= n_expert) break;+ if ((bi & 63) == lane) taken |= 1u << (bi >> 6);+ if (lane == 0) { ids[(size_t) t * k + i] = bi; weights[(size_t) t * k + i] = bv; }+ }+ if (lane == 0) {+ double s = 0.0;+ for (int i = 0; i < k; ++i) s += (double) weights[(size_t) t * k + i];+ const double sc = fmax(s, 6.103515625e-05); // 2**-14+ for (int i = 0; i < k; ++i)+ weights[(size_t) t * k + i] = (float) ((double) weights[(size_t) t * k + i] / sc);+ }+}+#endif // STRATA_HIP_GFX906+#if defined(__HIPCC__)// ---- S6, AMD: the same router, BIT-IDENTICAL, without its serial parts. Measured on RDNA4 (gfx1201) the kernel// above took 39 us per call in decode (16% of the GPU's decode time): the ascending double sum is 512 dependent FP64@@ -473,7 +550,13 @@ void router_top10(const float *logits, int n_tokens, int n_expert, int k,int *ids, float *weights, void *stream) try {#if defined(__HIPCC__){+#if defined(STRATA_HIP_GFX906)+ // gfx906 (wave64): the one-wavefront kernel below stays the default; the S6 kernel is wave32-shaped and only+ // runs here on request (STRATA_HIP_ROUTER_FAST=1) until it is measured on this card+ static const bool old = std::getenv("STRATA_HIP_ROUTER_FAST") == nullptr;+#elsestatic const bool old = std::getenv("STRATA_HIP_ROUTER_OLD") != nullptr;+#endifif (!old && n_tokens > 0 && n_expert > 64 && n_expert <= 512 && k > 0 && k <= 32) {launch_generic(logits, n_tokens, n_expert, k, ids, weights, stream, 1);const cudaError_t e = cudaGetLastError();@@ -502,6 +585,19 @@ void router_top10(const float *logits, int n_tokens, int n_expert, int k,RT_MAX_THREADS * 64);std::exit(1);}+#if defined(STRATA_HIP_GFX906)+ if (n_expert <= 64 * RW_PER && !std::getenv("STRATA_ROUTER_BLOCK")) {+ router_top10_wave_kernel<<<(unsigned) n_tokens, 64, 0, (cudaStream_t) stream>>>(logits, n_tokens, n_expert, k,+ ids, weights);+ const cudaError_t e = cudaGetLastError();+ if (e != cudaSuccess) {+ std::fprintf(stderr, "router_top10 launch: %s\n", cudaGetErrorString(e));+ std::exit(1);+ }+ if (stream == nullptr && cudaDeviceSynchronize() != cudaSuccess) std::exit(1);+ return;+ }+#endifint threads = n_expert < RT_MAX_THREADS ? n_expert : RT_MAX_THREADS;threads = (threads + 31) & ~31; // at least one full warp, for the reductions// the selection's taken-mask, then n_expert doubles for the exponentials, then n_expert floats for thediff --git a/sycl/src/kernels/cuda/s26_tsum.dp.hpp b/sycl/src/kernels/cuda/s26_tsum.dp.hppnew file mode 100644index 000000000..c902bc21c--- /dev/null+++ b/sycl/src/kernels/cuda/s26_tsum.dp.hpp@@ -0,0 +1,80 @@+// S26: several warp sums at once (P per-lane values -> P sums), bitwise equal to P separate xor-butterfly warp sums+// (`for (o = 16; o > 0; o >>= 1) v += shfl_xor(v, o)`). At offset 16 a lane keeps half of its P values and adds the+// partner's copy of that half, at 8 half again, ... until one value is left, then plain xor steps for the remaining+// offsets. Every level adds the same pair of values as the butterfly does (fp add commutes, so x + y == y + x+// bitwise), only each lane carries fewer of them: P - 1 + (5 - log2 P) cross-lane moves instead of 5 P. Value j's sum+// ends in the lanes whose bits 4, 3, .. (MSB first) spell j: tsum_lane<P>(j) is one of them. On AMD the moves are+// DPP row_xmask / permlanex16 instead of ds_bpermute.+#pragma once++#define DPCT_PROFILING_ENABLED+#include <sycl/sycl.hpp>+#include <dpct/dpct.hpp>+ // (before the first use of __forceinline__ / __float_as_int: a gfx906 build+ // gets them from its shim)++namespace strata::kernels::s26ts {++#if defined(__HIP_PLATFORM_AMD__) && !defined(STRATA_HIP_GFX906) // (permlanex16 / DPP row_xmask: gfx10+ only)+__device__ __forceinline__ float xmov16(float v) {+ return __int_as_float(__builtin_amdgcn_permlanex16(__float_as_int(v), __float_as_int(v), 0x76543210u, 0xfedcba98u,+ false, false));+}+template <int O>+__device__ __forceinline__ float xmov(float v) {+ if constexpr (O == 16) return xmov16(v);+ else return __int_as_float(__builtin_amdgcn_update_dpp(0, __float_as_int(v), 0x160 + O, 0xf, 0xf, false));+}+#else+template <int O>+/*+DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature+masked sub_group function which may not be supported by all compilers or+runtimes. You may need to adjust the code.+*/+__dpct_inline__ float xmov(float v) {+ return dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),+ v, O);+}+#endif++constexpr int pow2_ceil(int t) { return t <= 1 ? 1 : t <= 2 ? 2 : t <= 4 ? 4 : t <= 8 ? 8 : t <= 16 ? 16 : 32; }+constexpr int log2c(int p) { return p <= 1 ? 0 : p == 2 ? 1 : p == 4 ? 2 : p == 8 ? 3 : p == 16 ? 4 : 5; }++template <int O> __dpct_inline__ float tplain(float x) {+ if constexpr (O >= 1) { x += xmov<O>(x); return tplain<O / 2>(x); }+ else return x;+}+// v[0..CNT) (CNT a power of two <= 32): this lane's values; returns the sum of value tsum_token<CNT>(lane)+template <int CNT, int O = 16> __dpct_inline__ float tsum(float *v, int lane) {+ if constexpr (CNT > 1) {+ constexpr int H = CNT / 2;+ const bool hi = (lane & O) != 0;+#pragma unroll+ for (int j = 0; j < H; ++j) {+ const float send = hi ? v[j] : v[j + H];+ const float keep = hi ? v[j + H] : v[j];+ v[j] = keep + xmov<O>(send);+ }+ return tsum<H, O / 2>(v, lane);+ } else {+ return tplain<O>(v[0]);+ }+}+template <int P> __dpct_inline__ int tsum_token(int lane) {+ constexpr int L = log2c(P);+ int k = 0;+#pragma unroll+ for (int b = 0; b < L; ++b) k = (k << 1) | ((lane >> (4 - b)) & 1);+ return k;+}+template <int P> __dpct_inline__ int tsum_lane(int k) {+ constexpr int L = log2c(P);+ int lane = 0;+#pragma unroll+ for (int b = 0; b < L; ++b) lane |= ((k >> (L - 1 - b)) & 1) << (4 - b);+ return lane;+}++} // namespace strata::kernels::s26tsdiff --git a/sycl/src/kernels/cuda/s2_expert_grouped.dp.cpp b/sycl/src/kernels/cuda/s2_expert_grouped.dp.cppindex ff8bd9094..2da553b67 100644--- a/sycl/src/kernels/cuda/s2_expert_grouped.dp.cpp+++ b/sycl/src/kernels/cuda/s2_expert_grouped.dp.cpp@@ -20,6 +20,7 @@#include "strata/sycl_queue.hpp"#include "strata/kernels/s2_expert_grouped.hpp"#include "strata/kernels/dp4a.hpp"+#include "strata/kernels/f16_bits.hpp"#include "strata/kernels/quantize_act.hpp"#include "strata/kernels/verify_kernels.hpp"@@ -196,6 +197,51 @@ __dpct_inline__ void swiglu_kernel(float *__restrict__ gate_up,gate_up[i] = (g / (1.0f + sycl::native::exp(-g))) * u;}+__dpct_inline__ void swiglu_quantize_q8_0_scaled_kernel(+ float *__restrict__ gate_up, long long n_pairs,+ uint8_t *__restrict__ blocks, float *__restrict__ scales) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const long long n_blocks = n_pairs >> 5;+ const long long b =+ ((long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) ++ item_ct1.get_local_id(2)) >>+ 5;+ if (b >= n_blocks) return;+ const int lane = item_ct1.get_local_id(2) & 31;+ const long long idx = b * 32 + lane;+ const float g = gate_up[idx];+ const float u = gate_up[n_pairs + idx];+ const float xv = (g / (1.0f + sycl::native::exp(-g))) * u;+ gate_up[idx] = xv;+ uint8_t* out = blocks + b * 34;++ float amax = sycl::fabs(xv);+#pragma unroll+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature+ masked sub_group function which may not be supported by all compilers or+ runtimes. You may need to adjust the code.+ */+ for (int off = 16; off > 0; off >>= 1) amax =+ sycl::fmax(amax, dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu,+ sycl::ext::oneapi::this_work_item::get_sub_group(),+ amax, off));+ const float s = amax > 0.f ? amax / 127.f : 0.f;+ const float inv = s > 0.f ? 1.f / s : 0.f;+ if (lane == 0) {+ scales[b] = s;+ const uint16_t d16bits = f16_from_f32(s);+ out[0] = (uint8_t) (d16bits & 0xFF);+ out[1] = (uint8_t) (d16bits >> 8);+ }+ const float t = xv * inv;+ const float r = t + (t >= 0.f ? 0.5f : -0.5f);+ int v = (int) r;+ v = v < -127 ? -127 : (v > 127 ? 127 : v);+ out[2 + lane] = (uint8_t) (int8_t) v;+}+/// DOWN, ONE WARP PER ROW, reading the quantized intermediate the caller produced.////// `dst_index[h]` is which row of the shared output buffer hit `h` fills - see the header. It is the router's@@ -479,17 +525,17 @@ __dpct_inline__ float row_dot_cpu_order(const uint8_t *codes,const int hi = dot4(codes + b * 16 + 8 + lane,(const int8_t*) (xq + (size_t) (2 * b + 1) * 34 + 2) + lane * 4);/*- DPCT1013: The rounding mode could not be specified and the- generated code may have different accuracy than the original code.- Verify the correctness. SYCL math built-in function rounding mode is- aligned with OpenCL C 1.2 standard.+ DPCT1013: The rounding mode could not be specified and the generated+ code may have different accuracy than the original code. Verify the+ correctness. SYCL math built-in function rounding mode is aligned with+ OpenCL C 1.2 standard.*/acc = sycl::fma(d * xs[2 * b], (float)lo, acc);/*- DPCT1013: The rounding mode could not be specified and the- generated code may have different accuracy than the original code.- Verify the correctness. SYCL math built-in function rounding mode is- aligned with OpenCL C 1.2 standard.+ DPCT1013: The rounding mode could not be specified and the generated+ code may have different accuracy than the original code. Verify the+ correctness. SYCL math built-in function rounding mode is aligned with+ OpenCL C 1.2 standard.*/acc = sycl::fma(d * xs[2 * b + 1], (float)hi, acc);if (lane == 0)@@ -635,17 +681,17 @@ __dpct_inline__ void cpu_order_quantize_kernel(const float *x, uint8_t *blocks,int sum = 0;for (int j = 0; j < 32; ++j) {/*- DPCT1013: The rounding mode could not be specified and the- generated code may have different accuracy than the original code.- Verify the correctness. SYCL math built-in function rounding mode is- aligned with OpenCL C 1.2 standard.+ DPCT1013: The rounding mode could not be specified and the generated+ code may have different accuracy than the original code. Verify the+ correctness. SYCL math built-in function rounding mode is aligned with+ OpenCL C 1.2 standard.*/const float t = xb[j] * inv;/*- DPCT1013: The rounding mode could not be specified and the- generated code may have different accuracy than the original code.- Verify the correctness. SYCL math built-in function rounding mode is- aligned with OpenCL C 1.2 standard.+ DPCT1013: The rounding mode could not be specified and the generated+ code may have different accuracy than the original code. Verify the+ correctness. SYCL math built-in function rounding mode is aligned with+ OpenCL C 1.2 standard.*/int v = (int) (t + (t >= 0.0f ? 0.5f : -0.5f)); // SYCL port: dpct dropped the parentheses (it rounded every value to 0)v = v < -127 ? -127 : (v > 127 ? 127 : v);@@ -863,7 +909,7 @@ void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, conauto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- cs->parallel_for<dpct_kernel_name<class swiglu_kernel_30a435>>(+ cs->parallel_for<dpct_kernel_name<class swiglu_kernel_792534>>(sycl::nd_range<3>(sycl::range(1, 1, blocks) *sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),@@ -1020,7 +1066,7 @@ void moe_hit_grouped_s2_dev(const uint8_t* blob_base, const int32_t* slot_index,auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- cs->parallel_for<dpct_kernel_name<class swiglu_kernel_e17ecb>>(+ cs->parallel_for<dpct_kernel_name<class swiglu_kernel_5aa9a9>>(sycl::nd_range<3>(sycl::range(1, 1,(unsigned)((pairs + THREADS - 1) / THREADS)) *@@ -1085,7 +1131,7 @@ void moe_hit_grouped_s2_multi(const uint8_t* blob_base, const int32_t* slot_indeauto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- cs->parallel_for<dpct_kernel_name<class swiglu_kernel_3a6551>>(+ cs->parallel_for<dpct_kernel_name<class swiglu_kernel_a0c31a>>(sycl::nd_range<3>(sycl::range(1, 1,(unsigned)((pairs + THREADS - 1) / THREADS)) *@@ -1575,13 +1621,43 @@ void moe_grouped_s2(const unsigned long long* grp_ptr, const int32_t* grp_start,}check("moe_grouped_s2/gu", stream);}- {+ // #783 PR-k (stuchapin909): SwiGLU and the scaled Q8_0 quantize of its result in one kernel (gate_up still gets the+ // activation written back, so the parity checks read the same buffer); STRATA_S2_SWIGLU_Q8=0 keeps the two launches+ static const bool swiglu_q8 = [] {+ const char* e = std::getenv("STRATA_S2_SWIGLU_Q8");+ return e == nullptr || e[0] != '0';+ }();+ static_assert(FF % 32 == 0, "the fused SwiGLU + Q8_0 kernel works in whole 32-value blocks");+ if (fast && x_scales != nullptr && swiglu_q8) {+ const long long pairs = cap_entries * (long long) FF;+ const long long n_blocks = pairs >> 5;+ const int warps = THREADS / 32;+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ cs->parallel_for<dpct_kernel_name<+ class swiglu_quantize_q8_0_scaled_kernel_1271ea>>(+ sycl::nd_range<3>(+ sycl::range(1, 1,+ (unsigned)((n_blocks + warps - 1) / warps)) *+ sycl::range(1, 1, THREADS),+ sycl::range(1, 1, THREADS)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ swiglu_quantize_q8_0_scaled_kernel(gate_up, pairs,+ h_q8_0, h_scales);+ });+ }+ check("moe_grouped_s2/swiglu_q8", stream);+ } else {const long long pairs = cap_entries * (long long) FF;{auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- cs->parallel_for<dpct_kernel_name<class swiglu_kernel_5018f2>>(+ cs->parallel_for<dpct_kernel_name<class swiglu_kernel_90849f>>(sycl::nd_range<3>(sycl::range(1, 1,(unsigned)((pairs + THREADS - 1) / THREADS)) *@@ -1592,9 +1668,9 @@ void moe_grouped_s2(const unsigned long long* grp_ptr, const int32_t* grp_start,});}check("moe_grouped_s2/swiglu", stream);+ if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap_entries * (int64_t) FF, stream);+ else quantize_q8_0(gate_up, h_q8_0, cap_entries * (int64_t) FF, stream);}- if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap_entries * (int64_t) FF, stream);- else quantize_q8_0(gate_up, h_q8_0, cap_entries * (int64_t) FF, stream);{const dpct::dim3 grid((unsigned)(H / D_ROWS), (unsigned)cap_groups);const float* hs = x_scales != nullptr ? h_scales : nullptr;@@ -1699,7 +1775,7 @@ void moe_hit_grouped_s2_cpu_order(const uint8_t *blob_base,sycl::ext::oneapi::experimental::use_root_sync};cs->parallel_for<- dpct_kernel_name<class cpu_order_projection_kernel_6ed29b,+ dpct_kernel_name<class cpu_order_projection_kernel_2fbdd9,dpct_kernel_scalar<false>>>(sycl::nd_range<3>(sycl::range(1, 1,@@ -1775,7 +1851,7 @@ void moe_hit_grouped_s2_cpu_order(const uint8_t *blob_base,sycl::ext::oneapi::experimental::use_root_sync};cs->parallel_for<- dpct_kernel_name<class cpu_order_projection_kernel_c67875,+ dpct_kernel_name<class cpu_order_projection_kernel_2e007a,dpct_kernel_scalar<true>>>(sycl::nd_range<3>(sycl::range(1, 1,diff --git a/sycl/src/kernels/cuda/shared_expert.dp.cpp b/sycl/src/kernels/cuda/shared_expert.dp.cppindex 654105163..44d81a081 100644--- a/sycl/src/kernels/cuda/shared_expert.dp.cpp+++ b/sycl/src/kernels/cuda/shared_expert.dp.cpp@@ -76,6 +76,7 @@ __dpct_inline__ void native_swiglu_kernel(const float *gate, const float *up,out[i] = gate[i] / (1.0f + sycl::native::exp(-gate[i])) * up[i];}+void to_f16_kernel(const float* __restrict__ in, uint16_t* __restrict__ out, int n) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();const int i = item_ct1.get_group(2) * item_ct1.get_local_range(2) +@@ -181,8 +182,7 @@ __dpct_inline__ void native_scalar_sigmoid_kernel(float *gate) {// compilation flags. The dot product was already reduced by the pinned native MMVF implementation.gate[0] = 1.0f / (1.0f + sycl::native::exp(-gate[0]));}-__dpct_inline__ void native_scalar_sigmoid_multi_kernel(- float *gate) { // thread t = token t, same expression+void native_scalar_sigmoid_multi_kernel(float* gate) { // thread t = token t, same expression/*DPCT1064: Migrated __expf call is used in a macro/template definitionand may not be valid for all macro/template uses. Adjust the code.@@ -216,6 +216,7 @@ __dpct_inline__ void moe_combine_kernel(const float *__restrict__ parts,} // namespacevoid shared_expert_set_native_bf16(bool enabled) { native_bf16 = enabled; }+bool shared_expert_native_bf16_enabled() { return native_bf16; }namespace {__dpct_inline__ void scale_rows_kernel(float *__restrict__ out,@@ -226,57 +227,164 @@ __dpct_inline__ void scale_rows_kernel(float *__restrict__ out,item_ct1.get_local_id(2);if (i < n) out[(size_t) t * n + i] *= g[t];}-} // namespace-void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, const NativeSharedWeights& nw,- const uint16_t* gate_inp_bf16, float* gate, float* up, float* g, float* out, int64_t n_embd,- int64_t n_ff, void* stream) {- if (n_tok < 1 || n_tok > 8 || !nw.q8_1 || !nw.gate_data || !nw.up_data || !nw.down_data || !stream)- throw std::invalid_argument("shared_expert_multi: needs 1..8 tokens, native weights, scratch and a stream");- dpct::queue_ptr cs = strata::q_of(stream);- native_quantize_q8_1(x, nw.q8_1, (int) n_embd, n_tok, stream);- native_mmvq(nw.gate_type, nw.gate_data, nw.q8_1, gate, (int) n_embd, (int) n_ff, n_tok, stream);- native_mmvq(nw.up_type, nw.up_data, nw.q8_1, up, (int) n_embd, (int) n_ff, n_tok, stream);- const int n = (int) (n_ff * n_tok);- {+__dpct_inline__ void sigmoid_scale_rows_kernel(float *__restrict__ out,+ const float *__restrict__ g,+ int n) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int t = item_ct1.get_group(1);+ const int i = item_ct1.get_group(2) * item_ct1.get_local_range(2) ++ item_ct1.get_local_id(2);+ if (i < n) {+ const float gt = 1.0f / (1.0f + sycl::native::exp(-g[t]));+ out[(size_t) t * n + i] *= gt;+ }+}++__dpct_inline__ void+sigmoid_scale_rows_vec4_kernel(sycl::float4 *__restrict__ out4,+ const float *__restrict__ g, int n4) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int t = item_ct1.get_group(1);+ const int i = item_ct1.get_group(2) * item_ct1.get_local_range(2) ++ item_ct1.get_local_id(2);+ if (i < n4) {+ /*+ DPCT1098: The '*' expression is used instead of the __ldg call.+ These two expressions do not provide the exact same functionality. Check+ the generated code for potential precision and/or performance issues.+ */+ const float gt = 1.0f / (1.0f + sycl::native::exp(-*(g + t)));+ sycl::float4 v = out4[(size_t)t * n4 + i];+ v.x() *= gt;+ v.y() *= gt;+ v.z() *= gt;+ v.w() *= gt;+ out4[(size_t) t * n4 + i] = v;+ }+}++void launch_sigmoid_scale_rows(float *out, const float *g, int n_embd,+ int n_tok, dpct::queue_ptr cs) {+ if ((n_embd & 3) == 0 && ((uintptr_t) out & 15u) == 0) {+ const int n4 = n_embd >> 2;+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ cs->parallel_for<+ dpct_kernel_name<class sigmoid_scale_rows_vec4_kernel_723a94>>(+ sycl::nd_range<3>(+ sycl::range(1, (unsigned)n_tok,+ (unsigned)((n4 + THREADS - 1) / THREADS)) *+ sycl::range(1, 1, THREADS),+ sycl::range(1, 1, THREADS)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ sigmoid_scale_rows_vec4_kernel(+ reinterpret_cast<sycl::float4 *>(out), g, n4);+ });+ }+ } else {auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- cs->parallel_for<dpct_kernel_name<class native_swiglu_kernel_93d137>>(+ cs->parallel_for<+ dpct_kernel_name<class sigmoid_scale_rows_kernel_26f4a0>>(sycl::nd_range<3>(- sycl::range(1, 1, (unsigned)((n + THREADS - 1) / THREADS)) *+ sycl::range(1, (unsigned)n_tok,+ (unsigned)((n_embd + THREADS - 1) / THREADS)) *sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),exp_props, [=](sycl::nd_item<3> item_ct1) {- native_swiglu_kernel(gate, up, gate, n);+ sigmoid_scale_rows_kernel(out, g, n_embd);});}- native_quantize_q8_1(gate, nw.q8_1, (int) n_ff, n_tok, stream);- native_mmvq(nw.down_type, nw.down_data, nw.q8_1, out, (int) n_ff, (int) n_embd, n_tok, stream);- static const bool batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }();- if (native_bf16 && batch && n_tok > 1) { // one gemv for all rows (outputs identical), one sigmoid launch- bf16_gemv_fp32_mmvf_multi(x, n_embd, gate_inp_bf16, g, 1, n_embd, 1, n_tok, stream);- /*- 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. Adjust the work-group size if needed.- */+}++bool fused_swiglu_q81_enabled() {+ static const bool on = [] {+ const char* v = std::getenv("STRATA_FUSED_SWIGLU_Q81");+ return v == nullptr || std::atoi(v) != 0;+ }();+ return on;+}+} // namespace++void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, const NativeSharedWeights& nw,+ const uint16_t* gate_inp_bf16, float* gate, float* up, float* g, float* out, int64_t n_embd,+ int64_t n_ff, void* stream, const void* x_q8_1_ready, int lfuse) {+ const bool gate_deferred = (lfuse & 1) != 0, pair = (lfuse & 2) != 0;+ if (n_tok < 1 || n_tok > 8 || !nw.q8_1 || !nw.gate_data || !nw.up_data || !nw.down_data || !stream)+ throw std::invalid_argument("shared_expert_multi: needs 1..8 tokens, native weights, scratch and a stream");+ dpct::queue_ptr cs = strata::q_of(stream);+ // the activation's q8_1: the caller's (STRATA_VERIFY_QDEDUP, x_q8_1_ready) or the descriptor's, else quantized here+ const void* x_q8_1 = x_q8_1_ready ? x_q8_1_ready : nw.x_q8_1;+ if (!x_q8_1) {+ native_quantize_q8_1(x, nw.q8_1, (int) n_embd, n_tok, stream);+ x_q8_1 = nw.q8_1;+ }+ // S26 STRATA_LFUSE (gate_deferred): gate and up in one launch where the pair applies (bitwise the two calls)+ if (!(pair && nw.gate_type == nw.up_type &&+ native_mmvq_pair(nw.gate_type, nw.gate_data, nw.up_data, x_q8_1, gate, up, (int) n_embd, (int) n_ff, n_tok, stream))) {+ native_mmvq(nw.gate_type, nw.gate_data, x_q8_1, gate, (int) n_embd, (int) n_ff, n_tok, stream);+ native_mmvq(nw.up_type, nw.up_data, x_q8_1, up, (int) n_embd, (int) n_ff, n_tok, stream);+ }+ const int n = (int) (n_ff * n_tok);+ if (fused_swiglu_q81_enabled()) {+ native_swiglu_quantize_q8_1(gate, up, nw.q8_1, (int) n_ff, n_tok, stream);+ } else {{auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- cs->parallel_for<dpct_kernel_name<- class native_scalar_sigmoid_multi_kernel_e0530d>>(- sycl::nd_range<3>(sycl::range(1, 1, n_tok),- sycl::range(1, 1, n_tok)),+ cs->parallel_for<+ dpct_kernel_name<class native_swiglu_kernel_c4e755>>(+ sycl::nd_range<3>(+ sycl::range(1, 1, (unsigned)((n + THREADS - 1) / THREADS)) *+ sycl::range(1, 1, THREADS),+ sycl::range(1, 1, THREADS)),exp_props, [=](sycl::nd_item<3> item_ct1) {- native_scalar_sigmoid_multi_kernel(g);+ native_swiglu_kernel(gate, up, gate, n);});}- } else- for (int t = 0; t < n_tok; ++t) {- if (native_bf16) {- bf16_gemv_fp32_mmvf(x + (size_t) t * n_embd, gate_inp_bf16, g + t, n_embd, 1, stream);+ native_quantize_q8_1(gate, nw.q8_1, (int) n_ff, n_tok, stream);+ }+ native_mmvq(nw.down_type, nw.down_data, nw.q8_1, out, (int) n_ff, (int) n_embd, n_tok, stream);+ if (gate_deferred) { // the caller computed g (raw) with the router and scales `out` in the combine+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use the+ error codes. The cudaGetLastError function call was replaced with 0. You+ need to rewrite this code.+ */+ const dpct::err0 e = 0;+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use+ error codes. Please replace the "get_error_string_dummy(...)" with a+ real error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (e !=+ 0) throw std::runtime_error(std::string("shared_expert_multi: ") ++ dpct::get_error_string_dummy(e));+ return;+ }+ static const bool batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }();+ if (native_bf16 && batch && n_tok > 1) { // one gemv for all rows (outputs identical), fused sigmoid+scale+ bf16_gemv_fp32_mmvf_multi(x, n_embd, gate_inp_bf16, g, 1, n_embd, 1, n_tok, stream);+ launch_sigmoid_scale_rows(out, g, (int) n_embd, n_tok, cs);+ } else if (native_bf16 && n_tok == 1) {+ bf16_gemv_fp32_mmvf(x, gate_inp_bf16, g, n_embd, 1, stream);+ launch_sigmoid_scale_rows(out, g, (int) n_embd, 1, cs);+ } else {+ for (int t = 0; t < n_tok; ++t) {+ if (native_bf16) {+ bf16_gemv_fp32_mmvf(x + (size_t) t * n_embd, gate_inp_bf16, g + t, n_embd, 1, stream);{auto exp_props =sycl::ext::oneapi::experimental::properties{@@ -286,7 +394,7 @@ void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, consauto g_t_ct0 = g + t;cgh.parallel_for<dpct_kernel_name<- class native_scalar_sigmoid_kernel_344179>>(+ class native_scalar_sigmoid_kernel_9552ea>>(sycl::nd_range<3>(sycl::range(1, 1, 1),sycl::range(1, 1, 1)),exp_props, [=](sycl::nd_item<3> item_ct1) {@@ -294,7 +402,7 @@ void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, cons});});}- } else {+ } else {auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};dpct::has_capability_or_fail(cs->get_device(),@@ -306,7 +414,7 @@ void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, consauto g_t_ct2 = g + t;cgh.parallel_for<- dpct_kernel_name<class scalar_gate_kernel_372f76>>(+ dpct_kernel_name<class scalar_gate_kernel_76bc5d>>(sycl::nd_range<3>(sycl::range(1, 1, 256),sycl::range(1, 1, 256)),exp_props,@@ -317,21 +425,22 @@ void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, cons(int)n_embd);});});+ }}- }- {- auto exp_props = sycl::ext::oneapi::experimental::properties{- sycl::ext::oneapi::experimental::use_root_sync};+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};- cs->parallel_for<dpct_kernel_name<class scale_rows_kernel_4f17ec>>(- sycl::nd_range<3>(- sycl::range(1, (unsigned)n_tok,- (unsigned)((n_embd + THREADS - 1) / THREADS)) *- sycl::range(1, 1, THREADS),- sycl::range(1, 1, THREADS)),- exp_props, [=](sycl::nd_item<3> item_ct1) {- scale_rows_kernel(out, g, (int)n_embd);- });+ cs->parallel_for<dpct_kernel_name<class scale_rows_kernel_4f17ec>>(+ sycl::nd_range<3>(+ sycl::range(1, (unsigned)n_tok,+ (unsigned)((n_embd + THREADS - 1) / THREADS)) *+ sycl::range(1, 1, THREADS),+ sycl::range(1, 1, THREADS)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ scale_rows_kernel(out, g, (int)n_embd);+ });+ }}/*DPCT1010: SYCL uses exceptions to report errors and does not use the@@ -434,56 +543,62 @@ void shared_expert(const uint8_t *x_q8_0, const uint8_t *x_q8k,native_mmvq(native->up_type, native->up_data, native->q8_1, up, (int) n_embd, (int) n_ff, 1, stream);elsegemv(up_form, up_codes, up_scales, up_off, x_q8_0, x_q8k, up, n_embd, n_ff);- if (native_projection)- {- auto exp_props = sycl::ext::oneapi::experimental::properties{- sycl::ext::oneapi::experimental::use_root_sync};-- strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class native_swiglu_kernel_5e9503>>(- sycl::nd_range<3>(sycl::range(1, 1, g_ff) *- sycl::range(1, 1, THREADS),- sycl::range(1, 1, THREADS)),- exp_props, [=](sycl::nd_item<3> item_ct1) {- native_swiglu_kernel(gate, up, gate, (int)n_ff);- });+ if (native_projection && native_down && fused_swiglu_q81_enabled()) {+ native_swiglu_quantize_q8_1(gate, up, native->q8_1, (int) n_ff, 1, stream);+ native_mmvq(native->down_type, native->down_data, native->q8_1, out, (int) n_ff, (int) n_embd, 1, stream);} else {- auto exp_props = sycl::ext::oneapi::experimental::properties{- sycl::ext::oneapi::experimental::use_root_sync};- dpct::has_capability_or_fail(- strata::q_of(stream)->get_device(),- {sycl::aspect::fp64});+ if (native_projection)+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};- strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class swiglu_kernel_fbfcfe>>(- sycl::nd_range<3>(sycl::range(1, 1, g_ff) *- sycl::range(1, 1, THREADS),- sycl::range(1, 1, THREADS)),- exp_props, [=](sycl::nd_item<3> item_ct1) {- swiglu_kernel(gate, up, gate, (int)n_ff);- });- }+ strata::q_of(stream)+ ->parallel_for<+ dpct_kernel_name<class native_swiglu_kernel_75dcdc>>(+ sycl::nd_range<3>(sycl::range(1, 1, g_ff) *+ sycl::range(1, 1, THREADS),+ sycl::range(1, 1, THREADS)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ native_swiglu_kernel(gate, up, gate, (int)n_ff);+ });+ } else {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(+ strata::q_of(stream)->get_device(),+ {sycl::aspect::fp64});- // down: (n_ff) -> (n_embd), and THE INTERMEDIATE IS QUANTIZED TO THE DOWN WEIGHT'S OWN CONTRACT - which is- // what `ggml_mul_mat` does for every matmul in the model. It used to be rounded to fp16 with no- // justification beyond "the kernel takes fp16".- if (native_down) {- native_quantize_q8_1(gate, native->q8_1, (int) n_ff, 1, stream);- native_mmvq(native->down_type, native->down_data, native->q8_1, out, (int) n_ff, (int) n_embd, 1, stream);- } else if (down_form.act_kind == 1) {- if (n_ff % 256 != 0) {- std::fprintf(stderr, "shared_expert: the down weight wants Q8_K but n_ff %lld is not a multiple "- "of 256; Q8_K is structurally impossible here\n", (long long) n_ff);- std::exit(1);+ strata::q_of(stream)+ ->parallel_for<dpct_kernel_name<class swiglu_kernel_fbfcfe>>(+ sycl::nd_range<3>(sycl::range(1, 1, g_ff) *+ sycl::range(1, 1, THREADS),+ sycl::range(1, 1, THREADS)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ swiglu_kernel(gate, up, gate, (int)n_ff);+ });+ }++ // down: (n_ff) -> (n_embd), and THE INTERMEDIATE IS QUANTIZED TO THE DOWN WEIGHT'S OWN CONTRACT - which is+ // what `ggml_mul_mat` does for every matmul in the model. It used to be rounded to fp16 with no+ // justification beyond "the kernel takes fp16".+ if (native_down) {+ native_quantize_q8_1(gate, native->q8_1, (int) n_ff, 1, stream);+ native_mmvq(native->down_type, native->down_data, native->q8_1, out, (int) n_ff, (int) n_embd, 1, stream);+ } else if (down_form.act_kind == 1) {+ if (n_ff % 256 != 0) {+ std::fprintf(stderr, "shared_expert: the down weight wants Q8_K but n_ff %lld is not a multiple "+ "of 256; Q8_K is structurally impossible here\n", (long long) n_ff);+ std::exit(1);+ }+ quantize_q8_K(gate, h_q8k, n_ff, stream);+ gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd);+ } else if (down_form.code_bits == 2) {+ quantize_q8_0(gate, h_q8_0, n_ff, stream);+ gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd);+ } else {+ quantize_q8_0(gate, h_q8_0, n_ff, stream);+ gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd);}- quantize_q8_K(gate, h_q8k, n_ff, stream);- gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd);- } else if (down_form.code_bits == 2) {- quantize_q8_0(gate, h_q8_0, n_ff, stream);- gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd);- } else {- quantize_q8_0(gate, h_q8_0, n_ff, stream);- gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd);}// the per-token scalar gate, then the multiply. Note the gate is computed from `x`, the ORIGINAL hidden@@ -493,49 +608,41 @@ void shared_expert(const uint8_t *x_q8_0, const uint8_t *x_q8k,// round trip. 256 threads is the reduction's width, not the problem's size.if (use_native) {bf16_gemv_fp32_mmvf(x_f32, gate_inp_bf16, g, n_embd, 1, stream);+ launch_sigmoid_scale_rows(out, g, (int)n_embd, 1,+ strata::q_of(stream));+ } else {{auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(+ strata::q_of(stream)->get_device(),+ {sycl::aspect::fp64});strata::q_of(stream)- ->parallel_for<dpct_kernel_name<- class native_scalar_sigmoid_kernel_3dbcd0>>(- sycl::nd_range<3>(sycl::range(1, 1, 1),- sycl::range(1, 1, 1)),- exp_props, [=](sycl::nd_item<3> item_ct1) {- native_scalar_sigmoid_kernel(g);- });+ ->parallel_for<+ dpct_kernel_name<class scalar_gate_kernel_82de77>>(+ sycl::nd_range<3>(sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ scalar_gate_kernel(x_bf16, gate_inp_bf16, g,+ (int)n_embd);+ });}- } else {- auto exp_props = sycl::ext::oneapi::experimental::properties{- sycl::ext::oneapi::experimental::use_root_sync};- dpct::has_capability_or_fail(- strata::q_of(stream)->get_device(),- {sycl::aspect::fp64});+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};- strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class scalar_gate_kernel_264fbf>>(- sycl::nd_range<3>(sycl::range(1, 1, 256),- sycl::range(1, 1, 256)),- exp_props,- [=](sycl::nd_item<3> item_ct1)- [[sycl::reqd_sub_group_size(32)]] {- scalar_gate_kernel(x_bf16, gate_inp_bf16, g,- (int)n_embd);+ strata::q_of(stream)+ ->parallel_for<dpct_kernel_name<class scale_kernel_a41a71>>(+ sycl::nd_range<3>(sycl::range(1, 1, g_embd) *+ sycl::range(1, 1, THREADS),+ sycl::range(1, 1, THREADS)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ scale_kernel(out, g, (int)n_embd);});- }- {- auto exp_props = sycl::ext::oneapi::experimental::properties{- sycl::ext::oneapi::experimental::use_root_sync};-- strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class scale_kernel_a41a71>>(- sycl::nd_range<3>(sycl::range(1, 1, g_embd) *- sycl::range(1, 1, THREADS),- sycl::range(1, 1, THREADS)),- exp_props, [=](sycl::nd_item<3> item_ct1) {- scale_kernel(out, g, (int)n_embd);- });+ }}if (stream == nullptr) {diff --git a/sycl/src/kernels/cuda/verify_kernels.dp.cpp b/sycl/src/kernels/cuda/verify_kernels.dp.cppindex f3ca2482a..69f6d12ad 100644--- a/sycl/src/kernels/cuda/verify_kernels.dp.cpp+++ b/sycl/src/kernels/cuda/verify_kernels.dp.cpp@@ -11,8 +11,10 @@#include "strata/kernels/resident_plan_mirror.hpp"#include "strata/kernels/dp4a.hpp"+#include <algorithm>#include <cstdio>#include <cstdlib>+#include <cmath>#ifndef STRATA_PLAN_LOCAL#define STRATA_PLAN_LOCAL 1 // 0: the original one-thread plan kernel (A/B)@@ -38,12 +40,13 @@ void check(const char* what) {*/}-__dpct_inline__ void gdn_conv_l2_multi_kernel(const float *__restrict__ hist,+// `commit` (one token): the history then keeps it - [hist1, hist2, x_0], each thread its channel's, after reading them+__dpct_inline__ void gdn_conv_l2_multi_kernel(float *hist,const float *__restrict__ qkv,const float *__restrict__ w,float *__restrict__ h, int C,int qk_heads, float eps,- int t_begin) {+ int t_begin, bool commit) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();auto &part =*sycl::ext::oneapi::group_local_memory_for_overwrite<float[S / 32]>(@@ -58,6 +61,11 @@ auto &part =win[j] = src < 3 ? hist[c * 3 + src] : qkv[(size_t) (src - 3) * C + c];}const float v0 = win[0], v1 = win[1], v2 = win[2], x = qkv[(size_t) t * C + c];+ if (commit) {+ hist[c * 3] = v1;+ hist[c * 3 + 1] = v2;+ hist[c * 3 + 2] = x;+ }float sum = v0 * w[c * 4] + v1 * w[c * 4 + 1] + v2 * w[c * 4 + 2] + x * w[c * 4 + 3];float y = sum / (1.0f + sycl::native::exp(-sum));if ((int)item_ct1.get_group(2) < qk_heads) {@@ -78,7 +86,12 @@ runtimes. You may need to adjust the code.DPCT1118: SYCL group functions and algorithms must be encountered inconverged control flow. You may need to adjust the code.*/- item_ct1.barrier(sycl::access::fence_space::local_space);+ /*+ 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.+ */+ item_ct1.barrier();const float ss = part[0] + part[1] + part[2] + part[3];y *= sycl::rsqrt(ss + eps);}@@ -105,6 +118,7 @@ gdn_conv_commit_kernel(float *__restrict__ hist, const float *__restrict__ qkv,hist[c * 3 + 2] = seq[2];}+template <int MAX_T = kVerifyMaxT, bool EXACT_T = false>/*DPCT1110: The total declared local variable size in device functiongdn_ab_multi_kernel exceeds 128 bytes and may cause high register pressure.@@ -117,16 +131,16 @@ __dpct_inline__ void gdn_ab_multi_kernel(const float *__restrict__ ssm_a, float *__restrict__ gate,float *__restrict__ beta, int n, int h_v, int T) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();- const int row = item_ct1.get_group(2) * 8 + (item_ct1.get_local_id(2) >> 5),+ const int row = item_ct1.get_group(2) * 2 + (item_ct1.get_local_id(2) >> 5),lane = item_ct1.get_local_id(2) & 31;if (row >= 2 * h_v) return;const bool is_beta = row >= h_v;const int r = is_beta ? row - h_v : row;const sycl::uint4 *w4 = reinterpret_cast<const sycl::uint4 *>((is_beta ? wb : wa) + (size_t)r * n);- float acc[kVerifyMaxT];+ float acc[MAX_T];#pragma unroll- for (int t = 0; t < kVerifyMaxT; ++t) acc[t] = 0.0f;+ for (int t = 0; t < MAX_T; ++t) acc[t] = 0.0f;for (int j = lane; j < n / 8; j += 32) {/*DPCT1098: The '*' expression is used instead of the __ldg call.@@ -134,44 +148,54 @@ __dpct_inline__ void gdn_ab_multi_kernel(the generated code for potential precision and/or performance issues.*/const sycl::uint4 wv = *(w4 + j);+ const float w0 = sycl::bit_cast<float>(wv.x() << 16),+ w1 = sycl::bit_cast<float>(wv.x() & 0xffff0000u);+ const float w2 = sycl::bit_cast<float>(wv.y() << 16),+ w3 = sycl::bit_cast<float>(wv.y() & 0xffff0000u);+ const float w4f = sycl::bit_cast<float>(wv.z() << 16),+ w5 = sycl::bit_cast<float>(wv.z() & 0xffff0000u);+ const float w6 = sycl::bit_cast<float>(wv.w() << 16),+ w7 = sycl::bit_cast<float>(wv.w() & 0xffff0000u);#pragma unroll- for (int t = 0; t < kVerifyMaxT; ++t) {- if (t >= T) break;+ for (int t = 0; t < MAX_T; ++t) {+ if (!EXACT_T && t >= T) break;const float* xt = x + (size_t) t * n;- const sycl::float4 xa =- *reinterpret_cast<const sycl::float4 *>(xt + j * 8);- const sycl::float4 xb =- *reinterpret_cast<const sycl::float4 *>(xt + j * 8 + 4);+ /*+ DPCT1098: The '*' expression is used instead of the __ldg call.+ These two expressions do not provide the exact same functionality.+ Check the generated code for potential precision and/or performance+ issues.+ */+ const sycl::float4 xa = *reinterpret_cast<const sycl::float4 *>(xt + j * 8);+ /*+ DPCT1098: The '*' expression is used instead of the __ldg call.+ These two expressions do not provide the exact same functionality.+ Check the generated code for potential precision and/or performance+ issues.+ */+ const sycl::float4 xb = *reinterpret_cast<const sycl::float4 *>(xt + j * 8 + 4);float a = acc[t];- a = sycl::fma(sycl::bit_cast<float>(wv.x() << 16), (float)(xa.x()),- a);- a = sycl::fma(sycl::bit_cast<float>(wv.x() & 0xffff0000u),- (float)(xa.y()), a);- a = sycl::fma(sycl::bit_cast<float>(wv.y() << 16), (float)(xa.z()),- a);- a = sycl::fma(sycl::bit_cast<float>(wv.y() & 0xffff0000u),- (float)(xa.w()), a);- a = sycl::fma(sycl::bit_cast<float>(wv.z() << 16), (float)(xb.x()),- a);- a = sycl::fma(sycl::bit_cast<float>(wv.z() & 0xffff0000u),- (float)(xb.y()), a);- a = sycl::fma(sycl::bit_cast<float>(wv.w() << 16), (float)(xb.z()),- a);- a = sycl::fma(sycl::bit_cast<float>(wv.w() & 0xffff0000u),- (float)(xb.w()), a);+ a = sycl::fma((float)w0, (float)(xa.x()), a);+ a = sycl::fma((float)w1, (float)(xa.y()), a);+ a = sycl::fma((float)w2, (float)(xa.z()), a);+ a = sycl::fma((float)w3, (float)(xa.w()), a);+ a = sycl::fma((float)w4f, (float)(xb.x()), a);+ a = sycl::fma((float)w5, (float)(xb.y()), a);+ a = sycl::fma((float)w6, (float)(xb.z()), a);+ a = sycl::fma((float)w7, (float)(xb.w()), a);acc[t] = a;}}#pragma unroll- for (int t = 0; t < kVerifyMaxT; ++t) {- if (t >= T) break;+ for (int t = 0; t < MAX_T; ++t) {+ if (!EXACT_T && t >= T) break;float a = acc[t];- /*-DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature-masked sub_group function which may not be supported by all compilers or-runtimes. You may need to adjust the code.-*/#pragma unroll+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */for (int o = 16; o > 0; o >>= 1) a +=dpct::experimental::permute_sub_group_by_xor(0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),@@ -187,38 +211,33 @@ runtimes. You may need to adjust the code.}}+// State-only commit kernel: each head's 128 independent state columns are split across 4 blocks of 32 columns+// (48 * 4 = 192 blocks of 128 threads across all SMs, vs 48 blocks of 512 threads), with no sq/o/norm/z/y work./*DPCT1110: The total declared local variable size in device function-gdn_step_norm_multi_kernel exceeds 128 bytes and may cause high register-pressure. Consult with your hardware vendor to find the total register size-available and adjust the code, or use smaller sub-group size to avoid high-register pressure.+gdn_step_commit_kernel exceeds 128 bytes and may cause high register pressure.+Consult with your hardware vendor to find the total register size available and+adjust the code, or use smaller sub-group size to avoid high register pressure.*/-__dpct_inline__ void gdn_step_norm_multi_kernel(+__dpct_inline__ void gdn_step_commit_kernel(float *__restrict__ state, const float *__restrict__ hbuf, int C,- const float *__restrict__ gate, const float *__restrict__ beta,- const float *__restrict__ z, const float *__restrict__ gamma, float eps,- float *__restrict__ y, int h_k, int h_v, int T,- const int32_t *__restrict__ n_keep, int t_out_begin) {+ const float *__restrict__ gate, const float *__restrict__ beta, int h_k,+ int h_v, const int32_t *__restrict__ n_keep) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();-auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(- sycl::ext::oneapi::this_work_item::get_work_group<3>());- auto &sq = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(+ const int n = *n_keep;+ if (n <= 0) return;+ auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(sycl::ext::oneapi::this_work_item::get_work_group<3>());auto &red =- *sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][S]>(+ *sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][32]>(sycl::ext::oneapi::this_work_item::get_work_group<3>());- auto &wsum = *sycl::ext::oneapi::group_local_memory_for_overwrite<- float[S * RG / 32]>(- sycl::ext::oneapi::this_work_item::get_work_group<3>());const int head = item_ct1.get_group(2);- const int col = item_ct1.get_local_id(2);+ const int col_local = item_ct1.get_local_id(2);+ const int col = item_ct1.get_group(1) * 32 + col_local;const int rg = item_ct1.get_local_id(1);- const int tid = rg * S + col;+ const int tid = rg * 32 + col_local; // 0 .. 127const int qh = head % h_k;- const int qk = S * h_k; // q at [0, qk), k at [qk, 2qk), v at [2qk, ...)- const int value_dim = S * h_v;- const int n = n_keep ? *n_keep : T;+ const int qk = S * h_k;float s[RPG];float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;const size_t row_stride = (size_t) h_v * S;@@ -235,8 +254,8 @@ auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(sycl::nd_item::barrier(sycl::access::fence_space::local_space) forbetter performance if there is no access to global memory.*/- item_ct1.barrier(); // the previous token is done with sk/sq/red/wsum- if (tid < S) { sk[tid] = ht[qk + qh * S + tid]; sq[tid] = ht[qh * S + tid]; }+ item_ct1.barrier();+ sk[tid] = ht[qk + qh * S + tid];/*DPCT1118: SYCL group functions and algorithms must be encountered inconverged control flow. You may need to adjust the code.@@ -252,7 +271,7 @@ auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(#pragma unrollfor (int r = 0; r < RPG; ++r)kv = sycl::fma(s[r], sk[rg * RPG + r], kv);- red[rg][col] = kv;+ red[rg][col_local] = kv;/*DPCT1118: SYCL group functions and algorithms must be encountered inconverged control flow. You may need to adjust the code.@@ -263,14 +282,130 @@ auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(better performance if there is no access to global memory.*/item_ct1.barrier();- const float kv_col = red[0][col] + red[1][col] + red[2][col] + red[3][col];+ const float kv_col = red[0][col_local] + red[1][col_local] + red[2][col_local] + red[3][col_local];const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head];- float o = 0.0f;#pragma unroll- for (int r = 0; r < RPG; ++r) {+ for (int r = 0; r < RPG; ++r)s[r] = sycl::fma((float)g, s[r], sk[rg * RPG + r] * delta);- o = sycl::fma(s[r], sq[rg * RPG + r], o);+ }+#pragma unroll+ for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r];+}++// S26 (STRATA_QFUSE=1): the q8_1 image of a 32-column block, written by the warp that holds those columns with+// native_quantize_q8_1_kernel's quantizer (the same XOR-tree max and sum, d = amax / 127, roundf(x / d), ds = (d, sum)).+struct GdnQ81 { sycl::half2 ds; int8_t qs[32]; };+__dpct_inline__ void gdn_q8_1_store(GdnQ81 *__restrict__ xq, size_t idx,+ float xi) {+ // no contraction: xi is a product here, and fma(a, b, shfl) would round the first sum unlike the separate+ // quantizer, which reads xi from memory (S26 harness: ds.sum differed by 1 ulp without this)+#pragma clang fp contract(off)+ float amax = sycl::fabs(xi), sum = xi;+#pragma unroll+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature+ masked sub_group function which may not be supported by all compilers or+ runtimes. You may need to adjust the code.+ */+ for (int o = 16; o > 0; o >>= 1) amax = sycl::fmax(+ amax, dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu,+ sycl::ext::oneapi::this_work_item::get_sub_group(), amax, o));+#pragma unroll+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature+ masked sub_group function which may not be supported by all compilers or+ runtimes. You may need to adjust the code.+ */+ for (int o = 16; o > 0; o >>= 1) sum +=+ dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),+ sum, o);+ const float d = amax / 127.0f;+ const int8_t q = amax == 0.0f ? 0 : sycl::round(xi / d);+ xq[idx / 32].qs[idx % 32] = q;+ if (idx % 32 == 0) xq[idx / 32].ds = sycl::half2(d, sum);+}++template <bool ALL_OUT, bool Q>+/*+DPCT1110: The total declared local variable size in device function+gdn_step_norm_multi_kernel exceeds 128 bytes and may cause high register+pressure. Consult with your hardware vendor to find the total register size+available and adjust the code, or use smaller sub-group size to avoid high+register pressure.+*/+__dpct_inline__ void gdn_step_norm_multi_kernel(+ float *__restrict__ state, const float *__restrict__ hbuf, int C,+ const float *__restrict__ gate, const float *__restrict__ beta,+ const float *__restrict__ z, const float *__restrict__ gamma, float eps,+ float *__restrict__ y, int h_k, int h_v, int T,+ const int32_t *__restrict__ n_keep, int t_out_begin,+ GdnQ81 *__restrict__ xq) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[2][S]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &sq =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<float[2][S]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &red_kv =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][S]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &red_o =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][S]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &wsum =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S / 32]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const int head = item_ct1.get_group(2);+ const int col = item_ct1.get_local_id(2);+ const int rg = item_ct1.get_local_id(1);+ const int qh = head % h_k;+ const int qk = S * h_k; // q at [0, qk), k at [qk, 2qk), v at [2qk, ...)+ const int value_dim = S * h_v;+ const int n = ALL_OUT ? T : (n_keep ? *n_keep : T);+ if (n > 0) {+ if (rg == 0) sk[0][col] = hbuf[qk + qh * S + col];+ else if (rg == 1 && (ALL_OUT || 0 >= t_out_begin)) sq[0][col] = hbuf[qh * S + col];+ }+ const float gam = (rg == 0) ? gamma[col] : 0.0f;+ float s[RPG];+ float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;+ const size_t row_stride = (size_t) h_v * S;+#pragma unroll+ /*+ DPCT1098: The '*' expression is used instead of the __ldg call. These+ two expressions do not provide the exact same functionality. Check the+ generated code for potential precision and/or performance issues.+ */+ for (int r = 0; r < RPG; ++r) s[r] = ALL_OUT ? base[r * row_stride]+ : base[r * row_stride];+ for (int t = 0; t < n; ++t) {+ const int cur = t & 1, nxt = (t + 1) & 1;+ const float* ht = hbuf + (size_t) t * C;+ const bool need_out = ALL_OUT || (t >= t_out_begin);+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ if (t + 1 < n) {+ const float* ht_next = ht + C;+ const bool need_next = ALL_OUT || (t + 1 >= t_out_begin);+ if (rg == 0) sk[nxt][col] = ht_next[qk + qh * S + col];+ else if (rg == 1 && need_next) sq[nxt][col] = ht_next[qh * S + col];}+ const float g = sycl::native::exp(gate[(size_t)t * h_v + head]);+ float kv = 0.0f;+#pragma unroll+ for (int r = 0; r < RPG; ++r)+ kv = sycl::fma(s[r], sk[cur][rg * RPG + r], kv);+ red_kv[rg][col] = kv;/*DPCT1118: SYCL group functions and algorithms must be encountered inconverged control flow. You may need to adjust the code.@@ -281,7 +416,21 @@ auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(better performance if there is no access to global memory.*/item_ct1.barrier();- red[rg][col] = o;+ const float kv_col = red_kv[0][col] + red_kv[1][col] + red_kv[2][col] + red_kv[3][col];+ const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head];+ if (!need_out) {+#pragma unroll+ for (int r = 0; r < RPG; ++r)+ s[r] = sycl::fma((float)g, s[r], sk[cur][rg * RPG + r] * delta);+ continue;+ }+ float o = 0.0f;+#pragma unroll+ for (int r = 0; r < RPG; ++r) {+ s[r] = sycl::fma((float)g, s[r], sk[cur][rg * RPG + r] * delta);+ o = sycl::fma(s[r], sq[cur][rg * RPG + r], o);+ }+ red_o[rg][col] = o;/*DPCT1118: SYCL group functions and algorithms must be encountered inconverged control flow. You may need to adjust the code.@@ -294,11 +443,13 @@ auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(item_ct1.barrier();float oc = 0.0f, sq_part = 0.0f;if (rg == 0) {- oc = (red[0][col] + red[1][col] + red[2][col] + red[3][col]) *+ oc = (red_o[0][col] + red_o[1][col] + red_o[2][col] ++ red_o[3][col]) *sycl::rsqrt((float)S);sq_part = oc * oc;}- if (t < t_out_begin) continue; // a replayed token: its state update is needed, its output is not+ // every thread takes the shuffles, as the single-token kernel does: inside the `rg == 0` branch hipcc on+ // gfx1151 gave another rounding for 3% of the outputs (gdn_parity section 5 on Aurora)/*DPCT1108: '__shfl_xor_sync' was migrated with the experimental featuremasked sub_group function which may not be supported by all compilers or@@ -309,7 +460,7 @@ runtimes. You may need to adjust the code.dpct::experimental::permute_sub_group_by_xor(0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),sq_part, o2);- if ((tid & 31) == 0) wsum[tid >> 5] = sq_part;+ if (rg == 0 && (col & 31) == 0) wsum[col >> 5] = sq_part;/*DPCT1118: SYCL group functions and algorithms must be encountered inconverged control flow. You may need to adjust the code.@@ -324,16 +475,308 @@ runtimes. You may need to adjust the code.const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];const float scale = sycl::rsqrt(ss / (float)S + eps);const float zz = z[(size_t) t * value_dim + head * S + col];+ const float yv =+ oc * scale * gam * (1.0f / (1.0f + sycl::native::exp(-zz)));+ y[(size_t) t * value_dim + head * S + col] = yv;+ if constexpr (Q) gdn_q8_1_store(xq, (size_t) (t - t_out_begin) * value_dim + head * S + col, yv);+ }+ }+ if (!ALL_OUT && n_keep != nullptr && n > 0) {+#pragma unroll+ for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r];+ }+}++// S25 (STRATA_GDN_SPLIT=1): the same recurrence with each head's 128 state columns over 4 blocks of 32 columns+// (128 threads: the same (column, row group) threads, each with the same 32 state rows), so 4x the blocks of+// gdn_step_norm_multi_kernel - which ran one 512-thread block per head (32 blocks) and read the 2 MB state of a layer+// at ~60 GB/s. Every column's arithmetic is the original's; the output norm, which needs all 128 columns of a head,+// moves to gdn_out_norm_kernel: this kernel leaves the unnormalized output `oc` in y and the second kernel sums the+// squares by the same warps (columns 32w..32w+31, the same butterfly) in the same order.+// S26: OUT = false (the commit, whose outputs nobody reads) drops the output reduction and its two barriers; the+// norm kernel below has the old kernel's code shape (S x RG threads, rg 0 holding oc), which makes it bitwise equal -+// the 128-thread version differed from the old kernel by 1 ulp in ~7% of the outputs.+constexpr int GS_COLS = 32;+template <bool OUT>+/*+DPCT1110: The total declared local variable size in device function+gdn_step_split_kernel exceeds 128 bytes and may cause high register pressure.+Consult with your hardware vendor to find the total register size available and+adjust the code, or use smaller sub-group size to avoid high register pressure.+*/+__dpct_inline__ void+gdn_step_split_kernel(float *__restrict__ state, const float *__restrict__ hbuf,+ int C, const float *__restrict__ gate,+ const float *__restrict__ beta, float *__restrict__ y,+ int h_k, int h_v, int T,+ const int32_t *__restrict__ n_keep, int t_out_begin) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &sq = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &red = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ float[RG][GS_COLS]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const int head = item_ct1.get_group(2);+ const int c0 = item_ct1.get_group(1) * GS_COLS;+ const int lc = item_ct1.get_local_id(2); // local column+ const int col = c0 + lc;+ const int rg = item_ct1.get_local_id(1);+ const int tid = rg * GS_COLS + lc;+ const int qh = head % h_k;+ const int qk = S * h_k;+ const int value_dim = S * h_v;+ const int n = n_keep ? *n_keep : T;+ float s[RPG];+ float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;+ const size_t row_stride = (size_t) h_v * S;+#pragma unroll+ for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride];+ for (int t = 0; t < n; ++t) {+ const float* ht = hbuf + (size_t) t * C;+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ if (tid < S) { sk[tid] = ht[qk + qh * S + tid]; sq[tid] = ht[qh * S + tid]; }+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ const float g = sycl::native::exp(gate[(size_t)t * h_v + head]);+ float kv = 0.0f;+#pragma unroll+ for (int r = 0; r < RPG; ++r)+ kv = sycl::fma(s[r], sk[rg * RPG + r], kv);+ red[rg][lc] = kv;+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ const float kv_col = red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc];+ const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head];+ float o = 0.0f;+#pragma unroll+ for (int r = 0; r < RPG; ++r) {+ s[r] = sycl::fma((float)g, s[r], sk[rg * RPG + r] * delta);+ o = sycl::fma(s[r], sq[rg * RPG + r], o);+ }+ if (!OUT) continue;+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ red[rg][lc] = o;+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ if (rg == 0 && t >= t_out_begin)y[(size_t)t * value_dim + head * S + col] =- oc * scale * gamma[col] *- (1.0f / (1.0f + sycl::native::exp(-zz)));+ (red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc]) *+ sycl::rsqrt((float)S);+ }+ if (n_keep != nullptr && n > 0) {+#pragma unroll+ for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r];+ }+}+++// S26: the state-only replay (the commit) with its per-token inputs prefetched - gate, beta and the v column of every+// row up front, the next row's k / q while the current one computes. The arithmetic and its order are+// gdn_step_split_kernel<false>'s (gfx1151 harness: state bitwise equal; 44.5 -> 39.1 us at 1 row, 47.4 -> 40.5 at 2,+// 53.8 -> 42.9 at 4, h_v 48). With outputs the prefetch lost (register pressure), so the window keeps the plain split.+template <int MAXT>+/*+DPCT1110: The total declared local variable size in device function+gdn_state_replay_kernel exceeds 128 bytes and may cause high register pressure.+Consult with your hardware vendor to find the total register size available and+adjust the code, or use smaller sub-group size to avoid high register pressure.+*/+__dpct_inline__ void gdn_state_replay_kernel(+ float *__restrict__ state, const float *__restrict__ hbuf, int C,+ const float *__restrict__ gate, const float *__restrict__ beta, int h_k,+ int h_v, int T, const int32_t *__restrict__ n_keep) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &sq = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &red = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ float[RG][GS_COLS]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const int head = item_ct1.get_group(2);+ const int c0 = item_ct1.get_group(1) * GS_COLS;+ const int lc = item_ct1.get_local_id(2);+ const int col = c0 + lc;+ const int rg = item_ct1.get_local_id(1);+ const int tid = rg * GS_COLS + lc;+ const int qh = head % h_k;+ const int qk = S * h_k;+ const int n = n_keep ? *n_keep : T;+ float gv[MAXT], bv[MAXT], vv[MAXT];+#pragma unroll+ for (int t = 0; t < MAXT; ++t) {+ if (t < n) {+ gv[t] = gate[(size_t) t * h_v + head];+ bv[t] = beta[(size_t) t * h_v + head];+ vv[t] = hbuf[(size_t) t * C + 2 * qk + head * S + col];+ }+ }+ float kn = 0.0f, qn = 0.0f;+ if (n > 0) { kn = hbuf[qk + qh * S + tid]; qn = hbuf[qh * S + tid]; }+ float s[RPG];+ float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;+ const size_t row_stride = (size_t) h_v * S;+#pragma unroll+ for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride];+#pragma unroll+ for (int t = 0; t < MAXT; ++t) {+ if (t >= n) break;+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ sk[tid] = kn; sq[tid] = qn;+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ if (t + 1 < n) {+ const float* hn = hbuf + (size_t) (t + 1) * C;+ kn = hn[qk + qh * S + tid]; qn = hn[qh * S + tid];+ }+ const float g = sycl::native::exp(gv[t]);+ float kv = 0.0f;+#pragma unroll+ for (int r = 0; r < RPG; ++r)+ kv = sycl::fma(s[r], sk[rg * RPG + r], kv);+ red[rg][lc] = kv;+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ const float kv_col = red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc];+ const float delta = (vv[t] - g * kv_col) * bv[t];+ float o = 0.0f; // unused: kept because the measured code had it (without it: 51 us instead of 39 at 1 row)+#pragma unroll+ for (int r = 0; r < RPG; ++r) {+ s[r] = sycl::fma((float)g, s[r], sk[rg * RPG + r] * delta);+ o = sycl::fma(s[r], sq[rg * RPG + r], o);}+ (void) o;}if (n_keep != nullptr && n > 0) {#pragma unrollfor (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r];}}+// y = oc * rsqrt(mean(oc^2) + eps) * gamma * sigmoid(z) per head and token: gdn_step_norm_multi_kernel's tail with its+// code shape (S x RG threads; rg 0 holds oc, the other row groups contribute 0 to wsum), reading oc from y+template <bool Q>+__dpct_inline__ void gdn_out_norm_kernel(+ const float *__restrict__ z, const float *__restrict__ gamma, float eps,+ float *__restrict__ y, int h_v, int T, const int32_t *__restrict__ n_keep,+ int t_out_begin, GdnQ81 *__restrict__ xq) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+auto &wsum =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S * RG / 32]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const int head = item_ct1.get_group(2),+ t = item_ct1.get_group(1) + t_out_begin,+ col = item_ct1.get_local_id(2), rg = item_ct1.get_local_id(1);+ const int tid = rg * S + col;+ const int n = n_keep ? *n_keep : T;+ if (t >= n) return;+ const int value_dim = S * h_v;+ float oc = 0.0f, sq_part = 0.0f;+ if (rg == 0) {+ oc = y[(size_t) t * value_dim + head * S + col];+ sq_part = oc * oc;+ }+ /*+DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature+masked sub_group function which may not be supported by all compilers or+runtimes. You may need to adjust the code.+*/+#pragma unroll+ for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part +=+ dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),+ sq_part, o2);+ if ((tid & 31) == 0) wsum[tid >> 5] = sq_part;+ /*+ 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.+ */+ item_ct1.barrier();+ if (rg == 0) {+ const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];+ const float scale = sycl::rsqrt(ss / (float)S + eps);+ const float zz = z[(size_t) t * value_dim + head * S + col];+ if constexpr (Q) {+ const float yv = oc * scale * gamma[col] *+ (1.0f / (1.0f + sycl::native::exp(-zz)));+ y[(size_t) t * value_dim + head * S + col] = yv;+ gdn_q8_1_store(xq, (size_t) (t - t_out_begin) * value_dim + head * S + col, yv);+ } else {+ y[(size_t)t * value_dim + head * S + col] =+ oc * scale * gamma[col] *+ (1.0f / (1.0f + sycl::native::exp(-zz)));+ }+ }+}__dpct_inline__ void embedding_gather_dev_kernel(const uint8_t *__restrict__ codes, const float *__restrict__ scales,@@ -524,11 +967,19 @@ mtp_select_kernel(const float *__restrict__ R_src, int64_t stride,i < stride; i += (int64_t)item_ct1.get_group_range(2) *item_ct1.get_local_range(2))R_dst[i] = R_src[(size_t) row * stride + i];+ item_ct1.barrier(sycl::access::fence_space::local_space);if (item_ct1.get_group(2) == 0 && item_ct1.get_local_id(2) == 0) {const int32_t tok = ids[row];*tok_dst = tok;- if (out != nullptr) ((volatile int32_t*) out)[j] = tok;if (probs != nullptr && out_p != nullptr) ((volatile float*) out_p)[j] = probs[row];+ /*+ 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 (out != nullptr) ((volatile int32_t*) out)[j] = tok;}}@@ -544,6 +995,13 @@ __dpct_inline__ void dense_steps_kernel(const int32_t *__restrict__ cells,steps[i * 4 + 3] = c + 1;}+// --pipeline-windows: the drafter's chain, teacher forced (see force_token)+__dpct_inline__ void force_token_kernel(int32_t *tok, const int32_t *force,+ int j) {+ const int32_t f = ((const volatile int32_t*) force)[j];+ if (f >= 0) *tok = f;+}+} // namespacevoid fetch_blobs(const unsigned long long* src, const int32_t* n, uint8_t* dst, int64_t blob_bytes, int cap, void* stream) {@@ -630,6 +1088,47 @@ void ident_hits(const int32_t* ids, int n, int32_t* slot, int32_t* dst, int32_t*check("ident_hits");}+namespace {+__dpct_inline__ void+copy_row_to_first_kernel(const int32_t *__restrict__ row_dev, float *a,+ int64_t a_n, float *b, int64_t b_n, float *c,+ int64_t c_n) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int64_t row = *row_dev;+ if (row == 0) return;+ const int64_t i0 = (int64_t)item_ct1.get_group(2) *+ item_ct1.get_local_range(2) ++ item_ct1.get_local_id(2),+ st = (int64_t)item_ct1.get_group_range(2) *+ item_ct1.get_local_range(2);+#pragma unroll+ for (int64_t i = i0; i < a_n; i += st) a[i] = a[row * a_n + i];+#pragma unroll+ for (int64_t i = i0; i < b_n; i += st) b[i] = b[row * b_n + i];+#pragma unroll+ for (int64_t i = i0; i < c_n; i += st) c[i] = c[row * c_n + i];+}+} // namespace++void copy_row_to_first(const int32_t* row_dev, float* a, int64_t a_n, float* b, int64_t b_n, float* c, int64_t c_n,+ void* stream) {+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<+ dpct_kernel_name<class copy_row_to_first_kernel_993785>>(+ sycl::nd_range<3>(sycl::range(1, 1, 16) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ copy_row_to_first_kernel(row_dev, a, a_n, b, b_n, c, c_n);+ });+ }+ check("copy_row_to_first");+}+void mtp_select(const float* R_src, int64_t R_stride, const int32_t* ids, const int32_t* row_dev, float* R_dst,int32_t* tok_dst, int32_t* out, int j, void* stream, const float* probs, float* out_p) {{@@ -638,8 +1137,7 @@ void mtp_select(const float* R_src, int64_t R_stride, const int32_t* ids, conststrata::q_of(stream)->parallel_for<dpct_kernel_name<class mtp_select_kernel_4611fe>>(- sycl::nd_range<3>(sycl::range(1, 1, 16) *- sycl::range(1, 1, 256),+ sycl::nd_range<3>(sycl::range(1, 1, 256),sycl::range(1, 1, 256)),exp_props, [=](sycl::nd_item<3> item_ct1) {mtp_select_kernel(R_src, R_stride, ids, row_dev, R_dst,@@ -649,97 +1147,452 @@ void mtp_select(const float* R_src, int64_t R_stride, const int32_t* ids, constcheck("mtp_select");}-void gather_rows(const uint8_t* src, int64_t row_bytes, const int32_t* ids, int64_t n, uint8_t* dst, void* stream) {- dpct::queue_ptr s = strata::q_of(stream);- if (row_bytes % 16 == 0)- {- auto exp_props = sycl::ext::oneapi::experimental::properties{- sycl::ext::oneapi::experimental::use_root_sync};-- s->submit([&](sycl::handler &cgh) {- long long row_bytes_ct1 = row_bytes / 16;-- cgh.parallel_for<- dpct_kernel_name<class gather_rows_kernel_d4a04b, sycl::uint4>>(- sycl::nd_range<3>(sycl::range(1, 1, 48 * 8) *- sycl::range(1, 1, 256),- sycl::range(1, 1, 256)),- exp_props, [=](sycl::nd_item<3> item_ct1) {- gather_rows_kernel((const sycl::uint4 *)src, row_bytes_ct1,- ids, n, (sycl::uint4 *)dst);- });- });- } else if (row_bytes % 4 == 0)- {- auto exp_props = sycl::ext::oneapi::experimental::properties{- sycl::ext::oneapi::experimental::use_root_sync};-- s->submit([&](sycl::handler &cgh) {- long long row_bytes_ct1 = row_bytes / 4;-- cgh.parallel_for<- dpct_kernel_name<class gather_rows_kernel_7960b2, uint32_t>>(- sycl::nd_range<3>(sycl::range(1, 1, 48 * 8) *- sycl::range(1, 1, 256),- sycl::range(1, 1, 256)),- exp_props, [=](sycl::nd_item<3> item_ct1) {- gather_rows_kernel((const uint32_t *)src, row_bytes_ct1,- ids, n, (uint32_t *)dst);- });- });- } else {- auto exp_props = sycl::ext::oneapi::experimental::properties{- sycl::ext::oneapi::experimental::use_root_sync};+void force_token(int32_t* tok, const int32_t* force, int j, void* stream) {+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<dpct_kernel_name<class force_token_kernel_a9fa72>>(+ sycl::nd_range<3>(sycl::range(1, 1, 1), sycl::range(1, 1, 1)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ force_token_kernel(tok, force, j);+ });+ }+ check("force_token");+}++void gather_rows(const uint8_t* src, int64_t row_bytes, const int32_t* ids, int64_t n, uint8_t* dst, void* stream) {+ dpct::queue_ptr s = strata::q_of(stream);+ if (row_bytes % 16 == 0)+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ s->submit([&](sycl::handler &cgh) {+ long long row_bytes_ct1 = row_bytes / 16;++ cgh.parallel_for<+ dpct_kernel_name<class gather_rows_kernel_b3ae5a, sycl::uint4>>(+ sycl::nd_range<3>(sycl::range(1, 1, 48 * 8) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ gather_rows_kernel((const sycl::uint4 *)src, row_bytes_ct1,+ ids, n, (sycl::uint4 *)dst);+ });+ });+ } else if (row_bytes % 4 == 0)+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ s->submit([&](sycl::handler &cgh) {+ long long row_bytes_ct1 = row_bytes / 4;++ cgh.parallel_for<+ dpct_kernel_name<class gather_rows_kernel_f256ac, uint32_t>>(+ sycl::nd_range<3>(sycl::range(1, 1, 48 * 8) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ gather_rows_kernel((const uint32_t *)src, row_bytes_ct1,+ ids, n, (uint32_t *)dst);+ });+ });+ } else {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ s->parallel_for<+ dpct_kernel_name<class gather_rows_kernel_c5b171, uint8_t>>(+ sycl::nd_range<3>(sycl::range(1, 1, 48 * 8) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ gather_rows_kernel(src, row_bytes, ids, n, dst);+ });+ }+ check("gather_rows");+}++void map_ids(int32_t* ids, const int32_t* table, int n, void* stream) {+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<dpct_kernel_name<class map_ids_kernel_43a113>>(+ sycl::nd_range<3>(sycl::range(1, 1, 64), sycl::range(1, 1, 64)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ map_ids_kernel(ids, table, n);+ });+ }+ check("map_ids");+}++void row_top_prob(const float* logits, int n_rows, int n_vocab, const int32_t* ids, float* probs, void* stream) {+ /*+ 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.+ Adjust the work-group size if needed.+ */+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<dpct_kernel_name<class row_top_prob_kernel_6adbe2>>(+ sycl::nd_range<3>(sycl::range(1, 1, n_rows) *+ sycl::range(1, 1, 1024),+ sycl::range(1, 1, 1024)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ row_top_prob_kernel(logits, n_vocab, ids, probs);+ });+ }+ check("row_top_prob");+}++#if !defined(__HIPCC__) // warp-32 kernels: an AMD card keeps the one-block row_top_prob and sampler_greedy_kernel+namespace {++constexpr int kArgMaxBlocks = 128, kArgThreads = 256, kTopBlocks = 8;++// the larger value, on equality the lower index: sampler_greedy_kernel's order+__dpct_inline__ void arg_take(float ov, int oi, float &bv, int &bi) {+ if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }+}++// a block's (value, index) pick, in thread 0; `none` is the index of no candidate+__dpct_inline__ void arg_block(float &bv, int &bi, int none) {+ /*+ DPCT1115: The sycl::ext::oneapi::group_local_memory_for_overwrite is+ used to allocate group-local memory at the none kernel functor scope of a+ work-group data parallel kernel. You may need to adjust the code.+ */+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+auto &sv = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ /*+ DPCT1115: The sycl::ext::oneapi::group_local_memory_for_overwrite is+ used to allocate group-local memory at the none kernel functor scope of a+ work-group data parallel kernel. You may need to adjust the code.+ */+ auto &si = *sycl::ext::oneapi::group_local_memory_for_overwrite<int[32]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ for (int off = 16; off > 0; off >>= 1) {+ /*+ DPCT1108: '__shfl_down_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ /*+ DPCT1121: Make sure that the "bv" which is used in the SYCL group+ function/algorithm is initialized.+ */+ const float ov = dpct::experimental::shift_sub_group_left(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), bv,+ off);+ /*+ DPCT1108: '__shfl_down_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ /*+ DPCT1121: Make sure that the "bi" which is used in the SYCL group+ function/algorithm is initialized.+ */+ const int oi = dpct::experimental::shift_sub_group_left(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), bi,+ off);+ arg_take(ov, oi, bv, bi);+ }+ const int warp = (int)(item_ct1.get_local_id(2) >> 5),+ lane = (int)(item_ct1.get_local_id(2) & 31);+ if (lane == 0) { sv[warp] = bv; si[warp] = bi; }+ /*+ 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.+ */+ item_ct1.barrier();+ if (warp == 0) {+ const int nw = (int)(item_ct1.get_local_range(2) >> 5);+ bv = lane < nw ? sv[lane] : sycl::bit_cast<float, int>(0xff800000);+ bi = lane < nw ? si[lane] : none;+ for (int off = 16; off > 0; off >>= 1) {+ /*+ DPCT1108: '__shfl_down_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ /*+ DPCT1121: Make sure that the "bv" which is used in the SYCL+ group function/algorithm is initialized.+ */+ const float ov = dpct::experimental::shift_sub_group_left(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),+ bv, off);+ /*+ DPCT1108: '__shfl_down_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ /*+ DPCT1121: Make sure that the "bi" which is used in the SYCL+ group function/algorithm is initialized.+ */+ const int oi = dpct::experimental::shift_sub_group_left(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),+ bi, off);+ arg_take(ov, oi, bv, bi);+ }+ }+}++// A row's scratch, whatever the launch's row count (one scratch serves windows of every size): its counter, then+// the blocks' values and indices.+struct ArgRow {+ unsigned counter;+ unsigned pad[3];+ float v[kArgMaxBlocks];+ int i[kArgMaxBlocks];+};++// grid (blocks, rows): block b scans [b * per_block, +per_block) of its row+__dpct_inline__ void argmax_rows_kernel(const float *__restrict__ logits, int n,+ int per_block,+ ArgRow *__restrict__ rows,+ int32_t *out) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int row = (int)item_ct1.get_group(1), b = (int)item_ct1.get_group(2),+ nb = (int)item_ct1.get_group_range(2);+ unsigned* counter = &rows[row].counter;+ float* pv = rows[row].v;+ int* pi = rows[row].i;+ const float* l = logits + (size_t) row * n;+ const int lo = b * per_block, hi = sycl::min(n, lo + per_block);+ float bv = sycl::bit_cast<float, int>(0xff800000); // -inf+ int bi = n;+ for (int v = lo + (int)item_ct1.get_local_id(2); v < hi;+ v += (int)item_ct1.get_local_range(2)) {+ const float s = l[v];+ if (s > bv) { bv = s; bi = v; }+ }+ arg_block(bv, bi, n);+ auto &last = *sycl::ext::oneapi::group_local_memory_for_overwrite<bool>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ if (item_ct1.get_local_id(2) == 0) {+ pv[b] = bv;+ pi[b] = bi;+ /*+ 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::device);+ last =+ dpct::atomic_fetch_add<sycl::access::address_space::generic_space>(+ counter, 1u) == (unsigned)(nb - 1);+ }+ /*+ 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.+ */+ item_ct1.barrier();+ if (!last) return;+ /*+ 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::device);+ bv = sycl::bit_cast<float, int>(0xff800000);+ bi = n;+ if ((int)item_ct1.get_local_id(2) < nb) {+ bv = ((volatile const float *)pv)[item_ct1.get_local_id(2)];+ bi = ((volatile const int *)pi)[item_ct1.get_local_id(2)];+ }+ arg_block(bv, bi, n);+ if (item_ct1.get_local_id(2) == 0) {+ out[row] = bi < n ? bi : 0; // no value above -inf: 0, as the one-block kernel+ *counter = 0;+ }+}++// a row's top-probability scratch: its counter, then its 32 warps' sums+struct TopRow {+ unsigned counter;+ unsigned pad[3];+ float parts[32];+};++// grid (kTopBlocks, rows), 1024 / kTopBlocks threads: thread j of block b is row_top_prob's thread b * blockDim + j+__dpct_inline__ void row_top_prob_split_kernel(const float *__restrict__ logits,+ int n_vocab,+ const int32_t *__restrict__ ids,+ float *__restrict__ probs,+ TopRow *__restrict__ rows) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int row = (int)item_ct1.get_group(1);+ float* parts = rows[row].parts;+ const float* l = logits + (size_t) row * n_vocab;+ const float m = l[ids[row]];+ const int vt = (int)(item_ct1.get_group(2) * item_ct1.get_local_range(2) ++ item_ct1.get_local_id(2));+ float s = 0.0f;+#pragma unroll+ for (int i = vt; i < n_vocab; i += 1024) s += sycl::native::exp(l[i] - m);+ /*+DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature+masked sub_group function which may not be supported by all compilers or+runtimes. You may need to adjust the code.+*/+#pragma unroll+ for (int o = 16; o > 0; o >>= 1) s +=+ dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), s,+ o);+ if ((item_ct1.get_local_id(2) & 31) == 0) parts[vt >> 5] = s;+ /*+ 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::device);+ /*+ 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.+ */+ item_ct1.barrier();+ auto &last = *sycl::ext::oneapi::group_local_memory_for_overwrite<bool>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ if (item_ct1.get_local_id(2) == 0) last =+ dpct::atomic_fetch_add<sycl::access::address_space::generic_space>(+ &rows[row].counter, 1u) ==+ (unsigned)(item_ct1.get_group_range(2) - 1);+ /*+ 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.+ */+ item_ct1.barrier();+ if (!last || item_ct1.get_local_id(2) != 0) return;+ /*+ 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::device);+ float tot = 0.0f;+#pragma unroll+ for (int w = 0; w < 32; ++w) tot += ((volatile const float *)parts)[w];+ probs[row] = 1.0f / tot;+ rows[row].counter = 0;+}++} // namespace- s->parallel_for<- dpct_kernel_name<class gather_rows_kernel_6148af, uint8_t>>(- sycl::nd_range<3>(sycl::range(1, 1, 48 * 8) *- sycl::range(1, 1, 256),- sycl::range(1, 1, 256)),- exp_props, [=](sycl::nd_item<3> item_ct1) {- gather_rows_kernel(src, row_bytes, ids, n, dst);- });- }- check("gather_rows");-}+uint64_t argmax_rows_scratch_bytes(int n_rows) { return (uint64_t) n_rows * sizeof(ArgRow); }-void map_ids(int32_t* ids, const int32_t* table, int n, void* stream) {+void argmax_rows(const float* logits, int n_rows, int n, void* scratch, int32_t* out, void* stream) {+ if (n_rows <= 0) return;+ const int nb = std::min(kArgMaxBlocks, std::max(1, (n + 4095) / 4096));+ const int per_block = (n + nb - 1) / nb;{auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class map_ids_kernel_43a113>>(- sycl::nd_range<3>(sycl::range(1, 1, 64), sycl::range(1, 1, 64)),- exp_props, [=](sycl::nd_item<3> item_ct1) {- map_ids_kernel(ids, table, n);- });+ ->parallel_for<dpct_kernel_name<class argmax_rows_kernel_d5bcf6>>(+ sycl::nd_range<3>(+ sycl::range(1, (unsigned)n_rows, (unsigned)nb) *+ sycl::range(1, 1, kArgThreads),+ sycl::range(1, 1, kArgThreads)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ argmax_rows_kernel(logits, n, per_block,+ (ArgRow *)scratch, out);+ });}- check("map_ids");+ check("argmax_rows");}-void row_top_prob(const float* logits, int n_rows, int n_vocab, const int32_t* ids, float* probs, void* stream) {- /*- 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.- Adjust the work-group size if needed.- */+uint64_t row_top_prob_scratch_bytes(int n_rows) { return (uint64_t) n_rows * sizeof(TopRow); }++void row_top_prob_split(const float* logits, int n_rows, int n_vocab, const int32_t* ids, float* probs, void* scratch,+ void* stream) {+ if (n_rows <= 0) return;{auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class row_top_prob_kernel_6adbe2>>(- sycl::nd_range<3>(sycl::range(1, 1, n_rows) *- sycl::range(1, 1, 1024),- sycl::range(1, 1, 1024)),+ ->parallel_for<+ dpct_kernel_name<class row_top_prob_split_kernel_9495b0>>(+ sycl::nd_range<3>(sycl::range(1, (unsigned)n_rows, kTopBlocks) *+ sycl::range(1, 1, 1024 / kTopBlocks),+ sycl::range(1, 1, 1024 / kTopBlocks)),exp_props,[=](sycl::nd_item<3> item_ct1)[[sycl::reqd_sub_group_size(32)]] {- row_top_prob_kernel(logits, n_vocab, ids, probs);+ row_top_prob_split_kernel(logits, n_vocab, ids, probs,+ (TopRow *)scratch);});}- check("row_top_prob");+ check("row_top_prob_split");+}+#else+uint64_t argmax_rows_scratch_bytes(int) { return 0; }+void argmax_rows(const float*, int, int, void*, int32_t*, void*) {+ std::fprintf(stderr, "argmax_rows: not built for this backend\n");+ std::exit(1);+}+uint64_t row_top_prob_scratch_bytes(int) { return 0; }+void row_top_prob_split(const float* logits, int n_rows, int n_vocab, const int32_t* ids, float* probs, void*,+ void* stream) {+ row_top_prob(logits, n_rows, n_vocab, ids, probs, stream);+}+#endif++bool multi_block_head_ops() {+#if defined(__HIPCC__)+ return false;+#else+ static const bool on = [] {+ const char* v = std::getenv("STRATA_MULTI_BLOCK_ARGMAX");+ return v == nullptr || std::atoi(v) != 0;+ }();+ return on;+#endif+}++bool argmax_rows_wanted() try {+#if defined(__HIPCC__)+ return false;+#else+ // sm_80 to sm_89: sample_tokens' greedy pick there is the one-block kernel (sm_90+ has the cluster kernel)+ static const bool want = [] {+ int dev = 0, major = 0;+ if (DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()) != 0 ||+ DPCT_CHECK_ERROR(+ major = dpct::get_device(dev).get_major_version()) != 0)+ return false;+ return major == 8;+ }();+ return want && multi_block_head_ops();+#endif+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);}namespace {@@ -802,8 +1655,9 @@ void dense_steps(const int32_t* cells, int n, int32_t* steps, void* stream) {}void gdn_conv_l2_multi(const float* history, const float* qkv, const float* conv_w, float* h, int channels,- int qk_heads, float eps, int n_tok, void* stream, int t_begin) {- if (!history || !qkv || !conv_w || !h || channels % S != 0 || n_tok < 1 || n_tok > kVerifyMaxT) {+ int qk_heads, float eps, int n_tok, void* stream, int t_begin, bool commit) {+ if (!history || !qkv || !conv_w || !h || channels % S != 0 || n_tok < 1 || n_tok > kVerifyMaxT ||+ (commit && (n_tok != 1 || t_begin != 0))) {std::fprintf(stderr, "gdn_conv_l2_multi: invalid arguments\n");std::exit(1);}@@ -821,9 +1675,9 @@ void gdn_conv_l2_multi(const float* history, const float* qkv, const float* convexp_props,[=](sycl::nd_item<3> item_ct1)[[sycl::reqd_sub_group_size(32)]] {- gdn_conv_l2_multi_kernel(history, qkv, conv_w, h,- channels, qk_heads, eps,- t_begin);+ gdn_conv_l2_multi_kernel(+ const_cast<float *>(history), qkv, conv_w, h,+ channels, qk_heads, eps, t_begin, commit);});}check("gdn_conv_l2_multi");@@ -854,55 +1708,336 @@ void gdn_ab_multi(const float* x, const uint16_t* w_alpha, const uint16_t* w_betstd::fprintf(stderr, "gdn_ab_multi: invalid arguments\n");std::exit(1);}- {+ const unsigned blocks = (unsigned) ((2 * h_v + 1) / 2);+ dpct::queue_ptr st = strata::q_of(stream);+ switch (n_tok) {+ case 1: {auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class gdn_ab_multi_kernel_34dcce>>(- sycl::nd_range<3>(- sycl::range(1, 1, (unsigned)((2 * h_v + 7) / 8)) *- sycl::range(1, 1, 256),- sycl::range(1, 1, 256)),- exp_props,- [=](sycl::nd_item<3> item_ct1)- [[sycl::reqd_sub_group_size(32)]] {- gdn_ab_multi_kernel(x, w_alpha, w_beta, dt, ssm_a, gate,- beta, n_embd, h_v, n_tok);- });+ st->parallel_for<+ dpct_kernel_name<class gdn_ab_multi_kernel_34dcce,+ dpct_kernel_scalar<1>, dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, 1, 64),+ sycl::range(1, 1, 64)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ gdn_ab_multi_kernel<1, true>(x, w_alpha, w_beta, dt, ssm_a,+ gate, beta, n_embd, h_v, n_tok);+ });+ } break;+ case 2: {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ st->parallel_for<+ dpct_kernel_name<class gdn_ab_multi_kernel_34dcce,+ dpct_kernel_scalar<2>, dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, 1, 64),+ sycl::range(1, 1, 64)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ gdn_ab_multi_kernel<2, true>(x, w_alpha, w_beta, dt, ssm_a,+ gate, beta, n_embd, h_v, n_tok);+ });+ } break;+ case 3: {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ st->parallel_for<+ dpct_kernel_name<class gdn_ab_multi_kernel_34dcce,+ dpct_kernel_scalar<3>, dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, 1, 64),+ sycl::range(1, 1, 64)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ gdn_ab_multi_kernel<3, true>(x, w_alpha, w_beta, dt, ssm_a,+ gate, beta, n_embd, h_v, n_tok);+ });+ } break;+ case 4: {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ st->parallel_for<+ dpct_kernel_name<class gdn_ab_multi_kernel_34dcce,+ dpct_kernel_scalar<4>, dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, 1, 64),+ sycl::range(1, 1, 64)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ gdn_ab_multi_kernel<4, true>(x, w_alpha, w_beta, dt, ssm_a,+ gate, beta, n_embd, h_v, n_tok);+ });+ } break;+ case 5: {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ st->parallel_for<+ dpct_kernel_name<class gdn_ab_multi_kernel_34dcce,+ dpct_kernel_scalar<5>, dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, 1, 64),+ sycl::range(1, 1, 64)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ gdn_ab_multi_kernel<5, true>(x, w_alpha, w_beta, dt, ssm_a,+ gate, beta, n_embd, h_v, n_tok);+ });+ } break;+ case 6: {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ st->parallel_for<+ dpct_kernel_name<class gdn_ab_multi_kernel_34dcce,+ dpct_kernel_scalar<6>, dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, 1, 64),+ sycl::range(1, 1, 64)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ gdn_ab_multi_kernel<6, true>(x, w_alpha, w_beta, dt, ssm_a,+ gate, beta, n_embd, h_v, n_tok);+ });+ } break;+ default: {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ st->parallel_for<dpct_kernel_name<class gdn_ab_multi_kernel_34dcce,+ dpct_kernel_scalar<kVerifyMaxT>,+ dpct_kernel_scalar<false>>>(+ sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, 1, 64),+ sycl::range(1, 1, 64)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {+ gdn_ab_multi_kernel<kVerifyMaxT, false>(x, w_alpha, w_beta, dt,+ ssm_a, gate, beta,+ n_embd, h_v, n_tok);+ });+ } break;}check("gdn_ab_multi");}void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta,const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok,- const int32_t* n_keep, void* stream, int t_out_begin) {+ const int32_t* n_keep, void* stream, int t_out_begin, void* xq_out) {+ GdnQ81* const xq = static_cast<GdnQ81*>(xq_out); // S26: non-null = also the outputs' q8_1 (STRATA_QFUSE)if (!state || !h || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v % h_k || n_tok < 1 ||n_tok > kVerifyMaxT) {std::fprintf(stderr, "gdn_step_norm_multi: invalid arguments\n");std::exit(1);}- /*- 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.- Adjust the work-group size if needed.- */- {+ static const bool split = [] { const char* v = std::getenv("STRATA_GDN_SPLIT"); return v && v[0] == '1'; }();+ // S26: the split runs where it is faster (gfx1151 harness, h_v 48: the commit 8-19% per call; a window of 2+ rows+ // 3-13%; one row: no gain, the old kernel stays) - bitwise equal in every case+ if (split && (t_out_begin >= n_tok || n_tok - t_out_begin >= 2)) {+ const dpct::dim3 grid((unsigned)h_v, S / GS_COLS), block(GS_COLS, RG);+ if (t_out_begin >= n_tok) { // no outputs (the commit): the state only+ /*+ 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. Adjust the work-group size if+ needed.+ */+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<+ dpct_kernel_name<class gdn_state_replay_kernel_e4d4c4,+ dpct_kernel_scalar<kVerifyMaxT>>>(+ sycl::nd_range<3>(grid * block, block), exp_props,+ [=](sycl::nd_item<3> item_ct1) {+ gdn_state_replay_kernel<kVerifyMaxT>(+ state, h, conv_channels, gate, beta, h_k, h_v,+ n_tok, n_keep);+ });+ } else {+ /*+ 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. Adjust the work-group size if+ needed.+ */+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<+ dpct_kernel_name<class gdn_step_split_kernel_83c676,+ dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(grid * block, block), exp_props,+ [=](sycl::nd_item<3> item_ct1) {+ gdn_step_split_kernel<true>(+ state, h, conv_channels, gate, beta, y, h_k,+ h_v, n_tok, n_keep, t_out_begin);+ });+ }+ const dpct::dim3 ng((unsigned)h_v, (unsigned)(n_tok - t_out_begin));+ /*+ 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. Adjust the work-group size if+ needed.+ */+ if (xq) {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<+ dpct_kernel_name<class gdn_out_norm_kernel_a650eb,+ dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(ng * sycl::range(1, RG, S),+ sycl::range(1, RG, S)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ gdn_out_norm_kernel<true>(z, gamma, eps, y, h_v,+ n_tok, n_keep,+ t_out_begin, xq);+ });+ }+ /*+ 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. Adjust the work-group size if+ needed.+ */+ else {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<+ dpct_kernel_name<class gdn_out_norm_kernel_f6dfab,+ dpct_kernel_scalar<false>>>(+ sycl::nd_range<3>(ng * sycl::range(1, RG, S),+ sycl::range(1, RG, S)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ gdn_out_norm_kernel<false>(+ z, gamma, eps, y, h_v, n_tok, n_keep,+ t_out_begin, nullptr);+ });+ }+ }+ check("gdn_step_norm_multi (split)");+ return;+ }+ static const bool commit_split = [] {+ const char* e = std::getenv("STRATA_GDN_COMMIT_SPLIT");+ return !e || e[0] != '0';+ }();+ if (commit_split && n_keep != nullptr && t_out_begin >= n_tok) {+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<+ dpct_kernel_name<class gdn_step_commit_kernel_5d9da7>>(+ sycl::nd_range<3>(sycl::range(1, 4u, (unsigned)h_v) *+ sycl::range(1, RG, 32),+ sycl::range(1, RG, 32)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ gdn_step_commit_kernel(state, h, conv_channels, gate,+ beta, h_k, h_v, n_keep);+ });+ }+ check("gdn_step_commit");+ return;+ }+ const dpct::dim3 g1((unsigned)h_v), b1(S, RG);+ const bool all_out = n_keep == nullptr && t_out_begin <= 0;+ if (xq && t_out_begin < n_tok) {+ /*+ 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. Adjust the work-group size if needed.+ */+ if (all_out) {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<dpct_kernel_name<+ class gdn_step_norm_multi_kernel_42ae26,+ dpct_kernel_scalar<true>, dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(g1 * b1, b1), exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ gdn_step_norm_multi_kernel<true, true>(+ state, h, conv_channels, gate, beta, z, gamma,+ eps, y, h_k, h_v, n_tok, nullptr, 0, xq);+ });+ }+ /*+ 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. Adjust the work-group size if needed.+ */+ else {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<dpct_kernel_name<+ class gdn_step_norm_multi_kernel_42ae26,+ dpct_kernel_scalar<false>, dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(g1 * b1, b1), exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ gdn_step_norm_multi_kernel<false, true>(+ state, h, conv_channels, gate, beta, z, gamma,+ eps, y, h_k, h_v, n_tok, n_keep, t_out_begin,+ xq);+ });+ }+ } else if (all_out) {+ /*+ 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. Adjust the work-group size if needed.+ */auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<- dpct_kernel_name<class gdn_step_norm_multi_kernel_42ae26>>(- sycl::nd_range<3>(sycl::range(1, 1, (unsigned)h_v) *- sycl::range(1, RG, S),- sycl::range(1, RG, S)),- exp_props,+ ->parallel_for<dpct_kernel_name<+ class gdn_step_norm_multi_kernel_42ae26,+ dpct_kernel_scalar<true>, dpct_kernel_scalar<false>>>(+ sycl::nd_range<3>(g1 * b1, b1), exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ gdn_step_norm_multi_kernel<true, false>(+ state, h, conv_channels, gate, beta, z, gamma, eps,+ y, h_k, h_v, n_tok, nullptr, 0, nullptr);+ });+ } else {+ /*+ 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. Adjust the work-group size if needed.+ */+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<dpct_kernel_name<+ class gdn_step_norm_multi_kernel_42ae26,+ dpct_kernel_scalar<false>, dpct_kernel_scalar<false>>>(+ sycl::nd_range<3>(g1 * b1, b1), exp_props,[=](sycl::nd_item<3> item_ct1)[[sycl::reqd_sub_group_size(32)]] {- gdn_step_norm_multi_kernel(+ gdn_step_norm_multi_kernel<false, false>(state, h, conv_channels, gate, beta, z, gamma, eps,- y, h_k, h_v, n_tok, n_keep, t_out_begin);+ y, h_k, h_v, n_tok, n_keep, t_out_begin, nullptr);});}check("gdn_step_norm_multi");@@ -922,105 +2057,211 @@ __dpct_inline__ void wait_flag_ge_kernel(const volatile uint32_t *flag,} // namespacenamespace {-inline bool plan_parallel() { // STRATA_PLAN_PARALLEL=0: thread 0 groups the entries alone (the old way)- static const bool v = std::getenv("STRATA_PLAN_PARALLEL") == nullptr || std::atoi(std::getenv("STRATA_PLAN_PARALLEL")) != 0;- return v;-}-__dpct_inline__ void resident_plan_kernel(- const int32_t *__restrict__ ids, int n, int k,- const int32_t *__restrict__ res, int n_expert, const uint8_t *cache_base,- const unsigned long long *slot_off, long long blob,- int32_t *__restrict__ pl, long long capx, uint32_t *skip, uint32_t ring,- const unsigned long long *__restrict__ mir, bool par) {-#if STRATA_PLAN_LOCAL- // SYCL port: the host's exact loop, but over a local copy of the ids and their slots. One thread reading global- // memory for every compare (n^2 of them) took 87 us per layer on the B70 - 4% of a decode round; a work-group- // of 64 loads the n <= 60 entries once, then thread 0 groups them from local memory.- auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();- auto &s_ids = *sycl::ext::oneapi::group_local_memory_for_overwrite<int32_t[64]>(item.get_group());- auto &s_res = *sycl::ext::oneapi::group_local_memory_for_overwrite<int32_t[64]>(item.get_group());- auto &s_bad = *sycl::ext::oneapi::group_local_memory_for_overwrite<int>(item.get_group());- auto &s_mir = *sycl::ext::oneapi::group_local_memory_for_overwrite<unsigned long long[64]>(item.get_group());- const int tid = (int) item.get_local_id(2);+// one thread per window entry: up to kVerifyMaxT tokens x 10 routed experts (80), so 128 (#646 had 64: a window of+// 7+ tokens lost its last entries)+constexpr int kResidentPlanMax = 128;+static_assert(kVerifyMaxT * 10 <= kResidentPlanMax, "resident_plan: one thread per entry");+// the parallel scan keeps one partial sum per warp in s_wsum[4] and packs (entries << 16 | groups) in an int+static_assert(kResidentPlanMax <= 128 && kResidentPlanMax % 32 == 0, "resident_plan: at most 4 warps");+static_assert(kResidentPlanMax < 32768, "resident_plan: the packed entry count must stay below 2^15");+/*+DPCT1110: The total declared local variable size in device function+resident_plan_kernel exceeds 128 bytes and may cause high register pressure.+Consult with your hardware vendor to find the total register size available and+adjust the code, or use smaller sub-group size to avoid high register pressure.+*/+__dpct_inline__ void+resident_plan_kernel(const int32_t *__restrict__ ids, int n, int k,+ const int32_t *__restrict__ res, int n_expert,+ const uint8_t *cache_base,+ const unsigned long long *slot_off, long long blob,+ int32_t *__restrict__ pl, long long capx, uint32_t *skip,+ uint32_t ring, const unsigned long long *__restrict__ mir,+ volatile uint32_t *plan_err) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+auto &s_ids = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ int32_t[kResidentPlanMax]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &s_excl = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ int32_t[kResidentPlanMax]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &s_wsum =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<int32_t[4]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &s_bad = *sycl::ext::oneapi::group_local_memory_for_overwrite<int>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const int tid = item_ct1.get_local_id(2);if (tid == 0) s_bad = 0;- item.barrier(sycl::access::fence_space::local_space);- for (int i = tid; i < n && i < 64; i += 64) {- const int32_t e = ids[i];- const bool valid = e >= 0 && e < n_expert;- const int32_t sl = valid ? res[e] : -1;- const unsigned long long ma = (valid && sl < 0 && mir != nullptr) ? mir[e] : 0ull; // mirrored in host memory- s_ids[i] = e;- s_res[i] = sl;- s_mir[i] = ma;- if (!valid || (sl < 0 && ma == 0)) s_bad = 1;- }- item.barrier(sycl::access::fence_space::local_space);- if (s_bad || n > 64) { if (tid == 0) *skip = 0; return; } // n > 64 never happens (kVerifyMaxT * 10 = 60); refuse rather than read past- if (par) {- // SYCL port: the grouping in parallel, one thread per entry (unitrace: thread 0 alone took 73 us per layer,- // ~3.5 ms of a decode round). The plan is the host loop's exactly: groups in order of first occurrence,- // entries in a group in index order. Entry i: L = its expert's first index; its group = the number of- // first occurrences before L; the group starts at the number of entries whose leader is before L; its- // place in the group = the number of earlier entries with the same leader.- auto &s_lead = *sycl::ext::oneapi::group_local_memory_for_overwrite<int32_t[64]>(item.get_group());- if (tid < n) {- int L = tid;- for (int j = 0; j < tid; ++j) if (s_ids[j] == s_ids[tid]) { L = j; break; }- s_lead[tid] = L;- }- item.barrier(sycl::access::fence_space::local_space);- int32_t* counts = pl;- int32_t* start = pl + 4;- int32_t* dst = start + capx + 1;- int32_t* tok = dst + capx;- const long long ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll;- unsigned long long* ptr = (unsigned long long*) (pl + ptr_off);- int32_t* start2 = pl + ptr_off + 4 * capx;- if (tid < n) {- const int L = s_lead[tid];- int g = 0, gstart = 0, pos = 0;- for (int j = 0; j < n; ++j) {- const int Lj = s_lead[j];- if (j < L && Lj == j) ++g; // first occurrences before L- if (Lj < L) ++gstart; // entries of earlier groups- if (j < tid && Lj == L) ++pos; // earlier entries of this group+ item_ct1.barrier(sycl::access::fence_space::local_space);++ int32_t eid = -1;+ int32_t slot = -1;+ unsigned long long maddr = 0; // SYCL port: a host-mirrored expert (not in VRAM): its pinned mirror, read over PCIe+ if (tid < n) {+ eid = ids[tid];+ s_ids[tid] = eid;+ slot = (eid >= 0 && eid < n_expert) ? res[eid] : -1;+ if (slot < 0 && eid >= 0 && eid < n_expert && mir != nullptr) maddr = mir[eid];+ if (slot < 0 && maddr == 0)+ dpct::atomic_fetch_or<sycl::access::address_space::generic_space>(+ &s_bad, 1);+ }+ item_ct1.barrier(sycl::access::fence_space::local_space);+ if (s_bad) {+ if (tid == 0 && skip != nullptr) *skip = 0;+ if (tid == 0 && skip == nullptr) { // #871: the all-resident graph has no host plan to fall back on+ pl[0] = 0; pl[1] = 0; pl[2] = 0; // an empty plan: no expert runs on a stale pointer+ /*+ DPCT1078: Consider replacing memory_order::acq_rel with+ memory_order::seq_cst for correctness if strong memory order+ restrictions are needed.+ */+ if (plan_err != nullptr) {+ *plan_err = 1;+ sycl::atomic_fence(sycl::memory_order::acq_rel,+ sycl::memory_scope::system);}- dst[gstart + pos] = tid;- tok[gstart + pos] = tid / k;- if (L == tid) {- const int32_t slot = s_res[tid];- ptr[g] = slot >= 0 ? (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob))- : s_mir[tid];- start[g] = gstart;+ }+ return;+ }++ int first_j = tid;+ int rank_in_group = 0;+ int count_same = 0;+ if (tid < n) {+#pragma unroll+ for (int j = 0; j < n; ++j) {+ if (s_ids[j] == eid) {+ if (j < first_j) first_j = j;+ if (j < tid) ++rank_in_group;+ ++count_same;}}- item.barrier(sycl::access::fence_space::global_and_local);- if (tid != 0) return;- int groups = 0;- for (int i = 0; i < n; ++i) groups += s_lead[i] == i;+ }+ const bool is_first = (tid < n && first_j == tid && (slot >= 0 || maddr != 0));+ const int my_cnt = is_first ? count_same : 0;+ const int my_pack = (my_cnt << 16) | (is_first ? 1 : 0);+ const int lane = tid & 31;+ const int warp = tid >> 5;+ int pref = my_pack;+#pragma unroll+ for (int d = 1; d < 32; d <<= 1) {+ /*+ DPCT1108: '__shfl_up_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ const int up = dpct::experimental::shift_sub_group_right(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),+ pref, d);+ if (lane >= d) pref += up;+ }+ s_excl[tid] = pref - my_pack;+ if (lane == 31) {+ s_wsum[warp] = pref;+ }+ /*+ 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.+ */+ item_ct1.barrier();++ int32_t* counts = pl;+ int32_t* start = pl + 4;+ int32_t* dst = start + capx + 1;+ int32_t* tok = dst + capx;+ const long long ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll;+ unsigned long long* ptr = (unsigned long long*) (pl + ptr_off);+ int32_t* start2 = pl + ptr_off + 4 * capx;++ if (is_first) {+ int tot = s_excl[tid];+#pragma unroll+ for (int w = 0; w < 4; ++w) {+ if (w < warp) tot += s_wsum[w];+ }+ const int grp_idx = tot & 0xffff;+ const int ent_start = tot >> 16;+ ptr[grp_idx] = slot >= 0 ? (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob))+ : maddr;+ start[grp_idx] = ent_start;+ }+ if (tid < n) {+ const int fj_warp = first_j >> 5;+ int fj_tot = s_excl[first_j];+#pragma unroll+ for (int w = 0; w < 4; ++w) {+ if (w < fj_warp) fj_tot += s_wsum[w];+ }+ const int out_idx = (fj_tot >> 16) + rank_in_group;+ dst[out_idx] = tid;+ tok[out_idx] = tid / k;+ }+ if (tid == 0) {+ const int groups = (s_wsum[0] + s_wsum[1] + s_wsum[2] + s_wsum[3]) & 0xffff;start[groups] = n;start2[0] = n;counts[0] = groups;counts[1] = n;counts[2] = 0;- sycl::atomic_fence(sycl::memory_order::acq_rel, sycl::memory_scope::device);- strata::sys_store(skip, ring);- return;+ if (skip != nullptr) {+ /*+ 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::device);+ strata::sys_store(skip, ring);+ }}- if (tid != 0) return;-#else- // the original: one thread, the host's exact loop over global memory- for (int i = 0; i < n; ++i) {- const int32_t e = ids[i];- if (e < 0 || e >= n_expert || res[e] < 0) { *skip = 0; return; }+}+// The same plan in one block of 128 threads (n <= 128): thread i owns entry i. Groups are the distinct experts in+// order of first occurrence; group g's entries are its occurrences in increasing i - exactly the loop above+// (S26: the one-thread loop took ~44 us per call on gfx1151, 48 per window).+void resident_plan_par_kernel(const int32_t* __restrict__ ids, int n, int k, const int32_t* __restrict__ res,+ int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off,+ long long blob, int32_t* __restrict__ pl, long long capx, uint32_t* skip,+ uint32_t ring) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+auto &s_id = *sycl::ext::oneapi::group_local_memory_for_overwrite<int32_t[128]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &s_first =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<int[128]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &s_size =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<int[128]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &s_bad = *sycl::ext::oneapi::group_local_memory_for_overwrite<int>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const int i = item_ct1.get_local_id(2);+ if (i == 0) s_bad = 0;+ item_ct1.barrier(sycl::access::fence_space::local_space);+ int32_t e = -1;+ if (i < n) {+ e = ids[i];+ s_id[i] = e;+ if (e < 0 || e >= n_expert || res[e] < 0) s_bad = 1;}-#endif-#if !STRATA_PLAN_LOCAL-#define s_ids ids-#define S_RES(i) res[ids[i]]-#else-#define S_RES(i) s_res[i]-#endif+ item_ct1.barrier(sycl::access::fence_space::local_space);+ if (s_bad) { if (i == 0) *skip = 0; return; }+ int first = i, rank = 0, size = 0;+ if (i < n) {+ for (int j = 0; j < n; ++j) {+ const bool same = s_id[j] == e;+ if (same && j < first) first = j;+ if (same && j < i) ++rank;+ size += same;+ }+ }+ if (i < n) { s_first[i] = first; s_size[i] = size; }+ /*+ 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.+ */+ item_ct1.barrier();int32_t* counts = pl;int32_t* start = pl + 4;int32_t* dst = start + capx + 1;@@ -1028,44 +2269,43 @@ __dpct_inline__ void resident_plan_kernel(const long long ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll;unsigned long long* ptr = (unsigned long long*) (pl + ptr_off);int32_t* start2 = pl + ptr_off + 4 * capx;- int groups = 0, entries = 0;- for (int i0 = 0; i0 < n; ++i0) {- bool first = true;- for (int j = 0; j < i0; ++j) if (s_ids[j] == s_ids[i0]) {- first = false; break;+ if (i < n) {+ // group of entry i = the number of first occurrences before `first`; its start = their sizes' sum+ int group = 0, gstart = 0;+#pragma unroll+ for (int j = 0; j < first; ++j)+ if (s_first[j] == j) { ++group; gstart += s_size[j]; }+ if (i == first) {+ const int32_t slot = res[e];+ ptr[group] = (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob));+ start[group] = gstart;+ }+ dst[gstart + rank] = i;+ tok[gstart + rank] = i / k;+ if (i == 0) {+ int groups = 0;+#pragma unroll+ for (int j = 0; j < n; ++j) groups += s_first[j] == j;+ start[groups] = n;+ start2[0] = n;+ counts[0] = groups;+ counts[1] = n;+ counts[2] = 0;}- if (!first) continue;- const int32_t slot = S_RES(i0);-#if STRATA_PLAN_LOCAL- ptr[groups] = slot >= 0 ? (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob))- : s_mir[i0]; // not in VRAM: its pinned host mirror, read by the expert kernels over PCIe-#else- ptr[groups] = (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob));-#endif- start[groups] = entries;- for (int i = i0; i < n; ++i)- if (s_ids[i] == s_ids[i0]) {- // an entry belongs to i0's group when its first occurrence is i0: the same expert id- dst[entries] = i;- tok[entries] = i / k;- ++entries;- }- ++groups;}- start[groups] = entries;- start2[0] = entries;- counts[0] = groups;- counts[1] = entries;- counts[2] = 0;/*DPCT1078: Consider replacing memory_order::acq_rel withmemory_order::seq_cst for correctness if strong memory order restrictionsare needed.*/sycl::atomic_fence(sycl::memory_order::acq_rel, sycl::memory_scope::device);- strata::sys_store(skip, ring);-#undef s_ids-#undef S_RES+ /*+ 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.+ */+ item_ct1.barrier();+ if (i == 0) *skip = ring;}__dpct_inline__ void wait_flag_ge_or_kernel(const volatile uint32_t *flag,uint32_t value,@@ -1120,7 +2360,7 @@ void resident_plan_set_mirror(const int32_t* d_res, const unsigned long long* mi}void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_layer, int n_expert,const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan,- long long capx, uint32_t* skip, uint32_t ring, void* stream) {+ long long capx, uint32_t* skip, uint32_t ring, void* stream, uint32_t* plan_err) {const unsigned long long* mir = nullptr; // SYCL port: the layer's slice of the host-mirror table, if anyif (g_mirror_table != nullptr && g_mirror_res != nullptr && res_layer >= g_mirror_res)mir = g_mirror_table + (res_layer - g_mirror_res);@@ -1128,15 +2368,17 @@ void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- const bool par = plan_parallel();strata::q_of(stream)->parallel_for<dpct_kernel_name<class resident_plan_kernel_db6b7a>>(- sycl::nd_range<3>(sycl::range(1, 1, STRATA_PLAN_LOCAL ? 64 : 1), sycl::range(1, 1, STRATA_PLAN_LOCAL ? 64 : 1)),- exp_props, [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {- resident_plan_kernel(ids, n_entries, k, res_layer, n_expert,- cache_base, slot_off, blob, plan, capx,- skip, ring, mir, par);- });+ sycl::nd_range<3>(sycl::range(1, 1, kResidentPlanMax),+ sycl::range(1, 1, kResidentPlanMax)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ resident_plan_kernel(+ ids, n_entries, k, res_layer, n_expert, cache_base,+ slot_off, blob, plan, capx, skip, ring, mir, plan_err);+ });}check("resident_plan");}@@ -1277,7 +2519,9 @@ void copy_indexed(float* dst, const float* src, int64_t stride, const int32_t* inamespace {__dpct_inline__ void gpu_stamp_kernel(unsigned long long *buf, int i) {unsigned long long t;-#if defined(__HIPCC__)+#if defined(STRATA_HIP_GFX906)+ t = wall_clock64() * 40ull; // gfx906: the wall clock runs at 25 MHz (hipDeviceAttributeWallClockRate) -> ns+#elif defined(__HIPCC__)t = wall_clock64() * 10ull; // gfx10.3 / gfx11 / gfx12: a constant 100 MHz counter, in ns#else/*diff --git a/sycl/src/kernels/dequant_bf16_test.cpp b/sycl/src/kernels/dequant_bf16_test.cppindex 7e100c315..443059aec 100644--- a/sycl/src/kernels/dequant_bf16_test.cpp+++ b/sycl/src/kernels/dequant_bf16_test.cpp@@ -26,6 +26,7 @@ bool cpu_block(int type, const uint8_t* b, float* out) {switch (type) {case 2: dequantize_q4_0(b, out); return true;case 6: dequantize_q5_0(b, out); return true;+ case 7: dequantize_q5_1(b, out); return true;case 8: dequantize_q8_0(b, out); return true;case 11: dequantize_q3_K(b, out); return true;case 12: dequantize_q4_K(b, out); return true;diff --git a/sycl/src/kernels/fused_gr_bench.cpp b/sycl/src/kernels/fused_gr_bench.cppnew file mode 100644index 000000000..c4eedec5c--- /dev/null+++ b/sycl/src/kernels/fused_gr_bench.cpp@@ -0,0 +1,193 @@+// src/kernels/fused_gr_bench.cpp - fused_gr_read_multi: the AMD fast kernels (STRATA_GR_FAST) against the old+// ones, bit for bit on every output (lo, rs, inject, mixed, the in-place R), and each one's time.+//+// build/fused_gr_bench [iters] [T min] [T max]+#define DPCT_PROFILING_ENABLED+#include <sycl/sycl.hpp>+#include <dpct/dpct.hpp>+#include "strata/kernels/fused_gr.hpp"++#include <cmath>+#include <cstdint>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <random>+#include <vector>++namespace K = strata::kernels;++static uint16_t bf16(float x) {+ uint32_t u;+ std::memcpy(&u, &x, 4);+ return (uint16_t) ((u + 0x7fff + ((u >> 16) & 1)) >> 16);+}++int main(int argc, char** argv) {+ setvbuf(stdout, nullptr, _IONBF, 0);+ const int iters = argc > 1 ? std::atoi(argv[1]) : 500;+ const int t_lo = argc > 2 ? std::atoi(argv[2]) : 1, t_hi = argc > 3 ? std::atoi(argv[3]) : 6;+ const int N = 2560, HC = 4, D = N * HC, LR = 320, TM = K::kFusedGrMaxT;+ std::mt19937 rng(7);+ std::normal_distribution<float> nd(0.f, 1.f);+ auto fill = [&](std::vector<float>& v, float sc) { for (auto& x : v) x = sc * nd(rng); };+ std::vector<float> R((size_t) TM * D), bo((size_t) TM * N), inj((size_t) TM * HC), wn(D);+ fill(R, 1.0f); fill(bo, 0.5f); fill(inj, 1.0f); fill(wn, 0.3f);+ for (auto& x : wn) x += 1.0f;+ std::vector<uint16_t> wd((size_t) LR * D), wu((size_t) D * LR), wi((size_t) HC * D);+ for (auto& x : wd) x = bf16(0.02f * nd(rng));+ for (auto& x : wu) x = bf16(0.05f * nd(rng));+ for (auto& x : wi) x = bf16(0.02f * nd(rng));+ float *dR, *dbo, *dinj, *dwn, *dxn, *dlo, *drs, *dio, *dmix;+ uint16_t *dwd, *dwu, *dwi;+ dR = (float *)sycl::malloc_device(R.size() * 4, dpct::get_in_order_queue());+ dbo =+ (float *)sycl::malloc_device(bo.size() * 4, dpct::get_in_order_queue());+ dinj = (float *)sycl::malloc_device(inj.size() * 4,+ dpct::get_in_order_queue());+ dwn =+ (float *)sycl::malloc_device(wn.size() * 4, dpct::get_in_order_queue());+ dxn = (float *)sycl::malloc_device((size_t)TM * D * 4,+ dpct::get_in_order_queue());+ dlo = (float *)sycl::malloc_device((size_t)TM * LR * 4,+ dpct::get_in_order_queue());+ drs = (float *)sycl::malloc_device((size_t)TM * HC * 4,+ dpct::get_in_order_queue());+ dio = (float *)sycl::malloc_device((size_t)TM * HC * 4,+ dpct::get_in_order_queue());+ dmix = (float *)sycl::malloc_device((size_t)TM * N * 4,+ dpct::get_in_order_queue());+ dwd = (uint16_t *)sycl::malloc_device(wd.size() * 2,+ dpct::get_in_order_queue());+ dwu = (uint16_t *)sycl::malloc_device(wu.size() * 2,+ dpct::get_in_order_queue());+ dwi = (uint16_t *)sycl::malloc_device(wi.size() * 2,+ dpct::get_in_order_queue());+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ dpct::get_in_order_queue().memcpy(dbo, bo.data(), bo.size() * 4).wait();+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ dpct::get_in_order_queue().memcpy(dinj, inj.data(), inj.size() * 4).wait();+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ dpct::get_in_order_queue().memcpy(dwn, wn.data(), wn.size() * 4).wait();+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ dpct::get_in_order_queue().memcpy(dwd, wd.data(), wd.size() * 2).wait();+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ dpct::get_in_order_queue().memcpy(dwu, wu.data(), wu.size() * 2).wait();+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ dpct::get_in_order_queue().memcpy(dwi, wi.data(), wi.size() * 2).wait();+ dpct::queue_ptr s;+ s = dpct::get_current_device().create_queue(true);+ dpct::event_ptr e0, e1;+ e0 = new sycl::event();+ e1 = new sycl::event();+ int failures = 0;+ for (int T = t_lo; T <= t_hi; ++T)+ for (int apply = 0; apply < 2; ++apply)+ for (int inject = 0; inject < 2; ++inject) {+ K::FusedGrArgs a[TM];+ for (int t = 0; t < T; ++t) {+ a[t].R = dR + (size_t) t * D; a[t].R_out = dR + (size_t) t * D; a[t].apply = apply;+ a[t].bo_prev = dbo + (size_t) t * N; a[t].inj_prev = dinj + (size_t) t * HC;+ a[t].w_norm = dwn; a[t].w_down = dwd; a[t].w_up = dwu; a[t].w_inject = inject ? dwi : nullptr;+ a[t].lo = dlo + (size_t) t * LR; a[t].rs = drs + (size_t) t * HC;+ a[t].inject_out = dio + (size_t) t * HC; a[t].mixed = dmix + (size_t) t * N;+ }+ std::vector<float> out[2];+ for (int f = 0; f < 2; ++f) {+ dpct::get_in_order_queue()+ .memcpy(dR, R.data(), R.size() * 4)+ .wait();+ dpct::get_in_order_queue()+ .memset(dlo, 0xff, (size_t)TM * LR * 4)+ .wait();+ dpct::get_in_order_queue()+ .memset(drs, 0xff, (size_t)TM * HC * 4)+ .wait();+ dpct::get_in_order_queue()+ .memset(dio, 0xff, (size_t)TM * HC * 4)+ .wait();+ dpct::get_in_order_queue()+ .memset(dmix, 0xff, (size_t)TM * N * 4)+ .wait();+ K::fused_gr_set_fast(f);+ K::fused_gr_read_multi(a, T, dxn, s);+ s->wait();+ auto& o = out[f];+ o.resize((size_t) TM * (D + LR + HC + HC + N));+ float* p = o.data();+ dpct::get_in_order_queue()+ .memcpy(p, dR, (size_t)TM * D * 4)+ .wait();+ p += (size_t)TM * D;+ dpct::get_in_order_queue()+ .memcpy(p, dlo, (size_t)TM * LR * 4)+ .wait();+ p += (size_t)TM * LR;+ dpct::get_in_order_queue()+ .memcpy(p, drs, (size_t)TM * HC * 4)+ .wait();+ p += (size_t)TM * HC;+ dpct::get_in_order_queue()+ .memcpy(p, dio, (size_t)TM * HC * 4)+ .wait();+ p += (size_t)TM * HC;+ dpct::get_in_order_queue()+ .memcpy(p, dmix, (size_t)TM * N * 4)+ .wait();+ }+ const bool same = std::memcmp(out[0].data(), out[1].data(), out[0].size() * 4) == 0;+ double us[2] = {1e30, 1e30};+ for (int round = 0; round < 3; ++round)+ for (int f = 0; f < 2; ++f) {+ K::fused_gr_set_fast(f);+ for (int i = 0; i < 20; ++i) K::fused_gr_read_multi(a, T, dxn, s);+ dpct::sync_barrier(e0, s);+ for (int i = 0; i < iters; ++i) K::fused_gr_read_multi(a, T, dxn, s);+ dpct::sync_barrier(e1, s);+ e1->wait_and_throw();+ float ms = 0;+ ms = (e1->get_profiling_info<+ sycl::info::event_profiling::command_end>() -+ e0->get_profiling_info<+ sycl::info::event_profiling::+ command_start>()) /+ 1000000.0f;+ us[f] = std::fmin(us[f], 1e3 * ms / iters);+ }+ std::printf("T %d apply %d inject %d | old %6.1f us fast %6.1f us | %s\n", T, apply, inject, us[0], us[1],+ same ? "bitwise equal" : "DIFFERS");+ if (!same) ++failures;+ }+ std::printf("fused_gr_bench: %d differing\n", failures);+ return failures ? 1 : 0;+}diff --git a/sycl/src/kernels/gdn_parity.cpp b/sycl/src/kernels/gdn_parity.cppindex 16f482287..afe0ae20c 100644--- a/sycl/src/kernels/gdn_parity.cpp+++ b/sycl/src/kernels/gdn_parity.cpp@@ -22,6 +22,8 @@#include <sycl/sycl.hpp>#include <dpct/dpct.hpp>#include "strata/kernels/gdn.hpp"+#include "strata/kernels/fused_gdn.hpp"+#include "strata/kernels/verify_kernels.hpp"#include <cmath>#include <cstdio>@@ -587,6 +589,216 @@ int main(int argc, char** argv) {sycl::free(d_y, dpct::get_in_order_queue());}+ // ================= 5. the verify-window kernels, T = 1..8, bitwise against the single-token kernels =================+ // gdn_ab_multi and gdn_step_norm_multi are documented as bitwise `fused_gdn_ab` / `fused_gdn_step_norm` per+ // token (verify_kernels.hpp). Every T from 1 to kVerifyMaxT is its own exact-T instantiation, so each is run,+ // and every output and the state are compared with memcmp (not a tolerance).+ {+ const int n_embd = 2560, qk = S * h_k, C = 2 * qk + S * h_v, vd = S * h_v;+ const float eps = 1e-6f;+ auto bf16_of = [](float f) {+ uint32_t u;+ std::memcpy(&u, &f, 4);+ return (uint16_t) (u >> 16);+ };+ std::vector<uint16_t> wa((size_t) h_v * n_embd), wb((size_t) h_v * n_embd);+ for (auto& w : wa) w = bf16_of(gauss(rng) * 0.05f);+ for (auto& w : wb) w = bf16_of(gauss(rng) * 0.05f);+ std::vector<float> dt((size_t) h_v), ssm_a((size_t) h_v), gamma((size_t) S);+ for (auto& x : dt) x = gauss(rng);+ for (auto& x : ssm_a) x = -(0.1f + (float) (rng() % 100) / 50.0f);+ for (auto& x : gamma) x = 1.0f + 0.1f * gauss(rng);+ std::vector<float> st0((size_t) S * h_v * S);+ for (auto& x : st0) x = gauss(rng) * 0.1f;++ auto dev = [&](size_t bytes) {+ try {+ void *p = nullptr;+ check(DPCT_CHECK_ERROR(p = (void *)sycl::malloc_device(+ bytes, dpct::get_in_order_queue())),+ "m5");+ return p;+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ auto up = [&](const void *h, size_t bytes) {+ try {+ void *p = dev(bytes);+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable+ memory. If the memory is not pageable, call wait() on event return+ by memcpy API to ensure synchronization behavior.+ */+ check(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(p, h, bytes).wait()),+ "u5");+ return p;+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ auto down = [&](std::vector<float> &h, const void *d) {+ try {+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(h.data(), d, h.size() * 4)+ .wait()),+ "d5");+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ auto d_wa = (uint16_t*) up(wa.data(), wa.size() * 2);+ auto d_wb = (uint16_t*) up(wb.data(), wb.size() * 2);+ auto d_dt = (float*) up(dt.data(), dt.size() * 4);+ auto d_sa = (float*) up(ssm_a.data(), ssm_a.size() * 4);+ auto d_gm = (float*) up(gamma.data(), gamma.size() * 4);+ int ab_bad = 0, sn_bad = 0, ab_n = 0, sn_n = 0;+ for (int T = 1; T <= strata::kernels::kVerifyMaxT; ++T) {+ // --- alpha/beta+ std::vector<float> x((size_t) T * n_embd);+ for (auto& v : x) v = gauss(rng);+ auto d_x = (float*) up(x.data(), x.size() * 4);+ auto d_g = (float*) dev((size_t) T * h_v * 4), d_b = (float*) dev((size_t) T * h_v * 4);+ auto d_gr = (float*) dev((size_t) T * h_v * 4), d_br = (float*) dev((size_t) T * h_v * 4);+ strata::kernels::gdn_ab_multi(d_x, d_wa, d_wb, d_dt, d_sa, d_g, d_b, n_embd, h_v, T, nullptr);+ for (int t = 0; t < T; ++t)+ strata::kernels::fused_gdn_ab(d_x + (size_t) t * n_embd, d_wa, d_wb, d_dt, d_sa, d_gr + (size_t) t * h_v,+ d_br + (size_t) t * h_v, n_embd, h_v, nullptr);+ std::vector<float> g((size_t) T * h_v), b(g.size()), gr(g.size()), br(g.size());+ down(g, d_g); down(b, d_b); down(gr, d_gr); down(br, d_br);+ ++ab_n;+ if (std::memcmp(g.data(), gr.data(), g.size() * 4) != 0 || std::memcmp(b.data(), br.data(), b.size() * 4) != 0) {+ std::printf(" *** gdn_ab_multi T=%d differs from fused_gdn_ab (memcmp) ***\n", T);+ ++ab_bad;+ }+ sycl::free(d_x, dpct::get_in_order_queue());+ sycl::free(d_g, dpct::get_in_order_queue());+ sycl::free(d_b, dpct::get_in_order_queue());+ sycl::free(d_gr, dpct::get_in_order_queue());+ sycl::free(d_br, dpct::get_in_order_queue());++ // --- the recurrence + output norm+ std::vector<float> h((size_t) T * C), gate((size_t) T * h_v), beta((size_t) T * h_v), z((size_t) T * vd);+ for (auto& v : h) v = gauss(rng) * 0.1f;+ for (auto& v : gate) v = -(0.5f + 3.0f * (float) (rng() % 100) / 100.0f);+ for (auto& v : beta) v = (float) (rng() % 100) / 100.0f;+ for (auto& v : z) v = gauss(rng);+ auto d_h = (float*) up(h.data(), h.size() * 4);+ auto d_gate = (float*) up(gate.data(), gate.size() * 4);+ auto d_beta = (float*) up(beta.data(), beta.size() * 4);+ auto d_z = (float*) up(z.data(), z.size() * 4);+ auto d_y = (float*) dev((size_t) T * vd * 4);+ auto d_yr = (float*) dev((size_t) T * vd * 4);+ auto d_st = (float*) dev(st0.size() * 4);+ auto d_sr = (float*) dev(st0.size() * 4);+ int32_t* d_nk = (int32_t*) dev(4);+ // the reference chain (the single-token kernel), n tokens, into d_sr / d_yr+ auto run_ref = [&](int n) {+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization+ memcpy, assuming in the original code the source host memory is+ pageable memory. If the memory is not pageable, call wait() on+ event return by memcpy API to ensure synchronization behavior.+ */+ try {+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ d_sr, st0.data(), st0.size() * 4).wait()),+ "r0");+ for (int t = 0; t < n; ++t)+ strata::kernels::fused_gdn_step_norm(d_sr, d_h + (size_t) t * C, d_h + (size_t) t * C + qk,+ d_h + (size_t) t * C + 2 * qk, d_gate + (size_t) t * h_v,+ d_beta + (size_t) t * h_v, d_z + (size_t) t * vd, d_gm, eps,+ d_yr + (size_t) t * vd, h_k, h_v, nullptr);+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ std::vector<float> y((size_t) T * vd), yr(y.size()), st(st0.size()), sr(st0.size());+ // (name, n_keep tokens or -1 = verify half, t_out_begin)+ struct Case { const char* name; int n_keep; int tb; };+ std::vector<Case> cases = {{"verify", -1, 0}, {"verify tb", -1, T > 1 ? T / 2 : 0}, {"commit", T, 0},+ {"commit tb", T, T / 2}, {"commit state only", T, T}};+ if (T > 1) cases.push_back({"commit n-1", T - 1, T - 1});+ for (const Case& c : cases) {+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization+ memcpy, assuming in the original code the source host memory is+ pageable memory. If the memory is not pageable, call wait() on+ event return by memcpy API to ensure synchronization behavior.+ */+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ d_st, st0.data(), st0.size() * 4).wait()),+ "s0");+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memset(d_y, 0, (size_t)T * vd * 4)+ .wait()),+ "y0");+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memset(d_yr, 0, (size_t)T * vd * 4)+ .wait()),+ "yr0");+ const int n = c.n_keep < 0 ? T : c.n_keep;+ if (c.n_keep >= 0)+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(d_nk, &c.n_keep, 4)+ .wait()),+ "nk");+ strata::kernels::gdn_step_norm_multi(d_st, d_h, C, d_gate, d_beta, d_z, d_gm, eps, d_y, h_k, h_v, T,+ c.n_keep >= 0 ? d_nk : nullptr, nullptr, c.tb);+ run_ref(n);+ down(y, d_y); down(yr, d_yr); down(st, d_st); down(sr, d_sr);+ bool ok = true;+ size_t y_bad = 0, y_all = 0;+ for (int t = c.tb; t < n; ++t) {+ for (int i = 0; i < vd; ++i, ++y_all)+ if (std::memcmp(&y[(size_t) t * vd + i], &yr[(size_t) t * vd + i], 4) != 0) ++y_bad;+ }+ if (y_bad) ok = false;+ // the verify half leaves the state untouched; the commit half writes the state after n tokens+ const std::vector<float>& want_st = c.n_keep < 0 ? st0 : sr;+ if (std::memcmp(st.data(), want_st.data(), st.size() * 4) != 0) ok = false;+ ++sn_n;+ if (!ok) {+ std::printf(" *** gdn_step_norm_multi T=%d '%s' differs from fused_gdn_step_norm (memcmp): %zu of %zu y words%s ***\n",+ T, c.name, y_bad, y_all,+ std::memcmp(st.data(), (c.n_keep < 0 ? st0 : sr).data(), st.size() * 4) != 0 ? ", state too" : "");+ ++sn_bad;+ }+ }+ sycl::free(d_h, dpct::get_in_order_queue());+ sycl::free(d_gate, dpct::get_in_order_queue());+ sycl::free(d_beta, dpct::get_in_order_queue());+ sycl::free(d_z, dpct::get_in_order_queue());+ sycl::free(d_y, dpct::get_in_order_queue());+ sycl::free(d_yr, dpct::get_in_order_queue());+ sycl::free(d_st, dpct::get_in_order_queue());+ sycl::free(d_sr, dpct::get_in_order_queue());+ sycl::free(d_nk, dpct::get_in_order_queue());+ }+ sycl::free(d_wa, dpct::get_in_order_queue());+ sycl::free(d_wb, dpct::get_in_order_queue());+ sycl::free(d_dt, dpct::get_in_order_queue());+ sycl::free(d_sa, dpct::get_in_order_queue());+ sycl::free(d_gm, dpct::get_in_order_queue());+ std::printf("\n %-42s %s (%d cases)\n", "gdn_ab_multi T=1..8 == fused_gdn_ab", ab_bad ? "*** NO ***" : "bitwise", ab_n);+ std::printf(" %-42s %s (%d cases)\n", "gdn_step_norm_multi T=1..8 == single-token", sn_bad ? "*** NO ***" : "bitwise", sn_n);+ bad += ab_bad + sn_bad;+ }+std::printf("\ngdn: %d failures\n", bad);if (bad) return 1;if (selftest) std::printf("gdn_parity OK\n");diff --git a/sycl/src/kernels/gr_multi_parity.cpp b/sycl/src/kernels/gr_multi_parity.cppnew file mode 100644index 000000000..9f3c5956f--- /dev/null+++ b/sycl/src/kernels/gr_multi_parity.cpp@@ -0,0 +1,177 @@+// src/kernels/gr_multi_parity.cpp - the multi-token hyper-connection read and write (#783 PR-g: gr_read_multi,+// gr_write_multi and the exact-T BF16 projections under them) against the single-token calls, memcmp.+//+// Real geometry (n_embd 2560, hc 4, hc_lr 320), the pinned native MMVF path, every T = 1..8, with and without an+// injection weight (a layer read vs the final mixer), and the write both out of place and in place (R_out == R).+// Each output of the multi call must equal the token-by-token one bit for bit. GPU, synthetic, no model.+#define DPCT_PROFILING_ENABLED+#include <sycl/sycl.hpp>+#include <dpct/dpct.hpp>+#include "strata/kernels/gr.hpp"++#include <cstdint>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <random>+#include <vector>++namespace k = strata::kernels;++namespace {+void ck(dpct::err0 e, const char *w) {+}+template <typename T>+T* up(const std::vector<T>& h) {+ void* p = nullptr;+ ck(DPCT_CHECK_ERROR(+ p = (void *)sycl::malloc_device(h.size() * sizeof(T) + 64,+ dpct::get_in_order_queue())),+ "malloc");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in+ the original code the source host memory is pageable memory. If the memory+ is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ p, h.data(), h.size() * sizeof(T)).wait()),+ "h2d");+ return (T*) p;+}+template <typename T>+T* dev(size_t n) {+ void* p = nullptr;+ ck(DPCT_CHECK_ERROR(p = (void *)sycl::malloc_device(+ n * sizeof(T) + 64, dpct::get_in_order_queue())),+ "malloc");+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memset(p, 0, n * sizeof(T) + 64).wait()),+ "memset");+ return (T*) p;+}+template <typename T>+std::vector<T> down(const T* d, size_t n) {+ std::vector<T> h(n);+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(h.data(), d, n * sizeof(T))+ .wait()),+ "d2h");+ return h;+}+uint16_t bf16_of(float f) {+ uint32_t u;+ std::memcpy(&u, &f, 4);+ return (uint16_t) (u >> 16);+}+} // namespace++int main() {+ const long long n_embd = 2560, hc = 4, hc_lr = 320, hc_dim = hc * n_embd;+ const float eps = 1e-6f;+ std::mt19937 rng(783);+ std::normal_distribution<float> gauss(0.f, 1.f);+ k::gr_set_native_mmvf(true);++ std::vector<float> w_norm((size_t) hc_dim);+ for (auto& x : w_norm) x = 1.0f + 0.1f * gauss(rng);+ std::vector<uint16_t> w_down((size_t) (hc_lr * hc_dim)), w_up((size_t) (hc_dim * hc_lr)), w_inj((size_t) (hc * hc_dim));+ for (auto& x : w_down) x = bf16_of(gauss(rng) * 0.05f);+ for (auto& x : w_up) x = bf16_of(gauss(rng) * 0.05f);+ for (auto& x : w_inj) x = bf16_of(gauss(rng) * 0.02f);+ float* d_norm = up(w_norm);+ uint16_t *d_down = up(w_down), *d_up = up(w_up), *d_inj = up(w_inj);++ const k::GrShapes sh{n_embd, hc, hc_lr};+ void* ws_raw = nullptr;+ ck(DPCT_CHECK_ERROR(+ ws_raw = (void *)sycl::malloc_device(k::gr_workspace_bytes(sh),+ dpct::get_in_order_queue())),+ "ws");+ k::GrWorkspace ws;+ k::gr_workspace_init(sh, ws_raw, ws);++ int cases = 0, bad = 0;+ for (int T = 1; T <= 8; ++T) {+ std::vector<float> R((size_t) T * hc_dim);+ for (int t = 0; t < T; ++t)+ for (long long c = 0; c < hc; ++c)+ for (long long d = 0; d < n_embd; ++d) R[(size_t) t * hc_dim + c * n_embd + d] = gauss(rng) * (float) (1 << (2 * c));+ float* d_R = up(R);+ float* d_xn = dev<float>((size_t) T * hc_dim);+ float* d_lo = dev<float>((size_t) T * hc_lr);+ float* d_g = dev<float>((size_t) T * hc_dim);+ for (int with_inj = 0; with_inj < 2; ++with_inj) {+ float* d_mixed_m = dev<float>((size_t) T * n_embd);+ float* d_mixed_s = dev<float>((size_t) T * n_embd);+ float* d_inject_m = dev<float>((size_t) T * hc);+ float* d_inject_s = dev<float>((size_t) T * hc);+ const uint16_t* wi = with_inj ? d_inj : nullptr;+ k::gr_read_multi(d_R, d_norm, d_down, d_up, wi, eps, sh, ws, d_xn, d_lo, d_g, d_mixed_m,+ with_inj ? d_inject_m : nullptr, T, nullptr);+ for (int t = 0; t < T; ++t)+ k::gr_read(d_R + (size_t) t * hc_dim, d_norm, d_down, d_up, wi, eps, sh, ws, d_mixed_s + (size_t) t * n_embd,+ with_inj ? d_inject_s + (size_t) t * hc : nullptr, nullptr);+ ck(DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()),+ "sync");+ bool ok = std::memcmp(down(d_mixed_m, (size_t) T * n_embd).data(), down(d_mixed_s, (size_t) T * n_embd).data(),+ (size_t) T * n_embd * 4) == 0;+ if (with_inj)+ ok = ok && std::memcmp(down(d_inject_m, (size_t) T * hc).data(), down(d_inject_s, (size_t) T * hc).data(),+ (size_t) T * hc * 4) == 0;+ ++cases;+ if (!ok) {+ std::printf(" *** gr_read_multi T=%d %s differs from gr_read ***\n", T, with_inj ? "with injection" : "final mixer");+ ++bad;+ }+ sycl::free(d_mixed_m, dpct::get_in_order_queue());+ sycl::free(d_mixed_s, dpct::get_in_order_queue());+ sycl::free(d_inject_m, dpct::get_in_order_queue());+ sycl::free(d_inject_s, dpct::get_in_order_queue());+ }++ // the write: R_out[t] = R[t] + block_out[t] * 2 sigmoid(inject[t] / hc)+ std::vector<float> bo((size_t) T * n_embd), inj((size_t) T * hc);+ for (auto& x : bo) x = gauss(rng);+ for (auto& x : inj) x = gauss(rng) * 3.0f;+ float* d_bo = up(bo);+ float* d_in = up(inj);+ for (int inplace = 0; inplace < 2; ++inplace) {+ float* d_Rm = up(R);+ float* d_Rs = up(R);+ float* d_om = inplace ? d_Rm : dev<float>((size_t) T * hc_dim);+ float* d_os = inplace ? d_Rs : dev<float>((size_t) T * hc_dim);+ k::gr_write_multi(d_Rm, d_bo, d_in, sh, d_om, T, nullptr);+ for (int t = 0; t < T; ++t)+ k::gr_write(d_Rs + (size_t) t * hc_dim, d_bo + (size_t) t * n_embd, d_in + (size_t) t * hc, sh,+ d_os + (size_t) t * hc_dim, nullptr);+ ck(DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()),+ "sync");+ const bool ok = std::memcmp(down(d_om, (size_t) T * hc_dim).data(), down(d_os, (size_t) T * hc_dim).data(),+ (size_t) T * hc_dim * 4) == 0;+ ++cases;+ if (!ok) {+ std::printf(" *** gr_write_multi T=%d %s differs from gr_write ***\n", T, inplace ? "in place" : "out of place");+ ++bad;+ }+ sycl::free(d_Rm, dpct::get_in_order_queue());+ sycl::free(d_Rs, dpct::get_in_order_queue());+ if (!inplace) {+ sycl::free(d_om, dpct::get_in_order_queue());+ sycl::free(d_os, dpct::get_in_order_queue());+ }+ }+ sycl::free(d_R, dpct::get_in_order_queue());+ sycl::free(d_xn, dpct::get_in_order_queue());+ sycl::free(d_lo, dpct::get_in_order_queue());+ sycl::free(d_g, dpct::get_in_order_queue());+ sycl::free(d_bo, dpct::get_in_order_queue());+ sycl::free(d_in, dpct::get_in_order_queue());+ }+ std::printf("gr_multi: %d cases, %d failures\n", cases, bad);+ if (bad) return 1;+ std::printf("gr_multi_parity OK\n");+ return 0;+}diff --git a/sycl/src/kernels/gr_parity.cpp b/sycl/src/kernels/gr_parity.cppindex 3567a2a63..cea5253e3 100644--- a/sycl/src/kernels/gr_parity.cpp+++ b/sycl/src/kernels/gr_parity.cpp@@ -24,6 +24,7 @@#include <dpct/dpct.hpp>#include "strata/kernels/gr.hpp"#include "strata/kernels/fused_gr.hpp"+#include "strata/kernels/native_mmvq.hpp"#include <cmath>#include <cstdio>@@ -592,6 +593,88 @@ int fused_multi_lds_parity(const float* d_norm, const uint16_t* d_down, const ui++bad;}++ // S26 STRATA_QFUSE: the read's own q8_1 image of `mixed` must be the bytes native_quantize_q8_1 writes from it -+ // for every T (1..8), directly and through a captured graph replayed twice (the group counters must reset)+ {+ uint8_t *d_q = nullptr, *d_ref = nullptr;+ unsigned* d_cnt = nullptr;+ const size_t qbytes = (size_t) T * (N / 32) * 36;+ check(DPCT_CHECK_ERROR(d_q = (uint8_t *)sycl::malloc_device(+ qbytes, dpct::get_in_order_queue())),+ "qfuse q8");+ check(DPCT_CHECK_ERROR(d_ref = (uint8_t *)sycl::malloc_device(+ qbytes, dpct::get_in_order_queue())),+ "qfuse ref");+ check(DPCT_CHECK_ERROR(d_cnt = sycl::malloc_device<unsigned int>(+ (N / 32), dpct::get_in_order_queue())),+ "qfuse counters");+ check(+ DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memset(d_cnt, 0, (N / 32) * sizeof(unsigned))+ .wait()),+ "qfuse counters zero");+ int qbad = 0;+ std::vector<uint8_t> hq(qbytes), hr(qbytes);+ for (int tt = 1; tt <= T && !qbad; ++tt) {+ std::vector<FusedGrArgs> qa(args.begin(), args.begin() + tt);+ for (int t = 0; t < tt; ++t) { qa[t].q8_mixed = d_q + (size_t) t * (N / 32) * 36; qa[t].q8_cnt = d_cnt; }+ for (int rep = 0; rep < 3 && !qbad; ++rep) {+ check(DPCT_CHECK_ERROR(stream->memset(d_q, 0x5a, qbytes)),+ "qfuse poison");+ bool wrote = false;+ dpct::experimental::command_graph_ptr qg = nullptr;+ dpct::experimental::command_graph_exec_ptr qx = nullptr;+ if (rep == 0) {+ wrote = fused_gr_read_multi(qa.data(), tt, d_xn, stream);+ } else { // a captured read, replayed (twice: rep 1 and 2 use fresh captures, each replayed twice)+ check(DPCT_CHECK_ERROR(+ dpct::experimental::begin_recording(stream)),+ "qfuse begin");+ wrote = fused_gr_read_multi(qa.data(), tt, d_xn, stream);+ check(DPCT_CHECK_ERROR(+ dpct::experimental::end_recording(stream, &qg)),+ "qfuse end");+ check(+ DPCT_CHECK_ERROR(+ qx = new sycl::ext::oneapi::experimental::+ command_graph<sycl::ext::oneapi::experimental::+ graph_state::executable>(+ qg->finalize())),+ "qfuse instantiate");+ check(DPCT_CHECK_ERROR(stream->ext_oneapi_graph(*qx)),+ "qfuse replay 1");+ check(DPCT_CHECK_ERROR(stream->memset(d_q, 0x5a, qbytes)),+ "qfuse poison 2");+ check(DPCT_CHECK_ERROR(stream->ext_oneapi_graph(*qx)),+ "qfuse replay 2");+ }+ strata::kernels::native_quantize_q8_1(d_mixed, d_ref, N, tt, stream);+ check(DPCT_CHECK_ERROR(stream->wait()), "qfuse sync");+ if (qx) { delete (qx); delete (qg); }+ if (v3) { std::printf(" QFUSE: the v3 read writes no q8_1 (%s)\n", wrote ? "WRONG: it says it did" : "ok"); qbad += wrote; break; }+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(hq.data(), d_q,+ (size_t)tt * (N / 32) * 36)+ .wait()),+ "qfuse read");+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(hr.data(), d_ref,+ (size_t)tt * (N / 32) * 36)+ .wait()),+ "qfuse ref read");+ if (!wrote || std::memcmp(hq.data(), hr.data(), (size_t) tt * (N / 32) * 36) != 0) {+ std::printf(" QFUSE: T=%d rep %d: %s\n", tt, rep, wrote ? "q8_1 bytes differ" : "not written");+ ++qbad;+ }+ }+ }+ std::printf(" fused GR read + q8_1 (STRATA_QFUSE), T 1..8, direct and graph replays: %s\n", qbad ? "FAIL" : "pass");+ bad += qbad;+ sycl::free(d_q, dpct::get_in_order_queue());+ sycl::free(d_ref, dpct::get_in_order_queue());+ sycl::free(d_cnt, dpct::get_in_order_queue());+ }std::printf(" fused GR multi max-T=8 LDS launch and changing graph replay %s\n",bad == 0 ? "pass" : "FAIL");check(DPCT_CHECK_ERROR(delete (graph_exec)), "multi graph exec destroy");diff --git a/sycl/src/kernels/iq_multi_parity.cpp b/sycl/src/kernels/iq_multi_parity.cppindex ec795590d..0f086958a 100644--- a/sycl/src/kernels/iq_multi_parity.cpp+++ b/sycl/src/kernels/iq_multi_parity.cpp@@ -507,9 +507,10 @@ void bench(dpct::queue_ptr s, std::mt19937 &rng) {}}-// #606: both q8_1 activation quantizers (quantize_q8_1_rows and native_quantize_q8_1) against a host transcription-// of the 0.1.38 formula: every finite block bit for bit; a block whose sum (or scale) overflowed fp16 is now stored-// finite (the largest half, its sign), with its values in the int8 range.+// #606: the q8_1 activation quantizers (quantize_q8_1_rows, native_quantize_q8_1 and the shared expert's fused+// native_swiglu_quantize_q8_1) against a host transcription of the 0.1.38 formula: every finite block bit for bit; a+// block whose sum (or scale) overflowed fp16 is now stored finite (the largest half, its sign), with its values in the+// int8 range. The fused one gets gate = 32 and up = x / 32: silu(32) is 32 in float, so its activations are x exactly.void check_q8_1_finite(dpct::queue_ptr s, std::mt19937 &rng) {const int n = 2560, rows = 3, nb = n / 32;std::vector<float> x = random_x((size_t) rows * n, rng);@@ -527,10 +528,33 @@ void check_q8_1_finite(dpct::queue_ptr s, std::mt19937 &rng) {ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dx, x.data(), x.size() * 4).wait()),"x");+ std::vector<float> gate(x.size(), 32.0f), up(x.size());+ for (size_t i = 0; i < x.size(); ++i) up[i] = x[i] / 32.0f;+ float* dg = dalloc<float>(x.size());+ float* du = dalloc<float>(x.size());+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dg, gate.data(), x.size() * 4).wait()),+ "gate");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(du, up.data(), x.size() * 4).wait()),+ "up");uint8_t* dq = dalloc<uint8_t>((size_t) rows * nb * 36);- for (int path = 0; path < 2; ++path) {+ for (int path = 0; path < 3; ++path) {if (path == 0) k::quantize_q8_1_rows(dx, rows, n, dq, s);- else k::native_quantize_q8_1(dx, dq, n, rows, s);+ else if (path == 1) k::native_quantize_q8_1(dx, dq, n, rows, s);+ else k::native_swiglu_quantize_q8_1(dg, du, dq, n, rows, s);ck(DPCT_CHECK_ERROR(s->wait()), "quantize");std::vector<uint8_t> got((size_t) rows * nb * 36);ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())@@ -562,7 +586,7 @@ void check_q8_1_finite(dpct::queue_ptr s, std::mt19937 &rng) {want[4 + i] = (uint8_t) (int8_t) (amax == 0.0f ? 0.0f : std::round(v[i] / d));// native_mmvq.cu is built with --use_fast_math (its divisions are approximate): there the sum must be// the same bits, the scale within one fp16 step and each value within one step- bool near = path == 1 && gs == os && std::abs((int) gd - (int) od) <= 1;+ bool near = path >= 1 && gs == os && std::abs((int) gd - (int) od) <= 1;for (int i = 0; near && i < 32; ++i) near = std::abs((int) (int8_t) g[4 + i] - (int) (int8_t) want[4 + i]) <= 1;if (std::memcmp(want, g, 36) == 0 || near) ++same;else { ++bad; std::printf(" q8_1 path %d block %d: changed although it was finite\n", path, b); }@@ -576,10 +600,13 @@ void check_q8_1_finite(dpct::queue_ptr s, std::mt19937 &rng) {}}std::printf("q8_1 finite (%s): %d finite blocks as before, %d overflowed blocks clamped finite%s\n",- path == 0 ? "quantize_q8_1_rows" : "native_quantize_q8_1", same, clamped, bad ? " FAIL" : "");+ path == 0 ? "quantize_q8_1_rows" : path == 1 ? "native_quantize_q8_1" : "native_swiglu_quantize_q8_1",+ same, clamped, bad ? " FAIL" : "");g_fail += bad + (clamped != 3);}sycl::free(dx, dpct::get_in_order_queue());+ sycl::free(dg, dpct::get_in_order_queue());+ sycl::free(du, dpct::get_in_order_queue());sycl::free(dq, dpct::get_in_order_queue());}diff --git a/sycl/src/kernels/kv_hybrid_parity.cpp b/sycl/src/kernels/kv_hybrid_parity.cppindex 871532de3..8474abfdf 100644--- a/sycl/src/kernels/kv_hybrid_parity.cpp+++ b/sycl/src/kernels/kv_hybrid_parity.cpp@@ -101,9 +101,9 @@ int main() {for (int i = 0; i < pages; ++i) table[i] = (i * 5 + 3) % pages;int32_t* d_table = dalloc<int32_t>(pages);/*- DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in- the original code the source host memory is pageable memory. If the memory- is not pageable, call wait() on event return by memcpy API to ensure+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensuresynchronization behavior.*/ck(DPCT_CHECK_ERROR(@@ -181,9 +181,9 @@ int main() {k::kv_append_q8_step(d_kq, d_kq, d_ks, d_ks, d_table, d_step, d_kcur, d_kcur, s, nullptr, nullptr);k::kv_append_q4_step(d_v4, d_v4, d_table, d_step, d_vcur, d_vcur, s, nullptr, nullptr);/*- DPCT1010: SYCL uses exceptions to report errors and does not use the- error codes. The cudaGetLastError function call was replaced with 0. You- need to rewrite this code.+ DPCT1010: SYCL uses exceptions to report errors and does not use+ the error codes. The cudaGetLastError function call was replaced with 0.+ You need to rewrite this code.*/ck(0 != 0 ? 0 : 0, "append");}@@ -230,9 +230,9 @@ int main() {for (int i = 0; i < cells; ++i) ids[i] = i;int32_t* d_ids = dalloc<int32_t>(cells);/*- DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in- the original code the source host memory is pageable memory. If the memory- is not pageable, call wait() on event return by memcpy API to ensure+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensuresynchronization behavior.*/ck(DPCT_CHECK_ERROR(@@ -242,9 +242,9 @@ int main() {k::qsa_step_fill(step, cells - 1, s);step[k::kStepWidth] = cells; // select everything/*- DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in- the original code the source host memory is pageable memory. If the memory- is not pageable, call wait() on event return by memcpy API to ensure+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensuresynchronization behavior.*/ck(DPCT_CHECK_ERROR(@@ -283,9 +283,9 @@ int main() {for (auto& x : q) x = nd(rng);float* d_q = dalloc<float>(q.size());/*- DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in- the original code the source host memory is pageable memory. If the memory- is not pageable, call wait() on event return by memcpy API to ensure+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensuresynchronization behavior.*/ck(DPCT_CHECK_ERROR(@@ -444,7 +444,7 @@ int main() {float* d_at4 = dalloc<float>((size_t) QH * D);const bool took = k::qsa_prompt_attn_batch(d_q, pools, d_ids, d_step, cells, s, d_at4, 1, nullptr);if (!took) {-#if defined(STRATA_USE_HIP)+#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)// AMD: the tensor-core prompt path is CUDA-only, so it refuses every pool and the old kernel runsstd::printf("[5/5] qsa_prompt_attn mode 3: PASS (refused on HIP - the old kernel runs)\n");#elsediff --git a/sycl/src/kernels/kv_steps_parity.cpp b/sycl/src/kernels/kv_steps_parity.cppnew file mode 100644index 000000000..77131d5d2--- /dev/null+++ b/sycl/src/kernels/kv_steps_parity.cpp@@ -0,0 +1,179 @@+// src/kernels/kv_steps_parity.cpp - the batched K/V append (#783 PR-d): kv_append_q8_steps / kv_append_q4_steps for+// n = 1..8 cells in one launch against n calls of the single-cell append, memcmp on every pool byte.+//+// Cells land at scattered positions through a non-identity page table; the K/V rows are random with small, large and+// all-zero groups. Three layouts: INT8 K and V, Q4_0 K and V, and the K8V4 hybrid's folded call (the K pool passed as+// both halves, one plane). GPU, synthetic, no model.+#define DPCT_PROFILING_ENABLED+#include <sycl/sycl.hpp>+#include <dpct/dpct.hpp>+#include "strata/kernels/kv_q4.hpp"+#include "strata/kernels/kv_q8.hpp"+#include "strata/kernels/qsa.hpp"++#include <algorithm>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <random>+#include <vector>++namespace k = strata::kernels;++namespace {+int g_fail = 0;+void ck(dpct::err0 e, const char *w) {+}+template <typename T>+T* dalloc(size_t n) {+ T* p = nullptr;+ ck(DPCT_CHECK_ERROR(p = (T *)sycl::malloc_device(+ n * sizeof(T) + 64, dpct::get_in_order_queue())),+ "malloc");+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memset(p, 0, n * sizeof(T) + 64).wait()),+ "memset");+ return p;+}+template <typename T>+std::vector<T> fetch(const T* d, size_t n) {+ std::vector<T> h(n);+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(h.data(), d, n * sizeof(T))+ .wait()),+ "d2h");+ return h;+}+template <typename T>+void zero(T *d, size_t n) {+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memset(d, 0, n * sizeof(T) + 64).wait()),+ "zero");+}+bool same(const void* a, const void* b, size_t bytes) { return std::memcmp(a, b, bytes) == 0; }+} // namespace++int main() {+ k::QsaShapes s = k::qsa_real_shapes();+ s.page_size = 64;+ const int H = (int) s.n_head_kv, D = (int) s.head_dim, P = (int) s.page_size, G = D / k::KV_Q8_GROUP;+ const int pages = 8, cells = pages * P;+ std::mt19937 rng(783);+ std::normal_distribution<float> nd(0.f, 1.f);+ std::vector<int32_t> table(pages);+ for (int i = 0; i < pages; ++i) table[i] = (i * 5 + 3) % pages;+ int32_t* d_table = dalloc<int32_t>(pages);+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in+ the original code the source host memory is pageable memory. If the memory+ is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_table, table.data(), pages * 4).wait()),+ "table");++ const size_t q8n = (size_t) cells * H * D, q8s = (size_t) cells * H * G, q4n = (size_t) cells * H * D; // q4: <= 144 B per cell-head+ int8_t *kq1 = dalloc<int8_t>(q8n), *vq1 = dalloc<int8_t>(q8n), *kq2 = dalloc<int8_t>(q8n), *vq2 = dalloc<int8_t>(q8n);+ uint16_t *ks1 = dalloc<uint16_t>(q8s), *vs1 = dalloc<uint16_t>(q8s), *ks2 = dalloc<uint16_t>(q8s), *vs2 = dalloc<uint16_t>(q8s);+ uint8_t *k41 = dalloc<uint8_t>(q4n), *v41 = dalloc<uint8_t>(q4n), *k42 = dalloc<uint8_t>(q4n), *v42 = dalloc<uint8_t>(q4n);+ uint8_t *h41 = dalloc<uint8_t>(q4n), *h42 = dalloc<uint8_t>(q4n);+ int8_t *hq1 = dalloc<int8_t>(q8n), *hq2 = dalloc<int8_t>(q8n);+ uint16_t *hs1 = dalloc<uint16_t>(q8s), *hs2 = dalloc<uint16_t>(q8s);++ int total_cases = 0;+ for (int n = 1; n <= 8; ++n) {+ for (int round = 0; round < 3; ++round) {+ zero(kq1, q8n); zero(vq1, q8n); zero(kq2, q8n); zero(vq2, q8n);+ zero(ks1, q8s); zero(vs1, q8s); zero(ks2, q8s); zero(vs2, q8s);+ zero(k41, q4n); zero(v41, q4n); zero(k42, q4n); zero(v42, q4n); zero(h41, q4n); zero(h42, q4n);+ zero(hq1, q8n); zero(hq2, q8n); zero(hs1, q8s); zero(hs2, q8s);+ std::vector<int> positions(cells);+ for (int i = 0; i < cells; ++i) positions[i] = i;+ std::shuffle(positions.begin(), positions.end(), rng);+ std::vector<float> hk((size_t) n * H * D), hv(hk.size());+ for (int t = 0; t < n; ++t) {+ const float scale = (t % 3 == 0) ? 1e-3f : (t % 5 == 0 ? 40.f : 1.f);+ for (int i = 0; i < H * D; ++i) {+ hk[(size_t) t * H * D + i] = nd(rng) * scale;+ hv[(size_t) t * H * D + i] = nd(rng) * scale;+ }+ if (t % 4 == 1) std::fill(hk.begin() + (size_t) t * H * D, hk.begin() + (size_t) t * H * D + 64, 0.f);+ }+ std::vector<int32_t> hstep((size_t) n * k::kStepCount, 0);+ for (int t = 0; t < n; ++t) {+ hstep[(size_t) t * k::kStepCount + k::kStepPos] = positions[t];+ hstep[(size_t) t * k::kStepCount + 1] = positions[t] + 1;+ }+ float *d_k = dalloc<float>(hk.size()), *d_v = dalloc<float>(hv.size());+ int32_t* d_step = dalloc<int32_t>(hstep.size());+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable+ memory. If the memory is not pageable, call wait() on event return+ by memcpy API to ensure synchronization behavior.+ */+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ d_k, hk.data(), hk.size() * 4).wait()),+ "k");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable+ memory. If the memory is not pageable, call wait() on event return+ by memcpy API to ensure synchronization behavior.+ */+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ d_v, hv.data(), hv.size() * 4).wait()),+ "v");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable+ memory. If the memory is not pageable, call wait() on event return+ by memcpy API to ensure synchronization behavior.+ */+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ d_step, hstep.data(), hstep.size() * 4).wait()),+ "step");++ for (int t = 0; t < n; ++t) {+ const int32_t* st = d_step + (size_t) t * k::kStepCount;+ const float* kc = d_k + (size_t) t * H * D;+ const float* vc = d_v + (size_t) t * H * D;+ k::kv_append_q8_step(kq1, vq1, ks1, vs1, d_table, st, kc, vc, s, nullptr);+ k::kv_append_q4_step(k41, v41, d_table, st, kc, vc, s, nullptr);+ k::kv_append_q8_step(hq1, hq1, hs1, hs1, d_table, st, kc, kc, s, nullptr); // the hybrid's folded K call+ k::kv_append_q4_step(h41, h41, d_table, st, vc, vc, s, nullptr); // ... and its folded V call+ }+ k::kv_append_q8_steps(kq2, vq2, ks2, vs2, d_table, d_step, k::kStepCount, d_k, d_v, H * D, n, s, nullptr, nullptr);+ k::kv_append_q4_steps(k42, v42, d_table, d_step, k::kStepCount, n, d_k, d_v, s, nullptr);+ k::kv_append_q8_steps(hq2, hq2, hs2, hs2, d_table, d_step, k::kStepCount, d_k, d_k, H * D, n, s, nullptr, nullptr);+ k::kv_append_q4_steps(h42, h42, d_table, d_step, k::kStepCount, n, d_v, d_v, s, nullptr);+ ck(DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()),+ "sync");++ struct Chk { const char* name; bool ok; };+ const Chk chks[] = {+ {"INT8 K/V codes", same(fetch(kq1, q8n).data(), fetch(kq2, q8n).data(), q8n) && same(fetch(vq1, q8n).data(), fetch(vq2, q8n).data(), q8n)},+ {"INT8 K/V scales", same(fetch(ks1, q8s).data(), fetch(ks2, q8s).data(), q8s * 2) && same(fetch(vs1, q8s).data(), fetch(vs2, q8s).data(), q8s * 2)},+ {"Q4_0 K/V", same(fetch(k41, q4n).data(), fetch(k42, q4n).data(), q4n) && same(fetch(v41, q4n).data(), fetch(v42, q4n).data(), q4n)},+ {"hybrid K (folded INT8)", same(fetch(hq1, q8n).data(), fetch(hq2, q8n).data(), q8n) && same(fetch(hs1, q8s).data(), fetch(hs2, q8s).data(), q8s * 2)},+ {"hybrid V (folded Q4_0)", same(fetch(h41, q4n).data(), fetch(h42, q4n).data(), q4n)},+ };+ for (const Chk& c : chks) {+ ++total_cases;+ if (!c.ok) {+ std::printf(" *** n=%d round %d: %s differ from the per-cell appends ***\n", n, round, c.name);+ ++g_fail;+ }+ }+ sycl::free(d_k, dpct::get_in_order_queue());+ sycl::free(d_v, dpct::get_in_order_queue());+ sycl::free(d_step, dpct::get_in_order_queue());+ }+ }+ std::printf("kv_steps: %d checks, %d failures\n", total_cases, g_fail);+ if (g_fail) return 1;+ std::printf("kv_steps_parity OK\n");+ return 0;+}diff --git a/sycl/src/kernels/kv_stream_parity.cpp b/sycl/src/kernels/kv_stream_parity.cppindex 9ab9c99a5..759b821dd 100644--- a/sycl/src/kernels/kv_stream_parity.cpp+++ b/sycl/src/kernels/kv_stream_parity.cpp@@ -8,7 +8,8 @@// 2. the residency map is consistent after every call (slot_block and page_table invert each other);// 3. no call overflowed, and the hit/miss counters add up;// 4. a ring (the MTP drafter's layout) restored from the host copy reads the same values as the resident pool.-// INT8, FP16 and Q4_0 (PR #21) pools.+// INT8, FP16, Q4_0 (PR #21) and hybrid K8V4 pools; K8V4's appends are the engine's folded calls (layer.cpp), its host+// copy written through kv_hybrid_k_half / kv_hybrid_v_half.#define DPCT_PROFILING_ENABLED#include <sycl/sycl.hpp>#include <dpct/dpct.hpp>@@ -67,7 +68,12 @@ struct Pools { // one K/V pool set of `pages` pagesk::KvHostPools p; // reused as a plain pointer bundlevoid alloc(int64_t pages, const k::QsaShapes& s, int fmt, bool host) {const size_t rows = (size_t) pages * s.n_head_kv * s.page_size;- if (fmt == k::kKvQ4) {+ if (fmt == k::kKvHybrid) {+ const size_t b = rows * k::kv_q4_bytes_per_head((int) s.head_dim);+ p.k_q = host ? halloc<int8_t>(rows * s.head_dim) : dalloc<int8_t>(rows * s.head_dim);+ p.k_scale = host ? halloc<uint16_t>(rows * 4) : dalloc<uint16_t>(rows * 4);+ p.v_q4 = host ? halloc<uint8_t>(b) : dalloc<uint8_t>(b);+ } else if (fmt == k::kKvQ4) {const size_t b = rows * k::kv_q4_bytes_per_head((int) s.head_dim);p.k_q4 = host ? halloc<uint8_t>(b) : dalloc<uint8_t>(b);p.v_q4 = host ? halloc<uint8_t>(b) : dalloc<uint8_t>(b);@@ -91,7 +97,13 @@ struct Pools { // one K/V pool set of `pages` pagesvoid append(const Pools& pl, const int32_t* table, const int32_t* step, const float* kc, const float* vc,const k::QsaShapes& s, int fmt, const k::KvHostPools* host) {- if (fmt == k::kKvQ4) k::kv_append_q4_step(pl.p.k_q4, pl.p.v_q4, table, step, kc, vc, s, nullptr, host);+ if (fmt == k::kKvHybrid) { // exactly as qsa_layer: each half folded onto its own pool, host copy by halves+ const k::KvHostPools hk = host ? k::kv_hybrid_k_half(*host) : k::KvHostPools{},+ hv = host ? k::kv_hybrid_v_half(*host) : k::KvHostPools{};+ k::kv_append_q8_step(pl.p.k_q, pl.p.k_q, pl.p.k_scale, pl.p.k_scale, table, step, kc, kc, s, nullptr,+ host ? &hk : nullptr);+ k::kv_append_q4_step(pl.p.v_q4, pl.p.v_q4, table, step, vc, vc, s, nullptr, host ? &hv : nullptr);+ } else if (fmt == k::kKvQ4) k::kv_append_q4_step(pl.p.k_q4, pl.p.v_q4, table, step, kc, vc, s, nullptr, host);else if (fmt == k::kKvInt8) k::kv_append_q8_step(pl.p.k_q, pl.p.v_q, pl.p.k_scale, pl.p.v_scale, table, step, kc, vc, s, nullptr, host);else k::kv_append_step(pl.p.k_pool, pl.p.v_pool, table, step, kc, vc, s, nullptr, host);}@@ -119,7 +131,7 @@ std::vector<int32_t> selection(int64_t n_kv, int64_t width, std::mt19937& rng) {}bool run(int fmt) {- const char* name = fmt == k::kKvQ4 ? "q4_0" : fmt == k::kKvInt8 ? "int8" : "fp16";+ const char* name = fmt == k::kKvHybrid ? "k8v4" : fmt == k::kKvQ4 ? "q4_0" : fmt == k::kKvInt8 ? "int8" : "fp16";k::QsaShapes s = k::qsa_real_shapes();const int64_t N = 40000, n_blocks = (N + 3) / 4, n_slots = 8 * 516 + 700; // must evict: slots < blocksconst int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s), NQ = 8;@@ -337,8 +349,8 @@ bool run(int fmt) {int main() {std::printf("kv_stream_parity: streamed vs resident KV, bitwise\n");- const bool a = run(k::kKvInt8), b = run(k::kKvF16), c = run(k::kKvQ4);- if (!a || !b || !c) ++g_fail;+ const bool a = run(k::kKvInt8), b = run(k::kKvF16), c = run(k::kKvQ4), d = run(k::kKvHybrid);+ if (!a || !b || !c || !d) ++g_fail;std::printf(g_fail ? "FAIL\n" : "PASS\n");return g_fail ? 1 : 0;}diff --git a/sycl/src/kernels/mmvq_multi_parity.cpp b/sycl/src/kernels/mmvq_multi_parity.cppnew file mode 100644index 000000000..fdcd2f217--- /dev/null+++ b/sycl/src/kernels/mmvq_multi_parity.cpp@@ -0,0 +1,319 @@+// src/kernels/mmvq_multi_parity.cpp - the multi_exact contract of native_mmvq, tested bitwise.+//+// build/mmvq_multi_parity+//+// WHY IT EXISTS. `include/strata/kernels/native_mmvq.hpp` says of `native_mmvq_set_multi_exact`:+//+// "true (default): the ncols == 1 layout, every column bitwise equal to a single-column call"+//+// and `include/strata/core/verify.hpp` counts "multi-column MMVQ in exact mode" among the reasons the verify window+// produces what greedy decode would, bit for bit. Nothing tested that sentence: `iq_parity` calls `native_mmvq`+// with two columns and compares against a float64 reference at 2e-2, which cannot see a difference between one+// column and T columns.+//+// WHAT IT COMPARES. The SAME Q8_1 bytes: one T-column call against T single-column calls, each reading column j+// from the same buffer (the header: "its Q8_1 blocks at j * n_in / 32"). The quantization is shared, so the only+// thing under test is how the columns are laid out.+//+// THE DATA. The weights are random bytes, except each block's fp16 scales (`d`, and `dmin` where the format has+// one), which are rewritten as normal fp16 values in +-[2^-10, 2^-5): random bytes there would put inf and NaN in+// the outputs, and on the GPU every NaN comes out as the same canonical bit pattern, so a NaN output compares equal+// whatever operations produced it and proves nothing. With finite scales and finite normal activations (the+// precondition the header puts on the input) every output is finite, and a non-finite one fails the test.+//+// THE NEGATIVE CONTROL. The same comparison with `multi_exact` off must find differences, or the test has no power+// and its pass means nothing. Where it has power depends on T: in `native_mmvq.cu` the generic layout uses+// `NW = NCOLS <= 4 ? 4 : 2` warps, and with `WARPS = 4` and `BPI = F::BPI * NW / WARPS` it coincides with the+// exact layout at T <= 4. So the control is ASSERTED on T > 4 for every case, and at T <= 4 its silence is+// reported as that coincidence rather than skipped. The control needs a row long enough for the two layouts to+// group blocks differently: IQ4_XS takes 16 blocks per iteration with 4 warps and 8 with 2, so at n_in = 2048 (8+// blocks of 256) each thread holds at most one block in both layouts and they coincide; its case uses n_in = 4096.+#define DPCT_PROFILING_ENABLED+#include <sycl/sycl.hpp>+#include <dpct/dpct.hpp>+#include "strata/kernels/iq_kernels.hpp"+#include "strata/kernels/native_mmvq.hpp"++#include <cmath>+#include <cstdint>+#include <cstdio>+#include <cstdlib>+#include <string>+#include <cstring>+#include <random>+#include <vector>++namespace {++struct Case {+ const char* name;+ int type; // stable GGML type id, from the list in native_mmvq.hpp+ int n_in;+ int n_out;+ int block_elems; // elements per weight block+ int block_bytes;+ int scale_at[2]; // byte offsets of the block's fp16 scales in native_mmvq.cu's block structs; -1 = none+};++// the types a head or a projection can have in this model+const Case CASES[] = {+ {"Q4_0", 2, 2048, 512, 32, 18, {0, -1}}, // Q40Block: half d+ {"Q8_0", 8, 2048, 512, 32, 34, {0, -1}}, // Q80Block: half d+ {"Q4_K", 12, 2048, 512, 256, 144, {0, 2}}, // Q4KBlock: half2 dm+ {"Q5_K", 13, 2048, 512, 256, 176, {0, 2}}, // Q5KBlock: half2 dm+ {"Q6_K", 14, 2048, 512, 256, 210, {208, -1}}, // Q6KBlock: half d after ql, qh, scales+ {"IQ4_XS", 23, 4096, 512, 256, 136, {0, -1}}, // IQ4XSBlock: half d; n_in 4096, see THE NEGATIVE CONTROL+ {"Q5_K wide", 13, 4096, 2048, 256, 176, {0, 2}},+};++// a normal fp16 in +-[2^-10, 2^-5): exponent field 5..9 (bias 15), any mantissa, either sign+uint16_t sane_half(std::mt19937& rng) {+ const uint32_t r = rng();+ return (uint16_t) (((r >> 31) << 15) | ((5u + (r >> 10) % 5u) << 10) | (r & 0x3ffu));+}++// T = 4 is the last width where the two layouts coincide, T = 5 the first where they differ+const int WIDTHS[] = {1, 2, 3, 4, 5, 6, 8};+constexpr int COINCIDE_MAX_T = 4;++bool ck(dpct::err0 e, const char *what) {+ if (e == 0) return true;+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+ std::printf("CUDA: %s: %s\n", what, dpct::get_error_string_dummy(e));+ return false;+}++// Returns the number of outputs that differ bit for bit; counts the non-finite outputs and the differences on+// outputs that are finite in both paths.+long long compare(const Case &c, int T, dpct::queue_ptr s, long long &nonfinite,+ long long &diff_finite, bool &ran) try {+ ran = false;+ if (!strata::kernels::native_mmvq_supported(c.type)) return -1;++ const std::size_t wbytes = strata::kernels::native_mmvq_weight_bytes(c.type, c.n_in, c.n_out);+ const std::size_t qcol = strata::kernels::native_q8_1_bytes(c.n_in, 1); // Q8_1 bytes of ONE column+ const std::size_t qall = strata::kernels::native_q8_1_bytes(c.n_in, T);+ if (qall != qcol * (std::size_t) T) {+ std::printf("%-12s T=%d: the Q8_1 bytes of T columns (%zu) are not T times those of one (%zu): the test "+ "assumes contiguous columns and they are not\n", c.name, T, qall, qcol);+ return -1;+ }++ std::mt19937 rng(1234u + (unsigned) c.type * 97u + (unsigned) T);+ std::vector<uint8_t> w(wbytes);+ for (auto& b : w) b = (uint8_t) (rng() & 0xff);+ const std::size_t n_blocks = (std::size_t) c.n_out * (std::size_t) (c.n_in / c.block_elems);+ if (n_blocks * (std::size_t) c.block_bytes != wbytes) {+ std::printf("%-12s T=%d: %zu blocks of %d bytes are not the %zu weight bytes native_mmvq expects\n", c.name,+ T, n_blocks, c.block_bytes, wbytes);+ return -1;+ }+ for (std::size_t k = 0; k < n_blocks; ++k)+ for (int at : c.scale_at)+ if (at >= 0) {+ const uint16_t h = sane_half(rng);+ std::memcpy(&w[k * (std::size_t) c.block_bytes + (std::size_t) at], &h, 2);+ }+ std::vector<float> x((std::size_t) T * c.n_in);+ std::normal_distribution<float> nd(0.f, 1.f);+ for (auto& v : x) v = nd(rng);++ void* dw = nullptr;+ void* xq = nullptr;+ float* dx = nullptr;+ float* dmulti = nullptr;+ float* dsingle = nullptr;+ const std::size_t ybytes = (std::size_t) T * c.n_out * 4;+ if (!ck(DPCT_CHECK_ERROR(dw = (void *)sycl::malloc_device(+ wbytes, dpct::get_in_order_queue())),+ "malloc w") ||+ !ck(DPCT_CHECK_ERROR(xq = (void *)sycl::malloc_device(+ qall, dpct::get_in_order_queue())),+ "malloc xq") ||+ !ck(DPCT_CHECK_ERROR(dx = (float *)sycl::malloc_device(+ x.size() * 4, dpct::get_in_order_queue())),+ "malloc x") ||+ !ck(DPCT_CHECK_ERROR(dmulti = (float *)sycl::malloc_device(+ ybytes, dpct::get_in_order_queue())),+ "malloc multi") ||+ !ck(DPCT_CHECK_ERROR(dsingle = (float *)sycl::malloc_device(+ ybytes, dpct::get_in_order_queue())),+ "malloc single"))+ return -1;+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ if (!ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dw, w.data(), wbytes).wait()),+ "copy w") ||+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable memory.+ If the memory is not pageable, call wait() on event return by memcpy API+ to ensure synchronization behavior.+ */+ !ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dx, x.data(), x.size() * 4).wait()),+ "copy x"))+ return -1;++ // ONE quantization, shared by both paths: the quantization is not under test+ strata::kernels::quantize_q8_1_rows(dx, T, c.n_in, xq, s);+ if (!ck(DPCT_CHECK_ERROR(s->wait()), "quantize")) return -1;++ try {+ strata::kernels::native_mmvq(c.type, dw, xq, dmulti, c.n_in, c.n_out, T, s);+ for (int j = 0; j < T; ++j)+ strata::kernels::native_mmvq(c.type, dw, (const uint8_t*) xq + (std::size_t) j * qcol,+ dsingle + (std::size_t) j * c.n_out, c.n_in, c.n_out, 1, s);+ } catch (const std::exception& e) {+ std::printf("%-12s T=%d: %s\n", c.name, T, e.what());+ return -1;+ }+ if (!ck(DPCT_CHECK_ERROR(s->wait()), "mmvq")) return -1;++ std::vector<uint32_t> a((std::size_t) T * c.n_out), b(a.size());+ if (!ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(a.data(), dmulti, ybytes)+ .wait()),+ "read multi") ||+ !ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(b.data(), dsingle, ybytes)+ .wait()),+ "read single"))+ return -1;++ long long diff = 0;+ nonfinite = 0;+ diff_finite = 0;+ for (std::size_t i = 0; i < a.size(); ++i) {+ float fa, fb;+ std::memcpy(&fa, &a[i], 4);+ std::memcpy(&fb, &b[i], 4);+ const bool both_finite = std::isfinite(fa) && std::isfinite(fb);+ if (!both_finite) ++nonfinite;+ if (a[i] != b[i]) {+ ++diff;+ if (both_finite) ++diff_finite;+ }+ }+ sycl::free(dw, dpct::get_in_order_queue());+ sycl::free(xq, dpct::get_in_order_queue());+ sycl::free(dx, dpct::get_in_order_queue());+ sycl::free(dmulti, dpct::get_in_order_queue());+ sycl::free(dsingle, dpct::get_in_order_queue());+ ran = true;+ return diff;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++struct Totals {+ long long checked = 0, diff = 0, diff_finite = 0, nonfinite = 0; // all widths+ long long diff_finite_wide = 0; // T > COINCIDE_MAX_T only+ int powerless_cases = 0; // cases where the control found no difference at any T > COINCIDE_MAX_T+};++int sweep(bool exact, dpct::queue_ptr s, Totals &t) {+ strata::kernels::native_mmvq_set_multi_exact(exact);+ if (strata::kernels::native_mmvq_multi_exact() != exact) {+ std::printf("native_mmvq_multi_exact() does not reflect what was set\n");+ return 1;+ }+ std::printf("\n=== multi_exact %s ===\n", exact ? "ON (the default)" : "off (negative control)");+ std::printf("%-12s %3s %10s %10s %14s %10s\n", "type", "T", "outputs", "bits diff", "finite diff", "nonfinite");+ int bad = 0;+ for (const Case& c : CASES) {+ long long case_wide = 0;+ for (int T : WIDTHS) {+ long long nf = 0, dfin = 0;+ bool ran = false;+ const long long diff = compare(c, T, s, nf, dfin, ran);+ if (!ran) { ++bad; continue; }+ const long long n = (long long) T * c.n_out;+ t.checked += n;+ t.diff += diff;+ t.diff_finite += dfin;+ t.nonfinite += nf;+ if (T > COINCIDE_MAX_T) { t.diff_finite_wide += dfin; case_wide += dfin; }+ const char* verdict;+ if (exact) verdict = diff == 0 ? "ok" : "FAIL";+ else if (dfin > 0) verdict = "control sees it";+ else verdict = T <= COINCIDE_MAX_T ? "layouts coincide here (NW = 4)" : "no power at this T";+ std::printf("%-12s %3d %10lld %10lld %14lld %10lld %s\n", c.name, T, n, diff, dfin, nf, verdict);+ if (exact && diff != 0) ++bad;+ }+ if (!exact && case_wide == 0) ++t.powerless_cases;+ }+ return bad;+}++} // namespace++int main() try {+ dpct::queue_ptr s;+ if (!ck(DPCT_CHECK_ERROR(s = dpct::get_current_device().create_queue(true)),+ "stream create")) return 1;++ Totals on, off;+ const int bad = sweep(true, s, on);+ const int bad_off = sweep(false, s, off);+ strata::kernels::native_mmvq_set_multi_exact(true); // back to the default++ std::printf("\nmulti_exact on: %lld outputs compared, %lld differ bitwise, %lld non-finite\n",+ on.checked, on.diff, on.nonfinite);+ std::printf("multi_exact off: %lld outputs compared, %lld differ bitwise (%lld on finite outputs, %lld at T > %d)\n",+ off.checked, off.diff, off.diff_finite, off.diff_finite_wide, COINCIDE_MAX_T);++ if (on.nonfinite != 0 || off.nonfinite != 0) {+ std::printf("\nmmvq_multi_parity: FAILED. %lld non-finite outputs from finite scales and activations: the "+ "bit comparison is only meaningful on finite outputs.\n", on.nonfinite + off.nonfinite);+ return 1;+ }+ if (bad != 0 || bad_off != 0) {+ std::printf("\nmmvq_multi_parity: FAILED. %d case(s) with multi_exact on differ from single-column calls "+ "or did not run, %d case(s) did not run with it off. If they differ, the sentence in "+ "native_mmvq.hpp does not hold, and neither does the bit-exactness verify.hpp claims.\n",+ bad, bad_off);+ return 1;+ }+ // THE NEGATIVE CONTROL, asserted where it can see something: past T = 4 the generic layout is a different one,+ // so if it still finds no difference the comparison cannot tell the layouts apart and the pass proves nothing.+#if defined(STRATA_HIP_GFX906)+ // gfx906: the wave64 layout (one wavefront per row) is the same kernel for every column count, so multi_exact+ // has nothing to switch and the control cannot see a difference. The control with power is the CUDA layout:+ // ctest's mmvq_multi_parity_cuda_layout runs this with STRATA_MMVQ_WAVE=0.+ if (off.powerless_cases != 0 && !(std::getenv("STRATA_MMVQ_WAVE") && std::string(std::getenv("STRATA_MMVQ_WAVE")) == "0")) {+ std::printf("\nmmvq_multi_parity: ok (gfx906 wave64 layout: every column count runs the same exact kernel, "+ "so the negative control has no other layout to find; mmvq_multi_parity_cuda_layout checks it).\n");+ return 0;+ }+#endif+ if (off.powerless_cases != 0) {+ std::printf("\nmmvq_multi_parity: FAILED (no power). In %d case(s) no output differs with multi_exact off at "+ "any T > %d, where the generic layout is not the exact one: for those cases this comparison "+ "cannot tell the two layouts apart, so their pass above proves nothing.\n", off.powerless_cases,+ COINCIDE_MAX_T);+ return 1;+ }+ std::printf("\nmmvq_multi_parity: ok. With multi_exact on every column is bitwise equal to a single-column "+ "call; with it off the control finds differences at T > %d in every case, so the comparison has "+ "power.\n",+ COINCIDE_MAX_T);+ return 0;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}diff --git a/sycl/src/kernels/native_expert_bench.cpp b/sycl/src/kernels/native_expert_bench.cppnew file mode 100644index 000000000..48e048762--- /dev/null+++ b/sycl/src/kernels/native_expert_bench.cpp@@ -0,0 +1,171 @@+// src/kernels/native_expert_bench.cpp - the grouped native experts on real GGUF rows: one AMD layout against+// another, bit for bit, and each one's time.+//+// build/native_expert_bench <shard1.gguf> <layer[,layer...]> <groups> <tokens per group> <ref mode> <mode> [iters]+//+// Modes are STRATA_EXP_MODE values. A group is one expert (distinct blobs, ~2 MB each, so G >= 8 does not fit+// in L2); its entries read distinct tokens of an 8-token window. The output must be bitwise equal to the+// reference mode's: the verify window's text depends on it.+#define DPCT_PROFILING_ENABLED+#include <sycl/sycl.hpp>+#include <dpct/dpct.hpp>+#include "strata/artifact/gguf_reader.hpp"+#include "strata/kernels/cpu/native_expert.hpp"+#include "strata/kernels/iq_kernels.hpp"++#include "ggml.h"++#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <random>+#include <sstream>+#include <string>+#include <vector>++namespace cpu = strata::kernels::cpu;+namespace K = strata::kernels;++int main(int argc, char** argv) {+ setvbuf(stdout, nullptr, _IONBF, 0);+ if (argc < 7) {+ std::fprintf(stderr, "usage: native_expert_bench <shard1.gguf> <layer[,layer]> <groups> <tokens> <ref mode> <mode> [iters]\n");+ return 2;+ }+ strata::GgufFile gguf(argv[1]);+ std::vector<int> layers;+ {+ std::stringstream ss(argv[2]);+ std::string t;+ while (std::getline(ss, t, ',')) layers.push_back(std::atoi(t.c_str()));+ }+ const int G = std::atoi(argv[3]), T = std::atoi(argv[4]), mref = std::atoi(argv[5]), mode = std::atoi(argv[6]);+ const int iters = argc > 7 ? std::atoi(argv[7]) : 200;+ const int NTOK = 8;+ if (T < 1 || T > NTOK || G < 1) { std::fprintf(stderr, "tokens 1..8, groups >= 1\n"); return 2; }+ const int64_t H = 2560, FF_FULL = 640, FF = FF_FULL; // Flash-Next's expert geometry+ int failures = 0;+ dpct::queue_ptr s;+ s = dpct::get_current_device().create_queue(true);+ dpct::event_ptr e0, e1;+ e0 = new sycl::event();+ e1 = new sycl::event();+ for (int l : layers) {+ const strata::TensorInfo* t[3] = {};+ const char* roles[3] = {"gate", "up", "down"};+ for (const auto& ti : gguf.tensors())+ for (int r = 0; r < 3; ++r)+ if (ti.name == "blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight") t[r] = &ti;+ if (!t[0] || !t[1] || !t[2]) { std::printf("layer %d: no expert tensors\n", l); ++failures; continue; }+ cpu::NativeFmt f;+ std::string err;+ if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF, f, err)) {+ std::printf("layer %d: %s\n", l, err.c_str()); ++failures; continue;+ }+ cpu::NativeFmt ff; // the full expert's geometry, for strides into the GGUF+ if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF_FULL, ff, err)) {+ std::printf("layer %d: %s\n", l, err.c_str()); ++failures; continue;+ }+ const size_t dsz = f.bytes - f.down_off, dsz_full = ff.bytes - ff.down_off;+ const size_t drow = dsz / H, drow_full = dsz_full / H;+ std::vector<uint8_t> blobs((size_t) G * f.bytes);+ for (int g = 0; g < G; ++g) {+ const size_t E = (size_t) ((g * 37 + 5) % 256);+ uint8_t* b = blobs.data() + (size_t) g * f.bytes;+ std::memcpy(b, gguf.tensor_data(*t[0]) + E * ff.up_off, f.up_off);+ std::memcpy(b + f.up_off, gguf.tensor_data(*t[1]) + E * ff.up_off, f.up_off);+ for (int64_t r = 0; r < H; ++r)+ std::memcpy(b + f.down_off + r * drow, gguf.tensor_data(*t[2]) + E * dsz_full + r * drow_full, drow);+ }+ std::mt19937 rng(17 + l);+ std::normal_distribution<float> nd(0.f, 1.f);+ std::vector<float> x((size_t) NTOK * H);+ for (auto& v : x) v = nd(rng);+ const int NE = G * T;+ std::vector<unsigned long long> ptr(G);+ std::vector<int32_t> start(G + 1), dst(NE), tok(NE);+ const auto L = K::native_expert_layout(f.gu_type, f.d_type, H, FF);+ uint8_t* dblob;+ void *dx, *dxq, *dscr;+ float* dout;+ unsigned long long* dptr;+ int32_t *dstart, *dn, *ddst, *dtok;+ cudaMalloc((void**) &dblob, blobs.size());+ cudaMalloc(&dx, x.size() * 4);+ cudaMalloc(&dxq, (size_t) NTOK * H / 32 * 36);+ cudaMalloc(&dscr, K::native_expert_scratch_bytes(NE, FF));+ cudaMalloc((void**) &dout, (size_t) NE * H * 4);+ cudaMalloc((void**) &dptr, (size_t) G * 8);+ cudaMalloc((void**) &dstart, (size_t) (G + 1) * 4);+ cudaMalloc((void**) &dn, 4);+ cudaMalloc((void**) &ddst, (size_t) NE * 4);+ cudaMalloc((void**) &dtok, (size_t) NE * 4);+ for (int g = 0; g < G; ++g) {+ ptr[g] = (unsigned long long) (dblob + (size_t) g * f.bytes);+ start[g] = g * T;+ for (int j = 0; j < T; ++j) {+ dst[g * T + j] = g * T + j;+ tok[g * T + j] = (g * 3 + j) % NTOK;+ }+ }+ start[G] = NE;+ cudaMemcpy(dblob, blobs.data(), blobs.size(), cudaMemcpyHostToDevice);+ cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice);+ cudaMemcpy(dptr, ptr.data(), (size_t) G * 8, cudaMemcpyHostToDevice);+ cudaMemcpy(dstart, start.data(), (size_t) (G + 1) * 4, cudaMemcpyHostToDevice);+ cudaMemcpy(dn, &G, 4, cudaMemcpyHostToDevice);+ cudaMemcpy(ddst, dst.data(), (size_t) NE * 4, cudaMemcpyHostToDevice);+ cudaMemcpy(dtok, tok.data(), (size_t) NE * 4, cudaMemcpyHostToDevice);+ K::quantize_q8_1_rows((const float*) dx, NTOK, H, dxq, s);+ auto run = [&](int m, int phase) {+ K::native_expert_set_mode(m, phase);+ K::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, G, NE, dxq, dscr, dout, s);+ };+ std::vector<float> ref((size_t) NE * H), got((size_t) NE * H);+ cudaMemsetAsync(dout, 0xff, got.size() * 4, s);+ run(mref, 0);+ cudaMemcpyAsync(ref.data(), dout, ref.size() * 4, cudaMemcpyDeviceToHost, s);+ cudaMemsetAsync(dout, 0xff, got.size() * 4, s);+ run(mode, 0);+ cudaMemcpyAsync(got.data(), dout, got.size() * 4, cudaMemcpyDeviceToHost, s);+ if (cudaStreamSynchronize(s) != cudaSuccess) { std::printf("layer %d: CUDA error\n", l); return 1; }+ size_t ndiff = 0;+ double worst = 0;+ for (size_t i = 0; i < ref.size(); ++i)+ if (std::memcmp(&ref[i], &got[i], 4) != 0) {+ ++ndiff;+ worst = std::fmax(worst, std::fabs((double) ref[i] - got[i]) / (std::fabs((double) ref[i]) + 1e-6));+ }+ auto time = [&](int m, int phase) {+ for (int i = 0; i < 10; ++i) run(m, phase);+ cudaEventRecord(e0, s);+ for (int i = 0; i < iters; ++i) run(m, phase);+ cudaEventRecord(e1, s);+ cudaEventSynchronize(e1);+ float ms = 0;+ cudaEventElapsedTime(&ms, e0, e1);+ return 1e3 * ms / iters;+ };+ const double gu_b = (double) G * 2 * f.up_off, d_b = (double) G * dsz;+ double us[2][3] = {{1e30, 1e30, 1e30}, {1e30, 1e30, 1e30}};+ for (int round = 0; round < 3; ++round) // interleaved, the minimum: the clocks wander between runs+ for (int k = 0; k < 2; ++k)+ for (int p = 0; p < 3; ++p) us[k][p] = std::fmin(us[k][p], time(k ? mode : mref, p));+ std::printf("layer %2d %-7s/%-6s G %d T %d | mode %d: all %7.1f us gu %7.1f us (%3.0f GB/s) down %6.1f us (%3.0f GB/s)"+ " | mode %d: all %7.1f us gu %7.1f us (%3.0f GB/s) down %6.1f us (%3.0f GB/s) | %s\n",+ l, ggml_type_name((ggml_type) f.gu_type), ggml_type_name((ggml_type) f.d_type), G, T,+ mref, us[0][0], us[0][1], gu_b / us[0][1] / 1e3, us[0][2], d_b / us[0][2] / 1e3,+ mode, us[1][0], us[1][1], gu_b / us[1][1] / 1e3, us[1][2], d_b / us[1][2] / 1e3,+ ndiff ? "DIFFERS" : "bitwise equal");+ if (ndiff) {+ std::printf(" %zu of %zu outputs differ, worst rel %.2e\n", ndiff, ref.size(), worst);+ ++failures;+ }+ K::native_expert_set_mode(-1, 0);+ cudaFree(dblob); cudaFree(dx); cudaFree(dxq); cudaFree(dscr); cudaFree(dout); cudaFree(dptr);+ cudaFree(dstart); cudaFree(dn); cudaFree(ddst); cudaFree(dtok);+ }+ std::printf("native_expert_bench: %d differing\n", failures);+ return failures ? 1 : 0;+}diff --git a/sycl/src/kernels/native_grouped_parity.cpp b/sycl/src/kernels/native_grouped_parity.cppindex d20565eb2..da39852b7 100644--- a/sycl/src/kernels/native_grouped_parity.cpp+++ b/sycl/src/kernels/native_grouped_parity.cpp@@ -61,6 +61,7 @@ const char* name_of(int t) {case 42: return "Q2_0";case 12: return "Q4_K";case 13: return "Q5_K";+ case 14: return "Q6_K";case 7: return "Q5_1";case 8: return "Q8_0";default: return "?";@@ -447,7 +448,11 @@ int main(int argc, char** argv) {ck(DPCT_CHECK_ERROR(s = dpct::get_current_device().create_queue(true)),"stream");std::mt19937 rng(316);- for (int gu : {16, 17, 18, 21, 22, 23, 29, 42, 12, 13, 8}) // STRATA_GU_FMTS+ for (int gu : {16, 17, 18, 21, 22, 23, 29, 42, 12, 13,+#ifdef STRATA_Q6K_EXPERTS+ 14,+#endif+ 8}) // STRATA_GU_FMTSfor (int dt : {20, 23, 42, 7, 8}) check(gu, dt, 512, 256, s, rng); // STRATA_D_FMTS; IQ4_XS: n_ff % 256check(21, 20, 2560, 640, s, rng); // a model's shapescheck(21, 23, 2560, 768, s, rng);diff --git a/sycl/src/kernels/native_multi_parity.cpp b/sycl/src/kernels/native_multi_parity.cppnew file mode 100644index 000000000..2b5ee6885--- /dev/null+++ b/sycl/src/kernels/native_multi_parity.cpp@@ -0,0 +1,198 @@+// src/kernels/native_multi_parity.cpp - the multi-token router and the k = 10 combine, bitwise against their+// single-token contracts (#783 PR-c: route_multi, combine_k10_vec4).+//+// * native_router_top10_multi (one warp per token, 8 tokens per CTA) against native_router_top10 token by token,+// for n = 1..19 (a partial last CTA, and more than one CTA), on plain logits, on logits with exact ties and on+// logits with NaN (the router maps NaN to -FLT_MAX): ids and weights are compared with memcmp;+// * native_moe_combine / native_moe_combine_multi (k = 10 with a shared row takes the float4 kernel; a misaligned+// output, k = 9 and a null shared row take the scalar one) against a host replay of the documented contract:+// the first product rounds to F32, the next ones accumulate with FMA in expert order, the shared row is added+// once: memcmp.+#define DPCT_PROFILING_ENABLED+#include <sycl/sycl.hpp>+#include <dpct/dpct.hpp>+#include "strata/kernels/native_moe.hpp"+#include "strata/kernels/native_router.hpp"++#include <cmath>+#include <cstdint>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <random>+#include <string>+#include <vector>++namespace {++void check(dpct::err0 e, const char *what) {+}++template <typename T>+T* up(const std::vector<T>& h) {+ void* p = nullptr;+ check(DPCT_CHECK_ERROR(+ p = (void *)sycl::malloc_device(h.size() * sizeof(T) + 64,+ dpct::get_in_order_queue())),+ "malloc");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ p, h.data(), h.size() * sizeof(T)).wait()),+ "h2d");+ return (T*) p;+}+template <typename T>+std::vector<T> down(const T* d, size_t n) {+ std::vector<T> h(n);+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(h.data(), d, n * sizeof(T))+ .wait()),+ "d2h");+ return h;+}++} // namespace++int main(int argc, char**) {+ (void) argc;+ using namespace strata::kernels;+ std::mt19937 rng(783);+ std::normal_distribution<float> gauss(0.0f, 1.0f);+ int bad = 0;+ dpct::queue_ptr st = &dpct::get_in_order_queue();+ check(DPCT_CHECK_ERROR(st = dpct::get_current_device().create_queue(true)),+ "stream");++ // ---- the multi-token router+ for (int mode = 0; mode < 3; ++mode) {+ const char* names[] = {"random logits", "exact ties", "NaN logits"};+ int mode_bad = 0, cases = 0;+ for (int n = 1; n <= 19; ++n) {+ std::vector<float> lg((size_t) n * 512);+ for (auto& v : lg) v = gauss(rng) * 2.0f;+ if (mode == 1)+ for (size_t i = 0; i < lg.size(); ++i) lg[i] = (float) (int) (lg[i] * 2.0f) * 0.5f; // coarse: many exact ties+ if (mode == 2)+ for (int t = 0; t < n; ++t) lg[(size_t) t * 512 + (size_t) (rng() % 512)] = std::nanf("");+ float* d_l = up(lg);+ int32_t *d_i, *d_ir;+ float *d_w, *d_wr;+ check(DPCT_CHECK_ERROR(+ d_i = (int32_t *)sycl::malloc_device(+ (size_t)n * 10 * 4, dpct::get_in_order_queue())),+ "i");+ check(DPCT_CHECK_ERROR(+ d_ir = (int32_t *)sycl::malloc_device(+ (size_t)n * 10 * 4, dpct::get_in_order_queue())),+ "ir");+ check(DPCT_CHECK_ERROR(+ d_w = (float *)sycl::malloc_device(+ (size_t)n * 10 * 4, dpct::get_in_order_queue())),+ "w");+ check(DPCT_CHECK_ERROR(+ d_wr = (float *)sycl::malloc_device(+ (size_t)n * 10 * 4, dpct::get_in_order_queue())),+ "wr");+ native_router_top10_multi(d_l, d_i, d_w, n, st);+ for (int t = 0; t < n; ++t) native_router_top10(d_l + (size_t) t * 512, d_ir + t * 10, d_wr + t * 10, st);+ check(DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()),+ "sync");+ const auto i1 = down(d_i, (size_t) n * 10), i2 = down(d_ir, (size_t) n * 10);+ const auto w1 = down(d_w, (size_t) n * 10), w2 = down(d_wr, (size_t) n * 10);+ ++cases;+ if (std::memcmp(i1.data(), i2.data(), i1.size() * 4) != 0 || std::memcmp(w1.data(), w2.data(), w1.size() * 4) != 0) {+ std::printf(" *** native_router_top10_multi n=%d (%s) differs from native_router_top10 ***\n", n, names[mode]);+ ++mode_bad;+ }+ sycl::free(d_l, dpct::get_in_order_queue());+ sycl::free(d_i, dpct::get_in_order_queue());+ sycl::free(d_ir, dpct::get_in_order_queue());+ sycl::free(d_w, dpct::get_in_order_queue());+ sycl::free(d_wr, dpct::get_in_order_queue());+ }+ std::printf(" %-52s %s (%d cases)\n", (std::string("router multi == single, ") + names[mode]).c_str(),+ mode_bad ? "*** NO ***" : "bitwise", cases);+ bad += mode_bad;+ }++ // ---- the combine+ struct Cfg { const char* name; int k; bool shared; int out_off; };+ const Cfg cfgs[] = {{"k=10 + shared (float4 kernel)", 10, true, 0}, {"k=10 + shared, output misaligned", 10, true, 1},+ {"k=10 without shared", 10, false, 0}, {"k=9 + shared", 9, true, 0}};+ const int N = 2048;+ for (const Cfg& c : cfgs) {+ int cfg_bad = 0, cases = 0;+ for (int n = 1; n <= 8; ++n) {+ std::vector<float> parts((size_t) n * c.k * N), w((size_t) n * c.k), sh((size_t) n * N);+ for (auto& v : parts) v = gauss(rng);+ for (auto& v : w) v = (float) (rng() % 1000) / 1000.0f;+ for (auto& v : sh) v = gauss(rng);+ float* d_p = up(parts);+ float* d_w = up(w);+ float* d_s = up(sh);+ float* d_o = nullptr;+ check(DPCT_CHECK_ERROR(+ d_o = (float *)sycl::malloc_device(+ (size_t)n * N * 4 + 64, dpct::get_in_order_queue())),+ "o");+ float* out = d_o + c.out_off;+ if (c.out_off) {+ // a misaligned output cannot take a multi launch of rows with the 4-float stride contract either way:+ // the rows are still n*N floats from `out`+ }+ native_moe_combine_multi(d_p, d_w, c.shared ? d_s : nullptr, out, N, c.k, n, st);+ check(DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()),+ "sync");+ const auto got = down(out, (size_t) n * N);+ std::vector<float> want((size_t) n * N);+ for (int t = 0; t < n; ++t)+ for (int col = 0; col < N; ++col) {+ float s = parts[((size_t) t * c.k) * N + col] * w[(size_t) t * c.k];+ for (int e = 1; e < c.k; ++e)+ s = std::fmaf(parts[((size_t) t * c.k + e) * N + col], w[(size_t) t * c.k + e], s);+ if (c.shared) s += sh[(size_t) t * N + col];+ want[(size_t) t * N + col] = s;+ }+ ++cases;+ if (std::memcmp(got.data(), want.data(), got.size() * 4) != 0) {+ std::printf(" *** native_moe_combine_multi n=%d (%s) differs from the contract's host replay ***\n", n, c.name);+ ++cfg_bad;+ }+ // the single-token call is the same arithmetic+ if (n == 1) {+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memset(d_o, 0, (size_t)N * 4 + 64)+ .wait()),+ "z");+ native_moe_combine(d_p, d_w, c.shared ? d_s : nullptr, out, N, c.k, st);+ check(DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()),+ "sync");+ const auto g1 = down(out, (size_t) N);+ ++cases;+ if (std::memcmp(g1.data(), want.data(), g1.size() * 4) != 0) {+ std::printf(" *** native_moe_combine (%s) differs from the contract's host replay ***\n", c.name);+ ++cfg_bad;+ }+ }+ sycl::free(d_p, dpct::get_in_order_queue());+ sycl::free(d_w, dpct::get_in_order_queue());+ sycl::free(d_s, dpct::get_in_order_queue());+ sycl::free(d_o, dpct::get_in_order_queue());+ }+ std::printf(" %-52s %s (%d cases)\n", (std::string("combine ") + c.name).c_str(), cfg_bad ? "*** NO ***" : "bitwise", cases);+ bad += cfg_bad;+ }++ std::printf("\nnative_multi: %d failures\n", bad);+ if (bad) return 1;+ std::printf("native_multi_parity OK\n");+ return 0;+}diff --git a/sycl/src/kernels/qsa_parity.cpp b/sycl/src/kernels/qsa_parity.cppindex 0da7ce0d1..dd8ce2f93 100644--- a/sycl/src/kernels/qsa_parity.cpp+++ b/sycl/src/kernels/qsa_parity.cpp@@ -1531,6 +1531,53 @@ int main(int argc, char** argv) {check(DPCT_CHECK_ERROR(cs->wait()), "append");}strata::kernels::native_qsa_indexer_append_batch(drawAll.p, NB, 0, BASE, dw_kn.p, EPS, bufsB, S, MC, sc, cs);+ // #783 PR-d: native_qsa_indexer_append_steps - the verify window's n cells in one launch (positions at a+ // stride: kStepCount in a window, 1 in the commit graph) - leaves the same buffers as the sequential calls+ for (const int stride : {1, 5}) {+ Dev<float> pooledC(prows), deadC(IDXD), tailC(trows);+ Dev<int32_t> bposC(1), dposC((size_t) NB * stride);+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memset(pooledC.p, 0, prows * 4)+ .wait()),+ "zero");+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memset(deadC.p, 0, IDXD * 4)+ .wait()),+ "zero");+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memset(tailC.p, 0, trows * 4)+ .wait()),+ "zero");+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memset(bposC.p, 0, 4)+ .wait()),+ "zero");+ std::vector<int32_t> hp((size_t) NB * stride, -1);+ for (int64_t t = 0; t < NB; ++t) hp[(size_t) t * stride] = (int32_t) t;+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization+ memcpy, assuming in the original code the source host memory is+ pageable memory. If the memory is not pageable, call wait() on+ event return by memcpy API to ensure synchronization behavior.+ */+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ dposC.p, hp.data(), hp.size() * 4).wait()),+ "pos");+ strata::kernels::QsaIndexerBuffers bufsC{tailC.p, deadC.p, pooledC.p, bposC.p};+ strata::kernels::native_qsa_indexer_append_steps(drawAll.p, dposC.p, stride, (int) NB, BASE, dw_kn.p, EPS,+ bufsC, S, MC, sc, cs);+ check(DPCT_CHECK_ERROR(cs->wait()), "sync");+ const std::vector<float> pc = pooledC.get(prows), dc = deadC.get((size_t) IDXD), tc = tailC.get(trows);+ const std::vector<int32_t> bc = bposC.get(1);+ const std::vector<float> pa2 = pooledA.get(prows), da2 = deadA.get((size_t) IDXD), ta2 = tailA.get(trows);+ const std::vector<int32_t> ba2 = bposA.get(1);+ const bool same = std::memcmp(pc.data(), pa2.data(), pc.size() * 4) == 0 &&+ std::memcmp(dc.data(), da2.data(), dc.size() * 4) == 0 &&+ std::memcmp(tc.data(), ta2.data(), tc.size() * 4) == 0 && bc[0] == ba2[0];+ std::printf(" %-44s %s\n", (std::string("append_steps (stride ") + std::to_string(stride) + ") vs sequential, " + var.name).c_str(),+ same ? "bit-identical" : "*** WRONG ***");+ if (!same) ++g_bad;+ }check(DPCT_CHECK_ERROR(cs->wait()), "sync");const std::vector<float> pa = pooledA.get(prows), pb = pooledB.get(prows);const std::vector<float> da = deadA.get((size_t) IDXD), db = deadB.get((size_t) IDXD);diff --git a/sycl/src/kernels/qsa_prompt_attn_parity.cpp b/sycl/src/kernels/qsa_prompt_attn_parity.cppindex 1c964bd3d..b0f44347f 100644--- a/sycl/src/kernels/qsa_prompt_attn_parity.cpp+++ b/sycl/src/kernels/qsa_prompt_attn_parity.cpp@@ -65,6 +65,19 @@ uint16_t f2h(float f) {}int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16, 2 q4_0+#if !defined(__HIPCC__) && !defined(STRATA_USE_HIP)+ if (fmt == 2) { // mode 4 (Q4_0 KV) runs on sm_80 and newer only: below that the dispatcher keeps the old kernel+ int dev = 0, major = 0;+ ck(DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()), "device");+ ck(DPCT_CHECK_ERROR(major = dpct::get_device(dev).get_major_version()),+ "cc");+ if (major < 8) {+ std::printf("SKIP q4_0 ctx %lld: the tensor-core kernel takes Q4_0 KV on sm_80+ only (this device: sm_%d)\n",+ (long long) ctx, major);+ return 0;+ }+ }+#endifconst k::QsaShapes s = k::qsa_real_shapes();const int64_t HD = s.head_dim, NKV = s.n_head_kv, NH = s.n_head, PS = s.page_size;const int64_t pages = (ctx + PS - 1) / PS, rows = pages * NKV * PS;@@ -137,6 +150,62 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16, 2std::sort(v.begin(), v.end());std::copy(v.begin(), v.end(), sel);}+ // QA_SAME=1 (S23 probe): every query reads the same first-w cells - the best case of any K/V sharing between queries+ // (all loads hit the caches); QA_SAME=2: query i reads a window of w cells at i / 4 * 64 (neighbours share ~90%)+ if (const char* sm = std::getenv("QA_SAME")) {+ const int mode = std::atoi(sm);+ for (int64_t i = 0; i < nq; ++i) {+ const int64_t w = steps[i * k::kStepCount + k::kStepWidth], nkv = ctx - nq + i + 1;+ if (w == nkv) continue;+ if (mode == 3 || mode == 4) { // 3: w random cells per query (no overlap beyond chance); 4: a 4-query group shares+ // one random set of w - 512 cells (the union of 4 queries = 1x), the last 512 cells recent+ std::mt19937 r3((unsigned) (mode == 3 ? i : i / 4) * 2654435761u + 7);+ std::vector<int32_t> all((size_t) (nkv - 512));+ for (int64_t c = 0; c < nkv - 512; ++c) all[c] = (int32_t) c;+ std::shuffle(all.begin(), all.end(), r3);+ std::vector<int32_t> v(all.begin(), all.begin() + (w - 512));+ for (int64_t c = nkv - 512; c < nkv; ++c) v.push_back((int32_t) c);+ std::sort(v.begin(), v.end());+ std::copy(v.begin(), v.end(), ids.data() + i * cap);+ continue;+ }+ const int64_t base = mode == 1 ? 0 : std::min<int64_t>(i / 4 * 64, nkv - w);+ for (int64_t c = 0; c < w; ++c) ids[i * cap + c] = (int32_t) (base + c);+ }+ }+ // QA_DUMP=<file> QA_LAYER=n (S23 probe): the engine's own selections (STRATA_QSA_DUMP records {layer, pos0, T, cap} ++ // T*cap cells): the last record of that layer, whose T must be nq and pos0 + T ctx+ if (const char* df = std::getenv("QA_DUMP")) {+ const int want = std::getenv("QA_LAYER") ? std::atoi(std::getenv("QA_LAYER")) : 3;+ std::FILE* f = std::fopen(df, "rb");+ if (!f) { std::fprintf(stderr, "QA_DUMP: cannot open\n"); std::exit(2); }+ int32_t h[4];+ long at = -1;+ while (std::fread(h, 4, 4, f) == 4) {+ const long data = std::ftell(f);+ if (h[0] == want && h[2] == nq && h[1] + h[2] == ctx && h[3] == cap) at = data;+ std::fseek(f, (long) h[2] * h[3] * 4, SEEK_CUR);+ }+ if (at < 0) { std::fprintf(stderr, "QA_DUMP: no record for layer %d, T %lld, ctx %lld\n", want, (long long) nq, (long long) ctx); std::exit(2); }+ std::fseek(f, at, SEEK_SET);+ if (std::fread(ids.data(), 4, ids.size(), f) != ids.size()) std::exit(2);+ std::fclose(f);+ for (int grp : {2, 4, 8, 16}) { // the union of `grp` neighbouring queries' cells against grp x the width+ double su = 0, sw = 0;+ for (int64_t i0 = 0; i0 + grp <= nq; i0 += grp * 16) {+ std::vector<int32_t> u;+ for (int g2 = 0; g2 < grp; ++g2) {+ const int64_t w = steps[(i0 + g2) * k::kStepCount + k::kStepWidth];+ u.insert(u.end(), ids.begin() + (i0 + g2) * cap, ids.begin() + (i0 + g2) * cap + w);+ sw += (double) w;+ }+ std::sort(u.begin(), u.end());+ su += (double) (std::unique(u.begin(), u.end()) - u.begin());+ }+ std::printf("QA_DUMP overlap: %d-query groups read %.2fx the cells of one query (%.1f%% of %d x)\n", grp,+ su * grp / sw, 100.0 * su / sw, grp);+ }+ }k::QsaAttnPools pl;if (fmt == 2) { pl.k_q4 = up(k4); pl.v_q4 = up(v4); }else if (fmt == 1) { pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs); }@@ -192,6 +261,11 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16, 2.memcpy(nw.data(), d_new, nw.size() * 4).wait()),"down");+ { // a hash of the new kernel's output bits (bitwise A/B of two builds / switches)+ uint64_t hh = 1469598103934665603ull;+ for (float x : nw) { uint32_t u; std::memcpy(&u, &x, 4); hh = (hh ^ u) * 1099511628211ull; }+ std::printf("NEWHASH %016llx\n", (unsigned long long) hh);+ }// 1. FP64 reference on a sample of queriesdouble err_old = 0, err_new = 0, ref_scale = 0;for (int64_t i = 0; i < nq; i += std::max<int64_t>(1, nq / 16)) {@@ -290,8 +364,8 @@ int main(int argc, char** argv) {int dev = 0;hipDeviceProp_t prop{};if (hipGetDevice(&dev) != hipSuccess || hipGetDeviceProperties(&prop, dev) != hipSuccess) return 2;- if (std::strncmp(prop.gcnArchName, "gfx12", 5) != 0) {- std::printf("SKIP: %s is not gfx12 (the matrix-core prompt attention is RDNA4 only)\n", prop.gcnArchName);+ if (std::strncmp(prop.gcnArchName, "gfx12", 5) != 0 && std::strncmp(prop.gcnArchName, "gfx11", 5) != 0) {+ std::printf("SKIP: %s is not gfx11 / gfx12 (the matrix-core prompt attention)\n", prop.gcnArchName);return 77;}#if defined(_WIN32)diff --git a/sycl/src/kernels/qsa_topk_active_parity.cpp b/sycl/src/kernels/qsa_topk_active_parity.cppnew file mode 100644index 000000000..656507521--- /dev/null+++ b/sycl/src/kernels/qsa_topk_active_parity.cpp@@ -0,0 +1,127 @@+// Capacity 262144, live prefill up to the register boundary, and the legacy fallbacks.+// Compare selected IDs only: unused output padding is not part of the API contract.+#define DPCT_PROFILING_ENABLED+#include <sycl/sycl.hpp>+#include <dpct/dpct.hpp>+#include "strata/kernels/qsa.hpp"+#include "strata/kernels/qsa_select.hpp"+#include <algorithm>+#include <cstdio>+#include <cstdlib>+#include <random>+#include <vector>++namespace k = strata::kernels;+namespace {+void ck(dpct::err0 e) {+}+struct Case { int64_t ctx, queries; int mode; };+bool check(Case c) {+ constexpr int64_t stride = 262144 / 4 + 2;+ const auto s = k::qsa_real_shapes();+ const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s);+ std::vector<int32_t> steps((size_t)(c.queries * k::kStepCount));+ std::vector<float> scores((size_t)(c.queries * stride), -999.f);+ std::mt19937 rng(742913);+ std::uniform_real_distribution<float> random(0.f, 200.f);+ for (int64_t i = 0; i < c.queries; ++i) {+ auto* st = steps.data() + i * k::kStepCount;+ const int64_t pos = c.ctx - c.queries + i;+ st[k::kStepPos] = (int32_t)pos;+ st[k::kStepNKv] = (int32_t)(pos + 1);+ st[k::kStepNBid] = (int32_t)((pos + 1) / s.idx_block);+ st[k::kStepWidth] = (int32_t)k::qsa_selection_width(pos + 1, s);+ for (int64_t j = 0; j <= st[k::kStepNBid]; ++j)+ scores[(size_t)(i * stride + j)] = c.mode == 1 ? 0.f : c.mode == 2 ? float(j % 7) : random(rng);+ if ((pos + 1) % s.idx_block)+ scores[(size_t)(i * stride + st[k::kStepNBid])] += 1e9f;+ }+ int64_t active = steps[(size_t)((c.queries - 1) * k::kStepCount + k::kStepNBid)] + 1;+ if (c.mode == 3) active = 0;+ if (c.mode == 4) active = stride + 1;+ float* ds = nullptr;+ int32_t *dt = nullptr, *da = nullptr, *db = nullptr;+ ck(DPCT_CHECK_ERROR(ds = sycl::malloc_device<float>(+ scores.size(), dpct::get_in_order_queue())));+ ck(DPCT_CHECK_ERROR(dt = sycl::malloc_device<int32_t>(+ steps.size(), dpct::get_in_order_queue())));+ ck(DPCT_CHECK_ERROR(+ da = sycl::malloc_device<int32_t>((size_t)(c.queries * cap),+ dpct::get_in_order_queue())));+ ck(DPCT_CHECK_ERROR(+ db = sycl::malloc_device<int32_t>((size_t)(c.queries * cap),+ dpct::get_in_order_queue())));+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ ds, scores.data(), scores.size() * sizeof(float)).wait()));+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ dt, steps.data(), steps.size() * sizeof(int32_t)).wait()));+ // No bound: the exact capacity-based dispatch used by captured decode.+ k::qsa_block_topk(ds, dt, c.queries, stride, cap, s, da, nullptr);+ k::qsa_block_topk(ds, dt, c.queries, stride, cap, s, db, nullptr, active);+ ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()));+ std::vector<int32_t> a((size_t)(c.queries * cap)), b(a.size());+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(a.data(), da, a.size() * sizeof(int32_t))+ .wait()));+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(b.data(), db, b.size() * sizeof(int32_t))+ .wait()));+ bool ok = true;+ for (int64_t i = 0; i < c.queries; ++i) {+ const int64_t w = steps[(size_t)(i * k::kStepCount + k::kStepWidth)];+ if (!std::equal(a.begin() + i * cap, a.begin() + i * cap + w, b.begin() + i * cap)) {+ std::fprintf(stderr, "FAIL ctx=%lld queries=%lld mode=%d row=%lld\n",+ (long long)c.ctx, (long long)c.queries, c.mode, (long long)i);+ ok = false;+ break;+ }+ }+ ck(DPCT_CHECK_ERROR(sycl::free(ds, dpct::get_in_order_queue())));+ ck(DPCT_CHECK_ERROR(sycl::free(dt, dpct::get_in_order_queue())));+ ck(DPCT_CHECK_ERROR(sycl::free(da, dpct::get_in_order_queue())));+ ck(DPCT_CHECK_ERROR(sycl::free(db, dpct::get_in_order_queue())));+ return ok;+}+}++int main() try {+ int devices = 0;+ if (DPCT_CHECK_ERROR(devices = dpct::device_count()) != 0 || devices == 0) {+ std::puts("SKIP: no CUDA device");+ return 77;+ }+ // the active-bound dispatch is Turing's in the engine; forced here so every CUDA card checks it+#if defined(_WIN32)+ _putenv_s("STRATA_TOPK_ACTIVE_ANY", "1");+#else+ setenv("STRATA_TOPK_ACTIVE_ANY", "1", 1);+#endif+ const Case cases[] = {+ {1111, 256, 0}, {8192, 256, 0}, {32768, 256, 0}, {131072, 256, 0},+ {131075, 255, 0}, {135164, 256, 0}, {135168, 256, 0}, {250022, 256, 0},+ {262144, 256, 0}, {131072, 1, 0}, {131072, 8, 0}, {131072, 257, 0},+ {131072, 256, 1}, {131072, 256, 2}, {131072, 256, 3}, {131072, 256, 4},+ // either side of the Turing wide-kernel bound (22,528 blocks), and ties above the register limit+ {90108, 256, 0}, {90112, 256, 0}, {200000, 256, 2}, {262144, 256, 1},+ };+ for (const auto c : cases) if (!check(c)) return 1;+ std::puts("PASS: 20 top-k active-bound cases, selected IDs bitwise identical");+ return 0;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}diff --git a/sycl/src/kernels/qsa_topk_parity.cpp b/sycl/src/kernels/qsa_topk_parity.cppnew file mode 100644index 000000000..ba7c90a5a--- /dev/null+++ b/sycl/src/kernels/qsa_topk_parity.cpp@@ -0,0 +1,218 @@+// src/kernels/qsa_topk_parity.cpp - the QSA top-k the engine dispatches (qsa_block_topk) against the original kernel+// (qsa_block_topk_ref): the selected cells must be identical (GPU, synthetic, no model).+//+// A case is a context under a capacity (the engine's --max-context; max_blocks = capacity / 4 + 2, and without an+// active-block count the dispatch follows it), with consecutive queries at the context's end so that the tail block+// holds 0 to 3 cells. Three score sets per case: continuous, 64 levels (many ties at the threshold) and all equal+// (the rule's ties go to the lowest index). The dispatch is called as a decode window calls it (no block count) and as+// the prompt path does (with the call's largest block count). The reference and the dispatched kernel are also timed.+//+// Usage: qsa_topk_parity --selftest+// qsa_topk_parity CONTEXT [QUERIES=256] [REPS=10] [CAPACITY=CONTEXT] [COUNT=1] (COUNT=0: no block count)+#define DPCT_PROFILING_ENABLED+#include <sycl/sycl.hpp>+#include <dpct/dpct.hpp>+#include "strata/kernels/qsa.hpp"+#include "strata/kernels/qsa_select.hpp"++#include <algorithm>+#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <random>+#include <vector>++namespace k = strata::kernels;++namespace {+void ck(dpct::err0 e, const char *w) {+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+}++bool run_case(int64_t ctx, int64_t nq, int reps, int64_t capacity, bool counted) {+ const k::QsaShapes s = k::qsa_real_shapes();+ const int64_t max_blocks = capacity / s.idx_block + 2, cap = k::qsa_selection_width(k::kTopkMaxCells, s);+ std::vector<int32_t> steps((size_t) (nq * k::kStepCount));+ for (int64_t i = 0; i < nq; ++i) {+ int32_t* st = steps.data() + i * k::kStepCount;+ const int64_t pos = ctx - nq + i;+ st[k::kStepPos] = (int32_t) pos;+ st[k::kStepNKv] = (int32_t) (pos + 1);+ st[k::kStepNBid] = (int32_t) ((pos + 1) / s.idx_block);+ st[k::kStepWidth] = (int32_t) k::qsa_selection_width(pos + 1, s);+ }+ std::mt19937 rng((uint32_t) (ctx * 31 + capacity));+ std::normal_distribution<float> nd(0.f, 1.f);+ std::vector<float> scores((size_t) (nq * max_blocks)), tied(scores.size()), equal(scores.size(), 0.25f);+ for (int64_t i = 0; i < nq; ++i) {+ const int32_t* st = steps.data() + i * k::kStepCount;+ float* row = scores.data() + i * max_blocks;+ for (int64_t b = 0; b < max_blocks; ++b) row[b] = nd(rng);+ // the tail block as the scorers leave it: far above the others when it holds cells+ if (st[k::kStepNKv] % s.idx_block != 0) row[st[k::kStepNBid]] += 1e9f;+ for (int64_t b = 0; b < max_blocks; ++b)+ tied[(size_t) (i * max_blocks + b)] = row[b] > 1e8f ? row[b] : std::floor(row[b] * 8.0f) / 8.0f; // ~64 levels+ }+ int32_t *d_steps = nullptr, *ids_ref = nullptr, *ids_new = nullptr;+ float* d_scores = nullptr;+ ck(DPCT_CHECK_ERROR(d_steps = (int32_t *)sycl::malloc_device(+ steps.size() * 4, dpct::get_in_order_queue())),+ "malloc");+ ck(DPCT_CHECK_ERROR(d_scores = (float *)sycl::malloc_device(+ scores.size() * 4, dpct::get_in_order_queue())),+ "malloc");+ ck(DPCT_CHECK_ERROR(+ ids_ref = (int32_t *)sycl::malloc_device(+ (size_t)(nq * cap) * 4, dpct::get_in_order_queue())),+ "malloc");+ ck(DPCT_CHECK_ERROR(+ ids_new = (int32_t *)sycl::malloc_device(+ (size_t)(nq * cap) * 4, dpct::get_in_order_queue())),+ "malloc");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_steps, steps.data(),+ steps.size() * 4).wait()),+ "upload");+ const int64_t active = counted ? steps[(size_t) ((nq - 1) * k::kStepCount + k::kStepNBid)] + 1 : -1;+ std::vector<int32_t> a((size_t) (nq * cap)), b(a.size());+ auto same = [&](const std::vector<float> &sc) -> int64_t {+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable memory.+ If the memory is not pageable, call wait() on event return by memcpy API+ to ensure synchronization behavior.+ */+ try {+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_scores, sc.data(),+ sc.size() * 4).wait()),+ "upload");+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memset(ids_ref, 0xff, a.size() * 4)+ .wait()),+ "memset");+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memset(ids_new, 0xff, a.size() * 4)+ .wait()),+ "memset");+ k::qsa_block_topk_ref(d_scores, d_steps, nq, max_blocks, cap, s, ids_ref, nullptr);+ k::qsa_block_topk(d_scores, d_steps, nq, max_blocks, cap, s, ids_new, nullptr, active);+ ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),+ "sync");+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(a.data(), ids_ref, a.size() * 4)+ .wait()),+ "down");+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(b.data(), ids_new, b.size() * 4)+ .wait()),+ "down");+ int64_t n = 0;+ for (int64_t i = 0; i < nq; ++i) {+ const int64_t w = steps[(size_t) (i * k::kStepCount + k::kStepWidth)];+ n += std::equal(a.begin() + i * cap, a.begin() + i * cap + w, b.begin() + i * cap);+ }+ return n;+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ const int64_t same_tied = same(tied), same_equal = same(equal), same_cont = same(scores); // d_scores: continuous+ dpct::event_ptr e0, e1;+ ck(DPCT_CHECK_ERROR(e0 = new sycl::event()), "event");+ ck(DPCT_CHECK_ERROR(e1 = new sycl::event()), "event");+ auto timed = [&](auto f) {+ /*+ DPCT1024: The original code returned the error code that was+ further consumed by the program logic. This original code was replaced+ with 0. You may need to rewrite the program logic consuming the error+ code.+ */+ try {+ ck(DPCT_CHECK_ERROR(dpct::sync_barrier(e0)), "record");+ for (int r = 0; r < reps; ++r) f();+ /*+ DPCT1024: The original code returned the error code that was+ further consumed by the program logic. This original code was replaced+ with 0. You may need to rewrite the program logic consuming the error+ code.+ */+ ck(DPCT_CHECK_ERROR(dpct::sync_barrier(e1)), "record");+ ck(DPCT_CHECK_ERROR(e1->wait_and_throw()), "time");+ float ms = 0;+ ck(DPCT_CHECK_ERROR(+ ms = (e1->get_profiling_info<+ sycl::info::event_profiling::command_end>() -+ e0->get_profiling_info<+ sycl::info::event_profiling::command_start>()) /+ 1000000.0f),+ "elapsed");+ return ms / (float) reps;+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ const float t_ref = timed([&] { k::qsa_block_topk_ref(d_scores, d_steps, nq, max_blocks, cap, s, ids_ref, nullptr); });+ const float t_new = timed([&] { k::qsa_block_topk(d_scores, d_steps, nq, max_blocks, cap, s, ids_new, nullptr, active); });+ dpct::destroy_event(e0); dpct::destroy_event(e1);+ sycl::free(d_steps, dpct::get_in_order_queue());+ sycl::free(d_scores, dpct::get_in_order_queue());+ sycl::free(ids_ref, dpct::get_in_order_queue());+ sycl::free(ids_new, dpct::get_in_order_queue());+ const bool ok = same_cont == nq && same_tied == nq && same_equal == nq;+ std::printf("%s context %lld under a capacity of %lld (%lld blocks), %lld queries %s: reference %.3f ms, "+ "dispatched %.3f ms (%.1fx); identical ids: continuous %lld/%lld, 64 levels %lld/%lld, equal scores "+ "%lld/%lld\n", ok ? "PASS" : "FAIL", (long long) ctx, (long long) capacity, (long long) max_blocks,+ (long long) nq, counted ? "with their block count" : "without a block count", t_ref, t_new, t_ref / t_new,+ (long long) same_cont, (long long) nq, (long long) same_tied,+ (long long) nq, (long long) same_equal, (long long) nq);+ return ok;+}+} // namespace++int main(int argc, char** argv) {+ if (argc > 1 && std::strcmp(argv[1], "--selftest") == 0) {+ // {context, capacity}: both sides of the register kernel's reach (33,792 blocks = 135,168 cells), short+ // contexts under a long capacity (fewer blocks than the kernel's threads; a prompt batch below the dispatch's+ // 4,608 blocks), and the long contexts themselves+ const int64_t cases[][2] = {{9000, 9000}, {135160, 135160}, {135176, 135176}, {2100, 262144},+ {9000, 262144}, {32768, 262144}, {262144, 262144}, {300001, 524288},+ {524288, 524288}};+ bool ok = true;+ for (const auto& c : cases) {+ ok = run_case(c[0], 8, 3, c[1], false) && ok; // a decode window's call+ ok = run_case(c[0], 64, 3, c[1], true) && ok; // the prompt path's+ }+ std::printf("%s\n", ok ? "qsa_topk_parity: PASS" : "qsa_topk_parity: FAIL");+ return ok ? 0 : 1;+ }+ if (argc < 2) {+ std::fprintf(stderr, "usage: qsa_topk_parity --selftest | CONTEXT [QUERIES=256] [REPS=10] [CAPACITY=CONTEXT] "+ "[COUNT=1]\n");+ return 2;+ }+ const int64_t ctx = std::atoll(argv[1]);+ const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 256;+ const int reps = argc > 3 ? std::atoi(argv[3]) : 10;+ const int64_t capacity = argc > 4 ? std::atoll(argv[4]) : ctx;+ if (ctx < nq || nq <= 0 || reps <= 0 || capacity < ctx) {+ std::fprintf(stderr, "qsa_topk_parity: CONTEXT >= QUERIES > 0, REPS > 0, CAPACITY >= CONTEXT\n");+ return 2;+ }+ return run_case(ctx, nq, reps, capacity, argc <= 5 || std::atoi(argv[5]) != 0) ? 0 : 1;+}diff --git a/sycl/src/kernels/resident_plan_parity.cpp b/sycl/src/kernels/resident_plan_parity.cppnew file mode 100644index 000000000..fb958ccc1--- /dev/null+++ b/sycl/src/kernels/resident_plan_parity.cpp@@ -0,0 +1,227 @@+// src/kernels/resident_plan_parity.cpp - the verify window's device-built expert plan (#783 PR-e: the parallel+// grouping and the prefix scan that replaced thread 0's serial pass) against a host replay of its contract:+// distinct experts in routing order, each with its entries ascending, `ptr[g]` = the expert's slot, counts / start /+// dst / tok / start2 in the host pool's layout.+//+// n = 1..80 entries (a window of up to kVerifyMaxT tokens x 10 experts), ids drawn from pools of 3..512 experts so+// duplicates run from "every entry the same expert" to "all distinct", with and without a slot table (`slot_off`).+// Both modes are run: with a `skip` word (ring when the plan was built, 0 when an expert was not resident - and+// then the plan is untouched) and without one (the all-resident graph: a non-resident expert gives an empty plan and+// sets *plan_err).+// Every word of the plan the host pool would read is compared with memcmp. GPU, synthetic, no model.+#define DPCT_PROFILING_ENABLED+#include <sycl/sycl.hpp>+#include <dpct/dpct.hpp>+#include "strata/kernels/verify_kernels.hpp"++#include <cstdint>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <random>+#include <vector>++namespace k = strata::kernels;++namespace {+void ck(dpct::err0 e, const char *w) {+}+} // namespace++int main() {+ const int K = 10, NE = 512;+ const long long capx = (long long) k::kVerifyMaxT * K;+ const long long ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll;+ const size_t plan_words = (size_t) (ptr_off + 4 * capx + capx + 16);+ std::mt19937 rng(783);+ const long long blob = 1337;+ uint8_t* const cache_base = reinterpret_cast<uint8_t*>(uintptr_t(0x40000000)); // never dereferenced++ int32_t *d_ids, *d_res, *d_plan;+ unsigned long long* d_off;+ uint32_t* d_skip;+ ck(DPCT_CHECK_ERROR(d_ids = (int32_t *)sycl::malloc_device(+ 128 * 4, dpct::get_in_order_queue())),+ "ids");+ ck(DPCT_CHECK_ERROR(d_res = (int32_t *)sycl::malloc_device(+ NE * 4, dpct::get_in_order_queue())),+ "res");+ ck(DPCT_CHECK_ERROR(d_off = (unsigned long long *)sycl::malloc_device(+ 1024 * 8, dpct::get_in_order_queue())),+ "off");+ ck(DPCT_CHECK_ERROR(d_plan = (int32_t *)sycl::malloc_device(+ plan_words * 4, dpct::get_in_order_queue())),+ "plan");+ ck(DPCT_CHECK_ERROR(d_skip = (uint32_t *)sycl::malloc_device(+ 4, dpct::get_in_order_queue())),+ "skip");+ uint32_t* d_err = nullptr;+ ck(DPCT_CHECK_ERROR(d_err = (uint32_t *)sycl::malloc_device(+ 4, dpct::get_in_order_queue())),+ "err");++ std::vector<int32_t> res(NE);+ for (int e = 0; e < NE; ++e) res[e] = (e * 37 + 11) % 1000; // distinct slots, not the identity+ std::vector<unsigned long long> off(1024);+ for (int s = 0; s < 1024; ++s) off[s] = (unsigned long long) s * 4096 + (s % 7) * 64;+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_res, res.data(), NE * 4).wait()),+ "res");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming+ in the original code the source host memory is pageable memory. If the+ memory is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_off, off.data(), 1024 * 8).wait()),+ "off");++ int cases = 0, bad = 0;+ for (int n = 1; n <= 80; ++n) {+ for (int variant = 0; variant < 4; ++variant) {+ const int pool = variant == 0 ? 3 : (variant == 1 ? 12 : (variant == 2 ? 40 : 512));+ std::vector<int32_t> ids(n);+ for (int i = 0; i < n; ++i) ids[i] = (int32_t) ((rng() % pool) * (512 / pool));+ const bool use_off = (n + variant) % 2 == 1;+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable+ memory. If the memory is not pageable, call wait() on event return+ by memcpy API to ensure synchronization behavior.+ */+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_ids, ids.data(), n * 4).wait()),+ "ids");++ // host replay+ std::vector<int32_t> counts = {0, n, 0}, start, dst(n), tok(n);+ std::vector<unsigned long long> ptr;+ std::vector<int> first_seen; // group -> expert+ for (int i = 0; i < n; ++i) {+ int g = -1;+ for (size_t q = 0; q < first_seen.size(); ++q)+ if (first_seen[q] == ids[i]) g = (int) q;+ if (g < 0) { first_seen.push_back(ids[i]); g = (int) first_seen.size() - 1; }+ }+ const int groups = (int) first_seen.size();+ counts[0] = groups;+ start.assign(groups + 1, 0);+ int pos = 0;+ for (int g = 0; g < groups; ++g) {+ start[g] = pos;+ ptr.push_back((unsigned long long) (uintptr_t) cache_base ++ (use_off ? off[res[first_seen[g]]] : (unsigned long long) res[first_seen[g]] * (unsigned long long) blob));+ for (int i = 0; i < n; ++i)+ if (ids[i] == first_seen[g]) { dst[pos] = i; tok[pos] = i / K; ++pos; }+ }+ start[groups] = n;++ for (int mode = 0; mode < 2; ++mode) { // 0: general kernel with a skip word, 1: all resident+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memset(d_plan, 0xAB, plan_words * 4)+ .wait()),+ "fill");+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memset(d_skip, 0, 4).wait()),+ "skip0");+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memset(d_err, 0, 4).wait()),+ "err0");+ k::resident_plan(d_ids, n, K, d_res, NE, cache_base, use_off ? d_off : nullptr, blob, d_plan, capx,+ mode == 0 ? d_skip : nullptr, 7u, nullptr, d_err);+ ck(DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()),+ "sync");+ std::vector<int32_t> plan(plan_words);+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(plan.data(), d_plan, plan_words * 4)+ .wait()),+ "plan");+ uint32_t skip = 0;+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(&skip, d_skip, 4)+ .wait()),+ "skipr");+ bool ok = mode == 1 || skip == 7u;+ ok = ok && std::memcmp(plan.data(), counts.data(), 3 * 4) == 0;+ ok = ok && std::memcmp(plan.data() + 4, start.data(), (size_t) (groups + 1) * 4) == 0;+ const int32_t* pdst = plan.data() + 4 + capx + 1;+ ok = ok && std::memcmp(pdst, dst.data(), (size_t) n * 4) == 0;+ ok = ok && std::memcmp(pdst + capx, tok.data(), (size_t) n * 4) == 0;+ ok = ok && std::memcmp(plan.data() + ptr_off, ptr.data(), (size_t) groups * 8) == 0;+ ok = ok && plan[(size_t) (ptr_off + 4 * capx)] == n;+ ++cases;+ if (!ok) {+ std::printf(" *** n=%d pool=%d %s %s: the plan differs from the host replay ***\n", n, pool,+ use_off ? "slot_off" : "blob", mode ? "all_resident" : "general");+ ++bad;+ }+ }+ }+ }++ // a routed expert that is not resident: the general kernel leaves the plan alone and zeroes *skip+ {+ std::vector<int32_t> res2 = res;+ res2[5] = -1;+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable memory.+ If the memory is not pageable, call wait() on event return by memcpy API+ to ensure synchronization behavior.+ */+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_res, res2.data(), NE * 4).wait()),+ "res2");+ const int32_t ids[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable memory.+ If the memory is not pageable, call wait() on event return by memcpy API+ to ensure synchronization behavior.+ */+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_ids, ids, sizeof ids).wait()),+ "ids");+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memset(d_plan, 0xAB, plan_words * 4)+ .wait()),+ "fill");+ const uint32_t seven = 7;+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_skip, &seven, 4).wait()),+ "skip7");+ k::resident_plan(d_ids, 10, K, d_res, NE, cache_base, nullptr, blob, d_plan, capx, d_skip, 7u, nullptr, d_err);+ ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),+ "sync");+ std::vector<int32_t> plan(plan_words);+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(plan.data(), d_plan, plan_words * 4)+ .wait()),+ "plan");+ uint32_t skip = 99;+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(&skip, d_skip, 4).wait()),+ "skipr");+ bool untouched = true;+ for (int32_t w : plan) untouched = untouched && (uint32_t) w == 0xABABABABu;+ ++cases;+ if (skip != 0 || !untouched) {+ std::printf(" *** a non-resident expert: skip=%u untouched=%d (want 0 / 1) ***\n", skip, (int) untouched);+ ++bad;+ }+ }++ std::printf("resident_plan: %d cases, %d failures\n", cases, bad);+ if (bad) return 1;+ std::printf("resident_plan_parity OK\n");+ return 0;+}diff --git a/sycl/src/kernels/rope_parity.cpp b/sycl/src/kernels/rope_parity.cppindex 75fb1dc1c..cf11ccb1f 100644--- a/sycl/src/kernels/rope_parity.cpp+++ b/sycl/src/kernels/rope_parity.cpp@@ -28,6 +28,7 @@#include <sycl/sycl.hpp>#include <dpct/dpct.hpp>#include "strata/kernels/rope.hpp"+#include "strata/kernels/native_qsa.hpp"#include "strata/kernels/native_rope.hpp"#include <cmath>@@ -605,6 +606,160 @@ int main(int argc, char** argv) {std::printf(" native path vs table path, none %s (%lld of %d over 3e-3, worst rel %.3e)\n",none_bad5 ? "*** WRONG ***" : "agrees", none_bad5, nrows * head_dim, worst5);bad += (int) none_bad5;++ // ---- 6. FUSED RMSNorm + RoPE (`native_qsa_rms_norm_rope`) MUST BE BIT-IDENTICAL to+ // `native_qsa_rms_norm_weighted` followed by `native_rope_apply` for both contiguous+ // (`in_stride == head_dim`) and strided Q/gate split (`in_stride == 2 * head_dim`) inputs,+ // across supported head_dims (128, 256) and both unscaled and YaRN scaling.+ // The kernel is off by default on the HIP build until this check passes there (native_norm_rope_usable): the+ // check then reports SKIPPED, and STRATA_NORM_ROPE=1 runs it (gfx1151, Aurora, 0.1.40: it does not pass).+ const bool run6 = strata::kernels::native_norm_rope_usable(256, 64);+ if (!run6)+ std::printf(" native_qsa_rms_norm_rope SKIPPED (the fused kernel is not enabled on this build)\n");+ for (int hd6 : {128, 256}) {+ if (!run6) break;+ const int nr6 = 64;+ const int rows6 = 96;+ std::vector<float> x6_strided((size_t) rows6 * 2 * hd6);+ std::vector<float> gamma6((size_t) hd6);+ std::vector<int> pos6((size_t) rows6);+ for (auto& v : x6_strided) v = gauss2(rng2);+ for (auto& g : gamma6) g = 0.5f + std::fabs(gauss2(rng2));+ for (int r = 0; r < rows6; ++r) pos6[(size_t) r] = (r * 53 + 1) % npos;++ float *d_xs6 = nullptr, *d_g6 = nullptr, *d_ref6 = nullptr, *d_fus6 = nullptr;+ int* d_pos6 = nullptr;+ check(DPCT_CHECK_ERROR(+ d_xs6 = sycl::malloc_device<float>(+ x6_strided.size(), dpct::get_in_order_queue())),+ "malloc xs6");+ check(DPCT_CHECK_ERROR(+ d_g6 = sycl::malloc_device<float>(+ gamma6.size(), dpct::get_in_order_queue())),+ "malloc g6");+ check(DPCT_CHECK_ERROR(+ d_ref6 = sycl::malloc_device<float>(+ (size_t)rows6 * hd6, dpct::get_in_order_queue())),+ "malloc ref6");+ check(DPCT_CHECK_ERROR(+ d_fus6 = sycl::malloc_device<float>(+ (size_t)rows6 * hd6, dpct::get_in_order_queue())),+ "malloc fus6");+ check(+ DPCT_CHECK_ERROR(d_pos6 = sycl::malloc_device<int>(+ pos6.size(), dpct::get_in_order_queue())),+ "malloc pos6");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable+ memory. If the memory is not pageable, call wait() on event return+ by memcpy API to ensure synchronization behavior.+ */+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ d_xs6, x6_strided.data(),+ x6_strided.size() * sizeof(float)).wait()),+ "copy xs6");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable+ memory. If the memory is not pageable, call wait() on event return+ by memcpy API to ensure synchronization behavior.+ */+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ d_g6, gamma6.data(), gamma6.size() * sizeof(float)).wait()),+ "copy g6");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable+ memory. If the memory is not pageable, call wait() on event return+ by memcpy API to ensure synchronization behavior.+ */+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ d_pos6, pos6.data(), pos6.size() * sizeof(int)).wait()),+ "copy pos6");++ long long fbad = 0;+ for (const auto& sc6 : {none5, yarn}) {+ // (a) strided Q/gate split (in_stride = 2 * hd6) vs cudaMemcpy2DAsync + norm + rope+ /*+ DPCT1124: cudaMemcpy2DAsync is migrated to asynchronous+ memcpy API. While the origin API might be synchronous, it+ depends on the type of operand memory, so you may need to call+ wait() on event return by memcpy API to ensure synchronization+ behavior.+ */+ check(DPCT_CHECK_ERROR(dpct::async_dpct_memcpy(+ d_ref6, (size_t)hd6 * sizeof(float), d_xs6,+ (size_t)2 * hd6 * sizeof(float),+ (size_t)hd6 * sizeof(float), (size_t)rows6,+ dpct::device_to_device, *cs5)),+ "split6");+ strata::kernels::native_qsa_rms_norm_weighted(d_ref6, d_g6, d_ref6, hd6, rows6, 1e-6f, cs5);+ strata::kernels::native_rope_apply(d_ref6, d_ref6, rows6, hd6, nr6, sc6, d_pos6, cs5);++ strata::kernels::native_qsa_rms_norm_rope(d_xs6, 2 * hd6, d_g6, d_fus6, rows6, hd6, nr6, 1e-6f, sc6,+ d_pos6, cs5);+ check(DPCT_CHECK_ERROR(cs5->wait()), "sync6a");+ std::vector<float> href((size_t) rows6 * hd6), hfus((size_t) rows6 * hd6);+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(href.data(), d_ref6,+ href.size() * sizeof(float))+ .wait()),+ "back ref6a");+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(hfus.data(), d_fus6,+ hfus.size() * sizeof(float))+ .wait()),+ "back fus6a");+ for (size_t i = 0; i < href.size(); ++i) {+ if (std::memcmp(&href[i], &hfus[i], 4) != 0) ++fbad;+ }++ // (b) contiguous in-place (in_stride = hd6, output == input)+ /*+ DPCT1124: cudaMemcpy2DAsync is migrated to asynchronous+ memcpy API. While the origin API might be synchronous, it+ depends on the type of operand memory, so you may need to call+ wait() on event return by memcpy API to ensure synchronization+ behavior.+ */+ check(DPCT_CHECK_ERROR(dpct::async_dpct_memcpy(+ d_ref6, (size_t)hd6 * sizeof(float), d_xs6,+ (size_t)2 * hd6 * sizeof(float),+ (size_t)hd6 * sizeof(float), (size_t)rows6,+ dpct::device_to_device, *cs5)),+ "contig6_ref");+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ d_fus6, d_ref6, (size_t)rows6 * hd6 * sizeof(float)).wait()),+ "contig6_fus");+ strata::kernels::native_qsa_rms_norm_weighted(d_ref6, d_g6, d_ref6, hd6, rows6, 1e-6f, cs5);+ strata::kernels::native_rope_apply(d_ref6, d_ref6, rows6, hd6, nr6, sc6, d_pos6, cs5);+ strata::kernels::native_qsa_rms_norm_rope(d_fus6, hd6, d_g6, d_fus6, rows6, hd6, nr6, 1e-6f, sc6,+ d_pos6, cs5);+ check(DPCT_CHECK_ERROR(cs5->wait()), "sync6b");+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(href.data(), d_ref6,+ href.size() * sizeof(float))+ .wait()),+ "back ref6b");+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(hfus.data(), d_fus6,+ hfus.size() * sizeof(float))+ .wait()),+ "back fus6b");+ for (size_t i = 0; i < href.size(); ++i) {+ if (std::memcmp(&href[i], &hfus[i], 4) != 0) ++fbad;+ }+ }+ std::printf(" native_qsa_rms_norm_rope hd=%3d nr=%2d %s (%lld of %d elements differ)\n",+ hd6, nr6, fbad ? "*** WRONG ***" : "bit-identical", fbad, rows6 * hd6 * 4);+ bad += (int) fbad;+ sycl::free(d_xs6, dpct::get_in_order_queue());+ sycl::free(d_g6, dpct::get_in_order_queue());+ sycl::free(d_ref6, dpct::get_in_order_queue());+ sycl::free(d_fus6, dpct::get_in_order_queue());+ sycl::free(d_pos6, dpct::get_in_order_queue());+ }}std::printf("\nrope: %d failures\n", bad);diff --git a/sycl/src/kernels/route_window_parity.cpp b/sycl/src/kernels/route_window_parity.cppnew file mode 100644index 000000000..0eec8f55d--- /dev/null+++ b/sycl/src/kernels/route_window_parity.cpp@@ -0,0 +1,151 @@+// route_window_parity - the verify window's batched routing against the per-token calls, bit for bit.+//+// `moe_route_window` replaces n per-token (projection + top-k) pairs by one multi-column BF16 projection and one+// n-token top-k. Speculative decoding is exact only if a token's route does not depend on how many tokens share+// its window, so both batched kernels must equal their one-token forms exactly - this checks that on random data+// shaped like the router (2560 -> 256, top-10) and like the shared-expert gate (2560 -> 1).+#define DPCT_PROFILING_ENABLED+#include <sycl/sycl.hpp>+#include <dpct/dpct.hpp>+#include "strata/kernels/bf16_gemv.hpp"+#include "strata/kernels/router_top10.hpp"++#include <cstdint>+#include <cstdio>+#include <cstring>+#include <random>+#include <vector>++namespace {+void ck(dpct::err0 e, const char *what) {+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */+}+uint16_t bf16(float f) { uint32_t i; std::memcpy(&i, &f, 4); return (uint16_t) ((i + ((i >> 16) & 1u) + 0x7FFFu) >> 16); }+} // namespace++int main() {+ const int N = 2560, E = 256, K = 10;+ int bad = 0;+ std::mt19937 rng(7);+ std::normal_distribution<float> nd(0.0f, 1.0f);+ for (int n_out : {E, 1}) {+ for (int T : {2, 3, 4, 6}) {+ std::vector<uint16_t> w((size_t) n_out * N);+ std::vector<float> x((size_t) T * N);+ for (auto& v : w) v = bf16(nd(rng) * 0.05f);+ for (auto& v : x) v = nd(rng);+ uint16_t* dw; float *dx, *dy1, *dyn;+ ck(DPCT_CHECK_ERROR(dw = (uint16_t *)sycl::malloc_device(+ w.size() * 2, dpct::get_in_order_queue())),+ "w");+ ck(DPCT_CHECK_ERROR(+ dx = (float *)sycl::malloc_device(+ x.size() * 4, dpct::get_in_order_queue())),+ "x");+ ck(DPCT_CHECK_ERROR(+ dy1 = (float *)sycl::malloc_device(+ (size_t)T * n_out * 4, dpct::get_in_order_queue())),+ "y1");+ ck(DPCT_CHECK_ERROR(+ dyn = (float *)sycl::malloc_device(+ (size_t)T * n_out * 4, dpct::get_in_order_queue())),+ "yn");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable+ memory. If the memory is not pageable, call wait() on event return+ by memcpy API to ensure synchronization behavior.+ */+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ dw, w.data(), w.size() * 2).wait()),+ "up w");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable+ memory. If the memory is not pageable, call wait() on event return+ by memcpy API to ensure synchronization behavior.+ */+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ dx, x.data(), x.size() * 4).wait()),+ "up x");+ for (int t = 0; t < T; ++t)+ strata::kernels::bf16_gemv_fp32_mmvf(dx + (size_t) t * N, dw, dy1 + (size_t) t * n_out, N, n_out, nullptr);+ strata::kernels::bf16_gemv_fp32_mmvf_cols(dx, dw, dyn, N, n_out, T, nullptr);+ ck(DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()),+ "sync");+ std::vector<float> y1((size_t) T * n_out), yn((size_t) T * n_out);+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(y1.data(), dy1, y1.size() * 4)+ .wait()),+ "down 1");+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(yn.data(), dyn, yn.size() * 4)+ .wait()),+ "down n");+ const bool same = std::memcmp(y1.data(), yn.data(), y1.size() * 4) == 0;+ std::printf(" mmvf cols n_out %3d T %d %s\n", n_out, T, same ? "bit-identical" : "*** DIFFERS ***");+ if (!same) ++bad;+ if (n_out == E) {+ int *i1, *in_; float *w1, *wn;+ ck(DPCT_CHECK_ERROR(+ i1 = (int *)sycl::malloc_device(+ (size_t)T * K * 4, dpct::get_in_order_queue())),+ "i1");+ ck(DPCT_CHECK_ERROR(+ in_ = (int *)sycl::malloc_device(+ (size_t)T * K * 4, dpct::get_in_order_queue())),+ "in");+ ck(DPCT_CHECK_ERROR(+ w1 = (float *)sycl::malloc_device(+ (size_t)T * K * 4, dpct::get_in_order_queue())),+ "w1");+ ck(DPCT_CHECK_ERROR(+ wn = (float *)sycl::malloc_device(+ (size_t)T * K * 4, dpct::get_in_order_queue())),+ "wn");+ for (int t = 0; t < T; ++t)+ strata::kernels::router_top10(dy1 + (size_t) t * E, 1, E, K, i1 + t * K, w1 + t * K, nullptr);+ strata::kernels::router_top10(dy1, T, E, K, in_, wn, nullptr);+ ck(DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()),+ "sync top");+ std::vector<int> a((size_t) T * K), b((size_t) T * K);+ std::vector<float> fa((size_t) T * K), fb((size_t) T * K);+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(a.data(), i1, a.size() * 4)+ .wait()),+ "ids1");+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(b.data(), in_, b.size() * 4)+ .wait()),+ "idsn");+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(fa.data(), w1, fa.size() * 4)+ .wait()),+ "w1");+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(fb.data(), wn, fb.size() * 4)+ .wait()),+ "wn");+ const bool s2 = a == b && std::memcmp(fa.data(), fb.data(), fa.size() * 4) == 0;+ std::printf(" top10 n T %d %s\n", T, s2 ? "bit-identical" : "*** DIFFERS ***");+ if (!s2) ++bad;+ sycl::free(i1, dpct::get_in_order_queue());+ sycl::free(in_, dpct::get_in_order_queue());+ sycl::free(w1, dpct::get_in_order_queue());+ sycl::free(wn, dpct::get_in_order_queue());+ }+ sycl::free(dw, dpct::get_in_order_queue());+ sycl::free(dx, dpct::get_in_order_queue());+ sycl::free(dy1, dpct::get_in_order_queue());+ sycl::free(dyn, dpct::get_in_order_queue());+ }+ }+ std::printf(bad ? "route_window_parity: %d FAILURES\n" : "route_window_parity OK\n", bad);+ return bad ? 1 : 0;+}diff --git a/sycl/src/kernels/verify_parity.cpp b/sycl/src/kernels/verify_parity.cppnew file mode 100644index 000000000..9963ed512--- /dev/null+++ b/sycl/src/kernels/verify_parity.cpp@@ -0,0 +1,148 @@+// src/kernels/verify_parity.cpp - batched / split verify-window kernels against the kernels they replace, BITWISE.+//+// A verify window's token t must come out bit for bit as it would in a window of any other size (the drafts are+// accepted exactly when greedy decode would have produced them), so every kernel here is checked against the+// one it stands in for, on random inputs that include -0.0, denormals, NaN, -inf and large values. The tests+// follow eddoursul's fork (MIT; verify_parity.cpp), ported to this tree's kernels.+#define DPCT_PROFILING_ENABLED+#include <sycl/sycl.hpp>+#include <dpct/dpct.hpp>+#include "strata/kernels/sampler.hpp"+#include "strata/kernels/verify_kernels.hpp"++#include <algorithm>+#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <random>+#include <string>+#include <vector>++#include <cstdlib>+#include <cstring>+#include <random>+#include <string>+#include <vector>++namespace {++void check(dpct::err0 e, const char *what) {+}++template <typename T> T* dev(size_t n) {+ T* p = nullptr;+ check(DPCT_CHECK_ERROR(p = (T *)sycl::malloc_device(+ n * sizeof(T), dpct::get_in_order_queue())),+ "cudaMalloc");+ return p;+}+template <typename T> void up(T* d, const std::vector<T>& h) {+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in+ the original code the source host memory is pageable memory. If the memory+ is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ d, h.data(), h.size() * sizeof(T)).wait()),+ "upload");+}+template <typename T> std::vector<T> down(const T* d, size_t n) {+ std::vector<T> h(n);+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(h.data(), d, n * sizeof(T))+ .wait()),+ "download");+ return h;+}++// argmax_rows against sample_tokens' greedy pick and row_top_prob_split against row_top_prob, bitwise: rows of both+// vocabularies with ties at the maximum (the lowest index wins), NaN, -inf, a row with no value above -inf, and+// launches repeated on one scratch (each must leave its counters at zero)+int test_argmax(std::mt19937 &rng, dpct::queue_ptr s) {+ using namespace strata::kernels;+ int bad = 0;+ std::normal_distribution<float> nd(0.0f, 4.0f);+ uint8_t* sa = dev<uint8_t>(argmax_rows_scratch_bytes(8)); // one scratch for every row count, as in the engine+ uint8_t* st = dev<uint8_t>(row_top_prob_scratch_bytes(8));+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memset(sa, 0, argmax_rows_scratch_bytes(8))+ .wait()),+ "memset");+ check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memset(st, 0, row_top_prob_scratch_bytes(8))+ .wait()),+ "memset");+ for (const int n : {248320, 40525, 4097, 33}) {+ for (const int rows : {4, 8, 1, 3, 8, 2}) {+ std::vector<float> h((size_t) rows * n);+ for (float& v : h) v = nd(rng);+ for (int r = 0; r < rows; ++r) {+ float* row = h.data() + (size_t) r * n;+ const int a = (int) (rng() % n), b = (int) (rng() % n);+ row[a] = row[b] = 40.0f; // a tie at the maximum+ row[(int) (rng() % n)] = std::nanf(""); // never picked+ row[(int) (rng() % n)] = -INFINITY;+ if (r == 2) // no value above -inf: 0+ for (int i = 0; i < n; ++i) row[i] = i % 7 ? -INFINITY : std::nanf("");+ }+ float* d_l = dev<float>(h.size());+ up(d_l, h);+ int* d_ref = dev<int>(rows);+ int32_t* d_out = dev<int32_t>(rows);+ float* d_p1 = dev<float>(rows);+ float* d_p2 = dev<float>(rows);+ SamplerParams sp;+ sp.greedy = true;+ sp.temperature = 0.0f;+ sample_tokens(d_l, rows, n, nullptr, 0, sp, d_ref, s);+ row_top_prob(d_l, rows, n, d_ref, d_p1, s);+ for (int rep = 0; rep < 3; ++rep) {+ argmax_rows(d_l, rows, n, sa, d_out, s);+ row_top_prob_split(d_l, rows, n, d_out, d_p2, st, s);+ check(DPCT_CHECK_ERROR(s->wait()), "argmax");+ const std::vector<int> ref = down(d_ref, rows);+ const std::vector<int32_t> out = down(d_out, rows);+ const std::vector<float> p1 = down(d_p1, rows), p2 = down(d_p2, rows);+ for (int r = 0; r < rows; ++r)+ if (ref[r] != out[r] || std::memcmp(&p1[r], &p2[r], 4) != 0) {+ if (bad < 5)+ std::printf(" argmax n %d rows %d row %d: %d / %d, p %.9g / %.9g\n", n, rows, r, ref[r],+ out[r], p1[r], p2[r]);+ ++bad;+ }+ }+ sycl::free(d_l, dpct::get_in_order_queue());+ sycl::free(d_ref, dpct::get_in_order_queue());+ sycl::free(d_out, dpct::get_in_order_queue());+ sycl::free(d_p1, dpct::get_in_order_queue());+ sycl::free(d_p2, dpct::get_in_order_queue());+ }+ }+ sycl::free(sa, dpct::get_in_order_queue());+ sycl::free(st, dpct::get_in_order_queue());+ std::printf("argmax_rows, row_top_prob_split: %s\n",+ bad ? "MISMATCH" : "bitwise equal to the one-block kernels (ties, NaN, -inf, 1-8 rows on one scratch)");+ return bad;+}++} // namespace++int main(int argc, char** argv) {+ for (int i = 1; i < argc; ++i) {+ if (std::string(argv[i]) != "--selftest") {+ std::fprintf(stderr, "usage: verify_parity [--selftest]\n");+ return 2;+ }+ }+ std::mt19937 rng(20260925);+ dpct::queue_ptr s = &dpct::get_in_order_queue();+ check(DPCT_CHECK_ERROR(s = dpct::get_current_device().create_queue(true)),+ "stream");+ int bad = 0;+ bad += test_argmax(rng, s);+ dpct::get_current_device().destroy_queue(s);+ std::printf("verify_parity: %s\n", bad ? "FAIL" : "PASS");+ return bad ? 1 : 0;+}diff --git a/sycl/src/prefill/gemm.dp.cpp b/sycl/src/prefill/gemm.dp.cppindex c4069b684..110a5f90d 100644--- a/sycl/src/prefill/gemm.dp.cpp+++ b/sycl/src/prefill/gemm.dp.cpp@@ -7,6 +7,17 @@#include "strata/kernels/dequant_bf16.hpp"#include <dpct/blas_utils.hpp>+#if defined(STRATA_PREFILL_MMQ) && defined(__HIPCC__)+#include "strata/prefill/moe_mmq.hpp"+#endif++#ifdef STRATA_USE_HIP+#include "wmma_gemm.h"+#endif++#include <algorithm>+#include <atomic>+#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)// The HIP compatibility shim maps CUDA shuffle spellings to Strata helpers.// hipBLASLt's public headers declare native HIP shuffle functions, so keep@@ -18,11 +29,14 @@#undef __ballot_sync#endif+#include <algorithm>#include <climits>#include <cstdio>#include <cstdlib>#include <cstring>#include <memory>+#include <cmath>+#include <dpct/lib_common_utils.hpp>#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)@@ -35,8 +49,39 @@#include <tuple>#endif+#if defined(__HIPCC__)+#include <hip/hip_fp16.h>+#endif+namespace strata::prefill {namespace {+#if defined(__HIPCC__)+// Y's rows, written by an FP16-out GEMM as FP16 at the start of each FP32 row (ldc = 2 ldy halves), widened in place.+// Float c overwrites halves 2c and 2c+1, so a row is walked from its end in blocks: a block's halves are read into+// registers, the block syncs, then writes its floats - which only cover halves of blocks already read.+// STRATA_DBG_NAN: the FP16 outputs that are not finite (an FP32-accumulated sum past 65504 becomes inf in FP16).+__device__ unsigned long long g_f16_nonfinite = 0;+__global__ void widen_rows_f16(float* __restrict__ Y, int64_t n, int64_t ldy, int count_nonfinite) {+ float* y = Y + (int64_t) blockIdx.x * ldy;+ const __half* h = reinterpret_cast<const __half*>(y);+ const int64_t nb = (n + blockDim.x - 1) / blockDim.x;+ for (int64_t b = nb - 1; b >= 0; --b) {+ const int64_t c = b * blockDim.x + threadIdx.x;+ const float v = c < n ? __half2float(h[c]) : 0.0f;+ if (count_nonfinite && c < n && !isfinite(v)) atomicAdd(&g_f16_nonfinite, 1ull);+ __syncthreads();+ if (c < n) y[c] = v;+ __syncthreads();+ }+}+// BF16 weight rows -> FP16, saturated (bench/results/2026-10-04-rdna2-fp16-prompt: none leaves FP16's range)+__global__ void bf16_to_f16_rows(const uint16_t* __restrict__ s, __half* __restrict__ d, int64_t n) {+ for (int64_t i = blockIdx.x * (int64_t) blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) {+ const float f = __uint_as_float((uint32_t) s[i] << 16);+ d[i] = __float2half(isnan(f) ? f : fminf(fmaxf(f, -65504.0f), 65504.0f)); // as hf_sat: a NaN stays NaN+ }+}+#endifvoid ck(int s, const char *what) {if (s != 0) {@@ -128,7 +173,7 @@ struct HipLtDescriptors {if (c) hipblasLtMatrixLayoutDestroy(c);}- bool init(hipDataType type, int t, int n, int k, int ldy) {+ bool init(hipDataType type, int t, int n, int k, int ldy, int ldb = 0) {const hipblasOperation_t trans_a = HIPBLAS_OP_T;const hipblasOperation_t trans_b = HIPBLAS_OP_N;if (hipblasLtMatmulDescCreate(&op, HIPBLAS_COMPUTE_32F, HIP_R_32F) != HIPBLAS_STATUS_SUCCESS ||@@ -137,7 +182,7 @@ struct HipLtDescriptors {hipblasLtMatmulDescSetAttribute(op, HIPBLASLT_MATMUL_DESC_TRANSB, &trans_b, sizeof(trans_b)) !=HIPBLAS_STATUS_SUCCESS ||hipblasLtMatrixLayoutCreate(&a, type, k, n, k) != HIPBLAS_STATUS_SUCCESS ||- hipblasLtMatrixLayoutCreate(&b, type, k, t, k) != HIPBLAS_STATUS_SUCCESS ||+ hipblasLtMatrixLayoutCreate(&b, type, k, t, ldb > k ? ldb : k) != HIPBLAS_STATUS_SUCCESS ||hipblasLtMatrixLayoutCreate(&c, HIP_R_32F, n, t, ldy) != HIPBLAS_STATUS_SUCCESS) {return false;}@@ -244,9 +289,20 @@ HipLtCachedAlgo resolve_hipblaslt_algo(HipLtState& state, strata::prefill::hipblreturn state.cache.emplace(key, resolved).first->second;}+// the hipBLASLt solution index the tuning table gives this call (-1: none / unsupported)+int hipblaslt_solution_for(void* opaque_state, strata::prefill::hipblaslt::InputType type, int64_t t, int64_t n, int64_t k,+ int64_t ldy, float beta) {+ auto* state = static_cast<HipLtState*>(opaque_state);+ if (!state || t <= 0 || n <= 0 || k <= 0 || t > INT_MAX || n > INT_MAX || k > INT_MAX || ldy > INT_MAX || ldy < n) return -1;+ const auto resolved = resolve_hipblaslt_algo(*state, type, (int) t, (int) n, (int) k, (int) ldy, beta);+ if (!resolved.supported || resolved.workspace_bytes > state->workspace_bytes) return -1;+ auto algo = resolved.algo;+ return hipblaslt_ext::getIndexFromAlgo(algo);+}+bool try_hipblaslt(void* opaque_state, strata::prefill::hipblaslt::InputType type, const uint16_t* x,const uint16_t* w, float* y, int64_t t, int64_t n, int64_t k, int64_t ldy, float beta,- void* stream) {+ void* stream, int64_t ldx = 0) {auto* state = static_cast<HipLtState*>(opaque_state);if (!state || t <= 0 || n <= 0 || k <= 0 || t > INT_MAX || n > INT_MAX || k > INT_MAX || ldy > INT_MAX ||ldy < n) {@@ -270,7 +326,7 @@ bool try_hipblaslt(void* opaque_state, strata::prefill::hipblaslt::InputType typHipLtDescriptors desc;const hipDataType input_type = type == strata::prefill::hipblaslt::InputType::bf16 ? HIP_R_16BF : HIP_R_16F;- if (!desc.init(input_type, (int) t, (int) n, (int) k, (int) ldy)) return false;+ if (!desc.init(input_type, (int) t, (int) n, (int) k, (int) ldy, (int) ldx)) return false;const float alpha = 1.0f;const hipblasStatus_t status = hipblasLtMatmul(state->handle, desc.op, &alpha, w, desc.a, x, desc.b, &beta, y,desc.c, y, desc.c, &resolved.algo, state->workspace,@@ -298,11 +354,44 @@ bool try_hipblaslt(void* opaque_state, strata::prefill::hipblaslt::InputType typ} // namespace+bool prompt_f16() {+#if defined(__HIPCC__)+ constexpr int kMaxDev = 64;+ static std::atomic<int8_t> cached[kMaxDev] = {}; // 0 unknown, 1 off, 2 on+ int dev = 0;+ if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= kMaxDev) { (void) hipGetLastError(); return false; }+ if (const int8_t c = cached[dev].load(std::memory_order_relaxed)) return c == 2;+ // Opt-in (#835): only STRATA_HIP_PROMPT_F16=1 turns it on. It changes the prompt path's numbers (an FP16 rounding of+ // each 16-bit GEMM's output), so no card gets it unasked. On gfx103x it is ~2x faster, so we say so once.+ const char* e = std::getenv("STRATA_HIP_PROMPT_F16");+ const bool on = e != nullptr && e[0] == '1';+ hipDeviceProp_t p{};+ if (hipGetDeviceProperties(&p, dev) != hipSuccess) { (void) hipGetLastError(); p.gcnArchName[0] = 0; }+ if (on) std::fprintf(stderr, "strata prefill: HIP device %d%s%s - STRATA_HIP_PROMPT_F16=1: the prompt's 16-bit GEMMs run FP16 in and out "+ "(rocBLAS is tuned only for that on gfx103x; not bit-identical to the default)%s",+ dev, p.gcnArchName[0] ? " " : "", p.gcnArchName, "\n");+ else if (e == nullptr && std::strncmp(p.gcnArchName, "gfx103", 6) == 0)+ std::fprintf(stderr, "strata prefill: HIP device %d %s - tip: STRATA_HIP_PROMPT_F16=1 reads long prompts about 2x faster here "+ "(FP16 prompt GEMMs, rocBLAS is tuned only for FP16 on gfx103x; the numbers differ slightly, see docs/AMD_HIP.md)%s",+ dev, p.gcnArchName, "\n");+ cached[dev].store(on ? 2 : 1, std::memory_order_relaxed);+ return on;+#else+ return false;+#endif+}+Gemm::~Gemm() {+#if defined(STRATA_PREFILL_MMQ) && defined(__HIPCC__)+ delete static_cast<strata::prefill::mmq::Context*>(mmq_ctx_);+ if (mmq_buf_) cudaFree(mmq_buf_);+#endif#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)delete static_cast<HipLtState*>(hipblaslt_state_);#endifif (handle_) delete ((dpct::blas::descriptor_ptr)handle_);+ if (tc_w_) sycl::free(tc_w_, dpct::get_in_order_queue());+ if (tc_x_) sycl::free(tc_x_, dpct::get_in_order_queue());if (!external_) {if (scratch_) sycl::free(scratch_, dpct::get_in_order_queue());if (workspace_) sycl::free(workspace_, dpct::get_in_order_queue());@@ -438,24 +527,243 @@ catch (sycl::exception const &exc) {std::exit(1);}+#if !defined(__HIPCC__)+// ---- below sm_80: BF16 GEMMs without BF16 tensor cores (PR #655, #540, #395) ----------------------------------------+// Turing and Volta have no BF16 tensor cores: cublasGemmEx on CUDA_R_16BF inputs falls back to a SIMT fp32 kernel+// (magma_sgemmEx), a fifth of a 4K prompt on an RTX 2080 Ti (#655) and ~10% of a V100's prompt (#540). BF16 -> FP16+// is exact for every value inside FP16's normal range (the 7-bit mantissa fits in 10 bits); weights and normalized+// activations sit there. With the FP16 path, the weight is converted once per call and the activations in row+// slices, into the instance's own buffers, and the product runs as the FP16 GEMM (fp32 accumulate) on the tensor+// cores. Finite values beyond FP16's range are clamped to +-65504 (#540) instead of becoming Inf. A beta = 1+// product (STRATA_PREFILL_BF16X2's remainder, ~2^-9 of the original, deep in FP16's subnormal band) keeps cuBLAS.+// Default: on for compute capability 7.0 - 7.4 (Volta: only the experimental STRATA_EXPERIMENTAL_SM60 build runs+// there), OFF for 7.5 (RTX 20 in the ready-made engine: the sums round differently, so it is opt-in until it has+// been gated). STRATA_BF16_TC=1 / =0 turns it on / off on any 7.x card (=2, a test mode: on any card).+// Pascal (6.x) has no tensor cores and cuBLAS has no BF16 GEMM for it (#395, measured NOT_SUPPORTED on a P40): both+// operands are widened to fp32 by an exact shift and the product is cublasSgemm with the same fp32 accumulator.+namespace {+__dpct_inline__ void bf16_to_f16_kernel(const uint16_t *__restrict__ in,+ sycl::half *__restrict__ out,+ int64_t n) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int64_t i =+ (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) ++ item_ct1.get_local_id(2);+ if (i < n) {+ float f = sycl::bit_cast<float>((uint32_t)in[i] << 16);+ if (f > 65504.0f && !sycl::isinf(f)) f = 65504.0f;+ else if (f < -65504.0f && !sycl::isinf(f)) f = -65504.0f;+ out[i] = sycl::vec<float, 1>(f)+ .convert<sycl::half, sycl::rounding_mode::rte>()[0];+ }+}+void bf16_to_f16(const uint16_t *in, uint16_t *out, int64_t n,+ dpct::queue_ptr st) {+ if (n <= 0) return;+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});++ st->parallel_for<dpct_kernel_name<class bf16_to_f16_kernel_a0031a>>(+ sycl::nd_range<3>(sycl::range(1, 1, (unsigned)((n + 255) / 256)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ bf16_to_f16_kernel(in, reinterpret_cast<sycl::half *>(out), n);+ });+ }+}+#if defined(STRATA_EXPERIMENTAL_SM60) // Pascal runs only the experimental build+__global__ void bf16_to_f32_kernel(const uint16_t* __restrict__ in, float* __restrict__ out, int64_t n) {+ const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;+ if (i < n) out[i] = __uint_as_float((uint32_t) in[i] << 16);+}+void bf16_to_f32(const uint16_t* in, float* out, int64_t n, cudaStream_t st) {+ if (n <= 0) return;+ bf16_to_f32_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, st>>>(in, out, n);+}+#endif+// The current device's compute capability as 10 * major + minor, per device (a layer split can mix cards); 0: not+// known, read as "not an old card" so a failed query keeps the cuBLAS BF16 call.+int current_cc() try {+ static std::atomic<int> cc[64] = {};+ int dev = 0;+ /*+ DPCT1026: The call to cudaGetLastError was removed because this+ functionality is redundant in SYCL.+ */+ if (DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()) != 0 || dev < 0 ||+ dev >= 64) {+ ; return 0;+ }+ int v = cc[dev].load(std::memory_order_relaxed);+ if (v == 0) {+ int major = 0, minor = 0;+ if (DPCT_CHECK_ERROR(+ major = dpct::get_device(dev).get_major_version()) != 0 ||+ DPCT_CHECK_ERROR(+ minor = dpct::get_device(dev).get_minor_version()) != 0) {+ /*+ DPCT1026: The call to cudaGetLastError was removed because this+ functionality is redundant in SYCL.+ */+ return 0;+ }+ v = 10 * major + minor;+ cc[dev].store(v, std::memory_order_relaxed);+ }+ return v;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}+// 0: cuBLAS's BF16 GEMM, 1: through FP16 (tensor cores), 2: through FP32 (Pascal)+int bf16_path() {+ static const int forced = [] {+ const char* v = std::getenv("STRATA_BF16_TC");+ return v != nullptr && v[0] != '\0' ? std::atoi(v) : -1;+ }();+ const int cc = current_cc();+ if (forced == 2 && cc > 0) return 1; // a test mode: the FP16 path on any card (gemm_bf16_parity on sm_80+)+ if (cc <= 0 || cc >= 80) return 0;+ if (cc < 70) return 2;+ if (forced >= 0) return forced != 0 ? 1 : 0;+ return cc < 75 ? 1 : 0;+}+bool grow(uint16_t *&p, int64_t &have,+ int64_t want) try { // `have`, `want`: 2-byte elements+ if (have >= want) return true;+ if (p) sycl::free(p, dpct::get_in_order_queue());+ p = nullptr;+ have = 0;+ /*+ DPCT1026: The call to cudaGetLastError was removed because this+ functionality is redundant in SYCL.+ */+ if (DPCT_CHECK_ERROR(p = (uint16_t *)sycl::malloc_device(+ (size_t)want * 2, dpct::get_in_order_queue())) !=+ 0) {+ ; p = nullptr; return false;+ }+ have = want;+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}+constexpr int64_t kXSliceElems = 16ll << 20; // 32 MiB of FP16 activations per slice (64 MiB as fp32)+} // namespace+#endif+bool Gemm::bf16_hcd_exact(const uint16_t* X, int64_t ldx, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K) {+#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)+ static std::atomic<bool> told{false};+ if (!hipblaslt_state_ || N != 320 || K != 10240 || T < 1) {+ if (N == 320 && K == 10240 && !told.exchange(true))+ std::fprintf(stderr, "strata: STRATA_HCD_EXACT: no hipBLASLt tuning table is loaded, so the exact kernel has nothing to match: "+ "the hyper-connection down projection stays on hipBLAS\n");+ return false;+ }+ // The kernel copies hipBLASLt solution 1176 / 1177's summation order, which is only true of the library build the+ // table was calibrated with: take it only when the table makes hipBLASLt pick one of those two for this T.+ const int id = hipblaslt_solution_for(hipblaslt_state_, strata::prefill::hipblaslt::InputType::bf16, T, N, K, N, 0.0f);+ if (id != 1176 && id != 1177) {+ if (T >= 4096 && !told.exchange(true)) // (a short chunk may legitimately get another solution: not worth a line)+ std::fprintf(stderr, "strata: STRATA_HCD_EXACT: the tuning table gives the hyper-connection down projection (N 320, K 10240) "+ "solution %d at T %lld, not 1176 / 1177: hipBLASLt runs it (a changed table or library; "+ "tools/hip/gfx1151-hipblaslt-100401.txt is the one measured)\n",+ id, (long long) T);+ return false;+ }+ return strata_pf_hcdown_exact_bf16(X, ldx, W, Y, T, N, K, stream_);+#else+ (void) X; (void) ldx; (void) W; (void) Y; (void) T; (void) N; (void) K;+ return false;+#endif+}+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) {+ float beta, int64_t ldx) {if (T <= 0 || N <= 0) return;if (ldy <= 0) ldy = N;+ if (ldx <= K) ldx = 0;+#ifdef STRATA_USE_HIP+ // #313 (opt-in STRATA_WMMA_GEMM=1; STRATA_WMMA_BF16=0 excludes bf16): RDNA3 / RDNA3.5 WMMA dense GEMM, before+ // hipBLASLt; it returns false for shapes it does not take (and off gfx11) and this falls through+ static const bool wmma_on = [] { const char* v = std::getenv("STRATA_WMMA_GEMM"); return v && v[0] != 0 && v[0] != '0'; }();+ static const bool bf16_on = [] { const char* v = std::getenv("STRATA_WMMA_BF16"); return !v || (v[0] != 0 && v[0] != '0'); }();+ if (wmma_on && bf16_on && ldx == 0 && T >= 16 && (beta == 0.0f || beta == 1.0f) &&+ strata_wmma_gemm_bf16(X, W, Y, T, N, K, ldy, beta, stream_)) {+ return;+ }+#endif+#if defined(__HIPCC__)+ if (f16_io_) { // X is the FP16 image (set_act_f16); W goes through the dequantization scratch as FP16+ // the only accumulating BF16 product is the BF16X2 low part, which bf16x2_mode() turns off with this path+ if (beta != 0.0f) { std::fprintf(stderr, "prefill gemm: an accumulating BF16 GEMM on the FP16 prompt path\n"); std::exit(1); }+ const int64_t rows = std::min<int64_t>(N, scratch_elems_ / K);+ if (rows <= 0) { std::fprintf(stderr, "prefill gemm: scratch too small for K=%lld\n", (long long) K); std::exit(1); }+ for (int64_t r0 = 0; r0 < N; r0 += rows) {+ const int64_t n = std::min(rows, N - r0);+ bf16_to_f16_rows<<<1024, 256, 0, (cudaStream_t) stream_>>>(W + r0 * K, (__half*) scratch_, n * K);+ f16_inplace(X, scratch_, Y + r0, T, n, K, ldy);+ }+ return;+ }+#endifconst float alpha = 1.0f;#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::bf16, X, W, Y, T, N, K, ldy,- beta, stream_)) {+ beta, stream_, ldx)) {STRATA_ABSORB_HIPBLAS_STICKY("hipBLASLt bf16");return;}+#endif+#if !defined(__HIPCC__)+ if (const int path = K > 0 ? bf16_path() : 0; path == 1 && N > 1 && beta == 0.0f) {+ // a single output row stays cuBLAS's GEMV, faster than the conversions; beta = 1: see above+ const int64_t x_rows = std::max<int64_t>(1, std::min<int64_t>(T, kXSliceElems / K));+ if (grow(tc_w_, tc_w_elems_, N * K) && grow(tc_x_, tc_x_elems_, x_rows * K)) {+ bf16_to_f16(W, tc_w_, N * K, strata::q_of(stream_));+ for (int64_t t0 = 0; t0 < T; t0 += x_rows) {+ const int64_t n = std::min<int64_t>(x_rows, T - t0);+ bf16_to_f16(X + t0 * K, tc_x_, n * K, strata::q_of(stream_));+ f16(tc_x_, tc_w_, Y + t0 * ldy, n, N, K, ldy, beta);+ }+ return;+ }+ }+#if defined(STRATA_EXPERIMENTAL_SM60)+ else if (path == 2) {+ // Pascal: fp32 copies (2 elements of the 2-byte buffers each). Every tile is a disjoint block of Y, so each+ // gets the caller's beta.+ const int64_t x_rows = std::max<int64_t>(1, std::min<int64_t>(T, kXSliceElems / K));+ if (grow(tc_w_, tc_w_elems_, 2 * N * K) && grow(tc_x_, tc_x_elems_, 2 * x_rows * K)) {+ float* const wf = reinterpret_cast<float*>(tc_w_);+ float* const xf = reinterpret_cast<float*>(tc_x_);+ bf16_to_f32(W, wf, N * K, (cudaStream_t) stream_);+ for (int64_t t0 = 0; t0 < T; t0 += x_rows) {+ const int64_t n = std::min<int64_t>(x_rows, T - t0);+ bf16_to_f32(X + t0 * K, xf, n * K, (cudaStream_t) stream_);+ ck(cublasSgemm((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) n, (int) K, &alpha,+ wf, (int) K, xf, (int) K, &beta, Y + t0 * ldy, (int) ldy),+ "cublasSgemm (bf16 on Pascal)");+ }+ return;+ }+ }+#endif#endif// 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,oneapi::mkl::transpose::nontrans, (int)N, (int)T, (int)K, &alpha, W,dpct::library_data_t::real_bfloat16, (int)K, X,- dpct::library_data_t::real_bfloat16, (int)K, &beta, Y,+ dpct::library_data_t::real_bfloat16, (int)(ldx ? ldx : K), &beta, Y,dpct::library_data_t::real_float, (int)ldy,dpct::compute_type::f32)),"cublasGemmEx");@@ -466,6 +774,20 @@ void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_float beta) {if (T <= 0 || N <= 0) return;if (ldy <= 0) ldy = N;+#ifdef STRATA_USE_HIP+ // #313 (opt-in STRATA_WMMA_GEMM=1): RDNA3 / RDNA3.5 WMMA dense GEMM, before hipBLASLt (falls through when false)+ static const bool wmma_on = [] { const char* v = std::getenv("STRATA_WMMA_GEMM"); return v && v[0] != 0 && v[0] != '0'; }();+ static const bool pf_on = [] { const char* v = std::getenv("STRATA_PF_GEMM"); return v && v[0] == '1'; }();+ static const int64_t pf_min_t = [] { const char* v = std::getenv("STRATA_PF_SWITCH_MIN_T"); return v ? (int64_t) std::atoll(v) : (int64_t) 0; }();+ if (pf_on && T >= pf_min_t && strata_pf_gemm_f16(X, W, Y, T, N, K, ldy, beta, stream_)) return; // S23: opt-in+ if (wmma_on && T >= 16 && (beta == 0.0f || beta == 1.0f) &&+ strata_wmma_gemm_f16(X, W, Y, T, N, K, ldy, beta, stream_)) {+ return;+ }+#endif+#if defined(__HIPCC__)+ if (f16_io_ && beta == 0.0f) { f16_inplace(X, W, Y, T, N, K, ldy); return; }+#endifconst float alpha = 1.0f;#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::f16, X, W, Y, T, N, K, ldy,@@ -485,8 +807,133 @@ void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_STRATA_ABSORB_HIPBLAS_STICKY("cublasGemmEx f16");}+#if defined(STRATA_PREFILL_MMQ) && defined(__HIPCC__)+bool Gemm::native_mmq(const uint16_t* X, int type, const void* W, float* Y, int64_t T, int64_t N, int64_t K,+ int64_t ldy) {+ namespace mmq = strata::prefill::mmq;+ constexpr int64_t kRows = 1024, kMaxK = 8192;+ static const bool enabled = [] {+ const char* e = std::getenv("STRATA_DENSE_MMQ");+ return e && e[0] == '1';+ }();+ if (!enabled || mmq_failed_ || !mmq::built() || !mmq::fits(type, N)) return false;+ // K must be a multiple of 256: llama.cpp's MMQ loads the weights in 256-value K chunks, and the+ // chunk past a partial row reads past the row (the next row's bytes - or, for the last weight+ // row, bytes past the tensor, which no caller guarantees to be zeros). The MoE path is safe+ // because its gather buffers carry a zeroed tail; a dense tensor is passed as-is, so a K that+ // is not a full chunk multiple (e.g. the 640-value shared-expert down: 20 blocks of 32) stays on+ // the dequantize + cuBLAS path.+ if (K > kMaxK || K % 256 != 0) return false;+ int64_t R = scratch_elems_ / (2 * K); // FP32 activations for a chunk fit in the FP16 dequant scratch+ if (R > kRows) R = kRows;+ if (R > T) R = T;+ if (R < 1) return false;+ if (ldy <= 0) ldy = N;++ const auto up = [](size_t v) { return (v + 255) & ~(size_t) 255; };+ const size_t ident_off = up(mmq::q8_bytes(kRows, kMaxK));+ const size_t bounds_off = ident_off + up((size_t) kRows * 4);+ if (!mmq_buf_) {+ if (cudaMalloc(&mmq_buf_, bounds_off + 256) != cudaSuccess) {+ cudaGetLastError();+ mmq_failed_ = true;+ return false;+ }+ mmq_ctx_ = new mmq::Context();+ mmq::iota((int32_t*) ((uint8_t*) mmq_buf_ + ident_off), kRows, stream_);+ std::fprintf(stderr, "prefill gemm: dense MMQ on (STRATA_DENSE_MMQ=1)\n");+ }+ void* xq = mmq_buf_;+ const int32_t* ident = (const int32_t*) ((uint8_t*) mmq_buf_ + ident_off);+ int32_t* bounds = (int32_t*) ((uint8_t*) mmq_buf_ + bounds_off);+ float* xf = (float*) scratch_;+ auto* ctx = static_cast<mmq::Context*>(mmq_ctx_);++ for (int64_t r0 = 0; r0 < T; r0 += R) {+ const int64_t rows = (T - r0 < R) ? T - r0 : R;+ mmq::f16_to_f32(X + r0 * K, xf, rows * K, stream_);+ mmq::quantize(xf, nullptr, xq, type, K, K, rows, stream_);+ mmq::set_bounds(bounds, (int32_t) rows, stream_);+ mmq::Product p;+ p.w = W;+ p.type = type;+ p.w_rows = N;+ p.w_cols = K;+ p.expert_bytes = mmq::matrix_bytes(type, N, K);+ p.n = 1;+ p.xq = xq;+ p.bounds = bounds;+ p.ids = ident;+ p.total_rows = rows;+ p.max_rows = rows;+ p.dst = Y + r0 * ldy;+ p.ld_dst = ldy;+ ctx->run(p, stream_);+ }+ return true;+}+#endif+void Gemm::f16_inplace(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy) {+#if defined(__HIPCC__)+ const float one = 1.0f, zero = 0.0f;+ ck(cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &one, W, CUDA_R_16F,+ (int) K, X, CUDA_R_16F, (int) K, &zero, Y, CUDA_R_16F, (int) (2 * ldy), CUBLAS_COMPUTE_32F,+ CUBLAS_GEMM_DEFAULT),+ "cublasGemmEx f16 out");+ static const bool dbg_nan = std::getenv("STRATA_DBG_NAN") != nullptr;+ widen_rows_f16<<<(unsigned) T, 256, 0, (cudaStream_t) stream_>>>(Y, N, ldy, dbg_nan ? 1 : 0);+ if (dbg_nan) { // debug only: a sync per GEMM+ unsigned long long bad = 0, zero_count = 0;+ (void) hipStreamSynchronize((hipStream_t) stream_);+ if (hipMemcpyFromSymbol(&bad, HIP_SYMBOL(g_f16_nonfinite), sizeof bad) == hipSuccess && bad != 0) {+ std::fprintf(stderr, "strata prefill: STRATA_DBG_NAN: %llu non-finite FP16 GEMM outputs (T=%lld N=%lld K=%lld; FP16 ends at 65504)%s",+ bad, (long long) T, (long long) N, (long long) K, "\n");+ (void) hipMemcpyToSymbol(HIP_SYMBOL(g_f16_nonfinite), &zero_count, sizeof zero_count);+ }+ }+#else+ (void) X; (void) W; (void) Y; (void) T; (void) N; (void) K; (void) ldy;+#endif+}+void Gemm::native(const uint16_t* X, int ggml_type, const void* W_blocks, float* Y, int64_t T, int64_t N, int64_t K,- int64_t ldy, float beta) {+ int64_t ldy, float beta, int64_t ldx) {+#ifdef STRATA_USE_HIP+ // S23 (opt-in STRATA_PF_PAD=1, with STRATA_PF_GEMM=1 on chunks of STRATA_PF_SWITCH_MIN_T+ tokens): the weight+ // dequantized into the scratch with row stride K + 64 halves, so no 4 KB-multiple stride camps on the memory+ // channels (gemm_probe8: K 6144 19 -> 29 TFLOPS from W alone, 35 with X padded too). Bitwise the same products.+ static const bool pad_on = [] { const char* v = std::getenv("STRATA_PF_PAD"); return v && v[0] == '1'; }();+ static const bool pf_on = [] { const char* v = std::getenv("STRATA_PF_GEMM"); return v && v[0] == '1'; }();+ static const int64_t pf_min_t = [] { const char* v = std::getenv("STRATA_PF_SWITCH_MIN_T"); return v ? (int64_t) std::atoll(v) : (int64_t) 0; }();+ if (pad_on && pf_on && T >= pf_min_t && T >= 64 && N >= 512 && K % 32 == 0 && N * (K + 64) <= scratch_elems_) {+ const int64_t ldw = K + 64;+ if (strata::kernels::dequant_f16_ld(ggml_type, W_blocks, 0, N, K, ldw, scratch_, stream_) &&+ strata_pf_gemm_f16_ld(X, ldx > 0 ? ldx : K, scratch_, ldw, Y, T, N, K, ldy, beta, stream_)) {+ return;+ }+ }+#endif+ if (ldx > 0 && ldx != K) {+#ifdef STRATA_USE_HIP+ // X arrived padded but the weight cannot be (an i-quant without a strided dequant, or the scratch is too+ // small for N x (K + 64)): the weight unpadded, X read at its stride - the same products, the same bits+ const int64_t rows = scratch_elems_ / K;+ bool ok = rows > 0;+ if (ldy <= 0) ldy = N;+ for (int64_t r0 = 0; ok && r0 < N; r0 += rows) {+ const int64_t n = (N - r0 < rows) ? N - r0 : rows;+ strata::kernels::dequant_f16(ggml_type, W_blocks, r0, n, K, scratch_, stream_);+ ok = strata_pf_gemm_f16_ld(X, ldx, scratch_, K, Y + r0, T, n, K, ldy, beta, stream_);+ }+ if (ok) return;+#endif+ std::fprintf(stderr, "prefill gemm: a padded X (ldx %lld, K %lld) needs STRATA_PF_PAD's path\n",+ (long long) ldx, (long long) K);+ std::exit(1);+ }+#if defined(STRATA_PREFILL_MMQ) && defined(__HIPCC__)+ if (beta == 0.0f && (ldx == 0 || ldx == K) && native_mmq(X, ggml_type, W_blocks, Y, T, N, K, ldy)) return;+#endifif (N * K > scratch_elems_) {// Too large for the scratch at once: in row slices.const int64_t rows = scratch_elems_ / K;diff --git a/sycl/src/prefill/gemm_bf16_parity.dp.cpp b/sycl/src/prefill/gemm_bf16_parity.dp.cppnew file mode 100644index 000000000..7930148ff--- /dev/null+++ b/sycl/src/prefill/gemm_bf16_parity.dp.cpp@@ -0,0 +1,221 @@+// src/prefill/gemm_bf16_parity.cu - Gemm::bf16 against cuBLAS's own BF16 product (GPU, synthetic, no model).+//+// Below sm_80 (no BF16 tensor cores) Gemm::bf16 converts the weight and the activations to FP16 and runs the FP16+// tensor-core GEMM (Volta by default, Turing with STRATA_BF16_TC=1) or widens them to fp32 (Pascal); everywhere else+// it is the cuBLAS BF16 call itself. (On Pascal the cuBLAS BF16 reference itself may be refused: the test then fails+// at the reference, which says so.) This+// checks the result against cublasGemmEx on the same BF16 inputs, within fp32-accumulation rounding, over the prompt+// path's shapes: the hyper-connection down / up projections, the router and indexer rows, the PLE value matrix, a T+// large enough to slice the activations, beta = 1 accumulation (the bf16x2 low parts) and an output row stride wider+// than N. --bench adds the time of each against the cuBLAS BF16 product.+#define DPCT_PROFILING_ENABLED+#include <sycl/sycl.hpp>+#include <dpct/dpct.hpp>+#include "strata/prefill/gemm.hpp"+#include <dpct/blas_utils.hpp>++#include <algorithm>+#include <chrono>+#include <cmath>+#include <cstdint>+#include <cstdio>+#include <cstring>+#include <random>+#include <string>+#include <vector>+#include <dpct/lib_common_utils.hpp>++namespace {++uint16_t to_bf16(float f) { // round to nearest even+ uint32_t u;+ std::memcpy(&u, &f, 4);+ u += 0x7fffu + ((u >> 16) & 1u);+ return (uint16_t) (u >> 16);+}++bool ok_or(dpct::err0 e, const char *what) {+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use error+ codes. Please replace the "get_error_string_dummy(...)" with a real+ error-handling function.+ */++ return e == 0;+}++struct Shape {+ int64_t T, N, K, ldy;+ const char* what;+};++} // namespace++int main(int argc, char **argv) try {+ const bool bench = argc > 1 && std::string(argv[1]) == "--bench";+ int dev = 0, maj = 0, min = 0;+ dev = dpct::get_current_device_id();+ maj = dpct::get_device(dev).get_major_version();+ min = dpct::get_device(dev).get_minor_version();+ std::printf("gemm_bf16_parity: compute capability %d.%d\n", maj, min);++ dpct::queue_ptr st = &dpct::get_in_order_queue();+ if (!ok_or(DPCT_CHECK_ERROR(+ st = dpct::get_current_device().create_queue(true)),+ "stream")) return 1;+ strata::prefill::Gemm gemm;+ std::string err;+ if (!gemm.init(st, 0, err)) { std::printf("FAIL: %s\n", err.c_str()); return 1; }+ dpct::blas::descriptor_ptr h = nullptr;+ if (DPCT_CHECK_ERROR(h = new dpct::blas::descriptor()) != 0) {+ std::printf("FAIL: cublasCreate\n"); return 1;+ }+ h->set_queue(st);++ const Shape shapes[] = {+ {4096, 320, 10240, 0, "hc down (activations sliced)"},+ {4096, 10240, 320, 0, "hc up"},+ {777, 2560, 2560, 0, "PLE value"},+ {512, 512, 2560, 0, "router / indexer q"},+ {300, 4, 10240, 0, "hc inject"},+ {2048, 1, 2560, 0, "single row"},+ {333, 128, 2560, 136, "row stride wider than N"},+ };+ std::mt19937 rng(1234);+ std::normal_distribution<float> nd(0.0f, 1.0f);+ int failures = 0;+ for (const Shape& s : shapes) {+ const int64_t ldy = s.ldy > 0 ? s.ldy : s.N;+ std::vector<uint16_t> x((size_t) (s.T * s.K)), xlo(x.size()), w((size_t) (s.N * s.K));+ for (size_t i = 0; i < x.size(); ++i) {+ const float v = 3.0f * nd(rng); // activations: normalized, a few units+ x[i] = to_bf16(v);+ xlo[i] = to_bf16(1e-3f * nd(rng)); // a bf16x2 low part+ }+ for (auto& v : w) v = to_bf16(0.02f * nd(rng));+ uint16_t *dx = nullptr, *dxlo = nullptr, *dw = nullptr;+ float *dy = nullptr, *dr = nullptr;+ const size_t ybytes = (size_t) (s.T * ldy) * 4;+ bool ok =+ ok_or(+ DPCT_CHECK_ERROR(dx = (uint16_t *)sycl::malloc_device(+ x.size() * 2, dpct::get_in_order_queue())),+ "x") &&+ ok_or(+ DPCT_CHECK_ERROR(dxlo = (uint16_t *)sycl::malloc_device(+ x.size() * 2, dpct::get_in_order_queue())),+ "xlo") &&+ ok_or(+ DPCT_CHECK_ERROR(dw = (uint16_t *)sycl::malloc_device(+ w.size() * 2, dpct::get_in_order_queue())),+ "w") &&+ ok_or(DPCT_CHECK_ERROR(dy = (float *)sycl::malloc_device(+ ybytes, dpct::get_in_order_queue())),+ "y") &&+ ok_or(DPCT_CHECK_ERROR(dr = (float *)sycl::malloc_device(+ ybytes, dpct::get_in_order_queue())),+ "ref");+ if (!ok) return 1;+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable memory.+ If the memory is not pageable, call wait() on event return by memcpy API+ to ensure synchronization behavior.+ */+ dpct::get_in_order_queue().memcpy(dx, x.data(), x.size() * 2).wait();+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable memory.+ If the memory is not pageable, call wait() on event return by memcpy API+ to ensure synchronization behavior.+ */+ dpct::get_in_order_queue().memcpy(dxlo, xlo.data(), xlo.size() * 2).wait();+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable memory.+ If the memory is not pageable, call wait() on event return by memcpy API+ to ensure synchronization behavior.+ */+ dpct::get_in_order_queue().memcpy(dw, w.data(), w.size() * 2).wait();+ dpct::get_in_order_queue().memset(dy, 0, ybytes).wait();+ dpct::get_in_order_queue().memset(dr, 0, ybytes).wait();++ // the product under test: X . W^T, then the low part added with beta = 1+ gemm.bf16(dx, dw, dy, s.T, s.N, s.K, ldy);+ gemm.bf16(dxlo, dw, dy, s.T, s.N, s.K, ldy, 1.0f);+ // the reference: cuBLAS on the BF16 inputs, the same two calls+ const float one = 1.0f, zero = 0.0f;+ auto ref = [&](const uint16_t* X, float beta) {+ /*+ DPCT1020: Migration of cublasGemmEx, if it is called from+ __global__ or __device__ function, is not supported. You may need to+ redesign the code to use the host-side dpct::blas::gemm instead,+ which submits this call to the SYCL queue automatically.+ */+ return cublasGemmEx(+ h, oneapi::mkl::transpose::trans,+ oneapi::mkl::transpose::nontrans, (int)s.N, (int)s.T, (int)s.K,+ &one, dw, dpct::library_data_t::real_bfloat16, (int)s.K, X,+ dpct::library_data_t::real_bfloat16, (int)s.K, &beta, dr,+ dpct::library_data_t::real_float, (int)ldy,+ dpct::compute_type::f32, -1);+ };+ if (ref(dx, zero) != 0 || ref(dxlo, one) != 0) {+ std::printf("FAIL: reference cublasGemmEx\n");+ return 1;+ }+ if (!ok_or(DPCT_CHECK_ERROR(st->wait()), "sync")) return 1;+ std::vector<float> y((size_t) (s.T * ldy)), r(y.size());+ dpct::get_in_order_queue().memcpy(y.data(), dy, ybytes).wait();+ dpct::get_in_order_queue().memcpy(r.data(), dr, ybytes).wait();+ double worst = 0.0, mag = 1e-30;+ int bad = 0;+ for (int64_t t = 0; t < s.T; ++t)+ for (int64_t c = 0; c < s.N; ++c) {+ const float a = y[(size_t) (t * ldy + c)], b = r[(size_t) (t * ldy + c)];+ if (!std::isfinite(a)) ++bad;+ worst = std::max(worst, (double) std::fabs(a - b));+ mag = std::max(mag, (double) std::fabs(b));+ }+ // the untouched columns of a wider row stride stay as they were+ for (int64_t t = 0; t < s.T && ldy > s.N; ++t)+ for (int64_t c = s.N; c < ldy; ++c)+ if (y[(size_t) (t * ldy + c)] != 0.0f) ++bad;+ const bool pass = bad == 0 && worst <= 1e-4 * mag;+ if (!pass) ++failures;+ std::printf(" %-32s T %5lld N %5lld K %5lld ldy %5lld: worst |diff| %.3e of max |ref| %.3e (rel %.2e) %s\n",+ s.what, (long long) s.T, (long long) s.N, (long long) s.K, (long long) ldy, worst, mag, worst / mag,+ pass ? "pass" : "FAIL");++ if (bench) {+ auto time = [&](auto&& f) {+#pragma unroll+ for (int i = 0; i < 3; ++i) f();+ st->wait();+ const auto t0 = std::chrono::steady_clock::now();+#pragma unroll+ for (int i = 0; i < 20; ++i) f();+ st->wait();+ return std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count() / 20;+ };+ const double us_gemm = time([&] { gemm.bf16(dx, dw, dy, s.T, s.N, s.K, ldy); });+ const double us_ref = time([&] { ref(dx, zero); });+ std::printf(" bench: Gemm::bf16 %9.1f us cuBLAS BF16 %9.1f us (%.2fx)\n", us_gemm, us_ref,+ us_ref / us_gemm);+ }+ sycl::free(dx, dpct::get_in_order_queue());+ sycl::free(dxlo, dpct::get_in_order_queue());+ sycl::free(dw, dpct::get_in_order_queue());+ sycl::free(dy, dpct::get_in_order_queue());+ sycl::free(dr, dpct::get_in_order_queue());+ }+ delete (h);+ dpct::get_current_device().destroy_queue(st);+ std::printf("gemm_bf16_parity: %d failures\n", failures);+ return failures == 0 ? 0 : 1;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}diff --git a/sycl/src/prefill/kernels.dp.cpp b/sycl/src/prefill/kernels.dp.cppindex 36f064fa7..8646be312 100644--- a/sycl/src/prefill/kernels.dp.cpp+++ b/sycl/src/prefill/kernels.dp.cpp@@ -5,12 +5,17 @@#include "strata/sycl_queue.hpp"#include "strata/prefill/kernels.hpp"#include "strata/kernels/mrope.hpp"+#include "strata/kernels/gfx_arch.hpp"#include "strata/kernels/router_top10.hpp"+#include <algorithm>++#include <algorithm>#include <cfloat>#include <cmath>#include <cstdio>#include <cstdlib>+#include <cstring>namespace strata::prefill {namespace {@@ -69,6 +74,14 @@ __dpct_inline__ uint16_t hf_sat(float f) {return hf(sycl::isnan(f) ? f: sycl::fmin(sycl::fmax(f, -65504.0f), 65504.0f));}+// The prompt path's 16-bit activation image for the BF16-weight GEMMs: BF16, or FP16 where the GEMM library is fast+// only in FP16 (prompt_f16() in gemm.cu: rocBLAS on gfx103x). Set once per device before the first prompt.+#if defined(__HIPCC__) // HIP only (#835): the CUDA kernels stay exactly as they were, they never read the flag+__device__ int g_act_f16 = 0;+__device__ __forceinline__ uint16_t act16(float f) { return g_act_f16 ? hf_sat(f) : bf(f); }+#else+__dpct_inline__ uint16_t act16(float f) { return bf(f); }+#endif// block-wide sum for blockDim.x <= 1024, result broadcastinline float block_sum(float v, float *sh) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();@@ -137,7 +150,7 @@ auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(d += item_ct1.get_local_range(2)) {const float v = r[d] * rs * w[c * N + d];xn[row * N + d] = v;- const uint16_t h = bf(v);+ const uint16_t h = act16(v);xn16[row * N + d] = h;if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h);}@@ -148,13 +161,15 @@ __dpct_inline__ void gr_norm_rs_kernel(const float *__restrict__ R,const float *__restrict__ w, float eps,float *__restrict__ rs_out,uint16_t *__restrict__ xn16,- uint16_t *__restrict__ xn16_lo) {+ uint16_t *__restrict__ xn16_lo,+ int64_t ldx) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(sycl::ext::oneapi::this_work_item::get_work_group<3>());const int64_t row = item_ct1.get_group(2); // t * 4 + cconst int c = (int) (row % HC);const float* r = R + row * N;+ const int64_t xo = (row / HC) * ldx + (int64_t) c * N; // the BF16 image's row (token stride ldx)float ss = 0.0f;#pragma unrollfor (int d = item_ct1.get_local_id(2); d < N;@@ -164,9 +179,9 @@ auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(for (int d = item_ct1.get_local_id(2); d < N;d += item_ct1.get_local_range(2)) {const float v = r[d] * rs * w[c * N + d];- const uint16_t h = bf(v);- xn16[row * N + d] = h;- if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h);+ const uint16_t h = act16(v);+ xn16[xo + d] = h;+ if (xn16_lo) xn16_lo[xo + d] = bf_lo(v, h);}}__dpct_inline__ void@@ -191,7 +206,7 @@ gr_mix_r_kernel(const float *__restrict__ R, const float *__restrict__ rs,s /= (float) HC;mixed[i] = s;if (mixed16) {- const uint16_t h = bf(s);+ const uint16_t h = act16(s);mixed16[i] = h;if (mixed16_lo) mixed16_lo[i] = bf_lo(s, h);}@@ -206,7 +221,7 @@ gr_write_norm_rs_kernel(float *__restrict__ R, const float *__restrict__ bo,const float *__restrict__ inj, int64_t inj_ld,const float *__restrict__ w, float eps,float *__restrict__ rs_out, uint16_t *__restrict__ xn16,- uint16_t *__restrict__ xn16_lo) {+ uint16_t *__restrict__ xn16_lo, int64_t ldx) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(sycl::ext::oneapi::this_work_item::get_work_group<3>());@@ -214,6 +229,7 @@ auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(const int64_t t = row / HC;const int c = (int) (row % HC);float* r = R + row * N;+ const int64_t xo = t * ldx + (int64_t) c * N;const float sc = 2.0f * sigm(inj[t * inj_ld + c] / (float) HC);float v[GRW_PER];float ss = 0.0f;@@ -231,9 +247,122 @@ auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(#pragma unrollfor (int d = item_ct1.get_local_id(2); d < N; d += 256, ++k) {const float x = v[k] * rs * w[c * N + d];- const uint16_t h = bf(x);- xn16[row * N + d] = h;- if (xn16_lo) xn16_lo[row * N + d] = bf_lo(x, h);+ const uint16_t h = act16(x);+ xn16[xo + d] = h;+ if (xn16_lo) xn16_lo[xo + d] = bf_lo(x, h);+ }+}+// S23 (opt-in STRATA_CVEC_FUSE=1): a steered layer's FFN write, its control vector and the next half's norm in one+// pass over R (was gr_write + cvec_apply + gr_norm_rs: three). The write is gr_write_kernel's, the vector+// cvec_kernel's (the same per-thread dot order over d = tid + 256 k, the same two-level xor reduction), the norm+// gr_norm_rs_kernel's (the same ss order and block_sum): the same bits.+/*+DPCT1110: The total declared local variable size in device function+gr_write_cvec_norm_rs_kernel exceeds 128 bytes and may cause high register+pressure. Consult with your hardware vendor to find the total register size+available and adjust the code, or use smaller sub-group size to avoid high+register pressure.+*/+__dpct_inline__ void gr_write_cvec_norm_rs_kernel(+ float *__restrict__ R, const float *__restrict__ bo,+ const float *__restrict__ inj, int64_t inj_ld,+ const float *__restrict__ v_l, const float *__restrict__ s_l,+ const int *__restrict__ on, int mode, const float *__restrict__ w,+ float eps, float *__restrict__ rs_out, uint16_t *__restrict__ xn16,+ uint16_t *__restrict__ xn16_lo, int64_t ldx) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &part = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[8]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const int64_t row = item_ct1.get_group(2); // t * 4 + c+ const int64_t t = row / HC;+ const int c = (int) (row % HC);+ float* r = R + row * N;+ const float sc = 2.0f * sigm(inj[t * inj_ld + c] / (float) HC);+ const float s = *s_l;+ const bool steer = *on != 0 && s != 0.0f;+ float x[GRW_PER];+ float dot = 0.0f;+ int k = 0;+#pragma unroll+ for (int d = item_ct1.get_local_id(2); d < N; d += 256, ++k) {+ const float xv = sycl::fma((float)(bo[t * N + d]), (float)sc, r[d]);+ x[k] = xv;+ if (steer && mode == 0) dot =+ sycl::fma((float)xv, (float)(v_l[d]), dot);+ }+ if (steer && mode == 0) {+#pragma unroll+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ for (int o = 16; o > 0; o >>= 1) dot +=+ dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),+ dot, o);+ if ((item_ct1.get_local_id(2) & 31) == 0)+ part[item_ct1.get_local_id(2) >> 5] = dot;+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ if (item_ct1.get_local_id(2) < 32) {+ float p = item_ct1.get_local_id(2) < 8+ ? part[item_ct1.get_local_id(2)]+ : 0.0f;+#pragma unroll+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ for (int o = 16; o > 0; o >>= 1) p +=+ dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu,+ sycl::ext::oneapi::this_work_item::get_sub_group(), p, o);+ if (item_ct1.get_local_id(2) == 0) part[0] = p;+ }+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ dot = part[0] * s;+ }+ float ss = 0.0f;+ k = 0;+#pragma unroll+ for (int d = item_ct1.get_local_id(2); d < N; d += 256, ++k) {+ float xv = x[k];+ if (steer) xv =+ mode == 0 ? sycl::fma(-dot, (float)(v_l[d]), xv) : xv + v_l[d];+ r[d] = xv;+ x[k] = xv;+ ss += xv * xv;+ }+ const float rs = sycl::rsqrt(block_sum(ss, sh) / (float)N + eps);+ if (item_ct1.get_local_id(2) == 0) rs_out[row] = rs;+ k = 0;+#pragma unroll+ for (int d = item_ct1.get_local_id(2); d < N; d += 256, ++k) {+ const float y = x[k] * rs * w[c * N + d];+ const uint16_t h = act16(y);+ xn16[t * ldx + (int64_t) c * N + d] = h;+ if (xn16_lo) xn16_lo[t * ldx + (int64_t) c * N + d] = bf_lo(y, h);}}__dpct_inline__ void gr_silu_kernel(const float *__restrict__ lo,@@ -246,7 +375,7 @@ __dpct_inline__ void gr_silu_kernel(const float *__restrict__ lo,if (i >= n) return;const float x = lo[i] / (float) HC;const float v = x / (1.0f + sycl::native::exp(-x));- const uint16_t h = bf(v);+ const uint16_t h = act16(v);lo16[i] = h;if (lo16_lo) lo16_lo[i] = bf_lo(v, h);}@@ -271,7 +400,7 @@ __dpct_inline__ void gr_mix_kernel(const float *__restrict__ xn,s /= (float) HC;mixed[i] = s;if (mixed16) {- const uint16_t h = bf(s);+ const uint16_t h = act16(s);mixed16[i] = h;if (mixed16_lo) mixed16_lo[i] = bf_lo(s, h);}@@ -361,6 +490,103 @@ __dpct_inline__ void gdn_conv_tiled_kernel(const float *__restrict__ hist,v0 = v1; v1 = v2; v2 = x;}}+// Aurora (S23, opt-in STRATA_GDN_CONVL2=1): gdn_conv_tiled_kernel with gdn_l2_kernel folded in. A block's 128 threads+// are the 128 channels of one head, so for the q / k heads (block < 2 HK) the norm's sum of squares is the block's:+// the same warp_sum, the same four partials added in the same order, the same v * rsqrtf(ss + eps) on the same+// stored value - the same bits, without writing h and reading it back (16 tokens per round).+__dpct_inline__ void gdn_conv_l2_kernel(const float *__restrict__ hist,+ const float *__restrict__ qkv,+ const float *__restrict__ w,+ float *__restrict__ h, int64_t T,+ float eps) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int c = item_ct1.get_group(2) * item_ct1.get_local_range(2) ++ item_ct1.get_local_id(2);+ const int64_t t0 = (int64_t)item_ct1.get_group(1) * CONV_TILE;+ if (t0 >= T) return;+ const int64_t t1 = t0 + CONV_TILE < T ? t0 + CONV_TILE : T;+ auto input = [&](int64_t t) -> float { return t >= 0 ? qkv[t * C + c] : hist[c * 3 + (int) (t + 3)]; };+ float v0 = input(t0 - 3), v1 = input(t0 - 2), v2 = input(t0 - 1);+ const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3];+ for (int64_t t = t0; t < t1; ++t) { // gdn_conv_tiled_kernel's loop, verbatim+ const float x = qkv[t * C + c];+ const float s = v0 * w0 + v1 * w1 + v2 * w2 + x * w3;+ h[t * C + c] = s / (1.0f + sycl::native::exp(-s));+ v0 = v1; v1 = v2; v2 = x;+ }+ if (item_ct1.get_group(2) >= 2 * HK) return; // v channels: no norm+ auto &part =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<float[16][4]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ for (int64_t tb = t0; tb < t1; tb += 16) {+ const int n = (int) (t1 - tb < 16 ? t1 - tb : 16);+ for (int j = 0; j < n; ++j) { // (each thread reads back its own stored value)+ const float v = h[(tb + j) * C + c];+ // gdn_l2_kernel as the compiler built it: the first xor step adds the partner's rounded square to an+ // unrounded own one (an fma), the other steps are plain adds - spelled out so no contraction can differ+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ /*+ DPCT1013: The rounding mode could not be specified and the+ generated code may have different accuracy than the original code.+ Verify the correctness. SYCL math built-in function rounding mode is+ aligned with OpenCL C 1.2 standard.+ */+ float sq = sycl::fma(+ v, v,+ dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu,+ sycl::ext::oneapi::this_work_item::get_sub_group(), v * v,+ 16));+#pragma unroll+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ /*+ DPCT1013: The rounding mode could not be specified and the+ generated code may have different accuracy than the original code.+ Verify the correctness. SYCL math built-in function rounding mode is+ aligned with OpenCL C 1.2 standard.+ */+ for (int o = 8; o > 0; o >>= 1) sq =+ sq + dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu,+ sycl::ext::oneapi::this_work_item::get_sub_group(), sq,+ o);+ if ((item_ct1.get_local_id(2) & 31) == 0)+ part[j][item_ct1.get_local_id(2) >> 5] = sq;+ }+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ for (int j = 0; j < n; ++j) {+ const float ss = part[j][0] + part[j][1] + part[j][2] + part[j][3];+ h[(tb + j) * C + c] = h[(tb + j) * C + c] * sycl::rsqrt(ss + eps);+ }+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ }+}// the history after the chunk: its last three inputs (the older history where the chunk is shorter than 3)__dpct_inline__ void gdn_conv_hist_kernel(float *__restrict__ hist,const float *__restrict__ qkv,@@ -409,7 +635,7 @@ gdn_rec_kernel(float *__restrict__ state, const float *__restrict__ h,const float *__restrict__ gate, const float *__restrict__ beta,const float *__restrict__ z, const float *__restrict__ gamma,float eps, float *__restrict__ y, uint16_t *__restrict__ y16,- int64_t T) {+ int64_t T, int64_t ld16) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(sycl::ext::oneapi::this_work_item::get_work_group<3>());@@ -521,7 +747,7 @@ auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(const float v = oc * sycl::rsqrt(ss / (float)S + eps) * g_col *sigm(z[t * HV * S + head * S + col]);y[t * HV * S + head * S + col] = v;- y16[t * HV * S + head * S + col] = hf(v);+ y16[t * ld16 + head * S + col] = hf(v);}}#pragma unroll@@ -1006,12 +1232,419 @@ bool gdn_keyhead_ok() {return on;}#endif-// the output norm over a head's 128 columns, into the FP16 copy the out projection reads (the FP32 output before the-// norm stays in its scratch buffer)+#if defined(__HIPCC__) // the Aurora (gfx11) recurrence kernels: AMD builds only+// Aurora (S23): the recurrence with the column-split grid of gdn_rec_cols_pipe_kernel (four 32-column blocks per value+// head) but FOUR LANES per column, lane g holding the column's state rows 32g .. 32g + 31 in registers - exactly the+// row group the old kernel's thread (col, rg = g) held - so a token needs no __syncthreads: the four kv / o partials+// meet through wave shuffles and are added in the old order red[0] + red[1] + red[2] + red[3] (the same bits;+// tests/hip/gdn_rec_head.cpp). The q/k rows, v, gate and beta are staged in LDS HT tokens at a time, the next chunk+// loaded into registers while this one computes, and a token's k and q rows are read into registers before its+// products (one LDS latency per token, not one per load). The old kernels took ~4 barriers per token and ~3.5 us+// per token and layer on the Radeon 8060S; the output norm runs after it in gdn_out_norm_warp_kernel.+// STRATA_GDN_HEAD=0: the old kernels.+constexpr int HT = 4; // tokens per staged chunk (LDS ~10 KB: all 192 blocks resident)+constexpr int QCB = 32; // columns per block+constexpr int QTH = QCB * 4; // threads per block: 4 lanes per column+constexpr int QRS = 36; // staged row-group stride (32 rows + 4 pad: the 4 groups' reads+ // land in different LDS banks)+constexpr int QPF = HT * 2 * S / 4 / QTH; // float4 of q/k each thread prefetches per chunk (2)+__global__ void __launch_bounds__(QTH) gdn_rec_quad_kernel(float* __restrict__ state, const float* __restrict__ h,+ const float* __restrict__ gate, const float* __restrict__ beta,+ float* __restrict__ oc_out, int64_t T) {+ __shared__ __align__(16) float sqk[2][HT][2][4 * QRS]; // [buffer][token][q | k][group][row (padded)]+ __shared__ float sgb[2][2][HT]; // [buffer][gate | beta][token]+ __shared__ float sv[2][HT][QCB]; // [buffer][token][column] v+ const int head = blockIdx.x / (S / QCB), cb = blockIdx.x % (S / QCB);+ const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;+ const int g = lane >> 3, cl = wave * 8 + (lane & 7), col = cb * QCB + cl; // row group, column in block / head+ const int qh = head % HK;+ float s[32];+ {+ const float* base = state + ((size_t) (g * 32) * HV + head) * S + col;+#pragma unroll+ for (int r = 0; r < 32; ++r) s[r] = base[(size_t) r * HV * S];+ }+ float4 pf[QPF];+ float pv[HT], pgb = 0.0f;+ // chunk c's inputs into registers: q/k (float4 i of the chunk's [token][q|k][S/4] block), the column's v (lanes of+ // group 0) and gate (threads 0..HT-1) / beta (HT..2HT-1) of token `tid % HT`+ auto fetch = [&](int64_t c) {+ const int64_t t0 = c * HT;+#pragma unroll+ for (int u = 0; u < QPF; ++u) {+ const int i = tid + u * QTH;+ const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);+ const int64_t t = t0 + tt;+ pf[u] = t < T ? *reinterpret_cast<const float4*>(h + t * C + part * HK * S + qh * S + r4 * 4)+ : make_float4(0.f, 0.f, 0.f, 0.f);+ }+ if (g == 0) {+#pragma unroll+ for (int tt = 0; tt < HT; ++tt) {+ const int64_t t = t0 + tt;+ pv[tt] = t < T ? h[t * C + 2 * HK * S + head * S + col] : 0.0f;+ }+ }+ if (tid < 2 * HT) {+ const int64_t t = t0 + (tid % HT);+ pgb = t < T ? (tid < HT ? gate : beta)[t * HV + head] : 0.0f;+ }+ };+ const float rs_s = rsqrtf((float) S);+ const int src0 = lane & 7; // lane of group 0 for this column; group j is src0 + 8 j+ const int64_t nch = (T + HT - 1) / HT;+ if (nch > 0) fetch(0);+ for (int64_t c = 0; c < nch; ++c) {+ const int b = (int) (c & 1);+ if (g == 0) {+#pragma unroll+ for (int tt = 0; tt < HT; ++tt) sv[b][tt][cl] = pv[tt];+ }+#pragma unroll+ for (int u = 0; u < QPF; ++u) {+ const int i = tid + u * QTH;+ const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);+ const int row = r4 * 4;+ *reinterpret_cast<float4*>(&sqk[b][tt][part][(row >> 5) * QRS + (row & 31)]) = pf[u];+ }+ if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb;+ __syncthreads(); // chunk c staged (buffer b was last read two chunks ago)+ if (c + 1 < nch) fetch(c + 1);+ const int64_t t0 = c * HT;+ const int nt = (int) (T - t0 < HT ? T - t0 : HT);+ for (int tt = 0; tt < nt; ++tt) {+ float k[32], q[32];+ {+ const float4* k4 = reinterpret_cast<const float4*>(&sqk[b][tt][1][g * QRS]);+ const float4* q4 = reinterpret_cast<const float4*>(&sqk[b][tt][0][g * QRS]);+#pragma unroll+ for (int j = 0; j < 8; ++j) {+ const float4 kk = k4[j], qq = q4[j];+ k[4 * j] = kk.x; k[4 * j + 1] = kk.y; k[4 * j + 2] = kk.z; k[4 * j + 3] = kk.w;+ q[4 * j] = qq.x; q[4 * j + 1] = qq.y; q[4 * j + 2] = qq.z; q[4 * j + 3] = qq.w;+ }+ }+ const float g_exp = __expf(sgb[b][0][tt]);+ float kv = 0.0f;+#pragma unroll+ for (int r = 0; r < 32; ++r) kv = fmaf(s[r], k[r], kv);+ const float p0 = __shfl_sync(0xffffffffu, kv, src0), p1 = __shfl_sync(0xffffffffu, kv, src0 + 8),+ p2 = __shfl_sync(0xffffffffu, kv, src0 + 16), p3 = __shfl_sync(0xffffffffu, kv, src0 + 24);+ const float kv_col = p0 + p1 + p2 + p3;+ const float cvt = sv[b][tt][cl], cbt = sgb[b][1][tt];+ const float delta = (cvt - g_exp * kv_col) * cbt;+ float o = 0.0f;+#pragma unroll+ for (int r = 0; r < 32; ++r) {+ s[r] = fmaf(g_exp, s[r], k[r] * delta);+ o = fmaf(s[r], q[r], o);+ }+ const float o0 = __shfl_sync(0xffffffffu, o, src0), o1 = __shfl_sync(0xffffffffu, o, src0 + 8),+ o2 = __shfl_sync(0xffffffffu, o, src0 + 16), o3 = __shfl_sync(0xffffffffu, o, src0 + 24);+ if (g == 0) oc_out[(t0 + tt) * HV * S + head * S + col] = (o0 + o1 + o2 + o3) * rs_s;+ }+ }+ {+ float* base = state + ((size_t) (g * 32) * HV + head) * S + col;+#pragma unroll+ for (int r = 0; r < 32; ++r) base[(size_t) r * HV * S] = s[r];+ }+}+// Aurora (S23, opt-in STRATA_GDN_PP=1): gdn_rec_quad_kernel with the same arithmetic in the same order, two changes in+// how it is compiled. (1) The VGPR count: the 32 state-row addresses of the first loads were kept live across the+// whole walk to be reused by the final stores (64 VGPRs, 196 in all = 7 waves a SIMD for the 192 blocks of 4 waves+// that need 9.6): the stores' lane offset goes through an asm so the addresses are made again, 133 VGPRs, all blocks+// resident. (2) A full chunk's four tokens run with the state alternating between two register sets (the update+// writes the other set), so the compiler emits no 32 register copies after the update.+__global__ void __launch_bounds__(QTH) gdn_rec_quad_pp_kernel(float* __restrict__ state, const float* __restrict__ h,+ const float* __restrict__ gate, const float* __restrict__ beta,+ float* __restrict__ oc_out, int64_t T) {+ __shared__ __align__(16) float sqk[2][HT][2][4 * QRS]; // [buffer][token][q | k][group][row (padded)]+ __shared__ float sgb[2][2][HT]; // [buffer][gate | beta][token]+ __shared__ float sv[2][HT][QCB]; // [buffer][token][column] v+ const int head = blockIdx.x / (S / QCB), cb = blockIdx.x % (S / QCB);+ const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;+ const int g = lane >> 3, cl = wave * 8 + (lane & 7), col = cb * QCB + cl; // row group, column in block / head+ const int qh = head % HK;+ float s[32];+ {+ const float* sb = state + (size_t) head * S;+ const uint32_t voff = (uint32_t) ((g * 32) * HV * S + col);+#pragma unroll+ for (int r = 0; r < 32; ++r) s[r] = sb[(size_t) r * HV * S + voff];+ }+ float4 pf[QPF];+ float pv[HT], pgb = 0.0f;+ // chunk c's inputs into registers: q/k (float4 i of the chunk's [token][q|k][S/4] block), the column's v (lanes of+ // group 0) and gate (threads 0..HT-1) / beta (HT..2HT-1) of token `tid % HT`+ auto fetch = [&](int64_t c) {+ const int64_t t0 = c * HT;+#pragma unroll+ for (int u = 0; u < QPF; ++u) {+ const int i = tid + u * QTH;+ const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);+ const int64_t t = t0 + tt;+ pf[u] = t < T ? *reinterpret_cast<const float4*>(h + t * C + part * HK * S + qh * S + r4 * 4)+ : make_float4(0.f, 0.f, 0.f, 0.f);+ }+ if (g == 0) {+#pragma unroll+ for (int tt = 0; tt < HT; ++tt) {+ const int64_t t = t0 + tt;+ pv[tt] = t < T ? h[t * C + 2 * HK * S + head * S + col] : 0.0f;+ }+ }+ if (tid < 2 * HT) {+ const int64_t t = t0 + (tid % HT);+ pgb = t < T ? (tid < HT ? gate : beta)[t * HV + head] : 0.0f;+ }+ };+ const float rs_s = rsqrtf((float) S);+ const int src0 = lane & 7; // lane of group 0 for this column; group j is src0 + 8 j+ const int64_t nch = (T + HT - 1) / HT;+ if (nch > 0) fetch(0);+ for (int64_t c = 0; c < nch; ++c) {+ const int b = (int) (c & 1);+ if (g == 0) {+#pragma unroll+ for (int tt = 0; tt < HT; ++tt) sv[b][tt][cl] = pv[tt];+ }+#pragma unroll+ for (int u = 0; u < QPF; ++u) {+ const int i = tid + u * QTH;+ const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);+ const int row = r4 * 4;+ *reinterpret_cast<float4*>(&sqk[b][tt][part][(row >> 5) * QRS + (row & 31)]) = pf[u];+ }+ if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb;+ __syncthreads(); // chunk c staged (buffer b was last read two chunks ago)+ if (c + 1 < nch) fetch(c + 1);+ const int64_t t0 = c * HT;+ const int nt = (int) (T - t0 < HT ? T - t0 : HT);+ auto token = [&](int tt, float (&sin)[32], float (&sout)[32]) {+ float k[32], q[32];+ {+ const float4* k4 = reinterpret_cast<const float4*>(&sqk[b][tt][1][g * QRS]);+ const float4* q4 = reinterpret_cast<const float4*>(&sqk[b][tt][0][g * QRS]);+#pragma unroll+ for (int j = 0; j < 8; ++j) {+ const float4 kk = k4[j], qq = q4[j];+ k[4 * j] = kk.x; k[4 * j + 1] = kk.y; k[4 * j + 2] = kk.z; k[4 * j + 3] = kk.w;+ q[4 * j] = qq.x; q[4 * j + 1] = qq.y; q[4 * j + 2] = qq.z; q[4 * j + 3] = qq.w;+ }+ }+ const float g_exp = __expf(sgb[b][0][tt]);+ float kv = 0.0f;+#pragma unroll+ for (int r = 0; r < 32; ++r) kv = fmaf(sin[r], k[r], kv);+ const float p0 = __shfl_sync(0xffffffffu, kv, src0), p1 = __shfl_sync(0xffffffffu, kv, src0 + 8),+ p2 = __shfl_sync(0xffffffffu, kv, src0 + 16), p3 = __shfl_sync(0xffffffffu, kv, src0 + 24);+ const float kv_col = p0 + p1 + p2 + p3;+ const float cvt = sv[b][tt][cl], cbt = sgb[b][1][tt];+ const float delta = (cvt - g_exp * kv_col) * cbt;+ float o = 0.0f;+#pragma unroll+ for (int r = 0; r < 32; ++r) {+ sout[r] = fmaf(g_exp, sin[r], k[r] * delta);+ o = fmaf(sout[r], q[r], o);+ }+ const float o0 = __shfl_sync(0xffffffffu, o, src0), o1 = __shfl_sync(0xffffffffu, o, src0 + 8),+ o2 = __shfl_sync(0xffffffffu, o, src0 + 16), o3 = __shfl_sync(0xffffffffu, o, src0 + 24);+ if (g == 0) oc_out[(t0 + tt) * HV * S + head * S + col] = (o0 + o1 + o2 + o3) * rs_s;+ };+ if (nt == HT) { // the state alternates between two register sets: no copy after the update+ float s2[32];+ token(0, s, s2);+ token(1, s2, s);+ token(2, s, s2);+ token(3, s2, s);+ } else {+ for (int tt = 0; tt < nt; ++tt) {+ float s2[32];+ token(tt, s, s2);+#pragma unroll+ for (int r = 0; r < 32; ++r) s[r] = s2[r];+ }+ }+ }+ {+ float* sb = state + (size_t) head * S;+ uint32_t voff = (uint32_t) ((g * 32) * HV * S + col);+ asm volatile("" : "+v"(voff)); // (so the loads' 32 addresses are not kept alive across the whole loop)+#pragma unroll+ for (int r = 0; r < 32; ++r) sb[(size_t) r * HV * S + voff] = s[r];+ }+}++// Aurora (S23, opt-in STRATA_GDN_PP=2): gdn_rec_quad_kernel with two columns per lane (a wave: 4 row groups x 8 lanes x+// 2 columns = 16 columns; a block of 4 waves 64 columns, 96 blocks). A lane's two columns share the k / q rows it+// reads from shared memory (half the LDS reads and shuffles per column, the kernel's limit) and give each wave two+// independent dependency chains; the 384 waves fit in one round at 230 VGPRs. Per column the same arithmetic in+// the same order (the same bits as gdn_rec_quad_kernel). The store of the state goes through an asm for the reason+// given at gdn_rec_quad_pp_kernel.++// ---- C2: two columns per lane (a wave: 4 row groups x 8 lanes x 2 columns = 16 columns; a block of 4 waves 64+// columns). A lane's two columns share the k / q rows it reads from LDS (half the LDS reads and shuffles per column+// and two independent dependency chains in each wave). Per column the same arithmetic in the same order.+constexpr int C2CB = 64; // columns per block+constexpr int C2PF = HT * 2 * S / 4 / QTH; // float4 of q/k each thread prefetches per chunk (2)+__global__ void __launch_bounds__(QTH) gdn_rec_quad2c_kernel(float* __restrict__ state, const float* __restrict__ h,+ const float* __restrict__ gate, const float* __restrict__ beta,+ float* __restrict__ oc_out, int64_t T) {+ __shared__ __align__(16) float sqk[2][HT][2][4 * QRS];+ __shared__ float sgb[2][2][HT];+ __shared__ float sv[2][HT][C2CB];+ const int head = blockIdx.x / (S / C2CB), cb = blockIdx.x % (S / C2CB);+ const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;+ const int g = lane >> 3, cl0 = wave * 16 + (lane & 7), cl1 = cl0 + 8; // the lane's two columns in the block+ const int col0 = cb * C2CB + cl0, col1 = cb * C2CB + cl1;+ const int qh = head % HK;+ float s0[32], s1[32];+ {+ const float* sb = state + (size_t) head * S;+ const uint32_t voff = (uint32_t) ((g * 32) * HV * S);+#pragma unroll+ for (int r = 0; r < 32; ++r) { s0[r] = sb[(size_t) r * HV * S + voff + col0]; s1[r] = sb[(size_t) r * HV * S + voff + col1]; }+ }+ float4 pf[C2PF];+ float pv[2][HT], pgb = 0.0f;+ auto fetch = [&](int64_t c) {+ const int64_t t0 = c * HT;+#pragma unroll+ for (int u = 0; u < C2PF; ++u) {+ const int i = tid + u * QTH;+ const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);+ const int64_t t = t0 + tt;+ pf[u] = t < T ? *reinterpret_cast<const float4*>(h + t * C + part * HK * S + qh * S + r4 * 4)+ : make_float4(0.f, 0.f, 0.f, 0.f);+ }+ if (g == 0) {+#pragma unroll+ for (int tt = 0; tt < HT; ++tt) {+ const int64_t t = t0 + tt;+ pv[0][tt] = t < T ? h[t * C + 2 * HK * S + head * S + col0] : 0.0f;+ pv[1][tt] = t < T ? h[t * C + 2 * HK * S + head * S + col1] : 0.0f;+ }+ }+ if (tid < 2 * HT) {+ const int64_t t = t0 + (tid % HT);+ pgb = t < T ? (tid < HT ? gate : beta)[t * HV + head] : 0.0f;+ }+ };+ const float rs_s = rsqrtf((float) S);+ const int src0 = lane & 7;+ const int64_t nch = (T + HT - 1) / HT;+ if (nch > 0) fetch(0);+ for (int64_t c = 0; c < nch; ++c) {+ const int b = (int) (c & 1);+ if (g == 0) {+#pragma unroll+ for (int tt = 0; tt < HT; ++tt) { sv[b][tt][cl0] = pv[0][tt]; sv[b][tt][cl1] = pv[1][tt]; }+ }+#pragma unroll+ for (int u = 0; u < C2PF; ++u) {+ const int i = tid + u * QTH;+ const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);+ const int row = r4 * 4;+ *reinterpret_cast<float4*>(&sqk[b][tt][part][(row >> 5) * QRS + (row & 31)]) = pf[u];+ }+ if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb;+ __syncthreads();+ if (c + 1 < nch) fetch(c + 1);+ const int64_t t0 = c * HT;+ const int nt = (int) (T - t0 < HT ? T - t0 : HT);+ for (int tt = 0; tt < nt; ++tt) {+ float k[32], q[32];+ {+ const float4* k4 = reinterpret_cast<const float4*>(&sqk[b][tt][1][g * QRS]);+ const float4* q4 = reinterpret_cast<const float4*>(&sqk[b][tt][0][g * QRS]);+#pragma unroll+ for (int j = 0; j < 8; ++j) {+ const float4 kk = k4[j], qq = q4[j];+ k[4 * j] = kk.x; k[4 * j + 1] = kk.y; k[4 * j + 2] = kk.z; k[4 * j + 3] = kk.w;+ q[4 * j] = qq.x; q[4 * j + 1] = qq.y; q[4 * j + 2] = qq.z; q[4 * j + 3] = qq.w;+ }+ }+ const float g_exp = __expf(sgb[b][0][tt]);+ float kv0 = 0.0f, kv1 = 0.0f;+#pragma unroll+ for (int r = 0; r < 32; ++r) { kv0 = fmaf(s0[r], k[r], kv0); kv1 = fmaf(s1[r], k[r], kv1); }+ const float a0 = __shfl_sync(0xffffffffu, kv0, src0), a1 = __shfl_sync(0xffffffffu, kv0, src0 + 8),+ a2 = __shfl_sync(0xffffffffu, kv0, src0 + 16), a3 = __shfl_sync(0xffffffffu, kv0, src0 + 24);+ const float b0 = __shfl_sync(0xffffffffu, kv1, src0), b1 = __shfl_sync(0xffffffffu, kv1, src0 + 8),+ b2 = __shfl_sync(0xffffffffu, kv1, src0 + 16), b3 = __shfl_sync(0xffffffffu, kv1, src0 + 24);+ const float kvc0 = a0 + a1 + a2 + a3, kvc1 = b0 + b1 + b2 + b3;+ const float cbt = sgb[b][1][tt];+ const float d0 = (sv[b][tt][cl0] - g_exp * kvc0) * cbt, d1 = (sv[b][tt][cl1] - g_exp * kvc1) * cbt;+ float o0 = 0.0f, o1 = 0.0f;+#pragma unroll+ for (int r = 0; r < 32; ++r) {+ s0[r] = fmaf(g_exp, s0[r], k[r] * d0);+ s1[r] = fmaf(g_exp, s1[r], k[r] * d1);+ o0 = fmaf(s0[r], q[r], o0);+ o1 = fmaf(s1[r], q[r], o1);+ }+ const float x0 = __shfl_sync(0xffffffffu, o0, src0), x1 = __shfl_sync(0xffffffffu, o0, src0 + 8),+ x2 = __shfl_sync(0xffffffffu, o0, src0 + 16), x3 = __shfl_sync(0xffffffffu, o0, src0 + 24);+ const float y0 = __shfl_sync(0xffffffffu, o1, src0), y1 = __shfl_sync(0xffffffffu, o1, src0 + 8),+ y2 = __shfl_sync(0xffffffffu, o1, src0 + 16), y3 = __shfl_sync(0xffffffffu, o1, src0 + 24);+ if (g == 0) {+ oc_out[(t0 + tt) * HV * S + head * S + col0] = (x0 + x1 + x2 + x3) * rs_s;+ oc_out[(t0 + tt) * HV * S + head * S + col1] = (y0 + y1 + y2 + y3) * rs_s;+ }+ }+ }+ {+ float* sb = state + (size_t) head * S;+ uint32_t voff = (uint32_t) ((g * 32) * HV * S);+ asm volatile("" : "+v"(voff));+#pragma unroll+ for (int r = 0; r < 32; ++r) { sb[(size_t) r * HV * S + voff + col0] = s0[r]; sb[(size_t) r * HV * S + voff + col1] = s1[r]; }+ }+}++// gdn_out_norm_kernel's body over a grid-stride walk of the (token, head) rows: the old kernel launched a 128-thread+// block per row (T * 48 blocks; ~45 GB/s on the 8060S). The same code per row (the same compiled arithmetic: a wave+// per row with four values per lane rounded differently in its first xor step).+template <bool WY>+__global__ void __launch_bounds__(S) gdn_out_norm_loop_kernel(const float* __restrict__ z, const float* __restrict__ gamma,+ float eps, float* __restrict__ y, uint16_t* __restrict__ y16,+ int64_t rows, int64_t ld16) {+ __shared__ float wsum[4];+ const int col = threadIdx.x;+ for (int64_t row = blockIdx.x; row < rows; row += gridDim.x) {+ const size_t at = (size_t) row * S + col;+ const float oc = y[at];+ // (warp_sum as the compiler built it: the first xor step adds the partner's rounded square to an unrounded own+ // one, an fma; spelled out so neither instance's contraction can differ)+ float sp = __fmaf_rn(oc, oc, __shfl_xor_sync(0xffffffffu, __fmul_rn(oc, oc), 16));+#pragma unroll+ for (int o = 8; o > 0; o >>= 1) sp = __fadd_rn(sp, __shfl_xor_sync(0xffffffffu, sp, o));+ __syncthreads(); // the previous row's sums are read+ if ((col & 31) == 0) wsum[col >> 5] = sp;+ __syncthreads();+ const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];+ const float bp = oc * rsqrtf(ss / (float) S + eps) * gamma[col], sg = sigm(z[at]);+ const size_t o16 = (size_t) (row / HV) * ld16 + (size_t) (row % HV) * S + col;+ if constexpr (WY) {+ const float v = bp * sg;+ y[at] = v;+ y16[o16] = hf(v);+ } else {+ // STRATA_GDN_NOY=1: nothing reads the FP32 result (403 MB per 16K chunk). The FP16 value is what the+ // compiler makes of hf(v) next to the store: v_fma_mixlo_f16, the product rounded to FP16 once+ unsigned r;+ asm("v_fma_mixlo_f16 %0, %1, %2, 0" : "=v"(r) : "v"(sg), "v"(bp));+ y16[o16] = (uint16_t) r;+ }+ }+}+#endif // __HIPCC____dpct_inline__ void gdn_out_norm_kernel(const float *__restrict__ z,const float *__restrict__ gamma,- float eps, const float *__restrict__ y,- uint16_t *__restrict__ y16) {+ float eps, float *__restrict__ y,+ uint16_t *__restrict__ y16,+ int64_t ld16) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();auto &wsum = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[4]>(sycl::ext::oneapi::this_work_item::get_work_group<3>());@@ -1025,7 +1658,7 @@ auto &wsum = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[4]>(const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];const float v = oc * sycl::rsqrt(ss / (float)S + eps) * gamma[col] *sigm(z[t * HV * S + head * S + col]);- y16[at] = hf(v);+ y16[(size_t) t * ld16 + (size_t) head * S + col] = hf(v); // (the FP32 normalized value is not stored: nothing reads it)}// ---------------------------------------------------------------- MoE@@ -1195,6 +1828,46 @@ __dpct_inline__ void moe_combine_kernel(const float *__restrict__ Dm,bo[i] = s + shared[i] * sigm(sg[t]);}+// W (X5): four columns per thread, one float4 load per slot; the per-element expression and the k order are unchanged+// (bitwise equal to moe_combine_kernel). Needs 16-byte aligned Dm / shared / bo (N * 4 bytes per row is a multiple of 16).+/*+DPCT1110: The total declared local variable size in device function+moe_combine4_kernel exceeds 128 bytes and may cause high register pressure.+Consult with your hardware vendor to find the total register size available and+adjust the code, or use smaller sub-group size to avoid high register pressure.+*/+__dpct_inline__ void moe_combine4_kernel(+ const float *__restrict__ Dm, const int32_t *__restrict__ slot,+ const float *__restrict__ w, const sycl::float4 *__restrict__ shared,+ const float *__restrict__ sg, sycl::float4 *__restrict__ bo, int64_t T) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int64_t i =+ (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) ++ item_ct1.get_local_id(2); // float4 index+ if (i >= T * (N / 4)) return;+ const int64_t t = i / (N / 4), d = (i % (N / 4)) * 4;+ sycl::float4 s = sycl::float4(0.0f, 0.0f, 0.0f, 0.0f);+ sycl::float4 v[10];+ float ww[10];+#pragma unroll+ for (int k = 0; k < 10; ++k) {+ ww[k] = w[t * 10 + k];+ v[k] = *reinterpret_cast<const sycl::float4 *>(+ Dm + (int64_t)slot[t * 10 + k] * N + d);+ }+#pragma unroll+ for (int k = 0; k < 10; ++k) {+ s.x() = sycl::fma(ww[k], v[k].x(), s.x());+ s.y() = sycl::fma(ww[k], v[k].y(), s.y());+ s.z() = sycl::fma(ww[k], v[k].z(), s.z());+ s.w() = sycl::fma(ww[k], v[k].w(), s.w());+ }+ const float g = sigm(sg[t]);+ const sycl::float4 sh = shared[i];+ bo[i] = sycl::float4(s.x() + sh.x() * g, s.y() + sh.y() * g,+ s.z() + sh.z() * g, s.w() + sh.w() * g);+}+// ---------------------------------------------------------------- QSA helpers__dpct_inline__ void rms_rows_kernel(float *__restrict__ x,const float *__restrict__ w, int64_t cols,@@ -1257,14 +1930,15 @@ __dpct_inline__ void split_q_kernel(const float *__restrict__ qf,}__dpct_inline__ void gate_attn_kernel(const float *__restrict__ a,const float *__restrict__ qf,- uint16_t *__restrict__ o16, int64_t T) {+ uint16_t *__restrict__ o16, int64_t T,+ int64_t ld16) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();const int64_t i =(int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +item_ct1.get_local_id(2);if (i >= T * 24 * 256) return;const int64_t t = i / (24 * 256), h = (i / 256) % 24, d = i % 256;- o16[i] =+ o16[t * ld16 + h * 256 + d] =hf(a[i] * (1.0f / (1.0f + sycl::native::exp(-qf[t * 24 * 512 + h * 512 + 256 + d]))));}@@ -1377,12 +2051,83 @@ __dpct_inline__ void to_bf16_kernel(const float *__restrict__ x,item_ct1.get_local_id(2);i < n; i += (int64_t)item_ct1.get_group_range(2) *item_ct1.get_local_range(2)) {- const uint16_t h = bf(x[i]);+ const uint16_t h = act16(x[i]);y[i] = h;if (ylo) ylo[i] = bf_lo(x[i], h);}}+// S23 (opt-in STRATA_HC_UPMIX=1, gfx11): the hyper-connection read's up projection with gr_mix_r as its epilogue. The+// up GEMM's FP32 output `gated` (T x 10240: 671 MB per 16K chunk) is never written or read back: a block computes a+// tile of 64 tokens x 64 columns for all 4 streams on the matrix cores (BF16 in, FP32 accumulate over K = 320; the+// lo16 and w_up tiles staged in LDS), and each lane already holds the 4 streams' values of its (token, column) - the+// mix (x_c = R * rs * w, sum of x_c * sigmoid(gated_c), / 4) runs in registers, in gr_mix_r_kernel's order. The+// GEMM sums K in another order than hipBLASLt: rounding-level, hence opt-in and quality-gated.+#if defined(__HIPCC__)+typedef __bf16 um_b16 __attribute__((ext_vector_type(16)));+typedef float um_f8 __attribute__((ext_vector_type(8)));+__device__ __forceinline__ um_f8 um_wmma(um_b16 a, um_b16 b, um_f8 c) {+#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__)+ return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c);+#else+ (void) a; (void) b; return c; // not a gfx11 device pass: never launched (runtime gate)+#endif+}+constexpr int UM_T = 128, UM_D = 16, UM_LD = LR + 8; // a block: 128 tokens x 16 columns x the 4 streams+__device__ __forceinline__ um_b16 um_frag(const uint16_t* p) { // 16 BF16 (32 bytes, 16-byte aligned)+ const uint4 a = *reinterpret_cast<const uint4*>(p), b = *reinterpret_cast<const uint4*>(p + 8);+ const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w};+ return __builtin_bit_cast(um_b16, w);+}+// The block's w_up rows (16 columns x 4 streams x all 320 k) are staged in LDS once; each wave streams its own 16+// tokens' lo16 rows from global memory (every A fragment feeds the 4 streams' WMMAs) - one barrier per block.+__global__ void __launch_bounds__(256) gr_upmix_kernel(const uint16_t* __restrict__ lo16, const uint16_t* __restrict__ wu,+ const float* __restrict__ R, const float* __restrict__ rs,+ const float* __restrict__ w, float* __restrict__ mixed,+ uint16_t* __restrict__ mixed16, uint16_t* __restrict__ mixed_h,+ int64_t T) {+ __shared__ __align__(16) uint16_t sB[HC * UM_D][UM_LD];+ const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, l16 = lane & 15, hi = lane >> 4;+ // blocks ordered column-tile fastest: the blocks in flight share a token tile, so the epilogue's R reads run+ // along rows (token-tile fastest scattered them over 512 rows x 40 KB per block: 28 ms instead of 3.7 at 8K)+ const int64_t t0 = (int64_t) blockIdx.y * UM_T + 16 * wave;+ const int d0 = blockIdx.x * UM_D;+ for (int i = tid; i < HC * UM_D * (LR / 8); i += 256) {+ const int rr = i / (LR / 8), q = i % (LR / 8);+ const int c = rr / UM_D, dd = rr % UM_D;+ *reinterpret_cast<uint4*>(&sB[rr][8 * q]) = *reinterpret_cast<const uint4*>(wu + (size_t) (c * N + d0 + dd) * LR + 8 * q);+ }+ __syncthreads();+ if (t0 >= T) return;+ const int64_t ta = t0 + l16 < T ? t0 + l16 : T - 1;+ const uint16_t* arow = lo16 + ta * LR;+ um_f8 acc[HC];+#pragma unroll+ for (int c = 0; c < HC; ++c) acc[c] = um_f8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};+#pragma unroll+ for (int ks = 0; ks < LR; ks += 16) {+ const um_b16 a = um_frag(arow + ks);+#pragma unroll+ for (int c = 0; c < HC; ++c) acc[c] = um_wmma(a, um_frag(&sB[c * UM_D + l16][ks]), acc[c]);+ }+ const int d = d0 + l16;+#pragma unroll+ for (int i = 0; i < 8; ++i) {+ const int64_t t = t0 + 2 * i + hi;+ if (t >= T) continue;+ float s = 0.0f;+#pragma unroll+ for (int c = 0; c < HC; ++c) {+ const float x = R[t * D + c * N + d] * rs[t * HC + c] * w[c * N + d]; // gr_mix_r_kernel's order+ s = fmaf(x, sigm(acc[c][i]), s);+ }+ s /= (float) HC;+ mixed[t * N + d] = s;+ if (mixed16) mixed16[t * N + d] = act16(s);+ if (mixed_h) mixed_h[t * N + d] = hf(s);+ }+}+#endif} // namespacevoid kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const int32_t* page_table, int64_t page_size,@@ -1420,6 +2165,18 @@ void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const in}check("kv_append");}+void set_act_f16(bool on) {+#if !defined(__HIPCC__)+ (void) on; // CUDA: the activation image is always BF16+ return;+#else+ const int v = on ? 1 : 0;+ if (cudaMemcpyToSymbol(g_act_f16, &v, sizeof v) != cudaSuccess) {+ std::fprintf(stderr, "prefill: setting the FP16 activation image failed: %s\n", cudaGetErrorString(cudaGetLastError()));+ std::exit(1);+ }+#endif+}void to_f16(const float* x, uint16_t* y, int64_t n, void* stream) {if (n <= 0) return;{@@ -1501,21 +2258,27 @@ void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_tcheck("gr_norm");}void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream,- uint16_t* xn16_lo) {+ uint16_t* xn16_lo, int64_t ldx) {{auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class gr_norm_rs_kernel_6c01ba>>(- sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(T * HC)) *- sycl::range(1, 1, 256),- sycl::range(1, 1, 256)),- exp_props,- [=](sycl::nd_item<3> item_ct1)- [[sycl::reqd_sub_group_size(32)]] {- gr_norm_rs_kernel(R, w_norm, eps, rs, xn16, xn16_lo);- });+ ->submit([&](sycl::handler &cgh) {+ auto ldx_ldx_D_ct6 = ldx > 0 ? ldx : D;++ cgh.parallel_for<+ dpct_kernel_name<class gr_norm_rs_kernel_6c01ba>>(+ sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(T * HC)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ gr_norm_rs_kernel(R, w_norm, eps, rs, xn16, xn16_lo,+ ldx_ldx_D_ct6);+ });+ });}check("gr_norm_rs");}@@ -1537,27 +2300,80 @@ void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float*}check("gr_mix_r");}+bool gr_upmix(const uint16_t* lo16, const uint16_t* w_up, const float* R, const float* rs, const float* w_norm,+ float* mixed, uint16_t* mixed16, uint16_t* mixed_h, int64_t T, void* stream) {+#if defined(__HIPCC__)+ static const bool gfx11 = [] {+ int dev = 0;+ cudaDeviceProp p;+ if (cudaGetDevice(&dev) != cudaSuccess || cudaGetDeviceProperties(&p, dev) != cudaSuccess) return false;+ return strata::kernels::gfx_arch_is_gfx11_wmma(p.gcnArchName);+ }();+ if (!gfx11 || T <= 0) return false;+ gr_upmix_kernel<<<dim3(N / UM_D, (unsigned) ((T + UM_T - 1) / UM_T)), 256, 0, (cudaStream_t) stream>>>(+ lo16, w_up, R, rs, w_norm, mixed, mixed16, mixed_h, T);+ check("gr_upmix");+ return true;+#else+ (void) lo16; (void) w_up; (void) R; (void) rs; (void) w_norm; (void) mixed; (void) mixed16; (void) mixed_h;+ (void) T; (void) stream;+ return false;+#endif+}void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps,- float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo) {+ float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo, int64_t ldx) {{auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<- dpct_kernel_name<class gr_write_norm_rs_kernel_85f8e9>>(- sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(T * HC)) *- sycl::range(1, 1, 256),- sycl::range(1, 1, 256)),- exp_props,- [=](sycl::nd_item<3> item_ct1)- [[sycl::reqd_sub_group_size(32)]] {- gr_write_norm_rs_kernel(R, bo, inj, inj_ld, w_norm_next,- eps, rs, xn16, xn16_lo);- });+ ->submit([&](sycl::handler &cgh) {+ auto ldx_ldx_D_ct9 = ldx > 0 ? ldx : D;++ cgh.parallel_for<+ dpct_kernel_name<class gr_write_norm_rs_kernel_85f8e9>>(+ sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(T * HC)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ gr_write_norm_rs_kernel(R, bo, inj, inj_ld,+ w_norm_next, eps, rs, xn16,+ xn16_lo, ldx_ldx_D_ct9);+ });+ });}check("gr_write_norm_rs");}+void gr_write_cvec_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* v_l,+ const float* s_l, const int* on, int mode, const float* w_norm_next, float eps, float* rs,+ uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo, int64_t ldx) {+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->submit([&](sycl::handler &cgh) {+ auto ldx_ldx_D_ct13 = ldx > 0 ? ldx : D;++ cgh.parallel_for<dpct_kernel_name<+ class gr_write_cvec_norm_rs_kernel_abf888>>(+ sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(T * HC)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ gr_write_cvec_norm_rs_kernel(+ R, bo, inj, inj_ld, v_l, s_l, on, mode,+ w_norm_next, eps, rs, xn16, xn16_lo,+ ldx_ldx_D_ct13);+ });+ });+ }+ check("gr_write_cvec_norm_rs");+}void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo) {{auto exp_props = sycl::ext::oneapi::experimental::properties{@@ -1659,6 +2475,45 @@ void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, igdn_conv_kernel(history, qkv, conv_w, h, T);});} else {+ static const bool fused = [] { const char* v = std::getenv("STRATA_GDN_CONVL2"); return v && std::atoi(v) != 0; }();+ if (fused) {+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<+ dpct_kernel_name<class gdn_conv_l2_kernel_8e7204>>(+ sycl::nd_range<3>(+ sycl::range(+ 1, (unsigned)((T + CONV_TILE - 1) / CONV_TILE),+ C / 128) *+ sycl::range(1, 1, 128),+ sycl::range(1, 1, 128)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ gdn_conv_l2_kernel(history, qkv, conv_w, h, T,+ eps);+ });+ }+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<+ dpct_kernel_name<class gdn_conv_hist_kernel_e391a1>>(+ sycl::nd_range<3>(sycl::range(1, 1, C / 128) *+ sycl::range(1, 1, 128),+ sycl::range(1, 1, 128)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ gdn_conv_hist_kernel(history, qkv, T);+ });+ }+ check("gdn_conv");+ return;+ }{auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};@@ -1682,7 +2537,7 @@ void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, istrata::q_of(stream)->parallel_for<- dpct_kernel_name<class gdn_conv_hist_kernel_e391a1>>(+ dpct_kernel_name<class gdn_conv_hist_kernel_e391a2>>(sycl::nd_range<3>(sycl::range(1, 1, C / 128) *sycl::range(1, 1, 128),sycl::range(1, 1, 128)),@@ -1708,10 +2563,55 @@ void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, i}check("gdn_conv");}-void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z,- const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream) {+void gdn_recurrence_variant(int variant, float* state, const float* h, const float* gate, const float* beta,+ const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T,+ void* stream, int64_t ld16) {+ if (ld16 <= 0) ld16 = (int64_t) HV * S;+#if defined(__HIPCC__)+ if (variant == 3) { // diagnostics: the quad recurrence + the old norm kernel+ if (T > 0) {+ gdn_rec_quad_kernel<<<HV * (S / QCB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);+ gdn_out_norm_kernel<<<dim3((unsigned) T, HV), S, 0, (cudaStream_t) stream>>>(z, gamma, eps, y, y16, ld16);+ }+ return;+ }+ if (variant == 4 || variant == 5) { // diagnostics: the quad recurrence's PP / two-column kernels + the norm+ if (T > 0) {+ if (variant == 5)+ gdn_rec_quad2c_kernel<<<HV * (S / C2CB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);+ else+ gdn_rec_quad_pp_kernel<<<HV * (S / QCB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);+ gdn_out_norm_loop_kernel<true><<<(unsigned) std::min<int64_t>(T * HV, 4096), S, 0, (cudaStream_t) stream>>>(+ z, gamma, eps, y, y16, T * HV, ld16);+ }+ check("gdn_recurrence (quad pp)");+ return;+ }+ if (variant == 1) {+ if (T > 0) {+ static const int pp = [] { const char* v = std::getenv("STRATA_GDN_PP"); return v ? std::atoi(v) : 0; }();+ if (pp == 2)+ gdn_rec_quad2c_kernel<<<HV * (S / C2CB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);+ else if (pp)+ gdn_rec_quad_pp_kernel<<<HV * (S / QCB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);+ else+ gdn_rec_quad_kernel<<<HV * (S / QCB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);+ static const bool noy = [] { const char* v = std::getenv("STRATA_GDN_NOY"); return v && std::atoi(v) != 0; }();+ if (noy)+ gdn_out_norm_loop_kernel<false><<<(unsigned) std::min<int64_t>(T * HV, 4096), S, 0, (cudaStream_t) stream>>>(+ z, gamma, eps, y, y16, T * HV, ld16);+ else+ gdn_out_norm_loop_kernel<true><<<(unsigned) std::min<int64_t>(T * HV, 4096), S, 0, (cudaStream_t) stream>>>(+ z, gamma, eps, y, y16, T * HV, ld16);+ }+ check("gdn_recurrence (quad)");+ return;+ }+#else+ (void) variant; // the quad recurrence kernels are AMD-only+#endifstatic const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr; // the one-block-per-head kernel (A/B)- if (serial || T <= 0) {+ if (serial || T <= 0 || variant == 2) {/*DPCT1049: The work-group size passed to the SYCL kernel may exceedthe limit. To get the device limit, query@@ -1728,7 +2628,7 @@ void gdn_recurrence(float* state, const float* h, const float* gate, const float[=](sycl::nd_item<3> item_ct1)[[sycl::reqd_sub_group_size(32)]] {gdn_rec_kernel(state, h, gate, beta, z, gamma, eps, y,- y16, T);+ y16, T, ld16);});} else {static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }();@@ -1790,12 +2690,21 @@ void gdn_recurrence(float* state, const float* h, const float* gate, const floatexp_props,[=](sycl::nd_item<3> item_ct1)[[sycl::reqd_sub_group_size(32)]] {- gdn_out_norm_kernel(z, gamma, eps, y, y16);+ gdn_out_norm_kernel(z, gamma, eps, y, y16, ld16);});}}check("gdn_recurrence");}+void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z,+ const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream, int64_t ld16) {+ // Aurora (S23): four lanes per column + the grid-stride norm, the same bits (tests/hip/gdn_rec_head.cpp);+ // STRATA_GDN_HEAD=1 (on by default on gfx1151; off with STRATA_GDN_HEAD=0 or STRATA_GDN_REC_HEADS) takes them+ // (AMD builds only; the arch defaults set STRATA_GDN_HEAD=1 on gfx1151 and leave other cards on the earlier kernels)+ static const bool head = [] { const char* v = std::getenv("STRATA_GDN_HEAD"); return v != nullptr && std::atoi(v) != 0; }();+ static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr;+ gdn_recurrence_variant(head && !serial ? 1 : 0, state, h, gate, beta, z, gamma, eps, y, y16, T, stream, ld16);+}void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, void* stream) {if (n_expert == 512){@@ -1803,7 +2712,7 @@ void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_tsycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class route_kernel_4f80f3,+ ->parallel_for<dpct_kernel_name<class route_kernel_ceb296,dpct_kernel_scalar<16>>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)((T + 7) / 8)) *sycl::range(1, 1, 256),@@ -1819,7 +2728,7 @@ void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_tsycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class route_kernel_c02f30,+ ->parallel_for<dpct_kernel_name<class route_kernel_4c3133,dpct_kernel_scalar<8>>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)((T + 7) / 8)) *sycl::range(1, 1, 256),@@ -1839,7 +2748,7 @@ void blob_dequant(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* ssycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class blob_dequant_kernel_50ffea,+ ->parallel_for<dpct_kernel_name<class blob_dequant_kernel_252bb1,dpct_kernel_scalar<false>>>(sycl::nd_range<3>(sycl::range(1, 1, blocks_for(1280LL * 640 + 2560LL * 160)) *@@ -1857,7 +2766,7 @@ void blob_dequant_f16(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, voisycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class blob_dequant_kernel_cd530c,+ ->parallel_for<dpct_kernel_name<class blob_dequant_kernel_1d812a,dpct_kernel_scalar<true>>>(sycl::nd_range<3>(sycl::range(1, 1, blocks_for(1280LL * 640 + 2560LL * 160)) *@@ -1916,6 +2825,40 @@ __dpct_inline__ void copy_i32_kernel(int32_t *__restrict__ dst,dst[i] = src[i];}} // namespace+namespace {+__dpct_inline__ void copy_f4_kernel(sycl::float4 *__restrict__ dst,+ const sycl::float4 *__restrict__ src,+ int64_t n4) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+#pragma unroll+ for (int64_t i =+ (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) ++ item_ct1.get_local_id(2);+ i < n4; i += (int64_t)item_ct1.get_group_range(2) *+ item_ct1.get_local_range(2))+ dst[i] = src[i];+}+} // namespace+void copy_f32_wide(float* dst, const float* src, int64_t n, void* stream) {+ if (n <= 0) return;+ const int64_t n4 = n / 4, b = std::min<int64_t>((n4 + 255) / 256, 4096);+ if (n4 > 0) {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<dpct_kernel_name<class copy_f4_kernel_bb4110>>(+ sycl::nd_range<3>(sycl::range(1, 1, (unsigned)b) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ copy_f4_kernel((sycl::float4 *)dst,+ (const sycl::float4 *)src, n4);+ });+ }+ if (n % 4) copy_i32((int32_t*) dst + n4 * 4, (const int32_t*) src + n4 * 4, n % 4, stream);+ check("copy_f32_wide");+}void copy_i32(int32_t* dst, const int32_t* src, int64_t n, void* stream) {if (n <= 0) return;const int64_t b = (n + 255) / 256;@@ -1955,6 +2898,30 @@ void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, int}void moe_combine(const float* Dm, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo,int64_t T, void* stream) {+#ifndef STRATA_W_NO_COMB+ if (((reinterpret_cast<uintptr_t>(Dm) | reinterpret_cast<uintptr_t>(shared) | reinterpret_cast<uintptr_t>(bo)) & 15) == 0) {+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<+ dpct_kernel_name<class moe_combine4_kernel_1c986f>>(+ sycl::nd_range<3>(+ sycl::range(1, 1, blocks_for(T * (N / 4))) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ moe_combine4_kernel(+ Dm, slot, w,+ reinterpret_cast<const sycl::float4 *>(shared), sg,+ reinterpret_cast<sycl::float4 *>(bo), T);+ });+ }+ check("moe_combine");+ return;+ }+#endif{auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};@@ -2062,19 +3029,25 @@ void split_q(const float* q_full, float* q, int64_t T, void* stream) {}check("split_q");}-void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream) {+void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream, int64_t ld16) {{auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class gate_attn_kernel_3fc329>>(- sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * 24 * 256)) *- sycl::range(1, 1, 256),- sycl::range(1, 1, 256)),- exp_props, [=](sycl::nd_item<3> item_ct1) {- gate_attn_kernel(attn, q_full, out16, T);- });+ ->submit([&](sycl::handler &cgh) {+ auto ld16_ld16_ct4 = ld16 > 0 ? ld16 : 24 * 256;++ cgh.parallel_for<+ dpct_kernel_name<class gate_attn_kernel_3fc329>>(+ sycl::nd_range<3>(+ sycl::range(1, 1, blocks_for(T * 24 * 256)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ gate_attn_kernel(attn, q_full, out16, T, ld16_ld16_ct4);+ });+ });}check("gate_attn");}diff --git a/sycl/src/prefill/moe_fused.dp.cpp b/sycl/src/prefill/moe_fused.dp.cppnew file mode 100644index 000000000..1e05329a2--- /dev/null+++ b/sycl/src/prefill/moe_fused.dp.cpp@@ -0,0 +1,1162 @@+// src/prefill/moe_fused.cu - see include/strata/prefill/moe_fused.hpp (#136: the Q2_0 pack's prompt experts on+// Strata's own int8 tensor-core kernels, with the grouping on the GPU).+//+// The arithmetic. A Q2_0 block is 64 weights w = d_w * (q - 1), q in 0..3, four codes per byte, weight j of a block+// in byte j / 4 at bits 2 * (j % 4). An activation block of 32 values is x = d_x * a with a = round(x / d_x) in+// -127..127. Over one 32-value half-block+// sum w x = d_w * d_x * (sum q a - sum a),+// so the int8 product takes the codes as they are (0..3 is a valid s8) and the offset is the activations' own sum,+// stored with the block. The dot product (|sum q a| <= 32 * 3 * 127 < 2^22) becomes a float exactly with one+// integer add: as_float(0x4B400000 + dot) = 1.5 * 2^23 + dot, and the block stores c = -(1.5 * 2^23 + sum a), so+// as_float(0x4B400000 + dot) + c = dot - sum a with no rounding. Per output and 64-block that is+// acc += d_w * (d_x0 * t0 + d_x1 * t1) (t = dot - sum a of each half)+// - two integer adds, two float adds and three multiply-adds.+//+// The K order. mma.sync m16n8k32 takes four consecutive k of a row (A) or column (B) per register. Four consecutive+// weights are one code byte; four codes of one register instead come from the same 2-bit field of four consecutive+// bytes - (word >> 2t) & 0x03030303 holds weights t, t+4, t+8, t+12 of a 16-weight word. So the kernels use that order+// for the k of a half-block: mma k index 16h + 4t + j stands for weight (and activation) 16h + t + 4j. The+// activations are stored in it (perm32), and a lane's two B registers (h = 0 and 1) are adjacent: one 8-byte load.+#define DPCT_PROFILING_ENABLED+#include <sycl/sycl.hpp>+#include <dpct/dpct.hpp>+#include "strata/sycl_queue.hpp"+#include "strata/prefill/moe_fused.hpp"++#include <algorithm>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <mutex>+#include <cmath>++namespace strata::prefill::fused {+namespace {++void ck(dpct::err0 e, const char *what) {+}++constexpr int AB = 80; // activation bytes per 64 values: 64 codes, then {d0, c0, d1, c1}+constexpr int MAGIC = 0x4B400000; // the bits of 1.5 * 2^23+constexpr float MAGICF = 12582912.0f;+// The Strata Q2_0 blob (moe_mmq.cu strata_q2_kernel, kernels.cu blob_dequant_kernel): gate/up codes [1280][640 B]+// (rows interleaved: gate of feature f at row 2f, its up at 2f + 1), down codes [2560][160 B], gate/up scales+// [1280][40] fp16, down scales [2560][10] fp16.+constexpr size_t O_GU_CODES = 0, O_D_CODES = (size_t) 1280 * 640, O_GU_SC = O_D_CODES + (size_t) 2560 * 160,+ O_D_SC = O_GU_SC + (size_t) 1280 * 40 * 2;+constexpr int THREADS = 512; // 16 warps: 4 along the weight rows (64 each) x 4 along the tile rows (16 each)+constexpr int WROWS = 256; // weight rows per work item: 128 features of gate/up, or 256 outputs of down+constexpr int STAGES = 4; // cp.async pipeline depth, one 64-weight block of K per stage+constexpr int STAGE_BYTES = WROWS * 16 + kTileRows * AB;+constexpr size_t smem_bytes(bool gu) {+ return (size_t) WROWS * (gu ? 40 : 10) * 2 + STAGES * STAGE_BYTES + kTileRows * 4;+}++// the stored position of value k of a 32-value half-block (see "The K order")+__dpct_inline__ int perm32(int k) {+ return 8 * (k & 3) + 4 * (k >> 4) + ((k & 15) >> 2);+}+// where value k of a 32-value half-block is stored: perm32 for the CUDA kernel; on HIP the gfx11 WMMA kernel's order+// (value 4b + t of a 16-value word at 4t + b: see expert_w11_kernel)+__dpct_inline__ int act_pos(int k) {+#if defined(__HIPCC__)+ return (k & 16) | ((k & 3) << 2) | ((k >> 2) & 3);+#else+ return perm32(k);+#endif+}++struct Tables {+ int32_t *cnt, *off, *fill, *ts; // per expert: rows, first row (E + 1), placement cursor, first tile (E + 1)+ sycl::int2 *tiles; // {expert, first row}, in expert order+};+size_t tiles_at(int n_expert) { return ((size_t) (4 * n_expert + 2) * 4 + 15) / 16 * 16; }+Tables tables(void* scratch, int n_expert) {+ int32_t* p = (int32_t*) scratch;+ return {p, p + n_expert, p + 2 * n_expert + 1, p + 3 * n_expert + 1,+ (sycl::int2 *)((uint8_t *)scratch + tiles_at(n_expert))};+}++// ---- activations: one warp per 64 values+__dpct_inline__ void quant_act_kernel(const float *__restrict__ x, int64_t nblk,+ uint8_t *__restrict__ xa) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int64_t w =+ (int64_t)item_ct1.get_group(2) * (item_ct1.get_local_range(2) / 32) ++ item_ct1.get_local_id(2) / 32;+ const int lane = item_ct1.get_local_id(2) & 31;+ if (w >= nblk) return;+ const float v0 = x[w * 64 + lane], v1 = x[w * 64 + 32 + lane];+ float a0 = sycl::fabs(v0), a1 = sycl::fabs(v1);+#pragma unroll+ for (int o = 16; o > 0; o >>= 1) {+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ a0 = sycl::fmax(+ a0, dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu,+ sycl::ext::oneapi::this_work_item::get_sub_group(), a0, o));+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ a1 = sycl::fmax(+ a1, dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu,+ sycl::ext::oneapi::this_work_item::get_sub_group(), a1, o));+ }+ const int q0 = a0 > 0.0f ? sycl::vec<float, 1>{(v0 * (127.0f / a0))}+ .convert<int, sycl::rounding_mode::rte>()[0]+ : 0;+ const int q1 = a1 > 0.0f ? sycl::vec<float, 1>{(v1 * (127.0f / a1))}+ .convert<int, sycl::rounding_mode::rte>()[0]+ : 0;+ int s0 = q0, s1 = q1;+#pragma unroll+ for (int o = 16; o > 0; o >>= 1) {+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ s0 += dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), s0,+ o);+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ s1 += dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), s1,+ o);+ }+ uint8_t* out = xa + w * AB;+ out[act_pos(lane)] = (uint8_t) (int8_t) q0;+ out[32 + act_pos(lane)] = (uint8_t) (int8_t) q1;+ if (lane == 0)+ *(sycl::float4 *)(out + 64) =+ sycl::float4(a0 / 127.0f, -(MAGICF + (float)s0), a1 / 127.0f,+ -(MAGICF + (float)s1));+}++// ---- grouping: counts, offsets and tiles, placement+__dpct_inline__ void count_kernel(const int32_t *__restrict__ ids, int64_t n,+ int E, int32_t *__restrict__ cnt,+ uint8_t *dpct_local) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ auto hist = (int32_t *)dpct_local;+#pragma unroll+ for (int e = item_ct1.get_local_id(2); e < E;+ e += item_ct1.get_local_range(2)) hist[e] = 0;+ /*+ 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.+ */+ item_ct1.barrier();+ for (int64_t i =+ (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) ++ item_ct1.get_local_id(2);+ i < n; i += (int64_t)item_ct1.get_group_range(2) *+ item_ct1.get_local_range(2)) {+ const int e = ids[i];+ if ((unsigned)e < (unsigned)E)+ dpct::atomic_fetch_add<sycl::access::address_space::generic_space>(+ &hist[e], 1);+ }+ /*+ 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.+ */+ item_ct1.barrier();+#pragma unroll+ for (int e = item_ct1.get_local_id(2); e < E;+ e += item_ct1.get_local_range(2))+ if (hist[e])+ dpct::atomic_fetch_add<sycl::access::address_space::generic_space>(+ &cnt[e], hist[e]);+}++// exclusive prefix sum over the block (blockDim a multiple of 32); *total = the block's sum+inline int block_excl_sum(int v, int *total, int *sh) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int lane = item_ct1.get_local_id(2) & 31,+ w = item_ct1.get_local_id(2) >> 5,+ nw = item_ct1.get_local_range(2) >> 5;+ int x = v;+#pragma unroll+ for (int o = 1; o < 32; o <<= 1) {+ /*+ DPCT1108: '__shfl_up_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ const int y = dpct::experimental::shift_sub_group_right(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), x,+ o);+ if (lane >= o) x += y;+ }+ if (lane == 31) sh[w] = x;+ /*+ 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.+ */+ item_ct1.barrier();+ if (w == 0) {+ int s = lane < nw ? sh[lane] : 0;+#pragma unroll+ for (int o = 1; o < 32; o <<= 1) {+ /*+ DPCT1108: '__shfl_up_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ const int y = dpct::experimental::shift_sub_group_right(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),+ s, o);+ if (lane >= o) s += y;+ }+ sh[lane] = s;+ }+ /*+ 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.+ */+ item_ct1.barrier();+ const int r = x - v + (w > 0 ? sh[w - 1] : 0);+ *total = sh[nw - 1];+ /*+ 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.+ */+ item_ct1.barrier(); // sh is reused by the next call+ return r;+}++// one block, a thread per expert (E <= 1024)+__dpct_inline__ void scan_kernel(Tables tb, int E) {+ auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<int[32]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const int e =+ sycl::ext::oneapi::this_work_item::get_nd_item<3>().get_local_id(2);+ const int c = e < E ? tb.cnt[e] : 0, nt = (c + kTileRows - 1) / kTileRows;+ int rows = 0, tiles = 0;+ const int o = block_excl_sum(c, &rows, sh), to = block_excl_sum(nt, &tiles, sh);+ if (e < E) {+ tb.off[e] = o;+ tb.fill[e] = o;+ tb.ts[e] = to;+#pragma unroll+ for (int i = 0; i < nt; ++i)+ tb.tiles[to + i] = sycl::int2(e, o + i * kTileRows);+ }+ if (e == 0) {+ tb.off[E] = rows;+ tb.ts[E] = tiles;+ }+}++__dpct_inline__ void place_kernel(const int32_t *__restrict__ ids, int64_t n,+ int k, int E, Tables tb,+ int32_t *__restrict__ slot,+ int32_t *__restrict__ src) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int64_t i =+ (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) ++ item_ct1.get_local_id(2);+ if (i >= n) return;+ const int e = ids[i];+ if ((unsigned) e >= (unsigned) E) { slot[i] = 0; return; } // (the router never writes one)+ const int p =+ dpct::atomic_fetch_add<sycl::access::address_space::generic_space>(+ &tb.fill[e], 1);+ slot[i] = p;+ src[p] = (int32_t) (i / k);+}++// ---- the expert products+#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP >= 800+__dpct_inline__ void cp16(void *dst, const void *src) {+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)+ asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(+ (unsigned)__cvta_generic_to_shared(dst)),+ "l"(src));+#else+ *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(dst))) =+ *(((uint32_t *)(uintptr_t)src));+ if (16 > 4)+ *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(dst)) ++ 1) = *(((uint32_t *)(uintptr_t)src) + 1);+ if (16 > 8)+ *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(dst)) ++ 2) = *(((uint32_t *)(uintptr_t)src) + 2);+ if (16 > 12)+ *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(dst)) ++ 3) = *(((uint32_t *)(uintptr_t)src) + 3);+#endif+}+__dpct_inline__ void cp4(void *dst, const void *src) {+ /*+ DPCT1053: Migration of device assembly code is not supported.+ */+ asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"(+ (unsigned)__cvta_generic_to_shared(dst)),+ "l"(src));+}+/*+DPCT1026: The call to "cp.async.commit_group;+" was removed because current "cp.async" is migrated to synchronous copy+operation. You may need to adjust the code to tune the performance.+*/+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)+__device__ __forceinline__ void cp_commit() {+ asm volatile("cp.async.commit_group;\n" ::);+#else+__device__ __forceinline__ void cp_commit() {+#endif }+/*+DPCT1026: The call to "cp.async.wait_group %0;+" was removed because current "cp.async" is migrated to synchronous copy+operation. You may need to adjust the code to tune the performance.+*/+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)+ template <int N> __device__ __forceinline__ void cp_wait() {+ asm volatile("cp.async.wait_group %0;\n" ::"n"(N));+#else+ template <int N> __device__ __forceinline__ void cp_wait() {+#endif }+// d = A (16 x 32 s8, row) * B (32 x 8 s8, col), int32, from zero+__dpct_inline__ void mma_s8(int (&d)[4], const uint32_t (&a)[4], uint32_t b0,+ uint32_t b1) {+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)+ asm("mma.sync.aligned.m16n8k32.row.col.s32.s8.s8.s32 "+ "{%0,%1,%2,%3}, "+ "{%4,%5,%6,%7}, {%8,%9}, {%10,%10,%10,%10};\n"+ : "=r"(d[0]), "=r"(d[1]), "=r"(d[2]), "=r"(d[3])+ : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1),+ "r"(0));+#else+ {+ volatile void *d_mat_frag_ct1[4] = {&d[0], &d[1], &d[2], &d[3]};+ sycl::vec<uint32_t, 4> a_mat_frag_ct1(a[0], a[1], a[2], a[3]);+ sycl::vec<uint32_t, 2> b_mat_frag_ct1(b0, b1);+ sycl::vec<int32_t, 4> c_mat_frag_ct1(0, 0, 0, 0);+ dpct::experimental::matrix::mma<16, 8, 32, int8_t, int32_t>(+ reinterpret_cast<volatile void **>(d_mat_frag_ct1),+ &a_mat_frag_ct1, &b_mat_frag_ct1, &c_mat_frag_ct1);+ }+#endif+}+#endif++// One work item = (tile of up to 64 routed rows of expert e, a block of 256 weight rows); a persistent grid walks+// the batch's items (their count is on the device). GU: gate/up rows of 128 features against the rows' tokens'+// activations (`act` per token, 2560 values), SwiGLU, H to int8 per 32 features into `out` (per row, 640 values).+// !GU: down rows (256 outputs) against H (`act` per row), FP32 into `dm` per row.+// Warp (wf, wt): weight rows 64 wf.. as four m16 tiles (GU: a tile = 8 features, its gate rows as mma rows 0-7 and+// its up rows as 8-15, so a lane holds gate and up of one feature: SwiGLU in registers), tile rows 16 wt.. as two n8.+template <bool GU>+/*+DPCT1110: The total declared local variable size in device function+expert_kernel exceeds 128 bytes and may cause high register pressure. Consult+with your hardware vendor to find the total register size available and adjust+the code, or use smaller sub-group size to avoid high register pressure.+*/+__dpct_inline__ void expert_kernel(+ const Batch b, const Tables tb, const uint8_t *__restrict__ act,+ const int32_t *__restrict__ src, uint8_t *__restrict__ out,+ float *__restrict__ dm, uint8_t *dpct_local) {+#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP >= 800+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ constexpr int NKB = GU ? 40 : 10; // 64-weight blocks along K+ constexpr int NFB = GU ? 5 : 10; // weight-row blocks per tile+ constexpr int CODE_LD = GU ? 640 : 160; // code bytes per weight row+ constexpr size_t O_CODES = GU ? O_GU_CODES : O_D_CODES, O_SC = GU ? O_GU_SC : O_D_SC;+ constexpr int ACT_LD = NKB * AB; // bytes per activation row: 3200 (a token), 800 (a row's H)+ constexpr unsigned M2 = 0x03030303u;+ auto smem = (uint8_t *)dpct_local;+ const sycl::half *wsc =+ (const sycl::half *)smem; // [256][NKB] the work item's weight scales+ uint8_t* stages = smem + WROWS * NKB * 2; // [STAGES] x {codes [256][16], act [64][AB]}+ int* srow = (int*) (stages + STAGES * STAGE_BYTES); // [64] the activation row of each tile row++ const int tid = item_ct1.get_local_id(2), lane = tid & 31, warp = tid >> 5,+ g = lane >> 2, tig = lane & 3;+ const int wf = warp & 3, nb0 = 16 * (warp >> 2);+ int ra[4], rb[4]; // the local weight rows of mma rows g and g + 8+#pragma unroll+ for (int i = 0; i < 4; ++i) {+ if (GU) { ra[i] = 2 * (32 * wf + 8 * i + g); rb[i] = ra[i] + 1; }+ else { ra[i] = 64 * wf + 16 * i + g; rb[i] = ra[i] + 8; }+ }+ const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB;+ for (int w = item_ct1.get_group(2); w < nwork;+ w += item_ct1.get_group_range(2)) {+ const sycl::int2 tl = tb.tiles[t0 + w / NFB];+ const int fb = w % NFB, e = tl.x(), row0 = tl.y(),+ nrows = sycl::min(kTileRows, tb.off[e + 1] - row0);+ const uint8_t* blob = b.blob[e - b.e0];+ const int rbase = fb * WROWS;+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier(); // the previous item is done with the buffers+ if (tid < kTileRows) {+ const int r =+ row0 ++ sycl::min(+ tid,+ nrows - 1); // rows past the tile's end repeat its last one+ srow[tid] = GU ? src[r] : r;+ }+ for (int c = tid; c < WROWS * 5; c += THREADS) { // the scales: 5 x 16 B (GU) or 5 x 4 B a row+ const int r = c / 5, q = c % 5;+ if (GU) cp16(smem + r * 80 + q * 16, blob + O_SC + (size_t) (rbase + r) * 80 + q * 16);+ else cp4(smem + r * 20 + q * 4, blob + O_SC + (size_t) (rbase + r) * 20 + q * 4);+ }+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier(); // srow+ auto load = [&](int kb) {+ uint8_t* st = stages + (kb % STAGES) * STAGE_BYTES;+ if (tid < WROWS) cp16(st + tid * 16, blob + O_CODES + (size_t) (rbase + tid) * CODE_LD + kb * 16);+ const int a = tid - (THREADS - kTileRows * 5); // the last 320 threads: 64 rows x 5 x 16 B+ if (a >= 0) {+ const int r = a / 5, q = a % 5;+ cp16(st + WROWS * 16 + r * AB + q * 16, act + (size_t) srow[r] * ACT_LD + kb * AB + q * 16);+ }+ };+#pragma unroll+ for (int s = 0; s < STAGES - 1; ++s) {+ if (s < NKB) load(s);+ cp_commit();+ }+ // a warp whose rows are all past the tile's end only takes part in the loads+ const bool on0 = nb0 < nrows, on1 = nb0 + 8 < nrows;+ float acc[4][2][4];+#pragma unroll+ for (int i = 0; i < 4; ++i)+#pragma unroll+ for (int n = 0; n < 2; ++n)+#pragma unroll+ for (int q = 0; q < 4; ++q) acc[i][n][q] = 0.0f;+ for (int kb = 0; kb < NKB; ++kb) {+ cp_wait<STAGES - 2>();+ /*+ DPCT1118: SYCL group functions and algorithms must be+ encountered in converged control flow. You may need to adjust the+ code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ if (kb + STAGES - 1 < NKB) load(kb + STAGES - 1);+ cp_commit();+ if (!on0) continue;+ const uint8_t* st = stages + (kb % STAGES) * STAGE_BYTES;+ const uint8_t* sa = st + WROWS * 16;+ sycl::uint2 bq[2][2]; // [n8 tile][half]: the B registers+ sycl::float4 sc[2]+ [2]; // [n8 tile][column 2 tig + c]: {d0, c0, d1, c1}+#pragma unroll+ for (int n = 0; n < 2; ++n) {+ if (n == 1 && !on1) break;+ const uint8_t* r = sa + (nb0 + 8 * n + g) * AB + 8 * tig;+ bq[n][0] = *(const sycl::uint2 *)r;+ bq[n][1] = *(const sycl::uint2 *)(r + 32);+ sc[n][0] =+ *(const sycl::float4 *)(sa + (nb0 + 8 * n + 2 * tig) * AB ++ 64);+ sc[n][1] =+ *(const sycl::float4 *)(sa ++ (nb0 + 8 * n + 2 * tig + 1) * AB ++ 64);+ }+#pragma unroll+ for (int i = 0; i < 4; ++i) {+ const sycl::uint4 ca = *(const sycl::uint4 *)(st + ra[i] * 16),+ cb = *(const sycl::uint4 *)(st + rb[i] * 16);+ const float+ da = sycl::vec<sycl::half, 1>(wsc[ra[i] * NKB + kb])+ .convert<float,+ sycl::rounding_mode::automatic>()[0],+ db = sycl::vec<sycl::half, 1>(wsc[rb[i] * NKB + kb])+ .convert<float,+ sycl::rounding_mode::automatic>()[0];+ const int s = 2 * tig;+ const uint32_t a0[4] = {(ca.x() >> s) & M2, (cb.x() >> s) & M2,+ (ca.y() >> s) & M2, (cb.y() >> s) & M2};+ const uint32_t a1[4] = {(ca.z() >> s) & M2, (cb.z() >> s) & M2,+ (ca.w() >> s) & M2, (cb.w() >> s) & M2};+#pragma unroll+ for (int n = 0; n < 2; ++n) {+ if (n == 1 && !on1) break;+ int d0[4], d1[4];+ mma_s8(d0, a0, bq[n][0].x(), bq[n][0].y());+ mma_s8(d1, a1, bq[n][1].x(), bq[n][1].y());+#pragma unroll+ for (int q = 0; q < 4; ++q) {+ const sycl::float4 z = sc[n][q & 1];+ const float u0 = sycl::bit_cast<float>(MAGIC + d0[q]) ++ z.y(),+ u1 = sycl::bit_cast<float>(MAGIC + d1[q]) ++ z.w();+ acc[i][n][q] = sycl::fma(+ (float)(q < 2 ? da : db),+ sycl::fma((float)(z.z()), (float)u1, z.x() * u0),+ acc[i][n][q]);+ }+ }+ }+ }+ if (!on0) continue;+ if (GU) {+ // SwiGLU of feature 32 wf + 8 i + g (lane g of m tile i), tile rows nb0 + 8 n + 2 tig + c; H to int8 per+ // row over the warp's 32 features (= one 32-value half-block of the down product's K)+ const int blk = 4 * fb + wf;+#pragma unroll+ for (int n = 0; n < 2; ++n) {+ if (n == 1 && !on1) break;+#pragma unroll+ for (int c = 0; c < 2; ++c) {+ float h[4], am = 0.0f;+#pragma unroll+ for (int i = 0; i < 4; ++i) {+ const float gt = acc[i][n][c], up = acc[i][n][2 + c];+ h[i] = gt / (1.0f + sycl::native::exp(-gt)) * up;+ am = sycl::fmax(am, sycl::fabs(h[i]));+ }+#pragma unroll+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the+ experimental feature masked sub_group function which may not+ be supported by all compilers or runtimes. You may need to+ adjust the code.+ */+ for (int o = 4; o < 32; o <<= 1) am = sycl::fmax(+ am,+ dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu,+ sycl::ext::oneapi::this_work_item::get_sub_group(),+ am, o));+ const float inv = am > 0.0f ? 127.0f / am : 0.0f;+ int qv[4], sum = 0;+#pragma unroll+ for (int i = 0; i < 4; ++i) {+ qv[i] =+ sycl::vec<float, 1>{(h[i] * inv)}+ .convert<int, sycl::rounding_mode::rte>()[0];+ sum += qv[i];+ }+#pragma unroll+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the+ experimental feature masked sub_group function which may not+ be supported by all compilers or runtimes. You may need to+ adjust the code.+ */+ for (int o = 4; o < 32; o <<= 1) sum +=+ dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu,+ sycl::ext::oneapi::this_work_item::get_sub_group(),+ sum, o);+ const int r = nb0 + 8 * n + 2 * tig + c;+ if (r < nrows) {+ uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (blk >> 1) * AB;+ const int hh = blk & 1;+#pragma unroll+ for (int i = 0; i < 4; ++i) o[32 * hh + perm32(8 * i + g)] = (uint8_t) (int8_t) qv[i];+ if (g == 0) * (sycl::float2 *)(o + 64 + 8 * hh) =+ sycl::float2(am / 127.0f, -(MAGICF + (float)sum));+ }+ }+ }+ } else {+#pragma unroll+ for (int i = 0; i < 4; ++i)+#pragma unroll+ for (int n = 0; n < 2; ++n) {+ if (n == 1 && !on1) break;+#pragma unroll+ for (int q = 0; q < 4; ++q) {+ const int r = nb0 + 8 * n + 2 * tig + (q & 1);+ if (r < nrows) dm[(size_t) (row0 + r) * 2560 + rbase + (q < 2 ? ra[i] : rb[i])] = acc[i][n][q];+ }+ }+ }+ }+#endif+}++#if defined(__HIPCC__)+// ---- Aurora (S23): the same products on gfx11 (RDNA3 / RDNA3.5) matrix cores, v_wmma_i32_16x16x16_iu8 (wave32).+// Fragments (gfx11): A lane l holds the 16 k of row l % 16 (lanes 16..31 repeat lanes 0..15), B lane l the 16 k of+// column l % 16, C/D lane l holds D[2i + l / 16][l % 16], i = 0..7. A = 16 weight rows, B = 16 tile rows (tokens):+// a lane's eight results are eight weight rows of ONE tile row, whose activation scales it already holds.+// The K order of a 16-weight word (one k-step): A register t = (word >> 2t) & 0x03030303 holds weights t, t+4, t+8,+// t+12, so k index p = 4t + b stands for weight 4b + t; the activations are stored in that order (act_pos). The+// integer dot of each 32-value half (two k-steps) is exact and the epilogue is the CUDA kernel's, so the numbers are+// those of expert_kernel (another K order inside exact integer sums).+// No LDS staging: a wave reads its weight rows (16 B per row and 64-weight block) and its tile rows' activation+// blocks (80 B) straight from global memory (L2: an expert's rows are read by every tile, a token's by every weight+// block), one block ahead in registers; the work item's weight scales go to LDS once.+#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__)+#define STRATA_FUSED_W11 1+#else+#define STRATA_FUSED_W11 0+#endif+typedef int w11_i4 __attribute__((ext_vector_type(4)));+typedef int w11_i8 __attribute__((ext_vector_type(8)));+constexpr int W_ROWS = 128; // weight rows per work item (GU: 64 features = one H block)+constexpr int W_THREADS = 256; // 8 waves: 4 along the weight rows (32 each) x 2 along the tile (32)++__device__ __forceinline__ w11_i8 wmma_iu8(w11_i4 a, w11_i4 b, w11_i8 c) {+#if STRATA_FUSED_W11+ return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(false, a, true, b, c, false);+#else+ __builtin_trap();+ return c;+#endif+}++template <bool GU>+__global__ void __launch_bounds__(W_THREADS)+expert_w11_kernel(const Batch b, const Tables tb, const uint8_t* __restrict__ act, const int32_t* __restrict__ src,+ uint8_t* __restrict__ out, float* __restrict__ dm) {+#if STRATA_FUSED_W11+ constexpr int NKB = GU ? 40 : 10; // 64-weight blocks along K+ constexpr int NFB = (GU ? 1280 : 2560) / W_ROWS; // work items per tile+ constexpr int CODE_LD = GU ? 640 : 160; // code bytes per weight row+ constexpr size_t O_CODES = GU ? O_GU_CODES : O_D_CODES, O_SC = GU ? O_GU_SC : O_D_SC;+ constexpr int ACT_LD = NKB * AB; // bytes per activation row+ constexpr unsigned M2 = 0x03030303u;+ __shared__ __align__(16) uint16_t wsc[W_ROWS * NKB]; // the item's weight scales (fp16), [row][kb]+ __shared__ int srow[kTileRows];+ __shared__ float hs[GU ? kTileRows : 1][GU ? 65 : 1]; // GU: H of the item's 64 features, [tile row][feature]+ const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;+ const int wm = wave & 3, wn = wave >> 2, l16 = lane & 15, hi = lane >> 4;+ const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB;+ for (int w = blockIdx.x; w < nwork; w += gridDim.x) {+ const int2 tl = tb.tiles[t0 + w / NFB];+ const int fb = w % NFB, e = tl.x, row0 = tl.y, nrows = min(kTileRows, tb.off[e + 1] - row0);+ const uint8_t* blob = b.blob[e - b.e0];+ const int rbase = fb * W_ROWS;+ __syncthreads(); // the previous item is done with srow / wsc / hs+ if (tid < kTileRows) {+ const int r = row0 + min(tid, nrows - 1); // rows past the tile's end repeat its last one+ srow[tid] = GU ? src[r] : r;+ }+ {+ const uint4* s4 = reinterpret_cast<const uint4*>(blob + O_SC + (size_t) rbase * NKB * 2);+ for (int i = tid; i < W_ROWS * NKB / 8; i += W_THREADS) reinterpret_cast<uint4*>(wsc)[i] = s4[i];+ }+ __syncthreads();+ const bool on = 32 * wn < nrows; // a wave past the tile's rows only stages+ float acc[2][2][8];+#pragma unroll+ for (int mt = 0; mt < 2; ++mt)+#pragma unroll+ for (int nt = 0; nt < 2; ++nt)+#pragma unroll+ for (int i = 0; i < 8; ++i) acc[mt][nt][i] = 0.0f;+ if (on) {+ const uint8_t* arow[2];+ const uint8_t* brow[2];+#pragma unroll+ for (int mt = 0; mt < 2; ++mt) arow[mt] = blob + O_CODES + (size_t) (rbase + 32 * wm + 16 * mt + l16) * CODE_LD;+#pragma unroll+ for (int nt = 0; nt < 2; ++nt) brow[nt] = act + (size_t) srow[32 * wn + 16 * nt + l16] * ACT_LD;+ uint4 ac[2], bq[2][4];+ float4 bs[2];+ auto fetch = [&](int kb, uint4 (&a)[2], uint4 (&q)[2][4], float4 (&s)[2]) {+#pragma unroll+ for (int mt = 0; mt < 2; ++mt) a[mt] = *reinterpret_cast<const uint4*>(arow[mt] + kb * 16);+#pragma unroll+ for (int nt = 0; nt < 2; ++nt) {+ const uint4* p = reinterpret_cast<const uint4*>(brow[nt] + kb * AB);+ q[nt][0] = p[0]; q[nt][1] = p[1]; q[nt][2] = p[2]; q[nt][3] = p[3];+ s[nt] = *reinterpret_cast<const float4*>(brow[nt] + kb * AB + 64);+ }+ };+ fetch(0, ac, bq, bs);+ for (int kb = 0; kb < NKB; ++kb) {+ uint4 nac[2], nbq[2][4];+ float4 nbs[2];+ if (kb + 1 < NKB) fetch(kb + 1, nac, nbq, nbs);+ w11_i8 c[2][2][2]; // [half][mt][nt]+#pragma unroll+ for (int h = 0; h < 2; ++h)+#pragma unroll+ for (int mt = 0; mt < 2; ++mt)+#pragma unroll+ for (int nt = 0; nt < 2; ++nt) c[h][mt][nt] = w11_i8{0, 0, 0, 0, 0, 0, 0, 0};+#pragma unroll+ for (int ks = 0; ks < 4; ++ks) { // k-step = 16-weight word ks of the block+ w11_i4 A[2];+#pragma unroll+ for (int mt = 0; mt < 2; ++mt) {+ const unsigned wd = ks == 0 ? ac[mt].x : ks == 1 ? ac[mt].y : ks == 2 ? ac[mt].z : ac[mt].w;+ A[mt] = w11_i4{(int) (wd & M2), (int) ((wd >> 2) & M2), (int) ((wd >> 4) & M2),+ (int) ((wd >> 6) & M2)};+ }+#pragma unroll+ for (int nt = 0; nt < 2; ++nt) {+ const uint4 q = bq[nt][ks];+ const w11_i4 B = w11_i4{(int) q.x, (int) q.y, (int) q.z, (int) q.w};+#pragma unroll+ for (int mt = 0; mt < 2; ++mt) c[ks >> 1][mt][nt] = wmma_iu8(A[mt], B, c[ks >> 1][mt][nt]);+ }+ }+ // the epilogue: per 64-weight block acc += d_w * (d_x0 * (dot0 - sum0) + d_x1 * (dot1 - sum1))+#pragma unroll+ for (int mt = 0; mt < 2; ++mt) {+ float dw[8];+#pragma unroll+ for (int i = 0; i < 8; ++i) {+ const int m = 32 * wm + 16 * mt + 2 * i + hi;+ dw[i] = __half2float(__ushort_as_half(wsc[m * NKB + kb]));+ }+#pragma unroll+ for (int nt = 0; nt < 2; ++nt) {+ const float4 z = bs[nt];+#pragma unroll+ for (int i = 0; i < 8; ++i) {+ const float u0 = __int_as_float(MAGIC + c[0][mt][nt][i]) + z.y;+ const float u1 = __int_as_float(MAGIC + c[1][mt][nt][i]) + z.w;+ acc[mt][nt][i] = fmaf(dw[i], fmaf(z.z, u1, z.x * u0), acc[mt][nt][i]);+ }+ }+ }+ if (kb + 1 < NKB) {+#pragma unroll+ for (int mt = 0; mt < 2; ++mt) ac[mt] = nac[mt];+#pragma unroll+ for (int nt = 0; nt < 2; ++nt) {+ bs[nt] = nbs[nt];+#pragma unroll+ for (int j = 0; j < 4; ++j) bq[nt][j] = nbq[nt][j];+ }+ }+ }+ }+ if constexpr (GU) {+ // SwiGLU: row 2f is feature f's gate (lanes 0..15), 2f + 1 its up (lanes 16..31) - the same (mt, i)+ if (on) {+#pragma unroll+ for (int mt = 0; mt < 2; ++mt)+#pragma unroll+ for (int nt = 0; nt < 2; ++nt)+#pragma unroll+ for (int i = 0; i < 8; ++i) {+ const float up = __shfl_xor_sync(0xffffffffu, acc[mt][nt][i], 16);+ const float gt = acc[mt][nt][i];+ if (hi == 0) hs[32 * wn + 16 * nt + l16][16 * wm + 8 * mt + i] = gt / (1.0f + __expf(-gt)) * up;+ }+ }+ __syncthreads();+ // H block fb (features 64 fb .. 64 fb + 63) to int8: a thread per (tile row, half)+ if (tid < 2 * kTileRows) {+ const int r = tid >> 1, hh = tid & 1;+ if (r < nrows) {+ float am = 0.0f;+#pragma unroll 8+ for (int j = 0; j < 32; ++j) am = fmaxf(am, fabsf(hs[r][32 * hh + j]));+ const float inv = am > 0.0f ? 127.0f / am : 0.0f;+ uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (size_t) fb * AB;+ int sum = 0;+ uint32_t wd[8] = {};+#pragma unroll+ for (int j = 0; j < 32; ++j) {+ const int qv = __float2int_rn(hs[r][32 * hh + j] * inv);+ sum += qv;+ const int p = act_pos(j);+ wd[p >> 2] |= (uint32_t) (uint8_t) (int8_t) qv << (8 * (p & 3));+ }+ uint4* o4 = reinterpret_cast<uint4*>(o + 32 * hh);+ o4[0] = make_uint4(wd[0], wd[1], wd[2], wd[3]);+ o4[1] = make_uint4(wd[4], wd[5], wd[6], wd[7]);+ *reinterpret_cast<float2*>(o + 64 + 8 * hh) = make_float2(am / 127.0f, -(MAGICF + (float) sum));+ }+ }+ } else if (on) {+#pragma unroll+ for (int mt = 0; mt < 2; ++mt)+#pragma unroll+ for (int nt = 0; nt < 2; ++nt) {+ const int r = 32 * wn + 16 * nt + l16;+ if (r < nrows) {+ float* d = dm + (size_t) (row0 + r) * 2560 + rbase + 32 * wm + 16 * mt + hi;+#pragma unroll+ for (int i = 0; i < 8; ++i) d[2 * i] = acc[mt][nt][i];+ }+ }+ }+ }+#else+ __builtin_trap();+#endif+}+#endif // __HIPCC__++unsigned blocks(int64_t n, int per) { return (unsigned) ((n + per - 1) / per); }++struct DevInfo {+ bool done = false;+ int cc = 0, sms = 0, occ_gu = 0, occ_d = 0;+};+std::mutex g_mu;+DevInfo g_dev[32];++#if defined(__HIPCC__)+// Resident blocks per multiprocessor for the gfx11 WMMA prompt-expert kernels' persistent grids. HIP counts a gfx11+// WGP (two CUs, which these kernels use as one in the default WGP mode) as one multiprocessor, and the occupancy query+// answers 1 block for these kernels where 2 run side by side - so the grid was half the GPU's room. gfx1151 (20+// WGPs), 8192 tokens x top 10, IQ3_S / IQ4_NL, one layer: 1 block per WGP 60.7 ms, 2 44.7, 3 49.9, 4 45.2 (the same+// work items and arithmetic: the results do not change). STRATA_PF_OCC=N sets the blocks per WGP (an experiment knob).+static int wgp_blocks(int occ) {+ static const int env = [] {+ const char* v = std::getenv("STRATA_PF_OCC");+ return v != nullptr ? std::atoi(v) : 0;+ }();+ return env > 0 ? env : 2 * std::max(occ, 1);+}+#endif+const DevInfo &dev_info() try {+ int dev = 0;+ dev = dpct::get_current_device_id();+ std::lock_guard<std::mutex> lk(g_mu);+ DevInfo& d = g_dev[dev & 31];+ if (d.done) return d;+ d.done = true;+#if defined(STRATA_HIP_GFX906)+ // gfx906 reports compute capability 9.0 through HIP, but the mma.sync bodies above are CUDA sm_80+ only and+ // empty in a hipcc build: never available here (the prompt path keeps its own expert GEMMs)+ return d;+#elif defined(__HIPCC__)+ { // gfx11 (RDNA3 / RDNA3.5) with this build's code for it: the WMMA kernels+ cudaDeviceProp prop;+ cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev);+ hipFuncAttributes fa{};+ if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess || std::strncmp(prop.gcnArchName, "gfx11", 5) != 0 ||+ hipFuncGetAttributes(&fa, reinterpret_cast<const void*>(expert_w11_kernel<true>)) != hipSuccess) {+ cudaGetLastError();+ return d;+ }+ if (hipOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_gu, expert_w11_kernel<true>, W_THREADS, 0) != hipSuccess ||+ hipOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_d, expert_w11_kernel<false>, W_THREADS, 0) != hipSuccess)+ d.occ_gu = d.occ_d = 0;+ d.cc = d.occ_gu >= 1 && d.occ_d >= 1 ? 80 : 0;+ cudaGetLastError();+ return d;+ }+#else+ int major = 0, minor = 0;+ major = dpct::get_device(dev).get_major_version();+ minor = dpct::get_device(dev).get_minor_version();+ d.sms = dpct::get_device(dev).get_max_compute_units();+ d.cc = 10 * major + minor;+ if (d.cc < 80) return d;+ // the device code of this card's arch must have the kernels (a build without an sm_80+ target has an empty body)+ dpct::kernel_function_info fa{};+ if (DPCT_CHECK_ERROR(dpct::get_kernel_function_info(+ &fa, (const void *)expert_kernel<true>)) != 0 ||+ fa.ptxVersion < 80) {+ /*+ DPCT1026: The call to cudaGetLastError was removed because this+ functionality is redundant in SYCL.+ */+ d.cc = 0;+ return d;+ }+ /*+ DPCT1027: The call to cudaFuncSetAttribute was replaced with 0 because+ SYCL currently does not support corresponding setting.+ */+ ck(0, "smem gu");+ /*+ DPCT1027: The call to cudaFuncSetAttribute was replaced with 0 because+ SYCL currently does not support corresponding setting.+ */+ ck(0, "smem down");+ /*+ DPCT1111: Please verify the input arguments of+ "dpct::experimental::calculate_max_active_wg_per_xecore" base on the target+ function "expert_kernel<true>".+ */+ dpct::experimental::calculate_max_active_wg_per_xecore(+ &d.occ_gu, THREADS,+ smem_bytes(true) ++ dpct_placeholder /* total share local memory size */);+ /*+ DPCT1111: Please verify the input arguments of+ "dpct::experimental::calculate_max_active_wg_per_xecore" base on the target+ function "expert_kernel<false>".+ */+ dpct::experimental::calculate_max_active_wg_per_xecore(+ &d.occ_d, THREADS,+ smem_bytes(false) ++ dpct_placeholder /* total share local memory size */);+ if (d.occ_gu < 1 || d.occ_d < 1) d.cc = 0; // does not fit this card: the MMQ path+ /*+ DPCT1026: The call to cudaGetLastError was removed because this+ functionality is redundant in SYCL.+ */+#endif+ return d;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++} // namespace++bool built() { return true; }+bool available() { return dev_info().cc >= 80; }+// 0.1.36: on by default for the Q2_0 pack (+13-23% prompts on an RTX 5070; teacher-forced against the FP16 path as+// close as MMQ at 8K and closer at 32K: phaseA-tests s18-tf); STRATA_PF_FUSED=0 keeps MMQ. The native packs' kernels+// (moe_fused_iq) stay opt-in: STRATA_PF_FUSED=1 (requested()).+bool enabled() {+ static const bool env = [] {+ const char* v = std::getenv("STRATA_PF_FUSED");+#if defined(__HIPCC__)+ return v != nullptr && v[0] == '1'; // Aurora: the gfx11 WMMA kernels are opt-in (STRATA_PF_FUSED=1)+#else+ return v == nullptr || v[0] != '0';+#endif+ }();+ return env && available();+}+bool requested() {+ static const bool env = [] {+ const char* v = std::getenv("STRATA_PF_FUSED");+ return v != nullptr && v[0] == '1';+ }();+ return env && available();+}++size_t act_bytes(int64_t rows, int64_t cols) { return (size_t) rows * (size_t) (cols / 64) * AB; }+size_t group_bytes(int64_t n, int n_expert) {+ return tiles_at(n_expert) ++ ((size_t)(n + kTileRows - 1) / kTileRows + (size_t)n_expert) *+ sizeof(sycl::int2);+}++void quantize_act(const float* x, int64_t rows, int64_t cols, void* xa, void* stream) {+ if (rows <= 0) return;+ const int64_t nblk = rows * (cols / 64);+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<dpct_kernel_name<class quant_act_kernel_da6c97>>(+ sycl::nd_range<3>(sycl::range(1, 1, blocks(nblk, 8)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ quant_act_kernel(x, nblk, (uint8_t *)xa);+ });+ }+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use the+ error codes. The cudaGetLastError function call was replaced with 0. You+ need to rewrite this code.+ */+ ck(0, "quantize_act");+}++void group(const int32_t* ids, int64_t n, int k, int n_expert, void* scratch, int32_t* slot, int32_t* src,+ void* stream) {+ if (n_expert < 1 || n_expert > 1024) {+ std::fprintf(stderr, "prefill fused experts: %d experts (the grouping takes 1 to 1024)\n", n_expert);+ std::exit(1);+ }+ const dpct::queue_ptr s = strata::q_of(stream);+ const Tables tb = tables(scratch, n_expert);+ ck(DPCT_CHECK_ERROR(s->memset(tb.cnt, 0, (size_t)n_expert * 4)),+ "group memset");+ if (n > 0) {+ const unsigned nb = std::min<unsigned>(blocks(n, 1024), 4u * (unsigned) std::max(dev_info().sms, 1));+ /*+ 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. Adjust the work-group size if needed.+ */+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ s->submit([&](sycl::handler &cgh) {+ sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(+ sycl::range((size_t)n_expert * 4), cgh);++ cgh.parallel_for<+ dpct_kernel_name<class count_kernel_9919e0>>(+ sycl::nd_range<3>(sycl::range(1, 1, nb) *+ sycl::range(1, 1, 1024),+ sycl::range(1, 1, 1024)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ count_kernel(ids, n, n_expert, tb.cnt,+ dpct_local_acc_ct1+ .get_multi_ptr<+ sycl::access::decorated::no>()+ .get());+ });+ });+ }+ }+ /*+ 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.+ Adjust the work-group size if needed.+ */+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ s->parallel_for<dpct_kernel_name<class scan_kernel_7ed98e>>(+ sycl::nd_range<3>(+ sycl::range(1, 1, (unsigned)((n_expert + 31) / 32 * 32)),+ sycl::range(1, 1, (unsigned)((n_expert + 31) / 32 * 32))),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ scan_kernel(tb, n_expert);+ });+ }+ if (n > 0) {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ s->parallel_for<dpct_kernel_name<class place_kernel_cf784d>>(+ sycl::nd_range<3>(sycl::range(1, 1, blocks(n, 256)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ place_kernel(ids, n, k, n_expert, tb, slot, src);+ });+ }+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use the+ error codes. The cudaGetLastError function call was replaced with 0. You+ need to rewrite this code.+ */+ ck(0, "group");+}++void experts(const Batch& b, int n_expert, int64_t n, const void* scratch, const void* xa, const int32_t* src,+ void* ha, float* dm, void* stream) {+ if (b.e1 <= b.e0 || n <= 0) return;+ const DevInfo& d = dev_info();+ const dpct::queue_ptr s = strata::q_of(stream);+ const Tables tb = tables(const_cast<void*>(scratch), n_expert);+ // the most tiles the batch can have: every row in it, plus a partial tile per expert+ const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0);+#if defined(__HIPCC__)+ const unsigned g_gu = (unsigned) std::min<int64_t>(tiles * (1280 / W_ROWS), (int64_t) d.sms * wgp_blocks(d.occ_gu));+ const unsigned g_d = (unsigned) std::min<int64_t>(tiles * (2560 / W_ROWS), (int64_t) d.sms * wgp_blocks(d.occ_d));+ expert_w11_kernel<true><<<g_gu, W_THREADS, 0, s>>>(b, tb, (const uint8_t*) xa, src, (uint8_t*) ha, nullptr);+ expert_w11_kernel<false><<<g_d, W_THREADS, 0, s>>>(b, tb, (const uint8_t*) ha, src, nullptr, dm);+#else+ const unsigned g_gu = (unsigned) std::min<int64_t>(tiles * 5, (int64_t) d.sms * d.occ_gu);+ const unsigned g_d = (unsigned) std::min<int64_t>(tiles * 10, (int64_t) d.sms * d.occ_d);+ /*+ 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.+ Adjust the work-group size if needed.+ */+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});++ s->submit([&](sycl::handler &cgh) {+ sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(+ sycl::range(smem_bytes(true)), cgh);++ cgh.parallel_for<dpct_kernel_name<class expert_kernel_f38977,+ dpct_kernel_scalar<true>>>(+ sycl::nd_range<3>(sycl::range(1, 1, g_gu) *+ sycl::range(1, 1, THREADS),+ sycl::range(1, 1, THREADS)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ expert_kernel<true>(+ b, tb, (const uint8_t *)xa, src, (uint8_t *)ha,+ nullptr,+ dpct_local_acc_ct1+ .get_multi_ptr<sycl::access::decorated::no>()+ .get());+ });+ });+ }+ /*+ 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.+ Adjust the work-group size if needed.+ */+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});++ s->submit([&](sycl::handler &cgh) {+ sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(+ sycl::range(smem_bytes(false)), cgh);++ cgh.parallel_for<dpct_kernel_name<class expert_kernel_e2d106,+ dpct_kernel_scalar<false>>>(+ sycl::nd_range<3>(sycl::range(1, 1, g_d) *+ sycl::range(1, 1, THREADS),+ sycl::range(1, 1, THREADS)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ expert_kernel<false>(+ b, tb, (const uint8_t *)ha, src, nullptr, dm,+ dpct_local_acc_ct1+ .get_multi_ptr<sycl::access::decorated::no>()+ .get());+ });+ });+ }+#endif+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use the+ error codes. The cudaGetLastError function call was replaced with 0. You+ need to rewrite this code.+ */+ ck(0, "experts");+}++} // namespace strata::prefill::fuseddiff --git a/sycl/src/prefill/moe_fused_iq.dp.cpp b/sycl/src/prefill/moe_fused_iq.dp.cppnew file mode 100644index 000000000..637ed4acc--- /dev/null+++ b/sycl/src/prefill/moe_fused_iq.dp.cpp@@ -0,0 +1,1469 @@+// src/prefill/moe_fused_iq.cu - see include/strata/prefill/moe_fused_iq.hpp (#136: the native packs' prompt experts on+// the fused int8 kernels of moe_fused.cu).+//+// The arithmetic. An activation block of 32 values is x = d_x * a, a = round(x / d_x) in -127..127, stored in natural+// order (per 64 values: 64 codes, then {d_0, d_1} and 8 unused bytes - 80 bytes, the Q2_0 path's size). A weight+// block of 32 (or 16) values is w = d_w * q with q an int8: the i-quants' codebook entries with their signs applied+// (IQ2_XXS / IQ2_XS / IQ2_S: 0..43, IQ3_XXS: 0..62, IQ3_S: 0..15, IQ4_XS / IQ4_NL: -127..113), Q2_0's code - 1. So+// sum w x = d_w * d_x * sum q a, |sum q a| <= 32 * 127 * 127 < 2^22,+// and the int32 dot becomes a float exactly with one float add: the mma starts from C = 0x4B400000 (the bits of+// 1.5 * 2^23), so as_float(D) - 1.5 * 2^23 is the dot. Per output and 32 values: that add, d_w * d_x, one fma (the+// formats with a scale per 16 values: two dots, each times its d_w, then d_x). d_w is llama.cpp's own: IQ2_XXS+// d (2s + 1) / 8, IQ2_XS / IQ2_S d (2s + 1) / 8 per 16, IQ3_XXS d (2s + 1) / 4, IQ3_S d (2s + 1), IQ4_XS d (s - 32),+// IQ4_NL and Q2_0 d (dequantize_row_* in ggml-quants.c, mmq-load-tiles.cuh).+//+// The load stage. Per 64 values of K (a stage), a thread decodes one 32-value sub-block of one of the work item's+// weight rows: its block bytes are read from the blob with 16-bit loads (the GGUF blocks are 2-byte aligned: 66 / 74 /+// 82 / 98 / 110 / 136 / 18 bytes) one stage ahead into registers (and two 256-value blocks ahead into L2), then turned+// into 32 int8 and the sub-block's scales in shared memory, double-buffered. The codebooks live in shared memory (up+// to 8 KB, IQ2_S). The activations arrive by cp.async, four stages deep, as in moe_fused.cu; the fragments come by+// ldmatrix. The products are mma.sync m16n8k32 (m16n8k16 for the formats with a scale per 16 values); the epilogues+// (SwiGLU, H to int8 per 32 features; down into the per-slot rows) are moe_fused.cu's.+#define DPCT_PROFILING_ENABLED+#include <sycl/sycl.hpp>+#include <dpct/dpct.hpp>+#include "strata/sycl_queue.hpp"+#include "strata/prefill/moe_fused_iq.hpp"++#include "ggml.h"++#define GGML_COMMON_DECL_CUDA+#define GGML_COMMON_IMPL_CUDA+#include "ggml-common.h"++#include <algorithm>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <mutex>++namespace strata::prefill::fused {+namespace {++void ck(dpct::err0 e, const char *what) {+}++constexpr int AB = 80; // activation bytes per 64 values: 64 codes, {d0, d1}, 8 unused+constexpr int MAGIC = 0x4B400000; // the bits of 1.5 * 2^23+constexpr float MAGICF = 12582912.0f;+// 16 warps, each 64 weight rows x 16 routed rows; WW of them along the weight rows and 16 / WW along the routed rows: a+// work item is (WR = 64 WW weight rows) x (TR = 256 / WW routed rows of one expert) - 256 x 64 or 128 x 128, chosen+// per launch by the rows per expert (pick_ww)+constexpr int THREADS = 512;+constexpr int WLD = 80; // bytes per decoded weight row of a stage: 64 int8 + 16 (no bank conflicts)+constexpr int tile_rows(int ww) { return 256 / ww; }+constexpr int weight_rows(int ww) { return 64 * ww; }+constexpr int ASTAGES = 4; // cp.async depth of the activations (64 values of K a stage)+constexpr int GU_ROWS_K = 2560, D_ROWS_K = 640; // K of gate/up (n_embd) and of down (n_ff)++// the formats (ggml type ids)+constexpr int T_IQ2_XXS = GGML_TYPE_IQ2_XXS, T_IQ2_XS = GGML_TYPE_IQ2_XS, T_IQ2_S = GGML_TYPE_IQ2_S,+ T_IQ3_XXS = GGML_TYPE_IQ3_XXS, T_IQ3_S = GGML_TYPE_IQ3_S, T_IQ4_XS = GGML_TYPE_IQ4_XS,+ T_IQ4_NL = GGML_TYPE_IQ4_NL, T_Q2_0 = GGML_TYPE_Q2_0,+ // Aurora (opt-in, HIP gfx11 only): Unsloth UD-Q4_K_XL's experts - gate/up Q4_K (one layer Q5_K), down Q5_1+ // (five layers Q8_0). Their weights are w = d_w q + m_w (a minimum), so a sub-block's dot is+ // sum w x = d_x (d_w sum q a + m_w sum a):+ // the activation blocks carry sum a per 32 values in their eight spare bytes (quant_act_nat_kernel and+ // the H epilogue write it for every path; no other format reads it)+ T_Q4_K = GGML_TYPE_Q4_K, T_Q5_K = GGML_TYPE_Q5_K, T_Q5_1 = GGML_TYPE_Q5_1, T_Q8_0 = GGML_TYPE_Q8_0;+static_assert(sizeof(block_iq2_xxs) == 66 && sizeof(block_iq2_xs) == 74 && sizeof(block_iq2_s) == 82 &&+ sizeof(block_iq3_xxs) == 98 && sizeof(block_iq3_s) == 110 && sizeof(block_iq4_xs) == 136 &&+ sizeof(block_iq4_nl) == 18 && sizeof(block_q2_0) == 18 && sizeof(block_q4_K) == 144 &&+ sizeof(block_q5_K) == 176 && sizeof(block_q5_1) == 24 && sizeof(block_q8_0) == 34,+ "the block layouts this file decodes");++// block bytes, scale per 16 values, codebook bytes in shared memory+constexpr int block_bytes(int t) {+ return t == T_IQ2_XXS ? 66 : t == T_IQ2_XS ? 74 : t == T_IQ2_S ? 82 : t == T_IQ3_XXS ? 98 : t == T_IQ3_S ? 110+ : t == T_IQ4_XS ? 136 : t == T_Q4_K ? 144 : t == T_Q5_K ? 176 : t == T_Q5_1 ? 24 : t == T_Q8_0 ? 34 : 18;+}+// the formats with a minimum (w = d q + m), and the raw words a sub-block's load stage holds+constexpr bool has_min(int t) { return t == T_Q4_K || t == T_Q5_K || t == T_Q5_1; }+constexpr int raw_words(int t) {+ return t == T_Q4_K ? 10 : t == T_Q5_K ? 18 : t == T_Q5_1 ? 6 : t == T_Q8_0 ? 9 : 5;+}+constexpr bool per16(int t) { return t == T_IQ2_XS || t == T_IQ2_S; }+constexpr int grid_bytes(int t) {+ return t == T_IQ2_XXS ? 256 * 8 : t == T_IQ2_XS ? 512 * 8 : t == T_IQ2_S ? 1024 * 8 : t == T_IQ3_XXS ? 256 * 4+ : t == T_IQ3_S ? 512 * 4 : 0;+}+constexpr size_t smem_bytes(int t, int ww) {+ return (size_t) 2 * weight_rows(ww) * (WLD + 16) + (size_t) ASTAGES * tile_rows(ww) * AB ++ (size_t) tile_rows(ww) * 4 + grid_bytes(t);+}++// moe_fused.cu's grouping tables (the same layout: fused::group writes them)+struct Tables {+ int32_t *cnt, *off, *fill, *ts;+ sycl::int2 *tiles;+};+size_t tiles_at(int n_expert) { return ((size_t) (4 * n_expert + 2) * 4 + 15) / 16 * 16; }+Tables tables(void* scratch, int n_expert) {+ int32_t* p = (int32_t*) scratch;+ return {p, p + n_expert, p + 2 * n_expert + 1, p + 3 * n_expert + 1,+ (sycl::int2 *)((uint8_t *)scratch + tiles_at(n_expert))};+}++// ---- activations in natural order: one warp per 64 values+__dpct_inline__ void quant_act_nat_kernel(const float *__restrict__ x,+ int64_t nblk,+ uint8_t *__restrict__ xa) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int64_t w =+ (int64_t)item_ct1.get_group(2) * (item_ct1.get_local_range(2) / 32) ++ item_ct1.get_local_id(2) / 32;+ const int lane = item_ct1.get_local_id(2) & 31;+ if (w >= nblk) return;+ const float v0 = x[w * 64 + lane], v1 = x[w * 64 + 32 + lane];+ float a0 = sycl::fabs(v0), a1 = sycl::fabs(v1);+#pragma unroll+ for (int o = 16; o > 0; o >>= 1) {+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ a0 = sycl::fmax(+ a0, dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu,+ sycl::ext::oneapi::this_work_item::get_sub_group(), a0, o));+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ a1 = sycl::fmax(+ a1, dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu,+ sycl::ext::oneapi::this_work_item::get_sub_group(), a1, o));+ }+ uint8_t* out = xa + w * AB;+ const int c0 = a0 > 0.0f ? sycl::vec<float, 1>{(v0 * (127.0f / a0))}+ .convert<int, sycl::rounding_mode::rte>()[0]+ : 0,+ c1 = a1 > 0.0f ? sycl::vec<float, 1>{(v1 * (127.0f / a1))}+ .convert<int, sycl::rounding_mode::rte>()[0]+ : 0;+ out[lane] = (uint8_t) (int8_t) c0;+ out[32 + lane] = (uint8_t) (int8_t) c1;+ int s0 = c0, s1 = c1; // the codes' sums per 32 values (the formats with a minimum read them)+#pragma unroll+ for (int o = 16; o > 0; o >>= 1) {+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ s0 += dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), s0,+ o);+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ s1 += dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), s1,+ o);+ }+ if (lane == 0) * (sycl::float4 *)(out + 64) =+ sycl::float4(a0 / 127.0f, a1 / 127.0f, (float)s0, (float)s1);+}++#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP >= 800+__dpct_inline__ void cp16(void *dst, const void *src) {+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)+ asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(+ (unsigned)__cvta_generic_to_shared(dst)),+ "l"(src));+#else+ *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(dst))) =+ *(((uint32_t *)(uintptr_t)src));+ if (16 > 4)+ *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(dst)) ++ 1) = *(((uint32_t *)(uintptr_t)src) + 1);+ if (16 > 8)+ *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(dst)) ++ 2) = *(((uint32_t *)(uintptr_t)src) + 2);+ if (16 > 12)+ *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(dst)) ++ 3) = *(((uint32_t *)(uintptr_t)src) + 3);+#endif+}+/*+DPCT1026: The call to "cp.async.commit_group;+" was removed because current "cp.async" is migrated to synchronous copy+operation. You may need to adjust the code to tune the performance.+*/+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)+__device__ __forceinline__ void cp_commit() {+ asm volatile("cp.async.commit_group;\n" ::);+#else+__device__ __forceinline__ void cp_commit() {+#endif }+/*+DPCT1053: Migration of device assembly code is not supported.+*/+__dpct_inline__ void pf_l2(const void *p) {+ asm volatile("prefetch.global.L2 [%0];\n" ::"l"(p));+}+/*+DPCT1026: The call to "cp.async.wait_group %0;+" was removed because current "cp.async" is migrated to synchronous copy+operation. You may need to adjust the code to tune the performance.+*/+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)+ template <int N> __device__ __forceinline__ void cp_wait() {+ asm volatile("cp.async.wait_group %0;\n" ::"n"(N));+#else+ template <int N> __device__ __forceinline__ void cp_wait() {+#endif }+// d = MAGIC + A (16 x 32 s8, row) * B (32 x 8 s8, col): the int32 dot with the magic bias already added (the C+// operand), so as_float(d) - 1.5 * 2^23 is the dot as a float+__dpct_inline__ void mma32(int (&d)[4], const uint32_t (&a)[4], uint32_t b0,+ uint32_t b1) {+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)+ asm("mma.sync.aligned.m16n8k32.row.col.s32.s8.s8.s32 "+ "{%0,%1,%2,%3}, "+ "{%4,%5,%6,%7}, {%8,%9}, {%10,%10,%10,%10};\n"+ : "=r"(d[0]), "=r"(d[1]), "=r"(d[2]), "=r"(d[3])+ : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1),+ "r"(MAGIC));+#else+ {+ volatile void *d_mat_frag_ct1[4] = {&d[0], &d[1], &d[2], &d[3]};+ sycl::vec<uint32_t, 4> a_mat_frag_ct1(a[0], a[1], a[2], a[3]);+ sycl::vec<uint32_t, 2> b_mat_frag_ct1(b0, b1);+ sycl::vec<int32_t, 4> c_mat_frag_ct1(MAGIC, MAGIC, MAGIC,+ MAGIC);+ dpct::experimental::matrix::mma<16, 8, 32, int8_t, int32_t>(+ reinterpret_cast<volatile void **>(d_mat_frag_ct1),+ &a_mat_frag_ct1, &b_mat_frag_ct1, &c_mat_frag_ct1);+ }+#endif+}+// the same at m16n8k16 (A 16 x 16, B 16 x 8)+__dpct_inline__ void mma16(int (&d)[4], uint32_t a0, uint32_t a1, uint32_t b0) {+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)+ asm("mma.sync.aligned.m16n8k16.row.col.s32.s8.s8.s32 "+ "{%0,%1,%2,%3}, "+ "{%4,%5}, {%6}, {%7,%7,%7,%7};\n"+ : "=r"(d[0]), "=r"(d[1]), "=r"(d[2]), "=r"(d[3])+ : "r"(a0), "r"(a1), "r"(b0), "r"(MAGIC));+#else+ {+ volatile void *d_mat_frag_ct1[4] = {&d[0], &d[1], &d[2], &d[3]};+ sycl::vec<uint32_t, 2> a_mat_frag_ct1(a0, a1);+ sycl::vec<uint32_t, 1> b_mat_frag_ct1(b0);+ sycl::vec<int32_t, 4> c_mat_frag_ct1(MAGIC, MAGIC, MAGIC,+ MAGIC);+ dpct::experimental::matrix::mma<16, 8, 16, int8_t, int32_t>(+ reinterpret_cast<volatile void **>(d_mat_frag_ct1),+ &a_mat_frag_ct1, &b_mat_frag_ct1, &c_mat_frag_ct1);+ }+#endif+}+__dpct_inline__ float dotf(int d) {+ return sycl::bit_cast<float>(d) - MAGICF;+}+// four 8 x 16-byte matrices, row addresses from lanes 0-7, 8-15, 16-23, 24-31: lane (g, t) gets bytes 4t..4t+3 of row g+// of each - an mma fragment+__dpct_inline__ void ldsm4(uint32_t (&r)[4], const void *p) {+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)+ asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 "+ "{%0,%1,%2,%3}, [%4];\n"+ : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3])+ : "r"((unsigned)__cvta_generic_to_shared(p))+ : "memory");+#else+ dpct::experimental::matrix::ldmatrix(+ (uintptr_t)(unsigned)__cvta_generic_to_shared(p), &r[0], &r[1],+ &r[2], &r[3]);+#endif+}++#endif+#if (defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP >= 800) || \+ defined(__HIPCC__)+#if defined(__HIPCC__)+__device__ __forceinline__ float dotf(int d) { return __int_as_float(d) - MAGICF; }+#endif+// ---- the load stage: a 32-value sub-block's bytes into registers, then int8 and scales+__dpct_inline__ uint32_t ld16(const uint8_t *p) {+ return *(const uint16_t *)p;+}+__dpct_inline__ uint32_t ld32(const uint8_t *p) {+ return ld16(p) | (ld16(p + 2) << 16);+}+__dpct_inline__ float half_at(uint32_t w) {+ return sycl::vec<sycl::half, 1>(+ sycl::bit_cast<sycl::half, unsigned short>((unsigned short)w))+ .convert<float, sycl::rounding_mode::automatic>()[0];+}+// llama.cpp's sign unpacking: 7 bits of signs, the 8th their parity (bit 7 of v may be anything)+__dpct_inline__ uint32_t unpack_ksigns(uint32_t v) {+ v &= 0xFF;+ const uint32_t p = sycl::popcount(v) & 1;+ return (v ^ p << 7) * 0x01010101u;+}+// 8 bytes of a codebook entry with the sign byte `s` (broadcast) applied: bits 0-3 to .x, 4-7 to .y+__dpct_inline__ void signed8(uint32_t gx, uint32_t gy, uint32_t s, uint32_t &qx,+ uint32_t &qy) {+ const uint32_t m0 = dpct::vectorized_binary<sycl::uchar4>(+ s & 0x08040201u, 0, std::not_equal_to<>()),+ m1 = dpct::vectorized_binary<sycl::uchar4>(+ s & 0x80402010u, 0, std::not_equal_to<>());+ qx = dpct::vectorized_binary<sycl::uchar4>(gx ^ m0, m0, std::minus<>());+ qy = dpct::vectorized_binary<sycl::uchar4>(gy ^ m1, m1, std::minus<>());+}+#if defined(__HIPCC__)+// gfx11 (Aurora): the signs from a shared-memory table instead of the compare / subtract emulation. An entry (one per+// sign byte b; for the 7-bit sign formats per 7 bits, the parity bit folded in) is {m0, c0, m1, c1}: m = 0xFF in the+// bytes whose sign bit is set (bits 0-3 for .x, 4-7 for .y), c = m & 0x01010101. q = (g ^ m) + c is -g where the sign+// is set - the two's complement, byte-wise - and g elsewhere; no byte carries into the next, because no codebook entry+// has a zero byte (256 - g with g in 1..127; the grids' bytes are 1..62), so it is the bytes signed8 gives.+__device__ __forceinline__ void signed8t(uint32_t gx, uint32_t gy, const uint4 sg, uint32_t& qx, uint32_t& qy) {+ qx = (gx ^ sg.x) + sg.y;+ qy = (gy ^ sg.z) + sg.w;+}+__host__ __device__ constexpr int sign_entries(int t) { return t == T_IQ2_S || t == T_IQ3_S ? 256 : 128; }+__device__ __forceinline__ uint4 sign_entry(int i, bool parity) {+ uint32_t b = (uint32_t) i;+ if (parity) b ^= (__popc(b) & 1) << 7;+ const uint32_t m0 = __vcmpne4(((b & 15) * 0x01010101u) & 0x08040201u, 0),+ m1 = __vcmpne4(((b >> 4) * 0x01010101u) & 0x08040201u, 0);+ return make_uint4(m0, m0 & 0x01010101u, m1, m1 & 0x01010101u);+}+#endif+// 8 nibbles of q4 through a 16-entry int8 table (4 words): the low nibbles' values in .x, the high ones' in .y+// W (X5): direct-selector form on gfx: p = low 3 bits of each nibble picks within the table half, bit 3 picks the half;+// exhaustively bit-exact over all 2^32 inputs (X5). Disable with -DSTRATA_W_NO_T16.+#if defined(__HIPCC__) && !defined(STRATA_W_NO_T16)+__device__ __forceinline__ uint32_t table16_one(uint32_t x, const uint32_t (&t)[4]) {+ const uint32_t p = x & 0x07070707u;+ const uint32_t a = __builtin_amdgcn_perm(t[1], t[0], p), b = __builtin_amdgcn_perm(t[3], t[2], p);+ return __builtin_amdgcn_perm(b, a, ((x >> 1) & 0x04040404u) | 0x03020100u);+}+__device__ __forceinline__ void table16(uint32_t q4, const uint32_t (&t)[4], uint32_t& lo, uint32_t& hi) {+ lo = table16_one(q4, t);+ hi = table16_one(q4 >> 4, t);+}+#else+__dpct_inline__ void table16(uint32_t q4, const uint32_t (&t)[4], uint32_t &lo,+ uint32_t &hi) {+ uint32_t tmp[2];+ const uint32_t sel = 0x32103210u | ((q4 & 0x88888888u) >> 1);+#pragma unroll+ for (int i = 0; i < 2; ++i) {+ const uint32_t sh = 16 * i;+ const uint32_t l = dpct::byte_level_permute(t[0], t[1], q4 >> sh),+ h = dpct::byte_level_permute(t[2], t[3], q4 >> sh);+ tmp[i] = dpct::byte_level_permute(l, h, sel >> sh);+ }+ lo = dpct::byte_level_permute(tmp[0], tmp[1], 0x6420);+ hi = dpct::byte_level_permute(tmp[0], tmp[1], 0x7531);+}+#endif++// Raw bytes of sub-block `ib` of the block at `bp` (IQ: the 256-value super-block, ib 0..7; Q2_0: the 64-value block,+// ib 0..1; IQ4_NL: the 32-value block).+// 32 bits at a 2-byte aligned address (one load when it is 4-byte aligned)+__dpct_inline__ uint32_t ld32a(const uint8_t *p) {+ return ((uintptr_t) p & 3) == 0 ? *(const uint32_t*) p : ld32(p);+}+template <int T, int NW>+__dpct_inline__ void load_unit(const uint8_t *bp, int ib, uint32_t (&w)[NW]) {+ static_assert(NW >= raw_words(T), "raw words");+ if constexpr (T == T_IQ2_XXS) {+ w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld16(bp);+ } else if constexpr (T == T_IQ2_XS) {+ w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld16(bp) | ((uint32_t) bp[66 + ib] << 16);+ } else if constexpr (T == T_IQ2_S) {+ w[0] = ld32(bp + 2 + 4 * ib); w[1] = ld32(bp + 34 + 4 * ib);+ w[2] = ld16(bp) | ((uint32_t) bp[66 + ib] << 16) | ((uint32_t) bp[74 + ib] << 24);+ } else if constexpr (T == T_IQ3_XXS) {+ w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld32(bp + 66 + 4 * ib); w[3] = ld16(bp);+ } else if constexpr (T == T_IQ3_S) {+ w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld32(bp + 74 + 4 * ib);+ w[3] = ld16(bp) | ((uint32_t) bp[66 + ib] << 16) | ((uint32_t) ((bp[106 + ib / 2] >> (4 * (ib & 1))) & 15) << 24);+ } else if constexpr (T == T_IQ4_XS) {+#pragma unroll+ for (int k = 0; k < 4; ++k) w[k] = ld32(bp + 8 + 16 * ib + 4 * k);+ const uint32_t ls = ((bp[4 + ib / 2] >> (4 * (ib & 1))) & 15) | (((ld16(bp + 2) >> (2 * ib)) & 3) << 4);+ w[4] = ld16(bp) | (ls << 16);+ } else if constexpr (T == T_IQ4_NL) {+#pragma unroll+ for (int k = 0; k < 4; ++k) w[k] = ld32(bp + 2 + 4 * k);+ w[4] = ld16(bp);+ } else if constexpr (T == T_Q4_K || T == T_Q5_K) {+ // qs: 32 bytes of the sub-block pair (ib / 2), the nibble chosen in convert; w[8] = d | dmin << 16; w[9]: the+ // scale/min bytes (get_scale_min_k4's: ib < 4: sc[ib], sc[ib + 4]; else sc[ib + 4], sc[ib - 4], sc[ib]), ib << 24+ constexpr int QS = T == T_Q4_K ? 16 : 48;+ const uint8_t* q = bp + QS + 32 * (ib >> 1);+#pragma unroll+ for (int k = 0; k < 8; ++k) w[k] = ld32a(q + 4 * k);+ w[8] = ld32a(bp);+ const uint8_t* sc = bp + 4;+ w[9] = ib < 4 ? (uint32_t) sc[ib] | ((uint32_t) sc[ib + 4] << 8)+ : (uint32_t) sc[ib + 4] | ((uint32_t) sc[ib - 4] << 8) | ((uint32_t) sc[ib] << 16);+ w[9] |= (uint32_t) ib << 24;+ if constexpr (T == T_Q5_K) {+#pragma unroll+ for (int k = 0; k < 8; ++k) w[10 + k] = ld32a(bp + 16 + 4 * k); // qh+ }+ } else if constexpr (T == T_Q5_1) { // d, m, qh, qs[16]+#pragma unroll+ for (int k = 0; k < 4; ++k) w[k] = ld32a(bp + 8 + 4 * k);+ w[4] = ld32a(bp + 4);+ w[5] = ld32a(bp);+ } else if constexpr (T == T_Q8_0) { // d, qs[32]+#pragma unroll+ for (int k = 0; k < 8; ++k) w[k] = ld32(bp + 2 + 4 * k);+ w[8] = ld16(bp);+ } else { // Q2_0+ w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld16(bp);+ }+}++// The sub-block as 32 int8 (q[0..7], natural order) and its scales (s0: values 0-15, s1: 16-31).+template <int T, int NW>+/*+DPCT1110: The total declared local variable size in device function convert+exceeds 128 bytes and may cause high register pressure. Consult with your+hardware vendor to find the total register size available and adjust the code,+or use smaller sub-group size to avoid high register pressure.+*/+__dpct_inline__ void convert(+ const uint32_t (&w)[NW], const uint8_t *grid, const uint32_t (&kv)[4],+ uint32_t (&q)[8], float &s0, float &s1, const sycl::uint4 *sgn = nullptr) {+ if constexpr (T == T_Q4_K || T == T_Q5_K) {+ const int ib = (int) (w[9] >> 24), sh = 4 * (ib & 1);+ uint32_t sc, mn;+ if (ib < 4) { sc = w[9] & 63; mn = (w[9] >> 8) & 63; }+ else {+ sc = ((w[9] & 0xF) | (((w[9] >> 8) & 0xC0) >> 2)); // sc[ib + 4] & 15 | (sc[ib - 4] >> 6) << 4+ mn = (((w[9]) >> 4) & 0xF) | (((w[9] >> 16) & 0xC0) >> 2); // sc[ib + 4] >> 4 | (sc[ib] >> 6) << 4+ }+#pragma unroll+ for (int k = 0; k < 8; ++k) {+ q[k] = (w[k] >> sh) & 0x0F0F0F0Fu;+ if constexpr (T == T_Q5_K) q[k] |= ((w[10 + k] >> ib) & 0x01010101u) << 4;+ }+ s0 = half_at(w[8]) * (float) sc;+ s1 = -(half_at(w[8] >> 16) * (float) mn);+ } else if constexpr (T == T_Q5_1) {+#pragma unroll+ for (int k = 0; k < 4; ++k) {+ const uint32_t lo = ((w[4] >> (4 * k)) & 0xF) * 0x00204081u, hi = ((w[4] >> (16 + 4 * k)) & 0xF) * 0x00204081u;+ q[k] = (w[k] & 0x0F0F0F0Fu) | ((lo & 0x01010101u) << 4);+ q[4 + k] = ((w[k] >> 4) & 0x0F0F0F0Fu) | ((hi & 0x01010101u) << 4);+ }+ s0 = half_at(w[5]);+ s1 = half_at(w[5] >> 16);+ } else if constexpr (T == T_Q8_0) {+#pragma unroll+ for (int k = 0; k < 8; ++k) q[k] = w[k];+ s0 = s1 = half_at(w[8]);+ } else if constexpr (T == T_IQ2_XXS) {+ const sycl::uint2 *g = (const sycl::uint2 *)grid;+#pragma unroll+ for (int l = 0; l < 4; ++l) {+ const sycl::uint2 e = g[(w[0] >> (8 * l)) & 255];+#if defined(__HIPCC__)+ signed8t(e.x, e.y, sgn[(w[1] >> (7 * l)) & 127], q[2 * l], q[2 * l + 1]);+#else+ signed8(e.x(), e.y(), unpack_ksigns(w[1] >> (7 * l)), q[2 * l],+ q[2 * l + 1]);+#endif+ }+ s0 = s1 = half_at(w[2]) * (float) ((w[1] >> 27) | 1) * 0.125f;+ } else if constexpr (T == T_IQ2_XS) {+ const sycl::uint2 *g = (const sycl::uint2 *)grid;+#pragma unroll+ for (int l = 0; l < 4; ++l) {+ const uint32_t c = (w[l >> 1] >> (16 * (l & 1))) & 0xFFFF;+ const sycl::uint2 e = g[c & 511];+#if defined(__HIPCC__)+ signed8t(e.x, e.y, sgn[(c >> 9) & 127], q[2 * l], q[2 * l + 1]);+#else+ signed8(e.x(), e.y(), unpack_ksigns(c >> 9), q[2 * l],+ q[2 * l + 1]);+#endif+ }+ const float d = half_at(w[2]);+ const uint32_t sc = w[2] >> 16;+ s0 = d * (float) (2 * (sc & 15) + 1) * 0.125f;+ s1 = d * (float) (2 * ((sc >> 4) & 15) + 1) * 0.125f;+ } else if constexpr (T == T_IQ2_S) {+ const sycl::uint2 *g = (const sycl::uint2 *)grid;+ const uint32_t qh = (w[2] >> 16) & 255;+#pragma unroll+ for (int l = 0; l < 4; ++l) {+ const sycl::uint2 e =+ g[((w[0] >> (8 * l)) & 255) | ((qh << (8 - 2 * l)) & 0x300)];+#if defined(__HIPCC__)+ signed8t(e.x, e.y, sgn[(w[1] >> (8 * l)) & 255], q[2 * l], q[2 * l + 1]);+#else+ signed8(e.x(), e.y(), ((w[1] >> (8 * l)) & 255) * 0x01010101u,+ q[2 * l], q[2 * l + 1]);+#endif+ }+ const float d = half_at(w[2]);+ const uint32_t sc = w[2] >> 24;+ s0 = d * (float) (2 * (sc & 15) + 1) * 0.125f;+ s1 = d * (float) (2 * (sc >> 4) + 1) * 0.125f;+ } else if constexpr (T == T_IQ3_XXS) {+ const uint32_t* g = (const uint32_t*) grid;+#pragma unroll+ for (int l = 0; l < 4; ++l) {+ const uint32_t i0 = (w[l >> 1] >> (16 * (l & 1))) & 255, i1 = (w[l >> 1] >> (16 * (l & 1) + 8)) & 255;+#if defined(__HIPCC__)+ signed8t(g[i0], g[i1], sgn[(w[2] >> (7 * l)) & 127], q[2 * l], q[2 * l + 1]);+#else+ signed8(g[i0], g[i1], unpack_ksigns(w[2] >> (7 * l)), q[2 * l], q[2 * l + 1]);+#endif+ }+ s0 = s1 = half_at(w[3]) * (float) (2 * (w[2] >> 28) + 1) * 0.25f;+ } else if constexpr (T == T_IQ3_S) {+ const uint32_t* g = (const uint32_t*) grid;+ const uint32_t qh = (w[3] >> 16) & 255;+#pragma unroll+ for (int l = 0; l < 4; ++l) {+ const uint32_t i0 = (w[l >> 1] >> (16 * (l & 1))) & 255, i1 = (w[l >> 1] >> (16 * (l & 1) + 8)) & 255;+#if defined(__HIPCC__)+ signed8t(g[i0 | ((qh << (8 - 2 * l)) & 256)], g[i1 | ((qh << (7 - 2 * l)) & 256)],+ sgn[(w[2] >> (8 * l)) & 255], q[2 * l], q[2 * l + 1]);+#else+ signed8(g[i0 | ((qh << (8 - 2 * l)) & 256)], g[i1 | ((qh << (7 - 2 * l)) & 256)],+ ((w[2] >> (8 * l)) & 255) * 0x01010101u, q[2 * l], q[2 * l + 1]);+#endif+ }+ s0 = s1 = half_at(w[3]) * (float) (1 + 2 * (w[3] >> 24));+ } else if constexpr (T == T_IQ4_XS || T == T_IQ4_NL) {+#pragma unroll+ for (int k = 0; k < 4; ++k) table16(w[k], kv, q[k], q[4 + k]);+ s0 = s1 = T == T_IQ4_XS ? half_at(w[4]) * (float) ((int) (w[4] >> 16) - 32) : half_at(w[4]);+ } else { // Q2_0: code - 1 via a byte table {-1, 0, 1, 2}+#pragma unroll+ for (int h = 0; h < 4; ++h) {+ const uint32_t c = (w[h >> 1] >> (16 * (h & 1))) & 0xFFFF;+ const uint32_t qe =+ dpct::byte_level_permute(0x020100FFu, 0x020100FFu, c & 0x7777);+ const uint32_t qo = dpct::byte_level_permute(+ 0x020100FFu, 0x020100FFu, (c >> 2) & 0x7777);+ q[2 * h] = dpct::byte_level_permute(qe, qo, 0x5140);+ q[2 * h + 1] = dpct::byte_level_permute(qe, qo, 0x7362);+ }+ s0 = s1 = half_at(w[2]);+ }+}++template <int T>+__dpct_inline__ const void *grid_src(+ const uint64_t *iq2xxs_grid, const uint64_t *iq2xs_grid,+ const uint64_t *iq2s_grid, const uint32_t *iq3xxs_grid,+ const uint32_t *iq3s_grid) {+ if constexpr (T == T_IQ2_XXS) return iq2xxs_grid;+ else if constexpr (T == T_IQ2_XS) return iq2xs_grid;+ else if constexpr (T == T_IQ2_S) return iq2s_grid;+ else if constexpr (T == T_IQ3_XXS) return iq3xxs_grid;+ else if constexpr (T == T_IQ3_S) return iq3s_grid;+ else return nullptr;+}+#endif++// One work item = (TR routed rows of expert e - one or two of group()'s 64-row tiles -, a block of WR weight rows);+// a persistent grid walks the batch's items. GU: gate/up rows of WR / 2 features (format WT) against the rows'+// tokens' activations, SwiGLU, H to int8 per 32 features into `out`. !GU: down rows (format WT) against H, FP32 into+// `dm`. Warp (wf, wt): weight rows 64 wf.. as four m16 tiles (GU: a tile = 8 features, gate rows as mma rows 0-7 and+// up rows as 8-15, so a lane holds gate and up of one feature), routed rows 16 wt.. as two n8.+template <int WT, bool GU, int WW>+/*+DPCT1110: The total declared local variable size in device function+native_kernel exceeds 128 bytes and may cause high register pressure. Consult+with your hardware vendor to find the total register size available and adjust+the code, or use smaller sub-group size to avoid high register pressure.+*/+__dpct_inline__ void native_kernel(+ const Batch b, const NativeGeom geo, const Tables tb,+ const uint8_t *__restrict__ act, const int32_t *__restrict__ src,+ uint8_t *__restrict__ out, float *__restrict__ dm, uint8_t *dpct_local,+ uint64_t *iq2xxs_grid, uint64_t *iq2xs_grid, uint64_t *iq2s_grid,+ uint32_t *iq3xxs_grid, uint32_t *iq3s_grid, const int8_t *kvalues_iq4nl) {+#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP >= 800+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ constexpr int TR = tile_rows(WW), WR = weight_rows(WW);+ constexpr int WT_BYTES = WR * WLD, WS_FLOATS = WR * 4, ACT_STAGE = TR * AB;+ constexpr int NS = (GU ? GU_ROWS_K : D_ROWS_K) / 64; // 64-value stages along K+ constexpr int NFB = (GU ? 1280 : 2560) / WR; // weight-row blocks per tile+ constexpr int ACT_LD = NS * AB; // bytes per activation row: 3200 (a token), 800 (a row's H)+ constexpr int BS = block_bytes(WT);+ constexpr bool K16 = per16(WT);+ auto smem = (uint8_t *)dpct_local;+ uint8_t* wt = smem; // [2][WR][WLD] decoded int8 weights+ float* ws = (float*) (smem + 2 * WT_BYTES); // [2][WR][4] their scales per 16 values+ uint8_t* stages = (uint8_t*) (ws + 2 * WS_FLOATS); // [ASTAGES][TR][AB] activations+ int* srow = (int*) (stages + ASTAGES * ACT_STAGE); // [TR] the activation row of each tile row+ uint8_t* sgrid = (uint8_t*) (srow + TR); // the codebook++ const int tid = item_ct1.get_local_id(2), lane = tid & 31, warp = tid >> 5,+ g = lane >> 2, tig = lane & 3;+ const int wf = warp % WW, nb0 = 16 * (warp / WW);+ if constexpr (grid_bytes(WT) > 0) {+ const uint32_t *gs = (const uint32_t *)grid_src<WT>(+ iq2xxs_grid, iq2xs_grid, iq2s_grid, iq3xxs_grid, iq3s_grid);+#pragma unroll+ for (int i = tid; i < grid_bytes(WT) / 4;+ i += THREADS)((uint32_t *)sgrid)[i] = gs[i];+ }+ uint32_t kv[4] = {0, 0, 0, 0};+ if constexpr (WT == T_IQ4_XS || WT == T_IQ4_NL) {+#pragma unroll+ for (int k = 0; k < 16; ++k) kv[k >> 2] |= (uint32_t) (uint8_t) kvalues_iq4nl[k] << (8 * (k & 3));+ }+ // Local weight rows: m tile i of warp wf is rows 64 wf + 16 i.. (mma rows g and g + 8: rows +g and +8+g). For+ // gate/up a tile is 8 features, its gate rows then its up rows, so a lane holds gate and up of one feature. The+ // fragments come by ldmatrix: lane l gives the address of row (l & 7) of matrix l >> 3 - A: {rows 0-7, rows 8-15}+ // x {bytes 0-15, 16-31} of a 32-value chunk; B: {tokens nb0 + 0-7, + 8-15} x {bytes 0-15, 16-31}.+ const int lm = lane >> 3, l8 = lane & 7;+ const int a_off = (64 * wf + 8 * (lm & 1) + l8) * WLD + 16 * (lm >> 1);+ const int b_off = (nb0 + 8 * (lm >> 1) + l8) * AB + 16 * (lm & 1);+ // this thread's decode unit (the first 2 WR threads): local weight row ur, sub-block uj of each stage+ const bool dec = tid < 2 * WR;+ const int ur = dec ? tid >> 1 : 0, uj = tid & 1;+ const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB;+ for (int w = item_ct1.get_group(2); w < nwork;+ w += item_ct1.get_group_range(2)) {+ const sycl::int2 tl = tb.tiles[t0 + w / NFB];+ const int fb = w % NFB, e = tl.x(), row0 = tl.y();+ if ((row0 - tb.off[e]) % TR != 0) continue; // a 64-row tile inside an earlier item's TR rows+ const int nrows = sycl::min(TR, tb.off[e + 1] - row0);+ const uint8_t* blob = b.blob[e - b.e0];+ const int rbase = fb * WR;+ // local row ur: gate/up - feature (WR / 2) fb + 8 (ur >> 4) + (ur & 7), its up row when bit 3 is set+ const uint8_t* wrow = GU ? blob + ((ur & 8) ? geo.up_off : 0) ++ (size_t) (fb * (WR / 2) + 8 * (ur >> 4) + (ur & 7)) * geo.gu_row+ : blob + geo.down_off + (size_t) (rbase + ur) * geo.d_row;+ auto unit = [&](int s) -> const uint8_t* { // the block of stage s's sub-block+ if (GU) return wrow + (s >> 2) * BS;+ return WT == T_IQ4_NL ? wrow + (2 * s + uj) * BS : wrow + s * BS;+ };+ auto sub = [&](int s) { return GU ? 2 * (s & 3) + uj : uj; };+ // the weight bytes into L2 ahead of the register loads (one stage ahead only - less than a DRAM round trip):+ // gate/up PF super-blocks ahead (the row's two threads take a block's first and last line), down the whole row+ // slice at once (180 or 360 bytes a row)+ constexpr int PF = 2;+ auto prefetch_sb = [&](int sb) {+ if (dec && sb < GU_ROWS_K / 256) pf_l2(wrow + sb * BS + (uj ? BS - 1 : 0));+ };+ if (GU) {+#pragma unroll+ for (int sb = 0; sb < PF; ++sb) prefetch_sb(sb);+ } else if (dec) {+#pragma unroll+ for (size_t o = 128 * (size_t)uj; o < geo.d_row + 127; o += 256)+ pf_l2(wrow + dpct::min(o, geo.d_row - 1));+ }+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier(); // the previous item is done with the buffers+ if (tid < TR) srow[tid] = tid < nrows ? (GU ? src[row0 + tid] : row0 + tid) : -1;+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ 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.+ */+ item_ct1.barrier(); // srow+ // the rows past the item's end are not loaded: a warp entirely past it skips the products, and the columns+ // of a partial one are never written (no reduction mixes columns)+ auto load_act = [&](int s) {+ uint8_t* st = stages + (s % ASTAGES) * ACT_STAGE;+ for (int c = tid; c < TR * 5; c += THREADS) {+ const int r = c / 5, q = c % 5;+ if (r < nrows) cp16(st + r * AB + q * 16, act + (size_t) srow[r] * ACT_LD + s * AB + q * 16);+ }+ };+ auto put = [&](const uint32_t (&raw)[5], int buf) {+ if (!dec) return;+ uint32_t q[8];+ float s0, s1;+ convert<WT>(raw, sgrid, kv, q, s0, s1);+ sycl::uint4 *d =+ (sycl::uint4 *)(wt + buf * WT_BYTES + ur * WLD + 32 * uj);+ d[0] = sycl::uint4(q[0], q[1], q[2], q[3]);+ d[1] = sycl::uint4(q[4], q[5], q[6], q[7]);+ *(sycl::float2 *)(ws + buf * WS_FLOATS + ur * 4 + 2 * uj) =+ sycl::float2(s0, s1);+ };+#pragma unroll+ for (int s = 0; s < ASTAGES - 1; ++s) {+ if (s < NS) load_act(s);+ cp_commit();+ }+ uint32_t raw[5] = {0, 0, 0, 0, 0};+ if (dec) load_unit<WT>(unit(0), sub(0), raw);+ put(raw, 0);+ if (dec) load_unit<WT>(unit(1), sub(1), raw);+ // a warp whose rows are all past the tile's end only takes part in the loads+ const bool on0 = nb0 < nrows, on1 = nb0 + 8 < nrows;+ float acc[4][2][4];+#pragma unroll+ for (int i = 0; i < 4; ++i)+#pragma unroll+ for (int n = 0; n < 2; ++n)+#pragma unroll+ for (int q = 0; q < 4; ++q) acc[i][n][q] = 0.0f;+ for (int s = 0; s < NS; ++s) {+ cp_wait<ASTAGES - 2>();+ /*+ DPCT1118: SYCL group functions and algorithms must be+ encountered in converged control flow. You may need to adjust the+ code.+ */+ /*+ 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.+ */+ item_ct1.barrier();+ if (s + ASTAGES - 1 < NS) load_act(s + ASTAGES - 1);+ cp_commit();+ if (GU && (s & 3) == 0) prefetch_sb((s >> 2) + PF);+ if (on0) {+ const uint8_t* W = wt + (s & 1) * WT_BYTES;+ const float* S = ws + (s & 1) * WS_FLOATS;+ const uint8_t* sa = stages + (s % ASTAGES) * ACT_STAGE;+ // the stage's scales: per weight row 4 (per 16 values), per routed row 2 (per 32)+ sycl::float2 dx[2][2]; // [n8 tile][column 2 tig + cc]+#pragma unroll+ for (int n = 0; n < 2; ++n)+#pragma unroll+ for (int cc = 0; cc < 2; ++cc) dx[n][cc] =+ *(const sycl::float2 *)(sa ++ (nb0 + 8 * n + 2 * tig + cc) *+ AB ++ 64);+#pragma unroll+ for (int h = 0; h < 2; ++h) { // the stage's two 32-value halves+ uint32_t bq[4]; // {n0 bytes 0-15, n0 16-31, n1 0-15, n1 16-31}+ ldsm4(bq, sa + b_off + 32 * h);+#pragma unroll+ for (int i = 0; i < 4; ++i) {+ uint32_t a[4]; // {rows g, g + 8} x {bytes 0-15, 16-31}+ ldsm4(a, W + a_off + 16 * i * WLD + 32 * h);+ const sycl::float2 swa =+ *(const sycl::float2 *)(S ++ (64 * wf + 16 * i + g) * 4 ++ 2 * h);+ const sycl::float2 swb =+ *(const sycl::float2 *)(S ++ (64 * wf + 16 * i + 8 + g) *+ 4 ++ 2 * h);+ const float wa0 = swa.x(), wa1 = swa.y(), wb0 = swb.x(),+ wb1 = swb.y();+#pragma unroll+ for (int n = 0; n < 2; ++n) {+ if (n == 1 && !on1) break;+ if constexpr (K16) {+ // a scale per 16 weights: the two halves' dots, each times its scale, then d_x+ int d0[4], d1[4];+ mma16(d0, a[0], a[1], bq[2 * n]);+ mma16(d1, a[2], a[3], bq[2 * n + 1]);+#pragma unroll+ for (int q = 0; q < 4; ++q) {+ const float v = sycl::fma(+ (float)(q < 2 ? wa1 : wb1), dotf(d1[q]),+ (q < 2 ? wa0 : wb0) * dotf(d0[q]));+ acc[i][n][q] = sycl::fma(+ h ? dx[n][q & 1].y() : dx[n][q & 1].x(),+ (float)v, acc[i][n][q]);+ }+ } else {+ int d[4];+ mma32(d, a, bq[2 * n], bq[2 * n + 1]);+#pragma unroll+ for (int q = 0; q < 4; ++q) {+ const float p = (q < 2 ? wa0 : wb0) *+ (h ? dx[n][q & 1].y()+ : dx[n][q & 1].x());+ acc[i][n][q] = sycl::fma(+ (float)p, dotf(d[q]), acc[i][n][q]);+ }+ }+ }+ }+ }+ }+ // the next stage's weights (into the other buffer, read after the next barrier). (Decoding them before+ // this stage's products instead was slower on the RTX 5070: a layer of 2048 / 3584 / 8192 tokens, IQ2_S+ // 5.2 / 9.5 / 17.5 ms -> 6.0 / 10.2 / 18.3.)+ if (s + 1 < NS) {+ put(raw, (s + 1) & 1);+ if (dec && s + 2 < NS) load_unit<WT>(unit(s + 2), sub(s + 2), raw);+ }+ }+ if (!on0) continue;+ if (GU) {+ // SwiGLU of feature (WR / 2) fb + 32 wf + 8 i + g (lane g of m tile i: rows 64 wf + 16 i + g and + 8), tile+ // rows nb0 + 8 n + 2 tig + c; H to int8 per row over the warp's 32 features (one 32-value half-block of the+ // down product's K)+ const int blk = WW * fb + wf;+#pragma unroll+ for (int n = 0; n < 2; ++n) {+ if (n == 1 && !on1) break;+#pragma unroll+ for (int c = 0; c < 2; ++c) {+ float h[4], am = 0.0f;+#pragma unroll+ for (int i = 0; i < 4; ++i) {+ const float gt = acc[i][n][c], up = acc[i][n][2 + c];+ h[i] = gt / (1.0f + sycl::native::exp(-gt)) * up;+ am = sycl::fmax(am, sycl::fabs(h[i]));+ }+#pragma unroll+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the+ experimental feature masked sub_group function which may not+ be supported by all compilers or runtimes. You may need to+ adjust the code.+ */+ for (int o = 4; o < 32; o <<= 1) am = sycl::fmax(+ am,+ dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu,+ sycl::ext::oneapi::this_work_item::get_sub_group(),+ am, o));+ const float inv = am > 0.0f ? 127.0f / am : 0.0f;+ const int r = nb0 + 8 * n + 2 * tig + c;+ if (r < nrows) {+ uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (blk >> 1) * AB;+ const int hh = blk & 1;+#pragma unroll+ for (int i = 0; i < 4; ++i) o[32 * hh + 8 * i + g] =+ (uint8_t)(int8_t)sycl::vec<float, 1>{(h[i] * inv)}+ .convert<int, sycl::rounding_mode::rte>()[0];+ if (g == 0) *(float*) (o + 64 + 4 * hh) = am / 127.0f;+ }+ }+ }+ } else {+#pragma unroll+ for (int i = 0; i < 4; ++i)+#pragma unroll+ for (int n = 0; n < 2; ++n) {+ if (n == 1 && !on1) break;+#pragma unroll+ for (int q = 0; q < 4; ++q) {+ const int r = nb0 + 8 * n + 2 * tig + (q & 1);+ if (r < nrows) dm[(size_t) (row0 + r) * 2560 + rbase + 64 * wf + 16 * i + 8 * (q >> 1) + g] = acc[i][n][q];+ }+ }+ }+ }+#endif+}++#if defined(__HIPCC__)+// ---- Aurora (S23): the native packs' fused experts on gfx11 (RDNA3 / RDNA3.5) matrix cores, v_wmma_i32_16x16x16_iu8+// (wave32). The CUDA kernel's arithmetic: a 32-value sub-block decoded to int8 (load_unit / convert above) and its+// scales; per 32 values the int32 dot starts from MAGIC (the C operand), so as_float(d) - 1.5 * 2^23 is the dot; the+// formats with a scale per 16 values take each 16-value k-step's dot alone. Fragments (gfx11): A lane l holds the 16+// k of row l % 16 (lanes 16..31 repeat lanes 0..15), B lane l the 16 k of column l % 16, C/D lane l holds+// D[2i + l / 16][l % 16]. Both operands are in natural order: the decoded weights (LDS, double-buffered) and the+// activations (quant_act_nat_kernel; read by each lane from global/L2, a stage ahead).+// A work item = NW_ROWS weight rows x a 64-row tile; 8 waves: 4 along the weight rows (32 each) x 2 along the tile+// (32 each), each 2 x 2 WMMA tiles. Gate/up: local row r is feature r / 2, its gate (r even) or up (r odd) row, so a+// lane pair l, l + 16 holds gate and up of one feature.+#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__)+#define STRATA_NAT_W11 1+#else+#define STRATA_NAT_W11 0+#endif+typedef int nw_i4 __attribute__((ext_vector_type(4)));+typedef int nw_i8 __attribute__((ext_vector_type(8)));+constexpr int NW_ROWS = 128;+constexpr int NW_THREADS = 256;++__device__ __forceinline__ nw_i8 nw_wmma(nw_i4 a, nw_i4 b, nw_i8 c) {+#if STRATA_NAT_W11+ return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(true, a, true, b, c, false);+#else+ __builtin_trap();+ return c;+#endif+}+__device__ __forceinline__ nw_i4 nw_u4(uint4 v) { return nw_i4{(int) v.x, (int) v.y, (int) v.z, (int) v.w}; }++// W (X1): ALIAS = the H tile lives on the weight buffers (one extra barrier); LB > 0 = amdgpu_waves_per_eu(LB) (VGPR cap).+// Disable both with -DSTRATA_W_NO_OCC (the launch sites then use <WT, GU, false, 0> and grid factor wgp_blocks).+template <int WT, bool GU, bool ALIAS = false, int LB = 0>+__global__ void __launch_bounds__(NW_THREADS) __attribute__((amdgpu_waves_per_eu(LB > 0 ? LB : 1)))+native_w11_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_t* __restrict__ act,+ const int32_t* __restrict__ src, uint8_t* __restrict__ out, float* __restrict__ dm) {+#if STRATA_NAT_W11+ constexpr int NS = (GU ? GU_ROWS_K : D_ROWS_K) / 64; // 64-value stages along K+ constexpr int NFB = (GU ? 1280 : 2560) / NW_ROWS; // work items per tile+ constexpr int ACT_LD = NS * AB;+ constexpr int BS = block_bytes(WT);+ constexpr bool K16 = per16(WT);+ constexpr int GB = grid_bytes(WT) > 0 ? grid_bytes(WT) : 16;+ __shared__ __align__(16) uint8_t wtbuf[2 * NW_ROWS * WLD];+ uint8_t(*wt)[NW_ROWS][WLD] = reinterpret_cast<uint8_t(*)[NW_ROWS][WLD]>(wtbuf);+ __shared__ __align__(16) float ws[2][NW_ROWS][4]; // their scales per 16 values+ __shared__ __align__(16) uint8_t sgrid[GB];+ constexpr int SGN = (WT == T_IQ2_XXS || WT == T_IQ2_XS || WT == T_IQ2_S || WT == T_IQ3_XXS || WT == T_IQ3_S)+ ? sign_entries(WT) : 1;+ __shared__ __align__(16) uint4 ssign[SGN]; // the signs of a sign byte, as byte masks+ __shared__ int srow[kTileRows];+ __shared__ float hs_sep[(GU && !ALIAS) ? kTileRows : 1][65];+ static_assert(!ALIAS || (size_t) kTileRows * 65 * 4 <= (size_t) 2 * NW_ROWS * WLD, "H tile must fit the weight buffers");+ float(*hs)[65] = ALIAS ? reinterpret_cast<float(*)[65]>(wtbuf) : hs_sep;+ const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;+ const int wm = wave & 3, wn = wave >> 2, l16 = lane & 15, hi = lane >> 4;+ if constexpr (grid_bytes(WT) > 0) {+ const uint32_t* gs = (const uint32_t*) grid_src<WT>();+ for (int i = tid; i < grid_bytes(WT) / 4; i += NW_THREADS) ((uint32_t*) sgrid)[i] = gs[i];+ }+ if constexpr (SGN > 1) {+ for (int i = tid; i < SGN; i += NW_THREADS) ssign[i] = sign_entry(i, SGN == 128);+ }+ uint32_t kv[4] = {0, 0, 0, 0};+ if constexpr (WT == T_IQ4_XS || WT == T_IQ4_NL) {+#pragma unroll+ for (int k = 0; k < 16; ++k) kv[k >> 2] |= (uint32_t) (uint8_t) kvalues_iq4nl[k] << (8 * (k & 3));+ }+ const int ur = tid >> 1, uj = tid & 1; // this thread's decode unit: row ur, sub-block uj+ const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB;+ for (int w = blockIdx.x; w < nwork; w += gridDim.x) {+ const int2 tl = tb.tiles[t0 + w / NFB];+ const int fb = w % NFB, e = tl.x, row0 = tl.y, nrows = min(kTileRows, tb.off[e + 1] - row0);+ const uint8_t* blob = b.blob[e - b.e0];+ const int rbase = fb * NW_ROWS;+ const uint8_t* wrow = GU ? blob + ((ur & 1) ? geo.up_off : 0) + (size_t) (fb * (NW_ROWS / 2) + (ur >> 1)) * geo.gu_row+ : blob + geo.down_off + (size_t) (rbase + ur) * geo.d_row;+ auto unit = [&](int s) -> const uint8_t* {+ if (GU) return wrow + (s >> 2) * BS;+ return (WT == T_IQ4_NL || WT == T_Q5_1 || WT == T_Q8_0) ? wrow + (2 * s + uj) * BS : wrow + s * BS;+ };+ auto sub = [&](int s) { return GU ? 2 * (s & 3) + uj : uj; };+ auto put = [&](const uint32_t (&raw)[raw_words(WT)], int buf) {+ uint32_t q[8];+ float s0, s1;+ convert<WT>(raw, sgrid, kv, q, s0, s1, ssign);+ uint4* d = (uint4*) &wt[buf][ur][32 * uj];+ d[0] = make_uint4(q[0], q[1], q[2], q[3]);+ d[1] = make_uint4(q[4], q[5], q[6], q[7]);+ *(float2*) &ws[buf][ur][2 * uj] = make_float2(s0, s1);+ };+ __syncthreads(); // the previous item is done with the buffers+ if (tid < kTileRows) {+ const int r = row0 + min(tid, nrows - 1); // rows past the tile's end repeat its last one+ srow[tid] = GU ? src[r] : r;+ }+ uint32_t raw[raw_words(WT)] = {};+ load_unit<WT>(unit(0), sub(0), raw);+ put(raw, 0);+ if (NS > 1) load_unit<WT>(unit(1), sub(1), raw);+ __syncthreads(); // srow+ const bool on = 32 * wn < nrows;+ const uint8_t* brow[2];+#pragma unroll+ for (int nt = 0; nt < 2; ++nt) brow[nt] = act + (size_t) srow[32 * wn + 16 * nt + l16] * ACT_LD;+ float acc[2][2][8];+#pragma unroll+ for (int mt = 0; mt < 2; ++mt)+#pragma unroll+ for (int nt = 0; nt < 2; ++nt)+#pragma unroll+ for (int i = 0; i < 8; ++i) acc[mt][nt][i] = 0.0f;+ uint4 bq[2][4];+ float2 bx[2], bsum[2]; // the activation scales, and (the formats with a minimum) the codes' sums per 32 values+ auto fetch_b = [&](int s, uint4 (&q)[2][4], float2 (&x)[2], float2 (&sm)[2]) {+#pragma unroll+ for (int nt = 0; nt < 2; ++nt) {+ const uint4* p = reinterpret_cast<const uint4*>(brow[nt] + s * AB);+ q[nt][0] = p[0]; q[nt][1] = p[1]; q[nt][2] = p[2]; q[nt][3] = p[3];+ x[nt] = *reinterpret_cast<const float2*>(brow[nt] + s * AB + 64);+ if constexpr (has_min(WT)) sm[nt] = *reinterpret_cast<const float2*>(brow[nt] + s * AB + 72);+ else sm[nt] = make_float2(0.0f, 0.0f);+ }+ };+ if (on) fetch_b(0, bq, bx, bsum);+ for (int s = 0; s < NS; ++s) {+ __syncthreads(); // stage s's weights are in buffer s & 1+ uint4 nbq[2][4];+ float2 nbx[2], nbsum[2];+ if (on && s + 1 < NS) fetch_b(s + 1, nbq, nbx, nbsum);+ if (on) {+ const int bf = s & 1;+#pragma unroll+ for (int h = 0; h < 2; ++h) {+#pragma unroll+ for (int mt = 0; mt < 2; ++mt) {+ const int rb = 32 * wm + 16 * mt;+ const uint4* ap = reinterpret_cast<const uint4*>(&wt[bf][rb + l16][32 * h]);+ const nw_i4 A0 = nw_u4(ap[0]), A1 = nw_u4(ap[1]);+ float w0[8], w1[8];+#pragma unroll+ for (int i = 0; i < 8; ++i) {+ const float2 sw = *reinterpret_cast<const float2*>(&ws[bf][rb + 2 * i + hi][2 * h]);+ w0[i] = sw.x; w1[i] = sw.y;+ }+#pragma unroll+ for (int nt = 0; nt < 2; ++nt) {+ const float dx = h ? bx[nt].y : bx[nt].x;+ const nw_i4 B0 = nw_u4(bq[nt][2 * h]), B1 = nw_u4(bq[nt][2 * h + 1]);+ const nw_i8 m = nw_i8{MAGIC, MAGIC, MAGIC, MAGIC, MAGIC, MAGIC, MAGIC, MAGIC};+ if constexpr (K16) {+ const nw_i8 d0 = nw_wmma(A0, B0, m), d1 = nw_wmma(A1, B1, m);+#pragma unroll+ for (int i = 0; i < 8; ++i) {+ const float v = fmaf(w1[i], dotf(d1[i]), w0[i] * dotf(d0[i]));+ acc[mt][nt][i] = fmaf(dx, v, acc[mt][nt][i]);+ }+ } else {+ const nw_i8 d = nw_wmma(A1, B1, nw_wmma(A0, B0, m));+#pragma unroll+ for (int i = 0; i < 8; ++i) {+ acc[mt][nt][i] = fmaf(w0[i] * dx, dotf(d[i]), acc[mt][nt][i]);+ if constexpr (has_min(WT)) acc[mt][nt][i] = fmaf(w1[i] * dx, h ? bsum[nt].y : bsum[nt].x, acc[mt][nt][i]);+ }+ }+ }+ }+ }+ }+ if (s + 1 < NS) {+ put(raw, (s + 1) & 1); // the other buffer: its readers passed this barrier+ if (s + 2 < NS) load_unit<WT>(unit(s + 2), sub(s + 2), raw);+ if (on) {+#pragma unroll+ for (int nt = 0; nt < 2; ++nt) {+ bx[nt] = nbx[nt];+ bsum[nt] = nbsum[nt];+#pragma unroll+ for (int j = 0; j < 4; ++j) bq[nt][j] = nbq[nt][j];+ }+ }+ }+ }+ if constexpr (GU) {+ if constexpr (ALIAS) __syncthreads(); // every wave is done reading the weight buffers+ if (on) {+#pragma unroll+ for (int mt = 0; mt < 2; ++mt)+#pragma unroll+ for (int nt = 0; nt < 2; ++nt)+#pragma unroll+ for (int i = 0; i < 8; ++i) {+ const float up = __shfl_xor_sync(0xffffffffu, acc[mt][nt][i], 16);+ const float gt = acc[mt][nt][i];+ if (hi == 0) hs[32 * wn + 16 * nt + l16][16 * wm + 8 * mt + i] = gt / (1.0f + __expf(-gt)) * up;+ }+ }+ __syncthreads();+ // H block fb (features 64 fb ..) to int8 per 32, natural order: a thread per (tile row, half)+ if (tid < 2 * kTileRows) {+ const int r = tid >> 1, hh = tid & 1;+ if (r < nrows) {+ float am = 0.0f;+#pragma unroll 8+ for (int j = 0; j < 32; ++j) am = fmaxf(am, fabsf(hs[r][32 * hh + j]));+ const float inv = am > 0.0f ? 127.0f / am : 0.0f;+ uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (size_t) fb * AB;+ uint32_t wd[8] = {};+ int csum = 0;+#pragma unroll+ for (int j = 0; j < 32; ++j) {+ const int c = __float2int_rn(hs[r][32 * hh + j] * inv);+ csum += c;+ wd[j >> 2] |= (uint32_t) (uint8_t) (int8_t) c << (8 * (j & 3));+ }+ uint4* o4 = reinterpret_cast<uint4*>(o + 32 * hh);+ o4[0] = make_uint4(wd[0], wd[1], wd[2], wd[3]);+ o4[1] = make_uint4(wd[4], wd[5], wd[6], wd[7]);+ *reinterpret_cast<float*>(o + 64 + 4 * hh) = am / 127.0f;+ *reinterpret_cast<float*>(o + 72 + 4 * hh) = (float) csum; // (the formats with a minimum)+ }+ }+ } else {+ if (on) {+#pragma unroll+ for (int mt = 0; mt < 2; ++mt)+#pragma unroll+ for (int nt = 0; nt < 2; ++nt) {+ const int r = 32 * wn + 16 * nt + l16;+ if (r < nrows) {+ float* d = dm + (size_t) (row0 + r) * 2560 + rbase + 32 * wm + 16 * mt + hi;+#pragma unroll+ for (int i = 0; i < 8; ++i) d[2 * i] = acc[mt][nt][i];+ }+ }+ }+ }+ }+#else+ __builtin_trap();+#endif+}+#endif // __HIPCC__++unsigned blocks(int64_t n, int per) { return (unsigned) ((n + per - 1) / per); }++// per device: whether every kernel here runs (sm_80+, device code in this build, fits), and their occupancy+struct DevInfo {+ bool done = false, ok = false;+ int sms = 0, occ = 1;+};+std::mutex g_mu;+DevInfo g_dev[32];++#if !defined(__HIPCC__)+template <int T, bool GU, int WW> bool setup_ww(int& occ) {+ dpct::kernel_function_info fa{};+ if (cudaFuncGetAttributes(&fa, native_kernel<T, GU, WW>) != 0 ||+ fa.ptxVersion < 80) return false;+ if (cudaFuncSetAttribute(native_kernel<T, GU, WW>,+ cudaFuncAttributeMaxDynamicSharedMemorySize,+ (int)smem_bytes(T, WW)) != 0)+ return false;+ int o = 0;+ if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(+ &o, native_kernel<T, GU, WW>, THREADS, smem_bytes(T, WW)) != 0 ||+ o < 1)+ return false;+ occ = std::min(occ, o);+ return true;+}+template <int T, bool GU> bool setup_one(int& occ) { return setup_ww<T, GU, 4>(occ) && setup_ww<T, GU, 2>(occ); }+#endif++#if defined(__HIPCC__)+// Resident blocks per multiprocessor for the gfx11 WMMA prompt-expert kernels' persistent grids. HIP counts a gfx11+// WGP (two CUs, which these kernels use as one in the default WGP mode) as one multiprocessor, and the occupancy query+// answers 1 block for these kernels where 2 run side by side - so the grid was half the GPU's room. gfx1151 (20+// WGPs), 8192 tokens x top 10, IQ3_S / IQ4_NL, one layer: 1 block per WGP 60.7 ms, 2 44.7, 3 49.9, 4 45.2 (the same+// work items and arithmetic: the results do not change). STRATA_PF_OCC=N sets the blocks per WGP (an experiment knob).+static int wgp_blocks(int occ) {+ static const int env = [] {+ const char* v = std::getenv("STRATA_PF_OCC");+ return v != nullptr ? std::atoi(v) : 0;+ }();+ return env > 0 ? env : 2 * std::max(occ, 1);+}+#endif+const DevInfo& dev_info() {+ int dev = 0;+ dev = dpct::get_current_device_id();+ std::lock_guard<std::mutex> lk(g_mu);+ DevInfo& d = g_dev[dev & 31];+ if (d.done) return d;+ d.done = true;+#if defined(STRATA_HIP_GFX906)+ // gfx906 reports compute capability 9.0 through HIP, but the mma.sync bodies above are CUDA sm_80+ only and+ // empty in a hipcc build: never available here (the prompt path keeps its own expert GEMMs)+ return d;+#elif defined(__HIPCC__)+ { // gfx11 with this build's code: the WMMA kernels (one occupancy for all: the same shape and LDS budget)+ cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev);+ cudaDeviceProp prop;+ hipFuncAttributes fa{};+ if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess || std::strncmp(prop.gcnArchName, "gfx11", 5) != 0 ||+ hipFuncGetAttributes(&fa, reinterpret_cast<const void*>(native_w11_kernel<T_IQ3_XXS, true>)) != hipSuccess) {+ cudaGetLastError();+ return d;+ }+ int o = 0;+ if (hipOccupancyMaxActiveBlocksPerMultiprocessor(&o, native_w11_kernel<T_IQ2_S, true>, NW_THREADS, 0) != hipSuccess)+ o = 0;+ d.ok = o >= 1;+ d.occ = d.ok ? o : 1;+ cudaGetLastError();+ return d;+ }+#else+ int major = 0;+ major = dpct::get_device(dev).get_major_version();+ d.sms = dpct::get_device(dev).get_max_compute_units();+ if (major < 8) return d;+ int occ = 1 << 20;+ d.ok = setup_one<T_IQ2_XXS, true>(occ) && setup_one<T_IQ2_XS, true>(occ) && setup_one<T_IQ2_S, true>(occ) &&+ setup_one<T_IQ3_XXS, true>(occ) && setup_one<T_IQ3_S, true>(occ) && setup_one<T_IQ4_XS, true>(occ) &&+ setup_one<T_Q2_0, false>(occ) && setup_one<T_IQ4_NL, false>(occ);+ d.occ = d.ok ? occ : 1;+ /*+ DPCT1026: The call to cudaGetLastError was removed because this+ functionality is redundant in SYCL.+ */+#endif+ return d;+}++// opt-in on top of STRATA_PF_FUSED=1: STRATA_PF_FUSED_KQ=1 takes UD-Q4_K_XL's formats (the output differs from the FP16+// expert path's at rounding level; KL-gated, see aurora_s23.md)+bool kq_on() {+ static const bool on = [] {+ const char* v = std::getenv("STRATA_PF_FUSED_KQ");+ return v != nullptr && v[0] == '1';+ }();+ return on;+}+bool gu_covered(int t) {+ return t == T_IQ2_XXS || t == T_IQ2_XS || t == T_IQ2_S || t == T_IQ3_XXS || t == T_IQ3_S || t == T_IQ4_XS+#if defined(__HIPCC__)+ || ((t == T_Q4_K || t == T_Q5_K) && kq_on()) // the gfx11 kernels only+#endif+ ;+}+bool d_covered(int t) {+ return t == T_Q2_0 || t == T_IQ4_NL+#if defined(__HIPCC__)+ || ((t == T_Q5_1 || t == T_Q8_0) && kq_on())+#endif+ ;+}++template <int T, bool GU>+void launch(int ww, unsigned grid, const Batch &b, const NativeGeom &g,+ const Tables &tb, const void *act, const int32_t *src, void *out,+ float *dm, dpct::queue_ptr s) {+ const uint8_t* a = (const uint8_t*) act;+ uint8_t* o = (uint8_t*) out;+ /*+ 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.+ Adjust the work-group size if needed.+ */+ if (ww == 4) {+ iq2xxs_grid.init(*s);+ iq2xs_grid.init(*s);+ iq2s_grid.init(*s);+ iq3xxs_grid.init(*s);+ iq3s_grid.init(*s);+ kvalues_iq4nl.init(*s);++ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ s->submit([&](sycl::handler &cgh) {+ auto iq2xxs_grid_ptr_ct1 = iq2xxs_grid.get_ptr();+ auto iq2xs_grid_ptr_ct1 = iq2xs_grid.get_ptr();+ auto iq2s_grid_ptr_ct1 = iq2s_grid.get_ptr();+ auto iq3xxs_grid_ptr_ct1 = iq3xxs_grid.get_ptr();+ auto iq3s_grid_ptr_ct1 = iq3s_grid.get_ptr();+ auto kvalues_iq4nl_ptr_ct1 = kvalues_iq4nl.get_ptr();++ sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(+ sycl::range(smem_bytes(T, 4)), cgh);++ cgh.parallel_for<dpct_kernel_name<+ class native_kernel_6643fb, dpct_kernel_scalar<T>,+ dpct_kernel_scalar<GU>, dpct_kernel_scalar<4>>>(+ sycl::nd_range<3>(sycl::range(1, 1, grid) *+ sycl::range(1, 1, THREADS),+ sycl::range(1, 1, THREADS)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ native_kernel<T, GU, 4>(+ b, g, tb, a, src, o, dm,+ dpct_local_acc_ct1+ .get_multi_ptr<+ sycl::access::decorated::no>()+ .get(),+ iq2xxs_grid_ptr_ct1, iq2xs_grid_ptr_ct1,+ iq2s_grid_ptr_ct1, iq3xxs_grid_ptr_ct1,+ iq3s_grid_ptr_ct1, kvalues_iq4nl_ptr_ct1);+ });+ });+ }+ /*+ 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. Adjust the work-group size if+ needed.+ */+ else {+ iq2xxs_grid.init(*s);+ iq2xs_grid.init(*s);+ iq2s_grid.init(*s);+ iq3xxs_grid.init(*s);+ iq3s_grid.init(*s);+ kvalues_iq4nl.init(*s);++ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ s->submit([&](sycl::handler &cgh) {+ auto iq2xxs_grid_ptr_ct1 = iq2xxs_grid.get_ptr();+ auto iq2xs_grid_ptr_ct1 = iq2xs_grid.get_ptr();+ auto iq2s_grid_ptr_ct1 = iq2s_grid.get_ptr();+ auto iq3xxs_grid_ptr_ct1 = iq3xxs_grid.get_ptr();+ auto iq3s_grid_ptr_ct1 = iq3s_grid.get_ptr();+ auto kvalues_iq4nl_ptr_ct1 = kvalues_iq4nl.get_ptr();++ sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(+ sycl::range(smem_bytes(T, 2)), cgh);++ cgh.parallel_for<dpct_kernel_name<+ class native_kernel_e6c346, dpct_kernel_scalar<T>,+ dpct_kernel_scalar<GU>, dpct_kernel_scalar<2>>>(+ sycl::nd_range<3>(sycl::range(1, 1, grid) *+ sycl::range(1, 1, THREADS),+ sycl::range(1, 1, THREADS)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ native_kernel<T, GU, 2>(+ b, g, tb, a, src, o, dm,+ dpct_local_acc_ct1+ .get_multi_ptr<+ sycl::access::decorated::no>()+ .get(),+ iq2xxs_grid_ptr_ct1, iq2xs_grid_ptr_ct1,+ iq2s_grid_ptr_ct1, iq3xxs_grid_ptr_ct1,+ iq3s_grid_ptr_ct1, kvalues_iq4nl_ptr_ct1);+ });+ });+ }+}++// The work item's shape for a layer of `n` routed rows over `n_expert` experts: 128 routed rows when an expert has+// about one such tile (56 to 112 rows on average), else 64. Measured on the RTX 5070 (tests/cuda/prefill_fused_iq_test,+// a layer of 2048 / 3584 / 8192 tokens, ms, 64 -> 128): IQ2_S 5.2 -> 6.7, 9.5 -> 9.3, 17.5 -> 19.5; IQ2_XXS 4.2 ->+// 5.8, 7.4 -> 7.6, 13.6 -> 16.5; IQ3_S 5.6 -> 6.6, 10.2 -> 8.8, 18.4 -> 19.0; IQ3_XXS 5.1 -> 6.3, 9.1 -> 8.3, 16.5 ->+// 17.5 (256 rows was slower still). STRATA_PF_FUSED_TILE=64|128 forces one.+int pick_ww(int64_t n, int n_expert) {+ static const int forced = [] {+ const char* v = std::getenv("STRATA_PF_FUSED_TILE");+ const int t = v ? std::atoi(v) : 0;+ return t == 64 ? 4 : t == 128 ? 2 : 0;+ }();+ if (forced) return forced;+ const double avg = (double) n / std::max(n_expert, 1);+ return avg > 56.0 && avg <= 112.0 ? 2 : 4;+}++} // namespace++bool native_supported(int gu_type, int d_type) {+ static const bool off = [] { // STRATA_PF_FUSED_NATIVE=0: the native packs keep MMQ under STRATA_PF_FUSED=1 (A/B)+ const char* v = std::getenv("STRATA_PF_FUSED_NATIVE");+ return v != nullptr && v[0] == '0';+ }();+ return !off && requested() && gu_covered(gu_type) && d_covered(d_type) && dev_info().ok; // opt-in (=1)+}++void quantize_act_native(const float* x, int64_t rows, int64_t cols, void* xa, void* stream) {+ if (rows <= 0) return;+ const int64_t nblk = rows * (cols / 64);+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<+ dpct_kernel_name<class quant_act_nat_kernel_7d58c5>>(+ sycl::nd_range<3>(sycl::range(1, 1, blocks(nblk, 8)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ quant_act_nat_kernel(x, nblk, (uint8_t *)xa);+ });+ }+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use the+ error codes. The cudaGetLastError function call was replaced with 0. You+ need to rewrite this code.+ */+ ck(0, "quantize_act_native");+}++void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n, const void* scratch, const void* xa,+ const int32_t* src, void* ha, float* dm, void* stream) {+ if (b.e1 <= b.e0 || n <= 0) return;+ const DevInfo& d = dev_info();+ if (!d.ok || !gu_covered(g.gu_type) || !d_covered(g.d_type)) {+ std::fprintf(stderr, "prefill fused experts (native): types %d / %d are not covered here\n", g.gu_type, g.d_type);+ std::exit(1);+ }+ const dpct::queue_ptr s = strata::q_of(stream);+ const Tables tb = tables(const_cast<void*>(scratch), n_expert);+#if defined(__HIPCC__)+ {+ const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0);+ // W (X1): LDS alias of the H tile + waves_per_eu(8) (192 VGPRs) + 4 blocks per WGP, only for the types whose+ // kernels do not spill under the cap (measured: gate/up IQ2_*, IQ3_*, IQ4_XS 0-5 regs; down IQ4_NL 11, Q8_0 / Q2_0 0;+ // Q4_K / Q5_K gate/up and Q5_1 down spill 100+ and keep the old launch).+#ifdef STRATA_W_NO_OCC+ const bool occ_gu = false, occ_d = false;+#else+ const bool occ_gu = g.gu_type == T_IQ2_XXS || g.gu_type == T_IQ2_XS || g.gu_type == T_IQ2_S ||+ g.gu_type == T_IQ3_XXS || g.gu_type == T_IQ3_S || g.gu_type == T_IQ4_XS;+ const bool occ_d = g.d_type == T_Q2_0 || g.d_type == T_Q8_0 || g.d_type == T_IQ4_NL;+#endif+ const unsigned g_gu = (unsigned) std::min<int64_t>(tiles * (1280 / NW_ROWS), (int64_t) d.sms * (occ_gu ? 4 : wgp_blocks(d.occ)));+ const unsigned g_d = (unsigned) std::min<int64_t>(tiles * (2560 / NW_ROWS), (int64_t) d.sms * (occ_d ? 4 : wgp_blocks(d.occ)));+ const uint8_t* xa8 = (const uint8_t*) xa;+ uint8_t* ha8 = (uint8_t*) ha;+#define STRATA_NW_GU(T) do { if (occ_gu) native_w11_kernel<T, true, true, 8><<<g_gu, NW_THREADS, 0, s>>>(b, g, tb, xa8, src, ha8, nullptr); else native_w11_kernel<T, true><<<g_gu, NW_THREADS, 0, s>>>(b, g, tb, xa8, src, ha8, nullptr); } while (0)+ switch (g.gu_type) {+ case T_IQ2_XXS: STRATA_NW_GU(T_IQ2_XXS); break;+ case T_IQ2_XS: STRATA_NW_GU(T_IQ2_XS); break;+ case T_IQ2_S: STRATA_NW_GU(T_IQ2_S); break;+ case T_IQ3_XXS: STRATA_NW_GU(T_IQ3_XXS); break;+ case T_IQ3_S: STRATA_NW_GU(T_IQ3_S); break;+ case T_Q4_K: STRATA_NW_GU(T_Q4_K); break;+ case T_Q5_K: STRATA_NW_GU(T_Q5_K); break;+ default: STRATA_NW_GU(T_IQ4_XS); break;+ }+#undef STRATA_NW_GU+#define STRATA_NW_D(T) do { if (occ_d) native_w11_kernel<T, false, true, 8><<<g_d, NW_THREADS, 0, s>>>(b, g, tb, ha8, src, nullptr, dm); else native_w11_kernel<T, false><<<g_d, NW_THREADS, 0, s>>>(b, g, tb, ha8, src, nullptr, dm); } while (0)+ if (g.d_type == T_Q2_0) STRATA_NW_D(T_Q2_0);+ else if (g.d_type == T_Q5_1) STRATA_NW_D(T_Q5_1);+ else if (g.d_type == T_Q8_0) STRATA_NW_D(T_Q8_0);+ else STRATA_NW_D(T_IQ4_NL);+#undef STRATA_NW_D+ ck(cudaGetLastError(), "experts_native");+ return;+ }+#endif+ const int ww = pick_ww(n, n_expert);+ // the most 64-row tiles the batch can have (every row in it, plus a partial tile per expert) - the items of the+ // ones inside a larger item end at once+ const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0);+ const unsigned g_gu = (unsigned) std::min<int64_t>(tiles * (1280 / weight_rows(ww)), (int64_t) d.sms * d.occ);+ const unsigned g_d = (unsigned) std::min<int64_t>(tiles * (2560 / weight_rows(ww)), (int64_t) d.sms * d.occ);+ switch (g.gu_type) {+ case T_IQ2_XXS: launch<T_IQ2_XXS, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;+ case T_IQ2_XS: launch<T_IQ2_XS, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;+ case T_IQ2_S: launch<T_IQ2_S, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;+ case T_IQ3_XXS: launch<T_IQ3_XXS, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;+ case T_IQ3_S: launch<T_IQ3_S, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;+ default: launch<T_IQ4_XS, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;+ }+ if (g.d_type == T_Q2_0) launch<T_Q2_0, false>(ww, g_d, b, g, tb, ha, src, nullptr, dm, s);+ else launch<T_IQ4_NL, false>(ww, g_d, b, g, tb, ha, src, nullptr, dm, s);+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use the+ error codes. The cudaGetLastError function call was replaced with 0. You+ need to rewrite this code.+ */+ ck(0, "experts_native");+}++} // namespace strata::prefill::fuseddiff --git a/sycl/src/prefill/prefill.cpp b/sycl/src/prefill/prefill.cppindex ae02fbc7f..ae244c85c 100644--- a/sycl/src/prefill/prefill.cpp+++ b/sycl/src/prefill/prefill.cpp@@ -5,12 +5,15 @@#include "strata/sycl_queue.hpp"#include "strata/prefill/prefill.hpp"#include "strata/core/gguf_expert_source.hpp"+#include "../../../src/prefill/mmq_resident_sort.hpp"+#include "../../../src/prefill/wmma_gemm.h"#include "strata/core/mtp.hpp"#include "strata/core/progress.hpp"#include "strata/core/on_device.hpp"#include "strata/core/layout.hpp"#include "strata/kernels/cpu/expert.hpp"+#include "strata/kernels/native_qsa.hpp"#include "strata/kernels/native_qsa_indexer.hpp"#include "strata/kernels/ngram.hpp"#include "strata/kernels/ple.hpp"@@ -95,9 +98,16 @@ constexpr int64_t C = 10240, ZV = 6144, HV = 48;// plan v0.3 P6: staging holds the largest blob of the pack (a native pack's blobs differ per layer)inline int64_t MAXBLOB() { return (int64_t) strata::kernels::cpu::expert_layout().max_blob; }constexpr int STAGE = 8; // host->device expert staging ring (chunks below stream_all_min())+constexpr int kSplitHelpRing = 48; // layer split help: the helper stage's ring slots it streams through (at most)// Step 3: from this chunk size on, every non-resident expert of every layer streams in a fixed order through a// ring_slots()-slot ring (nearly all 512 are routed at such a chunk), so the copy engine keeps working through the// attention halves instead of waiting for each layer's routing.+// #828: STRATA_TEST_PAGEABLE=1 makes every pinned host allocation with a pageable fallback in Prefill::init fail, so the+// fallbacks (what an LXC container's memlock limit forces) run on a PC that can pin - for ASan / MALLOC_CHECK_=3 runs.+inline bool force_pageable() {+ static const bool v = [] { const char* e = std::getenv("STRATA_TEST_PAGEABLE"); return e != nullptr && e[0] == '1'; }();+ return v;+}constexpr int RING_MAX = 1024; // the arrays; the ring itself is ring_slots(), at most ring_cap()// The chunk size from which every expert streams: 1024 since 0.1.30 (was 2048). Measured on the 5070, Q2_0 / IQ2_XS,// fixed cache: 1,500-token prompts 621 -> 785 / 612 -> 735 tok/s, 2,000 727 -> 934 / 712 -> 892, 4,000 (its last@@ -114,7 +124,20 @@ double g_nonres_share = 0.0;// 8192-token chunks: 96 slots 1153 tok/s, 384 1294 (the next layer's experts arrive during its attention half) -// and 96 when a large share goes through host copies (IQ3_S on 64 GB, a third unpinned: 96 slots 1216, 256 1070 -// the host copies are the limit and the bigger ring only takes cache slots). STRATA_PREFILL_RING overrides.+//+// Those are slots on the pack they were measured on, and a slot is one WHOLE expert blob - a Q2_0 blob is+// 1,382,400 B, so 384 slots is 506 MiB. On a pack with bigger blobs the same slot count is a different amount of+// memory: 1,912 MiB on Q8_0 (5,222,400 B), which is more than half of an 8 GB card's expert cache and what held+// that card at a 1,024-token chunk when its own buffers would have fitted 6,144. Measured on the 4-way rig, one+// env var and nothing else: chunk 1,024 -> 6,144, prefill 87 -> 402 tok/s. So the budget is kept in BYTES and the+// slot count is derived from the pack (`ring_budget_slots`); Q2_0 still resolves to exactly 1024 (fused) and 384,+// so the pack all of this was tuned on does not move.int g_ring_override = 0; // #340: set by a layer split (Prefill::set_ring_override); 0 = the rule below+// #583 (0.1.39b): the auto chunk scan's byte-budget ring (Prefill::set_ring_budget), for requests whose chunk is above+// g_ring_small_max - the chunk 0.1.39's rule would have picked. A prompt that fits that chunk keeps 0.1.39's ring:+// on one chunk the smaller ring only slowed it (RTX 5070, 4K prompts: Coder -15%, IQ3_S -5%, IQ3_XXS -2%).+int g_ring_budget = 0;+int64_t g_ring_small_max = 0;// #136: the fused experts (STRATA_PF_FUSED=1) launch on a batch of a layer's streamed experts at once, so the ring// should hold a whole layer's (~460 of 512 on Q2_0): with 384 slots a layer's last batch waits for slots its own// first batch frees. Measured on the 5070, Q2_0, the 4K / 32K code-agent prompts (one run each): fused at 384 slots@@ -142,6 +165,30 @@ inline bool fused_ring() {// the largest ring: 512 slots; 1024 with the Q2_0 pack's fused experts (P3's smaller buffers, measured there) - the// native packs' fused layers were measured at 512inline int ring_cap() { return fused_ring() && !strata::kernels::cpu::expert_layout().native ? RING_MAX : 512; }+// The ring's budget in bytes: the measured slot counts above, at the blob size they were measured with. It is+// bytes and not slots because a slot is one whole blob and the blob is the pack's - see the note above.+inline constexpr uint64_t Q2_0_BLOB = 1382400ull; // the blob of the pack the ring was tuned on+inline uint64_t ring_bytes() {+ const uint64_t slots = fused_ring() ? 1024ull : 384ull; // #136: a fused ring holds two layers' experts+ return (g_pinned_share >= 0.9 ? slots : slots / 4) * Q2_0_BLOB;+}+// ...and what that buys on THIS pack, never past ring_cap(): the slot count `init` lays out, and what the auto+// chunk scan treats as a full ring. A pack whose blobs are larger than Q2_0's gets fewer slots for the same+// bytes, which is the point - the ring competes with the expert cache for the same VRAM.+// 0.1.39b: on by default (#583); STRATA_RING_BYTES=0 restores 0.1.39's ring, loan and auto chunk list. It moves the+// prompt path's loan on a native pack (fewer ring slots, the rest kept as cache slots, a larger auto chunk), so a long+// prompt's experts are read through a different mix of resident and streamed groups and its bits differ from 0.1.39's+// (RTX 5070, IQ3_XXS, 32K prompt: +14% to +26%; teacher-forced against the FP16 prompt path in the same band).+inline bool ring_bytes_on() {+ static const bool on = [] { const char* v = std::getenv("STRATA_RING_BYTES"); return v == nullptr || v[0] != '0'; }();+ return on;+}+inline int ring_budget_slots() {+ const int64_t per = MAXBLOB();+ const int64_t n = per > 0 ? (int64_t) (ring_bytes() / (uint64_t) per) : 0;+ const int cap = ring_cap();+ return (int) (n <= 0 ? 0 : (n > cap ? cap : n));+}inline int ring_slots(size_t T) {const char* v = std::getenv("STRATA_PREFILL_RING");#if defined(STRATA_USE_HIP)@@ -153,8 +200,14 @@ inline int ring_slots(size_t T) {}();if (!v && g_ring_override <= 0 && wmma) return (int64_t) T >= stream_all_min() ? 96 : STAGE;#endif- const int pinned_ring = fused_ring() ? 1024 : 384;- const int r = v ? std::atoi(v) : g_ring_override > 0 ? g_ring_override : (g_pinned_share >= 0.9 ? pinned_ring : 96);+ // the byte budget as this pack's slots: 1024 fused / 384 not on Q2_0, fewer on a pack with bigger blobs. The+ // unpinned arm stays a slot count (96): it was measured where the host copies are the limit, and there the ring+ // is not what is competing for VRAM.+ // 0.1.39's ring (1024 fused / 384 pinned, 96 when a large share goes through host copies), and the #583 byte+ // budget the auto scan chose for chunks past the size 0.1.39's rule would have picked (set_ring_budget)+ const int pinned_ring = g_pinned_share >= 0.9 ? (fused_ring() ? 1024 : 384) : 96;+ const bool budget = ring_bytes_on() && g_ring_budget > 0 && (int64_t) T > g_ring_small_max;+ const int r = v ? std::atoi(v) : g_ring_override > 0 ? g_ring_override : budget ? g_ring_budget : pinned_ring;if (v && r == STAGE) return STAGE; // Explicit opt-in to routed-only staging, including large chunks.// SYCL port: the stream-all walk (every non-resident expert of every layer, copied ahead across layers) hung on the// B70 in its first large chunk until 2026-10-02 - the stager's and the PLE upload's host waits on queue events,@@ -176,15 +229,61 @@ constexpr int DQ = 2; // dequantized-expert ring (FP16 gate/up + do// second GEMM (Y = W.hi + W.lo, ~16 mantissa bits): a router that picks its top 10 from the same x decode would.// 2 = all but the hyper-connection's; 1 = the hyper-connection's too (its activations are 10240 wide and its up// projection writes as much: slower); 0 (the default: opt-in, it changes the prompt path's numbers) = off.-inline int bf16x2_mode() {+// `f16_io`: the stage's FP16 prompt path (Prefill::init decides it once per stage, on the stage's own device): FP16+// activations carry 11 mantissa bits, so the BF16 low part does not apply there.+inline int bf16x2_mode(bool f16_io) {static const int v = [] {const char* e = std::getenv("STRATA_PREFILL_BF16X2");return e != nullptr ? std::atoi(e) : 0;}();+ return f16_io ? 0 : v;+}+inline bool bf16x2(bool f16_io) { return bf16x2_mode(f16_io) != 0; }+// S23 (opt-in STRATA_HC_UPMIX=1): the hyper-connection read's up projection and gr_mix_r as one kernel (gr_upmix, gfx11);+// STRATA_HC_UPMIX_CHECK=N also runs the default pair on the first N reads and reports the difference of `mixed`+static int64_t pf_switch_min_t() { // S23: STRATA_PF_SWITCH_MIN_T=N - the rounding-level prompt switches only on chunks of+ // N or more tokens (shorter prompts keep the default numerics, and their outputs; the switches pay on long ones)+ static const int64_t v = [] { const char* e = std::getenv("STRATA_PF_SWITCH_MIN_T"); return e ? (int64_t) std::atoll(e) : (int64_t) 0; }();+ return v;+}+inline bool hc_upmix() {+ static const bool v = [] { const char* e = std::getenv("STRATA_HC_UPMIX"); return e != nullptr && e[0] == '1'; }();+ return v;+}+inline bool bf16x2_hc(bool f16_io) { return bf16x2_mode(f16_io) == 1; }+// S23 (opt-in STRATA_CVEC_FUSE=1): a steered layer's FFN write + control vector + the next half's norm in one pass+// over R (gr_write_cvec_norm_rs; bitwise the gr_write + cvec_apply + gr_norm_rs it replaces)+// S23 (opt-in STRATA_PF_HCDOWN=1, on chunks of STRATA_PF_SWITCH_MIN_T+ tokens): the hyper-connection read's down and+// inject projections as one WMMA GEMM over xn16 (strata_pf_hcdown_bf16), xn16 written with token stride+// 10240 + 64. Rounding-level (another k order than hipBLASLt): quality-gated.+inline bool pf_hcdown() {+ static const bool v = [] { const char* e = std::getenv("STRATA_PF_HCDOWN"); return e && e[0] == '1'; }();+ return v;+}+constexpr int64_t XN_PAD = 64;+// S (opt-in STRATA_HCD_EXACT=1, on chunks of STRATA_PF_SWITCH_MIN_T+ tokens): the HC down projection by a WMMA kernel with+// hipBLASLt's own k order (bitwise: strata_pf_hcdown_exact_bf16), xn16 written with token stride 10240 + 64 (the inject+// projection stays on hipBLASLt, reading that stride)+inline bool hcd_exact() {+ static const bool v = [] { const char* e = std::getenv("STRATA_HCD_EXACT"); return e && e[0] == '1'; }();+ return v;+}+inline bool hc_pad() { return pf_hcdown() || hcd_exact(); }+inline bool cvec_fuse() {+ static const bool v = [] { const char* e = std::getenv("STRATA_CVEC_FUSE"); return e && e[0] == '1'; }();+ return v;+}+// S23 (opt-in STRATA_PF_PAD=1 with STRATA_PF_GEMM=1): the FP16 activations of the two K 6144 projections (ssm_out's+// y_h, attn_output's attn_h) with row stride 6144 + 64, so the GEMM's rows do not camp on the memory channels (the+// 4 KB-multiple stride; Gemm::native pads the weight the same way). Same bits.+inline bool pf_pad() {+ static const bool v = [] {+ const char* p = std::getenv("STRATA_PF_PAD"); const char* g = std::getenv("STRATA_PF_GEMM");+ return p && p[0] == '1' && g && g[0] == '1';+ }();return v;}-inline bool bf16x2() { return bf16x2_mode() != 0; }-inline bool bf16x2_hc() { return bf16x2_mode() == 1; }+constexpr int64_t ZV_PAD = 64;// F-1: STRATA_GR_UNFUSED=1 keeps the FP32 copy of the normalized rows (gr_norm + gr_mix), the A/B arminline bool gr_unfused() {@@ -199,13 +298,19 @@ double ms_since(Clock::time_point t) { return std::chrono::duration<double, std:struct Alloc {uint8_t* base = nullptr;uint64_t cap = 0, used = 0;+ uint64_t failed_bytes = 0; ///< the take that could not be allocated; the failure message names it+ uint64_t granule = 0; ///< count_only: each take rounds up to this (cudaMalloc's 2 MiB pages: owned buffers)bool count_only = false;std::vector<void*>* owned = nullptr;template <typename T> T *take(size_t n, bool &ok) try {- const uint64_t bytes = ((uint64_t) n * sizeof(T) + 256 + 255) & ~255ull;- if (count_only) { used += bytes; return nullptr; }+ uint64_t bytes = ((uint64_t) n * sizeof(T) + 256 + 255) & ~255ull;+ if (count_only) {+ if (granule > 0) bytes = (bytes + granule - 1) / granule * granule;+ used += bytes;+ return nullptr;+ }if (base != nullptr) {- if (used + bytes > cap) { ok = false; return nullptr; }+ if (used + bytes > cap) { ok = false; failed_bytes = bytes; return nullptr; }T* p = (T*) (base + used);used += bytes;return p;@@ -213,7 +318,7 @@ struct Alloc {void* p = nullptr;if (DPCT_CHECK_ERROR(p = (void *)sycl::malloc_device(bytes, dpct::get_in_order_queue())) != 0) {- ok = false; return nullptr;+ ok = false; failed_bytes = bytes; return nullptr;}owned->push_back(p);used += bytes;@@ -281,7 +386,8 @@ struct Stager {meaningful in the migrated code and was removed or replaced with 0.You may need to check the migrated code.*/- pinned[i] = DPCT_CHECK_ERROR(+ pinned[i] = !force_pageable() &&+ DPCT_CHECK_ERROR(buf[i] = (unsigned char *)sycl::malloc_host(blob_bytes, dpct::get_in_order_queue())) == 0;if (!pinned[i]) {@@ -456,6 +562,21 @@ struct PeerPrefill {int32_t *src = nullptr, *bounds = nullptr, *ident = nullptr;uint8_t *grp_gu = nullptr, *grp_d = nullptr;std::unique_ptr<mmq::Context> ctx;+ mmq::Context* run_ctx = nullptr; // the context its products run in: ctx, or a layer split helper stage's+ // Without P2P (a layer split's helper) the activations and the result rows go through MAPPED pinned host buffers: the device that needs them reads them with a copy kernel. A copy-engine+ // upload would queue behind the expert blobs that device's streams already hold (up to a ring of them, ~70 us+ // each - the grouping tables' reason for mapped memory too), and cudaMemcpyPeerAsync would be staged by the+ // driver. `back_at` / `back_rows`: the rows this layer sends back.+ bool p2p = true;+ // The row table and the group bounds go the same way: the primary's are pinned for its own device only (or+ // pageable), and a copy from them on the peer's stream would hold up the host until that stream is idle.+ float* host_x = nullptr; // T x N activations (mapped, portable)+ float* host_rows = nullptr; // the peer's result rows (mapped, portable)+ int32_t* host_src = nullptr; // the peer's rows' tokens (mapped, portable)+ int32_t* host_bounds = nullptr; // its group bounds (mapped, portable)+ size_t host_x_cap = 0, host_rows_cap = 0, host_src_cap = 0; // elements+ static constexpr size_t kHostBounds = 2 * (NE + NE / 16 + 2) + 64;+ int64_t back_at = 0, back_rows = 0;std::vector<int32_t> bounds_host;std::vector<void*> owned;int64_t layers = 0, experts = 0, rows = 0, over_cap = 0; // stats@@ -488,6 +609,10 @@ struct PeerPrefill {*/dpct::select_device(prev);if (ev_in) dpct::destroy_event(ev_in);+ if (host_x) sycl::free(host_x, dpct::get_in_order_queue());+ if (host_rows) sycl::free(host_rows, dpct::get_in_order_queue());+ if (host_src) sycl::free(host_src, dpct::get_in_order_queue());+ if (host_bounds) sycl::free(host_bounds, dpct::get_in_order_queue());}};@@ -510,6 +635,7 @@ struct Prefill::Impl {uint16_t *xn16 = nullptr, *lo16 = nullptr;float* mixed = nullptr;uint16_t *mixed_bf = nullptr, *mixed_h = nullptr;+ bool f16_io = false; // HIP, STRATA_HIP_PROMPT_F16=1: this stage's 16-bit GEMMs run FP16 in and out (set in init)uint16_t *xn16_lo = nullptr, *lo16_lo = nullptr, *mixed_bf_lo = nullptr; // bf16x2(): the BF16 GEMMs' low partsfloat* bo = nullptr;// GDN@@ -579,6 +705,8 @@ struct Prefill::Impl {// KV streaming: one layer's whole K/V, staged from the host copy per layer and chunk (identity layout)strata::kernels::KvHostPools stage;int32_t* ident_table = nullptr;+ dpct::queue_ptr kv_copy = &dpct::get_in_order_queue();+ dpct::event_ptr kv_released = nullptr, kv_ready = nullptr;// layer split: the device, and the hand-off to the next stage (two pinned chunk buffers, used in turn)int device = -1;float* hand[2] = {};@@ -586,6 +714,9 @@ struct Prefill::Impl {int32_t* tok_dev = nullptr;std::vector<int32_t> tok_host;std::unique_ptr<PeerPrefill> pp; // multi-GPU: the peer GPU's expert share (set_peer)+ // layer split: the next stage's GPU as a stream-only peer (set_stage_helper); its buffers are that stage's own+ // prompt buffers, bound per prompt, and it takes the place of `pp` for a run it helps+ std::unique_ptr<PeerPrefill> help_pp;};namespace {@@ -603,7 +734,11 @@ void take_stage(Alloc& o_borrowed, const core::SessionState& ss, const strata::kown.owned = o_borrowed.owned;Alloc& o = stage_own() ? own : o_borrowed;const size_t rows = (size_t) q0.n_pages * s.n_head_kv * s.page_size;- if (q0.kv_q4) {+ if (q0.kv_hybrid) { // K8V4: the three runs of kKvHybrid; pools_of() then reads as the hybrid pools (mode 3)+ st.k_q = o.take<int8_t>(rows * s.head_dim, ok);+ st.k_scale = o.take<uint16_t>(rows * (s.head_dim / 64), ok);+ st.v_q4 = o.take<uint8_t>(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok);+ } else if (q0.kv_q4) {st.k_q4 = o.take<uint8_t>(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok);st.v_q4 = o.take<uint8_t>(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok);} else if (q0.kv_int8) {@@ -638,6 +773,7 @@ void Prefill::release() {if (!impl_) return;if (impl_->cs) impl_->cs->wait();if (impl_->copy) impl_->copy->wait();+ if (impl_->kv_copy) impl_->kv_copy->wait();for (int i = 0; i < RING_MAX; ++i) {if (impl_->copied[i]) dpct::destroy_event(impl_->copied[i]);if (impl_->used[i]) dpct::destroy_event(impl_->used[i]);@@ -651,6 +787,10 @@ void Prefill::release() {sycl::free(impl_->ple_emb_host[b], dpct::get_in_order_queue());}if (impl_->copy) dpct::get_current_device().destroy_queue(impl_->copy);+ if (impl_->kv_copy) dpct::get_current_device().destroy_queue(+ impl_->kv_copy);+ if (impl_->kv_released) dpct::destroy_event(impl_->kv_released);+ if (impl_->kv_ready) dpct::destroy_event(impl_->kv_ready);if (impl_->grp_host)sycl::free(impl_->grp_host, dpct::get_in_order_queue());for (void *p : impl_->owned)@@ -669,14 +809,16 @@ constexpr size_t GEMM_WS = 32u << 20; // cuBLAS workspaceuint64_t gdn_set_bytes(size_t T) {Alloc a; a.count_only = true; bool ok = true;a.take<float>(T * C, ok); a.take<float>(T * ZV, ok); a.take<float>(T * 2 * HV, ok); a.take<float>(T * HV, ok);- a.take<float>(T * HV, ok); a.take<float>(T * C, ok); a.take<float>(T * ZV, ok); a.take<uint16_t>(T * ZV, ok);+ a.take<float>(T * HV, ok); a.take<float>(T * C, ok); a.take<float>(T * ZV, ok);+ a.take<uint16_t>(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok);return a.used;}uint64_t qsa_set_bytes(size_t T, int64_t cap, int64_t max_blocks, int64_t sel_batch, int64_t attn_batch,const strata::kernels::QsaShapes& s) {Alloc a; a.count_only = true; bool ok = true;a.take<float>(T * 512, ok); a.take<float>(T * 512, ok); a.take<float>(T * 12288, ok); a.take<float>(T * ZV, ok);- a.take<float>(T * 128, ok); a.take<float>(T * 512, ok); a.take<float>(T * ZV, ok); a.take<uint16_t>(T * ZV, ok);+ a.take<float>(T * 128, ok); a.take<float>(T * 512, ok); a.take<float>(T * ZV, ok);+ a.take<uint16_t>(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok);a.take<int32_t>(T * (size_t) cap, ok);a.take<float>((size_t) sel_batch * (size_t) max_blocks, ok);a.take<float>((size_t) attn_batch * strata::kernels::qsa_decode_attn_scratch_floats(cap, s), ok);@@ -693,6 +835,8 @@ constexpr size_t MMQ_TAIL = 4096;struct MmqPlan {bool any = false, fallback = true;std::vector<char> layer; // per layer: MMQ+ std::vector<char> fo; // per layer: no MMQ here but the native fused kernels cover its formats+ // (gfx11: UD-Q4_K_XL's Q4_K / Q5_K and Q5_1 / Q8_0 experts, STRATA_PF_FUSED=1)size_t gu_max = 0, d_max = 0;};const MmqPlan& mmq_plan() {@@ -703,11 +847,17 @@ const MmqPlan& mmq_plan() {const bool on = mmq::built() && (env == nullptr || std::atoi(env) != 0);const int64_t layers = lay.native ? (int64_t) lay.fmt.size() : lay.n_layers;p.layer.assign((size_t) std::max<int64_t>(layers, 0), 0);+ p.fo.assign(p.layer.size(), 0);p.fallback = !on || layers <= 0;for (int64_t l = 0; on && l < layers; ++l) {const int gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42, dt = lay.native ? lay.fmt[(size_t) l].d_type : 42;// #420: a tile on every GPU for these shapes (gate+up: 1280 rows, down: N rows), else the FP16 path- if (!mmq::fits(gt, 1280) || !mmq::fits(dt, N)) { p.fallback = true; continue; }+ if (!mmq::fits(gt, 1280) || !mmq::fits(dt, N)) {+ p.fallback = true;+ // the fused path's buffers (Xq, H) exist for it; a chunk it does not take (a small one) keeps the FP16 path+ if (on && lay.native && fused::native_supported(gt, dt)) { p.fo[(size_t) l] = 1; p.any = true; }+ continue;+ }p.layer[(size_t) l] = 1;p.any = true;p.gu_max = std::max(p.gu_max, mmq::matrix_bytes(gt, 1280, N));@@ -852,17 +1002,18 @@ bool Prefill::init(const core::WeightTable &wt, const core::ModelGeometry &g,m.grp_host = m.grp_dev = nullptr;m.grp_n = m.grp_tk = 0;void *h = nullptr, *d = nullptr;- /*- DPCT1048: The original value cudaHostAllocMapped is not- meaningful in the migrated code and was removed or replaced with 0.- You may need to check the migrated code.- */- /*- DPCT1048: The original value cudaHostAllocPortable is not- meaningful in the migrated code and was removed or replaced with 0.- You may need to check the migrated code.- */- if (DPCT_CHECK_ERROR(h = (void *)sycl::malloc_host(+ if (!force_pageable() &&+ /*+ DPCT1048: The original value cudaHostAllocMapped is not+ meaningful in the migrated code and was removed or replaced with+ 0. You may need to check the migrated code.+ */+ /*+ DPCT1048: The original value cudaHostAllocPortable is not+ meaningful in the migrated code and was removed or replaced with+ 0. You may need to check the migrated code.+ */+ DPCT_CHECK_ERROR(h = (void *)sycl::malloc_host(need * 4, dpct::get_in_order_queue())) ==0 &&DPCT_CHECK_ERROR(d = (void *)h) == 0) {@@ -886,9 +1037,10 @@ bool Prefill::init(const core::WeightTable &wt, const core::ModelGeometry &g,meaningful in the migrated code and was removed or replaced with 0.You may need to check the migrated code.*/- DPCT_CHECK_ERROR(- m.ple_emb_host[b] = (float *)sycl::malloc_host(- (size_t)T * N * 4, dpct::get_in_order_queue())) != 0) {+ (force_pageable() ||+ DPCT_CHECK_ERROR(+ m.ple_emb_host[b] = (float *)sycl::malloc_host(+ (size_t)T * N * 4, dpct::get_in_order_queue())) != 0)) {/*DPCT1026: The call to cudaGetLastError was removed because thisfunctionality is redundant in SYCL.@@ -936,9 +1088,31 @@ bool Prefill::init(const core::WeightTable &wt, const core::ModelGeometry &g,void* ws = o.take<uint8_t>(GEMM_WS, ok);if (!ok) { err = "prefill: GEMM scratch does not fit"; return false; }if (!m.gemm.init_external(stream, gs, GEMM_SCRATCH, ws, GEMM_WS, err)) return false;+ // this stage's device decides, once, here (init runs on the stage's own device): its gr_* kernels write the+ // image its GEMMs read, and set_act_f16 writes that device's symbol+ const core::OnDevice on_stage(m.device);+ m.f16_io = prompt_f16();+ m.gemm.set_f16_io(m.f16_io);+ set_act_f16(m.f16_io);}if (!carve(T, &o)) {- err = "prefill: device buffers for a chunk of " + std::to_string(chunk) + " tokens do not fit";+ size_t fb = 0, tb = 0;+ /*+ DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions+ for device information which may not be supported by all compilers or+ runtimes. You may need to adjust the code.+ */+ dpct::get_current_device().get_memory_info(fb, tb);+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use+ the error codes. The cudaGetLastError function call was replaced with 0.+ You need to rewrite this code.+ */+ (void)0;+ err = "prefill: device buffers for a chunk of " + std::to_string(chunk) + " tokens do not fit (" ++ std::to_string(fb >> 20) + " of " + std::to_string(tb >> 20) + " MiB free at the failure; " ++ std::to_string(o.used >> 20) + " MiB taken, the failing buffer wanted " ++ std::to_string(o.failed_bytes >> 20) + " MiB)";return false;}return true;@@ -960,12 +1134,12 @@ bool Prefill::carve(size_t T, void* alloc) {m.emb = o.take<float>(T * N, ok); m.R = o.take<float>(T * D, ok);m.xn = gr_unfused() ? o.take<float>(T * D, ok) : nullptr; // F-1: not needed (gr_mix_r reads R)m.grs = o.take<float>(T * HC, ok);- m.xn16 = o.take<uint16_t>(T * D, ok); m.lo = o.take<float>(T * LR, ok); m.lo16 = o.take<uint16_t>(T * LR, ok);+ m.xn16 = o.take<uint16_t>(T * (D + (hc_pad() ? XN_PAD : 0)), ok); m.lo = o.take<float>(T * LR, ok); m.lo16 = o.take<uint16_t>(T * LR, ok);m.gated = o.take<float>(T * D, ok); m.inj = o.take<float>(T * HC, ok);m.mixed = o.take<float>(T * N, ok); m.mixed_bf = o.take<uint16_t>(T * N, ok);m.mixed_h = o.take<uint16_t>(T * N, ok); m.bo = o.take<float>(T * N, ok);- if (bf16x2_hc()) { m.xn16_lo = o.take<uint16_t>(T * D, ok); m.lo16_lo = o.take<uint16_t>(T * LR, ok); }- if (bf16x2()) m.mixed_bf_lo = o.take<uint16_t>(T * N, ok);+ if (bf16x2_hc(m.f16_io)) { m.xn16_lo = o.take<uint16_t>(T * D, ok); m.lo16_lo = o.take<uint16_t>(T * LR, ok); }+ if (bf16x2(m.f16_io)) m.mixed_bf_lo = o.take<uint16_t>(T * N, ok);m.steps_dev = o.take<int32_t>(T * strata::kernels::kStepCount, ok);strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads;@@ -986,12 +1160,12 @@ bool Prefill::carve(size_t T, void* alloc) {a.base = base; a.cap = region; a.owned = &m.owned;m.qkv = a.take<float>(T * C, ok); m.z = a.take<float>(T * ZV, ok); m.ab = a.take<float>(T * 2 * HV, ok);m.gate = a.take<float>(T * HV, ok); m.beta = a.take<float>(T * HV, ok); m.hbuf = a.take<float>(T * C, ok);- m.y = a.take<float>(T * ZV, ok); m.y_h = a.take<uint16_t>(T * ZV, ok);+ m.y = a.take<float>(T * ZV, ok); m.y_h = a.take<uint16_t>(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok);Alloc b;b.base = base; b.cap = region; b.owned = &m.owned;m.Kc = b.take<float>(T * 512, ok); m.Vc = b.take<float>(T * 512, ok); m.Qf = b.take<float>(T * 12288, ok);m.q = b.take<float>(T * ZV, ok); m.idx_raw = b.take<float>(T * 128, ok); m.q_idx = b.take<float>(T * 512, ok);- m.attn = b.take<float>(T * ZV, ok); m.attn_h = b.take<uint16_t>(T * ZV, ok);+ m.attn = b.take<float>(T * ZV, ok); m.attn_h = b.take<uint16_t>(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok);m.sel_ids = b.take<int32_t>(T * (size_t) m.cap, ok);m.sel_scores = b.take<float>((size_t) m.sel_batch * (size_t) m.max_blocks, ok);m.attn_scratch = b.take<float>((size_t) m.attn_batch * strata::kernels::qsa_decode_attn_scratch_floats(m.cap, s), ok);@@ -1025,10 +1199,22 @@ bool Prefill::carve(size_t T, void* alloc) {if (!m.mmq_ctx) m.mmq_ctx = std::make_unique<mmq::Context>();}m.ring = ring_slots(T);- for (int i = 0; i < m.ring; ++i) {- m.stage_dev[i] = o.take<uint8_t>((size_t) MAXBLOB(), ok);- m.stage_live[i] = false; // a new buffer: nothing of an earlier layout to wait for- m.used_of[i] = i;+ if (o.base == nullptr && m.ring > 0) {+ // OWNED buffers: the ring in ONE allocation. 384 separate 2.7 MiB cudaMallocs each round up to a 2 MiB page+ // (~1.3 MiB a slot, ~0.5 GiB in all) that no count ever saw. A borrowed region keeps its per-slot layout (and+ // so its price, `bytes_needed`: the loans' slot counts do not move).+ uint8_t* ring_base = o.take<uint8_t>((size_t) m.ring * (size_t) MAXBLOB(), ok);+ for (int i = 0; ok && i < m.ring; ++i) {+ m.stage_dev[i] = ring_base + (size_t) i * (size_t) MAXBLOB();+ m.stage_live[i] = false;+ m.used_of[i] = i;+ }+ } else {+ for (int i = 0; i < m.ring; ++i) {+ m.stage_dev[i] = o.take<uint8_t>((size_t) MAXBLOB(), ok);+ m.stage_live[i] = false; // a new buffer: nothing of an earlier layout to wait for+ m.used_of[i] = i;+ }}m.ple_emb = o.take<float>(T * N, ok);m.ple_norm = o.take<float>((size_t) strata::kernels::NG_HC_DIM, ok);@@ -1045,7 +1231,8 @@ bool Prefill::relayout(int64_t chunk, void *borrow, uint64_t borrow_bytes,return false;}if (DPCT_CHECK_ERROR(m.cs->wait()) != 0 ||- DPCT_CHECK_ERROR(m.copy->wait()) != 0) {+ DPCT_CHECK_ERROR(m.copy->wait()) != 0 ||+ (m.kv_copy && DPCT_CHECK_ERROR(m.kv_copy->wait()) != 0)) {err = "prefill: relayout: the stream failed";return false;}@@ -1058,7 +1245,23 @@ bool Prefill::relayout(int64_t chunk, void *borrow, uint64_t borrow_bytes,void* ws = o.take<uint8_t>(GEMM_WS, ok);if (ok) m.gemm.rebind(gs, GEMM_SCRATCH, ws, GEMM_WS);if (!ok || !carve((size_t) chunk, &o)) {- err = "prefill: device buffers for a chunk of " + std::to_string(chunk) + " tokens do not fit";+ size_t fb = 0, tb = 0;+ /*+ DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions+ for device information which may not be supported by all compilers or+ runtimes. You may need to adjust the code.+ */+ dpct::get_current_device().get_memory_info(fb, tb);+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use+ the error codes. The cudaGetLastError function call was replaced with 0.+ You need to rewrite this code.+ */+ (void)0;+ err = "prefill: device buffers for a chunk of " + std::to_string(chunk) + " tokens do not fit (" ++ std::to_string(fb >> 20) + " of " + std::to_string(tb >> 20) + " MiB free at the failure; " ++ std::to_string(o.used >> 20) + " MiB taken, the failing buffer wanted " ++ std::to_string(o.failed_bytes >> 20) + " MiB)";return false;}return true;@@ -1219,7 +1422,10 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_tAPI to ensure synchronization behavior.*/m.cs->memcpy(hn, R_rows + (size_t)b0 * HCN, (size_t)nb * HCN * 4);- rms_rows(hn, w_nh, nb, HCN, HCN, EPS, m.cs);+ if (mtp.hnorm_per_stream()) // --mtp-hnorm stream: as the drafter's own pass (mtp.cpp)+ strata::kernels::native_qsa_rms_norm_grouped(hn, w_nh, hn, (int) Nn, (int) g.hc, (int) (nb * g.hc), EPS, m.cs);+ else+ rms_rows(hn, w_nh, nb, HCN, HCN, EPS, m.cs);if (!q8) to_f16(hn, hn16, nb * HCN, m.cs);proj(hn, hn16, w_fh, h2, nb * g.hc, Nn, Nn, 1); // every stream through fc_hiddenstrata::kernels::add_streams_broadcast(h2, e2, Rm, Nn, (int) g.hc, (int) nb, m.cs);@@ -1267,6 +1473,190 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t(long long) B, ms_idle, ms_since(tl0), ms_since(t0));return true;}+namespace {+// Layer split: STRATA_PREFILL_HELP=1 lends the idle stage's GPU (opt-in: the helped rows are computed in another MMQ+// grouping and round differently from the default, like STRATA_SPLIT_OWN). Unset or 0: every stage's prompt experts on+// its own GPU, as before.+bool split_help_env() {+ static const bool v = [] { const char* e = std::getenv("STRATA_PREFILL_HELP"); return e != nullptr && std::atoi(e) != 0; }();+ return v;+}+// The share of a stage's streamed experts the idle stage's GPU takes for a one-chunk prompt of T tokens (0: none).+// The streamed bytes are the same at any T; the hand-over (the activations there, the rows back) grows with T and is+// paid per layer whatever the share. Measured on 2x RTX 3090 (UD-Q4_K_XL, PCIe 4.0 x16 each, no P2P), fixed shares+// 0.2 / 0.3 / 0.4 against none: 1.5K tokens 749 / 820 / 908 (none 675), 3K 1335 / 1437 / 1328 (1262), 4K 1622 / 1620 /+// 1440 (1609), 6K 1811 / 1660 / 1471 (2038), 8K 1895 / 1804 / 1663 (2230) - the best share falls with T and from ~4K+// none pays, which this rule follows (0.41 at 1.5K, 0.32 at 3K, off from ~3.3K).+// STRATA_PREFILL_HELP_FRAC sets the share for every T.+double split_help_frac(int64_t T) {+ static const double fixed = [] {+ const char* e = std::getenv("STRATA_PREFILL_HELP_FRAC");+ return e ? std::clamp(std::atof(e), 0.0, 1.0) : -1.0;+ }();+ if (fixed >= 0.0) return fixed;+ const double f = std::min(0.45, 0.5 - (double) T / 16384.0);+ return f >= 0.3 ? f : 0.0;+}+} // namespace++bool Prefill::set_stage_helper(Prefill *helper, std::string &err) try {+ Impl& m = *impl_;+ m.help_pp.reset();+ if (helper == nullptr || helper == this || !split_help_env()) return true;+ const Impl& h = *helper->impl_;+ if (m.device < 0 || h.device < 0 || h.device == m.device || !mmq_plan().any) return true;+ auto pp = std::make_unique<PeerPrefill>();+ pp->peer = nullptr; // stream-only: it holds no experts, it streams a share of this stage's+ pp->compact = true;+ pp->p2p = false; // the mapped host route, whether or not the cards could reach each other (measured there)+ pp->out_pipe = true;+ bool ok;+ {+ const core::OnDevice on(m.device);+ ok = DPCT_CHECK_ERROR(pp->ev_in = new sycl::event()) == 0;+ }+ int prev = 0;+ prev = dpct::get_current_device_id();+ pp->dev = h.device;+ /*+ DPCT1093: The "pp->dev" device may be not the one intended for use.+ Adjust the selected device if needed.+ */+ dpct::select_device(pp->dev);+ /*+ DPCT1025: The SYCL queue is created ignoring the flag and priority+ options.+ */+ ok = ok &&+ DPCT_CHECK_ERROR(+ pp->s = dpct::get_current_device().create_queue(true)) == 0 &&+ /*+ DPCT1025: The SYCL queue is created ignoring the flag and priority+ options.+ */+ DPCT_CHECK_ERROR(+ pp->s_out = dpct::get_current_device().create_queue(true)) == 0 &&+ /*+ DPCT1025: The SYCL queue is created ignoring the flag and priority+ options.+ */+ DPCT_CHECK_ERROR(+ pp->s_cp = dpct::get_current_device().create_queue(true)) == 0 &&+ DPCT_CHECK_ERROR(pp->ev_done = new sycl::event()) == 0;+ for (int i = 0; ok && i < PeerPrefill::kGrpEv; ++i)+ ok = DPCT_CHECK_ERROR(pp->ev_grp[i] = new sycl::event()) == 0;+ for (int b = 0; ok && b < 2; ++b)+ ok = DPCT_CHECK_ERROR(pp->ev_dm[b] = new sycl::event()) == 0;+ // the ring's events; its slots are the helper stage's own ring, bound per prompt (bind_stage_helper)+ pp->pcopied.assign((size_t) kSplitHelpRing, nullptr);+ pp->pused.assign((size_t) kSplitHelpRing, nullptr);+ for (int i = 0; ok && i < kSplitHelpRing; ++i)+ ok =+ DPCT_CHECK_ERROR(pp->pcopied[(size_t)i] = new sycl::event()) == 0 &&+ DPCT_CHECK_ERROR(pp->pused[(size_t)i] = new sycl::event()) == 0;+ /*+ DPCT1093: The "prev" device may be not the one intended for use. Adjust+ the selected device if needed.+ */+ dpct::select_device(prev);+ if (!ok) { err = "prefill: the layer split's prompt help (streams and events)"; return false; }+ helper_ = helper;+ m.help_pp = std::move(pp);+ return true;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++// A one-chunk prompt of T tokens on a layer split: binds the stream-only peer to the helper stage's prompt buffers+// (that stage idles until this one hands its rows over). False when it cannot help this prompt.+bool Prefill::bind_stage_helper(int64_t T) {+ Impl& m = *impl_;+ if (!m.help_pp || helper_ == nullptr || m.pp) return false;+ const double frac = split_help_frac(T);+ if (frac <= 0.0 || T < stream_all_min() || m.src == nullptr || m.ring <= STAGE || fused_ring()) return false;+ const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();+ for (int64_t l = stage_lb_; l < stage_le_; ++l) {+ if (!(mmq_plan().any && mmq_plan().layer[(size_t) l])) return false; // the peer computes on MMQ only+ if (lay.native && fused::native_supported(lay.fmt[(size_t) l].gu_type, lay.fmt[(size_t) l].d_type)) return false;+ }+ Impl& h = *helper_->impl_;+ // the helper's buffers must be laid out for this chunk (the serve path lends every stage's at once)+ if (h.T < T || h.mixed == nullptr || h.Xq == nullptr || h.Hq == nullptr || h.GU == nullptr || h.H == nullptr ||+ h.Dm == nullptr || h.src_dev == nullptr || h.ids_identity == nullptr || h.bounds_dev == nullptr ||+ h.grp_gu == nullptr || h.grp_d == nullptr || !h.mmq_ctx || h.ring <= STAGE)+ return false;+ PeerPrefill& P = *m.help_pp;+ P.T_max = T;+ P.cap_rows = T * K;+ P.G = T; // one expert never has more rows than the chunk has tokens+ P.mixed = h.mixed;+ P.Xq_g = h.Xq; // the helper's per-layer buffers hold T * K rows: a group's T fit+ P.Hq_g = h.Hq;+ P.GU_g = h.GU;+ P.H_g = h.H;+ P.Dm_b[0] = h.Dm;+ P.Dm_b[1] = h.Dm + (size_t) T * N;+ P.src = h.src_dev;+ P.ident = h.ids_identity;+ P.bounds = h.bounds_dev;+ P.grp_gu = h.grp_gu;+ P.grp_d = h.grp_d;+ P.run_ctx = h.mmq_ctx.get();+ P.RP = std::min(h.ring, kSplitHelpRing);+ P.pstage.assign(h.stage_dev, h.stage_dev + P.RP);+ P.plive.assign((size_t) P.RP, 0);+ P.dm_live[0] = P.dm_live[1] = false;+ P.out_pending = false;+ P.ps_frac = frac;+ if (!P.p2p) { // grown once to the largest chunk it helped+ auto grow = [](auto *&p, size_t &cap, size_t n) {+ try {+ if (cap >= n) return true;+ if (p) sycl::free(p, dpct::get_in_order_queue());+ p = nullptr;+ cap = 0;+ /*+ DPCT1048: The original value cudaHostAllocPortable is not+ meaningful in the migrated code and was removed or replaced with 0.+ You may need to check the migrated code.+ */+ /*+ DPCT1048: The original value cudaHostAllocMapped is not+ meaningful in the migrated code and was removed or replaced with 0.+ You may need to check the migrated code.+ */+ if (DPCT_CHECK_ERROR(+ p = (std::remove_reference_t<decltype(p)>)sycl::malloc_host(+ n * sizeof(*p), dpct::get_in_order_queue())) != 0) {+ /*+ DPCT1026: The call to cudaGetLastError was removed because+ this functionality is redundant in SYCL.+ */+ p = nullptr;+ return false;+ }+ cap = n;+ return true;+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ size_t bounds_cap = P.host_bounds ? PeerPrefill::kHostBounds : 0;+ if (!grow(P.host_x, P.host_x_cap, (size_t) T * N) || !grow(P.host_rows, P.host_rows_cap, (size_t) T * K * N) ||+ !grow(P.host_src, P.host_src_cap, (size_t) T * K) || !grow(P.host_bounds, bounds_cap, PeerPrefill::kHostBounds))+ return false;+ }+ const core::OnDevice on(P.dev);+ mmq::iota(P.ident, T * K, P.s); // the helper's row table: a refill may have overwritten its slots+ return true;+}+bool Prefill::set_peer(core::PeerExperts *peer, int64_t cap_rows,std::string &err) try {Impl& m = *impl_;@@ -1388,6 +1778,7 @@ bool Prefill::set_peer(core::PeerExperts *peer, int64_t cap_rows,pp->grp_d = (uint8_t*) take(MMQ_GROUP * mp.d_max + MMQ_TAIL);if (ok) {pp->ctx = std::make_unique<mmq::Context>();+ pp->run_ctx = pp->ctx.get();mmq::iota(pp->ident, pp->cap_rows, pp->s);ok = DPCT_CHECK_ERROR(pp->s->wait()) == 0;}@@ -1421,21 +1812,51 @@ catch (sycl::exception const &exc) {void Prefill::set_pinned_share(double share) { g_pinned_share = share; }void set_nonresident_share(double share) { g_nonres_share = share; } // SYCL port (see ring_slots)void Prefill::set_ring_override(int slots) { g_ring_override = slots > 0 ? slots : 0; }+void Prefill::set_ring_budget(int slots, int64_t small_max) {+ g_ring_budget = slots > 0 ? slots : 0;+ g_ring_small_max = small_max > 0 ? small_max : 0;+}double Prefill::pinned_share() { return g_pinned_share; }+int64_t Prefill::stream_all_min_tokens() { return stream_all_min(); }uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk) {+ return bytes_needed_impl(g, ss, chunk, false);+}++// What `init` really allocates when the prompt path owns its buffers (no loan): every cudaMalloc rounds up to a 2 MiB+// page, and the ring is one allocation (carve). `bytes_needed` stays the borrowed region's sum.+uint64_t Prefill::bytes_needed_owned(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk) {+ return bytes_needed_impl(g, ss, chunk, true);+}++uint64_t Prefill::bytes_needed_impl(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk,+ bool owned_pages) {// the same allocation sequence as `init`, countedconst size_t T = (size_t) chunk;bool ok = true;Alloc o;o.count_only = true;+ if (owned_pages) o.granule = 2ull << 20;o.take<uint16_t>((size_t) GEMM_SCRATCH, ok);o.take<uint8_t>(GEMM_WS, ok);auto f = [&](size_t n) { o.take<float>(n, ok); };- f(T * N); f(T * D); f(T * D); o.take<uint16_t>(T * D, ok); f(T * LR); o.take<uint16_t>(T * LR, ok);+ // `carve`'s order, buffer for buffer: emb, R, xn, grs, xn16, lo, lo16, gated, inj, mixed, mixed_bf, mixed_h,+ // bo. This counted `xn` unconditionally (carve takes it only under STRATA_GR_UNFUSED) and never counted+ // `grs`. Net over-count T*(D-HC)*4 bytes: 42 MB at a 1024-token chunk, 252 MB (48 Q8_0 slots) at 6144 - the+ // prompt path was told it had less room than it did. Safe - the direction is over-estimating, and `take`+ // still bounds-checks - but it under-sizes every loan, so every chunk the scan picks is one step smaller.+ if (ring_bytes_on()) {+ f(T * N); f(T * D);+ if (gr_unfused()) f(T * D);+ f(T * HC);+ } else { // STRATA_RING_BYTES=0: 0.1.39's count+ f(T * N); f(T * D); f(T * D);+ }+ o.take<uint16_t>(T * (D + (hc_pad() ? XN_PAD : 0)), ok); f(T * LR); o.take<uint16_t>(T * LR, ok);f(T * D); f(T * HC); f(T * N); o.take<uint16_t>(T * N, ok); o.take<uint16_t>(T * N, ok); f(T * N);- if (bf16x2_hc()) { o.take<uint16_t>(T * D, ok); o.take<uint16_t>(T * LR, ok); }- if (bf16x2()) o.take<uint16_t>(T * N, ok);+ const bool f16_io = prompt_f16(); // the current device's mode (the stage's), as Prefill::init will decide it+ if (bf16x2_hc(f16_io)) { o.take<uint16_t>(T * D, ok); o.take<uint16_t>(T * LR, ok); }+ if (bf16x2(f16_io)) o.take<uint16_t>(T * N, ok);o.take<int32_t>(T * strata::kernels::kStepCount, ok);strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads;@@ -1452,7 +1873,11 @@ uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::Sessiono.take<uint8_t>(MMQ_GROUP * mp.gu_max + MMQ_TAIL, ok);o.take<uint8_t>(MMQ_GROUP * mp.d_max + MMQ_TAIL, ok);}- for (int i = 0; i < ring_slots(T); ++i) o.take<uint8_t>((size_t) MAXBLOB(), ok);+ if (owned_pages) {+ if (ring_slots(T) > 0) o.take<uint8_t>((size_t) ring_slots(T) * (size_t) MAXBLOB(), ok); // one allocation+ } else {+ for (int i = 0; i < ring_slots(T); ++i) o.take<uint8_t>((size_t) MAXBLOB(), ok);+ }f(T * N);f((size_t) strata::kernels::NG_HC_DIM);strata::kernels::KvHostPools stage;@@ -1460,6 +1885,33 @@ uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::Sessionreturn o.used + (8u << 20); // alignment slack}+uint64_t Prefill::bytes_needed_no_ring(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk) {+ return bytes_needed(g, ss, chunk) - (uint64_t) ring_slots((size_t) chunk) * (uint64_t) MAXBLOB();+}++int64_t Prefill::ring_default_slots() {+ const int r = g_pinned_share >= 0.9 ? (fused_ring() ? 1024 : 384) : 96;+ return (int64_t) std::min(r, ring_cap());+}++int64_t Prefill::ring_cap_for(int64_t old_chunk) {+ // 0.1.39b (#583, measured on the RTX 5070): giving up ring slots for a bigger chunk paid where 0.1.39's ring held+ // the chunk at 4096 or less (IQ3_XXS 32K prompts +14% to +26%: 4096/384 -> 6656/56) and lost where 0.1.39 already+ // read 6144-token chunks (the Coder: 6144/384 -> 7936/199, 32K -12%). From kKeepRingChunk on the ring keeps its+ // 0.1.39 size and the scan only looks for a bigger chunk next to it (IQ3_XXS unpinned 6144/96 -> 6912/96: +9%).+ constexpr int64_t kKeepRingChunk = 6144;+ return old_chunk >= kKeepRingChunk ? ring_default_slots() : ring_max_slots();+}++// the unpinned arm keeps its measured 96 (the PR's rule; the byte budget would have been ~49 slots on IQ3_S)+int64_t Prefill::ring_max_slots() {+ return g_pinned_share >= 0.9 ? (int64_t) ring_budget_slots() : (int64_t) std::min(96, ring_cap());+}++int64_t Prefill::ring_slots_for(int64_t chunk) { return ring_slots((size_t) chunk); }++bool Prefill::ring_bytes_enabled() { return ring_bytes_on(); }+namespace {const core::WeightRef* need(const core::LayerView& v, const char* suffix, std::string& err) {@@ -1468,15 +1920,15 @@ const core::WeightRef* need(const core::LayerView& v, const char* suffix, std::sreturn r;}bool native_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name,- std::string& err, int64_t ldy = 0) {+ std::string& err, int64_t ldy = 0, int64_t ldx = 0) {if (!w->native_data) { err = "prefill: " + name + " has no native GGUF blocks (run with --native)"; return false; }- gm.native(X, w->native_type, w->native_data, Y, T, w->ne1, w->ne0, ldy);+ gm.native(X, w->native_type, w->native_data, Y, T, w->ne1, w->ne0, ldy, 0.0f, ldx);return true;}bool bf16_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name,- std::string& err, int64_t ldy = 0, const uint16_t* X_lo = nullptr) {+ std::string& err, int64_t ldy = 0, const uint16_t* X_lo = nullptr, int64_t ldx = 0) {if (w->kind != core::WeightKind::Bf16InF32 || !w->data) { err = "prefill: " + name + " is not a resident BF16 tensor"; return false; }- gm.bf16(X, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy);+ gm.bf16(X, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 0.0f, ldx);if (X_lo) gm.bf16(X_lo, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 1.0f);return true;}@@ -1614,8 +2066,8 @@ struct PeTimer {};} // namespace-bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,- std::string &err) try {+bool Prefill::run_impl(const int64_t *tokens, int64_t n, int64_t pos0,+ std::string &err) try {err.clear();Impl& m = *impl_;const core::OnDevice on_device(m.device);@@ -1623,19 +2075,63 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,core::SessionState& ss = *m.ss;const auto t_start = Clock::now();const int64_t LB = stage_lb_, LE = stage_le_;- // the next stage reads chunk c on a thread while this one reads chunk c + 1 (declared first: an early return- // waits for it before anything it reads goes away)- std::string next_err;- std::future<bool> next_run;- int hand_buf = 0;+ // The direct successor's future lives on the Prefill object. Intermediate+ // stages therefore do not drain the complete remaining GPU chain here.double host_sync_ms = 0, host_chunk_ms = 0, host_setup_ms = 0; // STRATA_PREFILL_TIMING: the host's sharedouble grp_wait_ms = 0, grp_cpu_ms = 0; // the per-layer grouping: the drain wait, the host's loopsstrata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads;s.idx_dim = g.idx_key_dim;+ // read once (STRATA_KV_PREFETCH=1/0: the next streamed layer's KV prefix is staged on its own stream)+ static const bool kv_prefetch_on = [] {+ const char* e = std::getenv("STRATA_KV_PREFETCH");+ return e ? std::atoi(e) != 0 : false;+ }();+ const bool kv_prefetch = kv_prefetch_on;+ if (kv_prefetch) {+ /*+ DPCT1025: The SYCL queue is created ignoring the flag and priority+ options.+ */+ if ((!m.kv_copy &&+ DPCT_CHECK_ERROR(+ m.kv_copy = dpct::get_current_device().create_queue(true)) !=+ 0) ||+ (!m.kv_released &&+ DPCT_CHECK_ERROR(m.kv_released = new sycl::event()) != 0) ||+ (!m.kv_ready &&+ DPCT_CHECK_ERROR(m.kv_ready = new sycl::event()) != 0)) {+ err = "prefill: KV prefetch stream/events";+ return false;+ }+ }+ // An early return must drain DMA before the caller refills the borrowed expert slots.+ struct KvDrain {+ dpct::queue_ptr stream;+ ~KvDrain() { if (stream) stream->wait(); }+ } kv_drain{kv_prefetch ? m.kv_copy : &dpct::get_in_order_queue()};+ int64_t kv_prefetches = 0;const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size +(uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]};+ // layer split: a prompt of one chunk runs the stages one after the other, so the next stage's GPU idles while+ // this one reads; it streams and computes a share of this stage's experts then (set_stage_helper), in the+ // place of a --peer-device peer, and gives the stage back its own buffers when the run ends+ const bool single_chunk = hand_in_ == nullptr ? n <= m.T : single_chunk_;+ const bool helped = single_chunk && bind_stage_helper(n);+ if (helped) std::swap(m.pp, m.help_pp);+ struct HelpScope {+ Impl& m;+ bool on;+ ~HelpScope() {+ if (!on) return;+ const core::OnDevice d(m.pp->dev); // its work is done before the stage hands over; settle its streams+ m.pp->s_cp->wait();+ m.pp->s_out->wait();+ m.pp->s->wait();+ std::swap(m.pp, m.help_pp);+ }+ } help_scope{m, helped};PfTimer pt;PeTimer pe;if (m.pp) pe.dev = m.pp->dev; else pe.on = false;@@ -1867,6 +2363,62 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,int64_t qsa_index = 0, gdn_index = 0;for (int64_t l = 0; l < LB; ++l) (core::is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1;lap("step records");+ int64_t kv_pending = -1;+ auto kv_prefetch_after = [&](int64_t layer, int64_t ordinal) -> bool {+ try {+ if (!kv_prefetch || p0 <= 0) return true;+ if (kv_pending >= 0) return true; // one staging pool: the pending prefetch has not been consumed yet+ for (int64_t l = layer; l < LE; ++l) {+ if (!core::is_qsa_layer(g, l)) continue;+ const core::QsaState& state = ss.qsa_states[ordinal];+ if (state.kv_mode != 1) { ++ordinal; continue; }+ // Reuse one KV pool only after its last attention reader completes. The next layer's+ // [0, p0) host prefix is immutable throughout this chunk; its new rows are appended later.+ /*+ DPCT1024: The original code returned the error code that+ was further consumed by the program logic. This original code+ was replaced with 0. You may need to rewrite the program logic+ consuming the error code.+ */+ if (DPCT_CHECK_ERROR(dpct::sync_barrier(m.kv_released, cs)) !=+ 0 ||+ DPCT_CHECK_ERROR((m.kv_copy)->ext_oneapi_submit_barrier(+ {*m.kv_released})) != 0) {+ err = "prefill: releasing KV staging pool";+ return false;+ }+ strata::kernels::kv_stage_from_host(pools_of(m.stage, m.ident_table), state.host,+ core::qsa_kv_format(state), (p0 + s.page_size - 1) / s.page_size, s, m.kv_copy);+ /*+ DPCT1010: SYCL uses exceptions to report errors and does+ not use the error codes. The cudaPeekAtLastError function call+ was replaced with 0. You need to rewrite this code.+ */+ if (0 != 0 ||+ /*+ DPCT1024: The original code returned the error code+ that was further consumed by the program logic. This+ original code was replaced with 0. You may need to rewrite+ the program logic consuming the error code.+ */+ DPCT_CHECK_ERROR(+ dpct::sync_barrier(m.kv_ready, m.kv_copy)) != 0) {+ err = "prefill: enqueueing KV prefetch";+ return false;+ }+ kv_pending = ordinal;+ ++kv_prefetches;+ break;+ }+ return true;+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ if (!kv_prefetch_after(LB, qsa_index)) return false;// step 3: this chunk's stream - every non-resident expert of every layer, layer by layer in id order (entry// k lands in ring slot k % ring); a copy is issued once the entry `ring` before it is consumed (its slot's// `used` event recorded), so the copy stream never waits on an event that is not queued yet@@ -1941,7 +2493,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,if (ps_on) m.pp->pseq_start[(size_t) l] = m.pp->pseq.size();for (int32_t e = 0; e < m.g->n_expert; ++e) {if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;- if (m.pp && m.pp->peer->has(l, e)) continue; // multi-GPU: computed on (or read from) the peer+ if (m.pp && m.pp->peer && m.pp->peer->has(l, e)) continue; // multi-GPU: computed on (or read from) the peerint job = -1;const uint8_t* b = nullptr;if (gsrc != nullptr) { // read by the stager's thread when its turn comes (see Stager::Job)@@ -2164,7 +2716,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,const auto tp = Clock::now();const strata::kernels::PleWeights& pw = ss.ple.w;constexpr int64_t HD = strata::kernels::NG_HC_DIM;- const uint64_t per_token = (uint64_t) (3 * HD + N + 4) * 4 + (uint64_t) N * (bf16x2() ? 4 : 2) + 4096;+ const uint64_t per_token = (uint64_t) (3 * HD + N + 4) * 4 + (uint64_t) N * (bf16x2(m.f16_io) ? 4 : 2) + 4096;const int64_t SB = std::min<int64_t>(T, (int64_t) (m.region_bytes / per_token));for (int64_t s0 = 0; s0 < T; s0 += SB) {const int64_t nb = std::min(SB, T - s0);@@ -2176,7 +2728,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,float* val = carve_f((size_t) nb * N);float* gate = carve_f((size_t) nb * 4);uint16_t* e16 = (uint16_t*) carve_f((size_t) nb * N / 2);- uint16_t* e16_lo = bf16x2() ? (uint16_t*) carve_f((size_t) nb * N / 2) : nullptr;+ uint16_t* e16_lo = bf16x2(m.f16_io) ? (uint16_t*) carve_f((size_t) nb * N / 2) : nullptr;const float* emb = m.ple_emb + s0 * N;if (pw.key_bf16 != nullptr) {to_bf16(emb, e16, nb * N, m.cs, e16_lo);@@ -2219,16 +2771,79 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,*wu = need(v, su.c_str(), err), *wi = need(v, si.c_str(), err);if (!wn || !wd || !wu || !wi) return false;pt.mark(kPfHc, cs);+ // the xn16 token stride of this chunk (the writers of both halves and of the fused write-backs use it)+ const int64_t ldx = hc_pad() && T >= std::max<int64_t>(pf_switch_min_t(), 64) && !gr_unfused() &&+ !m.xn16_lo ? D + XN_PAD : D;if (gr_unfused()) gr_norm(m.R, (const float*) wn->data, EPS, m.xn, m.xn16, T, m.cs, m.xn16_lo);- else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs, m.xn16_lo);+ else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs, m.xn16_lo, ldx);normed = false;- if (!bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo)) return false;+ bool hcd = false;+ bool hdown = false;+ if (ldx != D && !pf_hcdown()) { // STRATA_HCD_EXACT: the exact-order down kernel when hipBLASLt would take 1176 / 1177+ hdown = wd->kind == core::WeightKind::Bf16InF32 && wd->data && wd->ne0 == D && wd->ne1 == LR &&+ m.gemm.bf16_hcd_exact(m.xn16, ldx, (const uint16_t*) wd->data, m.lo, T, LR, D);+ } else if (ldx != D) {+ if (wd->kind != core::WeightKind::Bf16InF32 || !wd->data || wd->ne0 != D || wd->ne1 != LR ||+ wi->kind != core::WeightKind::Bf16InF32 || !wi->data || wi->ne0 != D || wi->ne1 != HC ||+ !strata_pf_hcdown_bf16(m.xn16, ldx, (const uint16_t*) wd->data, (const uint16_t*) wi->data, LR,+ HC, m.lo, m.inj, T, D, m.cs)) {+ err = "prefill: STRATA_PF_HCDOWN could not run the hyper-connection projections";+ return false;+ }+ hcd = true;+ }+ if (!hcd && !hdown && !bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo, ldx != D ? ldx : 0)) return false;gr_silu(m.lo, m.lo16, T, m.cs, m.lo16_lo);- if (!bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo)) return false;- if (!bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo)) return false;- if (gr_unfused()) gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, m.mixed_bf_lo);- else gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h,- m.mixed_bf_lo);+ bool upmixed = false;+ if (hc_upmix() && T >= pf_switch_min_t() && !gr_unfused() && !m.lo16_lo && !m.mixed_bf_lo &&+ wu->kind == core::WeightKind::Bf16InF32 && wu->data && wu->ne0 == LR && wu->ne1 == D) {+ static int checks = [] { const char* e = std::getenv("STRATA_HC_UPMIX_CHECK"); return e ? std::atoi(e) : 0; }();+ if (checks > 0) { // the default pair first, kept for the comparison+ --checks;+ if (!bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err)) return false;+ gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h);+ std::vector<float> ref((size_t) T * N), got((size_t) T * N);+ /*+ DPCT1124: cudaMemcpyAsync is migrated to+ asynchronous memcpy API. While the origin API might be+ synchronous, it depends on the type of operand memory,+ so you may need to call wait() on event return by memcpy+ API to ensure synchronization behavior.+ */+ m.cs->memcpy(ref.data(), m.mixed, ref.size() * 4);+ upmixed = gr_upmix(m.lo16, (const uint16_t*) wu->data, m.R, m.grs, (const float*) wn->data,+ m.mixed, m.mixed_bf, m.mixed_h, T, m.cs);+ /*+ DPCT1124: cudaMemcpyAsync is migrated to+ asynchronous memcpy API. While the origin API might be+ synchronous, it depends on the type of operand memory,+ so you may need to call wait() on event return by memcpy+ API to ensure synchronization behavior.+ */+ m.cs->memcpy(got.data(), m.mixed, got.size() * 4);+ m.cs->wait();+ double e2 = 0, r2 = 0, emax = 0;+ for (size_t i = 0; i < ref.size(); ++i) {+ const double dd = (double) got[i] - ref[i];+ e2 += dd * dd; r2 += (double) ref[i] * ref[i]; emax = std::max(emax, std::fabs(dd));+ }+ std::fprintf(stderr, "strata: STRATA_HC_UPMIX_CHECK layer %lld half %d T %lld: mixed rel RMS %.3e, "+ "max |diff| %.3e (%s)\n", (long long) l, half, (long long) T,+ std::sqrt(e2 / std::max(r2, 1e-30)), emax, upmixed ? "upmix" : "upmix refused");+ } else {+ upmixed = gr_upmix(m.lo16, (const uint16_t*) wu->data, m.R, m.grs, (const float*) wn->data,+ m.mixed, m.mixed_bf, m.mixed_h, T, m.cs);+ }+ }+ if (!upmixed && !bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo)) return false;+ if (!hcd && !bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo, ldx != D ? ldx : 0)) return false;+ if (upmixed) {+ } else if (gr_unfused()) {+ gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, m.mixed_bf_lo);+ } else {+ gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h,+ m.mixed_bf_lo);+ }if (half == 0 && !core::is_qsa_layer(g, l)) {// ======================= GDN =======================@@ -2249,9 +2864,11 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,gdn_gates(m.ab, (const float*) wdt->data, (const float*) wsa->data, m.gate, m.beta, T, m.cs);gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, m.cs);pt.mark(kPfGdnRec, cs);- gdn_recurrence(state, m.hbuf, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, m.y, m.y_h, T, m.cs);+ const int64_t ld_y = pf_pad() && T >= std::max<int64_t>(pf_switch_min_t(), 64) ? ZV + ZV_PAD : 0;+ gdn_recurrence(state, m.hbuf, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, m.y, m.y_h, T, m.cs,+ ld_y);pt.mark(kPfGdnOut, cs);- if (!native_proj(m.gemm, wo, m.y_h, m.bo, T, v.name("ssm_out.weight"), err)) return false;+ if (!native_proj(m.gemm, wo, m.y_h, m.bo, T, v.name("ssm_out.weight"), err, 0, ld_y)) return false;++gdn_index;} else if (half == 0) {// ======================= QSA =======================@@ -2277,7 +2894,14 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,const bool staged = st.kv_mode == 1;if (staged) {pt.mark(kPfKvStage, cs);- strata::kernels::kv_stage_from_host(pools_of(m.stage, m.ident_table), st.host,+ if (kv_pending == qsa_index) {+ if (DPCT_CHECK_ERROR(cs->ext_oneapi_submit_barrier(+ {*m.kv_ready})) != 0) {+ err = "prefill: waiting for KV prefetch";+ return false;+ }+ kv_pending = -1;+ } else strata::kernels::kv_stage_from_host(pools_of(m.stage, m.ident_table), st.host,core::qsa_kv_format(st),(p0 + s.page_size - 1) / s.page_size, s, m.cs);pt.mark(kPfQsa, cs);@@ -2296,12 +2920,18 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,const bool host_by_dma = staged && kv_host_dma;const strata::kernels::KvHostPools* host_w = host_by_dma ? nullptr : &st.host;if (st.kv_hybrid) { // K8V4: K INT8 unrotated, V rotated Q4_0 (only V and the output rotate)+ // streamed: each half writes its part of the host copy and of the staging poolstrata::kernels::fwht256_inplace_cuda(m.Vc, T * 2, m.cs);+ const strata::kernels::KvHostPools hk = strata::kernels::kv_hybrid_k_half(st.host),+ hv = strata::kernels::kv_hybrid_v_half(st.host),+ sk = strata::kernels::kv_hybrid_k_half(m.stage),+ sv = strata::kernels::kv_hybrid_v_half(m.stage);+ const bool mirror = st.host.present();kv_append(m.Kc, m.Kc, T, p0, st.page_table, s.page_size, nullptr, nullptr,- st.k_q, st.k_q, st.k_scale, st.k_scale, m.cs, nullptr, // mode 0: no host mirror- staged ? &m.stage : nullptr);+ st.k_q, st.k_q, st.k_scale, st.k_scale, m.cs, mirror ? &hk : nullptr,+ staged ? &sk : nullptr);strata::kernels::kv_append_q4(st.v_q4, st.v_q4, st.page_table, p0, T, m.Vc, m.Vc, s, m.cs,- nullptr, staged ? &m.stage : nullptr);+ mirror ? &hv : nullptr, staged ? &sv : nullptr);} else {if (st.kv_rot) { // rotated K and V (kv_q4.hpp), the queries below too, the output backstrata::kernels::fwht256_inplace_cuda(m.Kc, T * 2, m.cs);@@ -2523,9 +3153,11 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,}if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(m.attn, T * 24, m.cs);pt.mark(kPfQsa, cs);- gate_attn(m.attn, m.Qf, m.attn_h, T, m.cs);- if (!native_proj(m.gemm, wo, m.attn_h, m.bo, T, v.name("attn_output.weight"), err)) return false;+ const int64_t ld_a = pf_pad() && T >= std::max<int64_t>(pf_switch_min_t(), 64) ? ZV + ZV_PAD : 0;+ gate_attn(m.attn, m.Qf, m.attn_h, T, m.cs, ld_a);+ if (!native_proj(m.gemm, wo, m.attn_h, m.bo, T, v.name("attn_output.weight"), err, 0, ld_a)) return false;++qsa_index;+ if (!kv_prefetch_after(l + 1, qsa_index)) return false;} else {// ======================= MoE =======================const core::WeightRef *wr = need(v, "ffn_gate_inp.weight", err),@@ -2559,7 +3191,8 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,// --peer-device: MMQ only, whether or not the peer took the prompt path (set_peer can decline), as// fused_ring() sized the ring and the buffers for itconst bool no_peer = !core::peer_portable();- const bool fused_nat = use_mmq && stream_all && no_peer && lay.native && fused::native_supported(mmq_gt, mmq_dt);+ const bool fused_only = mmq_plan().any && mmq_plan().fo[(size_t) l];+ const bool fused_nat = (use_mmq || fused_only) && stream_all && no_peer && lay.native && fused::native_supported(mmq_gt, mmq_dt);const bool fused_l = (use_mmq && stream_all && no_peer && !lay.native && fused::enabled()) || fused_nat;// #583 / #954: the fused layout's GU/H/Xq hold the grouping tables and the int8 rows, sized for// stream_all_min() - 1 tokens of MMQ's rows, so a layer that takes MMQ or the FP16 path at the FULL@@ -2697,7 +3330,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,continue;}if (c == 0 || (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) ||- !m.pp->peer->has(l, e))+ !m.pp->peer || !m.pp->peer->has(l, e))continue;if (rows_peer + c > m.pp->cap_rows) { ++m.pp->over_cap; continue; }on_peer[(size_t) e] = 1;@@ -2722,6 +3355,21 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,slot_h[(size_t) i] = p;src_h[(size_t) p] = (int32_t) (i / K);}+ // the experts, in id order: resident ones from VRAM, the others through the staging ring+ std::vector<int32_t> order, order_peer;+ for (int32_t e = 0; e < m.g->n_expert; ++e)+ if (m.cnt[(size_t) e] > 0 && (on_peer.empty() || on_peer[(size_t) e] != 2))+ (!on_peer.empty() && on_peer[(size_t) e] ? order_peer : order).push_back(e);+ for (int32_t e = 0; e < m.g->n_expert && !on_peer.empty(); ++e) // the peer-streamed ones last:+ if (on_peer[(size_t) e] == 2) order_peer.push_back(e); // their copies get the most time+ // Aurora (STRATA_MMQ_RESIDENT_SORT_NE=1, opt-in): a layer whose experts are ALL resident and+ // run through MMQ groups takes them in row-count order, so each 16-expert group's max_rows+ // (its padded tile rows) is close to its experts' own; slot/src/off are rebuilt coherently+ // before the upload, the routed ids, weights and the within-expert row order stay as they are.+ if (detail::mmq_resident_sort_eligible(detail::mmq_resident_sort_requested() && on_peer.empty(), use_mmq, lay.native,+ m.cache != nullptr, m.host_res ? m.host_res + (size_t) l * m.g->n_expert : nullptr,+ m.g->n_expert, stream_all, !stream_all || seq_start[(size_t) l] == seq_start[(size_t) l + 1]))+ detail::mmq_resident_sort_rows(ids_h, T * K, (int32_t) K, m.cnt, m.off, order, slot_h, src_h);if (grp_mapped) {copy_i32(m.slot_dev, m.grp_dev + m.grp_tk, T * K, m.cs);copy_i32(m.src_dev, m.grp_dev + 2 * m.grp_tk, T * K, m.cs);@@ -2747,13 +3395,6 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,m.cs->memcpy(m.src_dev, m.src_host.data(),(size_t)T * K * 4);}- // the experts, in id order: resident ones from VRAM, the others through the staging ring- std::vector<int32_t> order, order_peer;- for (int32_t e = 0; e < m.g->n_expert; ++e)- if (m.cnt[(size_t) e] > 0 && (on_peer.empty() || on_peer[(size_t) e] != 2))- (!on_peer.empty() && on_peer[(size_t) e] ? order_peer : order).push_back(e);- for (int32_t e = 0; e < m.g->n_expert && !on_peer.empty(); ++e) // the peer-streamed ones last:- if (on_peer[(size_t) e] == 2) order_peer.push_back(e); // their copies get the most timen_order = order.size();const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, 1280, N) : 0;const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, 640) : 0;@@ -2794,6 +3435,16 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,peer_now = use_mmq && !order_peer.empty();if (peer_now) {PeerPrefill& P = *m.pp;+ /*+ DPCT1124: cudaMemcpyAsync is migrated to+ asynchronous memcpy API. While the origin API might+ be synchronous, it depends on the type of operand+ memory, so you may need to call wait() on event+ return by memcpy API to ensure synchronization+ behavior.+ */+ if (!P.p2p) m.cs->memcpy(P.host_x, m.mixed,+ (size_t)T * N * 4);dpct::sync_barrier(P.ev_in, m.cs);int prevd = 0;prevd = dpct::get_current_device_id();@@ -2818,22 +3469,30 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,return by memcpy API to ensure synchronizationbehavior.*/- dpct::async_dpct_memcpy(P.mixed, P.dev, m.mixed,- prevd, (size_t)T * N * 4,- *ps);- /*- DPCT1124: cudaMemcpyAsync is migrated to- asynchronous memcpy API. While the origin API might- be synchronous, it depends on the type of operand- memory, so you may need to call wait() on event- return by memcpy API to ensure synchronization- behavior.- */- ps->memcpy(P.src,- src_h +- rows_local, // multi-GPU: the mapped- // table when on- (size_t)rows_peer * 4);+ if (P.p2p) dpct::async_dpct_memcpy(+ P.mixed, P.dev, m.mixed, prevd,+ (size_t)T * N * 4, *ps);+ else copy_f32_wide(P.mixed, P.host_x, T * N, ps);+ P.back_at = rows_local;+ P.back_rows = rows_peer;+ if (P.p2p) {+ /*+ DPCT1124: cudaMemcpyAsync is migrated to+ asynchronous memcpy API. While the origin API+ might be synchronous, it depends on the type of+ operand memory, so you may need to call wait()+ on event return by memcpy API to ensure+ synchronization behavior.+ */+ ps->memcpy(+ P.src,+ src_h + rows_local, // multi-GPU: the mapped+ // table when on+ (size_t)rows_peer * 4);+ } else {+ std::memcpy(P.host_src, src_h + rows_local, (size_t) rows_peer * 4);+ copy_i32(P.src, P.host_src, rows_peer, ps);+ }const size_t n = order_peer.size();if (P.compact) {// groups of up to MMQ_GROUP experts and at most G rows, each computed from its own rows@@ -2857,16 +3516,21 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,P.bounds_host[n + 1 + g2 * (MMQ_GROUP + 1) + i] =P.bounds_host[std::min(P.groups[g2].second, P.groups[g2].first + i)] -P.bounds_host[P.groups[g2].first];- /*- DPCT1124: cudaMemcpyAsync is migrated to- asynchronous memcpy API. While the origin API- might be synchronous, it depends on the type of- operand memory, so you may need to call wait()- on event return by memcpy API to ensure- synchronization behavior.- */- ps->memcpy(P.bounds, P.bounds_host.data(),- P.bounds_host.size() * 4);+ if (P.p2p || P.bounds_host.size() > PeerPrefill::kHostBounds) {+ /*+ DPCT1124: cudaMemcpyAsync is migrated+ to asynchronous memcpy API. While the origin+ API might be synchronous, it depends on the+ type of operand memory, so you may need to+ call wait() on event return by memcpy API to+ ensure synchronization behavior.+ */+ ps->memcpy(P.bounds, P.bounds_host.data(),+ P.bounds_host.size() * 4);+ } else {+ std::memcpy(P.host_bounds, P.bounds_host.data(), P.bounds_host.size() * 4);+ copy_i32(P.bounds, P.host_bounds, (int64_t) P.bounds_host.size(), ps);+ }pe.mark(kPeMoeGemm, ps);const auto& f = lay.fmt[(size_t) l];for (size_t g2 = 0; g2 < ng; ++g2) {@@ -2924,7 +3588,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,gu.w = P.grp_gu; gu.type = mmq_gt; gu.w_rows = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub;gu.n = ngx; gu.xq = P.Xq_g; gu.bounds = rel; gu.ids = P.ident;gu.total_rows = nr; gu.max_rows = maxr; gu.dst = P.GU_g; gu.ld_dst = 1280;- P.ctx->run(gu, ps);+ P.run_ctx->run(gu, ps);mmq::swiglu(P.GU_g, P.H_g, nr, 640, !lay.native, ps);mmq::quantize(P.H_g, nullptr, P.Hq_g, mmq_dt, 640, 640, nr, ps);const int b = (int) (g2 & 1);@@ -2937,24 +3601,39 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,dn.n = ngx; dn.xq = P.Hq_g; dn.bounds = rel;dn.ids = P.ident; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = P.Dm_b[b];dn.ld_dst = N;- P.ctx->run(dn, ps);+ P.run_ctx->run(dn, ps);dpct::sync_barrier(P.ev_grp[g2 % PeerPrefill::kGrpEv], ps);(P.s_out)->ext_oneapi_submit_barrier({*P.ev_grp[g2 % PeerPrefill::kGrpEv]});- /*- DPCT1124: cudaMemcpyPeerAsync is- migrated to asynchronous memcpy API. While- the origin API might be synchronous, it- depends on the type of operand memory, so- you may need to call wait() on event return- by memcpy API to ensure synchronization- behavior.- */- dpct::async_dpct_memcpy(- m.Dm + (size_t)(rows_local + r0) * N,- prevd, P.Dm_b[b], P.dev,- (size_t)nr * N * 4, *(P.s_out));+ if (P.p2p)+ /*+ DPCT1124: cudaMemcpyPeerAsync is+ migrated to asynchronous memcpy API.+ While the origin API might be+ synchronous, it depends on the type of+ operand memory, so you may need to call+ wait() on event return by memcpy API to+ ensure synchronization behavior.+ */+ dpct::async_dpct_memcpy(+ m.Dm ++ (size_t)(rows_local + r0) * N,+ prevd, P.Dm_b[b], P.dev,+ (size_t)nr * N * 4, *(P.s_out));+ else // the primary reads them when it combines (below)+ /*+ DPCT1124: cudaMemcpyAsync is+ migrated to asynchronous memcpy API.+ While the origin API might be+ synchronous, it depends on the type of+ operand memory, so you may need to call+ wait() on event return by memcpy API to+ ensure synchronization behavior.+ */+ P.s_out->memcpy(+ P.host_rows + (size_t)r0 * N,+ P.Dm_b[b], (size_t)nr * N * 4);dpct::sync_barrier(P.ev_dm[b], P.s_out);P.dm_live[b] = true;}@@ -2967,16 +3646,21 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,for (size_t i = 0; i <= MMQ_GROUP; ++i)P.bounds_host[n + 1 + g2 * (MMQ_GROUP + 1) + i] =P.bounds_host[std::min(n, g2 * MMQ_GROUP + i)] - P.bounds_host[g2 * MMQ_GROUP];- /*- DPCT1124: cudaMemcpyAsync is migrated to- asynchronous memcpy API. While the origin API- might be synchronous, it depends on the type of- operand memory, so you may need to call wait()- on event return by memcpy API to ensure- synchronization behavior.- */- ps->memcpy(P.bounds, P.bounds_host.data(),- P.bounds_host.size() * 4);+ if (P.p2p || P.bounds_host.size() > PeerPrefill::kHostBounds) {+ /*+ DPCT1124: cudaMemcpyAsync is migrated+ to asynchronous memcpy API. While the origin+ API might be synchronous, it depends on the+ type of operand memory, so you may need to+ call wait() on event return by memcpy API to+ ensure synchronization behavior.+ */+ ps->memcpy(P.bounds, P.bounds_host.data(),+ P.bounds_host.size() * 4);+ } else {+ std::memcpy(P.host_bounds, P.bounds_host.data(), P.bounds_host.size() * 4);+ copy_i32(P.bounds, P.host_bounds, (int64_t) P.bounds_host.size(), ps);+ }mmq::quantize(P.mixed, P.src, P.Xq, mmq_gt, N, N, rows_peer, ps);pe.mark(kPeMoeGemm, ps);const auto& f = lay.fmt[(size_t) l];@@ -3003,7 +3687,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,gu.w = P.grp_gu; gu.type = mmq_gt; gu.w_rows = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub;gu.n = ngx; gu.xq = P.Xq; gu.bounds = P.bounds + j0; gu.ids = P.ident;gu.total_rows = rows_peer; gu.max_rows = maxr; gu.dst = P.GU; gu.ld_dst = 1280;- P.ctx->run(gu, ps);+ P.run_ctx->run(gu, ps);mmq::swiglu(P.GU + r0 * 1280, P.H + r0 * 640, nr, 640, !lay.native, ps);mmq::quantize(P.H + r0 * 640, nullptr, P.Hq, mmq_dt, 640, 640, nr, ps);mmq::Product dn;@@ -3011,7 +3695,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,dn.n = ngx; dn.xq = P.Hq; dn.bounds = P.bounds + n + 1 + g2 * (MMQ_GROUP + 1);dn.ids = P.ident; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = P.Dm + r0 * N;dn.ld_dst = N;- P.ctx->run(dn, ps);+ P.run_ctx->run(dn, ps);if (P.out_pipe && nr > 0) { // this group's rows go back while the next group computesdpct::sync_barrier(P.ev_grp[g2], ps);(P.s_out)->ext_oneapi_submit_barrier(@@ -3360,7 +4044,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,} else {const bool r0 = m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0;const uint8_t* bp = r0 ? m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e])- : (m.pp ? m.pp->peer->slot_ptr(l, e) : nullptr); // over the cap: P2P+ : (m.pp && m.pp->peer ? m.pp->peer->slot_ptr(l, e) : nullptr); // over the cap: P2Pif (bp == nullptr) { err = "prefill: an expert is neither resident, streamed nor on the peer"; return false; }++stats_.experts_resident;if (!compute(j, bp, -1)) return false;@@ -3371,9 +4055,11 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,}}pt.mark(kPfCombine, cs);- if (peer_now)(m.cs)->ext_oneapi_submit_barrier(- {*m.pp->ev_done}); // multi-GPU: the peer's rows are in- // Dm+ if (peer_now) { // multi-GPU: the peer's rows are in Dm (or, without P2P, in host memory)+ (m.cs)->ext_oneapi_submit_barrier({*m.pp->ev_done});+ if (!m.pp->p2p)+ copy_f32_wide(m.Dm + (size_t) m.pp->back_at * N, m.pp->host_rows, m.pp->back_rows * N, m.cs);+ }moe_combine(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.bo, T, m.cs);// debug: STRATA_DBG_NAN=1 reports the first layer of a chunk whose MoE produced non-finite valuesif (static const bool dbg = std::getenv("STRATA_DBG_NAN") != nullptr; dbg) {@@ -3435,22 +4121,119 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,// touches R in between (not the stage's last half, not before the PLE block of layer 1, not under a// control vector)const int64_t nl = half == 0 ? l : l + 1;- const bool fuse = !gr_unfused() && nl < LE && !(half == 1 && nl == 1 && ple_on) &&- !(half == 1 && strata::kernels::cvec().covers(l));+ const bool steered = half == 1 && strata::kernels::cvec().covers(l);+ const float *cv_dir = nullptr, *cv_s = nullptr;+ const int* cv_on = nullptr;+ const bool cv_fused = steered && cvec_fuse() && !gr_unfused() && nl < LE && !(nl == 1 && ple_on) &&+ strata::kernels::cvec().n_embd == N && strata::kernels::cvec().hc == HC &&+ strata::kernels::cvec_tables(&cv_dir, &cv_s, &cv_on);+ const bool fuse = !gr_unfused() && nl < LE && !(half == 1 && nl == 1 && ple_on) && (!steered || cv_fused);const core::WeightRef* wnn = nullptr;if (fuse) {const core::LayerView vn(*m.wt, nl);wnn = need(vn, half == 0 ? "hc_ffn_norm.weight" : "hc_attn_norm.weight", err);if (!wnn) return false;}- if (wnn) {+ if (wnn && cv_fused) {+ // STRATA_CVEC_FUSE_CHECK=N: on the first N fused writes, also run the three-kernel path on a copy+ // of R and report whether R, the row scales and the BF16 image are bit-identical+ static int checks = [] { const char* e = std::getenv("STRATA_CVEC_FUSE_CHECK"); return e ? std::atoi(e) : 0; }();+ if (checks > 0) {+ --checks;+ float *Rc = nullptr, *rc = nullptr;+ uint16_t* xc = nullptr;+ Rc = (float *)sycl::malloc_device(+ (size_t)T * D * 4, dpct::get_in_order_queue());+ rc = (float *)sycl::malloc_device(+ (size_t)T * HC * 4, dpct::get_in_order_queue());+ xc = (uint16_t *)sycl::malloc_device(+ (size_t)T * D * 2, dpct::get_in_order_queue());+ /*+ DPCT1124: cudaMemcpyAsync is migrated to+ asynchronous memcpy API. While the origin API might be+ synchronous, it depends on the type of operand memory,+ so you may need to call wait() on event return by memcpy+ API to ensure synchronization behavior.+ */+ m.cs->memcpy(Rc, m.R, (size_t)T * D * 4);+ gr_write(Rc, m.bo, m.inj, HC, T, m.cs);+ strata::kernels::cvec_apply(Rc, l, T, D, nullptr, 0, nullptr, 0, false, m.cs);+ gr_norm_rs(Rc, (const float*) wnn->data, EPS, rc, xc, T, m.cs, nullptr, D);+ gr_write_cvec_norm_rs(m.R, m.bo, m.inj, HC, cv_dir + l * N, cv_s + l, cv_on,+ strata::kernels::cvec().mode, (const float*) wnn->data, EPS, m.grs,+ m.xn16, T, m.cs, m.xn16_lo, ldx);+ std::vector<float> a((size_t) T * D), b((size_t) T * D), ra((size_t) T * HC), rb((size_t) T * HC);+ std::vector<uint16_t> xa((size_t) T * D), xb((size_t) T * D);+ /*+ DPCT1124: cudaMemcpyAsync is migrated to+ asynchronous memcpy API. While the origin API might be+ synchronous, it depends on the type of operand memory,+ so you may need to call wait() on event return by memcpy+ API to ensure synchronization behavior.+ */+ m.cs->memcpy(a.data(), m.R, a.size() * 4);+ /*+ DPCT1124: cudaMemcpyAsync is migrated to+ asynchronous memcpy API. While the origin API might be+ synchronous, it depends on the type of operand memory,+ so you may need to call wait() on event return by memcpy+ API to ensure synchronization behavior.+ */+ m.cs->memcpy(b.data(), Rc, b.size() * 4);+ /*+ DPCT1124: cudaMemcpyAsync is migrated to+ asynchronous memcpy API. While the origin API might be+ synchronous, it depends on the type of operand memory,+ so you may need to call wait() on event return by memcpy+ API to ensure synchronization behavior.+ */+ m.cs->memcpy(ra.data(), m.grs, ra.size() * 4);+ /*+ DPCT1124: cudaMemcpyAsync is migrated to+ asynchronous memcpy API. While the origin API might be+ synchronous, it depends on the type of operand memory,+ so you may need to call wait() on event return by memcpy+ API to ensure synchronization behavior.+ */+ m.cs->memcpy(rb.data(), rc, rb.size() * 4);+ /*+ DPCT1124: cudaMemcpyAsync is migrated to+ asynchronous memcpy API. While the origin API might be+ synchronous, it depends on the type of operand memory,+ so you may need to call wait() on event return by memcpy+ API to ensure synchronization behavior.+ */+ m.cs->memcpy(xa.data(), m.xn16, xa.size() * 2);+ /*+ DPCT1124: cudaMemcpyAsync is migrated to+ asynchronous memcpy API. While the origin API might be+ synchronous, it depends on the type of operand memory,+ so you may need to call wait() on event return by memcpy+ API to ensure synchronization behavior.+ */+ m.cs->memcpy(xb.data(), xc, xb.size() * 2);+ m.cs->wait();+ sycl::free(Rc, dpct::get_in_order_queue());+ sycl::free(rc, dpct::get_in_order_queue());+ sycl::free(xc, dpct::get_in_order_queue());+ std::fprintf(stderr, "strata: STRATA_CVEC_FUSE_CHECK layer %lld T %lld: R %s, rs %s, xn16 %s\n",+ (long long) l, (long long) T,+ std::memcmp(a.data(), b.data(), a.size() * 4) ? "DIFFERS" : "identical",+ std::memcmp(ra.data(), rb.data(), ra.size() * 4) ? "DIFFERS" : "identical",+ std::memcmp(xa.data(), xb.data(), xa.size() * 2) ? "DIFFERS" : "identical");+ } else+ gr_write_cvec_norm_rs(m.R, m.bo, m.inj, HC, cv_dir + l * N, cv_s + l, cv_on,+ strata::kernels::cvec().mode, (const float*) wnn->data, EPS, m.grs, m.xn16,+ T, m.cs, m.xn16_lo, ldx);+ normed = true;+ } else if (wnn) {gr_write_norm_rs(m.R, m.bo, m.inj, HC, (const float*) wnn->data, EPS, m.grs, m.xn16, T, m.cs,- m.xn16_lo);+ m.xn16_lo, ldx);normed = true;} else {gr_write(m.R, m.bo, m.inj, HC, T, m.cs);}- if (half == 1 && strata::kernels::cvec().covers(l)) // --control-vector-scaled+ if (steered && !cv_fused) // --control-vector-scaledstrata::kernels::cvec_apply(m.R, l, T, D, nullptr, 0, nullptr, 0, false, m.cs);}}@@ -3465,8 +4248,8 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,core::progress_at("reading the prompt (batched): finishing the chunk from token", p0);pt.mark(kPfStart, cs);if (next_ != nullptr) {- // the rows to the host buffer the next stage read two chunks ago (it has finished: waited below)- float* h = m.hand[hand_buf];+ // The current hand-off slot was used two chunks ago.+ float* h = m.hand[hand_buf_];/*DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpyAPI. While the origin API might be synchronous, it depends on the@@ -3491,14 +4274,17 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,dpct::get_error_string_dummy(0);return false;}- // this stage's state is at the chunk's end now (synced) and moves on with the next chunk below+ // Wait only for the DIRECT successor's previous chunk. That successor+ // may already have forwarded its older chunk to later GPUs.if (on_stage_chunk && !on_stage_chunk(p0 + T, err)) return false;- if (next_run.valid() && !next_run.get()) { err = next_err; return false; }+ if (next_run_.valid() && !next_run_.get()) { err = next_err_; return false; }+ next_err_.clear();next_->hand_in_ = h;- next_run = std::async(std::launch::async, [this, tokens, c0, T, p0, &next_err] {- return next_->run(tokens + c0, T, p0, next_err);+ next_->single_chunk_ = single_chunk;+ next_run_ = std::async(std::launch::async, [this, tokens, c0, T, p0] {+ return next_->run_impl(tokens + c0, T, p0, next_err_);});- hand_buf ^= 1;+ hand_buf_ ^= 1;continue; // the last stage reports the chunk (on_chunk)}if (const char* dump = std::getenv("STRATA_PREFILL_DUMP_R")) { // debug: the final residuals, every 64th@@ -3516,6 +4302,30 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,std::fclose(f);}}+ if (const char* dump = std::getenv("STRATA_PREFILL_DUMP_R_ALL")) {+ // S25 (draft-layer distillation data, opt-in): every position's final multi-stream residual as BF16+ // (round-to-nearest-even), rows in position order, appended across chunks and requests: [n][hc*n_embd]+ m.cs->wait();+ if (std::FILE* f = std::fopen(dump, "ab")) {+ constexpr int64_t kRows = 512;+ std::vector<float> rows((size_t) (kRows * D));+ std::vector<uint16_t> out((size_t) (kRows * D));+ for (int64_t t0 = 0; t0 < T; t0 += kRows) {+ const int64_t nr = std::min<int64_t>(kRows, T - t0);+ dpct::get_in_order_queue()+ .memcpy(rows.data(), m.R + t0 * D, (size_t)(nr * D) * 4)+ .wait();+ for (int64_t i = 0; i < nr * D; ++i) {+ uint32_t u;+ std::memcpy(&u, &rows[(size_t) i], 4);+ u += 0x7fffu + ((u >> 16) & 1u);+ out[(size_t) i] = (uint16_t) (u >> 16);+ }+ std::fwrite(out.data(), 2, (size_t) (nr * D), f);+ }+ std::fclose(f);+ }+ }if (on_chunk || on_stage_chunk) {const auto toc = Clock::now();if (DPCT_CHECK_ERROR(m.cs->wait()) != 0) {@@ -3541,7 +4351,8 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,host_chunk_ms += ms_since(toc2);}}- if (next_run.valid() && !next_run.get()) { err = next_err; return false; }+ // Do not drain the successor here. This is the overlap: an intermediate+ // stage can return while later GPUs are still processing the previous chunk.ss.ple_prev[0] = prev[0];ss.ple_prev[1] = prev[1];if (std::getenv("STRATA_DBG_NAN") != nullptr) { // debug: the state the prompt leaves for the token path@@ -3603,6 +4414,28 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,dpct::get_error_string_dummy(cst);return false;}+ if (kv_prefetch) {+ /*+ DPCT1000: Error handling if-stmt was detected but could not be+ rewritten.+ */+ if (const dpct::err0 cst = DPCT_CHECK_ERROR(m.kv_copy->wait());+ cst != 0) {+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use+ error codes. Please replace the "get_error_string_dummy(...)" with a+ real error-handling function.+ */+ /*+ DPCT1001: The statement could not be removed.+ */+ err = std::string("prefill: KV prefetch stream: ") ++ dpct::get_error_string_dummy(cst);+ return false;+ }+ std::fprintf(stderr, "strata KV prefetch: %lld layer prefixes, single existing staging pool\n",+ (long long) kv_prefetches);+ }stats_.ms_total += ms_since(t_start);if (pt.on) {pt.fold();@@ -3671,4 +4504,39 @@ catch (sycl::exception const &exc) {std::exit(1);}+bool Prefill::drain_pipeline(std::string& err) {+ bool ok = true;++ if (next_run_.valid()) {+ if (!next_run_.get()) {+ err = next_err_;+ ok = false;+ }+ }++ if (next_ != nullptr) {+ std::string tail_err;+ if (!next_->drain_pipeline(tail_err)) {+ if (ok) err = tail_err;+ ok = false;+ }+ }++ return ok;+}++bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err) {+ const bool body_ok = run_impl(tokens, n, pos0, err);++ std::string drain_err;+ const bool drain_ok = drain_pipeline(drain_err);++ if (!body_ok) return false;+ if (!drain_ok) {+ err = drain_err;+ return false;+ }+ return true;+}+} // namespace strata::prefilldiff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cppindex 5372106f9..511a5efd0 100644--- a/sycl/src/program/generate.cpp+++ b/sycl/src/program/generate.cpp@@ -25,9 +25,13 @@#include <sycl/sycl.hpp>#include <dpct/dpct.hpp>#include "strata/sycl_queue.hpp"+#include "strata/core/arch_defaults.hpp"+#include "strata/core/dma_batch.hpp"#include "strata/core/device.hpp"+#include "strata/core/remote_expert_opt.hpp"#include "strata/core/expert_cache.hpp"#include "strata/core/conversation_snapshot.hpp"+#include "strata/core/conversation_file.hpp"#include "strata/core/conversation_memory.hpp"#include "strata/core/coupled_draft.hpp"#include "strata/core/expert_source.hpp"@@ -50,6 +54,7 @@ namespace strata::prefill { void set_nonresident_share(double share); } // SYC#include "strata/kernels/s2_expert_grouped.hpp"#include "strata/kernels/sampler.hpp"#include "strata/kernels/verify_kernels.hpp"+#include "strata/kernels/elementwise.hpp"#include "strata/kernels/shared_expert.hpp"#include "strata/kernels/native_moe.hpp"#include "strata/kernels/native_gdn.hpp"@@ -67,7 +72,9 @@ namespace strata::prefill { void set_nonresident_share(double share); } // SYC#include "strata/core/native_dense.hpp"#include "strata/program/logits_selection.hpp"#include "strata/program/conv_cache.hpp"+#include "strata/program/message_boundary.hpp"#include "strata/spec/draft_policy.hpp"+#include "strata/spec/draft_source.hpp"#include "strata/spec/suffix_drafter.hpp"#include "strata/kernels/cvec.hpp"#include "strata/core/progress.hpp"@@ -91,7 +98,9 @@ namespace strata::prefill { void set_nonresident_share(double share); } // SYC#include <array>#include <chrono>#include <algorithm>+#include <memory>#include <iostream>+#include <functional>#include <future>#include <thread>#include <atomic>@@ -144,9 +153,9 @@ std::string vram_free_note() try {if (DPCT_CHECK_ERROR(dpct::get_current_device().get_memory_info(free_b, total_b)) != 0) {/*- DPCT1010: SYCL uses exceptions to report errors and does not use the- error codes. The cudaGetLastError function call was replaced with 0. You- need to rewrite this code.+ DPCT1010: SYCL uses exceptions to report errors and does not use+ the error codes. The cudaGetLastError function call was replaced with 0.+ You need to rewrite this code.*/(void)0;return {};@@ -180,6 +189,42 @@ bool pin_blobs_on() {return false;#endif}+// #884 (HIP, opt-in STRATA_HIP_ADAPT_KERNEL_COPY=1): an adaptive swap's host-to-device copy as a kernel on the refill stream+// instead of a copy-engine (SDMA) memcpy. 2x RX 6900 XT hung after a long prompt only with the MMQ prompt path, adaptive swaps+// AND SDMA together (any one off avoids it; the barrier packet that never passes is a ROCm-side problem, #884). This keeps+// the swaps off SDMA without turning SDMA off for the prompt read (HSA_ENABLE_SDMA=0 costs 10-24% of it). Needs the source to+// be mapped, 16-byte aligned memory (the registered arena); anything else takes the normal cudaMemcpyAsync.+dpct::err0 adapt_copy_h2d(void *dst, const void *src, size_t bytes,+ dpct::queue_ptr st) try {+#if defined(STRATA_USE_HIP)+ static const bool kernel = [] {+ const char* e = std::getenv("STRATA_HIP_ADAPT_KERNEL_COPY");+ const bool on = e != nullptr && e[0] == '1';+ if (on) std::fprintf(stderr, "strata: STRATA_HIP_ADAPT_KERNEL_COPY=1: adaptive swaps copy with a kernel, not SDMA (#884)\n");+ return on;+ }();+ if (kernel && bytes % 16 == 0 && ((uintptr_t) src & 15) == 0 && ((uintptr_t) dst & 15) == 0) {+ void* dsrc = nullptr;+ if (cudaHostGetDevicePointer(&dsrc, const_cast<void*>(src), 0) == cudaSuccess && dsrc != nullptr) {+ strata::kernels::copy_from_mapped((float*) dst, (const float*) dsrc, (int64_t) (bytes / 4), (void*) st);+ return cudaGetLastError();+ }+ (void) cudaGetLastError(); // not registered / not mapped: the ordinary copy+ }+#endif+ /*+ DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While+ the origin API might be synchronous, it depends on the type of operand+ memory, so you may need to call wait() on event return by memcpy API to+ ensure synchronization behavior.+ */+ return DPCT_CHECK_ERROR(st->memcpy(dst, src, bytes));+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}int pin_blobs(std::vector<std::pair<uintptr_t, uintptr_t>> r, std::vector<void*>& live) {int failed = 0; // ranges left pageable (a copy from them still works, through the driver's staging)#if (defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)) && !defined(_WIN32)@@ -244,6 +289,13 @@ bool refill_blocking() {using Clock = std::chrono::steady_clock;+// --pipeline-windows: every STRATA_PIPELINE_* test and tuning variable (THETA, FORCE_MISS, SWITCH, LOG, TRACE, DOOM_SKIP,+// LOOKUP_PON, PRESTAGE, AGREE, SNAP_OVERLAP) is read only with STRATA_PIPELINE_DEBUG=1; without it the defaults apply.+static const char* pipe_dbg_env(const char* name) {+ static const bool on = [] { const char* v = std::getenv("STRATA_PIPELINE_DEBUG"); return v != nullptr && v[0] != 0 && v[0] != '0'; }();+ return on ? std::getenv(name) : nullptr;+}+// The resident RAM mode and the adaptive tier. A swap copies `in` (held in RAM) into the slot of `out` (held only// by that slot). Before the slot is overwritten, `out`'s bytes are copied back from it into an exchange buffer, so// the CPU computes `out` from RAM while the swap is in flight; when the swap has landed, `commit_exchanges` moves@@ -251,15 +303,25 @@ using Clock = std::chrono::steady_clock;// reads the file. Swaps that need no exchange (`out` in the lend region is held in RAM already; or `in` is not) go// on as before; ones beyond the buffers' room wait for a later round. Runs on the adaptive tier's thread while the// GPU commits and drafts: the copies back are on its stream, and waited for before the refills are queued.-template <class Swap>+//+// With a layer split, `host_res` holds slot numbers of WHICHEVER cache owns the layer, so the copy back must read the+// owning card's cache on that card's stream: `locate(layer)` names them (cache, stream, device; -1 = CUDA0). Reading+// a later stage's slot number out of CUDA0's cache copied another expert's bytes into RAM - the resident mode with a+// split then computed some experts from the wrong weights after the first adaptive swaps (garbage output).+struct SwapHome {+ strata::core::ExpertCache* cache;+ dpct::queue_ptr stream;+ int dev;+};+template <class Swap, class Locate>bool resident_stage_swaps(strata::core::FileExpertSource &src,- strata::core::ExpertCache &cache,const std::vector<int32_t> &host_res,int64_t n_expert, std::vector<Swap> &swaps,- dpct::queue_ptr stream) try {+ Locate locate) try {if (!src.complement_ready() || swaps.empty()) return true;struct Staged { int32_t layer, in, out; int64_t q; };std::vector<Staged> staged;+ std::vector<SwapHome> used;std::vector<Swap> kept;kept.reserve(swaps.size());for (const Swap& s : swaps) {@@ -268,24 +330,31 @@ bool resident_stage_swaps(strata::core::FileExpertSource &src,if (q >= src.exchange_capacity()) continue;const int32_t slot = host_res[(size_t) s.layer * (size_t) n_expert + (size_t) s.out];if (slot < 0) continue;+ const SwapHome home = locate(s.layer);+ const strata::core::OnDevice on(home.dev);/*DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.While the origin API might be synchronous, it depends on the type ofoperand memory, so you may need to call wait() on event return by memcpyAPI to ensure synchronization behavior.*/- if (DPCT_CHECK_ERROR(stream->memcpy(- src.exchange_buffer(q), cache.device_slot(slot),- (size_t)strata::kernels::cpu::expert_layout().blob_bytes(- s.layer))) != 0)- return false;++ bool seen = false;+ for (const SwapHome& u : used) seen = seen || u.stream == home.stream;+ if (!seen) used.push_back(home);staged.push_back({s.layer, s.in, s.out, q});kept.push_back(s);}if (!staged.empty()) {- if (DPCT_CHECK_ERROR(stream->wait()) != 0) return false;+ for (const SwapHome& u : used) {+ const strata::core::OnDevice on(u.dev);+ }for (const Staged& x : staged)- if (!src.stage_exchange(x.layer, x.in, x.out, x.q)) return false;+ if (!src.stage_exchange(x.layer, x.in, x.out, x.q)) {+ std::fprintf(stderr, "strata: stage_exchange refused layer %d in %d out %d\n", (int) x.layer,+ (int) x.in, (int) x.out);+ return false;+ }}swaps.swap(kept);return true;@@ -365,6 +434,7 @@ struct Options {bool ple_sync_submit = false; ///< A/B arm: submit reads on the token thread, no I/O workerstd::string kv = "fp16"; ///< plan v0.3 P7: KV storage, fp16 (default) or int8 (half the VRAM)int64_t kv_resident = 0; ///< KV streaming: resident cells per QSA layer (0: all in VRAM)+ bool kv_grow = false; ///< the elastic K/V (--kv-grow, STRATA_KV_GROW=1; kvg_ensure)std::string dump_residual;/// The head input, `bb.mixed`. It exists so the head can be SPLIT: steps 1-4 (the per-stream norm, the two/// bf16 projections and the stream mean) recompute cheaply in Python, and only the 794 MB GEMV does not.@@ -397,6 +467,8 @@ struct Options {int pool_workers = 0; ///< R2.2: 0 = "all physical cores minus the host's"; >0 overrides/// #272: the pool's core layout; `all` (the default) is the layout it always had, auto / p-cores are opt-instrata::kernels::cpu::PoolAffinity pool_affinity = strata::kernels::cpu::PoolAffinity::All;+ /// --host-core first|last (STRATA_HOST_CORE): the host thread's core (see HostCore in pool.hpp)+ std::string host_core;/// R2.2's first half, as an A/B arm. **ON by default**, because the measurement that justifies it is the/// pool's own drain: 33.7 GB/s against 5/6 x 44.14 = 36.8 for five workers, on a machine whose sixth core/// is reserved for a host thread that has nothing to do while the drain runs.@@ -427,6 +499,8 @@ struct Options {/// measurement found nothing - see `expert_cache_per_layer`.int expert_cache = 0;std::array<int, 3> expert_cache_remote{}; ///< CUDA1..3 slots; CUDA0 keeps dense/state/MTP+ std::array<bool, 3> expert_cache_remote_auto{};+ bool remote_expert_opt = false; ///< optional optimization of the existing remote-expert decode pathstd::string expert_cache_remote_placement = "stripe"; ///< stripe experts or assign complete layers to CUDA1..3bool expert_cache_cpu_order = false;/// **R4.2g. ROUND 328 MEASURED THAT THE GLOBAL ADMISSION POLICY CANNOT WORK, AND THIS IS THE FIX.**@@ -482,6 +556,9 @@ struct Options {/// `VRAM <reserve_mib>` command can give part of it back to other programs and take it again. Off: one cudaMalloc.bool vram_elastic = false;int64_t vram_segment_mib = 512;+ /// `--vram-reserve-later-mib N`: the reserve on a layer split's later cards (default: the same as the first).+ /// A card that drives no display needs less than the one the monitors are on.+ int vram_reserve_later_mib = -1;/// Plan v0.3 P5: batched prompt processing in chunks of this many tokens (0 = the token path).int64_t prefill_chunk = 0;/// `--prefill auto`: the largest chunk (up to 8192) whose buffers the expert cache can lend. Every expert a chunk@@ -505,8 +582,25 @@ struct Options {/// spec-1 drafts); 0 = plain decode. `spec_oracle` drafts from a token file (the expected continuation, for/// the exactness test); `spec_corrupt` N > 0 replaces every Nth draft with a wrong token.int spec = 0;+ /// --serve runs up to this many sequences at once, one token each per batch window (0 = off). A request+ /// sent as `BGEN <slot> <max_new> ...` reads its prompt and its first token through the usual path, then+ /// continues in slot <slot> of the batch windows (`BT <slot> <id>` lines, then `BDONE <slot> ...`).+ int batch = 0;+ /// With an explicit --layer-split, every GPU loads only its own layers' dense weights instead of the whole+ /// model's: the VRAM they took goes back to the expert cache (opt-in)+ bool trim_stage_weights = false;+ /// The --batch slots in this many groups pipelined through the stages of a layer split (stage k+ /// runs one group while stage k+1 runs another). 1 = every slot in one window, stage after stage.+ int batch_groups = 1;+ bool batch_mtp = false; ///< --batch-mtp / STRATA_BATCH_MTP=1 (opt-in): one MTP proposal per batch slotstd::string spec_oracle;int spec_corrupt = 0;+ /// Benchmarks and A/B checks (eddoursul's fork, F19): the run emits this continuation (token ids) instead of+ /// the window's argmax, and a draft is accepted when it matches it, so runs with different speculation+ /// settings process the same text.+ std::string spec_follow;+ /// Per verify window: a line with its size, a hash of its final residual rows and its argmaxes.+ std::string window_hashes;/// Plan v0.3 P6: the MTP draft layer's runtime directory (tools/mtp_rt.py); drafts come from it.std::string mtp;int64_t mtp_window = 32768; ///< the draft layer attends to the last N cells (0 = every cell)@@ -518,6 +612,10 @@ struct Options {/// the VRAM tier in place of the least-routed resident ones (decayed counts). 0 = static residency.int adapt_every = 4;float adapt_decay = 0.7f; ///< the usage counts are multiplied by this after each adaptation (--adapt-decay)+ /// --adapt-async 1 (--serve with the resident RAM mode; opt-in): the adaptive tier's rounds advance between verify+ /// windows on a helper thread instead of one window waiting for a whole round (see the tier in the --serve block).+ /// Not bit-exact run to run. 0 = the blocking tier.+ int adapt_async = 0;/// Plan v0.3 P6: a draft enters the verify window only while every draft before it (and itself) has at least/// this probability under the draft layer; 0 = always --spec-1 drafts.double spec_min_p = 0.0;@@ -547,8 +645,11 @@ struct Options {int64_t conversation_cache_mib = 0; // opt-in host RAM for independent conversationsint conversation_cache_slots = 4;int64_t conversation_cache_min_free_mib = 2560;+ /// --serve SAVE: disk space a session file must leave free where it is written (MiB; 0 = no check)+ int64_t session_min_free_mib = 4096;/// --serve: also keep a checkpoint every N freshly read prompt tokens (0 = only at the last turn boundary)int64_t prompt_cache_every = 16384;+ bool prompt_cache_tail = false; // optional extra checkpoint at an existing near-tail chunk boundary/// --serve: a prompt read from token 0 is also checkpointed at its first turn boundary - the end of the system/// prompt, which every chat of the same client shares - when that is at least N tokens (0 = never)int64_t prompt_cache_root = 2048;@@ -564,6 +665,11 @@ struct Options {/// result) goes through the verify windows, S tokens at a time, instead of the batched prompt path (0 = always/// the batched path)int64_t short_read = 64;+ /// --pipeline-windows N (--serve, a layer split on exactly two GPUs; opt-in): 1 = a prompt's short reads through+ /// the verify windows run with the stages overlapped (stage 0 reads window K+1 while stage 1 reads window K);+ /// 2 = the decode windows too: stage 0 runs window K+1 speculatively while stage 1 verifies window K (rolled back+ /// when K is not accepted as guessed). 0 = off (the stages take turns).+ int pipeline_windows = 0;/// The suffix drafter (prompt lookup): when the text being written repeats an earlier stretch of the context (code/// edits, quoted input, tool-call JSON) by at least this many tokens, the window may be filled with what followed/// it there instead of the MTP's drafts, where the MTP's own first guess agrees and the draft policy expects it to@@ -571,6 +677,18 @@ struct Options {int suffix_draft = 3;/// The MTP's own window cap (0 = --spec): with --spec 6 --mtp-max-t 4 the long windows come from suffix matches.int mtp_max_t = 0;+ /// --lookup-chain K (opt-in, 0 = off): prompt lookup CHAINED after the MTP's proposal. The suffix drafter matches+ /// the context followed by the MTP's drafts and appends up to K of the tokens that followed that match to the same+ /// verify window (the window grows to at most 8). Greedy verification keeps the output; its own counts are kept.+ int lookup_chain = 0;+ int lookup_chain_min = 3; ///< --lookup-chain-min M: the shortest match (in tokens, drafts included) it extends on+ /// --mtp-hnorm stream (opt-in): the draft layer's pre_fc_norm_hidden normalizes each hyper-connection stream on+ /// its own (llama.cpp's qwen4exp MTP graph) instead of one RMS over all four (the default, tools/mtp_probe.py).+ bool mtp_hnorm_stream = false;+ /// --mtp-q4 (opt-in): the draft layer's projections and draft head from 4-bit copies (fewer bytes per draft step)+ std::string mtp_q4; ///< "" (off), all, proj (the projections only) or head (the draft head only)+ /// --mtp-draft-vocab FILE (opt-in): the draft head's token subset from FILE instead of <mtp>/draft_vocab.bin+ std::string mtp_draft_vocab;/// A control vector on the residual stream (strata/kernels/cvec.hpp), with llama.cpp's flags: the/// `experimental-speed-projection` profile passes `--control-vector-scaled FILE:1.0 --control-vector-layer-range/// 4 44 --cvec-mode project --cvec-dir per-layer`. None by default; --serve switches a loaded one per request.@@ -602,10 +720,14 @@ void usage() {" --kv q4_0 4-bit K/V after a Hadamard rotation (PR #21): half of int8's memory,\n"" slightly lower precision (see bench/results/2026-09-27-kv-q4)\n"" --kv k8v4 hybrid: INT8 K (exact attention scores) + rotated Q4_0 V, 816 B/cell\n"- " (vs int8's 1,056); not with --kv-resident\n"+ " (vs int8's 1,056); streams with --kv-resident too\n"" --kv-resident N KV streaming: keep N cells of each QSA layer in VRAM (min 20480) and the\n"" whole K/V in pinned RAM; the freed VRAM goes to expert slots. 0 (default):\n"" all of it in VRAM. A context of N cells or fewer is not streamed\n"+ " --kv-grow the K/V takes VRAM only for the cells the requests reach and the expert\n"+ " cache holds the rest, giving slots back as the context grows (one GPU, with\n"+ " --expert-profile; STRATA_KV_GROW=1/0 also). Default: the whole --max-context\n"+ " allocated at start\n"" --stream-token enqueue token work on the session stream (experimental)\n"" --check-logits copy and check all logits in the stream-token path\n"" --gr-fp32-activations experimental CUDA-oracle GR activation precision\n"@@ -661,11 +783,25 @@ void usage() {" of RAM each; 0 = read every prompt from the start)\n"" --conversation-cache-mib N --serve: RAM budget for parked conversations (default 0 = off)\n"" --conversation-cache-slots N --serve: at most N parked conversations (default 4)\n"- " --conversation-cache-min-free-mib N --serve: physical RAM floor when parking (default 2560)\n"+ " --conversation-cache-min-free-mib N --serve: physical RAM floor when parking or restoring a\n"+ " session file (default 2560)\n"+ " --session-min-free-mib N --serve: disk space a SAVE must leave free (default 4096; 0 = no check)\n"" --vram-elastic --serve (#533, opt-in, NVIDIA): the expert cache in segments (--vram-segment-mib,\n"" default 512), so the command `VRAM <reserve_mib>` (the server's POST /v1/vram) can\n"" give VRAM back to other programs between requests and take it back later\n"+ " --batch N / --slots N --serve (opt-in): up to N requests decode together in batch slots (2..8\n"+ " normally; --batch-mtp waves more through eight-row windows),\n"+ " each slot with its own session (VRAM like the main one); docs/BATCHING.md\n"+ " --batch-mtp --batch (opt-in, one GPU, needs --mtp and --spec): each slot also verifies one MTP\n"+ " proposal per window (STRATA_BATCH_MTP=1 does the same); needs VRAM per slot\n"+ " --batch-groups G --batch with a layer split: the slots in G groups pipelined through the GPUs\n"+ " --pipeline-windows N --serve with a layer split on two GPUs (opt-in): one conversation's verify windows\n"+ " with the GPUs overlapped - 1 = the prompt's short reads, 2 = decode as well\n"+ " (stage 0 runs the next window while stage 1 verifies this one); docs/MULTI_GPU.md\n"+ " --trim-stage-weights an explicit --layer-split: each GPU loads only its own layers' dense weights\n"" --prompt-cache-every N --serve: also checkpoint every N fresh prompt tokens (default 16384, 0 = off)\n"+ " --prompt-cache-tail --serve, single GPU: one extra checkpoint near the prompt's end, at an existing\n"+ " chunk boundary (default off; requires --prompt-cache and --prompt-cache-every > 0)\n"" --turn-token ID --serve: the token that opens a chat turn (default 248045, <|im_start|>)\n"" --tail-role-token ID --serve: a turn of this role right before the last turn is left out of\n"" the conversation checkpoint (a trailing effort turn; default -1 = off)\n"@@ -674,6 +810,13 @@ void usage() {" --suffix-draft N prompt lookup: draft from an earlier repeat of the last N+ tokens of context\n"" when it pays (default 3; 0 = MTP only)\n"" --mtp-max-t M cap the MTP's windows at M tokens (0 = --spec; longer ones come from suffixes)\n"+ " --lookup-chain K opt-in: after the MTP's drafts, add up to K prompt-lookup drafts that continue\n"+ " them (the window grows to at most 8; default 0 = off)\n"+ " --lookup-chain-min M the shortest context match --lookup-chain extends on (default 3)\n"+ " --mtp-hnorm pooled|stream the draft layer's hidden-input norm: one RMS over all four streams\n"+ " (default) or one per stream (llama.cpp's MTP graph)\n"+ " --mtp-q4 all|proj|head opt-in: the draft layer's projections and/or draft head as 4-bit copies\n"+ " --mtp-draft-vocab FILE opt-in: the draft head's token subset (default <mtp>/draft_vocab.bin)\n"" --control-vector-scaled FILE:SCALE[,...] a control vector GGUF on the residual stream (llama.cpp's\n"" format; --control-vector FILE = scale 1). --serve: requests switch it (cvec=0|1)\n"" --control-vector-layer-range A B the layers it follows (inclusive; default 1 .. the last)\n"@@ -696,6 +839,12 @@ void usage() {" --gpu-only-full MEASURE: replay pre+post for all 48 layers plus the LM head, no pool.\n"" THE TRUE PER-TOKEN GPU FLOOR. Quote this one, not --graph-only.\n"" --stats print the per-stage breakdown\n"+ " --spec-follow PATH benchmarks: emit this continuation (token ids) instead of the argmax and\n"+ " accept the drafts that match it, so speculation settings compare on the\n"+ " same text (with --spec; not --serve)\n"+ " --window-hashes PATH per verify window, a line with its index, position, size, a 64-bit hash of\n"+ " its final residual rows and its argmaxes: two builds that do the same\n"+ " arithmetic write the same file (use with --spec-follow, --adapt-every 0)\n"" --gpu-stages R0.9: capture the layer as three graphs (mixer / ffn+router / post)\n"" and time them from OUTSIDE the capture. The per-stage table on the\n"" real graph that --stage-timing cannot give. Prints and exits.\n"@@ -714,9 +863,10 @@ void usage() {" GPU via `moe_hit_grouped_s2`. DEFAULT 0. Measured at 4096 slots\n"" with --expert-cache-per-layer: 54.4%% hits, CPU pool drain 19.1 -> 10.3\n"" ms/token, -2.7 ms/token end to end.\n"- " --expert-cache-device1 N pre-fill N experts on CUDA1 (experimental)\n"- " --expert-cache-device2 N pre-fill N more experts on CUDA2\n"- " --expert-cache-device3 N pre-fill N more experts on CUDA3\n"+ " --expert-cache-device1 N|auto fill CUDA1 with N experts or as many as fit\n"+ " --expert-cache-device2 N|auto fill CUDA2 with more experts\n"+ " --expert-cache-device3 N|auto fill CUDA3 with more experts\n"+ " --remote-expert-opt enable remote-expert decode optimizations (serve mode)\n"" --expert-cache-remote-placement stripe|layer distribute expert ranks or whole\n"" layers across CUDA1..3 (default: stripe)\n"" --peer-device N a second GPU as an adaptive expert-cache tier (rows over P2P; it also\n"@@ -739,6 +889,11 @@ void usage() {" except the one the host loop spins on (with --pool-affinity auto or\n"" p-cores on a hybrid CPU: P-cores minus 1). A sweep is how the pool's\n"" deviation from `cpu_s2` is attributed.\n"+ " --host-core WHERE The host thread's core: first (the default: the first physical core, as always) or\n"+ " last (the last physical core, the workers on the others). Windows sends a GPU's\n"+ " interrupts to one logical processor, usually the first, and every copy that lands\n"+ " raises one: a spinning host there waits for them. Moves threads only, never a\n"+ " result. Not on hybrid CPUs (STRATA_HOST_CORE sets it too).\n"" --pool-affinity MODE Worker CPU affinity: all (default: one worker per physical core, as\n"" always), auto (hybrid CPUs: P-cores first, then their SMT siblings,\n"" then E-cores) or p-cores (P-cores and their siblings only).\n"@@ -757,7 +912,27 @@ void usage() {" RAM allows); adaptive swaps exchange them, so none is read from the file again.\n"" --resident-experts the low-RAM PC's resident mode (setup): --mmap-experts --resident-cpu-experts\n"" with the copy page-locked when possible, 4 GiB headroom, plain mmap if it\n"- " does not fit. Same answers as --mmap-experts for the same placement.\n");+ " does not fit. Same answers as --mmap-experts for the same placement.\n"+ " --adapt-async 1 --serve with the resident RAM mode (opt-in): the adaptive tier's swaps\n"+ " advance between verify windows instead of a window waiting for a whole\n"+ " round. Not bit-exact run to run. 0 (default) = the blocking tier.\n");+}++// --lookup-chain: the context's last tokens for the draft sources (at most 64), the MTP's pending drafts last+int chain_tail(const strata::spec::SuffixDrafter& sfx, const int32_t* pending, int n_pending, std::vector<int32_t>& tail) {+ const std::vector<int32_t>& h = sfx.history();+ const int keep = std::max(0, std::min((int) h.size(), 64 - n_pending));+ tail.assign(h.end() - keep, h.end());+ tail.insert(tail.end(), pending, pending + n_pending);+ return (int) tail.size();+}++// --lookup-chain: the registered extra draft sources (strata/spec/draft_source.hpp) see the committed context too+void extra_sources_reset() {+ for (auto& src : strata::spec::extra_draft_sources()) src->reset();+}+void extra_sources_append(const int32_t* t, size_t n) {+ for (auto& src : strata::spec::extra_draft_sources()) src->append(t, n);}bool parse_i64_list(const char* s, std::vector<int64_t>& out, std::string& err) {@@ -886,6 +1061,7 @@ struct GpuStage {std::vector<std::pair<int32_t, int32_t>> profile; ///< its layers' share of the profile, hottest firstint32_t* d_res = nullptr; ///< the residency table on its devicestrata::core::Verifier ver;+ strata::core::Verifier ver_b; ///< --pipeline-windows: the odd windows' verifierstrata::prefill::Prefill sp;dpct::queue_ptr adapt_stream = &dpct::get_in_order_queue();dpct::event_ptr adapt_ev = nullptr;@@ -994,6 +1170,31 @@ void disk_wait_threads(std::FILE* f) {}#endif+// --pipeline-windows: what the watchdog prints about the pipelined decode loop (set while it runs)+struct PlDiag {+ strata::core::Verifier* v[2][2] = {};+ std::atomic<int> a_seq{0}, a_bits{0}, b_bits{0}, d_bits{0}, chain_kind{0}, doomed{0}, ending{0}, chain_live{0};+ std::atomic<long long> iters{0};+};+PlDiag g_pl_diag;+void pl_diag_print(std::FILE* f) {+ PlDiag& d = g_pl_diag;+ auto bits = [](int b, char* o) {+ std::snprintf(o, 16, "%c%c%c%c%c%c", b & 1 ? 'R' : '-', b & 2 ? 'L' : '-', b & 4 ? 'F' : '-', b & 8 ? 'C' : '-',+ b & 16 ? 'S' : '-', b & 32 ? 'V' : '-');+ return (const char*) o;+ };+ char ba[16], bb[16], bd[16];+ std::fprintf(f, " pipelined loop: %lld iterations; A seq %d [%s] B [%s] D [%s] (Ready Launched Finished Committed "+ "S1-launched S1-done); chain kind %d live %d; doomed %d ending %d\n", d.iters.load(), d.a_seq.load(),+ bits(d.a_bits.load(), ba), bits(d.b_bits.load(), bb), bits(d.d_bits.load(), bd), d.chain_kind.load(),+ d.chain_live.load(), d.doomed.load(), d.ending.load());+ const char* names[2][2] = {{"stage 0 even", "stage 0 odd"}, {"stage 1 even", "stage 1 odd"}};+ for (int st = 0; st < 2; ++st)+ for (int par = 0; par < 2; ++par)+ if (d.v[st][par] != nullptr) d.v[st][par]->diag_pipelined(f, names[st][par]);+}+void stall_report(std::FILE* f, uint64_t layers_during) {strata::core::Progress& p = strata::core::progress();std::fprintf(f, "strata serve: stall report (engine %s): stage \"%s\" for %lld s; %llu layers served since the "@@ -1007,6 +1208,7 @@ void stall_report(std::FILE* f, uint64_t layers_during) {}if (auto fn = strata::core::diag_pool_fn().load()) fn(f);if (auto fn = strata::core::diag_verify_fn().load()) fn(f);+ if (auto fn = strata::core::diag_pipeline_fn().load()) fn(f);#if !defined(_WIN32)disk_wait_threads(f);#endif@@ -1063,13 +1265,92 @@ bool adapt_nowait() {return v;}-int argmax(const std::vector<float>& v) {- int best = 0;- for (size_t i = 1; i < v.size(); ++i)- if (v[i] > v[best]) best = (int) i;- return best;+/// #463 without the stall: a verify window takes the adaptive tier's previous swaps only once they are this many windows+/// old, and then waits for their copies (which have landed by then). The window that first computes a swapped-in expert on+/// the GPU depends only on the window count, as with #463's wait, so the answers are as reproducible. Default 1 = #463 and+/// 0.1.39 (the very next window waits for the copies: ~4.6 ms per window on an RTX 2060 SUPER over PCIe 3.0 x8); lag 2 is+/// opt-in (STRATA_ADAPT_LAG=2). The batch paths, --pipeline-windows and the peer tier are not lagged. (#764)+int adapt_lag() {+ static const int v = [] { const char* e = std::getenv("STRATA_ADAPT_LAG"); return e ? std::max(1, std::atoi(e)) : 1; }();+ return v;}+/// --adapt-async: one background job at a time (the asynchronous adaptive tier's copies and memcpys). `post` hands+/// it over, `idle` says whether it has finished; the owner never posts while a job runs.+class JobThread {+public:+ JobThread() : th_([this] { loop(); }) {}+ ~JobThread() {+ { std::lock_guard<std::mutex> lk(mu_); quit_ = true; }+ cv_.notify_one();+ th_.join();+ }+ JobThread(const JobThread&) = delete;+ JobThread& operator=(const JobThread&) = delete;+ void post(std::function<void()> f) {+ {+ std::lock_guard<std::mutex> lk(mu_);+ job_ = std::move(f);+ has_ = true;+ done_.store(false, std::memory_order_release);+ }+ cv_.notify_one();+ }+ bool idle() const { return done_.load(std::memory_order_acquire); }+ void wait() const { while (!idle()) std::this_thread::yield(); }+private:+ // The second logical processor of the last physical core that has two: an SMT sibling no pool worker or host loop+ // is pinned to (the pool takes the first of every core but the first, the host the first core), or -1.+ static int smt_spare_cpu() {+#if defined(_WIN32)+ DWORD len = 0;+ GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &len);+ if (len == 0) return -1;+ std::vector<char> buf(len);+ if (!GetLogicalProcessorInformationEx(RelationProcessorCore, (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) buf.data(),+ &len))+ return -1;+ int best = -1, core = 0;+ for (const char* p = buf.data(); p < buf.data() + len;+ p += ((const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) p)->Size, ++core) {+ const auto* e = (const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) p;+ const GROUP_AFFINITY& ga = e->Processor.GroupMask[0];+ int seen = 0;+ for (int bit = 0; bit < 64; ++bit)+ if ((ga.Mask & (1ull << bit)) && ++seen == 2 && core > 0) best = ga.Group * 64 + bit;+ }+ return best;+#else+ return -1;+#endif+ }+ void loop() {+ // the job's memcpys stay off the host's core and the pool's: by default the spare SMT sibling of the last+ // two-thread core (Windows); STRATA_ADAPT_JOB_CPU=<logical cpu>, or -1 for no pinning+ const char* c = std::getenv("STRATA_ADAPT_JOB_CPU");+ const int cpu = c != nullptr ? std::atoi(c) : smt_spare_cpu();+ if (cpu >= 0) (void) strata::kernels::cpu::pin_current_thread(cpu);+ for (;;) {+ std::function<void()> f;+ {+ std::unique_lock<std::mutex> lk(mu_);+ cv_.wait(lk, [&] { return has_ || quit_; });+ if (!has_) return;+ f = std::move(job_);+ has_ = false;+ }+ f();+ done_.store(true, std::memory_order_release);+ }+ }+ std::mutex mu_;+ std::condition_variable cv_;+ std::function<void()> job_;+ bool has_ = false, quit_ = false;+ std::atomic<bool> done_{true};+ std::thread th_; // last: started once the members above exist+};+// ---- --serve's conversation cache. A chat or an agent sends the whole conversation again with every request, and// reading it again is what made a long session wait minutes for every turn. What a sequence leaves behind splits in// two, and only one half needs copying:@@ -1120,8 +1401,10 @@ bool checkpoint_restore(const ConvCheckpoint& c, strata::core::SessionState& ss,// --control-vector-scaled: llama.cpp's `common_control_vector_load` (every file's `direction.<l>` times its scale,// summed; layer 0 has none) and `llama_adapter_cvec::apply` with the projection-mode patch (project: the unit-// direction and its norm as the scale), into the tables `cvec_upload` takes. `summary` is what INFO reports.-bool load_control_vectors(const Options& o, const strata::core::ModelGeometry& g, std::string& summary, std::string& err) {+// direction and its norm as the scale), into the tables `cvec_upload` takes. `summary` is what INFO reports;+// `digest` identifies the uploaded tables, mode and range exactly (a session file is bound to it).+bool load_control_vectors(const Options& o, const strata::core::ModelGeometry& g, std::string& summary,+ uint64_t& digest, std::string& err) {const int64_t L = g.n_layers, N = g.n_embd;std::vector<float> data((size_t) (L * N), 0.0f);std::vector<bool> have((size_t) L, false);@@ -1184,6 +1467,17 @@ bool load_control_vectors(const Options& o, const strata::core::ModelGeometry& g}if (steered == 0) { err = "the control vector has no direction in layers " + std::to_string(first) + ".." + std::to_string(last); return false; }if (!strata::kernels::cvec_upload(dir, s, o.cvec_mode, first, last, N, g.hc, err)) return false;+ {+ strata::core::SessionIdentityBuilder b(0x43564543ull); // "CVEC"+ b.i64("mode", o.cvec_mode);+ b.i64("first", first);+ b.i64("last", last);+ b.i64("single", single);+ b.bytes("dir", dir.data(), dir.size() * sizeof(float));+ b.bytes("scale", s.data(), s.size() * sizeof(float));+ digest = b.digest();+ if (digest == 0) digest = 1; // 0 means "none loaded"+ }summary = std::string(o.cvec_mode == 0 ? "project" : "add") + ":" + std::to_string(first) + "-" + std::to_string(last) +(single >= 0 ? ":single" + std::to_string(single) : "");// the line llama.cpp's patched build prints, so a log shows the same thing@@ -1399,6 +1693,8 @@ int main(int argc, char **argv) try {else if (a == "--ple-sync-submit") o.ple_sync_submit = true;else if (a == "--kv") o.kv = next("--kv");else if (a == "--kv-resident") o.kv_resident = std::atoll(next("--kv-resident"));+ else if (a == "--kv-grow") o.kv_grow = true;+ else if (a == "--no-kv-grow") o.kv_grow = false;else if (a == "--stream-token") o.stream_token = true;else if (a == "--check-logits") o.check_logits = true;else if (a == "--gr-fp32-activations") o.gr_fp32_activations = true;@@ -1426,6 +1722,13 @@ int main(int argc, char **argv) try {else if (a == "--graph-only") o.graph_only = true;else if (a == "--gpu-only-full") o.gpu_only_full = true;else if (a == "--pool-workers") o.pool_workers = std::atoi(next("--pool-workers"));+ else if (a == "--host-core") {+ o.host_core = next("--host-core");+ if (o.host_core != "first" && o.host_core != "last") {+ std::fprintf(stderr, "strata generate: unknown --host-core value '%s' (expected first or last)\n", o.host_core.c_str());+ return 2;+ }+ }else if (a == "--pool-affinity") {const std::string v = next("--pool-affinity");if (v == "auto") o.pool_affinity = strata::kernels::cpu::PoolAffinity::Auto;@@ -1448,12 +1751,18 @@ int main(int argc, char **argv) try {const std::string v = next("--expert-cache");o.expert_cache = (v == "auto") ? -1 : std::atoi(v.c_str());}- else if (a == "--expert-cache-device1") o.expert_cache_remote[0] = std::atoi(next("--expert-cache-device1"));- else if (a == "--expert-cache-device2") o.expert_cache_remote[1] = std::atoi(next("--expert-cache-device2"));- else if (a == "--expert-cache-device3") o.expert_cache_remote[2] = std::atoi(next("--expert-cache-device3"));+ else if (a == "--expert-cache-device1" || a == "--expert-cache-device2" || a == "--expert-cache-device3") {+ const size_t r = (size_t) (a.back() - '1');+ const std::string v = next(a.c_str());+ o.expert_cache_remote_auto[r] = v == "auto";+ o.expert_cache_remote[r] = v == "auto" ? std::numeric_limits<int>::max() : std::atoi(v.c_str());+ }+ else if (a == "--remote-expert-opt") o.remote_expert_opt = true;else if (a == "--expert-cache-remote-placement")o.expert_cache_remote_placement = next("--expert-cache-remote-placement");else if (a == "--vram-reserve-mib") { o.vram_reserve_mib = std::atoi(next("--vram-reserve-mib")); o.vram_reserve_given = true; }+ else if (a == "--vram-reserve-later-mib")+ o.vram_reserve_later_mib = std::atoi(next("--vram-reserve-later-mib"));else if (a == "--prefill") {const std::string v = next("--prefill");o.prefill_auto = v == "auto" || v.rfind("auto:", 0) == 0;@@ -1472,13 +1781,21 @@ int main(int argc, char **argv) try {else if (a == "--prefill-until") o.prefill_until = std::atoll(next("--prefill-until"));else if (a == "--dump-final-r") o.dump_final_r = next("--dump-final-r");else if (a == "--spec") o.spec = std::atoi(next("--spec"));+ else if (a == "--batch") o.batch = std::atoi(next("--batch"));+ else if (a == "--slots") o.batch = std::atoi(next("--slots")); // the same as --batch+ else if (a == "--trim-stage-weights") o.trim_stage_weights = true;+ else if (a == "--batch-groups") o.batch_groups = std::atoi(next("--batch-groups"));+ else if (a == "--batch-mtp") o.batch_mtp = true;else if (a == "--spec-oracle") o.spec_oracle = next("--spec-oracle");else if (a == "--spec-corrupt") o.spec_corrupt = std::atoi(next("--spec-corrupt"));+ else if (a == "--spec-follow") o.spec_follow = next("--spec-follow");+ else if (a == "--window-hashes") o.window_hashes = next("--window-hashes");else if (a == "--mtp") o.mtp = next("--mtp");else if (a == "--mtp-window") o.mtp_window = std::atoll(next("--mtp-window"));else if (a == "--pcie-frac") o.pcie_frac = std::atof(next("--pcie-frac"));else if (a == "--adapt-every") o.adapt_every = std::atoi(next("--adapt-every"));else if (a == "--adapt-decay") o.adapt_decay = (float) std::atof(next("--adapt-decay"));+ else if (a == "--adapt-async") o.adapt_async = std::atoi(next("--adapt-async")) != 0 ? 1 : 0;else if (a == "--spec-min-p") o.spec_min_p = std::atof(next("--spec-min-p"));else if (a == "--stop-eos") o.stop_eos = true;else if (a == "--spec-split") o.spec_split = true;@@ -1490,7 +1807,7 @@ int main(int argc, char **argv) try {else if (a == "--vision") o.vision = true;else if (a == "--prompt-cache") o.prompt_cache = std::max(0, std::atoi(next("--prompt-cache")));else if (a == "--conversation-cache-mib" || a == "--conversation-cache-slots" ||- a == "--conversation-cache-min-free-mib") {+ a == "--conversation-cache-min-free-mib" || a == "--session-min-free-mib") {const std::string value = next(a.c_str());int64_t number = 0;const auto result = std::from_chars(value.data(), value.data() + value.size(), number);@@ -1501,15 +1818,36 @@ int main(int argc, char **argv) try {}if (a == "--conversation-cache-mib") o.conversation_cache_mib = number;else if (a == "--conversation-cache-min-free-mib") o.conversation_cache_min_free_mib = number;+ else if (a == "--session-min-free-mib") o.session_min_free_mib = number;else o.conversation_cache_slots = (int) number;}+ else if (a == "--prompt-cache-tail") o.prompt_cache_tail = true;else if (a == "--prompt-cache-every") o.prompt_cache_every = std::max(0LL, std::atoll(next("--prompt-cache-every")));else if (a == "--prompt-cache-root") o.prompt_cache_root = std::max(0LL, std::atoll(next("--prompt-cache-root")));else if (a == "--turn-token") o.turn_token = std::atoll(next("--turn-token"));else if (a == "--tail-role-token") o.tail_role_token = std::atoll(next("--tail-role-token"));else if (a == "--short-read") o.short_read = std::max(0LL, std::atoll(next("--short-read")));+ else if (a == "--pipeline-windows") o.pipeline_windows = std::max(0, std::min(2, std::atoi(next("--pipeline-windows"))));else if (a == "--suffix-draft") o.suffix_draft = std::max(0, std::atoi(next("--suffix-draft")));else if (a == "--mtp-max-t") o.mtp_max_t = std::max(0, std::atoi(next("--mtp-max-t")));+ else if (a == "--lookup-chain") o.lookup_chain = std::clamp(std::atoi(next("--lookup-chain")), 0, 7);+ else if (a == "--lookup-chain-min") o.lookup_chain_min = std::max(3, std::atoi(next("--lookup-chain-min")));+ else if (a == "--mtp-hnorm") {+ const std::string v = next("--mtp-hnorm");+ if (v != "pooled" && v != "stream") {+ std::fprintf(stderr, "strata generate: --mtp-hnorm takes pooled or stream\n");+ return 2;+ }+ o.mtp_hnorm_stream = v == "stream";+ }+ else if (a == "--mtp-q4") {+ o.mtp_q4 = next("--mtp-q4");+ if (o.mtp_q4 != "all" && o.mtp_q4 != "proj" && o.mtp_q4 != "head") {+ std::fprintf(stderr, "strata generate: --mtp-q4 takes all, proj or head\n");+ return 2;+ }+ }+ else if (a == "--mtp-draft-vocab") o.mtp_draft_vocab = next("--mtp-draft-vocab");else if (a == "--control-vector") o.cvec_files.push_back({next("--control-vector"), 1.0f});else if (a == "--control-vector-scaled") {// FILE:SCALE, comma-separated; the LAST colon splits, so a Windows path (C:\...) keeps its drive@@ -1605,19 +1943,31 @@ int main(int argc, char **argv) try {}}}+#if defined(STRATA_USE_HIP)+ { // gfx1151 (Strix Halo): the switches that are exact there are on by default (strata/core/arch_defaults.hpp); before+ // any engine code reads its switches (they are read at first use), and the user's own settings are kept+ cudaDeviceProp ad{};+ if (cudaGetDeviceProperties(&ad, 0) == cudaSuccess) strata::core::apply_arch_defaults(ad.gcnArchName);+ else (void) cudaGetLastError();+ }+#endifstrata::core::set_coupled_draft(o.coupled_draft);+ { // --host-core / STRATA_HOST_CORE, before the pool and the session pin any thread+ std::string hc = o.host_core;+ if (hc.empty())+ if (const char* e = std::getenv("STRATA_HOST_CORE")) hc = e;+ if (hc == "last") strata::kernels::cpu::set_host_core(strata::kernels::cpu::HostCore::Last);+ }strata::core::set_peer_portable(o.peer_device >= 1); // multi-GPU: the Portable flag on mapped host buffers only with a peer device (before any allocation)if (o.serve && o.conversation_cache_mib > 0 && (o.prompt_cache == 0 || o.conversation_cache_slots == 0))std::fprintf(stderr, "strata serve: warning: conversation caching is disabled by %s\n",o.prompt_cache == 0 ? "--prompt-cache 0" : "--conversation-cache-slots 0");- if (o.conversation_cache_mib > 0 && o.conversation_cache_slots > 0 && o.prompt_cache > 0 && !o.layer_split.empty()) {- std::fprintf(stderr, "strata serve: conversation parking does not yet support --layer-split; disable parking with --conversation-cache-mib 0\n");- return 2;- }+ // parking with --layer-split saves every stage (SavedConversation::stage_images)// Layer split (multi-GPU): the later stages run layers [K_i, K_i+1) on their own GPUs (--split-device, default- // the next visible ones); "auto" places the K from each GPU's free VRAM once the weights are in (below). Across- // GPUs, not yet: KV streaming, images, control vectors, the helper caches (--expert-cache-remote), and lending- // cache slots to the prompt path (each stage's prompt path has its own buffers).+ // the next visible ones); "auto" places the K from each GPU's free VRAM once the weights are in (below). KV+ // streaming and images (the server's GPU encoder) run across a split, also with parking and --batch. Across+ // GPUs, not yet: control vectors, the helper caches (--expert-cache-remote), and lending cache slots to the+ // prompt path (each stage's prompt path has its own buffers).// --pcie-frac given: that one share is every stage's (the stages' own link probes are skipped), so a split over// a fast and a slow link cannot set the two apart from the command line (#485)const bool pcie_given = o.pcie_frac >= 0.0;@@ -1652,6 +2002,11 @@ int main(int argc, char **argv) try {for (int d = 1; d < n_dev && (split_auto || split_devs.size() < split_at.size()); ++d) split_devs.push_back(d);if (ok && !split_auto && split_devs.empty() && split_at.size() == 1) split_devs.push_back(0); // one GPUsplit_same = ok && split_devs.size() == 1 && split_devs[0] == 0 && !split_auto;+ if (split_same && o.conversation_cache_mib > 0 && o.conversation_cache_slots > 0 && o.prompt_cache > 0) {+ std::fprintf(stderr, "strata serve: conversation parking does not support a layer split on one GPU "+ "(--split-device 0); disable parking with --conversation-cache-mib 0\n");+ return 2;+ }if (ok && split_auto && split_devs.empty()) {std::fprintf(stderr, "strata generate: --layer-split auto: one GPU visible, so no split\n");o.layer_split.clear();@@ -1684,19 +2039,10 @@ int main(int argc, char **argv) try {}const bool remote_caches = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 ||o.expert_cache_remote[2] > 0;- if (o.resident_cpu_experts && !o.layer_split.empty() && !remote_caches && o.resident_soft &&- !o.resident_cpu_explicit && o.resident_budget == 0) {- // #364 #384: setup's --resident-experts with a layer split (--gpus at start, or a config edited by hand) runs- // as the plain mmap mode - the placement those users measured 1.3-1.6x faster than one GPU - instead of- // refusing. Exactly --mmap-experts: nothing else reads these flags (the headroom only sizes the copy).- std::fprintf(stderr, "strata generate: WARNING: the resident RAM mode (--resident-experts) does not support a "- "layer split yet: the experts the GPUs do not hold are read through the OS file cache "- "(--mmap-experts), and RAM may fill up during long prompts\n");- o.resident_cpu_experts = o.resident_pin = o.resident_soft = false;- o.resident_headroom = 8ull << 30;- }- if (o.resident_cpu_experts && (!o.layer_split.empty() || remote_caches)) {- std::fprintf(stderr, "strata generate: --resident-cpu-experts does not support layer splits or remote expert caches\n");+ // A layer split keeps the resident RAM mode: every stage's GPU cache is left out of the RAM copy, and an adaptive+ // swap copies an evicted expert back from the card that owns its layer (resident_stage_swaps).+ if (o.resident_cpu_experts && remote_caches) {+ std::fprintf(stderr, "strata generate: --resident-cpu-experts does not support remote expert caches\n");return 2;}// the helper-GPU expert caches (--expert-cache-remote, docs/SECOND_GPU.md): CUDA1..3 on one GPU; with a layer@@ -1864,10 +2210,6 @@ int main(int argc, char **argv) try {std::fprintf(stderr, "strata generate: --kv-resident must be >= 0\n");return 2;}- if (o.kv == "k8v4" && o.kv_resident > 0) {- std::fprintf(stderr, "strata generate: --kv k8v4 does not support --kv-resident streaming (yet)\n");- return 2;- }strata::core::qsa_set_kv_resident(o.kv_resident);// Prompt lookup (the suffix drafter, on by default): the MTP keeps its --spec windows and a lookup window may be// up to 2 tokens longer; the draft policy (strata/spec/draft_policy.hpp) takes one only where it pays. Code@@ -1876,6 +2218,11 @@ int main(int argc, char **argv) try {o.mtp_max_t = o.spec;o.spec = std::min(o.spec + 2, 8); // kVerifyMaxT}+ // --lookup-chain (opt-in): the MTP keeps its windows; a lookup chained after its drafts may lengthen one by up to K+ if (o.lookup_chain > 0 && o.spec >= 2) {+ 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::core::layer_set_shared_early(!o.shared_late);if (!o.native_preset.empty()) {try {@@ -2000,6 +2347,10 @@ int main(int argc, char **argv) try {std::fprintf(stderr, "strata generate: --expert-cache-remote-placement must be stripe or layer\n");return 2;}+ if (o.remote_expert_opt && !o.serve) {+ std::fprintf(stderr, "strata generate: --remote-expert-opt requires --serve\n");+ return 2;+ }// the peer tier is the second card's only user: a layer split or a remote expert cache would put a second engine// part (and a second copy of the same experts) on itif (o.peer_device >= 1 && (!o.layer_split.empty() || o.expert_cache_remote[0] > 0)) {@@ -2050,12 +2401,33 @@ int main(int argc, char **argv) try {// ... and nothing runs on a CPU without AVX2: every CPU expert kernel is AVX2 at least (the AVX-512 ones are// chosen above it), and so is ggml-cpu in the release build, which the native pack's layout load initializes// next. Refused here, by name, rather than an illegal instruction in the first expert.- if (!strata::kernels::cpu::cpu_avx2_ok()) {- std::fprintf(stderr, "strata generate: this CPU (%s) does not support AVX2 with FMA and F16C, which every CPU "- "expert kernel needs; Strata runs on Intel Haswell (2013), AMD Zen (2017) or newer\n",+ // The experimental older-CPU build (STRATA_ISA_FLOOR=avx|none, compiled on that PC; #394 #595 #623) has ggml-cpu+ // for that floor, so a native pack's experts run there on ggml-cpu (every AVX2 kernel is behind cpu_avx2_ok).+ const char* isa_floor = strata::kernels::cpu::isa_floor_build();+ if (!strata::kernels::cpu::cpu_avx2_ok() && isa_floor[0] == '\0') {+ std::fprintf(stderr, "strata generate: this CPU (%s) does not support AVX2 with FMA and F16C, which this engine's "+ "CPU expert kernels need; Strata runs on Intel Haswell (2013), AMD Zen (2017) or newer. "+ "Older CPUs are EXPERIMENTAL and slow: setup compiles an engine for them on this PC "+ "(STRATA_ISA_FLOOR, see \"Older CPUs\" in docs/INSTALL.md)\n",strata::kernels::cpu::cpu_name().c_str());return 2;}+ if (isa_floor[0] != '\0') {+ const bool avx_floor = std::strcmp(isa_floor, "avx") == 0;+ if (avx_floor ? !strata::kernels::cpu::cpu_avx1_ok() : !strata::kernels::cpu::cpu_sse42_ok()) {+ std::fprintf(stderr, "strata generate: this engine is the older-CPU build for %s, which this CPU (%s) does "+ "not have%s\n", avx_floor ? "AVX" : "SSE4.2 with POPCNT",+ strata::kernels::cpu::cpu_name().c_str(),+ avx_floor ? "; compile it with STRATA_ISA_FLOOR=none" : "");+ return 2;+ }+ if (!strata::kernels::cpu::cpu_avx2_ok())+ std::fprintf(stderr, "strata generate: EXPERIMENTAL older-CPU build (ggml-cpu for %s): this CPU has no AVX2, "+ "so the CPU's experts run on ggml-cpu's kernels - expect it to be slow\n", isa_floor);+ else+ std::fprintf(stderr, "strata generate: this is the older-CPU build (ggml-cpu for %s); this CPU has AVX2, "+ "and the normal build is faster on it\n", isa_floor);+ }std::string err;if (!o.native_head_gguf.empty() && !o.stream_token) {@@ -2128,7 +2500,8 @@ int main(int argc, char **argv) try {else if (!strata::kernels::cpu::cpu_avx512_ok())std::fprintf(stderr, "strata generate: this CPU has no AVX-512: the expert kernels run on %s ""(multi-token for the i-quant gate/up rows)\n",- std::getenv("STRATA_NO_IQ256") == nullptr ? "AVX-2" : "ggml-cpu vec_dot (STRATA_NO_IQ256 set)");+ !strata::kernels::cpu::cpu_avx2_ok() ? "ggml-cpu vec_dot (no AVX2: the older-CPU build)"+ : std::getenv("STRATA_NO_IQ256") == nullptr ? "AVX-2" : "ggml-cpu vec_dot (STRATA_NO_IQ256 set)");strata::core::ModelGeometry g; // canonical defaults; the model file overrides the MoE shape belowint64_t K = 10;// THE ROPE CONFIG RESOLVES HERE, BEFORE ANY WEIGHT MOVES - the CLI and the model file have both spoken,@@ -2241,6 +2614,7 @@ int main(int argc, char **argv) try {return 2;}const strata::core::ModelGeometry g0;+ const auto embed_t0 = std::chrono::steady_clock::now();if (!native_embed.load(o.embd_gguf.empty() ? o.native_shards : std::vector<std::string>{o.embd_gguf}, g0.n_embd,248320, err)) {std::fprintf(stderr, "strata generate: %s\n", err.c_str());@@ -2248,9 +2622,10 @@ int main(int argc, char **argv) try {}strata::core::set_native_embed(&native_embed);std::fprintf(stderr, "strata generate: native pack: %s experts (largest blob %.2f MB), token embedding "- "%s in mapped host memory (%.0f MiB)\n",+ "%s in mapped host memory (%.0f MiB, %.1f s)\n",o.pack.c_str(), (double) strata::kernels::cpu::expert_layout().max_blob / 1e6,- strata::ggml_type_name((uint32_t) native_embed.type()), (double) native_embed.bytes() / 1048576.0);+ strata::ggml_type_name((uint32_t) native_embed.type()), (double) native_embed.bytes() / 1048576.0,+ std::chrono::duration<double>(std::chrono::steady_clock::now() - embed_t0).count());}// Plan v0.3 P1: tensors served in native form are not also loaded in canonical form (~2.7 GB of VRAM back// to the expert cache with --native). `--keep-canonical` loads both, as before.@@ -2271,15 +2646,29 @@ int main(int argc, char **argv) try {}if (native_pack) skip.insert("token_embd.weight");}- // Layer split with explicit split points: every GPU holds only the dense weights of ITS layers (the PLE tensors- // stay everywhere). Without this each card keeps a full copy (~3.4 GB for the Coder) that its stage never- // reads - VRAM the expert cache wants. Opt-in, STRATA_STAGE_TRIM=1, on HIP and CUDA alike: measured on 2x MI50- // (PR #639), and the default waits for its author's re-run of the release branch on his cards.+ // Layer split: every GPU holds only the dense weights of ITS layers (the PLE tensors stay everywhere).+ // Without this each card keeps a full copy (~3.4 GB for the Coder) that its stage never reads - VRAM the+ // expert cache wants. Opt-in, STRATA_STAGE_TRIM=1, on HIP and CUDA alike: measured on 2x MI50 (PR #639),+ // and the default waits for its author's re-run of the release branch on his cards.const std::set<std::string> skip_base = skip;- const bool stage_trim = multi_gpu && !split_auto && !split_at.empty() && [] {+ // --trim-stage-weights (PR #559) is the same switch as STRATA_STAGE_TRIM=1 (PR #639)+ const bool trim_asked = o.trim_stage_weights || [] {const char* v = std::getenv("STRATA_STAGE_TRIM");return v != nullptr && v[0] != 0 && std::string(v) != "0";}();+ // CUDA0'S ARENA IS BUILT BEFORE THE SPLIT IS KNOWN. The prompt path's PLE tables are read out of it, here,+ // and `auto` does not choose its split points until 590 lines below - so CUDA0 can still only trim an+ // explicit --layer-split. It is also the cheapest card to leave alone: it runs layers 0..split_at[0] on+ // the device with the most room, and on the 4-way IQ3_S rig the trim buys it 4598 -> 4608 slots. The VRAM+ // is on the later cards (CUDA2 1241 -> 2485, CUDA3 533 -> 1772), and THEIR weights load after the search,+ // so they trim under `auto` too - see the block past it.+ const bool stage_trim = trim_asked && multi_gpu && !split_auto && !split_at.empty();+ if (o.trim_stage_weights && !multi_gpu)+ std::fprintf(stderr, "strata generate: --trim-stage-weights needs a layer split across GPUs (ignored)\n");+ // Only `--layer-split auto` WITH the trim asked loads the later stages' weights after the split search (they can+ // only be trimmed once the split is known). Every other run keeps the 0.1.39 order: weights first, then the+ // search - so without the trim nothing about a split moves.+ const bool late_weights = trim_asked && multi_gpu && split_auto;// keep_routers: CUDA0 with --mmap-experts keeps every layer's router (ffn_gate_inp, ~2.5 MiB a layer) - the file// tier's routing-aware prefetch (RouterLookahead, below) copies all of them from CUDA0's arena, and would// otherwise turn itself off@@ -2352,14 +2741,21 @@ int main(int argc, char **argv) try {(unsigned long long)(total_b >> 20));return 1;}+ auto load_t0 = std::chrono::steady_clock::now();+ auto load_s = [&] {+ const auto t = std::chrono::steady_clock::now();+ const double s = std::chrono::duration<double>(t - load_t0).count();+ load_t0 = t;+ return s;+ };strata::core::WeightTable wt;if (!wt.load(o.pack, arena, pool_bytes, err, skip.empty() ? nullptr : &skip)) {std::fprintf(stderr, "strata generate: %s\n", err.c_str());return 1;}- std::fprintf(stderr, "strata generate: %llu MiB of weights loaded from %s (%zu canonical tensors skipped: "- "served natively)\n",- (unsigned long long) (pool_bytes >> 20), o.pack.c_str(), skip.size());+ std::fprintf(stderr, "strata generate: %llu MiB of weights loaded from %s in %.1f s (%zu canonical tensors "+ "skipped: served natively)\n",+ (unsigned long long) (pool_bytes >> 20), o.pack.c_str(), load_s(), skip.size());strata::core::NativeDense native_dense;if (!o.native_dense_gguf.empty()) {@@ -2367,8 +2763,8 @@ int main(int argc, char **argv) try {std::fprintf(stderr, "strata generate: native dense projections: %s\n", err.c_str());return 1;}- std::fprintf(stderr, "strata generate: %zu native projection matrices, %.2f MiB of weights\n",- native_dense.tensor_count(), (double) native_dense.weight_bytes() / (1024.0 * 1024.0));+ std::fprintf(stderr, "strata generate: %zu native projection matrices, %.2f MiB of weights, in %.1f s\n",+ native_dense.tensor_count(), (double) native_dense.weight_bytes() / (1024.0 * 1024.0), load_s());}strata::kernels::gr_set_fp32_activations(o.gr_fp32_activations);@@ -2420,9 +2816,10 @@ int main(int argc, char **argv) try {strata::kernels::ple_set_native_postops(o.native_ple_postops);// before session_init: every graph captured from here on has the vector's kernels where it appliesstd::string cvec_summary = "0";+ uint64_t cvec_digest = 0; // a session file is bound to the loaded vector (0: none)if (!o.cvec_files.empty()) {std::string ce;- if (!load_control_vectors(o, g, cvec_summary, ce)) {+ if (!load_control_vectors(o, g, cvec_summary, cvec_digest, ce)) {std::fprintf(stderr, "strata generate: control vector: %s\n", ce.c_str());return 2;}@@ -2472,8 +2869,8 @@ int main(int argc, char **argv) try {}const size_t n = (size_t) g.n_layers * (size_t) half_stride;/*- DPCT1048: The original value cudaHostAllocDefault is not meaningful in- the migrated code and was removed or replaced with 0. You may need to+ DPCT1048: The original value cudaHostAllocDefault is not meaningful+ in the migrated code and was removed or replaced with 0. You may need tocheck the migrated code.*/if (DPCT_CHECK_ERROR(half_stage = sycl::malloc_host<float>(@@ -2696,28 +3093,40 @@ int main(int argc, char **argv) try {}}strata::core::Verifier::set_commit_async(!multi_gpu); // see Verifier::set_commit_async+ // --pipeline-windows (opt-in): one conversation's windows with the two stages of a layer split overlapped. Decided+ // here, before any stage sizes its expert cache (the second verifier per stage and the snapshots are allocated+ // after the caches, so their room is kept out of them). What it does not support turns it off, said once.+ if (o.pipeline_windows > 0) {+ const bool helpers = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0;+ const char* off = !o.serve ? "it needs --serve"+ : split_same ? "it needs each stage of the layer split on its own GPU"+ : !multi_gpu ? "it needs a layer split on two GPUs"+ : split_devs.size() != 1 ? "it needs a layer split into exactly two stages"+ : o.mtp.empty() || o.spec < 2 ? "it needs the MTP drafter (--mtp, --spec)"+ : o.batch != 0 ? "not with --batch slots"+ : o.peer_device >= 1 ? "not with --peer-device"+ : helpers ? "not with the helper caches (--expert-cache-device1..3, --remote-expert-opt)"+ : nullptr;+ if (off != nullptr) {+ std::fprintf(stderr, "strata generate: --pipeline-windows %d is off: %s\n", o.pipeline_windows, off);+ o.pipeline_windows = 0;+ }+ }// ---- layer split across GPUs: each later stage's own copy of the dense weights, its session and (the last) the// head, made on its device before the host arena is mapped (as the drafter below, for the same WDDM reason)std::vector<std::unique_ptr<GpuStage>> stages;- for (size_t i = 0; multi_gpu && i < split_devs.size(); ++i) {- stages.push_back(std::make_unique<GpuStage>());- GpuStage& st = *stages.back();- st.dev = split_devs[i];- double free_gib = 0;- if (!strata::core::RemoteExperts::preflight(st.dev, free_gib, err)) {- std::fprintf(stderr, "strata generate: %s\n", err.c_str());- return 1;- }- const strata::core::OnDevice on(st.dev);- std::set<std::string> skip_s = skip_base;+ // One stage's dense weights on its device (the caller has made it current): `trim` = only layers [lb, le).+ auto load_stage_weights = [&](GpuStage &st, int64_t lb, int64_t le,+ bool trim) -> bool {+ try {+ std::set<std::string> skip_s = skip_base;uint64_t pool_s = pool_bytes;- if (stage_trim) {- const int64_t lb = split_at[i], le = i + 1 < split_at.size() ? split_at[i + 1] : g.n_layers;+ if (trim) {add_foreign(lb, le, skip_s, false);strata::core::NativeDense::set_layer_range((int) lb, (int) le);if (!strata::core::WeightTable::pool_bytes(o.pack, pool_s, err, &skip_s)) {std::fprintf(stderr, "strata generate: %s\n", err.c_str());- return 1;+ return false;}std::fprintf(stderr, "strata generate: layer split: CUDA%d loads the dense weights of layers %lld-%lld only\n",st.dev, (long long) lb, (long long) le - 1);@@ -2745,13 +3154,38 @@ int main(int argc, char **argv) try {err.empty() ? "the weight arena does not fit" : err.c_str(),(unsigned long long) (pool_s >> 20), (unsigned long long) (free_b >> 20),(unsigned long long) (total_b >> 20));- return 1;+ return false;}if (!o.native_dense_gguf.empty() && !st.dense.load(o.native_dense_gguf, st.wt, err, o.native_ple_key)) {std::fprintf(stderr, "strata generate: layer split, CUDA%d native dense projections: %s\n", st.dev,err.c_str());+ return false;+ }+ return true;+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ for (size_t i = 0; multi_gpu && i < split_devs.size(); ++i) {+ stages.push_back(std::make_unique<GpuStage>());+ GpuStage& st = *stages.back();+ st.dev = split_devs[i];+ double free_gib = 0;+ if (!strata::core::RemoteExperts::preflight(st.dev, free_gib, err)) {+ std::fprintf(stderr, "strata generate: %s\n", err.c_str());return 1;}+ const strata::core::OnDevice on(st.dev);+ // Later stages' weights load here (0.1.39), except `--layer-split auto` with the trim asked: those load after+ // the split search (see late_weights), so `auto` can trim them too.+ if (!late_weights) {+ const int64_t lb = stage_trim ? split_at[i] : 0;+ const int64_t le = stage_trim ? (i + 1 < split_at.size() ? split_at[i + 1] : g.n_layers) : 0;+ if (!load_stage_weights(st, lb, le, stage_trim)) return 1;+ }// THE SESSION AND THE HEAD WAIT FOR THE SPLIT SEARCH. `session_bytes` prices a stage's session by its// LAYER RANGE (the carve - every stage used to hold all 48 layers' state whatever it ran), so the// sessions are allocated after the search below has set `st.lb`/`st.le`; the last stage's head follows.@@ -2808,15 +3242,17 @@ int main(int argc, char **argv) try {std::fprintf(stderr, "strata generate: layer split: CUDA%d PCIe probe %.1f GB/s (best of %s) -> pcie_frac ""%.2f\n", st.dev, bw, bursts.c_str(), st.pcie_frac);}- size_t fb = 0, tb = 0;- /*- DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions- for device information which may not be supported by all compilers or- runtimes. You may need to adjust the code.- */- dpct::get_current_device().get_memory_info(fb, tb);- std::fprintf(stderr, "strata generate: layer split: CUDA%d holds its weights; %.2f GiB free (its session "- "follows the split search)\n", st.dev, (double) fb / 1073741824.0);+ if (!late_weights) {+ size_t fb = 0, tb = 0;+ /*+ DPCT1106: 'cudaMemGetInfo' was migrated with the Intel+ extensions for device information which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ dpct::get_current_device().get_memory_info(fb, tb);+ std::fprintf(stderr, "strata generate: layer split: CUDA%d holds its weights; %.2f GiB free (its session "+ "follows the split search)\n", st.dev, (double) fb / 1073741824.0);+ }}GpuStage* const last_st = stages.empty() ? nullptr : stages.back().get();@@ -2877,9 +3313,11 @@ int main(int argc, char **argv) try {// for the ~0.1% of the mass it pushes out of its cache);// - which experts a cache holds: its layers' profiled pairs, hottest first, until its free VRAM (less the// reserve, the prompt path's buffers and, on a later GPU, 1 GiB for its windows and the drafter) is used;- // the routed mass of rank r is taken as (r+1)^-1.2 (fits the sweep's hit rates: K=24/26/28 predicted- // 99.53/99.34/99.15%, measured 99.5/99.4/99.0%).- // Up to 3 GPUs every placement is tried; beyond, the layers are shared in proportion to speed.+ // the routed mass a cache holds follows the COVERAGE CURVE below, not the (r+1)^-1.2 this used to use.+ // Up to 4 GPUs every placement is tried; beyond, the layers are shared in proportion to speed.+ // A FOUR-WAY PLACEMENT USED TO BE THE PROPORTIONAL GUESS AND NOTHING ELSE. That formula reads only+ // `layer_ms`, so on four GPUs the free VRAM a placement leaves for expert caches - the whole point of+ // the search - never entered it. It does now; see the ns == 4 branch below.// STRATA_SPLIT_MISS_MS tunes the miss cost (a slower CPU: higher).// THE PROMPT PATH'S BUFFERS ARE BORROWED FROM THE CACHE, NOT WITHHELD BESIDE IT. With borrowing the cache// is sized first and at full size, and the prompt path is laid out in the tail of it (`Prefill::relayout`),@@ -2907,11 +3345,28 @@ int main(int argc, char **argv) try {// the windows and - only on the stage that carries them - the drafter and the head.const int64_t kWindowMib = 96; // the verify windows; 75 MiB measured, rounded upconst int64_t kDrafterMib = 1000; // the MTP drafter (839 MiB) + the head, on the last stage only+ // --pipeline-windows: a second verifier on every stage (its arena alone is 70-75 MiB and its graphs come on top:+ // 64 MiB left two RTX 5070 Ti under Linux short of it) and, with the decode pipelined, two copies of the first+ // stage's GDN state (sized from its session where the first card's cache is sized; this is the split search's+ // estimate). Allocated after the caches, so kept out of them.+ const int64_t kPipeWindowMib = o.pipeline_windows > 0 ? 160 : 0;+ const int64_t kPipeSnapMib = o.pipeline_windows >= 2 ? 96 : 0; // ~3 MiB per GDN layer, twice, ~15 layers+ auto gdn_snapshot_bytes = [&](const strata::core::SessionState& s0) -> size_t {+ return (size_t) s0.gdn_alloc * ((size_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size ++ (size_t) g.ssm_conv_channels * (g.ssm_d_conv - 1)) * sizeof(float);+ };// #340: with the own prompt buffers chosen by the split's rule (not asked for with --no-prefill-borrow) the// boundary is searched as the borrowing configuration would (no reserve): the reserve then only makes the caches// smaller, which measured cost no decode (K=28 on 9070 XT + R9700: 58.4 tok/s own vs 58.5 borrowing), while a// search with the reserve moved the boundary to K=32 and decode to 54.8. STRATA_SPLIT_OWN_PLACE=reserve: the// search sees the reserve.+ // ---- `--layer-split auto` with the trim asked: a later stage's weights load after this search, so its arena is+ // not in `cudaMemGetInfo` yet. Price it from the pack index as the full (untrimmed) copy the search has always+ // seen on the card (`pool_bytes` reads the index and allocates nothing), so the split it picks is the split it+ // has always picked: this buys cache, not a different placement. Every other run has its weights loaded: 0.+ std::vector<uint64_t> stage_pool(stages.size() + 1, 0);+ if (late_weights)+ for (size_t i = 1; i < stage_pool.size(); ++i) stage_pool[i] = pool_bytes;static const bool place_with_reserve = [] {const char* v = std::getenv("STRATA_SPLIT_OWN_PLACE");return v != nullptr && std::string(v) == "reserve";@@ -2929,8 +3384,10 @@ int main(int argc, char **argv) try {*/const int64_t pf = search && split_own_auto && !place_with_reserve ? 0 : split_pf_mib;- const int64_t reserve = ((int64_t) o.vram_reserve_mib + pf + (later ? kWindowMib : 0) +- (drafter ? kDrafterMib : 0)) << 20;+ const int64_t base_reserve =+ later && o.vram_reserve_later_mib >= 0 ? o.vram_reserve_later_mib : o.vram_reserve_mib;+ const int64_t reserve = (base_reserve + pf + (later ? kWindowMib : kPipeSnapMib) ++ kPipeWindowMib + (drafter ? kDrafterMib : 0)) << 20;return std::max<int64_t>((int64_t) fb - reserve, 0);}catch (sycl::exception const &exc) {@@ -2947,6 +3404,7 @@ int main(int argc, char **argv) try {for (int i = 0; i < ns; ++i) {const int dev = i == 0 ? 0 : stages[(size_t) i - 1]->dev;cap[(size_t) i] = stage_room(i == 0 ? -1 : dev, i > 0, i + 1 == ns, true);+ if (late_weights) cap[(size_t) i] = std::max<int64_t>(cap[(size_t) i] - (int64_t) stage_pool[(size_t) i], 0);int sms = 0, khz = 0;sms = dpct::get_device(dev).get_max_compute_units();if (DPCT_CHECK_ERROR(@@ -2965,9 +3423,47 @@ int main(int argc, char **argv) try {(double) cap[(size_t) i] / 1073741824.0);}const double miss_ms = std::getenv("STRATA_SPLIT_MISS_MS") ? std::atof(std::getenv("STRATA_SPLIT_MISS_MS")) : 190.0;- std::vector<double> mass(profile.size());+ // ---- THE COVERAGE CURVE: HOW MUCH ROUTED MASS A CACHE HOLDS, AND WHY IT IS NO LONGER A POWER LAW.+ //+ // `mass[r]` used to be (r+1)^-1.2, fitted to the 5080+3090 sweep. That fit is still right ON THE RIG IT+ // WAS FITTED TO - at 20,000 pairs held it predicts 99.35% of the routed mass and that rig measured 99.4%.+ // It is wrong on the IQ3_S 4-way rig, badly: it claims the top 5,805 pairs hold 94.9% of the mass, and+ // that rig measures 69.2% (four boots, 14.9M decode lookups). No exponent reconciles them, because the+ // curve is a property of the MODEL'S ROUTING, not a universal constant - and the profile file carries+ // only a RANKING, with no counts, so it cannot be read off the data either. (tools/make_profile.py has+ // the frequencies, and drops them; see the note there.)+ //+ // What the two rigs do agree on is that the hit rate follows the HELD COUNT and almost nothing else: two+ // different splits held 14,541 and 14,384 pairs and measured 92.2% and 89.8% of the routed mass. So the+ // curve is taken over the held FRACTION f, as H(f) = 1 - (1 - f)^b, and each rank's mass is that curve's+ // increment, which makes any prefix of N pairs sum to exactly H(N/total) while a cache holding+ // colder-than-prefix pairs still scores below it.+ //+ // b = 3 IS CHOSEN TO LEAVE THE PREVIOUSLY VALIDATED REGIME WHERE IT WAS. At 20,000 held (f = 0.8138) it+ // gives 99.35%, against the old fit's 99.35% and that rig's measured 99.4% - the 2-GPU placement is+ // untouched. At f = 0.59 it gives 93.2% against 92.2% measured. Below f ~ 0.5 the two curves diverge,+ // and that is the whole point: it is exactly the regime where the old one was wrong, and where it told+ // the search that stranding a card's VRAM costs almost nothing.+ //+ // THE CURVE IS A FIT TO ONE MODEL'S TRAFFIC. STRATA_SPLIT_COVER_B overrides b for a model whose routing+ // is sharper or flatter, and STRATA_SPLIT_MISS_MS still scales the miss cost it feeds.+ const size_t n_ranked = profile.size();+ const double cover_b = std::getenv("STRATA_SPLIT_COVER_B") ? std::atof(std::getenv("STRATA_SPLIT_COVER_B")) : 3.0;+ std::vector<double> mass(n_ranked);double total_mass = 0;- for (size_t r = 0; r < profile.size(); ++r) total_mass += (mass[r] = std::pow((double) r + 1.0, -1.2));+ // Up to 3 GPUs the 0.1.39 curve (r+1)^-1.2 is kept, so 2- and 3-GPU placements do not move (the new curve is a+ // fit to a 4-way rig and was not measured on them); STRATA_SPLIT_COVER_B asks for the coverage curve at any+ // GPU count.+ const bool coverage_curve = ns >= 4 || std::getenv("STRATA_SPLIT_COVER_B") != nullptr;+ for (size_t r = 0; r < n_ranked; ++r) {+ if (!coverage_curve) {+ total_mass += (mass[r] = std::pow((double) r + 1.0, -1.2));+ continue;+ }+ const double hi = std::pow(1.0 - (double) r / (double) n_ranked, cover_b);+ const double lo = std::pow(1.0 - (double) (r + 1) / (double) n_ranked, cover_b);+ total_mass += (mass[r] = hi - lo);+ }auto cost = [&](int64_t l) -> int64_t {return native_pack ? ((int64_t) lay.blob_bytes(l) + 255) / 256 * 256 : (int64_t) lay.max_blob;};@@ -3006,36 +3502,109 @@ int main(int argc, char **argv) try {};std::vector<int64_t> best, at((size_t) ns - 1);double best_ms = 1e30, best_mass = 0;- int64_t best_held = 0;+ int64_t best_held = 0, tried = 0;auto consider = [&]() {double hm = 0;int64_t held = 0;const double ms = predict(at, hm, held);+ ++tried;if (ms < best_ms) { best = at; best_ms = ms; best_mass = hm; best_held = held; }};const int64_t L = g.n_layers;- if (ns == 2) {- for (int64_t k = 2; k < L; ++k) { at[0] = k; consider(); }- } else if (ns == 3) {- for (int64_t k1 = 2; k1 + 1 < L; ++k1)- for (int64_t k2 = k1 + 1; k2 < L; ++k2) { at[0] = k1; at[1] = k2; consider(); }- } else {+ // share the layers in proportion to speed: the fallback beyond four GPUs, and the only placement a+ // model too small to hold four stages has (see the ns == 4 branch).+ auto proportional = [&]() {double total = 0;for (const double c : layer_ms) total += 1.0 / c;double acc = 0;for (int i = 0; i + 1 < ns; ++i) {acc += 1.0 / layer_ms[(size_t) i];at[(size_t) i] = std::clamp<int64_t>((int64_t) std::llround(acc / total * (double) L),- i == 0 ? 2 : at[(size_t) i - 1] + 1, L - (ns - 1 - i));+ i == 0 ? 2 : at[(size_t) i - 1] + 1, L - (ns - 1 - i));}consider();+ };+ if (ns == 2) {+ for (int64_t k = 2; k < L; ++k) { at[0] = k; consider(); }+ } else if (ns == 3) {+ for (int64_t k1 = 2; k1 + 1 < L; ++k1)+ for (int64_t k2 = k1 + 1; k2 < L; ++k2) { at[0] = k1; at[1] = k2; consider(); }+ } else if (ns == 4) {+ // ---- EVERY FOUR-WAY PLACEMENT IS TRIED. This branch used to share the layers in proportion to+ // speed and score that ONE candidate, and that formula reads only `layer_ms` - never the free VRAM.+ // So on a four-GPU rig cache capacity did not influence the placement AT ALL, and the card with+ // the most room left could be handed the fewest layers: on the 3060/3060/5060/5060 box CUDA1 ended+ // up with 1,841 MiB no cache could use while CUDA2 ran 15 layers it could only hold a third of.+ // All C(L-3,3) placements - 15,180 at 48 layers - are now scored.+ //+ // A STAGE'S FILL DEPENDS ONLY ON ITS OWN RANGE AND ITS OWN FREE VRAM. `predict` hands each ranked+ // pair to the one stage that owns its layer and each stage stops at its first pair that does not+ // fit, so the four fills are independent and a placement's held mass is a SUM over its four+ // ranges. That is what makes this affordable: each distinct range is walked once and memoised,+ // 1,121 walks instead of 15,180 - measured at 14 ms against 740 ms, for the same answer.+ // `le` runs to L inclusive, so a row is L+1 wide - keying on a stride of L would put the last+ // stage's [lb, L) one past the end of the vector.+ //+ // NOTE: on v0.1.39 the search only runs under `--layer-split auto`, where every card still holds+ // the whole model's dense weights, so `cap[i]` is already net of them and the stage's room is what+ // `predict` subtracts - the session. (On the branch this came from the carve reached `auto` too,+ // and each stage's own weight bytes were taken off here as well.)+ const size_t stride = (size_t) L + 1;+ std::vector<double> held_mass_at((size_t) ns * (size_t) L * stride, -1.0);+ std::vector<int64_t> held_at(held_mass_at.size(), 0);+ auto range_hold = [&](int i, int64_t lb, int64_t le) -> size_t {+ const size_t key = ((size_t) i * (size_t) L + (size_t) lb) * stride + (size_t) le;+ if (held_mass_at[key] < 0.0) {+ // one stage's own carve, exactly as `predict` prices it+ const int64_t room = cap[(size_t) i] -+ (int64_t) strata::core::session_bytes(g, o.max_context, K, lb, le);+ double hm = 0;+ int64_t used = 0, cnt = 0;+ for (size_t r = 0; r < profile.size(); ++r) {+ const int64_t l = profile[r].first;+ if (l < lb || l >= le) continue;+ if (used + cost(l) > room) break; // the fill stops exactly where predict's does+ used += cost(l);+ hm += mass[r];+ ++cnt;+ }+ held_mass_at[key] = hm;+ held_at[key] = cnt;+ }+ return key;+ };+ const double denom = std::max(total_mass, 1e-9);+ for (int64_t k1 = 2; k1 + 2 < L; ++k1)+ for (int64_t k2 = k1 + 1; k2 + 1 < L; ++k2)+ for (int64_t k3 = k2 + 1; k3 < L; ++k3) {+ const size_t a = range_hold(0, 0, k1), b = range_hold(1, k1, k2);+ const size_t c = range_hold(2, k2, k3), d = range_hold(3, k3, L);+ const double hm = held_mass_at[a] + held_mass_at[b] + held_mass_at[c] + held_mass_at[d];+ const double ms = miss_ms * (1.0 - hm / denom) ++ (double) k1 * layer_ms[0] + (double) (k2 - k1) * layer_ms[1] ++ (double) (k3 - k2) * layer_ms[2] + (double) (L - k3) * layer_ms[3];+ ++tried;+ if (ms < best_ms) {+ best = {k1, k2, k3};+ best_ms = ms;+ best_mass = hm / denom;+ best_held = held_at[a] + held_at[b] + held_at[c] + held_at[d];+ }+ }+ // Four stages into fewer than five layers: nothing was enumerated, so keep the old guess rather+ // than leave `best` empty - an empty split would leave every stage's lb/le unset.+ if (best.empty()) proportional();+ } else {+ // Beyond four GPUs the placements outnumber any budget worth spending at startup (C(46,4) is+ // 163,185 at five). Nothing on this rig reaches it.+ proportional();}split_at = best;std::string ks;for (const int64_t k : split_at) ks += (ks.empty() ? "" : ",") + std::to_string(k);std::fprintf(stderr, "strata generate: layer split auto: K=%s - predicted %.1f ms per decode window; the caches "- "hold %lld of %zu profiled pairs (~%.1f%% of the routed mass)\n", ks.c_str(), best_ms,- (long long) best_held, profile.size(), 100.0 * best_mass);+ "hold %lld of %zu profiled pairs (~%.1f%% of the routed mass), best of %lld placements\n",+ ks.c_str(), best_ms, (long long) best_held, profile.size(), 100.0 * best_mass, (long long) tried);}for (size_t i = 0; i < split_at.size(); ++i)if (split_at[i] >= g.n_layers) {@@ -3049,7 +3618,12 @@ int main(int argc, char **argv) try {while (st < (int) split_at.size() && l >= split_at[(size_t) st]) ++st;return st;};+ // the whole ranking, hottest first, before each stage takes its own layers' share: the resident RAM copy ranks+ // the experts no GPU holds over ALL the layers (with CUDA0's share alone, a copy that did not fit kept only layers+ // 0..K-1's experts and read every later layer's from the files)+ std::vector<std::pair<int32_t, int32_t>> profile_all;if (multi_gpu) {+ profile_all = profile;std::vector<std::pair<int32_t, int32_t>> mine;for (const auto& pr : profile) {const int st = stage_of(pr.first);@@ -3062,6 +3636,26 @@ int main(int argc, char **argv) try {}}+ // ---- `--layer-split auto` with the trim asked: THE STAGES' WEIGHTS, NOW THAT THE SPLIT IS KNOWN. Each later card+ // loads the dense weights of the layers it runs and nothing else (before this they loaded in the loop above, a+ // full copy per card: on the 4-way IQ3_S rig CUDA1 3650 expert slots, CUDA2 1241, CUDA3 533 and a 768-token prompt+ // chunk; carved 4608 / 2485 / 1772 and 6144). The search priced these arenas from the pack index (`stage_pool`).+ if (late_weights)+ for (size_t i = 0; i < stages.size(); ++i) {+ GpuStage& st = *stages[i];+ const strata::core::OnDevice on(st.dev);+ if (!load_stage_weights(st, st.lb, st.le, true)) return 1;+ size_t fb = 0, tb = 0;+ /*+ DPCT1106: 'cudaMemGetInfo' was migrated with the Intel+ extensions for device information which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ dpct::get_current_device().get_memory_info(fb, tb);+ std::fprintf(stderr, "strata generate: layer split: CUDA%d holds its weights; %.2f GiB free (its session "+ "follows)\n", st.dev, (double) fb / 1073741824.0);+ }+// ---- CUDA0's session, and the stages' sessions: sized to each device's own layer range (the carve). A// stage that runs [lb, le) carves only those layers' GDN rows and QSA pools - before the carve every stage// held all 48 layers' state whatever layers it ran, which is the same disease the chunked-QSA-prefill PR@@ -3069,6 +3663,25 @@ int main(int argc, char **argv) try {{const strata::core::OnDevice on0(0);const int64_t hi0 = multi_gpu ? split_at[0] : -1;+ // the elastic K/V (--kv-grow, see kvg_ensure): one GPU, the whole K/V in VRAM (no streaming), a profiled cache+ // that can give slots up, and every expert in RAM for the CPU to compute the ones it gives up+ {+ const char* ev = std::getenv("STRATA_KV_GROW");+ bool remote = false;+ for (const int r : o.expert_cache_remote) remote = remote || r > 0;+ const bool asked = ev != nullptr && ev[0] != '\0' ? ev[0] != '0' : o.kv_grow;+ const bool on = asked && !multi_gpu && o.kv_resident <= 0 &&+ !o.expert_profile.empty() && !o.resident_cpu_experts && o.expert_cache != 0 && !remote &&+ strata::core::vmm_available() &&+ // the batch slots carve their own K/V and --vram-elastic's cache is not one VMM range+ o.batch == 0 && !o.vram_elastic && o.peer_device < 0;+ if (asked && !on)+ std::fprintf(stderr, "strata generate: --kv-grow is off (one GPU, a profile, the whole K/V in VRAM, "+ "every expert in RAM, no --batch, --vram-elastic or --peer-device)\n");+ const char* iv = std::getenv("STRATA_KV_GROW_INIT");+ strata::core::qsa_set_kv_elastic(on, iv != nullptr && std::atoll(iv) > 0 ? std::atoll(iv) : 16384);+ strata::core::ExpertCache::set_vmm(on);+ }if (DPCT_CHECK_ERROR(sbuf = (void *)sycl::malloc_device(strata::core::session_bytes(g, o.max_context, K, 0, hi0),@@ -3138,21 +3751,150 @@ int main(int argc, char **argv) try {last ? " and the head" : "", (double) fb / 1073741824.0);}+ // --batch: every stage carves o.batch more sessions like its own (same layer range and context), one per+ // slot of the batch windows. Before the expert cache is sized, so `--expert-cache auto` leaves them room.+ // Recommend, never force: a count the engine cannot run is said and adjusted (or batching left off) - the+ // engine still starts and serves one request at a time.+ // --batch-mtp / STRATA_BATCH_MTP=1 (opt-in): a slot also verifies one MTP proposal per window. Recommend, never+ // force: when it cannot run it is said and left off (plain batching still starts); default off = exactly 0.1.39.+ const char* batch_mtp_env = std::getenv("STRATA_BATCH_MTP");+ bool batch_mtp = o.batch_mtp || (batch_mtp_env != nullptr && batch_mtp_env[0] != '\0' && batch_mtp_env[0] != '0');+ if (batch_mtp) {+ const char* why = o.batch < 2 ? "it needs --batch 2 or more" : o.mtp.empty() ? "it needs --mtp"+ : o.spec < 2 ? "it needs --spec T (T >= 2)" : (multi_gpu || split_same || !stages.empty())+ ? "it is for one GPU (no layer split or helper) for now" : !o.serve ? "it needs --serve" : nullptr;+ if (why != nullptr) {+ std::fprintf(stderr, "strata generate: WARNING: --batch-mtp is off: %s\n", why);+ batch_mtp = false;+ }+ }+ std::vector<std::vector<std::unique_ptr<strata::core::SessionState>>> bslot_ss;+ if (o.batch != 0) {+ const int cap = strata::kernels::kVerifyMaxT;+ const char* off = !o.serve ? "it needs --serve" : o.batch < 2 ? "it needs 2 or more slots"+ : split_same ? "it needs each stage of a layer split on its own GPU" : nullptr;+ if (off != nullptr) {+ std::fprintf(stderr, "strata generate: WARNING: --batch %d is off: %s\n", o.batch, off);+ o.batch = 0;+ } else if (o.batch > cap && !batch_mtp) {+ std::fprintf(stderr, "strata generate: WARNING: --batch %d: a batch window holds at most %d rows, so %d "+ "slots\n", o.batch, cap, cap);+ o.batch = cap;+ }+ }+ if (o.batch > 0 && o.batch_groups > 1 && (stages.empty() || o.batch % o.batch_groups != 0)) {+ std::fprintf(stderr, "strata generate: WARNING: --batch-groups %d needs a layer split and to divide --batch %d; "+ "one group\n", o.batch_groups, o.batch);+ o.batch_groups = 1;+ }+ if (o.batch > 0) {+ bslot_ss.resize(1 + stages.size());+ int fit = o.batch; // the slots every stage could carve+ uint64_t bytes0 = 0;+ for (size_t k = 0; k < bslot_ss.size(); ++k) {+ const int dev = k == 0 ? 0 : stages[k - 1]->dev;+ const int64_t lo = k == 0 ? 0 : stages[k - 1]->lb;+ const int64_t hi = k == 0 ? (multi_gpu ? split_at[0] : -1) : stages[k - 1]->le;+ const strata::core::OnDevice on_k(dev);+ const uint64_t bytes = strata::core::session_bytes(g, o.max_context, K, lo, hi);+ if (k == 0) bytes0 = bytes;+ for (int b = 0; b < fit; ++b) {+ auto u = std::make_unique<strata::core::SessionState>();+ void* buf = nullptr;+ if (DPCT_CHECK_ERROR(buf = (void *)sycl::malloc_device(+ bytes, dpct::get_in_order_queue())) !=+ 0 ||+ strata::core::session_init(g, o.max_context, K, buf, *u, lo,+ hi) == 0) {+ /*+ DPCT1026: The call to cudaGetLastError was removed+ because this functionality is redundant in SYCL.+ */+ if (buf != nullptr)+ sycl::free(buf, dpct::get_in_order_queue());+ size_t fb = 0, tb = 0;+ /*+ DPCT1106: 'cudaMemGetInfo' was migrated with the Intel+ extensions for device information which may not be supported+ by all compilers or runtimes. You may need to adjust the+ code.+ */+ dpct::get_current_device().get_memory_info(fb, tb);+ std::fprintf(stderr, "strata generate: WARNING: --batch %d: slot %d's session does not fit on CUDA%d "+ "(%.2f GiB each, %.2f GiB free); %d slot%s\n", o.batch, b, dev,+ (double) bytes / 1073741824.0, (double) fb / 1073741824.0, b, b == 1 ? "" : "s");+ fit = b;+ break;+ }+ strata::core::session_zero(*u, g, nullptr, nullptr);+ bslot_ss[k].push_back(std::move(u));+ }+ dpct::get_current_device().queues_wait_and_throw();+ size_t fb = 0, tb = 0;+ /*+ DPCT1106: 'cudaMemGetInfo' was migrated with the Intel+ extensions for device information which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ dpct::get_current_device().get_memory_info(fb, tb);+ std::fprintf(stderr, "strata generate: --batch: %d slot sessions on CUDA%d (%.2f GiB each); %.2f GiB free\n",+ (int) bslot_ss[k].size(), dev, (double) bytes / 1073741824.0, (double) fb / 1073741824.0);+ }+ for (auto& v : bslot_ss) if ((int) v.size() > fit) v.resize((size_t) fit); // the same count on every stage+ if (fit < 2) {+ std::fprintf(stderr, "strata generate: WARNING: --batch is off: not two slot sessions fit (a smaller "+ "--max-context or KV streaming, --kv-resident, makes them smaller)\n");+ bslot_ss.clear();+ o.batch = 0;+ } else {+ o.batch = fit;+ if (o.batch_groups > 1 && o.batch % o.batch_groups != 0) o.batch_groups = 1;+ // the sessions' VRAM is the expert cache's: say what it costs (docs/BATCHING.md has the measured trade)+ std::fprintf(stderr, "strata generate: --batch %d: the slot sessions take %.2f GiB of VRAM on CUDA0 that the "+ "expert cache would otherwise hold\n", o.batch,+ (double) bytes0 * o.batch / 1073741824.0);+ }+ }+// Secure MTP's CUDA0 allocations before the large host arena is registered with both CUDA contexts.// In particular WDDM can refuse the draft weights after mapping tens of GiB of host pages.strata::core::MtpDrafter mtp;+ // the draft layer's geometry (the canonical model's MTP head), `static` because MtpDrafter keeps a reference; the batch+ // slots' draft-KV copies use this one too+ static const strata::core::ModelGeometry draft_geometry{};+ std::vector<std::unique_ptr<strata::core::MtpDrafter>> slot_mtp;if (!o.mtp.empty()) {if (o.spec < 2) {std::fprintf(stderr, "strata generate: --mtp is ignored without --spec T (T >= 2)\n");o.mtp.clear();}if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size());+ mtp.set_hnorm_per_stream(o.mtp_hnorm_stream); // --mtp-hnorm stream (opt-in), before any capture+ mtp.set_q4(o.mtp_q4 == "all" || o.mtp_q4 == "proj", o.mtp_q4 == "all" || o.mtp_q4 == "head"); // before load+ if (!o.mtp_draft_vocab.empty()) mtp.set_draft_vocab(o.mtp_draft_vocab);// the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned,// so it always sees the canonical geometry; `static` because MtpDrafter keeps a reference- static const strata::core::ModelGeometry draft_geometry{};// with a layer split across GPUs the drafter reads the last stage's residual: it lives on that deviceconst strata::core::OnDevice on_mtp(last_st ? last_st->dev : -1);- if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st ? last_st->ss : ss, o.spec, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), vram_free_note().c_str()); return 1; }+ // --pipeline-windows 2: 8 rows (the chain runs on past the window in flight: its drafts, its bonus token and+ // the next window's drafts), and the round/step graphs carry the forcing kernel+ const int mtp_t = o.pipeline_windows >= 2 ? strata::kernels::kVerifyMaxT : o.spec;+ if (o.pipeline_windows >= 2) mtp.set_force_capture(true);+ if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st ? last_st->ss : ss, mtp_t, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), vram_free_note().c_str()); return 1; }+ mtp.set_ple_session(&ss);+ if (batch_mtp) {+ for (int b = 0; b < o.batch; ++b) {+ auto d = std::make_unique<strata::core::MtpDrafter>();+ if (!d->load(o.mtp, draft_geometry, *bslot_ss[0][(size_t) b], o.spec, err, o.mtp_window, &mtp)) {+ std::fprintf(stderr, "strata generate: batch MTP slot %d: %s%s\n", b, err.c_str(),+ vram_free_note().c_str());+ return 1;+ }+ d->set_max_drafts(1); // the first candidate verifies one proposal per slot+ d->set_ple_session(bslot_ss[0][(size_t) b].get());+ slot_mtp.push_back(std::move(d));+ }+ }}// THE HEAD BEFORE THE CACHE, AND BEFORE THE ARENA. The expert cache takes what is free minus the reserve, so// everything allocated after it comes out of the reserve. The native head (~0.5 GB with IQ3_S) was loaded after@@ -3165,12 +3907,14 @@ int main(int argc, char **argv) try {const int64_t n_vocab = wo->ne1;strata::core::NativeHead native_head;if (!o.native_head_gguf.empty() && !multi_gpu) { // a layer split's head is on its last stage+ const auto head_t0 = std::chrono::steady_clock::now();if (!native_head.load(o.native_head_shards, g.n_embd, n_vocab, err)) {std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), vram_free_note().c_str());return 1;}- std::fprintf(stderr, "strata generate: experimental native Q5_K head, %llu bytes\n",- (unsigned long long) native_head.weight_bytes());+ std::fprintf(stderr, "strata generate: experimental native Q5_K head, %llu bytes, in %.1f s\n",+ (unsigned long long) native_head.weight_bytes(),+ std::chrono::duration<double>(std::chrono::steady_clock::now() - head_t0).count());}std::vector<float> logits((size_t) n_vocab);float* d_logits = nullptr;@@ -3257,6 +4001,8 @@ int main(int argc, char **argv) try {strata::emulated_cc()? " (STRATA_EMULATE_CC: a test mode, the card is emulated)": "");+#if !defined(STRATA_HIP_GFX906) // a CUDA toolkit mismatch; the gfx906 HIP build+ // has no DPCT_COMPAT_RT_VERSION{ // #542: a build whose libcudart is older than its headers (a CUDA 13 kit with a dangling libcudart.so that// CMake resolved to the system's CUDA 12 one) reads cudaDeviceProp shifted - silently, and slowlyint rt = 0;@@ -3280,6 +4026,7 @@ int main(int argc, char **argv) try {DPCT_COMPAT_RT_VERSION % 1000 / 10, rt / 1000,rt % 1000 / 10);}+#endif#endifconst std::string e = strata::core::device_code_error();if (!e.empty()) {@@ -3333,11 +4080,18 @@ int main(int argc, char **argv) try {// #286: with a RAM budget the hottest experts live in it, and the rest are read from the drive unbuffered// when the file cache could not keep them beside the budget anyway (a 32 GB PC) - the mapped reads' page// faults are small requests on the critical path, and their pages take the RAM the budget was sized for- if (o.resident_budget > 0 || std::getenv("STRATA_UNBUFFERED_LOAD") != nullptr) {+ // #773: without a RAM budget there is no RAM copy and the file cache IS the expert tier (measured on a+ // 32 GB, 2 x 16 GB rig: forcing unbuffered reads there re-read 163-629 GB from the drive and halved the+ // speed), so STRATA_UNBUFFERED_LOAD=1 is not honoured in that mode+ if (o.resident_budget > 0) {std::string why;const bool ub = src.set_unbuffered(o.resident_budget, why);std::fprintf(stderr, "strata generate: the file tier reads %s (%s)\n",ub ? "unbuffered" : "through the file cache", why.c_str());+ } else if (const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); env != nullptr && env[0] != '\0' &&+ env[0] != '0') {+ std::fprintf(stderr, "strata generate: the file tier reads through the file cache (STRATA_UNBUFFERED_LOAD=%s "+ "ignored: without --resident-budget-gib the file cache holds the experts)\n", env);}srcp = &src;} else {@@ -3391,6 +4145,16 @@ int main(int argc, char **argv) try {std::fprintf(stderr, "strata generate: hybrid CPU detected (%d P-cores / %d threads, %d E-cores), pool workers: %d, affinity: %s\n",pool.p_cores(), pool.p_threads(), pool.e_cores(), pool.workers(), aff_str);}+ { // where the threads run (--host-core)+ const strata::kernels::cpu::CpuTopology ht = strata::kernels::cpu::detect_cpu_topology(true, o.pool_affinity);+ std::string on;+ for (int i = 0; i < pool.workers() && i < (int) ht.worker_cores.size(); ++i)+ on += (i > 0 ? "," : "") + std::to_string(ht.worker_cores[(size_t) i]);+ std::fprintf(stderr, "strata generate: %d pool workers on logical processors %s, the host thread on %d%s "+ "(--host-core %s)\n", pool.workers(), on.c_str(), ht.host_core,+ pool.host_works() ? " (draining too)" : "",+ strata::kernels::cpu::host_core_setting() == strata::kernels::cpu::HostCore::Last ? "last" : "first");+ }if (o.no_ple_prefetch) strata::kernels::ple_prefetch_enable(false);// ---- R4's slot storage. Allocated AFTER the weights and the session, so `cudaMemGetInfo` inside `open`// sees the memory this process actually has left rather than the card's idle figure - and refuses with both@@ -3400,24 +4164,41 @@ int main(int argc, char **argv) try {// THE HEAD BEFORE THE CACHE: the native head and the logits are allocated above, before the expert arena (#620)const bool auto_cache = o.expert_cache < 0;bool reserve_adapted = false; // #496: the auto sizing lowered the reserve so a small card's cache fits+ // --pipeline-windows: what it allocates on CUDA0 after the cache (see kPipeWindowMib)+ const int64_t pipe_first = o.pipeline_windows <= 0 ? 0+ : (kPipeWindowMib << 20) + (o.pipeline_windows >= 2 ? 2 * (int64_t) gdn_snapshot_bytes(ss) : 0);+ if (pipe_first > 0)+ std::fprintf(stderr, "strata generate: --pipeline-windows %d: %lld MiB of CUDA0 kept out of the expert cache "+ "(the second verifier%s)\n", o.pipeline_windows, (long long) (pipe_first >> 20),+ o.pipeline_windows >= 2 ? ", the GDN snapshots" : "");+ // The MiB the prompt path's OWN buffers (no loan) take, which the cache sizing leaves out. 0.1.39's rule is+ // 160 + chunk * 680 / 1024 (~16 GiB at 24576 against ~2.4 GiB really allocated); STRATA_OWNED_PRICE=exact prices the+ // real allocation instead (Prefill::bytes_needed_owned: 2 MiB pages, the ring in one piece, as PR #796 measured)+ // and gives that cache the difference. A recommendation to try, so it is not the default.+ auto owned_prefill_mib = [&]() -> int64_t {+ if (!(o.prefill_chunk > 0 && !pf_borrow)) return 0;+ static const bool exact = [] { const char* v = std::getenv("STRATA_OWNED_PRICE"); return v != nullptr && std::string(v) == "exact"; }();+ if (!exact) return 160 + (o.prefill_chunk * 680) / 1024;+ const int64_t mib = ((int64_t) strata::prefill::Prefill::bytes_needed_owned(g, ss, o.prefill_chunk) + (1 << 20) - 1) >> 20;+ std::fprintf(stderr, "strata generate: STRATA_OWNED_PRICE=exact: the prompt path's own buffers for a %lld-token chunk: %lld MiB (the 0.1.39 rule: %lld MiB)\n",+ (long long) o.prefill_chunk, (long long) mib, (long long) (160 + (o.prefill_chunk * 680) / 1024));+ return mib + 64; // a margin for the allocator+ };if (o.expert_cache < 0) {size_t free_b = 0, total_b = 0;- /*- DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions- for device information which may not be supported by all compilers or- runtimes. You may need to adjust the code.- */- dpct::get_current_device().get_memory_info(free_b, total_b);+ free_b = strata::core::device_free_bytes(); (void) total_b;// Plan v0.3 P5: the batched prompt path's chunk buffers are allocated later, so they are reserved here -// under WDDM an over-subscribed allocation does not fail, it pages to system memory and crawls.// (with borrowing - the default with a profile - the prompt path lends cache slots instead; `pf_borrow` is// the predicate a local `borrow` was here, hoisted above so both cache-size branches read the same one)- const int64_t prefill_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0;+ const int64_t prefill_mib = owned_prefill_mib();// the draft layer's head and logits are allocated when it binds, after this: 0.1.27's CJK subset made them// ~110-180 MiB larger, and out of the reserve they left 16 GB cards below the stall line (#199)- const int64_t mtp_bind = (!o.mtp.empty() && native_head.loaded())- ? (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) : 0;- const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind;+ int64_t mtp_bind = (!o.mtp.empty() && native_head.loaded())+ ? (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) : 0;+ for (const auto& d : slot_mtp)+ mtp_bind += (int64_t) d->bind_bytes(native_head.row_bytes(), n_vocab);+ const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind + pipe_first;const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;int64_t slots = ((int64_t) free_b - reserve) / blob;if (!profile.empty()) slots = std::min<int64_t>(slots, (int64_t) profile.size());@@ -3440,10 +4221,10 @@ int main(int argc, char **argv) try {? ((int64_t) strata::prefill::Prefill::bytes_needed(g, ss, 256) + blob - 1) / blob + 128 : 1;if (o.expert_cache < min_slots && !o.vram_reserve_given && o.vram_reserve_mib > kSmallReserveMib) {// the largest reserve (in MiB) that still leaves min_slots- const int64_t fit_mib = ((int64_t) free_b - mtp_bind - min_slots * blob) / (1 << 20) - prefill_mib;+ const int64_t fit_mib = ((int64_t) free_b - mtp_bind - pipe_first - min_slots * blob) / (1 << 20) - prefill_mib;if (fit_mib >= kSmallReserveMib) {const int r = (int) std::min<int64_t>(fit_mib, o.vram_reserve_mib);- int64_t s2 = ((int64_t) free_b - ((((int64_t) r + prefill_mib) << 20) + mtp_bind)) / blob;+ int64_t s2 = ((int64_t) free_b - ((((int64_t) r + prefill_mib) << 20) + mtp_bind + pipe_first)) / blob;if (!profile.empty()) s2 = std::min<int64_t>(s2, (int64_t) profile.size());std::fprintf(stderr, "strata generate: expert cache auto: the %d MiB reserve leaves too few slots on ""this card (a working cache needs %lld): a %d MiB reserve instead -> %lld slots\n",@@ -3457,7 +4238,7 @@ int main(int argc, char **argv) try {// what is short, and what makes room: the numbers a small card picks fromconst int64_t at_reserve = o.vram_reserve_given ? o.vram_reserve_mib: std::min(o.vram_reserve_mib, kSmallReserveMib);- const int64_t need_b = (((int64_t) at_reserve + prefill_mib) << 20) + mtp_bind + min_slots * blob;+ const int64_t need_b = (((int64_t) at_reserve + prefill_mib) << 20) + mtp_bind + pipe_first + min_slots * blob;const int64_t short_mib = std::max<int64_t>(1, (need_b - (int64_t) free_b + (1 << 20) - 1) >> 20);const int64_t session_mib =(int64_t) (strata::core::session_bytes(g, o.max_context, K, 0, g.n_layers) >> 20);@@ -3480,14 +4261,9 @@ int main(int argc, char **argv) try {// fails with "device buffers ... do not fit" (with borrowing - the default with a profile - the path lends// slots instead and `prefill_mib` is 0, so only the reserve is checked)size_t free_b = 0, total_b = 0;- /*- DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions- for device information which may not be supported by all compilers or- runtimes. You may need to adjust the code.- */- dpct::get_current_device().get_memory_info(free_b, total_b);- const int64_t prefill_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0;- const int64_t reserve = ((int64_t) o.vram_reserve_mib + prefill_mib) << 20;+ free_b = strata::core::device_free_bytes(); (void) total_b;+ const int64_t prefill_mib = owned_prefill_mib();+ const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + pipe_first;const int64_t fit = std::max<int64_t>(((int64_t) free_b - reserve) / (int64_t) strata::kernels::cpu::expert_layout().max_blob, 0);if (o.expert_cache > fit) {// a WARNING that names the knob: the user asked for this size, and gets fewer slots@@ -3505,16 +4281,12 @@ int main(int argc, char **argv) try {std::vector<int64_t> sized_slots;if (native_pack && o.expert_cache > 0 && !profile.empty() && !o.expert_cache_per_layer) {size_t free_b = 0, total_b = 0;- /*- DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions- for device information which may not be supported by all compilers or- runtimes. You may need to adjust the code.- */- dpct::get_current_device().get_memory_info(free_b, total_b);+ free_b = strata::core::device_free_bytes(); (void) total_b;const auto& lay = strata::kernels::cpu::expert_layout();const uint64_t budget = (uint64_t) o.expert_cache * lay.max_blob; // what the uniform sizing granteduint64_t used = 0;- size_t free_room = free_b > ((size_t) o.vram_reserve_mib << 20) ? free_b - ((size_t) o.vram_reserve_mib << 20) : 0;+ const size_t keep_free = ((size_t) o.vram_reserve_mib << 20) + (size_t) pipe_first;+ size_t free_room = free_b > keep_free ? free_b - keep_free : 0;const uint64_t cap = std::min<uint64_t>(budget, (uint64_t) free_room);for (const auto& pr : profile) {const uint64_t b = (lay.blob_bytes(pr.first) + 255) / 256 * 256;@@ -3522,6 +4294,13 @@ int main(int argc, char **argv) try {used += b;sized_slots.push_back((int64_t) lay.blob_bytes(pr.first));}+ // #831: the sized-slots loop walks the profile's pairs, so the profile's length is the ceiling; an explicit+ // --expert-cache above it used to be cut with no word. A warning only (what is allocated does not change).+ if (!auto_cache && o.expert_cache > 0 && sized_slots.size() == profile.size() && (size_t) o.expert_cache > profile.size())+ std::fprintf(stderr, "strata generate: WARNING: --expert-cache %d is more than the %zu pairs of the profile %s: "+ "%zu slots (the profile is the ceiling on a native pack; a profile that ranks every "+ "(layer, expert) pair lifts it - tools/make_profile.py)\n", o.expert_cache,+ profile.size(), o.expert_profile.c_str(), profile.size());o.expert_cache = (int) sized_slots.size();}// #533: --vram-elastic: the cache in physical segments (the VRAM command resizes it between requests). One GPU,@@ -3616,13 +4395,8 @@ int main(int argc, char **argv) try {.wait();dpct::get_current_device().queues_wait_and_throw();size_t free_b = 0, total_b = 0;- /*- DPCT1106: 'cudaMemGetInfo' was migrated with the Intel- extensions for device information which may not be supported by all- compilers or runtimes. You may need to adjust the code.- */- dpct::get_current_device().get_memory_info(free_b, total_b);- const int64_t want = (int64_t) o.vram_reserve_mib << 20;+ free_b = strata::core::device_free_bytes(); (void) total_b;+ const int64_t want = ((int64_t) o.vram_reserve_mib << 20) + pipe_first;if ((int64_t) free_b >= want - (64ll << 20)) break;// short by (want - free); a figure of 0 only says "at least": the first two such reads give back 1 GiB// each (under WDDM the free figure read before the allocation runs ~0.7 GiB high), later ones a quarter@@ -3744,12 +4518,22 @@ int main(int argc, char **argv) try {// #286: an unbuffered file tier reads the pairs in batches of 64, the next batch while this one is copiedstd::future<void> ahead;auto read_batch = [&](int64_t at) { src.prefetch_pairs(profile.data() + at, std::min<int64_t>(64, want - at)); };+ // mapped reads: advise the next `fill_ahead` pairs so their reads overlap; STRATA_FILL_AHEAD=0 turns it off+ int64_t fill_ahead = 0;+ if (!piped && !per_layer && srcp == &src && !src.unbuffered()) {+ const char* v = std::getenv("STRATA_FILL_AHEAD");+ fill_ahead = v == nullptr ? 256 : std::max(0, std::atoi(v));+ if (fill_ahead > 0 && !src.advise_pairs(profile.data(), std::min<int64_t>(fill_ahead, want))) fill_ahead = 0;+ std::fprintf(stderr, "strata generate: the profile fill asks for %lld pairs ahead (STRATA_FILL_AHEAD)\n",+ (long long) fill_ahead);+ }for (int64_t i = 0; i < want && !piped; ++i) {if (!per_layer && srcp == &src && src.unbuffered() && i % 64 == 0) {if (ahead.valid()) ahead.get();else read_batch(i);if (i + 64 < want) ahead = std::async(std::launch::async, read_batch, i + 64);}+ if (fill_ahead > 0 && i + fill_ahead < want) (void) src.advise_pairs(profile.data() + i + fill_ahead, 1);const int32_t slot = xcache.admit(profile[(size_t) i].first, profile[(size_t) i].second);if (slot == strata::core::kNotResident) {if (per_layer) continue;@@ -3779,8 +4563,10 @@ int main(int argc, char **argv) try {return 1;}mem_mark("the profile fill");- std::fprintf(stderr, "strata generate: pre-filled %lld of %lld slots from the profile; slot 0 verified\n",- (long long) prefilled, (long long) (per_layer ? xcache.slots() : want));+ std::fprintf(stderr, "strata generate: pre-filled %lld of %lld slots from the profile in %.1f s (%.0f MB/s); "+ "slot 0 verified\n",+ (long long) prefilled, (long long) (per_layer ? xcache.slots() : want), fill_s,+ fill_s > 0 ? (double) fill_bytes / 1e6 / fill_s : 0.0);}// SYCL port, plan item 2: the experts that did not fit VRAM, mirrored once in pinned host memory the GPU reads// over PCIe (--stream-experts has no host copy otherwise: each routed miss was an SSD read). The share of misses@@ -3863,9 +4649,28 @@ int main(int argc, char **argv) try {used += b;sized.push_back((int64_t) lay.blob_bytes(pr.first));}- if (sized.empty() ||- !(native_pack ? st.cache.open_sized(sized, g.n_layers, g.n_expert, err)- : st.cache.open((int64_t) sized.size(), g.n_layers, g.n_expert, (int64_t) lay.max_blob, err))) {+ // #841: a stage's cache can fail to open with the VRAM free (the card's allocation is also charged to the+ // Windows commit, or the free figure ran high): it is tried again with 90% of the slots, up to 3 times, each+ // try said. Nothing changes when the first open works.+ bool stage_open = false;+ for (int attempt = 0; !sized.empty(); ++attempt) {+ stage_open = native_pack ? st.cache.open_sized(sized, g.n_layers, g.n_expert, err)+ : st.cache.open((int64_t) sized.size(), g.n_layers, g.n_expert, (int64_t) lay.max_blob, err);+ if (stage_open || attempt >= 3) break;+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not+ use the error codes. The cudaGetLastError function call was replaced+ with 0. You need to rewrite this code.+ */+ (void)0;+ const size_t keep = sized.size() * 9 / 10;+ std::fprintf(stderr, "strata generate: layer split, CUDA%d expert cache: %s; trying %zu of %zu slots "+ "(try %d of 3)\n", st.dev, err.c_str(), keep, sized.size(), attempt + 1);+ if (keep == 0) break;+ st.cache.close();+ sized.resize(keep);+ }+ if (!stage_open) {std::fprintf(stderr, "strata generate: layer split, CUDA%d expert cache: %s\n", st.dev,sized.empty() ? "no room" : err.c_str());return 1;@@ -3899,6 +4704,8 @@ int main(int argc, char **argv) try {std::fprintf(stderr, "strata generate: layer split: CUDA0 runs layers 0-%lld\n", (long long) (split_at[0] - 1));std::array<strata::core::RemoteExperts, 3> remote_experts;+ std::unique_ptr<strata::core::RemoteExpertOpt> remote_opt;+ if (o.remote_expert_opt && o.expert_cache_remote[0] > 0) remote_opt = std::make_unique<strata::core::RemoteExpertOpt>();const bool multi_remote = o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0;if (o.expert_cache_remote[0] > 0) {if (o.expert_cache <= 0 || profile.empty() || o.no_pool) {@@ -3912,7 +4719,8 @@ int main(int argc, char **argv) try {for (const auto& pr : st->profile)if (st->cache.slot_of(pr.first, pr.second) < 0) ranked.push_back(pr);}- if (multi_remote) {+ if (multi_remote || std::any_of(o.expert_cache_remote_auto.begin(), o.expert_cache_remote_auto.end(),+ [](bool automatic) { return automatic; })) {// The shipped frequency profile names only 8000 of 24576 experts. Once exhausted,// fill remaining VRAM from unranked pairs in expert-then-layer order: this spreads// the tail across all layers instead of concentrating it on layer zero.@@ -3970,8 +4778,10 @@ int main(int argc, char **argv) try {if (st->cache.slot_of(pr.first, pr.second) >= 0)claimed[(size_t) pr.first * (size_t) g.n_expert + (size_t) pr.second] = 1;for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) {+ if (remote_opt) remote_opt->attach(remote_experts[(size_t) r]);if (!remote_experts[(size_t) r].open(remote_dev[r], o.expert_cache_remote[(size_t) r],- g.n_layers, g.n_expert, by_device[(size_t) r], xcache, *srcp, claimed, err)) {+ g.n_layers, g.n_expert, by_device[(size_t) r], xcache, *srcp, claimed, err,+ o.expert_cache_remote_auto[(size_t) r])) {std::fprintf(stderr, "strata generate: %s\n", err.c_str());return 1;}@@ -4000,7 +4810,18 @@ int main(int argc, char **argv) try {(long long) (peer.resident() + xcache.slots()), (long long) (g.n_layers * g.n_expert));}+ if (remote_opt && !remote_opt->init(err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; }Drive drive;+ // #731 (opt-in, STRATA_DISJOINT_ADAPT=1): the adaptive tiers leave an expert a helper GPU holds out of the primary's+ // promotion candidates (it would sit in both caches). Asked live, from the helper's own cache (RemoteExperts::holds,+ // #854), so an expert the helper's tier swaps in or out later is followed - never a copy taken at load.+ const bool disjoint_adapt = [] { const char* v = std::getenv("STRATA_DISJOINT_ADAPT"); return v != nullptr && std::atoi(v) != 0; }();+ auto helper_holds = [&](int64_t l, int32_t e) -> bool {+ if (!disjoint_adapt) return false;+ for (int r = 0; r < drive.d.remote_count; ++r)+ if (drive.d.remote[r]->holds(l, e)) return true;+ return false;+ };for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0)drive.d.remote[drive.d.remote_count++] = &remote_experts[(size_t) r];drive.d.peer = peer.valid() ? &peer : nullptr;@@ -4348,8 +5169,8 @@ int main(int argc, char **argv) try {return 1;}/*- DPCT1048: The original value cudaHostAllocDefault is not meaningful in- the migrated code and was removed or replaced with 0. You may need to+ DPCT1048: The original value cudaHostAllocDefault is not meaningful+ in the migrated code and was removed or replaced with 0. You may need tocheck the migrated code.*/if (DPCT_CHECK_ERROR(layer_stage = sycl::malloc_host<float>(@@ -4687,6 +5508,19 @@ int main(int argc, char **argv) try {// Plan v0.3 P4: with a PROFILE-filled cache the residency is static, so the hit decision moves onto the// device and the token graph keeps it. (A cache filled on demand still needs the per-layer host path.)std::vector<int32_t> host_res;+ // The residency table is read by kernels on non-blocking streams, which do not wait for the legacy stream a plain+ // cudaMemcpy runs on, and a pageable copy can return before its DMA has landed: each upload waits for its own copy+ // (the current device's legacy stream, stream 0 - nothing else; HIP has no cudaStreamLegacy name, #550).+ auto res_put = [&host_res](int32_t *dst) -> dpct::err0 {+ // SYCL port: the in-order queue's memcpy, waited for: the copy is complete when this returns+ try {+ dpct::get_in_order_queue().memcpy(dst, host_res.data(), host_res.size() * sizeof(int32_t)).wait();+ return 0;+ } catch (sycl::exception const& exc) {+ std::cerr << exc.what() << " (res_put)" << std::endl;+ return 1;+ }+ };int32_t* d_res = nullptr;int32_t* d_hit_count = nullptr;strata::core::TokenHits thits;@@ -4706,15 +5540,7 @@ int main(int argc, char **argv) try {host_res.size(), dpct::get_in_order_queue())) != 0 ||DPCT_CHECK_ERROR(d_hit_count = sycl::malloc_device<int32_t>(1, dpct::get_in_order_queue())) != 0 ||- /*- DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,- assuming in the original code the source host memory is pageable- memory. If the memory is not pageable, call wait() on event return- by memcpy API to ensure synchronization behavior.- */- DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(- d_res, host_res.data(), host_res.size() * sizeof(int32_t)).wait()) !=- 0) {+ res_put(d_res) != 0) {std::fprintf(stderr, "strata generate: the device residency table could not be staged\n");return 1;}@@ -4750,15 +5576,7 @@ int main(int argc, char **argv) try {if (DPCT_CHECK_ERROR(st->d_res = sycl::malloc_device<int32_t>(host_res.size(), dpct::get_in_order_queue())) != 0 ||- /*- DPCT1114: cudaMemcpy is migrated to asynchronization- memcpy, assuming in the original code the source host memory is- pageable memory. If the memory is not pageable, call wait() on- event return by memcpy API to ensure synchronization behavior.- */- DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(- st->d_res, host_res.data(),- host_res.size() * sizeof(int32_t)).wait()) != 0) {+ res_put(st->d_res) != 0) {std::fprintf(stderr, "strata generate: layer split: CUDA%d residency table failed\n", st->dev);return 1;}@@ -4837,8 +5655,9 @@ int main(int argc, char **argv) try {for (const int32_t r : host_res) nonres += r < 0;strata::prefill::set_nonresident_share(host_res.empty() ? 1.0 : (double) nonres / (double) host_res.size());}- auto lend_slots = [&](int64_t c) -> int64_t {- const uint64_t need = strata::prefill::Prefill::bytes_needed(g, ss, c);+ // bytes -> slots for CUDA0's cache: exact when it knows its per-slot offsets (a native pack's blobs differ+ // per layer), otherwise max_blob each.+ auto slots_from_bytes = [&](uint64_t need) -> int64_t {const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;int64_t k = (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob);if (xcache.slot_offsets() != nullptr) { // sized slots: take slots from the end until they hold `need`@@ -4848,6 +5667,18 @@ int main(int argc, char **argv) try {}return k;};+ // ...and its inverse, for the ring's room: the bytes the cache's last `k` slots hold. k can arrive <= 0: the+ // caller's lend budget is `min(slots - 128, pct * slots / 100)` and goes negative on a cache smaller than 128+ // slots, where `slots - k` would index slot_offsets() past its end. Such a cache lends nothing, so say so.+ auto bytes_from_slots = [&](int64_t k) -> uint64_t {+ if (k <= 0) return 0;+ if (xcache.slot_offsets() != nullptr)+ return (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[xcache.slots() - k]);+ return (uint64_t) k * (uint64_t) strata::kernels::cpu::expert_layout().max_blob;+ };+ auto lend_slots = [&](int64_t c) -> int64_t {+ return slots_from_bytes(strata::prefill::Prefill::bytes_needed(g, ss, c));+ };// `lend_bytes` went with the single-cache serve loan: a participant's loan is priced by `part_bytes` from its// OWN cache, and the only other user of the old helper was the serve path's own relayout.auto request_chunk = [](int64_t tokens, int64_t max_chunk) -> int64_t {@@ -4857,8 +5688,26 @@ int main(int argc, char **argv) try {: ((tokens + 255) / 256) * 256;return std::min(max_chunk, rounded);};+ // STRATA_PREFILL_EQUAL=1 (opt-in, PR #693): a segment of `tokens` reads in n = ceil(tokens / max_chunk) chunks of EQUAL+ // size (ceil(tokens / n) rounded up to 256) instead of full chunks and a short last one. A chunk of+ // stream_all_min_tokens() or more streams every expert the GPU does not hold, whatever its length, so a prompt's cost+ // is its number of such chunks and equal chunks borrow no more slots than that count needs. A last chunk below+ // stream_all_min_tokens() stays as it is (it moves only the experts its own tokens route to). Used ONLY where a+ // segment's chunk is chosen (the serve lend, generate's prompt); `request_chunk` is unchanged because+ // STRATA_SPLIT_SMALL_OWN uses it too. The chunk geometry changes the rounding, so it is off by default.+ static const bool equal_chunks = [] { const char* e = std::getenv("STRATA_PREFILL_EQUAL"); return e != nullptr && e[0] == '1'; }();+ auto equal_chunk = [&](int64_t tokens, int64_t max_chunk) -> int64_t {+ const int64_t plain = request_chunk(tokens, max_chunk);+ if (!equal_chunks || tokens <= 0 || max_chunk <= 0) return plain;+ const int64_t n = tokens / max_chunk + (tokens % max_chunk != 0);+ const int64_t last = tokens - (n - 1) * max_chunk;+ if (n <= 1 || last < strata::prefill::Prefill::stream_all_min_tokens()) return plain;+ const int64_t per = tokens / n + (tokens % n != 0);+ const int64_t rounded = per > std::numeric_limits<int64_t>::max() - 255 ? per : ((per + 255) / 256) * 256;+ return std::min(max_chunk, rounded);+ };// The prompt path's chunk and the slots it borrows for its buffers: the requested chunk halved until it fits,- // or with --prefill auto the largest of kAutoChunks whose buffers take at most kAutoLendPct % of the slots (a+ // or with --prefill auto the largest chunk whose buffers take at most kAutoLendPct % of the slots (a// lent slot's expert is streamed during the prompt and refilled after it; measured on a 12 GB card, 32K Q2_0// prompt: 4096 791 tok/s, 6144 878, 8192 973 with 69% of the slots lent). A request lends only what its own// prompt needs (Prefill::relayout), so a big chunk costs short prompts nothing. 0 = none fits.@@ -4871,20 +5720,95 @@ int main(int argc, char **argv) try {return v ? (int64_t) std::atoi(v): (int64_t) (strata::prefill::Prefill::pinned_share() >= 0.9 ? 90 : 85);}();+ // The largest chunk --prefill auto may pick: the operator's ceiling (--prefill auto:N) and never past the+ // context, but a bare `auto` always reaches 8192. 32768 and 16384 stay opt-in (#282): a 32K prompt with+ // IQ2_XS (RTX 5090, 64K context) read at 5,624 tok/s in 8192-token chunks and 6,465 in one 32768 chunk (40K+ // -> 18K experts streamed; an NVFP4 pack at 262K: 3,535 -> 5,201).+ const int64_t auto_ceiling = std::max<int64_t>(8192, std::min<int64_t>(o.prefill_auto_max, o.max_context));+ // The auto scan used to walk a fixed list of sizes - 32768, 16384, 8192, 6144, ... - and take the first that+ // fit. That list is coarse exactly where a rig needs it: this one affords ~8,700 tokens and was handed 8192,+ // and 8704 is not on it. `bytes_needed` is a sum of (T x positive constant) terms plus a max of such sums,+ // so it rises monotonically with T, and so does every test the scan applies - which makes the largest size+ // that fits a bisection on the 256-token grid the prompt path already works on (`request_chunk` rounds up to+ // it). log2(32768/256) = 7 probes, against the list's 10, at one `bytes_needed` per probe.+ auto biggest_chunk = [](int64_t ceiling, auto&& ok) -> int64_t {+ if (ceiling < 256) return 0;+ int64_t lo = 1, hi = ceiling / 256, best = 0; // n = T / 256, and ok() is monotone in n+ while (lo <= hi) {+ const int64_t mid = lo + (hi - lo) / 2;+ if (ok(mid * 256)) { best = mid * 256; lo = mid + 1; } else hi = mid - 1;+ }+ return best;+ };auto plan_lend = [&](int64_t& chunk) -> int64_t {- // 32768 and 16384 (#282, opt-in: --prefill auto:32768): a 32K prompt with IQ2_XS (RTX 5090, 64K context)- // read at 5,624 tok/s in 8192-token chunks and 6,465 in one 32768 chunk (40K -> 18K experts streamed; an- // NVFP4 pack at 262K: 3,535 -> 5,201)- static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256};auto slots_for = lend_slots;- if (o.prefill_auto) {+ // 0.1.39's list with its ring (also the size up to which a prompt keeps that ring under #583)+ auto old_rule = [&]() -> int64_t {+ strata::prefill::Prefill::set_ring_budget(0, 0);+ static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256};for (const int64_t c : kAutoChunks) {// above 8192: only when asked for, and only when a prompt of the context can use itif (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue;const int64_t k = slots_for(c);- if (k + 128 <= xcache.slots() && k * 100 <= kAutoLendPct * xcache.slots()) { chunk = c; return k; }+ if (k + 128 <= xcache.slots() && k * 100 <= kAutoLendPct * xcache.slots()) return c;}return 0;+ };+ if (o.prefill_auto && !strata::prefill::Prefill::ring_bytes_enabled()) { // STRATA_RING_BYTES=0: 0.1.39's list+ const int64_t c = old_rule();+ if (c > 0) { chunk = c; return slots_for(c); }+ return 0;+ }+ if (o.prefill_auto) { // the default since 0.1.39b (#583)+ // The chunk and the ring are one budget, and the ring is the better buy. Measured on this 4-way+ // IQ3_S rig (2x RTX 3060 + 2x RTX 5060, CUDA3 lending at its 90% cap) on a 120K prompt: 8960 tokens+ // with the 17-slot ring that leaves reads at 963 tok/s, 8192/130 at 1,008, 7168 with the ring full at+ // its 199-slot byte budget at 1,000, and 5632/199 at 915. A ring slot is worth ~0.53 tok/s there and+ // a chunk token ~0.05, so the 69 slots between a full ring and 8192's 130 are worth more than the+ // 512 chunk tokens they cost - and once the ring IS full, shrinking the chunk further buys nothing.+ // So: the largest chunk that still leaves the ring full. Only a rig where no chunk at all can afford+ // one falls back to the old rule, which takes the largest chunk whose ring clears kRingMin (the+ // value at or below which ring_slots() returns STAGE and streaming is off).+ constexpr int64_t kRingMin = 16;+ const int64_t small = old_rule(); // 0.1.39's chunk (and its ring for the prompts that fit it)+ const int64_t ring_max = strata::prefill::Prefill::ring_cap_for(small);+ const int64_t budget = std::min(xcache.slots() - 128, kAutoLendPct * xcache.slots() / 100);+ // The room is a BYTE budget. A ring slot is max_blob bytes (`carve` lays out one whole blob each),+ // while these cache slots hold their own layer's blob, which is smaller than max_blob unless the cache+ // happens to hold the pack's biggest layer - on the 4-way IQ3_S rig that is 2.15 MiB a slot against a+ // 2.54 MiB max_blob. Counting the room in slots priced the ring at 0.85x what it costs, `fits` then+ // rejected the whole chunk instead of shrinking the ring, and the scan stopped a step short: measured+ // against chunk 6144/ring 199, 8192 was refused where the same bytes afford a ~87-slot ring.+ const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;+ const uint64_t avail = bytes_from_slots(budget);+ auto room_of = [&](int64_t t) -> int64_t {+ const uint64_t nonring = strata::prefill::Prefill::bytes_needed_no_ring(g, ss, t);+ return std::min((int64_t) ((avail - std::min(avail, nonring)) / (uint64_t) blob), ring_max);+ };+ // `room_of` is capped at ring_max, so "the ring is full" is exactly room == ring_max, and both that+ // test and the ones below it only get harder as t grows - the bisection stays valid.+ auto scan = [&](int64_t floor) -> int64_t {+ return biggest_chunk(auto_ceiling, [&](int64_t t) -> bool {+ const int64_t room = room_of(t);+ if (room < floor) return false;+ strata::prefill::Prefill::set_ring_budget((int) room, 0);+ // ring_slots() now returns `room` - unless STRATA_PREFILL_RING overrides it, in which case the+ // chunk has to fit THAT ring, which is the pre-fix rule and the A/B arm+ const int64_t k = slots_for(t);+ return k + 128 <= xcache.slots() && k * 100 <= kAutoLendPct * xcache.slots();+ });+ };+ int64_t c = scan(ring_max);+ if (c == 0 && ring_max < strata::prefill::Prefill::ring_default_slots()) c = scan(kRingMin);+ // a prompt that fits 0.1.39's chunk keeps 0.1.39's ring (one chunk: the smaller ring only slowed it)+ if (small >= c) { // the scan bought nothing: 0.1.39's choice+ strata::prefill::Prefill::set_ring_budget(0, 0);+ if (small > 0) { chunk = small; return slots_for(small); }+ return 0;+ }+ strata::prefill::Prefill::set_ring_budget((int) room_of(c), small);+ chunk = c;+ return slots_for(c);}for (int64_t c = chunk; c >= 256; c /= 2) {const int64_t k = slots_for(c);@@ -4892,6 +5816,287 @@ int main(int argc, char **argv) try {}return 0;};+ // ---- THE ELASTIC K/V (--kv-grow; vmm.hpp). Allocated for the whole --max-context up front, the K/V of a 262K+ // context (3.35 GiB with the drafter's at int8) takes VRAM the expert cache could hold more experts in. Now the K/V pools hold physical memory only for the cells+ // the requests reach. When a request needs more, slots just below the prompt path's loan give up their experts+ // (the CPU computes those from RAM, like any miss) and their whole chunks are mapped into the K/V; a later short+ // request hands them back and the slots are refilled with the profile's hottest experts. Neither side's+ // addresses move, so every captured graph stays valid. The context is never smaller: --max-context cells always+ // fit, the cache simply holds fewer experts while a long one is live.+ struct KvGrow {+ bool on = false;+ int64_t top = 0, lo = 0; // slots [lo, top) hold no expert; their whole chunks may be with the K/V+ int64_t floor = 128; // the cache keeps at least these slots+ int64_t step = 8192; // the K/V grows in whole steps of cells+ int64_t cells = 0; // what every K/V pool holds now+ std::vector<strata::core::VmmChunk> spare; // out of the cache, not (yet) in the K/V+ int64_t grows = 0, trims = 0, fresh = 0, evicted = 0, refilled = 0;+ } kvg;+ auto kvg_start = [&](int64_t top) {+ kvg.on = strata::core::qsa_kv_elastic() && xcache.vmm_range() != nullptr && d_res != nullptr &&+ !host_res.empty() && srcp != nullptr && top > kvg.floor;+ if (!kvg.on) return;+ kvg.top = kvg.lo = top;+ kvg.cells = strata::core::qsa_kv_elastic_cells();+ if (const char* v = std::getenv("STRATA_KV_GROW_STEP"); v != nullptr && std::atoll(v) > 0) kvg.step = std::atoll(v);+ // tests: the cache keeps this many slots (its size: the K/V grows into new VRAM only)+ if (const char* v = std::getenv("STRATA_KV_GROW_FLOOR"); v != nullptr && std::atoll(v) > 0) kvg.floor = std::atoll(v);+ std::fprintf(stderr, "strata generate: elastic K/V: %lld of %lld cells in VRAM (%.2f of %.2f GiB); the expert "+ "cache (%lld slots) gives the K/V room below slot %lld as the context grows\n",+ (long long) kvg.cells, (long long) o.max_context,+ (double) strata::core::qsa_kv_elastic_mapped_bytes() / 1073741824.0,+ (double) strata::core::qsa_kv_elastic_full_bytes() / 1073741824.0, (long long) xcache.slots(),+ (long long) top);+ };+ // Room for `cells` cells (rounded up to a step). `quiesce` must leave nothing running on the device and land+ // the adaptive tier's swaps (a swap in flight could still be writing a slot given up here).+ auto kvg_ensure = [&](int64_t cells, const std::function<void()>& quiesce) -> bool {+ if (!kvg.on || cells <= kvg.cells) return true;+ const int64_t target = std::min<int64_t>(o.max_context, (cells + kvg.step - 1) / kvg.step * kvg.step);+ const int64_t need = strata::core::qsa_kv_elastic_need(target);+ if (need == 0) { kvg.cells = strata::core::qsa_kv_elastic_cells(); return true; }+ quiesce();+ strata::core::VmmRange& r = *xcache.vmm_range();+ const uint64_t G = strata::core::vmm_granularity();+ std::vector<int32_t> owner; // slot -> residency index+ // The slots given up are the ones just below the prompt path's loan, and the loan is most of the cache: they+ // hold experts of middling heat. So an expert there that is hotter than the coldest one in the loan region+ // moves into that one's slot (a device copy), and the coldest is given up instead - the cache then holds what+ // a smaller cache would. Heat: the adaptive tier's routing counts, then the profile's rank.+ std::vector<int32_t> rank;+ std::vector<std::pair<float, int32_t>> cold; // the loan region's residents, hottest first+ auto heat = [&](int32_t i) -> float {+ const float u = drive.d.usage.empty() ? 0.0f : drive.d.usage[(size_t) i];+ return u * 1048576.0f - (float) rank[(size_t) i];+ };+ const auto& lay = strata::kernels::cpu::expert_layout();+ int64_t gave = 0, moved = 0;+ auto freeable = [&]() -> int64_t { // mapped chunks wholly inside [lo, top): a chunk a live slot shares stays+ const int64_t c0 = (int64_t) ((xcache.slot_offset(kvg.lo) + G - 1) / G);+ const int64_t c1 = (int64_t) (xcache.slot_offset(kvg.top) / G);+ int64_t k = 0;+ for (int64_t c = c0; c < c1; ++c) k += r.mapped(c) ? 1 : 0;+ return k;+ };+ while ((int64_t) kvg.spare.size() + freeable() < need && kvg.lo > kvg.floor) {+ if (owner.empty()) {+ owner.assign((size_t) xcache.slots(), -1);+ for (size_t i = 0; i < host_res.size(); ++i)+ if (host_res[i] >= 0 && host_res[i] < xcache.slots()) owner[(size_t) host_res[i]] = (int32_t) i;+ rank.assign(host_res.size(), (int32_t) profile.size());+ for (size_t r = 0; r < profile.size(); ++r)+ rank[(size_t) profile[r].first * (size_t) g.n_expert + (size_t) profile[r].second] = (int32_t) r;+ for (size_t i = 0; i < host_res.size(); ++i)+ if (host_res[i] >= kvg.top) cold.emplace_back(heat((int32_t) i), (int32_t) i);+ std::sort(cold.begin(), cold.end(), [](const auto& a, const auto& b) { return a.first > b.first; });+ }+ --kvg.lo;+ ++gave;+ if (const int32_t oi = owner[(size_t) kvg.lo]; oi >= 0) {+ const int64_t layer = oi / g.n_expert;+ int32_t vi = -1;+ if (!cold.empty() && cold.back().first < heat(oi)) {+ vi = cold.back().second;+ const int32_t vs = host_res[(size_t) vi];+ if (xcache.slot_offset(vs + 1) - xcache.slot_offset(vs) <+ lay.blob_bytes(layer) ||+ DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(+ xcache.device_slot(vs),+ xcache.device_slot((int32_t)kvg.lo),+ (size_t)lay.blob_bytes(layer)).wait()) != 0)+ vi = -1;+ else {+ cold.pop_back();+ host_res[(size_t) oi] = vs;+ host_res[(size_t) vi] = strata::core::kNotResident;+ ++moved;+ }+ }+ if (vi < 0) host_res[(size_t) oi] = strata::core::kNotResident;+ ++kvg.evicted;+ }+ }+ // a device-to-device cudaMemcpy does not wait for the copy: the moves still read the slots given up, and a+ // chunk unmapped under a copy faults it (the error then sticks to whatever runs next)+ if (gave > 0 &&+ DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()) != 0) {+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use+ error codes. Please replace the "get_error_string_dummy(...)" with a+ real error-handling function.+ */+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not+ use the error codes. The cudaGetLastError function call was replaced+ with 0. You need to rewrite this code.+ */+ std::fprintf(stderr,+ "strata: moving experts for the K/V failed: %s\n",+ dpct::get_error_string_dummy(0));+ return false;+ }+ {+ const int64_t c0 = (int64_t) ((xcache.slot_offset(kvg.lo) + G - 1) / G);+ const int64_t c1 = (int64_t) (xcache.slot_offset(kvg.top) / G);+ for (int64_t c = c0; c < c1; ++c)+ if (r.mapped(c))+ if (const strata::core::VmmChunk h = r.unmap(c)) kvg.spare.push_back(h);+ }+ if (gave > 0 &&+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable+ memory. If the memory is not pageable, call wait() on event return+ by memcpy API to ensure synchronization behavior.+ */+ DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(+ d_res, host_res.data(), host_res.size() * sizeof(int32_t)).wait()) !=+ 0) {+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use+ error codes. Please replace the "get_error_string_dummy(...)" with a+ real error-handling function.+ */+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not+ use the error codes. The cudaGetLastError function call was replaced+ with 0. You need to rewrite this code.+ */+ std::fprintf(stderr,+ "strata: the residency table upload failed: %s\n",+ dpct::get_error_string_dummy(0));+ return false;+ }+ int64_t fresh = 0;+ const bool ok = strata::core::qsa_kv_elastic_grow(target, [&]() -> strata::core::VmmChunk {+ if (kvg.spare.empty()) { ++fresh; return 0; } // the cache is at its floor: new memory+ const strata::core::VmmChunk h = kvg.spare.back();+ kvg.spare.pop_back();+ return h;+ });+ kvg.fresh += fresh;+ kvg.cells = strata::core::qsa_kv_elastic_cells();+ ++kvg.grows;+ std::fprintf(stderr, "strata: K/V grown to %lld cells (%.2f GiB); the expert cache gave %lld slots for it, "+ "%lld hotter experts moved to colder ones' slots (%lld of %lld slots hold experts)%s\n",+ (long long) kvg.cells, (double) strata::core::qsa_kv_elastic_mapped_bytes() / 1073741824.0,+ (long long) gave, (long long) moved, (long long) (kvg.lo + (xcache.slots() - kvg.top)),+ (long long) xcache.slots(),+ fresh > 0 ? " - and new VRAM, the cache being at its floor" : "");+ if (!ok)+ std::fprintf(+ stderr, "strata: the K/V could not grow to %lld cells (%s)\n",+ (long long)target,+ /*+ DPCT1009: SYCL reports errors using exceptions and does not+ use error codes. Please replace the+ "get_error_string_dummy(...)" with a real error-handling+ function.+ */+ /*+ DPCT1010: SYCL uses exceptions to report errors and does+ not use the error codes. The cudaGetLastError function call was+ replaced with 0. You need to rewrite this code.+ */+ dpct::get_error_string_dummy(0));+ return ok;+ };+ // A request that needs far fewer cells than the K/V holds gives the rest back: the slots refill with the+ // profile's hottest experts the GPU does not hold. Run on a quiet device (as kvg_ensure's `quiesce`).+ auto kvg_trim = [&](int64_t cells) -> bool {+ if (!kvg.on) return true;+ const int64_t target = std::max<int64_t>(kvg.step, (cells + kvg.step - 1) / kvg.step * kvg.step);+ if (kvg.cells < target + 2 * kvg.step || kvg.lo >= kvg.top) return true;+ strata::core::qsa_kv_elastic_shrink(target, [&](strata::core::VmmChunk h) { kvg.spare.push_back(h); });+ kvg.cells = strata::core::qsa_kv_elastic_cells();+ strata::core::VmmRange& r = *xcache.vmm_range();+ const uint64_t G = strata::core::vmm_granularity();+ const int64_t c1 = (int64_t) (xcache.slot_offset(kvg.top) / G);+ { // one run from the lowest unmapped chunk, as long as the chunks handed back last (one access call)+ const int64_t c0 = (int64_t) (xcache.slot_offset(kvg.lo) / G);+ int64_t cend = c0, need = (int64_t) kvg.spare.size();+ while (cend < c1 && need > 0) need -= r.mapped(cend++) ? 0 : 1;+ if (!r.map_range(c0, cend, [&]() -> strata::core::VmmChunk {+ if (kvg.spare.empty()) return 0;+ const strata::core::VmmChunk h = kvg.spare.back();+ kvg.spare.pop_back();+ return h;+ }))+ std::fprintf(stderr, "strata: the expert cache could not take its VRAM back from the K/V\n");+ }+ const int64_t lo0 = kvg.lo;+ while (kvg.lo < kvg.top) { // a slot whose chunks are all mapped again holds an expert again+ const int64_t a = (int64_t) (xcache.slot_offset(kvg.lo) / G);+ const int64_t b = (int64_t) ((xcache.slot_offset(kvg.lo + 1) + G - 1) / G);+ bool all = true;+ for (int64_t c = a; c < b && all; ++c) all = r.mapped(c);+ if (!all) break;+ ++kvg.lo;+ }+ // the refills on one stream and one sync (a blocking copy each was a driver round trip per expert)+ const auto& lay = strata::kernels::cpu::expert_layout();+ std::vector<std::pair<size_t, int32_t>> filled; // (residency index, slot), resident once the copies landed+ size_t pi = 0;+ for (int64_t s = lo0; s < kvg.lo; ++s) {+ const uint64_t room = xcache.slot_offset(s + 1) - xcache.slot_offset(s);+ for (; pi < profile.size(); ++pi) {+ const int32_t l = profile[pi].first, e = profile[pi].second;+ const size_t i = (size_t) l * (size_t) g.n_expert + (size_t) e;+ if (host_res[i] >= 0 || lay.blob_bytes(l) > room) continue;+ const uint8_t* b = srcp->blob(l, e);+ if (b == nullptr) continue;+ /*+ DPCT1124: cudaMemcpyAsync is migrated to asynchronous+ memcpy API. While the origin API might be synchronous, it+ depends on the type of operand memory, so you may need to call+ wait() on event return by memcpy API to ensure synchronization+ behavior.+ */+ dpct::get_in_order_queue().memcpy(+ xcache.device_slot((int32_t)s), b,+ (size_t)lay.blob_bytes(l)).wait();+ filled.emplace_back(i, (int32_t) s);+ ++pi;+ break;+ }+ }+ if (DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()) != 0) {+ /*+ DPCT1009: SYCL reports errors using exceptions and does not use+ error codes. Please replace the "get_error_string_dummy(...)" with a+ real error-handling function.+ */+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not+ use the error codes. The cudaGetLastError function call was replaced+ with 0. You need to rewrite this code.+ */+ std::fprintf(stderr,+ "strata: refilling the expert cache failed: %s\n",+ dpct::get_error_string_dummy(0));+ return false;+ }+ for (const auto& [i, s] : filled) host_res[i] = s;+ kvg.refilled += (int64_t) filled.size();+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable memory.+ If the memory is not pageable, call wait() on event return by memcpy API+ to ensure synchronization behavior.+ */+ if (DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(+ d_res, host_res.data(), host_res.size() * sizeof(int32_t)).wait()) !=+ 0)+ return false;+ for (const strata::core::VmmChunk h : kvg.spare) strata::core::vmm_chunk_free(h); // new ones, if any+ kvg.spare.clear();+ ++kvg.trims;+ std::fprintf(stderr, "strata: K/V trimmed to %lld cells; %lld slots back to the expert cache, refilled from "+ "the profile\n", (long long) kvg.cells, (long long) (kvg.lo - lo0));+ return true;+ };// ---- the resident RAM mode (--resident-experts / --resident-cpu-experts): the experts the GPU cache does not// hold are copied from experts.bin into RAM once, so no decode or prompt step reads the file (the plain mmap// mode reads them through the OS file cache, which a small-RAM PC keeps giving back to the SSD). Built here,@@ -4899,6 +6104,26 @@ int main(int argc, char **argv) try {// streamed during a prompt and copied back after it, so those are kept in RAM too as far as RAM allows. The// bytes are the file's bytes and the placement is the same, so the answers are the plain mmap mode's; the// share-of-pinned figure above (which sizes the prompt path) is left as the mmap mode's for the same reason.+ // --adapt-async (opt-in): where the asynchronous adaptive tier does not apply, the blocking tier runs, said once.+ // It exchanges experts between the GPU caches and the resident RAM copy only (the copy is checked once it is+ // built, below). Not beside the --batch slots (their windows run between a request's prompt chunks), a peer+ // tier or the helper GPUs' tier, which pick their swaps from the same table. (A pipelined decode loop that+ // adapts beside windows in flight needs the blocking tier too: such a mode belongs on this list.)+ auto adapt_async_off = [&](const char* why) {+ std::fprintf(stderr, "strata generate: --adapt-async 1 is off (%s): the blocking adaptive tier\n", why);+ o.adapt_async = 0;+ };+ if (o.adapt_async) {+ const char* why = !o.serve ? "it needs --serve"+ : o.adapt_every <= 0 || o.adapt_swaps <= 0 ? "the adaptive tier is off"+ : !o.resident_cpu_experts ? "it needs the resident RAM mode, --resident-experts"+ : o.batch > 0 ? "not with --batch slots"+ : o.pipeline_windows > 0 ? "not with --pipeline-windows (its windows are in flight while the tier adapts)"+ : peer.valid() ? "not with --peer-device"+ : remote_opt ? "not with --remote-expert-opt"+ : nullptr;+ if (why != nullptr) adapt_async_off(why);+ }if (o.resident_cpu_experts) {int64_t lend_from = -1;if (o.prefill_chunk > 0 && !o.no_prefill_borrow && d_res != nullptr && xcache.slots() > 0) {@@ -4906,16 +6131,24 @@ int main(int argc, char **argv) try {const int64_t k = plan_lend(chunk);if (k > 0) lend_from = xcache.slots() - k;}- bool resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, {}, lend_from, o.resident_headroom,- o.resident_budget, &profile);+ // a layer split: the experts every later stage's cache holds are left out of the RAM copy, as CUDA0's are+ // (with them the copy keeps no lend region: pin_cache_complement turns the loan off)+ std::vector<std::pair<int32_t, int32_t>> stage_pairs;+ for (auto& st : stages)+ for (int64_t l = st->lb; l < st->le; ++l)+ for (int64_t e = 0; e < g.n_expert; ++e)+ if (st->cache.slot_of(l, e) >= 0) stage_pairs.emplace_back((int32_t) l, (int32_t) e);+ const std::vector<std::pair<int32_t, int32_t>>& rank_all = profile_all.empty() ? profile : profile_all;+ bool resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, stage_pairs, lend_from,+ o.resident_headroom, o.resident_budget, &rank_all);std::string whole_err;if (!resident_ok && o.resident_soft) {// #467: the whole complement does not fit - keep what does, the hottest by the profile, through the #403- // budget path (sized by the RAM alone) instead of none: the misses outside it read the same file bytes+ // budget path (sized by available memory) instead of none: the misses outside it read the same file bytes// the mmap fallback reads, so the answers are unchanged. Nothing pinned: the old fallback below.whole_err = err;- resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, {}, -1, o.resident_headroom,- strata::core::FileExpertSource::kResidentWhatFits, &profile);+ resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, stage_pairs, -1, o.resident_headroom,+ strata::core::FileExpertSource::kResidentWhatFits, &rank_all);if (resident_ok)std::fprintf(stderr, "strata generate: WARNING: the whole resident RAM mode does not fit (%s); %.2f ""GiB of the experts the GPU does not hold, the hottest by the expert profile, are "@@ -4926,6 +6159,14 @@ int main(int argc, char **argv) try {err = whole_err + "; " + err;}if (resident_ok) {+ // --adapt-async: twice the exchange buffers - the second half bounces the copies in whose source is not+ // page-locked (an asynchronous copy instead of the driver's staged, synchronous one)+ if (o.adapt_async && !src.reserve_exchanges(2 * std::min<int64_t>(o.adapt_swaps, 96), err))+ adapt_async_off(err.c_str());+ // pageable buffers would make every copy of a round synchronous (the driver stages them): that is the+ // blocking tier's cost, so the asynchronous tier is not worth running - said, and the blocking tier stays+ if (o.adapt_async && !src.exchange_pinned())+ adapt_async_off("the exchange buffers could not be page-locked");if (o.adapt_every > 0 && o.adapt_swaps > 0 &&!src.reserve_exchanges(std::min<int64_t>(o.adapt_swaps, 96), err)) {std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str());@@ -4946,17 +6187,18 @@ int main(int argc, char **argv) try {// #403: a RAM budget that cannot be kept is not a reason to stop - the experts it would have held are// read from the files like the ones outside it (pin_cache_complement leaves nothing half-built)std::fprintf(stderr, "strata generate: WARNING: the RAM budget (--resident-budget-gib) cannot be kept (%s); "- "every expert the GPU does not hold is read from the model files through the OS file "- "cache (--mmap-experts), which is slower\n", err.c_str());+ "every expert the GPU does not hold is read from the model files %s "+ "(--mmap-experts), which is slower\n", err.c_str(),+ src.unbuffered() ? "with unbuffered I/O" : "through the OS file cache");} else {std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str());return 1;}// #577: the unbuffered choice above was made before the RAM copy existed, from the budget asked for; now the// copy is built, decide again from the RAM it really holds and the expert bytes outside it (on a 96 GB PC- // the file cache keeps those, and every refill after a prompt read the drive instead). Windows only: the- // unbuffered reads exist there alone-#if defined(_WIN32)+ // the file cache keeps those, and every refill after a prompt read the drive instead). Windows and Linux: the+ // unbuffered reads exist there+#if defined(_WIN32) || defined(__linux__)if (o.mmap_experts && o.resident_budget > 0) {std::string why;const bool was = src.unbuffered();@@ -4966,13 +6208,20 @@ int main(int argc, char **argv) try {}#endif}+ if (o.adapt_async && !src.complement_ready()) adapt_async_off("the resident RAM mode is not running");if (o.serve) {- if (o.spec < 2 || o.mtp.empty() || o.prefill_chunk <= 0 ||+ if (o.spec < 2 || o.prefill_chunk <= 0 ||(graph_hits && (thits.d_res == nullptr || host_res.empty()))) {- std::fprintf(stderr, "strata serve: needs --spec T, --mtp DIR and --prefill CHUNK (and a fillable "+ std::fprintf(stderr, "strata serve: needs --spec T and --prefill CHUNK (and a fillable ""--expert-cache; the graphed hit path additionally needs --expert-profile P)\n");return 2;}+ // STRATA_VOLTA_BUILD backport (see docs/ and ninfer-flash-next-v100-backport): --mtp is optional here,+ // mirroring the plain `generate` command's own use_mtp handling below. Without it, drafting falls back+ // to the suffix/prompt-lookup drafter (DraftPolicy still picks Lookup vs plain per round) or, when+ // neither fires, plain one-token-per-round decoding - slower, never wrong: the verify window still+ // confirms every emitted token against the real model regardless of where the draft came from.+ const bool use_mtp = !o.mtp.empty();strata::prefill::Prefill sp;void* borrow = nullptr;uint64_t borrow_bytes = 0;@@ -4998,9 +6247,9 @@ int main(int argc, char **argv) try {int64_t lent_chunk = 0;std::vector<std::pair<int32_t, int32_t>> lent;};- auto part_slots = [&](const PfPart& p, int64_t c) -> int64_t {- const uint64_t need = strata::prefill::Prefill::bytes_needed(g, *p.ses, c);- strata::core::ExpertCache& xc = *p.cache;+ // bytes -> slots for one cache: exact when it knows its per-slot offsets (a native pack's blobs differ+ // per layer), otherwise max_blob each.+ auto cache_slots_for = [&](const strata::core::ExpertCache& xc, uint64_t need) -> int64_t {if (xc.slot_offsets() != nullptr) { // sized slots: from the end until they hold `need`int64_t k = 0;while (k < xc.slots() &&@@ -5010,6 +6259,9 @@ int main(int argc, char **argv) try {const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;return (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob);};+ auto part_slots = [&](const PfPart& p, int64_t c) -> int64_t {+ return cache_slots_for(*p.cache, strata::prefill::Prefill::bytes_needed(g, *p.ses, c));+ };auto part_bytes = [&](const PfPart& p, int32_t first) -> uint64_t {strata::core::ExpertCache& xc = *p.cache;return xc.slot_offsets() ? (uint64_t) (xc.bytes() - (int64_t) xc.slot_offsets()[first])@@ -5056,68 +6308,133 @@ int main(int argc, char **argv) try {if (!fits_one(p, c, cap)) return false;return true;};- static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256};- auto pick = [&](const PfPart* only) -> int64_t {- if (o.prefill_auto) {- for (const int64_t c : kAutoChunks) {- if (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue; // #282, as plan_lend- if (fits(c, true, only)) return c;- }- } else {+ // The chunk and the ring are one budget. The ring used to be a fixed 384 slots taken off the top+ // before the chunk was considered: 506 MiB on a Q2_0 pack, where it was tuned, but 1,912 MiB on+ // Q8_0, more than half an 8 GB card's cache - which is what kept that card at a 1024-token chunk.+ // Size the chunk first and hand the ring what the smallest participant leaves over, up to the ring's+ // byte budget - but hand it ALL of it, as in plan_lend: the ring is the better buy per byte (the+ // measurements are there), so the chunk to take is the largest one that still leaves the ring full,+ // not the largest one that leaves it anything at all. kRingMin is the fallback floor for a rig where+ // no chunk can afford a full ring; ring_slots() returns STAGE at or below it, which turns streaming+ // off.+ constexpr int64_t kRingMin = 16;+ // The room is a BYTE budget, as in plan_lend: a ring slot is max_blob bytes, but a cache slot holds+ // its own layer's blob, which on this rig averages 0.85 of it. In slots the ring looked 18% cheaper+ // than it is, and a chunk whose ring only fitted after that discount was refused outright - the scan+ // stopped one step short while the chunk it did take had room to spare for the cap-sized ring.+ const int64_t kBlob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;+ auto ring_room = [&](int64_t c, const PfPart* only, int64_t cap) -> int64_t {+ int64_t room = cap;+ for (const PfPart& p : pf_parts) {+ if (only != nullptr && &p != only) continue;+ // clamped at 0: a cache under 128 slots has a negative lend budget, and `slots - budget` is+ // then `slots`, which is off_[slots] - the end of the prefix sum, so that cache lends 0 bytes+ // rather than reading one entry past its offsets+ const int64_t budget = std::max<int64_t>(0, std::min(p.cache->slots() - 128,+ kAutoLendPct * p.cache->slots() / 100));+ const uint64_t avail = part_bytes(p, (int32_t) (p.cache->slots() - budget));+ const uint64_t nonring = strata::prefill::Prefill::bytes_needed_no_ring(g, *p.ses, c);+ room = std::min(room, (int64_t) ((avail - std::min(avail, nonring)) / (uint64_t) kBlob));+ }+ return room;+ };+ // The largest chunk on the 256-token grid that `only` - or, with null, every stage - can lend with the+ // ring still at its full byte budget (ring_room is capped at ring_max, so that is room == ring_max),+ // under the operator's ceiling (auto_ceiling keeps a bare `auto` at 8192, #282). Failing that, the+ // largest chunk whose ring clears kRingMin.+ // 0.1.39's list with its ring: the chunk it would pick, and the size up to which a prompt keeps that ring+ auto old_pick = [&](const PfPart* only) -> int64_t {+ strata::prefill::Prefill::set_ring_budget(0, 0);+ static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256};+ for (const int64_t c : kAutoChunks) {+ if (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue; // #282, as plan_lend+ if (fits(c, true, only)) return c;+ }+ return 0;+ };+ auto scan = [&](const PfPart* only) -> int64_t {+ if (!o.prefill_auto) { // an explicit --prefill is the operator's number, and a loan of it only has to fitfor (int64_t c = o.prefill_chunk; c >= 256; c /= 2)if (fits(c, false, only)) return c;+ return 0;}- return 0;+ if (!strata::prefill::Prefill::ring_bytes_enabled()) return old_pick(only); // STRATA_RING_BYTES=0+ const int64_t small = old_pick(only);+ const int64_t cap = strata::prefill::Prefill::ring_cap_for(small);+ auto probe = [&](int64_t floor) -> int64_t {+ return biggest_chunk(auto_ceiling, [&](int64_t t) -> bool {+ const int64_t room = ring_room(t, only, cap);+ if (room < floor) return false;+ strata::prefill::Prefill::set_ring_budget((int) room, 0);+ // ring_slots() now returns `room` - unless STRATA_PREFILL_RING overrides it, in which+ // case the chunk has to fit THAT ring, which is the pre-fix rule and the A/B arm+ return fits(t, true, only);+ });+ };+ int64_t c = probe(cap);+ if (c == 0 && cap < strata::prefill::Prefill::ring_default_slots()) c = probe(kRingMin);+ return std::max(c, small); // never a smaller chunk than 0.1.39's};- const int64_t chunk = pick(nullptr);+ const int64_t chunk = scan(nullptr);// #448: a small card in a layer split caps every stage's chunk (an RTX 3080's 512-slot cache held a// 32 GB card's split to 512 tokens: prompts 6.2x slower, decode the same). Named when it bites, so the// regression is one log line: each stage that cannot fund the chunk CUDA0 alone would read in.- if (pf_parts.size() > 1) {- const int64_t alone = pick(&pf_parts[0]);- if (alone > chunk) {- for (size_t i = 1; i < pf_parts.size(); ++i) {- const PfPart& p = pf_parts[i];- if (fits_one(p, alone, o.prefill_auto)) continue;- const int dev = p.dev < 0 ? 0 : p.dev;- dpct::device_info prop{};- if (DPCT_CHECK_ERROR(- dpct::get_device(dev).get_device_info(prop)) !=- 0) {- /*- DPCT1010: SYCL uses exceptions to report errors- and does not use the error codes. The- cudaGetLastError function call was replaced with 0.- You need to rewrite this code.- */- (void)0;- prop.get_name()[0] = 0;- }- const std::string pct =- o.prefill_auto ? ", and lend at most " + std::to_string(kAutoLendPct) + "%" : "";- std::fprintf(- stderr,- "strata serve: WARNING: prompt chunk %lld tokens, "- "not %lld: CUDA%d (%s) "- "has %lld expert-cache slots, and a %lld-token "- "chunk borrows %lld of them "- "(it must keep 128%s) - prompts read slower than "- "on CUDA0 alone (#448)\n",- (long long)chunk, (long long)alone, dev,- prop.get_name(), (long long)p.cache->slots(),- (long long)alone, (long long)part_slots(p, alone),- pct.c_str());- // the helper tiers start at CUDA1 without a split (and are enabled in order)- std::fprintf(stderr, "strata serve: a card this small can serve as a helper expert cache "- "instead of a split stage: without --layer-split, with %s "- "(docs/SECOND_GPU.md)\n",- dev == 1 ? "--expert-cache-device1 N" : "--expert-cache-device1..3 N, in order");+ const int64_t alone = pf_parts.size() > 1 ? scan(&pf_parts[0]) : chunk;+ // both scans left the ring override on their own last trial: put it back on the chunk that won, which+ // is what `init` lays out and what the INFO line reports+ if (chunk > 0 && o.prefill_auto && strata::prefill::Prefill::ring_bytes_enabled()) {+ // a prompt that fits 0.1.39's chunk keeps 0.1.39's ring (one chunk: the smaller ring only slowed+ // it); the byte-budget ring is for the chunks past it+ const int64_t small = old_pick(nullptr);+ strata::prefill::Prefill::set_ring_budget(+ small >= chunk ? 0 : (int) ring_room(chunk, nullptr, strata::prefill::Prefill::ring_cap_for(small)),+ small);+ }+ if (chunk > 0 && alone > chunk) {+ for (size_t i = 1; i < pf_parts.size(); ++i) {+ const PfPart& p = pf_parts[i];+ if (fits_one(p, alone, o.prefill_auto)) continue;+ const int dev = p.dev < 0 ? 0 : p.dev;+ dpct::device_info prop{};+ if (DPCT_CHECK_ERROR(+ dpct::get_device(dev).get_device_info(prop)) != 0) {+ /*+ DPCT1010: SYCL uses exceptions to report errors and+ does not use the error codes. The cudaGetLastError+ function call was replaced with 0. You need to rewrite+ this code.+ */+ (void)0;+ prop.get_name()[0] = 0;}+ const std::string pct =+ o.prefill_auto ? ", and lend at most " + std::to_string(kAutoLendPct) + "%" : "";+ std::fprintf(stderr,+ "strata serve: WARNING: prompt chunk %lld "+ "tokens, not %lld: CUDA%d (%s) "+ "has %lld expert-cache slots, and a "+ "%lld-token chunk borrows %lld of them "+ "(it must keep 128%s) - prompts read slower "+ "than on CUDA0 alone (#448)\n",+ (long long)chunk, (long long)alone, dev,+ prop.get_name(), (long long)p.cache->slots(),+ (long long)alone,+ (long long)part_slots(p, alone), pct.c_str());+ // the helper tiers start at CUDA1 without a split (and are enabled in order)+ std::fprintf(stderr, "strata serve: a card this small can serve as a helper expert cache "+ "instead of a split stage: without --layer-split, with %s "+ "(docs/SECOND_GPU.md)\n",+ dev == 1 ? "--expert-cache-device1 N" : "--expert-cache-device1..3 N, in order");}}if (chunk > 0) {if (o.prefill_auto)- std::fprintf(stderr, "strata serve: prompt chunk auto: %lld tokens\n", (long long) chunk);+ // the RESOLVED ring, not the room offered: ring_slots() clamps to [16, RING_MAX] and a chunk+ // under stream_all_min() gets STAGE, and STRATA_PREFILL_RING overrides both. This is what+ // `init` lays out, and what the INFO line reports to the Monitor tab.+ std::fprintf(stderr, "strata serve: prompt chunk auto: %lld tokens, a %lld-slot ring\n",+ (long long) chunk,+ (long long) strata::prefill::Prefill::ring_slots_for(chunk));else if (chunk != o.prefill_chunk)std::fprintf(stderr, "strata serve: prompt chunk %lld -> %lld tokens so its buffers fit in ""every expert cache\n", (long long) o.prefill_chunk, (long long) chunk);@@ -5339,6 +6656,19 @@ int main(int argc, char **argv) try {err.clear();}}+ // a layer split: a one-chunk prompt runs the stages one after the other, so each stage's prompt path gets the+ // next stage's GPU (the last one the first's) to stream and compute a share of its experts meanwhile+ if (multi_gpu && !stages.empty()) {+ std::vector<std::pair<strata::prefill::Prefill*, int>> paths{{&sp, 0}};+ for (const auto& st : stages) paths.emplace_back(&st->sp, st->dev);+ for (size_t i = 0; i < paths.size(); ++i) {+ const strata::core::OnDevice on(paths[i].second);+ if (!paths[i].first->set_stage_helper(paths[(i + 1) % paths.size()].first, err)) {+ std::fprintf(stderr, "strata serve: %s - stage %zu reads its prompts alone\n", err.c_str(), i);+ err.clear();+ }+ }+ }mem_mark("the head and the prompt path");// #340: STRATA_SPLIT_SMALL_OWN=S (tokens): on a layer split, every stage that borrows keeps the slots for an// S-token chunk's buffers for the whole session (0.1.29's own buffers, carved from the tail of its cache):@@ -5370,25 +6700,14 @@ int main(int argc, char **argv) try {}if (evicted > 0) {if (d_res != nullptr)- /*- DPCT1114: cudaMemcpy is migrated to asynchronization- memcpy, assuming in the original code the source host memory- is pageable memory. If the memory is not pageable, call- wait() on event return by memcpy API to ensure- synchronization behavior.- */- dpct::get_in_order_queue().memcpy(d_res, host_res.data(),- host_res.size() *- sizeof(int32_t)).wait();+ res_put(d_res);for (auto& st : stages) {const strata::core::OnDevice on(st->dev);- dpct::get_in_order_queue()- .memcpy(st->d_res, host_res.data(),- host_res.size() * sizeof(int32_t))- .wait();+ res_put(st->d_res);}}}+ kvg_start(borrow != nullptr ? (int64_t) lend_first : xcache.slots());// the penalty-history buffer: one row per verify-window row (`penalty_rows`), each the last// `penalty_last_n` tokens that row's pick follows, -1 padded in front. Allocated once at the cap for// the widest window; a request without penalties gets a null buffer and takes the byte-for-byte@@ -5409,6 +6728,7 @@ int main(int argc, char **argv) try {strata::core::VerifyHits vh;vh.d_res = thits.d_res;if (mirror_table_d) strata::kernels::resident_plan_set_mirror(thits.d_res, mirror_table_d);+ vh.h_res = host_res.empty() ? nullptr : host_res.data();vh.cache_base = thits.cache_base;vh.blob = thits.blob;vh.slot_off = xcache.slot_offsets(); // E-6: the device plan's pointers@@ -5423,6 +6743,45 @@ int main(int argc, char **argv) try {};auto pcie_num_of = [](double f) { return std::max(0, std::min(256, (int) (f * 256.0 + 0.5))); };const int n_stages = split_devs.empty() ? 1 : (int) split_at.size() + 1;+ // --pipeline-windows (decided where the split was): two verifiers per stage, one for the even windows and one+ // for the odd ones, sharing one stream of their card, and a hand-off per parity - so stage 0 can run window+ // K+1 while stage 1 still reads window K's hand-off+ const bool pipe = o.pipeline_windows > 0 && n_stages == 2 && !split_same && stages.size() == 1;+ strata::core::Verifier ver_b;+ SplitDrive split_drive_b;+ dpct::queue_ptr pl_stream[2] = {&dpct::get_in_order_queue(),+ &dpct::get_in_order_queue()};+ if (pipe) {+ /*+ DPCT1025: The SYCL queue is created ignoring the flag and+ priority options.+ */+ bool ok_p =+ DPCT_CHECK_ERROR(+ pl_stream[0] =+ dpct::get_current_device().create_queue(true)) == 0;+ {+ const strata::core::OnDevice on(stages[0]->dev);+ /*+ DPCT1025: The SYCL queue is created ignoring the flag and+ priority options.+ */+ ok_p =+ ok_p &&+ DPCT_CHECK_ERROR(+ pl_stream[1] =+ dpct::get_current_device().create_queue(true)) == 0;+ }+ if (!ok_p) { std::fprintf(stderr, "strata serve: --pipeline-windows: stream creation failed\n"); return 1; }+ for (strata::core::Verifier* v : {&ver, &ver_b}) {+ v->set_stream(pl_stream[0]);+ v->set_always_publish(true);+ }+ for (strata::core::Verifier* v : {&stages[0]->ver, &stages[0]->ver_b}) {+ v->set_stream(pl_stream[1]);+ v->set_always_publish(true);+ }+ }if (n_stages > 1) {const size_t hb = (size_t) strata::kernels::kVerifyMaxT *(size_t) strata::core::Verifier::handoff_floats(g) * sizeof(float);@@ -5461,17 +6820,19 @@ int main(int argc, char **argv) try {for (int st = 1; st < n_stages; ++st) {bool ok_s = false;if (split_same) {- ok_s = ver_same.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err);+ ok_s = ver_same.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, std::max(o.spec, o.batch), err);} else {GpuStage& gs = *stages[(size_t) st - 1];const strata::core::OnDevice on(gs.dev);strata::core::VerifyHits vs;vs.d_res = gs.d_res;+ vs.h_res = host_res.empty() ? nullptr : host_res.data();vs.cache_base = gs.cache.device_slot(0);vs.blob = thits.blob;vs.slot_off = gs.cache.slot_offsets();vs.n_slots = gs.cache.slots();- ok_s = gs.ver.init(gs.wt, g, gs.ss, vs, gs.head.loaded() ? &gs.head : nullptr, o.spec, err);+ gs.ver.set_remote_expert_opt(remote_opt.get());+ ok_s = gs.ver.init(gs.wt, g, gs.ss, vs, gs.head.loaded() ? &gs.head : nullptr, std::max(o.spec, o.batch), err);split_drive.cache_base[st] = gs.cache.device_slot(0);split_drive.cache_slot_off[st] = gs.cache.slot_offsets();split_drive.pcie_num[st] = pcie_num_of(gs.pcie_frac);@@ -5488,11 +6849,115 @@ int main(int argc, char **argv) try {" (CUDA" + std::to_string(split_same ? 0 : stages[(size_t) st - 1]->dev) + ")";std::fprintf(stderr, "strata serve: layer split: layers %s, one hand-off per window\n", plan_s.c_str());}- if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err) ||- !mtp.bind(last_st ? last_st->wt : wt, last_st ? &last_st->head : &native_head, ver.final_R_all(), err)) {+ // --pipeline-windows: the odd windows' verifiers and their hand-off (initialized before `ver`, which stays the+ // watchdog's verifier), and the drafter's own row buffer, which either parity's rows are copied into+ float* pl_mtp_R = nullptr;+ if (pipe) {+ const size_t hb = (size_t) strata::kernels::kVerifyMaxT *+ (size_t) strata::core::Verifier::handoff_floats(g) * sizeof(float);+ float *hh = nullptr, *hand_b = nullptr;+ /*+ DPCT1048: The original value cudaHostAllocMapped is not+ meaningful in the migrated code and was removed or replaced with 0.+ You may need to check the migrated code.+ */+ /*+ DPCT1048: The original value cudaHostAllocPortable is not+ meaningful in the migrated code and was removed or replaced with 0.+ You may need to check the migrated code.+ */+ if (DPCT_CHECK_ERROR(hh = (float *)sycl::malloc_host(+ hb, dpct::get_in_order_queue())) != 0 ||+ DPCT_CHECK_ERROR(*(void **)&hand_b = (float *)hh) != 0) {+ std::fprintf(stderr, "strata serve: --pipeline-windows: the second hand-off allocation failed\n");+ return 1;+ }+ std::memset(hh, 0, hb);+ GpuStage& gs = *stages[0];+ ver_b.set_stage(0, split_at[0], nullptr, hand_b);+ gs.ver_b.set_stage(split_at[0], -1, hand_b, nullptr);+ {+ const strata::core::OnDevice on(gs.dev);+ strata::core::VerifyHits vs;+ vs.d_res = gs.d_res;+ vs.h_res = host_res.empty() ? nullptr : host_res.data();+ vs.cache_base = gs.cache.device_slot(0);+ vs.blob = thits.blob;+ vs.slot_off = gs.cache.slot_offsets();+ vs.n_slots = gs.cache.slots();+ if (!gs.ver_b.init(gs.wt, g, gs.ss, vs, gs.head.loaded() ? &gs.head : nullptr, o.spec, err)) {+ std::fprintf(stderr, "strata serve: --pipeline-windows: the second verifier on CUDA%d (the later "+ "card): %s (raise --vram-reserve-mib by ~200, or --pipeline-windows 0)\n",+ gs.dev, err.c_str());+ return 1;+ }+ if (DPCT_CHECK_ERROR(pl_mtp_R = sycl::malloc_device<float>(+ (size_t)strata::kernels::kVerifyMaxT *+ (size_t)(g.hc * g.n_embd),+ dpct::get_in_order_queue())) != 0) {+ std::fprintf(stderr, "strata serve: --pipeline-windows: the drafter's row buffer does not fit\n");+ return 1;+ }+ }+ if (!ver_b.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err)) {+ std::fprintf(stderr, "strata serve: --pipeline-windows: the second verifier on CUDA0 (the first card): "+ "%s (raise --vram-reserve-mib by ~200, or --pipeline-windows 0)\n", err.c_str());+ return 1;+ }+ ver_b.set_next(&gs.ver_b, &split_drive_b); // the setters reach it; the pipeline never chains run/commit+ }+ ver.set_remote_expert_opt(remote_opt.get());+ if (batch_mtp) ver.set_batch_graph_limit(64); // --batch-mtp only: slot rotation makes many layouts (LRU); 0.1.39 keeps all+ if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr,+ batch_mtp ? strata::kernels::kVerifyMaxT : std::max(o.spec, o.batch), err) ||+ (use_mtp && !mtp.bind(last_st ? last_st->wt : wt, last_st ? &last_st->head : &native_head,+ pipe ? pl_mtp_R : ver.final_R_all(), err))) {std::fprintf(stderr, "strata serve: %s\n", err.c_str());return 1;}+ if (pipe) mtp.set_source_R(ver.final_R_all()); // the serial decode's rows (the last stage's even verifier)+ auto free_slot_mtp_rows = [](float *p) {+ try {+ if (p != nullptr) (void) DPCT_CHECK_ERROR(sycl::free(p, dpct::get_in_order_queue())); }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ std::vector<std::unique_ptr<float, decltype(free_slot_mtp_rows)>> slot_mtp_rows;+ if (batch_mtp) {+ for (int b = 0; b < o.batch; ++b) {+ float* r = nullptr;+ const size_t bytes = (size_t) o.spec * (size_t) g.hc * (size_t) g.n_embd * sizeof(float);+ if (DPCT_CHECK_ERROR(r = (float *)sycl::malloc_device(+ bytes, dpct::get_in_order_queue())) !=+ 0) {+ std::fprintf(stderr, "strata serve: batch MTP slot %d residual buffer does not fit%s\n",+ b, vram_free_note().c_str());+ return 1;+ }+ slot_mtp_rows.emplace_back(r, free_slot_mtp_rows);+ if (!slot_mtp[(size_t) b]->bind(wt, &native_head, r, err, &mtp)) {+ std::fprintf(stderr, "strata serve: batch MTP slot %d: %s%s\n", b, err.c_str(),+ vram_free_note().c_str());+ return 1;+ }+ }+ }+ // each stage's verifier gets its stage's slot sessions+ if (o.batch > 0) {+ for (size_t k = 0; k < bslot_ss.size(); ++k) {+ std::vector<strata::core::SessionState*> ptrs;+ for (auto& u : bslot_ss[k]) ptrs.push_back(u.get());+ strata::core::Verifier& vk = k == 0 ? ver : stages[k - 1]->ver;+ const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev);+ if (!vk.init_slots(ptrs, err)) {+ std::fprintf(stderr, "strata serve: --batch, stage %zu: %s\n", k + 1, err.c_str());+ return 1;+ }+ }+ }for (int st = 0; st < n_stages && n_stages > 1; ++st) {split_drive.plan[st] = stage_ver(st).plan_sink();if (st > 0) {@@ -5500,6 +6965,15 @@ int main(int argc, char **argv) try {stage_ver(st).set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2);}}+ if (pipe) { // the odd windows' pool routing: the same as the even ones', with their plans+ split_drive_b = split_drive;+ split_drive_b.plan[0] = ver_b.plan_sink();+ split_drive_b.plan[1] = stages[0]->ver_b.plan_sink();+ stages[0]->ver_b.set_split(o.spec_split);+ stages[0]->ver_b.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2);+ ver_b.set_split(o.spec_split);+ ver_b.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2);+ }// the pool the verify windows call: with a layer split, the wrapper that routes each layer to its stageconst strata::core::PoolMultiFn win_pool_fn = n_stages > 1 ? &drive_pool_split : &drive_pool_multi;void* const win_pool_user = n_stages > 1 ? (void*) &split_drive : (void*) &drive;@@ -5510,6 +6984,124 @@ int main(int argc, char **argv) try {// issue #31's thread dumps show the host stuck in that cudaMemcpyAsync on a driver lock for good. The copy// kernel needs no host CUDA call there, and costs ~1-3% decode on IQ3_S (45.3 -> 44.8 tok/s, 8 requests).ver.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2);+ // --pipeline-windows 2: stage 0's GDN state before a speculative commit, restored when the guess was wrong.+ // Window W reads the state its snapshot must hold and no window writes it (only commits do), so it is copied+ // on a side stream while W runs, into the buffer of W's parity, and only W's speculative commit waits for it+ // (STRATA_PIPELINE_SNAP_OVERLAP=0: one buffer, copied on the critical path).+ const size_t pl_snap_bytes = pipe ? gdn_snapshot_bytes(ss) : 0;+ float* pl_snap2[2] = {nullptr, nullptr};+ dpct::queue_ptr pl_snap_stream = &dpct::get_in_order_queue();+ dpct::event_ptr pl_snap_pre[2] = {nullptr, nullptr},+ pl_snap_ev[2] = {nullptr, nullptr};+ bool pl_snap_overlap = false;+ if (pipe && o.pipeline_windows >= 2) {+ if (DPCT_CHECK_ERROR(+ pl_snap2[0] = (float *)sycl::malloc_device(+ pl_snap_bytes, dpct::get_in_order_queue())) != 0) {+ std::fprintf(stderr, "strata serve: --pipeline-windows 2: the GDN snapshot (%.1f MiB) does not fit; the "+ "decode stays serial\n", (double) pl_snap_bytes / 1048576.0);+ /*+ DPCT1026: The call to cudaGetLastError was removed because+ this functionality is redundant in SYCL.+ */+ pl_snap2[0] = nullptr;+ } else if ([] { const char* v = pipe_dbg_env("STRATA_PIPELINE_SNAP_OVERLAP"); return v == nullptr || std::atoi(v) != 0; }()) {+ pl_snap_overlap =+ DPCT_CHECK_ERROR(+ pl_snap2[1] = (float *)sycl::malloc_device(+ pl_snap_bytes, dpct::get_in_order_queue())) == 0 &&+ /*+ DPCT1025: The SYCL queue is created ignoring the flag+ and priority options.+ */+ DPCT_CHECK_ERROR(+ pl_snap_stream =+ dpct::get_current_device().create_queue(true)) == 0;+ for (int i = 0; i < 2 && pl_snap_overlap; ++i)+ pl_snap_overlap =+ DPCT_CHECK_ERROR(pl_snap_pre[i] = new sycl::event()) ==+ 0 &&+ DPCT_CHECK_ERROR(pl_snap_ev[i] = new sycl::event()) ==+ 0;+ /*+ DPCT1010: SYCL uses exceptions to report errors and does+ not use the error codes. The cudaGetLastError function call was+ replaced with 0. You need to rewrite this code.+ */+ if (!pl_snap_overlap) 0;+ }+ }+ if (pipe)+ std::fprintf(stderr, "strata serve: --pipeline-windows %d: two verifiers per stage, the stages overlap across "+ "windows%s\n", o.pipeline_windows,+ pl_snap2[0] == nullptr ? "" : pl_snap_overlap ? " (decode too; the GDN snapshots beside the window)"+ : " (decode too; the GDN snapshot on the critical path)");+ // the verifiers by [stage][parity], their pool routing, and the drafter's events (in a pipelined prompt read, a+ // stage-1 window waits until the drafter has read the rows of the same parity's previous window)+ strata::core::Verifier* PV[2][2] = {{&ver, &ver_b}, {pipe ? &stages[0]->ver : nullptr, pipe ? &stages[0]->ver_b : nullptr}};+ SplitDrive* PSD[2] = {&split_drive, &split_drive_b};+ dpct::event_ptr pl_mtp_ev[2] = {nullptr, nullptr};+ bool pl_mtp_live[2] = {false, false};+ bool pl_prepared = false;+ // every graph captured and the drafter's prompt path sized while nothing is in flight (a capture syncs its stream)+ auto pl_prepare = [&](std::string &e) -> bool {+ try {+ if (pl_prepared) return true;+ for (int st = 0; st < 2; ++st)+ for (int par = 0; par < 2; ++par) {+ const strata::core::OnDevice on(PV[st][par]->device());+ if (!PV[st][par]->capture_all(e)) return false;+ }+ if (!mtp.prepare_prefill(e)) return false;+ if (o.pipeline_windows >= 2 && pl_snap2[0] != nullptr && !mtp.prepare_chain(e)) return false;+ const strata::core::OnDevice on(mtp.device());+ for (dpct::event_ptr &ev : pl_mtp_ev)+ if (ev == nullptr &&+ DPCT_CHECK_ERROR(ev = new sycl::event()) != 0) {+ e = "pipeline: event creation failed";+ return false;+ }+ pl_prepared = true;+ return true;+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ // INVARIANT: nothing pipelined is in flight outside read_windows_pl and the pipelined decode loop - both end+ // here (a checkpoint, a park, the next request and the serial paths all find both stages and the drafter idle).+ // Every window in flight is served to its end (its picks discarded), then both stages and the drafter idle.+ auto pl_drain = [&]() {+ try {+ std::string e2;+ for (int round = 0; round < 10000000; ++round) {+ bool any = false;+ for (int st = 0; st < 2; ++st)+ for (int par = 0; par < 2; ++par) {+ strata::core::Verifier& v = *PV[st][par];+ if (!v.in_flight()) continue;+ any = true;+ if (v.service(&drive_pool_split, PSD[par], e2) < 0) return;+ if (v.done(e2)) v.pl_finish(nullptr, e2);+ else if (!e2.empty()) return;+ }+ if (!any) break;+ }+ for (int st = 0; st < 2; ++st) {+ const strata::core::OnDevice on(PV[st][0]->device());+ PV[st][0]->stream()->wait();+ }+ const strata::core::OnDevice on(mtp.device());+ mtp.stream()->wait();+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };std::vector<int64_t> cur;// ---- the conversation cache (see ConvCheckpoint). `live` is what the session holds right now: the tokens// it has consumed, so a request that starts with exactly them continues without any copy. `checks` are the@@ -5523,40 +7115,161 @@ int main(int argc, char **argv) try {bool live_ok = false;std::vector<ConvCheckpoint> checks;uint64_t check_clock = 0; // the checkpoints' LRU clock; creation and every use advance it+ int64_t tail_ckpt_len = -1; // --prompt-cache-tail: the length of the one tail checkpoint alive (-1 = none)bool cvec_cached = true; // the control vector's state the live session and the checkpoints were read with+ // without --mtp the conversation cache stays on: a parked image carries the draft layer's K/V only when there is one+ // (the snapshots accept a null draft)strata::core::ConversationCache conversations(o.prompt_cache > 0 ? (size_t) o.conversation_cache_mib * 1024 * 1024 : 0,(size_t) o.conversation_cache_slots);+ // Disk sessions: what a session file is bound to. The model fingerprint samples every model input this+ // engine loaded, by role (conversation_file.hpp), once; the config fingerprint covers the RESOLVED settings+ // that change what the saved bytes mean - the rope (K is cached post-RoPE), the loaded control vector, the+ // K/V format and the arithmetic switches. Sampling, seeds, draft tuning and the expert tier are not in it.+ std::optional<uint64_t> model_fp, config_fp;+ auto session_identity = [&](strata::core::SessionFileIdentity& id, std::string& e,+ const std::function<void()>& next_file) -> bool {+ if (!model_fp) {+ // what the loaders actually resolved: the CLI inputs, the pack's files and - from the expert source+ // itself - every file its experts were read from (native_experts.txt can name GGUFs per layer/role)+ strata::core::SessionInputs in;+ in.native_shards = o.native_shards;+ in.native_dense = o.native_dense_gguf;+ in.native_head = o.native_head_shards;+ in.embedding = o.embd_gguf;+ in.ple = o.ple_gguf;+ in.pack = o.pack;+ in.mtp = o.mtp.empty() ? std::string() : o.mtp + "/dense.bin";+ if (srcp != nullptr) in.experts = srcp->model_inputs();+ std::vector<strata::core::SessionModelFile> files = strata::core::session_model_inputs(in);+ // the pack's other files the loader reads (weights.cpp, expert_layout.cpp)+ if (!o.pack.empty()) {+ for (const char* n : {"index.txt", "dense.bin"}) files.push_back({std::string("pack ") + n, o.pack + "/" + n});+ for (const char* n : {"embd.bin", "extra.bin", "manifest.json"})+ files.push_back({std::string("pack ") + n, o.pack + "/" + n, true});+ if (srcp == nullptr) files.push_back({"pack experts.bin", o.pack + "/experts.bin", true});+ }+ if (!o.mtp.empty()) {+ for (const char* n : {"dense.txt", "experts.bin"}) files.push_back({std::string("mtp ") + n, o.mtp + "/" + n});+ files.push_back({"mtp draft_vocab.bin", o.mtp + "/draft_vocab.bin", true});+ }+ uint64_t fp = 0;+ // each file is one blocking read of at most 2 MiB (head and tail): announced before it starts+ if (next_file) next_file();+ if (!strata::core::session_model_fingerprint(files, fp, e, next_file))+ return false;+ model_fp = fp;+ }+ if (!config_fp) {+ strata::core::SessionConfig c;+ c.engine_version = STRATA_VERSION;+#if defined(STRATA_USE_HIP)+ c.backend = "hip";+#else+ c.backend = "cuda";+#endif+ c.kv = o.kv;+ c.max_context = o.max_context;+ c.kv_resident = o.kv_resident;+ c.mtp_window = o.mtp.empty() ? -1 : o.mtp_window;+ const char* rot = std::getenv("STRATA_KV_ROT");+ c.kv_rot = rot != nullptr && rot[0] == '1';+ c.rope = {(int64_t) rope_cfg.type, rope_cfg.freq_base, rope_cfg.factor, rope_cfg.freq_scale(),+ rope_cfg.orig_ctx, rope_cfg.ext_factor, rope_cfg.attn_factor, rope_cfg.beta_fast,+ rope_cfg.beta_slow};+ c.cvec = cvec_digest;+ c.switches = {+ {"no_ple", o.no_ple}, {"native_bf16", o.native_bf16}, {"native_bf16_extra", o.native_bf16_extra},+ {"native_ple_key", o.native_ple_key}, {"native_moe_combine", o.native_moe_combine},+ {"native_gdn", o.native_gdn}, {"native_flash_attn_short", o.native_flash_attn_short},+ {"native_qsa_indexer", o.native_qsa_indexer}, {"native_qsa", o.native_qsa},+ {"native_rope", o.native_rope}, {"native_ple_postops", o.native_ple_postops},+ {"native_router", o.native_router}, {"cpu_oracle_q8_0", o.cpu_oracle_q8_0},+ {"gr_fp32_activations", o.gr_fp32_activations}, {"gr_native_mmvf", o.gr_native_mmvf},+ {"native_preset", !o.native_preset.empty()}, {"shared_late", o.shared_late},+ {"keep_canonical", o.keep_canonical}, {"no_fused_gr", o.no_fused_gr},+ {"no_fast_attn", o.no_fast_attn}, {"no_fused_gdn", o.no_fused_gdn},+ {"no_fast_select", o.no_fast_select}, {"vision", o.vision}};+ config_fp = strata::core::session_config_fingerprint(c);+ }+ id.model = *model_fp;+ id.config = *config_fp;+ return true;+ };// Save only on a switch/rewind, not on each continuing request. No graph// addresses change: all parked images live in ordinary host vectors.- auto park_current = [&](size_t held) -> bool {+ auto park_current_body = [&](size_t held) -> bool {if (!conversations.enabled() || !live_ok || live.empty()) return true;- const strata::core::ConversationView view{live, live_imgs, checks, cvec_cached};+ // #342: before make_room evicts oldest-first, the copies of this conversation a turn back go (they hold+ // nothing the outgoing chain does not, apart from the tail this conversation rewrote)+ if (const size_t dropped = conversations.drop_superseded(live, live_imgs, checks, cvec_cached))+ std::fprintf(stderr, "strata serve: conversation cache: dropped %zu superseded cop%s of this "+ "conversation; parked=%zu\n", dropped, dropped == 1 ? "y" : "ies", conversations.size());+ // A layer split parks one image per stage: the first stage's (with the draft layer's K/V) and one per+ // later stage (without it - the draft ring is saved once). The checkpoints are MOVED apart into their+ // stage parts for the capture and put back together whichever way this ends (no running state copied).+ const size_t n_st = stages.size();+ // the draft layer's K/V lives on the last stage's GPU (the drafter is loaded there): with a split it is+ // saved with that stage's image, under its device; stage 0's image holds none+ const strata::core::QsaState* draft0 = n_st > 0 || !use_mtp ? nullptr : &mtp.kv_state(); // no --mtp: no draft K/V (snapshots accept null)+ auto draft_of = [&](size_t k) -> const strata::core::QsaState* { return use_mtp && k + 1 == n_st ? &mtp.kv_state() : nullptr; };+ strata::core::ConversationCheckpointSplit cs;+ if (n_st > 0) cs = strata::core::conversation_checkpoints_split(std::move(checks), n_st); // #752: two-phase; a bad_alloc leaves `checks` whole+ struct MergeBack {+ strata::core::ConversationCheckpointSplit& cs; std::vector<ConvCheckpoint>& checks; bool on;+ ~MergeBack() { if (on && !strata::core::conversation_checkpoints_merge(std::move(cs), checks)) checks.clear(); }+ } merge_back{cs, checks, n_st > 0};+ const strata::core::ConversationView view{live, live_imgs, n_st > 0 ? cs.stage0 : checks, cvec_cached};auto reuse = conversations.take_reuse();- size_t estimate = 0;- if (!strata::core::conversation_snapshot_bytes(view, ss, g, mtp.kv_state(), estimate, err)) {+ std::vector<strata::core::ConversationKvReuse> stage_reuse = std::move(reuse.stages);+ stage_reuse.resize(n_st);+ reuse.stages.clear();+ // the later stages' estimates, each with its own retained K/V when it still fits+ size_t stage_estimate = 0, stage_retained = 0;+ for (size_t k = 0; k < n_st; ++k) {+ auto& st = stages[k];+ const strata::core::OnDevice on(st->dev);+ const strata::core::ConversationView view_k{live, live_imgs, cs.parts[k], cvec_cached};+ size_t b = 0;+ if (!strata::core::conversation_snapshot_bytes(view_k, st->ss, g, draft_of(k), b, err)) {+ std::fprintf(stderr, "strata serve: conversation cache: skip parking (stage CUDA%d: %s)\n",+ st->dev, err.c_str());+ err.clear();+ return true;+ }+ if (!stage_reuse[k].kv.empty()) {+ size_t r = 0;+ if (strata::core::conversation_snapshot_capture_bytes(stage_reuse[k], view_k, st->ss, g, draft_of(k),+ r, err)) {+ b = r;+ stage_retained += stage_reuse[k].bytes();+ } else {+ stage_reuse[k] = {};+ err.clear();+ }+ }+ stage_estimate += b;+ }+ size_t estimate = 0;+ if (!strata::core::conversation_snapshot_bytes(view, ss, g, draft0, estimate, err)) {std::fprintf(stderr, "strata serve: conversation cache: skip parking (%s)\n", err.c_str());err.clear(); // A recoverable miss must not poison the batched draft prefill's error channel.return true;}const size_t fresh_estimate = estimate;if (!reuse.kv.empty() && !strata::core::conversation_snapshot_capture_bytes(- reuse, view, ss, g, mtp.kv_state(), estimate, err)) {+ reuse, view, ss, g, draft0, estimate, err)) {reuse = {};estimate = fresh_estimate;err.clear();}+ estimate += stage_estimate;// A park carrying its own retained K/V replaces memory the cache// already held, so capacity is make_room's call - it runs next either// way, and put()'s accounting still bounds the budget. The with-reuse// estimate must stay uncapped: it counts the retained buffers'// capacity and directories, and put() charges that same true size -// a capped figure would under-evict and overfill the budget.- // #342: before make_room evicts oldest-first, the copies of this conversation a turn back go (they hold- // nothing the outgoing chain does not, apart from the tail this conversation rewrote)- if (const size_t dropped = conversations.drop_superseded(live, live_imgs, checks, cvec_cached))- std::fprintf(stderr, "strata serve: conversation cache: dropped %zu superseded cop%s of this "- "conversation; parked=%zu\n", dropped, dropped == 1 ? "y" : "ies", conversations.size());if (!conversations.make_room(estimate, held)) {std::fprintf(stderr, "strata serve: conversation cache: skip parking (snapshot %zu MiB exceeds available budget)\n",estimate >> 20);@@ -5565,7 +7278,8 @@ int main(int argc, char **argv) try {const auto t0 = Clock::now();try {const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib * 1024 * 1024;- const size_t additional = estimate - reuse.bytes();+ const size_t retained = reuse.bytes() + stage_retained;+ const size_t additional = estimate > retained ? estimate - retained : 0;if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(),additional, floor)) {std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor, or telemetry unavailable)\n",@@ -5574,8 +7288,22 @@ int main(int argc, char **argv) try {}strata::core::SavedConversation image;size_t reused_bytes = 0;- if (!strata::core::conversation_snapshot_save(image, view, ss, g, mtp.kv_state(), err,+ if (!strata::core::conversation_snapshot_save(image, view, ss, g, draft0, err,std::move(reuse), &reused_bytes)) return false;+ for (size_t k = 0; k < n_st; ++k) { // the later stages (the last one with the draft layer's K/V)+ auto& st = stages[k];+ const strata::core::OnDevice on(st->dev);+ if (DPCT_CHECK_ERROR(dpct::get_current_device()+ .queues_wait_and_throw()) != 0) {+ err = "stage sync failed"; return false;+ }+ const strata::core::ConversationView view_k{live, live_imgs, cs.parts[k], cvec_cached};+ strata::core::SavedConversation part;+ if (!strata::core::conversation_snapshot_save(part, view_k, st->ss, g, draft_of(k), err,+ std::move(stage_reuse[k]), &reused_bytes))+ return false;+ image.stage_images.push_back(std::move(part));+ }if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), 0, floor)) {std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM floor after capture, or telemetry unavailable)\n");return true;@@ -5593,7 +7321,17 @@ int main(int argc, char **argv) try {}return true;};+ // #752: the whole park (the checkpoint split included) is under one try, so a host OOM skips parking instead of+ // ending the server+ auto park_current = [&](size_t held) -> bool {+ try { return park_current_body(held); }+ catch (const std::bad_alloc&) {+ std::fprintf(stderr, "strata serve: conversation cache: allocation failed; skip parking\n");+ return true;+ }+ };int64_t pp_total = 0, pp_from = 0, pp_next_check = 0;+ bool pp_tail_saved = false;// #471: the position the prompt pass has read up to (a chunk's or a window's end): what a request cancelled// mid-read reports as read, instead of the whole promptint64_t pp_reached = 0;@@ -5636,11 +7374,15 @@ int main(int argc, char **argv) try {std::exit(1);}};- auto checkpoint_at = [&](int64_t L, std::vector<ConvCheckpoint>* parts = nullptr) -> bool {+ auto checkpoint_at = [&](int64_t L, std::vector<ConvCheckpoint>* parts = nullptr, bool as_tail = false) -> bool {ckpt_why.clear();if (o.prompt_cache <= 0 || L < 1) return true;for (ConvCheckpoint& c : checks)- if ((int64_t) c.ids.size() == L) { c.used = ++check_clock; return true; }+ if ((int64_t) c.ids.size() == L) {+ c.used = ++check_clock;+ if (!as_tail && L == tail_ckpt_len) tail_ckpt_len = -1; // a periodic one lands here: a normal item now+ return true;+ }ConvCheckpoint c;c.ids.assign(cur.begin(), cur.begin() + L);c.imgs = imgs_below(req_imgs, L);@@ -5663,13 +7405,29 @@ int main(int argc, char **argv) try {}}c.used = ++check_clock;+ if (as_tail) { // only one tail checkpoint stays alive: the previous request's goes+ const int64_t old_tail = tail_ckpt_len;+ checks.erase(std::remove_if(checks.begin(), checks.end(), [&](const ConvCheckpoint& k) {+ return old_tail >= 0 && (int64_t) k.ids.size() == old_tail;+ }), checks.end());+ tail_ckpt_len = L;+ } else if (L == tail_ckpt_len) {+ tail_ckpt_len = -1; // the flagged tail was dropped and a normal checkpoint takes its length+ }checks.push_back(std::move(c));while ((int) checks.size() > o.prompt_cache) {std::vector<uint64_t> stamps;+ std::vector<char> is_tail;stamps.reserve(checks.size());- for (const ConvCheckpoint& k : checks) stamps.push_back(k.used);- const size_t victim = strata::program::conv_cache::eviction_victim(stamps.data(), stamps.size(),- o.prompt_cache);+ for (const ConvCheckpoint& k : checks) {+ stamps.push_back(k.used);+ is_tail.push_back(tail_ckpt_len >= 0 && (int64_t) k.ids.size() == tail_ckpt_len);+ }+ // the tail checkpoint serves only a branch of the last request: it leaves before a periodic one+ std::unique_ptr<bool[]> tail_flags(new bool[is_tail.size()]);+ for (size_t i = 0; i < is_tail.size(); ++i) tail_flags[i] = is_tail[i] != 0;+ const size_t victim = strata::program::conv_cache::eviction_victim(+ stamps.data(), stamps.size(), o.prompt_cache, tail_flags.get());checks.erase(checks.begin() + (std::ptrdiff_t) victim);}return true;@@ -5678,9 +7436,9 @@ int main(int argc, char **argv) try {std::vector<int32_t> nxt((size_t) T);for (int64_t t = 0; t < T; ++t) nxt[(size_t) t] = (int32_t) cur[(size_t) (p0 + t + 1)];// E-9: batched through the prompt path when it can (one GPU: a layer split's drafter is on the last stage)- const bool batched = !multi_gpu && sp.draft_kv(mtp, R_rows, nxt.data(), T, p0, e);- if (!e.empty() || (!batched && !mtp.prefill(R_rows, nxt.data(), T, p0, e))) return false;- if (std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr)+ const bool batched = use_mtp && !multi_gpu && sp.draft_kv(mtp, R_rows, nxt.data(), T, p0, e);+ if (!e.empty() || (use_mtp && !batched && !mtp.prefill(R_rows, nxt.data(), T, p0, e))) return false;+ if (use_mtp && std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr)std::fprintf(stderr, "strata serve: DRAFT_PREFILL path=%s mode=%d cells=%lld\n",batched ? "batched" : "token", mtp.kv_state().kv_mode, (long long) T);// progress for the server window: PP <position reached> <prompt tokens> <ms> <fresh tokens/s>@@ -5692,7 +7450,13 @@ int main(int argc, char **argv) try {strata::core::progress_at("reading the prompt (batched), done up to token", done);strata::core::progress_beat();std::fflush(stdout);- if (o.prompt_cache_every > 0 && done >= pp_next_check) {+ const bool periodic_checkpoint = o.prompt_cache_every > 0 && done >= pp_next_check;+ // Keep the prefill's existing chunk geometry. One extra near-tail checkpoint+ // can serve a branch whose shared prefix ends before the final cached state.+ const bool tail_checkpoint = o.prompt_cache_tail && o.prompt_cache > 0 && o.prompt_cache_every > 0 &&+ !multi_gpu && !pp_tail_saved && pp_total - done > std::max<int64_t>(1, o.short_read) &&+ pp_total - done <= T; // this chunk's real size (--prefill auto chunks differ from o.prefill_chunk)+ if (periodic_checkpoint || tail_checkpoint) {bool saved = false;if (multi_gpu) { // the stages' parts, saved when each of them read this chunkstd::vector<ConvCheckpoint> parts;@@ -5706,10 +7470,11 @@ int main(int argc, char **argv) try {for (const ConvCheckpoint& k : parts) complete = complete && !k.gdn.empty();saved = !complete || checkpoint_at(done, &parts); // an incomplete set: no checkpoint here} else {- saved = checkpoint_at(done);+ saved = checkpoint_at(done, nullptr, tail_checkpoint && !periodic_checkpoint);}if (!saved) { e = "saving a conversation checkpoint failed" + ckpt_why; return false; }- pp_next_check = done + o.prompt_cache_every;+ if (periodic_checkpoint) pp_next_check = done + o.prompt_cache_every;+ if (tail_checkpoint) pp_tail_saved = true;}return true;};@@ -5735,11 +7500,14 @@ int main(int argc, char **argv) try {}drive.d.plan = ver.plan_sink();drive.d.pcie_num = std::max(0, std::min(256, (int) (o.pcie_frac * 256.0 + 0.5)));- if (o.adapt_every > 0 && o.adapt_swaps > 0) drive.d.usage.assign((size_t) (g.n_layers * g.n_expert), 0.0f);+ const bool all_experts_resident = !host_res.empty() &&+ std::all_of(host_res.begin(), host_res.end(), [](int32_t r) { return r >= 0; });+ if (o.adapt_every > 0 && o.adapt_swaps > 0 && !all_experts_resident)+ drive.d.usage.assign((size_t) (g.n_layers * g.n_expert), 0.0f);// #477 --expert-profile-save: what the adaptive tier learned, kept across restarts (opt-in; off: `heat` stays// empty and nothing below runs). It needs the adaptive tier's counts and the residency table.std::vector<double> heat;- if (!o.expert_profile_save.empty()) {+ if (!o.expert_profile_save.empty() && !all_experts_resident) {if (drive.d.usage.empty() || host_res.empty())std::fprintf(stderr, "strata serve: --expert-profile-save needs the adaptive tier (--adapt-every and ""--adapt-swaps above 0) and --expert-profile: nothing will be saved\n");@@ -5760,6 +7528,7 @@ int main(int argc, char **argv) try {}// plan v0.3 P6: swaps in flight - (residency index, slot) admitted when adapt_ev has completedstd::vector<std::pair<int32_t, int32_t>> pending;+ int pending_age = 0; // the windows the pending swaps have waited (adapt_lag)std::vector<void*> pin_live; // the swaps' locked arena pages (pin_blob), unlocked once they have landeddpct::event_ptr adapt_ev = nullptr;adapt_ev = new sycl::event();@@ -5767,20 +7536,10 @@ int main(int argc, char **argv) try {auto res_upload = [&]() {try {if (d_res != nullptr)- /*- DPCT1114: cudaMemcpy is migrated to asynchronization- memcpy, assuming in the original code the source host memory is- pageable memory. If the memory is not pageable, call wait() on- event return by memcpy API to ensure synchronization behavior.- */- dpct::get_in_order_queue().memcpy(- d_res, host_res.data(), host_res.size() * sizeof(int32_t)).wait();+ res_put(d_res);for (auto& st : stages) {const strata::core::OnDevice on(st->dev);- dpct::get_in_order_queue()- .memcpy(st->d_res, host_res.data(),- host_res.size() * sizeof(int32_t))- .wait();+ res_put(st->d_res);}}catch (sycl::exception const &exc) {@@ -5813,6 +7572,7 @@ int main(int argc, char **argv) try {srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert); // in VRAM now: RAM not needed}pending.clear();+ pending_age = 0;res_upload();}catch (sycl::exception const &exc) {@@ -5821,9 +7581,12 @@ int main(int argc, char **argv) try {std::exit(1);}};+ // --pipeline-windows: set while the tier adapts beside windows in flight (see its use in adapt)+ std::function<void()> adapt_fence;// the VRAM tier follows the conversation (the same rule as the speculative loop below)auto adapt = [&]() -> bool {if (!pending.empty()) return true; // the previous swaps are still in flight+ if (remote_opt && !remote_opt->adapt(drive.d.usage, host_res, pending, o.adapt_swaps, *srcp)) return false;struct Swap { float gain; int32_t layer, in, out; };std::vector<Swap> swaps;std::vector<std::pair<float, int32_t>> cand, vict;@@ -5833,7 +7596,7 @@ int main(int argc, char **argv) try {const float* u = drive.d.usage.data() + l * g.n_expert;const int32_t* r = host_res.data() + l * g.n_expert;for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) {- if (r[e] < 0) { if (u[e] >= 2.0f && !(peer.valid() && peer.has(l, e))) cand.emplace_back(u[e], e); }+ if (r[e] < 0) { if (u[e] >= 2.0f && !(peer.valid() && peer.has(l, e)) && !(remote_opt && remote_opt->owns(l, e)) && !helper_holds(l, e)) cand.emplace_back(u[e], e); }else vict.emplace_back(u[e], e);}if (cand.empty() || vict.empty()) continue;@@ -5848,7 +7611,16 @@ int main(int argc, char **argv) try {}std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; });if ((int) swaps.size() > o.adapt_swaps) swaps.resize((size_t) o.adapt_swaps);- if (!resident_stage_swaps(src, xcache, host_res, g.n_expert, swaps, adapt_stream)) return false;+ // the copies back read the cache of the card that owns each layer (see resident_stage_swaps)+ auto home_of = [&](int64_t layer) -> SwapHome {+ const int stn = multi_gpu ? stage_of(layer) : 0;+ if (stn > 0) {+ GpuStage* gs = stages[(size_t) stn - 1].get();+ return {&gs->cache, gs->adapt_stream, gs->dev};+ }+ return {&xcache, adapt_stream, -1};+ };+ if (!resident_stage_swaps(src, host_res, g.n_expert, swaps, home_of)) return false;if (pin_blobs_on()) { // lock the batch's source pages (a file-backed arena on AMD; see pin_blobs)std::vector<std::pair<uintptr_t, uintptr_t>> spans;for (const Swap& s : swaps)@@ -5857,29 +7629,51 @@ int main(int argc, char **argv) try {(uintptr_t) b + strata::kernels::cpu::expert_layout().blob_bytes(s.layer));pin_blobs(std::move(spans), pin_live);}+ // --pipeline-windows: windows are in flight while the tier adapts. The evicted experts stop being planned+ // for the GPU first (the pool computes them on the CPU from the rows every layer publishes, see+ // Verifier::set_always_publish); then every copy into their slots waits until all the work the stages'+ // streams hold now has completed: any window that may still read those slots was launched before this.+ std::vector<int32_t> fenced_slots;+ if (adapt_fence && !swaps.empty()) {+ for (const Swap& s : swaps) {+ const size_t out = (size_t) s.layer * g.n_expert + s.out;+ fenced_slots.push_back(host_res[out]);+ host_res[out] = strata::core::kNotResident;+ }+ std::atomic_thread_fence(std::memory_order_seq_cst);+ adapt_fence();+ }bool main_live = false;- for (const Swap& s : swaps) {+ // STRATA_DMA_BATCH (F12): the main device's copies as one cudaMemcpyBatchAsync (mode 0: one each)+ const int dma_mode = multi_gpu ? 0 : strata::core::dma_batch_mode();+ std::vector<void*> cp_dst;+ std::vector<const void*> cp_src;+ std::vector<size_t> cp_bytes;+ for (size_t si = 0; si < swaps.size(); ++si) {+ const Swap& s = swaps[si];const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out;- const int32_t slot = host_res[out];+ const int32_t slot = fenced_slots.empty() ? host_res[out] : fenced_slots[si];const uint8_t* b = srcp->blob(s.layer, s.in);const int stn = multi_gpu ? stage_of(s.layer) : 0; // the swap stays in the layer's own cacheGpuStage* gs = stn > 0 ? stages[(size_t) stn - 1].get() : nullptr;const strata::core::OnDevice on(gs ? gs->dev : -1);+ if (dma_mode != 0 && slot >= 0 && b != nullptr) {+ cp_dst.push_back(xcache.device_slot(slot));+ cp_src.push_back(b);+ cp_bytes.push_back((size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer));+ main_live = true;+ host_res[out] = strata::core::kNotResident;+ srcp->prefetch(s.layer, s.out);+ pending.emplace_back((int32_t) in, slot);+ continue;+ }if (slot < 0 || b == nullptr ||- /*- DPCT1124: cudaMemcpyAsync is migrated to asynchronous- memcpy API. While the origin API might be synchronous, it- depends on the type of operand memory, so you may need to- call wait() on event return by memcpy API to ensure- synchronization behavior.- */- DPCT_CHECK_ERROR(- (gs ? gs->adapt_stream : adapt_stream)->memcpy(- gs ? gs->cache.device_slot(slot)- : xcache.device_slot(slot),- b,- (size_t)strata::kernels::cpu::expert_layout()- .blob_bytes(s.layer))) != 0) {+ adapt_copy_h2d(gs ? gs->cache.device_slot(slot)+ : xcache.device_slot(slot),+ b,+ (size_t)strata::kernels::cpu::expert_layout()+ .blob_bytes(s.layer),+ gs ? gs->adapt_stream : adapt_stream) != 0) {std::fprintf(stderr,"strata serve: adaptive swap copy failed ""(layer %d, slot %d, pinned %d): %s\n",@@ -5906,6 +7700,27 @@ int main(int argc, char **argv) try {srcp->prefetch(s.layer, s.out); // a file-backed arena released its pages: read them back aheadpending.emplace_back((int32_t) in, slot); // resident once the copy has landed}+ if (!cp_dst.empty() &&+ strata::core::copy_blobs(cp_dst.data(), cp_src.data(),+ cp_bytes.data(), cp_dst.size(),+ adapt_stream, dma_mode) != 0) {+ std::fprintf(+ stderr,+ "strata serve: adaptive swap copy failed (batched): %s\n",+ /*+ DPCT1009: SYCL reports errors using exceptions and does+ not use error codes. Please replace the+ "get_error_string_dummy(...)" with a real error-handling+ function.+ */+ /*+ DPCT1010: SYCL uses exceptions to report errors and+ does not use the error codes. The cudaGetLastError function+ call was replaced with 0. You need to rewrite this code.+ */+ dpct::get_error_string_dummy(0));+ return false;+ }if (!swaps.empty()) dpct::sync_barrier(adapt_ev, adapt_stream);(void) main_live;for (auto& st : stages)@@ -5930,6 +7745,312 @@ int main(int argc, char **argv) try {for (float& v : drive.d.usage) v *= o.adapt_decay;return true;};+ // ---- --adapt-async 1: the asynchronous adaptive tier (opt-in; the resident RAM mode, see the checks where+ // the RAM copy is built). adapt() runs a whole round - choose, copy the evicted slots back with a stream sync,+ // copy the new experts in from the RAM copy - on a thread the decode loop joins after the draft: ~24 ms every+ // 4th window with ~90 swaps. Here a round moves through four steps, each started by `adapt_tick` between+ // windows once the previous step's copies (events) and host work (the job thread) are done:+ // 1. job: choose (adapt()'s rule, over snapshots of the routing counts and the residency) and copy the+ // evicted slots back into exchange buffers (D2H), each from the cache of the card that owns its layer;+ // 2. stage the exchanges and mark the evicted experts non-resident (the CPU reads them from the exchange+ // buffers from the next window on); job: copy the new experts in (straight from a page-locked RAM copy,+ // else through a pinned bounce buffer), on the owning card's refill stream;+ // 3. mark the new experts resident; job: move the evicted blobs into the RAM places the new ones left;+ // 4. flip the copy's offsets.+ // A slot is overwritten only after its old expert stopped being planned for the GPU (step 2, between windows,+ // with the device copies of the residency table uploaded as apply_pending does), and a RAM place only once its+ // expert is resident (step 3), so no window computes from memory that is changing. A request starts with the+ // round drained (adapt_tick(true)), before its prompt lends any slot. Not bit-exact run to run: which window+ // first computes a swapped-in expert on the GPU (which rounds differently from the CPU) depends on when its+ // copy lands. `j`: the swap's exchange buffer (its copy back) and bounce buffer (a_cap + j).+ struct ASwap { int32_t layer, in, out, slot; int home; int64_t j; bool exchange; };+ struct AHome {+ strata::core::ExpertCache *cache; dpct::queue_ptr stream;+ dpct::event_ptr ev;+ int dev;+ bool used;+ };+ enum class AState { Idle, CopyBack, SwapIn, Commit };+ AState astate = AState::Idle;+ std::vector<ASwap> aswaps;+ std::vector<float> a_usage;+ std::vector<int32_t> a_res;+ int64_t a_win = 0, a_last = 0, a_rounds = 0, a_swapped = 0;+ double a_ms = 0; // wall time from a round's start to its flip, summed (the "ms/round" stat)+ Clock::time_point a_t0;+ std::atomic<bool> a_err{false};+ std::vector<AHome> ahomes; // [0] = CUDA0's cache, [k] = layer split stage k's+ std::unique_ptr<JobThread> ajob;+ const int64_t a_cap = std::min<int64_t>(o.adapt_swaps, 96); // as the blocking tier's exchange buffers+ if (o.adapt_async && !drive.d.usage.empty() && src.complement_ready() && src.exchange_capacity() >= 2 * a_cap) {+ ahomes.push_back({&xcache, adapt_stream, adapt_ev, 0, false});+ for (auto& st : stages) ahomes.push_back({&st->cache, st->adapt_stream, st->adapt_ev, st->dev, false});+ ajob = std::make_unique<JobThread>();+ std::fprintf(stderr, "strata serve: adaptive tier asynchronous (--adapt-async 1): up to %lld swaps per round, "+ "a round every %d windows\n", (long long) a_cap, o.adapt_every);+ }+ auto a_flush = [&]() { // the job's copies: an event after them on every+ // stream used, submitted now (WDDM)+ try {+ for (AHome &h : ahomes)+ if (h.used) {+ const strata::core::OnDevice on(h.dev);+ /*+ DPCT1024: The original code returned the error code+ that was further consumed by the program logic. This+ original code was replaced with 0. You may need to rewrite+ the program logic consuming the error code.+ */+ if (DPCT_CHECK_ERROR(dpct::sync_barrier(h.ev, h.stream)) !=+ 0) a_err = true;+ (void)DPCT_CHECK_ERROR(((h.stream)->ext_oneapi_empty()));+ }+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ auto a_choose = [&]() { // step 1, on the job thread+ try {+ struct C { float gain; int32_t layer, in, out; };+ std::vector<C> all;+ std::vector<std::pair<float, int32_t>> cand, vict;+ for (int64_t l = 0; l < g.n_layers; ++l) {+ cand.clear();+ vict.clear();+ const float* u = a_usage.data() + l * g.n_expert;+ const int32_t* r = a_res.data() + l * g.n_expert;+ for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) {+ if (r[e] < 0) { if (u[e] >= 2.0f && !helper_holds(l, e)) cand.emplace_back(u[e], e); }+ else vict.emplace_back(u[e], e);+ }+ if (cand.empty() || vict.empty()) continue;+ std::sort(cand.begin(), cand.end(), [](auto& a, auto& b) { return a.first > b.first; });+ const size_t nc = std::min(cand.size(), vict.size());+ std::partial_sort(vict.begin(), vict.begin() + (ptrdiff_t) nc, vict.end(),+ [](auto& a, auto& b) { return a.first < b.first; });+ for (size_t i = 0; i < nc; ++i) {+ if (cand[i].first < vict[i].first + 1.5f) break;+ all.push_back({cand[i].first - vict[i].first, (int32_t) l, cand[i].second, vict[i].second});+ }+ }+ std::sort(all.begin(), all.end(), [](const C& a, const C& b) { return a.gain > b.gain; });+ aswaps.clear();+ for (const C& c : all) {+ if ((int64_t) aswaps.size() >= a_cap) break;+ const int32_t slot = a_res[(size_t) c.layer * g.n_expert + c.out];+ if (slot < 0) continue;+ // an exchange (as resident_stage_swaps): `in` from the RAM copy, `out` held by its slot alone takes its+ // place there; otherwise `out` is in the copy already (the lend region) or `in` is not (a RAM budget)+ const bool x = src.has_resident(c.layer, c.in) && !src.has_resident(c.layer, c.out);+ aswaps.push_back({c.layer, c.in, c.out, slot, multi_gpu ? stage_of(c.layer) : 0, (int64_t) aswaps.size(), x});+ }+ for (AHome& h : ahomes) h.used = false;+ for (const ASwap& w : aswaps) {+ if (!w.exchange) continue;+ AHome& h = ahomes[(size_t) w.home];+ const strata::core::OnDevice on(h.dev);+ /*+ DPCT1000: Error handling if-stmt was detected but could not+ be rewritten.+ */+ /*+ DPCT1124: cudaMemcpyAsync is migrated to asynchronous+ memcpy API. While the origin API might be synchronous, it+ depends on the type of operand memory, so you may need to call+ wait() on event return by memcpy API to ensure synchronization+ behavior.+ */+ if (const dpct::err0 e = DPCT_CHECK_ERROR(h.stream->memcpy(+ src.exchange_buffer(w.j), h.cache->device_slot(w.slot),+ (size_t)strata::kernels::cpu::expert_layout()+ .blob_bytes(w.layer)));+ e != 0) {+ std::fprintf(stderr,+ "strata serve: adaptive tier: copy back of "+ "layer %d slot %d (CUDA%d) failed: %s\n",+ /*+ DPCT1009: SYCL reports errors using+ exceptions and does not use error codes. Please+ replace the "get_error_string_dummy(...)" with+ a real error-handling function.+ */+ (int)w.layer, (int)w.slot, h.dev,+ dpct::get_error_string_dummy(e));+ /*+ DPCT1001: The statement could not be removed.+ */+ a_err = true;+ }+ h.used = true;+ }+ a_flush();+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ auto a_copy_in = [&]() { // step 2, on the job thread+ try {+ for (AHome &h : ahomes) h.used = false;+ for (const ASwap& w : aswaps) {+ AHome& h = ahomes[(size_t) w.home];+ const size_t nb = (size_t) strata::kernels::cpu::expert_layout().blob_bytes(w.layer);+ const uint8_t* b = src.pinned(w.layer, w.in) ? src.resident_blob(w.layer, w.in) : nullptr;+ if (b == nullptr) { // pageable, or not in the RAM copy: through a bounce buffer (an async copy)+ uint8_t* bb = src.exchange_buffer(a_cap + w.j);+ if (bb == nullptr || !src.copy_blob(w.layer, w.in, bb)) {+ std::fprintf(stderr, "strata serve: adaptive tier: layer %d expert %d could not be read\n",+ (int) w.layer, (int) w.in);+ a_err = true;+ continue;+ }+ b = bb;+ }+ const strata::core::OnDevice on(h.dev);+ /*+ DPCT1000: Error handling if-stmt was detected but could not+ be rewritten.+ */+ /*+ DPCT1124: cudaMemcpyAsync is migrated to asynchronous+ memcpy API. While the origin API might be synchronous, it+ depends on the type of operand memory, so you may need to call+ wait() on event return by memcpy API to ensure synchronization+ behavior.+ */+ if (const dpct::err0 e = DPCT_CHECK_ERROR(+ h.stream->memcpy(h.cache->device_slot(w.slot), b, nb));+ e != 0) {+ std::fprintf(stderr,+ "strata serve: adaptive tier: copy of layer "+ "%d into slot %d (CUDA%d) failed: %s\n",+ /*+ DPCT1009: SYCL reports errors using+ exceptions and does not use error codes. Please+ replace the "get_error_string_dummy(...)" with+ a real error-handling function.+ */+ (int)w.layer, (int)w.slot, h.dev,+ dpct::get_error_string_dummy(e));+ /*+ DPCT1001: The statement could not be removed.+ */+ a_err = true;+ }+ h.used = true;+ }+ a_flush();+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ auto a_ready =+ [&](bool wait) -> bool { // the job and its copies are done+ try {+ if (wait) ajob->wait();+ else if (!ajob->idle()) return false;+ for (AHome& h : ahomes)+ if (h.used) {+ const strata::core::OnDevice on(h.dev);+ if (wait) {+ if (DPCT_CHECK_ERROR(h.ev->wait_and_throw()) != 0)+ a_err = true;+ } else if (const dpct::err0 q =+ dpct::sycl_event_query(h.ev);+ q == 1) return false;+ /*+ DPCT1001: The statement could not be removed.+ */+ /*+ DPCT1000: Error handling if-stmt was detected but could+ not be rewritten.+ */+ else if (q != 0) a_err = true;+ }+ return true;+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ // between windows: `drain` finishes the round in flight and starts none. False when a copy failed.+ auto adapt_tick = [&](bool drain) -> bool {+ if (!ajob) return true;+ if (!drain) ++a_win; // one tick per window+ for (;;) {+ if (a_err.load()) return false;+ switch (astate) {+ case AState::Idle:+ if (drain || a_win - a_last < (int64_t) o.adapt_every) return true;+ a_last = a_win;+ ++a_rounds;+ a_t0 = Clock::now();+ a_usage = drive.d.usage;+ a_res = host_res;+ // #477: the routing counted, as adapt() counts it (--expert-profile-save; else `heat` is empty)+ for (size_t i = 0; i < heat.size(); ++i) heat[i] += (double) drive.d.usage[i];+ for (float& v : drive.d.usage) v *= o.adapt_decay;+ ajob->post(a_choose);+ astate = AState::CopyBack;+ return true;+ case AState::CopyBack: { // step 2: the evicted experts leave the GPU's plan+ if (!a_ready(drain)) return true;+ if (a_err.load()) return false;+ size_t k = 0;+ for (size_t i = 0; i < aswaps.size(); ++i) {+ const ASwap w = aswaps[i];+ const size_t out = (size_t) w.layer * g.n_expert + w.out;+ if (host_res[out] != w.slot) continue; // the table moved since the snapshot: not this one+ if (w.exchange && !src.stage_exchange(w.layer, w.in, w.out, w.j)) {+ std::fprintf(stderr, "strata serve: adaptive tier: stage_exchange refused layer %d in %d out %d\n",+ (int) w.layer, (int) w.in, (int) w.out);+ return false;+ }+ host_res[out] = strata::core::kNotResident; // the CPU computes it from the next window on+ srcp->prefetch(w.layer, w.out);+ aswaps[k++] = w;+ }+ aswaps.resize(k);+ res_upload();+ ajob->post(a_copy_in);+ astate = AState::SwapIn;+ if (!drain) return true;+ continue;+ }+ case AState::SwapIn: // step 3: the new experts are in their slots+ if (!a_ready(drain)) return true;+ if (a_err.load()) return false;+ for (const ASwap& w : aswaps) {+ host_res[(size_t) w.layer * g.n_expert + w.in] = w.slot;+ srcp->release(w.layer, w.in);+ }+ res_upload();+ a_swapped += (int64_t) aswaps.size();+ ajob->post([&] { src.commit_copies(); });+ astate = AState::Commit;+ if (!drain) return true;+ continue;+ case AState::Commit: // step 4+ if (!a_ready(drain)) return true;+ if (a_err.load()) return false;+ src.commit_flip();+ a_ms += std::chrono::duration<double, std::milli>(Clock::now() - a_t0).count();+ aswaps.clear();+ astate = AState::Idle;+ continue; // a round due now starts at this same boundary+ }+ }+ };// #477: write the learned profile (between requests and at QUIT: a prompt's lent slots are back by then).// A swap still in flight counts as done - its expert is resident once the copy lands. `why`: for the log.auto save_profile = [&](const char* why) {@@ -5937,6 +8058,8 @@ int main(int argc, char **argv) try {std::vector<uint8_t> resident(host_res.size(), 0);for (size_t i = 0; i < host_res.size(); ++i) resident[i] = host_res[i] >= 0;for (const auto& p : pending) resident[(size_t) p.first] = 1;+ if (astate == AState::SwapIn) // --adapt-async: the same for a round past its step 2+ for (const ASwap& w : aswaps) resident[(size_t) w.layer * g.n_expert + w.in] = 1;std::string e;const auto ranked = strata::core::rank_learned_profile(g.n_layers, g.n_expert, resident, heat,profile_loaded);@@ -6067,7 +8190,7 @@ int main(int argc, char **argv) try {"expert_slots_primary=%lld expert_cache_primary_mib=%lld spec=%d ""mtp_max=%d lookup=%d vram_free_mib=%lld cvec=%s arena_mib=%lld pool_workers=%d pcie_frac=%.2f ""spec_min_p=%.2f conversation_cache_mib=%lld conversation_cache_slots=%d "- "conversation_cache_min_free_mib=%lld tail_role_token=%lld vram_elastic=%d engine=" STRATA_VERSION "\n",+ "conversation_cache_min_free_mib=%lld tail_role_token=%lld vram_elastic=%d%s engine=" STRATA_VERSION "\n",(long long) o.max_context, o.kv.c_str(),(long long) (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1? ss.qsa_states[ss.qsa_primary()].n_slots * 4 : 0),@@ -6078,7 +8201,9 @@ int main(int argc, char **argv) try {(long long) ((o.mmap_experts ? src.resident_bytes() : strata::kernels::cpu::expert_layout().total) >> 20),pool.workers(), o.pcie_frac,o.spec_min_p, (long long) o.conversation_cache_mib, o.conversation_cache_slots,- (long long) o.conversation_cache_min_free_mib, (long long) o.tail_role_token, xcache.segmented() ? 1 : 0);+ (long long) o.conversation_cache_min_free_mib, (long long) o.tail_role_token, xcache.segmented() ? 1 : 0,+ o.batch > 0 ? (" batch_slots=" + std::to_string(o.batch) ++ " slot_cache=" + std::to_string(o.prompt_cache > 0 ? 1 : 0)).c_str() : "");}// issue #29: a request whose heartbeat (tokens, prompt chunks, verify windows) stops for this long is stuck on// a flag nobody will raise - end the engine with where it was, so the server starts it again instead of the@@ -6098,6 +8223,8 @@ int main(int argc, char **argv) try {const uint64_t b = p.beats.load();if (!p.busy.load() || b != last) { last = b; ticks_at = p.ticks.load(); since = now; continue; }if (now - since < std::chrono::seconds(limit)) continue;+ // a blocking step's explicit allowance (session files): still within it, not yet stuck+ if (strata::core::progress_now_ms() < p.allow_until_ms.load()) continue;std::fprintf(stderr, "strata serve: no progress for %d s during a request (%s) - stopping ""the engine so the server starts it again (issue #29)\n",limit, stage_text().c_str());@@ -6114,7 +8241,9 @@ int main(int argc, char **argv) try {int64_t rounds = 0;const int S = o.spec;const int S_mtp = o.mtp_max_t > 0 ? std::min(o.mtp_max_t, S) : S; // the MTP's windows; suffixes go up to S- if (S_mtp < S) mtp.set_max_drafts(S_mtp - 1);+ if (use_mtp && S_mtp < S) mtp.set_max_drafts(S_mtp - 1);+ // --pipeline-windows 2 loads the drafter with 8 rows: the serial loop's chain keeps its own length+ else if (use_mtp && mtp.max_t() > S_mtp) mtp.set_max_drafts(S_mtp - 1);strata::spec::SuffixDrafter sfx(std::max(1, o.suffix_draft), 64, (size_t) o.max_context + 4096);strata::spec::DraftPolicy policy(S); // MTP or lookup window, learned over the whole process// The vision path (--vision): GENI <max_new> <embeddings file> <id,id,...> carries images. The file is one@@ -6274,25 +8403,708 @@ int main(int argc, char **argv) try {std::exit(1);}};- while (next_line(line)) {+ // ---- --batch: the slots of the batch windows+ struct BSlot {+ bool active = false, stop = false;+ int32_t x = 0; ///< the token the next window feeds (not yet in the slot's state)+ std::array<int32_t, strata::kernels::kVerifyMaxT> draft{}; ///< the slot's next MTP proposal+ bool draft_ready = false;+ int64_t p = 0; ///< its position+ int64_t produced = 0, max_new = 0;+ Clock::time_point t0;+ // the slot's own conversation cache: the tokens its sessions hold (the prompt, then every token a window+ // fed). Kept when the request ends (`cached`), so the next turn of that conversation continues from it+ // instead of reading its history again (see `slot_source` in the request path).+ std::vector<int32_t> ids;+ bool cached = false; ///< idle, and its sessions still hold `ids`+ bool cvec = true; ///< the control vector setting `ids` were read with+ bool img = false; ///< the conversation has pictures (never reused from the slot)+ // the checkpoint its prompt read took at the last turn boundary (the history before the new turn's+ // header): a client's next turn renders the history again WITHOUT this reply's thinking, so it matches+ // the slot's tokens only up to there - the slot's K/V up to it plus this state continue from it+ std::vector<ConvCheckpoint> checks;+ // a prompt read that gave way to a waiting request (BYIELD): `ids` is the part read so far, and the same+ // request continues from it (the read goes on with the same chunks; `from0`: it had started at token 0)+ bool partial = false, partial_from0 = false;+ };+ std::vector<BSlot> bs((size_t) std::max(o.batch, 0));+ // timing of the batch windows since the slots were last all idle (one stderr line then)+ double bt_run = 0, bt_commit = 0, bt_emit = 0;+ double bt_wait0 = 0, bt_pool0 = 0;+ int64_t bt_miss0 = 0, bt_hits0 = 0, bt_pcie0 = 0;+ int64_t bt_windows = 0, bt_rows = 0, bt_tokens = 0;+ Clock::time_point bt_start = Clock::now();+ int admit_slot = -1; ///< the slot the request being read will continue in (BGEN)+ long long admit_max_new = 0;+ auto batch_on = [&] { for (const BSlot& b : bs) if (b.active) return true; return false; };+ auto try_next_line = [&](std::string& out) -> bool {+ std::lock_guard<std::mutex> lk(in_mu);+ if (in_lines.empty()) return false;+ out = std::move(in_lines.front());+ in_lines.pop_front();+ return true;+ };+ // the session a request just left behind (its prompt) -> slot b's sessions, on every stage+ auto copy_to_slot = [&](int b, const std::vector<int32_t> &ids,+ std::string &e) -> bool {+ try {+ const int64_t upto = (int64_t)ids.size();+ for (size_t k = 0; k < bslot_ss.size(); ++k) {+ strata::core::SessionState& from = k == 0 ? ss : stages[k - 1]->ss;+ strata::core::SessionState& to = *bslot_ss[k][(size_t) b];+ const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev);+ if (DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()) !=+ 0) {+ e = "batch admission: device sync failed"; return false;+ }+ strata::core::ConversationCheckpoint ck;+ ck.ids = ids;+ if (!strata::core::conversation_checkpoint_save(ck, from, g, e) ||+ !strata::core::conversation_checkpoint_restore(ck, to, g, e))+ return false;+ for (int64_t j = 0; j < from.qsa_alloc; ++j) {+ strata::core::ConversationKv img;+ if (!strata::core::conversation_kv_save(img, from.qsa_states[from.qsa_ord0 + j], g, upto, true, e))+ return false;+ if (DPCT_CHECK_ERROR(dpct::get_current_device()+ .queues_wait_and_throw()) != 0) {+ e = "batch admission: device sync failed"; return false;+ }+ if (!strata::core::conversation_kv_restore(img, to.qsa_states[to.qsa_ord0 + j], g, upto, true, e))+ return false;+ }+ if (DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()) !=+ 0) {+ e = "batch admission: device sync failed"; return false;+ }+ }+ if (batch_mtp) {+ // Admission first builds the solo draft KV; copy it into the slot before drafting.+ strata::core::ConversationKv image;+ if (!mtp.idle(e) || !slot_mtp[(size_t)b]->idle(e) ||+ !strata::core::conversation_kv_save(image, mtp.kv_state(),+ draft_geometry, upto,+ false, e) ||+ !strata::core::conversation_kv_restore(+ image, slot_mtp[(size_t)b]->kv_state(), draft_geometry,+ upto, false, e) ||+ DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()) !=+ 0)+ return false;+ slot_mtp[(size_t) b]->set_prompt_len(upto);+ }+ return true;+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ // slot b's sessions -> the main ones (the reverse of copy_to_slot): a request that continues the+ // conversation an idle slot holds reads on from there. Every stage, the same calls.+ // `at`: one of the slot's checkpoints - only the K/V up to it is copied and its state restored instead+ auto copy_from_slot = [&](int b, const ConvCheckpoint *at,+ std::string &e) -> bool {+ try {+ const int64_t upto = at != nullptr ? (int64_t)at->ids.size()+ : (int64_t)bs[(size_t)b].ids.size();+ if (at != nullptr && at->stage_parts.size() != stages.size()) { e = "a checkpoint without its stage parts"; return false; }+ for (size_t k = 0; k < bslot_ss.size(); ++k) {+ strata::core::SessionState& from = *bslot_ss[k][(size_t) b];+ strata::core::SessionState& to = k == 0 ? ss : stages[k - 1]->ss;+ const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev);+ if (DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()) !=+ 0) {+ e = "batch slot restore: device sync failed"; return false;+ }+ if (at != nullptr) {+ if (!strata::core::conversation_checkpoint_restore(k == 0 ? *at : at->stage_parts[k - 1], to, g, e))+ return false;+ } else {+ strata::core::ConversationCheckpoint ck;+ ck.ids = bs[(size_t) b].ids;+ if (!strata::core::conversation_checkpoint_save(ck, from, g, e) ||+ !strata::core::conversation_checkpoint_restore(ck, to, g, e))+ return false;+ }+ for (int64_t j = 0; j < from.qsa_alloc; ++j) {+ strata::core::ConversationKv img;+ if (!strata::core::conversation_kv_save(img, from.qsa_states[from.qsa_ord0 + j], g, upto, true, e))+ return false;+ if (DPCT_CHECK_ERROR(dpct::get_current_device()+ .queues_wait_and_throw()) != 0) {+ e = "batch slot restore: device sync failed";+ return false;+ }+ if (!strata::core::conversation_kv_restore(img, to.qsa_states[to.qsa_ord0 + j], g, upto, true, e))+ return false;+ }+ if (DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()) !=+ 0) {+ e = "batch slot restore: device sync failed"; return false;+ }+ }+ if (batch_mtp) {+ // A returning solo request resumes from its slot's draft KV.+ strata::core::ConversationKv image;+ if (!slot_mtp[(size_t)b]->idle(e) || !mtp.idle(e) ||+ !strata::core::conversation_kv_save(+ image, slot_mtp[(size_t)b]->kv_state(), draft_geometry,+ upto, false, e) ||+ !strata::core::conversation_kv_restore(+ image, mtp.kv_state(), draft_geometry, upto, false,+ e) ||+ DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()) !=+ 0)+ return false;+ mtp.set_prompt_len(upto);+ }+ return true;+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ // one batch window over the active slots only (row t is the t-th active slot): an idle slot is not touched,+ // so it keeps the conversation it holds+ auto batch_step = [&]() -> bool {+ int S = 0;+ int rows[strata::kernels::kVerifyMaxT] = {};+ int32_t tok[strata::kernels::kVerifyMaxT] = {}, outb[strata::kernels::kVerifyMaxT] = {};+ int64_t pos[strata::kernels::kVerifyMaxT] = {};+ int first[strata::kernels::kVerifyMaxT] = {}, active[strata::kernels::kVerifyMaxT] = {};+ static size_t next_slot = 0;+ // Each MTP slot uses two rows; rotate slots when more than four are active.+ int A = 0;+ for (size_t offset = 0; offset < bs.size() && S + (batch_mtp ? 2 : 1) <= strata::kernels::kVerifyMaxT; ++offset) {+ const int b = (int) ((next_slot + offset) % bs.size());+ if (bs[(size_t) b].active) {+ first[A] = S;+ active[A++] = b;+ rows[S] = b;+ tok[S] = bs[(size_t) b].x;+ pos[S] = bs[(size_t) b].p;+ ++S;+ if (batch_mtp) {+ rows[S] = b;+ if (!bs[(size_t) b].draft_ready) {+ err = "batch MTP: a live slot has no draft";+ return false;+ }+ tok[S] = bs[(size_t) b].draft[0];+ pos[S] = bs[(size_t) b].p + 1;+ ++S;+ }+ }+ }+ if (batch_mtp && A > 0) next_slot = ((size_t) active[A - 1] + 1) % bs.size();+ if (S == 0) return true;+ const bool was_busy = strata::core::progress().busy.load();+ strata::core::progress().busy.store(true);+ drive.d.layers = 0;+ drive.d.experts = 0;+ drive.d.failed = false;+ apply_pending(false);+ if (bt_windows == 0) {+ bt_start = Clock::now();+ bt_wait0 = ver.ms_wait; bt_pool0 = ver.ms_pool;+ bt_miss0 = drive.d.multi_misses; bt_hits0 = drive.d.cache_hits; bt_pcie0 = drive.d.pcie_experts;+ }+ const Clock::time_point w0 = Clock::now();+ if (!ver.run_slot_rows(rows, S, tok, pos, win_pool_fn, win_pool_user, outb, err) || drive.d.failed) {+ std::printf("ERR %s\n", drive.d.failed && drive.d.fail ? drive.d.fail : err.c_str());+ return false;+ }+ const Clock::time_point w1 = Clock::now();+ // Accept the proposal only when the target picked it and there is room to emit both tokens.+ std::vector<int> keep(bs.size(), 0);+ for (int a = 0; a < A; ++a) {+ const int b = active[a], i = first[a];+ const BSlot& sl = bs[(size_t) b];+ const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outb[i]) != o.eos_ids.end();+ keep[b] = batch_mtp && outb[i] == tok[i + 1] && !eos && !sl.stop &&+ sl.produced + 2 <= sl.max_new && sl.p + 3 <= o.max_context ? 2 : 1;+ }+ if (!(batch_mtp ? ver.commit_slot_prefixes(keep.data(), err) : ver.commit_slots(err))) {+ std::printf("ERR %s\n", err.c_str());+ return false;+ }+ const Clock::time_point w2 = Clock::now();+ auto msd = [](Clock::time_point a0, Clock::time_point b0) { return std::chrono::duration<double, std::milli>(b0 - a0).count(); };+ bt_run += msd(w0, w1);+ bt_commit += msd(w1, w2);+ ++bt_windows;+ for (int a = 0; a < A; ++a) bt_rows += keep[active[a]];+ for (int t = 0; t < A; ++t) {+ const int b = active[t];+ BSlot& sl = bs[(size_t) b];+ for (int j = 0; j < keep[b]; ++j) {+ const int32_t y = outb[first[t] + j];+ sl.ids.push_back(tok[first[t] + j]);+ std::printf("BT %d %d\n", b, (int) y);+ ++sl.produced;+ const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end();+ const char* fin = eos ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length"+ : sl.p + 2 > o.max_context ? "length" : nullptr;+ if (fin != nullptr) {+ const double ms = std::chrono::duration<double, std::milli>(Clock::now() - sl.t0).count();+ std::printf("BDONE %d %lld %s %.1f\n", b, (long long) sl.produced, fin, ms);+ sl.active = false;+ sl.cached = o.prompt_cache > 0 && !sl.img;+ break;+ }+ sl.x = y;+ sl.p += 1;+ }+ if (batch_mtp && sl.active) {+ const size_t stride = (size_t) g.hc * (size_t) g.n_embd;+ if (DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(+ slot_mtp_rows[(size_t)b].get(),+ ver.final_R_all() + (size_t)first[t] * stride,+ 2 * stride * sizeof(float)).wait()) != 0 ||+ !slot_mtp[(size_t)b]->draft(2, outb + first[t],+ pos[first[t]], keep[b] - 1,+ sl.draft.data(), err)) {+ std::printf("ERR batch MTP slot %d: %s\n", b, err.c_str());+ return false;+ }+ sl.draft_ready = true;+ }+ }+ std::fflush(stdout);+ bt_emit += msd(w2, Clock::now());+ strata::core::progress().busy.store(was_busy);+ if (!batch_on() && bt_windows > 0) {+ const double w = (double) bt_windows, wall = msd(bt_start, Clock::now());+ const double L = (double) g.n_layers;+ std::fprintf(stderr, "strata batch: %lld windows, avg %.2f rows, %.2f ms/window = run %.2f (CUDA0 GPU-reach "+ "wait %.2f + CPU experts %.2f) + commit %.2f + emit %.2f; per layer-window: CPU experts "+ "%.2f, VRAM hits %.2f, PCIe %.2f; %.1f rows/s over %.0f ms of wall time (admissions "+ "included)\n",+ (long long) bt_windows, bt_rows / w, (bt_run + bt_commit + bt_emit) / w, bt_run / w,+ (ver.ms_wait - bt_wait0) / w, (ver.ms_pool - bt_pool0) / w, bt_commit / w, bt_emit / w,+ (drive.d.multi_misses - bt_miss0) / (w * L), (drive.d.cache_hits - bt_hits0) / (w * L),+ (drive.d.pcie_experts - bt_pcie0) / (w * L), 1000.0 * bt_rows / std::max(wall, 1e-9), wall);+ for (size_t k = 0; k <= stages.size(); ++k) {+ const std::string pr = (k == 0 ? ver : stages[k - 1]->ver).profile_report();+ if (!pr.empty()) std::fprintf(stderr, "strata batch GPU stages, stage %zu (ms/window):%s\n", k + 1, pr.c_str());+ }+ bt_run = bt_commit = bt_emit = 0;+ bt_windows = bt_rows = bt_tokens = 0;+ }+ return true;+ };+ // ---- --batch-groups: the slot groups pipelined through the stages (--batch-groups G > 1 with a layer split)+ const int n_pipe = (int) stages.size() + 1;+ const bool piped = o.batch > 0 && o.batch_groups > 1 && n_pipe > 1;+ const int GS = piped ? o.batch / o.batch_groups : o.batch;+ struct PGroup {+ bool inflight = false;+ int stage = 0; ///< the stage it runs on or waits for+ int32_t tok[strata::kernels::kVerifyMaxT] = {};+ int64_t pos[strata::kernels::kVerifyMaxT] = {};+ int64_t since = 0; ///< tick it started waiting (fairness)+ };+ std::vector<PGroup> pg((size_t) (piped ? o.batch_groups : 0));+ std::vector<int> stage_group((size_t) n_pipe, -1);+ int64_t pipe_tick = 0, rr = 0;+ auto stage_verifier = [&](int k) -> strata::core::Verifier& { return k == 0 ? ver : stages[(size_t) k - 1]->ver; };+ auto pipe_inflight = [&] { for (const PGroup& x : pg) if (x.inflight) return true; return false; };+ auto group_active = [&](int gi) {+ for (int t = 0; t < GS; ++t) if (bs[(size_t) (gi * GS + t)].active) return true;+ return false;+ };+ // one turn: serve every running stage, hand finished groups on, start what can start+ auto pump = [&](bool may_start) -> bool {+ ++pipe_tick;+ if (bt_windows == 0 && !pipe_inflight()) {+ bt_start = Clock::now();+ bt_wait0 = ver.ms_wait; bt_pool0 = ver.ms_pool;+ bt_miss0 = drive.d.multi_misses; bt_hits0 = drive.d.cache_hits; bt_pcie0 = drive.d.pcie_experts;+ }+ for (int k = 0; k < n_pipe; ++k) {+ const int gi = stage_group[(size_t) k];+ if (gi < 0) continue;+ strata::core::Verifier& vk = stage_verifier(k);+ const int r = vk.batch_poll(win_pool_fn, win_pool_user, err);+ if (r < 0) { std::printf("ERR %s\n", err.c_str()); return false; }+ if (r == 0) continue;+ stage_group[(size_t) k] = -1;+ PGroup& G = pg[(size_t) gi];+ if (k + 1 < n_pipe) { G.stage = k + 1; G.since = pipe_tick; continue; }+ // the last stage: the group's picks+ const int32_t* outb = vk.batch_out();+ for (int t = 0; t < GS; ++t) {+ BSlot& sl = bs[(size_t) (gi * GS + t)];+ if (!sl.active) continue;+ const int32_t y = outb[t];+ std::printf("BT %d %d\n", gi * GS + t, (int) y);+ ++sl.produced;+ ++bt_rows;+ const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end();+ const char* fin = eos ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length"+ : sl.p + 2 > o.max_context ? "length" : nullptr;+ sl.ids.push_back(sl.x);+ if (fin != nullptr) {+ const double ms = std::chrono::duration<double, std::milli>(Clock::now() - sl.t0).count();+ std::printf("BDONE %d %lld %s %.1f\n", gi * GS + t, (long long) sl.produced, fin, ms);+ sl.active = false;+ sl.cached = false; // the pipeline's pad rows: a pipelined slot is not reused as a cache+ } else {+ sl.x = y;+ sl.p += 1;+ }+ }+ std::fflush(stdout);+ ++bt_windows;+ G.inflight = false;+ }+ // start waiting groups on free stages, the longest waiting first; a new step on stage 0 round-robin+ for (int k = n_pipe - 1; k >= 0; --k) {+ if (stage_group[(size_t) k] >= 0) continue;+ int pick = -1;+ if (k > 0) {+ for (int gi = 0; gi < (int) pg.size(); ++gi)+ if (pg[(size_t) gi].inflight && pg[(size_t) gi].stage == k &&+ (pick < 0 || pg[(size_t) gi].since < pg[(size_t) pick].since))+ pick = gi;+ if (pick < 0) continue;+ } else {+ if (!may_start) continue;+ for (int j = 0; j < (int) pg.size() && pick < 0; ++j) {+ const int gi = (int) ((rr + j) % (int64_t) pg.size());+ if (!pg[(size_t) gi].inflight && group_active(gi)) pick = gi;+ }+ if (pick < 0) continue;+ rr = pick + 1;+ PGroup& G = pg[(size_t) pick];+ for (int t = 0; t < GS; ++t) {+ BSlot& sl = bs[(size_t) (pick * GS + t)];+ G.tok[t] = sl.active ? sl.x : 0;+ G.pos[t] = sl.active ? sl.p : 0;+ if (!sl.active) sl.cached = false; // its pad row writes its state+ }+ G.inflight = true;+ G.stage = 0;+ drive.d.failed = false;+ apply_pending(false);+ }+ PGroup& G = pg[(size_t) pick];+ strata::core::progress().busy.store(true);+ if (!stage_verifier(k).batch_launch(pick * GS, GS, G.tok, G.pos, err)) {+ std::printf("ERR %s\n", err.c_str());+ return false;+ }+ stage_group[(size_t) k] = pick;+ }+ if (drive.d.failed) { std::printf("ERR %s\n", drive.d.fail ? drive.d.fail : "the expert pool failed"); return false; }+ if (!pipe_inflight() && !batch_on() && bt_windows > 0) { // all idle: the timing line, as batch_step+ const double w = (double) bt_windows, wall = std::chrono::duration<double, std::milli>(Clock::now() - bt_start).count();+ std::fprintf(stderr, "strata batch (pipelined, %d groups of %d): %lld group-steps, %lld rows in %.0f ms = "+ "%.1f rows/s (admissions included)\n", o.batch_groups, GS, (long long) bt_windows,+ (long long) bt_rows, wall, 1000.0 * bt_rows / std::max(wall, 1e-9));+ for (int k = 0; k < n_pipe; ++k) {+ const std::string pr = stage_verifier(k).profile_report();+ if (!pr.empty()) std::fprintf(stderr, "strata batch GPU stages, stage %d (ms/window):%s\n", k + 1, pr.c_str());+ }+ bt_windows = bt_rows = 0;+ strata::core::progress().busy.store(false);+ }+ return true;+ };+ auto pipe_drain = [&]() -> bool {+ while (pipe_inflight())+ if (!pump(false)) return false;+ return true;+ };+ for (;;) {+ if (batch_on() || (piped && pipe_inflight())) {+ if (!try_next_line(line)) {+ if (!(piped ? pump(true) : batch_step())) return 1;+ continue;+ }+ // a request reads its prompt through every stage: the groups in flight finish first+ if (piped && line.rfind("BSTOP ", 0) != 0 && !pipe_drain()) return 1;+ } else if (!next_line(line)) {+ break;+ }+ // --batch: BSTOP <slot> ends that slot at its next batch window; BGEN <slot> <max_new> ... reads the+ // request's prompt and first token as a GEN 1, then continues it in that slot+ if (line.rfind("BSTOP ", 0) == 0) {+ const int b = std::atoi(line.c_str() + 6);+ if (b >= 0 && b < (int) bs.size()) bs[(size_t) b].stop = true;+ continue;+ }+ if (line.rfind("BYIELD", 0) == 0) continue; // for a prompt read that has ended meanwhileif (line.rfind("VRAM", 0) == 0) { // #533 (above): between requests, not a requeststd::string verr;- if (!vram_command(line, verr)) std::printf("ERR %s\n", verr.c_str());+ if (batch_on()) verr = "VRAM: not while batch slots are decoding";+ else vram_command(line, verr);+ if (!verr.empty()) std::printf("ERR %s\n", verr.c_str());+ std::fflush(stdout);+ continue;+ }+ admit_slot = -1;+ if (line.rfind("BGEN ", 0) == 0 || line.rfind("BGENI ", 0) == 0) {+ const bool bimg = line.rfind("BGENI ", 0) == 0;+ char* e1 = nullptr;+ const long b = std::strtol(line.c_str() + (bimg ? 6 : 5), &e1, 10);+ char* e2 = nullptr;+ const long long mn = std::strtoll(e1, &e2, 10);+ if (bs.empty() || b < 0 || b >= (long) bs.size() || bs[(size_t) b].active || mn < 1 || e2 == e1) {+ std::printf("ERR BGEN: no such free slot (--batch %d) or a bad max_new\n", o.batch);+ std::fflush(stdout);+ continue;+ }+ admit_slot = (int) b;+ admit_max_new = mn;+ line = std::string(bimg ? "GENI 1" : "GEN 1") + e2;+ }+ // #477: every --expert-profile-save-every minutes, before the next request (at QUIT: after the loop)+ if (!heat.empty() && line != "QUIT" && o.expert_profile_save_min > 0 &&+ Clock::now() - profile_saved_at >= std::chrono::duration<double>(o.expert_profile_save_min * 60.0))+ save_profile("periodic");+ if (line == "QUIT") break;+ // the watchdog watches a request from here until this iteration ends, whichever way it ends+ struct BusyScope {+ BusyScope() {+ strata::core::progress().allow_until_ms.store(0);+ strata::core::progress().busy.store(true);+ strata::core::progress_at("request");+ }+ ~BusyScope() {+ strata::core::progress().busy.store(false);+ strata::core::progress().allow_until_ms.store(0);+ strata::core::progress_at("idle");+ }+ } busy_scope;+ stop_req.store(false); // a STOP that arrived between requests is stale+ err.clear();+ // Disk sessions: SAVE <path> | RESTORE <path>, between requests (the path runs to the end of the line,+ // UTF-8). The file holds what a parked conversation holds (conversation_file.hpp). Answers: SAVED /+ // RESTORED <tokens> <bytes> <ms>; SERR <invalid|storage|memory|io> <published 0|1> <reason> for a refusal+ // or failure that leaves the engine in step (the live session as it was, unless published=1 says the new+ // file already replaced the old one); FATAL <reason> (and the engine exits) for a restore transfer that+ // failed after the device state was touched. On the way: SESSION <done> <total> after every block of+ // the file moved (at most 16 MiB), and SWAIT <phase> <seconds> before a step that blocks in one call+ // (fingerprint file, state capture, file flush, rename + folder flush, validation, device transfer):+ // that step is allowed <seconds> (session_phase_limit_s) by the watchdog and by the server, no more.+ // (A verifier commit that fails before the command still answers ERR and exits, as for a request.)+ if (line.rfind("SAVE ", 0) == 0 || line.rfind("RESTORE ", 0) == 0) {+ const bool save = line[0] == 'S';+ const std::string path = line.substr(save ? 5 : 8);+ const auto t0 = Clock::now();+ auto ms = [&] { return std::chrono::duration<double, std::milli>(Clock::now() - t0).count(); };+ auto refuse = [&](const std::string& why, strata::core::SessionError kind = strata::core::SessionError::invalid,+ bool published = false) {+ std::fprintf(stderr, "strata serve: session %s %s: %s\n", save ? "save" : "restore", path.c_str(),+ why.c_str());+ std::string one = why; // one protocol line+ for (char& c : one) if (c == '\n' || c == '\r') c = ' ';+ std::printf("SERR %s %d %s\n", strata::core::session_error_name(kind), published ? 1 : 0, one.c_str());+ std::fflush(stdout);+ err.clear();+ };+ auto moving = [&](uint64_t done, uint64_t total) {+ strata::core::progress_at(save ? "writing a session file, MiB" : "reading a session file, MiB",+ (int64_t) (done >> 20));+ strata::core::progress_allow(0); // a block moved: the ordinary watchdog limit again, and a beat+ std::printf("SESSION %llu %llu\n", (unsigned long long) done, (unsigned long long) total);+ std::fflush(stdout);+ };+ // a step that blocks in one call: its explicit allowance, on both sides, announced before it starts+ auto blocking = [&](const char* phase, uint64_t bytes) {+ const int64_t s = strata::core::session_phase_limit_s(bytes);+ strata::core::progress_at(phase);+ strata::core::progress_allow(s);+ std::printf("SWAIT %s %lld\n", phase, (long long) s);+ std::fflush(stdout);+ };+ strata::core::progress_at(save ? "saving a session" : "restoring a session");+ if (path.empty()) { refuse("missing path"); continue; }+ if (!stages.empty() || multi_gpu) { refuse("session files do not support --layer-split"); continue; }+ if (o.peer_device >= 1) { refuse("session files do not support --peer-device"); continue; }+ if (o.batch > 0) { refuse("session files do not support --batch (parallel requests)"); continue; }+ if (o.prompt_cache <= 0) { refuse("session files need --prompt-cache > 0"); continue; }+ if (!ver.wait_commit(err)) {+ std::printf("ERR %s\n", err.c_str());+ return 1;+ }+ strata::core::SessionFileIdentity id;+ try {+ if (!session_identity(id, err, [&] { blocking("fingerprint", 2u << 20); })) {+ refuse(err, strata::core::SessionError::io);+ continue;+ }+ } catch (const std::bad_alloc&) {+ refuse("session identity: out of memory", strata::core::SessionError::memory);+ continue;+ } catch (const std::exception& e) {+ refuse(std::string("session identity: ") + e.what(), strata::core::SessionError::io);+ continue;+ }+ if (save) {+ if (!live_ok || live.empty()) { refuse("no complete session to save"); continue; }+ size_t bytes = 0, kept = 0;+ double capture_ms = 0;+ try {+ // RAM PREFLIGHT for the save (not a reservation), BEFORE anything is copied: the deepest+ // checkpoint is chosen by reference, and the copies it will take (the list below and the one+ // in `meta`), the copied live running state with its tokens and images, the K/V source+ // directory and the 16 MiB write buffer are asked for above the parking floor. Only the+ // deepest checkpoint goes to disk (the next turn's resume point); the K/V is streamed from+ // the authoritative pools straight into the file, without a full host capture.+ strata::core::SessionSaveLive sl;+ {+ strata::core::ConversationStateSizes z;+ std::string why;+ uint64_t state = UINT64_MAX; // unknown sizes: the preflight refuses rather than guesses+ if (strata::core::conversation_session_sizes(g, ss, z, why)) {+ const uint64_t q = (uint64_t) std::max<int64_t>(ss.qsa_alloc, 0);+ const uint64_t per = (uint64_t) z.tail + z.dead + z.block_pos;+ if (q == 0 || per <= (UINT64_MAX - z.gdn - z.ple) / q) state = z.gdn + z.ple + q * per;+ }+ sl.state_bytes = state;+ sl.tokens = live.size();+ sl.images = live_imgs.size();+ sl.kv_layers = (uint64_t) std::max<int64_t>(ss.qsa_alloc, 0) + 1;+ }+ const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20;+ auto admit = [&](uint64_t need, std::string& why) {+ const auto avail = strata::core::conversation_available_memory();+ if (strata::core::conversation_memory_admit(avail, need, floor)) return true;+ why = "not enough RAM to save the session (" ++ (need == UINT64_MAX ? std::string("unknown") : std::to_string(need >> 20)) ++ " MiB plus a floor of " + std::to_string((long long) o.conversation_cache_min_free_mib) ++ " MiB needed, " + (avail ? std::to_string(*avail >> 20) + " MiB available)"+ : "RAM telemetry unavailable)");+ return false;+ };+ std::vector<ConvCheckpoint> disk_checks;+ std::string why;+ if (!strata::core::session_save_checkpoints(checks, sl, admit, disk_checks, why)) {+ refuse(why, strata::core::SessionError::memory);+ continue;+ }+ kept = disk_checks.size();+ const strata::core::ConversationView view{live, live_imgs, disk_checks, cvec_cached};+ strata::core::SavedConversation meta;+ std::vector<strata::core::SessionKvSource> sources;+ // the live running state comes off the device in one synchronous copy+ blocking("capture", sl.state_bytes == UINT64_MAX ? 0 : sl.state_bytes);+ if (!strata::core::conversation_snapshot_sources(meta, sources, view, ss, g, mtp.kv_state(),+ err)) {+ refuse(err, strata::core::SessionError::io);+ continue;+ }+ capture_ms = ms();+ strata::core::SessionWriteOptions wo;+ wo.min_free_bytes = (uint64_t) o.session_min_free_mib << 20;+ wo.progress = moving;+ wo.phase = blocking;+ strata::core::SessionStatus st;+ if (!strata::core::session_file_write(path, meta, sources, id, bytes, err, wo, &st)) {+ refuse(err, st.error, st.published);+ continue;+ }+ if (st.dir_flush_unsupported)+ std::fprintf(stderr, "strata serve: session saved to %s; this filesystem cannot flush a "+ "folder, so the new name is not flushed\n", path.c_str());+ } catch (const std::bad_alloc&) {+ refuse("not enough RAM to save the session", strata::core::SessionError::memory);+ continue;+ }+ std::fprintf(stderr, "strata serve: session saved %zu tokens, %zu of %zu checkpoints, %zu bytes to %s "+ "in %.1f ms (state %.1f ms)\n", live.size(), kept, checks.size(), bytes,+ path.c_str(), ms(), capture_ms);+ std::printf("SAVED %zu %zu %.1f\n", live.size(), bytes, ms());+ } else {+ strata::core::SavedConversation image;+ size_t bytes = 0;+ try {+ // bounds this session can ever restore (geometry, layer range, tokens, checkpoints, every+ // state and K/V part), checked as the file is parsed and before each array is allocated; the+ // file size follows from them. The RAM the parse needs at its peak is asked first.+ strata::core::SessionReadLimits limits;+ limits.progress = moving;+ const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20;+ limits.admit = [floor, &o](uint64_t need, std::string& why) {+ const auto avail = strata::core::conversation_available_memory();+ if (strata::core::conversation_memory_admit(avail, need, floor)) return true;+ why = "not enough RAM to read it (" + std::to_string(need >> 20) + " MiB plus a floor of " ++ std::to_string((long long) o.conversation_cache_min_free_mib) + " MiB needed, " ++ (avail ? std::to_string(*avail >> 20) + " MiB available)" : "RAM telemetry unavailable)");+ return false;+ };+ if (!strata::core::conversation_session_read_limits(+ limits, ss, g, mtp.kv_state(), (uint64_t) o.max_context,+ (uint64_t) std::max(o.prompt_cache, 1), err)) {+ refuse(err, strata::core::SessionError::io);+ continue;+ }+ strata::core::SessionStatus st;+ if (!strata::core::session_file_read(path, id, image, bytes, err, limits, &st)) {+ refuse(err, st.error);+ continue;+ }+ } catch (const std::bad_alloc&) {+ refuse("not enough RAM to read the session", strata::core::SessionError::memory);+ continue;+ }+ const double read_ms = ms();+ // the whole image against this engine, still without any device write+ blocking("validate", bytes);+ if (!strata::core::conversation_snapshot_validate(image, ss, g, mtp.kv_state(), err)) {+ refuse(err);+ continue;+ }+ // the elastic K/V (--kv-grow) maps only the cells it has grown to: make room for the file's cells+ if (!kvg_ensure((int64_t) image.live.ids.size() + 256, [&] {+ dpct::get_current_device()+ .queues_wait_and_throw();+ apply_pending(+ true); })) {+ refuse("the K/V cannot grow to the saved conversation: no VRAM is left", strata::core::SessionError::memory);+ continue;+ }+ conversations.take_reuse(); // retained K/V described the outgoing session+ live_ok = false;+ // host -> device in synchronous copies of the whole state: one bounded allowance+ blocking("transfer", bytes);+ if (strata::core::conversation_snapshot_restore(image, ss, g, mtp.kv_state(), err) !=+ strata::core::ConversationRestore::restored) {+ // validated above: a failure here is a transfer failure, after device writes began - never+ // decode from a partial state; the server starts the engine again+ std::fprintf(stderr, "strata serve: session restore %s: transfer failed: %s\n", path.c_str(),+ err.c_str());+ std::printf("FATAL restoring the session file failed after the device state was changed: %s\n",+ err.c_str());+ std::fflush(stdout);+ return 1;+ }+ live = std::move(image.live.ids);+ live_imgs = std::move(image.live.imgs);+ checks = std::move(image.checkpoints);+ for (const ConvCheckpoint& c : checks) check_clock = std::max(check_clock, c.used);+ cvec_cached = image.cvec;+ live_ok = true;+ std::fprintf(stderr, "strata serve: session restored %zu tokens, %zu checkpoints, %zu bytes from %s "+ "in %.1f ms (read+check %.1f ms)\n", live.size(), checks.size(), bytes, path.c_str(),+ ms(), read_ms);+ std::printf("RESTORED %zu %zu %.1f\n", live.size(), bytes, ms());+ }std::fflush(stdout);continue;}- // #477: every --expert-profile-save-every minutes, before the next request (at QUIT: after the loop)- if (!heat.empty() && line != "QUIT" && o.expert_profile_save_min > 0 &&- Clock::now() - profile_saved_at >= std::chrono::duration<double>(o.expert_profile_save_min * 60.0))- save_profile("periodic");- if (line == "QUIT") break;- // the watchdog watches a request from here until this iteration ends, whichever way it ends- struct BusyScope {- BusyScope() { strata::core::progress().busy.store(true); strata::core::progress_at("request"); }- ~BusyScope() { strata::core::progress().busy.store(false); strata::core::progress_at("idle"); }- } busy_scope;- stop_req.store(false); // a STOP that arrived between requests is stale- err.clear();const bool geni = line.rfind("GENI ", 0) == 0;if (!geni && line.rfind("GEN ", 0) != 0) {std::printf("ERR expected: GEN <max_new> <id,id,...> or GENI <max_new> <file> <id,id,...>\n");@@ -6313,6 +9125,11 @@ int main(int argc, char **argv) try {// log-probability and the K most likely tokens', from the verify window's head logits (before sampling,// penalties and temperature). -1 (absent): no LP lines; a server that does not ask never sees one.int req_logprobs = -1;+ // ckpt=0: a one-shot call whose turn no later request extends. No checkpoint at its last turn boundary+ // (so no split there) nor every --prompt-cache-every tokens, and its session is neither continued nor+ // parked after it. It still resumes from a checkpoint it matches, and still saves the system-prompt root+ // when that reaches --prompt-cache-root. Absent = checkpointed as before.+ int req_ckpt = 1;// tuning keys (setup's calibration measures settings without restarting the engine): the PCIe share of// the missed experts and the draft-probability floor, for this request onlydouble req_pcie_frac = o.pcie_frac, req_spec_min_p = o.spec_min_p;@@ -6329,6 +9146,7 @@ int main(int argc, char **argv) try {const std::string key = tok.substr(0, eq);const float fv = std::strtof(tok.c_str() + eq + 1, nullptr);if (key == "cvec") req_cvec = std::atoi(tok.c_str() + eq + 1);+ else if (key == "ckpt") req_ckpt = std::atoi(tok.c_str() + eq + 1) != 0;else if (key == "temperature") req_temperature = fv;else if (key == "top_p") req_top_p = fv;else if (key == "top_k") req_top_k = std::atoi(tok.c_str() + eq + 1);@@ -6507,6 +9325,23 @@ int main(int argc, char **argv) try {std::printf("ERR %s\n", err.c_str());return 1;}+ auto kv_quiesce = [&] {+ try {+ dpct::get_current_device().queues_wait_and_throw(); apply_pending(true); }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ if (kvg.on) { // the elastic K/V: this prompt's cells (it gives back what it does not need below)+ // a failed growth may leave the tier half-changed: the engine stops (as for any CUDA failure)+ if (!kvg_ensure(n + 256, kv_quiesce)) {+ std::printf("ERR the K/V cannot grow to this prompt: no VRAM is left\n");+ std::fflush(stdout);+ return 1;+ }+ }int64_t resume = 0;bool from_live = false;if (o.prompt_cache > 0 && want_cvec == cvec_cached) {@@ -6517,51 +9352,159 @@ int main(int argc, char **argv) try {from_live = false;}}+ // --batch: an idle slot that holds the start of this prompt (the conversation it served last) is a+ // source too - its sessions are copied back below, so only the new part is read+ int slot_source = -1;+ int64_t slot_tokens = 0;+ bool resumed_from0 = false; // a prompt read parked in a slot (BYIELD) that had started at token 0+ const ConvCheckpoint* slot_ck = nullptr; // the slot's checkpoint the prompt continues from (else its end)+ if (o.prompt_cache > 0 && req_imgs.empty())+ for (int b = 0; b < (int) bs.size(); ++b) {+ const BSlot& sl = bs[(size_t) b];+ if (sl.active || !sl.cached || sl.cvec != want_cvec) continue;+ if ((int64_t) sl.ids.size() > std::max(resume, slot_tokens) && starts_with(sl.ids, {})) {+ slot_source = b;+ slot_tokens = (int64_t) sl.ids.size();+ slot_ck = nullptr;+ }+ for (const ConvCheckpoint& c : sl.checks)+ if ((int64_t) c.ids.size() > std::max(resume, slot_tokens) && starts_with(c.ids, c.imgs)) {+ slot_source = b;+ slot_tokens = (int64_t) c.ids.size();+ slot_ck = &c;+ }+ }const auto parked = conversations.best(ids, req_imgs, want_cvec);std::optional<strata::core::SavedConversation> incoming;- if (parked.tokens > resume) incoming.emplace(conversations.take(parked.index));+ if (parked.tokens > std::max(resume, slot_tokens)) incoming.emplace(conversations.take(parked.index));+ if (incoming) slot_source = -1;// Reject the entire image before parking/overwriting the outgoing// state. Invalid entries can safely fall back to its existing prefix.- if (incoming && !strata::core::conversation_snapshot_validate(*incoming, ss, g, mtp.kv_state(), err)) {+ if (incoming && incoming->stage_images.size() != stages.size()) {+ std::fprintf(stderr, "strata serve: conversation cache: discard snapshot (stage count)\n");+ incoming.reset();+ }+ if (incoming) for (size_t i = 0; i < stages.size(); ++i) {+ const strata::core::OnDevice on(stages[i]->dev);+ if (!strata::core::conversation_snapshot_validate(incoming->stage_images[i], stages[i]->ss, g,+ use_mtp && i + 1 == stages.size() ? &mtp.kv_state() : nullptr, err)) { // the draft: the last stage's+ std::fprintf(stderr, "strata serve: conversation cache: discard invalid stage snapshot (%s)\n",+ err.c_str());+ incoming.reset();+ err.clear();+ break;+ }+ }+ if (incoming && !strata::core::conversation_snapshot_validate(*incoming, ss, g,+ use_mtp && stages.empty() ? &mtp.kv_state() : nullptr, err)) {std::fprintf(stderr, "strata serve: conversation cache: discard invalid snapshot (%s)\n", err.c_str());incoming.reset();err.clear();}// Preserve the outgoing branch before any checkpoint rewind, reset,// or incoming restore overwrites the positional state it requires.- if ((!from_live || incoming) && !park_current(incoming ? incoming->bytes() : 0)) {+ if ((!from_live || incoming || slot_source >= 0) && !park_current(incoming ? incoming->bytes() : 0)) {std::printf("ERR %s\n", err.c_str());return 1;}+ if (slot_source >= 0) {+ const auto t0 = Clock::now();+ if (!copy_from_slot(slot_source, slot_ck, err)) {+ // the main session may be half written: read this prompt from the start+ std::fprintf(stderr, "strata batch: restoring slot %d failed (%s); reading the prompt\n",+ slot_source, err.c_str());+ err.clear();+ live.clear();+ live_imgs.clear();+ checks.clear();+ resume = 0;+ from_live = false;+ } else {+ checks.clear(); // the main session's checkpoints were of the conversation it held before+ // a read that gave way, the same request again (into its own slot): on with it - its segments and+ // checkpoints as if it had not stopped+ if (slot_ck == nullptr && bs[(size_t) slot_source].partial && admit_slot == slot_source) {+ resumed_from0 = bs[(size_t) slot_source].partial_from0;+ for (const ConvCheckpoint& c : bs[(size_t) slot_source].checks) checks.push_back(c);+ bs[(size_t) slot_source].partial = false;+ }+ if (slot_ck != nullptr) {+ live = slot_ck->ids;+ checks.push_back(*slot_ck); // the main session's chain has it now+ checks.back().used = ++check_clock;+ } else {+ live = bs[(size_t) slot_source].ids;+ }+ live_imgs.clear();+ resume = slot_tokens;+ from_live = true;+ std::fprintf(stderr, "strata batch: slot %d gave back %lld tokens of this conversation (%s) in "+ "%.1f ms\n", slot_source, (long long) slot_tokens,+ slot_ck != nullptr ? "its turn checkpoint" : "all it holds",+ std::chrono::duration<double, std::milli>(Clock::now() - t0).count());+ }+ }+ // the elastic K/V: a parked conversation is restored whole, and it may be longer than this prompt+ if (incoming && !kvg_ensure((int64_t) incoming->live.ids.size() + 256, kv_quiesce)) {+ std::printf("ERR the K/V cannot grow to the parked conversation: no VRAM is left\n");+ return 1;+ }if (incoming) {const auto t0 = Clock::now();- if (strata::core::conversation_snapshot_restore(*incoming, ss, g, mtp.kv_state(), err) !=+ if (strata::core::conversation_snapshot_restore(*incoming, ss, g,+ use_mtp && stages.empty() ? &mtp.kv_state() : nullptr, err) !=strata::core::ConversationRestore::restored) {// Already prevalidated above: a failure here is fatal, never// permission to decode from a partially restored session.std::printf("ERR restoring parked conversation: %s\n", err.c_str());return 1;}- if (std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr) {+ for (size_t i = 0; i < stages.size(); ++i) { // the later stages' parts+ const strata::core::OnDevice on(stages[i]->dev);+ if (strata::core::conversation_snapshot_restore(incoming->stage_images[i], stages[i]->ss, g,+ use_mtp && i + 1 == stages.size() ? &mtp.kv_state() : nullptr, err) !=+ strata::core::ConversationRestore::restored) {+ std::printf("ERR restoring parked conversation (stage CUDA%d): %s\n", stages[i]->dev,+ err.c_str());+ return 1;+ }+ if (DPCT_CHECK_ERROR(dpct::get_current_device()+ .queues_wait_and_throw()) != 0) {+ std::printf("ERR stage sync\n"); return 1;+ }+ }+ if (use_mtp && std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr) {uint64_t draft_hash = 0;- if (!strata::core::conversation_kv_verify(incoming->kv.back(), mtp.kv_state(), g,+ const auto& draft_kv = stages.empty() ? incoming->kv.back() : incoming->stage_images.back().kv.back();+ const strata::core::OnDevice on_d(stages.empty() ? 0 : stages.back()->dev);+ if (!strata::core::conversation_kv_verify(draft_kv, mtp.kv_state(), g,int64_t(incoming->live.ids.size()), false, draft_hash, err)) {std::printf("ERR verifying restored draft KV: %s\n", err.c_str());return 1;}std::fprintf(stderr, "strata serve: SNAPSHOT_VERIFY draft=%016llx cells=%lld mode=%d source=%s resident=%lld\n",- (unsigned long long) draft_hash, (long long) incoming->kv.back().cells,+ (unsigned long long) draft_hash, (long long) draft_kv.cells,mtp.kv_state().kv_mode, "ram",(long long) (mtp.kv_state().n_slots * strata::kernels::qsa_real_shapes().page_size));}live = std::move(incoming->live.ids);live_imgs = std::move(incoming->live.imgs);- checks = std::move(incoming->checkpoints);+ if (stages.empty()) {+ checks = std::move(incoming->checkpoints);+ } else { // give each checkpoint back its stage parts (moved, not copied); none if they do not line up+ strata::core::ConversationCheckpointSplit cs;+ cs.stage0 = std::move(incoming->checkpoints);+ for (auto& si : incoming->stage_images) cs.parts.push_back(std::move(si.checkpoints));+ if (!strata::core::conversation_checkpoints_merge(std::move(cs), checks)) checks.clear();+ }cvec_cached = incoming->cvec;resume = parked.tokens;from_live = parked.live;- if (std::getenv("STRATA_SNAPSHOT_FULL_CAPTURE") == nullptr)- conversations.retain(std::move(incoming->kv), int64_t(live.size()));+ if (std::getenv("STRATA_SNAPSHOT_FULL_CAPTURE") == nullptr) {+ std::vector<std::vector<strata::core::ConversationKv>> stage_kv; // every stage's, for its next park+ for (auto& si : incoming->stage_images) stage_kv.push_back(std::move(si.kv));+ conversations.retain(std::move(incoming->kv), int64_t(live.size()), std::move(stage_kv));+ }incoming.reset(); // Running-state/checkpoint copies are no longer needed.std::fprintf(stderr, "strata serve: conversation cache: restored %lld tokens (%s) in %.1f ms; parked=%zu bytes=%zu\n",(long long) resume, from_live ? "live" : "checkpoint",@@ -6580,6 +9523,16 @@ int main(int argc, char **argv) try {return (int64_t) c.ids.size() > resume || !starts_with(c.ids, c.imgs);}), checks.end());live_ok = false; // until this request has finished, the session is in between+ // the elastic K/V: the outgoing session is parked and this request rewrites every cell from `resume` on,+ // so cells past this prompt's are no longer anyone's - far more than it needs go back to the cache+ if (kvg.on) {+ kv_quiesce();+ if (!kvg_trim(n + 256)) {+ std::printf("ERR the K/V could not give its VRAM back to the expert cache\n");+ std::fflush(stdout);+ return 1;+ }+ }int64_t reread_to = -1; // STRATA_CKPT_REREAD only: read [0, reread_to) again instead of restoringif (resume == 0) {strata::core::session_zero(ss, g, nullptr, main_cs);@@ -6625,16 +9578,17 @@ int main(int argc, char **argv) try {}// KV streaming: the drafter's ring may hold cells past `resume` from a longer turn; the main layers'// host copies and slots are always current (every writer writes both), so they need nothing- if (resume > 0 && reread_to <= 0) mtp.kv_restore(resume);+ if (use_mtp && resume > 0 && reread_to <= 0) mtp.kv_restore(resume);tr("request", n, geni ? 1 : 0);- mtp.set_prompt_len(n);+ if (use_mtp) mtp.set_prompt_len(n);const int64_t read_from = reread_to > 0 ? 0 : resume;conversations.limit_reuse(read_from);pp_total = n;pp_from = read_from;pp_reached = read_from;pp_t0 = r0;- pp_next_check = reread_to > 0 ? INT64_MAX : resume + o.prompt_cache_every;+ pp_next_check = reread_to > 0 || !req_ckpt ? INT64_MAX : resume + o.prompt_cache_every; // ckpt=0: none+ pp_tail_saved = reread_to > 0 || !req_ckpt; // ckpt=0 (#861): no tail checkpoint either{std::lock_guard<std::mutex> lk(part_mu);part_at.clear();@@ -6651,15 +9605,135 @@ int main(int argc, char **argv) try {// read batched and its header still goes through the windows. Picture rows need the batched path.// STRATA_CKPT_REREAD compares a restored checkpoint with a batched re-read, so it keeps every read batched.static const bool no_short = std::getenv("STRATA_CKPT_REREAD") != nullptr;+ int64_t req_short_read = o.short_read; // STRATA_PIPELINE_SWITCH may set it per request (short_read=)auto windows_ok = [&](int64_t a, int64_t b) -> bool {- if (no_short || b - a > o.short_read) return false;+ if (no_short || b - a > req_short_read) return false;if (sp.embd_rows != nullptr)for (int64_t i = a; i < b; ++i)if (sp.embd_rows[i] != nullptr) return false;return true;};+ // --pipeline-windows, testing: STRATA_PIPELINE_SWITCH=<file> is read at every request, "pw=<0|1|2>+ // theta=<f> force_miss=<k> short_read=<n>" - an A/B of the pipelined and the serial loops (and forced+ // rollbacks) on one server, with the same expert placement+ int pl_pw = pipe ? o.pipeline_windows : 0;+ float pl_theta = [] { // a speculative window is launched only when its estimated chance is at least this+ const char* v = pipe_dbg_env("STRATA_PIPELINE_THETA");+ return v ? (float) std::atof(v) : 0.2f;+ }();+ int pl_force_miss = [] { // exactness test: every k-th speculative window gets a wrong first token+ const char* v = pipe_dbg_env("STRATA_PIPELINE_FORCE_MISS");+ return v ? std::max(0, std::atoi(v)) : 0;+ }();+ if (static const char* sw = pipe_dbg_env("STRATA_PIPELINE_SWITCH"); sw != nullptr && pipe) {+ if (std::FILE* f = std::fopen(sw, "r")) {+ char buf[256] = {};+ const size_t nr = std::fread(buf, 1, sizeof buf - 1, f);+ std::fclose(f);+ buf[nr] = 0;+ if (const char* q = std::strstr(buf, "pw=")) pl_pw = std::max(0, std::min(2, std::atoi(q + 3)));+ if (const char* q = std::strstr(buf, "theta=")) pl_theta = (float) std::atof(q + 6);+ if (const char* q = std::strstr(buf, "force_miss=")) pl_force_miss = std::max(0, std::atoi(q + 11));+ if (const char* q = std::strstr(buf, "short_read=")) req_short_read = std::max(0LL, std::atoll(q + 11));+ std::fprintf(stderr, "strata pipeline switch: pw=%d theta=%.3f force_miss=%d short_read=%lld\n", pl_pw,+ pl_theta, pl_force_miss, (long long) req_short_read);+ }+ }+ // --pipeline-windows: tokens [a, b) through the windows with the stages overlapped. The tokens are known,+ // so every window commits whole: stage 0 queues window K, its commit and window K+1 back to back (each+ // parity's verifier keeps its own window), and stage 1 runs window K once stage 0 is done with it. Every+ // stage runs the same windows in the same order as read_windows below, so the session ends the same.+ auto read_windows_pl = [&](int64_t a, int64_t b, std::string& e) -> bool {+ strata::core::progress_at("reading the prompt (pipelined verify windows), from token", a);+ if (!pl_prepare(e)) return false;+ for (int par = 0; par < 2; ++par) PV[0][par]->set_head_sampling(false); // reaches stage 1 (set_next)+ struct Restore {+ strata::core::Verifier* v[2];+ ~Restore() { v[0]->set_head_sampling(true); v[1]->set_head_sampling(true); }+ } restore{{PV[0][0], PV[0][1]}};+ struct Win { int T; int64_t q; };+ std::vector<Win> wins;+ for (int64_t q = a; q < b;) {+ const int T = (int) std::min<int64_t>(S, b - q);+ wins.push_back({T, q});+ q += T;+ }+ const size_t N = wins.size();+ std::vector<int32_t> w0((size_t) S), w1((size_t) S), nx((size_t) S);+ size_t l0 = 0, f0 = 0, l1 = 0, f1 = 0; // stage 0 launched / finished, stage 1 launched / finished+ drive.d.layers = 0;+ drive.d.experts = 0;+ drive.d.failed = false;+ auto fail = [&](std::string why) -> bool {+ pl_drain();+ e = why.empty() ? std::string("a pipelined prompt window failed") : why;+ return false;+ };+ while (f1 < N) {+ if (stop_req.load()) return fail("cancelled");+ // stage 0: up to two windows queued; window K+2 (K's parity) only once stage 1 has finished window+ // K, whose hand-off K+2 overwrites+ while (l0 < N && l0 < f0 + 2 && l0 < f1 + 2) {+ const Win& w = wins[l0];+ for (int t = 0; t < w.T; ++t) w0[(size_t) t] = (int32_t) cur[(size_t) (w.q + t)];+ strata::core::Verifier& v = *PV[0][l0 & 1];+ if (!v.pl_launch(w.T, w0.data(), w.q, e) || !v.pl_commit_async(w.T, e)) return fail(e);+ ++l0;+ }+ if (f0 < l0) {+ strata::core::Verifier& v = *PV[0][f0 & 1];+ if (v.service(win_pool_fn, PSD[f0 & 1], e) < 0) return fail(e);+ if (v.done(e)) {+ if (!v.pl_finish(nullptr, e)) return fail(e);+ ++f0;+ } else if (!e.empty()) return fail(e);+ }+ if (l1 < f0 && l1 == f1) { // stage 1: the next window, its stage 0 done+ const Win& w = wins[l1];+ for (int t = 0; t < w.T; ++t) w1[(size_t) t] = (int32_t) cur[(size_t) (w.q + t)];+ strata::core::Verifier& v = *PV[1][l1 & 1];+ if (pl_mtp_live[l1 & 1]) { // the drafter has read this parity's previous rows first+ const strata::core::OnDevice on(mtp.device());+ (v.stream())+ ->ext_oneapi_submit_barrier(+ {*pl_mtp_ev[l1 & 1]});+ }+ if (!v.pl_launch(w.T, w1.data(), w.q, e) || !v.pl_commit_async(w.T, e)) return fail(e);+ ++l1;+ }+ if (f1 < l1) {+ strata::core::Verifier& v = *PV[1][f1 & 1];+ if (v.service(win_pool_fn, PSD[f1 & 1], e) < 0) return fail(e);+ if (v.done(e)) {+ if (!v.pl_finish(nullptr, e)) return fail(e);+ const Win& w = wins[f1];+ for (int t = 0; t < w.T; ++t) nx[(size_t) t] = (int32_t) cur[(size_t) (w.q + t + 1)];+ if (!mtp.prefill(v.final_R(0), nx.data(), w.T, w.q, e, false)) return fail(e);+ {+ const strata::core::OnDevice on(mtp.device());+ dpct::sync_barrier(pl_mtp_ev[f1 & 1],+ mtp.stream());+ }+ pl_mtp_live[f1 & 1] = true;+ pp_reached = w.q + w.T; // #471+ ++f1;+ } else if (!e.empty()) return fail(e);+ }+ if (drive.d.failed) return fail(drive.d.fail ? drive.d.fail : "the expert pool failed");+ }+ pl_drain(); // nothing in flight: both stages' commits and the drafter's rows have landed+ pl_mtp_live[0] = pl_mtp_live[1] = false;+ const double ms = std::chrono::duration<double, std::milli>(Clock::now() - pp_t0).count();+ std::printf("PP %lld %lld %.0f %.1f\n", (long long) b, (long long) pp_total, ms,+ ms > 0.0 ? 1000.0 * (double) (b - pp_from) / ms : 0.0);+ strata::core::progress_beat();+ std::fflush(stdout);+ return true;+ };// tokens [a, b) through the windows: commit all of them, then give the draft layer their residualsauto read_windows = [&](int64_t a, int64_t b, std::string& e) -> bool {+ // (STRATA_LOGPOS reads every window's logits: the serial loop)+ if (pipe && pl_pw >= 1 && std::getenv("STRATA_LOGPOS") == nullptr) return read_windows_pl(a, b, e);strata::core::progress_at("reading the prompt (verify windows), from token", a); // #217: not "batched"// every token is committed and the picks are discarded: no head sampling (see set_head_sampling)struct NoHeadSampling {@@ -6696,7 +9770,7 @@ int main(int argc, char **argv) try {}();if (logpos != nullptr && !ver.window_logprobs(nxt.data(), T, q, logpos_extra, logpos, e))return false;- if (!ver.commit(T, e) || !mtp.prefill(ver.final_R_all(), nxt.data(), T, q, e)) return false;+ if (!ver.commit(T, e) || (use_mtp && !mtp.prefill(ver.final_R_all(), nxt.data(), T, q, e))) return false;q += T;pp_reached = q; // #471}@@ -6735,6 +9809,11 @@ int main(int argc, char **argv) try {auto refill_wait = [&](PfPart& p, std::string& e) -> bool {const strata::core::OnDevice on(p.dev);if (!p.cache->sync_queued(e)) return false;+#if defined(_WIN32)+ // The copies have landed: the file pages touched by the loan need not stay in the working set.+ for (const auto& [i, slot] : p.lent)+ srcp->release(i / g.n_expert, i % g.n_expert);+#endifp.lent.clear();p.lent_chunk = 0;return true;@@ -6778,7 +9857,7 @@ int main(int argc, char **argv) try {const auto t_ln = Clock::now();// what this segment needs, capped by the configured chunk: a request lends only what its own// prompt needs, so a large chunk costs a short prompt nothing- const int64_t want_full = request_chunk(tokens, o.prefill_chunk);+ const int64_t want_full = equal_chunk(tokens, o.prefill_chunk);// #340: a short enough request reads in the stages' own S-token chunks (nothing lent)const int64_t want = split_small > 0 && tokens <= split_small_max ? std::min(want_full, split_small): want_full;@@ -6823,7 +9902,104 @@ int main(int argc, char **argv) try {}return true;};+ // --batch: a prompt read while slots are decoding goes one prompt chunk at a time (the same chunks as one+ // run: each run starts where the last ended, at a multiple of the chunk), and between two chunks the slots+ // decode for a share of the time the chunk took (STRATA_BATCH_DECODE_SHARE, default 0.5), so a long+ // prompt does not stop the others. The slots' windows then see the cache without the slots this prompt+ // borrowed (marked missing: those experts run on the CPU), never a prompt buffer.+ static const double decode_share = [] {+ const char* v = std::getenv("STRATA_BATCH_DECODE_SHARE");+ return v != nullptr ? std::max(0.0, std::atof(v)) : 0.5;+ }();+ bool batch_fatal = false;+ int64_t il_parts = 0; // the slots' windows run between this prompt's chunks+ double il_ms = 0;+ int64_t yielded_at = -1; // BYIELD: the read stopped here and its slot holds it+ int yielded_slot = -1;+ // `BYIELD <slot>` (the server: a shorter request is waiting): at the next chunk boundary the part read so+ // far is copied into <slot> (this admission's own, or a free one the server reserved for a solo request),+ // the request ends with `YIELDED <slot> <tokens>` + DONE cancel, and the server sends it again later: it+ // continues from the slot with the same chunks. #656's cooperative preemption, with a slot as the park.+ auto read_part = [&](int64_t a0, int64_t b0, std::string& e) -> bool {+ // (a layer split reads its stages as a pipeline over one run's chunks: in pieces only beside slots)+ if (o.batch <= 0 || piped || (!stages.empty() && !batch_on())) return sp.run(ids.data() + a0, b0 - a0, a0, e);+ const int64_t C = std::max<int64_t>(sp.chunk(), 1);+ for (int64_t q = a0; q < b0;) {+ const int64_t r = std::min(b0, q + C);+ const auto tq = Clock::now();+ if (!sp.run(ids.data() + q, r - q, q, e)) return false;+ q = r;+ if (q >= b0) continue;+ int ys = -1;+ { // a BSTOP that came meanwhile ends its slot at its next window; a BYIELD is for this read+ std::lock_guard<std::mutex> lk(in_mu);+ for (auto it = in_lines.begin(); it != in_lines.end();) {+ if (it->rfind("BSTOP ", 0) == 0) {+ const int b = std::atoi(it->c_str() + 6);+ if (b >= 0 && b < (int) bs.size()) bs[(size_t) b].stop = true;+ it = in_lines.erase(it);+ } else if (it->rfind("BYIELD ", 0) == 0) {+ ys = std::atoi(it->c_str() + 7);+ it = in_lines.erase(it);+ } else {+ ++it;+ }+ }+ }+ if (ys >= 0) {+ // only where the rest is read the same way after it (more than a chunk and more than a short+ // read left), text only, and into a slot that is not decoding+ const bool can = ys < (int) bs.size() && !bs[(size_t) ys].active &&+ (admit_slot < 0 || ys == admit_slot) && req_imgs.empty() && o.prompt_cache > 0 &&+ b0 - q > std::max<int64_t>(C, o.short_read);+ std::string ye;+ const auto ty = Clock::now();+ std::vector<int32_t> pre(ids.begin(), ids.begin() + q);+ if (can && copy_to_slot(ys, pre, ye)) {+ BSlot& sl = bs[(size_t) ys];+ sl = BSlot{};+ sl.ids = std::move(pre);+ sl.cached = true;+ sl.partial = true;+ sl.partial_from0 = read_from == 0 || resumed_from0;+ sl.cvec = cvec_cached;+ for (const ConvCheckpoint& c : checks) // the root / periodic checkpoints of this read+ if ((int64_t) c.ids.size() <= q && std::equal(c.ids.begin(), c.ids.end(), ids.begin(),+ [](int32_t x, int64_t y) { return (int64_t) x == y; }))+ sl.checks.push_back(c);+ yielded_at = q;+ yielded_slot = ys;+ std::fprintf(stderr, "strata batch: the prompt read gives way at %lld of %lld tokens; slot %d "+ "holds it (copied in %.1f ms)\n", (long long) q, (long long) n, ys,+ std::chrono::duration<double, std::milli>(Clock::now() - ty).count());+ e = "yield";+ return false;+ }+ if (can) bs[(size_t) ys].cached = false; // half written+ std::fprintf(stderr, "strata batch: BYIELD %d not taken at %lld of %lld%s%s\n", ys, (long long) q,+ (long long) n, ye.empty() ? "" : ": ", ye.c_str());+ }+ if (decode_share <= 0.0 || !batch_on()) continue;+ const double budget = decode_share * std::chrono::duration<double, std::milli>(Clock::now() - tq).count();+ const auto td = Clock::now();+ do {+ if (!batch_step()) { batch_fatal = true; e = "a batch window failed"; return false; }+ } while (batch_on() && std::chrono::duration<double, std::milli>(Clock::now() - td).count() < budget);+ ++il_parts;+ il_ms += std::chrono::duration<double, std::milli>(Clock::now() - td).count();+ if (trace) {+ std::fprintf(stderr, "strata trace: prompt chunk to %lld, then the slots decoded %.0f ms\n",+ (long long) q, std::chrono::duration<double, std::milli>(Clock::now() - td).count());+ std::fflush(stderr);+ }+ }+ return true;+ };apply_pending(true);+ if (!adapt_tick(true)) { // --adapt-async: the round in flight lands before the prompt lends any slot+ std::printf("ERR an adaptive refill failed\n");+ return 1;+ }// per-request sampling for the verify window's head (greedy when temperature is absent)strata::kernels::SamplerParams req_sp;req_sp.greedy = req_temperature <= 0.0f;@@ -6839,14 +10015,17 @@ int main(int argc, char **argv) try {req_sp.penalty_present = req_penalty_present;req_sp.counter = 0;ver.set_sampling(req_sp);- mtp.set_draft_sampling(req_sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise)+ if (pipe) ver_b.set_sampling(req_sp); // (reaches the later stage's odd verifier)+ if (use_mtp) mtp.set_draft_sampling(req_sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise)drive.d.pcie_num = std::max(0, std::min(256, (int) (req_pcie_frac * 256.0 + 0.5)));// a layer split: CUDA0's share as asked; a later GPU keeps its own (its link) unless the request sets onefor (int st = 0; st < split_drive.n; ++st)split_drive.pcie_num[st] = (st == 0 || split_same || req_pcie_frac != o.pcie_frac)? drive.d.pcie_num : pcie_num_of(stages[(size_t) st - 1]->pcie_frac);+ if (pipe) for (int st = 0; st < split_drive.n; ++st) split_drive_b.pcie_num[st] = split_drive.pcie_num[st];const int hist_n = std::min(req_sp.penalty_last_n, kPenaltyWindowCap);ver.set_history(hist_n > 0 ? d_hist : nullptr, hist_n);+ if (pipe) ver_b.set_history(hist_n > 0 ? d_hist : nullptr, hist_n);bool cancelled = false;tr("prompt start", n - 1);// The prompt is read in two parts when it has a turn boundary past `resume`: up to the last <|im_start|>@@ -6871,15 +10050,24 @@ int main(int argc, char **argv) try {// which the retention policy pins (conv_cache.hpp), so the next new chat reads only what comes after it.// (PR #65, code-martin.) Only for a system prompt of --prompt-cache-root tokens or more: a small one// is cheaper to read again than the extra part costs (~0.3 s).+ const int64_t last_turn = turn_at; // ckpt=0 drops the split there, the root is still looked for before it+ if (!req_ckpt) turn_at = -1;int64_t root_at = -1;- if (o.prompt_cache > 0 && o.turn_token >= 0 && o.prompt_cache_root > 0 && read_from == 0)- for (int64_t i = 1; i < turn_at; ++i)+ if (o.prompt_cache > 0 && o.turn_token >= 0 && o.prompt_cache_root > 0 && (read_from == 0 || resumed_from0))+ for (int64_t i = 1; i < last_turn; ++i)if (ids[(size_t) i] == o.turn_token) {if (i >= o.prompt_cache_root) root_at = i;break;}+ static const bool message_checkpoint = [] {+ const char* e = std::getenv("STRATA_CACHE_MESSAGE_BOUNDARY");+ return e != nullptr && std::atoi(e) != 0;+ }();+ // Only add a snapshot; the existing token and image checks still decide reuse.+ const int64_t message_at = message_checkpoint && !multi_gpu && o.prompt_cache > 0+ ? strata::program::message_checkpoint_boundary(ids, resume, turn_at, o.turn_token) : -1;int64_t at = read_from;- for (const int64_t to : {reread_to, root_at, turn_at, n - 1}) {+ for (const int64_t to : {reread_to, root_at, message_at, turn_at, n - 1}) {if (to <= at) continue;err.clear();const bool win = windows_ok(at, to);@@ -6892,7 +10080,7 @@ int main(int argc, char **argv) try {return 1;}const auto tsp = Clock::now();- const bool sp_ok = win ? read_windows(at, to, err) : sp.run(ids.data() + at, to - at, at, err);+ const bool sp_ok = win ? read_windows(at, to, err) : read_part(at, to, err);if (trace) {std::fprintf(stderr, "strata trace: read %lld tokens (%s) in %.1f ms\n", (long long) (to - at),win ? "windows" : "batched",@@ -6900,7 +10088,7 @@ int main(int argc, char **argv) try {std::fflush(stderr);}if (!sp_ok) {- if (!stop_req.load()) {+ if (yielded_at < 0 && (batch_fatal || !stop_req.load())) {std::fprintf(stderr, "strata serve: %s\n", err.c_str());std::printf("ERR %s\n", err.c_str());// #224: a CUDA fault (an illegal address) poisons the context for the whole process, and@@ -6922,31 +10110,50 @@ int main(int argc, char **argv) try {break;}at = to;- if ((to == turn_at || to == root_at) && !checkpoint_at(to)) {+ if ((to == turn_at || to == root_at || to == message_at) &&+ !checkpoint_at(to, nullptr, to == message_at && to != turn_at && to != root_at)) { // the tail kind leaves firststd::printf("ERR saving a conversation checkpoint failed%s\n", ckpt_why.c_str());return 1;}+ if (trace && to == message_at)+ std::fprintf(stderr, "strata serve: message boundary checkpoint: %lld tokens, %lld tail\n",+ (long long) message_at, (long long) (turn_at - message_at));}if (!refill(err)) {std::printf("ERR refilling a lent slot failed: %s\n", err.c_str());return 1;}tr("prompt done (slots refilled)");+ if (il_parts > 0)+ std::fprintf(stderr, "strata batch: the prompt was read in %lld parts, the slots decoding %.0f ms between "+ "them\n", (long long) il_parts + 1, il_ms);const double prompt_ms = std::chrono::duration<double, std::milli>(Clock::now() - r0).count();std::printf("REUSED %lld\n", (long long) resume); // the prompt is read; the first window comes nextstd::fflush(stdout);// the verify windows: the first holds the last prompt token aloneint64_t p = n - 1;int32_t x = (int32_t) ids[(size_t) (n - 1)];- std::vector<int32_t> drafts((size_t) S, 0), window((size_t) S), outv((size_t) S);- std::vector<float> dprob((size_t) S, 0.0f);+ // (the drafter writes max_t - 1 drafts: 8 rows with --pipeline-windows 2)+ const size_t DS = (size_t) std::max(S, use_mtp ? mtp.max_t() : 0);+ std::vector<int32_t> drafts(DS, 0), window((size_t) S), outv((size_t) S);+ std::vector<float> dprob(DS, 0.0f);std::vector<int32_t> sbuf((size_t) S, 0);- if (o.suffix_draft > 0) {+ const bool sfx_on = o.suffix_draft > 0 || o.lookup_chain > 0;+ if (sfx_on) {sfx.reset();for (int64_t t : ids) sfx.append((int32_t) t);}+ if (o.lookup_chain > 0) {+ extra_sources_reset();+ for (int64_t t : ids) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); }+ }bool first_window = true;int64_t produced_n = 0, sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0;+ int64_t chain_windows = 0, chain_drafts = 0, chain_ok = 0; // --lookup-chain's own counts+ int64_t t2_rej[8] = {}, t2_hit[8] = {}; // STRATA_MTP_TOP2: rejections inside the MTP drafts by depth, runner-up hits+ std::vector<int32_t> cbuf((size_t) S, 0), ctail;+ strata::spec::PromptLookupSource lookup_src(sfx);+ static const bool chain_fixed = std::getenv("STRATA_LOOKUP_CHAIN_FIXED") != nullptr; // no policy gateint64_t draft_offered = 0, draft_accepted = 0;// what the session holds once this request is done: the prompt read so far, then every committed tokenstd::vector<int32_t> consumed;@@ -6975,9 +10182,697 @@ int main(int argc, char **argv) try {const int64_t decode_look0 = drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused;const int64_t offload0 = drive.d.offload_entries; // #588if (cancelled) finish = "cancel";- while (!cancelled && produced_n < max_new) {- int T = S_mtp;- if (req_spec_min_p > 0.0) {+ // ======== --pipeline-windows 2: the decode windows with the two cards overlapped ========+ // Stage 0 (the first card) runs window K+1 while stage 1 verifies window K, on the guess that K is accepted+ // whole and that its bonus token is the drafter's. The drafter, teacher-forced through K+1's drafts,+ // guesses K+1's bonus and drafts K+2 while stage 1 runs K+1. A wrong guess costs the speculative window:+ // stage 0's GDN state comes back from a snapshot and K's commit is replayed with its real count (the+ // window's own commit inputs are intact in its parity's verifier). Stage 1 never runs a speculative window+ // and a window row computes what it would in any other window, so every emitted token is the serial loop's+ // (with STRATA_IQ_MT_MIN=1 bit for bit; sampled requests with the same Philox draw per position).+ bool pl_ran = false;+ const bool pl_want = pipe && pl_pw >= 2 && pl_snap2[0] != nullptr;+ const char* pl_serial = !pl_want ? nullptr+ : hist_n > 0 ? "repetition penalties (penalty_last_n)"+ : mtp.coupled() ? "coupled draft sampling" : nullptr;+ if (pl_serial != nullptr) { // said once per reason+ static std::set<std::string> said;+ if (said.insert(pl_serial).second)+ std::fprintf(stderr, "strata serve: --pipeline-windows: a request with %s decodes serially\n",+ pl_serial);+ }+ if (pl_want && pl_serial == nullptr && !cancelled && produced_n < max_new) {+ pl_ran = true;+ if (!pl_prepare(err)) {+ std::printf("ERR %s\n", err.c_str());+ return 1;+ }+ struct PW {+ int T = 0, seq = 0;+ int64_t p = 0;+ int32_t tok[8] = {};+ float prob[8] = {}; // prob[i]: the drafter's probability of tok[i + 1]+ float p_on = 0.0f; // the chain's estimate that the window before is accepted whole, tok[0] its bonus+ bool ready = false, launched = false, finished = false, committed = false, s1 = false, s1_done = false;+ bool spec = false; // launched speculatively (behind the window before, ahead of its verdict)+ bool made = false; // made from a chain (its outcome can be scored even when the gate held it)+ bool sfx = false; // a lookup window (the suffix drafter's drafts)+ int sfx_match = 0;+ };+ auto V0 = [&](const PW& w) -> strata::core::Verifier& { return *PV[0][w.seq & 1]; };+ auto V1 = [&](const PW& w) -> strata::core::Verifier& { return *PV[1][w.seq & 1]; };+ auto SDf = [&](const PW& w) { return (void*) PSD[w.seq & 1]; };+ const float theta = pl_theta;+ const int force_miss = pl_force_miss;+ static const bool pl_log = pipe_dbg_env("STRATA_PIPELINE_LOG") != nullptr;+ const int dev0 = PV[0][0]->device();+ dpct::queue_ptr s0 = PV[0][0]->stream();+ // the snapshot of the GDN state window `seq` reads (overlapped: before its launch, on the side stream)+ auto snap_take = [&](int seq) -> bool {+ try {+ if (!pl_snap_overlap) return true;+ const strata::core::OnDevice on(dev0);+ const int q = seq & 1;+ /*+ DPCT1024: The original code returned the error code+ that was further consumed by the program logic. This+ original code was replaced with 0. You may need to rewrite+ the program logic consuming the error code.+ */+ return DPCT_CHECK_ERROR(+ dpct::sync_barrier(pl_snap_pre[q], s0)) == 0 &&+ DPCT_CHECK_ERROR(+ pl_snap_stream->ext_oneapi_submit_barrier(+ {*pl_snap_pre[q]})) == 0 &&+ /*+ DPCT1124: cudaMemcpyAsync is migrated to+ asynchronous memcpy API. While the origin API might+ be synchronous, it depends on the type of operand+ memory, so you may need to call wait() on event+ return by memcpy API to ensure synchronization+ behavior.+ */+ DPCT_CHECK_ERROR(pl_snap_stream->memcpy(+ pl_snap2[q], ss.gdn_state, pl_snap_bytes)) ==+ 0 &&+ /*+ DPCT1024: The original code returned the error+ code that was further consumed by the program logic.+ This original code was replaced with 0. You may need+ to rewrite the program logic consuming the error+ code.+ */+ DPCT_CHECK_ERROR(dpct::sync_barrier(+ pl_snap_ev[q], pl_snap_stream)) == 0 &&+ (DPCT_CHECK_ERROR(+ (pl_snap_stream->ext_oneapi_empty())),+ true);+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what()+ << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ PW A, B, D; // A: the oldest window not verified; B: the next; D: a wrong speculative window+ bool doomed = false; // D still runs: when it finishes, stage 0 goes back to undo_w's real commit+ PW undo_w;+ int undo_keep = 0;+ int32_t undo_ple[2] = {-1, -1};+ int chain_kind = 0; // 1: after an on-path verdict (A's drafts forced); 2: fresh (A's drafts from it)+ bool early_used = false;+ bool b_done = false; // B has been made from the chain in flight+ int chain_n = 0;+ int64_t pl_spec = 0, pl_on = 0, pl_undo = 0, pl_gate = 0, pl_fm = 0;+ std::vector<int32_t> outp(8, 0);+ bool ending = false;+ A.T = 1;+ A.p = p;+ A.tok[0] = x;+ A.ready = true;+ drive.d.layers = 0;+ drive.d.experts = 0;+ drive.d.failed = false;+ // the adaptive tier beside the pipeline: the serial loop's rule and adapt() on a thread of its own (its+ // copies wait for the windows in flight, which this loop keeps serving meanwhile)+ std::thread pl_adapt_thr;+ std::atomic<bool> pl_adapt_done{true};+ bool pl_adapt_ok = true;+ // an error ends the engine, as the serial loop's do: every GPU wait is released first (#267), so no+ // window in flight keeps spinning on a flag nobody raises, and the tier's thread can finish+ auto die = [&](const std::string& m) -> int {+ std::fprintf(stderr, "strata serve: pipelined decode: %s\n", m.c_str());+ strata::core::diag_pipeline_fn().store(nullptr);+ strata::core::release_gpu_waits(stderr);+ if (pl_adapt_thr.joinable()) pl_adapt_thr.join();+ std::printf("ERR %s\n", m.c_str());+ std::fflush(stdout);+ return 1;+ };+ // STRATA_PIPELINE_TRACE=<file>: every event of the loop with its time (appended per request)+ static const char* pl_trace_path = pipe_dbg_env("STRATA_PIPELINE_TRACE");+ std::string pl_trace;+ const Clock::time_point pl_tr0 = Clock::now();+ auto tre = [&](const char* ev, int seq, int x0 = 0, int x1 = 0) {+ if (pl_trace_path == nullptr) return;+ char b[96];+ std::snprintf(b, sizeof b, "%.3f %s %d %d %d\n",+ std::chrono::duration<double, std::milli>(Clock::now() - pl_tr0).count(), ev, seq, x0, x1);+ pl_trace += b;+ };+ auto pump0 = [&](PW& w) -> bool {+ if (!w.launched || w.finished) return true;+ strata::core::Verifier& v = V0(w);+ // a doomed window (its guess was wrong) gets empty plans: no expert work on the CPU or the GPU for+ // its remaining layers, so it frees stage 0 and the pool sooner (its rows are discarded and the+ // undo restores everything it wrote). STRATA_PIPELINE_DOOM_SKIP=0: served in full.+ static const bool doom_skip = [] { const char* e = pipe_dbg_env("STRATA_PIPELINE_DOOM_SKIP"); return e == nullptr || std::atoi(e) != 0; }();+ const bool skip = doom_skip && doomed && &w == &D;+ if (v.service(skip ? nullptr : &drive_pool_split, SDf(w), err) < 0) return false;+ if (v.done(err)) {+ if (!v.pl_finish(nullptr, err)) return false;+ w.finished = true;+ tre("F0", w.seq, w.T, w.spec);+ }+ return err.empty();+ };+ // the serial loop's window size over the chain's outputs from index `from` (`avail` of them)+ auto t_rule = [&](const float* pr, int from, int avail) {+ int T = S_mtp;+ if (req_spec_min_p > 0.0) {+ T = 1;+ while (T < S_mtp && from + T - 1 < avail && pr[from + T - 1] >= (float) req_spec_min_p) ++T;+ }+ return std::max(1, std::min(T, 1 + avail - from));+ };+ // B from the chain's outputs: its row 0 is the guess at index `base`, its drafts follow+ auto make_b = [&](const int32_t* oc, const float* op, int base, int avail, float pa) {+ B = PW{};+ if (base >= avail) return;+ B.seq = A.seq + 1;+ B.p = A.p + A.T;+ B.tok[0] = oc[base];+ B.T = t_rule(op, base + 1, avail);+ for (int i = 1; i < B.T; ++i) {+ B.tok[i] = oc[base + i];+ B.prob[i - 1] = op[base + i];+ }+ B.p_on = pa * op[base];+ if (force_miss > 0 && ++pl_fm % force_miss == 0) B.tok[0] = B.tok[0] == 0 ? 1 : 0;+ B.ready = true;+ B.made = true;+ };+ // events after all the work both stages' streams hold now, and whether they have passed+ dpct::event_ptr fence_ev[2] = {nullptr, nullptr},+ exch_ev[2] = {nullptr, nullptr};+ {+ const strata::core::OnDevice on0(dev0);+ fence_ev[0] = new sycl::event();+ exch_ev[0] = new sycl::event();+ }+ {+ const strata::core::OnDevice on1(stages[0]->dev);+ fence_ev[1] = new sycl::event();+ exch_ev[1] = new sycl::event();+ }+ auto stage_record = [&](dpct::event_ptr *ev) {+ try {+ {+ const strata::core::OnDevice on(dev0);+ dpct::sync_barrier(ev[0], s0);+ (void)DPCT_CHECK_ERROR((s0->ext_oneapi_empty()));+ }+ const strata::core::OnDevice on(stages[0]->dev);+ dpct::sync_barrier(ev[1], PV[1][0]->stream());+ (void)DPCT_CHECK_ERROR(+ ((PV[1][0]->stream())->ext_oneapi_empty()));+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what()+ << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ auto stage_passed = [&](dpct::event_ptr *ev) {+ try {+ return dpct::sycl_event_query(ev[0]) != 1 &&+ dpct::sycl_event_query(ev[1]) != 1;+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what()+ << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ // adapt()'s fence, on the tier's thread: it waits on the HOST. A device-side wait (the refill streams+ // waiting for the stages' events) would queue copies behind windows that need this loop, beside it.+ adapt_fence = [&]() {+ stage_record(fence_ev);+ while (!stage_passed(fence_ev)) std::this_thread::yield();+ };+ src.prepare_overrides();+ // The swaps land in two steps. Once their copies are done, the incoming experts are resident (the plans+ // from then on use their slots). What gives their RAM back - the resident RAM mode's exchange, the+ // released or unpinned pages - waits until every window that may still pull them over PCIe (a plan+ // published before that point) has completed: both stages' streams are fenced there.+ bool exch_wait = false;+ std::vector<int32_t> pl_landed;+ auto pl_release = [&]() {+ unpin_blobs(pin_live);+ src.commit_exchanges();+ for (const int32_t i : pl_landed) srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert);+ pl_landed.clear();+ exch_wait = false;+ };+ auto pl_apply = [&]() {+ try {+ if (exch_wait) {+ if (stage_passed(exch_ev)) pl_release();+ return;+ }+ if (pending.empty() ||+ adapt_ev->get_info<+ sycl::info::event::command_execution_status>() !=+ sycl::info::event_command_status::complete) return;+ for (auto& st : stages)+ if (st->adapt_live &&+ (st->adapt_ev)+ ->get_info<+ sycl::info::event::+ command_execution_status>() !=+ sycl::info::event_command_status::+ complete) return;+ for (auto& st : stages) st->adapt_live = false;+ for (const auto& [i, slot] : pending) {+ host_res[(size_t) i] = slot;+ pl_landed.push_back(i);+ }+ pending.clear();+ pending_age = 0;+ res_upload();+ stage_record(exch_ev);+ exch_wait = true;+ }+ catch (sycl::exception const &exc) {+ std::cerr << exc.what()+ << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+ }+ };+ auto pl_adapt = [&]() -> bool {+ if (pl_adapt_thr.joinable() && pl_adapt_done.load()) {+ pl_adapt_thr.join();+ if (!pl_adapt_ok) return false;+ }+ if (pl_adapt_thr.joinable()) return true; // still adapting+ pl_apply();+ if (!drive.d.usage.empty() && o.adapt_every > 0 && (rounds % o.adapt_every) == 0 && pending.empty() &&+ !exch_wait) {+ pl_adapt_done = false;+ pl_adapt_thr = std::thread([&] { pl_adapt_ok = adapt(); pl_adapt_done = true; });+ }+ return true;+ };+ // the serial loop's prompt lookup for a fresh window: where the text repeats an earlier stretch and the+ // drafter's own first guess agrees, the policy may take the lookup's continuation (up to S rows)+ std::vector<int32_t> pl_sbuf((size_t) (2 * S), 0);+ // a lookup window's continuation goes on past it: the next window (B) is taken from the same lookup and+ // speculated behind it (a copied stretch is mostly accepted whole). STRATA_PIPELINE_LOOKUP_PON: B's+ // estimate (default 0.75; 0 = no lookup B)+ static const float pl_lookup_pon = [] {+ const char* v = pipe_dbg_env("STRATA_PIPELINE_LOOKUP_PON");+ return v ? (float) std::atof(v) : 0.75f;+ }();+ auto pick_lookup = [&](PW& w, const int32_t* chain0) {+ if (o.suffix_draft <= 0 || w.seq == 0) return;+ const int k = sfx.propose(2 * S - 1, pl_sbuf.data());+ const int match = sfx.last_match();+ if (k <= 0 || pl_sbuf[0] != chain0[0]) return;+ const strata::spec::DraftPolicy::Pick pk = policy.choose(w.T, std::min(k, S - 1), match);+ if (!pk.lookup) return;+ w.T = pk.t;+ for (int i = 1; i < w.T; ++i) {+ w.tok[i] = pl_sbuf[(size_t) i - 1];+ w.prob[i - 1] = 1.0f;+ }+ w.sfx = true;+ w.sfx_match = match;+ const int rest = k - (w.T - 1); // lookup tokens past w: B's row 0 (w's bonus guess) and its drafts+ if (&w == &A && rest >= 1 && pl_lookup_pon > 0.0f && !b_done) {+ B = PW{};+ B.seq = A.seq + 1;+ B.p = A.p + A.T;+ B.T = std::min(S, rest);+ for (int i = 0; i < B.T; ++i) B.tok[i] = pl_sbuf[(size_t) (A.T - 1 + i)];+ for (int i = 1; i < B.T; ++i) B.prob[i - 1] = 1.0f;+ B.p_on = pl_lookup_pon;+ B.ready = true;+ B.made = true;+ b_done = true; // the chain in flight makes no B for this A+ tre("CD", A.seq + 1, 3, (int) (1000.0f * B.p_on));+ }+ };+ const Clock::time_point pl_t0 = Clock::now();+ for (int st = 0; st < 2; ++st)+ for (int par = 0; par < 2; ++par) g_pl_diag.v[st][par] = PV[st][par];+ strata::core::diag_pipeline_fn().store(&pl_diag_print);+ auto pw_bits = [](const PW& w) {+ return (w.ready ? 1 : 0) | (w.launched ? 2 : 0) | (w.finished ? 4 : 0) | (w.committed ? 8 : 0) |+ (w.s1 ? 16 : 0) | (w.s1_done ? 32 : 0);+ };+ // per window class (0: fresh, 1: run speculatively ahead of its predecessor's verdict): the time from+ // the previous verdict, the tokens it emitted, how many+ double cls_ms[2] = {0, 0}, cls_tok[2] = {0, 0}, cls_n[2] = {0, 0};+ int64_t cal_n[10] = {}, cal_on[10] = {}; // per p_on decile: windows scored, on the path+ double last_verdict = 0.0;+ int64_t pl_disagree = 0, pl_late = 0;+ static const bool pl_prestage = [] { // STRATA_PIPELINE_PRESTAGE=0: B staged at its launch+ const char* v = pipe_dbg_env("STRATA_PIPELINE_PRESTAGE");+ return v == nullptr || std::atoi(v) != 0;+ }();+ static const bool pl_agree = [] { // STRATA_PIPELINE_AGREE=0: only the old chain's probabilities+ const char* v = pipe_dbg_env("STRATA_PIPELINE_AGREE");+ return v == nullptr || std::atoi(v) != 0;+ }();+ auto ms_now = [&]() { return std::chrono::duration<double, std::milli>(Clock::now() - pl_t0).count(); };+ while (true) {+ g_pl_diag.iters.fetch_add(1, std::memory_order_relaxed);+ g_pl_diag.a_seq.store(A.seq, std::memory_order_relaxed);+ g_pl_diag.a_bits.store(pw_bits(A), std::memory_order_relaxed);+ g_pl_diag.b_bits.store(pw_bits(B), std::memory_order_relaxed);+ g_pl_diag.d_bits.store(pw_bits(D), std::memory_order_relaxed);+ g_pl_diag.chain_kind.store(chain_kind, std::memory_order_relaxed);+ g_pl_diag.chain_live.store(mtp.chain_live() ? 1 : 0, std::memory_order_relaxed);+ g_pl_diag.doomed.store(doomed ? 1 : 0, std::memory_order_relaxed);+ g_pl_diag.ending.store(ending ? 1 : 0, std::memory_order_relaxed);+ // ---- every window in flight served+ if ((doomed && !pump0(D)) || !pump0(A) || !pump0(B)) return die(err);+ if (A.s1 && !A.s1_done) {+ strata::core::Verifier& v = V1(A);+ if (v.service(&drive_pool_split, SDf(A), err) < 0) return die(err);+ if (v.done(err)) {+ if (!v.pl_finish(outp.data(), err)) return die(err);+ A.s1_done = true;+ tre("F1", A.seq, A.T);+ } else if (!err.empty()) return die(err);+ }+ if (drive.d.failed) return die(drive.d.fail ? drive.d.fail : "the expert pool failed");+ // ---- a wrong speculative window has finished: stage 0 back to the verified window's real commit+ if (doomed && D.finished) {+ {+ const strata::core::OnDevice on(dev0);+ /*+ DPCT1124: cudaMemcpyAsync is migrated to+ asynchronous memcpy API. While the origin API might+ be synchronous, it depends on the type of operand+ memory, so you may need to call wait() on event+ return by memcpy API to ensure synchronization+ behavior.+ */+ if (DPCT_CHECK_ERROR(s0->memcpy(+ ss.gdn_state,+ pl_snap2[pl_snap_overlap ? (undo_w.seq & 1)+ : 0],+ pl_snap_bytes)) != 0)+ return die("restoring the GDN snapshot failed");+ }+ ss.ple_prev[0] = undo_ple[0];+ ss.ple_prev[1] = undo_ple[1];+ if (!V0(undo_w).pl_commit_async(undo_keep, err)) return die(err);+ doomed = false;+ ++pl_undo;+ tre("U", undo_w.seq, undo_keep);+ }+ if (ending) {+ if (!doomed) break;+ continue;+ }+ // ---- the drafter's chain, read as its outputs land (an event after each): a fresh A once its size+ // is decided, then B once ITS size is decided - its bonus guess and a draft below spec_min_p (or+ // S_mtp - 1 drafts) - so stage 0 need not wait for the whole chain+ if (chain_kind != 0) {+ const int k_ready = mtp.chain_outputs_ready(err);+ if (k_ready < 0) return die(err);+ if (chain_kind == 2 && !early_used) {+ // A's size is decided by its first outputs: a draft below spec_min_p ends it (the serial+ // loop's rule), so A goes to stage 0 as soon as that is known, not after all S_mtp - 1+ const int k = k_ready;+ bool decided = k >= S_mtp - 1;+ if (!decided && req_spec_min_p > 0.0)+ for (int j = 0; j < k; ++j)+ if (mtp.chain_prob()[j] < (float) req_spec_min_p) { decided = true; break; }+ if (decided) {+ A.T = t_rule(mtp.chain_prob(), 0, std::min(k, S_mtp - 1));+ for (int i = 1; i < A.T; ++i) {+ A.tok[i] = mtp.chain_tok()[i - 1];+ A.prob[i - 1] = mtp.chain_prob()[i - 1];+ }+ pick_lookup(A, mtp.chain_tok());+ A.ready = true;+ early_used = true;+ tre("CE", A.seq, A.T);+ }+ }+ const int r = mtp.chain_poll(err);+ if (r < 0) return die(err);+ const int k = r == 1 ? chain_n : k_ready;+ const int32_t* oc = mtp.chain_tok();+ const float* op = mtp.chain_prob();+ if (r == 1 && chain_kind == 2 && !early_used) {+ A.T = t_rule(op, 0, std::min(chain_n, S_mtp - 1));+ for (int i = 1; i < A.T; ++i) {+ A.tok[i] = oc[i - 1];+ A.prob[i - 1] = op[i - 1];+ }+ pick_lookup(A, oc);+ A.ready = true;+ early_used = true;+ }+ if (!b_done && (chain_kind == 1 || early_used)) {+ const int base = A.T - 1; // B's row 0: the guess of A's bonus+ bool decided = r == 1 || k >= base + S_mtp;+ if (!decided && k > base + 1 && req_spec_min_p > 0.0)+ for (int j = base + 1; j < k; ++j)+ if (op[j] < (float) req_spec_min_p) { decided = true; break; }+ if (decided) {+ float pa = 1.0f;+ if (chain_kind == 1) {+ // forced through A's drafts: its outputs there are the drafter's own picks from+ // A's verified predecessor, a better estimate of A's acceptance than the chain that+ // drafted A; a disagreement means A is unlikely to be accepted whole+ bool agree = true;+ for (int i = 0; i + 1 < A.T; ++i) {+ if (oc[i] != A.tok[i + 1]) agree = false;+ pa *= pl_agree ? op[i] : A.prob[i];+ }+ if (pl_agree && !agree) { pa = 0.0f; ++pl_disagree; }+ } else {+ for (int i = 0; i + 1 < A.T; ++i) pa *= A.prob[i];+ }+ if (!A.sfx) make_b(oc, op, base, k, pa); // a lookup window's bonus is not the chain's+ // stage B now (its PLE rows from the tokens before it as they will be once A is+ // committed whole), so its launch behind A is only the graph launch (never while a+ // rollback is pending: B's verifier is the one the undo commit reads)+ if (B.ready && B.p_on >= theta && pl_prestage && !V0(B).in_flight() && !doomed) {+ int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]};+ for (int i = 0; i < A.T; ++i) { prev[0] = prev[1]; prev[1] = A.tok[i]; }+ if (!V0(B).prestage(B.T, B.tok, B.p, prev, err)) return die(err);+ }+ b_done = true;+ tre("CD", A.seq, chain_kind, (int) (1000.0f * B.p_on));+ if (pl_log)+ std::fprintf(stderr, "strata pipeline: chain %d for p=%lld T=%d: B T=%d p_on %.3f (%d "+ "outputs)\n", chain_kind, (long long) A.p, A.T, B.T, B.p_on, k);+ }+ }+ if (r == 1) chain_kind = 0;+ }+ // ---- stage 0: A (never while a wrong window still holds stage 0's state)+ if (A.ready && !A.launched && !doomed) {+ if (A.p + A.T > o.max_context) { ending = true; continue; }+ if (!snap_take(A.seq)) return die("the GDN snapshot failed");+ if (!V0(A).pl_launch(A.T, A.tok, A.p, err)) return die(err);+ A.launched = true;+ tre("L0", A.seq, A.T, 0);+ }+ // ---- stage 0: B, speculatively, right behind A+ if (B.ready && !B.launched && A.finished && !A.committed && !doomed) {+ if (B.p_on >= theta && B.p + B.T <= o.max_context) {+ {+ const strata::core::OnDevice on(dev0);+ if (pl_snap_overlap+ ? DPCT_CHECK_ERROR(+ s0->ext_oneapi_submit_barrier(+ {*pl_snap_ev[A.seq & 1]})) !=+ 0+ /*+ DPCT1124: cudaMemcpyAsync is+ migrated to asynchronous memcpy API.+ While the origin API might be+ synchronous, it depends on the type of+ operand memory, so you may need to call+ wait() on event return by memcpy API to+ ensure synchronization behavior.+ */+ : DPCT_CHECK_ERROR(s0->memcpy(+ pl_snap2[0], ss.gdn_state,+ pl_snap_bytes)) != 0)+ return die("the GDN snapshot failed");+ }+ undo_ple[0] = ss.ple_prev[0];+ undo_ple[1] = ss.ple_prev[1];+ if (!V0(A).pl_commit_async(A.T, err) || !snap_take(B.seq) ||+ !V0(B).pl_launch(B.T, B.tok, B.p, err))+ return die(err.empty() ? std::string("the GDN snapshot failed") : err);+ A.committed = true;+ B.launched = true;+ B.spec = true;+ tre("L0", B.seq, B.T, 1);+ ++pl_spec;+ } else {+ B.ready = false; // not worth it: A's verdict decides the next window+ ++pl_gate;+ }+ }+ // ---- stage 1: A, once its stage 0 is done+ if (A.finished && !A.s1) {+ if (chain_kind == 1 && !B.ready) ++pl_late; // stage 0 idles until the chain has B+ if (!V1(A).pl_launch(A.T, A.tok, A.p, err)) return die(err);+ A.s1 = true;+ tre("L1", A.seq, A.T);+ }+ // ---- A's verdict+ if (!A.s1_done) continue;+ // the drafter must be idle before the next chain. The chain needs nothing from the host, so this+ // wait is bounded even with B (made from its first outputs) in flight on stage 0; in practice the+ // chain ended long before a verdict that needs a whole stage-1 window.+ while (chain_kind != 0 && mtp.chain_live())+ if (mtp.chain_poll(err) < 0) return die(err);+ if (chain_kind != 0 && !B.launched && !B.made) B = PW{};+ chain_kind = 0;+ int a = 0;+ while (a < A.T - 1 && A.tok[a + 1] == outp[(size_t) a]) ++a;+ if (!V1(A).pl_commit_async(a + 1, err)) return die(err);+ for (int i = 0; i <= a; ++i) consumed.push_back(A.tok[i]);+ draft_offered += A.T - 1;+ draft_accepted += a;+ ++rounds;+ ++dec_windows;+ dec_T += A.T;+ bool eos = false;+ for (int i = 0; i <= a && produced_n < max_new && !eos; ++i) {+ std::printf("T %d\n", (int) outp[(size_t) i]);+ strata::core::progress_beat();+ ++produced_n;+ if (o.suffix_draft > 0) sfx.append(outp[(size_t) i]);+ eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outp[(size_t) i]) != o.eos_ids.end();+ }+ std::fflush(stdout);+ if (eos) finish = "stop";+ else if (stop_req.load()) finish = "cancel";+ const bool last = eos || produced_n >= max_new || stop_req.load();+ const bool on = B.launched && a == A.T - 1 && B.tok[0] == outp[(size_t) A.T - 1];+ if (B.made) { // the gate's calibration: would B have been on the path, by its estimate p_on+ const bool would = a == A.T - 1 && B.tok[0] == outp[(size_t) A.T - 1];+ const int bin = std::min(9, std::max(0, (int) (B.p_on * 10.0f)));+ cal_n[bin] += 1;+ cal_on[bin] += would ? 1 : 0;+ }+ tre("V", A.seq, a, on ? 1 : (B.launched ? -1 : 0));+ {+ const double now = ms_now();+ const int c = A.spec ? 1 : 0;+ if (A.sfx) { ++sfx_windows; sfx_drafts += A.T - 1; sfx_ok += a; }+ if (A.seq > 0 && !last) policy.observe(A.sfx, A.T, a, A.sfx_match, now - last_verdict);+ cls_ms[c] += now - last_verdict;+ cls_tok[c] += a + 1;+ cls_n[c] += 1;+ last_verdict = now;+ }+ if (pl_log)+ std::fprintf(stderr, "strata pipeline: verdict p=%lld T=%d a=%d B %s%s\n", (long long) A.p, A.T, a,+ B.launched ? "launched" : B.ready ? "ready" : "none", on ? " ON" : "");+ x = outp[(size_t) a];+ p = A.p + a + 1;+ if (!last && !pl_adapt()) return die("an adaptive refill failed");+ if (on && !last) {+ ++pl_on;+ // the chain over A, forced through B's drafts: B's bonus guess and the next window's drafts+ mtp.set_source_R(V1(A).final_R(0));+ chain_n = std::min(strata::kernels::kVerifyMaxT - 1, B.T + S_mtp - 1);+ if (!mtp.chain_launch(A.T, outp.data(), A.p, a, B.tok + 1, B.T - 1, chain_n, chain_n, err))+ return die(err);+ chain_kind = 1;+ tre("CL", A.seq, 1);+ early_used = false;+ b_done = false;+ A = B;+ B = PW{};+ } else {+ if (B.launched) { // a wrong guess (or the end): undo once it has finished+ doomed = true;+ D = B;+ undo_w = A;+ undo_keep = a + 1;+ } else if (!A.committed) {+ if (!V0(A).pl_commit_async(a + 1, err)) return die(err);+ }+ // B is D now (or dropped): never pump it twice (whichever copy saw the window complete first+ // would finish it, and the other would wait for it forever)+ B = PW{};+ if (!last) {+ mtp.set_source_R(V1(A).final_R(0));+ chain_n = strata::kernels::kVerifyMaxT - 1;+ if (!mtp.chain_launch(A.T, outp.data(), A.p, a, nullptr, 0, chain_n, chain_n, err))+ return die(err);+ chain_kind = 2;+ tre("CL", A.seq, 2);+ early_used = false;+ b_done = false;+ PW nA;+ nA.seq = A.seq + 1;+ nA.p = A.p + a + 1;+ nA.tok[0] = outp[(size_t) a];+ A = nA;+ }+ }+ if (last) ending = true;+ }+ pl_drain(); // nothing in flight: both stages' commits and the drafter have landed+ strata::core::diag_pipeline_fn().store(nullptr);+ if (pl_adapt_thr.joinable()) pl_adapt_thr.join(); // its copies waited only for finished work+ adapt_fence = nullptr;+ if (exch_wait) pl_release(); // every window has completed (drained)+ for (dpct::event_ptr ev : fence_ev) if (ev)+ dpct::destroy_event(ev);+ for (dpct::event_ptr ev : exch_ev) if (ev)+ dpct::destroy_event(ev);+ if (pl_trace_path != nullptr && !pl_trace.empty()) {+ if (std::FILE* f = std::fopen(pl_trace_path, "a")) {+ std::fprintf(f, "# request p0=%lld\n", (long long) (n - 1));+ std::fwrite(pl_trace.data(), 1, pl_trace.size(), f);+ std::fclose(f);+ }+ }+ // the odd windows' counters and GPU profiles into the verifiers that report them+ PV[0][0]->absorb_stats(*PV[0][1]);+ PV[1][0]->absorb_stats(*PV[1][1]);+ if (!pl_adapt_ok) {+ std::printf("ERR an adaptive refill failed\n");+ return 1;+ }+ while (mtp.chain_live() && mtp.chain_poll(err) == 0) {}+ mtp.set_source_R(ver.final_R_all()); // the serial loop's rows again+ const double pl_ms = std::chrono::duration<double, std::milli>(Clock::now() - pl_t0).count();+ dt_run += pl_ms;+ if (dec_timing) {+ auto avg = [](double s_, double n_) { return n_ > 0 ? s_ / n_ : 0.0; };+ std::fprintf(stderr, "strata pipeline: %lld windows in %.0f ms (%.2f ms/window): %lld speculative, %lld on "+ "the path, %lld rolled back, %lld below the gate (theta %.2f)\n",+ (long long) dec_windows, pl_ms, avg(pl_ms, (double) dec_windows), (long long) pl_spec,+ (long long) pl_on, (long long) pl_undo, (long long) pl_gate, theta);+ std::fprintf(stderr, "strata pipeline classes: fresh %.0f windows %.2f ms %.2f tok | speculative %.0f "+ "windows %.2f ms %.2f tok | forced-chain disagreements %lld, chain late %lld\n",+ cls_n[0], avg(cls_ms[0], cls_n[0]), avg(cls_tok[0], cls_n[0]), cls_n[1],+ avg(cls_ms[1], cls_n[1]), avg(cls_tok[1], cls_n[1]), (long long) pl_disagree,+ (long long) pl_late);+ std::string cal;+ char b[48];+ for (int i = 0; i < 10; ++i)+ if (cal_n[i] > 0) {+ std::snprintf(b, sizeof b, " %.1f:%lld/%lld", i / 10.0, (long long) cal_on[i], (long long) cal_n[i]);+ cal += b;+ }+ std::fprintf(stderr, "strata pipeline calibration (p_on decile: on/scored):%s\n", cal.c_str());+ }+ }+ while (!pl_ran && !cancelled && produced_n < max_new) {+ int T = use_mtp ? S_mtp : 1; // no --mtp: one token a round unless a lookup draft fires+ if (use_mtp && req_spec_min_p > 0.0) {T = 1;while (T < S_mtp && dprob[(size_t) T - 1] >= (float) req_spec_min_p) ++T;}@@ -6989,23 +10884,46 @@ int main(int argc, char **argv) try {if (o.suffix_draft > 0 && !first_window) {const int k = sfx.propose(S - 1, sbuf.data());sfx_match = sfx.last_match();- if (k > 0 && sbuf[0] == drafts[0]) {+ if (k > 0 && (!use_mtp || sbuf[0] == drafts[0])) {const strata::spec::DraftPolicy::Pick pk = policy.choose(T, k, sfx_match);if (pk.lookup) { T = pk.t; from_sfx = true; }}}+ // --lookup-chain: what followed an earlier occurrence of the context + the MTP's drafts, after them+ int chain_n = 0, cm = 0;+ if (o.lookup_chain > 0 && !first_window && !from_sfx && T < S) {+ int csrc = -1;+ const int nt = chain_tail(sfx, drafts.data(), T - 1, ctail);+ chain_n = strata::spec::propose_from_sources(lookup_src, ctail.data(), nt, T - 1,+ std::min(o.lookup_chain, S - T), o.lookup_chain_min,+ cbuf.data(), &cm, &csrc);+ // the policy keeps the chained tokens that pay at this machine's measured window costs+ if (chain_n > 0 && !chain_fixed) {+ double p_mtp = 1.0;+ for (int i = 0; i < T - 1; ++i) p_mtp *= dprob[(size_t) i];+ chain_n = policy.chain(T, p_mtp, chain_n, cm);+ }+ }+ const int T_mtp = T;+ T += chain_n;const bool timed_round = !first_window;const Clock::time_point round0 = Clock::now();if (p + T > o.max_context) break;window[0] = x;- for (int i = 1; i < T; ++i) window[(size_t) i] = from_sfx ? sbuf[(size_t) i - 1] : drafts[(size_t) i - 1];+ for (int i = 1; i < T_mtp; ++i) window[(size_t) i] = from_sfx ? sbuf[(size_t) i - 1] : drafts[(size_t) i - 1];+ for (int i = 0; i < chain_n; ++i) window[(size_t) (T_mtp + i)] = cbuf[(size_t) i];drive.d.layers = 0;drive.d.experts = 0;drive.d.failed = false;// #463: the previous adapt round's copies land first - with a non-blocking query, whether a swapped-in// expert ran on the GPU or the CPU (they round differently) depended on the copy's timing// (STRATA_ADAPT_NOWAIT=1: 0.1.37's non-blocking query, the A/B)- apply_pending(!adapt_nowait());+ if (adapt_nowait()) apply_pending(false);+ else if (pending.empty() || ++pending_age >= adapt_lag()) apply_pending(true);+ if (!adapt_tick(false)) { // --adapt-async: the round in flight moves on a step when it can+ std::printf("ERR an adaptive refill failed\n");+ return 1;+ }if (hist_n > 0) {// the tails the penalties count over, ONE PER ROW: the tokens the state has consumed, the// fed-back head `x` (it joins `consumed` only after this window commits), then the drafts@@ -7019,6 +10937,15 @@ int main(int argc, char **argv) try {(size_t)T * (size_t)hist_n * sizeof(int32_t)).wait();}+ // the elastic K/V: the window's cells and the drafter's beyond them+ if (kvg.on && p + T + 64 > kvg.cells &&+ !kvg_ensure(p + T + 64, [&] {+ dpct::get_current_device()+ .queues_wait_and_throw();+ apply_pending(true); })) {+ std::printf("ERR the K/V cannot grow: no VRAM is left\n");+ return 1;+ }tr("window", p, T);const Clock::time_point tw0 = Clock::now();if (!ver.run(T, window.data(), p, win_pool_fn, win_pool_user, outv.data(), err) || drive.d.failed) {@@ -7028,10 +10955,16 @@ int main(int argc, char **argv) try {int a = 0;while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a;if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; }+ if (chain_n > 0) { ++chain_windows; chain_drafts += chain_n; chain_ok += std::max(0, a - (T_mtp - 1)); }+ if (strata::core::MtpDrafter::top2_env() && !from_sfx && !first_window && a < T_mtp - 1 && a < 8) {+ ++t2_rej[a];+ if (mtp.top2(a) == outv[(size_t) a]) ++t2_hit[a];+ }const Clock::time_point tw1 = Clock::now();std::thread adapt_thr; // the adaptive tier beside the commit and the draft (as in generate)bool adapt_ok = true;- if (!drive.d.usage.empty() && ((rounds + 1) % o.adapt_every) == 0)+ // (--adapt-async 1: the asynchronous tier above instead, ticked before the window)+ if (!drive.d.usage.empty() && !ajob && ((rounds + 1) % o.adapt_every) == 0)adapt_thr = std::thread([&] { adapt_ok = adapt(); });if (!ver.commit(a + 1, err)) {if (adapt_thr.joinable()) adapt_thr.join();@@ -7072,7 +11005,8 @@ int main(int argc, char **argv) try {}strata::core::progress_beat();++produced_n;- if (o.suffix_draft > 0) sfx.append(outv[(size_t) i]);+ if (sfx_on) sfx.append(outv[(size_t) i]);+ if (o.lookup_chain > 0) extra_sources_append(&outv[(size_t) i], 1);eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end();}std::fflush(stdout);@@ -7080,9 +11014,9 @@ int main(int argc, char **argv) try {const Clock::time_point tw2 = Clock::now();// coupled drafts with penalties: the next window's row-0 history (`consumed` holds this window's// commit, outv[a] is its row 0) - the drafts extend it on the device as the verify rows will- if (hist_n > 0 && mtp.coupled() && !eos && produced_n < max_new)+ if (use_mtp && hist_n > 0 && mtp.coupled() && !eos && produced_n < max_new)mtp.set_draft_history(consumed.data(), (int64_t) consumed.size(), outv[(size_t) a]);- const bool drafted = eos || produced_n >= max_new ||+ const bool drafted = !use_mtp || eos || produced_n >= max_new ||mtp.draft(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) req_spec_min_p);{const Clock::time_point tw3 = Clock::now();@@ -7099,9 +11033,12 @@ int main(int argc, char **argv) try {std::printf("ERR %s\n", err.c_str());return 1;}- if (timed_round && !eos)+ if (timed_round && !eos && chain_n == 0)policy.observe(from_sfx, T, a, sfx_match,std::chrono::duration<double, std::milli>(Clock::now() - round0).count());+ else if (timed_round && !eos) // a chained window: its MTP part, its chain, its cost+ policy.observe_chain(T_mtp, chain_n, a, cm,+ std::chrono::duration<double, std::milli>(Clock::now() - round0).count());if (eos) { finish = "stop"; break; }if (stop_req.load()) { finish = "cancel"; break; }x = outv[(size_t) a];@@ -7125,18 +11062,22 @@ int main(int argc, char **argv) try {(d1.actq - ds0.actq) / w, (d1.jobs - ds0.jobs) / w, (d1.run - ds0.run) / w,(d1.host - ds0.host) / w, dt_commit / w, dt_draft / w, (d1.misses - ds0.misses) / (w * L),(d1.entries - ds0.entries) / (w * L), (d1.hits - ds0.hits) / (w * L), (d1.pcie - ds0.pcie) / (w * L));- const std::string pr = ver.profile_report();- if (!pr.empty()) std::fprintf(stderr, "strata decode GPU stages (ms/window):%s\n", pr.c_str());+ for (int st = 0; st < n_stages; ++st) { // every stage's GPU profile, not only the first card's+ const std::string pr = stage_ver(st).profile_report();+ if (pr.empty()) continue;+ if (st == 0) std::fprintf(stderr, "strata decode GPU stages (ms/window):%s\n", pr.c_str()); // text as before+ else std::fprintf(stderr, "strata decode GPU stages, stage %d (ms/window):%s\n", st, pr.c_str());+ }}if (!cancelled) {// a prompt stopped halfway leaves the session somewhere between two chunks: nothing to continue from// (the checkpoints taken while reading it are still good)live.swap(consumed);live_imgs = imgs_below(req_imgs, (int64_t) live.size());- live_ok = o.prompt_cache > 0;+ live_ok = o.prompt_cache > 0 && req_ckpt; // ckpt=0: nothing to continue or park (#830)}static const bool state_hash = std::getenv("STRATA_STATE_HASH") != nullptr;- if (state_hash && live_ok) {+ if (state_hash && !cancelled && o.prompt_cache > 0) { // every finished request, ckpt=0 too (parity gates)// DEBUG: a fingerprint of every part of the session over the positions it holds ([0, L)), and// separately of what lies past them in the last KV page (stale cells, fine unless something reads them)if (DPCT_CHECK_ERROR(@@ -7245,11 +11186,13 @@ int main(int argc, char **argv) try {h_stale = hash_cells(pool, w, L, end_cell, h_stale);}}- const strata::core::QsaState& ms = mtp.kv_state();uint64_t h_mtp = 1469598103934665603ull;- const int64_t mL = std::min<int64_t>(L, ms.max_cells);- for (const auto& [pool, w] : kv_arrays(ms))- if (pool != nullptr) h_mtp = hash_cells(pool, w, 0, mL, h_mtp);+ if (use_mtp) {+ const strata::core::QsaState& ms = mtp.kv_state();+ const int64_t mL = std::min<int64_t>(L, ms.max_cells);+ for (const auto& [pool, w] : kv_arrays(ms))+ if (pool != nullptr) h_mtp = hash_cells(pool, w, 0, mL, h_mtp);+ }if (!hash_ok) {std::printf("ERR reading state fingerprint\n");return 1;@@ -7273,14 +11216,65 @@ int main(int argc, char **argv) try {// [prompt tokens read] (#471: fewer than <prompt> - <reused> when a cancel stopped the read)// [offloaded] (#588: the decode's routed experts the GPU read over PCIe or another GPU computed;// not in [lookups])- std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld %lld\n",+ // [lookup-chain accepted] [lookup-chain offered] [suffix accepted] [suffix offered] [windows]+ // (only with --lookup-chain)+ char chain_txt[128] = "";+ if (o.lookup_chain > 0)+ std::snprintf(chain_txt, sizeof(chain_txt), " %lld %lld %lld %lld %lld", (long long) chain_ok,+ (long long) chain_drafts, (long long) sfx_ok, (long long) sfx_drafts, (long long) dec_windows);+ if (yielded_at >= 0) std::printf("YIELDED %d %lld\n", yielded_slot, (long long) yielded_at);+ std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld %lld%s\n",(long long) produced_n,(long long) n, prompt_ms, decode_ms, finish, (long long) draft_accepted, (long long) draft_offered,(long long) resume, (long long) req_hits, (long long) req_look,(long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0),(double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n,- (long long) req_offload);+ (long long) req_offload, chain_txt);std::fflush(stdout);+ if (admit_slot >= 0) { // --batch: BADM <slot> <1 = continues in the batch windows | 0 = done>+ bool cont = !cancelled && produced_n == 1 && admit_max_new > 1 && std::strcmp(finish, "length") == 0 &&+ (int64_t) live.size() == p;+ const auto tc0 = Clock::now();+ if (cont && !copy_to_slot(admit_slot, live, err)) {+ std::fprintf(stderr, "strata serve: batch admission failed: %s\n", err.c_str());+ bs[(size_t) admit_slot].cached = false; // its sessions may be half written+ cont = false;+ }+ if (cont) {+ ver.set_slot_sampling(admit_slot, req_sp); // the request's own sampling, row by row+ BSlot& sl = bs[(size_t) admit_slot];+ sl = BSlot{};+ sl.active = true;+ sl.x = x;+ sl.p = p;+ sl.produced = 1;+ sl.max_new = admit_max_new;+ sl.t0 = Clock::now();+ sl.ids = live;+ if (batch_mtp) {+ if (!slot_mtp[(size_t) admit_slot]->draft_first(1, ver.final_R_all(), sl.x,+ sl.p - 1, sl.draft.data(), err)) {+ std::fprintf(stderr, "strata batch: MTP admission for slot %d failed: %s\n",+ admit_slot, err.c_str());+ return 1;+ }+ sl.draft_ready = true;+ }+ sl.cvec = cvec_cached;+ sl.img = !live_imgs.empty(); // pictures: not matched again by tokens alone, so not cached+ const ConvCheckpoint* best = nullptr;+ for (const ConvCheckpoint& c : checks)+ if (c.ids.size() < live.size() && (best == nullptr || c.ids.size() > best->ids.size()) &&+ std::equal(c.ids.begin(), c.ids.end(), live.begin()))+ best = &c;+ if (best != nullptr && !sl.img) sl.checks.push_back(*best);+ std::fprintf(stderr, "strata batch: slot %d takes %lld tokens (copied in %.1f ms)\n", admit_slot,+ (long long) live.size(), std::chrono::duration<double, std::milli>(Clock::now() - tc0).count());+ }+ std::printf("BADM %d %d\n", admit_slot, cont ? 1 : 0);+ std::fflush(stdout);+ admit_slot = -1;+ }if (drive.routing != nullptr) std::fflush(drive.routing); // the routing trace survives a crash and is watchable mid-session// "12288 of 98179" when cancelled mid-read (#471), the rate from what was readchar read_txt[64];@@ -7315,6 +11309,14 @@ int main(int argc, char **argv) try {"VRAM tier, %lld blob reads from the file\n",(double) src.resident_bytes() / 1073741824.0, (long long) src.exchanges(),(long long) src.file_reads());+ if (ajob) // --adapt-async, cumulative (a round may still be in flight: it lands before the next request)+ std::fprintf(stderr, "strata serve: asynchronous adaptive tier: %lld rounds, %lld experts swapped in, "+ "%.1f ms per round (start to flip, between windows)\n",+ (long long) a_rounds, (long long) a_swapped, a_rounds > 0 ? a_ms / (double) a_rounds : 0.0);+ if (src.exchange_rotation())+ std::fprintf(stderr, "strata serve: exchange rotation: %llu blocks, %llu host memcpy bytes avoided (cumulative payload)\n",+ (unsigned long long)src.rotated_exchanges(),+ (unsigned long long)src.avoided_exchange_copy_bytes());// CS-T: the tiers, cumulative - GPU cache hits (the decode lookups above), RAM copy, files (SSD / OS cache)if (srcp == &src)std::fprintf(stderr, "strata serve: expert tiers: GPU %lld hits this request; since the start RAM %lld blobs, files %lld blobs "@@ -7349,6 +11351,14 @@ int main(int argc, char **argv) try {if (sfx_windows > 0)std::fprintf(stderr, "strata serve: suffix drafts: %lld windows, %lld of %lld drafts accepted\n",(long long) sfx_windows, (long long) sfx_ok, (long long) sfx_drafts);+ if (o.lookup_chain > 0)+ std::fprintf(stderr, "strata serve: lookup chain: %lld of %lld windows, %lld of %lld chained drafts accepted\n",+ (long long) chain_windows, (long long) dec_windows, (long long) chain_ok, (long long) chain_drafts);+ if (strata::core::MtpDrafter::top2_env())+ std::fprintf(stderr, "strata serve: mtp top2: rejected/runner-up by depth %lld/%lld %lld/%lld %lld/%lld %lld/%lld "+ "of %lld windows\n", (long long) t2_rej[0], (long long) t2_hit[0], (long long) t2_rej[1],+ (long long) t2_hit[1], (long long) t2_rej[2], (long long) t2_hit[2], (long long) t2_rej[3],+ (long long) t2_hit[3], (long long) dec_windows);for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0)std::fprintf(stderr, "strata serve: CUDA%d: %lld expert entries, %lld active layer launches, %.1f MiB returned ""(%.1f MiB with full rows) in this request; host %.0f ms staging+launching, %.0f ms "@@ -7382,6 +11392,7 @@ int main(int argc, char **argv) try {int64_t pos_start = 0;int64_t spec_pos = 0; // plan v0.3 P6: where the speculative loop starts (0 = not used)strata::prefill::Prefill prefill;+ bool kvg_started = false; // the elastic K/V took this run's cellsdouble prefill_batched_ms = 0;std::FILE* final_r = o.dump_final_r.empty() ? nullptr : std::fopen(o.dump_final_r.c_str(), "wb");std::vector<float> final_r_host(final_r ? (size_t) (g.hc * g.n_embd) : 0);@@ -7393,7 +11404,7 @@ int main(int argc, char **argv) try {if (!o.no_prefill_borrow && !host_res.empty() && d_res != nullptr) {int64_t chunk = o.prefill_chunk;int64_t k = plan_lend(chunk); // auto: the largest chunk that fits; fixed: halved to fit- const int64_t request_sized = request_chunk(n_batched, chunk);+ const int64_t request_sized = equal_chunk(n_batched, chunk);if (k > 0 && request_sized < chunk) { // no bigger than this prompt segment needschunk = request_sized;k = lend_slots(chunk);@@ -7409,15 +11420,17 @@ int main(int argc, char **argv) try {const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;if (k > 0) { // the lent slots are refilled after the promptconst int32_t first = (int32_t) (xcache.slots() - k);+ // the elastic K/V first: its hot experts move into slots of the loan, which are refilled after it+ kvg_started = true;+ kvg_start(first);+ if (!kvg_ensure(n_prompt + o.max_new + 64, [] {+ dpct::get_current_device().queues_wait_and_throw(); })) return 1;for (size_t i = 0; i < host_res.size(); ++i)if (host_res[i] >= first) {lent.emplace_back((int32_t) i, host_res[i]);host_res[i] = strata::core::kNotResident;}- dpct::get_in_order_queue()- .memcpy(d_res, host_res.data(),- host_res.size() * sizeof(int32_t))- .wait();+ res_put(d_res);borrow = xcache.device_slot(first);borrow_bytes = xcache.slot_offsets() ? (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[first]): (uint64_t) k * (uint64_t) blob;@@ -7446,6 +11459,12 @@ int main(int argc, char **argv) try {return e.empty() && mtp.prefill(R_rows, nxt.data(), T, p0, e);};}+ if (!kvg_started) { // the elastic K/V: every cell this run can reach (no loan)+ kvg_started = true;+ kvg_start(xcache.slots());+ if (!kvg_ensure(n_prompt + o.max_new + 64, [] {+ dpct::get_current_device().queues_wait_and_throw(); })) return 1;+ }const Clock::time_point tp0 = Clock::now();if (!prefill.run(o.tokens.data(), n_batched, 0, err)) {std::fprintf(stderr, "strata generate: %s\n", err.c_str());@@ -7476,10 +11495,11 @@ int main(int argc, char **argv) try {std::fprintf(stderr, "strata generate: refilling the lent slots failed: %s\n", err.c_str());return 1;}- dpct::get_in_order_queue()- .memcpy(d_res, host_res.data(),- host_res.size() * sizeof(int32_t))- .wait();+#if defined(_WIN32)+ for (const auto& [i, slot] : lent)+ srcp->release(i / g.n_expert, i % g.n_expert);+#endif+ res_put(d_res);std::fprintf(stderr, "strata generate: %zu lent slots refilled in %.1f ms\n", lent.size(),std::chrono::duration<double, std::milli>(Clock::now() - tr).count());}@@ -7498,6 +11518,12 @@ int main(int argc, char **argv) try {(long long) ps.experts_dma, ps.ms_experts_host, (long long) ps.experts_resident, ps.ms_ple);}+ if (!kvg_started) { // the elastic K/V of a prompt that was not read in batches+ kvg_started = true;+ kvg_start(xcache.slots());+ if (!kvg_ensure(n_prompt + o.max_new + 64, [] {+ dpct::get_current_device().queues_wait_and_throw(); })) return 1;+ }for (int64_t pos = pos_start;; ++pos) {// plan v0.3 P6: a native pack's last prompt token is the first verify window (T = 1)if (native_pack) { spec_pos = pos; break; }@@ -7773,16 +11799,24 @@ int main(int argc, char **argv) try {const bool ended = o.stop_eos && !produced.empty() &&std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) produced.back()) != o.eos_ids.end();if (spec_pos > 0 && (int64_t) produced.size() < o.max_new && !ended) {- std::vector<int64_t> oracle;- if (!o.spec_oracle.empty()) {- std::ifstream in(o.spec_oracle);+ auto read_ids = [](const std::string& path, std::vector<int64_t>& ids) {+ std::ifstream in(path);std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());std::string e;- if (!in || !parse_i64_list(text.c_str(), oracle, e)) {- std::fprintf(stderr, "strata generate: cannot read --spec-oracle %s\n", o.spec_oracle.c_str());- return 2;- }+ return (bool) in && parse_i64_list(text.c_str(), ids, e);+ };+ std::vector<int64_t> oracle, follow;+ if (!o.spec_oracle.empty() && !read_ids(o.spec_oracle, oracle)) {+ std::fprintf(stderr, "strata generate: cannot read --spec-oracle %s\n", o.spec_oracle.c_str());+ return 2;+ }+ if (!o.spec_follow.empty() && !read_ids(o.spec_follow, follow)) {+ std::fprintf(stderr, "strata generate: cannot read --spec-follow %s\n", o.spec_follow.c_str());+ return 2;}+ // --spec-follow: the run ends with the continuation+ const int64_t max_new = follow.empty() ? o.max_new : std::min<int64_t>(o.max_new, (int64_t) follow.size());+ int64_t follow_differ = 0, follow_emitted = 0;if (thits.d_res == nullptr) {std::fprintf(stderr, "strata generate: --spec needs the device residency table (--expert-profile, ""--expert-cache and the token graph)\n");@@ -7793,6 +11827,7 @@ int main(int argc, char **argv) try {strata::core::VerifyHits vh;vh.d_res = thits.d_res;if (mirror_table_d) strata::kernels::resident_plan_set_mirror(thits.d_res, mirror_table_d);+ vh.h_res = host_res.empty() ? nullptr : host_res.data();vh.cache_base = thits.cache_base;vh.blob = thits.blob;vh.slot_off = xcache.slot_offsets(); // E-6: the device plan's pointers@@ -7841,6 +11876,7 @@ int main(int argc, char **argv) try {}// plan v0.3 P6: swaps in flight - (residency index, slot) admitted when adapt_ev has completedstd::vector<std::pair<int32_t, int32_t>> pending;+ int pending_age = 0; // the windows the pending swaps have waited (adapt_lag)std::vector<void*> pin_live; // the swaps' locked arena pages (pin_blob), unlocked once they have landeddpct::event_ptr adapt_ev = nullptr;adapt_ev = new sycl::event();@@ -7868,15 +11904,9 @@ int main(int argc, char **argv) try {srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert); // in VRAM now: RAM not needed}pending.clear();+ pending_age = 0;if (d_res != nullptr)- /*- DPCT1114: cudaMemcpy is migrated to asynchronization- memcpy, assuming in the original code the source host memory is- pageable memory. If the memory is not pageable, call wait() on- event return by memcpy API to ensure synchronization behavior.- */- dpct::get_in_order_queue().memcpy(- d_res, host_res.data(), host_res.size() * sizeof(int32_t)).wait();+ res_put(d_res);}catch (sycl::exception const &exc) {std::cerr << exc.what() << "Exception caught at file:" << __FILE__@@ -7910,7 +11940,7 @@ int main(int argc, char **argv) try {const float* u = drive.d.usage.data() + l * g.n_expert;const int32_t* r = host_res.data() + l * g.n_expert;for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) {- if (r[e] < 0) { if (u[e] >= 2.0f) cand.emplace_back(u[e], e); }+ if (r[e] < 0) { if (u[e] >= 2.0f && !helper_holds(l, e)) cand.emplace_back(u[e], e); }else vict.emplace_back(u[e], e);}if (cand.empty() || vict.empty()) continue;@@ -7925,7 +11955,9 @@ int main(int argc, char **argv) try {}std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; });if ((int) swaps.size() > o.adapt_swaps) swaps.resize((size_t) o.adapt_swaps);- if (!resident_stage_swaps(src, xcache, host_res, g.n_expert, swaps, adapt_stream)) {+ // this (non-serve) path refills CUDA0's cache only, so its copies back read CUDA0's cache too+ if (!resident_stage_swaps(src, host_res, g.n_expert, swaps,+ [&](int64_t) -> SwapHome { return {&xcache, adapt_stream, -1}; })) {std::fprintf(stderr, "strata generate: an adaptive refill failed (copying evicted experts back)\n");return false;}@@ -7937,23 +11969,27 @@ int main(int argc, char **argv) try {(uintptr_t) b + strata::kernels::cpu::expert_layout().blob_bytes(s.layer));pin_blobs(std::move(spans), pin_live);}+ // STRATA_DMA_BATCH (F12): the round's copies as one cudaMemcpyBatchAsync; mode 0 is the loop of one copy each+ const int dma_mode = strata::core::dma_batch_mode();+ std::vector<void*> cp_dst;+ std::vector<const void*> cp_src;+ std::vector<size_t> cp_bytes;for (const Swap& s : swaps) {const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out;const int32_t slot = host_res[out];const uint8_t* b = srcp->blob(s.layer, s.in);+ const size_t blob_n = (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer);// asynchronous: the copies run while the MTP drafts; the next window waits for them- if (slot < 0 || b == nullptr ||- /*- DPCT1124: cudaMemcpyAsync is migrated to asynchronous- memcpy API. While the origin API might be synchronous, it- depends on the type of operand memory, so you may need to- call wait() on event return by memcpy API to ensure- synchronization behavior.- */- DPCT_CHECK_ERROR(adapt_stream->memcpy(- xcache.device_slot(slot), b,- (size_t)strata::kernels::cpu::expert_layout()- .blob_bytes(s.layer))) != 0) {+ if (slot < 0 || b == nullptr) {+ std::fprintf(stderr, "strata generate: an adaptive refill failed\n");+ return false;+ }+ if (dma_mode != 0) {+ cp_dst.push_back(xcache.device_slot(slot));+ cp_src.push_back(b);+ cp_bytes.push_back(blob_n);+ } else if (adapt_copy_h2d(xcache.device_slot(slot), b, blob_n,+ adapt_stream) != 0) {std::fprintf(stderr, "strata generate: an adaptive refill failed\n");return false;}@@ -7961,6 +11997,13 @@ int main(int argc, char **argv) try {srcp->prefetch(s.layer, s.out); // a file-backed arena released its pages: read them back aheadpending.emplace_back((int32_t) in, slot); // resident once the copy has landed}+ if (!cp_dst.empty() &&+ strata::core::copy_blobs(cp_dst.data(), cp_src.data(),+ cp_bytes.data(), cp_dst.size(),+ adapt_stream, dma_mode) != 0) {+ std::fprintf(stderr, "strata generate: an adaptive refill failed\n");+ return false;+ }if (!swaps.empty()) dpct::sync_barrier(adapt_ev, adapt_stream);if (trace_adapt)std::fprintf(stderr, "strata: ADAPT round=%lld swapped %zu of %d slots, usage decayed\n",@@ -7998,6 +12041,13 @@ int main(int argc, char **argv) try {return 1;}std::vector<int32_t> window((size_t) o.spec), outv((size_t) o.spec);+ std::vector<uint8_t> fdiff((size_t) o.spec, 0);+ std::FILE* hashes = o.window_hashes.empty() ? nullptr : std::fopen(o.window_hashes.c_str(), "w");+ if (!o.window_hashes.empty() && hashes == nullptr) {+ std::fprintf(stderr, "strata generate: cannot write %s\n", o.window_hashes.c_str());+ return 1;+ }+ std::vector<float> hash_rows;std::vector<int64_t> accepted_hist((size_t) o.spec, 0);int64_t rounds = 0, drafts_total = 0, drafts_ok = 0, corrupt_counter = 0;const int S_mtp = o.mtp_max_t > 0 ? std::min(o.mtp_max_t, o.spec) : o.spec;@@ -8006,13 +12056,22 @@ int main(int argc, char **argv) try {strata::spec::DraftPolicy policy(o.spec); // MTP or lookup window (see draft_policy.hpp)std::vector<int32_t> sbuf((size_t) o.spec, 0);int64_t sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0;- if (o.suffix_draft > 0) {+ int64_t chain_windows = 0, chain_drafts = 0, chain_ok = 0; // --lookup-chain's own counts+ std::vector<int32_t> cbuf((size_t) o.spec, 0), ctail;+ strata::spec::PromptLookupSource lookup_src(sfx);+ const bool sfx_on = o.suffix_draft > 0 || o.lookup_chain > 0;+ if (sfx_on) {for (int64_t t : o.tokens) sfx.append((int32_t) t);for (int64_t t : produced) sfx.append((int32_t) t);}+ if (o.lookup_chain > 0) {+ extra_sources_reset();+ for (int64_t t : o.tokens) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); }+ for (int64_t t : produced) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); }+ }const double pool_ms0 = drive.cpu_ms;const int64_t misses0 = drive.d.multi_misses, entries0 = drive.d.multi_entries;- while ((int64_t) produced.size() < o.max_new) {+ while ((int64_t) produced.size() < max_new) {const Clock::time_point t0 = Clock::now();int T = S_mtp;if (use_mtp && o.spec_min_p > 0.0) {@@ -8030,6 +12089,22 @@ int main(int argc, char **argv) try {if (pk.lookup) { T = pk.t; from_sfx = true; }}}+ // --lookup-chain: what followed an earlier occurrence of the context + the MTP's drafts, after them+ int chain_n = 0, cm = 0;+ if (o.lookup_chain > 0 && use_mtp && !first_window && !from_sfx && T < o.spec) {+ int csrc = -1;+ const int nt = chain_tail(sfx, drafts.data(), T - 1, ctail);+ chain_n = strata::spec::propose_from_sources(lookup_src, ctail.data(), nt, T - 1,+ std::min(o.lookup_chain, o.spec - T), o.lookup_chain_min,+ cbuf.data(), &cm, &csrc);+ if (chain_n > 0 && std::getenv("STRATA_LOOKUP_CHAIN_FIXED") == nullptr) {+ double p_mtp = 1.0;+ for (int i = 0; i < T - 1; ++i) p_mtp *= dprob[(size_t) i];+ chain_n = policy.chain(T, p_mtp, chain_n, cm);+ }+ }+ const int T_mtp = T;+ T += chain_n;const bool timed_round = !first_window;++window_hist[(size_t) T];if (p + T > o.max_context) {@@ -8041,6 +12116,7 @@ int main(int argc, char **argv) try {const size_t at = produced.size() - 1 + (size_t) i;int32_t d = from_sfx ? sbuf[(size_t) i - 1] : use_mtp ? drafts[(size_t) i - 1]: at < oracle.size() ? (int32_t) oracle[at] : 0;+ if (i >= T_mtp) d = cbuf[(size_t) (i - T_mtp)];if (o.spec_corrupt > 0 && (++corrupt_counter % o.spec_corrupt) == 0) d = (d + 1) % (int32_t) n_vocab;window[(size_t) i] = d;}@@ -8050,7 +12126,8 @@ int main(int argc, char **argv) try {// #463: the previous adapt round's copies land first - with a non-blocking query, whether a swapped-in// expert ran on the GPU or the CPU (they round differently) depended on the copy's timing// (STRATA_ADAPT_NOWAIT=1: 0.1.37's non-blocking query, the A/B)- apply_pending(!adapt_nowait());+ if (adapt_nowait()) apply_pending(false);+ else if (pending.empty() || ++pending_age >= adapt_lag()) apply_pending(true);if (!ver.run(T, window.data(), p, &drive_pool_multi, &drive, outv.data(), err)) {std::fprintf(stderr, "strata generate: %s\n", err.c_str());return 1;@@ -8061,6 +12138,27 @@ int main(int argc, char **argv) try {drive.d.fail ? drive.d.fail : "(no message)");return 1;}+ if (hashes != nullptr) { // FNV-1a over the window's final residual rows (a test path: a plain copy)+ const size_t n_floats = (size_t) T * (size_t) (g.hc * g.n_embd);+ hash_rows.resize(n_floats);+ dpct::get_in_order_queue()+ .memcpy(hash_rows.data(), ver.final_R_all(),+ n_floats * sizeof(float))+ .wait();+ uint64_t h = 1469598103934665603ull;+ const auto* bytes = (const uint8_t*) hash_rows.data();+ for (size_t i = 0; i < n_floats * sizeof(float); ++i) h = (h ^ bytes[i]) * 1099511628211ull;+ std::fprintf(hashes, "%lld %lld %d %016llx", (long long) rounds, (long long) p, T, (unsigned long long) h);+ for (int i = 0; i < T; ++i) std::fprintf(hashes, " %d", (int) outv[(size_t) i]);+ std::fprintf(hashes, "\n");+ }+ if (!follow.empty()) { // the continuation stands in for the argmax+ const size_t k0 = produced.size();+ for (int i = 0; i < T && k0 + (size_t) i < follow.size(); ++i) {+ fdiff[(size_t) i] = outv[(size_t) i] != (int32_t) follow[k0 + (size_t) i];+ outv[(size_t) i] = (int32_t) follow[k0 + (size_t) i];+ }+ }int a = 0;while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a;if (first_window) {@@ -8083,9 +12181,7 @@ int main(int argc, char **argv) try {bool adapt_ok = true;if (!drive.d.usage.empty() && ((rounds + 1) % o.adapt_every) == 0)adapt_thr = std::thread([&] { adapt_ok = adapt(); });- // SYCL port: the commit graph is left running while the drafter's round (its own queue) runs; collected- // below, before anything reads the committed state- if (!ver.commit(a + 1, err, /*wait=*/!use_mtp)) {+ if (!ver.commit(a + 1, err)) {if (adapt_thr.joinable()) adapt_thr.join();std::fprintf(stderr, "strata generate: %s\n", err.c_str());return 1;@@ -8095,19 +12191,22 @@ int main(int argc, char **argv) try {drafts_ok += a;++accepted_hist[(size_t) a];if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; }+ if (chain_n > 0) { ++chain_windows; chain_drafts += chain_n; chain_ok += std::max(0, a - (T_mtp - 1)); }bool eos = false;- for (int i = 0; i <= a && (int64_t) produced.size() < o.max_new && !eos; ++i) {+ for (int i = 0; i <= a && (int64_t) produced.size() < max_new && !eos; ++i) {produced.push_back(outv[(size_t) i]);- if (o.suffix_draft > 0) sfx.append(outv[(size_t) i]);+ if (sfx_on) sfx.append(outv[(size_t) i]);+ if (o.lookup_chain > 0) extra_sources_append(&outv[(size_t) i], 1);eos = o.stop_eos && std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end();+ if (!follow.empty()) { follow_differ += fdiff[(size_t) i]; ++follow_emitted; }}if (eos) {if (adapt_thr.joinable()) adapt_thr.join();- if (!ver.commit_finish(err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; }+ if (!ver.wait_commit(err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; }total_ms += std::chrono::duration<double, std::milli>(Clock::now() - t0).count();break;}- const bool drafted = !use_mtp || (int64_t) produced.size() >= o.max_new ||+ const bool drafted = !use_mtp || (int64_t) produced.size() >= max_new ||mtp.draft(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) o.spec_min_p);if (adapt_thr.joinable()) adapt_thr.join();if (!adapt_ok) return 1;@@ -8115,12 +12214,12 @@ int main(int argc, char **argv) try {std::fprintf(stderr, "strata generate: %s\n", err.c_str());return 1;}- if (!ver.commit_finish(err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; }x = outv[(size_t) a];p += a + 1;const double round_ms = std::chrono::duration<double, std::milli>(Clock::now() - t0).count();total_ms += round_ms;- if (timed_round) policy.observe(from_sfx, T, a, sfx_match, round_ms);+ if (timed_round && chain_n == 0) policy.observe(from_sfx, T, a, sfx_match, round_ms);+ else if (timed_round) policy.observe_chain(T_mtp, chain_n, a, cm, round_ms);if (rounds % 64 == 0)std::fprintf(stderr, "strata generate: position %lld, %lld tokens, %lld rounds\n", (long long) p,(long long) produced.size(), (long long) rounds);@@ -8130,10 +12229,14 @@ int main(int argc, char **argv) try {std::fprintf(stderr, "strata generate: %s\n", err.c_str());return 1;}+ if (hashes != nullptr) std::fclose(hashes);std::printf("%-24s %lld rounds of %d, drafts accepted %lld of %lld (%.3f), %.2f tokens per round\n","speculation", (long long) rounds, o.spec, (long long) drafts_ok, (long long) drafts_total,drafts_total > 0 ? (double) drafts_ok / (double) drafts_total : 0.0,rounds > 0 ? (double) (drafts_ok + rounds) / (double) rounds : 0.0);+ if (!follow.empty())+ std::printf("%-24s %lld of %lld emitted tokens differ from the argmax\n", "follow",+ (long long) follow_differ, (long long) follow_emitted);if (o.spec_min_p > 0.0) {std::printf("%-24s", "window sizes");for (size_t i = 1; i < window_hist.size(); ++i) std::printf(" T%zu:%lld", i, (long long) window_hist[i]);@@ -8142,6 +12245,9 @@ int main(int argc, char **argv) try {if (o.suffix_draft > 0)std::printf("%-24s %lld windows, drafts accepted %lld of %lld\n", "suffix drafts", (long long) sfx_windows,(long long) sfx_ok, (long long) sfx_drafts);+ if (o.lookup_chain > 0)+ std::printf("%-24s %lld windows, chained drafts accepted %lld of %lld\n", "lookup chain",+ (long long) chain_windows, (long long) chain_ok, (long long) chain_drafts);std::printf("%-24s", "accepted per round");for (size_t i = 0; i < accepted_hist.size(); ++i) std::printf(" %zu:%lld", i, (long long) accepted_hist[i]);std::printf("\n");@@ -8340,6 +12446,10 @@ int main(int argc, char **argv) try {? (double) xcache.resident() / (double) xcache.slots(): 0.0));}+ if (kvg.on)+ std::printf("%-24s %lld cells in VRAM, %lld grows, %lld trims, %lld experts given up, %lld refilled\n",+ " elastic K/V", (long long) kvg.cells, (long long) kvg.grows, (long long) kvg.trims,+ (long long) kvg.evicted, (long long) kvg.refilled);if (tgraph.captured && tgraph.calls > 0) {const double per = (double) tgraph.calls;std::printf("%-24s wait for rings %.3f pool %.3f ms/token (%lld flushes over %lld positions)\n",diff --git a/sycl/tools/build.sh b/sycl/tools/build.shindex 61a2fe415..ff6455610 100644--- a/sycl/tools/build.sh+++ b/sycl/tools/build.sh@@ -1,7 +1,7 @@#!/usr/bin/env bash# Configure + build the SYCL port inside strata-sycl-dev. sycl/build.sh [target...]set -uo pipefail-source /opt/intel/oneapi/setvars.sh >/dev/null 2>&1 || true+set +u; source /opt/intel/oneapi/setvars.sh >/dev/null 2>&1 || true; set -urepo=${REPO:-$(git rev-parse --show-toplevel)}b=${BUILD_DIR:-$repo/build-sycl}[ -f $b/build.ninja ] || cmake -S $repo/sycl -B $b -G Ninja -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx \diff --git a/sycl/tools/merge_upstream.py b/sycl/tools/merge_upstream.pyindex 3306ed2d6..307035a21 100644--- a/sycl/tools/merge_upstream.py+++ b/sycl/tools/merge_upstream.py@@ -23,7 +23,7 @@ for f in changed:print("NOT-MIGRATED (original used)" if not os.path.exists(pf) else "PORT-HAS-NO-DPCT?", rel); continuent = open(nf).read()if not os.path.exists(pf):- shutil.copy(nf, pf); print("NEWCOPY", rel); continue+ os.makedirs(os.path.dirname(pf), exist_ok=True); os.makedirs(os.path.dirname(pf), exist_ok=True); shutil.copy(nf, pf); print("NEWCOPY", rel); continueif not os.path.exists(bf):print("NO-BASE (new to dpct output)", rel); continuebt = open(bf).read()diff --git a/sycl/tools/migrate.sh b/sycl/tools/migrate.shindex 44994eb86..42b0d5b9f 100755--- a/sycl/tools/migrate.sh+++ b/sycl/tools/migrate.sh@@ -8,7 +8,7 @@ set -euo pipefailrepo=${1:-/work/Strata_B70}out=${2:-$repo/sycl}hdr=${CUDA_HEADERS:-/cuda-headers/include}-source /opt/intel/oneapi/setvars.sh >/dev/null 2>&1 || true+set +u; source /opt/intel/oneapi/setvars.sh >/dev/null 2>&1 || true; set -uexport PATH=/opt/intel/oneapi/dpcpp-ct/latest/bin:$PATHcd "$repo"# the compilation database: every .cu plus every .cpp/.hpp that includes a CUDA header@@ -20,6 +20,8 @@ repo, hdr, db_dir = sys.argv[1], sys.argv[2], sys.argv[3]files = subprocess.check_output(["bash", "-c",r"find src -name '*.cu'; grep -rl 'cuda_runtime\|cublas_v2\|cuda_fp16\|cuda\.h' src --include='*.cpp'"],cwd=repo, text=True).split()+if os.environ.get("MIGRATE_ONLY"): # explicit list: host files that reach CUDA only through the headers (verify.cpp, mtp.cpp)+ files = os.environ["MIGRATE_ONLY"].split()db = []# not in this tree: the optional ggml MMQ prefill path needs llama.cpp's ggml-cuda sources, and one parity test needs# ggml-cpu.h. Both stay CUDA-only for now.