Merge commit 'efddd28358' into f-ling32-int

This commit is contained in:
Niko1221 committed 2026-12-03 01:07:58 +01:00
commit ed115c6300
31 files changed
+6003 -3

No files matched your search

@@ -0,0 +1,3 @@
// SYCL build of Ling: no CUDA half types in the shared host code; the SYCL kernels use sycl::half. (Present only so that `#include <cuda_fp16.h>` resolves.)
#pragma once
#include "cuda_runtime.h"
@@ -0,0 +1,407 @@
// strata/sycl_compat/cuda_runtime.h - the subset of the CUDA runtime API that the Ling-3.2-Air host code uses (engine, model loader, tier store, spec driver, main, tests),
// implemented on SYCL / Level Zero. It plays the role that include/strata/hip_compat/cuda_runtime.h plays for AMD: the shared host files compile unchanged
// (`#include <cuda_runtime.h>` finds this header first, STRATA_USE_SYCL=1), and only the kernels have SYCL versions (src/ling32/sycl/).
//
// Mapping
// cudaStream_t in-order sycl::queue (strata::sy::Stream); the null stream is the device's default stream (also in-order)
// cudaEvent_t the sycl::event of a barrier submitted at cudaEventRecord
// cudaMalloc sycl::malloc_device; cudaHostAlloc / cudaMallocHost: sycl::malloc_host (pinned, device-visible, same pointer on the GPU: cudaHostGetDevicePointer returns it)
// cudaHostRegister NOT supported on Level Zero (cudaErrorNotSupported): callers fall back to cudaHostAlloc / pageable paths
// cudaGraph* NOT supported yet (cudaStreamBeginCapture returns cudaErrorNotSupported); the engine only captures when opt.cuda_graph is set
// A kernel launcher gets the SYCL queue of a stream with strata::sy::queue_of(stream).
#pragma once
#include <sycl/sycl.hpp>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <string>
#include <vector>
#ifndef STRATA_USE_SYCL
#define STRATA_USE_SYCL 1
#endif
namespace strata::sy {
struct Stream {
sycl::queue q;
int dev = 0;
};
struct Event {
sycl::event ev;
bool recorded = false;
double host_t = 0; // steady-clock seconds when the record call returned (cudaEventElapsedTime falls back to it)
};
inline double host_now() { return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count(); }
struct DevState {
sycl::device dev;
sycl::context ctx;
Stream* def = nullptr; // the null stream
std::atomic<uint64_t> allocated{0}; // bytes of cudaMalloc not yet freed (cudaMemGetInfo fallback when the driver gives no free-memory query)
explicit DevState(const sycl::device& d) : dev(d), ctx(d) {}
};
struct Runtime {
std::vector<DevState*> devs;
std::mutex mu;
std::vector<Stream*> streams; // every stream ever created (cudaDeviceSynchronize)
int err_last = 0;
Runtime() {
// STRATA_SY_RELAXED_LIMITS=1: allocations above the 4 GiB per-allocation limit of Alchemist (Level Zero maxMemAllocSize); must be set before the first SYCL call creates the Level Zero adapter
if (const char* r = std::getenv("STRATA_SY_RELAXED_LIMITS")) if (r[0] == '1') {
#ifdef _WIN32
_putenv_s("UR_L0_ENABLE_RELAXED_ALLOCATION_LIMITS", "1");
#else
setenv("UR_L0_ENABLE_RELAXED_ALLOCATION_LIMITS", "1", 1);
#endif
}
// Level Zero GPUs first (ONEAPI_DEVICE_SELECTOR=level_zero:gpu narrows the list already); other backends only when there is no Level Zero GPU
for (int pass = 0; pass < 2 && devs.empty(); ++pass)
for (auto& d : sycl::device::get_devices(sycl::info::device_type::gpu))
if (pass == 1 || d.get_backend() == sycl::backend::ext_oneapi_level_zero) devs.push_back(new DevState(d));
for (size_t i = 0; i < devs.size(); ++i) {
auto* s = new Stream{sycl::queue(devs[i]->ctx, devs[i]->dev, sycl::property_list{sycl::property::queue::in_order()}), static_cast<int>(i)};
devs[i]->def = s;
streams.push_back(s);
}
}
};
inline Runtime& rt() {
static Runtime r;
return r;
}
inline int& cur_dev() {
static thread_local int d = 0;
return d;
}
inline DevState& dev_state(int i = -1) {
auto& r = rt();
if (i < 0) i = cur_dev();
if (r.devs.empty()) { std::fprintf(stderr, "strata sycl: no GPU device found (set ONEAPI_DEVICE_SELECTOR=level_zero:gpu)\n"); std::abort(); }
return *r.devs[static_cast<size_t>(i) < r.devs.size() ? i : 0];
}
// the queue of a stream (nullptr: the default stream of the current device)
inline sycl::queue& queue_of(Stream* s) { return s ? s->q : dev_state().def->q; }
} // namespace strata::sy
typedef strata::sy::Stream* cudaStream_t;
typedef strata::sy::Event* cudaEvent_t;
typedef int cudaError_t;
struct dim3 {
unsigned x = 1, y = 1, z = 1;
dim3() = default;
dim3(unsigned a, unsigned b = 1, unsigned c = 1) : x(a), y(b), z(c) {}
};
enum : int {
cudaSuccess = 0,
cudaErrorMemoryAllocation = 2,
cudaErrorNotReady = 600,
cudaErrorNotSupported = 801,
cudaErrorInvalidValue = 1,
cudaErrorUnknown = 999,
};
enum cudaMemcpyKind { cudaMemcpyHostToHost = 0, cudaMemcpyHostToDevice = 1, cudaMemcpyDeviceToHost = 2, cudaMemcpyDeviceToDevice = 3, cudaMemcpyDefault = 4 };
enum : unsigned {
cudaHostAllocDefault = 0, cudaHostAllocPortable = 1, cudaHostAllocMapped = 2, cudaHostAllocWriteCombined = 4,
cudaHostRegisterDefault = 0, cudaHostRegisterPortable = 1, cudaHostRegisterMapped = 2,
cudaStreamDefault = 0, cudaStreamNonBlocking = 1,
cudaEventDefault = 0, cudaEventDisableTiming = 2,
};
enum cudaDeviceAttr { cudaDevAttrComputeCapabilityMajor = 75, cudaDevAttrComputeCapabilityMinor = 76, cudaDevAttrMultiProcessorCount = 16, cudaDevAttrMaxSharedMemoryPerBlockOptin = 97 };
struct cudaDeviceProp {
char name[256];
size_t totalGlobalMem;
size_t sharedMemPerBlock;
int major, minor;
int multiProcessorCount;
int maxThreadsPerBlock;
int warpSize;
int integrated;
int unifiedAddressing;
int pageableMemoryAccess;
int concurrentManagedAccess;
int canMapHostMemory;
};
inline const char* cudaGetErrorString(cudaError_t e) {
switch (e) {
case cudaSuccess: return "no error";
case cudaErrorMemoryAllocation: return "out of memory";
case cudaErrorNotReady: return "not ready";
case cudaErrorNotSupported: return "not supported on SYCL / Level Zero";
case cudaErrorInvalidValue: return "invalid value";
default: return "SYCL runtime error";
}
}
inline cudaError_t cudaGetLastError() { auto& r = strata::sy::rt(); int e = r.err_last; r.err_last = 0; return e; }
inline cudaError_t cudaPeekAtLastError() { return strata::sy::rt().err_last; }
namespace strata::sy {
inline cudaError_t fail(cudaError_t e) { rt().err_last = e; return e; }
template <class F>
inline cudaError_t guard(F&& f, cudaError_t on_exc = cudaErrorUnknown) {
try { f(); return cudaSuccess; }
catch (const sycl::exception& ex) {
if (std::getenv("STRATA_SY_VERBOSE")) std::fprintf(stderr, "strata sycl: %s\n", ex.what());
return fail(on_exc);
}
}
} // namespace strata::sy
// ---- devices
inline cudaError_t cudaGetDeviceCount(int* n) { *n = static_cast<int>(strata::sy::rt().devs.size()); return cudaSuccess; }
inline cudaError_t cudaGetDevice(int* d) { *d = strata::sy::cur_dev(); return cudaSuccess; }
inline cudaError_t cudaSetDevice(int d) {
if (d < 0 || static_cast<size_t>(d) >= strata::sy::rt().devs.size()) return strata::sy::fail(cudaErrorInvalidValue);
strata::sy::cur_dev() = d;
return cudaSuccess;
}
inline cudaError_t cudaGetDeviceProperties(cudaDeviceProp* p, int d) {
return strata::sy::guard([&] {
auto& ds = strata::sy::dev_state(d);
std::memset(p, 0, sizeof *p);
const std::string n = ds.dev.get_info<sycl::info::device::name>();
std::strncpy(p->name, n.c_str(), sizeof p->name - 1);
p->totalGlobalMem = ds.dev.get_info<sycl::info::device::global_mem_size>();
p->sharedMemPerBlock = ds.dev.get_info<sycl::info::device::local_mem_size>();
p->multiProcessorCount = static_cast<int>(ds.dev.get_info<sycl::info::device::max_compute_units>());
p->maxThreadsPerBlock = static_cast<int>(ds.dev.get_info<sycl::info::device::max_work_group_size>());
p->warpSize = 32;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
p->integrated = ds.dev.get_info<sycl::info::device::host_unified_memory>() ? 1 : 0;
#pragma clang diagnostic pop
p->unifiedAddressing = 1; // USM: a pinned (malloc_host) pointer is valid on the device
p->pageableMemoryAccess = 0;
p->canMapHostMemory = 1;
p->major = 0; // no CUDA compute capability: the engine takes its non-tensor-core branches
p->minor = 0;
});
}
inline cudaError_t cudaDeviceGetAttribute(int* v, cudaDeviceAttr a, int d) {
cudaDeviceProp p;
cudaError_t e = cudaGetDeviceProperties(&p, d);
if (e != cudaSuccess) return e;
switch (a) {
case cudaDevAttrComputeCapabilityMajor: *v = 0; break;
case cudaDevAttrComputeCapabilityMinor: *v = 0; break;
case cudaDevAttrMultiProcessorCount: *v = p.multiProcessorCount; break;
case cudaDevAttrMaxSharedMemoryPerBlockOptin: *v = static_cast<int>(p.sharedMemPerBlock); break;
}
return cudaSuccess;
}
inline cudaError_t cudaMemGetInfo(size_t* free_b, size_t* total_b) {
return strata::sy::guard([&] {
auto& ds = strata::sy::dev_state();
const size_t total = ds.dev.get_info<sycl::info::device::global_mem_size>();
size_t fr = 0;
bool ok = false;
if (ds.dev.has(sycl::aspect::ext_intel_free_memory)) {
try { fr = ds.dev.get_info<sycl::ext::intel::info::device::free_memory>(); ok = fr > 0; } catch (...) {}
}
if (!ok) { const size_t used = ds.allocated.load(); fr = total > used ? total - used : 0; } // no driver query (Windows without sysman): our own allocations only
if (free_b) *free_b = fr;
if (total_b) *total_b = total;
});
}
inline cudaError_t cudaDeviceSynchronize() {
return strata::sy::guard([&] {
auto& r = strata::sy::rt();
std::vector<strata::sy::Stream*> ss;
{ std::lock_guard<std::mutex> g(r.mu); ss = r.streams; }
for (auto* s : ss) s->q.wait_and_throw();
});
}
// ---- memory
inline cudaError_t cudaMalloc(void** p, size_t n) {
*p = nullptr;
auto& ds = strata::sy::dev_state();
cudaError_t e = strata::sy::guard([&] { *p = sycl::malloc_device(n ? n : 1, ds.dev, ds.ctx); }, cudaErrorMemoryAllocation);
if (e == cudaSuccess && !*p) return strata::sy::fail(cudaErrorMemoryAllocation);
if (e == cudaSuccess) ds.allocated += n;
return e;
}
template <class T>
inline cudaError_t cudaMalloc(T** p, size_t n) { return cudaMalloc(reinterpret_cast<void**>(p), n); }
inline cudaError_t cudaFree(void* p) {
if (!p) return cudaSuccess;
auto& ds = strata::sy::dev_state();
return strata::sy::guard([&] { sycl::free(p, ds.ctx); }); // the byte count of `allocated` is not tracked per pointer: the fallback free-memory figure only grows
}
inline cudaError_t cudaHostAlloc(void** p, size_t n, unsigned = 0) {
*p = nullptr;
auto& ds = strata::sy::dev_state();
// 64 KiB aligned: O_DIRECT / FILE_FLAG_NO_BUFFERING reads (DirectFile) land in these blocks and need 4 KiB aligned buffers
cudaError_t e = strata::sy::guard([&] { *p = sycl::aligned_alloc_host(65536, n ? n : 1, ds.ctx); }, cudaErrorMemoryAllocation);
if (e == cudaSuccess && !*p) return strata::sy::fail(cudaErrorMemoryAllocation);
return e;
}
inline cudaError_t cudaMallocHost(void** p, size_t n) { return cudaHostAlloc(p, n, 0); }
template <class T>
inline cudaError_t cudaMallocHost(T** p, size_t n) { return cudaHostAlloc(reinterpret_cast<void**>(p), n, 0); }
inline cudaError_t cudaFreeHost(void* p) {
if (!p) return cudaSuccess;
auto& ds = strata::sy::dev_state();
return strata::sy::guard([&] { sycl::free(p, ds.ctx); });
}
inline cudaError_t cudaHostRegister(void*, size_t, unsigned) { return strata::sy::fail(cudaErrorNotSupported); }
inline cudaError_t cudaHostUnregister(void*) { return cudaSuccess; }
inline cudaError_t cudaHostGetDevicePointer(void** dp, void* hp, unsigned) {
auto& ds = strata::sy::dev_state();
if (sycl::get_pointer_type(hp, ds.ctx) != sycl::usm::alloc::host) return strata::sy::fail(cudaErrorInvalidValue); // only malloc_host memory is visible to the device
*dp = hp;
return cudaSuccess;
}
inline cudaError_t cudaMemcpy(void* dst, const void* src, size_t n, cudaMemcpyKind = cudaMemcpyDefault) {
if (!n) return cudaSuccess;
return strata::sy::guard([&] { strata::sy::queue_of(nullptr).memcpy(dst, src, n).wait_and_throw(); });
}
// A copy from ordinary (pageable) host memory: CUDA has read the source by the time cudaMemcpyAsync returns (it stages it), so callers reuse or free the buffer at once (a stack variable, a std::vector).
// Level Zero reads a pageable source when the copy RUNS. Small pageable sources are therefore copied at enqueue time into a pinned staging block that goes back to the pool when the copy has finished;
// big ones (a copy from an unpinned warm tier) are waited for (the stream is in order, so the wait also drains the work before it). A pageable destination is waited for as well (CUDA does the same).
// Sources / destinations that are USM (malloc_host, malloc_device) are never touched by this.
namespace strata::sy {
constexpr size_t kStageBlock = 256 * 1024;
struct StagePool {
struct Slot { void* p = nullptr; sycl::event ev; bool busy = false; };
std::mutex mu;
std::vector<Slot> slots;
bool reclaim(Slot& s) {
if (!s.busy) return true;
try { if (s.ev.get_info<sycl::info::event::command_execution_status>() == sycl::info::event_command_status::complete) { s.busy = false; return true; } } catch (...) { s.busy = false; return true; }
return false;
}
// a free block (waits for the oldest copy when 64 are in flight)
Slot* acquire() {
for (auto& s : slots) if (s.p && reclaim(s)) return &s;
if (slots.size() < 64) {
auto& ds = dev_state();
slots.emplace_back();
slots.back().p = sycl::aligned_alloc_host(4096, kStageBlock, ds.ctx);
if (!slots.back().p) { slots.pop_back(); return nullptr; }
return &slots.back();
}
slots.front().ev.wait();
slots.front().busy = false;
return &slots.front();
}
};
inline StagePool& stage_pool() { static StagePool* p = new StagePool; return *p; }
inline bool is_usm(const void* p) { return sycl::get_pointer_type(p, dev_state().ctx) != sycl::usm::alloc::unknown; }
} // namespace strata::sy
inline cudaError_t cudaMemcpyAsync(void* dst, const void* src, size_t n, cudaMemcpyKind = cudaMemcpyDefault, cudaStream_t s = nullptr) {
if (!n) return cudaSuccess;
return strata::sy::guard([&] {
sycl::queue& q = strata::sy::queue_of(s);
const bool src_page = !strata::sy::is_usm(src), dst_page = !strata::sy::is_usm(dst);
if (src_page && !dst_page && n <= strata::sy::kStageBlock) {
auto& sp = strata::sy::stage_pool();
std::lock_guard<std::mutex> g(sp.mu);
auto* slot = sp.acquire();
if (slot) {
std::memcpy(slot->p, src, n);
slot->ev = q.memcpy(dst, slot->p, n);
slot->busy = true;
return;
}
}
sycl::event ev = q.memcpy(dst, src, n);
if (src_page || dst_page) ev.wait_and_throw();
});
}
inline cudaError_t cudaMemset(void* p, int v, size_t n) {
if (!n) return cudaSuccess;
return strata::sy::guard([&] { strata::sy::queue_of(nullptr).memset(p, v, n).wait_and_throw(); });
}
inline cudaError_t cudaMemsetAsync(void* p, int v, size_t n, cudaStream_t s = nullptr) {
if (!n) return cudaSuccess;
return strata::sy::guard([&] { strata::sy::queue_of(s).memset(p, v, n); });
}
// ---- streams
inline cudaError_t cudaStreamCreate(cudaStream_t* s) {
return strata::sy::guard([&] {
auto& ds = strata::sy::dev_state();
auto* st = new strata::sy::Stream{sycl::queue(ds.ctx, ds.dev, sycl::property_list{sycl::property::queue::in_order()}), strata::sy::cur_dev()};
{ std::lock_guard<std::mutex> g(strata::sy::rt().mu); strata::sy::rt().streams.push_back(st); }
*s = st;
});
}
inline cudaError_t cudaStreamCreateWithFlags(cudaStream_t* s, unsigned) { return cudaStreamCreate(s); }
inline cudaError_t cudaStreamDestroy(cudaStream_t s) {
if (!s) return cudaSuccess;
return strata::sy::guard([&] {
s->q.wait_and_throw();
auto& r = strata::sy::rt();
std::lock_guard<std::mutex> g(r.mu);
for (size_t i = 0; i < r.streams.size(); ++i) if (r.streams[i] == s) { r.streams.erase(r.streams.begin() + i); break; }
delete s;
});
}
inline cudaError_t cudaStreamSynchronize(cudaStream_t s) { return strata::sy::guard([&] { strata::sy::queue_of(s).wait_and_throw(); }); }
// ---- events
inline cudaError_t cudaEventCreate(cudaEvent_t* e) { *e = new strata::sy::Event; return cudaSuccess; }
inline cudaError_t cudaEventCreateWithFlags(cudaEvent_t* e, unsigned) { return cudaEventCreate(e); }
inline cudaError_t cudaEventDestroy(cudaEvent_t e) { delete e; return cudaSuccess; }
inline cudaError_t cudaEventRecord(cudaEvent_t e, cudaStream_t s = nullptr) {
return strata::sy::guard([&] {
e->ev = strata::sy::queue_of(s).ext_oneapi_submit_barrier();
e->recorded = true;
e->host_t = strata::sy::host_now();
});
}
inline cudaError_t cudaStreamWaitEvent(cudaStream_t s, cudaEvent_t e, unsigned = 0) {
if (!e->recorded) return cudaSuccess;
return strata::sy::guard([&] { strata::sy::queue_of(s).ext_oneapi_submit_barrier(std::vector<sycl::event>{e->ev}); });
}
inline cudaError_t cudaEventSynchronize(cudaEvent_t e) {
if (!e->recorded) return cudaSuccess;
return strata::sy::guard([&] { e->ev.wait_and_throw(); e->host_t = strata::sy::host_now(); });
}
inline cudaError_t cudaEventQuery(cudaEvent_t e) {
if (!e->recorded) return cudaSuccess;
try {
return e->ev.get_info<sycl::info::event::command_execution_status>() == sycl::info::event_command_status::complete ? cudaSuccess : cudaErrorNotReady;
} catch (...) { return strata::sy::fail(cudaErrorUnknown); }
}
// milliseconds between two recorded events: host clock at the (synchronized) completion; only meaningful after both events were synchronized
inline cudaError_t cudaEventElapsedTime(float* ms, cudaEvent_t a, cudaEvent_t b) {
*ms = static_cast<float>((b->host_t - a->host_t) * 1e3);
return cudaSuccess;
}
#ifndef CUDART_CB
#define CUDART_CB
#endif
// ---- host functions in a stream
inline cudaError_t cudaLaunchHostFunc(cudaStream_t s, void (*fn)(void*), void* ud) {
return strata::sy::guard([&] { strata::sy::queue_of(s).submit([=](sycl::handler& h) { h.host_task([=] { fn(ud); }); }); });
}
// ---- CUDA-only kernel attributes (never reached on SYCL; present so that the shared templates in ling32_kernels.hpp compile)
enum cudaFuncAttribute { cudaFuncAttributeMaxDynamicSharedMemorySize = 8 };
template <class F> inline cudaError_t cudaFuncSetAttribute(F, cudaFuncAttribute, int) { return cudaSuccess; }
template <class F> inline cudaError_t cudaOccupancyMaxActiveBlocksPerMultiprocessor(int* n, F, int, size_t) { *n = 1; return cudaSuccess; }
// ---- graphs: not available yet
typedef void* cudaGraph_t;
typedef void* cudaGraphExec_t;
enum cudaStreamCaptureMode { cudaStreamCaptureModeGlobal = 0, cudaStreamCaptureModeThreadLocal = 1, cudaStreamCaptureModeRelaxed = 2 };
inline cudaError_t cudaStreamBeginCapture(cudaStream_t, cudaStreamCaptureMode = cudaStreamCaptureModeGlobal) { return strata::sy::fail(cudaErrorNotSupported); }
inline cudaError_t cudaStreamEndCapture(cudaStream_t, cudaGraph_t*) { return strata::sy::fail(cudaErrorNotSupported); }
inline cudaError_t cudaGraphInstantiate(cudaGraphExec_t*, cudaGraph_t, unsigned long long = 0) { return strata::sy::fail(cudaErrorNotSupported); }
inline cudaError_t cudaGraphLaunch(cudaGraphExec_t, cudaStream_t) { return strata::sy::fail(cudaErrorNotSupported); }
inline cudaError_t cudaGraphDestroy(cudaGraph_t) { return cudaSuccess; }
inline cudaError_t cudaGraphExecDestroy(cudaGraphExec_t) { return cudaSuccess; }
+85 -1
View File
@@ -28,6 +28,9 @@ set(LING32_HIP_ARCH "gfx1151;gfx1201" CACHE STRING "HIP architectures (semicolon
if(LING32_HIP)
set(CMAKE_HIP_ARCHITECTURES ${LING32_HIP_ARCH}) # before the first target, so that every target gets them
endif()
option(LING32_SYCL "Build the engine and its kernel tests for Intel GPUs (SYCL / Level Zero, oneAPI DPC++ icx / icpx); the host files are the CUDA ones compiled through include/strata/sycl_compat, the kernels are src/ling32/sycl/" OFF)
set(LING32_SYCL_EXTRA_FLAGS "" CACHE STRING "extra SYCL compile and link flags, space separated (experiments, e.g. -ftarget-register-alloc-mode=bmg:large)")
set(LING32_SYCL_TARGETS "spir64,intel_gpu_bmg_g31" CACHE STRING "SYCL device targets: spir64 = JIT from SPIR-V (any Intel GPU), intel_gpu_bmg_g31 = Arc Pro B70 AOT (add intel_gpu_acm_g10 for Alchemist AOT)")
get_filename_component(engine_root "${CMAKE_CURRENT_SOURCE_DIR}/../.." ABSOLUTE)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -106,7 +109,88 @@ if(Python3_FOUND)
set_tests_properties(ling32_codec_test PROPERTIES FIXTURES_REQUIRED "ling32_fixture;ling32_codec_vectors")
endif()
if(LING32_CUDA OR LING32_HIP)
if(LING32_SYCL)
# icx / icpx default to a fast-math floating-point model (reassociation, contraction): the CPU codecs and the CPU expert emulation must round like the GCC / MSVC builds and the GPU kernels
if(WIN32)
target_compile_options(ling32_core PRIVATE /fp:precise)
else()
target_compile_options(ling32_core PRIVATE -ffp-model=precise -ffp-contract=off)
endif()
# same host sources as CUDA / HIP (compiled as C++ against sycl_compat/cuda_runtime.h), kernels in sycl/
set(_ling32_host_srcs ling32_model.cu ling32_engine.cu ling32_tier_store.cu)
set(_ling32_sy_srcs sycl/ling32_sy_todo.cpp sycl/ling32_sy_core.cpp)
file(GLOB _ling32_sy_impl CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/sycl/ling32_sy_k_*.cpp")
set_source_files_properties(${_ling32_host_srcs} PROPERTIES LANGUAGE CXX)
add_library(ling32_gpu STATIC ${_ling32_host_srcs} ${_ling32_sy_srcs} ${_ling32_sy_impl})
target_include_directories(ling32_gpu BEFORE PUBLIC "${engine_root}/include/strata/sycl_compat")
target_include_directories(ling32_gpu PUBLIC ${engine_root}/include ${CMAKE_CURRENT_SOURCE_DIR})
target_compile_definitions(ling32_gpu PUBLIC STRATA_USE_SYCL=1)
if(WIN32)
target_compile_definitions(ling32_gpu PUBLIC NOMINMAX _CRT_SECURE_NO_WARNINGS)
target_compile_options(ling32_gpu PUBLIC /fsycl /O2 /fp:precise /clang:-foffload-fp32-prec-div /clang:-foffload-fp32-prec-sqrt "-fsycl-targets=${LING32_SYCL_TARGETS}")
target_link_options(ling32_gpu PUBLIC /fsycl -foffload-fp32-prec-div -foffload-fp32-prec-sqrt "-fsycl-targets=${LING32_SYCL_TARGETS}")
else()
target_compile_options(ling32_gpu PUBLIC -fsycl -O3 -ffp-model=precise -foffload-fp32-prec-div -foffload-fp32-prec-sqrt "-fsycl-targets=${LING32_SYCL_TARGETS}")
target_link_options(ling32_gpu PUBLIC -fsycl -ffp-model=precise -foffload-fp32-prec-div -foffload-fp32-prec-sqrt "-fsycl-targets=${LING32_SYCL_TARGETS}")
endif()
if(LING32_SYCL_EXTRA_FLAGS)
separate_arguments(_sy_extra NATIVE_COMMAND "${LING32_SYCL_EXTRA_FLAGS}")
target_compile_options(ling32_gpu PUBLIC ${_sy_extra})
target_link_options(ling32_gpu PUBLIC ${_sy_extra})
endif()
target_link_libraries(ling32_gpu PUBLIC ling32_core)
target_compile_definitions(strata-ling32 PRIVATE LING32_HAVE_CUDA=1)
target_link_libraries(strata-ling32 PRIVATE ling32_gpu)
foreach(_t ling32_kernel_test ling32_model_test ling32_forward_test ling32_spec_test)
set_source_files_properties(${_tests_dir}/${_t}.cu PROPERTIES LANGUAGE CXX)
add_executable(${_t} ${_tests_dir}/${_t}.cu)
target_link_libraries(${_t} PRIVATE ling32_gpu)
endforeach()
add_test(NAME ling32_kernel_test COMMAND ling32_kernel_test ${_tests_dir}/data ${_fixture})
add_test(NAME ling32_model_test COMMAND ling32_model_test ${_fixture})
add_executable(ling32_moe_sy_test ${_tests_dir}/ling32_moe_sy_test.cpp) # L32-SY-MOE: routed experts, router, swiglu, combine against their CPU models
target_link_libraries(ling32_moe_sy_test PRIVATE ling32_gpu)
add_test(NAME ling32_moe_sy_test COMMAND ling32_moe_sy_test ${_tests_dir}/data)
add_executable(ling32_sy_mla_fd_test ${_tests_dir}/ling32_sy_mla_fd_test.cpp) # L32-SY-MLA: flash-decoding MLA attention against the original kernel
target_link_libraries(ling32_sy_mla_fd_test PRIVATE ling32_gpu)
add_test(NAME ling32_sy_mla_fd_test COMMAND ling32_sy_mla_fd_test)
add_executable(ling32_sy_bench ${_tests_dir}/ling32_sy_bench.cpp) # decode-step kernel cost model at the real shapes (not a ctest entry)
target_link_libraries(ling32_sy_bench PRIVATE ling32_gpu)
if(Python3_FOUND)
set(_ids "5,17,100,42,7,300,12,9,33,2,64,201")
add_test(NAME ling32_make_ref COMMAND ${Python3_EXECUTABLE} -I ${_tests_dir}/ling32_pyref.py ref ${_fixture} --ids ${_ids} --out ${CMAKE_BINARY_DIR}/ref)
set_tests_properties(ling32_make_ref PROPERTIES FIXTURES_REQUIRED ling32_fixture FIXTURES_SETUP ling32_ref)
add_test(NAME ling32_forward_test_f32 COMMAND ling32_forward_test ${_fixture} ${CMAKE_BINARY_DIR}/ref ${_ids})
add_test(NAME ling32_forward_test_q8 COMMAND ling32_forward_test ${_fixture} ${CMAKE_BINARY_DIR}/ref ${_ids} --q8)
set_tests_properties(ling32_forward_test_f32 ling32_forward_test_q8 PROPERTIES FIXTURES_REQUIRED ling32_ref)
set(_wide "${CMAKE_BINARY_DIR}/ling32_wide.strata") # the real model's head geometry (KDA head dim 128, 512-wide latent) on 2 heads
add_test(NAME ling32_make_wide COMMAND ${Python3_EXECUTABLE} -I ${_tests_dir}/ling32_pyref.py make-fixture ${_wide} --wide)
add_test(NAME ling32_make_wide_ref COMMAND ${Python3_EXECUTABLE} -I ${_tests_dir}/ling32_pyref.py ref ${_wide} --ids ${_ids} --out ${CMAKE_BINARY_DIR}/ref_wide)
set_tests_properties(ling32_make_wide PROPERTIES FIXTURES_SETUP ling32_wide)
set_tests_properties(ling32_make_wide_ref PROPERTIES FIXTURES_REQUIRED ling32_wide FIXTURES_SETUP ling32_wide_ref)
add_test(NAME ling32_forward_test_wide COMMAND ling32_forward_test ${_wide} ${CMAKE_BINARY_DIR}/ref_wide ${_ids})
set_tests_properties(ling32_forward_test_wide PROPERTIES FIXTURES_REQUIRED ling32_wide_ref)
set_tests_properties(ling32_kernel_test ling32_model_test PROPERTIES FIXTURES_REQUIRED ling32_fixture)
# the MTP sidecar next to every memory tier, and greedy speculative == plain decode (spans)
set(_wide_mtp "${CMAKE_BINARY_DIR}/ling32_wide_mtp.strata")
add_test(NAME ling32_make_wide_mtp COMMAND ${Python3_EXECUTABLE} -I ${_tests_dir}/ling32_pyref.py make-mtp-fixture ${_wide_mtp} --wide)
set_tests_properties(ling32_make_wide_mtp PROPERTIES FIXTURES_REQUIRED ling32_wide FIXTURES_SETUP ling32_wide_mtp)
add_test(NAME ling32_mtp_tier_regress COMMAND ${Python3_EXECUTABLE} -I ${_tests_dir}/ling32_mtp_tier_test.py $<TARGET_FILE:strata-ling32> ${_wide} ${_wide_mtp} ${CMAKE_BINARY_DIR}/mtp_tier_work)
set_tests_properties(ling32_mtp_tier_regress PROPERTIES FIXTURES_REQUIRED ling32_wide_mtp TIMEOUT 600)
add_test(NAME ling32_spec_span_regress COMMAND ${Python3_EXECUTABLE} -I ${_tests_dir}/ling32_spec_span_test.py $<TARGET_FILE:strata-ling32> ${_wide} ${_wide_mtp} ${CMAKE_BINARY_DIR}/spec_span_work)
set_tests_properties(ling32_spec_span_regress PROPERTIES FIXTURES_REQUIRED ling32_wide_mtp TIMEOUT 600)
endif()
add_test(NAME ling32_spec_test COMMAND ling32_spec_test)
# L32-SY-TIER: the tier store driven without the engine's kernels (table slabs compared on the host and by a SYCL kernel); run by hand / sycl/tools/l32sy_tierbox.sh tiercheck
add_executable(ling32_sy_tier_check ${_tests_dir}/ling32_sy_tier_check.cpp)
target_link_libraries(ling32_sy_tier_check PRIVATE ling32_gpu)
set_source_files_properties(${_tests_dir}/ling32_mm_test.cu PROPERTIES LANGUAGE CXX)
add_executable(ling32_sy_topk_test ${_tests_dir}/ling32_sy_topk_test.cpp) # gpu::topk_rows against a host sort
target_link_libraries(ling32_sy_topk_test PRIVATE ling32_gpu)
add_test(NAME ling32_sy_topk_test COMMAND ling32_sy_topk_test)
add_executable(ling32_mm_test ${_tests_dir}/ling32_mm_test.cu) # picture input: M-RoPE in the MLA layers and the embedding override (needs the vision golden dir: run by hand)
target_link_libraries(ling32_mm_test PRIVATE ling32_gpu)
elseif(LING32_CUDA OR LING32_HIP)
set(_ling32_gpu_srcs ling32_kernels.cu ling32_layers.cu ling32_moe_tc.cu ling32_mla_exp_hip.cu ling32_model.cu ling32_spec.cu ling32_engine.cu ling32_tier_store.cu ling32_vision_gpu.cu ling32_mla_exp.cu ${engine_root}/src/kernels/cuda/mla_latent_attn.cu)
if(LING32_HIP)
set(CMAKE_HIP_STANDARD 17)
+13
View File
@@ -1250,6 +1250,19 @@ struct Ling32Engine::Impl {
bool Ling32Engine::init(GpuModel& model, const EngineOptions& o, std::string& err) {
destroy();
opt = o;
#if defined(STRATA_USE_SYCL)
{ // Intel GPU (SYCL / Level Zero): what the SYCL kernel layer (src/ling32/sycl/) does not have yet is switched off here, loudly where the user asked for it
auto off = [](bool& f, const char* what) { if (f) { std::fprintf(stderr, "ling32: %s is not available on SYCL yet, ignored\n", what); f = false; } };
off(opt.cuda_graph, "--graph");
off(opt.pdl, "--pdl");
off(opt.mla_expanded, "--mla-prefill expanded");
off(opt.fuse_experts, "--fuse-experts");
// --tc (the trunk GEMMs of prefill chunks, sycl/ling32_sy_k_moe_xmx.cpp trunk_xmx_try) and --tc-moe (grouped experts) stay: XMX tiles where the device has them, else the float kernels.
// STRATA_L32_TRUNK_XMX=0 keeps the scalar GEMV for the trunk (A/B).
if (opt.mla_kernel > 0 || opt.mla_prefill_kernel > 0) { std::fprintf(stderr, "ling32: --mla-kernel is not available on SYCL yet, using the original MLA kernel\n"); opt.mla_kernel = 0; opt.mla_prefill_kernel = 0; }
opt.fuse_router = false; // router_fused_ok() decides per shape; the unfused kernels first
}
#endif
#if defined(STRATA_USE_HIP)
{ // the tensor-core kernels are wave32 WMMA (RDNA3 / 3.5 / 4: gfx11xx, gfx12xx); other AMD targets keep the dp4a / float kernels
hipDeviceProp_t prop;
+4 -2
View File
@@ -25,7 +25,7 @@ namespace strata::ling32::gpu {
// ---- programmatic dependent launch (sm_90+): a kernel launched through launch_pdl may start while the previous kernel of the stream is still running; it must call dev::pdl_wait() before it reads
// anything the previous kernels wrote (weights may be prefetched before). Off (plain launches) unless the engine switches it on.
inline bool g_pdl_on = false;
#if !defined(STRATA_USE_HIP)
#if !defined(STRATA_USE_HIP) && !defined(STRATA_USE_SYCL)
template <typename... KA, typename... A>
inline void launch_pdl(void (*k)(KA...), dim3 g, dim3 b, size_t smem, cudaStream_t s, A... a) {
cudaLaunchConfig_t cfg{};
@@ -36,13 +36,15 @@ inline void launch_pdl(void (*k)(KA...), dim3 g, dim3 b, size_t smem, cudaStream
cfg.attrs = at; cfg.numAttrs = g_pdl_on ? 1 : 0;
cudaLaunchKernelEx(&cfg, k, static_cast<KA>(a)...);
}
#elif defined(STRATA_USE_SYCL)
// SYCL: no kernel pointers, no programmatic dependent launch (kernels are SYCL lambdas inside the launchers of src/ling32/sycl/)
#else
template <typename... KA, typename... A>
inline void launch_pdl(void (*k)(KA...), dim3 g, dim3 b, size_t smem, cudaStream_t s, A... a) { hipLaunchKernelGGL(k, g, b, smem, s, static_cast<KA>(a)...); }
#endif
inline int device_smem_optin() { // the largest dynamic shared memory a block may request on the current device (opt-in); 64 KiB where the query is not available
#if defined(STRATA_USE_HIP)
#if defined(STRATA_USE_HIP) || defined(STRATA_USE_SYCL)
return 64 * 1024;
#else
static std::atomic<int> cache[64];
+385
View File
@@ -28,6 +28,9 @@
#include <mutex>
#include <thread>
#include <vector>
#if defined(STRATA_USE_SYCL)
#include <unordered_map>
#endif
namespace strata::ling32 {
@@ -46,6 +49,217 @@ constexpr uint64_t kPiece = 32ull << 20; // start-up read size
}
} // namespace
#if defined(STRATA_USE_SYCL)
// Intel GPUs (Level Zero): one allocation is limited (4 GiB on Alchemist, for malloc_device AND malloc_host: measured on the A750) and the big blocks of this store (the hot prefix on the card, the warm prefix
// in pinned RAM) are many GiB. Under SYCL they are LISTS of allocations cut at slab ends; ChunkPtr keeps the `base + offset` spelling of the shared code: `host + rel` is the address of byte rel of the
// logical block. A slab never straddles two chunks (the cuts are slab ends); a long range (a piece read, the MTP block) is split by the caller (read pieces per chunk, ChunkPtr::write).
struct ChunkSet {
std::vector<uint64_t> start, size;
std::vector<uint8_t*> base;
uint64_t total = 0;
size_t find(uint64_t rel) const { // the chunk that holds byte rel (the last one for rel == total)
size_t i = 0;
while (i + 1 < base.size() && rel >= start[i] + size[i]) ++i;
return i;
}
};
struct ChunkPtr {
const ChunkSet* cs = nullptr;
explicit ChunkPtr(const ChunkSet* c = nullptr) : cs(c) {}
explicit operator bool() const { return cs && !cs->base.empty(); }
template <class T>
uint8_t* operator+(T rel_) const {
const uint64_t rel = static_cast<uint64_t>(rel_);
const size_t i = cs->find(rel);
return cs->base[i] + (rel - cs->start[i]);
}
void write(uint64_t rel, const uint8_t* src, uint64_t n) const { // memcpy into the logical block, split at the chunk borders
while (n) {
const size_t i = cs->find(rel);
const uint64_t room = cs->start[i] + cs->size[i] - rel, k = std::min(room, n);
std::memcpy(cs->base[i] + (rel - cs->start[i]), src, static_cast<size_t>(k));
rel += k; src += k; n -= k;
}
}
};
// O_DIRECT reads into Level Zero host memory (sycl::malloc_host / aligned_alloc_host) fail with EFAULT (measured on the A750: the driver maps these blocks in a way get_user_pages cannot pin; ordinary
// posix_memalign memory reads fine). A read whose destination is USM memory therefore lands in an ordinary 4 KiB-aligned bounce buffer first and is copied into the destination by the thread that collects the
// completion; any other destination is read directly. The API is DirectFile's (the store only uses open / close / submit / wait / wake).
struct SyDirectFile {
platform::DirectFile in;
struct Pend { uint64_t tag = 0; void* dst = nullptr; uint8_t* buf = nullptr; size_t cap = 0; };
struct Job { Pend p; uint32_t bytes = 0; bool ok = false; };
struct Done { uint64_t tag = 0; uint32_t bytes = 0; bool ok = false; };
std::mutex mu;
std::unordered_map<uint64_t, Pend> pend;
std::vector<std::pair<uint8_t*, size_t>> freel; // pooled bounce buffers (<= 16 MiB each)
uint64_t next_id = 1;
bool bounce_all = false; // STRATA_SY_DIO_DIRECT=1: try the direct read into USM memory (Windows NO_BUFFERING may accept it)
// The bounce -> destination copies run on a small pool of threads (STRATA_SY_COPY_THREADS, default 4; 0: on the thread that collects the completions, the old behaviour): a single thread
// copying 4 MiB per read caps the whole store at one core's memcpy rate (~4-8 GB/s, a third of what the drive reads) and delays everything else that thread does. A completion is handed to the
// caller only after its copy has finished; the finishing copy thread wakes the caller's wait.
std::mutex cmu;
std::condition_variable ccv;
std::deque<Job> jobs;
std::vector<Done> done;
std::vector<std::thread> pool;
bool cstop = false;
std::atomic<uint64_t> st_copies{0}, st_bytes{0}, st_ns{0}; // STRATA_SY_COPY_STATS=1: printed when the file is closed
bool stats = false;
SyDirectFile() {
const char* e = std::getenv("STRATA_SY_DIO_DIRECT");
bounce_all = !(e && e[0] == '1');
const char* t = std::getenv("STRATA_SY_COPY_THREADS");
const int nt = t ? std::atoi(t) : 4;
const char* s = std::getenv("STRATA_SY_COPY_STATS");
stats = s && s[0] == '1';
for (int i = 0; i < nt && i < 32; ++i) pool.emplace_back([this] { copy_main(); });
}
~SyDirectFile() { close(); }
bool open(const std::string& path, std::string& err) { return in.open(path, err); }
void close() {
{
std::lock_guard<std::mutex> g(cmu);
cstop = true;
}
ccv.notify_all();
for (auto& t : pool)
if (t.joinable()) t.join();
pool.clear();
if (stats && st_copies.load()) std::fprintf(stderr, "tier store: bounce copies %llu, %.2f GiB, %.3f s of copy time (summed over the copy threads)\n", static_cast<unsigned long long>(st_copies.load()),
static_cast<double>(st_bytes.load()) / 1073741824.0, static_cast<double>(st_ns.load()) * 1e-9);
st_copies = 0;
in.close();
std::lock_guard<std::mutex> g(mu);
for (auto& f : freel) platform::DirectFile::free_aligned(f.first);
freel.clear();
}
void wake() { in.wake(); }
uint8_t* acquire(size_t len, size_t& cap) {
{
std::lock_guard<std::mutex> g(mu);
size_t best = freel.size();
for (size_t i = 0; i < freel.size(); ++i)
if (freel[i].second >= len && freel[i].second <= 2 * len && (best == freel.size() || freel[i].second < freel[best].second)) best = i;
if (best < freel.size()) { uint8_t* p = freel[best].first; cap = freel[best].second; freel.erase(freel.begin() + static_cast<long>(best)); return p; }
}
cap = (len + 4095) / 4096 * 4096;
return static_cast<uint8_t*>(platform::DirectFile::alloc_aligned(cap));
}
void release(uint8_t* p, size_t cap) {
std::lock_guard<std::mutex> g(mu);
if (cap <= (16u << 20) && freel.size() < 64) freel.emplace_back(p, cap);
else platform::DirectFile::free_aligned(p);
}
void do_copy(const Job& j) {
if (j.ok && j.bytes) {
const auto t0 = std::chrono::steady_clock::now();
std::memcpy(j.p.dst, j.p.buf, j.bytes);
if (stats) {
st_ns += static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - t0).count());
st_bytes += j.bytes;
++st_copies;
}
}
release(j.p.buf, j.p.cap);
}
void copy_main() {
for (;;) {
Job j;
{
std::unique_lock<std::mutex> lk(cmu);
ccv.wait(lk, [this] { return cstop || !jobs.empty(); });
if (jobs.empty()) return; // stopping
j = std::move(jobs.front());
jobs.pop_front();
}
do_copy(j);
{
std::lock_guard<std::mutex> lk(cmu);
done.push_back(Done{j.p.tag, j.bytes, j.ok});
}
in.wake(); // the thread blocked in wait() collects it
}
}
bool submit(uint64_t offset, void* buffer, uint32_t length, uint64_t tag, std::string& err) {
const bool bounce = bounce_all && strata::sy::is_usm(buffer);
Pend p;
p.tag = tag;
p.dst = buffer;
if (bounce) {
p.buf = acquire(length, p.cap);
if (!p.buf) { err = "tier store: no memory for an O_DIRECT bounce buffer"; return false; }
}
uint64_t id;
{
std::lock_guard<std::mutex> g(mu);
id = next_id++;
pend.emplace(id, p);
}
if (!in.submit(offset, bounce ? static_cast<void*>(p.buf) : buffer, length, id, err)) {
std::lock_guard<std::mutex> g(mu);
pend.erase(id);
if (bounce) { platform::DirectFile::free_aligned(p.buf); }
return false;
}
return true;
}
int wait(platform::Completion* out, int max, int timeout_ms) {
// finished copies first (they never wait for the drive)
int m = 0;
{
std::lock_guard<std::mutex> g(cmu);
while (m < max && !done.empty()) {
out[m].tag = done.front().tag;
out[m].bytes = done.front().bytes;
out[m].ok = done.front().ok;
done.erase(done.begin());
++m;
}
}
if (m == max) return m;
// a copy that finishes between the check above and the blocking wait below wakes it (in.wake() queues a completion), so no timeout is lost
platform::Completion tmp[64];
const int room = max - m < 64 ? max - m : 64;
const int n = in.wait(tmp, room, m > 0 ? 0 : timeout_ms);
for (int i = 0; i < n; ++i) {
if (tmp[i].tag == platform::DirectFile::WAKE_TAG) {
out[m++] = tmp[i];
continue;
}
Pend p;
{
std::lock_guard<std::mutex> g(mu);
auto it = pend.find(tmp[i].tag);
if (it == pend.end()) continue;
p = it->second;
pend.erase(it);
}
if (!p.buf) { // read straight into its destination
out[m] = tmp[i];
out[m].tag = p.tag;
++m;
} else if (pool.empty()) { // STRATA_SY_COPY_THREADS=0: copy here
Job j{p, tmp[i].bytes, tmp[i].ok};
do_copy(j);
out[m] = tmp[i];
out[m].tag = p.tag;
++m;
} else {
{
std::lock_guard<std::mutex> g(cmu);
jobs.push_back(Job{p, tmp[i].bytes, tmp[i].ok});
}
ccv.notify_one();
}
}
return m;
}
};
#endif
struct ExpertStore::Impl {
const Ling32File& f;
const GpuModel& m;
@@ -60,8 +274,15 @@ struct ExpertStore::Impl {
bool mtp_in = false;
// memory
#if defined(STRATA_USE_SYCL)
ChunkSet vram_cs, host_cs; // the hot prefix on the card / the warm prefix in pinned RAM, each as a list of allocations (see ChunkPtr)
ChunkPtr vram{&vram_cs};
ChunkPtr host{&host_cs}; // warm prefix, pinned (or one ordinary-pages block when the system refused the pinned allocations)
bool host_fallback = false; // `host` is the single ordinary-pages block of host_region
#else
uint8_t* vram = nullptr;
uint8_t* host = nullptr; // warm prefix, pinned
#endif
bool host_registered = false; // Windows HIP: VirtualAlloc + cudaHostRegister instead of cudaHostAlloc
bool host_pageable = false; // cudaHostAlloc was refused: `host` is ordinary pages, its front host_pinned_bytes registered with cudaHostRegister (see host_region)
uint64_t host_pinned_bytes = 0;
@@ -71,18 +292,31 @@ struct ExpertStore::Impl {
static constexpr int kDynChunk = 64; // small dynamic slots are allocated in chunks of this many: the lazy latent KV gives whole tail chunks back (release_bytes)
std::vector<uint8_t*> dyn_chunks; // dyn[0, n_small): chunk c holds slots [c * kDynChunk, ...), nullptr once released
int dyn_dead = 0; // slots of released chunks (state 4: never picked, never filled)
#if defined(STRATA_USE_SYCL)
ChunkSet dynbig_cs; // the big size class as a list of allocations (the per-allocation limit of Alchemist cards)
ChunkPtr dynb_big{&dynbig_cs}; // the big size class (max_slab slots), after the small ones in the dyn[] index space
#else
uint8_t* dynb_big = nullptr; // the big size class (max_slab slots), after the small ones in the dyn[] index space
#endif
int n_small = 0; // dyn[0, n_small): slots of slot_small bytes; dyn[n_small, size): slots of slot_bytes (n_small == dyn.size(): one size)
uint64_t slot_small = 0;
uint8_t* ringb = nullptr; // pinned
uint8_t* ringb_dev = nullptr; // the device-visible address of the ring (equal to ringb where the host pointer is valid on the device; the in-place reads of kind 3 use it)
#if defined(STRATA_USE_SYCL)
ChunkPtr host_dev{&host_cs}; // pinned (malloc_host) memory has the same address on the device
#else
uint8_t* host_dev = nullptr; // the same for the warm prefix (a registered VirtualAlloc range on Windows: the device address may differ from the host one)
#endif
const uint8_t** d_tab = nullptr; // device table [n_gi]
std::vector<const uint8_t**> h_tab; // pinned, one [E] window per pass
int* h_ridx = nullptr; // pinned
cudaStream_t pf = nullptr;
uint64_t gpu_alloc = 0, pinned_alloc = 0;
#if defined(STRATA_USE_SYCL)
SyDirectFile df;
#else
platform::DirectFile df;
#endif
// state (mu)
std::mutex mu;
@@ -277,7 +511,17 @@ struct ExpertStore::Impl {
if (!df.open(f.path(), err)) return false;
if (!cu(cudaStreamCreateWithFlags(&pf, cudaStreamNonBlocking), "stream", err)) return false;
// memory
#if defined(STRATA_USE_SYCL)
if (vp) {
std::vector<uint64_t> vcuts; // slab ends inside the hot prefix
for (size_t g = 0; g < static_cast<size_t>(n_gi); ++g) if (ed[g].off + ed[g].body_bytes <= vp) vcuts.push_back(ed[g].off + ed[g].body_bytes);
std::sort(vcuts.begin(), vcuts.end());
vcuts.erase(std::unique(vcuts.begin(), vcuts.end()), vcuts.end());
if (!alloc_chunks(vram_cs, vp, vcuts, false, "the hot prefix on the card", err)) return false;
}
#else
if (vp && !cu(cudaMalloc(reinterpret_cast<void**>(&vram), vp), "cudaMalloc (hot prefix)", err)) return false;
#endif
gpu_alloc += vp;
if (plan.dyn_slots > 0) {
const int nbig = plan.dyn_big > 0 && plan.dyn_big < plan.dyn_slots && plan.slot_small > 0 ? plan.dyn_big : 0;
@@ -291,7 +535,13 @@ struct ExpertStore::Impl {
gpu_alloc += cb;
}
if (nbig) {
#if defined(STRATA_USE_SYCL)
std::vector<uint64_t> sc;
for (int k = 1; k <= nbig; ++k) sc.push_back(static_cast<uint64_t>(k) * slot_bytes);
if (!alloc_chunks(dynbig_cs, static_cast<uint64_t>(nbig) * slot_bytes, sc, false, "the big dynamic slots", err)) return false;
#else
if (!cu(cudaMalloc(reinterpret_cast<void**>(&dynb_big), static_cast<size_t>(nbig) * slot_bytes), "cudaMalloc (big dynamic slots)", err)) return false;
#endif
gpu_alloc += static_cast<uint64_t>(nbig) * slot_bytes;
}
dyn.assign(static_cast<size_t>(plan.dyn_slots), Dyn{});
@@ -351,6 +601,25 @@ struct ExpertStore::Impl {
}
if (!so.quiet) std::printf("tier store: warm prefix allocated and registered in %.2f s\n", now_s() - tw0);
}
#elif defined(STRATA_USE_SYCL)
if (rp) {
const std::vector<uint64_t> cuts = warm_cuts();
const bool force_fail = [] { const char* e = std::getenv("STRATA_L32_PIN_FAIL"); return e && e[0] == '1'; }(); // test hook, as in host_region
std::string perr;
if (force_fail || !alloc_chunks(host_cs, rp, cuts, true, "the warm prefix in RAM", perr)) {
// the system gives no (or not enough) pinned memory: one block of ordinary pages; copies from it are staged by the driver (slower, correct), nothing is read in place
for (uint8_t* b : host_cs.base) cudaFreeHost(b);
host_cs = ChunkSet{};
std::printf("tier store: pinned chunks for the warm prefix refused (%s); ordinary pages instead\n", force_fail ? "STRATA_L32_PIN_FAIL" : perr.c_str());
uint8_t* p = host_region(rp, "the warm prefix in RAM", &cuts, 0, host_pinned_bytes, host_pageable, err);
if (!p) return false;
host_cs.base.push_back(p);
host_cs.start.push_back(0);
host_cs.size.push_back(rp);
host_cs.total = rp;
host_fallback = true;
}
}
#else
if (rp) {
const std::vector<uint64_t> cuts = warm_cuts();
@@ -383,7 +652,11 @@ struct ExpertStore::Impl {
if (vp && !fill_vram(err)) return false;
if (!so.quiet) std::printf("tier store: hot prefix filled; reading the warm prefix (%.2f GiB)\n", rp_file / 1073741824.0);
if (rp_file && !fill_host(err)) return false;
#if defined(STRATA_USE_SYCL)
if (mtp_in) host.write(rp_file, m.mtp.h_sec4, mtp_host_bytes);
#else
if (mtp_in) std::memcpy(host + rp_file, m.mtp.h_sec4, static_cast<size_t>(mtp_host_bytes));
#endif
adapt_on = so.zero_copy && so.adaptive_default && rp > 0; // default: on where the RAM tier is read in place (the Windows iGPU); STRATA_L32_ADAPT=0 / 1 overrides
if (const char* e = std::getenv("STRATA_L32_ADAPT")) adapt_on = e[0] == '1' && rp > 0;
if (const char* e = std::getenv("STRATA_L32_AD_DECAY")) ad_decay = std::max(0.5, std::min(0.9999, std::atof(e)));
@@ -488,6 +761,70 @@ struct ExpertStore::Impl {
size_t finished = 0;
};
#if defined(STRATA_USE_SYCL)
// `bytes` as a list of allocations (device memory, or pinned host memory), each cut at one of `cuts` (sorted slab ends; host chunks also at a multiple of 4096, the O_DIRECT / NO_BUFFERING alignment of the
// reads that fill them). The first chunk size is the device's per-allocation limit (minus a margin) or STRATA_SY_CHUNK_MIB; a refused allocation halves the target down to 64 MiB. On failure every chunk
// allocated so far is freed and `cs` is empty.
bool alloc_chunks(ChunkSet& cs, uint64_t bytes, const std::vector<uint64_t>& cuts, bool pinned_host, const char* what, std::string& err) {
constexpr uint64_t MiB = 1ull << 20, kMin = 64 * MiB;
uint64_t target = bytes;
if (const char* e = std::getenv("STRATA_SY_CHUNK_MIB")) target = std::max<uint64_t>(kMin, static_cast<uint64_t>(std::atoll(e)) * MiB);
else {
const uint64_t mx = strata::sy::dev_state().dev.get_info<sycl::info::device::max_mem_alloc_size>();
if (mx > 256 * MiB) target = std::min(target, mx - 128 * MiB);
}
cs = ChunkSet{};
uint64_t pos = 0;
std::string why;
while (pos < bytes) {
const uint64_t want = std::min(target, bytes - pos);
uint64_t end = pos + want;
if (end < bytes) { // the largest allowed cut at or below pos + want
auto it = std::upper_bound(cuts.begin(), cuts.end(), end);
end = 0;
while (it != cuts.begin()) {
--it;
if (*it <= pos) break;
if (!pinned_host || *it % 4096 == 0) { end = *it; break; }
}
if (end <= pos) { why = "no slab boundary inside a chunk of " + std::to_string(want / MiB) + " MiB"; break; }
}
void* p = nullptr;
const cudaError_t e = pinned_host ? cudaHostAlloc(&p, static_cast<size_t>(end - pos), cudaHostAllocPortable) : cudaMalloc(&p, static_cast<size_t>(end - pos));
if (e != cudaSuccess || !p) {
(void)cudaGetLastError();
if (target <= kMin) { why = std::string(cudaGetErrorString(e)) + " at chunk " + std::to_string(cs.base.size()) + " (" + std::to_string((end - pos) / MiB) + " MiB)"; break; }
target = std::max(kMin, target / 2);
continue;
}
cs.base.push_back(static_cast<uint8_t*>(p));
cs.start.push_back(pos);
cs.size.push_back(end - pos);
pos = end;
}
if (pos < bytes) {
for (uint8_t* b : cs.base) { if (pinned_host) cudaFreeHost(b); else cudaFree(b); }
cs = ChunkSet{};
err = std::string("tier store: ") + what + " (" + std::to_string(bytes / MiB) + " MiB): " + why;
return false;
}
cs.total = bytes;
if (!so.quiet && cs.base.size() > 1) std::printf("tier store: %s: %zu allocations (%.2f GiB, largest %.2f GiB; per-allocation limit)\n", what, cs.base.size(), bytes / 1073741824.0, *std::max_element(cs.size.begin(), cs.size.end()) / 1073741824.0);
return true;
}
// H2D copy of [off, off + len) of the hot prefix, split at the chunk borders
cudaError_t copy_to_vram(uint64_t off, const uint8_t* src, uint64_t len, cudaStream_t s) {
while (len) {
const size_t i = vram_cs.find(off);
const uint64_t k = std::min(len, vram_cs.start[i] + vram_cs.size[i] - off);
const cudaError_t e = cudaMemcpyAsync(vram_cs.base[i] + (off - vram_cs.start[i]), src, static_cast<size_t>(k), cudaMemcpyHostToDevice, s);
if (e != cudaSuccess) return e;
off += k; src += k; len -= k;
}
return cudaSuccess;
}
#endif
bool fill_vram(std::string& err) {
const uint64_t P = (vp + kPiece - 1) / kPiece;
const int nbuf = 4;
@@ -508,7 +845,11 @@ struct ExpertStore::Impl {
const uint64_t len = std::min<uint64_t>(kPiece, vp - p * kPiece);
if (!cs[i].ok || cs[i].bytes != len) { err = "tier store: a read of the hot prefix failed"; return false; }
const int b = static_cast<int>(p % nbuf);
#if defined(STRATA_USE_SYCL)
if (!cu(copy_to_vram(p * kPiece, buf[b], len, ls), "H2D (hot prefix)", err)) return false;
#else
if (!cu(cudaMemcpyAsync(vram + p * kPiece, buf[b], len, cudaMemcpyHostToDevice, ls), "H2D (hot prefix)", err)) return false;
#endif
cudaEventRecord(ev[b], ls);
done[p] = 1;
++finished;
@@ -532,6 +873,39 @@ struct ExpertStore::Impl {
return ok;
}
#if defined(STRATA_USE_SYCL)
bool fill_host(std::string& err) { // the same pump over reads that never cross a chunk border (every chunk starts on a 4096 multiple)
struct Pc { uint64_t rel, len; };
std::vector<Pc> pcs;
for (size_t c = 0; c < host_cs.base.size(); ++c) {
const uint64_t c0 = host_cs.start[c], c1 = std::min(c0 + host_cs.size[c], rp_file);
for (uint64_t r = c0; r < c1; r += kPiece) pcs.push_back({r, std::min<uint64_t>(kPiece, c1 - r)});
}
const uint64_t P = pcs.size();
std::vector<char> done(P, 0);
uint64_t finished = 0, next = 0;
const uint64_t qd = 32;
platform::Completion cs[32];
double last_progress = now_s();
while (finished < P) {
while (next < P && next - finished < qd) {
if (!df.submit(sec4_off + vp + pcs[next].rel, host + pcs[next].rel, static_cast<uint32_t>(pcs[next].len), next, err)) return false;
++next;
}
const int n = df.wait(cs, 32, 1000);
for (int i = 0; i < n; ++i) {
if (cs[i].tag == platform::DirectFile::WAKE_TAG) continue;
const uint64_t p = cs[i].tag;
if (!cs[i].ok || cs[i].bytes != pcs[p].len) { err = "tier store: a read of the warm prefix failed"; return false; }
++finished;
last_progress = now_s();
if (!so.quiet && finished % 128 == 0) std::printf("tier store: warm prefix read %.1f of %.1f GiB\n", finished * double(kPiece) / 1073741824.0, rp / 1073741824.0);
}
if (now_s() - last_progress > 300) { err = "tier store: the warm-prefix read stalled"; return false; }
}
return true;
}
#else
bool fill_host(std::string& err) {
const uint64_t P = (rp_file + kPiece - 1) / kPiece;
std::vector<char> done(P, 0);
@@ -558,6 +932,7 @@ struct ExpertStore::Impl {
}
return true;
}
#endif
// a few slabs of the card / RAM tiers against the file
bool verify(std::string& err) {
@@ -679,15 +1054,25 @@ struct ExpertStore::Impl {
if (cpu_stub) cudaFree(cpu_stub);
for (float* p : {h_ah, xT_ah, h_gu, h_actp, xT_act, h_ye}) if (p) cudaFreeHost(p);
if (cpu_stream) cudaStreamDestroy(cpu_stream);
#if defined(STRATA_USE_SYCL)
for (uint8_t* b : vram_cs.base) cudaFree(b);
#else
if (vram) cudaFree(vram);
#endif
for (uint8_t* cp : dyn_chunks) if (cp) cudaFree(cp);
#if defined(STRATA_USE_SYCL)
for (uint8_t* b : dynbig_cs.base) cudaFree(b);
#else
if (dynb_big) cudaFree(dynb_big);
#endif
if (d_tab) cudaFree(d_tab);
#if defined(STRATA_USE_HIP) && defined(_WIN32)
if (host) {
cudaHostUnregister(host);
VirtualFree(host, 0, MEM_RELEASE);
}
#elif defined(STRATA_USE_SYCL)
for (uint8_t* b : host_cs.base) { if (host_fallback) free_host_region(b, host_pageable, host_pinned_bytes); else cudaFreeHost(b); }
#else
free_host_region(host, host_pageable, host_pinned_bytes);
#endif
+223
View File
@@ -0,0 +1,223 @@
// src/ling32/sycl/ling32_sy.hpp - how a Ling-3.2-Air kernel is written for SYCL (Intel Arc / Battlemage), and the shared device primitives.
//
// The CUDA kernels of ling32_kernels.cu / ling32_layers.cu / ling32_moe_tc.cu / ling32_spec.cu are written for a 32-thread warp. The SYCL versions keep that structure so the
// arithmetic (and so the results) stay the same: a "warp" is a sub-group of 32 (reqd_sub_group_size(32), supported by Alchemist and Battlemage), a "block" is a work-group, the
// dynamic shared memory of a launch is one local accessor. A kernel is a lambda; this header gives it CUDA-like names.
//
// __global__ void k(args) { ... threadIdx.x ... blockIdx.x ... __shared__ ... __syncthreads() ... __shfl_xor_sync(m, v, x) ... }
// becomes
// sy::launch(stream, grid, block, smem_bytes, [=](sy::Blk b, char* smem) { ... b.tid() ... b.bid() ... carve smem ... b.sync() ... b.shfl_xor(v, x) ... });
//
// Rules for kernel authors (every owner of a sycl/ling32_sy_k_*.cpp file):
// * NO double precision anywhere in a kernel (Alchemist has no fp64 units; the engine's double RoPE angles are computed on the host into a float table or in float pairs, see the launcher).
// * no 8-wide sub-groups (IGC ICE on bmg_g31); only 32 (default here) or 16.
// * same summation order as the CUDA kernel unless you also change the CPU reference: the fixture golden tests compare bit-for-bit where the CUDA kernels do.
// * `launch` takes the cudaStream_t that the launcher received (strata::sy::queue_of); never wait() inside a launcher, the engine synchronises.
// * every launcher has the signature of its declaration in ling32_kernels.hpp / ling32_spec.hpp; delete its stub from ling32_sy_todo.cpp when you add the definition.
#pragma once
#include "../ling32_kernels.hpp"
#include <sycl/sycl.hpp>
#include <cstdint>
namespace strata::ling32::gpu::sy {
constexpr int kSg = 32; // warp width
#define L32_SG32 [[sycl::reqd_sub_group_size(32)]]
// CUDA-like view of the work-item inside a launch
struct Blk {
sycl::nd_item<1> it;
int tid() const { return static_cast<int>(it.get_local_id(0)); } // threadIdx.x
int bid() const { return static_cast<int>(it.get_group(0)); } // blockIdx.x (flat; a 2-D grid is decoded by the kernel: bx = bid % gx, by = bid / gx)
int bdim() const { return static_cast<int>(it.get_local_range(0)); } // blockDim.x
int nblk() const { return static_cast<int>(it.get_group_range(0)); } // gridDim.x
int lane() const { return static_cast<int>(it.get_sub_group().get_local_linear_id()); }
int warp() const { return tid() / kSg; }
void sync() const { sycl::group_barrier(it.get_group()); } // __syncthreads()
void warp_sync() const { sycl::group_barrier(it.get_sub_group()); } // __syncwarp()
// warp shuffles (all 32 lanes participate, as with the full 0xFFFFFFFF mask)
template <class T> T shfl_xor(T v, int m) const { return sycl::permute_group_by_xor(it.get_sub_group(), v, static_cast<unsigned>(m)); }
template <class T> T shfl(T v, int src) const { return sycl::select_from_group(it.get_sub_group(), v, static_cast<unsigned>(src)); }
template <class T> T shfl_down(T v, int d) const { return sycl::shift_group_left(it.get_sub_group(), v, static_cast<unsigned>(d)); }
template <class T> T shfl_up(T v, int d) const { return sycl::shift_group_right(it.get_sub_group(), v, static_cast<unsigned>(d)); }
// __reduce_*: lane-order independent only for max/min; for sums use a shfl_xor butterfly to keep the CUDA order
float warp_max(float v) const { return sycl::reduce_over_group(it.get_sub_group(), v, sycl::maximum<float>()); }
unsigned ballot(bool p) const {
auto sg = it.get_sub_group();
return static_cast<unsigned>(sycl::reduce_over_group(sg, p ? (1u << sg.get_local_linear_id()) : 0u, sycl::bit_or<unsigned>()));
}
};
// Launches `f(Blk, char* smem)` on `grid` blocks of `block` threads (block % 32 == 0) with `smem` bytes of shared memory (dynamic, 16-byte aligned by the accessor).
template <class F>
inline void launch(cudaStream_t s, int grid, int block, size_t smem, F f) {
auto& q = strata::sy::queue_of(s);
q.submit([&](sycl::handler& h) {
sycl::local_accessor<char, 1> lm(sycl::range<1>(smem ? smem : 1), h);
h.parallel_for(sycl::nd_range<1>(static_cast<size_t>(grid) * block, static_cast<size_t>(block)), [=](sycl::nd_item<1> it) L32_SG32 {
f(Blk{it}, lm.get_multi_ptr<sycl::access::decorated::no>().get());
});
});
}
// ---------------------------------------------------------------------------------------------------- shared device primitives (ports of ling32_dev.cuh; helper owners extend, never fork)
constexpr float kNorm128 = 0.08838834764831845f;
// superblock bytes of a code id (2 and 3: the 2- and 3-bit codes of the MTP sidecar's experts)
constexpr int sk_sb_bytes(int code) { return code == 2 ? 70 : code == 3 ? 102 : code == 4 ? 134 : code == 5 ? 166 : code == 6 ? 198 : 262; }
template <int CODE> struct Sk {
static constexpr int kBytes = sk_sb_bytes(CODE);
static constexpr float kHalf = CODE == 2 ? 1.5f : CODE == 3 ? 3.5f : CODE == 4 ? 7.5f : CODE == 5 ? 15.5f : CODE == 6 ? 31.5f : 0.0f;
};
// u / 255.0f for u = 0..255 evaluated by the host compiler at compile time (exactly rounded): the device compiler does not guarantee a correctly rounded divide, and the S_K group scales
// are bit-exact against the CPU decode (sk_codecs.cpp: D * (u / 255.0f))
struct Div255Table {
float v[256];
constexpr Div255Table() : v() { for (int i = 0; i < 256; ++i) v[i] = static_cast<float>(i) / 255.0f; }
};
inline constexpr Div255Table kDiv255{};
// int8x4 dot product with accumulate (CUDA __dp4a)
inline int dp4a(int a, int b, int c) {
const int8_t a0 = static_cast<int8_t>(a), a1 = static_cast<int8_t>(a >> 8), a2 = static_cast<int8_t>(a >> 16), a3 = static_cast<int8_t>(a >> 24);
const int8_t b0 = static_cast<int8_t>(b), b1 = static_cast<int8_t>(b >> 8), b2 = static_cast<int8_t>(b >> 16), b3 = static_cast<int8_t>(b >> 24);
return c + a0 * b0 + a1 * b1 + a2 * b2 + a3 * b3; // the compiler maps this to DP4A on Xe
}
// fp16 <-> fp32 on the device (round to nearest even), bit patterns in and out
inline float h2f(uint16_t h) { return static_cast<float>(sycl::bit_cast<sycl::half>(h)); }
inline uint16_t f2h(float f) { return sycl::bit_cast<uint16_t>(static_cast<sycl::half>(f)); }
// 8 consecutive weights idx0..idx0+7 (idx0 % 8 == 0) of a superblock payload as two words of 4 q bytes (q unsigned for S4/5/6, int8 for S8) - ling32_dev.cuh load_w8
template <int CODE>
inline void load_w8(const uint8_t* pl, int idx0, uint32_t w[2]) {
if (CODE == 8) {
// the payload starts 6 bytes into a superblock of an even size: 2-byte aligned, so four 16-bit loads instead of eight byte loads (same little-endian words)
const uint16_t* p = reinterpret_cast<const uint16_t*>(pl + idx0);
w[0] = static_cast<uint32_t>(p[0]) | (static_cast<uint32_t>(p[1]) << 16);
w[1] = static_cast<uint32_t>(p[2]) | (static_cast<uint32_t>(p[3]) << 16);
return;
}
if (CODE == 2 || CODE == 3) {
const int nb2 = idx0 >> 2;
const uint32_t c0 = pl[nb2], c1 = pl[nb2 + 1];
uint32_t a = (c0 & 3u) | (((c0 >> 2) & 3u) << 8) | (((c0 >> 4) & 3u) << 16) | (((c0 >> 6) & 3u) << 24);
uint32_t b = (c1 & 3u) | (((c1 >> 2) & 3u) << 8) | (((c1 >> 4) & 3u) << 16) | (((c1 >> 6) & 3u) << 24);
if (CODE == 3) {
const uint32_t hb = pl[64 + (idx0 >> 3)];
a |= ((hb & 1u) << 2) | (((hb >> 1) & 1u) << 10) | (((hb >> 2) & 1u) << 18) | (((hb >> 3) & 1u) << 26);
b |= (((hb >> 4) & 1u) << 2) | (((hb >> 5) & 1u) << 10) | (((hb >> 6) & 1u) << 18) | (((hb >> 7) & 1u) << 26);
}
w[0] = a;
w[1] = b;
return;
}
const int nb = idx0 >> 1;
const uint16_t* pn = reinterpret_cast<const uint16_t*>(pl + nb);
const uint32_t n01 = pn[0], n23 = pn[1];
const uint32_t b0 = n01 & 0xFFu, b1 = n01 >> 8, b2 = n23 & 0xFFu, b3 = n23 >> 8;
uint32_t a = (b0 & 0xFu) | ((b0 >> 4) << 8) | ((b1 & 0xFu) << 16) | ((b1 >> 4) << 24);
uint32_t b = (b2 & 0xFu) | ((b2 >> 4) << 8) | ((b3 & 0xFu) << 16) | ((b3 >> 4) << 24);
if (CODE == 5) {
const uint32_t hb = pl[128 + (idx0 >> 3)];
a |= ((hb & 1u) << 4) | (((hb >> 1) & 1u) << 12) | (((hb >> 2) & 1u) << 20) | (((hb >> 3) & 1u) << 28);
b |= (((hb >> 4) & 1u) << 4) | (((hb >> 5) & 1u) << 12) | (((hb >> 6) & 1u) << 20) | (((hb >> 7) & 1u) << 28);
} else if (CODE == 6) {
const uint32_t h0 = pl[128 + (idx0 >> 2)], h1 = pl[128 + (idx0 >> 2) + 1];
a |= ((h0 & 3u) << 4) | (((h0 >> 2) & 3u) << 12) | (((h0 >> 4) & 3u) << 20) | (((h0 >> 6) & 3u) << 28);
b |= ((h1 & 3u) << 4) | (((h1 >> 2) & 3u) << 12) | (((h1 >> 4) & 3u) << 20) | (((h1 >> 6) & 3u) << 28);
}
w[0] = a;
w[1] = b;
}
// FWHT-128 of one 128-element block held 4 per lane (lane l: elements 4l..4l+3): ling32_dev.cuh fwht128_warp, same order of operations
inline void fwht128_warp(const Blk& b, float v[4]) {
const float a0 = v[0] + v[1], a1 = v[0] - v[1], a2 = v[2] + v[3], a3 = v[2] - v[3];
v[0] = a0 + a2;
v[1] = a1 + a3;
v[2] = a0 - a2;
v[3] = a1 - a3;
const int lane = b.lane();
for (int mask = 1; mask <= 16; mask <<= 1) {
const bool upper = (lane & mask) != 0;
for (int i = 0; i < 4; ++i) {
const float p = b.shfl_xor(v[i], mask);
v[i] = upper ? (p - v[i]) : (v[i] + p);
}
}
for (int i = 0; i < 4; ++i) v[i] *= kNorm128;
}
// Q8_1 of one 128-wide block held 4 values per lane: writes the two 64-blocks dst2[0], dst2[1] (ling32_dev.cuh q8_store_warp)
inline void q8_store_warp(const Blk& b, const float v[4], Q8Blk* dst2) {
const int lane = b.lane();
float amax = sycl::fmax(sycl::fmax(sycl::fabs(v[0]), sycl::fabs(v[1])), sycl::fmax(sycl::fabs(v[2]), sycl::fabs(v[3])));
for (int off = 8; off >= 1; off >>= 1) amax = sycl::fmax(amax, b.shfl_xor(amax, off));
const float d = amax / 127.0f;
const float inv = (d > 0.0f) ? (1.0f / d) : 0.0f;
int q[4], qsum = 0;
for (int i = 0; i < 4; ++i) {
const float r = sycl::rint(v[i] * inv); // round to nearest even == __float2int_rn
q[i] = sycl::max(-127, sycl::min(127, static_cast<int>(r)));
qsum += q[i];
}
for (int off = 8; off >= 1; off >>= 1) qsum += b.shfl_xor(qsum, off);
Q8Blk& dst = dst2[lane >> 4];
const uint32_t packed = (static_cast<uint32_t>(q[0]) & 0xFFu) | ((static_cast<uint32_t>(q[1]) & 0xFFu) << 8) | ((static_cast<uint32_t>(q[2]) & 0xFFu) << 16) | ((static_cast<uint32_t>(q[3]) & 0xFFu) << 24);
*reinterpret_cast<uint32_t*>(dst.qs + (lane & 15) * 4) = packed;
if ((lane & 15) == 0) {
dst.d = d;
dst.s = d * static_cast<float>(qsum);
}
}
// A warp computes NT token dot products of one weight row (ling32_dev.cuh row_dot). Lane = (group g of 64 weights, 8 weights): a superblock per step. Q8: act = Q8Blk [N][K/64], else float [N][K].
template <int CODE, int NT, bool Q8>
inline void row_dot(const uint8_t* rowp, int nsb, const void* act, int K, int N, int t0, int lane, float acc[NT]) {
const int g = lane >> 3, in_g = (lane & 7) * 8, idx0 = g * 64 + in_g;
const Q8Blk* aq = static_cast<const Q8Blk*>(act);
const float* af = static_cast<const float*>(act);
for (int sb = 0; sb < nsb; ++sb) {
const uint8_t* blk = rowp + static_cast<size_t>(sb) * Sk<CODE>::kBytes;
const float D = h2f(static_cast<uint16_t>(blk[0] | (blk[1] << 8)));
const float eff = D * kDiv255.v[blk[2 + g]];
uint32_t w[2];
load_w8<CODE>(blk + 6, idx0, w);
for (int t = 0; t < NT; ++t) {
if (t0 + t >= N) break;
if (Q8) {
const Q8Blk& xb = aq[static_cast<size_t>(t0 + t) * (K >> 6) + sb * 4 + g];
int x0, x1;
std::memcpy(&x0, xb.qs + in_g, 4);
std::memcpy(&x1, xb.qs + in_g + 4, 4);
int isum = dp4a(static_cast<int>(w[0]), x0, 0);
isum = dp4a(static_cast<int>(w[1]), x1, isum);
if (CODE == 8) acc[t] += eff * xb.d * static_cast<float>(isum);
else acc[t] += eff * (xb.d * static_cast<float>(isum) - Sk<CODE>::kHalf * xb.s * 0.125f);
} else {
const float* xp = af + static_cast<size_t>(t0 + t) * K + sb * 256 + idx0;
float s = 0.0f;
for (int j = 0; j < 8; ++j) {
const uint32_t word = w[j >> 2];
const uint32_t byte = (word >> (8 * (j & 3))) & 0xFFu;
const float q = (CODE == 8) ? static_cast<float>(static_cast<int8_t>(byte)) : static_cast<float>(byte) - Sk<CODE>::kHalf;
s += q * xp[j];
}
acc[t] += eff * s;
}
}
}
}
// sum over the 32 lanes in the butterfly order of the CUDA kernels (xor 16, 8, 4, 2, 1)
inline float warp_sum_xor(const Blk& b, float v) {
for (int off = 16; off >= 1; off >>= 1) v += b.shfl_xor(v, off);
return v;
}
} // namespace strata::ling32::gpu::sy
+93
View File
@@ -0,0 +1,93 @@
// src/ling32/sycl/ling32_sy_core.cpp - globals of the kernel layer and the host-side methods of SpecState (ling32_spec.cu holds kernels and host code in one file; the SYCL build takes only the host half).
#include "ling32_sy.hpp"
#include "../ling32_spec.hpp"
#include "../ling32_vision_gpu.hpp"
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <string>
namespace strata::ling32::gpu {
int g_w2_nt = 0; // AMD WMMA tile knobs: no meaning on SYCL, kept so that shared code links
int g_w2_etn = 0;
int g_tc_min_n = 0;
int g_tc_mode = 0;
int g_kda_chunk_force = 0;
int g_alflb_ref = 0;
} // namespace strata::ling32::gpu
namespace strata::ling32 {
namespace {
constexpr int kMaxB = 16;
bool cu(cudaError_t e, const char* what, std::string& err) {
if (e == cudaSuccess) return true;
err = std::string(what) + " failed: " + cudaGetErrorString(e);
cudaGetLastError();
return false;
}
} // namespace
bool SpecState::init(const GpuModel&, const SpecParams& p, cudaStream_t st, std::string& err) {
destroy();
st_ = st;
params = p;
B_ = std::max(1, std::min(p.block, kMaxB));
params.block = B_;
if (p.temp > 0.0f && (p.top_k < 1 || p.top_k > 64)) { err = "MTP sampling needs 1 <= top_k <= 64"; return false; }
bool ok = cu(cudaMalloc(reinterpret_cast<void**>(&d_st_), sizeof(SpecDevState)), "cudaMalloc", err) && cu(cudaMalloc(reinterpret_cast<void**>(&d_cfg_), sizeof(SpecCfgDev)), "cudaMalloc", err) &&
cu(cudaMalloc(reinterpret_cast<void**>(&q_tok_), size_t(B_) * 64 * sizeof(int)), "cudaMalloc", err) && cu(cudaMalloc(reinterpret_cast<void**>(&q_p_), size_t(B_) * 64 * sizeof(float)), "cudaMalloc", err) &&
cu(cudaMalloc(reinterpret_cast<void**>(&q_n_), size_t(B_) * sizeof(int)), "cudaMalloc", err);
if (!ok) return false;
SpecCfgDev hc{};
hc.temp = p.temp; hc.top_p = p.top_p; hc.top_k = p.top_k; hc.block = B_; hc.seed = p.seed;
SpecDevState hs;
std::memset(&hs, 0, sizeof hs);
if (!cu(cudaMemcpy(d_cfg_, &hc, sizeof hc, cudaMemcpyHostToDevice), "cudaMemcpy", err) || !cu(cudaMemcpy(d_st_, &hs, sizeof hs, cudaMemcpyHostToDevice), "cudaMemcpy", err)) return false;
cudaMemset(q_n_, 0, size_t(B_) * sizeof(int));
cudaMemset(q_p_, 0, size_t(B_) * 64 * sizeof(float));
cudaMemset(q_tok_, 0, size_t(B_) * 64 * sizeof(int));
return true;
}
void SpecState::destroy() {
auto f2 = [](auto*& p) { if (p) { cudaFree(p); p = nullptr; } };
f2(d_st_); f2(d_cfg_); f2(q_tok_); f2(q_p_); f2(q_n_);
}
void SpecState::reset() {
SpecDevState* st = d_st_;
strata::sy::queue_of(st_).single_task([=] { st->nacc = 0; st->hrow = 0; st->grow = 0; st->dnext = 0; });
}
void SpecState::set_sampling(float temp, float top_p, int top_k, uint64_t seed) {
params.temp = temp;
params.top_p = top_p;
params.top_k = top_k;
params.seed = seed;
SpecCfgDev hc{};
hc.temp = temp; hc.top_p = top_p; hc.top_k = top_k; hc.block = params.block; hc.seed = seed;
cudaMemcpy(d_cfg_, &hc, sizeof hc, cudaMemcpyHostToDevice); // blocking: nothing of the previous cycle is in flight when a request starts
const unsigned long long zero = 0;
cudaMemcpy(&d_st_->ctr, &zero, sizeof zero, cudaMemcpyHostToDevice); // the Philox stream of a request restarts
}
void SpecState::set_nacc(int nacc, int hrow, int grow) {
SpecDevState* st = d_st_;
strata::sy::queue_of(st_).single_task([=] { st->nacc = nacc; st->hrow = hrow; st->grow = grow; });
}
} // namespace strata::ling32
// ---- picture encoder on the GPU: not ported (the CPU encoder serves pictures; vision_gpu_total_bytes = 0 makes the backend choice pick it)
namespace strata::ling32 {
struct VisionGpu::Dev {};
VisionGpu::VisionGpu(const std::string& vision_file, int device, double idle_seconds) : file_(vision_file), device_(device), idle_(idle_seconds) {}
VisionGpu::~VisionGpu() {}
bool VisionGpu::encode(const PreparedImage&, std::vector<float>&, std::string& err, VisionCheckpoints*, VisionGpuStats*) {
err = "the picture encoder on the GPU is not available in the SYCL build (use the CPU encoder)";
return false;
}
void VisionGpu::unload() {}
bool VisionGpu::loaded() const { return false; }
uint64_t VisionGpu::device_bytes() const { return 0; }
void VisionGpu::set_idle_seconds(double s) { idle_ = s; }
uint64_t vision_gpu_total_bytes(int) { return 0; }
} // namespace strata::ling32
+423
View File
@@ -0,0 +1,423 @@
// src/ling32/sycl/ling32_sy_k_kda.cpp - KDA (kimi delta attention) on SYCL: causal conv + SiLU + L2 norm, the delta-rule recurrence with a per-channel decay vector, the conv-history update.
// Port of kda_prep_kernel / kda_hist_kernel / kda_step_fused_kernel / kda_step_kernel of ling32_layers.cu, same arithmetic and order.
// Decode / verify batches use the sequential recurrence; prefill batches (N > 1, no snapshot) the chunk-parallel float32 form with chunks of 8 tokens (two kernels).
// TODO(perf): the state column s[HD] lives in registers (CUDA: 128 floats per thread); with a 32-wide sub-group that needs 256 GRFs, so it spills on Xe: keep the state in SLM (HD x HD floats = 64 KiB
// per head) or split a column over two lanes, and port the chunk-parallel form (kda_chunk_pre / kda_chunk_seq) for prefill.
#include "ling32_sy.hpp"
#include <cstdio>
#include <cstdlib>
namespace strata::ling32::gpu {
namespace {
inline float sigmoidf(float x) { return 1.0f / (1.0f + sycl::exp(-x)); }
inline float siluf(float x) { return x / (1.0f + sycl::exp(-x)); }
// sm: >= 33 floats. Every thread of the block must call; all get the sum (ling32_layers.cu block_sum)
inline float block_sum(const sy::Blk& b, float v, float* sm) {
const int lane = b.lane(), w = b.warp(), nw = (b.bdim() + 31) >> 5;
v = sy::warp_sum_xor(b, v);
b.sync();
if (lane == 0) sm[w] = v;
b.sync();
if (w == 0) {
float r = lane < nw ? sm[lane] : 0.0f;
r = sy::warp_sum_xor(b, r);
if (lane == 0) sm[32] = r;
}
b.sync();
return sm[32];
}
template <int HD>
void launch_prep(const float* proj, int ps, const float* qw, const float* kw, const float* vw, const float* hist, float* qn, float* kn, float* vc, int N, int H, cudaStream_t s) {
sy::launch(s, N * H, HD, 40 * sizeof(float), [=](sy::Blk b, char* smem) {
float* sm = reinterpret_cast<float*>(smem);
const int t = b.bid() % N, h = b.bid() / N, C = H * HD, c = h * HD + b.tid();
float y[3];
for (int which = 0; which < 3; ++which) {
const float* w = (which == 0 ? qw : which == 1 ? kw : vw) + static_cast<size_t>(c) * 4;
float acc = 0.0f;
for (int j = 0; j < 4; ++j) {
const int idx = t - 3 + j;
const float x = idx >= 0 ? proj[static_cast<size_t>(idx) * ps + which * C + c] : hist[(static_cast<size_t>(which) * C + c) * 3 + (3 + idx)];
acc += w[j] * x;
}
y[which] = siluf(acc);
}
const float qs = block_sum(b, y[0] * y[0], sm), ks = block_sum(b, y[1] * y[1], sm);
const size_t o = static_cast<size_t>(t) * C + c;
qn[o] = y[0] * (1.0f / sycl::sqrt(qs + 1e-6f)) * sycl::rsqrt(static_cast<float>(HD));
kn[o] = y[1] * (1.0f / sycl::sqrt(ks + 1e-6f));
vc[o] = y[2];
});
}
template <int HD>
void launch_step_fused(float* S, const float* proj, int ps, const float* qw, const float* kw, const float* vw, float* hist, const float* beta_raw, const float* A_log, const float* dt_bias,
const float* o_norm, float lower_bound, float eps, float* out, int N, int H, float* snap, float* ext, int ext_len, const float* bw, const float* hv, int Dm, cudaStream_t st) {
const size_t smem = (3 * HD + 40 + 1) * sizeof(float);
sy::launch(st, H, HD, smem, [=](sy::Blk b, char* smemp) {
float* sk = reinterpret_cast<float*>(smemp);
float* sq = sk + HD;
float* sg = sq + HD;
float* sm = sg + HD;
float* sbeta = sm + 40;
const int h = b.bid(), v = b.tid(), C = H * HD, c = h * HD + v;
float s[HD];
float* Sh = S + static_cast<size_t>(h) * HD * HD;
for (int d = 0; d < HD; ++d) s[d] = Sh[static_cast<size_t>(d) * HD + v];
const float a_exp = sycl::exp(A_log[h]);
for (int t = 0; t < N; ++t) {
if (bw && v < 32) { // this head's beta logit of token t = row h of b_proj . h_t in the arithmetic of the float GEMV (warp 0: 4 floats per lane, ascending, butterfly)
const float* wr = bw + static_cast<size_t>(h) * Dm;
const float* xr = hv + static_cast<size_t>(t) * Dm;
float acc = 0.0f;
for (int i = v; i < (Dm >> 2); i += 32) {
const float w0 = wr[4 * i], w1 = wr[4 * i + 1], w2 = wr[4 * i + 2], w3 = wr[4 * i + 3];
acc += w0 * xr[4 * i] + w1 * xr[4 * i + 1] + w2 * xr[4 * i + 2] + w3 * xr[4 * i + 3];
}
for (int off = 16; off >= 1; off >>= 1) acc += b.shfl_xor(acc, off);
if (v == 0) *sbeta = acc;
}
float y[3];
for (int which = 0; which < 3; ++which) {
const float* w = (which == 0 ? qw : which == 1 ? kw : vw) + static_cast<size_t>(c) * 4;
float acc = 0.0f;
for (int j = 0; j < 4; ++j) {
const int idx = t - 3 + j;
const float x = idx >= 0 ? proj[static_cast<size_t>(idx) * ps + which * C + c] : hist[(static_cast<size_t>(which) * C + c) * 3 + (3 + idx)];
acc += w[j] * x;
}
y[which] = siluf(acc);
}
const float qs = block_sum(b, y[0] * y[0], sm), ks = block_sum(b, y[1] * y[1], sm);
sq[v] = y[0] * (1.0f / sycl::sqrt(qs + 1e-6f)) * sycl::rsqrt(static_cast<float>(HD));
sk[v] = y[1] * (1.0f / sycl::sqrt(ks + 1e-6f));
sg[v] = sycl::exp(lower_bound * sigmoidf(a_exp * (proj[static_cast<size_t>(t) * ps + 3 * C + c] + dt_bias[c])));
b.sync();
const float beta = sigmoidf(bw ? *sbeta : beta_raw[static_cast<size_t>(t) * H + h]);
const float vt = y[2];
float pred = 0.0f;
for (int d = 0; d < HD; ++d) {
s[d] *= sg[d];
pred += sk[d] * s[d];
}
const float delta = beta * (vt - pred);
float o = 0.0f;
for (int d = 0; d < HD; ++d) {
s[d] += sk[d] * delta;
o += sq[d] * s[d];
}
if (snap && t < N - 1) { // speculative verify: S after token t
float* sp = snap + static_cast<size_t>(t) * H * HD * HD + static_cast<size_t>(h) * HD * HD;
for (int d = 0; d < HD; ++d) sp[static_cast<size_t>(d) * HD + v] = s[d];
}
const float ss = block_sum(b, o * o, sm);
const float r = 1.0f / sycl::sqrt(ss / static_cast<float>(HD) + eps);
out[static_cast<size_t>(t) * C + c] = o * r * o_norm[v] * sigmoidf(proj[static_cast<size_t>(t) * ps + 4 * C + c]);
b.sync();
}
for (int d = 0; d < HD; ++d) Sh[static_cast<size_t>(d) * HD + v] = s[d];
// conv history: the last 3 raw projections of this channel (only this thread reads and writes them)
for (int which = 0; which < 3; ++which) {
float* hp = hist + (static_cast<size_t>(which) * C + c) * 3;
const float old[3] = {hp[0], hp[1], hp[2]};
if (ext) {
float* e = ext + (static_cast<size_t>(which) * C + c) * ext_len;
e[0] = old[0]; e[1] = old[1]; e[2] = old[2];
for (int i = 0; i < N; ++i) e[3 + i] = proj[static_cast<size_t>(i) * ps + which * C + c];
}
for (int j = 0; j < 3; ++j) {
const int idx = N - 3 + j;
hp[j] = idx >= 0 ? proj[static_cast<size_t>(idx) * ps + which * C + c] : old[3 + idx];
}
}
});
}
template <int HD>
void launch_step(float* S, const float* qn, const float* kn, const float* vc, const float* f_raw, int fs, const float* g_raw, int gs, const float* beta_raw, const float* A_log, const float* dt_bias,
const float* o_norm, float lower_bound, float eps, float* out, int N, int H, float* snap, cudaStream_t st) {
const size_t smem = (3 * HD + 40) * sizeof(float);
sy::launch(st, H, HD, smem, [=](sy::Blk b, char* smemp) {
float* sk = reinterpret_cast<float*>(smemp);
float* sq = sk + HD;
float* sg = sq + HD;
float* sm = sg + HD;
const int h = b.bid(), v = b.tid(), C = H * HD;
float s[HD];
float* Sh = S + static_cast<size_t>(h) * HD * HD;
for (int d = 0; d < HD; ++d) s[d] = Sh[static_cast<size_t>(d) * HD + v];
const float a_exp = sycl::exp(A_log[h]);
for (int t = 0; t < N; ++t) {
sk[v] = kn[static_cast<size_t>(t) * C + h * HD + v];
sq[v] = qn[static_cast<size_t>(t) * C + h * HD + v];
sg[v] = sycl::exp(lower_bound * sigmoidf(a_exp * (f_raw[static_cast<size_t>(t) * fs + h * HD + v] + dt_bias[h * HD + v])));
b.sync();
const float beta = sigmoidf(beta_raw[static_cast<size_t>(t) * H + h]);
const float vt = vc[static_cast<size_t>(t) * C + h * HD + v];
float pred = 0.0f;
for (int d = 0; d < HD; ++d) {
s[d] *= sg[d];
pred += sk[d] * s[d];
}
const float delta = beta * (vt - pred);
float o = 0.0f;
for (int d = 0; d < HD; ++d) {
s[d] += sk[d] * delta;
o += sq[d] * s[d];
}
if (snap && t < N - 1) {
float* sp = snap + static_cast<size_t>(t) * H * HD * HD + static_cast<size_t>(h) * HD * HD;
for (int d = 0; d < HD; ++d) sp[static_cast<size_t>(d) * HD + v] = s[d];
}
const float ss = block_sum(b, o * o, sm);
const float r = 1.0f / sycl::sqrt(ss / static_cast<float>(HD) + eps);
out[static_cast<size_t>(t) * C + h * HD + v] = o * r * o_norm[v] * sigmoidf(g_raw[static_cast<size_t>(t) * gs + h * HD + v]);
b.sync();
}
for (int d = 0; d < HD; ++d) Sh[static_cast<size_t>(d) * HD + v] = s[d];
});
}
// ---------------------------------------------------------------------------------------------- chunk-parallel form (prefill batches), chunk length 8
// The state-independent part of a chunk (cumulative gate G, the A / Aq matrices, k e^G, q e^G, k e^(Gl - G), beta, e^Gl) is computed by one work-group per (head, chunk) into a scratch buffer; a second
// kernel walks the chunks of a head in order (U, outputs, state update). Port of kda_chunk_pre_kernel / kda_chunk_seq_kernel (CH = 8), same expressions and summation order.
constexpr int kChunk = 8;
template <int HD, int CH>
constexpr size_t kda_chunk_scr_floats() { return 3ull * CH * HD + 2ull * CH * CH + CH + HD; }
template <int HD, int CH>
void launch_chunk_pre(const float* qn, const float* kn, const float* f_raw, int fs, const float* beta_raw, const float* A_log, const float* dt_bias, float lower_bound, int N, int H, float* scr, cudaStream_t st) {
constexpr int LD = HD + 1;
const int nch = (N + CH - 1) / CH;
const size_t smem = (5ull * CH * LD + 2ull * CH * CH + CH + HD) * sizeof(float);
sy::launch(st, nch * H, HD, smem, [=](sy::Blk b, char* smemp) {
const int h = b.bid() % H, ci = b.bid() / H, v = b.tid(), C = H * HD;
const int s0 = ci * CH, c = sycl::min(CH, N - s0);
float* k_s = reinterpret_cast<float*>(smemp);
float* q_s = k_s + CH * LD;
float* G_s = q_s + CH * LD;
float* kE_s = G_s + CH * LD;
float* qE_s = kE_s + CH * LD;
float* A_s = qE_s + CH * LD;
float* Aq_s = A_s + CH * CH;
float* b_s = Aq_s + CH * CH;
float* eGl = b_s + CH;
const float a_exp = sycl::exp(A_log[h]);
float run = 0.0f;
for (int t = 0; t < CH; ++t) {
if (t < c) {
const size_t tok = static_cast<size_t>(s0 + t);
k_s[t * LD + v] = kn[tok * C + h * HD + v];
q_s[t * LD + v] = qn[tok * C + h * HD + v];
run += lower_bound * sigmoidf(a_exp * (f_raw[tok * fs + h * HD + v] + dt_bias[h * HD + v]));
G_s[t * LD + v] = run;
}
}
if (v < c) b_s[v] = sigmoidf(beta_raw[static_cast<size_t>(s0 + v) * H + h]);
b.sync();
for (int p = v; p < c * c; p += HD) {
const int t = p / c, i = p % c;
if (i > t) continue;
float a = 0.0f, aq = 0.0f;
for (int d = 0; d < HD; ++d) {
const float kk = k_s[i * LD + d] * sycl::exp(G_s[t * LD + d] - G_s[i * LD + d]);
a += k_s[t * LD + d] * kk;
aq += q_s[t * LD + d] * kk;
}
A_s[t * CH + i] = (i < t) ? a : 0.0f;
Aq_s[t * CH + i] = aq;
}
b.sync();
{
const float Gl = G_s[(c - 1) * LD + v];
eGl[v] = sycl::exp(Gl);
for (int t = 0; t < c; ++t) {
const float e = sycl::exp(G_s[t * LD + v]), kv = k_s[t * LD + v];
kE_s[t * LD + v] = kv * e;
qE_s[t * LD + v] = q_s[t * LD + v] * e;
k_s[t * LD + v] = kv * sycl::exp(Gl - G_s[t * LD + v]);
}
}
b.sync();
float* dst = scr + (static_cast<size_t>(ci) * H + h) * kda_chunk_scr_floats<HD, CH>();
for (int t = 0; t < c; ++t) {
dst[t * HD + v] = kE_s[t * LD + v];
dst[CH * HD + t * HD + v] = qE_s[t * LD + v];
dst[2 * CH * HD + t * HD + v] = k_s[t * LD + v];
}
float* dA = dst + 3 * CH * HD;
for (int p = v; p < c * CH; p += HD) {
dA[p] = A_s[p];
dA[CH * CH + p] = Aq_s[p];
}
float* dB = dA + 2 * CH * CH;
if (v < c) dB[v] = b_s[v];
dB[CH + v] = eGl[v];
});
}
template <int HD, int CH>
void launch_chunk_seq(float* S, const float* vc, const float* g_raw, int gs, const float* o_norm, float eps, float* out, int N, int H, const float* scr, cudaStream_t st) {
constexpr int LD = HD + 1, NW = HD / 32;
const size_t smem = (4ull * CH * LD + 2ull * CH * CH + CH + HD + CH * NW + CH) * sizeof(float);
sy::launch(st, H, HD, smem, [=](sy::Blk b, char* smemp) {
const int h = b.bid(), v = b.tid(), C = H * HD, w = v >> 5, lane = v & 31;
float* kE_s = reinterpret_cast<float*>(smemp);
float* qE_s = kE_s + CH * LD;
float* k_s = qE_s + CH * LD;
float* vc_s = k_s + CH * LD;
float* A_s = vc_s + CH * LD;
float* Aq_s = A_s + CH * CH;
float* b_s = Aq_s + CH * CH;
float* eGl = b_s + CH;
float* parts = eGl + HD;
float* ssv = parts + CH * NW;
float s[HD];
float* Sh = S + static_cast<size_t>(h) * HD * HD;
for (int d = 0; d < HD; ++d) s[d] = Sh[static_cast<size_t>(d) * HD + v];
for (int ci = 0, s0 = 0; s0 < N; ++ci, s0 += CH) {
const int c = sycl::min(CH, N - s0);
const float* src = scr + (static_cast<size_t>(ci) * H + h) * kda_chunk_scr_floats<HD, CH>();
for (int t = 0; t < CH; ++t)
if (t < c) {
kE_s[t * LD + v] = src[t * HD + v];
qE_s[t * LD + v] = src[CH * HD + t * HD + v];
k_s[t * LD + v] = src[2 * CH * HD + t * HD + v];
vc_s[t * LD + v] = vc[static_cast<size_t>(s0 + t) * C + h * HD + v];
}
const float* sA = src + 3 * CH * HD;
for (int p = v; p < c * CH; p += HD) {
A_s[p] = sA[p];
Aq_s[p] = sA[CH * CH + p];
}
const float* sB = sA + 2 * CH * CH;
if (v < c) b_s[v] = sB[v];
eGl[v] = sB[CH + v];
b.sync();
float U[CH];
{
float accd[CH];
for (int t = 0; t < CH; ++t) accd[t] = 0.0f;
for (int d = 0; d < HD; ++d) {
const float sd = s[d];
for (int t = 0; t < CH; ++t) accd[t] += kE_s[t * LD + d] * sd; // rows t >= c hold stale tiles: their results are never used
}
for (int t = 0; t < CH; ++t) {
U[t] = 0.0f;
if (t < c) {
float sub = 0.0f;
for (int i = 0; i < t; ++i) sub += A_s[t * CH + i] * U[i];
const float bt = b_s[t];
U[t] = bt * (vc_s[t * LD + v] - accd[t]) - bt * sub;
}
}
}
float O[CH];
{
for (int t = 0; t < CH; ++t) O[t] = 0.0f;
for (int d = 0; d < HD; ++d) {
const float sd = s[d];
for (int t = 0; t < CH; ++t) O[t] += qE_s[t * LD + d] * sd;
}
for (int t = 0; t < CH; ++t) {
if (t < c) {
float o = O[t];
for (int i = 0; i <= t; ++i) o += Aq_s[t * CH + i] * U[i];
O[t] = o;
const float wsum = sy::warp_sum_xor(b, o * o);
if (lane == 0) parts[t * NW + w] = wsum;
}
}
}
b.sync();
for (int t = w; t < c; t += NW) { // the cross-warp sum of block_sum, per row
float r = lane < NW ? parts[t * NW + lane] : 0.0f;
r = sy::warp_sum_xor(b, r);
if (lane == 0) ssv[t] = r;
}
b.sync();
for (int t = 0; t < CH; ++t)
if (t < c) {
const float r = 1.0f / sycl::sqrt(ssv[t] / static_cast<float>(HD) + eps);
const size_t tok = static_cast<size_t>(s0 + t);
out[tok * C + h * HD + v] = O[t] * r * o_norm[v] * sigmoidf(g_raw[tok * gs + h * HD + v]);
}
for (int d = 0; d < HD; ++d) {
float acc = eGl[d] * s[d];
for (int i = 0; i < CH; ++i)
if (i < c) acc += k_s[i * LD + d] * U[i];
s[d] = acc;
}
b.sync();
}
for (int d = 0; d < HD; ++d) Sh[static_cast<size_t>(d) * HD + v] = s[d];
});
}
[[noreturn]] void bad_hd(int hd) {
std::fprintf(stderr, "ling32: KDA head dim %d is not built (64, 128)\n", hd);
std::abort();
}
} // namespace
void kda_prep(const float* proj, int ps, const float* qw, const float* kw, const float* vw, float* hist, float* qn, float* kn, float* vc, int N, int H, int hd, cudaStream_t s, float* hist_ext,
int ext_len) {
if (hd == 128) launch_prep<128>(proj, ps, qw, kw, vw, hist, qn, kn, vc, N, H, s);
else if (hd == 64) launch_prep<64>(proj, ps, qw, kw, vw, hist, qn, kn, vc, N, H, s);
else bad_hd(hd);
const int C = H * hd;
const int gx = (C + 127) / 128;
sy::launch(s, gx * 3, 128, 0, [=](sy::Blk b, char*) {
const int c = (b.bid() % gx) * b.bdim() + b.tid(), which = b.bid() / gx;
if (c >= C) return;
float* hp = hist + (static_cast<size_t>(which) * C + c) * 3;
const float old[3] = {hp[0], hp[1], hp[2]};
if (hist_ext) {
float* e = hist_ext + (static_cast<size_t>(which) * C + c) * ext_len;
e[0] = old[0]; e[1] = old[1]; e[2] = old[2];
for (int i = 0; i < N; ++i) e[3 + i] = proj[static_cast<size_t>(i) * ps + which * C + c];
}
float nw[3];
for (int j = 0; j < 3; ++j) {
const int idx = N - 3 + j;
nw[j] = idx >= 0 ? proj[static_cast<size_t>(idx) * ps + which * C + c] : old[3 + idx];
}
hp[0] = nw[0]; hp[1] = nw[1]; hp[2] = nw[2];
});
}
void kda_step_fused(float* S, const float* proj, int ps, const float* qw, const float* kw, const float* vw, float* hist, const float* beta_raw, const float* A_log, const float* dt_bias,
const float* o_norm, float lower_bound, float eps, float* out, int N, int H, int hd, cudaStream_t s, float* snap, float* hist_ext, int ext_len, const float* b_proj, const float* hvec, int Dm) {
if (hd == 128) launch_step_fused<128>(S, proj, ps, qw, kw, vw, hist, beta_raw, A_log, dt_bias, o_norm, lower_bound, eps, out, N, H, snap, hist_ext, ext_len, b_proj, hvec, Dm, s);
else if (hd == 64) launch_step_fused<64>(S, proj, ps, qw, kw, vw, hist, beta_raw, A_log, dt_bias, o_norm, lower_bound, eps, out, N, H, snap, hist_ext, ext_len, b_proj, hvec, Dm, s);
else bad_hd(hd);
}
void kda_step(float* S, const float* qn, const float* kn, const float* vc, const float* f_raw, int fs, const float* g_raw, int gs, const float* beta_raw, const float* A_log, const float* dt_bias,
const float* o_norm, float lower_bound, float eps, float* out, int N, int H, int hd, bool chunked, cudaStream_t s, float* snap, float* scratch, size_t scratch_floats) {
if (chunked && N > 1 && !snap && scratch) { // the two-kernel chunk-parallel form (chunks of 8 tokens)
const int nch = (N + kChunk - 1) / kChunk;
const size_t need = static_cast<size_t>(nch) * H * (hd == 64 ? kda_chunk_scr_floats<64, kChunk>() : kda_chunk_scr_floats<128, kChunk>());
if (need > scratch_floats) { std::fprintf(stderr, "ling32: KDA chunk scratch too small\n"); std::abort(); }
if (hd == 128) { launch_chunk_pre<128, kChunk>(qn, kn, f_raw, fs, beta_raw, A_log, dt_bias, lower_bound, N, H, scratch, s); launch_chunk_seq<128, kChunk>(S, vc, g_raw, gs, o_norm, eps, out, N, H, scratch, s); }
else if (hd == 64) { launch_chunk_pre<64, kChunk>(qn, kn, f_raw, fs, beta_raw, A_log, dt_bias, lower_bound, N, H, scratch, s); launch_chunk_seq<64, kChunk>(S, vc, g_raw, gs, o_norm, eps, out, N, H, scratch, s); }
else bad_hd(hd);
return;
}
if (hd == 128) launch_step<128>(S, qn, kn, vc, f_raw, fs, g_raw, gs, beta_raw, A_log, dt_bias, o_norm, lower_bound, eps, out, N, H, snap, s);
else if (hd == 64) launch_step<64>(S, qn, kn, vc, f_raw, fs, g_raw, gs, beta_raw, A_log, dt_bias, o_norm, lower_bound, eps, out, N, H, snap, s);
else bad_hd(hd);
}
size_t kda_chunk_scratch_floats(int N, int H, int hd) {
const size_t nch = (static_cast<size_t>(N) + kChunk - 1) / kChunk;
return nch * H * (hd == 64 ? kda_chunk_scr_floats<64, kChunk>() : kda_chunk_scr_floats<128, kChunk>());
}
} // namespace strata::ling32::gpu
@@ -0,0 +1,34 @@
// src/ling32/sycl/ling32_sy_k_misc.cpp - small kernels of ling32_layers.cu on SYCL: argmax over rows of logits (ties: lower index).
#include "ling32_sy.hpp"
#include <cfloat>
namespace strata::ling32::gpu {
void argmax_rows(const float* logits, int N, int V, int* out, cudaStream_t s) {
sy::launch(s, N, 256, (32 * 2) * 4, [=](sy::Blk b, char* smem) {
float* sv = reinterpret_cast<float*>(smem);
int* si = reinterpret_cast<int*>(smem + 32 * 4);
const float* r = logits + static_cast<size_t>(b.bid()) * V;
float bv = -FLT_MAX;
int bi = 0;
for (int i = b.tid(); i < V; i += b.bdim())
if (r[i] > bv) { bv = r[i]; bi = i; }
for (int o = 16; o >= 1; o >>= 1) {
const float ov = b.shfl_xor(bv, o);
const int oi = b.shfl_xor(bi, o);
if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
}
if (b.lane() == 0) { sv[b.warp()] = bv; si[b.warp()] = bi; }
b.sync();
if (b.tid() == 0) {
float bb = sv[0];
int ii = si[0];
for (int w = 1; w < (b.bdim() >> 5); ++w)
if (sv[w] > bb || (sv[w] == bb && si[w] < ii)) { bb = sv[w]; ii = si[w]; }
out[b.bid()] = ii;
}
});
}
} // namespace strata::ling32::gpu
+260
View File
@@ -0,0 +1,260 @@
// src/ling32/sycl/ling32_sy_k_mla.cpp - absorbed MLA on SYCL: mla_prep (latent RMSNorm + cache write + rotary), mla_qabs, mla_attn (online softmax over the latent cache), mla_out, embed_override.
// Port of the "original" per-head attention path of ling32_layers.cu (engine option mla_kernel = 0). Latent cache formats: fp32 (default) and fp16. Not here: the Q8 / f16x2 / study (emul_*) caches
// and mla_attn_fast / mla_exp_* (stay aborting stubs in ling32_sy_todo.cpp; the engine takes them only for --mla-kernel / --mla-prefill options).
// The rotary angles are computed on the HOST in double precision (as the CUDA kernel does on the device, which Intel GPUs have no hardware for) into a float (cos, sin) table, once per (theta, rope).
#include "ling32_sy.hpp"
#include <cfloat>
#include <cmath>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <mutex>
#include <tuple>
namespace strata::ling32::gpu {
namespace {
inline float bf16f(uint16_t b) { return sycl::bit_cast<float>(static_cast<uint32_t>(b) << 16); }
inline float sigmoidf(float x) { return 1.0f / (1.0f + sycl::exp(-x)); }
inline float ldc(const void* c, size_t i, int f32) { return f32 ? static_cast<const float*>(c)[i] : sy::h2f(static_cast<const uint16_t*>(c)[i]); }
inline void stc(void* c, size_t i, float v, int f32) {
if (f32) static_cast<float*>(c)[i] = v;
else static_cast<uint16_t*>(c)[i] = sy::f2h(v);
}
inline float block_sum(const sy::Blk& b, float v, float* sm) {
const int lane = b.lane(), w = b.warp(), nw = (b.bdim() + 31) >> 5;
v = sy::warp_sum_xor(b, v);
b.sync();
if (lane == 0) sm[w] = v;
b.sync();
if (w == 0) {
float r = lane < nw ? sm[lane] : 0.0f;
r = sy::warp_sum_xor(b, r);
if (lane == 0) sm[32] = r;
}
b.sync();
return sm[32];
}
inline float block_max(const sy::Blk& b, float v, float* sm) {
const int lane = b.lane(), w = b.warp(), nw = (b.bdim() + 31) >> 5;
for (int o = 16; o >= 1; o >>= 1) v = sycl::fmax(v, b.shfl_xor(v, o));
b.sync();
if (lane == 0) sm[w] = v;
b.sync();
if (w == 0) {
float r = lane < nw ? sm[lane] : -FLT_MAX;
for (int o = 16; o >= 1; o >>= 1) r = sycl::fmax(r, b.shfl_xor(r, o));
if (lane == 0) sm[32] = r;
}
b.sync();
return sm[32];
}
// ---- rotary table: entry [pos][j] = (cos, sin) of pair j at position pos (double angle on the host, like rope_pair of the CUDA kernel)
struct RopeTab {
float* dev = nullptr; // float2 [npos][rope/2]
int npos = 0;
};
constexpr int kRopeMargin = 65536; // positions beyond max_ctx (a text tail after pictures shifts the angle position; M-RoPE triples are small)
RopeTab& rope_table(double theta, int rope, int rope_f32, int max_ctx) {
static std::mutex mu;
static std::map<std::tuple<double, int, int, int, int>, RopeTab> tabs;
std::lock_guard<std::mutex> g(mu);
const auto key = std::make_tuple(theta, rope, rope_f32, max_ctx, strata::sy::cur_dev());
auto it = tabs.find(key);
if (it != tabs.end()) return it->second;
RopeTab t;
t.npos = max_ctx + 2 * kRopeMargin; // positions -kRopeMargin .. max_ctx + kRopeMargin - 1 (picture positions can be negative after a rope delta)
const int np = rope / 2;
std::vector<float> h(static_cast<size_t>(t.npos) * np * 2);
for (int j = 0; j < np; ++j) {
if (rope_f32) {
const float inv = 1.0f / std::pow(static_cast<float>(theta), static_cast<float>(2 * j) / static_cast<float>(rope));
for (int p = 0; p < t.npos; ++p) {
const float a = static_cast<float>(p - kRopeMargin) * inv;
h[(static_cast<size_t>(p) * np + j) * 2] = std::cos(a);
h[(static_cast<size_t>(p) * np + j) * 2 + 1] = std::sin(a);
}
} else {
const double inv = std::pow(theta, -2.0 * j / static_cast<double>(rope));
for (int p = 0; p < t.npos; ++p) {
const double a = std::fmod(static_cast<double>(p - kRopeMargin) * inv, 6.283185307179586);
h[(static_cast<size_t>(p) * np + j) * 2] = std::cos(static_cast<float>(a));
h[(static_cast<size_t>(p) * np + j) * 2 + 1] = std::sin(static_cast<float>(a));
}
}
}
if (cudaMalloc(reinterpret_cast<void**>(&t.dev), h.size() * sizeof(float)) != cudaSuccess || cudaMemcpy(t.dev, h.data(), h.size() * sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess) {
std::fprintf(stderr, "ling32 (SYCL): cannot allocate the rotary table (%zu bytes)\n", h.size() * sizeof(float));
std::abort();
}
return tabs.emplace(key, t).first->second;
}
void check_mla_fmt(LatentFmt fmt, int emul_lat, int emul_pe) {
if ((fmt != LatentFmt::F32 && fmt != LatentFmt::F16) || (fmt == LatentFmt::F32 && (emul_lat || emul_pe)) || (fmt == LatentFmt::F16 && (emul_lat || emul_pe))) {
std::fprintf(stderr, "ling32 (SYCL): only the fp32 and fp16 latent caches are implemented (--latent f32 | f16)\n");
std::abort();
}
}
} // namespace
void mla_prep(float* q, const float* ckv, int cs, const float* ln, void* cache, const int* d_pos0, int N, int H, int nope, int rope, int kv_lora, double theta, float eps, LatentFmt fmt,
int max_ctx, int emul_lat, int emul_pe, bool rope_f32, cudaStream_t s, const int* d_mpos, const int* d_rdelta) {
check_mla_fmt(fmt, emul_lat, emul_pe);
const RopeTab& rt = rope_table(theta, rope, rope_f32 ? 1 : 0, max_ctx);
const float* tab = rt.dev;
const int npos = rt.npos, np = rope / 2;
const int cache_f32 = fmt == LatentFmt::F32;
sy::launch(s, N * (1 + H), 256, 40 * sizeof(float), [=](sy::Blk b, char* smem) {
float* sm = reinterpret_cast<float*>(smem);
const int t = b.bid() % N, by = b.bid() / N, pos = *d_pos0 + t, W = kv_lora + rope;
const int rtext = pos + (d_rdelta ? *d_rdelta : 0);
auto rpos = [&](int j) { return d_mpos ? d_mpos[t * 3 + (j < 24 ? (j % 2 == 0 ? 1 : 2) : 0)] : rtext; };
auto cossin = [&](int j, float& c, float& sn) {
int p = rpos(j) + kRopeMargin;
p = p < 0 ? 0 : (p >= npos ? npos - 1 : p);
c = tab[(static_cast<size_t>(p) * np + j) * 2];
sn = tab[(static_cast<size_t>(p) * np + j) * 2 + 1];
};
if (by > 0) { // blocks 1..H: the rotary part of head (by - 1)'s query
const int h = by - 1;
float* qh = q + static_cast<size_t>(t) * H * (nope + rope) + h * (nope + rope) + nope;
for (int j = b.tid(); j < np; j += b.bdim()) {
float c, sn;
cossin(j, c, sn);
float* p = qh + 2 * j;
const float xe = p[0], xo = p[1];
p[0] = xe * c - xo * sn;
p[1] = xo * c + xe * sn;
}
return;
}
const float* cr = ckv + static_cast<size_t>(t) * cs;
float ss = 0.0f;
for (int i = b.tid(); i < kv_lora; i += b.bdim()) ss += cr[i] * cr[i];
ss = block_sum(b, ss, sm);
const float r = 1.0f / sycl::sqrt(ss / static_cast<float>(kv_lora) + eps);
const size_t cl = static_cast<size_t>(pos) * W;
for (int i = b.tid(); i < kv_lora; i += b.bdim()) stc(cache, cl + i, cr[i] * r * ln[i], cache_f32);
for (int j = b.tid(); j < np; j += b.bdim()) {
float c, sn;
cossin(j, c, sn);
const float xe = cr[kv_lora + 2 * j], xo = cr[kv_lora + 2 * j + 1];
stc(cache, cl + kv_lora + 2 * j, xe * c - xo * sn, cache_f32);
stc(cache, cl + kv_lora + 2 * j + 1, xo * c + xe * sn, cache_f32);
}
});
}
void mla_prep_old(const float*, int, const float*, void*, const int*, int, int, int, int, double, float, int, int, int, bool, cudaStream_t, const int*, const int*) {
std::fprintf(stderr, "ling32 (SYCL): --age-mix (study) is not implemented\n");
std::abort();
}
void embed_override(float* x, const float* emb, const uint8_t* flag, int N, int D, cudaStream_t s) {
sy::launch(s, N, 256, 0, [=](sy::Blk b, char*) {
const int t = b.bid();
if (!flag[t]) return;
for (int i = b.tid(); i < D; i += b.bdim()) x[static_cast<size_t>(t) * D + i] = emb[static_cast<size_t>(t) * D + i];
});
}
// q_abs[t][h][k] = sum_d q_nope[t][h][d] * wk_b[h][d][k]. grid (N*H, ceil(kv_lora / 128)), block 128
void mla_qabs(const float* q, const uint16_t* wk_b, float* qabs, int N, int H, int nope, int rope, int kv_lora, cudaStream_t s) {
const int gx = N * H, gy = (kv_lora + 127) / 128;
sy::launch(s, gx * gy, 128, nope * sizeof(float), [=](sy::Blk b, char* smem) {
float* qs = reinterpret_cast<float*>(smem);
const int th = b.bid() % gx, by = b.bid() / gx, h = th % H;
for (int d = b.tid(); d < nope; d += b.bdim()) qs[d] = q[static_cast<size_t>(th) * (nope + rope) + d];
b.sync();
const int k = by * b.bdim() + b.tid();
if (k < kv_lora) {
float acc = 0.0f;
for (int d = 0; d < nope; ++d) acc += qs[d] * bf16f(wk_b[(static_cast<size_t>(h) * nope + d) * kv_lora + k]);
qabs[static_cast<size_t>(th) * kv_lora + k] = acc;
}
});
}
// (L32-SY-MLA: this is now mla_attn_orig; mla_attn itself is the dispatcher in ling32_sy_k_mla_fd.cpp)
// absorbed attention over the latent cache (online softmax, 256 keys per step). grid (N, H), block 256; smem (kv_lora + rope + 256) floats
void mla_attn_orig(const float* qabs, const float* q, const void* cache, const int* d_pos0, float* ctx, int N, int H, int nope, int rope, int kv_lora, float scale, bool cache_f32_b, cudaStream_t s) {
constexpr int kAttBlk = 256;
const int cache_f32 = cache_f32_b ? 1 : 0;
const size_t smem = (static_cast<size_t>(kv_lora) + rope + kAttBlk + 40) * sizeof(float);
sy::launch(s, N * H, kAttBlk, smem, [=](sy::Blk b, char* smemp) {
float* qa = reinterpret_cast<float*>(smemp);
float* qp = qa + kv_lora;
float* pr = qp + rope;
float* sm = pr + kAttBlk;
const int t = b.bid() % N, h = b.bid() / N, th = t * H + h, W = kv_lora + rope, L = *d_pos0 + t + 1;
const int tid = b.tid();
for (int k = tid; k < kv_lora; k += kAttBlk) qa[k] = qabs[static_cast<size_t>(th) * kv_lora + k];
for (int i = tid; i < rope; i += kAttBlk) qp[i] = q[static_cast<size_t>(th) * (nope + rope) + nope + i];
b.sync();
constexpr int kMaxAcc = 2; // kv_lora <= 512
float acc[kMaxAcc] = {0.0f, 0.0f};
float m = -FLT_MAX, l = 0.0f;
for (int j0 = 0; j0 < L; j0 += kAttBlk) {
const int n = sycl::min(kAttBlk, L - j0);
float sc = -FLT_MAX;
if (tid < n) {
const size_t row = static_cast<size_t>(j0 + tid) * W;
float a = 0.0f;
for (int k = 0; k < kv_lora; ++k) a += qa[k] * ldc(cache, row + k, cache_f32);
for (int i = 0; i < rope; ++i) a += qp[i] * ldc(cache, row + kv_lora + i, cache_f32);
sc = a * scale;
}
const float cm = block_max(b, sc, sm);
const float mn = sycl::fmax(m, cm);
const float corr = sycl::exp(m - mn);
const float p = tid < n ? sycl::exp(sc - mn) : 0.0f;
pr[tid] = p;
const float ps = block_sum(b, p, sm); // also the barrier that publishes pr
l = l * corr + ps;
for (int r = 0; r < kMaxAcc; ++r) acc[r] *= corr;
m = mn;
for (int r = 0; r < kMaxAcc; ++r) {
const int k = tid + r * kAttBlk;
if (k < kv_lora) {
float a = 0.0f;
for (int i = 0; i < n; ++i) a += pr[i] * ldc(cache, static_cast<size_t>(j0 + i) * W + k, cache_f32);
acc[r] += a;
}
}
b.sync();
}
for (int r = 0; r < kMaxAcc; ++r) {
const int k = tid + r * kAttBlk;
if (k < kv_lora) ctx[static_cast<size_t>(th) * kv_lora + k] = acc[r] / l;
}
});
}
// out[t][h][v] = (sum_k ctx[t][h][k] * wv_b[h][v][k]) * sigmoid(gate_logit[t][h]). grid (N, H, 8), block 128
void mla_out(const float* ctx, const uint16_t* wv_b, const float* gate_logit, float* out, int N, int H, int vhead, int kv_lora, cudaStream_t s) {
constexpr int GZ = 8;
sy::launch(s, N * H * GZ, 128, kv_lora * sizeof(float), [=](sy::Blk b, char* smem) {
float* cs = reinterpret_cast<float*>(smem);
const int t = b.bid() % N, h = (b.bid() / N) % H, z = b.bid() / (N * H), th = t * H + h;
const int rows_per = (vhead + GZ - 1) / GZ, v0 = z * rows_per, v1 = sycl::min(vhead, v0 + rows_per);
for (int k = b.tid(); k < kv_lora; k += b.bdim()) cs[k] = ctx[static_cast<size_t>(th) * kv_lora + k];
b.sync();
const int lane = b.lane(), w = b.warp(), nw = b.bdim() >> 5;
const float g = sigmoidf(gate_logit[th]);
for (int v = v0 + w; v < v1; v += nw) {
const uint16_t* row = wv_b + (static_cast<size_t>(h) * vhead + v) * kv_lora;
float a = 0.0f;
for (int k = lane; k < kv_lora; k += 32) a += cs[k] * bf16f(row[k]);
a = sy::warp_sum_xor(b, a);
if (lane == 0) out[static_cast<size_t>(th) * vhead + v] = a * g;
}
});
}
} // namespace strata::ling32::gpu
@@ -0,0 +1,290 @@
// src/ling32/sycl/ling32_sy_k_mla_fd.cpp - absorbed MLA decode attention as flash-decoding (split over the context, then a reduction), fp32 latent cache.
// Owner: L32-SY-MLA. The original kernel (ling32_sy_k_mla.cpp, mla_attn_orig) runs one work-group per (token, head): the 32 heads read the same latent rows 32 times, one row per thread, 5 GB/s.
// Here one work-group serves kFdHG = 8 heads over a slice of the context, reading each latent row once for K and again for V (K and V are the same data; the second read is L1/L2 hot):
// stage 1 grid (N tokens x H/8 head groups x kFdSplits slices), 256 threads (8 sub-groups). Per tile of 32 rows:
// QK a sub-group owns 4 rows (2 batches of 2): the lanes cover the 576 floats of a row (4 x float4 + a float2), q of the 8 heads is in SLM, the 16 (head, row) partial sums per
// lane are reduced over the 32 lanes with a reduce-scatter butterfly (16 shuffles per batch).
// softmax sub-group w = head w, lane = row (online: running max m, sum l, rescale factor corr).
// PV thread = (4 output columns, row parity), 8 heads x 4 accumulators in registers, one float4 of V per 32 FMA.
// the two row parities are summed at the end and the un-normalised partial (acc, m, l) goes to a scratch buffer.
// stage 2 grid (N x H x 4), 128 threads: combine the slices of a head with the usual max/sum merge, divide by the total l.
// The split count is fixed (the launcher cannot see the context length: d_pos0 is on the device); a slice is ceil(L / kFdSplits) rows rounded up to a multiple of 32, so a short context
// uses few slices and the remaining work-groups return at once. Summation order differs from the original kernel (not bit-exact, within 1e-5, see ling32_sy_mla_fd_test).
#include "ling32_sy.hpp"
#include <algorithm>
#include <cfloat>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <mutex>
namespace strata::ling32::gpu {
namespace {
constexpr int kFdHG = 8; // heads per work-group (= sub-groups per work-group)
constexpr int kFdRows = 32; // rows per tile
constexpr int kFdThreads = 256;
constexpr int kFdW = 576; // kv_lora 512 + rope 64
constexpr int kFdKv = 512;
constexpr int kFdMaxSplits = 128; // scratch size; the split count in use is a launcher argument (default kFdSplitsDef)
constexpr int kFdSplitsDef = 48;
constexpr int kFdMaxN = 16; // tokens per call served by this path (spec spans); larger N (prompt chunks) stays on the original kernel
using f4 = sycl::float4;
using f2 = sycl::float2;
struct FdScratch {
float* part = nullptr; // [N][H][ns][512]
float* ml = nullptr; // [N][H][ns][2]
};
FdScratch& fd_scratch(int H) {
static std::mutex mu;
static std::map<std::pair<int, int>, FdScratch> tabs;
std::lock_guard<std::mutex> g(mu);
const auto key = std::make_pair(strata::sy::cur_dev(), H);
auto it = tabs.find(key);
if (it != tabs.end()) return it->second;
FdScratch sc;
const size_t np = static_cast<size_t>(kFdMaxN) * H * kFdMaxSplits * kFdKv * sizeof(float), nm = static_cast<size_t>(kFdMaxN) * H * kFdMaxSplits * 2 * sizeof(float);
if (cudaMalloc(reinterpret_cast<void**>(&sc.part), np) != cudaSuccess || cudaMalloc(reinterpret_cast<void**>(&sc.ml), nm) != cudaSuccess) {
std::fprintf(stderr, "ling32 (SYCL): cannot allocate the MLA flash-decoding scratch (%zu bytes)\n", np + nm);
std::abort();
}
return tabs.emplace(key, sc).first->second;
}
// reduce-scatter step: v[0..2n) -> v[0..n); lane bit `mask` selects which half the lane keeps, the partner (lane ^ mask) sends the other half
template <int NN>
inline void rs_step(const sy::Blk& b, float* v, int mask) {
const bool up = (b.lane() & mask) != 0;
#pragma unroll
for (int i = 0; i < NN; ++i) {
const float keep = up ? v[i + NN] : v[i];
const float give = up ? v[i] : v[i + NN];
v[i] = keep + b.shfl_xor(give, mask);
}
}
// slice length (rows) of a context of L rows
inline int fd_chunk(int L, int ns) { return (((L + ns - 1) / ns) + (kFdRows - 1)) & ~(kFdRows - 1); }
template <int RB, int PVU>
void fd_stage1(const float* qabs, const float* q, const float* cache, const int* d_pos0, float* part, float* ml, int N, int H, int nope, int rope, float scale, int ns, cudaStream_t s) {
const int NHG = H / kFdHG;
const size_t smem = (static_cast<size_t>(kFdHG) * kFdW + kFdRows * kFdHG + 16) * sizeof(float);
sy::launch(s, N * NHG * ns, kFdThreads, smem, [=](sy::Blk b, char* smemp) {
float* qs = reinterpret_cast<float*>(smemp); // [8][576]; reused for the final row-parity merge
float* S = qs + kFdHG * kFdW; // [32 rows][8 heads]: scores, then probabilities
float* corr = S + kFdRows * kFdHG; // [8]
const int bid = b.bid(), hg = bid % NHG, sp = (bid / NHG) % ns, t = bid / (NHG * ns);
const int L = *d_pos0 + t + 1;
const int cs = fd_chunk(L, ns), start = sp * cs;
if (start >= L) return;
const int end = sycl::min(L, start + cs);
const int tid = b.tid(), lane = b.lane(), w = b.warp();
for (int idx = tid; idx < kFdHG * kFdW; idx += kFdThreads) {
const int hh = idx / kFdW, k = idx - hh * kFdW;
const size_t th = static_cast<size_t>(t) * H + hg * kFdHG + hh;
qs[idx] = k < kFdKv ? qabs[th * kFdKv + k] : q[th * (nope + rope) + nope + (k - kFdKv)];
}
b.sync();
float m = -FLT_MAX, l = 0.0f; // running state of head w (uniform over the sub-group)
const int cg = tid & 127, rh = tid >> 7; // PV: columns 4cg..4cg+3, rows of parity rh
float acc[kFdHG][4];
#pragma unroll
for (int hh = 0; hh < kFdHG; ++hh)
#pragma unroll
for (int c = 0; c < 4; ++c) acc[hh][c] = 0.0f;
for (int r0 = start; r0 < end; r0 += kFdRows) {
const int n = sycl::min(kFdRows, end - r0);
// ---- QK: RB rows per batch, 4 / RB batches per sub-group
#pragma unroll 1
for (int bt = 0; bt < 4 / RB; ++bt) {
const int ri0 = w * 4 + bt * RB;
f4 kv[RB][4];
f2 kr[RB];
#pragma unroll
for (int rb = 0; rb < RB; ++rb) {
const float* rp = cache + static_cast<size_t>(r0 + sycl::min(ri0 + rb, n - 1)) * kFdW;
#pragma unroll
for (int j = 0; j < 4; ++j) kv[rb][j] = *reinterpret_cast<const f4*>(rp + 4 * lane + 128 * j);
kr[rb] = *reinterpret_cast<const f2*>(rp + kFdKv + 2 * lane);
}
float a[RB * kFdHG];
#pragma unroll
for (int i = 0; i < RB * kFdHG; ++i) a[i] = 0.0f;
#pragma unroll
for (int hh = 0; hh < kFdHG; ++hh) {
const float* qh = qs + hh * kFdW;
#pragma unroll
for (int j = 0; j < 4; ++j) {
const f4 qv = *reinterpret_cast<const f4*>(qh + 4 * lane + 128 * j);
#pragma unroll
for (int rb = 0; rb < RB; ++rb) {
float x = a[hh * RB + rb];
x = sycl::fma(qv.x(), kv[rb][j].x(), x);
x = sycl::fma(qv.y(), kv[rb][j].y(), x);
x = sycl::fma(qv.z(), kv[rb][j].z(), x);
x = sycl::fma(qv.w(), kv[rb][j].w(), x);
a[hh * RB + rb] = x;
}
}
const f2 qr = *reinterpret_cast<const f2*>(qh + kFdKv + 2 * lane);
#pragma unroll
for (int rb = 0; rb < RB; ++rb) {
float x = a[hh * RB + rb];
x = sycl::fma(qr.x(), kr[rb].x(), x);
x = sycl::fma(qr.y(), kr[rb].y(), x);
a[hh * RB + rb] = x;
}
}
// reduce-scatter of the RB * 8 sums over the 32 lanes; lane then holds the sum for index (lane >> (5 - rounds)) & (NV - 1)
if (RB == 2) {
rs_step<8>(b, a, 16);
rs_step<4>(b, a, 8);
rs_step<2>(b, a, 4);
rs_step<1>(b, a, 2);
} else {
rs_step<4>(b, a, 16);
rs_step<2>(b, a, 8);
rs_step<1>(b, a, 4);
a[0] += b.shfl_xor(a[0], 2);
}
const float tot = a[0] + b.shfl_xor(a[0], 1);
if ((lane & 1) == 0 && (RB == 2 || (lane & 2) == 0)) {
const int idx = RB == 2 ? ((lane >> 1) & 15) : ((lane >> 2) & 7); // original index hh * RB + rb
S[(ri0 + (idx % RB)) * kFdHG + (idx / RB)] = tot * scale;
}
}
b.sync();
// ---- online softmax: sub-group w = head w, lane = row
{
const float sc = lane < n ? S[lane * kFdHG + w] : -FLT_MAX;
const float tm = b.warp_max(sc);
const float mn = sycl::fmax(m, tm);
const float cr = sycl::exp(m - mn);
const float p = lane < n ? sycl::exp(sc - mn) : 0.0f;
const float ps = sy::warp_sum_xor(b, p);
l = l * cr + ps;
m = mn;
S[lane * kFdHG + w] = p;
if (lane == 0) corr[w] = cr;
}
b.sync();
// ---- PV
{
const f4 c0 = *reinterpret_cast<const f4*>(corr), c1 = *reinterpret_cast<const f4*>(corr + 4);
const float cr[kFdHG] = {c0.x(), c0.y(), c0.z(), c0.w(), c1.x(), c1.y(), c1.z(), c1.w()};
#pragma unroll
for (int hh = 0; hh < kFdHG; ++hh)
#pragma unroll
for (int c = 0; c < 4; ++c) acc[hh][c] *= cr[hh];
// rows rr = rh, rh + 2, ... of the tile, PVU at a time with their V loads issued first; rows >= n are clamped to a valid row and have p = 0
#pragma unroll 1
for (int u = 0; 2 * u + rh < n; u += PVU) {
f4 vv[PVU];
#pragma unroll
for (int i = 0; i < PVU; ++i) vv[i] = *reinterpret_cast<const f4*>(cache + static_cast<size_t>(r0 + sycl::min(rh + 2 * (u + i), n - 1)) * kFdW + 4 * cg);
#pragma unroll
for (int i = 0; i < PVU; ++i) {
const int rr = rh + 2 * (u + i);
const f4 p0 = *reinterpret_cast<const f4*>(S + rr * kFdHG), p1 = *reinterpret_cast<const f4*>(S + rr * kFdHG + 4);
const float pp[kFdHG] = {p0.x(), p0.y(), p0.z(), p0.w(), p1.x(), p1.y(), p1.z(), p1.w()};
#pragma unroll
for (int hh = 0; hh < kFdHG; ++hh) {
acc[hh][0] = sycl::fma(pp[hh], vv[i].x(), acc[hh][0]);
acc[hh][1] = sycl::fma(pp[hh], vv[i].y(), acc[hh][1]);
acc[hh][2] = sycl::fma(pp[hh], vv[i].z(), acc[hh][2]);
acc[hh][3] = sycl::fma(pp[hh], vv[i].w(), acc[hh][3]);
}
}
}
}
b.sync();
}
// ---- merge the two row parities (through SLM) and write the partial
if (rh == 1) {
for (int hh = 0; hh < kFdHG; ++hh)
for (int c = 0; c < 4; ++c) qs[hh * kFdKv + 4 * cg + c] = acc[hh][c];
}
b.sync();
if (rh == 0) {
for (int hh = 0; hh < kFdHG; ++hh) {
const size_t th = static_cast<size_t>(t) * H + hg * kFdHG + hh;
f4 o;
o.x() = acc[hh][0] + qs[hh * kFdKv + 4 * cg];
o.y() = acc[hh][1] + qs[hh * kFdKv + 4 * cg + 1];
o.z() = acc[hh][2] + qs[hh * kFdKv + 4 * cg + 2];
o.w() = acc[hh][3] + qs[hh * kFdKv + 4 * cg + 3];
*reinterpret_cast<f4*>(part + (th * ns + sp) * kFdKv + 4 * cg) = o;
}
}
if (lane == 0) {
const size_t th = static_cast<size_t>(t) * H + hg * kFdHG + w;
ml[(th * ns + sp) * 2] = m;
ml[(th * ns + sp) * 2 + 1] = l;
}
});
}
void fd_stage2(const float* part, const float* ml, const int* d_pos0, float* ctx, int N, int H, int ns, cudaStream_t s) {
sy::launch(s, N * H * 4, 128, 2 * kFdMaxSplits * sizeof(float), [=](sy::Blk b, char* smemp) {
float* sm = reinterpret_cast<float*>(smemp);
const int tid = b.tid(), q4 = b.bid() & 3, th = b.bid() >> 2, t = th / H;
const int L = *d_pos0 + t + 1, cs = fd_chunk(L, ns), nact = (L + cs - 1) / cs;
for (int i = tid; i < nact * 2; i += 128) sm[i] = ml[static_cast<size_t>(th) * ns * 2 + i];
b.sync();
float gm = -FLT_MAX;
for (int i = 0; i < nact; ++i) gm = sycl::fmax(gm, sm[2 * i]);
float tot = 0.0f, o = 0.0f;
const int col = q4 * 128 + tid;
for (int i = 0; i < nact; ++i) {
const float wgt = sycl::exp(sm[2 * i] - gm);
tot += wgt * sm[2 * i + 1];
o += wgt * part[(static_cast<size_t>(th) * ns + i) * kFdKv + col];
}
ctx[static_cast<size_t>(th) * kFdKv + col] = o / tot;
});
}
} // namespace
// the dispatcher behind the engine's mla_attn (declared in ling32_kernels.hpp): the original per-head kernel is mla_attn_orig in ling32_sy_k_mla.cpp
void mla_attn_orig(const float* qabs, const float* q, const void* cache, const int* d_pos0, float* ctx, int N, int H, int nope, int rope, int kv_lora, float scale, bool cache_f32_b, cudaStream_t s);
bool mla_attn_fd_supported(int N, int H, int rope, int kv_lora, bool cache_f32);
void mla_attn_fd(const float* qabs, const float* q, const void* cache, const int* d_pos0, float* ctx, int N, int H, int nope, int rope, int kv_lora, float scale, cudaStream_t s, int stages);
void mla_attn(const float* qabs, const float* q, const void* cache, const int* d_pos0, float* ctx, int N, int H, int nope, int rope, int kv_lora, float scale, bool cache_f32_b, cudaStream_t s) {
// the context length is on the device (d_pos0), so the choice is by geometry only; at a short context the flash kernel costs about the same as the original (slices beyond L return at once)
static const bool force_orig = std::getenv("LING32_SY_MLA_ORIG") != nullptr; // A/B switch
if (!force_orig && mla_attn_fd_supported(N, H, rope, kv_lora, cache_f32_b)) mla_attn_fd(qabs, q, cache, d_pos0, ctx, N, H, nope, rope, kv_lora, scale, s, 3);
else mla_attn_orig(qabs, q, cache, d_pos0, ctx, N, H, nope, rope, kv_lora, scale, cache_f32_b, s);
}
// true when the flash-decoding kernel can serve this call (geometry and cache format); the caller falls back to mla_attn_orig otherwise
bool mla_attn_fd_supported(int N, int H, int rope, int kv_lora, bool cache_f32) { return cache_f32 && N >= 1 && N <= kFdMaxN && kv_lora == kFdKv && rope == kFdW - kFdKv && H % kFdHG == 0; }
void mla_attn_fd(const float* qabs, const float* q, const void* cache, const int* d_pos0, float* ctx, int N, int H, int nope, int rope, int kv_lora, float scale, cudaStream_t s, int stages) {
if (!mla_attn_fd_supported(N, H, rope, kv_lora, true)) {
std::fprintf(stderr, "ling32 (SYCL): mla_attn_fd called with an unsupported geometry\n");
std::abort();
}
const FdScratch& sc = fd_scratch(H);
static const int rb_env = std::getenv("LING32_SY_MLA_FD_RB") ? std::atoi(std::getenv("LING32_SY_MLA_FD_RB")) : 1; // tuning switches: rows per QK batch (1, 2)
static const int ns_env = std::getenv("LING32_SY_MLA_FD_NS") ? std::min(kFdMaxSplits, std::max(1, std::atoi(std::getenv("LING32_SY_MLA_FD_NS")))) : kFdSplitsDef; // slices
const int ns = ns_env;
static const int pvu_env = std::getenv("LING32_SY_MLA_FD_PVU") ? std::atoi(std::getenv("LING32_SY_MLA_FD_PVU")) : 1; // and PV rows in flight (1, 2, 4)
if (stages & 1) {
const float* cf = static_cast<const float*>(cache);
#define L32_FD_S1(RB_, PVU_) fd_stage1<RB_, PVU_>(qabs, q, cf, d_pos0, sc.part, sc.ml, N, H, nope, rope, scale, ns, s)
if (rb_env == 1) { if (pvu_env == 4) L32_FD_S1(1, 4); else if (pvu_env == 2) L32_FD_S1(1, 2); else L32_FD_S1(1, 1); }
else { if (pvu_env == 4) L32_FD_S1(2, 4); else if (pvu_env == 2) L32_FD_S1(2, 2); else L32_FD_S1(2, 1); }
#undef L32_FD_S1
}
if (stages & 2) fd_stage2(sc.part, sc.ml, d_pos0, ctx, N, H, ns, s);
}
} // namespace strata::ling32::gpu
+478
View File
@@ -0,0 +1,478 @@
// src/ling32/sycl/ling32_sy_k_moe.cpp - the routed-expert and SwiGLU kernels of ling32_layers.cu / ling32_moe_tc.cu on SYCL: moe_gu / moe_act / moe_dn (S2..S8 slabs, Q8 or float activations),
// swiglu, gemv2_swiglu_s8, moe_combine(_norm), the grouped-by-expert batch path (moe_tc_*, scalar for now: same rows and the same summation order as moe_gu / moe_dn with float activations).
// One warp = one weight row, 16 weights per lane-step, xor-butterfly sum: the arithmetic of the CUDA kernels. The fused single-token expert kernel is not ported (moe_experts_fused_ok = false).
#include "ling32_sy.hpp"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
namespace strata::ling32::gpu {
int moe_is_xe2(cudaStream_t s); // ling32_sy_k_moe_xmx.cpp: a Battlemage / PVC / Lunar Lake class device
namespace {
inline float siluf(float x) { return x / (1.0f + sycl::exp(-x)); }
// post_silu: min(silu(g), lim) * clamp(u, -lim, lim) (upstream BailingMoeV3MLP); else silu(min(g, lim)) * clamp(u). lim <= 0: no clamp.
inline float swiglu1(float g, float u, float lim, int post_silu) {
if (lim > 0.0f) {
const float gg = post_silu ? sycl::fmin(siluf(g), lim) : siluf(sycl::fmin(g, lim));
return gg * sycl::fmax(-lim, sycl::fmin(u, lim));
}
return siluf(g) * u;
}
// ---- float-activation row dots for the decode path: the arithmetic of sy::row_dot<CODE, 1, false> (same lane ownership, same fma chain: bit for bit the same results), with the memory traffic
// reorganised: 16-bit loads of exactly the words a lane needs (header word, the word with its scale byte, 1 .. 4 payload words) and the activations as two float4 per superblock, loaded once for R
// consecutive weight rows of the same slab (the activation row is re-read by every row of the matrix otherwise: 6 times the bytes of the weights). A SIMD32 work-item has room for about 32 live
// values, so more than one superblock in flight spills (measured on the A750: 2 superblocks 1.6x slower, 4 superblocks 3.5x slower).
template <int CODE, int R>
inline void rowdot_f_fast(const uint8_t* rowp, size_t row_bytes, int nr, int nsb, const float* act, int lane, float acc[R]) {
constexpr int SBB = sy::Sk<CODE>::kBytes;
const int g = lane >> 3, idx0 = lane * 8;
auto rd16 = [](const uint8_t* p) -> uint32_t { return *reinterpret_cast<const uint16_t*>(p); };
for (int r = 0; r < R; ++r) acc[r] = 0.0f;
for (int sb = 0; sb < nsb; ++sb) {
const sycl::float4* xp = reinterpret_cast<const sycl::float4*>(act + static_cast<size_t>(sb) * 256 + idx0);
const sycl::float4 xa = xp[0], xb = xp[1];
uint32_t hd[R], hs[R], raw0[R], raw1[R];
#pragma unroll
for (int r = 0; r < R; ++r) {
const uint8_t* blk = rowp + static_cast<size_t>(r < nr ? r : 0) * row_bytes + static_cast<size_t>(sb) * SBB;
const uint8_t* pl = blk + 6;
hd[r] = rd16(blk);
hs[r] = rd16(blk + ((2 + g) & ~1));
raw0[r] = raw1[r] = 0;
if (CODE == 8) {
raw0[r] = rd16(pl + idx0) | (rd16(pl + idx0 + 2) << 16);
raw1[r] = rd16(pl + idx0 + 4) | (rd16(pl + idx0 + 6) << 16);
} else if (CODE == 2 || CODE == 3) {
raw0[r] = rd16(pl + 2 * lane);
if (CODE == 3) raw1[r] = rd16(pl + ((64 + lane) & ~1));
} else {
raw0[r] = rd16(pl + 4 * lane) | (rd16(pl + 4 * lane + 2) << 16);
if (CODE == 5) raw1[r] = rd16(pl + ((128 + lane) & ~1));
else if (CODE == 6) raw1[r] = rd16(pl + 128 + 2 * lane);
}
}
const float xv[8] = {xa.x(), xa.y(), xa.z(), xa.w(), xb.x(), xb.y(), xb.z(), xb.w()};
#pragma unroll
for (int r = 0; r < R; ++r) {
const float D = sy::h2f(static_cast<uint16_t>(hd[r] & 0xFFFFu));
const float eff = D * (static_cast<float>((hs[r] >> (8 * (g & 1))) & 0xFFu) / 255.0f);
float s = 0.0f;
if (CODE == 8) {
for (int j = 0; j < 8; ++j) s += static_cast<float>(static_cast<int8_t>(((j < 4 ? raw0[r] : raw1[r]) >> (8 * (j & 3))) & 0xFFu)) * xv[j];
} else if (CODE == 2 || CODE == 3) {
const uint32_t hb = CODE == 3 ? ((raw1[r] >> (8 * (lane & 1))) & 0xFFu) : 0u;
for (int j = 0; j < 8; ++j) {
uint32_t v = (raw0[r] >> (2 * j)) & 3u;
if (CODE == 3) v |= ((hb >> j) & 1u) << 2;
s += (static_cast<float>(v) - sy::Sk<CODE>::kHalf) * xv[j];
}
} else {
const uint32_t hb = CODE == 5 ? ((raw1[r] >> (8 * (lane & 1))) & 0xFFu) : 0u;
for (int j = 0; j < 8; ++j) {
uint32_t v = (raw0[r] >> (4 * j)) & 15u;
if (CODE == 5) v |= ((hb >> j) & 1u) << 4;
else if (CODE == 6) v |= ((raw1[r] >> (2 * j)) & 3u) << 4;
s += (static_cast<float>(v) - sy::Sk<CODE>::kHalf) * xv[j];
}
}
acc[r] += eff * s;
}
}
}
// R rows of one slab matrix against one float activation row; acc[r] = the lane partial sums (not yet reduced)
template <int R>
inline void rowdot_fast_rows(int code, const uint8_t* rowp, size_t row_bytes, int nr, int K, const float* act, int lane, float acc[R]) {
switch (code) {
case 2: rowdot_f_fast<2, R>(rowp, row_bytes, nr, K >> 8, act, lane, acc); break;
case 3: rowdot_f_fast<3, R>(rowp, row_bytes, nr, K >> 8, act, lane, acc); break;
case 4: rowdot_f_fast<4, R>(rowp, row_bytes, nr, K >> 8, act, lane, acc); break;
case 5: rowdot_f_fast<5, R>(rowp, row_bytes, nr, K >> 8, act, lane, acc); break;
case 6: rowdot_f_fast<6, R>(rowp, row_bytes, nr, K >> 8, act, lane, acc); break;
default: rowdot_f_fast<8, R>(rowp, row_bytes, nr, K >> 8, act, lane, acc); break;
}
}
// one weight row of an S_K slab against ONE activation (a Q8Blk row or a float row): the 32 lane partial sums are NOT yet reduced
template <bool Q8>
inline float rowdot_code(int code, const uint8_t* rowp, int K, const void* act, int lane) {
float a[1] = {0.0f};
switch (code) {
case 2: sy::row_dot<2, 1, Q8>(rowp, K >> 8, act, K, 1, 0, lane, a); break;
case 3: sy::row_dot<3, 1, Q8>(rowp, K >> 8, act, K, 1, 0, lane, a); break;
case 4: sy::row_dot<4, 1, Q8>(rowp, K >> 8, act, K, 1, 0, lane, a); break;
case 5: sy::row_dot<5, 1, Q8>(rowp, K >> 8, act, K, 1, 0, lane, a); break;
case 6: sy::row_dot<6, 1, Q8>(rowp, K >> 8, act, K, 1, 0, lane, a); break;
default: sy::row_dot<8, 1, Q8>(rowp, K >> 8, act, K, 1, 0, lane, a); break;
}
return a[0];
}
// the float-activation decode path: R consecutive weight rows per warp share one read of the activation row (STRATA_L32_MOE_DEC = 1 / 2 / 4 rows per warp, 0 = launch_moe_gemv below)
template <bool DN, int R>
void launch_moe_gemv_f(const uint8_t* sec4, const ExpertDesc* desc, int layer_base, const int* idx, int P, int top_k, int rows, int K, const float* act, float* out,
const uint8_t* const* slab_ptrs, cudaStream_t s, bool old8) {
const int gx = (rows + 4 * R - 1) / (4 * R);
sy::launch(s, gx * P, 128, 0, [=](sy::Blk b, char*) {
const int bx = b.bid() % gx, p = b.bid() / gx;
const int row0 = (bx * 4 + b.warp()) * R;
if (row0 >= rows) return; // uniform over the warp
const int lane = b.lane();
const int token = p / top_k;
const int e = layer_base + idx[p];
const ExpertDesc d = desc[e];
const uint8_t* slab = slab_ptrs ? slab_ptrs[e] : sec4 + d.off;
if (!slab) return; // a null entry of the table: this expert belongs to another pass of the layer (tiering)
const int code = DN ? d.dn_code : d.gu_code;
const size_t row_bytes = static_cast<size_t>(K >> 8) * sy::sk_sb_bytes(code);
const uint8_t* rowp = slab + (DN ? d.dn_off : rows) /* S_xd: I fp16 = 2I bytes = rows bytes (rows = 2I) */ + static_cast<size_t>(row0) * row_bytes;
const float* a = act + static_cast<size_t>(DN ? p : token) * K;
const int nr = rows - row0 < R ? rows - row0 : R;
float acc[R];
if (old8 && code == 8) { // S8 on the Xe2 devices: the generic row dot is faster (B70: 0.070 vs 0.089 ms)
#pragma unroll
for (int r = 0; r < R; ++r) acc[r] = r < nr ? rowdot_code<false>(8, rowp + static_cast<size_t>(r) * row_bytes, K, a, lane) : 0.0f;
} else {
rowdot_fast_rows<R>(code, rowp, row_bytes, nr, K, a, lane, acc);
}
#pragma unroll
for (int r = 0; r < R; ++r) {
const float v = sy::warp_sum_xor(b, acc[r]);
if (lane == 0 && r < nr) out[static_cast<size_t>(p) * rows + row0 + r] = v;
}
});
}
// pair p = token * top_k + slot; DN = false: gu[p][r] = W_gu(row r) . act[token] (rows 2I, K = D); DN = true: ye[p][r] = W_dn(row r) . act2[p] (rows D, K = I)
template <bool DN, bool Q8>
void launch_moe_gemv(const uint8_t* sec4, const ExpertDesc* desc, int layer_base, const int* idx, int P, int top_k, int rows, int K, const void* act, float* out, const uint8_t* const* slab_ptrs,
cudaStream_t s) {
const int gx = (rows + 3) / 4;
sy::launch(s, gx * P, 128, 0, [=](sy::Blk b, char*) {
const int bx = b.bid() % gx, p = b.bid() / gx;
const int row = bx * 4 + b.warp();
if (row >= rows) return; // uniform over the warp
const int lane = b.lane();
const int token = p / top_k;
const int e = layer_base + idx[p];
const ExpertDesc d = desc[e];
const uint8_t* slab = slab_ptrs ? slab_ptrs[e] : sec4 + d.off;
if (!slab) return; // a null entry of the table: this expert belongs to another pass of the layer (tiering)
const int code = DN ? d.dn_code : d.gu_code;
const uint8_t* rowp = slab + (DN ? d.dn_off : rows) /* S_xd: I fp16 = 2I bytes = rows bytes (rows = 2I) */ + static_cast<size_t>(row) * (K >> 8) * sy::sk_sb_bytes(code);
const size_t a_off = static_cast<size_t>(DN ? p : token);
const void* a = Q8 ? static_cast<const void*>(static_cast<const Q8Blk*>(act) + a_off * (K >> 6)) : static_cast<const void*>(static_cast<const float*>(act) + a_off * K);
const float acc = sy::warp_sum_xor(b, rowdot_code<Q8>(code, rowp, K, a, lane));
if (lane == 0) out[static_cast<size_t>(p) * rows + row] = acc;
});
}
// float activations (the decode default). Rows per warp that share one read of the activation row, by device (measured): Xe2 / Battlemage-class (B70): 2 for one token, 4 for several (N >= 2), and the
// generic row dot for S8 slabs (0.070 vs 0.089 ms at N = 1); other devices (Alchemist, 8-wide XMX, 32-wide work-items spill registers with more rows in flight): 1 row per warp.
// STRATA_L32_MOE_DEC overrides: 0 the generic row dot, 1 / 2 / 4 rows per warp (S8 with the new row dot).
template <bool DN>
void launch_moe_gemv_float(const uint8_t* sec4, const ExpertDesc* desc, int layer_base, const int* idx, int P, int top_k, int rows, int K, const float* act, float* out,
const uint8_t* const* slab_ptrs, cudaStream_t s) {
static const int env = std::getenv("STRATA_L32_MOE_DEC") ? std::atoi(std::getenv("STRATA_L32_MOE_DEC")) : -1;
const bool xe2 = moe_is_xe2(s) != 0;
const int mode = env >= 0 ? env : (xe2 ? (P <= top_k ? 2 : 4) : 1);
const bool old8 = env < 0 && xe2;
if (mode >= 4) launch_moe_gemv_f<DN, 4>(sec4, desc, layer_base, idx, P, top_k, rows, K, act, out, slab_ptrs, s, old8);
else if (mode >= 2) launch_moe_gemv_f<DN, 2>(sec4, desc, layer_base, idx, P, top_k, rows, K, act, out, slab_ptrs, s, old8);
else if (mode == 1) launch_moe_gemv_f<DN, 1>(sec4, desc, layer_base, idx, P, top_k, rows, K, act, out, slab_ptrs, s, old8);
else launch_moe_gemv<DN, false>(sec4, desc, layer_base, idx, P, top_k, rows, K, act, out, slab_ptrs, s);
}
// pair p: a = swiglu(gu[p]) / S_xd[e] -> FWHT-128 -> Q8_1 (or float). one block per pair, one warp per 128 features
template <bool Q8>
void launch_moe_act(const uint8_t* sec4, const ExpertDesc* desc, int layer_base, const int* idx, const float* gu, int P, int I, float lim, int post_silu, void* out,
const uint8_t* const* slab_ptrs, cudaStream_t s) {
sy::launch(s, P, (I / 128) * 32, 0, [=](sy::Blk b, char*) {
const int p = b.bid(), lane = b.lane(), w = b.warp();
const int e = layer_base + idx[p];
const uint8_t* slab = slab_ptrs ? slab_ptrs[e] : sec4 + desc[e].off;
if (!slab) return; // another pass of the layer (tiering); uniform over the block
const float* g = gu + static_cast<size_t>(p) * 2 * I;
float v[4];
for (int i = 0; i < 4; ++i) {
const int f = w * 128 + lane * 4 + i;
const float sxd = sy::h2f(static_cast<uint16_t>(slab[2 * f] | (slab[2 * f + 1] << 8)));
v[i] = swiglu1(g[f], g[I + f], lim, post_silu) / sxd;
}
sy::fwht128_warp(b, v);
if (Q8) {
sy::q8_store_warp(b, v, static_cast<Q8Blk*>(out) + (static_cast<size_t>(p) * (I / 64) + w * 2));
} else {
float* o = static_cast<float*>(out) + static_cast<size_t>(p) * I + w * 128 + lane * 4;
o[0] = v[0]; o[1] = v[1]; o[2] = v[2]; o[3] = v[3];
}
});
}
// out[t][r] = swiglu(W_gate[r] . x[t], W_up[r] . x[t]): one pass over both S8_K matrices, float activations
template <int NT>
void launch_gemv2_swiglu(const uint8_t* Wg, const uint8_t* Wu, int rows, int K, const float* act, int N, float lim, int post_silu, float* out, int out_stride, cudaStream_t s) {
const int gx = (rows + 3) / 4, gy = (N + NT - 1) / NT;
sy::launch(s, gx * gy, 128, 0, [=](sy::Blk b, char*) {
const int bx = b.bid() % gx, by = b.bid() / gx;
const int row = bx * 4 + b.warp();
if (row >= rows) return;
const int lane = b.lane(), t0 = by * NT, nsb = K >> 8;
float ag[NT], au[NT];
#pragma unroll
for (int t = 0; t < NT; ++t) ag[t] = au[t] = 0.0f;
sy::row_dot<8, NT, false>(Wg + static_cast<size_t>(row) * nsb * 262, nsb, act, K, N, t0, lane, ag);
sy::row_dot<8, NT, false>(Wu + static_cast<size_t>(row) * nsb * 262, nsb, act, K, N, t0, lane, au);
#pragma unroll
for (int t = 0; t < NT; ++t) {
#pragma unroll
for (int off = 16; off >= 1; off >>= 1) {
ag[t] += b.shfl_xor(ag[t], off);
au[t] += b.shfl_xor(au[t], off);
}
}
if (lane == 0) {
#pragma unroll
for (int t = 0; t < NT; ++t)
if (t0 + t < N) out[static_cast<size_t>(t0 + t) * out_stride + row] = swiglu1(ag[t], au[t], lim, post_silu);
}
});
}
// ---------------------------------------------------------------------------------------------- grouped by expert (batches)
constexpr int kTn = 16; // pairs per tile
// one weight row against up to kTn pairs of ONE expert, float activations, gathered through pairs[]: the summation order of row_dot (so the results equal moe_gu / moe_dn)
template <int CODE, bool DN>
inline void gather_dot(const uint8_t* rowp, int nsb, const float* x, int K, const int* pairs, int nt, int top_k, int lane, float acc[kTn]) {
const int g = lane >> 3, in_g = (lane & 7) * 8, idx0 = g * 64 + in_g;
size_t xoff[kTn];
for (int t = 0; t < kTn; ++t) xoff[t] = t < nt ? static_cast<size_t>(DN ? pairs[t] : pairs[t] / top_k) * K : 0;
for (int sb = 0; sb < nsb; ++sb) {
const uint8_t* blk = rowp + static_cast<size_t>(sb) * sy::Sk<CODE>::kBytes;
const float Dh = sy::h2f(static_cast<uint16_t>(blk[0] | (blk[1] << 8)));
const float eff = Dh * (static_cast<float>(blk[2 + g]) / 255.0f);
uint32_t w[2];
sy::load_w8<CODE>(blk + 6, idx0, w);
for (int t = 0; t < kTn; ++t) {
if (t >= nt) break;
const float* xp = x + xoff[t] + sb * 256 + idx0;
float sum = 0.0f;
for (int j = 0; j < 8; ++j) {
const uint32_t word = w[j >> 2];
const uint32_t byte = (word >> (8 * (j & 3))) & 0xFFu;
const float q = (CODE == 8) ? static_cast<float>(static_cast<int8_t>(byte)) : static_cast<float>(byte) - sy::Sk<CODE>::kHalf;
sum += q * xp[j];
}
acc[t] += eff * sum;
}
}
}
template <bool DN>
void launch_moe_tc(const MoeTcWork& w, const uint8_t* sec4, const ExpertDesc* desc, int layer_base, const uint8_t* const* slab_ptrs, int P, int top_k, int rows, int K, const float* x, float* out,
cudaStream_t s) {
const int gx = (rows + 3) / 4;
const int ntile_bound = std::min(w.max_tiles, (P + kTn - 1) / kTn + std::min(w.n_exp, P));
const int* perm = w.perm;
const int *exp_start = w.exp_start, *exp_cnt = w.exp_cnt, *tile_e = w.tile_e, *tile_j = w.tile_j, *ntiles = w.ntiles;
sy::launch(s, gx * ntile_bound, 128, 0, [=](sy::Blk b, char*) {
const int bx = b.bid() % gx, t = b.bid() / gx;
if (t >= ntiles[0]) return;
const int e = tile_e[t], j = tile_j[t];
const ExpertDesc d = desc[layer_base + e];
const uint8_t* slab = slab_ptrs ? slab_ptrs[layer_base + e] : sec4 + d.off;
if (!slab) return;
const int row = bx * 4 + b.warp();
if (row >= rows) return;
const int first = exp_start[e] + j * kTn, nt = sycl::min(kTn, exp_cnt[e] - j * kTn);
const int code = DN ? d.dn_code : d.gu_code;
const uint8_t* rowp = slab + (DN ? d.dn_off : rows) + static_cast<size_t>(row) * (K >> 8) * sy::sk_sb_bytes(code);
const int lane = b.lane(), nsb = K >> 8;
float acc[kTn];
for (int i = 0; i < kTn; ++i) acc[i] = 0.0f;
const int* pairs = perm + first;
switch (code) {
case 2: gather_dot<2, DN>(rowp, nsb, x, K, pairs, nt, top_k, lane, acc); break;
case 3: gather_dot<3, DN>(rowp, nsb, x, K, pairs, nt, top_k, lane, acc); break;
case 4: gather_dot<4, DN>(rowp, nsb, x, K, pairs, nt, top_k, lane, acc); break;
case 5: gather_dot<5, DN>(rowp, nsb, x, K, pairs, nt, top_k, lane, acc); break;
case 6: gather_dot<6, DN>(rowp, nsb, x, K, pairs, nt, top_k, lane, acc); break;
default: gather_dot<8, DN>(rowp, nsb, x, K, pairs, nt, top_k, lane, acc); break;
}
for (int i = 0; i < kTn; ++i) {
for (int off = 16; off >= 1; off >>= 1) acc[i] += b.shfl_xor(acc[i], off);
}
if (lane == 0)
for (int i = 0; i < kTn; ++i)
if (i < nt) out[static_cast<size_t>(perm[first + i]) * rows + row] = acc[i];
});
}
} // namespace
// ================================================================================================ launchers
void swiglu(const float* g, int g_stride, const float* u, int u_stride, float lim, bool post_silu, float* out, int out_stride, int N, int I, cudaStream_t s) {
const int gx = (I + 255) / 256;
const int ps = post_silu ? 1 : 0;
sy::launch(s, gx * N, 256, 0, [=](sy::Blk b, char*) {
const int t = b.bid() / gx, i = (b.bid() % gx) * b.bdim() + b.tid();
if (i < I) out[static_cast<size_t>(t) * out_stride + i] = swiglu1(g[static_cast<size_t>(t) * g_stride + i], u[static_cast<size_t>(t) * u_stride + i], lim, ps);
});
}
void gemv2_swiglu_s8(const uint8_t* Wg, const uint8_t* Wu, int rows, int K, const float* act, int N, float lim, bool post_silu, float* out, int out_stride, cudaStream_t s) {
const int ps = post_silu ? 1 : 0;
if (N <= 1) launch_gemv2_swiglu<1>(Wg, Wu, rows, K, act, N, lim, ps, out, out_stride, s);
else if (N <= 4) launch_gemv2_swiglu<4>(Wg, Wu, rows, K, act, N, lim, ps, out, out_stride, s);
else launch_gemv2_swiglu<8>(Wg, Wu, rows, K, act, N, lim, ps, out, out_stride, s);
}
void moe_gu(const uint8_t* sec4, const ExpertDesc* desc, int layer_base, const int* idx, int N, int top_k, int E, int D, int I, const void* act, bool act_q8, float* gu, cudaStream_t s,
const uint8_t* const* slab_ptrs) {
(void)E;
if (act_q8) launch_moe_gemv<false, true>(sec4, desc, layer_base, idx, N * top_k, top_k, 2 * I, D, act, gu, slab_ptrs, s);
else launch_moe_gemv_float<false>(sec4, desc, layer_base, idx, N * top_k, top_k, 2 * I, D, static_cast<const float*>(act), gu, slab_ptrs, s);
}
void moe_act(const uint8_t* sec4, const ExpertDesc* desc, int layer_base, const int* idx, const float* gu, int N, int top_k, int I, float lim, bool post_silu, void* out, bool out_q8,
cudaStream_t s, const uint8_t* const* slab_ptrs) {
if (out_q8) launch_moe_act<true>(sec4, desc, layer_base, idx, gu, N * top_k, I, lim, post_silu ? 1 : 0, out, slab_ptrs, s);
else launch_moe_act<false>(sec4, desc, layer_base, idx, gu, N * top_k, I, lim, post_silu ? 1 : 0, out, slab_ptrs, s);
}
void moe_dn(const uint8_t* sec4, const ExpertDesc* desc, int layer_base, const int* idx, int N, int top_k, int E, int D, int I, const void* act, bool act_q8, float* ye, cudaStream_t s,
const uint8_t* const* slab_ptrs) {
(void)E;
if (act_q8) launch_moe_gemv<true, true>(sec4, desc, layer_base, idx, N * top_k, top_k, D, I, act, ye, slab_ptrs, s);
else launch_moe_gemv_float<true>(sec4, desc, layer_base, idx, N * top_k, top_k, D, I, static_cast<const float*>(act), ye, slab_ptrs, s);
}
// x[t] = (x[t] + ysh[t]) + sum_k w[t][k] * ye[t * top_k + k]
void moe_combine(float* x, const float* ye, const float* w, int N, int top_k, int D, cudaStream_t s, const float* ysh) {
sy::launch(s, N, 256, 0, [=](sy::Blk b, char*) {
const int t = b.bid();
for (int d = b.tid(); d < D; d += b.bdim()) {
float sum = 0.0f;
for (int k = 0; k < top_k; ++k) sum += w[t * top_k + k] * ye[(static_cast<size_t>(t) * top_k + k) * D + d];
const size_t at = static_cast<size_t>(t) * D + d;
x[at] = (ysh ? x[at] + ysh[at] : x[at]) + sum; // (x + shared) + routed, the order of the two accumulating GEMVs
}
});
}
// moe_combine + the NEXT layer's input rmsnorm in one kernel (the code of rmsnorm: 256 threads, same reduction order); D <= 4096
void moe_combine_norm(float* x, const float* ye, const float* w, int N, int top_k, int D, cudaStream_t s, const float* ysh, const float* gamma, float eps, float* hout) {
sy::launch(s, N, 256, 32 * sizeof(float), [=](sy::Blk b, char* smem) {
float* part = reinterpret_cast<float*>(smem);
const int t = b.bid();
float xv[16];
float ss = 0.0f;
int n = 0;
for (int d = b.tid(); d < D; d += 256, ++n) {
float sum = 0.0f;
for (int k = 0; k < top_k; ++k) sum += w[t * top_k + k] * ye[(static_cast<size_t>(t) * top_k + k) * D + d];
const size_t at = static_cast<size_t>(t) * D + d;
const float v = (ysh ? x[at] + ysh[at] : x[at]) + sum;
x[at] = v;
xv[n] = v;
ss += v * v;
}
for (int off = 16; off >= 1; off >>= 1) ss += b.shfl_xor(ss, off);
if (b.lane() == 0) part[b.warp()] = ss;
b.sync();
if (b.tid() < 32) {
float v = b.tid() < (b.bdim() >> 5) ? part[b.tid()] : 0.0f;
for (int off = 16; off >= 1; off >>= 1) v += b.shfl_xor(v, off);
if (b.tid() == 0) part[0] = v;
}
b.sync();
const float r = 1.0f / sycl::sqrt(part[0] / static_cast<float>(D) + eps);
n = 0;
for (int d = b.tid(); d < D; d += 256, ++n) hout[static_cast<size_t>(t) * D + d] = xv[n] * r * gamma[d];
});
}
// ---- grouped by expert (moe_tc_*): the XMX kernels of ling32_sy_k_moe_xmx.cpp where the device has them, else the scalar kernel above
bool moe_xmx_try(bool dn, const MoeTcWork& w, const uint8_t* sec4, const ExpertDesc* desc, int layer_base, const uint8_t* const* slab_ptrs, int P, int top_k, int rows, int K, const float* x, float* out, cudaStream_t s);
int moe_xmx_tile(int P, int n_exp, cudaStream_t s);
bool moe_tc_alloc(MoeTcWork& w, int max_pairs, int n_exp) {
w.max_tiles = (max_pairs + kTn - 1) / kTn + n_exp;
w.n_exp = n_exp;
return cudaMalloc(reinterpret_cast<void**>(&w.perm), size_t(max_pairs) * 4) == cudaSuccess && cudaMalloc(reinterpret_cast<void**>(&w.tile_e), size_t(w.max_tiles) * 4) == cudaSuccess &&
cudaMalloc(reinterpret_cast<void**>(&w.tile_j), size_t(w.max_tiles) * 4) == cudaSuccess && cudaMalloc(reinterpret_cast<void**>(&w.exp_start), size_t(n_exp) * 4) == cudaSuccess &&
cudaMalloc(reinterpret_cast<void**>(&w.exp_cnt), size_t(n_exp) * 4) == cudaSuccess && cudaMalloc(reinterpret_cast<void**>(&w.ntiles), 4) == cudaSuccess;
}
void moe_tc_free(MoeTcWork& w) {
for (int* p : {w.perm, w.tile_e, w.tile_j, w.exp_start, w.exp_cnt, w.ntiles})
if (p) cudaFree(p);
w = MoeTcWork{};
}
void set_moe_max_code(int code) { (void)code; } // sizes the shared memory of the CUDA tensor-core tiles; nothing to size here
// grouping of the P = tokens * top_k pairs by expert: perm (pairs sorted by expert), exp_start / exp_cnt, and the tile list (tiles of up to kTn pairs of one expert)
void moe_tc_route(const MoeTcWork& w, const int* idx, int P, cudaStream_t s) {
const int n_exp = w.n_exp;
const int kTn = moe_xmx_tile(P, n_exp, s); // tiles of 16 pairs, or of 32 for the XMX kernel (shadows the scalar kernel's constant: that kernel only runs with 16)
int *perm = w.perm, *exp_start = w.exp_start, *exp_cnt = w.exp_cnt, *tile_e = w.tile_e, *tile_j = w.tile_j, *ntiles = w.ntiles;
sy::launch(s, 1, 256, size_t(4) * n_exp * sizeof(int), [=](sy::Blk b, char* smem) {
int* cnt = reinterpret_cast<int*>(smem);
int* start = cnt + n_exp;
int* tstart = start + n_exp;
int* fill = tstart + n_exp;
const int t = b.tid(), nt = b.bdim();
for (int e = t; e < n_exp; e += nt) { cnt[e] = 0; fill[e] = 0; }
b.sync();
for (int p = t; p < P; p += nt) {
const int e = idx[p];
if (e >= 0 && e < n_exp) sycl::atomic_ref<int, sycl::memory_order::relaxed, sycl::memory_scope::work_group>(cnt[e]).fetch_add(1);
}
b.sync();
if (t == 0) {
int a = 0, bb = 0;
for (int e = 0; e < n_exp; ++e) {
start[e] = a;
tstart[e] = bb;
a += cnt[e];
bb += (cnt[e] + kTn - 1) / kTn;
}
ntiles[0] = bb;
}
b.sync();
for (int e = t; e < n_exp; e += nt) {
exp_start[e] = start[e];
exp_cnt[e] = cnt[e];
const int ntl = (cnt[e] + kTn - 1) / kTn;
for (int j = 0; j < ntl; ++j) { tile_e[tstart[e] + j] = e; tile_j[tstart[e] + j] = j; }
}
for (int p = t; p < P; p += nt) {
const int e = idx[p];
if (e >= 0 && e < n_exp) perm[start[e] + sycl::atomic_ref<int, sycl::memory_order::relaxed, sycl::memory_scope::work_group>(fill[e]).fetch_add(1)] = p;
}
});
}
void moe_tc_gu(const MoeTcWork& w, const uint8_t* sec4, const ExpertDesc* desc, int layer_base, const uint8_t* const* slab_ptrs, int P, int top_k, int D, int I, const float* x, float* gu, cudaStream_t s, bool /*low_codes: AMD launch choice, no meaning here*/) {
if (moe_xmx_try(false, w, sec4, desc, layer_base, slab_ptrs, P, top_k, 2 * I, D, x, gu, s)) return;
launch_moe_tc<false>(w, sec4, desc, layer_base, slab_ptrs, P, top_k, 2 * I, D, x, gu, s);
}
void moe_tc_dn(const MoeTcWork& w, const uint8_t* sec4, const ExpertDesc* desc, int layer_base, const uint8_t* const* slab_ptrs, int P, int top_k, int D, int I, const float* act, float* ye, cudaStream_t s, bool /*low_codes*/) {
if (moe_xmx_try(true, w, sec4, desc, layer_base, slab_ptrs, P, top_k, D, I, act, ye, s)) return;
launch_moe_tc<true>(w, sec4, desc, layer_base, slab_ptrs, P, top_k, D, I, act, ye, s);
}
// ---- the fused single-token expert kernel is not ported: the engine asks moe_experts_fused_ok first
bool moe_experts_fused_ok(int, int, int) { return false; }
void moe_experts_fused(const uint8_t*, const ExpertDesc*, int, const int*, int, int, int, const float*, float, bool, float*, float*, int*, const uint8_t* const*, cudaStream_t) {
std::fprintf(stderr, "ling32 (SYCL): moe_experts_fused is not available (moe_experts_fused_ok is false)\n");
std::abort();
}
} // namespace strata::ling32::gpu
@@ -0,0 +1,575 @@
// src/ling32/sycl/ling32_sy_k_moe_xmx.cpp - the grouped-by-expert routed-expert GEMMs (moe_tc_gu / moe_tc_dn) on the XMX engines of Intel GPUs (joint_matrix, fp16 operands, fp32 accumulation).
//
// Same arithmetic idea as the CUDA kernels of ling32_moe_tc.cu (exact weights, hi + lo activations, group scale on the fp32 sums):
// * a tile is up to 16 (token, expert) pairs of ONE expert against 128 weight rows per work-group; the work-group walks the K dimension superblock by superblock;
// * the weights of each 64-group of a superblock are decoded (16-bit loads) to fp16 integers (q - kHalf for S2..S6, int8
// for S8: exact) in the VNNI-2 packed layout of the B operand (exact);
// * the activations of the group are scaled per pair by a power of two that brings the group maximum to [2^10, 2^11), split into fp16 hi + lo (so x = (hi + lo) * 2^-e to ~22 bits) and stored row-major as the A operand;
// * per group a fresh fp32 accumulator gets sum_k q[row][k] * (hi + lo)[pair][k] from 2 x 4 DPAS steps (K = 16 each) and is merged into the fp32 running total with the factor eff[row] * 2^-e[pair].
// Shapes: Battlemage (and PVC / Lunar Lake / Panther Lake) run joint_matrix with 16-wide sub-groups, A 8x16, B 16x16, C 8x16; Alchemist (acm_g10 / g11 / g12) with 8-wide sub-groups, B 16x8, C 8x8.
// The joint_matrix code exists only in the device passes of those targets (the __SYCL_TARGET_INTEL_GPU_*__ macros, like the owner's ink_sy_intelarc_xmx.h); in every other pass (spir64 JIT) the same
// kernel runs a plain fp32 loop over the same shared-memory tiles, so results do not depend on the device, only the speed does. moe_xmx_try() tells the caller whether it ran.
// Never an 8-wide sub-group in a pass for a Battlemage target (IGC ICE on bmg_g31): the 8-wide kernel declares 16 there and is never launched on such a device.
//
// Layout assumption of the merge: a work-item of an 8 x N accumulator holds one column (N index = its lane) and the 8 rows as its elements (element i = row i); here rows are the pairs and the
// columns the weight rows, so lane = weight row and element i = pair (i, or 8 + i for the second accumulator). ling32_moe_sy_test checks it against the per-pair kernels.
#include "ling32_sy.hpp"
#if __has_include(<sycl/ext/intel/experimental/grf_size_properties.hpp>)
#include <sycl/ext/intel/experimental/grf_size_properties.hpp>
#endif
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#if __has_include(<sycl/ext/oneapi/matrix/matrix.hpp>)
#include <sycl/ext/oneapi/matrix/matrix.hpp>
#define L32_HAVE_JM 1
#else
#define L32_HAVE_JM 0
#endif
#if L32_HAVE_JM && defined(__SYCL_DEVICE_ONLY__)
#if (defined(__SYCL_TARGET_INTEL_GPU_BMG_G21__) && __SYCL_TARGET_INTEL_GPU_BMG_G21__ == 1) || (defined(__SYCL_TARGET_INTEL_GPU_BMG_G31__) && __SYCL_TARGET_INTEL_GPU_BMG_G31__ == 1) || \
(defined(__SYCL_TARGET_INTEL_GPU_LNL_M__) && __SYCL_TARGET_INTEL_GPU_LNL_M__ == 1) || (defined(__SYCL_TARGET_INTEL_GPU_PTL_H__) && __SYCL_TARGET_INTEL_GPU_PTL_H__ == 1) || \
(defined(__SYCL_TARGET_INTEL_GPU_PTL_U__) && __SYCL_TARGET_INTEL_GPU_PTL_U__ == 1) || (defined(__SYCL_TARGET_INTEL_GPU_PVC__) && __SYCL_TARGET_INTEL_GPU_PVC__ == 1)
#define L32_PASS_JM16 1
#endif
#if (defined(__SYCL_TARGET_INTEL_GPU_ACM_G10__) && __SYCL_TARGET_INTEL_GPU_ACM_G10__ == 1) || (defined(__SYCL_TARGET_INTEL_GPU_ACM_G11__) && __SYCL_TARGET_INTEL_GPU_ACM_G11__ == 1) || \
(defined(__SYCL_TARGET_INTEL_GPU_ACM_G12__) && __SYCL_TARGET_INTEL_GPU_ACM_G12__ == 1)
#define L32_PASS_JM8 1
#endif
#endif
#ifndef L32_PASS_JM16
#define L32_PASS_JM16 0
#endif
#ifndef L32_PASS_JM8
#define L32_PASS_JM8 0
#endif
// the sub-group size of the 8-wide kernel: 8 everywhere except in a pass for a 16-wide target (where the kernel is dead code and must not ask for 8)
#if L32_PASS_JM16
#define L32_SG8_SIZE 16
#else
#define L32_SG8_SIZE 8
#endif
namespace strata::ling32::gpu {
namespace {
constexpr int kTnMax = 32; // pairs per tile, at most (the tile list of moe_tc_route: 16 or 32, see xmx_plan)
constexpr int kBmr = 128; // weight rows per work-group
constexpr int kWg = 128; // work-group size
constexpr int kLdb = kBmr * 2 + 8; // halves between VNNI rows of the B tile (a multiple of 8, not of 32 banks)
constexpr int kXld = 72; // halves per activation row of the A tiles
// shared memory of one work-group, carved from one char array
struct Smem {
uint16_t* sB; // [32][kLdb] halves: VNNI-2 packed weights of the group, element (k, row) at (k >> 1) * kLdb + row * 2 + (k & 1)
uint16_t* sXh; // [32][kXld] halves
uint16_t* sXl; // [32][kXld]
float* sC; // [nsg][TN][JN] floats, aliases sB (used after the last group)
float* sIsc; // [32]
float* sEff; // [kBmr]
int* sPairs; // [32]
static constexpr size_t bytes(int tn) {
return size_t(32) * kLdb * 2 + size_t(2) * tn * kXld * 2 + kTnMax * 4 + kBmr * 4 + kTnMax * 4 + 64;
}
explicit Smem(char* p, int tn) {
sB = reinterpret_cast<uint16_t*>(p); p += size_t(32) * kLdb * 2;
sXh = reinterpret_cast<uint16_t*>(p); p += size_t(tn) * kXld * 2;
sXl = reinterpret_cast<uint16_t*>(p); p += size_t(tn) * kXld * 2;
sC = reinterpret_cast<float*>(sB); // the result tiles reuse the weight tile after the last group
sIsc = reinterpret_cast<float*>(p); p += kTnMax * 4;
sEff = reinterpret_cast<float*>(p); p += kBmr * 4;
sPairs = reinterpret_cast<int*>(p);
}
};
// 8 weights idx0 .. idx0 + 7 (idx0 % 8 == 0) of a superblock payload (pl even-aligned: 16-bit loads from global memory, the rows stay in cache) as 4 packed fp16 pairs holding q - kHalf (S2..S6) or the
// int8 q (S8), exact in fp16. Two weights per step in the two 16-bit lanes of a word: the integer field is placed in the mantissa of a half that has a fixed exponent (512 + q for the half-integer codes: the
// mantissa step is 0.5 there, so the field 2q gives 512 + q; 1024 + 128 + q for S8: the field q ^ 0x80 = q + 128) and one packed half subtraction of the constant (512 + kHalf, 1152) leaves the weight.
// the 16-bit words of the payload that the 8 weights idx0 .. idx0 + 7 need (pl even-aligned, 16-bit global loads): S8 4 words of q, S2 the word of 2-bit fields, S3 that + the word holding the
// high-bit byte, S4 two words of nibbles, S5 / S6 two words of nibbles + the word with the high bits. All the loads of a thread are issued before any of them is used.
template <int CODE>
inline void load_raw(const uint8_t* pl, int idx0, uint32_t r[4]) {
auto rd16 = [&](int off) -> uint32_t { return *reinterpret_cast<const uint16_t*>(pl + off); };
r[0] = r[1] = r[2] = r[3] = 0;
if (CODE == 8) {
for (int i = 0; i < 4; ++i) r[i] = rd16(idx0 + 2 * i);
} else if (CODE == 2 || CODE == 3) {
r[0] = rd16(idx0 >> 2);
if (CODE == 3) r[1] = rd16((64 + (idx0 >> 3)) & ~1);
} else {
r[0] = rd16(idx0 >> 1);
r[1] = rd16((idx0 >> 1) + 2);
if (CODE == 5) r[2] = rd16((128 + (idx0 >> 3)) & ~1);
else if (CODE == 6) r[2] = rd16(128 + (idx0 >> 2));
}
}
template <int CODE>
inline void decode_raw(const uint32_t r[4], int idx0, uint32_t out[4]) {
using h2 = sycl::vec<sycl::half, 2>;
constexpr float kBase = CODE == 8 ? 1152.0f : 512.0f + sy::Sk<CODE>::kHalf;
const h2 cst(static_cast<sycl::half>(kBase), static_cast<sycl::half>(kBase));
auto fin = [&](uint32_t w) -> uint32_t { // w: two integer fields (lo lane, hi lane at bit 16)
const uint32_t u = CODE == 8 ? ((w ^ 0x00800080u) | 0x64006400u) : ((w << 1) | 0x60006000u);
const h2 r = sycl::bit_cast<h2>(u) - cst;
return sycl::bit_cast<uint32_t>(r);
};
if (CODE == 8) {
for (int i = 0; i < 4; ++i) {
const uint32_t v = r[i];
out[i] = fin((v & 0xFFu) | ((v & 0xFF00u) << 8));
}
} else if (CODE == 2 || CODE == 3) {
const uint32_t v = r[0];
const uint32_t hb = CODE == 3 ? ((r[1] >> (8 * ((idx0 >> 3) & 1))) & 0xFFu) : 0u;
for (int i = 0; i < 4; ++i) {
const uint32_t t = v >> (4 * i);
uint32_t w = (t & 3u) | ((t & 0xCu) << 14);
if (CODE == 3) {
const uint32_t t2 = hb >> (2 * i);
w |= ((t2 & 1u) << 2) | ((t2 & 2u) << 17);
}
out[i] = fin(w);
}
} else {
const uint32_t va = r[0], vb = r[1];
const uint32_t hb = CODE == 5 ? ((r[2] >> (8 * ((idx0 >> 3) & 1))) & 0xFFu) : 0u;
const uint32_t hh = CODE == 6 ? r[2] : 0u;
for (int i = 0; i < 4; ++i) {
const uint32_t t = (i < 2 ? va : vb) >> (8 * (i & 1));
uint32_t w = (t & 0xFu) | ((t & 0xF0u) << 12);
if (CODE == 5) {
const uint32_t t2 = hb >> (2 * i);
w |= ((t2 & 1u) << 4) | ((t2 & 2u) << 19);
} else if (CODE == 6) {
const uint32_t t2 = hh >> (4 * i);
w |= ((t2 & 3u) << 4) | ((t2 & 0xCu) << 18);
}
out[i] = fin(w);
}
}
}
inline uint32_t pack2(uint16_t lo, uint16_t hi) { return static_cast<uint32_t>(lo) | (static_cast<uint32_t>(hi) << 16); }
// phase A of one 64-group: weights of the 128 rows into sB, per-row scale into sEff, the activations of the TN pairs split into sXh / sXl and the pair scales into sIsc.
// One thread per weight row (kWg == kBmr): the 8 chunks of 8 weights of its 64-group are decoded CB at a time (all loads of a batch first), and consecutive threads store consecutive words of a
// VNNI row of sB, so the shared-memory stores do not conflict (with 8 threads per row, 4 of a sub-group hit the same banks).
template <int CODE, bool DN, int TN, int CB>
inline void phase_a(const sy::Blk& b, Smem& sm, const uint8_t* wbase, int rows, int nsb, int row0, int sb, int g, int dbg, const float* x, int K, int nt, int top_k) {
static_assert(kWg == kBmr, "one thread per weight row");
constexpr int SBB = sy::Sk<CODE>::kBytes;
const int tid = b.tid();
const int r = tid;
const int grow = row0 + r < rows ? row0 + r : row0;
const uint8_t* rowg = wbase + (static_cast<size_t>(grow) * nsb + sb) * SBB;
if (!(dbg & 1)) {
uint32_t* sB32 = reinterpret_cast<uint32_t*>(sm.sB);
#pragma unroll
for (int c0 = 0; c0 < 8; c0 += CB) {
uint32_t raw[CB][4];
#pragma unroll
for (int c = 0; c < CB; ++c) load_raw<CODE>(rowg + 6, g * 64 + (c0 + c) * 8, raw[c]);
#pragma unroll
for (int c = 0; c < CB; ++c) {
uint32_t wq[4];
decode_raw<CODE>(raw[c], g * 64 + (c0 + c) * 8, wq);
#pragma unroll
for (int j = 0; j < 4; ++j) sB32[((c0 + c) * 4 + j) * (kLdb / 2) + r] = wq[j];
}
}
}
{
const float Dh = sy::h2f(static_cast<uint16_t>(*reinterpret_cast<const uint16_t*>(rowg)));
sm.sEff[r] = (row0 + r < rows) ? Dh * (static_cast<float>(rowg[2 + g]) / 255.0f) : 0.0f;
}
if (!(dbg & 2)) {
const int kk8 = (tid & 7) * 8;
for (int qq = 0; qq < TN / 16; ++qq) { // 16 pairs per pass of the 128 threads: 8 threads (8 values each) per pair
const int pr = (tid >> 3) + 16 * qq;
const bool x_ok = pr < nt;
const size_t xrow = static_cast<size_t>(DN ? sm.sPairs[pr] : sm.sPairs[pr] / top_k);
float v[8];
const float* xp = x + xrow * K + (sb * 4 + g) * 64 + kk8;
float am = 0.0f;
for (int i = 0; i < 8; ++i) {
v[i] = x_ok ? xp[i] : 0.0f;
am = sycl::fmax(am, sycl::fabs(v[i]));
}
for (int m = 4; m >= 1; m >>= 1) am = sycl::fmax(am, b.shfl_xor(am, m));
int e = static_cast<int>((sycl::bit_cast<uint32_t>(am) >> 23) & 255u) - 127;
e = sycl::max(e, -100);
const float sc = sycl::bit_cast<float>(static_cast<uint32_t>(127 + 10 - e) << 23);
const float isc = sycl::bit_cast<float>(static_cast<uint32_t>(127 + e - 10) << 23);
if ((tid & 7) == 0) sm.sIsc[pr] = isc;
uint16_t hi[8], lo[8];
for (int i = 0; i < 8; ++i) {
const float s = v[i] * sc;
hi[i] = sy::f2h(s);
lo[i] = sy::f2h(s - sy::h2f(hi[i]));
}
uint32_t* xh32 = reinterpret_cast<uint32_t*>(sm.sXh) + (pr * kXld + kk8) / 2;
uint32_t* xl32 = reinterpret_cast<uint32_t*>(sm.sXl) + (pr * kXld + kk8) / 2;
for (int i = 0; i < 4; ++i) {
xh32[i] = pack2(hi[2 * i], hi[2 * i + 1]);
xl32[i] = pack2(lo[2 * i], lo[2 * i + 1]);
}
}
}
}
// the body of one tile (TN = 16 or 32 pairs) for one weight code
template <int CODE, bool DN, int JN, int TN, int CB>
inline void tile_body(const sy::Blk& b, Smem& sm, const uint8_t* wbase, int rows, int K, const float* x, float* out, const int* pairs, int nt, int top_k, int row0, int dbg, int ostride, bool accum, int tok0) {
constexpr bool kJm = (JN == 16 && L32_PASS_JM16) || (JN == 8 && L32_PASS_JM8);
const int tid = b.tid(), nsb = K >> 8;
const int sgi = tid / JN, lane = tid % JN;
if (tid < TN) sm.sPairs[tid] = tid < nt ? (pairs ? pairs[tid] : tok0 + tid) : 0; // pairs == nullptr: the trunk GEMM, token tok0 + m
b.sync();
const int rbase = sgi * JN;
float* sCs = sm.sC + sgi * TN * JN;
if constexpr (kJm) {
namespace jm = sycl::ext::oneapi::experimental::matrix;
auto sg = b.it.get_sub_group();
auto pB = sycl::address_space_cast<sycl::access::address_space::local_space, sycl::access::decorated::no>(reinterpret_cast<sycl::half*>(sm.sB));
auto pH = sycl::address_space_cast<sycl::access::address_space::local_space, sycl::access::decorated::no>(reinterpret_cast<sycl::half*>(sm.sXh));
auto pL = sycl::address_space_cast<sycl::access::address_space::local_space, sycl::access::decorated::no>(reinterpret_cast<sycl::half*>(sm.sXl));
auto pC = sycl::address_space_cast<sycl::access::address_space::local_space, sycl::access::decorated::no>(sCs);
// joint_matrix variables stay flat in one scope per variant (IGC), 8 pairs (one M = 8 tile) each
if constexpr (TN == 16) {
jm::joint_matrix<sycl::sub_group, float, jm::use::accumulator, 8, JN> t0, t1, c0, c1;
jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::a, 8, 16, jm::layout::row_major> a0, a1;
jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::b, 16, JN, jm::layout::ext_intel_packed> bm;
jm::joint_matrix_fill(sg, t0, 0.0f);
jm::joint_matrix_fill(sg, t1, 0.0f);
for (int sb = 0; sb < nsb; ++sb) {
for (int g = 0; g < 4; ++g) {
phase_a<CODE, DN, TN, CB>(b, sm, wbase, rows, nsb, row0, sb, g, dbg, x, K, nt, top_k);
b.sync();
jm::joint_matrix_fill(sg, c0, 0.0f);
jm::joint_matrix_fill(sg, c1, 0.0f);
if (!(dbg & 4)) {
for (int ks = 0; ks < 4; ++ks) {
jm::joint_matrix_load(sg, bm, pB + ks * 8 * kLdb + rbase * 2, kLdb);
jm::joint_matrix_load(sg, a0, pH + ks * 16, kXld);
jm::joint_matrix_load(sg, a1, pH + 8 * kXld + ks * 16, kXld);
jm::joint_matrix_mad(sg, c0, a0, bm, c0);
jm::joint_matrix_mad(sg, c1, a1, bm, c1);
jm::joint_matrix_load(sg, a0, pL + ks * 16, kXld);
jm::joint_matrix_load(sg, a1, pL + 8 * kXld + ks * 16, kXld);
jm::joint_matrix_mad(sg, c0, a0, bm, c0);
jm::joint_matrix_mad(sg, c1, a1, bm, c1);
}
}
const float eff = sm.sEff[rbase + lane];
int ia = 0;
jm::joint_matrix_apply(sg, t0, c0, [&](float& t, float& c) { t += (eff * sm.sIsc[ia]) * c; ++ia; });
ia = 8;
jm::joint_matrix_apply(sg, t1, c1, [&](float& t, float& c) { t += (eff * sm.sIsc[ia]) * c; ++ia; });
b.sync();
}
}
jm::joint_matrix_store(sg, t0, pC, JN, jm::layout::row_major);
jm::joint_matrix_store(sg, t1, pC + 8 * JN, JN, jm::layout::row_major);
} else {
jm::joint_matrix<sycl::sub_group, float, jm::use::accumulator, 8, JN> t0, t1, t2, t3, c0, c1, c2, c3;
jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::a, 8, 16, jm::layout::row_major> a0, a1, a2, a3;
jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::b, 16, JN, jm::layout::ext_intel_packed> bm;
jm::joint_matrix_fill(sg, t0, 0.0f);
jm::joint_matrix_fill(sg, t1, 0.0f);
jm::joint_matrix_fill(sg, t2, 0.0f);
jm::joint_matrix_fill(sg, t3, 0.0f);
for (int sb = 0; sb < nsb; ++sb) {
for (int g = 0; g < 4; ++g) {
phase_a<CODE, DN, TN, CB>(b, sm, wbase, rows, nsb, row0, sb, g, dbg, x, K, nt, top_k);
b.sync();
jm::joint_matrix_fill(sg, c0, 0.0f);
jm::joint_matrix_fill(sg, c1, 0.0f);
jm::joint_matrix_fill(sg, c2, 0.0f);
jm::joint_matrix_fill(sg, c3, 0.0f);
if (!(dbg & 4)) {
for (int ks = 0; ks < 4; ++ks) {
jm::joint_matrix_load(sg, bm, pB + ks * 8 * kLdb + rbase * 2, kLdb);
jm::joint_matrix_load(sg, a0, pH + ks * 16, kXld);
jm::joint_matrix_load(sg, a1, pH + 8 * kXld + ks * 16, kXld);
jm::joint_matrix_load(sg, a2, pH + 16 * kXld + ks * 16, kXld);
jm::joint_matrix_load(sg, a3, pH + 24 * kXld + ks * 16, kXld);
jm::joint_matrix_mad(sg, c0, a0, bm, c0);
jm::joint_matrix_mad(sg, c1, a1, bm, c1);
jm::joint_matrix_mad(sg, c2, a2, bm, c2);
jm::joint_matrix_mad(sg, c3, a3, bm, c3);
jm::joint_matrix_load(sg, a0, pL + ks * 16, kXld);
jm::joint_matrix_load(sg, a1, pL + 8 * kXld + ks * 16, kXld);
jm::joint_matrix_load(sg, a2, pL + 16 * kXld + ks * 16, kXld);
jm::joint_matrix_load(sg, a3, pL + 24 * kXld + ks * 16, kXld);
jm::joint_matrix_mad(sg, c0, a0, bm, c0);
jm::joint_matrix_mad(sg, c1, a1, bm, c1);
jm::joint_matrix_mad(sg, c2, a2, bm, c2);
jm::joint_matrix_mad(sg, c3, a3, bm, c3);
}
}
const float eff = sm.sEff[rbase + lane];
int ia = 0;
jm::joint_matrix_apply(sg, t0, c0, [&](float& t, float& c) { t += (eff * sm.sIsc[ia]) * c; ++ia; });
ia = 8;
jm::joint_matrix_apply(sg, t1, c1, [&](float& t, float& c) { t += (eff * sm.sIsc[ia]) * c; ++ia; });
ia = 16;
jm::joint_matrix_apply(sg, t2, c2, [&](float& t, float& c) { t += (eff * sm.sIsc[ia]) * c; ++ia; });
ia = 24;
jm::joint_matrix_apply(sg, t3, c3, [&](float& t, float& c) { t += (eff * sm.sIsc[ia]) * c; ++ia; });
b.sync();
}
}
jm::joint_matrix_store(sg, t0, pC, JN, jm::layout::row_major);
jm::joint_matrix_store(sg, t1, pC + 8 * JN, JN, jm::layout::row_major);
jm::joint_matrix_store(sg, t2, pC + 16 * JN, JN, jm::layout::row_major);
jm::joint_matrix_store(sg, t3, pC + 24 * JN, JN, jm::layout::row_major);
}
sycl::group_barrier(sg);
const int row = row0 + rbase + lane;
if (row < rows)
for (int m = 0; m < TN; ++m)
if (m < nt) { float* o = out + static_cast<size_t>(sm.sPairs[m]) * ostride + row; *o = accum ? *o + sCs[m * JN + lane] : sCs[m * JN + lane]; }
} else {
float tot[TN];
for (int m = 0; m < TN; ++m) tot[m] = 0.0f;
for (int sb = 0; sb < nsb; ++sb) {
for (int g = 0; g < 4; ++g) {
phase_a<CODE, DN, TN, CB>(b, sm, wbase, rows, nsb, row0, sb, g, dbg, x, K, nt, top_k);
b.sync();
float cg[TN];
for (int m = 0; m < TN; ++m) cg[m] = 0.0f;
for (int k = 0; k < 64; ++k) {
const float w = sy::h2f(sm.sB[(k >> 1) * kLdb + (rbase + lane) * 2 + (k & 1)]);
for (int m = 0; m < TN; ++m) cg[m] += w * sy::h2f(sm.sXh[m * kXld + k]) + w * sy::h2f(sm.sXl[m * kXld + k]);
}
const float eff = sm.sEff[rbase + lane];
for (int m = 0; m < TN; ++m) tot[m] += (eff * sm.sIsc[m]) * cg[m];
b.sync();
}
}
const int row = row0 + rbase + lane;
if (row < rows)
for (int m = 0; m < TN; ++m)
if (m < nt) { float* o = out + static_cast<size_t>(sm.sPairs[m]) * ostride + row; *o = accum ? *o + tot[m] : tot[m]; }
}
(void)sCs;
}
template <bool DN, int JN, int TN, int CB>
void launch_xmx(const MoeTcWork& w, const uint8_t* sec4, const ExpertDesc* desc, int layer_base, const uint8_t* const* slab_ptrs, int P, int top_k, int rows, int K, const float* x, float* out,
cudaStream_t s) {
const int gx = (rows + kBmr - 1) / kBmr;
const int ntile_bound = std::min(w.max_tiles, (P + TN - 1) / TN + std::min(w.n_exp, P));
const int* perm = w.perm;
const int *exp_start = w.exp_start, *exp_cnt = w.exp_cnt, *tile_e = w.tile_e, *tile_j = w.tile_j, *ntiles = w.ntiles;
auto& q = strata::sy::queue_of(s);
const size_t smem = Smem::bytes(TN);
static const int dbg_env = std::getenv("L32MOE_XDBG") ? std::atoi(std::getenv("L32MOE_XDBG")) : 0; // timing experiments: 1 no weight decode, 2 no activation split, 4 no DPAS
const int dbg = dbg_env;
q.submit([&](sycl::handler& h) {
sycl::local_accessor<char, 1> lm(sycl::range<1>(smem), h);
auto body = [=](sycl::nd_item<1> it) {
const sy::Blk b{it};
const int bx = b.bid() % gx, t = b.bid() / gx;
if (t >= ntiles[0]) return;
const int e = tile_e[t], j = tile_j[t];
const ExpertDesc d = desc[layer_base + e];
const uint8_t* slab = slab_ptrs ? slab_ptrs[layer_base + e] : sec4 + d.off;
if (!slab) return;
const int first = exp_start[e] + j * TN, nt = sycl::min(TN, exp_cnt[e] - j * TN);
const int code = DN ? d.dn_code : d.gu_code;
const uint8_t* wbase = slab + (DN ? d.dn_off : rows);
Smem sm(lm.get_multi_ptr<sycl::access::decorated::no>().get(), TN);
const int row0 = bx * kBmr;
switch (code) {
case 2: tile_body<2, DN, JN, TN, CB>(b, sm, wbase, rows, K, x, out, perm + first, nt, top_k, row0, dbg, rows, false, 0); break;
case 3: tile_body<3, DN, JN, TN, CB>(b, sm, wbase, rows, K, x, out, perm + first, nt, top_k, row0, dbg, rows, false, 0); break;
case 4: tile_body<4, DN, JN, TN, CB>(b, sm, wbase, rows, K, x, out, perm + first, nt, top_k, row0, dbg, rows, false, 0); break;
case 5: tile_body<5, DN, JN, TN, CB>(b, sm, wbase, rows, K, x, out, perm + first, nt, top_k, row0, dbg, rows, false, 0); break;
case 6: tile_body<6, DN, JN, TN, CB>(b, sm, wbase, rows, K, x, out, perm + first, nt, top_k, row0, dbg, rows, false, 0); break;
default: tile_body<8, DN, JN, TN, 8>(b, sm, wbase, rows, K, x, out, perm + first, nt, top_k, row0, dbg, rows, false, 0); break;
}
};
if constexpr (JN == 16) {
static const bool grf256 = !std::getenv("STRATA_L32_MOE_GRF") || std::atoi(std::getenv("STRATA_L32_MOE_GRF")) != 0; // per-kernel large register file (256 GRFs): B70 S5 16 pairs 2.34 -> 1.40 ms; =0 off (A/B)
if (grf256)
h.parallel_for(sycl::nd_range<1>(static_cast<size_t>(gx) * ntile_bound * kWg, kWg), sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<256>},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(16)]] { body(it); });
else
h.parallel_for(sycl::nd_range<1>(static_cast<size_t>(gx) * ntile_bound * kWg, kWg), [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(16)]] { body(it); });
} else {
h.parallel_for(sycl::nd_range<1>(static_cast<size_t>(gx) * ntile_bound * kWg, kWg), [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(L32_SG8_SIZE)]] { body(it); });
}
});
}
// the trunk GEMM: out[t][r] (+)= W[r] . x[t] for one S_K matrix [rows, K] and N float token rows, tiles of TN tokens x 128 weight rows (the grouped expert kernel with the pair list replaced by the token range)
template <int JN, int TN, int CB>
void launch_trunk(const uint8_t* W, int code, int rows, int K, const float* x, int N, float* out, int out_stride, bool accum, cudaStream_t s) {
const int gx = (rows + kBmr - 1) / kBmr;
const int ntt = (N + TN - 1) / TN;
auto& q = strata::sy::queue_of(s);
const size_t smem = Smem::bytes(TN);
q.submit([&](sycl::handler& h) {
sycl::local_accessor<char, 1> lm(sycl::range<1>(smem), h);
auto body = [=](sycl::nd_item<1> it) {
const sy::Blk b{it};
const int bx = b.bid() % gx, t = b.bid() / gx;
const int first = t * TN, nt = sycl::min(TN, N - first);
Smem sm(lm.get_multi_ptr<sycl::access::decorated::no>().get(), TN);
const int row0 = bx * kBmr;
switch (code) {
case 2: tile_body<2, true, JN, TN, CB>(b, sm, W, rows, K, x, out, nullptr, nt, 1, row0, 0, out_stride, accum, first); break;
case 3: tile_body<3, true, JN, TN, CB>(b, sm, W, rows, K, x, out, nullptr, nt, 1, row0, 0, out_stride, accum, first); break;
case 4: tile_body<4, true, JN, TN, CB>(b, sm, W, rows, K, x, out, nullptr, nt, 1, row0, 0, out_stride, accum, first); break;
case 5: tile_body<5, true, JN, TN, CB>(b, sm, W, rows, K, x, out, nullptr, nt, 1, row0, 0, out_stride, accum, first); break;
case 6: tile_body<6, true, JN, TN, CB>(b, sm, W, rows, K, x, out, nullptr, nt, 1, row0, 0, out_stride, accum, first); break;
default: tile_body<8, true, JN, TN, 8>(b, sm, W, rows, K, x, out, nullptr, nt, 1, row0, 0, out_stride, accum, first); break;
}
};
const size_t total = static_cast<size_t>(gx) * ntt * kWg;
if constexpr (JN == 16) {
static const bool grf256 = !std::getenv("STRATA_L32_MOE_GRF") || std::atoi(std::getenv("STRATA_L32_MOE_GRF")) != 0;
if (grf256)
h.parallel_for(sycl::nd_range<1>(total, kWg), sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<256>},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(16)]] { body(it); });
else
h.parallel_for(sycl::nd_range<1>(total, kWg), [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(16)]] { body(it); });
} else {
h.parallel_for(sycl::nd_range<1>(total, kWg), [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(L32_SG8_SIZE)]] { body(it); });
}
});
}
// which joint_matrix sub-group width the device has: 16 (Battlemage and later, PVC), 8 (Alchemist), 0 (none)
int xmx_width(cudaStream_t s) {
static int cache[64];
static bool done[64];
int dev = 0;
cudaGetDevice(&dev);
dev &= 63;
if (done[dev]) return cache[dev];
int w = 0;
if (const char* e = std::getenv("STRATA_L32_MOE_XMX")) { // 0: off, 8 / 16: force a width (tests)
const int v = std::atoi(e);
w = (v == 8 || v == 16) ? v : 0;
} else {
#if L32_HAVE_JM
namespace exp = sycl::ext::oneapi::experimental;
const auto arch = strata::sy::queue_of(s).get_device().get_info<exp::info::device::architecture>();
switch (arch) {
case exp::architecture::intel_gpu_bmg_g21:
case exp::architecture::intel_gpu_bmg_g31:
case exp::architecture::intel_gpu_pvc:
case exp::architecture::intel_gpu_lnl_m:
w = 16;
break;
default: w = 0; break; // Alchemist: only on request (STRATA_L32_MOE_XMX=8) until the build carries its AOT image
}
#endif
}
done[dev] = true;
cache[dev] = w;
return w;
}
// pairs per tile for a batch of P pairs over n_exp experts: 0 = the scalar kernel (no XMX on the device, or too few pairs per expert for the decode of the weights to pay: measured on the B70, 4 pairs per
// expert are no faster than the scalar kernel), else 16 or 32 (32 from 24 pairs per expert: the decode of a weight tile is shared by more pairs). The tile list of moe_tc_route uses the same answer.
// STRATA_L32_MOE_XMX_MIN (pairs per expert, default 6; an explicit STRATA_L32_MOE_XMX switches the minimum off) and STRATA_L32_MOE_TN (16 / 32) override.
int xmx_plan(int P, int n_exp, cudaStream_t s) {
if (xmx_width(s) == 0) return 0;
static const int force_tn = std::getenv("STRATA_L32_MOE_TN") ? std::atoi(std::getenv("STRATA_L32_MOE_TN")) : 0;
static const int min_avg = std::getenv("STRATA_L32_MOE_XMX_MIN") ? std::atoi(std::getenv("STRATA_L32_MOE_XMX_MIN")) : (std::getenv("STRATA_L32_MOE_XMX") ? 0 : 6);
const int avg = P / std::max(1, n_exp);
if (avg < min_avg) return 0;
if (force_tn == 16 || force_tn == 32) return force_tn;
return avg >= 24 ? 32 : 16;
}
} // namespace
// a Battlemage / PVC / Lunar Lake class device (what the decode kernels of ling32_sy_k_moe.cpp tune for); independent of STRATA_L32_MOE_XMX
int moe_is_xe2(cudaStream_t s) {
#if L32_HAVE_JM
static int cache[64];
static bool done[64];
int dev = 0;
cudaGetDevice(&dev);
dev &= 63;
if (!done[dev]) {
namespace exp = sycl::ext::oneapi::experimental;
const auto arch = strata::sy::queue_of(s).get_device().get_info<exp::info::device::architecture>();
cache[dev] = (arch == exp::architecture::intel_gpu_bmg_g21 || arch == exp::architecture::intel_gpu_bmg_g31 || arch == exp::architecture::intel_gpu_pvc || arch == exp::architecture::intel_gpu_lnl_m) ? 1 : 0;
done[dev] = true;
}
return cache[dev];
#else
(void)s;
return 0;
#endif
}
// the tile width of moe_tc_route's tile list (16 unless the XMX kernel takes 32-pair tiles)
int moe_xmx_tile(int P, int n_exp, cudaStream_t s) {
const int tn = xmx_plan(P, n_exp, s);
return tn ? tn : 16;
}
// defined here, called by moe_tc_gu / moe_tc_dn of ling32_sy_k_moe.cpp: true when the XMX kernel ran
bool moe_xmx_try(bool dn, const MoeTcWork& w, const uint8_t* sec4, const ExpertDesc* desc, int layer_base, const uint8_t* const* slab_ptrs, int P, int top_k, int rows, int K, const float* x, float* out,
cudaStream_t s) {
if ((K & 255) != 0) return false; // cannot happen for S_K matrices; moe_tc_route tiles by moe_xmx_tile either way
const int tn = xmx_plan(P, w.n_exp, s);
if (tn == 0) return false;
const int width = xmx_width(s);
// chunks of 8 weights per thread whose loads are in flight together: 8 (all of a 64-group) or 4; STRATA_L32_MOE_XCH overrides (default: 4 on the 16-wide devices, whose registers are twice as
// costly per value, 8 on Alchemist)
static const int xch_env = std::getenv("STRATA_L32_MOE_XCH") ? std::atoi(std::getenv("STRATA_L32_MOE_XCH")) : 0;
const int cb = xch_env == 4 || xch_env == 8 ? xch_env : (width == 16 ? 4 : 8);
#define L32_LAUNCH(DNV, JNV, TNV, CBV) launch_xmx<DNV, JNV, TNV, CBV>(w, sec4, desc, layer_base, slab_ptrs, P, top_k, rows, K, x, out, s)
#define L32_PICK_CB(DNV, JNV, TNV) do { if (cb == 8) L32_LAUNCH(DNV, JNV, TNV, 8); else L32_LAUNCH(DNV, JNV, TNV, 4); } while (0)
if (width == 16) {
if (dn) { if (tn == 32) L32_PICK_CB(true, 16, 32); else L32_PICK_CB(true, 16, 16); }
else { if (tn == 32) L32_PICK_CB(false, 16, 32); else L32_PICK_CB(false, 16, 16); }
} else {
if (dn) { if (tn == 32) L32_PICK_CB(true, 8, 32); else L32_PICK_CB(true, 8, 16); }
else { if (tn == 32) L32_PICK_CB(false, 8, 32); else L32_PICK_CB(false, 8, 16); }
}
#undef L32_PICK_CB
#undef L32_LAUNCH
return true;
}
// the trunk projections of a prefill chunk on XMX (called by gemm_sk_tc of ling32_sy_k_trunk.cpp): true when the XMX kernel ran. N >= STRATA_L32_TRUNK_XMX_MIN tokens (default 32), tiles of 32 tokens
// from 24 tokens on (16 below); STRATA_L32_TRUNK_XMX=0 turns it off. Same device rule as the experts: Battlemage-class automatically, Alchemist with STRATA_L32_MOE_XMX=8.
bool trunk_xmx_try(const uint8_t* W, int code, int rows, int K, const float* x, int N, float* out, int out_stride, bool accumulate, cudaStream_t s) {
static const int off = std::getenv("STRATA_L32_TRUNK_XMX") ? std::atoi(std::getenv("STRATA_L32_TRUNK_XMX")) : 1;
static const int nmin = std::getenv("STRATA_L32_TRUNK_XMX_MIN") ? std::atoi(std::getenv("STRATA_L32_TRUNK_XMX_MIN")) : 32;
if (!off || (K & 255) != 0 || N < nmin || N < 1) return false;
const int width = xmx_width(s);
if (width == 0) return false;
static const int xch_env = std::getenv("STRATA_L32_MOE_XCH") ? std::atoi(std::getenv("STRATA_L32_MOE_XCH")) : 0;
const int cb = xch_env == 4 || xch_env == 8 ? xch_env : (width == 16 ? 4 : 8);
const bool big = N >= 24;
// work-groups of the launch: with fewer than STRATA_L32_TRUNK_XMX_TILES (default 128) the scalar GEMV wins (A750: [2560 x 4096] at N = 128 has 80 tiles and is 0.86x, [6144 x 2560] has 192 and is 1.6x)
static const int tmin = std::getenv("STRATA_L32_TRUNK_XMX_TILES") ? std::atoi(std::getenv("STRATA_L32_TRUNK_XMX_TILES")) : 128;
if (static_cast<long>((rows + kBmr - 1) / kBmr) * ((N + (big ? 32 : 16) - 1) / (big ? 32 : 16)) < tmin) return false;
#define L32_TR(JNV, TNV, CBV) launch_trunk<JNV, TNV, CBV>(W, code, rows, K, x, N, out, out_stride, accumulate, s)
if (width == 16) {
if (big) { if (cb == 8) L32_TR(16, 32, 8); else L32_TR(16, 32, 4); }
else { if (cb == 8) L32_TR(16, 16, 8); else L32_TR(16, 16, 4); }
} else {
if (big) { if (cb == 8) L32_TR(8, 32, 8); else L32_TR(8, 32, 4); }
else { if (cb == 8) L32_TR(8, 16, 8); else L32_TR(8, 16, 4); }
}
#undef L32_TR
return true;
}
} // namespace strata::ling32::gpu
@@ -0,0 +1,180 @@
// src/ling32/sycl/ling32_sy_k_router.cpp - the ALF-LB router on SYCL (ling32_layers.cu alflb_par_kernel / alflb_kernel). score = sigmoid(logit [+ add_bias]) + sel_bias; group score = sum of the top 2
// scores of its group; the top `topk_group` groups stay; the `top_n` best masked scores are returned best first (ties: the lower id first). The weights are the UNBIASED sigmoid of the chosen
// ones / (sum + 1e-20) * scale. Same arithmetic and tie-breaking as the CUDA kernels. router_fused (decode, N = 1, one launch with cross-block hand-over) is not ported yet: router_fused_ok = false.
#include "ling32_sy.hpp"
#include <cstdio>
#include <cstdlib>
namespace strata::ling32::gpu {
namespace {
constexpr float kFltMax = 3.402823466e+38f;
inline float sigmoidf(float x) { return 1.0f / (1.0f + sycl::exp(-x)); }
// the per-token scratch beyond the float arrays: group scores, kept groups, group list, chosen ids
struct RouteTail {
float* gscore; // [16]
int* gkeep; // [16]
int* glist; // [16]
int* chosen; // [64]
explicit RouteTail(char* p) : gscore(reinterpret_cast<float*>(p)), gkeep(reinterpret_cast<int*>(p + 64)), glist(reinterpret_cast<int*>(p + 128)), chosen(reinterpret_cast<int*>(p + 192)) {}
};
constexpr size_t kTailBytes = 192 + 64 * 4;
// group score m1 + m2 of a group (a warp per group): the two largest of its candidates, merged over the lanes by the xor butterfly
inline float group_top2_sum(const sy::Blk& b, const float* sc, int base, int per, int lane) {
float m1 = -kFltMax, m2 = -kFltMax;
for (int i = lane; i < per; i += 32) {
const float v = sc[base + i];
if (v > m1) { m2 = m1; m1 = v; } else if (v > m2) m2 = v;
}
for (int o = 16; o >= 1; o >>= 1) {
const float b1 = b.shfl_xor(m1, o), b2 = b.shfl_xor(m2, o);
const float n1 = sycl::fmax(m1, b1);
m2 = sycl::fmax(sycl::fmin(m1, b1), sycl::fmax(m2, b2));
m1 = n1;
}
return m1 + m2;
}
// one block of 256 threads per token: the group scores in parallel (a warp per group), the selected groups' experts compacted, the top-n by RANK (how many candidates beat an expert)
void launch_alflb_par(const float* logits, const float* add_bias, const float* sel_bias, int E, int n_group, int topk_group, int top_n, float scale, int do_w, int* out_idx, float* out_w, int N,
cudaStream_t s) {
const int ncand = topk_group * (E / n_group);
const size_t smem = (static_cast<size_t>(3) * E + ncand) * sizeof(float) + kTailBytes;
sy::launch(s, N, 256, smem, [=](sy::Blk b, char* mem) {
const int t = b.bid(), tid = b.tid(), lane = b.lane(), warp = b.warp(), nwarp = b.bdim() >> 5;
float* sig = reinterpret_cast<float*>(mem); // [E]
float* sc = sig + E; // [E]
float* scc = sig + 2 * E; // [ncand] scores of the candidates
int* eid = reinterpret_cast<int*>(sig + 3 * E); // [ncand] their expert ids
RouteTail tl(mem + (static_cast<size_t>(3) * E + ncand) * sizeof(float));
const float* lg = logits + static_cast<size_t>(t) * E;
for (int e = tid; e < E; e += b.bdim()) {
const float z = lg[e] + (add_bias ? add_bias[e] : 0.0f);
sig[e] = sigmoidf(z);
sc[e] = sig[e] + sel_bias[e];
}
b.sync();
const int per = E / n_group;
for (int g = warp; g < n_group; g += nwarp) {
const float gs = group_top2_sum(b, sc, g * per, per, lane);
if (lane == 0) tl.gscore[g] = gs;
}
b.sync();
if (tid == 0) {
for (int g = 0; g < n_group; ++g) tl.gkeep[g] = 0;
for (int k = 0; k < topk_group; ++k) {
int best = -1;
for (int g = 0; g < n_group; ++g)
if (!tl.gkeep[g] && (best < 0 || tl.gscore[g] > tl.gscore[best])) best = g;
tl.gkeep[best] = 1;
tl.glist[k] = best;
}
}
b.sync();
for (int c = tid; c < ncand; c += b.bdim()) {
const int e = tl.glist[c / per] * per + c % per;
eid[c] = e;
scc[c] = sc[e];
}
b.sync();
for (int c = tid; c < ncand; c += b.bdim()) {
const float v = scc[c];
const int e = eid[c];
int r = 0;
for (int f = 0; f < ncand; ++f) r += (scc[f] > v || (scc[f] == v && eid[f] < e)) ? 1 : 0;
if (r < top_n) tl.chosen[r] = e;
}
b.sync();
if (tid < top_n) out_idx[static_cast<size_t>(t) * top_n + tid] = tl.chosen[tid];
if (do_w && tid < top_n) {
float tot = 0.0f;
for (int i = 0; i < top_n; ++i) tot += sig[tl.chosen[i]];
out_w[static_cast<size_t>(t) * top_n + tid] = sig[tl.chosen[tid]] * (scale / (tot + 1e-20f));
}
});
}
// the reference form (any shape): one warp per token, top_n argmax rounds
void launch_alflb_ref(const float* logits, const float* add_bias, const float* sel_bias, int E, int n_group, int topk_group, int top_n, float scale, int do_w, int* out_idx, float* out_w, int N,
cudaStream_t s) {
const size_t smem = static_cast<size_t>(2) * E * sizeof(float) + E + kTailBytes + 8;
sy::launch(s, N, 32, smem, [=](sy::Blk b, char* mem) {
const int t = b.bid(), lane = b.lane();
float* sig = reinterpret_cast<float*>(mem);
float* sc = sig + E;
unsigned char* flag = reinterpret_cast<unsigned char*>(sig + 2 * E); // 1 = selectable, 2 = chosen
RouteTail tl(mem + static_cast<size_t>(2) * E * sizeof(float) + ((E + 7) & ~7));
const float* lg = logits + static_cast<size_t>(t) * E;
for (int e = lane; e < E; e += 32) {
const float z = lg[e] + (add_bias ? add_bias[e] : 0.0f);
sig[e] = sigmoidf(z);
sc[e] = sig[e] + sel_bias[e];
}
b.warp_sync();
const int per = E / n_group;
for (int g = 0; g < n_group; ++g) {
const float gs = group_top2_sum(b, sc, g * per, per, lane);
if (lane == 0) tl.gscore[g] = gs;
}
b.warp_sync();
if (lane == 0) {
for (int g = 0; g < n_group; ++g) tl.gkeep[g] = 0;
for (int k = 0; k < topk_group; ++k) {
int best = -1;
for (int g = 0; g < n_group; ++g)
if (!tl.gkeep[g] && (best < 0 || tl.gscore[g] > tl.gscore[best])) best = g;
tl.gkeep[best] = 1;
}
}
b.warp_sync();
for (int e = lane; e < E; e += 32) flag[e] = tl.gkeep[e / per] ? 1 : 0;
b.warp_sync();
for (int it = 0; it < top_n; ++it) {
float bv = -kFltMax;
int bi = 0x7FFFFFFF;
for (int e = lane; e < E; e += 32)
if (flag[e] == 1 && sc[e] > bv) { bv = sc[e]; bi = e; }
for (int o = 16; o >= 1; o >>= 1) {
const float ov = b.shfl_xor(bv, o);
const int oi = b.shfl_xor(bi, o);
if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
}
if (bi == 0x7FFFFFFF) bi = 0; // fewer selectable experts than top_n (cannot happen with the real shapes)
if (lane == 0) { tl.chosen[it] = bi; flag[bi] = 2; }
b.warp_sync();
}
if (lane < top_n) out_idx[static_cast<size_t>(t) * top_n + lane] = tl.chosen[lane];
if (lane + 32 < top_n) out_idx[static_cast<size_t>(t) * top_n + lane + 32] = tl.chosen[lane + 32];
if (do_w) {
float tot = 0.0f;
for (int i = 0; i < top_n; ++i) tot += sig[tl.chosen[i]];
const float k = scale / (tot + 1e-20f);
if (lane < top_n) out_w[static_cast<size_t>(t) * top_n + lane] = sig[tl.chosen[lane]] * k;
if (lane + 32 < top_n) out_w[static_cast<size_t>(t) * top_n + lane + 32] = sig[tl.chosen[lane + 32]] * k;
}
});
}
} // namespace
void alflb_route(const float* logits, const float* add_bias, const float* sel_bias, int E, int n_group, int topk_group, int top_n, float scale, bool weights, int* out_idx, float* out_w, int N,
cudaStream_t s) {
const int ncand = topk_group * (E / n_group);
if (E == 512 && n_group == 8 && top_n == 8 && topk_group >= 1 && topk_group <= 4 && ncand >= top_n && !g_alflb_ref) // the shape of Ling-3.2-Air
launch_alflb_par(logits, add_bias, sel_bias, E, n_group, topk_group, top_n, scale, weights ? 1 : 0, out_idx, out_w, N, s);
else
launch_alflb_ref(logits, add_bias, sel_bias, E, n_group, topk_group, top_n, scale, weights ? 1 : 0, out_idx, out_w, N, s);
}
// fused decode router: not ported (the engine checks router_fused_ok and falls back to rmsnorm + gemv_f32 + alflb_route)
bool router_fused_ok(int, int, int, int, int) { return false; }
void router_fused(const float*, const float*, float, float*, const float*, const float*, float*, unsigned int*, int, float, int*, float*, int, cudaStream_t) {
std::fprintf(stderr, "ling32 (SYCL): router_fused is not available (router_fused_ok is false)\n");
std::abort();
}
} // namespace strata::ling32::gpu
+333
View File
@@ -0,0 +1,333 @@
// src/ling32/sycl/ling32_sy_k_spec.cpp - the device-side steps of the speculative cycle on SYCL: top-K (radix select), accept / sample, first-token sampling, KDA rollback, position advance,
// diagnostics and the MTP drafting helpers. Port of the kernels of ling32_spec.cu (same arithmetic, same Philox stream, same tie rules).
#include "ling32_sy.hpp"
#include "../ling32_spec.hpp"
#include <cfloat>
#include <cstdio>
#include <cstdlib>
namespace strata::ling32::gpu {
namespace {
inline float philox_u(unsigned long long seed, unsigned long long ctr, unsigned stream) {
uint32_t c0 = static_cast<uint32_t>(ctr), c1 = static_cast<uint32_t>(ctr >> 32), c2 = stream, c3 = 0x5bd1e995u;
uint32_t k0 = static_cast<uint32_t>(seed), k1 = static_cast<uint32_t>(seed >> 32);
for (int r = 0; r < 10; ++r) {
const uint64_t p0 = static_cast<uint64_t>(0xD2511F53u) * c0, p1 = static_cast<uint64_t>(0xCD9E8D57u) * c2;
const uint32_t n0 = static_cast<uint32_t>(p1 >> 32) ^ c1 ^ k0, n1 = static_cast<uint32_t>(p1), n2 = static_cast<uint32_t>(p0 >> 32) ^ c3 ^ k1, n3 = static_cast<uint32_t>(p0);
c0 = n0; c1 = n1; c2 = n2; c3 = n3;
k0 += 0x9E3779B9u;
k1 += 0xBB67AE85u;
}
return static_cast<float>(c0 >> 8) * (1.0f / 16777216.0f); // [0, 1)
}
// the baseline sampler's distribution over a sorted top-k list: softmax(v / temp), cut at top_p (the crossing token kept), renormalised
inline void trunc_probs(const float* v, int n, float temp, float top_p, float* pn, int& cut) {
const float mx = v[0];
float z = 0.0f;
for (int i = 0; i < n; ++i) { pn[i] = sycl::exp((v[i] - mx) / temp); z += pn[i]; }
cut = n;
if (top_p < 1.0f) {
float acc = 0.0f;
for (int i = 0; i < n; ++i) { acc += pn[i] / z; if (acc >= top_p) { cut = i + 1; break; } }
}
float zc = 0.0f;
for (int i = 0; i < cut; ++i) zc += pn[i];
for (int i = 0; i < cut; ++i) pn[i] /= zc;
for (int i = cut; i < n; ++i) pn[i] = 0.0f;
}
// block sum in the order of ling32_spec.cu: warp butterfly, then the warp totals added in index order (safe to call repeatedly)
inline float block_sum_seq(const sy::Blk& b, float v, float* sm) {
const int nw = (b.bdim() + 31) >> 5;
v = sy::warp_sum_xor(b, v);
if (b.lane() == 0) sm[b.warp()] = v;
b.sync();
float t = 0.0f;
for (int i = 0; i < nw; ++i) t += sm[i];
b.sync();
return t;
}
inline uint32_t f2key(float x) {
uint32_t u = sycl::bit_cast<uint32_t>(x);
if ((u & 0x7FFFFFFFu) > 0x7F800000u) u = 0xFF800000u; // NaN ranks last
return (u & 0x80000000u) ? ~u : (u | 0x80000000u);
}
using LocalU32 = sycl::atomic_ref<uint32_t, sycl::memory_order::relaxed, sycl::memory_scope::work_group, sycl::access::address_space::generic_space>; // the work-group memory comes in as a plain pointer: generic space, not local_space
using LocalI32 = sycl::atomic_ref<int, sycl::memory_order::relaxed, sycl::memory_scope::work_group, sycl::access::address_space::generic_space>;
// the shared body of a draft pick: candidates (sorted desc, ties by lower id) -> token
inline void pick_from_sorted(const SpecCfgDev* cfg, SpecDevState* st, int slot, const float* cv, const int* ci, int* ids, int* q_tok, float* q_p, int* q_n) {
float* qp = q_p + static_cast<size_t>(slot) * 64;
int* qt = q_tok + static_cast<size_t>(slot) * 64;
int tok;
if (cfg->temp <= 0.0f) {
tok = ci[0];
qt[0] = tok;
qp[0] = 1.0f;
q_n[slot] = 1;
} else {
float pn[64];
const int ke = sycl::min(sycl::max(cfg->top_k, 1), 64);
int cut;
trunc_probs(cv, ke, cfg->temp, cfg->top_p, pn, cut);
const float u = philox_u(cfg->seed, st->ctr, 200u + slot);
float acc = 0.0f;
int pick = cut - 1;
for (int i = 0; i < cut; ++i) { acc += pn[i]; if (u < acc) { pick = i; break; } }
tok = ci[pick];
for (int i = 0; i < cut; ++i) { qt[i] = ci[i]; qp[i] = pn[i]; }
q_n[slot] = cut;
}
ids[slot + 1] = tok;
}
} // namespace
// ---------------------------------------------------------------------------------------------- top-K (exact, ties by lower index); K <= 64
// K rounds of "largest (value, then lower index) below the previous pick": every thread scans its strided elements, a work-group reduction takes the best. (The CUDA kernel is a radix select with
// shared-memory atomics; those did not give correct histograms on Xe in this build, and this form needs no shared memory at all.) One work-group of 256 per row.
void topk_rows(const float* x, int rows, int V, long stride, int K, float* ov, int* oi, cudaStream_t s) {
constexpr int kThreads = 256;
sy::launch(s, rows, kThreads, 0, [=](sy::Blk b, char*) {
const float* row = x + static_cast<size_t>(b.bid()) * stride;
const int tid = b.tid();
uint64_t prev = ~0ull;
for (int r = 0; r < K; ++r) {
uint64_t best = 0;
for (int i = tid; i < V; i += kThreads) {
const uint64_t c = (static_cast<uint64_t>(f2key(row[i])) << 32) | static_cast<uint64_t>(0xFFFFFFFFu - static_cast<uint32_t>(i));
if (c < prev && c > best) best = c;
}
best = sycl::reduce_over_group(b.it.get_group(), best, sycl::maximum<uint64_t>());
if (tid == 0) {
const int ix = static_cast<int>(0xFFFFFFFFu - static_cast<uint32_t>(best & 0xFFFFFFFFull));
ov[static_cast<size_t>(b.bid()) * K + r] = row[ix];
oi[static_cast<size_t>(b.bid()) * K + r] = ix;
}
prev = best;
}
});
}
// ---------------------------------------------------------------------------------------------- accept / first token
void spec_accept(const SpecCfgDev* cfg, SpecDevState* st, const float* tv, const int* ti, int K, int N, int* ids, const int* q_tok, const float* q_p, const int* q_n, cudaStream_t s) {
sy::launch(s, 1, 32, 0, [=](sy::Blk b, char*) {
if (b.tid() != 0) return;
const int D = N - 1;
int a = 0, bonus;
if (cfg->temp <= 0.0f) {
while (a < D && ids[a + 1] == ti[static_cast<size_t>(a) * K]) ++a;
bonus = ti[static_cast<size_t>(a) * K];
} else {
float pn[64], r[64];
int cut = 0;
bool rejected = false;
bonus = -1;
for (int i = 1; i <= D; ++i) {
trunc_probs(tv + static_cast<size_t>(i - 1) * K, K, cfg->temp, cfg->top_p, pn, cut);
const int t = ids[i];
float p_t = 0.0f, q_t = 0.0f;
for (int j = 0; j < cut; ++j) if (ti[static_cast<size_t>(i - 1) * K + j] == t) p_t = pn[j];
for (int j = 0; j < q_n[i - 1]; ++j) if (q_tok[static_cast<size_t>(i - 1) * 64 + j] == t) q_t = q_p[static_cast<size_t>(i - 1) * 64 + j];
const float u = philox_u(cfg->seed, st->ctr, static_cast<unsigned>((i - 1) * 4));
if (q_t > 0.0f && u * q_t < p_t) { a = i; continue; }
float sum = 0.0f;
for (int j = 0; j < cut; ++j) {
float qq = 0.0f;
const int tj = ti[static_cast<size_t>(i - 1) * K + j];
for (int l = 0; l < q_n[i - 1]; ++l) if (q_tok[static_cast<size_t>(i - 1) * 64 + l] == tj) qq = q_p[static_cast<size_t>(i - 1) * 64 + l];
r[j] = sycl::fmax(0.0f, pn[j] - qq);
sum += r[j];
}
if (!(sum > 0.0f)) { for (int j = 0; j < cut; ++j) r[j] = pn[j]; sum = 1.0f; }
const float u2 = philox_u(cfg->seed, st->ctr, static_cast<unsigned>((i - 1) * 4 + 1)) * sum;
float acc = 0.0f;
int pick = cut - 1;
for (int j = 0; j < cut; ++j) { acc += r[j]; if (u2 < acc) { pick = j; break; } }
bonus = ti[static_cast<size_t>(i - 1) * K + pick];
rejected = true;
break;
}
if (!rejected) {
trunc_probs(tv + static_cast<size_t>(D) * K, K, cfg->temp, cfg->top_p, pn, cut);
const float u = philox_u(cfg->seed, st->ctr, static_cast<unsigned>(D * 4 + 2));
float acc = 0.0f;
int pick = cut - 1;
for (int j = 0; j < cut; ++j) { acc += pn[j]; if (u < acc) { pick = j; break; } }
bonus = ti[static_cast<size_t>(D) * K + pick];
}
}
st->out[0] = a;
for (int i = 1; i <= a; ++i) st->out[i] = ids[i];
st->out[a + 1] = bonus;
st->out[11] = 0;
st->out[12] = N;
ids[0] = bonus;
st->nacc = a + 1;
st->hrow = a;
st->grow = a;
st->ctr += 1;
});
}
void spec_first(const SpecCfgDev* cfg, SpecDevState* st, const float* tv, const int* ti, int K, int* ids, cudaStream_t s) {
sy::launch(s, 1, 32, 0, [=](sy::Blk b, char*) {
if (b.tid() != 0) return;
int tok;
if (cfg->temp <= 0.0f) {
tok = ti[0];
} else {
float pn[64];
int cut;
trunc_probs(tv, K, cfg->temp, cfg->top_p, pn, cut);
const float u = philox_u(cfg->seed, st->ctr, 999u);
float acc = 0.0f;
int pick = cut - 1;
for (int j = 0; j < cut; ++j) { acc += pn[j]; if (u < acc) { pick = j; break; } }
tok = ti[pick];
}
st->out[0] = 0;
st->out[1] = tok;
st->out[11] = 1;
st->out[12] = 1;
ids[0] = tok;
st->ctr += 1;
});
}
// ---------------------------------------------------------------------------------------------- rollback, position, diagnostics
void kda_rollback(float* S_pool, const float* snap, float* hist_pool, const float* hist_ext, int n_kda, size_t S_sz, int C, int N, int slots, int ext_len, const SpecDevState* st, cudaStream_t s) {
sy::launch(s, 512, 256, 0, [=](sy::Blk b, char*) {
const int a = st->nacc - 1;
if (a >= N - 1) return; // everything accepted: the live state is the one after the last token
const size_t tid = static_cast<size_t>(b.bid()) * b.bdim() + b.tid(), nth = static_cast<size_t>(b.nblk()) * b.bdim();
for (size_t i = tid; i < static_cast<size_t>(n_kda) * S_sz; i += nth) {
const size_t k = i / S_sz, o = i - k * S_sz;
S_pool[i] = snap[(k * slots + a) * S_sz + o];
}
const size_t hsz = static_cast<size_t>(3) * C * 3; // [which][c][3]
for (size_t i = tid; i < static_cast<size_t>(n_kda) * 3 * C; i += nth) {
const size_t k = i / (3 * C), wc = i - k * 3 * C; // wc = which * C + c
const float* ex = hist_ext + (k * 3 * C + wc) * ext_len;
float* hp = hist_pool + k * hsz + wc * 3;
const int n = st->nacc;
hp[0] = ex[n];
hp[1] = ex[n + 1];
hp[2] = ex[n + 2];
}
});
}
void pos_advance(int* d_pos, const SpecDevState* st, cudaStream_t s) {
sy::launch(s, 1, 32, 0, [=](sy::Blk b, char*) { if (b.tid() == 0) *d_pos += st->nacc; });
}
void count_unique(const int* ridx, int P, int n_exp, int* out, cudaStream_t s) {
sy::launch(s, 1, 256, 32 * 4, [=](sy::Blk b, char* smem) {
uint32_t* bits = reinterpret_cast<uint32_t*>(smem);
if (b.tid() < 32) bits[b.tid()] = 0u;
b.sync();
for (int i = b.tid(); i < P; i += b.bdim()) { const int e = ridx[i]; if (e >= 0 && e < n_exp) LocalU32(bits[e >> 5]).fetch_or(1u << (e & 31)); }
b.sync();
if (b.tid() == 0) {
int n = 0;
for (int w = 0; w < (n_exp + 31) / 32; ++w) n += static_cast<int>(sycl::popcount(bits[w]));
sycl::atomic_ref<int, sycl::memory_order::relaxed, sycl::memory_scope::device> g(*out);
g.fetch_add(n);
}
});
}
void spec_unit_probs(const float* vals, int n, float temp, float top_p, float* pn, int* cut, cudaStream_t s) {
sy::launch(s, 1, 32, 0, [=](sy::Blk b, char*) { if (b.tid() == 0) { int c; trunc_probs(vals, n, temp, top_p, pn, c); *cut = c; } });
}
// ---------------------------------------------------------------------------------------------- MTP drafting helpers
void mtp_cat(const float* E, const float* X, const float* wfin, const float* wen, const float* whn, float eps, float* cat, int N, int D, cudaStream_t s) {
sy::launch(s, N, 256, 32 * 4, [=](sy::Blk b, char* smem) {
float* sm = reinterpret_cast<float*>(smem);
const int r = b.bid();
const float* e = E + static_cast<size_t>(r) * D;
const float* x = X + static_cast<size_t>(r) * D;
float* o = cat + static_cast<size_t>(r) * 2 * D;
float sacc = 0.0f;
for (int d = b.tid(); d < D; d += b.bdim()) sacc += e[d] * e[d];
const float ie = sycl::rsqrt(block_sum_seq(b, sacc, sm) / D + eps);
for (int d = b.tid(); d < D; d += b.bdim()) o[d] = e[d] * ie * wen[d];
float it = 1.0f;
if (wfin) {
sacc = 0.0f;
for (int d = b.tid(); d < D; d += b.bdim()) sacc += x[d] * x[d];
it = sycl::rsqrt(block_sum_seq(b, sacc, sm) / D + eps);
}
sacc = 0.0f;
for (int d = b.tid(); d < D; d += b.bdim()) { const float t = wfin ? x[d] * it * wfin[d] : x[d]; sacc += t * t; }
const float i2 = sycl::rsqrt(block_sum_seq(b, sacc, sm) / D + eps);
for (int d = b.tid(); d < D; d += b.bdim()) { const float t = wfin ? x[d] * it * wfin[d] : x[d]; o[D + d] = t * i2 * whn[d]; }
});
}
void mtp_nxt(const SpecDevState* st, const int* ids, int N, int* nxt, cudaStream_t s) {
sy::launch(s, 1, 32, 0, [=](sy::Blk b, char*) {
const int a = st->out[0];
for (int i = b.tid(); i < N; i += b.bdim()) nxt[i] = i <= a ? st->out[1 + i] : ids[sycl::min(i + 1, N - 1)];
});
}
void mtp_pos(const int* d_pos, int off, int* dst, cudaStream_t s) {
sy::launch(s, 1, 32, 0, [=](sy::Blk b, char*) { if (b.tid() == 0) *dst = *d_pos + off; });
}
void mtp_gather(const float* src, const SpecDevState* st, int row_fixed, int D, float* dst, cudaStream_t s) {
sy::launch(s, 1, 256, 0, [=](sy::Blk b, char*) {
const int row = row_fixed >= 0 ? row_fixed : st->out[0];
for (int d = b.tid(); d < D; d += b.bdim()) dst[d] = src[static_cast<size_t>(row) * D + d];
});
}
void mtp_setk(SpecDevState* st, int K, cudaStream_t s) {
sy::launch(s, 1, 32, 0, [=](sy::Blk b, char*) { if (b.tid() == 0) { st->dnext = K; st->out[10] = K; } });
}
void mtp_pick(const SpecCfgDev* cfg, SpecDevState* st, int slot, const float* cv, const int* ci, int* ids, int* q_tok, float* q_p, int* q_n, cudaStream_t s) {
sy::launch(s, 1, 32, 0, [=](sy::Blk b, char*) { if (b.tid() == 0) pick_from_sorted(cfg, st, slot, cv, ci, ids, q_tok, q_p, q_n); });
}
// the same pick when the candidates come from a low-bit copy of the head: their logits are recomputed with the exact S8_K head rows against hout, then sorted and drawn. One block of 256 threads.
void mtp_pick_rr(const SpecCfgDev* cfg, SpecDevState* st, int slot, const float* cv, const int* ci, const uint8_t* head, int D, const float* hout, int* ids, int* q_tok, float* q_p, int* q_n, cudaStream_t s) {
sy::launch(s, 1, 256, (64 * 3) * 4 + (64 * 2) * 4, [=](sy::Blk b, char* smem) {
float* sl = reinterpret_cast<float*>(smem);
float* ss = sl + 64;
int* sg = reinterpret_cast<int*>(ss + 64);
int* sgs = sg + 64;
const int tid = b.tid(), lane = b.lane(), w = b.warp();
if (tid < 64) { sg[tid] = ci[tid]; sl[tid] = cv[tid]; }
b.sync();
const int nsb = D / 256;
for (int c = w; c < 64; c += 8) {
const uint8_t* rowp = head + static_cast<size_t>(sg[c]) * nsb * sy::Sk<8>::kBytes;
float acc[1] = {0.0f};
sy::row_dot<8, 1, false>(rowp, nsb, hout, D, 1, 0, lane, acc);
const float sc = sy::warp_sum_xor(b, acc[0]);
if (lane == 0) sl[c] = sc;
}
b.sync();
if (tid < 64) {
const float v = sl[tid];
const int g = sg[tid];
int rank = 0;
for (int j = 0; j < 64; ++j) rank += (sl[j] > v || (sl[j] == v && sg[j] < g)) ? 1 : 0;
ss[rank] = v;
sgs[rank] = g;
}
b.sync();
if (tid == 0) pick_from_sorted(cfg, st, slot, ss, sgs, ids, q_tok, q_p, q_n);
});
}
} // namespace strata::ling32::gpu
@@ -0,0 +1,238 @@
// src/ling32/sycl/ling32_sy_k_trunk.cpp - the trunk kernels of ling32_kernels.cu on SYCL: Q8_1 / FWHT activation quantisers, the S_K GEMV (4 / 5 / 6 / 8-bit, Q8 or float activations),
// float GEMV (routers), RMSNorm, S8_K embedding. Same work split and summation order as the CUDA kernels (one warp = one weight row, 16 weights per lane-step, xor-butterfly sum).
// Not here (stubs stay in ling32_sy_todo.cpp): gemv_s8p (batched packed GEMV; the engine does not call it); gemm_sk_tc is forwarded to the float GEMV.
#include "ling32_sy.hpp"
#include <cstdio>
#include <cstdlib>
namespace strata::ling32::gpu {
namespace {
// ---------------------------------------------------------------------------------------------- activation quantisers
template <bool FWHT>
void launch_quant(const float* x, Q8Blk* out, int n128, cudaStream_t s) {
const int blocks = (n128 + 3) / 4;
sy::launch(s, blocks, 128, 0, [=](sy::Blk b, char*) {
const int blk = b.bid() * (b.bdim() >> 5) + b.warp();
const int lane = b.lane();
if (blk >= n128) return;
const float* p = x + static_cast<size_t>(blk) * 128 + lane * 4;
float v[4] = {p[0], p[1], p[2], p[3]};
if (FWHT) sy::fwht128_warp(b, v);
sy::q8_store_warp(b, v, out + static_cast<size_t>(blk) * 2);
});
}
// ---------------------------------------------------------------------------------------------- S_K GEMV
template <int CODE, int NT, bool Q8>
void launch_gemv_nt(const uint8_t* W, int rows, int K, const void* act, int N, float* out, int out_stride, int accumulate, cudaStream_t s) {
const int gx = (rows + 3) / 4, gy = (N + NT - 1) / NT;
sy::launch(s, gx * gy, 128, 0, [=](sy::Blk b, char*) {
const int bx = b.bid() % gx, by = b.bid() / gx;
const int row = bx * 4 + b.warp();
if (row >= rows) return; // uniform over the warp
const int lane = b.lane(), t0 = by * NT, nsb = K >> 8;
float acc[NT];
#pragma unroll
for (int t = 0; t < NT; ++t) acc[t] = 0.0f;
sy::row_dot<CODE, NT, Q8>(W + static_cast<size_t>(row) * nsb * sy::Sk<CODE>::kBytes, nsb, act, K, N, t0, lane, acc);
#pragma unroll
for (int t = 0; t < NT; ++t) {
#pragma unroll
for (int off = 16; off >= 1; off >>= 1) acc[t] += b.shfl_xor(acc[t], off);
}
if (lane == 0) {
#pragma unroll
for (int t = 0; t < NT; ++t)
if (t0 + t < N) {
float* o = out + static_cast<size_t>(t0 + t) * out_stride + row;
*o = accumulate ? *o + acc[t] : acc[t];
}
}
});
}
template <int CODE, int NT>
void launch_gemv_q(const uint8_t* W, int rows, int K, const void* act, bool q8, int N, float* out, int out_stride, int accumulate, cudaStream_t s) {
if (q8) launch_gemv_nt<CODE, NT, true>(W, rows, K, act, N, out, out_stride, accumulate, s);
else launch_gemv_nt<CODE, NT, false>(W, rows, K, act, N, out, out_stride, accumulate, s);
}
template <int CODE>
void launch_gemv_code(const uint8_t* W, int rows, int K, const void* act, bool q8, int N, float* out, int out_stride, int accumulate, cudaStream_t s) {
if (N <= 1) launch_gemv_q<CODE, 1>(W, rows, K, act, q8, N, out, out_stride, accumulate, s);
else if (N <= 4) launch_gemv_q<CODE, 4>(W, rows, K, act, q8, N, out, out_stride, accumulate, s);
else if (N <= 8) launch_gemv_q<CODE, 8>(W, rows, K, act, q8, N, out, out_stride, accumulate, s);
else launch_gemv_q<CODE, 16>(W, rows, K, act, q8, N, out, out_stride, accumulate, s);
}
// ---------------------------------------------------------------------------------------------- float GEMV (routers, b_proj, g_proj)
template <int NT>
void launch_gemv_f32(const float* W, int rows, int K, const float* x, int N, float* out, cudaStream_t s) {
const int gx = (rows + 3) / 4, gy = (N + NT - 1) / NT;
sy::launch(s, gx * gy, 128, 0, [=](sy::Blk b, char*) {
const int bx = b.bid() % gx, by = b.bid() / gx;
const int row = bx * 4 + b.warp();
if (row >= rows) return;
const int lane = b.lane(), t0 = by * NT;
float acc[NT];
#pragma unroll
for (int t = 0; t < NT; ++t) acc[t] = 0.0f;
const float* wr = W + static_cast<size_t>(row) * K;
for (int i = lane; i < (K >> 2); i += 32) {
const float w0 = wr[4 * i], w1 = wr[4 * i + 1], w2 = wr[4 * i + 2], w3 = wr[4 * i + 3];
#pragma unroll
for (int t = 0; t < NT; ++t) {
if (t0 + t >= N) break;
const float* xv = x + static_cast<size_t>(t0 + t) * K + 4 * i;
acc[t] += w0 * xv[0] + w1 * xv[1] + w2 * xv[2] + w3 * xv[3];
}
}
#pragma unroll
for (int t = 0; t < NT; ++t) {
#pragma unroll
for (int off = 16; off >= 1; off >>= 1) acc[t] += b.shfl_xor(acc[t], off);
}
if (lane == 0)
#pragma unroll
for (int t = 0; t < NT; ++t)
if (t0 + t < N) out[static_cast<size_t>(t0 + t) * rows + row] = acc[t];
});
}
} // namespace
void quant_q8(const float* x, Q8Blk* out, int M, int K, bool fwht, cudaStream_t s) {
const int n128 = M * (K / 128);
if (fwht) launch_quant<true>(x, out, n128, s);
else launch_quant<false>(x, out, n128, s);
}
void fwht128(const float* x, float* y, int M, int K, cudaStream_t s) {
const int n128 = M * (K / 128);
sy::launch(s, (n128 + 3) / 4, 128, 0, [=](sy::Blk b, char*) {
const int blk = b.bid() * (b.bdim() >> 5) + b.warp();
const int lane = b.lane();
if (blk >= n128) return;
const float* p = x + static_cast<size_t>(blk) * 128 + lane * 4;
float v[4] = {p[0], p[1], p[2], p[3]};
sy::fwht128_warp(b, v);
float* q = y + static_cast<size_t>(blk) * 128 + lane * 4;
q[0] = v[0]; q[1] = v[1]; q[2] = v[2]; q[3] = v[3];
});
}
bool trunk_xmx_try(const uint8_t* W, int code, int rows, int K, const float* x, int N, float* out, int out_stride, bool accumulate, cudaStream_t s); // ling32_sy_k_moe_xmx.cpp: the XMX trunk GEMM
void gemv_sk(const uint8_t* W, int code, int rows, int K, const void* act, bool act_q8, int N, float* out, int out_stride, bool accumulate, cudaStream_t s) {
if (!act_q8 && g_tc_min_n > 0 && N >= g_tc_min_n && trunk_xmx_try(W, code, rows, K, static_cast<const float*>(act), N, out, out_stride, accumulate, s)) return; // prefill chunks: XMX tiles where the device has them
switch (code) {
case 2: launch_gemv_code<2>(W, rows, K, act, act_q8, N, out, out_stride, accumulate, s); break;
case 3: launch_gemv_code<3>(W, rows, K, act, act_q8, N, out, out_stride, accumulate, s); break;
case 4: launch_gemv_code<4>(W, rows, K, act, act_q8, N, out, out_stride, accumulate, s); break;
case 5: launch_gemv_code<5>(W, rows, K, act, act_q8, N, out, out_stride, accumulate, s); break;
case 6: launch_gemv_code<6>(W, rows, K, act, act_q8, N, out, out_stride, accumulate, s); break;
case 8: launch_gemv_code<8>(W, rows, K, act, act_q8, N, out, out_stride, accumulate, s); break;
default: std::fprintf(stderr, "ling32: gemv_sk: unknown S_K code %d\n", code); std::abort();
}
}
// the tensor-core GEMM of the CUDA build: the XMX GEMM where the device has it (ling32_sy_k_moe_xmx.cpp), else the float GEMV (same results up to rounding)
void gemm_sk_tc(const uint8_t* W, int code, int rows, int K, const float* x, int N, float* out, int out_stride, bool accumulate, cudaStream_t s) {
if (trunk_xmx_try(W, code, rows, K, x, N, out, out_stride, accumulate, s)) return;
gemv_sk(W, code, rows, K, x, false, N, out, out_stride, accumulate, s);
}
void gemv_f32(const float* W, int rows, int K, const float* x, int N, float* out, cudaStream_t s) {
if (N <= 1) launch_gemv_f32<1>(W, rows, K, x, N, out, s);
else if (N <= 4) launch_gemv_f32<4>(W, rows, K, x, N, out, s);
else launch_gemv_f32<8>(W, rows, K, x, N, out, s);
}
void rmsnorm(const float* x, const float* gamma, float eps, float* y, int N, int D, cudaStream_t s) {
sy::launch(s, N, 256, 32 * sizeof(float), [=](sy::Blk b, char* smem) {
float* part = reinterpret_cast<float*>(smem);
const float* xr = x + static_cast<size_t>(b.bid()) * D;
float* yr = y + static_cast<size_t>(b.bid()) * D;
float ss = 0.0f;
for (int i = b.tid(); i < D; i += b.bdim()) ss += xr[i] * xr[i];
for (int off = 16; off >= 1; off >>= 1) ss += b.shfl_xor(ss, off);
if (b.lane() == 0) part[b.warp()] = ss;
b.sync();
if (b.tid() < 32) {
float v = b.tid() < (b.bdim() >> 5) ? part[b.tid()] : 0.0f;
for (int off = 16; off >= 1; off >>= 1) v += b.shfl_xor(v, off);
if (b.tid() == 0) part[0] = v;
}
b.sync();
const float r = 1.0f / sycl::sqrt(part[0] / static_cast<float>(D) + eps);
for (int i = b.tid(); i < D; i += b.bdim()) yr[i] = xr[i] * r * (gamma ? gamma[i] : 1.0f);
});
}
void embed_s8k(const uint8_t* W, int D, const int* ids, int N, float* x, cudaStream_t s) {
sy::launch(s, N, 256, 0, [=](sy::Blk b, char*) {
const int nsb = D >> 8;
const uint8_t* row = W + static_cast<size_t>(ids[b.bid()]) * nsb * 262;
for (int i = b.tid(); i < D; i += b.bdim()) {
const uint8_t* blk = row + (i >> 8) * 262;
const float Dh = sy::h2f(static_cast<uint16_t>(blk[0] | (blk[1] << 8)));
const float eff = Dh * sy::kDiv255.v[blk[2 + ((i & 255) >> 6)]];
x[static_cast<size_t>(b.bid()) * D + i] = static_cast<float>(static_cast<int8_t>(blk[6 + (i & 255)])) * eff;
}
});
}
// ---------------------------------------------------------------------------------------------- packed S8_K (single-token decode, float activations)
// repack_s8 turns the superblock layout (262 B, payload at odd 2-byte offsets) into q int8 [rows][K] (aligned rows) and eff = D * (u / 255) fp32 [rows][K / 64]; gemv_s8p1 then reads 8 weights of a lane
// as one aligned 8-byte word. Same arithmetic per lane as row_dot (float activation): s = sum_j q_j x_j in order, acc += eff * s per superblock, then the xor butterfly: bit-identical to gemv_sk.
void repack_s8(const uint8_t* W, int rows, int K, int8_t* q, float* sc, cudaStream_t s) {
const int nsb = K >> 8;
const size_t total = static_cast<size_t>(rows) * nsb * 4;
sy::launch(s, 4096, 256, 0, [=](sy::Blk b, char*) {
for (size_t i = static_cast<size_t>(b.bid()) * b.bdim() + b.tid(); i < total; i += static_cast<size_t>(b.nblk()) * b.bdim()) {
const size_t g = i & 3, sbi = i >> 2;
const uint8_t* blk = W + sbi * 262;
const float Dh = sy::h2f(static_cast<uint16_t>(blk[0] | (blk[1] << 8)));
const size_t row = sbi / nsb, sb = sbi % nsb;
sc[row * (K >> 6) + sb * 4 + g] = Dh * sy::kDiv255.v[blk[2 + g]];
int8_t* dst = q + row * K + sb * 256 + g * 64;
for (int j = 0; j < 64; ++j) dst[j] = static_cast<int8_t>(blk[6 + g * 64 + j]);
}
});
}
void gemv_s8p1(const int8_t* q, const float* ep, int rows, int K, const float* x, float* out, bool accumulate, cudaStream_t s) {
const int gx = (rows + 3) / 4;
sy::launch(s, gx, 128, 0, [=](sy::Blk b, char*) {
const int row = b.bid() * 4 + b.warp();
if (row >= rows) return;
const int lane = b.lane(), nsb = K >> 8;
const int g = lane >> 3, idx0 = g * 64 + (lane & 7) * 8;
const int8_t* qr = q + static_cast<size_t>(row) * K;
const float* er = ep + static_cast<size_t>(row) * (K >> 6);
float acc = 0.0f;
#pragma unroll 2
for (int sb = 0; sb < nsb; ++sb) {
const float eff = er[sb * 4 + g];
const sycl::vec<uint32_t, 2> w = *reinterpret_cast<const sycl::vec<uint32_t, 2>*>(qr + sb * 256 + idx0);
const sycl::vec<float, 4> xa = *reinterpret_cast<const sycl::vec<float, 4>*>(x + sb * 256 + idx0);
const sycl::vec<float, 4> xb = *reinterpret_cast<const sycl::vec<float, 4>*>(x + sb * 256 + idx0 + 4);
const float xs[8] = {xa[0], xa[1], xa[2], xa[3], xb[0], xb[1], xb[2], xb[3]};
const uint32_t ww[2] = {w[0], w[1]};
float sacc = 0.0f;
#pragma unroll
for (int j = 0; j < 8; ++j) {
const uint32_t byte = (ww[j >> 2] >> (8 * (j & 3))) & 0xFFu;
sacc += static_cast<float>(static_cast<int8_t>(byte)) * xs[j];
}
acc += eff * sacc;
}
for (int off = 16; off >= 1; off >>= 1) acc += b.shfl_xor(acc, off);
if (lane == 0) {
float* o = out + row;
*o = accumulate ? *o + acc : acc;
}
});
}
} // namespace strata::ling32::gpu
+22
View File
@@ -0,0 +1,22 @@
// src/ling32/sycl/ling32_sy_todo.cpp - GENERATED stubs (tools: phaseA-tests/ling32/sycl/tools/gen_todo.py): one aborting definition per gpu:: launcher of ling32_kernels.hpp / ling32_spec.hpp
// that has no SYCL implementation yet. To implement a launcher: write it in your own file sycl/ling32_sy_k_<area>.cpp and DELETE its line here (a duplicate definition fails the link).
#include "ling32_kernels.hpp"
#include "ling32_spec.hpp"
namespace {
[[noreturn]] void l32_todo(const char* what) {
std::fprintf(stderr, "ling32 (SYCL): %s is not implemented yet\n", what);
std::abort();
}
} // namespace
namespace strata::ling32::gpu {
void gemv_s8p(const int8_t* q, const float* sc, int rows, int K, const float* x, int N, float* out, int out_stride, bool accumulate, cudaStream_t s) { l32_todo("gemv_s8p"); }
size_t mla_attn_fast_workspace(int n_max, int H, int nope, int rope, int kv_lora, int max_ctx, LatentFmt fmt, int mode) { l32_todo("mla_attn_fast_workspace"); return 0; }
void mla_attn_fast(const float* qabs, const float* q, const void* cache, const int* d_pos0, float* ctx, int N, int H, int nope, int rope, int kv_lora, float scale, LatentFmt fmt, int max_ctx, int mode, void* ws, size_t ws_bytes, cudaStream_t s, const void* cache_old, int recent) { l32_todo("mla_attn_fast"); }
bool mla_exp_ok(int nope, int rope, int vhead, int kv_lora) { l32_todo("mla_exp_ok"); return false; }
size_t mla_exp_workspace_bytes(int nmax, int H, int slab) { l32_todo("mla_exp_workspace_bytes"); return 0; }
void mla_exp_convert_weights(const uint16_t* bf16_in, size_t n, uint16_t* fp16_out, cudaStream_t s) { l32_todo("mla_exp_convert_weights"); }
void mla_exp_prefill(const float* q, const float* cache, int lat_stride, const uint16_t* wk16, const uint16_t* wv16, const float* gate, float* out, int N, int H, int pos0, float scale, void* ws, size_t ws_bytes, int slab, cudaStream_t s) { l32_todo("mla_exp_prefill"); }
} // namespace strata::ling32::gpu
+37
View File
@@ -0,0 +1,37 @@
// divtest.cpp - is the float divide of a SYCL kernel correctly rounded? Counts results that differ from the host's IEEE division for a / 127.0f, a / 255.0f and 1.0f / a.
// icpx -fsycl <flags> divtest.cpp -o divtest && ONEAPI_DEVICE_SELECTOR=level_zero:gpu ./divtest
#include <sycl/sycl.hpp>
#include <cstdio>
#include <cstring>
#include <random>
#include <vector>
int main() {
sycl::queue q{sycl::gpu_selector_v};
std::printf("device %s\n", q.get_device().get_info<sycl::info::device::name>().c_str());
const int n = 1 << 20;
std::vector<float> a(n);
std::mt19937 g(5);
std::uniform_real_distribution<float> d(0.001f, 400.0f);
for (auto& x : a) x = d(g);
float* da = sycl::malloc_device<float>(n, q);
float* o1 = sycl::malloc_device<float>(n, q);
float* o2 = sycl::malloc_device<float>(n, q);
float* o3 = sycl::malloc_device<float>(n, q);
q.memcpy(da, a.data(), n * 4).wait();
q.parallel_for(sycl::range<1>(n), [=](sycl::id<1> i) { const float x = da[i]; o1[i] = x / 127.0f; o2[i] = x / 255.0f; o3[i] = 1.0f / x; }).wait();
std::vector<float> r1(n), r2(n), r3(n);
q.memcpy(r1.data(), o1, n * 4).wait();
q.memcpy(r2.data(), o2, n * 4).wait();
q.memcpy(r3.data(), o3, n * 4).wait();
int b1 = 0, b2 = 0, b3 = 0;
volatile float k127 = 127.0f, k255 = 255.0f, one = 1.0f;
for (int i = 0; i < n; ++i) {
const float h1 = a[i] / k127, h2 = a[i] / k255, h3 = one / a[i];
b1 += std::memcmp(&r1[i], &h1, 4) != 0;
b2 += std::memcmp(&r2[i], &h2, 4) != 0;
b3 += std::memcmp(&r3[i], &h3, 4) != 0;
}
std::printf("mismatches of %d: x/127 %d, x/255 %d, 1/x %d\n", n, b1, b2, b3);
return 0;
}
+22
View File
@@ -0,0 +1,22 @@
#!/bin/bash
# compiles divtest.cpp with several floating-point flag sets and runs each on the GPU
set +u
. /opt/intel/oneapi/setvars.sh >/dev/null 2>&1
export ONEAPI_DEVICE_SELECTOR=level_zero:gpu
cd "$(dirname "$0")" || exit 2
mkdir -p /tmp/l32sy_div_$$ && cd /tmp/l32sy_div_$$ || exit 2
src=$(dirname "$OLDPWD")/tools/divtest.cpp
[ -f "$src" ] || src="$OLDPWD/divtest.cpp"
run() {
name=$1; shift
echo "== $name: $*"
icpx -fsycl -O3 "$@" "$src" -o div_$name 2>&1 | grep -E "error" | head -3
./div_$name 2>&1 | tail -2
}
run default
run precise -ffp-model=precise
run precisediv -ffp-model=precise -foffload-fp32-prec-div -foffload-fp32-prec-sqrt
run backend -ffp-model=precise -foffload-fp32-prec-div "-Xsycl-target-backend=spir64" "-options -cl-fp32-correctly-rounded-divide-sqrt"
run strict -ffp-model=strict
run nofast -fno-fast-math -ffp-contract=off
cd / && rm -rf /tmp/l32sy_div_$$
@@ -0,0 +1,21 @@
#!/bin/bash
# Linux build + test of the SYCL Ling engine (dev loop on the Arc A750 box p1006, also fine on any Linux box with oneAPI DPC++ and an Intel GPU).
# ltest.py p1006 --wt <worktree> --name NAME -- "bash engine/src/ling32/sycl/tools/l32sy_build.sh" (build only)
# jobq.py submit p1006 --name NAME --lock gpu -- "bash ~/t027/w/NAME/engine/src/ling32/sycl/tools/l32sy_build.sh test ling32_kernel_test"
# modes: build (default) | test REGEX (ctest -R REGEX on the GPU; REGEX like "make_fixture|kernel_test")
# env: L32SY_FIX_PY (python with numpy + zstandard, default ~/l32sy/venv/bin/python), L32SY_TARGETS (default spir64 = JIT), L32SY_JOBS
set +u
. /opt/intel/oneapi/setvars.sh >/dev/null 2>&1
root=$(cd "$(dirname "$0")/../../../../.." && pwd)
cd "$root" || exit 2
mode=${1:-build}
bld=${L32SY_BLD:-bld}
if [ "$mode" = build ]; then
cmake -S engine/src/ling32 -B "$bld" -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx -DLING32_SYCL=ON \
"-DLING32_SYCL_TARGETS=${L32SY_TARGETS:-spir64}" "-DPython3_EXECUTABLE=${L32SY_FIX_PY:-$HOME/l32sy/venv/bin/python}" 2>&1 | tail -3
cmake --build "$bld" -j "${L32SY_JOBS:-8}" -- -k 0 2>&1 | grep -E "error|FAILED|undefined reference|warning: (variable|unused|implicit)" | cut -c1-300 | head -100
ls -la "$bld/strata-ling32" 2>&1 | tail -1
else
export ONEAPI_DEVICE_SELECTOR=${ONEAPI_DEVICE_SELECTOR:-level_zero:gpu}
ctest --test-dir "$bld" -R "${2:-kernel_test}" --output-on-failure 2>&1 | tail -${L32SY_TAIL:-80}
fi
@@ -0,0 +1,9 @@
#!/bin/bash
# O_DIRECT into Level Zero host memory probe (build + run on the Linux dev box); see l32sy_dio_probe.cpp
. /opt/intel/oneapi/setvars.sh >/dev/null 2>&1
export ONEAPI_DEVICE_SELECTOR=level_zero:gpu
cd "$(dirname "$0")/../../../../.." || exit 2
mkdir -p bld
icpx -fsycl -O1 engine/src/ling32/sycl/tools/l32sy_dio_probe.cpp -o bld/l32sy_dio_probe 2>&1 | grep -E "error" | head
timeout 60 bld/l32sy_dio_probe "${1:-$HOME/l32sy/fix/ling32_fixture.strata}"
df -T "${1:-$HOME/l32sy/fix}" | tail -1
@@ -0,0 +1,80 @@
// l32sy_dio_probe.cpp - O_DIRECT reads into Level Zero host (pinned) memory. icpx -fsycl l32sy_dio_probe.cpp -o l32sy_dio_probe && ./l32sy_dio_probe FILE
#include <sycl/sycl.hpp>
#include <chrono>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
static void try_read(const char* what, int fd, void* buf, size_t n, off_t off) {
errno = 0;
const ssize_t got = pread(fd, buf, n, off);
std::printf(" %-40s buf %p (%% 4096 = %zu, %% 65536 = %zu) len %zu off %lld -> %zd %s\n", what, buf, (size_t)((uintptr_t)buf % 4096), (size_t)((uintptr_t)buf % 65536), n, (long long)off, got, got < 0 ? std::strerror(errno) : "ok");
}
int main(int argc, char** argv) {
std::setvbuf(stdout, nullptr, _IONBF, 0);
if (argc < 2) return 2;
sycl::device dev{sycl::gpu_selector_v};
sycl::context ctx{dev};
const int fd = open(argv[1], O_RDONLY | O_DIRECT);
std::printf("open O_DIRECT: fd %d %s\n", fd, fd < 0 ? std::strerror(errno) : "ok");
if (fd < 0) return 1;
for (size_t n : {size_t(4096), size_t(65536), size_t(1u << 20), size_t(8u << 20)}) {
void* h0 = sycl::malloc_host(n + 4096, ctx);
void* h1 = sycl::aligned_alloc_host(65536, n, ctx);
void* d0 = sycl::malloc_device(n, dev, ctx);
void* s0 = sycl::malloc_shared(n, dev, ctx);
void* p0 = nullptr;
if (posix_memalign(&p0, 65536, n)) p0 = nullptr;
try_read("posix_memalign 64K", fd, p0, n, 0);
try_read("malloc_host", fd, h0, n, 0);
try_read("malloc_host +4096 aligned", fd, (char*)(((uintptr_t)h0 + 4095) & ~uintptr_t(4095)), n, 0);
try_read("aligned_alloc_host 64K", fd, h1, n, 0);
try_read("malloc_shared", fd, s0, n, 0);
try_read("malloc_device (expected to fail)", fd, d0, n, 0);
std::free(p0);
sycl::free(h0, ctx); sycl::free(h1, ctx); sycl::free(d0, ctx); sycl::free(s0, ctx);
}
// ordinary memory imported for device copies (zeDriverImportExternalPointer): read speed of the copy, and does a kernel read it?
#if __has_include(<sycl/ext/oneapi/experimental/prepare_for_device_copy.hpp>)
{
sycl::queue q{ctx, dev, sycl::property_list{sycl::property::queue::in_order()}};
const size_t N = 256ull << 20;
void* pg = nullptr;
if (posix_memalign(&pg, 65536, N)) return 1;
std::memset(pg, 7, N);
void* dv = sycl::malloc_device(N, dev, ctx);
auto bw = [&](const char* what) {
q.memcpy(dv, pg, N).wait();
const auto t0 = std::chrono::steady_clock::now();
for (int i = 0; i < 4; ++i) q.memcpy(dv, pg, N);
q.wait();
const double dt = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
std::printf(" H2D from ordinary memory %-22s %.1f GB/s\n", what, 4.0 * N / 1e9 / dt);
};
bw("(not imported)");
try {
sycl::ext::oneapi::experimental::prepare_for_device_copy(pg, N, q);
std::printf("prepare_for_device_copy: ok\n");
bw("(imported)");
// O_DIRECT into the imported range
try_read("imported posix_memalign O_DIRECT", fd, pg, 1 << 20, 0);
sycl::ext::oneapi::experimental::release_from_device_copy(pg, q);
} catch (const std::exception& ex) { std::printf("prepare_for_device_copy: %s\n", ex.what()); }
sycl::free(dv, ctx);
std::free(pg);
}
#else
std::printf("no prepare_for_device_copy header in this oneAPI\n");
#endif
// a buffered read of the same memory
const int fb = open(argv[1], O_RDONLY);
void* h1 = sycl::aligned_alloc_host(65536, 1 << 20, ctx);
std::printf("buffered:\n");
try_read("aligned_alloc_host 64K (buffered)", fb, h1, 1 << 20, 0);
return 0;
}
@@ -0,0 +1,181 @@
// l32sy_probe.cpp - memory-limit and copy probe of a SYCL / Level Zero GPU (tier-store planning for Ling on Intel).
// icpx -fsycl -O2 l32sy_probe.cpp -o l32sy_probe && ./l32sy_probe [max_host_gib] [max_dev_gib]
// Prints: device memory figures, the largest single malloc_device / malloc_host that succeeds (up to the caps), copy bandwidth from pinned and pageable memory,
// the "async copy from a pageable buffer that is reused before it runs" hazard, and kernel read bandwidth of malloc_host memory (zero copy).
#include <sycl/sycl.hpp>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
using clk = std::chrono::steady_clock;
static double now() { return std::chrono::duration<double>(clk::now().time_since_epoch()).count(); }
static const double GiB = 1073741824.0;
int main(int argc, char** argv) {
std::setvbuf(stdout, nullptr, _IONBF, 0);
const size_t max_host = static_cast<size_t>((argc > 1 ? std::atof(argv[1]) : 8.0) * GiB);
const bool allocs_only = std::getenv("L32SY_PROBE_ALLOCS_ONLY") != nullptr;
const size_t max_dev = static_cast<size_t>((argc > 2 ? std::atof(argv[2]) : 8.0) * GiB);
sycl::device dev{sycl::gpu_selector_v};
sycl::context ctx{dev};
sycl::queue q{ctx, dev, sycl::property_list{sycl::property::queue::in_order()}};
std::printf("device: %s\n", dev.get_info<sycl::info::device::name>().c_str());
std::printf("global_mem_size %.2f GiB, max_mem_alloc_size %.2f GiB\n", dev.get_info<sycl::info::device::global_mem_size>() / GiB, dev.get_info<sycl::info::device::max_mem_alloc_size>() / GiB);
if (dev.has(sycl::aspect::ext_intel_free_memory)) std::printf("free memory %.2f GiB\n", dev.get_info<sycl::ext::intel::info::device::free_memory>() / GiB);
for (const char* e : {"UR_L0_ENABLE_RELAXED_ALLOCATION_LIMITS", "SYCL_PI_LEVEL_ZERO_ENABLE_RELAXED_ALLOCATION_LIMITS", "NEOReadDebugKeys", "AllowUnrestrictedSize"})
if (const char* v = std::getenv(e)) std::printf("env %s=%s\n", e, v);
// ---- largest single allocations
std::printf("-- malloc_device (single allocation)\n");
for (double g : {1.0, 2.0, 3.0, 3.9, 4.0, 4.1, 6.0, 8.0, 10.0, 12.0, 16.0}) {
const size_t n = static_cast<size_t>(g * GiB);
if (n > max_dev) break;
void* p = nullptr;
std::printf(" %.1f GiB: allocating...\n", g);
try { p = sycl::malloc_device(n, dev, ctx); } catch (const sycl::exception& ex) { std::printf(" %.1f GiB: exception %s\n", g, ex.what()); }
if (!p) { std::printf(" %.1f GiB: FAIL\n", g); continue; }
std::printf(" %.1f GiB: allocated, touching with a kernel...\n", g);
// touch the first and the last bytes through a kernel (a >4 GiB buffer needs stateless addressing)
unsigned char* b = static_cast<unsigned char*>(p);
try {
q.memset(b, 0x11, 64);
q.memset(b + n - 64, 0x22, 64);
q.parallel_for(sycl::range<1>(2), [=](sycl::id<1> i) { if (i[0] == 0) b[n - 1] = static_cast<unsigned char>(b[0] + 1); else b[1] = static_cast<unsigned char>(b[n - 2] + 1); });
q.wait_and_throw();
unsigned char h[2];
q.memcpy(h, b + n - 1, 1).wait();
q.memcpy(h + 1, b + 1, 1).wait();
std::printf(" %.1f GiB: ok (kernel touch last byte -> 0x%02x, first+1 -> 0x%02x, want 0x12 0x23)\n", g, h[0], h[1]);
} catch (const sycl::exception& ex) { std::printf(" %.1f GiB: allocated, kernel/copy failed: %s\n", g, ex.what()); }
sycl::free(p, ctx);
}
std::printf("-- total device memory in many small allocations\n");
{
std::vector<void*> v;
size_t tot = 0;
const size_t piece = 512ull << 20;
while (tot < max_dev) {
void* p = nullptr;
try { p = sycl::malloc_device(piece, dev, ctx); } catch (...) {}
if (!p) break;
v.push_back(p);
tot += piece;
}
std::printf(" %zu x 512 MiB = %.2f GiB (cap %.1f GiB)\n", v.size(), tot / GiB, max_dev / GiB);
for (void* p : v) sycl::free(p, ctx);
}
std::printf("-- malloc_host (single allocation)\n");
for (double g : {0.5, 1.0, 2.0, 4.0, 8.0, 12.0, 16.0, 24.0, 32.0, 48.0}) {
const size_t n = static_cast<size_t>(g * GiB);
if (n > max_host) break;
void* p = nullptr;
const double t0 = now();
try { p = sycl::malloc_host(n, ctx); } catch (const sycl::exception& ex) { std::printf(" %.1f GiB: exception %s\n", g, ex.what()); }
if (!p) { std::printf(" %.1f GiB: FAIL\n", g); continue; }
const double t1 = now();
std::memset(p, 0x5a, n);
const double t2 = now();
std::printf(" %.1f GiB: ok (alloc %.2f s, first touch %.2f s)\n", g, t1 - t0, t2 - t1);
sycl::free(p, ctx);
}
if (allocs_only) return 0;
// ---- copy bandwidth
const size_t N = 512ull << 20;
void* dbuf = sycl::malloc_device(N, dev, ctx);
void* hpin = sycl::malloc_host(N, ctx);
void* hpage = std::aligned_alloc(4096, N);
std::memset(hpin, 1, N);
std::memset(hpage, 2, N);
auto bw = [&](const char* what, void* dst, const void* src) {
q.memcpy(dst, src, N).wait(); // warm up
const double t0 = now();
for (int i = 0; i < 4; ++i) q.memcpy(dst, src, N);
q.wait();
std::printf(" %-34s %.1f GB/s\n", what, 4.0 * N / 1e9 / (now() - t0));
};
std::printf("-- copy bandwidth (512 MiB x 4)\n");
bw("H2D pinned (malloc_host)", dbuf, hpin);
bw("H2D pageable (aligned_alloc)", dbuf, hpage);
bw("D2H pinned", hpin, dbuf);
bw("D2H pageable", hpage, dbuf);
// ---- hazard: an async copy from a pageable buffer that is reused before the copy runs
std::printf("-- async copy from pageable memory, source reused right after the enqueue\n");
{
const size_t S = 4ull << 20;
unsigned char* src = static_cast<unsigned char*>(std::aligned_alloc(4096, S));
unsigned char* dst = static_cast<unsigned char*>(dbuf);
unsigned char* spin_flag = sycl::malloc_device<unsigned char>(1, q);
int bad_runs = 0;
const int runs = 20;
{
const double ts = now();
q.parallel_for(sycl::range<1>(1), [=](sycl::id<1>) {
unsigned long x = 1;
for (long i = 0; i < 60000000; ++i) x = x * 6364136223846793005ull + 1442695040888963407ull;
spin_flag[0] = static_cast<unsigned char>(x);
});
q.wait();
std::printf(" (the busy kernel takes %.0f ms)\n", (now() - ts) * 1e3);
}
for (int r = 0; r < runs; ++r) {
std::memset(src, 0xAA, S);
// keep the queue busy so the copy runs late
q.parallel_for(sycl::range<1>(1), [=](sycl::id<1>) {
unsigned long x = 1;
for (long i = 0; i < 60000000; ++i) x = x * 6364136223846793005ull + 1442695040888963407ull;
spin_flag[0] = static_cast<unsigned char>(x);
});
q.memcpy(dst, src, S);
std::memset(src, 0x55, S); // the caller reuses its buffer
q.wait();
std::vector<unsigned char> h(S);
q.memcpy(h.data(), dst, S).wait();
size_t aa = 0, five = 0;
for (size_t i = 0; i < S; i += 4096) { aa += h[i] == 0xAA; five += h[i] == 0x55; }
if (five) ++bad_runs;
if (r < 3 || five) std::printf(" run %d: pages with the OLD data 0xAA %zu, with the REUSED data 0x55 %zu of %zu\n", r, aa, five, S / 4096);
}
std::printf(" hazard: %d of %d runs delivered the reused (wrong) bytes\n", bad_runs, runs);
std::free(src);
sycl::free(spin_flag, ctx);
}
// ---- kernel reads of host memory (zero copy)
std::printf("-- kernel read of malloc_host memory (sum of 512 MiB)\n");
{
const size_t words = N / 8;
unsigned long* hp = static_cast<unsigned long*>(hpin);
for (size_t i = 0; i < words; ++i) hp[i] = i;
unsigned long* out = sycl::malloc_device<unsigned long>(1, q);
q.memset(out, 0, 8).wait();
const size_t groups = 4096, wg = 256;
double best = 0;
unsigned long got = 0;
for (int it = 0; it < 4; ++it) {
q.memset(out, 0, 8).wait();
const double t0 = now();
q.parallel_for(sycl::nd_range<1>(groups * wg, wg), [=](sycl::nd_item<1> ni) {
unsigned long s = 0;
for (size_t i = ni.get_global_id(0); i < words; i += groups * wg) s += hp[i];
sycl::atomic_ref<unsigned long, sycl::memory_order::relaxed, sycl::memory_scope::device> a(out[0]);
a.fetch_add(s);
});
q.wait();
const double dt = now() - t0;
if (N / 1e9 / dt > best) best = N / 1e9 / dt;
q.memcpy(&got, out, 8).wait();
}
const unsigned long want = static_cast<unsigned long>(words) * (words - 1) / 2;
std::printf(" host-memory kernel read %.1f GB/s, sum %s\n", best, got == want ? "correct" : "WRONG");
sycl::free(out, ctx);
}
sycl::free(dbuf, ctx);
sycl::free(hpin, ctx);
std::free(hpage);
return 0;
}
@@ -0,0 +1,55 @@
"""Copies a worktree to p1006 (~/l32sy/w/<name>) and submits ONE jobq job there with the lock you choose (ltest.py always takes the 'test' lock, which other lanes hold for a long time).
python l32sy_push.py <worktree> <name> [--lock none|gpu] [--timeout 20m] -- "<command run inside the copy>"
Build: -- "bash engine/src/ling32/sycl/tools/l32sy_build.sh" (--lock none)
Test: -- "bash engine/src/ling32/sycl/tools/l32sy_build.sh build && bash engine/src/ling32/sycl/tools/l32sy_build.sh test 'kernel_test'" --lock gpu
Prints the job id; then: python jobq.py wait <id> --poll 15 (background)."""
import os
import subprocess
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
JOBQ = r"C:\Users\AI-Server\Desktop\Strata\phaseA-tests\jobq\jobq.py"
HOST = "p1006ssh.claryel.space"
SSH = ["ssh", "-o", "BatchMode=yes", "-o", "LogLevel=error"]
def main():
argv = sys.argv[1:]
if "--" not in argv or len(argv) < 4:
sys.exit(__doc__)
i = argv.index("--")
wt, name = argv[0], argv[1]
opts = argv[2:i]
cmd = " ".join(argv[i + 1:])
lock = "none"
timeout = "20m"
k = 0
while k < len(opts):
if opts[k] == "--lock":
lock = opts[k + 1]; k += 2
elif opts[k] == "--timeout":
timeout = opts[k + 1]; k += 2
else:
sys.exit("unknown option " + opts[k])
name = "".join(c if c.isalnum() or c in "-_" else "-" for c in name)
dest = "l32sy/w/" + name
files = subprocess.run(["git", "-C", wt, "ls-files", "-z", "-co", "--exclude-standard"], capture_output=True, check=True).stdout
keep = [f for f in files.split(b"\0") if f and os.path.isfile(os.path.join(wt.encode(), f))]
tar = subprocess.Popen(["tar", "-C", wt, "--null", "-T", "-", "-cf", "-"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
unpack = subprocess.Popen(SSH + [HOST, "rm -rf ~/%s && mkdir -p ~/%s && tar -xf - -C ~/%s 2>/dev/null; echo unpacked $(find ~/%s -type f | wc -l) files" % (dest, dest, dest, dest)],
stdin=tar.stdout, stdout=subprocess.PIPE)
tar.stdout.close()
tar.stdin.write(b"\0".join(keep) + b"\0")
tar.stdin.close()
out = unpack.communicate()[0].decode("utf-8", "replace").strip()
tar.wait()
print("push: %s (%d files sent) -> p1006:~/%s" % (out, len(keep), dest))
job = "cd ~/%s && %s" % (dest, cmd)
r = subprocess.run([sys.executable, JOBQ, "submit", "p1006", "--name", name, "--timeout", timeout, "--lock", lock, "--", "bash -lc " + "'" + job.replace("'", "'\\''") + "'"], capture_output=True, text=True)
sys.stdout.write(r.stdout)
sys.stderr.write(r.stderr)
return r.returncode
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,62 @@
#!/bin/bash
# Tier-store lane of the SYCL Ling port (Linux dev box, Intel GPU). Run from the copied tree like l32sy_build.sh:
# ltest.py p1006 --wt <wt> --name X -- "bash engine/src/ling32/sycl/tools/l32sy_tierbox.sh probe-build"
# jobq.py submit p1006 --name Y --lock gpu -- "bash ~/t027/w/X/engine/src/ling32/sycl/tools/l32sy_tierbox.sh probe-run 8 8"
# modes: probe-build | probe-run MAXHOSTGIB MAXDEVGIB | fixtures | tiercheck | memory
# probe-run: env of the caller passes through (UR_L0_ENABLE_RELAXED_ALLOCATION_LIMITS=1 ...)
# fixtures: the narrow and the wide fixture (+ MTP sidecar) in $L32SY_FIXDIR (default ~/l32sy/fix)
# tiercheck: the store test driver (bld/ling32_sy_tier_check) on the fixture in several tier shapes
set +u
. /opt/intel/oneapi/setvars.sh >/dev/null 2>&1
root=$(cd "$(dirname "$0")/../../../../.." && pwd)
cd "$root" || exit 2
mode=${1:-probe-build}
bld=${L32SY_BLD:-bld}
py=${L32SY_FIX_PY:-$HOME/l32sy/venv/bin/python}
fix=${L32SY_FIXDIR:-$HOME/l32sy/fix}
export ONEAPI_DEVICE_SELECTOR=${ONEAPI_DEVICE_SELECTOR:-level_zero:gpu}
case "$mode" in
memory)
free -m | head -3
ulimit -l
grep -E "MemTotal|MemAvailable|HugePages_Total|Hugepagesize" /proc/meminfo
;;
probe-build)
mkdir -p "$bld"
icpx -fsycl -O2 engine/src/ling32/sycl/tools/l32sy_probe.cpp -o "$bld/l32sy_probe" 2>&1 | grep -E "error|warning" | head -20
ls -la "$bld/l32sy_probe"
;;
probe-run)
timeout 600 "$bld/l32sy_probe" "${2:-8}" "${3:-8}"
;;
fixtures)
mkdir -p "$fix"
"$py" -I engine/tests/ling32/ling32_pyref.py make-fixture "$fix/ling32_fixture.strata" 2>&1 | tail -2
"$py" -I engine/tests/ling32/ling32_pyref.py make-fixture "$fix/ling32_wide.strata" --wide 2>&1 | tail -2
"$py" -I engine/tests/ling32/ling32_pyref.py make-mtp-fixture "$fix/ling32_wide_mtp.strata" --wide 2>&1 | tail -2
ls -la "$fix"
;;
tiercheck)
shift
exec "$bld/ling32_sy_tier_check" "$@"
;;
tiercheck-all)
# every tier shape on the fixture (E = 64 experts, 4 MoE layers): one line per run, then the totals. Extra env of the caller passes through (STRATA_L32_PIN_FAIL=1 ...).
file=${2:-$fix/ling32_fixture.strata}
npass=0; nfail=0
for shape in "--vr 16 --rr 48 --dyn 24 --zc 0" "--vr 16 --rr 48 --dyn 24 --zc 1" "--vr 0 --rr 64 --dyn 24 --zc 0" "--vr 0 --rr 64 --dyn 24 --zc 1" "--vr 0 --rr 64 --dyn 8 --zc 0 --pf 0" \
"--vr 8 --rr 8 --dyn 12 --ring 8 --zc 0" "--vr 8 --rr 8 --dyn 12 --ring 8 --zc 1" "--vr 0 --rr 0 --dyn 6 --ring 6 --zc 0" "--vr 0 --rr 0 --dyn 6 --ring 6 --zc 1" \
"--vr 4 --rr 0 --dyn 24 --ring 16 --zc 1 --pf 0" "--vr 4 --rr 12 --dyn 10 --ring 10 --zc 1 --noisy 0"; do
out=$(timeout "${L32SY_RUN_TIMEOUT:-300}" "$bld/ling32_sy_tier_check" "$file" $shape --fwds "${L32SY_FWDS:-12}" 2>&1)
rc=$?
host=$(echo "$out" | grep "STRATA_L32_TIER_CHECK compared" | sed 's/.*compared/compared/')
dev=$(echo "$out" | grep "device-side check")
if [ $rc -eq 0 ] && echo "$host" | grep -q " 0 wrong"; then r=PASS; npass=$((npass+1)); else r=FAIL; nfail=$((nfail+1)); fi
echo "$r rc=$rc [$shape] | $host | $dev"
if [ $r = FAIL ]; then echo "$out" | tail -${L32SY_FAILTAIL:-25}; fi
done
echo "TIERCHECK SUMMARY: $npass pass, $nfail fail ($file)"
[ $nfail -eq 0 ]
;;
*) echo "unknown mode $mode"; exit 2 ;;
esac
+883
View File
@@ -0,0 +1,883 @@
// tests/ling32/ling32_moe_sy_test.cpp - the SYCL routed-expert / router / SwiGLU / combine kernels (src/ling32/sycl/ling32_sy_k_moe.cpp, ling32_sy_k_router.cpp) against their CPU definitions.
// Usage: ling32_moe_sy_test DATA_DIR (DATA_DIR = engine/tests/ling32/data: pack_s{4,5,6,8}.bin, real S_K superblocks; S2_K / S3_K slabs are random superblocks)
// What is compared, and how:
// * float activations: the CPU model below does the arithmetic of the kernel (lane l of a warp owns 8 weights of each superblock, fmaf chain, xor butterfly) = ling32_cpu_expert.cpp; bit for bit, and
// (sanity) the relative error against a double reference stays below 2e-5.
// * Q8 activations: the integer dot products are exact; the CPU model repeats the float arithmetic of the kernel (lane order, fma contraction) bit for bit; and the error against
// dot_sk_q8_1_row (sequential group order) stays below 2e-5 of sum|w x|, like ling32_kernel_test.
// * moe_act: float output against the CPU swiglu / S_xd / FWHT-128 (exp is the device's: a relative tolerance), the Q8 output = CPU quantiser of the kernel's own float output, bit for bit.
// * null slab entries write nothing; moe_tc_* (grouped by expert) equal moe_gu / moe_dn with float activations bit for bit; ALF-LB routing, swiglu, gemv2_swiglu_s8, moe_combine(_norm).
#if defined(_WIN32)
#include <stdlib.h>
#define setenv(k, v, o) _putenv_s((k), (v)) // MSVC runtime: no setenv
#endif
#include "ling32_kernels.hpp"
#include "strata/ling32/ling32_sk.hpp"
#include "strata/quant/sk_codecs.hpp"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <random>
#include <string>
#include <vector>
using namespace strata::ling32;
using namespace strata::ling32::gpu;
using strata::quant::sk::BlockQ8_1_G64;
using strata::quant::sk::SkCode;
namespace {
int g_fail = 0;
void check(bool ok, const std::string& what) {
std::printf(" %-130s %s\n", what.c_str(), ok ? "ok" : "FAIL");
if (!ok) ++g_fail;
}
template <class T> T* dev(const std::vector<T>& h) {
T* d = nullptr;
cudaMalloc(reinterpret_cast<void**>(&d), std::max<size_t>(h.size() * sizeof(T), 4));
cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice);
return d;
}
template <class T> T* dev_alloc(size_t n) {
T* d = nullptr;
cudaMalloc(reinterpret_cast<void**>(&d), std::max<size_t>(n * sizeof(T), 4));
return d;
}
template <class T> std::vector<T> host(const T* d, size_t n) {
std::vector<T> h(n);
cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost);
return h;
}
bool slurp(const std::string& p, std::vector<uint8_t>& out) {
std::ifstream f(p, std::ios::binary);
if (!f) return false;
out.assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
return true;
}
std::mt19937 g_rng(20260);
float nrm() { static std::normal_distribution<float> nd(0.0f, 1.0f); return nd(g_rng); }
int rint_(int n) { return static_cast<int>(g_rng() % static_cast<unsigned>(n)); }
constexpr int sbb(int code) { return code == 2 ? 70 : code == 3 ? 102 : code == 4 ? 134 : code == 5 ? 166 : code == 6 ? 198 : 262; }
constexpr float khalf(int code) { return code == 2 ? 1.5f : code == 3 ? 3.5f : code == 4 ? 7.5f : code == 5 ? 15.5f : code == 6 ? 31.5f : 0.0f; }
// the q value of weight idx (0..255) of a superblock payload: unsigned (q - kHalf is the weight) for S2..S6, int8 for S8
int qraw(int code, const uint8_t* pl, int idx) {
if (code == 8) return static_cast<int8_t>(pl[idx]);
if (code == 2 || code == 3) {
int v = (pl[idx >> 2] >> (2 * (idx & 3))) & 3;
if (code == 3) v |= ((pl[64 + (idx >> 3)] >> (idx & 7)) & 1) << 2;
return v;
}
const int byte = pl[idx >> 1];
int v = (idx & 1) ? (byte >> 4) : (byte & 15);
if (code == 5) v |= ((pl[128 + (idx >> 3)] >> (idx & 7)) & 1) << 4;
else if (code == 6) v |= ((pl[128 + (idx >> 2)] >> (2 * (idx & 3))) & 3) << 4;
return v;
}
float qval(int code, const uint8_t* pl, int idx) { return code == 8 ? static_cast<float>(qraw(code, pl, idx)) : static_cast<float>(qraw(code, pl, idx)) - khalf(code); }
// a * b + c as one fused multiply-add (bit of g_fmask set) or as a rounded product and a sum: which one the SYCL compiler emits is a property of its contraction setting
int g_fmask = 3, g_dbg = 0;
inline float mad(float a, float b, float c, int bit) {
if (g_fmask & bit) return std::fmaf(a, b, c);
volatile float p = a * b;
return p + c;
}
// CPU model of one output row, float activations (ling32_cpu_expert.cpp): fma chains per lane, then the butterfly
float cpu_row_f(int code, const uint8_t* rowp, int K, const float* x) {
float lane[32] = {};
const int nsb = K / 256;
for (int sb = 0; sb < nsb; ++sb) {
const uint8_t* blk = rowp + static_cast<size_t>(sb) * sbb(code);
const float D = f16_bits_to_f32(static_cast<uint16_t>(blk[0] | (blk[1] << 8)));
for (int l = 0; l < 32; ++l) {
const int g = l >> 3, idx0 = g * 64 + (l & 7) * 8;
float s = 0.0f;
for (int j = 0; j < 8; ++j) s = mad(qval(code, blk + 6, idx0 + j), x[sb * 256 + idx0 + j], s, 1);
const float eff = D * (static_cast<float>(blk[2 + g]) / 255.0f);
lane[l] = mad(eff, s, lane[l], 2);
}
}
for (int o = 16; o >= 1; o >>= 1)
for (int l = 0; l < o; ++l) lane[l] = lane[l] + lane[l + o];
return lane[0];
}
// same, Q8 activations (xq: K/64 blocks): the kernel's float expression with the contraction clang makes of it
float cpu_row_q(int code, const uint8_t* rowp, int K, const Q8Blk* xq) {
float lane[32] = {};
const int nsb = K / 256;
for (int sb = 0; sb < nsb; ++sb) {
const uint8_t* blk = rowp + static_cast<size_t>(sb) * sbb(code);
const float D = f16_bits_to_f32(static_cast<uint16_t>(blk[0] | (blk[1] << 8)));
for (int l = 0; l < 32; ++l) {
const int g = l >> 3, idx0 = g * 64 + (l & 7) * 8;
const Q8Blk& xb = xq[sb * 4 + g];
int isum = 0;
for (int j = 0; j < 8; ++j) isum += qraw(code, blk + 6, idx0 + j) * xb.qs[(l & 7) * 8 + j];
const float eff = D * (static_cast<float>(blk[2 + g]) / 255.0f);
if (code == 8) lane[l] = mad(eff * xb.d, static_cast<float>(isum), lane[l], 2);
else lane[l] = mad(eff, mad(xb.d, static_cast<float>(isum), -((khalf(code) * xb.s) * 0.125f), 1), lane[l], 2);
}
}
for (int o = 16; o >= 1; o >>= 1)
for (int l = 0; l < o; ++l) lane[l] = lane[l] + lane[l + o];
return lane[0];
}
double row_ref_d(int code, const uint8_t* rowp, int K, const float* x, double* mag) {
double r = 0, m = 0;
for (int i = 0; i < K; ++i) {
const uint8_t* blk = rowp + static_cast<size_t>(i / 256) * sbb(code);
const double D = f16_bits_to_f32(static_cast<uint16_t>(blk[0] | (blk[1] << 8)));
const double eff = static_cast<float>(D) * (static_cast<float>(blk[2 + ((i & 255) >> 6)]) / 255.0f);
const double p = eff * qval(code, blk + 6, i & 255) * x[i];
r += p;
m += std::fabs(p);
}
*mag = m;
return r;
}
BlockQ8_1_G64 to_g64(const Q8Blk& q) { BlockQ8_1_G64 b; std::memcpy(b.qs, q.qs, 64); b.d = q.d; b.s = q.s; return b; }
Q8Blk from_g64(const BlockQ8_1_G64& b) { Q8Blk q; std::memcpy(q.qs, b.qs, 64); q.d = b.d; q.s = b.s; return q; }
std::vector<Q8Blk> quant_cpu(const float* x, int n) { // n % 64 == 0
std::vector<BlockQ8_1_G64> t(n / 64);
strata::quant::sk::quantize_q8_1_g64(x, t.data(), n);
std::vector<Q8Blk> r(t.size());
for (size_t i = 0; i < t.size(); ++i) r[i] = from_g64(t[i]);
return r;
}
// ---------------------------------------------------------------------------------------------- slabs
struct Slabs {
std::vector<uint8_t> buf;
std::vector<ExpertDesc> desc; // [layer_base + e]
int layer_base = 0, E = 0, D = 0, I = 0;
size_t stride = 0;
};
std::vector<uint8_t> g_pack[9]; // real superblocks of the codec vectors (codes 4, 5, 6, 8)
void fill_sb(int code, uint8_t* dst) {
if (!g_pack[code].empty() && !std::getenv("L32MOE_RANDSB")) {
const size_t n = g_pack[code].size() / sbb(code);
std::memcpy(dst, g_pack[code].data() + (g_rng() % n) * sbb(code), sbb(code));
return;
}
for (int i = 0; i < sbb(code); ++i) dst[i] = static_cast<uint8_t>(g_rng() & 0xFF); // S2_K / S3_K: random payload, a sane scale
const uint16_t h = static_cast<uint16_t>(0x2800 + g_rng() % 0x0C00);
dst[0] = h & 0xFF; dst[1] = h >> 8;
for (int g = 0; g < 4; ++g) dst[2 + g] = static_cast<uint8_t>(1 + g_rng() % 255);
}
Slabs make_slabs(int E, int D, int I, int layer_base, const std::vector<int>& codes) {
Slabs s;
s.E = E; s.D = D; s.I = I; s.layer_base = layer_base;
const size_t max_body = size_t(2) * I + size_t(2) * I * (D / 256) * 262 + size_t(D) * (I / 256) * 262;
s.stride = (max_body + 16383) / 16384 * 16384;
s.buf.assign(s.stride * E, 0);
s.desc.assign(size_t(layer_base) + E, ExpertDesc{});
for (int e = 0; e < E; ++e) {
const int gc = codes[rint_(int(codes.size()))], dc = codes[rint_(int(codes.size()))];
uint8_t* b = s.buf.data() + s.stride * e;
for (int i = 0; i < I; ++i) { // S_xd: fp16, 0.5 .. 2
const uint16_t h = f32_to_f16_bits(0.5f + 1.5f * (g_rng() % 1000) / 1000.0f);
b[2 * i] = h & 0xFF; b[2 * i + 1] = h >> 8;
}
const size_t gu_sb = size_t(2) * I * (D / 256), dn_sb = size_t(D) * (I / 256);
const size_t dn_off = size_t(2) * I + gu_sb * sbb(gc);
for (size_t i = 0; i < gu_sb; ++i) fill_sb(gc, b + size_t(2) * I + i * sbb(gc));
for (size_t i = 0; i < dn_sb; ++i) fill_sb(dc, b + dn_off + i * sbb(dc));
s.desc[size_t(layer_base) + e] = ExpertDesc{s.stride * e, gc, dc, int(dn_off), int(dn_off + dn_sb * sbb(dc))};
}
return s;
}
const uint8_t* slab_of(const Slabs& s, int e) { return s.buf.data() + s.stride * e; }
std::vector<float> make_act(size_t n) { // each 64-group scaled by 10^-U(0, 3): activations span decades
std::vector<float> x(n);
float grp = 1.0f;
for (size_t i = 0; i < n; ++i) {
if (i % 64 == 0) grp = std::pow(10.0f, -3.0f * std::uniform_real_distribution<float>(0.f, 1.f)(g_rng));
x[i] = std::getenv("L32MOE_XNORM") ? nrm() : nrm() * grp;
}
return x;
}
// ---------------------------------------------------------------------------------------------- the routed experts
void run_experts(const Slabs& S, int N, int top_k, bool null_some, bool use_table, const char* tag) {
const int D = S.D, I = S.I, P = N * top_k, E = S.E;
if (!use_table && null_some) return; // a null entry needs the table
std::vector<int> idx(P);
for (int p = 0; p < P; ++p) idx[p] = rint_(E);
std::vector<const uint8_t*> table(size_t(S.layer_base) + E, nullptr);
uint8_t* dsec = dev(S.buf);
ExpertDesc* ddesc = dev(S.desc);
std::vector<char> is_null(E, 0);
for (int e = 0; e < E; ++e) {
is_null[e] = (null_some && (e % 3 == 1)) ? 1 : 0;
table[size_t(S.layer_base) + e] = is_null[e] ? nullptr : dsec + S.stride * e;
}
const uint8_t* const* dtable = use_table ? reinterpret_cast<const uint8_t* const*>(dev(table)) : nullptr;
int* didx = dev(idx);
const std::vector<float> x = make_act(size_t(N) * D);
float* dx = dev(x);
const std::vector<Q8Blk> xq = quant_cpu(x.data(), N * D);
Q8Blk* dxq = dev(xq);
const float sentinel = 12345.0f;
std::vector<float> fill(size_t(P) * 2 * I, sentinel);
float* gu_f = dev(fill);
float* gu_q = dev(fill);
moe_gu(dsec, ddesc, S.layer_base, didx, N, top_k, E, D, I, dx, false, gu_f, 0, dtable);
moe_gu(dsec, ddesc, S.layer_base, didx, N, top_k, E, D, I, dxq, true, gu_q, 0, dtable);
cudaDeviceSynchronize();
const auto hf = host(gu_f, fill.size()), hq = host(gu_q, fill.size());
if (std::getenv("L32MOE_DBG") && !null_some) { // the trunk GEMV on the same rows of pair 0, for comparison with moe_gu and the CPU model
const ExpertDesc& d0 = S.desc[size_t(S.layer_base) + idx[0]];
float* tg = dev_alloc<float>(2 * I);
gemv_sk(dsec + S.stride * idx[0] + 2 * I, d0.gu_code, 2 * I, D, dx, false, 1, tg, 2 * I, false, 0);
cudaDeviceSynchronize();
const auto tgh = host(tg, 2 * I);
int dt = 0, dm = 0;
for (int r = 0; r < 2 * I; ++r) {
const float cf = cpu_row_f(d0.gu_code, slab_of(S, idx[0]) + 2 * I + size_t(r) * (D / 256) * sbb(d0.gu_code), D, x.data());
dt += std::memcmp(&cf, &tgh[r], 4) != 0;
dm += std::memcmp(&tgh[r], &hf[r], 4) != 0;
}
std::printf(" dbg pair 0 (code %d): trunk gemv_sk differs from the CPU model in %d of %d rows, from moe_gu in %d\n", d0.gu_code, dt, 2 * I, dm);
cudaFree(tg);
}
size_t bad_f = 0, bad_q = 0, written = 0, wrong_null = 0;
double e_f = 0, e_lib = 0;
for (int p = 0; p < P; ++p) {
const int e = idx[p];
const ExpertDesc& d = S.desc[size_t(S.layer_base) + e];
const uint8_t* slab = slab_of(S, e);
for (int r = 0; r < 2 * I; ++r) {
const size_t at = size_t(p) * 2 * I + r;
if (is_null[e]) { wrong_null += (hf[at] != sentinel) + (hq[at] != sentinel); continue; }
const uint8_t* rowp = slab + 2 * I + size_t(r) * (D / 256) * sbb(d.gu_code);
const float cf = cpu_row_f(d.gu_code, rowp, D, x.data() + size_t(p / top_k) * D);
const float cq = cpu_row_q(d.gu_code, rowp, D, xq.data() + size_t(p / top_k) * (D / 64));
bad_f += std::memcmp(&cf, &hf[at], 4) != 0;
bad_q += std::memcmp(&cq, &hq[at], 4) != 0;
if (std::getenv("L32MOE_DBG") && g_dbg < 12 && std::memcmp(&cf, &hf[at], 4) != 0) {
double mag;
const double ref = row_ref_d(d.gu_code, rowp, D, x.data() + size_t(p / top_k) * D, &mag);
std::printf(" dbg gu code %d row %d: gpu %.9g cpu %.9g double %.9g\n", d.gu_code, r, hf[at], cf, ref);
++g_dbg;
}
++written;
if (r % 17 == 0) {
double mag;
const double ref = row_ref_d(d.gu_code, rowp, D, x.data() + size_t(p / top_k) * D, &mag);
e_f = std::fmax(e_f, std::fabs(hf[at] - ref) / (mag + 1e-30));
std::vector<BlockQ8_1_G64> g(D / 64);
for (int i = 0; i < D / 64; ++i) g[i] = to_g64(xq[size_t(p / top_k) * (D / 64) + i]);
if (d.gu_code >= 4) e_lib = std::fmax(e_lib, std::fabs(hq[at] - strata::quant::sk::dot_sk_q8_1_row(rowp, static_cast<SkCode>(d.gu_code), g.data(), D)) / (mag + 1e-30));
}
}
}
const std::string t = std::string(tag) + " N=" + std::to_string(N) + " top_k=" + std::to_string(top_k) + " D=" + std::to_string(D) + " I=" + std::to_string(I) + (null_some ? " (null entries)" : "") + (use_table ? " [table]" : " [sec4+off]");
check(bad_f == 0 && wrong_null == 0, "moe_gu float acts: " + t + ": " + std::to_string(written) + " rows, " + std::to_string(bad_f) + " differ from the CPU model, " + std::to_string(wrong_null) + " null-entry writes; vs double " + std::to_string(e_f));
check(bad_q == 0 && e_lib < 2e-5, "moe_gu Q8 acts: " + t + ": " + std::to_string(bad_q) + " differ from the CPU model; vs dot_sk_q8_1_row " + std::to_string(e_lib));
// ---- moe_act on those gu rows (float and Q8 output) and moe_dn on its output
const float lim = (N % 2) ? 7.0f : 0.0f;
const bool post = (N % 3) != 0;
std::vector<float> gu_in(size_t(P) * 2 * I);
for (auto& v : gu_in) v = nrm() * 2.5f;
float* dgu = dev(gu_in);
std::vector<float> actfill(size_t(P) * I, sentinel);
float* act_f = dev(actfill);
std::vector<Q8Blk> qfill(size_t(P) * (I / 64));
for (auto& b : qfill) { std::memset(b.qs, 0x55, 64); b.d = sentinel; b.s = sentinel; }
Q8Blk* act_q = dev(qfill);
moe_act(dsec, ddesc, S.layer_base, didx, dgu, N, top_k, I, lim, post, act_f, false, 0, dtable);
moe_act(dsec, ddesc, S.layer_base, didx, dgu, N, top_k, I, lim, post, act_q, true, 0, dtable);
cudaDeviceSynchronize();
const auto af = host(act_f, actfill.size());
const auto aq = host(act_q, qfill.size());
double e_act = 0;
size_t qbad = 0, nwrong = 0;
for (int p = 0; p < P; ++p) {
const int e = idx[p];
const uint8_t* slab = slab_of(S, e);
if (is_null[e]) {
for (int i = 0; i < I; ++i) nwrong += af[size_t(p) * I + i] != sentinel;
for (int bq = 0; bq < I / 64; ++bq) nwrong += aq[size_t(p) * (I / 64) + bq].d != sentinel;
continue;
}
std::vector<float> v(I);
for (int i = 0; i < I; ++i) {
const float g = gu_in[size_t(p) * 2 * I + i], u = gu_in[size_t(p) * 2 * I + I + i];
auto silu = [](float a) { return a / (1.0f + std::exp(-a)); };
float r;
if (lim > 0.0f) {
const float gg = post ? std::fmin(silu(g), lim) : silu(std::fmin(g, lim));
r = gg * std::fmax(-lim, std::fmin(u, lim));
} else r = silu(g) * u;
const uint16_t h = static_cast<uint16_t>(slab[2 * i] | (slab[2 * i + 1] << 8));
v[i] = r / f16_bits_to_f32(h);
}
fwht128_f32(v.data(), v.data(), I);
double rms = 0;
for (float a : v) rms += double(a) * a;
rms = std::sqrt(rms / I) + 1e-30;
for (int i = 0; i < I; ++i) e_act = std::fmax(e_act, std::fabs(af[size_t(p) * I + i] - v[i]) / rms);
// the Q8 output = the CPU quantiser applied to the kernel's own float output
const std::vector<Q8Blk> ref = quant_cpu(af.data() + size_t(p) * I, I);
for (int bq = 0; bq < I / 64; ++bq) {
const Q8Blk& g = aq[size_t(p) * (I / 64) + bq];
qbad += std::memcmp(g.qs, ref[bq].qs, 64) != 0 || g.d != ref[bq].d || std::fabs(g.s - ref[bq].s) > 1e-6f * (1 + std::fabs(ref[bq].s));
}
}
check(e_act < 2e-5 && nwrong == 0 && qbad == 0, "moe_act float vs CPU (rel to rms) " + std::to_string(e_act) + ", Q8 blocks differing from the CPU quantiser of the float output: " + std::to_string(qbad) + ", null-entry writes " + std::to_string(nwrong) + " [lim " + std::to_string(lim) + (post ? " post_silu" : " pre") + "]");
// ---- moe_dn: float and Q8 activations, one activation row per pair (I wide)
const std::vector<float> a2 = make_act(size_t(P) * I);
const std::vector<Q8Blk> a2q = quant_cpu(a2.data(), P * I);
float* da2 = dev(a2);
Q8Blk* da2q = dev(a2q);
std::vector<float> yfill(size_t(P) * D, sentinel);
float* ye_f = dev(yfill);
float* ye_q = dev(yfill);
moe_dn(dsec, ddesc, S.layer_base, didx, N, top_k, E, D, I, da2, false, ye_f, 0, dtable);
moe_dn(dsec, ddesc, S.layer_base, didx, N, top_k, E, D, I, da2q, true, ye_q, 0, dtable);
cudaDeviceSynchronize();
const auto yf = host(ye_f, yfill.size()), yq = host(ye_q, yfill.size());
size_t dbad_f = 0, dbad_q = 0, dwrong = 0, drows = 0;
double d_lib = 0, d_dbl = 0;
for (int p = 0; p < P; ++p) {
const int e = idx[p];
const ExpertDesc& d = S.desc[size_t(S.layer_base) + e];
const uint8_t* slab = slab_of(S, e);
for (int r = 0; r < D; ++r) {
const size_t at = size_t(p) * D + r;
if (is_null[e]) { dwrong += (yf[at] != sentinel) + (yq[at] != sentinel); continue; }
const uint8_t* rowp = slab + d.dn_off + size_t(r) * (I / 256) * sbb(d.dn_code);
const float cf = cpu_row_f(d.dn_code, rowp, I, a2.data() + size_t(p) * I);
const float cq = cpu_row_q(d.dn_code, rowp, I, a2q.data() + size_t(p) * (I / 64));
dbad_f += std::memcmp(&cf, &yf[at], 4) != 0;
dbad_q += std::memcmp(&cq, &yq[at], 4) != 0;
++drows;
if (r % 29 == 0) {
double mag;
const double ref = row_ref_d(d.dn_code, rowp, I, a2.data() + size_t(p) * I, &mag);
d_dbl = std::fmax(d_dbl, std::fabs(yf[at] - ref) / (mag + 1e-30));
std::vector<BlockQ8_1_G64> g(I / 64);
for (int i = 0; i < I / 64; ++i) g[i] = to_g64(a2q[size_t(p) * (I / 64) + i]);
if (d.dn_code >= 4) d_lib = std::fmax(d_lib, std::fabs(yq[at] - strata::quant::sk::dot_sk_q8_1_row(rowp, static_cast<SkCode>(d.dn_code), g.data(), I)) / (mag + 1e-30));
}
}
}
check(dbad_f == 0 && dwrong == 0 && d_dbl < 2e-5, "moe_dn float acts: " + t + ": " + std::to_string(drows) + " rows, " + std::to_string(dbad_f) + " differ from the CPU model, null-entry writes " + std::to_string(dwrong) + "; vs double " + std::to_string(d_dbl));
check(dbad_q == 0 && d_lib < 2e-5, "moe_dn Q8 acts: " + t + ": " + std::to_string(dbad_q) + " differ from the CPU model; vs dot_sk_q8_1_row " + std::to_string(d_lib));
// ---- grouped by expert (float activations only): equal to moe_gu / moe_dn bit for bit
if (use_table || !null_some) {
MoeTcWork w;
const bool ok = moe_tc_alloc(w, P, E);
std::vector<float> g_fill(size_t(P) * 2 * I, sentinel);
float* tgu = dev(g_fill);
float* tye = dev(yfill);
float* gu_ref = dev(g_fill);
float* ye_ref = dev(yfill);
moe_tc_route(w, didx, P, 0);
moe_tc_gu(w, dsec, ddesc, S.layer_base, dtable, P, top_k, D, I, dx, tgu, 0);
moe_tc_dn(w, dsec, ddesc, S.layer_base, dtable, P, top_k, D, I, da2, tye, 0);
moe_gu(dsec, ddesc, S.layer_base, didx, N, top_k, E, D, I, dx, false, gu_ref, 0, dtable);
moe_dn(dsec, ddesc, S.layer_base, didx, N, top_k, E, D, I, da2, false, ye_ref, 0, dtable);
cudaDeviceSynchronize();
const auto a = host(tgu, g_fill.size()), b = host(gu_ref, g_fill.size()), c = host(tye, yfill.size()), d = host(ye_ref, yfill.size());
const bool same = std::memcmp(a.data(), b.data(), a.size() * 4) == 0 && std::memcmp(c.data(), d.data(), c.size() * 4) == 0;
auto rel_err = [&](const std::vector<float>& u, const std::vector<float>& v) { // max |u - v| of the written entries, relative to their rms
double e = 0, r = 0;
size_t n = 0;
for (size_t i = 0; i < u.size(); ++i) {
if (v[i] == sentinel && u[i] == sentinel) continue;
e = std::fmax(e, std::fabs(double(u[i]) - v[i]));
r += double(v[i]) * v[i];
++n;
}
return e / std::sqrt(r / std::max<size_t>(n, 1) + 1e-30);
};
const double e_tg = rel_err(a, b), e_td = rel_err(c, d);
check(ok && (same || (e_tg < 2e-5 && e_td < 2e-5)), std::string("moe_tc_route/gu/dn (grouped by expert) vs moe_gu / moe_dn: ") + (same ? "bit for bit" : "max error " + std::to_string(e_tg) + " / " + std::to_string(e_td) + " of the rms (XMX tiles)") + ": " + t);
moe_tc_free(w);
cudaFree(tgu); cudaFree(tye); cudaFree(gu_ref); cudaFree(ye_ref);
}
for (void* p : std::initializer_list<void*>{dsec, ddesc, didx, dx, dxq, gu_f, gu_q, dgu, act_f, act_q, da2, da2q, ye_f, ye_q}) cudaFree(p);
if (dtable) cudaFree(const_cast<uint8_t**>(reinterpret_cast<const uint8_t* const*>(dtable)));
}
// ---------------------------------------------------------------------------------------------- ALF-LB router
struct RouteRef {
std::vector<int> idx;
std::vector<float> w;
};
RouteRef route_cpu(const float* logits, const float* add_bias, const float* sel_bias, int E, int n_group, int topk_group, int top_n, float scale, int N) {
RouteRef r;
r.idx.resize(size_t(N) * top_n);
r.w.assign(size_t(N) * top_n, 0.0f);
const int per = E / n_group;
for (int t = 0; t < N; ++t) {
std::vector<float> sig(E), sc(E);
for (int e = 0; e < E; ++e) {
const float z = logits[size_t(t) * E + e] + (add_bias ? add_bias[e] : 0.0f);
sig[e] = 1.0f / (1.0f + std::exp(-z));
sc[e] = sig[e] + sel_bias[e];
}
std::vector<float> gs(n_group);
for (int g = 0; g < n_group; ++g) {
float m1 = -3.4e38f, m2 = -3.4e38f;
for (int i = 0; i < per; ++i) {
const float v = sc[g * per + i];
if (v > m1) { m2 = m1; m1 = v; } else if (v > m2) m2 = v;
}
gs[g] = m1 + m2;
}
std::vector<int> keep(n_group, 0);
for (int k = 0; k < topk_group; ++k) {
int best = -1;
for (int g = 0; g < n_group; ++g)
if (!keep[g] && (best < 0 || gs[g] > gs[best])) best = g;
keep[best] = 1;
}
std::vector<int> cand;
for (int e = 0; e < E; ++e)
if (keep[e / per]) cand.push_back(e);
std::sort(cand.begin(), cand.end(), [&](int a, int b) { return sc[a] > sc[b] || (sc[a] == sc[b] && a < b); });
float tot = 0.0f;
for (int i = 0; i < top_n; ++i) { r.idx[size_t(t) * top_n + i] = cand[i]; tot += sig[cand[i]]; }
for (int i = 0; i < top_n; ++i) r.w[size_t(t) * top_n + i] = sig[cand[i]] * (scale / (tot + 1e-20f));
}
return r;
}
void run_router(int E, int n_group, int topk_group, int top_n, int N, bool weights, bool add_b, bool ties) {
std::vector<float> lg(size_t(N) * E), ab(E), sb(E);
for (auto& v : lg) v = ties ? float(rint_(33) - 16) * 0.25f : nrm() * 2.0f; // ties: logits on a 0.25 grid, many equal scores
for (auto& v : ab) v = nrm() * 0.3f;
for (auto& v : sb) v = ties ? 0.0f : nrm() * 0.05f;
if (ties)
for (int e = 0; e < E; e += 5) sb[e] = 0.015625f * float(rint_(5));
float *dl = dev(lg), *dab = dev(ab), *dsb = dev(sb);
const float scale = 2.5f;
int* oi = dev_alloc<int>(size_t(N) * top_n);
float* ow = dev_alloc<float>(size_t(N) * top_n);
cudaMemset(ow, 0, size_t(N) * top_n * 4);
alflb_route(dl, add_b ? dab : nullptr, dsb, E, n_group, topk_group, top_n, scale, weights, oi, ow, N, 0);
cudaDeviceSynchronize();
const auto gi = host(oi, size_t(N) * top_n);
const auto gw = host(ow, size_t(N) * top_n);
const RouteRef ref = route_cpu(lg.data(), add_b ? ab.data() : nullptr, sb.data(), E, n_group, topk_group, top_n, scale, N);
size_t bad_i = 0;
double e_w = 0;
for (size_t i = 0; i < gi.size(); ++i) {
bad_i += gi[i] != ref.idx[i];
if (weights) e_w = std::fmax(e_w, std::fabs(gw[i] - ref.w[i]) / (std::fabs(ref.w[i]) + 1e-30));
}
// the reference kernel (one warp per token) and the parallel one agree
g_alflb_ref = 1;
int* oi2 = dev_alloc<int>(size_t(N) * top_n);
alflb_route(dl, add_b ? dab : nullptr, dsb, E, n_group, topk_group, top_n, scale, weights, oi2, ow, N, 0);
g_alflb_ref = 0;
cudaDeviceSynchronize();
const auto gi2 = host(oi2, size_t(N) * top_n);
const bool same = gi2 == gi;
check(bad_i == 0 && e_w < 1e-5 && same, "alflb_route E=" + std::to_string(E) + " groups " + std::to_string(n_group) + "/" + std::to_string(topk_group) + " top_n=" + std::to_string(top_n) + " N=" + std::to_string(N) +
(weights ? " weights" : " no weights") + (add_b ? " +add_bias" : "") + (ties ? " ties" : "") + ": " + std::to_string(bad_i) + " ids differ from the CPU, weights rel " + std::to_string(e_w) +
", ref kernel == par kernel: " + (same ? "yes" : "NO"));
cudaFree(dl); cudaFree(dab); cudaFree(dsb); cudaFree(oi); cudaFree(ow); cudaFree(oi2);
}
// ---------------------------------------------------------------------------------------------- swiglu / shared expert / combine
// ---------------------------------------------------------------------------------------------- route + grouped experts at the real batch sizes
// moe_tc_route counts and permutes the pairs by expert with work-group atomics in shared memory; this checks it (and the grouped kernels behind it) at the sizes of real prefill chunks: P = N * 8 pairs
// over E = 512 experts with uneven routing (a hot expert with 100+ pairs, a few experts without any, the last expert used), against a host histogram / permutation check and against the per-pair kernels.
struct BigRoute {
Slabs S;
uint8_t* dsec = nullptr;
ExpertDesc* ddesc = nullptr;
};
void run_big_route(BigRoute& B, int N, int top_k, int hot_pct, const char* tag) {
const Slabs& S = B.S;
const int D = S.D, I = S.I, P = N * top_k, E = S.E;
std::vector<int> idx(P), hist(E, 0);
for (int p = 0; p < P; ++p) {
const int r = rint_(100);
int e = rint_(E);
if (r < hot_pct) e = 3; // one hot expert
else if (r < hot_pct + 2) e = E - 1; // the last expert
else if (e >= 40 && e < 60) e += 20; // experts 40 .. 59 stay unused
idx[p] = e;
++hist[e];
}
int* didx = dev(idx);
const std::vector<float> x = make_act(size_t(N) * D), a2 = make_act(size_t(P) * I);
float *dx = dev(x), *da2 = dev(a2);
MoeTcWork w;
const bool ok = moe_tc_alloc(w, P, E);
moe_tc_route(w, didx, P, 0);
cudaDeviceSynchronize();
// the route tables
const auto perm = host(w.perm, P), est = host(w.exp_start, E), ecnt = host(w.exp_cnt, E), tile_e = host(w.tile_e, w.max_tiles), tile_j = host(w.tile_j, w.max_tiles);
const int ntiles = host(w.ntiles, 1)[0];
bool tabs = ok;
std::vector<char> seen(P, 0);
int start_expect = 0, mx = 0;
for (int e = 0; e < E && tabs; ++e) {
tabs = ecnt[e] == hist[e] && est[e] == start_expect;
start_expect += hist[e];
mx = std::max(mx, hist[e]);
for (int i = 0; tabs && i < ecnt[e]; ++i) {
const int p = perm[est[e] + i];
tabs = p >= 0 && p < P && !seen[p] && idx[p] == e;
if (tabs) seen[p] = 1;
}
}
for (int p = 0; tabs && p < P; ++p) tabs = seen[p] != 0;
// tile list: every expert with pairs has tiles j = 0 .. ceil(cnt / tn) - 1 for one tile width tn (16 or 32), in expert order
int tn_found = 0;
for (int tn : {16, 32}) {
int expect = 0;
for (int e = 0; e < E; ++e) expect += (hist[e] + tn - 1) / tn;
if (expect != ntiles) continue;
bool good = true;
int t = 0;
for (int e = 0; e < E && good; ++e)
for (int j = 0; j < (hist[e] + tn - 1) / tn && good; ++j, ++t) good = t < w.max_tiles && tile_e[t] == e && tile_j[t] == j;
if (good) { tn_found = tn; break; }
}
check(tabs && tn_found != 0, std::string("moe_tc_route ") + tag + " P=" + std::to_string(P) + " E=" + std::to_string(E) + ": counts, starts and the permutation by expert exact (largest expert " + std::to_string(mx) + " pairs), " +
std::to_string(ntiles) + " tiles of " + std::to_string(tn_found) + " pairs");
// the grouped GEMMs against the per-pair kernels
const float sentinel = 12345.0f;
std::vector<float> gfill(size_t(P) * 2 * I, sentinel), yfill(size_t(P) * D, sentinel);
float *tgu = dev(gfill), *tye = dev(yfill), *gref = dev(gfill), *yref = dev(yfill);
moe_tc_gu(w, B.dsec, B.ddesc, S.layer_base, nullptr, P, top_k, D, I, dx, tgu, 0);
moe_tc_dn(w, B.dsec, B.ddesc, S.layer_base, nullptr, P, top_k, D, I, da2, tye, 0);
moe_gu(B.dsec, B.ddesc, S.layer_base, didx, N, top_k, E, D, I, dx, false, gref, 0, nullptr);
moe_dn(B.dsec, B.ddesc, S.layer_base, didx, N, top_k, E, D, I, da2, false, yref, 0, nullptr);
cudaDeviceSynchronize();
const auto a = host(tgu, gfill.size()), b = host(gref, gfill.size()), c = host(tye, yfill.size()), d = host(yref, yfill.size());
auto rel = [&](const std::vector<float>& u, const std::vector<float>& v) {
double e = 0, r = 0;
size_t unwritten = 0;
for (size_t i = 0; i < u.size(); ++i) {
unwritten += u[i] == sentinel;
e = std::fmax(e, std::fabs(double(u[i]) - v[i]));
r += double(v[i]) * v[i];
}
return std::make_pair(e / std::sqrt(r / u.size() + 1e-30), unwritten);
};
const auto rg = rel(a, b), rd = rel(c, d);
const bool same = std::memcmp(a.data(), b.data(), a.size() * 4) == 0 && std::memcmp(c.data(), d.data(), c.size() * 4) == 0;
check(rg.second == 0 && rd.second == 0 && (same || (rg.first < 4e-5 && rd.first < 4e-5)), // the max over millions of outputs: 2.0e-5 at every size (the CUDA model test allows 5e-5)
std::string("grouped gate/up + down ") + tag + " P=" + std::to_string(P) + " vs the per-pair kernels: " + (same ? "bit for bit" : "max error " + std::to_string(rg.first) + " / " + std::to_string(rd.first) + " of the rms") + ", unwritten pairs " +
std::to_string(rg.second + rd.second));
moe_tc_free(w);
for (void* q : std::initializer_list<void*>{didx, dx, da2, tgu, tye, gref, yref}) cudaFree(q);
}
void run_swiglu_and_combine() {
{ // swiglu with strides
const int N = 5, I = 700, gs = 1400, us = 1000, os = 800;
std::vector<float> g(size_t(N) * gs), u(size_t(N) * us);
for (auto& v : g) v = nrm() * 3.0f;
for (auto& v : u) v = nrm() * 3.0f;
float *dg = dev(g), *du = dev(u), *dout = dev_alloc<float>(size_t(N) * os);
for (float lim : {0.0f, 7.0f})
for (int post = 0; post < 2; ++post) {
cudaMemset(dout, 0, size_t(N) * os * 4);
swiglu(dg, gs, du, us, lim, post != 0, dout, os, N, I, 0);
cudaDeviceSynchronize();
const auto o = host(dout, size_t(N) * os);
double e = 0;
for (int t = 0; t < N; ++t)
for (int i = 0; i < I; ++i) {
const float a = g[size_t(t) * gs + i], b = u[size_t(t) * us + i];
auto silu = [](float x) { return x / (1.0f + std::exp(-x)); };
float r;
if (lim > 0.0f) r = (post ? std::fmin(silu(a), lim) : silu(std::fmin(a, lim))) * std::fmax(-lim, std::fmin(b, lim));
else r = silu(a) * b;
e = std::fmax(e, std::fabs(o[size_t(t) * os + i] - r) / (std::fabs(r) + 1e-3));
}
check(e < 2e-6, std::string("swiglu N=5 I=700 lim=") + std::to_string(lim) + (post ? " post_silu" : " pre") + ": max rel error " + std::to_string(e));
}
cudaFree(dg); cudaFree(du); cudaFree(dout);
}
{ // gemv2_swiglu_s8: both S8_K matrices in one pass
const int rows = 70, K = 768;
const int nsb = K / 256;
std::vector<uint8_t> Wg(size_t(rows) * nsb * 262), Wu(size_t(rows) * nsb * 262);
for (size_t i = 0; i < size_t(rows) * nsb; ++i) { fill_sb(8, Wg.data() + i * 262); fill_sb(8, Wu.data() + i * 262); }
uint8_t *dWg = dev(Wg), *dWu = dev(Wu);
for (int N : {1, 3, 4, 7, 8, 16}) {
const std::vector<float> x = make_act(size_t(N) * K);
float* dx = dev(x);
const int os = rows + 3;
for (float lim : {0.0f, 7.0f}) {
float* dout = dev_alloc<float>(size_t(N) * os);
cudaMemset(dout, 0, size_t(N) * os * 4);
gemv2_swiglu_s8(dWg, dWu, rows, K, dx, N, lim, true, dout, os, 0);
cudaDeviceSynchronize();
const auto o = host(dout, size_t(N) * os);
double e = 0;
for (int t = 0; t < N; ++t)
for (int r = 0; r < rows; ++r) {
const float a = cpu_row_f(8, Wg.data() + size_t(r) * nsb * 262, K, x.data() + size_t(t) * K);
const float b = cpu_row_f(8, Wu.data() + size_t(r) * nsb * 262, K, x.data() + size_t(t) * K);
auto silu = [](float v) { return v / (1.0f + std::exp(-v)); };
const float ref = lim > 0 ? std::fmin(silu(a), lim) * std::fmax(-lim, std::fmin(b, lim)) : silu(a) * b;
e = std::fmax(e, std::fabs(o[size_t(t) * os + r] - ref) / (std::fabs(ref) + 0.05)); // the outputs are sums of terms of both signs: the error is relative to the typical output size
}
check(e < 1e-5, "gemv2_swiglu_s8 [70 x 768] N=" + std::to_string(N) + " lim=" + std::to_string(lim) + ": max rel error vs the CPU model " + std::to_string(e));
cudaFree(dout);
}
cudaFree(dx);
}
cudaFree(dWg); cudaFree(dWu);
}
{ // moe_combine and moe_combine_norm
for (int N : {1, 3, 16}) {
const int top_k = 8, D = 2560;
std::vector<float> x(size_t(N) * D), ye(size_t(N) * top_k * D), w(size_t(N) * top_k), ysh(size_t(N) * D), gamma(D);
for (auto& v : x) v = nrm();
for (auto& v : ye) v = nrm() * 0.5f;
for (auto& v : w) v = 0.05f + 0.2f * (g_rng() % 1000) / 1000.0f;
for (auto& v : ysh) v = nrm() * 0.3f;
for (auto& v : gamma) v = 1.0f + 0.1f * nrm();
float *dye = dev(ye), *dw = dev(w), *dysh = dev(ysh), *dg = dev(gamma);
for (int with_sh = 0; with_sh < 2; ++with_sh) {
float* dx1 = dev(x);
float* dx2 = dev(x);
float* dh = dev_alloc<float>(x.size());
float* dh2 = dev_alloc<float>(x.size());
moe_combine(dx1, dye, dw, N, top_k, D, 0, with_sh ? dysh : nullptr);
moe_combine_norm(dx2, dye, dw, N, top_k, D, 0, with_sh ? dysh : nullptr, dg, 1e-6f, dh);
rmsnorm(dx1, dg, 1e-6f, dh2, N, D, 0);
cudaDeviceSynchronize();
const auto o1 = host(dx1, x.size()), o2 = host(dx2, x.size()), h1 = host(dh, x.size()), h2 = host(dh2, x.size());
double e = 0;
for (int t = 0; t < N; ++t)
for (int d = 0; d < D; ++d) {
float s = 0.0f;
for (int k = 0; k < top_k; ++k) s = std::fmaf(w[t * top_k + k], ye[(size_t(t) * top_k + k) * D + d], s);
const size_t at = size_t(t) * D + d;
const float ref = (with_sh ? x[at] + ysh[at] : x[at]) + s;
e = std::fmax(e, std::fabs(o1[at] - ref) / (std::fabs(ref) + 1e-3));
}
check(e < 1e-6, "moe_combine N=" + std::to_string(N) + (with_sh ? " + shared" : "") + ": max rel error vs the CPU " + std::to_string(e));
check(std::memcmp(o1.data(), o2.data(), o1.size() * 4) == 0 && std::memcmp(h1.data(), h2.data(), h1.size() * 4) == 0,
"moe_combine_norm N=" + std::to_string(N) + (with_sh ? " + shared" : "") + ": x and h bit-identical to moe_combine + rmsnorm");
cudaFree(dx1); cudaFree(dx2); cudaFree(dh); cudaFree(dh2);
}
cudaFree(dye); cudaFree(dw); cudaFree(dysh); cudaFree(dg);
}
}
}
} // namespace
// ---------------------------------------------------------------------------------------------- the trunk GEMM (gemm_sk_tc: XMX tiles where the device has them) against the float GEMV
std::vector<uint8_t> make_matrix(int code, int rows, int K) {
std::vector<uint8_t> W(size_t(rows) * (K / 256) * sbb(code));
for (size_t i = 0; i < size_t(rows) * (K / 256); ++i) fill_sb(code, W.data() + i * sbb(code));
return W;
}
void run_trunk(int code, int rows, int K, int N, bool accumulate) {
const std::vector<uint8_t> W = make_matrix(code, rows, K);
const std::vector<float> x = make_act(size_t(N) * K);
std::vector<float> o0(size_t(N) * rows);
for (auto& v : o0) v = nrm();
uint8_t* dW = dev(W);
float *dx = dev(x), *dref = dev(o0), *dout = dev(o0);
gemv_sk(dW, code, rows, K, dx, false, N, dref, rows, accumulate, 0);
gemm_sk_tc(dW, code, rows, K, dx, N, dout, rows, accumulate, 0);
cudaDeviceSynchronize();
const auto a = host(dref, o0.size()), b = host(dout, o0.size());
double e = 0, r = 0;
for (size_t i = 0; i < a.size(); ++i) { e = std::fmax(e, std::fabs(double(a[i]) - b[i])); r += double(a[i]) * a[i]; }
const double rel = e / std::sqrt(r / a.size() + 1e-30);
const bool same = std::memcmp(a.data(), b.data(), a.size() * 4) == 0;
check(rel < 2e-5, "trunk GEMM S" + std::to_string(code) + " [" + std::to_string(rows) + " x " + std::to_string(K) + "] N=" + std::to_string(N) + (accumulate ? " accumulate" : "") + " vs the float GEMV: " +
(same ? "bit for bit" : "max error " + std::to_string(rel) + " of the rms"));
cudaFree(dW); cudaFree(dx); cudaFree(dref); cudaFree(dout);
}
// L32MOE_BENCH=trunk: the prefill GEMMs of the trunk at the real shapes (S8_K), scalar float GEMV vs gemm_sk_tc
void bench_trunk() {
struct Shape { const char* name; int rows, K; };
const Shape shapes[] = {{"KDA qkvfg [20480 x 2560]", 20480, 2560}, {"KDA/MLA o [2560 x 4096]", 2560, 4096}, {"MLA q [6144 x 2560]", 6144, 2560}, {"[2560 x 768]", 2560, 768},
{"dense / shared up-gate [6144 x 2560]", 6144, 2560}, {"dense down [2560 x 6144]", 2560, 6144}};
for (const Shape& sh : shapes) {
const std::vector<uint8_t> W = make_matrix(8, sh.rows, sh.K);
uint8_t* dW = dev(W);
for (int N : {32, 128, 512, 2048}) {
const std::vector<float> x = make_act(size_t(N) * sh.K);
float *dx = dev(x), *dout = dev_alloc<float>(size_t(N) * sh.rows);
auto time_ms = [&](auto&& fn) {
fn();
cudaDeviceSynchronize();
const auto t0 = std::chrono::steady_clock::now();
const int reps = N >= 512 ? 3 : 8;
for (int i = 0; i < reps; ++i) fn();
cudaDeviceSynchronize();
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count() / reps;
};
const double t_sc = time_ms([&] { gemv_sk(dW, 8, sh.rows, sh.K, dx, false, N, dout, sh.rows, false, 0); });
const double t_xm = time_ms([&] { gemm_sk_tc(dW, 8, sh.rows, sh.K, dx, N, dout, sh.rows, false, 0); });
const double fl = 2.0 * N * sh.rows * sh.K;
std::printf(" S8 %-38s N=%4d: scalar GEMV %8.3f ms = %6.2f TFLOP/s, gemm_sk_tc %8.3f ms = %6.2f TFLOP/s (%.2fx)\n", sh.name, N, t_sc, fl / (t_sc * 1e9), t_xm, fl / (t_xm * 1e9), t_sc / t_xm);
cudaFree(dx); cudaFree(dout);
}
cudaFree(dW);
}
}
// L32MOE_BENCH=decode: the decode path (1 and 4 tokens, top_k 8): moe_gu / moe_act / moe_dn with float and Q8 activations, rotating expert sets (weights from DRAM), GB/s of weights read.
void bench_decode() {
const int D = 2560, I = 768, E = 64, top_k = 8, nsets = 8;
for (int code : {5, 4, 6, 8}) {
const Slabs S = make_slabs(E, D, I, 0, {code});
uint8_t* dsec = dev(S.buf);
ExpertDesc* ddesc = dev(S.desc);
const double gu_bytes = double(2) * I * (D / 256) * sbb(code), dn_bytes = double(D) * (I / 256) * sbb(code);
for (int N : {1, 2, 4}) {
const int P = N * top_k;
std::vector<int> idx(size_t(nsets) * P);
for (int s = 0; s < nsets; ++s)
for (int p = 0; p < P; ++p) idx[size_t(s) * P + p] = (s * 8 + p) % E; /* distinct experts within a set, the sets cover all 64 */
int* didx = dev(idx);
const std::vector<float> x = make_act(size_t(N) * D), a2 = make_act(size_t(P) * I);
float *dx = dev(x), *da2 = dev(a2), *gu = dev_alloc<float>(size_t(P) * 2 * I), *ye = dev_alloc<float>(size_t(P) * D);
Q8Blk *dxq = dev(quant_cpu(x.data(), N * D)), *da2q = dev(quant_cpu(a2.data(), P * I));
auto time_ms = [&](auto&& fn) {
for (int s = 0; s < nsets; ++s) fn(s);
cudaDeviceSynchronize();
const auto t0 = std::chrono::steady_clock::now();
const int reps = 4;
for (int i = 0; i < reps * nsets; ++i) fn(i % nsets);
cudaDeviceSynchronize();
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count() / (reps * nsets);
};
const double t_gu = time_ms([&](int s) { moe_gu(dsec, ddesc, 0, didx + size_t(s) * P, N, top_k, E, D, I, dx, false, gu, 0, nullptr); });
const double t_dn = time_ms([&](int s) { moe_dn(dsec, ddesc, 0, didx + size_t(s) * P, N, top_k, E, D, I, da2, false, ye, 0, nullptr); });
const double t_guq = time_ms([&](int s) { moe_gu(dsec, ddesc, 0, didx + size_t(s) * P, N, top_k, E, D, I, dxq, true, gu, 0, nullptr); });
const double t_dnq = time_ms([&](int s) { moe_dn(dsec, ddesc, 0, didx + size_t(s) * P, N, top_k, E, D, I, da2q, true, ye, 0, nullptr); });
std::printf(" S%d N=%d (P=%2d): gate/up float %7.3f ms = %6.1f GB/s, down float %7.3f ms = %6.1f GB/s | Q8 acts: gate/up %7.3f ms = %6.1f GB/s, down %7.3f ms = %6.1f GB/s\n", code, N, P, t_gu, P * gu_bytes / (t_gu * 1e6), t_dn,
P * dn_bytes / (t_dn * 1e6), t_guq, P * gu_bytes / (t_guq * 1e6), t_dnq, P * dn_bytes / (t_dnq * 1e6));
for (void* p : std::initializer_list<void*>{didx, dx, da2, gu, ye, dxq, da2q}) cudaFree(p);
}
cudaFree(dsec); cudaFree(ddesc);
}
}
// L32MOE_BENCH=1: timing of the batch paths at the real shape (not part of the pass / fail run). Slabs of one code, pairs spread evenly over E experts.
void bench_batches() {
const int D = 2560, I = 768, E = 64, top_k = 8;
const double flop_pair = 2.0 * 3.0 * D * I; // gate + up + down
for (int code : {5, 8}) {
const Slabs S = make_slabs(E, D, I, 0, {code});
uint8_t* dsec = dev(S.buf);
ExpertDesc* ddesc = dev(S.desc);
for (int per : {4, 16, 64}) { // pairs per expert
const int P = per * E, N = P / top_k;
std::vector<int> idx(P);
for (int p = 0; p < P; ++p) idx[p] = p % E;
int* didx = dev(idx);
const std::vector<float> x = make_act(size_t(N) * D), a2 = make_act(size_t(P) * I);
float *dx = dev(x), *da2 = dev(a2), *gu = dev_alloc<float>(size_t(P) * 2 * I), *ye = dev_alloc<float>(size_t(P) * D);
MoeTcWork w;
moe_tc_alloc(w, P, E);
auto time_ms = [&](auto&& fn) {
fn();
cudaDeviceSynchronize();
const auto t0 = std::chrono::steady_clock::now();
const int reps = 5;
for (int i = 0; i < reps; ++i) fn();
cudaDeviceSynchronize();
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count() / reps;
};
const double t_pair = time_ms([&] { moe_gu(dsec, ddesc, 0, didx, N, top_k, E, D, I, dx, false, gu, 0, nullptr); moe_dn(dsec, ddesc, 0, didx, N, top_k, E, D, I, da2, false, ye, 0, nullptr); });
const double t_grp = time_ms([&] { moe_tc_route(w, didx, P, 0); moe_tc_gu(w, dsec, ddesc, 0, nullptr, P, top_k, D, I, dx, gu, 0); moe_tc_dn(w, dsec, ddesc, 0, nullptr, P, top_k, D, I, da2, ye, 0); });
const double wbytes = double(E) * (S.stride > 0 ? double(S.desc[0].body_bytes) : 0.0);
std::printf(" S%d slabs, %3d pairs/expert (P=%d): per-pair kernels %8.2f ms, grouped %8.2f ms = %6.2f TFLOP/s, %6.1f GB/s of weights\n", code, per, P, t_pair, t_grp,
flop_pair * P / (t_grp * 1e9), wbytes / (t_grp * 1e6));
moe_tc_free(w);
for (void* p : std::initializer_list<void*>{didx, dx, da2, gu, ye}) cudaFree(p);
}
cudaFree(dsec); cudaFree(ddesc);
}
}
int main(int argc, char** argv) {
if (!std::getenv("L32MOE_BENCH")) setenv("STRATA_L32_TRUNK_XMX_TILES", "0", 0); // the small trunk shapes of the test must reach the XMX kernel (the default needs 128 tiles)
if (argc < 2) { std::printf("usage: ling32_moe_sy_test DATA_DIR\n"); return 2; }
if (const char* e = std::getenv("L32MOE_FMA")) g_fmask = std::atoi(e);
int ndev = 0;
cudaGetDeviceCount(&ndev);
if (ndev < 1) { std::printf("no device\n"); return 2; }
cudaDeviceProp prop;
cudaGetDeviceProperties(&prop, 0);
std::printf("device 0: %s\n", prop.name);
if (const char* bm = std::getenv("L32MOE_BENCH")) { if (std::strcmp(bm, "decode") == 0) bench_decode(); else if (std::strcmp(bm, "trunk") == 0) bench_trunk(); else bench_batches(); return 0; }
for (int code : {4, 5, 6, 8})
if (!slurp(std::string(argv[1]) + "/pack_s" + std::to_string(code) + ".bin", g_pack[code])) { std::printf("pack_s%d.bin missing\n", code); return 2; }
std::printf("[routed experts: moe_gu / moe_act / moe_dn / moe_tc_*, small shape D=512 I=256, mixed S4/S5/S6/S8 slabs, N = 1..16 pairs]\n");
{
const Slabs S = make_slabs(12, 512, 256, 7, {4, 5, 6, 8});
for (int N = 1; N <= 16; ++N) run_experts(S, N, 1, false, false, "slabs");
for (int N : {1, 2, 5, 16}) run_experts(S, N, 8, false, true, "slabs");
for (int N : {1, 3, 16}) run_experts(S, N, 4, true, true, "slabs");
run_experts(S, 48, 8, false, true, "slabs, 32-pair tiles"); // 32 pairs per expert: the XMX kernel takes 32-pair tiles
run_experts(S, 40, 8, true, true, "slabs, 32-pair tiles");
}
std::printf("[routed experts: the MTP layer's S2_K / S3_K slabs (random superblocks) next to S4 / S8]\n");
{
const Slabs S = make_slabs(8, 512, 256, 3, {2, 3, 4, 8});
for (int N : {1, 4, 9, 16}) run_experts(S, N, 1, false, true, "S2/S3 slabs");
}
std::printf("[routed experts: the Ling-3.2-Air shape D=2560 I=768]\n");
{
const Slabs S = make_slabs(10, 2560, 768, 0, {4, 5, 6, 8});
run_experts(S, 1, 8, false, false, "real shape");
run_experts(S, 2, 8, true, true, "real shape");
}
std::printf("[ALF-LB router: ground-truth sort, ties to the lower id]\n");
for (int N : {1, 4, 16}) {
run_router(512, 8, 4, 8, N, true, false, false);
run_router(512, 8, 4, 8, N, true, false, true);
run_router(512, 8, 3, 8, N, true, true, true);
run_router(512, 8, 4, 40, N, false, true, false); // the lookahead ranking: a longer list, no weights
}
run_router(64, 4, 2, 8, 3, true, false, true); // other shape: reference kernel
run_router(512, 8, 1, 8, 2, true, false, true);
std::printf("[swiglu, shared expert (gemv2_swiglu_s8), combine]\n");
run_swiglu_and_combine();
std::printf("[trunk GEMM: gemm_sk_tc (XMX tiles where the device has them) against the float GEMV, row counts that are no multiple of the 128-row tile, token counts around the tile widths]\n");
for (int code : {8, 5, 4, 6, 2, 3})
for (int N : {1, 31, 33, 40, 100, 129}) run_trunk(code, code == 8 ? 200 : 392, code == 8 ? 768 : 512, N, N % 2 == 0);
std::printf("[route + grouped experts at the real batch sizes: P = 1024 .. 16384 pairs, E = 512 experts, a hot expert with 100+ pairs, unused experts]\n");
{
BigRoute B;
B.S = make_slabs(512, 512, 256, 0, {4, 5, 6, 8});
B.dsec = dev(B.S.buf);
B.ddesc = dev(B.S.desc);
run_big_route(B, 128, 8, 25, "hot 25 percent");
run_big_route(B, 512, 8, 12, "hot 12 percent");
run_big_route(B, 512, 8, 0, "uniform");
run_big_route(B, 64, 8, 60, "hot 60 percent");
run_big_route(B, 2048, 8, 5, "chunk of 2048 tokens");
cudaFree(B.dsec);
cudaFree(B.ddesc);
}
std::printf("%s (%d failed)\n", g_fail ? "FAIL" : "PASS", g_fail);
return g_fail ? 1 : 0;
}
+213
View File
@@ -0,0 +1,213 @@
// tests/ling32/ling32_sy_bench.cpp - decode-step cost model of Ling-3.2-Air on an Intel GPU from the SYCL kernels at the REAL shapes (random weights: timing only).
// Runs every kernel of a decode step (N = 1) in a loop, prints time per call and effective GB/s, then the sum for 35 KDA + 7 MLA layers, 40 MoE layers (top-8 routed + shared) and the lm_head.
// This is the all-resident (Mode A) floor of the kernels, without tier traffic. usage: ling32_sy_bench [ctx=1024] [code of the routed experts = 5]
#include "ling32_kernels.hpp"
#include <algorithm>
#include <chrono>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <random>
#include <vector>
using namespace strata::ling32;
using namespace strata::ling32::gpu;
namespace {
inline size_t sk_superblock_bytes_(int c) { return c == 2 ? 70 : c == 3 ? 102 : c == 4 ? 134 : c == 5 ? 166 : c == 6 ? 198 : 262; }
template <class T> T* dalloc(size_t n) { void* p = nullptr; if (cudaMalloc(&p, n * sizeof(T)) != cudaSuccess) { std::fprintf(stderr, "alloc of %zu bytes failed\n", n * sizeof(T)); std::exit(1); } return static_cast<T*>(p); }
std::mt19937 g_rng(7);
template <class T> T* drand(size_t n, float lo, float hi) {
std::vector<T> h(n);
std::uniform_real_distribution<float> d(lo, hi);
for (auto& v : h) v = static_cast<T>(d(g_rng));
T* p = dalloc<T>(n);
cudaMemcpy(p, h.data(), n * sizeof(T), cudaMemcpyHostToDevice);
return p;
}
// valid-ish S_K rows: random bytes, but the fp16 scale of every superblock is a small normal number
uint8_t* dsk(int rows, int K, int code) {
const size_t sb = sk_superblock_bytes_(code), n = static_cast<size_t>(rows) * (K / 256) * sb;
std::vector<uint8_t> h(n);
for (auto& b : h) b = static_cast<uint8_t>(g_rng());
for (size_t o = 0; o < n; o += sb) { h[o] = 0x00; h[o + 1] = 0x2c; } // fp16 0x2c00 = 0.0625
uint8_t* p = dalloc<uint8_t>(n);
cudaMemcpy(p, h.data(), n, cudaMemcpyHostToDevice);
return p;
}
double time_ms(int reps, const std::function<void()>& fn) {
fn();
cudaDeviceSynchronize();
const auto t0 = std::chrono::steady_clock::now();
for (int i = 0; i < reps; ++i) fn();
cudaDeviceSynchronize();
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count() / reps;
}
double g_total_ms = 0;
void row(const char* what, double ms, double bytes, double mult) {
std::printf(" %-52s %8.3f ms %6.1f GB/s x%-3.0f = %7.2f ms\n", what, ms, bytes > 0 ? bytes / (ms * 1e6) : 0.0, mult, ms * mult);
g_total_ms += ms * mult;
}
// trunk GEMV as the engine runs it by default (float activations, N = 1): the superblock kernel and the packed copy (repack at load, aligned 8-byte loads); the total counts the packed one
double gemv_rows(const char* name, uint8_t* W, int rows, int K, const float* xin, float* yout, bool acc) {
char buf[96];
const double bytes = static_cast<double>(rows) * (K / 256) * 262;
std::snprintf(buf, sizeof buf, "gemv_sk S8 %s float act", name);
const double a = time_ms(50, [&] { strata::ling32::gpu::gemv_sk(W, 8, rows, K, xin, false, 1, yout, rows, acc, 0); });
std::printf(" %-52s %8.3f ms %6.1f GB/s\n", buf, a, bytes / (a * 1e6));
int8_t* q = dalloc<int8_t>(static_cast<size_t>(rows) * K);
float* ep = dalloc<float>(static_cast<size_t>(rows) * (K / 64));
strata::ling32::gpu::repack_s8(W, rows, K, q, ep, 0);
cudaDeviceSynchronize();
std::snprintf(buf, sizeof buf, "gemv_s8p1 packed %s", name);
const double t = time_ms(50, [&] { strata::ling32::gpu::gemv_s8p1(q, ep, rows, K, xin, yout, acc, 0); });
row(buf, t, static_cast<double>(rows) * K + static_cast<double>(rows) * (K / 64) * 4, 1);
cudaFree(q);
cudaFree(ep);
return t;
}
} // namespace
int main(int argc, char** argv) {
const int ctx = argc > 1 ? std::atoi(argv[1]) : 1024;
const int ecode = argc > 2 ? std::atoi(argv[2]) : 5;
const int D = 2560, H = 32, hd = 128, C = H * hd, I = 768, E = 512, V = 157184, nope = 128, rope = 64, kvl = 512;
cudaDeviceProp prop;
cudaGetDeviceProperties(&prop, 0);
std::printf("device: %s, ctx %d, routed expert code S%d\n", prop.name, ctx, ecode);
const int TC = 8; // trunk code of the S8 trunk
auto sb = [](int c) { return static_cast<double>(sk_superblock_bytes_(c)); };
float* x = drand<float>(D, -1.f, 1.f);
float* x2 = drand<float>(D, -1.f, 1.f);
Q8Blk* xq = dalloc<Q8Blk>(D / 64);
float* y = dalloc<float>(static_cast<size_t>(std::max(V, 8 * C)));
float* gamma = drand<float>(D, 0.5f, 1.5f);
// ------------------------------------------------------------------ KDA layer
std::printf("[KDA layer, decode N = 1]\n");
g_total_ms = 0;
{
uint8_t* Wqkvfg = dsk(5 * C, D, TC);
uint8_t* Wo = dsk(D, C, TC);
float* proj = drand<float>(5 * C, -1.f, 1.f);
float* S = drand<float>(static_cast<size_t>(H) * hd * hd, -0.1f, 0.1f);
float* hist = drand<float>(3 * C * 3, -1.f, 1.f);
float *qw = drand<float>(C * 4, -0.5f, 0.5f), *kw = drand<float>(C * 4, -0.5f, 0.5f), *vw = drand<float>(C * 4, -0.5f, 0.5f);
float *beta = drand<float>(H, -1.f, 1.f), *alog = drand<float>(H, -1.f, 0.f), *dtb = drand<float>(C, -1.f, 1.f), *onorm = drand<float>(hd, 0.5f, 1.5f);
float* bproj = drand<float>(static_cast<size_t>(H) * D, -0.1f, 0.1f);
float* kout = dalloc<float>(C);
row("rmsnorm [2560]", time_ms(200, [&] { rmsnorm(x, gamma, 1e-6f, x2, 1, D, 0); }), 0, 2);
row("quant_q8 (FWHT off) [2560]", time_ms(200, [&] { quant_q8(x, xq, 1, D, false, 0); }), 0, 2);
gemv_rows("qkvfg [20480 x 2560]", Wqkvfg, 5 * C, D, x, y, false);
row("kda_step_fused (32 heads, hd 128)", time_ms(50, [&] { kda_step_fused(S, proj, 5 * C, qw, kw, vw, hist, beta, alog, dtb, onorm, -5.0f, 1e-6f, kout, 1, H, hd, 0, nullptr, nullptr, 0, bproj, x, D); }),
static_cast<double>(H) * hd * hd * 8, 1);
gemv_rows("o [2560 x 4096]", Wo, D, C, kout, y, true);
std::printf(" KDA layer total %.2f ms\n", g_total_ms);
}
const double kda_ms = g_total_ms;
// ------------------------------------------------------------------ MLA layer
std::printf("[MLA layer, decode N = 1, context %d]\n", ctx);
g_total_ms = 0;
{
uint8_t *Wq = dsk(H * (nope + rope), D, TC), *Wkva = dsk(kvl + rope, D, TC), *Wd = dsk(D, H * 128, TC);
float* q = drand<float>(static_cast<size_t>(H) * (nope + rope), -1.f, 1.f);
float* ckv = drand<float>(kvl + rope, -1.f, 1.f);
float* ln = drand<float>(kvl, 0.5f, 1.5f);
float* cache = drand<float>(static_cast<size_t>(ctx + 8) * (kvl + rope), -1.f, 1.f);
int* d_pos = dalloc<int>(1);
const int p0 = ctx - 1;
cudaMemcpy(d_pos, &p0, 4, cudaMemcpyHostToDevice);
uint16_t *wk = drand<uint16_t>(static_cast<size_t>(H) * nope * kvl, 0, 0), *wv = drand<uint16_t>(static_cast<size_t>(H) * 128 * kvl, 0, 0);
{ // bf16 values around +-0.05
std::vector<uint16_t> h(static_cast<size_t>(H) * nope * kvl, 0x3d4c);
cudaMemcpy(wk, h.data(), h.size() * 2, cudaMemcpyHostToDevice);
cudaMemcpy(wv, h.data(), h.size() * 2, cudaMemcpyHostToDevice);
}
float *qabs = dalloc<float>(static_cast<size_t>(H) * kvl), *cx = dalloc<float>(static_cast<size_t>(H) * kvl), *gate = drand<float>(H, -1.f, 1.f), *av = dalloc<float>(H * 128);
float* gp = drand<float>(static_cast<size_t>(H) * D, -0.1f, 0.1f);
float* av_big = drand<float>(H * 128, -1.f, 1.f);
gemv_rows("q [6144 x 2560]", Wq, H * (nope + rope), D, x, y, false);
gemv_rows("kv_a [576 x 2560]", Wkva, kvl + rope, D, x, y, false);
row("gemv_f32 g_proj [32 x 2560]", time_ms(100, [&] { gemv_f32(gp, H, D, x, 1, y, 0); }), 0, 1);
row("mla_prep", time_ms(100, [&] { mla_prep(q, ckv, kvl + rope, ln, cache, d_pos, 1, H, nope, rope, kvl, 6.0e6, 1e-6f, LatentFmt::F32, ctx + 8, 0, 0, false, 0); }), 0, 1);
row("mla_qabs", time_ms(50, [&] { mla_qabs(q, wk, qabs, 1, H, nope, rope, kvl, 0); }), static_cast<double>(H) * nope * kvl * 2, 1);
row("mla_attn (original kernel)", time_ms(20, [&] { mla_attn(qabs, q, cache, d_pos, cx, 1, H, nope, rope, kvl, 0.07f, true, 0); }), static_cast<double>(ctx) * (kvl + rope) * 4, 1);
row("mla_out", time_ms(50, [&] { mla_out(cx, wv, gate, av, 1, H, 128, kvl, 0); }), static_cast<double>(H) * 128 * kvl * 2, 1);
gemv_rows("dense [2560 x 4096]", Wd, D, H * 128, av_big, y, true);
std::printf(" MLA layer total %.2f ms\n", g_total_ms);
}
const double mla_ms = g_total_ms;
// ------------------------------------------------------------------ MoE layer
std::printf("[MoE layer, decode N = 1: router + top-8 routed experts S%d + shared expert]\n", ecode);
g_total_ms = 0;
{
const int nsb_gu = D / 256, nsb_dn = I / 256;
const size_t gu_bytes = static_cast<size_t>(2 * I) * nsb_gu * sk_superblock_bytes_(ecode), dn_bytes = static_cast<size_t>(D) * nsb_dn * sk_superblock_bytes_(ecode);
const int Ep = 64; // 64 distinct slabs are enough to defeat the cache
const size_t stride = ((2 * I * 2 + gu_bytes + dn_bytes) + 16383) / 16384 * 16384;
std::vector<uint8_t> hs(static_cast<size_t>(Ep) * stride);
for (auto& b : hs) b = static_cast<uint8_t>(g_rng());
std::vector<ExpertDesc> desc(Ep);
for (int e = 0; e < Ep; ++e) {
const size_t off = static_cast<size_t>(e) * stride;
desc[e] = ExpertDesc{off, ecode, ecode, static_cast<int>(2 * I * 2 + gu_bytes), static_cast<int>(2 * I * 2 + gu_bytes + dn_bytes)};
for (int i = 0; i < I; ++i) { hs[off + 2 * i] = 0x00; hs[off + 2 * i + 1] = 0x3c; } // S_xd = 1.0
for (size_t o = 0; o < gu_bytes; o += sk_superblock_bytes_(ecode)) { hs[off + 2 * I * 2 + o] = 0x00; hs[off + 2 * I * 2 + o + 1] = 0x2c; }
for (size_t o = 0; o < dn_bytes; o += sk_superblock_bytes_(ecode)) { hs[off + 2 * I * 2 + gu_bytes + o] = 0x00; hs[off + 2 * I * 2 + gu_bytes + o + 1] = 0x2c; }
}
uint8_t* sec4 = dalloc<uint8_t>(hs.size());
cudaMemcpy(sec4, hs.data(), hs.size(), cudaMemcpyHostToDevice);
ExpertDesc* ddesc = dalloc<ExpertDesc>(Ep);
cudaMemcpy(ddesc, desc.data(), Ep * sizeof(ExpertDesc), cudaMemcpyHostToDevice);
std::vector<int> hidx(8);
int* didx = dalloc<int>(8);
float *gu = dalloc<float>(8 * 2 * I), *act = dalloc<float>(8 * I), *ye = dalloc<float>(8 * D), *rw = drand<float>(8, 0.1f, 0.5f);
float* gate_w = drand<float>(static_cast<size_t>(E) * D, -0.1f, 0.1f);
float *lg = dalloc<float>(E), *sel = drand<float>(E, -0.1f, 0.1f), *ow = dalloc<float>(8);
int* oidx = dalloc<int>(8);
uint8_t *Wg = dsk(I, D, TC), *Wu = dsk(I, D, TC), *Wd = dsk(D, I, TC);
float* sh = dalloc<float>(I);
int rot = 0;
auto pick = [&] { // 8 different slabs each call (a rotating window) so that every call reads cold-ish weights
for (int k = 0; k < 8; ++k) hidx[k] = (rot + 8 * k) % Ep;
rot = (rot + 1) % 8;
cudaMemcpy(didx, hidx.data(), 32, cudaMemcpyHostToDevice);
};
pick();
row("rmsnorm [2560]", time_ms(200, [&] { rmsnorm(x, gamma, 1e-6f, x2, 1, D, 0); }), 0, 1);
row("gemv_f32 router [512 x 2560]", time_ms(100, [&] { gemv_f32(gate_w, E, D, x, 1, lg, 0); }), static_cast<double>(E) * D * 4, 1);
row("alflb_route (top-8 of 512)", time_ms(100, [&] { alflb_route(lg, nullptr, sel, E, 8, 4, 8, 2.5f, true, oidx, ow, 1, 0); }), 0, 1);
row("fwht128 [2560] (expert input)", time_ms(200, [&] { fwht128(x, x2, 1, D, 0); }), 0, 1);
row("moe_gu 8 experts (float act)", time_ms(50, [&] { moe_gu(sec4, ddesc, 0, didx, 1, 8, Ep, D, I, x2, false, gu, 0, nullptr); }), 8.0 * gu_bytes, 1);
row("moe_act 8 pairs (swiglu + FWHT)", time_ms(100, [&] { moe_act(sec4, ddesc, 0, didx, gu, 1, 8, I, 7.0f, true, act, false, 0, nullptr); }), 0, 1);
row("moe_dn 8 experts (float act)", time_ms(50, [&] { moe_dn(sec4, ddesc, 0, didx, 1, 8, Ep, D, I, act, false, ye, 0, nullptr); }), 8.0 * dn_bytes, 1);
row("moe_combine (+ shared)", time_ms(100, [&] { moe_combine(x, ye, rw, 1, 8, D, 0, nullptr); }), 0, 1);
row("gemv2_swiglu_s8 shared gate+up [768 x 2560]", time_ms(100, [&] { gemv2_swiglu_s8(Wg, Wu, I, D, x2, 1, 7.0f, true, sh, I, 0); }), 2.0 * I * nsb_gu * sb(TC), 1);
row("gemv_sk S8 shared down [2560 x 768]", time_ms(100, [&] { gemv_sk(Wd, TC, D, I, sh, false, 1, y, D, false, 0); }), static_cast<double>(D) * nsb_dn * sb(TC), 1);
std::printf(" MoE layer total %.2f ms (experts read %.1f MB)\n", g_total_ms, 8.0 * (gu_bytes + dn_bytes) / 1e6);
}
const double moe_ms = g_total_ms;
// ------------------------------------------------------------------ head
g_total_ms = 0;
std::printf("[lm_head]\n");
{
uint8_t* Wh = dsk(V, D, TC);
Q8Blk* hq = dalloc<Q8Blk>(D / 64);
float* logits = dalloc<float>(V);
gemv_rows("lm_head [157184 x 2560]", Wh, V, D, x, logits, false);
(void)hq;
}
const double head_ms = g_total_ms;
// layer composition: 42 layers = 35 KDA + 7 MLA; 2 dense + 40 MoE (dense MLP not measured: counted like the shared expert x4)
const double step = 35 * kda_ms + 7 * mla_ms + 40 * moe_ms + head_ms;
std::printf("[decode step estimate, everything resident, kernels only]\n 35 x KDA %.2f + 7 x MLA %.2f + 40 x MoE %.2f + head %.2f = %.1f ms per token = %.1f tok/s\n", kda_ms, mla_ms, moe_ms, head_ms, step, 1000.0 / step);
return 0;
}
@@ -0,0 +1,93 @@
// tests/ling32/ling32_sy_mla_fd_test.cpp - the flash-decoding MLA attention (sycl/ling32_sy_k_mla_fd.cpp) against the original per-head kernel (mla_attn_orig, ling32_sy_k_mla.cpp).
// Real geometry (32 heads, nope 128, rope 64, kv_lora 512), fp32 latent cache. Contexts 1, 2, 31, 32, 33, 64, 257, 1024, 8192, 32768, 131072 with N = 1, and spans of N = 3 and 16 tokens (each token sees its own prefix);
// three score regimes (flat, normal, peaked) so that the softmax merge across slices is exercised with very different maxima.
// The summation order changes, so the result is not bit-exact: it must stay within 1e-5 absolute and relative (relative against max(|ref|, 0.1)). Prints the timing of both kernels as well.
// usage: ling32_sy_mla_fd_test exit 0 = pass
#include "ling32_kernels.hpp"
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <random>
#include <vector>
using namespace strata::ling32;
using namespace strata::ling32::gpu;
namespace strata::ling32::gpu {
void mla_attn_orig(const float* qabs, const float* q, const void* cache, const int* d_pos0, float* ctx, int N, int H, int nope, int rope, int kv_lora, float scale, bool cache_f32_b, cudaStream_t s);
bool mla_attn_fd_supported(int N, int H, int rope, int kv_lora, bool cache_f32);
void mla_attn_fd(const float* qabs, const float* q, const void* cache, const int* d_pos0, float* ctx, int N, int H, int nope, int rope, int kv_lora, float scale, cudaStream_t s, int stages);
} // namespace strata::ling32::gpu
namespace {
template <class T> T* up(const std::vector<T>& h) {
void* p = nullptr;
if (cudaMalloc(&p, h.size() * sizeof(T)) != cudaSuccess) { std::fprintf(stderr, "alloc failed\n"); std::exit(1); }
cudaMemcpy(p, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice);
return static_cast<T*>(p);
}
double now_ms() { return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count(); }
} // namespace
int main() {
const int H = 32, nope = 128, rope = 64, kvl = 512, W = kvl + rope;
const float scale = 1.0f / std::sqrt(static_cast<float>(nope + rope));
std::mt19937 rng(11);
int fails = 0;
struct Case { int ctx, N; float qs; const char* what; };
const Case cases[] = {{1, 1, 0.1f, "flat"}, {2, 1, 0.1f, "flat"}, {31, 1, 0.3f, "normal"}, {32, 1, 0.3f, "normal"}, {33, 1, 0.3f, "normal"}, {64, 1, 0.3f, "normal"},
{257, 1, 0.1f, "flat"}, {1024, 1, 0.3f, "normal"}, {1024, 1, 1.5f, "peaked"}, {8192, 1, 0.1f, "flat"}, {8192, 1, 0.3f, "normal"}, {8192, 1, 1.5f, "peaked"},
{32768, 1, 0.3f, "normal"}, {131072, 1, 0.3f, "normal"}, {3000, 3, 0.3f, "normal"}, {1000, 16, 0.3f, "normal"}, {97, 16, 1.5f, "peaked"}};
for (const Case& c : cases) {
const int ctx = c.ctx, N = c.N, rows = ctx + 8;
std::vector<float> cache(static_cast<size_t>(rows) * W), qabs(static_cast<size_t>(N) * H * kvl), q(static_cast<size_t>(N) * H * (nope + rope));
std::uniform_real_distribution<float> du(-1.0f, 1.0f);
for (auto& v : cache) v = du(rng);
for (auto& v : qabs) v = du(rng) * c.qs;
for (auto& v : q) v = du(rng) * c.qs;
const int p0 = ctx - N; // the last token sees ctx rows
float *dc = up(cache), *dqa = up(qabs), *dq = up(q);
int* dp = up(std::vector<int>{p0});
std::vector<float> z(static_cast<size_t>(N) * H * kvl, 0.0f);
float *o_ref = up(z), *o_fd = up(z);
mla_attn_orig(dqa, dq, dc, dp, o_ref, N, H, nope, rope, kvl, scale, true, 0);
mla_attn_fd(dqa, dq, dc, dp, o_fd, N, H, nope, rope, kvl, scale, 0, 3);
cudaDeviceSynchronize();
std::vector<float> a(z.size()), bb(z.size());
cudaMemcpy(a.data(), o_ref, a.size() * 4, cudaMemcpyDeviceToHost);
cudaMemcpy(bb.data(), o_fd, bb.size() * 4, cudaMemcpyDeviceToHost);
double mabs = 0, mrel = 0;
bool bad = false;
for (size_t i = 0; i < a.size(); ++i) {
if (!std::isfinite(bb[i])) bad = true;
const double d = std::fabs(static_cast<double>(a[i]) - bb[i]);
mabs = std::max(mabs, d);
mrel = std::max(mrel, d / std::max(std::fabs(static_cast<double>(a[i])), 0.1));
}
const bool ok = !bad && mabs <= 1e-5 && mrel <= 1e-5; // mrel: relative to max(|ref|, 0.1)
if (!ok) ++fails;
// timing (N = 1 cases only)
double t_ref = 0, t_fd = 0, t_s1 = 0;
if (N == 1) {
const int reps = ctx >= 32768 ? 5 : (ctx >= 1024 ? 20 : 50);
double t0 = now_ms();
for (int i = 0; i < reps; ++i) mla_attn_orig(dqa, dq, dc, dp, o_ref, N, H, nope, rope, kvl, scale, true, 0);
cudaDeviceSynchronize();
t_ref = (now_ms() - t0) / reps;
t0 = now_ms();
for (int i = 0; i < reps; ++i) mla_attn_fd(dqa, dq, dc, dp, o_fd, N, H, nope, rope, kvl, scale, 0, 3);
cudaDeviceSynchronize();
t_fd = (now_ms() - t0) / reps;
t0 = now_ms();
for (int i = 0; i < reps; ++i) mla_attn_fd(dqa, dq, dc, dp, o_fd, N, H, nope, rope, kvl, scale, 0, 1);
cudaDeviceSynchronize();
t_s1 = (now_ms() - t0) / reps;
}
std::printf("ctx %5d N %2d %-6s max abs %.3e max rel %.3e orig %.3f ms fd %.3f ms (stage 1 alone %.3f) %s\n", ctx, N, c.what, mabs, mrel, t_ref, t_fd, t_s1, ok ? "ok" : "FAIL");
cudaFree(dc); cudaFree(dqa); cudaFree(dq); cudaFree(dp); cudaFree(o_ref); cudaFree(o_fd);
}
std::printf(fails ? "ling32_sy_mla_fd_test: %d FAILED\n" : "ling32_sy_mla_fd_test: all ok (%d)\n", fails);
return fails ? 1 : 0;
}
@@ -0,0 +1,240 @@
// tests/ling32/ling32_sy_tier_check.cpp - the Ling tier store (Mode B / C) driven without the engine's kernels, for the SYCL (Intel) build.
//
// ling32_sy_tier_check FILE.strata [--vr N] [--rr N] [--dyn N] [--ring N] [--fwds N] [--zc 0|1] [--pf 0|1] [--seed S] [--tokens a,b,c] [--noisy 0|1]
//
// What it does: plans a split by hand (ranks on the card / in pinned RAM, dynamic slots, SSD ring: the same forced-split rules as `strata-ling32 --force-*`), creates the ExpertStore (the start-up fill, the
// verification reads, pinned allocations, DirectFile reads), and then plays routing like the engine does: per forward and MoE layer prepare() / next_pass() with random top-8 sets, lookahead predictions
// (perfect or noisy) for the layers ahead. Two checks run on every table the store hands out:
// host side STRATA_L32_TIER_CHECK=1 (set by this program): the store compares every slab of the pass with the file bytes after its copies (`tier store: ... compared N slab reads, M wrong`)
// device side a SYCL kernel dereferences the table entries on the compute stream exactly as the MoE kernels do (in-place reads of pinned RAM and ring memory included) and compares the slab
// bytes with a device copy of Section 4
// Exit code 0 = both checks found no wrong slab. The fixture's Section 4 is small; the real file is too big for the mirror (the host check is off above 256 MiB).
#include "ling32_model.hpp"
#include "ling32_tier_store.hpp"
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <string>
#include <vector>
using namespace strata::ling32;
namespace {
double now_s() { return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count(); }
struct Verifier {
uint8_t* d_mirror = nullptr;
uint64_t* d_off = nullptr;
uint32_t* d_bytes = nullptr;
unsigned long long* d_cnt = nullptr; // [0] slabs checked, [1] wrong bytes, [2] slabs with a wrong byte
int E = 0, first_k = 0;
bool init(const Ling32File& f, const GpuModel& M, std::string& err) {
const uint64_t n = f.section_bytes(4);
if (n > (1ull << 30)) { err = "Section 4 is too big for the device-side mirror"; return false; }
std::vector<uint8_t> mir(n);
if (!f.reader().read_at(f.section_offset(4), mir.data(), n, err)) return false;
std::vector<uint64_t> off(M.experts.size());
std::vector<uint32_t> by(M.experts.size());
for (size_t i = 0; i < M.experts.size(); ++i) { off[i] = M.experts[i].off; by[i] = static_cast<uint32_t>(M.experts[i].body_bytes); }
E = f.cfg().n_exp;
first_k = f.cfg().first_k_dense;
if (cudaMalloc(&d_mirror, n) || cudaMalloc(&d_off, off.size() * 8) || cudaMalloc(&d_bytes, by.size() * 4) || cudaMalloc(&d_cnt, 3 * 8)) { err = "cudaMalloc (verifier)"; return false; }
cudaMemcpy(d_mirror, mir.data(), n, cudaMemcpyHostToDevice);
cudaMemcpy(d_off, off.data(), off.size() * 8, cudaMemcpyHostToDevice);
cudaMemcpy(d_bytes, by.data(), by.size() * 4, cudaMemcpyHostToDevice);
cudaMemset(d_cnt, 0, 3 * 8);
return true;
}
// compare every slab the table (window of layer il) points to, on the compute stream
void run(const uint8_t* const* tab, int il, cudaStream_t st) {
sycl::queue& q = strata::sy::queue_of(st);
const uint8_t* const* t = tab + static_cast<size_t>(il - first_k) * E;
const int gbase = (il - first_k) * E;
uint8_t* mir = d_mirror;
uint64_t* off = d_off;
uint32_t* by = d_bytes;
unsigned long long* cnt = d_cnt;
constexpr int WG = 128;
q.parallel_for(sycl::nd_range<1>(static_cast<size_t>(E) * WG, WG), [=](sycl::nd_item<1> it) {
const int e = static_cast<int>(it.get_group(0));
const uint8_t* p = t[e];
if (!p) return;
const int gi = gbase + e;
const uint32_t n = by[gi];
const uint8_t* ref = mir + off[gi];
unsigned bad = 0;
for (uint32_t i = static_cast<uint32_t>(it.get_local_id(0)); i < n; i += WG) bad += p[i] != ref[i];
const unsigned tot = sycl::reduce_over_group(it.get_group(), bad, sycl::plus<unsigned>());
if (it.get_local_id(0) == 0) {
sycl::atomic_ref<unsigned long long, sycl::memory_order::relaxed, sycl::memory_scope::device> a0(cnt[0]), a1(cnt[1]), a2(cnt[2]);
a0.fetch_add(1);
if (tot) { a1.fetch_add(tot); a2.fetch_add(1); }
}
});
}
};
} // namespace
int main(int argc, char** argv) {
if (argc < 2) { std::printf("usage: ling32_sy_tier_check FILE.strata [--vr N] [--rr N] [--dyn N] [--ring N] [--fwds N] [--zc 0|1] [--pf 0|1] [--seed S] [--tokens a,b,c] [--noisy 0|1]\n"); return 2; }
const std::string path = argv[1];
int vr = 0, rr = 0, dyn = 24, ring = 0, fwds = 12, zc = 0, pf = 1, noisy = 1;
unsigned seed = 7;
std::vector<int> tokens = {1, 1, 1, 2, 5, 32, 130, 256};
for (int i = 2; i + 1 < argc; i += 2) {
const std::string a = argv[i];
const std::string v = argv[i + 1];
if (a == "--vr") vr = std::atoi(v.c_str());
else if (a == "--rr") rr = std::atoi(v.c_str());
else if (a == "--dyn") dyn = std::atoi(v.c_str());
else if (a == "--ring") ring = std::atoi(v.c_str());
else if (a == "--fwds") fwds = std::atoi(v.c_str());
else if (a == "--zc") zc = std::atoi(v.c_str());
else if (a == "--pf") pf = std::atoi(v.c_str());
else if (a == "--noisy") noisy = std::atoi(v.c_str());
else if (a == "--seed") seed = static_cast<unsigned>(std::atoi(v.c_str()));
else if (a == "--tokens") {
tokens.clear();
size_t p = 0;
while (p < v.size()) { tokens.push_back(std::atoi(v.c_str() + p)); const size_t c = v.find(',', p); if (c == std::string::npos) break; p = c + 1; }
} else { std::printf("unknown option %s\n", a.c_str()); return 2; }
}
#ifdef _WIN32
_putenv_s("STRATA_L32_TIER_CHECK", "1");
#else
setenv("STRATA_L32_TIER_CHECK", "1", 1);
#endif
std::string err;
Ling32File f;
if (!f.open(path, err)) { std::printf("open: %s\n", err.c_str()); return 2; }
const Cfg& c = f.cfg();
const int E = c.n_exp, top_k = c.top_k, first_k = c.first_k_dense, n_moe = c.n_moe();
const auto& dir = f.reader().expert_directory();
RankTable rt;
if (!build_rank_table(dir.data(), dir.size(), E, rt, err)) { std::printf("rank table: %s\n", err.c_str()); return 2; }
// the split, by the rules of ling32_main.cpp make_plan (forced part)
TierPlan plan;
plan.ok = true;
vr = std::min(vr, rt.n_exp);
rr = std::min(rr, rt.n_exp - vr);
plan.vram_ranks = vr;
plan.ram_ranks = rr;
plan.vram_prefix_bytes = rt.bytes_of_ranks(vr);
plan.ram_prefix_bytes = rt.bytes_of_ranks(vr + rr) - plan.vram_prefix_bytes;
plan.ssd_bytes = rt.total - plan.vram_prefix_bytes - plan.ram_prefix_bytes;
plan.mode = vr >= rt.n_exp ? TierMode::A : plan.ssd_bytes == 0 ? TierMode::B : TierMode::C;
if (plan.mode == TierMode::A) { std::printf("this split is Mode A: nothing for the store to do\n"); return 2; }
plan.lookahead_k = 4;
plan.prefetch = pf != 0;
plan.prefetch_width = 4;
plan.io_qd = 16;
plan.dyn_slots = dyn;
plan.dyn_big = 0;
plan.slot_small = 0;
plan.slot_bytes = rt.max_slab;
plan.dyn_bytes = static_cast<uint64_t>(dyn) * rt.max_slab;
plan.ring_slots = plan.mode == TierMode::C ? std::max(ring, 4) : 0;
plan.ring_bytes = static_cast<uint64_t>(plan.ring_slots) * rt.max_slab;
std::printf("plan: %s, vram ranks %d (%.3f MiB), ram ranks %d (%.3f MiB), ssd %.3f MiB, dyn slots %d, ring slots %d, slab %llu B max; zero copy %d, prefetch %d\n", tier_name(plan.mode), vr, plan.vram_prefix_bytes / 1048576.0, rr,
plan.ram_prefix_bytes / 1048576.0, plan.ssd_bytes / 1048576.0, dyn, plan.ring_slots, static_cast<unsigned long long>(rt.max_slab), zc, pf);
GpuModel M;
LoadOptions lo;
lo.load_experts = false;
lo.load_lookahead = plan.prefetch;
lo.lookahead_ks = 2;
lo.verify_upload = false;
if (!M.load(f, lo, err)) { std::printf("GpuModel::load: %s\n", err.c_str()); return 1; }
StoreOptions so;
so.max_tokens = 256;
so.zero_copy = zc != 0;
auto store = ExpertStore::create(f, M, plan, rt, so, err);
if (!store) { std::printf("ExpertStore::create: %s\n", err.c_str()); return 1; }
std::printf("store ready: %.3f MiB on the card, %.3f MiB pinned\n", store->gpu_bytes() / 1048576.0, store->pinned_bytes() / 1048576.0);
Verifier V;
if (!V.init(f, M, err)) { std::printf("verifier: %s\n", err.c_str()); return 1; }
cudaStream_t st = nullptr;
cudaStreamCreate(&st);
int* d_ridx = nullptr;
cudaMalloc(&d_ridx, static_cast<size_t>(so.max_tokens) * top_k * sizeof(int));
// experts of the better ranks (card / RAM tier) so that the routing mixes hits and misses
std::vector<int> rank_of(static_cast<size_t>(E), 0), by_rank(static_cast<size_t>(E), 0);
for (int e = 0; e < E; ++e) rank_of[static_cast<size_t>(e)] = static_cast<int>(dir[static_cast<size_t>(e)].aux_offsets[0]);
for (int e = 0; e < E; ++e) by_rank[static_cast<size_t>(rank_of[static_cast<size_t>(e)])] = e;
std::mt19937 rng(seed);
auto pick_set = [&](std::vector<int>& out) {
out.clear();
while (static_cast<int>(out.size()) < top_k) {
int e;
const unsigned r = rng() % 100;
if (r < 45) e = by_rank[rng() % static_cast<unsigned>(std::max(1, std::min(E, vr + rr)))]; // a card / RAM tier expert
else if (r < 70) e = by_rank[static_cast<size_t>(E - 1 - static_cast<int>(rng() % static_cast<unsigned>(std::max(1, E - vr - rr))))]; // the coldest (SSD) ones
else e = static_cast<int>(rng() % static_cast<unsigned>(E));
if (std::find(out.begin(), out.end(), e) == out.end()) out.push_back(e);
}
};
const double t0 = now_s();
uint64_t layers = 0, passes_total = 0;
for (int fw = 0; fw < fwds; ++fw) {
const int n = std::min(tokens[static_cast<size_t>(fw) % tokens.size()], so.max_tokens);
std::vector<std::vector<int>> route(static_cast<size_t>(n_moe));
std::vector<int> one;
for (int L = 0; L < n_moe; ++L) {
auto& r = route[static_cast<size_t>(L)];
r.reserve(static_cast<size_t>(n) * top_k);
for (int t = 0; t < n; ++t) {
if (n > 8 && t > 0 && (rng() % 3)) { // a batch: neighbouring tokens share experts, as prompts do
pick_set(one);
const auto prev = std::vector<int>(r.end() - top_k, r.end());
for (int k = 0; k < top_k / 2; ++k) one[static_cast<size_t>(k)] = prev[static_cast<size_t>(k)];
std::sort(one.begin(), one.end());
one.erase(std::unique(one.begin(), one.end()), one.end());
while (static_cast<int>(one.size()) < top_k) { const int e = static_cast<int>(rng() % static_cast<unsigned>(E)); if (std::find(one.begin(), one.end(), e) == one.end()) one.push_back(e); }
} else {
pick_set(one);
}
r.insert(r.end(), one.begin(), one.end());
}
}
store->begin_forward(n);
for (int L = 0; L < n_moe; ++L) {
const int il = first_k + L;
cudaMemcpy(d_ridx, route[static_cast<size_t>(L)].data(), static_cast<size_t>(n) * top_k * sizeof(int), cudaMemcpyHostToDevice);
const uint8_t* const* tab = store->prepare(il, n, d_ridx, top_k, st);
if (!tab) { std::printf("prepare returned no table (forward %d layer %d)\n", fw, il); return 1; }
V.run(tab, il, st);
const int np = store->passes();
for (int j = 1; j < np; ++j) {
tab = store->next_pass(j, st);
if (!tab) { std::printf("next_pass %d returned no table\n", j); return 1; }
V.run(tab, il, st);
}
++layers;
passes_total += static_cast<uint64_t>(np);
// lookahead predictions for the layer plan.lookahead_k ahead (the ranked lists the engine's predictor would send): the true routing, or with some wrong experts
const int tl = L + plan.lookahead_k;
if (plan.prefetch && tl < n_moe && store->wants_prediction(n)) {
std::vector<int> pr = route[static_cast<size_t>(tl)];
if (noisy) for (auto& e : pr) if (rng() % 4 == 0) e = static_cast<int>(rng() % static_cast<unsigned>(E));
store->on_prediction(first_k + tl, plan.lookahead_k, pr.data(), n, top_k);
}
cudaStreamSynchronize(st); // the layer's compute (none here) ends
}
store->end_forward();
}
cudaDeviceSynchronize();
unsigned long long cnt[3] = {};
cudaMemcpy(cnt, V.d_cnt, sizeof cnt, cudaMemcpyDeviceToHost);
std::printf("%d forwards, %llu layers, %llu passes in %.2f s\n%s\n", fwds, static_cast<unsigned long long>(layers), static_cast<unsigned long long>(passes_total), now_s() - t0, store->report().c_str());
std::printf("device-side check: %llu slabs read through the table by a kernel, %llu wrong (%llu wrong bytes)\n", cnt[0], cnt[2], cnt[1]);
store.reset(); // prints the host-side check line
std::printf("%s\n", cnt[2] == 0 && cnt[0] > 0 ? "RESULT PASS device-side" : "RESULT FAIL device-side");
return cnt[2] == 0 && cnt[0] > 0 ? 0 : 1;
}
@@ -0,0 +1,61 @@
// tests/ling32/ling32_sy_topk_test.cpp - gpu::topk_rows (radix select, ties by lower index) against a host sort, for several vocab sizes, K and tie patterns.
#include "ling32_spec.hpp"
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <numeric>
#include <random>
#include <vector>
using namespace strata::ling32;
int main() {
int fail = 0, ncase = 0;
std::mt19937 g(11);
for (int V : {12, 100, 512, 1000, 5000, 157184}) {
for (int K : {1, 2, 5, 8, 16, 64}) {
if (K > V) continue;
for (int mode = 0; mode < 3; ++mode) { // 0: random normal, 1: many exact ties, 2: negative values with ties
const int rows = 3;
std::vector<float> x(static_cast<size_t>(rows) * V);
std::normal_distribution<float> nd(0.f, 3.f);
for (auto& v : x) {
v = nd(g);
if (mode >= 1) v = std::round(v * 2.0f) * 0.5f;
if (mode == 2) v = -std::fabs(v);
v += 0.0f; // -0 becomes +0 (the kernel orders -0 below +0 by their keys, the host sort calls them equal)
}
float* dx = nullptr; float* dv = nullptr; int* di = nullptr;
cudaMalloc(&dx, x.size() * 4);
cudaMalloc(&dv, static_cast<size_t>(rows) * K * 4);
cudaMalloc(&di, static_cast<size_t>(rows) * K * 4);
cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice);
gpu::topk_rows(dx, rows, V, V, K, dv, di, 0);
cudaDeviceSynchronize();
std::vector<float> ov(static_cast<size_t>(rows) * K);
std::vector<int> oi(static_cast<size_t>(rows) * K);
cudaMemcpy(ov.data(), dv, ov.size() * 4, cudaMemcpyDeviceToHost);
cudaMemcpy(oi.data(), di, oi.size() * 4, cudaMemcpyDeviceToHost);
bool ok = true;
for (int r = 0; r < rows && ok; ++r) {
std::vector<int> idx(V);
std::iota(idx.begin(), idx.end(), 0);
const float* row = x.data() + static_cast<size_t>(r) * V;
std::stable_sort(idx.begin(), idx.end(), [&](int a, int b) { return row[a] > row[b]; }); // value descending, ties lower index first
for (int k = 0; k < K; ++k)
if (oi[static_cast<size_t>(r) * K + k] != idx[k] || ov[static_cast<size_t>(r) * K + k] != row[idx[k]]) {
if (ok) std::printf(" mismatch V=%d K=%d mode=%d row %d rank %d: got id %d val %g, want id %d val %g\n", V, K, mode, r, k, oi[static_cast<size_t>(r) * K + k], ov[static_cast<size_t>(r) * K + k], idx[k], row[idx[k]]);
ok = false;
break;
}
}
++ncase;
if (!ok) ++fail;
cudaFree(dx); cudaFree(dv); cudaFree(di);
}
}
}
std::printf("topk_rows: %d cases, %d failed\n%s\n", ncase, fail, fail ? "FAIL" : "PASS");
return fail ? 1 : 0;
}